From 17a0ed43536ba049cbcd3ca418205f2d6e4b91f2 Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 13:26:46 +0000 Subject: [PATCH 01/33] docs(rules): add the C# code style rulebook source The complete style text is committed before registration so the rule registry can pin every chapter to an immutable source revision. --- .agents/rulebook/csharp-style.md | 3473 ++++++++++++++++++++++++++++++ 1 file changed, 3473 insertions(+) create mode 100644 .agents/rulebook/csharp-style.md diff --git a/.agents/rulebook/csharp-style.md b/.agents/rulebook/csharp-style.md new file mode 100644 index 000000000..e1c6510dc --- /dev/null +++ b/.agents/rulebook/csharp-style.md @@ -0,0 +1,3473 @@ +# InnoEngine C# code style + +This rulebook defines how handwritten C# in InnoEngine is named, laid out and written. It applies to every handwritten `.cs` file in the repository, including tests and tools. Third-party sources under `extern/`, generated files (`**/Generated/*.cs` and files carrying an `` header) and the cases listed in [section 16](#16-exceptions) are out of scope. + +The [coding rules](coding.md) own design, error-handling, resource and change-management requirements. This rulebook is the detailed authority for names and layout. + +- Every rule has an ID such as `B-05`. Cite the ID in reviews and commit messages. +- Each rule states the requirement first, then shows a compliant example. A block introduced by **Avoid** shows what the rule forbids. +- "Must", "always" and "never" are requirements. "Prefer" and "recommended" describe the default; deviate only when the default hurts readability. +- External contracts take precedence over this rulebook: interface implementations, overrides, MSBuild task parameters, serialized names and native interop signatures keep the names their contract requires (see [section 16](#16-exceptions)). +- Formatting changes and renames are separate changes. A formatting-only change must not alter names, logic, execution order or public contracts. Renaming a public member is an API change. +- Automatic formatters must preserve these rules. Do not apply a formatter whose output differs from this rulebook. + +Contents + +1. [Files and physical layout](#1-files-and-physical-layout) +2. [Namespaces and using directives](#2-namespaces-and-using-directives) +3. [Naming](#3-naming) +4. [Type declarations](#4-type-declarations) +5. [Member declarations](#5-member-declarations) +6. [Member order](#6-member-order) +7. [Braces and blocks](#7-braces-and-blocks) +8. [Parameter and argument lists](#8-parameter-and-argument-lists) +9. [Line breaks](#9-line-breaks) +10. [Initializers and collections](#10-initializers-and-collections) +11. [Spacing and blank lines](#11-spacing-and-blank-lines) +12. [Types and expression idioms](#12-types-and-expression-idioms) +13. [Control flow, exceptions and asynchronous code](#13-control-flow-exceptions-and-asynchronous-code) +14. [Comments and XML documentation](#14-comments-and-xml-documentation) +15. [Tests](#15-tests) +16. [Exceptions](#16-exceptions) +17. [Reference example](#17-reference-example) + +## 1. Files and physical layout + +### F-01 Encoding, line endings and indentation + +- UTF-8 without a byte order mark. +- LF line endings. +- Four spaces per indentation level. Never use tab characters. +- No trailing whitespace. +- The file ends with exactly one newline. +- At most one consecutive blank line. + +In the next two blocks `→` is a tab, `·` is a space and `¶` is a newline. + +```text +····private int m_count;¶ +}¶ +``` + +Avoid (tab indentation, trailing whitespace, extra blank line at the end of the file): + +```text +→private int m_count;··¶ +}¶ +¶ +``` + +### F-02 One top-level type per file, named after the type + +- The file name is the PascalCase name of its primary type: `EventDispatcher.cs` contains `EventDispatcher`. +- Generic arity is not part of the file name: `Pool` lives in `Pool.cs`. +- Additional files of a `partial` type are named `Type.Part.cs`. +- A small, tightly coupled contract (an enum, delegate or parameter record used only by the primary type) may share the file. The primary type comes first. + +```text +Inno.Core.Events/ + EventDispatcher.cs class EventDispatcher + EventDispatcher.Observation.cs partial class EventDispatcher + IEventSink.cs interface IEventSink +``` + +### F-03 File structure + +A file contains, in this order: the using directives, one blank line, the file-scoped namespace, one blank line, the types. There is no file header comment, no license banner and no leading blank line. + +```csharp +using System; +using System.Collections.Generic; + +namespace Inno.Core.Events; + +/// +/// Dispatches events to registered sinks. +/// +public sealed class EventDispatcher +{ + private readonly List m_sinks = []; +} +``` + +Avoid (no blank line after the namespace): + +```csharp +namespace Inno.Core.Events; +public sealed class EventDispatcher +{ + private readonly List m_sinks = []; +} +``` + +### F-04 Line width + +- Aim for 120 columns or fewer. 140 columns is the hard limit. +- Only an unsplittable string literal (a path, a URL, one diagnostic sentence) may exceed the hard limit. +- Do not split a name, a modifier list or a short expression body merely to shorten a line. + +```csharp +// 107 columns: stays on one line. +public bool isMissing => m_source is null || !m_source.exists || m_source.generation != m_owner.generation; + +// 145 columns on one line: break it by meaning. +throw new InvalidOperationException( + $"The importer '{importer.name}' produced no result for '{path}' while generation {generation} was active." +); +``` + +Avoid (a short declaration split for no reason): + +```csharp +public bool isMissing + => m_source is null; +``` + +### F-05 Indentation and alignment of continuation lines + +Prefer alignment over a fixed indent. + +- **Operator continuation.** When an expression is broken at an operator (`&&`, `||`, `??`, `+`, `?`, `:`, `or`, `and`, …), each continuation line begins with the operator and aligns with the first operand of that expression. +- **Fallback.** When alignment would push a line past the hard limit, indent the continuation lines four spaces from the start of the statement instead. +- **Delimited lists.** The contents of a broken parameter list, argument list, initializer or collection are indented four spaces from the line that opens them. The closing delimiter, when it is on its own line, aligns with the first token of the opening line. +- **Call chains, wrapped `=>` and clauses.** A wrapped `.Member(...)` link, a wrapped expression-body `=>`, and a wrapped `where` or constructor-initializer clause are indented four spaces from the start of the statement or declaration. + +```csharp +bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format; + +return left.order != right.order + || left.layer != right.layer; + +string name = entry.displayName + ?? entry.path.GetFileName() + ?? string.Empty; + +List names = m_entries + .Where(static entry => !entry.isMissing) + .Select(static entry => entry.displayName) + .ToList(); +``` + +Avoid (operator continuation indented by a fixed amount instead of aligned): + +```csharp +bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format; +``` + +## 2. Namespaces and using directives + +### N-01 File-scoped namespaces + +Use `namespace X;`. A file declares exactly one namespace. + +```csharp +namespace Inno.Core.Events; + +public sealed class EventDispatcher +{ + private int m_generation; +} +``` + +Avoid: + +```csharp +namespace Inno.Core.Events +{ + public sealed class EventDispatcher + { + private int m_generation; + } +} +``` + +### N-02 The namespace is the project name + +The namespace starts with `Inno`, uses PascalCase segments and equals the assembly name of the owning project. Directories inside a project organize files; they do not add namespace segments. + +```csharp +// File: src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs +namespace Inno.Assets.Pipeline; +``` + +Avoid: + +```csharp +// File: src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs +namespace Inno.Assets.Pipeline.Importing; +``` + +The one registered exception is `Inno.Editor.ImGui/Widgets`, which uses `Inno.Editor.ImGui.ImGuiWidget`. + +### N-03 Placement and kinds of using directives + +- All using directives are at the top of the file, outside the namespace. +- `global using`, implicit usings and MSBuild `Using` items are prohibited. Handwritten code never uses `global::`. +- `using static` is reserved for pure function containers such as math helpers. + +```csharp +using System; +using Inno.Core.Events; + +namespace Inno.Rendering; +``` + +Avoid: + +```csharp +global using System; + +namespace Inno.Rendering; + +using Inno.Core.Events; + +public sealed class Renderer +{ + private readonly global::Inno.Core.Events.EventDispatcher m_dispatcher = new(); +} +``` + +### N-04 Order of using directives + +Using directives form up to three groups, in this order, separated by exactly one blank line: + +1. Namespace usings. +2. `using static` directives. +3. Alias usings. + +Inside the namespace group the order is: + +1. `System` and `System.*`. +2. Everything else that is not `Inno` (third-party and framework packages). +3. `Inno` and `Inno.*`. + +Each tier is sorted alphabetically (ordinal). There are no blank lines inside a group. Static usings follow the same three tiers; aliases are sorted by alias name. + +```csharp +using System; +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis; +using Xunit; +using Inno.Core.Events; +using Inno.Core.Identity; + +using static System.MathF; + +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; +using NativeWindow = Inno.Adapter.Platform.Sdl3.Sdl3Window; +``` + +Avoid (`Inno` before third-party namespaces, a blank line inside the namespace group, an alias among the namespace usings, no blank line between kinds): + +```csharp +using Inno.Core.Events; +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; +using Xunit; + +using System; +using System.Collections.Generic; +using static System.MathF; +``` + +### N-05 No fully qualified names at the point of use + +Import a type with a using directive and refer to it by its short name. When two names collide, declare one alias at the top of the file and use only that alias throughout the file. + +```csharp +using System.IO; + +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; + +namespace Inno.Assets.Pipeline.Tests; + +public sealed class AssetLoaderTests +{ + private static AssetEvent Deleted(string path) => new(path, WatcherChangeTypes.Deleted); +} +``` + +Avoid: + +```csharp +namespace Inno.Assets.Pipeline.Tests; + +public sealed class AssetLoaderTests +{ + private static Inno.Assets.Pipeline.AssetChangedEvent Deleted(string path) + => new(path, System.IO.WatcherChangeTypes.Deleted); +} +``` + +### N-06 Alias names + +An alias is PascalCase, names the role the type plays in this file and differs from the short name of its target. One target has one alias per file. + +```csharp +using NativeWindow = Inno.Adapter.Platform.Sdl3.Sdl3Window; +``` + +Avoid (the alias repeats the target name, and a second alias names the same target): + +```csharp +using Sdl3Window = Inno.Adapter.Platform.Sdl3.Sdl3Window; +using Window = Inno.Adapter.Platform.Sdl3.Sdl3Window; +``` + +## 3. Naming + +### Summary + +| Element | Rule | Example | +| --- | --- | --- | +| Namespace segment | PascalCase | `Inno.Core.Events` | +| Class, struct, record, enum, delegate | PascalCase | `RenderGraph`, `AssetHandle` | +| Interface | `I` + PascalCase | `IEventSink` | +| Type parameter | `T` or `T` + PascalCase | `T`, `TSource` | +| Method, local function | PascalCase | `TryResolve`, `CreateBuffer` | +| Property, indexer | camelCase | `transform`, `isMissing` | +| Event | camelCase | `redrawRequested` | +| Constant (`const`, including local constants) | `C_` + UPPER_SNAKE | `C_MAX_COUNT` | +| `static readonly` field (any accessibility) | UPPER_SNAKE | `DEFAULT_OPTIONS`, `RED` | +| Private static mutable field | `s_` + camelCase | `s_nextID` | +| Private or protected instance field | `m_` + camelCase | `m_generation` | +| Internal or public instance field | camelCase | `latestSucceeded` | +| Enum member | PascalCase | `Borrowed` | +| Parameter, local variable, tuple element | camelCase | `outputDirectory` | +| Two-letter acronym | Upper case in PascalCase positions | `AssetID`, `IOStatus`, `UIScale` | +| Test class and test method | `XxxTests`, PascalCase sentence | `DispatchAfterDisposeThrows` | + +### NM-01 Type names + +A type name is a PascalCase noun or noun phrase. The suffix follows the role: `Attribute`, `Exception`, `EventArgs`, `Tests`, and `Extensions` for a class that holds extension methods. An abstract class has no `Base` or `Abstract` affix. + +```csharp +public sealed class InspectorMessageAttribute : Attribute; + +public static class PathExtensions +{ + public static string Normalize(this string path) => path.Replace('\\', '/'); +} + +public abstract class EditorDrop; +``` + +Avoid: + +```csharp +public sealed class InspectorMessage : Attribute; + +public static class PathHelpers +{ + public static string Normalize(this string path) => path.Replace('\\', '/'); +} + +public abstract class EditorDropBase; +``` + +### NM-02 Interfaces and type parameters + +An interface name starts with `I`. No other type starts with `I` followed by an upper-case letter. Use `T` when there is a single, obvious type parameter; otherwise use `T` plus a description. + +```csharp +public interface IAssetImporter + where TAsset : class +{ + TAsset Import(string path); +} + +public sealed class Pool; +``` + +Avoid: + +```csharp +public interface AssetImporter + where Asset : class +{ + Asset Import(string path); +} +``` + +### NM-03 Method names + +A method name is PascalCase and starts with a verb. These prefixes have fixed meanings: + +- `Try*` returns `bool`, does not throw on failure and returns its result through an `out` parameter. +- `Is*`, `Has*` and `Can*` return `bool` and have no side effects. +- `Create*` builds a new object that the caller owns. +- `Get*` reads existing state without side effects. +- `*Async` returns `Task` or `ValueTask` (NM-04). + +```csharp +public bool TryResolve( + AssetID id, + out AssetHandle handle +) => m_handles.TryGetValue(id, out handle); +``` + +Avoid (`Try*` that does not return `bool`): + +```csharp +public AssetHandle? TryResolve(AssetID id) => m_handles.GetValueOrDefault(id); +``` + +### NM-04 Asynchronous methods end with `Async` + +A method that returns `Task`, `Task`, `ValueTask` or `ValueTask` ends with `Async`. Overrides and interface implementations follow their contract. xUnit test methods do not take the suffix. + +```csharp +public async Task CompileAsync( + ShaderSource source, + CancellationToken cancellationToken +) { + ShaderProgram program = await m_frontend.ParseAsync(source, cancellationToken).ConfigureAwait(false); + return await m_backend.EmitAsync(program, cancellationToken).ConfigureAwait(false); +} +``` + +Avoid: + +```csharp +public async Task Compile( + ShaderSource source, + CancellationToken cancellationToken +) { + ShaderProgram program = await m_frontend.ParseAsync(source, cancellationToken).ConfigureAwait(false); + return await m_backend.EmitAsync(program, cancellationToken).ConfigureAwait(false); +} +``` + +### NM-05 Properties and indexers are camelCase + +Every property is camelCase, whatever its accessibility. A `bool` property starts with `is`, `has` or `can`, or is a past participle that states a condition, such as `disposed`. + +```csharp +public Transform transform { get; } +public bool isMissing => m_source is null; +public int count { get; private set; } +``` + +Avoid: + +```csharp +public Transform Transform { get; } +public bool Missing => m_source is null; +public int Count { get; private set; } +``` + +### NM-06 Instance fields + +- A private or protected instance field is `m_` + camelCase, whether or not it is `readonly`. +- An internal or public instance field is camelCase without a prefix. Such fields appear only in frame-local workspaces, interop structs and math types. +- One declaration declares one field. + +```csharp +public sealed class RenderQueue +{ + private readonly List m_items = []; + private int m_generation; +} + +internal struct GlyphVertex +{ + public Vector2 position; + public Vector2 uv; +} +``` + +Avoid: + +```csharp +public sealed class RenderQueue +{ + private readonly List _items = []; + private int generation, frameIndex; +} +``` + +### NM-07 Constants + +Every `const` is `C_` + UPPER_SNAKE: private, internal and public constants, and constants local to a method. + +```csharp +public sealed class SceneFile +{ + public const string C_DEFAULT_EXTENSION = ".iscene"; + private const int C_MAX_COUNT = 64; + + public void Flush() + { + const int C_BATCH_SIZE = 256; + Write(C_BATCH_SIZE); + } +} +``` + +Avoid: + +```csharp +public sealed class SceneFile +{ + public const string DefaultExtension = ".iscene"; + private const int MAX_COUNT = 64; + + public void Flush() + { + const int batchSize = 256; + Write(batchSize); + } +} +``` + +### NM-08 `static readonly` fields + +Every `static readonly` field is UPPER_SNAKE without any prefix, whatever its accessibility. The `C_` prefix is reserved for `const`. + +```csharp +public readonly struct Color +{ + public static readonly Color RED = FromBytes(255, 0, 0); + private static readonly JsonSerializerOptions SERIALIZER_OPTIONS = new(JsonSerializerDefaults.Web); +} +``` + +Avoid: + +```csharp +public readonly struct Color +{ + public static readonly Color Red = FromBytes(255, 0, 0); + private static readonly JsonSerializerOptions S_SERIALIZER_OPTIONS = new(); + private static readonly JsonSerializerOptions s_serializerOptions = new(); + private static readonly JsonSerializerOptions C_SERIALIZER_OPTIONS = new(); +} +``` + +### NM-09 Static mutable fields + +A private static mutable field is `s_` + camelCase. Product code does not declare non-private static mutable fields; shared process state belongs to an explicit host. + +```csharp +public sealed class HandleAllocator +{ + private static int s_nextID; +} +``` + +Avoid: + +```csharp +public sealed class HandleAllocator +{ + private static int m_nextID; + public static int nextID; +} +``` + +### NM-10 Events + +An event is camelCase, like a property. Name it with a past participle or as `xxxChanged` / `xxxRequested`. Its delegate type is a nullable `Action` or `Action<...>`. + +```csharp +public event Action? redrawRequested; +public event Action? assetReloaded; +``` + +Avoid: + +```csharp +public event Action? RedrawRequested; +public event EventHandler? OnRedraw; +``` + +### NM-11 Enums + +- A single-value enum has a singular name. A `[Flags]` enum has a plural name or ends with `Flags`. +- Members are PascalCase and never start with an underscore. +- `[Flags]` values are written as `1 << n`, with `None = 0`. Combined values are expressed with member names. +- One member per line, no trailing comma, no blank lines between members. + +```csharp +public enum EditorPlayModeState +{ + Editing, + Compiling, + Playing +} + +[Flags] +public enum EditorViewportNavigationCapabilities +{ + None = 0, + Orbit = 1 << 0, + Pan = 1 << 1, + Zoom = 1 << 2, + All = Orbit | Pan | Zoom +} +``` + +Avoid: + +```csharp +[Flags] +public enum EditorViewportNavigationCapability +{ + None = 0, + Orbit = 1, + Pan = 0x2, + Zoom = 4, +} +``` + +### NM-12 Parameters, local variables and tuple elements + +Use camelCase and whole words. Do not use Hungarian prefixes. Do not give a local variable or a parameter the name of a property of the same type, except for constructor parameters (E-08). + +| Situation | Name | +| --- | --- | +| `CancellationToken` parameter | `cancellationToken` | +| Default `catch` variable | `exception` | +| Unused lambda parameter | `_` | +| Loop index | `i`, `j`, `index` | +| Coordinate or component | `x`, `y`, `z`, `w` | + +Apart from this table, do not use one- or two-character names. `id` and `io` are whole words and are allowed. + +```csharp +public async Task SaveAsync( + Stream destination, + CancellationToken cancellationToken +) { + (int width, int height) size = Measure(); + foreach (AssetEntry entry in m_entries) + { + await entry.WriteAsync(destination, size, cancellationToken).ConfigureAwait(false); + } +} +``` + +Avoid: + +```csharp +public async Task SaveAsync( + Stream dst, + CancellationToken token +) { + (int Width, int Height) sz = Measure(); + foreach (AssetEntry e in m_entries) + { + await e.WriteAsync(dst, sz, token).ConfigureAwait(false); + } +} +``` + +### NM-13 Acronyms + +- A two-letter acronym is upper case wherever a PascalCase word would start: `ID`, `IO`, `UI`. This includes `ID`: write `AssetID`, `persistentID`, `GetID`, never `AssetId`. +- An acronym of three or more letters is written as an ordinary word: `Json`, `Http`, `Ktx`, `Sdl`. +- When an acronym starts a camelCase identifier, the whole acronym is lower case: `id`, `ioStatus`, `uiScale`. +- In UPPER_SNAKE names every word is upper case: `C_MAX_ID`. + +```csharp +public sealed class JsonAssetWriter +{ + public AssetID persistentID { get; } + public IOStatus ioStatus { get; } + public float uiScale { get; set; } + + public AssetID GetID(string id) => m_ids[id]; +} +``` + +Avoid: + +```csharp +public sealed class JSONAssetWriter +{ + public AssetId persistentId { get; } + public IoStatus IOStatus { get; } + public float UIScale { get; set; } + + public AssetId GetId(string ID) => m_ids[ID]; +} +``` + +## 4. Type declarations + +### T-01 Write every access modifier + +Every type and every member states its accessibility, including each file of a `partial` type. Interface members do not write `public`. + +```csharp +internal sealed partial class AssetLoader +{ + private int m_generation; +} + +public interface IEventSink +{ + void Publish(EventRecord record); +} +``` + +Avoid: + +```csharp +sealed partial class AssetLoader +{ + int m_generation; +} +``` + +### T-02 Modifier order + +Accessibility, then `static`, `extern`, `new`, then `virtual` / `abstract` / `sealed` / `override`, then `readonly`, `unsafe`, `required`, `volatile`, `async`, `partial`. + +```csharp +public static readonly Color RED = FromBytes(255, 0, 0); + +private static async Task RunAsync() +{ + await Task.Yield(); + Publish(); +} + +public sealed override string ToString() => name; + +public override readonly int GetHashCode() => m_value; + +internal static unsafe partial class NativeMethods; +``` + +Avoid: + +```csharp +public readonly override int GetHashCode() => m_value; + +static private int s_count; +``` + +### T-03 Classes are sealed by default + +Every class is `static`, `abstract` or `sealed`. Leave a class open only when it is a designed extension point, and document the derivation contract in its XML documentation. Nested private classes are sealed too. + +```csharp +public sealed class EventDispatcher; + +internal static class PathUtility +{ + internal static string Normalize(string path) => path.Replace('\\', '/'); +} + +public abstract class EditorDrop; +``` + +Avoid: + +```csharp +public class EventDispatcher; +``` + +### T-04 Records + +- A reference-type data contract is a `sealed record` with positional parameters, ending in `;`. +- A small value type is a `readonly record struct`. +- Positional parameters are properties, so they are camelCase. + +```csharp +public sealed record AssetChangedEvent( + string path, + WatcherChangeTypes change +); + +public readonly record struct AssetID(Guid value); +``` + +Avoid: + +```csharp +public record AssetChangedEvent(string Path, WatcherChangeTypes Change); + +public record struct AssetID(Guid value); +``` + +### T-05 Structs + +A struct is `readonly` by default. Use a mutable struct only for interop layouts and math types that are assigned field by field; its fields are public and camelCase. + +```csharp +public readonly struct FrameRange +{ + public int start { get; } + public int count { get; } +} + +[StructLayout(LayoutKind.Sequential)] +internal struct GlyphVertex +{ + public Vector2 position; + public Vector2 uv; +} +``` + +Avoid (a mutable struct that is not an interop or math type): + +```csharp +public struct FrameRange +{ + public int start { get; set; } + public int count { get; set; } +} +``` + +### T-06 Base lists and generic constraints on types + +- The base list stays on the line of the type name. +- Each `where` clause of a type is on its own line, indented four spaces. The opening brace stays on its own line. + +```csharp +public abstract class EditorDrop : EditorDrop + where TSource : IdentityObject + where TTarget : class +{ + public abstract bool Accepts(TSource source); +} +``` + +Avoid: + +```csharp +public abstract class EditorDrop + : EditorDrop where TSource : IdentityObject where TTarget : class +{ + public abstract bool Accepts(TSource source); +} +``` + +### T-07 Primary constructors + +- A record always uses a primary constructor. +- A class or struct may use a primary constructor to receive its dependencies. When it does, it uses the parameters directly and does not copy them into `m_` fields. +- Use an ordinary constructor with `m_` fields when arguments need validation or the fields must be `readonly`. +- Primary constructor parameters follow P-01. A base list follows the closing parenthesis as `) : Base`, with the opening brace on its own line. Without a base list the type body starts with `) {`. + +```csharp +internal sealed class TogglePlayModeAction(EditorPlayMode playMode) : EditorAction +{ + protected override bool CanExecute() => playMode.state != EditorPlayModeState.Compiling; +} + +internal sealed class SceneReloadChange( + RuntimeSession runtimeSession, + ISceneReloadStateTransfer migration +) : IGenerationChange +{ + public void Apply() => migration.Transfer(runtimeSession); +} + +internal sealed class FrameScope( + RenderGraph graph, + int frameIndex +) { + public bool isFirst => frameIndex == 0; + + public void Begin() => graph.BeginFrame(frameIndex); +} +``` + +Avoid (base list on a separate line, parameters copied into fields): + +```csharp +internal sealed class SceneReloadChange( + RuntimeSession runtimeSession, + ISceneReloadStateTransfer migration +) + : IGenerationChange +{ + private readonly RuntimeSession m_runtimeSession = runtimeSession; + private readonly ISceneReloadStateTransfer m_migration = migration; +} +``` + +### T-08 Nested types + +A nested type is placed at the end of its containing type. Nest a type only when the containing type is its only user. + +```csharp +public sealed class AssetCache +{ + private readonly Dictionary m_entries = []; + + public int count => m_entries.Count; + + private sealed class Entry + { + public AssetHandle handle { get; init; } + public int generation { get; set; } + } +} +``` + +Avoid (the nested type comes first): + +```csharp +public sealed class AssetCache +{ + private sealed class Entry + { + public AssetHandle handle { get; init; } + public int generation { get; set; } + } + + private readonly Dictionary m_entries = []; +} +``` + +## 5. Member declarations + +### M-01 Property forms + +- An auto-property is written on one line: `{ get; }`, `{ get; set; }`, `{ get; init; }`, `{ get; private set; }`. +- A read-only computed property uses an expression body. +- A property whose accessors contain logic is expanded: the braces are on their own lines, an accessor with a single expression uses `=>`, an accessor with statements uses a block. + +```csharp +public string name { get; } +public int count { get; private set; } +public bool isEmpty => m_items.Count == 0; + +public float scale +{ + get => m_scale; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + m_scale = value; + } +} +``` + +Avoid: + +```csharp +public bool isEmpty { get { return m_items.Count == 0; } } +public float scale { get => m_scale; set => m_scale = value; } +``` + +### M-02 Expression-bodied members + +- A method, property, indexer or operator whose body is one expression (one `return`, one call or one assignment) uses an expression body. +- A body with control flow, several statements or `try` uses a block. +- A constructor always uses a block body. + +```csharp +public override string ToString() => $"{name} ({count})"; + +public static bool operator ==( + Color left, + Color right +) => left.Equals(right); + +public RenderQueue(int capacity) +{ + m_items = new List(capacity); +} +``` + +Avoid: + +```csharp +public override string ToString() +{ + return $"{name} ({count})"; +} + +public RenderQueue(int capacity) => m_items = new List(capacity); +``` + +### M-03 Placement of `=>` in expression-bodied members + +1. When the whole member fits on one line, `=> expression` stays on the declaration line. +2. After a multi-line parameter list, the body starts on the line of the closing parenthesis: `) => expression`. When the expression is a call, an object creation or a collection that does not fit, break inside it (A-02). +3. When the signature is on one line and the body does not fit after it, move `=>` to the next line, indented four spaces. +4. After a wrapped `=>`, a brace-delimited expression (a `switch` expression, an object initializer or a `with` expression) puts its braces on their own lines at the column of the declaration, with its contents indented four spaces from the declaration. +5. After a wrapped `=>`, a call or object creation that must break follows A-02 relative to the `=>` line, and operator continuation lines align with the first operand (F-05). +6. `=>` never ends a line with the expression on the next line, and never stands alone on a line. + +```csharp +public bool isMissing => m_source is null; + +public static Color FromBytes( + byte r, + byte g, + byte b +) => new(r / 255f, g / 255f, b / 255f); + +public static Color Lerp( + Color from, + Color to, + float amount +) => new( + from.r + (to.r - from.r) * amount, + from.g + (to.g - from.g) * amount, + from.b + (to.b - from.b) * amount +); + +protected override EditorActionState Query(EditorActionContext context) + => playMode.state switch +{ + EditorPlayModeState.Editing => new EditorActionState(true, true), + EditorPlayModeState.Playing => new EditorActionState(true, false), + _ => EditorActionState.DISABLED +}; + +internal bool IsActiveFor(object? target) + => m_isActive + && m_activeTarget is not null + && m_activeTarget.Matches(m_activeInteractions, target); + +protected override EditorActionState Describe(EditorActionContext context) + => new EditorActionState( + isVisible: context.selection.count > 0, + isEnabled: playMode.state == EditorPlayModeState.Editing, + displayName: "Duplicate Selection" + ); +``` + +Avoid (`=>` left at the end of the line, braces indented under the wrapped `=>`, closing parenthesis left on the last argument): + +```csharp +protected override EditorActionState Query(EditorActionContext context) => + playMode.state switch + { + EditorPlayModeState.Editing => new EditorActionState(true, true), + _ => EditorActionState.DISABLED + }; + +public static Color Lerp( + Color from, + Color to, + float amount +) + => new( + from.r + (to.r - from.r) * amount, + from.g + (to.g - from.g) * amount, + from.b + (to.b - from.b) * amount); +``` + +### M-04 Field and property initializers + +- A field or property initializer uses a target-typed expression so the type is written once: `= new(...)` or `= []`. +- One declaration declares one field or one local variable. + +```csharp +private readonly Dictionary m_commands = new(StringComparer.Ordinal); +private readonly List m_items = []; + +public IReadOnlyList tags { get; init; } = []; +``` + +Avoid: + +```csharp +private readonly Dictionary m_commands = new Dictionary(StringComparer.Ordinal); +private readonly List m_items = new List(); +``` + +### M-05 Attributes + +- Each attribute is on its own line above the declaration. One pair of brackets holds one attribute. +- Omit the `Attribute` suffix. Omit empty parentheses. +- An attribute on a parameter stays on the line of the parameter. +- Attribute arguments break like any other argument list (A-02). + +```csharp +[Fact] +[Trait("Category", "Lifecycle")] +public void DisposeIsIdempotent() +{ + m_queue.Dispose(); + m_queue.Dispose(); +} + +[SerializableProperty] +public float speed { get; set; } + +public bool TryRead( + string key, + [NotNullWhen(true)] out string? value +) => m_values.TryGetValue(key, out value); +``` + +Avoid: + +```csharp +[Fact, Trait("Category", "Lifecycle")] +public void DisposeIsIdempotent() +{ + m_queue.Dispose(); + m_queue.Dispose(); +} + +[SerializableProperty()] public float speed { get; set; } +``` + +## 6. Member order + +### O-01 Group order + +Members of a type appear in these groups, in this order, with one blank line between groups: + +1. Constants (`const`). +2. Static fields: `static readonly` first, then static mutable. +3. Instance fields: `readonly` first, then mutable. +4. Constructors. +5. Public members. +6. Protected and internal members. +7. Private members. +8. Nested types. + +Inside groups 5, 6 and 7 the order is: properties, events, instance methods, static methods. An explicit interface implementation follows the public members of the interface it implements. + +```csharp +public sealed class RenderQueue : IDisposable +{ + private const int C_INITIAL_CAPACITY = 64; + + private static readonly RenderItemComparer COMPARER = new(); + + private readonly List m_items; + private bool m_disposed; + + public RenderQueue() + { + m_items = new List(C_INITIAL_CAPACITY); + } + + public int count => m_items.Count; + + public event Action? flushed; + + public void Enqueue(RenderItem item) + { + ObjectDisposedException.ThrowIf(m_disposed, this); + m_items.Add(item); + } + + public void Dispose() + { + m_items.Clear(); + m_disposed = true; + } + + internal void Sort() => m_items.Sort(COMPARER); + + private void NotifyFlushed() => flushed?.Invoke(); + + private sealed class RenderItemComparer : IComparer + { + public int Compare( + RenderItem left, + RenderItem right + ) => left.order.CompareTo(right.order); + } +} +``` + +Avoid (a private method before the public members, fields after the constructor): + +```csharp +public sealed class RenderQueue +{ + public RenderQueue() + { + m_items = new List(C_INITIAL_CAPACITY); + } + + private void NotifyFlushed() => flushed?.Invoke(); + + private readonly List m_items; + + public int count => m_items.Count; + + private const int C_INITIAL_CAPACITY = 64; +} +``` + +### O-02 Keep related members together + +Members of the same accessibility and kind are contiguous. Overloads are adjacent and ordered from fewest to most parameters. + +```csharp +public void Draw(Mesh mesh) => Draw(mesh, m_defaultMaterial); + +public void Draw( + Mesh mesh, + Material material +) { + Submit(new RenderItem(mesh, material)); + m_drawn++; +} + +public void Clear() => m_items.Clear(); + +private void Submit(RenderItem item) => m_items.Add(item); +``` + +Avoid (overloads separated, a private method between public methods): + +```csharp +public void Draw(Mesh mesh) => Draw(mesh, m_defaultMaterial); + +private void Submit(RenderItem item) => m_items.Add(item); + +public void Clear() => m_items.Clear(); + +public void Draw( + Mesh mesh, + Material material +) { + Submit(new RenderItem(mesh, material)); + m_drawn++; +} +``` + +## 7. Braces and blocks + +### B-01 Braces are on their own lines + +The opening brace of a type, a method body, an accessor, a control statement, a lambda block, an object or collection initializer and a `switch` expression is on its own line, aligned with the start of the construct. The closing brace is on its own line, aligned with the opening brace. + +The only places where an opening brace shares a line with other code are: + +- `) {` after a multi-line parameter list or a multi-line statement header (B-02). +- A single-line construct: an auto-property, a short initializer, a property pattern, a compact guard (B-05). +- An empty body `{}` (B-07). + +```csharp +public void Flush() +{ + foreach (RenderItem item in m_items) + { + Draw(item); + m_drawn++; + } + + try + { + Present(); + } + catch (DeviceLostException exception) + { + m_log.Error(exception.Message); + throw; + } + finally + { + m_items.Clear(); + } +} +``` + +Avoid: + +```csharp +public void Flush() { + foreach (RenderItem item in m_items) { + Draw(item); + } + + try { Present(); } + catch (DeviceLostException) { throw; } + finally { m_items.Clear(); } +} +``` + +### B-02 `) {` after a multi-line parameter list or statement header + +When a parameter list is expanded over several lines (P-01) and the body follows it directly, the opening brace shares the line of the closing parenthesis: `) {`. The closing brace aligns with the start of the declaration. This applies to methods, constructors, local functions, operators and primary constructors without a base list. The same form closes a control statement whose header spans several lines (W-05). + +```csharp +internal void Register( + string commandID, + Action command +) { + ArgumentException.ThrowIfNullOrWhiteSpace(commandID); + ArgumentNullException.ThrowIfNull(command); + m_commands.Add(commandID, command); +} +``` + +Avoid (brace on its own line after a multi-line parameter list, several parameters on one line): + +```csharp +internal void Register( + string commandID, + Action command +) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +internal void Unregister(string commandID, Action command) +{ + m_commands.Remove(commandID); + m_dirty = true; +} +``` + +### B-03 Clauses between `)` and the body + +A constructor initializer (`: base(...)`, `: this(...)`) or a `where` clause sits between the parameter list and the body. + +- After a multi-line parameter list, the clause follows the closing parenthesis on the same line: `) : this(...)` or `) where T : class`. The opening brace is then on its own line. +- After a single-line signature, the clause is on the next line, indented four spaces. The opening brace is on its own line. +- Additional `where` clauses each take their own line, aligned with the first `where`. + +```csharp +public InspectorMessageAttribute( + string text, + InspectorMessageType messageType +) : this(text, messageType, string.Empty) +{ + this.isExpanded = true; +} + +public InspectorMessageAttribute(string text) + : this(text, InspectorMessageType.Info) +{ + this.isExpanded = false; +} + +public T Resolve( + string id, + bool required +) where T : class +{ + object resolved = ResolveCore(typeof(T), id, required); + return (T)resolved; +} + +public TTarget Convert( + TSource source, + bool required +) where TSource : IdentityObject + where TTarget : class +{ + object converted = ConvertCore(source, typeof(TTarget), required); + return (TTarget)converted; +} + +public T Find(string id) + where T : class +{ + object found = FindCore(typeof(T), id); + return (T)found; +} +``` + +Avoid (clause on its own line after a multi-line parameter list, clause on the signature line of a single-line signature, `) {` after a clause): + +```csharp +public InspectorMessageAttribute( + string text, + InspectorMessageType messageType +) + : this(text, messageType, string.Empty) +{ + this.isExpanded = true; +} + +public InspectorMessageAttribute(string text) : this(text, InspectorMessageType.Info) +{ + this.isExpanded = false; +} + +public T Resolve( + string id, + bool required +) where T : class { + object resolved = ResolveCore(typeof(T), id, required); + return (T)resolved; +} +``` + +### B-04 Lambda bodies + +- **Expression body that fits:** `x => expression` on one line. +- **Block body:** `=>` ends the line; the braces are on their own lines, aligned with the start of the statement that contains the lambda. The closing brace is followed directly by `)`, `,` or `;`. This holds when the lambda has a multi-line parameter list too: `) =>`, then the brace on the next line. +- **Expression body that is a call or object creation and does not fit:** the call starts on the `=>` line and breaks inside its parentheses (A-02). +- **Any other expression body that does not fit:** wrap it in parentheses. `(` follows `=>`, the expression is indented four spaces, and `)` is on its own line. + +```csharp +m_dispatcher.Subscribe(entry => +{ + m_pending.Add(entry); + m_dirty = true; +}); + +entries.Sort(( + left, + right +) => +{ + int byName = string.CompareOrdinal(left.name, right.name); + return byName != 0 ? byName : left.order.CompareTo(right.order); +}); + +IEnumerable blended = pairs.Select(pair => new Color( + pair.from.r + (pair.to.r - pair.from.r) * amount, + pair.from.g + (pair.to.g - pair.from.g) * amount, + pair.from.b + (pair.to.b - pair.from.b) * amount +)); + +Func isStale = entry => ( + entry.lastWriteTimeUtc < threshold && !entry.isPinned +); +``` + +Avoid (brace on the `=>` line, block squeezed onto one line, expression body moved to the next line without parentheses): + +```csharp +m_dispatcher.Subscribe(entry => { + m_pending.Add(entry); + m_dirty = true; +}); + +m_dispatcher.Subscribe(entry => { m_pending.Add(entry); m_dirty = true; }); + +Func isStale = entry => + entry.lastWriteTimeUtc < threshold && !entry.isPinned; +``` + +### B-05 Control statement bodies always use braces + +1. The body of `if`, `else`, `for`, `foreach`, `while`, `do`, `using`, `lock` and `fixed` is always enclosed in braces, each brace on its own line. +2. One compact form is permitted where it reads better: an `if` without `else` whose body is a single short statement may be written entirely on one line, `if (condition) statement;`. Use it for guard clauses and keep a run of adjacent guards in the same form. +3. A body on the next line without braces is never allowed. +4. Stacked `using` or `fixed` headers that share one braced body are the only headers that may follow each other without braces in between. + +```csharp +if (m_disposed) +{ + return; +} + +while (reader.Read()) +{ + Process(reader.current); +} + +foreach (RenderItem item in m_items) +{ + if (item is null) continue; + if (!item.isVisible) continue; + + Draw(item); +} + +fixed (byte* source = input) +fixed (byte* target = output) +{ + Copy(source, target, length); +} +``` + +Avoid: + +```csharp +if (m_disposed) + return; + +foreach (RenderItem item in m_items) + Draw(item); + +foreach (AssetEntry entry in m_entries) + if (entry.isMissing) + missing.Add(entry); + +foreach (RenderItem item in m_items) Draw(item); +``` + +### B-06 `if` / `else` chains + +Every branch of an `if … else if … else` chain uses braces. The compact one-line form (B-05) is not used when the `if` has an `else`. + +```csharp +if (state == EditorPlayModeState.Editing) +{ + EnterPlayMode(); +} +else if (state == EditorPlayModeState.Playing) +{ + ExitPlayMode(); +} +else +{ + m_log.Warning("Play mode is changing."); +} +``` + +Avoid: + +```csharp +if (state == EditorPlayModeState.Editing) EnterPlayMode(); +else ExitPlayMode(); + +if (state == EditorPlayModeState.Editing) + EnterPlayMode(); +else +{ + m_log.Warning("Play mode is already active."); + ExitPlayMode(); +} +``` + +### B-07 Empty bodies + +- An empty type ends with a semicolon and has no braces. +- An empty method, constructor, accessor, local function or lambda body is `{}`, with no space inside, on the line where the header ends. +- An empty `catch` block is not empty: it contains a comment that explains why the exception is ignored (X-04). +- A property pattern that matches any non-null value is written `{ }`. + +```csharp +public sealed class EmptyPayload; + +public interface IMarker; + +protected virtual void OnActivated() {} + +public NullSink( + string name, + int capacity +) {} + +public NamedSink(string name) + : base(name) {} +``` + +Inside a method: + +```csharp +Action noop = () => {}; + +if (value is { } resolved) +{ + Use(resolved); +} +``` + +Avoid: + +```csharp +public sealed class EmptyPayload +{ +} + +public sealed class OtherPayload { } + +protected virtual void OnActivated() +{ +} + +protected virtual void OnDeactivated() { } +``` + +### B-08 `else`, `catch`, `finally` and `while` + +`else`, `catch` and `finally` start a new line after the closing brace. The `while` of a `do … while` loop starts a new line too. + +```csharp +do +{ + read = stream.Read(buffer); + total += read; +} +while (read > 0); +``` + +Avoid: + +```csharp +do +{ + read = stream.Read(buffer); + total += read; +} while (read > 0); +``` + +### B-09 One statement per line + +A line holds one statement. The statement after a `case` label starts on the next line. Nothing follows an opening brace on its line. The compact guard of B-05 is the only construct in which a statement shares the line of its header. + +```csharp +switch (key) +{ + case KeyCode.Left: + cursor--; + break; + case KeyCode.Right: + cursor++; + break; +} +``` + +Avoid: + +```csharp +switch (key) +{ + case KeyCode.Left: cursor--; break; + case KeyCode.Right: cursor++; break; +} + +x = 0; y = 0; +``` + +## 8. Parameter and argument lists + +### P-01 Parameter lists: one line for zero or one parameter, fully expanded for two or more + +A declaration with two or more parameters breaks after the opening parenthesis, puts each parameter on its own line indented four spaces, and puts the closing parenthesis on its own line aligned with the start of the declaration. A declaration with zero or one parameter stays on one line. + +This applies to methods, constructors, local functions, delegates, operators, primary constructors and lambdas. + +```csharp +public void Clear() => m_commands.Clear(); + +public void Remove(string commandID) => m_commands.Remove(commandID); + +public void Register( + string commandID, + Action command +) { + m_commands.Add(commandID, command); + m_dirty = true; +} + +public delegate void AssetCallback( + AssetID id, + AssetHandle handle +); +``` + +Local functions and lambdas follow the same rule: + +```csharp +void Visit( + Node node, + int depth +) { + m_visited.Add(node); + m_depths[node] = depth; +} + +bool duplicate = updated.Where(( + _, + candidateIndex +) => candidateIndex != index).Any(); +``` + +Avoid: + +```csharp +public void Register(string commandID, Action command) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +public void Register(string commandID, + Action command) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +public void Register( + string commandID, + Action command) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +bool duplicate = updated.Where((_, candidateIndex) => candidateIndex != index).Any(); +``` + +### P-02 What follows the closing parenthesis of a multi-line parameter list + +| Followed by | Form | +| --- | --- | +| Block body | `) {` | +| Empty body | `) {}` | +| Expression body | `) => expression;` — when the expression must break, it breaks inside its own delimiters: `) => new(` … `);` | +| No body (interface, abstract, delegate, record) | `);` | +| Constructor initializer | `) : base(...)` or `) : this(...)`, opening brace on its own line | +| `where` clause | `) where T : class`, opening brace on its own line | +| Base list of a primary constructor | `) : Base`, opening brace on its own line | +| Lambda body | `) =>`, then the expression, or the opening brace on its own line | + +```csharp +public interface IAssetStore +{ + Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ); +} + +public sealed class NullAssetStore : IAssetStore +{ + public NullAssetStore( + string name, + int capacity + ) {} + + public Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ) => Task.FromResult(AssetHandle.MISSING); +} +``` + +Avoid: + +```csharp +public sealed class NullAssetStore : IAssetStore +{ + public Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ) + => Task.FromResult(AssetHandle.MISSING); +} +``` + +### P-03 Parameter details + +- A default value is written `= value`, with one space on each side of `=`. +- `this`, `ref`, `out`, `in` and `params` are separated from the type by one space. +- `CancellationToken cancellationToken` is always the last parameter. + +```csharp +public Task LoadAsync( + AssetID id, + bool required = true, + CancellationToken cancellationToken = default +) { + cancellationToken.ThrowIfCancellationRequested(); + return LoadCoreAsync(id, required, cancellationToken); +} +``` + +Avoid: + +```csharp +public Task LoadAsync( + CancellationToken cancellationToken, + AssetID id, + bool required=true +) { + cancellationToken.ThrowIfCancellationRequested(); + return LoadCoreAsync(id, required, cancellationToken); +} +``` + +### A-01 Argument lists stay on one line when they fit + +The arguments of a call, an object creation or a constructor initializer stay on one line whenever the whole statement fits within the line width. + +```csharp +m_commands.Add(commandID, command); +var buffer = new VertexBuffer(device, capacity, VertexLayout.DEFAULT); +``` + +Avoid (a short call broken for no reason): + +```csharp +m_commands.Add( + commandID, + command +); +``` + +### A-02 Broken argument lists: one argument per line, closing parenthesis on its own line + +When an argument list does not fit on one line: + +- The opening parenthesis ends its line. +- Each argument is on its own line, indented four spaces from the line that contains the opening parenthesis. +- The closing parenthesis is on its own line, aligned with the start of the line that contains the opening parenthesis. Whatever follows the call — `;`, `.Next(...)`, `,` or an outer closing delimiter — follows that parenthesis. +- Nested calls apply the same rule one level deeper. + +This holds for every call, including `new`, `throw new`, `await`, `return`, attribute arguments and constructor initializers. + +```csharp +return await m_textureCompiler.CompileKtxAsync( + encoded, + texture.slot.colorSpace, + cancellationToken +).ConfigureAwait(false); + +throw new ArgumentException( + $"The viewport '{viewport.name}' does not support mode '{defaultMode}'.", + nameof(defaultMode) +); + +var result = new ShaderCompilationResult( + null, + [new ShaderDiagnostic( + "SHADER_COMPILE_EXCEPTION", + DiagnosticSeverity.Error, + message + )] +); + +string intermediate = scoped.GetNativeBuildRoot( + componentDescriptor, + configuration, + targetArchitecture +); +``` + +Avoid (closing parenthesis left on the last argument, first argument left on the opening line, several arguments packed on a line, arguments aligned with the parenthesis): + +```csharp +return await m_textureCompiler.CompileKtxAsync( + encoded, + texture.slot.colorSpace, + cancellationToken).ConfigureAwait(false); + +return await m_textureCompiler.CompileKtxAsync(encoded, + texture.slot.colorSpace, cancellationToken).ConfigureAwait(false); + +throw new ArgumentException($"The viewport '{viewport.name}' does not support mode '{defaultMode}'.", + nameof(defaultMode)); +``` + +### A-03 Hugging a single multi-line argument + +When exactly one argument spans several lines, and that argument is a lambda, an object initializer, an anonymous object or a collection expression, the arguments may all start on the line of the opening parenthesis. The multi-line argument is laid out by its own rule, and the closing parenthesis follows its closing delimiter. + +When two or more arguments span several lines, expand the list (A-02). + +```csharp +m_dispatcher.Subscribe(entry => +{ + m_pending.Add(entry); + m_dirty = true; +}); + +Task task = Task.Run(() => +{ + Compile(source); + Publish(source); +}, cancellationToken); + +loader.ApplySourceChanges([ + new AssetEvent("Text/new.txt", WatcherChangeTypes.Deleted), + new AssetEvent("Text/old.txt", WatcherChangeTypes.Deleted) +]); + +scheduler.Schedule( + () => + { + Compile(source); + Publish(source); + }, + exception => + { + m_log.Error(exception.Message); + m_failed = true; + } +); +``` + +Avoid (two multi-line arguments hugged together): + +```csharp +scheduler.Schedule(() => +{ + Compile(source); + Publish(source); +}, exception => +{ + m_log.Error(exception.Message); + m_failed = true; +}); +``` + +### A-04 Named arguments + +A named argument is written `name: value`, with no space before the colon and one space after it. Name adjacent `bool` or numeric literal arguments whose meaning is not obvious from the call. + +```csharp +var state = new EditorActionState(true, true, displayName: "Enter Play Mode"); +window.Resize(width: 1280, height: 720); +``` + +Avoid: + +```csharp +window.Resize(width : 1280, height:720); +texture.Update(true, false, 0, 4); +``` + +## 9. Line breaks + +### W-01 Binary operators lead the continuation line + +When an expression breaks at `&&`, `||`, `??`, `+`, `-`, `|` or another binary operator, the operator starts the next line. Continuation lines align with the first operand (F-05). + +```csharp +bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format; + +string message = "The asset database could not be opened because " + + "another editor instance holds the workspace lock."; + +string name = entry.displayName + ?? entry.path.GetFileName() + ?? string.Empty; +``` + +Avoid: + +```csharp +bool changed = previous.width != current.width || + previous.height != current.height; +``` + +### W-02 Conditional expressions + +A conditional expression stays on one line when it fits. Otherwise `?` and `:` each start a line, aligned with the condition (F-05). Do not nest conditional expressions; use a `switch` expression or an `if` statement. + +```csharp +int order = byName != 0 ? byName : left.order.CompareTo(right.order); + +ShaderCompilationResult result = pending.IsCompletedSuccessfully + ? pending.Result + : new ShaderCompilationResult(null, diagnostics); +``` + +Avoid: + +```csharp +ShaderCompilationResult result = pending.IsCompletedSuccessfully ? + pending.Result : + new ShaderCompilationResult(null, diagnostics); + +string label = count == 0 ? "none" : count == 1 ? "one" : "many"; +``` + +### W-03 Call chains + +A call chain stays on one line when it fits. Otherwise the first link stays on the statement line and every following `.` (or `?.`) starts a line, indented four spaces from the start of the statement. + +```csharp +List names = m_entries + .Where(static entry => !entry.isMissing) + .Select(static entry => entry.displayName) + .OrderBy(static name => name, StringComparer.Ordinal) + .ToList(); +``` + +Avoid: + +```csharp +List names = m_entries.Where(static entry => !entry.isMissing). + Select(static entry => entry.displayName). + ToList(); +``` + +### W-04 Assignments and arrows + +- Never break a line directly before or after `=`. Keep the start of the right-hand side on the line of the `=` and break inside it: after an opening parenthesis (A-02), before an operator (W-01) or before a `.` (W-03). The only exception is the opening bracket of a multi-line collection expression, which takes its own line (I-03). +- A lambda `=>` always ends its line when the body moves down; the body then follows B-04. An expression body that is not a call is wrapped in parentheses. +- The `=>` of a `switch` expression arm stays on the line of the arm. +- The `=>` of an expression-bodied member follows M-03. + +```csharp +string intermediate = scoped.GetNativeBuildRoot( + componentDescriptor, + configuration, + targetArchitecture +); + +Func isStale = entry => ( + entry.lastWriteTimeUtc < threshold && !entry.isPinned +); +``` + +Avoid: + +```csharp +string intermediate = + scoped.GetNativeBuildRoot(componentDescriptor, configuration, targetArchitecture); + +Func isStale = entry => + entry.lastWriteTimeUtc < threshold && !entry.isPinned; +``` + +### W-05 Multi-line conditions and statement headers + +- `is` stays on the line of its left operand. `or` and `and` start their continuation lines. +- When the parenthesized header of `if`, `else if`, `while`, `for`, `foreach`, `switch`, `lock`, `using` or `fixed` spans several lines, its closing parenthesis is on its own line, aligned with the keyword, and the opening brace follows it: `) {`. This mirrors the multi-line parameter list (B-02). + +```csharp +if (token.kind is TokenKind.Comma + or TokenKind.Semicolon + or TokenKind.CloseBrace +) { + return; +} + +if (capabilities != EditorViewportNavigationCapabilities.None + && !SupportsMode(capabilities, defaultMode) +) { + throw new ArgumentException("The default mode is not supported.", nameof(defaultMode)); +} + +foreach (KeyValuePair dependency in HostDependencyManifest + .GetInnoRuntimeAssemblies(roots) + .OrderBy(static dependency => dependency.Key, StringComparer.OrdinalIgnoreCase) +) { + Enqueue(dependency.Key, dependency.Value); +} +``` + +Avoid: + +```csharp +if (token.kind is TokenKind.Comma + or TokenKind.Semicolon + or TokenKind.CloseBrace) +{ + return; +} + +if (capabilities != EditorViewportNavigationCapabilities.None + && !SupportsMode(capabilities, defaultMode)) + throw new ArgumentException("The default mode is not supported.", nameof(defaultMode)); +``` + +## 10. Initializers and collections + +### I-01 Object initializers + +- A short initializer stays on one line with one space inside each brace: `new Foo { a = 1 }`. +- Otherwise the opening brace is on its own line, aligned with the start of the statement; each member is on its own line, indented four spaces; the closing brace is on its own line. +- Omit the empty `()` when an initializer is present. +- `with` expressions and anonymous objects follow the same rule. + +```csharp +var options = new JsonSerializerOptions { WriteIndented = true }; + +var request = new GameBuildRequest +{ + profile = profile, + outputDirectory = outputDirectory, + configuration = BuildConfiguration.Release +}; + +RenderSettings updated = settings with +{ + exposure = 1.5f, + toneMapping = ToneMapping.Aces +}; +``` + +Avoid: + +```csharp +var request = new GameBuildRequest() { + profile = profile, outputDirectory = outputDirectory, + configuration = BuildConfiguration.Release, +}; +``` + +### I-02 Collections use collection expressions + +- Arrays, `List`, spans and immutable collections are written as collection expressions: `[a, b]`, `[]`, `[.. source]`. +- A spread operator is followed by one space: `[.. source, extra]`. +- Use `new T(...)` when a constructor argument (a capacity, a comparer) is needed, and `new T[n]` for a fixed-size buffer. +- Do not write `new[] { ... }`, `new T[] { ... }`, `new List { ... }` or `Array.Empty()`. + +```csharp +List items = []; +string[] extensions = [".png", ".jpg", ".ktx"]; +List all = [.. builtIn, .. custom, "fallback"]; +var byName = new Dictionary(StringComparer.Ordinal); +var buffer = new byte[C_BUFFER_SIZE]; +``` + +Avoid: + +```csharp +List items = new List(); +string[] extensions = new[] { ".png", ".jpg", ".ktx" }; +List all = [..builtIn, ..custom, "fallback"]; +string[] none = Array.Empty(); +``` + +### I-03 Multi-line collection expressions + +- With two or more elements that do not fit on one line: one element per line, indented four spaces, and the closing bracket on its own line. +- As the value of a declaration or assignment, the opening bracket is on its own line, aligned with the start of the statement, like the brace of an object initializer. +- As an argument, the opening bracket follows the opening parenthesis or the preceding argument (A-03). +- A single element that itself spans several lines hugs the brackets: `[new X(` … `)]`. + +```csharp +string[] searchPaths = +[ + Path.Combine(root, "Assets"), + Path.Combine(root, "Packages"), + Path.Combine(root, "Library", "Imported") +]; + +loader.ApplySourceChanges([ + new AssetEvent("Text/new.txt", WatcherChangeTypes.Deleted), + new AssetEvent("Text/old.txt", WatcherChangeTypes.Deleted) +]); + +return new ShaderCompilationResult( + null, + [new ShaderDiagnostic( + "SHADER_COMPILE_EXCEPTION", + DiagnosticSeverity.Error, + message + )] +); +``` + +Avoid: + +```csharp +string[] searchPaths = [Path.Combine(root, "Assets"), + Path.Combine(root, "Packages"), Path.Combine(root, "Library", "Imported")]; + +return new ShaderCompilationResult( + null, + [new ShaderDiagnostic( + "SHADER_COMPILE_EXCEPTION", + DiagnosticSeverity.Error, + message)]); +``` + +### I-04 `switch` expressions + +`value switch` is on one line; the opening brace is on its own line; each arm is on its own line with its `=>`; the discard arm is last. + +```csharp +string label = state switch +{ + EditorPlayModeState.Editing => "Enter Play Mode", + EditorPlayModeState.Compiling => "Compiling", + EditorPlayModeState.Playing => "Exit Play Mode", + _ => throw new ArgumentOutOfRangeException(nameof(state)) +}; +``` + +Avoid: + +```csharp +string label = state switch { EditorPlayModeState.Editing => "Enter", _ => "Exit", }; +``` + +### I-05 No trailing commas + +The last item of an object initializer, a collection, an enum, a `switch` expression or an anonymous object is not followed by a comma. + +```csharp +public enum ToneMapping +{ + None, + Reinhard, + Aces +} +``` + +Avoid: + +```csharp +public enum ToneMapping +{ + None, + Reinhard, + Aces, +} +``` + +## 11. Spacing and blank lines + +### S-01 Spaces + +| Position | Rule | Example | +| --- | --- | --- | +| Control keyword and `(` | One space | `if (x)`, `foreach (T item in items)` | +| Method name, `typeof`, `nameof`, `default` and `(` | No space | `Draw(item)`, `typeof(int)` | +| `new` and `(` or `[` | No space | `new()`, `new[]` | +| Inside parentheses and brackets | No space | `Add(a, b)`, `items[0]` | +| Before an index bracket | No space | `items[0]` | +| Comma | None before, one after | `Add(a, b)` | +| Semicolon in `for` | None before, one after | `for (int i = 0; i < n; i++)` | +| Binary operators, assignment, `=>`, `??`, `?:` | One on each side | `a + b`, `x => x.id` | +| Unary operators | Attached to the operand | `!ready`, `-value`, `i++` | +| After a cast | No space | `(float)count` | +| Member access `.`, `?.`, `->` | No space | `entry?.name` | +| Inside generic angle brackets | No space | `Dictionary` | +| Nullable `?` and pointer `*` | Attached to the type | `string?`, `byte* data` | +| Range `..` | No space | `span[1..^1]` | +| Spread `..` | One space after | `[.. items]` | +| Inside single-line braces with content | One on each side | `{ get; }`, `new T { a = 1 }`, `is { }` | +| Empty body | No space inside | `{}` | +| Before `{` on the same line | One space | `) {`, `() {}` | +| Colon of a base list, constraint or initializer | One on each side | `class A : B`, `where T : class` | +| Colon of a named argument or attribute target | None before, one after | `width: 1280`, `[assembly: X]` | + +```csharp +if (ready) +{ + float ratio = (float)count / total; + int first = items[0]; + Draw(item, ratio, first); +} +``` + +Avoid: + +```csharp +if(ready) +{ + float ratio = (float) count/total; + int first = items [0]; + Draw( item,ratio , first ); +} +``` + +### S-02 Column alignment + +- When more than three consecutive `const` declarations, or more than three consecutive `static readonly` declarations, have the same type, aligning their `=` signs in a column is recommended. It is not required. +- A numeric matrix or lookup table may align its elements in columns. +- Everywhere else, use a single space between tokens. Do not column-align local variables, assignments, parameters or comments. + +```csharp +private const int C_WIDTH = 1280; +private const int C_HEIGHT = 720; +private const int C_REFRESH_RATE = 60; +private const int C_MIN_SIZE = 16; + +public static readonly Color RED = FromBytes(255, 0, 0); +public static readonly Color GREEN = FromBytes(0, 255, 0); +public static readonly Color BLUE = FromBytes(0, 0, 255); +public static readonly Color WHITE = FromBytes(255, 255, 255); + +private static readonly float[] IDENTITY = +[ + 1f, 0f, 0f, 0f, + 0f, 1f, 0f, 0f, + 0f, 0f, 1f, 0f, + 0f, 0f, 0f, 1f +]; +``` + +Avoid (alignment of local variables and trailing comments): + +```csharp +int width = 1280; +string title = "Scene"; // window title +float refreshRate = 60f; // hertz +``` + +### S-03 Blank lines between members + +- Methods, constructors, members with documentation comments and multi-line properties are separated by one blank line. +- Fields, constants and single-line properties of the same group that have no documentation comments are written consecutively. +- Different groups (O-01) are separated by one blank line. +- Enum members are not separated by blank lines, even when they have documentation comments. +- Types are separated by one blank line. + +```csharp +public sealed class Viewport +{ + private const int C_MIN_SIZE = 16; + private const int C_MAX_SIZE = 16384; + + private readonly RenderTarget m_target; + private int m_width; + private int m_height; + + /// + /// Gets the current width in pixels. + /// + public int width => m_width; + + /// + /// Gets the current height in pixels. + /// + public int height => m_height; + + internal bool isDirty { get; set; } + internal int generation { get; set; } +} +``` + +Avoid: + +```csharp +public sealed class Viewport +{ + private const int C_MIN_SIZE = 16; + + private const int C_MAX_SIZE = 16384; + private readonly RenderTarget m_target; + /// + /// Gets the current width in pixels. + /// + public int width => m_width; + internal bool isDirty { get; set; } + +} +``` + +### S-04 Blank lines inside method bodies + +- Separate processing phases (validation, preparation, execution, completion) with one blank line. Do not add blank lines mechanically. +- The argument validation at the start of a method (a run of `ThrowIf*` calls and guards) is contiguous and followed by one blank line. +- A local function is preceded by one blank line and placed at the end of the method body. +- No blank line follows an opening brace or precedes a closing brace. Never leave two consecutive blank lines. + +```csharp +public AssetHandle Import( + string path, + ImportOptions options +) { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + ArgumentNullException.ThrowIfNull(options); + ObjectDisposedException.ThrowIf(m_disposed, this); + + AssetSource source = OpenSource(path); + ImportPlan plan = BuildPlan(source, options); + + AssetHandle handle = Execute(plan); + m_handles.Add(handle.id, handle); + return handle; + + ImportPlan BuildPlan( + AssetSource target, + ImportOptions settings + ) => new(target, settings); +} +``` + +Avoid: + +```csharp +public AssetHandle Import( + string path, + ImportOptions options +) { + + ArgumentException.ThrowIfNullOrWhiteSpace(path); + + ArgumentNullException.ThrowIfNull(options); + AssetSource source = OpenSource(path); + + + return Execute(BuildPlan(source, options)); + +} +``` + +## 12. Types and expression idioms + +### E-01 Local variables state their type; `var` only with `new T(...)` + +- A local variable declares its type: `T x = expression;`. +- Use `var` when the right-hand side is `new T(...)` or `new T[...]`, where the type is visible on the same line. +- An anonymous type requires `var`. +- A local variable does not use `T x = new(...)`; that form is for fields and properties (M-04). +- A collection expression needs a target type, so the declaration states it: `List names = [];`. + +```csharp +AssetEntry entry = m_entries[index]; +int count = entry.dependencies.Count; +string name = entry.displayName; +var builder = new StringBuilder(capacity); +var buffer = new byte[C_BUFFER_SIZE]; +List names = []; +var projection = new { entry.id, entry.displayName }; +``` + +Avoid: + +```csharp +var entry = m_entries[index]; +var count = entry.dependencies.Count; +StringBuilder builder = new(capacity); +StringBuilder other = new StringBuilder(capacity); +``` + +### E-02 `foreach`, `for`, `using`, `out` and deconstruction state their types + +```csharp +foreach (AssetEntry entry in m_entries) +{ + Visit(entry); +} + +foreach ((string key, AssetEntry value) in m_byName) +{ + Visit(value); +} + +for (int i = 0; i < count; i++) +{ + Visit(m_entries[i]); +} + +using Stream stream = lease.OpenRead(); + +if (m_byName.TryGetValue(name, out AssetEntry? found)) +{ + Visit(found); +} +``` + +Avoid: + +```csharp +foreach (var entry in m_entries) +{ + Visit(entry); +} + +using var stream = lease.OpenRead(); + +if (m_byName.TryGetValue(name, out var found)) +{ + Visit(found); +} +``` + +### E-03 Built-in types use keywords + +Write `int`, `string`, `float`, `object`, `nint` and `nuint`, not `Int32`, `String`, `IntPtr` or `UIntPtr`. Access static members through the keyword as well. + +```csharp +nint handle = nint.Zero; +bool empty = string.IsNullOrWhiteSpace(name); +float largest = float.MaxValue; +``` + +Avoid: + +```csharp +IntPtr handle = IntPtr.Zero; +bool empty = String.IsNullOrWhiteSpace(name); +Single largest = Single.MaxValue; +``` + +### E-04 Null checks use patterns + +Use `is null` and `is not null`. Use `is { } x` or `is T x` to test and capture at once. Do not write `== null` or `!= null`. + +```csharp +if (m_source is null) return; + +if (m_owner is not null) +{ + m_owner.Release(); +} + +if (TryFind(id) is { } entry) +{ + Visit(entry); +} +``` + +Avoid: + +```csharp +if (m_source == null) return; + +if (!(m_owner is null)) +{ + m_owner.Release(); +} +``` + +### E-05 Argument validation + +Validation comes first in a method, in parameter order, and uses the `ThrowIf*` helpers. Do not write `?? throw new ArgumentNullException(...)`. + +```csharp +public Viewport( + RenderTarget target, + string name, + int width +) { + ArgumentNullException.ThrowIfNull(target); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + + m_target = target; + m_width = width; + this.name = name; +} +``` + +Avoid: + +```csharp +public Viewport( + RenderTarget target, + string name +) { + m_target = target ?? throw new ArgumentNullException(nameof(target)); + if (name == null) + { + throw new ArgumentNullException("name"); + } +} +``` + +### E-06 Object creation + +- A local variable: `var x = new T(...)` (E-01). +- A field or property initializer: `= new(...)` (M-04). +- A member that directly returns a new object of its declared return type may use `new(...)`. +- An argument, or a creation inside a larger expression, writes the type: `new T(...)`. + +```csharp +public static Color FromBytes( + byte r, + byte g, + byte b +) => new(r / 255f, g / 255f, b / 255f); +``` + +```csharp +var item = new RenderItem(mesh, material); +queue.Enqueue(new RenderItem(mesh, material)); +``` + +Avoid: + +```csharp +RenderItem item = new(mesh, material); +queue.Enqueue(new(mesh, material)); +``` + +### E-07 Common values + +| Meaning | Write | Not | +| --- | --- | --- | +| Empty string | `string.Empty` | `""` | +| Default value | `default` | `default(T)`, unless the type cannot be inferred | +| Empty collection | `[]` | `new List()`, `Array.Empty()` | +| Negation | `!ready` | `ready == false` | +| Non-nullable `bool` test | `if (ready)` | `if (ready == true)` | +| Nullable `bool?` test | `if (flag == true)` | `if (flag ?? false)` | +| Conversion | `(T)value` | `value as T` without a following null check | +| Type test with capture | `value is T typed` | `as` followed by a null check | +| Delegate invocation | `handler?.Invoke(args)` | a null check followed by a call | +| Rethrow | `throw;` | `throw exception;` | +| Infinite loop | `while (true)` | `for (;;)` | +| Current time | `DateTime.UtcNow`, `DateTimeOffset.UtcNow` | `DateTime.Now` | + +```csharp +string label = string.Empty; +Color color = default; +flushed?.Invoke(); +if (value is AssetEntry typed) +{ + Visit(typed); +} +``` + +Avoid: + +```csharp +string label = ""; +Color color = default(Color); +if (flushed != null) +{ + flushed.Invoke(); +} + +AssetEntry typed = value as AssetEntry; +if (typed != null) +{ + Visit(typed); +} +``` + +### E-08 `this.` + +- Inside a constructor, every assignment to an instance member that is not an `m_` field goes through `this.`: `this.name = name;`, `this.count = 0;`. This holds whether or not a parameter has the same name. +- Outside constructors, do not write `this.` unless it is needed to disambiguate. +- Apart from constructor parameters, a parameter or local variable does not take the name of a property of the same type. + +```csharp +public GameBuildPackageContext( + BuildProfile profile, + string outputDirectory +) { + m_createdUtc = DateTime.UtcNow; + this.profile = profile; + this.outputDirectory = outputDirectory; + this.isIncremental = true; +} + +public BuildProfile profile { get; } +public string outputDirectory { get; } +public bool isIncremental { get; private set; } + +public string Describe() => $"{profile.name} -> {outputDirectory}"; +``` + +Avoid (`isIncremental` assigned without `this.` in the constructor, `this.` outside the constructor): + +```csharp +public GameBuildPackageContext( + BuildProfile profile, + string outputDirectory +) { + this.profile = profile; + this.outputDirectory = outputDirectory; + isIncremental = true; +} + +public string Describe() => $"{this.profile.name} -> {this.outputDirectory}"; +``` + +### E-09 Strings + +- Build strings from values with interpolation, `$"..."`. Do not use `string.Format` or `string.Concat`. +- Split a long message with `+` at the start of the continuation line (W-01). Use a raw string literal, `"""`, for multi-line text. +- Comparison, lookup, sorting and dictionaries state `StringComparison.Ordinal` / `StringComparer.Ordinal` or the `OrdinalIgnoreCase` variants. +- Change case with `ToLowerInvariant()` / `ToUpperInvariant()` and format with `CultureInfo.InvariantCulture`. +- Refer to identifiers with `nameof(...)`. +- Test external input with `string.IsNullOrWhiteSpace`, and use `string.IsNullOrEmpty` only when whitespace is meaningful. + +```csharp +string message = $"The asset '{path}' could not be imported: {reason}"; +bool same = string.Equals(left, right, StringComparison.Ordinal); +var index = new Dictionary(StringComparer.OrdinalIgnoreCase); +throw new ArgumentException("The path must be relative.", nameof(path)); +``` + +Avoid: + +```csharp +string message = string.Format("The asset '{0}' could not be imported: {1}", path, reason); +bool same = left.ToLower() == right.ToLower(); +throw new ArgumentException("The path must be relative.", "path"); +``` + +### E-10 Numeric literals + +- `float`: write an integral value as `1f` and a fractional value as `1.5f`. Do not write `1.0f` or `1.50f`. +- Suffixes: `f`, `d`, `m` and `u` are lower case; `L` and `UL` are upper case. +- Hexadecimal: the `0x` prefix is lower case, the digits are upper case, and long values are grouped by four digits with `_`. +- Large decimal values are grouped by three digits with `_`. + +```csharp +float half = 0.5f; +float one = 1f; +uint mask = 0xFF00_00FFu; +long ticks = 10_000_000L; +``` + +Avoid: + +```csharp +float one = 1.0f; +float ratio = 1.50f; +uint mask = 0xff0000ffU; +long ticks = 10000000l; +``` + +### E-11 Lambdas + +- One parameter has no parentheses: `x => ...`. No parameters: `() => ...`. Two or more parameters are expanded (P-01). +- Parameters have meaningful names. An unused parameter is `_`. +- A lambda that captures neither a local variable nor `this` is `static`. +- A single-expression body uses the expression form; several statements use a block (B-04). +- When an expression body does not fit on the line of the lambda, it is wrapped in parentheses, unless it is a call or object creation, which breaks inside its own parentheses (B-04). +- Do not use anonymous methods (`delegate { }`). + +```csharp +entries.RemoveAll(static entry => entry.isMissing); +entries.RemoveAll(entry => entry.generation < m_generation); +button.clicked += () => m_log.Info("Clicked."); + +Func isStale = entry => ( + entry.lastWriteTimeUtc < threshold && !entry.isPinned +); +``` + +Avoid: + +```csharp +entries.RemoveAll((entry) => entry.isMissing); +entries.RemoveAll(x => x.isMissing); + +Func isStale = entry => + entry.lastWriteTimeUtc < threshold && !entry.isPinned; +``` + +### E-12 `using` declarations + +Use a `using` declaration when the resource lives until the end of the enclosing block. Use a `using` statement with a block only when the resource must be released earlier. + +```csharp +using Stream stream = lease.OpenRead(); +using var reader = new StreamReader(stream); +return reader.ReadToEnd(); +``` + +Avoid (a block that ends where the method ends): + +```csharp +using (Stream stream = lease.OpenRead()) +{ + using (var reader = new StreamReader(stream)) + { + return reader.ReadToEnd(); + } +} +``` + +## 13. Control flow, exceptions and asynchronous code + +### X-01 Guard clauses return early + +Handle invalid and boundary cases first and leave with `return`, `throw` or `continue`. The main path is not nested inside `else`. Guards may use the compact form of B-05. + +```csharp +public void Draw(RenderItem item) +{ + if (m_disposed) return; + if (!item.isVisible) return; + + Submit(item); + m_drawn++; +} +``` + +Avoid: + +```csharp +public void Draw(RenderItem item) +{ + if (!m_disposed) + { + if (item.isVisible) + { + Submit(item); + m_drawn++; + } + } +} +``` + +### X-02 `switch` + +- Use a `switch` expression to map a value to a value (I-04). +- Use a `switch` statement when the branches execute statements. `case` is indented four spaces from `switch`, and the statements four spaces from `case`. Each label is on its own line. `default` is last. Add braces to a section only when it declares local variables that would otherwise collide. + +```csharp +switch (command.kind) +{ + case CommandKind.Draw: + case CommandKind.DrawIndexed: + Submit(command); + break; + case CommandKind.Clear: + Clear(command.color); + break; + default: + throw new InvalidOperationException($"Unknown command kind '{command.kind}'."); +} +``` + +Avoid: + +```csharp +switch (command.kind) +{ +case CommandKind.Draw: case CommandKind.DrawIndexed: + Submit(command); break; +default: throw new InvalidOperationException($"Unknown command kind '{command.kind}'."); +case CommandKind.Clear: + Clear(command.color); + break; +} +``` + +### X-03 Exception types and messages + +| Situation | Exception | +| --- | --- | +| An argument is `null` | `ArgumentNullException`, through `ThrowIfNull` | +| An argument value is invalid | `ArgumentException`, `ArgumentOutOfRangeException` | +| The object state does not allow the operation | `InvalidOperationException` | +| The object has been disposed | `ObjectDisposedException`, through `ThrowIf` | +| Input data is malformed | `InvalidDataException` | +| The platform or backend does not support the operation | `NotSupportedException` | + +A message is a complete English sentence that includes the offending value. Parameter names use `nameof`. A `throw` whose arguments do not fit on one line breaks like any other call (A-02). + +```csharp +throw new InvalidDataException( + $"The scene file '{path}' declares version {version}, but only version {C_VERSION} is supported." +); +``` + +Avoid: + +```csharp +throw new InvalidDataException( + $"The scene file '{path}' declares version {version}, but only version {C_VERSION} is supported."); + +throw new Exception("bad version"); +``` + +### X-04 `catch` + +- Catch the specific type that can be handled. When catching `Exception`, filter with `when` or rethrow with `throw;` after handling. +- The variable is named `exception` by default. A name that states the role, such as `cleanupFailure`, is allowed when the exception is stored or aggregated. Omit the variable when it is not used. +- A bare `catch` without a type is only for "clean up, then rethrow". +- A `catch` block that deliberately ignores an exception contains a comment that says why. + +```csharp +try +{ + Directory.Delete(scratch, recursive: true); +} +catch (IOException) +{ + // The scratch directory is retried by the next retirement pass. +} + +try +{ + Publish(candidate); +} +catch (Exception exception) when (exception is not OperationCanceledException) +{ + m_log.Error($"Publication failed: {exception.Message}"); + throw; +} +``` + +Avoid: + +```csharp +try +{ + Directory.Delete(scratch, recursive: true); +} +catch {} + +try +{ + Publish(candidate); +} +catch (Exception ex) +{ + throw ex; +} +``` + +### X-05 Asynchronous code + +- Return `Task` or `ValueTask`. Never write `async void`. +- The method name ends with `Async` (NM-04). `CancellationToken cancellationToken` is the last parameter and is passed down to every asynchronous call. +- In product code (`src`, `build`, `backends`, `platforms`, `tools`, `entry`) every `await` ends with `.ConfigureAwait(false)`. Test code does not use `ConfigureAwait`. +- Do not block on asynchronous results with `.Wait()`, `.Result` or `.GetAwaiter().GetResult()`. An entry point that must wait synchronously carries a comment that explains why. +- On a broken `await` call, `.ConfigureAwait(false)` follows the closing parenthesis on its line. + +```csharp +public async Task LoadAsync( + AssetID id, + CancellationToken cancellationToken +) { + await using Stream stream = await m_storage.OpenAsync(id, cancellationToken).ConfigureAwait(false); + return await m_reader.ReadAsync( + stream, + id, + cancellationToken + ).ConfigureAwait(false); +} +``` + +Avoid: + +```csharp +public async void Load(AssetID id) +{ + Stream stream = m_storage.OpenAsync(id, CancellationToken.None).Result; + await m_reader.ReadAsync(stream, id, CancellationToken.None); +} +``` + +## 14. Comments and XML documentation + +### D-01 Which members need XML documentation + +Every externally visible public member, and every protected member that an external type can override, has complete English XML documentation. Important internal APIs are documented as well. Private members and test code do not need documentation. + +```csharp +/// +/// Stores render items until the next flush. +/// +public sealed class RenderQueue +{ + private readonly List m_items = []; + + /// + /// Gets the number of queued items. + /// + public int count => m_items.Count; + + private void Trim() => m_items.TrimExcess(); +} +``` + +Avoid (a public type and a public property without documentation): + +```csharp +public sealed class RenderQueue +{ + public int count => m_items.Count; +} +``` + +### D-02 Tags are expanded, one element per block + +- The start tag, the content and the end tag are on separate lines. `///` is followed by one space. A documentation block has no empty `///` lines. +- Tag order: `summary`, `typeparam`, `param` (in signature order), `returns`, `exception`, `remarks`. +- Every content block starts with a capital letter and ends with a period. +- Wrap long content at complete semantic boundaries. + +```csharp +/// +/// Resolves a loaded asset by its persistent identity. +/// +/// +/// The asset type expected by the caller. +/// +/// +/// The persistent identity of the asset. +/// +/// +/// Receives the asset when this method returns ; +/// otherwise . +/// +/// +/// when the asset is loaded and has the requested type; +/// otherwise . +/// +/// +/// The loader has been disposed. +/// +public bool TryResolve( + AssetID id, + [NotNullWhen(true)] out TAsset? asset +) where TAsset : class +{ + ObjectDisposedException.ThrowIf(m_disposed, this); + return TryResolveCore(id, out asset); +} +``` + +Avoid: + +```csharp +/// Resolves an asset +/// the asset +/// the id +/// true if found +public bool TryResolve( + AssetID id, + [NotNullWhen(true)] out TAsset? asset +) where TAsset : class +{ + ObjectDisposedException.ThrowIf(m_disposed, this); + return TryResolveCore(id, out asset); +} +``` + +### D-03 Wording of summaries + +| Member | Starts with | Example | +| --- | --- | --- | +| Read-only property | `Gets` | `Gets the current width in pixels.` | +| Writable property | `Gets or sets` | `Gets or sets the clear color.` | +| `bool` property | `Gets a value indicating whether` | `Gets a value indicating whether the asset is missing.` | +| Method | A third-person verb | `Creates`, `Releases`, `Determines whether`, `Attempts to` | +| Constructor | `Initializes a new instance of` or `Creates` | `Creates a dispatcher bound to the given hub.` | +| Type | A third-person verb or a noun phrase | `Identifies`, `Describes`, `Provides`, `Represents` | +| Event | `Occurs when` | `Occurs when the platform requests a redraw.` | + +A summary describes real behavior. It does not restate the member name. + +```csharp +/// +/// Gets the current width of the viewport in pixels. +/// +public int width => m_width; +``` + +Avoid: + +```csharp +/// +/// The width. +/// +public int width => m_width; +``` + +### D-04 References inside documentation + +- A type or member: ``. A parameter: ``. A type parameter: ``. +- A keyword: ``, ``, ``. +- A self-closing tag has no space before `/>`. +- An override or interface implementation uses `/// ` and documents any additional constraint locally with `remarks` or `exception`. + +```csharp +/// +public override string ToString() => name; +``` + +Avoid: + +```csharp +/// +/// Returns null if id is not found. See AssetLoader. +/// +/// +public override string ToString() => name; +``` + +### D-05 `//` comments + +- A comment explains a reason, a constraint, ownership or a lifetime. It does not restate the code. +- A comment is on its own line, above the code it explains, at the indentation of that code. Do not write trailing comments. +- `//` is followed by one space. The comment is a complete English sentence that starts with a capital letter and ends with a period. + +```csharp +// The native window must outlive the swap chain, so it is released last. +m_swapChain.Dispose(); +m_window.Dispose(); +``` + +Avoid: + +```csharp +m_swapChain.Dispose(); // dispose swap chain +//release window +m_window.Dispose(); +``` + +### D-06 Prohibited comments and directives + +- Comments in any language other than English. +- `TODO`, `FIXME` or `HACK` markers left in place indefinitely. +- Commented-out code. +- Separator lines, banner comments and `/* */` block comments. +- `#region` and `#endregion`. +- `#nullable` inside a file, and `#pragma warning disable` without a comment that states the reason. + +`#if`, `#elif`, `#else` and `#endif` start at column 0. Conditional symbols are UPPER_SNAKE with the `INNO_` prefix, except `DEBUG`. + +```csharp +#if INNO_HOST_WINDOWS_X64 + private const string C_LIBRARY_NAME = "bgfx.dll"; +#elif INNO_HOST_MACOS_ARM64 + private const string C_LIBRARY_NAME = "libbgfx.dylib"; +#endif +``` + +Avoid: + +```csharp +#region Constants + // ---------- library ---------- + // TODO: revisit + // private const string C_OLD_NAME = "bgfx_old.dll"; + private const string C_LIBRARY_NAME = "bgfx.dll"; /* windows */ +#endregion +``` + +## 15. Tests + +### TS-01 Structure + +- Tests use xUnit. A test class is `public sealed class XxxTests` in `XxxTests.cs`, in the namespace of the test project. +- A test method is `public`, returns `void` or `async Task`, and carries `[Fact]`, or `[Theory]` with `[InlineData]`. +- Test classes and test methods do not need XML documentation. +- Fixtures and test doubles follow the same naming and layout rules as product code. A nested test double is `private sealed` and placed at the end of the test class. + +```csharp +using System; +using Xunit; +using Inno.Core.Events; + +namespace Inno.Core.Events.Tests; + +public sealed class EventDispatcherTests +{ + [Fact] + public void NewDispatcherHasNoSinks() + { + var dispatcher = new EventDispatcher(); + + Assert.Empty(dispatcher.sinks); + } + + private sealed class RecordingSink : IEventSink + { + public int published { get; private set; } + + public void Publish(EventRecord record) => published++; + } +} +``` + +Avoid: + +```csharp +public class EventDispatcherTest +{ + [Fact] + void NewDispatcherHasNoSinks() {} +} +``` + +### TS-02 Test method names + +A test method name is a PascalCase statement of what happens under which condition. It has no underscores, no `Async` suffix and no `Test` prefix or suffix. + +```csharp +public sealed class EventDispatcherTests +{ + [Fact] + public void DispatchAfterDisposeThrowsObjectDisposedException() + { + var dispatcher = new EventDispatcher(); + dispatcher.Dispose(); + + Assert.Throws(() => dispatcher.Dispatch(new EventRecord())); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void NonPositiveCapacityIsRejected(int capacity) + => Assert.Throws(() => new EventDispatcher(capacity)); + + [Fact] + public async Task PendingEventsAreDeliveredBeforeShutdownCompletes() + { + var dispatcher = new EventDispatcher(); + List received = []; + dispatcher.dispatched += received.Add; + + dispatcher.Dispatch(new EventRecord()); + await dispatcher.ShutdownAsync(CancellationToken.None); + + Assert.Single(received); + } +} +``` + +Avoid: + +```csharp +public sealed class EventDispatcherTests +{ + [Fact] + public void Dispatch_AfterDispose_Throws() + { + var dispatcher = new EventDispatcher(); + dispatcher.Dispose(); + } + + [Fact] + public async Task TestShutdownAsync() + { + var dispatcher = new EventDispatcher(); + await dispatcher.ShutdownAsync(CancellationToken.None).ConfigureAwait(false); + } +} +``` + +### TS-03 Assertions and layout + +- Separate the arrange, act and assert phases with one blank line. A very short test may omit the separation. +- `Assert.Equal(expected, actual)`: the expected value comes first. +- Source text used as test data (generator inputs and expected outputs) is data, not code; this rulebook does not apply to it. + +```csharp +[Fact] +public void ResizeUpdatesBothDimensions() +{ + var viewport = new Viewport(m_target, "Main", 640); + + viewport.Resize(width: 1280, height: 720); + + Assert.Equal(1280, viewport.width); + Assert.Equal(720, viewport.height); +} +``` + +Avoid (actual value first, phases not separated): + +```csharp +[Fact] +public void ResizeUpdatesBothDimensions() +{ + var viewport = new Viewport(m_target, "Main", 640); + viewport.Resize(width: 1280, height: 720); + Assert.Equal(viewport.width, 1280); +} +``` + +## 16. Exceptions + +The following cases follow an external contract. Do not rename or reformat them to satisfy this rulebook. + +| Case | What it keeps | Example | +| --- | --- | --- | +| Generated code and third-party sources | Everything | `extern/`, `**/Generated/*.cs`, `` files | +| MSBuild task parameters | PascalCase property names bound by MSBuild | `public string OutputPath { get; set; }` | +| Overrides and interface implementations | The name declared by the base type or interface | `Stream.CanRead`, `IEnumerator.Current` | +| Special CLR members | Names required by the language or runtime | operators, `GetEnumerator`, `Deconstruct`, `Dispose` | +| Native interop signatures | Field names, enum values and imported function names from the native header | `SDL_Event`, bgfx enums | +| Serialized wire names | The serialized name; source property names and wire names are declared separately | | +| Third-party product names | The spelling used by the product | `RmlUi`, `ImGui`, `MiniAudio` | +| Keyboard and input code enums | Single-letter and digit members | `KeyCode.A`, `KeyCode.F1` | +| Numeric matrices and lookup tables | Several elements per line, column alignment (S-02) | a 4×4 matrix literal | +| Unsplittable string literals | Length beyond the line width (F-04) | paths, URLs | +| Generator templates and their tests | `global::` and fully qualified names required by the generation protocol | | +| Source text used as test data | Its own formatting (TS-03) | | + +Keep each exception as small as possible: it covers the name or the layout bound by the contract, and the rest of the file follows the rulebook. + +## 17. Reference example + +One file that applies the rules together. + +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Core.Identity; + +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; + +namespace Inno.Assets.Pipeline; + +/// +/// Caches loaded assets and reloads them when their sources change. +/// +public sealed class AssetCache : IDisposable +{ + private const int C_INITIAL_CAPACITY = 64; + private const int C_MAX_ATTEMPT_COUNT = 3; + + private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromMilliseconds(50); + + private readonly Dictionary m_entries = new(C_INITIAL_CAPACITY); + private readonly IAssetStore m_store; + private readonly ILogSink m_log; + private int m_generation; + private bool m_disposed; + + /// + /// Creates a cache that reads asset content from the given store. + /// + /// + /// The store that provides asset content. + /// + /// + /// The sink that receives reload diagnostics. + /// + /// + /// The diagnostic name of the cache. + /// + /// + /// is empty or consists only of white space. + /// + public AssetCache( + IAssetStore store, + ILogSink log, + string name + ) { + ArgumentNullException.ThrowIfNull(store); + ArgumentNullException.ThrowIfNull(log); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + + m_store = store; + m_log = log; + this.name = name; + this.isEnabled = true; + } + + /// + /// Gets the diagnostic name of the cache. + /// + public string name { get; } + + /// + /// Gets a value indicating whether the cache accepts source changes. + /// + public bool isEnabled { get; private set; } + + /// + /// Gets the number of cached assets. + /// + public int count => m_entries.Count; + + /// + /// Occurs when a cached asset has been reloaded from its source. + /// + public event Action? assetReloaded; + + /// + /// Attempts to find a cached asset that is still current. + /// + /// + /// The persistent identity of the asset. + /// + /// + /// Receives the cached handle when this method returns ; + /// otherwise . + /// + /// + /// when a current entry exists; otherwise . + /// + public bool TryResolve( + AssetID id, + [NotNullWhen(true)] out AssetHandle? handle + ) { + ObjectDisposedException.ThrowIf(m_disposed, this); + + if (m_entries.TryGetValue(id, out Entry? entry) + && entry.generation == m_generation + && !entry.handle.isMissing + ) { + handle = entry.handle; + return true; + } + + handle = null; + return false; + } + + /// + /// Loads an asset, reusing the cached handle when it is still current. + /// + /// + /// The persistent identity of the asset. + /// + /// + /// A token that cancels the load. + /// + /// + /// The loaded asset handle. + /// + /// + /// The store could not provide the asset after every attempt. + /// + public async Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ) { + if (TryResolve(id, out AssetHandle? cached)) return cached; + + for (int attempt = 1; attempt <= C_MAX_ATTEMPT_COUNT; attempt++) + { + try + { + AssetHandle handle = await m_store.LoadAsync(id, cancellationToken).ConfigureAwait(false); + m_entries[id] = new Entry(handle, m_generation); + return handle; + } + catch (IOException exception) when (attempt < C_MAX_ATTEMPT_COUNT) + { + m_log.Warning($"Loading asset '{id}' failed on attempt {attempt}: {exception.Message}"); + await Task.Delay(RETRY_DELAY, cancellationToken).ConfigureAwait(false); + } + } + + throw new InvalidDataException( + $"The asset '{id}' could not be loaded from store '{m_store.name}' after {C_MAX_ATTEMPT_COUNT} attempts." + ); + } + + /// + /// Applies source changes and invalidates the affected entries. + /// + /// + /// The source changes reported by the watcher. + /// + public void ApplySourceChanges(IReadOnlyList changes) + { + ArgumentNullException.ThrowIfNull(changes); + if (!isEnabled) return; + + m_generation++; + foreach (AssetEvent change in changes) + { + if (!m_store.TryGetID(change.path, out AssetID id)) continue; + + string action = change.change switch + { + WatcherChangeTypes.Deleted => "removed", + WatcherChangeTypes.Renamed => "renamed", + _ => "changed" + }; + m_log.Info($"Asset '{id}' was {action}."); + + m_entries.Remove(id); + assetReloaded?.Invoke(id); + } + } + + /// + public void Dispose() + { + if (m_disposed) return; + + // Entries only borrow their handles, so the store releases the content. + m_entries.Clear(); + m_disposed = true; + } + + internal bool IsCurrent(AssetID id) + => m_entries.TryGetValue(id, out Entry? entry) + && entry.generation == m_generation; + + private sealed record Entry( + AssetHandle handle, + int generation + ); +} +``` From 5f306daa9a40f7442a57ecbf6f6097c40b0965fa Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 13:27:09 +0000 Subject: [PATCH 02/33] docs(rules): register the C# code style rulebook and tidy agent guidance Register every chapter of the C# code style rulebook as a complete unit and route C# paths to it. Replace the coding clauses it supersedes through recorded amendments. Keep the documentation CI note in one workflow, index every decision and acceptance record, and point the Docs authority link at the published main branch. --- .agents/records/acceptance/README.md | 52 ++- .../decisions/CSHARP_STYLE_RULEBOOK.md | 43 ++ .agents/records/decisions/README.md | 10 + .agents/rulebook/README.md | 3 +- .agents/rulebook/coding.md | 16 +- .agents/rulebook/coverage.json | 397 +++++++++++++++++- .agents/rulebook/csharp-style.md | 54 +++ .agents/skills/inno-api-docs/SKILL.md | 2 +- .agents/skills/inno-change/SKILL.md | 2 - .agents/skills/inno-delivery/SKILL.md | 2 - .agents/skills/inno-verify/SKILL.md | 2 - 11 files changed, 548 insertions(+), 35 deletions(-) create mode 100644 .agents/records/decisions/CSHARP_STYLE_RULEBOOK.md diff --git a/.agents/records/acceptance/README.md b/.agents/records/acceptance/README.md index 0d488c646..385c96a38 100644 --- a/.agents/records/acceptance/README.md +++ b/.agents/records/acceptance/README.md @@ -1,36 +1,37 @@ # Acceptance records -- [CI/CD test ownership](cicd-test-migration.md) and [CI/CD performance](cicd-performance.md): test ownership, hosted certification and matched latency measurements. +[Records](../README.md) · [Open work](../open-items.md) · [Current acceptance](../acceptance/current.md) + +Each record establishes only its stated inputs, commit, environment and execution scope. Historical passes do not certify current inputs. Preserve original attachment bytes; the migration inventory separately identifies historical attachment links unavailable from Git. +Start from [current acceptance](current.md). Data files, probes and attachment directories sit beside the record that cites them. + +## Summarized records + +- [CI/CD test ownership](cicd-test-migration.md) and [CI/CD performance](cicd-performance.md): test ownership, hosted certification and matched latency measurements. - [Source certificate normalization](SOURCE_CERTIFICATE_NORMALIZATION_2026_11_13.md): real aggregate memory failure, shared input tables, exact input preservation and bounded imports. - [Full matrix and actual draft release](FULL_MATRIX_AND_DRAFT_RELEASE_2026_11_13.md): both extended platform jobs, ten warm samples, 1,000-cycle product journeys, exact-artifact draft upload and protected cleanup. - - [Script example receipt integration](CI_43191512147.md): 334 successful macOS checks followed by a reproduced report-format failure, real compiler/receipt regression and strict surface identities. - - [Documentation input compatibility](DOCUMENTATION_INPUT_COMPATIBILITY_2026_11_12.md): per-owner source/example provenance, authenticated baseline import, precise compatibility rejection and current query observations. - - [Static validation ownership and rule-source batching](STATIC_VALIDATION_SCOPE_2026_11_12.md): shared discovery, preserved conservative fallbacks, actual rule-loading samples and hosted Docs projection results. - - [Windows success and macOS follow-up](CI_43164720103.md): actual platform results, physical temporary roots, target-scoped examples and the remaining incremental certification gap. - - [Independent documentation merge gate](DOCUMENTATION_PAIRING_GATE_2026_11_12.md): exact merged Docs evidence, candidate-race rejection and explicit protected activation prerequisites. - - [Windows CI diagnosis and follow-up](CI_43067538817.md): real passing workloads, metadata/script failures, read-only capture, test scope and external setup. - - [Explicit documentation source certificates](DOCUMENTATION_SOURCE_CERTIFICATES_2026_11_12.md): authenticated preparation, complete reference coverage, read-only evidence and observed test latency. - - [Documentation publication receipts](DOCUMENTATION_PUBLICATION_RECEIPTS_2026_11_12.md): reconciled source/content correspondence for artifact-only promotion. - [Missing source capture execution](CI_MISSING_REFERENCE_CAPTURE_2026_11_12.md): independent execution, prepared capture and retained blocked certification. - [Canonical documentation cutover](DOCUMENTATION_LEGACY_CUTOVER_2026_11_12.md): physical legacy removal and preserved regression responsibilities. - -[Records](../README.md) · [Open work](../open-items.md) · [Current acceptance](../acceptance/current.md) - - [Logo, default font icons and attribution](LOGO_BRANDING_2026_11_07.md): outlined icons, v2 artwork and removal of embedded images; current and original evidence are recorded separately. - -Each record establishes only its stated inputs, commit, environment and execution scope. Historical passes do not certify current inputs. Preserve original attachment bytes; the migration inventory separately identifies historical attachment links unavailable from Git. - - [English migration CI candidate 42934085309](CI_42934085309.md): actual macOS failures, partial passing evidence, timing attribution and Windows runner communication loss. +- [Previous documentation and agent information-architecture acceptance](DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md) +## Index + +- [AI_PIPELINE_CI_CLOSURE_2026_11_06.md](AI_PIPELINE_CI_CLOSURE_2026_11_06.md) +- [API_DRAFT_PIPELINE_2026_11_13.md](API_DRAFT_PIPELINE_2026_11_13.md) +- [API_ELEMENT_PAGES_2026_11_14.md](API_ELEMENT_PAGES_2026_11_14.md) +- [API_GENERIC_NAMES_2026_11_14.md](API_GENERIC_NAMES_2026_11_14.md) +- [API_READING_LAYOUT_2026_11_14.md](API_READING_LAYOUT_2026_11_14.md) - [ARCHITECTURE_BGCS_CORE_REUSE_2026_10_21.md](ARCHITECTURE_BGCS_CORE_REUSE_2026_10_21.md) - [ATOMIC_FILE_PUBLICATION_ACCEPTANCE_2026_10_29.md](ATOMIC_FILE_PUBLICATION_ACCEPTANCE_2026_10_29.md) - [BGCS301_BROWSER_AGGREGATE_ABI.md](BGCS301_BROWSER_AGGREGATE_ABI.md) @@ -42,10 +43,24 @@ Each record establishes only its stated inputs, commit, environment and executio - [BUILD_COST_TOOL_HOST_DISK_CLOSURE_ACCEPTANCE.md](BUILD_COST_TOOL_HOST_DISK_CLOSURE_ACCEPTANCE.md) - [BUILD_ENTRY_CACHE_WIKI_REFINEMENT_ACCEPTANCE.md](BUILD_ENTRY_CACHE_WIKI_REFINEMENT_ACCEPTANCE.md) - [BUILD_ENTRY_CACHE_WIKI_REMEDIATION_2026_10_12.md](BUILD_ENTRY_CACHE_WIKI_REMEDIATION_2026_10_12.md) +- [CI_DOCUMENTATION_CANDIDATES_2026_11_11.md](CI_DOCUMENTATION_CANDIDATES_2026_11_11.md) +- [CI_NATIVE_PREFLIGHT_2026_11_11.md](CI_NATIVE_PREFLIGHT_2026_11_11.md) +- [CI_SHARED_DOCUMENTATION_CONTEXT_2026_11_12.md](CI_SHARED_DOCUMENTATION_CONTEXT_2026_11_12.md) - [CURRENT_ARCHITECTURE_REVIEW_2026_10_12.md](CURRENT_ARCHITECTURE_REVIEW_2026_10_12.md) - [CURRENT_ENGINE_OPEN_ITEMS_2026_10_15.md](CURRENT_ENGINE_OPEN_ITEMS_2026_10_15.md) - [CURRENT_FRAMEWORK_REVIEW_2026_10_14.md](CURRENT_FRAMEWORK_REVIEW_2026_10_14.md) - [DISK_CLEANUP_20261013.md](DISK_CLEANUP_20261013.md) +- [DOCUMENTATION_API_PREREQUISITES_2026_11_11.md](DOCUMENTATION_API_PREREQUISITES_2026_11_11.md) +- [DOCUMENTATION_DISPOSITIONS_2026_11_11.md](DOCUMENTATION_DISPOSITIONS_2026_11_11.md) +- [DOCUMENTATION_EVIDENCE_RELAY_2026_11_12.md](DOCUMENTATION_EVIDENCE_RELAY_2026_11_12.md) +- [DOCUMENTATION_EXAMPLE_EVIDENCE_2026_11_12.md](DOCUMENTATION_EXAMPLE_EVIDENCE_2026_11_12.md) +- [DOCUMENTATION_HISTORY_PRESERVATION_2026_11_11.md](DOCUMENTATION_HISTORY_PRESERVATION_2026_11_11.md) +- [DOCUMENTATION_QUERY_PREPARATION.md](DOCUMENTATION_QUERY_PREPARATION.md) +- [DOCUMENTATION_REFERENCE_SNAPSHOTS_2026_11_11.md](DOCUMENTATION_REFERENCE_SNAPSHOTS_2026_11_11.md) +- [DOCUMENTATION_RULE_AUTHORITY_2026_11_12.md](DOCUMENTATION_RULE_AUTHORITY_2026_11_12.md) +- [DOCUMENTATION_SCRIPT_SURFACES_2026_11_13.md](DOCUMENTATION_SCRIPT_SURFACES_2026_11_13.md) +- [DOCUMENTATION_SOURCE_COMPARISON_2026_11_11.md](DOCUMENTATION_SOURCE_COMPARISON_2026_11_11.md) +- [DOCUMENTATION_WRITER_CONCURRENCY.md](DOCUMENTATION_WRITER_CONCURRENCY.md) - [EDITOR_DEFAULT_LAYOUT_ACCEPTANCE_2026_10_29.md](EDITOR_DEFAULT_LAYOUT_ACCEPTANCE_2026_10_29.md) - [EDITOR_UI_ACCEPTANCE_2026_10_27.md](EDITOR_UI_ACCEPTANCE_2026_10_27.md) - [EDITOR_UI_CAPTURE_TAIL_ACCEPTANCE_2026_10_30.md](EDITOR_UI_CAPTURE_TAIL_ACCEPTANCE_2026_10_30.md) @@ -57,6 +72,7 @@ Each record establishes only its stated inputs, commit, environment and executio - [EDITOR_UI_SCRIPT_PUBLICATION_ACCEPTANCE_2026_10_30.md](EDITOR_UI_SCRIPT_PUBLICATION_ACCEPTANCE_2026_10_30.md) - [EDITOR_UI_SNAPSHOT_ACCEPTANCE_2026_10_29.md](EDITOR_UI_SNAPSHOT_ACCEPTANCE_2026_10_29.md) - [ENTRY_PROJECT_BUILD_SIMPLIFICATION_ACCEPTANCE.md](ENTRY_PROJECT_BUILD_SIMPLIFICATION_ACCEPTANCE.md) +- [EXTERNAL_DOCUMENTATION_VALIDATION_2026_11_11.md](EXTERNAL_DOCUMENTATION_VALIDATION_2026_11_11.md) - [FINAL_PLATFORM_RELOAD_NUGET_ACCEPTANCE.md](FINAL_PLATFORM_RELOAD_NUGET_ACCEPTANCE.md) - [FULL_ENGINE_AUDIT_2026_10_24.md](FULL_ENGINE_AUDIT_2026_10_24.md) - [ISSUE58_DYNAMIC_MODAL_ACCEPTANCE.md](ISSUE58_DYNAMIC_MODAL_ACCEPTANCE.md) @@ -70,13 +86,13 @@ Each record establishes only its stated inputs, commit, environment and executio - [NET10_BGCS3_PROGRESS_2026_10_20.md](NET10_BGCS3_PROGRESS_2026_10_20.md) - [NET10_CSHARP14.md](NET10_CSHARP14.md) - [NET10_NON_BGCS_ACCEPTANCE_2026_10_18.md](NET10_NON_BGCS_ACCEPTANCE_2026_10_18.md) +- [OWNED_CACHE_RETIREMENT_2026_11_11.md](OWNED_CACHE_RETIREMENT_2026_11_11.md) - [PLATFORM_OWNERSHIP_CACHE_ACCEPTANCE_2026_10_22.md](PLATFORM_OWNERSHIP_CACHE_ACCEPTANCE_2026_10_22.md) - [PLATFORM_OWNERSHIP_CACHE_FILE_TREE_2026_10_22.md](PLATFORM_OWNERSHIP_CACHE_FILE_TREE_2026_10_22.md) - [PLUGIN_EVENTS_IDENTITY_ACCEPTANCE_2026_10_22.md](PLUGIN_EVENTS_IDENTITY_ACCEPTANCE_2026_10_22.md) +- [PR83_DOCUMENTATION_SCOPE_2026_11_16.md](PR83_DOCUMENTATION_SCOPE_2026_11_16.md) - [PRIORITY_FIX_ACCEPTANCE_2026_10_25.md](PRIORITY_FIX_ACCEPTANCE_2026_10_25.md) - [REPOSITORY_HYGIENE_ACCEPTANCE_2026_10_25.md](REPOSITORY_HYGIENE_ACCEPTANCE_2026_10_25.md) - [STANDARD_NUGET_RESTORE_ACCEPTANCE_2026_10_26.md](STANDARD_NUGET_RESTORE_ACCEPTANCE_2026_10_26.md) +- [VALIDATION_PROGRESS_2026_11_11.md](VALIDATION_PROGRESS_2026_11_11.md) - [WINDOWS_VULKAN_EXIT_FAILURE_2026_10_20.md](WINDOWS_VULKAN_EXIT_FAILURE_2026_10_20.md) -- [current.md](current.md) - -- [Previous documentation and agent information-architecture acceptance](DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md) diff --git a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md new file mode 100644 index 000000000..cd4b26902 --- /dev/null +++ b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md @@ -0,0 +1,43 @@ +# C# code style rulebook + +[Decisions](README.md) · [Rule authority](../../rulebook/csharp-style.md) + +The user reviewed a complete audit of the handwritten C# source, revised the proposed rules on 2026-11-21 and approved one detailed style authority for humans and agents. The [C# code style rulebook](../../rulebook/csharp-style.md) is that authority for names and layout. The [coding rules](../../rulebook/coding.md) keep design, error-handling, resource and change-management requirements. + +## Registration + +The rulebook is a new authority, not a translation. Its complete text was committed first; the rule registry pins the preface and each chapter to that immutable source revision by section index and hash. Every chapter is one complete unit below the staged-read budget, and `.cs` paths select all of them. + +Changing a rule requires committing the new chapter text, then updating that unit's `source` and `sourceHash` in the registry. Updating a hash without a committed source is not a rule change. + +## Approved replacements + +These clauses of the existing coding rules contradicted the approved rulebook. Each replacement is a substantive amendment, not a translation. Original source hashes and translation mappings remain unchanged in the registry; one amendment hash binds each active line to this decision. + +| Unit | Replaced clause | Active clause | Rule | +| --- | --- | --- | --- | +| `naming` | Namespaces match the directory hierarchy by default. | A namespace equals the assembly name of its owning project; directories add no segments. | N-02 | +| `naming` | Constants use `C_` or clearly meaningful readonly static names. | Constants use `C_`; static readonly fields use unprefixed UPPER_SNAKE. | NM-07, NM-08 | +| `csharp-standard-1` | Namespaces follow their owning directory or project convention. | Namespaces follow their owning project. | N-02 | +| `csharp-standard-2` | Example `targetId`. | Example `targetID`. | NM-13 | +| `csharp-standard-2` | Static readonly members use clear semantic names such as `DefaultOptions`. | Static readonly fields use unprefixed UPPER_SNAKE such as `DEFAULT_OPTIONS`. | NM-08 | +| `csharp-standard-4` | Example parameter `commandId` (three lines). | Example parameter `commandID`. | NM-13 | + +All other clauses of those units remain in force. Where a general clause and a rulebook rule cover the same subject, the rulebook rule is the detailed form. + +## Interpretations + +The rulebook resolves these points where the approved revisions allowed more than one reading: + +- Conditional-expression continuations align with the condition; call-chain continuations indent four spaces. +- Every empty method, constructor and lambda body is `{}`; property patterns keep `{ }`. +- A multi-line header of `if`, `for`, `foreach`, `while`, `using`, `lock` and `fixed` closes with `) {`. +- Only an `if` without `else` whose statement fits on the same line may omit braces. +- Additional `where` clauses align with the first. +- A multi-line collection expression may open with `[` directly before its first element. +- Two-letter acronyms are lowercase at the start of a camelCase name and uppercase elsewhere. +- Column alignment is recommended from four consecutive declarations of one type. + +## Consequences + +Existing source does not yet conform. Formatting and renaming are separate, later changes: formatting-only changes preserve syntax tokens, and acronym or field renames that touch public members are API changes. `.editorconfig` and the style validator still express the previous static-readonly naming and must follow the rulebook before they are used as gates. diff --git a/.agents/records/decisions/README.md b/.agents/records/decisions/README.md index 2ecab0349..3a0270b6f 100644 --- a/.agents/records/decisions/README.md +++ b/.agents/records/decisions/README.md @@ -4,4 +4,14 @@ Record durable reasons, constraints and tradeoffs, with links to the current authoritative mechanism. Ordinary style adjustments, mechanical moves and local fixes do not require decision records. Move superseded designs to history rather than duplicating them as current rules. +## Rule authority + - [English rule preservation](ENGLISH_RULE_PRESERVATION.md): original rule identities, clause correspondence, reviewed meaning and explicitly approved ownership/language changes. +- [C# code style rulebook](CSHARP_STYLE_RULEBOOK.md): the detailed style authority, its registration and the coding clauses it replaced. +- [Root test ownership](ROOT_TEST_OWNERSHIP.md): one root tests boundary replacing backend-local test ownership. + +## Documentation and API + +- [API draft rule amendment](API_DRAFT_RULE_AMENDMENT.md) with its [clause changes](API_DRAFT_RULE_CHANGES.json): the draft/main API workflow. +- [API author metadata rule amendment](API_AUTHOR_METADATA_RULE_AMENDMENT.md) with its [clause changes](API_AUTHOR_METADATA_RULE_CHANGES.json): named prose ownership per API element. +- [API scope clause changes](API_SCOPE_RULE_CHANGES.json): the Engine API ownership boundary. diff --git a/.agents/rulebook/README.md b/.agents/rulebook/README.md index 023edeba5..af43ed42e 100644 --- a/.agents/rulebook/README.md +++ b/.agents/rulebook/README.md @@ -10,7 +10,8 @@ Behavior tags describe the work: for example, `new-boundary`, `public-api`, `own | --- | --- | | Architecture, boundaries, reuse and project ownership | [Architecture](architecture.md) | | Naming, XML, formatting, exceptions and concurrency | [Coding](coding.md) | -| Documentation, API, examples and content ownership | [Docs authority](https://github.com/Wolfiora/InnoEngine.Docs/blob/docs-modernization/.agents/rulebook/documentation.md); load with an explicit `-DocsRoot` | +| C# names, layout, line breaks and idioms, with examples | [C# code style](csharp-style.md) | +| Documentation, API, examples and content ownership | [Docs authority](https://github.com/Wolfiora/InnoEngine.Docs/blob/main/.agents/rulebook/documentation.md) on `main`, the published branch; [`draft`](https://github.com/Wolfiora/InnoEngine.Docs/blob/draft/.agents/rulebook/documentation.md) holds unpublished changes. Load with an explicit `-DocsRoot` | | Tests, compilation, completion and review | [Validation](validation.md) | | Commits, PRs and notifications | [Delivery](delivery.md) | | Editor | [Editor](domains/editor.md) | diff --git a/.agents/rulebook/coding.md b/.agents/rulebook/coding.md index d88269b74..84ed0b5bc 100644 --- a/.agents/rulebook/coding.md +++ b/.agents/rulebook/coding.md @@ -6,12 +6,12 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena ## 2. Naming - Match filenames to their primary type. -- By default, match namespaces to directory hierarchy. `src/composition/editor` uses the project-level namespace rules in section 13. +- A namespace equals the assembly name of its owning project; directories inside a project do not add namespace segments. `src/composition/editor` uses the project-level namespace rules in section 13. - Use PascalCase for type names. - Prefix interfaces with I. - Use meaningful camelCase for member parameters. - Prefix private fields with m_. -- Constants use a C_ prefix, such as C_MAX_COUNT, or clearly meaningful readonly static names. +- Constants use a C_ prefix, such as C_MAX_COUNT. Static readonly fields use UPPER_SNAKE names without a prefix, such as DEFAULT_OPTIONS. - Keep existing Unity-style API names, such as transform, scene, active and name, consistent with surrounding code. @@ -97,7 +97,7 @@ These requirements apply to handwritten C# source. Generated code and third-part ## 1. Design and responsibility - Prioritize architectural clarity, dependency direction, ownership, encapsulation and low coupling. -- Match filenames to primary types. Directories express independently understandable capabilities; namespaces follow their owning directory or project convention. +- Match filenames to primary types. Directories express independently understandable capabilities; namespaces follow their owning project. - Public APIs expose the smallest complete contracts needed for external composition. Prefer composition and supply dependencies through constructor parameters or explicit composition entries. - Check existing repository events, identity, serialization, mathematics and diagnostics first. Reuse them and avoid parallel management systems. - Interfaces or base classes express extension behavior; immutable discovery metadata is declared once. Replaceable boundaries isolate platforms, storage, compilers and presentation. @@ -115,10 +115,10 @@ These requirements apply to handwritten C# source. Generated code and third-part | --- | --- | --- | | Types, methods, enum members | PascalCase | GenerationRequest, TryResolve, Borrowed | | Interfaces | I prefix | IOutputTransaction | -| Properties, parameters, locals | camelCase | targetId, outputDirectory | +| Properties, parameters, locals | camelCase | targetID, outputDirectory | | Private fields | m_ prefix | m_generation | | Constants | C_ prefix | C_MAX_COUNT | -| Static readonly members | Clear semantic names | DefaultOptions | +| Static readonly fields | UPPER_SNAKE without a prefix | DEFAULT_OPTIONS | - External interface implementations, overrides, special CLR members and external protocol signatures follow their contracts. - The corresponding generator configuration declares generated binding names. @@ -154,12 +154,12 @@ internal sealed class CommandSet private readonly Dictionary m_commands = new(StringComparer.Ordinal); internal void Register( - string commandId, + string commandID, Action command ) { - ArgumentException.ThrowIfNullOrWhiteSpace(commandId); + ArgumentException.ThrowIfNullOrWhiteSpace(commandID); ArgumentNullException.ThrowIfNull(command); - m_commands.Add(commandId, command); + m_commands.Add(commandID, command); } } ``` diff --git a/.agents/rulebook/coverage.json b/.agents/rulebook/coverage.json index 40f1aec7c..6f4c7fea2 100644 --- a/.agents/rulebook/coverage.json +++ b/.agents/rulebook/coverage.json @@ -3122,6 +3122,22 @@ "sourceHash": "779100086672741a3bd94e2b881aa35d8217edd739afdd017731e3983cff3a3f", "targetHash": "aa807bb8015d7800fe77d0bada936898d50c066e8adb761d41f493812f0c4453" } + ], + "amendments": [ + { + "ordinal": 3, + "previousHash": "93840a0814cc3a178726e86b61586d956121c64a4d595b91a60420ed80470b3b", + "currentHash": "d4f1f0c0003033b2daa7ef05b263d0cd3942ae18da7e97f075cebb6930495b3d", + "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", + "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" + }, + { + "ordinal": 8, + "previousHash": "91ea145a10ba903fb71233bc29bc0a1edff9378d31569b1b5cc5e889e041a351", + "currentHash": "6e1c308fcb9476541b9d05ec0e1d1229bf66412bf8729f1c0fdea297e2a49821", + "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", + "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" + } ] } }, @@ -4862,6 +4878,15 @@ "sourceHash": "36132fa3b63f3460abdb38ffba3fa44c161e713f1778bc7098b5035f0d0d4979", "targetHash": "76828e0fe061b761c00c0afee82e308909dc0a93a5dc7fc75218d37362c2b61b" } + ], + "amendments": [ + { + "ordinal": 3, + "previousHash": "805254701ebf725180887414b642cf5e776d5259d41745703749de26000d1622", + "currentHash": "e15f9052327e9ba5e8a73585e66062b5c9f6220a36e24773d0ded57db77f3ce0", + "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", + "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" + } ] } }, @@ -4949,6 +4974,22 @@ "sourceHash": "f664f1d02435ef0cc33073dc7e99243f89fa35f277f14670d35d1d1fa60652bd", "targetHash": "326a3d166f7f239af5e4343769a8bd7cdc16df6eaba52a089ed215e726ead1f4" } + ], + "amendments": [ + { + "ordinal": 6, + "previousHash": "56d0aaa53ebcc644f9ff8e3084a166d11bab6d2d309f039f6d2845eec14c08d5", + "currentHash": "d63742aef216fbb6640f07b4e2ec5c944bced33774d352a95ed47d1807f758ef", + "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", + "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" + }, + { + "ordinal": 9, + "previousHash": "516b102cbcd19e64756bad14c8f563fbdee107f8603527b1a32fac07a90781a0", + "currentHash": "5dd04a005b5b03678533a5a5f6bc198c9412255b28c0b6d0cc15ec5a85c27c36", + "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", + "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" + } ] } }, @@ -5123,6 +5164,29 @@ "sourceHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5", "targetHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5" } + ], + "amendments": [ + { + "ordinal": 16, + "previousHash": "1939dcba42b25000ce9c4da51afabcfe974a692854c93acdd82e049643e1537b", + "currentHash": "76a70ad6442ba71c8cf0285318dca9eee29ae4de77ac6e1e6cb65c4c0b5b5932", + "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", + "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" + }, + { + "ordinal": 19, + "previousHash": "f5303ae6a3201ea52e30701cabe7f1bb4a4a0d66c2bb299f83981c8f77ac8b54", + "currentHash": "267c6ff223c302caecd3d34911f6f80c6c6b31e20210394a1be7bf740a8bb92a", + "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", + "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" + }, + { + "ordinal": 21, + "previousHash": "e0ac073295c3369afb71ba1437a0357153a4216453a8014091267b720f7370b7", + "currentHash": "33c9de50e08ac72e31c6772dc9ddec81e5e3c706a57238e97ebde48d8b881403", + "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", + "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" + } ] } }, @@ -5611,6 +5675,319 @@ ] } }, + { + "id": "csharp-style", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 0, + "sourceHash": "dd9d051caac7083966bc9ac53561090a4c65d96f318edba0038ec4018cdbc86a", + "requires": [], + "paths": [], + "tags": [ + "csharp-style" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-files", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-files", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 1, + "sourceHash": "db7b9649a9e34ed2cd39f3ba1711a6aa66c1ed8a7a6a16854243721b4a895f4e", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style", + "formatting" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-namespaces", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-namespaces", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 2, + "sourceHash": "79c4f4fe907c212d1adde45f51a17c774e07107203b218757b34b63957f25b82", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-naming", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-naming", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 3, + "sourceHash": "7d43b7e400d26ede576e0077137e93555403cea369c0edcfcbf42cf2a279856a", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style", + "naming" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-types", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-types", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 4, + "sourceHash": "ec8201e76922cd821115e9842f216140a258ba74b869d1a9cb07077e25b8bff9", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-members", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-members", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 5, + "sourceHash": "2e289b06e2175c79774465dbe0192069172307d7ae128962ff9a4e2a81ad27af", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-member-order", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-member-order", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 6, + "sourceHash": "b6faf59f653f2ae7ff4bc6e1d782313e6950f49c498d8a207febadc92df8152c", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style", + "members" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-braces", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-braces", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 7, + "sourceHash": "53e32f3e52a0e98fe9056a1546441db560105aad7efd3a71f08fdaa1b3af72b7", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style", + "formatting" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-parameters", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-parameters", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 8, + "sourceHash": "57e0429afe24fd0ee80b2b08b5581c3338b4294e9d8b3a3f740dd4fe89a08e36", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style", + "formatting" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-line-breaks", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-line-breaks", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 9, + "sourceHash": "b4e2c50e733f8ff3ae98d4b2b7ca0ca27f0c520c3c0585cd131ecf411c5e7204", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style", + "formatting" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-initializers", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-initializers", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 10, + "sourceHash": "c129cc1ffac6fd3030fb27b03af8bf2eded74d1cc50b0598488d29da62f19197", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style", + "formatting" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-spacing", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-spacing", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 11, + "sourceHash": "5508d9b2b32c93600f61cb1adcdec35608156c235063a01944f27938d56560ff", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style", + "formatting" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-idioms", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-idioms", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 12, + "sourceHash": "af1a07ca4615f20c706d65877ac916071665be1085f86c8fbe0b58fbd5422dc2", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-control-flow", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-control-flow", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 13, + "sourceHash": "a6631442ed62387c7841b3ca9bc518044832a0be107569491919868c04070028", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-comments", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-comments", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 14, + "sourceHash": "5704764651ff68d88eafe37a269de30039b0d60a3f6703863188c2daf53bef3a", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style", + "xml" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-tests", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-tests", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 15, + "sourceHash": "c0fbf18f3133ed5f75bafeacbfd3da9784f00e08d0aaa32e33f80b5c939b1f43", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-exceptions", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-exceptions", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 16, + "sourceHash": "c39c03791d13c10e6b6dbd7afdc8c79006320374a95b9d3fab8635352a262cf7", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, + { + "id": "csharp-style-example", + "path": ".agents/rulebook/csharp-style.md", + "anchor": "csharp-style-example", + "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", + "sourceSection": 17, + "sourceHash": "bbbe47646a9fbf0085c7cc8f94f9e69ff7e8f91fe6b8b39458bec09e5325469a", + "requires": [ + "csharp-style" + ], + "paths": [], + "tags": [ + "csharp-style" + ], + "reviewer": "implementing owner", + "check": "full source section preservation + semantic review" + }, { "id": "documentation-standard-0", "path": ".agents/rulebook/documentation.md", @@ -6460,7 +6837,25 @@ "csharp-standard-0", "csharp-standard-5", "csharp-standard-8", - "csharp-standard-9" + "csharp-standard-9", + "csharp-style", + "csharp-style-files", + "csharp-style-namespaces", + "csharp-style-naming", + "csharp-style-types", + "csharp-style-members", + "csharp-style-member-order", + "csharp-style-braces", + "csharp-style-parameters", + "csharp-style-line-breaks", + "csharp-style-initializers", + "csharp-style-spacing", + "csharp-style-idioms", + "csharp-style-control-flow", + "csharp-style-comments", + "csharp-style-tests", + "csharp-style-exceptions", + "csharp-style-example" ] }, { diff --git a/.agents/rulebook/csharp-style.md b/.agents/rulebook/csharp-style.md index e1c6510dc..74f1778b4 100644 --- a/.agents/rulebook/csharp-style.md +++ b/.agents/rulebook/csharp-style.md @@ -1,3 +1,5 @@ + + # InnoEngine C# code style This rulebook defines how handwritten C# in InnoEngine is named, laid out and written. It applies to every handwritten `.cs` file in the repository, including tests and tools. Third-party sources under `extern/`, generated files (`**/Generated/*.cs` and files carrying an `` header) and the cases listed in [section 16](#16-exceptions) are out of scope. @@ -30,7 +32,10 @@ Contents 15. [Tests](#15-tests) 16. [Exceptions](#16-exceptions) 17. [Reference example](#17-reference-example) + + + ## 1. Files and physical layout ### F-01 Encoding, line endings and indentation @@ -157,7 +162,10 @@ bool changed = previous.width != current.width || previous.height != current.height || previous.format != current.format; ``` + + + ## 2. Namespaces and using directives ### N-01 File-scoped namespaces @@ -317,7 +325,10 @@ Avoid (the alias repeats the target name, and a second alias names the same targ using Sdl3Window = Inno.Adapter.Platform.Sdl3.Sdl3Window; using Window = Inno.Adapter.Platform.Sdl3.Sdl3Window; ``` + + + ## 3. Naming ### Summary @@ -696,7 +707,10 @@ public sealed class JSONAssetWriter public AssetId GetId(string ID) => m_ids[ID]; } ``` + + + ## 4. Type declarations ### T-01 Write every access modifier @@ -927,7 +941,10 @@ public sealed class AssetCache private readonly Dictionary m_entries = []; } ``` + + + ## 5. Member declarations ### M-01 Property forms @@ -1116,7 +1133,10 @@ public void DisposeIsIdempotent() [SerializableProperty()] public float speed { get; set; } ``` + + + ## 6. Member order ### O-01 Group order @@ -1236,7 +1256,10 @@ public void Draw( m_drawn++; } ``` + + + ## 7. Braces and blocks ### B-01 Braces are on their own lines @@ -1629,7 +1652,10 @@ switch (key) x = 0; y = 0; ``` + + + ## 8. Parameter and argument lists ### P-01 Parameter lists: one line for zero or one parameter, fully expanded for two or more @@ -1919,7 +1945,10 @@ Avoid: window.Resize(width : 1280, height:720); texture.Update(true, false, 0, 4); ``` + + + ## 9. Line breaks ### W-01 Binary operators lead the continuation line @@ -2058,7 +2087,10 @@ if (capabilities != EditorViewportNavigationCapabilities.None && !SupportsMode(capabilities, defaultMode)) throw new ArgumentException("The default mode is not supported.", nameof(defaultMode)); ``` + + + ## 10. Initializers and collections ### I-01 Object initializers @@ -2205,7 +2237,10 @@ public enum ToneMapping Aces, } ``` + + + ## 11. Spacing and blank lines ### S-01 Spaces @@ -2386,7 +2421,10 @@ public AssetHandle Import( } ``` + + + ## 12. Types and expression idioms ### E-01 Local variables state their type; `var` only with `new T(...)` @@ -2747,7 +2785,10 @@ using (Stream stream = lease.OpenRead()) } } ``` + + + ## 13. Control flow, exceptions and asynchronous code ### X-01 Guard clauses return early @@ -2921,7 +2962,10 @@ public async void Load(AssetID id) await m_reader.ReadAsync(stream, id, CancellationToken.None); } ``` + + + ## 14. Comments and XML documentation ### D-01 Which members need XML documentation @@ -3110,7 +3154,10 @@ Avoid: private const string C_LIBRARY_NAME = "bgfx.dll"; /* windows */ #endregion ``` + + + ## 15. Tests ### TS-01 Structure @@ -3244,7 +3291,10 @@ public void ResizeUpdatesBothDimensions() Assert.Equal(viewport.width, 1280); } ``` + + + ## 16. Exceptions The following cases follow an external contract. Do not rename or reformat them to satisfy this rulebook. @@ -3265,7 +3315,10 @@ The following cases follow an external contract. Do not rename or reformat them | Source text used as test data | Its own formatting (TS-03) | | Keep each exception as small as possible: it covers the name or the layout bound by the contract, and the rest of the file follows the rulebook. + + + ## 17. Reference example One file that applies the rules together. @@ -3471,3 +3524,4 @@ public sealed class AssetCache : IDisposable ); } ``` + diff --git a/.agents/skills/inno-api-docs/SKILL.md b/.agents/skills/inno-api-docs/SKILL.md index 918faedfc..8d3fb98fc 100644 --- a/.agents/skills/inno-api-docs/SKILL.md +++ b/.agents/skills/inno-api-docs/SKILL.md @@ -3,7 +3,7 @@ name: inno-api-docs description: Maintain InnoEngine design, usage, API XML and examples against actual public and protected contracts. --- -Select applicable `wiki` and `xml` units through the rule loader with `-DocsRoot `. The [documentation rules](https://github.com/Wolfiora/InnoEngine.Docs/blob/draft/.agents/rulebook/documentation.md) have one authority in that checkout. Read its additional writing and presentation rules when editing authored content. Engine declarations and XML remain in the engine; narrative content belongs to Docs. +Select applicable `wiki` and `xml` units through the rule loader with `-DocsRoot `. The [documentation rules](https://github.com/Wolfiora/InnoEngine.Docs/blob/main/.agents/rulebook/documentation.md) have one authority in that checkout; `main` is published and [`draft`](https://github.com/Wolfiora/InnoEngine.Docs/blob/draft/.agents/rulebook/documentation.md) is unpublished. Read its additional writing and presentation rules when editing authored content. Engine declarations and XML remain in the engine; narrative content belongs to Docs. Use Build `docs search/read/symbol` against a prepared snapshot to locate task guidance, the authoritative project entry and exact qualified symbols. Read necessary associated contracts and explicit continuations. Search excerpts and API markers are not complete contracts or matching source verification evidence. diff --git a/.agents/skills/inno-change/SKILL.md b/.agents/skills/inno-change/SKILL.md index b4775a9bc..50d4a3307 100644 --- a/.agents/skills/inno-change/SKILL.md +++ b/.agents/skills/inno-change/SKILL.md @@ -10,5 +10,3 @@ When task guidance or an API contract is needed, select a prepared documentation Identify behavior changes, lifecycle obligations, failure rollback, required callers and finite acceptance. Reuse existing Core mechanisms. Keep task context to owners, rules, documentation/source entry points, decisions and verification reasons. Ordinary local changes do not require another whole-engine audit. Use `validate plan` for check selection; do not keep a skill-specific test list. A private presentation change still needs relevant behavior and lifecycle coverage; unrelated product obligations need an actual dependency or behavior reason. Maintain API XML in the engine; master-to-draft synchronization owns generated reference updates. Change the Docs Manual only when usage guidance changes, from its `draft` baseline. Update the existing [record](../../records/README.md) with scope, decisions, input identity, valid evidence, blockers and next action; track unrelated improvements separately. - -For documentation CI, use the Docs execution plan: ordinary draft work is incremental, a PR into main is a complete Release candidate, and main promotes only matching trusted artifacts. Inspect per-check input identities and invalidation reasons before repeating work. API preflight and owner extraction reuse do not replace engine functional acceptance. Report partial previews separately from publication evidence. diff --git a/.agents/skills/inno-delivery/SKILL.md b/.agents/skills/inno-delivery/SKILL.md index a811da138..2a7aa74a6 100644 --- a/.agents/skills/inno-delivery/SKILL.md +++ b/.agents/skills/inno-delivery/SKILL.md @@ -10,5 +10,3 @@ Reconcile the approved plan and every required result with current inputs. Disti Report API synchronization, Docs validation, manual editorial work and website deployment separately. API export tracks an exact master input; Docs can publish its already selected API version without waiting for a newer unrelated engine CI run. Draft previews never deploy. Only a human Docs `draft` to `main` merge authorizes automatic site deployment. Do not automatically merge either repository's PRs or formally publish an engine release. An authorized draft engine release uses the same verified product artifacts without rebuilding. Diagnose the first CI failure before retrying; preserve its evidence and the retry reason. Commit identity, pushes, publishing and external communication follow the delivery rules and existing user authorization. Local staged acceptance does not itself authorize a large remote matrix. Clean only owned temporary output through registered ownership and reading protections; retain useful caches, active readers and first-failure diagnostics. - -For documentation CI, use the Docs execution plan: ordinary draft work is incremental, a PR into main is a complete Release candidate, and main promotes only matching trusted artifacts. Inspect per-check input identities and invalidation reasons before repeating work. API preflight and owner extraction reuse do not replace engine functional acceptance. Report partial previews separately from publication evidence. diff --git a/.agents/skills/inno-verify/SKILL.md b/.agents/skills/inno-verify/SKILL.md index ec9ade8f7..fb7254947 100644 --- a/.agents/skills/inno-verify/SKILL.md +++ b/.agents/skills/inno-verify/SKILL.md @@ -12,5 +12,3 @@ Block work whose prerequisites failed; continue independent work when input inte Ordinary engine verification does not require a paired Docs candidate. Independent API extraction verifies complete source/XML/projection facts; Docs validation checks its selected API version and examples. `API editorial coverage` warnings are neutral and never substitute for or block these checks. Keep a tool crash, corrupt data, missing environment and an editorial reminder distinct. Write statuses, exact input identities, failure causes, fixes and outstanding evidence to the existing [acceptance record](../../records/acceptance/README.md). Respect an explicitly local acceptance boundary; retain the unexecuted matrix as outstanding work. Historical evidence is not current certification. - -For documentation CI, use the Docs execution plan: ordinary draft work is incremental, a PR into main is a complete Release candidate, and main promotes only matching trusted artifacts. Inspect per-check input identities and invalidation reasons before repeating work. API preflight and owner extraction reuse do not replace engine functional acceptance. Report partial previews separately from publication evidence. From 5689aaa4749a18166aface990010ef3ec8fc06e3 Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 13:52:16 +0000 Subject: [PATCH 03/33] docs(rules): require a human to vouch for every commit --- .agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md | 11 +++++++++++ .agents/records/decisions/README.md | 4 ++++ .agents/rulebook/coverage.json | 9 +++++++++ .agents/rulebook/delivery.md | 2 +- 4 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 .agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md diff --git a/.agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md b/.agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md new file mode 100644 index 000000000..cb7900c23 --- /dev/null +++ b/.agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md @@ -0,0 +1,11 @@ +# Human commit attribution + +[Decisions](README.md) · [Rule authority](../../rulebook/delivery.md#delivery) + +On 2026-11-21 the user replaced the delivery clause that named one person as the required Git author and committer. The requirement is a principle, not an identity: a human vouches for every commit. + +The active clause requires the Git author and committer to be the human contributor responsible for the commit, and forbids any agent, bot or application identity as author, committer, `Co-authored-by` or any other attribution. It applies to every contributor and every tool, so the rule no longer needs to change when contributors do. + +This is a substantive approved amendment, not an English translation. The original source hash and translation mapping remain unchanged in the rule registry; one amendment hash binds the active wording to this decision. The requirement to create pull requests with the GitHub account authorized by the user, and all other delivery obligations, remain in force. + +An agent whose environment adds its own attribution does not commit; it hands the change to an environment that commits solely in the responsible human's name. diff --git a/.agents/records/decisions/README.md b/.agents/records/decisions/README.md index 3a0270b6f..e5911c244 100644 --- a/.agents/records/decisions/README.md +++ b/.agents/records/decisions/README.md @@ -10,6 +10,10 @@ Record durable reasons, constraints and tradeoffs, with links to the current aut - [C# code style rulebook](CSHARP_STYLE_RULEBOOK.md): the detailed style authority, its registration and the coding clauses it replaced. - [Root test ownership](ROOT_TEST_OWNERSHIP.md): one root tests boundary replacing backend-local test ownership. +## Delivery + +- [Human commit attribution](HUMAN_COMMIT_ATTRIBUTION.md): a human vouches for every commit; no agent, bot or application attribution. + ## Documentation and API - [API draft rule amendment](API_DRAFT_RULE_AMENDMENT.md) with its [clause changes](API_DRAFT_RULE_CHANGES.json): the draft/main API workflow. diff --git a/.agents/rulebook/coverage.json b/.agents/rulebook/coverage.json index 6f4c7fea2..91e7ae060 100644 --- a/.agents/rulebook/coverage.json +++ b/.agents/rulebook/coverage.json @@ -3830,6 +3830,15 @@ "sourceHash": "de6a01673254e95d66beda0153ba848d3f808fb9e3164e41d4561dfe6d07aed2", "targetHash": "faacd093eb7499bf0665183a078ed48662b8b4e6e81a754b834705c231dc08c4" } + ], + "amendments": [ + { + "ordinal": 5, + "previousHash": "4c4fefa0ee638f7972f8c844c775cb7271426e48aa62cff4424e65448f1286e8", + "currentHash": "b9af9afc94393f7f1d5f2a036e4581c37537d7f7ced82986b4228978817ec4f0", + "approval": "Explicit user instruction, 2026-11-21: a human vouches for every commit; no agent or application attribution", + "review": ".agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md" + } ] } }, diff --git a/.agents/rulebook/delivery.md b/.agents/rulebook/delivery.md index b96c5e3ae..ef23bdd80 100644 --- a/.agents/rulebook/delivery.md +++ b/.agents/rulebook/delivery.md @@ -9,7 +9,7 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - When creating or updating a repository issue or pull request, use a `type(scope): description` title. Both the title and body must be entirely in English. - Issues must distinguish reproduced defects from risks awaiting verification, and state the responsible owner, reproduction conditions, actual result, expected result and executable acceptance criteria. Search existing issues before submission to avoid duplicates. - Pull request bodies must explain the problem, final behavior and actual verification against the complete difference from the target branch, and identify checks that were not run. Search existing PRs before creation. Never describe partial acceptance as a passed complete matrix. -- Use `Aaron Liao ` for both Git author and committer. Do not use a Codex/bot identity or add any `Co-authored-by` attribution. Create pull requests with the GitHub account authorized by the user. +- A human vouches for every commit: its Git author and committer are the human contributor responsible for it. No agent, bot or application identity may appear as author, committer, `Co-authored-by` or any other attribution. Create pull requests with the GitHub account authorized by the user. - Reproduce BGCS defects independently through public APIs and identify them explicitly. Do not modify BGCS source, packages or binaries, or manually edit generated output to bypass defects. From e06a8c541b34f16a0ea49fc1071f29d0d0924fc4 Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 15:32:05 +0000 Subject: [PATCH 04/33] refactor(rules): replace the hash registry with plain Markdown rule files Each rule file states its own paths and tags in front matter. The rule script lists the files to read and checks front matter, size limits and routing examples; it no longer needs Git history. coverage.json, line hashes, amendments and rule-unit markers are removed without an archive. The C# code style is one file per chapter, and the Editor and Build and Native domains are directories. Paths are whole-path globs instead of unanchored regular expressions. The validation planner no longer parses a registry, and the agent document validator rejects unlisted skills. --- ...ENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md | 2 +- .../decisions/CSHARP_STYLE_RULEBOOK.md | 4 +- .../decisions/HUMAN_COMMIT_ATTRIBUTION.md | 2 +- .../records/decisions/PLAIN_MARKDOWN_RULES.md | 15 + .agents/records/decisions/README.md | 1 + .agents/rulebook/README.md | 42 +- .agents/rulebook/architecture.md | 70 +- .agents/rulebook/coding.md | 112 +- .agents/rulebook/coverage.json | 8211 ----------------- .agents/rulebook/csharp-style.md | 3527 ------- .agents/rulebook/csharp-style/01-files.md | 130 + .../rulebook/csharp-style/02-namespaces.md | 163 + .agents/rulebook/csharp-style/03-naming.md | 382 + .agents/rulebook/csharp-style/04-types.md | 234 + .agents/rulebook/csharp-style/05-members.md | 192 + .../rulebook/csharp-style/06-member-order.md | 123 + .agents/rulebook/csharp-style/07-braces.md | 396 + .../rulebook/csharp-style/08-parameters.md | 293 + .../rulebook/csharp-style/09-line-breaks.md | 142 + .../rulebook/csharp-style/10-initializers.md | 150 + .agents/rulebook/csharp-style/11-spacing.md | 184 + .agents/rulebook/csharp-style/12-idioms.md | 364 + .../rulebook/csharp-style/13-control-flow.md | 177 + .agents/rulebook/csharp-style/14-comments.md | 192 + .agents/rulebook/csharp-style/15-tests.md | 137 + .../rulebook/csharp-style/16-exceptions.md | 24 + .agents/rulebook/csharp-style/17-example.md | 209 + .agents/rulebook/csharp-style/README.md | 36 + .agents/rulebook/delivery.md | 11 +- .agents/rulebook/documentation.md | 8 + .../build-native/backend-integration.md | 22 + .../rulebook/domains/build-native/hosts.md | 15 + .../platform-products.md} | 44 +- .agents/rulebook/domains/editor/projects.md | 14 + .agents/rulebook/domains/editor/state.md | 24 + .../domains/{editor.md => editor/ui.md} | 56 +- .agents/rulebook/domains/identity-reload.md | 18 +- .agents/rulebook/domains/plugins.md | 9 +- .agents/rulebook/domains/rendering.md | 12 +- .agents/rulebook/domains/scripting.md | 9 +- .agents/rulebook/no-legacy.md | 13 + .agents/rulebook/projects.md | 38 + .agents/rulebook/validation.md | 33 +- .agents/skills/inno-api-docs/SKILL.md | 2 +- .agents/skills/inno-change/SKILL.md | 2 +- .agents/skills/inno-delivery/SKILL.md | 2 +- .agents/skills/inno-verify/SKILL.md | 2 +- .gitignore | 1 - AGENTS.md | 6 +- tests/ci/Test-AgentRules.Tests.ps1 | 367 +- tests/ci/Test-AgentRules.examples.json | 20 + tests/ci/Test-AgentRules.ps1 | 378 +- .../AgentDocumentTests.cs | 14 + .../ValidationDocumentationTests.cs | 17 +- .../ValidationExecutionTests.cs | 13 +- .../AgentDocumentValidator.cs | 6 + .../ValidationCiContracts.cs | 1 + .../ValidationPlanner.cs | 46 +- 58 files changed, 4017 insertions(+), 12700 deletions(-) create mode 100644 .agents/records/decisions/PLAIN_MARKDOWN_RULES.md delete mode 100644 .agents/rulebook/coverage.json delete mode 100644 .agents/rulebook/csharp-style.md create mode 100644 .agents/rulebook/csharp-style/01-files.md create mode 100644 .agents/rulebook/csharp-style/02-namespaces.md create mode 100644 .agents/rulebook/csharp-style/03-naming.md create mode 100644 .agents/rulebook/csharp-style/04-types.md create mode 100644 .agents/rulebook/csharp-style/05-members.md create mode 100644 .agents/rulebook/csharp-style/06-member-order.md create mode 100644 .agents/rulebook/csharp-style/07-braces.md create mode 100644 .agents/rulebook/csharp-style/08-parameters.md create mode 100644 .agents/rulebook/csharp-style/09-line-breaks.md create mode 100644 .agents/rulebook/csharp-style/10-initializers.md create mode 100644 .agents/rulebook/csharp-style/11-spacing.md create mode 100644 .agents/rulebook/csharp-style/12-idioms.md create mode 100644 .agents/rulebook/csharp-style/13-control-flow.md create mode 100644 .agents/rulebook/csharp-style/14-comments.md create mode 100644 .agents/rulebook/csharp-style/15-tests.md create mode 100644 .agents/rulebook/csharp-style/16-exceptions.md create mode 100644 .agents/rulebook/csharp-style/17-example.md create mode 100644 .agents/rulebook/csharp-style/README.md create mode 100644 .agents/rulebook/documentation.md create mode 100644 .agents/rulebook/domains/build-native/backend-integration.md create mode 100644 .agents/rulebook/domains/build-native/hosts.md rename .agents/rulebook/domains/{build-native.md => build-native/platform-products.md} (51%) create mode 100644 .agents/rulebook/domains/editor/projects.md create mode 100644 .agents/rulebook/domains/editor/state.md rename .agents/rulebook/domains/{editor.md => editor/ui.md} (64%) create mode 100644 .agents/rulebook/no-legacy.md create mode 100644 .agents/rulebook/projects.md create mode 100644 tests/ci/Test-AgentRules.examples.json diff --git a/.agents/records/acceptance/DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md b/.agents/records/acceptance/DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md index d69510908..0bea1ec06 100644 --- a/.agents/records/acceptance/DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md +++ b/.agents/records/acceptance/DOCS_AGENT_INFORMATION_ARCHITECTURE_ACCEPTANCE.md @@ -7,7 +7,7 @@ - docs 保存产品设计、原理、用法、API 与使用边界;rulebook 保存修改要求;四个标准 SKILL.md 保存工作流;records 保存计划、决策和证据。 - [598 项迁移清单](../plans/docs-agent-migration.json) 覆盖全部基线文件;72 份原始附件哈希不变;[434 页审查登记](../plans/docs-agent-page-review.json) 覆盖全量分类、链接、包含和迁移发现。 - 246 个实际项目均有唯一同名入口,测试与 fixture 页统一位于 development/testing;59 个长入口按完整 API 章节拆分,Native .Api 分片仍由原入口纳入覆盖。 -- [规则登记](../../rulebook/coverage.json) 保留 241 条原规则和 26 个补充来源章节,形成 58 个完整加载单元。根 AGENTS 为 3268 字节;每阶段包含根指令并受 16 KiB 预算约束,不截断规则。 +- 规则登记(`.agents/rulebook/coverage.json`) 保留 241 条原规则和 26 个补充来源章节,形成 58 个完整加载单元。根 AGENTS 为 3268 字节;每阶段包含根指令并受 16 KiB 预算约束,不截断规则。 - 规则、skill 与记录不进入默认 docs 查询;记录修改不进入 Native 配方或全部测试的政策输入。未知可执行 Agent 输入仍保守扩大验证范围。 - 引擎运行逻辑、公开产品 API、第三方、生成绑定和相邻仓库未修改。 diff --git a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md index cd4b26902..2f11cfa4e 100644 --- a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md +++ b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md @@ -1,8 +1,8 @@ # C# code style rulebook -[Decisions](README.md) · [Rule authority](../../rulebook/csharp-style.md) +[Decisions](README.md) · [Rule authority](../../rulebook/csharp-style/README.md) -The user reviewed a complete audit of the handwritten C# source, revised the proposed rules on 2026-11-21 and approved one detailed style authority for humans and agents. The [C# code style rulebook](../../rulebook/csharp-style.md) is that authority for names and layout. The [coding rules](../../rulebook/coding.md) keep design, error-handling, resource and change-management requirements. +The user reviewed a complete audit of the handwritten C# source, revised the proposed rules on 2026-11-21 and approved one detailed style authority for humans and agents. The [C# code style rulebook](../../rulebook/csharp-style/README.md) is that authority for names and layout. The [coding rules](../../rulebook/coding.md) keep design, error-handling, resource and change-management requirements. ## Registration diff --git a/.agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md b/.agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md index cb7900c23..142c6679c 100644 --- a/.agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md +++ b/.agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md @@ -1,6 +1,6 @@ # Human commit attribution -[Decisions](README.md) · [Rule authority](../../rulebook/delivery.md#delivery) +[Decisions](README.md) · [Rule authority](../../rulebook/delivery.md) On 2026-11-21 the user replaced the delivery clause that named one person as the required Git author and committer. The requirement is a principle, not an identity: a human vouches for every commit. diff --git a/.agents/records/decisions/PLAIN_MARKDOWN_RULES.md b/.agents/records/decisions/PLAIN_MARKDOWN_RULES.md new file mode 100644 index 000000000..2d07b3b6c --- /dev/null +++ b/.agents/records/decisions/PLAIN_MARKDOWN_RULES.md @@ -0,0 +1,15 @@ +# Plain Markdown rules + +[Decisions](README.md) · [Rulebook](../../rulebook/README.md) + +On 2026-11-21 the user retired the rule registry. It was built to prove a one-time migration and translation, and it had become the mechanism for every later rule change: a changed sentence needed a registry amendment, a recomputed hash and a decision record, and a new rule file needed two commits. + +- Rules are plain Markdown. Each rule file states its own `paths` and `tags` in front matter; there is no central registry and no dependency list. +- A human merges every rule change through a pull request. That review replaces hash locking. +- `coverage.json`, its source identities, line hashes, translation mappings, amendments and approved-addition markers are removed without an archive or a compatibility path. Git history keeps them. +- The rule script selects files and checks front matter, the size limits and the routing examples. It needs no Git history and prints a file list instead of rule bodies. +- One topic per file within 16 KiB. The C# code style became one file per chapter; the Editor and Build and Native domains became directories; sections that former dependencies always loaded together now share a file. +- Paths are whole-path globs instead of unanchored regular expressions. Names such as `State` or `assets` outside their owners no longer select Editor state or identity rules. Editor state now applies to all Editor sources and tests, Editor UI to the presentation and panel directories, and identity rules also to references, extensibility reload and core identity. +- InnoEngine.Docs owns its rule files with the same front matter. The engine script reads them only from an explicit `-DocsRoot`. + +Earlier decision records describe changes in registry terms. Their rule text remains in force; the registry mechanics no longer apply. diff --git a/.agents/records/decisions/README.md b/.agents/records/decisions/README.md index e5911c244..a7f1dc623 100644 --- a/.agents/records/decisions/README.md +++ b/.agents/records/decisions/README.md @@ -6,6 +6,7 @@ Record durable reasons, constraints and tradeoffs, with links to the current aut ## Rule authority +- [Plain Markdown rules](PLAIN_MARKDOWN_RULES.md): rule files declare their own paths and tags; the hash registry is retired and a human merges every rule change. - [English rule preservation](ENGLISH_RULE_PRESERVATION.md): original rule identities, clause correspondence, reviewed meaning and explicitly approved ownership/language changes. - [C# code style rulebook](CSHARP_STYLE_RULEBOOK.md): the detailed style authority, its registration and the coding clauses it replaced. - [Root test ownership](ROOT_TEST_OWNERSHIP.md): one root tests boundary replacing backend-local test ownership. diff --git a/.agents/rulebook/README.md b/.agents/rulebook/README.md index af43ed42e..81a4fd3ff 100644 --- a/.agents/rulebook/README.md +++ b/.agents/rulebook/README.md @@ -2,29 +2,47 @@ This directory owns requirements for changing the engine. Product design, mechanisms, usage and contracts belong to [InnoEngine.Docs](https://github.com/Wolfiora/InnoEngine.Docs). Task progress and historical evidence belong to [records](../records/README.md). Humans and agents follow the same requirements. -Run `tests/ci/Test-AgentRules.ps1 -Paths -ShowInstructions` from the engine root to discover complete units. Add explicit units with `-Rules`, behavior tags with `-Behaviors`, and read stages with `-Stage`. [coverage.json](coverage.json) is the sole registry of authorities, sources, applicability and required relationships. +## Read the rules for a change -Behavior tags describe the work: for example, `new-boundary`, `public-api`, `ownership`, `serialization`, `reload`, `native`, `documentation`, `rules`, `skills`, `records` and `delivery`. Multiple paths, tags and dependencies may select one unit. Its complete body appears once with all selection reasons. +Run `pwsh tests/ci/Test-AgentRules.ps1 -Paths ` from the engine root. It lists the rule files that apply to those paths; read each listed file completely. Add `-Tags` for the kind of work and `-Rules` for a specific file. A rule ID is the file path under this directory without `.md`, for example `coding` or `csharp-style/03-naming`. -| Responsibility | Authority | +Tags describe the work: for example, `new-boundary`, `public-api`, `ownership`, `serialization`, `reload`, `native`, `documentation`, `rules`, `skills`, `records` and `delivery`. + +| Responsibility | Rules | | --- | --- | -| Architecture, boundaries, reuse and project ownership | [Architecture](architecture.md) | +| Architecture, boundaries, reuse and ownership | [Architecture](architecture.md) | +| Retired compatibility layers and schema versions | [No legacy compatibility](no-legacy.md) | +| Directories, solutions and project files | [Solutions and projects](projects.md) | | Naming, XML, formatting, exceptions and concurrency | [Coding](coding.md) | -| C# names, layout, line breaks and idioms, with examples | [C# code style](csharp-style.md) | -| Documentation, API, examples and content ownership | [Docs authority](https://github.com/Wolfiora/InnoEngine.Docs/blob/main/.agents/rulebook/documentation.md) on `main`, the published branch; [`draft`](https://github.com/Wolfiora/InnoEngine.Docs/blob/draft/.agents/rulebook/documentation.md) holds unpublished changes. Load with an explicit `-DocsRoot` | +| C# names, layout, line breaks and idioms, with examples | [C# code style](csharp-style/README.md) | +| Documentation, API, examples and content ownership | [Documentation](documentation.md), owned by InnoEngine.Docs | | Tests, compilation, completion and review | [Validation](validation.md) | | Commits, PRs and notifications | [Delivery](delivery.md) | -| Editor | [Editor](domains/editor.md) | +| Editor | [Projects](domains/editor/projects.md), [state](domains/editor/state.md) and [UI](domains/editor/ui.md) | | Identity, Missing and reload | [Identity and reload](domains/identity-reload.md) | | Scripting | [Scripting](domains/scripting.md) | | Plugins | [Plugins](domains/plugins.md) | | Rendering and frames | [Rendering](domains/rendering.md) | -| Builds, Native and platforms | [Build and Native](domains/build-native.md) | +| Builds, Native and platforms | [Hosts](domains/build-native/hosts.md), [platform products](domains/build-native/platform-products.md) and [backend integration](domains/build-native/backend-integration.md) | + +## Add or change a rule + +Rules are plain Markdown. Edit a file or add a new one, then open a pull request; a human merges it. Record a lasting decision in [decisions](../records/decisions/README.md) when its reason will matter later. -Load complete sections. Combining units into a file does not require every task to load that whole file. The checker retains all 241 original rule mappings and supplemental source requirements. Updating a target hash is not semantic preservation. +Every rule file starts with front matter that states when it applies: -English translations retain their original Git source identities and register every nonblank source/target line, including headings, examples and nested requirements. Original numbered clauses link to their English targets. The [translation review](../records/decisions/ENGLISH_RULE_PRESERVATION.md) records reviewed obligations and any interpretation. Automated coverage detects omissions and unregistered changes; the implementing owner remains responsible for semantic equivalence. Units not yet translated retain exact source-text verification. +```markdown +--- +paths: ["src/services/rendering/**", "tests/rendering/**"] +tags: [rendering] +--- +# Rendering +``` -Explicitly approved additional requirements may follow `` in an existing unit. Register the approval and the addition's SHA-256 in `approvedAddition`, using LF line endings and trimmed outer whitespace. The loader checks the original body or its reviewed translation separately, checks the addition, then emits both completely. This mechanism permits additions only; it does not authorize deleting or weakening existing rules. +- `paths` lists repository-relative globs that match the whole path. `**/` spans directories and `*` stays inside one name. Matching is case-sensitive. +- `tags` lists the work tags that select the file. +- Declare at least one of the two, each as a one-line list. +- Keep one topic per file and every file within 16 KiB. Split a larger topic into a directory. +- When routing changes, add a path that must select the file and one that must not to the [routing examples](../../tests/ci/Test-AgentRules.examples.json). -Explicit user-approved clause replacements use `translation.amendments`, each identifying the ordinal, original translated hash, new active hash, approval and decision record. Original provenance and translation mappings remain intact. The loader rejects unmapped, duplicate, altered or undocumented amendments; this mechanism does not infer approval from a hash update. +Run the script without arguments to check every rule file, the root instruction size and the routing examples. diff --git a/.agents/rulebook/architecture.md b/.agents/rulebook/architecture.md index 9ab200991..2dc4f832d 100644 --- a/.agents/rulebook/architecture.md +++ b/.agents/rulebook/architecture.md @@ -1,52 +1,18 @@ +--- +tags: [architecture, new-boundary, ownership, public-api, encapsulation, core-reuse, style] +--- # Architecture -Load complete rule units. The [registry](coverage.json) owns routing and provenance. - - - ## 1. Project style - Preserve the repository's consistent readability and extensibility. - Prioritize clear layering, explicit boundaries and low coupling. - Write all new comments in English by default, especially public API documentation. - - - ## 4. Encapsulation and responsibility - Expose the minimum necessary public API. - Prefer composition over inheritance. - Decouple through registries, factories and abstract interfaces. - - - - -## 10. Directory boundaries -- `src/foundation`: Core, extension catalogs, types and generation contracts. -- `src/content`: Assets, References, Scene and Animation. -- `src/services`: backend-neutral domain contracts and runtime services. -- `src/runtime`: Runtime, deployment, generators, Plugins and authoring-time scripting workflows. -- `src/adapters`: neutral SPIs, open Provider/Catalog contracts and Core Events input implementations. -- `backends/`: shared backend runtime, native code and build recipes; each component has one source owner. Component tests belong to `tests/backends/`. -- `platforms/`: system and SDK integration, explicit targets, thin Editor/Player entries, layouts and Support Packs. A platform must not reference another platform. -- `src/composition`: default engine, Shell, Player and Editor composition entries. -- `entry`: the two lightweight development entries and current-host routing. Other production layers must not reference it. `Inno.Packages.props` pins NuGet versions for the BGCS package family; no source-dependency entry is provided. -- `build`, `tools`, `tests`: neutral unified builds, concrete distribution registration, validation libraries and tests. All engine-owned tests, fixtures and test support belong to the root `tests` tree; upstream tests inside `extern` retain their upstream owner. Production projects must not reference test projects or test support. -- Place new files in directories matching the existing layers and responsibilities wherever possible. - - - - -## 15. No legacy compatibility or schema versions -- InnoEngine is a personal engine whose current source and current Project data evolve together. New or changed features do not support old files, schemas, fields, cache directories, namespaces, APIs or serialization layouts. Do not add fallback readers, migrations, compatibility aliases, former IDs, deprecated wrappers or dual writes for them. -- Persistence models, Attributes, Importers, Build Processors, History, Workspaces, Scenes, Prefabs, Asset metadata, Catalogs and script manifests must not introduce legacy-adaptation fields such as `version`, `schemaVersion`, `formatVersion` or `formerVersion`. When a format changes, update the current writer, reader, tests, documentation and Project data directly. Old data may be explicitly invalidated and regenerated. -- Do not reserve migration branches for hypothetical future compatibility. Only an explicit user request to import a particular old format permits a one-time converter with a clear boundary. Conversion logic must not enter normal runtime paths. -- Update all callers when deleting or refactoring an API. Do not retain old overloads, namespace facades, forwarding types or `[Obsolete]` compatibility layers unless the user explicitly requests them. -- These rules permit runtime identities required for current correctness, including TypeCache/Assembly generations, concurrency revisions, change counters, content hashes, artifact fingerprints, MVIDs, job-handle generations and strict magic/headers used only to reject damaged or incorrect input formats. They must not become mechanisms for reading multiple legacy schema generations. -- When reviewing or cleaning implementations named `version`, `legacy`, `migration`, `compatibility`, `former` or `deprecated`, first determine whether they serve only old data/APIs. If so, remove them together with their tests and documentation rather than extending them. - - - ## 21. Architecture, language frontends and third-party boundaries - Architectural clarity, dependency direction, responsibility and low coupling take precedence over every feature, performance goal and development convenience. Define the owning layer, public contracts, lifecycle and failure boundary before any feature or extension. Do not trade these for temporary direct connections, leaked implementation names, global singletons or convenient cross-layer calls. - General source assets in services and asset layers are inert text or byte carriers. Unless a language is explicitly an engine public standard, core importers, runtime services and script contracts must not parse, infer or depend on third-party syntax, or implicitly select semantics from the current backend or a filename. @@ -57,23 +23,25 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - Backend-neutral low-level public APIs for source plugins are permitted and necessary. Minimal public exposure means the smallest stable surface needed for external plugin composition, not only gameplay-level APIs. Plugin-author APIs must explicitly enter script export manifests. Backend SPIs, native bridges, concrete implementations and third-party handles remain unexported. - Explicitly define ownership and lifetimes on frame hot paths. Do not unconditionally copy all geometry, indices or texture pixels every frame, or encode the same data again for each draw command. Prefer generation-scoped stable handles, incremental resource updates/releases, persistent GPU caches, and pooled or owned buffers with explicit release protocols. Optimization must not expose unsafe borrowed native memory through public layers. - New systems and boundary changes must also update architecture-validator project classification, solution ownership, dependency rules, native-consumption rules, scripting allowlists and public documentation. They are not complete until repository architecture validation passes. - - - ## 22. Reuse foundational capabilities - Before adding events, identity, serialization, mathematics, diagnostics or other foundational capabilities, check for existing contracts in `Inno.Core`. Prefer using or wrapping them directly. Do not build parallel management systems in upper layers such as UI, Canvas or plugins. - UI and plugin event subscription, dispatch and lifetimes reuse `Inno.Core.Events`. Domains may define their own event types and adapters, but must not replace core event management with another queue, listener registry or event bus. - - - -## 26. Solutions and project files +## 1. Design and responsibility + +- Prioritize architectural clarity, dependency direction, ownership, encapsulation and low coupling. +- Match filenames to primary types. Directories express independently understandable capabilities; namespaces follow their owning project. +- Public APIs expose the smallest complete contracts needed for external composition. Prefer composition and supply dependencies through constructor parameters or explicit composition entries. +- Check existing repository events, identity, serialization, mathematics and diagnostics first. Reuse them and avoid parallel management systems. +- Interfaces or base classes express extension behavior; immutable discovery metadata is declared once. Replaceable boundaries isolate platforms, storage, compilers and presentation. +- Separate implementation from persistence protocols. Persistent data uses stable identities and neutral values; explicit lifetimes manage runtime objects, delegates and type references. +- Shared mechanisms, concrete backends, platform-system integration, product composition and build distributions each own their source. Shared mechanisms must not select concrete platforms or products. +- A build host describes only the tool execution environment. Requests explicitly select runtime target, CPU, ABI and managed deployment; do not infer them from host facts. +- One backend owns a third-party component's runtime, Native facade, binding configuration and build recipe. Platform products select them through capabilities and frozen descriptions. + +## Splitting responsibilities and changing boundaries + +Large owners may use partial files for independently understandable responsibilities, while fields, construction and the single lifecycle remain in the primary file. Move members and verify syntax tokens/order first; change behavior/performance separately. Public DTO filenames match their primary type, and closely related enums remain in the owning protocol. Do not create parallel event, identity or Undo managers merely to shorten files. -- Solution Folders represent actual architectural responsibilities. Remove empty groups containing neither valid projects nor Solution Items. Avoid unnecessary single-project wrapper groups for small project collections. -- Authored projects under `entry`, `src`, `backends`, `platforms`, `build`, `tools` and `tests` belong in the Solution, including binding-generation extensions and test fixtures. Exclude `obj`, `artifacts` and independent third-party projects in extern. A project without incoming ProjectReferences is not necessarily unused: check host entries, MSBuild tool calls and generator configuration before removing it. -- Use two-space indentation in `.csproj`, `.props` and `.targets`, blank lines between top-level responsibility blocks, one property per line in long property lists, and `/` in relative ProjectReference paths. -- Merge adjacent reference groups only when their conditions and reference visibility match. Do not reorder Imports, Properties or Targets, or change conditions, metadata or evaluation order. Preserve Editor public/implementation reference boundaries. -- Detailed rules are in `.agents/rulebook/coding.md`. After reorganization, verify valid XML, Solution project identities and configurations, then run affected builds and architecture validation. -- After phases of long builds or acceptance, clean this operation's obsolete tool snapshots, private load directories and test-browser profiles, and check free disk space. Before cleanup, verify the explicit owner, resolved absolute paths, symbolic links and active processes. Retain current artifacts and acceptance logs; do not clean user or SDK global caches. Logical sizes of hardlinked/compressed files do not establish physically reclaimed space. - +Public-contract changes update every consumer, reference visibility, script manifest, Stable ID, documentation, success/failure/boundary test and architecture gate. Record ownership, cancellation, thread affinity and final release for read streams, background tasks, snapshots, scratch, native callbacks and device resources. Performance conclusions require measurements; unmeasured values remain unknown. diff --git a/.agents/rulebook/coding.md b/.agents/rulebook/coding.md index 84ed0b5bc..7888e4bbd 100644 --- a/.agents/rulebook/coding.md +++ b/.agents/rulebook/coding.md @@ -1,9 +1,9 @@ +--- +paths: ["**/*.cs"] +tags: [naming, members, xml, errors, formatting, identity-naming, csharp-standard, public-api, ownership, documentation] +--- # Coding -Load complete rule units. The [registry](coverage.json) owns routing and provenance. - - - ## 2. Naming - Match filenames to their primary type. - A namespace equals the assembly name of its owning project; directories inside a project do not add namespace segments. `src/composition/editor` uses the project-level namespace rules in section 13. @@ -13,10 +13,7 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - Prefix private fields with m_. - Constants use a C_ prefix, such as C_MAX_COUNT. Static readonly fields use UPPER_SNAKE names without a prefix, such as DEFAULT_OPTIONS. - Keep existing Unity-style API names, such as transform, scene, active and name, consistent with surrounding code. - - - ## 3. Member organization - Group class members by access level and role, preferably near the top, in this order: 1. Constants (const / static) @@ -27,10 +24,7 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena 6. Private methods and utilities - Keep members of the same scope and type together where possible instead of scattering them through a class. - Public members come before restricted members. - - - ## 5. Comments must be English - All externally visible public members and protected members overridable by external derived types must have complete English XML documentation: - Types and members have a meaningful summary that does not merely repeat their names. @@ -42,26 +36,17 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - Also document important internal APIs when their behavioral impact warrants it. - Chinese source comments are prohibited. Avoid leaving temporary comments such as TODO indefinitely. - Complex logic may have comments written as complete, concise English sentences. - - - ## 6. Error handling - Validate arguments first: use ArgumentNullException.ThrowIfNull and clear ArgumentException messages. - Distinguish safe failure from exceptional failure. - Report explicit exception information at important boundaries. - - - ## 7. Transform and Identity naming clarity - Align with upper-layer semantics and preserve the existing API naming style. - Avoid local names that collide with properties and cause shadowing or readability conflicts. - Keep internal caches consistent after property updates; avoid the unnecessary cost of repeated complete recomputation. - - - ## 23. Source readability and formatting - Use one clear alias for the same type within a file; do not alternate facade aliases for the same call. XML documentation describes current real members. Give each member one meaningful summary and remove descriptions of deleted members. - Readability is a continuous requirement for all handwritten source in InnoEngine, Canvas and Rendering2D. Generated bindings and third-party extern source are outside manual formatting. Formatting changes must preserve execution order, initialization order, public contracts, serialized data, diagnostics and user experience. @@ -83,32 +68,11 @@ public void AAA( // Method body. } ``` - - - # C# development requirements These requirements apply to handwritten C# source. Generated code and third-party source follow their generation protocols or upstream standards. Repository domain protocols and product-publication policies are supplied by their respective architecture documents. - - - - -## 1. Design and responsibility -- Prioritize architectural clarity, dependency direction, ownership, encapsulation and low coupling. -- Match filenames to primary types. Directories express independently understandable capabilities; namespaces follow their owning project. -- Public APIs expose the smallest complete contracts needed for external composition. Prefer composition and supply dependencies through constructor parameters or explicit composition entries. -- Check existing repository events, identity, serialization, mathematics and diagnostics first. Reuse them and avoid parallel management systems. -- Interfaces or base classes express extension behavior; immutable discovery metadata is declared once. Replaceable boundaries isolate platforms, storage, compilers and presentation. -- Separate implementation from persistence protocols. Persistent data uses stable identities and neutral values; explicit lifetimes manage runtime objects, delegates and type references. -- Shared mechanisms, concrete backends, platform-system integration, product composition and build distributions each own their source. Shared mechanisms must not select concrete platforms or products. -- A build host describes only the tool execution environment. Requests explicitly select runtime target, CPU, ABI and managed deployment; do not infer them from host facts. -- One backend owns a third-party component's runtime, Native facade, binding configuration and build recipe. Platform products select them through capabilities and frozen descriptions. - - - - ## 2. Naming | Element | Rule | Examples | @@ -124,17 +88,11 @@ These requirements apply to handwritten C# source. Generated code and third-part - The corresponding generator configuration declares generated binding names. - Names convey meaning, units and ownership. Avoid abbreviations, meaningless helper names and local-variable shadowing. - Source property names and serialized wire names are declared separately. Naming refactors must not accidentally change data protocols. - - - ## 3. Member organization Group constants/static members, fields, constructors, public members, protected/internal members and private implementation in that order. Keep members of the same scope/type together and separate responsibilities with blank lines. - - - ## 4. Declarations and formatting - Keep zero/single-parameter functions and short expressions on one line when they fit a reasonable width. @@ -163,23 +121,15 @@ internal sealed class CommandSet } } ``` - - - ## 5. Using directives and compilation - Explicitly declare ordinary using directives in every file. - Global usings, implicit imports and MSBuild Using items are prohibited. - Enable nullable. Restrict unsafe code to actual interop boundaries and define buffer, pointer and resource lifetimes. - Resolve compilation targets and SDKs from project declarations. Caches do not replace correctness checks. - - - Handwritten C# must not use `global::` qualified names. Resolve conflicts with explicit ordinary using directives, clear file-level using type/namespace aliases or local renaming. Keep one alias per target rather than repeating fully qualified names at each use. Generated code, generator output templates and tests verifying that output follow their generation protocol; do not rewrite their qualified names to satisfy handwritten style rules. - - - ## 6. Documentation and comments - Source comments use English and explain reasons, constraints, ownership or lifetimes. @@ -189,10 +139,7 @@ internal sealed class CommandSet - Overrides and interface implementations may use inheritdoc; document additional constraints locally. - Template comments that merely restate names are prohibited. Use readable expanded XML tags. - XML-emitting projects treat CS1572, CS1573 and CS1591 as compilation errors. - - - ## 7. Validation, exceptions and transactions - Validate arguments first with ArgumentNullException.ThrowIfNull and clear ArgumentException messages. @@ -200,10 +147,7 @@ internal sealed class CommandSet - Fully prepare and validate candidates before atomic publication; failure retains last-good state. - Do not swallow critical exceptions, treat unsupported capabilities as success or use silent fallbacks. - API changes update current callers, documentation and tests and remove superseded paths. Format changes follow the owning product's current protocol. - - - ## 8. Resources, asynchronous work and concurrency - Identify the creator, owner, using thread, borrowing period, releaser and final release order. @@ -212,58 +156,10 @@ internal sealed class CommandSet - Callback exceptions must not cross unmanaged boundaries. After unregistration or cancellation, ensure callbacks no longer access released owners. - An explicit host manages shared process state. Avoid anonymous global state and global service locators. - Stop new work before retiring generation resources and verifying release. Preserve an explicit fault state on failure. - - - ## 9. Performance - Define hot-path caches, ownership and invalidation conditions. - Avoid per-frame complete scans, geometry/texture copies and duplicate command encoding. - Prefer incremental updates, stable handles, persistent resource caches and pooled buffers with explicit release protocols. - Do not expose borrowed native memory or expand public APIs for performance. - - - - -## 10. Tests and acceptance - -- Use real public contracts and replaceable public boundaries. -- InternalsVisibleTo, test backdoors, reflection bypasses and widening internal visibility for tests are prohibited. -- Cover real success, failure, cancellation, boundary and lifecycle behavior. Do not write tests that merely repeat the implementation. -- Native calls, AOT, trimming and platform support require actual artifact evidence. -- Report build, test, SDK, host and device status separately. Unexecuted checks are not passes. - - - - -## 11. Change management - -- Formatting-only changes preserve syntax tokens, execution order, contracts and diagnostics. -- Validate naming, responsibility and behavior changes separately from pure formatting. -- Public API, reference-boundary and generation-protocol changes also update consumers, indexes, examples and architecture checks. -- Before completion, ensure the target scope compiles and record validation commands, results and remaining limitations. - - - - -## 12. Solution and MSBuild readability - -- Solution Folders express actual responsibility layers. Remove groups without projects or valid Solution Items. Small repositories do not need extra categories wrapping single projects. -- Include all authored source projects in the Solution, including binding-generation extensions and test fixtures; exclude generated artifacts and third-party projects. Before declaring a project without incoming references obsolete, check host entries, MSBuild tool calls and generation configuration. -- Use two-space indentation and LF in `.csproj`, `.props` and `.targets`, with one blank line between top-level responsibility blocks. Do not mix tabs and spaces. -- Keep simple declarations on one line. Put long attribute lists after the element name, one attribute per line. Do not split attribute values in ways that change paths, conditions or commands. -- Use `/` in relative ProjectReference paths. Group implementation dependencies separately from public-signature dependencies according to project rules. Do not mechanically merge groups with different conditions, visibility or responsibilities. -- Remove empty PropertyGroup/ItemGroup elements with no attributes, content or comments. Merge adjacent reference groups only when conditions and visibility match and no intervening evaluation step exists. -- MSBuild evaluates in order. Formatting-only cleanup verifies property values, conditions, metadata, Imports, Targets and effective project-reference order. General XML sorting is not safe project reorganization. -- Preserve actual platform conditions and SDK/toolchain constraints. Formatting platform projects must not move those concerns into neutral business layers. - - - - -## Splitting responsibilities and changing boundaries - -Large owners may use partial files for independently understandable responsibilities, while fields, construction and the single lifecycle remain in the primary file. Move members and verify syntax tokens/order first; change behavior/performance separately. Public DTO filenames match their primary type, and closely related enums remain in the owning protocol. Do not create parallel event, identity or Undo managers merely to shorten files. - -Public-contract changes update every consumer, reference visibility, script manifest, Stable ID, documentation, success/failure/boundary test and architecture gate. Record ownership, cancellation, thread affinity and final release for read streams, background tasks, snapshots, scratch, native callbacks and device resources. Performance conclusions require measurements; unmeasured values remain unknown. - diff --git a/.agents/rulebook/coverage.json b/.agents/rulebook/coverage.json deleted file mode 100644 index 91e7ae060..000000000 --- a/.agents/rulebook/coverage.json +++ /dev/null @@ -1,8211 +0,0 @@ -{ - "baseline": "7f56dd64bd29231351f5441c18877b0c3ad3229b", - "rootBudgetBytes": 8192, - "taskBudgetBytes": 16384, - "rules": [ - { - "id": "1.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-1", - "path": ".agents/rulebook/architecture.md", - "originalHash": "0438048c6c19d09a17302f8833d072eee0bc1dbbea42ef63792c8e182acdd9b6", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "style", - "translatedHash": "619bdc60de5e116996897c86ebd06284331a38e36dec8f1362e53616f9ad7fef" - }, - { - "id": "1.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-1", - "path": ".agents/rulebook/architecture.md", - "originalHash": "7548a57f38c92debf7c5fbb29b5f477132cd9dc587bb166ecafd996d2529e745", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "style", - "translatedHash": "2acbd5f71f6e0b3a57bc47e5611f6422106ff61340977f67f89962f3a49b77a3" - }, - { - "id": "1.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-1", - "path": ".agents/rulebook/architecture.md", - "originalHash": "4c955118aec3a46bfc2136417987f168069fe06a1991534daeea48f6e032490b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "style", - "translatedHash": "99e629ab7c8595b0bb3bffb29440446cbd1b4e3a4f272d58b784a1eb0855581a" - }, - { - "id": "2.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "23ed7825005c55de7bab25a13ad15e4d6f9003fa963e9dc6c8f83f25aa156aba", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "ec60fa8773db69f2d94c5e28c5901b9ce970d29f6002af8e2da7079b5b4b0b56" - }, - { - "id": "2.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "7146fd46302f8cb642df8c5543f331a66155d896ac1e73a902b4225731cefb22", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "93840a0814cc3a178726e86b61586d956121c64a4d595b91a60420ed80470b3b" - }, - { - "id": "2.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "1254fc0af71afb409b4898cd71bc434108cda6aff826f68e79fed35a059b7a43", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "a68bfd544c316dd8bd4140f7eaa5a16ce35adb1d0d0afcc885249f509ede18b4" - }, - { - "id": "2.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "c7d1597e6822b378b28cff3f9a6360068544ad29df7f7118e736d012ffb58230", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "e65985a0124327bb5ac46f97c457fd9c8b6678a6df1abf6ed312f65deeaf708e" - }, - { - "id": "2.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "de1e8fc2ce15a3e73e3f8a940abf54b6279a7d557154acb8298b5e688b8d82b0", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "c1fb02fbe518037ebdb862c96b2a42034e86f230c99fea894caee80f23f2290f" - }, - { - "id": "2.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "00238457aa080323c071fbab13a30fba20d564883baf55386c4e2b878f67da94", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "7eb5975ceb7bb9091a8d1b602e78a93e5bd4e2406777c26d8596810568640a99" - }, - { - "id": "2.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "4dd1a89dc1b7a7b4354e70948fc01c4ae5993733201c0ff5bf7f4713a5abefcd", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "91ea145a10ba903fb71233bc29bc0a1edff9378d31569b1b5cc5e889e041a351" - }, - { - "id": "2.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-2", - "path": ".agents/rulebook/coding.md", - "originalHash": "779100086672741a3bd94e2b881aa35d8217edd739afdd017731e3983cff3a3f", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "naming", - "translatedHash": "aa807bb8015d7800fe77d0bada936898d50c066e8adb761d41f493812f0c4453" - }, - { - "id": "3.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-3", - "path": ".agents/rulebook/coding.md", - "originalHash": "155b573531fa878aa6c0186be8cb195d0df3cdcfeb74ae9ef7426d4de92344b9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "members", - "translatedHash": "fe50f60ab778c20cc0d21a6ad0822b8d1d74fb9878eca124ed11172b8171c8ee" - }, - { - "id": "3.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-3", - "path": ".agents/rulebook/coding.md", - "originalHash": "42c62c7d7814e5d5233bdf69c66252172ddb30d91cadd2d789f390959fac14ed", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "members", - "translatedHash": "84739f16c81513c858158016ff5eb127eb0a32313a8f8e08611418c8062fa91c" - }, - { - "id": "3.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-3", - "path": ".agents/rulebook/coding.md", - "originalHash": "6a0621716390e0c953ed9eed37545093931c0c1eaf280210e4c8312a6981ac9e", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "members", - "translatedHash": "26bf77b12ee406168444733e6cda0634672562df93b7fe79929b10b2572f16b4" - }, - { - "id": "4.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-4", - "path": ".agents/rulebook/architecture.md", - "originalHash": "b41c9ac4a02994caca07eae9f9f88b1a04a54588576dc83b210317d72f54f76f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "encapsulation", - "translatedHash": "61d23811216ed1dce965f002ac5cc7b1d8b9548eb5a048459f4c103a7d9f6e4e" - }, - { - "id": "4.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-4", - "path": ".agents/rulebook/architecture.md", - "originalHash": "c99a1440e54ed1f02f47977ef854a48b8e3ba1ad66f80b02acea7285a1ac5bc3", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "encapsulation", - "translatedHash": "4b9c7f47bf61bc389e0925ac64026e38a90b588f4e47155d88dea7256d216eaf" - }, - { - "id": "4.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-4", - "path": ".agents/rulebook/architecture.md", - "originalHash": "da4c375502ff67444749d190568441619c09ceecf1a2cb8afffb691b326f9bca", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "encapsulation", - "translatedHash": "31b9db7d408e5d0fcd307fd1b9574f67716e904f53a9ca7f51475058312b360a" - }, - { - "id": "5.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-5", - "path": ".agents/rulebook/coding.md", - "originalHash": "6b3170a223fbeeaa9708f03854dd47d7601bcc74996a78b9d7ec626f11fbc9d1", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "xml", - "translatedHash": "beac146b517f48ed476a18e9aa7f2fdab6820f3b4fe0541a84f7260f58c8c9d7" - }, - { - "id": "5.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-5", - "path": ".agents/rulebook/coding.md", - "originalHash": "53a79b0ffff61e3c64fadd0822b5eaf64d9d86c64f03abc4f10662923ebec648", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "xml", - "translatedHash": "2d5ddf314df4b45cfc643bbb67ee8f27f0d473a331e3430a7c21efe94762a9bf" - }, - { - "id": "5.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-5", - "path": ".agents/rulebook/coding.md", - "originalHash": "230cd76be9c06b7b0154b24b64777add074d6436884be6cba68c8ebd6ebd887c", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "xml", - "translatedHash": "88c9235f5140174c3ba6859d2daea92448b59fd05a49db081cf9cbda38dd7a90" - }, - { - "id": "5.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-5", - "path": ".agents/rulebook/coding.md", - "originalHash": "0771e910c76a4d4fe8240049d51a9777a9ca6d429b972d2b7f37c3915cfa24f6", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "xml", - "translatedHash": "ead7747e86c87d719e3f7d10f04baf07c58081893fc8eef642e3667041e763e1" - }, - { - "id": "5.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-5", - "path": ".agents/rulebook/coding.md", - "originalHash": "59a8922dc82b328b1745c0f3b91fc0db931b0eb3fd0e3c26fdf6b18bd3f38ced", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "xml", - "translatedHash": "7a58317c4532181f9281b4245b89cf89416e5c7f789ba0d4a89909ba300d0c4b" - }, - { - "id": "6.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-6", - "path": ".agents/rulebook/coding.md", - "originalHash": "0980b1aadfe2ac68f2408411a4c8faa47d4827bfcab4626fa364d341f1c740fa", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "errors", - "translatedHash": "b00524a3be4313da355adf562e233fc3f040313649c6608e091bae13d0eaf4e2" - }, - { - "id": "6.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-6", - "path": ".agents/rulebook/coding.md", - "originalHash": "76b50f93158d312ca2fdf09d100930fdac90a842695d5d71982bc1e62d47187c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "errors", - "translatedHash": "397927257f1a6166ae6e517a14b27d64adeaf1f1114445342e8eece6f6e4f56b" - }, - { - "id": "6.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-6", - "path": ".agents/rulebook/coding.md", - "originalHash": "4976e70e627ac2a6a257fa2480583a521c47ebccadf5a58e480b1da5512e369a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "errors", - "translatedHash": "454b07214dc2ad21ecf0626da999dc93ac75863293ff9267ba6186a0c05aba58" - }, - { - "id": "7.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-7", - "path": ".agents/rulebook/coding.md", - "originalHash": "5b08d747721d1fff4043b5b4cdcc9ff5a2012f5b2dc38d6cc15d1005115c3458", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-naming", - "translatedHash": "2713b77ce0dc27d740dee0e57723fa3d23d3d680decd110a02a647f3cc645fc7" - }, - { - "id": "7.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-7", - "path": ".agents/rulebook/coding.md", - "originalHash": "4ade080ca04bd3a8af8c5cc2a079c0d7c576063df419672c0beec9f8e88c58eb", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-naming", - "translatedHash": "d420312b557f9c342f653da36246a2d21c4e3207e3da9a3a40b6a3fc64e40659" - }, - { - "id": "7.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-7", - "path": ".agents/rulebook/coding.md", - "originalHash": "714ca4b88d20ad2f599c3e8c7287cb819db79eeaef3377ce67c9590515568ca8", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-naming", - "translatedHash": "2804cc91a2b24bc15e9da3dd4221dcb713b9ff097b7122029bebd75b0825201c" - }, - { - "id": "8.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-8", - "path": ".agents/rulebook/validation.md", - "originalHash": "4d36e33d8774770bda3087a17e046899067d6245b693c62d5c23b8d497390701", - "disposition": "superseded-by-approved-plan", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "tests" - }, - { - "id": "8.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-8", - "path": ".agents/rulebook/validation.md", - "originalHash": "ee26061ccd340d9dcb274ba8facee84e6cbf1fae4cdd67df149028fe8e6ba697", - "disposition": "superseded-by-approved-plan", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "tests" - }, - { - "id": "9.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-9", - "path": ".agents/rulebook/validation.md", - "originalHash": "a743bcef487abea16b872c402957ae77f7060eb95df7e2a912abd615215f0cef", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "compilation", - "translatedHash": "a204c03670687042691bbfb56ba3981bc162bc516a14e05a589db9328b1873e5" - }, - { - "id": "9.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-9", - "path": ".agents/rulebook/validation.md", - "originalHash": "191eedc7864cd1a54ce09fdaec1018a177b1364934c04d1d7b6ea850f6d3e6ad", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "compilation", - "translatedHash": "19960351775059c13c3bf2ccb3ce451bba20e8cc0c16fd74b00724eec00db7b2" - }, - { - "id": "10.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "5f0ecb345e2161c7505f72636b3869f4b2f5d36c854a4cdf080a365154dced3b", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "93b916cb653dafbe1ac6b1541318c6d2a99b4ded5430651fb234f09c1180d095" - }, - { - "id": "10.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "cf4346c90282c6ab53c2e461e575b9d72eb07351721701f75db9577cf9736121", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "d885e29cfc85d40947d57fd971a252a8188390c7c2c1c0a3882343cc277292d6" - }, - { - "id": "10.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "68be7e5cbe335410234b361ddc9a1d2a470d52a2efeec1cc51df20b1104df9fb", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "a58db9c776f2a269ddc19ae2b0dca051b7decf63ddec38627a5e85c24084dc6f" - }, - { - "id": "10.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "baf67bc8327069fca81f39fdd43a48c48942ad117e14c21a07d5d3ac3a2cf785", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "b8797541d6389bd1e41e1ce9fe2ebdd00c5a5de4f3f052d127e1deeb1bb6bc4e" - }, - { - "id": "10.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "826058d66069113fdd2ddf34145f9a3cfcd007cbf94058820e4b16c739492a7e", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "860205ee7cc7104f0b7870e716ce87c6a55794010451e58d244618cb4e1fe81f" - }, - { - "id": "10.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "994b998db615f982f3bec7be1d89e09f1c23f503c0919cc3d6e206713b2bd91e", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "7174f703b0a255c6b67e6e0eb62f06f435f8d62ba8140d6ad8e1eccfb66450bc" - }, - { - "id": "10.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "aa4a2e04b024bba81ec11150d13eac13d2e640c7e908177c8e7a9d3a6221572e", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "c850a0f9751d00ab4c72006c8412ca36f84e9eb97cd16a42fbf7f99db8b6988c" - }, - { - "id": "10.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "3725c7f1220801b602870d097eb30b8101fe29c3d0f0dbcc25b9706b3d7b9ffd", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "d284c4be4bd867dacb5232fe688e3d342ce37b8b27ae0538532b06e56c76bf60" - }, - { - "id": "10.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "22e3056d5cffccb699ab9f877c922098768541bf4f1f38f09d241ab128799ef9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "75206b141137df2f81699e6643bc8e496c70b9d89b394e01bb93017a3caa0538" - }, - { - "id": "10.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "b44cca91ac82e75c8eebc27fb13765fd4b7e7a77a7a8df68c6aae6f9b4d66e05", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "61dd28ec15b54946f7a6e16a616a700c68254f65b288b2c71f56b59251a7256b" - }, - { - "id": "10.11", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-10", - "path": ".agents/rulebook/architecture.md", - "originalHash": "163b6b3e30a395ad2deb4ac88fa58052e5b17073729b41c31e1b56f91a2606a3", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "directories", - "translatedHash": "f1e2390738b878c94984a774ba27f7ce1dfe9304624b4f14238b10ee17ad9d29" - }, - { - "id": "11.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "96ccf044ebe34361538ac4c3dac0fd3d2b7c9db5ad532b3e7837d04945d57363", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "9c171f3383ff9da15e8face978be93b8e1da13d5696517f201fd2e639cab8733", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "1dc0296ec2118708e1a75334f08d993e5b18f50ac371cd911d5862dfed847932", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "cc08880907c077e40ef8bdc501254fbbe9022842760fac1e7e32a52c0ca6f3af", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "f3f7debbcd9b552b379d4bfeea8312c3c6d9a4c55564db4ba8005f7a6e461d16", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "f69c49e7f0c709879f599f30063db2086b783e60971508865aff02748a194ae0", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "2568dc23c50d9799f22535715a1d496259248c52318d5280129d71d928a350af", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "a77e7aac30183eb14f83cc9c085ab9821dec19ae63f8bd6eafffaa48aaaa758b", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "5534ff06531b8f0e4dcede3a7409924a894a57e11848043c894a891cc226419e", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "f85f2d2ad085f23b258020732abb8034becd84c5964ae41c00d977df176afe47", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "d84e481c7e94dccb3d7646f58403de71f291ddf796eb607f6762b5a8cd1d077a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "8495ee4427e26bb8a6ee37d6de19f92de7513ef9419398bcb4cf6e86a8a61b5e", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "8905a7d3ff5e3dc12c838f074a7eed0664d76a6695e44ff5a1f99d4f6b60f4a8", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "5ae53f3449101c75753f1d4f1a259267adf4ce383492782fcd10de7c815f3de6", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "0e1d603608acd5aa204278ec1a5b69fc0e271ede6c8edb77edf667a1b3868b9b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "2cc05fd8785c66d75571462f5888b9990c8720bf6f6a402708e0b83cb784f6dc", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "06dbaecfd67f1807ce241fa928a76e1b9da9fc66c5e19457f8ee84e843d95c44", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "3d9951ef1257c276f5d3a96b0e7c482bc8986fe597fdd2e990c73d1cf1e36282", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "11.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-11", - "path": ".agents/rulebook/documentation.md", - "originalHash": "f91ef9d6d4abc6129c4ed63429a5786c8f63324d43544bc62422f4d51bd17cd9", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "wiki", - "translatedHash": "58fad6bddd9ff0a3400450ce71641e40827a76bbdb53c19e0e035ebd21926bb9", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "12.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "5d9f37c482d7ed2d1831728bfe868cdf0ef116cf3dfda5a68ac0be5491c6b44d", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "dad28a5daedf52b61db2aed9d3ee23a1195f76b283bed2b140c76fa8048f7aea" - }, - { - "id": "12.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "5c9522580d5b894b7597f4f96ac9128b92e6635bc21fdf7fef209f33a09f14ac", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "d973ef9f713818aae14881414686d10cbcdd0dd9db99b0daa45e5311cebda0e1" - }, - { - "id": "12.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "500bf61050900845ef55695ad3920e9d6904499db3ac32b4ee13cd9a227c05c3", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "79c5afbb8bd7d50ad8ea5fa3561c5320206c852540c066b10d1fb0c351a8babc" - }, - { - "id": "12.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "e7c01c6e4c8764cf658d961174e881c4c70cf317597643d35d9cd070e60d0633", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "dde5503206d60a43d01f0e7e4f22a8d95446f67d34511ead3712b206d1a3f2c4" - }, - { - "id": "12.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "94120d8bac9df2ed991b33100188f9a5785ac28cbd4ebc93c9649c31f8f4e937", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "d529ef789e2aaa8e38f60f4ac198a46e4facdf0bdabd1ed9562e558aa9df4ffe" - }, - { - "id": "12.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "7ed60e2fe34199e32bf4156299913bd1058fde36733c1eed362fc55a1adeb8f9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "31b99354bfac665554a4395877403af5c4688d106fa52c7d6085d3b4d6549dbc" - }, - { - "id": "12.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-12", - "path": ".agents/rulebook/domains/scripting.md", - "originalHash": "9d8ee25f4a083113ca0e53db9a1482d7a74aef76bd1b87fb9841bea819143dd1", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "scripting", - "translatedHash": "cf7311aa118331bb6e7cc9e1f371bf80521521a657088acd450f70c31d5c0c68" - }, - { - "id": "13.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "9443cafc9093dae4fd32a2c037d02de87486add1e4cc1b52377cd1f94a125619", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "b5559064539f4b6b66250bfdf2e6d88dc318169e195c3b687e0735829633031b" - }, - { - "id": "13.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "4f5e5aed6897ace5c4b6cbfdb87904d6a6a8929cd0df981f479cee26ffd96743", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "39faedb7db5aab968faf5d85d5e00e3ce311a714928a0c0e187c7219ffed2d10" - }, - { - "id": "13.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "84cc6095ce04a31a8beeb1661912a58b8de562db0624475248f755b77a0e20e9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "dd03d5a1ab0cc5f3b2c34f8f04f1763797fd42d79621c86ffef90dfceafc926b" - }, - { - "id": "13.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "5fe6ec264db83e6748ca0ae5daa13968f80aac8d6d005ee4e2ded8e32199491d", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "32d84d8fac657689afe63348ff0f5e41562769c11bd91a1d17e2beaf27850d97" - }, - { - "id": "13.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "bb394f03ce7c3962d38eb892f3240eeca07f7582563dfaaa56a128c5f9956757", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "fa2bf21fbe0202b247506afd72d2cafb390661d703060b1b1e56c2afb4dfc095" - }, - { - "id": "13.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "f03c8af813a56eea5cf54f57b7a6cbe268261de47a5d1c06c63facc942081797", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "96288472fe332b65829a9c6502eede3ddfdf9708aded8e000a855062d2261bcc" - }, - { - "id": "13.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-13", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ea83c11a5783a0e4674ddbf18b0bd8d13ae741d859ba8d18ad3ac2d57309dead", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "editor-projects", - "translatedHash": "3f91286809466021084655a592bad37b159faca5722312122300f29dfed86e38" - }, - { - "id": "14.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "802beca59c3c5542e350400d5553b4376e4fd603b93289346cddac56db95287f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "f1564be509a447142575c7444c71599d53f5e20b9a4c805c358575d5d13bcc78" - }, - { - "id": "14.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ab15e73721074f5f58250e7e325e01403f065f8bf3ef26057fd9d4c287a2871f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "790f7c69224b7ea64c5a0a1373b7a14b082c74ae3549aae36a6c28604ded12a8" - }, - { - "id": "14.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "4ab9e48bd4ad307a8eaf797efe07f0383ca83d3cf7a28f5f5c976ffcc21b71ec", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "5d944a27c3f73de2bd90576fdb16ec02ec43f96f87f011b13b9e4be7fcb33077" - }, - { - "id": "14.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "f439cf9fc6e91c8205613454bef02d000df1f466bce557863dcdb89daa5467ea", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "db8e4b6285cbc3f2db01c93c779205af7e79d0d183558548ddfa6b23eff5cc43" - }, - { - "id": "14.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "5e625d5ffdba8dc2fa694a43c0e2d06993f973f21f2582fa12e3613ea1f4bd6f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "25300dddd17b788ff48a0592f39143241cfad86a73aa8d589947f59dc8630714" - }, - { - "id": "14.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "8f1386ba061db6235bb1f467ac5ff571974533e5ce32362da4692176d8f1d544", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "65fb119594d3e326fc2bb92d94600560f43a866c2118677e28721cf475b735ff" - }, - { - "id": "14.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "c886a65a41f603a5bea7387efe60e2af979dbdd589945ec485b82c5473f3d972", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "481ee912c2eb7d1469ccfa29593223c284a5cfee137eeed7e0e00ae3db19c177" - }, - { - "id": "14.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "11a421a9a00cf21080803c70bc4740cc226479a4c9adb1f5592e82eebd5e8550", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "cae6ec6b47f8f1ce871a5663c92db9336433bb4b8b91b33c12be418d81e42a83" - }, - { - "id": "14.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "80fd966faab70b6d56473c56b0bbffeaca4831ee75830e7195a4a7f8fc46262b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "1c9714e407adcaa31fb97d2a9f3cac2df6f9bfa0e90fdf14d43bd4a7b08da6f5" - }, - { - "id": "14.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "6d61fb5dcecd2a282ec55c91f551fbf012adce132bdae2589a134bfeadd3d70d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "a47795754591c1f7d048d40fe777c5ea13139d09d90f5ed5975b87947c1ececd" - }, - { - "id": "14.11", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "1e309e4880134bdf98872c3601eb16261a30b08ce818ce2919acb47877ffd8ed", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "45b8afb771f26069f27b34ba44bdbd20205c2326d0b51f2e7726138dbe758a8a" - }, - { - "id": "14.12", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "89047a47e41186f278ab244de7f51ef84f5a4fc8e33999fa99e84eda365a4b1c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "6788b28fc30cfdf61c3bfcc1908275d0fefb87d4d7dfc090048307bf5a0eada3" - }, - { - "id": "14.13", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ced6359a37b15683302c590a140cf9f9c5b8ce14a4583b80ab64082e9a164735", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "9da5caecada51f64b5e3aee43cbca9a0211a16a9d8d53ba8579e7d66d8e7635e" - }, - { - "id": "14.14", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "aa037a2eb62bc515463abef944986e311e5889fa1ee4bc031884fb591c405d61", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "f0e84b1b52daa6d016be5554dc787ce3d317b8a661ab91fc2fed8c3507dc1ece" - }, - { - "id": "14.15", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "38878299c8a97469089022a237b2896e3699d76cff0af54d8c2a21e8a68f453c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "8084285b098674b7da1c0d669a65e729be5d82a42ef0ae513f99e065b5a02a04" - }, - { - "id": "14.16", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "d17b7484e2d5247bc6ed1dc891fa65149977f5d341c2079801f746c646c97843", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "79e84e819e757a783d8c88259ec68709db4c48ed616162650ff5d9f9b2b8c9ae" - }, - { - "id": "14.17", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-14", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "b8459066a743985e3556a91a0e8e30de69fbc32d33d2de7aa13e127e635f14ad", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-state", - "translatedHash": "f25581ebde68849f22ca41e7f5740243e79236682060ba13ecd38681383d33d5" - }, - { - "id": "15.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "ca3db635c67a5e06af1fc552d2d14673df5219117c438670b2bb80261308e997", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "5598f61c60c7e528aa02dddc381a65b16b9c29b41dd113d1e7a205ed1c3cd834" - }, - { - "id": "15.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "cd95d65721a19bed59819a9dfb3218039fbf58ce5532b9516c3db44984c7d452", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "308cdac10ffa559063cfb6e676b0aafdd0aa0827d8f0daab0a80ed7c832f9ee5" - }, - { - "id": "15.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "e42ad938b23b8d9430521e0e67abcefb208494d08e4c19a53d5a45acd4e0d76b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "79de0f9bd4ab824161b9dce0d0a277e5424cbeababd377095c2eb9d60e0fcd70" - }, - { - "id": "15.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "2b8f8939ec19c4de68cd0c8460a2366d20cdd71d6049839e54eb77572fd9cb28", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "2b64330331a1ee8039cbf370adf831b23896ac47b39d1ac2c7d4517f146d36b8" - }, - { - "id": "15.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "2126318b976262755e90da066ca6efa95c95318fbafd150e1eff03f6b1d8578c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "c7468bc8577b9e9f5bdb1c9b7d59dbe4b1acdea283c247666e84d11e0d5b5c02" - }, - { - "id": "15.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-15", - "path": ".agents/rulebook/architecture.md", - "originalHash": "5586fdaa422ec00e446f3499402e7672a9cd07466802b5c0d8e9cf8b2e2665cc", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "no-legacy", - "translatedHash": "c77319428a2d92e4f9b97d80f76706cb83559b267cf2b10d12a8530e19fa264c" - }, - { - "id": "16.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-16", - "path": ".agents/rulebook/delivery.md", - "originalHash": "1df3e0e0a5f191314228a4d5be1242bd096be2fa118a256e29d168b2a59bd9f1", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "notification", - "translatedHash": "ef7e4415eaa30f14c183aa9ce389d8c2205d0001ba92c481a2655185b09fa200" - }, - { - "id": "16.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-16", - "path": ".agents/rulebook/delivery.md", - "originalHash": "8b74dc6c1bcb5502e35ce4ba58d7ca4be4828fb387862bb479937ba101029a76", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "notification", - "translatedHash": "13791b5add506d7d6991f492648a2a86e0ebfebb703646ce47857557dbc3eea9" - }, - { - "id": "17.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "ee5e8af526141af2cb7ee6ab91b439e48d714da2c1f8e832da7553ef22c503a6", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "c4b79e930d63306c74e4971ee30aebe894d8a63c1e1c8c63a548637e1ce2e098" - }, - { - "id": "17.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "656c7f1ead45a3c2d3163ae94c6f0c49657a07676f798b0615deb70769a5103e", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "6884e80117b1b268d6ccc90625c90b76fc1f7cef3d809241e60103628fdfedf3" - }, - { - "id": "17.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "1ea202115e8e050c1713a7233da99ad2bc40b4dd94cb29d5cbf5e7061bdec892", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "41a700e5ca6457dfb3b993750452ad8f61e764fe78b965cb510408f3ffdda786" - }, - { - "id": "17.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "db8d1cd54f08743dd4298fd3d5411a31e8444aadbb26a42dcd8b3f5b27a8fd63", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "916437cbafc25fe06d0bdee7041d760172ae5fffbe54dadb1c5ba54c8d54c3f5" - }, - { - "id": "17.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "71eadeb9ec2aa3ec64d0f246f13251317f05bb6bbcc44f1aeab3f5433d01d2ac", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "ae883035d12008e913974ca35a0867231c2088c1a8ae62901566f021cc18ccdb" - }, - { - "id": "17.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "f899f36c3b77d92fcc886d9b7d293b9881feeca684e86924773830af0b4b372f", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "303882022ebcf8c451e2066059ec9db1d0750ae31690e8e0d4be4eebf569e768" - }, - { - "id": "17.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "6cbbcfde884e75e96c1efa01bc4eba9521b988dd0539a50971e71a34c7a6717a", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "8f1bcb3b34247ece9e813fb2629cf73ca156a91a65b48d8d01d0bf42754d0440" - }, - { - "id": "17.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "7ede213dd1659d4ad6f51ee6eb413609ada0db844ff03f38311bef69b2e77cb1", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "f55f5fbf29d1d956319ce9c0290eb74dc8066464aaeb19aa047d0af2ad95bac3" - }, - { - "id": "17.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-17", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "0e9ff540e001733230ba91a68544e1305ee617702ac64afa50608e05971e14db", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "rendering", - "translatedHash": "5b4a800ce70b35064669ae0b2cc88c49d8a2a282717b0e150359a383f9da6b3e" - }, - { - "id": "18.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "e1ea473d5024366f6c1b634551d461d2271cc9699cf1c765b2be393c8e947494", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "49bc313818af030b0fb0001db9b11ac40d82d4d250cb2f240f66a19e8d58f4c7" - }, - { - "id": "18.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "010d03f20e88a10ca3465d22b36ea51f9495938372834fb019c236ce8bb9a67b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "cd74fc9db1ac9ad8552ddc1026da2e047d767fbae0750b4229c026d14a8ffebc" - }, - { - "id": "18.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "0a74219bb93287684baac21ff83548cae7bcb14e0e7fd53284e1763a11b6e548", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "33ca94517dcd97e912d8078690047eda94c1769221a3516a076975e2091de14d" - }, - { - "id": "18.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "af5f687faf8913e068718e3a73cba0003d520121aeeb249479f62505f3aaf3a6", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "4fabe28f2f6f87bed92709444d8db01eeeb6eb9fe3e1eb1104b6411c0bc46d94" - }, - { - "id": "18.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "c46d6878522f11987318a6a509d56e72b4f6681e98af45cff3623657630d9959", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "a4e8d4fe297362f0912a6310926344416859262af97417f26fef4c422161f6e1" - }, - { - "id": "18.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "ad39665d09837ad8d1e4f78c284b97d4277c68a2d44ae4442a1185d9b8a3b896", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "be4aa6279247bea1bc60e5e3ea8b0d38a9cfbbc1e5c3b9fcb841fa604d787564" - }, - { - "id": "18.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "f4ab19400c0702d8da6092df70ecdb4c75293f97205663411aa847c3c325963c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "264796708436b8d5574b48bfe1033bc1fe45698ca89141352d21041b53261234" - }, - { - "id": "18.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-18", - "path": ".agents/rulebook/domains/plugins.md", - "originalHash": "6397690af4b51494ac9f83bde6b137aca3326fdd6aa74bab0dc42d93490a2d21", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "plugins", - "translatedHash": "3a363df664fe8edde37d6e6d62ffe0566dc1fe90376c61aa869a2bbcc410b6bf" - }, - { - "id": "19.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "b8e41433b5af0edc8f9e61054e6ac81c6aa2cacd0d90bbdbab1fb3b889c54bbd", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "50c049e7626af91e85a48625b352767356976794cd70460159a9f031323708ec" - }, - { - "id": "19.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "73e27ca28caa6f4e6c6f7cd1fe54ca2dc8e49e2ba15490ce7c5b1068354f8c71", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "cbbe4d856b6f17019688e721d7ce90667d36df2a59ccae9ff90325f50d4cab04" - }, - { - "id": "19.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "cde43bdde3090f6b7947886e50001b552d09d461f5ff40a0914968e988446ca2", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "9a46ff44b37d46c5a25c290b7730653dce6d57495aa98b26f22c1a3adb89f498" - }, - { - "id": "19.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "49c25780621007dcc71be5f2e2b4f4b002de2b0a9d96c40e81d193604c75f2ab", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "8d7d2cb58e7e0d01d42d1a49fbdb9c521b8fcfc7a503400100a292cd4be941c3" - }, - { - "id": "19.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "c9950b8ac4190e36f1941ec0d592853ba28171f1c75724002906cf5eb1bb4b4d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "3325bd1c35ba13ea900f2a1d311afdfb36ccf2c97187043c7151b25336d5d56f" - }, - { - "id": "19.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "24a6745290c0969a46d0461042c788fabc2e4d0d0b69b3d355aebe16f7de0e92", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "ff823b2f21dc4d5d21e106aaffbf5c5651ae2d918e50e4280055927da58a197c" - }, - { - "id": "19.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-19", - "path": ".agents/rulebook/validation.md", - "originalHash": "38808df39142443fd505e2cadbcb49dadb6cbc8e876d68b23fdf516472173de4", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "completion", - "translatedHash": "3628b29e12c796edde653461ce6b6c68ea22d00eaefefcee55cdd72e00887879" - }, - { - "id": "20.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "d04589d0ce99484f813001832e92a2f8411d2d1a4bc64aaff8175fa1e1475e0b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "96e1a4c1f7b1276a60dded704ccb43f726c58f86c99b06fb62c81a191ec78d1f" - }, - { - "id": "20.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "975f6da00e76191fdb166d04c732a9d0acc77828f65b1d270c6aa94bd0b0d07a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "99cd52450ef209e62d9b1df287979ed26fd21732f487649198a6d2e68cf53902" - }, - { - "id": "20.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "5c2f32dc18a4142ae2b41e7f0191688430deb3942f8d653c058ca5fb09ae9380", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "ce9dd22d95b882852ac19d5bdc44feb0d4b1a7b622ff2ee54226edb48d07135e" - }, - { - "id": "20.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "811e0a9fda7f7c75556ae181360e3af2a2c4a57ddf60a74bab1d17eabed0b896", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "43793c651d33494c2fca6270495afddf406398e15f21897b5e5d0c78b92c20e4" - }, - { - "id": "20.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "92829893c198c28c5c8f6d5fb3542e80f592ee4c6b362826cc9965d23506bb79", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "82d65edcf81d1ebab2f7445cfa727c37a2fa6515c7e8401499ea049bb1fc0471" - }, - { - "id": "20.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "63e109baa64f062a988a244a78754cf21234b8d3478124c99a0f3a5b131a4f3d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "643d446e16b807fb946ce67a8e30bb8fa902dadda34e6209c76b922fe1724b38" - }, - { - "id": "20.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "da38afa634e638869a4aa17188dd56e7762b25c0d33026205f91a9df4fee53ee", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "7c4e21bb14ba0d418ef4bda4c9d861566f4440aec7dc9e80491f2cb49cae9cfe" - }, - { - "id": "20.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "54c7a14b2e0f3011f82089ee72b14d27f8963883d6ee166fcbc0e6deda1414d2", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "4f660e19e473ed31e64beb070c3f3e2ed7c4954a7492677ec27b73e09942e56f" - }, - { - "id": "20.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "1b7d6605e20bbfa15843a42196d806ce2b1d06b97b9c7d678304cc474ed022c2", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "0ede328f6a2f73b21505f069bdfa56c0a8aeb2f9e8ad69d91e25353f6b21e25d" - }, - { - "id": "20.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-20", - "path": ".agents/rulebook/domains/identity-reload.md", - "originalHash": "9117cdcf7615cfaa27c12cdb1a27b762440a39595a279414c42e876acdc60e25", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "identity-reload", - "translatedHash": "ca4b44218ee5981e939f63225dbac05eb2c2bee9092f5f1a107e566e209d9919" - }, - { - "id": "21.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "0ee4a1381219a58a864b2d34e63490bc76b41a6d3a91f162d10b545296301eb4", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "601a49a2801a6609c14b3059e972139dc73c4cab54e7fa4c3e551173232c74b8" - }, - { - "id": "21.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "b8fcd9e15d3ebd1fe14864d7337caf534fe5be36043c761b9da98aaf817f10ff", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "4dd627fa435109d5532f0aec4b4e087503378c5a03ca4d8f80f15bb80429ba4c" - }, - { - "id": "21.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "3ae787b3f7492f78c4d175c1afeb3440f337470bc957514fd541e334ca7a6791", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "bd95a93492c285b77af96ddb96b379bac6adae61891528a4f9c58b13d03ed6c5" - }, - { - "id": "21.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "f0646b2f9c636d6649ae60527b2a3171e98f1667369d7bca95825102773f09f3", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "5e83c73b6bb8440c2039d7b0961b946b8efb122076a9a319cb6299aae81fda5f" - }, - { - "id": "21.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "fc03e6bc382adbe5a20029ffbb9d84bf52481670141c960b6ee9daa7188efc37", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "fd5c6a6cde29106b250246e87a8cefac8b065e49e2324c313da280b1adcbc103" - }, - { - "id": "21.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "114ac52f6a6a08e00af88d925c557453cc899572151d6638fe5e6b485b98d7f1", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "eeddbcb38d649a9925df85e272adfd61bb5d3224bd09379256550f2c5d670cbf" - }, - { - "id": "21.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "1f55a6c4e2413d61a0c260b94b1379c3ba5381dd3fddb553d5068f8784585b6d", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "ce369b79a7e86ba1ec735801712b3209da7406c2eb97567c9b2da689ff960c09" - }, - { - "id": "21.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "10a2bfdf68c81051d2f8b0fbab24495a609c1771531462fbf9868e9bef0bc320", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "1282710a648b2c4ce6f358c0d742353f9d0411f2cb038224d986a2ef48115f44" - }, - { - "id": "21.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-21", - "path": ".agents/rulebook/architecture.md", - "originalHash": "bab9bd3ed3aa17a1a152fa893a422014284ab69be0c24b7aa6576647c333335b", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "architecture", - "translatedHash": "078b288e1bfce8f69a0336108fed302b9640b776b8264c532755cc10f562f2f2" - }, - { - "id": "22.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-22", - "path": ".agents/rulebook/architecture.md", - "originalHash": "6fa5cc593dbe1d5fe96ff5e177c49a6b4feecd18f9cec91e80e7dcbec482cef8", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "core-reuse", - "translatedHash": "3a0267e4d2d341ec997e02e6c0ce7d2bab535e93cb4c478da1a6b8bf2f059d6c" - }, - { - "id": "22.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-22", - "path": ".agents/rulebook/architecture.md", - "originalHash": "43025970366c56e171047fa7cc31fb9ad071cd667dfba68297c36756f02e73cb", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "core-reuse", - "translatedHash": "5f82bceb744a6fb021aea81059457bf115a54f4b388adb979bde1db0755d10f9" - }, - { - "id": "23.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "a7180c7b2a595dffc271bbf430dad6da72ac8dbabaa7a713ac746d3be7bdcbd9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "2e5009668d2b80970bc549bfd3b689fb956a9cbc8f6e46a17a8a993088ce1b4c" - }, - { - "id": "23.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "31891a8a828b1709293b0f1f3d81067b15c1e35e0a9e8b2f6ef6149a56f0c635", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "e46c450ce7289e844808b05542a5405de9c3cc5223da703962351a2e8977ed03" - }, - { - "id": "23.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "95e12ed427e31ee89b53ebdd3551f8b671bb56c5d8d85a7c141127c989abfcda", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "9259801cd440e5cc5b6b5cd2fed583eedacd34d58d7996ce25a85593eb4737f3" - }, - { - "id": "23.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "8338542136dae7aa818b9446f5050658f3e1e89402c0c97e9d4f5abcc8b7d0cd", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "e1769de8f4cfb3964abe3c2337c13ebc543581c165c1db1b9602c1b1daed3002" - }, - { - "id": "23.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "41874671f58ef7bc6285d79b4539b0d61ea6e5787d16732d3e2493d84b043ba2", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "0037d6a15be093a1b084de5f680f593450f1e932905c775bb4f8822fdb307be5" - }, - { - "id": "23.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "19ef285a86c7baaf07c63b9a8fc5cd74742cfdc2048821333f3cf14a22acb7c9", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "0d0d8f06fb572349230c1faca233dc503361e135e9adb9d3b429d3f973601201" - }, - { - "id": "23.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "e37bcae5aa76b76e6688c78103d6163a25fc73ed080c760964579585038c086c", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "26d1fd9f48b300d262bf87e7122e38c49037aef35b791538082963a728ebab00" - }, - { - "id": "23.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-23", - "path": ".agents/rulebook/coding.md", - "originalHash": "00ab8e1bf5ec15ca8c2df55c202cfcd4172b471b8fb6ee80cfa15a58bcbaf1bc", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "formatting", - "translatedHash": "0bac228dd3b888345ff647461b01c6ad677caf65942c708d325d28739e3058d0" - }, - { - "id": "24.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "a78da5ad23986a44349374372658a6557ee2d9976628b07e933721594fc468fb", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "10244dc31c8640f6338ea9fda49ed04d9b88f275d78a5d1ac0d9921647a6fc24" - }, - { - "id": "24.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ff8188e23b8af5d3991c935b771b773a59598b7babf864d5b944150c0e013e27", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "a945b0383eb161ec90c28bcac8c42671649e0075ea4cfac4a64896aeaa1025e0" - }, - { - "id": "24.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "d2f1efe96013a971a0f435d8592204bebbe86ec48abb5f4bb537ad6b12f3e7d4", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "9a17d7b49fd799e072b6a9bc74ac804bab28a0b409d5c94355753fc174b07947" - }, - { - "id": "24.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "3376fbba35db3b14186fad6856628170c46b5ea568ec4da85d68e13a360df83e", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "2f686f33426418cf4f0f9eec5367effccd701e63d4c694cb7d6d15db75ced0da" - }, - { - "id": "24.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "102fc73957d8dcc7555e9f021d87b707da29f344e4b6715357256318c6944ead", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "8f0b47e959d0ede256c2c32cee6900ec3bf5e3d1a4b12238517767a4eff4a805" - }, - { - "id": "24.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "9aa7299366b57f5a1b1b5ca963563c742683e3fb6380dacb2af72d6e1d99fc1d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "7cfd8c31799dd63abed0ed504917ff8314fcb6d63f452138228af79921b580e7" - }, - { - "id": "24.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-24", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "a60a708374ddcfa25bb62fbd311ec7a8bb959a60e3d74fc03ccb28777eefae77", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-layout", - "translatedHash": "426d40ba0085d6926ea69ecd5ef43299ae49bc34da5f6f6b5e5ca9dcdca8e08c" - }, - { - "id": "25.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "b19118c564bf7869a979959cb5942e88df5ab3a54f541061adb140aa316ba10c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "6f3541d92930adac22f939113bedc1be29b6dcd0b0256d342d4426a1cd3f31dc" - }, - { - "id": "25.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "c7c3e1e13e6ec6f3600f6355d31a4a8d755f43369274baf9acfbe21440e8a0d6", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "48ac069968aebbff6d00744c92c6b5c1c47cd81503c31164b1e49962a34a6394" - }, - { - "id": "25.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "2ce9b85e57802b8c2a31c4cc3d0c8235b69068b7d46a7e5277978472f4de88d7", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "5ca44339f245dfdeecb8cb02b274bd3d830327330c73814987e11c93f2429800" - }, - { - "id": "25.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "8b73963b3c9f46a9705c77b3a0a00ab19c234e26eaffd223d6fc0b2e932f603a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "00aae0b2ecff9452b6ed1bddfb1dc00a6b0aa126dafb52b3b2b71fabf3b7a72b" - }, - { - "id": "25.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "df22738791386899274f61f777a931262733f8a48f1744208c042fea57880d80", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "4ae5ee3546730297ce1e27aeddf37b00703842a3fa13f3780e65e520c495016f" - }, - { - "id": "25.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "b2d018fd842124e7109ad0973e6e907e908ea05c3d29d2ff0bbde4cc7abc8e4e", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "5e19b875c132a28b4329330254028c2514adafa89b1721a0836adc7bb523bbcb" - }, - { - "id": "25.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-25", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "224ccdec3ed83d364b31ccbc614ca441b1dc8b66d1985e44e5c5d615342d7a67", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "build-host", - "translatedHash": "bb30e559aad2e6a87f7859cfcb4defc3eecb0d2f2b8071011d4a10db773697e2" - }, - { - "id": "26.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "bb60b33ba54c7336e9799166c01b4052d126a112d4722915e3904b66fc4b5ab0", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "0483b55fccc5f6d01514232acd1f02e3f183882b5577f3b00d9926260bd982a6" - }, - { - "id": "26.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "96c711350d8ff162324062dfb4b49240d44be6a667a5fd42a42bf590c3a5e3ef", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "795bb85622bc01870e1e65eccb18705c1218060ae36969d3b6b356499e658d40" - }, - { - "id": "26.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "fac2752dd3f41f02a5029638af0b428b76cd57c54b1e806d7075b11720f6e4d3", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "8db8f6984ea6d97e8089f27c6d194ed044c67bdf33f61d890a137fdba29101fe" - }, - { - "id": "26.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "24eb6050ce21ea7ff4821e7c8829d4beeed5e4ffa67e27dbff16f278a535ae78", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "58bd97d696b2fb242b9115ed807e9f25c231ee908b2d99a46b3187d29e8747ee" - }, - { - "id": "26.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "73642ccb128fdfa44c92f79efe6cfa8da42c7c16b4fc99e21e64f6ddac3c47ef", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "ea5a66ec42e2b16e5433a1bb9ac555169660b9be567d296b7ad8fb6425c98c19" - }, - { - "id": "26.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-26", - "path": ".agents/rulebook/architecture.md", - "originalHash": "25a9c3360ddadcf3681147ed90c1d86a63205a903b3dddde86992c1866b32e79", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "solution", - "translatedHash": "7ddcc1494b4e535474a0bd52ebe4f29e8063b9a84fa51409a8618a561e7dea15" - }, - { - "id": "27.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "9cc6e95f7ea461fd696de07ce76f8797c96ed41f0433e310e1af26582805b22b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "a3c3d40432341948da3425111919483a71dd9a670453a779ce14988de2c86b27" - }, - { - "id": "27.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "7603640023e8356e822dbdca1f0bce8573039862e61d8e8926b0acd6611b9494", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "799b62a6394cc3d00628d0011a636ee7132d70faf3b87a2ad91dd2ebbb26fe6b" - }, - { - "id": "27.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "aa8f68717a46b2a24105079cfff00c2955062fc80da10d8005ef3611bd7d997d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "b275fdd63312c343487ef5900b754569044bdefa162e7984ff45a3ec6ac9d121" - }, - { - "id": "27.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "b95630e0b3deb0b2d09de1f2ce037457354b9e319ebd2f39c8106174275eb320", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "e6801a9f0117cbeb680dfcda3d3becfa769e2dfa867fa33426faea40f37d2ae8" - }, - { - "id": "27.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "8e6c8256ca3966575e246bf2c4986d105214afbb19a069bbf83c3e0b40de379d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "e3eb98850d4fc6b9d1f10314f59ff960d02fcc31805fb8c1806e4871da6a2cee" - }, - { - "id": "27.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "2c398b51c32d526e1b9337797dc9d7a06302c34f25f22fb2806075bca491c99a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "7abc730bed80f7182f50a2fa2d800ec1a7ff4c7f93c10603a7f9db78d1ecf0a7" - }, - { - "id": "27.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "1eda47cd0c85d1ffa678dd58baa94224f78967bdd53aeb22c46f5b551bb403f8", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "5295573eccd283d7ebe32cbc6a81a9d7de00cc5c69053fd80c864f87ba200db1" - }, - { - "id": "27.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-27", - "path": ".agents/rulebook/domains/rendering.md", - "originalHash": "ee7ed4698848793ab73e52bd3e73fd8c709f75028df195bbe876b70e0f648a28", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "content-frame", - "translatedHash": "1ebf3f605999863b058ea2e0842296ae13c048c5c2913da0e05fab43b2a207d3" - }, - { - "id": "28.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "bbd068ddf45b8a55440546f88432f08f1bc7a2b94ed6aca1d4f72c53a59c15f8", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "1ccc62336920d8d206c660bb69253fc729a50009f5183994d8f51e997f81a733" - }, - { - "id": "28.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "38365fab9c07d85ea81c40cd0d181f0549b781dea9c48bdfeb0559a24a02c607", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "e07c444e54ad0706b8d60f18ea4251134de8da429be5becd82f620b34e9cf3c3" - }, - { - "id": "28.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "1e3f7d9acc0b4f337cc02dc2fe79d66ccda45221c943c14cf71f91de709ad989", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "d4e895af3df576a50c336831087da0154a6a61c49435523ab21d1c38719aab82" - }, - { - "id": "28.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "e584940bd16fa8ff45182ea7674910860e3a03209a16703f1b06a98866620b01", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "f298d49d33a65277f5984042f0db3612a2ca869dade024d0d9f35414d598feb2" - }, - { - "id": "28.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "a1d364c82b7a1c3cb16f56bd1aae66832cb7b15706a9a2c5206ba3fdaa79a886", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "cc05be97176ef293898bc6e19032c1d524212f4072c437cde90d72971f79b18a" - }, - { - "id": "28.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "875e20eacd91a77fba60d63920f357e4e7d1a3e3ae2c1f9f830da1fd8b8000a7", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "df72d5380faf70912ec865e14811a77f0fc2549269872aa8bd9b47989cbdeb9f" - }, - { - "id": "28.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "6af5d2f1a1c1f5083c4e8da9c181963e99d54ea38a9563da8747ea5fbcaab5e0", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "6adab6f1f34ef19fdd6e7b53cebc19f7c644791c9b9c3ae1dd3832d18570fdfb" - }, - { - "id": "28.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "dbfa9fbd4fa122d1eb9ea53bd5d523239d856d17a436e8df8616730f411e6a95", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "6ec84e13d26475f76db8a7cb32da00e07c29c3c112810af53e982217410c0065" - }, - { - "id": "28.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "c02df2b6b87a837d2297dead8bd588d68b1e0b158f265aa2f720331fb975487a", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "cc2c00b11df385e07035448fffcf8d681df96acd8382ec0e1558f5d61ed8f0f3" - }, - { - "id": "28.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "91e9b473ace4cf03421e9e288264dbc1c14ede8d85b92a96436ade4f1831095b", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "e51ebcaf4adffa66818e1fd80078f4b77797905a7bc1b34cf6e2be8289b159e9" - }, - { - "id": "28.11", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "a80250da185512ce2c8cd8d97ae37f7e29f823e844cfb499659b0e89502d3ae3", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "4b3ba100cd3a0a89254d79cdd4d493856dfa800f804636a44ba8849cdd82d4ca" - }, - { - "id": "28.12", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "627102228e1d72789f8c8c31687375dbeedb3e7c275a879eeed503ceaf1203d6", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "ba4580a371549e2c475316965ddc62910ef7c48a76d4ed19937b4ad6ff97d989" - }, - { - "id": "28.13", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "86fc3f18e3017b563ef8b55f15576986538a7e01dc9f61b869e698a24ee7cbfa", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "1d6604b2c73f03940f77f447e9dd42a9bfec9ef056d70190985378c7ee76d2bf" - }, - { - "id": "28.14", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "a5945bfa41a6b678b345609c3fb7753aa2aa3a183b9ebc7d11427caeaa0ab25c", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "38ad850bf1f51ee335adcf4b28bac58eb15636a54d7d90b2d5ce1d04ba4e0ebe" - }, - { - "id": "28.15", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "a4e99ab18a653cd24bc57f0d7df13d1dfb5778cdbf0a59aee49002ac93b77915", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "999168f0eebea40a7f0a0c41fdb26eea4b45a29e467ae42450117a3c18e769bc" - }, - { - "id": "28.16", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "0afee409eaa98d08d8e1a0334b61183523ae221b3f3b86f59d9607e0babec762", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "7e606e087f9376f10f2fb4cb2ab487372c83fb64d3f39fcce62806b806b80028" - }, - { - "id": "28.17", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "09969edea363049274eb103b0f3ed28431ee6c029070d88a2de8e287f5f0ceeb", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "8e56582f7971f183cf862b5dfa4b238440064196565221baad83cc0a096c76d5" - }, - { - "id": "28.18", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "066a20c7fa263bec6fb1bf35b123412cdc19b984fe121365b77d5eb4e8bd7fe2", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "770fb60453044c83021640675b4db0b4b0d66d24e76025e3bae9c3022b1fb3c2" - }, - { - "id": "28.19", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "f6b7f455387f2ffe8b272441fe9ccd7c6fb793a640332c7889ec4b963ceec35f", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "a5d16ebffec8484bdd8e48ddf07eb6f9010296c0d3d03506894434e5ad90b20a" - }, - { - "id": "28.20", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "96a1de39674aff5c38eee8057c697e37d7b1a34051133b3471bb96ff56933c6c", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "80284b4568ad4e28bf6d275ef21ccd35b92160cbad4d4832749532bd55caf1a1" - }, - { - "id": "28.21", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "2530d325d5dbe1448fda7a6e246d71380bddcb95a48162a33cf8950573e8b381", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "01c97c9490d373912aa39f72eb12078aefb786893fdf19d8d1f867575b37aea4" - }, - { - "id": "28.22", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "85f424ca1b9c5b3d21b925ef469a1a515c31f2ed651a82a92a208258f55e961a", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "1e1554ca14b8f1c1c792b2ecc51e5a22d04b4db18e731de88befcee8d23444bd" - }, - { - "id": "28.23", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "1121c4faa7c7e120a90135449a220ec60b622d7831ad68c2c621d96fc0e7efcd", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "dc1b482f4aab5734dd96ca96d2d3831385aae7c4886d7cd76388459e689bae4f" - }, - { - "id": "28.24", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "b61c0f0e7f3be551ed431b43a76b62991a811b2b51bafee0af5ebdb39d320a59", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "f1bd1a5d08935b55441ccf2c4708d8841d92a9f5a6b80a5698e1a47d1519fb25" - }, - { - "id": "28.25", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "1193087c674adcad2e28e80da089bca39d1bb083e175c00c46e3bfac2e21f07a", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "7f8759274527c9b1b1ead5bf64427baf9aec1dcb42e3902fac73ab250ff7ff03" - }, - { - "id": "28.26", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-28", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "780f84046cc74eea6834fe6397421a5e76f32bc030c29b2d0a7e66ac18155bb1", - "disposition": "preserved", - "check": "architecture + semantic review", - "reviewer": "implementing owner", - "unit": "platform-products", - "translatedHash": "af63d3d2ab4dd248aea2c3f8eb82cec97a485bc066d80430c680c7c87c5da3f8" - }, - { - "id": "29.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "1184ebc811c53110f9b93a156ddbfe721a06e84ff561b7b170de4b8a4f09c7d1", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "fe2f86b126dc556658b3d98510c367c9b0d0e1cdadbbde575b452615d2dd5b9f" - }, - { - "id": "29.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "24e7a817f0f579805afd40f5ed16f6c767153b6ebd44dacee9c627313443d019", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "8bc7f52cde6311fb50418b498c44debfbd02a9e5072a2002d3c4ce6f78133a06" - }, - { - "id": "29.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "930fcd222b949ce695b267388f8203bd798c04c174217146304ffc68ac90e511", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "ad3910305ee11b6cc3c301f641715d36d27bf349ea279be1690f4137dd73b6d7" - }, - { - "id": "29.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "464eade4d3d14b2b800c761c2c5e26c77a22a4351b5ceebcd1f112dd3cfdfc2a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "229dcf70819f94d7a8291b75d8cbfdb623e6c6e39b36db4f37726d8c1fb43f8f" - }, - { - "id": "29.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "47a490a8d8506b2fb25cf4e48407c8654b2cbc143c272e53e509ecaeb52dbbb5", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "452e40de8c98a748c939e30115ca9962a497cb38c20ebc931cbc691240e59ecd" - }, - { - "id": "29.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "77c7d40f8caca628be02ac2147345e04132df08185765da27e5d6e823ac61f1c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "88fe122ded5a5662f59de6cb274cf44aeea96fd79acea3c3d8ddb8160b0f9882" - }, - { - "id": "29.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "dca2a1bf003d9c82f5c57956cc315bd20cfe11d5c9c52caf2aa2c3c06a6ac852", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "49a91d8ef3552a254e865b8629a5e296fbbdd3f9808a30932cb3af1179682abc" - }, - { - "id": "29.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "1ea3f833bf68f4009d0a8baf5b54744de3b51c97d38370e47e41a34bc31a0f96", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "94d8980e98c8bce72f4cc50106880b725f8a4dc62f9fefa0d08047bd816c451c" - }, - { - "id": "29.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "db9846f1d6d8462e20d840a76c3fd2271e2cb1c171ab6a3c3dab8373c31d5e6b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "6d5a1d919c9a6d1c0ab3d783e344175cabaf1b7696b2280051dee36b64204ec3" - }, - { - "id": "29.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "4417ce20429062015905ffbe98b19a0d31908960f6d5863c80c27fd2b7644ea3", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "c932db0ddc349b2623393bc3be6ecee78b5b949dd6ffbe790994736f0caf7aa4" - }, - { - "id": "29.11", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "167343d8d3372823fd6a5c09a919f63b5bd1524b4cb1b6229f516f4eb6a7044f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "93cd250c40b90c2dac1407b7622fa51b291b959f2576e2a09d48fc04c2ae4a7b" - }, - { - "id": "29.12", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "d03b95720e5346978f818d1cee320f8eb0576eb915431635b925dd83b318f5bd", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "fa6f1d36700726347605104c6b97cce1e94833efd072d50b39f17d96687c380c" - }, - { - "id": "29.13", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-29", - "path": ".agents/rulebook/domains/build-native.md", - "originalHash": "d8360e8265f5088a3def25af85805151c7aebd7a508d09cc919f19f5e24d666b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "backend-build", - "translatedHash": "c718e498d894d8502a6e4f66a5896eaa1683c6fcf81cb18d27e39a9007126bd3" - }, - { - "id": "30.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "3e0df150e5273f71eff27bbbc8671a331f09cb12a5c07a96c8e861a64bf28ae3", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "d2de9e4e7dead46bed8bdd02cd62f88fd8a4dc7fd5919fe7c35246dd42a47c46" - }, - { - "id": "30.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "1d25bc7acfa0735c58e3814dca382bf3234a0e7d965325e173bd88a903c14af4", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "718c54731d8094e34a332a646726fcabb768aff145338555d967fe2fe537e775" - }, - { - "id": "30.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "4c780ef5b65a99dad550c107a7c514591d3e2812ddff8d00cd308978579b15be", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "b5af8f7f7c5b556b5030eedeb74b12ba7c0b47abdb819ac3d06dcfc7bb4ff51a" - }, - { - "id": "30.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "009ca6574de647708b05c24de08073f8af6183a5c3b7fc0abbcf5fb23fe9ed39", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "e15d9eec2ecc8ba2bc85a5115eff36f54181b0a457f730082de4439fa5bbf59a" - }, - { - "id": "30.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "33c44f2b873bacb7822af7718aedd66c8967bd7cc3e1ac6f8a193caa4013a663", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "cc2046e1746a60a30a83b59a2278a35c7b918fbe41cf4de4fbd22232463c3344" - }, - { - "id": "30.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-30", - "path": ".agents/rulebook/validation.md", - "originalHash": "e3dbaacfefac2daa3eef9aba4b6d0d9656b068941246544f122f5ac40e767e6d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "review", - "translatedHash": "16c75b1f4fd6c9e3ad3b1188a4b78c09a27e30fad55ceb9e0c7dd25b94d55285" - }, - { - "id": "31.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-31", - "path": ".agents/rulebook/delivery.md", - "originalHash": "3b1ecfb344235b63cb4015fa1548529093f605c5673ae454bc1660106d7b3d3a", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "delivery", - "translatedHash": "b67c64583f6b8dfc7eb0706a3cdf820e5e138fce3dc57b6957775ace596f9df0" - }, - { - "id": "31.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-31", - "path": ".agents/rulebook/delivery.md", - "originalHash": "e5bc32830644660581c3286a3d352fcf4828b676c91c116afa23e08b48f00c85", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "delivery", - "translatedHash": "68b629f0d9e3d314f21508e9a2e2267ddc9cf87d80f08c64b7fe80154fd67b25" - }, - { - "id": "31.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-31", - "path": ".agents/rulebook/delivery.md", - "originalHash": "5101467f70d294ab413e4befbd85c00c6717a855cf3fbee0aa1b24c48467f2c6", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "delivery", - "translatedHash": "2c0cb58de507485b88f08d2823a84dbdb3ae16fcaedba435b7ce4ac6843873f4" - }, - { - "id": "31.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-31", - "path": ".agents/rulebook/delivery.md", - "originalHash": "f67f47be3449ea304ec5c3279342840557c75efccf63bdcc783df37d2d974053", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "delivery", - "translatedHash": "4c4fefa0ee638f7972f8c844c775cb7271426e48aa62cff4424e65448f1286e8" - }, - { - "id": "31.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-31", - "path": ".agents/rulebook/delivery.md", - "originalHash": "de6a01673254e95d66beda0153ba848d3f808fb9e3164e41d4561dfe6d07aed2", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "delivery", - "translatedHash": "faacd093eb7499bf0665183a078ed48662b8b4e6e81a754b834705c231dc08c4" - }, - { - "id": "32.1", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "1df2bd9d01c7611d9916939771fdd2becb76f37d10cbfa4d1542ee2c8f938eca", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.2", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "22fd6af1bb890a7d27b23d959b8504b5db470e401d2b581c63ba038f4c957914", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.3", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "22e9cf2e6c3a92b4655ca67b49479f7a54525bf1d3f59e904c1fb91168a97175", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.4", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "c6f50e26701141e063be238e81bb9c0fbf0c60e1a49bc1925e71e59b51cbb97c", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.5", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "87015c79749cfa3edcc9f013455858720122b3f2df306b9f507fd634e1fe53a5", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.6", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "cfa03efef9d5ec20da6ca65f90d6761a38e59891d567887476cc392e0b32b09d", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.7", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "616d978818c8ea9234ef6765a405f2099a74021ea0a5b43f6b6e72c965516b22", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.8", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "5e7b3322365eeb3a3a454a09842e63914b9c1ed22fb330012dbb026612372641", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.9", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "0ec49656b2d037e60ea3b07ae7d8ca86fa67f996e8395e7baf375163b28e47ed", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.10", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "e425b5e45991d571e96373a3315bf81929ff0b8984a0dcb5c1ade024fe38f965", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.11", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "74cbd2228ca2f4aa825d56f3716cad9b10b6def5eeeaf1b9923bd511f2986ffe", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.12", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "26c8b3a4f5b3d5912f20cf6fd304de30470a8a81618e5a441ed1e497762bba27", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.13", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ecbde133185bbf5cf11dcd67eef943701bd229a987d8201b48f769e1adc2bbec", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.14", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "0a616cb021da2aca735b276f89b6bc78090c19fdcbec1ec83cbef96e2bd7023b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.15", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "7306cf65c6b8dcd323bb97ad664f248e95f7da3934d6414041f959dd2649908b", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.16", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "8f22deaf3629f8fccb357421384db74be421c8e9a05a672ebb22409ada07cf5f", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.17", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "fbbbb0cd6acaf286fbde2fd4e51abe04c768ecf13ab67d53d313d47d1ba054ea", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - }, - { - "id": "32.18", - "source": "7f56dd64bd29231351f5441c18877b0c3ad3229b:AGENTS.md#section-32", - "path": ".agents/rulebook/domains/editor.md", - "originalHash": "ed3692df56697465796d1e95ae805068eabf4418cf8e9ec3ed5327607578d4a4", - "disposition": "preserved", - "check": "owner contract tests + semantic review", - "reviewer": "implementing owner", - "unit": "editor-acceptance" - } - ], - "units": [ - { - "id": "style", - "path": ".agents/rulebook/architecture.md", - "anchor": "style", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/style.md", - "sourceHash": "c92daaba3fab8ddd29a07e2f41f68108dabc168f285256d0c8dab2ae8bd61ea0", - "requires": [], - "paths": [], - "tags": [ - "style" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "0e2214dc4aedf0d4b00f1e7a6d0729343611cb5ffc8ef8b8ad153ef8755e8826", - "targetHash": "a54583ae86207c636bb8c0e702652683096299c4b22f2b1a86ac3fd1f05c86a1" - }, - { - "ordinal": 2, - "sourceHash": "0438048c6c19d09a17302f8833d072eee0bc1dbbea42ef63792c8e182acdd9b6", - "targetHash": "619bdc60de5e116996897c86ebd06284331a38e36dec8f1362e53616f9ad7fef" - }, - { - "ordinal": 3, - "sourceHash": "7548a57f38c92debf7c5fbb29b5f477132cd9dc587bb166ecafd996d2529e745", - "targetHash": "2acbd5f71f6e0b3a57bc47e5611f6422106ff61340977f67f89962f3a49b77a3" - }, - { - "ordinal": 4, - "sourceHash": "4c955118aec3a46bfc2136417987f168069fe06a1991534daeea48f6e032490b", - "targetHash": "99e629ab7c8595b0bb3bffb29440446cbd1b4e3a4f272d58b784a1eb0855581a" - } - ] - } - }, - { - "id": "encapsulation", - "path": ".agents/rulebook/architecture.md", - "anchor": "encapsulation", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/encapsulation.md", - "sourceHash": "ad4eda770415dc6f4a543bd0724f31d6652f88baae3e7ed8d6c2cdce9b845e81", - "requires": [], - "paths": [], - "tags": [ - "encapsulation", - "new-boundary", - "public-api" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "21c4ee238927515fe775b303abdd8b7d2c087f71aebd8e2585058e42c09fca84", - "targetHash": "b1ff182ee1efb760ecd40ea10fa1df91ff9262cb2c609b9ce028f747a2ca3ad8" - }, - { - "ordinal": 2, - "sourceHash": "b41c9ac4a02994caca07eae9f9f88b1a04a54588576dc83b210317d72f54f76f", - "targetHash": "61d23811216ed1dce965f002ac5cc7b1d8b9548eb5a048459f4c103a7d9f6e4e" - }, - { - "ordinal": 3, - "sourceHash": "c99a1440e54ed1f02f47977ef854a48b8e3ba1ad66f80b02acea7285a1ac5bc3", - "targetHash": "4b9c7f47bf61bc389e0925ac64026e38a90b588f4e47155d88dea7256d216eaf" - }, - { - "ordinal": 4, - "sourceHash": "da4c375502ff67444749d190568441619c09ceecf1a2cb8afffb691b326f9bca", - "targetHash": "31b9db7d408e5d0fcd307fd1b9574f67716e904f53a9ca7f51475058312b360a" - } - ] - } - }, - { - "id": "directories", - "path": ".agents/rulebook/architecture.md", - "anchor": "directories", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/directories.md", - "sourceHash": "9190caf277e7690896e060164a74a6b92ca99e1714dc48dc95fb37fcfe6bf524", - "requires": [], - "paths": [], - "tags": [ - "directories", - "new-boundary" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "3384c9ea100daae62385d0fc5cedd92e11d5df4992b2360b1f6e87ff1f833efc", - "targetHash": "8c36723587c0454b397357de2571e3e2437f21947df7a74d9cb87a2a43bb5e4e" - }, - { - "ordinal": 2, - "sourceHash": "5f0ecb345e2161c7505f72636b3869f4b2f5d36c854a4cdf080a365154dced3b", - "targetHash": "93b916cb653dafbe1ac6b1541318c6d2a99b4ded5430651fb234f09c1180d095" - }, - { - "ordinal": 3, - "sourceHash": "cf4346c90282c6ab53c2e461e575b9d72eb07351721701f75db9577cf9736121", - "targetHash": "d885e29cfc85d40947d57fd971a252a8188390c7c2c1c0a3882343cc277292d6" - }, - { - "ordinal": 4, - "sourceHash": "68be7e5cbe335410234b361ddc9a1d2a470d52a2efeec1cc51df20b1104df9fb", - "targetHash": "a58db9c776f2a269ddc19ae2b0dca051b7decf63ddec38627a5e85c24084dc6f" - }, - { - "ordinal": 5, - "sourceHash": "baf67bc8327069fca81f39fdd43a48c48942ad117e14c21a07d5d3ac3a2cf785", - "targetHash": "b8797541d6389bd1e41e1ce9fe2ebdd00c5a5de4f3f052d127e1deeb1bb6bc4e" - }, - { - "ordinal": 6, - "sourceHash": "826058d66069113fdd2ddf34145f9a3cfcd007cbf94058820e4b16c739492a7e", - "targetHash": "860205ee7cc7104f0b7870e716ce87c6a55794010451e58d244618cb4e1fe81f" - }, - { - "ordinal": 7, - "sourceHash": "994b998db615f982f3bec7be1d89e09f1c23f503c0919cc3d6e206713b2bd91e", - "targetHash": "7174f703b0a255c6b67e6e0eb62f06f435f8d62ba8140d6ad8e1eccfb66450bc" - }, - { - "ordinal": 8, - "sourceHash": "aa4a2e04b024bba81ec11150d13eac13d2e640c7e908177c8e7a9d3a6221572e", - "targetHash": "c850a0f9751d00ab4c72006c8412ca36f84e9eb97cd16a42fbf7f99db8b6988c" - }, - { - "ordinal": 9, - "sourceHash": "3725c7f1220801b602870d097eb30b8101fe29c3d0f0dbcc25b9706b3d7b9ffd", - "targetHash": "d284c4be4bd867dacb5232fe688e3d342ce37b8b27ae0538532b06e56c76bf60" - }, - { - "ordinal": 10, - "sourceHash": "22e3056d5cffccb699ab9f877c922098768541bf4f1f38f09d241ab128799ef9", - "targetHash": "75206b141137df2f81699e6643bc8e496c70b9d89b394e01bb93017a3caa0538" - }, - { - "ordinal": 11, - "sourceHash": "b44cca91ac82e75c8eebc27fb13765fd4b7e7a77a7a8df68c6aae6f9b4d66e05", - "targetHash": "61dd28ec15b54946f7a6e16a616a700c68254f65b288b2c71f56b59251a7256b" - }, - { - "ordinal": 12, - "sourceHash": "163b6b3e30a395ad2deb4ac88fa58052e5b17073729b41c31e1b56f91a2606a3", - "targetHash": "f1e2390738b878c94984a774ba27f7ce1dfe9304624b4f14238b10ee17ad9d29" - } - ], - "amendments": [ - { - "ordinal": 7, - "previousHash": "7174f703b0a255c6b67e6e0eb62f06f435f8d62ba8140d6ad8e1eccfb66450bc", - "currentHash": "fc58ad6c6d4b1439f732c3ffa8f9c16635d7ea95771f5f98a5139d87dbe2c23c", - "approval": "User-approved InnoEngine CI/CD, platform ownership and testing refactor plan, sections 4.1 and 4.8", - "review": ".agents/records/decisions/ROOT_TEST_OWNERSHIP.md" - }, - { - "ordinal": 11, - "previousHash": "61dd28ec15b54946f7a6e16a616a700c68254f65b288b2c71f56b59251a7256b", - "currentHash": "5df2b1554553a9db29feabf4ab466bc948597f06ba9a5f7f0c4c6e0d305faf0f", - "approval": "User-approved InnoEngine CI/CD, platform ownership and testing refactor plan, sections 4.1 and 4.8", - "review": ".agents/records/decisions/ROOT_TEST_OWNERSHIP.md" - } - ] - } - }, - { - "id": "no-legacy", - "path": ".agents/rulebook/architecture.md", - "anchor": "no-legacy", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/no-legacy.md", - "sourceHash": "35f95260d922e900c047f140671b4805f65fd755f4e086822c2a50b8ba1ec3b1", - "requires": [], - "paths": [], - "tags": [ - "no-legacy", - "new-boundary" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "a2da8bd11d5151d3ff856399dd88c86cfc2e4a3bf66cfaa095b39183a90f5536", - "targetHash": "91d7b048836348b136a12a876a8aab4149b9137d2593c659883ebeaab0b888e5" - }, - { - "ordinal": 2, - "sourceHash": "ca3db635c67a5e06af1fc552d2d14673df5219117c438670b2bb80261308e997", - "targetHash": "5598f61c60c7e528aa02dddc381a65b16b9c29b41dd113d1e7a205ed1c3cd834" - }, - { - "ordinal": 3, - "sourceHash": "cd95d65721a19bed59819a9dfb3218039fbf58ce5532b9516c3db44984c7d452", - "targetHash": "308cdac10ffa559063cfb6e676b0aafdd0aa0827d8f0daab0a80ed7c832f9ee5" - }, - { - "ordinal": 4, - "sourceHash": "e42ad938b23b8d9430521e0e67abcefb208494d08e4c19a53d5a45acd4e0d76b", - "targetHash": "79de0f9bd4ab824161b9dce0d0a277e5424cbeababd377095c2eb9d60e0fcd70" - }, - { - "ordinal": 5, - "sourceHash": "2b8f8939ec19c4de68cd0c8460a2366d20cdd71d6049839e54eb77572fd9cb28", - "targetHash": "2b64330331a1ee8039cbf370adf831b23896ac47b39d1ac2c7d4517f146d36b8" - }, - { - "ordinal": 6, - "sourceHash": "2126318b976262755e90da066ca6efa95c95318fbafd150e1eff03f6b1d8578c", - "targetHash": "c7468bc8577b9e9f5bdb1c9b7d59dbe4b1acdea283c247666e84d11e0d5b5c02" - }, - { - "ordinal": 7, - "sourceHash": "5586fdaa422ec00e446f3499402e7672a9cd07466802b5c0d8e9cf8b2e2665cc", - "targetHash": "c77319428a2d92e4f9b97d80f76706cb83559b267cf2b10d12a8530e19fa264c" - } - ] - } - }, - { - "id": "architecture", - "path": ".agents/rulebook/architecture.md", - "anchor": "architecture", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/architecture.md", - "sourceHash": "f67344b2282dc9dfa2850382f5e398fb0e3fff0727d274e523231ae25532756c", - "requires": [ - "csharp-standard-1", - "csharp-standard-13" - ], - "paths": [], - "tags": [ - "architecture", - "new-boundary", - "ownership" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "1d0e28ee4c9fa6b7570ea77acc93de9df2171ad572be65d1ab3150def8ff1719", - "targetHash": "ea65daf30a811da2ec7dc7dedd847b681176f502810a4eeab08ec0810c491e4d" - }, - { - "ordinal": 2, - "sourceHash": "0ee4a1381219a58a864b2d34e63490bc76b41a6d3a91f162d10b545296301eb4", - "targetHash": "601a49a2801a6609c14b3059e972139dc73c4cab54e7fa4c3e551173232c74b8" - }, - { - "ordinal": 3, - "sourceHash": "b8fcd9e15d3ebd1fe14864d7337caf534fe5be36043c761b9da98aaf817f10ff", - "targetHash": "4dd627fa435109d5532f0aec4b4e087503378c5a03ca4d8f80f15bb80429ba4c" - }, - { - "ordinal": 4, - "sourceHash": "3ae787b3f7492f78c4d175c1afeb3440f337470bc957514fd541e334ca7a6791", - "targetHash": "bd95a93492c285b77af96ddb96b379bac6adae61891528a4f9c58b13d03ed6c5" - }, - { - "ordinal": 5, - "sourceHash": "f0646b2f9c636d6649ae60527b2a3171e98f1667369d7bca95825102773f09f3", - "targetHash": "5e83c73b6bb8440c2039d7b0961b946b8efb122076a9a319cb6299aae81fda5f" - }, - { - "ordinal": 6, - "sourceHash": "fc03e6bc382adbe5a20029ffbb9d84bf52481670141c960b6ee9daa7188efc37", - "targetHash": "fd5c6a6cde29106b250246e87a8cefac8b065e49e2324c313da280b1adcbc103" - }, - { - "ordinal": 7, - "sourceHash": "114ac52f6a6a08e00af88d925c557453cc899572151d6638fe5e6b485b98d7f1", - "targetHash": "eeddbcb38d649a9925df85e272adfd61bb5d3224bd09379256550f2c5d670cbf" - }, - { - "ordinal": 8, - "sourceHash": "1f55a6c4e2413d61a0c260b94b1379c3ba5381dd3fddb553d5068f8784585b6d", - "targetHash": "ce369b79a7e86ba1ec735801712b3209da7406c2eb97567c9b2da689ff960c09" - }, - { - "ordinal": 9, - "sourceHash": "10a2bfdf68c81051d2f8b0fbab24495a609c1771531462fbf9868e9bef0bc320", - "targetHash": "1282710a648b2c4ce6f358c0d742353f9d0411f2cb038224d986a2ef48115f44" - }, - { - "ordinal": 10, - "sourceHash": "bab9bd3ed3aa17a1a152fa893a422014284ab69be0c24b7aa6576647c333335b", - "targetHash": "078b288e1bfce8f69a0336108fed302b9640b776b8264c532755cc10f562f2f2" - } - ] - } - }, - { - "id": "core-reuse", - "path": ".agents/rulebook/architecture.md", - "anchor": "core-reuse", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/core-reuse.md", - "sourceHash": "81f1f41f250d478973221b4e118e33d2a2a63e38dffcf4fe0eb1f0e541382b22", - "requires": [], - "paths": [], - "tags": [ - "core-reuse", - "new-boundary", - "ownership" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "1d1f7d4337cb7b3557772df8bd5c15ffa860c75c2437d323fd40a229bc7e0efc", - "targetHash": "5110ab1c16365bf82455f7973b4d4d795f677f395ae9f9df7fd052958fd6b57e" - }, - { - "ordinal": 2, - "sourceHash": "6fa5cc593dbe1d5fe96ff5e177c49a6b4feecd18f9cec91e80e7dcbec482cef8", - "targetHash": "3a0267e4d2d341ec997e02e6c0ce7d2bab535e93cb4c478da1a6b8bf2f059d6c" - }, - { - "ordinal": 3, - "sourceHash": "43025970366c56e171047fa7cc31fb9ad071cd667dfba68297c36756f02e73cb", - "targetHash": "5f82bceb744a6fb021aea81059457bf115a54f4b388adb979bde1db0755d10f9" - } - ] - } - }, - { - "id": "solution", - "path": ".agents/rulebook/architecture.md", - "anchor": "solution", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/solution.md", - "sourceHash": "20387390e2515fcecb193685b6832b6c072b6f9ac77528104274a70a01961346", - "requires": [ - "csharp-standard-12" - ], - "paths": [], - "tags": [ - "solution" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "4065ae4b625383e39bdc3924fc4a77e9eb8858b53a3ae6ae65343eba51e5ab7b", - "targetHash": "30135c42cba5ba64d85f4bed5b342cfc6fb42aaa9b2ecfcd95c6ec654a76629a" - }, - { - "ordinal": 2, - "sourceHash": "bb60b33ba54c7336e9799166c01b4052d126a112d4722915e3904b66fc4b5ab0", - "targetHash": "0483b55fccc5f6d01514232acd1f02e3f183882b5577f3b00d9926260bd982a6" - }, - { - "ordinal": 3, - "sourceHash": "96c711350d8ff162324062dfb4b49240d44be6a667a5fd42a42bf590c3a5e3ef", - "targetHash": "795bb85622bc01870e1e65eccb18705c1218060ae36969d3b6b356499e658d40" - }, - { - "ordinal": 4, - "sourceHash": "fac2752dd3f41f02a5029638af0b428b76cd57c54b1e806d7075b11720f6e4d3", - "targetHash": "8db8f6984ea6d97e8089f27c6d194ed044c67bdf33f61d890a137fdba29101fe" - }, - { - "ordinal": 5, - "sourceHash": "24eb6050ce21ea7ff4821e7c8829d4beeed5e4ffa67e27dbff16f278a535ae78", - "targetHash": "58bd97d696b2fb242b9115ed807e9f25c231ee908b2d99a46b3187d29e8747ee" - }, - { - "ordinal": 6, - "sourceHash": "557d3320b8ef8a82bfa2902a8aebd9d3645b7084fef20ec6932baa3c00b35c77", - "targetHash": "ea5a66ec42e2b16e5433a1bb9ac555169660b9be567d296b7ad8fb6425c98c19" - }, - { - "ordinal": 7, - "sourceHash": "25a9c3360ddadcf3681147ed90c1d86a63205a903b3dddde86992c1866b32e79", - "targetHash": "7ddcc1494b4e535474a0bd52ebe4f29e8063b9a84fa51409a8618a561e7dea15" - } - ] - } - }, - { - "id": "naming", - "path": ".agents/rulebook/coding.md", - "anchor": "naming", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/naming.md", - "sourceHash": "ac51c466873569f50b4d319ede1e533d53ae6eaa4cf2ef63709b37dc80e20f30", - "requires": [ - "csharp-standard-2" - ], - "paths": [], - "tags": [ - "naming" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "a2ecd34c1a38ff4e0cdb6b62b29b72798eca5e7d8200ecee596a0810ef2cdb97", - "targetHash": "c03ed48491913faf71c543a24a31ffca134b16b52e0474d4e89d7e6e14477ead" - }, - { - "ordinal": 2, - "sourceHash": "23ed7825005c55de7bab25a13ad15e4d6f9003fa963e9dc6c8f83f25aa156aba", - "targetHash": "ec60fa8773db69f2d94c5e28c5901b9ce970d29f6002af8e2da7079b5b4b0b56" - }, - { - "ordinal": 3, - "sourceHash": "7146fd46302f8cb642df8c5543f331a66155d896ac1e73a902b4225731cefb22", - "targetHash": "93840a0814cc3a178726e86b61586d956121c64a4d595b91a60420ed80470b3b" - }, - { - "ordinal": 4, - "sourceHash": "1254fc0af71afb409b4898cd71bc434108cda6aff826f68e79fed35a059b7a43", - "targetHash": "a68bfd544c316dd8bd4140f7eaa5a16ce35adb1d0d0afcc885249f509ede18b4" - }, - { - "ordinal": 5, - "sourceHash": "c7d1597e6822b378b28cff3f9a6360068544ad29df7f7118e736d012ffb58230", - "targetHash": "e65985a0124327bb5ac46f97c457fd9c8b6678a6df1abf6ed312f65deeaf708e" - }, - { - "ordinal": 6, - "sourceHash": "de1e8fc2ce15a3e73e3f8a940abf54b6279a7d557154acb8298b5e688b8d82b0", - "targetHash": "c1fb02fbe518037ebdb862c96b2a42034e86f230c99fea894caee80f23f2290f" - }, - { - "ordinal": 7, - "sourceHash": "00238457aa080323c071fbab13a30fba20d564883baf55386c4e2b878f67da94", - "targetHash": "7eb5975ceb7bb9091a8d1b602e78a93e5bd4e2406777c26d8596810568640a99" - }, - { - "ordinal": 8, - "sourceHash": "4dd1a89dc1b7a7b4354e70948fc01c4ae5993733201c0ff5bf7f4713a5abefcd", - "targetHash": "91ea145a10ba903fb71233bc29bc0a1edff9378d31569b1b5cc5e889e041a351" - }, - { - "ordinal": 9, - "sourceHash": "779100086672741a3bd94e2b881aa35d8217edd739afdd017731e3983cff3a3f", - "targetHash": "aa807bb8015d7800fe77d0bada936898d50c066e8adb761d41f493812f0c4453" - } - ], - "amendments": [ - { - "ordinal": 3, - "previousHash": "93840a0814cc3a178726e86b61586d956121c64a4d595b91a60420ed80470b3b", - "currentHash": "d4f1f0c0003033b2daa7ef05b263d0cd3942ae18da7e97f075cebb6930495b3d", - "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", - "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" - }, - { - "ordinal": 8, - "previousHash": "91ea145a10ba903fb71233bc29bc0a1edff9378d31569b1b5cc5e889e041a351", - "currentHash": "6e1c308fcb9476541b9d05ec0e1d1229bf66412bf8729f1c0fdea297e2a49821", - "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", - "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" - } - ] - } - }, - { - "id": "members", - "path": ".agents/rulebook/coding.md", - "anchor": "members", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/members.md", - "sourceHash": "c2d7dcf9f01fd35785f5ca48ddab736ef338c05d6c3a831b979fa9ddacf6feca", - "requires": [ - "csharp-standard-3" - ], - "paths": [], - "tags": [ - "members" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "aeb83b2e3122df1174d2c41aea66196c503afe2be00362b0bb36455d2c95f535", - "targetHash": "085917a9e331374bdbffe0ab1b23a54a59b4a786efbd15cb1e6211b58ae5e819" - }, - { - "ordinal": 2, - "sourceHash": "155b573531fa878aa6c0186be8cb195d0df3cdcfeb74ae9ef7426d4de92344b9", - "targetHash": "fe50f60ab778c20cc0d21a6ad0822b8d1d74fb9878eca124ed11172b8171c8ee" - }, - { - "ordinal": 3, - "sourceHash": "21745673b0f5b00b93e217086d16c7cfb6032c6072c4a8a21d105e98b157afce", - "targetHash": "ff288d2db1925c5d45c15b8e615ae98de4fd532318df01077cd63da01c538e42" - }, - { - "ordinal": 4, - "sourceHash": "1013fa4a85db1b26be138b031f945ea3898e6408263acc3f8fea609270dbc4e5", - "targetHash": "974c2d1b934e4a8bf03e45c29cd7986379f5004432d6b221abf110ab1a0086dc" - }, - { - "ordinal": 5, - "sourceHash": "2be3e9229479242eb71723a3dc5b8fd0db9c7c77bfc06734362afb2177fef038", - "targetHash": "699a9572ad5560136fa23325e5c7463536eb0183ee14165e6cbe882dd9ad841e" - }, - { - "ordinal": 6, - "sourceHash": "15180fb47b019f533b39b45e4a634ef50ef086c781beb94a9d1171104d4f5fb6", - "targetHash": "5cf1e4657f622cfc45de3ab16fff72f5aa3633d483405f433ab89b3c0ae93d41" - }, - { - "ordinal": 7, - "sourceHash": "c00132896f827af44bcf3278f821645a1f0abe390cfaf5937bca68de30091b17", - "targetHash": "662c636b28489a240e62e4e4ff0eb0bf67ccc2b9f8b94ed461cd2ea88fa8bfec" - }, - { - "ordinal": 8, - "sourceHash": "96bac172645be96150f5d526df8293fb2e45ace5d28f1aa833e97cb8a3207b8a", - "targetHash": "23eca0ed30fbc3112f9912c8000b3a7e6f84dc4e30995e7618d995520476968f" - }, - { - "ordinal": 9, - "sourceHash": "42c62c7d7814e5d5233bdf69c66252172ddb30d91cadd2d789f390959fac14ed", - "targetHash": "84739f16c81513c858158016ff5eb127eb0a32313a8f8e08611418c8062fa91c" - }, - { - "ordinal": 10, - "sourceHash": "6a0621716390e0c953ed9eed37545093931c0c1eaf280210e4c8312a6981ac9e", - "targetHash": "26bf77b12ee406168444733e6cda0634672562df93b7fe79929b10b2572f16b4" - } - ] - } - }, - { - "id": "xml", - "path": ".agents/rulebook/coding.md", - "anchor": "xml", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/xml.md", - "sourceHash": "393dd0ea6825ded193ef10f1d6b114980d329af7a8c4bb4413a73b23e5aa54c3", - "requires": [ - "csharp-standard-6" - ], - "paths": [], - "tags": [ - "xml", - "public-api", - "documentation" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "7a3b010f1f556a0a4785fa2e0690d44e293735d9be73d684a173591be07c5793", - "targetHash": "7e1614602f9fe181223680359ab1f5bd48a8eb13c3df4636a7aa391e35d523fb" - }, - { - "ordinal": 2, - "sourceHash": "6b3170a223fbeeaa9708f03854dd47d7601bcc74996a78b9d7ec626f11fbc9d1", - "targetHash": "beac146b517f48ed476a18e9aa7f2fdab6820f3b4fe0541a84f7260f58c8c9d7" - }, - { - "ordinal": 3, - "sourceHash": "d612096e688a5c09d76a1b76f752ad16fb46152762b19175c5d3cd60ebec09df", - "targetHash": "c41cdb59a1d92c4bf77c05f55c2a0f4e8b120e04c75c0bfe4b4ed9114c2dbee0" - }, - { - "ordinal": 4, - "sourceHash": "7f1ffd3ababd147eefcbf539f98b37a7b1f72c71d90bbf1fb67063aaedfbd7ea", - "targetHash": "8d3a7e677d859685df4887afe75f337b6580c13a1f6d0ad8fad977762e900b50" - }, - { - "ordinal": 5, - "sourceHash": "8506f6d7df6456cc94e41eb26b73a779e56f702613304ca390a1ef7335a3a459", - "targetHash": "081c51b97a049870a642efb380e6f0c8f7f599f345b23bd7374ca3451eda903a" - }, - { - "ordinal": 6, - "sourceHash": "e1028d8d116d4bdf5be75dfb3ddbdb695cb8ed7635b7fa715004fe6a57545d75", - "targetHash": "db70458ea56d2cf1058f3dfdb653e179190cece63fcc31eeb175e8eb0d60cf17" - }, - { - "ordinal": 7, - "sourceHash": "d7c0d0b86975a71c9a0e05f68035490cd17dee25a52f1ee0de47b8f3e516984a", - "targetHash": "948a3d51f81a8080165a9873f3047e95d622f66af4c5f026f680691ffd35958b" - }, - { - "ordinal": 8, - "sourceHash": "53a79b0ffff61e3c64fadd0822b5eaf64d9d86c64f03abc4f10662923ebec648", - "targetHash": "2d5ddf314df4b45cfc643bbb67ee8f27f0d473a331e3430a7c21efe94762a9bf" - }, - { - "ordinal": 9, - "sourceHash": "230cd76be9c06b7b0154b24b64777add074d6436884be6cba68c8ebd6ebd887c", - "targetHash": "88c9235f5140174c3ba6859d2daea92448b59fd05a49db081cf9cbda38dd7a90" - }, - { - "ordinal": 10, - "sourceHash": "0771e910c76a4d4fe8240049d51a9777a9ca6d429b972d2b7f37c3915cfa24f6", - "targetHash": "ead7747e86c87d719e3f7d10f04baf07c58081893fc8eef642e3667041e763e1" - }, - { - "ordinal": 11, - "sourceHash": "59a8922dc82b328b1745c0f3b91fc0db931b0eb3fd0e3c26fdf6b18bd3f38ced", - "targetHash": "7a58317c4532181f9281b4245b89cf89416e5c7f789ba0d4a89909ba300d0c4b" - } - ] - } - }, - { - "id": "errors", - "path": ".agents/rulebook/coding.md", - "anchor": "errors", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/errors.md", - "sourceHash": "30704c6cf70560a9fc721937bcdfd23a425314b3023129c0d49d3fa310b051b1", - "requires": [ - "csharp-standard-7", - "csharp-standard-8" - ], - "paths": [], - "tags": [ - "errors", - "ownership" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "6282b05e7b7c40379cabb5455a04cc3cc13d17b37590554705a48af0d4f9c168", - "targetHash": "f633ab87a742f490f6844c5a76ade2c82788cf7614cf8940efc494ece6359aec" - }, - { - "ordinal": 2, - "sourceHash": "0980b1aadfe2ac68f2408411a4c8faa47d4827bfcab4626fa364d341f1c740fa", - "targetHash": "b00524a3be4313da355adf562e233fc3f040313649c6608e091bae13d0eaf4e2" - }, - { - "ordinal": 3, - "sourceHash": "76b50f93158d312ca2fdf09d100930fdac90a842695d5d71982bc1e62d47187c", - "targetHash": "397927257f1a6166ae6e517a14b27d64adeaf1f1114445342e8eece6f6e4f56b" - }, - { - "ordinal": 4, - "sourceHash": "4976e70e627ac2a6a257fa2480583a521c47ebccadf5a58e480b1da5512e369a", - "targetHash": "454b07214dc2ad21ecf0626da999dc93ac75863293ff9267ba6186a0c05aba58" - } - ] - } - }, - { - "id": "identity-naming", - "path": ".agents/rulebook/coding.md", - "anchor": "identity-naming", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/identity-naming.md", - "sourceHash": "200622c79a19914f1fc0a446f45ef0435af2fd895cc21f3eae3e8d04caf8943e", - "requires": [], - "paths": [], - "tags": [ - "identity-naming" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "94f2925d0a44f1b14240ee545aee5a3bd93c870898c4c93a12080cfb8de69f8d", - "targetHash": "2bcd9bb11b125445662ce6cb27bf034526113842a3865910a96d7abc9580c79c" - }, - { - "ordinal": 2, - "sourceHash": "5b08d747721d1fff4043b5b4cdcc9ff5a2012f5b2dc38d6cc15d1005115c3458", - "targetHash": "2713b77ce0dc27d740dee0e57723fa3d23d3d680decd110a02a647f3cc645fc7" - }, - { - "ordinal": 3, - "sourceHash": "4ade080ca04bd3a8af8c5cc2a079c0d7c576063df419672c0beec9f8e88c58eb", - "targetHash": "d420312b557f9c342f653da36246a2d21c4e3207e3da9a3a40b6a3fc64e40659" - }, - { - "ordinal": 4, - "sourceHash": "714ca4b88d20ad2f599c3e8c7287cb819db79eeaef3377ce67c9590515568ca8", - "targetHash": "2804cc91a2b24bc15e9da3dd4221dcb713b9ff097b7122029bebd75b0825201c" - } - ] - } - }, - { - "id": "formatting", - "path": ".agents/rulebook/coding.md", - "anchor": "formatting", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/formatting.md", - "sourceHash": "a1ea00ddad629daac88c8803b1f3bcac004a281b7ba86d761467118270ccb4d2", - "requires": [ - "csharp-standard-4" - ], - "paths": [], - "tags": [ - "formatting" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "15ffb0266967a20a678fa44d3a1a861394fd38c234e1994ac49f3c842d4a9377", - "targetHash": "cb43e57656d394eecb667b5a91bf099d57955790fcb3ec79047c13c41c087a9f" - }, - { - "ordinal": 2, - "sourceHash": "a7180c7b2a595dffc271bbf430dad6da72ac8dbabaa7a713ac746d3be7bdcbd9", - "targetHash": "2e5009668d2b80970bc549bfd3b689fb956a9cbc8f6e46a17a8a993088ce1b4c" - }, - { - "ordinal": 3, - "sourceHash": "31891a8a828b1709293b0f1f3d81067b15c1e35e0a9e8b2f6ef6149a56f0c635", - "targetHash": "e46c450ce7289e844808b05542a5405de9c3cc5223da703962351a2e8977ed03" - }, - { - "ordinal": 4, - "sourceHash": "95e12ed427e31ee89b53ebdd3551f8b671bb56c5d8d85a7c141127c989abfcda", - "targetHash": "9259801cd440e5cc5b6b5cd2fed583eedacd34d58d7996ce25a85593eb4737f3" - }, - { - "ordinal": 5, - "sourceHash": "8338542136dae7aa818b9446f5050658f3e1e89402c0c97e9d4f5abcc8b7d0cd", - "targetHash": "e1769de8f4cfb3964abe3c2337c13ebc543581c165c1db1b9602c1b1daed3002" - }, - { - "ordinal": 6, - "sourceHash": "41874671f58ef7bc6285d79b4539b0d61ea6e5787d16732d3e2493d84b043ba2", - "targetHash": "0037d6a15be093a1b084de5f680f593450f1e932905c775bb4f8822fdb307be5" - }, - { - "ordinal": 7, - "sourceHash": "19ef285a86c7baaf07c63b9a8fc5cd74742cfdc2048821333f3cf14a22acb7c9", - "targetHash": "0d0d8f06fb572349230c1faca233dc503361e135e9adb9d3b429d3f973601201" - }, - { - "ordinal": 8, - "sourceHash": "e37bcae5aa76b76e6688c78103d6163a25fc73ed080c760964579585038c086c", - "targetHash": "26d1fd9f48b300d262bf87e7122e38c49037aef35b791538082963a728ebab00" - }, - { - "ordinal": 9, - "sourceHash": "00ab8e1bf5ec15ca8c2df55c202cfcd4172b471b8fb6ee80cfa15a58bcbaf1bc", - "targetHash": "0bac228dd3b888345ff647461b01c6ad677caf65942c708d325d28739e3058d0" - }, - { - "ordinal": 10, - "sourceHash": "71d91f2dd249257949dd61c65bcc8ce6de0858dd093b4ce579a994233d78b1b1", - "targetHash": "9a29e75e154d9dc75e58f929fab1f2395c4421445636ba3ba09c02ffecf3eb58" - }, - { - "ordinal": 11, - "sourceHash": "0d3623254a13451a943b452751857f006364093dcc0d75d2f55ca78a5af96c6b", - "targetHash": "0d3623254a13451a943b452751857f006364093dcc0d75d2f55ca78a5af96c6b" - }, - { - "ordinal": 12, - "sourceHash": "220a360337c27b13b8b71061abce48e28d1e15b2be35f926d7b5073d2469bab6", - "targetHash": "220a360337c27b13b8b71061abce48e28d1e15b2be35f926d7b5073d2469bab6" - }, - { - "ordinal": 13, - "sourceHash": "bd72eb58404a8ec9c955888629d584dd75f8fc9c16ec823e28b7c8b33582f20a", - "targetHash": "bd72eb58404a8ec9c955888629d584dd75f8fc9c16ec823e28b7c8b33582f20a" - }, - { - "ordinal": 14, - "sourceHash": "292a1cee656bf17bbba7105dd15078649bbea67e2c0595da61ecdf76cd982017", - "targetHash": "292a1cee656bf17bbba7105dd15078649bbea67e2c0595da61ecdf76cd982017" - }, - { - "ordinal": 15, - "sourceHash": "abfa59370983ca52fbab3823eb970ba6f336b6cdb702d15fb183e6cdcb5e4661", - "targetHash": "abfa59370983ca52fbab3823eb970ba6f336b6cdb702d15fb183e6cdcb5e4661" - }, - { - "ordinal": 16, - "sourceHash": "d726209c4b79b93a897f315bfe110bb25769be2eb1743210c8240ba3db71845a", - "targetHash": "d726209c4b79b93a897f315bfe110bb25769be2eb1743210c8240ba3db71845a" - }, - { - "ordinal": 17, - "sourceHash": "d10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2", - "targetHash": "d10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2" - }, - { - "ordinal": 18, - "sourceHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5", - "targetHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5" - } - ] - } - }, - { - "id": "wiki", - "path": ".agents/rulebook/documentation.md", - "anchor": "wiki", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/wiki.md", - "sourceHash": "f133fa3bf600afe23b9f9c689e2ec6dba577a8bb40e2d0b4e103ea03e33dad86", - "requires": [ - "documentation-standard-0", - "documentation-standard-1", - "documentation-standard-2", - "documentation-standard-3", - "documentation-standard-4", - "documentation-standard-5", - "documentation-standard-6" - ], - "paths": [], - "tags": [ - "wiki", - "public-api", - "documentation" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English modernization and subsequent API automatic synchronization / Docs draft-main scope and editorial amendments", - "review": ".agents/records/decisions/API_DRAFT_RULE_AMENDMENT.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "29dd21456d3528c0aad4b35e725528a51737d4655ded222cd7ca16ec0559ab25", - "targetHash": "b7f909e062f751affaff3e8cd4d7c98ea53a3cbc8f37a17959e3b0640fdc57a9" - }, - { - "ordinal": 2, - "sourceHash": "96ccf044ebe34361538ac4c3dac0fd3d2b7c9db5ad532b3e7837d04945d57363", - "targetHash": "9c171f3383ff9da15e8face978be93b8e1da13d5696517f201fd2e639cab8733" - }, - { - "ordinal": 3, - "sourceHash": "824b508de366ea12fd61e4d9654921f3caebb1bd6a482c8bfc82949010f8bb31", - "targetHash": "cc08880907c077e40ef8bdc501254fbbe9022842760fac1e7e32a52c0ca6f3af" - }, - { - "ordinal": 4, - "sourceHash": "103c5e61c0f120534a56a37d455c285452c869f8e2ce24a72806cd9a1ad4f16b", - "targetHash": "f69c49e7f0c709879f599f30063db2086b783e60971508865aff02748a194ae0" - }, - { - "ordinal": 5, - "sourceHash": "2568dc23c50d9799f22535715a1d496259248c52318d5280129d71d928a350af", - "targetHash": "a77e7aac30183eb14f83cc9c085ab9821dec19ae63f8bd6eafffaa48aaaa758b" - }, - { - "ordinal": 6, - "sourceHash": "5534ff06531b8f0e4dcede3a7409924a894a57e11848043c894a891cc226419e", - "targetHash": "f85f2d2ad085f23b258020732abb8034becd84c5964ae41c00d977df176afe47" - }, - { - "ordinal": 7, - "sourceHash": "d84e481c7e94dccb3d7646f58403de71f291ddf796eb607f6762b5a8cd1d077a", - "targetHash": "8495ee4427e26bb8a6ee37d6de19f92de7513ef9419398bcb4cf6e86a8a61b5e" - }, - { - "ordinal": 8, - "sourceHash": "8905a7d3ff5e3dc12c838f074a7eed0664d76a6695e44ff5a1f99d4f6b60f4a8", - "targetHash": "5ae53f3449101c75753f1d4f1a259267adf4ce383492782fcd10de7c815f3de6" - }, - { - "ordinal": 9, - "sourceHash": "0e1d603608acd5aa204278ec1a5b69fc0e271ede6c8edb77edf667a1b3868b9b", - "targetHash": "2cc05fd8785c66d75571462f5888b9990c8720bf6f6a402708e0b83cb784f6dc" - }, - { - "ordinal": 10, - "sourceHash": "06dbaecfd67f1807ce241fa928a76e1b9da9fc66c5e19457f8ee84e843d95c44", - "targetHash": "3d9951ef1257c276f5d3a96b0e7c482bc8986fe597fdd2e990c73d1cf1e36282" - }, - { - "ordinal": 11, - "sourceHash": "f91ef9d6d4abc6129c4ed63429a5786c8f63324d43544bc62422f4d51bd17cd9", - "targetHash": "58fad6bddd9ff0a3400450ce71641e40827a76bbdb53c19e0e035ebd21926bb9" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "tests", - "path": ".agents/rulebook/validation.md", - "anchor": "tests", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/tests.md", - "sourceHash": "08acc77e48825494e38da726f62129622ae84b2624c745fb3e3665ab6475f5a3", - "requires": [ - "csharp-standard-10" - ], - "paths": [], - "tags": [ - "tests" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "c666816f0894af76a5be080782b59d8a8c0d15a85d4a6d1e8fa88159085ba12a", - "targetHash": "71d8db9a48a6b37684c19e104a5c612b12efeb672a315213569cf409397341fc" - }, - { - "ordinal": 2, - "sourceHash": "e1b8470579451b60155c666adec815c504850c61de7a9b4fc16c94d61d46a3a7", - "targetHash": "c34aa9c4c84ed97426154ff61d3e1bce0628f3cdb7cf039c5b889c4f2ae1e82d" - }, - { - "ordinal": 3, - "sourceHash": "30a3e74ba432a5d41617670f4d683c3fe3cbb6f17af87327fe243715539ad60f", - "targetHash": "0080a897667020bb6af2025af6f10bff06651ab19251c850ebd8189bfa6ff76f" - } - ] - } - }, - { - "id": "compilation", - "path": ".agents/rulebook/validation.md", - "anchor": "compilation", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/compilation.md", - "sourceHash": "1eee0e7df80eff706cfb890d9af48b5b0d4da8ea26ea6e16172d750369af3cdb", - "requires": [], - "paths": [], - "tags": [ - "compilation" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "41e7c3bb71db905e291e0d73dc660314ac65945b98be0d6044e25bca9f7dcb76", - "targetHash": "1ba3e574076477aa95f3fed742515edd4e22378d7041dabc7dd72e1ba6de8ac8" - }, - { - "ordinal": 2, - "sourceHash": "a743bcef487abea16b872c402957ae77f7060eb95df7e2a912abd615215f0cef", - "targetHash": "a204c03670687042691bbfb56ba3981bc162bc516a14e05a589db9328b1873e5" - }, - { - "ordinal": 3, - "sourceHash": "191eedc7864cd1a54ce09fdaec1018a177b1364934c04d1d7b6ea850f6d3e6ad", - "targetHash": "19960351775059c13c3bf2ccb3ce451bba20e8cc0c16fd74b00724eec00db7b2" - } - ] - } - }, - { - "id": "completion", - "path": ".agents/rulebook/validation.md", - "anchor": "completion", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/completion.md", - "sourceHash": "4dac1cd4f65641310d3e2d43ff402c91b56ab43868072cf219154ec861a8f391", - "requires": [], - "paths": [], - "tags": [ - "completion", - "new-boundary", - "rules", - "skills" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "cf73b7afc8d1c43a34e8307a65608c81b99129538e169bbc882aa89d02987956", - "targetHash": "e93bddd549b254c29da36a58d11863f98ac962467bfb6f59e5f8d84997bff161" - }, - { - "ordinal": 2, - "sourceHash": "b8e41433b5af0edc8f9e61054e6ac81c6aa2cacd0d90bbdbab1fb3b889c54bbd", - "targetHash": "50c049e7626af91e85a48625b352767356976794cd70460159a9f031323708ec" - }, - { - "ordinal": 3, - "sourceHash": "73e27ca28caa6f4e6c6f7cd1fe54ca2dc8e49e2ba15490ce7c5b1068354f8c71", - "targetHash": "cbbe4d856b6f17019688e721d7ce90667d36df2a59ccae9ff90325f50d4cab04" - }, - { - "ordinal": 4, - "sourceHash": "cde43bdde3090f6b7947886e50001b552d09d461f5ff40a0914968e988446ca2", - "targetHash": "9a46ff44b37d46c5a25c290b7730653dce6d57495aa98b26f22c1a3adb89f498" - }, - { - "ordinal": 5, - "sourceHash": "49c25780621007dcc71be5f2e2b4f4b002de2b0a9d96c40e81d193604c75f2ab", - "targetHash": "8d7d2cb58e7e0d01d42d1a49fbdb9c521b8fcfc7a503400100a292cd4be941c3" - }, - { - "ordinal": 6, - "sourceHash": "c9950b8ac4190e36f1941ec0d592853ba28171f1c75724002906cf5eb1bb4b4d", - "targetHash": "3325bd1c35ba13ea900f2a1d311afdfb36ccf2c97187043c7151b25336d5d56f" - }, - { - "ordinal": 7, - "sourceHash": "24a6745290c0969a46d0461042c788fabc2e4d0d0b69b3d355aebe16f7de0e92", - "targetHash": "ff823b2f21dc4d5d21e106aaffbf5c5651ae2d918e50e4280055927da58a197c" - }, - { - "ordinal": 8, - "sourceHash": "38808df39142443fd505e2cadbcb49dadb6cbc8e876d68b23fdf516472173de4", - "targetHash": "3628b29e12c796edde653461ce6b6c68ea22d00eaefefcee55cdd72e00887879" - } - ] - } - }, - { - "id": "review", - "path": ".agents/rulebook/validation.md", - "anchor": "review", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/review.md", - "sourceHash": "d50c80da5e8711ba64a368e4702b72a6bcfd74cfa244dc5be4841e431909a14a", - "requires": [ - "csharp-standard-11" - ], - "paths": [], - "tags": [ - "review", - "public-api", - "ownership", - "delivery", - "rules", - "skills", - "records" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "e59fde7855e2854f5bb618dfe8f567e384bf2f4b7aea0374309af9a63f6295ae", - "targetHash": "2b380866737ba2ae9bb35b5bb74e64335a375297476a298b8b2d3819cef64f1b" - }, - { - "ordinal": 2, - "sourceHash": "3e0df150e5273f71eff27bbbc8671a331f09cb12a5c07a96c8e861a64bf28ae3", - "targetHash": "d2de9e4e7dead46bed8bdd02cd62f88fd8a4dc7fd5919fe7c35246dd42a47c46" - }, - { - "ordinal": 3, - "sourceHash": "1d25bc7acfa0735c58e3814dca382bf3234a0e7d965325e173bd88a903c14af4", - "targetHash": "718c54731d8094e34a332a646726fcabb768aff145338555d967fe2fe537e775" - }, - { - "ordinal": 4, - "sourceHash": "4c780ef5b65a99dad550c107a7c514591d3e2812ddff8d00cd308978579b15be", - "targetHash": "b5af8f7f7c5b556b5030eedeb74b12ba7c0b47abdb819ac3d06dcfc7bb4ff51a" - }, - { - "ordinal": 5, - "sourceHash": "009ca6574de647708b05c24de08073f8af6183a5c3b7fc0abbcf5fb23fe9ed39", - "targetHash": "e15d9eec2ecc8ba2bc85a5115eff36f54181b0a457f730082de4439fa5bbf59a" - }, - { - "ordinal": 6, - "sourceHash": "33c44f2b873bacb7822af7718aedd66c8967bd7cc3e1ac6f8a193caa4013a663", - "targetHash": "cc2046e1746a60a30a83b59a2278a35c7b918fbe41cf4de4fbd22232463c3344" - }, - { - "ordinal": 7, - "sourceHash": "e3dbaacfefac2daa3eef9aba4b6d0d9656b068941246544f122f5ac40e767e6d", - "targetHash": "16c75b1f4fd6c9e3ad3b1188a4b78c09a27e30fad55ceb9e0c7dd25b94d55285" - } - ] - } - }, - { - "id": "delivery", - "path": ".agents/rulebook/delivery.md", - "anchor": "delivery", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/delivery.md", - "sourceHash": "2885f4b1c8b1e7df776974fe199eb1434472042809972ed3be880e06ec65896f", - "requires": [], - "paths": [], - "tags": [ - "delivery" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "b86e8824d8bca39066e9cf7f6cf8ed191231dbe4a6d1402aff14debe8a722ab7", - "targetHash": "75bdf71fe20e4ae0db067be100a3c2d383faca67c136eb364f1a1ad67737da39" - }, - { - "ordinal": 2, - "sourceHash": "3b1ecfb344235b63cb4015fa1548529093f605c5673ae454bc1660106d7b3d3a", - "targetHash": "b67c64583f6b8dfc7eb0706a3cdf820e5e138fce3dc57b6957775ace596f9df0" - }, - { - "ordinal": 3, - "sourceHash": "e5bc32830644660581c3286a3d352fcf4828b676c91c116afa23e08b48f00c85", - "targetHash": "68b629f0d9e3d314f21508e9a2e2267ddc9cf87d80f08c64b7fe80154fd67b25" - }, - { - "ordinal": 4, - "sourceHash": "5101467f70d294ab413e4befbd85c00c6717a855cf3fbee0aa1b24c48467f2c6", - "targetHash": "2c0cb58de507485b88f08d2823a84dbdb3ae16fcaedba435b7ce4ac6843873f4" - }, - { - "ordinal": 5, - "sourceHash": "f67f47be3449ea304ec5c3279342840557c75efccf63bdcc783df37d2d974053", - "targetHash": "4c4fefa0ee638f7972f8c844c775cb7271426e48aa62cff4424e65448f1286e8" - }, - { - "ordinal": 6, - "sourceHash": "de6a01673254e95d66beda0153ba848d3f808fb9e3164e41d4561dfe6d07aed2", - "targetHash": "faacd093eb7499bf0665183a078ed48662b8b4e6e81a754b834705c231dc08c4" - } - ], - "amendments": [ - { - "ordinal": 5, - "previousHash": "4c4fefa0ee638f7972f8c844c775cb7271426e48aa62cff4424e65448f1286e8", - "currentHash": "b9af9afc94393f7f1d5f2a036e4581c37537d7f7ced82986b4228978817ec4f0", - "approval": "Explicit user instruction, 2026-11-21: a human vouches for every commit; no agent or application attribution", - "review": ".agents/records/decisions/HUMAN_COMMIT_ATTRIBUTION.md" - } - ] - } - }, - { - "id": "notification", - "path": ".agents/rulebook/delivery.md", - "anchor": "notification", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/notification.md", - "sourceHash": "fb194215eb09cff4767222c9ba6d7c40d67ca7605f4f5a8acfeaa0927e65b3ff", - "requires": [], - "paths": [], - "tags": [ - "notification", - "delivery" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "79f37f44bc331d7924d62bf9f4247230ba284ce9399f74f9b8dedb52232bb557", - "targetHash": "a2ddcd88b762633cba624f02b97aeb0c95f4d4d7f35811fc44683ae8b46d6b0e" - }, - { - "ordinal": 2, - "sourceHash": "1df3e0e0a5f191314228a4d5be1242bd096be2fa118a256e29d168b2a59bd9f1", - "targetHash": "ef7e4415eaa30f14c183aa9ce389d8c2205d0001ba92c481a2655185b09fa200" - }, - { - "ordinal": 3, - "sourceHash": "8b74dc6c1bcb5502e35ce4ba58d7ca4be4828fb387862bb479937ba101029a76", - "targetHash": "13791b5add506d7d6991f492648a2a86e0ebfebb703646ce47857557dbc3eea9" - } - ] - } - }, - { - "id": "editor-projects", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-projects", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/editor-projects.md", - "sourceHash": "d9d573caae906f0630b035ec9a3bfa54a80a3c50599f7e7c5cef9341b5a60077", - "requires": [], - "paths": [], - "tags": [ - "editor-projects" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "e96d1c62c661cb5454c99143fb5f1a6cc8fd33daf956ec7a820ef4b755e71c7b", - "targetHash": "10d2588f823c1749153de1f3e501e661e1b4ca29c4e20fd176f84957f3f8e96a" - }, - { - "ordinal": 2, - "sourceHash": "9443cafc9093dae4fd32a2c037d02de87486add1e4cc1b52377cd1f94a125619", - "targetHash": "b5559064539f4b6b66250bfdf2e6d88dc318169e195c3b687e0735829633031b" - }, - { - "ordinal": 3, - "sourceHash": "4f5e5aed6897ace5c4b6cbfdb87904d6a6a8929cd0df981f479cee26ffd96743", - "targetHash": "39faedb7db5aab968faf5d85d5e00e3ce311a714928a0c0e187c7219ffed2d10" - }, - { - "ordinal": 4, - "sourceHash": "84cc6095ce04a31a8beeb1661912a58b8de562db0624475248f755b77a0e20e9", - "targetHash": "dd03d5a1ab0cc5f3b2c34f8f04f1763797fd42d79621c86ffef90dfceafc926b" - }, - { - "ordinal": 5, - "sourceHash": "5fe6ec264db83e6748ca0ae5daa13968f80aac8d6d005ee4e2ded8e32199491d", - "targetHash": "32d84d8fac657689afe63348ff0f5e41562769c11bd91a1d17e2beaf27850d97" - }, - { - "ordinal": 6, - "sourceHash": "bb394f03ce7c3962d38eb892f3240eeca07f7582563dfaaa56a128c5f9956757", - "targetHash": "fa2bf21fbe0202b247506afd72d2cafb390661d703060b1b1e56c2afb4dfc095" - }, - { - "ordinal": 7, - "sourceHash": "f03c8af813a56eea5cf54f57b7a6cbe268261de47a5d1c06c63facc942081797", - "targetHash": "96288472fe332b65829a9c6502eede3ddfdf9708aded8e000a855062d2261bcc" - }, - { - "ordinal": 8, - "sourceHash": "ea83c11a5783a0e4674ddbf18b0bd8d13ae741d859ba8d18ad3ac2d57309dead", - "targetHash": "3f91286809466021084655a592bad37b159faca5722312122300f29dfed86e38" - } - ] - } - }, - { - "id": "editor-state", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-state", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/editor-state.md", - "sourceHash": "e72034747237a4a58c7793a1089a9edeffca5f3d5928f44421d622ea64cabc57", - "requires": [], - "paths": [], - "tags": [ - "editor-state" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "21913b4af529f3333c80fce2614de58bcee1cee8301d3a6965c3f557b10a4afa", - "targetHash": "b60c90ea3d239c0efad54377f869482807600201f2b530e5a717c685c69afad6" - }, - { - "ordinal": 2, - "sourceHash": "802beca59c3c5542e350400d5553b4376e4fd603b93289346cddac56db95287f", - "targetHash": "f1564be509a447142575c7444c71599d53f5e20b9a4c805c358575d5d13bcc78" - }, - { - "ordinal": 3, - "sourceHash": "ab15e73721074f5f58250e7e325e01403f065f8bf3ef26057fd9d4c287a2871f", - "targetHash": "790f7c69224b7ea64c5a0a1373b7a14b082c74ae3549aae36a6c28604ded12a8" - }, - { - "ordinal": 4, - "sourceHash": "4ab9e48bd4ad307a8eaf797efe07f0383ca83d3cf7a28f5f5c976ffcc21b71ec", - "targetHash": "5d944a27c3f73de2bd90576fdb16ec02ec43f96f87f011b13b9e4be7fcb33077" - }, - { - "ordinal": 5, - "sourceHash": "f439cf9fc6e91c8205613454bef02d000df1f466bce557863dcdb89daa5467ea", - "targetHash": "db8e4b6285cbc3f2db01c93c779205af7e79d0d183558548ddfa6b23eff5cc43" - }, - { - "ordinal": 6, - "sourceHash": "5e625d5ffdba8dc2fa694a43c0e2d06993f973f21f2582fa12e3613ea1f4bd6f", - "targetHash": "25300dddd17b788ff48a0592f39143241cfad86a73aa8d589947f59dc8630714" - }, - { - "ordinal": 7, - "sourceHash": "8f1386ba061db6235bb1f467ac5ff571974533e5ce32362da4692176d8f1d544", - "targetHash": "65fb119594d3e326fc2bb92d94600560f43a866c2118677e28721cf475b735ff" - }, - { - "ordinal": 8, - "sourceHash": "c886a65a41f603a5bea7387efe60e2af979dbdd589945ec485b82c5473f3d972", - "targetHash": "481ee912c2eb7d1469ccfa29593223c284a5cfee137eeed7e0e00ae3db19c177" - }, - { - "ordinal": 9, - "sourceHash": "11a421a9a00cf21080803c70bc4740cc226479a4c9adb1f5592e82eebd5e8550", - "targetHash": "cae6ec6b47f8f1ce871a5663c92db9336433bb4b8b91b33c12be418d81e42a83" - }, - { - "ordinal": 10, - "sourceHash": "80fd966faab70b6d56473c56b0bbffeaca4831ee75830e7195a4a7f8fc46262b", - "targetHash": "1c9714e407adcaa31fb97d2a9f3cac2df6f9bfa0e90fdf14d43bd4a7b08da6f5" - }, - { - "ordinal": 11, - "sourceHash": "6d61fb5dcecd2a282ec55c91f551fbf012adce132bdae2589a134bfeadd3d70d", - "targetHash": "a47795754591c1f7d048d40fe777c5ea13139d09d90f5ed5975b87947c1ececd" - }, - { - "ordinal": 12, - "sourceHash": "1e309e4880134bdf98872c3601eb16261a30b08ce818ce2919acb47877ffd8ed", - "targetHash": "45b8afb771f26069f27b34ba44bdbd20205c2326d0b51f2e7726138dbe758a8a" - }, - { - "ordinal": 13, - "sourceHash": "89047a47e41186f278ab244de7f51ef84f5a4fc8e33999fa99e84eda365a4b1c", - "targetHash": "6788b28fc30cfdf61c3bfcc1908275d0fefb87d4d7dfc090048307bf5a0eada3" - }, - { - "ordinal": 14, - "sourceHash": "ced6359a37b15683302c590a140cf9f9c5b8ce14a4583b80ab64082e9a164735", - "targetHash": "9da5caecada51f64b5e3aee43cbca9a0211a16a9d8d53ba8579e7d66d8e7635e" - }, - { - "ordinal": 15, - "sourceHash": "aa037a2eb62bc515463abef944986e311e5889fa1ee4bc031884fb591c405d61", - "targetHash": "f0e84b1b52daa6d016be5554dc787ce3d317b8a661ab91fc2fed8c3507dc1ece" - }, - { - "ordinal": 16, - "sourceHash": "38878299c8a97469089022a237b2896e3699d76cff0af54d8c2a21e8a68f453c", - "targetHash": "8084285b098674b7da1c0d669a65e729be5d82a42ef0ae513f99e065b5a02a04" - }, - { - "ordinal": 17, - "sourceHash": "d17b7484e2d5247bc6ed1dc891fa65149977f5d341c2079801f746c646c97843", - "targetHash": "79e84e819e757a783d8c88259ec68709db4c48ed616162650ff5d9f9b2b8c9ae" - }, - { - "ordinal": 18, - "sourceHash": "b8459066a743985e3556a91a0e8e30de69fbc32d33d2de7aa13e127e635f14ad", - "targetHash": "f25581ebde68849f22ca41e7f5740243e79236682060ba13ecd38681383d33d5" - } - ] - } - }, - { - "id": "editor-layout", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-layout", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/editor-layout.md", - "sourceHash": "5efec2d08af93248bdcb799473c0feffedb7252e6b79e21dd4e817a891853635", - "requires": [], - "paths": [], - "tags": [ - "editor-layout" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "0cc5f006ef001013725d7dfc893c2e4a3316801789d35046c34165d263d1ca74", - "targetHash": "b3d8d55da1736c8f726d1e953bc299dc44b4a601b75d871e860290eac0f5b761" - }, - { - "ordinal": 2, - "sourceHash": "a78da5ad23986a44349374372658a6557ee2d9976628b07e933721594fc468fb", - "targetHash": "10244dc31c8640f6338ea9fda49ed04d9b88f275d78a5d1ac0d9921647a6fc24" - }, - { - "ordinal": 3, - "sourceHash": "ff8188e23b8af5d3991c935b771b773a59598b7babf864d5b944150c0e013e27", - "targetHash": "a945b0383eb161ec90c28bcac8c42671649e0075ea4cfac4a64896aeaa1025e0" - }, - { - "ordinal": 4, - "sourceHash": "d2f1efe96013a971a0f435d8592204bebbe86ec48abb5f4bb537ad6b12f3e7d4", - "targetHash": "9a17d7b49fd799e072b6a9bc74ac804bab28a0b409d5c94355753fc174b07947" - }, - { - "ordinal": 5, - "sourceHash": "3376fbba35db3b14186fad6856628170c46b5ea568ec4da85d68e13a360df83e", - "targetHash": "2f686f33426418cf4f0f9eec5367effccd701e63d4c694cb7d6d15db75ced0da" - }, - { - "ordinal": 6, - "sourceHash": "102fc73957d8dcc7555e9f021d87b707da29f344e4b6715357256318c6944ead", - "targetHash": "8f0b47e959d0ede256c2c32cee6900ec3bf5e3d1a4b12238517767a4eff4a805" - }, - { - "ordinal": 7, - "sourceHash": "9aa7299366b57f5a1b1b5ca963563c742683e3fb6380dacb2af72d6e1d99fc1d", - "targetHash": "7cfd8c31799dd63abed0ed504917ff8314fcb6d63f452138228af79921b580e7" - }, - { - "ordinal": 8, - "sourceHash": "a60a708374ddcfa25bb62fbd311ec7a8bb959a60e3d74fc03ccb28777eefae77", - "targetHash": "426d40ba0085d6926ea69ecd5ef43299ae49bc34da5f6f6b5e5ca9dcdca8e08c" - } - ] - } - }, - { - "id": "editor-acceptance", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-acceptance", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/editor-acceptance.md", - "sourceHash": "90c48174dc83e59f7a4c41cb0fb050b7f66ca7f9ee1f3754e0080e2a2e4b0681", - "requires": [ - "editor-standard-9", - "editor-standard-10" - ], - "paths": [], - "tags": [ - "editor-acceptance" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review" - }, - { - "id": "identity-reload", - "path": ".agents/rulebook/domains/identity-reload.md", - "anchor": "identity-reload", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/identity-reload.md", - "sourceHash": "444b49c1e3ce53936fee718115595fdf49d01ac03ba1f2b51555f4700b4cc2d9", - "requires": [ - "identity-standard-12", - "identity-standard-13", - "identity-standard-14" - ], - "paths": [], - "tags": [ - "identity-reload", - "serialization", - "reload" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "7efd6f55cdc573ede6dbd3da88c1e062e81a9d08206e8eb6a08d33cf391c8744", - "targetHash": "461d9cd3c4b4965f945d82df383799cef81636ca050fec38fa4cc4fe823090e3" - }, - { - "ordinal": 2, - "sourceHash": "d04589d0ce99484f813001832e92a2f8411d2d1a4bc64aaff8175fa1e1475e0b", - "targetHash": "96e1a4c1f7b1276a60dded704ccb43f726c58f86c99b06fb62c81a191ec78d1f" - }, - { - "ordinal": 3, - "sourceHash": "975f6da00e76191fdb166d04c732a9d0acc77828f65b1d270c6aa94bd0b0d07a", - "targetHash": "99cd52450ef209e62d9b1df287979ed26fd21732f487649198a6d2e68cf53902" - }, - { - "ordinal": 4, - "sourceHash": "5c2f32dc18a4142ae2b41e7f0191688430deb3942f8d653c058ca5fb09ae9380", - "targetHash": "ce9dd22d95b882852ac19d5bdc44feb0d4b1a7b622ff2ee54226edb48d07135e" - }, - { - "ordinal": 5, - "sourceHash": "811e0a9fda7f7c75556ae181360e3af2a2c4a57ddf60a74bab1d17eabed0b896", - "targetHash": "43793c651d33494c2fca6270495afddf406398e15f21897b5e5d0c78b92c20e4" - }, - { - "ordinal": 6, - "sourceHash": "92829893c198c28c5c8f6d5fb3542e80f592ee4c6b362826cc9965d23506bb79", - "targetHash": "82d65edcf81d1ebab2f7445cfa727c37a2fa6515c7e8401499ea049bb1fc0471" - }, - { - "ordinal": 7, - "sourceHash": "63e109baa64f062a988a244a78754cf21234b8d3478124c99a0f3a5b131a4f3d", - "targetHash": "643d446e16b807fb946ce67a8e30bb8fa902dadda34e6209c76b922fe1724b38" - }, - { - "ordinal": 8, - "sourceHash": "da38afa634e638869a4aa17188dd56e7762b25c0d33026205f91a9df4fee53ee", - "targetHash": "7c4e21bb14ba0d418ef4bda4c9d861566f4440aec7dc9e80491f2cb49cae9cfe" - }, - { - "ordinal": 9, - "sourceHash": "54c7a14b2e0f3011f82089ee72b14d27f8963883d6ee166fcbc0e6deda1414d2", - "targetHash": "4f660e19e473ed31e64beb070c3f3e2ed7c4954a7492677ec27b73e09942e56f" - }, - { - "ordinal": 10, - "sourceHash": "1b7d6605e20bbfa15843a42196d806ce2b1d06b97b9c7d678304cc474ed022c2", - "targetHash": "0ede328f6a2f73b21505f069bdfa56c0a8aeb2f9e8ad69d91e25353f6b21e25d" - }, - { - "ordinal": 11, - "sourceHash": "036d942ebff4f22a51c0b0ccd9addc19f374304a7554e9992a545162b92395ae", - "targetHash": "ca4b44218ee5981e939f63225dbac05eb2c2bee9092f5f1a107e566e209d9919" - } - ] - } - }, - { - "id": "scripting", - "path": ".agents/rulebook/domains/scripting.md", - "anchor": "scripting", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/scripting.md", - "sourceHash": "80e8df6fc099479be2c0ff32979713e750ae82d3bfdb4eabf93ed80cdf3400f1", - "requires": [], - "paths": [], - "tags": [ - "scripting" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "ae7fac91b32b5c7a54822bd463c7e8c24ed5b911311cccf18ee32bf9e57c3bf5", - "targetHash": "5435c2ae2dfba123581a5d70711c3a7174ba2d5130abc7d3439d270ac1b1e273" - }, - { - "ordinal": 2, - "sourceHash": "5d9f37c482d7ed2d1831728bfe868cdf0ef116cf3dfda5a68ac0be5491c6b44d", - "targetHash": "dad28a5daedf52b61db2aed9d3ee23a1195f76b283bed2b140c76fa8048f7aea" - }, - { - "ordinal": 3, - "sourceHash": "5c9522580d5b894b7597f4f96ac9128b92e6635bc21fdf7fef209f33a09f14ac", - "targetHash": "d973ef9f713818aae14881414686d10cbcdd0dd9db99b0daa45e5311cebda0e1" - }, - { - "ordinal": 4, - "sourceHash": "500bf61050900845ef55695ad3920e9d6904499db3ac32b4ee13cd9a227c05c3", - "targetHash": "79c5afbb8bd7d50ad8ea5fa3561c5320206c852540c066b10d1fb0c351a8babc" - }, - { - "ordinal": 5, - "sourceHash": "e7c01c6e4c8764cf658d961174e881c4c70cf317597643d35d9cd070e60d0633", - "targetHash": "dde5503206d60a43d01f0e7e4f22a8d95446f67d34511ead3712b206d1a3f2c4" - }, - { - "ordinal": 6, - "sourceHash": "94120d8bac9df2ed991b33100188f9a5785ac28cbd4ebc93c9649c31f8f4e937", - "targetHash": "d529ef789e2aaa8e38f60f4ac198a46e4facdf0bdabd1ed9562e558aa9df4ffe" - }, - { - "ordinal": 7, - "sourceHash": "7ed60e2fe34199e32bf4156299913bd1058fde36733c1eed362fc55a1adeb8f9", - "targetHash": "31b99354bfac665554a4395877403af5c4688d106fa52c7d6085d3b4d6549dbc" - }, - { - "ordinal": 8, - "sourceHash": "9d8ee25f4a083113ca0e53db9a1482d7a74aef76bd1b87fb9841bea819143dd1", - "targetHash": "cf7311aa118331bb6e7cc9e1f371bf80521521a657088acd450f70c31d5c0c68" - } - ] - } - }, - { - "id": "plugins", - "path": ".agents/rulebook/domains/plugins.md", - "anchor": "plugins", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/plugins.md", - "sourceHash": "534004fd37921a54e1c0f376836cbdfd1aa6ecfe3fa6a1633b2138e4f582cf08", - "requires": [], - "paths": [], - "tags": [ - "plugins" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "0b7e6492b31100a32d590ab3a41be5463038d17404f53edce4c5657a8d9ebc5b", - "targetHash": "060489b1b5249dc793a82e452dd1bd8cb61f901ccce63c81a79d3e0506115a97" - }, - { - "ordinal": 2, - "sourceHash": "e1ea473d5024366f6c1b634551d461d2271cc9699cf1c765b2be393c8e947494", - "targetHash": "49bc313818af030b0fb0001db9b11ac40d82d4d250cb2f240f66a19e8d58f4c7" - }, - { - "ordinal": 3, - "sourceHash": "010d03f20e88a10ca3465d22b36ea51f9495938372834fb019c236ce8bb9a67b", - "targetHash": "cd74fc9db1ac9ad8552ddc1026da2e047d767fbae0750b4229c026d14a8ffebc" - }, - { - "ordinal": 4, - "sourceHash": "0a74219bb93287684baac21ff83548cae7bcb14e0e7fd53284e1763a11b6e548", - "targetHash": "33ca94517dcd97e912d8078690047eda94c1769221a3516a076975e2091de14d" - }, - { - "ordinal": 5, - "sourceHash": "af5f687faf8913e068718e3a73cba0003d520121aeeb249479f62505f3aaf3a6", - "targetHash": "4fabe28f2f6f87bed92709444d8db01eeeb6eb9fe3e1eb1104b6411c0bc46d94" - }, - { - "ordinal": 6, - "sourceHash": "c46d6878522f11987318a6a509d56e72b4f6681e98af45cff3623657630d9959", - "targetHash": "a4e8d4fe297362f0912a6310926344416859262af97417f26fef4c422161f6e1" - }, - { - "ordinal": 7, - "sourceHash": "ad39665d09837ad8d1e4f78c284b97d4277c68a2d44ae4442a1185d9b8a3b896", - "targetHash": "be4aa6279247bea1bc60e5e3ea8b0d38a9cfbbc1e5c3b9fcb841fa604d787564" - }, - { - "ordinal": 8, - "sourceHash": "f4ab19400c0702d8da6092df70ecdb4c75293f97205663411aa847c3c325963c", - "targetHash": "264796708436b8d5574b48bfe1033bc1fe45698ca89141352d21041b53261234" - }, - { - "ordinal": 9, - "sourceHash": "6397690af4b51494ac9f83bde6b137aca3326fdd6aa74bab0dc42d93490a2d21", - "targetHash": "3a363df664fe8edde37d6e6d62ffe0566dc1fe90376c61aa869a2bbcc410b6bf" - } - ] - } - }, - { - "id": "rendering", - "path": ".agents/rulebook/domains/rendering.md", - "anchor": "rendering", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/rendering.md", - "sourceHash": "3ce1ddba07e09326bbda59b5ea8fc931e767d0698f14871d5d3178c0432ed78a", - "requires": [], - "paths": [], - "tags": [ - "rendering" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "5932ea2fb64b334a2f80454b87bae12abbc4f754261284548020c888ab21f19d", - "targetHash": "2daee5dc2000d60570098fa21495cc91b822bc6ea9375919f518aaeba72e0ae2" - }, - { - "ordinal": 2, - "sourceHash": "ee5e8af526141af2cb7ee6ab91b439e48d714da2c1f8e832da7553ef22c503a6", - "targetHash": "c4b79e930d63306c74e4971ee30aebe894d8a63c1e1c8c63a548637e1ce2e098" - }, - { - "ordinal": 3, - "sourceHash": "656c7f1ead45a3c2d3163ae94c6f0c49657a07676f798b0615deb70769a5103e", - "targetHash": "6884e80117b1b268d6ccc90625c90b76fc1f7cef3d809241e60103628fdfedf3" - }, - { - "ordinal": 4, - "sourceHash": "1ea202115e8e050c1713a7233da99ad2bc40b4dd94cb29d5cbf5e7061bdec892", - "targetHash": "41a700e5ca6457dfb3b993750452ad8f61e764fe78b965cb510408f3ffdda786" - }, - { - "ordinal": 5, - "sourceHash": "db8d1cd54f08743dd4298fd3d5411a31e8444aadbb26a42dcd8b3f5b27a8fd63", - "targetHash": "916437cbafc25fe06d0bdee7041d760172ae5fffbe54dadb1c5ba54c8d54c3f5" - }, - { - "ordinal": 6, - "sourceHash": "71eadeb9ec2aa3ec64d0f246f13251317f05bb6bbcc44f1aeab3f5433d01d2ac", - "targetHash": "ae883035d12008e913974ca35a0867231c2088c1a8ae62901566f021cc18ccdb" - }, - { - "ordinal": 7, - "sourceHash": "f899f36c3b77d92fcc886d9b7d293b9881feeca684e86924773830af0b4b372f", - "targetHash": "303882022ebcf8c451e2066059ec9db1d0750ae31690e8e0d4be4eebf569e768" - }, - { - "ordinal": 8, - "sourceHash": "6cbbcfde884e75e96c1efa01bc4eba9521b988dd0539a50971e71a34c7a6717a", - "targetHash": "8f1bcb3b34247ece9e813fb2629cf73ca156a91a65b48d8d01d0bf42754d0440" - }, - { - "ordinal": 9, - "sourceHash": "7ede213dd1659d4ad6f51ee6eb413609ada0db844ff03f38311bef69b2e77cb1", - "targetHash": "f55f5fbf29d1d956319ce9c0290eb74dc8066464aaeb19aa047d0af2ad95bac3" - }, - { - "ordinal": 10, - "sourceHash": "0e9ff540e001733230ba91a68544e1305ee617702ac64afa50608e05971e14db", - "targetHash": "5b4a800ce70b35064669ae0b2cc88c49d8a2a282717b0e150359a383f9da6b3e" - } - ] - } - }, - { - "id": "content-frame", - "path": ".agents/rulebook/domains/rendering.md", - "anchor": "content-frame", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/content-frame.md", - "sourceHash": "2497480b3fccd8e6cd5151273000b4e58403d7564490ed0fa416c020ab55c3bb", - "requires": [], - "paths": [], - "tags": [ - "content-frame" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "b828af239b13805714c4ff0893b3ac805dcbe968cbddc152e9b83a7fba2df93c", - "targetHash": "9d3d49609e700b227a88cf6d080046723da6080ddd5603ed1ac6124a55ca927a" - }, - { - "ordinal": 2, - "sourceHash": "9cc6e95f7ea461fd696de07ce76f8797c96ed41f0433e310e1af26582805b22b", - "targetHash": "a3c3d40432341948da3425111919483a71dd9a670453a779ce14988de2c86b27" - }, - { - "ordinal": 3, - "sourceHash": "7603640023e8356e822dbdca1f0bce8573039862e61d8e8926b0acd6611b9494", - "targetHash": "799b62a6394cc3d00628d0011a636ee7132d70faf3b87a2ad91dd2ebbb26fe6b" - }, - { - "ordinal": 4, - "sourceHash": "aa8f68717a46b2a24105079cfff00c2955062fc80da10d8005ef3611bd7d997d", - "targetHash": "b275fdd63312c343487ef5900b754569044bdefa162e7984ff45a3ec6ac9d121" - }, - { - "ordinal": 5, - "sourceHash": "b95630e0b3deb0b2d09de1f2ce037457354b9e319ebd2f39c8106174275eb320", - "targetHash": "e6801a9f0117cbeb680dfcda3d3becfa769e2dfa867fa33426faea40f37d2ae8" - }, - { - "ordinal": 6, - "sourceHash": "8e6c8256ca3966575e246bf2c4986d105214afbb19a069bbf83c3e0b40de379d", - "targetHash": "e3eb98850d4fc6b9d1f10314f59ff960d02fcc31805fb8c1806e4871da6a2cee" - }, - { - "ordinal": 7, - "sourceHash": "2c398b51c32d526e1b9337797dc9d7a06302c34f25f22fb2806075bca491c99a", - "targetHash": "7abc730bed80f7182f50a2fa2d800ec1a7ff4c7f93c10603a7f9db78d1ecf0a7" - }, - { - "ordinal": 8, - "sourceHash": "1eda47cd0c85d1ffa678dd58baa94224f78967bdd53aeb22c46f5b551bb403f8", - "targetHash": "5295573eccd283d7ebe32cbc6a81a9d7de00cc5c69053fd80c864f87ba200db1" - }, - { - "ordinal": 9, - "sourceHash": "ee7ed4698848793ab73e52bd3e73fd8c709f75028df195bbe876b70e0f648a28", - "targetHash": "1ebf3f605999863b058ea2e0842296ae13c048c5c2913da0e05fab43b2a207d3" - } - ] - } - }, - { - "id": "build-host", - "path": ".agents/rulebook/domains/build-native.md", - "anchor": "build-host", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/build-host.md", - "sourceHash": "cdffaedc391e3a93d30493d9b9313e68b9b4cce51909986ad08d9854fb83b5d5", - "requires": [], - "paths": [], - "tags": [ - "build-host", - "native" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "f6321c47ec82e2ff39f1ca03bedcc8dd4ecb43acb812077b709241a61ecbc40d", - "targetHash": "5dd7f241116e94ec54013b739e2fc8b0b889bd2e08dcf2f3df1d6dd3e3db8da1" - }, - { - "ordinal": 2, - "sourceHash": "b19118c564bf7869a979959cb5942e88df5ab3a54f541061adb140aa316ba10c", - "targetHash": "6f3541d92930adac22f939113bedc1be29b6dcd0b0256d342d4426a1cd3f31dc" - }, - { - "ordinal": 3, - "sourceHash": "c7c3e1e13e6ec6f3600f6355d31a4a8d755f43369274baf9acfbe21440e8a0d6", - "targetHash": "48ac069968aebbff6d00744c92c6b5c1c47cd81503c31164b1e49962a34a6394" - }, - { - "ordinal": 4, - "sourceHash": "2ce9b85e57802b8c2a31c4cc3d0c8235b69068b7d46a7e5277978472f4de88d7", - "targetHash": "5ca44339f245dfdeecb8cb02b274bd3d830327330c73814987e11c93f2429800" - }, - { - "ordinal": 5, - "sourceHash": "8b73963b3c9f46a9705c77b3a0a00ab19c234e26eaffd223d6fc0b2e932f603a", - "targetHash": "00aae0b2ecff9452b6ed1bddfb1dc00a6b0aa126dafb52b3b2b71fabf3b7a72b" - }, - { - "ordinal": 6, - "sourceHash": "df22738791386899274f61f777a931262733f8a48f1744208c042fea57880d80", - "targetHash": "4ae5ee3546730297ce1e27aeddf37b00703842a3fa13f3780e65e520c495016f" - }, - { - "ordinal": 7, - "sourceHash": "b2d018fd842124e7109ad0973e6e907e908ea05c3d29d2ff0bbde4cc7abc8e4e", - "targetHash": "5e19b875c132a28b4329330254028c2514adafa89b1721a0836adc7bb523bbcb" - }, - { - "ordinal": 8, - "sourceHash": "224ccdec3ed83d364b31ccbc614ca441b1dc8b66d1985e44e5c5d615342d7a67", - "targetHash": "bb30e559aad2e6a87f7859cfcb4defc3eecb0d2f2b8071011d4a10db773697e2" - } - ] - } - }, - { - "id": "platform-products", - "path": ".agents/rulebook/domains/build-native.md", - "anchor": "platform-products", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/platform-products.md", - "sourceHash": "2944ea52876d78948249d82531ccd4e288b06747115d925e3dd82fe97984a24e", - "requires": [], - "paths": [], - "tags": [ - "platform-products", - "native" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "e4a5c69d79d1b3df103fccdd30a962295bcbaa9abcd77f19244d699c651fc8a3", - "targetHash": "283faab72abcd7c6e59e24926ed39bc73668e8cf3d3e9476350c1b3f834b3165" - }, - { - "ordinal": 2, - "sourceHash": "bbd068ddf45b8a55440546f88432f08f1bc7a2b94ed6aca1d4f72c53a59c15f8", - "targetHash": "1ccc62336920d8d206c660bb69253fc729a50009f5183994d8f51e997f81a733" - }, - { - "ordinal": 3, - "sourceHash": "38365fab9c07d85ea81c40cd0d181f0549b781dea9c48bdfeb0559a24a02c607", - "targetHash": "e07c444e54ad0706b8d60f18ea4251134de8da429be5becd82f620b34e9cf3c3" - }, - { - "ordinal": 4, - "sourceHash": "1e3f7d9acc0b4f337cc02dc2fe79d66ccda45221c943c14cf71f91de709ad989", - "targetHash": "d4e895af3df576a50c336831087da0154a6a61c49435523ab21d1c38719aab82" - }, - { - "ordinal": 5, - "sourceHash": "e584940bd16fa8ff45182ea7674910860e3a03209a16703f1b06a98866620b01", - "targetHash": "f298d49d33a65277f5984042f0db3612a2ca869dade024d0d9f35414d598feb2" - }, - { - "ordinal": 6, - "sourceHash": "a1d364c82b7a1c3cb16f56bd1aae66832cb7b15706a9a2c5206ba3fdaa79a886", - "targetHash": "cc05be97176ef293898bc6e19032c1d524212f4072c437cde90d72971f79b18a" - }, - { - "ordinal": 7, - "sourceHash": "875e20eacd91a77fba60d63920f357e4e7d1a3e3ae2c1f9f830da1fd8b8000a7", - "targetHash": "df72d5380faf70912ec865e14811a77f0fc2549269872aa8bd9b47989cbdeb9f" - }, - { - "ordinal": 8, - "sourceHash": "6af5d2f1a1c1f5083c4e8da9c181963e99d54ea38a9563da8747ea5fbcaab5e0", - "targetHash": "6adab6f1f34ef19fdd6e7b53cebc19f7c644791c9b9c3ae1dd3832d18570fdfb" - }, - { - "ordinal": 9, - "sourceHash": "dbfa9fbd4fa122d1eb9ea53bd5d523239d856d17a436e8df8616730f411e6a95", - "targetHash": "6ec84e13d26475f76db8a7cb32da00e07c29c3c112810af53e982217410c0065" - }, - { - "ordinal": 10, - "sourceHash": "c02df2b6b87a837d2297dead8bd588d68b1e0b158f265aa2f720331fb975487a", - "targetHash": "cc2c00b11df385e07035448fffcf8d681df96acd8382ec0e1558f5d61ed8f0f3" - }, - { - "ordinal": 11, - "sourceHash": "91e9b473ace4cf03421e9e288264dbc1c14ede8d85b92a96436ade4f1831095b", - "targetHash": "e51ebcaf4adffa66818e1fd80078f4b77797905a7bc1b34cf6e2be8289b159e9" - }, - { - "ordinal": 12, - "sourceHash": "a80250da185512ce2c8cd8d97ae37f7e29f823e844cfb499659b0e89502d3ae3", - "targetHash": "4b3ba100cd3a0a89254d79cdd4d493856dfa800f804636a44ba8849cdd82d4ca" - }, - { - "ordinal": 13, - "sourceHash": "627102228e1d72789f8c8c31687375dbeedb3e7c275a879eeed503ceaf1203d6", - "targetHash": "ba4580a371549e2c475316965ddc62910ef7c48a76d4ed19937b4ad6ff97d989" - }, - { - "ordinal": 14, - "sourceHash": "86fc3f18e3017b563ef8b55f15576986538a7e01dc9f61b869e698a24ee7cbfa", - "targetHash": "1d6604b2c73f03940f77f447e9dd42a9bfec9ef056d70190985378c7ee76d2bf" - }, - { - "ordinal": 15, - "sourceHash": "a5945bfa41a6b678b345609c3fb7753aa2aa3a183b9ebc7d11427caeaa0ab25c", - "targetHash": "38ad850bf1f51ee335adcf4b28bac58eb15636a54d7d90b2d5ce1d04ba4e0ebe" - }, - { - "ordinal": 16, - "sourceHash": "a4e99ab18a653cd24bc57f0d7df13d1dfb5778cdbf0a59aee49002ac93b77915", - "targetHash": "999168f0eebea40a7f0a0c41fdb26eea4b45a29e467ae42450117a3c18e769bc" - }, - { - "ordinal": 17, - "sourceHash": "0afee409eaa98d08d8e1a0334b61183523ae221b3f3b86f59d9607e0babec762", - "targetHash": "7e606e087f9376f10f2fb4cb2ab487372c83fb64d3f39fcce62806b806b80028" - }, - { - "ordinal": 18, - "sourceHash": "09969edea363049274eb103b0f3ed28431ee6c029070d88a2de8e287f5f0ceeb", - "targetHash": "8e56582f7971f183cf862b5dfa4b238440064196565221baad83cc0a096c76d5" - }, - { - "ordinal": 19, - "sourceHash": "066a20c7fa263bec6fb1bf35b123412cdc19b984fe121365b77d5eb4e8bd7fe2", - "targetHash": "770fb60453044c83021640675b4db0b4b0d66d24e76025e3bae9c3022b1fb3c2" - }, - { - "ordinal": 20, - "sourceHash": "f6b7f455387f2ffe8b272441fe9ccd7c6fb793a640332c7889ec4b963ceec35f", - "targetHash": "a5d16ebffec8484bdd8e48ddf07eb6f9010296c0d3d03506894434e5ad90b20a" - }, - { - "ordinal": 21, - "sourceHash": "96a1de39674aff5c38eee8057c697e37d7b1a34051133b3471bb96ff56933c6c", - "targetHash": "80284b4568ad4e28bf6d275ef21ccd35b92160cbad4d4832749532bd55caf1a1" - }, - { - "ordinal": 22, - "sourceHash": "2530d325d5dbe1448fda7a6e246d71380bddcb95a48162a33cf8950573e8b381", - "targetHash": "01c97c9490d373912aa39f72eb12078aefb786893fdf19d8d1f867575b37aea4" - }, - { - "ordinal": 23, - "sourceHash": "85f424ca1b9c5b3d21b925ef469a1a515c31f2ed651a82a92a208258f55e961a", - "targetHash": "1e1554ca14b8f1c1c792b2ecc51e5a22d04b4db18e731de88befcee8d23444bd" - }, - { - "ordinal": 24, - "sourceHash": "1121c4faa7c7e120a90135449a220ec60b622d7831ad68c2c621d96fc0e7efcd", - "targetHash": "dc1b482f4aab5734dd96ca96d2d3831385aae7c4886d7cd76388459e689bae4f" - }, - { - "ordinal": 25, - "sourceHash": "b61c0f0e7f3be551ed431b43a76b62991a811b2b51bafee0af5ebdb39d320a59", - "targetHash": "f1bd1a5d08935b55441ccf2c4708d8841d92a9f5a6b80a5698e1a47d1519fb25" - }, - { - "ordinal": 26, - "sourceHash": "1193087c674adcad2e28e80da089bca39d1bb083e175c00c46e3bfac2e21f07a", - "targetHash": "7f8759274527c9b1b1ead5bf64427baf9aec1dcb42e3902fac73ab250ff7ff03" - }, - { - "ordinal": 27, - "sourceHash": "780f84046cc74eea6834fe6397421a5e76f32bc030c29b2d0a7e66ac18155bb1", - "targetHash": "af63d3d2ab4dd248aea2c3f8eb82cec97a485bc066d80430c680c7c87c5da3f8" - } - ] - } - }, - { - "id": "backend-build", - "path": ".agents/rulebook/domains/build-native.md", - "anchor": "backend-build", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/rules/backend-build.md", - "sourceHash": "0148f6f69bbb6ba3463ae4341dd1f406496948fe9fa5bd4ec8156be0b2db35a6", - "requires": [], - "paths": [], - "tags": [ - "backend-build", - "native" - ], - "reviewer": "implementing owner", - "check": "Test-AgentRules.ps1 + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "0b0c54c567bd05ce35312c32ae5d319d22543f554671f078b2bf33bfb7bec768", - "targetHash": "5c94c310b27e6a9df124ef8dd9d80d81ce0b2337516f75634906f6613f916fcc" - }, - { - "ordinal": 2, - "sourceHash": "1184ebc811c53110f9b93a156ddbfe721a06e84ff561b7b170de4b8a4f09c7d1", - "targetHash": "fe2f86b126dc556658b3d98510c367c9b0d0e1cdadbbde575b452615d2dd5b9f" - }, - { - "ordinal": 3, - "sourceHash": "24e7a817f0f579805afd40f5ed16f6c767153b6ebd44dacee9c627313443d019", - "targetHash": "8bc7f52cde6311fb50418b498c44debfbd02a9e5072a2002d3c4ce6f78133a06" - }, - { - "ordinal": 4, - "sourceHash": "930fcd222b949ce695b267388f8203bd798c04c174217146304ffc68ac90e511", - "targetHash": "ad3910305ee11b6cc3c301f641715d36d27bf349ea279be1690f4137dd73b6d7" - }, - { - "ordinal": 5, - "sourceHash": "464eade4d3d14b2b800c761c2c5e26c77a22a4351b5ceebcd1f112dd3cfdfc2a", - "targetHash": "229dcf70819f94d7a8291b75d8cbfdb623e6c6e39b36db4f37726d8c1fb43f8f" - }, - { - "ordinal": 6, - "sourceHash": "47a490a8d8506b2fb25cf4e48407c8654b2cbc143c272e53e509ecaeb52dbbb5", - "targetHash": "452e40de8c98a748c939e30115ca9962a497cb38c20ebc931cbc691240e59ecd" - }, - { - "ordinal": 7, - "sourceHash": "77c7d40f8caca628be02ac2147345e04132df08185765da27e5d6e823ac61f1c", - "targetHash": "88fe122ded5a5662f59de6cb274cf44aeea96fd79acea3c3d8ddb8160b0f9882" - }, - { - "ordinal": 8, - "sourceHash": "dca2a1bf003d9c82f5c57956cc315bd20cfe11d5c9c52caf2aa2c3c06a6ac852", - "targetHash": "49a91d8ef3552a254e865b8629a5e296fbbdd3f9808a30932cb3af1179682abc" - }, - { - "ordinal": 9, - "sourceHash": "1ea3f833bf68f4009d0a8baf5b54744de3b51c97d38370e47e41a34bc31a0f96", - "targetHash": "94d8980e98c8bce72f4cc50106880b725f8a4dc62f9fefa0d08047bd816c451c" - }, - { - "ordinal": 10, - "sourceHash": "db9846f1d6d8462e20d840a76c3fd2271e2cb1c171ab6a3c3dab8373c31d5e6b", - "targetHash": "6d5a1d919c9a6d1c0ab3d783e344175cabaf1b7696b2280051dee36b64204ec3" - }, - { - "ordinal": 11, - "sourceHash": "4417ce20429062015905ffbe98b19a0d31908960f6d5863c80c27fd2b7644ea3", - "targetHash": "c932db0ddc349b2623393bc3be6ecee78b5b949dd6ffbe790994736f0caf7aa4" - }, - { - "ordinal": 12, - "sourceHash": "167343d8d3372823fd6a5c09a919f63b5bd1524b4cb1b6229f516f4eb6a7044f", - "targetHash": "93cd250c40b90c2dac1407b7622fa51b291b959f2576e2a09d48fc04c2ae4a7b" - }, - { - "ordinal": 13, - "sourceHash": "d03b95720e5346978f818d1cee320f8eb0576eb915431635b925dd83b318f5bd", - "targetHash": "fa6f1d36700726347605104c6b97cce1e94833efd072d50b39f17d96687c380c" - }, - { - "ordinal": 14, - "sourceHash": "d8360e8265f5088a3def25af85805151c7aebd7a508d09cc919f19f5e24d666b", - "targetHash": "c718e498d894d8502a6e4f66a5896eaa1683c6fcf81cb18d27e39a9007126bd3" - } - ] - } - }, - { - "id": "csharp-standard-0", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-0", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 0, - "sourceHash": "1ae167521e9170f3f63e3f8945bdb849e260d44c79aa523435df060da55077ab", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "9c59de057b27b99349948ddfcd688fc59906fa79587ce29428c2787f948f0fd2", - "targetHash": "9c3e7f891fe5b00f62469b1bbb2543dbb748fd248b39b051c6d9c657c1a274c3" - }, - { - "ordinal": 2, - "sourceHash": "2cbe9059c50549861b8ece9ad35ec1bd5c87886fc01da521d2bbc9d73c39132c", - "targetHash": "a1736a899605f9dbe302d2891ebd2d871f84c5448be3624cf7a130be9bb38d7e" - } - ] - } - }, - { - "id": "csharp-standard-1", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-1", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 1, - "sourceHash": "e6bb6be83dda2765ee0b7f4147efe8d179357e106fa40a77b666d79b6f7764d0", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "6ee4ceec96bb3b6021f4893cd90edd04e72e3f2a46c786e8c934a3aed28745ba", - "targetHash": "c3b767fc362bc09f11a826fc31139b772fff0314e8ec76b496a93913ba19836e" - }, - { - "ordinal": 2, - "sourceHash": "888b98a8bcffd2623bb63ec661c3cd24dbad4c62c070b538d82f2fa31b4fc7a3", - "targetHash": "64e2901909af165f76cab1149c9729bf5bcd046394d18b8453443d6789927cf3" - }, - { - "ordinal": 3, - "sourceHash": "4bfd2941b7773db394a6e661183b975a55a81a195a7f4c0b7f5cf23ab8d46908", - "targetHash": "805254701ebf725180887414b642cf5e776d5259d41745703749de26000d1622" - }, - { - "ordinal": 4, - "sourceHash": "b9e40ee1518b1f41589718f6deff2b2b2e0a34fa42a35852c61f2468ab94e9ab", - "targetHash": "b3bd1bce40cf14e041e29ad28d4f6fe7736feb5f574892f12db012d2aaf36fed" - }, - { - "ordinal": 5, - "sourceHash": "357681e6e42d804f722960eeeef8732b5b052faa63e9e30343b0ce9007005768", - "targetHash": "6f707239dafc252e4194421f344ead08c03e7600efc08da7138a3011285c712c" - }, - { - "ordinal": 6, - "sourceHash": "e49798a40cb8b13ff6773073397a318a21e0bf1377c6626dcb52f0d0dffb12c7", - "targetHash": "54d5f693ea07a0cc986c422d463ce2630b3944b65e9f48dc7bad2268b8477b0b" - }, - { - "ordinal": 7, - "sourceHash": "6e973c36089850c8e3825c98e606a7fd2478bf31ad160f14ab3cc8a5bc7190ec", - "targetHash": "830f24ed78a6178f864b21c4382c777d4b584f754c4040a62980f1142cc347e9" - }, - { - "ordinal": 8, - "sourceHash": "35029df979fea84e4c4c21691c32bb5d52bd2bb0694d7b66bfdcfc4330d08bca", - "targetHash": "de628dddce646380f858186a822e5cf0f6dec0b9b81a13b3e3567e2f8b2ca8d8" - }, - { - "ordinal": 9, - "sourceHash": "efa3f684a3deb795b6859bb7bbb45378f93375ca97b48a9eac2bf112ec4c9b45", - "targetHash": "efb6880f1350a328c366a5f3476e3614b3c2cfb94200a6bebafb7d73d10f6a2e" - }, - { - "ordinal": 10, - "sourceHash": "36132fa3b63f3460abdb38ffba3fa44c161e713f1778bc7098b5035f0d0d4979", - "targetHash": "76828e0fe061b761c00c0afee82e308909dc0a93a5dc7fc75218d37362c2b61b" - } - ], - "amendments": [ - { - "ordinal": 3, - "previousHash": "805254701ebf725180887414b642cf5e776d5259d41745703749de26000d1622", - "currentHash": "e15f9052327e9ba5e8a73585e66062b5c9f6220a36e24773d0ded57db77f3ce0", - "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", - "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" - } - ] - } - }, - { - "id": "csharp-standard-2", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-2", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 2, - "sourceHash": "cd7faf5c94f1eaf2ce951777b9dbc7220c57528b38bfe38f1b47ae1cb18470ec", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "2a1db15f2cf52f0f95bc16796ed368d13d5838d938507cc3ff64e3e1233d4aeb", - "targetHash": "c03ed48491913faf71c543a24a31ffca134b16b52e0474d4e89d7e6e14477ead" - }, - { - "ordinal": 2, - "sourceHash": "bdf2562bd82aeca96c2e749eae7385269480302e400cf043a29caed25ab7a013", - "targetHash": "7033c5e9966f88a09eef43b70046fcaba63af49c2d66f2c555172631ffbb0483" - }, - { - "ordinal": 3, - "sourceHash": "b8ec48555607bc6202126c5db642f11cf898151fb6f2aa19d2e28aea19d7e532", - "targetHash": "b8ec48555607bc6202126c5db642f11cf898151fb6f2aa19d2e28aea19d7e532" - }, - { - "ordinal": 4, - "sourceHash": "8c142212a767f020c0c49c9fa73da04642b8a45cc773ce37b88c16f5b12135be", - "targetHash": "9bd93d6d6eddb2c2c5f3dcdabf0cea833ca4a75ae0d1db7c7811d2ada13c5a17" - }, - { - "ordinal": 5, - "sourceHash": "53f170c754c5ea5453b8cb79d9019b84a7fb5939925733b1a510b0eb7cdbb890", - "targetHash": "d0bf6bef623f2c3066f21253b127d345da2bb450060e83cbe718209afc8dbe99" - }, - { - "ordinal": 6, - "sourceHash": "f2387cfd9284c5446d0273c02585de39adb41f5a87724febef62afaff75e7f80", - "targetHash": "56d0aaa53ebcc644f9ff8e3084a166d11bab6d2d309f039f6d2845eec14c08d5" - }, - { - "ordinal": 7, - "sourceHash": "b836ebbeb1d666671b5b0828c56021c81ee90969fe7cfabbf2a1864dd60a8142", - "targetHash": "8ff1928b68a5ea3677710c81ba93f0d11865b2a89e4033debaaee5eedea8998d" - }, - { - "ordinal": 8, - "sourceHash": "797dd7a782adab46721f3bafbad4449d81309d115bad776e8dcfe4245a68f91b", - "targetHash": "918169dc34a2e6b2624075a83435d358d9e647db5c6a49afb18c74dd1138fa30" - }, - { - "ordinal": 9, - "sourceHash": "6fe5493740a39c129e316e6b968189f6a0fca8e9eaeb33f67f87363162772025", - "targetHash": "516b102cbcd19e64756bad14c8f563fbdee107f8603527b1a32fac07a90781a0" - }, - { - "ordinal": 10, - "sourceHash": "21b1cc15fb6a6b576235cf883e1c564c05d1bb3cbc8dc4521b5a197cf1da9c92", - "targetHash": "948e70960b87fad036e3c3cc3bd3be41ef6483e5d6700881294c16057f3e003e" - }, - { - "ordinal": 11, - "sourceHash": "6138673c0e4ba945c4e799b186de33e5a3fbaf717b943b50f09bab13a92b3ce1", - "targetHash": "507463a0be7e145d3f1c01bdc6e848ba6aba319421cd7348f0638211896c5e68" - }, - { - "ordinal": 12, - "sourceHash": "f3605ef5c893175dea12dc1d5fec5be85610daa8dff0216a97141fb38237f3e4", - "targetHash": "b780ea7e5182b22d9f876df497d2b7bd18c9352e3204e88572905ffd8a352666" - }, - { - "ordinal": 13, - "sourceHash": "f664f1d02435ef0cc33073dc7e99243f89fa35f277f14670d35d1d1fa60652bd", - "targetHash": "326a3d166f7f239af5e4343769a8bd7cdc16df6eaba52a089ed215e726ead1f4" - } - ], - "amendments": [ - { - "ordinal": 6, - "previousHash": "56d0aaa53ebcc644f9ff8e3084a166d11bab6d2d309f039f6d2845eec14c08d5", - "currentHash": "d63742aef216fbb6640f07b4e2ec5c944bced33774d352a95ed47d1807f758ef", - "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", - "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" - }, - { - "ordinal": 9, - "previousHash": "516b102cbcd19e64756bad14c8f563fbdee107f8603527b1a32fac07a90781a0", - "currentHash": "5dd04a005b5b03678533a5a5f6bc198c9412255b28c0b6d0cc15ec5a85c27c36", - "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", - "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" - } - ] - } - }, - { - "id": "csharp-standard-3", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-3", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 3, - "sourceHash": "75f0a926f0b06b60c211588ca953b239d229e9967fcca8f7cc8a27be8091a3e7", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "1c05e9d5a84367951b498cf424b39205dc042ca24765082f22c146b3cd2e0f5e", - "targetHash": "085917a9e331374bdbffe0ab1b23a54a59b4a786efbd15cb1e6211b58ae5e819" - }, - { - "ordinal": 2, - "sourceHash": "b7fac7e1f5d412eb64b7953d09480a04c5ce1e256a675068988567fb44008f2b", - "targetHash": "4eb75ae22ebc4298fd09b3b02348405d6a87de46539040119f92bf9e32025676" - } - ] - } - }, - { - "id": "csharp-standard-4", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-4", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 4, - "sourceHash": "30b69ca4a4f4788914691f57fbf66ea5f84a89b41b4d123b57f3c294e926deb8", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "0e76f3ec6ab88ecacea8579a89e848cac5555e3d7b546b734c8a20628db371ce", - "targetHash": "4a2da7db79ead93d57d95876f924519b97cd1cff017efa8aff275b8024f8e034" - }, - { - "ordinal": 2, - "sourceHash": "2ee4f49742f6165c3cbc004f70d87949fba5945273f77a4257992799bae9ff3d", - "targetHash": "24a130c6bd5708b80471b734547ee13a8384ec0da55c2e130e750a6b8e2333f8" - }, - { - "ordinal": 3, - "sourceHash": "7b781b0b3e782bf4608ac199db45d88f618981d240b45e0c85d94357c52dd401", - "targetHash": "c3143d67c5398ea03b77854dc74b687f15c3a0840f7c2f85433dd035ff4e9bcc" - }, - { - "ordinal": 4, - "sourceHash": "ec46d88bee70f83eb0dc91ce75626ee524818848362c23cd4a48f318b96ec0de", - "targetHash": "7243e5afe7052dc0ffa66bb70f6a022f0a7979fced37c737e47b754ae4602997" - }, - { - "ordinal": 5, - "sourceHash": "7b401a21c5881f5e4633f28ed91ef6ebbc3f6a90fb11de9c49d4d6a54cc867d0", - "targetHash": "382cbf673499ba493964ec4d57a581dab6fdad314136a81da37ef4a355655aee" - }, - { - "ordinal": 6, - "sourceHash": "3efb123634905ffca53f8592c946d99019a174281756210be994ba742c6adb19", - "targetHash": "6551c78cd40bda9a80cd187bfe51a45cb00adc39cba8029ce0a9965a5f027b91" - }, - { - "ordinal": 7, - "sourceHash": "274a3245c966d81da7150fb9cd7810a513ea70eb0239d0ea8a27669c752d11a5", - "targetHash": "ce05cd5e1e3172c2ad00e82cdd7851d56ba1f89370c557651b8b9016f164d09a" - }, - { - "ordinal": 8, - "sourceHash": "603ccd47e936b6aded57cc5163f0905d06bff9a8ac7f683caf5bb9c70e8d6ce7", - "targetHash": "8bffc74725c719931ade1768d30efaed8656cbb09aec835d951a61bfe8bb5efe" - }, - { - "ordinal": 9, - "sourceHash": "0d3623254a13451a943b452751857f006364093dcc0d75d2f55ca78a5af96c6b", - "targetHash": "0d3623254a13451a943b452751857f006364093dcc0d75d2f55ca78a5af96c6b" - }, - { - "ordinal": 10, - "sourceHash": "f622329f717c750ffc8fe0c409c66fa73310880df12ffbe59e4c61894c82f979", - "targetHash": "f622329f717c750ffc8fe0c409c66fa73310880df12ffbe59e4c61894c82f979" - }, - { - "ordinal": 11, - "sourceHash": "914a3311bff3058d48f38512053c30becd2c879d3fce2c49685b0860271b0957", - "targetHash": "914a3311bff3058d48f38512053c30becd2c879d3fce2c49685b0860271b0957" - }, - { - "ordinal": 12, - "sourceHash": "d10cd75e7bd08a8208c43ce168bebe074524bbffe48afc9d71dde27c2e493403", - "targetHash": "d10cd75e7bd08a8208c43ce168bebe074524bbffe48afc9d71dde27c2e493403" - }, - { - "ordinal": 13, - "sourceHash": "021fb596db81e6d02bf3d2586ee3981fe519f275c0ac9ca76bbcf2ebb4097d96", - "targetHash": "021fb596db81e6d02bf3d2586ee3981fe519f275c0ac9ca76bbcf2ebb4097d96" - }, - { - "ordinal": 14, - "sourceHash": "0ac850e1c2f83e6715c147d174c7a1cf26eda3641174777c64df44750429116a", - "targetHash": "0ac850e1c2f83e6715c147d174c7a1cf26eda3641174777c64df44750429116a" - }, - { - "ordinal": 15, - "sourceHash": "72228e1f698045d5aeeb03d7bfc662ab8dc7fb72d9aa4886b289c16f48dd0dc3", - "targetHash": "72228e1f698045d5aeeb03d7bfc662ab8dc7fb72d9aa4886b289c16f48dd0dc3" - }, - { - "ordinal": 16, - "sourceHash": "1939dcba42b25000ce9c4da51afabcfe974a692854c93acdd82e049643e1537b", - "targetHash": "1939dcba42b25000ce9c4da51afabcfe974a692854c93acdd82e049643e1537b" - }, - { - "ordinal": 17, - "sourceHash": "d90b324832055af883f20cc746cf7b7f5058bb4e8da84be3d4d21110df0be2f2", - "targetHash": "d90b324832055af883f20cc746cf7b7f5058bb4e8da84be3d4d21110df0be2f2" - }, - { - "ordinal": 18, - "sourceHash": "e4f59d270c7614ec7acd35091e519264454f5fa7b53f83e87f8646d59095736a", - "targetHash": "e4f59d270c7614ec7acd35091e519264454f5fa7b53f83e87f8646d59095736a" - }, - { - "ordinal": 19, - "sourceHash": "f5303ae6a3201ea52e30701cabe7f1bb4a4a0d66c2bb299f83981c8f77ac8b54", - "targetHash": "f5303ae6a3201ea52e30701cabe7f1bb4a4a0d66c2bb299f83981c8f77ac8b54" - }, - { - "ordinal": 20, - "sourceHash": "263d2b59db8ede9334d008264c0886d9038cc330bdc872c4e92300d558ec3df5", - "targetHash": "263d2b59db8ede9334d008264c0886d9038cc330bdc872c4e92300d558ec3df5" - }, - { - "ordinal": 21, - "sourceHash": "e0ac073295c3369afb71ba1437a0357153a4216453a8014091267b720f7370b7", - "targetHash": "e0ac073295c3369afb71ba1437a0357153a4216453a8014091267b720f7370b7" - }, - { - "ordinal": 22, - "sourceHash": "28d86778615f6af47bb1bc4f40face756749768e5111f114cfa234a5060c25af", - "targetHash": "28d86778615f6af47bb1bc4f40face756749768e5111f114cfa234a5060c25af" - }, - { - "ordinal": 23, - "sourceHash": "d10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2", - "targetHash": "d10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2" - }, - { - "ordinal": 24, - "sourceHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5", - "targetHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5" - } - ], - "amendments": [ - { - "ordinal": 16, - "previousHash": "1939dcba42b25000ce9c4da51afabcfe974a692854c93acdd82e049643e1537b", - "currentHash": "76a70ad6442ba71c8cf0285318dca9eee29ae4de77ac6e1e6cb65c4c0b5b5932", - "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", - "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" - }, - { - "ordinal": 19, - "previousHash": "f5303ae6a3201ea52e30701cabe7f1bb4a4a0d66c2bb299f83981c8f77ac8b54", - "currentHash": "267c6ff223c302caecd3d34911f6f80c6c6b31e20210394a1be7bf740a8bb92a", - "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", - "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" - }, - { - "ordinal": 21, - "previousHash": "e0ac073295c3369afb71ba1437a0357153a4216453a8014091267b720f7370b7", - "currentHash": "33c9de50e08ac72e31c6772dc9ddec81e5e3c706a57238e97ebde48d8b881403", - "approval": "User-approved InnoEngine C# code style rulebook, 2026-11-21", - "review": ".agents/records/decisions/CSHARP_STYLE_RULEBOOK.md" - } - ] - } - }, - { - "id": "csharp-standard-5", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-5", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 5, - "sourceHash": "ace556d3813740e6a4e788f488e34cb5fc4442a4b15f50db0349e7effaffc237", - "approvedAddition": { - "approval": "User request on 2026-11-08: prohibit global:: in handwritten C# and record the rule in coding.md.", - "hash": "11daf5b535242c204be26f40eebc86a38ae7449501f035ab867d8d5416cce465", - "translation": { - "language": "en", - "source": "a31375a5f01a9523edce97b54a0055fdde92c067:.agents/rulebook/coding.md", - "approval": "User-approved English modernization; original addition obligation unchanged", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "11daf5b535242c204be26f40eebc86a38ae7449501f035ab867d8d5416cce465", - "targetHash": "650503dd2742a9729f9656bce96b02aa7be14c4cd444e1ec66980b112cec23e6" - } - ] - } - }, - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "fbdca3db6661bced81495cda5ab5cbae231a4b5bf041af1e5e5db5db097bcf51", - "targetHash": "1d66628f237692fd7eb91aa99b97689102ec1e66f351fbb47239255603c2ba22" - }, - { - "ordinal": 2, - "sourceHash": "fc3d8f40ca5efadb2e73ba60e9fa39d574e9e5ca26f5ba3bd5a3bf632bb8e9be", - "targetHash": "6febeef0a913a94c550bd0adc41f2319ad1b81cdc9a9f9484a69607679731f01" - }, - { - "ordinal": 3, - "sourceHash": "17689d3c29320cec885899230bf2de2bb068e4b999dd65a6a71f73cb56c27b95", - "targetHash": "a2da9948d1f1df8239206ffd810b15b5d281518b56270f6789431e7907d286bd" - }, - { - "ordinal": 4, - "sourceHash": "609c51fe9f58dfc022b8b46ccb07d81ff7b50198fbd437d6d5264a992dee2e8d", - "targetHash": "8c4ad7175c28810e07380f44f456cbdaf70d3a0ffbc67c7dc46814570b963f64" - }, - { - "ordinal": 5, - "sourceHash": "9a10ed4f1319e1f1c9e5f49254d8543c84b4a88ea1eb56d24ec09085cee00bb5", - "targetHash": "cac9e75375e991ba6f79925bd252e37a77e23f64349d7438ad732e8aa75441b2" - } - ] - } - }, - { - "id": "csharp-standard-6", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-6", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 6, - "sourceHash": "9513894db97113c26aa081c3cd9d382cdf0ee4676d5c15cb127e0c54103d6194", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "28df84f81a5dfe455793038b671cb6954bda75c1ba6c3db0f4fe70c099f0be9a", - "targetHash": "dbfc49026f38704b938dfa5e4ee6d27265d8d0d3c5949e11cb1fc88e11e634fd" - }, - { - "ordinal": 2, - "sourceHash": "808fef544f6eeb0692319a5307f51c9e3d94da9a0e44f481cd7a9d16b8977410", - "targetHash": "5fd8e3d6275ee4949ad3fddf759091bb26f7934569be267ad0e9bc4915ff21b4" - }, - { - "ordinal": 3, - "sourceHash": "8280fb67fa4af7ea095815754ead7fa4bad07e0c3729b1ed0f9321ea5cd0356a", - "targetHash": "508202489b9d14acb588f15af344c6cc8e321dd6614c6892df8db70ec1a5edd5" - }, - { - "ordinal": 4, - "sourceHash": "39192fce16e032f167aee1ed11ad7dec675f603262a30f8147b1a82a5016553c", - "targetHash": "c85850ef42775ee52c6317810c7c4f632f88d9e4da7b7918f10fc5346438d924" - }, - { - "ordinal": 5, - "sourceHash": "3bea06883794548590673be3eed3dd909fef101220e5e3dc0ace842b07ac71a9", - "targetHash": "9e7e606d78a67bd8faaaaa0107c0bf3aa011dccbbb0797def4b8c429974f52bd" - }, - { - "ordinal": 6, - "sourceHash": "b094db2f3bc93173e6e7a9c067a5d34538d49bec0c02917dde5f0053d6a24e6f", - "targetHash": "b375e2dce7a8d47cc7f5eba34fe45329f01d66abc7c950910c5fe4663bf892eb" - }, - { - "ordinal": 7, - "sourceHash": "7e3eecabc11656d7e5abfc6dc3011b78a1ac5f14fc012cccd8f4e30f6cc411fc", - "targetHash": "8e83f08594761e24aea8de252a64d011c5a80b5cfd2bbfbdfd63950f1bb52631" - }, - { - "ordinal": 8, - "sourceHash": "cedc1d7fcc2fec17fbc1e0b3bad7a1f563457dddf5c6e838b339c69846ea48b2", - "targetHash": "6e1d70097b436467ad7b11e9c030a1c66e44341e42424f1a1122ad39456a1b3d" - } - ] - } - }, - { - "id": "csharp-standard-7", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-7", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 7, - "sourceHash": "d2f70bc4ab9ed29686da1c043ffd9630fc160b4ad5259a2dc48ea698e90b56c7", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "a0be6f683d72d53b7dbdb50f1ea58c120ae27921bab335e18dc4f0cf2a0ae759", - "targetHash": "20b6887d47f797c8cda7f622c4eb5ed19cd240fc6b5a010993024525911fb2eb" - }, - { - "ordinal": 2, - "sourceHash": "439ae488bcad7c90069d1ba1573168d46b2bbd3db295423faa4526dd316114fb", - "targetHash": "9e9a4898d4cabe4380e34343c28a1952c39d28d1a0d91adc874d96be9a323ba7" - }, - { - "ordinal": 3, - "sourceHash": "895935c86d3690478a0b128d60d8c75beeaa42b5ae0a90f9f2611293ae16b5ac", - "targetHash": "6172e1fc7d4ffd1f8824660c37c26c3eb5e5b4f5217b9b59e42af22d0d0b033d" - }, - { - "ordinal": 4, - "sourceHash": "543a61005388c162a545099c929ce8cc0bfb8f57dddfb6db3a5629009ee0c4ab", - "targetHash": "30c3fcad6f1d5853aaafea7b6bb38938613b1079cd89d04e401bc74e371fa4f4" - }, - { - "ordinal": 5, - "sourceHash": "af90858955c2025436dea38d3968a317354062610603afcea883900f13b00671", - "targetHash": "f86f503a20af95d32ed0a1c1cfd2c1ec38de12a517287269669a92fdb41381ed" - }, - { - "ordinal": 6, - "sourceHash": "d86060325fb1e93c57affac20326b65e3a7b7bae570d0768322fecba214c7d76", - "targetHash": "978dbe01188d211a623edaab5207e0b392ce678db45f0a3cd99820dac69d456c" - } - ] - } - }, - { - "id": "csharp-standard-8", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-8", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 8, - "sourceHash": "d59caf636e6d1a2614a542203c5d2e502d47299ad9b434c12083afa1642b0020", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "5a3060e58c3176f0ad032bcf05c2a61a6e6a1100771e62224af05cdba9a9c35d", - "targetHash": "97a965239f9b9cb2d4a2928ad1266593ea14dd80ffd7c6cf72ad08bd752f9812" - }, - { - "ordinal": 2, - "sourceHash": "820e84a3e882c755dfef876948ca415d23dab182a0ed8bdb8780bb9af5985322", - "targetHash": "c4b93d73d5f678510d0b71a9e0aa6c132047d2a659603d56c710c7008c9266e7" - }, - { - "ordinal": 3, - "sourceHash": "e4031dca31bf985203ae2dc7eb0be455441aa84a163bcdfaa4fa80cc849d7ce8", - "targetHash": "71ee4ef1f14d78af5b5d1dd0dc818e0e810fd2303c27146d8b504a47847aa075" - }, - { - "ordinal": 4, - "sourceHash": "8a23e7a0fc35d7915d1dee1d92499e98b1d625fed50dde8907e0f1db41b98146", - "targetHash": "cb94773c52926d4a30066f41eebf25a52db646ab74384e3d673a7fe5269d9a2d" - }, - { - "ordinal": 5, - "sourceHash": "cee15864cd70f7788fcf2fc10b2992d12538c0738963d2ee7d39b0dc03c38751", - "targetHash": "56585f625eade9a3997dfd2cd253202e1074fb7a07da09ea9ceb5f7db3b99481" - }, - { - "ordinal": 6, - "sourceHash": "4aa10716eaa5a957775b3381cd6c89235bd9d93bbc44889b797388f7f947e362", - "targetHash": "42a086ec659e97e860628d94db20f02bc6ca99bd7e146a7fd97f465bb538dc9d" - }, - { - "ordinal": 7, - "sourceHash": "1917b9a45ffbb5a811b8fc2c0bd8d175000437f4abe2fb023ee5c7978fa74fa9", - "targetHash": "ecc11744af3860cf39bfdd0445ab85bd6a08d1a7e36bdabf1732ebd787f95d89" - } - ] - } - }, - { - "id": "csharp-standard-9", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-9", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 9, - "sourceHash": "264a7aa49566628811332c607f0a852dfa14135e8319c3945e20e8f7bd7f1425", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "46701af87ced263bc9ba88b638e831be8ab548a125880e9da94da358420927ff", - "targetHash": "374d39163bb3453b09ef9a8aff3458c199626c053c37cc4bd7d1118996553dfd" - }, - { - "ordinal": 2, - "sourceHash": "09bb496a44962878b1968f10d1c2ffd7b1ae2180a179e310511f7e126d32ffb9", - "targetHash": "245170dac1c6e605793a3e5f1a0f783c7da5e7b3dc7911bdb4af8a1c3e5ff2d2" - }, - { - "ordinal": 3, - "sourceHash": "d6d85ea546d42ff6228e5eae5091f92f53430e4d226d2a2c710b25e2ca89ec40", - "targetHash": "f2cf8678e0d35bb701ae3de1abff76f47b3a8a1a4103697a8b0b6fbea1424bc3" - }, - { - "ordinal": 4, - "sourceHash": "dd9c8dbb7c46aa487e28832506b06a9d60d935bf168752a6d7b614cb4411bddf", - "targetHash": "0511a208309a0ada60d6a1f824d360043b4f06a2d1b3d282e69936a4e8e95726" - }, - { - "ordinal": 5, - "sourceHash": "6b1d171d2c1a30f944d6761a9f7c704e648aa5695d6693904c7d66cfd54a979f", - "targetHash": "ac9ffd7becab6e3b5f8f1387c411d716f80fbfa855b37d300aa8058ee1d9f734" - } - ] - } - }, - { - "id": "csharp-standard-10", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-10", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 10, - "sourceHash": "8e9915979f7d691ef5b067c80bcbf944331135f4d4073e1e90db7fd6b5cddbce", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "8727ea6ef780080d7aaf1e686b97ae9c27cbc77c6738bf40b3dc90734f08499a", - "targetHash": "2414828088d78c4c1db1edcc3f14b4d337ee3775544a8d52b5572e9dbcdc16a7" - }, - { - "ordinal": 2, - "sourceHash": "6bf5070507e2c81f797dca6bbdc175dc084fb3dff82f4904e5690b352bef406a", - "targetHash": "3ddf6d9facb84fe0e55c53e7efdbfb68f49aa7196e95ee1926be2afab2aa4f0a" - }, - { - "ordinal": 3, - "sourceHash": "9d95106a201cd6f93d7038e125693d3d332b7f3a9e43ddb13dd7382ed19359bd", - "targetHash": "16a31eb9f1c0d61bb7da2f3f559bc8476b226ec5f56ef0ce62c522dcf044760a" - }, - { - "ordinal": 4, - "sourceHash": "cbf14ae59bb4d7d1af66ed784d042431cf68249374af00b5a27e944c615fc8a2", - "targetHash": "9e967b6413a72ea84ab0916612ae5a774159301d92f7621a2ebe143d1c8dd793" - }, - { - "ordinal": 5, - "sourceHash": "3a058cc62e35dc737f7064017cdf2be132ea48e2e890540a62e22883d2ff0552", - "targetHash": "3fb2d4c98b5b1a933d87dec7fc5640eeb61d21ead07b183d2724e80b4dbaa66c" - }, - { - "ordinal": 6, - "sourceHash": "6a1aa914078b5971014d6d53a29225406e536c34075e6c38f8fa5ea664712f9f", - "targetHash": "ffd3073f7bb56d6e85c581ef3f1324bbfc28e05e738356b10532a372b15e7130" - } - ] - } - }, - { - "id": "csharp-standard-11", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-11", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 11, - "sourceHash": "594831b9bba1df40656233274f526cd7462d02baef33d61b47a401ca3b77cf42", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "c390f8074d8045a88ec9c80245ad8917901d74200e1e0ac86d29314aeda5bae5", - "targetHash": "6c24e27d56a00fecffe47a3438882019ed6257cb69e7e45adec87e3ec61f545d" - }, - { - "ordinal": 2, - "sourceHash": "a82d7df0d23579b739375a0ebb94c728f1c9e52fe70a28993cc9b1cbec588dbd", - "targetHash": "94b519aa68b716ba1a3cb0245777b6f9cd6bd493b714276b74233243af170509" - }, - { - "ordinal": 3, - "sourceHash": "78f38c229d8a58637157daa7e1e9495f2c5370725b207e80990992a830ab2d78", - "targetHash": "836785d545bb812a24c82f0782178d41aba1012a1eaac86af97d5beeefa9cf10" - }, - { - "ordinal": 4, - "sourceHash": "4d7bfdea52a075ad764ad61e829998d15cb043024df34a553588139cf220f614", - "targetHash": "493ed144d74bd63118eeb76ee47011d562e6fa31b7dc8661d92e797060539a81" - }, - { - "ordinal": 5, - "sourceHash": "1abf05950ed4306d0f04641f8440751c8ce59124b7a985559eb4fb27df47d360", - "targetHash": "b0eb9b00dd364555cd55569bce2b769ba5918a225284ae93a904f48f14f4900c" - } - ] - } - }, - { - "id": "csharp-standard-12", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-12", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 12, - "sourceHash": "ec9f401d7f7c23a50e563ee86d16a3a852ddb58c3c595ba4b6be4619650627f4", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "67a8e3894c349182da7fb29e4abf36e61b9c93819ab04d5200faec4d5855a8b7", - "targetHash": "7dee3f6b7aa992240115ac1f48c28f2cf3602e483345d3c341bda23e443db508" - }, - { - "ordinal": 2, - "sourceHash": "22d9b218bba744ff2523a49dc07bec67e477329787f5bd09541188302a191b00", - "targetHash": "2bc40cffd8c5cbfc1ee12d7bd57fd2d2dd148b4d3e7629a388960a73a701a146" - }, - { - "ordinal": 3, - "sourceHash": "a9908bebb4829633ed2362e2542a418a8c3653f6b1903416d949e79e3039dcca", - "targetHash": "0179901db9208077def1353dd6f20501968fca7a2ef4c5b9b6b74ff18926be2a" - }, - { - "ordinal": 4, - "sourceHash": "d2b82519aca9fdb58ccb243cc529de4007ff9d2974258306d39614c10d2b765b", - "targetHash": "89a0be93616b990368b9b70310ecfeee95829843e488f281c5dbb78c20874883" - }, - { - "ordinal": 5, - "sourceHash": "c68852cc4067cac36b6b87a5f9aff6ef036ab886916a9bb4ff2f0cbc9c8728af", - "targetHash": "e7362ad4e73f04dd63d35bc01d358e3684e7a70a7fd058822e6fd28b395af24b" - }, - { - "ordinal": 6, - "sourceHash": "76fc467dc8eade03577e3a109c96302a5f77b5c2933c44bdc3371d429d31f5ca", - "targetHash": "b2e3c0757d797d93b4d779037d211b10eb4f7abdae9e807d9566efdea5a6c215" - }, - { - "ordinal": 7, - "sourceHash": "9acba233e90d643b858cc8e6830fb17437888a1af533b51859584817b8ce8eaa", - "targetHash": "39e8ce468554d0e68d510364db43502aadf1df6fdfac109faa2bf7932c859cf9" - }, - { - "ordinal": 8, - "sourceHash": "33e0aed50227158e1f6a8aec7a1fd8b49c9dadf0209d7a87113402edb25b3674", - "targetHash": "bf09a964b4030f20eb08d660514796ed4134477001ab149845ecc4804fdac696" - }, - { - "ordinal": 9, - "sourceHash": "af73502abd2e29fd481d7b17de471abeed43dd517b649126994301d5be6df770", - "targetHash": "947326cd21100e3a028a48637d83b38a41e746521a2e82720a8b77c57d688112" - } - ] - } - }, - { - "id": "csharp-standard-13", - "path": ".agents/rulebook/coding.md", - "anchor": "csharp-standard-13", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "sourceSection": 13, - "sourceHash": "b52fbd3c7d57be9738c521c668ba64a2493bc01d6b44c8100f9d3fd75a8b08d4", - "requires": [], - "paths": [], - "tags": [ - "csharp-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "d75b96d35705577c153ef7e83211a9e108cb6b23b349d2c3214af1eddb0620e2", - "targetHash": "029ff0cbfc2449fbf83e64b5417e96fa07ef32576eb5c2107c5c66679fe78112" - }, - { - "ordinal": 2, - "sourceHash": "ed9d423a413c1b8457d9c1fb5632a4df807e941b8a25c1e4e401429b7e05f242", - "targetHash": "e4bbf6abd499436019554d319f4b0834fb4b2eba164893b6c6f12a53713b5360" - }, - { - "ordinal": 3, - "sourceHash": "197344a969f727c21e8e0593ba064020bc18ca030a1a46ce90d3c60287cf09b4", - "targetHash": "866d72c6ce11cc5b02052ac52ee11b6010cc8133e37a15641152aeffad55106f" - } - ] - } - }, - { - "id": "csharp-style", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 0, - "sourceHash": "dd9d051caac7083966bc9ac53561090a4c65d96f318edba0038ec4018cdbc86a", - "requires": [], - "paths": [], - "tags": [ - "csharp-style" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-files", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-files", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 1, - "sourceHash": "db7b9649a9e34ed2cd39f3ba1711a6aa66c1ed8a7a6a16854243721b4a895f4e", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style", - "formatting" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-namespaces", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-namespaces", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 2, - "sourceHash": "79c4f4fe907c212d1adde45f51a17c774e07107203b218757b34b63957f25b82", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-naming", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-naming", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 3, - "sourceHash": "7d43b7e400d26ede576e0077137e93555403cea369c0edcfcbf42cf2a279856a", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style", - "naming" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-types", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-types", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 4, - "sourceHash": "ec8201e76922cd821115e9842f216140a258ba74b869d1a9cb07077e25b8bff9", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-members", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-members", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 5, - "sourceHash": "2e289b06e2175c79774465dbe0192069172307d7ae128962ff9a4e2a81ad27af", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-member-order", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-member-order", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 6, - "sourceHash": "b6faf59f653f2ae7ff4bc6e1d782313e6950f49c498d8a207febadc92df8152c", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style", - "members" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-braces", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-braces", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 7, - "sourceHash": "53e32f3e52a0e98fe9056a1546441db560105aad7efd3a71f08fdaa1b3af72b7", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style", - "formatting" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-parameters", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-parameters", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 8, - "sourceHash": "57e0429afe24fd0ee80b2b08b5581c3338b4294e9d8b3a3f740dd4fe89a08e36", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style", - "formatting" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-line-breaks", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-line-breaks", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 9, - "sourceHash": "b4e2c50e733f8ff3ae98d4b2b7ca0ca27f0c520c3c0585cd131ecf411c5e7204", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style", - "formatting" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-initializers", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-initializers", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 10, - "sourceHash": "c129cc1ffac6fd3030fb27b03af8bf2eded74d1cc50b0598488d29da62f19197", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style", - "formatting" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-spacing", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-spacing", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 11, - "sourceHash": "5508d9b2b32c93600f61cb1adcdec35608156c235063a01944f27938d56560ff", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style", - "formatting" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-idioms", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-idioms", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 12, - "sourceHash": "af1a07ca4615f20c706d65877ac916071665be1085f86c8fbe0b58fbd5422dc2", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-control-flow", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-control-flow", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 13, - "sourceHash": "a6631442ed62387c7841b3ca9bc518044832a0be107569491919868c04070028", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-comments", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-comments", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 14, - "sourceHash": "5704764651ff68d88eafe37a269de30039b0d60a3f6703863188c2daf53bef3a", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style", - "xml" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-tests", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-tests", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 15, - "sourceHash": "c0fbf18f3133ed5f75bafeacbfd3da9784f00e08d0aaa32e33f80b5c939b1f43", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-exceptions", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-exceptions", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 16, - "sourceHash": "c39c03791d13c10e6b6dbd7afdc8c79006320374a95b9d3fab8635352a262cf7", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "csharp-style-example", - "path": ".agents/rulebook/csharp-style.md", - "anchor": "csharp-style-example", - "source": "17a0ed43536ba049cbcd3ca418205f2d6e4b91f2:.agents/rulebook/csharp-style.md", - "sourceSection": 17, - "sourceHash": "bbbe47646a9fbf0085c7cc8f94f9e69ff7e8f91fe6b8b39458bec09e5325469a", - "requires": [ - "csharp-style" - ], - "paths": [], - "tags": [ - "csharp-style" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review" - }, - { - "id": "documentation-standard-0", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-0", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 0, - "sourceHash": "2b3f30679024db5d9b1d07ff1086179e79654d12aeb7d585f9101d857c7c5cd5", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "d40f3ce7191cebf3bc675fb594a4d8b0d29a638d2e3382dd7d0e48a1d2741b90", - "targetHash": "bfb5d3ff9b354b0c01a9916b2cb23dcdedc0b077c6b0d8dffed2e5e906d3a8f3" - }, - { - "ordinal": 2, - "sourceHash": "c14e2113564984dc2fd1f306c11ca7e8eea93037ba33f2798edcf342c142bf51", - "targetHash": "dda0f207813397cbcdea5e62ef2cd2b77966ef0dffe4e57ecaf350d2808a57b9" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-1", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-1", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 1, - "sourceHash": "6b05a0ec83b508519b83132ffd74c35db7f53ebd1d955367afd966333a3e9c30", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "1490aa516834dc13b8bcbff59e07e23e8800a65f5823162c78be02baadf71534", - "targetHash": "086594ddf0a6b3e662adbe5773987abd6fc5575bface84163f26fd0e9b1f2ab6" - }, - { - "ordinal": 2, - "sourceHash": "3ad78594488a55898157dd4797129137e2d9490d878880ac4ab400db68dc1b2c", - "targetHash": "25268c99b4275a51af3324a645d483d8bbd0dedd5c810415914d7ed2b2eec177" - }, - { - "ordinal": 3, - "sourceHash": "b0821299063f116b6132c9ee23659cba0b6f3254f9104e69e33cf9677e07203d", - "targetHash": "e1af2f77ce196b8f5a834d718bbc3f9d88fb453093a3af100638f904cfb5a213" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-2", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-2", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 2, - "sourceHash": "652d09619bf30978b0061ed778331dd33c9154f3ce49c509f05b128e6fd909fa", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved named API authors, editable description overrides and tool-maintained contracts (2026-11-16)", - "review": ".agents/records/decisions/API_AUTHOR_METADATA_RULE_AMENDMENT.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "c75987175eb7af167bb6d11e6ff2694bdaa7e8b0de11cb2c8c4244fd129cd12f", - "targetHash": "2ea15628c7ef541beceed02a0f14c90aed483d196a1d3578f6823c1756abcdac" - }, - { - "ordinal": 2, - "sourceHash": "136d19292806db2f5054d6c1bd11df0679805d5c21fd298c3815a20498a801bf", - "targetHash": "176898b6017d0a25a8e4a64a6c03d4072bf6c4b1d5a4455945606435dba7eaf2" - }, - { - "ordinal": 3, - "sourceHash": "3b0b7137ff392ff0bf8bd7d13053824b6d85875abc0d96b90518329f42bc5a8d", - "targetHash": "8af5f7bad6857a615a9093d57f808ef733dfa4f39fae7b13284a926035759c84" - }, - { - "ordinal": 4, - "sourceHash": "9e87bff673c6b685be8d82a195390ebaaed9455c58fe9e215c1c0ec736653930", - "targetHash": "7422c46f261edc4d8da8e4ae471f53322d791f6bbf8bb2fbe9f0917cfd085944" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-3", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-3", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 3, - "sourceHash": "d50017b48c0e71a1ce5f026d029ffb6ee93a88d8d018a5f002118d88aa00314c", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "32ca6ef85f16922dea70bd0df1c91600b78c3f3b25d6ba933c480a3f7660b64a", - "targetHash": "0d19ab46319785768005536313f02bd3b9b779aaed82eeac5bf7a7f796ad3ef1" - }, - { - "ordinal": 2, - "sourceHash": "b3c3173b9e01c60896c1d8663b98cfe7912069446dd380db236e5a0f56be743d", - "targetHash": "fe81134cac575566520515b6a628b674e81ad37d4444b8ea9520b158c804cb0b" - }, - { - "ordinal": 3, - "sourceHash": "aaa9eb0ee1c76bec522e75eb80314defee804c0ec89088a73b0fce1c0bf9b9ae", - "targetHash": "82f4a2988289b8be37d30fd4962f80666458697ad5f5e82f98d6abae24266ff3" - }, - { - "ordinal": 4, - "sourceHash": "7eb1b49b258e57073a3bef9842e0ec5335e5aaa38778b3b4c76cb0f9a7770af7", - "targetHash": "e3339f0925f02590dd58073983a32a6af2284a7a95f9e4d69f7f2b0b106392ad" - }, - { - "ordinal": 5, - "sourceHash": "0bbd408781d09bfc0d64c6f2a6df025088bae87dbd29ddb62361b6950f17b73a", - "targetHash": "34dfc71a9367f078b9002bfd06eb995d65163794c66949947e08512052c0d6e7" - }, - { - "ordinal": 6, - "sourceHash": "ca0d12775c803373493ae4a660f8a9bc2e270f87ee07dc3aae8c5b11012e1948", - "targetHash": "682c848319352ffed13444f5f62ba034c7d635a0109a0b1fdc3d87819589bb91" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-4", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-4", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 4, - "sourceHash": "b4e203ad58328e392684d984491729c023a8643bb8daf527e3c1431dfa495196", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "582f4d8d820f9789c0759812e43f499e78d55389cee09ec843a3760f6aed5cb5", - "targetHash": "793761fe962922ec048d78b5f4d412834858b2891394a7084d7136587afeaab1" - }, - { - "ordinal": 2, - "sourceHash": "82d25bfdf970603898c23530491d9ac39565466989ebe6100984e1033f9249a3", - "targetHash": "de748bade3a4c1bf762baab60b169a655241d9e6c17c4037d8bc6e331ea10fbd" - }, - { - "ordinal": 3, - "sourceHash": "b8ce7eb8b2e27687c7efb77ed24f530c539b8fde25d71d0f42d1a395eaf45cb3", - "targetHash": "43aa30aea59b4f89b0abd187ff612529af822af3aafb1d91e1772cb840146f72" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-5", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-5", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 5, - "sourceHash": "d17e16a584ffa310b40873a100b302ae616e77495c262be03a8d6c9a14565b66", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English modernization and subsequent API automatic synchronization / Docs draft-main scope and editorial amendments", - "review": ".agents/records/decisions/API_DRAFT_RULE_AMENDMENT.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "11202eb25b2d933c909c1e250f7f0c27c8984ed7eb906cec3a7ea1fe48521f38", - "targetHash": "7a1e9d36126ed9af0639496f1877a6dc30dce5af1fd2766f2c94a18f6e4e5f30" - }, - { - "ordinal": 2, - "sourceHash": "9582c6a1e89590bebf7a314b634ae5e0ad35ff98d0d750b5f68ae3e44016e448", - "targetHash": "546b13605ada9ad14e78010fe2d6dde5ad44c3007df3172ec6a51d382951f46c" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "documentation-standard-6", - "path": ".agents/rulebook/documentation.md", - "anchor": "documentation-standard-6", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/DOCUMENTATION_STANDARD.md", - "sourceSection": 6, - "sourceHash": "e4755ac95fa67c8079c901ee495f1f523c103f3a0f2d7bf419a9e2760367a8f2", - "requires": [], - "paths": [], - "tags": [ - "documentation-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English modernization and subsequent API automatic synchronization / Docs draft-main scope and editorial amendments", - "review": ".agents/records/decisions/API_DRAFT_RULE_AMENDMENT.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "7d1a463d62b40dc279f0bcbb2dda6de62d2bdc39fbe1fdab514604c19afbcf46", - "targetHash": "bdb7ffe98f4ab63e001c1e5a0250358ecbe82e6b5ac71d39e91c816df99554e7" - }, - { - "ordinal": 2, - "sourceHash": "74fa08a7c5cc7a9aec4a1272ad757e830dc7f82446cf7fdb993502ae84ffcc89", - "targetHash": "f0c899a46a7abff68879c7aa0f4dd5417c90b6c2526d818131978ed15e559e69" - }, - { - "ordinal": 3, - "sourceHash": "a86daf878310539249a382b48f28d4fe3b31268843ca189c2234e597b47d7105", - "targetHash": "39b3af164ffdf99c152f46819e2419258b0d6c50d46a7cf91f7e9bed921f7735" - }, - { - "ordinal": 4, - "sourceHash": "6c7b0020590849ccd7372ced6bec75da43ab66d7cbe801784c796e42b65ed3be", - "targetHash": "a7bf7dadaa989f736b8125232199994636753916bcb00b00b4f52e2eb06ab916" - }, - { - "ordinal": 5, - "sourceHash": "572982ca2711b2329ac43f26715debbe332f66f9da0c002ad1ecbef2f4cf74c2", - "targetHash": "75b551e961d6e6b78d8396f4ebd554a7ced350b1d1c11f4b2a6f20fc544a1366" - }, - { - "ordinal": 6, - "sourceHash": "a9ca4f5ff5cefd378615f369f1872e4145ecafa56f49de0e0819da0394886a4a", - "targetHash": "f63c773829fb474f8dc34e9b7196c88ef8c65a4e8f7154a38f3e17bb30fb940d" - }, - { - "ordinal": 7, - "sourceHash": "9e6859773c8903f1faabbec92a00af4d43fbb98a75318b4a6698497aba77ea04", - "targetHash": "7930567cddc3fbbc030746f99b6e73f44a3ae3a30c1d5704215e24bbbcbc4671" - }, - { - "ordinal": 8, - "sourceHash": "5b0a1e6316db48e961ae73b98b9edae1108ef3c22bbcfded5f9160ad077e4e6b", - "targetHash": "d2a5c84282697f34e56aadfe92dd982430035cf22d664d2b2798e81cf2caf626" - }, - { - "ordinal": 9, - "sourceHash": "683c506dd23c61a8865fcc8f1fb27bbcd47b571dac371fbfc4fa52e9246581d0", - "targetHash": "4dc89cc8dbc3629f9a068baae136a9839275a2679ce40eb640bed285ea0ef365" - } - ] - }, - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "id": "editor-standard-9", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-standard-9", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/EDITOR_UI_DESIGN_STANDARD.md", - "sourceSection": 9, - "sourceHash": "4c27d71eeeb375245a649934a3e280a722687d62110e88c0ca371ea607dade70", - "requires": [], - "paths": [], - "tags": [ - "editor-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "5af98fc5b27946f97187c485b563377c31523556261a5d2346fb8f09a29d2799", - "targetHash": "fa23fd44069153ae245075f69cd2d116dd324260c576d5a72b8e64c4cce943cb" - }, - { - "ordinal": 2, - "sourceHash": "e717be6d5789b75e8ce9724168fb8971c064679e6bf305b4657422a6628f54b7", - "targetHash": "7fd65ebce34528e4ca1598cbff466ba08bfa9deb93776e1d733cb191b72dbea9" - }, - { - "ordinal": 3, - "sourceHash": "adeb7ebcfafb194e366c14d212168c1a5633539633a7eab2cd86d3781f4f1759", - "targetHash": "87d7b4a837c8a2dc7dd0b777f4eccdb1134d0c7ef7a8c9a0deb9866abac18e5e" - }, - { - "ordinal": 4, - "sourceHash": "eac23233cbb4786fdae140082b570cc12e764a48ef1e733700b4b1bd22759191", - "targetHash": "a2871f5a9803c9d3e0c79679ad168ba003919989ec2a89c391666dd1a17f76ee" - }, - { - "ordinal": 5, - "sourceHash": "a664f27eb75c84c851228c926669120b741f02b72d2a7453588e638cdb3d0d3b", - "targetHash": "a419dd1995ce54e54488816847bb232ce673cee425fb6d34473be2ac5419821a" - }, - { - "ordinal": 6, - "sourceHash": "26e63d5c69c966096cfbfbd0a0344fdd888ac3f0f7a952e40c339ff0b14903c9", - "targetHash": "db0b23498dfc1f364cf1a7863d16794a67af9dc33d261a57644d6084907baa60" - }, - { - "ordinal": 7, - "sourceHash": "5d9634441c3bfab383b60433d289f61c0b98f8ae0d5198e803a65646e7bc83ca", - "targetHash": "6335d97df8a916f7c17a96c968312734fedb7571c388356748251ed838c4e4db" - }, - { - "ordinal": 8, - "sourceHash": "fa5277e42773bb18e65ac6dcaaa84e3aca868f550fe1cc91c4a3f4dd35304604", - "targetHash": "efcb36d339f46b11a8300001c41a0be5ad1bfb7d0ce799f6ba825652d6ff3f00" - } - ] - } - }, - { - "id": "editor-standard-10", - "path": ".agents/rulebook/domains/editor.md", - "anchor": "editor-standard-10", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/EDITOR_UI_DESIGN_STANDARD.md", - "sourceSection": 10, - "sourceHash": "7c051be2869f46bd2beac2d5dacfd75da8afb5b39047d02955d8c4bea5fcb475", - "requires": [], - "paths": [], - "tags": [ - "editor-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "9c7f0fc7ede41cbd678aa63129f224e66b66798813dbeb627b8d5445064d89d1", - "targetHash": "8c475aa3008a17c3b04e9c6bdd360b8ee1ed13fc04c2e90e4ca945ae9211b16e" - }, - { - "ordinal": 2, - "sourceHash": "27f5731a0a5e6300a028317ae933dc693e81d6a513748732dc3894f2454306ac", - "targetHash": "a74ad8c29936557f40687f1e5afcaa578a45a9f695a767af818dd764cd7776c3" - }, - { - "ordinal": 3, - "sourceHash": "cb59ebd9f3f8ceec16bcb3db3bf03ae9b3225d90e6b110ba46e11a8b0da4cf43", - "targetHash": "563026fb39be04a8a7620b98daaff86e87d2c2ffbc4003eeed2bad09d3fa0e91" - }, - { - "ordinal": 4, - "sourceHash": "a738608b6f36855f4a4e0ac506656159da8122aa195dbb035cd509bfc99ebe4f", - "targetHash": "fb974820251d971ebeae65d596af0d1fb09fa46009538ddd9a296093ad47f725" - }, - { - "ordinal": 5, - "sourceHash": "126c515920613f1a133b2d8bea796af15c7880f146e43061eb755d972e5a8cec", - "targetHash": "e23e4974bbccc05a4bde3885b3e0cb7f74ebc5d3b9c2790b5908a81b84b642da" - }, - { - "ordinal": 6, - "sourceHash": "0387b218d3e368b207621ec75610231f308a1f8635d497840f260baddb707a40", - "targetHash": "5785c31ba9c268ed8948f437a00e66f1c8242ea90cb3882fa0136f2d294dc24c" - }, - { - "ordinal": 7, - "sourceHash": "80f00da15617b31fdcec378d9e38c64a682359355b3f3a6992f1fc85c1da45f6", - "targetHash": "7c275c2732c7b1f8d3a1ccaf146cb07ed9f62cbe817d598c3aaa76692a1abfe9" - }, - { - "ordinal": 8, - "sourceHash": "1933c293314efdc4770be33e561aad8c17619280f1d022a6d8c5ae68a85bb420", - "targetHash": "45cdb5335658bc92f8c6efd9c779018cdc2c95702baf1671ca9612e2c57633ed" - }, - { - "ordinal": 9, - "sourceHash": "0c174ab5ae307ead9852705a9cef5562be2eeaa41f5d19ae1a38dcec1d0c1b15", - "targetHash": "d5d87e25f5cf3360f97dcc04cec0c8360c14149bb3959e123989c1b35ecfa72d" - }, - { - "ordinal": 10, - "sourceHash": "3219506ec257d9873272709f5f0391df074edf5faad9c5ffea530d8d408672d7", - "targetHash": "4e61230cf5c5564db81131acbbedc835f91c5dc7c5c53028aabdc381cfc20e31" - }, - { - "ordinal": 11, - "sourceHash": "3701e24bc7049221695ba62bebd6c39e0a8d8b5f88e3f8d75d6830f22df23f00", - "targetHash": "53c7cd04856398d348b8880b0ea0a86e3c4e2be3e4f5d59a57da9fe290ccc7dc" - } - ] - } - }, - { - "id": "identity-standard-12", - "path": ".agents/rulebook/domains/identity-reload.md", - "anchor": "identity-standard-12", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "sourceSection": 12, - "sourceHash": "c04a13c50f3dfe682a2b41855e42100b349db014d40a7a06530c0b3ee4dd6779", - "requires": [], - "paths": [], - "tags": [ - "identity-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "9c5ea9f5d15d225b698f982b3db4b7d83fa4f3c8640e97f4698bf5181b2a6cda", - "targetHash": "eb11f4b9d27b79b45bb4e736120814109c26e3183d3fc2663550008271354aeb" - }, - { - "ordinal": 2, - "sourceHash": "c816a06c4a8be6d812578b6f7383cbf8dee59b91225444f8d590c9fbd7c0701e", - "targetHash": "edf62c7da90bb4ac368c0eb9aa7836ef688e87fe4121b53b2a2a5bf560f3b33a" - }, - { - "ordinal": 3, - "sourceHash": "b9d2f3b86842dae33a41867b197836afe6233c4241829e1204b3848f508dfb3d", - "targetHash": "6f06cff5253ced9abe30a33f6a2289b114867c6a1d833aacd60c9f078e9d73de" - }, - { - "ordinal": 4, - "sourceHash": "050fd62a5c1de4d1d901303d6aa89ea5555acefb49640f67e6d33f18efd8676a", - "targetHash": "2af2caa9ddee739bacb662a9da9be5808dc27cff7db5aa6d871a6c2dbee8b92a" - }, - { - "ordinal": 5, - "sourceHash": "ad4fafc213ed296ebdb6c0f7951ba5bee9c20b2d8c36e931174f69cb268754a0", - "targetHash": "77bd1af2dd50b9811ee9a43b8fa89b78214a702f05f2e05671579b287140b839" - }, - { - "ordinal": 6, - "sourceHash": "0366bdf3d76726d6b207a0895ce5cdceab1476e0716bb4f77483ae5b8c2fc6be", - "targetHash": "407623152ef87ea249c2e6a6b1d73a7594155903c6b0deabb1152d687ea00363" - }, - { - "ordinal": 7, - "sourceHash": "839ac57e01a117bf8b9f9115fcc63b68cdb48a227cf8f7da9c1da75c1b6bc792", - "targetHash": "b1be478f727cbb95f56154f35988d3c1bdff3bd8052bc2b4e49dc5fd73f81316" - }, - { - "ordinal": 8, - "sourceHash": "23292ba0a0bd516469687f53b6cbf8a084e1e894da78103eecd697ddef20d0f2", - "targetHash": "32c267afbe380e5b790d4262e221dfdf60b96b49e74d7a2e2cc9ac897c0880a5" - }, - { - "ordinal": 9, - "sourceHash": "0ca89e6798245ba4d58d1ddafbdefae6dfa475a5ec3ae0731e85a2614ab1428e", - "targetHash": "c98316cffcb8d38ebffb7f3fa83931223dd430e36623c0b2eb5084c3bed2ceec" - }, - { - "ordinal": 10, - "sourceHash": "4a9430fac11ba3904d0df22cfe6d6236ffa3e75c17d4580529d5309b43221412", - "targetHash": "d1a826dba8450aa3875725dd824cfc603b648142da6156c6f754f3930eb970d1" - }, - { - "ordinal": 11, - "sourceHash": "425536a1d8ec21ca9166d6d955545547c278c57c1b856ee726fef42f2dcba724", - "targetHash": "cf51c14d13ee05e86fcfa183611564a97ea7e62bc736671feec8dbc2bb9f234c" - }, - { - "ordinal": 12, - "sourceHash": "b2ae179032fdd003eeec23502dde2fe85b0ec8c940cdf3325d9d2011f1996d39", - "targetHash": "f0cda63fca605ec854c588ad13773864383df3bdb7fa3615acc7a652401b288c" - }, - { - "ordinal": 13, - "sourceHash": "30cd85d0831091e93eeecae70e77f41fa71b5d51e10d7ba09e5f3d137f4e35c0", - "targetHash": "e0cb3f486f36dafdaa1af82c873edabc66594166cf01222174212c225e9870c6" - }, - { - "ordinal": 14, - "sourceHash": "8965297f5daa9c1ed2ddb4ea9da55733de7e760843f0ead75acf3ee5ed96dff3", - "targetHash": "feb7abcfe22b598e3403569e7da1b986a91255b421645cc68b2ce721e56c1097" - }, - { - "ordinal": 15, - "sourceHash": "5ad2da98723f1a021b09ae6b718fa20466a9a4562f3441bf085156641d69302a", - "targetHash": "2f91feccc5de9a2f71268e187151f6141ccf2fbfffab0f3f1a1aa3df89e47688" - } - ] - } - }, - { - "id": "identity-standard-13", - "path": ".agents/rulebook/domains/identity-reload.md", - "anchor": "identity-standard-13", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "sourceSection": 13, - "sourceHash": "52493148de955847cbea6609f0c895bfdefe5008ba5cbd50a6283a5664cac692", - "requires": [], - "paths": [], - "tags": [ - "identity-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "2d5d7e2789f297edbf3431970c66f4895d44a6ba990657615c61668b3e3c3230", - "targetHash": "4a9909a8648625c07cc29fca118c1eb68e2ebd471093d018537ab1a77dcf1ada" - }, - { - "ordinal": 2, - "sourceHash": "121c3630353bfa5ef6e5eec92867689bcf301155caa15d5d7d3a0def0cdf0c83", - "targetHash": "121c3630353bfa5ef6e5eec92867689bcf301155caa15d5d7d3a0def0cdf0c83" - }, - { - "ordinal": 3, - "sourceHash": "7f4691ce35276b1ab3344d5fafd462bef2c1168e87b5ce2f658212c5e3c46764", - "targetHash": "e84459a6b63dfd8935786b6d6ac2d3d46231268b78721514ce19a34b0bad6dc2" - }, - { - "ordinal": 4, - "sourceHash": "310728c2e9b7e5045fc21bdbd258950a29e16f3e4333b41bca9e18e1d75429ec", - "targetHash": "aeb2e4b1813c86971cb5ec22701e78cfe5a7265db39b4badf6fb12f761b5048f" - }, - { - "ordinal": 5, - "sourceHash": "294874ede85f308d3a57cdc5c61c4a8d58f883db8396573db69d37f2fce3fdc6", - "targetHash": "111f4a5e339808d2ef2ba90e52e18c4bdcad56cb34407c5d1b2f598ff9da20cb" - }, - { - "ordinal": 6, - "sourceHash": "b5a54418a805c5d19628b3bb41620ae7984aff74707011b0ff7b26817619a9f7", - "targetHash": "ebc11ba5eb3869ba2e92c60f26a8ed56ba63d5976815d276cf29a0594236fe56" - }, - { - "ordinal": 7, - "sourceHash": "7d6268ef94d331e07152a34feaec74d997d2591fc3bcf0859ad7441c97124672", - "targetHash": "25d354aca3c2968421169defb0070c4807ee7eea23265d2094302c6c83da1f02" - }, - { - "ordinal": 8, - "sourceHash": "3e7172a4a728597dd8cb9ab3d95502a6e6aa04b14387428d0412c1dc194afd3f", - "targetHash": "3e7172a4a728597dd8cb9ab3d95502a6e6aa04b14387428d0412c1dc194afd3f" - }, - { - "ordinal": 9, - "sourceHash": "b1e8c4885217c846af9e269228df9a91b681e9842c03f619cb79459f768ba8a2", - "targetHash": "0ec8b03880b690e25ececf4d4eafd5d87218a55cbd3267e95b339b16da6864c8" - }, - { - "ordinal": 10, - "sourceHash": "11693d0aa493bf2b38a8ba48cecf90c8da625b5303761d4eb1023fee5a8dc20d", - "targetHash": "a567b2b46121035e43203a571dc9cfa163686da28807c480e91d94b2ed594de8" - }, - { - "ordinal": 11, - "sourceHash": "067f6a4b5afaf0f316fccd7118d272cfeab684c39eae99f082e8e8e8c5c5b752", - "targetHash": "4c4894d90154253b9bc02bdf06d74e1ef73bb73604ec6927b9f44c6852456948" - }, - { - "ordinal": 12, - "sourceHash": "39d9e1dcc09b54a0b7501746d1153790ed7d02e86acbb9c30581120a3f9cc9b9", - "targetHash": "9bedabda2ade55f06ae87212a403a2026199d5d4b2646e3db1a6b417bbb01043" - }, - { - "ordinal": 13, - "sourceHash": "2448e92a9031555d4baf576686eb804b35b3ca8b678217e4a6a2dc43741062ff", - "targetHash": "91efd14b79286c2b2764ae164684a4a463cbcb19804d82a236e5e43c3ecd2b1c" - }, - { - "ordinal": 14, - "sourceHash": "b9cef8bf99cd4bd9293438f3d1baf3a101e7d78992112f2bdda74956c32c7c4c", - "targetHash": "ef83b11427026a6cd408313dcc87e2223516202e5e874b8e200bcb2581077278" - }, - { - "ordinal": 15, - "sourceHash": "a0659b75c00466135f6ba3e21d24e832f9899f98807e0480992fc30569d0268d", - "targetHash": "54b1807fe77912fe4778e593cad96559e31346a291e43c48fff24e8993e9fc00" - }, - { - "ordinal": 16, - "sourceHash": "b4a313791c1fbca2c1410d1d5b1190af4087723ec1b6c1c4ba776298d6dd6228", - "targetHash": "b4a313791c1fbca2c1410d1d5b1190af4087723ec1b6c1c4ba776298d6dd6228" - }, - { - "ordinal": 17, - "sourceHash": "dc676b42859915c826f8bbaef6511998f7aedbd6e332565faeda17fc33ec6320", - "targetHash": "dc676b42859915c826f8bbaef6511998f7aedbd6e332565faeda17fc33ec6320" - }, - { - "ordinal": 18, - "sourceHash": "926eeba6058ff5b18954fc1a5707376a2670dfb439ee5b00660e2dc6cb6716f5", - "targetHash": "926eeba6058ff5b18954fc1a5707376a2670dfb439ee5b00660e2dc6cb6716f5" - }, - { - "ordinal": 19, - "sourceHash": "87a08ffe9a6f80e34a71c7691fddda770a89a4c249637d50683f5fd9534ee360", - "targetHash": "87a08ffe9a6f80e34a71c7691fddda770a89a4c249637d50683f5fd9534ee360" - }, - { - "ordinal": 20, - "sourceHash": "f783399583a877391438dfa759912922fec0c63faa2024e8d1481138653d12b8", - "targetHash": "f783399583a877391438dfa759912922fec0c63faa2024e8d1481138653d12b8" - }, - { - "ordinal": 21, - "sourceHash": "06969734222d809a6bfa8531289fc6a29de47247e8fdd6fa94e2fd64b1546eb1", - "targetHash": "06969734222d809a6bfa8531289fc6a29de47247e8fdd6fa94e2fd64b1546eb1" - }, - { - "ordinal": 22, - "sourceHash": "85b028d477ba8186e3a1a1e86aa949f9cc514ec0e1b6da2eec77f94033a6ce8c", - "targetHash": "85b028d477ba8186e3a1a1e86aa949f9cc514ec0e1b6da2eec77f94033a6ce8c" - }, - { - "ordinal": 23, - "sourceHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5", - "targetHash": "f1b901847390b0ed7e374e7c1e464ec17b46a427c487a5ad6cbd2906405083d5" - }, - { - "ordinal": 24, - "sourceHash": "03a8f641293904182090dd83b0a17a3dfc171f6cd2c15957da45a8b076878181", - "targetHash": "1303393cadec1612b995355e5a40bc2d3a9b8ac2580f533e44b02a4089293f43" - }, - { - "ordinal": 25, - "sourceHash": "6d188a3a6b6f3ef3e9b54b90bbe8644afbb67a687a79793cc6478b78603aa4f5", - "targetHash": "09912f1d65e2e610cfc42c00d91a3b6f4f85d9fdc7df631b83322a3e096e1500" - }, - { - "ordinal": 26, - "sourceHash": "1c72b28b05f6ffc0914a1a90674cdd0045c93ebef464fc64ac56f22468e3e786", - "targetHash": "200de7b94ffea3c65e469bc80592ad6aef00823ce6417b42a8bb000d66a49625" - }, - { - "ordinal": 27, - "sourceHash": "00b254fb327db3f20efe1a71793957730f23bc28137eb8b7d84ac13642973c58", - "targetHash": "4a82ef9729ac15aa5d830ea8363c60cb18ea4105c259f0a956afcd2b2c8aded7" - }, - { - "ordinal": 28, - "sourceHash": "68ad0d01f982e6f258cac64e466967775b67fb658f5c4803fe83fdb4f89fa4a7", - "targetHash": "d7c285ced0bd38d6306e187158110f4435e2f9d65439a738c674e77e05ea84f9" - }, - { - "ordinal": 29, - "sourceHash": "ab54461d0f419b5a54b388ee2f8ae558aa50522b1b7409733a40e249482815fd", - "targetHash": "749d441b3e4bf1282bb0eba1ba8c894c075748520d8e9819b5922a0d5b8cd8b3" - }, - { - "ordinal": 30, - "sourceHash": "a92c88c9f2d32dcfc7079078c6f520dcd494093bf77d7718aaed6b8c05aea81f", - "targetHash": "1cc12481c05844706b89f202b2c0abea50fd58196f8e42738478767fb8be7107" - }, - { - "ordinal": 31, - "sourceHash": "383d635bd2c50f69f8402d18ff659964e3542968acf4a696767b7e14567c2560", - "targetHash": "383d635bd2c50f69f8402d18ff659964e3542968acf4a696767b7e14567c2560" - }, - { - "ordinal": 32, - "sourceHash": "4420df8991446fc486e7a15201beac3670db325f891d3406ef68de47b8ae9175", - "targetHash": "e8cb10a4cfa091f65833f4e557d3bd0a948b42ad05bafbf520cf64f900a1f6ce" - }, - { - "ordinal": 33, - "sourceHash": "dc394083646ddca9b59bc602979b82c9a7601e58443ed3178f62685b913e9bfd", - "targetHash": "adbe063776c0c7581a8fb0350ec7b34363b05ee21dc2bccbb4e4d0da8ca3255c" - }, - { - "ordinal": 34, - "sourceHash": "107c645619abff8e4c7bab6e8dcdc509eb523116e0645b9edcefe32c24a85664", - "targetHash": "f8c3e071c5d109730dbed376c09d86717dbae2f116fb7c8409edbb685914dfd5" - }, - { - "ordinal": 35, - "sourceHash": "9c1ff26b58f1aaed263ff9c98b59b8caf9be4ca1e8f0d93c86bc1beac7a8f0d5", - "targetHash": "0594ec9f6fcf6b9421151b7408c86fd959b392e50aaf51201501f188d11679ff" - }, - { - "ordinal": 36, - "sourceHash": "8604d20bfd06096c3800ad1d302f3332768f2ec2dd5793a424a9ef8848da2478", - "targetHash": "da578b5f559f8e63531ac1f9c1c7c0a3d8b1c63f3bd37a4cb5ca2ef5aaade878" - }, - { - "ordinal": 37, - "sourceHash": "3efae27b85314dbccde928e8d3d71d8422709e3d27c4c4c645a31c3afcd245e6", - "targetHash": "e05965b4a4f34a9e91ce0af5cd091dd952e1626b1e996b358c866f6c5b43841e" - }, - { - "ordinal": 38, - "sourceHash": "ad5c2ad9efab6172d1e2f263d289676a177762baf550116294df1b2e774a807f", - "targetHash": "e6fbeb18d3c8250d44fad79efe44f8444474637ab3a57daaec81e3431bb370f1" - }, - { - "ordinal": 39, - "sourceHash": "a132d925134321e599d9d68386a39ade207c5503c74771527b229bad355d3750", - "targetHash": "a132d925134321e599d9d68386a39ade207c5503c74771527b229bad355d3750" - }, - { - "ordinal": 40, - "sourceHash": "dafc8e4178e8bc68d10c60e30fe31d5948545d193dae91f7c268d88dfd73eb3f", - "targetHash": "4f3d9ee0de38fe960cc014e3815d3a490431d298024b58691fd64d72e1a53f47" - }, - { - "ordinal": 41, - "sourceHash": "b9b88b4903de2a4accb4e7da6473959549b95d551f0696cc93f0f6a2e471404f", - "targetHash": "bbac5c3d97ddc122d55990238d81f83ad58064be0fb5ed550cc5e0918d773d7e" - }, - { - "ordinal": 42, - "sourceHash": "98352764e4558c4c9f1739549f460ee16a5dda5eceaef4822f74f5c19fc12e92", - "targetHash": "d2f49afd9d4d5d48812f5b1ec10e27c0ef47e71b77aeafe832cc65d91d2b158e" - }, - { - "ordinal": 43, - "sourceHash": "1d48b746a8b9e9fa2d48acb1a9534ce39920a78d0e1bd86c318b4644dc1df800", - "targetHash": "a5df5ad75cab8084f01adb5892e6bee37d44252c268378904d3f2e8a5dc49b25" - }, - { - "ordinal": 44, - "sourceHash": "f3567ea7df9e453b4acbb77fdd07e4a51dcdff58b296cefc59da16e09cc6558a", - "targetHash": "6f6e4a48bea92ec1aaf81c62c3b046e3e91c9443a311913d7cca92da5371a902" - }, - { - "ordinal": 45, - "sourceHash": "76b5d63c88fbc109ac4dfd2ef13b245d508d9f9c087d7f0f25306813cec8571a", - "targetHash": "d3b7e0955f44f49b0861b496a4a0f9566c2528cbfd69416aaab81fb98aeedf24" - }, - { - "ordinal": 46, - "sourceHash": "8868b837dc0ce140e59552d8ea9da27f6e547cd5c6e3ea230dba383183ea809b", - "targetHash": "2cea3a29070d526beba0ae632a20eff47dcd8b6371cdbf56d3343e01a26110c8" - }, - { - "ordinal": 47, - "sourceHash": "b43c2af4e54526ac8aa49e43f8052e982e12c879d495e25e489769c0a2fe6d38", - "targetHash": "74b669208c873e54245e57f53da423d6cf8d8bde2d064ff8fc2ae69eca7b383c" - } - ] - } - }, - { - "id": "identity-standard-14", - "path": ".agents/rulebook/domains/identity-reload.md", - "anchor": "identity-standard-14", - "source": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b:docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "sourceSection": 14, - "sourceHash": "b04c5ad7493811978bc460e2dfe6f77919b7024e230bb0f8fc2afff0f790ebeb", - "requires": [], - "paths": [], - "tags": [ - "identity-standard" - ], - "reviewer": "implementing owner", - "check": "full source section preservation + semantic review", - "translation": { - "language": "en", - "approval": "User-approved English Documentation, AI Workflow, and CI/CD Modernization plan", - "review": ".agents/records/decisions/ENGLISH_RULE_PRESERVATION.md", - "lines": [ - { - "ordinal": 1, - "sourceHash": "44bdb92c728dc030c682de99ff55c7bc2d3d706281979361e7371da1cd2ebaa3", - "targetHash": "daf36302d83833a011268b63658437a5369ec3880cfeb7fd46f6507b405ee6c8" - }, - { - "ordinal": 2, - "sourceHash": "f544a9fdbe99713a38cdea11f261d92f159d385ab391e56f4ba63ff0f894bb33", - "targetHash": "e9240abee48d7f0b44e532ca09189d067de00eb65291e0f93b5dc5139b899457" - }, - { - "ordinal": 3, - "sourceHash": "a44c25b5b54146e969cf15d3c187987f9973af96a0e6b44a690f9c9b97c68549", - "targetHash": "8d749a1372a89f5cb497a3a9719c7109b3a6430bafeffbc964ee2f158cd77291" - } - ] - } - } - ], - "routes": [ - { - "pattern": "\\.cs$", - "units": [ - "naming", - "members", - "xml", - "errors", - "formatting", - "csharp-standard-0", - "csharp-standard-5", - "csharp-standard-8", - "csharp-standard-9", - "csharp-style", - "csharp-style-files", - "csharp-style-namespaces", - "csharp-style-naming", - "csharp-style-types", - "csharp-style-members", - "csharp-style-member-order", - "csharp-style-braces", - "csharp-style-parameters", - "csharp-style-line-breaks", - "csharp-style-initializers", - "csharp-style-spacing", - "csharp-style-idioms", - "csharp-style-control-flow", - "csharp-style-comments", - "csharp-style-tests", - "csharp-style-exceptions", - "csharp-style-example" - ] - }, - { - "pattern": "(\\.csproj$|\\.slnx?$|\\.props$|\\.targets$)", - "units": [ - "solution", - "directories" - ] - }, - { - "pattern": "(^tests/|/tests/)", - "units": [ - "tests", - "compilation", - "review" - ] - }, - { - "pattern": "(scripting|ScriptingApi)", - "units": [ - "scripting", - "identity-reload" - ] - }, - { - "pattern": "(plugins|identity|scene|assets)", - "units": [ - "identity-reload" - ] - }, - { - "pattern": "plugins", - "units": [ - "plugins", - "no-legacy" - ] - }, - { - "pattern": "composition/editor", - "units": [ - "editor-projects" - ] - }, - { - "pattern": "(editor/.+(presentation|panels)|ImGui)", - "units": [ - "editor-layout", - "editor-acceptance" - ] - }, - { - "pattern": "(History|Workspace|State)", - "units": [ - "editor-state" - ] - }, - { - "pattern": "rendering", - "units": [ - "rendering", - "content-frame" - ] - }, - { - "pattern": "^(build/|backends/|platforms/|\\.github/|Directory\\.(Build|Solution)\\.(props|targets)$)", - "units": [ - "build-host", - "platform-products", - "backend-build" - ] - }, - { - "pattern": "^(AGENTS\\.md$|CONTRIBUTING\\.md$|\\.agents/(rulebook|skills)/)", - "units": [ - "completion", - "review" - ] - }, - { - "pattern": "^\\.agents/records/", - "units": [ - "review" - ] - } - ], - "supplementalSources": [ - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 0, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-0", - "hash": "1ae167521e9170f3f63e3f8945bdb849e260d44c79aa523435df060da55077ab" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 1, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-1", - "hash": "e6bb6be83dda2765ee0b7f4147efe8d179357e106fa40a77b666d79b6f7764d0" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 2, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-2", - "hash": "cd7faf5c94f1eaf2ce951777b9dbc7220c57528b38bfe38f1b47ae1cb18470ec" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 3, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-3", - "hash": "75f0a926f0b06b60c211588ca953b239d229e9967fcca8f7cc8a27be8091a3e7" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 4, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-4", - "hash": "30b69ca4a4f4788914691f57fbf66ea5f84a89b41b4d123b57f3c294e926deb8" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 5, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-5", - "hash": "ace556d3813740e6a4e788f488e34cb5fc4442a4b15f50db0349e7effaffc237" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 6, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-6", - "hash": "9513894db97113c26aa081c3cd9d382cdf0ee4676d5c15cb127e0c54103d6194" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 7, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-7", - "hash": "d2f70bc4ab9ed29686da1c043ffd9630fc160b4ad5259a2dc48ea698e90b56c7" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 8, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-8", - "hash": "d59caf636e6d1a2614a542203c5d2e502d47299ad9b434c12083afa1642b0020" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 9, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-9", - "hash": "264a7aa49566628811332c607f0a852dfa14135e8319c3945e20e8f7bd7f1425" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 10, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-10", - "hash": "8e9915979f7d691ef5b067c80bcbf944331135f4d4073e1e90db7fd6b5cddbce" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 11, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-11", - "hash": "594831b9bba1df40656233274f526cd7462d02baef33d61b47a401ca3b77cf42" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 12, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-12", - "hash": "ec9f401d7f7c23a50e563ee86d16a3a852ddb58c3c595ba4b6be4619650627f4" - }, - { - "source": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "section": 13, - "target": ".agents/rulebook/coding.md", - "unit": "csharp-standard-13", - "hash": "b52fbd3c7d57be9738c521c668ba64a2493bc01d6b44c8100f9d3fd75a8b08d4" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 0, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-0", - "hash": "2b3f30679024db5d9b1d07ff1086179e79654d12aeb7d585f9101d857c7c5cd5", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 1, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-1", - "hash": "6b05a0ec83b508519b83132ffd74c35db7f53ebd1d955367afd966333a3e9c30", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 2, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-2", - "hash": "652d09619bf30978b0061ed778331dd33c9154f3ce49c509f05b128e6fd909fa", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 3, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-3", - "hash": "d50017b48c0e71a1ce5f026d029ffb6ee93a88d8d018a5f002118d88aa00314c", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 4, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-4", - "hash": "b4e203ad58328e392684d984491729c023a8643bb8daf527e3c1431dfa495196", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 5, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-5", - "hash": "d17e16a584ffa310b40873a100b302ae616e77495c262be03a8d6c9a14565b66", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/DOCUMENTATION_STANDARD.md", - "section": 6, - "target": ".agents/rulebook/documentation.md", - "unit": "documentation-standard-6", - "hash": "e4755ac95fa67c8079c901ee495f1f523c103f3a0f2d7bf419a9e2760367a8f2", - "repository": "Wolfiora/InnoEngine.Docs" - }, - { - "source": "docs/architecture/EDITOR_UI_DESIGN_STANDARD.md", - "section": 9, - "target": ".agents/rulebook/domains/editor.md", - "unit": "editor-standard-9", - "hash": "4c27d71eeeb375245a649934a3e280a722687d62110e88c0ca371ea607dade70" - }, - { - "source": "docs/architecture/EDITOR_UI_DESIGN_STANDARD.md", - "section": 10, - "target": ".agents/rulebook/domains/editor.md", - "unit": "editor-standard-10", - "hash": "7c051be2869f46bd2beac2d5dacfd75da8afb5b39047d02955d8c4bea5fcb475" - }, - { - "source": "docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "section": 12, - "target": ".agents/rulebook/domains/identity-reload.md", - "unit": "identity-standard-12", - "hash": "c04a13c50f3dfe682a2b41855e42100b349db014d40a7a06530c0b3ee4dd6779" - }, - { - "source": "docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "section": 13, - "target": ".agents/rulebook/domains/identity-reload.md", - "unit": "identity-standard-13", - "hash": "52493148de955847cbea6609f0c895bfdefe5008ba5cbd50a6283a5664cac692" - }, - { - "source": "docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "section": 14, - "target": ".agents/rulebook/domains/identity-reload.md", - "unit": "identity-standard-14", - "hash": "b04c5ad7493811978bc460e2dfe6f77919b7024e230bb0f8fc2afff0f790ebeb" - } - ], - "migrationBaseline": "6e2cd51e4a5f7c3df1119a840e100b5cea90a57b", - "pathReplacements": [ - { - "old": "`docs/core`", - "current": "`docs/modules/core`" - }, - { - "old": "`docs/assets`", - "current": "`docs/modules/assets`" - }, - { - "old": "`docs/engine`", - "current": "`docs/modules/runtime`" - }, - { - "old": "`docs/rendering`", - "current": "`docs/modules/rendering`" - }, - { - "old": "`docs/editor`", - "current": "`docs/modules/editor`" - }, - { - "old": "docs/core/Inno.Extensibility.Types.md", - "current": "docs/modules/extensibility/Inno.Extensibility.Types.md" - }, - { - "old": "`records/`", - "current": "`.agents/records/`" - }, - { - "old": "docs/testing/Inno.Assets.Pipeline.DuplicateImporterFixture.md", - "current": "docs/development/testing/Inno.Assets.Pipeline.DuplicateImporterFixture.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Modules.TestModule.Invalid.md", - "current": "docs/development/testing/Inno.Extensibility.Modules.TestModule.Invalid.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Modules.TestDependency.md", - "current": "docs/development/testing/Inno.Extensibility.Modules.TestDependency.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Modules.TestModule.V1.md", - "current": "docs/development/testing/Inno.Extensibility.Modules.TestModule.V1.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Modules.TestModule.V2.md", - "current": "docs/development/testing/Inno.Extensibility.Modules.TestModule.V2.md" - }, - { - "old": "docs/testing/Inno.Rendering.Runtime.Reload.TestModule.md", - "current": "docs/development/testing/Inno.Rendering.Runtime.Reload.TestModule.md" - }, - { - "old": "docs/architecture/IDENTITY_REFERENCE_RELOAD_STANDARD.md", - "current": "docs/architecture/identity-and-reload.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Types.TestAssemblyA.md", - "current": "docs/development/testing/Inno.Extensibility.Types.TestAssemblyA.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Types.TestAssemblyB.md", - "current": "docs/development/testing/Inno.Extensibility.Types.TestAssemblyB.md" - }, - { - "old": "docs/testing/Inno.Adapter.Content.FileSystem.Tests.md", - "current": "docs/development/testing/Inno.Adapter.Content.FileSystem.Tests.md" - }, - { - "old": "docs/testing/Inno.Rendering.Assets.Authoring.Tests.md", - "current": "docs/development/testing/Inno.Rendering.Assets.Authoring.Tests.md" - }, - { - "old": "docs/architecture/NATIVE_BUILD_PLATFORM_OWNERSHIP.md", - "current": "docs/architecture/platform-and-products.md" - }, - { - "old": "docs/architecture/DEVELOPMENT_ENTRY_ARCHITECTURE.md", - "current": "docs/development/entry/README.md" - }, - { - "old": "docs/architecture/PLATFORM_RUNTIME_ARCHITECTURE.md", - "current": "docs/architecture/platform-and-products.md" - }, - { - "old": "docs/rendering/Inno.Adapter.Rendering.Authoring.md", - "current": "docs/modules/rendering/Inno.Adapter.Rendering.Authoring.md" - }, - { - "old": "docs/testing/Inno.Adapter.Audio.MiniAudio.Tests.md", - "current": "docs/development/testing/Inno.Adapter.Audio.MiniAudio.Tests.md" - }, - { - "old": "docs/testing/Inno.Build.NativePerformance.Tests.md", - "current": "docs/development/testing/Inno.Build.NativePerformance.Tests.md" - }, - { - "old": "docs/architecture/ENGINE_ARCHITECTURE_OVERVIEW.md", - "current": "docs/architecture/overview.md" - }, - { - "old": "docs/extensibility/Inno.Extensibility.Catalogs.md", - "current": "docs/modules/extensibility/Inno.Extensibility.Catalogs.md" - }, - { - "old": "docs/rendering/Inno.Rendering.Assets.Authoring.md", - "current": "docs/modules/rendering/Inno.Rendering.Assets.Authoring.md" - }, - { - "old": "docs/testing/Inno.Adapter.Rendering.Bgfx.Tests.md", - "current": "docs/development/testing/Inno.Adapter.Rendering.Bgfx.Tests.md" - }, - { - "old": "docs/architecture/CSHARP_DEVELOPMENT_STANDARD.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/extensibility/Inno.Extensibility.Modules.md", - "current": "docs/modules/extensibility/Inno.Extensibility.Modules.md" - }, - { - "old": "docs/testing/Inno.Adapter.Platform.Sdl3.Tests.md", - "current": "docs/development/testing/Inno.Adapter.Platform.Sdl3.Tests.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Modules.Tests.md", - "current": "docs/development/testing/Inno.Extensibility.Modules.Tests.md" - }, - { - "old": "docs/core/Inno.Core.Serialization.Generators.md", - "current": "docs/modules/core/Inno.Core.Serialization.Generators.md" - }, - { - "old": "docs/extensibility/Inno.Extensibility.Reload.md", - "current": "docs/modules/extensibility/Inno.Extensibility.Reload.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Reload.Tests.md", - "current": "docs/development/testing/Inno.Extensibility.Reload.Tests.md" - }, - { - "old": "docs/tooling/Inno.Tooling.Architecture.Tests.md", - "current": "docs/development/testing/Inno.Tooling.Architecture.Tests.md" - }, - { - "old": "docs/architecture/EDITOR_UI_DESIGN_STANDARD.md", - "current": "docs/architecture/editor-ui.md" - }, - { - "old": "docs/build/Inno.Build.Distribution.Standard.md", - "current": "docs/development/build/Inno.Build.Distribution.Standard.md" - }, - { - "old": "docs/extensibility/Inno.Extensibility.Types.md", - "current": "docs/modules/extensibility/Inno.Extensibility.Types.md" - }, - { - "old": "docs/rendering/Inno.Rendering.Shaders.Tests.md", - "current": "docs/development/testing/Inno.Rendering.Shaders.Tests.md" - }, - { - "old": "docs/runtime/Inno.Adapter.Authoring.Default.md", - "current": "docs/modules/runtime/Inno.Adapter.Authoring.Default.md" - }, - { - "old": "docs/testing/Inno.Editor.Interactions.Tests.md", - "current": "docs/development/testing/Inno.Editor.Interactions.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.Presentation.Tests.md", - "current": "docs/development/testing/Inno.Editor.Presentation.Tests.md" - }, - { - "old": "docs/testing/Inno.Extensibility.Types.Tests.md", - "current": "docs/development/testing/Inno.Extensibility.Types.Tests.md" - }, - { - "old": "docs/architecture/BUILD_CACHE_ARCHITECTURE.md", - "current": "docs/architecture/build-and-cache.md" - }, - { - "old": "docs/architecture/PLATFORM_EXTENSION_GUIDE.md", - "current": "docs/development/adding-platform.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.ShaderEditor.md", - "current": "docs/modules/editor/Inno.Editor.Panel.ShaderEditor.md" - }, - { - "old": "docs/testing/Inno.Core.Serialization.Tests.md", - "current": "docs/development/testing/Inno.Core.Serialization.Tests.md" - }, - { - "old": "docs/testing/Inno.Runtime.Generators.Tests.md", - "current": "docs/development/testing/Inno.Runtime.Generators.Tests.md" - }, - { - "old": "docs/testing/Inno.Scripting.Compiler.Tests.md", - "current": "docs/development/testing/Inno.Scripting.Compiler.Tests.md" - }, - { - "old": "docs/tooling/Inno.Tooling.Validation.Tests.md", - "current": "docs/development/testing/Inno.Tooling.Validation.Tests.md" - }, - { - "old": "docs/architecture/WEB_PLAYER_ARCHITECTURE.md", - "current": "docs/architecture/web-player.md" - }, - { - "old": "docs/architecture/rules/editor-acceptance.md", - "current": ".agents/rulebook/domains/editor.md" - }, - { - "old": "docs/architecture/rules/platform-products.md", - "current": ".agents/rulebook/domains/build-native.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.FileBrowser.md", - "current": "docs/modules/editor/Inno.Editor.Panel.FileBrowser.md" - }, - { - "old": "docs/testing/Inno.Editor.Inspection.Tests.md", - "current": "docs/development/testing/Inno.Editor.Inspection.Tests.md" - }, - { - "old": "docs/testing/Inno.Rendering.Runtime.Tests.md", - "current": "docs/development/testing/Inno.Rendering.Runtime.Tests.md" - }, - { - "old": "docs/testing/Inno.Scene.Reload.TestModule.md", - "current": "docs/development/testing/Inno.Scene.Reload.TestModule.md" - }, - { - "old": "docs/testing/Inno.Testing.Processes.Tests.md", - "current": "docs/development/testing/Inno.Testing.Processes.Tests.md" - }, - { - "old": "docs/architecture/DOCUMENTATION_STANDARD.md", - "current": ".agents/rulebook/documentation.md" - }, - { - "old": "docs/architecture/EDITOR_UI_ARCHITECTURE.md", - "current": "docs/architecture/editor-ui.md" - }, - { - "old": "docs/testing/Inno.Build.Toolchains.Tests.md", - "current": "docs/development/testing/Inno.Build.Toolchains.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Collections.Tests.md", - "current": "docs/development/testing/Inno.Core.Collections.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Diagnostics.Tests.md", - "current": "docs/development/testing/Inno.Core.Diagnostics.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Mathematics.Tests.md", - "current": "docs/development/testing/Inno.Core.Mathematics.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.Scripting.Tests.md", - "current": "docs/development/testing/Inno.Editor.Scripting.Tests.md" - }, - { - "old": "docs/testing/Inno.Native.MiniAudio.Tests.md", - "current": "docs/development/testing/Inno.Native.MiniAudio.Tests.md" - }, - { - "old": "docs/testing/Inno.Rendering.Assets.Tests.md", - "current": "docs/development/testing/Inno.Rendering.Assets.Tests.md" - }, - { - "old": "docs/architecture/rules/editor-projects.md", - "current": ".agents/rulebook/domains/editor.md" - }, - { - "old": "docs/architecture/rules/identity-naming.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/architecture/rules/identity-reload.md", - "current": ".agents/rulebook/domains/identity-reload.md" - }, - { - "old": "docs/build/Inno.Build.Products.Standard.md", - "current": "docs/development/build/Inno.Build.Products.Standard.md" - }, - { - "old": "docs/build/Inno.Build.SupportPacks.Core.md", - "current": "docs/development/build/Inno.Build.SupportPacks.Core.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.Hierarchy.md", - "current": "docs/modules/editor/Inno.Editor.Panel.Hierarchy.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.Inspector.md", - "current": "docs/modules/editor/Inno.Editor.Panel.Inspector.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.SceneView.md", - "current": "docs/modules/editor/Inno.Editor.Panel.SceneView.md" - }, - { - "old": "docs/testing/Inno.Assets.Pipeline.Tests.md", - "current": "docs/development/testing/Inno.Assets.Pipeline.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Coroutines.Tests.md", - "current": "docs/development/testing/Inno.Core.Coroutines.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.PlayMode.Tests.md", - "current": "docs/development/testing/Inno.Editor.PlayMode.Tests.md" - }, - { - "old": "docs/testing/Inno.Native.ImGuizmo.Tests.md", - "current": "docs/development/testing/Inno.Native.ImGuizmo.Tests.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.GameView.md", - "current": "docs/modules/editor/Inno.Editor.Panel.GameView.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.Settings.md", - "current": "docs/modules/editor/Inno.Editor.Panel.Settings.md" - }, - { - "old": "docs/scripting/Inno.Scripting.Compiler.md", - "current": "docs/modules/scripting/Inno.Scripting.Compiler.md" - }, - { - "old": "docs/testing/Inno.Core.Execution.Tests.md", - "current": "docs/development/testing/Inno.Core.Execution.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.Hosting.Tests.md", - "current": "docs/development/testing/Inno.Editor.Hosting.Tests.md" - }, - { - "old": "docs/tooling/Inno.Tooling.Architecture.md", - "current": "docs/development/tooling/Inno.Tooling.Architecture.md" - }, - { - "old": "docs/animation/Inno.Animation.Runtime.md", - "current": "docs/modules/animation/Inno.Animation.Runtime.md" - }, - { - "old": "docs/architecture/rules/backend-build.md", - "current": ".agents/rulebook/domains/build-native.md" - }, - { - "old": "docs/architecture/rules/content-frame.md", - "current": ".agents/rulebook/domains/rendering.md" - }, - { - "old": "docs/architecture/rules/editor-layout.md", - "current": ".agents/rulebook/domains/editor.md" - }, - { - "old": "docs/architecture/rules/encapsulation.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.Logging.md", - "current": "docs/modules/editor/Inno.Editor.Panel.Logging.md" - }, - { - "old": "docs/editor/Inno.Editor.Shaders.ImGui.md", - "current": "docs/modules/editor/Inno.Editor.Shaders.ImGui.md" - }, - { - "old": "docs/rendering/Inno.Adapter.Rendering.md", - "current": "docs/modules/rendering/Inno.Adapter.Rendering.md" - }, - { - "old": "docs/rendering/Inno.Rendering.Runtime.md", - "current": "docs/modules/rendering/Inno.Rendering.Runtime.md" - }, - { - "old": "docs/rendering/Inno.Rendering.Shaders.md", - "current": "docs/modules/rendering/Inno.Rendering.Shaders.md" - }, - { - "old": "docs/testing/Inno.Audio.Runtime.Tests.md", - "current": "docs/development/testing/Inno.Audio.Runtime.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Identity.Tests.md", - "current": "docs/development/testing/Inno.Core.Identity.Tests.md" - }, - { - "old": "docs/animation/Inno.Animation.Assets.md", - "current": "docs/modules/animation/Inno.Animation.Assets.md" - }, - { - "old": "docs/architecture/CURRENT_ACCEPTANCE.md", - "current": ".agents/records/acceptance/current.md" - }, - { - "old": "docs/architecture/rules/architecture.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/architecture/rules/editor-state.md", - "current": ".agents/rulebook/domains/editor.md" - }, - { - "old": "docs/architecture/rules/notification.md", - "current": ".agents/rulebook/delivery.md" - }, - { - "old": "docs/editor/Inno.Editor.Assets.ImGui.md", - "current": "docs/modules/editor/Inno.Editor.Assets.ImGui.md" - }, - { - "old": "docs/editor/Inno.Editor.Interactions.md", - "current": "docs/modules/editor/Inno.Editor.Interactions.md" - }, - { - "old": "docs/rendering/Inno.Rendering.Assets.md", - "current": "docs/modules/rendering/Inno.Rendering.Assets.md" - }, - { - "old": "docs/runtime/Inno.Runtime.Generators.md", - "current": "docs/modules/runtime/Inno.Runtime.Generators.md" - }, - { - "old": "docs/scripting/Inno.Scripting.Reload.md", - "current": "docs/modules/scripting/Inno.Scripting.Reload.md" - }, - { - "old": "docs/testing/Inno.Audio.Assets.Tests.md", - "current": "docs/development/testing/Inno.Audio.Assets.Tests.md" - }, - { - "old": "docs/testing/Inno.Content.CacheProbe.md", - "current": "docs/development/testing/Inno.Content.CacheProbe.md" - }, - { - "old": "docs/testing/Inno.Core.Logging.Tests.md", - "current": "docs/development/testing/Inno.Core.Logging.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.Audio.Tests.md", - "current": "docs/development/testing/Inno.Editor.Audio.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.Graph.Tests.md", - "current": "docs/development/testing/Inno.Editor.Graph.Tests.md" - }, - { - "old": "docs/testing/Inno.Editor.ImGui.Tests.md", - "current": "docs/development/testing/Inno.Editor.ImGui.Tests.md" - }, - { - "old": "docs/testing/Inno.Native.ImGui.Tests.md", - "current": "docs/development/testing/Inno.Native.ImGui.Tests.md" - }, - { - "old": "docs/tooling/Inno.Tooling.Validation.md", - "current": "docs/development/tooling/Inno.Tooling.Validation.md" - }, - { - "old": "docs/architecture/rules/compilation.md", - "current": ".agents/rulebook/validation.md" - }, - { - "old": "docs/architecture/rules/directories.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/editor/Inno.Editor.Annotations.md", - "current": "docs/modules/editor/Inno.Editor.Annotations.md" - }, - { - "old": "docs/editor/Inno.Editor.Diagnostics.md", - "current": "docs/modules/editor/Inno.Editor.Diagnostics.md" - }, - { - "old": "docs/editor/Inno.Editor.Graph.ImGui.md", - "current": "docs/modules/editor/Inno.Editor.Graph.ImGui.md" - }, - { - "old": "docs/editor/Inno.Editor.Panel.Stats.md", - "current": "docs/modules/editor/Inno.Editor.Panel.Stats.md" - }, - { - "old": "docs/plugins/Inno.Plugins.Authoring.md", - "current": "docs/modules/plugins/Inno.Plugins.Authoring.md" - }, - { - "old": "docs/runtime/Inno.Runtime.Contracts.md", - "current": "docs/modules/runtime/Inno.Runtime.Contracts.md" - }, - { - "old": "docs/testing/Inno.Core.Events.Tests.md", - "current": "docs/development/testing/Inno.Core.Events.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Graphs.Tests.md", - "current": "docs/development/testing/Inno.Core.Graphs.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.Layers.Tests.md", - "current": "docs/development/testing/Inno.Core.Layers.Tests.md" - }, - { - "old": "docs/testing/Inno.Native.Bgfx.Tests.md", - "current": "docs/development/testing/Inno.Native.Bgfx.Tests.md" - }, - { - "old": "docs/testing/Inno.Native.Sdl3.Tests.md", - "current": "docs/development/testing/Inno.Native.Sdl3.Tests.md" - }, - { - "old": "docs/testing/Inno.Testing.Processes.md", - "current": "docs/development/testing/Inno.Testing.Processes.md" - }, - { - "old": "docs/ui/Inno.Adapter.UI.RmlUi.Tests.md", - "current": "docs/development/testing/Inno.Adapter.UI.RmlUi.Tests.md" - }, - { - "old": "docs/architecture/rules/build-host.md", - "current": ".agents/rulebook/domains/build-native.md" - }, - { - "old": "docs/architecture/rules/completion.md", - "current": ".agents/rulebook/validation.md" - }, - { - "old": "docs/architecture/rules/core-reuse.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/architecture/rules/formatting.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/editor/Inno.Editor.Inspection.md", - "current": "docs/modules/editor/Inno.Editor.Inspection.md" - }, - { - "old": "docs/testing/Inno.References.Tests.md", - "current": "docs/development/testing/Inno.References.Tests.md" - }, - { - "old": "docs/architecture/rules/no-legacy.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/architecture/rules/rendering.md", - "current": ".agents/rulebook/domains/rendering.md" - }, - { - "old": "docs/architecture/rules/scripting.md", - "current": ".agents/rulebook/domains/scripting.md" - }, - { - "old": "docs/build/Inno.Build.Composition.md", - "current": "docs/development/build/Inno.Build.Composition.md" - }, - { - "old": "docs/build/Inno.Build.TaskHosting.md", - "current": "docs/development/build/Inno.Build.TaskHosting.md" - }, - { - "old": "docs/core/Inno.Core.Serialization.md", - "current": "docs/modules/core/Inno.Core.Serialization.md" - }, - { - "old": "docs/editor/Inno.Editor.Exporting.md", - "current": "docs/modules/editor/Inno.Editor.Exporting.md" - }, - { - "old": "docs/editor/Inno.Editor.Rendering.md", - "current": "docs/modules/editor/Inno.Editor.Rendering.md" - }, - { - "old": "docs/editor/Inno.Editor.Scripting.md", - "current": "docs/modules/editor/Inno.Editor.Scripting.md" - }, - { - "old": "docs/editor/Inno.Editor.Workbench.md", - "current": "docs/modules/editor/Inno.Editor.Workbench.md" - }, - { - "old": "docs/runtime/Inno.Adapter.Default.md", - "current": "docs/modules/runtime/Inno.Adapter.Default.md" - }, - { - "old": "docs/scripting/Inno.Scripting.Api.md", - "current": "docs/modules/scripting/Inno.Scripting.Api.md" - }, - { - "old": "docs/storage/Inno.Adapter.Storage.md", - "current": "docs/modules/storage/Inno.Adapter.Storage.md" - }, - { - "old": "docs/storage/Inno.Storage.Runtime.md", - "current": "docs/modules/storage/Inno.Storage.Runtime.md" - }, - { - "old": "docs/testing/Inno.Animation.Tests.md", - "current": "docs/development/testing/Inno.Animation.Tests.md" - }, - { - "old": "docs/testing/Inno.Content.Testing.md", - "current": "docs/development/testing/Inno.Content.Testing.md" - }, - { - "old": "docs/testing/Inno.Core.Jobs.Tests.md", - "current": "docs/development/testing/Inno.Core.Jobs.Tests.md" - }, - { - "old": "docs/testing/Inno.Rendering.Tests.md", - "current": "docs/development/testing/Inno.Rendering.Tests.md" - }, - { - "old": "docs/architecture/CURRENT_ISSUES.md", - "current": ".agents/records/open-items.md" - }, - { - "old": "docs/architecture/rules/delivery.md", - "current": ".agents/rulebook/delivery.md" - }, - { - "old": "docs/architecture/rules/solution.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/assets/Inno.Assets.Pipeline.md", - "current": "docs/modules/assets/Inno.Assets.Pipeline.md" - }, - { - "old": "docs/build/DEPENDENCY_SUBMISSION.md", - "current": "docs/development/build/DEPENDENCY_SUBMISSION.md" - }, - { - "old": "docs/build/Inno.Build.Toolchains.md", - "current": "docs/development/build/Inno.Build.Toolchains.md" - }, - { - "old": "docs/editor/Inno.Editor.PlayMode.md", - "current": "docs/modules/editor/Inno.Editor.PlayMode.md" - }, - { - "old": "docs/editor/Inno.Editor.Settings.md", - "current": "docs/modules/editor/Inno.Editor.Settings.md" - }, - { - "old": "docs/runtime/Inno.Engine.Default.md", - "current": "docs/modules/runtime/Inno.Engine.Default.md" - }, - { - "old": "docs/runtime/Inno.Player.Runtime.md", - "current": "docs/modules/runtime/Inno.Player.Runtime.md" - }, - { - "old": "docs/testing/Inno.Testing.Source.md", - "current": "docs/development/testing/Inno.Testing.Source.md" - }, - { - "old": "docs/architecture/rules/members.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/architecture/rules/plugins.md", - "current": ".agents/rulebook/domains/plugins.md" - }, - { - "old": "docs/core/Inno.Core.Collections.md", - "current": "docs/modules/core/Inno.Core.Collections.md" - }, - { - "old": "docs/core/Inno.Core.Diagnostics.md", - "current": "docs/modules/core/Inno.Core.Diagnostics.md" - }, - { - "old": "docs/core/Inno.Core.Mathematics.md", - "current": "docs/modules/core/Inno.Core.Mathematics.md" - }, - { - "old": "docs/editor/Inno.Editor.Hosting.md", - "current": "docs/modules/editor/Inno.Editor.Hosting.md" - }, - { - "old": "docs/editor/Inno.Editor.Shaders.md", - "current": "docs/modules/editor/Inno.Editor.Shaders.md" - }, - { - "old": "docs/references/Inno.References.md", - "current": "docs/modules/references/Inno.References.md" - }, - { - "old": "docs/testing/Inno.Content.Tests.md", - "current": "docs/development/testing/Inno.Content.Tests.md" - }, - { - "old": "docs/testing/Inno.Core.IO.Tests.md", - "current": "docs/development/testing/Inno.Core.IO.Tests.md" - }, - { - "old": "docs/testing/Inno.Plugins.Tests.md", - "current": "docs/development/testing/Inno.Plugins.Tests.md" - }, - { - "old": "docs/testing/Inno.Runtime.Tests.md", - "current": "docs/development/testing/Inno.Runtime.Tests.md" - }, - { - "old": "docs/testing/Inno.Storage.Tests.md", - "current": "docs/development/testing/Inno.Storage.Tests.md" - }, - { - "old": "docs/architecture/rules/README.md", - "current": ".agents/rulebook/README.md" - }, - { - "old": "docs/architecture/rules/errors.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/architecture/rules/naming.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/architecture/rules/review.md", - "current": ".agents/rulebook/validation.md" - }, - { - "old": "docs/build/Inno.Build.Bindings.md", - "current": "docs/development/build/Inno.Build.Bindings.md" - }, - { - "old": "docs/core/Inno.Core.Coroutines.md", - "current": "docs/modules/core/Inno.Core.Coroutines.md" - }, - { - "old": "docs/editor/Inno.Editor.Assets.md", - "current": "docs/modules/editor/Inno.Editor.Assets.md" - }, - { - "old": "docs/testing/Inno.Assets.Tests.md", - "current": "docs/development/testing/Inno.Assets.Tests.md" - }, - { - "old": "docs/animation/Inno.Animation.md", - "current": "docs/modules/animation/Inno.Animation.md" - }, - { - "old": "docs/architecture/rules/style.md", - "current": ".agents/rulebook/architecture.md" - }, - { - "old": "docs/architecture/rules/tests.md", - "current": ".agents/rulebook/validation.md" - }, - { - "old": "docs/audio/Inno.Adapter.Audio.md", - "current": "docs/modules/audio/Inno.Adapter.Audio.md" - }, - { - "old": "docs/audio/Inno.Audio.Runtime.md", - "current": "docs/modules/audio/Inno.Audio.Runtime.md" - }, - { - "old": "docs/build/Inno.Build.Managed.md", - "current": "docs/development/build/Inno.Build.Managed.md" - }, - { - "old": "docs/core/Inno.Core.Execution.md", - "current": "docs/modules/core/Inno.Core.Execution.md" - }, - { - "old": "docs/editor/Inno.Editor.Audio.md", - "current": "docs/modules/editor/Inno.Editor.Audio.md" - }, - { - "old": "docs/editor/Inno.Editor.Graph.md", - "current": "docs/modules/editor/Inno.Editor.Graph.md" - }, - { - "old": "docs/editor/Inno.Editor.ImGui.md", - "current": "docs/modules/editor/Inno.Editor.ImGui.md" - }, - { - "old": "docs/editor/Inno.Editor.Scene.md", - "current": "docs/modules/editor/Inno.Editor.Scene.md" - }, - { - "old": "docs/input/Inno.Adapter.Input.md", - "current": "docs/modules/input/Inno.Adapter.Input.md" - }, - { - "old": "docs/input/Inno.Input.Runtime.md", - "current": "docs/modules/input/Inno.Input.Runtime.md" - }, - { - "old": "docs/native/BindingGeneration.md", - "current": "docs/development/native-bindings.md" - }, - { - "old": "docs/rendering/Inno.Rendering.md", - "current": "docs/modules/rendering/Inno.Rendering.md" - }, - { - "old": "docs/testing/Inno.Audio.Tests.md", - "current": "docs/development/testing/Inno.Audio.Tests.md" - }, - { - "old": "docs/testing/Inno.Build.Tests.md", - "current": "docs/development/testing/Inno.Build.Tests.md" - }, - { - "old": "docs/testing/Inno.Input.Tests.md", - "current": "docs/development/testing/Inno.Input.Tests.md" - }, - { - "old": "docs/testing/Inno.Scene.Tests.md", - "current": "docs/development/testing/Inno.Scene.Tests.md" - }, - { - "old": "docs/architecture/rules/wiki.md", - "current": ".agents/rulebook/documentation.md" - }, - { - "old": "docs/audio/Inno.Audio.Assets.md", - "current": "docs/modules/audio/Inno.Audio.Assets.md" - }, - { - "old": "docs/core/Inno.Core.Identity.md", - "current": "docs/modules/core/Inno.Core.Identity.md" - }, - { - "old": "docs/core/Inno.Core.Settings.md", - "current": "docs/modules/core/Inno.Core.Settings.md" - }, - { - "old": "docs/editor/Inno.Editor.Core.md", - "current": "docs/modules/editor/Inno.Editor.Core.md" - }, - { - "old": "docs/entry/InnoEngine.Editor.md", - "current": "docs/development/entry/InnoEngine.Editor.md" - }, - { - "old": "docs/scene/Inno.Scene.Assets.md", - "current": "docs/modules/scene/Inno.Scene.Assets.md" - }, - { - "old": "docs/architecture/rules/xml.md", - "current": ".agents/rulebook/coding.md" - }, - { - "old": "docs/build/Inno.Build.Tasks.md", - "current": "docs/development/build/Inno.Build.Tasks.md" - }, - { - "old": "docs/core/Inno.Core.Logging.md", - "current": "docs/modules/core/Inno.Core.Logging.md" - }, - { - "old": "docs/entry/InnoEngine.Build.md", - "current": "docs/development/entry/InnoEngine.Build.md" - }, - { - "old": "docs/text/Inno.Adapter.Text.md", - "current": "docs/modules/text/Inno.Adapter.Text.md" - }, - { - "old": "docs/text/Inno.Text.Runtime.md", - "current": "docs/modules/text/Inno.Text.Runtime.md" - }, - { - "old": "docs/core/Inno.Core.Events.md", - "current": "docs/modules/core/Inno.Core.Events.md" - }, - { - "old": "docs/core/Inno.Core.Graphs.md", - "current": "docs/modules/core/Inno.Core.Graphs.md" - }, - { - "old": "docs/core/Inno.Core.Layers.md", - "current": "docs/modules/core/Inno.Core.Layers.md" - }, - { - "old": "docs/text/Inno.Text.Assets.md", - "current": "docs/modules/text/Inno.Text.Assets.md" - }, - { - "old": "docs/build/Inno.Build.Cli.md", - "current": "docs/development/build/Inno.Build.Cli.md" - }, - { - "old": "docs/core/Inno.Core.Input.md", - "current": "docs/modules/core/Inno.Core.Input.md" - }, - { - "old": "docs/extensibility/README.md", - "current": "docs/modules/extensibility/README.md" - }, - { - "old": "docs/plugins/Inno.Plugins.md", - "current": "docs/modules/plugins/Inno.Plugins.md" - }, - { - "old": "docs/runtime/Inno.Adapter.md", - "current": "docs/modules/runtime/Inno.Adapter.md" - }, - { - "old": "docs/runtime/Inno.Runtime.md", - "current": "docs/modules/runtime/Inno.Runtime.md" - }, - { - "old": "docs/storage/Inno.Storage.md", - "current": "docs/modules/storage/Inno.Storage.md" - }, - { - "old": "docs/text/Inno.Text.Tests.md", - "current": "docs/development/testing/Inno.Text.Tests.md" - }, - { - "old": "docs/assets/Inno.Content.md", - "current": "docs/modules/assets/Inno.Content.md" - }, - { - "old": "docs/core/Inno.Core.Jobs.md", - "current": "docs/modules/core/Inno.Core.Jobs.md" - }, - { - "old": "docs/assets/Inno.Assets.md", - "current": "docs/modules/assets/Inno.Assets.md" - }, - { - "old": "docs/runtime/Inno.Shell.md", - "current": "docs/modules/runtime/Inno.Shell.md" - }, - { - "old": "docs/ui/Inno.Adapter.UI.md", - "current": "docs/modules/ui/Inno.Adapter.UI.md" - }, - { - "old": "docs/ui/Inno.UI.Runtime.md", - "current": "docs/modules/ui/Inno.UI.Runtime.md" - }, - { - "old": "docs/core/Inno.Core.IO.md", - "current": "docs/modules/core/Inno.Core.IO.md" - }, - { - "old": "docs/references/README.md", - "current": "docs/modules/references/README.md" - }, - { - "old": "docs/ui/Inno.UI.Assets.md", - "current": "docs/modules/ui/Inno.UI.Assets.md" - }, - { - "old": "docs/animation/README.md", - "current": "docs/modules/animation/README.md" - }, - { - "old": "docs/audio/Inno.Audio.md", - "current": "docs/modules/audio/Inno.Audio.md" - }, - { - "old": "docs/build/Inno.Build.md", - "current": "docs/development/build/Inno.Build.md" - }, - { - "old": "docs/input/Inno.Input.md", - "current": "docs/modules/input/Inno.Input.md" - }, - { - "old": "docs/rendering/README.md", - "current": "docs/modules/rendering/README.md" - }, - { - "old": "docs/scene/Inno.Scene.md", - "current": "docs/modules/scene/Inno.Scene.md" - }, - { - "old": "docs/scripting/README.md", - "current": "docs/modules/scripting/README.md" - }, - { - "old": "docs/ui/Inno.UI.Tests.md", - "current": "docs/development/testing/Inno.UI.Tests.md" - }, - { - "old": "docs/plugins/README.md", - "current": "docs/modules/plugins/README.md" - }, - { - "old": "docs/runtime/README.md", - "current": "docs/modules/runtime/README.md" - }, - { - "old": "docs/storage/README.md", - "current": "docs/modules/storage/README.md" - }, - { - "old": "docs/testing/README.md", - "current": "docs/development/testing/README.md" - }, - { - "old": "docs/text/Inno.Text.md", - "current": "docs/modules/text/Inno.Text.md" - }, - { - "old": "docs/tooling/README.md", - "current": "docs/development/tooling/README.md" - }, - { - "old": "docs/assets/README.md", - "current": "docs/modules/assets/README.md" - }, - { - "old": "docs/editor/README.md", - "current": "docs/modules/editor/README.md" - }, - { - "old": "docs/native/README.md", - "current": "docs/development/README.md" - }, - { - "old": "docs/audio/README.md", - "current": "docs/modules/audio/README.md" - }, - { - "old": "docs/build/README.md", - "current": "docs/development/build/README.md" - }, - { - "old": "docs/entry/README.md", - "current": "docs/development/building.md" - }, - { - "old": "docs/input/README.md", - "current": "docs/modules/input/README.md" - }, - { - "old": "docs/scene/README.md", - "current": "docs/modules/scene/README.md" - }, - { - "old": "docs/core/README.md", - "current": "docs/modules/core/README.md" - }, - { - "old": "docs/text/README.md", - "current": "docs/modules/text/README.md" - }, - { - "old": "docs/ui/Inno.UI.md", - "current": "docs/modules/ui/Inno.UI.md" - }, - { - "old": "docs/ui/README.md", - "current": "docs/modules/ui/README.md" - } - ] -} diff --git a/.agents/rulebook/csharp-style.md b/.agents/rulebook/csharp-style.md deleted file mode 100644 index 74f1778b4..000000000 --- a/.agents/rulebook/csharp-style.md +++ /dev/null @@ -1,3527 +0,0 @@ - - -# InnoEngine C# code style - -This rulebook defines how handwritten C# in InnoEngine is named, laid out and written. It applies to every handwritten `.cs` file in the repository, including tests and tools. Third-party sources under `extern/`, generated files (`**/Generated/*.cs` and files carrying an `` header) and the cases listed in [section 16](#16-exceptions) are out of scope. - -The [coding rules](coding.md) own design, error-handling, resource and change-management requirements. This rulebook is the detailed authority for names and layout. - -- Every rule has an ID such as `B-05`. Cite the ID in reviews and commit messages. -- Each rule states the requirement first, then shows a compliant example. A block introduced by **Avoid** shows what the rule forbids. -- "Must", "always" and "never" are requirements. "Prefer" and "recommended" describe the default; deviate only when the default hurts readability. -- External contracts take precedence over this rulebook: interface implementations, overrides, MSBuild task parameters, serialized names and native interop signatures keep the names their contract requires (see [section 16](#16-exceptions)). -- Formatting changes and renames are separate changes. A formatting-only change must not alter names, logic, execution order or public contracts. Renaming a public member is an API change. -- Automatic formatters must preserve these rules. Do not apply a formatter whose output differs from this rulebook. - -Contents - -1. [Files and physical layout](#1-files-and-physical-layout) -2. [Namespaces and using directives](#2-namespaces-and-using-directives) -3. [Naming](#3-naming) -4. [Type declarations](#4-type-declarations) -5. [Member declarations](#5-member-declarations) -6. [Member order](#6-member-order) -7. [Braces and blocks](#7-braces-and-blocks) -8. [Parameter and argument lists](#8-parameter-and-argument-lists) -9. [Line breaks](#9-line-breaks) -10. [Initializers and collections](#10-initializers-and-collections) -11. [Spacing and blank lines](#11-spacing-and-blank-lines) -12. [Types and expression idioms](#12-types-and-expression-idioms) -13. [Control flow, exceptions and asynchronous code](#13-control-flow-exceptions-and-asynchronous-code) -14. [Comments and XML documentation](#14-comments-and-xml-documentation) -15. [Tests](#15-tests) -16. [Exceptions](#16-exceptions) -17. [Reference example](#17-reference-example) - - - - -## 1. Files and physical layout - -### F-01 Encoding, line endings and indentation - -- UTF-8 without a byte order mark. -- LF line endings. -- Four spaces per indentation level. Never use tab characters. -- No trailing whitespace. -- The file ends with exactly one newline. -- At most one consecutive blank line. - -In the next two blocks `→` is a tab, `·` is a space and `¶` is a newline. - -```text -····private int m_count;¶ -}¶ -``` - -Avoid (tab indentation, trailing whitespace, extra blank line at the end of the file): - -```text -→private int m_count;··¶ -}¶ -¶ -``` - -### F-02 One top-level type per file, named after the type - -- The file name is the PascalCase name of its primary type: `EventDispatcher.cs` contains `EventDispatcher`. -- Generic arity is not part of the file name: `Pool` lives in `Pool.cs`. -- Additional files of a `partial` type are named `Type.Part.cs`. -- A small, tightly coupled contract (an enum, delegate or parameter record used only by the primary type) may share the file. The primary type comes first. - -```text -Inno.Core.Events/ - EventDispatcher.cs class EventDispatcher - EventDispatcher.Observation.cs partial class EventDispatcher - IEventSink.cs interface IEventSink -``` - -### F-03 File structure - -A file contains, in this order: the using directives, one blank line, the file-scoped namespace, one blank line, the types. There is no file header comment, no license banner and no leading blank line. - -```csharp -using System; -using System.Collections.Generic; - -namespace Inno.Core.Events; - -/// -/// Dispatches events to registered sinks. -/// -public sealed class EventDispatcher -{ - private readonly List m_sinks = []; -} -``` - -Avoid (no blank line after the namespace): - -```csharp -namespace Inno.Core.Events; -public sealed class EventDispatcher -{ - private readonly List m_sinks = []; -} -``` - -### F-04 Line width - -- Aim for 120 columns or fewer. 140 columns is the hard limit. -- Only an unsplittable string literal (a path, a URL, one diagnostic sentence) may exceed the hard limit. -- Do not split a name, a modifier list or a short expression body merely to shorten a line. - -```csharp -// 107 columns: stays on one line. -public bool isMissing => m_source is null || !m_source.exists || m_source.generation != m_owner.generation; - -// 145 columns on one line: break it by meaning. -throw new InvalidOperationException( - $"The importer '{importer.name}' produced no result for '{path}' while generation {generation} was active." -); -``` - -Avoid (a short declaration split for no reason): - -```csharp -public bool isMissing - => m_source is null; -``` - -### F-05 Indentation and alignment of continuation lines - -Prefer alignment over a fixed indent. - -- **Operator continuation.** When an expression is broken at an operator (`&&`, `||`, `??`, `+`, `?`, `:`, `or`, `and`, …), each continuation line begins with the operator and aligns with the first operand of that expression. -- **Fallback.** When alignment would push a line past the hard limit, indent the continuation lines four spaces from the start of the statement instead. -- **Delimited lists.** The contents of a broken parameter list, argument list, initializer or collection are indented four spaces from the line that opens them. The closing delimiter, when it is on its own line, aligns with the first token of the opening line. -- **Call chains, wrapped `=>` and clauses.** A wrapped `.Member(...)` link, a wrapped expression-body `=>`, and a wrapped `where` or constructor-initializer clause are indented four spaces from the start of the statement or declaration. - -```csharp -bool changed = previous.width != current.width - || previous.height != current.height - || previous.format != current.format; - -return left.order != right.order - || left.layer != right.layer; - -string name = entry.displayName - ?? entry.path.GetFileName() - ?? string.Empty; - -List names = m_entries - .Where(static entry => !entry.isMissing) - .Select(static entry => entry.displayName) - .ToList(); -``` - -Avoid (operator continuation indented by a fixed amount instead of aligned): - -```csharp -bool changed = previous.width != current.width - || previous.height != current.height - || previous.format != current.format; -``` - - - - -## 2. Namespaces and using directives - -### N-01 File-scoped namespaces - -Use `namespace X;`. A file declares exactly one namespace. - -```csharp -namespace Inno.Core.Events; - -public sealed class EventDispatcher -{ - private int m_generation; -} -``` - -Avoid: - -```csharp -namespace Inno.Core.Events -{ - public sealed class EventDispatcher - { - private int m_generation; - } -} -``` - -### N-02 The namespace is the project name - -The namespace starts with `Inno`, uses PascalCase segments and equals the assembly name of the owning project. Directories inside a project organize files; they do not add namespace segments. - -```csharp -// File: src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs -namespace Inno.Assets.Pipeline; -``` - -Avoid: - -```csharp -// File: src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs -namespace Inno.Assets.Pipeline.Importing; -``` - -The one registered exception is `Inno.Editor.ImGui/Widgets`, which uses `Inno.Editor.ImGui.ImGuiWidget`. - -### N-03 Placement and kinds of using directives - -- All using directives are at the top of the file, outside the namespace. -- `global using`, implicit usings and MSBuild `Using` items are prohibited. Handwritten code never uses `global::`. -- `using static` is reserved for pure function containers such as math helpers. - -```csharp -using System; -using Inno.Core.Events; - -namespace Inno.Rendering; -``` - -Avoid: - -```csharp -global using System; - -namespace Inno.Rendering; - -using Inno.Core.Events; - -public sealed class Renderer -{ - private readonly global::Inno.Core.Events.EventDispatcher m_dispatcher = new(); -} -``` - -### N-04 Order of using directives - -Using directives form up to three groups, in this order, separated by exactly one blank line: - -1. Namespace usings. -2. `using static` directives. -3. Alias usings. - -Inside the namespace group the order is: - -1. `System` and `System.*`. -2. Everything else that is not `Inno` (third-party and framework packages). -3. `Inno` and `Inno.*`. - -Each tier is sorted alphabetically (ordinal). There are no blank lines inside a group. Static usings follow the same three tiers; aliases are sorted by alias name. - -```csharp -using System; -using System.Collections.Generic; -using System.Threading; -using Microsoft.CodeAnalysis; -using Xunit; -using Inno.Core.Events; -using Inno.Core.Identity; - -using static System.MathF; - -using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; -using NativeWindow = Inno.Adapter.Platform.Sdl3.Sdl3Window; -``` - -Avoid (`Inno` before third-party namespaces, a blank line inside the namespace group, an alias among the namespace usings, no blank line between kinds): - -```csharp -using Inno.Core.Events; -using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; -using Xunit; - -using System; -using System.Collections.Generic; -using static System.MathF; -``` - -### N-05 No fully qualified names at the point of use - -Import a type with a using directive and refer to it by its short name. When two names collide, declare one alias at the top of the file and use only that alias throughout the file. - -```csharp -using System.IO; - -using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; - -namespace Inno.Assets.Pipeline.Tests; - -public sealed class AssetLoaderTests -{ - private static AssetEvent Deleted(string path) => new(path, WatcherChangeTypes.Deleted); -} -``` - -Avoid: - -```csharp -namespace Inno.Assets.Pipeline.Tests; - -public sealed class AssetLoaderTests -{ - private static Inno.Assets.Pipeline.AssetChangedEvent Deleted(string path) - => new(path, System.IO.WatcherChangeTypes.Deleted); -} -``` - -### N-06 Alias names - -An alias is PascalCase, names the role the type plays in this file and differs from the short name of its target. One target has one alias per file. - -```csharp -using NativeWindow = Inno.Adapter.Platform.Sdl3.Sdl3Window; -``` - -Avoid (the alias repeats the target name, and a second alias names the same target): - -```csharp -using Sdl3Window = Inno.Adapter.Platform.Sdl3.Sdl3Window; -using Window = Inno.Adapter.Platform.Sdl3.Sdl3Window; -``` - - - - -## 3. Naming - -### Summary - -| Element | Rule | Example | -| --- | --- | --- | -| Namespace segment | PascalCase | `Inno.Core.Events` | -| Class, struct, record, enum, delegate | PascalCase | `RenderGraph`, `AssetHandle` | -| Interface | `I` + PascalCase | `IEventSink` | -| Type parameter | `T` or `T` + PascalCase | `T`, `TSource` | -| Method, local function | PascalCase | `TryResolve`, `CreateBuffer` | -| Property, indexer | camelCase | `transform`, `isMissing` | -| Event | camelCase | `redrawRequested` | -| Constant (`const`, including local constants) | `C_` + UPPER_SNAKE | `C_MAX_COUNT` | -| `static readonly` field (any accessibility) | UPPER_SNAKE | `DEFAULT_OPTIONS`, `RED` | -| Private static mutable field | `s_` + camelCase | `s_nextID` | -| Private or protected instance field | `m_` + camelCase | `m_generation` | -| Internal or public instance field | camelCase | `latestSucceeded` | -| Enum member | PascalCase | `Borrowed` | -| Parameter, local variable, tuple element | camelCase | `outputDirectory` | -| Two-letter acronym | Upper case in PascalCase positions | `AssetID`, `IOStatus`, `UIScale` | -| Test class and test method | `XxxTests`, PascalCase sentence | `DispatchAfterDisposeThrows` | - -### NM-01 Type names - -A type name is a PascalCase noun or noun phrase. The suffix follows the role: `Attribute`, `Exception`, `EventArgs`, `Tests`, and `Extensions` for a class that holds extension methods. An abstract class has no `Base` or `Abstract` affix. - -```csharp -public sealed class InspectorMessageAttribute : Attribute; - -public static class PathExtensions -{ - public static string Normalize(this string path) => path.Replace('\\', '/'); -} - -public abstract class EditorDrop; -``` - -Avoid: - -```csharp -public sealed class InspectorMessage : Attribute; - -public static class PathHelpers -{ - public static string Normalize(this string path) => path.Replace('\\', '/'); -} - -public abstract class EditorDropBase; -``` - -### NM-02 Interfaces and type parameters - -An interface name starts with `I`. No other type starts with `I` followed by an upper-case letter. Use `T` when there is a single, obvious type parameter; otherwise use `T` plus a description. - -```csharp -public interface IAssetImporter - where TAsset : class -{ - TAsset Import(string path); -} - -public sealed class Pool; -``` - -Avoid: - -```csharp -public interface AssetImporter - where Asset : class -{ - Asset Import(string path); -} -``` - -### NM-03 Method names - -A method name is PascalCase and starts with a verb. These prefixes have fixed meanings: - -- `Try*` returns `bool`, does not throw on failure and returns its result through an `out` parameter. -- `Is*`, `Has*` and `Can*` return `bool` and have no side effects. -- `Create*` builds a new object that the caller owns. -- `Get*` reads existing state without side effects. -- `*Async` returns `Task` or `ValueTask` (NM-04). - -```csharp -public bool TryResolve( - AssetID id, - out AssetHandle handle -) => m_handles.TryGetValue(id, out handle); -``` - -Avoid (`Try*` that does not return `bool`): - -```csharp -public AssetHandle? TryResolve(AssetID id) => m_handles.GetValueOrDefault(id); -``` - -### NM-04 Asynchronous methods end with `Async` - -A method that returns `Task`, `Task`, `ValueTask` or `ValueTask` ends with `Async`. Overrides and interface implementations follow their contract. xUnit test methods do not take the suffix. - -```csharp -public async Task CompileAsync( - ShaderSource source, - CancellationToken cancellationToken -) { - ShaderProgram program = await m_frontend.ParseAsync(source, cancellationToken).ConfigureAwait(false); - return await m_backend.EmitAsync(program, cancellationToken).ConfigureAwait(false); -} -``` - -Avoid: - -```csharp -public async Task Compile( - ShaderSource source, - CancellationToken cancellationToken -) { - ShaderProgram program = await m_frontend.ParseAsync(source, cancellationToken).ConfigureAwait(false); - return await m_backend.EmitAsync(program, cancellationToken).ConfigureAwait(false); -} -``` - -### NM-05 Properties and indexers are camelCase - -Every property is camelCase, whatever its accessibility. A `bool` property starts with `is`, `has` or `can`, or is a past participle that states a condition, such as `disposed`. - -```csharp -public Transform transform { get; } -public bool isMissing => m_source is null; -public int count { get; private set; } -``` - -Avoid: - -```csharp -public Transform Transform { get; } -public bool Missing => m_source is null; -public int Count { get; private set; } -``` - -### NM-06 Instance fields - -- A private or protected instance field is `m_` + camelCase, whether or not it is `readonly`. -- An internal or public instance field is camelCase without a prefix. Such fields appear only in frame-local workspaces, interop structs and math types. -- One declaration declares one field. - -```csharp -public sealed class RenderQueue -{ - private readonly List m_items = []; - private int m_generation; -} - -internal struct GlyphVertex -{ - public Vector2 position; - public Vector2 uv; -} -``` - -Avoid: - -```csharp -public sealed class RenderQueue -{ - private readonly List _items = []; - private int generation, frameIndex; -} -``` - -### NM-07 Constants - -Every `const` is `C_` + UPPER_SNAKE: private, internal and public constants, and constants local to a method. - -```csharp -public sealed class SceneFile -{ - public const string C_DEFAULT_EXTENSION = ".iscene"; - private const int C_MAX_COUNT = 64; - - public void Flush() - { - const int C_BATCH_SIZE = 256; - Write(C_BATCH_SIZE); - } -} -``` - -Avoid: - -```csharp -public sealed class SceneFile -{ - public const string DefaultExtension = ".iscene"; - private const int MAX_COUNT = 64; - - public void Flush() - { - const int batchSize = 256; - Write(batchSize); - } -} -``` - -### NM-08 `static readonly` fields - -Every `static readonly` field is UPPER_SNAKE without any prefix, whatever its accessibility. The `C_` prefix is reserved for `const`. - -```csharp -public readonly struct Color -{ - public static readonly Color RED = FromBytes(255, 0, 0); - private static readonly JsonSerializerOptions SERIALIZER_OPTIONS = new(JsonSerializerDefaults.Web); -} -``` - -Avoid: - -```csharp -public readonly struct Color -{ - public static readonly Color Red = FromBytes(255, 0, 0); - private static readonly JsonSerializerOptions S_SERIALIZER_OPTIONS = new(); - private static readonly JsonSerializerOptions s_serializerOptions = new(); - private static readonly JsonSerializerOptions C_SERIALIZER_OPTIONS = new(); -} -``` - -### NM-09 Static mutable fields - -A private static mutable field is `s_` + camelCase. Product code does not declare non-private static mutable fields; shared process state belongs to an explicit host. - -```csharp -public sealed class HandleAllocator -{ - private static int s_nextID; -} -``` - -Avoid: - -```csharp -public sealed class HandleAllocator -{ - private static int m_nextID; - public static int nextID; -} -``` - -### NM-10 Events - -An event is camelCase, like a property. Name it with a past participle or as `xxxChanged` / `xxxRequested`. Its delegate type is a nullable `Action` or `Action<...>`. - -```csharp -public event Action? redrawRequested; -public event Action? assetReloaded; -``` - -Avoid: - -```csharp -public event Action? RedrawRequested; -public event EventHandler? OnRedraw; -``` - -### NM-11 Enums - -- A single-value enum has a singular name. A `[Flags]` enum has a plural name or ends with `Flags`. -- Members are PascalCase and never start with an underscore. -- `[Flags]` values are written as `1 << n`, with `None = 0`. Combined values are expressed with member names. -- One member per line, no trailing comma, no blank lines between members. - -```csharp -public enum EditorPlayModeState -{ - Editing, - Compiling, - Playing -} - -[Flags] -public enum EditorViewportNavigationCapabilities -{ - None = 0, - Orbit = 1 << 0, - Pan = 1 << 1, - Zoom = 1 << 2, - All = Orbit | Pan | Zoom -} -``` - -Avoid: - -```csharp -[Flags] -public enum EditorViewportNavigationCapability -{ - None = 0, - Orbit = 1, - Pan = 0x2, - Zoom = 4, -} -``` - -### NM-12 Parameters, local variables and tuple elements - -Use camelCase and whole words. Do not use Hungarian prefixes. Do not give a local variable or a parameter the name of a property of the same type, except for constructor parameters (E-08). - -| Situation | Name | -| --- | --- | -| `CancellationToken` parameter | `cancellationToken` | -| Default `catch` variable | `exception` | -| Unused lambda parameter | `_` | -| Loop index | `i`, `j`, `index` | -| Coordinate or component | `x`, `y`, `z`, `w` | - -Apart from this table, do not use one- or two-character names. `id` and `io` are whole words and are allowed. - -```csharp -public async Task SaveAsync( - Stream destination, - CancellationToken cancellationToken -) { - (int width, int height) size = Measure(); - foreach (AssetEntry entry in m_entries) - { - await entry.WriteAsync(destination, size, cancellationToken).ConfigureAwait(false); - } -} -``` - -Avoid: - -```csharp -public async Task SaveAsync( - Stream dst, - CancellationToken token -) { - (int Width, int Height) sz = Measure(); - foreach (AssetEntry e in m_entries) - { - await e.WriteAsync(dst, sz, token).ConfigureAwait(false); - } -} -``` - -### NM-13 Acronyms - -- A two-letter acronym is upper case wherever a PascalCase word would start: `ID`, `IO`, `UI`. This includes `ID`: write `AssetID`, `persistentID`, `GetID`, never `AssetId`. -- An acronym of three or more letters is written as an ordinary word: `Json`, `Http`, `Ktx`, `Sdl`. -- When an acronym starts a camelCase identifier, the whole acronym is lower case: `id`, `ioStatus`, `uiScale`. -- In UPPER_SNAKE names every word is upper case: `C_MAX_ID`. - -```csharp -public sealed class JsonAssetWriter -{ - public AssetID persistentID { get; } - public IOStatus ioStatus { get; } - public float uiScale { get; set; } - - public AssetID GetID(string id) => m_ids[id]; -} -``` - -Avoid: - -```csharp -public sealed class JSONAssetWriter -{ - public AssetId persistentId { get; } - public IoStatus IOStatus { get; } - public float UIScale { get; set; } - - public AssetId GetId(string ID) => m_ids[ID]; -} -``` - - - - -## 4. Type declarations - -### T-01 Write every access modifier - -Every type and every member states its accessibility, including each file of a `partial` type. Interface members do not write `public`. - -```csharp -internal sealed partial class AssetLoader -{ - private int m_generation; -} - -public interface IEventSink -{ - void Publish(EventRecord record); -} -``` - -Avoid: - -```csharp -sealed partial class AssetLoader -{ - int m_generation; -} -``` - -### T-02 Modifier order - -Accessibility, then `static`, `extern`, `new`, then `virtual` / `abstract` / `sealed` / `override`, then `readonly`, `unsafe`, `required`, `volatile`, `async`, `partial`. - -```csharp -public static readonly Color RED = FromBytes(255, 0, 0); - -private static async Task RunAsync() -{ - await Task.Yield(); - Publish(); -} - -public sealed override string ToString() => name; - -public override readonly int GetHashCode() => m_value; - -internal static unsafe partial class NativeMethods; -``` - -Avoid: - -```csharp -public readonly override int GetHashCode() => m_value; - -static private int s_count; -``` - -### T-03 Classes are sealed by default - -Every class is `static`, `abstract` or `sealed`. Leave a class open only when it is a designed extension point, and document the derivation contract in its XML documentation. Nested private classes are sealed too. - -```csharp -public sealed class EventDispatcher; - -internal static class PathUtility -{ - internal static string Normalize(string path) => path.Replace('\\', '/'); -} - -public abstract class EditorDrop; -``` - -Avoid: - -```csharp -public class EventDispatcher; -``` - -### T-04 Records - -- A reference-type data contract is a `sealed record` with positional parameters, ending in `;`. -- A small value type is a `readonly record struct`. -- Positional parameters are properties, so they are camelCase. - -```csharp -public sealed record AssetChangedEvent( - string path, - WatcherChangeTypes change -); - -public readonly record struct AssetID(Guid value); -``` - -Avoid: - -```csharp -public record AssetChangedEvent(string Path, WatcherChangeTypes Change); - -public record struct AssetID(Guid value); -``` - -### T-05 Structs - -A struct is `readonly` by default. Use a mutable struct only for interop layouts and math types that are assigned field by field; its fields are public and camelCase. - -```csharp -public readonly struct FrameRange -{ - public int start { get; } - public int count { get; } -} - -[StructLayout(LayoutKind.Sequential)] -internal struct GlyphVertex -{ - public Vector2 position; - public Vector2 uv; -} -``` - -Avoid (a mutable struct that is not an interop or math type): - -```csharp -public struct FrameRange -{ - public int start { get; set; } - public int count { get; set; } -} -``` - -### T-06 Base lists and generic constraints on types - -- The base list stays on the line of the type name. -- Each `where` clause of a type is on its own line, indented four spaces. The opening brace stays on its own line. - -```csharp -public abstract class EditorDrop : EditorDrop - where TSource : IdentityObject - where TTarget : class -{ - public abstract bool Accepts(TSource source); -} -``` - -Avoid: - -```csharp -public abstract class EditorDrop - : EditorDrop where TSource : IdentityObject where TTarget : class -{ - public abstract bool Accepts(TSource source); -} -``` - -### T-07 Primary constructors - -- A record always uses a primary constructor. -- A class or struct may use a primary constructor to receive its dependencies. When it does, it uses the parameters directly and does not copy them into `m_` fields. -- Use an ordinary constructor with `m_` fields when arguments need validation or the fields must be `readonly`. -- Primary constructor parameters follow P-01. A base list follows the closing parenthesis as `) : Base`, with the opening brace on its own line. Without a base list the type body starts with `) {`. - -```csharp -internal sealed class TogglePlayModeAction(EditorPlayMode playMode) : EditorAction -{ - protected override bool CanExecute() => playMode.state != EditorPlayModeState.Compiling; -} - -internal sealed class SceneReloadChange( - RuntimeSession runtimeSession, - ISceneReloadStateTransfer migration -) : IGenerationChange -{ - public void Apply() => migration.Transfer(runtimeSession); -} - -internal sealed class FrameScope( - RenderGraph graph, - int frameIndex -) { - public bool isFirst => frameIndex == 0; - - public void Begin() => graph.BeginFrame(frameIndex); -} -``` - -Avoid (base list on a separate line, parameters copied into fields): - -```csharp -internal sealed class SceneReloadChange( - RuntimeSession runtimeSession, - ISceneReloadStateTransfer migration -) - : IGenerationChange -{ - private readonly RuntimeSession m_runtimeSession = runtimeSession; - private readonly ISceneReloadStateTransfer m_migration = migration; -} -``` - -### T-08 Nested types - -A nested type is placed at the end of its containing type. Nest a type only when the containing type is its only user. - -```csharp -public sealed class AssetCache -{ - private readonly Dictionary m_entries = []; - - public int count => m_entries.Count; - - private sealed class Entry - { - public AssetHandle handle { get; init; } - public int generation { get; set; } - } -} -``` - -Avoid (the nested type comes first): - -```csharp -public sealed class AssetCache -{ - private sealed class Entry - { - public AssetHandle handle { get; init; } - public int generation { get; set; } - } - - private readonly Dictionary m_entries = []; -} -``` - - - - -## 5. Member declarations - -### M-01 Property forms - -- An auto-property is written on one line: `{ get; }`, `{ get; set; }`, `{ get; init; }`, `{ get; private set; }`. -- A read-only computed property uses an expression body. -- A property whose accessors contain logic is expanded: the braces are on their own lines, an accessor with a single expression uses `=>`, an accessor with statements uses a block. - -```csharp -public string name { get; } -public int count { get; private set; } -public bool isEmpty => m_items.Count == 0; - -public float scale -{ - get => m_scale; - set - { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); - m_scale = value; - } -} -``` - -Avoid: - -```csharp -public bool isEmpty { get { return m_items.Count == 0; } } -public float scale { get => m_scale; set => m_scale = value; } -``` - -### M-02 Expression-bodied members - -- A method, property, indexer or operator whose body is one expression (one `return`, one call or one assignment) uses an expression body. -- A body with control flow, several statements or `try` uses a block. -- A constructor always uses a block body. - -```csharp -public override string ToString() => $"{name} ({count})"; - -public static bool operator ==( - Color left, - Color right -) => left.Equals(right); - -public RenderQueue(int capacity) -{ - m_items = new List(capacity); -} -``` - -Avoid: - -```csharp -public override string ToString() -{ - return $"{name} ({count})"; -} - -public RenderQueue(int capacity) => m_items = new List(capacity); -``` - -### M-03 Placement of `=>` in expression-bodied members - -1. When the whole member fits on one line, `=> expression` stays on the declaration line. -2. After a multi-line parameter list, the body starts on the line of the closing parenthesis: `) => expression`. When the expression is a call, an object creation or a collection that does not fit, break inside it (A-02). -3. When the signature is on one line and the body does not fit after it, move `=>` to the next line, indented four spaces. -4. After a wrapped `=>`, a brace-delimited expression (a `switch` expression, an object initializer or a `with` expression) puts its braces on their own lines at the column of the declaration, with its contents indented four spaces from the declaration. -5. After a wrapped `=>`, a call or object creation that must break follows A-02 relative to the `=>` line, and operator continuation lines align with the first operand (F-05). -6. `=>` never ends a line with the expression on the next line, and never stands alone on a line. - -```csharp -public bool isMissing => m_source is null; - -public static Color FromBytes( - byte r, - byte g, - byte b -) => new(r / 255f, g / 255f, b / 255f); - -public static Color Lerp( - Color from, - Color to, - float amount -) => new( - from.r + (to.r - from.r) * amount, - from.g + (to.g - from.g) * amount, - from.b + (to.b - from.b) * amount -); - -protected override EditorActionState Query(EditorActionContext context) - => playMode.state switch -{ - EditorPlayModeState.Editing => new EditorActionState(true, true), - EditorPlayModeState.Playing => new EditorActionState(true, false), - _ => EditorActionState.DISABLED -}; - -internal bool IsActiveFor(object? target) - => m_isActive - && m_activeTarget is not null - && m_activeTarget.Matches(m_activeInteractions, target); - -protected override EditorActionState Describe(EditorActionContext context) - => new EditorActionState( - isVisible: context.selection.count > 0, - isEnabled: playMode.state == EditorPlayModeState.Editing, - displayName: "Duplicate Selection" - ); -``` - -Avoid (`=>` left at the end of the line, braces indented under the wrapped `=>`, closing parenthesis left on the last argument): - -```csharp -protected override EditorActionState Query(EditorActionContext context) => - playMode.state switch - { - EditorPlayModeState.Editing => new EditorActionState(true, true), - _ => EditorActionState.DISABLED - }; - -public static Color Lerp( - Color from, - Color to, - float amount -) - => new( - from.r + (to.r - from.r) * amount, - from.g + (to.g - from.g) * amount, - from.b + (to.b - from.b) * amount); -``` - -### M-04 Field and property initializers - -- A field or property initializer uses a target-typed expression so the type is written once: `= new(...)` or `= []`. -- One declaration declares one field or one local variable. - -```csharp -private readonly Dictionary m_commands = new(StringComparer.Ordinal); -private readonly List m_items = []; - -public IReadOnlyList tags { get; init; } = []; -``` - -Avoid: - -```csharp -private readonly Dictionary m_commands = new Dictionary(StringComparer.Ordinal); -private readonly List m_items = new List(); -``` - -### M-05 Attributes - -- Each attribute is on its own line above the declaration. One pair of brackets holds one attribute. -- Omit the `Attribute` suffix. Omit empty parentheses. -- An attribute on a parameter stays on the line of the parameter. -- Attribute arguments break like any other argument list (A-02). - -```csharp -[Fact] -[Trait("Category", "Lifecycle")] -public void DisposeIsIdempotent() -{ - m_queue.Dispose(); - m_queue.Dispose(); -} - -[SerializableProperty] -public float speed { get; set; } - -public bool TryRead( - string key, - [NotNullWhen(true)] out string? value -) => m_values.TryGetValue(key, out value); -``` - -Avoid: - -```csharp -[Fact, Trait("Category", "Lifecycle")] -public void DisposeIsIdempotent() -{ - m_queue.Dispose(); - m_queue.Dispose(); -} - -[SerializableProperty()] public float speed { get; set; } -``` - - - - -## 6. Member order - -### O-01 Group order - -Members of a type appear in these groups, in this order, with one blank line between groups: - -1. Constants (`const`). -2. Static fields: `static readonly` first, then static mutable. -3. Instance fields: `readonly` first, then mutable. -4. Constructors. -5. Public members. -6. Protected and internal members. -7. Private members. -8. Nested types. - -Inside groups 5, 6 and 7 the order is: properties, events, instance methods, static methods. An explicit interface implementation follows the public members of the interface it implements. - -```csharp -public sealed class RenderQueue : IDisposable -{ - private const int C_INITIAL_CAPACITY = 64; - - private static readonly RenderItemComparer COMPARER = new(); - - private readonly List m_items; - private bool m_disposed; - - public RenderQueue() - { - m_items = new List(C_INITIAL_CAPACITY); - } - - public int count => m_items.Count; - - public event Action? flushed; - - public void Enqueue(RenderItem item) - { - ObjectDisposedException.ThrowIf(m_disposed, this); - m_items.Add(item); - } - - public void Dispose() - { - m_items.Clear(); - m_disposed = true; - } - - internal void Sort() => m_items.Sort(COMPARER); - - private void NotifyFlushed() => flushed?.Invoke(); - - private sealed class RenderItemComparer : IComparer - { - public int Compare( - RenderItem left, - RenderItem right - ) => left.order.CompareTo(right.order); - } -} -``` - -Avoid (a private method before the public members, fields after the constructor): - -```csharp -public sealed class RenderQueue -{ - public RenderQueue() - { - m_items = new List(C_INITIAL_CAPACITY); - } - - private void NotifyFlushed() => flushed?.Invoke(); - - private readonly List m_items; - - public int count => m_items.Count; - - private const int C_INITIAL_CAPACITY = 64; -} -``` - -### O-02 Keep related members together - -Members of the same accessibility and kind are contiguous. Overloads are adjacent and ordered from fewest to most parameters. - -```csharp -public void Draw(Mesh mesh) => Draw(mesh, m_defaultMaterial); - -public void Draw( - Mesh mesh, - Material material -) { - Submit(new RenderItem(mesh, material)); - m_drawn++; -} - -public void Clear() => m_items.Clear(); - -private void Submit(RenderItem item) => m_items.Add(item); -``` - -Avoid (overloads separated, a private method between public methods): - -```csharp -public void Draw(Mesh mesh) => Draw(mesh, m_defaultMaterial); - -private void Submit(RenderItem item) => m_items.Add(item); - -public void Clear() => m_items.Clear(); - -public void Draw( - Mesh mesh, - Material material -) { - Submit(new RenderItem(mesh, material)); - m_drawn++; -} -``` - - - - -## 7. Braces and blocks - -### B-01 Braces are on their own lines - -The opening brace of a type, a method body, an accessor, a control statement, a lambda block, an object or collection initializer and a `switch` expression is on its own line, aligned with the start of the construct. The closing brace is on its own line, aligned with the opening brace. - -The only places where an opening brace shares a line with other code are: - -- `) {` after a multi-line parameter list or a multi-line statement header (B-02). -- A single-line construct: an auto-property, a short initializer, a property pattern, a compact guard (B-05). -- An empty body `{}` (B-07). - -```csharp -public void Flush() -{ - foreach (RenderItem item in m_items) - { - Draw(item); - m_drawn++; - } - - try - { - Present(); - } - catch (DeviceLostException exception) - { - m_log.Error(exception.Message); - throw; - } - finally - { - m_items.Clear(); - } -} -``` - -Avoid: - -```csharp -public void Flush() { - foreach (RenderItem item in m_items) { - Draw(item); - } - - try { Present(); } - catch (DeviceLostException) { throw; } - finally { m_items.Clear(); } -} -``` - -### B-02 `) {` after a multi-line parameter list or statement header - -When a parameter list is expanded over several lines (P-01) and the body follows it directly, the opening brace shares the line of the closing parenthesis: `) {`. The closing brace aligns with the start of the declaration. This applies to methods, constructors, local functions, operators and primary constructors without a base list. The same form closes a control statement whose header spans several lines (W-05). - -```csharp -internal void Register( - string commandID, - Action command -) { - ArgumentException.ThrowIfNullOrWhiteSpace(commandID); - ArgumentNullException.ThrowIfNull(command); - m_commands.Add(commandID, command); -} -``` - -Avoid (brace on its own line after a multi-line parameter list, several parameters on one line): - -```csharp -internal void Register( - string commandID, - Action command -) -{ - m_commands.Add(commandID, command); - m_dirty = true; -} - -internal void Unregister(string commandID, Action command) -{ - m_commands.Remove(commandID); - m_dirty = true; -} -``` - -### B-03 Clauses between `)` and the body - -A constructor initializer (`: base(...)`, `: this(...)`) or a `where` clause sits between the parameter list and the body. - -- After a multi-line parameter list, the clause follows the closing parenthesis on the same line: `) : this(...)` or `) where T : class`. The opening brace is then on its own line. -- After a single-line signature, the clause is on the next line, indented four spaces. The opening brace is on its own line. -- Additional `where` clauses each take their own line, aligned with the first `where`. - -```csharp -public InspectorMessageAttribute( - string text, - InspectorMessageType messageType -) : this(text, messageType, string.Empty) -{ - this.isExpanded = true; -} - -public InspectorMessageAttribute(string text) - : this(text, InspectorMessageType.Info) -{ - this.isExpanded = false; -} - -public T Resolve( - string id, - bool required -) where T : class -{ - object resolved = ResolveCore(typeof(T), id, required); - return (T)resolved; -} - -public TTarget Convert( - TSource source, - bool required -) where TSource : IdentityObject - where TTarget : class -{ - object converted = ConvertCore(source, typeof(TTarget), required); - return (TTarget)converted; -} - -public T Find(string id) - where T : class -{ - object found = FindCore(typeof(T), id); - return (T)found; -} -``` - -Avoid (clause on its own line after a multi-line parameter list, clause on the signature line of a single-line signature, `) {` after a clause): - -```csharp -public InspectorMessageAttribute( - string text, - InspectorMessageType messageType -) - : this(text, messageType, string.Empty) -{ - this.isExpanded = true; -} - -public InspectorMessageAttribute(string text) : this(text, InspectorMessageType.Info) -{ - this.isExpanded = false; -} - -public T Resolve( - string id, - bool required -) where T : class { - object resolved = ResolveCore(typeof(T), id, required); - return (T)resolved; -} -``` - -### B-04 Lambda bodies - -- **Expression body that fits:** `x => expression` on one line. -- **Block body:** `=>` ends the line; the braces are on their own lines, aligned with the start of the statement that contains the lambda. The closing brace is followed directly by `)`, `,` or `;`. This holds when the lambda has a multi-line parameter list too: `) =>`, then the brace on the next line. -- **Expression body that is a call or object creation and does not fit:** the call starts on the `=>` line and breaks inside its parentheses (A-02). -- **Any other expression body that does not fit:** wrap it in parentheses. `(` follows `=>`, the expression is indented four spaces, and `)` is on its own line. - -```csharp -m_dispatcher.Subscribe(entry => -{ - m_pending.Add(entry); - m_dirty = true; -}); - -entries.Sort(( - left, - right -) => -{ - int byName = string.CompareOrdinal(left.name, right.name); - return byName != 0 ? byName : left.order.CompareTo(right.order); -}); - -IEnumerable blended = pairs.Select(pair => new Color( - pair.from.r + (pair.to.r - pair.from.r) * amount, - pair.from.g + (pair.to.g - pair.from.g) * amount, - pair.from.b + (pair.to.b - pair.from.b) * amount -)); - -Func isStale = entry => ( - entry.lastWriteTimeUtc < threshold && !entry.isPinned -); -``` - -Avoid (brace on the `=>` line, block squeezed onto one line, expression body moved to the next line without parentheses): - -```csharp -m_dispatcher.Subscribe(entry => { - m_pending.Add(entry); - m_dirty = true; -}); - -m_dispatcher.Subscribe(entry => { m_pending.Add(entry); m_dirty = true; }); - -Func isStale = entry => - entry.lastWriteTimeUtc < threshold && !entry.isPinned; -``` - -### B-05 Control statement bodies always use braces - -1. The body of `if`, `else`, `for`, `foreach`, `while`, `do`, `using`, `lock` and `fixed` is always enclosed in braces, each brace on its own line. -2. One compact form is permitted where it reads better: an `if` without `else` whose body is a single short statement may be written entirely on one line, `if (condition) statement;`. Use it for guard clauses and keep a run of adjacent guards in the same form. -3. A body on the next line without braces is never allowed. -4. Stacked `using` or `fixed` headers that share one braced body are the only headers that may follow each other without braces in between. - -```csharp -if (m_disposed) -{ - return; -} - -while (reader.Read()) -{ - Process(reader.current); -} - -foreach (RenderItem item in m_items) -{ - if (item is null) continue; - if (!item.isVisible) continue; - - Draw(item); -} - -fixed (byte* source = input) -fixed (byte* target = output) -{ - Copy(source, target, length); -} -``` - -Avoid: - -```csharp -if (m_disposed) - return; - -foreach (RenderItem item in m_items) - Draw(item); - -foreach (AssetEntry entry in m_entries) - if (entry.isMissing) - missing.Add(entry); - -foreach (RenderItem item in m_items) Draw(item); -``` - -### B-06 `if` / `else` chains - -Every branch of an `if … else if … else` chain uses braces. The compact one-line form (B-05) is not used when the `if` has an `else`. - -```csharp -if (state == EditorPlayModeState.Editing) -{ - EnterPlayMode(); -} -else if (state == EditorPlayModeState.Playing) -{ - ExitPlayMode(); -} -else -{ - m_log.Warning("Play mode is changing."); -} -``` - -Avoid: - -```csharp -if (state == EditorPlayModeState.Editing) EnterPlayMode(); -else ExitPlayMode(); - -if (state == EditorPlayModeState.Editing) - EnterPlayMode(); -else -{ - m_log.Warning("Play mode is already active."); - ExitPlayMode(); -} -``` - -### B-07 Empty bodies - -- An empty type ends with a semicolon and has no braces. -- An empty method, constructor, accessor, local function or lambda body is `{}`, with no space inside, on the line where the header ends. -- An empty `catch` block is not empty: it contains a comment that explains why the exception is ignored (X-04). -- A property pattern that matches any non-null value is written `{ }`. - -```csharp -public sealed class EmptyPayload; - -public interface IMarker; - -protected virtual void OnActivated() {} - -public NullSink( - string name, - int capacity -) {} - -public NamedSink(string name) - : base(name) {} -``` - -Inside a method: - -```csharp -Action noop = () => {}; - -if (value is { } resolved) -{ - Use(resolved); -} -``` - -Avoid: - -```csharp -public sealed class EmptyPayload -{ -} - -public sealed class OtherPayload { } - -protected virtual void OnActivated() -{ -} - -protected virtual void OnDeactivated() { } -``` - -### B-08 `else`, `catch`, `finally` and `while` - -`else`, `catch` and `finally` start a new line after the closing brace. The `while` of a `do … while` loop starts a new line too. - -```csharp -do -{ - read = stream.Read(buffer); - total += read; -} -while (read > 0); -``` - -Avoid: - -```csharp -do -{ - read = stream.Read(buffer); - total += read; -} while (read > 0); -``` - -### B-09 One statement per line - -A line holds one statement. The statement after a `case` label starts on the next line. Nothing follows an opening brace on its line. The compact guard of B-05 is the only construct in which a statement shares the line of its header. - -```csharp -switch (key) -{ - case KeyCode.Left: - cursor--; - break; - case KeyCode.Right: - cursor++; - break; -} -``` - -Avoid: - -```csharp -switch (key) -{ - case KeyCode.Left: cursor--; break; - case KeyCode.Right: cursor++; break; -} - -x = 0; y = 0; -``` - - - - -## 8. Parameter and argument lists - -### P-01 Parameter lists: one line for zero or one parameter, fully expanded for two or more - -A declaration with two or more parameters breaks after the opening parenthesis, puts each parameter on its own line indented four spaces, and puts the closing parenthesis on its own line aligned with the start of the declaration. A declaration with zero or one parameter stays on one line. - -This applies to methods, constructors, local functions, delegates, operators, primary constructors and lambdas. - -```csharp -public void Clear() => m_commands.Clear(); - -public void Remove(string commandID) => m_commands.Remove(commandID); - -public void Register( - string commandID, - Action command -) { - m_commands.Add(commandID, command); - m_dirty = true; -} - -public delegate void AssetCallback( - AssetID id, - AssetHandle handle -); -``` - -Local functions and lambdas follow the same rule: - -```csharp -void Visit( - Node node, - int depth -) { - m_visited.Add(node); - m_depths[node] = depth; -} - -bool duplicate = updated.Where(( - _, - candidateIndex -) => candidateIndex != index).Any(); -``` - -Avoid: - -```csharp -public void Register(string commandID, Action command) -{ - m_commands.Add(commandID, command); - m_dirty = true; -} - -public void Register(string commandID, - Action command) -{ - m_commands.Add(commandID, command); - m_dirty = true; -} - -public void Register( - string commandID, - Action command) -{ - m_commands.Add(commandID, command); - m_dirty = true; -} - -bool duplicate = updated.Where((_, candidateIndex) => candidateIndex != index).Any(); -``` - -### P-02 What follows the closing parenthesis of a multi-line parameter list - -| Followed by | Form | -| --- | --- | -| Block body | `) {` | -| Empty body | `) {}` | -| Expression body | `) => expression;` — when the expression must break, it breaks inside its own delimiters: `) => new(` … `);` | -| No body (interface, abstract, delegate, record) | `);` | -| Constructor initializer | `) : base(...)` or `) : this(...)`, opening brace on its own line | -| `where` clause | `) where T : class`, opening brace on its own line | -| Base list of a primary constructor | `) : Base`, opening brace on its own line | -| Lambda body | `) =>`, then the expression, or the opening brace on its own line | - -```csharp -public interface IAssetStore -{ - Task LoadAsync( - AssetID id, - CancellationToken cancellationToken - ); -} - -public sealed class NullAssetStore : IAssetStore -{ - public NullAssetStore( - string name, - int capacity - ) {} - - public Task LoadAsync( - AssetID id, - CancellationToken cancellationToken - ) => Task.FromResult(AssetHandle.MISSING); -} -``` - -Avoid: - -```csharp -public sealed class NullAssetStore : IAssetStore -{ - public Task LoadAsync( - AssetID id, - CancellationToken cancellationToken - ) - => Task.FromResult(AssetHandle.MISSING); -} -``` - -### P-03 Parameter details - -- A default value is written `= value`, with one space on each side of `=`. -- `this`, `ref`, `out`, `in` and `params` are separated from the type by one space. -- `CancellationToken cancellationToken` is always the last parameter. - -```csharp -public Task LoadAsync( - AssetID id, - bool required = true, - CancellationToken cancellationToken = default -) { - cancellationToken.ThrowIfCancellationRequested(); - return LoadCoreAsync(id, required, cancellationToken); -} -``` - -Avoid: - -```csharp -public Task LoadAsync( - CancellationToken cancellationToken, - AssetID id, - bool required=true -) { - cancellationToken.ThrowIfCancellationRequested(); - return LoadCoreAsync(id, required, cancellationToken); -} -``` - -### A-01 Argument lists stay on one line when they fit - -The arguments of a call, an object creation or a constructor initializer stay on one line whenever the whole statement fits within the line width. - -```csharp -m_commands.Add(commandID, command); -var buffer = new VertexBuffer(device, capacity, VertexLayout.DEFAULT); -``` - -Avoid (a short call broken for no reason): - -```csharp -m_commands.Add( - commandID, - command -); -``` - -### A-02 Broken argument lists: one argument per line, closing parenthesis on its own line - -When an argument list does not fit on one line: - -- The opening parenthesis ends its line. -- Each argument is on its own line, indented four spaces from the line that contains the opening parenthesis. -- The closing parenthesis is on its own line, aligned with the start of the line that contains the opening parenthesis. Whatever follows the call — `;`, `.Next(...)`, `,` or an outer closing delimiter — follows that parenthesis. -- Nested calls apply the same rule one level deeper. - -This holds for every call, including `new`, `throw new`, `await`, `return`, attribute arguments and constructor initializers. - -```csharp -return await m_textureCompiler.CompileKtxAsync( - encoded, - texture.slot.colorSpace, - cancellationToken -).ConfigureAwait(false); - -throw new ArgumentException( - $"The viewport '{viewport.name}' does not support mode '{defaultMode}'.", - nameof(defaultMode) -); - -var result = new ShaderCompilationResult( - null, - [new ShaderDiagnostic( - "SHADER_COMPILE_EXCEPTION", - DiagnosticSeverity.Error, - message - )] -); - -string intermediate = scoped.GetNativeBuildRoot( - componentDescriptor, - configuration, - targetArchitecture -); -``` - -Avoid (closing parenthesis left on the last argument, first argument left on the opening line, several arguments packed on a line, arguments aligned with the parenthesis): - -```csharp -return await m_textureCompiler.CompileKtxAsync( - encoded, - texture.slot.colorSpace, - cancellationToken).ConfigureAwait(false); - -return await m_textureCompiler.CompileKtxAsync(encoded, - texture.slot.colorSpace, cancellationToken).ConfigureAwait(false); - -throw new ArgumentException($"The viewport '{viewport.name}' does not support mode '{defaultMode}'.", - nameof(defaultMode)); -``` - -### A-03 Hugging a single multi-line argument - -When exactly one argument spans several lines, and that argument is a lambda, an object initializer, an anonymous object or a collection expression, the arguments may all start on the line of the opening parenthesis. The multi-line argument is laid out by its own rule, and the closing parenthesis follows its closing delimiter. - -When two or more arguments span several lines, expand the list (A-02). - -```csharp -m_dispatcher.Subscribe(entry => -{ - m_pending.Add(entry); - m_dirty = true; -}); - -Task task = Task.Run(() => -{ - Compile(source); - Publish(source); -}, cancellationToken); - -loader.ApplySourceChanges([ - new AssetEvent("Text/new.txt", WatcherChangeTypes.Deleted), - new AssetEvent("Text/old.txt", WatcherChangeTypes.Deleted) -]); - -scheduler.Schedule( - () => - { - Compile(source); - Publish(source); - }, - exception => - { - m_log.Error(exception.Message); - m_failed = true; - } -); -``` - -Avoid (two multi-line arguments hugged together): - -```csharp -scheduler.Schedule(() => -{ - Compile(source); - Publish(source); -}, exception => -{ - m_log.Error(exception.Message); - m_failed = true; -}); -``` - -### A-04 Named arguments - -A named argument is written `name: value`, with no space before the colon and one space after it. Name adjacent `bool` or numeric literal arguments whose meaning is not obvious from the call. - -```csharp -var state = new EditorActionState(true, true, displayName: "Enter Play Mode"); -window.Resize(width: 1280, height: 720); -``` - -Avoid: - -```csharp -window.Resize(width : 1280, height:720); -texture.Update(true, false, 0, 4); -``` - - - - -## 9. Line breaks - -### W-01 Binary operators lead the continuation line - -When an expression breaks at `&&`, `||`, `??`, `+`, `-`, `|` or another binary operator, the operator starts the next line. Continuation lines align with the first operand (F-05). - -```csharp -bool changed = previous.width != current.width - || previous.height != current.height - || previous.format != current.format; - -string message = "The asset database could not be opened because " - + "another editor instance holds the workspace lock."; - -string name = entry.displayName - ?? entry.path.GetFileName() - ?? string.Empty; -``` - -Avoid: - -```csharp -bool changed = previous.width != current.width || - previous.height != current.height; -``` - -### W-02 Conditional expressions - -A conditional expression stays on one line when it fits. Otherwise `?` and `:` each start a line, aligned with the condition (F-05). Do not nest conditional expressions; use a `switch` expression or an `if` statement. - -```csharp -int order = byName != 0 ? byName : left.order.CompareTo(right.order); - -ShaderCompilationResult result = pending.IsCompletedSuccessfully - ? pending.Result - : new ShaderCompilationResult(null, diagnostics); -``` - -Avoid: - -```csharp -ShaderCompilationResult result = pending.IsCompletedSuccessfully ? - pending.Result : - new ShaderCompilationResult(null, diagnostics); - -string label = count == 0 ? "none" : count == 1 ? "one" : "many"; -``` - -### W-03 Call chains - -A call chain stays on one line when it fits. Otherwise the first link stays on the statement line and every following `.` (or `?.`) starts a line, indented four spaces from the start of the statement. - -```csharp -List names = m_entries - .Where(static entry => !entry.isMissing) - .Select(static entry => entry.displayName) - .OrderBy(static name => name, StringComparer.Ordinal) - .ToList(); -``` - -Avoid: - -```csharp -List names = m_entries.Where(static entry => !entry.isMissing). - Select(static entry => entry.displayName). - ToList(); -``` - -### W-04 Assignments and arrows - -- Never break a line directly before or after `=`. Keep the start of the right-hand side on the line of the `=` and break inside it: after an opening parenthesis (A-02), before an operator (W-01) or before a `.` (W-03). The only exception is the opening bracket of a multi-line collection expression, which takes its own line (I-03). -- A lambda `=>` always ends its line when the body moves down; the body then follows B-04. An expression body that is not a call is wrapped in parentheses. -- The `=>` of a `switch` expression arm stays on the line of the arm. -- The `=>` of an expression-bodied member follows M-03. - -```csharp -string intermediate = scoped.GetNativeBuildRoot( - componentDescriptor, - configuration, - targetArchitecture -); - -Func isStale = entry => ( - entry.lastWriteTimeUtc < threshold && !entry.isPinned -); -``` - -Avoid: - -```csharp -string intermediate = - scoped.GetNativeBuildRoot(componentDescriptor, configuration, targetArchitecture); - -Func isStale = entry => - entry.lastWriteTimeUtc < threshold && !entry.isPinned; -``` - -### W-05 Multi-line conditions and statement headers - -- `is` stays on the line of its left operand. `or` and `and` start their continuation lines. -- When the parenthesized header of `if`, `else if`, `while`, `for`, `foreach`, `switch`, `lock`, `using` or `fixed` spans several lines, its closing parenthesis is on its own line, aligned with the keyword, and the opening brace follows it: `) {`. This mirrors the multi-line parameter list (B-02). - -```csharp -if (token.kind is TokenKind.Comma - or TokenKind.Semicolon - or TokenKind.CloseBrace -) { - return; -} - -if (capabilities != EditorViewportNavigationCapabilities.None - && !SupportsMode(capabilities, defaultMode) -) { - throw new ArgumentException("The default mode is not supported.", nameof(defaultMode)); -} - -foreach (KeyValuePair dependency in HostDependencyManifest - .GetInnoRuntimeAssemblies(roots) - .OrderBy(static dependency => dependency.Key, StringComparer.OrdinalIgnoreCase) -) { - Enqueue(dependency.Key, dependency.Value); -} -``` - -Avoid: - -```csharp -if (token.kind is TokenKind.Comma - or TokenKind.Semicolon - or TokenKind.CloseBrace) -{ - return; -} - -if (capabilities != EditorViewportNavigationCapabilities.None - && !SupportsMode(capabilities, defaultMode)) - throw new ArgumentException("The default mode is not supported.", nameof(defaultMode)); -``` - - - - -## 10. Initializers and collections - -### I-01 Object initializers - -- A short initializer stays on one line with one space inside each brace: `new Foo { a = 1 }`. -- Otherwise the opening brace is on its own line, aligned with the start of the statement; each member is on its own line, indented four spaces; the closing brace is on its own line. -- Omit the empty `()` when an initializer is present. -- `with` expressions and anonymous objects follow the same rule. - -```csharp -var options = new JsonSerializerOptions { WriteIndented = true }; - -var request = new GameBuildRequest -{ - profile = profile, - outputDirectory = outputDirectory, - configuration = BuildConfiguration.Release -}; - -RenderSettings updated = settings with -{ - exposure = 1.5f, - toneMapping = ToneMapping.Aces -}; -``` - -Avoid: - -```csharp -var request = new GameBuildRequest() { - profile = profile, outputDirectory = outputDirectory, - configuration = BuildConfiguration.Release, -}; -``` - -### I-02 Collections use collection expressions - -- Arrays, `List`, spans and immutable collections are written as collection expressions: `[a, b]`, `[]`, `[.. source]`. -- A spread operator is followed by one space: `[.. source, extra]`. -- Use `new T(...)` when a constructor argument (a capacity, a comparer) is needed, and `new T[n]` for a fixed-size buffer. -- Do not write `new[] { ... }`, `new T[] { ... }`, `new List { ... }` or `Array.Empty()`. - -```csharp -List items = []; -string[] extensions = [".png", ".jpg", ".ktx"]; -List all = [.. builtIn, .. custom, "fallback"]; -var byName = new Dictionary(StringComparer.Ordinal); -var buffer = new byte[C_BUFFER_SIZE]; -``` - -Avoid: - -```csharp -List items = new List(); -string[] extensions = new[] { ".png", ".jpg", ".ktx" }; -List all = [..builtIn, ..custom, "fallback"]; -string[] none = Array.Empty(); -``` - -### I-03 Multi-line collection expressions - -- With two or more elements that do not fit on one line: one element per line, indented four spaces, and the closing bracket on its own line. -- As the value of a declaration or assignment, the opening bracket is on its own line, aligned with the start of the statement, like the brace of an object initializer. -- As an argument, the opening bracket follows the opening parenthesis or the preceding argument (A-03). -- A single element that itself spans several lines hugs the brackets: `[new X(` … `)]`. - -```csharp -string[] searchPaths = -[ - Path.Combine(root, "Assets"), - Path.Combine(root, "Packages"), - Path.Combine(root, "Library", "Imported") -]; - -loader.ApplySourceChanges([ - new AssetEvent("Text/new.txt", WatcherChangeTypes.Deleted), - new AssetEvent("Text/old.txt", WatcherChangeTypes.Deleted) -]); - -return new ShaderCompilationResult( - null, - [new ShaderDiagnostic( - "SHADER_COMPILE_EXCEPTION", - DiagnosticSeverity.Error, - message - )] -); -``` - -Avoid: - -```csharp -string[] searchPaths = [Path.Combine(root, "Assets"), - Path.Combine(root, "Packages"), Path.Combine(root, "Library", "Imported")]; - -return new ShaderCompilationResult( - null, - [new ShaderDiagnostic( - "SHADER_COMPILE_EXCEPTION", - DiagnosticSeverity.Error, - message)]); -``` - -### I-04 `switch` expressions - -`value switch` is on one line; the opening brace is on its own line; each arm is on its own line with its `=>`; the discard arm is last. - -```csharp -string label = state switch -{ - EditorPlayModeState.Editing => "Enter Play Mode", - EditorPlayModeState.Compiling => "Compiling", - EditorPlayModeState.Playing => "Exit Play Mode", - _ => throw new ArgumentOutOfRangeException(nameof(state)) -}; -``` - -Avoid: - -```csharp -string label = state switch { EditorPlayModeState.Editing => "Enter", _ => "Exit", }; -``` - -### I-05 No trailing commas - -The last item of an object initializer, a collection, an enum, a `switch` expression or an anonymous object is not followed by a comma. - -```csharp -public enum ToneMapping -{ - None, - Reinhard, - Aces -} -``` - -Avoid: - -```csharp -public enum ToneMapping -{ - None, - Reinhard, - Aces, -} -``` - - - - -## 11. Spacing and blank lines - -### S-01 Spaces - -| Position | Rule | Example | -| --- | --- | --- | -| Control keyword and `(` | One space | `if (x)`, `foreach (T item in items)` | -| Method name, `typeof`, `nameof`, `default` and `(` | No space | `Draw(item)`, `typeof(int)` | -| `new` and `(` or `[` | No space | `new()`, `new[]` | -| Inside parentheses and brackets | No space | `Add(a, b)`, `items[0]` | -| Before an index bracket | No space | `items[0]` | -| Comma | None before, one after | `Add(a, b)` | -| Semicolon in `for` | None before, one after | `for (int i = 0; i < n; i++)` | -| Binary operators, assignment, `=>`, `??`, `?:` | One on each side | `a + b`, `x => x.id` | -| Unary operators | Attached to the operand | `!ready`, `-value`, `i++` | -| After a cast | No space | `(float)count` | -| Member access `.`, `?.`, `->` | No space | `entry?.name` | -| Inside generic angle brackets | No space | `Dictionary` | -| Nullable `?` and pointer `*` | Attached to the type | `string?`, `byte* data` | -| Range `..` | No space | `span[1..^1]` | -| Spread `..` | One space after | `[.. items]` | -| Inside single-line braces with content | One on each side | `{ get; }`, `new T { a = 1 }`, `is { }` | -| Empty body | No space inside | `{}` | -| Before `{` on the same line | One space | `) {`, `() {}` | -| Colon of a base list, constraint or initializer | One on each side | `class A : B`, `where T : class` | -| Colon of a named argument or attribute target | None before, one after | `width: 1280`, `[assembly: X]` | - -```csharp -if (ready) -{ - float ratio = (float)count / total; - int first = items[0]; - Draw(item, ratio, first); -} -``` - -Avoid: - -```csharp -if(ready) -{ - float ratio = (float) count/total; - int first = items [0]; - Draw( item,ratio , first ); -} -``` - -### S-02 Column alignment - -- When more than three consecutive `const` declarations, or more than three consecutive `static readonly` declarations, have the same type, aligning their `=` signs in a column is recommended. It is not required. -- A numeric matrix or lookup table may align its elements in columns. -- Everywhere else, use a single space between tokens. Do not column-align local variables, assignments, parameters or comments. - -```csharp -private const int C_WIDTH = 1280; -private const int C_HEIGHT = 720; -private const int C_REFRESH_RATE = 60; -private const int C_MIN_SIZE = 16; - -public static readonly Color RED = FromBytes(255, 0, 0); -public static readonly Color GREEN = FromBytes(0, 255, 0); -public static readonly Color BLUE = FromBytes(0, 0, 255); -public static readonly Color WHITE = FromBytes(255, 255, 255); - -private static readonly float[] IDENTITY = -[ - 1f, 0f, 0f, 0f, - 0f, 1f, 0f, 0f, - 0f, 0f, 1f, 0f, - 0f, 0f, 0f, 1f -]; -``` - -Avoid (alignment of local variables and trailing comments): - -```csharp -int width = 1280; -string title = "Scene"; // window title -float refreshRate = 60f; // hertz -``` - -### S-03 Blank lines between members - -- Methods, constructors, members with documentation comments and multi-line properties are separated by one blank line. -- Fields, constants and single-line properties of the same group that have no documentation comments are written consecutively. -- Different groups (O-01) are separated by one blank line. -- Enum members are not separated by blank lines, even when they have documentation comments. -- Types are separated by one blank line. - -```csharp -public sealed class Viewport -{ - private const int C_MIN_SIZE = 16; - private const int C_MAX_SIZE = 16384; - - private readonly RenderTarget m_target; - private int m_width; - private int m_height; - - /// - /// Gets the current width in pixels. - /// - public int width => m_width; - - /// - /// Gets the current height in pixels. - /// - public int height => m_height; - - internal bool isDirty { get; set; } - internal int generation { get; set; } -} -``` - -Avoid: - -```csharp -public sealed class Viewport -{ - private const int C_MIN_SIZE = 16; - - private const int C_MAX_SIZE = 16384; - private readonly RenderTarget m_target; - /// - /// Gets the current width in pixels. - /// - public int width => m_width; - internal bool isDirty { get; set; } - -} -``` - -### S-04 Blank lines inside method bodies - -- Separate processing phases (validation, preparation, execution, completion) with one blank line. Do not add blank lines mechanically. -- The argument validation at the start of a method (a run of `ThrowIf*` calls and guards) is contiguous and followed by one blank line. -- A local function is preceded by one blank line and placed at the end of the method body. -- No blank line follows an opening brace or precedes a closing brace. Never leave two consecutive blank lines. - -```csharp -public AssetHandle Import( - string path, - ImportOptions options -) { - ArgumentException.ThrowIfNullOrWhiteSpace(path); - ArgumentNullException.ThrowIfNull(options); - ObjectDisposedException.ThrowIf(m_disposed, this); - - AssetSource source = OpenSource(path); - ImportPlan plan = BuildPlan(source, options); - - AssetHandle handle = Execute(plan); - m_handles.Add(handle.id, handle); - return handle; - - ImportPlan BuildPlan( - AssetSource target, - ImportOptions settings - ) => new(target, settings); -} -``` - -Avoid: - -```csharp -public AssetHandle Import( - string path, - ImportOptions options -) { - - ArgumentException.ThrowIfNullOrWhiteSpace(path); - - ArgumentNullException.ThrowIfNull(options); - AssetSource source = OpenSource(path); - - - return Execute(BuildPlan(source, options)); - -} -``` - - - - -## 12. Types and expression idioms - -### E-01 Local variables state their type; `var` only with `new T(...)` - -- A local variable declares its type: `T x = expression;`. -- Use `var` when the right-hand side is `new T(...)` or `new T[...]`, where the type is visible on the same line. -- An anonymous type requires `var`. -- A local variable does not use `T x = new(...)`; that form is for fields and properties (M-04). -- A collection expression needs a target type, so the declaration states it: `List names = [];`. - -```csharp -AssetEntry entry = m_entries[index]; -int count = entry.dependencies.Count; -string name = entry.displayName; -var builder = new StringBuilder(capacity); -var buffer = new byte[C_BUFFER_SIZE]; -List names = []; -var projection = new { entry.id, entry.displayName }; -``` - -Avoid: - -```csharp -var entry = m_entries[index]; -var count = entry.dependencies.Count; -StringBuilder builder = new(capacity); -StringBuilder other = new StringBuilder(capacity); -``` - -### E-02 `foreach`, `for`, `using`, `out` and deconstruction state their types - -```csharp -foreach (AssetEntry entry in m_entries) -{ - Visit(entry); -} - -foreach ((string key, AssetEntry value) in m_byName) -{ - Visit(value); -} - -for (int i = 0; i < count; i++) -{ - Visit(m_entries[i]); -} - -using Stream stream = lease.OpenRead(); - -if (m_byName.TryGetValue(name, out AssetEntry? found)) -{ - Visit(found); -} -``` - -Avoid: - -```csharp -foreach (var entry in m_entries) -{ - Visit(entry); -} - -using var stream = lease.OpenRead(); - -if (m_byName.TryGetValue(name, out var found)) -{ - Visit(found); -} -``` - -### E-03 Built-in types use keywords - -Write `int`, `string`, `float`, `object`, `nint` and `nuint`, not `Int32`, `String`, `IntPtr` or `UIntPtr`. Access static members through the keyword as well. - -```csharp -nint handle = nint.Zero; -bool empty = string.IsNullOrWhiteSpace(name); -float largest = float.MaxValue; -``` - -Avoid: - -```csharp -IntPtr handle = IntPtr.Zero; -bool empty = String.IsNullOrWhiteSpace(name); -Single largest = Single.MaxValue; -``` - -### E-04 Null checks use patterns - -Use `is null` and `is not null`. Use `is { } x` or `is T x` to test and capture at once. Do not write `== null` or `!= null`. - -```csharp -if (m_source is null) return; - -if (m_owner is not null) -{ - m_owner.Release(); -} - -if (TryFind(id) is { } entry) -{ - Visit(entry); -} -``` - -Avoid: - -```csharp -if (m_source == null) return; - -if (!(m_owner is null)) -{ - m_owner.Release(); -} -``` - -### E-05 Argument validation - -Validation comes first in a method, in parameter order, and uses the `ThrowIf*` helpers. Do not write `?? throw new ArgumentNullException(...)`. - -```csharp -public Viewport( - RenderTarget target, - string name, - int width -) { - ArgumentNullException.ThrowIfNull(target); - ArgumentException.ThrowIfNullOrWhiteSpace(name); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - - m_target = target; - m_width = width; - this.name = name; -} -``` - -Avoid: - -```csharp -public Viewport( - RenderTarget target, - string name -) { - m_target = target ?? throw new ArgumentNullException(nameof(target)); - if (name == null) - { - throw new ArgumentNullException("name"); - } -} -``` - -### E-06 Object creation - -- A local variable: `var x = new T(...)` (E-01). -- A field or property initializer: `= new(...)` (M-04). -- A member that directly returns a new object of its declared return type may use `new(...)`. -- An argument, or a creation inside a larger expression, writes the type: `new T(...)`. - -```csharp -public static Color FromBytes( - byte r, - byte g, - byte b -) => new(r / 255f, g / 255f, b / 255f); -``` - -```csharp -var item = new RenderItem(mesh, material); -queue.Enqueue(new RenderItem(mesh, material)); -``` - -Avoid: - -```csharp -RenderItem item = new(mesh, material); -queue.Enqueue(new(mesh, material)); -``` - -### E-07 Common values - -| Meaning | Write | Not | -| --- | --- | --- | -| Empty string | `string.Empty` | `""` | -| Default value | `default` | `default(T)`, unless the type cannot be inferred | -| Empty collection | `[]` | `new List()`, `Array.Empty()` | -| Negation | `!ready` | `ready == false` | -| Non-nullable `bool` test | `if (ready)` | `if (ready == true)` | -| Nullable `bool?` test | `if (flag == true)` | `if (flag ?? false)` | -| Conversion | `(T)value` | `value as T` without a following null check | -| Type test with capture | `value is T typed` | `as` followed by a null check | -| Delegate invocation | `handler?.Invoke(args)` | a null check followed by a call | -| Rethrow | `throw;` | `throw exception;` | -| Infinite loop | `while (true)` | `for (;;)` | -| Current time | `DateTime.UtcNow`, `DateTimeOffset.UtcNow` | `DateTime.Now` | - -```csharp -string label = string.Empty; -Color color = default; -flushed?.Invoke(); -if (value is AssetEntry typed) -{ - Visit(typed); -} -``` - -Avoid: - -```csharp -string label = ""; -Color color = default(Color); -if (flushed != null) -{ - flushed.Invoke(); -} - -AssetEntry typed = value as AssetEntry; -if (typed != null) -{ - Visit(typed); -} -``` - -### E-08 `this.` - -- Inside a constructor, every assignment to an instance member that is not an `m_` field goes through `this.`: `this.name = name;`, `this.count = 0;`. This holds whether or not a parameter has the same name. -- Outside constructors, do not write `this.` unless it is needed to disambiguate. -- Apart from constructor parameters, a parameter or local variable does not take the name of a property of the same type. - -```csharp -public GameBuildPackageContext( - BuildProfile profile, - string outputDirectory -) { - m_createdUtc = DateTime.UtcNow; - this.profile = profile; - this.outputDirectory = outputDirectory; - this.isIncremental = true; -} - -public BuildProfile profile { get; } -public string outputDirectory { get; } -public bool isIncremental { get; private set; } - -public string Describe() => $"{profile.name} -> {outputDirectory}"; -``` - -Avoid (`isIncremental` assigned without `this.` in the constructor, `this.` outside the constructor): - -```csharp -public GameBuildPackageContext( - BuildProfile profile, - string outputDirectory -) { - this.profile = profile; - this.outputDirectory = outputDirectory; - isIncremental = true; -} - -public string Describe() => $"{this.profile.name} -> {this.outputDirectory}"; -``` - -### E-09 Strings - -- Build strings from values with interpolation, `$"..."`. Do not use `string.Format` or `string.Concat`. -- Split a long message with `+` at the start of the continuation line (W-01). Use a raw string literal, `"""`, for multi-line text. -- Comparison, lookup, sorting and dictionaries state `StringComparison.Ordinal` / `StringComparer.Ordinal` or the `OrdinalIgnoreCase` variants. -- Change case with `ToLowerInvariant()` / `ToUpperInvariant()` and format with `CultureInfo.InvariantCulture`. -- Refer to identifiers with `nameof(...)`. -- Test external input with `string.IsNullOrWhiteSpace`, and use `string.IsNullOrEmpty` only when whitespace is meaningful. - -```csharp -string message = $"The asset '{path}' could not be imported: {reason}"; -bool same = string.Equals(left, right, StringComparison.Ordinal); -var index = new Dictionary(StringComparer.OrdinalIgnoreCase); -throw new ArgumentException("The path must be relative.", nameof(path)); -``` - -Avoid: - -```csharp -string message = string.Format("The asset '{0}' could not be imported: {1}", path, reason); -bool same = left.ToLower() == right.ToLower(); -throw new ArgumentException("The path must be relative.", "path"); -``` - -### E-10 Numeric literals - -- `float`: write an integral value as `1f` and a fractional value as `1.5f`. Do not write `1.0f` or `1.50f`. -- Suffixes: `f`, `d`, `m` and `u` are lower case; `L` and `UL` are upper case. -- Hexadecimal: the `0x` prefix is lower case, the digits are upper case, and long values are grouped by four digits with `_`. -- Large decimal values are grouped by three digits with `_`. - -```csharp -float half = 0.5f; -float one = 1f; -uint mask = 0xFF00_00FFu; -long ticks = 10_000_000L; -``` - -Avoid: - -```csharp -float one = 1.0f; -float ratio = 1.50f; -uint mask = 0xff0000ffU; -long ticks = 10000000l; -``` - -### E-11 Lambdas - -- One parameter has no parentheses: `x => ...`. No parameters: `() => ...`. Two or more parameters are expanded (P-01). -- Parameters have meaningful names. An unused parameter is `_`. -- A lambda that captures neither a local variable nor `this` is `static`. -- A single-expression body uses the expression form; several statements use a block (B-04). -- When an expression body does not fit on the line of the lambda, it is wrapped in parentheses, unless it is a call or object creation, which breaks inside its own parentheses (B-04). -- Do not use anonymous methods (`delegate { }`). - -```csharp -entries.RemoveAll(static entry => entry.isMissing); -entries.RemoveAll(entry => entry.generation < m_generation); -button.clicked += () => m_log.Info("Clicked."); - -Func isStale = entry => ( - entry.lastWriteTimeUtc < threshold && !entry.isPinned -); -``` - -Avoid: - -```csharp -entries.RemoveAll((entry) => entry.isMissing); -entries.RemoveAll(x => x.isMissing); - -Func isStale = entry => - entry.lastWriteTimeUtc < threshold && !entry.isPinned; -``` - -### E-12 `using` declarations - -Use a `using` declaration when the resource lives until the end of the enclosing block. Use a `using` statement with a block only when the resource must be released earlier. - -```csharp -using Stream stream = lease.OpenRead(); -using var reader = new StreamReader(stream); -return reader.ReadToEnd(); -``` - -Avoid (a block that ends where the method ends): - -```csharp -using (Stream stream = lease.OpenRead()) -{ - using (var reader = new StreamReader(stream)) - { - return reader.ReadToEnd(); - } -} -``` - - - - -## 13. Control flow, exceptions and asynchronous code - -### X-01 Guard clauses return early - -Handle invalid and boundary cases first and leave with `return`, `throw` or `continue`. The main path is not nested inside `else`. Guards may use the compact form of B-05. - -```csharp -public void Draw(RenderItem item) -{ - if (m_disposed) return; - if (!item.isVisible) return; - - Submit(item); - m_drawn++; -} -``` - -Avoid: - -```csharp -public void Draw(RenderItem item) -{ - if (!m_disposed) - { - if (item.isVisible) - { - Submit(item); - m_drawn++; - } - } -} -``` - -### X-02 `switch` - -- Use a `switch` expression to map a value to a value (I-04). -- Use a `switch` statement when the branches execute statements. `case` is indented four spaces from `switch`, and the statements four spaces from `case`. Each label is on its own line. `default` is last. Add braces to a section only when it declares local variables that would otherwise collide. - -```csharp -switch (command.kind) -{ - case CommandKind.Draw: - case CommandKind.DrawIndexed: - Submit(command); - break; - case CommandKind.Clear: - Clear(command.color); - break; - default: - throw new InvalidOperationException($"Unknown command kind '{command.kind}'."); -} -``` - -Avoid: - -```csharp -switch (command.kind) -{ -case CommandKind.Draw: case CommandKind.DrawIndexed: - Submit(command); break; -default: throw new InvalidOperationException($"Unknown command kind '{command.kind}'."); -case CommandKind.Clear: - Clear(command.color); - break; -} -``` - -### X-03 Exception types and messages - -| Situation | Exception | -| --- | --- | -| An argument is `null` | `ArgumentNullException`, through `ThrowIfNull` | -| An argument value is invalid | `ArgumentException`, `ArgumentOutOfRangeException` | -| The object state does not allow the operation | `InvalidOperationException` | -| The object has been disposed | `ObjectDisposedException`, through `ThrowIf` | -| Input data is malformed | `InvalidDataException` | -| The platform or backend does not support the operation | `NotSupportedException` | - -A message is a complete English sentence that includes the offending value. Parameter names use `nameof`. A `throw` whose arguments do not fit on one line breaks like any other call (A-02). - -```csharp -throw new InvalidDataException( - $"The scene file '{path}' declares version {version}, but only version {C_VERSION} is supported." -); -``` - -Avoid: - -```csharp -throw new InvalidDataException( - $"The scene file '{path}' declares version {version}, but only version {C_VERSION} is supported."); - -throw new Exception("bad version"); -``` - -### X-04 `catch` - -- Catch the specific type that can be handled. When catching `Exception`, filter with `when` or rethrow with `throw;` after handling. -- The variable is named `exception` by default. A name that states the role, such as `cleanupFailure`, is allowed when the exception is stored or aggregated. Omit the variable when it is not used. -- A bare `catch` without a type is only for "clean up, then rethrow". -- A `catch` block that deliberately ignores an exception contains a comment that says why. - -```csharp -try -{ - Directory.Delete(scratch, recursive: true); -} -catch (IOException) -{ - // The scratch directory is retried by the next retirement pass. -} - -try -{ - Publish(candidate); -} -catch (Exception exception) when (exception is not OperationCanceledException) -{ - m_log.Error($"Publication failed: {exception.Message}"); - throw; -} -``` - -Avoid: - -```csharp -try -{ - Directory.Delete(scratch, recursive: true); -} -catch {} - -try -{ - Publish(candidate); -} -catch (Exception ex) -{ - throw ex; -} -``` - -### X-05 Asynchronous code - -- Return `Task` or `ValueTask`. Never write `async void`. -- The method name ends with `Async` (NM-04). `CancellationToken cancellationToken` is the last parameter and is passed down to every asynchronous call. -- In product code (`src`, `build`, `backends`, `platforms`, `tools`, `entry`) every `await` ends with `.ConfigureAwait(false)`. Test code does not use `ConfigureAwait`. -- Do not block on asynchronous results with `.Wait()`, `.Result` or `.GetAwaiter().GetResult()`. An entry point that must wait synchronously carries a comment that explains why. -- On a broken `await` call, `.ConfigureAwait(false)` follows the closing parenthesis on its line. - -```csharp -public async Task LoadAsync( - AssetID id, - CancellationToken cancellationToken -) { - await using Stream stream = await m_storage.OpenAsync(id, cancellationToken).ConfigureAwait(false); - return await m_reader.ReadAsync( - stream, - id, - cancellationToken - ).ConfigureAwait(false); -} -``` - -Avoid: - -```csharp -public async void Load(AssetID id) -{ - Stream stream = m_storage.OpenAsync(id, CancellationToken.None).Result; - await m_reader.ReadAsync(stream, id, CancellationToken.None); -} -``` - - - - -## 14. Comments and XML documentation - -### D-01 Which members need XML documentation - -Every externally visible public member, and every protected member that an external type can override, has complete English XML documentation. Important internal APIs are documented as well. Private members and test code do not need documentation. - -```csharp -/// -/// Stores render items until the next flush. -/// -public sealed class RenderQueue -{ - private readonly List m_items = []; - - /// - /// Gets the number of queued items. - /// - public int count => m_items.Count; - - private void Trim() => m_items.TrimExcess(); -} -``` - -Avoid (a public type and a public property without documentation): - -```csharp -public sealed class RenderQueue -{ - public int count => m_items.Count; -} -``` - -### D-02 Tags are expanded, one element per block - -- The start tag, the content and the end tag are on separate lines. `///` is followed by one space. A documentation block has no empty `///` lines. -- Tag order: `summary`, `typeparam`, `param` (in signature order), `returns`, `exception`, `remarks`. -- Every content block starts with a capital letter and ends with a period. -- Wrap long content at complete semantic boundaries. - -```csharp -/// -/// Resolves a loaded asset by its persistent identity. -/// -/// -/// The asset type expected by the caller. -/// -/// -/// The persistent identity of the asset. -/// -/// -/// Receives the asset when this method returns ; -/// otherwise . -/// -/// -/// when the asset is loaded and has the requested type; -/// otherwise . -/// -/// -/// The loader has been disposed. -/// -public bool TryResolve( - AssetID id, - [NotNullWhen(true)] out TAsset? asset -) where TAsset : class -{ - ObjectDisposedException.ThrowIf(m_disposed, this); - return TryResolveCore(id, out asset); -} -``` - -Avoid: - -```csharp -/// Resolves an asset -/// the asset -/// the id -/// true if found -public bool TryResolve( - AssetID id, - [NotNullWhen(true)] out TAsset? asset -) where TAsset : class -{ - ObjectDisposedException.ThrowIf(m_disposed, this); - return TryResolveCore(id, out asset); -} -``` - -### D-03 Wording of summaries - -| Member | Starts with | Example | -| --- | --- | --- | -| Read-only property | `Gets` | `Gets the current width in pixels.` | -| Writable property | `Gets or sets` | `Gets or sets the clear color.` | -| `bool` property | `Gets a value indicating whether` | `Gets a value indicating whether the asset is missing.` | -| Method | A third-person verb | `Creates`, `Releases`, `Determines whether`, `Attempts to` | -| Constructor | `Initializes a new instance of` or `Creates` | `Creates a dispatcher bound to the given hub.` | -| Type | A third-person verb or a noun phrase | `Identifies`, `Describes`, `Provides`, `Represents` | -| Event | `Occurs when` | `Occurs when the platform requests a redraw.` | - -A summary describes real behavior. It does not restate the member name. - -```csharp -/// -/// Gets the current width of the viewport in pixels. -/// -public int width => m_width; -``` - -Avoid: - -```csharp -/// -/// The width. -/// -public int width => m_width; -``` - -### D-04 References inside documentation - -- A type or member: ``. A parameter: ``. A type parameter: ``. -- A keyword: ``, ``, ``. -- A self-closing tag has no space before `/>`. -- An override or interface implementation uses `/// ` and documents any additional constraint locally with `remarks` or `exception`. - -```csharp -/// -public override string ToString() => name; -``` - -Avoid: - -```csharp -/// -/// Returns null if id is not found. See AssetLoader. -/// -/// -public override string ToString() => name; -``` - -### D-05 `//` comments - -- A comment explains a reason, a constraint, ownership or a lifetime. It does not restate the code. -- A comment is on its own line, above the code it explains, at the indentation of that code. Do not write trailing comments. -- `//` is followed by one space. The comment is a complete English sentence that starts with a capital letter and ends with a period. - -```csharp -// The native window must outlive the swap chain, so it is released last. -m_swapChain.Dispose(); -m_window.Dispose(); -``` - -Avoid: - -```csharp -m_swapChain.Dispose(); // dispose swap chain -//release window -m_window.Dispose(); -``` - -### D-06 Prohibited comments and directives - -- Comments in any language other than English. -- `TODO`, `FIXME` or `HACK` markers left in place indefinitely. -- Commented-out code. -- Separator lines, banner comments and `/* */` block comments. -- `#region` and `#endregion`. -- `#nullable` inside a file, and `#pragma warning disable` without a comment that states the reason. - -`#if`, `#elif`, `#else` and `#endif` start at column 0. Conditional symbols are UPPER_SNAKE with the `INNO_` prefix, except `DEBUG`. - -```csharp -#if INNO_HOST_WINDOWS_X64 - private const string C_LIBRARY_NAME = "bgfx.dll"; -#elif INNO_HOST_MACOS_ARM64 - private const string C_LIBRARY_NAME = "libbgfx.dylib"; -#endif -``` - -Avoid: - -```csharp -#region Constants - // ---------- library ---------- - // TODO: revisit - // private const string C_OLD_NAME = "bgfx_old.dll"; - private const string C_LIBRARY_NAME = "bgfx.dll"; /* windows */ -#endregion -``` - - - - -## 15. Tests - -### TS-01 Structure - -- Tests use xUnit. A test class is `public sealed class XxxTests` in `XxxTests.cs`, in the namespace of the test project. -- A test method is `public`, returns `void` or `async Task`, and carries `[Fact]`, or `[Theory]` with `[InlineData]`. -- Test classes and test methods do not need XML documentation. -- Fixtures and test doubles follow the same naming and layout rules as product code. A nested test double is `private sealed` and placed at the end of the test class. - -```csharp -using System; -using Xunit; -using Inno.Core.Events; - -namespace Inno.Core.Events.Tests; - -public sealed class EventDispatcherTests -{ - [Fact] - public void NewDispatcherHasNoSinks() - { - var dispatcher = new EventDispatcher(); - - Assert.Empty(dispatcher.sinks); - } - - private sealed class RecordingSink : IEventSink - { - public int published { get; private set; } - - public void Publish(EventRecord record) => published++; - } -} -``` - -Avoid: - -```csharp -public class EventDispatcherTest -{ - [Fact] - void NewDispatcherHasNoSinks() {} -} -``` - -### TS-02 Test method names - -A test method name is a PascalCase statement of what happens under which condition. It has no underscores, no `Async` suffix and no `Test` prefix or suffix. - -```csharp -public sealed class EventDispatcherTests -{ - [Fact] - public void DispatchAfterDisposeThrowsObjectDisposedException() - { - var dispatcher = new EventDispatcher(); - dispatcher.Dispose(); - - Assert.Throws(() => dispatcher.Dispatch(new EventRecord())); - } - - [Theory] - [InlineData(0)] - [InlineData(-1)] - public void NonPositiveCapacityIsRejected(int capacity) - => Assert.Throws(() => new EventDispatcher(capacity)); - - [Fact] - public async Task PendingEventsAreDeliveredBeforeShutdownCompletes() - { - var dispatcher = new EventDispatcher(); - List received = []; - dispatcher.dispatched += received.Add; - - dispatcher.Dispatch(new EventRecord()); - await dispatcher.ShutdownAsync(CancellationToken.None); - - Assert.Single(received); - } -} -``` - -Avoid: - -```csharp -public sealed class EventDispatcherTests -{ - [Fact] - public void Dispatch_AfterDispose_Throws() - { - var dispatcher = new EventDispatcher(); - dispatcher.Dispose(); - } - - [Fact] - public async Task TestShutdownAsync() - { - var dispatcher = new EventDispatcher(); - await dispatcher.ShutdownAsync(CancellationToken.None).ConfigureAwait(false); - } -} -``` - -### TS-03 Assertions and layout - -- Separate the arrange, act and assert phases with one blank line. A very short test may omit the separation. -- `Assert.Equal(expected, actual)`: the expected value comes first. -- Source text used as test data (generator inputs and expected outputs) is data, not code; this rulebook does not apply to it. - -```csharp -[Fact] -public void ResizeUpdatesBothDimensions() -{ - var viewport = new Viewport(m_target, "Main", 640); - - viewport.Resize(width: 1280, height: 720); - - Assert.Equal(1280, viewport.width); - Assert.Equal(720, viewport.height); -} -``` - -Avoid (actual value first, phases not separated): - -```csharp -[Fact] -public void ResizeUpdatesBothDimensions() -{ - var viewport = new Viewport(m_target, "Main", 640); - viewport.Resize(width: 1280, height: 720); - Assert.Equal(viewport.width, 1280); -} -``` - - - - -## 16. Exceptions - -The following cases follow an external contract. Do not rename or reformat them to satisfy this rulebook. - -| Case | What it keeps | Example | -| --- | --- | --- | -| Generated code and third-party sources | Everything | `extern/`, `**/Generated/*.cs`, `` files | -| MSBuild task parameters | PascalCase property names bound by MSBuild | `public string OutputPath { get; set; }` | -| Overrides and interface implementations | The name declared by the base type or interface | `Stream.CanRead`, `IEnumerator.Current` | -| Special CLR members | Names required by the language or runtime | operators, `GetEnumerator`, `Deconstruct`, `Dispose` | -| Native interop signatures | Field names, enum values and imported function names from the native header | `SDL_Event`, bgfx enums | -| Serialized wire names | The serialized name; source property names and wire names are declared separately | | -| Third-party product names | The spelling used by the product | `RmlUi`, `ImGui`, `MiniAudio` | -| Keyboard and input code enums | Single-letter and digit members | `KeyCode.A`, `KeyCode.F1` | -| Numeric matrices and lookup tables | Several elements per line, column alignment (S-02) | a 4×4 matrix literal | -| Unsplittable string literals | Length beyond the line width (F-04) | paths, URLs | -| Generator templates and their tests | `global::` and fully qualified names required by the generation protocol | | -| Source text used as test data | Its own formatting (TS-03) | | - -Keep each exception as small as possible: it covers the name or the layout bound by the contract, and the rest of the file follows the rulebook. - - - - -## 17. Reference example - -One file that applies the rules together. - -```csharp -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Inno.Core.Diagnostics; -using Inno.Core.Identity; - -using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; - -namespace Inno.Assets.Pipeline; - -/// -/// Caches loaded assets and reloads them when their sources change. -/// -public sealed class AssetCache : IDisposable -{ - private const int C_INITIAL_CAPACITY = 64; - private const int C_MAX_ATTEMPT_COUNT = 3; - - private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromMilliseconds(50); - - private readonly Dictionary m_entries = new(C_INITIAL_CAPACITY); - private readonly IAssetStore m_store; - private readonly ILogSink m_log; - private int m_generation; - private bool m_disposed; - - /// - /// Creates a cache that reads asset content from the given store. - /// - /// - /// The store that provides asset content. - /// - /// - /// The sink that receives reload diagnostics. - /// - /// - /// The diagnostic name of the cache. - /// - /// - /// is empty or consists only of white space. - /// - public AssetCache( - IAssetStore store, - ILogSink log, - string name - ) { - ArgumentNullException.ThrowIfNull(store); - ArgumentNullException.ThrowIfNull(log); - ArgumentException.ThrowIfNullOrWhiteSpace(name); - - m_store = store; - m_log = log; - this.name = name; - this.isEnabled = true; - } - - /// - /// Gets the diagnostic name of the cache. - /// - public string name { get; } - - /// - /// Gets a value indicating whether the cache accepts source changes. - /// - public bool isEnabled { get; private set; } - - /// - /// Gets the number of cached assets. - /// - public int count => m_entries.Count; - - /// - /// Occurs when a cached asset has been reloaded from its source. - /// - public event Action? assetReloaded; - - /// - /// Attempts to find a cached asset that is still current. - /// - /// - /// The persistent identity of the asset. - /// - /// - /// Receives the cached handle when this method returns ; - /// otherwise . - /// - /// - /// when a current entry exists; otherwise . - /// - public bool TryResolve( - AssetID id, - [NotNullWhen(true)] out AssetHandle? handle - ) { - ObjectDisposedException.ThrowIf(m_disposed, this); - - if (m_entries.TryGetValue(id, out Entry? entry) - && entry.generation == m_generation - && !entry.handle.isMissing - ) { - handle = entry.handle; - return true; - } - - handle = null; - return false; - } - - /// - /// Loads an asset, reusing the cached handle when it is still current. - /// - /// - /// The persistent identity of the asset. - /// - /// - /// A token that cancels the load. - /// - /// - /// The loaded asset handle. - /// - /// - /// The store could not provide the asset after every attempt. - /// - public async Task LoadAsync( - AssetID id, - CancellationToken cancellationToken - ) { - if (TryResolve(id, out AssetHandle? cached)) return cached; - - for (int attempt = 1; attempt <= C_MAX_ATTEMPT_COUNT; attempt++) - { - try - { - AssetHandle handle = await m_store.LoadAsync(id, cancellationToken).ConfigureAwait(false); - m_entries[id] = new Entry(handle, m_generation); - return handle; - } - catch (IOException exception) when (attempt < C_MAX_ATTEMPT_COUNT) - { - m_log.Warning($"Loading asset '{id}' failed on attempt {attempt}: {exception.Message}"); - await Task.Delay(RETRY_DELAY, cancellationToken).ConfigureAwait(false); - } - } - - throw new InvalidDataException( - $"The asset '{id}' could not be loaded from store '{m_store.name}' after {C_MAX_ATTEMPT_COUNT} attempts." - ); - } - - /// - /// Applies source changes and invalidates the affected entries. - /// - /// - /// The source changes reported by the watcher. - /// - public void ApplySourceChanges(IReadOnlyList changes) - { - ArgumentNullException.ThrowIfNull(changes); - if (!isEnabled) return; - - m_generation++; - foreach (AssetEvent change in changes) - { - if (!m_store.TryGetID(change.path, out AssetID id)) continue; - - string action = change.change switch - { - WatcherChangeTypes.Deleted => "removed", - WatcherChangeTypes.Renamed => "renamed", - _ => "changed" - }; - m_log.Info($"Asset '{id}' was {action}."); - - m_entries.Remove(id); - assetReloaded?.Invoke(id); - } - } - - /// - public void Dispose() - { - if (m_disposed) return; - - // Entries only borrow their handles, so the store releases the content. - m_entries.Clear(); - m_disposed = true; - } - - internal bool IsCurrent(AssetID id) - => m_entries.TryGetValue(id, out Entry? entry) - && entry.generation == m_generation; - - private sealed record Entry( - AssetHandle handle, - int generation - ); -} -``` - diff --git a/.agents/rulebook/csharp-style/01-files.md b/.agents/rulebook/csharp-style/01-files.md new file mode 100644 index 000000000..4327e62a3 --- /dev/null +++ b/.agents/rulebook/csharp-style/01-files.md @@ -0,0 +1,130 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 1. Files and physical layout + +## F-01 Encoding, line endings and indentation + +- UTF-8 without a byte order mark. +- LF line endings. +- Four spaces per indentation level. Never use tab characters. +- No trailing whitespace. +- The file ends with exactly one newline. +- At most one consecutive blank line. + +In the next two blocks `→` is a tab, `·` is a space and `¶` is a newline. + +```text +····private int m_count;¶ +}¶ +``` + +Avoid (tab indentation, trailing whitespace, extra blank line at the end of the file): + +```text +→private int m_count;··¶ +}¶ +¶ +``` + +## F-02 One top-level type per file, named after the type + +- The file name is the PascalCase name of its primary type: `EventDispatcher.cs` contains `EventDispatcher`. +- Generic arity is not part of the file name: `Pool` lives in `Pool.cs`. +- Additional files of a `partial` type are named `Type.Part.cs`. +- A small, tightly coupled contract (an enum, delegate or parameter record used only by the primary type) may share the file. The primary type comes first. + +```text +Inno.Core.Events/ + EventDispatcher.cs class EventDispatcher + EventDispatcher.Observation.cs partial class EventDispatcher + IEventSink.cs interface IEventSink +``` + +## F-03 File structure + +A file contains, in this order: the using directives, one blank line, the file-scoped namespace, one blank line, the types. There is no file header comment, no license banner and no leading blank line. + +```csharp +using System; +using System.Collections.Generic; + +namespace Inno.Core.Events; + +/// +/// Dispatches events to registered sinks. +/// +public sealed class EventDispatcher +{ + private readonly List m_sinks = []; +} +``` + +Avoid (no blank line after the namespace): + +```csharp +namespace Inno.Core.Events; +public sealed class EventDispatcher +{ + private readonly List m_sinks = []; +} +``` + +## F-04 Line width + +- Aim for 120 columns or fewer. 140 columns is the hard limit. +- Only an unsplittable string literal (a path, a URL, one diagnostic sentence) may exceed the hard limit. +- Do not split a name, a modifier list or a short expression body merely to shorten a line. + +```csharp +// 107 columns: stays on one line. +public bool isMissing => m_source is null || !m_source.exists || m_source.generation != m_owner.generation; + +// 145 columns on one line: break it by meaning. +throw new InvalidOperationException( + $"The importer '{importer.name}' produced no result for '{path}' while generation {generation} was active." +); +``` + +Avoid (a short declaration split for no reason): + +```csharp +public bool isMissing + => m_source is null; +``` + +## F-05 Indentation and alignment of continuation lines + +Prefer alignment over a fixed indent. + +- **Operator continuation.** When an expression is broken at an operator (`&&`, `||`, `??`, `+`, `?`, `:`, `or`, `and`, …), each continuation line begins with the operator and aligns with the first operand of that expression. +- **Fallback.** When alignment would push a line past the hard limit, indent the continuation lines four spaces from the start of the statement instead. +- **Delimited lists.** The contents of a broken parameter list, argument list, initializer or collection are indented four spaces from the line that opens them. The closing delimiter, when it is on its own line, aligns with the first token of the opening line. +- **Call chains, wrapped `=>` and clauses.** A wrapped `.Member(...)` link, a wrapped expression-body `=>`, and a wrapped `where` or constructor-initializer clause are indented four spaces from the start of the statement or declaration. + +```csharp +bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format; + +return left.order != right.order + || left.layer != right.layer; + +string name = entry.displayName + ?? entry.path.GetFileName() + ?? string.Empty; + +List names = m_entries + .Where(static entry => !entry.isMissing) + .Select(static entry => entry.displayName) + .ToList(); +``` + +Avoid (operator continuation indented by a fixed amount instead of aligned): + +```csharp +bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format; +``` diff --git a/.agents/rulebook/csharp-style/02-namespaces.md b/.agents/rulebook/csharp-style/02-namespaces.md new file mode 100644 index 000000000..7ad80e597 --- /dev/null +++ b/.agents/rulebook/csharp-style/02-namespaces.md @@ -0,0 +1,163 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 2. Namespaces and using directives + +## N-01 File-scoped namespaces + +Use `namespace X;`. A file declares exactly one namespace. + +```csharp +namespace Inno.Core.Events; + +public sealed class EventDispatcher +{ + private int m_generation; +} +``` + +Avoid: + +```csharp +namespace Inno.Core.Events +{ + public sealed class EventDispatcher + { + private int m_generation; + } +} +``` + +## N-02 The namespace is the project name + +The namespace starts with `Inno`, uses PascalCase segments and equals the assembly name of the owning project. Directories inside a project organize files; they do not add namespace segments. + +```csharp +// File: src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs +namespace Inno.Assets.Pipeline; +``` + +Avoid: + +```csharp +// File: src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs +namespace Inno.Assets.Pipeline.Importing; +``` + +The one registered exception is `Inno.Editor.ImGui/Widgets`, which uses `Inno.Editor.ImGui.ImGuiWidget`. + +## N-03 Placement and kinds of using directives + +- All using directives are at the top of the file, outside the namespace. +- `global using`, implicit usings and MSBuild `Using` items are prohibited. Handwritten code never uses `global::`. +- `using static` is reserved for pure function containers such as math helpers. + +```csharp +using System; +using Inno.Core.Events; + +namespace Inno.Rendering; +``` + +Avoid: + +```csharp +global using System; + +namespace Inno.Rendering; + +using Inno.Core.Events; + +public sealed class Renderer +{ + private readonly global::Inno.Core.Events.EventDispatcher m_dispatcher = new(); +} +``` + +## N-04 Order of using directives + +Using directives form up to three groups, in this order, separated by exactly one blank line: + +1. Namespace usings. +2. `using static` directives. +3. Alias usings. + +Inside the namespace group the order is: + +1. `System` and `System.*`. +2. Everything else that is not `Inno` (third-party and framework packages). +3. `Inno` and `Inno.*`. + +Each tier is sorted alphabetically (ordinal). There are no blank lines inside a group. Static usings follow the same three tiers; aliases are sorted by alias name. + +```csharp +using System; +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis; +using Xunit; +using Inno.Core.Events; +using Inno.Core.Identity; + +using static System.MathF; + +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; +using NativeWindow = Inno.Adapter.Platform.Sdl3.Sdl3Window; +``` + +Avoid (`Inno` before third-party namespaces, a blank line inside the namespace group, an alias among the namespace usings, no blank line between kinds): + +```csharp +using Inno.Core.Events; +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; +using Xunit; + +using System; +using System.Collections.Generic; +using static System.MathF; +``` + +## N-05 No fully qualified names at the point of use + +Import a type with a using directive and refer to it by its short name. When two names collide, declare one alias at the top of the file and use only that alias throughout the file. + +```csharp +using System.IO; + +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; + +namespace Inno.Assets.Pipeline.Tests; + +public sealed class AssetLoaderTests +{ + private static AssetEvent Deleted(string path) => new(path, WatcherChangeTypes.Deleted); +} +``` + +Avoid: + +```csharp +namespace Inno.Assets.Pipeline.Tests; + +public sealed class AssetLoaderTests +{ + private static Inno.Assets.Pipeline.AssetChangedEvent Deleted(string path) + => new(path, System.IO.WatcherChangeTypes.Deleted); +} +``` + +## N-06 Alias names + +An alias is PascalCase, names the role the type plays in this file and differs from the short name of its target. One target has one alias per file. + +```csharp +using NativeWindow = Inno.Adapter.Platform.Sdl3.Sdl3Window; +``` + +Avoid (the alias repeats the target name, and a second alias names the same target): + +```csharp +using Sdl3Window = Inno.Adapter.Platform.Sdl3.Sdl3Window; +using Window = Inno.Adapter.Platform.Sdl3.Sdl3Window; +``` diff --git a/.agents/rulebook/csharp-style/03-naming.md b/.agents/rulebook/csharp-style/03-naming.md new file mode 100644 index 000000000..6096d27e9 --- /dev/null +++ b/.agents/rulebook/csharp-style/03-naming.md @@ -0,0 +1,382 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, naming] +--- +# 3. Naming + +## Summary + +| Element | Rule | Example | +| --- | --- | --- | +| Namespace segment | PascalCase | `Inno.Core.Events` | +| Class, struct, record, enum, delegate | PascalCase | `RenderGraph`, `AssetHandle` | +| Interface | `I` + PascalCase | `IEventSink` | +| Type parameter | `T` or `T` + PascalCase | `T`, `TSource` | +| Method, local function | PascalCase | `TryResolve`, `CreateBuffer` | +| Property, indexer | camelCase | `transform`, `isMissing` | +| Event | camelCase | `redrawRequested` | +| Constant (`const`, including local constants) | `C_` + UPPER_SNAKE | `C_MAX_COUNT` | +| `static readonly` field (any accessibility) | UPPER_SNAKE | `DEFAULT_OPTIONS`, `RED` | +| Private static mutable field | `s_` + camelCase | `s_nextID` | +| Private or protected instance field | `m_` + camelCase | `m_generation` | +| Internal or public instance field | camelCase | `latestSucceeded` | +| Enum member | PascalCase | `Borrowed` | +| Parameter, local variable, tuple element | camelCase | `outputDirectory` | +| Two-letter acronym | Upper case in PascalCase positions | `AssetID`, `IOStatus`, `UIScale` | +| Test class and test method | `XxxTests`, PascalCase sentence | `DispatchAfterDisposeThrows` | + +## NM-01 Type names + +A type name is a PascalCase noun or noun phrase. The suffix follows the role: `Attribute`, `Exception`, `EventArgs`, `Tests`, and `Extensions` for a class that holds extension methods. An abstract class has no `Base` or `Abstract` affix. + +```csharp +public sealed class InspectorMessageAttribute : Attribute; + +public static class PathExtensions +{ + public static string Normalize(this string path) => path.Replace('\\', '/'); +} + +public abstract class EditorDrop; +``` + +Avoid: + +```csharp +public sealed class InspectorMessage : Attribute; + +public static class PathHelpers +{ + public static string Normalize(this string path) => path.Replace('\\', '/'); +} + +public abstract class EditorDropBase; +``` + +## NM-02 Interfaces and type parameters + +An interface name starts with `I`. No other type starts with `I` followed by an upper-case letter. Use `T` when there is a single, obvious type parameter; otherwise use `T` plus a description. + +```csharp +public interface IAssetImporter + where TAsset : class +{ + TAsset Import(string path); +} + +public sealed class Pool; +``` + +Avoid: + +```csharp +public interface AssetImporter + where Asset : class +{ + Asset Import(string path); +} +``` + +## NM-03 Method names + +A method name is PascalCase and starts with a verb. These prefixes have fixed meanings: + +- `Try*` returns `bool`, does not throw on failure and returns its result through an `out` parameter. +- `Is*`, `Has*` and `Can*` return `bool` and have no side effects. +- `Create*` builds a new object that the caller owns. +- `Get*` reads existing state without side effects. +- `*Async` returns `Task` or `ValueTask` (NM-04). + +```csharp +public bool TryResolve( + AssetID id, + out AssetHandle handle +) => m_handles.TryGetValue(id, out handle); +``` + +Avoid (`Try*` that does not return `bool`): + +```csharp +public AssetHandle? TryResolve(AssetID id) => m_handles.GetValueOrDefault(id); +``` + +## NM-04 Asynchronous methods end with `Async` + +A method that returns `Task`, `Task`, `ValueTask` or `ValueTask` ends with `Async`. Overrides and interface implementations follow their contract. xUnit test methods do not take the suffix. + +```csharp +public async Task CompileAsync( + ShaderSource source, + CancellationToken cancellationToken +) { + ShaderProgram program = await m_frontend.ParseAsync(source, cancellationToken).ConfigureAwait(false); + return await m_backend.EmitAsync(program, cancellationToken).ConfigureAwait(false); +} +``` + +Avoid: + +```csharp +public async Task Compile( + ShaderSource source, + CancellationToken cancellationToken +) { + ShaderProgram program = await m_frontend.ParseAsync(source, cancellationToken).ConfigureAwait(false); + return await m_backend.EmitAsync(program, cancellationToken).ConfigureAwait(false); +} +``` + +## NM-05 Properties and indexers are camelCase + +Every property is camelCase, whatever its accessibility. A `bool` property starts with `is`, `has` or `can`, or is a past participle that states a condition, such as `disposed`. + +```csharp +public Transform transform { get; } +public bool isMissing => m_source is null; +public int count { get; private set; } +``` + +Avoid: + +```csharp +public Transform Transform { get; } +public bool Missing => m_source is null; +public int Count { get; private set; } +``` + +## NM-06 Instance fields + +- A private or protected instance field is `m_` + camelCase, whether or not it is `readonly`. +- An internal or public instance field is camelCase without a prefix. Such fields appear only in frame-local workspaces, interop structs and math types. +- One declaration declares one field. + +```csharp +public sealed class RenderQueue +{ + private readonly List m_items = []; + private int m_generation; +} + +internal struct GlyphVertex +{ + public Vector2 position; + public Vector2 uv; +} +``` + +Avoid: + +```csharp +public sealed class RenderQueue +{ + private readonly List _items = []; + private int generation, frameIndex; +} +``` + +## NM-07 Constants + +Every `const` is `C_` + UPPER_SNAKE: private, internal and public constants, and constants local to a method. + +```csharp +public sealed class SceneFile +{ + public const string C_DEFAULT_EXTENSION = ".iscene"; + private const int C_MAX_COUNT = 64; + + public void Flush() + { + const int C_BATCH_SIZE = 256; + Write(C_BATCH_SIZE); + } +} +``` + +Avoid: + +```csharp +public sealed class SceneFile +{ + public const string DefaultExtension = ".iscene"; + private const int MAX_COUNT = 64; + + public void Flush() + { + const int batchSize = 256; + Write(batchSize); + } +} +``` + +## NM-08 `static readonly` fields + +Every `static readonly` field is UPPER_SNAKE without any prefix, whatever its accessibility. The `C_` prefix is reserved for `const`. + +```csharp +public readonly struct Color +{ + public static readonly Color RED = FromBytes(255, 0, 0); + private static readonly JsonSerializerOptions SERIALIZER_OPTIONS = new(JsonSerializerDefaults.Web); +} +``` + +Avoid: + +```csharp +public readonly struct Color +{ + public static readonly Color Red = FromBytes(255, 0, 0); + private static readonly JsonSerializerOptions S_SERIALIZER_OPTIONS = new(); + private static readonly JsonSerializerOptions s_serializerOptions = new(); + private static readonly JsonSerializerOptions C_SERIALIZER_OPTIONS = new(); +} +``` + +## NM-09 Static mutable fields + +A private static mutable field is `s_` + camelCase. Product code does not declare non-private static mutable fields; shared process state belongs to an explicit host. + +```csharp +public sealed class HandleAllocator +{ + private static int s_nextID; +} +``` + +Avoid: + +```csharp +public sealed class HandleAllocator +{ + private static int m_nextID; + public static int nextID; +} +``` + +## NM-10 Events + +An event is camelCase, like a property. Name it with a past participle or as `xxxChanged` / `xxxRequested`. Its delegate type is a nullable `Action` or `Action<...>`. + +```csharp +public event Action? redrawRequested; +public event Action? assetReloaded; +``` + +Avoid: + +```csharp +public event Action? RedrawRequested; +public event EventHandler? OnRedraw; +``` + +## NM-11 Enums + +- A single-value enum has a singular name. A `[Flags]` enum has a plural name or ends with `Flags`. +- Members are PascalCase and never start with an underscore. +- `[Flags]` values are written as `1 << n`, with `None = 0`. Combined values are expressed with member names. +- One member per line, no trailing comma, no blank lines between members. + +```csharp +public enum EditorPlayModeState +{ + Editing, + Compiling, + Playing +} + +[Flags] +public enum EditorViewportNavigationCapabilities +{ + None = 0, + Orbit = 1 << 0, + Pan = 1 << 1, + Zoom = 1 << 2, + All = Orbit | Pan | Zoom +} +``` + +Avoid: + +```csharp +[Flags] +public enum EditorViewportNavigationCapability +{ + None = 0, + Orbit = 1, + Pan = 0x2, + Zoom = 4, +} +``` + +## NM-12 Parameters, local variables and tuple elements + +Use camelCase and whole words. Do not use Hungarian prefixes. Do not give a local variable or a parameter the name of a property of the same type, except for constructor parameters (E-08). + +| Situation | Name | +| --- | --- | +| `CancellationToken` parameter | `cancellationToken` | +| Default `catch` variable | `exception` | +| Unused lambda parameter | `_` | +| Loop index | `i`, `j`, `index` | +| Coordinate or component | `x`, `y`, `z`, `w` | + +Apart from this table, do not use one- or two-character names. `id` and `io` are whole words and are allowed. + +```csharp +public async Task SaveAsync( + Stream destination, + CancellationToken cancellationToken +) { + (int width, int height) size = Measure(); + foreach (AssetEntry entry in m_entries) + { + await entry.WriteAsync(destination, size, cancellationToken).ConfigureAwait(false); + } +} +``` + +Avoid: + +```csharp +public async Task SaveAsync( + Stream dst, + CancellationToken token +) { + (int Width, int Height) sz = Measure(); + foreach (AssetEntry e in m_entries) + { + await e.WriteAsync(dst, sz, token).ConfigureAwait(false); + } +} +``` + +## NM-13 Acronyms + +- A two-letter acronym is upper case wherever a PascalCase word would start: `ID`, `IO`, `UI`. This includes `ID`: write `AssetID`, `persistentID`, `GetID`, never `AssetId`. +- An acronym of three or more letters is written as an ordinary word: `Json`, `Http`, `Ktx`, `Sdl`. +- When an acronym starts a camelCase identifier, the whole acronym is lower case: `id`, `ioStatus`, `uiScale`. +- In UPPER_SNAKE names every word is upper case: `C_MAX_ID`. + +```csharp +public sealed class JsonAssetWriter +{ + public AssetID persistentID { get; } + public IOStatus ioStatus { get; } + public float uiScale { get; set; } + + public AssetID GetID(string id) => m_ids[id]; +} +``` + +Avoid: + +```csharp +public sealed class JSONAssetWriter +{ + public AssetId persistentId { get; } + public IoStatus IOStatus { get; } + public float UIScale { get; set; } + + public AssetId GetId(string ID) => m_ids[ID]; +} +``` diff --git a/.agents/rulebook/csharp-style/04-types.md b/.agents/rulebook/csharp-style/04-types.md new file mode 100644 index 000000000..c5cea11a2 --- /dev/null +++ b/.agents/rulebook/csharp-style/04-types.md @@ -0,0 +1,234 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 4. Type declarations + +## T-01 Write every access modifier + +Every type and every member states its accessibility, including each file of a `partial` type. Interface members do not write `public`. + +```csharp +internal sealed partial class AssetLoader +{ + private int m_generation; +} + +public interface IEventSink +{ + void Publish(EventRecord record); +} +``` + +Avoid: + +```csharp +sealed partial class AssetLoader +{ + int m_generation; +} +``` + +## T-02 Modifier order + +Accessibility, then `static`, `extern`, `new`, then `virtual` / `abstract` / `sealed` / `override`, then `readonly`, `unsafe`, `required`, `volatile`, `async`, `partial`. + +```csharp +public static readonly Color RED = FromBytes(255, 0, 0); + +private static async Task RunAsync() +{ + await Task.Yield(); + Publish(); +} + +public sealed override string ToString() => name; + +public override readonly int GetHashCode() => m_value; + +internal static unsafe partial class NativeMethods; +``` + +Avoid: + +```csharp +public readonly override int GetHashCode() => m_value; + +static private int s_count; +``` + +## T-03 Classes are sealed by default + +Every class is `static`, `abstract` or `sealed`. Leave a class open only when it is a designed extension point, and document the derivation contract in its XML documentation. Nested private classes are sealed too. + +```csharp +public sealed class EventDispatcher; + +internal static class PathUtility +{ + internal static string Normalize(string path) => path.Replace('\\', '/'); +} + +public abstract class EditorDrop; +``` + +Avoid: + +```csharp +public class EventDispatcher; +``` + +## T-04 Records + +- A reference-type data contract is a `sealed record` with positional parameters, ending in `;`. +- A small value type is a `readonly record struct`. +- Positional parameters are properties, so they are camelCase. + +```csharp +public sealed record AssetChangedEvent( + string path, + WatcherChangeTypes change +); + +public readonly record struct AssetID(Guid value); +``` + +Avoid: + +```csharp +public record AssetChangedEvent(string Path, WatcherChangeTypes Change); + +public record struct AssetID(Guid value); +``` + +## T-05 Structs + +A struct is `readonly` by default. Use a mutable struct only for interop layouts and math types that are assigned field by field; its fields are public and camelCase. + +```csharp +public readonly struct FrameRange +{ + public int start { get; } + public int count { get; } +} + +[StructLayout(LayoutKind.Sequential)] +internal struct GlyphVertex +{ + public Vector2 position; + public Vector2 uv; +} +``` + +Avoid (a mutable struct that is not an interop or math type): + +```csharp +public struct FrameRange +{ + public int start { get; set; } + public int count { get; set; } +} +``` + +## T-06 Base lists and generic constraints on types + +- The base list stays on the line of the type name. +- Each `where` clause of a type is on its own line, indented four spaces. The opening brace stays on its own line. + +```csharp +public abstract class EditorDrop : EditorDrop + where TSource : IdentityObject + where TTarget : class +{ + public abstract bool Accepts(TSource source); +} +``` + +Avoid: + +```csharp +public abstract class EditorDrop + : EditorDrop where TSource : IdentityObject where TTarget : class +{ + public abstract bool Accepts(TSource source); +} +``` + +## T-07 Primary constructors + +- A record always uses a primary constructor. +- A class or struct may use a primary constructor to receive its dependencies. When it does, it uses the parameters directly and does not copy them into `m_` fields. +- Use an ordinary constructor with `m_` fields when arguments need validation or the fields must be `readonly`. +- Primary constructor parameters follow P-01. A base list follows the closing parenthesis as `) : Base`, with the opening brace on its own line. Without a base list the type body starts with `) {`. + +```csharp +internal sealed class TogglePlayModeAction(EditorPlayMode playMode) : EditorAction +{ + protected override bool CanExecute() => playMode.state != EditorPlayModeState.Compiling; +} + +internal sealed class SceneReloadChange( + RuntimeSession runtimeSession, + ISceneReloadStateTransfer migration +) : IGenerationChange +{ + public void Apply() => migration.Transfer(runtimeSession); +} + +internal sealed class FrameScope( + RenderGraph graph, + int frameIndex +) { + public bool isFirst => frameIndex == 0; + + public void Begin() => graph.BeginFrame(frameIndex); +} +``` + +Avoid (base list on a separate line, parameters copied into fields): + +```csharp +internal sealed class SceneReloadChange( + RuntimeSession runtimeSession, + ISceneReloadStateTransfer migration +) + : IGenerationChange +{ + private readonly RuntimeSession m_runtimeSession = runtimeSession; + private readonly ISceneReloadStateTransfer m_migration = migration; +} +``` + +## T-08 Nested types + +A nested type is placed at the end of its containing type. Nest a type only when the containing type is its only user. + +```csharp +public sealed class AssetCache +{ + private readonly Dictionary m_entries = []; + + public int count => m_entries.Count; + + private sealed class Entry + { + public AssetHandle handle { get; init; } + public int generation { get; set; } + } +} +``` + +Avoid (the nested type comes first): + +```csharp +public sealed class AssetCache +{ + private sealed class Entry + { + public AssetHandle handle { get; init; } + public int generation { get; set; } + } + + private readonly Dictionary m_entries = []; +} +``` diff --git a/.agents/rulebook/csharp-style/05-members.md b/.agents/rulebook/csharp-style/05-members.md new file mode 100644 index 000000000..47021a8b5 --- /dev/null +++ b/.agents/rulebook/csharp-style/05-members.md @@ -0,0 +1,192 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 5. Member declarations + +## M-01 Property forms + +- An auto-property is written on one line: `{ get; }`, `{ get; set; }`, `{ get; init; }`, `{ get; private set; }`. +- A read-only computed property uses an expression body. +- A property whose accessors contain logic is expanded: the braces are on their own lines, an accessor with a single expression uses `=>`, an accessor with statements uses a block. + +```csharp +public string name { get; } +public int count { get; private set; } +public bool isEmpty => m_items.Count == 0; + +public float scale +{ + get => m_scale; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + m_scale = value; + } +} +``` + +Avoid: + +```csharp +public bool isEmpty { get { return m_items.Count == 0; } } +public float scale { get => m_scale; set => m_scale = value; } +``` + +## M-02 Expression-bodied members + +- A method, property, indexer or operator whose body is one expression (one `return`, one call or one assignment) uses an expression body. +- A body with control flow, several statements or `try` uses a block. +- A constructor always uses a block body. + +```csharp +public override string ToString() => $"{name} ({count})"; + +public static bool operator ==( + Color left, + Color right +) => left.Equals(right); + +public RenderQueue(int capacity) +{ + m_items = new List(capacity); +} +``` + +Avoid: + +```csharp +public override string ToString() +{ + return $"{name} ({count})"; +} + +public RenderQueue(int capacity) => m_items = new List(capacity); +``` + +## M-03 Placement of `=>` in expression-bodied members + +1. When the whole member fits on one line, `=> expression` stays on the declaration line. +2. After a multi-line parameter list, the body starts on the line of the closing parenthesis: `) => expression`. When the expression is a call, an object creation or a collection that does not fit, break inside it (A-02). +3. When the signature is on one line and the body does not fit after it, move `=>` to the next line, indented four spaces. +4. After a wrapped `=>`, a brace-delimited expression (a `switch` expression, an object initializer or a `with` expression) puts its braces on their own lines at the column of the declaration, with its contents indented four spaces from the declaration. +5. After a wrapped `=>`, a call or object creation that must break follows A-02 relative to the `=>` line, and operator continuation lines align with the first operand (F-05). +6. `=>` never ends a line with the expression on the next line, and never stands alone on a line. + +```csharp +public bool isMissing => m_source is null; + +public static Color FromBytes( + byte r, + byte g, + byte b +) => new(r / 255f, g / 255f, b / 255f); + +public static Color Lerp( + Color from, + Color to, + float amount +) => new( + from.r + (to.r - from.r) * amount, + from.g + (to.g - from.g) * amount, + from.b + (to.b - from.b) * amount +); + +protected override EditorActionState Query(EditorActionContext context) + => playMode.state switch +{ + EditorPlayModeState.Editing => new EditorActionState(true, true), + EditorPlayModeState.Playing => new EditorActionState(true, false), + _ => EditorActionState.DISABLED +}; + +internal bool IsActiveFor(object? target) + => m_isActive + && m_activeTarget is not null + && m_activeTarget.Matches(m_activeInteractions, target); + +protected override EditorActionState Describe(EditorActionContext context) + => new EditorActionState( + isVisible: context.selection.count > 0, + isEnabled: playMode.state == EditorPlayModeState.Editing, + displayName: "Duplicate Selection" + ); +``` + +Avoid (`=>` left at the end of the line, braces indented under the wrapped `=>`, closing parenthesis left on the last argument): + +```csharp +protected override EditorActionState Query(EditorActionContext context) => + playMode.state switch + { + EditorPlayModeState.Editing => new EditorActionState(true, true), + _ => EditorActionState.DISABLED + }; + +public static Color Lerp( + Color from, + Color to, + float amount +) + => new( + from.r + (to.r - from.r) * amount, + from.g + (to.g - from.g) * amount, + from.b + (to.b - from.b) * amount); +``` + +## M-04 Field and property initializers + +- A field or property initializer uses a target-typed expression so the type is written once: `= new(...)` or `= []`. +- One declaration declares one field or one local variable. + +```csharp +private readonly Dictionary m_commands = new(StringComparer.Ordinal); +private readonly List m_items = []; + +public IReadOnlyList tags { get; init; } = []; +``` + +Avoid: + +```csharp +private readonly Dictionary m_commands = new Dictionary(StringComparer.Ordinal); +private readonly List m_items = new List(); +``` + +## M-05 Attributes + +- Each attribute is on its own line above the declaration. One pair of brackets holds one attribute. +- Omit the `Attribute` suffix. Omit empty parentheses. +- An attribute on a parameter stays on the line of the parameter. +- Attribute arguments break like any other argument list (A-02). + +```csharp +[Fact] +[Trait("Category", "Lifecycle")] +public void DisposeIsIdempotent() +{ + m_queue.Dispose(); + m_queue.Dispose(); +} + +[SerializableProperty] +public float speed { get; set; } + +public bool TryRead( + string key, + [NotNullWhen(true)] out string? value +) => m_values.TryGetValue(key, out value); +``` + +Avoid: + +```csharp +[Fact, Trait("Category", "Lifecycle")] +public void DisposeIsIdempotent() +{ + m_queue.Dispose(); + m_queue.Dispose(); +} + +[SerializableProperty()] public float speed { get; set; } +``` diff --git a/.agents/rulebook/csharp-style/06-member-order.md b/.agents/rulebook/csharp-style/06-member-order.md new file mode 100644 index 000000000..b217ccccc --- /dev/null +++ b/.agents/rulebook/csharp-style/06-member-order.md @@ -0,0 +1,123 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, members] +--- +# 6. Member order + +## O-01 Group order + +Members of a type appear in these groups, in this order, with one blank line between groups: + +1. Constants (`const`). +2. Static fields: `static readonly` first, then static mutable. +3. Instance fields: `readonly` first, then mutable. +4. Constructors. +5. Public members. +6. Protected and internal members. +7. Private members. +8. Nested types. + +Inside groups 5, 6 and 7 the order is: properties, events, instance methods, static methods. An explicit interface implementation follows the public members of the interface it implements. + +```csharp +public sealed class RenderQueue : IDisposable +{ + private const int C_INITIAL_CAPACITY = 64; + + private static readonly RenderItemComparer COMPARER = new(); + + private readonly List m_items; + private bool m_disposed; + + public RenderQueue() + { + m_items = new List(C_INITIAL_CAPACITY); + } + + public int count => m_items.Count; + + public event Action? flushed; + + public void Enqueue(RenderItem item) + { + ObjectDisposedException.ThrowIf(m_disposed, this); + m_items.Add(item); + } + + public void Dispose() + { + m_items.Clear(); + m_disposed = true; + } + + internal void Sort() => m_items.Sort(COMPARER); + + private void NotifyFlushed() => flushed?.Invoke(); + + private sealed class RenderItemComparer : IComparer + { + public int Compare( + RenderItem left, + RenderItem right + ) => left.order.CompareTo(right.order); + } +} +``` + +Avoid (a private method before the public members, fields after the constructor): + +```csharp +public sealed class RenderQueue +{ + public RenderQueue() + { + m_items = new List(C_INITIAL_CAPACITY); + } + + private void NotifyFlushed() => flushed?.Invoke(); + + private readonly List m_items; + + public int count => m_items.Count; + + private const int C_INITIAL_CAPACITY = 64; +} +``` + +## O-02 Keep related members together + +Members of the same accessibility and kind are contiguous. Overloads are adjacent and ordered from fewest to most parameters. + +```csharp +public void Draw(Mesh mesh) => Draw(mesh, m_defaultMaterial); + +public void Draw( + Mesh mesh, + Material material +) { + Submit(new RenderItem(mesh, material)); + m_drawn++; +} + +public void Clear() => m_items.Clear(); + +private void Submit(RenderItem item) => m_items.Add(item); +``` + +Avoid (overloads separated, a private method between public methods): + +```csharp +public void Draw(Mesh mesh) => Draw(mesh, m_defaultMaterial); + +private void Submit(RenderItem item) => m_items.Add(item); + +public void Clear() => m_items.Clear(); + +public void Draw( + Mesh mesh, + Material material +) { + Submit(new RenderItem(mesh, material)); + m_drawn++; +} +``` diff --git a/.agents/rulebook/csharp-style/07-braces.md b/.agents/rulebook/csharp-style/07-braces.md new file mode 100644 index 000000000..b0a39f07e --- /dev/null +++ b/.agents/rulebook/csharp-style/07-braces.md @@ -0,0 +1,396 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 7. Braces and blocks + +## B-01 Braces are on their own lines + +The opening brace of a type, a method body, an accessor, a control statement, a lambda block, an object or collection initializer and a `switch` expression is on its own line, aligned with the start of the construct. The closing brace is on its own line, aligned with the opening brace. + +The only places where an opening brace shares a line with other code are: + +- `) {` after a multi-line parameter list or a multi-line statement header (B-02). +- A single-line construct: an auto-property, a short initializer, a property pattern, a compact guard (B-05). +- An empty body `{}` (B-07). + +```csharp +public void Flush() +{ + foreach (RenderItem item in m_items) + { + Draw(item); + m_drawn++; + } + + try + { + Present(); + } + catch (DeviceLostException exception) + { + m_log.Error(exception.Message); + throw; + } + finally + { + m_items.Clear(); + } +} +``` + +Avoid: + +```csharp +public void Flush() { + foreach (RenderItem item in m_items) { + Draw(item); + } + + try { Present(); } + catch (DeviceLostException) { throw; } + finally { m_items.Clear(); } +} +``` + +## B-02 `) {` after a multi-line parameter list or statement header + +When a parameter list is expanded over several lines (P-01) and the body follows it directly, the opening brace shares the line of the closing parenthesis: `) {`. The closing brace aligns with the start of the declaration. This applies to methods, constructors, local functions, operators and primary constructors without a base list. The same form closes a control statement whose header spans several lines (W-05). + +```csharp +internal void Register( + string commandID, + Action command +) { + ArgumentException.ThrowIfNullOrWhiteSpace(commandID); + ArgumentNullException.ThrowIfNull(command); + m_commands.Add(commandID, command); +} +``` + +Avoid (brace on its own line after a multi-line parameter list, several parameters on one line): + +```csharp +internal void Register( + string commandID, + Action command +) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +internal void Unregister(string commandID, Action command) +{ + m_commands.Remove(commandID); + m_dirty = true; +} +``` + +## B-03 Clauses between `)` and the body + +A constructor initializer (`: base(...)`, `: this(...)`) or a `where` clause sits between the parameter list and the body. + +- After a multi-line parameter list, the clause follows the closing parenthesis on the same line: `) : this(...)` or `) where T : class`. The opening brace is then on its own line. +- After a single-line signature, the clause is on the next line, indented four spaces. The opening brace is on its own line. +- Additional `where` clauses each take their own line, aligned with the first `where`. + +```csharp +public InspectorMessageAttribute( + string text, + InspectorMessageType messageType +) : this(text, messageType, string.Empty) +{ + this.isExpanded = true; +} + +public InspectorMessageAttribute(string text) + : this(text, InspectorMessageType.Info) +{ + this.isExpanded = false; +} + +public T Resolve( + string id, + bool required +) where T : class +{ + object resolved = ResolveCore(typeof(T), id, required); + return (T)resolved; +} + +public TTarget Convert( + TSource source, + bool required +) where TSource : IdentityObject + where TTarget : class +{ + object converted = ConvertCore(source, typeof(TTarget), required); + return (TTarget)converted; +} + +public T Find(string id) + where T : class +{ + object found = FindCore(typeof(T), id); + return (T)found; +} +``` + +Avoid (clause on its own line after a multi-line parameter list, clause on the signature line of a single-line signature, `) {` after a clause): + +```csharp +public InspectorMessageAttribute( + string text, + InspectorMessageType messageType +) + : this(text, messageType, string.Empty) +{ + this.isExpanded = true; +} + +public InspectorMessageAttribute(string text) : this(text, InspectorMessageType.Info) +{ + this.isExpanded = false; +} + +public T Resolve( + string id, + bool required +) where T : class { + object resolved = ResolveCore(typeof(T), id, required); + return (T)resolved; +} +``` + +## B-04 Lambda bodies + +- **Expression body that fits:** `x => expression` on one line. +- **Block body:** `=>` ends the line; the braces are on their own lines, aligned with the start of the statement that contains the lambda. The closing brace is followed directly by `)`, `,` or `;`. This holds when the lambda has a multi-line parameter list too: `) =>`, then the brace on the next line. +- **Expression body that is a call or object creation and does not fit:** the call starts on the `=>` line and breaks inside its parentheses (A-02). +- **Any other expression body that does not fit:** wrap it in parentheses. `(` follows `=>`, the expression is indented four spaces, and `)` is on its own line. + +```csharp +m_dispatcher.Subscribe(entry => +{ + m_pending.Add(entry); + m_dirty = true; +}); + +entries.Sort(( + left, + right +) => +{ + int byName = string.CompareOrdinal(left.name, right.name); + return byName != 0 ? byName : left.order.CompareTo(right.order); +}); + +IEnumerable blended = pairs.Select(pair => new Color( + pair.from.r + (pair.to.r - pair.from.r) * amount, + pair.from.g + (pair.to.g - pair.from.g) * amount, + pair.from.b + (pair.to.b - pair.from.b) * amount +)); + +Func isStale = entry => ( + entry.lastWriteTimeUtc < threshold && !entry.isPinned +); +``` + +Avoid (brace on the `=>` line, block squeezed onto one line, expression body moved to the next line without parentheses): + +```csharp +m_dispatcher.Subscribe(entry => { + m_pending.Add(entry); + m_dirty = true; +}); + +m_dispatcher.Subscribe(entry => { m_pending.Add(entry); m_dirty = true; }); + +Func isStale = entry => + entry.lastWriteTimeUtc < threshold && !entry.isPinned; +``` + +## B-05 Control statement bodies always use braces + +1. The body of `if`, `else`, `for`, `foreach`, `while`, `do`, `using`, `lock` and `fixed` is always enclosed in braces, each brace on its own line. +2. One compact form is permitted where it reads better: an `if` without `else` whose body is a single short statement may be written entirely on one line, `if (condition) statement;`. Use it for guard clauses and keep a run of adjacent guards in the same form. +3. A body on the next line without braces is never allowed. +4. Stacked `using` or `fixed` headers that share one braced body are the only headers that may follow each other without braces in between. + +```csharp +if (m_disposed) +{ + return; +} + +while (reader.Read()) +{ + Process(reader.current); +} + +foreach (RenderItem item in m_items) +{ + if (item is null) continue; + if (!item.isVisible) continue; + + Draw(item); +} + +fixed (byte* source = input) +fixed (byte* target = output) +{ + Copy(source, target, length); +} +``` + +Avoid: + +```csharp +if (m_disposed) + return; + +foreach (RenderItem item in m_items) + Draw(item); + +foreach (AssetEntry entry in m_entries) + if (entry.isMissing) + missing.Add(entry); + +foreach (RenderItem item in m_items) Draw(item); +``` + +## B-06 `if` / `else` chains + +Every branch of an `if … else if … else` chain uses braces. The compact one-line form (B-05) is not used when the `if` has an `else`. + +```csharp +if (state == EditorPlayModeState.Editing) +{ + EnterPlayMode(); +} +else if (state == EditorPlayModeState.Playing) +{ + ExitPlayMode(); +} +else +{ + m_log.Warning("Play mode is changing."); +} +``` + +Avoid: + +```csharp +if (state == EditorPlayModeState.Editing) EnterPlayMode(); +else ExitPlayMode(); + +if (state == EditorPlayModeState.Editing) + EnterPlayMode(); +else +{ + m_log.Warning("Play mode is already active."); + ExitPlayMode(); +} +``` + +## B-07 Empty bodies + +- An empty type ends with a semicolon and has no braces. +- An empty method, constructor, accessor, local function or lambda body is `{}`, with no space inside, on the line where the header ends. +- An empty `catch` block is not empty: it contains a comment that explains why the exception is ignored (X-04). +- A property pattern that matches any non-null value is written `{ }`. + +```csharp +public sealed class EmptyPayload; + +public interface IMarker; + +protected virtual void OnActivated() {} + +public NullSink( + string name, + int capacity +) {} + +public NamedSink(string name) + : base(name) {} +``` + +Inside a method: + +```csharp +Action noop = () => {}; + +if (value is { } resolved) +{ + Use(resolved); +} +``` + +Avoid: + +```csharp +public sealed class EmptyPayload +{ +} + +public sealed class OtherPayload { } + +protected virtual void OnActivated() +{ +} + +protected virtual void OnDeactivated() { } +``` + +## B-08 `else`, `catch`, `finally` and `while` + +`else`, `catch` and `finally` start a new line after the closing brace. The `while` of a `do … while` loop starts a new line too. + +```csharp +do +{ + read = stream.Read(buffer); + total += read; +} +while (read > 0); +``` + +Avoid: + +```csharp +do +{ + read = stream.Read(buffer); + total += read; +} while (read > 0); +``` + +## B-09 One statement per line + +A line holds one statement. The statement after a `case` label starts on the next line. Nothing follows an opening brace on its line. The compact guard of B-05 is the only construct in which a statement shares the line of its header. + +```csharp +switch (key) +{ + case KeyCode.Left: + cursor--; + break; + case KeyCode.Right: + cursor++; + break; +} +``` + +Avoid: + +```csharp +switch (key) +{ + case KeyCode.Left: cursor--; break; + case KeyCode.Right: cursor++; break; +} + +x = 0; y = 0; +``` diff --git a/.agents/rulebook/csharp-style/08-parameters.md b/.agents/rulebook/csharp-style/08-parameters.md new file mode 100644 index 000000000..80fc8736c --- /dev/null +++ b/.agents/rulebook/csharp-style/08-parameters.md @@ -0,0 +1,293 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 8. Parameter and argument lists + +## P-01 Parameter lists: one line for zero or one parameter, fully expanded for two or more + +A declaration with two or more parameters breaks after the opening parenthesis, puts each parameter on its own line indented four spaces, and puts the closing parenthesis on its own line aligned with the start of the declaration. A declaration with zero or one parameter stays on one line. + +This applies to methods, constructors, local functions, delegates, operators, primary constructors and lambdas. + +```csharp +public void Clear() => m_commands.Clear(); + +public void Remove(string commandID) => m_commands.Remove(commandID); + +public void Register( + string commandID, + Action command +) { + m_commands.Add(commandID, command); + m_dirty = true; +} + +public delegate void AssetCallback( + AssetID id, + AssetHandle handle +); +``` + +Local functions and lambdas follow the same rule: + +```csharp +void Visit( + Node node, + int depth +) { + m_visited.Add(node); + m_depths[node] = depth; +} + +bool duplicate = updated.Where(( + _, + candidateIndex +) => candidateIndex != index).Any(); +``` + +Avoid: + +```csharp +public void Register(string commandID, Action command) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +public void Register(string commandID, + Action command) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +public void Register( + string commandID, + Action command) +{ + m_commands.Add(commandID, command); + m_dirty = true; +} + +bool duplicate = updated.Where((_, candidateIndex) => candidateIndex != index).Any(); +``` + +## P-02 What follows the closing parenthesis of a multi-line parameter list + +| Followed by | Form | +| --- | --- | +| Block body | `) {` | +| Empty body | `) {}` | +| Expression body | `) => expression;` — when the expression must break, it breaks inside its own delimiters: `) => new(` … `);` | +| No body (interface, abstract, delegate, record) | `);` | +| Constructor initializer | `) : base(...)` or `) : this(...)`, opening brace on its own line | +| `where` clause | `) where T : class`, opening brace on its own line | +| Base list of a primary constructor | `) : Base`, opening brace on its own line | +| Lambda body | `) =>`, then the expression, or the opening brace on its own line | + +```csharp +public interface IAssetStore +{ + Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ); +} + +public sealed class NullAssetStore : IAssetStore +{ + public NullAssetStore( + string name, + int capacity + ) {} + + public Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ) => Task.FromResult(AssetHandle.MISSING); +} +``` + +Avoid: + +```csharp +public sealed class NullAssetStore : IAssetStore +{ + public Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ) + => Task.FromResult(AssetHandle.MISSING); +} +``` + +## P-03 Parameter details + +- A default value is written `= value`, with one space on each side of `=`. +- `this`, `ref`, `out`, `in` and `params` are separated from the type by one space. +- `CancellationToken cancellationToken` is always the last parameter. + +```csharp +public Task LoadAsync( + AssetID id, + bool required = true, + CancellationToken cancellationToken = default +) { + cancellationToken.ThrowIfCancellationRequested(); + return LoadCoreAsync(id, required, cancellationToken); +} +``` + +Avoid: + +```csharp +public Task LoadAsync( + CancellationToken cancellationToken, + AssetID id, + bool required=true +) { + cancellationToken.ThrowIfCancellationRequested(); + return LoadCoreAsync(id, required, cancellationToken); +} +``` + +## A-01 Argument lists stay on one line when they fit + +The arguments of a call, an object creation or a constructor initializer stay on one line whenever the whole statement fits within the line width. + +```csharp +m_commands.Add(commandID, command); +var buffer = new VertexBuffer(device, capacity, VertexLayout.DEFAULT); +``` + +Avoid (a short call broken for no reason): + +```csharp +m_commands.Add( + commandID, + command +); +``` + +## A-02 Broken argument lists: one argument per line, closing parenthesis on its own line + +When an argument list does not fit on one line: + +- The opening parenthesis ends its line. +- Each argument is on its own line, indented four spaces from the line that contains the opening parenthesis. +- The closing parenthesis is on its own line, aligned with the start of the line that contains the opening parenthesis. Whatever follows the call — `;`, `.Next(...)`, `,` or an outer closing delimiter — follows that parenthesis. +- Nested calls apply the same rule one level deeper. + +This holds for every call, including `new`, `throw new`, `await`, `return`, attribute arguments and constructor initializers. + +```csharp +return await m_textureCompiler.CompileKtxAsync( + encoded, + texture.slot.colorSpace, + cancellationToken +).ConfigureAwait(false); + +throw new ArgumentException( + $"The viewport '{viewport.name}' does not support mode '{defaultMode}'.", + nameof(defaultMode) +); + +var result = new ShaderCompilationResult( + null, + [new ShaderDiagnostic( + "SHADER_COMPILE_EXCEPTION", + DiagnosticSeverity.Error, + message + )] +); + +string intermediate = scoped.GetNativeBuildRoot( + componentDescriptor, + configuration, + targetArchitecture +); +``` + +Avoid (closing parenthesis left on the last argument, first argument left on the opening line, several arguments packed on a line, arguments aligned with the parenthesis): + +```csharp +return await m_textureCompiler.CompileKtxAsync( + encoded, + texture.slot.colorSpace, + cancellationToken).ConfigureAwait(false); + +return await m_textureCompiler.CompileKtxAsync(encoded, + texture.slot.colorSpace, cancellationToken).ConfigureAwait(false); + +throw new ArgumentException($"The viewport '{viewport.name}' does not support mode '{defaultMode}'.", + nameof(defaultMode)); +``` + +## A-03 Hugging a single multi-line argument + +When exactly one argument spans several lines, and that argument is a lambda, an object initializer, an anonymous object or a collection expression, the arguments may all start on the line of the opening parenthesis. The multi-line argument is laid out by its own rule, and the closing parenthesis follows its closing delimiter. + +When two or more arguments span several lines, expand the list (A-02). + +```csharp +m_dispatcher.Subscribe(entry => +{ + m_pending.Add(entry); + m_dirty = true; +}); + +Task task = Task.Run(() => +{ + Compile(source); + Publish(source); +}, cancellationToken); + +loader.ApplySourceChanges([ + new AssetEvent("Text/new.txt", WatcherChangeTypes.Deleted), + new AssetEvent("Text/old.txt", WatcherChangeTypes.Deleted) +]); + +scheduler.Schedule( + () => + { + Compile(source); + Publish(source); + }, + exception => + { + m_log.Error(exception.Message); + m_failed = true; + } +); +``` + +Avoid (two multi-line arguments hugged together): + +```csharp +scheduler.Schedule(() => +{ + Compile(source); + Publish(source); +}, exception => +{ + m_log.Error(exception.Message); + m_failed = true; +}); +``` + +## A-04 Named arguments + +A named argument is written `name: value`, with no space before the colon and one space after it. Name adjacent `bool` or numeric literal arguments whose meaning is not obvious from the call. + +```csharp +var state = new EditorActionState(true, true, displayName: "Enter Play Mode"); +window.Resize(width: 1280, height: 720); +``` + +Avoid: + +```csharp +window.Resize(width : 1280, height:720); +texture.Update(true, false, 0, 4); +``` diff --git a/.agents/rulebook/csharp-style/09-line-breaks.md b/.agents/rulebook/csharp-style/09-line-breaks.md new file mode 100644 index 000000000..753016f2e --- /dev/null +++ b/.agents/rulebook/csharp-style/09-line-breaks.md @@ -0,0 +1,142 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 9. Line breaks + +## W-01 Binary operators lead the continuation line + +When an expression breaks at `&&`, `||`, `??`, `+`, `-`, `|` or another binary operator, the operator starts the next line. Continuation lines align with the first operand (F-05). + +```csharp +bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format; + +string message = "The asset database could not be opened because " + + "another editor instance holds the workspace lock."; + +string name = entry.displayName + ?? entry.path.GetFileName() + ?? string.Empty; +``` + +Avoid: + +```csharp +bool changed = previous.width != current.width || + previous.height != current.height; +``` + +## W-02 Conditional expressions + +A conditional expression stays on one line when it fits. Otherwise `?` and `:` each start a line, aligned with the condition (F-05). Do not nest conditional expressions; use a `switch` expression or an `if` statement. + +```csharp +int order = byName != 0 ? byName : left.order.CompareTo(right.order); + +ShaderCompilationResult result = pending.IsCompletedSuccessfully + ? pending.Result + : new ShaderCompilationResult(null, diagnostics); +``` + +Avoid: + +```csharp +ShaderCompilationResult result = pending.IsCompletedSuccessfully ? + pending.Result : + new ShaderCompilationResult(null, diagnostics); + +string label = count == 0 ? "none" : count == 1 ? "one" : "many"; +``` + +## W-03 Call chains + +A call chain stays on one line when it fits. Otherwise the first link stays on the statement line and every following `.` (or `?.`) starts a line, indented four spaces from the start of the statement. + +```csharp +List names = m_entries + .Where(static entry => !entry.isMissing) + .Select(static entry => entry.displayName) + .OrderBy(static name => name, StringComparer.Ordinal) + .ToList(); +``` + +Avoid: + +```csharp +List names = m_entries.Where(static entry => !entry.isMissing). + Select(static entry => entry.displayName). + ToList(); +``` + +## W-04 Assignments and arrows + +- Never break a line directly before or after `=`. Keep the start of the right-hand side on the line of the `=` and break inside it: after an opening parenthesis (A-02), before an operator (W-01) or before a `.` (W-03). The only exception is the opening bracket of a multi-line collection expression, which takes its own line (I-03). +- A lambda `=>` always ends its line when the body moves down; the body then follows B-04. An expression body that is not a call is wrapped in parentheses. +- The `=>` of a `switch` expression arm stays on the line of the arm. +- The `=>` of an expression-bodied member follows M-03. + +```csharp +string intermediate = scoped.GetNativeBuildRoot( + componentDescriptor, + configuration, + targetArchitecture +); + +Func isStale = entry => ( + entry.lastWriteTimeUtc < threshold && !entry.isPinned +); +``` + +Avoid: + +```csharp +string intermediate = + scoped.GetNativeBuildRoot(componentDescriptor, configuration, targetArchitecture); + +Func isStale = entry => + entry.lastWriteTimeUtc < threshold && !entry.isPinned; +``` + +## W-05 Multi-line conditions and statement headers + +- `is` stays on the line of its left operand. `or` and `and` start their continuation lines. +- When the parenthesized header of `if`, `else if`, `while`, `for`, `foreach`, `switch`, `lock`, `using` or `fixed` spans several lines, its closing parenthesis is on its own line, aligned with the keyword, and the opening brace follows it: `) {`. This mirrors the multi-line parameter list (B-02). + +```csharp +if (token.kind is TokenKind.Comma + or TokenKind.Semicolon + or TokenKind.CloseBrace +) { + return; +} + +if (capabilities != EditorViewportNavigationCapabilities.None + && !SupportsMode(capabilities, defaultMode) +) { + throw new ArgumentException("The default mode is not supported.", nameof(defaultMode)); +} + +foreach (KeyValuePair dependency in HostDependencyManifest + .GetInnoRuntimeAssemblies(roots) + .OrderBy(static dependency => dependency.Key, StringComparer.OrdinalIgnoreCase) +) { + Enqueue(dependency.Key, dependency.Value); +} +``` + +Avoid: + +```csharp +if (token.kind is TokenKind.Comma + or TokenKind.Semicolon + or TokenKind.CloseBrace) +{ + return; +} + +if (capabilities != EditorViewportNavigationCapabilities.None + && !SupportsMode(capabilities, defaultMode)) + throw new ArgumentException("The default mode is not supported.", nameof(defaultMode)); +``` diff --git a/.agents/rulebook/csharp-style/10-initializers.md b/.agents/rulebook/csharp-style/10-initializers.md new file mode 100644 index 000000000..0f23ac963 --- /dev/null +++ b/.agents/rulebook/csharp-style/10-initializers.md @@ -0,0 +1,150 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 10. Initializers and collections + +## I-01 Object initializers + +- A short initializer stays on one line with one space inside each brace: `new Foo { a = 1 }`. +- Otherwise the opening brace is on its own line, aligned with the start of the statement; each member is on its own line, indented four spaces; the closing brace is on its own line. +- Omit the empty `()` when an initializer is present. +- `with` expressions and anonymous objects follow the same rule. + +```csharp +var options = new JsonSerializerOptions { WriteIndented = true }; + +var request = new GameBuildRequest +{ + profile = profile, + outputDirectory = outputDirectory, + configuration = BuildConfiguration.Release +}; + +RenderSettings updated = settings with +{ + exposure = 1.5f, + toneMapping = ToneMapping.Aces +}; +``` + +Avoid: + +```csharp +var request = new GameBuildRequest() { + profile = profile, outputDirectory = outputDirectory, + configuration = BuildConfiguration.Release, +}; +``` + +## I-02 Collections use collection expressions + +- Arrays, `List`, spans and immutable collections are written as collection expressions: `[a, b]`, `[]`, `[.. source]`. +- A spread operator is followed by one space: `[.. source, extra]`. +- Use `new T(...)` when a constructor argument (a capacity, a comparer) is needed, and `new T[n]` for a fixed-size buffer. +- Do not write `new[] { ... }`, `new T[] { ... }`, `new List { ... }` or `Array.Empty()`. + +```csharp +List items = []; +string[] extensions = [".png", ".jpg", ".ktx"]; +List all = [.. builtIn, .. custom, "fallback"]; +var byName = new Dictionary(StringComparer.Ordinal); +var buffer = new byte[C_BUFFER_SIZE]; +``` + +Avoid: + +```csharp +List items = new List(); +string[] extensions = new[] { ".png", ".jpg", ".ktx" }; +List all = [..builtIn, ..custom, "fallback"]; +string[] none = Array.Empty(); +``` + +## I-03 Multi-line collection expressions + +- With two or more elements that do not fit on one line: one element per line, indented four spaces, and the closing bracket on its own line. +- As the value of a declaration or assignment, the opening bracket is on its own line, aligned with the start of the statement, like the brace of an object initializer. +- As an argument, the opening bracket follows the opening parenthesis or the preceding argument (A-03). +- A single element that itself spans several lines hugs the brackets: `[new X(` … `)]`. + +```csharp +string[] searchPaths = +[ + Path.Combine(root, "Assets"), + Path.Combine(root, "Packages"), + Path.Combine(root, "Library", "Imported") +]; + +loader.ApplySourceChanges([ + new AssetEvent("Text/new.txt", WatcherChangeTypes.Deleted), + new AssetEvent("Text/old.txt", WatcherChangeTypes.Deleted) +]); + +return new ShaderCompilationResult( + null, + [new ShaderDiagnostic( + "SHADER_COMPILE_EXCEPTION", + DiagnosticSeverity.Error, + message + )] +); +``` + +Avoid: + +```csharp +string[] searchPaths = [Path.Combine(root, "Assets"), + Path.Combine(root, "Packages"), Path.Combine(root, "Library", "Imported")]; + +return new ShaderCompilationResult( + null, + [new ShaderDiagnostic( + "SHADER_COMPILE_EXCEPTION", + DiagnosticSeverity.Error, + message)]); +``` + +## I-04 `switch` expressions + +`value switch` is on one line; the opening brace is on its own line; each arm is on its own line with its `=>`; the discard arm is last. + +```csharp +string label = state switch +{ + EditorPlayModeState.Editing => "Enter Play Mode", + EditorPlayModeState.Compiling => "Compiling", + EditorPlayModeState.Playing => "Exit Play Mode", + _ => throw new ArgumentOutOfRangeException(nameof(state)) +}; +``` + +Avoid: + +```csharp +string label = state switch { EditorPlayModeState.Editing => "Enter", _ => "Exit", }; +``` + +## I-05 No trailing commas + +The last item of an object initializer, a collection, an enum, a `switch` expression or an anonymous object is not followed by a comma. + +```csharp +public enum ToneMapping +{ + None, + Reinhard, + Aces +} +``` + +Avoid: + +```csharp +public enum ToneMapping +{ + None, + Reinhard, + Aces, +} +``` diff --git a/.agents/rulebook/csharp-style/11-spacing.md b/.agents/rulebook/csharp-style/11-spacing.md new file mode 100644 index 000000000..d4503f52f --- /dev/null +++ b/.agents/rulebook/csharp-style/11-spacing.md @@ -0,0 +1,184 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, formatting] +--- +# 11. Spacing and blank lines + +## S-01 Spaces + +| Position | Rule | Example | +| --- | --- | --- | +| Control keyword and `(` | One space | `if (x)`, `foreach (T item in items)` | +| Method name, `typeof`, `nameof`, `default` and `(` | No space | `Draw(item)`, `typeof(int)` | +| `new` and `(` or `[` | No space | `new()`, `new[]` | +| Inside parentheses and brackets | No space | `Add(a, b)`, `items[0]` | +| Before an index bracket | No space | `items[0]` | +| Comma | None before, one after | `Add(a, b)` | +| Semicolon in `for` | None before, one after | `for (int i = 0; i < n; i++)` | +| Binary operators, assignment, `=>`, `??`, `?:` | One on each side | `a + b`, `x => x.id` | +| Unary operators | Attached to the operand | `!ready`, `-value`, `i++` | +| After a cast | No space | `(float)count` | +| Member access `.`, `?.`, `->` | No space | `entry?.name` | +| Inside generic angle brackets | No space | `Dictionary` | +| Nullable `?` and pointer `*` | Attached to the type | `string?`, `byte* data` | +| Range `..` | No space | `span[1..^1]` | +| Spread `..` | One space after | `[.. items]` | +| Inside single-line braces with content | One on each side | `{ get; }`, `new T { a = 1 }`, `is { }` | +| Empty body | No space inside | `{}` | +| Before `{` on the same line | One space | `) {`, `() {}` | +| Colon of a base list, constraint or initializer | One on each side | `class A : B`, `where T : class` | +| Colon of a named argument or attribute target | None before, one after | `width: 1280`, `[assembly: X]` | + +```csharp +if (ready) +{ + float ratio = (float)count / total; + int first = items[0]; + Draw(item, ratio, first); +} +``` + +Avoid: + +```csharp +if(ready) +{ + float ratio = (float) count/total; + int first = items [0]; + Draw( item,ratio , first ); +} +``` + +## S-02 Column alignment + +- When more than three consecutive `const` declarations, or more than three consecutive `static readonly` declarations, have the same type, aligning their `=` signs in a column is recommended. It is not required. +- A numeric matrix or lookup table may align its elements in columns. +- Everywhere else, use a single space between tokens. Do not column-align local variables, assignments, parameters or comments. + +```csharp +private const int C_WIDTH = 1280; +private const int C_HEIGHT = 720; +private const int C_REFRESH_RATE = 60; +private const int C_MIN_SIZE = 16; + +public static readonly Color RED = FromBytes(255, 0, 0); +public static readonly Color GREEN = FromBytes(0, 255, 0); +public static readonly Color BLUE = FromBytes(0, 0, 255); +public static readonly Color WHITE = FromBytes(255, 255, 255); + +private static readonly float[] IDENTITY = +[ + 1f, 0f, 0f, 0f, + 0f, 1f, 0f, 0f, + 0f, 0f, 1f, 0f, + 0f, 0f, 0f, 1f +]; +``` + +Avoid (alignment of local variables and trailing comments): + +```csharp +int width = 1280; +string title = "Scene"; // window title +float refreshRate = 60f; // hertz +``` + +## S-03 Blank lines between members + +- Methods, constructors, members with documentation comments and multi-line properties are separated by one blank line. +- Fields, constants and single-line properties of the same group that have no documentation comments are written consecutively. +- Different groups (O-01) are separated by one blank line. +- Enum members are not separated by blank lines, even when they have documentation comments. +- Types are separated by one blank line. + +```csharp +public sealed class Viewport +{ + private const int C_MIN_SIZE = 16; + private const int C_MAX_SIZE = 16384; + + private readonly RenderTarget m_target; + private int m_width; + private int m_height; + + /// + /// Gets the current width in pixels. + /// + public int width => m_width; + + /// + /// Gets the current height in pixels. + /// + public int height => m_height; + + internal bool isDirty { get; set; } + internal int generation { get; set; } +} +``` + +Avoid: + +```csharp +public sealed class Viewport +{ + private const int C_MIN_SIZE = 16; + + private const int C_MAX_SIZE = 16384; + private readonly RenderTarget m_target; + /// + /// Gets the current width in pixels. + /// + public int width => m_width; + internal bool isDirty { get; set; } + +} +``` + +## S-04 Blank lines inside method bodies + +- Separate processing phases (validation, preparation, execution, completion) with one blank line. Do not add blank lines mechanically. +- The argument validation at the start of a method (a run of `ThrowIf*` calls and guards) is contiguous and followed by one blank line. +- A local function is preceded by one blank line and placed at the end of the method body. +- No blank line follows an opening brace or precedes a closing brace. Never leave two consecutive blank lines. + +```csharp +public AssetHandle Import( + string path, + ImportOptions options +) { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + ArgumentNullException.ThrowIfNull(options); + ObjectDisposedException.ThrowIf(m_disposed, this); + + AssetSource source = OpenSource(path); + ImportPlan plan = BuildPlan(source, options); + + AssetHandle handle = Execute(plan); + m_handles.Add(handle.id, handle); + return handle; + + ImportPlan BuildPlan( + AssetSource target, + ImportOptions settings + ) => new(target, settings); +} +``` + +Avoid: + +```csharp +public AssetHandle Import( + string path, + ImportOptions options +) { + + ArgumentException.ThrowIfNullOrWhiteSpace(path); + + ArgumentNullException.ThrowIfNull(options); + AssetSource source = OpenSource(path); + + + return Execute(BuildPlan(source, options)); + +} +``` diff --git a/.agents/rulebook/csharp-style/12-idioms.md b/.agents/rulebook/csharp-style/12-idioms.md new file mode 100644 index 000000000..b7f0d4375 --- /dev/null +++ b/.agents/rulebook/csharp-style/12-idioms.md @@ -0,0 +1,364 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 12. Types and expression idioms + +## E-01 Local variables state their type; `var` only with `new T(...)` + +- A local variable declares its type: `T x = expression;`. +- Use `var` when the right-hand side is `new T(...)` or `new T[...]`, where the type is visible on the same line. +- An anonymous type requires `var`. +- A local variable does not use `T x = new(...)`; that form is for fields and properties (M-04). +- A collection expression needs a target type, so the declaration states it: `List names = [];`. + +```csharp +AssetEntry entry = m_entries[index]; +int count = entry.dependencies.Count; +string name = entry.displayName; +var builder = new StringBuilder(capacity); +var buffer = new byte[C_BUFFER_SIZE]; +List names = []; +var projection = new { entry.id, entry.displayName }; +``` + +Avoid: + +```csharp +var entry = m_entries[index]; +var count = entry.dependencies.Count; +StringBuilder builder = new(capacity); +StringBuilder other = new StringBuilder(capacity); +``` + +## E-02 `foreach`, `for`, `using`, `out` and deconstruction state their types + +```csharp +foreach (AssetEntry entry in m_entries) +{ + Visit(entry); +} + +foreach ((string key, AssetEntry value) in m_byName) +{ + Visit(value); +} + +for (int i = 0; i < count; i++) +{ + Visit(m_entries[i]); +} + +using Stream stream = lease.OpenRead(); + +if (m_byName.TryGetValue(name, out AssetEntry? found)) +{ + Visit(found); +} +``` + +Avoid: + +```csharp +foreach (var entry in m_entries) +{ + Visit(entry); +} + +using var stream = lease.OpenRead(); + +if (m_byName.TryGetValue(name, out var found)) +{ + Visit(found); +} +``` + +## E-03 Built-in types use keywords + +Write `int`, `string`, `float`, `object`, `nint` and `nuint`, not `Int32`, `String`, `IntPtr` or `UIntPtr`. Access static members through the keyword as well. + +```csharp +nint handle = nint.Zero; +bool empty = string.IsNullOrWhiteSpace(name); +float largest = float.MaxValue; +``` + +Avoid: + +```csharp +IntPtr handle = IntPtr.Zero; +bool empty = String.IsNullOrWhiteSpace(name); +Single largest = Single.MaxValue; +``` + +## E-04 Null checks use patterns + +Use `is null` and `is not null`. Use `is { } x` or `is T x` to test and capture at once. Do not write `== null` or `!= null`. + +```csharp +if (m_source is null) return; + +if (m_owner is not null) +{ + m_owner.Release(); +} + +if (TryFind(id) is { } entry) +{ + Visit(entry); +} +``` + +Avoid: + +```csharp +if (m_source == null) return; + +if (!(m_owner is null)) +{ + m_owner.Release(); +} +``` + +## E-05 Argument validation + +Validation comes first in a method, in parameter order, and uses the `ThrowIf*` helpers. Do not write `?? throw new ArgumentNullException(...)`. + +```csharp +public Viewport( + RenderTarget target, + string name, + int width +) { + ArgumentNullException.ThrowIfNull(target); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + + m_target = target; + m_width = width; + this.name = name; +} +``` + +Avoid: + +```csharp +public Viewport( + RenderTarget target, + string name +) { + m_target = target ?? throw new ArgumentNullException(nameof(target)); + if (name == null) + { + throw new ArgumentNullException("name"); + } +} +``` + +## E-06 Object creation + +- A local variable: `var x = new T(...)` (E-01). +- A field or property initializer: `= new(...)` (M-04). +- A member that directly returns a new object of its declared return type may use `new(...)`. +- An argument, or a creation inside a larger expression, writes the type: `new T(...)`. + +```csharp +public static Color FromBytes( + byte r, + byte g, + byte b +) => new(r / 255f, g / 255f, b / 255f); +``` + +```csharp +var item = new RenderItem(mesh, material); +queue.Enqueue(new RenderItem(mesh, material)); +``` + +Avoid: + +```csharp +RenderItem item = new(mesh, material); +queue.Enqueue(new(mesh, material)); +``` + +## E-07 Common values + +| Meaning | Write | Not | +| --- | --- | --- | +| Empty string | `string.Empty` | `""` | +| Default value | `default` | `default(T)`, unless the type cannot be inferred | +| Empty collection | `[]` | `new List()`, `Array.Empty()` | +| Negation | `!ready` | `ready == false` | +| Non-nullable `bool` test | `if (ready)` | `if (ready == true)` | +| Nullable `bool?` test | `if (flag == true)` | `if (flag ?? false)` | +| Conversion | `(T)value` | `value as T` without a following null check | +| Type test with capture | `value is T typed` | `as` followed by a null check | +| Delegate invocation | `handler?.Invoke(args)` | a null check followed by a call | +| Rethrow | `throw;` | `throw exception;` | +| Infinite loop | `while (true)` | `for (;;)` | +| Current time | `DateTime.UtcNow`, `DateTimeOffset.UtcNow` | `DateTime.Now` | + +```csharp +string label = string.Empty; +Color color = default; +flushed?.Invoke(); +if (value is AssetEntry typed) +{ + Visit(typed); +} +``` + +Avoid: + +```csharp +string label = ""; +Color color = default(Color); +if (flushed != null) +{ + flushed.Invoke(); +} + +AssetEntry typed = value as AssetEntry; +if (typed != null) +{ + Visit(typed); +} +``` + +## E-08 `this.` + +- Inside a constructor, every assignment to an instance member that is not an `m_` field goes through `this.`: `this.name = name;`, `this.count = 0;`. This holds whether or not a parameter has the same name. +- Outside constructors, do not write `this.` unless it is needed to disambiguate. +- Apart from constructor parameters, a parameter or local variable does not take the name of a property of the same type. + +```csharp +public GameBuildPackageContext( + BuildProfile profile, + string outputDirectory +) { + m_createdUtc = DateTime.UtcNow; + this.profile = profile; + this.outputDirectory = outputDirectory; + this.isIncremental = true; +} + +public BuildProfile profile { get; } +public string outputDirectory { get; } +public bool isIncremental { get; private set; } + +public string Describe() => $"{profile.name} -> {outputDirectory}"; +``` + +Avoid (`isIncremental` assigned without `this.` in the constructor, `this.` outside the constructor): + +```csharp +public GameBuildPackageContext( + BuildProfile profile, + string outputDirectory +) { + this.profile = profile; + this.outputDirectory = outputDirectory; + isIncremental = true; +} + +public string Describe() => $"{this.profile.name} -> {this.outputDirectory}"; +``` + +## E-09 Strings + +- Build strings from values with interpolation, `$"..."`. Do not use `string.Format` or `string.Concat`. +- Split a long message with `+` at the start of the continuation line (W-01). Use a raw string literal, `"""`, for multi-line text. +- Comparison, lookup, sorting and dictionaries state `StringComparison.Ordinal` / `StringComparer.Ordinal` or the `OrdinalIgnoreCase` variants. +- Change case with `ToLowerInvariant()` / `ToUpperInvariant()` and format with `CultureInfo.InvariantCulture`. +- Refer to identifiers with `nameof(...)`. +- Test external input with `string.IsNullOrWhiteSpace`, and use `string.IsNullOrEmpty` only when whitespace is meaningful. + +```csharp +string message = $"The asset '{path}' could not be imported: {reason}"; +bool same = string.Equals(left, right, StringComparison.Ordinal); +var index = new Dictionary(StringComparer.OrdinalIgnoreCase); +throw new ArgumentException("The path must be relative.", nameof(path)); +``` + +Avoid: + +```csharp +string message = string.Format("The asset '{0}' could not be imported: {1}", path, reason); +bool same = left.ToLower() == right.ToLower(); +throw new ArgumentException("The path must be relative.", "path"); +``` + +## E-10 Numeric literals + +- `float`: write an integral value as `1f` and a fractional value as `1.5f`. Do not write `1.0f` or `1.50f`. +- Suffixes: `f`, `d`, `m` and `u` are lower case; `L` and `UL` are upper case. +- Hexadecimal: the `0x` prefix is lower case, the digits are upper case, and long values are grouped by four digits with `_`. +- Large decimal values are grouped by three digits with `_`. + +```csharp +float half = 0.5f; +float one = 1f; +uint mask = 0xFF00_00FFu; +long ticks = 10_000_000L; +``` + +Avoid: + +```csharp +float one = 1.0f; +float ratio = 1.50f; +uint mask = 0xff0000ffU; +long ticks = 10000000l; +``` + +## E-11 Lambdas + +- One parameter has no parentheses: `x => ...`. No parameters: `() => ...`. Two or more parameters are expanded (P-01). +- Parameters have meaningful names. An unused parameter is `_`. +- A lambda that captures neither a local variable nor `this` is `static`. +- A single-expression body uses the expression form; several statements use a block (B-04). +- When an expression body does not fit on the line of the lambda, it is wrapped in parentheses, unless it is a call or object creation, which breaks inside its own parentheses (B-04). +- Do not use anonymous methods (`delegate { }`). + +```csharp +entries.RemoveAll(static entry => entry.isMissing); +entries.RemoveAll(entry => entry.generation < m_generation); +button.clicked += () => m_log.Info("Clicked."); + +Func isStale = entry => ( + entry.lastWriteTimeUtc < threshold && !entry.isPinned +); +``` + +Avoid: + +```csharp +entries.RemoveAll((entry) => entry.isMissing); +entries.RemoveAll(x => x.isMissing); + +Func isStale = entry => + entry.lastWriteTimeUtc < threshold && !entry.isPinned; +``` + +## E-12 `using` declarations + +Use a `using` declaration when the resource lives until the end of the enclosing block. Use a `using` statement with a block only when the resource must be released earlier. + +```csharp +using Stream stream = lease.OpenRead(); +using var reader = new StreamReader(stream); +return reader.ReadToEnd(); +``` + +Avoid (a block that ends where the method ends): + +```csharp +using (Stream stream = lease.OpenRead()) +{ + using (var reader = new StreamReader(stream)) + { + return reader.ReadToEnd(); + } +} +``` diff --git a/.agents/rulebook/csharp-style/13-control-flow.md b/.agents/rulebook/csharp-style/13-control-flow.md new file mode 100644 index 000000000..c7b2bde99 --- /dev/null +++ b/.agents/rulebook/csharp-style/13-control-flow.md @@ -0,0 +1,177 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 13. Control flow, exceptions and asynchronous code + +## X-01 Guard clauses return early + +Handle invalid and boundary cases first and leave with `return`, `throw` or `continue`. The main path is not nested inside `else`. Guards may use the compact form of B-05. + +```csharp +public void Draw(RenderItem item) +{ + if (m_disposed) return; + if (!item.isVisible) return; + + Submit(item); + m_drawn++; +} +``` + +Avoid: + +```csharp +public void Draw(RenderItem item) +{ + if (!m_disposed) + { + if (item.isVisible) + { + Submit(item); + m_drawn++; + } + } +} +``` + +## X-02 `switch` + +- Use a `switch` expression to map a value to a value (I-04). +- Use a `switch` statement when the branches execute statements. `case` is indented four spaces from `switch`, and the statements four spaces from `case`. Each label is on its own line. `default` is last. Add braces to a section only when it declares local variables that would otherwise collide. + +```csharp +switch (command.kind) +{ + case CommandKind.Draw: + case CommandKind.DrawIndexed: + Submit(command); + break; + case CommandKind.Clear: + Clear(command.color); + break; + default: + throw new InvalidOperationException($"Unknown command kind '{command.kind}'."); +} +``` + +Avoid: + +```csharp +switch (command.kind) +{ +case CommandKind.Draw: case CommandKind.DrawIndexed: + Submit(command); break; +default: throw new InvalidOperationException($"Unknown command kind '{command.kind}'."); +case CommandKind.Clear: + Clear(command.color); + break; +} +``` + +## X-03 Exception types and messages + +| Situation | Exception | +| --- | --- | +| An argument is `null` | `ArgumentNullException`, through `ThrowIfNull` | +| An argument value is invalid | `ArgumentException`, `ArgumentOutOfRangeException` | +| The object state does not allow the operation | `InvalidOperationException` | +| The object has been disposed | `ObjectDisposedException`, through `ThrowIf` | +| Input data is malformed | `InvalidDataException` | +| The platform or backend does not support the operation | `NotSupportedException` | + +A message is a complete English sentence that includes the offending value. Parameter names use `nameof`. A `throw` whose arguments do not fit on one line breaks like any other call (A-02). + +```csharp +throw new InvalidDataException( + $"The scene file '{path}' declares version {version}, but only version {C_VERSION} is supported." +); +``` + +Avoid: + +```csharp +throw new InvalidDataException( + $"The scene file '{path}' declares version {version}, but only version {C_VERSION} is supported."); + +throw new Exception("bad version"); +``` + +## X-04 `catch` + +- Catch the specific type that can be handled. When catching `Exception`, filter with `when` or rethrow with `throw;` after handling. +- The variable is named `exception` by default. A name that states the role, such as `cleanupFailure`, is allowed when the exception is stored or aggregated. Omit the variable when it is not used. +- A bare `catch` without a type is only for "clean up, then rethrow". +- A `catch` block that deliberately ignores an exception contains a comment that says why. + +```csharp +try +{ + Directory.Delete(scratch, recursive: true); +} +catch (IOException) +{ + // The scratch directory is retried by the next retirement pass. +} + +try +{ + Publish(candidate); +} +catch (Exception exception) when (exception is not OperationCanceledException) +{ + m_log.Error($"Publication failed: {exception.Message}"); + throw; +} +``` + +Avoid: + +```csharp +try +{ + Directory.Delete(scratch, recursive: true); +} +catch {} + +try +{ + Publish(candidate); +} +catch (Exception ex) +{ + throw ex; +} +``` + +## X-05 Asynchronous code + +- Return `Task` or `ValueTask`. Never write `async void`. +- The method name ends with `Async` (NM-04). `CancellationToken cancellationToken` is the last parameter and is passed down to every asynchronous call. +- In product code (`src`, `build`, `backends`, `platforms`, `tools`, `entry`) every `await` ends with `.ConfigureAwait(false)`. Test code does not use `ConfigureAwait`. +- Do not block on asynchronous results with `.Wait()`, `.Result` or `.GetAwaiter().GetResult()`. An entry point that must wait synchronously carries a comment that explains why. +- On a broken `await` call, `.ConfigureAwait(false)` follows the closing parenthesis on its line. + +```csharp +public async Task LoadAsync( + AssetID id, + CancellationToken cancellationToken +) { + await using Stream stream = await m_storage.OpenAsync(id, cancellationToken).ConfigureAwait(false); + return await m_reader.ReadAsync( + stream, + id, + cancellationToken + ).ConfigureAwait(false); +} +``` + +Avoid: + +```csharp +public async void Load(AssetID id) +{ + Stream stream = m_storage.OpenAsync(id, CancellationToken.None).Result; + await m_reader.ReadAsync(stream, id, CancellationToken.None); +} +``` diff --git a/.agents/rulebook/csharp-style/14-comments.md b/.agents/rulebook/csharp-style/14-comments.md new file mode 100644 index 000000000..345545119 --- /dev/null +++ b/.agents/rulebook/csharp-style/14-comments.md @@ -0,0 +1,192 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style, xml] +--- +# 14. Comments and XML documentation + +## D-01 Which members need XML documentation + +Every externally visible public member, and every protected member that an external type can override, has complete English XML documentation. Important internal APIs are documented as well. Private members and test code do not need documentation. + +```csharp +/// +/// Stores render items until the next flush. +/// +public sealed class RenderQueue +{ + private readonly List m_items = []; + + /// + /// Gets the number of queued items. + /// + public int count => m_items.Count; + + private void Trim() => m_items.TrimExcess(); +} +``` + +Avoid (a public type and a public property without documentation): + +```csharp +public sealed class RenderQueue +{ + public int count => m_items.Count; +} +``` + +## D-02 Tags are expanded, one element per block + +- The start tag, the content and the end tag are on separate lines. `///` is followed by one space. A documentation block has no empty `///` lines. +- Tag order: `summary`, `typeparam`, `param` (in signature order), `returns`, `exception`, `remarks`. +- Every content block starts with a capital letter and ends with a period. +- Wrap long content at complete semantic boundaries. + +```csharp +/// +/// Resolves a loaded asset by its persistent identity. +/// +/// +/// The asset type expected by the caller. +/// +/// +/// The persistent identity of the asset. +/// +/// +/// Receives the asset when this method returns ; +/// otherwise . +/// +/// +/// when the asset is loaded and has the requested type; +/// otherwise . +/// +/// +/// The loader has been disposed. +/// +public bool TryResolve( + AssetID id, + [NotNullWhen(true)] out TAsset? asset +) where TAsset : class +{ + ObjectDisposedException.ThrowIf(m_disposed, this); + return TryResolveCore(id, out asset); +} +``` + +Avoid: + +```csharp +/// Resolves an asset +/// the asset +/// the id +/// true if found +public bool TryResolve( + AssetID id, + [NotNullWhen(true)] out TAsset? asset +) where TAsset : class +{ + ObjectDisposedException.ThrowIf(m_disposed, this); + return TryResolveCore(id, out asset); +} +``` + +## D-03 Wording of summaries + +| Member | Starts with | Example | +| --- | --- | --- | +| Read-only property | `Gets` | `Gets the current width in pixels.` | +| Writable property | `Gets or sets` | `Gets or sets the clear color.` | +| `bool` property | `Gets a value indicating whether` | `Gets a value indicating whether the asset is missing.` | +| Method | A third-person verb | `Creates`, `Releases`, `Determines whether`, `Attempts to` | +| Constructor | `Initializes a new instance of` or `Creates` | `Creates a dispatcher bound to the given hub.` | +| Type | A third-person verb or a noun phrase | `Identifies`, `Describes`, `Provides`, `Represents` | +| Event | `Occurs when` | `Occurs when the platform requests a redraw.` | + +A summary describes real behavior. It does not restate the member name. + +```csharp +/// +/// Gets the current width of the viewport in pixels. +/// +public int width => m_width; +``` + +Avoid: + +```csharp +/// +/// The width. +/// +public int width => m_width; +``` + +## D-04 References inside documentation + +- A type or member: ``. A parameter: ``. A type parameter: ``. +- A keyword: ``, ``, ``. +- A self-closing tag has no space before `/>`. +- An override or interface implementation uses `/// ` and documents any additional constraint locally with `remarks` or `exception`. + +```csharp +/// +public override string ToString() => name; +``` + +Avoid: + +```csharp +/// +/// Returns null if id is not found. See AssetLoader. +/// +/// +public override string ToString() => name; +``` + +## D-05 `//` comments + +- A comment explains a reason, a constraint, ownership or a lifetime. It does not restate the code. +- A comment is on its own line, above the code it explains, at the indentation of that code. Do not write trailing comments. +- `//` is followed by one space. The comment is a complete English sentence that starts with a capital letter and ends with a period. + +```csharp +// The native window must outlive the swap chain, so it is released last. +m_swapChain.Dispose(); +m_window.Dispose(); +``` + +Avoid: + +```csharp +m_swapChain.Dispose(); // dispose swap chain +//release window +m_window.Dispose(); +``` + +## D-06 Prohibited comments and directives + +- Comments in any language other than English. +- `TODO`, `FIXME` or `HACK` markers left in place indefinitely. +- Commented-out code. +- Separator lines, banner comments and `/* */` block comments. +- `#region` and `#endregion`. +- `#nullable` inside a file, and `#pragma warning disable` without a comment that states the reason. + +`#if`, `#elif`, `#else` and `#endif` start at column 0. Conditional symbols are UPPER_SNAKE with the `INNO_` prefix, except `DEBUG`. + +```csharp +#if INNO_HOST_WINDOWS_X64 + private const string C_LIBRARY_NAME = "bgfx.dll"; +#elif INNO_HOST_MACOS_ARM64 + private const string C_LIBRARY_NAME = "libbgfx.dylib"; +#endif +``` + +Avoid: + +```csharp +#region Constants + // ---------- library ---------- + // TODO: revisit + // private const string C_OLD_NAME = "bgfx_old.dll"; + private const string C_LIBRARY_NAME = "bgfx.dll"; /* windows */ +#endregion +``` diff --git a/.agents/rulebook/csharp-style/15-tests.md b/.agents/rulebook/csharp-style/15-tests.md new file mode 100644 index 000000000..cc4a41d8e --- /dev/null +++ b/.agents/rulebook/csharp-style/15-tests.md @@ -0,0 +1,137 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 15. Tests + +## TS-01 Structure + +- Tests use xUnit. A test class is `public sealed class XxxTests` in `XxxTests.cs`, in the namespace of the test project. +- A test method is `public`, returns `void` or `async Task`, and carries `[Fact]`, or `[Theory]` with `[InlineData]`. +- Test classes and test methods do not need XML documentation. +- Fixtures and test doubles follow the same naming and layout rules as product code. A nested test double is `private sealed` and placed at the end of the test class. + +```csharp +using System; +using Xunit; +using Inno.Core.Events; + +namespace Inno.Core.Events.Tests; + +public sealed class EventDispatcherTests +{ + [Fact] + public void NewDispatcherHasNoSinks() + { + var dispatcher = new EventDispatcher(); + + Assert.Empty(dispatcher.sinks); + } + + private sealed class RecordingSink : IEventSink + { + public int published { get; private set; } + + public void Publish(EventRecord record) => published++; + } +} +``` + +Avoid: + +```csharp +public class EventDispatcherTest +{ + [Fact] + void NewDispatcherHasNoSinks() {} +} +``` + +## TS-02 Test method names + +A test method name is a PascalCase statement of what happens under which condition. It has no underscores, no `Async` suffix and no `Test` prefix or suffix. + +```csharp +public sealed class EventDispatcherTests +{ + [Fact] + public void DispatchAfterDisposeThrowsObjectDisposedException() + { + var dispatcher = new EventDispatcher(); + dispatcher.Dispose(); + + Assert.Throws(() => dispatcher.Dispatch(new EventRecord())); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void NonPositiveCapacityIsRejected(int capacity) + => Assert.Throws(() => new EventDispatcher(capacity)); + + [Fact] + public async Task PendingEventsAreDeliveredBeforeShutdownCompletes() + { + var dispatcher = new EventDispatcher(); + List received = []; + dispatcher.dispatched += received.Add; + + dispatcher.Dispatch(new EventRecord()); + await dispatcher.ShutdownAsync(CancellationToken.None); + + Assert.Single(received); + } +} +``` + +Avoid: + +```csharp +public sealed class EventDispatcherTests +{ + [Fact] + public void Dispatch_AfterDispose_Throws() + { + var dispatcher = new EventDispatcher(); + dispatcher.Dispose(); + } + + [Fact] + public async Task TestShutdownAsync() + { + var dispatcher = new EventDispatcher(); + await dispatcher.ShutdownAsync(CancellationToken.None).ConfigureAwait(false); + } +} +``` + +## TS-03 Assertions and layout + +- Separate the arrange, act and assert phases with one blank line. A very short test may omit the separation. +- `Assert.Equal(expected, actual)`: the expected value comes first. +- Source text used as test data (generator inputs and expected outputs) is data, not code; this rulebook does not apply to it. + +```csharp +[Fact] +public void ResizeUpdatesBothDimensions() +{ + var viewport = new Viewport(m_target, "Main", 640); + + viewport.Resize(width: 1280, height: 720); + + Assert.Equal(1280, viewport.width); + Assert.Equal(720, viewport.height); +} +``` + +Avoid (actual value first, phases not separated): + +```csharp +[Fact] +public void ResizeUpdatesBothDimensions() +{ + var viewport = new Viewport(m_target, "Main", 640); + viewport.Resize(width: 1280, height: 720); + Assert.Equal(viewport.width, 1280); +} +``` diff --git a/.agents/rulebook/csharp-style/16-exceptions.md b/.agents/rulebook/csharp-style/16-exceptions.md new file mode 100644 index 000000000..79c827d19 --- /dev/null +++ b/.agents/rulebook/csharp-style/16-exceptions.md @@ -0,0 +1,24 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 16. Exceptions + +The following cases follow an external contract. Do not rename or reformat them to satisfy this rulebook. + +| Case | What it keeps | Example | +| --- | --- | --- | +| Generated code and third-party sources | Everything | `extern/`, `**/Generated/*.cs`, `` files | +| MSBuild task parameters | PascalCase property names bound by MSBuild | `public string OutputPath { get; set; }` | +| Overrides and interface implementations | The name declared by the base type or interface | `Stream.CanRead`, `IEnumerator.Current` | +| Special CLR members | Names required by the language or runtime | operators, `GetEnumerator`, `Deconstruct`, `Dispose` | +| Native interop signatures | Field names, enum values and imported function names from the native header | `SDL_Event`, bgfx enums | +| Serialized wire names | The serialized name; source property names and wire names are declared separately | | +| Third-party product names | The spelling used by the product | `RmlUi`, `ImGui`, `MiniAudio` | +| Keyboard and input code enums | Single-letter and digit members | `KeyCode.A`, `KeyCode.F1` | +| Numeric matrices and lookup tables | Several elements per line, column alignment (S-02) | a 4×4 matrix literal | +| Unsplittable string literals | Length beyond the line width (F-04) | paths, URLs | +| Generator templates and their tests | `global::` and fully qualified names required by the generation protocol | | +| Source text used as test data | Its own formatting (TS-03) | | + +Keep each exception as small as possible: it covers the name or the layout bound by the contract, and the rest of the file follows the rulebook. diff --git a/.agents/rulebook/csharp-style/17-example.md b/.agents/rulebook/csharp-style/17-example.md new file mode 100644 index 000000000..5f20396a3 --- /dev/null +++ b/.agents/rulebook/csharp-style/17-example.md @@ -0,0 +1,209 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# 17. Reference example + +One file that applies the rules together. + +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Core.Identity; + +using AssetEvent = Inno.Assets.Pipeline.AssetChangedEvent; + +namespace Inno.Assets.Pipeline; + +/// +/// Caches loaded assets and reloads them when their sources change. +/// +public sealed class AssetCache : IDisposable +{ + private const int C_INITIAL_CAPACITY = 64; + private const int C_MAX_ATTEMPT_COUNT = 3; + + private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromMilliseconds(50); + + private readonly Dictionary m_entries = new(C_INITIAL_CAPACITY); + private readonly IAssetStore m_store; + private readonly ILogSink m_log; + private int m_generation; + private bool m_disposed; + + /// + /// Creates a cache that reads asset content from the given store. + /// + /// + /// The store that provides asset content. + /// + /// + /// The sink that receives reload diagnostics. + /// + /// + /// The diagnostic name of the cache. + /// + /// + /// is empty or consists only of white space. + /// + public AssetCache( + IAssetStore store, + ILogSink log, + string name + ) { + ArgumentNullException.ThrowIfNull(store); + ArgumentNullException.ThrowIfNull(log); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + + m_store = store; + m_log = log; + this.name = name; + this.isEnabled = true; + } + + /// + /// Gets the diagnostic name of the cache. + /// + public string name { get; } + + /// + /// Gets a value indicating whether the cache accepts source changes. + /// + public bool isEnabled { get; private set; } + + /// + /// Gets the number of cached assets. + /// + public int count => m_entries.Count; + + /// + /// Occurs when a cached asset has been reloaded from its source. + /// + public event Action? assetReloaded; + + /// + /// Attempts to find a cached asset that is still current. + /// + /// + /// The persistent identity of the asset. + /// + /// + /// Receives the cached handle when this method returns ; + /// otherwise . + /// + /// + /// when a current entry exists; otherwise . + /// + public bool TryResolve( + AssetID id, + [NotNullWhen(true)] out AssetHandle? handle + ) { + ObjectDisposedException.ThrowIf(m_disposed, this); + + if (m_entries.TryGetValue(id, out Entry? entry) + && entry.generation == m_generation + && !entry.handle.isMissing + ) { + handle = entry.handle; + return true; + } + + handle = null; + return false; + } + + /// + /// Loads an asset, reusing the cached handle when it is still current. + /// + /// + /// The persistent identity of the asset. + /// + /// + /// A token that cancels the load. + /// + /// + /// The loaded asset handle. + /// + /// + /// The store could not provide the asset after every attempt. + /// + public async Task LoadAsync( + AssetID id, + CancellationToken cancellationToken + ) { + if (TryResolve(id, out AssetHandle? cached)) return cached; + + for (int attempt = 1; attempt <= C_MAX_ATTEMPT_COUNT; attempt++) + { + try + { + AssetHandle handle = await m_store.LoadAsync(id, cancellationToken).ConfigureAwait(false); + m_entries[id] = new Entry(handle, m_generation); + return handle; + } + catch (IOException exception) when (attempt < C_MAX_ATTEMPT_COUNT) + { + m_log.Warning($"Loading asset '{id}' failed on attempt {attempt}: {exception.Message}"); + await Task.Delay(RETRY_DELAY, cancellationToken).ConfigureAwait(false); + } + } + + throw new InvalidDataException( + $"The asset '{id}' could not be loaded from store '{m_store.name}' after {C_MAX_ATTEMPT_COUNT} attempts." + ); + } + + /// + /// Applies source changes and invalidates the affected entries. + /// + /// + /// The source changes reported by the watcher. + /// + public void ApplySourceChanges(IReadOnlyList changes) + { + ArgumentNullException.ThrowIfNull(changes); + if (!isEnabled) return; + + m_generation++; + foreach (AssetEvent change in changes) + { + if (!m_store.TryGetID(change.path, out AssetID id)) continue; + + string action = change.change switch + { + WatcherChangeTypes.Deleted => "removed", + WatcherChangeTypes.Renamed => "renamed", + _ => "changed" + }; + m_log.Info($"Asset '{id}' was {action}."); + + m_entries.Remove(id); + assetReloaded?.Invoke(id); + } + } + + /// + public void Dispose() + { + if (m_disposed) return; + + // Entries only borrow their handles, so the store releases the content. + m_entries.Clear(); + m_disposed = true; + } + + internal bool IsCurrent(AssetID id) + => m_entries.TryGetValue(id, out Entry? entry) + && entry.generation == m_generation; + + private sealed record Entry( + AssetHandle handle, + int generation + ); +} +``` diff --git a/.agents/rulebook/csharp-style/README.md b/.agents/rulebook/csharp-style/README.md new file mode 100644 index 000000000..ef07c5eb3 --- /dev/null +++ b/.agents/rulebook/csharp-style/README.md @@ -0,0 +1,36 @@ +--- +paths: ["**/*.cs"] +tags: [csharp-style] +--- +# InnoEngine C# code style + +This rulebook defines how handwritten C# in InnoEngine is named, laid out and written. It applies to every handwritten `.cs` file in the repository, including tests and tools. Third-party sources under `extern/`, generated files (`**/Generated/*.cs` and files carrying an `` header) and the cases listed in [section 16](16-exceptions.md) are out of scope. + +The [coding rules](../coding.md) own design, error-handling, resource and change-management requirements. This rulebook is the detailed authority for names and layout. + +- Every rule has an ID such as `B-05`. Cite the ID in reviews and commit messages. +- Each rule states the requirement first, then shows a compliant example. A block introduced by **Avoid** shows what the rule forbids. +- "Must", "always" and "never" are requirements. "Prefer" and "recommended" describe the default; deviate only when the default hurts readability. +- External contracts take precedence over this rulebook: interface implementations, overrides, MSBuild task parameters, serialized names and native interop signatures keep the names their contract requires (see [section 16](16-exceptions.md)). +- Formatting changes and renames are separate changes. A formatting-only change must not alter names, logic, execution order or public contracts. Renaming a public member is an API change. +- Automatic formatters must preserve these rules. Do not apply a formatter whose output differs from this rulebook. + +Contents + +1. [Files and physical layout](01-files.md) +2. [Namespaces and using directives](02-namespaces.md) +3. [Naming](03-naming.md) +4. [Type declarations](04-types.md) +5. [Member declarations](05-members.md) +6. [Member order](06-member-order.md) +7. [Braces and blocks](07-braces.md) +8. [Parameter and argument lists](08-parameters.md) +9. [Line breaks](09-line-breaks.md) +10. [Initializers and collections](10-initializers.md) +11. [Spacing and blank lines](11-spacing.md) +12. [Types and expression idioms](12-idioms.md) +13. [Control flow, exceptions and asynchronous code](13-control-flow.md) +14. [Comments and XML documentation](14-comments.md) +15. [Tests](15-tests.md) +16. [Exceptions](16-exceptions.md) +17. [Reference example](17-example.md) diff --git a/.agents/rulebook/delivery.md b/.agents/rulebook/delivery.md index ef23bdd80..58664c7c5 100644 --- a/.agents/rulebook/delivery.md +++ b/.agents/rulebook/delivery.md @@ -1,9 +1,8 @@ +--- +tags: [delivery, notification] +--- # Delivery -Load complete rule units. The [registry](coverage.json) owns routing and provenance. - - - ## 31. Issues and pull requests - When creating or updating a repository issue or pull request, use a `type(scope): description` title. Both the title and body must be entirely in English. @@ -11,11 +10,7 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - Pull request bodies must explain the problem, final behavior and actual verification against the complete difference from the target branch, and identify checks that were not run. Search existing PRs before creation. Never describe partial acceptance as a passed complete matrix. - A human vouches for every commit: its Git author and committer are the human contributor responsible for it. No agent, bot or application identity may appear as author, committer, `Co-authored-by` or any other attribution. Create pull requests with the GitHub account authorized by the user. - Reproduce BGCS defects independently through public APIs and identify them explicitly. Do not modify BGCS source, packages or binaries, or manually edit generated output to bypass defects. - - - ## 16. Completion sound - By default, play `/System/Library/Sounds/Glass.aiff` before waiting for a design decision that changes scope, after completing the final design, and after completing the requested code or file operations and their necessary validation. The user need not repeat this request for each task. - If the environment cannot access audio, state in the final result that the sound could not be played. Do not play it when the user explicitly requests silence. - diff --git a/.agents/rulebook/documentation.md b/.agents/rulebook/documentation.md new file mode 100644 index 000000000..74bc18adb --- /dev/null +++ b/.agents/rulebook/documentation.md @@ -0,0 +1,8 @@ +--- +tags: [documentation, wiki, public-api] +--- +# Documentation + +[InnoEngine.Docs](https://github.com/Wolfiora/InnoEngine.Docs) owns the rules for documentation, API prose, examples and content ownership: the [documentation rules](https://github.com/Wolfiora/InnoEngine.Docs/blob/main/.agents/rulebook/documentation.md) on `main`, the published branch; [`draft`](https://github.com/Wolfiora/InnoEngine.Docs/blob/draft/.agents/rulebook/documentation.md) holds unpublished changes. + +Run the rule script again with `-DocsRoot `. It then also selects from the rule files of that checkout and lists them with the `docs/` prefix. It never guesses a sibling path or downloads the rules. diff --git a/.agents/rulebook/domains/build-native/backend-integration.md b/.agents/rulebook/domains/build-native/backend-integration.md new file mode 100644 index 000000000..52279580a --- /dev/null +++ b/.agents/rulebook/domains/build-native/backend-integration.md @@ -0,0 +1,22 @@ +--- +paths: ["build/**", "backends/**", "platforms/**", ".github/**", "Directory.Build.props", "Directory.Build.targets", "Directory.Solution.props", "Directory.Solution.targets"] +tags: [backend-build, native] +--- +# Backend integration + +## 29. Backend integration and generation cost + +- Shared SDL window creation and focus reading have one backend owner; platform integrations handle actual SDK differences only. Shared BGFX Devices receive borrowed surfaces through IBgfxSurfaceIntegration and maintain no named-platform/ABI allowlist. Default catalogs receive explicit rendering factories. +- Closing additional windows first unregisters interaction, then retires renderer surfaces. Release native windows only after rendering confirms framebuffer-destruction commands were processed. Native callbacks neither wait for nor advance frames. Final drain occurs only on the owner thread, outside a frame and without an active graph/encoder; failure retains dependency owners. Task completion is not a general GPU fence. +- Component Bindings/bindings.props solely owns Native generation definitions shared by MSBuild and library calls. Toolchains depend only on INativeBindingGenerator; Inno.Build.Bindings owns concrete BGCS workflows, and Tasks map parameters/cancellation/logging only. A product closure requests one complete binding batch. Managed consumers retain Native-selected fingerprints and each component's Static/Shared request. Dynamic-initialization switches consume actual linkage only at Native compilation boundaries, never inferred from platform names or hosts. +- Binding configuration path variables expand only from the operation's frozen Native SDK environment. Direct libraries and MSBuild share target resolution. Do not mutate process environments or temporary PATH values to expose SDKs to generators. Missing configuration fails before candidate creation. +- Product binding selection belongs to that product's SDK intermediate directory and remains after Build/Publish for content-identical reuse. Only Native binding projects import it; transient selection files must not become common-domain compilation inputs. Identical content does not rewrite timestamps; changes replace atomically; product cleanup retires the file. Native Publish still verifies the current managed compilation's closure, fingerprints and source. Retaining a selection file does not hold a generation-cache read lease; actual consumers acquire independent protection. +- Revalidate freshness initially, after batch locks/generation and after each Native lock/compilation. Deduplicate complete content reads only within one explicit phase, never across waits/execution. Copy mutable source to freeze it; hardlinks do not make mutable input immutable. +- Cold CMake producers use the common executor to freeze recipe-declared workspace inputs. Browser aggregate component includes, bridges and arguments resolve into the same copied tree. Warm hits do not copy. External SDKs and outputs retain their own locations and owners; do not misroute outputs by replacing the entire repository root in strings. +- Task runtimes reuse only successful immutable publications within one IBuildEngine4 Build lifetime and the same complete request identity. Registries store BCL data only, never SDK owners, leases or private-ALC types. Each actual load boundary retains an independent owner; failures/cancellation are not cached. Core.IO leases coordinate shared restore writes, yielding/reacquiring MSBuild nodes while waiting and retaining lock files. +- Independent concurrent managed builds use explicit SDK ArtifactsPath values for separate bin/obj owners. Common rules must not override that output selection. Actual product Restore graphs select NuGet Runtime assets; content-addressed Native caches share through their own leases. Ordinary IDE bin/obj belongs to one active build; two independent processes writing the same paths is not supported concurrency. +- Neutral and product requests within one SDK graph also isolate actual outputs. With ArtifactsPath, select an ArtifactsProjectName containing product inputs before SDK default paths are established, preserving SDK configuration/TFM/RID pivots and explicit caller settings. Before building, the development Editor entry uses existing owned restore for its selected product's complete reference closure. It cannot rely on later platform-child restores to satisfy direct or SDK-added transitive references. +- Owned NuGet Restore uses standard ExcludeRestorePackageImports=true. Compilation uses a separate evaluation configuration including restored imports. A cached ProjectInstance must not carry old package content items into new assembly outputs. Package-name exceptions, patched NuGet imports and cache deletion must not conceal mixed artifacts. +- NuGet dependencies use ordinary csproj PackageReferences and SDK Restore. Do not enable, generate or commit dependency lockfiles, or maintain per-project/host/RID/AOT/trimming lock inventories and naming schemes. Official declarations own package versions; BGCS retains its unified exact version. Consumers read actual SDK-evaluated assets/package content. CI performs ordinary restore and verifies builds, package identities and source hygiene. Custom dependency resolvers, clearing real SDK properties and ignore rules must not replace the correct flow. Core IO leases for concurrency, process ownership and atomic publication are not dependency locking and must remain. + +- Engine-managed build SDK working caches and coordination locks belong inside the corresponding artifacts/obj or explicit output owner. Do not retain global ignore rules or validation exemptions for retired cache locations in source directories. Before removing old project directories, verify current project/restore graphs, Git ownership, symlinks, active processes and complete file inventories. Ordinary runtime locks retain existing owner-retirement protocols. Historical configuration on an old remote branch is not an untracked current-branch file; do not delete manifests across branches or rewrite history to fabricate cleanup. diff --git a/.agents/rulebook/domains/build-native/hosts.md b/.agents/rulebook/domains/build-native/hosts.md new file mode 100644 index 000000000..4e9d5516b --- /dev/null +++ b/.agents/rulebook/domains/build-native/hosts.md @@ -0,0 +1,15 @@ +--- +paths: ["build/**", "backends/**", "platforms/**", ".github/**", "Directory.Build.props", "Directory.Build.targets", "Directory.Solution.props", "Directory.Solution.targets"] +tags: [build-host, native] +--- +# Hosts and unified builds + +## 25. Hosts, platform targets and unified builds + +- Shared Foundation, Shell and Player Runtime do not detect capabilities with OperatingSystem.IsBrowser. Platform entries inject frame scheduling, module activation, storage, logging and threading policy. Input uses the same Core Events entry. +- Each Native component has one project, separating common BGCS declarations from target profiles. The host single file is Generated/Bindings.cs; target managed output is artifacts/bindings////Generated/Bindings.cs. CMake intermediates remain in the owning toolchain's obj/native. Different targets and generation identities must not overwrite each other's output. +- BGCS-generated ABI carriers have explicit marshalling. Common MSBuild rules enable DisableRuntimeMarshalling for every binding component. Do not let the runtime reinterpret declarations or duplicate assembly attributes in components. Acceptance checks actual parameters, returns and callbacks, not merely sizeof. +- Cpp2C target bridges use artifacts/bindings////Native and share staging validation and atomic commit with the managed single file. They must not overwrite host Native/Generated. Target toolchains read the current request's generation description and select the bridge through CMake parameters. Emscripten SDK/Cache/Node/Python selection follows the target project's MSBuild workload; do not guess the highest installed package version. +- Development executable projects are only entry's InnoEngine.Editor and InnoEngine.Build. Inno.Build.Cli is a shared application library. Component toolchains, Shader compilation, Support Pack transactions and architecture validation remain composed libraries; MSBuild uses thin Task adapters. +- Ordinary Editor IDE/MSBuild Build and Publish prepare the current configuration's entire native closure through the same Native toolchain and deployment contracts. Failed builds must not report runnable output. Runtime Loaders load explicitly deployed files only; they do not build, probe repository caches or support old symbols. Preserve content-identical deployed files rather than recopying or replacing loaded DLLs. +- Support Pack core registers targets through IPlayerSupportPackSource and IPlayerSupportPackValidator, without concrete platform branches. Inno.Build.Composition accepts neutral binding contributions only. Built-in targets, managed deployments, Support Packs and product-component closures register only in Inno.Build.Distribution.Standard. Editor, CLI and MSBuild inject host context and consume the same immutable distribution. General Build libraries must not reference that composition library or Editor in reverse. Validate requested targets and managed-deployment capabilities before Support Pack provision or external tool execution; do not perform expensive preparation before rejecting unsupported combinations. diff --git a/.agents/rulebook/domains/build-native.md b/.agents/rulebook/domains/build-native/platform-products.md similarity index 51% rename from .agents/rulebook/domains/build-native.md rename to .agents/rulebook/domains/build-native/platform-products.md index 637a57986..01ad56fc6 100644 --- a/.agents/rulebook/domains/build-native.md +++ b/.agents/rulebook/domains/build-native/platform-products.md @@ -1,22 +1,9 @@ -# Build and Native +--- +paths: ["build/**", "backends/**", "platforms/**", ".github/**", "Directory.Build.props", "Directory.Build.targets", "Directory.Solution.props", "Directory.Solution.targets"] +tags: [platform-products, native] +--- +# Platform products -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - -## 25. Hosts, platform targets and unified builds - -- Shared Foundation, Shell and Player Runtime do not detect capabilities with OperatingSystem.IsBrowser. Platform entries inject frame scheduling, module activation, storage, logging and threading policy. Input uses the same Core Events entry. -- Each Native component has one project, separating common BGCS declarations from target profiles. The host single file is Generated/Bindings.cs; target managed output is artifacts/bindings////Generated/Bindings.cs. CMake intermediates remain in the owning toolchain's obj/native. Different targets and generation identities must not overwrite each other's output. -- BGCS-generated ABI carriers have explicit marshalling. Common MSBuild rules enable DisableRuntimeMarshalling for every binding component. Do not let the runtime reinterpret declarations or duplicate assembly attributes in components. Acceptance checks actual parameters, returns and callbacks, not merely sizeof. -- Cpp2C target bridges use artifacts/bindings////Native and share staging validation and atomic commit with the managed single file. They must not overwrite host Native/Generated. Target toolchains read the current request's generation description and select the bridge through CMake parameters. Emscripten SDK/Cache/Node/Python selection follows the target project's MSBuild workload; do not guess the highest installed package version. -- Development executable projects are only entry's InnoEngine.Editor and InnoEngine.Build. Inno.Build.Cli is a shared application library. Component toolchains, Shader compilation, Support Pack transactions and architecture validation remain composed libraries; MSBuild uses thin Task adapters. -- Ordinary Editor IDE/MSBuild Build and Publish prepare the current configuration's entire native closure through the same Native toolchain and deployment contracts. Failed builds must not report runnable output. Runtime Loaders load explicitly deployed files only; they do not build, probe repository caches or support old symbols. Preserve content-identical deployed files rather than recopying or replacing loaded DLLs. -- Support Pack core registers targets through IPlayerSupportPackSource and IPlayerSupportPackValidator, without concrete platform branches. Inno.Build.Composition accepts neutral binding contributions only. Built-in targets, managed deployments, Support Packs and product-component closures register only in Inno.Build.Distribution.Standard. Editor, CLI and MSBuild inject host context and consume the same immutable distribution. General Build libraries must not reference that composition library or Editor in reverse. Validate requested targets and managed-deployment capabilities before Support Pack provision or external tool execution; do not perform expensive preparation before rejecting unsupported combinations. - - - - ## 28. Platforms, shared backends and product composition - Organize shared code by responsibility, system/SDK integration by platform, builds by explicit targets including architecture and ABI, and Editor/Player by product composition. Desktop is not a target. Declare tool host, runtime target, product and managed deployment separately. @@ -48,24 +35,3 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - ImGui viewport position and logical size coordinate through platform events and ImGui getter/setter protocols. Drawable-metrics synchronization must not overwrite requested position/size or generate Move/Resize requests, avoiding feedback that interferes with dragging. - Both entries use ordinary ProjectReferences and direct public calls. Do not restore prebuilt Editor receipts, CLI-started workers, runtime child MSBuild or shared .run mechanisms. Only an entry may lift Solution build suppression for its own conditional product references; this does not bring other host products into default builds. - - - - -## 29. Backend integration and generation cost - -- Shared SDL window creation and focus reading have one backend owner; platform integrations handle actual SDK differences only. Shared BGFX Devices receive borrowed surfaces through IBgfxSurfaceIntegration and maintain no named-platform/ABI allowlist. Default catalogs receive explicit rendering factories. -- Closing additional windows first unregisters interaction, then retires renderer surfaces. Release native windows only after rendering confirms framebuffer-destruction commands were processed. Native callbacks neither wait for nor advance frames. Final drain occurs only on the owner thread, outside a frame and without an active graph/encoder; failure retains dependency owners. Task completion is not a general GPU fence. -- Component Bindings/bindings.props solely owns Native generation definitions shared by MSBuild and library calls. Toolchains depend only on INativeBindingGenerator; Inno.Build.Bindings owns concrete BGCS workflows, and Tasks map parameters/cancellation/logging only. A product closure requests one complete binding batch. Managed consumers retain Native-selected fingerprints and each component's Static/Shared request. Dynamic-initialization switches consume actual linkage only at Native compilation boundaries, never inferred from platform names or hosts. -- Binding configuration path variables expand only from the operation's frozen Native SDK environment. Direct libraries and MSBuild share target resolution. Do not mutate process environments or temporary PATH values to expose SDKs to generators. Missing configuration fails before candidate creation. -- Product binding selection belongs to that product's SDK intermediate directory and remains after Build/Publish for content-identical reuse. Only Native binding projects import it; transient selection files must not become common-domain compilation inputs. Identical content does not rewrite timestamps; changes replace atomically; product cleanup retires the file. Native Publish still verifies the current managed compilation's closure, fingerprints and source. Retaining a selection file does not hold a generation-cache read lease; actual consumers acquire independent protection. -- Revalidate freshness initially, after batch locks/generation and after each Native lock/compilation. Deduplicate complete content reads only within one explicit phase, never across waits/execution. Copy mutable source to freeze it; hardlinks do not make mutable input immutable. -- Cold CMake producers use the common executor to freeze recipe-declared workspace inputs. Browser aggregate component includes, bridges and arguments resolve into the same copied tree. Warm hits do not copy. External SDKs and outputs retain their own locations and owners; do not misroute outputs by replacing the entire repository root in strings. -- Task runtimes reuse only successful immutable publications within one IBuildEngine4 Build lifetime and the same complete request identity. Registries store BCL data only, never SDK owners, leases or private-ALC types. Each actual load boundary retains an independent owner; failures/cancellation are not cached. Core.IO leases coordinate shared restore writes, yielding/reacquiring MSBuild nodes while waiting and retaining lock files. -- Independent concurrent managed builds use explicit SDK ArtifactsPath values for separate bin/obj owners. Common rules must not override that output selection. Actual product Restore graphs select NuGet Runtime assets; content-addressed Native caches share through their own leases. Ordinary IDE bin/obj belongs to one active build; two independent processes writing the same paths is not supported concurrency. -- Neutral and product requests within one SDK graph also isolate actual outputs. With ArtifactsPath, select an ArtifactsProjectName containing product inputs before SDK default paths are established, preserving SDK configuration/TFM/RID pivots and explicit caller settings. Before building, the development Editor entry uses existing owned restore for its selected product's complete reference closure. It cannot rely on later platform-child restores to satisfy direct or SDK-added transitive references. -- Owned NuGet Restore uses standard ExcludeRestorePackageImports=true. Compilation uses a separate evaluation configuration including restored imports. A cached ProjectInstance must not carry old package content items into new assembly outputs. Package-name exceptions, patched NuGet imports and cache deletion must not conceal mixed artifacts. -- NuGet dependencies use ordinary csproj PackageReferences and SDK Restore. Do not enable, generate or commit dependency lockfiles, or maintain per-project/host/RID/AOT/trimming lock inventories and naming schemes. Official declarations own package versions; BGCS retains its unified exact version. Consumers read actual SDK-evaluated assets/package content. CI performs ordinary restore and verifies builds, package identities and source hygiene. Custom dependency resolvers, clearing real SDK properties and ignore rules must not replace the correct flow. Core IO leases for concurrency, process ownership and atomic publication are not dependency locking and must remain. - -- Engine-managed build SDK working caches and coordination locks belong inside the corresponding artifacts/obj or explicit output owner. Do not retain global ignore rules or validation exemptions for retired cache locations in source directories. Before removing old project directories, verify current project/restore graphs, Git ownership, symlinks, active processes and complete file inventories. Ordinary runtime locks retain existing owner-retirement protocols. Historical configuration on an old remote branch is not an untracked current-branch file; do not delete manifests across branches or rewrite history to fabricate cleanup. - diff --git a/.agents/rulebook/domains/editor/projects.md b/.agents/rulebook/domains/editor/projects.md new file mode 100644 index 000000000..b73b06bee --- /dev/null +++ b/.agents/rulebook/domains/editor/projects.md @@ -0,0 +1,14 @@ +--- +paths: ["src/composition/editor/**"] +tags: [editor-projects] +--- +# Editor projects + +## 13. Editor projects and reference boundaries +- Business source in each project under `src/composition/editor` uses a namespace exactly matching its csproj/assembly name. Feature directories organize files without adding namespace segments. For example, types under Inno.Editor.Inspection/PropertyDrawing still use namespace Inno.Editor.Inspection. +- Reusable InspectionDrawers, PropertyDrawers, Registries and serialized-property renderers belong to Inno.Editor.Inspection. Business Panels implement specific Drawers in their own projects and must not reference Inno.Editor.Panel.Inspector merely to extend inspection presentation. +- The sole namespace exception is Inno.Editor.ImGui/Widgets: all its types use namespace Inno.Editor.ImGui.ImGuiWidget. +- Inno.Editor.ImGui/Widgets contains only ImGuiWidget.*.cs files. Each widget's presentation, options, results and private state belong together in ImGuiWidget..cs. Do not create separate Widget helper files. +- Organize Editor project directories by independently understandable capabilities, such as Interactions, Documents, Zoom and PropertyDrawing. Do not mechanically scatter one feature's Actions, Menus, DragDrop, Runtime and Presentation into tiny type-role directories. Ambiguous Internal directories are prohibited; C# declarations, not directory names, express accessibility. +- Group Editor csproj ProjectReferences by public API boundary: the first ItemGroup contains only implementation dependencies absent from all public/protected APIs, each with PrivateAssets="compile"; the second contains only dependencies actually exposed through public signatures, base classes or interfaces. Remove unused references. +- Determine public reference visibility from actual API signatures, not merely runtime assembly use. Recheck the groups after changing public types, base classes, parameters, returns or properties. diff --git a/.agents/rulebook/domains/editor/state.md b/.agents/rulebook/domains/editor/state.md new file mode 100644 index 000000000..a4fed0c30 --- /dev/null +++ b/.agents/rulebook/domains/editor/state.md @@ -0,0 +1,24 @@ +--- +paths: ["src/composition/editor/**", "tests/editor/**"] +tags: [editor-state] +--- +# Editor state + +## 14. Editor History and Workspace state +- Reversible Editor data changes use EditorInteractions.history. Do not keep another Undo stack in a Panel or treat a simple inverse Action as the general model. +- Feature Modules apply the domain change first, then record it with RecordApplied(name, EditorHistoryChange). History payloads contain only stable protocol kinds, persistent IDs, Stable Type IDs, paths, indexes, scalars and neutral serialized bytes. They must not capture runtime objects, Plugin Types, extension instances or collectible-ALC delegates. +- Every reload-safe protocol declares [EditorHistoryHandler(kind)]. Handler Query only checks current-generation availability; Apply rolls back partial modifications on failure. Its Registry participates in candidate construction and atomic switching with the other Editor Registries. +- RecordValue, delegate-based Execute and derived EditorHistoryOperation are permitted only for Host-only compatibility workflows. These runtime-bound entries are truncated when extension generations change and must not serve EditorScripts or long-lived Scene/Asset records. +- Stable mergeKeys apply only to continuous input for the same logical value. Do not merge boolean toggles, creation, deletion or ordering. Use BeginTransaction for multiple steps, with each child independently atomic. +- Failed Undo/Redo leaves the operation on its original stack without moving pointers or overwriting new state. New operations release the Redo branch. Evicted/cleared operations release their files, objects and Plugin-generation references. +- EditorHistoryOptions automatically spills large payloads to /Library/Editor/History. Entry, resident-byte and disk-byte budgets all constrain History. Its cache does not enter editor.ini, Asset metadata or Scene serialization. +- Pure workflows such as saving, opening and selection do not enter data Undo by default. Record only the data portion when they actually modify Project data. +- Cross-startup Project semantic state belongs directly to Modules/Panels. Their Attributes require stable, globally unique IDs, and protected Capture(EditorState)/Restore(EditorState) hooks participate in persistence. Extensions use only Get/Set on the parameter object, without exposing JSON implementations in public/protected APIs. Types that do not override Capture do not enter state IO. Do not restore separate Workspace interfaces, readers/writers or second state IDs. Persistent values must be neutral and resolvable again. +- editor.ini is the unified readable Project-level Editor settings document. Standard ImGui sections store layout; each Module/Panel uses [InnoEditor][Module.] or [InnoEditor][Panel.]; Panel switches use [InnoEditor][Panels]. Do not wrap the entire Workspace in Base64 or one opaque payload. Do not persist Undo stacks, dirty Scene content, runtime references or compilation intermediate state. +- The standard Host's embedded resource supplies a new Project's default layout. Core receives a neutral initial document and reuses Core IO atomic writing. Initialize only when the file does not exist; do not overwrite an existing or deliberately empty editor.ini. Templates contain no example Scenes, Asset IDs, Plugin state, Selection, History or temporary popups. +- Editor Selection is transient interaction state for the current session and must not enter editor.ini. Workspace may save independently meaningful navigation positions, open documents and active documents. Startup must not automatically restore Asset, Scene, GameObject, Component or System selection. +- Normal Editor shutdown captures every stateful Module/Panel, then the latest ImGui layout, then forces one atomic write of the complete editor.ini before stopping Modules or unloading Scenes. Throttled runtime saves remain allowed but do not replace shutdown saving. +- All Editor Scene edits use Inno.Editor.Scene.SceneEdits. Ordinary properties store only one property's bytes; Components/Systems store element identity/type/index/state; GameObject deletion stores the minimal subtree; hierarchy changes store only affected placements. Do not serialize or restore an entire Scene for small edits. +- Module/Panel restoration tolerates missing Assets, damaged payloads and script types not yet present in TypeCache. Do not destroy the current editable state before the candidate is fully prepared. +- A stateful Module/Panel must successfully complete protected Restore once before Capture may overwrite its disk section. Extension Registry refresh may reenter during startup/script activation. The restoration coordinator weakly tracks restoring/restored state per instance, prevents reentrant callbacks and does not assume an instance retained in a new snapshot has already been restored. +- Scene Workspace restoration distinguishes an actually missing source file from an Asset Source Index awaiting its first reconciliation. If physical source still exists, retain pending Scene setup and retry. Do not overwrite Project settings with a temporarily empty runtime Scene collection. Editor permits no loaded Scenes; restoration, startup and deletion of the last Scene must not implicitly create an Untitled Scene. diff --git a/.agents/rulebook/domains/editor.md b/.agents/rulebook/domains/editor/ui.md similarity index 64% rename from .agents/rulebook/domains/editor.md rename to .agents/rulebook/domains/editor/ui.md index 8f3945c5c..962c28c23 100644 --- a/.agents/rulebook/domains/editor.md +++ b/.agents/rulebook/domains/editor/ui.md @@ -1,43 +1,9 @@ -# Editor - -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - -## 13. Editor projects and reference boundaries -- Business source in each project under `src/composition/editor` uses a namespace exactly matching its csproj/assembly name. Feature directories organize files without adding namespace segments. For example, types under Inno.Editor.Inspection/PropertyDrawing still use namespace Inno.Editor.Inspection. -- Reusable InspectionDrawers, PropertyDrawers, Registries and serialized-property renderers belong to Inno.Editor.Inspection. Business Panels implement specific Drawers in their own projects and must not reference Inno.Editor.Panel.Inspector merely to extend inspection presentation. -- The sole namespace exception is Inno.Editor.ImGui/Widgets: all its types use namespace Inno.Editor.ImGui.ImGuiWidget. -- Inno.Editor.ImGui/Widgets contains only ImGuiWidget.*.cs files. Each widget's presentation, options, results and private state belong together in ImGuiWidget..cs. Do not create separate Widget helper files. -- Organize Editor project directories by independently understandable capabilities, such as Interactions, Documents, Zoom and PropertyDrawing. Do not mechanically scatter one feature's Actions, Menus, DragDrop, Runtime and Presentation into tiny type-role directories. Ambiguous Internal directories are prohibited; C# declarations, not directory names, express accessibility. -- Group Editor csproj ProjectReferences by public API boundary: the first ItemGroup contains only implementation dependencies absent from all public/protected APIs, each with PrivateAssets="compile"; the second contains only dependencies actually exposed through public signatures, base classes or interfaces. Remove unused references. -- Determine public reference visibility from actual API signatures, not merely runtime assembly use. Recheck the groups after changing public types, base classes, parameters, returns or properties. - - - - -## 14. Editor History and Workspace state -- Reversible Editor data changes use EditorInteractions.history. Do not keep another Undo stack in a Panel or treat a simple inverse Action as the general model. -- Feature Modules apply the domain change first, then record it with RecordApplied(name, EditorHistoryChange). History payloads contain only stable protocol kinds, persistent IDs, Stable Type IDs, paths, indexes, scalars and neutral serialized bytes. They must not capture runtime objects, Plugin Types, extension instances or collectible-ALC delegates. -- Every reload-safe protocol declares [EditorHistoryHandler(kind)]. Handler Query only checks current-generation availability; Apply rolls back partial modifications on failure. Its Registry participates in candidate construction and atomic switching with the other Editor Registries. -- RecordValue, delegate-based Execute and derived EditorHistoryOperation are permitted only for Host-only compatibility workflows. These runtime-bound entries are truncated when extension generations change and must not serve EditorScripts or long-lived Scene/Asset records. -- Stable mergeKeys apply only to continuous input for the same logical value. Do not merge boolean toggles, creation, deletion or ordering. Use BeginTransaction for multiple steps, with each child independently atomic. -- Failed Undo/Redo leaves the operation on its original stack without moving pointers or overwriting new state. New operations release the Redo branch. Evicted/cleared operations release their files, objects and Plugin-generation references. -- EditorHistoryOptions automatically spills large payloads to /Library/Editor/History. Entry, resident-byte and disk-byte budgets all constrain History. Its cache does not enter editor.ini, Asset metadata or Scene serialization. -- Pure workflows such as saving, opening and selection do not enter data Undo by default. Record only the data portion when they actually modify Project data. -- Cross-startup Project semantic state belongs directly to Modules/Panels. Their Attributes require stable, globally unique IDs, and protected Capture(EditorState)/Restore(EditorState) hooks participate in persistence. Extensions use only Get/Set on the parameter object, without exposing JSON implementations in public/protected APIs. Types that do not override Capture do not enter state IO. Do not restore separate Workspace interfaces, readers/writers or second state IDs. Persistent values must be neutral and resolvable again. -- editor.ini is the unified readable Project-level Editor settings document. Standard ImGui sections store layout; each Module/Panel uses [InnoEditor][Module.] or [InnoEditor][Panel.]; Panel switches use [InnoEditor][Panels]. Do not wrap the entire Workspace in Base64 or one opaque payload. Do not persist Undo stacks, dirty Scene content, runtime references or compilation intermediate state. -- The standard Host's embedded resource supplies a new Project's default layout. Core receives a neutral initial document and reuses Core IO atomic writing. Initialize only when the file does not exist; do not overwrite an existing or deliberately empty editor.ini. Templates contain no example Scenes, Asset IDs, Plugin state, Selection, History or temporary popups. -- Editor Selection is transient interaction state for the current session and must not enter editor.ini. Workspace may save independently meaningful navigation positions, open documents and active documents. Startup must not automatically restore Asset, Scene, GameObject, Component or System selection. -- Normal Editor shutdown captures every stateful Module/Panel, then the latest ImGui layout, then forces one atomic write of the complete editor.ini before stopping Modules or unloading Scenes. Throttled runtime saves remain allowed but do not replace shutdown saving. -- All Editor Scene edits use Inno.Editor.Scene.SceneEdits. Ordinary properties store only one property's bytes; Components/Systems store element identity/type/index/state; GameObject deletion stores the minimal subtree; hierarchy changes store only affected placements. Do not serialize or restore an entire Scene for small edits. -- Module/Panel restoration tolerates missing Assets, damaged payloads and script types not yet present in TypeCache. Do not destroy the current editable state before the candidate is fully prepared. -- A stateful Module/Panel must successfully complete protected Restore once before Capture may overwrite its disk section. Extension Registry refresh may reenter during startup/script activation. The restoration coordinator weakly tracks restoring/restored state per instance, prevents reentrant callbacks and does not assume an instance retained in a new snapshot has already been restored. -- Scene Workspace restoration distinguishes an actually missing source file from an Asset Source Index awaiting its first reconciliation. If physical source still exists, retain pending Scene setup and retry. Do not overwrite Project settings with a temporarily empty runtime Scene collection. Editor permits no loaded Scenes; restoration, startup and deletion of the last Scene must not implicitly create an Untitled Scene. - - - - +--- +paths: ["src/composition/editor/presentation/**", "src/composition/editor/panels/**", "**/*ImGui*", "**/*ImGui*/**"] +tags: [editor-layout, editor-acceptance, editor-standard] +--- +# Editor UI + ## 24. Editor forms and scrolling - Each visible region has one scrolling owner. Parent Panel/Modal, layout Child and content Child must not produce scrollbars in the same direction for the same content. A parent hosting a fill-area scrollable Child disables the corresponding scrolling. @@ -47,10 +13,7 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Align Popup size constraints to pixels at the Widget boundary: floor upper bounds and ceil required content sizes to prevent false overflow when ImGui truncates fractional padding. Regressions cover fractional zoom such as 85%, 90% and 110%, not only integer/half-integer padding. Do not conceal failures with NoScrollbar. - Custom hit regions check both rectangle containment and whether their owning ImGui window is the currently interactive foreground window. Floating windows, Popups and Modals must block underlying Panel close actions, canvas gestures and game input. Platform events still use Inno.Core.Events; ImGui determines visible-UI hits/focus only. Play Sessions have an independent Input backend receiving events filtered by Game View focus policy, without a second event bus. - Tree-row disclosure controls, text and overlay buttons each own an independent hit region. Native TreeNodes must not cover custom text using full-row SpanFullWidth/AllowOverlap. Regressions cover prior hover and same-frame move/press, text double-click, arrow expansion and overlay buttons. Clicking must not require an extra hover frame. - - - ## 32. Editor UI ownership and acceptance - Domain editing in `features` must remain independent from native UI, Panels and Workbench. Panels compose feature APIs; they do not reference other Panels. Reusable controls belong to the session-owned ImGui adapter, and generic Graph presentation cannot depend on Shader semantics. @@ -73,10 +36,7 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Workflow progress and cancellation are bound to the original owner and operation identity. Late callbacks cannot overwrite a newer request or a cancellation state, and progress presentation cannot weaken publication or generation retirement. - CI and local acceptance must follow the actual changed owners. Use scoped Editor verification for bounded UI changes; retain full verification for build, platform, backend, SDK, shared runtime or unknown owners. Record omitted checks explicitly and never bypass production validation to shorten CI. - - - ## Delivery and acceptance Changes update source, callers, project references, public XML, documentation and applicable tests together. Use real public contracts and replaceable boundaries, without IVT, private reflection or test backdoors. @@ -92,10 +52,7 @@ Distinguish native-borrow verification from pure value conversion according to a EditorUiInput Control/Super values mean physical modifiers, not native controls' internal shortcut normalization. The presentation boundary reconstructs them from the current Context's keyboard configuration. List selection reuses those snapshot semantics; platforms still choose primary modifiers through EditorKeyboardPolicy. Native text controls retain that Context's input conventions. Tests explicitly declare their keyboard configuration and cover Control/Super combined with both native modes rather than relying on runner defaults. Final reports separately assess architecture, organization, state/lifetimes, abstraction, reuse, style, extensibility, interaction, Undo/Redo, menus and granularity, with evidence and limitations for each. Neat directories, test counts or successful startup do not replace visual/input acceptance, repeated reload, resource convergence and paired performance measurements. - - - ## Dynamic Modal state and size - Window size, wrapping and drawing use one snapshot for the current frame, never the previous message's height. @@ -112,4 +69,3 @@ Engine CI selects checks from the complete Git change set and actual SDK depende Inno.Tooling.Validation is the sole plan owner and does not weaken production-build integrity. Moves cover old and new owners; PRs use actual merge candidates and merge bases; local plans include staged, unstaged and untracked files. Record selection reasons and exclusions. A bounded pass is not a complete product/device matrix pass. Unavailable required environments, missing results and empty required tests fail or block. Cheap architecture rules remain repository-wide. Prepare compilation metadata and documentation examples from actual dependencies, sharing the batch graph across architecture, tests and documentation. Impact analysis includes project references, imports, source, resources and generated inputs. Text similarity cannot declare SDK/TFM/shared-build changes irrelevant. Log directories, reports, commits/pushes and session recovery do not justify repeated acceptance. Reuse only deterministic evidence with matching inputs, tools, environments and artifacts. - diff --git a/.agents/rulebook/domains/identity-reload.md b/.agents/rulebook/domains/identity-reload.md index 750465ce8..5f899629f 100644 --- a/.agents/rulebook/domains/identity-reload.md +++ b/.agents/rulebook/domains/identity-reload.md @@ -1,9 +1,9 @@ +--- +paths: ["src/content/assets/**", "src/content/scene/**", "src/content/references/**", "src/foundation/core/Inno.Core.Identity/**", "src/foundation/extensibility/Inno.Extensibility.Reload/**", "tests/assets/**", "tests/scene/**", "src/runtime/plugins/**", "tests/plugins/**", "src/foundation/scripting/**", "src/runtime/scripting/**", "tests/scripting/**", "**/*ScriptingApi*"] +tags: [identity-reload, serialization, reload, identity-standard] +--- # Identity and reload -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - ## 20. Identity, Missing, references and reload - Resolve live objects through `Inno.Core.Identity` when crossing UI, callback, queue, frame, Scene, Asset, Scripting or Plugin-generation boundaries. Use `Identity.runtimeId` for transient resolution within the current domain. Persistence, History and cross-generation restoration store only `Identity.persistentId`. Runtime IDs must never enter Scenes, Prefabs, Asset metadata, Settings, Plugin manifests or History. - Stable Type IDs, semantic IDs such as Plugin/Feature/Importer IDs, Artifact keys and generation handles retain separate meanings and must not be confused with object Identity. Domain secondary indexes may map paths/semantic keys to persistent IDs or immutable records, but cannot become another authority for live objects across generations. @@ -15,10 +15,7 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Scripting, Plugin, Asset type, Serializer and extension generations participate in the shared candidate transaction. Successful retirement of old collectible ALCs requires Full GC → `GC.WaitForPendingFinalizers()` → Full GC and weak monitors confirming every context is unreachable. Before that barrier completes, reload must not report Success or permit another reload, Play, Build or Export. - An unload-verification timeout causes an explicit exception and Faulted state. Never clear still-Pending monitors and continue. Failures identify module/domain/scope/generation. A Faulted process cannot continue generation transactions and requires a full Host restart. Tests cover old-generation strong references from statics, events, tasks, threads, AsyncLocal, GCHandle, native callbacks and Editor transient state. - The full specification, target APIs, current gaps and test matrix are in the selected InnoEngine.Docs snapshot's `content/en/architecture/identity-and-recovery.md` and linked source validation records. Reconcile those authorities when changing Identity, Scripting, Plugins, Assets, Scene, Editor Interactions/History or any collectible extension. - - - ## 12. Required architecture checks Once they can be implemented reliably with low false-positive rates, the Architecture Tool must check at least: @@ -37,10 +34,7 @@ Once they can be implemented reliably with low false-positive rates, the Archite 12. Secondary indexes map domain keys only to identities/immutable records, never becoming live-object authorities across generations. Use Roslyn/metadata analysis for rules requiring C# type and field understanding. Keyword scans that misclassify contentVersion, list indexes or backend handles do not replace semantic checks. - - - ## 13. Test matrix ### 13.1 Identity @@ -101,13 +95,9 @@ Also verify: - Success is published only after every monitor is Completed. - Shadow generation storage is cleaned after success. - Shutdown aggregates and reports still-Pending/Faulted generations instead of silently exiting. - - - ## 14. Acceptance and change requirements Changes to identity, resolvers, Missing or reload must run the preceding matrix and update domain callers and shutdown order together. A count of passing tests does not replace evidence of cross-domain production transactions, failure compensation and old-ALC unreachability. Maintain current execution status in [current acceptance](../../records/acceptance/current.md) and [open items](../../records/open-items.md). This page does not maintain a second progress ledger or historical test count. - diff --git a/.agents/rulebook/domains/plugins.md b/.agents/rulebook/domains/plugins.md index 7eaf1e689..3895d21e8 100644 --- a/.agents/rulebook/domains/plugins.md +++ b/.agents/rulebook/domains/plugins.md @@ -1,9 +1,9 @@ +--- +paths: ["src/runtime/plugins/**", "tests/plugins/**"] +tags: [plugins] +--- # Plugins -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - ## 18. Plugin and structured-content boundaries - The Project root has sibling `Plugins` and `Assets` directories. `Assets` is the sole official writable authoring source. Export an entire Project directly to `.iplugin` with File > Export as Plugin; do not create a PluginDefinitionAsset or a second package-authoring asset. `Plugins/*.iplugin` is the sole installation source. Folder Plugins, `.zip` Plugins and other extensions are unsupported. Fully validate installed packages and mount them as read-only Asset Sources in the existing Asset Catalog, Importer, dependency graph and Artifact flow. Do not create a Plugin-specific asset database. - File Browser and all Asset mutation APIs must treat installed `.iplugin` content as logically read-only. External replacement of an `.iplugin` updates installed content and starts a candidate transaction; it grants no Editor write permission. `Library/Plugins` always remains a noneditable, fully rebuildable cache. @@ -13,4 +13,3 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Plugin extensions must reuse existing AssemblyDomain.InnoPlugin, collectible ALC, TypeCache, TypeRegistry and candidate transactions. Persistent state must not retain Plugin Types, instances or delegates. - All structured assets, Graphs, Plugin manifests and Project Settings must use ISerializable, SerializableProperty, Serialization Converters and SerializationManager. Only inherently textual content, such as C#, Shader source/includes and ordinary documentation, may remain text. Do not create separate JSON persistence paths for Rendering, Plugins or Settings. - Plugins may contribute assets, Shaders, Pipelines, Importers, Components, Editor extensions, settings and gameplay code together. Manifests must not maintain per-domain type lists. Stable attributes and TypeRegistry continue to discover concrete extensions automatically. - diff --git a/.agents/rulebook/domains/rendering.md b/.agents/rulebook/domains/rendering.md index 1caf393d9..eeafa8cf5 100644 --- a/.agents/rulebook/domains/rendering.md +++ b/.agents/rulebook/domains/rendering.md @@ -1,9 +1,9 @@ +--- +paths: ["src/services/rendering/**", "src/adapters/rendering/**", "tests/rendering/**"] +tags: [rendering, content-frame] +--- # Rendering -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - ## 17. Rendering boundaries - Rendering's public design must satisfy cross-platform support, API usability, flexible extension and low coupling together. Implementation convenience does not justify sacrificing any of them. - Only `Inno.Adapter.Rendering.Bgfx`, BGFX build toolchains and the corresponding native tests may reference `Inno.Native.Bgfx`. BGFX handles, View IDs, native pointers and BGFX enums must not appear in other projects' public/protected APIs. @@ -14,10 +14,7 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Project script extensions may use only backend-neutral Rendering APIs. Isolate extension failures. Activate successful candidates atomically only at frame-safe points, retaining last-good Pipelines, Shaders and GPU resources. - Rendering Core provides graphics mechanisms only. It must not embed 2D, 2.5D, 3D, PBR, Forward, Deferred, Light, Shadow, Camera, MeshRenderer or any concrete rendering worldview. All concrete rendering models must be composable from scratch through Project scripts or Plugins. - Shaders, Techniques, Materials and Pipelines compose through open Stable ID contracts. The core must not maintain closed lists of Pass Tags, Render Paths, resource semantics or quality settings. - - - ## 27. Content, rendering layers and frame ownership - `Inno.Content` depends only on necessary Foundation contracts and unifies logical ContentKeys, Pack indexes, read budgets and read-only leases. Shared Player, Runtime Session and AssetDatabase code does not read deployment files or create physical directories. Concrete content sources own files, HTTP, caches and owned streams. Asset consumption reuses `ArtifactLease.OpenRead()`; each opened stream holds an independent pin. @@ -28,4 +25,3 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Rebuild Contributor snapshots only when registration changes, and freeze them at frame start. Clear extension references from private scratch on normal frames, failures and retirement. Graph Validate performs analysis only; final Compile performs complete resource allocation exactly once. Mutation rollback restores both graph and validation state. Do not modify an accepted pass. - Native recipes declare their actual input closure and tool identities. Share the initial input scan within an operation, retaining necessary revalidation after waiting for a lease and before publication. An unrelated assembly MVID cannot replace a component recipe identity. Unify Task bootstrapping and isolate target properties. Content-identical native deployment must not copy files, replace loaded DLLs or update mtimes. - Shared compilation of a Task's complete execution closure uses Core IO leases to coordinate cross-process writes and releases MSBuild nodes while waiting. The minimal bootstrap publisher uses operation-private intermediate state. Existing immutable-publication and reader protocols then manage loading and retirement. - diff --git a/.agents/rulebook/domains/scripting.md b/.agents/rulebook/domains/scripting.md index 9fa19d005..fc18c8c55 100644 --- a/.agents/rulebook/domains/scripting.md +++ b/.agents/rulebook/domains/scripting.md @@ -1,9 +1,9 @@ +--- +paths: ["src/foundation/scripting/**", "src/runtime/scripting/**", "tests/scripting/**", "**/*ScriptingApi*"] +tags: [scripting] +--- # Scripting -Load complete rule units. The [registry](../coverage.json) owns routing and provenance. - - - ## 12. Scripting API manifests - Each project participating in the script API has exactly one `Properties/ScriptingApi.cs`. Do not scatter export attributes through business source or centralize them in a manifest project that depends back on every module. - Export each type explicitly with `ScriptingApiExport`. Do not restore metadata/property mechanisms that expose an assembly's entire public API. @@ -12,4 +12,3 @@ Load complete rule units. The [registry](../coverage.json) owns routing and prov - Runtime compilation and IDE projects must use the same trimmed reference assemblies. Verify both paths after changing a manifest. - Compilation-wide/global usings are completely prohibited, including handwritten directives, MSBuild `Using` items, implicit imports and metadata injection. Every source and script file must explicitly declare its own ordinary `using` directives. - Scripts must use logical namespaces, such as `using InnoEngine.Scene;`, and must not directly use implementation-side `Inno.*` namespaces. - diff --git a/.agents/rulebook/no-legacy.md b/.agents/rulebook/no-legacy.md new file mode 100644 index 000000000..5917e1f56 --- /dev/null +++ b/.agents/rulebook/no-legacy.md @@ -0,0 +1,13 @@ +--- +paths: ["src/runtime/plugins/**", "tests/plugins/**"] +tags: [no-legacy, new-boundary] +--- +# No legacy compatibility + +## 15. No legacy compatibility or schema versions +- InnoEngine is a personal engine whose current source and current Project data evolve together. New or changed features do not support old files, schemas, fields, cache directories, namespaces, APIs or serialization layouts. Do not add fallback readers, migrations, compatibility aliases, former IDs, deprecated wrappers or dual writes for them. +- Persistence models, Attributes, Importers, Build Processors, History, Workspaces, Scenes, Prefabs, Asset metadata, Catalogs and script manifests must not introduce legacy-adaptation fields such as `version`, `schemaVersion`, `formatVersion` or `formerVersion`. When a format changes, update the current writer, reader, tests, documentation and Project data directly. Old data may be explicitly invalidated and regenerated. +- Do not reserve migration branches for hypothetical future compatibility. Only an explicit user request to import a particular old format permits a one-time converter with a clear boundary. Conversion logic must not enter normal runtime paths. +- Update all callers when deleting or refactoring an API. Do not retain old overloads, namespace facades, forwarding types or `[Obsolete]` compatibility layers unless the user explicitly requests them. +- These rules permit runtime identities required for current correctness, including TypeCache/Assembly generations, concurrency revisions, change counters, content hashes, artifact fingerprints, MVIDs, job-handle generations and strict magic/headers used only to reject damaged or incorrect input formats. They must not become mechanisms for reading multiple legacy schema generations. +- When reviewing or cleaning implementations named `version`, `legacy`, `migration`, `compatibility`, `former` or `deprecated`, first determine whether they serve only old data/APIs. If so, remove them together with their tests and documentation rather than extending them. diff --git a/.agents/rulebook/projects.md b/.agents/rulebook/projects.md new file mode 100644 index 000000000..21efc3f38 --- /dev/null +++ b/.agents/rulebook/projects.md @@ -0,0 +1,38 @@ +--- +paths: ["**/*.csproj", "**/*.sln", "**/*.slnx", "**/*.props", "**/*.targets"] +tags: [solution, directories, new-boundary] +--- +# Solutions and projects + +## 10. Directory boundaries +- `src/foundation`: Core, extension catalogs, types and generation contracts. +- `src/content`: Assets, References, Scene and Animation. +- `src/services`: backend-neutral domain contracts and runtime services. +- `src/runtime`: Runtime, deployment, generators, Plugins and authoring-time scripting workflows. +- `src/adapters`: neutral SPIs, open Provider/Catalog contracts and Core Events input implementations. +- `backends/`: shared backend runtime, native code and build recipes; each component has one source owner. Component tests belong to `tests/backends/`. +- `platforms/`: system and SDK integration, explicit targets, thin Editor/Player entries, layouts and Support Packs. A platform must not reference another platform. +- `src/composition`: default engine, Shell, Player and Editor composition entries. +- `entry`: the two lightweight development entries and current-host routing. Other production layers must not reference it. `Inno.Packages.props` pins NuGet versions for the BGCS package family; no source-dependency entry is provided. +- `build`, `tools`, `tests`: neutral unified builds, concrete distribution registration, validation libraries and tests. All engine-owned tests, fixtures and test support belong to the root `tests` tree; upstream tests inside `extern` retain their upstream owner. Production projects must not reference test projects or test support. +- Place new files in directories matching the existing layers and responsibilities wherever possible. + +## 26. Solutions and project files + +- Solution Folders represent actual architectural responsibilities. Remove empty groups containing neither valid projects nor Solution Items. Avoid unnecessary single-project wrapper groups for small project collections. +- Authored projects under `entry`, `src`, `backends`, `platforms`, `build`, `tools` and `tests` belong in the Solution, including binding-generation extensions and test fixtures. Exclude `obj`, `artifacts` and independent third-party projects in extern. A project without incoming ProjectReferences is not necessarily unused: check host entries, MSBuild tool calls and generator configuration before removing it. +- Use two-space indentation in `.csproj`, `.props` and `.targets`, blank lines between top-level responsibility blocks, one property per line in long property lists, and `/` in relative ProjectReference paths. +- Merge adjacent reference groups only when their conditions and reference visibility match. Do not reorder Imports, Properties or Targets, or change conditions, metadata or evaluation order. Preserve Editor public/implementation reference boundaries. +- Detailed rules are in `.agents/rulebook/coding.md`. After reorganization, verify valid XML, Solution project identities and configurations, then run affected builds and architecture validation. +- After phases of long builds or acceptance, clean this operation's obsolete tool snapshots, private load directories and test-browser profiles, and check free disk space. Before cleanup, verify the explicit owner, resolved absolute paths, symbolic links and active processes. Retain current artifacts and acceptance logs; do not clean user or SDK global caches. Logical sizes of hardlinked/compressed files do not establish physically reclaimed space. + +## 12. Solution and MSBuild readability + +- Solution Folders express actual responsibility layers. Remove groups without projects or valid Solution Items. Small repositories do not need extra categories wrapping single projects. +- Include all authored source projects in the Solution, including binding-generation extensions and test fixtures; exclude generated artifacts and third-party projects. Before declaring a project without incoming references obsolete, check host entries, MSBuild tool calls and generation configuration. +- Use two-space indentation and LF in `.csproj`, `.props` and `.targets`, with one blank line between top-level responsibility blocks. Do not mix tabs and spaces. +- Keep simple declarations on one line. Put long attribute lists after the element name, one attribute per line. Do not split attribute values in ways that change paths, conditions or commands. +- Use `/` in relative ProjectReference paths. Group implementation dependencies separately from public-signature dependencies according to project rules. Do not mechanically merge groups with different conditions, visibility or responsibilities. +- Remove empty PropertyGroup/ItemGroup elements with no attributes, content or comments. Merge adjacent reference groups only when conditions and visibility match and no intervening evaluation step exists. +- MSBuild evaluates in order. Formatting-only cleanup verifies property values, conditions, metadata, Imports, Targets and effective project-reference order. General XML sorting is not safe project reorganization. +- Preserve actual platform conditions and SDK/toolchain constraints. Formatting platform projects must not move those concerns into neutral business layers. diff --git a/.agents/rulebook/validation.md b/.agents/rulebook/validation.md index 5a49f35ef..273fedc2f 100644 --- a/.agents/rulebook/validation.md +++ b/.agents/rulebook/validation.md @@ -1,24 +1,26 @@ +--- +paths: ["tests/**", "**/tests/**", "AGENTS.md", "CONTRIBUTING.md", ".agents/**"] +tags: [tests, compilation, completion, review, new-boundary, public-api, ownership, delivery, rules, skills, records] +--- # Validation -Load complete rule units. The [registry](coverage.json) owns routing and provenance. - - - ## 8. Test boundaries - Changes to regression, public-contract and validation-tool tests required by the task are permitted. Preserve existing assertions and failure scenarios. Unrelated test rewrites, weaker assertions, production entry points only for tests, InternalsVisibleTo and reflection bypasses are prohibited. - Select tests from the actual impact graph, behavioral contracts and execution prerequisites. Test filters must not conceal native build dependencies. - - - ## 9. Compilation safety - Before ending a conversation, do not leave visible compilation errors introduced within the changed target scope, including non-test code. - Explicitly identify potential compilation risks in the delivery description. - - - +## 10. Tests and acceptance + +- Use real public contracts and replaceable public boundaries. +- InternalsVisibleTo, test backdoors, reflection bypasses and widening internal visibility for tests are prohibited. +- Cover real success, failure, cancellation, boundary and lifecycle behavior. Do not write tests that merely repeat the implementation. +- Native calls, AOT, trimming and platform support require actual artifact evidence. +- Report build, test, SDK, host and device status separately. Unexecuted checks are not passes. + ## 19. Completion requirements for new systems - Define clear assembly/domain boundaries and minimal public entry points before implementing UI or platform adapters. Isolate platforms, storage, compilers and presentation behind replaceable contracts. Do not accumulate temporary workflows in Panel, Application or static utility classes. - Prefer explicit base classes or interfaces for extension discovery. When inheritance or an interface completely identifies an extension and no additional declaration data is required, do not add a parameterless marker Attribute. Attributes carry parameters or explicitly optional semantics that type relationships cannot express, such as stable IDs, ordering, scope and multiple-instance permission. Never make inheritance and a parameterless Attribute two registration conditions that must be synchronized. @@ -27,10 +29,7 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - Keep public APIs small and complete. Do not ask users to create companion assets, repeat manifests or change unrelated callers for information the engine can reliably derive. Explain each new public API's necessity and stable semantics in the delivery description. - InternalsVisibleTo, test backdoors, reflection bypasses and widening internal member visibility to simplify tests are strictly prohibited. Test behavior through real public contracts and replaceable public boundaries only. - Classify new projects and feature files by responsibility; match each filename to its primary type. A file contains closely related contracts or implementation only. Avoid ambiguous helper/internal directories and giant files containing unrelated types. - - - ## 30. Semantic review and delivery - Do not create or retain Agent.md, AGENTS.md or case variants in the BindGen-CS repository. Engine agent requirements belong only in the engine's own rules. @@ -39,4 +38,10 @@ Load complete rule units. The [registry](coverage.json) owns routing and provena - Verify extensibility through real callers, replaceable boundaries and applicable validation. Explain from actual code which owners must change to add a backend or platform. Unexecuted tests and abstract declarations are not evidence. - Every final delivery must briefly state this review's findings, actual validation evidence and unresolved or unavailable work. If verification is incomplete, say so; do not claim perfection or that everything passed. - Before ending execution, reconcile the issue's actual resolution criteria, all approved implementation and acceptance requirements, architectural clarity, foundational reuse and new regressions. When actionable work remains, update the remaining execution plan and continue automatically without requesting repeated approval. Deliver only after all applicable work is complete or external blockers that cannot be resolved independently are explicitly recorded. Stage progress or passing CI does not establish completion of the entire plan. - + +## 11. Change management + +- Formatting-only changes preserve syntax tokens, execution order, contracts and diagnostics. +- Validate naming, responsibility and behavior changes separately from pure formatting. +- Public API, reference-boundary and generation-protocol changes also update consumers, indexes, examples and architecture checks. +- Before completion, ensure the target scope compiles and record validation commands, results and remaining limitations. diff --git a/.agents/skills/inno-api-docs/SKILL.md b/.agents/skills/inno-api-docs/SKILL.md index 8d3fb98fc..eba181be9 100644 --- a/.agents/skills/inno-api-docs/SKILL.md +++ b/.agents/skills/inno-api-docs/SKILL.md @@ -3,7 +3,7 @@ name: inno-api-docs description: Maintain InnoEngine design, usage, API XML and examples against actual public and protected contracts. --- -Select applicable `wiki` and `xml` units through the rule loader with `-DocsRoot `. The [documentation rules](https://github.com/Wolfiora/InnoEngine.Docs/blob/main/.agents/rulebook/documentation.md) have one authority in that checkout; `main` is published and [`draft`](https://github.com/Wolfiora/InnoEngine.Docs/blob/draft/.agents/rulebook/documentation.md) is unpublished. Read its additional writing and presentation rules when editing authored content. Engine declarations and XML remain in the engine; narrative content belongs to Docs. +Select the `wiki` and `xml` tags through the rule script with `-DocsRoot `. The [documentation rules](https://github.com/Wolfiora/InnoEngine.Docs/blob/main/.agents/rulebook/documentation.md) have one authority in that checkout; `main` is published and [`draft`](https://github.com/Wolfiora/InnoEngine.Docs/blob/draft/.agents/rulebook/documentation.md) is unpublished. Read its additional writing and presentation rules when editing authored content. Engine declarations and XML remain in the engine; narrative content belongs to Docs. Use Build `docs search/read/symbol` against a prepared snapshot to locate task guidance, the authoritative project entry and exact qualified symbols. Read necessary associated contracts and explicit continuations. Search excerpts and API markers are not complete contracts or matching source verification evidence. diff --git a/.agents/skills/inno-change/SKILL.md b/.agents/skills/inno-change/SKILL.md index 50d4a3307..50b6d3cd8 100644 --- a/.agents/skills/inno-change/SKILL.md +++ b/.agents/skills/inno-change/SKILL.md @@ -3,7 +3,7 @@ name: inno-change description: Scope an InnoEngine implementation by actual owners, behavior changes, applicable rules and finite acceptance. --- -Confirm the branch, workspace changes and implementing owner; protect other sessions. Run `tests/ci/Test-AgentRules.ps1` from the engine root to select complete rule units by repository-relative paths and behavior tags. The [rulebook](../../rulebook/README.md) is their sole authority. +Confirm the branch, workspace changes and implementing owner; protect other sessions. Run `tests/ci/Test-AgentRules.ps1` from the engine root to select rule files by repository-relative paths and work tags. The [rulebook](../../rulebook/README.md) is their sole authority. When task guidance or an API contract is needed, select a prepared documentation snapshot. Use Build `docs search/read/symbol`, then verify relevant source and actual project relationships. Reuse loaded content while its identity and scope remain unchanged. Refresh after relevant edits; a query never creates a Docs candidate or certifies source API correctness. diff --git a/.agents/skills/inno-delivery/SKILL.md b/.agents/skills/inno-delivery/SKILL.md index 2a7aa74a6..e93eb87f4 100644 --- a/.agents/skills/inno-delivery/SKILL.md +++ b/.agents/skills/inno-delivery/SKILL.md @@ -3,7 +3,7 @@ name: inno-delivery description: Review InnoEngine semantic risks and matching evidence, then prepare accurate issues or pull requests and diagnose CI failures. --- -Select `delivery`, `review` and `notification` units through the rule loader; use the [delivery rules](../../rulebook/delivery.md). Review changed dependency directions, input authority, rollback, concurrency and resource retirement. Directory neatness and test counts do not prove correctness. +Select the `delivery`, `review` and `notification` tags through the rule script; use the [delivery rules](../../rulebook/delivery.md). Review changed dependency directions, input authority, rollback, concurrency and resource retirement. Directory neatness and test counts do not prove correctness. Reconcile the approved plan and every required result with current inputs. Distinguish missing implementation, unexecuted acceptance and external blockers. Report final behavior, actual checks, outstanding work and necessary action. Use English `type(scope): description` issue/PR titles and English bodies. Never promote historical evidence to a current pass. diff --git a/.agents/skills/inno-verify/SKILL.md b/.agents/skills/inno-verify/SKILL.md index fb7254947..2d98acc4a 100644 --- a/.agents/skills/inno-verify/SKILL.md +++ b/.agents/skills/inno-verify/SKILL.md @@ -3,7 +3,7 @@ name: inno-verify description: Plan and execute bounded InnoEngine validation; diagnose failures and reconcile evidence with current inputs. --- -Load applicable units from the [validation rules](../../rulebook/validation.md) through the rule selector. Use Build `validate plan/run/full/evidence`; inspect owners, reasons, environments, prerequisite artifacts and exclusions. The planner owns the check inventory. +Load the [validation rules](../../rulebook/validation.md) through the rule script. Use Build `validate plan/run/full/evidence`; inspect owners, reasons, environments, prerequisite artifacts and exclusions. The planner owns the check inventory. Check evidence identities before executing missing or invalid work. Commits, pushes, report edits and session recovery are not reasons to repeat valid checks. Record the exact invalidating input. Preserve the first failure and retry reason; do not rerun until a run happens to turn green. Unknown owners, empty required discovery, skipped jobs and unavailable environments are not passes. Device, performance, stress and lifecycle checks follow their actual obligations. diff --git a/.gitignore b/.gitignore index 9fc4472b7..1142e00d5 100644 --- a/.gitignore +++ b/.gitignore @@ -151,7 +151,6 @@ _TeamCity* # Coverlet is a free, cross platform Code Coverage Tool coverage*.json -!.agents/rulebook/coverage.json coverage*.xml coverage*.info diff --git a/AGENTS.md b/AGENTS.md index 33bd14305..3a88e6a59 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,8 +5,8 @@ Architecture, responsibility, dependency direction, low coupling and resource ow ## Start a task 1. Confirm the branch, workspace changes, owner, behavioral scope and finite acceptance. Protect other sessions. Adjacent repositories are read-only unless explicitly authorized; InnoEngine.Docs owns product documentation. -2. Run `tests/ci/Test-AgentRules.ps1 -Paths -ShowInstructions` from the engine root. Absolute paths are also accepted. Add behavior tags with `-Behaviors` or explicit units with `-Rules`; the [rule registry](.agents/rulebook/coverage.json) is the sole routing authority. Documentation rules require `-DocsRoot `; the loader never guesses or downloads their authority. Do not depend on a client discovering nested instructions. -3. Read all selected complete units, their sources and reasons. If the combination exceeds 16 KiB, read every reported `-Stage` in sequence; never truncate or skip requirements. Root instructions have an 8 KiB hard limit. Use `new-boundary` for new boundaries and `delivery` for delivery work. +2. Run `tests/ci/Test-AgentRules.ps1 -Paths ` from the engine root. Absolute paths are also accepted. Add work tags with `-Tags` or explicit rule files with `-Rules`; each rule file declares its own paths and tags. Documentation rules require `-DocsRoot `; the script never guesses or downloads their authority. Do not depend on a client discovering nested instructions. +3. Read every listed rule file completely; never truncate or skip requirements. A rule file has a 16 KiB limit and root instructions an 8 KiB hard limit. Use `new-boundary` for new boundaries and `delivery` for delivery work. 4. When documentation is needed, select an explicit Docs snapshot. Build `docs index --docs-root ` prepares it; `docs search/read/symbol` query the published snapshot. Reuse loaded rules and documentation while their identities and scope remain unchanged. Refresh after relevant edits. Never guess sibling paths, silently compile during a query or require a Docs candidate for an ordinary engine task. ## Task workflows @@ -22,7 +22,7 @@ Skills describe workflows; they do not replace rules or maintain test lists. Def - [InnoEngine.Docs](https://github.com/Wolfiora/InnoEngine.Docs) owns Manual, tutorials and authored API prose. The engine owns C# declarations, XML, actual script projection and query tooling. API changes maintain XML here; master exports flow to Docs `draft`. Manual changes use a Docs branch based on `draft`. No paired engine/Docs PR metadata is required. - Engine API includes public and externally usable protected C# contracts only from `src/` and `build/`, excluding declared tests and fixtures. All other roots are outside Engine API. Scripting uses actual projections and declared Scope. Platform implementation guides are excluded; shared capability limits and engine functional acceptance remain required. API prose is XML-managed unless its individual type/member has a nonempty author name in `source` other than `xml`; declarations follow source facts. Editorial gaps warn without blocking. Only a human `draft` to `main` release merge may publish the site. -- The [rulebook](.agents/rulebook/README.md) owns development requirements. Human contributors use the same rules through [CONTRIBUTING](CONTRIBUTING.md). +- The [rulebook](.agents/rulebook/README.md) owns development requirements as plain Markdown; rules change through a pull request that a human merges. Human contributors use the same rules through [CONTRIBUTING](CONTRIBUTING.md). - [Records](.agents/records/README.md) hold necessary plans, lasting decisions and acceptance. A handoff retains scope, decisions, input identity, valid evidence, blockers and next action. Do not load historical records by default. - Complete all applicable behavior, callers, references, XML, documentation and validation in the approved task. Record unrelated improvements separately. Required regression, contract and tooling tests may change; unrelated rewrites, weaker assertions, reflection bypasses and test-only production visibility remain prohibited. - Evidence must match current inputs. Missing, skipped or unavailable checks are not passes. Commits, pushes, report edits and session recovery do not by themselves invalidate evidence. Reconcile the approved plan and report unfinished acceptance and external blockers accurately; continue actionable work. diff --git a/tests/ci/Test-AgentRules.Tests.ps1 b/tests/ci/Test-AgentRules.Tests.ps1 index c4eb08cf0..cf87aa710 100644 --- a/tests/ci/Test-AgentRules.Tests.ps1 +++ b/tests/ci/Test-AgentRules.Tests.ps1 @@ -2,292 +2,101 @@ param([string]$DocsRoot) $ErrorActionPreference = 'Stop' $repository = [IO.Path]::GetFullPath('../..', $PSScriptRoot) $entry = Join-Path $PSScriptRoot 'Test-AgentRules.ps1' -$root = @(& $entry -Paths 'src/services/input/Example.cs' -Rules completion) -join "`n" -Push-Location (Join-Path $repository 'tools') -try { $nested = @(& $entry -Paths 'src/services/input/Example.cs' -Rules completion) -join "`n" } -finally { Pop-Location } -if ($root -cne $nested) { throw 'Root and nested invocation selected different instruction units.' } -if ($root -notmatch 'Preserved mapping: 241 rules') { throw 'Original rule coverage is incomplete.' } -foreach ($path in @('Directory.Build.targets', 'Directory.Solution.targets')) { - $selection = @(& $entry -Paths $path) -join "`n" - foreach ($required in @('build-host', 'platform-products', 'backend-build', 'solution')) { - if (-not $selection.Contains($required)) { throw "Shared build input $path did not route to $required." } - } + +function Assert-Rejected([string]$message, [scriptblock]$action) { + $failure = $null + try { & $action | Out-Null } catch { $failure = $_.Exception.Message } + if ($null -eq $failure -or -not $failure.Contains($message)) { throw "Expected a rejection containing '$message' but got: $failure" } } -foreach ($scenario in @(@{ Rules = 'unknown-unit' }, @{ Behaviors = 'unknown-behavior' }, @{ Stage = 999 })) { - $rejected = $false - try { & $entry @scenario | Out-Null } catch { $rejected = $true } - if (-not $rejected) { throw 'Invalid rule selection was accepted.' } +function Assert-Selection([string]$output, [string[]]$includes, [string[]]$excludes = @()) { + foreach ($file in $includes) { if (-not $output.Contains($file + ' |')) { throw "Expected rule file $file in: $output" } } + foreach ($file in $excludes) { if ($output.Contains($file + ' |')) { throw "Unexpected rule file $file in: $output" } } } -$manifest = Get-Content -LiteralPath (Join-Path $repository '.agents/rulebook/coverage.json') -Raw | ConvertFrom-Json -foreach ($unit in $manifest.units) { - if (-not $unit.sourceHash -or -not $unit.check -or -not $unit.reviewer) { throw "Incomplete rule responsibility: $($unit.id)" } -} -$all = @(& $entry -Rules @($manifest.units | Where-Object { -not $_.repository } | ForEach-Object id)) -join "`n" -foreach ($match in [regex]::Matches($all, 'Stage \d+: (\d+) bytes')) { - if ([int]$match.Groups[1].Value -gt 16384) { throw 'A staged instruction set exceeds its complete-read budget.' } -} -$first = @(& $entry -Paths 'src/services/input/Example.cs' -Rules completion -Stage 1 -ShowInstructions) -join "`n" -if (-not $first.Contains('# InnoEngine agent instructions') -or -not $first.Contains('Define clear assembly/domain boundaries')) { throw 'Actual instruction bodies were not emitted.' } -$fixtureParent = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()) -$fixture = Join-Path $fixtureParent ('InnoRuleTests-' + [guid]::NewGuid().ToString('N')) + +# The repository rules load identically from any working directory and in both list forms. +$root = @(& $entry -Paths 'src/services/input/Example.cs' -Rules validation) -join "`n" +Push-Location (Join-Path $repository 'tools') +try { $nested = @(& $entry -Paths 'src/services/input/Example.cs' -Rules validation) -join "`n" } +finally { Pop-Location } +if ($root -cne $nested) { throw 'Root and nested invocation selected different rule files.' } +Assert-Selection $root @('.agents/rulebook/coding.md', '.agents/rulebook/validation.md', '.agents/rulebook/csharp-style/README.md') +$joined = @(& $entry -Paths 'Directory.Build.targets,Directory.Solution.targets') -join "`n" +if ($joined -cne (@(& $entry -Paths 'Directory.Build.targets', 'Directory.Solution.targets') -join "`n")) { throw 'Comma-joined and array selections differ.' } +Assert-Selection $joined @('.agents/rulebook/projects.md', '.agents/rulebook/domains/build-native/hosts.md', + '.agents/rulebook/domains/build-native/platform-products.md', '.agents/rulebook/domains/build-native/backend-integration.md') +Assert-Selection (@(& $entry -Paths (Join-Path $repository 'AGENTS.md')) -join "`n") @('.agents/rulebook/validation.md') +Assert-Rejected 'Unknown rule: unknown-rule' { & $entry -Rules unknown-rule } +Assert-Rejected 'Unknown tag: unknown-tag' { & $entry -Tags unknown-tag } +Assert-Rejected 'Path is outside the repository' { & $entry -Paths '../outside.cs' } +if ($DocsRoot) { Assert-Selection (@(& $entry -DocsRoot $DocsRoot -Tags documentation) -join "`n") @('.agents/rulebook/documentation.md') } + +$fixture = Join-Path ([IO.Path]::GetFullPath([IO.Path]::GetTempPath())) ('InnoRuleTests-' + [guid]::NewGuid().ToString('N')) try { - & git clone --quiet --shared --no-checkout $repository $fixture - if ($LASTEXITCODE -ne 0) { throw 'Cannot create the isolated rule provenance fixture.' } - # A clone of a shallow CI checkout does not inherit separately fetched provenance objects. - # Acquire only missing original revisions from the explicit local owner, never the network. - $provenance = @("$($manifest.baseline):AGENTS.md") + @($manifest.units | ForEach-Object source) + - @($manifest.units | Where-Object { $_.approvedAddition.translation } | ForEach-Object { $_.approvedAddition.translation.source }) - foreach ($source in @($provenance | Sort-Object -Unique)) { - & git -C $fixture cat-file -e $source 2>$null - if ($LASTEXITCODE -eq 0) { continue } - $revision = ($source -split ':', 2)[0] - if ($revision -cnotmatch '^[a-f0-9]{40}$') { throw 'The rule fixture requires immutable local provenance.' } - & git -C $fixture fetch --quiet --no-tags --depth=1 $repository $revision - if ($LASTEXITCODE -ne 0) { throw 'Cannot prepare original rule provenance from the local checkout.' } - & git -C $fixture cat-file -e $source 2>$null - if ($LASTEXITCODE -ne 0) { throw "Original rule provenance is unavailable in the fixture: $source" } - } - [void][IO.Directory]::CreateDirectory((Join-Path $fixture 'tests/ci')) - [void][IO.Directory]::CreateDirectory((Join-Path $fixture '.agents')) - Copy-Item -LiteralPath (Join-Path $repository '.agents/rulebook') -Destination (Join-Path $fixture '.agents/rulebook') -Recurse - Copy-Item -LiteralPath (Join-Path $repository 'AGENTS.md') -Destination $fixture - Copy-Item -LiteralPath $entry -Destination (Join-Path $fixture 'tests/ci/Test-AgentRules.ps1') - foreach ($instruction in @((Join-Path $repository 'AGENTS.md')) + @(Get-ChildItem (Join-Path $repository '.agents/rulebook') -Recurse -Filter '*.md' | ForEach-Object FullName)) { - foreach ($link in [regex]::Matches([IO.File]::ReadAllText($instruction), '\]\(([^)#]+)(?:#[^)]*)?\)')) { - $relative = $link.Groups[1].Value - if ($relative -match '^[a-z]+:') { continue } - $sourceFile = [IO.Path]::GetFullPath($relative, (Split-Path $instruction)) - $target = Join-Path $fixture ([IO.Path]::GetRelativePath($repository, $sourceFile)) - if (-not [IO.Path]::GetFullPath($target).StartsWith($fixture + [IO.Path]::DirectorySeparatorChar, [StringComparison]::Ordinal)) { - throw 'Instruction fixture link escaped its isolated owner.' - } - [void][IO.Directory]::CreateDirectory((Split-Path $target)) - Copy-Item -LiteralPath $sourceFile -Destination $target - } - } - foreach ($review in @($manifest.units | Where-Object translation | ForEach-Object { ($_.translation.review -split '#')[0] } | Sort-Object -Unique)) { - $reviewTarget = Join-Path $fixture $review - [void][IO.Directory]::CreateDirectory((Split-Path $reviewTarget)) - Copy-Item -LiteralPath (Join-Path $repository $review) -Destination $reviewTarget - } - foreach ($review in @($manifest.units | ForEach-Object { $_.translation.amendments } | Where-Object { $null -ne $_ } | ForEach-Object review | Sort-Object -Unique)) { - $reviewTarget = Join-Path $fixture $review - [void][IO.Directory]::CreateDirectory((Split-Path $reviewTarget)) - Copy-Item -LiteralPath (Join-Path $repository $review) -Destination $reviewTarget + $rules = Join-Path $fixture '.agents/rulebook' + $docs = Join-Path $fixture 'docs-checkout' + foreach ($directory in @((Join-Path $fixture 'tests/ci'), (Join-Path $rules 'domains'), (Join-Path $docs '.agents/rulebook'))) { + [void][IO.Directory]::CreateDirectory($directory) } $fixtureEntry = Join-Path $fixture 'tests/ci/Test-AgentRules.ps1' - $registry = Join-Path $fixture '.agents/rulebook/coverage.json' - $originalRegistry = [IO.File]::ReadAllText($registry) - foreach ($scenario in @('missing-original', 'non-file-original', 'injected-source-line')) { - $copy = $originalRegistry | ConvertFrom-Json - $revision = ($copy.units[0].source -split ':', 2)[0] - $expected = 'Unavailable rule source' - switch ($scenario) { - 'missing-original' { $copy.units[0].source = $revision + ':missing-rule-original.md' } - 'non-file-original' { $copy.units[0].source = $revision + ':docs' } - 'injected-source-line' { - $copy.units[0].source += "`n" + $copy.units[1].source - $expected = 'Invalid immutable rule source' - } - } - [IO.File]::WriteAllText($registry, ($copy | ConvertTo-Json -Depth 50)) - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains($expected)) { throw "Wrong source rejection for ${scenario}: $failure" } + $examples = Join-Path $fixture 'tests/ci/Test-AgentRules.examples.json' + Copy-Item -LiteralPath $entry -Destination $fixtureEntry + function Write-Fixture([string]$path, [string]$text) { [IO.File]::WriteAllText((Join-Path $fixture $path), $text) } + Write-Fixture 'AGENTS.md' "# Entry`n" + Write-Fixture '.agents/rulebook/README.md' "# Index without front matter`n" + Write-Fixture '.agents/rulebook/coding.md' "---`npaths: [`"**/*.cs`", `"src/*.txt`"]`ntags: [coding, shared]`n---`n# Coding`n" + Write-Fixture '.agents/rulebook/domains/editor.md' "---`npaths: [`"src/editor/**`"]`n---`n# Editor`n" + Write-Fixture '.agents/rulebook/delivery.md' "---`ntags: [delivery, shared]`n---`n# Delivery`n" + Write-Fixture 'docs-checkout/.agents/rulebook/README.md' "# Docs index`n" + Write-Fixture 'docs-checkout/.agents/rulebook/writing.md' "---`npaths: [`"content/**`"]`ntags: [writing]`n---`n# Writing`n" + Write-Fixture 'tests/ci/Test-AgentRules.examples.json' '[{ "path": "src/editor/State.cs", "includes": ["coding", "domains/editor"], "excludes": ["delivery"] }]' + + # Globs match the whole path, `*` stays inside one name and matching is case-sensitive. + $valid = @(& $fixtureEntry) -join "`n" + if (-not $valid.Contains('Rules are valid: 3 files.')) { throw "Unexpected fixture summary: $valid" } + Assert-Selection (@(& $fixtureEntry -Paths 'Root.cs') -join "`n") @('.agents/rulebook/coding.md') @('.agents/rulebook/domains/editor.md') + Assert-Selection (@(& $fixtureEntry -Paths 'src/editor/panels/Panel.cs') -join "`n") @('.agents/rulebook/coding.md', '.agents/rulebook/domains/editor.md') + Assert-Selection (@(& $fixtureEntry -Paths 'src/note.txt') -join "`n") @('.agents/rulebook/coding.md') + foreach ($unmatched in @('src/nested/note.txt', 'src/Editor/note.md', 'tools/editor/note.md', 'Root.CS')) { + if ((@(& $fixtureEntry -Paths $unmatched) -join "`n").Contains(' | ')) { throw "Path must not select a rule: $unmatched" } } - [IO.File]::WriteAllText($registry, $originalRegistry) - foreach ($scenario in @('missing-amendment-approval', 'changed-amendment-hash', 'unmapped-amendment', 'duplicate-amendment')) { - $copy = $originalRegistry | ConvertFrom-Json - $translation = ($copy.units | Where-Object id -CEQ 'directories').translation - switch ($scenario) { - 'missing-amendment-approval' { $translation.amendments[0].approval = ''; $expected = 'Invalid approved rule amendment' } - 'changed-amendment-hash' { $translation.amendments[0].currentHash = '0' * 64; $expected = 'Changed or unmapped translation clause' } - 'unmapped-amendment' { $translation.amendments += [pscustomobject]@{ ordinal = 999 }; $expected = 'Unmapped approved rule amendment' } - 'duplicate-amendment' { $translation.amendments += $translation.amendments[0]; $expected = 'Duplicate approved rule amendment' } + Assert-Selection (@(& $fixtureEntry -Tags shared) -join "`n") @('.agents/rulebook/coding.md', '.agents/rulebook/delivery.md') @('.agents/rulebook/domains/editor.md') + Assert-Selection (@(& $fixtureEntry -Rules 'domains/editor') -join "`n") @('.agents/rulebook/domains/editor.md') + + # An explicit Docs checkout adds its own rule files; its paths never select engine rules. + Assert-Rejected 'Unknown tag: writing' { & $fixtureEntry -Tags writing } + $writing = Join-Path $docs '.agents/rulebook/writing.md' + Assert-Selection (@(& $fixtureEntry -DocsRoot $docs -Tags writing) -join "`n") @($writing) + Assert-Selection (@(& $fixtureEntry -DocsRoot $docs -Rules 'docs/writing') -join "`n") @($writing) + Assert-Selection (@(& $fixtureEntry -DocsRoot $docs -Paths (Join-Path $docs 'content/Guide.cs')) -join "`n") @($writing) @('.agents/rulebook/coding.md') + + $cases = @( + @{ message = 'needs front matter'; path = '.agents/rulebook/broken.md'; text = "# No front matter`n" }, + @{ message = 'needs front matter'; path = '.agents/rulebook/broken.md'; text = "---`ntags:`n - block-list`n---`n# Rule`n" }, + @{ message = 'needs front matter'; path = '.agents/rulebook/broken.md'; text = "---`n---`n# Rule`n" }, + @{ message = 'Unknown or repeated front matter field'; path = '.agents/rulebook/broken.md'; text = "---`nrequires: [coding]`n---`n# Rule`n" }, + @{ message = 'Unknown or repeated front matter field'; path = '.agents/rulebook/broken.md'; text = "---`ntags: [one]`ntags: [two]`n---`n# Rule`n" }, + @{ message = 'Empty front matter value'; path = '.agents/rulebook/broken.md'; text = "---`ntags: []`n---`n# Rule`n" }, + @{ message = 'Invalid rule tag'; path = '.agents/rulebook/broken.md'; text = "---`ntags: [Not Valid]`n---`n# Rule`n" }, + @{ message = 'not a repository-relative glob'; path = '.agents/rulebook/broken.md'; text = "---`npaths: [`"/src/**`"]`n---`n# Rule`n" }, + @{ message = 'not a repository-relative glob'; path = '.agents/rulebook/broken.md'; text = "---`npaths: [`"src/../**`"]`n---`n# Rule`n" }, + @{ message = 'exceeds 16384 bytes'; path = '.agents/rulebook/broken.md'; text = "---`ntags: [large]`n---`n" + ('x' * 16384) }, + @{ message = 'Root instructions exceed 8192 bytes'; path = 'AGENTS.md'; text = 'x' * 8193 }, + @{ message = 'must select delivery'; path = 'tests/ci/Test-AgentRules.examples.json'; text = '[{ "path": "src/a.cs", "includes": ["delivery"] }]' }, + @{ message = 'must not select coding'; path = 'tests/ci/Test-AgentRules.examples.json'; text = '[{ "path": "src/a.cs", "excludes": ["coding"] }]' }, + @{ message = 'names an unknown rule: retired'; path = 'tests/ci/Test-AgentRules.examples.json'; text = '[{ "path": "src/a.cs", "excludes": ["retired"] }]' } + ) + foreach ($case in $cases) { + $target = Join-Path $fixture $case.path + $original = if (Test-Path -LiteralPath $target) { [IO.File]::ReadAllText($target) } else { $null } + try { + [IO.File]::WriteAllText($target, $case.text) + Assert-Rejected $case.message { & $fixtureEntry } + } finally { + if ($null -eq $original) { Remove-Item -LiteralPath $target } else { [IO.File]::WriteAllText($target, $original) } } - [IO.File]::WriteAllText($registry, ($copy | ConvertTo-Json -Depth 50)) - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains($expected)) { throw "Wrong amendment rejection for $scenario : $failure" } - } - [IO.File]::WriteAllText($registry, $originalRegistry) - # Use one real preserved engine unit as an isolated external-authority fixture. No network, - # sibling checkout or copied current Docs tree is needed by engine-only regression execution. - $authorityRoot = Join-Path $fixture 'external-authority' - $authorityRules = Join-Path $authorityRoot '.agents/rulebook' - [void][IO.Directory]::CreateDirectory($authorityRules) - $externalCopy = $originalRegistry | ConvertFrom-Json - $externalUnit = $externalCopy.units | Where-Object id -CEQ 'style' - $localAuthority = Join-Path $fixture $externalUnit.path - $localText = [IO.File]::ReadAllText($localAuthority) - $unitPattern = '(?s).*?' - $externalText = [regex]::Match($localText, $unitPattern).Value - $externalUnit | Add-Member repository 'Wolfiora/InnoEngine.Docs' - $externalUnit.path = '.agents/rulebook/imported.md' - foreach ($row in $externalCopy.rules | Where-Object unit -CEQ 'style') { - $row | Add-Member repository 'Wolfiora/InnoEngine.Docs' - $row.path = $externalUnit.path - } - $externalPath = Join-Path $authorityRoot $externalUnit.path - [IO.File]::WriteAllText($externalPath, $externalText) - [IO.File]::WriteAllText($localAuthority, [regex]::Replace($localText, $unitPattern, '')) - [IO.File]::WriteAllText($registry, ($externalCopy | ConvertTo-Json -Depth 50)) - # Other migrated units are not part of this single-authority fixture; selecting a missing - # authority must fail before any complete instruction output can be claimed. - $failure = '' - try { & $fixtureEntry -Rules style | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains('Supply -DocsRoot')) { throw "Missing explicit external rule authority was accepted: $failure" } - foreach ($scenario in @('unknown-repository', 'escaped-authority')) { - $originalPath = $externalUnit.path - if ($scenario -eq 'unknown-repository') { $externalUnit.repository = 'Other/Rules' } - else { $externalUnit.path = '../../escaped.md' } - [IO.File]::WriteAllText($registry, ($externalCopy | ConvertTo-Json -Depth 50)) - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - $expected = if ($scenario -eq 'unknown-repository') { 'Unknown rule repository' } else { 'Rule path escapes owner' } - if (-not $failure.Contains($expected)) { throw "Wrong external authority rejection for ${scenario}: $failure" } - $externalUnit.repository = 'Wolfiora/InnoEngine.Docs' - $externalUnit.path = $originalPath - } - [IO.File]::WriteAllText($registry, $originalRegistry) - [IO.File]::WriteAllText($localAuthority, $localText) - if ($DocsRoot) { - foreach ($path in @($manifest.units | Where-Object repository | ForEach-Object path | Sort-Object -Unique)) { - $target = Join-Path $authorityRoot $path - [void][IO.Directory]::CreateDirectory((Split-Path $target)) - Copy-Item -LiteralPath (Join-Path $DocsRoot $path) -Destination $target - } - $complete = @(& $fixtureEntry -DocsRoot $authorityRoot -Rules wiki -ShowInstructions) -join "`n" - if (-not $complete.Contains('External authority verified: 8 complete units') -or -not $complete.Contains('Canonical source and example verification')) { - throw 'Explicit external authority did not load complete current requirements.' - } - Push-Location (Join-Path $fixture 'tests') - try { $nestedExternal = @(& $fixtureEntry -DocsRoot $authorityRoot -Rules wiki -ShowInstructions) -join "`n" } - finally { Pop-Location } - if ($complete -cne $nestedExternal) { throw 'Nested invocation changed external authority or rule bodies.' } - $authority = Join-Path $authorityRoot '.agents/rulebook/documentation.md' - $originalAuthority = [IO.File]::ReadAllText($authority) - [IO.File]::WriteAllText($authority, $originalAuthority.Replace('## API reference and source', '## Weakened contract')) - $failure = '' - try { & $fixtureEntry -DocsRoot $authorityRoot | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains('Changed or unmapped translation clause')) { throw 'Changed external rule body passed provenance validation.' } - [IO.File]::WriteAllText($authority, $originalAuthority) - [IO.File]::WriteAllText($authority, $originalAuthority + "`n`n") - $failure = '' - try { & $fixtureEntry -DocsRoot $authorityRoot | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains('Unregistered external rule authority')) { throw 'Unregistered external rule authority passed validation.' } - [IO.File]::WriteAllText($authority, $originalAuthority) - } - foreach ($scenario in @('cycle', 'missing-section', 'unregistered-section')) { - [IO.File]::WriteAllText($registry, $originalRegistry) - $copy = $originalRegistry | ConvertFrom-Json - $unitPath = Join-Path $fixture $copy.units[0].path - $originalUnit = [IO.File]::ReadAllText($unitPath) - $expected = switch ($scenario) { - 'cycle' { - $copy.units[0].requires = @($copy.units[0].id) - [IO.File]::WriteAllText($registry, ($copy | ConvertTo-Json -Depth 50)) - 'Cyclic rule dependency' - } - 'missing-section' { - [IO.File]::WriteAllText($unitPath, $originalUnit.Replace('', '')) - 'Missing or repeated complete rule unit' - } - 'unregistered-section' { - [IO.File]::WriteAllText($unitPath, $originalUnit + "`n`n") - 'Unregistered rule unit' - } - } - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - [IO.File]::WriteAllText($unitPath, $originalUnit) - if (-not $failure.Contains($expected)) { throw "Wrong rejection for $scenario : $failure" } - } - [IO.File]::WriteAllText($registry, $originalRegistry) - $translationUnit = ($originalRegistry | ConvertFrom-Json).units | Where-Object id -CEQ 'delivery' - $translationPath = Join-Path $fixture $translationUnit.path - $originalTranslation = [IO.File]::ReadAllText($translationPath) - foreach ($scenario in @('changed-translation', 'missing-clause', 'changed-source-map', 'missing-review', 'escaped-review', 'lost-original-rule')) { - $copy = $originalRegistry | ConvertFrom-Json - $translated = $copy.units | Where-Object id -CEQ 'delivery' - [IO.File]::WriteAllText($translationPath, $originalTranslation) - $expected = switch ($scenario) { - 'changed-translation' { - [IO.File]::WriteAllText($translationPath, $originalTranslation.Replace('must be entirely in English', 'may be in any language')) - 'Changed or unmapped translation clause' - } - 'missing-clause' { - $translated.translation.lines = @($translated.translation.lines | Select-Object -Skip 1) - 'Incomplete translation coverage' - } - 'changed-source-map' { - $translated.translation.lines[0].sourceHash = 'invalid' - 'Changed or unmapped translation clause' - } - 'missing-review' { - $translated.translation.review = '.agents/records/missing.md' - 'Missing translation review' - } - 'escaped-review' { - $translated.translation.review = '.agents/records/../../AGENTS.md' - 'Missing translation review' - } - 'lost-original-rule' { - ($copy.rules | Where-Object id -CEQ '31.1').translatedHash = 'invalid' - 'Rule translation was lost' - } - } - [IO.File]::WriteAllText($registry, ($copy | ConvertTo-Json -Depth 50)) - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains($expected)) { throw "Wrong rejection for $scenario : $failure" } - } - [IO.File]::WriteAllText($translationPath, $originalTranslation) - [IO.File]::WriteAllText($registry, $originalRegistry) - $nestedRulePath = Join-Path $fixture '.agents/rulebook/coding.md' - $nestedRuleText = [IO.File]::ReadAllText($nestedRulePath) - [IO.File]::WriteAllText($nestedRulePath, $nestedRuleText.Replace(' - Types and members', '- Types and members')) - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - [IO.File]::WriteAllText($nestedRulePath, $nestedRuleText) - if (-not $failure.Contains('Changed or unmapped translation clause')) { throw 'Nested rule indentation lost its provenance protection.' } - $additionUnit = ($originalRegistry | ConvertFrom-Json).units | Where-Object id -CEQ 'csharp-standard-5' - $additionPath = Join-Path $fixture $additionUnit.path - $originalAddition = [IO.File]::ReadAllText($additionPath) - $loaded = @(& $entry -Rules $additionUnit.id -ShowInstructions) -join "`n" - if (-not $loaded.Contains('Handwritten C# must not use `global::`')) { throw 'Approved addition was not loaded.' } - foreach ($scenario in @('changed-addition', 'missing-addition', 'missing-approval', 'changed-baseline')) { - [IO.File]::WriteAllText($registry, $originalRegistry) - [IO.File]::WriteAllText($additionPath, $originalAddition) - $expected = 'Invalid approved rule addition' - switch ($scenario) { - 'changed-addition' { - [IO.File]::WriteAllText($additionPath, $originalAddition.Replace('Handwritten C# must not use', 'Handwritten C# may use')) - $expected = 'Changed or unmapped translation clause' - } - 'missing-addition' { - [IO.File]::WriteAllText($additionPath, $originalAddition.Replace('', '')) - } - 'missing-approval' { - $copy = $originalRegistry | ConvertFrom-Json - ($copy.units | Where-Object id -CEQ $additionUnit.id).approvedAddition.approval = '' - [IO.File]::WriteAllText($registry, ($copy | ConvertTo-Json -Depth 50)) - } - 'changed-baseline' { - [IO.File]::WriteAllText($additionPath, $originalAddition.Replace('- Explicitly declare ordinary using directives in every file.', '')) - $expected = 'Incomplete translation coverage' - } - } - $failure = '' - try { & $fixtureEntry | Out-Null } catch { $failure = $_.Exception.Message } - if (-not $failure.Contains($expected)) { throw "Wrong rejection for $scenario : $failure" } } + & $fixtureEntry | Out-Null } finally { - $resolved = [IO.Path]::GetFullPath($fixture) - if (-not $resolved.StartsWith($fixtureParent, [StringComparison]::Ordinal) -or (Split-Path $resolved -Leaf) -notmatch '^InnoRuleTests-[a-f0-9]{32}$') { - throw 'Rule fixture cleanup escaped its unique owner.' - } - if (Test-Path -LiteralPath $resolved) { Remove-Item -LiteralPath $resolved -Recurse -Force } + if (Test-Path -LiteralPath $fixture) { Remove-Item -LiteralPath $fixture -Recurse -Force } } -Write-Output 'Agent rule coverage, actual loading, root/nested routing, staged budgets, invalid selections, missing units, cyclic dependencies, approved additions and English translation provenance passed.' +Write-Output 'Agent rule loading, front matter, glob routing, size limits, invalid selections, routing examples and explicit Docs checkouts passed.' diff --git a/tests/ci/Test-AgentRules.examples.json b/tests/ci/Test-AgentRules.examples.json new file mode 100644 index 000000000..d23f8a436 --- /dev/null +++ b/tests/ci/Test-AgentRules.examples.json @@ -0,0 +1,20 @@ +[ + { "path": "src/foundation/core/Inno.Core.Mathematics/Vector2.cs", "includes": ["coding", "csharp-style/README", "csharp-style/03-naming", "csharp-style/17-example"], "excludes": ["domains/editor/state", "domains/identity-reload", "validation", "projects"] }, + { "path": "src/foundation/core/Inno.Core.Execution/StateMachine.cs", "excludes": ["domains/editor/state", "domains/editor/projects"] }, + { "path": "tools/Inno.Tooling.Validation/ValidationWorkspace.cs", "excludes": ["domains/editor/state"] }, + { "path": "assets/branding/logo.svg", "excludes": ["domains/identity-reload"] }, + { "path": "tools/Inno.Tooling.Validation/AssetsReport.cs", "includes": ["coding"], "excludes": ["domains/identity-reload"] }, + { "path": "src/composition/editor/framework/Inno.Editor.Core/History/UndoStack.cs", "includes": ["coding", "domains/editor/projects", "domains/editor/state"], "excludes": ["domains/editor/ui"] }, + { "path": "src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/Form.cs", "includes": ["domains/editor/projects", "domains/editor/state", "domains/editor/ui"] }, + { "path": "backends/ImGui/runtime/Inno.Backend.ImGui/ImGuiRenderer.cs", "includes": ["domains/editor/ui", "domains/build-native/hosts", "domains/build-native/platform-products", "domains/build-native/backend-integration"] }, + { "path": "src/services/rendering/Inno.Rendering/Inno.Rendering.csproj", "includes": ["projects", "domains/rendering"], "excludes": ["coding"] }, + { "path": "src/services/audio/Inno.Audio/Properties/ScriptingApi.cs", "includes": ["domains/scripting", "domains/identity-reload"], "excludes": ["domains/plugins"] }, + { "path": "src/runtime/plugins/Inno.Plugins/PluginCatalog.cs", "includes": ["domains/plugins", "no-legacy", "domains/identity-reload"] }, + { "path": "src/content/scene/Inno.Scene/Scene.cs", "includes": ["domains/identity-reload"], "excludes": ["domains/rendering", "domains/plugins"] }, + { "path": "tests/rendering/Inno.Rendering.Tests/FrameTests.cs", "includes": ["validation", "coding", "domains/rendering"] }, + { "path": "Directory.Build.props", "includes": ["projects", "domains/build-native/hosts"] }, + { "path": ".github/workflows/validation.yml", "includes": ["domains/build-native/hosts"], "excludes": ["validation"] }, + { "path": ".agents/rulebook/coding.md", "includes": ["validation"], "excludes": ["coding"] }, + { "path": "AGENTS.md", "includes": ["validation"] }, + { "path": ".agents/records/decisions/README.md", "includes": ["validation"] } +] diff --git a/tests/ci/Test-AgentRules.ps1 b/tests/ci/Test-AgentRules.ps1 index 9c2cdd741..38bb89ff4 100644 --- a/tests/ci/Test-AgentRules.ps1 +++ b/tests/ci/Test-AgentRules.ps1 @@ -1,308 +1,104 @@ param( [string[]]$Paths = @(), [string[]]$Rules = @(), - [string[]]$Behaviors = @(), - [switch]$ShowInstructions, - [int]$Stage = 0, + [string[]]$Tags = @(), [string]$DocsRoot ) $ErrorActionPreference = 'Stop' $OutputEncoding = [Text.UTF8Encoding]::new($false) [Console]::OutputEncoding = $OutputEncoding +$rootBudget = 8192 +$fileBudget = 16384 $repository = [IO.Path]::GetFullPath('../..', $PSScriptRoot) -$ruleRoot = Join-Path $repository '.agents/rulebook' -$manifest = Get-Content -LiteralPath (Join-Path $ruleRoot 'coverage.json') -Raw | ConvertFrom-Json -$rootText = Get-Content -LiteralPath (Join-Path $repository 'AGENTS.md') -Raw -$rootBytes = [Text.Encoding]::UTF8.GetByteCount($rootText) -if ($rootBytes -gt $manifest.rootBudgetBytes) { throw 'Root instructions exceed 8 KiB.' } -$sources = @{} -$sourceIdentities = @("$($manifest.baseline):AGENTS.md") + @($manifest.units | ForEach-Object source) + - @($manifest.units | Where-Object { $_.approvedAddition.translation } | ForEach-Object { $_.approvedAddition.translation.source }) -$sourceReader = [Diagnostics.Process]::new() -$sourceReader.StartInfo.FileName = 'git' -foreach ($argument in @('-C', $repository, 'cat-file', '--batch')) { $sourceReader.StartInfo.ArgumentList.Add($argument) } -$sourceReader.StartInfo.UseShellExecute = $false -$sourceReader.StartInfo.CreateNoWindow = $true -$sourceReader.StartInfo.RedirectStandardInput = $true -$sourceReader.StartInfo.RedirectStandardOutput = $true -$sourceReader.StartInfo.RedirectStandardError = $true -$sourceReader.StartInfo.StandardInputEncoding = [Text.UTF8Encoding]::new($false) -# Preparation owns acquisition. Reading rules never hydrates a partial clone over the network. -$sourceReader.StartInfo.Environment['GIT_NO_LAZY_FETCH'] = '1' -$sourceReader.StartInfo.Environment['GIT_TERMINAL_PROMPT'] = '0' -$sourceStarted = $false -$bytes = $null -try { - $sourceStarted = $sourceReader.Start() - if (-not $sourceStarted) { throw 'Cannot read immutable rule provenance.' } - $sourceErrors = $sourceReader.StandardError.ReadToEndAsync() - $bytes = [IO.BinaryReader]::new($sourceReader.StandardOutput.BaseStream) - foreach ($identity in @($sourceIdentities | Sort-Object -Unique)) { - if ($identity -cnotmatch '^[a-f0-9]{40}:[^\r\n\x00]+$') { throw "Invalid immutable rule source: $identity" } - # Exchange one request and its size-delimited response at a time: neither pipe can fill - # while its peer is waiting for the complete batch, even for a large original rulebook. - $sourceReader.StandardInput.WriteLine($identity) - $sourceReader.StandardInput.Flush() - $header = [Text.StringBuilder]::new() - while (($value = $bytes.ReadByte()) -ne 10) { - if ($header.Length -ge 4096) { throw 'Invalid rule provenance response.' } - [void]$header.Append([char]$value) +# `pwsh -File` from another shell passes `a,b` as one value; accept both forms. +$Paths, $Rules, $Tags = @($Paths, $Rules, $Tags | ForEach-Object { , @($_ -split ',' | ForEach-Object Trim | Where-Object { $_ }) }) + +function ConvertTo-PathPattern([string]$glob, [string]$owner) { + # Globs are repository-relative and match the whole path: `**/` spans directories, `*` stays inside one name. + if ($glob -cnotmatch '^[^/\\][^\\]*$' -or $glob -cmatch '(^|/)\.\.?(/|$)') { throw "Rule path is not a repository-relative glob: $owner -> $glob" } + $pattern = [regex]::Escape($glob).Replace('\*\*/', '(?:.*/)?').Replace('\*\*', '.*').Replace('\*', '[^/]*') + return [regex]::new('^' + $pattern + '$') +} +function Read-Rules([string]$root, [string]$prefix) { + $ruleRoot = Join-Path $root '.agents/rulebook' + $index = Join-Path $ruleRoot 'README.md' + foreach ($file in Get-ChildItem -LiteralPath $ruleRoot -Filter '*.md' -Recurse | Sort-Object FullName) { + if ($file.FullName -ceq $index) { continue } + $relative = [IO.Path]::GetRelativePath($ruleRoot, $file.FullName).Replace('\', '/') + $id = $prefix + $relative.Substring(0, $relative.Length - 3) + $text = (Get-Content -LiteralPath $file.FullName -Raw).Replace("`r`n", "`n") + $header = [regex]::Match($text, '\A---\n((?:[a-z]+: \[[^\]\n]*\]\n)+)---\n') + if (-not $header.Success) { throw "Rule file needs front matter with paths or tags: $id" } + $fields = @{ paths = @(); tags = @() } + foreach ($line in $header.Groups[1].Value.TrimEnd("`n") -split "`n") { + $key, $list = $line -split ': ', 2 + if (-not $fields.ContainsKey($key) -or $fields[$key].Count) { throw "Unknown or repeated front matter field: $id -> $key" } + $fields[$key] = @($list.Trim('[', ']') -split ',' | ForEach-Object { $_.Trim().Trim('"') }) + if (-not $fields[$key].Count -or $fields[$key] -contains '') { throw "Empty front matter value: $id -> $key" } } - $match = [regex]::Match($header.ToString(), '^[a-f0-9]{40} blob ([0-9]+)$') - if (-not $match.Success) { throw "Unavailable rule source: $identity" } - $length = [long]::Parse($match.Groups[1].Value) - if ($length -gt 16777216) { throw "Rule provenance exceeds the bounded source size: $identity" } - $content = $bytes.ReadBytes([int]$length) - if ($content.Length -ne $length -or $bytes.ReadByte() -ne 10) { throw "Incomplete rule source: $identity" } - $sources[$identity] = [Text.UTF8Encoding]::new($false, $true).GetString($content).Replace("`r`n", "`n").TrimEnd([char]10) - } - $sourceReader.StandardInput.Close() - $sourceReader.WaitForExit() - $diagnostic = $sourceErrors.GetAwaiter().GetResult() - if ($sourceReader.ExitCode -ne 0) { throw "Cannot read immutable rule provenance: $diagnostic" } -} finally { - if ($sourceStarted -and -not $sourceReader.HasExited) { $sourceReader.Kill(); $sourceReader.WaitForExit() } - if ($bytes) { $bytes.Dispose() } - $sourceReader.Dispose() -} -function Read-Source([string]$identity) { - if (-not $sources.ContainsKey($identity)) { throw "Unavailable rule source: $identity" } - return $sources[$identity] -} -function Get-Hash([string]$value) { - return [Convert]::ToHexStringLower([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($value))) -} -function Normalize-Links([string]$value) { - # Relocated link destinations do not change their labels or surrounding requirements. - return [regex]::Replace($value.Replace("`r`n", "`n").Trim(), '(\]\()[^)]+(\))', '$1$2') -} -function Get-RuleLines([string]$value) { - # Every nonblank line participates, including headings, examples and nested requirements. - return @($value.Replace("`r`n", "`n").Trim() -split "`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) -} -function Normalize-RuleLine([string]$value) { - # Indentation expresses nested Markdown obligations and code examples; preserve it. - return [regex]::Replace($value, '(\]\()[^)]+(\))', '$1$2') -} -function Test-Translation($unit, [string]$source, [string]$target) { - $translation = $unit.translation - if ($translation.language -cne 'en' -or [string]::IsNullOrWhiteSpace($translation.approval) -or - [string]::IsNullOrWhiteSpace($translation.review)) { throw "Incomplete translation review: $($unit.id)" } - $reviewRoot = [IO.Path]::GetFullPath('.agents/records/', $repository) - $reviewPath = [IO.Path]::GetFullPath(($translation.review -split '#')[0], $repository) - if (-not $reviewPath.StartsWith($reviewRoot, [StringComparison]::Ordinal) -or - -not (Test-Path -LiteralPath $reviewPath -PathType Leaf)) { throw "Missing translation review: $($unit.id)" } - $sourceLines = @(Get-RuleLines $source) - $targetLines = @(Get-RuleLines $target) - if ($translation.lines.Count -ne $sourceLines.Count -or $targetLines.Count -ne $sourceLines.Count) { - throw "Incomplete translation coverage: $($unit.id)" - } - for ($index = 0; $index -lt $sourceLines.Count; $index++) { - $line = $translation.lines[$index] - $targetHash = $line.targetHash - $amendments = @($translation.amendments | Where-Object { $null -ne $_ -and $_.ordinal -eq $index + 1 }) - if ($amendments.Count -gt 1) { throw "Duplicate approved rule amendment: $($unit.id)" } - if ($amendments.Count -eq 1) { - $amendment = $amendments[0] - if ([string]::IsNullOrWhiteSpace($amendment.approval) -or $amendment.previousHash -cne $line.targetHash -or - $amendment.currentHash -cnotmatch '^[a-f0-9]{64}$' -or [string]::IsNullOrWhiteSpace($amendment.review)) { - throw "Invalid approved rule amendment: $($unit.id)" - } - $amendmentReview = [IO.Path]::GetFullPath($amendment.review, $repository) - if (-not $amendmentReview.StartsWith($reviewRoot, [StringComparison]::Ordinal) -or - -not (Test-Path -LiteralPath $amendmentReview -PathType Leaf)) { throw "Missing amendment review: $($unit.id)" } - $targetHash = $amendment.currentHash - } - if ($line.ordinal -ne $index + 1 -or $line.sourceHash -cne (Get-Hash (Normalize-RuleLine $sourceLines[$index])) -or - $targetHash -cne (Get-Hash (Normalize-RuleLine $targetLines[$index]))) { - throw "Changed or unmapped translation clause: $($unit.id) line $($index + 1)" - } - } - foreach ($amendment in $translation.amendments) { - if ($null -ne $amendment -and ($amendment.ordinal -lt 1 -or $amendment.ordinal -gt $sourceLines.Count)) { - throw "Unmapped approved rule amendment: $($unit.id)" - } - } -} -$units = @{}; $bodies = @{}; $external = @{} -function Resolve-Authority($unit) { - $ownerRoot = $repository - if ($unit.PSObject.Properties.Name -contains 'repository') { - if ($unit.repository -cne 'Wolfiora/InnoEngine.Docs') { throw "Unknown rule repository: $($unit.id)" } - $external[$unit.id] = $true - if ($DocsRoot) { $ownerRoot = [IO.Path]::GetFullPath($DocsRoot) } - } - $ownerRules = [IO.Path]::GetFullPath('.agents/rulebook/', $ownerRoot) - $destination = [IO.Path]::GetFullPath($unit.path, $ownerRoot) - if (-not $destination.StartsWith($ownerRules, [StringComparison]::Ordinal)) { throw "Rule path escapes owner: $($unit.id)" } - if ($external.ContainsKey($unit.id) -and -not $DocsRoot) { return $null } - $currentPath = $destination - while ($currentPath -and $currentPath.Length -ge $ownerRoot.Length) { - if (Test-Path -LiteralPath $currentPath) { - if ((Get-Item -LiteralPath $currentPath -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Rule authority cannot traverse a link: $($unit.id)" } - } - $currentPath = Split-Path $currentPath -Parent - } - return $destination -} -foreach ($unit in $manifest.units) { - if ($units.ContainsKey($unit.id)) { throw "Duplicate rule unit: $($unit.id)" } - $destination = Resolve-Authority $unit - $source = Read-Source $unit.source - if ($unit.PSObject.Properties.Name -contains 'sourceSection') { $source = [regex]::Split($source, '(?m)(?=^## )')[$unit.sourceSection] } - if ((Get-Hash $source.Trim()) -cne $unit.sourceHash) { throw "Changed source identity: $($unit.id)" } - foreach ($replacement in $manifest.pathReplacements) { $source = $source.Replace($replacement.old, $replacement.current) } - if ($null -eq $destination) { - $sourceLines = @(Get-RuleLines $source) - if ($unit.translation.language -cne 'en' -or [string]::IsNullOrWhiteSpace($unit.translation.approval) -or - $unit.translation.lines.Count -ne $sourceLines.Count) { throw "External rule source mapping is incomplete: $($unit.id)" } - for ($index = 0; $index -lt $sourceLines.Count; $index++) { - $line = $unit.translation.lines[$index] - if ($line.ordinal -ne $index + 1 -or $line.sourceHash -cne (Get-Hash (Normalize-RuleLine $sourceLines[$index])) -or - $line.targetHash -cnotmatch '^[a-f0-9]{64}$') { throw "Invalid external rule source clause: $($unit.id)" } - } - $units[$unit.id] = $unit - continue - } - $text = Get-Content -LiteralPath $destination -Raw - $pattern = '(?s)\s*\s*(.*?)\s*' - $matches = [regex]::Matches($text, $pattern) - if ($matches.Count -ne 1) { throw "Missing or repeated complete rule unit: $($unit.id)" } - $body = $matches[0].Groups[1].Value - $preservedBody = $body - if ($unit.PSObject.Properties.Name -contains 'approvedAddition') { - $parts = [regex]::Split($body, '(?m)^\r?$') - if ($parts.Count -ne 2 -or [string]::IsNullOrWhiteSpace($parts[1]) -or - [string]::IsNullOrWhiteSpace($unit.approvedAddition.approval)) { - throw "Invalid approved rule addition: $($unit.id)" - } - if ($unit.approvedAddition.PSObject.Properties.Name -contains 'translation') { - $additionOriginal = Read-Source $unit.approvedAddition.translation.source - $additionOriginal = [regex]::Match($additionOriginal, $pattern).Groups[1].Value - $additionParts = [regex]::Split($additionOriginal, '(?m)^\r?$') - if ($additionParts.Count -ne 2 -or (Get-Hash $additionParts[1].Replace("`r`n", "`n").Trim()) -cne $unit.approvedAddition.hash) { - throw "Invalid approved addition source: $($unit.id)" - } - Test-Translation @{ id = $unit.id + '/addition'; translation = $unit.approvedAddition.translation } $additionParts[1] $parts[1] - } elseif ((Get-Hash $parts[1].Replace("`r`n", "`n").Trim()) -cne $unit.approvedAddition.hash) { - throw "Invalid approved rule addition: $($unit.id)" + foreach ($tag in $fields.tags) { if ($tag -cnotmatch '^[a-z0-9-]+$') { throw "Invalid rule tag: $id -> $tag" } } + $size = [Text.Encoding]::UTF8.GetByteCount($text) + if ($size -gt $fileBudget) { throw "Rule file exceeds $fileBudget bytes; split it by topic: $id" } + [pscustomobject]@{ + id = $id; root = $root; file = $file.FullName; bytes = $size; tags = $fields.tags + patterns = @($fields.paths | ForEach-Object { ConvertTo-PathPattern $_ $id }) } - $preservedBody = $parts[0] } - if ($unit.PSObject.Properties.Name -contains 'translation') { - Test-Translation $unit $source $preservedBody - } elseif ((Normalize-Links $preservedBody) -cne (Normalize-Links $source)) { throw "Lost nested requirements, examples or prose: $($unit.id)" } - $units[$unit.id] = $unit; $bodies[$unit.id] = $body } -$original = Read-Source "$($manifest.baseline):AGENTS.md" + +$rootBytes = [Text.Encoding]::UTF8.GetByteCount((Get-Content -LiteralPath (Join-Path $repository 'AGENTS.md') -Raw)) +if ($rootBytes -gt $rootBudget) { throw "Root instructions exceed $rootBudget bytes." } +$catalog = @(Read-Rules $repository '') +$docs = $null if ($DocsRoot) { - foreach ($path in @($manifest.units | Where-Object repository | ForEach-Object path | Sort-Object -Unique)) { - foreach ($marker in [regex]::Matches([IO.File]::ReadAllText((Join-Path $DocsRoot $path)), '')) { - $id = $marker.Groups[1].Value - if (-not $external.ContainsKey($id) -or $units[$id].path -cne $path) { throw "Unregistered external rule authority: $id" } + $docs = (Resolve-Path -LiteralPath $DocsRoot).Path + $catalog += @(Read-Rules $docs 'docs/') +} +function Select-ByPath([string]$path) { + $full = [IO.Path]::GetFullPath($path, $repository) + $owner = if ($docs -and $full.StartsWith($docs + [IO.Path]::DirectorySeparatorChar, [StringComparison]::Ordinal)) { $docs } else { $repository } + $relative = [IO.Path]::GetRelativePath($owner, $full).Replace('\', '/') + if ($relative -cmatch '^\.\.(/|$)') { throw "Path is outside the repository: $path" } + foreach ($rule in $catalog) { + if ($rule.root -ceq $owner -and @($rule.patterns | Where-Object { $_.IsMatch($relative) }).Count) { [pscustomobject]@{ rule = $rule; reason = "path: $relative" } } + } +} + +$examplesPath = Join-Path $PSScriptRoot 'Test-AgentRules.examples.json' +if (Test-Path -LiteralPath $examplesPath) { + foreach ($example in Get-Content -LiteralPath $examplesPath -Raw | ConvertFrom-Json) { + $actual = @(Select-ByPath $example.path | ForEach-Object { $_.rule.id }) + foreach ($id in @($example.includes) + @($example.excludes)) { + if ($id -and -not @($catalog | Where-Object id -CEQ $id).Count) { throw "Routing example names an unknown rule: $id" } } - } -} -foreach ($file in Get-ChildItem -LiteralPath $ruleRoot -Filter '*.md' -Recurse) { - if ($file.Name -cne 'README.md' -and -not @($manifest.units | Where-Object { -not $_.repository -and [IO.Path]::GetFullPath($_.path, $repository) -ceq $file.FullName }).Count) { - throw "Unregistered rule file: $($file.FullName)" - } - foreach ($marker in [regex]::Matches((Get-Content -LiteralPath $file.FullName -Raw), '')) { - $id = $marker.Groups[1].Value - if (-not $units.ContainsKey($id) -or $units[$id].repository -or [IO.Path]::GetFullPath($units[$id].path, $repository) -cne $file.FullName) { - throw "Unregistered rule unit or authority: $id in $($file.FullName)" - } - } -} -$count = 0 -foreach ($section in [regex]::Matches($original, '(?ms)^## (\d+)\. .*?(?=^## \d+\. |\z)')) { - $number = [int]$section.Groups[1].Value; $ordinal = 0 - foreach ($bullet in [regex]::Matches($section.Value, '(?m)^- .*')) { - $ordinal++; $id = "$number.$ordinal" - $rows = @($manifest.rules | Where-Object id -CEQ $id) - if ($rows.Count -ne 1) { throw "Missing or duplicate rule mapping: $id" } - $row = $rows[0] - if ($row.originalHash -cne (Get-Hash $bullet.Value) -or -not $row.check -or -not $row.reviewer) { throw "Invalid provenance or responsibility: $id" } - if (-not $units.ContainsKey($row.unit) -or $units[$row.unit].path -cne $row.path -or $units[$row.unit].repository -cne $row.repository) { throw "Rule has no unique authority: $id" } - $expected = $bullet.Value - foreach ($replacement in $manifest.pathReplacements) { $expected = $expected.Replace($replacement.old, $replacement.current) } - if ($row.disposition -eq 'preserved') { - if ($units[$row.unit].PSObject.Properties.Name -contains 'translation') { - $mapping = @($units[$row.unit].translation.lines | Where-Object sourceHash -CEQ (Get-Hash (Normalize-RuleLine $expected))) - if ($mapping.Count -ne 1 -or $row.translatedHash -cne $mapping[0].targetHash) { throw "Rule translation was lost: $id" } - } elseif (-not (Normalize-Links $bodies[$row.unit]).Contains((Normalize-Links $expected), [StringComparison]::Ordinal)) { throw "Rule was lost: $id" } - } elseif ($number -ne 8 -or $row.disposition -ne 'superseded-by-approved-plan') { throw "Unapproved replacement: $id" } - $count++ - } -} -if ($count -ne $manifest.rules.Count) { throw 'Unknown baseline rule mappings.' } -$selected = @{} -$active = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) -$checked = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) -function Check-Dependencies([string]$id) { - if (-not $units.ContainsKey($id)) { throw "Unknown rule: $id" } - if ($checked.Contains($id)) { return } - if (-not $active.Add($id)) { throw "Cyclic rule dependency: $id" } - foreach ($dependency in $units[$id].requires) { Check-Dependencies $dependency } - [void]$active.Remove($id); [void]$checked.Add($id) -} -foreach ($id in $units.Keys) { Check-Dependencies $id } -foreach ($route in $manifest.routes) { - [void][regex]::new($route.pattern) - foreach ($id in $route.units) { - if (-not $units.ContainsKey($id)) { throw "Unknown routed rule: $id" } - } -} -function Select-Unit([string]$id, [string]$reason) { - if (-not $units.ContainsKey($id)) { throw "Unknown rule: $id" } - if ($selected.ContainsKey($id)) { $selected[$id].Add($reason); return } - $selected[$id] = [Collections.Generic.List[string]]::new(); $selected[$id].Add($reason) - foreach ($dependency in $units[$id].requires) { Select-Unit $dependency "required by $id" } -} -foreach ($id in $Rules) { Select-Unit $id 'explicit rule' } -foreach ($tag in $Behaviors) { - $matches = @($manifest.units | Where-Object { $tag -cin $_.tags }) - if ($matches.Count -eq 0) { throw "Unknown behavior: $tag" } - foreach ($unit in $matches) { Select-Unit $unit.id "behavior: $tag" } -} -foreach ($path in $Paths) { - $normalized = $path.Replace('\', '/') - if ([IO.Path]::IsPathRooted($path)) { $normalized = [IO.Path]::GetRelativePath($repository, $path).Replace('\', '/') } - foreach ($route in $manifest.routes) { - if ($normalized -match $route.pattern) { foreach ($id in $route.units) { Select-Unit $id "path: $normalized" } } - } -} -foreach ($file in @((Join-Path $repository 'AGENTS.md')) + @(Get-ChildItem -LiteralPath $ruleRoot -Filter '*.md' -Recurse | ForEach-Object FullName)) { - foreach ($link in [regex]::Matches((Get-Content -LiteralPath $file -Raw), '\]\(([^)#]+)(?:#[^)]*)?\)')) { - $target = $link.Groups[1].Value - if ($target -match '^[a-z]+:') { continue } - if (-not (Test-Path -LiteralPath ([IO.Path]::GetFullPath($target, (Split-Path $file))))) { throw "Broken instruction link: $file -> $target" } - } -} -$stages = [Collections.Generic.List[object]]::new() -$current = [Collections.Generic.List[string]]::new(); $bytes = $rootBytes -foreach ($id in ($selected.Keys | Sort-Object)) { - if (-not $bodies.ContainsKey($id)) { throw "Selected rule $id belongs to Wolfiora/InnoEngine.Docs. Supply -DocsRoot with the explicitly selected checkout; no network fetch or sibling-path guess is performed." } - $size = [Text.Encoding]::UTF8.GetByteCount($bodies[$id]) - if ($size + $rootBytes -gt $manifest.taskBudgetBytes) { throw "Unit $id needs smaller complete subchapters; truncation is forbidden." } - if ($bytes + $size -gt $manifest.taskBudgetBytes) { - $stages.Add(@{ ids = $current.ToArray(); bytes = $bytes }); $current.Clear(); $bytes = $rootBytes - } - $current.Add($id); $bytes += $size -} -$stages.Add(@{ ids = $current.ToArray(); bytes = $bytes }) -if ($Stage -lt 0 -or $Stage -gt $stages.Count) { throw 'Invalid instruction stage.' } -Write-Output "Preserved mapping: $count rules; $($units.Count) complete units. Root: $rootBytes bytes. Stages: $($stages.Count)." -if ($external.Count -gt 0) { - if ($DocsRoot) { Write-Output "External authority verified: $($external.Count) complete units in $([IO.Path]::GetFullPath($DocsRoot))." } - else { Write-Output "External authority not read: $($external.Count) source mappings only. Documentation work requires -DocsRoot; this result certifies engine-owned rule bodies only." } -} -for ($index = 0; $index -lt $stages.Count; $index++) { - $entry = $stages[$index] - Write-Output "Stage $($index + 1): $($entry.bytes) bytes; units: $($entry.ids -join ', ')" - foreach ($id in $entry.ids) { Write-Output "$id | $($units[$id].repository)/$($units[$id].path)#$id | source: $($units[$id].source) | $($selected[$id] -join '; ')" } - if ($ShowInstructions -and ($Stage -eq 0 -or $Stage -eq $index + 1)) { - Write-Output $rootText - foreach ($id in $entry.ids) { Write-Output $bodies[$id] } + foreach ($id in $example.includes) { if ($id -cnotin $actual) { throw "Routing example failed: $($example.path) must select $id" } } + foreach ($id in $example.excludes) { if ($id -cin $actual) { throw "Routing example failed: $($example.path) must not select $id" } } + } +} + +$selected = [ordered]@{} +function Add-Selection($rule, [string]$reason) { + if (-not $selected.Contains($rule.id)) { $selected[$rule.id] = @{ rule = $rule; reasons = [Collections.Generic.List[string]]::new() } } + $selected[$rule.id].reasons.Add($reason) +} +foreach ($id in $Rules) { + $rule = @($catalog | Where-Object id -CEQ $id) + if (-not $rule.Count) { throw "Unknown rule: $id" } + Add-Selection $rule[0] 'explicit rule' +} +foreach ($tag in $Tags) { + $tagged = @($catalog | Where-Object { $tag -cin $_.tags }) + if (-not $tagged.Count) { throw "Unknown tag: $tag" } + foreach ($rule in $tagged) { Add-Selection $rule "tag: $tag" } +} +foreach ($path in $Paths) { foreach ($match in Select-ByPath $path) { Add-Selection $match.rule $match.reason } } + +Write-Output "Rules are valid: $($catalog.Count) files. Root: $rootBytes bytes." +if ($selected.Count) { + $total = ($selected.Values | ForEach-Object { $_.rule.bytes } | Measure-Object -Sum).Sum + Write-Output "Read each file completely: $($selected.Count) files, $total bytes." + foreach ($entry in $selected.Values) { + $shown = if ($entry.rule.root -ceq $repository) { [IO.Path]::GetRelativePath($repository, $entry.rule.file).Replace('\', '/') } else { $entry.rule.file } + Write-Output "$shown | $(@($entry.reasons | Select-Object -Unique) -join '; ')" } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs index 72db4003a..aa3743ace 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs @@ -35,6 +35,20 @@ public void AgentLinksUseParsedHeadingsReferencesAndExplicitAnchorsWithoutReadin Assert.Contains("missing path", ArchitectureCommandFixture.Run(m_root, "--agent-documents-only").output); } + [Fact] + public void SkillsAreListedInTheRootInstructions() + { + string skill = Path.Combine(m_root, ".agents/skills/example"); + Directory.CreateDirectory(skill); + File.WriteAllText(Path.Combine(skill, "SKILL.md"), "---\nname: example\ndescription: Example workflow.\n---\n\nSteps.\n"); + File.WriteAllText(Path.Combine(m_root, "AGENTS.md"), "# Entry\n"); + var rejected = ArchitectureCommandFixture.Run(m_root, "--agent-documents-only"); + Assert.Equal(1, rejected.exitCode); + Assert.Contains("Skill is not listed in AGENTS.md: example", rejected.output); + File.AppendAllText(Path.Combine(m_root, "AGENTS.md"), "\n- [example](.agents/skills/example/SKILL.md): example workflow.\n"); + Assert.Equal(0, ArchitectureCommandFixture.Run(m_root, "--agent-documents-only").exitCode); + } + [Theory] [InlineData("--wiki")] [InlineData("--wiki-only")] diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs index 86f4be2a3..9f15f9f9b 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs @@ -124,7 +124,7 @@ void BindProjection(string signature) [InlineData(".agents/records/acceptance/native-reload.json", false)] [InlineData(".agents/records/plans/work.md", false)] [InlineData(".agents/skills/inno-change/SKILL.md", false)] - [InlineData(".agents/rulebook/coverage.json", true)] + [InlineData(".agents/rulebook/coding.md", true)] public async Task AgentTextChangesKeepProductAndInstructionEvidenceSeparate( string path, bool policyInput @@ -132,10 +132,10 @@ bool policyInput using var repository = new ValidationRepository(); repository.Write("tests/Native.Tests/Native.Tests.csproj", ValidationRepository.Project( "truenativeeditor")); - repository.Write(path, policyInput ? "{\"units\":[],\"review\":\"before\"}" : "before"); + repository.Write(path, "before"); repository.Git("add", "."); repository.Git("commit", "-m", "Declare agent document and native sentinel"); - repository.Write(path, policyInput ? "{\"units\":[],\"review\":\"after!\"}" : "after!"); + repository.Write(path, "after!"); using JsonDocument plan = await repository.PlanAsync(); Assert.False(plan.RootElement.GetProperty("full").GetBoolean()); Assert.False(plan.RootElement.GetProperty("contexts").TryGetProperty("native", out _)); @@ -148,17 +148,6 @@ bool policyInput Assert.DoesNotContain(plan.RootElement.GetProperty("inputSets").GetProperty("tooling").EnumerateArray(), input => input.GetString() == path); } - [Fact] - public async Task MalformedRuleRegistryCannotProduceAPlan() - { - using var repository = new ValidationRepository(); - repository.Write(".agents/rulebook/coverage.json", "not a registry"); - InvalidDataException failure = await Assert.ThrowsAsync(() => repository.PlanAsync()); - Assert.Contains(".agents/rulebook/coverage.json", failure.Message); - Assert.IsAssignableFrom(failure.InnerException); - Assert.False(File.Exists(repository.PathOf("artifacts/plan/plan.json"))); - } - [Fact] public async Task CanonicalFragmentOwnersSelectOnlyTheirDeclaredExampleContext() { diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationExecutionTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationExecutionTests.cs index 14e96768a..e7264867b 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationExecutionTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationExecutionTests.cs @@ -35,21 +35,18 @@ public async Task UnrelatedCliPayloadDoesNotInvalidateTheValidationToolEnvironme } [Fact] - public async Task ToolSourceInputsFollowEvaluatedReferencesAndPolicyIncludesItsReview() + public async Task ToolSourceInputsFollowEvaluatedReferencesAndPolicyIncludesRuleFiles() { using var repository = new ValidationRepository(); const string C_TOOL = "tools/Inno.Tooling.Validation/Inno.Tooling.Validation.csproj"; const string C_DEPENDENCY = "src/Example/ToolDependency.cs"; const string C_UNRELATED = "tools/Inno.Unrelated/Unrelated.cs"; - const string C_REVIEW = ".agents/records/decisions/translation.md"; + const string C_RULE = ".agents/rulebook/domains/example.md"; repository.Write(C_TOOL, ValidationRepository.Project("")); repository.Write(C_DEPENDENCY, "namespace Example; internal class ToolDependency { }"); repository.Write("tools/Inno.Unrelated/Inno.Unrelated.csproj", ValidationRepository.Project()); repository.Write(C_UNRELATED, "namespace Unrelated; internal class Unrelated { }"); - repository.Write(C_REVIEW, "# Reviewed translation\n"); - repository.Write(".agents/rulebook/coverage.json", """ - { "units": [{ "translation": { "review": ".agents/records/decisions/translation.md" } }] } - """); + repository.Write(C_RULE, "---\ntags: [example]\n---\n# Example\n"); repository.Git("add", "."); repository.Git("commit", "-m", "Declare actual tooling dependencies"); using JsonDocument plan = await repository.PlanAsync(); @@ -58,9 +55,9 @@ public async Task ToolSourceInputsFollowEvaluatedReferencesAndPolicyIncludesItsR Assert.Contains(C_TOOL, inputs); Assert.Contains(C_DEPENDENCY, inputs); Assert.DoesNotContain(C_UNRELATED, inputs); - Assert.DoesNotContain(C_REVIEW, inputs); + Assert.DoesNotContain(C_RULE, inputs); JsonElement policy = plan.RootElement.GetProperty("checks").EnumerateArray().Single(check => check.GetProperty("id").GetString() == "instructions"); - Assert.Contains(C_REVIEW, policy.GetProperty("inputs").EnumerateArray().Select(static value => value.GetString())); + Assert.Contains(C_RULE, policy.GetProperty("inputs").EnumerateArray().Select(static value => value.GetString())); } [Fact] diff --git a/tools/Inno.Tooling.Architecture/AgentDocumentValidator.cs b/tools/Inno.Tooling.Architecture/AgentDocumentValidator.cs index 1d118fc61..d9b3cd4c6 100644 --- a/tools/Inno.Tooling.Architecture/AgentDocumentValidator.cs +++ b/tools/Inno.Tooling.Architecture/AgentDocumentValidator.cs @@ -15,6 +15,8 @@ ICollection failures AgentLinkValidator.Validate(root, failures, ".agents"); foreach (string entry in new[] { "AGENTS.md", "CONTRIBUTING.md", "README.md" }) AgentLinkValidator.Validate(root, failures, entry); + string instructionPath = Path.Combine(root, "AGENTS.md"); + string instructions = File.Exists(instructionPath) ? File.ReadAllText(instructionPath) : string.Empty; foreach (string skill in RepositorySourceInventory.Files(Path.Combine(root, ".agents", "skills"), "SKILL.md")) { string text = File.ReadAllText(skill).Replace("\r\n", "\n"); @@ -22,6 +24,10 @@ ICollection failures if (!text.StartsWith("---\n", StringComparison.Ordinal) || !text.Contains("\nname: " + name + "\n", StringComparison.Ordinal) || !Regex.IsMatch(text, @"(?m)^description: \S.+$") || text.IndexOf("\n---\n", 4, StringComparison.Ordinal) < 0) failures.Add("Invalid skill metadata: " + Path.GetRelativePath(root, skill)); + if (!instructions.Contains("(.agents/skills/" + name + "/SKILL.md)", StringComparison.Ordinal)) + { + failures.Add("Skill is not listed in AGENTS.md: " + name); + } } foreach (string category in new[] { "rulebook", "records", "records/plans", "records/decisions", "records/acceptance", "records/history" }) if (!File.Exists(Path.Combine(root, ".agents", category, "README.md"))) diff --git a/tools/Inno.Tooling.Validation/ValidationCiContracts.cs b/tools/Inno.Tooling.Validation/ValidationCiContracts.cs index 07e1c0b3f..0713d77c4 100644 --- a/tools/Inno.Tooling.Validation/ValidationCiContracts.cs +++ b/tools/Inno.Tooling.Validation/ValidationCiContracts.cs @@ -7,6 +7,7 @@ namespace Inno.Tooling.Validation; internal static class ValidationCiContracts { internal const string C_RULE_LOADER = "tests/ci/Test-AgentRules.ps1"; + internal const string C_RULE_EXAMPLES = "tests/ci/Test-AgentRules.examples.json"; private const string C_DIRECTORY = "tests/ci/"; internal const string C_GATE = "tests/ci/Invoke-ValidationGate.ps1"; diff --git a/tools/Inno.Tooling.Validation/ValidationPlanner.cs b/tools/Inno.Tooling.Validation/ValidationPlanner.cs index c6eca060e..b04d67104 100644 --- a/tools/Inno.Tooling.Validation/ValidationPlanner.cs +++ b/tools/Inno.Tooling.Validation/ValidationPlanner.cs @@ -325,7 +325,7 @@ internal static async Task CreateAsync( } string[] policyInputs = inputs.Keys.Where(static path => path == "AGENTS.md" || path.StartsWith(".agents/rulebook/", StringComparison.Ordinal) - || path == ValidationCiContracts.C_RULE_LOADER).Concat(RuleReviewInputs()).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + || path is ValidationCiContracts.C_RULE_LOADER or ValidationCiContracts.C_RULE_EXAMPLES).Order(StringComparer.Ordinal).ToArray(); var inputSets = projects.ToDictionary(static project => project.path, project => CapturedInputs(project.inputs.Concat(nativeProjects[project.path].inputs)), StringComparer.Ordinal); var entryInputs = contexts.ToDictionary(static pair => pair.Key, @@ -345,7 +345,7 @@ internal static async Task CreateAsync( inputSets.Add("native-sources", submoduleInputs); var checks = new List { - new("instructions", "instructions", "AGENTS.md", "Rule preservation, discoverability, budgets and links.", "any", [], policyInputs, true, null), + new("instructions", "instructions", "AGENTS.md", "Rule front matter, size limits and routing examples.", "any", [], policyInputs, true, null), new("architecture", "architecture", "tools/Inno.Tooling.Architecture", "Cheap repository-wide source, ownership and architecture invariants.", "any", [], inputs.Keys.Where(static path => path.Split('/')[0] is "src" or "entry" or "backends" or "platforms" or "build" or "tools" || path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) @@ -746,47 +746,6 @@ void AddDocumentationChecks() Task GitAsync(params string[] arguments) => ValidationProcess.RunAsync("git", arguments, root, null, cancellation); - IEnumerable RuleReviewInputs() - { - const string C_REGISTRY = ".agents/rulebook/coverage.json"; - if (!inputs.ContainsKey(C_REGISTRY) || inputs[C_REGISTRY] == "missing") - yield break; - using JsonDocument registry = ReadRegistry(); - foreach (JsonElement unit in registry.RootElement.GetProperty("units").EnumerateArray()) - { - if (unit.TryGetProperty("translation", out JsonElement translation)) - { - yield return ReviewPath(translation); - if (translation.TryGetProperty("amendments", out JsonElement amendments)) - foreach (JsonElement amendment in amendments.EnumerateArray()) - yield return ReviewPath(amendment); - } - if (unit.TryGetProperty("approvedAddition", out JsonElement addition) - && addition.TryGetProperty("translation", out translation)) - yield return ReviewPath(translation); - } - - string ReviewPath(JsonElement translation) - { - string path = translation.GetProperty("review").GetString()!.Split('#', 2)[0]; - ValidationInputs.Resolve(root, path); - return path; - } - - JsonDocument ReadRegistry() - { - try - { - return JsonDocument.Parse(File.ReadAllBytes(ValidationInputs.Resolve(root, C_REGISTRY))); - } - catch (JsonException failure) - { - throw new InvalidDataException("Rule registry is invalid: " + C_REGISTRY, failure); - } - } - } - - string[] CapturedInputs(IEnumerable declared) { string[] paths = declared.ToArray(); @@ -827,7 +786,6 @@ private static bool IsCiContractInput(string path) private static bool IsDocumentation(string path) => path.EndsWith(".md", StringComparison.OrdinalIgnoreCase) - || path == ".agents/rulebook/coverage.json" || (path.StartsWith("docs/", StringComparison.Ordinal) || path.StartsWith(".agents/records/", StringComparison.Ordinal)) && (Path.GetExtension(path) is ".json" or ".csv" or ".png" or ".jpg" or ".svg" || path.EndsWith(".cs.txt", StringComparison.Ordinal)); } From 86ac4544fa6470824043aa7df8c3f03110639b6e Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 15:32:13 +0000 Subject: [PATCH 05/33] docs(rules): remove environment-specific and personal guidance Drop the local output drive from the root instructions, stop naming a macOS sound file in the completion sound rule, and use a neutral author placeholder in the contributor guide. --- .agents/records/decisions/PLAIN_MARKDOWN_RULES.md | 2 ++ .agents/rulebook/delivery.md | 2 +- AGENTS.md | 2 +- CONTRIBUTING.md | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.agents/records/decisions/PLAIN_MARKDOWN_RULES.md b/.agents/records/decisions/PLAIN_MARKDOWN_RULES.md index 2d07b3b6c..ef76fc330 100644 --- a/.agents/records/decisions/PLAIN_MARKDOWN_RULES.md +++ b/.agents/records/decisions/PLAIN_MARKDOWN_RULES.md @@ -13,3 +13,5 @@ On 2026-11-21 the user retired the rule registry. It was built to prove a one-ti - InnoEngine.Docs owns its rule files with the same front matter. The engine script reads them only from an explicit `-DocsRoot`. Earlier decision records describe changes in registry terms. Their rule text remains in force; the registry mechanics no longer apply. + +The same change removed environment-specific guidance: the local output drive, a platform sound path and a personal name used as an example. diff --git a/.agents/rulebook/delivery.md b/.agents/rulebook/delivery.md index 58664c7c5..53a706fcb 100644 --- a/.agents/rulebook/delivery.md +++ b/.agents/rulebook/delivery.md @@ -12,5 +12,5 @@ tags: [delivery, notification] - Reproduce BGCS defects independently through public APIs and identify them explicitly. Do not modify BGCS source, packages or binaries, or manually edit generated output to bypass defects. ## 16. Completion sound -- By default, play `/System/Library/Sounds/Glass.aiff` before waiting for a design decision that changes scope, after completing the final design, and after completing the requested code or file operations and their necessary validation. The user need not repeat this request for each task. +- By default, play the local system notification sound before waiting for a design decision that changes scope, after completing the final design, and after completing the requested code or file operations and their necessary validation. The user need not repeat this request for each task. - If the environment cannot access audio, state in the final result that the sound could not be played. Do not play it when the user explicitly requests silence. diff --git a/AGENTS.md b/AGENTS.md index 3a88e6a59..59d0c78ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,6 +26,6 @@ Skills describe workflows; they do not replace rules or maintain test lists. Def - [Records](.agents/records/README.md) hold necessary plans, lasting decisions and acceptance. A handoff retains scope, decisions, input identity, valid evidence, blockers and next action. Do not load historical records by default. - Complete all applicable behavior, callers, references, XML, documentation and validation in the approved task. Record unrelated improvements separately. Required regression, contract and tooling tests may change; unrelated rewrites, weaker assertions, reflection bypasses and test-only production visibility remain prohibited. - Evidence must match current inputs. Missing, skipped or unavailable checks are not passes. Commits, pushes, report edits and session recovery do not by themselves invalidate evidence. Reconcile the approved plan and report unfinished acceptance and external blockers accurately; continue actionable work. -- Reuse stable build directories by workspace, configuration and target; keep logs separate. Local output uses explicit C-drive owners. Clean only owned temporary artifacts through the existing lease, registry and retirement protocols. Protect other sessions, active readers, useful caches and first failures. Remote delivery follows user authorization and delivery rules. +- Reuse stable build directories by workspace, configuration and target; keep logs separate. Clean only owned temporary artifacts through the existing lease, registry and retirement protocols. Protect other sessions, active readers, useful caches and first failures. Remote delivery follows user authorization and delivery rules. Documentation CI uses incremental draft checks and complete release-candidate checks. API export preflight and owner/context reuse are independent of engine functional acceptance. Read the Docs README for current event and artifact boundaries. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 987e5b3db..aca294b50 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,7 +8,7 @@ Before implementation, identify the owner, observable behavior and finite accept For an API change, maintain its source XML and run the applicable engine checks. After a human merge to `master`, independent API export synchronizes eligible C# contracts and actual script projections into the Docs repository's persistent `draft` branch. This does not wait for unrelated full-engine acceptance. Backend, extern, test and fixture API references are excluded; their necessary engine tests remain. -Maintain tutorials and Manual changes separately in Docs, starting from `draft`. API types and members each have their own Markdown: `source: xml` (including an absent marker) is synchronized; `source: FLwolfy` preserves that symbol's prose. Generated declarations remain authoritative. Incomplete manual explanations produce non-blocking editorial warnings. A human merges Docs `draft` into `main` to publish the validated website. Engine PRs do not require paired Docs metadata. +Maintain tutorials and Manual changes separately in Docs, starting from `draft`. API types and members each have their own Markdown: `source: xml` (including an absent marker) is synchronized; `source: ` preserves that symbol's prose. Generated declarations remain authoritative. Incomplete manual explanations produce non-blocking editorial warnings. A human merges Docs `draft` into `main` to publish the validated website. Engine PRs do not require paired Docs metadata. Keep implementation and acceptance records in [.agents/records](.agents/records/README.md). Write active guidance and contributions in English; preserve historical evidence in its original form. Delivery must distinguish checks actually executed from work still outstanding. From c787fa8f5c375f73768a808a3d63c9a620772cdf Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 17:08:40 +0000 Subject: [PATCH 06/33] feat(docs): create and remove project guides with the API page policy API synchronization now applies the API page rules to project guides. A project outside platforms/ that no project page owns receives a registered synchronized guide beside its owner kind: tests/ projects under contributing/testing/projects, backends/ projects under backends/projects, all others under architecture/projects. A removed project deletes its synchronized guide and keeps an authored guide with a warning. Hand-authored pages without a registry entry are never registered, rewritten or deleted, and a checkout without the registry manages no guides. Synchronized guides no longer feed API category descriptions, so creating or removing one leaves every other planned page unchanged. --- .../DocumentationApiSynchronizationTests.cs | 89 +++++++++++++++++++ .../Indexing/DocumentationApiFragment.cs | 2 +- .../Indexing/DocumentationApiPresentation.cs | 10 ++- .../Indexing/DocumentationProjectGuides.cs | 74 +++++++++++++-- 4 files changed, 166 insertions(+), 9 deletions(-) diff --git a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs index 373ea4b1d..090f53e6c 100644 --- a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs +++ b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs @@ -74,6 +74,74 @@ public async Task ProjectGuideRegistryCannotClaimUnrelatedManualPages() Assert.Equal("Preserve this unrelated guide.", File.ReadAllText(Path.Combine(m_root, "content/en/manual/keep.md"))); } + [Fact] + public async Task NewProjectsReceiveSynchronizedGuidesBesideTheirOwnerKind() + { + const string C_AUTHORED = "content/en/contributing/testing/projects/authored.md"; + const string C_AUTHORED_TEXT = "---\nuid: project.authored\ntitle: Authored\nkind: project\nowners:\n - Inno.Authored.Tests\n---\n# Authored\n"; + WriteGuideRegistry(); + Write(C_AUTHORED, C_AUTHORED_TEXT); + SetProjects(("Inno.Probe", "src/Inno.Probe.csproj"), ("Inno.Probe.Tests", "tests/Inno.Probe.Tests/Inno.Probe.Tests.csproj"), + ("Inno.Adapter.Probe", "backends/Probe/Inno.Adapter.Probe.csproj"), ("Inno.Platform.Probe", "platforms/Probe/Inno.Platform.Probe.csproj"), + ("Inno.Authored.Tests", "tests/Inno.Authored.Tests/Inno.Authored.Tests.csproj")); + await Sync(); + string source = File.ReadAllText(Path.Combine(m_root, "content/en/architecture/projects/inno-probe.md")); + Assert.Contains("uid: project.inno-probe\nsymbol: project:Inno.Probe\ntitle: Inno.Probe\nkind: project\nowners:\n- Inno.Probe\n", source); + Assert.Contains("source: xml", source); + Assert.Contains("The value contract.", source); + Assert.Contains("source: xml", File.ReadAllText(Path.Combine(m_root, "content/en/contributing/testing/projects/inno-probe-tests.md"))); + Assert.Contains("source: xml", File.ReadAllText(Path.Combine(m_root, "content/en/backends/projects/inno-adapter-probe.md"))); + string[] expected = ["content/en/architecture/projects/inno-probe.md", "content/en/backends/projects/inno-adapter-probe.md", + "content/en/contributing/testing/projects/inno-probe-tests.md"]; + Assert.Equal(expected, GuideRegistry()); + Assert.Equal(C_AUTHORED_TEXT, File.ReadAllText(Path.Combine(m_root, C_AUTHORED))); + Assert.Single(Directory.GetFiles(Path.Combine(m_root, "content/en/contributing/testing/projects")), path => path.EndsWith("inno-probe-tests.md", StringComparison.Ordinal)); + Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); + string cache = Path.Combine(m_root, "artifacts/project-query"); + var indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); + using var snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); + Assert.Contains("[!SYNCED]", (await snapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.inno-probe-tests").markdown); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RemovedProjectsDeleteSynchronizedGuidesAndPreserveAuthoredGuides(bool manual) + { + const string C_PAGE = "content/en/architecture/projects/inno-retired.md"; + WriteGuideRegistry(); + SetProjects(("Inno.Probe", "src/Inno.Probe.csproj"), ("Inno.Retired", "tools/Inno.Retired/Inno.Retired.csproj")); + await Sync(); + string path = Path.Combine(m_root, C_PAGE); + if (manual) File.WriteAllText(path, File.ReadAllText(path).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) + "\nRetained guidance.\n"); + SetProjects(("Inno.Probe", "src/Inno.Probe.csproj")); + await Sync(); + Assert.Equal(manual, File.Exists(path)); + Assert.Equal(manual, GuideRegistry().Contains(C_PAGE)); + if (manual) Assert.Contains("Retained guidance.", File.ReadAllText(path)); + Assert.Contains("content/en/architecture/projects/inno-probe.md", GuideRegistry()); + Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); + } + + [Fact] + public async Task NewProjectGuidesCannotOverwriteUnregisteredFiles() + { + const string C_PAGE = "content/en/architecture/projects/inno-probe.md"; + WriteGuideRegistry(); + Write(C_PAGE, "Preserve this unregistered page."); + await Assert.ThrowsAsync(() => Sync(CancellationToken.None)); + Assert.Equal("Preserve this unregistered page.", File.ReadAllText(Path.Combine(m_root, C_PAGE))); + Assert.Empty(GuideRegistry()); + } + + [Fact] + public async Task CheckoutsWithoutAGuideRegistryDoNotManageProjectGuides() + { + await Sync(); + Assert.False(File.Exists(Path.Combine(m_root, "reference/projects/content.json"))); + Assert.False(Directory.Exists(Path.Combine(m_root, "content/en/architecture/projects"))); + } + [Theory] [InlineData("T:Inno.Probe.Value`1", "public class Inno.Probe.Value", "Value")] [InlineData("T:Inno.Probe.Value`2", "public class Inno.Probe.Value", "Value")] @@ -1015,6 +1083,27 @@ private void SetTypes(params (string id, string signature)[] types) Write("reference/engine.lock.json", binding.ToJsonString()); } + private void WriteGuideRegistry() + => Write("reference/projects/content.json", JsonSerializer.Serialize(new { schema = "inno-project-guides/1", entries = Array.Empty() })); + + private string[] GuideRegistry() + { + using JsonDocument registry = JsonDocument.Parse(File.ReadAllBytes(Path.Combine(m_root, "reference/projects/content.json"))); + return registry.RootElement.GetProperty("entries").EnumerateArray().Select(entry => entry.GetProperty("path").GetString()!).ToArray(); + } + + private void SetProjects(params (string name, string path)[] projects) + { + string inventory = JsonSerializer.Serialize(projects.Select(project => new + { + project.name, project.path, surfaces = new[] { "source-clr" }, isTest = project.path.StartsWith("tests/", StringComparison.Ordinal) + })); + Write("reference/projects/catalog.json", inventory); + JsonNode binding = JsonNode.Parse(File.ReadAllText(Path.Combine(m_root, "reference/engine.lock.json")))!; + binding["projectManifestIdentity"] = Hash(inventory); + Write("reference/engine.lock.json", binding.ToJsonString()); + } + private void SetTypeDocumentation(string xml) { JsonNode facts = JsonNode.Parse(File.ReadAllText(Path.Combine(m_root, "reference/api/probe.json")))!; diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFragment.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFragment.cs index fe949ff61..1090b224d 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFragment.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFragment.cs @@ -74,7 +74,7 @@ private string ProseFingerprint() => DocumentationMarkdown.Hash(System.Text.Json description = Summaries("").Select(value => value.ReplaceLineEndings("\n").Trim()) })); - private static bool IsNull(YamlNode node) + internal static bool IsNull(YamlNode node) => node is YamlScalarNode { Style: YamlDotNet.Core.ScalarStyle.Plain, Value: null or "" or "~" or "null" or "Null" or "NULL" }; internal string[] Summaries(string documentation) diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPresentation.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPresentation.cs index 9e3d11298..81f6c911d 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPresentation.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPresentation.cs @@ -68,8 +68,14 @@ internal static IReadOnlyDictionary ProjectDescriptions(string r || kind is not YamlScalarNode { Value: "project" }) continue; if (!metadata.Children.TryGetValue(new YamlScalarNode("owners"), out YamlNode? owners) || owners is not YamlSequenceNode sequence) continue; - string summary = metadata.Children.TryGetValue(new YamlScalarNode("description"), out YamlNode? description) - && description is YamlScalarNode { Value: string value } ? value + metadata.Children.TryGetValue(new YamlScalarNode("description"), out YamlNode? description); + if (description is not null && DocumentationApiFragment.IsNull(description)) description = null; + // A synchronized guide has no authored summary. Its generated body must not feed API navigation, + // so creating or removing the guide leaves every other planned page unchanged. + bool synchronized = metadata.Children.ContainsKey(new YamlScalarNode("symbol")) + && (!metadata.Children.TryGetValue(new YamlScalarNode("source"), out YamlNode? source) || source is YamlScalarNode { Value: "xml" }); + if (description is null && synchronized) continue; + string summary = description is YamlScalarNode { Value: string value } ? value : description is YamlSequenceNode items ? string.Join(" ", items.Children.Cast().Select(item => item.Value)) : Summary(text); foreach (YamlScalarNode owner in sequence.Children) diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs index 17eb0d03a..d57f404f0 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs @@ -24,6 +24,10 @@ internal static class DocumentationProjectGuides { internal const string C_REGISTRY = "reference/projects/content.json"; + private const string C_GUIDES = "content/en/architecture/projects/"; + private const string C_BACKEND_GUIDES = "content/en/backends/projects/"; + private const string C_TEST_GUIDES = "content/en/contributing/testing/projects/"; + internal static DocumentationProjectGuide[] Entries(string root) { string path = DocumentationApiFacts.Resolve(root, C_REGISTRY); @@ -37,7 +41,7 @@ internal static DocumentationProjectGuide[] Entries(string root) throw new InvalidDataException("Invalid project guide registry."); foreach (var entry in registry.entries) { - if (!entry.path.StartsWith("content/en/architecture/projects/", StringComparison.Ordinal) + if (!IsGuidePath(entry.path) || !entry.path.EndsWith(".md", StringComparison.Ordinal) || entry.path.Split('/').Any(segment => segment is ".." or "." or "")) throw new InvalidDataException("Project guide is outside its registered content directory."); @@ -55,15 +59,33 @@ IReadOnlyDictionary facts var warnings = new List(); var projects = JsonSerializer.Deserialize(File.ReadAllText(DocumentationApiFacts.Resolve(root, binding.projectManifest)))! .ToDictionary(project => project.name, StringComparer.Ordinal); - var entries = Entries(root); - foreach (var entry in entries) + var registered = Entries(root); + string registryPath = DocumentationApiFacts.Resolve(root, C_REGISTRY); + // A checkout without the registry does not manage project guides. + var created = File.Exists(registryPath) ? NewGuides(root, projects.Values, registered) : []; + var entries = new List(); + foreach (var entry in registered.Concat(created)) { - string text = File.ReadAllText(DocumentationApiFacts.Resolve(root, entry.path)); - var fragment = Read(entry, text); + bool isNew = !registered.Contains(entry); + string absolute = DocumentationApiFacts.Resolve(root, entry.path); + if (isNew && File.Exists(absolute)) + { + throw new InvalidDataException("Synchronization cannot overwrite an unregistered project guide: " + entry.path); + } + string? text = isNew ? null : File.ReadAllText(absolute); + var fragment = Read(entry, text ?? "---\nuid: " + entry.uid + "\nsymbol: project:" + entry.project + "\nsource: xml\n---\n"); projects.TryGetValue(entry.project, out var project); var contexts = facts.Values.SelectMany(context => context).Where(fact => fact.project == entry.project).ToArray(); string contract = Identity(project, contexts); bool manual = fragment.source != "xml"; + if (project is null && !manual) + { + // The same removal rule as API pages: synchronized prose leaves with its source, + // authored prose stays for editorial resolution. + edits.Add(new(entry.path, DocumentationMarkdown.Hash(text!), null)); + continue; + } + entries.Add(entry); string? staleProse = StaleProse(fragment, project, contexts, contract); bool stale = fragment.IsOutdated(staleProse); if (project is null) @@ -74,11 +96,51 @@ IReadOnlyDictionary facts warnings.Add(new(entry.project, entry.path, "ManualExplanationRequired", "This project guide uses generated source information.")); string updated = Metadata(entry, fragment, contract, staleProse) + (manual || project is null ? fragment.body : "\n\n" + Body(entry, contexts)); - if (updated != text) edits.Add(new(entry.path, DocumentationMarkdown.Hash(text), updated)); + if (updated != text) edits.Add(new(entry.path, text is null ? null : DocumentationMarkdown.Hash(text), updated)); + } + if (created.Length != 0 || entries.Count != registered.Length) + { + var registry = new DocumentationProjectGuideRegistry( + "inno-project-guides/1", + entries.OrderBy(entry => entry.path, StringComparer.Ordinal).ToArray() + ); + var options = new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" }; + edits.Add(new( + C_REGISTRY, + DocumentationMarkdown.Hash(File.ReadAllText(registryPath)), + JsonSerializer.Serialize(registry, options) + "\n" + )); } return new(edits, warnings, 0); } + private static bool IsGuidePath(string path) + => path.StartsWith(C_GUIDES, StringComparison.Ordinal) + || path.StartsWith(C_BACKEND_GUIDES, StringComparison.Ordinal) + || path.StartsWith(C_TEST_GUIDES, StringComparison.Ordinal); + + // Plans a synchronized guide for each reader-facing project that no project page owns yet. + // Authored project pages own their projects without a registry entry; synchronization never claims them. + private static DocumentationProjectGuide[] NewGuides( + string root, + IEnumerable projects, + DocumentationProjectGuide[] registered + ) { + var owned = new HashSet(registered.Select(entry => entry.project), StringComparer.Ordinal); + owned.UnionWith(DocumentationApiPresentation.ProjectDescriptions(root).Keys); + var guides = new List(); + foreach (var project in projects.OrderBy(project => project.name, StringComparer.Ordinal)) + { + if (project.path.StartsWith("platforms/", StringComparison.Ordinal) || owned.Contains(project.name)) continue; + string slug = project.name.ToLowerInvariant().Replace('.', '-'); + string directory = project.path.StartsWith("tests/", StringComparison.Ordinal) + ? C_TEST_GUIDES + : project.path.StartsWith("backends/", StringComparison.Ordinal) ? C_BACKEND_GUIDES : C_GUIDES; + guides.Add(new(directory + slug + ".md", "project." + slug, project.name)); + } + return guides.ToArray(); + } + internal static void Compose( string root, DocumentationBinding binding, From 5223abaf13971a9127c5e8a5ece3f5938d64413b Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 19:51:49 +0000 Subject: [PATCH 07/33] feat(tooling): check and fix C# style by rulebook rule ID Add a Roslyn style engine to Inno.Tooling.Architecture that reports each finding by rulebook rule ID and fixes it in place. Layout fixes must keep the token sequence, reorder fixes the token multiset, and every fix must reparse without syntax errors; a fix that fails is rejected and reported. `InnoEngine.Build style check|fix` exposes the engine, and architecture verification now runs it over production and test sources in place of the previous line-based style validator. Generated and third-party sources are skipped; a source that only writes a generated marker into a string is still handwritten. The rulebook record lists which rule IDs the tool reports today. --- .../decisions/CSHARP_STYLE_RULEBOOK.md | 22 + .editorconfig | 2 + .gitattributes | 3 +- build/cli/Inno.Build.Cli/BuildApplication.cs | 40 +- .../ArchitectureCommandTests.cs | 183 +++- .../StyleCommandTests.cs | 898 ++++++++++++++++++ .../ValidationCompletionTests.cs | 323 +++++-- .../ValidationHostContractsTests.cs | 52 +- .../ValidationTestOwnershipTests.cs | 59 +- .../ArchitectureValidator.cs | 532 ++++++++--- .../CSharpStyleValidator.cs | 54 +- .../Style/Rules/ArgumentJoinStyleRule.cs | 59 ++ .../Style/Rules/ArgumentListStyleRule.cs | 111 +++ .../Style/Rules/ArrowMemberStyleRule.cs | 160 ++++ .../Style/Rules/BraceBlankLineStyleRule.cs | 40 + .../Style/Rules/BraceListStyleRule.cs | 122 +++ .../Style/Rules/BraceStyleRule.cs | 104 ++ .../Style/Rules/ChainStyleRule.cs | 245 +++++ .../Style/Rules/ClauseStyleRule.cs | 95 ++ .../Style/Rules/EmbeddedBraceStyleRule.cs | 96 ++ .../Style/Rules/EmptyBodyStyleRule.cs | 103 ++ .../Style/Rules/FileStructureStyleRule.cs | 77 ++ .../Style/Rules/FileTextStyleRule.cs | 144 +++ .../Style/Rules/HeaderCloseStyleRule.cs | 77 ++ .../Style/Rules/LambdaBodyStyleRule.cs | 90 ++ .../Style/Rules/LeadingOperatorStyleRule.cs | 65 ++ .../Style/Rules/LineWidthStyleRule.cs | 283 ++++++ .../Style/Rules/MemberSpacingStyleRule.cs | 87 ++ .../Style/Rules/OperatorAlignmentStyleRule.cs | 104 ++ .../Style/Rules/ParameterCloseStyleRule.cs | 96 ++ .../Style/Rules/ParameterListStyleRule.cs | 84 ++ .../Style/Rules/SingleLineBlockStyleRule.cs | 93 ++ .../Style/Rules/TrailingCommaStyleRule.cs | 58 ++ .../Style/Rules/UsingOrderStyleRule.cs | 80 ++ .../Style/StyleCommand.cs | 87 ++ .../Style/StyleEdit.cs | 8 + .../Style/StyleEngine.cs | 232 +++++ .../Style/StyleFinding.cs | 8 + .../Style/StyleLayout.cs | 211 ++++ .../Style/StyleLines.cs | 71 ++ .../Style/StyleList.cs | 65 ++ .../Style/StyleOperators.cs | 95 ++ .../Style/StyleRejection.cs | 8 + .../Style/StyleReport.cs | 10 + .../Style/StyleRule.cs | 18 + .../Style/StyleRuleKind.cs | 11 + .../Style/StyleSource.cs | 147 +++ 47 files changed, 5314 insertions(+), 298 deletions(-) create mode 100644 tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ArgumentJoinStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ArgumentListStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ArrowMemberStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/BraceBlankLineStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/BraceListStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/BraceStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ChainStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ClauseStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/EmbeddedBraceStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/EmptyBodyStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/FileStructureStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/FileTextStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/HeaderCloseStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/LambdaBodyStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/LeadingOperatorStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/LineWidthStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/MemberSpacingStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/OperatorAlignmentStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ParameterCloseStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ParameterListStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/SingleLineBlockStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/TrailingCommaStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/UsingOrderStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleCommand.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleEdit.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleEngine.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleFinding.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleLayout.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleLines.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleList.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleOperators.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleRejection.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleReport.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleRuleKind.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/StyleSource.cs diff --git a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md index 2f11cfa4e..c7b823e66 100644 --- a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md +++ b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md @@ -41,3 +41,25 @@ The rulebook resolves these points where the approved revisions allowed more tha ## Consequences Existing source does not yet conform. Formatting and renaming are separate, later changes: formatting-only changes preserve syntax tokens, and acronym or field renames that touch public members are API changes. `.editorconfig` and the style validator still express the previous static-readonly naming and must follow the rulebook before they are used as gates. + +## Tooling status + +`InnoEngine.Build style check|fix ROOT` checks handwritten C# against the rulebook by rule ID and applies the automatic fixes; the architecture validator runs the same engine. A layout fix keeps the token sequence, a reorder keeps the token multiset, and a rewrite is rejected unless the result parses. + +The engine currently enforces these rules. A finding is reported under the first ID of its group. + +| Reported ID | Also covers | +| --- | --- | +| F-01, F-03, F-04, F-05 | | +| N-04 | | +| M-03 | | +| B-01, B-04, B-05, B-07 | B-06, B-08 | +| B-03 | T-06 | +| B-09 | M-01 | +| P-01, P-02 | | +| A-01, A-02 | A-03 | +| W-01, W-03, W-05 | W-02 | +| I-01, I-05 | I-03, I-04 | +| S-03, S-04 | | + +Every other rule is not yet checked by the tool and is enforced in review: F-02, N-01 to N-03, N-05, N-06, all NM rules, T-01 to T-05, T-07, T-08, M-02, M-04, M-05, B-02, P-03, A-04, W-04, I-02, S-01, S-02, all E, X, D and TS rules. Naming rules (NM) need symbol-level renames; `.editorconfig` keeps the previous static-readonly naming until those renames land. diff --git a/.editorconfig b/.editorconfig index 9b7881294..411c8916c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,6 +13,8 @@ indent_size = 2 [*.cs] indent_style = space indent_size = 4 +# F-04: aim for 120 columns; 140 is the hard limit checked by 'InnoEngine.Build style'. +max_line_length = 140 # Method and lambda bodies keep the opening brace with the closing parameter list. csharp_new_line_before_open_brace = types, properties, accessors, anonymous_types, control_blocks, object_collection_array_initializers csharp_using_directive_placement = outside_namespace:warning diff --git a/.gitattributes b/.gitattributes index 375b2ba2a..798584fc0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ -# Keep authored MSBuild files consistent on every checkout host. +# Keep authored C# and MSBuild files consistent on every checkout host. +*.cs text eol=lf *.csproj text eol=lf *.props text eol=lf *.targets text eol=lf diff --git a/build/cli/Inno.Build.Cli/BuildApplication.cs b/build/cli/Inno.Build.Cli/BuildApplication.cs index 7f7a4f6fc..ddabed792 100644 --- a/build/cli/Inno.Build.Cli/BuildApplication.cs +++ b/build/cli/Inno.Build.Cli/BuildApplication.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using Inno.Tooling.Architecture; using Inno.Tooling.Validation; + using DocumentationCommand = Inno.Tooling.Documentation.DocumentationCommand; namespace Inno.Build.Cli; @@ -34,10 +35,17 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(arguments); if (arguments.Length == 0 || arguments[0] is "help" or "--help" or "-h") { - Console.WriteLine("InnoEngine.Build [options]"); + Console.WriteLine( + "InnoEngine.Build [options]" + ); Console.WriteLine("Default entry command: support --product editor (current SDK host and entry configuration)."); - Console.WriteLine("support --product editor|player --target TARGET: prepare reusable target support without building the Editor's managed source."); + Console.WriteLine( + "support --product editor|player --target TARGET: prepare reusable target support without building the Editor's managed source." + ); Console.WriteLine("editor [--clean]: build the complete Editor entry and its dependencies."); + Console.WriteLine( + "style check|fix ROOT [--rule ID]... [--paths-from FILE] [--report FILE]: check handwritten C# against the style rulebook or apply its automatic fixes." + ); return 0; } try @@ -54,19 +62,33 @@ CancellationToken cancellationToken return await ProjectBuildWorkflow.RunAsync(arguments, cancellationToken); case "verify": return ArchitectureValidator.Execute(options, cancellationToken); + case "style": + return StyleCommand.Execute(options); case "docs": if (options.Length != 0 && options[0] == "export-plan") + { return await DocumentationReferences.PlanExportAsync(options[1..], cancellationToken); + } if (options.Length != 0 && options[0] == "export-projects") + { return DocumentationReferences.ExportProjects(options[1..], cancellationToken); + } if (options.Length > 0 && options[0] == "export-api") + { return DocumentationReferences.ExportApi(options[1..], cancellationToken); + } if (options.Length > 0 && options[0] == "validate-api") + { return await DocumentationReferences.ValidateApiAsync(options[1..], cancellationToken); + } if (options.Length > 0 && options[0] == "validate-examples") + { return await DocumentationExamples.ExecuteAsync(options[1..], cancellationToken); + } if (options.Length > 0 && options[0] == "example-plan") + { return await DocumentationExamples.ExecuteAsync([..options[1..], "--operation", "plan"], cancellationToken); + } return await DocumentationCommand.ExecuteAsync(options, cancellationToken); case "validate": return await ValidationCommand.ExecuteAsync(options, cancellationToken); @@ -91,8 +113,18 @@ CancellationToken cancellationToken "shader" => ["assets", "shader", "renderer", "output"], _ => [] }; - parsed.Validate(["engine-root", "dotnet", "target", "tools-target", "configuration", - "cache-budget-gib", "cache-min-free-gib", "cache-time-seconds", "native-dependencies", ..specific]); + parsed.Validate([ + "engine-root", + "dotnet", + "target", + "tools-target", + "configuration", + "cache-budget-gib", + "cache-min-free-gib", + "cache-time-seconds", + "native-dependencies", + ..specific + ]); var context = new BuildCommandContext(parsed); switch (command) { diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureCommandTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureCommandTests.cs index eb3ab9956..edb59537e 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureCommandTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureCommandTests.cs @@ -22,9 +22,11 @@ bool rejected File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); string project = Path.Combine(root, projectLocation); Directory.CreateDirectory(project); - File.WriteAllText(Path.Combine(project, Path.GetFileName(project) + ".csproj"), + File.WriteAllText( + Path.Combine(project, Path.GetFileName(project) + ".csproj"), "net10.0" - + ""); + + "" + ); (_, string output) = ArchitectureCommandFixture.Run(root); Assert.Equal(rejected, output.Contains("the interop runtime dependency belongs", StringComparison.Ordinal)); Assert.DoesNotContain("does not resolve to a repository project", output, StringComparison.Ordinal); @@ -32,7 +34,9 @@ bool rejected finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -50,23 +54,27 @@ string expected Directory.CreateDirectory(root); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); string relative = scenario == "target" - ? "platforms/WindowsX64/player/Inno.Player.WindowsX64" - : "src/foundation/core/Inno.Core.Probe"; + ? "platforms/WindowsX64/player/Inno.Player.WindowsX64" + : "src/foundation/core/Inno.Core.Probe"; string project = Path.Combine(root, relative); Directory.CreateDirectory(project); string properties = scenario == "target" ? "Exeplayerwindows-x64windows-x64" : string.Empty; - File.WriteAllText(Path.Combine(project, Path.GetFileName(project) + ".csproj"), + File.WriteAllText( + Path.Combine(project, Path.GetFileName(project) + ".csproj"), "net10.0" - + properties + ""); + + properties + "" + ); string imported; if (scenario == "reference") { string upper = Path.Combine(root, "platforms/MacOSArm64/runtime/Probe"); Directory.CreateDirectory(upper); - File.WriteAllText(Path.Combine(upper, "Probe.csproj"), - "net10.0"); + File.WriteAllText( + Path.Combine(upper, "Probe.csproj"), + "net10.0" + ); imported = ""; } else if (scenario == "source") @@ -77,11 +85,15 @@ string expected imported = ""; } else + { imported = "macos-arm64"; + } File.WriteAllText(Path.Combine(root, "Directory.Build.targets"), "" + imported + ""); string dotnet = Path.GetFullPath("../../../dotnet", RuntimeEnvironment.GetRuntimeDirectory()); if (OperatingSystem.IsWindows()) + { dotnet += ".exe"; + } string graph = Path.Combine(root, "evaluated.json"); (int code, string output) = ArchitectureCommandFixture.Run(root, "--dotnet", dotnet, "--project-graph", graph); Assert.Equal(1, code); @@ -93,7 +105,9 @@ string expected finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -110,28 +124,42 @@ bool rejected try { foreach (string folder in new[] { "src", "native", "build", "tools", "tests" }) + { Directory.CreateDirectory(Path.Combine(root, folder)); + } File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); File.WriteAllText(Path.Combine(root, "src", "Probe.cs"), source); (_, string output) = ArchitectureCommandFixture.Run(root); - Assert.Equal(rejected, output.Contains("place each parameter", StringComparison.Ordinal)); + Assert.Equal(rejected, output.Contains("P-01: Expand the parameter list", StringComparison.Ordinal)); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } [Theory] - [InlineData("Directory.Build.props", "true", "implicit usings", true)] + [InlineData( + "Directory.Build.props", + "true", + "implicit usings", + true + )] [InlineData("build/Probe.targets", "", "MSBuild Using", true)] [InlineData("tests/Probe.cs", "global using System;", "global using", true)] [InlineData("build/Probe.cs.txt", "global using System;", "global using", true)] - [InlineData("tests/Probe.cs", "using System; // global using is prohibited\ninternal class Probe { }", "global using", false)] - [InlineData("tests/Probe.cs", "internal class Probe { const string Message = \"global using System;\"; }", "global using", false)] + [InlineData("tests/Probe.cs", "using System; // global using is prohibited\n\ninternal class Probe;\n", "global using", false)] + [InlineData( + "tests/Probe.cs", + "internal class Probe\n{\n const string Message = \"global using System;\";\n}\n", + "global using", + false + )] public void CliRejectsCompilationWideImportsAcrossSourceAndBuildInputs( string relative, string content, @@ -152,27 +180,99 @@ bool rejected finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } [Theory] [InlineData("src/services/audio/Probe.cs", "global using System;", "global using", true)] - [InlineData("src/composition/player/Inno.Player.Runtime/Probe.cs", "internal class Probe { private BgfxDevice device; }", "backend-neutral", true)] - [InlineData("src/content/assets/Probe.cs", "internal class Probe { void Read() { context.With(resolver); } }", "owner-complete", true)] + [InlineData( + "src/composition/player/Inno.Player.Runtime/Probe.cs", + "internal class Probe { private BgfxDevice device; }", + "backend-neutral", + true + )] + [InlineData( + "src/content/assets/Probe.cs", + "internal class Probe { void Read() { context.With(resolver); } }", + "owner-complete", + true + )] [InlineData("src/services/audio/Probe.cs", "public class Probe { public MaEngine engine; }", "native implementation", true)] - [InlineData("src/services/audio/Probe.cs", "internal class Probe { void Release() { OnCleanupFailed(phase, failure); } }", "diagnostic-only", true)] - [InlineData("src/composition/editor/panels/Probe.cs", "using Ui = Inno.Editor.ImGui.ImGui; internal class Probe { void Draw() { for (int i = 0; i < 2; i++) { Ui.PushId(i); DrawRow(); if (i == 1) break; Ui.PopId(); } } }", "presentation loop ID scopes", true)] - [InlineData("src/composition/editor/panels/Probe.cs", "using Ui = Inno.Editor.ImGui.ImGui; internal class Probe { void Draw() { for (int i = 0; i < 2; i++) { Ui.PushId(i); try { DrawRow(); if (i == 1) break; } finally { Ui.PopId(); } } } }", "presentation loop ID scopes", false)] - [InlineData("src/composition/editor/panels/Probe.cs", "using Ui = Inno.Editor.ImGui.ImGui; using Other = Inno.Editor.ImGui.ImGui; internal class Probe { }", "multiple presentation aliases", true)] - [InlineData("src/composition/editor/panels/Probe.cs", "using Ui = Inno.Editor.ImGui.ImGui; using NativeUi = Inno.Native.ImGui.ImGui; internal class Probe { }", "multiple presentation aliases", false)] - [InlineData("src/composition/editor/panels/Probe.cs", "/// \n/// Removed identity.\n/// \n/// \n/// Actual section.\n/// \ninternal class Probe { }", "multiple XML summary elements", true)] - [InlineData("src/composition/editor/panels/Probe.cs", "/// \n/// Actual section.\n/// \ninternal class Probe { }", "multiple XML summary elements", false)] - [InlineData("src/services/Probe.cs", "using Ui = Inno.Editor.ImGui.ImGui; internal class Probe { void Draw() { for (int i = 0; i < 2; i++) { Ui.PushId(i); DrawRow(); Ui.PopId(); } } }", "presentation loop ID scopes", false)] - [InlineData("src/composition/editor/panels/Probe.cs", "internal class Probe { void Draw() { for (int i = 0; i < 2; i++) { collector.PushId(i); DrawRow(); collector.PopId(); } } }", "presentation loop ID scopes", false)] - [InlineData("src/services/audio/Probe.cs", "internal class Probe { void Release() { try { } catch (RetirementPendingException) { throw; } } }", "wrapped pending ownership", true)] - [InlineData("src/services/audio/Probe.cs", "internal class Probe { void Release() { try { } catch (Inno.Core.Execution.RetirementTimeoutException failure) { throw; } } }", "wrapped pending ownership", true)] - [InlineData("src/services/audio/Probe.cs", "internal class Probe { void Release() { try { } catch (Exception error) when (RetirementPendingException.Find(error) is not null) { throw; } } }", "wrapped pending ownership", false)] + [InlineData( + "src/services/audio/Probe.cs", + "internal class Probe { void Release() { OnCleanupFailed(phase, failure); } }", + "diagnostic-only", + true + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "using Ui = Inno.Editor.ImGui.ImGui; internal class Probe { void Draw() { for (int i = 0; i < 2; i++) { Ui.PushId(i); DrawRow(); if (i == 1) break; Ui.PopId(); } } }", + "presentation loop ID scopes", + true + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "using Ui = Inno.Editor.ImGui.ImGui;\n\ninternal class Probe\n{\n void Draw()\n {\n for (int i = 0; i < 2; i++)\n {\n Ui.PushId(i);\n try\n {\n DrawRow();\n if (i == 1) break;\n }\n finally\n {\n Ui.PopId();\n }\n }\n }\n}\n", + "presentation loop ID scopes", + false + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "using Ui = Inno.Editor.ImGui.ImGui; using Other = Inno.Editor.ImGui.ImGui; internal class Probe { }", + "multiple presentation aliases", + true + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "using NativeUi = Inno.Native.ImGui.ImGui;\nusing Ui = Inno.Editor.ImGui.ImGui;\n\ninternal class Probe;\n", + "multiple presentation aliases", + false + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "/// \n/// Removed identity.\n/// \n/// \n/// Actual section.\n/// \ninternal class Probe { }", + "multiple XML summary elements", + true + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "/// \n/// Actual section.\n/// \ninternal class Probe;\n", + "multiple XML summary elements", + false + )] + [InlineData( + "src/services/Probe.cs", + "using Ui = Inno.Editor.ImGui.ImGui;\n\ninternal class Probe\n{\n void Draw()\n {\n for (int i = 0; i < 2; i++)\n {\n Ui.PushId(i);\n DrawRow();\n Ui.PopId();\n }\n }\n}\n", + "presentation loop ID scopes", + false + )] + [InlineData( + "src/composition/editor/panels/Probe.cs", + "internal class Probe\n{\n void Draw()\n {\n for (int i = 0; i < 2; i++)\n {\n collector.PushId(i);\n DrawRow();\n collector.PopId();\n }\n }\n}\n", + "presentation loop ID scopes", + false + )] + [InlineData( + "src/services/audio/Probe.cs", + "internal class Probe { void Release() { try { } catch (RetirementPendingException) { throw; } } }", + "wrapped pending ownership", + true + )] + [InlineData( + "src/services/audio/Probe.cs", + "internal class Probe { void Release() { try { } catch (Inno.Core.Execution.RetirementTimeoutException failure) { throw; } } }", + "wrapped pending ownership", + true + )] + [InlineData( + "src/services/audio/Probe.cs", + "internal class Probe\n{\n void Release()\n {\n try\n {\n Run();\n }\n catch (Exception error) when (RetirementPendingException.Find(error) is not null)\n {\n throw;\n }\n }\n}\n", + "wrapped pending ownership", + false + )] public void CliValidatesSourceContracts( string relative, string source, @@ -183,7 +283,9 @@ bool rejected try { foreach (string folder in new[] { "src", "native", "build", "tools", "tests" }) + { Directory.CreateDirectory(Path.Combine(root, folder)); + } File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), """ Microsoft Visual Studio Solution File, Format Version 12.00 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{BBD55508-6095-4D53-B0E4-59B04BFB9376}" @@ -204,7 +306,9 @@ bool rejected (int code, string output) = ArchitectureCommandFixture.Run(root); Assert.Equal(1, code); if (rejected) + { Assert.Contains(expected, output, StringComparison.OrdinalIgnoreCase); + } else { Assert.DoesNotContain(expected, output, StringComparison.OrdinalIgnoreCase); @@ -214,7 +318,9 @@ bool rejected finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -236,7 +342,9 @@ bool rejected try { foreach (string folder in new[] { "src", "native", "build", "tools", "tests" }) + { Directory.CreateDirectory(Path.Combine(root, folder)); + } File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), """ Microsoft Visual Studio Solution File, Format Version 12.00 Global @@ -244,11 +352,13 @@ bool rejected """); string bindings = Path.Combine(root, "backends", "Probe", "native", "Inno.Native.Probe", "Bindings"); Directory.CreateDirectory(bindings); - File.WriteAllText(Path.Combine(Path.GetDirectoryName(bindings)!, "Inno.Native.Probe.csproj"), + File.WriteAllText( + Path.Combine(Path.GetDirectoryName(bindings)!, "Inno.Native.Probe.csproj"), "net10.0" + "true" + (scenario == "missing-import" ? string.Empty : "") - + ""); + + "" + ); File.WriteAllText(Path.Combine(bindings, "bindgen.json"), "{}"); string definition = """ @@ -262,13 +372,23 @@ bool rejected { "escaped-input" => definition.Replace("bindgen.json", "../outside.json", StringComparison.Ordinal), "missing-input" => definition.Replace("bindgen.json", "missing.json", StringComparison.Ordinal), - "unknown-property" => definition.Replace("", "bridge.json", StringComparison.Ordinal), - "conditional" => definition.Replace("", "", StringComparison.Ordinal), + "unknown-property" => definition.Replace( + "", + "bridge.json", + StringComparison.Ordinal + ), + "conditional" => definition.Replace( + "", + "", + StringComparison.Ordinal + ), "platform-table" => definition.Replace("", "", StringComparison.Ordinal), _ => definition }; if (scenario != "missing-definition") + { File.WriteAllText(Path.Combine(bindings, "bindings.props"), definition); + } (int code, string output) = ArchitectureCommandFixture.Run(root); @@ -278,8 +398,9 @@ bool rejected finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } - } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs new file mode 100644 index 000000000..701a34005 --- /dev/null +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs @@ -0,0 +1,898 @@ +using System; +using System.IO; +using Xunit; + +namespace Inno.Tooling.Architecture.Tests; + +public sealed class StyleCommandTests +{ + public static TheoryData Fixes() + => new() + { + { + "F-01", + "internal sealed class Probe; \r\n\r\n", + Source( + """ + internal sealed class Probe; + """ + ) + }, + { + "N-04", + Source( + """ + using Inno.Core; + using static System.Math; + using System; + + namespace Probe; + """ + ), + Source( + """ + using System; + using Inno.Core; + + using static System.Math; + + namespace Probe; + """ + ) + }, + { + "F-03", + "\nusing System;\nnamespace Probe;\ninternal sealed class Probe;\n", + Source( + """ + using System; + + namespace Probe; + + internal sealed class Probe; + """ + ) + }, + { + "S-03", + Source( + """ + internal sealed class Probe + { + internal void First() {} + internal void Second() {} + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void First() {} + + internal void Second() {} + } + """ + ) + }, + { + "S-04", + Source( + """ + internal sealed class Probe + { + + internal void First() {} + + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void First() {} + } + """ + ) + }, + { + "A-01", + Source( + """ + internal sealed class Probe + { + internal int Run() => Add(1, + 2); + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal int Run() => Add(1, 2); + } + """ + ) + }, + { + "A-02", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Register(firstArgumentWithALongName, secondArgumentWithALongName, thirdArgumentWithALongName, + fourthArgumentWithALongName, fifthArgumentWithALongName); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Register( + firstArgumentWithALongName, + secondArgumentWithALongName, + thirdArgumentWithALongName, + fourthArgumentWithALongName, + fifthArgumentWithALongName + ); + } + } + """ + ) + }, + { + "P-01", + Source( + """ + internal sealed class Probe + { + internal void Run(int first, int second) {} + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run( + int first, + int second + ) {} + } + """ + ) + }, + { + "P-02", + Source( + """ + internal sealed class Probe + { + internal void Run( + int first, + int second + ) + { + Step(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run( + int first, + int second + ) { + Step(); + } + } + """ + ) + }, + { + "B-03", + Source( + """ + internal sealed class Probe : Base + { + internal Probe(int value) : base(value) {} + } + """ + ), + Source( + """ + internal sealed class Probe : Base + { + internal Probe(int value) + : base(value) {} + } + """ + ) + }, + { + "M-03", + Source( + """ + internal sealed class Probe + { + internal int Run() => + m_value; + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal int Run() => m_value; + } + """ + ) + }, + { + "W-01", + Source( + """ + internal sealed class Probe + { + internal bool Run() => m_first && + m_second; + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal bool Run() + => m_first + && m_second; + } + """ + ) + }, + { + "W-03", + Source( + """ + internal sealed class Probe + { + internal int Run() + { + return m_values.Where(static value => value > 0).Select(static value => value * 2). + Sum(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal int Run() + { + return m_values.Where(static value => value > 0) + .Select(static value => value * 2) + .Sum(); + } + } + """ + ) + }, + { + "B-09", + Source( + """ + internal sealed class Probe + { + internal void Run() { Step(); } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Step(); + } + } + """ + ) + }, + { + "B-04", + Source( + """ + internal sealed class Probe + { + internal bool Run() => m_entries.All(static entry => entry.isReadyForPresentation && entry.owner.isVisibleInHierarchy + && entry.isVisible); + + internal Func Count() => () => m_first.TryGetValue( + m_key, + out int value + ) && value > 0 + ? value + : 0; + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal bool Run() + => m_entries.All(static entry => ( + entry.isReadyForPresentation && entry.owner.isVisibleInHierarchy + && entry.isVisible + )); + + internal Func Count() + => () => ( + m_first.TryGetValue(m_key, out int value) && value > 0 + ? value + : 0 + ); + } + """ + ) + }, + { + "F-04", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_width >= 500) Assert.True(m_details, "The details column is expected to be visible once the panel is at least five hundred wide."); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_width >= 500) + { + Assert.True(m_details, "The details column is expected to be visible once the panel is at least five hundred wide."); + } + } + } + """ + ) + }, + { + "B-01", + Source( + """ + internal sealed class Probe { + internal void Run() { + Step(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Step(); + } + } + """ + ) + }, + { + "B-07", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + } + + private sealed class Empty { } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() {} + + private sealed class Empty; + } + """ + ) + }, + { + "W-05", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_first + && m_second) + { + Step(); + } + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_first + && m_second + ) { + Step(); + } + } + } + """ + ) + }, + { + "B-05", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_first) + Step(); + foreach (int value in m_values) Step(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + if (m_first) + { + Step(); + } + foreach (int value in m_values) + { + Step(); + } + } + } + """ + ) + }, + { + "F-05", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + bool both = m_first + && m_second; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + bool both = m_first + && m_second; + } + } + """ + ) + }, + { + "I-01", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var options = new Options { + first = 1, second = 2 }; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var options = new Options + { + first = 1, + second = 2 + }; + } + } + """ + ) + }, + { + "I-05", + Source( + """ + internal enum Probe + { + First, + Second, + } + """ + ), + Source( + """ + internal enum Probe + { + First, + Second + } + """ + ) + }, + { + "F-04", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Register(firstArgumentWithALongName, secondArgumentWithALongName, thirdArgumentWithALongName, fourthArgumentWithALongName, fifthArgumentWithALongName); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Register( + firstArgumentWithALongName, + secondArgumentWithALongName, + thirdArgumentWithALongName, + fourthArgumentWithALongName, + fifthArgumentWithALongName + ); + } + } + """ + ) + }, + { + "M-03", + Source( + """ + internal sealed class Probe + { + internal string Label() => m_isMissing ? "The asset is missing from the project." : + m_displayName; + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal string Label() + => m_isMissing + ? "The asset is missing from the project." + : m_displayName; + } + """ + ) + }, + { + "I-01", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var options = new ProbeOptions + { first = 1, second = 2 }; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var options = new ProbeOptions { first = 1, second = 2 }; + } + } + """ + ) + }, + { + "F-04", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + List names = m_entries.Where(static entry => !entry.isMissing && entry.isVisible).Select(static entry => entry.displayName).OrderBy(static name => name).ToList(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + List names = m_entries + .Where(static entry => !entry.isMissing && entry.isVisible) + .Select(static entry => entry.displayName) + .OrderBy(static name => name) + .ToList(); + } + } + """ + ) + }, + { + "F-04", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + bool changed = previous.width != current.width || previous.height != current.height || previous.format != current.format || previous.depth != current.depth; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + bool changed = previous.width != current.width + || previous.height != current.height + || previous.format != current.format + || previous.depth != current.depth; + } + } + """ + ) + }, + { + "F-04", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Report($"The viewport '{viewport.name}' does not support the requested mode '{Describe(defaultMode, viewport.capabilities)}' in '{viewport.owner}'."); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Report( + $"The viewport '{viewport.name}' does not support the requested mode '{Describe(defaultMode, viewport.capabilities)}' in '{viewport.owner}'." + ); + } + } + """ + ) + } + }; + + [Theory] + [MemberData(nameof(Fixes))] + public void FixRewritesTheReportedViolationAndLeavesNoFinding( + string rule, + string before, + string after + ) { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", "Probe.cs"); + string report = Path.Combine(root, "report.tsv"); + File.WriteAllText(path, before); + + Assert.Equal(1, StyleCommand.Execute(["check", root, "--rule", rule, "--report", report])); + Assert.StartsWith(rule + "\tsrc/Probe.cs\t", File.ReadAllText(report), StringComparison.Ordinal); + Assert.Equal(before, File.ReadAllText(path)); + + Assert.Equal(0, StyleCommand.Execute(["fix", root])); + Assert.Equal(after, File.ReadAllText(path)); + Assert.Equal(0, StyleCommand.Execute(["check", root])); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Theory] + [InlineData("src/Generated/Probe.cs", "internal sealed class Probe { }\n")] + [InlineData("src/Probe.cs", "// \ninternal sealed class Probe { }\n")] + [InlineData("src/Probe.cs", "[GeneratedCode(\"Tool\", \"1\")]\ninternal sealed class Probe { }\n")] + [InlineData("extern/Probe.cs", "internal sealed class Probe { }\n")] + [InlineData("src/obj/Probe.cs", "internal sealed class Probe { }\n")] + public void GeneratedAndThirdPartySourcesAreNeitherReportedNorRewritten( + string relativePath, + string content + ) { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, relativePath); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + + Assert.Equal(0, StyleCommand.Execute(["check", root])); + Assert.Equal(0, StyleCommand.Execute(["fix", root])); + Assert.Equal(content, File.ReadAllText(path)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Theory] + [InlineData("// ")] + [InlineData("[GeneratedCode(\\\"Tool\\\", \\\"1\\\")]")] + public void SourcesThatOnlyWriteAGeneratedMarkerAreHandwritten(string marker) + { + string content = + "internal sealed class Probe\n{\n internal string Run() { return \"" + marker + "\"; }\n}\n"; + + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", "Probe.cs"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + + Assert.Equal(1, StyleCommand.Execute(["check", root])); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Fact] + public void FixKeepsTextInsideMultiLineStrings() + { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", "Probe.cs"); + string content = "internal sealed class Probe\n{\n internal string Text() => \"\"\"\n if (first) { \n second();\n \"\"\";\n}\n"; + File.WriteAllText(path, content); + + Assert.Equal(0, StyleCommand.Execute(["fix", root])); + Assert.Equal(content, File.ReadAllText(path)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Fact] + public void FixLeavesASourceWithSyntaxErrorsUnchangedAndFails() + { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", "Probe.cs"); + string content = "internal sealed class Probe {\n internal void Run( {\n}\n"; + File.WriteAllText(path, content); + + Assert.Equal(1, StyleCommand.Execute(["fix", root])); + Assert.Equal(content, File.ReadAllText(path)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Fact] + public void PathsFromLimitsTheRunToTheListedSources() + { + string root = CreateRoot(); + try + { + string listed = Path.Combine(root, "src", "Listed.cs"); + string other = Path.Combine(root, "src", "Other.cs"); + string paths = Path.Combine(root, "paths.txt"); + File.WriteAllText(listed, "internal sealed class Listed { }\n"); + File.WriteAllText(other, "internal sealed class Other { }\n"); + File.WriteAllText(paths, "src/Listed.cs\n"); + + Assert.Equal(0, StyleCommand.Execute(["fix", root, "--paths-from", paths])); + Assert.Equal("internal sealed class Listed;\n", File.ReadAllText(listed)); + Assert.Equal("internal sealed class Other { }\n", File.ReadAllText(other)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + + [Theory] + [InlineData] + [InlineData("check")] + [InlineData("format", ".")] + [InlineData("check", ".", "--rule")] + [InlineData("check", ".", "--unknown", "value")] + public void InvalidArgumentsAreRejected(params string[] arguments) + { + Assert.Throws(() => StyleCommand.Execute(arguments)); + } + + private static string CreateRoot() + { + string root = Path.Combine(Path.GetTempPath(), "InnoStyleCommandTests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Path.Combine(root, "src")); + return root; + } + + private static string Source(string text) => text + "\n"; +} diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs index ba75b4621..acd34f107 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs @@ -1,13 +1,13 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Testing.Source; +using Inno.Testing.Validation; using Inno.Tooling.Documentation; -using Xunit; namespace Inno.Tooling.Validation.Integration.Tests; @@ -32,10 +32,15 @@ private static async Task ChangedUnionRootsAsync( const string C_FIXTURE = "tests/input/fixtures/Inno.Input.CompilationFixture"; const string C_PROJECT = "tests/input/Inno.Input.Tests/Inno.Input.Tests.csproj"; const string C_TEST = "tests/input/Inno.Input.Tests/UnionCompilationProbe.cs"; - repository.Write(C_FIXTURE + "/Inno.Input.CompilationFixture.csproj", ValidationRepository.Project( - "")); + repository.Write( + C_FIXTURE + "/Inno.Input.CompilationFixture.csproj", + ValidationRepository.Project( + "" + ) + ); repository.Write(C_FIXTURE + "/Probe.cs", """ namespace Inno.Input.CompilationFixture; + /// Exposes a real fixture compilation value. public static class Probe { @@ -43,27 +48,43 @@ public static class Probe /// The current fixture value. public static int Read() => 1; } + """); - repository.Write(C_PROJECT, File.ReadAllText(repository.PathOf(C_PROJECT)).Replace("", - "true", StringComparison.Ordinal) - .Replace("", + "true", + StringComparison.Ordinal + ) + .Replace(" Assert.Equal(1, Probe.Read()); } + """); if (lateSelection) { - repository.Write(C_PROJECT, File.ReadAllText(repository.PathOf(C_PROJECT)) - .Replace("", - string.Empty, StringComparison.Ordinal) - .Replace("", """ + repository.Write( + C_PROJECT, + File.ReadAllText(repository.PathOf(C_PROJECT)) + .Replace( + "", + string.Empty, + StringComparison.Ordinal + ) + .Replace("", """ @@ -73,16 +94,26 @@ public sealed class UnionCompilationProbe - """, StringComparison.Ordinal)); + """, StringComparison.Ordinal) + ); } - repository.Write("Directory.Build.targets", File.ReadAllText(repository.PathOf("Directory.Build.targets")).Replace("", """ + repository.Write( + "Directory.Build.targets", + File.ReadAllText(repository.PathOf("Directory.Build.targets")).Replace("", """ - """, StringComparison.Ordinal)); - await repository.SdkAsync("sln", "InnoEngine.sln", "add", C_FIXTURE + "/Inno.Input.CompilationFixture.csproj", - "--solution-folder", "tests/input/fixtures"); + """, StringComparison.Ordinal) + ); + await repository.SdkAsync( + "sln", + "InnoEngine.sln", + "add", + C_FIXTURE + "/Inno.Input.CompilationFixture.csproj", + "--solution-folder", + "tests/input/fixtures" + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare the compilation dependency and its real assertion"); var documentation = new ValidationDocumentationFixture(repository); @@ -103,24 +134,43 @@ await repository.SdkAsync("sln", "InnoEngine.sln", "add", C_FIXTURE + "/Inno.Inp { if (value == 3 && variant) { - repository.Write(C_PROJECT, File.ReadAllText(repository.PathOf(C_PROJECT)).Replace( - "Inno.Input.CompilationFixture.csproj\"", "Inno.Input.CompilationFixture.csproj\" AdditionalProperties=\"ArtifactsPath=$(ArtifactsPath)/variant\"", - StringComparison.Ordinal)); + repository.Write( + C_PROJECT, + File.ReadAllText(repository.PathOf(C_PROJECT)).Replace( + "Inno.Input.CompilationFixture.csproj\"", + "Inno.Input.CompilationFixture.csproj\" AdditionalProperties=\"ArtifactsPath=$(ArtifactsPath)/variant\"", + StringComparison.Ordinal + ) + ); repository.Git("add", C_PROJECT); repository.Git("commit", "-m", "Consume a second effective property instance"); // The first real run has established workspace ownership. Restore the extra NuGet output instance before measuring it. - using (await Inno.Core.IO.CoordinatedFileLease.AcquireAsync(Path.Combine(Path.GetDirectoryName(workspace)!, "owner.lock"), - workspace + ".lock", Timeout.InfiniteTimeSpan, cancellationToken: cancellation.Token)) - await repository.SdkAsync("restore", C_FIXTURE + "/Inno.Input.CompilationFixture.csproj", - "-p:ArtifactsPath=" + variantArtifacts, "-p:Configuration=Debug", "--disable-parallel", "-nr:false"); + using (await Inno.Core.IO.CoordinatedFileLease.AcquireAsync( + Path.Combine(Path.GetDirectoryName(workspace)!, "owner.lock"), + workspace + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken: cancellation.Token + )) { + await repository.SdkAsync( + "restore", + C_FIXTURE + "/Inno.Input.CompilationFixture.csproj", + "-p:ArtifactsPath=" + variantArtifacts, + "-p:Configuration=Debug", + "--disable-parallel", + "-nr:false" + ); + } } foreach (string relative in new[] { C_FIXTURE + "/Probe.cs", C_TEST }) { string path = repository.PathOf(relative); DateTime timestamp = File.GetLastWriteTimeUtc(path); - repository.Write(relative, File.ReadAllText(path) - .Replace("=> " + (value - 1), "=> " + value, StringComparison.Ordinal) - .Replace("Assert.Equal(" + (value - 1), "Assert.Equal(" + value, StringComparison.Ordinal)); + repository.Write( + relative, + File.ReadAllText(path) + .Replace("=> " + (value - 1), "=> " + value, StringComparison.Ordinal) + .Replace("Assert.Equal(" + (value - 1), "Assert.Equal(" + value, StringComparison.Ordinal) + ); File.SetLastWriteTimeUtc(path, timestamp); } using (JsonDocument plan = await documentation.PlanAsync(documentationSnapshot)) @@ -128,33 +178,86 @@ await repository.SdkAsync("restore", C_FIXTURE + "/Inno.Input.CompilationFixture Assert.False(plan.RootElement.GetProperty("contexts").TryGetProperty("native", out _)); Assert.Equal(2, plan.RootElement.GetProperty("owners").GetArrayLength()); if (lateSelection) - Assert.DoesNotContain(plan.RootElement.GetProperty("contexts").GetProperty("managed").GetProperty("sdkGraph").EnumerateArray() - .Single(snapshot => snapshot.GetProperty("Path").GetString()!.EndsWith("Inno.Input.Tests.csproj", StringComparison.Ordinal)) - .GetProperty("Items").GetProperty("ProjectReference").EnumerateArray(), reference => - reference.GetProperty("FullPath").GetString()!.EndsWith("Inno.Input.CompilationFixture.csproj", StringComparison.Ordinal)); - JsonElement fixture = plan.RootElement.GetProperty("contexts").GetProperty("managed").GetProperty("sdkGraph").EnumerateArray() - .Single(snapshot => snapshot.GetProperty("Path").GetString()!.EndsWith("Inno.Input.CompilationFixture.csproj", StringComparison.Ordinal)); + { + Assert.DoesNotContain( + plan.RootElement.GetProperty("contexts") + .GetProperty("managed") + .GetProperty("sdkGraph") + .EnumerateArray() + .Single( + snapshot => snapshot + .GetProperty("Path") + .GetString()! + .EndsWith("Inno.Input.Tests.csproj", StringComparison.Ordinal) + ) + .GetProperty("Items") + .GetProperty("ProjectReference") + .EnumerateArray(), + reference => + reference + .GetProperty("FullPath") + .GetString()! + .EndsWith("Inno.Input.CompilationFixture.csproj", StringComparison.Ordinal) + ); + } + JsonElement fixture = plan.RootElement + .GetProperty("contexts") + .GetProperty("managed") + .GetProperty("sdkGraph") + .EnumerateArray() + .Single( + snapshot => snapshot + .GetProperty("Path") + .GetString()! + .EndsWith("Inno.Input.CompilationFixture.csproj", StringComparison.Ordinal) + ); if (variant && value >= 3) - Assert.Contains(fixture.GetProperty("Variants").EnumerateArray(), instance => + { + Assert.Contains(fixture.GetProperty("Variants").EnumerateArray(), instance => ( instance.GetProperty("Properties").GetProperty("TargetPath").GetString() - != fixture.GetProperty("Properties").GetProperty("TargetPath").GetString()); + != fixture.GetProperty("Properties").GetProperty("TargetPath").GetString() + )); + } else + { Assert.Empty(fixture.GetProperty("Variants").EnumerateArray()); - variantArtifacts = Path.Combine(plan.RootElement.GetProperty("contexts").GetProperty("managed").GetProperty("properties") - .GetProperty("ArtifactsPath").GetString()!, "variant"); + } + variantArtifacts = Path.Combine( + plan.RootElement.GetProperty("contexts") + .GetProperty("managed") + .GetProperty("properties") + .GetProperty("ArtifactsPath") + .GetString()!, + "variant" + ); variantArtifacts = repository.BindWorkspace(variantArtifacts); workspace = repository.BindWorkspace(plan.RootElement.GetProperty("artifacts").GetString()!); string environment = plan.RootElement.GetProperty("environment").GetString()!; if (value == 3) + { restoredEnvironment = environment; + } else if (value == 4) + { Assert.Equal(restoredEnvironment, environment); - dependencyOutput = plan.RootElement.GetProperty("contexts").GetProperty("managed").GetProperty("sdkGraph").EnumerateArray() + } + dependencyOutput = plan.RootElement.GetProperty("contexts") + .GetProperty("managed") + .GetProperty("sdkGraph") + .EnumerateArray() .Single(snapshot => snapshot.GetProperty("Path").GetString()!.EndsWith("Inno.Core.IO.csproj", StringComparison.Ordinal)) - .GetProperty("Properties").GetProperty("TargetPath").GetString()!; + .GetProperty("Properties") + .GetProperty("TargetPath") + .GetString()!; dependencyOutput = repository.BindWorkspace(dependencyOutput); - dependencyBuildLog = Path.Combine(plan.RootElement.GetProperty("contexts").GetProperty("managed") - .GetProperty("properties").GetProperty("ArtifactsPath").GetString()!, "dependency-builds.log"); + dependencyBuildLog = Path.Combine( + plan.RootElement.GetProperty("contexts") + .GetProperty("managed") + .GetProperty("properties") + .GetProperty("ArtifactsPath") + .GetString()!, + "dependency-builds.log" + ); dependencyBuildLog = repository.BindWorkspace(dependencyBuildLog); } string output = "artifacts/union-" + value; @@ -165,22 +268,38 @@ await repository.SdkAsync("restore", C_FIXTURE + "/Inno.Input.CompilationFixture catch (Exception failure) { string runDirectory = repository.PathOf(output); - string diagnostics = string.Join("\n", Directory.Exists(runDirectory) - ? Directory.EnumerateFiles(runDirectory, "*.log").Select(path => Path.GetFileName(path) + ":\n" + File.ReadAllText(path)) - : new[] { "The run did not start." }); + string diagnostics = string.Join( + "\n", + Directory.Exists(runDirectory) + ? Directory.EnumerateFiles(runDirectory, "*.log") + .Select(path => Path.GetFileName(path) + ":\n" + File.ReadAllText(path)) + : new[] { "The run did not start." } + ); string results = Path.Combine(runDirectory, "results.json"); if (File.Exists(results)) + { diagnostics += "\nResults:\n" + File.ReadAllText(results); - throw new InvalidOperationException("Union compilation failed for value " + value + ":\n" - + diagnostics, failure); + } + throw new InvalidOperationException( + "Union compilation failed for value " + value + ":\n" + + diagnostics, + failure + ); } if (variant && value >= 3) { - using JsonDocument resolved = JsonDocument.Parse(File.ReadAllText(repository.PathOf(output + "/managed-resolved-sdk-graph.json"))); - JsonElement owner = resolved.RootElement.EnumerateArray().Single(snapshot => snapshot.GetProperty("Path").GetString()! + using JsonDocument resolved = JsonDocument.Parse( + File.ReadAllText(repository.PathOf(output + "/managed-resolved-sdk-graph.json")) + ); + JsonElement owner = resolved.RootElement.EnumerateArray().Single(snapshot => snapshot.GetProperty("Path") + .GetString()! .EndsWith("Inno.Input.CompilationFixture.csproj", StringComparison.Ordinal)); - Assert.Contains(owner.GetProperty("Variants").EnumerateArray(), instance => - instance.GetProperty("Properties").GetProperty("TargetPath").GetString() != owner.GetProperty("Properties").GetProperty("TargetPath").GetString()); + Assert.Contains(owner.GetProperty("Variants").EnumerateArray(), instance => ( + instance + .GetProperty("Properties") + .GetProperty("TargetPath") + .GetString() != owner.GetProperty("Properties").GetProperty("TargetPath").GetString() + )); } if (value == 3) { @@ -193,18 +312,29 @@ await repository.SdkAsync("restore", C_FIXTURE + "/Inno.Input.CompilationFixture Assert.Equal(dependencyBytes, File.ReadAllBytes(dependencyOutput)); if (!variant) { - Assert.True(outputTimestamp == File.GetLastWriteTimeUtc(dependencyOutput), - "An unchanged dependency was rebuilt. Clean log:\n" + File.ReadAllText(repository.PathOf(output + "/managed-clean.log"))); + Assert.True( + outputTimestamp == File.GetLastWriteTimeUtc(dependencyOutput), + "An unchanged dependency was rebuilt. Clean log:\n" + + File.ReadAllText(repository.PathOf(output + "/managed-clean.log")) + ); Assert.Equal(dependencyBuilds, File.ReadAllLines(dependencyBuildLog).Length); } Assert.Equal(0, await repository.EvidenceAsync(repository.PathOf(output + "/results.json"))); if (variant) { - using DocumentationSnapshot reader = await DocumentationStore.OpenAsync(documentation.cache, documentationSnapshot.snapshot); + using DocumentationSnapshot reader = await DocumentationStore.OpenAsync( + documentation.cache, + documentationSnapshot.snapshot + ); DocumentationCatalogReport catalog = await reader.ExportCatalogAsync(); string reference = catalog.references.Single(item => item.model == "source-clr").identity; - File.WriteAllText(Path.Combine(documentation.cache, "references", reference, "reference.json"), "damaged immutable source facts"); - InvalidDataException failure = await Assert.ThrowsAsync(() => repository.EvidenceAsync(repository.PathOf(output + "/results.json"))); + File.WriteAllText( + Path.Combine(documentation.cache, "references", reference, "reference.json"), + "damaged immutable source facts" + ); + InvalidDataException failure = await Assert.ThrowsAsync( + () => repository.EvidenceAsync(repository.PathOf(output + "/results.json")) + ); Assert.Contains("integrity mismatch", failure.Message); } } @@ -223,14 +353,18 @@ public async Task ChangedCompilationInputsCannotPublishReusableBuildIdentity() const string C_RULES = "tests/ci/Test-AgentRules.ps1"; string gate = repository.PathOf("artifacts/change-compilation-input"); string source = repository.PathOf(C_PROBE); - repository.Write(C_RULES, File.ReadAllText(repository.PathOf(C_RULES)) + "\n" + repository.Write( + C_RULES, + File.ReadAllText(repository.PathOf(C_RULES)) + "\n" + "$gate = '" + gate.Replace("'", "''", StringComparison.Ordinal) + "'\n" + "if (Test-Path -LiteralPath $gate) {\n" + " $source = '" + source.Replace("'", "''", StringComparison.Ordinal) + "'\n" + " [IO.File]::WriteAllText($source, [IO.File]::ReadAllText($source).Replace('Assert.Equal(2, CompilationDependencyProbe.value)', 'Assert.Equal(3, CompilationDependencyProbe.value)'))\n" - + " Remove-Item -LiteralPath $gate\n}\n"); + + " Remove-Item -LiteralPath $gate\n}\n" + ); repository.Write(C_DEPENDENCY, """ namespace Inno.Core.IO; + /// /// Supplies an observable compiled dependency value for the validation fixture. /// @@ -241,18 +375,22 @@ public static class CompilationDependencyProbe /// public static int value => 2; } + """); repository.Git("add", C_RULES, C_DEPENDENCY); repository.Git("commit", "-m", "Declare a coordinated compilation input mutation"); repository.Write(C_PROBE, """ using Xunit; using Inno.Core.IO; + namespace Inno.Input.Tests; + public sealed class CompilationInputProbe { [Fact] - public void CompiledInputMatchesItsDeclaredSource() { Assert.Equal(2, CompilationDependencyProbe.value); } + public void CompiledInputMatchesItsDeclaredSource() => Assert.Equal(2, CompilationDependencyProbe.value); } + """); Assert.Equal(0, await repository.RunCurrentAsync(cancellation.Token, "artifacts/warmup")); repository.Write(C_PROBE, File.ReadAllText(source) + "\n// Change this owner's compilation input.\n"); @@ -263,22 +401,39 @@ public sealed class CompilationInputProbe using (JsonDocument failed = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/run/results.json")))) { JsonElement[] results = failed.RootElement.GetProperty("results").EnumerateArray().ToArray(); - Assert.Contains(failed.RootElement.GetProperty("failures").EnumerateArray(), fault => fault.GetProperty("stage").GetString() == "input-stability"); - Assert.Contains(results, result => result.GetProperty("id").GetString() == "test:tests/input/Inno.Input.Tests/Inno.Input.Tests.csproj" + Assert.Contains( + failed.RootElement.GetProperty("failures").EnumerateArray(), + fault => fault.GetProperty("stage").GetString() == "input-stability" + ); + Assert.Contains(results, result => ( + result + .GetProperty("id") + .GetString() == "test:tests/input/Inno.Input.Tests/Inno.Input.Tests.csproj" && result.GetProperty("status").GetString() == "Failed" - && result.GetProperty("detail").GetString()!.Contains("CompiledInputMatchesItsDeclaredSource", StringComparison.Ordinal)); + && result.GetProperty("detail").GetString()!.Contains("CompiledInputMatchesItsDeclaredSource", StringComparison.Ordinal) + )); } File.WriteAllBytes(source, original); File.SetLastWriteTimeUtc(source, timestamp); Assert.Equal(0, await repository.RunCurrentAsync(cancellation.Token, "artifacts/repaired")); - Assert.Equal(0, await repository.EvidenceAsync(repository.PathOf("artifacts/repaired/results.json"), "artifacts/repaired/plan.json")); + Assert.Equal( + 0, + await repository.EvidenceAsync(repository.PathOf("artifacts/repaired/results.json"), "artifacts/repaired/plan.json") + ); repository.Write(C_PROBE, File.ReadAllText(source) + "\n// Recompile only this owner's changed source.\n"); string dependencyOutput; using (JsonDocument plan = await repository.PlanAsync()) - dependencyOutput = plan.RootElement.GetProperty("contexts").GetProperty("managed").GetProperty("sdkGraph").EnumerateArray() + { + dependencyOutput = plan.RootElement.GetProperty("contexts") + .GetProperty("managed") + .GetProperty("sdkGraph") + .EnumerateArray() .Single(snapshot => snapshot.GetProperty("Path").GetString()!.EndsWith("Inno.Core.IO.csproj", StringComparison.Ordinal)) - .GetProperty("Properties").GetProperty("TargetPath").GetString()!; + .GetProperty("Properties") + .GetProperty("TargetPath") + .GetString()!; + } dependencyOutput = repository.BindWorkspace(dependencyOutput); DateTime outputTimestamp = File.GetLastWriteTimeUtc(dependencyOutput); byte[] dependencyBytes = File.ReadAllBytes(dependencyOutput); @@ -294,13 +449,16 @@ public sealed class CompilationInputProbe repository.Git("add", "--renormalize", "--", C_DEPENDENCY); repository.Git("commit", "-m", "Change a previously compiled dependency without changing its timestamp"); using (JsonDocument plan = await repository.PlanAsync()) + { Assert.Single(plan.RootElement.GetProperty("owners").EnumerateArray()); + } await Assert.ThrowsAsync(() => repository.RunAsync(cancellation.Token, "artifacts/dependency-changed")); using JsonDocument changed = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/dependency-changed/results.json"))); - Assert.Contains(changed.RootElement.GetProperty("results").EnumerateArray(), result => + Assert.Contains(changed.RootElement.GetProperty("results").EnumerateArray(), result => ( result.GetProperty("id").GetString() == "test:tests/input/Inno.Input.Tests/Inno.Input.Tests.csproj" && result.GetProperty("status").GetString() == "Failed" - && result.GetProperty("detail").GetString()!.Contains("CompiledInputMatchesItsDeclaredSource", StringComparison.Ordinal)); + && result.GetProperty("detail").GetString()!.Contains("CompiledInputMatchesItsDeclaredSource", StringComparison.Ordinal) + )); } [Fact] @@ -310,14 +468,25 @@ public async Task FailedClosingReadCannotCertifyOtherwisePassingIntermediateResu using var external = new ValidationRepository(); string dependency = external.PathOf("Shared.props"); const string C_PROJECT = "tests/input/Inno.Input.Tests/Inno.Input.Tests.csproj"; - repository.Write(C_PROJECT, File.ReadAllText(repository.PathOf(C_PROJECT)).Replace("", - "", StringComparison.Ordinal)); + repository.Write( + C_PROJECT, + File.ReadAllText(repository.PathOf(C_PROJECT)).Replace( + "", + "", + StringComparison.Ordinal + ) + ); string signal = repository.PathOf("artifacts/check-ready"); string release = repository.PathOf("artifacts/check-release"); const string C_RULES = "tests/ci/Test-AgentRules.ps1"; - repository.Write(C_RULES, File.ReadAllText(repository.PathOf(C_RULES)) + "\n" + repository.Write( + C_RULES, + File.ReadAllText(repository.PathOf(C_RULES)) + "\n" + "[IO.File]::WriteAllText('" + signal.Replace("'", "''", StringComparison.Ordinal) + "', 'ready')\n" - + "while (-not (Test-Path -LiteralPath '" + release.Replace("'", "''", StringComparison.Ordinal) + "')) { Start-Sleep -Milliseconds 10 }\n"); + + "while (-not (Test-Path -LiteralPath '" + + release.Replace("'", "''", StringComparison.Ordinal) + + "')) { Start-Sleep -Milliseconds 10 }\n" + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare a coordinated closing-read failure fixture"); repository.Write("README.md", File.ReadAllText(repository.PathOf("README.md")) + "\nClosing evidence acceptance.\n"); @@ -330,7 +499,9 @@ public async Task FailedClosingReadCannotCertifyOtherwisePassingIntermediateResu while (!File.Exists(signal)) { if (execution.IsCompleted) + { Assert.Fail("Validation ended before the real instruction check reached its coordination point."); + } await Task.Delay(20, cancellation.Token); } using (var reader = new FileStream(dependency, FileMode.Open, FileAccess.Read, FileShare.None)) @@ -343,7 +514,10 @@ public async Task FailedClosingReadCannotCertifyOtherwisePassingIntermediateResu } string evidence = repository.PathOf("artifacts/run/results.json"); using JsonDocument results = JsonDocument.Parse(File.ReadAllText(evidence)); - Assert.Equal(plan.RootElement.GetProperty("checks").GetArrayLength(), results.RootElement.GetProperty("results").GetArrayLength()); + Assert.Equal( + plan.RootElement.GetProperty("checks").GetArrayLength(), + results.RootElement.GetProperty("results").GetArrayLength() + ); Assert.All(results.RootElement.GetProperty("results").EnumerateArray(), result => Assert.Contains(result.GetProperty("status").GetString(), new[] { "Passed", "Reused", "NotApplicable" })); Assert.False(results.RootElement.GetProperty("completed").GetBoolean()); @@ -357,7 +531,10 @@ public async Task FailedClosingReadCannotCertifyOtherwisePassingIntermediateResu { cancellation.Cancel(); File.WriteAllText(release, "drain"); - try { await execution; } + try + { + await execution; + } catch (Exception) { /* The assertion above owns the original failure; drain before retiring the fixture. */ } } } diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationHostContractsTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationHostContractsTests.cs index 0d9db8345..46dbd27c3 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationHostContractsTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationHostContractsTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Linq; using System.Text.Json; using System.Threading.Tasks; -using Inno.Testing.Source; using Xunit; using Xunit.Abstractions; +using Inno.Testing.Source; +using Inno.Testing.Validation; namespace Inno.Tooling.Validation.Tests; @@ -26,15 +26,19 @@ public async Task ActualTrxDistinguishesCompiledHostExclusionsFromMissingRequire using System; using System.Runtime.Versioning; using Xunit; + namespace Inno.Input.Tests; + [SupportedOSPlatform("{{otherHost}}")] public sealed class HostContractProbe { [Fact(Skip = "The declared host is unavailable in this matrix cell.")] - public void UnsupportedHost() { Assert.Fail("This case must not execute on another host."); } + public void UnsupportedHost() => Assert.Fail("This case must not execute on another host."); + [Fact] [SupportedOSPlatform("{{currentHost}}")] - public void RequiredHost() { Assert.Equal(2, 1 + 1); } + public void RequiredHost() => Assert.Equal(2, 1 + 1); + [Fact] public void ExistingGuard() { @@ -42,11 +46,14 @@ public void ExistingGuard() Assert.True(true); } } + """; const string C_PROBE = "tests/input/Inno.Input.Tests/HostContractProbe.cs"; repository.Write(C_PROBE, source); using (JsonDocument plan = await repository.PlanAsync()) + { Assert.False(plan.RootElement.GetProperty("contexts").TryGetProperty("native", out _)); + } try { Assert.Equal(0, await repository.RunAsync()); @@ -54,29 +61,48 @@ public void ExistingGuard() catch { foreach (string file in Directory.EnumerateFiles(repository.PathOf("artifacts/run"), "*", SearchOption.TopDirectoryOnly) - .Where(static path => path.EndsWith(".log", StringComparison.Ordinal) || Path.GetFileName(path) == "results.json")) + .Where(static path => path.EndsWith(".log", StringComparison.Ordinal) || Path.GetFileName(path) == "results.json") + ) { m_output.WriteLine(Path.GetFileName(file) + "\n" + File.ReadAllText(file)); + } throw; } - using (JsonDocument receipt = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/run/managed-trx/host-contracts.json")))) - { + using (JsonDocument receipt = JsonDocument.Parse( + File.ReadAllText(repository.PathOf("artifacts/run/managed-trx/host-contracts.json")) + )) { string[] excluded = receipt.RootElement.GetProperty("tests/input/Inno.Input.Tests/Inno.Input.Tests.csproj") - .EnumerateArray().Select(static item => item.GetString()!).ToArray(); + .EnumerateArray() + .Select(static item => item.GetString()!) + .ToArray(); Assert.Equal(2, excluded.Length); Assert.Contains(excluded, static item => item.Contains("UnsupportedHost", StringComparison.Ordinal)); Assert.Contains(excluded, static item => item.Contains("ExistingGuard", StringComparison.Ordinal)); Assert.DoesNotContain(excluded, static item => item.Contains("RequiredHost", StringComparison.Ordinal)); } - repository.Write(C_PROBE, source.Replace("public void UnsupportedHost()", - "[SupportedOSPlatform(\"" + currentHost + "\")]\n public void UnsupportedHost()", StringComparison.Ordinal)); + repository.Write( + C_PROBE, + source.Replace( + "public void UnsupportedHost()", + "[SupportedOSPlatform(\"" + currentHost + "\")]\n public void UnsupportedHost()", + StringComparison.Ordinal + ) + ); using (await repository.PlanAsync()) { } await Assert.ThrowsAsync(() => repository.RunAsync(output: "artifacts/required-host")); - Assert.Contains("Required test was skipped", File.ReadAllText(repository.PathOf("artifacts/required-host/results.json")), StringComparison.Ordinal); + Assert.Contains( + "Required test was skipped", + File.ReadAllText(repository.PathOf("artifacts/required-host/results.json")), + StringComparison.Ordinal + ); - repository.Write(C_PROBE, source.Replace("[SupportedOSPlatform(\"" + otherHost + "\")]", string.Empty, StringComparison.Ordinal)); + repository.Write(C_PROBE, source.Replace("[SupportedOSPlatform(\"" + otherHost + "\")]\n", string.Empty, StringComparison.Ordinal)); using (await repository.PlanAsync()) { } await Assert.ThrowsAsync(() => repository.RunAsync(output: "artifacts/undeclared-skip")); - Assert.Contains("Required test was skipped", File.ReadAllText(repository.PathOf("artifacts/undeclared-skip/results.json")), StringComparison.Ordinal); + Assert.Contains( + "Required test was skipped", + File.ReadAllText(repository.PathOf("artifacts/undeclared-skip/results.json")), + StringComparison.Ordinal + ); } } diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationTestOwnershipTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationTestOwnershipTests.cs index 35377ba86..e9e868f96 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationTestOwnershipTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationTestOwnershipTests.cs @@ -1,11 +1,11 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Linq; using System.Text.Json; using System.Threading.Tasks; -using Inno.Testing.Source; using Xunit; +using Inno.Testing.Source; +using Inno.Testing.Validation; namespace Inno.Tooling.Validation.Integration.Tests; @@ -20,29 +20,39 @@ public async Task AFailedUnionRetainsSuccessfulOwnersAndRejectsMissingIsolatedRe const string C_PROBE = "tests/input/Inno.Input.Tests/UnionFailureProbe.cs"; repository.Write(C_PROBE, """ using Xunit; + namespace Inno.Input.Tests; + public sealed class UnionFailureProbe { [Fact] - public void SharedFailure() { Assert.Fail("Intentional owner failure"); } + public void SharedFailure() => Assert.Fail("Intentional owner failure"); + [Fact, Trait("ProcessIsolation", "Required")] - public void IsolatedFailure() { Assert.Fail("Intentional isolated owner failure"); } + public void IsolatedFailure() => Assert.Fail("Intentional isolated owner failure"); } + """); repository.Write("tests/ui/Inno.UI.Tests/UnionSuccessProbe.cs", """ using Xunit; + namespace Inno.UI.Tests; + public sealed class UnionSuccessProbe { [Fact, Trait("ProcessIsolation", "Required")] - public void IsolatedSuccess() { Assert.Equal(2, 1 + 1); } + public void IsolatedSuccess() => Assert.Equal(2, 1 + 1); } + """); string failedSource = File.ReadAllText(repository.PathOf(C_PROBE)); - string passingSource = failedSource.Replace("Assert.Fail(\"Intentional owner failure\")", "Assert.Equal(2, 1 + 1)", StringComparison.Ordinal) + string passingSource = failedSource + .Replace("Assert.Fail(\"Intentional owner failure\")", "Assert.Equal(2, 1 + 1)", StringComparison.Ordinal) .Replace("Assert.Fail(\"Intentional isolated owner failure\")", "Assert.Equal(2, 1 + 1)", StringComparison.Ordinal); using (JsonDocument plan = await repository.PlanAsync()) + { Assert.False(plan.RootElement.GetProperty("contexts").TryGetProperty("native", out _)); + } await Assert.ThrowsAsync(() => repository.RunAsync()); JsonElement originalUi; using (JsonDocument results = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/run/results.json")))) @@ -64,21 +74,35 @@ public sealed class UnionSuccessProbe using (await repository.PlanAsync()) { } Assert.Equal(0, await repository.RunAsync(output: "artifacts/repaired", evidence: "artifacts/run/results.json")); using JsonDocument repaired = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/repaired/results.json"))); - JsonElement ui = repaired.RootElement.GetProperty("results").EnumerateArray().Single(check => check.GetProperty("id").GetString() == "test:" + C_UI); + JsonElement ui = repaired.RootElement + .GetProperty("results") + .EnumerateArray() + .Single(check => check.GetProperty("id").GetString() == "test:" + C_UI); string expected = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CI")) ? "Reused" : "Passed"; - Assert.True(ui.GetProperty("status").GetString() == expected, - "Expected " + expected + "; original owner evidence: " + originalUi.GetRawText() + "; repaired: " + ui.GetRawText()); + Assert.True( + ui.GetProperty("status").GetString() == expected, + "Expected " + expected + "; original owner evidence: " + originalUi.GetRawText() + "; repaired: " + ui.GetRawText() + ); const string C_EXECUTOR = "tests/Invoke-IsolatedTests.ps1"; string executor = File.ReadAllText(repository.PathOf(C_EXECUTOR)); - repository.Write(C_EXECUTOR, executor.Replace("Add-CheckResult 'Isolated' $name", - "if ($project.BaseName -eq 'Inno.UI.Tests') { continue }; Add-CheckResult 'Isolated' $name", StringComparison.Ordinal)); + repository.Write( + C_EXECUTOR, + executor.Replace( + "Add-CheckResult 'Isolated' $name", + "if ($project.BaseName -eq 'Inno.UI.Tests') { continue }; Add-CheckResult 'Isolated' $name", + StringComparison.Ordinal + ) + ); repository.Git("add", C_EXECUTOR); repository.Git("commit", "-m", "Model an executor losing an isolated receipt"); using (await repository.PlanAsync()) { } await Assert.ThrowsAsync(() => repository.RunAsync(output: "artifacts/missing-isolation")); using JsonDocument incomplete = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/missing-isolation/results.json"))); - JsonElement missing = incomplete.RootElement.GetProperty("results").EnumerateArray().Single(check => check.GetProperty("id").GetString() == "test:" + C_UI); + JsonElement missing = incomplete.RootElement + .GetProperty("results") + .EnumerateArray() + .Single(check => check.GetProperty("id").GetString() == "test:" + C_UI); Assert.Equal("Failed", missing.GetProperty("status").GetString()); Assert.Contains("Required isolated execution is missing", missing.GetProperty("detail").GetString()); @@ -89,8 +113,10 @@ public sealed class UnionSuccessProbe var failure = await Assert.ThrowsAsync(() => repository.RunAsync(output: "artifacts/process-failure")); Assert.Contains("exited with 17", failure.Message); using JsonDocument process = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/process-failure/results.json"))); - JsonElement[] tests = process.RootElement.GetProperty("results").EnumerateArray() - .Where(check => check.GetProperty("id").GetString()!.StartsWith("test:", StringComparison.Ordinal)).ToArray(); + JsonElement[] tests = process.RootElement.GetProperty("results") + .EnumerateArray() + .Where(check => check.GetProperty("id").GetString()!.StartsWith("test:", StringComparison.Ordinal)) + .ToArray(); foreach (JsonElement check in tests) { string? id = check.GetProperty("id").GetString(); @@ -99,6 +125,9 @@ public sealed class UnionSuccessProbe } Assert.Contains(tests, check => check.GetProperty("id").GetString() == "test:" + C_INPUT); Assert.Contains(tests, check => check.GetProperty("id").GetString() == "test:" + C_UI); - Assert.Equal("test-execution", Assert.Single(process.RootElement.GetProperty("failures").EnumerateArray()).GetProperty("stage").GetString()); + Assert.Equal( + "test-execution", + Assert.Single(process.RootElement.GetProperty("failures").EnumerateArray()).GetProperty("stage").GetString() + ); } } diff --git a/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs b/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs index 43c7479bd..75e7d2165 100644 --- a/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs +++ b/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs @@ -17,6 +17,7 @@ namespace Inno.Tooling.Architecture; public static partial class ArchitectureValidator { private static readonly string[] S_PRODUCTION_ROOTS = ["entry", "src", "backends", "platforms", "build", "tools"]; + private static readonly HashSet S_IGNORED_DIRECTORIES = new(StringComparer.OrdinalIgnoreCase) { "bin", @@ -24,6 +25,7 @@ public static partial class ArchitectureValidator "dependencies", "Generated" }; + private static readonly HashSet S_FORBIDDEN_DIRECTORY_NAMES = new(StringComparer.OrdinalIgnoreCase) { "Legacy", @@ -79,23 +81,41 @@ public static int Execute( { string argument = arguments[index]; if (argument == "--expand-xml" && !expandXml) + { expandXml = true; + } else if (argument == "--agent-documents-only" && !agentDocumentsOnly) + { agentDocumentsOnly = true; + } else if (argument == "--source-only" && !sourceOnly) + { sourceOnly = true; + } else if (argument == "--metadata-only" && !metadataOnly) + { metadataOnly = true; + } else if (argument == "--api-project" && index + 1 < arguments.Length) + { apiProjects.Add(arguments[++index].Replace('\\', '/')); + } else if (argument == "--sdk-snapshot" && sdkSnapshot is null && index + 1 < arguments.Length) + { sdkSnapshot = File.ReadAllText(arguments[++index]); + } else if (argument == "--dotnet" && dotnetHost is null && index + 1 < arguments.Length) + { dotnetHost = arguments[++index]; + } else if (argument == "--project-graph" && projectGraphPath is null && index + 1 < arguments.Length) + { projectGraphPath = arguments[++index]; + } else if (argument == "--artifacts-path" && artifactsPath is null && index + 1 < arguments.Length) + { artifactsPath = Path.GetFullPath(arguments[++index]); + } else if (argument == "--configuration" && !selectedConfiguration && index + 1 < arguments.Length) { configuration = arguments[++index] switch @@ -108,25 +128,35 @@ public static int Execute( selectedConfiguration = true; } else if (!argument.StartsWith("--", StringComparison.Ordinal) && paths.Count == 0) + { paths.Add(argument); + } else + { throw new ArgumentException( "Usage: verify [engine-root] [--configuration Debug|SourceDebug|Release] [--expand-xml] [--source-only|--metadata-only|--agent-documents-only] [--api-project project.csproj] [--dotnet SDK] [--artifacts-path directory] [--project-graph output.json] [--sdk-snapshot input.json]", nameof(arguments) ); + } } if ((projectGraphPath is not null || artifactsPath is not null) && dotnetHost is null) + { throw new ArgumentException("Evaluated project graph output requires an explicitly selected --dotnet SDK.", nameof(arguments)); + } string repositoryRoot = ResolveRepositoryRoot(paths); foreach (string project in apiProjects) { string selected = Path.GetFullPath(project, repositoryRoot); if (!selected.StartsWith(repositoryRoot + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) - || !selected.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) || !File.Exists(selected)) + || !selected.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) || !File.Exists(selected) + ) { throw new ArgumentException($"The selected API owner is not a repository project: {project}", nameof(arguments)); + } } if (sourceOnly && (metadataOnly || apiProjects.Count != 0)) + { throw new ArgumentException("Source-only validation cannot claim compiled API evidence.", nameof(arguments)); + } if (expandXml) { int changedFileCount = ExpandXmlDocumentation(repositoryRoot); @@ -137,31 +167,53 @@ public static int Execute( if (agentDocumentsOnly) { if (sourceOnly || metadataOnly || apiProjects.Count != 0 || dotnetHost is not null) + { throw new ArgumentException("Agent document checks do not claim product or SDK validation."); + } AgentDocumentValidator.Validate(repositoryRoot, failures); foreach (string failure in failures) + { Console.Error.WriteLine(failure); + } return failures.Count == 0 ? 0 : 1; } - DocumentationProjectReferences? evaluatedReferences = dotnetHost is null ? null - : new DocumentationProjectReferences(repositoryRoot, configuration, dotnetHost, target: null, artifactsPath, + DocumentationProjectReferences? evaluatedReferences = dotnetHost is null + ? null + : new DocumentationProjectReferences( + repositoryRoot, + configuration, + dotnetHost, + target: null, + artifactsPath, apiProjects.Count == 0 ? null : apiProjects.Select(project => Path.GetFullPath(project, repositoryRoot)) - .ToHashSet(StringComparer.OrdinalIgnoreCase), sdkSnapshot); - var documentationModels = new DocumentationSourceModels(repositoryRoot, configuration, - evaluatedReferences, cancellationToken, failures); + .ToHashSet(StringComparer.OrdinalIgnoreCase), + sdkSnapshot + ); + var documentationModels = new DocumentationSourceModels( + repositoryRoot, + configuration, + evaluatedReferences, + cancellationToken, + failures + ); var sourceTrees = new Dictionary(StringComparer.Ordinal); if (!metadataOnly) + { foreach (string rootName in S_PRODUCTION_ROOTS) { string root = Path.Combine(repositoryRoot, rootName); if (!Directory.Exists(root)) + { continue; + } ValidateDirectories(repositoryRoot, root, failures); ValidateSources(repositoryRoot, root, failures, documentationModels, sourceTrees, sourceOnly); } + } if (!metadataOnly) { + ValidateTestStyle(repositoryRoot, failures); UsingPolicyValidator.Validate(repositoryRoot, failures, sourceTrees); ValidateProjectReferences(repositoryRoot, failures); ValidateProductionSolutionFolders(repositoryRoot, failures); @@ -170,42 +222,79 @@ public static int Execute( } IReadOnlyDictionary? outputs = null; if (dotnetHost is not null) - outputs = MSBuildProjectGraphValidator.ValidateAsync(repositoryRoot, configuration, dotnetHost, artifactsPath, - projectGraphPath, failures, cancellationToken, sdkSnapshot, apiProjects.Count == 0 ? null : apiProjects).GetAwaiter().GetResult(); + { + outputs = MSBuildProjectGraphValidator.ValidateAsync( + repositoryRoot, + configuration, + dotnetHost, + artifactsPath, + projectGraphPath, + failures, + cancellationToken, + sdkSnapshot, + apiProjects.Count == 0 ? null : apiProjects + ).GetAwaiter().GetResult(); + } if (!sourceOnly) - PublicApiBoundaryValidator.Validate(repositoryRoot, configuration, failures, outputs, - apiProjects.Count == 0 ? null : apiProjects, evaluatedReferences, cancellationToken); + { + PublicApiBoundaryValidator.Validate( + repositoryRoot, + configuration, + failures, + outputs, + apiProjects.Count == 0 ? null : apiProjects, + evaluatedReferences, + cancellationToken + ); + } if (metadataOnly) { IEnumerable projects = apiProjects.Count == 0 ? S_PRODUCTION_ROOTS.SelectMany(root => RepositorySourceInventory.Files(Path.Combine(repositoryRoot, root), "*.csproj")) : apiProjects.Select(project => Path.GetFullPath(project, repositoryRoot)); - foreach (string project in projects.Where(project => !Relative(repositoryRoot, project).StartsWith("tests/", StringComparison.Ordinal))) - ValidateSources(repositoryRoot, Path.GetDirectoryName(project)!, failures, documentationModels, sourceTrees, semanticOnly: true); + foreach (string project in projects.Where( + project => !Relative(repositoryRoot, project).StartsWith("tests/", StringComparison.Ordinal) + )) { + ValidateSources( + repositoryRoot, + Path.GetDirectoryName(project)!, + failures, + documentationModels, + sourceTrees, + semanticOnly: true + ); + } } if (failures.Count == 0) { - Console.WriteLine(sourceOnly ? "InnoEngine source architecture validation passed; compiled API evidence is separate." - : metadataOnly ? "InnoEngine selected compiled API validation passed." : "InnoEngine architecture validation passed."); + Console.WriteLine( + sourceOnly + ? "InnoEngine source architecture validation passed; compiled API evidence is separate." + : metadataOnly ? "InnoEngine selected compiled API validation passed." : "InnoEngine architecture validation passed." + ); return 0; } Console.Error.WriteLine($"InnoEngine architecture validation failed with {failures.Count} violation(s):"); foreach (string failure in failures.Order(StringComparer.Ordinal)) + { Console.Error.WriteLine(" " + failure); + } return 1; } private static string ResolveRepositoryRoot(IReadOnlyList arguments) { string start = arguments.Count == 0 - ? Directory.GetCurrentDirectory() - : Path.GetFullPath(arguments[0]); + ? Directory.GetCurrentDirectory() + : Path.GetFullPath(arguments[0]); DirectoryInfo? current = new(start); while (current is not null) { if (File.Exists(Path.Combine(current.FullName, "InnoEngine.sln"))) + { return current.FullName; + } current = current.Parent; } throw new DirectoryNotFoundException("Could not locate the InnoEngine repository root."); @@ -226,6 +315,17 @@ ICollection failures } } + // Test sources follow the style rulebook; the production contracts below do not apply to them. + private static void ValidateTestStyle( + string repositoryRoot, + ICollection failures + ) { + foreach (string path in EnumerateFiles(Path.Combine(repositoryRoot, "tests"), "*.cs")) + { + CSharpStyleValidator.ValidateStyle(Relative(repositoryRoot, path), File.ReadAllText(path), failures); + } + } + private static void ValidateSources( string repositoryRoot, string root, @@ -239,7 +339,9 @@ private static void ValidateSources( { string source = File.ReadAllText(path); if (IsGenerated(source)) + { continue; + } string relative = Relative(repositoryRoot, path); if (!sourceTrees.TryGetValue(path, out SyntaxTree? syntax)) { @@ -247,44 +349,84 @@ private static void ValidateSources( sourceTrees.Add(path, syntax); } if (!semanticOnly) - CSharpStyleValidator.Validate(relative, syntax, failures); + { + CSharpStyleValidator.Validate(relative, source, syntax, failures); + } if (relative.StartsWith("tools/Inno.Tooling.Architecture/", StringComparison.Ordinal) - || RepositorySourceInventory.IsTestPath(relative)) + || RepositorySourceInventory.IsTestPath(relative) + ) { continue; - PublicApiDocumentationValidator.Validate(relative, syntax, failures, + } + PublicApiDocumentationValidator.Validate( + relative, + syntax, + failures, !sourceOnly && source.Contains("()) - { + .DescendantNodes() + .OfType() + ) { if (model.GetDeclaredSymbol(field) is IFieldSymbol symbol && symbol.Type is INamedTypeSymbol type && (type.ToDisplayString() == "Inno.Build.IGameContentCompiler" - || type.AllInterfaces.Any(static contract => contract.ToDisplayString() == "Inno.Build.IGameContentCompiler"))) + || type.AllInterfaces.Any( + static contract => contract.ToDisplayString() == "Inno.Build.IGameContentCompiler" + )) + ) { failures.Add($"{relative}: platform packaging cannot own a content compiler; bind it in the distribution."); + } } } } if (semanticOnly) + { continue; + } GenerationCleanupValidator.Validate(relative, syntax, failures); - AddSourceFailure(source.Contains("InternalsVisibleTo", StringComparison.Ordinal), relative, - "friend assemblies are forbidden", failures); - AddSourceFailure(source.Contains("[Obsolete", StringComparison.Ordinal), relative, - "obsolete compatibility APIs are forbidden", failures); - AddSourceFailure(source.Contains("TypeForwardedTo", StringComparison.Ordinal), relative, - "type forwarding is forbidden", failures); - AddSourceFailure(CompatibilityFieldPattern().IsMatch(source), relative, - "schema compatibility fields are forbidden", failures); - AddSourceFailure(UninformativeXmlPattern().IsMatch(source), relative, - "public API XML contains an uninformative generated placeholder", failures); + AddSourceFailure( + source.Contains("InternalsVisibleTo", StringComparison.Ordinal), + relative, + "friend assemblies are forbidden", + failures + ); + AddSourceFailure( + source.Contains("[Obsolete", StringComparison.Ordinal), + relative, + "obsolete compatibility APIs are forbidden", + failures + ); + AddSourceFailure( + source.Contains("TypeForwardedTo", StringComparison.Ordinal), + relative, + "type forwarding is forbidden", + failures + ); + AddSourceFailure( + CompatibilityFieldPattern().IsMatch(source), + relative, + "schema compatibility fields are forbidden", + failures + ); + AddSourceFailure( + UninformativeXmlPattern().IsMatch(source), + relative, + "public API XML contains an uninformative generated placeholder", + failures + ); int lineNumber = 0; using var reader = new StringReader(source); @@ -307,12 +449,16 @@ private static int ExpandXmlDocumentation(string repositoryRoot) { string root = Path.Combine(repositoryRoot, rootName); if (!Directory.Exists(root)) + { continue; + } foreach (string path in EnumerateFiles(root, "*.cs")) { string source = File.ReadAllText(path); if (IsGenerated(source)) + { continue; + } string newline = source.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n"; string expanded = ExpandableXmlPattern().Replace(source, match => { @@ -324,10 +470,13 @@ private static int ExpandXmlDocumentation(string repositoryRoot) newline, $"{indentation}/// <{element}{attributes}>", $"{indentation}/// {content}", - $"{indentation}/// "); + $"{indentation}/// " + ); }); if (string.Equals(source, expanded, StringComparison.Ordinal)) + { continue; + } File.WriteAllText(path, expanded); changedFileCount++; } @@ -342,67 +491,71 @@ ICollection failures foreach (string projectPath in EnumerateFiles(repositoryRoot, "*.csproj")) { if (IsIgnoredPath(projectPath)) + { continue; + } string projectRelative = Relative(repositoryRoot, projectPath); XDocument project = XDocument.Load(projectPath); foreach (XElement reference in project.Descendants("ProjectReference")) { string? include = reference.Attribute("Include")?.Value; if (string.IsNullOrWhiteSpace(include)) + { continue; + } string target = Path.GetFullPath(include, Path.GetDirectoryName(projectPath)!); string targetRelative = Relative(repositoryRoot, target); - if (projectRelative.StartsWith("src/foundation/", StringComparison.Ordinal) && - !targetRelative.StartsWith("src/foundation/", StringComparison.Ordinal)) - { + if (projectRelative.StartsWith("src/foundation/", StringComparison.Ordinal) + && !targetRelative.StartsWith("src/foundation/", StringComparison.Ordinal) + ) { failures.Add($"{projectRelative}: Foundation cannot reference upper-layer project {targetRelative}."); } - if (projectRelative.StartsWith("build/", StringComparison.Ordinal) && - !projectRelative.StartsWith("build/cli/", StringComparison.Ordinal) && - targetRelative.StartsWith("src/composition/editor/", StringComparison.Ordinal)) - { + if (projectRelative.StartsWith("build/", StringComparison.Ordinal) + && !projectRelative.StartsWith("build/cli/", StringComparison.Ordinal) + && targetRelative.StartsWith("src/composition/editor/", StringComparison.Ordinal) + ) { failures.Add($"{projectRelative}: Build cannot reference Editor project {targetRelative}."); } - if (projectRelative.StartsWith("src/runtime/", StringComparison.Ordinal) && - (targetRelative.StartsWith("src/composition/", StringComparison.Ordinal) || - targetRelative.StartsWith("build/", StringComparison.Ordinal))) - { + if (projectRelative.StartsWith("src/runtime/", StringComparison.Ordinal) + && (targetRelative.StartsWith("src/composition/", StringComparison.Ordinal) + || targetRelative.StartsWith("build/", StringComparison.Ordinal)) + ) { failures.Add($"{projectRelative}: Runtime cannot reference {targetRelative}."); } - if (targetRelative.Contains("Inno.Native.Bgfx", StringComparison.Ordinal) && - !projectRelative.Contains("Inno.Adapter.Rendering.Bgfx", StringComparison.Ordinal) && - !projectRelative.Contains("Inno.Native.Bgfx", StringComparison.Ordinal) && - !projectRelative.StartsWith("backends/Bgfx/build/Inno.Build.Toolchains.Bgfx", StringComparison.Ordinal) && - !projectRelative.StartsWith("tests/", StringComparison.Ordinal)) - { + if (targetRelative.Contains("Inno.Native.Bgfx", StringComparison.Ordinal) + && !projectRelative.Contains("Inno.Adapter.Rendering.Bgfx", StringComparison.Ordinal) + && !projectRelative.Contains("Inno.Native.Bgfx", StringComparison.Ordinal) + && !projectRelative.StartsWith("backends/Bgfx/build/Inno.Build.Toolchains.Bgfx", StringComparison.Ordinal) + && !projectRelative.StartsWith("tests/", StringComparison.Ordinal) + ) { failures.Add($"{projectRelative}: BGFX native code is restricted to the BGFX adapter."); } - if (targetRelative.Contains("Inno.Native.Sdl3", StringComparison.Ordinal) && - !projectRelative.Contains("Inno.Adapter.Platform.Sdl3", StringComparison.Ordinal) && - !projectRelative.Contains("Inno.Adapter.Presentation.ImGui.Sdl3", StringComparison.Ordinal) && - !projectRelative.Contains("Inno.Native.Sdl3", StringComparison.Ordinal) && - !(projectRelative.StartsWith("platforms/", StringComparison.Ordinal) - && projectRelative.Contains("/integrations/Inno.Integration.", StringComparison.Ordinal) - && projectRelative.Contains(".Sdl3/", StringComparison.Ordinal)) && - !projectRelative.StartsWith("backends/Sdl3/build/Inno.Build.Toolchains.Sdl3", StringComparison.Ordinal) && - !projectRelative.StartsWith("tests/", StringComparison.Ordinal)) - { + if (targetRelative.Contains("Inno.Native.Sdl3", StringComparison.Ordinal) + && !projectRelative.Contains("Inno.Adapter.Platform.Sdl3", StringComparison.Ordinal) + && !projectRelative.Contains("Inno.Adapter.Presentation.ImGui.Sdl3", StringComparison.Ordinal) + && !projectRelative.Contains("Inno.Native.Sdl3", StringComparison.Ordinal) + && !(projectRelative.StartsWith("platforms/", StringComparison.Ordinal) + && projectRelative.Contains("/integrations/Inno.Integration.", StringComparison.Ordinal) + && projectRelative.Contains(".Sdl3/", StringComparison.Ordinal)) + && !projectRelative.StartsWith("backends/Sdl3/build/Inno.Build.Toolchains.Sdl3", StringComparison.Ordinal) + && !projectRelative.StartsWith("tests/", StringComparison.Ordinal) + ) { failures.Add($"{projectRelative}: SDL3 native code is restricted to the SDL3 platform adapter."); } - if (targetRelative.Contains("Inno.Native.MiniAudio", StringComparison.Ordinal) && - !projectRelative.Contains("Inno.Adapter.Audio.MiniAudio", StringComparison.Ordinal) && - !projectRelative.Contains("Inno.Native.MiniAudio", StringComparison.Ordinal) && - !projectRelative.StartsWith("backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio", StringComparison.Ordinal) && - !projectRelative.StartsWith("tests/", StringComparison.Ordinal)) - { + if (targetRelative.Contains("Inno.Native.MiniAudio", StringComparison.Ordinal) + && !projectRelative.Contains("Inno.Adapter.Audio.MiniAudio", StringComparison.Ordinal) + && !projectRelative.Contains("Inno.Native.MiniAudio", StringComparison.Ordinal) + && !projectRelative.StartsWith("backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio", StringComparison.Ordinal) + && !projectRelative.StartsWith("tests/", StringComparison.Ordinal) + ) { failures.Add($"{projectRelative}: miniaudio native code is restricted to the MiniAudio adapter."); } - if (targetRelative.Contains("Inno.Native.UI", StringComparison.Ordinal) && - !projectRelative.Contains("Inno.Adapter.UI.RmlUi", StringComparison.Ordinal) && - !projectRelative.Contains("Inno.Native.UI", StringComparison.Ordinal) && - !projectRelative.StartsWith("backends/RmlUi/build/Inno.Build.Toolchains.UI", StringComparison.Ordinal) && - !projectRelative.StartsWith("tests/", StringComparison.Ordinal)) - { + if (targetRelative.Contains("Inno.Native.UI", StringComparison.Ordinal) + && !projectRelative.Contains("Inno.Adapter.UI.RmlUi", StringComparison.Ordinal) + && !projectRelative.Contains("Inno.Native.UI", StringComparison.Ordinal) + && !projectRelative.StartsWith("backends/RmlUi/build/Inno.Build.Toolchains.UI", StringComparison.Ordinal) + && !projectRelative.StartsWith("tests/", StringComparison.Ordinal) + ) { failures.Add($"{projectRelative}: RmlUi native code is restricted to the RmlUi adapter."); } } @@ -428,8 +581,13 @@ ICollection failures string id = project.Groups["id"].Value; names[id] = project.Groups["name"].Value; paths[id] = project.Groups["path"].Value.Replace('\\', '/'); - if (string.Equals(project.Groups["type"].Value, "{2150E333-8FDC-42A3-9474-1A3956D46DE8}", StringComparison.OrdinalIgnoreCase)) + if (string.Equals( + project.Groups["type"].Value, + "{2150E333-8FDC-42A3-9474-1A3956D46DE8}", + StringComparison.OrdinalIgnoreCase + )) { solutionFolders.Add(id); + } continue; } @@ -444,15 +602,20 @@ ICollection failures continue; } if (!readingNestedProjects) + { continue; + } Match nesting = SolutionNestingPattern().Match(line); if (nesting.Success) + { parents[nesting.Groups[1].Value] = nesting.Groups[2].Value; + } } - string? testsRoot = solutionFolders.FirstOrDefault(id => - string.Equals(names.GetValueOrDefault(id), "tests", StringComparison.Ordinal) && !parents.ContainsKey(id)); + string? testsRoot = solutionFolders.FirstOrDefault(id => ( + string.Equals(names.GetValueOrDefault(id), "tests", StringComparison.Ordinal) && !parents.ContainsKey(id) + )); if (testsRoot is null) { failures.Add("InnoEngine.sln: missing root tests Solution Folder."); @@ -460,42 +623,50 @@ ICollection failures } var declaredTestProjects = paths - .Where(static pair => pair.Value.StartsWith("tests/", StringComparison.Ordinal) && - pair.Value.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)) + .Where(static pair => ( + pair.Value.StartsWith("tests/", StringComparison.Ordinal) + && pair.Value.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) + )) .ToDictionary(static pair => pair.Value, static pair => pair.Key, StringComparer.OrdinalIgnoreCase); string testsDirectory = Path.Combine(repositoryRoot, "tests"); foreach (string projectPath in EnumerateFiles(testsDirectory, "*.csproj")) { string relative = Relative(repositoryRoot, projectPath); if (!declaredTestProjects.ContainsKey(relative)) + { failures.Add($"{relative}: test project is missing from InnoEngine.sln."); + } } foreach ((string projectPath, string projectId) in declaredTestProjects) { - if (!parents.TryGetValue(projectId, out string? parentId) || - string.Equals(parentId, testsRoot, StringComparison.OrdinalIgnoreCase) || - !solutionFolders.Contains(parentId) || - !HasSolutionAncestor(parentId, testsRoot, parents)) - { + if (!parents.TryGetValue(projectId, out string? parentId) + || string.Equals(parentId, testsRoot, StringComparison.OrdinalIgnoreCase) + || !solutionFolders.Contains(parentId) + || !HasSolutionAncestor(parentId, testsRoot, parents) + ) { failures.Add($"{projectPath}: test project must be nested below a tests/ Solution Folder."); continue; } string projectName = names[projectId]; - bool isFixture = projectName.Contains(".TestModule", StringComparison.Ordinal) || - projectName.Contains(".TestAssembly", StringComparison.Ordinal) || - projectName.Contains(".TestDependency", StringComparison.Ordinal); + bool isFixture = projectName.Contains(".TestModule", StringComparison.Ordinal) + || projectName.Contains(".TestAssembly", StringComparison.Ordinal) + || projectName.Contains(".TestDependency", StringComparison.Ordinal); if (isFixture && !HasNamedSolutionAncestor(parentId, "fixtures", names, parents)) + { failures.Add($"{projectPath}: test support project must be nested below a fixtures Solution Folder."); + } string actualPath = GetSolutionFolderPath(projectId, names, solutionFolders, parents); string physicalGroup = Path.GetDirectoryName(Path.GetDirectoryName(projectPath))? - .Replace('\\', '/').TrimEnd('/') ?? string.Empty; + .Replace('\\', '/') + .TrimEnd('/') ?? string.Empty; if (!string.Equals(physicalGroup, actualPath, StringComparison.Ordinal)) { failures.Add( - $"{projectPath}: physical test folder '{physicalGroup}' must match Solution Folder '{actualPath}'."); + $"{projectPath}: physical test folder '{physicalGroup}' must match Solution Folder '{actualPath}'." + ); } } } @@ -519,8 +690,13 @@ ICollection failures string id = project.Groups["id"].Value; names[id] = project.Groups["name"].Value; paths[id] = project.Groups["path"].Value.Replace('\\', '/'); - if (string.Equals(project.Groups["type"].Value, "{2150E333-8FDC-42A3-9474-1A3956D46DE8}", StringComparison.OrdinalIgnoreCase)) + if (string.Equals( + project.Groups["type"].Value, + "{2150E333-8FDC-42A3-9474-1A3956D46DE8}", + StringComparison.OrdinalIgnoreCase + )) { solutionFolders.Add(id); + } continue; } @@ -535,30 +711,41 @@ ICollection failures continue; } if (!readingNestedProjects) + { continue; + } Match nesting = SolutionNestingPattern().Match(line); if (!nesting.Success) + { continue; + } string childId = nesting.Groups[1].Value; string parentId = nesting.Groups[2].Value; if (!parents.TryAdd(childId, parentId)) - failures.Add($"InnoEngine.sln: project or folder '{names.GetValueOrDefault(childId, childId)}' has more than one Solution Folder parent."); + { + failures.Add( + $"InnoEngine.sln: project or folder '{names.GetValueOrDefault(childId, childId)}' has more than one Solution Folder parent." + ); + } } var declaredSourceProjects = paths - .Where(static pair => S_PRODUCTION_ROOTS.Any(root => - pair.Value.StartsWith(root + "/", StringComparison.Ordinal)) && - pair.Value.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)) + .Where(static pair => ( + S_PRODUCTION_ROOTS.Any(root => pair.Value.StartsWith(root + "/", StringComparison.Ordinal)) + && pair.Value.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) + )) .ToDictionary(static pair => pair.Value, static pair => pair.Key, StringComparer.OrdinalIgnoreCase); foreach (string projectPath in S_PRODUCTION_ROOTS - .Select(root => Path.Combine(repositoryRoot, root)) - .Where(Directory.Exists) - .SelectMany(root => EnumerateFiles(root, "*.csproj"))) - { + .Select(root => Path.Combine(repositoryRoot, root)) + .Where(Directory.Exists) + .SelectMany(root => EnumerateFiles(root, "*.csproj")) + ) { string relative = Relative(repositoryRoot, projectPath); if (!declaredSourceProjects.ContainsKey(relative)) + { failures.Add($"{relative}: project is missing from InnoEngine.sln."); + } } foreach ((string projectPath, string projectId) in declaredSourceProjects) @@ -579,22 +766,31 @@ ICollection failures } string projectDirectory = Path.GetDirectoryName(Path.Combine(repositoryRoot, projectPath))!; - if (EnumerateFiles(projectDirectory, "*.csproj").Any(path => Path.GetFullPath(path) != Path.GetFullPath(Path.Combine(repositoryRoot, projectPath)))) + if (EnumerateFiles(projectDirectory, "*.csproj").Any( + path => Path.GetFullPath(path) != Path.GetFullPath(Path.Combine(repositoryRoot, projectPath)) + )) { expectedPath = Path.GetDirectoryName(projectPath)!.Replace('\\', '/'); + } string actualPath = GetSolutionFolderPath(projectId, names, solutionFolders, parents); if (!string.Equals(actualPath, expectedPath, StringComparison.Ordinal)) + { failures.Add($"{projectPath}: expected Solution Folder '{expectedPath}', found '{actualPath}'."); + } string physicalGroup = sourceRoot is "tools" or "entry" - ? sourceRoot - : Path.GetDirectoryName(Path.GetDirectoryName(projectPath))? - .Replace('\\', '/').TrimEnd('/') ?? string.Empty; + ? sourceRoot + : Path.GetDirectoryName(Path.GetDirectoryName(projectPath))? + .Replace('\\', '/') + .TrimEnd('/') ?? string.Empty; if (expectedPath == Path.GetDirectoryName(projectPath)?.Replace('\\', '/')) + { physicalGroup = expectedPath; + } if (!string.Equals(physicalGroup, expectedPath, StringComparison.Ordinal)) { failures.Add( - $"{projectPath}: physical source folder '{physicalGroup}' must match conceptual folder '{expectedPath}'."); + $"{projectPath}: physical source folder '{physicalGroup}' must match conceptual folder '{expectedPath}'." + ); } } } @@ -602,93 +798,175 @@ ICollection failures private static string? ClassifySourceSolutionPath(string projectName) { if (projectName.StartsWith("Inno.Core.", StringComparison.Ordinal)) + { return "src/foundation/core"; + } if (projectName.StartsWith("Inno.Extensibility.", StringComparison.Ordinal)) + { return "src/foundation/extensibility"; + } if (string.Equals(projectName, "Inno.Scripting.Api", StringComparison.Ordinal)) + { return "src/foundation/scripting"; + } if (string.Equals(projectName, "Inno.Shell", StringComparison.Ordinal)) + { return "src/composition/shell"; + } if (string.Equals(projectName, "Inno.Player.Runtime", StringComparison.Ordinal)) + { return "src/composition/player"; + } if (string.Equals(projectName, "Inno.Editor.Annotations", StringComparison.Ordinal)) + { return "src/composition/editor/contracts"; + } if (projectName.StartsWith("Inno.Editor.Panel.", StringComparison.Ordinal)) + { return "src/composition/editor/panels"; + } if (string.Equals(projectName, "Inno.Editor.Hosting", StringComparison.Ordinal)) + { return "src/composition/editor/hosting"; - if (projectName is "Inno.Editor.ImGui" or "Inno.Editor.Workbench" or "Inno.Editor.Assets.ImGui" or "Inno.Editor.Shaders.ImGui" or "Inno.Editor.Graph.ImGui") + } + if (projectName is "Inno.Editor.ImGui" + or "Inno.Editor.Workbench" + or "Inno.Editor.Assets.ImGui" + or "Inno.Editor.Shaders.ImGui" + or "Inno.Editor.Graph.ImGui" + ) { return "src/composition/editor/presentation"; - if (string.Equals(projectName, "Inno.Editor.Core", StringComparison.Ordinal) || - string.Equals(projectName, "Inno.Editor.Diagnostics", StringComparison.Ordinal) || - string.Equals(projectName, "Inno.Editor.Graph", StringComparison.Ordinal) || - string.Equals(projectName, "Inno.Editor.Inspection", StringComparison.Ordinal) || - string.Equals(projectName, "Inno.Editor.Interactions", StringComparison.Ordinal) || - string.Equals(projectName, "Inno.Editor.Settings", StringComparison.Ordinal)) - { + } + if (string.Equals(projectName, "Inno.Editor.Core", StringComparison.Ordinal) + || string.Equals(projectName, "Inno.Editor.Diagnostics", StringComparison.Ordinal) + || string.Equals(projectName, "Inno.Editor.Graph", StringComparison.Ordinal) + || string.Equals(projectName, "Inno.Editor.Inspection", StringComparison.Ordinal) + || string.Equals(projectName, "Inno.Editor.Interactions", StringComparison.Ordinal) + || string.Equals(projectName, "Inno.Editor.Settings", StringComparison.Ordinal) + ) { return "src/composition/editor/framework"; } if (projectName.StartsWith("Inno.Editor.", StringComparison.Ordinal)) + { return "src/composition/editor/features"; + } if (string.Equals(projectName, "Inno.Adapter", StringComparison.Ordinal)) + { return "src/adapters/common"; + } if (string.Equals(projectName, "Inno.Adapter.Default", StringComparison.Ordinal)) + { return "src/composition/adapters"; + } if (string.Equals(projectName, "Inno.Adapter.Authoring.Default", StringComparison.Ordinal)) + { return "src/composition/adapters"; + } if (projectName.StartsWith("Inno.Adapter.Presentation", StringComparison.Ordinal)) + { return "src/adapters/presentation"; + } if (projectName.StartsWith("Inno.Adapter.Platform", StringComparison.Ordinal)) + { return "src/adapters/platform"; + } if (projectName.StartsWith("Inno.Adapter.Input", StringComparison.Ordinal)) + { return "src/adapters/input"; + } if (projectName.StartsWith("Inno.Adapter.Storage", StringComparison.Ordinal)) + { return "src/adapters/storage"; + } if (projectName.StartsWith("Inno.Adapter.Rendering", StringComparison.Ordinal)) + { return "src/adapters/rendering"; + } if (projectName.StartsWith("Inno.Adapter.Text", StringComparison.Ordinal)) + { return "src/adapters/text"; + } if (projectName.StartsWith("Inno.Adapter.UI", StringComparison.Ordinal)) + { return "src/adapters/ui"; + } if (projectName.StartsWith("Inno.Adapter.Audio", StringComparison.Ordinal)) + { return "src/adapters/audio"; + } if (string.Equals(projectName, "Inno.Content", StringComparison.Ordinal)) + { return "src/content/deployment"; + } if (projectName.StartsWith("Inno.References", StringComparison.Ordinal)) + { return "src/content/references"; + } if (projectName.StartsWith("Inno.Assets", StringComparison.Ordinal)) + { return "src/content/assets"; + } if (projectName.StartsWith("Inno.Scene", StringComparison.Ordinal)) + { return "src/content/scene"; + } if (projectName.StartsWith("Inno.Animation", StringComparison.Ordinal)) + { return "src/content/animation"; + } if (string.Equals(projectName, "Inno.Platform", StringComparison.Ordinal)) + { return "src/services/platform"; + } if (projectName.StartsWith("Inno.Input", StringComparison.Ordinal)) + { return "src/services/input"; + } if (projectName.StartsWith("Inno.Storage", StringComparison.Ordinal)) + { return "src/services/storage"; + } if (projectName.StartsWith("Inno.Rendering", StringComparison.Ordinal)) + { return "src/services/rendering"; + } if (projectName.StartsWith("Inno.Text", StringComparison.Ordinal)) + { return "src/services/text"; + } if (projectName.StartsWith("Inno.UI", StringComparison.Ordinal)) + { return "src/services/ui"; + } if (projectName.StartsWith("Inno.Audio", StringComparison.Ordinal)) + { return "src/services/audio"; + } if (string.Equals(projectName, "Inno.Runtime", StringComparison.Ordinal)) + { return "src/runtime/engine"; + } if (string.Equals(projectName, "Inno.Runtime.Contracts", StringComparison.Ordinal)) + { return "src/runtime/contracts"; + } if (string.Equals(projectName, "Inno.Runtime.Generators", StringComparison.Ordinal)) + { return "src/runtime/generators"; + } if (string.Equals(projectName, "Inno.Engine.Default", StringComparison.Ordinal)) + { return "src/composition/default"; + } if (projectName.StartsWith("Inno.Scripting", StringComparison.Ordinal)) + { return "src/runtime/scripting"; + } if (projectName.StartsWith("Inno.Plugins", StringComparison.Ordinal)) + { return "src/runtime/plugins"; + } return null; } @@ -699,17 +977,23 @@ private static string GetSolutionFolderPath( IReadOnlyDictionary parents ) { if (!parents.TryGetValue(projectId, out string? currentId)) + { return ""; + } var segments = new List(); var visited = new HashSet(StringComparer.OrdinalIgnoreCase); while (visited.Add(currentId)) { if (!solutionFolders.Contains(currentId)) + { return ""; + } segments.Add(names.GetValueOrDefault(currentId, currentId)); if (!parents.TryGetValue(currentId, out currentId!)) + { break; + } } segments.Reverse(); return string.Join('/', segments); @@ -725,9 +1009,13 @@ IReadOnlyDictionary parents while (visited.Add(currentId)) { if (string.Equals(currentId, expectedAncestorId, StringComparison.OrdinalIgnoreCase)) + { return true; + } if (!parents.TryGetValue(currentId, out currentId!)) + { return false; + } } return false; } @@ -743,9 +1031,13 @@ IReadOnlyDictionary parents while (visited.Add(currentId)) { if (string.Equals(names.GetValueOrDefault(currentId), expectedName, StringComparison.Ordinal)) + { return true; + } if (!parents.TryGetValue(currentId, out currentId!)) + { return false; + } } return false; } @@ -753,8 +1045,7 @@ IReadOnlyDictionary parents private static bool IsAnyDomain( string path, params string[] domains - ) - => domains.Any(domain => path.StartsWith($"src/{domain}/", StringComparison.Ordinal)); + ) => domains.Any(domain => path.StartsWith($"src/{domain}/", StringComparison.Ordinal)); private static void AddSourceFailure( bool condition, @@ -763,11 +1054,12 @@ private static void AddSourceFailure( ICollection failures ) { if (condition) + { failures.Add($"{path}: {message}."); + } } - private static IEnumerable EnumerateDirectories(string root) - => RepositorySourceInventory.Directories(root); + private static IEnumerable EnumerateDirectories(string root) => RepositorySourceInventory.Directories(root); private static IEnumerable EnumerateFiles( string root, @@ -777,8 +1069,8 @@ string pattern private static bool IsIgnoredPath(string path) => path.Split(Path.DirectorySeparatorChar).Any(S_IGNORED_DIRECTORIES.Contains); private static bool IsGenerated(string source) - => source.Contains("", StringComparison.OrdinalIgnoreCase) || - source.Contains("[GeneratedCode", StringComparison.Ordinal); + => source.Contains("", StringComparison.OrdinalIgnoreCase) + || source.Contains("[GeneratedCode", StringComparison.Ordinal); private static string Relative( string repositoryRoot, @@ -788,7 +1080,9 @@ string path [GeneratedRegex(@"\b(schemaVersion|formatVersion|formerVersion)\b", RegexOptions.IgnoreCase)] private static partial Regex CompatibilityFieldPattern(); - [GeneratedRegex(@"Executes this contract at the caller-controlled boundary|Transforms validated inputs into a deterministic result|Gets caller-visible|input consumed by this operation|state exposed by this contract|value associated with this contract|Models the .* domain value|Performs the .* operation|Runs the .* operation|Gets the .* value owned by the current instance")] + [GeneratedRegex( + @"Executes this contract at the caller-controlled boundary|Transforms validated inputs into a deterministic result|Gets caller-visible|input consumed by this operation|state exposed by this contract|value associated with this contract|Models the .* domain value|Performs the .* operation|Runs the .* operation|Gets the .* value owned by the current instance" + )] private static partial Regex UninformativeXmlPattern(); [GeneratedRegex(@"^\s*///\s*<(summary|param|typeparam|returns|exception|remarks)\b[^>]*>.+\s*$")] diff --git a/tools/Inno.Tooling.Architecture/CSharpStyleValidator.cs b/tools/Inno.Tooling.Architecture/CSharpStyleValidator.cs index 06223720e..03935e3af 100644 --- a/tools/Inno.Tooling.Architecture/CSharpStyleValidator.cs +++ b/tools/Inno.Tooling.Architecture/CSharpStyleValidator.cs @@ -1,11 +1,5 @@ -using System; using System.Collections.Generic; -using System.Linq; - using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; namespace Inno.Tooling.Architecture; @@ -13,47 +7,23 @@ internal static class CSharpStyleValidator { internal static void Validate( string relativePath, + string content, SyntaxTree tree, ICollection failures ) { - SourceText text = tree.GetText(); EditorPresentationSourceValidator.Validate(relativePath, tree, failures); - foreach (ParameterListSyntax parameters in tree.GetRoot().DescendantNodes().OfType()) - { - if (parameters.Parameters.Count <= 1) - continue; - var violations = new List(); - TextLine opening = text.Lines.GetLineFromPosition(parameters.OpenParenToken.SpanStart); - int previous = opening.LineNumber; - foreach (ParameterSyntax parameter in parameters.Parameters) - { - TextLine line = text.Lines.GetLineFromPosition(parameter.SpanStart); - if (line.LineNumber <= previous) - violations.Add("place each parameter on its own line after the opening parenthesis"); - previous = text.Lines.GetLineFromPosition(parameter.Span.End - 1).LineNumber; - } - - TextLine closing = text.Lines.GetLineFromPosition(parameters.CloseParenToken.SpanStart); - string prefix = text.ToString(TextSpan.FromBounds(closing.Start, parameters.CloseParenToken.SpanStart)); - TextLine declaration = text.Lines.GetLineFromPosition(parameters.Parent!.SpanStart); - string indentation = new(declaration.ToString().TakeWhile(static value => value is ' ' or '\t').ToArray()); - if (closing.LineNumber <= previous || prefix != indentation) - violations.Add("align the closing parenthesis on its own line with the declaration"); - - BlockSyntax? body = parameters.Parent switch - { - MethodDeclarationSyntax { ConstraintClauses.Count: 0 } method => method.Body, - ConstructorDeclarationSyntax { Initializer: null } constructor => constructor.Body, - LocalFunctionStatementSyntax { ConstraintClauses.Count: 0 } local => local.Body, - OperatorDeclarationSyntax operation => operation.Body, - ConversionOperatorDeclarationSyntax conversion => conversion.Body, - _ => null - }; - if (body is not null && text.Lines.GetLineFromPosition(body.OpenBraceToken.SpanStart).LineNumber != closing.LineNumber) - violations.Add("place the function body opening brace after the closing parenthesis as ') {'"); + ValidateStyle(relativePath, content, failures); + } - if (violations.Count > 0) - failures.Add($"{relativePath}:{opening.LineNumber + 1}: {string.Join("; ", violations.Distinct(StringComparer.Ordinal))}."); + // Reports each finding of the style rulebook as ':: : '. + internal static void ValidateStyle( + string relativePath, + string content, + ICollection failures + ) { + foreach (StyleFinding finding in StyleEngine.Check(relativePath, content)) + { + failures.Add($"{finding.path}:{finding.line}: {finding.rule}: {finding.message}"); } } } diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ArgumentJoinStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ArgumentJoinStyleRule.cs new file mode 100644 index 000000000..2e980e8dd --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ArgumentJoinStyleRule.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// A-01: an argument list stays on one line whenever the line that results fits within the line width. +internal sealed class ArgumentJoinStyleRule : StyleRule +{ + private const string C_ID = "A-01"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((StyleList list, string _) in Joinable(source)) + { + findings.Add(source.Finding(C_ID, list.open.SpanStart, "Keep the argument list on one line: it fits within the line width.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + var spans = new List(); + // Innermost lists first: an outer list is judged again once its content has settled. + foreach ((StyleList list, string joined) in Joinable(source).OrderByDescending(static entry => entry.list.open.SpanStart)) + { + TextSpan span = TextSpan.FromBounds(list.open.SpanStart, list.close.Span.End); + if (spans.Any(inner => span.Contains(inner))) continue; + edits.Add(new(span.Start, span.End, joined)); + spans.Add(span); + } + + return edits; + } + + private static IEnumerable<(StyleList list, string joined)> Joinable(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + StyleList? list = StyleList.Arguments(node); + if (list is null) continue; + int openLine = source.LineNumber(list.open.SpanStart); + int closeLine = source.LineNumber(list.close.SpanStart); + if (openLine == closeLine) continue; + string? joined = StyleLayout.Join(source, list.open, list.close); + if (joined is null) continue; + int tail = source.text.Lines[closeLine].End - list.close.Span.End; + if (source.Column(list.open.SpanStart) + joined.Length + tail > StyleLayout.C_WIDTH) continue; + yield return (list, joined); + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ArgumentListStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ArgumentListStyleRule.cs new file mode 100644 index 000000000..2ebbd3c82 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ArgumentListStyleRule.cs @@ -0,0 +1,111 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// A-02 and A-03: a broken argument list puts the opening parenthesis at the end of its line, each argument +// on its own line indented four spaces, and the closing parenthesis on its own line. One multi-line lambda, +// initializer, anonymous object, collection expression or multi-line string may instead hug the parentheses. +internal sealed class ArgumentListStyleRule : StyleRule +{ + private const string C_ID = "A-02"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (StyleList list in Violations(source)) + { + findings.Add( + source.Finding(C_ID, list.open.SpanStart, "Expand the broken argument list: one argument per line and ')' on its own line.") + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + var edits = new List(); + var fixedSpans = new List(); + foreach (StyleList list in Violations(source).OrderBy(static list => list.open.SpanStart)) + { + // Nested lists are fixed in a later round, after their container has settled. + TextSpan span = TextSpan.FromBounds(list.open.SpanStart, list.close.Span.End); + if (fixedSpans.Any(outer => outer.Contains(span))) continue; + List? listEdits = StyleLayout.Expand(source, list, protectedSpans); + if (listEdits is null) continue; + edits.AddRange(listEdits); + fixedSpans.Add(span); + } + + return edits; + } + + private static IEnumerable Violations(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + StyleList? list = StyleList.Arguments(node); + if (list is null) continue; + if (source.LineNumber(list.open.SpanStart) == source.LineNumber(list.close.SpanStart)) continue; + if (IsHugged(source, list) || StyleLayout.IsExpanded(source, list)) continue; + yield return list; + } + } + + private static bool IsHugged( + StyleSource source, + StyleList list + ) { + int openLine = source.LineNumber(list.open.SpanStart); + SyntaxNode? multiLine = null; + foreach (SyntaxNode argument in list.items) + { + if (source.LineNumber(argument.SpanStart) == source.LineNumber(argument.Span.End)) continue; + if (multiLine is not null) return false; + multiLine = argument; + } + + if (multiLine is null || !CanHug(multiLine)) return false; + // Arguments before the multi-line one share the opening line; the rest follow its closing delimiter. + int endLine = source.LineNumber(multiLine.Span.End); + foreach (SyntaxNode argument in list.items) + { + int line = source.LineNumber(argument.SpanStart); + if (argument.SpanStart <= multiLine.SpanStart ? line != openLine : line != endLine) return false; + } + + return source.LineNumber(list.close.SpanStart) == endLine; + } + + private static bool CanHug(SyntaxNode argument) + { + ExpressionSyntax? expression = argument switch + { + ArgumentSyntax value => value.Expression, + AttributeArgumentSyntax value => value.Expression, + _ => null + }; + return expression switch + { + LambdaExpressionSyntax or AnonymousMethodExpressionSyntax => true, + AnonymousObjectCreationExpressionSyntax or CollectionExpressionSyntax => true, + ObjectCreationExpressionSyntax { Initializer: not null } => true, + ImplicitObjectCreationExpressionSyntax { Initializer: not null } => true, + ArrayCreationExpressionSyntax { Initializer: not null } or ImplicitArrayCreationExpressionSyntax => true, + LiteralExpressionSyntax literal => literal.IsKind(SyntaxKind.StringLiteralExpression) || literal.IsKind( + SyntaxKind.Utf8StringLiteralExpression + ), + InterpolatedStringExpressionSyntax => true, + _ => false + }; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ArrowMemberStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ArrowMemberStyleRule.cs new file mode 100644 index 000000000..8a9234dfd --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ArrowMemberStyleRule.cs @@ -0,0 +1,160 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// M-03: '=> expression' stays on the declaration line when the member fits; otherwise '=>' starts the next +// line, indented four spaces. It never ends a line, and a brace-delimited body after a wrapped '=>' puts +// its braces at the column of the declaration. +internal sealed class ArrowMemberStyleRule : StyleRule +{ + private const string C_ID = "M-03"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (node is not ArrowExpressionClauseSyntax clause) continue; + (string message, List edits)? violation = Violation(source, clause, protectedSpans); + if (violation is { } found) findings.Add(source.Finding(C_ID, clause.ArrowToken.SpanStart, found.message)); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + var edits = new List(); + int fixedEnd = -1; + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + // A member nested in the body of another fixed member waits for the next round. + if (node is not ArrowExpressionClauseSyntax clause || clause.SpanStart < fixedEnd) continue; + if (Violation(source, clause, protectedSpans) is not { } found) continue; + edits.AddRange(found.edits); + fixedEnd = clause.Span.End; + } + + return edits; + } + + private static (string message, List edits)? Violation( + StyleSource source, + ArrowExpressionClauseSyntax clause, + IReadOnlyList protectedSpans + ) { + SyntaxToken arrow = clause.ArrowToken; + SyntaxToken previous = arrow.GetPreviousToken(); + SyntaxToken first = clause.Expression.GetFirstToken(); + if (arrow.IsMissing || first.IsMissing) return null; + string content = source.content; + if (!StyleLayout.IsBlank(content, previous.Span.End, arrow.SpanStart) + || !StyleLayout.IsBlank(content, arrow.Span.End, first.SpanStart) + ) { + return null; + } + int declaration = source.Indentation(previous.SpanStart); + int arrowLine = source.LineNumber(arrow.SpanStart); + int firstLine = source.LineNumber(first.SpanStart); + int lastLine = source.LineNumber(clause.Expression.Span.End); + bool afterParameters = StyleLayout.ClosesMultiLineHeader(source, previous); + var edits = new List(); + if (arrowLine != firstLine) + { + // '=>' ends its line: it moves in front of the expression. + bool wrapped = !afterParameters; + if (wrapped) + { + TextLine signatureLine = source.Line(previous.Span.End); + int joined = signatureLine.End - signatureLine.Start + " => ".Length + source.text.Lines[firstLine].End - first.SpanStart; + wrapped = firstLine != lastLine || joined > StyleLayout.C_WIDTH; + } + + edits.Add(new(previous.Span.End, arrow.SpanStart, wrapped ? "\n" + new string(' ', declaration + StyleLayout.C_INDENT) : " ")); + edits.Add(new(arrow.Span.End, first.SpanStart, " ")); + if (!wrapped) + { + AddShifts(source, edits, firstLine + 1, lastLine, declaration - source.Indentation(first.SpanStart), protectedSpans); + } + + return ("Do not end a line with '=>'.", edits); + } + + if (!source.IsFirstOnLine(arrow)) + { + // M-03: a body that does not fit after a one-line signature starts on the next line with '=>'. + if (afterParameters || firstLine == lastLine || clause.Parent is AccessorDeclarationSyntax) return null; + // A multi-line string has no layout of its own to move. + if (clause.Expression is LiteralExpressionSyntax or InterpolatedStringExpressionSyntax) return null; + if (source.LineNumber(clause.Parent!.GetFirstToken().SpanStart) != arrowLine) return null; + edits.Add(new(previous.Span.End, arrow.SpanStart, "\n" + new string(' ', declaration + StyleLayout.C_INDENT))); + bool isDelimited = clause.Expression is SwitchExpressionSyntax or WithExpressionSyntax + or BaseObjectCreationExpressionSyntax { Initializer: not null }; + if (!isDelimited) AddShifts(source, edits, firstLine + 1, lastLine, StyleLayout.C_INDENT, protectedSpans); + return ("Move '=>' to the next line: the body does not fit after the signature.", edits); + } + + if (afterParameters) return null; + // A wrapped '=>' whose member fits on one line returns to the declaration line. + TextLine signature = source.text.Lines[source.LineNumber(previous.Span.End)]; + if (firstLine == lastLine + && signature.End - signature.Start + 1 + source.text.Lines[arrowLine].End - arrow.SpanStart <= StyleLayout.C_WIDTH + && source.LineNumber(clause.Parent!.GetFirstToken().SpanStart) == source.LineNumber(previous.Span.End) + ) { + edits.Add(new(previous.Span.End, arrow.SpanStart, " ")); + return ("Keep '=> expression' on the declaration line: the member fits on one line.", edits); + } + + int delta = declaration + StyleLayout.C_INDENT - source.Column(arrow.SpanStart); + if (delta != 0) + { + AddShifts(source, edits, arrowLine, lastLine, delta, protectedSpans); + return ("Indent a wrapped '=>' four spaces from the declaration.", edits); + } + + // Braces of a switch expression, an initializer or a 'with' expression sit at the declaration column. + SyntaxToken brace = clause.Expression switch + { + SwitchExpressionSyntax expression => expression.OpenBraceToken, + WithExpressionSyntax expression => expression.Initializer.OpenBraceToken, + BaseObjectCreationExpressionSyntax { Initializer: not null } expression => expression.Initializer.OpenBraceToken, + _ => default + }; + if (brace.Span.Length == 0 || !source.IsFirstOnLine(brace) || source.Column(brace.SpanStart) == declaration) + { + return null; + } + AddShifts( + source, + edits, + source.LineNumber(brace.SpanStart), + lastLine, + declaration - source.Column(brace.SpanStart), + protectedSpans + ); + return ("Put the braces of a wrapped expression body at the column of the declaration.", edits); + } + + private static void AddShifts( + StyleSource source, + List edits, + int firstLine, + int lastLine, + int delta, + IReadOnlyList protectedSpans + ) { + for (int line = firstLine; line <= lastLine && delta != 0; line++) + { + StyleEdit? shift = StyleLayout.Shift(source, line, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/BraceBlankLineStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/BraceBlankLineStyleRule.cs new file mode 100644 index 000000000..90f0a67d3 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/BraceBlankLineStyleRule.cs @@ -0,0 +1,40 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Inno.Tooling.Architecture; + +// S-04: no blank line follows an opening brace or precedes a closing brace. +internal sealed class BraceBlankLineStyleRule : StyleRule +{ + private const string C_ID = "S-04"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (StyleEdit edit in Fix(source)) + { + findings.Add(source.Finding(C_ID, edit.start, "Remove the blank line next to the brace.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + int count = source.text.Lines.Count; + for (int line = 1; line < count - 1; line++) + { + if (!StyleLines.IsBlank(source, line)) continue; + bool afterOpen = StyleLines.LastToken(source, line - 1).IsKind(SyntaxKind.OpenBraceToken); + bool beforeClose = StyleLines.FirstToken(source, line + 1).IsKind(SyntaxKind.CloseBraceToken); + if (afterOpen || beforeClose) edits.Add(StyleLines.Remove(source, line)); + } + + return edits; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/BraceListStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/BraceListStyleRule.cs new file mode 100644 index 000000000..1bfe807b0 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/BraceListStyleRule.cs @@ -0,0 +1,122 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// I-01, I-03 and I-04: a multi-line initializer, anonymous object, 'with' expression, switch expression or +// collection expression has one item per line and its closing delimiter on its own line. Braces, and the +// bracket of a collection that is the value of a declaration or assignment, open on their own line. +internal sealed class BraceListStyleRule : StyleRule +{ + private const string C_ID = "I-01"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((StyleList list, List _) in Violations(source)) + { + findings.Add( + source.Finding( + C_ID, + list.open.SpanStart, + "Lay out the initializer or collection: one line when it fits, otherwise one item per line with the delimiters on their own lines." + ) + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + int fixedEnd = -1; + foreach ((StyleList list, List listEdits) in Violations(source).OrderBy( + static violation => violation.list.open.SpanStart + )) { + // A list nested in a fixed list waits for the next round. + if (list.open.SpanStart < fixedEnd) continue; + edits.AddRange(listEdits); + fixedEnd = list.close.Span.End; + } + + return edits; + } + + private static bool IsLiteral(SyntaxNode item) + => item switch + { + ExpressionElementSyntax element => IsLiteral(element.Expression), + LiteralExpressionSyntax => true, + PrefixUnaryExpressionSyntax unary => IsLiteral(unary.Operand), + _ => false + }; + + private static IEnumerable<(StyleList list, List edits)> Violations(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + StyleList? list = StyleList.Braces(node); + if (list is null) continue; + if (source.LineNumber(list.open.SpanStart) == source.LineNumber(list.close.SpanStart)) + { + // I-01: a one-line initializer does not start a line; it joins 'new T' or expands. + if (node is not (InitializerExpressionSyntax or AnonymousObjectCreationExpressionSyntax)) continue; + if (!source.IsFirstOnLine(list.open) || node is AnonymousObjectCreationExpressionSyntax) continue; + SyntaxToken owner = list.open.GetPreviousToken(); + if (!StyleLayout.IsBlank(source.content, owner.Span.End, list.open.SpanStart)) continue; + TextLine ownerLine = source.Line(owner.Span.End); + TextLine braceLine = source.Line(list.open.SpanStart); + if (owner.Span.End == ownerLine.End + && ownerLine.End - ownerLine.Start + 1 + braceLine.End - list.open.SpanStart <= StyleLayout.C_WIDTH + ) { + yield return (list, [new(owner.Span.End, list.open.SpanStart, " ")]); + continue; + } + + List? expanded = StyleLayout.Expand(source, list, protectedSpans); + if (expanded is not null && expanded.Count > 0) yield return (list, expanded); + continue; + } + + // A single element that spans several lines hugs the brackets (I-03). + if (node is CollectionExpressionSyntax && list.items.Count == 1) continue; + // A numeric matrix or lookup table may keep several elements per line (S-02). + bool isWide = Enumerable + .Range( + source.LineNumber(list.open.SpanStart), + source.LineNumber(list.close.SpanStart) - source.LineNumber(list.open.SpanStart) + 1 + ) + .Any(line => source.text.Lines[line].End - source.text.Lines[line].Start > StyleLayout.C_HARD_WIDTH); + if (list.items.Count > 1 && !isWide && list.items.All(static item => IsLiteral(item))) continue; + SyntaxToken previous = list.open.GetPreviousToken(); + bool opensLine = node is not CollectionExpressionSyntax || node.Parent is EqualsValueClauseSyntax or AssignmentExpressionSyntax; + if (opensLine && !source.IsFirstOnLine(list.open)) + { + if (!StyleLayout.IsBlank(source.content, previous.Span.End, list.open.SpanStart)) continue; + int indentation = source.Indentation(previous.SpanStart); + // After a wrapped '=>' the braces sit at the column of the declaration (M-03). + SyntaxToken lineStart = StyleLines.FirstToken(source, source.LineNumber(previous.SpanStart)); + if (lineStart.IsKind(SyntaxKind.EqualsGreaterThanToken) + && lineStart.Parent is ArrowExpressionClauseSyntax + ) { + indentation -= StyleLayout.C_INDENT; + } + yield return (list, [new(previous.Span.End, list.open.SpanStart, "\n" + new string(' ', indentation))]); + continue; + } + + if (StyleLayout.IsExpanded(source, list)) continue; + List? edits = StyleLayout.Expand(source, list, protectedSpans); + if (edits is not null && edits.Count > 0) yield return (list, edits); + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/BraceStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/BraceStyleRule.cs new file mode 100644 index 000000000..b7735c4c9 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/BraceStyleRule.cs @@ -0,0 +1,104 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// B-01, B-08 and B-09: the braces of a multi-line body are on their own lines, nothing shares the line of +// an opening brace, and 'else', 'catch', 'finally' and the 'while' of a 'do' loop start a new line. +internal sealed class BraceStyleRule : StyleRule +{ + private const string C_ID = "B-01"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((int position, string _, string message) in Violations(source)) + { + findings.Add(source.Finding(C_ID, position, message)); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + foreach ((int position, string indent, string _) in Violations(source)) + { + int start = position; + while (start > 0 && source.content[start - 1] == ' ') + { + start--; + } + + edits.Add(new(start, position, "\n" + indent)); + } + + return edits; + } + + // Each violation is a token that must start a new line, with the indentation that line takes. + private static IEnumerable<(int position, string indent, string message)> Violations(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + (SyntaxToken open, SyntaxToken close)? braces = Braces(node); + if (braces is { } pair && !pair.open.IsMissing && !pair.close.IsMissing + && source.LineNumber(pair.open.SpanStart) != source.LineNumber(pair.close.SpanStart) + ) { + SyntaxToken previous = pair.open.GetPreviousToken(); + int indentation = source.IsFirstOnLine(pair.open) + ? source.Column(pair.open.SpanStart) + : source.Indentation(previous.SpanStart); + if (!source.IsFirstOnLine(pair.open) && !StyleLayout.ClosesMultiLineHeader(source, previous)) + { + yield return (pair.open.SpanStart, new(' ', indentation), "Put the opening brace on its own line."); + } + + SyntaxToken next = pair.open.GetNextToken(); + if (source.LineNumber(next.SpanStart) == source.LineNumber(pair.open.SpanStart)) + { + yield return (next.SpanStart, new( + ' ', + indentation + StyleLayout.C_INDENT + ), "Nothing follows an opening brace on its line."); + } + + if (!source.IsFirstOnLine(pair.close)) + { + yield return (pair.close.SpanStart, new(' ', indentation), "Put the closing brace on its own line."); + } + } + + SyntaxToken keyword = node switch + { + ElseClauseSyntax clause => clause.ElseKeyword, + CatchClauseSyntax clause => clause.CatchKeyword, + FinallyClauseSyntax clause => clause.FinallyKeyword, + DoStatementSyntax loop => loop.WhileKeyword, + _ => default + }; + if (keyword.IsKind(SyntaxKind.None) || keyword.IsMissing || source.IsFirstOnLine(keyword)) continue; + SyntaxToken before = keyword.GetPreviousToken(); + if (!before.IsKind(SyntaxKind.CloseBraceToken)) continue; + yield return (keyword.SpanStart, new(' ', source.Indentation(before.SpanStart)), $"Start a new line for '{keyword.Text}'."); + } + } + + private static (SyntaxToken open, SyntaxToken close)? Braces(SyntaxNode node) + => node switch + { + BlockSyntax block => (block.OpenBraceToken, block.CloseBraceToken), + BaseTypeDeclarationSyntax type when !type.OpenBraceToken.IsKind(SyntaxKind.None) => (type.OpenBraceToken, type.CloseBraceToken), + NamespaceDeclarationSyntax scope => (scope.OpenBraceToken, scope.CloseBraceToken), + SwitchStatementSyntax statement => (statement.OpenBraceToken, statement.CloseBraceToken), + SwitchExpressionSyntax expression => (expression.OpenBraceToken, expression.CloseBraceToken), + AccessorListSyntax accessors => (accessors.OpenBraceToken, accessors.CloseBraceToken), + _ => null + }; +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ChainStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ChainStyleRule.cs new file mode 100644 index 000000000..3c2aca117 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ChainStyleRule.cs @@ -0,0 +1,245 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// W-03: in a broken call chain every '.' starts its line, indented four spaces from the line on which the +// chain starts, and consecutive calls after the first break each take their own line. +internal sealed class ChainStyleRule : StyleRule +{ + private const string C_ID = "W-03"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((int position, string message, List _) in Violations(source)) + { + findings.Add(source.Finding(C_ID, position, message)); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + int fixedEnd = -1; + foreach ((int position, string _, List chainEdits) in Violations(source)) + { + // A chain nested in the lines of a fixed chain waits for the next round. + if (position < fixedEnd) continue; + edits.AddRange(chainEdits); + fixedEnd = chainEdits.Max(static edit => edit.end); + } + + return edits; + } + + private static IEnumerable<(int position, string message, List edits)> Violations(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + IEnumerable> chains = source.root.DescendantNodes() + .Where(static node => node is MemberAccessExpressionSyntax or MemberBindingExpressionSyntax) + .Cast() + .GroupBy(Top) + .OrderBy(static chain => chain.Key.SpanStart); + foreach (IGrouping chain in chains) + { + ExpressionSyntax top = chain.Key; + int firstLine = source.LineNumber(top.SpanStart); + int lastLine = source.LineNumber(top.Span.End); + if (firstLine == lastLine) continue; + ExpressionSyntax[] links = chain.OrderBy(static link => Dot(link).SpanStart).ToArray(); + int indent = source.Indentation(top.SpanStart) + StyleLayout.C_INDENT; + string lineBreak = "\n" + new string(' ', indent); + var edits = new List(); + string? message = null; + // The receiver and the first call may share the statement line; every later call starts a line. + bool isBroken = links.Any(link => source.IsFirstOnLine(Lead(Dot(link)))); + for (int index = 0; index < links.Length; index++) + { + SyntaxToken dot = Dot(links[index]); + SyntaxToken lead = Lead(dot); + SyntaxToken previous = lead.GetPreviousToken(); + SyntaxToken next = dot.GetNextToken(); + if (source.LineNumber(dot.SpanStart) != source.LineNumber(next.SpanStart)) + { + // A '.' that ends its line moves in front of the member it selects. + string gap = source.content[dot.Span.End..next.SpanStart]; + if (!StyleLayout.IsBlank(gap, 0, gap.Length) || source.IsFirstOnLine(lead)) continue; + edits.Add(new(previous.Span.End, next.SpanStart, lineBreak + source.content[lead.SpanStart..dot.Span.End])); + message ??= "Start the continuation line with '.' instead of ending the line with it."; + isBroken = true; + continue; + } + + if (source.IsFirstOnLine(lead)) continue; + if (!isBroken || !IsCall(links[index])) continue; + if (index == 0 || !IsCall(links[index - 1])) + { + // The first call keeps the statement line unless its own arguments are broken and calls follow it. + var arguments = ((InvocationExpressionSyntax)links[index].Parent!).ArgumentList; + bool isSplit = source.LineNumber(arguments.OpenParenToken.SpanStart) != source.LineNumber( + arguments.CloseParenToken.SpanStart + ); + if (!isSplit || index + 1 >= links.Length || !IsCall(links[index + 1])) continue; + } + + if (!StyleLayout.IsBlank(source.content, previous.Span.End, lead.SpanStart)) continue; + edits.Add(new(previous.Span.End, lead.SpanStart, lineBreak)); + message ??= "Put each call of a broken chain on its own line."; + + // The lines of the arguments keep their offset from the line the call now starts. + int dotLine = source.LineNumber(dot.SpanStart); + int delta = indent - source.Indentation(source.text.Lines[dotLine].Start); + int closeLine = source.LineNumber(links[index].Parent!.Span.End); + for (int line = dotLine + 1; line <= closeLine && delta != 0; line++) + { + StyleEdit? shift = StyleLayout.Shift(source, line, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + } + + if (edits.Count == 0) + { + int[] lines = links + .Select(link => Lead(Dot(link))) + .Where(source.IsFirstOnLine) + .Select(lead => source.LineNumber(lead.SpanStart)) + .Where(line => line > firstLine) + .Distinct() + .Order() + .ToArray(); + for (int index = 0; index < lines.Length; index++) + { + int delta = indent - source.Indentation(source.text.Lines[lines[index]].Start); + int end = index + 1 < lines.Length ? lines[index + 1] - 1 : lastLine; + for (int line = lines[index]; line <= end && delta != 0; line++) + { + StyleEdit? shift = StyleLayout.Shift(source, line, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + } + + if (edits.Count > 0) message = "Indent the chain four spaces from the line on which it starts."; + } + + if (message is not null) yield return (edits.Min(static edit => edit.start), message, edits); + } + } + + // F-04: the outermost call chain of an over-long line breaks before each of its calls on that line. The + // receiver and, for a static call, the first call keep the statement line. + internal static (TextSpan span, List edits)? BreakOnLine( + StyleSource source, + TextLine line + ) { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + (TextSpan span, List edits)? best = null; + IEnumerable> chains = source.root + .DescendantNodes(TextSpan.FromBounds(line.Start, line.End)) + .Where(static node => node is MemberAccessExpressionSyntax or MemberBindingExpressionSyntax) + .Cast() + .GroupBy(Top); + foreach (IGrouping chain in chains) + { + ExpressionSyntax top = chain.Key; + if (best is { } current && top.Span.Length <= current.span.Length) continue; + if (StyleLayout.IsInInterpolation(top)) continue; + ExpressionSyntax[] links = chain.OrderBy(static link => Dot(link).SpanStart).ToArray(); + int calls = links.Count(IsCall); + if (IsCall(links[^1]) && Name(links[^1]) == "ConfigureAwait") calls--; + if (calls < 2) continue; + int indent = source.Indentation(top.SpanStart) + StyleLayout.C_INDENT; + string lineBreak = "\n" + new string(' ', indent); + int delta = indent - source.Indentation(line.Start); + bool isFirstCall = true; + var edits = new List(); + foreach (ExpressionSyntax link in links) + { + if (!IsCall(link)) continue; + bool keepsLine = isFirstCall && IsStaticReceiver(links[0]); + isFirstCall = false; + SyntaxToken lead = Lead(Dot(link)); + SyntaxToken previous = lead.GetPreviousToken(); + if (keepsLine || lead.SpanStart < line.Start || lead.SpanStart >= line.End || source.IsFirstOnLine(lead)) + { + continue; + } + if (!StyleLayout.IsBlank(source.content, previous.Span.End, lead.SpanStart)) continue; + edits.Add(new(previous.Span.End, lead.SpanStart, lineBreak)); + + // The lines of arguments that continue below keep their offset from the line the call now starts. + int closeLine = source.LineNumber(link.Parent!.Span.End); + for (int below = line.LineNumber + 1; below <= closeLine && delta != 0; below++) + { + StyleEdit? shift = StyleLayout.Shift(source, below, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + } + + if (edits.Count > 0) best = (top.Span, edits); + } + + return best; + } + + private static string Name(ExpressionSyntax link) + => link is MemberAccessExpressionSyntax access + ? access.Name.Identifier.Text + : ((MemberBindingExpressionSyntax)link).Name.Identifier.Text; + + // A type name, 'this' or 'base' in front of the first '.': the first call reads as one unit with it. + private static bool IsStaticReceiver(ExpressionSyntax first) + { + if (first is not MemberAccessExpressionSyntax access) return false; + return access.Expression switch + { + PredefinedTypeSyntax or ThisExpressionSyntax or BaseExpressionSyntax or GenericNameSyntax => true, + IdentifierNameSyntax name => char.IsUpper(name.Identifier.Text[0]), + _ => false + }; + } + + // The outermost expression of the chain a member access belongs to. + private static ExpressionSyntax Top(ExpressionSyntax expression) + { + while (true) + { + ExpressionSyntax? parent = expression.Parent switch + { + MemberAccessExpressionSyntax access when access.Expression == expression => access, + InvocationExpressionSyntax invocation when invocation.Expression == expression => invocation, + ElementAccessExpressionSyntax element when element.Expression == expression => element, + ConditionalAccessExpressionSyntax conditional => conditional, + PostfixUnaryExpressionSyntax postfix when postfix.IsKind(SyntaxKind.SuppressNullableWarningExpression) => postfix, + _ => null + }; + if (parent is null) return expression; + expression = parent; + } + } + + private static SyntaxToken Dot(ExpressionSyntax link) + => link is MemberAccessExpressionSyntax access ? access.OperatorToken : ((MemberBindingExpressionSyntax)link).OperatorToken; + + // The token that starts the link: the '?' of '?.', otherwise the '.' itself. + private static SyntaxToken Lead(SyntaxToken dot) + { + SyntaxToken previous = dot.GetPreviousToken(); + bool isConditional = previous.IsKind(SyntaxKind.QuestionToken) + && previous.Parent is ConditionalAccessExpressionSyntax + && previous.Span.End == dot.SpanStart; + return isConditional ? previous : dot; + } + + private static bool IsCall(ExpressionSyntax link) + => link.Parent is InvocationExpressionSyntax invocation && invocation.Expression == link; +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ClauseStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ClauseStyleRule.cs new file mode 100644 index 000000000..669553f9d --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ClauseStyleRule.cs @@ -0,0 +1,95 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// B-03 and T-06: after a single-line signature a constructor initializer or a 'where' clause starts the +// next line, indented four spaces. Further 'where' clauses each take a line aligned with the first, and +// the base list of a type stays on the line of the type name. +internal sealed class ClauseStyleRule : StyleRule +{ + private const string C_ID = "B-03"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((StyleEdit edit, string message) in Violations(source)) + { + findings.Add(source.Finding(C_ID, edit.end, message)); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + => Violations(source).Select(static violation => violation.edit).ToArray(); + + private static IEnumerable<(StyleEdit edit, string message)> Violations(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + SyntaxList constraints = node switch + { + MethodDeclarationSyntax method => method.ConstraintClauses, + LocalFunctionStatementSyntax local => local.ConstraintClauses, + DelegateDeclarationSyntax callback => callback.ConstraintClauses, + TypeDeclarationSyntax type => type.ConstraintClauses, + _ => default + }; + SyntaxToken first = node is ConstructorDeclarationSyntax { Initializer: { } initializer } + ? initializer.ColonToken + : constraints.Count > 0 ? constraints[0].WhereKeyword : default; + if (first.Span.Length == 0 || first.IsMissing) continue; + int declaration = source.Indentation(node.GetFirstToken().SpanStart); + SyntaxToken previous = first.GetPreviousToken(); + string clause = first.IsKind(SyntaxKind.ColonToken) ? "constructor initializer" : "'where' clause"; + bool follows = previous.IsKind(SyntaxKind.CloseParenToken) && StyleLayout.ClosesMultiLineHeader(source, previous); + if (StyleLayout.IsBlank(source.content, previous.Span.End, first.SpanStart)) + { + // After a multi-line parameter list the clause follows ')' (P-02); otherwise it starts a line. + string expected = "\n" + new string(' ', declaration + StyleLayout.C_INDENT); + if (!follows && source.content[previous.Span.End..first.SpanStart] != expected) + { + yield return (new( + previous.Span.End, + first.SpanStart, + expected + ), $"Start the {clause} on its own line, indented four spaces."); + continue; + } + } + + for (int index = 1; index < constraints.Count; index++) + { + SyntaxToken keyword = constraints[index].WhereKeyword; + SyntaxToken before = keyword.GetPreviousToken(); + if (!StyleLayout.IsBlank(source.content, before.Span.End, keyword.SpanStart)) continue; + string expected = "\n" + new string(' ', source.Column(first.SpanStart)); + if (source.content[before.Span.End..keyword.SpanStart] == expected) continue; + yield return (new( + before.Span.End, + keyword.SpanStart, + expected + ), "Put each 'where' clause on its own line, aligned with the first."); + } + } + + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (node is not BaseTypeDeclarationSyntax { BaseList: { } bases }) continue; + SyntaxToken previous = bases.ColonToken.GetPreviousToken(); + if (source.LineNumber(previous.Span.End) == source.LineNumber(bases.ColonToken.SpanStart)) continue; + if (!StyleLayout.IsBlank(source.content, previous.Span.End, bases.ColonToken.SpanStart)) continue; + if (StyleLayout.ClosesMultiLineHeader(source, previous)) continue; + int joined = source.Column(previous.Span.End) + 1 + source.Line(bases.ColonToken.SpanStart).End - bases.ColonToken.SpanStart; + if (joined > StyleLayout.C_HARD_WIDTH) continue; + yield return (new(previous.Span.End, bases.ColonToken.SpanStart, " "), "Keep the base list on the line of the type name."); + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/EmbeddedBraceStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/EmbeddedBraceStyleRule.cs new file mode 100644 index 000000000..874e2e5a2 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/EmbeddedBraceStyleRule.cs @@ -0,0 +1,96 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// B-05 and B-06: the body of a control statement is enclosed in braces. An 'if' without 'else' whose single +// statement fits on the line of its header may keep the compact one-line form. +internal sealed class EmbeddedBraceStyleRule : StyleRule +{ + private const string C_ID = "B-05"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((SyntaxNode _, StatementSyntax body) in Violations(source)) + { + findings.Add(source.Finding(C_ID, body.SpanStart, "Enclose the body of the control statement in braces.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + (SyntaxNode owner, StatementSyntax body)[] violations = Violations(source).ToArray(); + var edits = new List(); + foreach ((SyntaxNode owner, StatementSyntax body) in violations) + { + // Innermost bodies first: an outer body is braced once its content has settled. + if (violations.Any(other => other.body != body && body.Span.Contains(other.body.Span))) continue; + string indent = new(' ', source.Indentation(owner.GetFirstToken().SpanStart)); + SyntaxToken previous = body.GetFirstToken().GetPreviousToken(); + SyntaxToken last = body.GetLastToken(); + SyntaxToken next = last.GetNextToken(); + if (source.LineNumber(previous.SpanStart) == source.LineNumber(body.SpanStart)) + { + edits.Add(new(previous.Span.End, body.SpanStart, "\n" + indent + "{\n" + indent + new string(' ', StyleLayout.C_INDENT))); + } + else + { + int end = source.text.Lines[source.LineNumber(previous.Span.End)].End; + edits.Add(new(end, end, "\n" + indent + "{")); + } + + if (!next.IsKind(SyntaxKind.None) && source.LineNumber(next.SpanStart) == source.LineNumber(last.Span.End)) + { + edits.Add(new(last.Span.End, next.SpanStart, "\n" + indent + "}\n" + indent)); + } + else + { + int end = source.text.Lines[source.LineNumber(last.Span.End)].End; + edits.Add(new(end, end, "\n" + indent + "}")); + } + } + + return edits; + } + + private static IEnumerable<(SyntaxNode owner, StatementSyntax body)> Violations(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + StatementSyntax? body = node switch + { + IfStatementSyntax statement => statement.Statement, + ElseClauseSyntax clause when clause.Statement is not IfStatementSyntax => clause.Statement, + WhileStatementSyntax statement => statement.Statement, + DoStatementSyntax statement => statement.Statement, + ForStatementSyntax statement => statement.Statement, + CommonForEachStatementSyntax statement => statement.Statement, + LockStatementSyntax statement => statement.Statement, + // Stacked headers share the braced body of the innermost one. + UsingStatementSyntax statement when statement.Statement is not UsingStatementSyntax => statement.Statement, + FixedStatementSyntax statement when statement.Statement is not FixedStatementSyntax => statement.Statement, + _ => null + }; + if (body is null or BlockSyntax || body.IsMissing) continue; + if (node is IfStatementSyntax { Else: null } compact + && compact.Parent is not ElseClauseSyntax + && source.LineNumber(compact.SpanStart) == source.LineNumber(compact.Span.End) + && source.text.Lines[source.LineNumber(compact.SpanStart)].Span.Length <= StyleLayout.C_WIDTH + ) { + continue; + } + + yield return (node, body); + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/EmptyBodyStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/EmptyBodyStyleRule.cs new file mode 100644 index 000000000..d18c32a2e --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/EmptyBodyStyleRule.cs @@ -0,0 +1,103 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// B-07: an empty method, constructor, accessor, local function or lambda body is '{}' on the line where +// the header ends. +internal sealed class EmptyBodyStyleRule : StyleRule +{ + private const string C_ID = "B-07"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (StyleEdit edit in Fix(source)) + { + findings.Add(source.Finding(C_ID, edit.end - 1, "Write an empty body as '{}' on the line where the header ends.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (node is not BlockSyntax { Statements.Count: 0 } block || block.OpenBraceToken.IsMissing || block.CloseBraceToken.IsMissing) + { + continue; + } + if (block.Parent is not (BaseMethodDeclarationSyntax + or AccessorDeclarationSyntax + or LocalFunctionStatementSyntax + or AnonymousFunctionExpressionSyntax) + ) { + continue; + } + SyntaxToken previous = block.OpenBraceToken.GetPreviousToken(); + int start = previous.Span.End; + int end = block.CloseBraceToken.Span.End; + // A comment or a directive between the header and the closing brace keeps its layout. + if (!StyleLayout.IsBlank(source.content, start, block.OpenBraceToken.SpanStart)) continue; + if (!StyleLayout.IsBlank(source.content, block.OpenBraceToken.Span.End, block.CloseBraceToken.SpanStart)) + { + continue; + } + if (source.content[start..end] == " {}") continue; + edits.Add(new(start, end, " {}")); + } + + return edits; + } +} + +// B-07: an empty type ends with a semicolon and has no braces. +internal sealed class EmptyTypeStyleRule : StyleRule +{ + private const string C_ID = "B-07"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (StyleEdit edit in Fix(source)) + { + findings.Add(source.Finding(C_ID, edit.end - 1, "End an empty type with a semicolon instead of braces.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (node is not TypeDeclarationSyntax { Members.Count: 0 } type + || type.OpenBraceToken.Span.Length == 0 + || type.CloseBraceToken.IsMissing + ) { + continue; + } + SyntaxToken previous = type.OpenBraceToken.GetPreviousToken(); + if (!StyleLayout.IsBlank(source.content, previous.Span.End, type.OpenBraceToken.SpanStart)) continue; + if (!StyleLayout.IsBlank(source.content, type.OpenBraceToken.Span.End, type.CloseBraceToken.SpanStart)) + { + continue; + } + if (type.DescendantTrivia().Any(static trivia => trivia.IsDirective)) continue; + edits.Add(new(previous.Span.End, type.CloseBraceToken.Span.End, ";")); + } + + return edits; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/FileStructureStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/FileStructureStyleRule.cs new file mode 100644 index 000000000..1b0c1b71f --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/FileStructureStyleRule.cs @@ -0,0 +1,77 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// F-03: no leading blank line; one blank line separates the using directives from the file-scoped +// namespace, and the namespace from the types. +internal sealed class FileStructureStyleRule : StyleRule +{ + private const string C_ID = "F-03"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (StyleEdit edit in Fix(source)) + { + findings.Add( + source.Finding(C_ID, edit.start, "Use no leading blank line and exactly one blank line around the namespace declaration.") + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + int count = source.text.Lines.Count; + int leading = 0; + while (leading < count - 1 && StyleLines.IsBlank(source, leading)) + { + edits.Add(StyleLines.Remove(source, leading)); + leading++; + } + + if (source.root is not CompilationUnitSyntax unit) return edits; + foreach (MemberDeclarationSyntax member in unit.Members) + { + if (member is not FileScopedNamespaceDeclarationSyntax scope || scope.SemicolonToken.IsMissing) continue; + int first = source.LineNumber(scope.NamespaceKeyword.SpanStart); + int last = source.LineNumber(scope.SemicolonToken.SpanStart); + // A comment or an attribute directly above the namespace belongs to it. + while (first > leading && !StyleLines.IsBlank(source, first - 1) && StyleLines.FirstToken(source, first - 1).Span.Length == 0) + { + first--; + } + + if (first > leading) Separate(source, edits, first - 1, -1, leading); + if (last < count - 1 && !StyleLayout.IsBlank(source.content, source.text.Lines[last].End, source.content.Length)) + { + Separate(source, edits, last + 1, 1, count); + } + } + + return edits; + } + + // Leaves exactly one blank line in the run that starts at 'line' and extends in 'direction'. + private static void Separate( + StyleSource source, + List edits, + int line, + int direction, + int bound + ) { + int blank = 0; + for (int current = line; current != bound && StyleLines.IsBlank(source, current); current += direction) + { + if (++blank > 1) edits.Add(StyleLines.Remove(source, current)); + } + + if (blank == 0) edits.Add(StyleLines.InsertBefore(source, direction < 0 ? line + 1 : line)); + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/FileTextStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/FileTextStyleRule.cs new file mode 100644 index 000000000..01a0ffc3c --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/FileTextStyleRule.cs @@ -0,0 +1,144 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// F-01: LF line endings, four-space indentation without tabs, no trailing whitespace, +// exactly one final newline and at most one consecutive blank line. +internal sealed class FileTextStyleRule : StyleRule +{ + private const string C_ID = "F-01"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (Violation violation in Scan(source)) + { + findings.Add(source.Finding(C_ID, violation.start, violation.message)); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + => Scan(source) + .Where(static violation => violation.replacement is not null) + .Select(static violation => new StyleEdit(violation.start, violation.end, violation.replacement!)) + .ToArray(); + + private static List Scan(StyleSource source) + { + string content = source.content; + IReadOnlyList protectedSpans = source.ProtectedSpans(); + var violations = new List(); + if (content.Length > 0 && content[0] == '\uFEFF') + { + violations.Add(new(0, 1, "Remove the byte order mark.", "")); + } + + int blankRun = 0; + int position = content.Length > 0 && content[0] == '\uFEFF' ? 1 : 0; + while (position < content.Length) + { + int lineStart = position; + int lineEnd = content.IndexOf('\n', lineStart); + int next = lineEnd < 0 ? content.Length : lineEnd + 1; + if (lineEnd < 0) lineEnd = content.Length; + int textEnd = lineEnd; + if (textEnd > lineStart && content[textEnd - 1] == '\r') + { + textEnd--; + AddUnlessProtected(textEnd, textEnd + 1, "Use LF line endings.", ""); + } + + int indentEnd = lineStart; + while (indentEnd < textEnd && content[indentEnd] is ' ' or '\t') + { + indentEnd++; + } + + bool isBlank = indentEnd == textEnd; + if (isBlank) + { + blankRun++; + // The whole surplus line is removed, including its line break. + if (blankRun > 1 && next > lineStart) + { + AddUnlessProtected(lineStart, next, "Keep at most one consecutive blank line.", ""); + } + else if (textEnd > lineStart) + { + AddUnlessProtected(lineStart, textEnd, "Remove trailing whitespace.", ""); + } + } + else + { + blankRun = 0; + if (content.IndexOf('\t', lineStart, indentEnd - lineStart) >= 0) + { + string indentation = content[lineStart..indentEnd].Replace("\t", " "); + AddUnlessProtected(lineStart, indentEnd, "Indent with four spaces, not tabs.", indentation); + } + + int trimmedEnd = textEnd; + while (trimmedEnd > indentEnd && content[trimmedEnd - 1] is ' ' or '\t') + { + trimmedEnd--; + } + + if (trimmedEnd < textEnd) + { + AddUnlessProtected(trimmedEnd, textEnd, "Remove trailing whitespace.", ""); + } + } + + position = next; + } + + AddFinalNewline(); + return violations; + + void AddUnlessProtected( + int start, + int end, + string message, + string replacement + ) { + foreach (TextSpan span in protectedSpans) + { + if (start < span.End && end > span.Start) return; + } + + // A removed surplus blank line may contain trailing whitespace that was already reported. + if (violations.Count > 0 && violations[^1].end > start) return; + violations.Add(new(start, end, message, replacement)); + } + + void AddFinalNewline() + { + if (content.Length == 0) return; + int end = content.Length; + int trimmed = end; + while (trimmed > 0 && content[trimmed - 1] is '\n' or '\r' or ' ' or '\t') + { + trimmed--; + } + + if (content[trimmed..end] == "\n") return; + // Earlier edits may already cover part of the tail; replace the tail as one edit. + violations.RemoveAll(violation => violation.start >= trimmed); + violations.Add(new(trimmed, end, "End the file with exactly one newline.", "\n")); + } + } + + private sealed record Violation( + int start, + int end, + string message, + string? replacement + ); +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/HeaderCloseStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/HeaderCloseStyleRule.cs new file mode 100644 index 000000000..d68dfdb26 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/HeaderCloseStyleRule.cs @@ -0,0 +1,77 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// W-05: the closing parenthesis of a control statement header that spans several lines starts its own line, +// aligned with the keyword, and the opening brace follows it: ') {'. +internal sealed class HeaderCloseStyleRule : StyleRule +{ + private const string C_ID = "W-05"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (StyleEdit edit in Fix(source)) + { + findings.Add( + source.Finding(C_ID, edit.end, "Close a multi-line statement header with ') {' on its own line, aligned with the keyword.") + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (StyleLayout.Header(node) is not { } header || header.open.IsMissing || header.close.IsMissing) continue; + if (source.LineNumber(header.open.SpanStart) == source.LineNumber(header.close.SpanStart)) continue; + SyntaxToken brace = header.close.GetNextToken(); + // A body without braces is given its braces first (B-05). + if (!brace.IsKind(SyntaxKind.OpenBraceToken)) continue; + int indentation = source.Indentation(node.GetFirstToken().SpanStart); + if (!ClosesLine(source, header.close, indentation)) + { + int start = header.close.SpanStart; + while (start > 0 && source.content[start - 1] == ' ') + { + start--; + } + + edits.Add(new(start, header.close.SpanStart, "\n" + new string(' ', indentation))); + } + + string gap = source.content[header.close.Span.End..brace.SpanStart]; + if (gap != " " && StyleLayout.IsBlank(gap, 0, gap.Length)) + { + edits.Add(new(header.close.Span.End, brace.SpanStart, " ")); + } + } + + return edits; + } + + // Whether only closing delimiters precede the parenthesis on a line that is aligned with the keyword. + private static bool ClosesLine( + StyleSource source, + SyntaxToken close, + int indentation + ) { + if (source.Indentation(close.SpanStart) != indentation) return false; + int lineStart = source.text.Lines[source.LineNumber(close.SpanStart)].Start; + for (int index = lineStart + indentation; index < close.SpanStart; index++) + { + if (source.content[index] is not (')' or ']' or '}')) return false; + } + + return true; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/LambdaBodyStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/LambdaBodyStyleRule.cs new file mode 100644 index 000000000..0f2910b28 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/LambdaBodyStyleRule.cs @@ -0,0 +1,90 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// B-04: an operator or conditional expression body of a lambda that does not fit on the line of the lambda is +// wrapped in parentheses: '(' follows '=>', the expression is indented four spaces and ')' is on its own line. +internal sealed class LambdaBodyStyleRule : StyleRule +{ + private const string C_ID = "B-04"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (LambdaExpressionSyntax lambda in Violations(source)) + { + findings.Add( + source.Finding( + C_ID, + lambda.ArrowToken.SpanStart, + "Wrap the lambda body in parentheses: it does not fit on the line of the lambda." + ) + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + LambdaExpressionSyntax[] violations = Violations(source).ToArray(); + var edits = new List(); + foreach (LambdaExpressionSyntax lambda in violations) + { + // Innermost lambdas first: an outer body is wrapped once its content has settled. + if (violations.Any(other => other != lambda && lambda.Span.Contains(other.Span))) continue; + ExpressionSyntax body = lambda.ExpressionBody!; + SyntaxToken arrow = lambda.ArrowToken; + SyntaxToken first = body.GetFirstToken(); + SyntaxToken last = body.GetLastToken(); + if (!StyleLayout.IsBlank(source.content, arrow.Span.End, first.SpanStart)) continue; + int firstLine = source.LineNumber(first.SpanStart); + int lastLine = source.LineNumber(last.Span.End); + if (protectedSpans.Any(span => span.Start < last.Span.End && span.End > first.SpanStart)) continue; + int indentation = source.Indentation(arrow.SpanStart); + int inner = indentation + StyleLayout.C_INDENT; + int column = source.Column(first.SpanStart); + bool isSameLine = source.LineNumber(arrow.SpanStart) == firstLine; + edits.Add(new(arrow.Span.End, first.SpanStart, " (\n" + new string(' ', inner))); + for (int line = firstLine + 1; line <= lastLine; line++) + { + // A line aligned with the body follows it; a line indented from its statement moves one level. + int current = source.Indentation(source.text.Lines[line].Start); + int delta = isSameLine && current < column ? StyleLayout.C_INDENT : inner - column; + StyleEdit? shift = StyleLayout.Shift(source, line, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + + edits.Add(new(last.Span.End, last.Span.End, "\n" + new string(' ', indentation) + ")")); + } + + return edits; + } + + private static IEnumerable Violations(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (node is not LambdaExpressionSyntax { ExpressionBody: { } body } lambda) continue; + if (body is not (BinaryExpressionSyntax or IsPatternExpressionSyntax or ConditionalExpressionSyntax)) + { + continue; + } + if (StyleLayout.IsInInterpolation(lambda)) continue; + int arrowLine = source.LineNumber(lambda.ArrowToken.SpanStart); + if (arrowLine == source.LineNumber(body.SpanStart) && arrowLine == source.LineNumber(body.Span.End)) + { + continue; + } + yield return lambda; + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/LeadingOperatorStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/LeadingOperatorStyleRule.cs new file mode 100644 index 000000000..73041a257 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/LeadingOperatorStyleRule.cs @@ -0,0 +1,65 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// W-01 and W-02: when an expression breaks at an operator, the operator starts the continuation line. +internal sealed class LeadingOperatorStyleRule : StyleRule +{ + private const string C_ID = "W-01"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (StyleEdit edit in Fix(source)) + { + findings.Add( + source.Finding(C_ID, edit.start, "Start each continuation line of the broken expression with its operator.") + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + var seen = new HashSet(); + foreach ((SyntaxNode chain, SyntaxToken anchor, IReadOnlyList operators) in StyleOperators.Chains(source.root)) + { + // W-02: a conditional expression that breaks before its ':' starts a line with '?' and with ':'. + if (chain is ConditionalExpressionSyntax conditional + && source.LineNumber(conditional.Condition.Span.End) != source.LineNumber(conditional.ColonToken.SpanStart) + ) { + string lineBreak = "\n" + new string(' ', source.Column(anchor.SpanStart)); + foreach (SyntaxToken token in operators) + { + SyntaxToken before = token.GetPreviousToken(); + if (source.IsFirstOnLine(token) || source.IsLastOnLine(token)) continue; + if (!StyleLayout.IsBlank(source.content, before.Span.End, token.SpanStart) || !seen.Add(token.SpanStart)) + { + continue; + } + edits.Add(new(before.Span.End, token.SpanStart, lineBreak)); + } + } + + foreach (SyntaxToken token in operators) + { + SyntaxToken previous = token.GetPreviousToken(); + SyntaxToken next = token.GetNextToken(); + if (source.LineNumber(token.SpanStart) == source.LineNumber(next.SpanStart)) continue; + if (source.LineNumber(token.SpanStart) != source.LineNumber(previous.Span.End)) continue; + string gap = source.content[token.Span.End..next.SpanStart]; + if (!StyleLayout.IsBlank(gap, 0, gap.Length) || !seen.Add(token.SpanStart)) continue; + edits.Add(new(previous.Span.End, next.SpanStart, gap + token.Text + " ")); + } + } + + return edits; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/LineWidthStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/LineWidthStyleRule.cs new file mode 100644 index 000000000..435355d60 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/LineWidthStyleRule.cs @@ -0,0 +1,283 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// F-04: no line passes the hard limit, except for an unsplittable string literal. A line that does is +// broken at its outermost argument list (A-02). +internal sealed class LineWidthStyleRule : StyleRule +{ + private const string C_ID = "F-04"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((TextLine line, StyleList? _) in Violations(source)) + { + findings.Add( + source.Finding( + C_ID, + line.Start + StyleLayout.C_HARD_WIDTH, + $"Break the line: it is longer than {StyleLayout.C_HARD_WIDTH} columns." + ) + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + var edits = new List(); + int fixedEnd = -1; + foreach ((TextLine line, StyleList? list) in Violations(source)) + { + // A line that an earlier fix of this round reaches waits for the next round. + if (line.Start < fixedEnd) continue; + if (HasCompactBody(source, line)) continue; + (TextSpan span, List edits)? calls = ChainStyleRule.BreakOnLine(source, line); + if (calls is { } chain && list is not null && list.open.SpanStart < chain.span.Start && list.close.SpanStart >= chain.span.End) + { + calls = null; + } + + List? lineEdits = WrapArrow(source, line) ?? BreakOperators(source, line, list, calls?.span) ?? calls?.edits; + if (lineEdits is null && list is not null) lineEdits = StyleLayout.Expand(source, list, protectedSpans); + lineEdits ??= ExpandParameter(source, line, protectedSpans); + if (lineEdits is null || lineEdits.Count == 0) continue; + edits.AddRange(lineEdits); + fixedEnd = lineEdits.Max(static edit => edit.end); + } + + return edits; + } + + // B-05: an over-long line that holds a control statement and its body is first split by the braces of the body. + private static bool HasCompactBody( + StyleSource source, + TextLine line + ) { + foreach (SyntaxNode node in source.root.DescendantNodes(TextSpan.FromBounds(line.Start, line.End))) + { + if (node is not StatementSyntax statement || node is BlockSyntax) continue; + if (statement.Parent is not (StatementSyntax or ElseClauseSyntax) || statement.Parent is BlockSyntax) + { + continue; + } + if (statement.Parent is ElseClauseSyntax && statement is IfStatementSyntax) continue; + if (statement.Parent is LabeledStatementSyntax or LocalFunctionStatementSyntax) continue; + SyntaxToken first = statement.GetFirstToken(); + if (first.SpanStart >= line.Start && first.SpanStart < line.End && !source.IsFirstOnLine(first)) + { + return true; + } + } + + return false; + } + + // P-01 keeps a single parameter on one line; when nothing else can shorten the line, the list expands. + private static List? ExpandParameter( + StyleSource source, + TextLine line, + IReadOnlyList protectedSpans + ) { + foreach (SyntaxNode node in source.root.DescendantNodes(TextSpan.FromBounds(line.Start, line.End))) + { + if (node is not ParameterListSyntax { Parameters.Count: 1 } parameters || node.Parent is LambdaExpressionSyntax) + { + continue; + } + if (parameters.SpanStart < line.Start || parameters.Span.End > line.End) continue; + var list = new StyleList(parameters.OpenParenToken, parameters.CloseParenToken, parameters.Parameters.ToArray()); + return StyleLayout.Expand(source, list, protectedSpans); + } + + return null; + } + + // M-03: a member whose signature and expression body share an over-long line moves '=>' to the next line. + private static List? WrapArrow( + StyleSource source, + TextLine line + ) { + foreach (SyntaxNode node in source.root.DescendantNodes(TextSpan.FromBounds(line.Start, line.End))) + { + if (node is not ArrowExpressionClauseSyntax clause || clause.Parent is null) continue; + SyntaxToken arrow = clause.ArrowToken; + SyntaxToken previous = arrow.GetPreviousToken(); + if (source.LineNumber(arrow.SpanStart) != line.LineNumber || source.IsFirstOnLine(arrow)) continue; + if (source.LineNumber(clause.Parent.GetFirstToken().SpanStart) != line.LineNumber) continue; + if (!StyleLayout.IsBlank(source.content, previous.Span.End, arrow.SpanStart)) continue; + int indentation = source.Indentation(line.Start) + StyleLayout.C_INDENT; + return [new(previous.Span.End, arrow.SpanStart, "\n" + new string(' ', indentation))]; + } + + return null; + } + + // W-01: the outermost operator chain of an over-long line breaks before each of its operators, unless + // an argument list encloses it. + private static List? BreakOperators( + StyleSource source, + TextLine line, + StyleList? list, + TextSpan? calls + ) { + (SyntaxNode chain, SyntaxToken anchor, IReadOnlyList operators)? best = null; + (SyntaxNode chain, SyntaxToken anchor, IReadOnlyList operators)? outer = null; + foreach ((SyntaxNode chain, SyntaxToken anchor, IReadOnlyList operators) candidate in StyleOperators.Chains( + source.root + )) { + SyntaxNode chain = candidate.chain; + if (StyleLayout.IsInInterpolation(chain)) continue; + if (chain.SpanStart >= line.Start && chain.Span.End <= line.End) + { + if (best is not { } current || chain.Span.Length > current.chain.Span.Length) best = candidate; + } + else if (candidate.operators.Any(token => IsInside(source, line, token))) + { + if (outer is not { } current || chain.Span.Length > current.chain.Span.Length) outer = candidate; + } + } + + // A chain that is already broken puts every operator of the over-long line at the start of a line. + if (outer is { } broken && (best is not { } inner || broken.chain.Span.Contains(inner.chain.Span))) + { + // A call chain around the broken operators breaks first. + if (calls is { } around && around.Contains(broken.chain.Span) && around != broken.chain.Span) return null; + int column = source.LineNumber(broken.anchor.SpanStart) == line.LineNumber + ? source.Column(broken.anchor.SpanStart) + : source.Indentation(line.Start); + return Break(source, broken.operators.Where(token => IsInside(source, line, token)).ToArray(), column); + } + + if (best is not { } found) return null; + // An operator inside an argument of a call chain waits until the chain itself is broken. + if (calls is { } span && span.Contains(found.chain.Span) && span != found.chain.Span) return null; + if (list is not null) + { + bool isOperand = StyleOperators.IsComparison(found.chain) && found.chain.Span.Contains(list.open.Span); + if (isOperand || IsEnclosed(source, line, found.chain)) return null; + } + + return Break(source, found.operators, source.Column(found.anchor.SpanStart)); + } + + // True when an argument list or a brace list on the line contains the node: that list breaks first. + private static bool IsEnclosed( + StyleSource source, + TextLine line, + SyntaxNode node + ) { + foreach (SyntaxNode ancestor in node.Ancestors()) + { + if (ancestor is StatementSyntax or MemberDeclarationSyntax) return false; + StyleList? list = StyleList.Arguments(ancestor) ?? StyleList.Braces(ancestor); + if (list is null || list.open.SpanStart > node.SpanStart || list.close.SpanStart < node.Span.End) continue; + if (list.open.SpanStart >= line.Start && list.close.SpanStart <= line.End) return true; + } + + return false; + } + + private static bool IsInside( + StyleSource source, + TextLine line, + SyntaxToken token + ) => token.SpanStart >= line.Start && token.SpanStart < line.End && !source.IsFirstOnLine(token); + + private static List? Break( + StyleSource source, + IReadOnlyList operators, + int column + ) { + string lineBreak = "\n" + new string(' ', column); + var edits = new List(); + foreach (SyntaxToken token in operators) + { + SyntaxToken previous = token.GetPreviousToken(); + if (!StyleLayout.IsBlank(source.content, previous.Span.End, token.SpanStart)) return null; + edits.Add(new(previous.Span.End, token.SpanStart, lineBreak)); + } + + return edits.Count == 0 ? null : edits; + } + + // Each over-long line, with the argument list that breaks it or null when the line has none. + private static IEnumerable<(TextLine line, StyleList? list)> Violations(StyleSource source) + { + Dictionary lists = []; + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + StyleList? list = StyleList.Arguments(node) ?? StyleList.Braces(node); + if (list is null || (list.items.Count == 1 && node is CollectionExpressionSyntax)) continue; + if (StyleLayout.IsInInterpolation(node)) continue; + int line = source.LineNumber(list.open.SpanStart); + if (line != source.LineNumber(list.close.SpanStart)) continue; + // Only an outermost list is broken; among those, the longest one. + if (lists.TryGetValue(line, out StyleList? current)) + { + if (list.open.SpanStart < current.close.SpanStart) continue; + if (list.close.SpanStart - list.open.SpanStart <= current.close.SpanStart - current.open.SpanStart) + { + continue; + } + } + + lists[line] = list; + } + + IReadOnlyList protectedSpans = source.ProtectedSpans(); + foreach (TextLine line in source.text.Lines) + { + if (line.End - line.Start <= StyleLayout.C_HARD_WIDTH) continue; + if (protectedSpans.Any(span => span.Start < line.Start && span.End > line.Start)) continue; + lists.TryGetValue(line.LineNumber, out StyleList? list); + if (list is null && IsUnsplittable(source, line) && WrapArrow(source, line) is null) continue; + yield return (line, list); + } + } + + // True when the line fits without its longest literal or comment, which cannot be broken. + private static bool IsUnsplittable( + StyleSource source, + TextLine line + ) { + int longest = 0; + for (int position = line.Start; position < line.End;) + { + SyntaxTrivia trivia = source.root.FindTrivia(position); + if (trivia.Span.Length > 0 && !trivia.IsKind(SyntaxKind.WhitespaceTrivia)) + { + longest = System.Math.Max(longest, System.Math.Min(trivia.Span.End, line.End) - position); + position = trivia.Span.End; + continue; + } + + SyntaxToken token = source.root.FindToken(position); + if (token.Span.Length == 0 || token.SpanStart < position) + { + position++; + continue; + } + + SyntaxNode? literal = token.Parent?.AncestorsAndSelf().FirstOrDefault( + static node => node is InterpolatedStringExpressionSyntax or LiteralExpressionSyntax + ); + int end = literal is null ? token.Span.End : literal.Span.End; + if (literal is not null) longest = System.Math.Max(longest, System.Math.Min(end, line.End) - position); + position = System.Math.Max(end, position + 1); + } + + return line.End - line.Start - longest <= StyleLayout.C_HARD_WIDTH - 20; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/MemberSpacingStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/MemberSpacingStyleRule.cs new file mode 100644 index 000000000..b2319d7c9 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/MemberSpacingStyleRule.cs @@ -0,0 +1,87 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// S-03: types, methods, constructors, documented members and multi-line members are separated by one blank +// line. Enum members are never separated by blank lines. +internal sealed class MemberSpacingStyleRule : StyleRule +{ + private const string C_ID = "S-03"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((StyleEdit edit, string message) in Violations(source)) + { + findings.Add(source.Finding(C_ID, edit.start, message)); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + => Violations(source).Select(static violation => violation.edit).ToArray(); + + private static IEnumerable<(StyleEdit edit, string message)> Violations(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodesAndSelf()) + { + IReadOnlyList members = node switch + { + CompilationUnitSyntax unit => unit.Members, + BaseNamespaceDeclarationSyntax scope => scope.Members, + TypeDeclarationSyntax type => type.Members, + EnumDeclarationSyntax declaration => declaration.Members, + _ => [] + }; + for (int index = 1; index < members.Count; index++) + { + SyntaxNode previous = members[index - 1]; + SyntaxNode current = members[index]; + if (previous is BaseNamespaceDeclarationSyntax) continue; + int end = source.LineNumber(previous.Span.End); + int start = source.LineNumber(current.SpanStart); + if (start <= end) continue; + int next = end + 1; + while (next < start && StyleLines.IsBlank(source, next)) + { + next++; + } + + if (node is EnumDeclarationSyntax) + { + for (int line = end + 1; line < next; line++) + { + yield return (StyleLines.Remove(source, line), "Do not separate enum members with blank lines."); + } + + continue; + } + + if (next > end + 1 || !(IsSeparated(source, previous) || IsSeparated(source, current))) continue; + // A preprocessor directive between two members keeps its position. + if (current.GetLeadingTrivia().Any(static trivia => trivia.IsDirective)) continue; + yield return (StyleLines.InsertBefore(source, next), "Separate these members with one blank line."); + } + } + } + + private static bool IsSeparated( + StyleSource source, + SyntaxNode member + ) => member is BaseMethodDeclarationSyntax or BaseTypeDeclarationSyntax or DelegateDeclarationSyntax + || source.LineNumber(member.SpanStart) != source.LineNumber(member.Span.End) + || member.GetLeadingTrivia().Any( + static trivia => ( + trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia) + || trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia) + ) + ); +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/OperatorAlignmentStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/OperatorAlignmentStyleRule.cs new file mode 100644 index 000000000..02d0ff4f0 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/OperatorAlignmentStyleRule.cs @@ -0,0 +1,104 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// F-05: a continuation line that begins with an operator aligns with the first operand of its expression. +// When alignment would pass the hard line limit, the lines are indented four spaces from the statement. +internal sealed class OperatorAlignmentStyleRule : StyleRule +{ + private const string C_ID = "F-05"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((int position, List _) in Violations(source)) + { + findings.Add(source.Finding(C_ID, position, "Align the operator continuation lines with the first operand.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + int fixedEnd = -1; + foreach ((int position, List chainEdits) in Violations(source)) + { + // A chain nested in the lines of a fixed chain waits for the next round. + if (position < fixedEnd) continue; + edits.AddRange(chainEdits); + fixedEnd = chainEdits.Max(static edit => edit.end); + } + + return edits; + } + + private static IEnumerable<(int position, List edits)> Violations(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + foreach ((SyntaxNode chain, SyntaxToken anchor, IReadOnlyList operators) in StyleOperators.Chains(source.root).OrderBy( + static entry => entry.chain.SpanStart + )) { + int[] lines = operators + .Where(token => source.IsFirstOnLine(token) && source.LineNumber(token.SpanStart) > source.LineNumber(anchor.SpanStart)) + .Select(token => source.LineNumber(token.SpanStart)) + .Distinct() + .Order() + .ToArray(); + if (lines.Length == 0) continue; + int lastLine = source.LineNumber(chain.Span.End); + int aligned = source.Column(anchor.SpanStart); + int target = aligned; + if (Overflows(source, lines, lastLine, aligned)) + { + SyntaxNode? owner = chain.AncestorsAndSelf().FirstOrDefault( + static node => node is StatementSyntax or MemberDeclarationSyntax + ); + if (owner is null) continue; + target = source.Indentation(owner.GetFirstToken().SpanStart) + StyleLayout.C_INDENT; + } + + var edits = new List(); + for (int index = 0; index < lines.Length; index++) + { + int delta = target - source.Indentation(source.text.Lines[lines[index]].Start); + int end = index + 1 < lines.Length ? lines[index + 1] - 1 : lastLine; + for (int line = lines[index]; line <= end && delta != 0; line++) + { + StyleEdit? shift = StyleLayout.Shift(source, line, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + } + + if (edits.Count > 0) yield return (source.text.Lines[lines[0]].Start, edits); + } + } + + private static bool Overflows( + StyleSource source, + int[] lines, + int lastLine, + int target + ) { + for (int index = 0; index < lines.Length; index++) + { + int delta = target - source.Indentation(source.text.Lines[lines[index]].Start); + int end = index + 1 < lines.Length ? lines[index + 1] - 1 : lastLine; + for (int line = lines[index]; line <= end; line++) + { + TextLine textLine = source.text.Lines[line]; + if (textLine.End - textLine.Start + delta > StyleLayout.C_HARD_WIDTH) return true; + } + } + + return false; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ParameterCloseStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ParameterCloseStyleRule.cs new file mode 100644 index 000000000..4d24ae5b5 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ParameterCloseStyleRule.cs @@ -0,0 +1,96 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// P-02: the body, expression body, constructor initializer, base list or 'where' clause that follows the +// closing parenthesis of a multi-line parameter list starts on the line of that parenthesis. +internal sealed class ParameterCloseStyleRule : StyleRule +{ + private const string C_ID = "P-02"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((SyntaxToken close, SyntaxToken next, string _) in Violations(source)) + { + findings.Add( + source.Finding(C_ID, close.SpanStart, $"Write '{next.Text}' on the line of the closing parenthesis of the parameter list.") + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + var edits = new List(); + foreach ((SyntaxToken close, SyntaxToken next, string gap) in Violations(source)) + { + edits.Add(new(close.Span.End, next.SpanStart, gap)); + // What moved up keeps its own continuation lines relative to the declaration. + int delta = source.Indentation(close.SpanStart) - source.Indentation(next.SpanStart); + if (delta == 0 || next.IsKind(SyntaxKind.OpenBraceToken) || next.IsKind(SyntaxKind.SemicolonToken)) + { + continue; + } + SyntaxNode moved = next.Parent!; + int first = source.LineNumber(next.SpanStart) + 1; + int last = source.LineNumber(moved.Span.End); + for (int line = first; line <= last; line++) + { + StyleEdit? shift = StyleLayout.Shift(source, line, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + } + + return edits; + } + + private static IEnumerable<(SyntaxToken close, SyntaxToken next, string gap)> Violations(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (node is not ParameterListSyntax parameters || parameters.CloseParenToken.IsMissing) continue; + SyntaxToken close = parameters.CloseParenToken; + if (source.LineNumber(parameters.OpenParenToken.SpanStart) == source.LineNumber(close.SpanStart)) continue; + if (!source.IsFirstOnLine(close)) continue; + SyntaxToken next = close.GetNextToken(); + string? gap = Gap(parameters, next); + if (gap is null) continue; + string actual = source.content[close.Span.End..next.SpanStart]; + if (actual == gap || !StyleLayout.IsBlank(actual, 0, actual.Length)) continue; + yield return (close, next, gap); + } + } + + // The text required between the closing parenthesis and the token that follows it, or null when this rule does not own it. + private static string? Gap( + ParameterListSyntax parameters, + SyntaxToken next + ) { + SyntaxNode owner = parameters.Parent!; + switch (next.Kind()) + { + case SyntaxKind.SemicolonToken: + return ""; + case SyntaxKind.EqualsGreaterThanToken: + case SyntaxKind.WhereKeyword: + return " "; + case SyntaxKind.ColonToken: + return next.Parent is ConstructorInitializerSyntax or BaseListSyntax ? " " : null; + case SyntaxKind.OpenBraceToken: + // A lambda block keeps the brace on its own line (B-04). + return owner is BaseMethodDeclarationSyntax or LocalFunctionStatementSyntax or TypeDeclarationSyntax ? " " : null; + default: + return null; + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ParameterListStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ParameterListStyleRule.cs new file mode 100644 index 000000000..d709ad89a --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ParameterListStyleRule.cs @@ -0,0 +1,84 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// P-01: a parameter list with two or more parameters is fully expanded; one with fewer stays on one line. +internal sealed class ParameterListStyleRule : StyleRule +{ + private const string C_ID = "P-01"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((StyleList list, bool expand) in Violations(source)) + { + string message = expand + ? "Expand the parameter list: one parameter per line and ')' on its own line." + : "Keep a parameter list with fewer than two parameters on one line."; + findings.Add(source.Finding(C_ID, list.open.SpanStart, message)); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + var edits = new List(); + var spans = new List(); + foreach ((StyleList list, bool expand) in Violations(source).OrderBy(static entry => entry.list.open.SpanStart)) + { + // Nested lists are fixed in a later round, after their container has settled. + TextSpan span = TextSpan.FromBounds(list.open.SpanStart, list.close.Span.End); + if (spans.Any(outer => outer.Contains(span))) continue; + if (expand) + { + List? listEdits = StyleLayout.Expand(source, list, protectedSpans); + if (listEdits is null) continue; + edits.AddRange(listEdits); + } + else + { + string? joined = StyleLayout.Join(source, list.open, list.close); + if (joined is null) continue; + edits.Add(new(span.Start, span.End, joined)); + } + + spans.Add(span); + } + + return edits; + } + + private static IEnumerable<(StyleList list, bool expand)> Violations(StyleSource source) + { + foreach (ParameterListSyntax parameters in source.root.DescendantNodes().OfType()) + { + if (parameters.OpenParenToken.IsMissing || parameters.CloseParenToken.IsMissing) continue; + var list = new StyleList(parameters.OpenParenToken, parameters.CloseParenToken, parameters.Parameters.ToArray()); + bool multiLine = source.LineNumber(list.open.SpanStart) != source.LineNumber(list.close.SpanStart); + if (list.items.Count >= 2) + { + if (!StyleLayout.IsExpanded(source, list)) yield return (list, true); + } + else if (multiLine) + { + // The hard line limit (F-04) outranks the one-line form of a single parameter. + string? joined = StyleLayout.Join(source, list.open, list.close); + int tail = source.Line(list.close.SpanStart).End - list.close.Span.End; + if (joined is null || source.Column(list.open.SpanStart) + joined.Length + tail > StyleLayout.C_HARD_WIDTH) + { + continue; + } + yield return (list, false); + } + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/SingleLineBlockStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/SingleLineBlockStyleRule.cs new file mode 100644 index 000000000..fcb5db588 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/SingleLineBlockStyleRule.cs @@ -0,0 +1,93 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// B-09 and M-01: a block that holds statements is never squeezed onto one line, and a property whose +// accessors have bodies is expanded with one accessor per line. +internal sealed class SingleLineBlockStyleRule : StyleRule +{ + private const string C_ID = "B-09"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((SyntaxToken open, List _) in Violations(source)) + { + findings.Add(source.Finding(C_ID, open.SpanStart, "Expand the braces: a body with content is not written on one line.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + int fixedEnd = -1; + foreach ((SyntaxToken open, List blockEdits) in Violations(source)) + { + // A block nested in an expanded block waits for the next round. + if (open.SpanStart < fixedEnd) continue; + edits.AddRange(blockEdits); + fixedEnd = blockEdits.Max(static edit => edit.end); + } + + return edits; + } + + private static IEnumerable<(SyntaxToken open, List edits)> Violations(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + SyntaxToken open; + SyntaxToken close; + IReadOnlyList items; + switch (node) + { + case BlockSyntax { Statements.Count: > 0 } block: + (open, close, items) = (block.OpenBraceToken, block.CloseBraceToken, block.Statements); + break; + case AccessorListSyntax accessors when accessors.Accessors.Any( + static accessor => accessor.Body is not null || accessor.ExpressionBody is not null + ): + (open, close, items) = (accessors.OpenBraceToken, accessors.CloseBraceToken, accessors.Accessors); + break; + default: + continue; + } + + if (open.IsMissing || close.IsMissing || source.LineNumber(open.SpanStart) != source.LineNumber(close.SpanStart)) + { + continue; + } + SyntaxToken previous = open.GetPreviousToken(); + int indentation = source.Indentation(open.SpanStart); + string outer = "\n" + new string(' ', indentation); + string inner = "\n" + new string(' ', indentation + StyleLayout.C_INDENT); + var edits = new List(); + if (!source.IsFirstOnLine(open) && !StyleLayout.ClosesMultiLineHeader(source, previous)) + { + if (!StyleLayout.IsBlank(source.content, previous.Span.End, open.SpanStart)) continue; + edits.Add(new(previous.Span.End, open.SpanStart, outer)); + } + + int position = open.Span.End; + bool isPlain = true; + foreach (SyntaxNode item in items) + { + isPlain &= StyleLayout.IsBlank(source.content, position, item.SpanStart); + edits.Add(new(position, item.SpanStart, inner)); + position = item.Span.End; + } + + if (!isPlain || !StyleLayout.IsBlank(source.content, position, close.SpanStart)) continue; + edits.Add(new(position, close.SpanStart, outer)); + yield return (open, edits); + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/TrailingCommaStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/TrailingCommaStyleRule.cs new file mode 100644 index 000000000..8e12f6974 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/TrailingCommaStyleRule.cs @@ -0,0 +1,58 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// I-05: the last item of an initializer, a collection, an enum, a switch expression or an anonymous object +// is not followed by a comma. +internal sealed class TrailingCommaStyleRule : StyleRule +{ + private const string C_ID = "I-05"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (SyntaxToken comma in TrailingCommas(source.root)) + { + findings.Add(source.Finding(C_ID, comma.SpanStart, "Remove the comma after the last item.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + foreach (SyntaxToken comma in TrailingCommas(source.root)) + { + edits.Add(new(comma.SpanStart, comma.Span.End, "")); + } + + return edits; + } + + private static IEnumerable TrailingCommas(SyntaxNode root) + { + foreach (SyntaxNode node in root.DescendantNodes()) + { + SyntaxToken comma = node switch + { + InitializerExpressionSyntax initializer => Trailing(initializer.Expressions), + AnonymousObjectCreationExpressionSyntax anonymous => Trailing(anonymous.Initializers), + CollectionExpressionSyntax collection => Trailing(collection.Elements), + EnumDeclarationSyntax declaration => Trailing(declaration.Members), + SwitchExpressionSyntax expression => Trailing(expression.Arms), + _ => default + }; + if (comma.Span.Length > 0) yield return comma; + } + } + + private static SyntaxToken Trailing(SeparatedSyntaxList list) + where TNode : SyntaxNode + => list.Count > 0 && list.SeparatorCount == list.Count ? list.GetSeparator(list.Count - 1) : default; +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/UsingOrderStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/UsingOrderStyleRule.cs new file mode 100644 index 000000000..030819361 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/UsingOrderStyleRule.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// N-04: namespace usings, static usings and aliases form three groups separated by one blank line. Inside a +// group, System comes first, then other namespaces, then Inno, each tier in ordinal order. +internal sealed class UsingOrderStyleRule : StyleRule +{ + private const string C_ID = "N-04"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Reorder; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + if (Expected(source) is { } expected) + { + findings.Add( + source.Finding( + C_ID, + expected.start, + "Order the using directives: namespaces, static usings, aliases; System, others, Inno." + ) + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + => Expected(source) is { } expected ? [new(expected.start, expected.end, expected.text)] : []; + + // The span of the using block and the text it must have, or null when the block is already in order + // or holds comments or directives that an automatic reorder could misplace. + private static (int start, int end, string text)? Expected(StyleSource source) + { + if (source.root is not CompilationUnitSyntax unit || unit.Usings.Count == 0) return null; + UsingDirectiveSyntax[] usings = unit.Usings.ToArray(); + if (usings.Any(static directive => !directive.GlobalKeyword.IsKind(SyntaxKind.None))) return null; + int start = usings[0].SpanStart; + int end = usings[^1].Span.End; + for (int index = 1; index < usings.Length; index++) + { + if (!StyleLayout.IsBlank(source.content, usings[index - 1].Span.End, usings[index].SpanStart)) return null; + } + + var lines = new List(); + int previousGroup = -1; + foreach (UsingDirectiveSyntax directive in usings.OrderBy(Group).ThenBy(Tier).ThenBy(Key, StringComparer.Ordinal)) + { + int group = Group(directive); + if (previousGroup >= 0 && group != previousGroup) lines.Add(""); + lines.Add(source.content[directive.SpanStart..directive.Span.End]); + previousGroup = group; + } + + string text = string.Join('\n', lines); + return text == source.content[start..end] ? null : (start, end, text); + } + + private static int Group(UsingDirectiveSyntax directive) + => directive.Alias is not null ? 2 : directive.StaticKeyword.IsKind(SyntaxKind.None) ? 0 : 1; + + private static int Tier(UsingDirectiveSyntax directive) + { + if (directive.Alias is not null) return 0; + string name = directive.NamespaceOrType.ToString(); + if (name == "System" || name.StartsWith("System.", StringComparison.Ordinal)) return 0; + return name == "Inno" || name.StartsWith("Inno.", StringComparison.Ordinal) ? 2 : 1; + } + + private static string Key(UsingDirectiveSyntax directive) + => directive.Alias is not null ? directive.Alias.Name.Identifier.Text : directive.NamespaceOrType.ToString(); +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleCommand.cs b/tools/Inno.Tooling.Architecture/Style/StyleCommand.cs new file mode 100644 index 000000000..41434ab4e --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleCommand.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Inno.Tooling.Architecture; + +/// +/// Checks handwritten C# against the style rulebook and applies its automatic fixes. +/// +public static class StyleCommand +{ + /// + /// Runs check or fix for a repository root. + /// + /// + /// The operation, the repository root, and the optional --rule, --paths-from and --report options. + /// + /// + /// Zero when no finding and no rejected fix remains; otherwise one. + /// + /// + /// The arguments do not name an operation and a repository root, or an option is unknown. + /// + public static int Execute(string[] arguments) + { + if (arguments.Length < 2 || arguments[0] is not ("check" or "fix")) + { + throw new ArgumentException("Usage: style [--rule ID]... [--paths-from FILE] [--report FILE]"); + } + + string root = Path.GetFullPath(arguments[1]); + var ruleIds = new List(); + string? pathsFrom = null; + string? report = null; + for (int index = 2; index < arguments.Length; index += 2) + { + if (index + 1 >= arguments.Length) + { + throw new ArgumentException($"The option '{arguments[index]}' requires a value."); + } + + string value = arguments[index + 1]; + switch (arguments[index]) + { + case "--rule": + ruleIds.Add(value); + break; + case "--paths-from": + pathsFrom = value; + break; + case "--report": + report = value; + break; + default: + throw new ArgumentException($"Unknown option '{arguments[index]}'."); + } + } + + string[] paths = pathsFrom is null + ? StyleEngine.EnumerateSources(root).ToArray() + : File.ReadAllLines(pathsFrom) + .Where(static line => line.Length > 0) + .Select(line => Path.Combine(root, line)) + .ToArray(); + StyleReport result = StyleEngine.Run(root, paths, ruleIds, fix: arguments[0] == "fix"); + if (report is not null) + { + IEnumerable lines = result.findings + .Select(static finding => $"{finding.rule}\t{finding.path}\t{finding.line}\t{finding.message}") + .Concat( + result.rejections.Select(static rejection => $"REJECTED:{rejection.rule}\t{rejection.path}\t0\t{rejection.reason}") + ); + File.WriteAllLines(report, lines); + } + + Console.WriteLine( + $"Files: {result.files}. Changed: {result.changedFiles}. Findings: {result.findings.Count}. Rejected fixes: {result.rejections.Count}." + ); + foreach (IGrouping group in result.findings.GroupBy(static finding => finding.rule)) + { + Console.WriteLine($"{group.Key}\t{group.Count()}\t{group.Select(static finding => finding.path).Distinct().Count()} files"); + } + + return result.findings.Count == 0 && result.rejections.Count == 0 ? 0 : 1; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleEdit.cs b/tools/Inno.Tooling.Architecture/Style/StyleEdit.cs new file mode 100644 index 000000000..aff10e24c --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleEdit.cs @@ -0,0 +1,8 @@ +namespace Inno.Tooling.Architecture; + +// Replaces the half-open character range [start, end) of the original text. +internal sealed record StyleEdit( + int start, + int end, + string text +); diff --git a/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs b/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs new file mode 100644 index 000000000..0179aeafb --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// Checks handwritten C# against the style rulebook and applies the automatic fixes. +internal static class StyleEngine +{ + private const int C_MAX_ROUNDS = 40; + + private const string C_GENERATED_HEADER = " RULES = + [ + new FileTextStyleRule(), + new UsingOrderStyleRule(), + new FileStructureStyleRule(), + new BraceBlankLineStyleRule(), + new MemberSpacingStyleRule(), + new ArgumentJoinStyleRule(), + new ArgumentListStyleRule(), + new LineWidthStyleRule(), + new ParameterListStyleRule(), + new ParameterCloseStyleRule(), + new ClauseStyleRule(), + new ArrowMemberStyleRule(), + new LeadingOperatorStyleRule(), + new ChainStyleRule(), + new SingleLineBlockStyleRule(), + new BraceListStyleRule(), + new BraceStyleRule(), + new EmptyBodyStyleRule(), + new EmptyTypeStyleRule(), + new HeaderCloseStyleRule(), + new EmbeddedBraceStyleRule(), + new LambdaBodyStyleRule(), + new OperatorAlignmentStyleRule(), + new TrailingCommaStyleRule() + ]; + + internal static IEnumerable EnumerateSources(string root) + { + var pending = new Stack(); + pending.Push(root); + while (pending.Count > 0) + { + string directory = pending.Pop(); + foreach (string child in Directory.EnumerateDirectories(directory)) + { + if (!SKIPPED_DIRECTORIES.Contains(Path.GetFileName(child), StringComparer.Ordinal)) + { + pending.Push(child); + } + } + + foreach (string file in Directory.EnumerateFiles(directory, "*.cs")) + { + yield return file; + } + } + } + + // Generated and third-party sources follow their producer, not the rulebook. A marker counts only as the file + // header comment or as an attribute, so a generator that writes the marker into its output stays handwritten. + internal static bool IsHandwritten( + string relativePath, + string content + ) { + if (relativePath.Contains("/Generated/", StringComparison.Ordinal)) return false; + bool hasHeader = content.Contains(C_GENERATED_HEADER, StringComparison.OrdinalIgnoreCase); + bool hasAttribute = content.Contains(C_GENERATED_ATTRIBUTE, StringComparison.Ordinal); + if (!hasHeader && !hasAttribute) return true; + SyntaxNode root = new StyleSource(relativePath, content).root; + if (hasHeader && root.GetFirstToken(includeZeroWidth: true).LeadingTrivia.Any(IsGeneratedHeader)) return false; + return !hasAttribute || !root.DescendantNodes().OfType().Any(IsGeneratedAttribute); + } + + private static bool IsGeneratedHeader(SyntaxTrivia trivia) + => (trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) || trivia.IsKind(SyntaxKind.MultiLineCommentTrivia)) + && trivia.ToString().Contains(C_GENERATED_HEADER, StringComparison.OrdinalIgnoreCase); + + private static bool IsGeneratedAttribute(AttributeSyntax attribute) + => attribute.Name.ToString().Split('.')[^1] is "GeneratedCode" or "GeneratedCodeAttribute"; + + internal static StyleReport Run( + string root, + IReadOnlyCollection paths, + IReadOnlyCollection ruleIds, + bool fix + ) { + StyleRule[] rules = RULES.Where(rule => ruleIds.Count == 0 || ruleIds.Contains(rule.id)).ToArray(); + var findings = new ConcurrentBag(); + var rejections = new ConcurrentBag(); + int files = 0; + int changedFiles = 0; + Parallel.ForEach( + paths, + path => + { + string relativePath = Path.GetRelativePath(root, path).Replace('\\', '/'); + string original = ENCODING.GetString(File.ReadAllBytes(path)); + if (!IsHandwritten(relativePath, original)) return; + Interlocked.Increment(ref files); + string content = fix ? Fix(relativePath, original, rules, rejections) : original; + if (!string.Equals(content, original, StringComparison.Ordinal)) + { + File.WriteAllBytes(path, ENCODING.GetBytes(content)); + Interlocked.Increment(ref changedFiles); + } + + var source = new StyleSource(relativePath, content); + var local = new List(); + foreach (StyleRule rule in rules) + { + rule.Check(source, local); + } + + foreach (StyleFinding finding in local) + { + findings.Add(finding); + } + } + ); + StyleFinding[] ordered = findings + .OrderBy(static finding => finding.rule, StringComparer.Ordinal) + .ThenBy(static finding => finding.path, StringComparer.Ordinal) + .ThenBy(static finding => finding.line) + .ToArray(); + StyleRejection[] rejected = rejections + .OrderBy(static rejection => rejection.path, StringComparer.Ordinal) + .ThenBy(static rejection => rejection.rule, StringComparer.Ordinal) + .ToArray(); + return new StyleReport(files, changedFiles, ordered, rejected); + } + + // Reports every finding of every rule for one source; a generated source has none. + internal static IReadOnlyList Check( + string relativePath, + string content + ) { + var findings = new List(); + if (!IsHandwritten(relativePath, content)) return findings; + var source = new StyleSource(relativePath, content); + if (source.hasSyntaxErrors) return findings; + foreach (StyleRule rule in RULES) + { + rule.Check(source, findings); + } + + return findings; + } + + // Applies every fix until the text is stable. A fix is kept only when it provably preserves the tokens. + internal static string Fix( + string relativePath, + string original, + IReadOnlyList rules, + ConcurrentBag rejections + ) { + string content = original; + var rejectedRules = new HashSet(StringComparer.Ordinal); + for (int round = 0; round < C_MAX_ROUNDS; round++) + { + bool isChanged = false; + foreach (StyleRule rule in rules) + { + if (rejectedRules.Contains(rule.id)) continue; + var source = new StyleSource(relativePath, content); + if (source.hasSyntaxErrors) + { + rejections.Add(new(rule.id, relativePath, "The file has syntax errors.")); + return content; + } + + IReadOnlyList edits = rule.Fix(source); + if (edits.Count == 0) continue; + string updated = StyleSource.Apply(content, edits); + if (string.Equals(updated, content, StringComparison.Ordinal)) continue; + var candidate = new StyleSource(relativePath, updated); + string? reason = Preservation(rule.kind, source, candidate); + if (reason is not null) + { + rejectedRules.Add(rule.id); + rejections.Add(new(rule.id, relativePath, reason)); + continue; + } + + content = updated; + isChanged = true; + } + + if (!isChanged) return content; + } + + rejections.Add(new("*", relativePath, "The fixes did not converge.")); + return content; + } + + private static string? Preservation( + StyleRuleKind kind, + StyleSource before, + StyleSource after + ) { + if (after.hasSyntaxErrors) return "The fix introduced a syntax error."; + if (kind == StyleRuleKind.Rewrite) return null; + IReadOnlyList expected = before.TokenTexts(); + IReadOnlyList actual = after.TokenTexts(); + if (kind == StyleRuleKind.Reorder) + { + return expected.Order(StringComparer.Ordinal).SequenceEqual(actual.Order(StringComparer.Ordinal), StringComparer.Ordinal) + ? null + : "The fix added or removed tokens."; + } + + return expected.SequenceEqual(actual, StringComparer.Ordinal) ? null : "The fix changed the token sequence."; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleFinding.cs b/tools/Inno.Tooling.Architecture/Style/StyleFinding.cs new file mode 100644 index 000000000..f7f32f733 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleFinding.cs @@ -0,0 +1,8 @@ +namespace Inno.Tooling.Architecture; + +internal sealed record StyleFinding( + string rule, + string path, + int line, + string message +); diff --git a/tools/Inno.Tooling.Architecture/Style/StyleLayout.cs b/tools/Inno.Tooling.Architecture/Style/StyleLayout.cs new file mode 100644 index 000000000..8813b9c65 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleLayout.cs @@ -0,0 +1,211 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// Text operations shared by the layout rules. +internal static class StyleLayout +{ + internal const int C_INDENT = 4; + internal const int C_WIDTH = 120; + internal const int C_HARD_WIDTH = 140; + + // An expression in a hole of an interpolated string is never broken: the string stays one unit. + internal static bool IsInInterpolation(SyntaxNode node) + => node.Ancestors().Any(static ancestor => ancestor is InterpolationSyntax); + + internal static bool IsBlank( + string content, + int start, + int end + ) { + for (int index = start; index < end; index++) + { + if (!char.IsWhiteSpace(content[index])) return false; + } + + return true; + } + + // Moves the indentation of one line by a number of columns, unless the line starts inside protected text. + internal static StyleEdit? Shift( + StyleSource source, + int line, + int delta, + IReadOnlyList protectedSpans + ) { + TextLine textLine = source.text.Lines[line]; + int start = textLine.Start; + foreach (TextSpan span in protectedSpans) + { + if (start > span.Start && start < span.End) return null; + } + + int end = start; + while (end < textLine.End && source.content[end] == ' ') + { + end++; + } + + if (end == textLine.End) return null; + int width = end - start + delta; + return new(start, end, new string(' ', width < 0 ? 0 : width)); + } + + // Whether the list has the expanded form: the opener ends its line, each item is on its own line one level + // deeper, and the closer starts its own line at the indentation of the line that opens the list. + internal static bool IsExpanded( + StyleSource source, + StyleList list + ) { + int indentation = source.Indentation(list.open.SpanStart); + if (!source.IsLastOnLine(list.open)) return false; + foreach (SyntaxNode argument in list.items) + { + SyntaxToken first = argument.GetFirstToken(); + if (!source.IsFirstOnLine(first) || source.Column(first.SpanStart) != indentation + C_INDENT) return false; + } + + return source.IsFirstOnLine(list.close) && source.Column(list.close.SpanStart) == indentation; + } + + // The edits that give the list its expanded form, or null when something other than whitespace separates its items. + internal static List? Expand( + StyleSource source, + StyleList list, + IReadOnlyList protectedSpans + ) { + string content = source.content; + int indentation = source.Indentation(list.open.SpanStart); + string argumentIndent = new(' ', indentation + C_INDENT); + var edits = new List(); + int previousEnd = list.open.Span.End; + foreach (SyntaxNode argument in list.items) + { + SyntaxToken first = argument.GetFirstToken(); + if (!IsBlank(content, previousEnd, first.SpanStart)) return null; + int startLine = source.LineNumber(first.SpanStart); + int delta = indentation + C_INDENT - source.Indentation(first.SpanStart); + edits.Add(new(previousEnd, first.SpanStart, "\n" + argumentIndent)); + int endLine = source.LineNumber(argument.Span.End); + for (int line = startLine + 1; line <= endLine && delta != 0; line++) + { + StyleEdit? shift = Shift(source, line, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + + // The separator stays on the argument's last line. + SyntaxToken next = argument.GetLastToken().GetNextToken(); + previousEnd = next.IsKind(SyntaxKind.CommaToken) ? next.Span.End : argument.Span.End; + } + + if (!IsBlank(content, previousEnd, list.close.SpanStart)) return null; + edits.Add(new(previousEnd, list.close.SpanStart, "\n" + new string(' ', indentation))); + return edits; + } + + // The parentheses of the header of a control statement, when it has one. + internal static (SyntaxToken open, SyntaxToken close)? Header(SyntaxNode statement) + => statement switch + { + IfStatementSyntax node => (node.OpenParenToken, node.CloseParenToken), + WhileStatementSyntax node => (node.OpenParenToken, node.CloseParenToken), + ForStatementSyntax node => (node.OpenParenToken, node.CloseParenToken), + CommonForEachStatementSyntax node => (node.OpenParenToken, node.CloseParenToken), + SwitchStatementSyntax node when !node.OpenParenToken.IsKind(SyntaxKind.None) => (node.OpenParenToken, node.CloseParenToken), + LockStatementSyntax node => (node.OpenParenToken, node.CloseParenToken), + UsingStatementSyntax node => (node.OpenParenToken, node.CloseParenToken), + FixedStatementSyntax node => (node.OpenParenToken, node.CloseParenToken), + _ => null + }; + + // Whether the parenthesis closes a parameter list or a control statement header that spans several lines. + internal static bool ClosesMultiLineHeader( + StyleSource source, + SyntaxToken close + ) { + if (!close.IsKind(SyntaxKind.CloseParenToken) || close.Parent is null) return false; + SyntaxToken open; + if (close.Parent is ParameterListSyntax parameters) + { + open = parameters.OpenParenToken; + } + else if (Header(close.Parent) is { } header && header.close == close) + { + open = header.open; + } + else + { + return false; + } + + return source.LineNumber(open.SpanStart) != source.LineNumber(close.SpanStart); + } + + // The text between two tokens joined onto one line, or null when a comment, a directive, a multi-line + // token or a construct that owns its own multi-line layout lies between them. + internal static string? Join( + StyleSource source, + SyntaxToken open, + SyntaxToken close + ) { + SyntaxNode parent = open.Parent!; + foreach (SyntaxNode node in parent.DescendantNodes()) + { + // A nested list of two or more parameters is always expanded (P-01), so its owner cannot be joined. + if (node is ParameterListSyntax { Parameters.Count: >= 2 }) return null; + if (!OwnsLayout(node)) continue; + if (source.LineNumber(node.SpanStart) != source.LineNumber(node.Span.End)) return null; + } + + var builder = new StringBuilder(); + SyntaxToken token = open; + while (true) + { + if (source.LineNumber(token.SpanStart) != source.LineNumber(token.Span.End)) return null; + builder.Append(token.Text); + if (token == close) break; + SyntaxToken next = token.GetNextToken(); + string gap = source.content[token.Span.End..next.SpanStart]; + if (!IsBlank(gap, 0, gap.Length)) return null; + if (gap.Contains('\n')) + { + gap = Glues(token, next) ? "" : " "; + } + + builder.Append(gap); + token = next; + } + + return builder.ToString(); + } + + private static bool OwnsLayout(SyntaxNode node) + => node is BlockSyntax + or SwitchExpressionSyntax + or InitializerExpressionSyntax + or CollectionExpressionSyntax + or AnonymousObjectCreationExpressionSyntax + or QueryExpressionSyntax + or InterpolatedStringExpressionSyntax + or WithExpressionSyntax + or PropertyPatternClauseSyntax; + + private static bool Glues( + SyntaxToken left, + SyntaxToken right + ) => left.IsKind(SyntaxKind.OpenParenToken) + || left.IsKind(SyntaxKind.OpenBracketToken) + || left.IsKind(SyntaxKind.DotToken) + || right.IsKind(SyntaxKind.CloseParenToken) + || right.IsKind(SyntaxKind.CloseBracketToken) + || right.IsKind(SyntaxKind.CommaToken) + || right.IsKind(SyntaxKind.SemicolonToken) + || right.IsKind(SyntaxKind.DotToken) + || right.Parent is ConditionalAccessExpressionSyntax && right.IsKind(SyntaxKind.QuestionToken); +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleLines.cs b/tools/Inno.Tooling.Architecture/Style/StyleLines.cs new file mode 100644 index 000000000..652186420 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleLines.cs @@ -0,0 +1,71 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// Line-level facts and edits shared by the blank-line rules. +internal static class StyleLines +{ + // True for an empty or whitespace-only line that lies between tokens, not inside a literal or a comment. + internal static bool IsBlank( + StyleSource source, + int line + ) { + TextLine textLine = source.text.Lines[line]; + if (!StyleLayout.IsBlank(source.content, textLine.Start, textLine.End)) return false; + if (textLine.Start >= source.content.Length) return true; + SyntaxTrivia trivia = source.root.FindTrivia(textLine.Start); + return trivia.IsKind(SyntaxKind.EndOfLineTrivia) || trivia.IsKind(SyntaxKind.WhitespaceTrivia); + } + + internal static StyleEdit Remove( + StyleSource source, + int line + ) { + TextLine textLine = source.text.Lines[line]; + return new(textLine.Start, textLine.EndIncludingLineBreak, ""); + } + + internal static StyleEdit InsertBefore( + StyleSource source, + int line + ) { + int start = source.text.Lines[line].Start; + return new(start, start, "\n"); + } + + // The token that ends the line, or default when the line ends with a comment or inside a literal. + internal static SyntaxToken LastToken( + StyleSource source, + int line + ) { + TextLine textLine = source.text.Lines[line]; + int position = textLine.End - 1; + while (position >= textLine.Start && source.content[position] is ' ' or '\t') + { + position--; + } + + if (position < textLine.Start) return default; + SyntaxToken token = source.root.FindToken(position); + return token.Span.End - 1 == position ? token : default; + } + + // The token that starts the line, or default when the line starts with a comment or inside a literal. + internal static SyntaxToken FirstToken( + StyleSource source, + int line + ) { + TextLine textLine = source.text.Lines[line]; + int position = textLine.Start; + while (position < textLine.End && source.content[position] is ' ' or '\t') + { + position++; + } + + if (position >= textLine.End) return default; + SyntaxToken token = source.root.FindToken(position); + return token.SpanStart == position ? token : default; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleList.cs b/tools/Inno.Tooling.Architecture/Style/StyleList.cs new file mode 100644 index 000000000..782465684 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleList.cs @@ -0,0 +1,65 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// A delimited list with its opening and closing tokens and its items in source order. +internal sealed record StyleList( + SyntaxToken open, + SyntaxToken close, + IReadOnlyList items +) { + // The argument list of a call, an object creation, a constructor initializer or an attribute, when it has arguments. + internal static StyleList? Arguments(SyntaxNode node) + { + StyleList? list = node switch + { + ArgumentListSyntax arguments => new( + arguments.OpenParenToken, + arguments.CloseParenToken, + arguments.Arguments.ToArray() + ), + AttributeArgumentListSyntax arguments => new( + arguments.OpenParenToken, + arguments.CloseParenToken, + arguments.Arguments.ToArray() + ), + _ => null + }; + return list is null || list.items.Count == 0 || list.open.IsMissing || list.close.IsMissing ? null : list; + } + + // The brace or bracket list of an initializer, an anonymous object, a switch expression or a collection + // expression, when it has items. + internal static StyleList? Braces(SyntaxNode node) + { + StyleList? list = node switch + { + InitializerExpressionSyntax initializer when !initializer.IsKind(SyntaxKind.ComplexElementInitializerExpression) => new( + initializer.OpenBraceToken, + initializer.CloseBraceToken, + initializer.Expressions.ToArray() + ), + AnonymousObjectCreationExpressionSyntax anonymous => new( + anonymous.OpenBraceToken, + anonymous.CloseBraceToken, + anonymous.Initializers.ToArray() + ), + SwitchExpressionSyntax expression => new( + expression.OpenBraceToken, + expression.CloseBraceToken, + expression.Arms.ToArray() + ), + CollectionExpressionSyntax collection => new( + collection.OpenBracketToken, + collection.CloseBracketToken, + collection.Elements.ToArray() + ), + _ => null + }; + return list is null || list.items.Count == 0 || list.open.IsMissing || list.close.IsMissing ? null : list; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleOperators.cs b/tools/Inno.Tooling.Architecture/Style/StyleOperators.cs new file mode 100644 index 000000000..05826829f --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleOperators.cs @@ -0,0 +1,95 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// The operator chains whose continuation lines begin with an operator and align with the first operand. +internal static class StyleOperators +{ + // Each chain is one run of operators of the same precedence, with the token its continuation lines align with. + // An operand of another precedence is a chain of its own, so breaking 'a == b && c' never separates 'a == b'. + internal static IEnumerable<(SyntaxNode chain, SyntaxToken anchor, IReadOnlyList operators)> Chains(SyntaxNode root) + { + foreach (SyntaxNode node in root.DescendantNodes()) + { + var operators = new List(); + switch (node) + { + case BinaryExpressionSyntax binary when IsChained(binary) && !IsSameTier(binary, node.Parent): + Collect(binary, Tier(binary.Kind()), operators); + yield return (node, node.GetFirstToken(), operators); + break; + case BinaryPatternSyntax pattern when !(node.Parent is BinaryPatternSyntax parent && parent.Kind() == pattern.Kind()): + Collect(pattern, operators); + SyntaxNode owner = node.Parent is IsPatternExpressionSyntax ? node.Parent : node; + yield return (node, owner.GetFirstToken(), operators); + break; + case ConditionalExpressionSyntax conditional: + operators.Add(conditional.QuestionToken); + operators.Add(conditional.ColonToken); + yield return (node, node.GetFirstToken(), operators); + break; + } + } + } + + // True for a chain of comparisons, whose operands stay together while a looser construct can break. + internal static bool IsComparison(SyntaxNode chain) => chain is BinaryExpressionSyntax binary && Tier(binary.Kind()) is 6 or 7; + + // 'is' and 'as' stay on the line of their left operand and do not take part in a chain. + private static bool IsChained(BinaryExpressionSyntax binary) + => !binary.IsKind(SyntaxKind.IsExpression) && !binary.IsKind(SyntaxKind.AsExpression); + + private static bool IsSameTier( + BinaryExpressionSyntax binary, + SyntaxNode? parent + ) => parent is BinaryExpressionSyntax outer && IsChained(outer) && Tier(outer.Kind()) == Tier(binary.Kind()); + + private static int Tier(SyntaxKind kind) + => kind switch + { + SyntaxKind.CoalesceExpression => 0, + SyntaxKind.LogicalOrExpression => 1, + SyntaxKind.LogicalAndExpression => 2, + SyntaxKind.BitwiseOrExpression => 3, + SyntaxKind.ExclusiveOrExpression => 4, + SyntaxKind.BitwiseAndExpression => 5, + SyntaxKind.EqualsExpression or SyntaxKind.NotEqualsExpression => 6, + SyntaxKind.LessThanExpression + or SyntaxKind.LessThanOrEqualExpression + or SyntaxKind.GreaterThanExpression + or SyntaxKind.GreaterThanOrEqualExpression => 7, + SyntaxKind.LeftShiftExpression + or SyntaxKind.RightShiftExpression + or SyntaxKind.UnsignedRightShiftExpression => 8, + SyntaxKind.AddExpression or SyntaxKind.SubtractExpression => 9, + _ => 10 + }; + + private static void Collect( + BinaryExpressionSyntax binary, + int tier, + List operators + ) { + if (binary.Left is BinaryExpressionSyntax left && IsChained(left) && Tier(left.Kind()) == tier) + { + Collect(left, tier, operators); + } + operators.Add(binary.OperatorToken); + if (binary.Right is BinaryExpressionSyntax right && IsChained(right) && Tier(right.Kind()) == tier) + { + Collect(right, tier, operators); + } + } + + private static void Collect( + BinaryPatternSyntax pattern, + List operators + ) { + if (pattern.Left is BinaryPatternSyntax left && left.Kind() == pattern.Kind()) Collect(left, operators); + operators.Add(pattern.OperatorToken); + if (pattern.Right is BinaryPatternSyntax right && right.Kind() == pattern.Kind()) Collect(right, operators); + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleRejection.cs b/tools/Inno.Tooling.Architecture/Style/StyleRejection.cs new file mode 100644 index 000000000..8403e96ee --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleRejection.cs @@ -0,0 +1,8 @@ +namespace Inno.Tooling.Architecture; + +// A fix that was discarded because its result did not preserve the program text. +internal sealed record StyleRejection( + string rule, + string path, + string reason +); diff --git a/tools/Inno.Tooling.Architecture/Style/StyleReport.cs b/tools/Inno.Tooling.Architecture/Style/StyleReport.cs new file mode 100644 index 000000000..2765e3151 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleReport.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace Inno.Tooling.Architecture; + +internal sealed record StyleReport( + int files, + int changedFiles, + IReadOnlyList findings, + IReadOnlyList rejections +); diff --git a/tools/Inno.Tooling.Architecture/Style/StyleRule.cs b/tools/Inno.Tooling.Architecture/Style/StyleRule.cs new file mode 100644 index 000000000..12db2c950 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleRule.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace Inno.Tooling.Architecture; + +internal abstract class StyleRule +{ + internal abstract string id { get; } + + internal abstract StyleRuleKind kind { get; } + + internal abstract void Check( + StyleSource source, + ICollection findings + ); + + // Returns non-overlapping edits against the current text, or an empty list when the rule has no automatic fix. + internal virtual IReadOnlyList Fix(StyleSource source) => []; +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleRuleKind.cs b/tools/Inno.Tooling.Architecture/Style/StyleRuleKind.cs new file mode 100644 index 000000000..0e88aa625 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleRuleKind.cs @@ -0,0 +1,11 @@ +namespace Inno.Tooling.Architecture; + +internal enum StyleRuleKind +{ + // Changes whitespace and line breaks only. The token sequence is identical before and after. + Layout, + // Moves tokens without adding or removing any. The token multiset is identical before and after. + Reorder, + // Adds, removes or replaces tokens without changing program meaning. + Rewrite +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleSource.cs b/tools/Inno.Tooling.Architecture/Style/StyleSource.cs new file mode 100644 index 000000000..0662b46c5 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/StyleSource.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +internal sealed class StyleSource +{ + private static readonly CSharpParseOptions PARSE_OPTIONS = new(LanguageVersion.CSharp14); + + internal string path { get; } + + internal string content { get; } + + internal SyntaxTree tree { get; } + + internal SyntaxNode root { get; } + + internal SourceText text { get; } + + internal StyleSource( + string path, + string content + ) { + this.path = path; + this.content = content; + this.tree = CSharpSyntaxTree.ParseText(content, PARSE_OPTIONS, path: path); + this.root = this.tree.GetRoot(); + this.text = this.tree.GetText(); + } + + internal int LineNumber(int position) => text.Lines.GetLineFromPosition(position).LineNumber; + + internal TextLine Line(int position) => text.Lines.GetLineFromPosition(position); + + // Counts the columns of leading whitespace on the line that contains the position. + internal int Indentation(int position) + { + TextLine line = Line(position); + int column = 0; + while (line.Start + column < line.End && content[line.Start + column] == ' ') + { + column++; + } + + return column; + } + + internal int Column(int position) => position - Line(position).Start; + + internal bool IsFirstOnLine(SyntaxToken token) + { + TextLine line = Line(token.SpanStart); + for (int index = line.Start; index < token.SpanStart; index++) + { + if (!char.IsWhiteSpace(content[index])) return false; + } + + return true; + } + + internal bool IsLastOnLine(SyntaxToken token) + { + TextLine line = Line(token.Span.End); + for (int index = token.Span.End; index < line.End; index++) + { + if (!char.IsWhiteSpace(content[index])) return false; + } + + return true; + } + + // Ranges whose characters belong to program text or disabled code and must never be reformatted: + // tokens that span several lines (verbatim and raw strings) and text excluded by the preprocessor. + internal IReadOnlyList ProtectedSpans() + { + var spans = new List(); + foreach (SyntaxToken token in root.DescendantTokens(descendIntoTrivia: true)) + { + if (token.Span.Length > 0 && LineNumber(token.SpanStart) != LineNumber(token.Span.End)) + { + spans.Add(token.Span); + } + } + + // The text and closing delimiter of a multi-line interpolated string depend on their own indentation. + foreach (SyntaxNode node in root.DescendantNodes()) + { + if (node is InterpolatedStringExpressionSyntax && LineNumber(node.SpanStart) != LineNumber(node.Span.End)) + { + spans.Add(node.Span); + } + } + + foreach (SyntaxTrivia trivia in root.DescendantTrivia(descendIntoTrivia: true)) + { + if (trivia.IsKind(SyntaxKind.DisabledTextTrivia)) + { + spans.Add(trivia.Span); + } + } + + return spans; + } + + internal StyleFinding Finding( + string rule, + int position, + string message + ) => new(rule, path, LineNumber(position) + 1, message); + + // The token texts in source order. Layout rules must leave this sequence unchanged. + internal IReadOnlyList TokenTexts() + => root.DescendantTokens(descendIntoTrivia: false).Select(static token => token.Text).ToArray(); + + internal bool hasSyntaxErrors + => tree.GetDiagnostics().Any(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error); + + internal static string Apply( + string content, + IReadOnlyList edits + ) { + if (edits.Count == 0) return content; + StyleEdit[] ordered = edits.OrderBy(static edit => edit.start).ThenBy(static edit => edit.end).ToArray(); + var builder = new StringBuilder(content.Length + 64); + int position = 0; + foreach (StyleEdit edit in ordered) + { + if (edit.start < position) + { + throw new InvalidOperationException("Style edits overlap."); + } + + builder.Append(content, position, edit.start - position); + builder.Append(edit.text); + position = edit.end; + } + + builder.Append(content, position, content.Length - position); + return builder.ToString(); + } +} From 9a88abf2030410838978c6a1be82c7612e99d9d8 Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 19:52:01 +0000 Subject: [PATCH 08/33] style(csharp): apply the rulebook layout to all handwritten C# Run `style fix` over every handwritten C# file. Generated bindings, extern and auto-generated sources are untouched. The changes are layout only, with two exceptions that add tokens without changing behavior: braces around single-statement control bodies (B-05) and parentheses around multi-line expression lambdas (B-04). `style check` reports no findings afterwards. --- .../ShaderArtifactBuilder.cs | 60 +- .../ShaderBuildInputs.cs | 25 +- .../BgfxAuthoringProvider.cs | 3 +- .../BgfxGameContentCompiler.cs | 92 +- .../BgfxShaderCompilerProfile.cs | 9 +- .../BgfxShaderTargetProfile.cs | 13 +- .../BgfxShadercToolchain.cs | 60 +- .../BgfxTargetCapabilities.cs | 9 +- .../BgfxTextureTargetCompiler.cs | 40 +- .../Execution/ToolRunResult.cs | 1 - .../Execution/ToolRunner.cs | 36 +- .../BgfxShaderIrGenerator.ControlFlow.cs | 42 +- .../BgfxShaderIrGenerator.Resources.cs | 79 +- .../BgfxShaderIrGenerator.Source.cs | 136 +- .../Intermediate/BgfxShaderIrGenerator.cs | 170 +- .../BgfxShadercToolchain.Reflection.cs | 12 +- .../BgfxShadercToolchain.Typed.cs | 153 +- .../Sources/BgfxPreprocessorExpression.cs | 70 +- .../Sources/BgfxShaderSourceFrontend.cs | 163 +- .../Sources/BgfxSourceLexer.cs | 39 +- .../Sources/BgfxSourcePreprocessor.cs | 135 +- .../BgfxBindingProject.cs | 27 +- .../BgfxBuildConstants.cs | 5 + .../BgfxBuildInvocation.cs | 2 + .../BgfxBuildRequest.cs | 41 +- .../BgfxBuildSession.cs | 62 +- .../BgfxBuildUtils.cs | 6 +- .../BgfxNativeBuild.cs | 6 +- .../BgfxToolsBuild.cs | 3 +- backends/Bgfx/native/Inno.Native.Bgfx/bgfx.cs | 2 +- .../BgfxCapabilityMapper.cs | 82 +- .../BgfxCommandEncoder.Bindings.cs | 87 +- .../BgfxCommandEncoder.Compute.cs | 14 +- .../BgfxCommandEncoder.Draw.cs | 46 +- .../BgfxCommandEncoder.Geometry.cs | 43 +- .../BgfxCommandEncoder.State.cs | 115 +- .../BgfxCommandEncoder.Transfers.cs | 15 +- .../BgfxCommandEncoder.Validation.cs | 27 +- .../BgfxCommandEncoder.cs | 1 - .../BgfxCompositionProgramProvider.cs | 33 +- .../BgfxDevice.FrameBuffers.cs | 75 +- .../BgfxDevice.Frames.cs | 16 +- .../BgfxDevice.Graphs.cs | 20 +- .../BgfxDevice.Readback.cs | 35 +- .../BgfxDevice.Resources.cs | 273 ++-- .../BgfxDevice.Retirement.cs | 45 +- .../BgfxDevice.Surfaces.cs | 66 +- .../BgfxDevice.Textures.cs | 175 +- .../BgfxDevice.Transients.cs | 31 +- .../Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs | 51 +- .../BgfxDeviceOptions.cs | 12 +- .../BgfxNativeCalls.cs | 16 +- .../BgfxProcessDeviceLease.cs | 13 +- .../BgfxRenderingBackendProvider.cs | 3 +- .../BgfxResources.cs | 25 +- .../Surfaces/BgfxSurfaceBinding.cs | 2 + .../Surfaces/BgfxSurfaceDescriptor.cs | 2 + .../Desktop/CoreClrDeploymentCompiler.cs | 19 +- .../NativeAot/NativeAotDeploymentCompiler.cs | 19 +- .../Publishing/DotNetDeploymentPublisher.cs | 15 +- .../Publishing/DotNetPublishExecutor.cs | 83 +- .../WebAssembly/MonoWasmDeploymentCompiler.cs | 25 +- .../Discovery/ReflectionTypeCatalogSource.cs | 43 +- .../DotNetAssemblyCatalogSource.cs | 61 +- .../DotNetModuleSource.cs | 150 +- .../Loading/HostDependencyManifest.cs | 22 +- .../Loading/ModuleLoadContext.cs | 25 +- .../Reloading/AssemblyUnloadMonitor.cs | 27 +- .../Reloading/DotNetModuleLifetime.cs | 2 + .../Discovery/ReflectionCollectionMetadata.cs | 55 +- .../Discovery/ReflectionObjectMetadata.cs | 57 +- .../Discovery/ReflectionStructMetadata.cs | 47 +- .../ReflectionSerializationMetadataSource.cs | 73 +- .../ContentCacheGeneration.cs | 22 +- .../ContentCachePublication.cs | 33 +- .../ContentCacheRetirement.cs | 11 +- .../ContentCacheValidator.cs | 16 + .../FileContentCacheOptions.cs | 4 + .../FileContentDeployment.cs | 47 +- .../FileContentPreparation.cs | 37 +- .../FileContentStore.cs | 2 + .../FileSystemApplicationStorage.cs | 45 +- .../FileSystemStorageBackendProvider.cs | 8 +- .../CimguiSourceOverlay.cs | 22 +- .../ImGuiToolchain.cs | 65 +- .../CImguizmoBuildConstants.cs | 6 + .../CImguizmoBuildUtils.cs | 6 +- .../ImGuizmoToolchain.cs | 69 +- .../ImGui/native/Inno.Native.ImGui/ImGui.cs | 2 +- .../ImGuizmoModuleProvider.cs | 2 + .../BgfxImGuiRenderer.cs | 252 ++- .../BgfxImGuiShaderArtifacts.cs | 8 +- .../ImGuiPresentationContext.cs | 31 +- .../ImGuiPresentationProvider.cs | 3 +- .../Api/IPlatformImGuiRenderer.Api.cs | 2 +- .../Api/ImGuiInteractionOptions.cs | 2 + .../Sdl3PlatformApplicationImGuiExtensions.cs | 33 +- .../Context/PlatformImGuiContext.Clipboard.cs | 15 + .../Context/PlatformImGuiContext.cs | 131 +- .../ImGuiFont.cs | 42 +- .../ImGuiFontStyle.cs | 2 - .../Interop/ImGuiPlatformIoNative.cs | 8 +- .../Interop/Sdl3PlatformWindowAccess.cs | 1 - .../Rendering/ImGuiPackedColor.cs | 2 +- .../Rendering/PlatformImGuiSdlRenderer.cs | 36 +- .../PlatformImGuiViewportBackend.Monitors.cs | 11 + ...PlatformImGuiViewportBackend.Retirement.cs | 19 +- .../Viewports/PlatformImGuiViewportBackend.cs | 127 +- .../NativeDeploymentIndex.cs | 27 +- .../NativeDllLoader.cs | 19 +- .../MiniAudioToolchain.cs | 55 +- .../native/Inno.Native.MiniAudio/MiniAudio.cs | 2 +- .../MiniAudioBackendProvider.cs | 4 +- .../MiniAudioClipPreparation.cs | 30 +- .../MiniAudioDevice.cs | 291 +++- .../MiniAudioDeviceOptions.cs | 2 + .../MiniAudioEncodedArtifactCache.cs | 27 +- .../Inno.Build.Toolchains.UI/UiToolchain.cs | 62 +- .../RmlUi/native/Inno.Native.UI/UiNative.cs | 2 +- .../RmlUiDocumentFrontend.cs | 144 +- .../RmlUiDocumentImporter.cs | 15 +- .../Inno.Adapter.UI.RmlUi/RmlUiBackend.cs | 289 +++- .../RmlUiBackendProvider.cs | 3 +- .../RmlUiNativeErrors.cs | 8 +- .../RmlUiNativeFrames.cs | 116 +- .../RmlUiNativeRuntime.cs | 186 +-- .../Sdl3Toolchain.cs | 55 +- backends/Sdl3/native/Inno.Native.Sdl3/SDL.cs | 2 +- .../Api/Sdl3FolderDialog.cs | 6 + .../Api/Sdl3PlatformApplication.cs | 6 +- .../Api/Sdl3PlatformWindow.cs | 2 +- .../Api/Sdl3WindowOperations.cs | 14 +- .../Sdl3PlatformApplication.Internal.cs | 35 +- .../Sdl3PlatformApplication.Windows.cs | 14 +- .../Sdl3PlatformBackendProvider.cs | 3 +- .../Sdl3PlatformWindow.Internal.cs | 9 +- .../TextToolchain.cs | 61 +- .../native/Inno.Native.Text/TextNative.cs | 2 +- .../FreeTypeHarfBuzzTextBackend.cs | 118 +- .../FreeTypeHarfBuzzTextBackendProvider.cs | 4 +- .../TextNativeOperations.cs | 66 +- .../Configuration/BindingDefinitionReader.cs | 26 +- .../BindingGenerationConfiguration.cs | 59 +- .../Configuration/NativeBindingProfile.cs | 54 +- .../Generation/BindingGenerationOperation.cs | 132 +- .../Generation/BindingHostExecution.cs | 48 +- .../Generation/BindingHostFactory.cs | 16 +- .../Generation/BindingNativeCompilation.cs | 66 +- .../Generation/TargetBindingGeneration.cs | 2 + .../Identity/BindingInputPlanning.cs | 4 +- .../NativeBindingGenerationIdentity.cs | 56 +- .../Output/BindingGenerationDiagnostics.cs | 38 +- .../BindingGenerationPublication.cs | 20 +- build/cli/Inno.Build.Cli/BuildCommand.cs | 65 +- .../cli/Inno.Build.Cli/BuildCommandContext.cs | 40 +- build/cli/Inno.Build.Cli/BuildCommandLine.cs | 13 +- build/cli/Inno.Build.Cli/BuildComposition.cs | 36 +- build/cli/Inno.Build.Cli/BuildWorkspace.cs | 151 +- .../Cleanup/ProductCleanExecutor.cs | 19 +- .../Cleanup/ProductCleanPlan.cs | 17 +- .../Inno.Build.Cli/Commands/BindingCommand.cs | 36 +- .../Inno.Build.Cli/Commands/CleanCommand.cs | 41 +- .../Commands/EditorBuildCommand.cs | 9 +- .../Commands/NativeDependenciesCommand.cs | 132 +- .../Inno.Build.Cli/Commands/ShaderCommand.cs | 51 +- .../Commands/SupportBuildCommand.cs | 19 +- .../Commands/SupportPackCommand.cs | 18 +- .../NativeBindingsVerification.cs | 262 ++- .../NativeVerificationOptions.cs | 19 +- .../Inno.Build.Cli/ProjectBuildWorkflow.cs | 57 +- .../BuildCompositionContext.cs | 7 +- .../BuildDistribution.cs | 52 +- .../BuildPipelineFactory.cs | 19 +- .../BuildPlatformContribution.cs | 23 +- .../NativeProductContribution.cs | 1 + .../NativeToolchainContribution.cs | 7 +- .../StandardBuildCaches.cs | 134 +- .../StandardBuildDistribution.cs | 66 +- .../StandardBuildEnvironment.cs | 4 +- .../StandardBuildHosts.cs | 4 + .../ManagedDeploymentCapabilities.cs | 4 +- .../ManagedDeploymentCatalog.cs | 27 +- .../Inno.Build.Managed/ManagedDeploymentId.cs | 4 + .../ManagedDeploymentResult.cs | 10 +- build/pipeline/Inno.Build/BuildDiagnostic.cs | 2 - build/pipeline/Inno.Build/BuildPipeline.cs | 47 +- build/pipeline/Inno.Build/BuildProfile.cs | 45 +- .../pipeline/Inno.Build/BuildProfileStore.cs | 9 +- build/pipeline/Inno.Build/BuildProgress.cs | 5 +- build/pipeline/Inno.Build/BuildResult.cs | 8 +- build/pipeline/Inno.Build/BuildSettings.cs | 57 +- .../pipeline/Inno.Build/BuildSettingsStore.cs | 23 +- build/pipeline/Inno.Build/BuildTargetId.cs | 2 + .../Inno.Build/Content/ContentPackWriter.cs | 47 +- .../Inno.Build/Game/GameBuildPipeline.cs | 206 ++- .../Inno.Build/Game/GameBuildTargetBinding.cs | 2 + .../Inno.Build/Game/IGameBuildTarget.cs | 2 +- .../Game/PlayerCodeCompositionWriter.cs | 45 +- build/pipeline/Inno.Build/GameBuildRequest.cs | 4 + .../Inno.Build/Pipeline/BuildFileSystem.cs | 18 +- .../Player/PlayerSupportPackCatalog.cs | 95 +- .../pipeline/Inno.Build/PluginBuildRequest.cs | 16 +- .../Plugins/PluginPackageBuilder.cs | 171 +- .../SdkScriptCompilationEnvironment.cs | 65 +- .../Snapshots/BuildSnapshotFingerprint.cs | 9 +- .../StandardNativeComponents.cs | 148 +- .../StandardNativeDeployment.cs | 31 +- .../StandardSupportPackRequirements.cs | 36 +- .../FilePlayerSupportPackPreparation.cs | 172 +- .../PlayerSupportPackClosureValidator.cs | 19 +- .../PlayerSupportPackFiles.cs | 96 +- .../PlayerSupportPackPlan.cs | 4 +- .../PlayerSupportPackPreparationIdentity.cs | 101 +- .../PlayerSupportPackPreparationIndex.cs | 13 +- .../PlayerSupportPackPublisher.cs | 44 +- .../PlayerSupportPackRequirements.cs | 26 +- .../SourcePlayerSupportPackProvisioner.cs | 32 +- .../BuildTaskRuntimeTask.cs | 149 +- .../MaterializeBindingsTask.cs | 42 +- .../PublishTaskHostTask.cs | 42 +- .../RegisterTaskPublisherTask.cs | 13 +- .../RestoreOwnedProjectTask.cs | 38 +- .../TaskRuntimeBootstrapOwner.cs | 14 +- .../TaskRuntimeBuildScope.cs | 24 +- .../TaskRuntimePackageInputs.cs | 45 +- .../TaskRuntimePreparation.cs | 88 +- .../TaskRuntimeRequestKey.cs | 93 +- .../TaskRuntimeRequestSnapshot.cs | 18 +- .../Inno.Build.Tasks/CompileShaderTask.cs | 146 +- .../Inno.Build.Tasks/GenerateBindingsTask.cs | 105 +- .../MaintainBuildCachesTask.cs | 11 +- .../PrepareProductNativeTask.cs | 74 +- .../PublishSupportPackTask.cs | 23 +- .../BuildArtifactManifest.cs | 42 +- .../BuildArtifactOptions.cs | 22 +- .../Cache/BackendPrebuiltArchive.cs | 73 +- .../Cache/BuildArtifactReadLease.cs | 22 +- .../Cache/BuildArtifactWriteLease.cs | 12 +- .../Cache/BuildCacheArtifactDescriptor.cs | 17 +- .../Cache/BuildCacheArtifactRole.cs | 2 - .../Cache/BuildCacheCleanupPlan.cs | 75 +- .../Cache/BuildCacheFileInventory.cs | 10 + .../Cache/BuildCacheInventory.cs | 59 +- .../Cache/BuildCacheInventoryProgress.cs | 38 +- .../Cache/BuildCacheOwnerCatalog.cs | 41 +- .../Cache/BuildCacheOwnerDescriptor.cs | 5 +- .../Cache/BuildCachePolicy.cs | 6 + .../Cache/BuildCachePublisher.cs | 174 +- .../Cache/BuildCacheRetirement.cs | 52 +- .../Cache/NativeArtifactTransfer.cs | 88 +- .../Cache/NativeDependencyAsset.cs | 1 + .../NativeDependencyManifest.Aggregates.cs | 165 +- .../Cache/NativeDependencyManifest.cs | 390 ++++- .../Cache/NativeDependencySource.cs | 73 +- .../Host/BuildHostServices.cs | 3 + .../PhysicalToolchainWorkspaceProvider.cs | 2 + .../BuildMaintenanceApplication.cs | 70 +- .../Managed/DotNetSdkEnvironment.cs | 6 + .../Managed/DotNetSdkResolver.cs | 22 +- .../Managed/ManagedBuildExecution.cs | 76 +- .../Managed/ManagedBuildInputReader.cs | 159 +- .../Managed/ManagedBuildInputSnapshot.cs | 41 +- .../Managed/ManagedInputEvaluation.cs | 30 +- .../ManagedInputEvaluatorPreparation.cs | 152 +- .../Managed/ManagedProjectGraphCapture.cs | 114 +- .../Native/ComponentNativeProductExecutor.cs | 33 +- .../Native/NativeArtifact.cs | 45 +- .../Native/NativeArtifactPublisher.cs | 195 ++- .../Native/NativeBindingCMake.cs | 57 +- .../Native/NativeBindingCompilation.cs | 59 +- .../NativeBindingGenerationDescriptor.cs | 53 +- .../Native/NativeBindingGenerationRequest.cs | 29 +- .../Native/NativeBindingGenerationResult.cs | 6 + .../Native/NativeBindingInputPaths.cs | 42 +- .../Native/NativeBindingPreparation.cs | 13 +- .../Native/NativeBuildFingerprint.cs | 2 + .../Native/NativeBuildInput.cs | 12 +- .../Native/NativeBuildInputState.cs | 33 +- .../Native/NativeBuildPhaseStatistics.cs | 3 + .../Native/NativeBuildRecipe.cs | 140 +- .../Native/NativeBuildStatistics.cs | 1 - .../Native/NativeCMakeExecutor.cs | 46 +- .../Native/NativeCMakeSource.cs | 57 +- .../Native/NativeCompilerInputs.cs | 19 +- .../Native/NativeComponentBuildOptions.cs | 37 +- .../Native/NativeComponentDescriptor.cs | 18 +- .../Native/NativeInputMaterializer.cs | 23 +- .../Native/NativeInputReadCache.cs | 84 +- .../Native/NativeInputSnapshot.cs | 12 +- .../Native/NativeInputVerificationScope.cs | 2 + .../Native/NativeLinkPlan.cs | 33 +- .../Native/NativeStaticBuildDefinition.cs | 20 +- .../Native/NativeToolchainPreparation.cs | 27 +- .../Native/NativeToolchainSelection.cs | 69 +- .../Native/NativeWorkspaceIdentity.cs | 24 +- .../Native/ProductNativeBuildPlan.cs | 29 +- .../Native/ProductNativeBuildResult.cs | 5 +- .../Native/ProductNativeBuildStep.cs | 36 +- .../Native/ProductNativeCacheLookup.cs | 124 +- .../Native/ProductNativeDeployment.cs | 51 +- .../Native/ProductNativePreparation.cs | 152 +- .../NativeBuildContext.cs | 57 +- .../ToolchainEnvironment.cs | 37 +- .../ToolchainWorkingDirectory.cs | 2 + entry/InnoEngine.Build/Program.cs | 12 + entry/InnoEngine.Editor/Program.cs | 13 +- .../BrowserWasm32BuildModule.cs | 17 +- .../EmscriptenToolchainResolver.cs | 46 +- .../Native/BrowserWasm32LinkerSettings.cs | 3 +- .../BrowserWasm32NativeProductExecutor.cs | 158 +- .../BrowserWasm32PlayerSupportPackSource.cs | 164 +- .../BrowserWasm32SupportPackValidator.cs | 55 +- .../Targets/BrowserWasm32GameBuildTarget.cs | 10 +- .../EmscriptenNativeToolchainProvider.cs | 42 +- .../BrowserWasm32BgfxSurfaceIntegration.cs | 9 +- .../BrowserWasm32BgfxIntegration.cs | 9 +- .../BrowserWasm32BgfxShaderProfiles.cs | 40 +- .../Bindings/BrowserWasm32BindingProfile.cs | 16 +- .../BrowserWasm32BuildIntegration.cs | 17 +- .../Deployment/BrowserWasm32NativeLayout.cs | 7 +- .../Products/BrowserWasm32NativeProducts.cs | 6 +- .../BrowserWasm32Sdl3HostIntegration.cs | 10 +- .../BrowserWasm32PlayerComposition.cs | 20 +- .../HttpPlayerContentSource.cs | 21 +- .../BrowserWasm32ApplicationStorage.cs | 15 +- .../BrowserWasm32StorageBackendProvider.cs | 4 +- .../Host/MacOSArm64BuildHostProvider.cs | 16 +- .../MacOSArm64BuildModule.cs | 20 +- .../Native/MacOSArm64LinkerSettings.cs | 11 +- .../MacOSArm64PlayerSupportPackSource.cs | 14 +- .../MacOSArm64SupportPackValidator.cs | 22 +- .../Targets/MacOSArm64GameBuildTarget.cs | 33 +- .../MacOSArm64NativeToolchainProvider.cs | 50 +- .../MacOSArm64EditorComposition.cs | 44 +- .../MacOSArm64BgfxSurfaceIntegration.cs | 7 +- .../MacOSArm64BgfxBuildProfile.cs | 12 +- .../MacOSArm64BgfxShaderProfiles.cs | 17 +- .../MacOSArm64BgfxToolContribution.cs | 16 +- .../Bindings/MacOSArm64BindingProfile.cs | 12 +- .../Deployment/MacOSArm64NativeLayout.cs | 7 +- .../MacOSArm64BuildIntegration.cs | 35 +- .../Products/MacOSArm64NativeProducts.cs | 8 +- .../MacOSArm64Sdl3HostIntegration.cs | 6 + .../MacOSArm64PlayerComposition.cs | 31 +- .../MacOSArm64PlayerContentSource.cs | 4 +- .../MacOSArm64ApplicationLocations.cs | 12 +- .../Host/WindowsBuildHostProvider.cs | 21 +- .../Workspace/WindowsToolchainDirectory.cs | 18 +- .../WindowsToolchainWorkspaceProvider.cs | 16 +- .../Native/WindowsX64LinkerSettings.cs | 3 +- .../WindowsX64PlayerSupportPackSource.cs | 14 +- .../WindowsX64SupportPackValidator.cs | 24 +- .../Targets/WindowsX64GameBuildTarget.cs | 25 +- .../WindowsX64NativeToolchainProvider.cs | 81 +- .../WindowsX64BuildModule.cs | 20 +- .../WindowsX64EditorComposition.cs | 44 +- .../WindowsX64BgfxSurfaceIntegration.cs | 7 +- .../WindowsX64BgfxBuildProfile.cs | 18 +- .../WindowsX64BgfxIntegration.cs | 9 +- .../WindowsX64BgfxShaderProfiles.cs | 19 +- .../WindowsX64BgfxToolContribution.cs | 16 +- .../Bindings/WindowsX64BindingProfile.cs | 12 +- .../Deployment/WindowsX64NativeLayout.cs | 7 +- .../Products/WindowsX64NativeProducts.cs | 6 +- .../WindowsX64BuildIntegration.cs | 35 +- .../WindowsX64Sdl3HostIntegration.cs | 10 +- .../WindowsX64PlayerComposition.cs | 31 +- .../WindowsX64PlayerContentSource.cs | 4 +- .../WindowsX64ApplicationLocations.cs | 6 + .../Inno.Adapter.Audio/AudioBackendCatalog.cs | 7 +- .../Inno.Adapter.Audio/AudioBackendId.cs | 5 +- .../AudioBackendProvider.cs | 3 +- .../common/Inno.Adapter/AdapterSelection.cs | 5 +- .../common/Inno.Adapter/IAdapterCatalog.cs | 1 - .../Inno.Adapter.Input/EventInputBackend.cs | 24 +- .../EventInputBackendProvider.cs | 4 +- .../Inno.Adapter.Input/EventInputSource.cs | 5 +- .../Inno.Adapter.Input/InputBackendCatalog.cs | 7 +- .../Inno.Adapter.Input/InputBackendId.cs | 5 +- .../InputBackendProvider.cs | 3 +- .../PlatformBackendCatalog.cs | 10 +- .../PlatformBackendId.cs | 5 +- .../PlatformBackendProvider.cs | 3 +- .../PlatformNativeHandleId.cs | 4 + .../IPresentationContext.cs | 1 - .../PresentationBackendCatalog.cs | 6 +- .../PresentationBackendId.cs | 5 +- .../PresentationBackendProvider.cs | 2 + .../PresentationFeatures.cs | 3 - .../PresentationTextureHandle.cs | 2 + .../RenderingAuthoringBackendCatalog.cs | 10 +- .../RenderingAuthoringBackendProvider.cs | 2 + .../RenderingBackendCatalog.cs | 10 +- .../RenderingBackendId.cs | 4 + .../RenderingBackendProvider.cs | 2 + .../StorageBackendCatalog.cs | 9 +- .../Inno.Adapter.Storage/StorageBackendId.cs | 5 +- .../StorageBackendProvider.cs | 3 +- .../Inno.Adapter.Text/TextBackendCatalog.cs | 10 +- .../text/Inno.Adapter.Text/TextBackendId.cs | 5 +- .../Inno.Adapter.Text/TextBackendProvider.cs | 3 +- .../ui/Inno.Adapter.UI/UiBackendCatalog.cs | 9 +- .../ui/Inno.Adapter.UI/UiBackendId.cs | 4 + .../ui/Inno.Adapter.UI/UiBackendProvider.cs | 2 + .../DefaultAuthoringAdapterCatalog.cs | 12 +- .../DefaultAdapterCatalog.cs | 1 - .../DefaultAdapterCatalogOptions.cs | 4 +- .../StandardAdapterSelection.cs | 3 +- .../Animation/AnimationSubsystem.cs | 7 +- .../Audio/AudioSubsystem.cs | 38 +- .../EngineSessionComposition.cs | 7 + .../Inno.Engine.Default/Text/TextSubsystem.cs | 3 +- .../Inno.Engine.Default/UI/UiSubsystem.cs | 3 +- .../InspectorPresentationAttributes.cs | 60 +- .../Properties/ScriptingApi.cs | 2 +- .../Creation/AssetCreationTemplate.cs | 13 +- .../Documents/AssetDraftDocuments.cs | 107 +- .../Editing/AssetCreationRegistry.cs | 40 +- .../Editing/AssetEditingModule.Creation.cs | 23 +- .../Editing/AssetEditingModule.Selection.cs | 37 +- .../Editing/AssetEditingModule.cs | 149 +- .../Inno.Editor.Assets/Editing/AssetEditor.cs | 16 +- .../Editing/AssetEditorAttribute.cs | 3 + .../Editing/AssetEditorContext.cs | 8 + .../Editing/AssetEditorRegistry.cs | 37 +- .../Editing/AssetOperationValidation.cs | 3 + .../History/AssetHistoryData.cs | 12 +- .../History/AssetHistoryHandler.cs | 110 +- .../History/AssetHistoryKinds.cs | 1 + .../History/AssetHistoryOperationKind.cs | 1 + .../History/AssetSourceArchive.cs | 32 + .../AssetImportSettingsEdits.cs | 26 +- .../Properties/ScriptingApi.cs | 2 +- .../Samples/AssetSampleImportModule.cs | 67 +- .../Inno.Editor.Audio/EditorAudioHost.cs | 102 +- .../Inno.Editor.Audio/IEditorAudioHost.cs | 2 +- .../Runtime/EditorExportService.cs | 83 +- .../EditorPlayModeState.cs | 5 - .../Inno.Editor.PlayMode/IEditorPlayMode.cs | 1 - .../Interactions/TogglePlayModeAction.cs | 64 +- .../Properties/ScriptingApi.cs | 7 +- .../Runtime/EditorPlayModeController.cs | 91 +- .../Runtime/EditorPlayModeLoop.cs | 8 +- .../Runtime/EditorPlayModeModule.cs | 4 +- ...itorRenderTargetArtifactProvider.Drafts.cs | 70 +- .../EditorRenderTargetArtifactProvider.cs | 167 +- .../Compilation/EditorShaderCompilation.cs | 17 +- .../EditorGizmoProvider.cs | 4 + .../EditorGizmoProviderRegistry.cs | 11 +- .../EditorPreviewService.cs | 2 + .../EditorRenderingModule.cs | 249 +-- .../EditorViewportContributor.cs | 40 +- .../EditorViewportContributorRegistry.cs | 13 +- .../EditorViewportNavigation.cs | 95 +- .../EditorViewportOutput.cs | 18 +- .../Pipelines/PipelineDocuments.cs | 20 +- .../RenderPipelineAssetCreationTemplate.cs | 3 +- .../Properties/ScriptingApi.cs | 7 +- .../SceneStateDiagnosticPublisher.cs | 30 +- .../SceneStateDiagnosticTracker.cs | 15 +- .../EditorSceneDiagnosticPublisher.cs | 57 +- .../Documents/EditorSceneWorkspace.History.cs | 35 +- .../EditorSceneWorkspace.Persistence.cs | 110 +- .../EditorSceneWorkspace.PlayMode.cs | 76 +- .../Documents/EditorSceneWorkspace.Reload.cs | 58 +- .../Documents/EditorSceneWorkspace.Restore.cs | 48 +- .../EditorSceneWorkspace.SourceChanges.cs | 84 +- .../Documents/EditorSceneWorkspace.cs | 64 +- .../Documents/EditorSceneWorkspaceFactory.cs | 5 +- .../Documents/EditorSceneWorkspaceHost.cs | 8 +- .../Documents/IEditorScenePlayMode.cs | 1 - .../Documents/IEditorSceneWorkspace.cs | 1 - .../Documents/SceneEdits.Elements.cs | 54 +- .../Documents/SceneEdits.Hierarchy.cs | 41 +- .../Documents/SceneEdits.History.cs | 63 +- .../Documents/SceneEdits.Objects.cs | 65 +- .../Documents/SceneEdits.Properties.cs | 99 +- .../Documents/SceneEdits.Selection.cs | 49 +- .../Inno.Editor.Scene/Documents/SceneEdits.cs | 23 +- .../Documents/SceneHierarchyEdit.cs | 1 - .../History/SceneDocumentHistoryData.cs | 14 +- .../History/SceneDocumentHistoryHandler.cs | 53 +- .../History/SceneElementHistoryData.cs | 17 +- .../History/SceneElementHistoryHandler.cs | 194 ++- .../History/SceneHierarchyHistoryData.cs | 6 + .../History/SceneHierarchyHistoryHandler.cs | 79 +- .../History/SceneHistoryCompensation.cs | 29 +- .../History/SceneOrderHistoryData.cs | 5 +- .../History/SceneOrderHistoryHandler.cs | 13 +- .../History/ScenePropertyHistoryData.cs | 21 +- .../History/ScenePropertyHistoryHandler.cs | 65 +- .../History/SceneScalarHistoryData.cs | 7 +- .../History/SceneScalarHistoryHandler.cs | 78 +- .../History/SceneSubtreeHistoryData.cs | 16 +- .../History/SceneSubtreeHistoryHandler.cs | 82 +- .../Properties/ScriptingApi.cs | 7 +- .../References/SceneReferenceIndex.cs | 134 +- .../Reloading/SceneReloadIntegration.cs | 22 +- .../Runtime/EditorScripting.cs | 115 +- .../Runtime/IEditorScriptCompilation.cs | 4 +- .../Runtime/ScriptCompilationTicket.cs | 22 +- .../Runtime/ScriptCompilationTicketState.cs | 5 - .../Runtime/ScriptDiagnosticPublisher.cs | 45 +- .../ScriptingReloadActions.cs | 9 +- .../MaterialAssetCreationTemplate.cs | 3 +- .../Materials/MaterialDocuments.cs | 30 +- .../Materials/ShaderParameterPresentation.cs | 22 +- .../Nodes/ShaderInspectionSelection.cs | 5 + .../Previews/ShaderPreviewProvider.cs | 12 +- .../Extensions/EditorModal.cs | 7 +- .../Extensions/EditorModalAttribute.cs | 4 + .../Extensions/EditorModule.cs | 33 +- .../Extensions/EditorModuleAttribute.cs | 2 + .../Extensions/EditorPanel.cs | 24 +- .../Extensions/EditorPanelAttribute.cs | 10 +- .../Extensions/EditorTypeSpecificity.cs | 3 + .../Properties/ScriptingApi.cs | 2 +- .../Reloading/EditorReloadCoordinator.cs | 49 +- .../Reloading/IEditorReloadParticipant.cs | 2 +- .../Inno.Editor.Core/Runtime/EditorContext.cs | 10 +- .../Runtime/EditorKeyboardPolicy.cs | 2 + .../Runtime/EditorLayoutSettings.cs | 56 +- .../Inno.Editor.Core/Runtime/EditorState.cs | 4 +- .../Runtime/EditorStatistics.cs | 26 +- .../Inno.Editor.Diagnostics/EditorConsole.cs | 56 +- .../EditorConsoleEntryKind.cs | 1 - .../EditorConsoleOccurrence.cs | 1 - .../Inno.Editor.Graph/GraphCanvasState.cs | 4 +- .../GraphDocumentController.cs | 40 +- .../Inno.Editor.Graph/GraphEditorModule.cs | 52 +- .../Inno.Editor.Graph/GraphHistory.cs | 67 +- .../Properties/ScriptingApi.cs | 2 +- .../BuiltInInspectorAttributeDrawers.cs | 63 +- .../IInspectorAttributeDrawer.cs | 12 +- .../InspectorAttributeDrawContext.cs | 18 +- .../InspectorAttributeDrawerAttribute.cs | 2 + .../InspectorAttributeDrawerRegistry.cs | 111 +- .../InspectorMemberMetadata.cs | 16 +- .../ObjectDrawing/DefaultInspectionDrawer.cs | 6 +- .../ObjectDrawing/InspectionDrawContext.cs | 52 +- .../ObjectDrawing/InspectionDrawer.cs | 20 +- .../ObjectDrawing/InspectionDrawerRegistry.cs | 93 +- .../Properties/ScriptingApi.cs | 2 +- .../PropertyDrawing/BooleanPropertyDrawer.cs | 1 + .../CollectionPropertyDrawer.cs | 28 +- .../PropertyDrawing/DrawerTypeUtility.cs | 6 +- .../EditorCollectionUtility.cs | 54 +- .../PropertyDrawing/EnumPropertyDrawer.cs | 9 +- .../PropertyDrawing/GuidPropertyDrawer.cs | 10 +- .../IInspectionPropertyEditService.cs | 1 + .../MathematicsPropertyDrawers.cs | 71 +- .../PropertyDrawing/NullablePropertyDrawer.cs | 7 +- .../PropertyDrawing/NumericPropertyDrawer.cs | 49 +- .../PropertyDrawing/PropertyDrawContext.cs | 74 +- .../PropertyDrawing/PropertyDrawerRegistry.cs | 90 +- .../SerializableObjectPropertyDrawer.cs | 9 +- .../SerializedPropertyRenderer.cs | 36 +- .../PropertyDrawing/StringPropertyDrawer.cs | 3 + .../PropertyDrawing/StructPropertyDrawer.cs | 38 +- .../UnsupportedPropertyDrawer.cs | 4 +- .../Actions/EditorAction.cs | 82 +- .../Actions/EditorActionAttribute.cs | 7 +- .../Actions/EditorActionContext.cs | 7 + .../Actions/EditorActionRouter.cs | 133 +- .../Actions/EditorActionState.cs | 8 + .../Actions/EditorShortcutAttribute.cs | 6 +- .../Actions/HotKeyGesture.cs | 29 +- .../Discovery/EditorExtensionActivator.cs | 73 +- .../Discovery/EditorExtensionCatalog.cs | 409 +++-- .../EditorExtensionDiagnosticPublisher.cs | 13 +- .../Discovery/EditorTypeDistance.cs | 2 + .../Documents/EditorDocumentContext.cs | 1 - .../Documents/EditorDocumentService.cs | 94 +- .../Documents/IEditorDocumentService.cs | 1 - .../DragDrop/EditorDragContext.cs | 1 - .../DragDrop/EditorDragData.cs | 7 +- .../DragDrop/EditorDrop.cs | 7 +- .../DragDrop/EditorDropAttribute.cs | 4 +- .../DragDrop/EditorDropContext.cs | 1 - .../DragDrop/EditorDropPlacement.cs | 3 - .../DragDrop/EditorDropResult.cs | 3 +- .../DragDrop/EditorDropRouter.cs | 63 +- .../DragDrop/EditorDropVisual.cs | 4 - .../Editing/EditorEditGesture.cs | 10 +- .../Editing/EditorOperationPreparingEvent.cs | 1 + .../History/EditorHistory.cs | 245 ++- .../History/EditorHistoryBlobStore.cs | 16 +- .../History/EditorHistoryChange.cs | 8 +- .../History/EditorHistoryContext.cs | 1 - .../History/EditorHistoryDirection.cs | 1 - .../History/EditorHistoryHandler.cs | 9 +- .../History/EditorHistoryHandlerAttribute.cs | 1 - .../History/EditorHistoryOperation.cs | 14 +- .../History/EditorHistoryOptions.cs | 10 +- .../History/EditorHistoryPayload.cs | 8 + .../History/EditorHistoryTransaction.cs | 16 +- .../Menus/EditorMenuAttribute.cs | 4 + .../Menus/EditorMenuBuilder.cs | 4 + .../Menus/EditorMenuCatalog.cs | 86 +- .../Menus/EditorMenuContext.cs | 1 - .../Menus/EditorMenuItem.cs | 1 - .../Menus/EditorMenuSourceAttribute.cs | 2 + .../Properties/ScriptingApi.cs | 2 +- .../Runtime/EditorInteraction.cs | 18 + .../Runtime/EditorInteractionRuntime.cs | 77 +- .../Runtime/EditorInteractions.cs | 102 +- .../Runtime/EditorModalExtension.cs | 26 +- .../Runtime/EditorPanelExtension.cs | 3 +- .../Runtime/EditorTargetReference.cs | 17 +- .../Selection/EditorSelectionSnapshot.cs | 14 +- .../Selection/EditorSelectionState.cs | 36 + ...EditorExtensionStateDiagnosticPublisher.cs | 15 +- .../State/EditorExtensionStateStore.cs | 66 +- .../State/EditorJsonState.cs | 13 +- .../Toolbars/EditorToolbarCatalog.cs | 29 +- .../Toolbars/EditorToolbarIcon.cs | 5 - .../Toolbars/EditorToolbarItemAttribute.cs | 10 + .../Viewport/EditorPlanarNavigation.cs | 14 + .../Viewport/EditorViewportToolContext.cs | 21 + .../Viewport/EditorViewportToolSession.cs | 6 + .../Definitions/EditorSetting.cs | 36 +- .../Definitions/EditorSettingObject.cs | 27 +- .../Definitions/EditorSettingPathAttribute.cs | 9 +- .../Definitions/EditorSettingValue.cs | 148 +- .../Definitions/EditorSettingsPathUtility.cs | 6 +- .../Definitions/ProjectSettingEditor.cs | 40 +- .../ProjectSettingPathAttribute.cs | 4 +- .../Properties/ScriptingApi.cs | 2 +- .../Runtime/EditorSettings.cs | 35 +- .../Runtime/EditorSettingsCatalog.cs | 12 +- .../Runtime/EditorSettingsChangedEvent.cs | 1 + .../Runtime/EditorSettingsDocument.cs | 1 - .../Runtime/EditorSettingsHistory.cs | 11 +- .../Runtime/EditorSettingsStore.cs | 21 +- .../Runtime/ProjectSettingEditorCatalog.cs | 16 +- .../Runtime/ProjectSettingsEditor.cs | 16 +- .../Runtime/ProjectSettingsHistory.cs | 13 +- .../Inno.Editor.Hosting/EditorApplication.cs | 10 +- .../EditorCommandLineOptions.cs | 30 +- .../EditorLaunchOptions.cs | 2 +- .../Hosting/EditorAuthoringServices.cs | 32 +- .../Inno.Editor.Hosting/Hosting/EditorHost.cs | 227 ++- .../Hosting/EditorHostResourceStack.cs | 4 + .../Hosting/EditorLayer.cs | 18 +- .../EditorProjectDiagnosticPublisher.cs | 9 +- .../Hosting/EditorRenderingHostService.cs | 129 +- .../Layout/EditorDefaultLayout.cs | 2 +- .../Browser/FileBrowserChangeTracker.cs | 53 +- .../Browser/FileBrowserContextMenu.cs | 38 +- .../Browser/FileBrowserData.cs | 53 +- .../Browser/FileBrowserDragDrop.cs | 39 +- .../Browser/FileBrowserNavigation.cs | 27 +- .../Browser/FileBrowserPanel.Filters.cs | 19 +- .../Browser/FileBrowserPanel.Grid.cs | 43 +- .../Browser/FileBrowserPanel.Layout.cs | 66 +- .../Browser/FileBrowserPanel.List.cs | 64 +- .../Browser/FileBrowserPanel.Navigation.cs | 49 +- .../Browser/FileBrowserPanel.cs | 11 +- .../Browser/FileBrowserRename.cs | 39 +- .../Browser/FileBrowserTree.Navigation.cs | 36 +- .../Browser/FileBrowserTree.Rows.cs | 48 +- .../Browser/FileBrowserTree.cs | 41 +- .../Browser/FileBrowserUtility.cs | 56 +- .../FileBrowserInteractionIds.cs | 1 + .../Interactions/CreateAssetCommand.cs | 20 +- .../Interactions/CreateAssetFolderCommand.cs | 22 +- .../Interactions/DeleteAssetCommand.cs | 7 +- .../Interactions/ImportAssetSampleCommand.cs | 9 +- .../Interactions/MoveAssetEntryDropHandler.cs | 17 +- .../Interactions/OpenAssetCommand.cs | 21 +- .../Interactions/RenameAssetCommand.cs | 36 +- .../Samples/AssetSampleImportModal.cs | 18 +- .../GamePresentationSetting.cs | 9 + .../GameViewBackgroundSetting.cs | 12 +- .../GameViewPanel.cs | 48 +- .../CreateChildGameObjectCommand.cs | 4 +- .../Interactions/CreateGameObjectCommand.cs | 4 +- .../Interactions/DeleteGameObjectCommand.cs | 17 +- .../Interactions/HierarchyObjectDropTarget.cs | 2 - .../Interactions/HierarchySceneDropTarget.cs | 2 - .../InstantiatePrefabAssetCommand.cs | 17 +- .../Interactions/LoadSceneAssetCommand.cs | 17 +- .../MoveGameObjectToSceneDropHandler.cs | 11 +- .../Interactions/OpenPrefabAssetAction.cs | 8 +- .../Interactions/OpenSceneAssetAction.cs | 6 +- .../RenameHierarchyTargetCommand.cs | 27 +- .../Interactions/ReorderSceneDropHandler.cs | 15 +- .../ReparentGameObjectDropHandler.cs | 42 +- .../Interactions/SaveCommand.cs | 10 +- .../SavePrefabAssetDropHandler.cs | 10 +- .../Interactions/SaveSceneAssetDropHandler.cs | 10 +- .../Interactions/SetActiveSceneCommand.cs | 4 +- .../Interactions/UnloadSceneCommand.cs | 10 +- .../Presentation/HierarchyDropVisual.cs | 11 +- .../Presentation/HierarchyPanel.Rows.cs | 42 +- .../Presentation/HierarchyPanel.cs | 160 +- .../Presentation/HierarchySelection.cs | 24 +- .../Properties/ScriptingApi.cs | 7 +- .../DragDrop/AssetReferenceDropHandler.cs | 19 +- .../EngineObjectReferenceDropHandler.cs | 23 +- .../EngineObjectReferenceDropTarget.cs | 2 - .../Interactions/AddComponentCommand.cs | 15 +- .../Interactions/AddComponentMenuProvider.cs | 22 +- .../Interactions/AddSystemCommand.cs | 9 +- .../Interactions/AddSystemMenuProvider.cs | 22 +- .../Interactions/RemoveComponentCommand.cs | 9 +- .../Interactions/RemoveSystemCommand.cs | 7 +- .../Interactions/ResetComponentCommand.cs | 7 +- .../Interactions/ResetSystemCommand.cs | 7 +- .../Layers/GameLayerDiagnosticPublisher.cs | 16 +- .../Layers/GameLayersSetting.cs | 59 +- .../Layers/GameObjectLayerSelector.cs | 23 +- .../Layers/SceneProjectSettingsModule.cs | 15 +- .../Presentation/InspectorCardControls.cs | 107 +- .../Presentation/InspectorLockControl.cs | 11 +- .../Presentation/InspectorPanel.cs | 23 +- .../Presentation/InspectorTargetHeader.cs | 32 +- .../Presentation/InspectorTypeOrigin.cs | 4 +- .../Properties/ScriptingApi.cs | 7 +- .../AssetReferencePropertyDrawer.cs | 68 +- .../EngineObjectReferencePropertyDrawer.cs | 26 +- .../SceneInspectionPropertyEditService.cs | 5 +- .../Runtime/InspectionDrawerActivator.cs | 28 +- .../Runtime/SceneInspectionModule.cs | 40 +- .../Targets/GameObjectInspectionDrawer.cs | 117 +- .../Targets/GameObjectTagSelector.cs | 21 +- .../Targets/GameSceneInspectionDrawer.cs | 90 +- .../Targets/GameTagDiagnosticPublisher.cs | 16 +- .../Targets/GameTagsSetting.cs | 38 +- .../Targets/PipelineInspectionDrawer.cs | 116 +- .../Targets/SelectionInspectionDrawer.cs | 76 +- .../Targets/TransformInspectionDrawer.cs | 94 +- .../Console/ConsoleEntryCopyTarget.cs | 17 +- .../Console/ConsoleEntryImGuiIdentity.cs | 1 + .../Console/ConsolePanel.Layout.cs | 54 +- .../Console/ConsolePanel.cs | 81 +- .../Console/ConsolePanelContent.cs | 25 +- .../Console/ConsoleView.cs | 30 +- .../Console/CopyConsoleDetailsCommand.cs | 4 +- .../Console/CopyConsoleMessageCommand.cs | 4 +- .../Logging/LoggingModule.cs | 16 +- .../Settings/ConsoleSettings.cs | 9 +- .../SceneViewBackgroundSetting.cs | 12 +- .../SceneViewPanel.cs | 268 +++- .../Presentation/BuildSettingsPresentation.cs | 116 +- .../ProjectIdentitySettingsEditor.cs | 8 +- .../Presentation/SettingsModal.cs | 83 +- .../Presentation/SettingsNavigation.cs | 12 + .../Presentation/SettingsPageView.cs | 48 +- .../Presentation/SettingsTree.cs | 102 +- .../Runtime/BuildSettingsHistory.cs | 13 +- .../Runtime/SettingsEditSession.cs | 116 +- .../Runtime/SettingsWindowModule.cs | 9 +- .../Canvas/ShaderEditorCanvas.Controls.cs | 224 ++- .../ShaderEditorCanvas.InputDefaults.cs | 24 +- .../Canvas/ShaderEditorCanvas.MiniMap.cs | 45 +- .../Canvas/ShaderEditorCanvas.Parameters.cs | 93 +- .../Canvas/ShaderEditorCanvas.PassSettings.cs | 102 +- .../Canvas/ShaderEditorCanvas.PortRepair.cs | 41 +- .../ShaderEditorCanvas.SourceSettings.cs | 83 +- .../Canvas/ShaderEditorCanvas.Target.cs | 16 +- .../Canvas/ShaderEditorCanvas.Techniques.cs | 62 +- .../Canvas/ShaderEditorCanvas.cs | 440 ++++- .../ShaderEditorDocuments.CanvasEdits.cs | 16 +- .../ShaderEditorDocuments.Clipboard.cs | 20 +- .../ShaderEditorDocuments.Creation.cs | 116 +- .../Documents/ShaderEditorDocuments.cs | 242 ++- .../Inspection/ShaderInspectionDrawers.cs | 94 +- .../Interactions/CreateShaderAsset.cs | 13 +- .../Interactions/ShaderCanvasActions.cs | 282 +++- .../ShaderCanvasOrganizationActions.cs | 240 ++- .../Interactions/ShaderGraphAutoLayout.cs | 59 +- .../Presentation/ShaderCheckModal.cs | 5 + .../ShaderEditorPanel.cs | 26 +- .../FrameStatisticsSampler.cs | 14 +- .../Inno.Editor.Panel.Stats/StatsPanel.cs | 30 +- .../Icons/AssetIconAttribute.cs | 23 +- .../Icons/AssetIconRegistry.cs | 62 +- .../Icons/BuiltInAssetIcons.cs | 3 +- .../AssetSelectionInspectionDrawer.cs | 22 +- .../Navigation/AssetBrowserModule.cs | 23 +- .../Navigation/AssetBrowserState.cs | 26 +- .../Canvas/GraphCanvasLayout.cs | 8 + .../Canvas/GraphCanvasNode.cs | 10 +- .../Canvas/GraphCanvasPointerController.cs | 36 +- .../Canvas/GraphCanvasPort.cs | 10 +- .../Canvas/GraphCanvasView.Nodes.cs | 80 +- .../Canvas/GraphCanvasView.cs | 34 +- .../Properties/ScriptingApi.cs | 2 +- .../Controls/ImGui.Controls.cs | 2 + .../Controls/ImGui.Drawing.cs | 2 + .../Inno.Editor.ImGui/Controls/ImGui.Input.cs | 2 + .../Controls/ImGui.Layout.cs | 2 + .../Controls/ImGui.Tables.cs | 2 + .../Controls/Options/ImGuiButtonFlags.cs | 3 +- .../Controls/Options/ImGuiChildFlags.cs | 3 +- .../Controls/Options/ImGuiCol.cs | 3 +- .../Controls/Options/ImGuiColorEditFlags.cs | 3 +- .../Controls/Options/ImGuiComboFlags.cs | 3 +- .../Controls/Options/ImGuiCond.cs | 3 +- .../Controls/Options/ImGuiFocusedFlags.cs | 3 +- .../Controls/Options/ImGuiHoveredFlags.cs | 3 +- .../Controls/Options/ImGuiInputTextFlags.cs | 3 +- .../Controls/Options/ImGuiKey.cs | 3 +- .../Controls/Options/ImGuiMouseButton.cs | 3 +- .../Controls/Options/ImGuiMouseCursor.cs | 3 +- .../Controls/Options/ImGuiPopupFlags.cs | 3 +- .../Controls/Options/ImGuiSelectableFlags.cs | 3 +- .../Controls/Options/ImGuiSliderFlags.cs | 3 +- .../Controls/Options/ImGuiStyleVar.cs | 3 +- .../Controls/Options/ImGuiTabBarFlags.cs | 3 +- .../Controls/Options/ImGuiTabItemFlags.cs | 3 +- .../Controls/Options/ImGuiTableBgTarget.cs | 3 +- .../Controls/Options/ImGuiTableColumnFlags.cs | 3 +- .../Controls/Options/ImGuiTableFlags.cs | 3 +- .../Controls/Options/ImGuiTableRowFlags.cs | 3 +- .../Controls/Options/ImGuiTreeNodeFlags.cs | 3 +- .../Controls/Options/ImGuiWindowFlags.cs | 3 +- .../Drawing/EditorDrawList.cs | 34 +- .../Drawing/ImGui.Drawing.cs | 7 + .../presentation/Inno.Editor.ImGui/ImGui.cs | 23 +- .../Properties/ScriptingApi.cs | 3 +- .../Runtime/EditorDragDropRenderer.cs | 32 +- .../Runtime/EditorGameInputCapture.cs | 31 +- .../Runtime/EditorMenuRenderer.cs | 93 +- .../Runtime/EditorModalHost.cs | 24 +- .../Runtime/EditorModalRenderer.cs | 62 +- .../Runtime/EditorUiInput.cs | 9 + .../Runtime/EditorUiSession.cs | 50 +- .../Runtime/ImGuiEditorRuntime.cs | 63 +- .../Styling/EditorPalette.cs | 7 +- .../Styling/EditorStyleMetrics.cs | 12 +- .../Styling/EditorUiLayout.cs | 8 + .../TextInput/EditorIconCatalog.cs | 10 +- .../Inno.Editor.ImGui/TextInput/ImGuiFont.cs | 9 +- .../Inno.Editor.ImGui/TextInput/ImGuiIcon.cs | 43 + .../TextInput/ImGuiUtf8Buffer.cs | 59 +- .../Widgets/ImGuiWidget.Card.cs | 33 +- .../Widgets/ImGuiWidget.Clipping.cs | 19 + .../Widgets/ImGuiWidget.ContextMenu.cs | 23 +- .../Widgets/ImGuiWidget.Controls.cs | 72 +- .../Widgets/ImGuiWidget.Dialog.cs | 79 +- .../Widgets/ImGuiWidget.DragDrop.cs | 42 +- .../Widgets/ImGuiWidget.Editing.cs | 25 +- .../Widgets/ImGuiWidget.Gizmo.cs | 71 +- .../Widgets/ImGuiWidget.HelpBox.cs | 42 +- .../Widgets/ImGuiWidget.InlineRename.cs | 26 +- .../Widgets/ImGuiWidget.Lifetime.cs | 8 + .../Widgets/ImGuiWidget.MixedValue.cs | 2 + .../Widgets/ImGuiWidget.Panel.cs | 76 +- .../Widgets/ImGuiWidget.Property.cs | 40 +- .../Widgets/ImGuiWidget.Search.cs | 8 + .../Widgets/ImGuiWidget.Selection.cs | 65 +- .../Widgets/ImGuiWidget.Selector.cs | 27 +- .../Widgets/ImGuiWidget.Style.cs | 5 + .../Widgets/ImGuiWidget.Text.cs | 78 +- .../Widgets/ImGuiWidget.Tree.cs | 133 +- .../Widgets/ImGuiWidget.Trend.cs | 7 + .../Materials/MaterialInspectionDrawer.cs | 151 +- .../Materials/MaterialSelectionDrawer.cs | 195 ++- .../Materials/ShaderPropertyInspector.cs | 54 +- .../Nodes/ShaderNodeDrawer.cs | 43 +- .../Nodes/ShaderNodeDrawerRegistry.cs | 24 +- .../Previews/ShaderPreviews.cs | 67 +- .../Actions/HistoryActions.cs | 29 +- .../Actions/SelectionActions.cs | 1 + .../Actions/TogglePanelAction.cs | 15 +- .../Commands/CommandSearchAction.cs | 5 +- .../Commands/CommandSearchModal.cs | 15 +- .../Commands/CommandSearchModule.cs | 10 + .../Exporting/ExportActions.cs | 1 + .../Exporting/ExportInteractionIds.cs | 1 + .../Exporting/ExportWindowModule.cs | 47 +- .../Exporting/GameExportModal.cs | 62 +- .../Exporting/GameExportProgressModal.cs | 8 + .../Exporting/PluginExportModal.cs | 38 +- .../GlobalInteractionIds.cs | 1 + .../Menus/WorkbenchMenuSource.cs | 1 + .../Scripting/ScriptCompilationModal.cs | 8 + .../Settings/DensitySetting.cs | 12 +- .../Settings/FramePacingSettings.cs | 14 +- .../Settings/GlobalSettingsPages.cs | 1 + .../Settings/IconSettings.cs | 28 +- .../Zoom/ActualSizeSetting.cs | 25 +- .../Zoom/EditorZoomModule.cs | 9 +- .../Inno.Editor.Workbench/Zoom/ZoomActions.cs | 13 +- .../Deployment/PlayerContentMetadata.cs | 2 + .../Deployment/StaticPlayerModuleActivator.cs | 15 +- .../Inno.Player.Runtime/GamePlayerHost.cs | 125 +- .../PlayerCommandLineOptions.cs | 19 +- .../Inno.Shell/PollingShellFrameDriver.cs | 2 + .../Inno.Shell/ScheduledShellFrameDriver.cs | 2 + src/composition/shell/Inno.Shell/Shell.cs | 117 +- .../shell/Inno.Shell/ShellState.cs | 7 - .../AnimationClipImporter.cs | 9 +- .../AnimationBindingRuntime.cs | 41 +- .../AnimationClipSnapshot.cs | 5 +- .../AnimationRuntime.cs | 100 +- .../AnimationRuntimeFactory.cs | 8 +- .../animation/Inno.Animation/Animation.cs | 12 +- .../AnimationBindingProvider.cs | 2 +- .../AnimationBindingProviderAttribute.cs | 2 + .../Inno.Animation/AnimationClipAsset.cs | 27 +- .../AnimationPlaybackAllocator.cs | 6 + .../Inno.Animation/AnimationSampling.cs | 9 +- .../Inno.Animation/AnimationTarget.cs | 5 +- .../Inno.Animation/AnimationTypes.cs | 49 +- .../Inno.Animation/IAnimationService.cs | 3 +- .../Inno.Animation/Properties/ScriptingApi.cs | 5 +- .../AssetPipeline.Artifacts.cs | 31 +- .../AssetPipeline.Changes.cs | 90 +- .../AssetPipeline.Discovery.cs | 37 +- .../AssetPipeline.Loading.cs | 75 +- .../AssetPipeline.Mutations.cs | 72 +- .../AssetPipeline.Retirement.cs | 34 +- .../Inno.Assets.Pipeline/AssetPipeline.cs | 59 +- .../Inno.Assets.Pipeline/AssetPipelineMode.cs | 1 - .../AssetPipelineOptions.cs | 5 +- .../AssetSourceMountRecovery.cs | 24 +- .../AssetSourceMountTransaction.cs | 28 +- .../AssetPipelineDiagnosticPublisher.cs | 13 +- .../Editing/AssetSourceStore.cs | 34 +- .../Inno.Assets.Pipeline/EditorAssets.cs | 23 +- .../Importing/Artifacts/AssetArtifactStore.cs | 110 +- .../Artifacts/AssetArtifactWriter.cs | 14 +- .../Importing/AssetCatalogCandidate.cs | 8 + .../Importing/AssetDeploymentScope.cs | 1 - .../Importing/AssetExportContext.cs | 3 +- .../Importing/AssetImportContext.cs | 45 +- ...ssetImportExtensionUnavailableException.cs | 3 +- .../Importing/AssetImportHealthSnapshot.cs | 3 +- .../Importing/AssetImporter.cs | 25 +- .../Importing/AssetLoader.Catalog.cs | 151 +- .../Importing/AssetLoader.Dependencies.cs | 132 +- .../Importing/AssetLoader.Diagnostics.cs | 118 +- .../Importing/AssetLoader.ImportSettings.cs | 134 +- .../Importing/AssetLoader.Importing.cs | 156 +- .../Importing/AssetLoader.Loading.cs | 128 +- .../Importing/AssetLoader.Recovery.cs | 59 +- .../Importing/AssetLoader.Residency.cs | 40 +- .../Importing/AssetLoader.Retirement.cs | 48 +- .../Importing/AssetLoader.RuntimeExport.cs | 108 +- .../Importing/AssetLoader.Saving.cs | 68 +- .../Importing/AssetLoader.SourceChanges.cs | 139 +- .../Importing/AssetLoader.SourceIO.cs | 186 ++- .../Importing/AssetLoader.cs | 112 +- .../Importing/AssetSerializationServices.cs | 25 +- .../Importing/AssetSourceMetadataStage.cs | 14 +- .../Importing/Building/AssetBuildContext.cs | 4 +- .../Importing/Building/AssetBuildProcessor.cs | 15 +- .../Building/AssetBuildProcessorRegistry.cs | 12 +- .../Importing/Catalog/AssetCatalogStore.cs | 39 +- .../Importing/Catalog/AssetSourceFileStamp.cs | 13 +- .../Importing/Catalog/AssetSourceMeta.cs | 1 - .../Diagnostics/AssetDiagnosticPublisher.cs | 117 +- .../Importers/BinaryAssetImporter.cs | 4 +- .../Importing/Importers/TextAssetImporter.cs | 7 +- .../Importing/Importing/AssetImportWriter.cs | 27 +- .../Internal/AssetImporterRegistry.cs | 37 +- .../Importing/Internal/AssetMeta.cs | 1 - .../Properties/ScriptingApi.cs | 5 +- .../NativeAssetSourceSerialization.cs | 17 +- .../Sources/AssetChangeBatchNormalizer.cs | 47 + .../Sources/AssetFileEntry.cs | 13 +- .../Sources/AssetFileSystem.cs | 126 +- .../Sources/AssetPipeline.Samples.cs | 51 +- .../Sources/AssetPipeline.SourceMounts.cs | 88 +- .../Sources/AssetSample.cs | 11 +- .../Sources/AssetSampleImportTransaction.cs | 60 +- .../Sources/AssetSampleSnapshot.cs | 73 +- .../Sources/AssetSampleSourceRewriter.cs | 4 + .../Sources/AssetSourceMount.cs | 4 +- .../Sources/Filtering/AssetSourcePolicy.cs | 25 +- .../Sources/IAssetSourceSnapshot.cs | 5 +- .../Sources/Watching/AssetWatcher.cs | 36 +- .../Artifacts/ArtifactRetention.cs | 11 +- .../Inno.Assets/Artifacts/AssetArtifactKey.cs | 10 +- .../assets/Inno.Assets/AssetDependency.cs | 3 +- .../assets/Inno.Assets/AssetImportStatus.cs | 5 - src/content/assets/Inno.Assets/AssetInfo.cs | 2 + src/content/assets/Inno.Assets/AssetObject.cs | 21 +- src/content/assets/Inno.Assets/AssetPath.cs | 27 +- .../assets/Inno.Assets/AssetReferenceKind.cs | 1 + .../assets/Inno.Assets/AssetSourceKind.cs | 1 - .../Inno.Assets/Changes/AssetChangeKind.cs | 6 - .../Inno.Assets/Properties/ScriptingApi.cs | 5 +- .../Runtime/AssetDatabase.Residency.cs | 94 +- .../Inno.Assets/Runtime/AssetDatabase.cs | 194 ++- .../Runtime/AssetExecutionContext.cs | 3 +- .../Inno.Assets/Runtime/AssetResidency.cs | 15 +- .../assets/Inno.Assets/Runtime/Assets.cs | 26 +- .../Inno.Assets/Runtime/IAssetLookup.cs | 6 +- .../Inno.Assets/Runtime/ResidencyLease.cs | 13 +- .../AssetDependencyCollection.cs | 24 +- .../Serialization/AssetDependencyConverter.cs | 6 +- .../Serialization/AssetObjectConverter.cs | 21 +- .../Serialization/AssetPropertySnapshot.cs | 6 + .../AssetSerializationContext.cs | 1 - .../Serialization/IAssetReferenceResolver.cs | 34 +- .../assets/Inno.Assets/Types/BinaryAsset.cs | 6 +- .../assets/Inno.Assets/Types/TextAsset.cs | 6 +- .../deployment/Inno.Content/ContentEntry.cs | 6 + .../deployment/Inno.Content/ContentKey.cs | 20 +- .../Inno.Content/ContentPackDescriptor.cs | 2 + .../Inno.Content/ContentPackIndex.cs | 4 + .../Inno.Content/ContentPackIndexCodec.cs | 21 +- .../Inno.Content/ContentPackReader.cs | 36 +- .../Inno.Content/ContentReadLease.cs | 2 +- .../Inno.Content/PackContentStore.cs | 17 + .../Inno.References/ContentReadScope.cs | 20 +- .../IReferenceRecoveryParticipant.cs | 1 - .../Inno.References/ReferenceCatalog.cs | 15 +- .../Inno.References/ReferenceDescriptor.cs | 2 + .../Inno.References/ReferenceKey.cs | 4 + .../Inno.References/ReferenceKindId.cs | 2 + .../ReferenceRecoveryTransaction.cs | 40 +- .../Inno.References/ReferenceResolution.cs | 2 + .../ReferenceResolutionState.cs | 4 - .../EngineResourceEnvelope.cs | 6 +- .../Importers/PrefabAssetImporter.cs | 23 +- .../Importers/SceneAssetImporter.cs | 23 +- .../Inno.Scene/Assets/EngineAssetContent.cs | 2 + .../scene/Inno.Scene/Assets/PrefabAsset.cs | 17 +- .../scene/Inno.Scene/Assets/SceneAsset.cs | 13 +- .../Concrete/MissingGameComponent.cs | 8 +- .../Inno.Scene/Concrete/MissingGameSystem.cs | 8 +- .../scene/Inno.Scene/Concrete/Transform.cs | 38 +- .../scene/Inno.Scene/Core/EngineObject.cs | 24 +- .../scene/Inno.Scene/Core/GameBehavior.cs | 52 +- .../scene/Inno.Scene/Core/GameComponent.cs | 11 +- .../scene/Inno.Scene/Core/GameObject.cs | 58 +- .../scene/Inno.Scene/Core/GameScene.cs | 202 ++- .../scene/Inno.Scene/Core/GameSystem.cs | 70 +- .../scene/Inno.Scene/Core/GameTagCatalog.cs | 27 +- .../Core/GameTagSettingsComposer.cs | 28 +- .../scene/Inno.Scene/Layers/GameLayer.cs | 2 + .../Inno.Scene/Layers/GameLayerCatalog.cs | 75 +- .../Layers/GameLayerCatalogConverter.cs | 11 +- .../Inno.Scene/Layers/GameLayerConverter.cs | 3 +- .../Inno.Scene/Layers/GameLayerDefinition.cs | 3 +- .../scene/Inno.Scene/Layers/GameLayerId.cs | 12 +- .../Inno.Scene/Layers/GameLayerIdConverter.cs | 3 +- .../scene/Inno.Scene/Layers/GameLayerMask.cs | 2 + .../Layers/GameLayerMaskConverter.cs | 3 +- .../Layers/GameLayerSettingsComposer.cs | 56 +- .../Lifecycle/GameBehaviorLifecycleRunner.cs | 68 +- .../Lifecycle/ISceneLifecycleObject.cs | 2 + .../Inno.Scene/Lifecycle/SceneLifecycle.cs | 15 +- .../Lifecycle/SceneSystemScheduler.cs | 118 +- .../Prefabs/PrefabConnectionRecord.cs | 2 +- .../Inno.Scene/Prefabs/PrefabInstanceInfo.cs | 1 - .../Inno.Scene/Prefabs/PrefabOverrideSet.cs | 28 +- .../Prefabs/PrefabStructureOverride.cs | 2 +- .../Inno.Scene/Properties/ScriptingApi.cs | 17 +- .../SceneElementReferenceResolver.cs | 22 +- .../Reloading/SceneReloadDiagnostic.cs | 2 +- .../Reloading/SceneReloadRecovery.cs | 23 +- .../Reloading/SceneReloadService.cs | 8 +- src/content/scene/Inno.Scene/SceneManager.cs | 9 +- src/content/scene/Inno.Scene/SceneWorld.cs | 50 +- .../GameComponentReferenceConverter.cs | 6 +- .../Converters/GameObjectConverter.cs | 99 +- .../Converters/GameSceneConverter.cs | 33 +- .../GameSystemReferenceConverter.cs | 6 +- .../Serialization/PrefabOverrideProcessor.cs | 279 ++-- .../SceneElementSerialization.cs | 87 +- .../Serialization/SceneElementState.cs | 27 +- .../SceneGraph/RestoredSceneGraph.cs | 1 - .../SceneGraph/SceneGraphReferenceMap.cs | 19 +- .../SceneGraph/SceneGraphSerialization.cs | 450 +++--- .../SceneGraph/SceneGraphSourceIds.cs | 16 + .../SceneGraph/ScenePropertyReferenceScope.cs | 31 +- .../SceneGraph/SceneReferenceScope.cs | 29 +- .../ScenePropertySerialization.cs | 23 +- .../Serialization/SceneReloadStateTransfer.cs | 313 ++-- .../Serialization/SceneRestoreCompensation.cs | 30 +- .../SceneSubtreeSerialization.cs | 14 +- .../SceneSubtreeStateConverter.cs | 27 +- .../SceneTypeResolutionException.cs | 5 +- .../SerializedPropertyValueCodec.cs | 8 +- .../Inno.Scene/Service/ActivationService.cs | 5 +- .../Inno.Scene/Service/HierarchyService.cs | 40 +- .../Inno.Scene/Storage/ComponentFactory.cs | 2 + .../scene/Inno.Scene/Storage/SceneStore.cs | 254 ++- .../Storage/SceneStructureSnapshot.cs | 8 + .../Inno.Scene/Storage/SceneTypeCatalog.cs | 55 +- .../DependencyGraph/DependencyGraph.cs | 78 +- .../IndexedObjectStore/IndexedObjectEntry.cs | 3 +- .../IndexedObjectStore/IndexedObjectIndex.cs | 58 +- .../IndexedObjectStore/IndexedObjectKey.cs | 8 +- .../IndexedObjectStore/IndexedObjectQuery.cs | 12 +- .../IndexedObjectStore.Handles.cs | 9 +- .../IndexedObjectStore.Keys.cs | 34 +- .../IndexedObjectStore.OrderedQueries.cs | 65 +- .../IndexedObjectStore.Queries.cs | 27 +- .../IndexedObjectStore/IndexedObjectStore.cs | 18 +- .../KeyOrdering/IKeyOrdering.cs | 6 +- .../KeyOrdering/NullKeyOrdering.cs | 12 +- .../KeyOrdering/SortedKeyOrdering.cs | 5 +- .../KeyStorage/IKeyStorage.cs | 11 +- .../KeyStorage/MultiKeyStorage.cs | 12 +- .../KeyStorage/UniqueKeyStorage.cs | 8 +- .../IIndexedObjectQueryCondition.cs | 3 +- .../IndexedObjectKeyCondition.cs | 4 +- .../IndexedObjectPredicateCondition.cs | 3 +- .../CoroutineScheduler.cs | 62 +- .../core/Inno.Core.Diagnostics/Diagnostic.cs | 14 +- .../DiagnosticCallerResolver.cs | 20 +- .../Inno.Core.Diagnostics/DiagnosticHub.cs | 24 +- .../DiagnosticLocation.cs | 12 +- .../DiagnosticReporter.cs | 23 +- .../DiagnosticSeverity.cs | 2 - .../Inno.Core.Diagnostics/DiagnosticSource.cs | 4 + .../core/Inno.Core.Diagnostics/Diagnostics.cs | 8 +- .../core/Inno.Core.Events/EventDispatcher.cs | 10 + .../core/Inno.Core.Events/EventHub.cs | 8 +- .../Events/ApplicationEvents.cs | 8 +- .../core/Inno.Core.Events/Events/Event.cs | 1 + .../core/Inno.Core.Events/Events/KeyEvents.cs | 16 +- .../Inno.Core.Events/Events/MouseEvents.cs | 18 +- .../Inno.Core.Events/Events/WindowEvents.cs | 5 +- .../core/Inno.Core.Execution/ExecutionSlot.cs | 15 +- .../core/Inno.Core.Execution/LifetimeScope.cs | 66 +- .../OwnerThreadExecution.cs | 12 +- .../Inno.Core.Execution/RetirementBarrier.cs | 21 +- .../RetirementPendingException.cs | 19 +- .../RetirementTimeoutException.cs | 2 +- .../core/Inno.Core.Graphs/GraphDocument.cs | 2 + .../Inno.Core.Graphs/GraphDocumentCodec.cs | 39 +- .../Inno.Core.Graphs/GraphSerializedValue.cs | 2 + .../core/Inno.Core.Graphs/GraphValidation.cs | 159 +- .../Properties/ScriptingApi.cs | 5 +- .../core/Inno.Core.IO/AtomicDirectory.cs | 21 +- .../core/Inno.Core.IO/AtomicFile.cs | 30 +- .../core/Inno.Core.IO/CoordinatedFileLease.cs | 22 +- .../Inno.Core.IO/DirectoryCleanupException.cs | 8 +- .../Inno.Core.IO/FileByteDocumentStore.cs | 4 + src/foundation/core/Inno.Core.IO/FileLease.cs | 36 +- .../core/Inno.Core.IO/FileSystemRename.cs | 6 +- .../core/Inno.Core.IO/OwnedReadStream.cs | 14 + .../core/Inno.Core.IO/PathBoundary.cs | 19 +- .../core/Inno.Core.IO/PhysicalPathResolver.cs | 15 +- .../core/Inno.Core.IO/PosixFilePublication.cs | 12 +- .../Inno.Core.IO/ProcessOwnedDirectory.cs | 109 +- .../core/Inno.Core.IO/ProcessOwnerStamp.cs | 26 +- .../core/Inno.Core.IO/ProcessOwnerState.cs | 2 - .../Inno.Core.IO/ReadOnlyByteDocumentStore.cs | 4 +- .../core/Inno.Core.Identity/Identity.cs | 27 +- .../Inno.Core.Identity/IdentityAllocator.cs | 25 +- .../Inno.Core.Identity/IdentityRegistry.cs | 30 +- .../Properties/ScriptingApi.cs | 5 +- .../core/Inno.Core.Identity/RuntimeIdCodec.cs | 6 + .../Inno.Core.Identity/RuntimeIdentity.cs | 4 + .../core/Inno.Core.Input/KeyCode.cs | 14 +- .../core/Inno.Core.Input/KeyModifier.cs | 4 +- .../core/Inno.Core.Input/MouseButton.cs | 2 +- .../core/Inno.Core.Input/MouseCursor.cs | 3 +- .../Properties/ScriptingApi.cs | 5 +- .../core/Inno.Core.Jobs/JobExecutionMode.cs | 1 - .../core/Inno.Core.Jobs/JobScheduler.cs | 3 +- .../Inno.Core.Jobs/JobSchedulerStatistics.cs | 6 + .../Systems/MainThreadWorkQueue.cs | 26 +- .../Systems/SingleThreadJobSystem.cs | 21 +- .../Systems/WorkStealingJobSystem.cs | 29 +- src/foundation/core/Inno.Core.Layers/Layer.cs | 53 +- .../core/Inno.Core.Layers/LayerStack.cs | 37 +- .../Inno.Core.Logging/DiagnosticLogSink.cs | 30 +- .../core/Inno.Core.Logging/FileLogSink.cs | 12 +- src/foundation/core/Inno.Core.Logging/Log.cs | 31 +- .../core/Inno.Core.Logging/LogDeliveryMode.cs | 1 - .../core/Inno.Core.Logging/LogEntry.cs | 1 - .../core/Inno.Core.Logging/LogLevel.cs | 4 - .../core/Inno.Core.Logging/LogRouter.cs | 49 +- .../Inno.Core.Logging/LogSessionContext.cs | 5 +- .../core/Inno.Core.Logging/Logger.cs | 29 +- .../Properties/ScriptingApi.cs | 5 +- .../core/Inno.Core.Mathematics/Color.cs | 44 +- .../core/Inno.Core.Mathematics/MathHelper.cs | 27 +- .../core/Inno.Core.Mathematics/Matrix.cs | 282 ++-- .../Properties/ScriptingApi.cs | 7 +- .../core/Inno.Core.Mathematics/Quaternion.cs | 112 +- .../core/Inno.Core.Mathematics/Rect.cs | 43 +- .../core/Inno.Core.Mathematics/RectInt.cs | 30 +- .../core/Inno.Core.Mathematics/SimdMath.cs | 6 +- .../core/Inno.Core.Mathematics/Vector2.cs | 23 +- .../core/Inno.Core.Mathematics/Vector2Int.cs | 8 + .../core/Inno.Core.Mathematics/Vector3.cs | 53 +- .../core/Inno.Core.Mathematics/Vector3Int.cs | 9 + .../core/Inno.Core.Mathematics/Vector4.cs | 61 +- .../core/Inno.Core.Mathematics/Vector4Int.cs | 47 +- .../SerializationCollectionGenerator.cs | 124 +- .../SerializationConverterGenerator.cs | 204 ++- .../SerializationMetadataGenerator.cs | 338 +++- .../SerializationMetadataScope.cs | 78 +- .../Capture/SerializationCaptureKeyBuilder.cs | 66 +- .../Context/SerializationContext.cs | 22 +- .../Converters/SerializationConverter.cs | 6 +- .../Converters/TypeRefConverter.cs | 3 +- .../IO/SerializationReader.cs | 20 +- .../IO/SerializationWriter.cs | 67 +- .../BinarySerializationFormat.Capture.cs | 4 + .../BinarySerializationFormat.Sizing.cs | 11 +- .../Internal/BinarySerializationFormat.cs | 37 +- .../Internal/ConverterRegistry.cs | 141 +- .../Internal/PropertySnapshotBinaryFormat.cs | 10 + .../Internal/PropertySnapshotPipeline.cs | 105 +- .../Internal/SerializationArrayCapture.cs | 21 +- .../Internal/SerializationNode.cs | 10 +- .../Internal/SerializationNodeReuse.cs | 24 +- .../Internal/SerializationOperation.cs | 32 +- .../Internal/ValuePipeline.cs | 244 ++- .../Metadata/PropertyVisibility.cs | 12 +- .../SerializationCollectionMetadata.cs | 7 +- .../Metadata/SerializationMemberMetadata.cs | 11 +- .../Metadata/SerializationTypeMetadata.cs | 54 +- .../Metadata/SerializedProperty.cs | 4 + .../StaticSerializationMetadataSource.cs | 13 +- .../Properties/ScriptingApi.cs | 10 +- .../SerializationPropertyRestoreMode.cs | 1 - .../SerializationGeneration.cs | 12 +- .../SerializationRegistry.cs | 60 +- .../SerializationSnapshot.cs | 2 + .../SerializedIdentityRemapper.cs | 35 +- .../IProjectSettingsLookup.cs | 3 +- .../Inno.Core.Settings/ProjectIdentity.cs | 33 +- .../ProjectSettingComposition.cs | 20 +- .../ProjectSettingContracts.cs | 14 +- .../Inno.Core.Settings/ProjectSettings.cs | 181 ++- .../ProjectSettingsExecutionContext.cs | 3 +- .../ProjectSettingsRegistry.cs | 47 +- .../ProjectSettingsStore.cs | 36 +- .../Properties/ScriptingApi.cs | 7 +- .../core/Inno.Core.Settings/Settings.cs | 6 +- .../SettingsDocumentStore.cs | 15 +- .../Catalog/AssemblyCatalogCoordinator.cs | 60 +- .../Catalog/CompositeAssemblyUnloadProbe.cs | 2 + .../Catalog/IAssemblyCatalogSource.cs | 4 + .../Catalog/IModuleSource.cs | 7 + .../Catalog/ModuleCatalogContribution.cs | 19 +- .../Catalog/ModuleSourceContext.cs | 14 +- .../Metadata/AssemblyDomain.cs | 2 - .../Metadata/AssemblyExtensions.cs | 14 +- .../Metadata/AssemblyScope.cs | 1 - .../Inno.Extensibility.Modules/ModuleHost.cs | 426 +++-- .../Modules/AssemblyModuleEntry.cs | 9 +- .../Reloading/AssemblyReloadContext.cs | 16 +- .../Reloading/AssemblyReloadSession.cs | 8 +- .../AssemblyUnloadBarrier.cs | 28 +- .../AssemblyUnloadBarrierState.cs | 2 - .../AssemblyUnloadException.cs | 15 +- .../GenerationCoordinator.cs | 80 +- .../IGenerationChange.cs | 4 + .../IGenerationPublication.cs | 5 +- .../Properties/ScriptingApi.cs | 5 +- .../TypeCache/ITypeCatalogSource.cs | 1 - .../TypeCache/TypeCacheBuildException.cs | 3 +- .../TypeCache/TypeCacheReloadContext.cs | 10 +- .../TypeCache/TypeCacheSnapshot.cs | 29 +- .../TypeCache/TypeCatalog.cs | 42 +- .../TypeCache/TypeIdentityRegistry.cs | 65 +- .../TypeCache/TypeQueryRegistry.cs | 29 +- .../TypeCache/TypeRef.cs | 15 +- .../Inno.Extensibility.Types/TypeRegistry.cs | 102 +- .../TypeRegistryCoordinator.cs | 64 +- .../ScriptingApiExportAttribute.cs | 9 +- .../ScriptingApiIgnoreAttribute.cs | 17 +- .../ScriptingApiNamespaceAttribute.cs | 4 + .../Inno.Scripting.Api/ScriptingApiScope.cs | 2 - .../RuntimeSubsystem.cs | 73 +- .../RuntimeSubsystemContext.cs | 10 +- .../RuntimeSubsystemDescriptor.cs | 14 + .../RuntimeSubsystemRequirement.cs | 1 - .../Deployment/GameCodeDeployment.cs | 44 +- .../Inno.Runtime/Deployment/GameCodeModule.cs | 2 + .../Deployment/GameRuntimeAssembly.cs | 8 +- .../Deployment/GameRuntimeManifest.cs | 34 +- .../Deployment/GameRuntimeModule.cs | 17 +- .../Deployment/GameRuntimePlugin.cs | 25 +- .../Deployment/RuntimeContentCatalog.cs | 6 + .../Deployment/RuntimeManifestEnvelope.cs | 40 +- .../engine/Inno.Runtime/Execution/Time.cs | 16 +- .../engine/Inno.Runtime/Hosting/EngineHost.cs | 34 +- .../Inno.Runtime/Hosting/EngineHostBuilder.cs | 17 +- .../Hosting/RuntimeJobExecutionMode.cs | 1 - .../Inno.Runtime/Hosting/RuntimeSession.cs | 98 +- .../Hosting/RuntimeSessionKind.cs | 2 - .../Hosting/RuntimeSessionOptions.cs | 5 +- .../Inno.Runtime/Hosting/SessionLogSink.cs | 4 + .../Presentation/GamePresentationSettings.cs | 6 +- .../Inno.Runtime/Properties/ScriptingApi.cs | 11 +- .../StaticAssemblyCatalogSource.cs | 13 +- .../Registration/StaticModuleSource.cs | 21 +- .../Registration/StaticTypeCatalogSource.cs | 72 +- .../Subsystems/RuntimeSubsystemPipeline.cs | 118 +- .../Subsystems/SceneRuntimeSubsystem.cs | 6 + .../RuntimeRegistrationDiagnostics.cs | 19 +- .../Registration/RuntimeFactoryGenerator.cs | 53 +- .../RuntimeModuleCatalogGenerator.cs | 307 +++- .../RuntimeTypeCatalogGenerator.cs | 147 +- .../RuntimeSubsystemGenerator.cs | 144 +- .../Inno.Plugins.Authoring/PluginCatalog.cs | 29 +- .../PluginEnvironment.cs | 170 +- .../PluginRecoveryParticipant.cs | 6 +- .../PluginSourceModels.cs | 22 +- .../PluginSourceService.cs | 239 ++- .../Properties/ScriptingApi.cs | 5 +- .../plugins/Inno.Plugins/PluginManifest.cs | 34 +- .../Assets/ScriptAssemblyDefinitionAsset.cs | 7 +- .../Assets/ScriptAssemblyScope.cs | 1 - .../Assets/ScriptSourceAsset.cs | 6 +- .../Assets/ScriptSourceTypeManifest.cs | 8 +- .../Compilation/CSharpSampleSourceRewriter.cs | 47 +- .../Compilation/FrameworkReferenceResolver.cs | 17 +- .../LogicalScriptingApiAnalyzer.cs | 148 +- .../Compilation/ScriptApiArtifactCache.cs | 8 +- .../Compilation/ScriptApiCatalog.cs | 152 +- .../ScriptApiDocumentationBuilder.cs | 108 +- .../Compilation/ScriptApiMap.cs | 10 +- .../Compilation/ScriptApiMapBuilder.cs | 8 +- .../Compilation/ScriptApiReferenceBuilder.cs | 137 +- .../Compilation/ScriptApiStubSourceBuilder.cs | 386 +++-- .../Compilation/ScriptApiUsingRewriter.cs | 96 +- .../Compilation/ScriptArtifactCache.cs | 21 +- .../ScriptAuthoringAnnotationRewriter.cs | 16 +- .../Compilation/ScriptCompilationResult.cs | 13 +- .../ScriptCompilationStageTiming.cs | 4 + .../ScriptCompilerCacheSerialization.cs | 7 +- .../Compilation/ScriptCompilerEngine.cs | 484 +++--- .../ScriptDeploymentReferenceResolver.cs | 21 +- .../Compilation/ScriptDiagnostic.cs | 1 + .../ScriptIdePluginReferenceBuilder.cs | 67 +- .../Compilation/ScriptModuleDeployment.cs | 6 +- .../Compilation/ScriptProjectGenerator.cs | 247 +-- .../Compilation/ScriptSourceLocations.cs | 14 +- .../Compilation/ScriptSourceSet.cs | 320 ++-- .../Compilation/ScriptStaticMemberRewriter.cs | 14 +- .../Compilation/ScriptTypeAnalyzer.cs | 181 ++- .../Compilation/ScriptTypeIdentity.cs | 2 + .../SerializablePropertyOrderRewriter.cs | 22 +- .../Importers/CSharpScriptImporter.cs | 35 +- .../ScriptAssemblyDefinitionImporter.cs | 19 +- .../ScriptCompilationInputs.cs | 6 +- .../Inno.Scripting.Compiler/ScriptCompiler.cs | 50 +- .../IScriptReloadCoordinator.cs | 3 +- .../Inno.Scripting.Reload/ScriptReloadHost.cs | 399 +++-- .../ScriptReloadOptions.cs | 1 + .../Inno.Audio.Assets/AudioClipImporter.cs | 50 +- .../Inno.Audio.Runtime/AudioClipCache.cs | 104 +- .../Inno.Audio.Runtime/AudioClipRequest.cs | 15 +- .../Inno.Audio.Runtime/AudioContentOwner.cs | 53 +- .../AudioDeviceCandidate.cs | 2 + .../AudioExtensionRegistry.cs | 29 +- .../Inno.Audio.Runtime/AudioMixerOwner.cs | 66 +- .../audio/Inno.Audio.Runtime/AudioRuntime.cs | 87 +- .../Inno.Audio.Runtime/AudioRuntimeFactory.cs | 8 +- .../Inno.Audio.Runtime/AudioRuntimeOptions.cs | 2 + .../Inno.Audio.Runtime/AudioVoiceOwner.cs | 75 +- .../Inno.Audio.Runtime/MutedAudioDevice.cs | 109 +- src/services/audio/Inno.Audio/Audio.cs | 15 +- .../audio/Inno.Audio/AudioClipAsset.cs | 15 +- .../audio/Inno.Audio/AudioClipDescriptor.cs | 5 +- src/services/audio/Inno.Audio/AudioContent.cs | 4 + .../audio/Inno.Audio/AudioContentProvider.cs | 14 +- .../audio/Inno.Audio/AudioDeviceLimits.cs | 2 + .../Inno.Audio/AudioDeviceVoiceHandle.cs | 2 + src/services/audio/Inno.Audio/AudioMixer.cs | 38 +- src/services/audio/Inno.Audio/AudioTypes.cs | 54 +- .../audio/Inno.Audio/AudioValueValidation.cs | 2 + .../audio/Inno.Audio/AudioVoiceAllocator.cs | 2 + .../Inno.Audio/AudioVoiceCompletedEvent.cs | 2 + src/services/audio/Inno.Audio/IAudioDevice.cs | 2 + .../Inno.Audio/Properties/ScriptingApi.cs | 5 +- .../input/Inno.Input.Runtime/InputRuntime.cs | 4 +- .../Inno.Input.Runtime/InputRuntimeFactory.cs | 8 +- src/services/input/Inno.Input/Input.cs | 4 +- .../input/Inno.Input/InputSnapshot.cs | 5 +- .../Compilation/ShaderCompilation.cs | 80 +- .../Compilation/ShaderGraphArtifact.cs | 59 +- .../Compilation/ShaderGraphCompilation.cs | 219 ++- .../Compilation/ShaderLastGoodStore.cs | 11 +- .../Compilation/ShaderSourceBundle.cs | 109 +- .../Compilation/ShaderStageCompilation.cs | 26 +- .../Compilation/TextureTargetCompiler.cs | 5 +- .../Editing/ShaderGraphSourceStore.cs | 12 +- .../Importing/GeometryAssetImporter.cs | 27 +- .../Importing/GltfJson.cs | 27 +- .../Importing/GltfMeshParser.cs | 206 ++- .../Importing/MaterialAssetImporter.cs | 67 +- .../Importing/ObjMeshParser.cs | 82 +- .../Importing/RenderPipelineAssetImporter.cs | 24 +- .../RenderingAssetFormatException.cs | 8 +- .../Importing/ShaderAssetImporter.cs | 70 +- .../Importing/ShaderFunctionAsset.cs | 5 +- .../Importing/ShaderFunctionImporter.cs | 67 +- .../Importing/ShaderSourceImportSettings.cs | 6 +- .../Importing/TextureAssetImporter.cs | 21 +- .../Deployment/RenderShaderArtifact.cs | 9 +- .../Deployment/RenderShaderArtifactCodec.cs | 93 +- .../Deployment/RenderShaderPassArtifact.cs | 53 +- .../Deployment/RenderShaderStageArtifact.cs | 7 +- .../Deployment/RenderShaderVariant.cs | 36 +- .../Deployment/RenderTargetArtifactPath.cs | 19 +- .../Geometry/GeometryArtifact.cs | 15 +- .../Geometry/GeometryAsset.cs | 13 +- .../Geometry/GeometryAssetRuntime.cs | 5 +- .../Geometry/GeometryData.cs | 5 +- .../Geometry/GeometrySection.cs | 5 +- .../Geometry/GeometryVertex.cs | 5 +- .../Materials/MaterialAsset.cs | 33 +- .../Materials/MaterialMetadataEntry.cs | 7 +- .../Materials/MaterialPassResolution.cs | 7 +- .../Materials/MaterialPassResolver.cs | 24 +- .../Materials/MaterialPropertyBlock.cs | 11 +- .../Materials/MaterialPropertyEntry.cs | 9 +- .../Materials/MaterialValue.cs | 10 +- .../Pipelines/RenderFeatureConfiguration.cs | 11 +- .../Pipelines/RenderPipelineAsset.cs | 8 +- .../SerializedRenderExtensionState.cs | 7 +- ...SerializedRenderExtensionStateConverter.cs | 8 +- .../Shaders/ShaderAsset.cs | 18 +- .../Shaders/ShaderContractId.cs | 7 +- .../Shaders/ShaderDefinition.cs | 11 +- .../Shaders/ShaderDefinitionSnapshot.cs | 29 +- .../Shaders/ShaderDefinitionValidator.cs | 59 +- .../Shaders/ShaderDiagnostic.cs | 5 +- .../Shaders/ShaderKeywordDefinition.cs | 7 +- .../Shaders/ShaderMetadataEntry.cs | 7 +- .../Shaders/ShaderPassDefinition.cs | 7 +- .../Shaders/ShaderPassRoleId.cs | 7 +- .../Shaders/ShaderPropertyBindingOwner.cs | 7 +- .../Shaders/ShaderPropertyDefinition.cs | 47 +- .../Shaders/ShaderRenderState.cs | 10 +- .../Shaders/ShaderSourceLocation.cs | 6 +- .../Shaders/ShaderTechniqueDefinition.cs | 11 +- .../Shaders/ShaderTechniqueId.cs | 7 +- .../Shaders/ShaderTechniquePass.cs | 9 +- .../Textures/IRenderTextureArtifactSource.cs | 3 +- .../RenderTextureArtifactReference.cs | 8 +- .../Textures/RenderTextureArtifactSlot.cs | 3 +- .../Textures/TextureAsset.cs | 18 +- .../Textures/TextureColorSpace.cs | 7 +- .../ContentRenderTargetArtifactProvider.cs | 29 +- .../IRenderTargetArtifactProvider.cs | 3 +- .../Deployment/RenderTargetArtifactStatus.cs | 4 - .../GraphicsSettings.cs | 16 +- .../Models/IRenderModel.cs | 7 +- .../Models/RenderModelExtensionAttribute.cs | 7 +- .../Models/RenderModelOutput.cs | 10 +- .../Models/RenderOutputInput.cs | 30 +- .../Models/RenderOutputLayer.cs | 12 +- .../Models/RenderOutputRoute.cs | 13 +- .../Models/RenderOutputSession.cs | 25 +- .../Models/ViewContent.cs | 24 +- .../Pipelines/RenderExtensionStateContext.cs | 3 +- .../Pipelines/RenderFeatureContext.cs | 5 +- .../RenderFeatureExtensionAttribute.cs | 5 +- .../Pipelines/RenderPipeline.cs | 11 +- .../Pipelines/RenderPipelineContext.cs | 5 +- .../RenderPipelineExtensionAttribute.cs | 5 +- .../Pipelines/RenderPipelineFeature.cs | 7 +- .../Pipelines/RenderResourceMap.cs | 13 +- .../RenderExtensionRegistry.cs | 94 +- .../RenderFrameScratch.cs | 2 +- .../RenderFrameUploadService.cs | 53 +- .../RenderGeometryOwner.cs | 61 +- .../RenderLayerCompositor.cs | 94 +- .../RenderMaterialOwner.cs | 316 +++- .../RenderPipelineGeneration.cs | 2 + .../RenderPresentationComposer.cs | 15 +- .../RenderReadbackOwner.cs | 17 +- .../RenderResourceCache.cs | 19 +- .../RenderResourceLimits.cs | 3 + .../RenderResourceService.cs | 184 ++- .../RenderResourceStatistics.cs | 12 + .../RenderRetirementQueue.cs | 2 + .../RenderRuntime.Contributors.cs | 19 +- .../RenderRuntime.Diagnostics.cs | 47 +- .../RenderRuntime.Frames.cs | 122 +- .../RenderRuntime.Models.cs | 82 +- .../RenderRuntime.Pipelines.cs | 156 +- .../RenderRuntime.Presentation.cs | 129 +- .../RenderRuntime.Requests.cs | 87 +- .../RenderRuntime.Retirement.cs | 23 +- .../Inno.Rendering.Runtime/RenderRuntime.cs | 60 +- .../RenderRuntimeFactory.cs | 8 +- .../RenderTargetStore.cs | 36 +- .../Requests/IRenderRequestSink.cs | 3 +- .../Requests/RenderFrameData.cs | 20 +- .../Requests/RenderRequest.cs | 5 +- .../Requests/RenderRequestProvider.cs | 17 +- .../Resources/IRenderResourceService.cs | 7 +- .../Resources/RenderGeometry.cs | 9 +- .../Resources/RenderGeometrySection.cs | 7 +- .../Resources/RenderMaterialPass.cs | 55 +- .../Resources/RenderPersistentResourceId.cs | 7 +- .../Resources/RenderResourceProvider.cs | 33 +- .../Resources/RenderTextureSubresourceData.cs | 9 +- .../Compilation/ShaderBuiltinNodeCompilers.cs | 120 +- .../Compilation/ShaderGraphLoweringRequest.cs | 22 +- .../Compilation/ShaderNodeCompiler.cs | 17 +- .../Compilation/ShaderNodeCompilerCatalog.cs | 103 +- .../Compilation/ShaderNodeCompilerRegistry.cs | 10 +- .../Compilation/ShaderRerouteNodeCompiler.cs | 2 + .../Compilation/ShaderStorageNodeCompilers.cs | 53 +- .../Compilation/ShaderValueNodeCompilers.cs | 33 +- .../Documents/ShaderGraphBindings.cs | 185 ++- .../Documents/ShaderGraphClipboard.cs | 114 +- .../Documents/ShaderGraphDocument.cs | 28 +- .../Documents/ShaderGraphLiteral.cs | 41 +- .../Documents/ShaderGraphNodes.cs | 186 ++- .../Documents/ShaderGraphProgram.cs | 5 + .../Documents/ShaderGraphProgramCompiler.cs | 296 +++- .../Documents/ShaderGraphPrograms.cs | 42 +- .../Documents/ShaderGraphTemplates.cs | 60 +- .../Documents/ShaderGraphType.cs | 57 +- .../Documents/ShaderGraphValueConverters.cs | 31 +- .../Intermediate/ShaderIrBlock.cs | 22 +- .../ShaderIrBuilder.ControlFlow.cs | 18 +- .../Intermediate/ShaderIrBuilder.Resources.cs | 28 +- .../Intermediate/ShaderIrBuilder.cs | 72 +- .../Intermediate/ShaderIrSemanticHash.cs | 6 + .../Intermediate/ShaderIrStage.cs | 85 +- .../Intermediate/ShaderStorageType.cs | 25 +- .../Sources/IShaderSourceFrontend.cs | 14 +- .../Sources/ShaderSourceFrontendCatalog.cs | 76 +- .../Sources/ShaderSourceFrontendRegistry.cs | 10 +- .../Sources/ShaderSourceFunction.cs | 29 +- .../Sources/ShaderSourceModuleAnalysis.cs | 34 +- .../Sources/ShaderSourceNodeDefinition.cs | 35 +- .../Sources/ShaderSourceType.cs | 31 +- .../Targets/ShaderTarget.cs | 6 +- .../Targets/ShaderTargetRegistry.cs | 11 +- .../Templates/ShaderGraphTemplate.cs | 33 +- .../Templates/ShaderGraphTemplateRegistry.cs | 19 +- .../Device/ComputePipelineDescriptor.cs | 1 - .../Device/GraphicsCapabilities.cs | 57 +- .../Device/GraphicsPipelineDescriptor.cs | 1 - .../Inno.Rendering/Device/IRenderDevice.cs | 3 +- .../Device/PersistentBufferDescriptor.cs | 9 +- .../Device/RecordedRenderCommandBuffer.cs | 27 +- .../RecordedRenderCommandEncoder.Replay.cs | 96 +- .../Device/RecordedRenderCommandEncoder.cs | 3 +- .../Inno.Rendering/Device/RenderBlendState.cs | 13 +- .../Device/RenderBufferUploads.cs | 21 +- .../Inno.Rendering/Device/RenderCommands.cs | 17 +- .../Device/RenderRasterState.cs | 5 +- .../Inno.Rendering/Device/RenderResources.cs | 33 +- .../Device/RenderSamplerState.cs | 13 +- .../Device/RenderShaderBindingDescriptor.cs | 7 +- .../Device/RenderStencilState.cs | 11 +- .../Device/RenderTextureReadback.cs | 4 + .../Device/RenderVertexLayout.cs | 17 +- .../Graph/CompiledRenderGraph.cs | 29 +- .../Graph/ComputePassBuilder.cs | 40 +- .../Inno.Rendering/Graph/CopyPassBuilder.cs | 27 +- .../Inno.Rendering/Graph/RasterPassBuilder.cs | 45 +- .../Graph/RenderGraphBuilder.Mutations.cs | 26 +- .../Graph/RenderGraphBuilder.cs | 55 +- .../Graph/RenderGraphCompiler.cs | 70 +- .../Graph/RenderGraphDependencyAnalysis.cs | 30 +- .../Graph/RenderGraphMutationScope.cs | 2 + .../Graph/RenderGraphNameScope.cs | 3 +- .../Graph/RenderGraphResourceAllocation.cs | 50 +- .../Graph/RenderGraphScheduling.cs | 2 +- .../Inno.Rendering/Graph/RenderGraphTypes.cs | 16 +- .../Graph/RenderGraphValidator.cs | 501 +++--- .../Inno.Rendering/Graph/RenderPassBuilder.cs | 13 +- .../IRenderFrameUploadService.cs | 1 - .../Shaders/GraphicsProgramArtifactCodec.cs | 45 +- .../Inno.Rendering/Shaders/ShaderInterface.cs | 2 - .../Shaders/ShaderInterfaceBinding.cs | 8 +- .../Shaders/ShaderProgramKind.cs | 7 +- .../Shaders/ShaderPropertyBindingKind.cs | 7 +- .../Shaders/ShaderPropertyId.cs | 7 +- .../Shaders/ShaderPropertyType.cs | 7 +- .../Inno.Rendering/Shaders/ShaderStage.cs | 7 +- .../Inno.Rendering/Targets/RenderTarget.cs | 1 - .../Inno.Rendering/Targets/RenderTexture.cs | 1 - .../Inno.Rendering/Views/RenderViewport.cs | 1 - .../Inno.Storage.Runtime/StorageRuntime.cs | 36 +- .../StorageRuntimeFactory.cs | 8 +- src/services/storage/Inno.Storage/Storage.cs | 18 +- .../storage/Inno.Storage/StorageKey.cs | 15 +- .../storage/Inno.Storage/StorageScope.cs | 10 +- .../text/Inno.Text.Assets/FontImporter.cs | 8 +- .../text/Inno.Text.Runtime/TextRuntime.cs | 17 +- .../Inno.Text.Runtime/TextRuntimeFactory.cs | 6 +- src/services/text/Inno.Text/FontAsset.cs | 6 +- src/services/text/Inno.Text/Text.cs | 10 +- src/services/text/Inno.Text/TextTypes.cs | 34 + .../ui/Inno.UI.Assets/UiDocumentFrontend.cs | 40 +- .../UiDocumentImportSettings.cs | 1 + .../ui/Inno.UI.Assets/UiDocumentImporter.cs | 40 +- src/services/ui/Inno.UI.Runtime/UiRuntime.cs | 66 +- .../ui/Inno.UI.Runtime/UiRuntimeFactory.cs | 6 +- src/services/ui/Inno.UI/IUiBackend.cs | 18 + src/services/ui/Inno.UI/IUiService.cs | 18 +- src/services/ui/Inno.UI/UI.cs | 50 +- .../ui/Inno.UI/UiBackendCapabilities.cs | 4 +- src/services/ui/Inno.UI/UiDocumentAsset.cs | 28 +- src/services/ui/Inno.UI/UiDocumentFontFace.cs | 7 + src/services/ui/Inno.UI/UiFontRegistration.cs | 9 +- src/services/ui/Inno.UI/UiIdentifiers.cs | 4 + src/services/ui/Inno.UI/UiRendering.cs | 43 +- src/services/ui/Inno.UI/UiTypes.cs | 24 +- .../AnimationBindingTests.cs | 47 +- .../AnimationRuntimeTests.cs | 73 +- .../AssetFileSystemChangeTests.cs | 18 +- .../AssetFileSystemTests.cs | 34 +- .../AssetLoaderTests.cs | 763 ++++++--- .../ImportSettingsTests.cs | 52 +- .../ImporterIntegrationTests.cs | 44 +- .../SettingsReferenceTests.cs | 85 +- .../Inno.Assets.Tests/AssetCoreTests.cs | 30 +- .../AssetExecutionContextTests.cs | 24 +- .../Inno.Assets.Tests/AssetResidencyTests.cs | 37 +- .../AssetRuntimeOwnerTests.cs | 14 +- .../Inno.Assets.Tests/AssetTypesTests.cs | 3 +- .../ResidencyRetirementTests.cs | 82 +- .../DuplicateImporters.cs | 9 +- .../AudioClipImporterTests.cs | 30 +- .../AudioRuntimeTests.cs | 346 ++-- .../LeaseAudioTestSource.cs | 1 + .../AudioContentContractTests.cs | 6 +- .../Inno.Audio.Tests/AudioContractTests.cs | 57 +- .../AudioScriptingApiTests.cs | 55 +- .../AudioValueValidationTests.cs | 16 +- .../BgfxCompositionProgramProviderTests.cs | 41 +- .../BgfxDeviceTests.cs | 173 +- .../BgfxImGuiColorContractTests.cs | 14 +- .../BgfxProcessLifetimeTests.cs | 17 +- .../BgfxShutdownTests.cs | 28 +- .../BgfxSurfaceIntegrationTests.cs | 43 +- .../BgfxSurfaceRetirementTests.cs | 39 +- .../NativeHostFixture.cs | 13 +- .../NativeWindowTestHost.cs | 19 +- .../BgfxToolchainTests.cs | 139 +- .../ToolRunnerTests.cs | 7 +- .../BgfxNativeProfileTests.cs | 32 +- .../BgfxShaderProfileTests.cs | 64 +- .../BgfxShaderTargetTests.cs | 16 +- .../ToolRunnerTests.cs | 2 - .../Inno.Testing.Bgfx/ShaderProfileFixture.cs | 65 +- .../ContentCacheCancellationTests.cs | 10 +- .../ContentCacheConcurrencyTests.cs | 8 +- .../ContentCacheFixture.cs | 27 +- .../ContentCacheIntegrityTests.cs | 4 +- .../ContentCacheProcessTests.cs | 24 +- .../ContentCachePublicationTests.cs | 14 +- .../ContentCacheRetirementTests.cs | 2 +- .../Inno.Native.ImGui.Tests/ImGuiInitTests.cs | 5 +- .../ImGuiPlatformCallbackTests.cs | 10 +- .../ImGuizmoInitTests.cs | 2 +- .../EncodedAudioTestSource.cs | 1 + .../EncodedContentTests.cs | 39 +- .../MiniAudioDeviceTests.cs | 174 +- .../UiServiceTests.cs | 168 +- .../HostIntegrationTests.cs | 35 +- .../NativeHostFixture.cs | 13 +- .../NativeSurfaceLifetimeTests.cs | 12 +- .../NativeWindowTestHost.cs | 38 +- .../Sdl3WindowOperationsTests.cs | 20 +- .../WindowOwnershipTests.cs | 37 +- .../WindowSurfaceTests.cs | 21 +- .../NativeDllLoaderTests.cs | 15 +- .../BindingDefinitionTests.cs | 5 +- .../BindingGenerationBatchTests.cs | 70 +- .../BindingGenerationProcessTests.cs | 76 +- .../BindingMaterializationTests.cs | 21 +- .../BindingSelectionLifetimeTests.cs | 113 +- .../NativeBindingGenerationTests.cs | 322 ++-- .../NativeBindingProfileTests.cs | 62 +- .../ArchitectureVerificationCommandTests.cs | 13 +- .../DevelopmentEntryCommandTests.cs | 2 +- .../DevelopmentEntrySdkSelectionTests.cs | 4 +- .../NativeDependencyDescriptionTests.cs | 25 +- .../ProjectCommandSourceTests.cs | 16 +- .../ScriptCommandTests.cs | 57 +- .../BindingToolchainTaskTests.cs | 15 +- .../CompilerToolBuildScopeTests.cs | 57 +- .../DevelopmentAppHostSdkTests.cs | 56 +- .../DevelopmentEntryBuildTests.cs | 39 +- .../DotNetSdkEnvironmentTests.cs | 26 +- .../FileProductPublicationTests.cs | 93 +- .../GeneratorRestoreScopeTests.cs | 27 +- .../HostRuntimeClosureBuildTests.cs | 114 +- .../ManagedBuildInputSnapshotTests.cs | 278 +++- .../ManagedOutputOwnershipTests.cs | 38 +- .../NativeBindingCompilationTests.cs | 229 ++- .../NativeBindingConfigurationTests.cs | 11 +- .../NativeBindingSelectionBuildTests.cs | 32 +- .../NuGetBindingDependencyTests.cs | 67 +- .../NuGetLoadedIdentityTests.cs | 117 +- .../OwnedRestoreTests.cs | 18 +- .../SdkRestoreTests.cs | 55 +- .../SolutionBootstrapOwnershipTests.cs | 63 +- .../TaskHostPublicationProcess.cs | 108 +- .../TaskHostPublicationTests.cs | 35 +- .../TaskPublisherBootstrapTests.cs | 132 +- .../TaskRegistrationBuildTests.cs | 26 +- .../TaskRestoreEvaluationTests.cs | 129 +- .../TaskRuntimeBuildTests.cs | 159 +- .../ToolchainEnvironmentTests.cs | 10 +- .../ProductNativeCostTests.cs | 41 +- .../EditorShaderProfileTests.cs | 204 ++- .../ProductBindingSelectionTests.cs | 20 +- .../StaticGraphRestoreTests.cs | 84 +- .../BuildCachePublisherTests.cs | 22 +- .../BuildCompositionTests.cs | 108 +- .../BuildTargetCatalogTests.cs | 21 +- .../BuildTestProducts.cs | 20 +- .../GameBuildWorkflowTests.cs | 212 ++- .../GameContentCompilerBindingTests.cs | 3 +- .../ManagedDeploymentTests.cs | 35 +- .../NativeBuildContextTests.cs | 28 +- .../NativeComponentBuildOptionsTests.cs | 71 +- .../NativeRecipeClosureTests.cs | 184 ++- .../PlatformBackendIntegrationTests.cs | 8 +- .../PlatformOwnershipContractTests.cs | 127 +- .../ShaderBuildInputsTests.cs | 22 +- .../ShaderToolSelectionTests.cs | 40 +- .../SupportPackClosureValidationTests.cs | 42 +- .../SupportPackPreparationCacheTests.cs | 41 +- .../SupportPackPublisherTests.cs | 131 +- .../SupportPackWorkflowTests.cs | 58 +- .../Inno.Build.Tests/BuildProfileTests.cs | 22 +- .../BackendPrebuiltArchiveTests.cs | 26 +- .../BuildCacheInventoryProgressTests.cs | 48 +- .../BuildCacheMetadataRetirementTests.cs | 14 +- .../BuildCacheOwnerCatalogTests.cs | 26 +- .../BuildCacheRetirementFailureTests.cs | 22 +- .../BuildCacheRetirementTests.cs | 158 +- .../BuildCacheWorkspaceLinkTests.cs | 36 +- .../BuildOutputOwnershipTests.cs | 69 +- .../DevelopmentBuildProvenanceTests.cs | 76 +- .../ImmutableRegistrationTests.cs | 33 +- .../ManagedProjectGraphCaptureTests.cs | 205 ++- .../NativeArtifactIdentityTests.cs | 87 +- .../NativeArtifactImportTests.cs | 128 +- .../NativeArtifactPublicationTests.cs | 348 +++- .../NativeBindingCompilationTests.cs | 21 +- .../NativeDependencyManifestTests.cs | 212 ++- .../NativeDeploymentIndexTests.cs | 12 +- .../NativeInputBatchTests.cs | 8 +- .../NativeProductExecutorTests.cs | 103 +- .../NativeToolchainPreparationTests.cs | 50 +- .../NativeVerificationPhaseTests.cs | 29 +- .../NativeWorkspaceReuseTests.cs | 104 +- .../ProcessOwnershipTests.cs | 27 +- .../ProductNativeCacheLookupTests.cs | 83 +- .../ProductNativePreparationTests.cs | 148 +- .../ToolchainDiagnosticTests.cs | 20 +- .../ToolchainProcessTests.cs | 38 +- .../UnixFileLinksFactAttribute.cs | 2 + .../BuildPipelineFixture.cs | 171 +- .../PlayerSupportPackFixture.cs | 50 +- .../PackContentStoreTests.cs | 56 +- .../Inno.Content.CacheProbe/Program.cs | 10 +- .../Inno.Content.Testing/ContentTestStore.cs | 31 +- .../DependencyGraphTests.cs | 19 +- .../IndexedObjectStoreTests.cs | 19 +- .../CoroutineRetirementTests.cs | 176 +- .../CoroutineSchedulerTests.cs | 18 +- .../DiagnosticHubTests.cs | 40 +- .../EventDispatchObservationTests.cs | 5 +- .../EventDispatcherBehaviorTests.cs | 28 +- .../ExecutionSlotTests.cs | 3 +- .../LifetimeAdmissionTests.cs | 11 +- .../LifetimeScopeTests.cs | 39 +- .../OwnerThreadExecutionTests.cs | 49 +- .../RetirementFailureTests.cs | 62 +- .../GraphDocumentTests.cs | 6 +- .../GraphValidatorTests.cs | 73 +- .../AtomicFilePublicationTests.cs | 42 +- .../ByteDocumentStoreTests.cs | 20 +- .../CoordinatedFileLeaseTests.cs | 15 +- .../core/Inno.Core.IO.Tests/FileLeaseTests.cs | 8 +- .../FileSystemSafetyTests.cs | 88 +- .../OwnedReadStreamTests.cs | 2 + .../PhysicalPathResolverTests.cs | 4 + .../IdentityAllocatorTests.cs | 29 +- .../JobSystemPerformanceTests.cs | 11 +- .../JobSystemBehaviorTests.cs | 58 +- .../Inno.Core.Layers.Tests/LayerStackTests.cs | 31 +- .../FileLogSinkTests.cs | 28 +- .../InlineLogDeliveryTests.cs | 123 +- .../LoggingBehaviorTests.cs | 30 +- .../VectorMatrixTests.cs | 39 +- .../SerializationBehaviorTests.ArrayKeys.cs | 65 +- .../SerializationBehaviorTests.CaptureKeys.cs | 20 +- .../SerializationBehaviorTests.Concurrency.cs | 2 +- .../SerializationBehaviorTests.Efficiency.cs | 27 +- .../SerializationBehaviorTests.Encoding.cs | 53 +- ...SerializationBehaviorTests.OrdinalReuse.cs | 4 +- .../SerializationBehaviorTests.Snapshots.cs | 18 +- .../SerializationBehaviorTests.cs | 206 ++- .../EditorAudioHostTests.cs | 82 +- .../ExportPresentationTests.cs | 103 +- .../ExportWorkflowTests.cs | 18 +- .../GraphDocumentControllerTests.cs | 79 +- .../EditorApplicationTests.cs | 30 +- .../EditorCommandLineOptionsTests.cs | 10 +- .../EditorScriptProjectionCollection.cs | 4 +- .../RepositoryWikiTests.cs | 70 +- .../DynamicModalTests.cs | 81 +- .../EditorUiSessionTests.cs | 3 +- .../FontCoverageTests.cs | 143 +- .../ImGuiInteractionOptionsTests.cs | 2 +- .../NativeHostFixture.cs | 13 +- .../NativeWindowTestHost.cs | 84 +- .../ViewportMetricsTests.cs | 259 ++- .../ViewportRetirementTests.cs | 128 +- .../WidgetLayoutTests.cs | 208 ++- .../ConditionalInspectionTests.cs | 48 +- .../EditorHistoryTests.cs | 58 +- .../SceneHistoryTests.Selection.cs | 27 +- .../SceneHistoryTests.cs | 174 +- .../LargePanelPerformanceTests.Input.cs | 74 +- .../LargePanelPerformanceTests.Workflows.cs | 45 +- .../LargePanelPerformanceTests.cs | 92 +- .../ConsoleEntryLayoutTests.cs | 24 +- .../ConsolePanelNativeLayoutTests.cs | 63 +- .../ConsoleSearchNativeTests.cs | 20 +- .../ConsoleVirtualizationNativeTests.cs | 37 +- .../DefaultLayoutNativeTests.cs | 19 +- .../EditorGameInputCaptureTests.cs | 19 +- .../EditorLayoutInitializationTests.cs | 6 +- .../EditorPlayModeTests.cs | 97 +- .../EditorPopupLayoutTests.cs | 16 +- .../GraphCanvasNativeTests.cs | 87 +- .../ListPanelKeyboardNativeTests.cs | 6 +- .../MissingSceneSourceTests.cs | 4 +- .../PlayModeLogRetentionTests.cs | 40 +- .../SceneDirtyCaptureTests.cs | 29 +- .../SceneDocumentLifecycleNativeTests.cs | 4 +- .../SettingsApplyNativeTests.cs | 56 +- .../StatisticsPanelNativeTests.cs | 7 +- .../TreeKeyboardOwnershipNativeTests.cs | 17 +- .../VisualScaleMatrixTests.cs | 33 +- .../AssetHistoryTests.cs | 60 +- .../EditorRuntimeTests.Commands.cs | 12 +- .../EditorRuntimeTests.Performance.cs | 45 +- .../EditorRuntimeTests.Selection.cs | 26 +- .../EditorRuntimeTests.Statistics.cs | 7 +- .../EditorRuntimeTests.cs | 190 ++- .../EditorSettingsTests.cs | 78 +- .../GraphCanvasPointerTests.cs | 43 +- .../GraphCanvasPresentationTests.cs | 25 +- .../GraphCanvasViewTests.cs | 3 +- .../NativeClipboard.cs | 3 + .../NativePanelHost.cs | 48 +- .../NativePanelInput.cs | 9 + .../NativeProjectPanelHost.cs | 73 +- .../NativeProjectPanelProbe.cs | 7 +- .../SettingsPanelServices.cs | 31 +- .../AssemblyManagerTests.cs | 135 +- .../HostLoadContextTests.cs | 8 +- .../ModuleRetirementTests.cs | 77 +- .../AssemblyUnloadBarrierTests.cs | 8 +- .../GenerationCoordinatorTests.cs | 153 +- .../AssemblyExtensionsTests.cs | 22 +- .../AssemblyInfo.cs | 6 +- .../RegistryRetirementTests.cs | 23 +- .../TypeCacheTests.cs | 89 +- .../ReloadableExtension.cs | 2 +- .../ReloadableExtension.cs | 2 +- .../editor-ui/ManagedMemorySample.editor.cs | 17 +- .../editor-ui/PanelLifecycle.editor.cs | 68 +- .../Inno.Input.Tests/InputRuntimeTests.cs | 31 +- .../NativeWindowSurfaceTests.cs | 3 +- .../Inno.Input.Tests/ShellFrameDriverTests.cs | 8 +- .../Inno.Input.Tests/ShellLifecycleTests.cs | 80 +- .../BrowserDependencyConsumptionTests.cs | 11 +- .../BrowserSupportPackAbiTests.cs | 5 +- .../BrowserSupportPackTests.cs | 45 +- .../BrowserToolchainTests.cs | 62 +- .../SupportPackValidationTests.cs | 22 +- .../NativeBindingCMakeTests.cs | 67 +- .../ToolchainWorkingDirectoryBuildTests.cs | 35 +- .../WindowsColdPublicationTests.cs | 84 +- .../WindowsNativeWorkspaceTests.cs | 43 +- .../SupportPackValidationTests.cs | 10 +- .../ToolRunnerPathTests.cs | 11 +- .../ToolchainWorkingDirectoryTests.cs | 17 +- .../PluginSourceServiceTests.cs | 239 +-- .../DiscoveryLogger.cs | 17 +- .../NativeProcessHostFixture.cs | 6 + .../NativeProcessTestHostTests.cs | 9 +- .../NativeProcessTestHost.cs | 20 +- .../ContentReadScopeTests.cs | 2 +- .../ReferenceCatalogTests.cs | 43 +- .../ReferenceRecoveryTests.cs | 102 +- .../MeshAndStateTests.cs | 133 +- .../RenderingImporterIntegrationTests.cs | 299 ++-- .../ShaderCompilerTests.cs | 167 +- .../ShaderGraphArtifactTests.cs | 106 +- .../ShaderPublicationTests.cs | 41 +- .../GeometryArtifactTests.cs | 10 +- .../RuntimeAssetSerializationTests.cs | 15 +- ...ontentRenderTargetArtifactProviderTests.cs | 37 +- .../EmptyRenderingKernelTests.cs | 823 ++++++---- ...nderRuntimeGenerationTests.Contributors.cs | 93 +- ...nderRuntimeGenerationTests.Presentation.cs | 26 +- .../ShaderProgramPublicationTests.cs | 147 +- .../RegistryLifetimeCollection.cs | 2 +- .../RenderingBackendRegistrationTests.cs | 19 +- .../ShaderControlFlowIrTests.cs | 165 +- .../ShaderGraphInputDefaultTests.cs | 87 +- .../ShaderGraphLoweringTests.Validation.cs | 61 +- .../ShaderGraphLoweringTests.cs | 175 +- .../ShaderGraphProgramTests.cs | 75 +- .../ShaderGraphSharedProgramTests.cs | 65 +- .../ShaderGraphStorageTests.cs | 98 +- .../ShaderIrBuilderTests.cs | 50 +- .../ShaderIrStageTests.cs | 39 +- .../ShaderResourceIrTests.cs | 155 +- .../ShaderSourceFrontendRegistryTests.cs | 29 +- .../ShaderSourceFrontendTests.cs | 48 +- .../ShaderSourceModuleTests.cs | 103 +- .../ShaderSourceNodeDefinitionTests.cs | 54 +- .../ShaderTargetTests.cs | 50 +- .../ShaderTypedNativeCompilationTests.cs | 227 ++- .../Inno.Rendering.Tests/GraphicsApiTests.cs | 26 +- .../GraphicsProgramArtifactTests.cs | 37 +- .../ParallelCommandRecordingTests.cs | 78 +- .../PipelineResourceTests.cs | 101 +- .../RenderGraphCompilerTests.cs | 549 ++++--- .../RenderGraphMutationTests.cs | 29 +- .../RenderGraphValidationTests.cs | 27 +- .../ReloadableContributor.cs | 10 +- .../ReloadableRenderPipeline.cs | 12 +- .../RuntimeModuleCatalogGeneratorTests.cs | 36 +- .../RuntimeSubsystemGeneratorTests.cs | 55 +- .../SerializationMetadataGeneratorTests.cs | 62 +- .../Inno.Runtime.Tests/AdapterCatalogTests.cs | 54 +- .../AssemblyClassificationTests.cs | 14 +- .../GamePresentationSettingsTests.cs | 29 +- .../PlayerContentSourceTests.cs | 61 +- .../PlayerWithoutFileSystemTests.Adapters.cs | 112 +- .../PlayerWithoutFileSystemTests.Startup.cs | 55 +- .../PlayerWithoutFileSystemTests.cs | 21 +- .../RuntimeRetirementTests.cs | 112 +- .../Inno.Runtime.Tests/RuntimeSessionTests.cs | 124 +- .../RuntimeSubsystemPolicyTests.cs | 73 +- .../StaticDeploymentTests.cs | 22 +- .../StaticGenericFactoryTests.cs | 14 +- .../StaticProjectSettingsTests.cs | 68 +- .../Inno.Scene.Tests/EngineAssetComponents.cs | 5 +- ...ssetIntegrationTests.PropertyReferences.cs | 2 +- .../EngineAssetIntegrationTests.cs | 38 +- .../scene/Inno.Scene.Tests/GameLayerTests.cs | 8 +- .../scene/Inno.Scene.Tests/GameSystemTests.cs | 16 +- .../PluginSceneReloadTests.cs | 67 +- .../Inno.Scene.Tests/SceneFacadeTests.cs | 22 +- .../SceneSerializationTests.CaptureKeys.cs | 3 +- ...SceneSerializationTests.PropertyAliases.cs | 41 +- ...neSerializationTests.PropertyReferences.cs | 37 +- .../SceneSerializationTests.cs | 27 +- .../Inno.Scene.Tests/SceneTestsCollection.cs | 26 +- .../scene/Inno.Scene.Tests/TransformTests.cs | 25 +- .../ReloadableSceneComponent.cs | 2 + .../ControlledSampleAssetImporter.cs | 9 +- .../ControlledSampleSourceRewriter.cs | 13 +- .../EditorStyleMetricsTests.cs | 249 ++- .../EditorViewportCompositionTests.cs | 22 +- .../EditorViewportNavigationTests.cs | 19 +- .../InspectionPipelineTests.cs | 65 +- .../InspectorPresentationLayoutTests.cs | 41 +- .../ProjectSettingsExecutionContextTests.cs | 15 +- .../ScriptingPipelineTests.Progress.cs | 5 +- .../ScriptingPipelineTests.UiLifecycle.cs | 2 +- .../ScriptingPipelineTests.cs | 593 +++++-- .../ShaderEditorWorkflowTests.Performance.cs | 80 +- .../ShaderEditorWorkflowTests.Visual.cs | 8 + .../ShaderEditorWorkflowTests.cs | 358 ++++- .../CSharp14ScriptingTests.cs | 107 +- .../CompilerFixture.cs | 55 +- .../IdeProjectIsolationTests.cs | 39 +- .../ScriptCachePublicationTests.cs | 91 +- .../SdkCompilationInputsTests.cs | 20 +- .../Inno.Testing.Source/TestRepository.cs | 18 +- .../Inno.Storage.Tests/StorageTests.cs | 80 +- .../text/Inno.Text.Tests/TextServiceTests.cs | 25 +- .../AgentDocumentTests.cs | 15 +- .../ArchitectureOutputOwnerTests.cs | 145 +- .../ArchitectureSymbolTests.cs | 201 ++- .../DocumentationExampleTests.cs | 416 ++++- .../DocumentationReferenceTests.cs | 408 ++++- .../DocumentationSourceContractTests.cs | 211 ++- .../IntegrationBoundaryTests.cs | 147 +- .../NativePlatformPolicyTests.cs | 8 +- .../RepositoryInputTests.cs | 7 +- .../TestRepositoryInputsTests.cs | 49 +- .../DocumentationApiSynchronizationTests.cs | 429 +++-- .../DocumentationEvidenceTests.cs | 174 +- .../DocumentationSnapshotTests.cs | 327 +++- .../ValidationConsumerInputTests.cs | 65 +- ...ValidationDocumentationCompilationTests.cs | 83 +- .../ValidationFailureExecutionTests.cs | 23 +- .../ValidationProgressTests.cs | 13 +- .../ValidationRuntimeClosureTests.cs | 49 +- .../ValidationShardExecutionTests.cs | 601 +++++-- .../ValidationSolutionBuildTests.cs | 47 +- .../ValidationSolutionTests.cs | 70 +- .../BackendInputTests.cs | 228 ++- .../ValidationDocumentationInputTests.cs | 35 +- .../ValidationDocumentationTests.cs | 301 +++- .../ValidationExecutionTests.cs | 44 +- .../ValidationPlanningTests.cs | 1046 +++++++++--- .../ValidationDocumentationFixture.cs | 82 +- .../ValidationRepository.cs | 119 +- tests/ui/Inno.UI.Tests/UiRuntimeTests.cs | 115 +- .../AgentDocumentValidator.cs | 23 +- .../AgentLinkValidator.cs | 39 +- .../ArchitectureRules.cs | 726 ++++----- .../AssemblyDocumentationProvider.cs | 8 +- .../DocumentationApiExtractor.cs | 197 ++- .../DocumentationExamples.cs | 263 ++- .../DocumentationExportCache.cs | 53 +- .../DocumentationExportInputs.cs | 26 +- .../DocumentationExportPlan.cs | 135 +- .../DocumentationPackageReferences.cs | 34 +- .../DocumentationPreparedExports.cs | 29 +- .../DocumentationProjectReferences.cs | 262 ++- .../DocumentationReferences.cs | 315 +++- .../DocumentationScriptApi.cs | 299 +++- .../DocumentationScriptReferences.cs | 25 +- .../DocumentationSourceModels.cs | 112 +- .../EditorPresentationSourceValidator.cs | 41 +- .../EditorUiBoundaryValidator.cs | 60 +- .../GenerationCleanupValidator.cs | 19 +- .../MSBuildProjectGraphValidator.cs | 162 +- .../NativeBindingOwnershipValidator.cs | 37 +- .../NativePlatformPolicyValidator.cs | 20 +- .../PackageDependencyBoundaryValidator.cs | 17 +- .../PlatformOwnershipValidator.cs | 114 +- .../PublicApiBoundaryValidator.cs | 195 ++- .../PublicApiDocumentationValidator.cs | 104 +- .../RepositorySourceInventory.cs | 32 +- .../RuntimeContentBoundaryValidator.cs | 25 +- .../UsingPolicyValidator.cs | 29 +- .../DocumentationCatalogReport.cs | 1 + .../DocumentationCommand.cs | 103 +- .../DocumentationEvidence.cs | 95 +- .../DocumentationHit.cs | 4 + .../DocumentationPageInfo.cs | 2 + .../DocumentationSnapshot.cs | 344 +++- .../DocumentationStore.cs | 311 ++-- .../Indexing/DocumentationApiComposition.cs | 246 ++- .../Indexing/DocumentationApiContent.cs | 230 ++- .../Indexing/DocumentationApiFacts.cs | 121 +- .../Indexing/DocumentationApiFragment.cs | 71 +- .../Indexing/DocumentationApiLinks.cs | 33 +- .../Indexing/DocumentationApiNavigation.cs | 99 +- .../Indexing/DocumentationApiPackage.cs | 115 +- .../Indexing/DocumentationApiPresentation.cs | 41 +- .../DocumentationApiSynchronization.cs | 77 +- .../Indexing/DocumentationCatalog.cs | 58 +- .../Indexing/DocumentationMarkdown.cs | 134 +- .../Indexing/DocumentationProjectGuides.cs | 177 +- .../Indexing/DocumentationReferenceStore.cs | 61 +- .../Indexing/DocumentationXml.cs | 142 +- .../ValidationAcceptance.cs | 14 +- .../ValidationBuildInputs.cs | 75 +- .../ValidationCiContracts.cs | 7 +- .../ValidationCommand.cs | 307 +++- .../ValidationCompiledGraph.cs | 27 +- .../ValidationDeliverables.cs | 41 +- .../ValidationDependencyInputs.cs | 92 +- .../ValidationDocumentation.cs | 147 +- .../ValidationDocumentationInputs.cs | 48 +- .../ValidationEntryInputs.cs | 20 +- .../ValidationEnvironment.cs | 104 +- .../ValidationInputs.cs | 268 +++- .../ValidationOutputs.cs | 49 +- .../Inno.Tooling.Validation/ValidationPlan.cs | 8 +- .../ValidationPlanTransport.cs | 48 +- .../ValidationPlanner.Backends.cs | 286 +++- .../ValidationPlanner.cs | 1417 +++++++++++++---- .../ValidationProcess.cs | 50 +- .../ValidationProductInput.cs | 147 +- .../ValidationProfile.cs | 7 +- .../ValidationProject.cs | 43 +- .../ValidationRunner.cs | 801 ++++++++-- .../ValidationShard.cs | 111 +- .../ValidationTestEvidence.cs | 84 +- .../ValidationTestHosts.cs | 45 +- .../ValidationWorkspace.cs | 34 +- 2088 files changed, 71429 insertions(+), 27264 deletions(-) diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs index fb1ea281f..c2c2f7422 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs @@ -1,15 +1,15 @@ -using Inno.Adapter.Modules.DotNet; -using Inno.Adapter.Serialization.DotNet; using System; -using System.Threading; using System.IO; using System.Linq; +using System.Threading; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Diagnostics; -using Inno.Core.Identity; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Extensibility.Modules; @@ -139,7 +139,9 @@ public static void CompileGraphicsProgram( ArgumentException.ThrowIfNullOrWhiteSpace(outputFile); RenderShaderArtifact artifact = CompileArtifact(inputs, workspace, shaderPath, platform, backend, tools, cancellationToken); if (artifact.passes.Count != 1 || artifact.passes[0].programKind != ShaderProgramKind.Raster) + { throw new InvalidDataException("A device graphics program requires exactly one raster pass."); + } RenderShaderPassArtifact pass = artifact.passes[0]; RenderShaderBindingDescriptor[] bindings = pass.shaderInterface.bindings.Select(static binding => new RenderShaderBindingDescriptor( new RenderBindingId(binding.id.value), @@ -155,11 +157,15 @@ public static void CompileGraphicsProgram( uniformType: binding.type == ShaderPropertyType.Matrix4x4 ? RenderUniformType.Matrix4x4 : RenderUniformType.Vector4, count: binding.arrayCount, storageAccess: binding.storageAccess, - nativeName: binding.nativeName)).ToArray(); + nativeName: binding.nativeName + )).ToArray(); var descriptor = new GraphicsPipelineDescriptor( pass.stages.Single(static stage => stage.stage == ShaderStage.Vertex).bytes.Span, pass.stages.Single(static stage => stage.stage == ShaderStage.Fragment).bytes.Span, - bindings, null, pass.rasterState); + bindings, + null, + pass.rasterState + ); byte[] payload = GraphicsProgramArtifactCodec.Encode(descriptor); inputs.VerifyUnchanged(cancellationToken); AtomicFile.WriteAllBytes(Path.GetFullPath(outputFile), payload); @@ -179,7 +185,9 @@ CancellationToken cancellationToken ArgumentException.ThrowIfNullOrWhiteSpace(shaderPath); string scratch = workspace.directory; if (!Directory.Exists(scratch) || Directory.EnumerateFileSystemEntries(scratch).Any()) + { throw new InvalidOperationException("Shader compilation requires a fresh, retained operation directory."); + } string assetRoot = inputs.Materialize(scratch, cancellationToken); var identities = new IdentityAllocator(); using IDisposable identityScope = identities.EnterScope(); @@ -187,25 +195,48 @@ CancellationToken cancellationToken using IDisposable diagnosticScope = diagnostics.EnterScope(); diagnostics.RegisterSink(new DiagnosticOutput()); using var logs = new LogRouter(); - using var modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderArtifactBuilder).Assembly)}); + using var modules = new ModuleHost( + new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderArtifactBuilder).Assembly)} + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - using var assets = new AssetPipeline(modules, types, serialization, identities, diagnostics, logs, - new() { assetRoot = Path.GetFullPath(assetRoot), libraryRoot = Path.Combine(scratch, "Library") }); + using var assets = new AssetPipeline( + modules, + types, + serialization, + identities, + diagnostics, + logs, + new() { assetRoot = Path.GetFullPath(assetRoot), libraryRoot = Path.Combine(scratch, "Library") } + ); AssetPath path = AssetPath.Project(shaderPath); // A fresh source import must succeed. An earlier build artifact never masks current source errors. if (!assets.Import(path)) + { throw new InvalidDataException($"Shader source '{path}' failed to import."); + } ShaderAsset shader = assets.Load(path); GraphicsCapabilities capabilities = platform.Resolve(backend).capabilities; var compiler = new ShaderCompiler(new BgfxShadercToolchain(platform, tools)); ShaderCompileTarget target = compiler.CreateTarget(capabilities); - ShaderCompilationResult result = compiler.CompileGraphAsync(shader, target, RenderShaderVariant.empty, - types, serialization, AssetSerializationContext.Create(assets), assets, cancellationToken).AsTask().GetAwaiter().GetResult(); + ShaderCompilationResult result = compiler.CompileGraphAsync( + shader, + target, + RenderShaderVariant.empty, + types, + serialization, + AssetSerializationContext.Create(assets), + assets, + cancellationToken + ).AsTask().GetAwaiter().GetResult(); foreach (ShaderDiagnostic diagnostic in result.diagnostics) + { Console.Error.WriteLine($"{diagnostic.code}: {diagnostic.message}"); + } if (!result.succeeded || result.artifact is null) + { throw new InvalidDataException("Shader compilation failed; the output was not replaced."); + } Console.WriteLine($"Compiled {path}: {result.artifact.passes.Count} passes, {target.key}"); inputs.VerifyUnchanged(cancellationToken); return result.artifact.CreateRuntimeArtifact(); @@ -222,15 +253,20 @@ private sealed class DiagnosticOutput : IDiagnosticSink public void Replace(DiagnosticReport report) { foreach (Diagnostic diagnostic in report.diagnostics) + { if (diagnostic.severity == DiagnosticSeverity.Error) + { Console.Error.WriteLine($"{diagnostic.code}: {diagnostic.message}"); + } + } } + /// /// Ignores report removal because console output retains no diagnostic state. /// /// /// The diagnostic source whose report was removed. /// - public void Clear(DiagnosticSource source) { } + public void Clear(DiagnosticSource source) {} } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs index 96eecf5cc..80c525830 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs @@ -88,7 +88,9 @@ public void VerifyUnchanged(CancellationToken cancellationToken = default) { string actual = ComputeFingerprint(Discover(m_sourceRoot, cancellationToken), cancellationToken); if (!string.Equals(actual, fingerprint, StringComparison.Ordinal)) + { throw new InvalidDataException("Shader authoring inputs changed during compilation; the candidate cannot be published."); + } } internal string Materialize( @@ -112,11 +114,15 @@ CancellationToken cancellationToken Directory.CreateDirectory(Path.GetDirectoryName(copy)!); using (var reading = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var writing = new FileStream(copy, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { reading.CopyToAsync(writing, cancellationToken).GetAwaiter().GetResult(); + } copies.Add(new NativeBuildInput(input.logicalPath, copy)); } if (ComputeFingerprint(new Inventory([.. copies], m_directories), cancellationToken) != fingerprint) + { throw new InvalidDataException("Shader inputs changed while copying the frozen compilation tree."); + } VerifyUnchanged(cancellationToken); return destination; } @@ -125,14 +131,19 @@ private static string ComputeFingerprint( Inventory inventory, CancellationToken cancellationToken ) => NativeBuildFingerprint.Create( - inventory.directories.Select(static path => "shader-directory/" + path), inventory.files, cancellationToken); + inventory.directories.Select(static path => "shader-directory/" + path), + inventory.files, + cancellationToken + ); private static Inventory Discover( string root, CancellationToken cancellationToken ) { if (!Directory.Exists(root)) + { throw new DirectoryNotFoundException($"Shader authoring root '{root}' does not exist."); + } var pending = new Stack(); List files = []; List directories = []; @@ -146,23 +157,31 @@ CancellationToken cancellationToken foreach (string child in Directory.EnumerateDirectories(directory)) { if (!policy.IsIgnored(Path.GetRelativePath(root, child), isDirectory: true)) + { pending.Push(child); + } } foreach (string path in Directory.EnumerateFiles(directory)) { cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(root, path).Replace('\\', '/'); if (AtomicFile.IsCandidatePath(relative)) + { continue; + } bool metadata = relative.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase); if (!metadata && policy.IsIgnored(relative, isDirectory: false)) + { continue; + } PathBoundary.RequireUnlinkedPath(root, path); files.Add(new NativeBuildInput("shader-source/" + relative, path)); } } - return new Inventory(files.OrderBy(static input => input.logicalPath, StringComparer.Ordinal).ToArray(), - directories.Order(StringComparer.Ordinal).ToArray()); + return new Inventory( + files.OrderBy(static input => input.logicalPath, StringComparer.Ordinal).ToArray(), + directories.Order(StringComparer.Ordinal).ToArray() + ); } private sealed record Inventory( diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs index 4c95ed410..165d313a8 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs @@ -25,7 +25,8 @@ public sealed class BgfxAuthoringProvider : RenderingAuthoringBackendProvider public BgfxAuthoringProvider( BgfxShaderTargetProfile target, ToolRunner? tools = null - ) : base(RenderingBackendId.bgfx) { + ) : base(RenderingBackendId.bgfx) + { ArgumentNullException.ThrowIfNull(target); m_target = target; m_tools = tools; diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs index 953ef8900..75de7454e 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs @@ -7,8 +7,8 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Serialization; -using Inno.Rendering; using Inno.Extensibility.Types; +using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; @@ -68,15 +68,21 @@ ToolRunner tools m_tools = tools; GraphicsApi[] snapshot = backends.Distinct().ToArray(); if (snapshot.Length == 0) + { throw new ArgumentException("At least one Player graphics backend is required.", nameof(backends)); + } if (snapshot.Contains(GraphicsApi.Noop)) + { throw new ArgumentException("A deployable Player cannot target the Noop graphics backend.", nameof(backends)); + } m_assets = assets; m_types = types ?? throw new ArgumentNullException(nameof(types)); m_serialization = serialization; ArgumentNullException.ThrowIfNull(platform); foreach (GraphicsApi backend in snapshot) + { platform.Resolve(backend); + } m_platform = platform; m_backends = snapshot; } @@ -109,7 +115,9 @@ public async ValueTask CompileAsync( ArgumentNullException.ThrowIfNull(context); cancellationToken.ThrowIfCancellationRequested(); if (context.profile.target != target) + { throw new ArgumentException("The content context target does not match the compiler.", nameof(context)); + } ContentSnapshot snapshot = CaptureSnapshot(); string outputRoot = Path.GetFullPath(context.outputDirectory); Directory.CreateDirectory(outputRoot); @@ -120,39 +128,47 @@ public async ValueTask CompileAsync( ShaderCompileTarget target = shaderCompiler.CreateTarget( capabilities, optimize: true, - debugInformation: false); + debugInformation: false + ); foreach (ShaderInput shader in snapshot.shaders) { foreach (RenderShaderVariant variant in shader.variants.OrderBy(static value => value.value, StringComparer.Ordinal)) { cancellationToken.ThrowIfCancellationRequested(); - ShaderCompilationResult result = await shaderCompiler.CompileGraphAsync( + ShaderCompilationResult result = await shaderCompiler + .CompileGraphAsync( shader.asset, target, variant, - m_types, m_serialization, AssetSerializationContext.Create(m_assets), m_assets, - cancellationToken) + m_types, + m_serialization, + AssetSerializationContext.Create(m_assets), + m_assets, + cancellationToken + ) .ConfigureAwait(false); if (!result.succeeded) { string diagnostics = string.Join( Environment.NewLine, - result.diagnostics.Select(static value => $"[{value.code}] {value.message}")); + result.diagnostics.Select(static value => $"[{value.code}] {value.message}") + ); throw new InvalidOperationException( - $"Shader '{shader.asset.assetPath}' failed target compilation for '{backend}':{Environment.NewLine}" + - diagnostics); + $"Shader '{shader.asset.assetPath}' failed target compilation for '{backend}':{Environment.NewLine}" + + diagnostics + ); } string destination = ResolveOutput( outputRoot, - RenderTargetArtifactPath.GetShaderPath( - shader.asset.identity.persistentId, - backend, - variant)); + RenderTargetArtifactPath.GetShaderPath(shader.asset.identity.persistentId, backend, variant) + ); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); - await File.WriteAllBytesAsync( + await File + .WriteAllBytesAsync( destination, RenderShaderArtifactCodec.Encode(result.artifact!.CreateRuntimeArtifact()), - cancellationToken) + cancellationToken + ) .ConfigureAwait(false); } } @@ -165,18 +181,14 @@ await File.WriteAllBytesAsync( byte[] bytes; using (ArtifactLease source = m_assets.AcquireArtifact( texture.reference.assetId, - texture.reference.slot.sourceOutputName)) - { + texture.reference.slot.sourceOutputName + )) { using Stream encoded = source.OpenRead(); - bytes = await textureCompiler.CompileKtxAsync( - encoded, - texture.reference.slot.colorSpace, - cancellationToken) + bytes = await textureCompiler + .CompileKtxAsync(encoded, texture.reference.slot.colorSpace, cancellationToken) .ConfigureAwait(false); } - string destination = ResolveOutput( - outputRoot, - RenderTargetArtifactPath.GetTexturePath(texture.reference)); + string destination = ResolveOutput(outputRoot, RenderTargetArtifactPath.GetTexturePath(texture.reference)); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); await File.WriteAllBytesAsync(destination, bytes, cancellationToken).ConfigureAwait(false); } @@ -185,9 +197,12 @@ await File.WriteAllBytesAsync( private ContentSnapshot CaptureSnapshot() { if (!m_assets.isInitialized) + { throw new InvalidOperationException("BGFX target compilation requires an active authoring Asset database."); + } Dictionary mounts = m_assets.sourceMounts.ToDictionary( - static mount => mount.id); + static mount => mount.id + ); var shaders = new Dictionary(); var textures = new Dictionary(); var materialVariants = new List<(ShaderAsset shader, RenderShaderVariant variant)>(); @@ -197,19 +212,25 @@ private ContentSnapshot CaptureSnapshot() foreach (AssetFileEntry entry in entries) { if (!m_assets.TryGetAssetType(entry.assetPath, out Type? assetType) || assetType is null) + { continue; + } if (typeof(MaterialAsset).IsAssignableFrom(assetType)) { MaterialAsset material = m_assets.Load(entry.assetPath); if (material.shader is not null) + { materialVariants.Add((material.shader, RenderShaderVariant.FromMaterial(material))); + } } if (typeof(ShaderAsset).IsAssignableFrom(assetType)) { ShaderAsset shader = m_assets.Load(entry.assetPath); // Passless graphs are reusable authoring nodes, not executable shaders. if (shader.definition is { passes.Length: > 0 }) + { AddShader(shaders, mounts, shader, RenderShaderVariant.empty); + } } if (typeof(IRenderTextureArtifactSource).IsAssignableFrom(assetType)) { @@ -218,13 +239,16 @@ private ContentSnapshot CaptureSnapshot() } } foreach ((ShaderAsset shader, RenderShaderVariant variant) in materialVariants) + { AddShader(shaders, mounts, shader, variant); + } return new ContentSnapshot( shaders.Values.OrderBy(static value => value.asset.identity.persistentId).ToArray(), textures.Values .OrderBy(static value => value.reference.assetId) .ThenBy(static value => value.reference.slot.id, StringComparer.Ordinal) - .ToArray()); + .ToArray() + ); } private static void AddTextures( @@ -232,7 +256,9 @@ private static void AddTextures( AssetObject asset ) { if (asset is not IRenderTextureArtifactSource source) + { return; + } Guid id = RequireIdentity(asset); var slots = new HashSet(StringComparer.Ordinal); foreach (RenderTextureArtifactSlot slot in source.textureArtifacts) @@ -240,12 +266,14 @@ AssetObject asset if (string.IsNullOrWhiteSpace(slot.id) || string.IsNullOrWhiteSpace(slot.sourceOutputName)) { throw new InvalidOperationException( - $"Texture source asset '{asset.assetPath}' declares an invalid artifact slot."); + $"Texture source asset '{asset.assetPath}' declares an invalid artifact slot." + ); } if (!slots.Add(slot.id)) { throw new InvalidOperationException( - $"Texture source asset '{asset.assetPath}' declares duplicate slot '{slot.id}'."); + $"Texture source asset '{asset.assetPath}' declares duplicate slot '{slot.id}'." + ); } var reference = new RenderTextureArtifactReference(id, asset.contentVersion, slot); textures.Add(new TextureArtifactKey(id, slot.id), new TextureInput(reference)); @@ -272,7 +300,9 @@ private static Guid RequireIdentity(AssetObject asset) { Guid id = asset.identity.persistentId; if (id == Guid.Empty) + { throw new InvalidOperationException($"Runtime asset '{asset.assetPath}' has no persistent identity."); + } return id; } @@ -281,7 +311,9 @@ private static void RequireMount( AssetPath path ) { if (!mounts.ContainsKey(path.source)) + { throw new InvalidOperationException($"Asset source mount '{path.source}' is not active."); + } } private static string ResolveOutput( @@ -291,10 +323,12 @@ string relativePath string result = Path.GetFullPath(Path.Combine(root, relativePath)); string prefix = Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar; StringComparison comparison = OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase - : StringComparison.Ordinal; + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; if (!result.StartsWith(prefix, comparison)) + { throw new InvalidOperationException("A target artifact path escaped its staging directory."); + } return result; } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs index f8cef1c0e..d36cf958e 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs @@ -55,8 +55,10 @@ public BgfxShaderCompilerProfile( ArgumentNullException.ThrowIfNull(computeProfile); string[] snapshot = defines?.ToArray() ?? []; if (snapshot.Any(string.IsNullOrWhiteSpace) || capabilities.backend == GraphicsApi.Noop - || capabilities.Supports(GraphicsCapability.Compute) != !string.IsNullOrWhiteSpace(computeProfile)) + || capabilities.Supports(GraphicsCapability.Compute) != !string.IsNullOrWhiteSpace(computeProfile) + ) { throw new ArgumentException("A shader profile requires valid defines, a renderer and consistent compute support."); + } this.capabilities = capabilities; this.shadercPlatform = shadercPlatform; this.vertexProfile = vertexProfile; @@ -101,7 +103,8 @@ public BgfxShaderCompilerProfile( /// public string key { get; } - internal string GetStageProfile(ShaderStage stage) => stage switch + internal string GetStageProfile(ShaderStage stage) + => stage switch { ShaderStage.Vertex => vertexProfile, ShaderStage.Fragment => fragmentProfile, @@ -121,7 +124,9 @@ internal string CreateKey(GraphicsCapabilities requested) writer.Write(computeProfile); writer.Write(defines.Count); foreach (string define in defines) + { writer.Write(define); + } writer.Write(requested.backend.value); writer.Write((int)requested.features); writer.Write(requested.limits.maxViews); diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderTargetProfile.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderTargetProfile.cs index 40b3b48ba..d23e8876c 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderTargetProfile.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderTargetProfile.cs @@ -32,10 +32,16 @@ IEnumerable renderers ArgumentNullException.ThrowIfNull(renderers); var snapshot = new Dictionary(); foreach (BgfxShaderCompilerProfile renderer in renderers) + { if (renderer is null || !snapshot.TryAdd(renderer.capabilities.backend, renderer)) + { throw new ArgumentException("Shader renderers must be non-null and unique.", nameof(renderers)); + } + } if (snapshot.Count == 0) + { throw new ArgumentException("A shader target requires at least one renderer.", nameof(renderers)); + } this.id = id; m_renderers = new ReadOnlyDictionary(snapshot); } @@ -58,15 +64,18 @@ IEnumerable renderers /// The target has no configuration for this API. /// public BgfxShaderCompilerProfile Resolve(GraphicsApi backend) - => m_renderers.TryGetValue(backend, out BgfxShaderCompilerProfile? renderer) ? renderer - : throw new NotSupportedException($"Shader target '{id}' has no renderer profile for '{backend}'."); + => m_renderers.TryGetValue(backend, out BgfxShaderCompilerProfile? renderer) + ? renderer + : throw new NotSupportedException($"Shader target '{id}' has no renderer profile for '{backend}'."); internal BgfxShaderCompilerProfile Resolve(GraphicsCapabilities capabilities) { ArgumentNullException.ThrowIfNull(capabilities); BgfxShaderCompilerProfile renderer = Resolve(capabilities.backend); if (capabilities.Supports(GraphicsCapability.Compute) && renderer.computeProfile.Length == 0) + { throw new NotSupportedException($"Shader target '{id}' does not support compute."); + } return renderer; } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShadercToolchain.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShadercToolchain.cs index 52bc89b15..eac9c99f8 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShadercToolchain.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShadercToolchain.cs @@ -4,8 +4,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Rendering.Assets; using Inno.Rendering; +using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; namespace Inno.Build.Toolchains.Bgfx.Tools; @@ -73,35 +73,33 @@ CancellationToken cancellationToken { throw new ArgumentException( $"Shader target '{target.profileKey}' does not belong to this BGFX toolchain.", - nameof(target)); + nameof(target) + ); } string temporaryDirectory = Path.Combine( Path.GetTempPath(), "InnoEngine", "Shaderc", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(temporaryDirectory); try { string sourcePath = Path.Combine(temporaryDirectory, "stage.sc"); string outputPath = Path.Combine(temporaryDirectory, "stage.bin"); string bgfxShaderInclude = ResolveBgfxShaderInclude(); - File.Copy( - bgfxShaderInclude, - Path.Combine(temporaryDirectory, "bgfx_shader.sh"), - overwrite: true); + File.Copy(bgfxShaderInclude, Path.Combine(temporaryDirectory, "bgfx_shader.sh"), overwrite: true); File.Copy( Path.Combine( Path.GetDirectoryName(bgfxShaderInclude) - ?? throw new InvalidOperationException("BGFX shader include has no parent directory."), - "bgfx_compute.sh"), + ?? throw new InvalidOperationException("BGFX shader include has no parent directory."), + "bgfx_compute.sh" + ), Path.Combine(temporaryDirectory, "bgfx_compute.sh"), - overwrite: true); - await File.WriteAllTextAsync( - sourcePath, - source, - cancellationToken).ConfigureAwait(false); + overwrite: true + ); + await File.WriteAllTextAsync(sourcePath, source, cancellationToken).ConfigureAwait(false); List arguments = [ @@ -121,10 +119,7 @@ await File.WriteAllTextAsync( if (stage != ShaderStage.Compute && varying is not null) { string varyingPath = Path.Combine(temporaryDirectory, "varying.def.sc"); - await File.WriteAllTextAsync( - varyingPath, - varying, - cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync(varyingPath, varying, cancellationToken).ConfigureAwait(false); arguments.Add("--varyingdef"); arguments.Add(varyingPath); } @@ -142,38 +137,39 @@ await File.WriteAllTextAsync( } if (target.debugInformation) + { arguments.Add("--debug"); + } arguments.Add("--keepcomments"); ToolRunResult result = await m_tools.RunAsync( BgfxTool.Shaderc, arguments, temporaryDirectory, - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); byte[]? bytes = result.succeeded && File.Exists(outputPath) - ? await File.ReadAllBytesAsync(outputPath, cancellationToken).ConfigureAwait(false) - : null; - return new BgfxShadercResult( - bytes, - result.exitCode, - result.standardOutput, - result.standardError); + ? await File.ReadAllBytesAsync(outputPath, cancellationToken).ConfigureAwait(false) + : null; + return new BgfxShadercResult(bytes, result.exitCode, result.standardOutput, result.standardError); } finally { if (Directory.Exists(temporaryDirectory)) + { Directory.Delete(temporaryDirectory, recursive: true); + } } } private static string ToShadercStage(ShaderStage stage) => stage switch - { - ShaderStage.Vertex => "vertex", - ShaderStage.Fragment => "fragment", - ShaderStage.Compute => "compute", - _ => throw new ArgumentOutOfRangeException(nameof(stage), stage, "A single shader stage is required.") - }; + { + ShaderStage.Vertex => "vertex", + ShaderStage.Fragment => "fragment", + ShaderStage.Compute => "compute", + _ => throw new ArgumentOutOfRangeException(nameof(stage), stage, "A single shader stage is required.") + }; private string ResolveBgfxShaderInclude() => m_tools.ResolveShaderInclude("bgfx_shader.sh"); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs index 744d4dd26..3bad4fe35 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs @@ -18,9 +18,8 @@ public static class BgfxTargetCapabilities /// /// The immutable offline validation profile for the selected target. /// - public static GraphicsCapabilities Create( - GraphicsApi backend - ) { + public static GraphicsCapabilities Create(GraphicsApi backend) + { GraphicsCapability features = Enum.GetValues() .Aggregate(GraphicsCapability.None, static ( current, @@ -39,7 +38,7 @@ GraphicsApi backend homogeneousDepth: backend == GraphicsApi.OpenGL || backend == GraphicsApi.OpenGLES, formats, formats, - formats); + formats + ); } - } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs index 9f21dc2fe..f87e13911 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs @@ -46,58 +46,78 @@ public async ValueTask CompileKtxAsync( ) { ArgumentNullException.ThrowIfNull(source); if (!source.CanRead) + { throw new ArgumentException("Texture compilation requires readable encoded input.", nameof(source)); + } cancellationToken.ThrowIfCancellationRequested(); string temporaryDirectory = Path.Combine( Path.GetTempPath(), "InnoEngine", "Texturec", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(temporaryDirectory); try { string sourcePath = Path.Combine(temporaryDirectory, "source.image"); - await using (FileStream inputFile = new(sourcePath, FileMode.CreateNew, FileAccess.Write, - FileShare.None, 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan)) - { + await using (FileStream inputFile = new( + sourcePath, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) { await source.CopyToAsync(inputFile, cancellationToken).ConfigureAwait(false); } string outputPath = Path.Combine(temporaryDirectory, "texture.ktx"); var arguments = new List { - "-f", Path.GetFullPath(sourcePath), - "-o", outputPath, - "-t", "RGBA8", + "-f", + Path.GetFullPath(sourcePath), + "-o", + outputPath, + "-t", + "RGBA8", "--mips", "--validate" }; if (colorSpace == TextureColorSpace.Linear) + { arguments.Add("--linear"); + } ToolRunResult result = await m_tools.RunAsync( BgfxTool.Texturec, arguments, temporaryDirectory, - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); if (!result.succeeded || !File.Exists(outputPath)) { string diagnostics = string.Join( Environment.NewLine, - new[] { result.standardOutput, result.standardError }); + new[] { result.standardOutput, result.standardError } + ); throw new InvalidOperationException( - $"texturec rejected the encoded input with exit code {result.exitCode}: {diagnostics}"); + $"texturec rejected the encoded input with exit code {result.exitCode}: {diagnostics}" + ); } byte[] artifact = await File.ReadAllBytesAsync(outputPath, cancellationToken) .ConfigureAwait(false); if (artifact.Length == 0) + { throw new InvalidOperationException("texturec produced an empty artifact."); + } return artifact; } finally { if (Directory.Exists(temporaryDirectory)) + { Directory.Delete(temporaryDirectory, recursive: true); + } } } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunResult.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunResult.cs index a6675ad87..84e771d07 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunResult.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunResult.cs @@ -47,4 +47,3 @@ string standardError /// public bool succeeded => exitCode == 0; } - diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs index 158d19498..2a9695c86 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs @@ -26,7 +26,8 @@ public sealed class ToolRunner /// /// Explicit execution path policy, or null for physical execution. /// - public ToolRunner(IToolchainWorkspaceProvider? workspaces = null) => m_workspaces = workspaces ?? new PhysicalToolchainWorkspaceProvider(); + public ToolRunner(IToolchainWorkspaceProvider? workspaces = null) + => m_workspaces = workspaces ?? new PhysicalToolchainWorkspaceProvider(); /// /// Freezes executables selected and validated by the host's toolchain operation. @@ -55,14 +56,23 @@ public ToolRunner( ArgumentNullException.ThrowIfNull(executables); ArgumentException.ThrowIfNullOrWhiteSpace(includesDirectory); if (!Path.IsPathFullyQualified(includesDirectory) || !Directory.Exists(includesDirectory)) + { throw new ArgumentException("The selected shader include directory must exist at an absolute path.", nameof(includesDirectory)); + } Dictionary snapshot = []; foreach ((BgfxTool tool, string path) in executables) { if (!Enum.IsDefined(tool) || !Path.IsPathFullyQualified(path)) - throw new ArgumentException("A tool runner requires supported identities and absolute executable paths.", nameof(executables)); + { + throw new ArgumentException( + "A tool runner requires supported identities and absolute executable paths.", + nameof(executables) + ); + } if (!File.Exists(path)) + { throw new FileNotFoundException("A selected BGFX executable is unavailable.", path); + } snapshot.Add(tool, Path.GetFullPath(path)); } m_executables = new ReadOnlyDictionary(snapshot); @@ -88,8 +98,7 @@ public ToolRunResult Run( BgfxTool tool, IReadOnlyList arguments, string? workingDirectory = null - ) - => RunAsync(tool, arguments, workingDirectory).AsTask().GetAwaiter().GetResult(); + ) => RunAsync(tool, arguments, workingDirectory).AsTask().GetAwaiter().GetResult(); /// /// Runs the external tool asynchronously and captures its complete process outcome. @@ -128,7 +137,9 @@ public async ValueTask RunAsync( cancellationToken.ThrowIfCancellationRequested(); string toolPath = ResolveToolPath(tool); using ToolchainWorkingDirectory execution = await m_workspaces.OpenAsync( - Path.GetDirectoryName(toolPath)!, cancellationToken).ConfigureAwait(false); + Path.GetDirectoryName(toolPath)!, + cancellationToken + ).ConfigureAwait(false); var startInfo = new ProcessStartInfo { FileName = Path.Combine(execution.toolPath, Path.GetFileName(toolPath)), @@ -145,7 +156,7 @@ public async ValueTask RunAsync( } using Process process = Process.Start(startInfo) - ?? throw new InvalidOperationException($"Failed to start tool: {toolPath}"); + ?? throw new InvalidOperationException($"Failed to start tool: {toolPath}"); Task standardOutput = process.StandardOutput.ReadToEndAsync(); Task standardError = process.StandardError.ReadToEndAsync(); try @@ -154,14 +165,17 @@ public async ValueTask RunAsync( return new ToolRunResult( process.ExitCode, await standardOutput.ConfigureAwait(false), - await standardError.ConfigureAwait(false)); + await standardError.ConfigureAwait(false) + ); } catch { try { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } } catch (InvalidOperationException) when (process.HasExited) { @@ -183,7 +197,9 @@ await standardOutput.ConfigureAwait(false), internal string ResolveShaderInclude(string name) { if (name is not ("bgfx_shader.sh" or "bgfx_compute.sh")) + { throw new ArgumentException("The shader include is not part of this backend's declared tool product.", nameof(name)); + } string path = m_includesDirectory is null ? NativeDllLoader.FindNativeFile(name) : Path.Combine(m_includesDirectory, name); return File.Exists(path) ? path : throw new FileNotFoundException("A selected shader include is unavailable.", path); } @@ -191,10 +207,12 @@ internal string ResolveShaderInclude(string name) private string ResolveToolPath(BgfxTool tool) { if (m_executables is not null) + { return m_executables.TryGetValue(tool, out string? executable) - ? executable : throw new FileNotFoundException($"The selected distribution has no '{tool}' executable."); + ? executable + : throw new FileNotFoundException($"The selected distribution has no '{tool}' executable."); + } string name = tool.ToString().ToLowerInvariant(); return NativeDllLoader.FindNativeFile(name); } - } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.ControlFlow.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.ControlFlow.cs index 59aa412b8..c2c086a66 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.ControlFlow.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.ControlFlow.cs @@ -10,9 +10,13 @@ internal sealed partial class BgfxShaderIrGenerator private bool EmitControlFlow(ShaderIrInstruction instruction) { if (instruction.operation is not (ShaderIrOperation.Branch or ShaderIrOperation.Loop)) + { return false; + } foreach (ShaderIrValue output in instruction.outputs) + { m_body.Append(" ").Append(Declaration(output.type, NewLocal(output))).AppendLine(";"); + } if (instruction.operation == ShaderIrOperation.Branch) { m_body.Append(" if (").Append(Value(instruction.inputs[0])).AppendLine(") {"); @@ -26,14 +30,32 @@ private bool EmitControlFlow(ShaderIrInstruction instruction) } for (int index = 0; index < instruction.outputs.Count; index++) + { Assign(m_body, instruction.outputs[index].type, Value(instruction.outputs[index]), Value(instruction.inputs[index + 1])); + } ShaderIrBlock region = instruction.regions[0]; - ShaderIrInstruction iteration = region.instructions.Single(static value => value.operation == ShaderIrOperation.RegionInput && value.inputName == "iteration"); + ShaderIrInstruction iteration = region.instructions.Single( + static value => value.operation == ShaderIrOperation.RegionInput && value.inputName == "iteration" + ); string counter = NewLocal(iteration.outputs[0]); - m_body.Append(" for (uint ").Append(counter).Append(" = 0u; ").Append(counter).Append(" < ") - .Append(Value(instruction.inputs[0])).Append("; ++").Append(counter).AppendLine(") {"); - ShaderIrInstruction[] carried = region.instructions.Where(static value => value.operation == ShaderIrOperation.RegionInput && value.inputName!.StartsWith("state.", StringComparison.Ordinal)) - .OrderBy(static value => value.inputName, StringComparer.Ordinal).ToArray(); + m_body.Append(" for (uint ") + .Append(counter) + .Append(" = 0u; ") + .Append(counter) + .Append(" < ") + .Append(Value(instruction.inputs[0])) + .Append("; ++") + .Append(counter) + .AppendLine(") {"); + ShaderIrInstruction[] carried = region.instructions + .Where( + static value => ( + value.operation == ShaderIrOperation.RegionInput + && value.inputName!.StartsWith("state.", StringComparison.Ordinal) + ) + ) + .OrderBy(static value => value.inputName, StringComparer.Ordinal) + .ToArray(); for (int index = 0; index < carried.Length; index++) { ShaderIrValue parameter = carried[index].outputs[0]; @@ -52,8 +74,12 @@ private bool EmitControlFlow(ShaderIrInstruction instruction) private void EmitRegion(ShaderIrBlock region) { foreach (ShaderIrInstruction instruction in region.instructions) + { if (instruction.operation != ShaderIrOperation.RegionInput) + { EmitInstruction(instruction); + } + } } private void AssignRegionOutputs( @@ -61,8 +87,10 @@ private void AssignRegionOutputs( int regionIndex = 0 ) { int index = 0; - foreach (KeyValuePair pair in instruction.regions[regionIndex].outputs.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) - { + foreach (KeyValuePair pair in instruction.regions[regionIndex].outputs.OrderBy( + static pair => pair.Key, + StringComparer.Ordinal + )) { ShaderIrValue output = instruction.outputs[index++]; Assign(m_body, output.type, Value(output), Value(pair.Value)); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Resources.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Resources.cs index 3a9e6bb64..405b70c91 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Resources.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Resources.cs @@ -16,7 +16,9 @@ string name ShaderStorageType storage = input.type.storage!; string access = storage.access switch { - RenderStorageAccess.Read => "RO", RenderStorageAccess.Write => "WO", RenderStorageAccess.ReadWrite => "RW", + RenderStorageAccess.Read => "RO", + RenderStorageAccess.Write => "WO", + RenderStorageAccess.ReadWrite => "RW", _ => throw Error("Unsupported storage access.") }; if (!storage.isImage) @@ -25,29 +27,58 @@ string name // packing cannot be inferred safely; structured layouts need explicit target packing first. string element = storage.valueType.id; if (storage.valueType.elementType is not null || storage.valueType.fields.Count != 0 - || element is not ("float" or "float2" or "float4" or "int" or "int2" or "int4" or "uint" or "uint2" or "uint4")) - throw Error("BGFX storage buffer elements require 32-bit scalars, two-component or four-component vectors with an explicit runtime stride."); - text.Append("BUFFER_").Append(access).Append('(').Append(name).Append(", ") - .Append(TypeName(storage.valueType)).Append(", ").Append(input.location).AppendLine(");"); + || element is not ("float" or "float2" or "float4" or "int" or "int2" or "int4" or "uint" or "uint2" or "uint4") + ) { + throw Error( + "BGFX storage buffer elements require 32-bit scalars, two-component or four-component vectors with an explicit runtime stride." + ); + } + text.Append("BUFFER_") + .Append(access) + .Append('(') + .Append(name) + .Append(", ") + .Append(TypeName(storage.valueType)) + .Append(", ") + .Append(input.location) + .AppendLine(");"); return; } string shape = storage.dimension == RenderTextureDimension.Texture3D ? "3D" : storage.array ? "2D_ARRAY" : "2D"; string format = storage.format switch { - RenderTextureFormat.R8 => "r8", RenderTextureFormat.RG8 => "rg8", RenderTextureFormat.RGBA8 => "rgba8", - RenderTextureFormat.RGBA16Float => "rgba16f", RenderTextureFormat.R32Float => "r32f", - RenderTextureFormat.RGB10A2 => "rgb10_a2", RenderTextureFormat.RG11B10Float => "r11f_g11f_b10f", + RenderTextureFormat.R8 => "r8", + RenderTextureFormat.RG8 => "rg8", + RenderTextureFormat.RGBA8 => "rgba8", + RenderTextureFormat.RGBA16Float => "rgba16f", + RenderTextureFormat.R32Float => "r32f", + RenderTextureFormat.RGB10A2 => "rgb10_a2", + RenderTextureFormat.RG11B10Float => "r11f_g11f_b10f", _ => throw Error("The storage image format has no BGFX SC representation.") }; - text.Append("IMAGE").Append(shape).Append('_').Append(access).Append('(').Append(name).Append(", ") - .Append(format).Append(", ").Append(input.location).AppendLine(");"); + text.Append("IMAGE") + .Append(shape) + .Append('_') + .Append(access) + .Append('(') + .Append(name) + .Append(", ") + .Append(format) + .Append(", ") + .Append(input.location) + .AppendLine(");"); } private bool EmitResourceInstruction(ShaderIrInstruction instruction) { if (instruction.operation is not (ShaderIrOperation.TextureSample or ShaderIrOperation.TextureSampleLevel - or ShaderIrOperation.StorageLoad or ShaderIrOperation.StorageStore or ShaderIrOperation.StorageAtomicAdd or ShaderIrOperation.Discard)) + or ShaderIrOperation.StorageLoad + or ShaderIrOperation.StorageStore + or ShaderIrOperation.StorageAtomicAdd + or ShaderIrOperation.Discard) + ) { return false; + } string[] operands = instruction.inputs.Select(Value).ToArray(); string? result = null; if (instruction.outputs.Count != 0) @@ -62,28 +93,44 @@ private bool EmitResourceInstruction(ShaderIrInstruction instruction) case ShaderIrOperation.TextureSampleLevel: string function = instruction.inputs[0].type.id switch { - "sampled-texture2d" => "texture2D", "sampled-texture2d-array" => "texture2DArray", - "sampled-texture3d" => "texture3D", "sampled-texture-cube" => "textureCube", + "sampled-texture2d" => "texture2D", + "sampled-texture2d-array" => "texture2DArray", + "sampled-texture3d" => "texture3D", + "sampled-texture-cube" => "textureCube", _ => throw Error("Unsupported sampled texture shape.") }; if (instruction.operation == ShaderIrOperation.TextureSampleLevel) + { function += "Lod"; + } Assign(m_body, instruction.outputs[0].type, result!, function + "(" + string.Join(", ", operands) + ")"); break; case ShaderIrOperation.StorageLoad: string load = instruction.inputs[0].type.storage!.isImage - ? $"imageLoad({operands[0]}, {operands[1]})" : $"{operands[0]}[{operands[1]}]"; + ? $"imageLoad({operands[0]}, {operands[1]})" + : $"{operands[0]}[{operands[1]}]"; Assign(m_body, instruction.outputs[0].type, result!, load); break; case ShaderIrOperation.StorageStore: if (instruction.inputs[0].type.storage!.isImage) + { m_body.Append(" imageStore(").AppendJoin(", ", operands).AppendLine(");"); + } else + { Assign(m_body, instruction.inputs[2].type, $"{operands[0]}[{operands[1]}]", operands[2]); + } break; case ShaderIrOperation.StorageAtomicAdd: - m_body.Append(" atomicFetchAndAdd(").Append(operands[0]).Append('[').Append(operands[1]).Append("], ") - .Append(operands[2]).Append(", ").Append(result).AppendLine(");"); + m_body.Append(" atomicFetchAndAdd(") + .Append(operands[0]) + .Append('[') + .Append(operands[1]) + .Append("], ") + .Append(operands[2]) + .Append(", ") + .Append(result) + .AppendLine(");"); break; case ShaderIrOperation.Discard: m_body.Append(" if (").Append(operands[0]).AppendLine(") { discard; }"); diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs index b09d1bf63..6bded9603 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs @@ -14,38 +14,60 @@ internal sealed partial class BgfxShaderIrGenerator private string EmitModule(ShaderSourceImplementationAnalysis implementation) { if (implementation.languageId != "inno.shader-language.bgfx-sc") - throw new BgfxSourceSyntaxException($"BGFX SC generation cannot embed language '{implementation.languageId}'.", new(implementation.sourcePath, 1, 1)); + { + throw new BgfxSourceSyntaxException( + $"BGFX SC generation cannot embed language '{implementation.languageId}'.", + new(implementation.sourcePath, 1, 1) + ); + } ShaderSourceRequest request = implementation.CreateSourceRequest(); List tokens = new BgfxSourcePreprocessor(request).Process(); var parser = new BgfxSourceDeclarationParser(tokens, request); ShaderSourceFunction parsed = parser.Parse(); if (!parsed.HasSameInterface(implementation.analysis.function!)) + { Fail("The frozen source interface differs from its analyzed snapshot."); + } string prefix = "inno_module_" + implementation.contentHash.ToLowerInvariant() + "_"; var symbols = parser.globals.ToDictionary(static value => value, value => prefix + value, StringComparer.Ordinal); // Shaderc injects varying macros before function declarations. Isolate module-local names // that collide with those generated bindings, including exported function parameters. foreach (string varying in stage.inputs.Where(static input => input.kind == ShaderIrInputKind.Varying) .Select(static input => VaryingName(input.semantic, input.location)) - .Concat(stage.outputs.Where(static output => output.kind == ShaderIrOutputKind.Varying) - .Select(static output => VaryingName(output.semantic, output.location)))) + .Concat( + stage.outputs.Where(static output => output.kind == ShaderIrOutputKind.Varying) + .Select(static output => VaryingName(output.semantic, output.location)) + ) + ) { symbols.TryAdd(varying, prefix + varying); + } foreach ((string name, ShaderSourceType type) in parser.types) { if (type.elementType is not null) - throw new BgfxSourceSyntaxException("BGFX SC does not support array typedef declarations; declare fixed arrays at their use sites.", new(implementation.sourcePath, 1, 1)); + { + throw new BgfxSourceSyntaxException( + "BGFX SC does not support array typedef declarations; declare fixed arrays at their use sites.", + new(implementation.sourcePath, 1, 1) + ); + } symbols.Add(name, TypeName(type)); } var removed = new HashSet(); foreach ((int start, int end) in parser.typeDeclarations) + { for (int index = start; index < end; index++) + { removed.Add(index); + } + } ShaderSourcePosition? position = null; string previous = string.Empty; for (int index = 0; index < tokens.Count; index++) { if (removed.Contains(index)) + { continue; + } BgfxSourceToken token = tokens[index]; if (position?.assetPath != token.position.assetPath || position?.line != token.position.line) { @@ -57,7 +79,9 @@ private string EmitModule(ShaderSourceImplementationAnalysis implementation) } string text = token.text; if (previous != "." && symbols.TryGetValue(text, out string? replacement)) + { text = replacement; + } m_modules.Append(text).Append(' '); previous = token.text; } @@ -68,7 +92,9 @@ private string EmitModule(ShaderSourceImplementationAnalysis implementation) private string TypeName(ShaderSourceType type) { if (type.elementType is not null) + { return TypeName(type.elementType); + } if (type.fields.Count != 0) { string name = "InnoType_" + Hash(TypeKey(type)); @@ -77,40 +103,75 @@ private string TypeName(ShaderSourceType type) m_structures.Add(name, type); var declaration = new StringBuilder("struct ").Append(name).AppendLine(" {"); foreach (ShaderSourceField field in type.fields) + { declaration.Append(" ").Append(Declaration(field.type, FieldName(field.name))).AppendLine(";"); + } m_types.Append(declaration).AppendLine("};"); } else if (!previous.IsEquivalentTo(type)) + { Fail("A generated structure identity collided."); + } return name; } if (type.id is "void" or "float" or "int" or "uint" or "bool") + { return type.id; + } if (type.id == "sampled-texture2d") + { return "sampler2D"; + } if (type.id == "sampled-texture2d-array") + { return "sampler2DArray"; + } if (type.id == "sampled-texture3d") + { return "sampler3D"; + } if (type.id == "sampled-texture-cube") + { return "samplerCube"; + } if (IsMatrix(type)) { if (type.id[5] == type.id[7]) + { return "mat" + type.id[5]; + } string name = "inno_mat" + type.id[5..]; if (m_matrices.Add(name)) { m_types.AppendLine("#if BGFX_SHADER_LANGUAGE_GLSL").Append("#define ").Append(name).Append(" mat").AppendLine(type.id[5..]); - m_types.AppendLine("#elif BGFX_SHADER_MATRIX_COLUMN_MAJOR").Append("#define ").Append(name).Append(" float").AppendLine(type.id[5..]); - m_types.AppendLine("#else").Append("#define ").Append(name).Append(" float").Append(type.id[7]).Append('x').Append(type.id[5]).AppendLine(); + m_types + .AppendLine("#elif BGFX_SHADER_MATRIX_COLUMN_MAJOR") + .Append("#define ") + .Append(name) + .Append(" float") + .AppendLine(type.id[5..]); + m_types + .AppendLine("#else") + .Append("#define ") + .Append(name) + .Append(" float") + .Append(type.id[7]) + .Append('x') + .Append(type.id[5]) + .AppendLine(); m_types.AppendLine("#endif"); } return name; } foreach ((string prefix, string native) in new[] { ("float", "vec"), ("int", "ivec"), ("uint", "uvec"), ("bool", "bvec") }) - if (type.id.Length == prefix.Length + 1 && type.id.StartsWith(prefix, StringComparison.Ordinal) && type.id[^1] is >= '2' and <= '4') + { + if (type.id.Length == prefix.Length + 1 + && type.id.StartsWith(prefix, StringComparison.Ordinal) + && type.id[^1] is >= '2' and <= '4' + ) { return native + type.id[^1]; + } + } throw Error($"BGFX SC cannot represent IR value type '{type.id}'."); } @@ -136,10 +197,14 @@ string source if (type.elementType is not null) { for (int index = 0; index < type.elementCount; index++) + { Assign(text, type.elementType, $"{destination}[{index}]", $"{source}[{index}]"); + } } else + { text.Append(" ").Append(destination).Append(" = ").Append(source).AppendLine(";"); + } } private string NewLocal(ShaderIrValue value) @@ -150,16 +215,21 @@ private string NewLocal(ShaderIrValue value) } private string Value(ShaderIrValue value) => m_values[value.index]; + private static string Binary( ShaderIrOperation operation, string left, string right ) => operation switch { - ShaderIrOperation.Add => $"({left} + {right})", ShaderIrOperation.Subtract => $"({left} - {right})", - ShaderIrOperation.Multiply => $"({left} * {right})", ShaderIrOperation.Divide => $"({left} / {right})", - ShaderIrOperation.Minimum => $"min({left}, {right})", ShaderIrOperation.Maximum => $"max({left}, {right})", - ShaderIrOperation.Equal => $"({left} == {right})", ShaderIrOperation.LessThan => $"({left} < {right})", + ShaderIrOperation.Add => $"({left} + {right})", + ShaderIrOperation.Subtract => $"({left} - {right})", + ShaderIrOperation.Multiply => $"({left} * {right})", + ShaderIrOperation.Divide => $"({left} / {right})", + ShaderIrOperation.Minimum => $"min({left}, {right})", + ShaderIrOperation.Maximum => $"max({left}, {right})", + ShaderIrOperation.Equal => $"({left} == {right})", + ShaderIrOperation.LessThan => $"({left} < {right})", _ => throw Error($"Unsupported typed operation '{operation}'.") }; @@ -182,8 +252,10 @@ private static string FloatLiteral(float value) } private static string TypeKey(ShaderSourceType type) - => type.elementType is not null ? $"{type.id.Length}:{type.id}[{type.elementCount}]{TypeKey(type.elementType)}" - : $"{type.id.Length}:{type.id}" + string.Concat(type.fields.Select(field => $"{field.name.Length}:{field.name}{TypeKey(field.type)}")); + => type.elementType is not null + ? $"{type.id.Length}:{type.id}[{type.elementCount}]{TypeKey(type.elementType)}" + : $"{type.id.Length}:{type.id}" + + string.Concat(type.fields.Select(field => $"{field.name.Length}:{field.name}{TypeKey(field.type)}")); private static string Hash(string text) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text))); @@ -209,28 +281,45 @@ string id } } if (count != 0) + { result.Append(alphabet[(int)((bits << (5 - count)) & 31)]); + } return result.ToString(); } + private static string MatrixElement( string matrix, int column, int row ) => $"inno_matrix_element({matrix},{column},{row})"; + private static bool IsMatrix(ShaderSourceType type) - => type.id.Length == 8 && type.id.StartsWith("float", StringComparison.Ordinal) && type.id[5] is >= '2' and <= '4' && type.id[6] == 'x' && type.id[7] is >= '2' and <= '4'; + => type.id.Length == 8 + && type.id.StartsWith("float", StringComparison.Ordinal) + && type.id[5] is >= '2' and <= '4' + && type.id[6] == 'x' + && type.id[7] is >= '2' and <= '4'; private static string FieldName(string name) { - if (name.Length == 0 || !(char.IsAsciiLetter(name[0]) || name[0] == '_') || name.Any(static c => !char.IsAsciiLetterOrDigit(c) && c != '_')) + if (name.Length == 0 + || !(char.IsAsciiLetter(name[0]) || name[0] == '_') + || name.Any(static c => !char.IsAsciiLetterOrDigit(c) && c != '_') + ) { throw Error("BGFX SC structure field names must be identifiers."); + } return name; } - private static string AttributeName(ShaderIrStageInput input) => (input.semantic, input.location) switch + private static string AttributeName(ShaderIrStageInput input) + => (input.semantic, input.location) switch { - ("position", 0) => "a_position", ("normal", 0) => "a_normal", ("tangent", 0) => "a_tangent", ("bitangent", 0) => "a_bitangent", - ("indices", 0) => "a_indices", ("weight", 0) => "a_weight", + ("position", 0) => "a_position", + ("normal", 0) => "a_normal", + ("tangent", 0) => "a_tangent", + ("bitangent", 0) => "a_bitangent", + ("indices", 0) => "a_indices", + ("weight", 0) => "a_weight", ("color", >= 0 and <= 3) => "a_color" + input.location, ("texcoord", >= 0 and <= 7) => "a_texcoord" + input.location, ("instance-data", >= 0 and <= 4) => "i_data" + input.location, @@ -242,8 +331,12 @@ private static string Semantic( int location ) => (semantic, location) switch { - ("position", 0) => "POSITION", ("normal", 0) => "NORMAL", ("tangent", 0) => "TANGENT", ("bitangent", 0) => "BITANGENT", - ("indices", 0) => "BLENDINDICES", ("weight", 0) => "BLENDWEIGHT", + ("position", 0) => "POSITION", + ("normal", 0) => "NORMAL", + ("tangent", 0) => "TANGENT", + ("bitangent", 0) => "BITANGENT", + ("indices", 0) => "BLENDINDICES", + ("weight", 0) => "BLENDWEIGHT", ("texcoord", >= 0 and <= 15) => "TEXCOORD" + location, ("color", >= 0 and <= 3) => "COLOR" + location, ("instance-data", >= 0 and <= 4) => "TEXCOORD" + (7 - location), @@ -255,7 +348,9 @@ private static string VaryingName( int location ) { if (semantic is not ("texcoord" or "color")) + { throw Error($"BGFX cannot interpolate semantic '{semantic}'."); + } _ = Semantic(semantic, location); return "v_" + semantic + location; } @@ -279,5 +374,6 @@ ShaderStage kind }; private static BgfxSourceSyntaxException Error(string message) => new(message, new("inno-generated-stage", 1, 1)); + private static void Fail(string message) => throw Error(message); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs index c7339b24e..0c791f6c1 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs @@ -6,8 +6,8 @@ using System.Text; using Inno.Rendering; using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Build.Toolchains.Bgfx.Tools; @@ -49,29 +49,50 @@ internal BgfxGeneratedStage Generate() case ShaderIrInputKind.VertexAttribute: name = AttributeName(input); inputNames.Add(name); - varying.Append(Declaration(input.type, name)).Append(" : ").Append(Semantic(input.semantic, input.location)).AppendLine(";"); + varying + .Append(Declaration(input.type, name)) + .Append(" : ") + .Append(Semantic(input.semantic, input.location)) + .AppendLine(";"); break; case ShaderIrInputKind.Varying: name = VaryingName(input.semantic, input.location); inputNames.Add(name); - varying.Append(Declaration(input.type, name)).Append(" : ").Append(Semantic(input.semantic, input.location)).AppendLine(";"); + varying + .Append(Declaration(input.type, name)) + .Append(" : ") + .Append(Semantic(input.semantic, input.location)) + .AppendLine(";"); break; case ShaderIrInputKind.Uniform: name = BindingName("u_inno_", input.id); bool packed = input.type.id is "float" or "float2" or "float3"; - if (!packed && input.type.id is not ("float4" or "float3x3" or "float4x4") && input.type.elementType?.id is not ("float4" or "float3x3" or "float4x4")) - Fail("BGFX uniform layout requires vec4, mat3 or mat4 storage (or fixed arrays); lower scalar/vector parameters through explicit layout components."); - declarations.Append("uniform ").Append(Declaration(packed ? ShaderSourceType.Atomic("float4") : input.type, name)).AppendLine(";"); + if (!packed + && input.type.id is not ("float4" or "float3x3" or "float4x4") + && input.type.elementType?.id is not ("float4" or "float3x3" or "float4x4") + ) { + Fail( + "BGFX uniform layout requires vec4, mat3 or mat4 storage (or fixed arrays); lower scalar/vector parameters through explicit layout components." + ); + } + declarations + .Append("uniform ") + .Append(Declaration(packed ? ShaderSourceType.Atomic("float4") : input.type, name)) + .AppendLine(";"); m_bindings.Add(new(input.id, name, input.location)); if (packed) + { name += input.type.id switch { "float" => ".x", "float2" => ".xy", _ => ".xyz" }; + } break; case ShaderIrInputKind.SampledTexture: name = BindingName("s_inno_", input.id); string macro = input.type.id switch { - "sampled-texture2d" => "SAMPLER2D", "sampled-texture2d-array" => "SAMPLER2DARRAY", - "sampled-texture3d" => "SAMPLER3D", "sampled-texture-cube" => "SAMPLERCUBE", + "sampled-texture2d" => "SAMPLER2D", + "sampled-texture2d-array" => "SAMPLER2DARRAY", + "sampled-texture3d" => "SAMPLER3D", + "sampled-texture-cube" => "SAMPLERCUBE", _ => throw Error($"Unsupported sampled resource '{input.type.id}'.") }; declarations.Append(macro).Append('(').Append(name).Append(", ").Append(input.location).AppendLine(");"); @@ -80,7 +101,9 @@ internal BgfxGeneratedStage Generate() case ShaderIrInputKind.Builtin: (name, string type) = Builtin(input.semantic, stage.stage); if (!input.type.IsEquivalentTo(ShaderSourceType.Atomic(type))) + { Fail($"Builtin '{input.semantic}' requires {type}, not {input.type.id}."); + } break; case ShaderIrInputKind.Storage: name = BindingName("r_inno_", input.id); @@ -92,22 +115,34 @@ internal BgfxGeneratedStage Generate() stageInputs.Add(input.id, name); } foreach (ShaderIrStageOutput output in stage.outputs) + { if (output.kind == ShaderIrOutputKind.Varying) { string name = VaryingName(output.semantic, output.location); outputNames.Add(name); - varying.Append(Declaration(stage.body.outputs[output.id].type, name)).Append(" : ") - .Append(Semantic(output.semantic, output.location)).AppendLine(";"); + varying.Append(Declaration(stage.body.outputs[output.id].type, name)) + .Append(" : ") + .Append(Semantic(output.semantic, output.location)) + .AppendLine(";"); } + } if (inputNames.Count != 0) + { header.Append("$input ").AppendJoin(", ", inputNames.Order(StringComparer.Ordinal)).AppendLine(); + } if (outputNames.Count != 0) + { header.Append("$output ").AppendJoin(", ", outputNames.Order(StringComparer.Ordinal)).AppendLine(); + } header.AppendLine("#include "); DeclareFragmentOutputs(header); - header.AppendLine("#if BGFX_SHADER_MATRIX_COLUMN_MAJOR\n#define inno_matrix_element(m,c,r) ((m)[c][r])\n#else\n#define inno_matrix_element(m,c,r) ((m)[r][c])\n#endif"); + header.AppendLine( + "#if BGFX_SHADER_MATRIX_COLUMN_MAJOR\n#define inno_matrix_element(m,c,r) ((m)[c][r])\n#else\n#define inno_matrix_element(m,c,r) ((m)[r][c])\n#endif" + ); if (stage.stage == ShaderStage.Compute) + { header.AppendLine("#include "); + } foreach (ShaderIrInstruction instruction in stage.body.instructions) { if (instruction.operation == ShaderIrOperation.Input) @@ -124,8 +159,10 @@ internal BgfxGeneratedStage Generate() ShaderIrOutputKind.ClipPosition => "gl_Position", ShaderIrOutputKind.Varying => VaryingName(output.semantic, output.location), ShaderIrOutputKind.Depth => "gl_FragDepth", - ShaderIrOutputKind.Color => stage.outputs.Count(static value => value.kind == ShaderIrOutputKind.Color) == 1 && output.location == 0 - ? "gl_FragColor" : $"inno_fragment_color_{output.location}", + ShaderIrOutputKind.Color => stage.outputs.Count(static value => value.kind == ShaderIrOutputKind.Color) == 1 + && output.location == 0 + ? "gl_FragColor" + : $"inno_fragment_color_{output.location}", _ => throw Error("Unsupported stage output.") }; ShaderIrValue value = stage.body.outputs[output.id]; @@ -134,7 +171,16 @@ internal BgfxGeneratedStage Generate() var source = new StringBuilder().Append(header).Append(m_types).Append(declarations).Append(m_modules); source.AppendLine("#line 1 \"inno-generated-stage\""); if (stage.stage == ShaderStage.Compute) - source.Append("NUM_THREADS(").Append(stage.threadsX).Append(", ").Append(stage.threadsY).Append(", ").Append(stage.threadsZ).AppendLine(")"); + { + source + .Append("NUM_THREADS(") + .Append(stage.threadsX) + .Append(", ") + .Append(stage.threadsY) + .Append(", ") + .Append(stage.threadsZ) + .AppendLine(")"); + } source.AppendLine("void main() {").Append(m_body).AppendLine("}"); return new(source.ToString(), varying.ToString(), m_bindings.AsReadOnly(), m_sourcePositions.AsReadOnly()); } @@ -142,20 +188,33 @@ internal BgfxGeneratedStage Generate() private void DeclareFragmentOutputs(StringBuilder header) { ShaderIrStageOutput[] colors = stage.outputs.Where(static output => output.kind == ShaderIrOutputKind.Color) - .OrderBy(static output => output.location).ToArray(); + .OrderBy(static output => output.location) + .ToArray(); if (colors.Length == 0 || colors.Length == 1 && colors[0].location == 0) + { return; + } // Shaderc passes modern desktop GLSL through without lowering its deprecated MRT builtins. // Explicit locations also preserve sparse output slots; other dialects retain shaderc's lowering. header.AppendLine("#if BGFX_SHADER_LANGUAGE_GLSL >= 400 && !BGFX_SHADER_LANGUAGE_ESSL"); foreach (ShaderIrStageOutput color in colors) - header.Append("layout(location = ").Append(color.location).Append(") out vec4 inno_fragment_color_") - .Append(color.location).AppendLine(";"); + { + header.Append("layout(location = ") + .Append(color.location) + .Append(") out vec4 inno_fragment_color_") + .Append(color.location) + .AppendLine(";"); + } header.AppendLine("#else"); foreach (ShaderIrStageOutput color in colors) - header.Append("#define inno_fragment_color_").Append(color.location).Append(" gl_FragData[") - .Append(color.location).AppendLine("]"); + { + header.Append("#define inno_fragment_color_") + .Append(color.location) + .Append(" gl_FragData[") + .Append(color.location) + .AppendLine("]"); + } header.AppendLine("#endif"); } @@ -167,9 +226,13 @@ private void EmitInstruction(ShaderIrInstruction instruction) return; } if (EmitControlFlow(instruction)) + { return; + } if (EmitResourceInstruction(instruction)) + { return; + } ShaderIrValue output = instruction.outputs[0]; string name = NewLocal(output); m_body.Append(" ").Append(Declaration(output.type, name)).AppendLine(";"); @@ -181,22 +244,45 @@ private void EmitInstruction(ShaderIrInstruction instruction) break; case ShaderIrOperation.Construct: if (output.type.elementType is not null) + { for (int index = 0; index < operands.Length; index++) + { Assign(m_body, output.type.elementType, $"{name}[{index}]", operands[index]); + } + } else if (output.type.fields.Count != 0) + { for (int index = 0; index < operands.Length; index++) - Assign(m_body, output.type.fields[index].type, name + "." + FieldName(output.type.fields[index].name), operands[index]); + { + Assign( + m_body, + output.type.fields[index].type, + name + "." + FieldName(output.type.fields[index].name), + operands[index] + ); + } + } else if (IsMatrix(output.type)) { int columns = output.type.id[5] - '0'; int rows = output.type.id[7] - '0'; for (int column = 0; column < columns; column++) + { for (int row = 0; row < rows; row++) - Assign(m_body, ShaderSourceType.Atomic("float"), - MatrixElement(name, column, row), operands[column * rows + row]); + { + Assign( + m_body, + ShaderSourceType.Atomic("float"), + MatrixElement(name, column, row), + operands[column * rows + row] + ); + } + } } else + { Assign(m_body, output.type, name, TypeName(output.type) + "(" + string.Join(", ", operands) + ")"); + } break; case ShaderIrOperation.Extract: ShaderSourceType aggregate = instruction.inputs[0].type; @@ -204,11 +290,19 @@ private void EmitInstruction(ShaderIrInstruction instruction) { int rows = aggregate.id[7] - '0'; for (int row = 0; row < rows; row++) - Assign(m_body, ShaderSourceType.Atomic("float"), $"{name}[{row}]", - MatrixElement(operands[0], instruction.memberIndex, row)); + { + Assign( + m_body, + ShaderSourceType.Atomic("float"), + $"{name}[{row}]", + MatrixElement(operands[0], instruction.memberIndex, row) + ); + } break; } - string suffix = aggregate.fields.Count != 0 ? "." + FieldName(aggregate.fields[instruction.memberIndex].name) : $"[{instruction.memberIndex}]"; + string suffix = aggregate.fields.Count != 0 + ? "." + FieldName(aggregate.fields[instruction.memberIndex].name) + : $"[{instruction.memberIndex}]"; Assign(m_body, output.type, name, operands[0] + suffix); break; case ShaderIrOperation.Select: @@ -224,14 +318,26 @@ private void EmitInstruction(ShaderIrInstruction instruction) int columns = output.type.id[5] - '0'; int rows = output.type.id[7] - '0'; for (int column = 0; column < columns; column++) + { for (int row = 0; row < rows; row++) { - Assign(m_body, ShaderSourceType.Atomic("float"), MatrixElement(name, column, row), - Binary(instruction.operation, MatrixElement(operands[0], column, row), MatrixElement(operands[1], column, row))); + Assign( + m_body, + ShaderSourceType.Atomic("float"), + MatrixElement(name, column, row), + Binary( + instruction.operation, + MatrixElement(operands[0], column, row), + MatrixElement(operands[1], column, row) + ) + ); } + } } else + { Assign(m_body, output.type, name, Binary(instruction.operation, operands[0], operands[1])); + } break; } } @@ -248,24 +354,34 @@ private void EmitCall(ShaderIrInstruction instruction) int inputIndex = 0; int outputIndex = function.returnType.id == "void" ? 0 : 1; foreach (ShaderIrValue output in instruction.outputs) + { m_body.Append(" ").Append(Declaration(output.type, NewLocal(output))).AppendLine(";"); + } var arguments = new List(); foreach (ShaderSourceParameter parameter in function.parameters) { if (parameter.direction == ShaderSourceParameterDirection.Input) + { arguments.Add(Value(instruction.inputs[inputIndex++])); + } else { string output = Value(instruction.outputs[outputIndex++]); if (parameter.direction == ShaderSourceParameterDirection.InputOutput) + { Assign(m_body, parameter.type, output, Value(instruction.inputs[inputIndex++])); + } arguments.Add(output); } } string call = functionName + "(" + string.Join(", ", arguments) + ")"; if (function.returnType.id == "void") + { m_body.Append(" ").Append(call).AppendLine(";"); + } else + { Assign(m_body, function.returnType, Value(instruction.outputs[0]), call); + } } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs index 7ae8901aa..ac9591406 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs @@ -6,8 +6,8 @@ using System.Text; using Inno.Rendering; using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Build.Toolchains.Bgfx.Tools; @@ -42,7 +42,9 @@ IReadOnlyList bindings string name = Encoding.UTF8.GetString(binary, offset, nameLength); offset += nameLength + C_SHADER_UNIFORM_METADATA_SIZE; if (activeNames.Contains(name)) + { records.Add(name, binary.AsSpan(start, offset - start).ToArray()); + } } // Shaderc's line scanner stops at layout-qualified declarations. Complete its metadata @@ -51,18 +53,24 @@ IReadOnlyList bindings { ShaderIrStageInput input = stage.inputs.Single(value => value.id == binding.id); if (input.kind != ShaderIrInputKind.Storage && !records.ContainsKey(binding.nativeName)) + { records.Add(binding.nativeName, EncodeGlslUniform(input, binding.nativeName)); + } } if (records.Count > ushort.MaxValue) + { throw new InvalidDataException("The compiled GLSL uniform table exceeds the BGFX binary limit."); + } using var output = new MemoryStream(); output.Write(binary.AsSpan(0, C_SHADER_BINARY_HEADER_SIZE)); Span encodedCount = stackalloc byte[sizeof(ushort)]; BinaryPrimitives.WriteUInt16LittleEndian(encodedCount, (ushort)records.Count); output.Write(encodedCount); foreach (byte[] record in records.OrderBy(static pair => pair.Key, StringComparer.Ordinal).Select(static pair => pair.Value)) + { output.Write(record); + } output.Write(binary.AsSpan(offset)); return output.ToArray(); } @@ -84,7 +92,9 @@ string nativeName _ => throw new InvalidDataException($"The compiled GLSL uniform '{nativeName}' has unsupported storage '{typeId}'.") }; if (name.Length == 0 || name.Length > byte.MaxValue || count <= 0 || count > byte.MaxValue) + { throw new InvalidDataException($"The compiled GLSL uniform '{nativeName}' exceeds the BGFX binary limits."); + } int registerCount = count * (type == ShaderUniformType.Mat3 ? 3 : type == ShaderUniformType.Mat4 ? 4 : 1); byte[] record = new byte[1 + name.Length + C_SHADER_UNIFORM_METADATA_SIZE]; record[0] = (byte)name.Length; diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs index 763cde291..114a81b03 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs @@ -10,8 +10,8 @@ using Inno.Core.Diagnostics; using Inno.Rendering; using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Build.Toolchains.Bgfx.Tools; @@ -66,14 +66,31 @@ CancellationToken cancellationToken { return new([], [], [new("BGFX_IR_GENERATION", DiagnosticSeverity.Error, failure.Message, failure.position)]); } - BgfxShadercResult native = await RunCompilerAsync(generated.source, generated.varying, request.stage.stage, - request.target, cancellationToken).ConfigureAwait(false); + BgfxShadercResult native = await RunCompilerAsync( + generated.source, + generated.varying, + request.stage.stage, + request.target, + cancellationToken + ).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); List diagnostics = ParseDiagnostics(native, generated.sourcePositions, new("inno-generated-stage", 0, 0)); - if (native.exitCode != 0 || native.bytes is null || native.bytes.Length == 0 || diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) - { + if (native.exitCode != 0 + || native.bytes is null + || native.bytes.Length == 0 + || diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error) + ) { if (!diagnostics.Any(static diagnostic => diagnostic.severity == DiagnosticSeverity.Error)) - diagnostics.Add(new("BGFX_SHADER_COMPILE_FAILED", DiagnosticSeverity.Error, $"BGFX shaderc exited with code {native.exitCode} without a usable binary.", new("inno-generated-stage", 0, 0))); + { + diagnostics.Add( + new( + "BGFX_SHADER_COMPILE_FAILED", + DiagnosticSeverity.Error, + $"BGFX shaderc exited with code {native.exitCode} without a usable binary.", + new("inno-generated-stage", 0, 0) + ) + ); + } return new([], generated.bindings, diagnostics); } IReadOnlyList reflectedBindings; @@ -86,13 +103,21 @@ CancellationToken cancellationToken return input.kind == ShaderIrInputKind.Storage || reflectedNames.Contains(binding.nativeName); }).ToArray(); if (request.target.capabilities.backend == GraphicsApi.OpenGL - || request.target.capabilities.backend == GraphicsApi.OpenGLES) + || request.target.capabilities.backend == GraphicsApi.OpenGLES + ) { native = native with { bytes = NormalizeGlslUniformTable(native.bytes, request.stage, reflectedBindings) }; + } } catch (InvalidDataException failure) { - diagnostics.Add(new("BGFX_SHADER_REFLECTION", DiagnosticSeverity.Error, failure.Message, - new("inno-generated-stage", 0, 0))); + diagnostics.Add( + new( + "BGFX_SHADER_REFLECTION", + DiagnosticSeverity.Error, + failure.Message, + new("inno-generated-stage", 0, 0) + ) + ); return new([], [], diagnostics); } return new(native.bytes, reflectedBindings, diagnostics); @@ -103,13 +128,20 @@ private static HashSet ReadReflectedUniformNames( GraphicsApi backend ) { if (binary.Length < C_SHADER_BINARY_HEADER_SIZE + sizeof(ushort)) + { throw new InvalidDataException("BGFX shaderc returned a truncated shader binary header."); + } if (binary[1] != (byte)'S' || binary[2] != (byte)'H' - || binary[0] is not ((byte)'V' or (byte)'F' or (byte)'C')) + || binary[0] is not ((byte)'V' or (byte)'F' or (byte)'C') + ) { throw new InvalidDataException("BGFX shaderc returned an unrecognized shader binary."); + } if (binary[3] != C_SHADER_BINARY_VERSION) + { throw new InvalidDataException( - $"BGFX shader binary version {binary[3]} does not match the bundled reader version {C_SHADER_BINARY_VERSION}."); + $"BGFX shader binary version {binary[3]} does not match the bundled reader version {C_SHADER_BINARY_VERSION}." + ); + } int offset = C_SHADER_BINARY_HEADER_SIZE; ushort count = BinaryPrimitives.ReadUInt16LittleEndian(binary.Slice(offset, sizeof(ushort))); @@ -122,7 +154,9 @@ GraphicsApi backend RequireBinaryRange(binary, offset, nameLength + C_SHADER_UNIFORM_METADATA_SIZE); string name = Encoding.UTF8.GetString(binary.Slice(offset, nameLength)); if (string.IsNullOrWhiteSpace(name) || !result.Add(name)) + { throw new InvalidDataException("BGFX shader binary contains an invalid reflected uniform table."); + } offset += nameLength + C_SHADER_UNIFORM_METADATA_SIZE; } if (backend == GraphicsApi.OpenGL || backend == GraphicsApi.OpenGLES) @@ -140,17 +174,22 @@ HashSet names RequireBinaryRange(payload, 0, sizeof(uint)); uint length = BinaryPrimitives.ReadUInt32LittleEndian(payload); if (length > int.MaxValue - sizeof(uint) - 1) + { throw new InvalidDataException("BGFX shaderc returned an invalid GLSL payload length."); + } RequireBinaryRange(payload, sizeof(uint), (int)length + 1); if (payload[sizeof(uint) + (int)length] != 0) + { throw new InvalidDataException("BGFX shaderc returned an unterminated GLSL payload."); + } List tokens; try { string source = S_GLSL_ENCODING.GetString(payload.Slice(sizeof(uint), (int)length)); tokens = BgfxSourceLexer.Tokenize(new ShaderSourceFile("bgfx-compiled-stage", source)) - .Where(static token => token.text != "\n").ToList(); + .Where(static token => token.text != "\n") + .ToList(); } catch (Exception failure) when (failure is DecoderFallbackException or BgfxSourceSyntaxException) { @@ -161,7 +200,9 @@ HashSet names foreach (BgfxSourceToken token in tokens) { if (token.isIdentifier) + { identifierCounts[token.text] = identifierCounts.GetValueOrDefault(token.text) + 1; + } } // Desktop GLSL can retain layout qualifiers that shaderc's uniform table scanner does not recognize. @@ -169,15 +210,19 @@ HashSet names for (int index = 0; index < tokens.Count; index++) { if (tokens[index].text != "uniform") + { continue; + } int typeIndex = index + 1; if (typeIndex < tokens.Count && tokens[typeIndex].text is "lowp" or "mediump" or "highp") + { typeIndex++; + } int nameIndex = typeIndex + 1; if (nameIndex + 1 < tokens.Count && tokens[nameIndex].isIdentifier && identifierCounts[tokens[nameIndex].text] > 1 - && tokens[nameIndex + 1].text is ";" or "[") - { + && tokens[nameIndex + 1].text is ";" or "[" + ) { names.Add(tokens[nameIndex].text); } } @@ -189,7 +234,9 @@ private static void RequireBinaryRange( int length ) { if (length < 0 || offset < 0 || offset > binary.Length - length) + { throw new InvalidDataException("BGFX shaderc returned a truncated reflected uniform table."); + } } private static List ParseDiagnostics( @@ -198,32 +245,45 @@ private static List ParseDiagnostics( ShaderSourcePosition fallback ) { var diagnostics = new List(); - string[] lines = (native.standardOutput + "\n" + native.standardError).Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + string[] lines = (native.standardOutput + "\n" + native.standardError).Split( + '\n', + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries + ); var sourceMap = new Dictionary(); foreach (string line in lines) { Match excerpt = SourceExcerptPattern().Match(line); if (!excerpt.Success || !int.TryParse(excerpt.Groups["line"].Value, out int physicalLine) - || !int.TryParse(excerpt.Groups["marker"].Value, out int marker)) + || !int.TryParse(excerpt.Groups["marker"].Value, out int marker) + ) { continue; + } if (marker >= 0 && marker < sourcePositions.Count) + { sourceMap[physicalLine] = sourcePositions[marker]; + } } foreach (string line in lines) { if (line == "Code:" || line == "---") + { continue; - DiagnosticSeverity severity = ErrorSeverityPattern().IsMatch(line) ? DiagnosticSeverity.Error - : WarningSeverityPattern().IsMatch(line) ? DiagnosticSeverity.Warning : DiagnosticSeverity.Info; + } + DiagnosticSeverity severity = ErrorSeverityPattern().IsMatch(line) + ? DiagnosticSeverity.Error + : WarningSeverityPattern().IsMatch(line) ? DiagnosticSeverity.Warning : DiagnosticSeverity.Info; Match match = SourceDiagnosticPattern().Match(line); ShaderSourcePosition position = fallback; if (match.Success && int.TryParse(match.Groups["line"].Value, out int sourceLine)) { _ = int.TryParse(match.Groups["column"].Value, out int column); - position = sourceMap.TryGetValue(sourceLine, out ShaderSourcePosition original) ? original - : new(fallback.assetPath, sourceLine, column); + position = sourceMap.TryGetValue(sourceLine, out ShaderSourcePosition original) + ? original + : new(fallback.assetPath, sourceLine, column); } - diagnostics.Add(new(severity == DiagnosticSeverity.Warning ? "BGFX_SHADER_WARNING" : "BGFX_SHADER_DIAGNOSTIC", severity, line, position)); + diagnostics.Add( + new(severity == DiagnosticSeverity.Warning ? "BGFX_SHADER_WARNING" : "BGFX_SHADER_DIAGNOSTIC", severity, line, position) + ); } return diagnostics; } @@ -233,47 +293,88 @@ private static void ValidateCapabilities( GraphicsCapabilities capabilities ) { if (stage.stage == ShaderStage.Compute) + { Require(GraphicsCapability.Compute); + } foreach (ShaderIrStageInput input in stage.inputs) { if (input.kind == ShaderIrInputKind.VertexAttribute && input.semantic == "instance-data") + { Require(GraphicsCapability.Instancing); + } if (input.kind == ShaderIrInputKind.Builtin && input.semantic == "vertex-id") + { Require(GraphicsCapability.ProceduralDraw); + } if (input.type.id == "sampled-texture2d-array") + { Require(GraphicsCapability.Texture2DArray); + } if (input.type.id == "sampled-texture3d") + { Require(GraphicsCapability.Texture3D); + } if (input.type.storage is ShaderStorageType storage) { if (stage.stage != ShaderStage.Compute) - throw new BgfxSourceSyntaxException("The BGFX runtime contract exposes storage bindings only for compute passes.", new("inno-generated-stage", 1, 1)); + { + throw new BgfxSourceSyntaxException( + "The BGFX runtime contract exposes storage bindings only for compute passes.", + new("inno-generated-stage", 1, 1) + ); + } Require(storage.isImage ? GraphicsCapability.StorageTexture : GraphicsCapability.StorageBuffer); if (input.location >= capabilities.limits.maxComputeBindings) - throw new BgfxSourceSyntaxException("A storage binding exceeds the target compute binding limit.", new("inno-generated-stage", 1, 1)); + { + throw new BgfxSourceSyntaxException( + "A storage binding exceeds the target compute binding limit.", + new("inno-generated-stage", 1, 1) + ); + } if (storage.isImage) { if (storage.array) + { Require(GraphicsCapability.Texture2DArray); + } if (storage.dimension == RenderTextureDimension.Texture3D) + { Require(GraphicsCapability.Texture3D); + } if (!capabilities.SupportsStorage(storage.format!.Value, storage.access)) - throw new BgfxSourceSyntaxException($"Storage format '{storage.format}' does not support '{storage.access}' on this target.", new("inno-generated-stage", 1, 1)); + { + throw new BgfxSourceSyntaxException( + $"Storage format '{storage.format}' does not support '{storage.access}' on this target.", + new("inno-generated-stage", 1, 1) + ); + } } } } foreach (ShaderIrStageOutput output in stage.outputs) { if (output.kind == ShaderIrOutputKind.Depth) + { Require(GraphicsCapability.FragmentDepth); + } if (output.kind == ShaderIrOutputKind.Color && output.location >= capabilities.limits.maxColorAttachments) - throw new BgfxSourceSyntaxException($"Color attachment {output.location} exceeds the target limit {capabilities.limits.maxColorAttachments}.", new("inno-generated-stage", 1, 1)); + { + throw new BgfxSourceSyntaxException( + $"Color attachment {output.location} exceeds the target limit {capabilities.limits.maxColorAttachments}.", + new("inno-generated-stage", 1, 1) + ); + } } return; void Require(GraphicsCapability capability) { if (!capabilities.Supports(capability)) - throw new BgfxSourceSyntaxException($"The stage requires unsupported capability '{capability}'.", new("inno-generated-stage", 1, 1)); + { + throw new BgfxSourceSyntaxException( + $"The stage requires unsupported capability '{capability}'.", + new("inno-generated-stage", 1, 1) + ); + } } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxPreprocessorExpression.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxPreprocessorExpression.cs index 5d439459b..7be20e818 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxPreprocessorExpression.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxPreprocessorExpression.cs @@ -11,10 +11,14 @@ internal sealed class BgfxPreprocessorExpression(IReadOnlyList internal long Evaluate() { if (tokens.Count == 0) + { throw new InvalidOperationException("A preprocessing expression is empty."); + } long value = Conditional(true); if (m_offset != tokens.Count) + { Fail("Unexpected token in integer constant expression."); + } return value; } @@ -22,10 +26,14 @@ private long Conditional(bool evaluate) { long condition = Binary(1, evaluate); if (!Match("?")) + { return condition; + } long whenTrue = Conditional(evaluate && condition != 0); if (!Match(":")) + { Fail("Expected ':' in conditional expression."); + } long whenFalse = Conditional(evaluate && condition == 0); return condition != 0 ? whenTrue : whenFalse; } @@ -40,7 +48,9 @@ bool evaluate string operation = tokens[m_offset].text; int precedence = Precedence(operation); if (precedence < minimum) + { break; + } m_offset++; bool evaluateRight = evaluate && !(operation == "&&" && left == 0 || operation == "||" && left != 0); long right = Binary(precedence + 1, evaluateRight); @@ -50,17 +60,27 @@ bool evaluate continue; } if (operation is "/" or "%" && right == 0) + { Fail("Division by zero in integer constant expression."); + } left = operation switch { "||" => left != 0 || right != 0 ? 1 : 0, "&&" => left != 0 && right != 0 ? 1 : 0, - "|" => left | right, "^" => left ^ right, "&" => left & right, - "==" => left == right ? 1 : 0, "!=" => left != right ? 1 : 0, - "<" => left < right ? 1 : 0, ">" => left > right ? 1 : 0, - "<=" => left <= right ? 1 : 0, ">=" => left >= right ? 1 : 0, - "<<" => left << (int)right, ">>" => left >> (int)right, - "+" => unchecked(left + right), "-" => unchecked(left - right), "*" => unchecked(left * right), + "|" => left | right, + "^" => left ^ right, + "&" => left & right, + "==" => left == right ? 1 : 0, + "!=" => left != right ? 1 : 0, + "<" => left < right ? 1 : 0, + ">" => left > right ? 1 : 0, + "<=" => left <= right ? 1 : 0, + ">=" => left >= right ? 1 : 0, + "<<" => left << (int)right, + ">>" => left >> (int)right, + "+" => unchecked(left + right), + "-" => unchecked(left - right), + "*" => unchecked(left * right), "/" => left == long.MinValue && right == -1 ? long.MinValue : left / right, "%" => left == long.MinValue && right == -1 ? 0 : left % right, _ => throw new InvalidOperationException("Unknown preprocessing operation.") @@ -72,34 +92,54 @@ bool evaluate private long Unary(bool evaluate) { if (Match("!")) + { return Unary(evaluate) == 0 ? 1 : 0; + } if (Match("~")) + { return ~Unary(evaluate); + } if (Match("-")) + { return unchecked(-Unary(evaluate)); + } if (Match("+")) + { return Unary(evaluate); + } if (Match("(")) { long value = Conditional(evaluate); if (!Match(")")) + { Fail("Expected ')' in constant expression."); + } return value; } if (m_offset >= tokens.Count) + { Fail("Expected an integer expression."); + } BgfxSourceToken token = tokens[m_offset++]; if (token.isIdentifier) + { return 0; + } string number = token.text.TrimEnd('u', 'U', 'l', 'L'); try { if (number.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + { return unchecked((long)ulong.Parse(number.AsSpan(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture)); + } if (number.Length > 1 && number[0] == '0') + { return Convert.ToInt64(number, 8); + } if (long.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out long parsed)) + { return parsed; + } } catch (Exception exception) when (exception is FormatException or OverflowException or ArgumentException) { } throw new BgfxSourceSyntaxException($"'{token.text}' is not an integer constant.", token.position); @@ -108,7 +148,9 @@ private long Unary(bool evaluate) private bool Match(string value) { if (m_offset >= tokens.Count || tokens[m_offset].text != value) + { return false; + } m_offset++; return true; } @@ -116,11 +158,19 @@ private bool Match(string value) private void Fail(string message) => throw new BgfxSourceSyntaxException(message, tokens[Math.Clamp(m_offset, 0, tokens.Count - 1)].position); - private static int Precedence(string operation) => operation switch + private static int Precedence(string operation) + => operation switch { - "||" => 1, "&&" => 2, "|" => 3, "^" => 4, "&" => 5, - "==" or "!=" => 6, "<" or ">" or "<=" or ">=" => 7, - "<<" or ">>" => 8, "+" or "-" => 9, "*" or "/" or "%" => 10, + "||" => 1, + "&&" => 2, + "|" => 3, + "^" => 4, + "&" => 5, + "==" or "!=" => 6, + "<" or ">" or "<=" or ">=" => 7, + "<<" or ">>" => 8, + "+" or "-" => 9, + "*" or "/" or "%" => 10, _ => 0 }; } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs index 0b09608db..06bc78a82 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs @@ -38,8 +38,11 @@ public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) } catch (BgfxSourceSyntaxException failure) { - return new(null, preprocessor.dependencies, - [new ShaderSourceDiagnostic("SHADER_SOURCE_INTERFACE", DiagnosticSeverity.Error, failure.Message, failure.position)]); + return new( + null, + preprocessor.dependencies, + [new ShaderSourceDiagnostic("SHADER_SOURCE_INTERFACE", DiagnosticSeverity.Error, failure.Message, failure.position)] + ); } } } @@ -62,7 +65,9 @@ internal ShaderSourceFunction Parse() while (m_offset < tokens.Count) { if (Match(";")) + { continue; + } int declarationStart = m_offset; if (Peek("struct")) { @@ -73,25 +78,35 @@ internal ShaderSourceFunction Parse() bool alias = Match("typedef"); bool constant = false; while (m_offset < tokens.Count && IsQualifier(tokens[m_offset].text)) + { constant |= tokens[m_offset++].text == "const"; + } ShaderSourceType type = ReadType(); BgfxSourceToken name = ReadIdentifier(); if (Match("(")) { if (alias) + { Fail("Function typedefs are not source module value types.", name); + } List parameters = ReadParameters(); if (name.text == "main") + { Fail("A source module cannot declare main(); shader entries are generated from graph outputs.", name); + } globals.Add(name.text); if (Match(";")) + { continue; + } Require("{"); m_bodies.Add((parameters, ReadBody())); if (name.text == request.entryPoint) { if (!StringComparer.Ordinal.Equals(name.position.assetPath, request.source.assetPath)) + { Fail("The exported function must be declared in its selected source file, not an include.", name); + } m_exports.Add(new(name.text, type, parameters, name.position)); } continue; @@ -100,28 +115,40 @@ internal ShaderSourceFunction Parse() if (alias) { if (!m_types.TryAdd(name.text, type)) + { Fail($"Type '{name.text}' is already declared.", name); + } Require(";"); typeDeclarations.Add((declarationStart, m_offset)); continue; } if (!constant) + { Fail("Module globals must be constants; stage inputs and resource bindings belong to the graph target.", name); + } globals.Add(name.text); if (Match("=")) { List initializer = ReadUntilSemicolon(); if (type.id is "int" or "uint") + { m_constants[name.text] = EvaluateInteger(initializer, name); + } } else + { Require(";"); + } } if (m_exports.Count != 1) - throw new BgfxSourceSyntaxException(m_exports.Count == 0 + { + throw new BgfxSourceSyntaxException( + m_exports.Count == 0 ? $"Source does not define the selected public function '{request.entryPoint}'." : $"Public function '{request.entryPoint}' is overloaded or defined more than once; select an unambiguous export.", - new(request.source.assetPath, 1, 1)); + new(request.source.assetPath, 1, 1) + ); + } ValidateExplicitInterfaces(); return m_exports[0]; } @@ -130,7 +157,9 @@ private List ReadParameters() { var parameters = new List(); if (Match(")")) + { return parameters; + } if (Peek("void") && m_offset + 1 < tokens.Count && tokens[m_offset + 1].text == ")") { m_offset += 2; @@ -146,7 +175,9 @@ private List ReadParameters() if (qualifier.text is "in" or "out" or "inout") { if (directionAssigned) + { Fail("A parameter has more than one direction qualifier.", qualifier); + } directionAssigned = true; direction = qualifier.text switch { @@ -157,19 +188,28 @@ private List ReadParameters() m_offset++; } else if (IsQualifier(qualifier.text)) + { m_offset++; + } else + { break; + } } ShaderSourceType type = ReadType(); BgfxSourceToken name = ReadIdentifier(); if (type.id == "void") + { Fail("A parameter cannot have void type.", name); + } type = ReadArray(type); if (parameters.Any(parameter => parameter.name == name.text)) + { Fail("Duplicate public parameter name.", name); + } parameters.Add(new(name.text, type, direction)); - } while (Match(",")); + } + while (Match(",")); Require(")"); return parameters; } @@ -183,41 +223,64 @@ private void ReadStructure() while (!Match("}")) { while (m_offset < tokens.Count && IsQualifier(tokens[m_offset].text)) + { m_offset++; + } ShaderSourceType type = ReadType(); if (type.id == "void") + { Fail("A structure field cannot have void type.", name); + } do { BgfxSourceToken field = ReadIdentifier(); ShaderSourceType fieldType = ReadArray(type); if (fields.Any(existing => existing.name == field.text)) + { Fail("Duplicate structure member name.", field); + } fields.Add(new(field.text, fieldType)); - } while (Match(",")); + } + while (Match(",")); Require(";"); } Require(";"); if (fields.Count == 0) + { Fail("A structure requires at least one field.", name); + } if (!m_types.TryAdd(name.text, ShaderSourceType.Structure("struct:" + name.text, fields))) + { Fail($"Type '{name.text}' is already declared.", name); + } } private ShaderSourceType ReadType() { BgfxSourceToken token = ReadIdentifier(); if (m_types.TryGetValue(token.text, out ShaderSourceType? declared)) + { return declared; + } string? canonical = token.text switch { "void" or "bool" or "int" or "uint" or "float" or "double" => token.text, "half" => "float16", - "vec2" or "float2" => "float2", "vec3" or "float3" => "float3", "vec4" or "float4" => "float4", - "ivec2" or "int2" => "int2", "ivec3" or "int3" => "int3", "ivec4" or "int4" => "int4", - "uvec2" or "uint2" => "uint2", "uvec3" or "uint3" => "uint3", "uvec4" or "uint4" => "uint4", - "bvec2" or "bool2" => "bool2", "bvec3" or "bool3" => "bool3", "bvec4" or "bool4" => "bool4", - "mat2" or "float2x2" => "float2x2", "mat3" or "float3x3" => "float3x3", "mat4" or "float4x4" => "float4x4", + "vec2" or "float2" => "float2", + "vec3" or "float3" => "float3", + "vec4" or "float4" => "float4", + "ivec2" or "int2" => "int2", + "ivec3" or "int3" => "int3", + "ivec4" or "int4" => "int4", + "uvec2" or "uint2" => "uint2", + "uvec3" or "uint3" => "uint3", + "uvec4" or "uint4" => "uint4", + "bvec2" or "bool2" => "bool2", + "bvec3" or "bool3" => "bool3", + "bvec4" or "bool4" => "bool4", + "mat2" or "float2x2" => "float2x2", + "mat3" or "float3x3" => "float3x3", + "mat4" or "float4x4" => "float4x4", "sampler2D" or "BgfxSampler2D" => "sampled-texture2d", "sampler2DArray" or "BgfxSampler2DArray" => "sampled-texture2d-array", "sampler3D" or "BgfxSampler3D" => "sampled-texture3d", @@ -225,7 +288,9 @@ private ShaderSourceType ReadType() _ => null }; if (canonical is null) + { Fail($"Unsupported or undeclared source type '{token.text}'.", token); + } return ShaderSourceType.Atomic(canonical!); } @@ -236,17 +301,25 @@ private ShaderSourceType ReadArray(ShaderSourceType element) { BgfxSourceToken start = Current(); if (element.id == "void") + { Fail("An array cannot contain void values.", start); + } var expression = new List(); while (!Match("]")) + { expression.Add(Next()); + } long count = EvaluateInteger(expression, start); if (count <= 0 || count > int.MaxValue) + { Fail("Function interface arrays require a positive, fixed 32-bit length.", start); + } lengths.Add((int)count); } for (int i = lengths.Count - 1; i >= 0; i--) + { element = ShaderSourceType.ArrayOf(element, lengths[i]); + } return element; } @@ -255,7 +328,9 @@ private long EvaluateInteger( BgfxSourceToken location ) { if (expression.Count == 0) + { Fail("Expected a fixed integer expression.", location); + } var values = new List(); foreach (BgfxSourceToken token in expression) { @@ -265,11 +340,15 @@ BgfxSourceToken location continue; } if (!m_constants.TryGetValue(token.text, out long constant)) + { Fail($"Unresolved array constant '{token.text}'.", token); + } values.Add(new("(", token.position)); - foreach (BgfxSourceToken literal in BgfxSourceLexer.Tokenize(new(token.position.assetPath, - constant.ToString(CultureInfo.InvariantCulture)))) + foreach (BgfxSourceToken literal in BgfxSourceLexer.Tokenize( + new(token.position.assetPath, constant.ToString(CultureInfo.InvariantCulture)) + )) { values.Add(literal with { position = token.position }); + } values.Add(new(")", token.position)); } return new BgfxPreprocessorExpression(values).Evaluate(); @@ -284,15 +363,25 @@ private List ReadUntilSemicolon() { BgfxSourceToken token = Next(); if (token.text == ";" && braces == 0 && parentheses == 0) + { return result; + } if (token.text == "{") + { braces++; + } if (token.text == "}") + { braces--; + } if (token.text == "(") + { parentheses++; + } if (token.text == ")") + { parentheses--; + } result.Add(token); } } @@ -305,9 +394,13 @@ private List ReadBody() { BgfxSourceToken token = Next(); if (token.text == "{") + { nesting++; + } if (token.text == "}") + { nesting--; + } body.Add(token); } return body; @@ -323,36 +416,51 @@ private void ValidateExplicitInterfaces() { BgfxSourceToken token = body[index]; if (index != 0 && body[index - 1].text == ".") + { continue; + } if (!explicitNames.Contains(token.text) && IsImplicitStageName(token.text)) - Fail($"Source functions must receive '{token.text}' through an explicit parameter; native stage bindings are generated by the graph target.", token); + { + Fail( + $"Source functions must receive '{token.text}' through an explicit parameter; native stage bindings are generated by the graph target.", + token + ); + } } } } private static bool IsImplicitStageName(string name) => name.StartsWith("gl_", StringComparison.Ordinal) || name.StartsWith("inno_", StringComparison.Ordinal) - || name.StartsWith("u_inno_", StringComparison.Ordinal) || name.StartsWith("s_inno_", StringComparison.Ordinal) - || name.StartsWith("v_texcoord", StringComparison.Ordinal) || name.StartsWith("v_color", StringComparison.Ordinal) - || name.StartsWith("i_data", StringComparison.Ordinal) || name.StartsWith("a_texcoord", StringComparison.Ordinal) - || name.StartsWith("a_color", StringComparison.Ordinal) - || name is "a_position" or "a_normal" or "a_tangent" or "a_bitangent" or "a_weight" or "a_indices" - or "u_viewRect" or "u_viewTexel" or "u_view" or "u_invView" or "u_proj" or "u_invProj" or "u_viewProj" - or "u_invViewProj" or "u_model" or "u_modelView" or "u_invModelView" or "u_modelViewProj" or "u_alphaRef4"; + || name.StartsWith("u_inno_", StringComparison.Ordinal) || name.StartsWith("s_inno_", StringComparison.Ordinal) + || name.StartsWith("v_texcoord", StringComparison.Ordinal) || name.StartsWith("v_color", StringComparison.Ordinal) + || name.StartsWith("i_data", StringComparison.Ordinal) || name.StartsWith("a_texcoord", StringComparison.Ordinal) + || name.StartsWith("a_color", StringComparison.Ordinal) + || name is "a_position" or "a_normal" or "a_tangent" or "a_bitangent" or "a_weight" or "a_indices" + or "u_viewRect" or "u_viewTexel" or "u_view" or "u_invView" or "u_proj" or "u_invProj" or "u_viewProj" + or "u_invViewProj" or "u_model" or "u_modelView" or "u_invModelView" or "u_modelViewProj" or "u_alphaRef4"; private BgfxSourceToken ReadIdentifier() { BgfxSourceToken token = Next(); if (!token.isIdentifier) + { Fail($"Expected an identifier, found '{token.text}'.", token); + } return token; } private BgfxSourceToken Current() { if (m_offset >= tokens.Count) - throw new BgfxSourceSyntaxException("Unexpected end of source declaration.", tokens.Count == 0 - ? new(request.source.assetPath, 1, 1) : tokens[^1].position); + { + throw new BgfxSourceSyntaxException( + "Unexpected end of source declaration.", + tokens.Count == 0 + ? new(request.source.assetPath, 1, 1) + : tokens[^1].position + ); + } return tokens[m_offset]; } @@ -362,20 +470,29 @@ private BgfxSourceToken Next() m_offset++; return token; } + private bool Peek(string value) => m_offset < tokens.Count && tokens[m_offset].text == value; + private bool Match(string value) { if (!Peek(value)) + { return false; + } m_offset++; return true; } + private void Require(string value) { if (!Match(value)) + { Fail($"Expected '{value}'.", Current()); + } } + private static bool IsQualifier(string value) => value is "const" or "static" or "inline" or "highp" or "mediump" or "lowp"; + private static void Fail( string message, BgfxSourceToken token diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs index 4308aa649..07993d9b0 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs @@ -35,22 +35,30 @@ internal static List Tokenize(ShaderSourceFile source) { Advance(); if (offset < text.Length && text[offset] == '\r') + { Advance(); + } if (offset < text.Length && text[offset] == '\n') + { Advance(); + } continue; } if (char.IsWhiteSpace(current)) { if (current == '\n') + { tokens.Add(new("\n", new(source.assetPath, line, column))); + } Advance(); continue; } if (current == '/' && offset + 1 < text.Length && text[offset + 1] == '/') { while (offset < text.Length && text[offset] != '\n') + { Advance(); + } continue; } var position = new ShaderSourcePosition(source.assetPath, line, column); @@ -65,18 +73,25 @@ internal static List Tokenize(ShaderSourceFile source) Advance(); Advance(); closed = true; break; } if (text[offset] == '\n') + { tokens.Add(new("\n", new(source.assetPath, line, column))); + } Advance(); } if (!closed) + { throw new BgfxSourceSyntaxException("Unterminated block comment.", position); + } continue; } int start = offset; if (char.IsLetter(current) || current == '_') { do - Advance(); while (offset < text.Length && (char.IsLetterOrDigit(text[offset]) || text[offset] == '_')); + { + Advance(); + } + while (offset < text.Length && (char.IsLetterOrDigit(text[offset]) || text[offset] == '_')); } else if (char.IsDigit(current) || (current == '.' && offset + 1 < text.Length && char.IsDigit(text[offset + 1]))) { @@ -87,8 +102,11 @@ internal static List Tokenize(ShaderSourceFile source) Advance(); bool exponent = hexadecimal ? previous is 'p' or 'P' : previous is 'e' or 'E'; if (exponent && offset < text.Length && text[offset] is '+' or '-') + { Advance(); - } while (offset < text.Length && (char.IsLetterOrDigit(text[offset]) || text[offset] == '.')); + } + } + while (offset < text.Length && (char.IsLetterOrDigit(text[offset]) || text[offset] == '.')); } else if (current is '"' or '\'') { @@ -104,12 +122,18 @@ internal static List Tokenize(ShaderSourceFile source) break; } if (character == '\\' && offset < text.Length) + { Advance(); + } else if (character == '\n') + { throw new BgfxSourceSyntaxException("Unterminated string literal.", position); + } } if (!closed) + { throw new BgfxSourceSyntaxException("Unterminated string literal.", position); + } } else { @@ -119,7 +143,9 @@ internal static List Tokenize(ShaderSourceFile source) char second = text[offset]; Advance(); if (current == second && current is '<' or '>' && offset < text.Length && text[offset] == '=') + { Advance(); + } } } tokens.Add(new(text[start..offset], position)); @@ -134,15 +160,16 @@ void Advance() column = 1; } else + { column++; + } } } private static bool IsPair( char first, char second - ) - => (first, second) is ('&', '&') or ('|', '|') or ('=', '=') or ('!', '=') or ('<', '=') or ('>', '=') - or ('<', '<') or ('>', '>') or ('#', '#') or ('+', '+') or ('-', '-') or ('+', '=') or ('-', '=') - or ('*', '=') or ('/', '=') or ('&', '=') or ('|', '=') or ('^', '=') or ('%', '='); + ) => (first, second) is ('&', '&') or ('|', '|') or ('=', '=') or ('!', '=') or ('<', '=') or ('>', '=') + or ('<', '<') or ('>', '>') or ('#', '#') or ('+', '+') or ('-', '-') or ('+', '=') or ('-', '=') + or ('*', '=') or ('/', '=') or ('&', '=') or ('|', '=') or ('^', '=') or ('%', '='); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs index e8acfc1ae..d8aa7659c 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs @@ -34,9 +34,16 @@ private List ProcessFile( int depth ) { if (m_once.Contains(source.assetPath)) + { return []; + } if (depth >= C_MAX_DEPTH) - throw new BgfxSourceSyntaxException("Shader include depth exceeded; check for an unguarded include cycle.", new(source.assetPath, 1, 1)); + { + throw new BgfxSourceSyntaxException( + "Shader include depth exceeded; check for an unguarded include cycle.", + new(source.assetPath, 1, 1) + ); + } List input = BgfxSourceLexer.Tokenize(source); var output = new List(); var pending = new List(); @@ -46,21 +53,31 @@ int depth { int start = index; while (index < input.Count && input[index].text != "\n") + { index++; + } List line = input.GetRange(start, index - start); if (index < input.Count) + { index++; + } if (line.Count == 0) + { continue; + } if (line[0].text != "#") { if (active) + { pending.AddRange(line); + } continue; } Flush(); if (line.Count < 2) + { continue; + } BgfxSourceToken directive = line[1]; List arguments = line.GetRange(2, line.Count - 2); switch (directive.text) @@ -70,9 +87,12 @@ int depth case "ifndef": { if (directive.text != "if" && (arguments.Count != 1 || !arguments[0].isIdentifier)) + { Fail("Expected one macro name after conditional directive.", directive); - bool selected = active && (directive.text == "if" ? Evaluate(arguments, directive) : - m_macros.ContainsKey(arguments[0].text) == (directive.text == "ifdef")); + } + bool selected = active && (directive.text == "if" + ? Evaluate(arguments, directive) + : m_macros.ContainsKey(arguments[0].text) == (directive.text == "ifdef")); conditions.Push(new(active, selected, false)); active = selected; break; @@ -80,7 +100,9 @@ int depth case "elif": { if (conditions.Count == 0 || conditions.Peek().hasElse) + { Fail("Unexpected #elif.", directive); + } Conditional branch = conditions.Pop(); active = branch.parentActive && !branch.taken && Evaluate(arguments, directive); conditions.Push(branch with { taken = branch.taken || active }); @@ -89,7 +111,9 @@ int depth case "else": { if (arguments.Count != 0 || conditions.Count == 0 || conditions.Peek().hasElse) + { Fail("Unexpected #else.", directive); + } Conditional branch = conditions.Pop(); active = branch.parentActive && !branch.taken; conditions.Push(branch with { taken = true, hasElse = true }); @@ -97,12 +121,16 @@ int depth } case "endif": if (arguments.Count != 0 || conditions.Count == 0) + { Fail("Unexpected #endif.", directive); + } active = conditions.Pop().parentActive; break; default: if (active) + { ApplyDirective(); + } break; } @@ -113,7 +141,9 @@ void ApplyDirective() case "define": Define(arguments, directive); break; case "undef": if (arguments.Count != 1 || !arguments[0].isIdentifier) + { Fail("Expected one macro name after #undef.", directive); + } m_macros.Remove(arguments[0].text); break; case "include": @@ -121,9 +151,13 @@ void ApplyDirective() List expanded = Expand(arguments, [], 0); string include; if (expanded.Count == 1 && expanded[0].text.StartsWith('"') && expanded[0].text.EndsWith('"')) + { include = expanded[0].text[1..^1]; + } else if (expanded.Count > 2 && expanded[0].text == "<" && expanded[^1].text == ">") + { include = string.Concat(expanded.Skip(1).Take(expanded.Count - 2).Select(static token => token.text)); + } else { Fail("Expected a quoted or bracketed include path.", directive); @@ -138,7 +172,10 @@ void ApplyDirective() failure is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException && RetirementPendingException.Find(failure) is null) { - throw new BgfxSourceSyntaxException($"Cannot resolve include '{include}': {failure.Message}", directive.position); + throw new BgfxSourceSyntaxException( + $"Cannot resolve include '{include}': {failure.Message}", + directive.position + ); } ArgumentNullException.ThrowIfNull(dependency); ArgumentException.ThrowIfNullOrWhiteSpace(dependency.assetPath); @@ -149,9 +186,13 @@ failure is IOException or UnauthorizedAccessException or InvalidOperationExcepti } case "pragma": if (arguments.Count == 1 && arguments[0].text == "once") + { m_once.Add(source.assetPath); + } else + { Fail("Unsupported module pragma; stage configuration belongs to the graph target.", directive); + } break; case "error": Fail(string.Join(" ", arguments.Select(static token => token.text)), directive); break; default: Fail($"Unsupported module preprocessor directive '#{directive.text}'.", directive); break; @@ -160,13 +201,17 @@ failure is IOException or UnauthorizedAccessException or InvalidOperationExcepti } Flush(); if (conditions.Count != 0) + { throw new BgfxSourceSyntaxException("Unterminated preprocessor conditional.", new(source.assetPath, 1, 1)); + } return output; void Flush() { if (pending.Count == 0) + { return; + } output.AddRange(Expand(pending, [], 0)); pending.Clear(); } @@ -177,7 +222,9 @@ private bool Evaluate( BgfxSourceToken directive ) { if (input.Count == 0) + { Fail("Expected a preprocessor expression.", directive); + } var replaced = new List(); for (int i = 0; i < input.Count; i++) { @@ -189,17 +236,25 @@ BgfxSourceToken directive } bool parenthesized = i + 1 < input.Count && input[i + 1].text == "("; if (parenthesized) + { i++; + } if (++i >= input.Count || !input[i].isIdentifier) + { Fail("Expected a macro identifier after defined.", token); + } bool defined = m_macros.ContainsKey(input[i].text); if (parenthesized && (++i >= input.Count || input[i].text != ")")) + { Fail("Expected ')' after defined.", token); + } replaced.Add(new(defined ? "1" : "0", token.position)); } List expanded = Expand(replaced, [], 0); if (expanded.Count == 0) + { Fail("Preprocessor expression expanded to no tokens.", directive); + } return new BgfxPreprocessorExpression(expanded).Evaluate() != 0; } @@ -208,43 +263,59 @@ private void Define( BgfxSourceToken directive ) { if (arguments.Count == 0 || !arguments[0].isIdentifier) + { Fail("Expected a macro identifier after #define.", directive); + } BgfxSourceToken name = arguments[0]; int offset = 1; string[]? parameters = null; - if (offset < arguments.Count && arguments[offset].text == "(" && - arguments[offset].position.line == name.position.line && - arguments[offset].position.column == name.position.column + name.text.Length) - { + if (offset < arguments.Count && arguments[offset].text == "(" + && arguments[offset].position.line == name.position.line + && arguments[offset].position.column == name.position.column + name.text.Length + ) { offset++; var names = new List(); while (offset < arguments.Count && arguments[offset].text != ")") { if (!arguments[offset].isIdentifier) + { Fail("Expected a named macro parameter.", arguments[offset]); + } string parameter = arguments[offset++].text; if (names.Contains(parameter, StringComparer.Ordinal)) + { Fail("Duplicate macro parameter.", name); + } names.Add(parameter); if (offset < arguments.Count && arguments[offset].text == ",") { offset++; if (offset >= arguments.Count || arguments[offset].text == ")") + { Fail("A macro parameter is missing after ','.", name); + } } else if (offset < arguments.Count && arguments[offset].text != ")") + { Fail("Expected ',' or ')' in macro declaration.", arguments[offset]); + } } if (offset >= arguments.Count) + { Fail("Unterminated macro parameter list.", name); + } offset++; parameters = names.ToArray(); } var macro = new Macro(parameters, arguments.Skip(offset).ToArray()); - if (m_macros.TryGetValue(name.text, out Macro? previous) && - (!SameParameters(previous.parameters, parameters) || - !previous.replacement.Select(static token => token.text).SequenceEqual(macro.replacement.Select(static token => token.text)))) + if (m_macros.TryGetValue(name.text, out Macro? previous) + && (!SameParameters(previous.parameters, parameters) + || !previous.replacement + .Select(static token => token.text) + .SequenceEqual(macro.replacement.Select(static token => token.text))) + ) { Fail($"Conflicting macro definition '{name.text}'.", name); + } m_macros[name.text] = macro; } @@ -254,7 +325,9 @@ private List Expand( int depth ) { if (depth >= C_MAX_DEPTH && tokens.Count != 0) + { Fail("Shader macro expansion exceeded its depth budget.", tokens[0]); + } var pending = tokens.Select(token => new ExpansionToken(token, disabled)).ToList(); var result = new List(); for (int i = 0; i < pending.Count; i++) @@ -262,7 +335,9 @@ int depth ExpansionToken current = pending[i]; BgfxSourceToken token = current.token; if (++m_emittedTokens > C_MAX_TOKENS) + { Fail("Shader source expansion exceeded its token budget.", token); + } if (token.text == "__LINE__") { result.Add(new(token.position.line.ToString(CultureInfo.InvariantCulture), token.position)); @@ -295,7 +370,9 @@ int depth { BgfxSourceToken next = pending[i].token; if (next.text == ")" && nesting == 0) + { break; + } if (next.text == "," && nesting == 0) { arguments.Add(argument); @@ -303,26 +380,40 @@ int depth continue; } if (next.text == "(") + { nesting++; + } if (next.text == ")") + { nesting--; + } argument.Add(next); } if (i >= pending.Count) + { Fail("Unterminated function-like macro invocation.", token); + } if (argument.Count != 0 || arguments.Count != 0 || macro.parameters.Length != 0) + { arguments.Add(argument); + } if (arguments.Count != macro.parameters.Length) + { Fail($"Macro '{token.text}' has an incorrect argument count.", token); + } replacement = Substitute(macro, arguments, token, current.disabled, depth); } else + { replacement = Paste(replacement, token); + } // Rescan replacement tokens together with the following input. An alias may expand to // a function-like macro whose '(' was not part of the alias replacement list. var nestedDisabled = new HashSet(current.disabled, StringComparer.Ordinal) { token.text }; if (nestedDisabled.Count >= C_MAX_DEPTH) + { Fail("Shader macro expansion exceeded its depth budget.", token); + } pending.RemoveRange(start, i - start + 1); pending.InsertRange(start, replacement.Select(value => new ExpansionToken(value, nestedDisabled))); i = start - 1; @@ -345,9 +436,12 @@ int depth { int parameter = Array.IndexOf(macro.parameters!, macro.replacement[++index].text); if (parameter < 0) + { Fail("Stringification requires a macro parameter.", item); + } string literal = string.Join(" ", arguments[parameter].Select(static value => value.text)) - .Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal); + .Replace("\\", "\\\\", StringComparison.Ordinal) + .Replace("\"", "\\\"", StringComparison.Ordinal); substituted.Add(new('"' + literal + '"', invocation.position)); continue; } @@ -357,12 +451,16 @@ int depth substituted.Add(item); continue; } - bool pasted = index > 0 && macro.replacement[index - 1].text == "##" || - index + 1 < macro.replacement.Length && macro.replacement[index + 1].text == "##"; + bool pasted = index > 0 && macro.replacement[index - 1].text == "##" + || index + 1 < macro.replacement.Length && macro.replacement[index + 1].text == "##"; if (pasted && arguments[parameterIndex].Count == 0) + { substituted.Add(new(string.Empty, invocation.position)); + } else + { substituted.AddRange(pasted ? arguments[parameterIndex] : Expand(arguments[parameterIndex], disabled, depth + 1)); + } } return Paste(substituted, invocation); } @@ -380,11 +478,15 @@ BgfxSourceToken invocation continue; } if (output.Count == 0 || i + 1 >= substituted.Count) + { Fail("Token pasting requires two nonempty operands.", invocation); + } string combined = output[^1].text + substituted[++i].text; List joined = BgfxSourceLexer.Tokenize(new(invocation.position.assetPath, combined)); if (combined.Length > 0 && joined.Count != 1) + { Fail("Token pasting did not produce one preprocessing token.", invocation); + } output[^1] = new(combined, invocation.position); } output.RemoveAll(static token => token.text.Length == 0); @@ -394,8 +496,7 @@ BgfxSourceToken invocation private static bool SameParameters( string[]? first, string[]? second - ) - => first is null ? second is null : second is not null && first.SequenceEqual(second); + ) => first is null ? second is null : second is not null && first.SequenceEqual(second); private static void Fail( string message, @@ -406,10 +507,12 @@ private sealed record Macro( string[]? parameters, BgfxSourceToken[] replacement ); + private sealed record ExpansionToken( BgfxSourceToken token, HashSet disabled ); + private readonly record struct Conditional( bool parentActive, bool taken, diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs index 43588096e..e88915de8 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs @@ -19,16 +19,25 @@ CancellationToken cancellationToken ) { context.RequireBindings(request.component); string definition = Path.Combine(request.component.GetToolchainRoot(context.engineRoot), "Native", "SharedBindings"); - string build = await NativeCMakeExecutor.BuildAsync(context, request.component, definition, - "inno_bgfx_binding", request.bindingCmakeArguments, cancellationToken).ConfigureAwait(false); - string archive = NativeCMakeExecutor.FindOutput(context, build, - "inno_bgfx_binding" + context.RequireToolchain().linkPlan.GetFileExtension(NativeLibraryKind.Static)); + string build = await NativeCMakeExecutor.BuildAsync( + context, + request.component, + definition, + "inno_bgfx_binding", + request.bindingCmakeArguments, + cancellationToken + ).ConfigureAwait(false); + string archive = NativeCMakeExecutor.FindOutput( + context, + build, + "inno_bgfx_binding" + context.RequireToolchain().linkPlan.GetFileExtension(NativeLibraryKind.Static) + ); var linking = profile.CreateBindingLinkSettings(archive); string script = Path.Combine(context.GetNativeBuildRoot(request.component), "BindingProject.lua"); string text = "dofile(" + Literal(Path.Combine(source, "scripts", "genie.lua")) + ")\n" - + "project \"bgfx-shared-lib\"\nconfiguration {}\n" - + "links { " + Literal(linking.reference) + " }\n" - + "linkoptions { " + string.Join(", ", linking.arguments.Select(Literal)) + " }\n"; + + "project \"bgfx-shared-lib\"\nconfiguration {}\n" + + "links { " + Literal(linking.reference) + " }\n" + + "linkoptions { " + string.Join(", ", linking.arguments.Select(Literal)) + " }\n"; AtomicFile.WriteAllBytes(script, Encoding.UTF8.GetBytes(text)); return script; } @@ -36,11 +45,15 @@ CancellationToken cancellationToken private static string Literal(string value) { if (value.AsSpan().IndexOfAnyInRange('\0', '\x1f') >= 0) + { throw new InvalidDataException("A GENie input path cannot contain control characters."); + } string portable = value.Replace('\\', '/'); string delimiter = "="; while (portable.Contains("]" + delimiter + "]", StringComparison.Ordinal)) + { delimiter += "="; + } return "[" + delimiter + "[" + portable + "]" + delimiter + "]"; } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildConstants.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildConstants.cs index a5dec743e..0c4ed7960 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildConstants.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildConstants.cs @@ -6,22 +6,27 @@ internal static class BgfxBuildConstants /// The output product dir name value used as part of this type's public representation. /// public const string OUTPUT_PRODUCT_DIR_NAME = "bgfx"; + /// /// The output dll name value used as part of this type's public representation. /// public const string OUTPUT_DLL_NAME = "bgfx-shared-lib"; + /// /// The bgfx dir name value used as part of this type's public representation. /// public const string BGFX_DIR_NAME = "bgfx"; + /// /// The bx dir name value used as part of this type's public representation. /// public const string BX_DIR_NAME = "bx"; + /// /// The bimg dir name value used as part of this type's public representation. /// public const string BIMG_DIR_NAME = "bimg"; + /// /// The build dir name value used as part of this type's public representation. /// diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildInvocation.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildInvocation.cs index 50b520c2b..79432a64f 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildInvocation.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildInvocation.cs @@ -32,7 +32,9 @@ IEnumerable arguments ArgumentNullException.ThrowIfNull(arguments); string[] snapshot = arguments.ToArray(); if (snapshot.Any(static value => value is null)) + { throw new ArgumentException("Invocation arguments cannot be null.", nameof(arguments)); + } this.tool = tool; this.arguments = Array.AsReadOnly(snapshot); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs index 792f439d8..e0978ff09 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs @@ -15,23 +15,30 @@ bool includeTools NativeToolchainSelection initial = operation.RequireToolchain(); ArgumentNullException.ThrowIfNull(profile); if (profile.targetId != initial.targetId) + { throw new ArgumentException("The BGFX profile does not match the frozen toolchain target.", nameof(profile)); + } context = operation.WithToolchain(profile.SelectTools(operation, includeTools)); component = includeTools ? BgfxToolsBuild.componentDescriptor : BgfxNativeBuild.componentDescriptor; NativeComponentBuildOptions options = context.RequireComponentOptions(component); if (options.libraryKind != NativeLibraryKind.Shared || options.cmakeArguments.Count != 0) + { throw new NotSupportedException("The standalone graphics recipe requires shared linkage and its explicit generation profile."); + } artifactToken = profile.artifactPathToken; ArgumentException.ThrowIfNullOrWhiteSpace(artifactToken); string[] arguments = profile.generatorArguments?.ToArray() - ?? throw new ArgumentException("The BGFX profile has no generator arguments.", nameof(profile)); + ?? throw new ArgumentException("The BGFX profile has no generator arguments.", nameof(profile)); if (arguments.Length == 0 || arguments.Any(static value => value is null)) + { throw new ArgumentException("The BGFX profile requires assigned generator arguments.", nameof(profile)); - generatorArguments = includeTools ? ["--with-shared-lib", "--with-tools", .. arguments] - : ["--with-shared-lib", .. arguments]; + } + generatorArguments = includeTools + ? ["--with-shared-lib", "--with-tools", .. arguments] + : ["--with-shared-lib", .. arguments]; bindingCmakeArguments = includeTools ? [] : profile.bindingCmakeArguments.ToArray(); invocation = profile.CreateBuildInvocation(context, includeTools) - ?? throw new ArgumentException("The BGFX profile returned no SDK invocation.", nameof(profile)); + ?? throw new ArgumentException("The BGFX profile returned no SDK invocation.", nameof(profile)); NativeToolchainSelection tools = context.RequireToolchain(); compiler = tools.ResolveExecutable(invocation.tool); externalDirectory = Path.Combine(context.engineRoot, "extern"); @@ -40,19 +47,31 @@ bool includeTools string bimg = Path.Combine(externalDirectory, "bimg"); BgfxBuildUtils.ValidateSubmodules(bgfx, bx, bimg); genie = tools.ResolveExecutable("genie"); - string[] declarations = ["artifact=" + artifactToken, + string[] declarations = + [ + "artifact=" + artifactToken, .. generatorArguments.Select(static value => "generate=" + value), .. bindingCmakeArguments.Select(static value => "bridge=" + value), - "compiler=" + compiler, .. invocation.arguments.Select(static value => "compile=" + value)]; + "compiler=" + compiler, + .. invocation.arguments.Select(static value => "compile=" + value) + ]; string implementation = component.GetToolchainRoot(context.engineRoot); - recipe = NativeBuildRecipe.CreateForComponent(context, component, - includeTools ? "bgfx-tools" : "bgfx", tools.targetId, - new[] { bgfx, bx, bimg, genie }.Concat(includeTools ? [] : - [Path.Combine(implementation, "Native", "SharedBindings", "CMakeLists.txt")]), declarations, + recipe = NativeBuildRecipe.CreateForComponent( + context, + component, + includeTools ? "bgfx-tools" : "bgfx", + tools.targetId, + new[] { bgfx, bx, bimg, genie }.Concat( + includeTools + ? [] + : [Path.Combine(implementation, "Native", "SharedBindings", "CMakeLists.txt")] + ), + declarations, new[] { "BgfxBuildConstants.cs", "BgfxBuildInvocation.cs", "BgfxBuildRequest.cs", "BgfxBuildSession.cs", "BgfxBuildUtils.cs", "BgfxNativeBuild.cs", "BgfxNativeBuildProfile.cs", "BgfxToolsBuild.cs" } .Concat(includeTools ? [] : ["BgfxBindingProject.cs"]) - .Select(file => Path.Combine(implementation, file))); + .Select(file => Path.Combine(implementation, file)) + ); } internal NativeBuildContext context { get; } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs index 7c093fb59..d1f0667d6 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs @@ -22,8 +22,13 @@ CancellationToken cancellationToken @scoped, output, token - ) => { - NativeCMakeSource snapshot = await NativeCMakeExecutor.PrepareSourceAsync(scoped, request.component, token).ConfigureAwait(false); + ) => + { + NativeCMakeSource snapshot = await NativeCMakeExecutor.PrepareSourceAsync( + scoped, + request.component, + token + ).ConfigureAwait(false); string source = snapshot.ResolvePath(Path.Combine(request.externalDirectory, "bgfx")); string[] generatorArguments = request.generatorArguments; if (!includeTools) @@ -32,20 +37,46 @@ CancellationToken cancellationToken generatorArguments = ["--file=" + script, .. generatorArguments]; } await ToolchainEnvironment.RunAsync(scoped, request.genie, generatorArguments, source, token).ConfigureAwait(false); - await ToolchainEnvironment.RunAsync(scoped, request.compiler, request.invocation.arguments, source, token).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + scoped, + request.compiler, + request.invocation.arguments, + source, + token + ).ConfigureAwait(false); token.ThrowIfCancellationRequested(); if (includeTools) + { CopyTools(source, output, request.artifactToken, scoped); + } else - BuildArtifactCopier.CopyArtifacts(source, output, scoped.configuration, - new(".build", ["bgfx-shared-lib"], [scoped.RequireToolchain().sharedLibraryExtension], - [request.artifactToken], ToolchainEnvironment.NormalizeOutputName)); - }, cancellationToken, describeOutputs: ( + { + BuildArtifactCopier.CopyArtifacts( + source, + output, + scoped.configuration, + new( + ".build", + ["bgfx-shared-lib"], + [scoped.RequireToolchain().sharedLibraryExtension], + [request.artifactToken], + ToolchainEnvironment.NormalizeOutputName + ) + ); + } + }, + cancellationToken, + describeOutputs: ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories) - .Select(file => new NativeArtifact(Path.GetRelativePath(output, file), file, - includeTools ? NativeArtifactRole.SupportFile : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + .Select(file => new NativeArtifact( + Path.GetRelativePath(output, file), + file, + includeTools ? NativeArtifactRole.SupportFile : NativeArtifactRole.SharedLibrary + )) + .ToArray() + ).ConfigureAwait(false); } private static void CopyTools( @@ -61,17 +92,26 @@ NativeBuildContext context foreach (string name in new[] { "shaderc", "texturec", "geometryc", "geometryv", "texturev" }) { string[] candidates = Directory.EnumerateFiles(build, name + suffix + extension, SearchOption.AllDirectories) - .Where(file => file.Replace('\\', '/').Contains(artifactToken, StringComparison.Ordinal)).ToArray(); + .Where(file => file.Replace('\\', '/').Contains(artifactToken, StringComparison.Ordinal)) + .ToArray(); if (candidates.Length != 1) - throw new FileNotFoundException($"Expected one '{name}' tool for {context.RequireToolchain().targetId}/{configuration}; found {candidates.Length}."); + { + throw new FileNotFoundException( + $"Expected one '{name}' tool for {context.RequireToolchain().targetId}/{configuration}; found {candidates.Length}." + ); + } string destination = Path.Combine(output, name + extension); File.Copy(candidates[0], destination); if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(destination, File.GetUnixFileMode(candidates[0])); + } } string includes = Path.Combine(output, "includes"); Directory.CreateDirectory(includes); foreach (string name in new[] { "bgfx_shader.sh", "bgfx_compute.sh" }) + { File.Copy(Path.Combine(source, "src", name), Path.Combine(includes, name)); + } } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildUtils.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildUtils.cs index 81efe79f3..320a960b4 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildUtils.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildUtils.cs @@ -24,13 +24,15 @@ string bimgDir if (!Directory.Exists(bgfxDir)) { throw new DirectoryNotFoundException( - $"bgfx submodule not found at {bgfxDir}. Please initialize submodules before running this tool."); + $"bgfx submodule not found at {bgfxDir}. Please initialize submodules before running this tool." + ); } if (!Directory.Exists(bxDir) || !Directory.Exists(bimgDir)) { throw new DirectoryNotFoundException( - $"bx/bimg submodules not found next to bgfx. Expected {bxDir} and {bimgDir}."); + $"bx/bimg submodules not found next to bgfx. Expected {bxDir} and {bimgDir}." + ); } } } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs index 5e04e1438..af98e8b0d 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs @@ -19,8 +19,10 @@ public static class BgfxNativeBuild new NativeStaticBuildDefinition( "backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/Native/StaticLibraries.cmake", ["extern/bgfx", "extern/bx", "extern/bimg"], - ["bgfxRelease", "bxRelease", "bimgRelease", "bimg_decodeRelease"]), - bindingDefinition: "backends/Bgfx/native/Inno.Native.Bgfx/Bindings/bindings.props"); + ["bgfxRelease", "bxRelease", "bimgRelease", "bimg_decodeRelease"] + ), + bindingDefinition: "backends/Bgfx/native/Inno.Native.Bgfx/Bindings/bindings.props" + ); /// /// Builds and installs graphics artifacts using explicit platform-owned SDK configuration. diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs index 5e64d75fc..7d4c82db8 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs @@ -15,7 +15,8 @@ public static class BgfxToolsBuild public static NativeComponentDescriptor componentDescriptor { get; } = new( "bgfx-tools", BgfxNativeBuild.componentDescriptor.nativeProject, - BgfxNativeBuild.componentDescriptor.toolchainProject); + BgfxNativeBuild.componentDescriptor.toolchainProject + ); /// /// Builds and installs graphics artifacts using explicit platform-owned SDK configuration. diff --git a/backends/Bgfx/native/Inno.Native.Bgfx/bgfx.cs b/backends/Bgfx/native/Inno.Native.Bgfx/bgfx.cs index 0ea70134f..28612e2cb 100644 --- a/backends/Bgfx/native/Inno.Native.Bgfx/bgfx.cs +++ b/backends/Bgfx/native/Inno.Native.Bgfx/bgfx.cs @@ -23,4 +23,4 @@ static bgfx() Load(NativeDllLoader.FindNativeLibrary(LibName)); #endif } -} \ No newline at end of file +} diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCapabilityMapper.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCapabilityMapper.cs index 67ce627a1..0bf15fc9d 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCapabilityMapper.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCapabilityMapper.cs @@ -127,24 +127,24 @@ public static unsafe GraphicsCapabilities FromNative(bgfx.Caps* caps) bgfx.TextureFormat nativeFormat = ToNativeFormat(format); bgfx.CapsFormatFlags formatCaps = (bgfx.CapsFormatFlags)caps->formats[(int)nativeFormat]; bgfx.CapsFormatFlags sampledFlag = format == RenderTextureFormat.RGBA8Srgb - ? bgfx.CapsFormatFlags.Texture2dSrgb - : bgfx.CapsFormatFlags.Texture2d; + ? bgfx.CapsFormatFlags.Texture2dSrgb + : bgfx.CapsFormatFlags.Texture2d; if ((formatCaps & sampledFlag) != 0) { sampled.Add(format); } bgfx.CapsFormatFlags sampled3DFlag = format == RenderTextureFormat.RGBA8Srgb - ? bgfx.CapsFormatFlags.Texture3dSrgb - : bgfx.CapsFormatFlags.Texture3d; + ? bgfx.CapsFormatFlags.Texture3dSrgb + : bgfx.CapsFormatFlags.Texture3d; if ((formatCaps & sampled3DFlag) != 0) { sampled3D.Add(format); } bgfx.CapsFormatFlags sampledCubeFlag = format == RenderTextureFormat.RGBA8Srgb - ? bgfx.CapsFormatFlags.TextureCubeSrgb - : bgfx.CapsFormatFlags.TextureCube; + ? bgfx.CapsFormatFlags.TextureCubeSrgb + : bgfx.CapsFormatFlags.TextureCube; if ((formatCaps & sampledCubeFlag) != 0) { sampledCube.Add(format); @@ -178,7 +178,8 @@ public static unsafe GraphicsCapabilities FromNative(bgfx.Caps* caps) checked((int)caps->limits.maxViews), checked((int)caps->limits.maxFBAttachments), checked((int)caps->limits.maxTextureSize), - checked((int)caps->limits.maxComputeBindings)), + checked((int)caps->limits.maxComputeBindings) + ), sampled, renderTargets, storageRead, @@ -187,7 +188,8 @@ public static unsafe GraphicsCapabilities FromNative(bgfx.Caps* caps) caps->homogeneousDepth != 0, sampled3D, sampledCube, - multisampleRenderTargets); + multisampleRenderTargets + ); } /// @@ -202,21 +204,37 @@ public static unsafe GraphicsCapabilities FromNative(bgfx.Caps* caps) public static bgfx.RendererType ToNativeRenderer(GraphicsApi backend) { if (backend == GraphicsApi.Noop) + { return bgfx.RendererType.Noop; + } if (backend == GraphicsApi.Direct3D11) + { return bgfx.RendererType.Direct3d11; + } if (backend == GraphicsApi.Direct3D12) + { return bgfx.RendererType.Direct3d12; + } if (backend == GraphicsApi.Metal) + { return bgfx.RendererType.Metal; + } if (backend == GraphicsApi.Vulkan) + { return bgfx.RendererType.Vulkan; + } if (backend == GraphicsApi.OpenGL) + { return bgfx.RendererType.OpenGL; + } if (backend == GraphicsApi.OpenGLES) + { return bgfx.RendererType.OpenGLES; + } if (backend == GraphicsApi.WebGPU) + { return bgfx.RendererType.WebGPU; + } throw new NotSupportedException($"BGFX does not support graphics backend '{backend}'."); } @@ -231,17 +249,17 @@ public static bgfx.RendererType ToNativeRenderer(GraphicsApi backend) /// public static GraphicsApi ToGraphicsApi(bgfx.RendererType backend) => backend switch - { - bgfx.RendererType.Noop => GraphicsApi.Noop, - bgfx.RendererType.Direct3d11 => GraphicsApi.Direct3D11, - bgfx.RendererType.Direct3d12 => GraphicsApi.Direct3D12, - bgfx.RendererType.Metal => GraphicsApi.Metal, - bgfx.RendererType.Vulkan => GraphicsApi.Vulkan, - bgfx.RendererType.OpenGL => GraphicsApi.OpenGL, - bgfx.RendererType.OpenGLES => GraphicsApi.OpenGLES, - bgfx.RendererType.WebGPU => GraphicsApi.WebGPU, - _ => throw new NotSupportedException($"BGFX renderer '{backend}' has no public Rendering.Core mapping.") - }; + { + bgfx.RendererType.Noop => GraphicsApi.Noop, + bgfx.RendererType.Direct3d11 => GraphicsApi.Direct3D11, + bgfx.RendererType.Direct3d12 => GraphicsApi.Direct3D12, + bgfx.RendererType.Metal => GraphicsApi.Metal, + bgfx.RendererType.Vulkan => GraphicsApi.Vulkan, + bgfx.RendererType.OpenGL => GraphicsApi.OpenGL, + bgfx.RendererType.OpenGLES => GraphicsApi.OpenGLES, + bgfx.RendererType.WebGPU => GraphicsApi.WebGPU, + _ => throw new NotSupportedException($"BGFX renderer '{backend}' has no public Rendering.Core mapping.") + }; /// /// Converts this value to its native format representation. @@ -254,17 +272,17 @@ public static GraphicsApi ToGraphicsApi(bgfx.RendererType backend) /// public static bgfx.TextureFormat ToNativeFormat(RenderTextureFormat format) => format switch - { - RenderTextureFormat.R8 => bgfx.TextureFormat.R8, - RenderTextureFormat.RG8 => bgfx.TextureFormat.RG8, - RenderTextureFormat.RGBA8 => bgfx.TextureFormat.RGBA8, - RenderTextureFormat.RGBA8Srgb => bgfx.TextureFormat.RGBA8, - RenderTextureFormat.RGB10A2 => bgfx.TextureFormat.RGB10A2, - RenderTextureFormat.RG11B10Float => bgfx.TextureFormat.RG11B10F, - RenderTextureFormat.RGBA16Float => bgfx.TextureFormat.RGBA16F, - RenderTextureFormat.R32Float => bgfx.TextureFormat.R32f, - RenderTextureFormat.Depth24Stencil8 => bgfx.TextureFormat.D24s8, - RenderTextureFormat.Depth32Float => bgfx.TextureFormat.D32f, - _ => throw new ArgumentOutOfRangeException(nameof(format)) - }; + { + RenderTextureFormat.R8 => bgfx.TextureFormat.R8, + RenderTextureFormat.RG8 => bgfx.TextureFormat.RG8, + RenderTextureFormat.RGBA8 => bgfx.TextureFormat.RGBA8, + RenderTextureFormat.RGBA8Srgb => bgfx.TextureFormat.RGBA8, + RenderTextureFormat.RGB10A2 => bgfx.TextureFormat.RGB10A2, + RenderTextureFormat.RG11B10Float => bgfx.TextureFormat.RG11B10F, + RenderTextureFormat.RGBA16Float => bgfx.TextureFormat.RGBA16F, + RenderTextureFormat.R32Float => bgfx.TextureFormat.R32f, + RenderTextureFormat.Depth24Stencil8 => bgfx.TextureFormat.D24s8, + RenderTextureFormat.Depth32Float => bgfx.TextureFormat.D32f, + _ => throw new ArgumentOutOfRangeException(nameof(format)) + }; } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Bindings.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Bindings.cs index ee42f1596..55297ef57 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Bindings.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Bindings.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Binds the graphics pipeline used by subsequent draw commands. /// @@ -61,8 +60,7 @@ public override void BindTexture( RenderBindingId binding, RenderTextureHandle texture, RenderSamplerState sampler - ) - => BindTexture(binding, m_device.ResolveTexture(texture), sampler); + ) => BindTexture(binding, m_device.ResolveTexture(texture), sampler); /// /// Binds a texture resource to the requested shader binding. @@ -80,8 +78,7 @@ public override void BindTexture( RenderBindingId binding, PersistentTextureHandle texture, RenderSamplerState sampler - ) - => BindTexture(binding, m_device.ResolveTexture(texture), sampler); + ) => BindTexture(binding, m_device.ResolveTexture(texture), sampler); /// /// Binds a writable texture resource to the requested shader binding. @@ -99,12 +96,12 @@ public override void BindStorageTexture( RenderBindingId binding, RenderTextureHandle texture, int mipLevel = 0 - ) - => BindStorageTexture( - binding, - m_device.ResolveTexture(texture), - m_device.ResolveTextureDescriptor(texture), - mipLevel); + ) => BindStorageTexture( + binding, + m_device.ResolveTexture(texture), + m_device.ResolveTextureDescriptor(texture), + mipLevel + ); /// /// Binds a writable texture resource to the requested shader binding. @@ -122,12 +119,12 @@ public override void BindStorageTexture( RenderBindingId binding, PersistentTextureHandle texture, int mipLevel = 0 - ) - => BindStorageTexture( - binding, - m_device.ResolveTexture(texture), - m_device.ResolveTextureDescriptor(texture), - mipLevel); + ) => BindStorageTexture( + binding, + m_device.ResolveTexture(texture), + m_device.ResolveTextureDescriptor(texture), + mipLevel + ); /// /// Binds a buffer resource to the requested shader binding. @@ -141,8 +138,7 @@ public override void BindStorageTexture( public override void BindBuffer( RenderBindingId binding, RenderBufferHandle buffer - ) - => BindBuffer(binding, m_device.ResolveBuffer(buffer)); + ) => BindBuffer(binding, m_device.ResolveBuffer(buffer)); /// /// Binds a buffer resource to the requested shader binding. @@ -156,8 +152,7 @@ RenderBufferHandle buffer public override void BindBuffer( RenderBindingId binding, PersistentBufferHandle buffer - ) - => BindBuffer(binding, m_device.ResolveBuffer(buffer)); + ) => BindBuffer(binding, m_device.ResolveBuffer(buffer)); /// /// Updates the uniform state and applies the resulting invariants. @@ -185,7 +180,8 @@ ReadOnlySpan value { throw new ArgumentException( $"Uniform '{binding.value}' requires exactly {expectedSize} bytes.", - nameof(value)); + nameof(value) + ); } fixed (byte* data = value) @@ -194,7 +190,8 @@ ReadOnlySpan value m_encoder, resource.uniform, data, - checked((ushort)resource.descriptor.count)); + checked((ushort)resource.descriptor.count) + ); } } @@ -209,7 +206,8 @@ RenderSamplerState sampler checked((byte)resource.descriptor.slot), resource.uniform, texture, - SamplerFlags(sampler)); + SamplerFlags(sampler) + ); } private void BindStorageTexture( @@ -221,22 +219,25 @@ int mipLevel BgfxShaderBindingResource resource = ResolveBinding(binding, RenderShaderBindingKind.StorageTexture); if (!m_device.capabilities.Supports(GraphicsCapability.StorageTexture)) { - throw new NotSupportedException( - "The active graphics backend does not support shader storage textures."); + throw new NotSupportedException("The active graphics backend does not support shader storage textures."); } if ((descriptor.usage & RenderTextureUsage.Storage) == 0) { throw new ArgumentException( $"Texture bound to '{binding.value}' was not created for storage access.", - nameof(descriptor)); + nameof(descriptor) + ); } ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); if (mipLevel >= descriptor.mipCount) + { throw new ArgumentOutOfRangeException(nameof(mipLevel)); + } if (!m_device.capabilities.SupportsStorage(descriptor.format, resource.descriptor.storageAccess)) { throw new NotSupportedException( - $"Texture format '{descriptor.format}' does not support {resource.descriptor.storageAccess} storage access."); + $"Texture format '{descriptor.format}' does not support {resource.descriptor.storageAccess} storage access." + ); } BgfxNativeCalls.EncoderSetImage( @@ -245,7 +246,8 @@ int mipLevel texture, checked((byte)mipLevel), StorageAccess(resource.descriptor.storageAccess), - BgfxCapabilityMapper.ToNativeFormat(descriptor.format)); + BgfxCapabilityMapper.ToNativeFormat(descriptor.format) + ); } private void BindBuffer( @@ -257,7 +259,8 @@ BgfxBufferResource buffer { throw new ArgumentException( $"Buffer bound to '{binding.value}' was not created for storage access.", - nameof(buffer)); + nameof(buffer) + ); } byte slot = checked((byte)resource.descriptor.slot); @@ -269,35 +272,40 @@ BgfxBufferResource buffer m_encoder, slot, new bgfx.VertexBufferHandle { idx = buffer.nativeIndex }, - access); + access + ); break; case BgfxBufferKind.Index: BgfxNativeCalls.EncoderSetComputeIndexBuffer( m_encoder, slot, new bgfx.IndexBufferHandle { idx = buffer.nativeIndex }, - access); + access + ); break; case BgfxBufferKind.DynamicVertex: BgfxNativeCalls.EncoderSetComputeDynamicVertexBuffer( m_encoder, slot, new bgfx.DynamicVertexBufferHandle { idx = buffer.nativeIndex }, - access); + access + ); break; case BgfxBufferKind.DynamicIndex: BgfxNativeCalls.EncoderSetComputeDynamicIndexBuffer( m_encoder, slot, new bgfx.DynamicIndexBufferHandle { idx = buffer.nativeIndex }, - access); + access + ); break; case BgfxBufferKind.Indirect: BgfxNativeCalls.EncoderSetComputeIndirectBuffer( m_encoder, slot, new bgfx.IndirectBufferHandle { idx = buffer.nativeIndex }, - access); + access + ); break; default: throw new ArgumentOutOfRangeException(nameof(buffer)); @@ -314,22 +322,23 @@ RenderShaderBindingKind requiredKind } BgfxPipelineResource pipeline = m_pipeline - ?? throw new InvalidOperationException("A pipeline must be bound before shader resources."); + ?? throw new InvalidOperationException("A pipeline must be bound before shader resources."); if (!pipeline.bindings.TryGetValue(binding.value, out BgfxShaderBindingResource? resource)) { throw new ArgumentException( $"Pipeline does not declare shader binding '{binding.value}'.", - nameof(binding)); + nameof(binding) + ); } if (resource.descriptor.kind != requiredKind) { throw new ArgumentException( $"Shader binding '{binding.value}' is {resource.descriptor.kind}, not {requiredKind}.", - nameof(binding)); + nameof(binding) + ); } return resource; } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Compute.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Compute.cs index b6d059149..8abcf5400 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Compute.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Compute.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Dispatches compute work using the supplied thread-group dimensions. /// @@ -36,7 +35,8 @@ public override void Dispatch( checked((uint)groupCountX), checked((uint)groupCountY), checked((uint)groupCountZ), - checked((byte)bgfx.DiscardFlags.All)); + checked((byte)bgfx.DiscardFlags.All) + ); m_device.RecordDispatch(); } @@ -56,8 +56,7 @@ public override void DispatchIndirect( RenderBufferHandle buffer, int firstCommand = 0, int commandCount = 1 - ) - => DispatchIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); + ) => DispatchIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); /// /// Dispatches compute work using dimensions read from the supplied indirect buffer. @@ -75,8 +74,7 @@ public override void DispatchIndirect( PersistentBufferHandle buffer, int firstCommand = 0, int commandCount = 1 - ) - => DispatchIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); + ) => DispatchIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); private void DispatchIndirect( BgfxBufferResource buffer, @@ -92,8 +90,8 @@ int commandCount new bgfx.IndirectBufferHandle { idx = buffer.nativeIndex }, checked((uint)firstCommand), checked((uint)commandCount), - checked((byte)bgfx.DiscardFlags.All)); + checked((byte)bgfx.DiscardFlags.All) + ); m_device.RecordDispatch(commandCount); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Draw.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Draw.cs index 216e730ac..a09447367 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Draw.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Draw.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Renders the value presentation for the current editor frame. /// @@ -26,7 +25,8 @@ public override void Draw( if (m_vertexBuffer is null) { throw new InvalidOperationException( - "A direct non-procedural draw requires a bound vertex buffer. Use DrawProcedural explicitly otherwise."); + "A direct non-procedural draw requires a bound vertex buffer. Use DrawProcedural explicitly otherwise." + ); } SetVertexBuffer(pipeline, m_vertexBuffer, m_firstVertex, vertexCount); @@ -49,8 +49,7 @@ public override void DrawProcedural( BgfxPipelineResource pipeline = RequireGraphicsPipeline(); if (!m_device.capabilities.Supports(GraphicsCapability.ProceduralDraw)) { - throw new NotSupportedException( - "The active graphics backend does not support procedural vertex-ID draws."); + throw new NotSupportedException("The active graphics backend does not support procedural vertex-ID draws."); } ValidateDrawCounts(vertexCount, instanceCount); bgfx.Raw.encoder_set_vertex_count(m_encoder, checked((uint)vertexCount)); @@ -86,7 +85,8 @@ public override void DrawIndexed( pipeline, m_vertexBuffer, m_firstVertex, - m_vertexBuffer.descriptor.elementCount - m_firstVertex); + m_vertexBuffer.descriptor.elementCount - m_firstVertex + ); SetIndexBuffer(m_indexBuffer, m_firstIndex, indexCount); Submit(pipeline, instanceCount); } @@ -107,8 +107,7 @@ public override void DrawIndirect( RenderBufferHandle buffer, int firstCommand = 0, int commandCount = 1 - ) - => DrawIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); + ) => DrawIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); /// /// Renders the indirect presentation for the current editor frame. @@ -126,8 +125,7 @@ public override void DrawIndirect( PersistentBufferHandle buffer, int firstCommand = 0, int commandCount = 1 - ) - => DrawIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); + ) => DrawIndirect(m_device.ResolveBuffer(buffer), firstCommand, commandCount); private void DrawIndirect( BgfxBufferResource buffer, @@ -142,19 +140,18 @@ int commandCount pipeline, m_vertexBuffer, m_firstVertex, - m_vertexBuffer.descriptor.elementCount - m_firstVertex); + m_vertexBuffer.descriptor.elementCount - m_firstVertex + ); } else if (!m_device.capabilities.Supports(GraphicsCapability.ProceduralDraw)) { throw new NotSupportedException( - "An indirect draw without a vertex buffer requires procedural draw capability."); + "An indirect draw without a vertex buffer requires procedural draw capability." + ); } if (m_indexBuffer is not null) { - SetIndexBuffer( - m_indexBuffer, - m_firstIndex, - m_indexBuffer.descriptor.elementCount - m_firstIndex); + SetIndexBuffer(m_indexBuffer, m_firstIndex, m_indexBuffer.descriptor.elementCount - m_firstIndex); } SetDrawState(pipeline); BgfxNativeCalls.EncoderSubmitIndirect( @@ -165,7 +162,8 @@ int commandCount checked((uint)firstCommand), checked((uint)commandCount), 0, - checked((byte)bgfx.DiscardFlags.All)); + checked((byte)bgfx.DiscardFlags.All) + ); m_device.RecordDraw(commandCount); m_instanceDataBound = false; } @@ -175,12 +173,15 @@ private void Submit( int instanceCount ) { if (instanceCount > 1 && !m_device.capabilities.Supports(GraphicsCapability.Instancing)) + { throw new NotSupportedException("The active graphics backend does not support instancing."); + } if (m_instanceDataBound && instanceCount != 1) { throw new ArgumentException( "A draw with bound instance data must use the bound instance count.", - nameof(instanceCount)); + nameof(instanceCount) + ); } if (!m_instanceDataBound && instanceCount > 1) { @@ -188,12 +189,7 @@ int instanceCount } SetDrawState(pipeline); - BgfxNativeCalls.EncoderSubmit( - m_encoder, - m_viewId, - pipeline.program, - 0, - checked((byte)bgfx.DiscardFlags.All)); + BgfxNativeCalls.EncoderSubmit(m_encoder, m_viewId, pipeline.program, 0, checked((byte)bgfx.DiscardFlags.All)); m_device.RecordDraw(); m_instanceDataBound = false; } @@ -210,7 +206,7 @@ private void SetDrawState(BgfxPipelineResource pipeline) bgfx.Raw.encoder_set_stencil( m_encoder, StencilFlags(m_stencilState, m_stencilState.front), - StencilFlags(m_stencilState, m_stencilState.back)); + StencilFlags(m_stencilState, m_stencilState.back) + ); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs index b22197715..cbf95a3ba 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Binds a vertex buffer and its first vertex for subsequent draws. /// @@ -20,8 +19,7 @@ internal sealed unsafe partial class BgfxCommandEncoder public override void BindVertexBuffer( RenderBufferHandle buffer, int firstVertex = 0 - ) - => BindVertexBuffer(m_device.ResolveBuffer(buffer), firstVertex); + ) => BindVertexBuffer(m_device.ResolveBuffer(buffer), firstVertex); /// /// Binds a vertex buffer and its first vertex for subsequent draws. @@ -35,8 +33,7 @@ public override void BindVertexBuffer( public override void BindVertexBuffer( PersistentBufferHandle buffer, int firstVertex = 0 - ) - => BindVertexBuffer(m_device.ResolveBuffer(buffer), firstVertex); + ) => BindVertexBuffer(m_device.ResolveBuffer(buffer), firstVertex); /// /// Binds an index buffer and its first index for subsequent indexed draws. @@ -50,8 +47,7 @@ public override void BindVertexBuffer( public override void BindIndexBuffer( RenderBufferHandle buffer, int firstIndex = 0 - ) - => BindIndexBuffer(m_device.ResolveBuffer(buffer), firstIndex); + ) => BindIndexBuffer(m_device.ResolveBuffer(buffer), firstIndex); /// /// Binds an index buffer and its first index for subsequent indexed draws. @@ -65,8 +61,7 @@ public override void BindIndexBuffer( public override void BindIndexBuffer( PersistentBufferHandle buffer, int firstIndex = 0 - ) - => BindIndexBuffer(m_device.ResolveBuffer(buffer), firstIndex); + ) => BindIndexBuffer(m_device.ResolveBuffer(buffer), firstIndex); /// /// Binds per-instance data for subsequent instanced draws. @@ -84,8 +79,7 @@ public override void BindInstanceBuffer( RenderBufferHandle buffer, int firstInstance, int instanceCount - ) - => BindInstanceBuffer(m_device.ResolveBuffer(buffer), firstInstance, instanceCount); + ) => BindInstanceBuffer(m_device.ResolveBuffer(buffer), firstInstance, instanceCount); /// /// Binds per-instance data for subsequent instanced draws. @@ -103,8 +97,7 @@ public override void BindInstanceBuffer( PersistentBufferHandle buffer, int firstInstance, int instanceCount - ) - => BindInstanceBuffer(m_device.ResolveBuffer(buffer), firstInstance, instanceCount); + ) => BindInstanceBuffer(m_device.ResolveBuffer(buffer), firstInstance, instanceCount); private void BindVertexBuffer( BgfxBufferResource buffer, @@ -150,7 +143,9 @@ private void BindInstanceBuffer( int instanceCount ) { if (!m_device.capabilities.Supports(GraphicsCapability.Instancing)) + { throw new NotSupportedException("The active graphics backend does not support instancing."); + } ArgumentOutOfRangeException.ThrowIfNegative(firstInstance); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(instanceCount); ValidateRange(firstInstance, instanceCount, buffer.descriptor.elementCount, nameof(instanceCount)); @@ -161,14 +156,16 @@ int instanceCount m_encoder, new bgfx.VertexBufferHandle { idx = buffer.nativeIndex }, checked((uint)firstInstance), - checked((uint)instanceCount)); + checked((uint)instanceCount) + ); break; case BgfxBufferKind.DynamicVertex: BgfxNativeCalls.EncoderSetInstanceDataFromDynamicVertexBuffer( m_encoder, new bgfx.DynamicVertexBufferHandle { idx = buffer.nativeIndex }, checked((uint)firstInstance), - checked((uint)instanceCount)); + checked((uint)instanceCount) + ); break; default: throw new ArgumentException("Instance data requires a vertex-compatible buffer.", nameof(buffer)); @@ -186,7 +183,8 @@ int vertexCount if (pipeline.vertexLayout is null || !pipeline.vertexLayoutHandle.Valid) { throw new InvalidOperationException( - "A graphics pipeline with procedural vertices cannot bind a vertex buffer."); + "A graphics pipeline with procedural vertices cannot bind a vertex buffer." + ); } if (buffer.vertexLayout is not null && !buffer.vertexLayout.Equals(pipeline.vertexLayout)) @@ -207,7 +205,8 @@ int vertexCount handle, first, count, - pipeline.vertexLayoutHandle); + pipeline.vertexLayoutHandle + ); } else { @@ -228,7 +227,8 @@ int vertexCount handle, first, count, - pipeline.vertexLayoutHandle); + pipeline.vertexLayoutHandle + ); } else { @@ -255,7 +255,8 @@ int indexCount m_encoder, new bgfx.IndexBufferHandle { idx = buffer.nativeIndex }, first, - count); + count + ); return; } @@ -265,11 +266,11 @@ int indexCount m_encoder, new bgfx.DynamicIndexBufferHandle { idx = buffer.nativeIndex }, first, - count); + count + ); return; } throw new InvalidOperationException("The bound resource is not an index buffer."); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.State.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.State.cs index 416630d57..5fd01ccda 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.State.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.State.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Updates the transform state and applies the resulting invariants. /// @@ -38,10 +37,11 @@ public override void SetRasterState(RenderRasterState state) ArgumentNullException.ThrowIfNull(state); _ = RequireGraphicsPipeline(); if (state.blend.alphaToCoverage - && !m_device.capabilities.Supports(GraphicsCapability.AlphaToCoverage)) - { + && !m_device.capabilities.Supports(GraphicsCapability.AlphaToCoverage) + ) { throw new NotSupportedException( - "The active graphics backend does not support alpha-to-coverage rasterization."); + "The active graphics backend does not support alpha-to-coverage rasterization." + ); } m_rasterState = state; } @@ -58,8 +58,7 @@ public override void SetStencil(RenderStencilState state) _ = RequireGraphicsPipeline(); if (state.enabled && state.writeMask != byte.MaxValue) { - throw new NotSupportedException( - "BGFX does not expose an independent dynamic stencil write mask."); + throw new NotSupportedException("BGFX does not expose an independent dynamic stencil write mask."); } m_stencilState = state; } @@ -94,7 +93,8 @@ int height checked((ushort)x), checked((ushort)y), checked((ushort)width), - checked((ushort)height)); + checked((ushort)height) + ); } /// @@ -127,7 +127,8 @@ int height checked((ushort)x), checked((ushort)y), checked((ushort)width), - checked((ushort)height)); + checked((ushort)height) + ); } private static ulong RasterState(RenderRasterState state) @@ -192,7 +193,9 @@ private static ulong RasterState(RenderRasterState state) } if (state.blend.alphaToCoverage) + { flags |= bgfx.StateFlags.BlendAlphaToCoverage; + } if (state.multisampling) { @@ -214,12 +217,12 @@ private static ulong RasterState(RenderRasterState state) private static bgfx.Access StorageAccess(RenderStorageAccess access) => access switch - { - RenderStorageAccess.Read => bgfx.Access.Read, - RenderStorageAccess.Write => bgfx.Access.Write, - RenderStorageAccess.ReadWrite => bgfx.Access.ReadWrite, - _ => throw new ArgumentOutOfRangeException(nameof(access)) - }; + { + RenderStorageAccess.Read => bgfx.Access.Read, + RenderStorageAccess.Write => bgfx.Access.Write, + RenderStorageAccess.ReadWrite => bgfx.Access.ReadWrite, + _ => throw new ArgumentOutOfRangeException(nameof(access)) + }; private static uint SamplerFlags(RenderSamplerState state) { @@ -228,7 +231,7 @@ private static uint SamplerFlags(RenderSamplerState state) RenderSamplerFilter.Point => bgfx.SamplerFlags.Point, RenderSamplerFilter.Linear => bgfx.SamplerFlags.None, RenderSamplerFilter.Anisotropic => bgfx.SamplerFlags.MinAnisotropic - | bgfx.SamplerFlags.MagAnisotropic, + | bgfx.SamplerFlags.MagAnisotropic, _ => throw new ArgumentOutOfRangeException(nameof(state)) }; flags |= AddressFlags(state.addressU, 'U'); @@ -240,21 +243,20 @@ private static uint SamplerFlags(RenderSamplerState state) private static bgfx.SamplerFlags AddressFlags( RenderSamplerAddressMode mode, char axis - ) - => (axis, mode) switch - { - (_, RenderSamplerAddressMode.Repeat) => bgfx.SamplerFlags.None, - ('U', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.UMirror, - ('U', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.UClamp, - ('U', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.UBorder, - ('V', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.VMirror, - ('V', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.VClamp, - ('V', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.VBorder, - ('W', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.WMirror, - ('W', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.WClamp, - ('W', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.WBorder, - _ => throw new ArgumentOutOfRangeException(nameof(mode)) - }; + ) => (axis, mode) switch + { + (_, RenderSamplerAddressMode.Repeat) => bgfx.SamplerFlags.None, + ('U', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.UMirror, + ('U', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.UClamp, + ('U', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.UBorder, + ('V', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.VMirror, + ('V', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.VClamp, + ('V', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.VBorder, + ('W', RenderSamplerAddressMode.Mirror) => bgfx.SamplerFlags.WMirror, + ('W', RenderSamplerAddressMode.Clamp) => bgfx.SamplerFlags.WClamp, + ('W', RenderSamplerAddressMode.Border) => bgfx.SamplerFlags.WBorder, + _ => throw new ArgumentOutOfRangeException(nameof(mode)) + }; private static uint StencilFlags( RenderStencilState state, @@ -314,8 +316,8 @@ private static ulong BlendFunction(RenderBlendState state) ulong alphaSource = (ulong)BlendFactor(state.alphaSource); ulong alphaDestination = (ulong)BlendFactor(state.alphaDestination); return colorSource - | (colorDestination << 4) - | ((alphaSource | (alphaDestination << 4)) << 8); + | (colorDestination << 4) + | ((alphaSource | (alphaDestination << 4)) << 8); } private static ulong BlendEquation(RenderBlendState state) @@ -327,32 +329,31 @@ private static ulong BlendEquation(RenderBlendState state) private static bgfx.StateFlags BlendFactor(RenderBlendFactor factor) => factor switch - { - RenderBlendFactor.Zero => bgfx.StateFlags.BlendZero, - RenderBlendFactor.One => bgfx.StateFlags.BlendOne, - RenderBlendFactor.SourceColor => bgfx.StateFlags.BlendSrcColor, - RenderBlendFactor.InverseSourceColor => bgfx.StateFlags.BlendInvSrcColor, - RenderBlendFactor.SourceAlpha => bgfx.StateFlags.BlendSrcAlpha, - RenderBlendFactor.InverseSourceAlpha => bgfx.StateFlags.BlendInvSrcAlpha, - RenderBlendFactor.DestinationAlpha => bgfx.StateFlags.BlendDstAlpha, - RenderBlendFactor.InverseDestinationAlpha => bgfx.StateFlags.BlendInvDstAlpha, - RenderBlendFactor.DestinationColor => bgfx.StateFlags.BlendDstColor, - RenderBlendFactor.InverseDestinationColor => bgfx.StateFlags.BlendInvDstColor, - RenderBlendFactor.SourceAlphaSaturate => bgfx.StateFlags.BlendSrcAlphaSat, - RenderBlendFactor.Constant => bgfx.StateFlags.BlendFactor, - RenderBlendFactor.InverseConstant => bgfx.StateFlags.BlendInvFactor, - _ => throw new ArgumentOutOfRangeException(nameof(factor)) - }; + { + RenderBlendFactor.Zero => bgfx.StateFlags.BlendZero, + RenderBlendFactor.One => bgfx.StateFlags.BlendOne, + RenderBlendFactor.SourceColor => bgfx.StateFlags.BlendSrcColor, + RenderBlendFactor.InverseSourceColor => bgfx.StateFlags.BlendInvSrcColor, + RenderBlendFactor.SourceAlpha => bgfx.StateFlags.BlendSrcAlpha, + RenderBlendFactor.InverseSourceAlpha => bgfx.StateFlags.BlendInvSrcAlpha, + RenderBlendFactor.DestinationAlpha => bgfx.StateFlags.BlendDstAlpha, + RenderBlendFactor.InverseDestinationAlpha => bgfx.StateFlags.BlendInvDstAlpha, + RenderBlendFactor.DestinationColor => bgfx.StateFlags.BlendDstColor, + RenderBlendFactor.InverseDestinationColor => bgfx.StateFlags.BlendInvDstColor, + RenderBlendFactor.SourceAlphaSaturate => bgfx.StateFlags.BlendSrcAlphaSat, + RenderBlendFactor.Constant => bgfx.StateFlags.BlendFactor, + RenderBlendFactor.InverseConstant => bgfx.StateFlags.BlendInvFactor, + _ => throw new ArgumentOutOfRangeException(nameof(factor)) + }; private static bgfx.StateFlags BlendEquation(RenderBlendEquation equation) => equation switch - { - RenderBlendEquation.Add => bgfx.StateFlags.BlendEquationAdd, - RenderBlendEquation.Subtract => bgfx.StateFlags.BlendEquationSub, - RenderBlendEquation.ReverseSubtract => bgfx.StateFlags.BlendEquationRevsub, - RenderBlendEquation.Minimum => bgfx.StateFlags.BlendEquationMin, - RenderBlendEquation.Maximum => bgfx.StateFlags.BlendEquationMax, - _ => throw new ArgumentOutOfRangeException(nameof(equation)) - }; - + { + RenderBlendEquation.Add => bgfx.StateFlags.BlendEquationAdd, + RenderBlendEquation.Subtract => bgfx.StateFlags.BlendEquationSub, + RenderBlendEquation.ReverseSubtract => bgfx.StateFlags.BlendEquationRevsub, + RenderBlendEquation.Minimum => bgfx.StateFlags.BlendEquationMin, + RenderBlendEquation.Maximum => bgfx.StateFlags.BlendEquationMax, + _ => throw new ArgumentOutOfRangeException(nameof(equation)) + }; } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Transfers.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Transfers.cs index b5740f697..aa77f6ac4 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Transfers.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Transfers.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - /// /// Copies texture without transferring ownership of the source state. /// @@ -49,7 +48,8 @@ RenderTextureHandle destination checked((ushort)layer), width, height, - 1); + 1 + ); } } } @@ -83,8 +83,8 @@ RenderTextureRegion destinationRegion ValidateTextureCopyFormats(sourceDescriptor, destinationDescriptor); if (sourceRegion.width != destinationRegion.width || sourceRegion.height != destinationRegion.height - || sourceRegion.depth != destinationRegion.depth) - { + || sourceRegion.depth != destinationRegion.depth + ) { throw new ArgumentException("BGFX blit source and destination extents must match."); } BgfxNativeCalls.EncoderBlit( @@ -102,7 +102,8 @@ RenderTextureRegion destinationRegion checked((ushort)sourceRegion.layer), checked((ushort)sourceRegion.width), checked((ushort)sourceRegion.height), - checked((ushort)sourceRegion.depth)); + checked((ushort)sourceRegion.depth) + ); } /// @@ -121,7 +122,7 @@ RenderBufferHandle destination _ = source; _ = destination; throw new NotSupportedException( - "BGFX has no general buffer-copy command; use a Plugin compute pass on supported devices."); + "BGFX has no general buffer-copy command; use a Plugin compute pass on supported devices." + ); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Validation.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Validation.cs index 18c541572..8b23fe701 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Validation.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Validation.cs @@ -7,7 +7,6 @@ namespace Inno.Adapter.Rendering.Bgfx; internal sealed unsafe partial class BgfxCommandEncoder { - private void RequireTextureBlit() { if (!m_device.capabilities.Supports(GraphicsCapability.TextureBlit)) @@ -26,10 +25,11 @@ RenderTextureDescriptor destination || source.depth != destination.depth || source.dimension != destination.dimension || source.mipCount != destination.mipCount - || source.arrayLayers != destination.arrayLayers) - { + || source.arrayLayers != destination.arrayLayers + ) { throw new ArgumentException( - "A complete texture copy requires equal dimensions, mip counts, and array layers."); + "A complete texture copy requires equal dimensions, mip counts, and array layers." + ); } } @@ -48,10 +48,9 @@ RenderTextureDescriptor destination } if ((source.usage & RenderTextureUsage.CopySource) == 0 - || (destination.usage & RenderTextureUsage.CopyDestination) == 0) - { - throw new ArgumentException( - "Texture copies require CopySource and CopyDestination usage respectively."); + || (destination.usage & RenderTextureUsage.CopyDestination) == 0 + ) { + throw new ArgumentException("Texture copies require CopySource and CopyDestination usage respectively."); } } @@ -69,8 +68,8 @@ string parameterName int mipHeight = Math.Max(1, descriptor.height >> region.mip); if (region.x > mipWidth - region.width || region.y > mipHeight - region.height - || region.layer > descriptor.GetSubresourceLayerCount(region.mip) - region.depth) - { + || region.layer > descriptor.GetSubresourceLayerCount(region.mip) - region.depth + ) { throw new ArgumentOutOfRangeException(parameterName, "Texture region is outside the descriptor."); } } @@ -81,12 +80,16 @@ private void ValidateIndirect( int commandCount ) { if (!m_device.capabilities.Supports(GraphicsCapability.Indirect)) + { throw new NotSupportedException("The active graphics backend does not support indirect commands."); + } ArgumentOutOfRangeException.ThrowIfNegative(firstCommand); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(commandCount); ValidateRange(firstCommand, commandCount, buffer.descriptor.elementCount, nameof(commandCount)); if (buffer.kind != BgfxBufferKind.Indirect) + { throw new ArgumentException("The buffer was not created for indirect commands.", nameof(buffer)); + } } private BgfxPipelineResource RequireGraphicsPipeline() @@ -127,8 +130,8 @@ string parameterName { throw new ArgumentOutOfRangeException( parameterName, - $"Requested range [{first}, {first + count}) exceeds buffer element count {available}."); + $"Requested range [{first}, {first + count}) exceeds buffer element count {available}." + ); } } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.cs index eac84650e..97f575606 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.cs @@ -40,5 +40,4 @@ ushort viewId m_encoder = encoder; m_viewId = viewId; } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCompositionProgramProvider.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCompositionProgramProvider.cs index 668989b2a..8ac64b8c1 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCompositionProgramProvider.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCompositionProgramProvider.cs @@ -61,31 +61,46 @@ RenderVertexLayout vertexLayout Assembly assembly = typeof(BgfxCompositionProgramProvider).Assembly; string suffix = "." + capabilities.backend.value; string[] resources = assembly.GetManifestResourceNames() - .Where(name => name.StartsWith($"Inno.BgfxShaders.{programName}.", StringComparison.Ordinal) - && name.EndsWith(suffix, StringComparison.Ordinal)) + .Where(name => ( + name.StartsWith($"Inno.BgfxShaders.{programName}.", StringComparison.Ordinal) + && name.EndsWith(suffix, StringComparison.Ordinal) + )) .ToArray(); if (resources.Length != 1) + { throw new InvalidDataException( - $"The BGFX adapter requires exactly one {programName} shader for '{capabilities.backend}'; found {resources.Length}."); + $"The BGFX adapter requires exactly one {programName} shader for '{capabilities.backend}'; found {resources.Length}." + ); + } using Stream source = assembly.GetManifestResourceStream(resources[0]) - ?? throw new InvalidDataException($"The BGFX adapter cannot read {programName} shader '{resources[0]}'."); + ?? throw new InvalidDataException($"The BGFX adapter cannot read {programName} shader '{resources[0]}'."); using var bytes = new MemoryStream(); source.CopyTo(bytes); GraphicsPipelineDescriptor program = GraphicsProgramArtifactCodec.Decode(bytes.ToArray(), vertexLayout); RenderShaderBindingDescriptor binding = program.bindings.Single(); if (binding.id.value != "s_tex" || binding.kind != RenderShaderBindingKind.Texture - || binding.slot != 0) + || binding.slot != 0 + ) { throw new InvalidDataException($"The BGFX {programName} shader must expose s_tex at slot zero."); + } RenderRasterState authored = program.rasterState; var raster = new RenderRasterState( - RenderCullMode.None, authored.frontFace, RenderDepthCompare.Always, - depthWrite: false, blend, - authored.colorWriteMask, authored.multisampling, authored.topology); + RenderCullMode.None, + authored.frontFace, + RenderDepthCompare.Always, + depthWrite: false, + blend, + authored.colorWriteMask, + authored.multisampling, + authored.topology + ); return new GraphicsPipelineDescriptor( program.vertexShader.Span, program.fragmentShader.Span, [new(S_TEXTURE, RenderShaderBindingKind.Texture, slot: 0, nativeName: binding.nativeName)], - vertexLayout, raster); + vertexLayout, + raster + ); } } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs index 5ea197b42..6553e80f9 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs @@ -1,10 +1,10 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -52,7 +52,8 @@ CompiledRenderPass pass attachment.slot, attachment.isDepth, attachment.mipLevel, - attachment.arrayLayer); + attachment.arrayLayer + ); BgfxNativeCalls.AttachmentInit( &attachments[index], nativeTexture, @@ -60,24 +61,24 @@ CompiledRenderPass pass checked((ushort)attachment.arrayLayer), 1, checked((ushort)attachment.mipLevel), - (byte)bgfx.ResolveFlags.None); + (byte)bgfx.ResolveFlags.None + ); } bgfx.FrameBufferHandle frameBuffer = BgfxNativeCalls.CreateFrameBufferFromAttachment( checked((byte)pass.attachments.Count), attachments, - 0); + 0 + ); if (!frameBuffer.Valid) { throw new InvalidOperationException($"BGFX could not create framebuffer for pass '{pass.name}'."); } m_transientFrameBufferAllocationCount++; - m_graphFrameBufferCache.Add(new CachedGraphFrameBuffer( - frameBuffer, - pass.name, - signature, - m_submissionSequence)); + m_graphFrameBufferCache.Add( + new CachedGraphFrameBuffer(frameBuffer, pass.name, signature, m_submissionSequence) + ); m_graphFrameBuffers.Add(frameBuffer); bgfx.set_view_frame_buffer(viewId, frameBuffer); } @@ -89,26 +90,21 @@ CompiledRenderPass pass ref clearFlags, ref clearColor, ref clearDepth, - ref clearStencil); + ref clearStencil + ); } else { bgfx.set_view_frame_buffer(viewId, new bgfx.FrameBufferHandle { idx = ushort.MaxValue }); } - if (pass.clearsPresentationTarget) { clearFlags |= bgfx.ClearFlags.Color; clearColor = PackColor(pass.presentationClearColor); } - bgfx.set_view_rect( - viewId, - 0, - 0, - checked((ushort)width), - checked((ushort)height)); + bgfx.set_view_rect(viewId, 0, 0, checked((ushort)width), checked((ushort)height)); bgfx.set_view_clear(viewId, (ushort)clearFlags, clearColor, clearDepth, clearStencil); } @@ -118,7 +114,9 @@ private bgfx.FrameBufferHandle FindCachedFrameBuffer(CompiledRenderPass pass) { CachedGraphFrameBuffer cached = m_graphFrameBufferCache[cacheIndex]; if (cached.attachments.Length != pass.attachments.Count) + { continue; + } bool matches = true; for (int attachmentIndex = 0; attachmentIndex < pass.attachments.Count; attachmentIndex++) @@ -130,15 +128,17 @@ private bgfx.FrameBufferHandle FindCachedFrameBuffer(CompiledRenderPass pass) || signature.slot != attachment.slot || signature.isDepth != attachment.isDepth || signature.mipLevel != attachment.mipLevel - || signature.arrayLayer != attachment.arrayLayer) - { + || signature.arrayLayer != attachment.arrayLayer + ) { matches = false; break; } } if (!matches) + { continue; + } cached.lastUsedSubmission = m_submissionSequence; return cached.handle; @@ -153,8 +153,8 @@ private void RetireSupersededFrameBuffer(string passName) { CachedGraphFrameBuffer cached = m_graphFrameBufferCache[index]; if (!string.Equals(cached.passName, passName, StringComparison.Ordinal) - || cached.lastUsedSubmission == m_submissionSequence) - { + || cached.lastUsedSubmission == m_submissionSequence + ) { continue; } @@ -187,7 +187,9 @@ ref byte clearStencil { clearFlags |= bgfx.ClearFlags.Depth; if (descriptor.format == RenderTextureFormat.Depth24Stencil8) + { clearFlags |= bgfx.ClearFlags.Stencil; + } clearDepth = attachment.clearDepth; clearStencil = attachment.clearStencil; } @@ -201,8 +203,8 @@ ref byte clearStencil if (attachment.storeAction == RenderStoreAction.Discard) { clearFlags |= attachment.isDepth - ? bgfx.ClearFlags.DiscardDepth - : ColorDiscardFlag(attachment.slot); + ? bgfx.ClearFlags.DiscardDepth + : ColorDiscardFlag(attachment.slot); } } } @@ -213,7 +215,9 @@ private void RemoveCachedFrameBuffersReferencing(ushort textureIndex) { CachedGraphFrameBuffer cached = m_graphFrameBufferCache[index]; if (!cached.ContainsTexture(textureIndex)) + { continue; + } EnqueueDestroy(DeferredResource.ForFrameBuffer(cached.handle)); m_graphFrameBufferCache.RemoveAt(index); } @@ -243,7 +247,9 @@ internal bool ContainsTexture(ushort textureIndex) foreach (GraphAttachmentSignature attachment in attachments) { if (attachment.textureIndex == textureIndex) + { return true; + } } return false; @@ -252,16 +258,15 @@ internal bool ContainsTexture(ushort textureIndex) private static bgfx.ClearFlags ColorDiscardFlag(int slot) => slot switch - { - 0 => bgfx.ClearFlags.DiscardColor0, - 1 => bgfx.ClearFlags.DiscardColor1, - 2 => bgfx.ClearFlags.DiscardColor2, - 3 => bgfx.ClearFlags.DiscardColor3, - 4 => bgfx.ClearFlags.DiscardColor4, - 5 => bgfx.ClearFlags.DiscardColor5, - 6 => bgfx.ClearFlags.DiscardColor6, - 7 => bgfx.ClearFlags.DiscardColor7, - _ => throw new ArgumentOutOfRangeException(nameof(slot)) - }; - + { + 0 => bgfx.ClearFlags.DiscardColor0, + 1 => bgfx.ClearFlags.DiscardColor1, + 2 => bgfx.ClearFlags.DiscardColor2, + 3 => bgfx.ClearFlags.DiscardColor3, + 4 => bgfx.ClearFlags.DiscardColor4, + 5 => bgfx.ClearFlags.DiscardColor5, + 6 => bgfx.ClearFlags.DiscardColor6, + 7 => bgfx.ClearFlags.DiscardColor7, + _ => throw new ArgumentOutOfRangeException(nameof(slot)) + }; } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs index bafa4f3fd..1820709fa 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs @@ -1,10 +1,10 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -52,7 +52,8 @@ public void BeginFrame() checked((uint)m_backbufferWidth), checked((uint)m_backbufferHeight), m_resetFlags, - bgfx.TextureFormat.Count); + bgfx.TextureFormat.Count + ); } } @@ -124,9 +125,13 @@ public void SetPrimaryPresentationSize(RenderPresentationSize? size) EnsureApiThread(); ObjectDisposedException.ThrowIf(m_disposed, this); if (size is RenderPresentationSize assigned && !assigned.isValid) + { throw new ArgumentException("A primary presentation extent must have positive pixel dimensions.", nameof(size)); + } if (size.HasValue && !m_hasPrimarySurface) + { throw new NotSupportedException("A windowless BGFX device has no primary presentation surface."); + } m_pendingPresentationSize = size; m_presentationUpdatePending = true; } @@ -143,10 +148,12 @@ public void SetVerticalSync(bool enabled) EnsureApiThread(); ObjectDisposedException.ThrowIf(m_disposed, this); uint next = enabled - ? m_resetFlags | (uint)bgfx.ResetFlags.Vsync - : m_resetFlags & ~(uint)bgfx.ResetFlags.Vsync; + ? m_resetFlags | (uint)bgfx.ResetFlags.Vsync + : m_resetFlags & ~(uint)bgfx.ResetFlags.Vsync; if (next == m_resetFlags) + { return; + } m_resetFlags = next; m_resetPending = true; } @@ -160,5 +167,4 @@ private void ResetPreviousViews() m_nextViewId = 0; } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs index 0177acbc6..64f2e1ed4 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs @@ -1,10 +1,10 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -34,7 +34,8 @@ public void BeginGraph(CompiledRenderGraph graph) throw new InvalidOperationException( $"Frame requires at least {m_nextViewId + requestedViews} views, " + $"but the device supports {capabilities.limits.maxViews}. " - + "Reduce active cameras, viewports, or render passes."); + + "Reduce active cameras, viewports, or render passes." + ); } m_activeGraph = graph; @@ -67,17 +68,15 @@ public void BeginGraph(CompiledRenderGraph graph) if (!m_transientTextureSlots.TryGetValue(texture.physicalSlot, out nativeTexture)) { - nativeTexture = AcquireTransientTexture( - texture.descriptor, - texture.name, - texture.physicalSlot); + nativeTexture = AcquireTransientTexture(texture.descriptor, texture.name, texture.physicalSlot); m_transientTextureSlots.Add(texture.physicalSlot, nativeTexture); m_transientTextureSlotDescriptors.Add(texture.physicalSlot, texture.descriptor); } else if (!m_transientTextureSlotDescriptors[texture.physicalSlot].Equals(texture.descriptor)) { throw new InvalidOperationException( - $"Render-graph physical texture slot {texture.physicalSlot} aliases incompatible descriptors."); + $"Render-graph physical texture slot {texture.physicalSlot} aliases incompatible descriptors." + ); } } @@ -95,7 +94,8 @@ public void BeginGraph(CompiledRenderGraph graph) bgfx.Raw.set_view_order( checked((ushort)m_activeGraphViewBase), checked((ushort)graph.passes.Count), - order); + order + ); } m_nextViewId += requestedViews; @@ -128,7 +128,8 @@ public RenderCommandEncoder BeginPass(CompiledRenderPass pass) ushort viewId = checked((ushort)(m_activeGraphViewBase + pass.viewIndex)); int viewNameLength = Encoding.UTF8.GetByteCount(pass.name); Span viewNameBytes = viewNameLength < 256 - ? stackalloc byte[256] : new byte[checked(viewNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(viewNameLength + 1)]; Encoding.UTF8.GetBytes(pass.name, viewNameBytes); viewNameBytes[viewNameLength] = 0; fixed (byte* viewNamePointer = viewNameBytes) @@ -216,5 +217,4 @@ private void ReleasePreparedGraphResources() m_activeGraph = null; m_activeGraphViewBase = 0; } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs index 2eee672e2..741b20a08 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs @@ -1,10 +1,10 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -33,16 +33,22 @@ public RenderTextureReadbackHandle BeginTextureReadback( ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); ValidatePersistentHandle(texture); if (!capabilities.Supports(GraphicsCapability.TextureReadback)) + { throw new NotSupportedException("The active BGFX renderer does not support texture readback."); + } if (!m_persistentTextures.TryGetValue(GetHandleIdentity(texture).value, out bgfx.TextureHandle nativeTexture) - || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor)) - { + || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor) + ) { throw new ArgumentException("Persistent texture is not active on this device.", nameof(texture)); } if ((descriptor.usage & RenderTextureUsage.Readback) == 0) + { throw new ArgumentException("Texture was not created for readback.", nameof(texture)); + } if (mipLevel >= descriptor.mipCount) + { throw new ArgumentOutOfRangeException(nameof(mipLevel)); + } int width = Math.Max(1, descriptor.width >> mipLevel); int height = Math.Max(1, descriptor.height >> mipLevel); int layers = descriptor.GetSubresourceLayerCount(mipLevel); @@ -68,7 +74,9 @@ public RenderTextureReadbackHandle BeginTextureReadback( rowPitch, byteCount, (nint)data, - checked(m_submissionSequence + unchecked(readyFrame - m_backendFrame)))); + checked(m_submissionSequence + unchecked(readyFrame - m_backendFrame)) + ) + ); return CreateRenderTextureReadbackHandle(id, generation); } @@ -91,22 +99,24 @@ out RenderTextureReadbackResult? result EnsureFrameSafetyPoint(); ValidateReadbackHandle(readback); if (!m_textureReadbacks.TryGetValue(GetHandleIdentity(readback).value, out PendingTextureReadback? pending)) + { throw new ArgumentException("Texture readback is not active on this device.", nameof(readback)); + } result = null; if (m_submissionSequence < pending.readySubmission) + { return false; + } m_textureReadbacks.Remove(GetHandleIdentity(readback).value); try { if (pending.canceled) + { return false; + } byte[] bytes = new byte[pending.byteCount]; Marshal.Copy(pending.data, bytes, 0, bytes.Length); - result = new RenderTextureReadbackResult( - pending.descriptor, - pending.mipLevel, - pending.rowPitch, - bytes); + result = new RenderTextureReadbackResult(pending.descriptor, pending.mipLevel, pending.rowPitch, bytes); return true; } finally @@ -126,7 +136,9 @@ public void CancelTextureReadback(RenderTextureReadbackHandle readback) EnsureFrameSafetyPoint(); ValidateReadbackHandle(readback); if (m_textureReadbacks.TryGetValue(GetHandleIdentity(readback).value, out PendingTextureReadback? pending)) + { pending.canceled = true; + } } private void ProcessCanceledReadbacks() @@ -134,7 +146,9 @@ private void ProcessCanceledReadbacks() foreach ((ulong id, PendingTextureReadback pending) in m_textureReadbacks.ToArray()) { if (!pending.canceled || m_submissionSequence < pending.readySubmission) + { continue; + } NativeMemory.Free((void*)pending.data); m_textureReadbacks.Remove(id); } @@ -143,7 +157,9 @@ private void ProcessCanceledReadbacks() private void ValidateReadbackHandle(RenderTextureReadbackHandle readback) { if (!readback.isValid || GetHandleIdentity(readback).generation != generation) + { throw new ArgumentException("Texture readback belongs to another device generation.", nameof(readback)); + } } private sealed class PendingTextureReadback( @@ -162,5 +178,4 @@ ulong readySubmission internal ulong readySubmission { get; } = readySubmission; internal bool canceled { get; set; } } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs index 6db2cf4a8..e7c49fabc 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs @@ -49,7 +49,8 @@ string name { throw new ArgumentException( $"Initial buffer data must contain exactly {expectedSize} bytes.", - nameof(initialData)); + nameof(initialData) + ); } BgfxBufferResource resource = CreateNativeBuffer(descriptor, initialData, name); @@ -104,7 +105,8 @@ public void UpdateBuffer( if (resource.kind == BgfxBufferKind.Indirect) { throw new NotSupportedException( - "BGFX indirect command buffers are populated by compute shaders, not CPU updates."); + "BGFX indirect command buffers are populated by compute shaders, not CPU updates." + ); } if ((resource.descriptor.usage & RenderBufferUsage.Dynamic) == 0) { @@ -129,13 +131,15 @@ public void UpdateBuffer( BgfxNativeCalls.UpdateDynamicVertexBuffer( new bgfx.DynamicVertexBufferHandle { idx = resource.nativeIndex }, checked((uint)startElement), - memory); + memory + ); break; case BgfxBufferKind.DynamicIndex: BgfxNativeCalls.UpdateDynamicIndexBuffer( new bgfx.DynamicIndexBufferHandle { idx = resource.nativeIndex }, checked((uint)startElement), - memory); + memory + ); break; default: throw new InvalidOperationException("A Dynamic descriptor resolved to an immutable BGFX buffer."); @@ -263,8 +267,8 @@ internal BgfxBufferResource ResolveBuffer(RenderBufferHandle buffer) { if (m_activeGraph is null || GetHandleIdentity(buffer).generation != m_activeGraph.generation - || !m_graphBuffers.TryGetValue(GetHandleIdentity(buffer).index, out BgfxBufferResource? resource)) - { + || !m_graphBuffers.TryGetValue(GetHandleIdentity(buffer).index, out BgfxBufferResource? resource) + ) { throw new ArgumentException("Buffer is not active in the current BGFX graph.", nameof(buffer)); } @@ -317,7 +321,8 @@ private void PrepareGraphBuffers(CompiledRenderGraph graph) if (!resource.descriptor.Equals(buffer.descriptor)) { throw new InvalidOperationException( - $"Imported buffer '{buffer.name}' does not match its persistent descriptor."); + $"Imported buffer '{buffer.name}' does not match its persistent descriptor." + ); } } else @@ -335,7 +340,8 @@ private void PrepareGraphBuffers(CompiledRenderGraph graph) else if (!resource.descriptor.Equals(buffer.descriptor)) { throw new InvalidOperationException( - $"Render-graph physical buffer slot {buffer.physicalSlot} aliases incompatible descriptors."); + $"Render-graph physical buffer slot {buffer.physicalSlot} aliases incompatible descriptors." + ); } } @@ -350,18 +356,20 @@ string name ) { RenderBufferDescriptor buffer = descriptor.buffer; if ((buffer.usage & RenderBufferUsage.Indirect) != 0 - && (buffer.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) == 0) - { + && (buffer.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) == 0 + ) { if (!capabilities.Supports(GraphicsCapability.Indirect)) + { throw new NotSupportedException("The active backend does not support indirect command buffers."); + } if (!initialData.IsEmpty) { throw new ArgumentException( "BGFX indirect buffers cannot be initialized from CPU data.", - nameof(initialData)); + nameof(initialData) + ); } - bgfx.IndirectBufferHandle indirect = bgfx.create_indirect_buffer( - checked((uint)buffer.elementCount)); + bgfx.IndirectBufferHandle indirect = bgfx.create_indirect_buffer(checked((uint)buffer.elementCount)); EnsureValid(indirect.Valid, name); return BgfxBufferResource.FromIndirect(buffer, indirect); } @@ -369,8 +377,8 @@ string name bool dynamic = (buffer.usage & (RenderBufferUsage.Dynamic | RenderBufferUsage.Storage)) != 0; if (indexBuffer && descriptor.indexFormat == RenderIndexFormat.UInt32 - && !capabilities.Supports(GraphicsCapability.Index32)) - { + && !capabilities.Supports(GraphicsCapability.Index32) + ) { throw new NotSupportedException("The active backend does not support unsigned 32-bit indices."); } ValidateVertexLayoutCapabilities(descriptor.vertexLayout); @@ -387,7 +395,8 @@ string name { bgfx.DynamicIndexBufferHandle handle = bgfx.create_dynamic_index_buffer( checked((uint)buffer.elementCount), - flags); + flags + ); EnsureValid(handle.Valid, name); if (!initialData.IsEmpty) { @@ -401,7 +410,8 @@ string name EnsureValid(staticHandle.Valid, name); int indexBufferNameLength = Encoding.UTF8.GetByteCount(name); Span indexBufferNameBytes = indexBufferNameLength < 256 - ? stackalloc byte[256] : new byte[checked(indexBufferNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(indexBufferNameLength + 1)]; Encoding.UTF8.GetBytes(name, indexBufferNameBytes); indexBufferNameBytes[indexBufferNameLength] = 0; fixed (byte* indexBufferNamePointer = indexBufferNameBytes) @@ -415,19 +425,19 @@ string name bool storageBuffer = (buffer.usage & RenderBufferUsage.Storage) != 0; if (!vertexBuffer && !storageBuffer) { - throw new NotSupportedException( - "BGFX persistent buffers must be vertex, index, or storage resources."); + throw new NotSupportedException("BGFX persistent buffers must be vertex, index, or storage resources."); } bgfx.VertexLayout nativeLayout = descriptor.vertexLayout is null - ? CreateSkippedLayout(buffer.elementStride) - : CreateNativeLayout(descriptor.vertexLayout); + ? CreateSkippedLayout(buffer.elementStride) + : CreateNativeLayout(descriptor.vertexLayout); if (initialData.IsEmpty || dynamic) { bgfx.DynamicVertexBufferHandle handle = BgfxNativeCalls.CreateDynamicVertexBuffer( checked((uint)buffer.elementCount), &nativeLayout, - flags); + flags + ); EnsureValid(handle.Valid, name); if (!initialData.IsEmpty) { @@ -441,7 +451,8 @@ string name EnsureValid(vertexHandle.Valid, name); int vertexBufferNameLength = Encoding.UTF8.GetByteCount(name); Span vertexBufferNameBytes = vertexBufferNameLength < 256 - ? stackalloc byte[256] : new byte[checked(vertexBufferNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(vertexBufferNameLength + 1)]; Encoding.UTF8.GetBytes(name, vertexBufferNameBytes); vertexBufferNameBytes[vertexBufferNameLength] = 0; fixed (byte* vertexBufferNamePointer = vertexBufferNameBytes) @@ -454,12 +465,13 @@ string name private BgfxBufferResource CreateTransientBuffer(RenderBufferDescriptor descriptor) { if ((descriptor.usage & RenderBufferUsage.Indirect) != 0 - && (descriptor.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) == 0) - { + && (descriptor.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) == 0 + ) { if (!capabilities.Supports(GraphicsCapability.Indirect)) + { throw new NotSupportedException("The active backend does not support indirect command buffers."); - bgfx.IndirectBufferHandle indirect = bgfx.create_indirect_buffer( - checked((uint)descriptor.elementCount)); + } + bgfx.IndirectBufferHandle indirect = bgfx.create_indirect_buffer(checked((uint)descriptor.elementCount)); EnsureValid(indirect.Valid, "transient indirect buffer"); return BgfxBufferResource.FromIndirect(descriptor, indirect); } @@ -472,28 +484,29 @@ private BgfxBufferResource CreateTransientBuffer(RenderBufferDescriptor descript _ => throw new NotSupportedException("Transient index buffers require a two- or four-byte stride.") }; if (format == RenderIndexFormat.UInt32 - && !capabilities.Supports(GraphicsCapability.Index32)) - { + && !capabilities.Supports(GraphicsCapability.Index32) + ) { throw new NotSupportedException("The active backend does not support unsigned 32-bit indices."); } bgfx.DynamicIndexBufferHandle index = bgfx.create_dynamic_index_buffer( checked((uint)descriptor.elementCount), - BufferFlags(descriptor, format)); + BufferFlags(descriptor, format) + ); EnsureValid(index.Valid, "transient index buffer"); return BgfxBufferResource.FromDynamicIndex(descriptor, format, index); } if ((descriptor.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Storage)) == 0) { - throw new NotSupportedException( - "BGFX transient buffers must be vertex, index, or storage resources."); + throw new NotSupportedException("BGFX transient buffers must be vertex, index, or storage resources."); } bgfx.VertexLayout layout = CreateSkippedLayout(descriptor.elementStride); bgfx.DynamicVertexBufferHandle vertex = BgfxNativeCalls.CreateDynamicVertexBuffer( checked((uint)descriptor.elementCount), &layout, - BufferFlags(descriptor, RenderIndexFormat.UInt32)); + BufferFlags(descriptor, RenderIndexFormat.UInt32) + ); EnsureValid(vertex.Valid, "transient vertex or storage buffer"); return BgfxBufferResource.FromDynamicVertex(descriptor, null, vertex); } @@ -506,8 +519,8 @@ int physicalSlot { PooledTransientBuffer pooled = m_transientBufferPool[index]; if (pooled.physicalSlot != physicalSlot - || !pooled.resource.descriptor.Equals(descriptor)) - { + || !pooled.resource.descriptor.Equals(descriptor) + ) { continue; } m_transientBufferPool.RemoveAt(index); @@ -518,7 +531,9 @@ int physicalSlot { PooledTransientBuffer pooled = m_transientBufferPool[index]; if (!pooled.resource.descriptor.Equals(descriptor)) + { continue; + } m_transientBufferPool.RemoveAt(index); return pooled.resource; } @@ -562,7 +577,8 @@ string name descriptor.vertexLayout, layoutHandle, descriptor.rasterState, - false); + false + ); } catch { @@ -586,21 +602,25 @@ string name private void ValidateVertexLayoutCapabilities(RenderVertexLayout? layout) { if (layout is null) + { return; + } foreach (RenderVertexAttribute attribute in layout.attributes) { if (attribute.format is RenderVertexFormat.Half2 or RenderVertexFormat.Half4 - && !capabilities.Supports(GraphicsCapability.VertexAttributeHalf)) - { + && !capabilities.Supports(GraphicsCapability.VertexAttributeHalf) + ) { throw new NotSupportedException( - "The active backend does not support half-precision vertex attributes."); + "The active backend does not support half-precision vertex attributes." + ); } if (attribute.format == RenderVertexFormat.UInt10Normalized4 - && !capabilities.Supports(GraphicsCapability.VertexAttributeUInt10)) - { + && !capabilities.Supports(GraphicsCapability.VertexAttributeUInt10) + ) { throw new NotSupportedException( - "The active backend does not support packed 10:10:10:2 vertex attributes."); + "The active backend does not support packed 10:10:10:2 vertex attributes." + ); } } } @@ -608,10 +628,9 @@ private void ValidateVertexLayoutCapabilities(RenderVertexLayout? layout) private void ValidateRasterStateCapabilities(RenderRasterState state) { if (state.blend.alphaToCoverage - && !capabilities.Supports(GraphicsCapability.AlphaToCoverage)) - { - throw new NotSupportedException( - "The active backend does not support alpha-to-coverage rasterization."); + && !capabilities.Supports(GraphicsCapability.AlphaToCoverage) + ) { + throw new NotSupportedException("The active backend does not support alpha-to-coverage rasterization."); } } @@ -631,13 +650,7 @@ string name program = bgfx.create_compute_program(computeShader, true); EnsureValid(program.Valid, name); computeShader = InvalidShader(); - return new BgfxPipelineResource( - program, - bindings, - null, - InvalidVertexLayout(), - null, - true); + return new BgfxPipelineResource(program, bindings, null, InvalidVertexLayout(), null, true); } catch { @@ -661,20 +674,20 @@ IReadOnlyDictionary reflected foreach ((string name, ReflectedUniform uniform) in reflected) { if (!declared.TryGetValue(name, out RenderShaderBindingDescriptor? binding) - || binding.kind is RenderShaderBindingKind.StorageBuffer or RenderShaderBindingKind.StorageTexture) - { - throw new InvalidOperationException( - $"Shader reflection contains undeclared uniform '{name}'."); + || binding.kind is RenderShaderBindingKind.StorageBuffer or RenderShaderBindingKind.StorageTexture + ) { + throw new InvalidOperationException($"Shader reflection contains undeclared uniform '{name}'."); } bgfx.UniformType expectedType = binding.kind == RenderShaderBindingKind.Texture - ? bgfx.UniformType.Sampler - : ToNativeUniformType(binding.uniformType); + ? bgfx.UniformType.Sampler + : ToNativeUniformType(binding.uniformType); if (uniform.type != expectedType || uniform.count != binding.count) { throw new InvalidOperationException( $"Shader binding '{name}' reflected as {uniform.type}[{uniform.count}] but the manifest requires " - + $"{expectedType}[{binding.count}]."); + + $"{expectedType}[{binding.count}]." + ); } } @@ -690,7 +703,8 @@ IReadOnlyDictionary reflected if (!reflected.TryGetValue(binding.nativeName, out ReflectedUniform uniform)) { throw new InvalidOperationException( - $"Shader manifest binding '{binding.id.value}' is absent from compiled reflection."); + $"Shader manifest binding '{binding.id.value}' is absent from compiled reflection." + ); } result.Add(binding.id.value, new BgfxShaderBindingResource(binding, uniform.handle)); @@ -721,10 +735,11 @@ private static Dictionary ReflectShaders(params bgfx.S string name = UniformName(info); ReflectedUniform reflected = new(uniforms[index], info.type, info.num); if (result.TryGetValue(name, out ReflectedUniform current) - && (current.type != reflected.type || current.count != reflected.count)) - { + && (current.type != reflected.type || current.count != reflected.count) + ) { throw new InvalidOperationException( - $"Shader stages disagree about reflected binding '{name}'."); + $"Shader stages disagree about reflected binding '{name}'." + ); } result[name] = reflected; @@ -752,7 +767,8 @@ string name EnsureValid(shader.Valid, name); int shaderNameLength = Encoding.UTF8.GetByteCount(name); Span shaderNameBytes = shaderNameLength < 256 - ? stackalloc byte[256] : new byte[checked(shaderNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(shaderNameLength + 1)]; Encoding.UTF8.GetBytes(name, shaderNameBytes); shaderNameBytes[shaderNameLength] = 0; fixed (byte* shaderNamePointer = shaderNameBytes) @@ -777,7 +793,8 @@ private bgfx.VertexLayout CreateNativeLayout(RenderVertexLayout layout) count, type, normalized ? (byte)1 : (byte)0, - asInteger ? (byte)1 : (byte)0); + asInteger ? (byte)1 : (byte)0 + ); currentOffset = checked(attribute.byteOffset + attribute.byteSize); } @@ -787,7 +804,8 @@ private bgfx.VertexLayout CreateNativeLayout(RenderVertexLayout layout) if (native.stride != layout.stride) { throw new InvalidOperationException( - $"BGFX produced vertex stride {native.stride}, expected {layout.stride}."); + $"BGFX produced vertex stride {native.stride}, expected {layout.stride}." + ); } return native; @@ -798,7 +816,9 @@ private static void AddVertexLayoutPadding( int byteCount ) { if (byteCount < 0) + { throw new InvalidOperationException("A resolved vertex layout cannot contain overlapping attributes."); + } while (byteCount != 0) { byte chunk = checked((byte)Math.Min(byteCount, byte.MaxValue)); @@ -825,57 +845,57 @@ private bgfx.VertexLayout CreateSkippedLayout(int stride) private static (byte count, bgfx.AttribType type, bool normalized, bool asInteger) AttributeFormat(RenderVertexFormat format) => format switch - { - RenderVertexFormat.Float1 => (1, bgfx.AttribType.Float, false, false), - RenderVertexFormat.Float2 => (2, bgfx.AttribType.Float, false, false), - RenderVertexFormat.Float3 => (3, bgfx.AttribType.Float, false, false), - RenderVertexFormat.Float4 => (4, bgfx.AttribType.Float, false, false), - RenderVertexFormat.Half2 => (2, bgfx.AttribType.Half, false, false), - RenderVertexFormat.Half4 => (4, bgfx.AttribType.Half, false, false), - RenderVertexFormat.UInt8Normalized2 => (2, bgfx.AttribType.Uint8, true, false), - RenderVertexFormat.UInt8Normalized4 => (4, bgfx.AttribType.Uint8, true, false), - RenderVertexFormat.UInt8Integer2 => (2, bgfx.AttribType.Uint8, false, true), - RenderVertexFormat.UInt8Integer4 => (4, bgfx.AttribType.Uint8, false, true), - RenderVertexFormat.UInt10Normalized4 => (4, bgfx.AttribType.Uint10, true, false), - RenderVertexFormat.Int16Normalized2 => (2, bgfx.AttribType.Int16, true, false), - RenderVertexFormat.Int16Normalized4 => (4, bgfx.AttribType.Int16, true, false), - RenderVertexFormat.Int16Integer2 => (2, bgfx.AttribType.Int16, false, true), - RenderVertexFormat.Int16Integer4 => (4, bgfx.AttribType.Int16, false, true), - _ => throw new ArgumentOutOfRangeException(nameof(format)) - }; + { + RenderVertexFormat.Float1 => (1, bgfx.AttribType.Float, false, false), + RenderVertexFormat.Float2 => (2, bgfx.AttribType.Float, false, false), + RenderVertexFormat.Float3 => (3, bgfx.AttribType.Float, false, false), + RenderVertexFormat.Float4 => (4, bgfx.AttribType.Float, false, false), + RenderVertexFormat.Half2 => (2, bgfx.AttribType.Half, false, false), + RenderVertexFormat.Half4 => (4, bgfx.AttribType.Half, false, false), + RenderVertexFormat.UInt8Normalized2 => (2, bgfx.AttribType.Uint8, true, false), + RenderVertexFormat.UInt8Normalized4 => (4, bgfx.AttribType.Uint8, true, false), + RenderVertexFormat.UInt8Integer2 => (2, bgfx.AttribType.Uint8, false, true), + RenderVertexFormat.UInt8Integer4 => (4, bgfx.AttribType.Uint8, false, true), + RenderVertexFormat.UInt10Normalized4 => (4, bgfx.AttribType.Uint10, true, false), + RenderVertexFormat.Int16Normalized2 => (2, bgfx.AttribType.Int16, true, false), + RenderVertexFormat.Int16Normalized4 => (4, bgfx.AttribType.Int16, true, false), + RenderVertexFormat.Int16Integer2 => (2, bgfx.AttribType.Int16, false, true), + RenderVertexFormat.Int16Integer4 => (4, bgfx.AttribType.Int16, false, true), + _ => throw new ArgumentOutOfRangeException(nameof(format)) + }; private static bgfx.Attrib ToNativeAttribute(RenderVertexSemantic semantic) => semantic switch - { - RenderVertexSemantic.Position => bgfx.Attrib.Position, - RenderVertexSemantic.Normal => bgfx.Attrib.Normal, - RenderVertexSemantic.Tangent => bgfx.Attrib.Tangent, - RenderVertexSemantic.Bitangent => bgfx.Attrib.Bitangent, - RenderVertexSemantic.Color0 => bgfx.Attrib.Color0, - RenderVertexSemantic.Color1 => bgfx.Attrib.Color1, - RenderVertexSemantic.Color2 => bgfx.Attrib.Color2, - RenderVertexSemantic.Color3 => bgfx.Attrib.Color3, - RenderVertexSemantic.TextureCoordinate0 => bgfx.Attrib.TexCoord0, - RenderVertexSemantic.TextureCoordinate1 => bgfx.Attrib.TexCoord1, - RenderVertexSemantic.TextureCoordinate2 => bgfx.Attrib.TexCoord2, - RenderVertexSemantic.TextureCoordinate3 => bgfx.Attrib.TexCoord3, - RenderVertexSemantic.TextureCoordinate4 => bgfx.Attrib.TexCoord4, - RenderVertexSemantic.TextureCoordinate5 => bgfx.Attrib.TexCoord5, - RenderVertexSemantic.TextureCoordinate6 => bgfx.Attrib.TexCoord6, - RenderVertexSemantic.TextureCoordinate7 => bgfx.Attrib.TexCoord7, - RenderVertexSemantic.BlendIndices => bgfx.Attrib.Indices, - RenderVertexSemantic.BlendWeights => bgfx.Attrib.Weight, - _ => throw new ArgumentOutOfRangeException(nameof(semantic)) - }; + { + RenderVertexSemantic.Position => bgfx.Attrib.Position, + RenderVertexSemantic.Normal => bgfx.Attrib.Normal, + RenderVertexSemantic.Tangent => bgfx.Attrib.Tangent, + RenderVertexSemantic.Bitangent => bgfx.Attrib.Bitangent, + RenderVertexSemantic.Color0 => bgfx.Attrib.Color0, + RenderVertexSemantic.Color1 => bgfx.Attrib.Color1, + RenderVertexSemantic.Color2 => bgfx.Attrib.Color2, + RenderVertexSemantic.Color3 => bgfx.Attrib.Color3, + RenderVertexSemantic.TextureCoordinate0 => bgfx.Attrib.TexCoord0, + RenderVertexSemantic.TextureCoordinate1 => bgfx.Attrib.TexCoord1, + RenderVertexSemantic.TextureCoordinate2 => bgfx.Attrib.TexCoord2, + RenderVertexSemantic.TextureCoordinate3 => bgfx.Attrib.TexCoord3, + RenderVertexSemantic.TextureCoordinate4 => bgfx.Attrib.TexCoord4, + RenderVertexSemantic.TextureCoordinate5 => bgfx.Attrib.TexCoord5, + RenderVertexSemantic.TextureCoordinate6 => bgfx.Attrib.TexCoord6, + RenderVertexSemantic.TextureCoordinate7 => bgfx.Attrib.TexCoord7, + RenderVertexSemantic.BlendIndices => bgfx.Attrib.Indices, + RenderVertexSemantic.BlendWeights => bgfx.Attrib.Weight, + _ => throw new ArgumentOutOfRangeException(nameof(semantic)) + }; private static bgfx.UniformType ToNativeUniformType(RenderUniformType type) => type switch - { - RenderUniformType.Vector4 => bgfx.UniformType.Vec4, - RenderUniformType.Matrix3x3 => bgfx.UniformType.Mat3, - RenderUniformType.Matrix4x4 => bgfx.UniformType.Mat4, - _ => throw new ArgumentOutOfRangeException(nameof(type)) - }; + { + RenderUniformType.Vector4 => bgfx.UniformType.Vec4, + RenderUniformType.Matrix3x3 => bgfx.UniformType.Mat3, + RenderUniformType.Matrix4x4 => bgfx.UniformType.Mat4, + _ => throw new ArgumentOutOfRangeException(nameof(type)) + }; private void ValidateBindingSlots( IReadOnlyList bindings, @@ -885,34 +905,40 @@ bool allowStorageResources foreach (RenderShaderBindingDescriptor binding in bindings) { if (binding.kind is RenderShaderBindingKind.Texture - or RenderShaderBindingKind.StorageTexture - or RenderShaderBindingKind.StorageBuffer - && binding.slot > byte.MaxValue) - { + or RenderShaderBindingKind.StorageTexture + or RenderShaderBindingKind.StorageBuffer + && binding.slot > byte.MaxValue + ) { throw new ArgumentOutOfRangeException( nameof(bindings), - $"Binding '{binding.id.value}' slot exceeds the BGFX byte-sized stage range."); + $"Binding '{binding.id.value}' slot exceeds the BGFX byte-sized stage range." + ); } if (binding.kind is not (RenderShaderBindingKind.StorageTexture or RenderShaderBindingKind.StorageBuffer)) + { continue; + } if (!allowStorageResources) { throw new NotSupportedException( - $"BGFX graphics pipelines cannot bind storage resource '{binding.id.value}'."); + $"BGFX graphics pipelines cannot bind storage resource '{binding.id.value}'." + ); } if (!storageSlots.Add(binding.slot)) { throw new ArgumentException( $"Storage binding slot {binding.slot} is declared more than once.", - nameof(bindings)); + nameof(bindings) + ); } GraphicsCapability required = binding.kind == RenderShaderBindingKind.StorageTexture - ? GraphicsCapability.StorageTexture - : GraphicsCapability.StorageBuffer; + ? GraphicsCapability.StorageTexture + : GraphicsCapability.StorageBuffer; if (!capabilities.Supports(required)) { throw new NotSupportedException( - $"The active backend does not support {binding.kind} binding '{binding.id.value}'."); + $"The active backend does not support {binding.kind} binding '{binding.id.value}'." + ); } } @@ -921,7 +947,8 @@ or RenderShaderBindingKind.StorageBuffer { throw new NotSupportedException( $"Pipeline requires {storageCount} storage bindings, but the device supports " - + $"{capabilities.limits.maxComputeBindings}."); + + $"{capabilities.limits.maxComputeBindings}." + ); } } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs index c3a82bc1f..337c61c14 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs @@ -1,10 +1,10 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -45,7 +45,9 @@ public void Dispose() surface.retirement.pending.Add(surface.frameBuffer); surface.retirement.closing = true; if (!m_surfaceRetirements.Contains(surface.retirement)) + { m_surfaceRetirements.Add(surface.retirement); + } } m_windowSurfaces.Clear(); DrainWindowSurfaceRetirements(); @@ -107,7 +109,9 @@ public void Dispose() finally { foreach (PendingTextureReadback pending in m_textureReadbacks.Values) + { NativeMemory.Free((void*)pending.data); + } m_textureReadbacks.Clear(); m_disposed = true; generation = 0; @@ -115,14 +119,18 @@ public void Dispose() } if (closureFailure is not null) + { throw new InvalidOperationException(closureFailure); + } } private void EnqueueDestroy(DeferredResource resource) - => m_deferredResources.Add(resource with - { - eligibleSubmission = checked(m_submissionSequence + (ulong)m_deferredDestroyFrames) - }); + => m_deferredResources.Add( + resource with + { + eligibleSubmission = checked(m_submissionSequence + (ulong)m_deferredDestroyFrames) + } + ); private void EnqueuePipelineDestroy(BgfxPipelineResource pipeline) => EnqueueDestroy(DeferredResource.ForProgram(pipeline.program)); @@ -215,8 +223,8 @@ private void DrainDeferredResourcesForShutdown() || m_computePipelines.Count != 0 || m_windowSurfaces.Count != 0 || m_surfaceRetirements.Count != 0 - || m_deferredResources.Count != 0) - { + || m_deferredResources.Count != 0 + ) { return "BGFX shutdown detected a non-empty managed resource ownership graph."; } @@ -274,15 +282,19 @@ public static DeferredResource ForFrameBuffer(bgfx.FrameBufferHandle frameBuffer /// The validated deferred resource that represents the completed operation. /// public static DeferredResource ForBuffer(BgfxBufferResource buffer) - => new(buffer.kind switch - { - BgfxBufferKind.Vertex => DeferredResourceKind.VertexBuffer, - BgfxBufferKind.Index => DeferredResourceKind.IndexBuffer, - BgfxBufferKind.DynamicVertex => DeferredResourceKind.DynamicVertexBuffer, - BgfxBufferKind.DynamicIndex => DeferredResourceKind.DynamicIndexBuffer, - BgfxBufferKind.Indirect => DeferredResourceKind.IndirectBuffer, - _ => throw new ArgumentOutOfRangeException(nameof(buffer)) - }, buffer.nativeIndex, 0); + => new( + buffer.kind switch + { + BgfxBufferKind.Vertex => DeferredResourceKind.VertexBuffer, + BgfxBufferKind.Index => DeferredResourceKind.IndexBuffer, + BgfxBufferKind.DynamicVertex => DeferredResourceKind.DynamicVertexBuffer, + BgfxBufferKind.DynamicIndex => DeferredResourceKind.DynamicIndexBuffer, + BgfxBufferKind.Indirect => DeferredResourceKind.IndirectBuffer, + _ => throw new ArgumentOutOfRangeException(nameof(buffer)) + }, + buffer.nativeIndex, + 0 + ); /// /// Creates a deferred resource record for the supplied program handle. @@ -307,5 +319,4 @@ public static DeferredResource ForBuffer(BgfxBufferResource buffer) public static DeferredResource ForVertexLayout(bgfx.VertexLayoutHandle layout) => new(DeferredResourceKind.VertexLayout, layout.idx, 0); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs index 95a0f51dd..30ebf6518 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs @@ -1,8 +1,8 @@ -using System.Threading.Tasks; -using Inno.Core.Execution; -using Inno.Adapter.Platform; using System; using System.Collections.Generic; +using System.Threading.Tasks; +using Inno.Adapter.Platform; +using Inno.Core.Execution; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -53,13 +53,17 @@ string name IBgfxSurfaceIntegration integration = m_surfaceIntegration ?? throw new NotSupportedException("Additional BGFX windows require an explicit surface integration."); if (!integration.supportsAdditionalSurfaces) + { throw new NotSupportedException("The selected host does not support additional window surfaces."); + } BgfxSurfaceDescriptor descriptor = BgfxSurfaceBinding.Validate( - integration.Resolve(nativeHandles, BgfxSurfaceRole.Additional)); + integration.Resolve(nativeHandles, BgfxSurfaceRole.Additional) + ); if (!capabilities.Supports(GraphicsCapability.SwapChain)) { throw new NotSupportedException( - "The active graphics backend does not support additional presentation surfaces."); + "The active graphics backend does not support additional presentation surfaces." + ); } bgfx.FrameBufferHandle frameBuffer = CreateNativeWindowSurface(descriptor, width, height); @@ -89,8 +93,8 @@ public bool WindowSurfaceIsSrgb(RenderSurfaceHandle surface) { _ = ResolveSurface(surface); return backbufferIsSrgb - && capabilities.backend != GraphicsApi.Direct3D11 - && capabilities.backend != GraphicsApi.Direct3D12; + && capabilities.backend != GraphicsApi.Direct3D11 + && capabilities.backend != GraphicsApi.Direct3D12; } /// @@ -134,7 +138,9 @@ int height resource.height = height; resource.retirement.pending.Add(previous); if (!m_surfaceRetirements.Contains(resource.retirement)) + { m_surfaceRetirements.Add(resource.retirement); + } } /// @@ -161,7 +167,9 @@ public Task RetireWindowSurface(RenderSurfaceHandle surface) resource.retirement.pending.Add(resource.frameBuffer); resource.retirement.closing = true; if (!m_surfaceRetirements.Contains(resource.retirement)) + { m_surfaceRetirements.Add(resource.retirement); + } return resource.retirement.completion.Task; } @@ -183,16 +191,24 @@ public void DrainWindowSurfaceRetirements() { EnsureSurfaceSafetyPoint(); if (m_frameOpen) + { throw new InvalidOperationException("Window retirement draining requires a closed render frame."); + } if (!HasClosingSurface()) + { return; + } m_surfaceRetirementBarrier ??= new RetirementBarrier("BGFX window surfaces"); m_surfaceRetirementBarrier.Wait(() => { SubmitRetirementFrame(); foreach (BgfxSurfaceRetirement retirement in m_surfaceRetirements) + { if (retirement.closing) + { throw new RetirementPendingException("BGFX has not acknowledged window destruction.", retirement.failure); + } + } }); m_surfaceRetirementBarrier = null; } @@ -200,8 +216,12 @@ public void DrainWindowSurfaceRetirements() private bool HasClosingSurface() { foreach (BgfxSurfaceRetirement retirement in m_surfaceRetirements) + { if (retirement.closing) + { return true; + } + } return false; } @@ -218,13 +238,19 @@ private uint SubmitNativeFrame(bgfx.FrameFlags flags) foreach (BgfxSurfaceRetirement retirement in m_surfaceRetirements) { if (retirement.failure is not null) + { throw new RetirementPendingException("A window framebuffer could not retire.", retirement.failure); + } try { foreach (bgfx.FrameBufferHandle frameBuffer in retirement.pending) + { bgfx.destroy_frame_buffer(frameBuffer); + } if (retirement.pending.Count > 0) + { retirement.lastSubmission = submission; + } retirement.pending.Clear(); } catch (Exception failure) @@ -258,9 +284,13 @@ private uint SubmitNativeFrame(bgfx.FrameFlags flags) { BgfxSurfaceRetirement retirement = m_surfaceRetirements[index]; if (retirement.lastSubmission > acknowledged) + { continue; + } if (retirement.closing) + { retirement.completion.TrySetResult(); + } m_surfaceRetirements.RemoveAt(index); } return frame; @@ -270,13 +300,13 @@ private static bgfx.FrameBufferHandle CreateNativeWindowSurface( BgfxSurfaceDescriptor descriptor, int width, int height - ) - => BgfxNativeCalls.CreateFrameBufferFromNwh( - descriptor.windowHandle.ToPointer(), - checked((ushort)width), - checked((ushort)height), - bgfx.TextureFormat.BGRA8, - bgfx.TextureFormat.D24s8); + ) => BgfxNativeCalls.CreateFrameBufferFromNwh( + descriptor.windowHandle.ToPointer(), + checked((ushort)width), + checked((ushort)height), + bgfx.TextureFormat.BGRA8, + bgfx.TextureFormat.D24s8 + ); private BgfxWindowSurfaceResource ResolveSurface(RenderSurfaceHandle surface) { @@ -296,7 +326,8 @@ private void EnsureSurfaceSafetyPoint() if (m_activeGraph is not null || m_activeEncoder != null) { throw new InvalidOperationException( - "Window surface changes require an API-thread point outside graph execution."); + "Window surface changes require an API-thread point outside graph execution." + ); } } @@ -338,19 +369,24 @@ string name /// Gets the BGFX framebuffer owned by this presentation surface. /// public bgfx.FrameBufferHandle frameBuffer { get; set; } + internal BgfxSurfaceRetirement retirement { get; } = new(); + /// /// Gets the scalar measurement or identity associated with the current state. /// public int width { get; set; } + /// /// Gets the scalar measurement or identity associated with the current state. /// public int height { get; set; } + /// /// Gets the platform-native window and display handles used to create the surface. /// public BgfxSurfaceDescriptor descriptor { get; } + /// /// Gets the human-readable name used for presentation and diagnostics. /// diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs index fd1f14751..da26f8a6a 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs @@ -1,10 +1,10 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -40,7 +40,8 @@ string name int textureNameLength = Encoding.UTF8.GetByteCount(name); Span textureNameBytes = textureNameLength < 256 - ? stackalloc byte[256] : new byte[checked(textureNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(textureNameLength + 1)]; Encoding.UTF8.GetBytes(name, textureNameBytes); textureNameBytes[textureNameLength] = 0; fixed (byte* textureNamePointer = textureNameBytes) @@ -100,7 +101,8 @@ string name memory, sRgb ? (ulong)bgfx.TextureFlags.Srgb : 0, 0, - &info); + &info + ); if (!nativeTexture.Valid) { throw new InvalidOperationException($"BGFX could not create encoded texture '{name}'."); @@ -108,7 +110,8 @@ string name int textureNameLength = Encoding.UTF8.GetByteCount(name); Span textureNameBytes = textureNameLength < 256 - ? stackalloc byte[256] : new byte[checked(textureNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(textureNameLength + 1)]; Encoding.UTF8.GetBytes(name, textureNameBytes); textureNameBytes[textureNameLength] = 0; fixed (byte* textureNamePointer = textureNameBytes) @@ -146,14 +149,14 @@ public void UpdateTexture( ArgumentOutOfRangeException.ThrowIfNegative(arrayLayer); ValidatePersistentHandle(texture); if (!m_persistentTextures.TryGetValue(GetHandleIdentity(texture).value, out bgfx.TextureHandle nativeTexture) - || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor)) - { + || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor) + ) { throw new ArgumentException("Persistent texture is not active on this device.", nameof(texture)); } if (mipLevel >= descriptor.mipCount - || arrayLayer >= descriptor.GetSubresourceLayerCount(mipLevel)) - { + || arrayLayer >= descriptor.GetSubresourceLayerCount(mipLevel) + ) { throw new ArgumentOutOfRangeException(nameof(mipLevel), "Texture subresource is outside the descriptor."); } @@ -164,7 +167,8 @@ public void UpdateTexture( { throw new ArgumentException( $"Texture update requires exactly {expectedSize} tightly packed bytes.", - nameof(data)); + nameof(data) + ); } bgfx.Memory* memory; @@ -185,7 +189,8 @@ public void UpdateTexture( checked((ushort)width), checked((ushort)height), memory, - ushort.MaxValue); + ushort.MaxValue + ); break; case RenderTextureDimension.Texture3D: BgfxNativeCalls.UpdateTexture3d( @@ -197,7 +202,8 @@ public void UpdateTexture( checked((ushort)width), checked((ushort)height), 1, - memory); + memory + ); break; case RenderTextureDimension.Cube: BgfxNativeCalls.UpdateTextureCube( @@ -210,7 +216,8 @@ public void UpdateTexture( checked((ushort)width), checked((ushort)height), memory, - ushort.MaxValue); + ushort.MaxValue + ); break; default: throw new ArgumentOutOfRangeException(nameof(descriptor)); @@ -237,26 +244,29 @@ ReadOnlySpan data EnsureFrameSafetyPoint(); ValidatePersistentHandle(texture); if (!m_persistentTextures.TryGetValue(GetHandleIdentity(texture).value, out bgfx.TextureHandle nativeTexture) - || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor)) - { + || !m_persistentTextureDescriptors.TryGetValue(GetHandleIdentity(texture).value, out RenderTextureDescriptor? descriptor) + ) { throw new ArgumentException("Persistent texture is not active on this device.", nameof(texture)); } if (region.mip >= descriptor.mipCount) + { throw new ArgumentOutOfRangeException(nameof(region), "Texture mip is outside its descriptor."); + } int mipWidth = Math.Max(1, descriptor.width >> region.mip); int mipHeight = Math.Max(1, descriptor.height >> region.mip); int layerCount = descriptor.GetSubresourceLayerCount(region.mip); - if (region.x + region.width > mipWidth || - region.y + region.height > mipHeight || - region.layer + region.depth > layerCount) - { + if (region.x + region.width > mipWidth + || region.y + region.height > mipHeight + || region.layer + region.depth > layerCount + ) { throw new ArgumentOutOfRangeException(nameof(region), "Texture update region is outside its descriptor."); } if (descriptor.dimension != RenderTextureDimension.Texture3D && region.depth != 1) { throw new ArgumentException( "Two-dimensional and cubemap updates address exactly one layer or face.", - nameof(region)); + nameof(region) + ); } int rowPitch = checked(region.width * BytesPerPixel(descriptor.format)); int expectedSize = checked(rowPitch * region.height * region.depth); @@ -264,12 +274,15 @@ ReadOnlySpan data { throw new ArgumentException( $"Texture region update requires exactly {expectedSize} tightly packed bytes.", - nameof(data)); + nameof(data) + ); } bgfx.Memory* memory; fixed (byte* pointer = data) + { memory = bgfx.Raw.copy(pointer, checked((uint)data.Length)); + } switch (descriptor.dimension) { case RenderTextureDimension.Texture2D: @@ -282,7 +295,8 @@ ReadOnlySpan data checked((ushort)region.width), checked((ushort)region.height), memory, - checked((ushort)rowPitch)); + checked((ushort)rowPitch) + ); break; case RenderTextureDimension.Texture3D: BgfxNativeCalls.UpdateTexture3d( @@ -294,7 +308,8 @@ ReadOnlySpan data checked((ushort)region.width), checked((ushort)region.height), checked((ushort)region.depth), - memory); + memory + ); break; case RenderTextureDimension.Cube: BgfxNativeCalls.UpdateTextureCube( @@ -307,7 +322,8 @@ ReadOnlySpan data checked((ushort)region.width), checked((ushort)region.height), memory, - checked((ushort)rowPitch)); + checked((ushort)rowPitch) + ); break; default: throw new ArgumentOutOfRangeException(nameof(descriptor)); @@ -339,8 +355,8 @@ internal bgfx.TextureHandle ResolveTexture(RenderTextureHandle texture) { if (m_activeGraph is null || GetHandleIdentity(texture).generation != m_activeGraph.generation - || !m_graphTextures.TryGetValue(GetHandleIdentity(texture).index, out bgfx.TextureHandle nativeTexture)) - { + || !m_graphTextures.TryGetValue(GetHandleIdentity(texture).index, out bgfx.TextureHandle nativeTexture) + ) { throw new ArgumentException("Texture is not active in the current BGFX graph.", nameof(texture)); } @@ -361,88 +377,93 @@ private bgfx.TextureHandle CreateNativeTexture(RenderTextureDescriptor descripto { if (descriptor.width > capabilities.limits.maxTextureSize || descriptor.height > capabilities.limits.maxTextureSize - || descriptor.depth > capabilities.limits.maxTextureSize) - { - throw new NotSupportedException( - "The texture descriptor exceeds the active backend extent limit."); + || descriptor.depth > capabilities.limits.maxTextureSize + ) { + throw new NotSupportedException("The texture descriptor exceeds the active backend extent limit."); } if (!capabilities.SupportsSampled(descriptor.format, descriptor.dimension) - && (descriptor.usage & RenderTextureUsage.Sampled) != 0) - { + && (descriptor.usage & RenderTextureUsage.Sampled) != 0 + ) { throw new NotSupportedException( - $"The active graphics backend cannot sample {descriptor.dimension} textures in format '{descriptor.format}'."); + $"The active graphics backend cannot sample {descriptor.dimension} textures in format '{descriptor.format}'." + ); } if ((descriptor.usage - & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0 - && !capabilities.SupportsRenderTarget(descriptor.format)) - { + & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0 + && !capabilities.SupportsRenderTarget(descriptor.format) + ) { throw new NotSupportedException( - $"The active graphics backend cannot attach texture format '{descriptor.format}'."); + $"The active graphics backend cannot attach texture format '{descriptor.format}'." + ); } if ((descriptor.usage - & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0 + & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0 && descriptor.sampleCount > 1 - && !capabilities.SupportsMultisampleRenderTarget(descriptor.format)) - { + && !capabilities.SupportsMultisampleRenderTarget(descriptor.format) + ) { throw new NotSupportedException( - $"The active graphics backend cannot multisample texture format '{descriptor.format}'."); + $"The active graphics backend cannot multisample texture format '{descriptor.format}'." + ); } if ((descriptor.usage & RenderTextureUsage.Storage) != 0 && (!capabilities.Supports(GraphicsCapability.Compute) || !capabilities.Supports(GraphicsCapability.StorageTexture) || (!capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Read) - && !capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Write)))) - { + && !capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Write))) + ) { throw new NotSupportedException( - $"The active graphics backend cannot use texture format '{descriptor.format}' for storage access."); + $"The active graphics backend cannot use texture format '{descriptor.format}' for storage access." + ); } if ((descriptor.usage & RenderTextureUsage.Readback) != 0) { if (!capabilities.Supports(GraphicsCapability.TextureReadback)) - throw new NotSupportedException("The active graphics backend does not support texture readback."); - if (descriptor.sampleCount != 1 || - (descriptor.usage & (RenderTextureUsage.ColorAttachment | - RenderTextureUsage.DepthStencilAttachment | - RenderTextureUsage.Storage)) != 0) { + throw new NotSupportedException("The active graphics backend does not support texture readback."); + } + if (descriptor.sampleCount != 1 + || (descriptor.usage & (RenderTextureUsage.ColorAttachment + | RenderTextureUsage.DepthStencilAttachment + | RenderTextureUsage.Storage)) != 0 + ) { throw new ArgumentException( "Readback textures must be single-sampled transfer resources, not attachments or storage images.", - nameof(descriptor)); + nameof(descriptor) + ); } } if (descriptor.dimension == RenderTextureDimension.Texture2D && descriptor.arrayLayers > 1 - && !capabilities.Supports(GraphicsCapability.Texture2DArray)) - { + && !capabilities.Supports(GraphicsCapability.Texture2DArray) + ) { throw new NotSupportedException( - "The active graphics backend does not support two-dimensional texture arrays."); + "The active graphics backend does not support two-dimensional texture arrays." + ); } if (descriptor.dimension == RenderTextureDimension.Texture3D - && !capabilities.Supports(GraphicsCapability.Texture3D)) - { - throw new NotSupportedException( - "The active graphics backend does not support three-dimensional textures."); + && !capabilities.Supports(GraphicsCapability.Texture3D) + ) { + throw new NotSupportedException("The active graphics backend does not support three-dimensional textures."); } if (descriptor.dimension == RenderTextureDimension.Cube && descriptor.arrayLayers > 1 - && !capabilities.Supports(GraphicsCapability.TextureCubeArray)) - { - throw new NotSupportedException( - "The active graphics backend does not support cubemap texture arrays."); + && !capabilities.Supports(GraphicsCapability.TextureCubeArray) + ) { + throw new NotSupportedException("The active graphics backend does not support cubemap texture arrays."); } bgfx.TextureFlags flags = bgfx.TextureFlags.None; if ((descriptor.usage - & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0) - { + & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0 + ) { flags |= descriptor.sampleCount switch { 1 => bgfx.TextureFlags.Rt, @@ -484,7 +505,8 @@ private bgfx.TextureHandle CreateNativeTexture(RenderTextureDescriptor descripto BgfxCapabilityMapper.ToNativeFormat(descriptor.format), (ulong)flags, null, - 0), + 0 + ), RenderTextureDimension.Texture3D => BgfxNativeCalls.CreateTexture3d( checked((ushort)descriptor.width), checked((ushort)descriptor.height), @@ -493,7 +515,8 @@ private bgfx.TextureHandle CreateNativeTexture(RenderTextureDescriptor descripto BgfxCapabilityMapper.ToNativeFormat(descriptor.format), (ulong)flags, null, - 0), + 0 + ), RenderTextureDimension.Cube => BgfxNativeCalls.CreateTextureCube( checked((ushort)descriptor.width), descriptor.mipCount > 1 ? (byte)1 : (byte)0, @@ -501,22 +524,22 @@ private bgfx.TextureHandle CreateNativeTexture(RenderTextureDescriptor descripto BgfxCapabilityMapper.ToNativeFormat(descriptor.format), (ulong)flags, null, - 0), + 0 + ), _ => throw new ArgumentOutOfRangeException(nameof(descriptor)) }; } private static int BytesPerPixel(RenderTextureFormat format) => format switch - { - RenderTextureFormat.R8 => 1, - RenderTextureFormat.RG8 => 2, - RenderTextureFormat.RGBA8 or RenderTextureFormat.RGBA8Srgb - or RenderTextureFormat.RGB10A2 or RenderTextureFormat.RG11B10Float - or RenderTextureFormat.R32Float or RenderTextureFormat.Depth24Stencil8 - or RenderTextureFormat.Depth32Float => 4, - RenderTextureFormat.RGBA16Float => 8, - _ => throw new ArgumentOutOfRangeException(nameof(format)) - }; - + { + RenderTextureFormat.R8 => 1, + RenderTextureFormat.RG8 => 2, + RenderTextureFormat.RGBA8 or RenderTextureFormat.RGBA8Srgb + or RenderTextureFormat.RGB10A2 or RenderTextureFormat.RG11B10Float + or RenderTextureFormat.R32Float or RenderTextureFormat.Depth24Stencil8 + or RenderTextureFormat.Depth32Float => 4, + RenderTextureFormat.RGBA16Float => 8, + _ => throw new ArgumentOutOfRangeException(nameof(format)) + }; } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs index 3d5f4c9c1..c765d6aa6 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs @@ -1,10 +1,10 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -22,7 +22,9 @@ int physicalSlot { PooledTransientTexture pooled = m_transientTexturePool[index]; if (pooled.physicalSlot != physicalSlot || !pooled.descriptor.Equals(descriptor)) + { continue; + } m_transientTexturePool.RemoveAt(index); return pooled.handle; } @@ -31,17 +33,22 @@ int physicalSlot { PooledTransientTexture pooled = m_transientTexturePool[index]; if (!pooled.descriptor.Equals(descriptor)) + { continue; + } m_transientTexturePool.RemoveAt(index); return pooled.handle; } bgfx.TextureHandle texture = CreateNativeTexture(descriptor); if (!texture.Valid) + { throw new InvalidOperationException($"BGFX could not allocate transient texture '{name}'."); + } int textureNameLength = Encoding.UTF8.GetByteCount(name); Span textureNameBytes = textureNameLength < 256 - ? stackalloc byte[256] : new byte[checked(textureNameLength + 1)]; + ? stackalloc byte[256] + : new byte[checked(textureNameLength + 1)]; Encoding.UTF8.GetBytes(name, textureNameBytes); textureNameBytes[textureNameLength] = 0; fixed (byte* textureNamePointer = textureNameBytes) @@ -56,15 +63,15 @@ private void ReturnTransientGraphResources() { foreach ((int slot, bgfx.TextureHandle texture) in m_transientTextureSlots) { - m_transientTexturePool.Add(new PooledTransientTexture( - m_transientTextureSlotDescriptors[slot], - texture, - m_submissionSequence, - slot)); + m_transientTexturePool.Add( + new PooledTransientTexture(m_transientTextureSlotDescriptors[slot], texture, m_submissionSequence, slot) + ); } foreach ((int slot, BgfxBufferResource buffer) in m_transientBufferSlots) + { m_transientBufferPool.Add(new PooledTransientBuffer(buffer, m_submissionSequence, slot)); + } m_transientTextureSlots.Clear(); m_transientTextureSlotDescriptors.Clear(); @@ -77,7 +84,9 @@ private void TrimTransientResourceCaches() { CachedGraphFrameBuffer cached = m_graphFrameBufferCache[index]; if (!CacheEntryExpired(cached.lastUsedSubmission)) + { continue; + } EnqueueDestroy(DeferredResource.ForFrameBuffer(cached.handle)); m_graphFrameBufferCache.RemoveAt(index); } @@ -86,7 +95,9 @@ private void TrimTransientResourceCaches() { PooledTransientTexture pooled = m_transientTexturePool[index]; if (!CacheEntryExpired(pooled.lastUsedSubmission)) + { continue; + } RemoveCachedFrameBuffersReferencing(pooled.handle.idx); EnqueueDestroy(DeferredResource.ForTexture(pooled.handle)); m_transientTexturePool.RemoveAt(index); @@ -96,13 +107,16 @@ private void TrimTransientResourceCaches() { PooledTransientBuffer pooled = m_transientBufferPool[index]; if (!CacheEntryExpired(pooled.lastUsedSubmission)) + { continue; + } EnqueueDestroy(DeferredResource.ForBuffer(pooled.resource)); m_transientBufferPool.RemoveAt(index); } } - private bool CacheEntryExpired(ulong lastUsedSubmission) => m_submissionSequence - lastUsedSubmission > C_TRANSIENT_CACHE_RETENTION_FRAMES; + private bool CacheEntryExpired(ulong lastUsedSubmission) + => m_submissionSequence - lastUsedSubmission > C_TRANSIENT_CACHE_RETENTION_FRAMES; private readonly record struct PooledTransientTexture( RenderTextureDescriptor descriptor, @@ -116,5 +130,4 @@ private readonly record struct PooledTransientBuffer( ulong lastUsedSubmission, int physicalSlot ); - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs index 511ae2e90..fb6d4942f 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs @@ -1,9 +1,9 @@ -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading; +using Inno.Adapter.Platform; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -73,31 +73,38 @@ public sealed unsafe partial class BgfxDevice : RenderDevice, IRenderDevice, IRe public BgfxDevice(BgfxDeviceOptions options) { ArgumentNullException.ThrowIfNull(options); - PlatformNativeHandles nativeHandles = options.window is null ? default - : options.window is INativeWindowSurface surface ? surface.nativeHandles - : throw new NotSupportedException("BGFX requires a window that implements INativeWindowSurface."); + PlatformNativeHandles nativeHandles = options.window is null + ? default + : options.window is INativeWindowSurface surface + ? surface.nativeHandles + : throw new NotSupportedException("BGFX requires a window that implements INativeWindowSurface."); m_surfaceIntegration = options.surfaceIntegration; - BgfxSurfaceDescriptor primarySurface = options.window is null ? default - : BgfxSurfaceBinding.Validate((m_surfaceIntegration - ?? throw new ArgumentException("A windowed BGFX device requires an explicit surface integration.", nameof(options))) - .Resolve(nativeHandles, BgfxSurfaceRole.Primary)); + BgfxSurfaceDescriptor primarySurface = options.window is null + ? default + : BgfxSurfaceBinding.Validate( + (m_surfaceIntegration + ?? throw new ArgumentException("A windowed BGFX device requires an explicit surface integration.", nameof(options))) + .Resolve(nativeHandles, BgfxSurfaceRole.Primary) + ); m_apiThreadId = Environment.CurrentManagedThreadId; m_deferredDestroyFrames = options.deferredDestroyFrames; m_hasPrimarySurface = options.window is not null; int pixelWidth = options.backbufferWidth; int pixelHeight = options.backbufferHeight; primaryPresentationSize = m_hasPrimarySurface && pixelWidth > 0 && pixelHeight > 0 - ? new RenderPresentationSize(pixelWidth, pixelHeight) : null; + ? new RenderPresentationSize(pixelWidth, pixelHeight) + : null; m_backbufferWidth = Math.Max(1, pixelWidth); m_backbufferHeight = Math.Max(1, pixelHeight); m_resetFlags = (uint)( (options.verticalSync ? bgfx.ResetFlags.Vsync : bgfx.ResetFlags.None) | (options.sRgbBackbuffer && (!m_hasPrimarySurface || primarySurface.supportsSrgbReset) - ? bgfx.ResetFlags.SrgbBackbuffer - : bgfx.ResetFlags.None)); + ? bgfx.ResetFlags.SrgbBackbuffer + : bgfx.ResetFlags.None)); bgfx.RendererType? preferredRenderer = options.preferredBackend is GraphicsApi backend - ? BgfxCapabilityMapper.ToNativeRenderer(backend) : null; + ? BgfxCapabilityMapper.ToNativeRenderer(backend) + : null; m_processLease = BgfxProcessDeviceLease.Acquire(options.forceSingleThreaded); bool nativeInitialized = false; try @@ -111,10 +118,14 @@ public BgfxDevice(BgfxDeviceOptions options) bgfx.Init init; bgfx.Raw.init_ctor(&init); if (preferredRenderer.HasValue) + { init.type = preferredRenderer.Value; + } if (options.window is not null) + { BgfxSurfaceBinding.Apply(ref init, primarySurface); + } init.resolution.width = checked((uint)m_backbufferWidth); init.resolution.height = checked((uint)m_backbufferHeight); init.resolution.reset = m_resetFlags; @@ -135,7 +146,9 @@ public BgfxDevice(BgfxDeviceOptions options) catch { if (nativeInitialized) + { bgfx.shutdown(); + } m_processLease.Dispose(); throw; } @@ -159,8 +172,9 @@ public BgfxDevice(BgfxDeviceOptions options) /// /// Gets whether both the selected host and active renderer permit additional window surfaces. /// - public bool supportsAdditionalSurfaces => m_surfaceIntegration?.supportsAdditionalSurfaces == true - && capabilities.Supports(GraphicsCapability.SwapChain); + public bool supportsAdditionalSurfaces + => m_surfaceIntegration?.supportsAdditionalSurfaces == true + && capabilities.Supports(GraphicsCapability.SwapChain); /// /// Gets the generation identity that owns this value. @@ -186,8 +200,12 @@ public RenderDeviceAllocationCounters? allocationCounters { EnsureApiThread(); ObjectDisposedException.ThrowIf(m_disposed, this); - return new RenderDeviceAllocationCounters(generation, m_transientTextureAllocationCount, - m_transientBufferAllocationCount, m_transientFrameBufferAllocationCount); + return new RenderDeviceAllocationCounters( + generation, + m_transientTextureAllocationCount, + m_transientBufferAllocationCount, + m_transientFrameBufferAllocationCount + ); } } @@ -244,5 +262,4 @@ private static uint PackColor(RenderClearColor color) byte a = (byte)(Math.Clamp(color.a, 0f, 1f) * 255f); return ((uint)r << 24) | ((uint)g << 16) | ((uint)b << 8) | a; } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDeviceOptions.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDeviceOptions.cs index 8f2622ada..ee78b7bce 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDeviceOptions.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDeviceOptions.cs @@ -36,8 +36,8 @@ public int backbufferWidth { get => window?.pixelWidth ?? m_backbufferWidth; set => m_backbufferWidth = value > 0 - ? value - : throw new ArgumentOutOfRangeException(nameof(value)); + ? value + : throw new ArgumentOutOfRangeException(nameof(value)); } /// @@ -47,8 +47,8 @@ public int backbufferHeight { get => window?.pixelHeight ?? m_backbufferHeight; set => m_backbufferHeight = value > 0 - ? value - : throw new ArgumentOutOfRangeException(nameof(value)); + ? value + : throw new ArgumentOutOfRangeException(nameof(value)); } /// @@ -77,7 +77,7 @@ public int deferredDestroyFrames { get => m_deferredDestroyFrames; set => m_deferredDestroyFrames = value >= 1 - ? value - : throw new ArgumentOutOfRangeException(nameof(value)); + ? value + : throw new ArgumentOutOfRangeException(nameof(value)); } } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs index 68b37a220..d2a4a210e 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs @@ -60,7 +60,8 @@ ushort flags return result; } - internal static bgfx.ShaderHandle CreateShader(bgfx.Memory* memory) { + internal static bgfx.ShaderHandle CreateShader(bgfx.Memory* memory) + { bgfx.ShaderHandle result = default; bgfx.Raw.create_shader(memory, &result); return result; @@ -131,7 +132,8 @@ ushort flags return result; } - internal static bgfx.VertexLayoutHandle CreateVertexLayout(bgfx.VertexLayout* layout) { + internal static bgfx.VertexLayoutHandle CreateVertexLayout(bgfx.VertexLayout* layout) + { bgfx.VertexLayoutHandle result = default; bgfx.Raw.create_vertex_layout(layout, &result); return result; @@ -169,7 +171,8 @@ ushort depth srcZ, width, height, - depth); + depth + ); } internal static void EncoderDispatch( @@ -274,7 +277,8 @@ bgfx.VertexLayoutHandle layoutHandle &handle, startVertex, numVertices, - &layoutHandle); + &layoutHandle + ); } internal static void EncoderSetImage( @@ -358,7 +362,8 @@ bgfx.VertexLayoutHandle layoutHandle &handle, startVertex, numVertices, - &layoutHandle); + &layoutHandle + ); } internal static void EncoderSubmit( @@ -497,5 +502,4 @@ ushort pitch ) { bgfx.Raw.update_texture_cube(&handle, layer, side, mip, x, y, width, height, memory, pitch); } - } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxProcessDeviceLease.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxProcessDeviceLease.cs index 39bc1a651..6bab6fb3b 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxProcessDeviceLease.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxProcessDeviceLease.cs @@ -24,11 +24,14 @@ internal static BgfxProcessDeviceLease Acquire(bool singleThreaded) lock (S_SYNC) { if (s_active is not null) + { throw new InvalidOperationException("Only one BGFX device may own the native process runtime."); + } if (s_singleThreadedRuntimeConsumed) { throw new InvalidOperationException( - "BGFX cannot be initialized again after this process entered single-threaded mode."); + "BGFX cannot be initialized again after this process entered single-threaded mode." + ); } var lease = new BgfxProcessDeviceLease(singleThreaded); @@ -42,9 +45,13 @@ internal void MarkSingleThreadedEntered() lock (S_SYNC) { if (!ReferenceEquals(s_active, this) || m_disposed) + { throw new InvalidOperationException("The BGFX process lease is not active."); + } if (m_singleThreaded) + { s_singleThreadedRuntimeConsumed = true; + } } } @@ -56,9 +63,13 @@ public void Dispose() lock (S_SYNC) { if (m_disposed) + { return; + } if (!ReferenceEquals(s_active, this)) + { throw new InvalidOperationException("BGFX process leases must be released by their owner."); + } m_disposed = true; s_active = null; } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs index 2b6dad31e..867d98688 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs @@ -19,7 +19,8 @@ public sealed class BgfxRenderingBackendProvider : RenderingBackendProvider /// /// The integration is null. /// - public BgfxRenderingBackendProvider(IBgfxSurfaceIntegration surfaceIntegration) : base(RenderingBackendId.bgfx) + public BgfxRenderingBackendProvider(IBgfxSurfaceIntegration surfaceIntegration) + : base(RenderingBackendId.bgfx) { ArgumentNullException.ThrowIfNull(surfaceIntegration); m_surfaceIntegration = surfaceIntegration; diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxResources.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxResources.cs index 406ff73bd..b456c9c6e 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxResources.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxResources.cs @@ -34,18 +34,22 @@ ushort nativeIndex /// Gets the backend-neutral descriptor used to validate and recreate this resource. /// public RenderBufferDescriptor descriptor { get; } + /// /// Gets the optional vertex layout required by this resource or pipeline. /// public RenderVertexLayout? vertexLayout { get; } + /// /// Gets the element width used by this index buffer. /// public RenderIndexFormat indexFormat { get; } + /// /// Gets the operation kind that determines how this value is interpreted. /// public BgfxBufferKind kind { get; } + /// /// Gets the BGFX dynamic-buffer index used by deferred destruction. /// @@ -70,8 +74,7 @@ public static BgfxBufferResource FromVertex( RenderBufferDescriptor descriptor, RenderVertexLayout? layout, bgfx.VertexBufferHandle handle - ) - => new(descriptor, layout, RenderIndexFormat.UInt32, BgfxBufferKind.Vertex, handle.idx); + ) => new(descriptor, layout, RenderIndexFormat.UInt32, BgfxBufferKind.Vertex, handle.idx); /// /// Creates the target representation from the supplied index value. @@ -92,8 +95,7 @@ public static BgfxBufferResource FromIndex( RenderBufferDescriptor descriptor, RenderIndexFormat format, bgfx.IndexBufferHandle handle - ) - => new(descriptor, null, format, BgfxBufferKind.Index, handle.idx); + ) => new(descriptor, null, format, BgfxBufferKind.Index, handle.idx); /// /// Creates the target representation from the supplied dynamic vertex value. @@ -114,8 +116,7 @@ public static BgfxBufferResource FromDynamicVertex( RenderBufferDescriptor descriptor, RenderVertexLayout? layout, bgfx.DynamicVertexBufferHandle handle - ) - => new(descriptor, layout, RenderIndexFormat.UInt32, BgfxBufferKind.DynamicVertex, handle.idx); + ) => new(descriptor, layout, RenderIndexFormat.UInt32, BgfxBufferKind.DynamicVertex, handle.idx); /// /// Creates the target representation from the supplied dynamic index value. @@ -136,8 +137,7 @@ public static BgfxBufferResource FromDynamicIndex( RenderBufferDescriptor descriptor, RenderIndexFormat format, bgfx.DynamicIndexBufferHandle handle - ) - => new(descriptor, null, format, BgfxBufferKind.DynamicIndex, handle.idx); + ) => new(descriptor, null, format, BgfxBufferKind.DynamicIndex, handle.idx); /// /// Creates the target representation from the supplied indirect value. @@ -154,8 +154,7 @@ bgfx.DynamicIndexBufferHandle handle public static BgfxBufferResource FromIndirect( RenderBufferDescriptor descriptor, bgfx.IndirectBufferHandle handle - ) - => new(descriptor, null, RenderIndexFormat.UInt32, BgfxBufferKind.Indirect, handle.idx); + ) => new(descriptor, null, RenderIndexFormat.UInt32, BgfxBufferKind.Indirect, handle.idx); } internal sealed class BgfxShaderBindingResource @@ -181,6 +180,7 @@ bgfx.UniformHandle uniform /// Gets the backend-neutral descriptor used to validate and recreate this resource. /// public RenderShaderBindingDescriptor descriptor { get; } + /// /// Gets the BGFX uniform handle backing this shader binding. /// @@ -230,22 +230,27 @@ bool compute /// Gets the linked BGFX shader program owned by this pipeline resource. /// public bgfx.ProgramHandle program { get; } + /// /// Gets the immutable lookup of stable binding IDs to BGFX uniform resources. /// public IReadOnlyDictionary bindings { get; } + /// /// Gets the optional vertex layout required by this resource or pipeline. /// public RenderVertexLayout? vertexLayout { get; } + /// /// Gets the BGFX vertex-layout handle owned by this pipeline resource. /// public bgfx.VertexLayoutHandle vertexLayoutHandle { get; } + /// /// Gets the optional rasterization state encoded by this pipeline. /// public RenderRasterState? rasterState { get; } + /// /// Gets whether the caller-visible condition represented by this property is satisfied. /// diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceBinding.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceBinding.cs index 088076ca9..42f0935be 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceBinding.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceBinding.cs @@ -8,7 +8,9 @@ internal static unsafe class BgfxSurfaceBinding internal static BgfxSurfaceDescriptor Validate(BgfxSurfaceDescriptor descriptor) { if (descriptor.windowHandle == 0) + { throw new ArgumentException("The surface integration returned an invalid window descriptor."); + } return descriptor; } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceDescriptor.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceDescriptor.cs index 9f765203a..76f30fc09 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceDescriptor.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/BgfxSurfaceDescriptor.cs @@ -32,7 +32,9 @@ public BgfxSurfaceDescriptor( bool supportsSrgbReset ) { if (windowHandle == 0) + { throw new ArgumentException("A live borrowed window value is required.", nameof(windowHandle)); + } this.windowHandle = windowHandle; this.displayHandle = displayHandle; this.supportsSrgbReset = supportsSrgbReset; diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs index 9b7d104d9..0be42fcb4 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs @@ -41,8 +41,12 @@ IToolchainWorkspaceProvider workspaces ArgumentNullException.ThrowIfNull(workspaces); m_hostPath = hostPath; m_workspaces = workspaces; - capabilities = new ManagedDeploymentCapabilities(runtimeIdentifiers, - dynamicCode: true, aheadOfTime: false, nativeStaticLinking: false); + capabilities = new ManagedDeploymentCapabilities( + runtimeIdentifiers, + dynamicCode: true, + aheadOfTime: false, + nativeStaticLinking: false + ); } /// @@ -55,7 +59,14 @@ IToolchainWorkspaceProvider workspaces public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default - ) => DotNetDeploymentPublisher.PublishAsync(id, capabilities, m_hostPath, m_workspaces, request, + ) => DotNetDeploymentPublisher.PublishAsync( + id, + capabilities, + m_hostPath, + m_workspaces, + request, ["SelfContained=true", "PublishSingleFile=true", "PublishTrimmed=true", "TrimMode=full", - "IncludeNativeLibrariesForSelfExtract=true"], cancellationToken); + "IncludeNativeLibrariesForSelfExtract=true"], + cancellationToken + ); } diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs index 0d648da59..3fc36c14e 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs @@ -41,8 +41,12 @@ IToolchainWorkspaceProvider workspaces ArgumentNullException.ThrowIfNull(workspaces); m_hostPath = hostPath; m_workspaces = workspaces; - capabilities = new ManagedDeploymentCapabilities(runtimeIdentifiers, - dynamicCode: false, aheadOfTime: true, nativeStaticLinking: true); + capabilities = new ManagedDeploymentCapabilities( + runtimeIdentifiers, + dynamicCode: false, + aheadOfTime: true, + nativeStaticLinking: true + ); } /// @@ -55,6 +59,13 @@ IToolchainWorkspaceProvider workspaces public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default - ) => DotNetDeploymentPublisher.PublishAsync(id, capabilities, m_hostPath, m_workspaces, request, - ["SelfContained=true", "PublishAot=true", "PublishTrimmed=true", "TrimMode=full"], cancellationToken); + ) => DotNetDeploymentPublisher.PublishAsync( + id, + capabilities, + m_hostPath, + m_workspaces, + request, + ["SelfContained=true", "PublishAot=true", "PublishTrimmed=true", "TrimMode=full"], + cancellationToken + ); } diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetDeploymentPublisher.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetDeploymentPublisher.cs index 70dae8148..79a370341 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetDeploymentPublisher.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetDeploymentPublisher.cs @@ -20,10 +20,17 @@ CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(request); if (!capabilities.runtimeIdentifiers.Contains(request.runtimeIdentifier, StringComparer.Ordinal)) + { throw new InvalidOperationException($"Managed deployment '{id}' does not support '{request.runtimeIdentifier}'."); - DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(hostPath, - request.projectPath, cancellationToken).ConfigureAwait(false); - return await DotNetPublishExecutor.PublishAsync(new DotNetPublishRequest(sdk, - id, request, properties, workspaces), cancellationToken).ConfigureAwait(false); + } + DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync( + hostPath, + request.projectPath, + cancellationToken + ).ConfigureAwait(false); + return await DotNetPublishExecutor.PublishAsync( + new DotNetPublishRequest(sdk, id, request, properties, workspaces), + cancellationToken + ).ConfigureAwait(false); } } diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs index c2ce40e67..738d2912f 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs @@ -18,28 +18,54 @@ CancellationToken cancellationToken ) { ManagedDeploymentRequest publication = request.publication; if (!Directory.Exists(publication.codeInputDirectory)) + { throw new DirectoryNotFoundException("The frozen managed code input directory is absent."); + } if (Directory.Exists(publication.outputDirectory) - && Directory.EnumerateFileSystemEntries(publication.outputDirectory).Any()) + && Directory.EnumerateFileSystemEntries(publication.outputDirectory).Any() + ) { throw new InvalidOperationException("Managed publication requires an empty staging directory."); + } Directory.CreateDirectory(publication.logDirectory); - await File.WriteAllTextAsync(Path.Combine(publication.logDirectory, "managed-sdk.txt"), - request.sdk.sdkIdentity, cancellationToken).ConfigureAwait(false); - await File.WriteAllTextAsync(Path.Combine(publication.logDirectory, "managed-cli.txt"), - request.sdk.cliPath, cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(publication.logDirectory, "managed-sdk.txt"), + request.sdk.sdkIdentity, + cancellationToken + ).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(publication.logDirectory, "managed-cli.txt"), + request.sdk.cliPath, + cancellationToken + ).ConfigureAwait(false); string physicalProjectDirectory = Path.GetDirectoryName(publication.projectPath)!; using ToolchainWorkingDirectory workspace = await request.workspaces.OpenAsync( - physicalProjectDirectory, cancellationToken).ConfigureAwait(false); - await File.WriteAllLinesAsync(Path.Combine(publication.logDirectory, "managed-working-directory.txt"), - [physicalProjectDirectory, workspace.toolPath], cancellationToken).ConfigureAwait(false); + physicalProjectDirectory, + cancellationToken + ).ConfigureAwait(false); + await File.WriteAllLinesAsync( + Path.Combine(publication.logDirectory, "managed-working-directory.txt"), + [physicalProjectDirectory, workspace.toolPath], + cancellationToken + ).ConfigureAwait(false); var arguments = new List { - request.sdk.cliPath, "publish", Path.Combine(workspace.toolPath, Path.GetFileName(publication.projectPath)), - "--disable-build-servers", "-m:1", "-nodeReuse:false", - "--configuration", "Release", "--runtime", publication.runtimeIdentifier, - "--output", publication.outputDirectory, "--nologo", - "-p:DebugType=None", "-p:DebugSymbols=false", - "-p:TreatWarningsAsErrors=true", "-p:TrimmerSingleWarn=false", + request.sdk.cliPath, + "publish", + Path.Combine(workspace.toolPath, Path.GetFileName(publication.projectPath)), + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--configuration", + "Release", + "--runtime", + publication.runtimeIdentifier, + "--output", + publication.outputDirectory, + "--nologo", + "-p:DebugType=None", + "-p:DebugSymbols=false", + "-p:TreatWarningsAsErrors=true", + "-p:TrimmerSingleWarn=false", "-p:InnoGameManagedRoot=" + publication.codeInputDirectory }; arguments.AddRange(request.properties.Select(static property => "-p:" + property)); @@ -47,19 +73,32 @@ await File.WriteAllLinesAsync(Path.Combine(publication.logDirectory, "managed-wo await using var error = new TailLogWriter(Path.Combine(publication.logDirectory, "managed-error.log")); try { - await ToolchainEnvironment.RunAsync(request.sdk.hostPath, arguments, - workspace.toolPath, cancellationToken, - DotNetSdkEnvironment.Create(request.sdk.hostPath), output, error).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + request.sdk.hostPath, + arguments, + workspace.toolPath, + cancellationToken, + DotNetSdkEnvironment.Create(request.sdk.hostPath), + output, + error + ).ConfigureAwait(false); } catch (InvalidOperationException exception) { - throw new InvalidOperationException($"Managed deployment '{request.deployment}' failed." - + Environment.NewLine + output.tail + Environment.NewLine + error.tail, exception); + throw new InvalidOperationException( + $"Managed deployment '{request.deployment}' failed." + + Environment.NewLine + output.tail + Environment.NewLine + error.tail, + exception + ); } if (!Directory.Exists(publication.outputDirectory)) + { throw new InvalidOperationException("The managed publisher produced no output directory."); + } string[] files = Directory.EnumerateFiles(publication.outputDirectory, "*", SearchOption.AllDirectories) - .Select(file => Path.GetRelativePath(publication.outputDirectory, file)).Order(StringComparer.Ordinal).ToArray(); + .Select(file => Path.GetRelativePath(publication.outputDirectory, file)) + .Order(StringComparer.Ordinal) + .ToArray(); return new ManagedDeploymentResult(request.deployment, publication.outputDirectory, request.sdk.sdkIdentity, files); } @@ -80,10 +119,14 @@ public override async Task WriteLineAsync(string? value) { await m_log.WriteLineAsync(value).ConfigureAwait(false); if (value is null) + { return; + } m_tail.Enqueue(value.Length <= 4096 ? value : value[..4096]); if (m_tail.Count > 100) + { m_tail.Dequeue(); + } } /// diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs index 6c2ea9f80..838462fa5 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs @@ -47,8 +47,12 @@ bool aheadOfTime m_hostPath = hostPath; m_workspaces = workspaces; m_aheadOfTime = aheadOfTime; - capabilities = new ManagedDeploymentCapabilities(runtimeIdentifiers, - dynamicCode: false, aheadOfTime: aheadOfTime, nativeStaticLinking: true); + capabilities = new ManagedDeploymentCapabilities( + runtimeIdentifiers, + dynamicCode: false, + aheadOfTime: aheadOfTime, + nativeStaticLinking: true + ); } /// @@ -61,7 +65,18 @@ bool aheadOfTime public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default - ) => DotNetDeploymentPublisher.PublishAsync(id, capabilities, m_hostPath, m_workspaces, request, - ["WasmBuildNative=true", "PublishTrimmed=true", "TrimMode=full", - "RunAOTCompilation=" + (m_aheadOfTime ? "true" : "false")], cancellationToken); + ) => DotNetDeploymentPublisher.PublishAsync( + id, + capabilities, + m_hostPath, + m_workspaces, + request, + [ + "WasmBuildNative=true", + "PublishTrimmed=true", + "TrimMode=full", + "RunAOTCompilation=" + (m_aheadOfTime ? "true" : "false") + ], + cancellationToken + ); } diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs index 46fc8986a..1eca3583d 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs @@ -1,11 +1,10 @@ using System; using System.Collections.Generic; -using System.Reflection; using System.Linq; +using System.Reflection; using System.Runtime.ExceptionServices; -using Inno.Extensibility.Types; - using Inno.Extensibility.Catalogs; +using Inno.Extensibility.Types; namespace Inno.Adapter.Modules.DotNet; @@ -27,15 +26,25 @@ public TypeCatalogMetadata GetMetadata(Type type) ArgumentNullException.ThrowIfNull(type); var ancestors = new List(); for (Type? current = type.BaseType; current is not null && current != typeof(object); current = current.BaseType) + { ancestors.Add(current); - return new TypeCatalogMetadata(type, ancestors, type.GetInterfaces(), + } + return new TypeCatalogMetadata( + type, + ancestors, + type.GetInterfaces(), type.GetCustomAttributes(inherit: false).OfType().ToArray(), type.GetCustomAttributes(inherit: true).OfType().ToArray(), type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) - .Where(static method => !method.IsGenericMethod && method.GetParameters().Length == 0 && - method.GetBaseDefinition().DeclaringType != method.DeclaringType) - .Select(static method => (method.Name, method.GetBaseDefinition().DeclaringType!)).ToArray()); + .Where(static method => ( + !method.IsGenericMethod && method.GetParameters().Length == 0 + && method.GetBaseDefinition().DeclaringType != method.DeclaringType + )) + .Select(static method => (method.Name, method.GetBaseDefinition().DeclaringType!)) + .ToArray() + ); } + /// public Type? ConstructGenericType( Type definition, @@ -44,10 +53,14 @@ IReadOnlyList arguments ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(arguments); if (!definition.IsGenericTypeDefinition) + { throw new ArgumentException("The declaration must be a generic type definition.", nameof(definition)); - if (arguments.Count != definition.GetGenericArguments().Length || - arguments.Any(static argument => argument is null || argument.ContainsGenericParameters)) + } + if (arguments.Count != definition.GetGenericArguments().Length + || arguments.Any(static argument => argument is null || argument.ContainsGenericParameters) + ) { throw new ArgumentException("The complete closed type argument set is required.", nameof(arguments)); + } try { return definition.MakeGenericType(arguments.ToArray()); @@ -62,9 +75,13 @@ IReadOnlyList arguments public bool CanCreateInstance(Type type) { ArgumentNullException.ThrowIfNull(type); - return !type.IsAbstract && !type.ContainsGenericParameters && - (type.IsValueType || type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - binder: null, Type.EmptyTypes, modifiers: null) is not null); + return !type.IsAbstract && !type.ContainsGenericParameters + && (type.IsValueType || type.GetConstructor( + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + binder: null, + Type.EmptyTypes, + modifiers: null + ) is not null); } /// @@ -74,7 +91,7 @@ public object CreateInstance(Type type) try { return Activator.CreateInstance(type, nonPublic: true) - ?? throw new InvalidOperationException($"Type '{type}' did not produce an instance."); + ?? throw new InvalidOperationException($"Type '{type}' did not produce an instance."); } catch (TargetInvocationException exception) when (exception.InnerException is not null) { diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs index 1fd54dcef..2b6e4d771 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs @@ -36,12 +36,15 @@ public DotNetAssemblyCatalogSource(params Assembly[] roots) { ArgumentNullException.ThrowIfNull(roots); if (roots.Length == 0) + { throw new ArgumentException("At least one composition root is required.", nameof(roots)); + } m_roots = roots.Distinct().ToArray(); m_hostLoadContext = AssemblyLoadContext.GetLoadContext(m_roots[0])!; - if (m_roots.Any(assembly => - AssemblyLoadContext.GetLoadContext(assembly) != m_hostLoadContext)) + if (m_roots.Any(assembly => AssemblyLoadContext.GetLoadContext(assembly) != m_hostLoadContext)) + { throw new ArgumentException("Composition roots must share one load context.", nameof(roots)); + } PreloadInnoHostDependencies(); AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoaded; } @@ -54,9 +57,12 @@ public IReadOnlyList GetAssemblies() { ObjectDisposedException.ThrowIf(m_disposed, this); lock (m_ownedAssemblies) - return m_ownedAssemblies.Where(static assembly => - assembly.TryGetInnoAssemblyClassification(out AssemblyDomain domain, out _) && - domain == AssemblyDomain.InnoInternal).ToArray(); + { + return m_ownedAssemblies.Where(static assembly => ( + assembly.TryGetInnoAssemblyClassification(out AssemblyDomain domain, out _) + && domain == AssemblyDomain.InnoInternal + )).ToArray(); + } } /// @@ -64,8 +70,12 @@ public IReadOnlyList GetSharedAssemblies() { ObjectDisposedException.ThrowIf(m_disposed, this); lock (m_ownedAssemblies) - return m_ownedAssemblies.Concat(AppDomain.CurrentDomain.GetAssemblies() - .Where(IsTrustedFrameworkAssembly)).Distinct().ToArray(); + { + return m_ownedAssemblies.Concat( + AppDomain.CurrentDomain.GetAssemblies() + .Where(IsTrustedFrameworkAssembly) + ).Distinct().ToArray(); + } } /// @@ -78,7 +88,9 @@ public IReadOnlyList GetSharedAssemblies() public void Dispose() { if (m_disposed) + { return; + } AppDomain.CurrentDomain.AssemblyLoad -= OnAssemblyLoaded; changed = null; m_ownedAssemblies.Clear(); @@ -92,12 +104,16 @@ AssemblyLoadEventArgs args // Discovery remains the explicit composition closure. New assemblies become visible only // when referenced by a root; arbitrary assemblies in the process never enter the catalog. if (AssemblyLoadContext.GetLoadContext(args.LoadedAssembly) != m_hostLoadContext) + { return; + } int previousCount; lock (m_ownedAssemblies) { if (m_disposed || m_discovering) + { return; + } previousCount = m_ownedAssemblies.Count; m_discovering = true; try @@ -109,7 +125,9 @@ AssemblyLoadEventArgs args m_discovering = false; } if (m_ownedAssemblies.Count == previousCount) + { return; + } } changed?.Invoke(); } @@ -118,7 +136,9 @@ private void PreloadInnoHostDependencies() { Assembly[] roots = m_roots; if (roots.Length == 0) + { return; + } var visited = new HashSet(StringComparer.OrdinalIgnoreCase); var pending = new Queue(); @@ -126,21 +146,28 @@ private void PreloadInnoHostDependencies() { string rootName = root.GetName().Name ?? string.Empty; if (!string.IsNullOrEmpty(rootName)) + { visited.Add(rootName); + } m_ownedAssemblies.Add(root); pending.Enqueue(root); } foreach (KeyValuePair dependency in HostDependencyManifest.GetInnoRuntimeAssemblies(roots) - .OrderBy(static dependency => dependency.Key, StringComparer.OrdinalIgnoreCase)) + .OrderBy(static dependency => dependency.Key, StringComparer.OrdinalIgnoreCase) + ) { TryEnqueueHostAssembly(new AssemblyName(dependency.Key), visited, pending, dependency.Value); + } while (pending.Count > 0) { Assembly assembly = pending.Dequeue(); foreach (AssemblyName reference in assembly.GetReferencedAssemblies()) + { TryEnqueueHostAssembly(reference, visited, pending); + } } } + private void TryEnqueueHostAssembly( AssemblyName assemblyName, ISet visited, @@ -149,32 +176,40 @@ private void TryEnqueueHostAssembly( ) { string name = assemblyName.Name ?? string.Empty; if (!name.StartsWith("Inno.", StringComparison.Ordinal) || !visited.Add(name)) + { return; + } Assembly assembly = manifestPath is null - ? m_hostLoadContext.LoadFromAssemblyName(assemblyName) - : m_hostLoadContext.LoadFromAssemblyPath(manifestPath); + ? m_hostLoadContext.LoadFromAssemblyName(assemblyName) + : m_hostLoadContext.LoadFromAssemblyPath(manifestPath); lock (m_ownedAssemblies) + { m_ownedAssemblies.Add(assembly); + } pending.Enqueue(assembly); } + private static HashSet GetTrustedPlatformAssemblyNames() { string paths = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") as string ?? string.Empty; return paths.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries) - .Select(Path.GetFileNameWithoutExtension).OfType() + .Select(Path.GetFileNameWithoutExtension) + .OfType() .ToHashSet(StringComparer.OrdinalIgnoreCase); } private static bool IsTrustedFrameworkAssembly(Assembly assembly) { if (AssemblyLoadContext.GetLoadContext(assembly) != AssemblyLoadContext.Default) + { return false; + } AssemblyName identity = assembly.GetName(); string name = identity.Name ?? string.Empty; if (!name.StartsWith("System.", StringComparison.Ordinal) && !name.StartsWith("Microsoft.Win32.", StringComparison.Ordinal) - && name is not ("System" or "netstandard" or "mscorlib")) - { + && name is not ("System" or "netstandard" or "mscorlib") + ) { return false; } string token = Convert.ToHexString(identity.GetPublicKeyToken() ?? []); diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs index 8e721ac88..f47817714 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs @@ -75,11 +75,15 @@ public IReadOnlyList GetAssemblyNames() foreach (string path in new[] { mainAssemblyPath }.Concat(preloadAssemblyPaths)) { if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) + { throw new FileNotFoundException("A module assembly does not exist.", path); + } string name = AssemblyName.GetAssemblyName(path).Name - ?? throw new InvalidDataException($"Assembly '{path}' has no simple name."); + ?? throw new InvalidDataException($"Assembly '{path}' has no simple name."); if (!names.Add(name)) + { throw new InvalidDataException($"Module contains duplicate assembly name '{name}'."); + } } return names.OrderBy(static name => name, StringComparer.Ordinal).ToArray(); } @@ -95,14 +99,17 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrWhiteSpace(artifactRootDirectory); if (!Path.IsPathFullyQualified(artifactRootDirectory)) + { throw new ArgumentException("Dynamic module storage requires an absolute adapter-owned root.", nameof(artifactRootDirectory)); + } DotNetModuleSource request = this; _ = GetAssemblyNames(); string generationDirectory = Path.Combine( artifactRootDirectory, SanitizePathSegment(request.moduleName), - context.generation.ToString(System.Globalization.CultureInfo.InvariantCulture) + "-" + Guid.NewGuid().ToString("N")); + context.generation.ToString(System.Globalization.CultureInfo.InvariantCulture) + "-" + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(generationDirectory); string[] sourcePaths = new[] { request.mainAssemblyPath } @@ -115,9 +122,11 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) foreach (string sourcePath in sourcePaths) { string assemblyName = AssemblyName.GetAssemblyName(sourcePath).Name - ?? throw new InvalidOperationException($"Assembly '{sourcePath}' has no simple name."); + ?? throw new InvalidOperationException($"Assembly '{sourcePath}' has no simple name."); if (shadowPathsByName.ContainsKey(assemblyName)) + { throw new InvalidOperationException($"Module contains duplicate assembly name '{assemblyName}'."); + } string shadowPath = CopyAssemblyArtifacts(sourcePath, generationDirectory, assemblyName); shadowPathsByName.Add(assemblyName, shadowPath); explicitShadowPaths.Add(shadowPath); @@ -133,13 +142,15 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) IReadOnlyDictionary sharedAssemblies = BuildSharedAssemblies( request, context, - shadowPathsByName.Keys); + shadowPathsByName.Keys + ); var loadContext = new ModuleLoadContext( $"{request.moduleName}#{context.generation}", mainShadowPath, request.collectible, sharedAssemblies, - shadowPathsByName.Values); + shadowPathsByName.Values + ); try { @@ -151,10 +162,12 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) { string name = AssemblyName.GetAssemblyName(shadowPath).Name ?? string.Empty; if (assemblies.Any(assembly => string.Equals( - assembly.GetName().Name, - name, - StringComparison.OrdinalIgnoreCase))) + assembly.GetName().Name, + name, + StringComparison.OrdinalIgnoreCase + ))) { continue; + } assemblies.Add(loadContext.LoadFromAssemblyPath(shadowPath)); } @@ -164,11 +177,12 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) { string simpleName = assembly.GetName().Name ?? string.Empty; AssemblyScope assemblyScope = request.assemblyScopes.GetValueOrDefault(simpleName, request.scope); - if (request.domain == AssemblyDomain.InnoScripting && - (!HasRequestedClassification(assembly, assemblyScope))) - { + if (request.domain == AssemblyDomain.InnoScripting + && (!HasRequestedClassification(assembly, assemblyScope)) + ) { throw new InvalidDataException( - $"Script assembly '{simpleName}' does not declare its requested domain and scope metadata."); + $"Script assembly '{simpleName}' does not declare its requested domain and scope metadata." + ); } loadedScopes.Add(assembly, assemblyScope); } @@ -179,12 +193,21 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) loadedScopes, sharedAssemblies, context.upstreamModules, - context.plannedAssemblies); + context.plannedAssemblies + ); return new ModuleCatalogContribution( - moduleName, domain, scope, loadedAssemblies, loadedScopes, - new DotNetModuleLifetime(loadContext, generationDirectory, - $"{moduleName} ({domain}/{scope}, generation {context.generation})")); + moduleName, + domain, + scope, + loadedAssemblies, + loadedScopes, + new DotNetModuleLifetime( + loadContext, + generationDirectory, + $"{moduleName} ({domain}/{scope}, generation {context.generation})" + ) + ); } catch { @@ -196,8 +219,8 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) } throw; } - } + private static IReadOnlyDictionary BuildSharedAssemblies( DotNetModuleSource request, ModuleSourceContext context, @@ -212,7 +235,8 @@ IEnumerable ownedNames if (result.ContainsKey(ownedName)) { throw new InvalidDataException( - $"Module assembly '{ownedName}' duplicates an assembly already shared by the host context."); + $"Module assembly '{ownedName}' duplicates an assembly already shared by the host context." + ); } } @@ -220,18 +244,21 @@ IEnumerable ownedNames { foreach (Assembly assembly in upstream.assemblies) { - if (request.scope == AssemblyScope.Runtime && - upstream.assemblyScopes[assembly] == AssemblyScope.Editor) - { + if (request.scope == AssemblyScope.Runtime + && upstream.assemblyScopes[assembly] == AssemblyScope.Editor + ) { continue; } string name = assembly.GetName().Name ?? string.Empty; if (owned.Contains(name) || !result.TryAdd(name, assembly)) + { throw new InvalidDataException($"Reload graph contains duplicate managed assembly name '{name}'."); + } } } return result; } + private static void ValidateLoadedModule( DotNetModuleSource request, ModuleSourceContext context, @@ -243,12 +270,15 @@ IReadOnlyDictionary plannedAssemblies ) { var ownByName = assemblies.ToDictionary( static assembly => assembly.GetName().Name ?? string.Empty, - StringComparer.OrdinalIgnoreCase); + StringComparer.OrdinalIgnoreCase + ); ValidateOwnedDependencyGraph(ownByName); var forbiddenDownstreamNames = context.activeModules - .Where(module => request.domain == AssemblyDomain.InnoPlugin + .Where(module => ( + request.domain == AssemblyDomain.InnoPlugin ? module.domain == AssemblyDomain.InnoScripting - : request.scope == AssemblyScope.Runtime && module.scope == AssemblyScope.Editor) + : request.scope == AssemblyScope.Runtime && module.scope == AssemblyScope.Editor + )) .SelectMany(static module => module.assemblies) .Select(static assembly => assembly.GetName().Name ?? string.Empty) .ToHashSet(StringComparer.OrdinalIgnoreCase); @@ -257,7 +287,8 @@ IReadOnlyDictionary plannedAssemblies .ToDictionary( static pair => pair.assembly.GetName().Name ?? string.Empty, static pair => pair, - StringComparer.OrdinalIgnoreCase); + StringComparer.OrdinalIgnoreCase + ); foreach (Assembly assembly in assemblies) { @@ -267,90 +298,104 @@ IReadOnlyDictionary plannedAssemblies string name = reference.Name ?? string.Empty; if (ownByName.TryGetValue(name, out Assembly? ownedDependency)) { - if (sourceScope == AssemblyScope.Runtime && - assemblyScopes[ownedDependency] == AssemblyScope.Editor) - { + if (sourceScope == AssemblyScope.Runtime + && assemblyScopes[ownedDependency] == AssemblyScope.Editor + ) { throw new InvalidDataException( - $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'."); + $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'." + ); } continue; } if (forbiddenDownstreamNames.Contains(name)) { throw new InvalidDataException( - $"Assembly '{assembly.GetName().Name}' has a forbidden downstream reference to '{name}'."); + $"Assembly '{assembly.GetName().Name}' has a forbidden downstream reference to '{name}'." + ); } if (upstreamByName.TryGetValue(name, out var upstream)) { - if (sourceScope == AssemblyScope.Runtime && - upstream.module.assemblyScopes[upstream.assembly] == AssemblyScope.Editor) - { + if (sourceScope == AssemblyScope.Runtime + && upstream.module.assemblyScopes[upstream.assembly] == AssemblyScope.Editor + ) { throw new InvalidDataException( - $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'."); + $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'." + ); } continue; } if (plannedAssemblies.TryGetValue(name, out ModuleAssemblyDescriptor planned)) { - if (request.domain == AssemblyDomain.InnoPlugin && - planned.domain == AssemblyDomain.InnoScripting) - { + if (request.domain == AssemblyDomain.InnoPlugin + && planned.domain == AssemblyDomain.InnoScripting + ) { throw new InvalidDataException( - $"Plugin assembly '{assembly.GetName().Name}' cannot reference project script assembly '{name}'."); + $"Plugin assembly '{assembly.GetName().Name}' cannot reference project script assembly '{name}'." + ); } if (sourceScope == AssemblyScope.Runtime && planned.scope == AssemblyScope.Editor) { throw new InvalidDataException( - $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'."); + $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor assembly '{name}'." + ); } throw new InvalidDataException( - $"Assembly '{assembly.GetName().Name}' has an unavailable downstream reference to '{name}'."); + $"Assembly '{assembly.GetName().Name}' has an unavailable downstream reference to '{name}'." + ); } if (context.host.IsFrameworkReference(name) || (sharedAssemblies.TryGetValue(name, out Assembly? platformAssembly) - && context.host.IsFrameworkAssembly(platformAssembly))) + && context.host.IsFrameworkAssembly(platformAssembly)) + ) { continue; + } if (sharedAssemblies.TryGetValue(name, out Assembly? sharedAssembly)) { if (sharedAssembly.GetInnoAssemblyDomain() != AssemblyDomain.InnoInternal) { throw new InvalidDataException( - $"Assembly '{assembly.GetName().Name}' can only share BCL or InnoInternal contracts, not '{name}'."); + $"Assembly '{assembly.GetName().Name}' can only share BCL or InnoInternal contracts, not '{name}'." + ); } if (sourceScope == AssemblyScope.Runtime && sharedAssembly.GetInnoAssemblyScope() == AssemblyScope.Editor) { throw new InvalidDataException( - $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor contract '{name}'."); + $"Runtime assembly '{assembly.GetName().Name}' cannot reference editor contract '{name}'." + ); } continue; } throw new InvalidDataException( - $"Assembly '{assembly.GetName().Name}' references unavailable assembly '{name}'. " + - "Include the dependency in its module or load an InnoInternal contract in the host."); + $"Assembly '{assembly.GetName().Name}' references unavailable assembly '{name}'. " + + "Include the dependency in its module or load an InnoInternal contract in the host." + ); } } } + private static void ValidateOwnedDependencyGraph(IReadOnlyDictionary assemblies) { - var graph = new DependencyGraph( - StringComparer.OrdinalIgnoreCase, - StringComparer.Ordinal); + var graph = new DependencyGraph(StringComparer.OrdinalIgnoreCase, StringComparer.Ordinal); foreach (string name in assemblies.Keys) + { graph.AddNode(name); + } foreach ((string name, Assembly assembly) in assemblies) { foreach (AssemblyName reference in assembly.GetReferencedAssemblies()) { if (reference.Name is string dependency && assemblies.ContainsKey(dependency)) + { graph.AddDependency(name, dependency); + } } } if (graph.TryFindCycle(out IReadOnlyList cycle)) { - throw new InvalidDataException( - $"Module assembly reference cycle: {string.Join(" -> ", cycle)}."); + throw new InvalidDataException($"Module assembly reference cycle: {string.Join(" -> ", cycle)}."); } } + private static string CopyAssemblyArtifacts( string sourcePath, string destinationDirectory, @@ -360,12 +405,17 @@ string assemblyName File.Copy(sourcePath, destinationPath, overwrite: true); string sourcePdb = Path.ChangeExtension(sourcePath, ".pdb"); if (File.Exists(sourcePdb)) + { File.Copy(sourcePdb, Path.Combine(destinationDirectory, Path.GetFileName(sourcePdb)), overwrite: true); + } string sourceDeps = Path.ChangeExtension(sourcePath, ".deps.json"); if (File.Exists(sourceDeps)) + { File.Copy(sourceDeps, Path.Combine(destinationDirectory, Path.GetFileName(sourceDeps)), overwrite: true); + } return destinationPath; } + private static string SanitizePathSegment(string value) { char[] invalid = Path.GetInvalidFileNameChars(); diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/HostDependencyManifest.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/HostDependencyManifest.cs index 33918ecd0..372a9b9f1 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/HostDependencyManifest.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/HostDependencyManifest.cs @@ -16,7 +16,9 @@ internal static IReadOnlyDictionary GetInnoRuntimeAssemblies(IRe var names = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string dependencyFile in GetDependencyFiles(rootAssemblies)) + { ReadRuntimeAssemblyNames(dependencyFile, names); + } return names; } @@ -29,10 +31,14 @@ private static IReadOnlyList GetDependencyFiles(IReadOnlyList { string location = rootAssembly.Location; if (string.IsNullOrWhiteSpace(location)) + { continue; + } string dependencyFile = Path.ChangeExtension(location, ".deps.json"); if (File.Exists(dependencyFile)) + { paths.Add(Path.GetFullPath(dependencyFile)); + } } return paths.ToArray(); } @@ -46,24 +52,30 @@ IDictionary names using FileStream stream = File.OpenRead(dependencyFile); using JsonDocument document = JsonDocument.Parse(stream); if (!document.RootElement.TryGetProperty("targets", out JsonElement targets)) + { return; + } foreach (JsonProperty target in targets.EnumerateObject()) { foreach (JsonProperty library in target.Value.EnumerateObject()) { if (!library.Value.TryGetProperty("runtime", out JsonElement runtime)) + { continue; + } foreach (JsonProperty asset in runtime.EnumerateObject()) { string fileName = Path.GetFileName(asset.Name); - if (!fileName.StartsWith("Inno.", StringComparison.Ordinal) || - !fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) - { + if (!fileName.StartsWith("Inno.", StringComparison.Ordinal) + || !fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + ) { continue; } - names.TryAdd(Path.GetFileNameWithoutExtension(fileName), - Path.Combine(Path.GetDirectoryName(dependencyFile)!, fileName)); + names.TryAdd( + Path.GetFileNameWithoutExtension(fileName), + Path.Combine(Path.GetDirectoryName(dependencyFile)!, fileName) + ); } } } diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs index ec5e12f52..5249e8ccc 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs @@ -20,16 +20,18 @@ internal ModuleLoadContext( bool collectible, IReadOnlyDictionary sharedAssemblies, IEnumerable moduleAssemblyPaths - ) - : base(name, collectible) + ) : base(name, collectible) { m_resolver = new AssemblyDependencyResolver(mainAssemblyPath); m_sharedAssemblies = sharedAssemblies; m_moduleAssemblyPaths = moduleAssemblyPaths.ToDictionary( - static path => AssemblyName.GetAssemblyName(path).Name - ?? throw new InvalidOperationException($"Assembly '{path}' has no simple name."), + static path => ( + AssemblyName.GetAssemblyName(path).Name + ?? throw new InvalidOperationException($"Assembly '{path}' has no simple name.") + ), static path => path, - StringComparer.OrdinalIgnoreCase); + StringComparer.OrdinalIgnoreCase + ); Unloading += ReleaseSharedAssemblies; } @@ -51,7 +53,9 @@ IEnumerable moduleAssemblyPaths return sharedAssembly; } if (m_moduleAssemblyPaths.TryGetValue(simpleName, out string? modulePath)) + { return LoadFromAssemblyPath(modulePath); + } return null; } @@ -73,15 +77,16 @@ AssemblyName shared string sharedCulture = shared.CultureName ?? string.Empty; byte[] requestedToken = requested.GetPublicKeyToken() ?? []; byte[] sharedToken = shared.GetPublicKeyToken() ?? []; - if (versionMatches && - string.Equals(requestedCulture, sharedCulture, StringComparison.OrdinalIgnoreCase) && - requestedToken.SequenceEqual(sharedToken)) - { + if (versionMatches + && string.Equals(requestedCulture, sharedCulture, StringComparison.OrdinalIgnoreCase) + && requestedToken.SequenceEqual(sharedToken) + ) { return; } throw new FileLoadException( - $"Module dependency '{requested.FullName}' is incompatible with shared engine assembly '{shared.FullName}'."); + $"Module dependency '{requested.FullName}' is incompatible with shared engine assembly '{shared.FullName}'." + ); } /// diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs index 97ba213ab..34f71a562 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs @@ -15,7 +15,6 @@ internal enum AssemblyUnloadStatus /// At least one runtime reference still keeps the load context alive. /// Pending, - /// /// The load context is no longer reachable, or the module was not collectible. /// @@ -69,37 +68,47 @@ public AssemblyUnloadStatus status get { if (m_children is not null) + { return m_children.All(static child => child.isCompleted) - ? AssemblyUnloadStatus.Completed - : AssemblyUnloadStatus.Pending; + ? AssemblyUnloadStatus.Completed + : AssemblyUnloadStatus.Pending; + } if (m_loadContext is not null && m_loadContext.IsAlive) + { return AssemblyUnloadStatus.Pending; + } return TryCleanupShadowDirectory() - ? AssemblyUnloadStatus.Completed - : AssemblyUnloadStatus.Pending; + ? AssemblyUnloadStatus.Completed + : AssemblyUnloadStatus.Pending; } } internal bool TryCleanupShadowDirectory() { if (m_children is not null) + { return m_children.All(static child => child.TryCleanupShadowDirectory()); + } if (m_loadContext is not null && m_loadContext.IsAlive) + { return false; + } lock (m_sync) { if (m_isShadowDirectoryCleaned) + { return true; + } try { if (!string.IsNullOrWhiteSpace(m_shadowDirectory) && Directory.Exists(m_shadowDirectory)) { Directory.Delete(m_shadowDirectory, recursive: true); string? moduleDirectory = Path.GetDirectoryName(m_shadowDirectory); - if (!string.IsNullOrWhiteSpace(moduleDirectory) && - Directory.Exists(moduleDirectory) && - !Directory.EnumerateFileSystemEntries(moduleDirectory).Any()) - { + if (!string.IsNullOrWhiteSpace(moduleDirectory) + && Directory.Exists(moduleDirectory) + && !Directory.EnumerateFileSystemEntries(moduleDirectory).Any() + ) { Directory.Delete(moduleDirectory); } } diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs index 7e10c3d4e..f11a863d6 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs @@ -26,7 +26,9 @@ string description public IAssemblyUnloadProbe BeginRetirement() { if (m_retirement is not null) + { return m_retirement; + } var reference = new WeakReference(m_loadContext!, trackResurrection: false); m_loadContext!.Unload(); m_loadContext = null; diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs index 7e0f882d7..afa397cd3 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Inno.Core.Serialization; namespace Inno.Adapter.Serialization.DotNet; @@ -38,9 +37,9 @@ out Type elementType } Type candidateElementType = candidate.GetGenericArguments()[0]; - if (candidateElementType.IsGenericType && - candidateElementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) - { + if (candidateElementType.IsGenericType + && candidateElementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>) + ) { continue; } @@ -186,7 +185,8 @@ internal static object BuildSequence( ConstructorInfo? constructor = FindSingleArgumentConstructor( targetType, listType, - typeof(IEnumerable<>).MakeGenericType(elementType)); + typeof(IEnumerable<>).MakeGenericType(elementType) + ); if (constructor is not null) { return constructor.Invoke([list]); @@ -201,7 +201,7 @@ internal static object BuildSequence( if (!targetType.IsAbstract && ResolveSequenceAddMethod(targetType, elementType) is MethodInfo addMethod) { object instance = Activator.CreateInstance(targetType, nonPublic: true) - ?? throw new InvalidOperationException($"Cannot create sequence type '{targetType.FullName}'."); + ?? throw new InvalidOperationException($"Cannot create sequence type '{targetType.FullName}'."); for (int i = 0; i < values.Count; i++) { addMethod.Invoke(instance, [values[i]]); @@ -211,7 +211,8 @@ internal static object BuildSequence( } throw new InvalidOperationException( - $"Cannot construct sequence type '{targetType.FullName}'. Provide ctor(IEnumerable), static CreateRange/Create, or Add(T)."); + $"Cannot construct sequence type '{targetType.FullName}'. Provide ctor(IEnumerable), static CreateRange/Create, or Add(T)." + ); } internal static object BuildMap( @@ -233,7 +234,8 @@ internal static object BuildMap( ConstructorInfo? constructor = FindSingleArgumentConstructor( targetType, pairListType, - typeof(IEnumerable<>).MakeGenericType(pairType)); + typeof(IEnumerable<>).MakeGenericType(pairType) + ); if (constructor is not null) { return constructor.Invoke([pairList]); @@ -248,7 +250,7 @@ internal static object BuildMap( if (!targetType.IsAbstract && ResolveMapAddMethod(targetType, keyType, valueType) is MethodInfo addMethod) { object instance = Activator.CreateInstance(targetType, nonPublic: true) - ?? throw new InvalidOperationException($"Cannot create map type '{targetType.FullName}'."); + ?? throw new InvalidOperationException($"Cannot create map type '{targetType.FullName}'."); for (int i = 0; i < entries.Count; i++) { KeyValuePair entry = entries[i]; @@ -259,7 +261,8 @@ internal static object BuildMap( } throw new InvalidOperationException( - $"Cannot construct map type '{targetType.FullName}'. Provide ctor(IEnumerable>), static CreateRange/Create, or Add(K,V)."); + $"Cannot construct map type '{targetType.FullName}'. Provide ctor(IEnumerable>), static CreateRange/Create, or Add(K,V)." + ); } private static object BuildTypedList( @@ -284,9 +287,7 @@ private static object BuildTypedDictionary( for (int i = 0; i < entries.Count; i++) { KeyValuePair entry = entries[i]; - dictionary.Add( - entry.Key ?? throw new InvalidOperationException("Map keys cannot be null."), - entry.Value); + dictionary.Add(entry.Key ?? throw new InvalidOperationException("Map keys cannot be null."), entry.Value); } return dictionary; @@ -312,7 +313,8 @@ private static object BuildTypedKeyValueList( params Type[] candidateArgumentTypes ) { ConstructorInfo[] constructors = targetType.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); for (int i = 0; i < constructors.Length; i++) { ParameterInfo[] parameters = constructors[i].GetParameters(); @@ -339,11 +341,12 @@ Type argumentType ) { return targetType .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) - .FirstOrDefault(method => - (method.Name == "CreateRange" || method.Name == "Create") && - targetType.IsAssignableFrom(method.ReturnType) && - method.GetParameters().Length == 1 && - method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType)); + .FirstOrDefault(method => ( + (method.Name == "CreateRange" || method.Name == "Create") + && targetType.IsAssignableFrom(method.ReturnType) + && method.GetParameters().Length == 1 + && method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType) + )); } private static MethodInfo? ResolveSequenceAddMethod( @@ -355,7 +358,8 @@ Type elementType BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, binder: null, types: [elementType], - modifiers: null); + modifiers: null + ); if (direct is not null) { return direct; @@ -363,8 +367,8 @@ Type elementType Type collectionInterface = typeof(ICollection<>).MakeGenericType(elementType); return collectionInterface.IsAssignableFrom(targetType) - ? collectionInterface.GetMethod("Add", [elementType]) - : null; + ? collectionInterface.GetMethod("Add", [elementType]) + : null; } private static MethodInfo? ResolveMapAddMethod( @@ -377,7 +381,8 @@ Type valueType BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, binder: null, types: [keyType, valueType], - modifiers: null); + modifiers: null + ); if (direct is not null) { return direct; @@ -385,8 +390,8 @@ Type valueType Type dictionaryInterface = typeof(IDictionary<,>).MakeGenericType(keyType, valueType); return dictionaryInterface.IsAssignableFrom(targetType) - ? dictionaryInterface.GetMethod("Add", [keyType, valueType]) - : null; + ? dictionaryInterface.GetMethod("Add", [keyType, valueType]) + : null; } private static IEnumerable EnumerateSelfAndInterfaces(Type type) diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs index c691ff3a3..329de03be 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; - using Inno.Core.Serialization; namespace Inno.Adapter.Serialization.DotNet; @@ -26,13 +25,18 @@ internal static SerializationMemberMetadata[] GetSerializableMembers(Type type) { MethodInfo[] hooks = GetRestoreHooks(type); if (hooks.Length == 0) + { return null; + } return ( value, context - ) => { + ) => + { foreach (MethodInfo hook in hooks) + { hook.Invoke(value, hook.GetParameters().Length == 0 ? null : [context]); + } }; } @@ -40,7 +44,9 @@ private static SerializationMemberMetadata[] BuildSerializableMembers(Type runti { var hierarchy = new List(8); for (Type? current = runtimeType; current is not null && current != typeof(object); current = current.BaseType) + { hierarchy.Add(current); + } hierarchy.Reverse(); var members = new List(32); @@ -59,19 +65,23 @@ private static SerializationMemberMetadata[] BuildSerializableMembers(Type runti SerializablePropertyAttribute? attribute = declaredMember.GetCustomAttribute(inherit: true); if (attribute is null) + { continue; + } SerializationMemberMetadata member = declaredMember switch { FieldInfo field => CreateFieldMember(runtimeType, field, attribute.propertyVisibility), PropertyInfo property => CreatePropertyMember(runtimeType, property, attribute.propertyVisibility), _ => throw new InvalidOperationException( - $"Serializable member '{runtimeType.FullName}.{declaredMember.Name}' must be a field or property.") + $"Serializable member '{runtimeType.FullName}.{declaredMember.Name}' must be a field or property." + ) }; if (!names.Add(member.name)) { throw new InvalidOperationException( - $"Serializable type '{runtimeType.FullName}' declares duplicate serialized key '{member.name}' in its inheritance hierarchy."); + $"Serializable type '{runtimeType.FullName}' declares duplicate serialized key '{member.name}' in its inheritance hierarchy." + ); } members.Add(member); @@ -84,7 +94,7 @@ private static SerializationMemberMetadata[] BuildSerializableMembers(Type runti private static int GetSerializableOrder(MemberInfo member) { return member.GetCustomAttribute(inherit: true)?.order - ?? int.MaxValue; + ?? int.MaxValue; } private static SerializationMemberMetadata CreateFieldMember( @@ -97,7 +107,8 @@ PropertyVisibility visibility if (requiresWrite && field.IsInitOnly) { throw new InvalidOperationException( - $"Serializable field '{runtimeType.FullName}.{field.Name}' must be writable for visibility '{visibility}'."); + $"Serializable field '{runtimeType.FullName}.{field.Name}' must be writable for visibility '{visibility}'." + ); } return new SerializationMemberMetadata( @@ -105,7 +116,8 @@ PropertyVisibility visibility field.FieldType, visibility, requiresRead ? field.GetValue : null, - requiresWrite ? field.SetValue : null); + requiresWrite ? field.SetValue : null + ); } private static SerializationMemberMetadata CreatePropertyMember( @@ -114,7 +126,9 @@ private static SerializationMemberMetadata CreatePropertyMember( PropertyVisibility visibility ) { if (property.GetIndexParameters().Length != 0) + { throw new InvalidOperationException($"Serializable property '{runtimeType.FullName}.{property.Name}' cannot be an indexer."); + } bool requiresRead = RequiresRead(visibility); bool requiresWrite = RequiresWrite(visibility); @@ -123,12 +137,14 @@ PropertyVisibility visibility if (requiresRead && getter is null) { throw new InvalidOperationException( - $"Serializable property '{runtimeType.FullName}.{property.Name}' must define a getter for visibility '{visibility}'."); + $"Serializable property '{runtimeType.FullName}.{property.Name}' must define a getter for visibility '{visibility}'." + ); } if (requiresWrite && setter is null) { throw new InvalidOperationException( - $"Serializable property '{runtimeType.FullName}.{property.Name}' must define a setter for visibility '{visibility}'."); + $"Serializable property '{runtimeType.FullName}.{property.Name}' must define a setter for visibility '{visibility}'." + ); } return new SerializationMemberMetadata( @@ -136,21 +152,25 @@ PropertyVisibility visibility property.PropertyType, visibility, getter is null ? null : property.GetValue, - setter is null ? null : property.SetValue); + setter is null ? null : property.SetValue + ); } private static MethodInfo[] GetRestoreHooks(Type runtimeType) { return S_RESTORE_HOOKS.GetValue( runtimeType, - static value => new RestoreHooksBox(BuildRestoreHooks(value))).hooks; + static value => new RestoreHooksBox(BuildRestoreHooks(value)) + ).hooks; } private static MethodInfo[] BuildRestoreHooks(Type runtimeType) { var hierarchy = new List(8); for (Type? current = runtimeType; current is not null && current != typeof(object); current = current.BaseType) + { hierarchy.Add(current); + } hierarchy.Reverse(); var hooks = new List(hierarchy.Count); @@ -163,20 +183,24 @@ private static MethodInfo[] BuildRestoreHooks(Type runtimeType) if (declaredHooks.Length > 1) { throw new InvalidOperationException( - $"Serializable type '{hierarchy[i].FullName}' declares more than one OnSerializableRestored method."); + $"Serializable type '{hierarchy[i].FullName}' declares more than one OnSerializableRestored method." + ); } if (declaredHooks.Length == 0) + { continue; + } MethodInfo hook = declaredHooks[0]; ParameterInfo[] parameters = hook.GetParameters(); - bool validParameters = parameters.Length == 0 || - parameters.Length == 1 && parameters[0].ParameterType == typeof(SerializationContext); + bool validParameters = parameters.Length == 0 + || parameters.Length == 1 && parameters[0].ParameterType == typeof(SerializationContext); if (hook.IsStatic || hook.IsVirtual || hook.ReturnType != typeof(void) || !validParameters) { throw new InvalidOperationException( - $"Restore callback '{hierarchy[i].FullName}.{hook.Name}' must be a non-static, non-virtual void method " + - "with either no parameters or one SerializationContext parameter."); + $"Restore callback '{hierarchy[i].FullName}.{hook.Name}' must be a non-static, non-virtual void method " + + "with either no parameters or one SerializationContext parameter." + ); } hooks.Add(hook); @@ -192,5 +216,6 @@ private static bool RequiresWrite(PropertyVisibility visibility) => (visibility & (PropertyVisibility.Deserialize | PropertyVisibility.RuntimeSet)) != 0; private sealed record MembersBox(SerializationMemberMetadata[] members); + private sealed record RestoreHooksBox(MethodInfo[] hooks); } diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs index ebcb8b18e..7d80ec97c 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; - using Inno.Core.Serialization; namespace Inno.Adapter.Serialization.DotNet; @@ -25,15 +24,22 @@ internal static bool HasPureFieldAccess( SerializationTypeMetadata metadata ) { if (!type.IsValueType || metadata.requiresConverter || metadata.collection is not null || metadata.members.Count == 0) + { return false; + } foreach (SerializationMemberMetadata member in metadata.members) { if ((member.visibility & PropertyVisibility.Serialize) == 0) continue; FieldInfo? field = type.GetField(member.name, C_MEMBERS); - if (field is null || field.FieldType != member.type || - !(field.FieldType.IsPrimitive && field.FieldType != typeof(IntPtr) && field.FieldType != typeof(UIntPtr) && field.FieldType != typeof(char) - || field.FieldType == typeof(decimal) || field.FieldType == typeof(System.Guid) || field.FieldType == typeof(string))) + if (field is null || field.FieldType != member.type + || !(field.FieldType.IsPrimitive + && field.FieldType != typeof(IntPtr) + && field.FieldType != typeof(UIntPtr) + && field.FieldType != typeof(char) + || field.FieldType == typeof(decimal) || field.FieldType == typeof(System.Guid) || field.FieldType == typeof(string)) + ) { return false; + } } return true; } @@ -56,11 +62,14 @@ private static SerializationMemberMetadata[] BuildMembers(Type structType) _ => null }; if (member is null) + { continue; + } if (!names.Add(member.name)) { throw new InvalidOperationException( - $"Struct '{structType.FullName}' declares duplicate serialized key '{member.name}'."); + $"Struct '{structType.FullName}' declares duplicate serialized key '{member.name}'." + ); } members.Add(member); } @@ -68,7 +77,8 @@ private static SerializationMemberMetadata[] BuildMembers(Type structType) if (members.Count == 0) { throw new InvalidOperationException( - $"Struct '{structType.FullName}' has no public writable data members. Register a SerializationConverter<{structType.Name}>."); + $"Struct '{structType.FullName}' has no public writable data members. Register a SerializationConverter<{structType.Name}>." + ); } return [.. members]; @@ -77,7 +87,7 @@ private static SerializationMemberMetadata[] BuildMembers(Type structType) private static int GetSerializableOrder(MemberInfo member) { return member.GetCustomAttribute(inherit: true)?.order - ?? int.MaxValue; + ?? int.MaxValue; } private static SerializationMemberMetadata? TryCreateField( @@ -85,20 +95,25 @@ private static int GetSerializableOrder(MemberInfo member) FieldInfo field ) { if (field.IsStatic) + { return null; + } SerializablePropertyAttribute? attribute = field.GetCustomAttribute(inherit: true); bool isDefaultMember = field.IsPublic && !field.IsInitOnly; if (attribute is null && !isDefaultMember) + { return null; + } PropertyVisibility visibility = attribute?.propertyVisibility ?? PropertyVisibility.Show; bool requiresWrite = (visibility & (PropertyVisibility.Deserialize | PropertyVisibility.RuntimeSet)) != 0; if (requiresWrite && field.IsInitOnly) { throw new InvalidOperationException( - $"Struct field '{structType.FullName}.{field.Name}' must be writable for visibility '{visibility}'."); + $"Struct field '{structType.FullName}.{field.Name}' must be writable for visibility '{visibility}'." + ); } return new SerializationMemberMetadata( @@ -106,7 +121,8 @@ FieldInfo field field.FieldType, visibility, field.GetValue, - field.IsInitOnly ? null : field.SetValue); + field.IsInitOnly ? null : field.SetValue + ); } private static SerializationMemberMetadata? TryCreateProperty( @@ -114,7 +130,9 @@ FieldInfo field PropertyInfo property ) { if (property.GetIndexParameters().Length != 0) + { return null; + } SerializablePropertyAttribute? attribute = property.GetCustomAttribute(inherit: true); @@ -122,7 +140,9 @@ PropertyInfo property MethodInfo? setter = property.GetSetMethod(nonPublic: true); bool isDefaultMember = getter?.IsPublic == true && setter?.IsPublic == true; if (attribute is null && !isDefaultMember) + { return null; + } PropertyVisibility visibility = attribute?.propertyVisibility ?? PropertyVisibility.Show; bool requiresRead = (visibility & (PropertyVisibility.Serialize | PropertyVisibility.RuntimeGet)) != 0; @@ -130,12 +150,14 @@ PropertyInfo property if (requiresRead && getter is null) { throw new InvalidOperationException( - $"Struct property '{structType.FullName}.{property.Name}' must define a getter for visibility '{visibility}'."); + $"Struct property '{structType.FullName}.{property.Name}' must define a getter for visibility '{visibility}'." + ); } if (requiresWrite && setter is null) { throw new InvalidOperationException( - $"Struct property '{structType.FullName}.{property.Name}' must define a setter for visibility '{visibility}'."); + $"Struct property '{structType.FullName}.{property.Name}' must define a setter for visibility '{visibility}'." + ); } return new SerializationMemberMetadata( @@ -143,7 +165,8 @@ PropertyInfo property property.PropertyType, visibility, getter is null ? null : property.GetValue, - setter is null ? null : property.SetValue); + setter is null ? null : property.SetValue + ); } private sealed record MembersBox(SerializationMemberMetadata[] members); diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs index b9223c45c..ad6924fc8 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs @@ -26,38 +26,66 @@ private static SerializationTypeMetadata BuildMetadata(Type type) SerializationCollectionMetadata? collection = null; if (ReflectionCollectionMetadata.TryGetMapTypes(type, out Type keyType, out Type valueType)) { - collection = new SerializationCollectionMetadata(valueType, keyType, null, + collection = new SerializationCollectionMetadata( + valueType, + keyType, + null, entries => ReflectionCollectionMetadata.BuildMap(type, keyType, valueType, entries), - value => ReflectionCollectionMetadata.TryEnumerateMap(value, type, out List> entries) - ? entries : throw new InvalidOperationException($"Map '{type}' cannot be enumerated.")); + value => ( + ReflectionCollectionMetadata.TryEnumerateMap(value, type, out List> entries) + ? entries + : throw new InvalidOperationException($"Map '{type}' cannot be enumerated.") + ) + ); } else if (ReflectionCollectionMetadata.TryGetSequenceElementType(type, out Type elementType)) { - collection = new SerializationCollectionMetadata(elementType, null, - values => ReflectionCollectionMetadata.BuildSequence(type, elementType, values), null, null); + collection = new SerializationCollectionMetadata( + elementType, + null, + values => ReflectionCollectionMetadata.BuildSequence(type, elementType, values), + null, + null + ); } IReadOnlyList members = typeof(ISerializable).IsAssignableFrom(type) - ? ReflectionObjectMetadata.GetSerializableMembers(type) - : type.IsValueType && !type.IsPrimitive && !type.IsEnum && type != typeof(Guid) - && type != typeof(decimal) ? ReflectionStructMetadata.GetMembers(type) : []; + ? ReflectionObjectMetadata.GetSerializableMembers(type) + : type.IsValueType && !type.IsPrimitive && !type.IsEnum && type != typeof(Guid) + && type != typeof(decimal) ? ReflectionStructMetadata.GetMembers(type) : []; Func? factory = !type.IsAbstract && !type.IsInterface && !type.ContainsGenericParameters - && (type.IsValueType || type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - binder: null, Type.EmptyTypes, modifiers: null) is not null) ? () => CreateInstance(type) : null; - var metadata = new SerializationTypeMetadata(type, members, factory, + && (type.IsValueType || type.GetConstructor( + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + binder: null, + Type.EmptyTypes, + modifiers: null + ) is not null) ? () => CreateInstance(type) : null; + var metadata = new SerializationTypeMetadata( + type, + members, + factory, typeof(ISerializable).IsAssignableFrom(type) ? ReflectionObjectMetadata.CreateRestoreHandler(type) : null, - collection, type.IsDefined(typeof(RequiresSerializationConverterAttribute), inherit: true)); + collection, + type.IsDefined(typeof(RequiresSerializationConverterAttribute), inherit: true) + ); if (ReflectionStructMetadata.HasPureFieldAccess(type, metadata)) + { metadata = metadata.WithPureFieldAccess(); + } SerializationRevisionAttribute? revision = type.GetCustomAttribute(inherit: false); if (revision is null) + { return metadata; + } foreach (SerializationMemberMetadata member in metadata.members) - if (string.Equals(member.name, revision.memberName, StringComparison.Ordinal) && - (member.visibility & PropertyVisibility.Serialize) != 0) - { + { + if (string.Equals(member.name, revision.memberName, StringComparison.Ordinal) + && (member.visibility & PropertyVisibility.Serialize) != 0 + ) { throw new InvalidOperationException( - $"Capture revision '{type.FullName}.{revision.memberName}' must not be serialized."); + $"Capture revision '{type.FullName}.{revision.memberName}' must not be serialized." + ); } + } const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; FieldInfo? field = type.GetField(revision.memberName, flags); if (field is not null && !field.IsStatic && (field.FieldType == typeof(ulong) || field.FieldType == typeof(ulong?))) @@ -66,15 +94,16 @@ private static SerializationTypeMetadata BuildMetadata(Type type) return metadata.WithCaptureRevision(value => ReadCaptureRevision(value, readField)); } PropertyInfo? property = type.GetProperty(revision.memberName, flags); - if (property is not null && property.GetIndexParameters().Length == 0 && - property.GetGetMethod(true) is { IsStatic: false } - && (property.PropertyType == typeof(ulong) || property.PropertyType == typeof(ulong?))) - { + if (property is not null && property.GetIndexParameters().Length == 0 + && property.GetGetMethod(true) is { IsStatic: false } + && (property.PropertyType == typeof(ulong) || property.PropertyType == typeof(ulong?)) + ) { Func readProperty = property.GetValue; return metadata.WithCaptureRevision(value => ReadCaptureRevision(value, readProperty)); } throw new InvalidOperationException( - $"Capture revision '{type.FullName}.{revision.memberName}' must be a readable ulong or nullable ulong instance member."); + $"Capture revision '{type.FullName}.{revision.memberName}' must be a readable ulong or nullable ulong instance member." + ); } private static object CreateInstance(Type type) @@ -82,7 +111,7 @@ private static object CreateInstance(Type type) try { return Activator.CreateInstance(type, nonPublic: true) - ?? throw new InvalidOperationException($"Serialization type '{type}' did not produce an instance."); + ?? throw new InvalidOperationException($"Serialization type '{type}' did not produce an instance."); } catch (TargetInvocationException exception) when (exception.InnerException is not null) { diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs index e42302c76..355c4cf95 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs @@ -53,11 +53,17 @@ private Stream OpenPinned(ContentEntry entry) FileStream? input = null; try { - input = new FileStream(ContentCacheValidator.Resolve(m_root, entry.key), - FileMode.Open, FileAccess.Read, FileShare.Read); + input = new FileStream( + ContentCacheValidator.Resolve(m_root, entry.key), + FileMode.Open, + FileAccess.Read, + FileShare.Read + ); if (input.Length != entry.length - || !StringComparer.Ordinal.Equals(Convert.ToHexString(SHA256.HashData(input)), entry.contentHash)) + || !StringComparer.Ordinal.Equals(Convert.ToHexString(SHA256.HashData(input)), entry.contentHash) + ) { throw new InvalidDataException($"Cached content '{entry.key}' changed after preparation."); + } input.Position = 0; return new GenerationReadStream(input, ReleasePin); } @@ -90,12 +96,16 @@ Action release /// public override bool CanRead => m_release is not null; + /// public override bool CanSeek => m_release is not null; + /// public override bool CanWrite => false; + /// public override long Length => m_input.Length; + /// public override long Position { @@ -109,19 +119,25 @@ public override int Read( int offset, int count ) => m_input.Read(buffer, offset, count); + /// public override int Read(Span buffer) => m_input.Read(buffer); + /// public override int ReadByte() => m_input.ReadByte(); + /// public override long Seek( long offset, SeekOrigin origin ) => m_input.Seek(offset, origin); + /// public override void Flush() => throw new NotSupportedException(); + /// public override void SetLength(long value) => throw new NotSupportedException(); + /// public override void Write( byte[] buffer, diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs index 68fcd5760..2aaa91930 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs @@ -28,23 +28,35 @@ CancellationToken cancellationToken Directory.CreateDirectory(Path.GetDirectoryName(output)!); using ContentReadLease lease = source.Acquire(entry.key); using Stream input = lease.OpenRead(); - await using FileStream destination = new(output, FileMode.CreateNew, FileAccess.Write, - FileShare.None, 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan); + await using FileStream destination = new( + output, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + ); long remaining = entry.length; byte[] buffer = System.Buffers.ArrayPool.Shared.Rent(128 * 1024); try { while (remaining > 0) { - int read = await input.ReadAsync(buffer.AsMemory(0, (int)Math.Min(buffer.Length, remaining)), - cancellationToken).ConfigureAwait(false); + int read = await input.ReadAsync( + buffer.AsMemory(0, (int)Math.Min(buffer.Length, remaining)), + cancellationToken + ).ConfigureAwait(false); if (read == 0) + { throw new InvalidDataException($"Content '{entry.key}' ended before its indexed length."); + } await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); remaining -= read; } if (input.ReadByte() != -1) + { throw new InvalidDataException($"Content '{entry.key}' exceeded its indexed length."); + } await destination.FlushAsync(cancellationToken).ConfigureAwait(false); destination.Flush(flushToDisk: true); } @@ -54,10 +66,15 @@ CancellationToken cancellationToken } } if (!ContentCacheValidator.Validate(candidate, source.index, cancellationToken)) - throw new InvalidDataException("The prepared content generation failed complete validation."); - using (await FileLease.AcquireAsync(Path.Combine(cache, "leases", generation + ".lock"), - TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) { + throw new InvalidDataException("The prepared content generation failed complete validation."); + } + using (await FileLease.AcquireAsync( + Path.Combine(cache, "leases", generation + ".lock"), + TimeSpan.Zero, + cancellationToken + ).ConfigureAwait(false) + ) { AtomicDirectory.Publish(candidate, target, cancellationToken); } cancellationToken.ThrowIfCancellationRequested(); @@ -67,7 +84,9 @@ CancellationToken cancellationToken finally { if (Directory.Exists(candidate)) + { Directory.Delete(candidate, recursive: true); + } } } } diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheRetirement.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheRetirement.cs index 547760526..abc37053b 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheRetirement.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheRetirement.cs @@ -18,19 +18,26 @@ string current { string name = Path.GetFileName(directory); if (name == current) + { continue; + } try { if (!Guid.TryParseExact(name, "N", out _)) + { throw new IOException("An unrecognized directory cannot be retired as a cache generation."); + } PathBoundary.RequireUnlinkedPath(cache, directory); string lockPath = PathBoundary.RequireUnlinkedPath(cache, Path.Combine(cache, "leases", name + ".lock")); if (!File.Exists(lockPath)) + { throw new IOException("The generation lease is missing; existing reader ownership cannot be proven."); - using FileLease lease = await FileLease.AcquireAsync(lockPath, - TimeSpan.Zero).ConfigureAwait(false); + } + using FileLease lease = await FileLease.AcquireAsync(lockPath, TimeSpan.Zero).ConfigureAwait(false); foreach (string file in PathBoundary.EnumerateFiles(directory)) + { _ = file; + } Directory.Delete(directory, recursive: true); } catch (TimeoutException) diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs index f95462ea8..206aaa5b1 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs @@ -17,7 +17,9 @@ internal static bool Validate( CancellationToken cancellationToken ) { if (!Directory.Exists(root) || (File.GetAttributes(root) & FileAttributes.ReparsePoint) != 0) + { return false; + } HashSet files = new(StringComparer.Ordinal); HashSet directories = new(StringComparer.Ordinal); foreach (ContentEntry entry in index.entries) @@ -25,7 +27,9 @@ CancellationToken cancellationToken string key = entry.key.value!; files.Add(key); for (int separator = key.IndexOf('/'); separator >= 0; separator = key.IndexOf('/', separator + 1)) + { directories.Add(key[..separator]); + } } Stack pending = new(); pending.Push(root); @@ -36,21 +40,29 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); FileAttributes attributes = File.GetAttributes(path); if ((attributes & FileAttributes.ReparsePoint) != 0) + { return false; + } string key = Path.GetRelativePath(root, path).Replace('\\', '/'); if ((attributes & FileAttributes.Directory) != 0) { if (!directories.Remove(key)) + { return false; + } pending.Push(path); continue; } if (!files.Remove(key)) + { return false; + } } } if (files.Count != 0 || directories.Count != 0) + { return false; + } foreach (ContentEntry entry in index.entries) { cancellationToken.ThrowIfCancellationRequested(); @@ -58,10 +70,14 @@ CancellationToken cancellationToken { using FileStream input = new(Resolve(root, entry.key), FileMode.Open, FileAccess.Read, FileShare.Read); if (input.Length != entry.length) + { return false; + } string hash = ComputeHash(input, cancellationToken); if (!string.Equals(hash, entry.contentHash, StringComparison.Ordinal)) + { return false; + } } catch (FileNotFoundException) { diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentCacheOptions.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentCacheOptions.cs index 417f15a99..b5293dcf2 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentCacheOptions.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentCacheOptions.cs @@ -26,11 +26,15 @@ public FileContentCacheOptions( ) { ArgumentException.ThrowIfNullOrWhiteSpace(applicationCacheRoot); if (!Path.IsPathFullyQualified(applicationCacheRoot)) + { throw new ArgumentException("Content caches require an absolute host-selected root.", nameof(applicationCacheRoot)); + } this.applicationCacheRoot = Path.GetFullPath(applicationCacheRoot); this.lockTimeout = lockTimeout ?? TimeSpan.FromSeconds(30); if (this.lockTimeout < TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(lockTimeout)); + } } /// diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs index 63688d57e..f99df7743 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs @@ -75,25 +75,44 @@ public async ValueTask PrepareAsync( ArgumentNullException.ThrowIfNull(pack); ArgumentNullException.ThrowIfNull(serialization); if (!scope.isValid) + { throw new ArgumentException("Content preparation requires an application namespace.", nameof(scope)); + } cancellationToken.ThrowIfCancellationRequested(); - var stream = new FileStream(Path.Combine(m_contentDirectory, pack.fileName), - FileMode.Open, FileAccess.Read, FileShare.Read); + var stream = new FileStream( + Path.Combine(m_contentDirectory, pack.fileName), + FileMode.Open, + FileAccess.Read, + FileShare.Read + ); PackContentStore? source = null; try { - source = await Task.Run(() => ContentPackReader.Open(stream, pack, serialization, - m_limits, cancellationToken), CancellationToken.None).ConfigureAwait(false); - return await FileContentPreparation.PrepareAsync(source, - new FileContentCacheOptions(Path.Combine(m_cacheRoot, scope.value!)), cancellationToken) + source = await Task.Run(() => ContentPackReader.Open( + stream, + pack, + serialization, + m_limits, + cancellationToken + ), CancellationToken.None).ConfigureAwait(false); + return await FileContentPreparation + .PrepareAsync( + source, + new FileContentCacheOptions(Path.Combine(m_cacheRoot, scope.value!)), + cancellationToken + ) .ConfigureAwait(false); } finally { if (source is not null) + { source.Dispose(); + } else + { stream.Dispose(); + } } } @@ -121,15 +140,27 @@ CancellationToken cancellationToken ) { ArgumentException.ThrowIfNullOrWhiteSpace(fileName); if (fileName is "." or ".." || fileName.IndexOfAny(['/', '\\', ':']) >= 0) + { throw new ArgumentException("A deployment document requires a single portable filename.", nameof(fileName)); - using var stream = new FileStream(Path.Combine(m_contentDirectory, fileName), - FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous); + } + using var stream = new FileStream( + Path.Combine(m_contentDirectory, fileName), + FileMode.Open, + FileAccess.Read, + FileShare.Read, + 4096, + FileOptions.Asynchronous + ); if (stream.Length is <= 0 or > C_METADATA_LIMIT) + { throw new InvalidDataException($"Deployment metadata '{fileName}' exceeds its document budget."); + } byte[] bytes = new byte[checked((int)stream.Length)]; await stream.ReadExactlyAsync(bytes, cancellationToken).ConfigureAwait(false); if (stream.ReadByte() != -1) + { throw new InvalidDataException($"Deployment metadata '{fileName}' changed during acquisition."); + } return bytes; } } diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs index d404531a1..31f38f3b3 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs @@ -47,26 +47,43 @@ public static async ValueTask PrepareAsync( string cache = Path.Combine(options.applicationCacheRoot, "Content", source.descriptor.contentHash); PathBoundary.RequireUnlinkedPath(options.applicationCacheRoot, cache); PathBoundary.RequireUnlinkedPath(cache, Path.Combine(cache, "install.lock")); - using FileLease writer = await FileLease.AcquireAsync(Path.Combine(cache, "install.lock"), - options.lockTimeout, cancellationToken).ConfigureAwait(false); + using FileLease writer = await FileLease.AcquireAsync( + Path.Combine(cache, "install.lock"), + options.lockTimeout, + cancellationToken + ).ConfigureAwait(false); foreach (string entry in new[] { "generations", "staging", "leases", "current" }) + { PathBoundary.RequireUnlinkedPath(cache, Path.Combine(cache, entry)); + } Directory.CreateDirectory(Path.Combine(cache, "generations")); string? current = ReadCurrent(cache); bool valid = current is not null - && File.Exists(PathBoundary.RequireUnlinkedPath(cache, Path.Combine(cache, "leases", current + ".lock"))) - && await Task.Run(() => ContentCacheValidator.Validate( - Path.Combine(cache, "generations", current), source.index, cancellationToken), cancellationToken).ConfigureAwait(false); + && File.Exists(PathBoundary.RequireUnlinkedPath(cache, Path.Combine(cache, "leases", current + ".lock"))) + && await Task.Run(() => ContentCacheValidator.Validate( + Path.Combine(cache, "generations", current), + source.index, + cancellationToken + ), cancellationToken).ConfigureAwait(false); if (!valid) + { current = await ContentCachePublication.PublishAsync(cache, source, cancellationToken).ConfigureAwait(false); - FileLease reader = await FileLease.AcquireSharedAsync(Path.Combine(cache, "leases", current + ".lock"), - options.lockTimeout, cancellationToken).ConfigureAwait(false); + } + FileLease reader = await FileLease.AcquireSharedAsync( + Path.Combine(cache, "leases", current + ".lock"), + options.lockTimeout, + cancellationToken + ).ConfigureAwait(false); try { var diagnostics = await ContentCacheRetirement.RetireAsync(cache, current!).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); - return new FileContentStore(source.descriptor, source.index, - new ContentCacheGeneration(Path.Combine(cache, "generations", current!), reader), diagnostics); + return new FileContentStore( + source.descriptor, + source.index, + new ContentCacheGeneration(Path.Combine(cache, "generations", current!), reader), + diagnostics + ); } catch { @@ -81,7 +98,9 @@ public static async ValueTask PrepareAsync( try { if (new FileInfo(pointer).Length != 32) + { return null; + } string value = File.ReadAllText(pointer); return Guid.TryParseExact(value, "N", out _) ? value : null; } diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs index 670c43e51..483745064 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs @@ -43,7 +43,9 @@ public ContentReadLease Acquire(ContentKey key) { ContentCacheGeneration generation = m_generation ?? throw new ObjectDisposedException(nameof(FileContentStore)); if (!index.TryGetEntry(key, out ContentEntry? entry)) + { throw new FileNotFoundException($"Content '{key}' does not exist in pack '{descriptor.contentHash}'."); + } return generation.Acquire(entry!); } } diff --git a/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemApplicationStorage.cs b/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemApplicationStorage.cs index ed51ff744..fd4271f6e 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemApplicationStorage.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemApplicationStorage.cs @@ -4,9 +4,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - -using Inno.Storage; using Inno.Core.IO; +using Inno.Storage; namespace Inno.Adapter.Storage.FileSystem; @@ -97,8 +96,8 @@ public async ValueTask ExistsAsync( ThrowIfDisposed(); ValidateExistingPath(path, includeLeaf: true); return File.Exists(path) - ? await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false) - : null; + ? await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false) + : null; } finally { @@ -132,15 +131,13 @@ public async ValueTask WriteAsync( { ThrowIfDisposed(); string directory = Path.GetDirectoryName(path) - ?? throw new IOException("A storage key did not resolve to a parent directory."); + ?? throw new IOException("A storage key did not resolve to a parent directory."); ValidateExistingPath(directory, includeLeaf: true); Directory.CreateDirectory(directory); ValidateExistingPath(directory, includeLeaf: true); ValidateExistingPath(path, includeLeaf: true); - string temporaryPath = Path.Combine( - directory, - $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp"); + string temporaryPath = Path.Combine(directory, $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp"); try { await using (var stream = new FileStream( @@ -149,8 +146,8 @@ public async ValueTask WriteAsync( FileAccess.Write, FileShare.None, 4096, - FileOptions.Asynchronous | FileOptions.WriteThrough)) - { + FileOptions.Asynchronous | FileOptions.WriteThrough + )) { await stream.WriteAsync(value, cancellationToken).ConfigureAwait(false); stream.Flush(flushToDisk: true); } @@ -160,7 +157,9 @@ public async ValueTask WriteAsync( finally { if (File.Exists(temporaryPath)) + { File.Delete(temporaryPath); + } } } finally @@ -192,7 +191,9 @@ public async ValueTask DeleteAsync( ThrowIfDisposed(); ValidateExistingPath(path, includeLeaf: true); if (!File.Exists(path)) + { return false; + } File.Delete(path); return true; } @@ -228,9 +229,10 @@ public async ValueTask> ListAsync( if (prefix is { } requestedPrefix) { string prefixValue = requestedPrefix.value; - filtered = filtered.Where(candidate => + filtered = filtered.Where(candidate => ( string.Equals(candidate.value, prefixValue, StringComparison.Ordinal) - || candidate.value.StartsWith(prefixValue + "/", StringComparison.Ordinal)); + || candidate.value.StartsWith(prefixValue + "/", StringComparison.Ordinal) + )); } return filtered .OrderBy(static key => key.value, StringComparer.Ordinal) @@ -276,7 +278,9 @@ CancellationToken cancellationToken continue; } if (entry is not FileInfo) + { continue; + } string relative = Path.GetRelativePath(m_root, entry.FullName) .Replace(Path.DirectorySeparatorChar, '/'); values.Add(new StorageKey(relative)); @@ -287,10 +291,10 @@ private string Resolve(StorageKey key) { ThrowIfDisposed(); if (!key.isValid) + { throw new ArgumentException("A valid storage key is required.", nameof(key)); - return PathBoundary.Resolve( - m_root, - key.value.Replace('/', Path.DirectorySeparatorChar)); + } + return PathBoundary.Resolve(m_root, key.value.Replace('/', Path.DirectorySeparatorChar)); } private void ValidateExistingPath( @@ -301,24 +305,33 @@ bool includeLeaf string current = m_root; string[] segments = relative.Split( [Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], - StringSplitOptions.RemoveEmptyEntries); + StringSplitOptions.RemoveEmptyEntries + ); int length = includeLeaf ? segments.Length : Math.Max(0, segments.Length - 1); for (int index = 0; index < length; index++) { current = Path.Combine(current, segments[index]); if (Directory.Exists(current)) + { RejectLink(new DirectoryInfo(current)); + } else if (File.Exists(current)) + { RejectLink(new FileInfo(current)); + } else + { break; + } } } private static void RejectLink(FileSystemInfo entry) { if (entry.LinkTarget is not null || (entry.Attributes & FileAttributes.ReparsePoint) != 0) + { throw new IOException($"Storage sandbox path '{entry.FullName}' contains a symbolic link or reparse point."); + } } private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(m_disposed, this); diff --git a/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs b/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs index 2a86af323..4834db4b3 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs @@ -20,11 +20,14 @@ public sealed class FileSystemStorageBackendProvider : StorageBackendProvider /// /// The root is absent or not fully qualified. /// - public FileSystemStorageBackendProvider(string rootDirectory) : base(StorageBackendId.fileSystem) + public FileSystemStorageBackendProvider(string rootDirectory) + : base(StorageBackendId.fileSystem) { ArgumentException.ThrowIfNullOrWhiteSpace(rootDirectory); if (!Path.IsPathFullyQualified(rootDirectory)) + { throw new ArgumentException("A filesystem storage provider requires an absolute host root.", nameof(rootDirectory)); + } m_rootDirectory = Path.GetFullPath(rootDirectory); } @@ -32,8 +35,9 @@ public FileSystemStorageBackendProvider(string rootDirectory) : base(StorageBack public override IApplicationStorage CreateStorage(StorageScope scope) { if (!scope.isValid) + { throw new ArgumentException("Storage requires an assigned application namespace.", nameof(scope)); + } return new FileSystemApplicationStorage(Path.Combine(m_rootDirectory, scope.value!, "Storage")); } } - diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGui/CimguiSourceOverlay.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGui/CimguiSourceOverlay.cs index 7069f3487..197597440 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGui/CimguiSourceOverlay.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGui/CimguiSourceOverlay.cs @@ -11,19 +11,25 @@ internal static string Prepare( string cimguiDirectory ) { string source = File.ReadAllText(Path.Combine(cimguiDirectory, "imgui", "imgui.cpp")); - source = ReplaceOnce(source, + source = ReplaceOnce( + source, "ImRect bg_rect(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size);", - "// Keep one continuous backing surface under the title and body. Independently anti-aliased shared edges leak the window behind them.\n" + - " ImRect bg_rect(window->DockIsActive ? window->Pos + ImVec2(0, window->TitleBarHeight) : window->Pos, window->Pos + window->Size);"); - source = ReplaceOnce(source, + "// Keep one continuous backing surface under the title and body. Independently anti-aliased shared edges leak the window behind them.\n" + + " ImRect bg_rect(window->DockIsActive ? window->Pos + ImVec2(0, window->TitleBarHeight) : window->Pos, window->Pos + window->Size);" + ); + source = ReplaceOnce( + source, "bg_rounding_flags = (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersBottom;", - "bg_rounding_flags = ImDrawFlags_RoundCornersAll;"); + "bg_rounding_flags = ImDrawFlags_RoundCornersAll;" + ); string directory = Path.Combine(context.GetNativeBuildRoot(ImGuiToolchain.componentDescriptor), "Source"); Directory.CreateDirectory(directory); string output = Path.Combine(directory, "imgui.cpp"); if (!File.Exists(output) || File.ReadAllText(output) != source) + { File.WriteAllText(output, source); + } return output; } @@ -34,7 +40,11 @@ string replacement ) { int index = source.IndexOf(expected, StringComparison.Ordinal); if (index < 0 || source.IndexOf(expected, index + expected.Length, StringComparison.Ordinal) >= 0) - throw new InvalidOperationException("The cimgui window-background source no longer matches its validated overlay. Review the upstream change before building."); + { + throw new InvalidOperationException( + "The cimgui window-background source no longer matches its validated overlay. Review the upstream change before building." + ); + } return string.Concat(source.AsSpan(0, index), replacement, source.AsSpan(index + expected.Length)); } } diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs index 7598713b1..d10b485c0 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs @@ -19,7 +19,8 @@ public static class ImGuiToolchain "cimgui", "backends/ImGui/native/Inno.Native.ImGui/Inno.Native.ImGui.csproj", "backends/ImGui/build/Inno.Build.Toolchains.ImGui/Inno.Build.Toolchains.ImGui.csproj", - bindingDefinition: "backends/ImGui/native/Inno.Native.ImGui/Bindings/bindings.props"); + bindingDefinition: "backends/ImGui/native/Inno.Native.ImGui/Bindings/bindings.props" + ); /// /// Builds the component using the explicitly selected target SDK and validates the complete native product. @@ -48,18 +49,34 @@ public static async Task BuildAsync( string upstream = Path.Combine(context.engineRoot, "extern", "cimgui"); string[] arguments = ["-DINNO_CIMGUI_SOURCE_DIR=" + upstream, "-DBUILD_SHARED_LIBS=ON", "-DCIMGUI_VARGS0=ON"]; NativeBuildRecipe recipe = CreateRecipe(context); - return await NativeArtifactPublisher.PublishAsync(context, recipe, + return await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { - NativeCMakeSource sources = await NativeCMakeExecutor.PrepareSourceAsync(scoped, componentDescriptor, token).ConfigureAwait(false); + ) => + { + NativeCMakeSource sources = await NativeCMakeExecutor.PrepareSourceAsync( + scoped, + componentDescriptor, + token + ).ConfigureAwait(false); string windowSource = CimguiSourceOverlay.Prepare(scoped, sources.ResolvePath(upstream)); - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - componentDescriptor.GetToolchainRoot(scoped.engineRoot), "cimgui", - [.. arguments, "-DINNO_IMGUI_WINDOW_SOURCE=" + windowSource], token).ConfigureAwait(false); - string library = NativeCMakeExecutor.FindOutput(scoped, build, "*cimgui-" + scoped.configuration + selection.sharedLibraryExtension); + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + componentDescriptor.GetToolchainRoot(scoped.engineRoot), + "cimgui", + [.. arguments, "-DINNO_IMGUI_WINDOW_SOURCE=" + windowSource], + token + ).ConfigureAwait(false); + string library = NativeCMakeExecutor.FindOutput( + scoped, + build, + "*cimgui-" + scoped.configuration + selection.sharedLibraryExtension + ); string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); if (selection.linkPlan.importLibraryExtension is string importExtension) @@ -69,14 +86,21 @@ public static async Task BuildAsync( Directory.CreateDirectory(link); File.Copy(import, Path.Combine(link, Path.GetFileName(import))); } - }, cancellationToken, describeOutputs: static ( + }, + cancellationToken, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray() + ).ConfigureAwait(false); } /// @@ -102,14 +126,25 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) + { throw new NotSupportedException("This presentation recipe supports shared linkage only."); + } string source = componentDescriptor.GetToolchainRoot(context.engineRoot); string upstream = Path.Combine(context.engineRoot, "extern", "cimgui"); string adapter = Path.Combine(componentDescriptor.GetNativeRoot(context.engineRoot), "Native"); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, - "cimgui", selection.targetId, [upstream, Path.Combine(source, "CMakeLists.txt"), - Path.Combine(adapter, "ImGuiPlatformCallbacks.h"), Path.Combine(adapter, "ImGuiPlatformCallbacks.cpp")], + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "cimgui", + selection.targetId, + [ + upstream, + Path.Combine(source, "CMakeLists.txt"), + Path.Combine(adapter, "ImGuiPlatformCallbacks.h"), + Path.Combine(adapter, "ImGuiPlatformCallbacks.cpp") + ], ["-DINNO_CIMGUI_SOURCE_DIR=" + upstream, "-DBUILD_SHARED_LIBS=ON", "-DCIMGUI_VARGS0=ON", "window-source=continuous-background"], - [Path.Combine(source, "CimguiSourceOverlay.cs"), Path.Combine(source, "ImGuiToolchain.cs")]); + [Path.Combine(source, "CimguiSourceOverlay.cs"), Path.Combine(source, "ImGuiToolchain.cs")] + ); } } diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildConstants.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildConstants.cs index f750af78e..2b23a126a 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildConstants.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildConstants.cs @@ -6,26 +6,32 @@ internal static class CImguizmoBuildConstants /// The output product dir name value used as part of this type's public representation. /// public const string OUTPUT_PRODUCT_DIR_NAME = "cimguizmo"; + /// /// The output dll name value used as part of this type's public representation. /// public const string OUTPUT_DLL_NAME = "libcimguizmo"; + /// /// The cimgui dir name value used as part of this type's public representation. /// public const string CIMGUI_DIR_NAME = "cimgui"; + /// /// The cimguizmo dir name value used as part of this type's public representation. /// public const string CIMGUIZMO_DIR_NAME = "cimguizmo"; + /// /// The cimguimo cpp file value used as part of this type's public representation. /// public const string CIMGUIMO_CPP_FILE = "cimguizmo.cpp"; + /// /// The imguizmo cpp file value used as part of this type's public representation. /// public const string IMGUIZMO_CPP_FILE = "ImGuizmo.cpp"; + /// /// The imguizmo dir name value used as part of this type's public representation. /// diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs index c5dff87c8..faa32839c 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs @@ -21,13 +21,15 @@ string cimguiDir if (!Directory.Exists(cimguizmoDir)) { throw new DirectoryNotFoundException( - $"cimguizmo source not found at {cimguizmoDir}. Place the cimguizmo repository in extern/cimguizmo before running this tool."); + $"cimguizmo source not found at {cimguizmoDir}. Place the cimguizmo repository in extern/cimguizmo before running this tool." + ); } if (!Directory.Exists(cimguiDir)) { throw new DirectoryNotFoundException( - $"cimgui source not found at {cimguiDir}. Place the cimgui repository in extern/cimgui before running this tool."); + $"cimgui source not found at {cimguiDir}. Place the cimgui repository in extern/cimgui before running this tool." + ); } var cimguizmoCpp = Path.Combine(cimguizmoDir, CImguizmoBuildConstants.CIMGUIMO_CPP_FILE); diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs index ad2acb80a..737a8a53f 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.ImGuizmo; @@ -20,7 +19,8 @@ public static class ImGuizmoToolchain "cimguizmo", "backends/ImGui/native/Inno.Native.ImGuizmo/Inno.Native.ImGuizmo.csproj", "backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/Inno.Build.Toolchains.ImGuizmo.csproj", - bindingDefinition: "backends/ImGui/native/Inno.Native.ImGuizmo/Bindings/bindings.props"); + bindingDefinition: "backends/ImGui/native/Inno.Native.ImGuizmo/Bindings/bindings.props" + ); /// /// Builds and installs the component for the explicitly selected native target. @@ -56,12 +56,17 @@ public static async Task BuildAsync( NativeToolchainSelection selection = context.RequireToolchain(); NativeBuildRecipe sourceRecipe = CreateRecipe(context); if (imGui.component != "cimgui" || imGui.targetId != selection.targetId) + { throw new ArgumentException("The supplied ImGui product does not match this gizmo target.", nameof(imGui)); + } NativeArtifactRole role = imGui.artifacts.Any(static artifact => artifact.role == NativeArtifactRole.ImportLibrary) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary; + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary; string[] libraries = imGui.artifacts.Where(artifact => artifact.role == role).Select(static artifact => artifact.file).ToArray(); if (libraries.Length != 1) + { throw new InvalidOperationException("The ImGui product must provide exactly one link library."); + } string cimguiDir = Path.Combine(context.engineRoot, "extern", "cimgui"); NativeBuildRecipe recipe = BindImGui(context, sourceRecipe, imGui); return await NativeArtifactPublisher.PublishAsync( @@ -71,24 +76,38 @@ public static async Task BuildAsync( @scoped, output, token - ) => { - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - componentDescriptor.GetToolchainRoot(scoped.engineRoot), "cimguizmo", - ["-DINNO_CIMGUI_SOURCE_DIR=" + cimguiDir, - "-DINNO_CIMGUI_LIBRARY=" + libraries[0]], token).ConfigureAwait(false); + ) => + { + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + componentDescriptor.GetToolchainRoot(scoped.engineRoot), + "cimguizmo", + [ + "-DINNO_CIMGUI_SOURCE_DIR=" + cimguiDir, + "-DINNO_CIMGUI_LIBRARY=" + libraries[0] + ], + token + ).ConfigureAwait(false); string library = NativeCMakeExecutor.FindOutput(scoped, build, "*cimguizmo" + selection.sharedLibraryExtension); string name = "libcimguizmo-" + scoped.configuration + selection.sharedLibraryExtension; File.Copy(library, Path.Combine(output, name)); token.ThrowIfCancellationRequested(); - - }, cancellationToken, describeOutputs: static ( + }, + cancellationToken, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray() + ).ConfigureAwait(false); } /// @@ -114,15 +133,26 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) + { throw new NotSupportedException("This presentation recipe supports shared linkage only."); + } string source = componentDescriptor.GetToolchainRoot(context.engineRoot); string upstream = Path.Combine(context.engineRoot, "extern", "cimguizmo"); string imGui = Path.Combine(context.engineRoot, "extern", "cimgui"); CImguizmoBuildUtils.ValidateSource(upstream, imGui); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, - "cimguizmo", selection.targetId, [upstream, imGui, Path.Combine(source, "CMakeLists.txt")], - ["dependency=cimgui"], [Path.Combine(source, "CImguizmoBuildConstants.cs"), - Path.Combine(source, "CImguizmoBuildUtils.cs"), Path.Combine(source, "ImGuizmoToolchain.cs")]); + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "cimguizmo", + selection.targetId, + [upstream, imGui, Path.Combine(source, "CMakeLists.txt")], + ["dependency=cimgui"], + [ + Path.Combine(source, "CImguizmoBuildConstants.cs"), + Path.Combine(source, "CImguizmoBuildUtils.cs"), + Path.Combine(source, "ImGuizmoToolchain.cs") + ] + ); } /// @@ -156,12 +186,17 @@ NativeBuildProduct imGui ArgumentNullException.ThrowIfNull(imGui); NativeToolchainSelection selection = context.RequireToolchain(); if (imGui.component != "cimgui" || imGui.targetId != selection.targetId) + { throw new ArgumentException("The supplied ImGui product does not match this gizmo target.", nameof(imGui)); + } NativeArtifactRole role = imGui.artifacts.Any(static artifact => artifact.role == NativeArtifactRole.ImportLibrary) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary; + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary; string[] libraries = imGui.artifacts.Where(artifact => artifact.role == role).Select(static artifact => artifact.file).ToArray(); if (libraries.Length != 1) + { throw new InvalidOperationException("The ImGui product must provide exactly one link library."); + } return sourceRecipe.WithDependency(NativeBuildInput.FromPath(context.engineRoot, libraries[0]), imGui.fingerprint); } } diff --git a/backends/ImGui/native/Inno.Native.ImGui/ImGui.cs b/backends/ImGui/native/Inno.Native.ImGui/ImGui.cs index bd67e9dca..0bab900f8 100644 --- a/backends/ImGui/native/Inno.Native.ImGui/ImGui.cs +++ b/backends/ImGui/native/Inno.Native.ImGui/ImGui.cs @@ -23,4 +23,4 @@ static ImGui() Load(NativeDllLoader.FindNativeLibrary(LibName)); #endif } -} \ No newline at end of file +} diff --git a/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs b/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs index 690080979..e964b415b 100644 --- a/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs +++ b/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs @@ -38,7 +38,9 @@ public void Dispose() lock (m_gate) { if (m_closing) + { return; + } m_closing = true; // A failed API unload is terminal; its dependency must remain retained for process lifetime. m_api.Dispose(); diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs index 9bee115a5..a283c936f 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs @@ -1,13 +1,14 @@ -using System.Threading.Tasks; using System; using System.Buffers.Binary; using System.Collections.Generic; using System.Linq; using System.Numerics; -using Inno.Native.ImGui; +using System.Threading.Tasks; using Inno.Adapter.Presentation.ImGui; using Inno.Adapter.Rendering.Bgfx; +using Inno.Native.ImGui; using Inno.Rendering; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -27,17 +28,21 @@ public sealed unsafe class BgfxImGuiRenderer : IPlatformImGuiRenderer, IRenderFr private static readonly byte[] S_LINEAR_OUTPUT = new byte[16]; private static readonly byte[] S_ENCODED_OUTPUT = CreateOutputEncoding(); private static readonly RenderPhaseId S_USER_INTERFACE_PHASE = new("inno.imgui.compose"); + private static readonly RenderClearColor S_PRESENTATION_CLEAR_COLOR = new( SrgbToLinear(0.08f), SrgbToLinear(0.08f), SrgbToLinear(0.09f), - 1f); + 1f + ); + private static readonly RenderVertexLayout S_VERTEX_LAYOUT = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2), - new RenderVertexAttribute(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), - new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) - ]); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2), + new RenderVertexAttribute(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), + new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) + ] + ); private readonly object m_sync = new(); private readonly IRenderDevice m_device; @@ -85,7 +90,7 @@ GraphicsPipelineDescriptor pipelineDescriptor ValidatePipelineDescriptor(pipelineDescriptor); m_device = device; m_bgfxDevice = device as BgfxDevice - ?? throw new NotSupportedException("The BGFX ImGui renderer requires an Inno.Adapter.Rendering.Bgfx device."); + ?? throw new NotSupportedException("The BGFX ImGui renderer requires an Inno.Adapter.Rendering.Bgfx device."); m_pendingPipelineDescriptor = pipelineDescriptor; } @@ -209,8 +214,10 @@ int pixelHeight lock (m_sync) { if (m_mainPacket is not null - && (m_mainPacket.pixelWidth != pixelWidth || m_mainPacket.pixelHeight != pixelHeight)) + && (m_mainPacket.pixelWidth != pixelWidth || m_mainPacket.pixelHeight != pixelHeight) + ) { m_mainPacket = null; + } } } @@ -306,7 +313,8 @@ public Task RetireViewport(PlatformImGuiViewportTarget target) if (m_viewports.TryGetValue(target.viewportId, out ViewportState? state)) { Task retirement = state.surface.isValid - ? m_bgfxDevice.RetireWindowSurface(state.surface) : Task.CompletedTask; + ? m_bgfxDevice.RetireWindowSurface(state.surface) + : Task.CompletedTask; m_viewports.Remove(target.viewportId); m_framePackets = m_framePackets.Where(packet => packet.viewportId != target.viewportId).ToArray(); return retirement; @@ -353,7 +361,9 @@ public void PrepareFrame(ulong frameIndex) } } if (needsOutputTransfer) + { PreparePresentationQuad(); + } PrepareTextures(); PrepareDrawPackets(); } @@ -384,38 +394,64 @@ ulong frameIndex foreach (PreparedPacket packet in m_framePackets) { if (packet.viewportId == 0 && !m_device.primaryPresentationSize.HasValue) + { continue; + } string name = packet.viewportId == 0 ? "ImGui/Main" : $"ImGui/Viewport/{packet.viewportId}"; bool needsOutputTransfer = packet.surface.isValid - ? !m_bgfxDevice.WindowSurfaceIsSrgb(packet.surface) - : !m_bgfxDevice.backbufferIsSrgb; + ? !m_bgfxDevice.WindowSurfaceIsSrgb(packet.surface) + : !m_bgfxDevice.backbufferIsSrgb; RasterPassBuilder pass = graph.AddRasterPass(name, S_USER_INTERFACE_PHASE, packet, ExecutePacket); pass.SetViewTransform(Identity(), Orthographic(packet.displayPosition, packet.displaySize)); if (needsOutputTransfer) { - RenderTextureHandle composed = graph.CreateTexture($"{name}/LinearComposition", - new RenderTextureDescriptor(packet.pixelWidth, packet.pixelHeight, + RenderTextureHandle composed = graph.CreateTexture( + $"{name}/LinearComposition", + new RenderTextureDescriptor( + packet.pixelWidth, + packet.pixelHeight, RenderTextureFormat.RGBA8Srgb, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); - pass.UseColorAttachment(composed, 0, RenderLoadAction.Clear, RenderStoreAction.Store, - S_PRESENTATION_CLEAR_COLOR); - var presentation = new PresentationPacket(packet.surface, composed, - packet.pixelWidth, packet.pixelHeight, packet.pipeline, - m_presentationVertices, m_presentationIndices); - RasterPassBuilder output = graph.AddRasterPass($"{name}/Present", S_USER_INTERFACE_PHASE, - presentation, ExecutePresentationPacket); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); + pass.UseColorAttachment( + composed, + 0, + RenderLoadAction.Clear, + RenderStoreAction.Store, + S_PRESENTATION_CLEAR_COLOR + ); + var presentation = new PresentationPacket( + packet.surface, + composed, + packet.pixelWidth, + packet.pixelHeight, + packet.pipeline, + m_presentationVertices, + m_presentationIndices + ); + RasterPassBuilder output = graph.AddRasterPass( + $"{name}/Present", + S_USER_INTERFACE_PHASE, + presentation, + ExecutePresentationPacket + ); output.SetViewTransform(Identity(), Identity()) .ClearPresentationTarget(default) .HasSideEffect(); output.ReadTexture(composed); if (packet.surface.isValid) + { output.UseSurface(packet.surface); + } } else { pass.ClearPresentationTarget(S_PRESENTATION_CLEAR_COLOR).HasSideEffect(); if (packet.surface.isValid) + { pass.UseSurface(packet.surface); + } } } } @@ -430,7 +466,9 @@ public void Dispose() { m_disposeRequested = true; foreach (uint viewportId in m_viewports.Keys.ToArray()) + { _ = RetireViewport(m_viewports[viewportId].target); + } m_mainPacket = null; m_framePackets = []; } @@ -448,7 +486,8 @@ private void PreparePipeline() { GraphicsPipelineHandle candidate = m_device.CreateGraphicsPipeline( m_pendingPipelineDescriptor, - "ImGui Pipeline"); + "ImGui Pipeline" + ); GraphicsPipelineHandle previous = m_pipeline; m_pipeline = candidate; m_pendingPipelineDescriptor = null; @@ -468,7 +507,9 @@ private void PreparePipeline() private void PreparePresentationQuad() { if (m_presentationVertices.isValid) + { return; + } PersistentBufferHandle vertices = default; PersistentBufferHandle indices = default; try @@ -476,20 +517,27 @@ private void PreparePresentationQuad() vertices = m_device.CreateBuffer( new PersistentBufferDescriptor(new RenderBufferDescriptor(4, C_VERTEX_STRIDE, RenderBufferUsage.Vertex), S_VERTEX_LAYOUT), CreatePresentationVertices(m_device.capabilities.originBottomLeft), - "ImGui Presentation Vertices"); + "ImGui Presentation Vertices" + ); indices = m_device.CreateBuffer( new PersistentBufferDescriptor( new RenderBufferDescriptor(6, C_INDEX_STRIDE, RenderBufferUsage.Index), - indexFormat: RenderIndexFormat.UInt16), + indexFormat: RenderIndexFormat.UInt16 + ), [0, 0, 1, 0, 2, 0, 0, 0, 2, 0, 3, 0], - "ImGui Presentation Indices"); + "ImGui Presentation Indices" + ); } catch { if (indices.isValid) + { m_device.DestroyBuffer(indices); + } if (vertices.isValid) + { m_device.DestroyBuffer(vertices); + } throw; } m_presentationVertices = vertices; @@ -506,7 +554,8 @@ private void PrepareSurfaces() state.target.nativeHandles, state.target.width, state.target.height, - $"ImGui Viewport {state.target.viewportId}"); + $"ImGui Viewport {state.target.viewportId}" + ); state.resizePending = false; } else if (state.resizePending) @@ -539,15 +588,16 @@ private void PrepareTextures() PersistentTextureHandle texture; if (m_ownedTextures.TryGetValue(token, out OwnedTexture? current) && current.width == upload.width - && current.height == upload.height) - { + && current.height == upload.height + ) { texture = current.handle; } else { texture = m_device.CreateTexture( new RenderTextureDescriptor(upload.width, upload.height, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled), - $"ImGui Texture {token}"); + $"ImGui Texture {token}" + ); if (current is not null) { m_device.DestroyTexture(current.handle); @@ -604,29 +654,35 @@ private void PrepareDrawPackets() { if (m_textures.TryGetValue(command.textureToken, out PersistentTextureHandle texture)) { - commands.Add(new PreparedDrawCommand( - command.clipX, - command.clipY, - command.clipWidth, - command.clipHeight, - vertexBase + command.firstVertex, - indexBase + command.firstIndex, - command.indexCount, - texture)); + commands.Add( + new PreparedDrawCommand( + command.clipX, + command.clipY, + command.clipWidth, + command.clipHeight, + vertexBase + command.firstVertex, + indexBase + command.firstIndex, + command.indexCount, + texture + ) + ); } } - prepared.Add(new PreparedPacket( - packet.viewportId, - packet.surface, - packet.displayPosition, - packet.displaySize, - packet.pixelWidth, - packet.pixelHeight, - commands, - m_pipeline, - m_vertexBuffer, - m_indexBuffer)); + prepared.Add( + new PreparedPacket( + packet.viewportId, + packet.surface, + packet.displayPosition, + packet.displaySize, + packet.pixelWidth, + packet.pixelHeight, + commands, + m_pipeline, + m_vertexBuffer, + m_indexBuffer + ) + ); vertexBase += packet.vertices.Length / C_VERTEX_STRIDE; indexBase += packet.indices.Length / C_INDEX_STRIDE; } @@ -646,9 +702,11 @@ int indexCount PersistentBufferHandle replacement = m_device.CreateBuffer( new PersistentBufferDescriptor( new RenderBufferDescriptor(capacity, C_VERTEX_STRIDE, RenderBufferUsage.Vertex | RenderBufferUsage.Dynamic), - S_VERTEX_LAYOUT), + S_VERTEX_LAYOUT + ), ReadOnlySpan.Empty, - "ImGui Vertices"); + "ImGui Vertices" + ); if (m_vertexBuffer.isValid) { m_device.DestroyBuffer(m_vertexBuffer); @@ -664,9 +722,11 @@ int indexCount PersistentBufferHandle replacement = m_device.CreateBuffer( new PersistentBufferDescriptor( new RenderBufferDescriptor(capacity, C_INDEX_STRIDE, RenderBufferUsage.Index | RenderBufferUsage.Dynamic), - indexFormat: RenderIndexFormat.UInt16), + indexFormat: RenderIndexFormat.UInt16 + ), ReadOnlySpan.Empty, - "ImGui Indices"); + "ImGui Indices" + ); if (m_indexBuffer.isValid) { m_device.DestroyBuffer(m_indexBuffer); @@ -697,7 +757,9 @@ RenderSurfaceHandle surface int pixelWidth = checked((int)MathF.Round(drawData->DisplaySize.X * clipScale.X)); int pixelHeight = checked((int)MathF.Round(drawData->DisplaySize.Y * clipScale.Y)); if (pixelWidth <= 0 || pixelHeight <= 0) + { return null; + } ProcessTextureRequests(drawData); byte[] vertices = new byte[checked(drawData->TotalVtxCount * C_VERTEX_STRIDE)]; byte[] indices = new byte[checked(drawData->TotalIdxCount * C_INDEX_STRIDE)]; @@ -733,15 +795,18 @@ RenderSurfaceHandle surface continue; } - commands.Add(new CapturedDrawCommand( - clipX, - clipY, - clipRight - clipX, - clipBottom - clipY, - checked(vertexBase + (int)command.VtxOffset), - checked(indexBase + (int)command.IdxOffset), - checked((int)command.ElemCount), - ImGuiNative.Raw.GetTexID(&command))); + commands.Add( + new CapturedDrawCommand( + clipX, + clipY, + clipRight - clipX, + clipBottom - clipY, + checked(vertexBase + (int)command.VtxOffset), + checked(indexBase + (int)command.IdxOffset), + checked((int)command.ElemCount), + ImGuiNative.Raw.GetTexID(&command) + ) + ); } vertexBase += listVertexCount; @@ -757,7 +822,8 @@ RenderSurfaceHandle surface pixelHeight, vertices, indices, - commands); + commands + ); } private void ProcessTextureRequests(ImDrawData* drawData) @@ -793,8 +859,8 @@ private void ProcessTextureRequests(ImDrawData* drawData) if (textureData->Status is not (ImTextureStatus.WantCreate or ImTextureStatus.WantUpdates) || textureData->Pixels is null || textureData->Width <= 0 - || textureData->Height <= 0) - { + || textureData->Height <= 0 + ) { continue; } @@ -808,7 +874,8 @@ private void ProcessTextureRequests(ImDrawData* drawData) m_pendingTextureUploads[token] = new TextureUpload( textureData->Width, textureData->Height, - CopyTexturePixels(textureData)); + CopyTexturePixels(textureData) + ); ImGuiNative.Raw.SetStatus(textureData, ImTextureStatus.Ok); } } @@ -894,9 +961,13 @@ private void ReleaseDeviceResources() } if (m_presentationIndices.isValid) + { m_device.DestroyBuffer(m_presentationIndices); + } if (m_presentationVertices.isValid) + { m_device.DestroyBuffer(m_presentationVertices); + } if (m_pipeline.isValid) { @@ -930,14 +1001,20 @@ private static void ValidatePipelineDescriptor(GraphicsPipelineDescriptor descri } RenderShaderBindingDescriptor? texture = descriptor.bindings.SingleOrDefault( - static value => value.id == S_TEXTURE_BINDING); + static value => value.id == S_TEXTURE_BINDING + ); if (texture is null || texture.kind != RenderShaderBindingKind.Texture || texture.slot != 0) + { throw new ArgumentException("ImGui pipeline must declare texture binding 's_tex' at slot zero.", nameof(descriptor)); + } RenderShaderBindingDescriptor? outputEncoding = descriptor.bindings.SingleOrDefault( - static value => value.id == S_OUTPUT_ENCODING); + static value => value.id == S_OUTPUT_ENCODING + ); if (descriptor.bindings.Count != 2 || outputEncoding is null - || outputEncoding.kind != RenderShaderBindingKind.Uniform) + || outputEncoding.kind != RenderShaderBindingKind.Uniform + ) { throw new ArgumentException("ImGui pipeline must declare its outputEncoding render-pass uniform.", nameof(descriptor)); + } } private static int GrowCapacity( @@ -989,12 +1066,11 @@ float v private static float SrgbToLinear(float value) => value <= 0.04045f - ? value / 12.92f - : MathF.Pow((value + 0.055f) / 1.055f, 2.4f); + ? value / 12.92f + : MathF.Pow((value + 0.055f) / 1.055f, 2.4f); private static float[] Identity() - => - [ + => [ 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, @@ -1011,10 +1087,22 @@ Vector2 size float bottom = position.Y + size.Y; return [ - 2f / (right - left), 0f, 0f, 0f, - 0f, 2f / (top - bottom), 0f, 0f, - 0f, 0f, 1f, 0f, - (right + left) / (left - right), (top + bottom) / (bottom - top), 0f, 1f + 2f / (right - left), + 0f, + 0f, + 0f, + 0f, + 2f / (top - bottom), + 0f, + 0f, + 0f, + 0f, + 1f, + 0f, + (right + left) / (left - right), + (top + bottom) / (bottom - top), + 0f, + 1f ]; } @@ -1027,18 +1115,22 @@ private sealed class ViewportState /// The existing target that receives the validated result. /// public ViewportState(PlatformImGuiViewportTarget target) => this.target = target; + /// /// Gets the platform viewport whose render resources are tracked by this state. /// public PlatformImGuiViewportTarget target { get; set; } + /// /// Gets the presentation surface targeted by this render pass. /// public RenderSurfaceHandle surface { get; set; } + /// /// Gets the most recently prepared immutable draw packet, or null before preparation. /// public DrawPacket? packet { get; set; } + /// /// Gets whether the caller-visible condition represented by this property is satisfied. /// @@ -1050,11 +1142,13 @@ private sealed record OwnedTexture( int width, int height ); + private sealed record TextureUpload( int width, int height, byte[] pixels ); + private sealed record CapturedDrawCommand( int clipX, int clipY, diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs index 9dc86416b..8864a1671 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs @@ -26,7 +26,9 @@ public static GraphicsPipelineDescriptor Load(GraphicsApi api) { string resource = $"Inno.BuiltInShaders.ImGui.{api}"; using Stream source = typeof(BgfxImGuiShaderArtifacts).Assembly.GetManifestResourceStream(resource) - ?? throw new InvalidDataException($"Missing precompiled ImGui shader '{resource}'. Rebuild or repair the adapter installation; runtime source compilation is not supported."); + ?? throw new InvalidDataException( + $"Missing precompiled ImGui shader '{resource}'. Rebuild or repair the adapter installation; runtime source compilation is not supported." + ); using var bytes = new MemoryStream(); source.CopyTo(bytes); GraphicsPipelineDescriptor program = GraphicsProgramArtifactCodec.Decode(bytes.ToArray(), BgfxImGuiRenderer.vertexLayout); @@ -35,8 +37,10 @@ public static GraphicsPipelineDescriptor Load(GraphicsApi api) RenderShaderBindingDescriptor? outputEncoding = bindings.SingleOrDefault(static binding => binding.id.value == "outputEncoding"); if (bindings.Count != 2 || texture is null || texture.kind != RenderShaderBindingKind.Texture || texture.slot != 0 || outputEncoding is null - || outputEncoding.kind != RenderShaderBindingKind.Uniform) + || outputEncoding.kind != RenderShaderBindingKind.Uniform + ) { throw new InvalidDataException("The built-in ImGui graph must expose s_tex and the outputEncoding render-pass uniform."); + } return program; } } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationContext.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationContext.cs index 25dfe8b2e..900398f6f 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationContext.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationContext.cs @@ -1,6 +1,5 @@ using System; using System.Numerics; - using Inno.Adapter.Platform.Sdl3; using Inno.Adapter.Presentation; using Inno.Adapter.Presentation.ImGui; @@ -22,11 +21,13 @@ ImGuiInteractionOptions interaction ) { ArgumentNullException.ThrowIfNull(options); m_application = options.platformApplication as Sdl3PlatformApplication - ?? throw new NotSupportedException( - "The built-in ImGui presentation requires the selected platform adapter to support SDL3 integration."); + ?? throw new NotSupportedException( + "The built-in ImGui presentation requires the selected platform adapter to support SDL3 integration." + ); m_window = options.window as Sdl3PlatformWindow - ?? throw new NotSupportedException( - "The built-in ImGui presentation requires a window created by the selected SDL3 platform adapter."); + ?? throw new NotSupportedException( + "The built-in ImGui presentation requires a window created by the selected SDL3 platform adapter." + ); GraphicsPipelineDescriptor pipeline = BgfxImGuiShaderArtifacts.Load(options.renderDevice.capabilities.backend); m_renderer = new BgfxImGuiRenderer(options.renderDevice, pipeline); @@ -36,7 +37,8 @@ ImGuiInteractionOptions interaction m_window, ToImGuiFlags(options.features), interaction, - m_renderer); + m_renderer + ); } catch { @@ -57,8 +59,7 @@ out uint windowId bool IPresentationContext.TryCaptureLayout( out string settings, bool force - ) - => m_context.TryCaptureIniSettings(out settings, force); + ) => m_context.TryCaptureIniSettings(out settings, force); void IPresentationContext.RenderFrame( Action drawFrame, @@ -79,7 +80,9 @@ void IPresentationContext.DrawImage( Vector2 size ) { if (!texture.isValid) + { throw new ArgumentException("The presentation texture handle is invalid.", nameof(texture)); + } m_context.DrawImage(new ImGuiTextureHandle(texture.value), size); } @@ -88,27 +91,33 @@ Vector2 size void IRenderFrameGraphContributor.AddRenderPasses( RenderGraphBuilder graph, ulong frameIndex - ) - => m_renderer.AddRenderPasses(graph, frameIndex); + ) => m_renderer.AddRenderPasses(graph, frameIndex); void IDisposable.Dispose() { if (m_disposed) + { return; + } m_application.DestroyImGuiContext(m_window); m_disposed = true; } - private static ImGuiContextFlags ToImGuiFlags(PresentationFeatures features) { ImGuiContextFlags result = ImGuiContextFlags.None; if ((features & PresentationFeatures.MultipleWindows) != 0) + { result |= ImGuiContextFlags.EnableViewports; + } if ((features & PresentationFeatures.Docking) != 0) + { result |= ImGuiContextFlags.EnableDocking; + } if ((features & PresentationFeatures.SmoothResize) != 0) + { result |= ImGuiContextFlags.EnableSmoothResize; + } return result; } } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs index 6dd1bc408..ecc1e4593 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs @@ -19,7 +19,8 @@ public sealed class ImGuiPresentationProvider : PresentationBackendProvider /// /// Interaction configuration is absent. /// - public ImGuiPresentationProvider(ImGuiInteractionOptions interaction) : base(PresentationBackendId.imGui) + public ImGuiPresentationProvider(ImGuiInteractionOptions interaction) + : base(PresentationBackendId.imGui) { ArgumentNullException.ThrowIfNull(interaction); m_interaction = interaction; diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs index 77fba39da..a32e8e1a5 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs @@ -1,6 +1,6 @@ +using System; using System.Threading.Tasks; using Inno.Adapter.Platform; -using System; using Inno.Platform; namespace Inno.Adapter.Presentation.ImGui; diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiInteractionOptions.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiInteractionOptions.cs index 173c67c00..ab8a2a2cc 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiInteractionOptions.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiInteractionOptions.cs @@ -24,7 +24,9 @@ public ImGuiInteractionOptions( int horizontalWheelDirection ) { if (horizontalWheelDirection is not (1 or -1)) + { throw new ArgumentOutOfRangeException(nameof(horizontalWheelDirection), "Wheel direction must be one or minus one."); + } this.commandKeyBehavior = commandKeyBehavior; this.horizontalWheelDirection = horizontalWheelDirection; } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs index 397a835d5..9625fbd76 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; - using Inno.Adapter.Platform.Sdl3; using Inno.Native.Sdl3; @@ -37,7 +36,9 @@ internal void Release( PlatformImGuiContext context ) { if (!contexts.TryGetValue(windowId, out PlatformImGuiContext? registered) || !ReferenceEquals(registered, context)) + { throw new InvalidOperationException("The retired ImGui context no longer owns its application registration."); + } contexts.Remove(windowId); } @@ -52,7 +53,9 @@ scoped ReadOnlySpan nativeEventData SDLEvent sdlEvent = MemoryMarshal.Read(nativeEventData); foreach (PlatformImGuiContext context in contexts.Values) + { context.ProcessEvent(ref sdlEvent); + } } void ISdl3ApplicationExtension.PrepareLiveResizeWindow( @@ -60,7 +63,9 @@ void ISdl3ApplicationExtension.PrepareLiveResizeWindow( uint windowId ) { foreach (PlatformImGuiContext context in contexts.Values) + { context.PrepareLiveResizeWindow(windowId); + } } void ISdl3ApplicationExtension.OnApplicationDisposing(Sdl3PlatformApplication application) @@ -69,7 +74,9 @@ void ISdl3ApplicationExtension.OnApplicationDisposing(Sdl3PlatformApplication ap var retiring = new PlatformImGuiContext[contexts.Count]; contexts.Values.CopyTo(retiring, 0); foreach (PlatformImGuiContext context in retiring) + { context.Dispose(); + } s_states.Remove(application); m_registration?.Dispose(); m_registration = null; @@ -120,22 +127,38 @@ public static PlatformImGuiContext CreateImGuiContext( ArgumentNullException.ThrowIfNull(interaction); if (window.isClosed) + { throw new InvalidOperationException("Cannot create an ImGui context for a closed window."); + } bool registered = false; foreach (Sdl3PlatformWindow candidate in application.GetWindows()) + { registered |= ReferenceEquals(candidate, window); + } if (!registered) + { throw new ArgumentException("The window must belong to the supplied SDL application.", nameof(window)); + } ImGuiState state = s_states.GetValue(application, CreateState); if (state.isRetiring) + { throw new InvalidOperationException("The application presentation state is retiring and cannot create another context."); + } if (state.contexts.ContainsKey(window.windowId)) + { throw new InvalidOperationException("This window already owns an ImGui context."); + } uint windowId = window.windowId; - var context = new PlatformImGuiContext(application, window, contextFlags, interaction, renderer, - retired => state.Release(windowId, retired)); + var context = new PlatformImGuiContext( + application, + window, + contextFlags, + interaction, + renderer, + retired => state.Release(windowId, retired) + ); state.contexts[windowId] = context; return context; } @@ -163,9 +186,13 @@ Sdl3PlatformWindow window ArgumentNullException.ThrowIfNull(window); if (!s_states.TryGetValue(application, out ImGuiState? state)) + { return; + } if (!state.contexts.TryGetValue(window.windowId, out PlatformImGuiContext? context)) + { return; + } context.Dispose(); } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs index f2bd51f32..0f4f056c3 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs @@ -4,6 +4,7 @@ using System.Runtime.InteropServices; using Inno.Native.ImGui; using Inno.Native.Sdl3; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -40,7 +41,9 @@ private static void PlatformSetClipboardTextCallback( try { if (text != null && FindClipboardContext(context) is not null) + { _ = SDL.Raw.SetClipboardText(text); + } } catch { @@ -51,16 +54,22 @@ private static void PlatformSetClipboardTextCallback( private static PlatformImGuiContext? FindClipboardContext(ImGuiNativeContext* context) { if (context == null) + { return null; + } lock (S_CLIPBOARD_CONTEXT_SYNC) + { return S_CLIPBOARD_CONTEXTS.GetValueOrDefault((nuint)context); + } } private sbyte* GetClipboardText() { ReleaseClipboardText(); if (SDL.Raw.HasClipboardText() == 0) + { return null; + } // SDL transfers this allocation to the caller; retain it until the next request or context shutdown. m_clipboardText = (nint)SDL.Raw.GetClipboardText(); return (sbyte*)m_clipboardText; @@ -69,7 +78,9 @@ private static void PlatformSetClipboardTextCallback( private void RegisterClipboardCallbacks() { lock (S_CLIPBOARD_CONTEXT_SYNC) + { S_CLIPBOARD_CONTEXTS.Add((nuint)m_context, this); + } ImGuiPlatformIO* platformIo = ImGuiNative.Raw.GetPlatformIO(); platformIo->PlatformGetClipboardTextFn = &PlatformGetClipboardTextCallback; platformIo->PlatformSetClipboardTextFn = &PlatformSetClipboardTextCallback; @@ -84,7 +95,9 @@ private void UnregisterClipboardCallbacks() { nuint contextKey = (nuint)m_context; if (S_CLIPBOARD_CONTEXTS.GetValueOrDefault(contextKey) == this) + { S_CLIPBOARD_CONTEXTS.Remove(contextKey); + } } ReleaseClipboardText(); } @@ -92,7 +105,9 @@ private void UnregisterClipboardCallbacks() private void ReleaseClipboardText() { if (m_clipboardText == 0) + { return; + } SDL.Raw.Free((void*)m_clipboardText); m_clipboardText = 0; } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs index 1564bf3d6..7e9865784 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs @@ -5,10 +5,10 @@ using System.Numerics; using System.Runtime.InteropServices; using System.Text; - using Inno.Adapter.Platform.Sdl3; -using Inno.Native.Sdl3; using Inno.Native.ImGui; +using Inno.Native.Sdl3; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -80,8 +80,8 @@ Action releaseRegistration // docking, and the official SDL backend disables this capability on macOS. Let Dear ImGui // use its viewport heuristic instead of publishing incorrect hovered viewport identities. io->BackendFlags |= (int)ImGuiBackendFlags.HasMouseCursors - | (int)ImGuiBackendFlags.HasSetMousePos - | (int)ImGuiBackendFlags.RendererHasTextures; + | (int)ImGuiBackendFlags.HasSetMousePos + | (int)ImGuiBackendFlags.RendererHasTextures; io->ConfigFlags |= (int)ImGuiConfigFlags.NavEnableKeyboard; if (enableDocking) @@ -107,7 +107,9 @@ Action releaseRegistration UpdateDisplayMetrics(io); m_renderer = renderer ?? new PlatformImGuiSdlRenderer(window); if (m_renderer.supportsVertexOffsets) + { io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasVtxOffset; + } m_viewports = enableViewports ? new PlatformImGuiViewportBackend(application, window, m_renderer) : null; RegisterClipboardCallbacks(); } @@ -117,7 +119,9 @@ Action releaseRegistration ImGuiFont.UnregisterContext(m_context); ImGuiNative.Raw.DestroyContext(m_context); if (renderer is null) + { m_renderer?.Dispose(); + } throw; } } @@ -149,7 +153,9 @@ out uint windowId return true; } if (m_viewports is not null && m_viewports.TryGetWindowId(viewportId, out windowId)) + { return true; + } windowId = 0; return false; } @@ -164,7 +170,9 @@ public partial void SetIniFile(string? filePath) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_hasStartedFrame) + { throw new InvalidOperationException("The ImGui layout file must be configured before the first frame."); + } ImGuiNative.Raw.SetCurrentContext(m_context); var io = ImGuiNative.Raw.GetIO(); @@ -182,7 +190,9 @@ public partial void SetIniFile(string? filePath) string fullPath = Path.GetFullPath(filePath); string? directory = Path.GetDirectoryName(fullPath); if (!string.IsNullOrWhiteSpace(directory)) + { Directory.CreateDirectory(directory); + } m_iniFilename = Marshal.StringToCoTaskMemUTF8(fullPath); SetIniFilename(io, m_iniFilename); } @@ -197,14 +207,20 @@ public partial void LoadIniSettings(string? settings) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_hasStartedFrame) + { throw new InvalidOperationException("ImGui layout settings must be loaded before the first frame."); + } if (string.IsNullOrEmpty(settings)) + { return; + } ImGuiNative.Raw.SetCurrentContext(m_context); byte[] encoded = Encoding.UTF8.GetBytes(settings); fixed (byte* data = encoded) + { ImGuiNative.Raw.LoadIniSettingsFromMemory((sbyte*)data, (uint)encoded.Length); + } } /// @@ -239,11 +255,7 @@ Vector2 uv1 uv1 = Vector2.One; } - ImGuiNative.Image( - new ImTextureRef { TexID = texture.value }, - size, - uv0, - uv1); + ImGuiNative.Image(new ImTextureRef { TexID = texture.value }, size, uv0, uv1); } /// @@ -301,27 +313,37 @@ float fontSizePixels ) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_hasStartedFrame) + { throw new InvalidOperationException("Font styles must be registered before the first ImGui frame."); + } ImGuiFont.ValidateStyle(style); ArgumentException.ThrowIfNullOrWhiteSpace(filePath); if (!float.IsFinite(fontSizePixels) || fontSizePixels <= 0f) + { throw new ArgumentOutOfRangeException(nameof(fontSizePixels)); + } string fullPath = Path.GetFullPath(filePath); if (!File.Exists(fullPath)) + { throw new FileNotFoundException("The font file does not exist.", fullPath); + } ImGuiNative.Raw.SetCurrentContext(m_context); ImGuiIO* io = ImGuiNative.Raw.GetIO(); ImFont* loadedFont = LoadFont(io->Fonts, fullPath, fontSizePixels); if (loadedFont == null) + { throw new InvalidOperationException($"Could not load the font '{fullPath}'."); + } ResolveFontPaths(out _, out List iconFontPaths); MergeIconFontsIntoCurrentBaseFont(io->Fonts, iconFontPaths); ImGuiFont.RegisterStyle(m_context, style, (nint)loadedFont); if (style == ImGuiFontStyle.Regular) + { io->FontDefault = loadedFont; + } } private static void ConfigureFonts( @@ -366,7 +388,9 @@ private static void ConfigureFonts( io->FontDefault = defaultFont; if (defaultFont != null && !styleFonts.ContainsKey(ImGuiFontStyle.Regular)) + { styleFonts[ImGuiFontStyle.Regular] = (nint)defaultFont; + } ImGuiFont.RegisterContext(context, styleFonts); } @@ -375,8 +399,8 @@ private static ImGuiFontStyle GetFontStyle(string fontPath) string name = Path.GetFileNameWithoutExtension(fontPath); bool bold = name.Contains("Bold", StringComparison.OrdinalIgnoreCase); bool italic = name.Contains("Italic", StringComparison.OrdinalIgnoreCase); - return (bold ? ImGuiFontStyle.Bold : ImGuiFontStyle.Regular) | - (italic ? ImGuiFontStyle.Italic : ImGuiFontStyle.Regular); + return (bold ? ImGuiFontStyle.Bold : ImGuiFontStyle.Regular) + | (italic ? ImGuiFontStyle.Italic : ImGuiFontStyle.Regular); } private static int FindPreferredFontIndex(List fontPaths) @@ -459,8 +483,8 @@ bool includeSubdirectories { var extension = Path.GetExtension(fontFile); if (!extension.Equals(".ttf", StringComparison.OrdinalIgnoreCase) - && !extension.Equals(".otf", StringComparison.OrdinalIgnoreCase)) - { + && !extension.Equals(".otf", StringComparison.OrdinalIgnoreCase) + ) { continue; } @@ -520,7 +544,9 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) } if (m_enableSmoothResize) + { RefreshLiveResizeHoverLock(eventType, eventWindowId, ref sdlEvent); + } m_viewports?.ProcessEvent(ref sdlEvent, eventWindowId); @@ -542,7 +568,13 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) if (key != ImGuiKey.None) { ImGuiNative.Raw.AddKeyEvent(io, key, down ? (byte)1 : (byte)0); - ImGuiNative.Raw.SetKeyEventNativeData(io, key, (int)sdlEvent.Key.Key, (int)sdlEvent.Key.Scancode, (int)sdlEvent.Key.Scancode); + ImGuiNative.Raw.SetKeyEventNativeData( + io, + key, + (int)sdlEvent.Key.Key, + (int)sdlEvent.Key.Scancode, + (int)sdlEvent.Key.Scancode + ); } break; } @@ -550,7 +582,9 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) case SDLEventType.TextInput: { if (sdlEvent.Text.Text != null) + { ImGuiNative.Raw.AddInputCharactersUTF8(io, sdlEvent.Text.Text); + } break; } @@ -559,11 +593,7 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) m_mouseWindowId = eventWindowId; m_mousePendingLeaveFrame = 0; m_mousePendingLeaveWindowId = 0; - Vector2 mousePosition = GetEventMousePosition( - io, - eventWindowId, - sdlEvent.Motion.X, - sdlEvent.Motion.Y); + Vector2 mousePosition = GetEventMousePosition(io, eventWindowId, sdlEvent.Motion.X, sdlEvent.Motion.Y); ImGuiNative.Raw.AddMousePosEvent(io, mousePosition.X, mousePosition.Y); break; } @@ -576,9 +606,13 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) { int mask = 1 << button; if (down) + { m_mouseButtonsDown |= mask; + } else + { m_mouseButtonsDown &= ~mask; + } ImGuiNative.Raw.AddMouseButtonEvent(io, button, down ? (byte)1 : (byte)0); // Docking can destroy the source viewport before SDL emits MouseUp. Capturing // the mouse keeps the complete press/release sequence inside this application. @@ -594,9 +628,11 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) wheelX *= m_interaction.horizontalWheelDirection; - ImGuiNative.Raw.AddMouseWheelEvent(io, + ImGuiNative.Raw.AddMouseWheelEvent( + io, wheelX * DEFAULT_MOUSE_SCROLLING_UNITS, - wheelY * DEFAULT_MOUSE_SCROLLING_UNITS); + wheelY * DEFAULT_MOUSE_SCROLLING_UNITS + ); break; } @@ -677,7 +713,9 @@ public partial IntPtr RenderFrame( ArgumentNullException.ThrowIfNull(drawFrame); ObjectDisposedException.ThrowIf(m_disposed, this); if (m_isFrameOperationActive || m_isFrameActive) + { throw new InvalidOperationException("An ImGui frame cannot be reentered."); + } var now = m_frameTimer.Elapsed; var deltaSeconds = (float)(now - m_lastFrameTime).TotalSeconds; @@ -713,7 +751,9 @@ public partial IntPtr RenderFrame( private void AbortNativeFrame() { if (m_disposed || m_context->WithinFrameScope == 0) + { return; + } ImGuiNativeContext* previous = ImGuiNative.Raw.GetCurrentContext(); ImGuiNative.Raw.SetCurrentContext(m_context); try @@ -723,7 +763,9 @@ private void AbortNativeFrame() finally { if (previous != m_context) + { ImGuiNative.Raw.SetCurrentContext(previous); + } } } @@ -759,8 +801,8 @@ private void BeginFrame( var mainViewport = ImGuiNative.Raw.GetMainViewport(); if (m_liveResizeLockedWindowId != 0 && (io->ConfigFlags & (int)ImGuiConfigFlags.ViewportsEnable) != 0 - && mainViewport != null) - { + && mainViewport != null + ) { mainViewport->Flags &= ~(int)ImGuiViewportFlags.CanHostOtherWindows; } } @@ -832,8 +874,8 @@ ref SDLEvent sdlEvent if (eventType == SDLEventType.WindowExposed && eventWindowId == m_liveResizeLockedWindowId - && sdlEvent.Window.Data1 == 0) - { + && sdlEvent.Window.Data1 == 0 + ) { m_liveResizeLockedWindowId = 0; return; } @@ -862,7 +904,9 @@ public partial void Dispose() } if (m_isFrameOperationActive) + { throw new InvalidOperationException("A presentation context cannot retire during its frame operation."); + } ImGuiNative.Raw.SetCurrentContext(m_context); var io = ImGuiNative.Raw.GetIO(); @@ -983,7 +1027,9 @@ IntPtr fileName Encoding.UTF8.GetBytes(filePath, encoded); encoded[length] = 0; fixed (byte* filename = encoded) + { return ImGuiNative.Raw.AddFontFromFileTTF(fonts, (sbyte*)filename, fontSizePixels, config, null); + } } private static unsafe ImFont* LoadDefaultFont(ImFontAtlas* fonts) => ImGuiNative.Raw.AddFontDefault(fonts, null); @@ -1038,14 +1084,18 @@ private void SynchronizePendingLiveResizeWindows() m_renderer.SynchronizeMainOutput(pixelWidth, pixelHeight); } else + { m_viewports?.SynchronizeWindow(windowId); + } } } private void ReconcileMouseButtons(ImGuiIO* io) { if (m_mouseButtonsDown == 0) + { return; + } float mouseX = 0f; float mouseY = 0f; @@ -1062,11 +1112,15 @@ private void ReconcileMouseButtons(ImGuiIO* io) { int trackedMask = 1 << button; if ((m_mouseButtonsDown & trackedMask) == 0) + { continue; + } SDLMouseButtonFlags sdlMask = (SDLMouseButtonFlags)(1u << (sdlButtons[button] - 1)); if ((currentButtons & sdlMask) != 0) + { continue; + } // Recover when a destroyed viewport prevented the corresponding MouseUp event from // reaching the event queue. Without this release ImGui keeps its active drag forever. @@ -1075,7 +1129,9 @@ private void ReconcileMouseButtons(ImGuiIO* io) } if (m_mouseButtonsDown == 0) + { _ = SDL.CaptureMouse(false); + } } private static Vector2 GetEventMousePosition( @@ -1105,12 +1161,12 @@ float localY private void FlushPendingMouseLeave(ImGuiIO* io) { if (!ShouldFlushPendingMouseLeave( - m_mousePendingLeaveFrame, - ImGuiNative.GetFrameCount(), - m_mouseButtonsDown, - m_mousePendingLeaveWindowId, - m_liveResizeLockedWindowId)) - { + m_mousePendingLeaveFrame, + ImGuiNative.GetFrameCount(), + m_mouseButtonsDown, + m_mousePendingLeaveWindowId, + m_liveResizeLockedWindowId + )) { return; } @@ -1122,10 +1178,10 @@ private void FlushPendingMouseLeave(ImGuiIO* io) private void ReleaseCompletedLiveResizeHoverLock() { - if (m_liveResizeLockedWindowId == 0 || - (m_frameTimer.Elapsed - m_lastLiveResizeLockTime).TotalSeconds <= - LIVE_RESIZE_HOVER_LOCK_TIMEOUT_SECONDS) - { + if (m_liveResizeLockedWindowId == 0 + || (m_frameTimer.Elapsed - m_lastLiveResizeLockTime).TotalSeconds + <= LIVE_RESIZE_HOVER_LOCK_TIMEOUT_SECONDS + ) { return; } @@ -1133,7 +1189,9 @@ private void ReleaseCompletedLiveResizeHoverLock() float mouseY = 0f; SDLMouseButtonFlags mouseButtons = ((SDLMouseButtonFlags)SDL.Raw.GetMouseState(&mouseX, &mouseY)); if ((mouseButtons & SDLMouseButtonFlags.Left) == 0) + { m_liveResizeLockedWindowId = 0; + } } private static bool ShouldFlushPendingMouseLeave( @@ -1144,7 +1202,9 @@ private static bool ShouldFlushPendingMouseLeave( uint liveResizeLockedWindowId ) { if (pendingFrame == 0 || mouseButtonsDown != 0 || currentFrame < pendingFrame) + { return false; + } return liveResizeLockedWindowId == 0 || pendingWindowId != liveResizeLockedWindowId; } @@ -1400,5 +1460,4 @@ out uint windowId return false; } } - } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs index c340999d7..4d076ba0c 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; - using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -28,12 +28,14 @@ public static bool IsAvailable(ImGuiFontStyle style) ValidateStyle(style); ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); if (context == null) + { return false; + } lock (s_sync) { - return s_fontsByContext.TryGetValue(GetContextKey(context), out Dictionary? fonts) && - fonts.ContainsKey(style); + return s_fontsByContext.TryGetValue(GetContextKey(context), out Dictionary? fonts) + && fonts.ContainsKey(style); } } @@ -51,15 +53,17 @@ public static ImGuiFontScope PushStyle(ImGuiFontStyle style) ValidateStyle(style); ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); if (context == null) + { return default; + } nuint contextKey = GetContextKey(context); nint font; lock (s_sync) { - if (!s_fontsByContext.TryGetValue(contextKey, out Dictionary? fonts) || - !TryResolve(fonts, style, out font)) - { + if (!s_fontsByContext.TryGetValue(contextKey, out Dictionary? fonts) + || !TryResolve(fonts, style, out font) + ) { return default; } } @@ -73,7 +77,9 @@ internal static void RegisterContext( IReadOnlyDictionary fonts ) { if (context == null) + { throw new ArgumentException("An ImGui context is required.", nameof(context)); + } ArgumentNullException.ThrowIfNull(fonts); var registered = new Dictionary(); @@ -81,11 +87,15 @@ IReadOnlyDictionary fonts { ValidateStyle(style); if (font != 0) + { registered[style] = font; + } } lock (s_sync) + { s_fontsByContext[GetContextKey(context)] = registered; + } } internal static void RegisterStyle( @@ -94,10 +104,14 @@ internal static void RegisterStyle( nint font ) { if (context == null) + { throw new ArgumentException("An ImGui context is required.", nameof(context)); + } ValidateStyle(style); if (font == 0) + { throw new ArgumentException("A loaded font is required.", nameof(font)); + } lock (s_sync) { @@ -114,23 +128,31 @@ nint font internal static void UnregisterContext(ImGuiNativeContext* context) { if (context == null) + { return; + } lock (s_sync) + { s_fontsByContext.Remove(GetContextKey(context)); + } } internal static void ValidateStyle(ImGuiFontStyle style) { const ImGuiFontStyle supported = ImGuiFontStyle.Bold | ImGuiFontStyle.Italic; if ((style & ~supported) != 0) + { throw new ArgumentOutOfRangeException(nameof(style), style, "The font style contains unsupported flags."); + } } internal static void PopStyle(nuint contextKey) { ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); if (context == null || GetContextKey(context) != contextKey) + { throw new InvalidOperationException("The font style scope must be disposed in the context where it was created."); + } NativeImGui.PopFont(); } @@ -142,11 +164,17 @@ private static bool TryResolve( out nint font ) { if (fonts.TryGetValue(style, out font)) + { return true; + } if ((style & ImGuiFontStyle.Bold) != 0 && fonts.TryGetValue(ImGuiFontStyle.Bold, out font)) + { return true; + } if ((style & ImGuiFontStyle.Italic) != 0 && fonts.TryGetValue(ImGuiFontStyle.Italic, out font)) + { return true; + } return fonts.TryGetValue(ImGuiFontStyle.Regular, out font); } } @@ -173,7 +201,9 @@ bool isPushed public void Dispose() { if (!m_isPushed) + { return; + } ImGuiFont.PopStyle(m_contextKey); m_isPushed = false; } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontStyle.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontStyle.cs index e305d530f..491922d3f 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontStyle.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontStyle.cs @@ -12,12 +12,10 @@ public enum ImGuiFontStyle /// Uses the regular font face. /// Regular = 0, - /// /// Uses a bold font face. /// Bold = 1 << 0, - /// /// Uses an italic font face. /// diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs index 544b3e35d..258195b98 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs @@ -1,8 +1,8 @@ using System; using System.Runtime.InteropServices; using Inno.Core.Execution; - using Inno.Native.ImGui; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -16,16 +16,22 @@ internal static unsafe class ImGuiPlatformIoNative ) { void* registration = ImGuiNative.Raw.InnoCreatePlatformWindowCallbacks(context, setPosition, setSize); if (registration == null) + { throw new InvalidOperationException("The current ImGui context cannot own platform window callbacks."); + } return registration; } internal static void DestroyWindowCallbacks(void* registration) { if (registration == null) + { return; + } if (ImGuiNative.Raw.InnoCanDestroyPlatformWindowCallbacks(registration) == 0) + { throw new RetirementPendingException("Platform window callbacks still require their current context's idle owner thread."); + } ImGuiNative.Raw.InnoDestroyPlatformWindowCallbacks(registration); } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/Sdl3PlatformWindowAccess.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/Sdl3PlatformWindowAccess.cs index aaa18c2ab..0960d57ad 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/Sdl3PlatformWindowAccess.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/Sdl3PlatformWindowAccess.cs @@ -1,5 +1,4 @@ using System; - using Inno.Adapter.Platform.Sdl3; using Inno.Native.Sdl3; diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs index cccd9b60f..7084053c5 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs @@ -1,8 +1,8 @@ using System; using System.Numerics; +using Inno.Native.Sdl3; using ImGuiNative = Inno.Native.ImGui.ImGui; -using Inno.Native.Sdl3; namespace Inno.Adapter.Presentation.ImGui; diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs index a6457d993..af920c566 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs @@ -1,11 +1,11 @@ -using System.Runtime.InteropServices; -using System.Threading.Tasks; using System; using System.Numerics; - +using System.Runtime.InteropServices; +using System.Threading.Tasks; using Inno.Adapter.Platform.Sdl3; -using Inno.Native.Sdl3; using Inno.Native.ImGui; +using Inno.Native.Sdl3; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -78,7 +78,7 @@ public void CreateViewport(PlatformImGuiViewportTarget target) /// /// The existing target that receives the validated result. /// - public void ResizeViewport(PlatformImGuiViewportTarget target) { } + public void ResizeViewport(PlatformImGuiViewportTarget target) {} /// /// Records ImGui draw data for the supplied auxiliary viewport. @@ -92,7 +92,7 @@ public void ResizeViewport(PlatformImGuiViewportTarget target) { } public void RenderViewport( PlatformImGuiViewportTarget target, IntPtr drawData - ) { } + ) {} /// /// Presents the completed frame for the supplied auxiliary viewport. @@ -100,7 +100,7 @@ IntPtr drawData /// /// The existing target that receives the validated result. /// - public void PresentViewport(PlatformImGuiViewportTarget target) { } + public void PresentViewport(PlatformImGuiViewportTarget target) {} /// /// Destroys the auxiliary viewport and releases its rendering resources. @@ -114,7 +114,7 @@ public void PresentViewport(PlatformImGuiViewportTarget target) { } public Task RetireViewport(PlatformImGuiViewportTarget target) => Task.CompletedTask; /// - public void DrainViewportRetirements() { } + public void DrainViewportRetirements() {} internal void Render(ImDrawData* drawData) { @@ -176,8 +176,10 @@ internal void Render(ImDrawData* drawData) var clipRect = new SDLRect { - X = (int)clipRectX, Y = (int)clipRectY, - W = (int)(clipRectZ - clipRectX), H = (int)(clipRectW - clipRectY) + X = (int)clipRectX, + Y = (int)clipRectY, + W = (int)(clipRectZ - clipRectX), + H = (int)(clipRectW - clipRectY) }; if (SDL.Raw.SetRenderClipRect(m_renderer, &clipRect) == 0) @@ -211,13 +213,7 @@ internal void Render(ImDrawData* drawData) fixed (SDLVertex* pVertices = m_vertexScratch) fixed (int* pIndices = m_indexScratch) { - _ = SDL.Raw.RenderGeometry( - m_renderer, - texture, - pVertices, - vertexCount, - pIndices, - elemCount); + _ = SDL.Raw.RenderGeometry(m_renderer, texture, pVertices, vertexCount, pIndices, elemCount); } } } @@ -239,11 +235,7 @@ internal void SynchronizeOutputSize() // A macOS live-resize expose callback can run before SDL's renderer event watcher has // consumed the matching pixel-size event. Re-applying the disabled presentation mode // makes SDL query the native drawable immediately instead of clipping to its old size. - _ = SDL.Raw.SetRenderLogicalPresentation( - m_renderer, - 0, - 0, - SDLRendererLogicalPresentation.Disabled); + _ = SDL.Raw.SetRenderLogicalPresentation(m_renderer, 0, 0, SDLRendererLogicalPresentation.Disabled); _ = SDL.Raw.SetRenderViewport(m_renderer, null); _ = SDL.Raw.SetRenderClipRect(m_renderer, null); } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs index 947b1352b..312f5b1b7 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs @@ -3,6 +3,7 @@ using System.Runtime.InteropServices; using Inno.Native.ImGui; using Inno.Native.Sdl3; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -20,19 +21,25 @@ private static void RefreshMonitors(SDLWindow* fallbackWindow) if (displays != null && displayCount > 0) { if (primary != 0) + { AddDisplayMonitor(primary, monitors); + } for (int index = 0; index < displayCount; index++) { uint display = displays[index]; if (display != 0 && display != primary) + { AddDisplayMonitor(display, monitors); + } } } if (monitors.Count == 0 && fallbackWindow != null) { uint fallback = SDL.Raw.GetDisplayForWindow(fallbackWindow); if (fallback != 0) + { AddDisplayMonitor(fallback, monitors); + } } } finally @@ -47,7 +54,9 @@ private static void RefreshMonitors(SDLWindow* fallbackWindow) uint bytes = checked((uint)monitors.Count * (uint)sizeof(ImGuiPlatformMonitor)); var replacement = (ImGuiPlatformMonitor*)ImGuiNative.Raw.MemAlloc(bytes); if (replacement == null) + { throw new OutOfMemoryException("Cannot allocate the ImGui monitor snapshot."); + } CollectionsMarshal.AsSpan(monitors).CopyTo(new Span(replacement, monitors.Count)); ImGuiPlatformMonitor* previous = storage.Data; storage.Data = replacement; @@ -69,7 +78,9 @@ List monitors ) { SDLRect main = default; if (SDL.Raw.GetDisplayBounds(displayId, &main) == 0) + { return; + } SDLRect work = main; _ = SDL.Raw.GetDisplayUsableBounds(displayId, &work); float scale = SDL.GetDisplayContentScale(displayId); diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs index 080896a90..115cddc11 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs @@ -15,16 +15,25 @@ internal void ProcessRetirements() ViewportWindowData data = m_retiringViewports[index]; Task retirement = data.retirement!; if (!retirement.IsCompleted) + { continue; + } if (!retirement.IsCompletedSuccessfully) + { throw new RetirementPendingException("Rendering failed to release a detached SDL window.", retirement.Exception); + } DestroyRetiredWindow(data); m_retiringViewports.RemoveAt(index); } if (m_callbackFailure is Exception callbackFailure) { if (m_retiringViewports.Count != 0) - throw new RetirementPendingException("An ImGui callback failed; its renderer still borrows a detached window.", callbackFailure); + { + throw new RetirementPendingException( + "An ImGui callback failed; its renderer still borrows a detached window.", + callbackFailure + ); + } m_callbackFailure = null; throw new InvalidOperationException("An ImGui window callback failed and its resources have retired.", callbackFailure); } @@ -33,7 +42,9 @@ internal void ProcessRetirements() private static void DestroyViewportWindow(ViewportWindowData data) { if (data.detached) + { return; + } data.detached = true; data.drawable = false; data.owner.m_retiringViewports.Add(data); @@ -41,8 +52,8 @@ private static void DestroyViewportWindow(ViewportWindowData data) { data.owner.m_application.ReleaseWindow(data.registeredWindow); data.retirement = data.externalRenderer is not null && data.externalTarget is not null - ? data.externalRenderer.RetireViewport(data.externalTarget) - : Task.CompletedTask; + ? data.externalRenderer.RetireViewport(data.externalTarget) + : Task.CompletedTask; } catch (Exception failure) { @@ -52,7 +63,9 @@ private static void DestroyViewportWindow(ViewportWindowData data) { data.viewport = default; if (data.gcHandle.IsAllocated) + { data.gcHandle.Free(); + } } } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs index 9855a9440..bd2a7fa0b 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs @@ -1,16 +1,16 @@ -using System.Threading.Tasks; -using Inno.Core.Execution; -using Inno.Adapter.Platform; using System; using System.Collections.Generic; using System.Numerics; -using System.Runtime.InteropServices; using System.Runtime.CompilerServices; - +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Inno.Adapter.Platform; using Inno.Adapter.Platform.Sdl3; -using Inno.Platform; -using Inno.Native.Sdl3; +using Inno.Core.Execution; using Inno.Native.ImGui; +using Inno.Native.Sdl3; +using Inno.Platform; + using ImGuiNative = Inno.Native.ImGui.ImGui; namespace Inno.Adapter.Presentation.ImGui; @@ -69,12 +69,16 @@ IPlatformImGuiRenderer renderer ArgumentNullException.ThrowIfNull(renderer); ImGuiNativeContext* context = ImGuiNative.Raw.GetCurrentContext(); if (context == null) + { throw new InvalidOperationException("An active ImGui context is required for viewport routing."); + } m_contextKey = (nuint)context; lock (S_CONTEXT_SYNC) { if (S_BACKENDS_BY_CONTEXT.ContainsKey(m_contextKey)) + { throw new InvalidOperationException("The current ImGui context already owns a viewport backend."); + } } m_application = application; m_renderer = renderer; @@ -83,7 +87,9 @@ IPlatformImGuiRenderer renderer var platformIo = ImGuiNative.Raw.GetPlatformIO(); if (ImGuiNative.Raw.GetIO()->BackendPlatformUserData != null) + { throw new InvalidOperationException("The current ImGui context already has platform backend state."); + } platformIo->PlatformCreateWindow = &PlatformCreateWindowCallback; platformIo->PlatformDestroyWindow = &PlatformDestroyWindowCallback; platformIo->PlatformShowWindow = &PlatformShowWindowCallback; @@ -107,9 +113,14 @@ IPlatformImGuiRenderer renderer { RefreshMonitors(mainSdlWindow); m_windowCallbacks = ImGuiPlatformIoNative.CreateWindowCallbacks( - context, &PlatformSetWindowPosCallback, &PlatformSetWindowSizeCallback); + context, + &PlatformSetWindowPosCallback, + &PlatformSetWindowSizeCallback + ); lock (S_CONTEXT_SYNC) + { S_BACKENDS_BY_CONTEXT.Add(m_contextKey, this); + } } catch { @@ -148,23 +159,29 @@ uint windowId var eventType = (SDLEventType)sdlEvent.Type; if (eventType >= SDLEventType.DisplayFirst && eventType <= SDLEventType.DisplayLast || eventType == SDLEventType.WindowDisplayChanged - || eventType == SDLEventType.WindowDisplayScaleChanged) - { + || eventType == SDLEventType.WindowDisplayScaleChanged + ) { m_monitorsDirty = true; } if (!m_windowToViewport.TryGetValue(windowId, out uint viewportId) - || !m_viewportsById.TryGetValue(viewportId, out ViewportWindowData? data)) - { + || !m_viewportsById.TryGetValue(viewportId, out ViewportWindowData? data) + ) { return; } ImGuiViewport* viewport = data.viewport; if (eventType == SDLEventType.WindowCloseRequested) + { viewport->PlatformRequestClose = 1; + } if (eventType == SDLEventType.WindowMoved) + { viewport->PlatformRequestMove = 1; + } if (eventType == SDLEventType.WindowResized || eventType == SDLEventType.WindowPixelSizeChanged) + { viewport->PlatformRequestResize = 1; + } } internal void SynchronizeMetrics() @@ -180,10 +197,14 @@ internal void SynchronizeMetrics() { main->FramebufferScale = new ImVec2C { X = scale.X, Y = scale.Y }; if (main->DpiScale == 0f) + { main->DpiScale = GetWindowDpiScale(m_mainWindow); + } } foreach (ViewportWindowData data in m_viewportsById.Values) + { SynchronizeWindow(data.windowId); + } } /// @@ -220,7 +241,9 @@ internal void SynchronizeWindow(uint windowId) if (framebufferScale.X > 0 && framebufferScale.Y > 0) { if (viewport->DpiScale == 0f) + { viewport->DpiScale = GetWindowDpiScale(data.window); + } viewport->FramebufferScale = new ImVec2C { X = framebufferScale.X, Y = framebufferScale.Y }; } int pixelWidth = 0; @@ -261,10 +284,14 @@ public void Dispose() m_viewportsById.Clear(); m_windowToViewport.Clear(); if (m_retiringViewports.Count != 0) + { m_renderer.DrainViewportRetirements(); + } ProcessRetirements(); if (m_retiringViewports.Count != 0) + { throw new RetirementPendingException("Detached ImGui windows are still borrowed by their renderer."); + } var platformIo = ImGuiNative.Raw.GetPlatformIO(); ImGuiPlatformIoNative.DestroyWindowCallbacks(m_windowCallbacks); @@ -282,8 +309,8 @@ public void Dispose() lock (S_CONTEXT_SYNC) { if (S_BACKENDS_BY_CONTEXT.TryGetValue(m_contextKey, out PlatformImGuiViewportBackend? registered) - && ReferenceEquals(registered, this)) - { + && ReferenceEquals(registered, this) + ) { S_BACKENDS_BY_CONTEXT.Remove(m_contextKey); } } @@ -320,7 +347,9 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) var height = Math.Max(1, (int)viewport->Size.Y); SDLWindow* window; fixed (byte* title = "ImGui\0"u8) + { window = SDL.Raw.CreateWindow((sbyte*)title, width, height, (ulong)flags); + } if (window == null) { return; @@ -351,7 +380,9 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) catch { if (renderer != null) + { SDL.Raw.DestroyRenderer(renderer); + } SDL.Raw.DestroyWindow(window); throw; } @@ -378,7 +409,8 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) data.windowId, registeredWindow.nativeHandles, pixelWidth, - pixelHeight); + pixelHeight + ); rendererBackend.CreateViewport(data.externalTarget); } data.gcHandle = GCHandle.Alloc(data, GCHandleType.Normal); @@ -663,7 +695,9 @@ private static void RendererRenderWindowCallback( data.owner.SynchronizeWindow(data.windowId); if (!data.drawable) + { return; + } if (data.externalRenderer is not null && data.externalTarget is not null) { @@ -696,7 +730,9 @@ private static void RendererSwapBuffersCallback( data.owner.SynchronizeWindow(data.windowId); if (!data.drawable) + { return; + } if (data.externalRenderer is not null && data.externalTarget is not null) { @@ -793,8 +829,8 @@ private static void EnsureViewportFontTexture(ViewportWindowData data) } var needsRecreate = data.fontTexture == null - || data.fontTextureWidth != texData->Width - || data.fontTextureHeight != texData->Height; + || data.fontTextureWidth != texData->Width + || data.fontTextureHeight != texData->Height; if (needsRecreate) { if (data.fontTexture != null) @@ -821,13 +857,13 @@ private static void EnsureViewportFontTexture(ViewportWindowData data) var usedRect = texData->UsedRect; var updateRect = texData->UpdateRect; var needsUpload = needsRecreate - || data.fontPixelsPtr != pixelsPtr - || data.fontTexturePitch != pitch - || data.fontTextureUniqueId != uniqueId - || !TextureRectEquals(data.fontUsedRect, usedRect) - || !TextureRectEquals(data.fontUpdateRect, updateRect) - || texData->Status == ImTextureStatus.WantCreate - || texData->Status == ImTextureStatus.WantUpdates; + || data.fontPixelsPtr != pixelsPtr + || data.fontTexturePitch != pitch + || data.fontTextureUniqueId != uniqueId + || !TextureRectEquals(data.fontUsedRect, usedRect) + || !TextureRectEquals(data.fontUpdateRect, updateRect) + || texData->Status == ImTextureStatus.WantCreate + || texData->Status == ImTextureStatus.WantUpdates; if (!needsUpload) { return; @@ -898,8 +934,10 @@ private static void RenderDrawData( var clipRect = new SDLRect { - X = (int)clipRectX, Y = (int)clipRectY, - W = (int)(clipRectZ - clipRectX), H = (int)(clipRectW - clipRectY) + X = (int)clipRectX, + Y = (int)clipRectY, + W = (int)(clipRectZ - clipRectX), + H = (int)(clipRectW - clipRectY) }; _ = SDL.Raw.SetRenderClipRect(renderer, &clipRect); @@ -913,7 +951,9 @@ private static void RenderDrawData( data.indexScratch[i] = srcIndices[idxOffset + i] + vtxOffset; } - var texture = ImGuiNative.Raw.GetTexID(&drawCmd) == fontTexId ? fontTexture : TextureFromImGui(ImGuiNative.Raw.GetTexID(&drawCmd)); + var texture = ImGuiNative.Raw.GetTexID(&drawCmd) == fontTexId + ? fontTexture + : TextureFromImGui(ImGuiNative.Raw.GetTexID(&drawCmd)); if (texture == null) { texture = fontTexture; @@ -942,12 +982,12 @@ private static PlatformImGuiViewportBackend GetCurrentBackend() { ImGuiNativeContext* context = ImGuiNative.Raw.GetCurrentContext(); if (context == null) + { throw new InvalidOperationException("No ImGui context is active for a viewport callback."); + } lock (S_CONTEXT_SYNC) { - if (S_BACKENDS_BY_CONTEXT.TryGetValue( - (nuint)context, - out PlatformImGuiViewportBackend? backend)) + if (S_BACKENDS_BY_CONTEXT.TryGetValue((nuint)context, out PlatformImGuiViewportBackend? backend)) { return backend; } @@ -962,11 +1002,7 @@ private static void SynchronizeRendererOutput(SDLRenderer* renderer) return; } - _ = SDL.Raw.SetRenderLogicalPresentation( - renderer, - 0, - 0, - SDLRendererLogicalPresentation.Disabled); + _ = SDL.Raw.SetRenderLogicalPresentation(renderer, 0, 0, SDLRendererLogicalPresentation.Disabled); _ = SDL.Raw.SetRenderViewport(renderer, null); _ = SDL.Raw.SetRenderClipRect(renderer, null); } @@ -1043,8 +1079,12 @@ private static float GetWindowDpiScale(SDLWindow* window) // ImGui's DPI value is in logical coordinates; pixel density belongs to FramebufferScale. float scale = SDL.Raw.GetWindowDisplayScale(window) / SDL.Raw.GetWindowPixelDensity(window); if (!float.IsFinite(scale) || scale <= 0f) - throw new InvalidOperationException("SDL could not resolve the live window's display scale: " - + Marshal.PtrToStringUTF8((nint)SDL.Raw.GetError())); + { + throw new InvalidOperationException( + "SDL could not resolve the live window's display scale: " + + Marshal.PtrToStringUTF8((nint)SDL.Raw.GetError()) + ); + } return scale; } @@ -1075,12 +1115,13 @@ private static bool TextureRectEquals( ImTextureRect b ) { return a.X == b.X - && a.Y == b.Y - && a.W == b.W - && a.H == b.H; + && a.Y == b.Y + && a.W == b.W + && a.H == b.H; } - private void RecordCallbackFailure(Exception failure) => m_callbackFailure = m_callbackFailure is null - ? failure : new AggregateException("Multiple native viewport callbacks failed in the same frame.", m_callbackFailure, failure); - + private void RecordCallbackFailure(Exception failure) + => m_callbackFailure = m_callbackFailure is null + ? failure + : new AggregateException("Multiple native viewport callbacks failed in the same frame.", m_callbackFailure, failure); } diff --git a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs index 4d667bf36..6ea88aaa0 100644 --- a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs +++ b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs @@ -102,9 +102,14 @@ public static NativeDeploymentIndex Decode(ReadOnlySpan bytes) JsonElement root = document.RootElement; string[] names = root.EnumerateObject().Select(static entry => entry.Name).Order(StringComparer.Ordinal).ToArray(); if (!names.SequenceEqual(new[] { "files", "libraries", "targetId" }, StringComparer.Ordinal)) + { throw new InvalidDataException("The native deployment index must contain its exact current fields."); - return new(root.GetProperty("targetId").GetString()!, ReadMapping(root.GetProperty("libraries")), - ReadMapping(root.GetProperty("files"))); + } + return new( + root.GetProperty("targetId").GetString()!, + ReadMapping(root.GetProperty("libraries")), + ReadMapping(root.GetProperty("files")) + ); } catch (Exception failure) when (failure is JsonException or ArgumentException or InvalidOperationException) { @@ -133,8 +138,10 @@ string name ) { string file = Resolve(nativeDirectory, name, libraries); if (!OperatingSystem.IsWindows() || file.StartsWith(@"\\?\", StringComparison.Ordinal) - || file.StartsWith(@"\\.\", StringComparison.Ordinal)) + || file.StartsWith(@"\\.\", StringComparison.Ordinal) + ) { return file; + } // Windows native loading can reject ordinary paths even below MAX_PATH. // Apply loading syntax only after validating the actual deployment boundary. return file.StartsWith(@"\\", StringComparison.Ordinal) ? @"\\?\UNC\" + file[2..] : @"\\?\" + file; @@ -168,8 +175,10 @@ private static IReadOnlyDictionary Freeze(IReadOnlyDictionary= 0 || alias is "." or ".." || string.IsNullOrWhiteSpace(path) || path.Contains('\\') - || path.Contains(':') || path.Split('/').Any(static part => part is "" or "." or "..")) + || path.Contains(':') || path.Split('/').Any(static part => part is "" or "." or "..") + ) { throw new ArgumentException("Native deployment aliases and paths must be assigned and portable.", nameof(mapping)); + } result.Add(alias, path); } return new ReadOnlyDictionary(result); @@ -182,15 +191,21 @@ IReadOnlyDictionary mapping ) { ArgumentException.ThrowIfNullOrWhiteSpace(name); if (!mapping.TryGetValue(name, out string? relative)) + { throw new FileNotFoundException($"No native deployment entry is registered for '{name}'."); + } string file = PathBoundary.RequireUnlinkedPath(directory, PathBoundary.Resolve(directory, relative)); if (!File.Exists(file)) + { throw new FileNotFoundException("An explicitly deployed native payload is absent.", file); + } return file; } private static IReadOnlyDictionary ReadMapping(JsonElement element) - => element.EnumerateObject().ToDictionary(static entry => entry.Name, static entry => entry.Value.GetString()!, StringComparer.Ordinal); + => element + .EnumerateObject() + .ToDictionary(static entry => entry.Name, static entry => entry.Value.GetString()!, StringComparer.Ordinal); private static void WriteMapping( Utf8JsonWriter writer, @@ -199,7 +214,9 @@ IReadOnlyDictionary mapping ) { writer.WriteStartObject(name); foreach ((string alias, string path) in mapping) + { writer.WriteString(alias, path); + } writer.WriteEndObject(); } } diff --git a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllLoader.cs b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllLoader.cs index 94643755f..21ab9483e 100644 --- a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllLoader.cs +++ b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDllLoader.cs @@ -65,12 +65,20 @@ private static NativeDeploymentIndex ReadIndex(string nativeRoot) { string path = Path.Combine(nativeRoot, NativeDeploymentIndex.C_FILE_NAME); if (!File.Exists(path)) - throw new FileNotFoundException("The product has no explicit native deployment index. Prepare the product before starting it.", path); + { + throw new FileNotFoundException( + "The product has no explicit native deployment index. Prepare the product before starting it.", + path + ); + } return NativeDeploymentIndex.Decode(File.ReadAllBytes(path)); } - [UnconditionalSuppressMessage("SingleFile", "IL3000", - Justification = "Assembly-local outputs serve isolated hosts; an empty bundled assembly location explicitly selects the application directory.")] + [UnconditionalSuppressMessage( + "SingleFile", + "IL3000", + Justification = "Assembly-local outputs serve isolated hosts; an empty bundled assembly location explicitly selects the application directory." + )] private static string ResolveOutputRoot() { string location = typeof(NativeDllLoader).Assembly.Location; @@ -83,8 +91,9 @@ string parameterName ) { ArgumentException.ThrowIfNullOrWhiteSpace(fileName, parameterName); if (fileName is "." or ".." || fileName != Path.GetFileName(fileName) - || fileName.IndexOfAny(['*', '?', '/', '\\']) >= 0) + || fileName.IndexOfAny(['*', '?', '/', '\\']) >= 0 + ) { throw new ArgumentException("Native discovery requires an exact file name.", parameterName); + } } - } diff --git a/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs b/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs index 34301810c..f43f6e8cb 100644 --- a/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs +++ b/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs @@ -25,8 +25,10 @@ public static class MiniAudioToolchain new NativeStaticBuildDefinition( "backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/Native/StaticLibraries.cmake", ["extern/miniaudio"], - ["libminiaudio"]), - bindingDefinition: "backends/MiniAudio/native/Inno.Native.MiniAudio/Bindings/bindings.props"); + ["libminiaudio"] + ), + bindingDefinition: "backends/MiniAudio/native/Inno.Native.MiniAudio/Bindings/bindings.props" + ); /// /// Builds the component using the explicitly selected target SDK and validates the complete native product. @@ -54,26 +56,41 @@ public static async Task BuildAsync( NativeToolchainSelection selection = context.RequireToolchain(); string source = componentDescriptor.GetToolchainRoot(context.engineRoot); NativeBuildRecipe recipe = CreateRecipe(context); - return await NativeArtifactPublisher.PublishAsync(context, recipe, + return await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - source, "miniaudio", S_ARGUMENTS, token).ConfigureAwait(false); + ) => + { + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + source, + "miniaudio", + S_ARGUMENTS, + token + ).ConfigureAwait(false); string library = NativeCMakeExecutor.FindOutput(scoped, build, "*miniaudio" + selection.sharedLibraryExtension); string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); - - }, cancellationToken, describeOutputs: static ( + }, + cancellationToken, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray() + ).ConfigureAwait(false); } /// @@ -102,10 +119,20 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) - throw new NotSupportedException("This standalone producer requires shared linkage; static products use the declared aggregate recipe."); + { + throw new NotSupportedException( + "This standalone producer requires shared linkage; static products use the declared aggregate recipe." + ); + } string implementation = componentDescriptor.GetToolchainRoot(context.engineRoot); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, "miniaudio", selection.targetId, - [Path.Combine(context.engineRoot, "extern", "miniaudio"), Path.Combine(implementation, "CMakeLists.txt")], S_ARGUMENTS, - [Path.Combine(implementation, "MiniAudioToolchain.cs")]); + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "miniaudio", + selection.targetId, + [Path.Combine(context.engineRoot, "extern", "miniaudio"), Path.Combine(implementation, "CMakeLists.txt")], + S_ARGUMENTS, + [Path.Combine(implementation, "MiniAudioToolchain.cs")] + ); } } diff --git a/backends/MiniAudio/native/Inno.Native.MiniAudio/MiniAudio.cs b/backends/MiniAudio/native/Inno.Native.MiniAudio/MiniAudio.cs index ff47c4515..4f4c5d201 100644 --- a/backends/MiniAudio/native/Inno.Native.MiniAudio/MiniAudio.cs +++ b/backends/MiniAudio/native/Inno.Native.MiniAudio/MiniAudio.cs @@ -23,4 +23,4 @@ static MiniAudio() Load(NativeDllLoader.FindNativeLibrary(LibName)); #endif } -} \ No newline at end of file +} diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs index f9f27cd9b..7447ec624 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs @@ -11,7 +11,8 @@ public sealed class MiniAudioBackendProvider : AudioBackendProvider /// /// Creates an explicitly composed registration for the bundled implementation. /// - public MiniAudioBackendProvider() : base(AudioBackendId.miniAudio) { } + public MiniAudioBackendProvider() + : base(AudioBackendId.miniAudio) {} /// public override IAudioDevice CreateDevice(AudioBackendOptions options) @@ -19,4 +20,3 @@ public override IAudioDevice CreateDevice(AudioBackendOptions options) return new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = options.noDevice }); } } - diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs index e5ca77713..4ac81fc2c 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs @@ -24,7 +24,8 @@ SemaphoreSlim slots try { using AsyncFlowControl? suppression = ExecutionContext.IsFlowSuppressed() - ? null : ExecutionContext.SuppressFlow(); + ? null + : ExecutionContext.SuppressFlow(); completion = Task.Run(() => PrepareAsync(source, slots), CancellationToken.None); } catch @@ -46,10 +47,14 @@ SemaphoreSlim slots public void Dispose() { if (!completion.IsCompleted) + { throw new InvalidOperationException("Encoded preparation must drain before releasing its owner."); + } _ = completion.Exception; if (File.Exists(path)) + { File.Delete(path); + } m_cancellation.Dispose(); } @@ -70,21 +75,30 @@ SemaphoreSlim slots Directory.CreateDirectory(Path.GetDirectoryName(path)!); using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); long copied = 0; - using (var output = new FileStream(candidate, FileMode.CreateNew, FileAccess.Write, - FileShare.None, buffer.Length, FileOptions.Asynchronous)) - { + using (var output = new FileStream( + candidate, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + buffer.Length, + FileOptions.Asynchronous + )) { int count; while ((count = await reader.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) != 0) { copied = checked(copied + count); if (copied > length) + { throw new InvalidDataException("Encoded audio exceeds its declared length."); + } hash.AppendData(buffer, 0, count); await output.WriteAsync(buffer.AsMemory(0, count), cancellationToken).ConfigureAwait(false); } - if (copied != length || !string.Equals(Convert.ToHexString(hash.GetHashAndReset()), - contentHash, StringComparison.Ordinal)) - { + if (copied != length || !string.Equals( + Convert.ToHexString(hash.GetHashAndReset()), + contentHash, + StringComparison.Ordinal + )) { throw new InvalidDataException("Encoded audio does not match its content identity."); } await output.FlushAsync(cancellationToken).ConfigureAwait(false); @@ -97,7 +111,9 @@ SemaphoreSlim slots try { if (File.Exists(candidate)) + { File.Delete(candidate); + } } finally { diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs index 3bf3685c3..bf23e5fbe 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs @@ -4,9 +4,9 @@ using System.Runtime.InteropServices; using System.Text; using System.Threading; - using Inno.Audio; using Inno.Native.MiniAudio; + using NativeApi = Inno.Native.MiniAudio.MiniAudio; namespace Inno.Adapter.Audio.MiniAudio; @@ -42,9 +42,7 @@ public sealed unsafe class MiniAudioDevice : AudioDevice, IAudioDevice /// Creates a MiniAudio device using the default operating-system output device. /// public MiniAudioDevice() - : this(new MiniAudioDeviceOptions()) - { - } + : this(new MiniAudioDeviceOptions()) {} /// /// Creates one MiniAudio backend generation with explicit output and headless settings. @@ -71,7 +69,9 @@ public MiniAudioDevice(MiniAudioDeviceOptions options) config.NoDevice = m_options.noDevice ? 1u : 0u; MaResult result = NativeApi.Raw.EngineInit(&config, m_engine); if (result != MaResult.MA_SUCCESS) + { throw new InvalidOperationException($"MiniAudio engine initialization failed with result '{result}'."); + } m_engineInitialized = true; int actualSampleRate = checked((int)NativeApi.Raw.EngineGetSampleRate(m_engine)); @@ -79,7 +79,8 @@ public MiniAudioDevice(MiniAudioDeviceOptions options) if (m_options.noDevice) { m_processBuffer = (float*)NativeMemory.AllocZeroed( - checked((nuint)(C_PROCESS_BLOCK_FRAMES * (uint)m_options.channels * sizeof(float)))); + checked((nuint)(C_PROCESS_BLOCK_FRAMES * (uint)m_options.channels * sizeof(float))) + ); m_state = AudioDeviceState.Muted; } else @@ -90,7 +91,9 @@ public MiniAudioDevice(MiniAudioDeviceOptions options) catch { if (m_engineInitialized) + { NativeApi.Raw.EngineUninit(m_engine); + } NativeMemory.Free(m_engine); throw; } @@ -116,8 +119,8 @@ public MiniAudioDevice(MiniAudioDeviceOptions options) /// public double dspTime => m_engineInitialized - ? NativeApi.Raw.EngineGetTimeInPcmFrames(m_engine) / (double)capabilities.sampleRate - : 0d; + ? NativeApi.Raw.EngineGetTimeInPcmFrames(m_engine) / (double)capabilities.sampleRate + : 0d; /// /// Gets current native resource counts and approximate decoded storage. @@ -129,7 +132,8 @@ public AudioStatistics statistics m_clips.Values .Where(static descriptor => descriptor.loadMode == AudioClipLoadMode.Decode) .Sum(EstimateDecodedByteLength), - 0); + 0 + ); AudioClipHandle IAudioDevice.CreateClip( AudioClipDescriptor descriptor, @@ -138,10 +142,12 @@ IAudioClipSource source EnsureActive(); ArgumentNullException.ThrowIfNull(source); if (m_clips.Count >= m_options.limits.clips) + { return default; + } if (!descriptor.codec.isValid || descriptor.channels <= 0 || descriptor.sampleRate <= 0 - || descriptor.encodedByteLength != source.length || !Enum.IsDefined(descriptor.loadMode)) - { + || descriptor.encodedByteLength != source.length || !Enum.IsDefined(descriptor.loadMode) + ) { throw new ArgumentException("An audio descriptor must match its immutable source.", nameof(descriptor)); } MiniAudioClipSourceLease lease = m_encodedArtifacts.Acquire(source); @@ -154,9 +160,13 @@ IAudioClipSource source private bool PrepareNativeClip(ulong identity) { if (m_clipSources.ContainsKey(identity)) + { return true; + } if (m_failedClips.Contains(identity)) + { return false; + } MiniAudioClipPreparation preparation = m_clipPreparations[identity].preparation; if (!preparation.completion.IsCompletedSuccessfully) { @@ -169,16 +179,19 @@ private bool PrepareNativeClip(ulong identity) } AudioClipDescriptor descriptor = m_clips[identity]; MaResourceManagerDataSource* source = (MaResourceManagerDataSource*)NativeMemory.AllocZeroed( - (nuint)sizeof(MaResourceManagerDataSource)); - uint flags = (uint)(MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC | - (descriptor.loadMode == AudioClipLoadMode.Stream - ? MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM : MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE)); + (nuint)sizeof(MaResourceManagerDataSource) + ); + uint flags = (uint)(MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC + | (descriptor.loadMode == AudioClipLoadMode.Stream + ? MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM + : MaResourceManagerDataSourceFlags.MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE)); MaResult result; try { int pathByteCount = Encoding.UTF8.GetByteCount(preparation.path); Span pathBytes = pathByteCount < 1024 - ? stackalloc byte[1024] : new byte[checked(pathByteCount + 1)]; + ? stackalloc byte[1024] + : new byte[checked(pathByteCount + 1)]; Encoding.UTF8.GetBytes(preparation.path, pathBytes); pathBytes[pathByteCount] = 0; fixed (byte* pathPointer = pathBytes) @@ -189,7 +202,8 @@ private bool PrepareNativeClip(ulong identity) (sbyte*)pathPointer, flags, null, - source); + source + ); } } catch @@ -211,9 +225,13 @@ AudioClipState IAudioDevice.GetClipState(AudioClipHandle clip) { DeviceHandleIdentity identity = GetHandleIdentity(clip); if (identity.generation != generation || !m_clips.ContainsKey(identity.value)) + { return AudioClipState.Failed; + } if (!PrepareNativeClip(identity.value)) + { return m_failedClips.Contains(identity.value) ? AudioClipState.Failed : AudioClipState.Preparing; + } nint pointer = m_clipSources[identity.value]; return NativeApi.Raw.ResourceManagerDataSourceResult((MaResourceManagerDataSource*)pointer) switch { @@ -227,13 +245,15 @@ bool IAudioDevice.DestroyClip(AudioClipHandle clip) { EnsureActive(); DeviceHandleIdentity identity = GetHandleIdentity(clip); - if (identity.generation != generation || - m_voices.Values.Any(voice => voice.clipIdentity == identity.value)) - { + if (identity.generation != generation + || m_voices.Values.Any(voice => voice.clipIdentity == identity.value) + ) { return false; } if (!m_clips.ContainsKey(identity.value)) + { return false; + } ReleaseClipSource(identity.value); m_clips.Remove(identity.value); return true; @@ -247,34 +267,45 @@ AudioDeviceVoiceHandle IAudioDevice.Play( ) { EnsureActive(); if (m_voices.Count + m_completions.Count >= m_options.limits.voices) + { return default; + } if (!options.bus.isValid) + { return default; + } DeviceHandleIdentity clipIdentity = GetHandleIdentity(clip); DeviceHandleIdentity busIdentity = GetHandleIdentity(bus); if (clipIdentity.generation != generation || !m_clips.TryGetValue(clipIdentity.value, out AudioClipDescriptor descriptor)) + { return default; + } if (!PrepareNativeClip(clipIdentity.value)) + { return default; + } if (busIdentity.generation != generation || !m_buses.TryGetValue(busIdentity.value, out BusRecord? busRecord)) - return default; - if (scheduledDspTime is double startTime && - (double.IsNaN(startTime) || double.IsInfinity(startTime) || startTime < 0d)) { return default; } + if (scheduledDspTime is double startTime + && (double.IsNaN(startTime) || double.IsInfinity(startTime) || startTime < 0d) + ) { + return default; + } string path = m_clipPreparations[clipIdentity.value].preparation.path; int pathByteCount = Encoding.UTF8.GetByteCount(path); Span pathBytes = pathByteCount < 1024 - ? stackalloc byte[1024] : new byte[checked(pathByteCount + 1)]; + ? stackalloc byte[1024] + : new byte[checked(pathByteCount + 1)]; Encoding.UTF8.GetBytes(path, pathBytes); pathBytes[pathByteCount] = 0; MaSound* sound = (MaSound*)NativeMemory.AllocZeroed((nuint)sizeof(MaSound)); MaSound* soundPointer = sound; uint flags = descriptor.loadMode == AudioClipLoadMode.Stream - ? (uint)MaSoundFlags.MA_SOUND_FLAG_STREAM - : (uint)MaSoundFlags.MA_SOUND_FLAG_DECODE; + ? (uint)MaSoundFlags.MA_SOUND_FLAG_STREAM + : (uint)MaSoundFlags.MA_SOUND_FLAG_DECODE; flags |= (uint)MaSoundFlags.MA_SOUND_FLAG_ASYNC; MaResult initResult; try @@ -287,7 +318,8 @@ AudioDeviceVoiceHandle IAudioDevice.Play( flags, busRecord.group, null, - soundPointer); + soundPointer + ); } } catch @@ -310,7 +342,8 @@ AudioDeviceVoiceHandle IAudioDevice.Play( { NativeApi.Raw.SoundSetStartTimeInPcmFrames( soundPointer, - checked((ulong)Math.Round(scheduled * capabilities.sampleRate))); + checked((ulong)Math.Round(scheduled * capabilities.sampleRate)) + ); playbackState = AudioPlaybackState.Scheduled; } @@ -337,7 +370,9 @@ AudioDeviceVoiceHandle IAudioDevice.Play( bool IAudioDevice.Stop(AudioDeviceVoiceHandle voice) { if (!TryGetVoice(voice, out ulong identity, out VoiceRecord record)) + { return false; + } NativeApi.Raw.SoundStop(record.sound); CompleteVoice(identity, record, AudioCompletionReason.Stopped); return true; @@ -346,9 +381,13 @@ bool IAudioDevice.Stop(AudioDeviceVoiceHandle voice) bool IAudioDevice.Pause(AudioDeviceVoiceHandle voice) { if (!TryGetVoice(voice, out _, out VoiceRecord record) || record.state == AudioPlaybackState.Paused) + { return false; + } if (NativeApi.Raw.SoundStop(record.sound) != MaResult.MA_SUCCESS) + { return false; + } record.state = AudioPlaybackState.Paused; return true; } @@ -356,12 +395,16 @@ bool IAudioDevice.Pause(AudioDeviceVoiceHandle voice) bool IAudioDevice.Resume(AudioDeviceVoiceHandle voice) { if (!TryGetVoice(voice, out _, out VoiceRecord record) || record.state != AudioPlaybackState.Paused) + { return false; + } if (NativeApi.Raw.SoundStart(record.sound) != MaResult.MA_SUCCESS) + { return false; + } record.state = record.scheduledDspTime is double scheduled && scheduled > dspTime - ? AudioPlaybackState.Scheduled - : AudioPlaybackState.Playing; + ? AudioPlaybackState.Scheduled + : AudioPlaybackState.Playing; return true; } @@ -370,7 +413,9 @@ bool IAudioDevice.Seek( TimeSpan position ) { if (position < TimeSpan.Zero || !TryGetVoice(voice, out _, out VoiceRecord record)) + { return false; + } ulong frame = checked((ulong)Math.Round(position.TotalSeconds * capabilities.sampleRate)); return NativeApi.Raw.SoundSeekToPcmFrame(record.sound, frame) == MaResult.MA_SUCCESS; } @@ -380,9 +425,13 @@ bool IAudioDevice.SetVoiceParameters( AudioVoiceParameters parameters ) { if (parameters.pitch <= 0f) + { return false; + } if (!TryGetVoice(voice, out _, out VoiceRecord record)) + { return false; + } ApplyVoiceParameters(record.sound, parameters); return true; } @@ -394,7 +443,8 @@ out AudioPlaybackState playbackState if (TryGetVoice(voice, out _, out VoiceRecord record)) { MaResult preparation = NativeApi.Raw.ResourceManagerDataSourceResult( - record.sound->PResourceManagerDataSource); + record.sound->PResourceManagerDataSource + ); playbackState = preparation == MaResult.MA_BUSY ? AudioPlaybackState.Preparing : record.state; return true; } @@ -408,14 +458,18 @@ AudioBusHandle parent ) { EnsureActive(); if (!id.isValid || m_buses.Count >= m_options.limits.buses) + { return default; + } BusRecord? parentRecord = null; if (parent.isValid) { DeviceHandleIdentity parentIdentity = GetHandleIdentity(parent); if (parentIdentity.generation != generation || !m_buses.TryGetValue(parentIdentity.value, out parentRecord)) + { return default; + } } else if (id != AudioBusId.master) { @@ -427,7 +481,8 @@ AudioBusHandle parent m_engine, 0, parentRecord is null ? null : parentRecord.group, - group); + group + ); if (result != MaResult.MA_SUCCESS) { NativeMemory.Free(group); @@ -436,8 +491,8 @@ AudioBusHandle parent ulong identity = m_nextIdentity++; void* target = parentRecord is null - ? NativeApi.Raw.EngineGetEndpoint(m_engine) - : parentRecord.group; + ? NativeApi.Raw.EngineGetEndpoint(m_engine) + : parentRecord.group; m_buses.Add(identity, new BusRecord(id, parentRecord, group, target)); return CreateBusHandle(identity, generation); } @@ -446,12 +501,14 @@ bool IAudioDevice.DestroyBus(AudioBusHandle bus) { EnsureActive(); if (!TryGetBus(bus, out ulong identity, out BusRecord record)) - return false; - if (m_buses.Values.Any(candidate => candidate.parent == record) || - m_voices.Values.Any(voice => voice.bus == record)) { return false; } + if (m_buses.Values.Any(candidate => candidate.parent == record) + || m_voices.Values.Any(voice => voice.bus == record) + ) { + return false; + } ReleaseBus(record); m_buses.Remove(identity); return true; @@ -462,7 +519,9 @@ bool IAudioDevice.SetBusVolume( float volume ) { if (!float.IsFinite(volume) || volume < 0f || !TryGetBus(bus, out _, out BusRecord record)) + { return false; + } record.volume = volume; ApplyBusVolume(record); return true; @@ -473,7 +532,9 @@ bool IAudioDevice.SetBusMuted( bool muted ) { if (!TryGetBus(bus, out _, out BusRecord record)) + { return false; + } record.muted = muted; ApplyBusVolume(record); return true; @@ -484,14 +545,20 @@ bool IAudioDevice.SetBusPaused( bool paused ) { if (!TryGetBus(bus, out _, out BusRecord record)) + { return false; + } if (record.paused == paused) + { return true; + } MaResult result = paused - ? NativeApi.Raw.SoundGroupStop(record.group) - : NativeApi.Raw.SoundGroupStart(record.group); + ? NativeApi.Raw.SoundGroupStop(record.group) + : NativeApi.Raw.SoundGroupStart(record.group); if (result != MaResult.MA_SUCCESS) + { return false; + } record.paused = paused; return true; } @@ -502,15 +569,19 @@ AudioProcessorConfiguration processor ) { ArgumentNullException.ThrowIfNull(processor); if (!TryGetBus(bus, out _, out BusRecord record)) + { return false; + } NativeProcessor? nativeProcessor = CreateProcessor(processor); if (nativeProcessor is null) + { return false; + } - if (NativeApi.Raw.NodeDetachOutputBus(record.tail, 0) != MaResult.MA_SUCCESS || - NativeApi.Raw.NodeAttachOutputBus(record.tail, 0, nativeProcessor.node, 0) != MaResult.MA_SUCCESS || - NativeApi.Raw.NodeAttachOutputBus(nativeProcessor.node, 0, record.target, 0) != MaResult.MA_SUCCESS) - { + if (NativeApi.Raw.NodeDetachOutputBus(record.tail, 0) != MaResult.MA_SUCCESS + || NativeApi.Raw.NodeAttachOutputBus(record.tail, 0, nativeProcessor.node, 0) != MaResult.MA_SUCCESS + || NativeApi.Raw.NodeAttachOutputBus(nativeProcessor.node, 0, record.target, 0) != MaResult.MA_SUCCESS + ) { NativeApi.Raw.NodeDetachOutputBus(record.tail, 0); NativeApi.Raw.NodeDetachOutputBus(nativeProcessor.node, 0); NativeApi.Raw.NodeAttachOutputBus(record.tail, 0, record.target, 0); @@ -527,7 +598,9 @@ AudioListenerHandle IAudioDevice.CreateListener(AudioListenerState state) { EnsureActive(); if (m_listeners.Count >= capabilities.maxListeners) + { return default; + } uint listenerIndex = Enumerable.Range(0, capabilities.maxListeners) .Select(static index => checked((uint)index)) .First(index => !m_listeners.ContainsValue(index)); @@ -543,7 +616,9 @@ AudioListenerState state ) { DeviceHandleIdentity identity = GetHandleIdentity(listener); if (identity.generation != generation || !m_listeners.TryGetValue(identity.value, out uint listenerIndex)) + { return false; + } ApplyListener(listenerIndex, state, true); return true; } @@ -552,7 +627,9 @@ bool IAudioDevice.DestroyListener(AudioListenerHandle listener) { DeviceHandleIdentity identity = GetHandleIdentity(listener); if (identity.generation != generation || !m_listeners.Remove(identity.value, out uint listenerIndex)) + { return false; + } NativeApi.Raw.EngineListenerSetEnabled(m_engine, listenerIndex, 0); return true; } @@ -560,37 +637,52 @@ bool IAudioDevice.DestroyListener(AudioListenerHandle listener) void IAudioDevice.Update(float deltaTime) { if (deltaTime < 0f) + { throw new ArgumentOutOfRangeException(nameof(deltaTime)); + } EnsureActive(); foreach (ulong identity in m_clips.Keys) + { _ = PrepareNativeClip(identity); + } if (m_options.noDevice) + { ProcessHeadlessFrames(deltaTime); + } else + { UpdateOutputDeviceState(); + } if (m_state == AudioDeviceState.Lost) + { return; + } double currentTime = dspTime; foreach ((ulong identity, VoiceRecord record) in m_voices.ToArray()) { MaResult preparation = NativeApi.Raw.ResourceManagerDataSourceResult( - record.sound->PResourceManagerDataSource); + record.sound->PResourceManagerDataSource + ); if (preparation == MaResult.MA_BUSY) + { continue; + } if (preparation != MaResult.MA_SUCCESS) { CompleteVoice(identity, record, AudioCompletionReason.DecodeFailed); continue; } - if (record.state == AudioPlaybackState.Scheduled && - record.scheduledDspTime is double scheduled && scheduled <= currentTime) - { + if (record.state == AudioPlaybackState.Scheduled + && record.scheduledDspTime is double scheduled && scheduled <= currentTime + ) { record.state = AudioPlaybackState.Playing; } if (NativeApi.Raw.SoundAtEnd(record.sound) != 0) + { CompleteVoice(identity, record, AudioCompletionReason.NaturalEnd); + } } } @@ -607,10 +699,14 @@ bool IAudioDevice.TryDequeueCompletion(out AudioDeviceCompletion completion) public void Dispose() { if (m_state == AudioDeviceState.Disposed) + { return; + } foreach (VoiceRecord voice in m_voices.Values.ToArray()) + { ReleaseVoice(voice); + } m_voices.Clear(); m_encodedArtifacts.CancelPreparation(); @@ -622,7 +718,9 @@ public void Dispose() m_encodedArtifacts.Dispose(); foreach (BusRecord bus in m_buses.Values.OrderByDescending(GetBusDepth).ToArray()) + { ReleaseBus(bus); + } m_buses.Clear(); if (m_engineInitialized) @@ -656,8 +754,8 @@ private static uint NextGeneration() { uint generation = unchecked((uint)Interlocked.Increment(ref S_NEXT_GENERATION)); return generation == 0 - ? unchecked((uint)Interlocked.Increment(ref S_NEXT_GENERATION)) - : generation; + ? unchecked((uint)Interlocked.Increment(ref S_NEXT_GENERATION)) + : generation; } private static long EstimateDecodedByteLength(AudioClipDescriptor descriptor) @@ -677,7 +775,9 @@ private static int GetBusDepth(BusRecord bus) { int depth = 0; for (BusRecord? current = bus.parent; current is not null; current = current.parent) + { depth++; + } return depth; } @@ -689,20 +789,22 @@ float defaultValue foreach (AudioProcessorParameter parameter in processor.parameters) { if (parameter.id == id) + { return parameter.value; + } } return defaultValue; } private static MaAttenuationModel ToNativeDistanceModel(AudioDistanceModel model) => model switch - { - AudioDistanceModel.None => MaAttenuationModel.ma_attenuation_model_none, - AudioDistanceModel.Inverse => MaAttenuationModel.ma_attenuation_model_inverse, - AudioDistanceModel.Linear => MaAttenuationModel.ma_attenuation_model_linear, - AudioDistanceModel.Exponential => MaAttenuationModel.ma_attenuation_model_exponential, - _ => throw new ArgumentOutOfRangeException(nameof(model)) - }; + { + AudioDistanceModel.None => MaAttenuationModel.ma_attenuation_model_none, + AudioDistanceModel.Inverse => MaAttenuationModel.ma_attenuation_model_inverse, + AudioDistanceModel.Linear => MaAttenuationModel.ma_attenuation_model_linear, + AudioDistanceModel.Exponential => MaAttenuationModel.ma_attenuation_model_exponential, + _ => throw new ArgumentOutOfRangeException(nameof(model)) + }; private static void ApplyVoiceParameters( MaSound* sound, @@ -730,7 +832,8 @@ AudioVoiceParameters parameters sound, spatial.coneInnerAngle * (MathF.PI / 180f), spatial.coneOuterAngle * (MathF.PI / 180f), - spatial.coneOuterGain); + spatial.coneOuterGain + ); NativeApi.Raw.SoundSetDopplerFactor(sound, spatial.dopplerFactor); } @@ -761,12 +864,14 @@ bool enabled checked((uint)m_options.channels), checked((uint)capabilities.sampleRate), delayFrames, - decay); + decay + ); MaResult result = NativeApi.Raw.DelayNodeInit( NativeApi.Raw.EngineGetNodeGraph(m_engine), &config, null, - node); + node + ); if (result != MaResult.MA_SUCCESS) { NativeMemory.Free(node); @@ -775,14 +880,14 @@ bool enabled return new NativeProcessor(node, true); } - if (processor.id != AudioProcessorId.lowPass && - processor.id != AudioProcessorId.highPass && - processor.id != AudioProcessorId.bandPass && - processor.id != AudioProcessorId.notch && - processor.id != AudioProcessorId.peak && - processor.id != AudioProcessorId.lowShelf && - processor.id != AudioProcessorId.highShelf) - { + if (processor.id != AudioProcessorId.lowPass + && processor.id != AudioProcessorId.highPass + && processor.id != AudioProcessorId.bandPass + && processor.id != AudioProcessorId.notch + && processor.id != AudioProcessorId.peak + && processor.id != AudioProcessorId.lowShelf + && processor.id != AudioProcessorId.highShelf + ) { return null; } @@ -795,12 +900,14 @@ bool enabled coefficients.b2, coefficients.a0, coefficients.a1, - coefficients.a2); + coefficients.a2 + ); MaResult biquadResult = NativeApi.Raw.BiquadNodeInit( NativeApi.Raw.EngineGetNodeGraph(m_engine), &biquadConfig, null, - biquad); + biquad + ); if (biquadResult != MaResult.MA_SUCCESS) { NativeMemory.Free(biquad); @@ -814,7 +921,8 @@ private BiquadCoefficients CreateBiquadCoefficients(AudioProcessorConfiguration double frequency = Math.Clamp( GetParameter(processor, AudioParameterId.frequency, processor.id == AudioProcessorId.lowPass ? 20000f : 200f), 1f, - capabilities.sampleRate * 0.499f); + capabilities.sampleRate * 0.499f + ); double quality = Math.Max(0.001, GetParameter(processor, AudioParameterId.quality, 0.70710678f)); double gain = GetParameter(processor, AudioParameterId.gainDecibels, 0f); double shelfSlope = Math.Max(0.001, GetParameter(processor, AudioParameterId.shelfSlope, 1f)); @@ -824,17 +932,34 @@ private BiquadCoefficients CreateBiquadCoefficients(AudioProcessorConfiguration double alpha = sine / (2d * quality); if (processor.id == AudioProcessorId.lowPass) + { return new((1d - cosine) / 2d, 1d - cosine, (1d - cosine) / 2d, 1d + alpha, -2d * cosine, 1d - alpha); + } if (processor.id == AudioProcessorId.highPass) + { return new((1d + cosine) / 2d, -(1d + cosine), (1d + cosine) / 2d, 1d + alpha, -2d * cosine, 1d - alpha); + } if (processor.id == AudioProcessorId.bandPass) + { return new(alpha, 0d, -alpha, 1d + alpha, -2d * cosine, 1d - alpha); + } if (processor.id == AudioProcessorId.notch) + { return new(1d, -2d * cosine, 1d, 1d + alpha, -2d * cosine, 1d - alpha); + } double amplitude = Math.Pow(10d, gain / 40d); if (processor.id == AudioProcessorId.peak) - return new(1d + alpha * amplitude, -2d * cosine, 1d - alpha * amplitude, 1d + alpha / amplitude, -2d * cosine, 1d - alpha / amplitude); + { + return new( + 1d + alpha * amplitude, + -2d * cosine, + 1d - alpha * amplitude, + 1d + alpha / amplitude, + -2d * cosine, + 1d - alpha / amplitude + ); + } double shelfAlpha = sine / 2d * Math.Sqrt((amplitude + 1d / amplitude) * (1d / shelfSlope - 1d) + 2d); double twoRootAAlpha = 2d * Math.Sqrt(amplitude) * shelfAlpha; @@ -846,7 +971,8 @@ private BiquadCoefficients CreateBiquadCoefficients(AudioProcessorConfiguration amplitude * ((amplitude + 1d) - (amplitude - 1d) * cosine - twoRootAAlpha), (amplitude + 1d) + (amplitude - 1d) * cosine + twoRootAAlpha, -2d * ((amplitude - 1d) + (amplitude + 1d) * cosine), - (amplitude + 1d) + (amplitude - 1d) * cosine - twoRootAAlpha); + (amplitude + 1d) + (amplitude - 1d) * cosine - twoRootAAlpha + ); } return new( amplitude * ((amplitude + 1d) + (amplitude - 1d) * cosine + twoRootAAlpha), @@ -854,7 +980,8 @@ private BiquadCoefficients CreateBiquadCoefficients(AudioProcessorConfiguration amplitude * ((amplitude + 1d) + (amplitude - 1d) * cosine - twoRootAAlpha), (amplitude + 1d) - (amplitude - 1d) * cosine + twoRootAAlpha, 2d * ((amplitude - 1d) - (amplitude + 1d) * cosine), - (amplitude + 1d) - (amplitude - 1d) * cosine - twoRootAAlpha); + (amplitude + 1d) - (amplitude - 1d) * cosine - twoRootAAlpha + ); } private void ProcessHeadlessFrames(float deltaTime) @@ -864,21 +991,21 @@ private void ProcessHeadlessFrames(float deltaTime) { ulong requested = (ulong)Math.Min(Math.Floor(m_pendingProcessFrames), C_PROCESS_BLOCK_FRAMES); ulong read = 0; - MaResult result = NativeApi.Raw.EngineReadPcmFrames( - m_engine, - m_processBuffer, - requested, - &read); + MaResult result = NativeApi.Raw.EngineReadPcmFrames(m_engine, m_processBuffer, requested, &read); if (result != MaResult.MA_SUCCESS) { m_state = AudioDeviceState.Lost; foreach ((ulong identity, VoiceRecord voice) in m_voices.ToArray()) + { CompleteVoice(identity, voice, AudioCompletionReason.DeviceLost); + } return; } m_pendingProcessFrames -= read; if (read == 0) + { return; + } } } @@ -903,7 +1030,9 @@ private void UpdateOutputDeviceState() } m_state = AudioDeviceState.Lost; foreach ((ulong identity, VoiceRecord voice) in m_voices.ToArray()) + { CompleteVoice(identity, voice, AudioCompletionReason.DeviceLost); + } } private bool TryGetVoice( @@ -959,23 +1088,31 @@ private void ReleaseBus(BusRecord bus) { NativeApi.Raw.SoundGroupUninit(bus.group); for (int index = bus.processors.Count - 1; index >= 0; index--) + { ReleaseProcessor(bus.processors[index]); + } NativeMemory.Free(bus.group); } private static void ReleaseProcessor(NativeProcessor processor) { if (processor.isDelay) + { NativeApi.Raw.DelayNodeUninit((MaDelayNode*)processor.node, null); + } else + { NativeApi.Raw.BiquadNodeUninit((MaBiquadNode*)processor.node, null); + } NativeMemory.Free(processor.node); } private void EnsureActive() { if (m_state == AudioDeviceState.Disposed) + { throw new ObjectDisposedException(nameof(MiniAudioDevice)); + } } private sealed class BusRecord diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs index 3eff9d54e..222b3a804 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs @@ -39,7 +39,9 @@ internal MiniAudioDeviceOptions Validate() ArgumentOutOfRangeException.ThrowIfNegativeOrZero(channels); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); if (listenerCount is < 1 or > 4) + { throw new ArgumentOutOfRangeException(nameof(listenerCount), "MiniAudio supports between one and four listeners."); + } return this; } } diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs index baafb2ea6..8dd092f0b 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs @@ -21,15 +21,18 @@ internal MiniAudioClipSourceLease Acquire(IAudioClipSource source) ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(source); if (source.length < 0 || source.contentHash is not { Length: 64 } - || source.contentHash.Any(static character => !Uri.IsHexDigit(character))) - { + || source.contentHash.Any(static character => !Uri.IsHexDigit(character)) + ) { throw new ArgumentException("Encoded audio requires an exact length and SHA-256 identity.", nameof(source)); } string hash = source.contentHash.ToUpperInvariant(); if (!m_entries.TryGetValue(hash, out MiniAudioClipPreparation? entry)) { - entry = new MiniAudioClipPreparation(source, - Path.Combine(m_root, hash + "-" + Guid.NewGuid().ToString("N") + ".audio"), m_slots); + entry = new MiniAudioClipPreparation( + source, + Path.Combine(m_root, hash + "-" + Guid.NewGuid().ToString("N") + ".audio"), + m_slots + ); m_entries.Add(hash, entry); } else if (entry.length != source.length) @@ -45,7 +48,9 @@ internal void Release(MiniAudioClipPreparation entry) if (entry.references > 1) { if (!entry.completion.IsCompleted) + { throw new RetirementPendingException("Shared encoded audio preparation still borrows its first clip source."); + } entry.references--; return; } @@ -65,21 +70,31 @@ internal void Release(MiniAudioClipPreparation entry) internal void CancelPreparation() { foreach (MiniAudioClipPreparation entry in m_entries.Values) + { entry.Cancel(); + } foreach (MiniAudioClipPreparation entry in m_retiring) + { entry.Cancel(); + } } /// public void Dispose() { if (m_disposed) + { return; + } CancelPreparation(); if (m_entries.Count != 0 || m_retiring.Count != 0) + { throw new RetirementPendingException("Encoded audio still has clip owners awaiting retirement."); + } if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: false); + } m_slots.Dispose(); m_disposed = true; } @@ -87,8 +102,8 @@ public void Dispose() private void RemoveActiveEntry(MiniAudioClipPreparation entry) { if (m_entries.TryGetValue(entry.contentHash, out MiniAudioClipPreparation? current) - && ReferenceEquals(current, entry)) - { + && ReferenceEquals(current, entry) + ) { m_entries.Remove(entry.contentHash); } } diff --git a/backends/RmlUi/build/Inno.Build.Toolchains.UI/UiToolchain.cs b/backends/RmlUi/build/Inno.Build.Toolchains.UI/UiToolchain.cs index c37c326c2..07b43bc37 100644 --- a/backends/RmlUi/build/Inno.Build.Toolchains.UI/UiToolchain.cs +++ b/backends/RmlUi/build/Inno.Build.Toolchains.UI/UiToolchain.cs @@ -21,10 +21,19 @@ public static class UiToolchain "backends/RmlUi/build/Inno.Build.Toolchains.UI/Inno.Build.Toolchains.UI.csproj", new NativeStaticBuildDefinition( "backends/RmlUi/build/Inno.Build.Toolchains.UI/Native/StaticLibraries.cmake", - ["extern/freetype", "extern/harfbuzz", "extern/RmlUi", "backends/RmlUi/native/Inno.Native.UI/Native/include", "backends/RmlUi/native/Inno.Native.UI/Native/src", "backends/RmlUi/native/Inno.Native.UI/Native/CMakeLists.txt"], + [ + "extern/freetype", + "extern/harfbuzz", + "extern/RmlUi", + "backends/RmlUi/native/Inno.Native.UI/Native/include", + "backends/RmlUi/native/Inno.Native.UI/Native/src", + "backends/RmlUi/native/Inno.Native.UI/Native/CMakeLists.txt" + ], ["libinno-ui", "librmlui"], - nativeSourceDirectory: "backends/RmlUi/native/Inno.Native.UI"), - bindingDefinition: "backends/RmlUi/native/Inno.Native.UI/Bindings/bindings.props"); + nativeSourceDirectory: "backends/RmlUi/native/Inno.Native.UI" + ), + bindingDefinition: "backends/RmlUi/native/Inno.Native.UI/Bindings/bindings.props" + ); /// /// Builds the component using the explicitly selected target SDK and validates the complete native product. @@ -52,26 +61,41 @@ public static async Task BuildAsync( NativeToolchainSelection selection = context.RequireToolchain(); string source = Path.Combine(componentDescriptor.GetNativeRoot(context.engineRoot), "Native"); NativeBuildRecipe recipe = CreateRecipe(context); - return await NativeArtifactPublisher.PublishAsync(context, recipe, + return await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - source, "inno-ui", [], token).ConfigureAwait(false); + ) => + { + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + source, + "inno-ui", + [], + token + ).ConfigureAwait(false); string library = NativeCMakeExecutor.FindOutput(scoped, build, "*inno-ui" + selection.sharedLibraryExtension); string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); - - }, cancellationToken, describeOutputs: static ( + }, + cancellationToken, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray() + ).ConfigureAwait(false); } /// @@ -100,9 +124,19 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) - throw new NotSupportedException("This standalone producer requires shared linkage; static products use the declared aggregate recipe."); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, "ui", selection.targetId, + { + throw new NotSupportedException( + "This standalone producer requires shared linkage; static products use the declared aggregate recipe." + ); + } + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "ui", + selection.targetId, componentDescriptor.staticBuild!.inputPaths.Select(path => Path.GetFullPath(path, context.engineRoot)), - [], [Path.Combine(componentDescriptor.GetToolchainRoot(context.engineRoot), "UiToolchain.cs")]); + [], + [Path.Combine(componentDescriptor.GetToolchainRoot(context.engineRoot), "UiToolchain.cs")] + ); } } diff --git a/backends/RmlUi/native/Inno.Native.UI/UiNative.cs b/backends/RmlUi/native/Inno.Native.UI/UiNative.cs index 5802629bd..72dba1333 100644 --- a/backends/RmlUi/native/Inno.Native.UI/UiNative.cs +++ b/backends/RmlUi/native/Inno.Native.UI/UiNative.cs @@ -23,4 +23,4 @@ static UiNative() Load(NativeDllLoader.FindNativeLibrary(LibName)); #endif } -} \ No newline at end of file +} diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs index f249edd69..5f1059474 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs @@ -4,7 +4,6 @@ using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; - using Inno.Assets; using Inno.Text; using Inno.UI; @@ -17,22 +16,45 @@ namespace Inno.Adapter.UI.RmlUi.Authoring; /// public sealed class RmlUiDocumentFrontend : IUiDocumentFrontend { - private static readonly Regex S_FONT_FACE = new(@"@font-face\s*\{(?[^{}]*)\}", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_PROPERTY = new(@"(?[a-z-]+)\s*:\s*(?[^;]+);?", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_FAMILY = new(@"(?im)(font-family\s*:\s*)(?[^;}]+)", - RegexOptions.Compiled | RegexOptions.CultureInvariant); - private static readonly Regex S_URL = new(@"^url\(\s*['""]?(?[^)'""]+)['""]?\s*\)$", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_LINK = new(@"]*>", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_HREF = new(@"\bhref\s*=\s*['""](?[^'""]+)['""]", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_IMPORT = new(@"@import\s+(?:url\(\s*)?['""](?[^'""]+)['""]\s*\)?\s*;", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - private static readonly Regex S_FONT_SOURCE = new(@"(?\bsrc\s*:\s*url\(\s*['""]?)(?[^)'""]+)(?['""]?\s*\))", - RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + private static readonly Regex S_FONT_FACE = new( + @"@font-face\s*\{(?[^{}]*)\}", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex S_PROPERTY = new( + @"(?[a-z-]+)\s*:\s*(?[^;]+);?", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex S_FAMILY = new( + @"(?im)(font-family\s*:\s*)(?[^;}]+)", + RegexOptions.Compiled | RegexOptions.CultureInvariant + ); + + private static readonly Regex S_URL = new( + @"^url\(\s*['""]?(?[^)'""]+)['""]?\s*\)$", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex S_LINK = new( + @"]*>", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex S_HREF = new( + @"\bhref\s*=\s*['""](?[^'""]+)['""]", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex S_IMPORT = new( + @"@import\s+(?:url\(\s*)?['""](?[^'""]+)['""]\s*\)?\s*;", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); + + private static readonly Regex S_FONT_SOURCE = new( + @"(?\bsrc\s*:\s*url\(\s*['""]?)(?[^)'""]+)(?['""]?\s*\))", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant + ); /// /// Gets the RML source language identifier accepted by this frontend. @@ -52,9 +74,13 @@ public UiDocumentAnalysis Analyze(UiDocumentSourceFile source) { ArgumentNullException.ThrowIfNull(source); if (string.IsNullOrWhiteSpace(source.text)) + { return new(null, [new("RML_EMPTY", "The RML document is empty.", 1, 1)]); + } if (!source.text.Contains("(); var fonts = new List(); var families = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -72,12 +98,14 @@ public UiDocumentAnalysis Analyze(UiDocumentSourceFile source) { var properties = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (Match property in S_PROPERTY.Matches(match.Groups["body"].Value)) + { properties[property.Groups["name"].Value] = property.Groups["value"].Value.Trim(); + } properties.TryGetValue("src", out string? sourceValue); Match url = S_URL.Match(sourceValue ?? string.Empty); if (!properties.TryGetValue("font-family", out string? logical) - || !url.Success) - { + || !url.Success + ) { diagnostics.Add(new("RML_FONT_FACE_INVALID", "@font-face requires font-family and src: url(...).", 1, 1)); return string.Empty; } @@ -88,28 +116,35 @@ public UiDocumentAnalysis Analyze(UiDocumentSourceFile source) return string.Empty; } string physical = families.TryGetValue(logical, out string? existing) - ? existing : families[logical] = PrivateFamily(source.assetPath, logical); + ? existing + : families[logical] = PrivateFamily(source.assetPath, logical); string path = url.Groups["path"].Value.Trim(); try { AssetPath fontPath = path.Contains("::", StringComparison.Ordinal) - ? AssetPath.Parse(path) - : new AssetPath(documentPath.source, - Path.Combine(Path.GetDirectoryName(documentPath.localPath) ?? string.Empty, path) - .Replace('\\', '/')); + ? AssetPath.Parse(path) + : new AssetPath( + documentPath.source, + Path.Combine(Path.GetDirectoryName(documentPath.localPath) ?? string.Empty, path) + .Replace('\\', '/') + ); int weight = properties.TryGetValue("font-weight", out string? weightText) - ? weightText.ToLowerInvariant() switch - { - "normal" => 400, - "bold" => 700, - _ when int.TryParse(weightText, out int numeric) => numeric, - _ => -1 - } : 400; + ? weightText.ToLowerInvariant() switch + { + "normal" => 400, + "bold" => 700, + _ when int.TryParse(weightText, out int numeric) => numeric, + _ => -1 + } + : 400; if (weight is < 100 or > 1000) + { throw new ArgumentException("font-weight must be 100–1000, normal, or bold."); + } TextFontStyle style = properties.TryGetValue("font-style", out string? styleText) - && styleText.Equals("italic", StringComparison.OrdinalIgnoreCase) - ? TextFontStyle.Italic : TextFontStyle.Normal; + && styleText.Equals("italic", StringComparison.OrdinalIgnoreCase) + ? TextFontStyle.Italic + : TextFontStyle.Normal; fonts.Add(new(fontPath.ToString(), physical, style, weight)); } catch (Exception exception) when (exception is ArgumentException or InvalidOperationException) @@ -125,7 +160,8 @@ _ when int.TryParse(weightText, out int numeric) => numeric, { string logical = requested[index].Trim('\'', '"', ' '); requested[index] = families.TryGetValue(logical, out string? physical) - ? physical : PrivateFamily(source.assetPath, "missing/" + logical); + ? physical + : PrivateFamily(source.assetPath, "missing/" + logical); } return match.Groups[1].Value + string.Join(", ", requested); }); @@ -144,17 +180,20 @@ private static string ExpandStyles( UiDocumentSourceFile source, AssetPath documentPath, HashSet active - ) - => S_LINK.Replace(source.text, match => + ) => S_LINK.Replace(source.text, match => + { + Match href = S_HREF.Match(match.Value); + if (!href.Success || !href.Groups["path"].Value.EndsWith(".rcss", StringComparison.OrdinalIgnoreCase)) { - Match href = S_HREF.Match(match.Value); - if (!href.Success || !href.Groups["path"].Value.EndsWith(".rcss", StringComparison.OrdinalIgnoreCase)) - return match.Value; - if (source.readSource is null) - throw new InvalidOperationException("External RCSS requires an import source reader."); - AssetPath sheetPath = ResolvePath(documentPath, href.Groups["path"].Value); - return ""; - }); + return match.Value; + } + if (source.readSource is null) + { + throw new InvalidOperationException("External RCSS requires an import source reader."); + } + AssetPath sheetPath = ResolvePath(documentPath, href.Groups["path"].Value); + return ""; + }); private static string ExpandSheet( Func readSource, @@ -162,16 +201,19 @@ private static string ExpandSheet( HashSet active ) { if (!active.Add(path)) + { throw new InvalidDataException($"RCSS import cycle includes '{path}'."); + } try { string text = readSource(path); text = S_IMPORT.Replace(text, match => ExpandSheet(readSource, ResolvePath(path, match.Groups["path"].Value), active)); - return S_FONT_FACE.Replace(text, match => S_FONT_SOURCE.Replace(match.Value, font => + return S_FONT_FACE.Replace(text, match => S_FONT_SOURCE.Replace(match.Value, font => ( font.Groups["prefix"].Value + FormatExplicitPath(ResolvePath(path, font.Groups["path"].Value.Trim())) - + font.Groups["suffix"].Value)); + + font.Groups["suffix"].Value + ))); } finally { @@ -184,23 +226,33 @@ private static AssetPath ResolvePath( string relative ) { if (relative.Contains("::", StringComparison.Ordinal)) + { return AssetPath.Parse(relative); + } if (Path.IsPathRooted(relative)) + { throw new ArgumentException("An RCSS path must be source-relative.", nameof(relative)); + } var segments = new List(owner.localPath.Replace('\\', '/').Split('/')); segments.RemoveAt(segments.Count - 1); foreach (string segment in relative.Replace('\\', '/').Split('/')) { if (segment is "" or ".") + { continue; + } if (segment == "..") { if (segments.Count == 0) + { throw new ArgumentException("An RCSS path escapes its asset source.", nameof(relative)); + } segments.RemoveAt(segments.Count - 1); } else + { segments.Add(segment); + } } return new AssetPath(owner.source, string.Join('/', segments)); } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentImporter.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentImporter.cs index cab40a929..7fdaf6fef 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentImporter.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentImporter.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets.Pipeline; using Inno.UI; using Inno.UI.Assets; @@ -38,11 +37,11 @@ protected override ValueTask ImportAsync( AssetImportContext context, AssetImportWriter output, CancellationToken cancellationToken - ) - => UiDocumentImportPipeline.ImportAsync( - context, - output, - RmlUiIdentifiers.documentLanguage, - RmlUiIdentifiers.backend.value, - cancellationToken); + ) => UiDocumentImportPipeline.ImportAsync( + context, + output, + RmlUiIdentifiers.documentLanguage, + RmlUiIdentifiers.backend.value, + cancellationToken + ); } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs index c6db940a4..d19047973 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs @@ -5,7 +5,6 @@ using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; - using Inno.Core.Input; using Inno.Core.Mathematics; using Inno.Native.UI; @@ -21,10 +20,14 @@ public sealed unsafe class RmlUiBackend : IUiBackend { private static readonly UiBackendCapabilities S_CAPABILITIES = new( [RmlUiIdentifiers.documentLanguage], - supportsFontCollectionFaces: false); + supportsFontCollectionFaces: false + ); + private static readonly Regex S_FONT_FAMILY = new( @"(?im)(font-family\s*:\s*)([^;}]+)", - RegexOptions.Compiled | RegexOptions.CultureInvariant); + RegexOptions.Compiled | RegexOptions.CultureInvariant + ); + private InnoUIRmlUiAdapterRuntime* m_runtime; private readonly Dictionary m_fontAliases = new(StringComparer.OrdinalIgnoreCase); private bool m_disposed; @@ -46,7 +49,9 @@ public RmlUiBackend() { m_runtime = RmlUiNativeErrors.CreateSession(); if (m_runtime == null) + { throw CreateNativeException("create UI runtime", Result.UnknownError); + } } /// @@ -62,8 +67,17 @@ public UiContextHandle CreateContext(UiContextOptions options) { EnsureActive(); ulong value = 0; - ThrowIfFailed(RmlUiNativeRuntime.CreateContext( - m_runtime, options.name, options.width, options.height, options.density, ref value), "create UI context"); + ThrowIfFailed( + RmlUiNativeRuntime.CreateContext( + m_runtime, + options.name, + options.width, + options.height, + options.density, + ref value + ), + "create UI context" + ); return new UiContextHandle(value); } @@ -104,7 +118,9 @@ float density ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); if (!float.IsFinite(density) || density <= 0f) + { throw new ArgumentOutOfRangeException(nameof(density)); + } ThrowIfFailed(RmlUiNativeRuntime.SetViewport(m_runtime, Require(context), width, height, density), "set UI viewport"); } @@ -128,8 +144,16 @@ UiDocumentSource source ArgumentNullException.ThrowIfNull(source); EnsureRml(source.language); ulong document = 0; - ThrowIfFailed(RmlUiNativeRuntime.LoadDocument( - m_runtime, Require(context), RewriteFontFamilies(source.text), source.sourceUri, ref document), "load UI document"); + ThrowIfFailed( + RmlUiNativeRuntime.LoadDocument( + m_runtime, + Require(context), + RewriteFontFamilies(source.text), + source.sourceUri, + ref document + ), + "load UI document" + ); return new UiDocumentHandle(document); } @@ -212,8 +236,17 @@ string text ArgumentException.ThrowIfNullOrWhiteSpace(elementId); ArgumentNullException.ThrowIfNull(text); byte changed = 0; - ThrowIfFailed(RmlUiNativeRuntime.SetInnerMarkup( - m_runtime, Require(context), Require(document), elementId, WebUtility.HtmlEncode(text), ref changed), "set UI text"); + ThrowIfFailed( + RmlUiNativeRuntime.SetInnerMarkup( + m_runtime, + Require(context), + Require(document), + elementId, + WebUtility.HtmlEncode(text), + ref changed + ), + "set UI text" + ); return changed != 0; } @@ -245,13 +278,17 @@ UiDocumentFragment content ArgumentException.ThrowIfNullOrWhiteSpace(elementId); EnsureRml(content.language); byte changed = 0; - ThrowIfFailed(RmlUiNativeRuntime.SetInnerMarkup( - m_runtime, - Require(context), - Require(document), - elementId, - RewriteFontFamilies(content.text), - ref changed), "set UI content"); + ThrowIfFailed( + RmlUiNativeRuntime.SetInnerMarkup( + m_runtime, + Require(context), + Require(document), + elementId, + RewriteFontFamilies(content.text), + ref changed + ), + "set UI content" + ); return changed != 0; } @@ -288,14 +325,18 @@ string value ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(value); byte changed = 0; - ThrowIfFailed(RmlUiNativeRuntime.SetAttribute( - m_runtime, - Require(context), - Require(document), - elementId, - name, - value, - ref changed), "set UI attribute"); + ThrowIfFailed( + RmlUiNativeRuntime.SetAttribute( + m_runtime, + Require(context), + Require(document), + elementId, + name, + value, + ref changed + ), + "set UI attribute" + ); return changed != 0; } @@ -331,14 +372,18 @@ bool active ArgumentException.ThrowIfNullOrWhiteSpace(elementId); ArgumentException.ThrowIfNullOrWhiteSpace(className); byte changed = 0; - ThrowIfFailed(RmlUiNativeRuntime.SetClass( - m_runtime, - Require(context), - Require(document), - elementId, - className, - active ? (byte)1 : (byte)0, - ref changed), "set UI class"); + ThrowIfFailed( + RmlUiNativeRuntime.SetClass( + m_runtime, + Require(context), + Require(document), + elementId, + className, + active ? (byte)1 : (byte)0, + ref changed + ), + "set UI class" + ); return changed != 0; } @@ -352,24 +397,31 @@ public void RegisterFont(UiFontRegistration registration) { EnsureActive(); if (registration.faceIndex != 0) + { throw new UiCapabilityUnavailableException(UiBackendCapability.FontCollectionFaceSelection); + } // All weights and styles of one declared family must share one native family. // Document imports give each family a private name before it reaches this backend. - string familyHash = Convert.ToHexString(SHA256.HashData( - Encoding.UTF8.GetBytes(registration.family.ToLowerInvariant()))).ToLowerInvariant(); + string familyHash = Convert.ToHexString( + SHA256.HashData(Encoding.UTF8.GetBytes(registration.family.ToLowerInvariant())) + ).ToLowerInvariant(); string physicalFamily = $"__inno_{familyHash[..24]}"; ReadOnlySpan data = registration.data.Span; using var family = new RmlUiUtf8String(physicalFamily); fixed (byte* bytes = data) { - ThrowIfFailed(RmlUiNativeRuntime.LoadFont( - m_runtime, - bytes, - checked((uint)data.Length), - family.pointer, - (int)registration.style, - registration.weight, - 0), "register UI font"); + ThrowIfFailed( + RmlUiNativeRuntime.LoadFont( + m_runtime, + bytes, + checked((uint)data.Length), + family.pointer, + (int)registration.style, + registration.weight, + 0 + ), + "register UI font" + ); } m_fontAliases[registration.family] = physicalFamily; } @@ -398,14 +450,18 @@ UiTextureData texture using var nativeSource = new RmlUiUtf8String(source); fixed (byte* pixelPointer = pixels) { - ThrowIfFailed(RmlUiNativeRuntime.RegisterTexture( - m_runtime, - Require(context), - nativeSource.pointer, - texture.width, - texture.height, - pixelPointer, - checked((uint)pixels.Length)), "register UI texture"); + ThrowIfFailed( + RmlUiNativeRuntime.RegisterTexture( + m_runtime, + Require(context), + nativeSource.pointer, + texture.width, + texture.height, + pixelPointer, + checked((uint)pixels.Length) + ), + "register UI texture" + ); } } @@ -427,8 +483,16 @@ Vector2 position ) { EnsureActive(); byte hit = 0; - ThrowIfFailed(RmlUiNativeRuntime.HasElementAtPoint(m_runtime, Require(context), - (int)position.x, (int)position.y, ref hit), "query UI element hit"); + ThrowIfFailed( + RmlUiNativeRuntime.HasElementAtPoint( + m_runtime, + Require(context), + (int)position.x, + (int)position.y, + ref hit + ), + "query UI element hit" + ); return hit != 0; } @@ -449,21 +513,48 @@ UiInputSnapshot input ArgumentNullException.ThrowIfNull(input); ulong handle = Require(context); int modifiers = (int)input.modifiers; - ThrowIfFailed(RmlUiNativeRuntime.ProcessMouseMove( - m_runtime, handle, (int)input.mousePosition.x, (int)input.mousePosition.y, modifiers), "process UI pointer position"); + ThrowIfFailed( + RmlUiNativeRuntime.ProcessMouseMove( + m_runtime, + handle, + (int)input.mousePosition.x, + (int)input.mousePosition.y, + modifiers + ), + "process UI pointer position" + ); if (input.scrollDelta.x != 0f || input.scrollDelta.y != 0f) { - ThrowIfFailed(RmlUiNativeRuntime.ProcessMouseWheel( - m_runtime, handle, input.scrollDelta.x, input.scrollDelta.y, modifiers), "process UI pointer wheel"); + ThrowIfFailed( + RmlUiNativeRuntime.ProcessMouseWheel( + m_runtime, + handle, + input.scrollDelta.x, + input.scrollDelta.y, + modifiers + ), + "process UI pointer wheel" + ); } foreach (MouseButton button in input.buttonsPressed) + { ThrowIfFailed(RmlUiNativeRuntime.ProcessMouseButton(m_runtime, handle, (int)button, 1, modifiers), "process UI pointer press"); + } foreach (MouseButton button in input.buttonsReleased) - ThrowIfFailed(RmlUiNativeRuntime.ProcessMouseButton(m_runtime, handle, (int)button, 0, modifiers), "process UI pointer release"); + { + ThrowIfFailed( + RmlUiNativeRuntime.ProcessMouseButton(m_runtime, handle, (int)button, 0, modifiers), + "process UI pointer release" + ); + } foreach (KeyCode key in input.keysPressed) + { ThrowIfFailed(RmlUiNativeRuntime.ProcessKey(m_runtime, handle, (int)key, 1, modifiers), "process UI key press"); + } foreach (KeyCode key in input.keysReleased) + { ThrowIfFailed(RmlUiNativeRuntime.ProcessKey(m_runtime, handle, (int)key, 0, modifiers), "process UI key release"); + } foreach (string text in input.textInput) { using var nativeText = new RmlUiUtf8String(text); @@ -508,16 +599,23 @@ public UiRenderFrame Render(UiContextHandle context) builder.AddMeshUpdate(new(mesh.Id), mesh.Revision, vertices, indices); } foreach (ulong mesh in CopyReleasedMeshes(handle, info.ReleasedMeshCount)) + { builder.AddReleasedMesh(new(mesh)); + } InnoUIRmlUiAdapterDrawCommand[] nativeCommands = new InnoUIRmlUiAdapterDrawCommand[checked((int)info.CommandCount)]; CopyCommands(handle, nativeCommands); foreach (InnoUIRmlUiAdapterDrawCommand value in nativeCommands) - builder.AddCommand(new( - new(value.MeshId), - new(value.TextureId), - value.ScissorEnabled != 0, - new(value.ScissorX, value.ScissorY, value.ScissorWidth, value.ScissorHeight))); + { + builder.AddCommand( + new( + new(value.MeshId), + new(value.TextureId), + value.ScissorEnabled != 0, + new(value.ScissorX, value.ScissorY, value.ScissorWidth, value.ScissorHeight) + ) + ); + } for (int index = 0; index < checked((int)info.TextureUpdateCount); index++) { @@ -525,15 +623,18 @@ public UiRenderFrame Render(UiContextHandle context) ThrowIfFailed(RmlUiNativeFrames.GetTextureInfo(m_runtime, handle, checked((ulong)index), ref texture), "query UI texture"); byte[] pixels = new byte[checked((int)texture.ByteLength)]; if (pixels.Length > 0) - ThrowIfFailed(RmlUiNativeFrames.CopyTexturePixels( - m_runtime, - handle, - texture.Id, - pixels.AsSpan()), "copy UI texture"); + { + ThrowIfFailed( + RmlUiNativeFrames.CopyTexturePixels(m_runtime, handle, texture.Id, pixels.AsSpan()), + "copy UI texture" + ); + } builder.AddTextureUpdate(new(texture.Id), texture.Revision, texture.Width, texture.Height, pixels); } foreach (ulong texture in CopyReleasedTextures(handle, info.ReleasedTextureCount)) + { builder.AddReleasedTexture(new(texture)); + } UiRenderFrame frame = builder.Build(); ThrowIfFailed(RmlUiNativeFrames.FinishFrame(m_runtime, handle), "finish UI frame transfer"); @@ -569,15 +670,15 @@ public IReadOnlyList DrainEvents(UiContextHandle context) InnoUIRmlUiAdapterEventInfo info = default; ThrowIfFailed(RmlUiNativeFrames.GetEventInfo(m_runtime, handle, checked((ulong)index), ref info), "query UI event"); byte[] targetBytes = new byte[checked((int)info.TargetIdLength + 1)]; - ThrowIfFailed(RmlUiNativeFrames.CopyEventTargetId( - m_runtime, - handle, - checked((ulong)index), - targetBytes.AsSpan()), "copy UI event target"); + ThrowIfFailed( + RmlUiNativeFrames.CopyEventTargetId(m_runtime, handle, checked((ulong)index), targetBytes.AsSpan()), + "copy UI event target" + ); events[index] = new UiEvent( (UiEventType)info.Type, new UiDocumentHandle(info.Document), - Encoding.UTF8.GetString(targetBytes, 0, checked((int)info.TargetIdLength))); + Encoding.UTF8.GetString(targetBytes, 0, checked((int)info.TargetIdLength)) + ); } return events; } @@ -593,7 +694,9 @@ public IReadOnlyList DrainEvents(UiContextHandle context) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; RmlUiNativeErrors.DestroySession(m_runtime); m_runtime = null; @@ -605,7 +708,9 @@ private void CopyMeshVertices( InnoUIRmlUiAdapterVertex[] values ) { if (values.Length == 0) + { return; + } ThrowIfFailed(RmlUiNativeFrames.CopyMeshVertices(m_runtime, context, mesh, values), "copy UI mesh vertices"); } @@ -615,12 +720,13 @@ private void CopyMeshIndices( uint[] values ) { if (values.Length == 0) + { return; - ThrowIfFailed(RmlUiNativeFrames.CopyMeshIndices( - m_runtime, - context, - mesh, - values.AsSpan()), "copy UI mesh indices"); + } + ThrowIfFailed( + RmlUiNativeFrames.CopyMeshIndices(m_runtime, context, mesh, values.AsSpan()), + "copy UI mesh indices" + ); } private void CopyCommands( @@ -628,7 +734,9 @@ private void CopyCommands( InnoUIRmlUiAdapterDrawCommand[] values ) { if (values.Length == 0) + { return; + } ThrowIfFailed(RmlUiNativeFrames.CopyCommands(m_runtime, context, values), "copy UI commands"); } @@ -638,10 +746,12 @@ ulong count ) { ulong[] values = new ulong[checked((int)count)]; if (values.Length > 0) - ThrowIfFailed(RmlUiNativeFrames.CopyReleasedMeshes( - m_runtime, - context, - values.AsSpan()), "copy released UI meshes"); + { + ThrowIfFailed( + RmlUiNativeFrames.CopyReleasedMeshes(m_runtime, context, values.AsSpan()), + "copy released UI meshes" + ); + } return values; } @@ -651,17 +761,21 @@ ulong count ) { ulong[] values = new ulong[checked((int)count)]; if (values.Length > 0) - ThrowIfFailed(RmlUiNativeFrames.CopyReleasedTextures( - m_runtime, - context, - values.AsSpan()), "copy released UI textures"); + { + ThrowIfFailed( + RmlUiNativeFrames.CopyReleasedTextures(m_runtime, context, values.AsSpan()), + "copy released UI textures" + ); + } return values; } private static void EnsureRml(UiDocumentLanguageId language) { if (language != RmlUiIdentifiers.documentLanguage) + { throw new NotSupportedException($"RmlUi adapter cannot decode UI language '{language}'."); + } } private string RewriteFontFamilies(string source) @@ -688,14 +802,15 @@ private static void ThrowIfFailed( string operation ) { if (result != Result.Success) + { throw CreateNativeException(operation, result); + } } private static InvalidOperationException CreateNativeException( string operation, Result result ) { - string message = result switch { Result.InvalidArgument => "invalid argument", diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs index a5f8b57f0..1d2751f49 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs @@ -10,7 +10,8 @@ public sealed class RmlUiBackendProvider : UiBackendProvider /// /// Creates a composition-owned registration for the bundled implementation. /// - public RmlUiBackendProvider() : base(UiBackendId.rmlUi) { } + public RmlUiBackendProvider() + : base(UiBackendId.rmlUi) {} /// public override IUiBackend CreateBackend() => new RmlUiBackend(); diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs index 848b21315..5be1d6706 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs @@ -25,16 +25,22 @@ internal static void CheckBridge( BgcsInnoRmluiError* error ) { if (status == 0 && error == null) + { return; + } try { string? message = error == null ? null : Marshal.PtrToStringUTF8((nint)UiNative.Raw.BgcsInnoRmluiErrorMessage(error)); - throw new InvalidOperationException($"The UI bridge failed with status {status}: {message ?? "No native error text is available."}"); + throw new InvalidOperationException( + $"The UI bridge failed with status {status}: {message ?? "No native error text is available."}" + ); } finally { if (error != null) + { UiNative.Raw.BgcsInnoRmluiErrorRelease(error); + } } } } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeFrames.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeFrames.cs index b58f5cf98..ffd286b59 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeFrames.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeFrames.cs @@ -11,13 +11,7 @@ ulong context ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ClearEvents( - runtime, - context, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.ClearEvents(runtime, context, &result, &error), error); return result; } @@ -29,6 +23,7 @@ Span commands Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterDrawCommand* commandsPointer = commands) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyCommands( runtime, @@ -36,8 +31,11 @@ Span commands (InnoUIRmlUiAdapterDrawCommandNative*)commandsPointer, checked((ulong)commands.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -50,6 +48,7 @@ Span targetId Result result = default; BgcsInnoRmluiError* error = null; fixed (byte* targetIdPointer = targetId) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyEventTargetId( runtime, @@ -58,8 +57,11 @@ Span targetId (sbyte*)targetIdPointer, checked((ulong)targetId.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -72,6 +74,7 @@ Span indices Result result = default; BgcsInnoRmluiError* error = null; fixed (uint* indicesPointer = indices) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyMeshIndices( runtime, @@ -80,8 +83,11 @@ Span indices (uint*)indicesPointer, checked((ulong)indices.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -94,6 +100,7 @@ Span vertices Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterVertex* verticesPointer = vertices) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyMeshVertices( runtime, @@ -102,8 +109,11 @@ Span vertices (InnoUIRmlUiAdapterVertexNative*)verticesPointer, checked((ulong)vertices.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -115,6 +125,7 @@ Span meshes Result result = default; BgcsInnoRmluiError* error = null; fixed (ulong* meshesPointer = meshes) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyReleasedMeshes( runtime, @@ -122,8 +133,11 @@ Span meshes (ulong*)meshesPointer, checked((ulong)meshes.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -135,6 +149,7 @@ Span textures Result result = default; BgcsInnoRmluiError* error = null; fixed (ulong* texturesPointer = textures) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyReleasedTextures( runtime, @@ -142,8 +157,11 @@ Span textures (ulong*)texturesPointer, checked((ulong)textures.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -156,6 +174,7 @@ Span pixels Result result = default; BgcsInnoRmluiError* error = null; fixed (byte* pixelsPointer = pixels) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CopyTexturePixels( runtime, @@ -164,8 +183,11 @@ Span pixels (byte*)pixelsPointer, checked((ulong)pixels.Length), &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -175,13 +197,7 @@ ulong context ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.FinishFrame( - runtime, - context, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.FinishFrame(runtime, context, &result, &error), error); return result; } @@ -193,14 +209,12 @@ ref ulong count Result result = default; BgcsInnoRmluiError* error = null; fixed (ulong* countPointer = &count) + { RmlUiNativeErrors.CheckBridge( - UiNative.Raw.GetEventCount( - runtime, - context, - countPointer, - &result, - &error), - error); + UiNative.Raw.GetEventCount(runtime, context, countPointer, &result, &error), + error + ); + } return result; } @@ -213,6 +227,7 @@ ref InnoUIRmlUiAdapterEventInfo eventInfo Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterEventInfo* eventInfoPointer = &eventInfo) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.GetEventInfo( runtime, @@ -220,8 +235,11 @@ ref InnoUIRmlUiAdapterEventInfo eventInfo index, (InnoUIRmlUiAdapterEventInfoNative*)eventInfoPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -234,6 +252,7 @@ ref InnoUIRmlUiAdapterMeshInfo mesh Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterMeshInfo* meshPointer = &mesh) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.GetMeshInfo( runtime, @@ -241,8 +260,11 @@ ref InnoUIRmlUiAdapterMeshInfo mesh index, (InnoUIRmlUiAdapterMeshInfoNative*)meshPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -255,6 +277,7 @@ ref InnoUIRmlUiAdapterTextureInfo texture Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterTextureInfo* texturePointer = &texture) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.GetTextureInfo( runtime, @@ -262,8 +285,11 @@ ref InnoUIRmlUiAdapterTextureInfo texture index, (InnoUIRmlUiAdapterTextureInfoNative*)texturePointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -275,14 +301,18 @@ ref InnoUIRmlUiAdapterFrameInfo frame Result result = default; BgcsInnoRmluiError* error = null; fixed (InnoUIRmlUiAdapterFrameInfo* framePointer = &frame) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.Render( runtime, context, (InnoUIRmlUiAdapterFrameInfoNative*)framePointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeRuntime.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeRuntime.cs index 62cfcb061..d912bfa54 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeRuntime.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeRuntime.cs @@ -12,14 +12,7 @@ ulong document ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.CloseDocument( - runtime, - context, - document, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.CloseDocument(runtime, context, document, &result, &error), error); return result; } @@ -35,6 +28,7 @@ ref ulong context BgcsInnoRmluiError* error = null; using var nameText = new RmlUiUtf8String(name); fixed (ulong* contextPointer = &context) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.CreateContext( runtime, @@ -44,8 +38,11 @@ ref ulong context density, contextPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -55,13 +52,7 @@ ulong context ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.DestroyContext( - runtime, - context, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.DestroyContext(runtime, context, &result, &error), error); return result; } @@ -75,16 +66,12 @@ ref byte hit Result result = default; BgcsInnoRmluiError* error = null; fixed (byte* hitPointer = &hit) + { RmlUiNativeErrors.CheckBridge( - UiNative.Raw.HasElementAtPoint( - runtime, - context, - x, - y, - hitPointer, - &result, - &error), - error); + UiNative.Raw.HasElementAtPoint(runtime, context, x, y, hitPointer, &result, &error), + error + ); + } return result; } @@ -95,14 +82,7 @@ ulong document ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.HideDocument( - runtime, - context, - document, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.HideDocument(runtime, context, document, &result, &error), error); return result; } @@ -118,6 +98,7 @@ ref ulong document using var markupText = new RmlUiUtf8String(markup); using var sourceUrlText = new RmlUiUtf8String(sourceUrl); fixed (ulong* documentPointer = &document) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.LoadDocument( runtime, @@ -126,8 +107,11 @@ ref ulong document (sbyte*)sourceUrlText.pointer, documentPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -143,17 +127,9 @@ byte fallback Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.LoadFont( - runtime, - data, - dataLength, - (sbyte*)family, - style, - weight, - fallback, - &result, - &error), - error); + UiNative.Raw.LoadFont(runtime, data, dataLength, (sbyte*)family, style, weight, fallback, &result, &error), + error + ); return result; } @@ -167,15 +143,9 @@ int modifiers Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ProcessKey( - runtime, - context, - key, - down, - modifiers, - &result, - &error), - error); + UiNative.Raw.ProcessKey(runtime, context, key, down, modifiers, &result, &error), + error + ); return result; } @@ -189,15 +159,9 @@ int modifiers Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ProcessMouseButton( - runtime, - context, - button, - down, - modifiers, - &result, - &error), - error); + UiNative.Raw.ProcessMouseButton(runtime, context, button, down, modifiers, &result, &error), + error + ); return result; } @@ -211,15 +175,9 @@ int modifiers Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ProcessMouseMove( - runtime, - context, - x, - y, - modifiers, - &result, - &error), - error); + UiNative.Raw.ProcessMouseMove(runtime, context, x, y, modifiers, &result, &error), + error + ); return result; } @@ -233,15 +191,9 @@ int modifiers Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ProcessMouseWheel( - runtime, - context, - x, - y, - modifiers, - &result, - &error), - error); + UiNative.Raw.ProcessMouseWheel(runtime, context, x, y, modifiers, &result, &error), + error + ); return result; } @@ -252,14 +204,7 @@ internal static Result ProcessText( ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ProcessText( - runtime, - context, - (sbyte*)text, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.ProcessText(runtime, context, (sbyte*)text, &result, &error), error); return result; } @@ -284,8 +229,10 @@ ulong pixelCapacity pixels, pixelCapacity, &result, - &error), - error); + &error + ), + error + ); return result; } @@ -304,6 +251,7 @@ ref byte changed using var nameText = new RmlUiUtf8String(name); using var valueText = new RmlUiUtf8String(value); fixed (byte* changedPointer = &changed) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.SetAttribute( runtime, @@ -314,8 +262,11 @@ ref byte changed (sbyte*)valueText.pointer, changedPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -333,6 +284,7 @@ ref byte changed using var elementIdText = new RmlUiUtf8String(elementId); using var classNameText = new RmlUiUtf8String(className); fixed (byte* changedPointer = &changed) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.SetClass( runtime, @@ -343,8 +295,11 @@ ref byte changed active, changedPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -361,6 +316,7 @@ ref byte changed using var elementIdText = new RmlUiUtf8String(elementId); using var markupText = new RmlUiUtf8String(markup); fixed (byte* changedPointer = &changed) + { RmlUiNativeErrors.CheckBridge( UiNative.Raw.SetInnerMarkup( runtime, @@ -370,8 +326,11 @@ ref byte changed (sbyte*)markupText.pointer, changedPointer, &result, - &error), - error); + &error + ), + error + ); + } return result; } @@ -385,15 +344,9 @@ float density Result result = default; BgcsInnoRmluiError* error = null; RmlUiNativeErrors.CheckBridge( - UiNative.Raw.SetViewport( - runtime, - context, - width, - height, - density, - &result, - &error), - error); + UiNative.Raw.SetViewport(runtime, context, width, height, density, &result, &error), + error + ); return result; } @@ -404,14 +357,7 @@ ulong document ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.ShowDocument( - runtime, - context, - document, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.ShowDocument(runtime, context, document, &result, &error), error); return result; } @@ -421,13 +367,7 @@ ulong context ) { Result result = default; BgcsInnoRmluiError* error = null; - RmlUiNativeErrors.CheckBridge( - UiNative.Raw.Update( - runtime, - context, - &result, - &error), - error); + RmlUiNativeErrors.CheckBridge(UiNative.Raw.Update(runtime, context, &result, &error), error); return result; } } diff --git a/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs b/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs index fb5762dfa..0daf98ebc 100644 --- a/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs +++ b/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs @@ -24,8 +24,10 @@ public static class Sdl3Toolchain new NativeStaticBuildDefinition( "backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Native/StaticLibraries.cmake", ["extern/SDL"], - ["libSDL3"]), - bindingDefinition: "backends/Sdl3/native/Inno.Native.Sdl3/Bindings/bindings.props"); + ["libSDL3"] + ), + bindingDefinition: "backends/Sdl3/native/Inno.Native.Sdl3/Bindings/bindings.props" + ); /// /// Builds the component using the explicitly selected target SDK and validates the complete native product. @@ -53,26 +55,41 @@ public static async Task BuildAsync( NativeToolchainSelection selection = context.RequireToolchain(); string source = Path.Combine(context.engineRoot, "extern", "SDL"); NativeBuildRecipe recipe = CreateRecipe(context); - return await NativeArtifactPublisher.PublishAsync(context, recipe, + return await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - source, "SDL3-shared", S_ARGUMENTS, token).ConfigureAwait(false); + ) => + { + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + source, + "SDL3-shared", + S_ARGUMENTS, + token + ).ConfigureAwait(false); string library = NativeCMakeExecutor.FindOutput(scoped, build, "*SDL3" + selection.sharedLibraryExtension); string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); - - }, cancellationToken, describeOutputs: static ( + }, + cancellationToken, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray() + ).ConfigureAwait(false); } /// @@ -101,10 +118,20 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) - throw new NotSupportedException("This standalone producer requires shared linkage; static products use the declared aggregate recipe."); + { + throw new NotSupportedException( + "This standalone producer requires shared linkage; static products use the declared aggregate recipe." + ); + } string implementation = componentDescriptor.GetToolchainRoot(context.engineRoot); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, "sdl3", selection.targetId, - [Path.Combine(context.engineRoot, "extern", "SDL")], S_ARGUMENTS, - [Path.Combine(implementation, "Sdl3Toolchain.cs")]); + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "sdl3", + selection.targetId, + [Path.Combine(context.engineRoot, "extern", "SDL")], + S_ARGUMENTS, + [Path.Combine(implementation, "Sdl3Toolchain.cs")] + ); } } diff --git a/backends/Sdl3/native/Inno.Native.Sdl3/SDL.cs b/backends/Sdl3/native/Inno.Native.Sdl3/SDL.cs index 5d528de26..88a983344 100644 --- a/backends/Sdl3/native/Inno.Native.Sdl3/SDL.cs +++ b/backends/Sdl3/native/Inno.Native.Sdl3/SDL.cs @@ -23,4 +23,4 @@ static SDL() Load(NativeDllLoader.FindNativeLibrary(LibName)); #endif } -} \ No newline at end of file +} diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs index 06a1ef0a6..1afeea663 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs @@ -54,7 +54,9 @@ public static class Sdl3FolderDialog Thread.Sleep(10); } if (pumpFailure is not null) + { throw new InvalidOperationException("Platform event processing failed while selecting a directory.", pumpFailure); + } return result.Task.GetAwaiter().GetResult(); } finally @@ -73,9 +75,13 @@ int filter try { if (files == null) + { result.TrySetException(new InvalidOperationException(Sdl3NativeText.ReadError() ?? "The native folder dialog failed.")); + } else + { result.TrySetResult(files[0] == null ? null : Marshal.PtrToStringUTF8((nint)files[0])); + } } catch (Exception failure) { diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformApplication.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformApplication.cs index 20c3bac94..25a8a56d7 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformApplication.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformApplication.cs @@ -63,11 +63,9 @@ public Sdl3PlatformApplication(ISdl3HostIntegration hostIntegration) /// public partial IReadOnlyList GetWindows(); - IPlatformWindow IPlatformApplication.CreateWindow(PlatformWindowOptions options) - => CreateWindow(options); + IPlatformWindow IPlatformApplication.CreateWindow(PlatformWindowOptions options) => CreateWindow(options); - IReadOnlyList IPlatformApplication.GetWindows() - => GetWindows(); + IReadOnlyList IPlatformApplication.GetWindows() => GetWindows(); /// /// Registers an optional platform backend integration for this application instance. diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformWindow.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformWindow.cs index ee1fd4309..8d3b7cf27 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformWindow.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3PlatformWindow.cs @@ -1,5 +1,5 @@ -using Inno.Adapter.Platform; using System; +using Inno.Adapter.Platform; using Inno.Platform; namespace Inno.Adapter.Platform.Sdl3; diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs index b4bdac357..d5e63d87d 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs @@ -36,7 +36,9 @@ bool requireOpenGl ArgumentOutOfRangeException.ThrowIfNegativeOrZero(options.height); uint properties = SDL.CreateProperties(); if (properties == 0) + { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_CreateProperties failed."); + } try { if (!SDL.SetStringProperty(properties, SDL.Constants.SDL_PROP_WINDOW_CREATE_TITLE_STRING, options.title) @@ -45,13 +47,19 @@ bool requireOpenGl || !SDL.SetBooleanProperty(properties, SDL.Constants.SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, requireOpenGl) || !SDL.SetBooleanProperty(properties, SDL.Constants.SDL_PROP_WINDOW_CREATE_HIDDEN_BOOLEAN, !options.visible) || !SDL.SetBooleanProperty(properties, SDL.Constants.SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, options.resizable) - || !SDL.SetBooleanProperty(properties, SDL.Constants.SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, options.highPixelDensity)) - { + || !SDL.SetBooleanProperty( + properties, + SDL.Constants.SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, + options.highPixelDensity + ) + ) { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL window properties could not be set."); } SDLWindow* window = SDL.Raw.CreateWindowWithProperties(properties); if (window == null) + { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL window creation failed."); + } return (nint)window; } finally @@ -75,7 +83,9 @@ bool requireOpenGl public static unsafe bool ReadFocus(nint windowHandle) { if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } return ((SDLWindowFlags)SDL.Raw.GetWindowFlags((SDLWindow*)windowHandle) & SDLWindowFlags.InputFocus) != 0; } } diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs index bc104195f..256c5148c 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; using System.Threading; using Inno.Core.Events; using Inno.Core.Input; @@ -50,7 +50,9 @@ private unsafe void Initialize() // Browser frames are already driven by requestAnimationFrame; SDL's native // resize callback is only needed by desktop window move/resize loops. if (!m_hostIntegration.capabilities.liveResize) + { return; + } m_liveResizeEventWatch = LiveResizeEventWatch; m_liveResizeMainThreadCallback = LiveResizeMainThreadCallback; @@ -135,7 +137,9 @@ public partial IDisposable RegisterExtension(ISdl3ApplicationExtension extension ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(extension); if (m_extensions.Contains(extension)) + { throw new InvalidOperationException("The platform extension is already registered."); + } m_extensions.Add(extension); return new ExtensionRegistration(this, extension); } @@ -176,8 +180,8 @@ private void PollAndCoalescePendingEvents() } if (TryCreatePendingEventCoalesceKey(translatedEvent, out var key) - && latestEventIndicesByKey.TryGetValue(key, out var index)) - { + && latestEventIndicesByKey.TryGetValue(key, out var index) + ) { m_pendingEvents[index] = translatedEvent; continue; } @@ -220,7 +224,9 @@ public partial void Dispose() } foreach (ISdl3ApplicationExtension extension in m_extensions.ToArray()) + { extension.OnApplicationDisposing(this); + } m_extensions.Clear(); foreach (var window in new List(m_windows.Values)) @@ -298,17 +304,19 @@ private static unsafe void LiveResizeMainThreadCallback(void* userData) private unsafe void DispatchNativeEvent(ref SDLEvent sdlEvent) { - ReadOnlySpan nativeEventData = new( - Unsafe.AsPointer(ref sdlEvent), - sizeof(SDLEvent)); + ReadOnlySpan nativeEventData = new(Unsafe.AsPointer(ref sdlEvent), sizeof(SDLEvent)); foreach (ISdl3ApplicationExtension extension in m_extensions.ToArray()) + { extension.ProcessNativeEvent(this, nativeEventData); + } } private void DispatchLiveResizeRedraw(uint windowId) { if (m_dispatchingRedraw || m_redrawFailure is not null) + { return; + } m_dispatchingRedraw = true; try { @@ -316,11 +324,15 @@ private void DispatchLiveResizeRedraw(uint windowId) { int width = 0, height = 0; if (SDL.Raw.GetWindowSize(window.sdlWindow, &width, &height) == 0) + { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_GetWindowSize failed during live resize."); + } window.UpdateLogicalSize(width, height); } foreach (ISdl3ApplicationExtension extension in m_extensions.ToArray()) + { extension.PrepareLiveResizeWindow(this, windowId); + } redrawRequested?.Invoke(windowId); } finally @@ -347,7 +359,9 @@ public void Dispose() Sdl3PlatformApplication? owner = Interlocked.Exchange(ref m_application, null); ISdl3ApplicationExtension? registered = Interlocked.Exchange(ref m_extension, null); if (owner is not null && registered is not null) + { owner.UnregisterExtension(registered); + } } } @@ -399,7 +413,8 @@ out Event? evnt evnt = new WindowResizeEvent( sdlEvent.Window.WindowID, pixelResizedWindow.width, - pixelResizedWindow.height); + pixelResizedWindow.height + ); return true; } @@ -420,7 +435,9 @@ out Event? evnt { bool isFocused = eventType == SDLEventType.WindowFocusGained; if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out Sdl3PlatformWindow? focusedWindow)) + { focusedWindow.UpdateFocus(isFocused); + } evnt = new WindowFocusChangedEvent(sdlEvent.Window.WindowID, isFocused); return true; } @@ -444,8 +461,8 @@ out Event? evnt case SDLEventType.TextInput: { string? text = sdlEvent.Text.Text == null - ? null - : Marshal.PtrToStringUTF8((IntPtr)sdlEvent.Text.Text); + ? null + : Marshal.PtrToStringUTF8((IntPtr)sdlEvent.Text.Text); if (!string.IsNullOrEmpty(text)) { evnt = new TextInputEvent(sdlEvent.Text.WindowID, text); diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs index db8939dd0..3adbc71d8 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs @@ -29,7 +29,9 @@ public partial Sdl3PlatformWindow CreateWindow(PlatformWindowOptions options) ValidateWindowRegistration(); nint handle = m_hostIntegration.CreateWindow(options); if (handle == 0) + { throw new InvalidOperationException("The SDL host integration returned no window."); + } SDLWindow* nativeWindow = (SDLWindow*)handle; try { @@ -64,7 +66,9 @@ public Sdl3PlatformWindow AdoptWindow(nint windowHandle) { ValidateWindowRegistration(); if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } SDLWindow* window = (SDLWindow*)windowHandle; return RegisterWindow(window, Sdl3NativeText.ReadWindowTitle(window) ?? string.Empty, ownsNativeWindow: false); } @@ -87,8 +91,10 @@ public void ReleaseWindow(Sdl3PlatformWindow window) ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(window); if (window.ownsNativeWindow || !m_windows.TryGetValue(window.windowId, out Sdl3PlatformWindow? registered) - || !ReferenceEquals(registered, window)) + || !ReferenceEquals(registered, window) + ) { throw new ArgumentException("Only this application's adopted window can be released.", nameof(window)); + } window.Dispose(); } @@ -99,7 +105,9 @@ bool ownsNativeWindow ) { uint id = SDL.Raw.GetWindowId(nativeWindow); if (id == 0 || m_windows.ContainsKey(id)) + { throw new ArgumentException("The SDL window is invalid or already registered.", nameof(nativeWindow)); + } var window = new Sdl3PlatformWindow(nativeWindow, title, ownsNativeWindow, m_hostIntegration, RemoveWindow, m_ownerThreadId); m_windows.Add(id, window); return window; @@ -112,12 +120,16 @@ private void ValidateWindowRegistration() ValidateOwnerThread(); ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_hostIntegration.capabilities.multipleWindows && m_windows.Count != 0) + { throw new NotSupportedException("The selected SDL host supports only one window."); + } } private void ValidateOwnerThread() { if (Environment.CurrentManagedThreadId != m_ownerThreadId) + { throw new InvalidOperationException("SDL application operations must run on their owner thread."); + } } } diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs index 2b7ffd79f..f42c96f2e 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs @@ -19,7 +19,8 @@ public sealed class Sdl3PlatformBackendProvider : PlatformBackendProvider /// /// Host integration is absent. /// - public Sdl3PlatformBackendProvider(ISdl3HostIntegration hostIntegration) : base(PlatformBackendId.sdl3) + public Sdl3PlatformBackendProvider(ISdl3HostIntegration hostIntegration) + : base(PlatformBackendId.sdl3) { ArgumentNullException.ThrowIfNull(hostIntegration); m_hostIntegration = hostIntegration; diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs index 4ffe0d3dc..7d121f471 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs @@ -1,5 +1,5 @@ -using Inno.Adapter.Platform; using System; +using Inno.Adapter.Platform; using Inno.Native.Sdl3; using Inno.Platform; @@ -50,7 +50,9 @@ int ownerThreadId var currentWidth = 0; var currentHeight = 0; if (SDL.Raw.GetWindowSize(m_window, ¤tWidth, ¤tHeight) == 0) + { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_GetWindowSize failed."); + } m_width = currentWidth; m_height = currentHeight; RefreshPixelSize(); @@ -114,7 +116,9 @@ private void RefreshPixelSize() var pixelWidth = 0; var pixelHeight = 0; if (SDL.Raw.GetWindowSizeInPixels(m_window, &pixelWidth, &pixelHeight) == 0) + { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_GetWindowSizeInPixels failed."); + } UpdatePixelSize(pixelWidth, pixelHeight); } @@ -132,7 +136,9 @@ public partial void RequestClose() public partial void Dispose() { if (Environment.CurrentManagedThreadId != m_ownerThreadId) + { throw new InvalidOperationException("SDL window disposal must run on its owner thread."); + } if (m_disposed) { return; @@ -149,5 +155,4 @@ public partial void Dispose() m_disposed = true; m_onDisposed(this); } - } diff --git a/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs b/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs index fabc99d75..03d3a55c7 100644 --- a/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs +++ b/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs @@ -21,10 +21,18 @@ public static class TextToolchain "backends/Text/build/Inno.Build.Toolchains.Text/Inno.Build.Toolchains.Text.csproj", new NativeStaticBuildDefinition( "backends/Text/build/Inno.Build.Toolchains.Text/Native/StaticLibraries.cmake", - ["extern/freetype", "extern/harfbuzz", "backends/Text/native/Inno.Native.Text/Native/include", "backends/Text/native/Inno.Native.Text/Native/src", "backends/Text/native/Inno.Native.Text/Native/CMakeLists.txt"], + [ + "extern/freetype", + "extern/harfbuzz", + "backends/Text/native/Inno.Native.Text/Native/include", + "backends/Text/native/Inno.Native.Text/Native/src", + "backends/Text/native/Inno.Native.Text/Native/CMakeLists.txt" + ], ["libinno-text", "libfreetype", "libharfbuzz"], - nativeSourceDirectory: "backends/Text/native/Inno.Native.Text"), - bindingDefinition: "backends/Text/native/Inno.Native.Text/Bindings/bindings.props"); + nativeSourceDirectory: "backends/Text/native/Inno.Native.Text" + ), + bindingDefinition: "backends/Text/native/Inno.Native.Text/Bindings/bindings.props" + ); /// /// Builds the component using the explicitly selected target SDK and validates the complete native product. @@ -52,26 +60,41 @@ public static async Task BuildAsync( NativeToolchainSelection selection = context.RequireToolchain(); string source = Path.Combine(componentDescriptor.GetNativeRoot(context.engineRoot), "Native"); NativeBuildRecipe recipe = CreateRecipe(context); - return await NativeArtifactPublisher.PublishAsync(context, recipe, + return await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - source, "inno-text", [], token).ConfigureAwait(false); + ) => + { + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + source, + "inno-text", + [], + token + ).ConfigureAwait(false); string library = NativeCMakeExecutor.FindOutput(scoped, build, "*inno-text" + selection.sharedLibraryExtension); string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); - - }, cancellationToken, describeOutputs: static ( + }, + cancellationToken, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Select(file => - new NativeArtifact(Path.GetRelativePath(output, file), file, + new NativeArtifact( + Path.GetRelativePath(output, file), + file, Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary)).ToArray()).ConfigureAwait(false); + ? NativeArtifactRole.ImportLibrary + : NativeArtifactRole.SharedLibrary + )).ToArray() + ).ConfigureAwait(false); } /// @@ -100,9 +123,19 @@ public static NativeBuildRecipe CreateRecipe(NativeBuildContext context) ArgumentNullException.ThrowIfNull(context); NativeToolchainSelection selection = context.RequireToolchain(); if (context.RequireComponentOptions(componentDescriptor).libraryKind != NativeLibraryKind.Shared) - throw new NotSupportedException("This standalone producer requires shared linkage; static products use the declared aggregate recipe."); - return NativeBuildRecipe.CreateForComponent(context, componentDescriptor, "text", selection.targetId, + { + throw new NotSupportedException( + "This standalone producer requires shared linkage; static products use the declared aggregate recipe." + ); + } + return NativeBuildRecipe.CreateForComponent( + context, + componentDescriptor, + "text", + selection.targetId, componentDescriptor.staticBuild!.inputPaths.Select(path => Path.GetFullPath(path, context.engineRoot)), - [], [Path.Combine(componentDescriptor.GetToolchainRoot(context.engineRoot), "TextToolchain.cs")]); + [], + [Path.Combine(componentDescriptor.GetToolchainRoot(context.engineRoot), "TextToolchain.cs")] + ); } } diff --git a/backends/Text/native/Inno.Native.Text/TextNative.cs b/backends/Text/native/Inno.Native.Text/TextNative.cs index c0191ea6c..730238151 100644 --- a/backends/Text/native/Inno.Native.Text/TextNative.cs +++ b/backends/Text/native/Inno.Native.Text/TextNative.cs @@ -23,4 +23,4 @@ static TextNative() Load(NativeDllLoader.FindNativeLibrary(LibName)); #endif } -} \ No newline at end of file +} diff --git a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs index 98f9c27cd..41813eb93 100644 --- a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs +++ b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs @@ -1,6 +1,5 @@ using System; using System.Text; - using Inno.Native.Text; using Inno.Text; @@ -21,7 +20,9 @@ public FreeTypeHarfBuzzTextBackend() { InnoTextFontAdapterRuntime* context = TextNativeOperations.CreateSession(); if (context == null) + { throw new InvalidOperationException("The native text backend returned a null context."); + } m_context = context; } @@ -43,7 +44,9 @@ int faceIndex ) { EnsureActive(); if (data.IsEmpty) + { throw new ArgumentException("Font data cannot be empty.", nameof(data)); + } ArgumentOutOfRangeException.ThrowIfNegative(faceIndex); ulong handle = 0; ThrowIfFailed(TextNativeOperations.LoadFont(m_context, data, faceIndex, ref handle), "load font"); @@ -60,7 +63,9 @@ public void ReleaseFont(TextFontHandle font) { EnsureActive(); if (!font.isValid) + { return; + } ThrowIfFailed(TextNativeOperations.ReleaseFont(m_context, font.value), "release font"); } @@ -90,7 +95,9 @@ TextShapingOptions options ) { EnsureActive(); if (!font.isValid) + { throw new ArgumentException("A valid font handle is required.", nameof(font)); + } ArgumentNullException.ThrowIfNull(text); byte[] textBytes = Utf8(text); byte[] languageBytes = Utf8(options.language ?? string.Empty); @@ -100,35 +107,43 @@ TextShapingOptions options fixed (byte* languagePointer = languageBytes) fixed (byte* scriptPointer = scriptBytes) { - ThrowIfFailed(TextNativeOperations.ShapeUtf8( - m_context, - font.value, - textPointer, - checked((uint)(textBytes.Length - 1)), - style.fontSize, - (Direction)options.direction, - languagePointer, - scriptPointer, - (InnoTextFontAdapterGlyph*)null, - 0, - &glyphCount), "query shaped glyph count"); + ThrowIfFailed( + TextNativeOperations.ShapeUtf8( + m_context, + font.value, + textPointer, + checked((uint)(textBytes.Length - 1)), + style.fontSize, + (Direction)options.direction, + languagePointer, + scriptPointer, + (InnoTextFontAdapterGlyph*)null, + 0, + &glyphCount + ), + "query shaped glyph count" + ); InnoTextFontAdapterGlyph[] nativeGlyphs = new InnoTextFontAdapterGlyph[checked((int)glyphCount)]; if (nativeGlyphs.Length > 0) { fixed (InnoTextFontAdapterGlyph* glyphPointer = nativeGlyphs) { - ThrowIfFailed(TextNativeOperations.ShapeUtf8( - m_context, - font.value, - textPointer, - checked((uint)(textBytes.Length - 1)), - style.fontSize, - (Direction)options.direction, - languagePointer, - scriptPointer, - glyphPointer, - checked((uint)nativeGlyphs.Length), - &glyphCount), "shape text"); + ThrowIfFailed( + TextNativeOperations.ShapeUtf8( + m_context, + font.value, + textPointer, + checked((uint)(textBytes.Length - 1)), + style.fontSize, + (Direction)options.direction, + languagePointer, + scriptPointer, + glyphPointer, + checked((uint)nativeGlyphs.Length), + &glyphCount + ), + "shape text" + ); } } @@ -140,9 +155,13 @@ TextShapingOptions options float advanceX = glyph.AdvanceX; float advanceY = glyph.AdvanceY; if (options.direction is TextDirection.TopToBottom or TextDirection.BottomToTop) + { advanceY += MathF.CopySign(style.letterSpacing, advanceY == 0f ? 1f : advanceY); + } else + { advanceX += MathF.CopySign(style.letterSpacing, advanceX == 0f ? 1f : advanceX); + } width += MathF.Abs(advanceX); glyphs[index] = new TextGlyph( glyph.GlyphId, @@ -150,7 +169,8 @@ TextShapingOptions options advanceX, advanceY, glyph.OffsetX, - glyph.OffsetY); + glyph.OffsetY + ); } InnoTextFontAdapterMetrics metrics = default; ThrowIfFailed(TextNativeOperations.GetMetrics(m_context, font.value, style.fontSize, ref metrics), "query font metrics"); @@ -159,7 +179,8 @@ TextShapingOptions options metrics.Descender, metrics.LineHeight, metrics.UnderlinePosition, - metrics.UnderlineThickness); + metrics.UnderlineThickness + ); return new TextLayout(glyphs, publicMetrics, width, MathF.Max(0f, metrics.LineHeight)); } } @@ -186,27 +207,38 @@ float fontSize ) { EnsureActive(); if (!font.isValid) + { throw new ArgumentException("A valid font handle is required.", nameof(font)); + } if (!float.IsFinite(fontSize) || fontSize <= 0f) + { throw new ArgumentOutOfRangeException(nameof(fontSize)); + } InnoTextFontAdapterBitmap bitmap = default; - ThrowIfFailed(TextNativeOperations.RasterizeGlyph( - m_context, font.value, glyphId, fontSize, null, 0, &bitmap), "query glyph bitmap"); + ThrowIfFailed( + TextNativeOperations.RasterizeGlyph(m_context, font.value, glyphId, fontSize, null, 0, &bitmap), + "query glyph bitmap" + ); byte[] pixels = new byte[checked((int)bitmap.ByteLength)]; if (pixels.Length > 0) { fixed (byte* pixelPointer = pixels) - ThrowIfFailed(TextNativeOperations.RasterizeGlyph( - m_context, font.value, glyphId, fontSize, pixelPointer, checked((uint)pixels.Length), &bitmap), - "rasterize glyph"); + { + ThrowIfFailed( + TextNativeOperations.RasterizeGlyph( + m_context, + font.value, + glyphId, + fontSize, + pixelPointer, + checked((uint)pixels.Length), + &bitmap + ), + "rasterize glyph" + ); + } } - return new GlyphBitmap( - bitmap.Width, - bitmap.Height, - bitmap.BearingX, - bitmap.BearingY, - bitmap.AdvanceX, - pixels); + return new GlyphBitmap(bitmap.Width, bitmap.Height, bitmap.BearingX, bitmap.BearingY, bitmap.AdvanceX, pixels); } /// @@ -215,7 +247,9 @@ float fontSize public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; TextNativeOperations.DestroySession(m_context); m_context = null; @@ -233,7 +267,11 @@ private static void ThrowIfFailed( string operation ) { if (result != Result.Success) - throw new InvalidOperationException($"Failed to {operation}: {TextNativeOperations.ResultMessage(result) ?? result.ToString()}."); + { + throw new InvalidOperationException( + $"Failed to {operation}: {TextNativeOperations.ResultMessage(result) ?? result.ToString()}." + ); + } } private void EnsureActive() => ObjectDisposedException.ThrowIf(m_disposed, this); diff --git a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs index 78c5c20e6..cd2189530 100644 --- a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs +++ b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs @@ -11,7 +11,8 @@ public sealed class FreeTypeHarfBuzzTextBackendProvider : TextBackendProvider /// /// Creates an explicitly composed registration for the bundled implementation. /// - public FreeTypeHarfBuzzTextBackendProvider() : base(TextBackendId.freeTypeHarfBuzz) { } + public FreeTypeHarfBuzzTextBackendProvider() + : base(TextBackendId.freeTypeHarfBuzz) {} /// public override ITextBackend CreateBackend() @@ -19,4 +20,3 @@ public override ITextBackend CreateBackend() return new FreeTypeHarfBuzzTextBackend(); } } - diff --git a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs index 300a2175f..869dbe827 100644 --- a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs +++ b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs @@ -30,7 +30,12 @@ ref ulong handle BgcsInnoTextError* error = null; fixed (byte* bytes = data) fixed (ulong* destination = &handle) - CheckBridge(TextNative.Raw.LoadFont(runtime, bytes, checked((uint)data.Length), faceIndex, destination, &result, &error), error); + { + CheckBridge( + TextNative.Raw.LoadFont(runtime, bytes, checked((uint)data.Length), faceIndex, destination, &result, &error), + error + ); + } return result; } @@ -60,8 +65,24 @@ internal static Result ShapeUtf8( Result result = default; BgcsInnoTextError* error = null; // BGCS verifies every DTO field, offset, size and alignment in the native bridge. - CheckBridge(TextNative.Raw.ShapeUtf8(runtime, handle, (sbyte*)text, textLength, fontSize, direction, - (sbyte*)language, (sbyte*)script, (InnoTextFontAdapterGlyphNative*)glyphs, capacity, count, &result, &error), error); + CheckBridge( + TextNative.Raw.ShapeUtf8( + runtime, + handle, + (sbyte*)text, + textLength, + fontSize, + direction, + (sbyte*)language, + (sbyte*)script, + (InnoTextFontAdapterGlyphNative*)glyphs, + capacity, + count, + &result, + &error + ), + error + ); return result; } @@ -74,8 +95,19 @@ ref InnoTextFontAdapterMetrics metrics Result result = default; BgcsInnoTextError* error = null; fixed (InnoTextFontAdapterMetrics* destination = &metrics) - CheckBridge(TextNative.Raw.GetMetrics(runtime, handle, fontSize, - (InnoTextFontAdapterMetricsNative*)destination, &result, &error), error); + { + CheckBridge( + TextNative.Raw.GetMetrics( + runtime, + handle, + fontSize, + (InnoTextFontAdapterMetricsNative*)destination, + &result, + &error + ), + error + ); + } return result; } @@ -90,8 +122,20 @@ internal static Result RasterizeGlyph( ) { Result result = default; BgcsInnoTextError* error = null; - CheckBridge(TextNative.Raw.RasterizeGlyph(runtime, handle, glyphId, fontSize, pixels, capacity, - (InnoTextFontAdapterBitmapNative*)bitmap, &result, &error), error); + CheckBridge( + TextNative.Raw.RasterizeGlyph( + runtime, + handle, + glyphId, + fontSize, + pixels, + capacity, + (InnoTextFontAdapterBitmapNative*)bitmap, + &result, + &error + ), + error + ); return result; } @@ -108,16 +152,22 @@ private static void CheckBridge( BgcsInnoTextError* error ) { if (status == 0 && error == null) + { return; + } try { string? message = error == null ? null : Marshal.PtrToStringUTF8((nint)TextNative.Raw.BgcsInnoTextErrorMessage(error)); - throw new InvalidOperationException($"The text bridge failed with status {status}: {message ?? "No native error text is available."}"); + throw new InvalidOperationException( + $"The text bridge failed with status {status}: {message ?? "No native error text is available."}" + ); } finally { if (error != null) + { TextNative.Raw.BgcsInnoTextErrorRelease(error); + } } } } diff --git a/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs b/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs index d54ee33bb..f648603c9 100644 --- a/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs +++ b/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs @@ -18,41 +18,61 @@ NativeBindingProfile profile string definition = Path.GetFullPath(component.bindingDefinition!, context.engineRoot); string directory = Path.GetDirectoryName(definition)!; XElement project = XDocument.Load(definition).Root - ?? throw new InvalidDataException("A binding definition is empty."); + ?? throw new InvalidDataException("A binding definition is empty."); if (project.Name != "Project" || project.Attributes().Any()) + { throw new InvalidDataException("Binding definitions must be declarative Project data."); + } Dictionary properties = new(StringComparer.Ordinal); foreach (XElement group in project.Elements()) { if (group.Attributes().Any()) + { throw new InvalidDataException("Binding definitions cannot evaluate conditions."); + } if (group.Name == "PropertyGroup") { foreach (XElement property in group.Elements()) { if (property.Name.LocalName is not ("InnoNativeComponentId" or "InnoBindingConfig") - || property.Attributes().Any() || property.HasElements || !properties.TryAdd(property.Name.LocalName, property.Value)) + || property.Attributes().Any() + || property.HasElements + || !properties.TryAdd(property.Name.LocalName, property.Value) + ) { throw new InvalidDataException("A binding definition has an unknown or repeated property."); + } } } else + { throw new InvalidDataException("A binding definition cannot contain executable build logic."); + } } if (!properties.TryGetValue("InnoNativeComponentId", out string? componentId) || componentId != component.id) + { throw new InvalidDataException("The binding definition must declare the requested component identity."); + } if (!properties.TryGetValue("InnoBindingConfig", out string? hostConfig)) + { throw new InvalidDataException("A binding definition requires its common binding configuration."); + } if (request.targetId != profile.targetId) + { throw new NotSupportedException($"The selected binding profile does not serve '{request.targetId}'."); + } return new(component, definition, Resolve(hostConfig), request, profile); string Resolve(string path) { if (string.IsNullOrWhiteSpace(path) || Path.IsPathFullyQualified(path) || path.Contains('$') || path.Contains('@') - || path.Contains(':') || path.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..")) + || path.Contains(':') || path.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..") + ) { throw new InvalidDataException("Binding definition paths must be literal relative children."); + } string absolute = Path.GetFullPath(path, directory); if (!File.Exists(absolute)) + { throw new FileNotFoundException("A declared binding input is missing.", absolute); + } return absolute; } } diff --git a/build/bindings/Inno.Build.Bindings/Configuration/BindingGenerationConfiguration.cs b/build/bindings/Inno.Build.Bindings/Configuration/BindingGenerationConfiguration.cs index 2c12dbc8f..1f4a11cd3 100644 --- a/build/bindings/Inno.Build.Bindings/Configuration/BindingGenerationConfiguration.cs +++ b/build/bindings/Inno.Build.Bindings/Configuration/BindingGenerationConfiguration.cs @@ -36,30 +36,59 @@ internal GenerationRequest Load( CancellationToken cancellation ) { if (context.toolchain is NativeToolchainSelection selected && selected.targetId != request.targetId) + { throw new InvalidOperationException("The selected SDK does not match the binding target."); + } using HostServices host = BindingHostFactory.CreateHostServices(context.engineRoot); - GenerationRequest captured = GenerationRequest.FromFile(configPath).MaterializeAsync(host.paths, cancellation) - .AsTask().GetAwaiter().GetResult(); + GenerationRequest captured = GenerationRequest.FromFile(configPath) + .MaterializeAsync(host.paths, cancellation) + .AsTask() + .GetAwaiter() + .GetResult(); if (captured.configuration.targets.Length != 1) + { throw new InvalidDataException("A component binding request must select exactly one native target."); + } if (captured.configuration.output.layout != "singleFile" || captured.configuration.output.singleFileName != "Bindings.cs" - || captured.configuration.runtime.mode != "package") + || captured.configuration.runtime.mode != "package" + ) { throw new InvalidDataException("Native components require one Bindings.cs source and the package Runtime."); - captured = captured.WithConfiguration(captured.configuration with - { - cache = captured.configuration.cache with + } + captured = captured.WithConfiguration( + captured.configuration with { - directory = Path.Combine(context.engineRoot, "artifacts", "build-tools", "bindings", "sdk-workspaces", component.id, request.targetId) + cache = captured.configuration.cache with + { + directory = Path.Combine( + context.engineRoot, + "artifacts", + "build-tools", + "bindings", + "sdk-workspaces", + component.id, + request.targetId + ) + } } - }); - return profile.Apply(captured, context.toolchain?.compilerInputs, - request.componentOptions.GetValueOrDefault(component.nativeProject), context.engineRoot) - .MaterializeAsync(host.paths, cancellation).AsTask().GetAwaiter().GetResult(); + ); + return profile + .Apply( + captured, + context.toolchain?.compilerInputs, + request.componentOptions.GetValueOrDefault(component.nativeProject), + context.engineRoot + ) + .MaterializeAsync(host.paths, cancellation) + .AsTask() + .GetAwaiter() + .GetResult(); } - internal string GetOutputRoot(NativeBuildContext context) => request.outputMode == NativeBindingOutputMode.TargetArtifacts - ? Path.Combine(context.engineRoot, "artifacts", "bindings", component.id, request.targetId) - : Path.Combine(component.GetNativeRoot(context.engineRoot), "Generated"); + internal string GetOutputRoot(NativeBuildContext context) + => request.outputMode == NativeBindingOutputMode.TargetArtifacts + ? Path.Combine(context.engineRoot, "artifacts", "bindings", component.id, request.targetId) + : Path.Combine(component.GetNativeRoot(context.engineRoot), "Generated"); - internal string GetHostNativeRoot(NativeBuildContext context) => Path.Combine(component.GetNativeRoot(context.engineRoot), "Native", "Generated"); + internal string GetHostNativeRoot(NativeBuildContext context) + => Path.Combine(component.GetNativeRoot(context.engineRoot), "Native", "Generated"); } diff --git a/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs b/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs index 31ad617ae..f6346f621 100644 --- a/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs +++ b/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs @@ -53,14 +53,20 @@ public NativeBindingProfile( ) { ArgumentException.ThrowIfNullOrWhiteSpace(targetId); if (targetId == "host") + { throw new ArgumentException("A binding profile requires an explicit engine target.", nameof(targetId)); + } ArgumentNullException.ThrowIfNull(target); if (target.id == "host" || string.IsNullOrWhiteSpace(target.id)) + { throw new ArgumentException("Binding profiles require an explicit native ABI.", nameof(target)); + } this.targetId = targetId; this.target = target; if (importMode is { } selectedImport && !Enum.IsDefined(selectedImport)) + { throw new ArgumentOutOfRangeException(nameof(importMode)); + } this.runtime = runtime; this.importMode = importMode; this.inputPaths = Array.AsReadOnly((inputPaths ?? []).Select(ValidatePath).ToArray()); @@ -71,18 +77,22 @@ public NativeBindingProfile( /// Gets the engine target authorized to consume this profile. /// public string targetId { get; } + /// /// Gets the immutable official BGCS target configuration. /// public TargetConfiguration target { get; } + /// /// Gets the managed projection runtime, or null for the component's portable default. /// public ManagedRuntimeId? runtime { get; } + /// /// Gets the explicit platform import mechanism, or null for the component's mechanism. /// public BindingImportMode? importMode { get; } + /// /// Gets the profile's exact checkout implementation inputs. /// @@ -90,8 +100,8 @@ public NativeBindingProfile( internal void Configure(BindingHostBuilder builder) => m_configureGenerator?.Invoke(builder); - internal IEnumerable GetExtensionAssemblies() => - m_configureGenerator?.GetInvocationList().Select(static action => action.Method.Module.Assembly) ?? []; + internal IEnumerable GetExtensionAssemblies() + => m_configureGenerator?.GetInvocationList().Select(static action => action.Method.Module.Assembly) ?? []; internal GenerationRequest Apply( GenerationRequest request, @@ -101,12 +111,14 @@ string engineRoot ) { TargetConfiguration selected = target; if (compiler is not null) + { selected = selected with { settings = selected.settings with { compilerPath = request.configuration.source.language == BGCS.Core.Inputs.SourceLanguage.Cpp - ? compiler.cppCompiler : compiler.cCompiler, + ? compiler.cppCompiler + : compiler.cCompiler, sysRoot = compiler.sysRoot, systemIncludeDirectories = compiler.systemIncludeDirectories.ToImmutableArray(), cxxSystemIncludeDirectories = compiler.cppSystemIncludeDirectories.ToImmutableArray(), @@ -114,29 +126,37 @@ string engineRoot arguments = [.. selected.settings.arguments, .. compiler.arguments] } }; + } BindingConfiguration config = request.configuration; - return request.WithConfiguration(config with - { - targets = [selected], - api = config.api with - { - runtime = runtime ?? config.api.runtime, - importMode = importMode ?? config.api.importMode - }, - library = config.library with { nativeName = options?.bindingLibraryName ?? config.library.nativeName }, - source = config.source with + return request.WithConfiguration( + config with { - includeDirectories = [.. config.source.includeDirectories, - .. (options?.bindingIncludeDirectories ?? []).Select(path => Path.GetFullPath(path, engineRoot))] + targets = [selected], + api = config.api with + { + runtime = runtime ?? config.api.runtime, + importMode = importMode ?? config.api.importMode + }, + library = config.library with { nativeName = options?.bindingLibraryName ?? config.library.nativeName }, + source = config.source with + { + includeDirectories = + [ + .. config.source.includeDirectories, + .. (options?.bindingIncludeDirectories ?? []).Select(path => Path.GetFullPath(path, engineRoot)) + ] + } } - }); + ); } private static string ValidatePath(string path) { if (string.IsNullOrWhiteSpace(path) || Path.IsPathFullyQualified(path) || path.Contains(':') - || path.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..")) + || path.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..") + ) { throw new ArgumentException("Binding profile inputs must remain within the checkout.", nameof(path)); + } return path.Replace('\\', '/'); } } diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs index 0300f7f32..51242e26b 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Build.Toolchains; using Inno.Core.IO; @@ -36,19 +35,37 @@ internal async ValueTask ExecuteAsync(Cancellatio BindingDefinitionReader.Read(m_context, component, m_request, m_profile)).ToArray(); string[] fingerprints = definitions.Select(definition => Compute(definition, m_context, cancellation)).ToArray(); for (int index = 0; index < definitions.Length; index++) + { if (m_request.expectedFingerprints.TryGetValue(definitions[index].component.nativeProject, out string? expected) - && expected != fingerprints[index]) + && expected != fingerprints[index] + ) { throw new InvalidOperationException("Binding inputs changed after their generation was selected."); - BuildCacheOwnerCatalog.Register(m_context.engineRoot, Path.Combine(m_context.engineRoot, "artifacts", "bindings"), - "bindings", BuildCacheArtifactRole.ImmutableArtifact, cancellation); + } + } + BuildCacheOwnerCatalog.Register( + m_context.engineRoot, + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + "bindings", + BuildCacheArtifactRole.ImmutableArtifact, + cancellation + ); // Batch leases are acquired in canonical path order. No partial closure is returned on failure. StringComparer paths = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; foreach (string path in definitions.Select(definition => Path.Combine( - definition.component.GetNativeRoot(m_context.engineRoot), "obj", "bindings", "generation.lock")).Order(paths)) + definition.component.GetNativeRoot(m_context.engineRoot), + "obj", + "bindings", + "generation.lock" + )).Order(paths) + ) { m_leases.Add(await FileLease.AcquireAsync(path, Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false)); + } if (m_request.outputMode == NativeBindingOutputMode.TargetArtifacts) { - var cache = new BuildCachePublisher(Path.Combine(m_context.engineRoot, "artifacts", "bindings"), BuildCacheArtifactRole.ImmutableArtifact); + var cache = new BuildCachePublisher( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + BuildCacheArtifactRole.ImmutableArtifact + ); m_leases.Add(await cache.AcquireUseAsync(cancellation).ConfigureAwait(false)); } m_context.RecordBindingBatch(); @@ -68,13 +85,28 @@ internal async ValueTask ExecuteAsync(Cancellatio string destination = Path.Combine(output, fingerprint); try { - m_reading.Add(await BuildArtifactReadLease.AcquireAsync(destination, Path.Combine(m_context.engineRoot, "artifacts", "bindings"), fingerprint, - ["Native", "Generated"], cancellation, m_context).ConfigureAwait(false)); + m_reading.Add( + await BuildArtifactReadLease.AcquireAsync( + destination, + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + fingerprint, + ["Native", "Generated"], + cancellation, + m_context + ).ConfigureAwait(false) + ); protectedTargets.Add(destination); if (!m_request.checkOnly) { - results.Add(definition.component.nativeProject, TargetBindingGeneration.Describe( - Path.Combine(m_context.engineRoot, "artifacts", "bindings"), destination, fingerprint, usesRuntimeImports)); + results.Add( + definition.component.nativeProject, + TargetBindingGeneration.Describe( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + destination, + fingerprint, + usesRuntimeImports + ) + ); continue; } } @@ -82,20 +114,37 @@ internal async ValueTask ExecuteAsync(Cancellatio { // Invalid output is repaired only after exclusive artifact ownership is acquired at commit. } - var publication = BindingGenerationPublication.CreateTarget(Path.Combine(m_context.engineRoot, "artifacts", "bindings"), destination, cancellation); + var publication = BindingGenerationPublication.CreateTarget( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + destination, + cancellation + ); m_publications.Add(publication); TargetBindingGeneration.Generate(m_context, definition, loaded, publication, fingerprint, cancellation); - results.Add(definition.component.nativeProject, TargetBindingGeneration.Describe( - Path.Combine(m_context.engineRoot, "artifacts", "bindings"), destination, fingerprint, usesRuntimeImports)); + results.Add( + definition.component.nativeProject, + TargetBindingGeneration.Describe( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + destination, + fingerprint, + usesRuntimeImports + ) + ); } else { - var publication = BindingGenerationPublication.CreateHost(Path.Combine(m_context.engineRoot, "artifacts", "bindings"), output, definition.GetHostNativeRoot(m_context), cancellation); + var publication = BindingGenerationPublication.CreateHost( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + output, + definition.GetHostNativeRoot(m_context), + cancellation + ); m_publications.Add(publication); HostBindingGeneration.Generate(m_context, definition, loaded, publication, fingerprint, cancellation); results.Add(definition.component.nativeProject, new NativeBindingGenerationDescriptor { - fingerprint = fingerprint, bindingsPath = Path.Combine(output, "Bindings.cs"), + fingerprint = fingerprint, + bindingsPath = Path.Combine(output, "Bindings.cs"), usesRuntimeImports = usesRuntimeImports, artifactDirectory = string.Empty, artifactOwnerDirectory = string.Empty, @@ -106,25 +155,42 @@ internal async ValueTask ExecuteAsync(Cancellatio Verify(definitions, fingerprints, m_context.BeginInputVerification("binding-generation"), cancellation); cancellation.ThrowIfCancellationRequested(); foreach (BindingGenerationPublication publication in m_publications) + { if (!m_request.checkOnly) { if (m_request.outputMode == NativeBindingOutputMode.TargetArtifacts) { using BuildArtifactWriteLease mutation = await BuildArtifactWriteLease.AcquireAsync( - publication.managedDestination, Path.Combine(m_context.engineRoot, "artifacts", "bindings"), cancellation).ConfigureAwait(false); + publication.managedDestination, + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + cancellation + ).ConfigureAwait(false); publication.Commit(); } else + { publication.Commit(); + } } + } if (m_request.outputMode == NativeBindingOutputMode.TargetArtifacts) { foreach (NativeBindingGenerationDescriptor descriptor in results.Values) { string directory = descriptor.artifactDirectory; if (!protectedTargets.Contains(directory)) - m_reading.Add(await BuildArtifactReadLease.AcquireAsync(directory, Path.Combine(m_context.engineRoot, "artifacts", "bindings"), descriptor.fingerprint, - ["Native", "Generated"], cancellation, m_context).ConfigureAwait(false)); + { + m_reading.Add( + await BuildArtifactReadLease.AcquireAsync( + directory, + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + descriptor.fingerprint, + ["Native", "Generated"], + cancellation, + m_context + ).ConfigureAwait(false) + ); + } } } else @@ -135,12 +201,21 @@ internal async ValueTask ExecuteAsync(Cancellatio } if (m_request.outputMode == NativeBindingOutputMode.TargetArtifacts && !m_request.checkOnly) { - var cache = new BuildCachePublisher(Path.Combine(m_context.engineRoot, "artifacts", "bindings"), BuildCacheArtifactRole.ImmutableArtifact); + var cache = new BuildCachePublisher( + Path.Combine(m_context.engineRoot, "artifacts", "bindings"), + BuildCacheArtifactRole.ImmutableArtifact + ); foreach (BindingGenerationConfiguration definition in definitions) { NativeBindingGenerationDescriptor generation = results[definition.component.nativeProject]; - cache.Record(generation.artifactDirectory, generation.artifactDirectory + ".read.lock", [], - definition.component.id + "/" + m_request.targetId, m_request.targetId, cancellation); + cache.Record( + generation.artifactDirectory, + generation.artifactDirectory + ".read.lock", + [], + definition.component.id + "/" + m_request.targetId, + m_request.targetId, + cancellation + ); } } var result = new NativeBindingGenerationResult(results, m_reading); @@ -188,7 +263,9 @@ public void Dispose() } } if (failures.Count > 0) + { throw new AggregateException("Binding batch cleanup failed after draining generation.", failures); + } } private void Verify( @@ -199,9 +276,18 @@ CancellationToken cancellation ) { for (int index = 0; index < definitions.Count; index++) { - BindingGenerationConfiguration current = BindingDefinitionReader.Read(verification, definitions[index].component, m_request, m_profile); + BindingGenerationConfiguration current = BindingDefinitionReader.Read( + verification, + definitions[index].component, + m_request, + m_profile + ); if (Compute(current, verification, cancellation) != fingerprints[index]) - throw new InvalidOperationException("Binding inputs changed during an ownership wait or generation; the candidate was not published."); + { + throw new InvalidOperationException( + "Binding inputs changed during an ownership wait or generation; the candidate was not published." + ); + } } } diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs index 4ef98b628..8770c4114 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs @@ -35,39 +35,67 @@ CancellationToken cancellation { Console.WriteLine($"BGCS {diagnostic.severity} {diagnostic.code}: {diagnostic.message}"); if (diagnostic.details is not null) + { Console.WriteLine(diagnostic.details); + } } if (!result.success) - throw new InvalidDataException("BGCS generation failed: " + string.Join(Environment.NewLine, - result.diagnostics.Where(static diagnostic => diagnostic.severity is BGCS.Core.BindingDiagnosticSeverity.Error - or BGCS.Core.BindingDiagnosticSeverity.Critical) - .Select(static diagnostic => diagnostic.code + ": " + diagnostic.message))); + { + throw new InvalidDataException( + "BGCS generation failed: " + string.Join( + Environment.NewLine, + result.diagnostics + .Where(static diagnostic => ( + diagnostic.severity is BGCS.Core.BindingDiagnosticSeverity.Error + or BGCS.Core.BindingDiagnosticSeverity.Critical + )) + .Select(static diagnostic => diagnostic.code + ": " + diagnostic.message) + ) + ); + } foreach (var stage in result.cacheStages) + { Console.WriteLine($"BGCS cache {stage.targetId}/{stage.stage}: {stage.status}; {stage.reason}"); + } var artifacts = BindingArtifactManifest.Read(result.outputRoot, request.configuration.library.id, services.paths, cancellation); - ArtifactDescriptor[] managed = artifacts.Where(static artifact => artifact.relativePath.EndsWith("/managed/Bindings.cs", StringComparison.Ordinal)).ToArray(); + ArtifactDescriptor[] managed = artifacts + .Where(static artifact => artifact.relativePath.EndsWith("/managed/Bindings.cs", StringComparison.Ordinal)) + .ToArray(); if (managed.Length != 1) + { throw new InvalidDataException("BGCS must publish exactly one selected target's managed Bindings.cs."); + } NativeSourceManifest[] manifests = BindingArtifactManifest.ReadNativeSources( - result.outputRoot, request.configuration.library.id, services.paths, cancellation).ToArray(); + result.outputRoot, + request.configuration.library.id, + services.paths, + cancellation + ).ToArray(); if (manifests.Length != 1) + { throw new InvalidDataException("A component generation requires exactly one native source manifest."); + } NativeSourceManifest manifest = manifests[0]; var generatedRoots = manifest.inputRoots.Where(static root => root.kind == "generated") - .Select(static root => root.id).ToHashSet(StringComparer.Ordinal); - var nativePaths = manifest.sources.Concat(manifest.headers).Select(static artifact => artifact.relativePath) + .Select(static root => root.id) + .ToHashSet(StringComparer.Ordinal); + var nativePaths = manifest.sources.Concat(manifest.headers) + .Select(static artifact => artifact.relativePath) .Concat(manifest.inputs.Where(input => generatedRoots.Contains(input.rootId)).Select(static input => input.relativePath)) .ToHashSet(StringComparer.Ordinal); var selectedArtifacts = artifacts.Where(artifact => nativePaths.Contains(artifact.relativePath)).ToArray(); if (selectedArtifacts.Length != nativePaths.Count) + { throw new InvalidDataException("Every generated native input must belong to the SDK's verified publication."); + } Directory.CreateDirectory(managedOutput); Directory.CreateDirectory(nativeOutput); foreach (ArtifactDescriptor artifact in selectedArtifacts.Append(managed[0])) { cancellation.ThrowIfCancellationRequested(); - string destination = artifact == managed[0] ? Path.Combine(managedOutput, "Bindings.cs") - : Path.Combine(nativeOutput, artifact.relativePath); + string destination = artifact == managed[0] + ? Path.Combine(managedOutput, "Bindings.cs") + : Path.Combine(nativeOutput, artifact.relativePath); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(Path.Combine(result.outputRoot, artifact.relativePath), destination, overwrite: false); } diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingHostFactory.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingHostFactory.cs index 9c9016372..620f34692 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingHostFactory.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingHostFactory.cs @@ -4,8 +4,8 @@ using System.Threading; using BGCS; using BGCS.Core.Hosting; -using BGCS.Core.Ports; using BGCS.Core.Plugins; +using BGCS.Core.Ports; using BGCS.Frontend.Clang.Workers; using BGCS.Hosting.Standard; @@ -13,8 +13,8 @@ namespace Inno.Build.Bindings; internal static class BindingHostFactory { - internal static HostServices CreateHostServices(string baseDirectory) => new HostServicesProvider().Create( - new(baseDirectory, JsonSerializer.SerializeToElement(new { }))); + internal static HostServices CreateHostServices(string baseDirectory) + => new HostServicesProvider().Create(new(baseDirectory, JsonSerializer.SerializeToElement(new { }))); internal static BindingHostBuilder CreateBuilder( NativeBindingProfile profile, @@ -29,9 +29,13 @@ CancellationToken cancellation context => { HostServices host = context.RequireHostServices(); - return new FrontendWorkerClient(WorkerAssetLocator.Locate(host, applicationBase: application), host, - TimeSpan.FromSeconds(300)); - }); + return new FrontendWorkerClient( + WorkerAssetLocator.Locate(host, applicationBase: application), + host, + TimeSpan.FromSeconds(300) + ); + } + ); profile.Configure(builder); return builder; } diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs index a3b08f83b..6e9fcf5c8 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs @@ -27,20 +27,35 @@ CancellationToken cancellation root.id, root.kind == "generated" ? string.Empty : Path.GetRelativePath(engineRoot, bindings[root.id].directory).Replace('\\', '/'), root.kind == "generated", - root.kind is "generated" or "project" or "user")).ToArray(); + root.kind is "generated" or "project" or "user" + )).ToArray(); var sources = manifest.sources.Select(static source => source.relativePath).ToHashSet(StringComparer.Ordinal); - var files = manifest.inputs.Select(input => new NativeBindingSourceFile(input.rootId, input.relativePath, - input.length, input.digest.value, input.role == "ShimSource" - || input.rootId == "generated" && sources.Contains(input.relativePath))).ToList(); + var files = manifest.inputs.Select(input => new NativeBindingSourceFile( + input.rootId, + input.relativePath, + input.length, + input.digest.value, + input.role == "ShimSource" + || input.rootId == "generated" && sources.Contains(input.relativePath) + )).ToList(); foreach (ArtifactDescriptor artifact in manifest.sources.Concat(manifest.headers)) { if (!files.Any(file => file.rootId == "generated" && file.relativePath == artifact.relativePath)) - files.Add(new("generated", artifact.relativePath, new FileInfo(Path.Combine(nativeOutput, artifact.relativePath)).Length, - artifact.digest.value, sources.Contains(artifact.relativePath))); + { + files.Add( + new( + "generated", + artifact.relativePath, + new FileInfo(Path.Combine(nativeOutput, artifact.relativePath)).Length, + artifact.digest.value, + sources.Contains(artifact.relativePath) + ) + ); + } } var table = manifest.staticExportTable; var target = result.targetModels.Single(model => model.targetId == manifest.targetId).resolvedTarget - ?? throw new InvalidDataException("The SDK must return the resolved target used for generation."); + ?? throw new InvalidDataException("The SDK must return the resolved target used for generation."); var parserDefines = target.toolchain.defines.ToHashSet(StringComparer.Ordinal); var explicitDefines = request.configuration.source.defines.Concat(request.configuration.targets.Single().settings.defines) .ToHashSet(StringComparer.Ordinal); @@ -48,17 +63,34 @@ CancellationToken cancellation { roots = roots, files = files.OrderBy(static file => file.rootId, StringComparer.Ordinal) - .ThenBy(static file => file.relativePath, StringComparer.Ordinal).ToArray(), + .ThenBy(static file => file.relativePath, StringComparer.Ordinal) + .ToArray(), includeDirectories = manifest.includeDirectories.Select(static directory => new NativeBindingIncludeDirectory( - directory.rootId, directory.relativePath, directory.isSystem, directory.isFramework)).ToArray(), + directory.rootId, + directory.relativePath, + directory.isSystem, + directory.isFramework + )).ToArray(), defines = manifest.defines.Where(define => !parserDefines.Contains(define) || explicitDefines.Contains(define)).ToArray(), - compilerDefines = manifest.defines.Where(define => parserDefines.Contains(define) && !explicitDefines.Contains(define)).ToArray(), - cxxStandard = Math.Max(manifest.language == SourceLanguage.Cpp ? ParseStandard(manifest.languageStandard, "c++") : 0, - manifest.languageRequirements.Select(static requirement => requirement.minimumStandard).DefaultIfEmpty().Max()), + compilerDefines = manifest.defines + .Where(define => parserDefines.Contains(define) && !explicitDefines.Contains(define)) + .ToArray(), + cxxStandard = Math.Max( + manifest.language == SourceLanguage.Cpp ? ParseStandard(manifest.languageStandard, "c++") : 0, + manifest.languageRequirements.Select(static requirement => requirement.minimumStandard).DefaultIfEmpty().Max() + ), cStandard = manifest.language == SourceLanguage.C ? ParseStandard(manifest.languageStandard, "c") : 0, - requiredExports = manifest.exportBindings.Select(static binding => binding.exportName).Distinct(StringComparer.Ordinal).ToArray(), - staticExportSymbols = table is null ? [] : [table.getExportSymbol, table.getRevisionSymbol, table.getCountSymbol, - table.getAbiIdentitySymbol, table.getPointerSizeSymbol], + requiredExports = manifest.exportBindings + .Select(static binding => binding.exportName) + .Distinct(StringComparer.Ordinal) + .ToArray(), + staticExportSymbols = table is null ? [] : [ + table.getExportSymbol, + table.getRevisionSymbol, + table.getCountSymbol, + table.getAbiIdentitySymbol, + table.getPointerSizeSymbol + ], staticExportAbi = table?.abiIdentity ?? string.Empty, staticExportNames = table?.exportNames.ToArray() ?? [] }; @@ -73,8 +105,10 @@ string prefix ) { string normalized = standard.StartsWith("gnu", StringComparison.Ordinal) ? "c" + standard[3..] : standard; if (!normalized.StartsWith(prefix, StringComparison.Ordinal) - || !int.TryParse(normalized.AsSpan(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out int value)) + || !int.TryParse(normalized.AsSpan(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out int value) + ) { throw new InvalidDataException("The selected native language standard cannot be represented by CMake: " + standard); + } return value; } } diff --git a/build/bindings/Inno.Build.Bindings/Generation/TargetBindingGeneration.cs b/build/bindings/Inno.Build.Bindings/Generation/TargetBindingGeneration.cs index 6a04f66b1..e2a5eab84 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/TargetBindingGeneration.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/TargetBindingGeneration.cs @@ -24,7 +24,9 @@ CancellationToken cancellation BindingGenerationDiagnostics.RequireEqual(native, Path.Combine(publication.managedDestination, "Native"), false); } else + { BuildArtifactManifest.Write(publication.targetCandidate, fingerprint, ["Native", "Generated"], context); + } } internal static NativeBindingGenerationDescriptor Describe( diff --git a/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs b/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs index 8e43a4bff..32928dd90 100644 --- a/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs +++ b/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs @@ -21,7 +21,9 @@ NativeBindingProfile profile foreach (NativeComponentDescriptor component in request.components) { BindingGenerationConfiguration definition = BindingDefinitionReader.Read(context, component, request, profile); - declarations.Add(NativeBindingGenerationIdentity.Compute(definition.Load(context, cancellation), definition, context, cancellation)); + declarations.Add( + NativeBindingGenerationIdentity.Compute(definition.Load(context, cancellation), definition, context, cancellation) + ); } return ValueTask.FromResult(NativeBuildFingerprint.Create(context, declarations, [], cancellation)); } diff --git a/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs b/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs index 34625fdae..68058f88b 100644 --- a/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs +++ b/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs @@ -32,7 +32,9 @@ CancellationToken cancellation using HostServices services = BindingHostFactory.CreateHostServices(context.engineRoot); var builder = BindingHostFactory.CreateBuilder(definition.profile, cancellation); foreach (string plugin in request.configuration.extensions.plugins) + { builder.AddPluginManifest(plugin, services.paths); + } BindingHost host = builder.Build(); try { @@ -44,9 +46,14 @@ CancellationToken cancellation { targetId = target.id, triple = target.triple, - toolchain = new NativeToolchainDescriptor(compilerPath: settings.compilerPath, sysRoot: settings.sysRoot, - systemIncludeFolders: settings.systemIncludeDirectories, cxxSystemIncludeFolders: settings.cxxSystemIncludeDirectories, - defines: settings.defines, arguments: settings.arguments), + toolchain = new NativeToolchainDescriptor( + compilerPath: settings.compilerPath, + sysRoot: settings.sysRoot, + systemIncludeFolders: settings.systemIncludeDirectories, + cxxSystemIncludeFolders: settings.cxxSystemIncludeDirectories, + defines: settings.defines, + arguments: settings.arguments + ), languageStandard = source.languageStandard!, includeDirectories = source.includeDirectories, systemIncludeDirectories = source.systemIncludeDirectories, @@ -59,7 +66,9 @@ CancellationToken cancellation parseSystemIncludes = source.includeSystemDeclarations }, cancellation).GetAwaiter().GetResult(); if (!analysis.success || analysis.snapshot is null) + { throw new InvalidDataException("BGCS input analysis failed: " + analysis.GetDiagnosticSummary()); + } var declarations = new List { SerializeIdentity(config), @@ -72,26 +81,47 @@ CancellationToken cancellation definition.request.targetId, definition.request.outputMode.ToString() }; - var profileInputs = definition.profile.inputPaths.Select(path => NativeBuildInput.FromPath(context.engineRoot, Path.GetFullPath(path, context.engineRoot))); - var inputs = request.configurationSnapshot.files.Concat(request.pluginSnapshots.SelectMany(static snapshot => snapshot.files)).Concat(analysis.snapshot.files) - .Concat(analysis.argumentInputs?.files ?? []).Select(input => NativeBuildInput.FromPath(context.engineRoot, input.path)).ToList(); + var profileInputs = definition.profile.inputPaths.Select( + path => NativeBuildInput.FromPath(context.engineRoot, Path.GetFullPath(path, context.engineRoot)) + ); + var inputs = request.configurationSnapshot.files + .Concat(request.pluginSnapshots.SelectMany(static snapshot => snapshot.files)) + .Concat(analysis.snapshot.files) + .Concat(analysis.argumentInputs?.files ?? []) + .Select(input => NativeBuildInput.FromPath(context.engineRoot, input.path)) + .ToList(); inputs.AddRange(profileInputs); Assembly implementation = typeof(NativeBindingGenerator).Assembly; string implementationIdentity = implementation.GetCustomAttributes() .Single(attribute => attribute.Key == "Inno.BindingImplementation").Value ?? throw new InvalidDataException("The binding implementation must declare its content identity."); declarations.Add("bindingImplementation=" + implementationIdentity); - var assemblies = new[] { typeof(BindingHost).Assembly, typeof(BGCS.Core.BindingDiagnostic).Assembly, - typeof(BGCS.Runtime.NativeModuleSession).Assembly }.Concat(definition.profile.GetExtensionAssemblies()).ToList(); - foreach (AssemblyName reference in assemblies.Prepend(implementation).SelectMany(static assembly => assembly.GetReferencedAssemblies()) - .Where(static reference => reference.Name == "BGCS" || reference.Name!.StartsWith("BGCS.", StringComparison.Ordinal)) - .DistinctBy(static reference => reference.FullName).ToArray()) + var assemblies = new[] + { + typeof(BindingHost).Assembly, + typeof(BGCS.Core.BindingDiagnostic).Assembly, + typeof(BGCS.Runtime.NativeModuleSession).Assembly + }.Concat(definition.profile.GetExtensionAssemblies()).ToList(); + foreach (AssemblyName reference in assemblies + .Prepend(implementation) + .SelectMany(static assembly => assembly.GetReferencedAssemblies()) + .Where( + static reference => reference.Name == "BGCS" || reference.Name!.StartsWith("BGCS.", StringComparison.Ordinal) + ) + .DistinctBy(static reference => reference.FullName) + .ToArray() + ) { assemblies.Add(Assembly.Load(reference)); + } foreach (Assembly assembly in assemblies.Distinct()) + { inputs.Add(new NativeBuildInput("binding-implementation/" + Path.GetFileName(assembly.Location), assembly.Location)); + } string resources = Path.Combine(Path.GetDirectoryName(typeof(BindingHost).Assembly.Location)!, "bgcs", "worker-assets"); if (!Directory.Exists(resources)) + { throw new DirectoryNotFoundException("The restored BGCS SDK worker content is missing: " + resources); + } inputs.Add(new NativeBuildInput("binding-worker-assets", resources)); return NativeBuildFingerprint.Create(context, declarations, inputs, cancellation); } @@ -129,10 +159,14 @@ JsonElement value { writer.WriteStartArray(); foreach (JsonElement element in value.EnumerateArray()) + { WriteIdentity(writer, element); + } writer.WriteEndArray(); } else + { value.WriteTo(writer); + } } } diff --git a/build/bindings/Inno.Build.Bindings/Output/BindingGenerationDiagnostics.cs b/build/bindings/Inno.Build.Bindings/Output/BindingGenerationDiagnostics.cs index 755fe4ef7..f2536bb1e 100644 --- a/build/bindings/Inno.Build.Bindings/Output/BindingGenerationDiagnostics.cs +++ b/build/bindings/Inno.Build.Bindings/Output/BindingGenerationDiagnostics.cs @@ -20,18 +20,28 @@ internal static void Generate( string managedOutput, CancellationToken cancellation ) { - GenerationRequest selected = request.WithConfiguration(request.configuration with - { - output = request.configuration.output with { root = candidate } - }); + GenerationRequest selected = request.WithConfiguration( + request.configuration with + { + output = request.configuration.output with { root = candidate } + } + ); context.RecordBindingGeneration(); string root = Path.Combine(context.engineRoot, "artifacts", "build-tools", "bindings", "sdk-workspaces"); string workspace = selected.configuration.cache.directory; var cache = new BuildCachePublisher(root, BuildCacheArtifactRole.ReusableWorkspace); - BuildCacheOwnerCatalog.Register(context.engineRoot, root, "bgcs-workspaces", BuildCacheArtifactRole.ReusableWorkspace, cancellation); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + root, + "bgcs-workspaces", + BuildCacheArtifactRole.ReusableWorkspace, + cancellation + ); using FileLease activity = cache.AcquireUseAsync(cancellation).AsTask().GetAwaiter().GetResult(); using FileLease ownership = FileLease.AcquireAsync(workspace + ".lock", Timeout.InfiniteTimeSpan, cancellation) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); cache.BeginWorkingDirectory(workspace, workspace + ".lock", definition.request.targetId, cancellation); BindingHostExecution.Generate(selected, definition.profile, context.engineRoot, nativeOutput, managedOutput, cancellation); cache.Record(workspace, workspace + ".lock", [], null, definition.request.targetId, cancellation); @@ -44,16 +54,24 @@ bool normalizeNewlines ) { string[] files = Directory.EnumerateFiles(candidate, "*", SearchOption.AllDirectories).ToArray(); if (!Directory.Exists(current) || Directory.EnumerateFiles(current, "*", SearchOption.AllDirectories).Count() != files.Length) + { throw new InvalidDataException($"Generated output is missing or has a different file inventory: {current}"); + } foreach (string file in files) { string other = Path.Combine(current, Path.GetRelativePath(candidate, file)); - bool equal = File.Exists(other) && (normalizeNewlines - ? File.ReadAllText(file).Replace("\r\n", "\n", StringComparison.Ordinal) - == File.ReadAllText(other).Replace("\r\n", "\n", StringComparison.Ordinal) - : File.ReadAllBytes(file).AsSpan().SequenceEqual(File.ReadAllBytes(other))); + bool equal = + File.Exists(other) + && ( + normalizeNewlines + ? File.ReadAllText(file).Replace("\r\n", "\n", StringComparison.Ordinal) + == File.ReadAllText(other).Replace("\r\n", "\n", StringComparison.Ordinal) + : File.ReadAllBytes(file).AsSpan().SequenceEqual(File.ReadAllBytes(other)) + ); if (!equal) + { throw new InvalidDataException($"Generated output is out of date: {other}"); + } } } } diff --git a/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs b/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs index 4fc3d107f..e0ab53972 100644 --- a/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs +++ b/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; -using System.Threading; -using Inno.Core.IO; using System.IO; using System.Linq; +using System.Threading; +using Inno.Core.IO; namespace Inno.Build.Bindings; @@ -29,7 +29,9 @@ CancellationToken cancellation m_target = target; m_candidates.Add(destination, Path.Combine(m_owner.directory, "Managed")); if (native is not null) + { m_candidates.Add(native, Path.Combine(m_owner.directory, "Native")); + } } internal string managedDestination { get; } @@ -94,9 +96,13 @@ internal void Commit() try { if (installed.Contains(destination)) + { Directory.Move(destination, m_candidates[destination]); + } if (previous.TryGetValue(destination, out string? backup)) + { Directory.Move(backup, destination); + } } catch (Exception rollbackFailure) { @@ -107,7 +113,13 @@ internal void Commit() { m_preserveRecovery = true; new Inno.Build.Toolchains.BuildCachePublisher(m_workingRoot, Inno.Build.Toolchains.BuildCacheArtifactRole.ImmutableArtifact) - .Record(m_owner.directory, m_owner.directory + ".work.lock", [], "binding-recovery:" + Path.GetFileName(m_owner.directory), null); + .Record( + m_owner.directory, + m_owner.directory + ".work.lock", + [], + "binding-recovery:" + Path.GetFileName(m_owner.directory), + null + ); throw new AggregateException("Binding publication failed; owned recovery trees could not be fully restored.", failures); } throw; @@ -120,6 +132,8 @@ internal void Commit() public void Dispose() { if (!m_preserveRecovery) + { m_owner.Dispose(); + } } } diff --git a/build/cli/Inno.Build.Cli/BuildCommand.cs b/build/cli/Inno.Build.Cli/BuildCommand.cs index b41b3c5fa..25642bdb7 100644 --- a/build/cli/Inno.Build.Cli/BuildCommand.cs +++ b/build/cli/Inno.Build.Cli/BuildCommand.cs @@ -27,11 +27,13 @@ IReadOnlyDictionary values this.kind = kind; m_values = values; if (kind == BuildCommandKind.Game) + { _ = Require(values, "target"); + } projectDirectory = Require(values, "project"); supportPackRoot = kind == BuildCommandKind.Game - ? Require(values, "support-packs") - : values.GetValueOrDefault("support-packs", Path.Combine(AppContext.BaseDirectory, "SupportPacks")); + ? Require(values, "support-packs") + : values.GetValueOrDefault("support-packs", Path.Combine(AppContext.BaseDirectory, "SupportPacks")); } internal BuildCommandKind kind { get; } @@ -61,7 +63,9 @@ IReadOnlyDictionary values internal static BuildCommand Parse(IReadOnlyList args) { if (args.Count == 0 || args[0] is "help" or "--help" or "-h") + { throw new ArgumentException(Usage()); + } BuildCommandKind kind = args[0] switch { "game" => BuildCommandKind.Game, @@ -75,7 +79,9 @@ internal static BuildCommand Parse(IReadOnlyList args) { string argument = args[index]; if (!argument.StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Unexpected argument '{argument}'."); + } string key = argument[2..]; if (key is "include-dependencies" or "ide") { @@ -83,7 +89,9 @@ internal static BuildCommand Parse(IReadOnlyList args) continue; } if (++index >= args.Count || args[index].StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Argument '--{key}' requires a value."); + } values.Add(key, args[index]); } string[] specific = kind switch @@ -95,11 +103,19 @@ internal static BuildCommand Parse(IReadOnlyList args) _ => [] }; string[] preparation = kind is BuildCommandKind.Game or BuildCommandKind.Plugin - ? ["tools-target", "support-packs", "native-dependencies"] : []; - var allowed = new HashSet(["engine-root", "dotnet", "project", "output", ..preparation, ..specific], StringComparer.Ordinal); + ? ["tools-target", "support-packs", "native-dependencies"] + : []; + var allowed = new HashSet( + ["engine-root", "dotnet", "project", "output", ..preparation, ..specific], + StringComparer.Ordinal + ); foreach (string key in values.Keys) + { if (!allowed.Contains(key)) + { throw new ArgumentException($"Unknown argument '--{key}' for '{args[0]}'."); + } + } return new BuildCommand(kind, values); } @@ -107,11 +123,17 @@ internal GameBuildRequest CreateGameRequest(BuildProfile profile) { ArgumentNullException.ThrowIfNull(profile); if (m_values.TryGetValue("startup-scene", out string? scene)) + { profile.startupScene = AssetPath.Parse(scene).ToString(); + } if (m_values.TryGetValue("target", out string? target)) + { profile.target = new BuildTargetId(target); + } if (m_values.TryGetValue("deployment", out string? deployment)) + { profile.managedDeployment = new ManagedDeploymentId(deployment); + } return new GameBuildRequest { profile = profile, @@ -121,29 +143,28 @@ internal GameBuildRequest CreateGameRequest(BuildProfile profile) internal PluginBuildRequest CreatePluginRequest(ProjectId projectId) => new() - { - pluginId = projectId.value, - displayName = Require(m_values, "display-name"), - outputPath = Require(m_values, "output"), - dependencies = m_values.TryGetValue("dependencies", out string? dependencyList) - ? dependencyList.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) - : Array.Empty(), - includeDependencies = m_values.ContainsKey("include-dependencies") - }; + { + pluginId = projectId.value, + displayName = Require(m_values, "display-name"), + outputPath = Require(m_values, "output"), + dependencies = m_values.TryGetValue("dependencies", out string? dependencyList) + ? dependencyList.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) + : Array.Empty(), + includeDependencies = m_values.ContainsKey("include-dependencies") + }; private static string Require( IReadOnlyDictionary values, string key - ) - => values.TryGetValue(key, out string? value) && !string.IsNullOrWhiteSpace(value) - ? value - : throw new ArgumentException($"Required argument '--{key}' is missing."); + ) => values.TryGetValue(key, out string? value) && !string.IsNullOrWhiteSpace(value) + ? value + : throw new ArgumentException($"Required argument '--{key}' is missing."); private static string Usage() => "Usage:\n" - + " Project commands accept [--engine-root ] for an executable outside the source checkout.\n" - + " InnoEngine.Build game --tools-target --project --support-packs --output [--profile ] --target [--deployment ] [--startup-scene ]\n" - + " InnoEngine.Build plugin --tools-target --project --output --display-name [--dependencies ] [--include-dependencies]\n" - + " InnoEngine.Build import-sample --project --source [--dotnet ]\n" - + " InnoEngine.Build scripts --project --output [--dotnet ] [--ide]"; + + " Project commands accept [--engine-root ] for an executable outside the source checkout.\n" + + " InnoEngine.Build game --tools-target --project --support-packs --output [--profile ] --target [--deployment ] [--startup-scene ]\n" + + " InnoEngine.Build plugin --tools-target --project --output --display-name [--dependencies ] [--include-dependencies]\n" + + " InnoEngine.Build import-sample --project --source [--dotnet ]\n" + + " InnoEngine.Build scripts --project --output [--dotnet ] [--ide]"; } diff --git a/build/cli/Inno.Build.Cli/BuildCommandContext.cs b/build/cli/Inno.Build.Cli/BuildCommandContext.cs index fb3648bc2..6bc902245 100644 --- a/build/cli/Inno.Build.Cli/BuildCommandContext.cs +++ b/build/cli/Inno.Build.Cli/BuildCommandContext.cs @@ -17,15 +17,21 @@ internal BuildCommandContext(BuildCommandLine options) nativeDependencies = options.Read("native-dependencies", string.Empty); root = ResolveEngineRoot(options.Read("engine-root", string.Empty)); if (nativeDependencies.Length > 0) + { nativeDependencies = Path.GetFullPath(nativeDependencies, root); + } configuration = options.Read("configuration", "Release"); ToolchainEnvironment.ValidateConfiguration(configuration.ToLowerInvariant()); configuration = configuration.Equals("debug", StringComparison.OrdinalIgnoreCase) ? "Debug" : "Release"; toolsTarget = new BuildTargetId(options.Require("tools-target")); target = new BuildTargetId(options.Read("target", toolsTarget.value)); string dotnet = ToolchainEnvironment.ResolveExecutable(options.Read("dotnet", "dotnet")); - composition = StandardBuildEnvironment.Capture(Path.GetDirectoryName(typeof(BuildApplication).Assembly.Location)!, toolsTarget, dotnet, - nativeDependencies.Length == 0 ? null : nativeDependencies); + composition = StandardBuildEnvironment.Capture( + Path.GetDirectoryName(typeof(BuildApplication).Assembly.Location)!, + toolsTarget, + dotnet, + nativeDependencies.Length == 0 ? null : nativeDependencies + ); distribution = StandardBuildDistribution.Create(composition).build; } @@ -41,7 +47,9 @@ internal static string ResolveEngineRoot(string? selectedRoot) { string root = Path.GetFullPath(string.IsNullOrWhiteSpace(selectedRoot) ? ToolchainEnvironment.FindRepoRoot() : selectedRoot); if (!File.Exists(Path.Combine(root, "InnoEngine.sln"))) + { throw new DirectoryNotFoundException($"Engine checkout is unavailable at '{root}'."); + } return root; } @@ -50,18 +58,28 @@ internal async Task PreflightEditorAsync(CancellationToken cancellationT cancellationToken.ThrowIfCancellationRequested(); BuildPlatformContribution? platform = distribution.platforms.SingleOrDefault(value => value.descriptor.id == target); string project = platform?.editorProject - ?? throw new NotSupportedException($"Target '{target}' does not provide an Editor product."); + ?? throw new NotSupportedException($"Target '{target}' does not provide an Editor product."); var native = new NativeBuildContext(root, configuration.ToLowerInvariant()); if (nativeDependencies.Length == 0) - await distribution.ResolveNativeToolchain(target.value).ResolveAsync(native, composition.host, - target.value, cancellationToken).ConfigureAwait(false); + { + await distribution.ResolveNativeToolchain(target.value).ResolveAsync( + native, + composition.host, + target.value, + cancellationToken + ).ConfigureAwait(false); + } return Path.Combine(root, "entry", "InnoEngine.Editor", "InnoEngine.Editor.csproj"); } - internal string[] ProductArguments(string project) => - [ - project, "--configuration", configuration, - "--disable-build-servers", "-m:1", "-nodeReuse:false", - ..(nativeDependencies.Length == 0 ? Array.Empty() : ["-p:InnoNativeDependencyManifest=" + nativeDependencies]) - ]; + internal string[] ProductArguments(string project) + => [ + project, + "--configuration", + configuration, + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + ..(nativeDependencies.Length == 0 ? Array.Empty() : ["-p:InnoNativeDependencyManifest=" + nativeDependencies]) + ]; } diff --git a/build/cli/Inno.Build.Cli/BuildCommandLine.cs b/build/cli/Inno.Build.Cli/BuildCommandLine.cs index 045660602..91c67a3fe 100644 --- a/build/cli/Inno.Build.Cli/BuildCommandLine.cs +++ b/build/cli/Inno.Build.Cli/BuildCommandLine.cs @@ -14,17 +14,23 @@ internal static BuildCommandLine Parse(IReadOnlyList arguments) { string key = arguments[index]; if (!key.StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Expected '--name value'; incomplete option '{key}'."); + } bool flag = key is "--clean" or "--dry-run"; string value = "true"; if (!flag) { if (++index >= arguments.Count || arguments[index].StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Missing value for '{key}'."); + } value = arguments[index]; } if (!result.m_values.TryAdd(key[2..], value)) + { throw new ArgumentException($"Duplicate option '{key}'."); + } } return result; } @@ -35,8 +41,12 @@ internal void Validate(params string[] allowed) { var names = new HashSet(allowed, StringComparer.Ordinal); foreach (string key in m_values.Keys) + { if (!names.Contains(key)) + { throw new ArgumentException($"Unknown option '--{key}'."); + } + } } internal string Read( @@ -46,5 +56,6 @@ string defaultValue internal string Require(string name) => m_values.TryGetValue(name, out string? value) && !string.IsNullOrWhiteSpace(value) - ? value : throw new ArgumentException($"Required option '--{name}' is missing."); + ? value + : throw new ArgumentException($"Required option '--{name}' is missing."); } diff --git a/build/cli/Inno.Build.Cli/BuildComposition.cs b/build/cli/Inno.Build.Cli/BuildComposition.cs index 7754f497e..87ac8f56c 100644 --- a/build/cli/Inno.Build.Cli/BuildComposition.cs +++ b/build/cli/Inno.Build.Cli/BuildComposition.cs @@ -31,12 +31,28 @@ internal static async Task PrepareNativeAsync( var distribution = StandardBuildDistribution.Create(context).build; NativeProductContribution contribution = distribution.ResolveNativeProduct(context.toolsTarget.value, "shader-tools"); if (nativeDependencies is not null) - return await NativeDependencyManifest.AcquireAsync(engineRoot, nativeDependencies, context.toolsTarget.value, - C_HOST_CONFIGURATION, contribution.plan, cancellationToken).ConfigureAwait(false); - var nativeContext = new NativeBuildContext(engineRoot, C_HOST_CONFIGURATION).WithBindingGenerator(StandardBuildDistribution.Create(context).build.ResolveBindingGenerator(context.toolsTarget.value)); + { + return await NativeDependencyManifest.AcquireAsync( + engineRoot, + nativeDependencies, + context.toolsTarget.value, + C_HOST_CONFIGURATION, + contribution.plan, + cancellationToken + ).ConfigureAwait(false); + } + var nativeContext = new NativeBuildContext(engineRoot, C_HOST_CONFIGURATION).WithBindingGenerator( + StandardBuildDistribution.Create(context).build.ResolveBindingGenerator(context.toolsTarget.value) + ); var provider = StandardBuildDistribution.Create(context).build.ResolveNativeToolchain(context.toolsTarget.value); - nativeContext = nativeContext.WithToolchain(await provider.ResolveAsync( - nativeContext, context.host, context.toolsTarget.value, cancellationToken).ConfigureAwait(false)); + nativeContext = nativeContext.WithToolchain( + await provider.ResolveAsync( + nativeContext, + context.host, + context.toolsTarget.value, + cancellationToken + ).ConfigureAwait(false) + ); return await contribution.BuildAsync(nativeContext, cancellationToken).ConfigureAwait(false); } @@ -51,6 +67,14 @@ internal static BuildPipeline CreatePipeline( ToolRunner tools ) { return BuildPipelineFactory.Create( - context, StandardBuildDistribution.Create(context, tools).build, engine, assets, plugins, settings, compiler, supportPackRoot); + context, + StandardBuildDistribution.Create(context, tools).build, + engine, + assets, + plugins, + settings, + compiler, + supportPackRoot + ); } } diff --git a/build/cli/Inno.Build.Cli/BuildWorkspace.cs b/build/cli/Inno.Build.Cli/BuildWorkspace.cs index ee85160c6..3a30bc2ae 100644 --- a/build/cli/Inno.Build.Cli/BuildWorkspace.cs +++ b/build/cli/Inno.Build.Cli/BuildWorkspace.cs @@ -1,22 +1,21 @@ -using Inno.Build.Composition; -using Inno.Build.Toolchains.Bgfx.Tools; -using Inno.Core.IO; -using Inno.Extensibility.Modules; -using Inno.Adapter.Modules.DotNet; -using Inno.Adapter.Serialization.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; - +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Build; +using Inno.Build.Composition; +using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Execution; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Settings; +using Inno.Extensibility.Modules; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; @@ -76,11 +75,19 @@ CancellationToken cancellationToken ) => { ScriptCompilationResult result = await m_compiler.CompileAuthoringGenerationAsync( - cancellationToken: cancellationToken, sourceSnapshot: sources).ConfigureAwait(false); + cancellationToken: cancellationToken, + sourceSnapshot: sources + ).ConfigureAwait(false); if (!result.success) - throw new InvalidOperationException("Sample script preflight failed:" + Environment.NewLine - + string.Join(Environment.NewLine, - result.diagnostics.Select(static diagnostic => diagnostic.message))); + { + throw new InvalidOperationException( + "Sample script preflight failed:" + Environment.NewLine + + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => diagnostic.message) + ) + ); + } }); while (!import.isValidationComplete) { @@ -104,24 +111,31 @@ CancellationToken cancellationToken ) { ArgumentException.ThrowIfNullOrWhiteSpace(outputDirectory); ScriptCompilationResult result = m_compiler.CompileAuthoringGenerationAsync(cancellationToken: cancellationToken) - .GetAwaiter().GetResult(); + .GetAwaiter() + .GetResult(); if (!result.success) - throw new InvalidOperationException("Project script compilation failed:" + Environment.NewLine - + string.Join(Environment.NewLine, - result.diagnostics.Select(static diagnostic => diagnostic.message))); + { + throw new InvalidOperationException( + "Project script compilation failed:" + Environment.NewLine + + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message)) + ); + } if (generateIdeProjects) + { m_compiler.GenerateProjectFiles(); + } cancellationToken.ThrowIfCancellationRequested(); string[] assemblies = result.moduleDeployments .Where(static request => request.domain == Inno.Extensibility.Modules.AssemblyDomain.InnoScripting) - .SelectMany(static request => new[] { request.mainAssemblyPath } - .Concat(request.preloadAssemblyPaths)) + .SelectMany(static request => new[] { request.mainAssemblyPath }.Concat(request.preloadAssemblyPaths)) .Distinct(StringComparer.OrdinalIgnoreCase) .ToArray(); string destination = Path.GetFullPath(outputDirectory); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); using ProcessOwnedDirectory stagingOwner = ProcessOwnedDirectory.CreateAsync(Path.GetDirectoryName(destination)!, cancellationToken) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); string staging = stagingOwner.directory; try { @@ -131,7 +145,9 @@ CancellationToken cancellationToken File.Copy(assembly, Path.Combine(staging, Path.GetFileName(assembly))); string symbols = Path.ChangeExtension(assembly, ".pdb"); if (File.Exists(symbols)) + { File.Copy(symbols, Path.Combine(staging, Path.GetFileName(symbols))); + } } try { @@ -161,7 +177,9 @@ CancellationToken cancellationToken string pluginsRoot = Path.Combine(projectRoot, "Plugins"); string libraryRoot = Path.Combine(projectRoot, "Library"); if (!Directory.Exists(assetsRoot)) + { throw new DirectoryNotFoundException($"Project Assets directory '{assetsRoot}' does not exist."); + } Directory.CreateDirectory(pluginsRoot); Directory.CreateDirectory(libraryRoot); @@ -172,14 +190,18 @@ CancellationToken cancellationToken try { engine = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(BuildWorkspace).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(BuildWorkspace).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); var sources = new PluginSourceService(engine.serialization, pluginsRoot, libraryRoot); PluginScanResult scan = sources.Scan(); AssetPipelineOptions options = AssetPipelineOptions.Create(assetsRoot, libraryRoot); - AssetSourceMount projectMount = options.sourceMounts!.Single(static mount => - mount.id == AssetSourceId.project); + AssetSourceMount projectMount = options.sourceMounts!.Single(static mount => ( + mount.id == AssetSourceId.project + )); assets = new AssetPipeline( engine.modules, engine.types, @@ -196,13 +218,15 @@ options with projectMount, .. PluginSourceService.GetActivatableMounts(scan) ] - }); + } + ); settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, SettingsFileNames.project))), engine.types, engine.serialization, ProjectId.FromName(new DirectoryInfo(projectRoot).Name), - AssetSerializationContext.Create(assets)); + AssetSerializationContext.Create(assets) + ); plugins = new PluginEnvironment( assets, settings, @@ -210,13 +234,19 @@ .. PluginSourceService.GetActivatableMounts(scan) pluginsRoot, libraryRoot, scan, - engine.modules.generations); + engine.modules.generations + ); if (plugins.discovery.diagnostics.Count != 0 - || plugins.activePlugins.Count != scan.candidates.Count) - { - throw new InvalidOperationException("Installed Plugin activation failed:" + Environment.NewLine - + string.Join(Environment.NewLine, plugins.discovery.diagnostics.Select(static diagnostic => - $"{diagnostic.sourcePath}: {diagnostic.message}"))); + || plugins.activePlugins.Count != scan.candidates.Count + ) { + throw new InvalidOperationException( + "Installed Plugin activation failed:" + Environment.NewLine + + string.Join( + Environment.NewLine, + plugins.discovery.diagnostics.Select(static diagnostic => + $"{diagnostic.sourcePath}: {diagnostic.message}") + ) + ); } var compiler = new ScriptCompiler( new ScriptCompilerOptions @@ -225,7 +255,8 @@ .. PluginSourceService.GetActivatableMounts(scan) compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) }, assets, - plugins); + plugins + ); ActivateAuthoring(engine, plugins, compiler, Path.Combine(libraryRoot, "Build", "Metadata"), cancellationToken); engine.generations.Wait(); assets.CompleteExtensionDiscovery(); @@ -245,19 +276,18 @@ .. PluginSourceService.GetActivatableMounts(scan) private static IModuleSource CreateScriptModuleSource( ScriptModuleDeployment deployment, string artifactRootDirectory - ) - => new DotNetModuleSource - { - artifactRootDirectory = artifactRootDirectory, - moduleName = deployment.moduleName, - mainAssemblyPath = deployment.mainAssemblyPath, - domain = deployment.domain, - scope = deployment.scope, - preloadAssemblyPaths = deployment.preloadAssemblyPaths, - upstreamModuleNames = deployment.upstreamModuleNames, - assemblyScopes = deployment.assemblyScopes, - collectible = true - }; + ) => new DotNetModuleSource + { + artifactRootDirectory = artifactRootDirectory, + moduleName = deployment.moduleName, + mainAssemblyPath = deployment.mainAssemblyPath, + domain = deployment.domain, + scope = deployment.scope, + preloadAssemblyPaths = deployment.preloadAssemblyPaths, + upstreamModuleNames = deployment.upstreamModuleNames, + assemblyScopes = deployment.assemblyScopes, + collectible = true + }; private static void ActivateAuthoring( EngineHost engine, @@ -268,12 +298,20 @@ CancellationToken cancellationToken ) { // Asset importers and graph extensions belong to the authoring generation, including in a // headless build. Compiling only Player scripts would export unresolved/last-good asset state. - ScriptCompilationResult result = compiler.CompileAuthoringGenerationAsync(cancellationToken: cancellationToken).GetAwaiter().GetResult(); + ScriptCompilationResult result = compiler + .CompileAuthoringGenerationAsync(cancellationToken: cancellationToken) + .GetAwaiter() + .GetResult(); if (!result.success) - throw new InvalidOperationException("Build authoring compilation failed:" + Environment.NewLine - + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message))); + { + throw new InvalidOperationException( + "Build authoring compilation failed:" + Environment.NewLine + + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message)) + ); + } using Inno.Extensibility.Modules.AssemblyReloadSession reload = engine.modules.BeginReload( - result.moduleDeployments.Select(deployment => CreateScriptModuleSource(deployment, artifactRootDirectory)).ToArray()); + result.moduleDeployments.Select(deployment => CreateScriptModuleSource(deployment, artifactRootDirectory)).ToArray() + ); _ = engine.generations.Execute("Build authoring generation", reload, [plugins.CreateReloadChange()]); } @@ -303,25 +341,28 @@ BuildTargetId defaultTarget BuildSettings defaults = BuildSettings.CreateDefault( Path.GetFileName(Path.TrimEndingDirectorySeparator(m_projectDirectory)), FindDefaultStartupScene(), - defaultTarget); + defaultTarget + ); var settings = new BuildSettingsStore( Path.Combine(m_projectDirectory, SettingsFileNames.build), m_engine.serialization, - defaults); + defaults + ); return settings.Load().CreateGameProfile(projectId); } private string FindDefaultStartupScene() { foreach (AssetFileEntry entry in m_assets.GetFileSystemEntries(includeDirectories: false) - .Where(static entry => entry.source == AssetSourceId.project) - .Where(static entry => !AssetSample.IsRuntimeExcluded(entry.assetPath, isDirectory: false)) - .OrderBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal)) - { + .Where(static entry => entry.source == AssetSourceId.project) + .Where(static entry => !AssetSample.IsRuntimeExcluded(entry.assetPath, isDirectory: false)) + .OrderBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal) + ) { if (m_assets.TryGetAssetType(entry.assetPath, out Type? type) && type == typeof(SceneAsset)) + { return entry.assetPath.ToString(); + } } return string.Empty; } } - diff --git a/build/cli/Inno.Build.Cli/Cleanup/ProductCleanExecutor.cs b/build/cli/Inno.Build.Cli/Cleanup/ProductCleanExecutor.cs index 317ba1efa..e4da9bd8c 100644 --- a/build/cli/Inno.Build.Cli/Cleanup/ProductCleanExecutor.cs +++ b/build/cli/Inno.Build.Cli/Cleanup/ProductCleanExecutor.cs @@ -12,8 +12,19 @@ internal static class ProductCleanExecutor internal static ValueTask AcquireAsync( BuildCommandContext context, CancellationToken cancellationToken - ) => FileLease.AcquireAsync(Path.Combine(context.root, "artifacts", "products", "editor", context.target.value, - context.configuration, "product.lock"), TimeSpan.FromSeconds(10), cancellationToken); + ) => FileLease.AcquireAsync( + Path.Combine( + context.root, + "artifacts", + "products", + "editor", + context.target.value, + context.configuration, + "product.lock" + ), + TimeSpan.FromSeconds(10), + cancellationToken + ); internal static void Execute( ProductCleanPlan plan, @@ -22,13 +33,17 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); foreach (string directory in plan.directories) + { PathBoundary.RequireUnlinkedPath(plan.root, directory); + } foreach (string directory in plan.directories) { cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine($"{(dryRun ? "Would clean" : "Cleaning")} {directory}"); if (!dryRun) + { ToolchainEnvironment.DeleteDirectory(directory); + } } } } diff --git a/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs b/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs index db947ceb1..bfc9ec6a7 100644 --- a/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs +++ b/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs @@ -20,15 +20,24 @@ CancellationToken cancellationToken ) { var projects = new List { project }; foreach (var platform in context.distribution.platforms) + { if (platform.descriptor.id == context.target && platform.editorProject is not null) + { projects.Add(Path.GetFullPath(platform.editorProject, context.root)); + } + } var directories = new List(); foreach (string selected in projects) { string result = await ToolchainEnvironment.CaptureOutputAsync( context.composition.dotnetHost, - ["msbuild", selected, "-nologo", "-getProperty:TargetDir,IntermediateOutputPath", - "-p:Configuration=" + context.configuration], + [ + "msbuild", + selected, + "-nologo", + "-getProperty:TargetDir,IntermediateOutputPath", + "-p:Configuration=" + context.configuration + ], context.root, cancellationToken, DotNetSdkEnvironment.Create(context.composition.dotnetHost) @@ -52,8 +61,10 @@ string output string path = Path.GetFullPath(output, owner).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); string relative = Path.GetRelativePath(root, path); if (Path.IsPathRooted(relative) || relative == "." || relative == ".." - || relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + || relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) + ) { throw new InvalidOperationException($"The selected product output is outside its '{category}' owner: '{path}'."); + } return PathBoundary.RequireUnlinkedPath(root, path); } } diff --git a/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs b/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs index 537e41cd9..f6389f902 100644 --- a/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs @@ -35,21 +35,37 @@ CancellationToken cancellationToken ProductNativeBuildPlan product = distribution.ResolveNativeProduct(target.value, productId).plan; if (request.nativeDependencies.Length != 0) { - using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync(root, - request.nativeDependencies, target.value, configuration.ToLowerInvariant(), product, cancellationToken).ConfigureAwait(false); + using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( + root, + request.nativeDependencies, + target.value, + configuration.ToLowerInvariant(), + product, + cancellationToken + ).ConfigureAwait(false); return; } NativeBuildContext bindings = new(root, configuration.ToLowerInvariant()); bindings = bindings.WithBindingGenerator(distribution.ResolveBindingGenerator(target.value)); - bindings = bindings.WithToolchain(await distribution.ResolveNativeToolchain(target.value) - .ResolveAsync(bindings, context.host, target.value, cancellationToken).ConfigureAwait(false)); - var generation = new NativeBindingGenerationRequest(product.steps.Select(static step => step.component) - .Where(static owner => owner.bindingDefinition is not null).DistinctBy(static owner => owner.nativeProject), - target.value, NativeBindingOutputMode.TargetArtifacts, componentOptions: product.steps + bindings = bindings.WithToolchain( + await distribution.ResolveNativeToolchain(target.value) + .ResolveAsync(bindings, context.host, target.value, cancellationToken) + .ConfigureAwait(false) + ); + var generation = new NativeBindingGenerationRequest( + product.steps.Select(static step => step.component) + .Where(static owner => owner.bindingDefinition is not null) + .DistinctBy(static owner => owner.nativeProject), + target.value, + NativeBindingOutputMode.TargetArtifacts, + componentOptions: product.steps .Where(static step => step.component.bindingDefinition is not null) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal)); - using NativeBindingGenerationResult completed = await distribution.ResolveBindingGenerator(target.value).GenerateAsync(bindings, generation, cancellationToken).ConfigureAwait(false); - + .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal) + ); + using NativeBindingGenerationResult completed = await distribution + .ResolveBindingGenerator(target.value) + .GenerateAsync(bindings, generation, cancellationToken) + .ConfigureAwait(false); } } diff --git a/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs b/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs index 28ce259b5..6e5c56e73 100644 --- a/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs @@ -22,7 +22,9 @@ CancellationToken cancellationToken return; } if (scope != "product") + { throw new ArgumentException($"Unsupported cleanup scope '{scope}'."); + } string project = await context.PreflightEditorAsync(cancellationToken).ConfigureAwait(false); using var ownership = await ProductCleanExecutor.AcquireAsync(context, cancellationToken).ConfigureAwait(false); ProductCleanPlan plan = await ProductCleanPlan.CreateAsync(context, project, cancellationToken).ConfigureAwait(false); @@ -40,16 +42,37 @@ long ReadBytes( long fallback ) { string? value = options.Has(name) ? options.Require(name) : null; - return value is null ? fallback : checked(long.Parse(value, NumberStyles.None, CultureInfo.InvariantCulture) * 1024 * 1024 * 1024); + return value is null + ? fallback + : checked(long.Parse(value, NumberStyles.None, CultureInfo.InvariantCulture) * 1024 * 1024 * 1024); } - double seconds = double.Parse(options.Read("cache-time-seconds", automatic ? "5" : "600"), - NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); - var policy = new BuildCachePolicy(ReadBytes("cache-budget-gib", 64L << 30), ReadBytes("cache-min-free-gib", 20L << 30), - TimeSpan.FromSeconds(seconds)); + double seconds = double.Parse( + options.Read("cache-time-seconds", automatic ? "5" : "600"), + NumberStyles.AllowDecimalPoint, + CultureInfo.InvariantCulture + ); + var policy = new BuildCachePolicy( + ReadBytes("cache-budget-gib", 64L << 30), + ReadBytes("cache-min-free-gib", 20L << 30), + TimeSpan.FromSeconds(seconds) + ); if (!options.Has("dry-run")) - StandardBuildCaches.CreateOwners(context.root, context.distribution.platforms.SelectMany(static platform => platform.nativeProducts.Values) - .SelectMany(static product => product.plan.steps).Select(static step => step.component).ToArray()); - await BuildMaintenanceApplication.CleanAsync(context.root, policy, !automatic, options.Has("dry-run"), - !automatic && options.Has("target") ? options.Require("target") : null, cancellation).ConfigureAwait(false); + { + StandardBuildCaches.CreateOwners( + context.root, + context.distribution.platforms.SelectMany(static platform => platform.nativeProducts.Values) + .SelectMany(static product => product.plan.steps) + .Select(static step => step.component) + .ToArray() + ); + } + await BuildMaintenanceApplication.CleanAsync( + context.root, + policy, + !automatic, + options.Has("dry-run"), + !automatic && options.Has("target") ? options.Require("target") : null, + cancellation + ).ConfigureAwait(false); } } diff --git a/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs b/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs index 0c0e8bb11..887d235bd 100644 --- a/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs @@ -18,7 +18,12 @@ CancellationToken cancellationToken ProductCleanPlan plan = await ProductCleanPlan.CreateAsync(context, project, cancellationToken).ConfigureAwait(false); ProductCleanExecutor.Execute(plan, false, cancellationToken); } - await ToolchainEnvironment.RunAsync(context.composition.dotnetHost, ["build", ..context.ProductArguments(project), "-p:InnoSuppressBuildMaintenance=true"], - context.root, cancellationToken, DotNetSdkEnvironment.Create(context.composition.dotnetHost)).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + context.composition.dotnetHost, + ["build", ..context.ProductArguments(project), "-p:InnoSuppressBuildMaintenance=true"], + context.root, + cancellationToken, + DotNetSdkEnvironment.Create(context.composition.dotnetHost) + ).ConfigureAwait(false); } } diff --git a/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs b/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs index 37d3a792d..651df8355 100644 --- a/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs @@ -1,8 +1,8 @@ using System; using System.Diagnostics; using System.IO; -using System.Text.Json; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Inno.Build.Composition; @@ -10,6 +10,7 @@ using Inno.Build.Toolchains; namespace Inno.Build.Cli; + internal static class NativeDependenciesCommand { internal static async Task RunAsync( @@ -32,13 +33,18 @@ CancellationToken cancellation if (operation == "describe") { - BuildPlatformContribution platform = request.distribution.platforms.SingleOrDefault(platform => platform.descriptor.id == request.target) + BuildPlatformContribution platform = request.distribution.platforms.SingleOrDefault( + platform => platform.descriptor.id == request.target + ) ?? throw new NotSupportedException("No native dependency platform is registered for '" + request.target + "'."); - Inno.Core.IO.AtomicFile.WriteAllBytes(options.Require("output"), System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new - { - target = platform.descriptor.id.value, - products = platform.nativeProducts.Keys.Order(StringComparer.Ordinal).ToArray() - })); + Inno.Core.IO.AtomicFile.WriteAllBytes( + options.Require("output"), + System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new + { + target = platform.descriptor.id.value, + products = platform.nativeProducts.Keys.Order(StringComparer.Ordinal).ToArray() + }) + ); return; } @@ -46,22 +52,47 @@ CancellationToken cancellation if (operation == "verify-bindings") { if (options.Read("native-dependencies", string.Empty).Length != 0) + { throw new ArgumentException("Producer binding verification cannot consume a prebuilt selection."); + } var steps = product.plan.steps.Where(static step => step.component.bindingDefinition is not null) - .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal).ToArray(); + .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) + .ToArray(); if (steps.Length == 0) + { return; + } var generator = request.distribution.ResolveBindingGenerator(request.target.value); - var bindingContext = new NativeBuildContext(request.root, request.configuration.ToLowerInvariant()).WithBindingGenerator(generator); - bindingContext = bindingContext.WithToolchain(await request.distribution.ResolveNativeToolchain(request.target.value) - .ResolveAsync(bindingContext, request.composition.host, request.target.value, cancellation).ConfigureAwait(false)); + var bindingContext = new NativeBuildContext( + request.root, + request.configuration.ToLowerInvariant() + ).WithBindingGenerator(generator); + bindingContext = bindingContext.WithToolchain( + await request.distribution.ResolveNativeToolchain(request.target.value) + .ResolveAsync(bindingContext, request.composition.host, request.target.value, cancellation) + .ConfigureAwait(false) + ); // Verify the exact target publications being released, with their product linkage/options. // Authored host descriptors contain the author's SDK paths and are not target package evidence. - var bindingRequest = new NativeBindingGenerationRequest(steps.Select(static group => group.First().component), - request.target.value, NativeBindingOutputMode.TargetArtifacts, checkOnly: true, - componentOptions: steps.ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal)); - using NativeBindingGenerationResult verified = await generator.GenerateAsync(bindingContext, bindingRequest, cancellation).ConfigureAwait(false); - Console.WriteLine($"Verified target binding publications: {steps.Length}; native processes: {bindingContext.statistics.nativeProcesses}."); + var bindingRequest = new NativeBindingGenerationRequest( + steps.Select(static group => group.First().component), + request.target.value, + NativeBindingOutputMode.TargetArtifacts, + checkOnly: true, + componentOptions: steps.ToDictionary( + static group => group.Key, + static group => group.First().options, + StringComparer.Ordinal + ) + ); + using NativeBindingGenerationResult verified = await generator.GenerateAsync( + bindingContext, + bindingRequest, + cancellation + ).ConfigureAwait(false); + Console.WriteLine( + $"Verified target binding publications: {steps.Length}; native processes: {bindingContext.statistics.nativeProcesses}." + ); return; } @@ -70,47 +101,92 @@ CancellationToken cancellation string output = options.Require("output"); try { - var assets = await NativeDependencyManifest.SelectAsync(request.root, options.Require("native-dependencies"), - request.target.value, request.configuration.ToLowerInvariant(), product.plan, cancellation).ConfigureAwait(false); - byte[] result = operation == "select" ? JsonSerializer.SerializeToUtf8Bytes(assets) - : JsonSerializer.SerializeToUtf8Bytes(new { matched = true, assets }); + var assets = await NativeDependencyManifest.SelectAsync( + request.root, + options.Require("native-dependencies"), + request.target.value, + request.configuration.ToLowerInvariant(), + product.plan, + cancellation + ).ConfigureAwait(false); + byte[] result = operation == "select" + ? JsonSerializer.SerializeToUtf8Bytes(assets) + : JsonSerializer.SerializeToUtf8Bytes(new { matched = true, assets }); Inno.Core.IO.AtomicFile.WriteAllBytes(output, result); } catch (InvalidDataException failure) when (operation == "evaluate") { - Inno.Core.IO.AtomicFile.WriteAllBytes(output, JsonSerializer.SerializeToUtf8Bytes(new { matched = false, reason = failure.Message })); + Inno.Core.IO.AtomicFile.WriteAllBytes( + output, + JsonSerializer.SerializeToUtf8Bytes(new { matched = false, reason = failure.Message }) + ); } return; } if (operation != "produce") + { throw new ArgumentException("Unknown native dependency operation: " + operation); + } if (options.Read("native-dependencies", string.Empty).Length != 0) + { throw new ArgumentException("Dependency production cannot consume a prebuilt selection."); + } var phase = Stopwatch.StartNew(); - Console.WriteLine($"Native producer: {product.plan.productId}/{request.target.value}/{request.configuration}; resolving the explicit toolchain."); - var context = new NativeBuildContext(request.root, request.configuration.ToLowerInvariant()).WithBindingGenerator(request.distribution.ResolveBindingGenerator(request.target.value)); - context = context.WithToolchain(await request.distribution.ResolveNativeToolchain(request.target.value).ResolveAsync(context, request.composition.host, request.target.value, cancellation).ConfigureAwait(false)); + Console.WriteLine( + $"Native producer: {product.plan.productId}/{request.target.value}/{request.configuration}; resolving the explicit toolchain." + ); + var context = new NativeBuildContext(request.root, request.configuration.ToLowerInvariant()).WithBindingGenerator( + request.distribution.ResolveBindingGenerator(request.target.value) + ); + context = context.WithToolchain( + await request.distribution + .ResolveNativeToolchain(request.target.value) + .ResolveAsync(context, request.composition.host, request.target.value, cancellation) + .ConfigureAwait(false) + ); Report("toolchain"); StandardBuildCaches.CreateOwners(request.root, product.plan.steps.Select(static step => step.component).ToArray()); string identity = await ProductNativePreparation.FreezeAsync(context, product.plan, cancellation).ConfigureAwait(false); Report("input-capture"); using ProductNativeBuildResult products = await product.BuildAsync(context, cancellation).ConfigureAwait(false); Report("production"); - if (identity != await ProductNativePreparation.FreezeAsync(context.BeginInputVerification("dependency-export"), product.plan, cancellation).ConfigureAwait(false)) + if (identity != await ProductNativePreparation.FreezeAsync( + context.BeginInputVerification("dependency-export"), + product.plan, + cancellation + ).ConfigureAwait(false) + ) { throw new InvalidOperationException("Native producer inputs changed before export."); + } Report("pre-export-verification"); - string selection = await NativeDependencyManifest.ExportAsync(context, product.plan, products, options.Require("output"), cancellation).ConfigureAwait(false); + string selection = await NativeDependencyManifest.ExportAsync( + context, + product.plan, + products, + options.Require("output"), + cancellation + ).ConfigureAwait(false); Report("export"); - if (identity != await ProductNativePreparation.FreezeAsync(context.BeginInputVerification("dependency-export-complete"), product.plan, cancellation).ConfigureAwait(false)) + if (identity != await ProductNativePreparation.FreezeAsync( + context.BeginInputVerification("dependency-export-complete"), + product.plan, + cancellation + ).ConfigureAwait(false) + ) { throw new InvalidOperationException("Native producer inputs changed during export."); + } Report("closing-verification"); Console.WriteLine("Native dependency selection: " + selection); Console.WriteLine($"Native processes: {context.statistics.nativeProcesses}; hashed bytes: {context.statistics.hashedBytes}."); void Report(string name) { - Console.WriteLine(FormattableString.Invariant($"Native producer phase={name} seconds={phase.Elapsed.TotalSeconds:F3} nativeProcesses={context.statistics.nativeProcesses} hashedBytes={context.statistics.hashedBytes}")); + Console.WriteLine( + FormattableString.Invariant( + $"Native producer phase={name} seconds={phase.Elapsed.TotalSeconds:F3} nativeProcesses={context.statistics.nativeProcesses} hashedBytes={context.statistics.hashedBytes}" + ) + ); phase.Restart(); } } diff --git a/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs b/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs index 9653d10a6..74277e57f 100644 --- a/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs @@ -33,28 +33,55 @@ CancellationToken cancellationToken BgfxShaderTargetProfile platform = StandardBuildDistribution.Create(context).ResolveShaderTarget(target); if (!GraphicsApi.TryParse(options.Require("renderer"), out GraphicsApi renderer)) + { throw new ArgumentException("The shader platform or rendering API is invalid."); + } NativeBuildContext native = new NativeBuildContext(root, configuration.ToLowerInvariant()) .WithBindingGenerator(distribution.ResolveBindingGenerator(toolsTarget.value)); if (request.nativeDependencies.Length == 0) - native = native.WithToolchain(await distribution.ResolveNativeToolchain(toolsTarget.value) - .ResolveAsync(native, context.host, toolsTarget.value, cancellationToken).ConfigureAwait(false)); + { + native = native.WithToolchain( + await distribution.ResolveNativeToolchain(toolsTarget.value) + .ResolveAsync(native, context.host, toolsTarget.value, cancellationToken) + .ConfigureAwait(false) + ); + } NativeProductContribution contribution = distribution.ResolveNativeProduct(toolsTarget.value, "shader-tools"); using ProductNativeBuildResult products = request.nativeDependencies.Length == 0 - ? await contribution.BuildAsync(native, cancellationToken).ConfigureAwait(false) - : await NativeDependencyManifest.AcquireAsync(root, request.nativeDependencies, toolsTarget.value, - configuration.ToLowerInvariant(), contribution.plan, cancellationToken).ConfigureAwait(false); + ? await contribution.BuildAsync(native, cancellationToken).ConfigureAwait(false) + : await NativeDependencyManifest.AcquireAsync( + root, + request.nativeDependencies, + toolsTarget.value, + configuration.ToLowerInvariant(), + contribution.plan, + cancellationToken + ).ConfigureAwait(false); NativeBuildProduct product = products.Single(); string extension = context.host.services.executableExtension; - var executables = Enum.GetValues().ToDictionary(static tool => tool, - tool => product.files.Single(file => Path.GetFileName(file) == tool.ToString().ToLowerInvariant() - + extension)); + var executables = Enum.GetValues().ToDictionary( + static tool => tool, + tool => product.files.Single(file => ( + Path.GetFileName(file) == tool.ToString().ToLowerInvariant() + + extension + )) + ); string includes = Path.GetDirectoryName(product.files.Single(file => Path.GetFileName(file) == "bgfx_shader.sh"))!; ShaderBuildInputs inputs = ShaderBuildInputs.Capture(options.Require("assets"), cancellationToken); - using ProcessOwnedDirectory compilation = await StandardBuildCaches.CreateShaderWorkspaceAsync(root, cancellationToken).ConfigureAwait(false); - ShaderArtifactBuilder.Compile(inputs, compilation, options.Require("shader"), - platform, renderer, options.Require("output"), new ToolRunner(executables, includes, context.host.services.workspaces), cancellationToken); + using ProcessOwnedDirectory compilation = await StandardBuildCaches.CreateShaderWorkspaceAsync( + root, + cancellationToken + ).ConfigureAwait(false); + ShaderArtifactBuilder.Compile( + inputs, + compilation, + options.Require("shader"), + platform, + renderer, + options.Require("output"), + new ToolRunner(executables, includes, context.host.services.workspaces), + cancellationToken + ); return; - } } diff --git a/build/cli/Inno.Build.Cli/Commands/SupportBuildCommand.cs b/build/cli/Inno.Build.Cli/Commands/SupportBuildCommand.cs index de579e5f6..25becdc32 100644 --- a/build/cli/Inno.Build.Cli/Commands/SupportBuildCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/SupportBuildCommand.cs @@ -17,23 +17,34 @@ CancellationToken cancellationToken ) { string productId = options.Read("product", "editor"); if (productId is not ("editor" or "player")) + { throw new ArgumentException("Support preparation requires product 'editor' or 'player'."); + } NativeProductContribution product = request.distribution.ResolveNativeProduct(request.target.value, productId); if (request.nativeDependencies.Length != 0) { - using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync(request.root, - request.nativeDependencies, request.target.value, request.configuration.ToLowerInvariant(), product.plan, cancellationToken).ConfigureAwait(false); + using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( + request.root, + request.nativeDependencies, + request.target.value, + request.configuration.ToLowerInvariant(), + product.plan, + cancellationToken + ).ConfigureAwait(false); Console.WriteLine($"Consumed {productId} support for {request.target}: {imported.Count} artifacts; native processes: 0."); return; } var context = new NativeBuildContext(request.root, request.configuration.ToLowerInvariant()); context = context.WithBindingGenerator(request.distribution.ResolveBindingGenerator(request.target.value)); NativeToolchainSelection toolchain = await request.distribution.ResolveNativeToolchain(request.target.value) - .ResolveAsync(context, request.composition.host, request.target.value, cancellationToken).ConfigureAwait(false); + .ResolveAsync(context, request.composition.host, request.target.value, cancellationToken) + .ConfigureAwait(false); context = context.WithToolchain(toolchain); StandardBuildCaches.CreateOwners(context.engineRoot, product.plan.steps.Select(static step => step.component).ToArray()); using ProductNativeBuildResult products = await product.BuildAsync(context, cancellationToken).ConfigureAwait(false); Console.WriteLine($"Prepared {productId} support for {request.target}: {products.Count} artifacts."); - Console.WriteLine($"Native processes: {context.statistics.nativeProcesses}; binding generations: {context.statistics.bindingGenerations}."); + Console.WriteLine( + $"Native processes: {context.statistics.nativeProcesses}; binding generations: {context.statistics.bindingGenerations}." + ); } } diff --git a/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs b/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs index 848698798..8865985b6 100644 --- a/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs @@ -1,10 +1,10 @@ using System; using System.IO; using System.IO.Compression; -using Inno.Build.SupportPacks; -using Inno.Core.IO; using System.Threading; using System.Threading.Tasks; +using Inno.Build.SupportPacks; +using Inno.Core.IO; namespace Inno.Build.Cli; @@ -16,8 +16,14 @@ internal static async Task RunAsync( CancellationToken cancellationToken ) { string output = options.Read("output", Path.Combine(context.root, "artifacts", "support-packs")); - using PlayerSupportPackPublication pack = await context.distribution.supportPacks.PublishAsync(context.root, output, context.target, - context.composition.dotnetHost, cancellationToken, context.nativeDependencies.Length == 0 ? null : context.nativeDependencies).ConfigureAwait(false); + using PlayerSupportPackPublication pack = await context.distribution.supportPacks.PublishAsync( + context.root, + output, + context.target, + context.composition.dotnetHost, + cancellationToken, + context.nativeDependencies.Length == 0 ? null : context.nativeDependencies + ).ConfigureAwait(false); string archive = options.Read("archive", string.Empty); if (archive.Length != 0) { @@ -38,11 +44,15 @@ CancellationToken cancellationToken finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } } Console.WriteLine(pack.directory); foreach (string diagnostic in pack.diagnostics) + { Console.Error.WriteLine(diagnostic); + } } } diff --git a/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs b/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs index a91f4400d..cbd1537b1 100644 --- a/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs +++ b/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs @@ -36,42 +36,78 @@ CancellationToken cancellationToken { NativeVerificationOptions options = NativeVerificationOptions.Parse(args); string repositoryRoot = options.engineRoot; - BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, - new BuildTargetId(options.target), options.dotnet); + BuildCompositionContext execution = StandardBuildEnvironment.Capture( + AppContext.BaseDirectory, + new BuildTargetId(options.target), + options.dotnet + ); BuildDistribution distribution = StandardBuildDistribution.Create(execution).build; - BuildPlatformContribution platform = distribution.platforms.SingleOrDefault(platform => platform.descriptor.id.value == options.target) + BuildPlatformContribution platform = distribution.platforms.SingleOrDefault( + platform => platform.descriptor.id.value == options.target + ) ?? throw new NotSupportedException($"No publication target is registered for '{options.target}'."); if (platform.editorProject is null) - throw new NotSupportedException($"Native verification requires a registered Editor test host; '{options.target}' contributes no such runner."); + { + throw new NotSupportedException( + $"Native verification requires a registered Editor test host; '{options.target}' contributes no such runner." + ); + } NativeProductContribution contribution = distribution.ResolveNativeProduct(options.target, "editor"); var nativeContext = new NativeBuildContext(repositoryRoot, options.configuration.ToLowerInvariant()) .WithBindingGenerator(distribution.ResolveBindingGenerator(options.target)); NativeToolchainSelection sdk = await distribution.ResolveNativeToolchain(options.target) - .ResolveAsync(nativeContext, execution.host, options.target, cancellationToken).ConfigureAwait(false); + .ResolveAsync(nativeContext, execution.host, options.target, cancellationToken) + .ConfigureAwait(false); nativeContext = nativeContext.WithToolchain(sdk); string testHost = ToolchainEnvironment.ResolveExecutable("pwsh"); string testEntry = Path.Combine(repositoryRoot, "tests", "Invoke-IsolatedTests.ps1"); if (!File.Exists(testEntry)) + { throw new FileNotFoundException("The common test execution entry is unavailable.", testEntry); + } IReadOnlyList bindingProjects = DiscoverBindingProjects(repositoryRoot, contribution.plan); ValidateInputs(bindingProjects); string target = options.target; string operationRoot = Path.Combine(repositoryRoot, "artifacts", "build-tools", "verification"); - BuildCacheOwnerCatalog.Register(repositoryRoot, operationRoot, "native-verification", BuildCacheArtifactRole.ProcessWorkingDirectory, cancellationToken); - using ProcessOwnedDirectory operation = await ProcessOwnedDirectory.CreateAsync(operationRoot, cancellationToken).ConfigureAwait(false); + BuildCacheOwnerCatalog.Register( + repositoryRoot, + operationRoot, + "native-verification", + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ); + using ProcessOwnedDirectory operation = await ProcessOwnedDirectory.CreateAsync( + operationRoot, + cancellationToken + ).ConfigureAwait(false); string artifactsPath = Path.Combine(operation.directory, "managed"); Console.WriteLine("[inno-bindings] Verify deterministic generation against the checked-in host sources."); foreach (string project in bindingProjects) { - await ToolchainEnvironment.RunAsync(options.dotnet, - ["build", project, - "--configuration", options.configuration, "-t:CheckBindings", + await ToolchainEnvironment.RunAsync( + options.dotnet, + [ + "build", + project, + "--configuration", + options.configuration, + "-t:CheckBindings", $"-p:InnoBindingDotnetHost={options.dotnet}", - "-p:InnoBindingTargetId=" + target, "-p:InnoBindingOutputMode=HostSource", - $"-p:InnoNativeTarget={target}", $"-p:InnoToolTarget={target}", - "--disable-build-servers", "-m:1", "-nr:false", "-p:UseSharedCompilation=false", "--nologo"], - repositoryRoot, cancellationToken, DotNetSdkEnvironment.Create(options.dotnet)); + "-p:InnoBindingTargetId=" + target, + "-p:InnoBindingOutputMode=HostSource", + $"-p:InnoNativeTarget={target}", + $"-p:InnoToolTarget={target}", + "--disable-build-servers", + "-m:1", + "-nr:false", + "-p:UseSharedCompilation=false", + "--nologo" + ], + repositoryRoot, + cancellationToken, + DotNetSdkEnvironment.Create(options.dotnet) + ); } AuditNativeImports(repositoryRoot); @@ -80,7 +116,8 @@ await ToolchainEnvironment.RunAsync(options.dotnet, await ToolchainEnvironment.RunAsync( options.dotnet, [ - "restore", Path.Combine(repositoryRoot, "InnoEngine.sln"), + "restore", + Path.Combine(repositoryRoot, "InnoEngine.sln"), "-p:Configuration=Source" + options.configuration, $"-p:InnoToolTarget={target}", $"-p:ArtifactsPath={artifactsPath}", @@ -89,7 +126,10 @@ await ToolchainEnvironment.RunAsync( "/nodeReuse:false", "--nologo" ], - repositoryRoot, cancellationToken, DotNetSdkEnvironment.Create(options.dotnet)); + repositoryRoot, + cancellationToken, + DotNetSdkEnvironment.Create(options.dotnet) + ); var native = await BuildNativeDependenciesAsync(nativeContext, contribution, cancellationToken); using ProductNativeBuildResult nativeOwnership = native.products; @@ -98,20 +138,36 @@ await ToolchainEnvironment.RunAsync( await ToolchainEnvironment.RunAsync( options.dotnet, [ - "build", Path.Combine(repositoryRoot, "InnoEngine.sln"), - "--configuration", "Source" + options.configuration, + "build", + Path.Combine(repositoryRoot, "InnoEngine.sln"), + "--configuration", + "Source" + options.configuration, "--no-restore", - "-m:1", "-nodeReuse:false", "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--disable-build-servers", $"-p:InnoToolTarget={target}", $"-p:ArtifactsPath={artifactsPath}", "-p:TreatWarningsAsErrors=true", "--nologo" ], - repositoryRoot, cancellationToken, DotNetSdkEnvironment.Create(options.dotnet)); + repositoryRoot, + cancellationToken, + DotNetSdkEnvironment.Create(options.dotnet) + ); IReadOnlyList testProjects = DiscoverTestProjects(repositoryRoot); - string testResults = await RunTestsAsync(repositoryRoot, options, testProjects, - native.products, native.plan, testHost, testEntry, artifactsPath, cancellationToken); + string testResults = await RunTestsAsync( + repositoryRoot, + options, + testProjects, + native.products, + native.plan, + testHost, + testEntry, + artifactsPath, + cancellationToken + ); string reportPath = await WriteReportAsync( repositoryRoot, target, @@ -119,10 +175,12 @@ await ToolchainEnvironment.RunAsync( testProjects.Count, native.plan, testResults, - cancellationToken); + cancellationToken + ); Console.WriteLine( $"[inno-bindings] Project binding diffs, native builds, solution build, import audit, " - + $"and {testProjects.Count} test projects passed."); + + $"and {testProjects.Count} test projects passed." + ); Console.WriteLine($"[inno-bindings] Acceptance report: {reportPath}"); successfulRoot = repositoryRoot; return 0; @@ -138,8 +196,14 @@ await ToolchainEnvironment.RunAsync( { try { - await BuildMaintenanceApplication.CleanAsync(successfulRoot, new BuildCachePolicy(), - false, false, null, CancellationToken.None).ConfigureAwait(false); + await BuildMaintenanceApplication.CleanAsync( + successfulRoot, + new BuildCachePolicy(), + false, + false, + null, + CancellationToken.None + ).ConfigureAwait(false); } catch (Exception failure) { @@ -155,7 +219,9 @@ private static void ValidateInputs(IReadOnlyList bindingProjects) { string definition = Path.Combine(Path.GetDirectoryName(project)!, "Bindings", "bindings.props"); if (!File.Exists(definition)) + { throw new FileNotFoundException("The sole component binding definition was not found.", definition); + } } } @@ -165,12 +231,17 @@ ProductNativeBuildPlan plan ) { string[] projects = plan.steps .Select(step => Path.GetFullPath(step.component.nativeProject, repositoryRoot)) - .Distinct(StringComparer.Ordinal).Where(File.Exists) - .Where(project => XDocument.Load(project).Descendants("BindGenGeneratedBindings") + .Distinct(StringComparer.Ordinal) + .Where(File.Exists) + .Where(project => XDocument.Load(project) + .Descendants("BindGenGeneratedBindings") .Any(static property => property.Value.Trim() == "true")) - .Order(StringComparer.Ordinal).ToArray(); + .Order(StringComparer.Ordinal) + .ToArray(); if (projects.Length == 0) + { throw new InvalidOperationException("No Native projects declare BindGenGeneratedBindings=true."); + } return projects; } @@ -184,8 +255,8 @@ private static void AuditNativeImports(string repositoryRoot) string relativePath = Path.GetRelativePath(repositoryRoot, path).Replace('\\', '/'); if (relativePath.Contains("/Generated/", StringComparison.OrdinalIgnoreCase) || relativePath.Contains("/bin/", StringComparison.OrdinalIgnoreCase) - || relativePath.Contains("/obj/", StringComparison.OrdinalIgnoreCase)) - { + || relativePath.Contains("/obj/", StringComparison.OrdinalIgnoreCase) + ) { continue; } @@ -194,7 +265,9 @@ private static void AuditNativeImports(string repositoryRoot) { lineNumber++; if (NativeImportPattern().IsMatch(line)) + { violations.Add($"{relativePath}:{lineNumber}:{line.Trim()}"); + } } } @@ -202,13 +275,14 @@ private static void AuditNativeImports(string repositoryRoot) { string[] reported = violations.Take(C_MAX_REPORTED_VIOLATIONS).ToArray(); string remainder = violations.Count > reported.Length - ? $"{Environment.NewLine}... and {violations.Count - reported.Length} more violation(s)." - : string.Empty; + ? $"{Environment.NewLine}... and {violations.Count - reported.Length} more violation(s)." + : string.Empty; throw new InvalidOperationException( "Hand-authored native imports remain outside generated binding roots:" + Environment.NewLine + string.Join(Environment.NewLine, reported) - + remainder); + + remainder + ); } Console.WriteLine("[inno-bindings] No hand-authored native imports exist outside generated binding roots."); @@ -227,19 +301,25 @@ private static IReadOnlyList DiscoverTestProjects(string repositoryRoot) { string nativeTestsRoot = Path.Combine(repositoryRoot, "backends"); var projects = Directory.EnumerateFiles(nativeTestsRoot, "*.csproj", SearchOption.AllDirectories) - .Where(static path => Path.GetFileNameWithoutExtension(path).StartsWith("Inno.Native.", StringComparison.Ordinal) + .Where(static path => ( + Path.GetFileNameWithoutExtension(path).StartsWith("Inno.Native.", StringComparison.Ordinal) && path.Contains(Path.DirectorySeparatorChar + "tests" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - && !path.Split(Path.DirectorySeparatorChar).Any(static part => part is "bin" or "obj")) - .Order(StringComparer.Ordinal).ToList(); + && !path.Split(Path.DirectorySeparatorChar).Any(static part => part is "bin" or "obj") + )) + .Order(StringComparer.Ordinal) + .ToList(); projects.Add(Path.Combine(repositoryRoot, "tests", "text", "Inno.Text.Tests", "Inno.Text.Tests.csproj")); projects.Add(Path.Combine(repositoryRoot, "tests", "ui", "Inno.UI.Tests", "Inno.UI.Tests.csproj")); if (projects.Count == 0) + { throw new InvalidOperationException("No native binding test projects were discovered."); + } if (projects.Any(static project => !File.Exists(project))) { throw new FileNotFoundException( "A required native binding test project is missing.", - projects.First(static project => !File.Exists(project))); + projects.First(static project => !File.Exists(project)) + ); } return projects; } @@ -258,33 +338,71 @@ CancellationToken cancellationToken Console.WriteLine("[inno-bindings] Run every native binding, Text, and UI test project."); foreach (string project in testProjects) { - string output = (await ToolchainEnvironment.CaptureOutputAsync(options.dotnet, - ["msbuild", project, "-getProperty:TargetDir", $"-p:Configuration={options.configuration}", - $"-p:InnoToolTarget={options.target}", $"-p:ArtifactsPath={artifactsPath}"], - repositoryRoot, cancellationToken, DotNetSdkEnvironment.Create(options.dotnet))).Trim(); + string output = (await ToolchainEnvironment.CaptureOutputAsync( + options.dotnet, + [ + "msbuild", + project, + "-getProperty:TargetDir", + $"-p:Configuration={options.configuration}", + $"-p:InnoToolTarget={options.target}", + $"-p:ArtifactsPath={artifactsPath}" + ], + repositoryRoot, + cancellationToken, + DotNetSdkEnvironment.Create(options.dotnet) + )).Trim(); if (!Path.IsPathFullyQualified(output)) + { throw new InvalidDataException("The test project did not declare an absolute target output directory."); - await ProductNativeDeployment.InstallAsync(nativeProducts, nativePlan, - output, cancellationToken) + } + await ProductNativeDeployment.InstallAsync(nativeProducts, nativePlan, output, cancellationToken) .ConfigureAwait(false); } - string results = Path.Combine(repositoryRoot, "artifacts", "acceptance", "native-bindings", - options.target, Guid.NewGuid().ToString("N")); + string results = Path.Combine( + repositoryRoot, + "artifacts", + "acceptance", + "native-bindings", + options.target, + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(results); string selection = Path.Combine(results, "Native.slnf"); - File.WriteAllText(selection, JsonSerializer.Serialize(new - { - solution = new + File.WriteAllText( + selection, + JsonSerializer.Serialize(new { - path = Path.Combine(repositoryRoot, "InnoEngine.sln"), - projects = testProjects.Select(project => Path.GetRelativePath(repositoryRoot, project)).ToArray() - } - })); - await ToolchainEnvironment.RunAsync(testHost, - ["-NoLogo", "-NoProfile", "-NonInteractive", "-File", testEntry, - "-Configuration", "Source" + options.configuration, "-Dotnet", options.dotnet, - "-Solution", selection, "-ResultsDirectory", results, "-ArtifactsPath", artifactsPath], - repositoryRoot, cancellationToken, DotNetSdkEnvironment.Create(options.dotnet)); + solution = new + { + path = Path.Combine(repositoryRoot, "InnoEngine.sln"), + projects = testProjects.Select(project => Path.GetRelativePath(repositoryRoot, project)).ToArray() + } + }) + ); + await ToolchainEnvironment.RunAsync( + testHost, + [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-File", + testEntry, + "-Configuration", + "Source" + options.configuration, + "-Dotnet", + options.dotnet, + "-Solution", + selection, + "-ResultsDirectory", + results, + "-ArtifactsPath", + artifactsPath + ], + repositoryRoot, + cancellationToken, + DotNetSdkEnvironment.Create(options.dotnet) + ); return Path.GetRelativePath(repositoryRoot, results).Replace('\\', '/'); } @@ -298,17 +416,26 @@ private static async Task WriteReportAsync( CancellationToken cancellationToken ) { string innoRevision = (await ToolchainEnvironment.CaptureOutputAsync( - "git", ["-C", repositoryRoot, "rev-parse", "HEAD"], repositoryRoot, cancellationToken)).Trim(); + "git", + ["-C", repositoryRoot, "rev-parse", "HEAD"], + repositoryRoot, + cancellationToken + )).Trim(); Assembly bindingImplementation = typeof(NativeBindingGenerator).Assembly; string packageVersion = bindingImplementation.GetCustomAttributes() .Single(static metadata => metadata.Key == "Inno.BindingPackageVersion").Value - ?? throw new InvalidDataException("The binding implementation has no frozen package version."); + ?? throw new InvalidDataException("The binding implementation has no frozen package version."); string implementationHash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(bindingImplementation.Location))); - bool innoDirty = !string.IsNullOrWhiteSpace(await ToolchainEnvironment.CaptureOutputAsync( - "git", ["-C", repositoryRoot, "status", "--porcelain", "--untracked-files=all"], repositoryRoot, cancellationToken)); + bool innoDirty = !string.IsNullOrWhiteSpace( + await ToolchainEnvironment.CaptureOutputAsync( + "git", + ["-C", repositoryRoot, "status", "--porcelain", "--untracked-files=all"], + repositoryRoot, + cancellationToken + ) + ); DateTimeOffset generatedAt = DateTimeOffset.UtcNow; - string reportDirectory = Path.Combine( - repositoryRoot, "artifacts", "bindings", "acceptance", target); + string reportDirectory = Path.Combine(repositoryRoot, "artifacts", "bindings", "acceptance", target); Directory.CreateDirectory(reportDirectory); var report = new @@ -339,7 +466,8 @@ CancellationToken cancellationToken File.WriteAllText( jsonPath, JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }) + Environment.NewLine, - new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + new UTF8Encoding(encoderShouldEmitUTF8Identifier: false) + ); string markdown = $""" # InnoEngine generated-native-binding acceptance @@ -360,11 +488,11 @@ CancellationToken cancellationToken File.WriteAllText( Path.Combine(reportDirectory, "report.md"), markdown + Environment.NewLine, - new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + new UTF8Encoding(encoderShouldEmitUTF8Identifier: false) + ); return jsonPath; } [GeneratedRegex(@"\[(DllImport|LibraryImport)\b|partial\s+.*\bextern\b|static\s+extern\b")] private static partial Regex NativeImportPattern(); - } diff --git a/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs b/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs index a9f21437e..60305fdf7 100644 --- a/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs +++ b/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs @@ -41,29 +41,42 @@ internal static NativeVerificationOptions Parse(IReadOnlyList args) { string argument = args[index]; if (!argument.StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Unexpected argument '{argument}'.{Environment.NewLine}{usage}"); + } string key = argument[2..]; if (++index >= args.Count) + { throw new ArgumentException($"Argument '{argument}' requires a value."); + } if (!values.TryAdd(key, args[index])) + { throw new ArgumentException($"Argument '{argument}' was specified more than once."); + } } string selectedRoot = values.GetValueOrDefault("engine-root", string.Empty); string engineRoot = Path.GetFullPath(string.IsNullOrWhiteSpace(selectedRoot) ? ToolchainEnvironment.FindRepoRoot() : selectedRoot); string configuration = values.GetValueOrDefault("configuration", C_DEFAULT_CONFIGURATION); if (configuration is not ("Debug" or "Release")) + { throw new ArgumentException("--configuration must be either Debug or Release."); - string dotnet = ToolchainEnvironment.ResolveExecutable(values.GetValueOrDefault("dotnet") - ?? Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet"); + } + string dotnet = ToolchainEnvironment.ResolveExecutable( + values.GetValueOrDefault("dotnet") + ?? Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet" + ); if (!values.TryGetValue("target", out string? target) || string.IsNullOrWhiteSpace(target)) + { throw new ArgumentException("--target requires an explicit implemented native target."); + } string[] knownKeys = ["engine-root", "configuration", "dotnet", "target"]; string? unknownKey = values.Keys.FirstOrDefault(key => !knownKeys.Contains(key, StringComparer.Ordinal)); if (unknownKey != null) + { throw new ArgumentException($"Unknown argument '--{unknownKey}'.{Environment.NewLine}{usage}"); + } return new NativeVerificationOptions(engineRoot, configuration, dotnet, target); } - } diff --git a/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs b/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs index 2272c648c..f1907369e 100644 --- a/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs +++ b/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs @@ -24,8 +24,14 @@ CancellationToken cancellationToken { try { - await BuildMaintenanceApplication.CleanAsync(engineRoot, new BuildCachePolicy(), - false, false, null, cancellationToken).ConfigureAwait(false); + await BuildMaintenanceApplication.CleanAsync( + engineRoot, + new BuildCachePolicy(), + false, + false, + null, + cancellationToken + ).ConfigureAwait(false); } catch (Exception failure) { @@ -44,19 +50,32 @@ CancellationToken cancellationToken { string dotnet = StandardBuildEnvironment.ResolveManagedHost(command.dotnetHost); using BuildWorkspace authoring = BuildWorkspace.Open(command.projectDirectory, dotnet, cancellationToken); - Console.WriteLine(command.kind == BuildCommandKind.Scripts + Console.WriteLine( + command.kind == BuildCommandKind.Scripts ? authoring.ExportProjectScripts(command.outputDirectory, command.generateIdeProjects, cancellationToken) - : authoring.ImportSample(command.sampleSource, cancellationToken).ToString()); + : authoring.ImportSample(command.sampleSource, cancellationToken).ToString() + ); return 0; } string application = Path.GetDirectoryName(typeof(BuildApplication).Assembly.Location)!; - BuildCompositionContext context = StandardBuildEnvironment.Capture(application, command.toolsTarget, command.dotnetHost, - string.IsNullOrWhiteSpace(command.nativeDependencies) ? null : Path.GetFullPath(command.nativeDependencies, engineRoot)); - using ProductNativeBuildResult products = await BuildComposition.PrepareNativeAsync(context, engineRoot, cancellationToken, command.nativeDependencies).ConfigureAwait(false); + BuildCompositionContext context = StandardBuildEnvironment.Capture( + application, + command.toolsTarget, + command.dotnetHost, + string.IsNullOrWhiteSpace(command.nativeDependencies) ? null : Path.GetFullPath(command.nativeDependencies, engineRoot) + ); + using ProductNativeBuildResult products = await BuildComposition.PrepareNativeAsync( + context, + engineRoot, + cancellationToken, + command.nativeDependencies + ).ConfigureAwait(false); NativeBuildProduct product = products.Single(); string extension = context.host.services.executableExtension; - var executables = Enum.GetValues().ToDictionary(static tool => tool, - tool => product.files.Single(file => Path.GetFileName(file) == tool.ToString().ToLowerInvariant() + extension)); + var executables = Enum.GetValues().ToDictionary( + static tool => tool, + tool => product.files.Single(file => Path.GetFileName(file) == tool.ToString().ToLowerInvariant() + extension) + ); string includes = Path.GetDirectoryName(product.files.Single(file => Path.GetFileName(file) == "bgfx_shader.sh"))!; var tools = new ToolRunner(executables, includes, context.host.services.workspaces); using BuildWorkspace workspace = BuildWorkspace.Open(command.projectDirectory, context.dotnetHost, cancellationToken); @@ -68,24 +87,36 @@ CancellationToken cancellationToken GameBuildRequest request = command.CreateGameRequest(workspace.LoadGameProfile(command.profilePath, command.gameTarget)); // The command-line host has no UI scheduler. Keep the authoring owner on this thread // while preparing external tools, then capture its build snapshot before the first await. - using PlayerSupportPackLease prepared = pipeline.EnsurePlayerSupportPackAsync( - request.profile.target, request.profile.managedDeployment, cancellationToken) - .GetAwaiter().GetResult(); + using PlayerSupportPackLease prepared = pipeline + .EnsurePlayerSupportPackAsync( + request.profile.target, + request.profile.managedDeployment, + cancellationToken + ) + .GetAwaiter() + .GetResult(); result = await pipeline.BuildGameAsync(request, progress, cancellationToken); } else if (command.kind == BuildCommandKind.Plugin) { result = await pipeline.BuildPluginAsync( - command.CreatePluginRequest(workspace.projectId), progress, cancellationToken); + command.CreatePluginRequest(workspace.projectId), + progress, + cancellationToken + ); } else { throw new InvalidOperationException("Unknown project build kind."); } foreach (BuildDiagnostic diagnostic in result.diagnostics) + { Console.Error.WriteLine($"{diagnostic.severity} {diagnostic.code}: {diagnostic.message}"); + } if (!result.succeeded) + { return 1; + } Console.WriteLine(result.outputPath); return 0; } diff --git a/build/composition/Inno.Build.Composition/BuildCompositionContext.cs b/build/composition/Inno.Build.Composition/BuildCompositionContext.cs index 55d2b20c1..5936f6d78 100644 --- a/build/composition/Inno.Build.Composition/BuildCompositionContext.cs +++ b/build/composition/Inno.Build.Composition/BuildCompositionContext.cs @@ -41,11 +41,17 @@ public BuildCompositionContext( ArgumentException.ThrowIfNullOrWhiteSpace(applicationDirectory); ArgumentNullException.ThrowIfNull(host); if (string.IsNullOrWhiteSpace(toolsTarget.value)) + { throw new ArgumentException("A build composition must declare its executable native tools target.", nameof(toolsTarget)); + } if (!Path.IsPathFullyQualified(applicationDirectory)) + { throw new ArgumentException("The build host requires an absolute application directory.", nameof(applicationDirectory)); + } if (nativeDependencies is not null && !Path.IsPathFullyQualified(nativeDependencies)) + { throw new ArgumentException("A native dependency selection must be absolute.", nameof(nativeDependencies)); + } this.dotnetHost = dotnetHost; this.applicationDirectory = Path.GetFullPath(applicationDirectory); this.host = host; @@ -77,5 +83,4 @@ public BuildCompositionContext( /// Gets the explicit consume-only selection propagated to product and Support Pack preparation. /// public string? nativeDependencies { get; } - } diff --git a/build/composition/Inno.Build.Composition/BuildDistribution.cs b/build/composition/Inno.Build.Composition/BuildDistribution.cs index 21db89648..f3a7e956e 100644 --- a/build/composition/Inno.Build.Composition/BuildDistribution.cs +++ b/build/composition/Inno.Build.Composition/BuildDistribution.cs @@ -50,27 +50,48 @@ public BuildDistribution( ArgumentNullException.ThrowIfNull(games); ArgumentNullException.ThrowIfNull(managedCompilers); if (games.Count == 0 || games.Any(static contribution => contribution is null)) + { throw new ArgumentException("A distribution requires complete platform contributions.", nameof(games)); + } m_games = games.ToArray(); m_platforms = m_games.Select(static game => game.platform).ToArray(); m_platformSnapshot = Array.AsReadOnly(m_platforms); foreach (BuildPlatformContribution platform in m_platforms) + { if (platform.bindingGenerator is not null) + { m_bindingGenerators.Add(platform.descriptor.id.value, platform.bindingGenerator); + } + } m_targetIds = m_platforms.Select(static contribution => contribution.descriptor.id).ToHashSet(); if (m_targetIds.Count != m_platforms.Length) + { throw new ArgumentException("Platform target identities must be unique.", nameof(games)); - var native = m_platforms.ToDictionary(static platform => platform.descriptor.id.value, - static platform => platform.toolchainProvider, StringComparer.Ordinal); - var products = m_platforms.ToDictionary(static platform => platform.descriptor.id.value, - static platform => platform.nativeProducts, StringComparer.Ordinal); + } + var native = m_platforms.ToDictionary( + static platform => platform.descriptor.id.value, + static platform => platform.toolchainProvider, + StringComparer.Ordinal + ); + var products = m_platforms.ToDictionary( + static platform => platform.descriptor.id.value, + static platform => platform.nativeProducts, + StringComparer.Ordinal + ); foreach (NativeToolchainContribution contribution in nativeOnlyContributions ?? []) { if (contribution is null || !native.TryAdd(contribution.descriptor.id.value, contribution.provider)) - throw new ArgumentException("Native SDK contributions must be complete and have unique target identities.", nameof(nativeOnlyContributions)); + { + throw new ArgumentException( + "Native SDK contributions must be complete and have unique target identities.", + nameof(nativeOnlyContributions) + ); + } products.Add(contribution.descriptor.id.value, contribution.nativeProducts); if (contribution.bindingGenerator is not null) + { m_bindingGenerators.Add(contribution.descriptor.id.value, contribution.bindingGenerator); + } } m_nativeProducts = new System.Collections.ObjectModel.ReadOnlyDictionary>(products); @@ -113,8 +134,9 @@ public BuildDistribution( /// The target contributes no binding generator. /// public INativeBindingGenerator ResolveBindingGenerator(string targetId) - => m_bindingGenerators.TryGetValue(targetId, out INativeBindingGenerator? generator) ? generator - : throw new NotSupportedException($"No binding generator is registered for '{targetId}'."); + => m_bindingGenerators.TryGetValue(targetId, out INativeBindingGenerator? generator) + ? generator + : throw new NotSupportedException($"No binding generator is registered for '{targetId}'."); /// /// Resolves the SDK integration bound to an explicitly registered publication target. @@ -132,7 +154,9 @@ public INativeToolchainProvider ResolveNativeToolchain(string targetId) { ArgumentException.ThrowIfNullOrWhiteSpace(targetId); if (m_nativeToolchains.TryGetValue(targetId, out INativeToolchainProvider? provider)) + { return provider; + } throw new NotSupportedException($"No native toolchain is registered for target '{targetId}'."); } @@ -185,8 +209,10 @@ string productId ArgumentException.ThrowIfNullOrWhiteSpace(targetId); ArgumentException.ThrowIfNullOrWhiteSpace(productId); if (m_nativeProducts.TryGetValue(targetId, out IReadOnlyDictionary? products) - && products.TryGetValue(productId, out NativeProductContribution? plan)) + && products.TryGetValue(productId, out NativeProductContribution? plan) + ) { return plan; + } throw new NotSupportedException($"No ordinary native build is registered for product '{productId}' on target '{targetId}'."); } @@ -223,13 +249,15 @@ TypeCatalog types { BuildPlatformContribution platform = m_platforms[index]; IGameBuildTarget target = platform.factory() - ?? throw new InvalidOperationException("A build target factory returned no target."); + ?? throw new InvalidOperationException("A build target factory returned no target."); if (target.id != platform.descriptor.id || target.runtimeIdentifier != platform.descriptor.runtimeIdentifier - || !identities.Add(target.id)) + || !identities.Add(target.id) + ) { throw new InvalidOperationException($"Build target '{target.id}' does not match its bound platform description."); + } managedDeployments.Resolve(target.defaultManagedDeployment, target.runtimeIdentifier); IGameContentCompiler compiler = m_games[index].compilerFactory(assets, serialization, types) - ?? throw new InvalidOperationException("A content compiler factory returned no compiler."); + ?? throw new InvalidOperationException("A content compiler factory returned no compiler."); targets[index] = new GameBuildTargetBinding(target, compiler); } return Array.AsReadOnly(targets); @@ -253,7 +281,9 @@ ManagedDeploymentId deployment ) { ArgumentNullException.ThrowIfNull(target); if (!m_targetIds.Contains(target.id)) + { throw new InvalidOperationException($"Build target '{target.id}' is not registered in this distribution."); + } managedDeployments.Resolve(deployment, target.runtimeIdentifier); } } diff --git a/build/composition/Inno.Build.Composition/BuildPipelineFactory.cs b/build/composition/Inno.Build.Composition/BuildPipelineFactory.cs index e67cdf25e..603bbf4e4 100644 --- a/build/composition/Inno.Build.Composition/BuildPipelineFactory.cs +++ b/build/composition/Inno.Build.Composition/BuildPipelineFactory.cs @@ -1,8 +1,8 @@ using System; using Inno.Assets.Pipeline; using Inno.Build.SupportPacks; -using Inno.Core.Settings; using Inno.Core.Logging; +using Inno.Core.Settings; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scripting.Compiler; @@ -59,11 +59,22 @@ string supportPackRoot ArgumentNullException.ThrowIfNull(engine); Logger logger = engine.logs.CreateLogger(); return new BuildPipeline( - assets, plugins, settings, engine.serialization, engine.generations, compiler, supportPackRoot, + assets, + plugins, + settings, + engine.serialization, + engine.generations, + compiler, + supportPackRoot, distribution.CreateBindings(assets, engine.serialization, engine.types), distribution.managedDeployments, SourcePlayerSupportPackProvisioner.TryCreateForHost( - context.applicationDirectory, distribution.supportPacks, context.dotnetHost, - diagnostic => logger.Write(LogLevel.Warn, diagnostic), context.nativeDependencies)); + context.applicationDirectory, + distribution.supportPacks, + context.dotnetHost, + diagnostic => logger.Write(LogLevel.Warn, diagnostic), + context.nativeDependencies + ) + ); } } diff --git a/build/composition/Inno.Build.Composition/BuildPlatformContribution.cs b/build/composition/Inno.Build.Composition/BuildPlatformContribution.cs index 1e2816912..6663ba3e1 100644 --- a/build/composition/Inno.Build.Composition/BuildPlatformContribution.cs +++ b/build/composition/Inno.Build.Composition/BuildPlatformContribution.cs @@ -62,13 +62,17 @@ public BuildPlatformContribution( ArgumentNullException.ThrowIfNull(supportPackSource); ArgumentNullException.ThrowIfNull(toolchainProvider); if (descriptor.id != supportPackSource.target) + { throw new ArgumentException("A platform source must match its declared target.", nameof(supportPackSource)); + } string? editor = editorProject?.Replace('\\', '/'); if (descriptor.supportsEditor != (editor is not null) || editor is not null && (editor.StartsWith('/') || editor.Contains(':') - || !editor.EndsWith(".csproj", StringComparison.Ordinal) - || editor.Split('/').Any(static segment => segment is "" or "." or ".."))) + || !editor.EndsWith(".csproj", StringComparison.Ordinal) + || editor.Split('/').Any(static segment => segment is "" or "." or "..")) + ) { throw new ArgumentException("Editor capability requires one explicit contained product project.", nameof(editorProject)); + } this.descriptor = descriptor; this.bindingGenerator = bindingGenerator; this.factory = factory; @@ -77,13 +81,22 @@ public BuildPlatformContribution( this.editorProject = editor; var products = new Dictionary(StringComparer.Ordinal); foreach (NativeProductContribution product in nativeProducts ?? []) + { if (product is null || !products.TryAdd(product.plan.productId, product)) - throw new ArgumentException("Native product plans must be complete and have unique product identities.", nameof(nativeProducts)); + { + throw new ArgumentException( + "Native product plans must be complete and have unique product identities.", + nameof(nativeProducts) + ); + } + } this.nativeProducts = new ReadOnlyDictionary(products); ManagedDeploymentId[] deployments = (managedDeployments ?? []).ToArray(); if (deployments.Any(static id => string.IsNullOrWhiteSpace(id.value)) - || deployments.Distinct().Count() != deployments.Length) + || deployments.Distinct().Count() != deployments.Length + ) { throw new ArgumentException("Platform deployment identities must be assigned and unique.", nameof(managedDeployments)); + } this.managedDeployments = Array.AsReadOnly(deployments); } @@ -116,6 +129,7 @@ public BuildPlatformContribution( /// Gets the frozen ordinary product-build closures explicitly contributed by this target. /// public IReadOnlyDictionary nativeProducts { get; } + /// /// Gets the target-owned generator, or null when no binding capability is registered. /// @@ -125,5 +139,4 @@ public BuildPlatformContribution( /// Gets the deployment identities this platform authorizes for its declared managed runtime target. /// public IReadOnlyList managedDeployments { get; } - } diff --git a/build/composition/Inno.Build.Composition/NativeProductContribution.cs b/build/composition/Inno.Build.Composition/NativeProductContribution.cs index b6368b358..74b5e107d 100644 --- a/build/composition/Inno.Build.Composition/NativeProductContribution.cs +++ b/build/composition/Inno.Build.Composition/NativeProductContribution.cs @@ -31,6 +31,7 @@ INativeProductExecutor executor /// Gets the immutable product graph. /// public ProductNativeBuildPlan plan { get; } + /// /// Gets the platform-selected executor. /// diff --git a/build/composition/Inno.Build.Composition/NativeToolchainContribution.cs b/build/composition/Inno.Build.Composition/NativeToolchainContribution.cs index 0dd609006..d97dcdae8 100644 --- a/build/composition/Inno.Build.Composition/NativeToolchainContribution.cs +++ b/build/composition/Inno.Build.Composition/NativeToolchainContribution.cs @@ -42,9 +42,12 @@ public NativeToolchainContribution( this.provider = provider; nativeProducts ??= []; if (nativeProducts.Any(static plan => plan is null)) + { throw new ArgumentException("Native product contributions cannot be null.", nameof(nativeProducts)); + } this.nativeProducts = new ReadOnlyDictionary( - nativeProducts.ToDictionary(static product => product.plan.productId, StringComparer.Ordinal)); + nativeProducts.ToDictionary(static product => product.plan.productId, StringComparer.Ordinal) + ); } /// @@ -56,6 +59,7 @@ public NativeToolchainContribution( /// Gets the registered SDK boundary; registration does not start tools or inspect the environment. /// public INativeToolchainProvider provider { get; } + /// /// Gets explicitly implemented native-only product closures keyed by stable product identity. /// @@ -65,5 +69,4 @@ public NativeToolchainContribution( /// Gets the target-owned generator, or null when no binding capability is registered. /// public INativeBindingGenerator? bindingGenerator { get; } - } diff --git a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildCaches.cs b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildCaches.cs index 4072dc246..1d30931bf 100644 --- a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildCaches.cs +++ b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildCaches.cs @@ -4,8 +4,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Distribution.Standard; @@ -42,9 +42,17 @@ public static ValueTask CreateShaderWorkspaceAsync( ) { ArgumentException.ThrowIfNullOrWhiteSpace(engineRoot); if (!Path.IsPathFullyQualified(engineRoot)) + { throw new ArgumentException("Shader workspaces require an absolute checkout root.", nameof(engineRoot)); + } string root = Path.Combine(engineRoot, "artifacts", "build-tools", "shaders", "requests"); - BuildCacheOwnerCatalog.Register(engineRoot, root, "shader-requests", BuildCacheArtifactRole.ProcessWorkingDirectory, cancellationToken); + BuildCacheOwnerCatalog.Register( + engineRoot, + root, + "shader-requests", + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ); return ProcessOwnedDirectory.CreateAsync(root, cancellationToken); } @@ -71,30 +79,116 @@ IReadOnlyList components ArgumentException.ThrowIfNullOrWhiteSpace(engineRoot); ArgumentNullException.ThrowIfNull(components); if (!Path.IsPathFullyQualified(engineRoot)) + { throw new ArgumentException("Cache registration requires an absolute checkout.", nameof(engineRoot)); + } var owners = new List { - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact), "native"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "bindings"), BuildCacheArtifactRole.ImmutableArtifact), "bindings"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "support-packs"), BuildCacheArtifactRole.ImmutableArtifact), "support-packs"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "shaders", "requests"), BuildCacheArtifactRole.ProcessWorkingDirectory), "shader-requests"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "managed", "workspaces"), BuildCacheArtifactRole.ReusableWorkspace), "managed-workspaces"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "managed-inputs", "evaluators"), BuildCacheArtifactRole.ImmutableArtifact), "managed-evaluators"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "managed-inputs", "requests"), BuildCacheArtifactRole.ProcessWorkingDirectory), "managed-input-requests"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "extensions"), BuildCacheArtifactRole.ImmutableArtifact), "binding-extensions"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "intermediate"), BuildCacheArtifactRole.ReusableWorkspace), "binding-workspaces"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "sdk-workspaces"), BuildCacheArtifactRole.ReusableWorkspace), "bgcs-workspaces"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "hosts"), BuildCacheArtifactRole.ImmutableArtifact), "task-hosts"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "loads"), BuildCacheArtifactRole.ProcessWorkingDirectory), "task-loads"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "publishers"), BuildCacheArtifactRole.ProcessWorkingDirectory), "task-publishers"), - Describe(new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "workspaces"), BuildCacheArtifactRole.ReusableWorkspace), "task-workspaces") + Describe( + new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact), + "native" + ), + Describe( + new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "bindings"), BuildCacheArtifactRole.ImmutableArtifact), + "bindings" + ), + Describe( + new BuildCachePublisher(Path.Combine(engineRoot, "artifacts", "support-packs"), BuildCacheArtifactRole.ImmutableArtifact), + "support-packs" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "shaders", "requests"), + BuildCacheArtifactRole.ProcessWorkingDirectory + ), + "shader-requests" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "managed", "workspaces"), + BuildCacheArtifactRole.ReusableWorkspace + ), + "managed-workspaces" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "managed-inputs", "evaluators"), + BuildCacheArtifactRole.ImmutableArtifact + ), + "managed-evaluators" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "managed-inputs", "requests"), + BuildCacheArtifactRole.ProcessWorkingDirectory + ), + "managed-input-requests" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "extensions"), + BuildCacheArtifactRole.ImmutableArtifact + ), + "binding-extensions" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "intermediate"), + BuildCacheArtifactRole.ReusableWorkspace + ), + "binding-workspaces" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "bindings", "sdk-workspaces"), + BuildCacheArtifactRole.ReusableWorkspace + ), + "bgcs-workspaces" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "hosts"), + BuildCacheArtifactRole.ImmutableArtifact + ), + "task-hosts" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "loads"), + BuildCacheArtifactRole.ProcessWorkingDirectory + ), + "task-loads" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "publishers"), + BuildCacheArtifactRole.ProcessWorkingDirectory + ), + "task-publishers" + ), + Describe( + new BuildCachePublisher( + Path.Combine(engineRoot, "artifacts", "build-tools", "tasks", "workspaces"), + BuildCacheArtifactRole.ReusableWorkspace + ), + "task-workspaces" + ) }; NativeComponentDescriptor[] workspaceComponents = components.ToArray(); - foreach (string project in workspaceComponents.Select(static component => component.toolchainProject).Distinct(StringComparer.Ordinal)) - { + foreach (string project in workspaceComponents + .Select(static component => component.toolchainProject) + .Distinct(StringComparer.Ordinal) + ) { NativeComponentDescriptor component = workspaceComponents.First(value => value.toolchainProject == project); - owners.Add(Describe(new BuildCachePublisher(Path.Combine(component.GetToolchainRoot(engineRoot), "obj", "native"), BuildCacheArtifactRole.ReusableWorkspace), - "workspace:" + project)); + owners.Add( + Describe( + new BuildCachePublisher( + Path.Combine(component.GetToolchainRoot(engineRoot), "obj", "native"), + BuildCacheArtifactRole.ReusableWorkspace + ), + "workspace:" + project + ) + ); } return owners.AsReadOnly(); diff --git a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildDistribution.cs b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildDistribution.cs index 53edd6fda..13cd13a18 100644 --- a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildDistribution.cs +++ b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildDistribution.cs @@ -57,23 +57,58 @@ public static StandardBuildDistribution Create( tools ??= new ToolRunner(context.host.services.workspaces); (BuildPlatformContribution platform, BgfxShaderTargetProfile shaders, GameContentCompilerFactory compiler)[] bindings = [ - (WindowsX64BuildIntegration.Create(context), WindowsX64BgfxIntegration.shaderProfile, WindowsX64BgfxIntegration.CreateContentCompilerFactory(tools)), - (MacOSArm64BuildIntegration.Create(context), MacOSArm64BgfxIntegration.shaderProfile, MacOSArm64BgfxIntegration.CreateContentCompilerFactory(tools)), - (BrowserWasm32BuildIntegration.Create(context), BrowserWasm32BgfxIntegration.shaderProfile, BrowserWasm32BgfxIntegration.CreateContentCompilerFactory(tools)) + (WindowsX64BuildIntegration.Create( + context + ), WindowsX64BgfxIntegration.shaderProfile, WindowsX64BgfxIntegration.CreateContentCompilerFactory(tools)), + (MacOSArm64BuildIntegration.Create( + context + ), MacOSArm64BgfxIntegration.shaderProfile, MacOSArm64BgfxIntegration.CreateContentCompilerFactory(tools)), + (BrowserWasm32BuildIntegration.Create( + context + ), BrowserWasm32BgfxIntegration.shaderProfile, BrowserWasm32BgfxIntegration.CreateContentCompilerFactory(tools)) ]; foreach ((BuildPlatformContribution platform, BgfxShaderTargetProfile shaders, GameContentCompilerFactory _) in bindings) + { if (platform.descriptor.id.value != shaders.id) + { throw new InvalidOperationException("Platform publication and shader target identities disagree."); - string[] Runtimes(ManagedDeploymentId deployment) => bindings - .Where(binding => binding.platform.managedDeployments.Contains(deployment)) - .Select(static binding => binding.platform.descriptor.runtimeIdentifier).Distinct(StringComparer.Ordinal).ToArray(); - var build = new BuildDistribution(bindings.Select(static binding => new GameBuildContribution(binding.platform, binding.compiler)).ToArray(), - [new CoreClrDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentId.coreClr), context.host.services.workspaces), - new MonoWasmDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentId.monoWasm), context.host.services.workspaces, aheadOfTime: false), - new MonoWasmDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentId.monoWasmAot), context.host.services.workspaces, aheadOfTime: true), - new NativeAotDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentId.nativeAot), context.host.services.workspaces)]); - return new(build, new ReadOnlyDictionary( - bindings.ToDictionary(static binding => binding.platform.descriptor.id, static binding => binding.shaders))); + } + } + string[] Runtimes(ManagedDeploymentId deployment) + => bindings + .Where(binding => binding.platform.managedDeployments.Contains(deployment)) + .Select(static binding => binding.platform.descriptor.runtimeIdentifier) + .Distinct(StringComparer.Ordinal) + .ToArray(); + var build = new BuildDistribution( + bindings.Select(static binding => new GameBuildContribution(binding.platform, binding.compiler)).ToArray(), + [ + new CoreClrDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentId.coreClr), context.host.services.workspaces), + new MonoWasmDeploymentCompiler( + context.dotnetHost, + Runtimes(ManagedDeploymentId.monoWasm), + context.host.services.workspaces, + aheadOfTime: false + ), + new MonoWasmDeploymentCompiler( + context.dotnetHost, + Runtimes(ManagedDeploymentId.monoWasmAot), + context.host.services.workspaces, + aheadOfTime: true + ), + new NativeAotDeploymentCompiler( + context.dotnetHost, + Runtimes(ManagedDeploymentId.nativeAot), + context.host.services.workspaces + ) + ] + ); + return new( + build, + new ReadOnlyDictionary( + bindings.ToDictionary(static binding => binding.platform.descriptor.id, static binding => binding.shaders) + ) + ); } /// @@ -89,6 +124,7 @@ [new CoreClrDeploymentCompiler(context.dotnetHost, Runtimes(ManagedDeploymentId. /// The distribution has no shader configuration for this target. /// public BgfxShaderTargetProfile ResolveShaderTarget(BuildTargetId target) - => m_shaders.TryGetValue(target, out BgfxShaderTargetProfile? profile) ? profile - : throw new NotSupportedException($"No shader configuration is registered for '{target}'."); + => m_shaders.TryGetValue(target, out BgfxShaderTargetProfile? profile) + ? profile + : throw new NotSupportedException($"No shader configuration is registered for '{target}'."); } diff --git a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildEnvironment.cs b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildEnvironment.cs index 67626a513..b9925dc02 100644 --- a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildEnvironment.cs +++ b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildEnvironment.cs @@ -66,7 +66,7 @@ public static BuildCompositionContext Capture( public static string ResolveManagedHost(string? dotnetHost = null) { string host = dotnetHost ?? Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? CurrentRuntimeHost("dotnet" + StandardBuildHosts.Capture().services.executableExtension); + ?? CurrentRuntimeHost("dotnet" + StandardBuildHosts.Capture().services.executableExtension); return ToolchainEnvironment.ResolveExecutable(host); } @@ -79,7 +79,9 @@ private static string CurrentRuntimeHost(string executable) { string runtimeHost = Path.Combine(installation.FullName, executable); if (File.Exists(runtimeHost)) + { return runtimeHost; + } } return executable; } diff --git a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildHosts.cs b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildHosts.cs index 547a0706b..fc570d7cb 100644 --- a/build/distributions/Inno.Build.Distribution.Standard/StandardBuildHosts.cs +++ b/build/distributions/Inno.Build.Distribution.Standard/StandardBuildHosts.cs @@ -23,8 +23,12 @@ public static BuildHostDescriptor Capture() { IBuildHostProvider[] providers = [new WindowsBuildHostProvider(), new MacOSArm64BuildHostProvider()]; foreach (IBuildHostProvider provider in providers) + { if (provider.TryCapture() is BuildHostDescriptor host) + { return host; + } + } throw new PlatformNotSupportedException("No registered build host supports this machine."); } } diff --git a/build/managed/Inno.Build.Managed/ManagedDeploymentCapabilities.cs b/build/managed/Inno.Build.Managed/ManagedDeploymentCapabilities.cs index a6be9c514..f21021c82 100644 --- a/build/managed/Inno.Build.Managed/ManagedDeploymentCapabilities.cs +++ b/build/managed/Inno.Build.Managed/ManagedDeploymentCapabilities.cs @@ -32,8 +32,10 @@ bool nativeStaticLinking ) { ArgumentNullException.ThrowIfNull(runtimeIdentifiers); if (runtimeIdentifiers.Count == 0 || runtimeIdentifiers.Any(string.IsNullOrWhiteSpace) - || runtimeIdentifiers.Distinct(StringComparer.Ordinal).Count() != runtimeIdentifiers.Count) + || runtimeIdentifiers.Distinct(StringComparer.Ordinal).Count() != runtimeIdentifiers.Count + ) { throw new ArgumentException("A managed provider requires unique runtime targets.", nameof(runtimeIdentifiers)); + } this.runtimeIdentifiers = Array.AsReadOnly(runtimeIdentifiers.ToArray()); this.dynamicCode = dynamicCode; this.aheadOfTime = aheadOfTime; diff --git a/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs b/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs index 7cccc8e93..c07c7871b 100644 --- a/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs +++ b/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs @@ -23,13 +23,20 @@ public sealed class ManagedDeploymentCatalog public ManagedDeploymentCatalog(IReadOnlyList compilers) { ArgumentNullException.ThrowIfNull(compilers); - if (compilers.Count == 0 || compilers.Any(static compiler => compiler is null - || string.IsNullOrWhiteSpace(compiler.id.value)) - || compilers.Select(static compiler => compiler.id).Distinct().Count() != compilers.Count) + if (compilers.Count == 0 || compilers.Any(static compiler => ( + compiler is null + || string.IsNullOrWhiteSpace(compiler.id.value) + )) + || compilers.Select(static compiler => compiler.id).Distinct().Count() != compilers.Count + ) { throw new ArgumentException("Managed providers require unique valid identities.", nameof(compilers)); + } m_compilers = compilers.ToDictionary(static compiler => compiler.id); - availableDeployments = Array.AsReadOnly(compilers.Select(static compiler => compiler.id) - .OrderBy(static id => id.value, StringComparer.Ordinal).ToArray()); + availableDeployments = Array.AsReadOnly( + compilers.Select(static compiler => compiler.id) + .OrderBy(static id => id.value, StringComparer.Ordinal) + .ToArray() + ); } /// @@ -47,8 +54,10 @@ public ManagedDeploymentCatalog(IReadOnlyList compil /// A new immutable list in stable identity order; unsupported targets produce an empty list. /// public IReadOnlyList GetSupportedDeployments(string runtimeIdentifier) - => Array.AsReadOnly(availableDeployments.Where(id => - m_compilers[id].capabilities.runtimeIdentifiers.Contains(runtimeIdentifier, StringComparer.Ordinal)).ToArray()); + => Array.AsReadOnly( + availableDeployments.Where(id => + m_compilers[id].capabilities.runtimeIdentifiers.Contains(runtimeIdentifier, StringComparer.Ordinal)).ToArray() + ); /// /// Resolves a provider and verifies target support before staging begins. @@ -70,9 +79,13 @@ public IManagedDeploymentCompiler Resolve( string runtimeIdentifier ) { if (!m_compilers.TryGetValue(deployment, out IManagedDeploymentCompiler? compiler)) + { throw new InvalidOperationException($"Managed deployment '{deployment}' is not registered."); + } if (!compiler.capabilities.runtimeIdentifiers.Contains(runtimeIdentifier, StringComparer.Ordinal)) + { throw new InvalidOperationException($"Managed deployment '{deployment}' does not support '{runtimeIdentifier}'."); + } return compiler; } } diff --git a/build/managed/Inno.Build.Managed/ManagedDeploymentId.cs b/build/managed/Inno.Build.Managed/ManagedDeploymentId.cs index c37350b42..a971b6221 100644 --- a/build/managed/Inno.Build.Managed/ManagedDeploymentId.cs +++ b/build/managed/Inno.Build.Managed/ManagedDeploymentId.cs @@ -40,8 +40,12 @@ public ManagedDeploymentId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (!(character is >= 'a' and <= 'z' or >= '0' and <= '9' or '-')) + { throw new ArgumentException("Managed deployment IDs require lowercase portable characters.", nameof(value)); + } + } this.value = value; } diff --git a/build/managed/Inno.Build.Managed/ManagedDeploymentResult.cs b/build/managed/Inno.Build.Managed/ManagedDeploymentResult.cs index c7c899b21..58e3743a4 100644 --- a/build/managed/Inno.Build.Managed/ManagedDeploymentResult.cs +++ b/build/managed/Inno.Build.Managed/ManagedDeploymentResult.cs @@ -35,10 +35,14 @@ IReadOnlyList files ArgumentException.ThrowIfNullOrWhiteSpace(outputDirectory); ArgumentException.ThrowIfNullOrWhiteSpace(sdkIdentity); ArgumentNullException.ThrowIfNull(files); - if (files.Count == 0 || files.Any(static file => string.IsNullOrWhiteSpace(file) - || Path.IsPathRooted(file) || file.Split('/', '\\').Any(static segment => segment is "." or "..")) - || files.Distinct(StringComparer.Ordinal).Count() != files.Count) + if (files.Count == 0 || files.Any(static file => ( + string.IsNullOrWhiteSpace(file) + || Path.IsPathRooted(file) || file.Split('/', '\\').Any(static segment => segment is "." or "..") + )) + || files.Distinct(StringComparer.Ordinal).Count() != files.Count + ) { throw new ArgumentException("Managed output requires unique relative artifact paths.", nameof(files)); + } this.deployment = deployment; this.outputDirectory = Path.GetFullPath(outputDirectory); this.sdkIdentity = sdkIdentity; diff --git a/build/pipeline/Inno.Build/BuildDiagnostic.cs b/build/pipeline/Inno.Build/BuildDiagnostic.cs index 72338f61c..940a95c7c 100644 --- a/build/pipeline/Inno.Build/BuildDiagnostic.cs +++ b/build/pipeline/Inno.Build/BuildDiagnostic.cs @@ -11,12 +11,10 @@ public enum BuildDiagnosticSeverity /// Provides non-failing build context. /// Information, - /// /// Reports a condition that did not prevent output creation. /// Warning, - /// /// Reports a condition that prevented a valid build. /// diff --git a/build/pipeline/Inno.Build/BuildPipeline.cs b/build/pipeline/Inno.Build/BuildPipeline.cs index 8804bd9d5..8b8926909 100644 --- a/build/pipeline/Inno.Build/BuildPipeline.cs +++ b/build/pipeline/Inno.Build/BuildPipeline.cs @@ -1,6 +1,4 @@ using System; -using Inno.Build.Managed; -using Inno.Extensibility.Reload; using System.Collections.Generic; using System.IO; using System.Linq; @@ -8,9 +6,11 @@ using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; +using Inno.Build.Managed; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Reload; +using Inno.Plugins.Authoring; using Inno.Scripting.Compiler; namespace Inno.Build; @@ -89,22 +89,34 @@ public BuildPipeline( m_managedDeployments = managedDeployments; GameBuildTargetBinding[] targets = gameTargets.ToArray(); if (targets.Any(static value => value is null)) + { throw new ArgumentException("Game target collection cannot contain null values.", nameof(gameTargets)); + } if (targets.Length == 0) + { throw new ArgumentException("At least one game build target is required.", nameof(gameTargets)); + } if (targets.Any(static value => string.IsNullOrWhiteSpace(value.packager.id.value))) + { throw new ArgumentException("Every game build target requires a valid identity.", nameof(gameTargets)); + } if (targets.Any(static value => string.IsNullOrWhiteSpace(value.packager.displayName))) + { throw new ArgumentException("Every game build target requires a display name.", nameof(gameTargets)); + } IGrouping? duplicate = targets .GroupBy(static value => value.packager.id) .FirstOrDefault(static group => group.Count() > 1); if (duplicate is not null) + { throw new ArgumentException($"Game target '{duplicate.Key}' is registered more than once.", nameof(gameTargets)); - m_availableGameTargets = Array.AsReadOnly(targets - .Select(static target => target.packager.id) - .OrderBy(static id => id.value, StringComparer.Ordinal) - .ToArray()); + } + m_availableGameTargets = Array.AsReadOnly( + targets + .Select(static target => target.packager.id) + .OrderBy(static id => id.value, StringComparer.Ordinal) + .ToArray() + ); m_gameTargets = targets.ToDictionary(static value => value.packager.id); m_supportPacks = new PlayerSupportPackCatalog(supportPackRoot); m_supportPackProvisioner = supportPackProvisioner; @@ -116,12 +128,9 @@ public BuildPipeline( compiler, m_gameTargets, m_supportPacks, - managedDeployments); - m_plugins = new PluginPackageBuilder( - assets, - plugins, - settings, - serialization); + managedDeployments + ); + m_plugins = new PluginPackageBuilder(assets, plugins, settings, serialization); } /// @@ -143,8 +152,8 @@ public BuildPipeline( /// public IReadOnlyList GetManagedDeployments(BuildTargetId target) => m_gameTargets.TryGetValue(target, out GameBuildTargetBinding? gameTarget) - ? m_managedDeployments.GetSupportedDeployments(gameTarget.packager.runtimeIdentifier) - : throw new ArgumentException($"Game target '{target}' is not registered.", nameof(target)); + ? m_managedDeployments.GetSupportedDeployments(gameTarget.packager.runtimeIdentifier) + : throw new ArgumentException($"Game target '{target}' is not registered.", nameof(target)); /// /// Tries to get the adapter-owned display name for a registered game target. @@ -206,12 +215,18 @@ public async ValueTask EnsurePlayerSupportPackAsync( CancellationToken cancellationToken = default ) { if (!m_gameTargets.TryGetValue(target, out GameBuildTargetBinding? binding)) + { throw new NotSupportedException($"Game target '{target}' is not registered."); + } IGameBuildTarget packager = binding.packager; _ = m_managedDeployments.Resolve(deployment ?? packager.defaultManagedDeployment, packager.runtimeIdentifier); cancellationToken.ThrowIfCancellationRequested(); return await m_supportPacks.ResolveOrProvisionAsync( - target, packager, m_supportPackProvisioner, cancellationToken).ConfigureAwait(false); + target, + packager, + m_supportPackProvisioner, + cancellationToken + ).ConfigureAwait(false); } /// diff --git a/build/pipeline/Inno.Build/BuildProfile.cs b/build/pipeline/Inno.Build/BuildProfile.cs index ae399d299..4b4cd7f69 100644 --- a/build/pipeline/Inno.Build/BuildProfile.cs +++ b/build/pipeline/Inno.Build/BuildProfile.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; - -using Inno.Core.Serialization; using Inno.Build.Managed; +using Inno.Core.Serialization; namespace Inno.Build; @@ -88,7 +87,8 @@ public ManagedDeploymentId? managedDeployment /// /// A newly owned profile with the same current-format scalar settings and stable selections. /// - public BuildProfile Copy() => new() + public BuildProfile Copy() + => new() { applicationId = applicationId, productName = productName, @@ -109,14 +109,22 @@ public ManagedDeploymentId? managedDeployment public void Validate() { if (!IsPortableIdentifier(applicationId)) + { throw new InvalidDataException("Application ID must be a stable lowercase portable identifier."); + } if (!IsPortableProductName(productName)) + { throw new InvalidDataException("Product name must be a portable file name."); - if (persistentDataPath is null || - !IsPortableDataPath(persistentDataPath.Length == 0 ? applicationId : persistentDataPath)) + } + if (persistentDataPath is null + || !IsPortableDataPath(persistentDataPath.Length == 0 ? applicationId : persistentDataPath) + ) { throw new InvalidDataException("Persistent data path must contain only portable folder names separated by '/'."); + } if (string.IsNullOrWhiteSpace(startupScene)) + { throw new InvalidDataException("A startup scene is required."); + } try { _ = new BuildTargetId(m_targetId); @@ -126,48 +134,61 @@ public void Validate() throw new InvalidDataException("A game build target is required and must use a portable target ID.", exception); } if (m_managedDeploymentId is null) + { throw new InvalidDataException("Managed deployment selection cannot be null."); + } if (m_managedDeploymentId.Length > 0) { - try { _ = new ManagedDeploymentId(m_managedDeploymentId); } + try + { + _ = new ManagedDeploymentId(m_managedDeploymentId); + } catch (ArgumentException exception) { throw new InvalidDataException("Managed deployment selection must use a portable provider ID.", exception); } } if (windowWidth <= 0 || windowHeight <= 0) + { throw new InvalidDataException("Window dimensions must be positive."); + } } private static bool IsPortableIdentifier(string value) { if (string.IsNullOrWhiteSpace(value)) + { return false; - return value.All(static character => + } + return value.All(static character => ( character is >= 'a' and <= 'z' || character is >= '0' and <= '9' - || character is '.' or '_' or '-'); + || character is '.' or '_' or '-' + )); } private static bool IsPortableDataPath(string value) => value is not null - && (value.Length == 0 || value.Split('/').All(static segment => + && (value.Length == 0 || value.Split('/').All(static segment => ( segment is not "." and not ".." && !segment.EndsWith('.') && !S_WINDOWS_RESERVED_NAMES.Contains(segment.Split('.', 2)[0]) - && IsPortableIdentifier(segment))); + && IsPortableIdentifier(segment) + ))); private static bool IsPortableProductName(string value) { if (string.IsNullOrWhiteSpace(value) || value is "." or ".." || value.EndsWith(' ') - || value.EndsWith('.')) - { + || value.EndsWith('.') + ) { return false; } if (value.Any(static character => character < ' ' || "<>:\"/\\|?*".Contains(character))) + { return false; + } string stem = value.Split('.', 2)[0]; return !S_WINDOWS_RESERVED_NAMES.Contains(stem); } diff --git a/build/pipeline/Inno.Build/BuildProfileStore.cs b/build/pipeline/Inno.Build/BuildProfileStore.cs index 7640d30d6..71f8d5956 100644 --- a/build/pipeline/Inno.Build/BuildProfileStore.cs +++ b/build/pipeline/Inno.Build/BuildProfileStore.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.IO; using Inno.Core.Serialization; @@ -63,7 +62,9 @@ SerializationRegistry serialization public BuildProfile Load() { if (!File.Exists(m_path)) + { throw new FileNotFoundException("The project build profile does not exist.", m_path); + } BuildProfile profile; try @@ -71,9 +72,9 @@ public BuildProfile Load() profile = m_serialization.Deserialize(File.ReadAllBytes(m_path)); } catch (Exception exception) when (exception is IOException - or InvalidDataException - or InvalidOperationException - or ArgumentException) + or InvalidDataException + or InvalidOperationException + or ArgumentException) { throw new InvalidDataException($"Build profile '{m_path}' is not a valid current-format document.", exception); } diff --git a/build/pipeline/Inno.Build/BuildProgress.cs b/build/pipeline/Inno.Build/BuildProgress.cs index b0233b8a7..61ceab869 100644 --- a/build/pipeline/Inno.Build/BuildProgress.cs +++ b/build/pipeline/Inno.Build/BuildProgress.cs @@ -29,13 +29,14 @@ public BuildProgress( string stage, double fraction, string message - ) - : this() + ) : this() { ArgumentException.ThrowIfNullOrWhiteSpace(stage); ArgumentException.ThrowIfNullOrWhiteSpace(message); if (fraction is < 0d or > 1d || double.IsNaN(fraction)) + { throw new ArgumentOutOfRangeException(nameof(fraction)); + } this.stage = stage; this.fraction = fraction; this.message = message; diff --git a/build/pipeline/Inno.Build/BuildResult.cs b/build/pipeline/Inno.Build/BuildResult.cs index 0fe01c6da..8cb87de92 100644 --- a/build/pipeline/Inno.Build/BuildResult.cs +++ b/build/pipeline/Inno.Build/BuildResult.cs @@ -96,7 +96,8 @@ internal static BuildResult Success( artifactBundleCount, runtimeAssemblyCount, embeddedPluginCount, - diagnostics); + diagnostics + ); } internal static BuildResult Failure( @@ -105,7 +106,9 @@ IReadOnlyList diagnostics ) { ArgumentNullException.ThrowIfNull(diagnostics); if (diagnostics.Count == 0) + { throw new ArgumentException("A failed build requires at least one diagnostic.", nameof(diagnostics)); + } return new BuildResult( false, outputPath: null, @@ -115,6 +118,7 @@ IReadOnlyList diagnostics artifactBundleCount: 0, runtimeAssemblyCount: 0, embeddedPluginCount: 0, - diagnostics); + diagnostics + ); } } diff --git a/build/pipeline/Inno.Build/BuildSettings.cs b/build/pipeline/Inno.Build/BuildSettings.cs index 90ee51d4a..a0ea9328a 100644 --- a/build/pipeline/Inno.Build/BuildSettings.cs +++ b/build/pipeline/Inno.Build/BuildSettings.cs @@ -1,7 +1,6 @@ using System; -using Inno.Build.Managed; using System.IO; - +using Inno.Build.Managed; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -118,7 +117,9 @@ BuildTargetId target ArgumentException.ThrowIfNullOrWhiteSpace(projectName); ArgumentNullException.ThrowIfNull(startupScene); if (string.IsNullOrWhiteSpace(target.value)) + { throw new ArgumentException("A default build target is required.", nameof(target)); + } string portableId = ProjectId.FromName(projectName).value; return new BuildSettings { @@ -145,16 +146,16 @@ BuildTargetId target /// public BuildProfile CreateGameProfile(ProjectId projectId) => new() - { - applicationId = projectId.value, - productName = gameProductName, - persistentDataPath = gamePersistentDataPath, - startupScene = gameStartupScene, - target = gameTarget, - managedDeployment = gameManagedDeployment, - windowWidth = gameWindowWidth, - windowHeight = gameWindowHeight - }; + { + applicationId = projectId.value, + productName = gameProductName, + persistentDataPath = gamePersistentDataPath, + startupScene = gameStartupScene, + target = gameTarget, + managedDeployment = gameManagedDeployment, + windowWidth = gameWindowWidth, + windowHeight = gameWindowHeight + }; /// /// Creates an isolated copy suitable for a temporary export draft. @@ -164,19 +165,19 @@ public BuildProfile CreateGameProfile(ProjectId projectId) /// public BuildSettings Copy() => new() - { - pluginDisplayName = pluginDisplayName, - pluginOutputPath = pluginOutputPath, - includePluginDependencies = includePluginDependencies, - gameProductName = gameProductName, - gamePersistentDataPath = gamePersistentDataPath, - gameStartupScene = gameStartupScene, - gameOutputDirectory = gameOutputDirectory, - gameWindowWidth = gameWindowWidth, - gameWindowHeight = gameWindowHeight, - m_gameTargetId = m_gameTargetId, - m_gameManagedDeploymentId = m_gameManagedDeploymentId - }; + { + pluginDisplayName = pluginDisplayName, + pluginOutputPath = pluginOutputPath, + includePluginDependencies = includePluginDependencies, + gameProductName = gameProductName, + gamePersistentDataPath = gamePersistentDataPath, + gameStartupScene = gameStartupScene, + gameOutputDirectory = gameOutputDirectory, + gameWindowWidth = gameWindowWidth, + gameWindowHeight = gameWindowHeight, + m_gameTargetId = m_gameTargetId, + m_gameManagedDeploymentId = m_gameManagedDeploymentId + }; internal void ValidateDocument() { @@ -187,12 +188,14 @@ internal void ValidateDocument() || gameStartupScene is null || gameOutputDirectory is null || m_gameTargetId is null - || m_gameManagedDeploymentId is null) - { + || m_gameManagedDeploymentId is null + ) { throw new InvalidDataException("Build Settings contains a null string."); } if (gameWindowWidth <= 0 || gameWindowHeight <= 0) + { throw new InvalidDataException("Build Settings window dimensions must be positive."); + } try { _ = gameTarget; diff --git a/build/pipeline/Inno.Build/BuildSettingsStore.cs b/build/pipeline/Inno.Build/BuildSettingsStore.cs index 557f72a8b..a0320e893 100644 --- a/build/pipeline/Inno.Build/BuildSettingsStore.cs +++ b/build/pipeline/Inno.Build/BuildSettingsStore.cs @@ -1,9 +1,8 @@ using System; using System.IO; - +using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Core.IO; namespace Inno.Build; @@ -47,7 +46,8 @@ BuildSettings defaultSettings new FileByteDocumentStore(Path.GetFullPath(path)), serialization, defaultSettings.Copy, - static value => value.ValidateDocument()); + static value => value.ValidateDocument() + ); m_defaultSettings = defaultSettings.Copy(); } @@ -59,7 +59,9 @@ public bool exists get { lock (m_sync) + { return m_documents.exists; + } } } @@ -71,7 +73,9 @@ public BuildSettings defaultSettings get { lock (m_sync) + { return m_defaultSettings.Copy(); + } } } @@ -87,7 +91,9 @@ public BuildSettings defaultSettings public BuildSettings Load() { lock (m_sync) + { return LoadLocked(); + } } /// @@ -110,7 +116,9 @@ public void Save(BuildSettings settings) ArgumentNullException.ThrowIfNull(settings); settings.ValidateDocument(); lock (m_sync) + { m_documents.Save(settings.Copy()); + } } /// @@ -122,7 +130,9 @@ public void Save(BuildSettings settings) public byte[] CaptureDocument() { lock (m_sync) + { return m_documents.Capture(LoadLocked()); + } } /// @@ -141,7 +151,9 @@ public void RestoreDocument(ReadOnlySpan document) { BuildSettings settings = Deserialize(document); lock (m_sync) + { m_documents.Save(settings); + } } /// @@ -158,13 +170,12 @@ public void RestoreDocument(ReadOnlySpan document) private BuildSettings LoadLocked() { return m_documents.exists - ? m_documents.LoadRequired() - : m_defaultSettings.Copy(); + ? m_documents.LoadRequired() + : m_defaultSettings.Copy(); } private BuildSettings Deserialize(ReadOnlySpan document) { return m_documents.Deserialize(document); } - } diff --git a/build/pipeline/Inno.Build/BuildTargetId.cs b/build/pipeline/Inno.Build/BuildTargetId.cs index fa9363e50..16cf0ad7e 100644 --- a/build/pipeline/Inno.Build/BuildTargetId.cs +++ b/build/pipeline/Inno.Build/BuildTargetId.cs @@ -22,7 +22,9 @@ public BuildTargetId(string value) foreach (char character in value) { if (!(character is >= 'a' and <= 'z' || character is >= '0' and <= '9' || character == '-')) + { throw new ArgumentException("Build target IDs must use lowercase portable characters.", nameof(value)); + } } this.value = value; } diff --git a/build/pipeline/Inno.Build/Content/ContentPackWriter.cs b/build/pipeline/Inno.Build/Content/ContentPackWriter.cs index fcc6c2f0c..5a6429b85 100644 --- a/build/pipeline/Inno.Build/Content/ContentPackWriter.cs +++ b/build/pipeline/Inno.Build/Content/ContentPackWriter.cs @@ -1,16 +1,15 @@ using System; +using System.Buffers; +using System.Collections.Generic; using System.IO; using System.IO.Compression; -using System.Collections.Generic; -using System.Buffers; using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - +using Inno.Content; using Inno.Core.IO; using Inno.Core.Serialization; -using Inno.Content; namespace Inno.Build; @@ -27,18 +26,20 @@ CancellationToken cancellationToken Directory.CreateDirectory(contentRoot); string temporary = Path.Combine(contentRoot, ".content.pack.staging-" + Guid.NewGuid().ToString("N")); string[] files = PathBoundary.EnumerateFiles(sourceRoot) - .OrderBy(static value => value, StringComparer.Ordinal).ToArray(); + .OrderBy(static value => value, StringComparer.Ordinal) + .ToArray(); ContentKey[] keys = files.Select(file => new ContentKey(Path.GetRelativePath(sourceRoot, file).Replace('\\', '/'))).ToArray(); _ = new ContentPackIndex(keys.Select(static key => new ContentEntry(key, 0, new string('0', 64)))); try { await using (FileStream stream = new( - temporary, - FileMode.CreateNew, - FileAccess.Write, - FileShare.None, - 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan)) + temporary, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { List entries = []; @@ -54,7 +55,8 @@ CancellationToken cancellationToken FileAccess.Read, FileShare.Read, 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan); + FileOptions.Asynchronous | FileOptions.SequentialScan + ); using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); byte[] buffer = ArrayPool.Shared.Rent(128 * 1024); long length = 0; @@ -78,18 +80,21 @@ CancellationToken cancellationToken ZipArchiveEntry indexEntry = archive.CreateEntry(ContentPackIndex.C_INDEX_KEY, CompressionLevel.Optimal); indexEntry.LastWriteTime = S_ARCHIVE_TIME; await using Stream indexOutput = indexEntry.Open(); - await indexOutput.WriteAsync(ContentPackIndexCodec.Encode(inventory, serialization), cancellationToken).ConfigureAwait(false); + await indexOutput.WriteAsync( + ContentPackIndexCodec.Encode(inventory, serialization), + cancellationToken + ).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); string contentHash; await using (FileStream input = new( - temporary, - FileMode.Open, - FileAccess.Read, - FileShare.Read, - 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan)) - { + temporary, + FileMode.Open, + FileAccess.Read, + FileShare.Read, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) { contentHash = Convert.ToHexString(await SHA256.HashDataAsync(input, cancellationToken).ConfigureAwait(false)); } string packPath = Path.Combine(contentRoot, $"content-{contentHash}.pack"); @@ -99,7 +104,9 @@ CancellationToken cancellationToken catch { if (File.Exists(temporary)) + { File.Delete(temporary); + } throw; } } diff --git a/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs b/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs index e650d50fe..081a6c6a3 100644 --- a/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs +++ b/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs @@ -1,20 +1,20 @@ -using Inno.Build.Managed; -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Security.Cryptography; using System.Reflection; +using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; +using Inno.Build.Managed; +using Inno.Core.Diagnostics; +using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Core.IO; using Inno.Extensibility.Modules; +using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; @@ -60,12 +60,18 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(request); request.Validate(); if (!m_targets.TryGetValue(request.profile.target, out GameBuildTargetBinding? binding)) + { throw new InvalidOperationException($"No game packager is registered for '{request.profile.target}'."); + } IGameBuildTarget target = binding.packager; IManagedDeploymentCompiler managedCompiler = m_managedDeployments.Resolve( - request.profile.managedDeployment ?? target.defaultManagedDeployment, target.runtimeIdentifier); + request.profile.managedDeployment ?? target.defaultManagedDeployment, + target.runtimeIdentifier + ); if (!m_assets.isInitialized) + { throw new InvalidOperationException("Game build requires an active authoring asset database."); + } string outputRoot = Path.GetFullPath(request.outputDirectory); ValidateOutputRoot(outputRoot); cancellationToken.ThrowIfCancellationRequested(); @@ -75,12 +81,15 @@ CancellationToken cancellationToken m_assets.WaitForIdle(); AssetPath startupPath = AssetPath.Parse(request.profile.startupScene); if (!m_assets.TryGetAssetType(startupPath, out Type? sceneType) || sceneType != typeof(SceneAsset)) + { throw new InvalidOperationException($"Startup scene '{startupPath}' is not an imported Scene asset."); + } if (AssetSample.IsRuntimeExcluded(startupPath, isDirectory: false)) { throw new InvalidOperationException( - $"Startup scene '{startupPath}' belongs to an authoring-only '~' sample directory " + - "and cannot be included in a Player build."); + $"Startup scene '{startupPath}' belongs to an authoring-only '~' sample directory " + + "and cannot be included in a Player build." + ); } long assetRevision = m_assets.revision; @@ -92,7 +101,10 @@ CancellationToken cancellationToken progress?.Report(new BuildProgress("snapshot", 0.05d, "Captured the combined authoring generation.")); Directory.CreateDirectory(outputRoot); - using ProcessOwnedDirectory stagingOwner = await ProcessOwnedDirectory.CreateAsync(outputRoot, cancellationToken).ConfigureAwait(false); + using ProcessOwnedDirectory stagingOwner = await ProcessOwnedDirectory.CreateAsync( + outputRoot, + cancellationToken + ).ConfigureAwait(false); string staging = stagingOwner.directory; using var stagingCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); Task? assetExportTask = null; @@ -106,18 +118,17 @@ CancellationToken cancellationToken string rawContent = Path.Combine(staging, "RawContent"); string targetContent = Path.Combine(staging, "TargetContent"); progress?.Report(new BuildProgress("content", 0.12d, "Exporting the runtime artifact closure.")); - assetExportTask = m_assets.ExportRuntimeArtifactsAsync( - rawContent, - stagingToken); - targetContentTask = binding.compiler.CompileAsync( - new GameBuildContentContext(request.profile, targetContent, serialization), - stagingToken) + assetExportTask = m_assets.ExportRuntimeArtifactsAsync(rawContent, stagingToken); + targetContentTask = binding.compiler + .CompileAsync(new GameBuildContentContext(request.profile, targetContent, serialization), stagingToken) .AsTask(); - ScriptCompilationResult compilation = await m_compiler.CompileRuntimeDeploymentAsync( + ScriptCompilationResult compilation = await m_compiler + .CompileRuntimeDeploymentAsync( Path.Combine(supportPack, "References"), new ScriptBuildProgress(progress), - stagingToken) + stagingToken + ) .ConfigureAwait(false); if (!compilation.success) { @@ -139,12 +150,15 @@ CancellationToken cancellationToken [new BuildDiagnostic( BuildDiagnosticSeverity.Error, "INNOBUILD1001", - "Runtime script compilation did not produce a complete assembly generation.")]); + "Runtime script compilation did not produce a complete assembly generation." + )] + ); } GameRuntimeModule[] runtimeModules = CreateRuntimeModules(compilation.moduleDeployments); byte[] runtimeManifest = RuntimeManifestEnvelope.Encode( CreateManifest(request.profile, plugins, runtimeModules), - serialization); + serialization + ); EnsureGenerationUnchanged(assetRevision, pluginRevision, settingsRevision); progress?.Report(new BuildProgress("prepare", 0.28d, "Prepared the runtime script and manifest generation.")); @@ -154,10 +168,7 @@ await BuildFileSystem.MergeDirectoryAsync(targetContent, rawContent, stagingToke .ConfigureAwait(false); EnsureGenerationUnchanged(assetRevision, pluginRevision, settingsRevision); - await File.WriteAllBytesAsync( - Path.Combine(rawContent, SettingsFileNames.project), - settings, - stagingToken) + await File.WriteAllBytesAsync(Path.Combine(rawContent, SettingsFileNames.project), settings, stagingToken) .ConfigureAwait(false); string managed = Path.Combine(staging, "CodeInputs"); Directory.CreateDirectory(managed); @@ -166,32 +177,25 @@ await File.WriteAllBytesAsync( stagingToken.ThrowIfCancellationRequested(); string destination = Path.Combine(managed, Path.GetFileName(assemblies[index])); if (File.Exists(destination)) + { throw new InvalidOperationException($"Runtime assembly '{Path.GetFileName(destination)}' is duplicated."); + } await BuildFileSystem.CopyFileAsync(assemblies[index], destination, stagingToken) .ConfigureAwait(false); } - string snapshotFingerprint = await BuildSnapshotFingerprint.ComputeAsync( - assetRevision, - assemblies, - plugins, - settings, - stagingToken) + string snapshotFingerprint = await BuildSnapshotFingerprint + .ComputeAsync(assetRevision, assemblies, plugins, settings, stagingToken) .ConfigureAwait(false); string packagedContent = Path.Combine(staging, "PackagedContent"); Directory.CreateDirectory(packagedContent); - await File.WriteAllBytesAsync( - Path.Combine(packagedContent, "runtime.manifest"), - runtimeManifest, - stagingToken) + await File + .WriteAllBytesAsync(Path.Combine(packagedContent, "runtime.manifest"), runtimeManifest, stagingToken) .ConfigureAwait(false); progress?.Report(new BuildProgress("pack", 0.55d, "Writing the deterministic content pack.")); - (_, string contentHash) = await ContentPackWriter.WriteAsync( - rawContent, - packagedContent, - serialization, - stagingToken) + (_, string contentHash) = await ContentPackWriter + .WriteAsync(rawContent, packagedContent, serialization, stagingToken) .ConfigureAwait(false); var catalog = new RuntimeContentCatalog { @@ -203,39 +207,59 @@ await File.WriteAllBytesAsync( runtimeAssemblyCount = assemblies.Length }; catalog.Validate(); - await File.WriteAllBytesAsync( + await File + .WriteAllBytesAsync( Path.Combine(packagedContent, "catalog.inno"), serialization.Serialize(catalog), - stagingToken) + stagingToken + ) .ConfigureAwait(false); EnsureGenerationUnchanged(assetRevision, pluginRevision, settingsRevision); string playerLink = Path.Combine(staging, "PlayerLink"); - await BuildFileSystem.CopyDirectoryAsync(Path.Combine(supportPack, "PlayerLink"), - playerLink, stagingToken).ConfigureAwait(false); - await PlayerCodeCompositionWriter.WriteAsync(playerLink, - GameCodeDeployment.FromManifest(runtimeModules), stagingToken).ConfigureAwait(false); + await BuildFileSystem.CopyDirectoryAsync( + Path.Combine(supportPack, "PlayerLink"), + playerLink, + stagingToken + ).ConfigureAwait(false); + await PlayerCodeCompositionWriter.WriteAsync( + playerLink, + GameCodeDeployment.FromManifest(runtimeModules), + stagingToken + ).ConfigureAwait(false); progress?.Report(new BuildProgress("managed", 0.62d, "Publishing the frozen game code deployment.")); string managedStaging = Path.Combine(staging, "ManagedDeployment"); ManagedDeploymentResult managedDeployment = await managedCompiler.CompileAsync( - new ManagedDeploymentRequest(Path.Combine(playerLink, "Player.csproj"), - target.runtimeIdentifier, managed, managedStaging, - Path.Combine(outputRoot, ".build-logs", Path.GetFileName(staging))), stagingToken).ConfigureAwait(false); + new ManagedDeploymentRequest( + Path.Combine(playerLink, "Player.csproj"), + target.runtimeIdentifier, + managed, + managedStaging, + Path.Combine(outputRoot, ".build-logs", Path.GetFileName(staging)) + ), + stagingToken + ).ConfigureAwait(false); ValidateManagedPublication(managedCompiler.id, managedStaging, managedDeployment); EnsureGenerationUnchanged(assetRevision, pluginRevision, settingsRevision); string platformStaging = Path.Combine(staging, "Platform"); Directory.CreateDirectory(platformStaging); progress?.Report(new BuildProgress("package", 0.78d, $"Composing {request.profile.target} Player output.")); - string composed = await target.PackageAsync( + string composed = await target + .PackageAsync( new GameBuildPackageContext(request.profile, supportPack, packagedContent, managedDeployment, platformStaging), - stagingToken) + stagingToken + ) .ConfigureAwait(false); string normalizedComposed = Path.GetFullPath(composed); if (!IsWithin(platformStaging, normalizedComposed)) + { throw new InvalidOperationException("A game target returned output outside its staging directory."); + } if (!Directory.Exists(normalizedComposed)) + { throw new DirectoryNotFoundException("The game target did not create its declared output directory."); + } stagingToken.ThrowIfCancellationRequested(); string final = Path.Combine(outputRoot, Path.GetFileName(normalizedComposed)); try @@ -253,8 +277,13 @@ await PlayerCodeCompositionWriter.WriteAsync(playerLink, } catch (Exception observerFailure) { - publicationDiagnostics.Add(new(BuildDiagnosticSeverity.Warning, "INNO-BUILD-PROGRESS", - $"The complete game was committed, but its progress observer failed: {observerFailure.Message}")); + publicationDiagnostics.Add( + new( + BuildDiagnosticSeverity.Warning, + "INNO-BUILD-PROGRESS", + $"The complete game was committed, but its progress observer failed: {observerFailure.Message}" + ) + ); } return BuildResult.Success( final, @@ -264,7 +293,8 @@ await PlayerCodeCompositionWriter.WriteAsync(playerLink, assetInfo.artifactBundleCount, assemblies.Length, embeddedPluginCount: 0, - diagnostics: publicationDiagnostics.AsReadOnly()); + diagnostics: publicationDiagnostics.AsReadOnly() + ); } finally { @@ -277,8 +307,13 @@ await PlayerCodeCompositionWriter.WriteAsync(playerLink, } catch (Exception cleanupFailure) when (committed && cleanupFailure is IOException or UnauthorizedAccessException) { - publicationDiagnostics.Add(new(BuildDiagnosticSeverity.Warning, "INNO-BUILD-CLEANUP", - $"The complete game was committed, but staging cleanup was deferred for '{staging}': {cleanupFailure.Message}")); + publicationDiagnostics.Add( + new( + BuildDiagnosticSeverity.Warning, + "INNO-BUILD-CLEANUP", + $"The complete game was committed, but staging cleanup was deferred for '{staging}': {cleanupFailure.Message}" + ) + ); } } } @@ -286,7 +321,9 @@ await PlayerCodeCompositionWriter.WriteAsync(playerLink, private static async ValueTask ObserveCompletionAsync(Task? task) { if (task is null) + { return; + } try { await task.ConfigureAwait(false); @@ -304,14 +341,21 @@ ManagedDeploymentResult result ) { ArgumentNullException.ThrowIfNull(result); StringComparison comparison = OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; if (result.deployment != deployment || !string.Equals(Path.GetFullPath(staging), result.outputDirectory, comparison) - || !Directory.Exists(result.outputDirectory)) + || !Directory.Exists(result.outputDirectory) + ) { throw new InvalidDataException("The managed publisher returned foreign or absent staging output."); + } string[] actualFiles = Directory.EnumerateFiles(result.outputDirectory, "*", SearchOption.AllDirectories) - .Select(file => Path.GetRelativePath(result.outputDirectory, file)).Order(StringComparer.Ordinal).ToArray(); + .Select(file => Path.GetRelativePath(result.outputDirectory, file)) + .Order(StringComparer.Ordinal) + .ToArray(); if (!actualFiles.SequenceEqual(result.files.Order(StringComparer.Ordinal), StringComparer.Ordinal)) + { throw new InvalidDataException("The managed publication evidence differs from its staged output."); + } } private static BuildDiagnostic ToBuildDiagnostic(ScriptDiagnostic diagnostic) @@ -323,8 +367,8 @@ private static BuildDiagnostic ToBuildDiagnostic(ScriptDiagnostic diagnostic) _ => BuildDiagnosticSeverity.Information }; string location = diagnostic.filePath is null - ? string.Empty - : $" ({diagnostic.filePath}:{diagnostic.line}:{diagnostic.column})"; + ? string.Empty + : $" ({diagnostic.filePath}:{diagnostic.line}:{diagnostic.column})"; return new BuildDiagnostic(severity, diagnostic.id, diagnostic.message + location); } @@ -362,11 +406,14 @@ private static GameRuntimeModule[] CreateRuntimeModules(IReadOnlyList request.assemblyScopes.TryGetValue( + .Where(path => ( + request.assemblyScopes.TryGetValue( Path.GetFileNameWithoutExtension(path), - out AssemblyScope scope) + out AssemblyScope scope + ) ? scope == AssemblyScope.Runtime - : request.scope == AssemblyScope.Runtime) + : request.scope == AssemblyScope.Runtime + )) .ToArray() }) .Where(static candidate => candidate.assemblies.Length > 0) @@ -392,21 +439,28 @@ private static GameRuntimeModule[] CreateRuntimeModules(IReadOnlyList(StringComparer.Ordinal); var ordered = new List(candidates.Length); foreach (GameRuntimeModule module in candidates.OrderBy(static module => module.name, StringComparer.Ordinal)) + { Visit(module); + } return ordered.ToArray(); void Visit(GameRuntimeModule module) { if (visited.Contains(module.name)) + { return; + } if (!visiting.Add(module.name)) + { throw new InvalidOperationException($"Runtime module dependency cycle contains '{module.name}'."); + } foreach (string dependencyName in module.dependencies.Order(StringComparer.Ordinal)) { if (!byName.TryGetValue(dependencyName, out GameRuntimeModule? dependency)) { throw new InvalidOperationException( - $"Runtime module '{module.name}' depends on missing module '{dependencyName}'."); + $"Runtime module '{module.name}' depends on missing module '{dependencyName}'." + ); } Visit(dependency); } @@ -423,11 +477,12 @@ long expectedSettingsRevision ) { if (m_assets.revision != expectedAssetRevision || m_plugins.revision != expectedPluginRevision - || m_settings.revision != expectedSettingsRevision) - { + || m_settings.revision != expectedSettingsRevision + ) { throw new InvalidOperationException( - "The active Asset, Plugin, or Project Settings generation changed during the build. " + - "No output was committed; start a new build from the latest generation."); + "The active Asset, Plugin, or Project Settings generation changed during the build. " + + "No output was committed; start a new build from the latest generation." + ); } } @@ -439,12 +494,15 @@ private void ValidateOutputRoot(string outputRoot) .ToList(); string? projectRoot = Directory.GetParent(m_assets.assetRoot)?.FullName; if (projectRoot is not null) + { protectedRoots.Add(Path.Combine(projectRoot, "Plugins")); + } string? conflict = protectedRoots.FirstOrDefault(root => IsWithin(root, outputRoot)); if (conflict is not null) { throw new InvalidOperationException( - $"Build output cannot be written inside managed project content '{Path.GetFullPath(conflict)}'."); + $"Build output cannot be written inside managed project content '{Path.GetFullPath(conflict)}'." + ); } } @@ -454,14 +512,13 @@ string candidate ) { string normalizedRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); StringComparison comparison = OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase - : StringComparison.Ordinal; + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; return string.Equals(candidate, normalizedRoot, comparison) || candidate.StartsWith(normalizedRoot + Path.DirectorySeparatorChar, comparison); } - private sealed class ScriptBuildProgress(IProgress? progress) - : IProgress + private sealed class ScriptBuildProgress(IProgress? progress) : IProgress { /// /// Publishes one progress update to the receiving workflow. @@ -470,9 +527,6 @@ private sealed class ScriptBuildProgress(IProgress? progress) /// The concrete value read or transformed by this operation. /// public void Report(ScriptCompilationProgress value) - => progress?.Report(new BuildProgress( - "scripting", - 0.05d + value.fraction * 0.2d, - value.stage)); + => progress?.Report(new BuildProgress("scripting", 0.05d + value.fraction * 0.2d, value.stage)); } } diff --git a/build/pipeline/Inno.Build/Game/GameBuildTargetBinding.cs b/build/pipeline/Inno.Build/Game/GameBuildTargetBinding.cs index e8f5347d3..7bd66422d 100644 --- a/build/pipeline/Inno.Build/Game/GameBuildTargetBinding.cs +++ b/build/pipeline/Inno.Build/Game/GameBuildTargetBinding.cs @@ -29,7 +29,9 @@ IGameContentCompiler compiler ArgumentNullException.ThrowIfNull(packager); ArgumentNullException.ThrowIfNull(compiler); if (string.IsNullOrWhiteSpace(packager.id.value) || packager.id != compiler.target) + { throw new ArgumentException("Packaging and content compilation require the same assigned target.", nameof(compiler)); + } this.packager = packager; this.compiler = compiler; } diff --git a/build/pipeline/Inno.Build/Game/IGameBuildTarget.cs b/build/pipeline/Inno.Build/Game/IGameBuildTarget.cs index 645ba0979..2ad5955ce 100644 --- a/build/pipeline/Inno.Build/Game/IGameBuildTarget.cs +++ b/build/pipeline/Inno.Build/Game/IGameBuildTarget.cs @@ -1,6 +1,6 @@ -using Inno.Build.Managed; using System.Threading; using System.Threading.Tasks; +using Inno.Build.Managed; namespace Inno.Build; diff --git a/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs b/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs index c04f0dae1..196dca1f9 100644 --- a/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs +++ b/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs @@ -20,33 +20,54 @@ CancellationToken cancellationToken XDocument document = XDocument.Load(project); string? assemblyName = document.Descendants("AssemblyName").Select(static item => item.Value).SingleOrDefault(); if (string.IsNullOrWhiteSpace(assemblyName)) + { throw new InvalidDataException("A prepared Player project must declare its assembly name explicitly."); + } var source = new StringBuilder("// \n#nullable enable\n"); - source.Append("namespace ").Append(assemblyName).Append(".Generated;\n\n") + source.Append("namespace ") + .Append(assemblyName) + .Append(".Generated;\n\n") .Append("internal static class PlayerDeploymentDefinition\n{\n") .Append(" internal static global::Inno.Runtime.GameCodeDeployment CreateDeployment() => new([\n"); foreach (GameCodeModule module in deployment.modules) { - source.Append(" new global::Inno.Runtime.GameCodeModule(\n ").Append(Quote(module.name)) - .Append(", global::Inno.Extensibility.Modules.AssemblyDomain.").Append(module.domain).Append(", [\n"); + source.Append(" new global::Inno.Runtime.GameCodeModule(\n ") + .Append(Quote(module.name)) + .Append(", global::Inno.Extensibility.Modules.AssemblyDomain.") + .Append(module.domain) + .Append(", [\n"); foreach (GameCodeAssembly assembly in module.assemblies) - source.Append(" new global::Inno.Runtime.GameCodeAssembly(").Append(Quote(assembly.name)) - .Append(", ").Append(Quote(assembly.contentFingerprint)).Append("),\n"); + { + source.Append(" new global::Inno.Runtime.GameCodeAssembly(") + .Append(Quote(assembly.name)) + .Append(", ") + .Append(Quote(assembly.contentFingerprint)) + .Append("),\n"); + } source.Append(" ], [").Append(string.Join(", ", module.dependencies.Select(Quote))).Append("]),\n"); } source.Append(" ]);\n\n") - .Append(" internal static global::System.Collections.Generic.IReadOnlyDictionary> CreateAssemblies() =>\n") - .Append(" new global::System.Collections.Generic.Dictionary>\n {\n"); + .Append( + " internal static global::System.Collections.Generic.IReadOnlyDictionary> CreateAssemblies() =>\n" + ) + .Append( + " new global::System.Collections.Generic.Dictionary>\n {\n" + ); foreach (GameCodeModule module in deployment.modules) { source.Append(" [").Append(Quote(module.name)).Append("] = [\n"); foreach (GameCodeAssembly assembly in module.assemblies) + { source.Append(" global::").Append(assembly.name).Append(".Generated.RuntimeModuleCatalog.assembly,\n"); + } source.Append(" ],\n"); } source.Append(" };\n}\n"); - await File.WriteAllTextAsync(Path.Combine(playerDirectory, "PlayerDeploymentDefinition.g.cs"), - source.ToString(), cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(playerDirectory, "PlayerDeploymentDefinition.g.cs"), + source.ToString(), + cancellationToken + ).ConfigureAwait(false); } private static string Quote(string value) @@ -55,11 +76,17 @@ private static string Quote(string value) foreach (char character in value) { if (character is '\\' or '"') + { literal.Append('\\').Append(character); + } else if (char.IsControl(character)) + { literal.Append("\\u").Append(((int)character).ToString("x4", System.Globalization.CultureInfo.InvariantCulture)); + } else + { literal.Append(character); + } } return literal.Append('"').ToString(); } diff --git a/build/pipeline/Inno.Build/GameBuildRequest.cs b/build/pipeline/Inno.Build/GameBuildRequest.cs index 30d419be2..4451d4234 100644 --- a/build/pipeline/Inno.Build/GameBuildRequest.cs +++ b/build/pipeline/Inno.Build/GameBuildRequest.cs @@ -27,9 +27,13 @@ public sealed class GameBuildRequest public void Validate() { if (profile is null) + { throw new InvalidDataException("A game build profile is required."); + } profile.Validate(); if (string.IsNullOrWhiteSpace(outputDirectory)) + { throw new InvalidDataException("A game output directory is required."); + } } } diff --git a/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs b/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs index 4820bd5c0..b3ae5f298 100644 --- a/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs +++ b/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs @@ -1,9 +1,8 @@ using System; using System.IO; - -using Inno.Core.IO; using System.Threading; using System.Threading.Tasks; +using Inno.Core.IO; namespace Inno.Build; @@ -15,7 +14,9 @@ internal static async ValueTask MergeDirectoryAsync( CancellationToken cancellationToken ) { if (!Directory.Exists(source)) + { return; + } Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) { @@ -28,7 +29,9 @@ CancellationToken cancellationToken string target = Path.Combine(destination, Path.GetRelativePath(source, file)); Directory.CreateDirectory(Path.GetDirectoryName(target)!); if (File.Exists(target)) + { throw new IOException($"Target artifact '{Path.GetRelativePath(destination, target)}' collides with runtime content."); + } await CopyFileAsync(file, target, cancellationToken).ConfigureAwait(false); } } @@ -39,7 +42,9 @@ internal static async ValueTask CopyDirectoryAsync( CancellationToken cancellationToken ) { if (!Directory.Exists(source)) + { throw new DirectoryNotFoundException($"Build input directory '{source}' does not exist."); + } Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) { @@ -66,23 +71,26 @@ CancellationToken cancellationToken FileAccess.Read, FileShare.Read, 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan); + FileOptions.Asynchronous | FileOptions.SequentialScan + ); await using FileStream output = new( destination, FileMode.CreateNew, FileAccess.Write, FileShare.None, 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan); + FileOptions.Asynchronous | FileOptions.SequentialScan + ); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); await output.FlushAsync(cancellationToken).ConfigureAwait(false); if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(destination, File.GetUnixFileMode(source)); + } } internal static void InstallDirectoryAtomically( string source, string destination ) => AtomicDirectory.Install(source, destination); - } diff --git a/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs b/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs index cabc4682a..ebbc52261 100644 --- a/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs +++ b/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs @@ -1,13 +1,13 @@ using System; -using System.Collections.Generic; using System.Collections.Concurrent; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; -using Inno.Core.IO; using System.Threading; using System.Threading.Tasks; +using Inno.Core.IO; namespace Inno.Build; @@ -92,14 +92,24 @@ public async ValueTask SelectAsync( ArgumentNullException.ThrowIfNull(validator); ArgumentNullException.ThrowIfNull(verifyInputs); if (fingerprint is null || fingerprint.Length != 64 - || fingerprint.Any(static character => !char.IsAsciiHexDigitLower(character))) + || fingerprint.Any(static character => !char.IsAsciiHexDigitLower(character)) + ) { throw new ArgumentException("A prepared Pack requires its exact content identity.", nameof(fingerprint)); + } cancellationToken.ThrowIfCancellationRequested(); string targetRoot = PathBoundary.Resolve(m_root, target.value); - using FileLease selection = await FileLease.AcquireAsync(Path.Combine(targetRoot, "current.lock"), - Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); - PlayerSupportPackLease reading = AcquireArtifact(PathBoundary.Resolve(targetRoot, fingerprint), fingerprint, - target, validator, cancellationToken); + using FileLease selection = await FileLease.AcquireAsync( + Path.Combine(targetRoot, "current.lock"), + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); + PlayerSupportPackLease reading = AcquireArtifact( + PathBoundary.Resolve(targetRoot, fingerprint), + fingerprint, + target, + validator, + cancellationToken + ); try { await VerifySelectionInputsAsync(verifyInputs, cancellationToken).ConfigureAwait(false); @@ -153,12 +163,15 @@ public PlayerSupportPackLease Acquire( if (!File.Exists(index)) { throw new DirectoryNotFoundException( - $"Player Support Pack '{target}' is not installed at '{targetRoot}'. " + - "Install or generate the target Support Pack before exporting."); + $"Player Support Pack '{target}' is not installed at '{targetRoot}'. " + + "Install or generate the target Support Pack before exporting." + ); } string fingerprint = File.ReadAllText(index); if (fingerprint.Length != 64 || fingerprint.Any(static character => !char.IsAsciiHexDigitLower(character))) + { throw new InvalidDataException($"Player Support Pack '{target}' has an invalid current fingerprint."); + } string directory = Path.Combine(targetRoot, fingerprint); return AcquireArtifact(directory, fingerprint, target, validator, cancellationToken); } @@ -211,7 +224,10 @@ public async ValueTask PublishAsync( string targetRoot = Path.Combine(m_root, target.value); Directory.CreateDirectory(targetRoot); using FileLease ownership = await FileLease.AcquireAsync( - Path.Combine(targetRoot, "current.lock"), Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + Path.Combine(targetRoot, "current.lock"), + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); string destination = Path.Combine(targetRoot, fingerprint); bool valid = false; if (Directory.Exists(destination)) @@ -219,7 +235,12 @@ public async ValueTask PublishAsync( try { using PlayerSupportPackLease existing = AcquireArtifact( - destination, fingerprint, target, validator, cancellationToken); + destination, + fingerprint, + target, + validator, + cancellationToken + ); valid = true; } catch (InvalidDataException) { } @@ -227,9 +248,14 @@ public async ValueTask PublishAsync( if (!valid) { using FileLease publication = await FileLease.AcquireAsync( - GetLeasePath(destination), TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false); + GetLeasePath(destination), + TimeSpan.FromSeconds(30), + cancellationToken + ).ConfigureAwait(false); if (verifyInputs is not null) + { await VerifySelectionInputsAsync(verifyInputs, cancellationToken).ConfigureAwait(false); + } cancellationToken.ThrowIfCancellationRequested(); PathBoundary.RequireUnlinkedPath(targetRoot, destination); try @@ -242,12 +268,16 @@ public async ValueTask PublishAsync( } } else if (verifyInputs is not null) + { await VerifySelectionInputsAsync(verifyInputs, cancellationToken).ConfigureAwait(false); + } PlayerSupportPackLease reading = AcquireArtifact(destination, fingerprint, target, validator, cancellationToken); try { if (verifyInputs is not null) + { await VerifySelectionInputsAsync(verifyInputs, cancellationToken).ConfigureAwait(false); + } cancellationToken.ThrowIfCancellationRequested(); SelectCurrent(targetRoot, fingerprint); return reading; @@ -265,7 +295,9 @@ string fingerprint ) { string index = Path.Combine(targetRoot, "current"); if (!File.Exists(index) || File.ReadAllText(index) != fingerprint) + { AtomicFile.WriteAllBytes(index, Encoding.UTF8.GetBytes(fingerprint)); + } } private static async ValueTask VerifySelectionInputsAsync( @@ -292,16 +324,24 @@ CancellationToken cancellationToken string path = GetLeasePath(directory); if (!File.Exists(path)) { - using FileLease initializer = FileLease.AcquireAsync(path, - TimeSpan.FromSeconds(30), cancellationToken).GetAwaiter().GetResult(); + using FileLease initializer = FileLease.AcquireAsync( + path, + TimeSpan.FromSeconds(30), + cancellationToken + ).GetAwaiter().GetResult(); } - FileLease lease = FileLease.AcquireSharedAsync(path, - TimeSpan.FromSeconds(30), cancellationToken).GetAwaiter().GetResult(); + FileLease lease = FileLease.AcquireSharedAsync( + path, + TimeSpan.FromSeconds(30), + cancellationToken + ).GetAwaiter().GetResult(); try { ValidateDirectory(directory, target, validator); if (ComputeFingerprint(directory, cancellationToken) != fingerprint) + { throw new InvalidDataException($"Player Support Pack '{target}' no longer matches its immutable fingerprint."); + } return new PlayerSupportPackLease(directory, lease); } catch @@ -319,27 +359,34 @@ private static void ValidateDirectory( IPlayerSupportPackValidator validator ) { if (!Directory.Exists(directory)) + { throw new InvalidDataException($"Player Support Pack '{target}' points to a missing artifact '{directory}'."); + } string[] files = PathBoundary.EnumerateFiles(directory).ToArray(); if (files.Length == 0) + { throw new InvalidDataException($"Player Support Pack '{target}' is empty."); + } foreach (string file in files) { string relativePath = Path.GetRelativePath(directory, file); if (relativePath.StartsWith("PlayerLink" + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { continue; + } string name = Path.GetFileName(file); if (S_FORBIDDEN_EXTENSIONS.Contains(Path.GetExtension(name)) - || S_FORBIDDEN_NAME_TOKENS.Any(token => name.Contains(token, StringComparison.OrdinalIgnoreCase))) - { + || S_FORBIDDEN_NAME_TOKENS.Any(token => name.Contains(token, StringComparison.OrdinalIgnoreCase)) + ) { throw new InvalidDataException( - $"Player Support Pack '{target}' contains forbidden build-time file '{name}'."); + $"Player Support Pack '{target}' contains forbidden build-time file '{name}'." + ); } } string referenceDirectory = Path.Combine(directory, "References"); if (!Directory.Exists(referenceDirectory) - || !Directory.EnumerateFiles(referenceDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly).Any()) - { + || !Directory.EnumerateFiles(referenceDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly).Any() + ) { throw new InvalidDataException($"Player Support Pack '{target}' has no target compilation references."); } validator.Validate(directory); @@ -353,7 +400,9 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); if (provisioner is null) + { return Acquire(target, validator, cancellationToken); + } SemaphoreSlim gate = m_provisionGates.GetOrAdd(target, static _ => new SemaphoreSlim(1, 1)); await gate.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -376,8 +425,8 @@ CancellationToken cancellationToken using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); Span length = stackalloc byte[sizeof(int)]; foreach (string file in PathBoundary.EnumerateFiles(directory) - .OrderBy(path => Path.GetRelativePath(directory, path).Replace('\\', '/'), StringComparer.Ordinal)) - { + .OrderBy(path => Path.GetRelativePath(directory, path).Replace('\\', '/'), StringComparer.Ordinal) + ) { cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(directory, file).Replace('\\', '/'); byte[] path = Encoding.UTF8.GetBytes(relative); diff --git a/build/pipeline/Inno.Build/PluginBuildRequest.cs b/build/pipeline/Inno.Build/PluginBuildRequest.cs index e9e5fa32f..ca8603909 100644 --- a/build/pipeline/Inno.Build/PluginBuildRequest.cs +++ b/build/pipeline/Inno.Build/PluginBuildRequest.cs @@ -1,7 +1,7 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; -using System.Collections.Generic; namespace Inno.Build; @@ -49,19 +49,23 @@ public void Validate() || pluginId.Any(static character => !(character is >= 'a' and <= 'z' || character is >= '0' and <= '9' - || character is '.' or '_' or '-'))) - { + || character is '.' or '_' or '-')) + ) { throw new InvalidDataException("Plugin ID must be a non-reserved lowercase portable identifier."); } if (string.IsNullOrWhiteSpace(displayName)) + { throw new InvalidDataException("A Plugin display name is required."); + } if (string.IsNullOrWhiteSpace(outputPath) - || !string.Equals(Path.GetExtension(outputPath), ".iplugin", StringComparison.OrdinalIgnoreCase)) - { + || !string.Equals(Path.GetExtension(outputPath), ".iplugin", StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidDataException("Plugin destination must use the .iplugin extension."); } if (dependencies is null || dependencies.Any(string.IsNullOrWhiteSpace) - || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Count) + || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Count + ) { throw new InvalidDataException("Plugin dependencies must be distinct non-empty IDs."); + } } } diff --git a/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs b/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs index 54c04116c..216f3ddd1 100644 --- a/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs +++ b/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs @@ -8,17 +8,18 @@ using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; -using Inno.Plugins; using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Plugins; +using Inno.Plugins.Authoring; namespace Inno.Build; internal sealed class PluginPackageBuilder { private static readonly DateTimeOffset S_ARCHIVE_TIME = new(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly HashSet S_FORBIDDEN_EXTENSIONS = new(StringComparer.OrdinalIgnoreCase) { ".dll", ".exe", ".dylib", ".so", ".a", ".lib", ".pdb" @@ -49,10 +50,12 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(request); request.Validate(); if (!m_assets.isInitialized) + { throw new InvalidOperationException("Plugin build requires an active authoring asset database."); + } if (m_plugins.activePlugins.Any(plugin => - string.Equals(plugin.manifest.pluginId, request.pluginId, StringComparison.Ordinal))) - { + string.Equals(plugin.manifest.pluginId, request.pluginId, StringComparison.Ordinal)) + ) { throw new InvalidOperationException($"Plugin ID '{request.pluginId}' is already active in this project."); } string destination = Path.GetFullPath(request.outputPath); @@ -65,12 +68,13 @@ CancellationToken cancellationToken try { await using (FileStream stream = new( - temporary, - FileMode.CreateNew, - FileAccess.Write, - FileShare.None, - 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan)) + temporary, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { await WriteBytesAsync(archive, "Plugin.inno", plan.manifest, cancellationToken) @@ -80,41 +84,50 @@ await WriteBytesAsync(archive, "Plugin.inno", plan.manifest, cancellationToken) { await WriteSourceAsync(archive, source, cancellationToken).ConfigureAwait(false); completed++; - progress?.Report(new BuildProgress( - "project-content", - 0.15d + 0.5d * completed / Math.Max(1d, plan.projectEntries.Count), - $"Packaging project source {completed}/{plan.projectEntries.Count}.")); + progress?.Report( + new BuildProgress( + "project-content", + 0.15d + 0.5d * completed / Math.Max(1d, plan.projectEntries.Count), + $"Packaging project source {completed}/{plan.projectEntries.Count}." + ) + ); } for (int index = 0; index < plan.dependencies.Count; index++) { PluginDependencyPlan dependency = plan.dependencies[index]; ZipArchiveEntry packageEntry = archive.CreateEntry( $"Dependencies/{dependency.pluginId}.iplugin", - CompressionLevel.Optimal); + CompressionLevel.Optimal + ); packageEntry.LastWriteTime = S_ARCHIVE_TIME; await using Stream packageStream = packageEntry.Open(); using var nested = new ZipArchive(packageStream, ZipArchiveMode.Create, leaveOpen: true); await WriteBytesAsync(nested, "Plugin.inno", dependency.manifest, cancellationToken) .ConfigureAwait(false); foreach (SourceEntry source in dependency.entries) + { await WriteSourceAsync(nested, source, cancellationToken).ConfigureAwait(false); - progress?.Report(new BuildProgress( - "dependencies", - 0.7d + 0.2d * (index + 1) / Math.Max(1d, plan.dependencies.Count), - $"Embedded dependency {index + 1}/{plan.dependencies.Count}.")); + } + progress?.Report( + new BuildProgress( + "dependencies", + 0.7d + 0.2d * (index + 1) / Math.Max(1d, plan.dependencies.Count), + $"Embedded dependency {index + 1}/{plan.dependencies.Count}." + ) + ); } } EnsurePlanUnchanged(plan); cancellationToken.ThrowIfCancellationRequested(); string contentHash; await using (FileStream stream = new( - temporary, - FileMode.Open, - FileAccess.Read, - FileShare.Read, - 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan)) - { + temporary, + FileMode.Open, + FileAccess.Read, + FileShare.Read, + 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) { contentHash = Convert.ToHexString(await SHA256.HashDataAsync(stream, cancellationToken).ConfigureAwait(false)); } AtomicFile.Install(temporary, destination); @@ -126,41 +139,54 @@ await WriteBytesAsync(nested, "Plugin.inno", dependency.manifest, cancellationTo plan.assetCount, artifactBundleCount: 0, runtimeAssemblyCount: 0, - plan.dependencies.Count); + plan.dependencies.Count + ); } finally { if (File.Exists(temporary)) + { File.Delete(temporary); + } } } private PluginPackagePlan CapturePlan(PluginBuildRequest request) { - AssetSourceMount projectMount = m_assets.sourceMounts.Single( - static mount => mount.id == AssetSourceId.project); + AssetSourceMount projectMount = m_assets.sourceMounts.Single(static mount => mount.id == AssetSourceId.project); PluginCandidate[] installedPlugins = m_plugins.activePlugins.ToArray(); ValidateDependencyGraph(installedPlugins); var selectedIds = new HashSet(StringComparer.Ordinal); var installedById = installedPlugins.ToDictionary( - static plugin => plugin.manifest.pluginId, StringComparer.Ordinal); + static plugin => plugin.manifest.pluginId, + StringComparer.Ordinal + ); void SelectDependency(string id) { if (!installedById.TryGetValue(id, out PluginCandidate? plugin)) + { throw new InvalidOperationException($"Declared plugin dependency '{id}' is not installed and active."); + } if (!selectedIds.Add(id)) + { return; + } foreach (string upstream in plugin.manifest.dependencies) + { SelectDependency(upstream); + } } foreach (string id in request.dependencies) + { SelectDependency(id); + } PluginCandidate[] activePlugins = installedPlugins .Where(plugin => selectedIds.Contains(plugin.manifest.pluginId)) .ToArray(); string[] dependencyIds = activePlugins.Select(static plugin => plugin.manifest.pluginId).ToArray(); ProjectSettingsDocument settingsDocument = m_serialization.Deserialize( - m_settings.CaptureDocument()); + m_settings.CaptureDocument() + ); string[] overrides = activePlugins .Where(plugin => plugin.manifest.settingContributions.Any(contribution => settingsDocument.overrides.Any(project => project.id == contribution.id))) @@ -170,15 +196,15 @@ void SelectDependency(string id) HashSet overrideSet = overrides.ToHashSet(StringComparer.Ordinal); var settings = new List(); foreach (ProjectSettingRecord record in settingsDocument.overrides - .OrderBy(static value => value.id.value, StringComparer.Ordinal)) - { + .OrderBy(static value => value.id.value, StringComparer.Ordinal) + ) { if (m_settings.TryCapture( - record.id, - request.pluginId, - dependencySet, - overrideSet, - out ProjectSettingRecord captured)) - { + record.id, + request.pluginId, + dependencySet, + overrideSet, + out ProjectSettingRecord captured + )) { settings.Add(captured); } } @@ -188,12 +214,16 @@ void SelectDependency(string id) .OrderBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal) .ToArray(); if (projectFiles.Length == 0) + { throw new InvalidOperationException("The project contains no source content to export."); + } string[] relativeFiles = projectFiles.Select(static entry => entry.assetPath.localPath).ToArray(); foreach (string relative in relativeFiles) { if (S_FORBIDDEN_EXTENSIONS.Contains(Path.GetExtension(relative))) + { throw new InvalidOperationException($"Plugin content '{relative}' is a forbidden binary."); + } } var manifest = new PluginManifest { @@ -231,20 +261,22 @@ void SelectDependency(string id) { foreach (PluginCandidate plugin in activePlugins) { - SourceEntry[] entries = Directory.EnumerateFiles( - plugin.sourceMount.rootPath, - "*", - SearchOption.AllDirectories) + SourceEntry[] entries = Directory + .EnumerateFiles(plugin.sourceMount.rootPath, "*", SearchOption.AllDirectories) .Select(path => SourceEntry.Capture( path, - "Assets/" + Path.GetRelativePath(plugin.sourceMount.rootPath, path).Replace('\\', '/'))) + "Assets/" + Path.GetRelativePath(plugin.sourceMount.rootPath, path).Replace('\\', '/') + )) .OrderBy(static value => value.archivePath, StringComparer.Ordinal) .ToArray(); - dependencies.Add(new PluginDependencyPlan( - plugin.manifest.pluginId, - plugin.contentHash, - m_serialization.Serialize(plugin.manifest), - entries)); + dependencies.Add( + new PluginDependencyPlan( + plugin.manifest.pluginId, + plugin.contentHash, + m_serialization.Serialize(plugin.manifest), + entries + ) + ); } } return new PluginPackagePlan( @@ -252,7 +284,8 @@ void SelectDependency(string id) projectEntries, dependencies, projectFiles.Length, - installedPlugins.Select(static plugin => (plugin.manifest.pluginId, plugin.contentHash)).ToArray()); + installedPlugins.Select(static plugin => (plugin.manifest.pluginId, plugin.contentHash)).ToArray() + ); } private static async ValueTask WriteSourceAsync( @@ -270,7 +303,8 @@ CancellationToken cancellationToken FileAccess.Read, FileShare.Read, 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan); + FileOptions.Asynchronous | FileOptions.SequentialScan + ); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); source.EnsureUnchanged(); } @@ -290,40 +324,55 @@ CancellationToken cancellationToken private void EnsurePlanUnchanged(PluginPackagePlan plan) { foreach (SourceEntry source in plan.projectEntries) + { source.EnsureUnchanged(); + } foreach (PluginDependencyPlan dependency in plan.dependencies) { foreach (SourceEntry source in dependency.entries) + { source.EnsureUnchanged(); + } } (string pluginId, string contentHash)[] current = m_plugins.activePlugins .Select(static plugin => (plugin.manifest.pluginId, plugin.contentHash)) .ToArray(); if (!plan.activePlugins.SequenceEqual(current)) + { throw new InvalidOperationException("The active Plugin generation changed during package creation."); + } } private static void ValidateDependencyGraph(IReadOnlyList plugins) { Dictionary byId = plugins.ToDictionary( static value => value.manifest.pluginId, - StringComparer.Ordinal); + StringComparer.Ordinal + ); var completed = new HashSet(StringComparer.Ordinal); var visiting = new HashSet(StringComparer.Ordinal); foreach (PluginCandidate plugin in plugins) + { Visit(plugin.manifest.pluginId); + } void Visit(string id) { if (completed.Contains(id)) + { return; + } if (!visiting.Add(id)) + { throw new InvalidOperationException($"Plugin dependency graph contains a cycle at '{id}'."); + } PluginCandidate plugin = byId[id]; foreach (string dependency in plugin.manifest.dependencies) { if (!byId.ContainsKey(dependency)) + { throw new InvalidOperationException($"Plugin '{id}' requires unavailable dependency '{dependency}'."); + } Visit(dependency); } visiting.Remove(id); @@ -354,10 +403,14 @@ private void ValidateDestination(string destination) .ToList(); string? projectRoot = Directory.GetParent(m_assets.assetRoot)?.FullName; if (projectRoot is not null) + { protectedRoots.Add(Path.Combine(projectRoot, "Plugins")); + } string? conflict = protectedRoots.FirstOrDefault(root => IsWithin(root, destination)); if (conflict is not null) + { throw new InvalidOperationException($"Plugin output cannot be written inside '{Path.GetFullPath(conflict)}'."); + } } private static bool IsWithin( @@ -366,8 +419,8 @@ string candidate ) { string normalizedRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); StringComparison comparison = OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase - : StringComparison.Ordinal; + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; return string.Equals(candidate, normalizedRoot, comparison) || candidate.StartsWith(normalizedRoot + Path.DirectorySeparatorChar, comparison); } @@ -399,19 +452,19 @@ string archivePath ) { var info = new FileInfo(sourcePath); if (!info.Exists) + { throw new InvalidOperationException($"Plugin source dependency '{sourcePath}' is missing."); - return new SourceEntry( - info.FullName, - archivePath.Replace('\\', '/'), - info.Length, - info.LastWriteTimeUtc); + } + return new SourceEntry(info.FullName, archivePath.Replace('\\', '/'), info.Length, info.LastWriteTimeUtc); } internal void EnsureUnchanged() { var info = new FileInfo(sourcePath); if (!info.Exists || info.Length != length || info.LastWriteTimeUtc != lastWriteTimeUtc) + { throw new InvalidOperationException($"Plugin source '{sourcePath}' changed during package creation."); + } } } } diff --git a/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs b/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs index f4dafb011..c5c38fb8b 100644 --- a/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs +++ b/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs @@ -1,6 +1,6 @@ using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text.Json; using System.Threading; @@ -47,7 +47,11 @@ public ScriptCompilationInputs Capture(CancellationToken cancellationToken = def private async Task CaptureAsync(CancellationToken cancellationToken) { - DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync(m_dotnetHost, m_projectRoot, cancellationToken).ConfigureAwait(false); + DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync( + m_dotnetHost, + m_projectRoot, + cancellationToken + ).ConfigureAwait(false); string requests = Path.Combine(m_projectRoot, "Library", "Scripting", "SdkInputs"); using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync(requests, cancellationToken).ConfigureAwait(false); string project = Path.Combine(owner.directory, "Framework.csproj"); @@ -71,23 +75,44 @@ await File.WriteAllTextAsync(project, """ """, cancellationToken).ConfigureAwait(false); - _ = await RunSdkAsync(sdk, + _ = await RunSdkAsync( + sdk, [sdk.cliPath, "restore", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet"], - owner.directory, cancellationToken).ConfigureAwait(false); - string output = await RunSdkAsync(sdk, - [sdk.cliPath, "msbuild", project, "-nologo", "-m:1", "-nr:false", "-t:CaptureScriptFramework", - "-getItem:ReferencePath", "-getProperty:TargetFramework,LangVersion,DefineConstants,NETCoreSdkVersion"], - owner.directory, cancellationToken).ConfigureAwait(false); + owner.directory, + cancellationToken + ).ConfigureAwait(false); + string output = await RunSdkAsync( + sdk, + [ + sdk.cliPath, + "msbuild", + project, + "-nologo", + "-m:1", + "-nr:false", + "-t:CaptureScriptFramework", + "-getItem:ReferencePath", + "-getProperty:TargetFramework,LangVersion,DefineConstants,NETCoreSdkVersion" + ], + owner.directory, + cancellationToken + ).ConfigureAwait(false); using JsonDocument document = JsonDocument.Parse(output); JsonElement properties = document.RootElement.GetProperty("Properties"); if (properties.GetProperty("TargetFramework").GetString() != "net10.0" || properties.GetProperty("LangVersion").GetString() != "14.0" - || properties.GetProperty("NETCoreSdkVersion").GetString() != sdk.sdkIdentity) + || properties.GetProperty("NETCoreSdkVersion").GetString() != sdk.sdkIdentity + ) { throw new InvalidDataException("SDK scripting evaluation returned an inconsistent framework, language or SDK identity."); - return new ScriptCompilationInputs(sdk.sdkIdentity, - document.RootElement.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray() + } + return new ScriptCompilationInputs( + sdk.sdkIdentity, + document.RootElement.GetProperty("Items") + .GetProperty("ReferencePath") + .EnumerateArray() .Select(static item => item.GetProperty("FullPath").GetString()!), - properties.GetProperty("DefineConstants").GetString()!.Split(';', StringSplitOptions.RemoveEmptyEntries)); + properties.GetProperty("DefineConstants").GetString()!.Split(';', StringSplitOptions.RemoveEmptyEntries) + ); } private static async Task RunSdkAsync( @@ -100,13 +125,23 @@ CancellationToken cancellationToken using var errors = new StringWriter(); try { - await ToolchainEnvironment.RunAsync(sdk.hostPath, arguments, directory, cancellationToken, - DotNetSdkEnvironment.Create(sdk.hostPath), output, errors).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + arguments, + directory, + cancellationToken, + DotNetSdkEnvironment.Create(sdk.hostPath), + output, + errors + ).ConfigureAwait(false); return output.ToString(); } catch (InvalidOperationException failure) { - throw new InvalidOperationException($"Script framework evaluation with SDK '{sdk.sdkIdentity}' failed.\n{output}{errors}", failure); + throw new InvalidOperationException( + $"Script framework evaluation with SDK '{sdk.sdkIdentity}' failed.\n{output}{errors}", + failure + ); } } } diff --git a/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs b/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs index e8efd5822..cd78742dd 100644 --- a/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs +++ b/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs @@ -37,7 +37,8 @@ CancellationToken cancellationToken FileAccess.Read, FileShare.Read, 128 * 1024, - FileOptions.Asynchronous | FileOptions.SequentialScan); + FileOptions.Asynchronous | FileOptions.SequentialScan + ); byte[] fileHash = await SHA256.HashDataAsync(stream, cancellationToken).ConfigureAwait(false); hash.AppendData(fileHash); } @@ -49,12 +50,14 @@ internal static bool MatchesPlugins( IReadOnlyList actual ) { if (expected.Count != actual.Count) + { return false; + } for (int index = 0; index < expected.Count; index++) { if (!string.Equals(expected[index].manifest.pluginId, actual[index].manifest.pluginId, StringComparison.Ordinal) - || !string.Equals(expected[index].contentHash, actual[index].contentHash, StringComparison.Ordinal)) - { + || !string.Equals(expected[index].contentHash, actual[index].contentHash, StringComparison.Ordinal) + ) { return false; } } diff --git a/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs b/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs index 8514cfdf2..370679a3f 100644 --- a/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs +++ b/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs @@ -81,33 +81,47 @@ public static ProductNativeBuildPlan CreateEditor( ) { List steps = CreatePlayerSteps(RequireProfile(profile), options, layout); steps.Add(CreateShaderToolsStep(profile, options, layout)); - steps.Add(new("cimgui", ImGuiToolchain.componentDescriptor, options("cimgui"), [], - static ( - context, - dependencies, - token - ) => ImGuiToolchain.BuildAsync(context, token), - ImGuiToolchain.CreateRecipe, - ( - relative, - target - ) => layout("cimgui", relative, target))); - steps.Add(new("cimguizmo", ImGuizmoToolchain.componentDescriptor, options("cimguizmo"), ["cimgui"], - static ( - context, - dependencies, - token - ) => ImGuizmoToolchain.BuildAsync(context, dependencies["cimgui"], token), - ImGuizmoToolchain.CreateRecipe, - ( - relative, - target - ) => layout("cimguizmo", relative, target), - bindDependencies: static ( - context, - recipe, - dependencies - ) => ImGuizmoToolchain.BindImGui(context, recipe, dependencies["cimgui"]))); + steps.Add( + new( + "cimgui", + ImGuiToolchain.componentDescriptor, + options("cimgui"), + [], + static ( + context, + dependencies, + token + ) => ImGuiToolchain.BuildAsync(context, token), + ImGuiToolchain.CreateRecipe, + ( + relative, + target + ) => layout("cimgui", relative, target) + ) + ); + steps.Add( + new( + "cimguizmo", + ImGuizmoToolchain.componentDescriptor, + options("cimguizmo"), + ["cimgui"], + static ( + context, + dependencies, + token + ) => ImGuizmoToolchain.BuildAsync(context, dependencies["cimgui"], token), + ImGuizmoToolchain.CreateRecipe, + ( + relative, + target + ) => layout("cimguizmo", relative, target), + bindDependencies: static ( + context, + recipe, + dependencies + ) => ImGuizmoToolchain.BindImGui(context, recipe, dependencies["cimgui"]) + ) + ); return new("editor", steps, StandardNativeDeployment.CreateMetadata); } @@ -131,7 +145,9 @@ public static ProductNativeBuildPlan CreateStaticPlayer( ArgumentNullException.ThrowIfNull(layout); List steps = CreatePlayerSteps(null, options, layout); if (steps.Any(static step => step.options.libraryKind != NativeLibraryKind.Static)) + { throw new ArgumentException("Static aggregation requires explicit static component linkage.", nameof(options)); + } return new("player", steps); } @@ -145,26 +161,34 @@ private static ProductNativeBuildStep CreateShaderToolsStep( BgfxNativeBuildProfile profile, Func options, Func layout - ) => new("bgfx-tools", BgfxToolsBuild.componentDescriptor, options("bgfx-tools"), [], - ( - context, - dependencies, - token - ) => BgfxToolsBuild.BuildAsync(context, profile, token), - context => BgfxToolsBuild.CreateRecipe(context, profile), - ( - relative, - target - ) => layout("bgfx-tools", relative, target), - configuration: "release"); + ) => new( + "bgfx-tools", + BgfxToolsBuild.componentDescriptor, + options("bgfx-tools"), + [], + ( + context, + dependencies, + token + ) => BgfxToolsBuild.BuildAsync(context, profile, token), + context => BgfxToolsBuild.CreateRecipe(context, profile), + ( + relative, + target + ) => layout("bgfx-tools", relative, target), + configuration: "release" + ); private static List CreatePlayerSteps( BgfxNativeBuildProfile? profile, Func options, Func layout - ) => - [ - new("bgfx", BgfxNativeBuild.componentDescriptor, options("bgfx"), [], + ) => [ + new( + "bgfx", + BgfxNativeBuild.componentDescriptor, + options("bgfx"), + [], profile is null ? null : ( context, dependencies, @@ -174,8 +198,13 @@ private static List CreatePlayerSteps( ( relative, target - ) => layout("bgfx", relative, target)), - new("sdl3", Sdl3Toolchain.componentDescriptor, options("sdl3"), [], + ) => layout("bgfx", relative, target) + ), + new( + "sdl3", + Sdl3Toolchain.componentDescriptor, + options("sdl3"), + [], profile is null ? null : static ( context, dependencies, @@ -185,8 +214,13 @@ private static List CreatePlayerSteps( ( relative, target - ) => layout("sdl3", relative, target)), - new("miniaudio", MiniAudioToolchain.componentDescriptor, options("miniaudio"), [], + ) => layout("sdl3", relative, target) + ), + new( + "miniaudio", + MiniAudioToolchain.componentDescriptor, + options("miniaudio"), + [], profile is null ? null : static ( context, dependencies, @@ -196,8 +230,13 @@ private static List CreatePlayerSteps( ( relative, target - ) => layout("miniaudio", relative, target)), - new("text", TextToolchain.componentDescriptor, options("text"), [], + ) => layout("miniaudio", relative, target) + ), + new( + "text", + TextToolchain.componentDescriptor, + options("text"), + [], profile is null ? null : static ( context, dependencies, @@ -207,8 +246,13 @@ private static List CreatePlayerSteps( ( relative, target - ) => layout("text", relative, target)), - new("ui", UiToolchain.componentDescriptor, options("ui"), [], + ) => layout("text", relative, target) + ), + new( + "ui", + UiToolchain.componentDescriptor, + options("ui"), + [], profile is null ? null : static ( context, dependencies, @@ -218,7 +262,7 @@ private static List CreatePlayerSteps( ( relative, target - ) => layout("ui", relative, target)) + ) => layout("ui", relative, target) + ) ]; - } diff --git a/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs b/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs index a7353f166..64a25fc81 100644 --- a/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs +++ b/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs @@ -57,8 +57,10 @@ IReadOnlyDictionary payloads Add(files, Path.GetFileNameWithoutExtension(name), portable); NativeBuildProduct product = products.Single(product => product.files.Contains(source, StringComparer.Ordinal)); if (product.artifacts.Single(artifact => artifact.file == source).role != NativeArtifactRole.SharedLibrary - || product.sharedLibraryExtension is not string extension) + || product.sharedLibraryExtension is not string extension + ) { continue; + } string stem = name[..^extension.Length]; AddLibraryAliases(libraries, stem, portable); } @@ -72,7 +74,9 @@ private static void Add( string path ) { if (mapping.TryGetValue(alias, out string? prior) && prior != path) + { throw new InvalidDataException($"Native deployment alias '{alias}' has multiple selected payloads."); + } mapping[alias] = path; } @@ -83,7 +87,9 @@ string path ) { Add(libraries, stem, path); if (stem.StartsWith("lib", StringComparison.Ordinal) && stem.Length > 3) + { Add(libraries, stem[3..], path); + } } private sealed class DeploymentValidator( @@ -95,20 +101,33 @@ string extension public void Validate(string directory) { string root = PathBoundary.Resolve(directory, "native"); - NativeDeploymentIndex index = NativeDeploymentIndex.Decode(File.ReadAllBytes(Path.Combine(root, NativeDeploymentIndex.C_FILE_NAME))); + NativeDeploymentIndex index = NativeDeploymentIndex.Decode( + File.ReadAllBytes(Path.Combine(root, NativeDeploymentIndex.C_FILE_NAME)) + ); if (index.targetId != target.value) + { throw new InvalidDataException("The selected Native deployment metadata has a foreign target."); - var actual = new HashSet(PathBoundary.EnumerateFiles(root) - .Where(path => Path.GetFileName(path) != NativeDeploymentIndex.C_FILE_NAME) - .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')), StringComparer.Ordinal); + } + var actual = new HashSet( + PathBoundary.EnumerateFiles(root) + .Where(path => Path.GetFileName(path) != NativeDeploymentIndex.C_FILE_NAME) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')), + StringComparer.Ordinal + ); if (!actual.SetEquals(index.files.Values) || index.libraries.Values.Any(path => !actual.Contains(path))) + { throw new InvalidDataException("Native deployment metadata does not describe the complete selected payload."); + } var expectedLibraries = new Dictionary(StringComparer.Ordinal); foreach (string path in actual.Where(path => path.EndsWith(extension, StringComparison.Ordinal))) + { AddLibraryAliases(expectedLibraries, Path.GetFileName(path)[..^extension.Length], path); + } if (index.libraries.Count != expectedLibraries.Count - || expectedLibraries.Any(pair => !index.libraries.TryGetValue(pair.Key, out string? path) || path != pair.Value)) + || expectedLibraries.Any(pair => !index.libraries.TryGetValue(pair.Key, out string? path) || path != pair.Value) + ) { throw new InvalidDataException("Native deployment metadata does not expose the selected library aliases."); + } } } } diff --git a/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs b/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs index ef4a1f85a..753efa160 100644 --- a/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs +++ b/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs @@ -32,10 +32,15 @@ public static PlayerSupportPackRequirements CreateDynamic( BuildTargetId target, string extension ) { - string[] groups = plan.steps.Select(step => step.deploymentPath("selected" + extension, target.value) - ?? throw new InvalidOperationException("A Player component has no runtime deployment policy.")) - .Select(path => Path.GetDirectoryName(path)?.Replace('\\', '/') - ?? throw new InvalidOperationException("A Player component must declare an owned deployment group.")) + string[] groups = plan.steps + .Select(step => ( + step.deploymentPath("selected" + extension, target.value) + ?? throw new InvalidOperationException("A Player component has no runtime deployment policy.") + )) + .Select(path => ( + Path.GetDirectoryName(path)?.Replace('\\', '/') + ?? throw new InvalidOperationException("A Player component must declare an owned deployment group.") + )) .ToArray(); return new(target, ManagedFiles(plan), "native", groups, extension); } @@ -60,12 +65,19 @@ public static PlayerSupportPackRequirements CreateStatic( BuildTargetId target, NativeLinkPlan linkPlan ) { - string[] archives = plan.steps.SelectMany(step => step.component.staticBuild?.logicalOutputs - .Select(name => "PlayerLink/Native/" + step.id + "/" + target.value + "/" + linkPlan.GetStaticFileName(name)) - ?? throw new InvalidOperationException("A static Player component has no declared archive closure.")).ToArray(); - return new(target, [.. ManagedFiles(plan), .. archives], "PlayerLink/Native", - plan.steps.Select(step => step.id + "/" + target.value).ToArray(), linkPlan.staticLibraryExtension!, - archives.Select(path => path["PlayerLink/Native/".Length..]).ToArray()); + string[] archives = plan.steps.SelectMany(step => ( + step.component.staticBuild?.logicalOutputs + .Select(name => "PlayerLink/Native/" + step.id + "/" + target.value + "/" + linkPlan.GetStaticFileName(name)) + ?? throw new InvalidOperationException("A static Player component has no declared archive closure.") + )).ToArray(); + return new( + target, + [.. ManagedFiles(plan), .. archives], + "PlayerLink/Native", + plan.steps.Select(step => step.id + "/" + target.value).ToArray(), + linkPlan.staticLibraryExtension!, + archives.Select(path => path["PlayerLink/Native/".Length..]).ToArray() + ); } private static string[] ManagedFiles(ProductNativeBuildPlan plan) @@ -74,5 +86,7 @@ private static string[] ManagedFiles(ProductNativeBuildPlan plan) { "References/" + Path.GetFileNameWithoutExtension(step.component.nativeProject) + ".dll", "PlayerLink/References/" + Path.GetFileNameWithoutExtension(step.component.nativeProject) + ".dll" - }).Append("PlayerLink/References/BGCS.Runtime.dll").ToArray(); + }) + .Append("PlayerLink/References/BGCS.Runtime.dll") + .ToArray(); } diff --git a/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs b/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs index 5d1ffe502..d268aba01 100644 --- a/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs +++ b/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs @@ -144,26 +144,50 @@ CancellationToken cancellationToken string project = Inno.Core.IO.PathBoundary.Resolve(context.engineRoot, m_productProject); string template = Inno.Core.IO.PathBoundary.Resolve(context.engineRoot, m_templateFile); if (!File.Exists(template)) + { throw new FileNotFoundException("The Player publication template is absent.", template); + } var native = new NativeBuildContext(context.engineRoot, ToolchainLayout.C_RELEASE_CONFIGURATION) .WithBindingGenerator(m_bindingGenerator); if (context.nativeDependencies is null) - native = native.WithToolchain(await m_toolchainProvider.ResolveAsync( - native, m_host, m_nativePlatform, cancellationToken).ConfigureAwait(false)); + { + native = native.WithToolchain( + await m_toolchainProvider.ResolveAsync( + native, + m_host, + m_nativePlatform, + cancellationToken + ).ConfigureAwait(false) + ); + } DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync( - context.dotnetHost, project, cancellationToken).ConfigureAwait(false); + context.dotnetHost, + project, + cancellationToken + ).ConfigureAwait(false); var properties = new Dictionary { - ["Configuration"] = "Release", ["RuntimeIdentifier"] = m_runtimeIdentifier, - ["DebugType"] = "None", ["DebugSymbols"] = "false", + ["Configuration"] = "Release", + ["RuntimeIdentifier"] = m_runtimeIdentifier, + ["DebugType"] = "None", + ["DebugSymbols"] = "false", ["InnoShaderToolSourceRoot"] = context.engineRoot, - ["InnoNativeTarget"] = m_target.value, ["InnoPrepareProductNative"] = "false" + ["InnoNativeTarget"] = m_target.value, + ["InnoPrepareProductNative"] = "false" }; if (context.nativeDependencies is not null) + { properties["InnoNativeDependencyManifest"] = context.nativeDependencies; + } PlayerSupportPackPreparationIdentity identity = await PlayerSupportPackPreparationIdentity.CaptureAsync( - native, m_nativePlan, sdk, project, properties, - m_preparationInputs.Append(template).ToArray(), cancellationToken).ConfigureAwait(false); + native, + m_nativePlan, + sdk, + project, + properties, + m_preparationInputs.Append(template).ToArray(), + cancellationToken + ).ConfigureAwait(false); return new PreparationPlan(this, context.engineRoot, project, sdk, native, identity); } @@ -175,52 +199,107 @@ private async ValueTask ExecuteAsync( CancellationToken cancellationToken ) { using ProductNativeBuildResult products = identity.nativeDependencies is string manifest - ? await NativeDependencyManifest.AcquireAsync(native.engineRoot, manifest, m_target.value, - native.configuration, m_nativePlan, cancellationToken).ConfigureAwait(false) + ? await NativeDependencyManifest.AcquireAsync( + native.engineRoot, + manifest, + m_target.value, + native.configuration, + m_nativePlan, + cancellationToken + ).ConfigureAwait(false) : await m_nativeExecutor.BuildAsync(native, m_nativePlan, cancellationToken).ConfigureAwait(false); using ManagedBuildExecution execution = await identity.CreateExecutionAsync(cancellationToken).ConfigureAwait(false); context = new PlayerSupportPackBuildContext(execution.engineRoot, context.stagingDirectory, context.sdk); project = execution.project; string bindingSelection = Path.Combine(Path.GetDirectoryName(execution.project)!, "obj", "support-pack", "BindingSelection.props"); - NativeBindingGenerationDescriptor.WriteSelection(bindingSelection, - m_nativePlan.steps.Select(( - step, - index - ) => (step, product: products[index])) + NativeBindingGenerationDescriptor.WriteSelection( + bindingSelection, + m_nativePlan.steps + .Select(( + step, + index + ) => (step, product: products[index])) .Where(static pair => pair.product.bindingGeneration is not null) - .ToDictionary(static pair => pair.step.component.nativeProject, - static pair => pair.product.bindingGeneration!, StringComparer.Ordinal), - m_nativePlan.steps.Where(( - step, - index - ) => products[index].bindingGeneration is not null) - .ToDictionary(static step => step.component.nativeProject, static step => step.options.libraryKind, StringComparer.Ordinal)); - await ToolchainEnvironment.RunAsync(context.sdk.hostPath, - [context.sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--configuration", "Release", - "--runtime", m_runtimeIdentifier, "--nologo", "-p:DebugType=None", "-p:DebugSymbols=false", - "-p:InnoNativeTarget=" + m_target.value, "-p:InnoPrepareProductNative=false", + .ToDictionary( + static pair => pair.step.component.nativeProject, + static pair => pair.product.bindingGeneration!, + StringComparer.Ordinal + ), + m_nativePlan.steps + .Where(( + step, + index + ) => products[index].bindingGeneration is not null) + .ToDictionary(static step => step.component.nativeProject, static step => step.options.libraryKind, StringComparer.Ordinal) + ); + await ToolchainEnvironment.RunAsync( + context.sdk.hostPath, + [ + context.sdk.cliPath, + "build", + project, + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--configuration", + "Release", + "--runtime", + m_runtimeIdentifier, + "--nologo", + "-p:DebugType=None", + "-p:DebugSymbols=false", + "-p:InnoNativeTarget=" + m_target.value, + "-p:InnoPrepareProductNative=false", "-p:InnoShaderToolSourceRoot=" + native.engineRoot, "-p:InnoNativeBindingSelection=" + bindingSelection, - ..(identity.nativeDependencies is string selection ? new[] { "-p:InnoNativeDependencyManifest=" + selection } : Array.Empty())], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(context.sdk.hostPath)).ConfigureAwait(false); - string buildOutput = (await ToolchainEnvironment.CaptureOutputAsync(context.sdk.hostPath, - [context.sdk.cliPath, "msbuild", project, "-getProperty:TargetDir", "-p:Configuration=Release", "-p:RuntimeIdentifier=" + m_runtimeIdentifier, - "-p:InnoNativeTarget=" + m_target.value, "-p:DesignTimeBuild=true", "-nologo"], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(context.sdk.hostPath)).ConfigureAwait(false)).Trim(); + ..(identity.nativeDependencies is string selection + ? new[] { "-p:InnoNativeDependencyManifest=" + selection } + : Array.Empty()) + ], + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(context.sdk.hostPath) + ).ConfigureAwait(false); + string buildOutput = (await ToolchainEnvironment.CaptureOutputAsync( + context.sdk.hostPath, + [ + context.sdk.cliPath, + "msbuild", + project, + "-getProperty:TargetDir", + "-p:Configuration=Release", + "-p:RuntimeIdentifier=" + + m_runtimeIdentifier, + "-p:InnoNativeTarget=" + m_target.value, + "-p:DesignTimeBuild=true", + "-nologo" + ], + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(context.sdk.hostPath) + ).ConfigureAwait(false)).Trim(); PlayerSupportPackFiles.CopyReferences( buildOutput, - Path.Combine(context.stagingDirectory, "References"), Path.GetFileNameWithoutExtension(project)); + Path.Combine(context.stagingDirectory, "References"), + Path.GetFileNameWithoutExtension(project) + ); await CopyNativeRuntimeAsync(products, context.stagingDirectory, cancellationToken).ConfigureAwait(false); string link = Path.Combine(context.stagingDirectory, "PlayerLink"); Directory.CreateDirectory(link); File.Copy(Inno.Core.IO.PathBoundary.Resolve(context.engineRoot, m_templateFile), Path.Combine(link, "Player.csproj")); await PlayerSupportPackFiles.CopyPlayerSourcesAsync( - context, project, link, cancellationToken).ConfigureAwait(false); + context, + project, + link, + cancellationToken + ).ConfigureAwait(false); PlayerSupportPackFiles.CopyCompositionInputs(context.engineRoot, link); string references = Path.Combine(link, "References"); Directory.CreateDirectory(references); foreach (string reference in Directory.EnumerateFiles(Path.Combine(context.stagingDirectory, "References"), "*.dll")) + { File.Copy(reference, Path.Combine(references, Path.GetFileName(reference))); + } await CopyNativeToTemplateAsync(context.stagingDirectory, link, cancellationToken).ConfigureAwait(false); await execution.VerifyAsync(cancellationToken).ConfigureAwait(false); } @@ -241,11 +320,16 @@ CancellationToken cancellationToken foreach (NativeBuildProduct product in products) { if (product.targetId != m_nativePlatform) - throw new InvalidDataException($"Native product '{product.component}' targets '{product.targetId}', not '{m_nativePlatform}'."); + { + throw new InvalidDataException( + $"Native product '{product.component}' targets '{product.targetId}', not '{m_nativePlatform}'." + ); + } if (!product.files.Any(file => string.Equals(Path.GetExtension(file), m_nativeExtension, StringComparison.OrdinalIgnoreCase))) { throw new InvalidDataException( - $"Native runtime product '{product.component}' and '{m_target}' is empty."); + $"Native runtime product '{product.component}' and '{m_target}' is empty." + ); } } await ProductNativeDeployment.StageAsync(products, m_nativePlan, staging, cancellationToken).ConfigureAwait(false); @@ -266,9 +350,12 @@ CancellationToken cancellationToken await using FileStream output = new(destination, FileMode.CreateNew); await source.CopyToAsync(output, cancellationToken).ConfigureAwait(false); if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(destination, File.GetUnixFileMode(input)); + } } } + private sealed class PreparationPlan( FilePlayerSupportPackPreparation owner, string engineRoot, @@ -276,7 +363,8 @@ private sealed class PreparationPlan( DotNetSdkDescriptor sdk, NativeBuildContext native, PlayerSupportPackPreparationIdentity identity - ) : PlayerSupportPackPlan(owner.target, identity.fingerprint) { + ) : PlayerSupportPackPlan(owner.target, identity.fingerprint) + { /// public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => identity.VerifyAsync(cancellationToken); @@ -284,8 +372,12 @@ PlayerSupportPackPreparationIdentity identity public override ValueTask PrepareAsync( string stagingDirectory, CancellationToken cancellationToken - ) => owner.ExecuteAsync(new PlayerSupportPackBuildContext(engineRoot, stagingDirectory, sdk), - project, native, identity, cancellationToken); + ) => owner.ExecuteAsync( + new PlayerSupportPackBuildContext(engineRoot, stagingDirectory, sdk), + project, + native, + identity, + cancellationToken + ); } - } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackClosureValidator.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackClosureValidator.cs index 4136bba22..38668d171 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackClosureValidator.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackClosureValidator.cs @@ -56,22 +56,37 @@ public void Validate(string directory) ArgumentException.ThrowIfNullOrWhiteSpace(directory); m_platform.Validate(directory); foreach (string relative in m_requirements.requiredFiles) + { if (!File.Exists(PathBoundary.Resolve(directory, relative))) + { throw new InvalidDataException($"Support Pack '{m_requirements.target}' lacks selected input '{relative}'."); + } + } string root = PathBoundary.Resolve(directory, m_requirements.nativeRoot); if (!Directory.Exists(root)) + { throw new InvalidDataException($"Support Pack '{m_requirements.target}' has no selected native deployment."); + } string[] libraries = PathBoundary.EnumerateFiles(root) .Where(path => Path.GetExtension(path).Equals(m_requirements.nativeExtension, StringComparison.OrdinalIgnoreCase)) - .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')).ToArray(); + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .ToArray(); foreach (string group in m_requirements.nativeDirectories) + { if (!libraries.Any(path => path.StartsWith(group + "/", StringComparison.Ordinal))) + { throw new InvalidDataException($"Support Pack '{m_requirements.target}' lacks native component group '{group}'."); + } + } if (libraries.Any(path => !m_requirements.nativeDirectories.Any(group => path.StartsWith(group + "/", StringComparison.Ordinal)))) + { throw new InvalidDataException($"Support Pack '{m_requirements.target}' contains an undeclared native component group."); + } if (m_requirements.nativeFiles is { } selected - && !libraries.ToHashSet(StringComparer.Ordinal).SetEquals(selected)) + && !libraries.ToHashSet(StringComparer.Ordinal).SetEquals(selected) + ) { throw new InvalidDataException($"Support Pack '{m_requirements.target}' does not match its selected native file closure."); + } m_deployment?.Validate(directory); } } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackFiles.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackFiles.cs index 43c4b8c70..584b9ab2f 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackFiles.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackFiles.cs @@ -49,30 +49,48 @@ public static async Task CopyPlayerSourcesAsync( ) { string evaluated = await ToolchainEnvironment.CaptureOutputAsync( context.sdk.hostPath, - [context.sdk.cliPath, "msbuild", project, "-getItem:Compile", "-p:Configuration=Release", - "-p:DesignTimeBuild=true", "-nodeReuse:false", "-nologo"], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(context.sdk.hostPath, environment)).ConfigureAwait(false); + [ + context.sdk.cliPath, + "msbuild", + project, + "-getItem:Compile", + "-p:Configuration=Release", + "-p:DesignTimeBuild=true", + "-nodeReuse:false", + "-nologo" + ], + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(context.sdk.hostPath, environment) + ).ConfigureAwait(false); using JsonDocument document = JsonDocument.Parse(evaluated); JsonElement sources = document.RootElement.GetProperty("Items").GetProperty("Compile"); string projectDirectory = Path.GetDirectoryName(project)!; var outputs = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (JsonElement source in sources.EnumerateArray() - .OrderBy(static source => source.GetProperty("Identity").GetString(), StringComparer.Ordinal)) - { + .OrderBy(static source => source.GetProperty("Identity").GetString(), StringComparer.Ordinal) + ) { cancellationToken.ThrowIfCancellationRequested(); string input = PathBoundary.RequireUnlinkedPath( - context.engineRoot, source.GetProperty("FullPath").GetString()!); + context.engineRoot, + source.GetProperty("FullPath").GetString()! + ); string relative = source.TryGetProperty("Link", out JsonElement link) - && !string.IsNullOrWhiteSpace(link.GetString()) - ? link.GetString()! : Path.GetRelativePath(projectDirectory, input); + && !string.IsNullOrWhiteSpace(link.GetString()) + ? link.GetString()! + : Path.GetRelativePath(projectDirectory, input); string output = PathBoundary.Resolve(destination, relative); if (!outputs.Add(relative.Replace('\\', '/'))) + { throw new InvalidDataException($"Player sources repeat publication path '{relative}'."); + } Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.Copy(input, output); } if (outputs.Count == 0) + { throw new InvalidDataException("The Player project declares no publication sources."); + } } /// @@ -93,15 +111,40 @@ string playerDirectory ) { string analyzerDirectory = Path.Combine(playerDirectory, "Analyzers"); Directory.CreateDirectory(analyzerDirectory); - string analyzer = Path.Combine(engineRoot, "src", "runtime", "generators", - "Inno.Runtime.Generators", "bin", "Release", "netstandard2.0", "Inno.Runtime.Generators.dll"); + string analyzer = Path.Combine( + engineRoot, + "src", + "runtime", + "generators", + "Inno.Runtime.Generators", + "bin", + "Release", + "netstandard2.0", + "Inno.Runtime.Generators.dll" + ); if (!File.Exists(analyzer)) + { throw new FileNotFoundException("The runtime registration generator is absent from the prepared build.", analyzer); + } File.Copy(analyzer, Path.Combine(analyzerDirectory, Path.GetFileName(analyzer))); - string serializationAnalyzer = Path.Combine(engineRoot, "src", "foundation", "core", - "Inno.Core.Serialization.Generators", "bin", "Release", "netstandard2.0", "Inno.Core.Serialization.Generators.dll"); + string serializationAnalyzer = Path.Combine( + engineRoot, + "src", + "foundation", + "core", + "Inno.Core.Serialization.Generators", + "bin", + "Release", + "netstandard2.0", + "Inno.Core.Serialization.Generators.dll" + ); if (!File.Exists(serializationAnalyzer)) - throw new FileNotFoundException("The serialization metadata generator is absent from the prepared build.", serializationAnalyzer); + { + throw new FileNotFoundException( + "The serialization metadata generator is absent from the prepared build.", + serializationAnalyzer + ); + } File.Copy(serializationAnalyzer, Path.Combine(analyzerDirectory, Path.GetFileName(serializationAnalyzer))); string sdkSelection = Path.Combine(engineRoot, "global.json"); File.Copy(sdkSelection, Path.Combine(playerDirectory, "global.json")); @@ -129,26 +172,39 @@ string productAssemblyName ) { string dependencyFile = Path.Combine(buildOutput, productAssemblyName + ".deps.json"); if (!File.Exists(dependencyFile)) + { throw new InvalidDataException("Player build has no SDK-selected runtime dependency closure."); + } using JsonDocument dependencies = JsonDocument.Parse(File.ReadAllBytes(dependencyFile)); JsonElement root = dependencies.RootElement; string target = root.GetProperty("runtimeTarget").GetProperty("name").GetString() - ?? throw new InvalidDataException("Player dependencies have no explicit runtime target."); - string[] files = root.GetProperty("targets").GetProperty(target).EnumerateObject() + ?? throw new InvalidDataException("Player dependencies have no explicit runtime target."); + string[] files = root.GetProperty("targets") + .GetProperty(target) + .EnumerateObject() .Where(static dependency => dependency.Value.TryGetProperty("runtime", out _)) - .SelectMany(static dependency => dependency.Value.GetProperty("runtime").EnumerateObject() + .SelectMany(static dependency => dependency.Value.GetProperty("runtime") + .EnumerateObject() .Select(static asset => Path.GetFileName(asset.Name))) - .Where(name => name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) - && Path.GetFileNameWithoutExtension(name) != productAssemblyName) - .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal) - .Select(name => PathBoundary.Resolve(buildOutput, name)).ToArray(); + .Where(name => ( + name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + && Path.GetFileNameWithoutExtension(name) != productAssemblyName + )) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .Select(name => PathBoundary.Resolve(buildOutput, name)) + .ToArray(); if (files.Length == 0) + { throw new InvalidDataException("Player build produced no target compilation references."); + } Directory.CreateDirectory(destination); foreach (string file in files) { if (!File.Exists(file)) + { throw new InvalidDataException($"Selected Player dependency '{Path.GetFileName(file)}' was not deployed by the SDK."); + } File.Copy(file, Path.Combine(destination, Path.GetFileName(file))); } } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs index 1d4f85007..9ecb50f5c 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs @@ -28,8 +28,10 @@ string preparationIdentity ) { ArgumentException.ThrowIfNullOrWhiteSpace(target.value); if (preparationIdentity is null || preparationIdentity.Length != 64 - || System.Linq.Enumerable.Any(preparationIdentity, static character => !char.IsAsciiHexDigitLower(character))) + || System.Linq.Enumerable.Any(preparationIdentity, static character => !char.IsAsciiHexDigitLower(character)) + ) { throw new ArgumentException("A Support Pack requires a complete lowercase source input identity.", nameof(preparationIdentity)); + } this.target = target; this.preparationIdentity = preparationIdentity; } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs index 520f822db..ca65b01ff 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs @@ -99,9 +99,16 @@ public static async ValueTask CaptureAsync ArgumentNullException.ThrowIfNull(preparationInputs); ArgumentException.ThrowIfNullOrWhiteSpace(project); var frozen = new System.Collections.ObjectModel.ReadOnlyDictionary( - properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase)); - var result = new PlayerSupportPackPreparationIdentity(context, nativePlan, sdk, project, frozen, - Array.AsReadOnly(preparationInputs.ToArray())); + properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase) + ); + var result = new PlayerSupportPackPreparationIdentity( + context, + nativePlan, + sdk, + project, + frozen, + Array.AsReadOnly(preparationInputs.ToArray()) + ); result.fingerprint = await result.ComputeAsync(context, cancellationToken).ConfigureAwait(false); return result; } @@ -116,7 +123,8 @@ public static async ValueTask CaptureAsync /// Caller-owned input copies for compilation and source extraction. /// public ValueTask CreateExecutionAsync(CancellationToken cancellationToken = default) - => (m_managed ?? throw new InvalidOperationException("Managed preparation was not captured.")).CreateExecutionAsync(cancellationToken); + => (m_managed + ?? throw new InvalidOperationException("Managed preparation was not captured.")).CreateExecutionAsync(cancellationToken); /// /// Freshly verifies the complete current source input closure after waiting or preparing output. @@ -135,9 +143,14 @@ public ValueTask CreateExecutionAsync(CancellationToken c /// public async ValueTask VerifyAsync(CancellationToken cancellationToken = default) { - string current = await ComputeAsync(m_context.BeginInputVerification("support-pack-inputs"), cancellationToken).ConfigureAwait(false); + string current = await ComputeAsync( + m_context.BeginInputVerification("support-pack-inputs"), + cancellationToken + ).ConfigureAwait(false); if (current != fingerprint) + { throw new InvalidOperationException("Support Pack inputs changed after planning; the candidate cannot be selected."); + } } private async ValueTask ComputeAsync( @@ -148,37 +161,75 @@ CancellationToken cancellation var declarations = new List { "support-pack-preparation", m_nativePlan.productId }; if (m_properties.TryGetValue("InnoNativeDependencyManifest", out string? manifest)) { - IReadOnlyList assets = await NativeDependencyManifest.SelectAsync(context.engineRoot, - manifest, m_properties["InnoNativeTarget"], context.configuration, m_nativePlan, cancellation).ConfigureAwait(false); - declarations.AddRange(assets.OrderBy(static asset => asset.asset, StringComparer.Ordinal) - .Select(static asset => asset.asset + "=" + asset.sha256)); + IReadOnlyList assets = await NativeDependencyManifest.SelectAsync( + context.engineRoot, + manifest, + m_properties["InnoNativeTarget"], + context.configuration, + m_nativePlan, + cancellation + ).ConfigureAwait(false); + declarations.AddRange( + assets.OrderBy(static asset => asset.asset, StringComparer.Ordinal) + .Select(static asset => asset.asset + "=" + asset.sha256) + ); } else { IReadOnlyList recipes = m_nativePlan.CreateRecipes(context); declarations.Add(context.RequireToolchain().targetId); foreach (NativeBuildRecipe recipe in recipes) - declarations.Add(recipe.component + "=" + NativeBuildFingerprint.Create(context, recipe.declarations, recipe.inputs, cancellation)); + { + declarations.Add( + recipe.component + "=" + NativeBuildFingerprint.Create(context, recipe.declarations, recipe.inputs, cancellation) + ); + } NativeComponentDescriptor[] generated = m_nativePlan.steps.Select(static step => step.component) - .Where(static component => component.bindingDefinition is not null).DistinctBy(static component => component.nativeProject).ToArray(); + .Where(static component => component.bindingDefinition is not null) + .DistinctBy(static component => component.nativeProject) + .ToArray(); if (generated.Length > 0) - declarations.Add("bindings=" + await context.RequireBindingGenerator().ComputeInputFingerprintAsync(context, - new NativeBindingGenerationRequest(generated, context.RequireToolchain().targetId, NativeBindingOutputMode.TargetArtifacts, - componentOptions: m_nativePlan.steps.Where(static step => step.component.bindingDefinition is not null) - .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal)), - cancellation).ConfigureAwait(false)); + { + declarations.Add( + "bindings=" + await context.RequireBindingGenerator().ComputeInputFingerprintAsync( + context, + new NativeBindingGenerationRequest( + generated, + context.RequireToolchain().targetId, + NativeBindingOutputMode.TargetArtifacts, + componentOptions: m_nativePlan.steps.Where(static step => step.component.bindingDefinition is not null) + .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) + .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal) + ), + cancellation + ).ConfigureAwait(false) + ); + } } - ManagedBuildInputSnapshot managed = await ManagedBuildInputSnapshot.CaptureAsync(context, m_sdk, m_project, - m_properties, cancellation).ConfigureAwait(false); + ManagedBuildInputSnapshot managed = await ManagedBuildInputSnapshot.CaptureAsync( + context, + m_sdk, + m_project, + m_properties, + cancellation + ).ConfigureAwait(false); m_managed ??= managed; declarations.Add("managed=" + managed.fingerprint); string root = Path.Combine(context.engineRoot, "build", "support", "Inno.Build.SupportPacks.Core"); - IEnumerable inputs = m_inputs.Concat(new[] { "FilePlayerSupportPackPreparation.cs", "PlayerSupportPackFiles.cs", - "PlayerSupportPackPreparationIdentity.cs", "PlayerSupportPackPublisher.cs", "PlayerSupportPackPreparationIndex.cs", - "PlayerSupportPackPlan.cs", "Inno.Build.SupportPacks.Core.csproj" }.Select(file => Path.Combine(root, file))) - .Append(Path.Combine(context.engineRoot, "build", "toolchains", "Inno.Build.Toolchains", "Native", "ProductNativeDeployment.cs")); - return NativeBuildFingerprint.Create(context, declarations, - inputs.Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), cancellation); + IEnumerable inputs = m_inputs + .Concat( + new[] { "FilePlayerSupportPackPreparation.cs", "PlayerSupportPackFiles.cs", + "PlayerSupportPackPreparationIdentity.cs", "PlayerSupportPackPublisher.cs", "PlayerSupportPackPreparationIndex.cs", + "PlayerSupportPackPlan.cs", "Inno.Build.SupportPacks.Core.csproj" }.Select(file => Path.Combine(root, file)) + ) + .Append( + Path.Combine(context.engineRoot, "build", "toolchains", "Inno.Build.Toolchains", "Native", "ProductNativeDeployment.cs") + ); + return NativeBuildFingerprint.Create( + context, + declarations, + inputs.Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), + cancellation + ); } } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs index adfe73d98..de7760094 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs @@ -15,7 +15,9 @@ string preparation ) { string path = GetPath(root, target, preparation); if (!File.Exists(path)) + { return null; + } string fingerprint = File.ReadAllText(path); return IsIdentity(fingerprint) ? fingerprint : null; } @@ -27,12 +29,16 @@ internal static void Write( string content ) { if (!IsIdentity(content)) + { throw new InvalidDataException("A prepared Pack index requires a complete content identity."); + } string path = GetPath(root, target, preparation); Directory.CreateDirectory(Path.GetDirectoryName(path)!); PathBoundary.RequireUnlinkedPath(root, path); if (!File.Exists(path) || File.ReadAllText(path) != content) + { AtomicFile.WriteAllBytes(path, Encoding.UTF8.GetBytes(content)); + } new BuildCachePublisher(Path.GetFullPath(root), BuildCacheArtifactRole.ImmutableArtifact) .RecordIndex(path, [PathBoundary.Resolve(root, target + "/" + content)]); } @@ -43,10 +49,13 @@ private static string GetPath( string preparation ) { if (!IsIdentity(preparation)) + { throw new InvalidDataException("A prepared Pack index requires a complete source identity."); + } return PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, target + "/.preparations/" + preparation)); } - private static bool IsIdentity(string identity) => identity.Length == 64 - && !System.Linq.Enumerable.Any(identity, static character => !char.IsAsciiHexDigitLower(character)); + private static bool IsIdentity(string identity) + => identity.Length == 64 + && !System.Linq.Enumerable.Any(identity, static character => !char.IsAsciiHexDigitLower(character)); } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs index 56f91e45e..73ba18210 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs @@ -32,8 +32,10 @@ public PlayerSupportPackPublisher(IEnumerable sources) foreach (IPlayerSupportPackSource source in sources) { if (source is null || string.IsNullOrWhiteSpace(source.target.value) - || !registered.TryAdd(source.target, source)) + || !registered.TryAdd(source.target, source) + ) { throw new ArgumentException("Support Pack sources must be non-null and have unique target identities.", nameof(sources)); + } } m_sources = registered; } @@ -93,22 +95,30 @@ public async ValueTask PublishAsync( ArgumentException.ThrowIfNullOrWhiteSpace(outputRoot); ArgumentException.ThrowIfNullOrWhiteSpace(dotnetHost); if (!m_sources.TryGetValue(target, out IPlayerSupportPackSource? source)) + { throw new ArgumentException($"No Support Pack source is registered for '{target}'.", nameof(target)); + } string root = Path.GetFullPath(engineRoot); if (!File.Exists(Path.Combine(root, "InnoEngine.sln"))) + { throw new DirectoryNotFoundException($"Engine root '{root}' has no InnoEngine.sln."); + } cancellationToken.ThrowIfCancellationRequested(); PlayerSupportPackPlan plan = await source.CreatePlanAsync( - new PlayerSupportPackPlanningContext(root, dotnetHost, nativeDependencies), cancellationToken).ConfigureAwait(false); + new PlayerSupportPackPlanningContext(root, dotnetHost, nativeDependencies), + cancellationToken + ).ConfigureAwait(false); if (plan is null || plan.target != target) + { throw new InvalidDataException("The Support Pack plan does not match its registered target."); + } cancellationToken.ThrowIfCancellationRequested(); var cache = new BuildCachePublisher(Path.GetFullPath(outputRoot), BuildCacheArtifactRole.ImmutableArtifact); using FileLease cacheUse = await cache.AcquireUseAsync(cancellationToken).ConfigureAwait(false); string output = Path.GetFullPath(outputRoot); Directory.CreateDirectory(output); - using FileLease ownership = await FileLease.AcquireAsync( - Path.Combine(output, target.value + ".lock"), Timeout.InfiniteTimeSpan, cancellationToken) + using FileLease ownership = await FileLease + .AcquireAsync(Path.Combine(output, target.value + ".lock"), Timeout.InfiniteTimeSpan, cancellationToken) .ConfigureAwait(false); var catalog = new PlayerSupportPackCatalog(output); string? prepared = PlayerSupportPackPreparationIndex.Read(output, target.value, plan.preparationIdentity); @@ -116,8 +126,13 @@ public async ValueTask PublishAsync( { try { - PlayerSupportPackLease selected = await catalog.SelectAsync(target, prepared, source, - plan.VerifyInputsAsync, cancellationToken).ConfigureAwait(false); + PlayerSupportPackLease selected = await catalog.SelectAsync( + target, + prepared, + source, + plan.VerifyInputsAsync, + cancellationToken + ).ConfigureAwait(false); return Complete(selected, []); } catch (InvalidDataException) @@ -140,12 +155,21 @@ public async ValueTask PublishAsync( await plan.PrepareAsync(staging, cancellationToken) .ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); - published = await catalog.PublishAsync(target, staging, source, cancellationToken, - plan.VerifyInputsAsync).ConfigureAwait(false); + published = await catalog.PublishAsync( + target, + staging, + source, + cancellationToken, + plan.VerifyInputsAsync + ).ConfigureAwait(false); try { - PlayerSupportPackPreparationIndex.Write(output, target.value, plan.preparationIdentity, - Path.GetFileName(published.directory)); + PlayerSupportPackPreparationIndex.Write( + output, + target.value, + plan.preparationIdentity, + Path.GetFileName(published.directory) + ); } catch (Exception failure) when (failure is IOException or UnauthorizedAccessException) { diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackRequirements.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackRequirements.cs index 3c15bc474..0036a5bdb 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackRequirements.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackRequirements.cs @@ -49,19 +49,33 @@ public PlayerSupportPackRequirements( ArgumentNullException.ThrowIfNull(nativeDirectories); ArgumentException.ThrowIfNullOrWhiteSpace(nativeExtension); if (!nativeExtension.StartsWith(".", StringComparison.Ordinal) || nativeExtension.Contains('/') || nativeExtension.Contains('\\')) + { throw new ArgumentException("A selected native suffix must be one file extension.", nameof(nativeExtension)); + } ValidatePath(nativeRoot); foreach (string path in requiredFiles.Concat(nativeDirectories)) + { ValidatePath(path); + } foreach (string path in nativeFiles ?? []) + { ValidatePath(path); + } if (requiredFiles.Distinct(StringComparer.Ordinal).Count() != requiredFiles.Count || nativeDirectories.Distinct(StringComparer.Ordinal).Count() != nativeDirectories.Count - || nativeFiles is not null && nativeFiles.Distinct(StringComparer.Ordinal).Count() != nativeFiles.Count) + || nativeFiles is not null && nativeFiles.Distinct(StringComparer.Ordinal).Count() != nativeFiles.Count + ) { throw new ArgumentException("Selected publication inputs cannot repeat ownership paths."); - if (nativeFiles is not null && nativeFiles.Any(path => !path.EndsWith(nativeExtension, StringComparison.Ordinal) - || !nativeDirectories.Any(group => path.StartsWith(group + "/", StringComparison.Ordinal)))) - throw new ArgumentException("Exact selected libraries must belong to their declared native groups and suffix.", nameof(nativeFiles)); + } + if (nativeFiles is not null && nativeFiles.Any(path => ( + !path.EndsWith(nativeExtension, StringComparison.Ordinal) + || !nativeDirectories.Any(group => path.StartsWith(group + "/", StringComparison.Ordinal)) + ))) { + throw new ArgumentException( + "Exact selected libraries must belong to their declared native groups and suffix.", + nameof(nativeFiles) + ); + } this.target = target; this.requiredFiles = Array.AsReadOnly(requiredFiles.ToArray()); this.nativeRoot = nativeRoot; @@ -104,7 +118,9 @@ private static void ValidatePath(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); if (path.Contains('\\') || path.Contains(':') || path.StartsWith('/') - || path.Split('/').Any(static segment => segment is "" or "." or "..")) + || path.Split('/').Any(static segment => segment is "" or "." or "..") + ) { throw new ArgumentException("Publication requirements must use portable owned relative paths.", nameof(path)); + } } } diff --git a/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs b/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs index a2201da7d..c10a6c22c 100644 --- a/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs +++ b/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs @@ -49,7 +49,9 @@ public SourcePlayerSupportPackProvisioner( ArgumentNullException.ThrowIfNull(reportDiagnostic); m_reportDiagnostic = reportDiagnostic; if (nativeDependencies is not null && !Path.IsPathFullyQualified(nativeDependencies)) + { throw new ArgumentException("A native dependency selection must be absolute.", nameof(nativeDependencies)); + } m_nativeDependencies = nativeDependencies; ArgumentException.ThrowIfNullOrWhiteSpace(dotnetHost); m_publisher = publisher; @@ -57,7 +59,9 @@ public SourcePlayerSupportPackProvisioner( ArgumentException.ThrowIfNullOrWhiteSpace(engineRoot); m_engineRoot = Path.GetFullPath(engineRoot); if (!IsEngineRoot(m_engineRoot)) + { throw new DirectoryNotFoundException($"Engine source checkout '{m_engineRoot}' is unavailable."); + } } /// @@ -97,13 +101,23 @@ public SourcePlayerSupportPackProvisioner( ArgumentException.ThrowIfNullOrWhiteSpace(dotnetHost); string? configured = Environment.GetEnvironmentVariable("INNO_ENGINE_ROOT"); if (!string.IsNullOrWhiteSpace(configured)) + { return new SourcePlayerSupportPackProvisioner(configured, publisher, dotnetHost, reportDiagnostic, nativeDependencies); + } for (DirectoryInfo? directory = new(Path.GetFullPath(startDirectory)); directory is not null; - directory = directory.Parent) - { + directory = directory.Parent + ) { if (IsEngineRoot(directory.FullName)) - return new SourcePlayerSupportPackProvisioner(directory.FullName, publisher, dotnetHost, reportDiagnostic, nativeDependencies); + { + return new SourcePlayerSupportPackProvisioner( + directory.FullName, + publisher, + dotnetHost, + reportDiagnostic, + nativeDependencies + ); + } } return null; } @@ -134,13 +148,17 @@ public async ValueTask ProvisionAsync( target, m_dotnetHost, cancellationToken, - m_nativeDependencies).ConfigureAwait(false); + m_nativeDependencies + ).ConfigureAwait(false); foreach (string diagnostic in installed.diagnostics) + { m_reportDiagnostic(diagnostic); + } } private static bool IsEngineRoot(string path) - => File.Exists(Path.Combine(path, "InnoEngine.sln")) && - File.Exists(Path.Combine(path, "build", "distributions", "Inno.Build.Distribution.Standard", "Inno.Build.Distribution.Standard.csproj")); - + => File.Exists(Path.Combine(path, "InnoEngine.sln")) + && File.Exists( + Path.Combine(path, "build", "distributions", "Inno.Build.Distribution.Standard", "Inno.Build.Distribution.Standard.csproj") + ); } diff --git a/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs b/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs index b1fb4f6ce..9eddcca00 100644 --- a/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs @@ -4,9 +4,9 @@ using System.IO; using System.Linq; using System.Threading; -using Inno.Core.IO; -using Inno.Build.Toolchains; using Microsoft.Build.Framework; +using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.TaskHosting; @@ -76,7 +76,9 @@ public override bool Execute() CancellationToken token = m_cancellation.Token; token.ThrowIfCancellationRequested(); if (BuildEngine is not IBuildEngine4 engine) + { throw new InvalidOperationException("Task-runtime preparation requires the MSBuild Build-lifetime registry."); + } string project = RequireAbsolute(ProjectFile); string artifacts = RequireAbsolute(ArtifactsDirectory); string load = RequireAbsolute(LoadDirectory); @@ -86,23 +88,31 @@ public override bool Execute() string[] targets = Targets.ToArray(); string[] removed = RemoveProperties.ToArray(); if (!File.Exists(project) || targets.Length == 0 || targets.Any(string.IsNullOrWhiteSpace)) + { throw new ArgumentException("A task project and nonempty build targets are required."); + } IDictionary properties = FreezeProperties(artifacts, removed); // MSBuild's API applies undefinitions to the final request. Explicit task // properties must survive removal of identically named parent globals. removed = removed.Where(name => !properties.Contains(name)).ToArray(); var workspaces = new BuildCachePublisher(Path.GetDirectoryName(artifacts)!, BuildCacheArtifactRole.ReusableWorkspace); ownerUses = AcquireOwnerUses( - [new(cache, BuildCacheArtifactRole.ImmutableArtifact), - new(taskRoot, BuildCacheArtifactRole.ProcessWorkingDirectory), workspaces], engine, token); + [ + new(cache, BuildCacheArtifactRole.ImmutableArtifact), + new(taskRoot, BuildCacheArtifactRole.ProcessWorkingDirectory), + workspaces + ], + engine, + token + ); TaskRuntimePreparation.RegisterWorkspaceReader(load, artifacts, token); TaskRuntimeRequestSnapshot initial = TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token); bool restoreRequired = initial.needsRestore; bool restoreRequested = targets.Contains("Restore", StringComparer.OrdinalIgnoreCase); string? request = restoreRequired ? null : initial.key; if (request is not null && (TaskRuntimeBuildScope.Read(engine, request, load, cancellation: token) - ?? TaskRuntimePreparation.ReadRequest(cache, request, load, token)) is ITaskItem[] reused) - { + ?? TaskRuntimePreparation.ReadRequest(cache, request, load, token)) is ITaskItem[] reused + ) { TargetOutputs = reused; TaskRuntimeBuildScope.Register(engine, request, reused); Log.LogMessage(MessageImportance.High, "INNO-TASK-RUNTIME reused {0}", request); @@ -112,8 +122,11 @@ public override bool Execute() engine.Yield(); try { - ownership = FileLease.AcquireAsync(artifacts + ".lock", - Timeout.InfiniteTimeSpan, token).AsTask().GetAwaiter().GetResult(); + ownership = FileLease.AcquireAsync( + artifacts + ".lock", + Timeout.InfiniteTimeSpan, + token + ).AsTask().GetAwaiter().GetResult(); } finally { @@ -133,63 +146,114 @@ public override bool Execute() workspaces.BeginWorkingDirectory(artifacts, artifacts + ".lock", null, token); if (restoreRequired || restoreRequested) { - BuildEngineResult restored = engine.BuildProjectFilesInParallel([project], ["Restore"], - [RestoreProperties(properties)], [removed], [null!], returnTargetOutputs: false); + BuildEngineResult restored = engine.BuildProjectFilesInParallel( + [project], + ["Restore"], + [RestoreProperties(properties)], + [removed], + [null!], + returnTargetOutputs: false + ); token.ThrowIfCancellationRequested(); if (!restored.Result) + { return false; - + } } TaskRuntimeRequestSnapshot restoredInputs = restoreRequired || restoreRequested - ? TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token) : initial; + ? TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token) + : initial; foreach (TaskRuntimeRestoreRequest inputRestore in restoredInputs.restoreRequests - .DistinctBy(static input => input.project + "|" + string.Join(";", input.properties - .OrderBy(static property => property.Key, StringComparer.OrdinalIgnoreCase) - .Select(static property => property.Key + "=" + property.Value)))) - { + .DistinctBy(static input => ( + input.project + "|" + string.Join( + ";", + input.properties + .OrderBy(static property => property.Key, StringComparer.OrdinalIgnoreCase) + .Select(static property => property.Key + "=" + property.Value) + ) + )) + ) { var inputProperties = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (var property in inputRestore.properties) + { inputProperties[property.Key] = property.Value; - BuildEngineResult restored = engine.BuildProjectFilesInParallel([inputRestore.project], ["Restore"], - [RestoreProperties(inputProperties)], [inputRestore.removedProperties - .Where(static name => !name.Equals("ExcludeRestorePackageImports", StringComparison.OrdinalIgnoreCase)).ToArray()], [null!], returnTargetOutputs: false); + } + BuildEngineResult restored = engine.BuildProjectFilesInParallel( + [inputRestore.project], + ["Restore"], + [RestoreProperties(inputProperties)], + [inputRestore.removedProperties + .Where(static name => !name.Equals("ExcludeRestorePackageImports", StringComparison.OrdinalIgnoreCase)) + .ToArray()], + [null!], + returnTargetOutputs: false + ); token.ThrowIfCancellationRequested(); if (!restored.Result) + { return false; + } } TaskRuntimeRequestSnapshot locked = restoredInputs != initial && restoredInputs.restoreRequests.Count == 0 - ? restoredInputs : TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token); + ? restoredInputs + : TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token); if (locked.needsRestore) + { throw new InvalidOperationException("Task-runtime dependencies are not restored."); + } if (!restoreRequested && !restoreRequired && request is not null && locked.key != request) + { throw new InvalidOperationException("Task-runtime inputs changed while waiting for build ownership."); + } request = locked.key; if ((TaskRuntimeBuildScope.Read(engine, request, load, cancellation: token) - ?? TaskRuntimePreparation.ReadRequest(cache, request, load, token)) is ITaskItem[] completed) - { + ?? TaskRuntimePreparation.ReadRequest(cache, request, load, token)) is ITaskItem[] completed + ) { TargetOutputs = completed; TaskRuntimeBuildScope.Register(engine, request, completed); Log.LogMessage(MessageImportance.High, "INNO-TASK-RUNTIME reused {0}", request); return true; } - string[] compilationTargets = targets.Where(static target => !target.Equals("Restore", StringComparison.OrdinalIgnoreCase)).ToArray(); + string[] compilationTargets = targets + .Where(static target => !target.Equals("Restore", StringComparison.OrdinalIgnoreCase)) + .ToArray(); if (compilationTargets.Length == 0) + { throw new ArgumentException("Task-runtime preparation requires a publication target after restore.", nameof(Targets)); - BuildEngineResult result = engine.BuildProjectFilesInParallel([project], compilationTargets, - [properties], [removed], [null!], returnTargetOutputs: true); + } + BuildEngineResult result = engine.BuildProjectFilesInParallel( + [project], + compilationTargets, + [properties], + [removed], + [null!], + returnTargetOutputs: true + ); token.ThrowIfCancellationRequested(); if (!result.Result) + { return false; + } TargetOutputs = result.TargetOutputsPerProject.SelectMany(static projectOutputs => projectOutputs.Values) - .SelectMany(static output => output).ToArray(); + .SelectMany(static output => output) + .ToArray(); if (TargetOutputs.Length == 0) + { throw new InvalidDataException("The task project returned no runtime closure."); + } TaskRuntimeRequestSnapshot compiled = TaskRuntimeRequestKey.Capture(project, artifacts, targets, properties, token); if (compiled.key != request) - throw new InvalidOperationException("Task-runtime inputs changed during compilation; its preparation was not cached. " - + locked.DescribeChanges(compiled)); + { + throw new InvalidOperationException( + "Task-runtime inputs changed during compilation; its preparation was not cached. " + + locked.DescribeChanges(compiled) + ); + } TargetOutputs = TaskRuntimePreparation.Publish(cache, TargetOutputs, engine, load, token); - TaskRuntimePreparation.RegisterReader(load, TargetOutputs.Single(static item => item.GetMetadata("RelativePath") == "Inno.Build.Tasks.dll").ItemSpec); + TaskRuntimePreparation.RegisterReader( + load, + TargetOutputs.Single(static item => item.GetMetadata("RelativePath") == "Inno.Build.Tasks.dll").ItemSpec + ); workspaces.Record(artifacts, artifacts + ".lock", [], null, null, token); TaskRuntimeBuildScope.Register(engine, request, TargetOutputs); TaskRuntimePreparation.RecordRequest(cache, request, TargetOutputs); @@ -205,7 +269,9 @@ public override bool Execute() finally { foreach (FileLease activity in ownerUses) + { activity.Dispose(); + } lock (m_cancellationGate) { m_finished = true; @@ -220,8 +286,12 @@ public override bool Execute() public void Cancel() { lock (m_cancellationGate) + { if (!m_finished) + { m_cancellation.Cancel(); + } + } } private static FileLease[] AcquireOwnerUses( @@ -234,13 +304,18 @@ CancellationToken cancellation try { foreach (BuildCachePublisher publisher in publishers.OrderBy( - static entry => entry.Describe("task-runtime").coordinationPath, StringComparer.Ordinal)) + static entry => entry.Describe("task-runtime").coordinationPath, + StringComparer.Ordinal + )) { activities.Push(publisher.AcquireUseAsync(cancellation).AsTask().GetAwaiter().GetResult()); + } } catch { while (activities.TryPop(out FileLease? activity)) + { activity.Dispose(); + } throw; } finally @@ -252,7 +327,9 @@ CancellationToken cancellation catch { while (activities.TryPop(out FileLease? activity)) + { activity.Dispose(); + } throw; } } @@ -265,18 +342,28 @@ IReadOnlyList removed ) { Hashtable properties = new(StringComparer.OrdinalIgnoreCase); if (BuildEngine is IBuildEngine6 engine) + { foreach (var property in engine.GetGlobalProperties()) + { if (!removed.Contains(property.Key, StringComparer.OrdinalIgnoreCase)) + { properties[property.Key] = property.Value; + } + } + } var explicitNames = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (string property in Properties) { int separator = property.IndexOf('='); if (separator <= 0 || !explicitNames.Add(property[..separator])) + { throw new ArgumentException("Task properties require unique name=value declarations."); + } string name = property[..separator]; if (string.Equals(name, "ArtifactsPath", StringComparison.OrdinalIgnoreCase)) + { throw new ArgumentException("The task artifact owner cannot be overridden."); + } properties[name] = property[(separator + 1)..]; } properties["ArtifactsPath"] = artifacts; @@ -299,7 +386,9 @@ private static string RequireAbsolute(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); if (!Path.IsPathFullyQualified(value)) + { throw new ArgumentException("Task-runtime ownership requires absolute locations."); + } return Path.GetFullPath(value); } } diff --git a/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs b/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs index 6aaff3322..4a52836ea 100644 --- a/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs @@ -4,6 +4,7 @@ using Microsoft.Build.Framework; using Inno.Build.Toolchains; using Inno.Core.IO; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.TaskHosting; @@ -62,8 +63,12 @@ public sealed class MaterializeBindingsTask : BuildTask, ICancelableTask public void Cancel() { lock (m_lifecycle) + { if (!m_completed) + { m_cancellation.Cancel(); + } + } } /// @@ -79,17 +84,23 @@ public override bool Execute() CancellationToken cancellation = m_cancellation.Token; cancellation.ThrowIfCancellationRequested(); if (!Path.IsPathFullyQualified(Source) || !Path.IsPathFullyQualified(IntermediateDirectory) - || !Path.IsPathFullyQualified(ComponentProject)) + || !Path.IsPathFullyQualified(ComponentProject) + ) { throw new ArgumentException("Binding consumption requires absolute source and owner paths."); + } string source = Path.GetFullPath(Source); using IDisposable ownership = Acquire(source, cancellation); string destination = Path.Combine(Path.GetFullPath(IntermediateDirectory), "bindings", "Bindings.cs"); if (SamePath(source, destination)) + { throw new ArgumentException("The SDK consumer must not overwrite the publisher's source."); + } byte[] content = File.ReadAllBytes(source); cancellation.ThrowIfCancellationRequested(); if (!File.Exists(destination) || !content.AsSpan().SequenceEqual(File.ReadAllBytes(destination))) + { AtomicFile.WriteAllBytes(destination, content); + } MaterializedSource = destination; return true; } @@ -141,23 +152,40 @@ CancellationToken cancellation if (ArtifactDirectory.Length != 0) { if (!Path.IsPathFullyQualified(ArtifactDirectory)) + { throw new ArgumentException("Binding artifacts require an absolute publication owner."); + } string directory = Path.GetFullPath(ArtifactDirectory); if (!SamePath(source, Path.Combine(directory, "Generated", "Bindings.cs"))) + { throw new ArgumentException("The selected source is outside its declared binding artifact."); - return BuildArtifactReadLease.AcquireAsync(directory, ArtifactOwnerDirectory, Fingerprint, ["Native", "Generated"], cancellation) - .AsTask().GetAwaiter().GetResult(); + } + return BuildArtifactReadLease + .AcquireAsync(directory, ArtifactOwnerDirectory, Fingerprint, ["Native", "Generated"], cancellation) + .AsTask() + .GetAwaiter() + .GetResult(); } string owner = Path.GetDirectoryName(Path.GetFullPath(ComponentProject))!; if (!SamePath(source, Path.Combine(owner, "Generated", "Bindings.cs"))) + { throw new ArgumentException("Host bindings must belong to their Native project's Generated directory."); - return FileLease.AcquireAsync(Path.Combine(owner, "obj", "bindings", "generation.lock"), - Timeout.InfiniteTimeSpan, cancellation).AsTask().GetAwaiter().GetResult(); + } + return FileLease.AcquireAsync( + Path.Combine(owner, "obj", "bindings", "generation.lock"), + Timeout.InfiniteTimeSpan, + cancellation + ).AsTask().GetAwaiter().GetResult(); } private static bool SamePath( string left, string right - ) => string.Equals(left, right, OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); + ) => string.Equals( + left, + right, + OperatingSystem.IsWindows() + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal + ); } diff --git a/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs b/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs index bb6354629..3bc08b9fb 100644 --- a/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs @@ -83,25 +83,42 @@ public override bool Execute() var publisherCache = new BuildCachePublisher(cache, BuildCacheArtifactRole.ImmutableArtifact); using FileLease activity = publisherCache.AcquireUseAsync(cancellation).AsTask().GetAwaiter().GetResult(); bool prepared = BuildEngine is IBuildEngine4 engine - && TaskRuntimeBuildScope.Read(engine, "publication:" + cache + "/" + fingerprint, load, verifyOutputs: false, cancellation: cancellation) - is ITaskItem[] publication - && publication.Length == files.Length - && publication.Zip(files).All(static pair => pair.First.ItemSpec == pair.Second.source - && pair.First.GetMetadata("RelativePath") == pair.Second.relative - && pair.First.GetMetadata("FileHash") == pair.Second.hash); + && TaskRuntimeBuildScope.Read( + engine, + "publication:" + cache + "/" + fingerprint, + load, + verifyOutputs: false, + cancellation: cancellation + ) + is ITaskItem[] publication + && publication.Length == files.Length + && publication.Zip(files).All(static pair => ( + pair.First.ItemSpec == pair.Second.source + && pair.First.GetMetadata("RelativePath") == pair.Second.relative + && pair.First.GetMetadata("FileHash") == pair.Second.hash + )); if (!prepared) { - using FileLease ownership = FileLease.AcquireAsync(destination + ".lock", - Timeout.InfiniteTimeSpan, cancellation).AsTask().GetAwaiter().GetResult(); + using FileLease ownership = FileLease.AcquireAsync( + destination + ".lock", + Timeout.InfiniteTimeSpan, + cancellation + ).AsTask().GetAwaiter().GetResult(); TaskRuntimePreparation.ValidateSources(files, cancellation); if (!TaskRuntimePreparation.IsComplete(Path.Combine(destination, "Runtime"), files, cancellation)) + { TaskRuntimePreparation.PublishCandidate(destination, files, cancellation); + } TaskRuntimePreparation.ValidateSources(files, cancellation); } PublishedAssembly = Path.Combine(destination, "Runtime", "Inno.Build.Tasks.dll"); using (FileLease ownership = FileLease.AcquireAsync(destination + ".lock", Timeout.InfiniteTimeSpan, cancellation) - .AsTask().GetAwaiter().GetResult()) + .AsTask() + .GetAwaiter() + .GetResult() + ) { publisherCache.Record(destination, destination + ".lock", [], null, null, cancellation); + } RegisterReader(load, PublishedAssembly); Log.LogMessage(MessageImportance.Normal, "INNO-TASK-HOST verified {0}", fingerprint); return true; @@ -127,15 +144,22 @@ is ITaskItem[] publication public void Cancel() { lock (m_cancellationGate) + { if (!m_finished) + { m_cancellation.Cancel(); + } + } } private TaskRuntimePreparation.RuntimeFile[] FreezeFiles() => TaskRuntimePreparation.FreezeFiles(InputFiles); + private static string RequireAbsolute(string path) => TaskRuntimePreparation.RequireAbsolute(path); + private static void RegisterReader( string load, string assembly ) => TaskRuntimePreparation.RegisterReader(load, assembly); + private static void RegisterProcessOwner(string directory) => TaskRuntimePreparation.RegisterProcessOwner(directory); } diff --git a/build/tasks/Inno.Build.TaskHosting/RegisterTaskPublisherTask.cs b/build/tasks/Inno.Build.TaskHosting/RegisterTaskPublisherTask.cs index 69be54df3..fee614bf8 100644 --- a/build/tasks/Inno.Build.TaskHosting/RegisterTaskPublisherTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/RegisterTaskPublisherTask.cs @@ -1,7 +1,8 @@ using System; using System.IO; -using Inno.Core.IO; using Microsoft.Build.Framework; +using Inno.Core.IO; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.TaskHosting; @@ -47,9 +48,15 @@ public override bool Execute() PathBoundary.RequireUnlinkedPath(root, bootstrap); string assembly = Path.GetFullPath(typeof(RegisterTaskPublisherTask).Assembly.Location); string expected = Path.Combine(directory, "Inno.Build.TaskHosting.dll"); - if (!string.Equals(assembly, expected, OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + if (!string.Equals( + assembly, + expected, + OperatingSystem.IsWindows() + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal + )) { throw new InvalidOperationException("Publisher ownership must identify this task's actual private assembly."); + } TaskRuntimePreparation.RegisterProcessOwner(directory); TaskRuntimePreparation.RegisterProcessOwner(bootstrap); return true; diff --git a/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs b/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs index 25b128a84..1268d4750 100644 --- a/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs @@ -4,8 +4,8 @@ using System.IO; using System.Linq; using System.Threading; -using Inno.Core.IO; using Microsoft.Build.Framework; +using Inno.Core.IO; namespace Inno.Build.TaskHosting; @@ -49,9 +49,13 @@ public override bool Execute() try { if (BuildEngine is not IBuildEngine3 engine || !Path.IsPathFullyQualified(LockPath)) + { throw new ArgumentException("Owned restore requires an MSBuild node and an absolute write-owner lock."); + } if (Projects.Length == 0) + { throw new ArgumentException("Owned restore requires at least one explicitly selected project."); + } CancellationToken token = m_cancellation.Token; token.ThrowIfCancellationRequested(); var projects = new List(Projects.Length); @@ -60,7 +64,9 @@ public override bool Execute() { string path = project.GetMetadata("FullPath"); if (!File.Exists(path)) + { throw new FileNotFoundException("An owned restore project is missing.", path); + } var properties = new Hashtable(StringComparer.OrdinalIgnoreCase); Apply(project.GetMetadata("AdditionalProperties").Split(';', StringSplitOptions.RemoveEmptyEntries), properties); Apply(Properties, properties); @@ -72,7 +78,9 @@ public override bool Execute() try { ownership = FileLease.AcquireAsync(LockPath, Timeout.InfiniteTimeSpan, token) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); } finally { @@ -89,13 +97,23 @@ public override bool Execute() { "SolutionPath", "SolutionDir", "SolutionName", "SolutionFileName", "SolutionExt", "RestoreGraphProjectInput", "_RestoreSolutionFileUsed" - }.Concat(Projects[index].GetMetadata("GlobalPropertiesToRemove") - .Split(';', StringSplitOptions.RemoveEmptyEntries)) + } + .Concat( + Projects[index].GetMetadata("GlobalPropertiesToRemove") + .Split(';', StringSplitOptions.RemoveEmptyEntries) + ) .Where(static name => !name.Equals("ExcludeRestorePackageImports", StringComparison.OrdinalIgnoreCase)) - .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); } - BuildEngineResult result = engine.BuildProjectFilesInParallel(projects.ToArray(), ["Restore"], - globals.ToArray(), removed, versions, returnTargetOutputs: false); + BuildEngineResult result = engine.BuildProjectFilesInParallel( + projects.ToArray(), + ["Restore"], + globals.ToArray(), + removed, + versions, + returnTargetOutputs: false + ); token.ThrowIfCancellationRequested(); return result.Result; } @@ -121,8 +139,12 @@ public override bool Execute() public void Cancel() { lock (m_gate) + { if (!m_finished) + { m_cancellation.Cancel(); + } + } } private static void Apply( @@ -133,7 +155,9 @@ IDictionary properties { int separator = declaration.IndexOf('='); if (separator <= 0) + { throw new ArgumentException("Restore properties require explicit name=value declarations."); + } properties[declaration[..separator]] = Microsoft.Build.Evaluation.ProjectCollection.Unescape(declaration[(separator + 1)..]); } } diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs index db8fa5cb4..5018a18f0 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs @@ -51,10 +51,18 @@ public override bool Execute() // The IDE build host must not keep the normal SDK output file locked between builds. Assembly foundation = Assembly.Load(File.ReadAllBytes(FoundationAssembly)); Type owner = foundation.GetType("Inno.Core.IO.ProcessOwnedDirectory", throwOnError: true)!; - MethodInfo create = owner.GetMethod("CreateForProcessAsync", BindingFlags.Public | BindingFlags.Static, - null, [typeof(string), typeof(string), typeof(CancellationToken)], null)!; + MethodInfo create = owner.GetMethod( + "CreateForProcessAsync", + BindingFlags.Public | BindingFlags.Static, + null, + [typeof(string), typeof(string), typeof(CancellationToken)], + null + )!; object pending = create.Invoke(null, [Root, Identity, CancellationToken.None])!; - var operation = (Task)pending.GetType().GetMethod("AsTask", BindingFlags.Public | BindingFlags.Instance)!.Invoke(pending, null)!; + var operation = (Task)pending + .GetType() + .GetMethod("AsTask", BindingFlags.Public | BindingFlags.Instance)! + .Invoke(pending, null)!; Directory = operation.GetAwaiter().GetResult(); return true; } diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBuildScope.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBuildScope.cs index 680eac2ef..1955fda35 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBuildScope.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBuildScope.cs @@ -22,22 +22,32 @@ internal static class TaskRuntimeBuildScope CancellationToken cancellation = default ) { if (engine.GetRegisteredTaskObject(C_PREFIX + identity, RegisteredTaskObjectLifetime.Build) is not string[][] rows) + { return null; + } ITaskItem[] outputs = Restore(rows); string assembly = outputs.Single(static item => item.GetMetadata("RelativePath") == "Inno.Build.Tasks.dll").ItemSpec; string runtime = Path.GetDirectoryName(assembly)!; string publication = Path.GetDirectoryName(runtime)!; string owner = Path.GetDirectoryName(publication)!; if (!Directory.Exists(publication)) + { return null; + } try { using FileLease activity = FileLease.AcquireSharedAsync(Path.Combine(owner, "owner.lock"), TimeSpan.Zero, cancellation) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); using FileLease reading = FileLease.AcquireSharedAsync(publication + ".lock", TimeSpan.Zero, cancellation) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); if (verifyOutputs && !TaskRuntimePreparation.IsComplete(runtime, TaskRuntimePreparation.FreezeFiles(outputs), cancellation)) + { return null; + } TaskRuntimePreparation.RegisterReader(load, assembly); return outputs; } @@ -53,8 +63,12 @@ internal static void Register( ITaskItem[] outputs ) { string[][] rows = outputs.Select(static output => new[] { output.ItemSpec } - .Concat(output.CloneCustomMetadata().Keys.Cast().Order(StringComparer.Ordinal) - .SelectMany(name => new[] { name, output.GetMetadata(name) })).ToArray()).ToArray(); + .Concat( + output.CloneCustomMetadata().Keys.Cast() + .Order(StringComparer.Ordinal) + .SelectMany(name => new[] { name, output.GetMetadata(name) }) + ) + .ToArray()).ToArray(); // Only BCL data crosses private task load boundaries. No leases or SDK owners enter the registry. engine.UnregisterTaskObject(C_PREFIX + identity, RegisteredTaskObjectLifetime.Build); engine.RegisterTaskObject(C_PREFIX + identity, rows, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: false); @@ -67,7 +81,9 @@ private static ITaskItem[] Restore(string[][] rows) { var item = new TaskItem(row[0]); for (int index = 1; index < row.Length; index += 2) + { item.SetMetadata(row[index], row[index + 1]); + } outputs.Add(item); } return outputs.ToArray(); diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimePackageInputs.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimePackageInputs.cs index 909cfb25e..2aeab39a8 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimePackageInputs.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimePackageInputs.cs @@ -4,8 +4,8 @@ using System.Linq; using System.Text.Json; using System.Threading; -using Inno.Core.IO; using Microsoft.Build.Execution; +using Inno.Core.IO; namespace Inno.Build.TaskHosting; @@ -24,10 +24,14 @@ CancellationToken cancellation ) { string assets = project.GetPropertyValue("ProjectAssetsFile"); if (assets.Length == 0) + { return true; + } assets = Path.GetFullPath(assets, Path.GetDirectoryName(project.FullPath)!); if (!File.Exists(assets)) + { return false; + } inputs.Add(assets); using JsonDocument document = JsonDocument.Parse(File.ReadAllText(assets)); JsonElement root = document.RootElement; @@ -37,28 +41,44 @@ CancellationToken cancellation string runtime = project.GetPropertyValue("RuntimeIdentifier"); string suffix = runtime.Length == 0 ? string.Empty : "/" + runtime; if (!targets.TryGetProperty(framework + suffix, out JsonElement target) - && !targets.TryGetProperty(moniker + suffix, out target)) + && !targets.TryGetProperty(moniker + suffix, out target) + ) { return false; + } JsonElement libraries = root.GetProperty("libraries"); - string[] folders = root.GetProperty("packageFolders").EnumerateObject() - .Select(static folder => folder.Name).ToArray(); + string[] folders = root.GetProperty("packageFolders") + .EnumerateObject() + .Select(static folder => folder.Name) + .ToArray(); foreach (JsonProperty dependency in target.EnumerateObject()) { cancellation.ThrowIfCancellationRequested(); if (dependency.Value.GetProperty("type").GetString() != "package") + { continue; + } JsonElement library = libraries.GetProperty(dependency.Name); string relative = library.GetProperty("path").GetString() - ?? throw new InvalidDataException("A restored task package has no location."); + ?? throw new InvalidDataException("A restored task package has no location."); string? directory = folders.Select(folder => PathBoundary.Resolve(folder, relative)) .FirstOrDefault(Directory.Exists); if (directory is null) - throw new DirectoryNotFoundException($"The task runtime package '{dependency.Name}' is absent from its restored package roots."); + { + throw new DirectoryNotFoundException( + $"The task runtime package '{dependency.Name}' is absent from its restored package roots." + ); + } var selected = new HashSet(StringComparer.Ordinal); foreach (string group in S_ASSET_GROUPS) + { if (dependency.Value.TryGetProperty(group, out JsonElement entries)) + { foreach (JsonProperty entry in entries.EnumerateObject()) + { selected.Add(entry.Name); + } + } + } // Analyzer assemblies are selected from the package file inventory by the SDK, // rather than represented as a separate target asset group. foreach (JsonElement entry in library.GetProperty("files").EnumerateArray()) @@ -66,17 +86,26 @@ CancellationToken cancellation string path = entry.GetString()!; if (path.StartsWith("analyzers/", StringComparison.Ordinal) && !path.Contains("/vb/", StringComparison.Ordinal) - && !path.Contains("/fs/", StringComparison.Ordinal)) + && !path.Contains("/fs/", StringComparison.Ordinal) + ) { selected.Add(path); + } } foreach (string relativeInput in selected) { cancellation.ThrowIfCancellationRequested(); if (Path.GetFileName(relativeInput) == "_._") + { continue; + } string input = PathBoundary.Resolve(directory, relativeInput); if (!File.Exists(input)) - throw new FileNotFoundException($"The restored task runtime input '{dependency.Name}/{relativeInput}' is absent.", input); + { + throw new FileNotFoundException( + $"The restored task runtime input '{dependency.Name}/{relativeInput}' is absent.", + input + ); + } inputs.Add(input); } } diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimePreparation.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimePreparation.cs index 3ce9ba7ba..ec86290fc 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimePreparation.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimePreparation.cs @@ -25,7 +25,9 @@ CancellationToken cancellation using FileLease activity = publisher.AcquireUseAsync(cancellation).AsTask().GetAwaiter().GetResult(); string index = Path.Combine(cache, request + ".request.json"); if (!File.Exists(index)) + { return null; + } RuntimeFile[] files; try { @@ -38,18 +40,26 @@ CancellationToken cancellation return null; } if (files.Length == 0) + { return null; + } string assembly = files.Single(static file => file.relative == "Inno.Build.Tasks.dll").source; string runtime = Path.GetDirectoryName(assembly)!; string publication = Path.GetDirectoryName(runtime)!; PathBoundary.RequireUnlinkedPath(cache, publication); if (Path.GetRelativePath(cache, publication) != Fingerprint(files) - || files.Any(file => file.source != PathBoundary.Resolve(runtime, file.relative))) + || files.Any(file => file.source != PathBoundary.Resolve(runtime, file.relative)) + ) { return null; + } using FileLease reading = FileLease.AcquireSharedAsync(publication + ".lock", TimeSpan.FromSeconds(30), cancellation) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); if (!IsComplete(runtime, files, cancellation)) + { return null; + } RegisterReader(load, assembly); return CreateOutputs(files); } @@ -64,20 +74,29 @@ ITaskItem[] outputs RuntimeFile[] files = FreezeFiles(outputs); string path = Path.Combine(cache, request + ".request.json"); AtomicFile.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(files)); - publisher.RecordIndex(path, files.Select(static file => Path.GetDirectoryName(Path.GetDirectoryName(file.source)!)!) - .Distinct(StringComparer.Ordinal).ToArray()); + publisher.RecordIndex( + path, + files.Select(static file => Path.GetDirectoryName(Path.GetDirectoryName(file.source)!)!) + .Distinct(StringComparer.Ordinal) + .ToArray() + ); } - private static ITaskItem[] CreateOutputs(IReadOnlyList files) => files.Select(file => - { - var item = new TaskItem(file.source); - item.SetMetadata("RelativePath", file.relative); - item.SetMetadata("FileHash", file.hash); - return (ITaskItem)item; - }).ToArray(); + private static ITaskItem[] CreateOutputs(IReadOnlyList files) + => files.Select(file => + { + var item = new TaskItem(file.source); + item.SetMetadata("RelativePath", file.relative); + item.SetMetadata("FileHash", file.hash); + return (ITaskItem)item; + }).ToArray(); - internal static string Fingerprint(IReadOnlyList files) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes( - string.Join('\n', files.Select(static file => file.relative + "|" + file.hash))))); + internal static string Fingerprint(IReadOnlyList files) + => Convert.ToHexString( + SHA256.HashData( + Encoding.UTF8.GetBytes(string.Join('\n', files.Select(static file => file.relative + "|" + file.hash))) + ) + ); internal static ITaskItem[] Publish( string cache, @@ -92,10 +111,14 @@ CancellationToken cancellation var publisher = new BuildCachePublisher(cache, BuildCacheArtifactRole.ImmutableArtifact); using FileLease activity = publisher.AcquireUseAsync(cancellation).AsTask().GetAwaiter().GetResult(); using FileLease lease = FileLease.AcquireAsync(destination + ".lock", Timeout.InfiniteTimeSpan, cancellation) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); ValidateSources(files, cancellation); if (!IsComplete(Path.Combine(destination, "Runtime"), files, cancellation)) + { PublishCandidate(destination, files, cancellation); + } ValidateSources(files, cancellation); ITaskItem[] output = files.Select(file => { @@ -113,7 +136,9 @@ CancellationToken cancellation internal static RuntimeFile[] FreezeFiles(ITaskItem[] inputFiles) { if (inputFiles.Length == 0) + { throw new InvalidDataException("The task runtime closure is empty."); + } var paths = new HashSet(StringComparer.OrdinalIgnoreCase); RuntimeFile[] files = inputFiles.Select(item => { @@ -121,12 +146,16 @@ internal static RuntimeFile[] FreezeFiles(ITaskItem[] inputFiles) string hash = item.GetMetadata("FileHash").ToUpperInvariant(); if (relative.Length == 0 || relative.Split('/').Any(static segment => segment is "" or "." or "..") || relative.Contains(':') || !paths.Add(relative) - || hash.Length != 64 || hash.Any(static character => !Uri.IsHexDigit(character))) + || hash.Length != 64 || hash.Any(static character => !Uri.IsHexDigit(character)) + ) { throw new InvalidDataException("A runtime input has an invalid path, hash or duplicate identity."); + } return new RuntimeFile(RequireAbsolute(item.ItemSpec), relative, hash); }).OrderBy(static file => file.relative, StringComparer.Ordinal).ToArray(); if (!paths.Contains("Inno.Build.Tasks.dll")) + { throw new InvalidDataException("The task runtime closure has no task assembly."); + } return files; } @@ -134,7 +163,9 @@ internal static string RequireAbsolute(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); if (!Path.IsPathFullyQualified(path)) + { throw new ArgumentException("Task host locations must be absolute.", nameof(path)); + } return Path.GetFullPath(path); } @@ -146,7 +177,9 @@ CancellationToken cancellation { cancellation.ThrowIfCancellationRequested(); if (Hash(file.source) != file.hash) + { throw new InvalidDataException($"Task runtime input changed after selection: {file.source}"); + } } } @@ -156,16 +189,23 @@ internal static bool IsComplete( CancellationToken cancellation ) { if (!Directory.Exists(runtime)) + { return false; + } string[] actual = PathBoundary.EnumerateFiles(runtime) - .Select(path => Path.GetRelativePath(runtime, path).Replace('\\', '/')).ToArray(); + .Select(path => Path.GetRelativePath(runtime, path).Replace('\\', '/')) + .ToArray(); if (!actual.ToHashSet(StringComparer.Ordinal).SetEquals(files.Select(static file => file.relative))) + { return false; + } foreach (RuntimeFile file in files) { cancellation.ThrowIfCancellationRequested(); if (Hash(PathBoundary.Resolve(runtime, file.relative)) != file.hash) + { return false; + } } return true; } @@ -176,7 +216,9 @@ internal static void PublishCandidate( CancellationToken cancellation ) { using ProcessOwnedDirectory candidateOwner = ProcessOwnedDirectory.CreateAsync(Path.GetDirectoryName(destination)!, cancellation) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); string staging = candidateOwner.directory; string runtime = Path.Combine(staging, "Runtime"); try @@ -189,7 +231,9 @@ CancellationToken cancellation File.Copy(file.source, output); } if (!IsComplete(runtime, files, cancellation)) + { throw new InvalidDataException("The copied task runtime did not match its selected closure."); + } ValidateSources(files, cancellation); cancellation.ThrowIfCancellationRequested(); try @@ -235,13 +279,19 @@ string assembly string host = Path.GetDirectoryName(Path.GetDirectoryName(assembly))!; var hostPublisher = new BuildCachePublisher(Path.GetDirectoryName(host)!, BuildCacheArtifactRole.ImmutableArtifact); using FileLease activity = hostPublisher.AcquireUseAsync().AsTask().GetAwaiter().GetResult(); - new BuildCachePublisher(root, BuildCacheArtifactRole.ProcessWorkingDirectory).RecordProcessUse(operation, operation + ".lock", [host]); + new BuildCachePublisher( + root, + BuildCacheArtifactRole.ProcessWorkingDirectory + ).RecordProcessUse(operation, operation + ".lock", [host]); } internal static void RegisterProcessOwner(string directory) { string operation = Path.GetDirectoryName(directory)!; - new BuildCachePublisher(Path.GetDirectoryName(operation)!, BuildCacheArtifactRole.ProcessWorkingDirectory).RecordProcessUse(operation, operation + ".lock", []); + new BuildCachePublisher( + Path.GetDirectoryName(operation)!, + BuildCacheArtifactRole.ProcessWorkingDirectory + ).RecordProcessUse(operation, operation + ".lock", []); } internal sealed record RuntimeFile( diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs index 30e4dba30..a44365422 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs @@ -21,7 +21,10 @@ internal static TaskRuntimeRequestSnapshot Capture( CancellationToken cancellation ) { var globals = properties.Cast().ToDictionary( - static entry => (string)entry.Key, static entry => (string)entry.Value!, StringComparer.OrdinalIgnoreCase); + static entry => (string)entry.Key, + static entry => (string)entry.Value!, + StringComparer.OrdinalIgnoreCase + ); using var collection = new ProjectCollection(); var graph = new ProjectGraph(project, globals, collection); bool needsRestore = false; @@ -31,9 +34,11 @@ CancellationToken cancellation var declarations = new List { project, artifacts, string.Join(";", targets) }; // Execution ownership reaches nested tool builds, but is not a compiler input itself. // Evaluated source, imports and compiler properties below still capture any derived behavior. - declarations.AddRange(globals.Where(static entry => IsInputProperty(entry.Key)) - .OrderBy(static entry => entry.Key, StringComparer.OrdinalIgnoreCase) - .Select(static entry => entry.Key + "=" + entry.Value)); + declarations.AddRange( + globals.Where(static entry => IsInputProperty(entry.Key)) + .OrderBy(static entry => entry.Key, StringComparer.OrdinalIgnoreCase) + .Select(static entry => entry.Key + "=" + entry.Value) + ); foreach (var node in graph.ProjectNodes.OrderBy(static node => node.ProjectInstance.FullPath, paths)) { cancellation.ThrowIfCancellationRequested(); @@ -45,50 +50,85 @@ CancellationToken cancellation string[] removedProperties = item.GetMetadataValue("GlobalPropertiesToRemove") .Split(';', StringSplitOptions.RemoveEmptyEntries); foreach (string removedProperty in removedProperties) + { restoreProperties.Remove(removedProperty); + } foreach (string declaration in item.GetMetadataValue("AdditionalProperties") - .Split(';', StringSplitOptions.RemoveEmptyEntries)) - { + .Split(';', StringSplitOptions.RemoveEmptyEntries) + ) { int separator = declaration.IndexOf('='); if (separator <= 0) + { throw new ArgumentException("Owned input restore requires name=value properties."); + } restoreProperties[declaration[..separator]] = ProjectCollection.Unescape(declaration[(separator + 1)..]); } - restoreRequests.Add(new(restoreProject, - new System.Collections.ObjectModel.ReadOnlyDictionary(restoreProperties), removedProperties)); + restoreRequests.Add( + new( + restoreProject, + new System.Collections.ObjectModel.ReadOnlyDictionary(restoreProperties), + removedProperties + ) + ); } inputs.Add(instance.FullPath); foreach (string import in instance.ImportPaths) + { inputs.Add(import); + } needsRestore |= !TaskRuntimePackageInputs.Collect(instance, inputs, cancellation); - declarations.AddRange(instance.GlobalProperties.Where(static entry => IsInputProperty(entry.Key)) - .OrderBy(static entry => entry.Key, StringComparer.OrdinalIgnoreCase) - .Select(entry => instance.FullPath + "|" + entry.Key + "=" + entry.Value)); - foreach (string property in new[] { "TargetFramework", "RuntimeIdentifier", "NETCoreSdkRuntimeIdentifier", "DefineConstants", "LangVersion", "Nullable", "PathMap", - "NETCoreSdkVersion", "MSBuildToolsPath", "MSBuildSDKsPath", "TreatWarningsAsErrors", "Optimize" }) + declarations.AddRange( + instance.GlobalProperties.Where(static entry => IsInputProperty(entry.Key)) + .OrderBy(static entry => entry.Key, StringComparer.OrdinalIgnoreCase) + .Select(entry => instance.FullPath + "|" + entry.Key + "=" + entry.Value) + ); + foreach (string property in new[] + { + "TargetFramework", + "RuntimeIdentifier", + "NETCoreSdkRuntimeIdentifier", + "DefineConstants", + "LangVersion", + "Nullable", + "PathMap", + "NETCoreSdkVersion", + "MSBuildToolsPath", + "MSBuildSDKsPath", + "TreatWarningsAsErrors", + "Optimize" + }) { declarations.Add(instance.FullPath + "|" + property + "=" + instance.GetPropertyValue(property)); + } foreach (var item in instance.Items) { bool source = item.ItemType is "Compile" or "EmbeddedResource" or "Analyzer" - or "AdditionalFiles" or "EditorConfigFiles" or "GlobalAnalyzerConfigFiles" or "AdditionalCompileInputs"; + or "AdditionalFiles" or "EditorConfigFiles" or "GlobalAnalyzerConfigFiles" or "AdditionalCompileInputs"; bool copy = item.GetMetadataValue("CopyToOutputDirectory") is "Always" or "PreserveNewest"; if (source || copy) { string input = Path.GetFullPath(item.EvaluatedInclude, Path.GetDirectoryName(instance.FullPath)!); if (File.Exists(input)) + { inputs.Add(input); + } } if (item.ItemType == "Reference" && item.GetMetadataValue("HintPath") is string hint && hint.Length != 0) { string input = Path.GetFullPath(hint, Path.GetDirectoryName(instance.FullPath)!); if (File.Exists(input)) + { inputs.Add(input); + } } if (item.ItemType == "PackageReference") + { declarations.Add(instance.FullPath + "|package:" + item.EvaluatedInclude + "=" + item.GetMetadataValue("Version")); + } } - for (DirectoryInfo? directory = new(Path.GetDirectoryName(instance.FullPath)!); directory is not null; directory = directory.Parent) - { + for (DirectoryInfo? directory = new( + Path.GetDirectoryName(instance.FullPath)! + ); directory is not null; directory = directory.Parent + ) { string sdkSelection = Path.Combine(directory.FullName, "global.json"); if (File.Exists(sdkSelection)) { @@ -99,20 +139,28 @@ CancellationToken cancellation } string sdkRoot = graph.EntryPointNodes.Single().ProjectInstance.GetPropertyValue("MSBuildToolsPath"); foreach (string name in new[] { "Microsoft.Build.dll", "Microsoft.Build.Framework.dll", "Microsoft.Build.Utilities.Core.dll", - "Microsoft.Build.Tasks.Core.dll", "MSBuild.runtimeconfig.json", "MSBuild.deps.json" }) - { + "Microsoft.Build.Tasks.Core.dll", "MSBuild.runtimeconfig.json", "MSBuild.deps.json" } + ) { string path = Path.Combine(sdkRoot, name); if (File.Exists(path)) + { inputs.Add(path); + } } string compiler = Path.Combine(sdkRoot, "Roslyn", "bincore"); if (Directory.Exists(compiler)) + { foreach (string path in Directory.EnumerateFiles(compiler)) + { inputs.Add(path); + } + } using var digest = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); var hashes = new Dictionary(paths); foreach (string declaration in declarations) + { digest.AppendData(Encoding.UTF8.GetBytes(declaration + "\n")); + } foreach (string input in inputs.Order(paths)) { cancellation.ThrowIfCancellationRequested(); @@ -122,8 +170,13 @@ CancellationToken cancellation digest.AppendData(hash); hashes.Add(input, Convert.ToHexString(hash)); } - return new TaskRuntimeRequestSnapshot(Convert.ToHexString(digest.GetHashAndReset()), needsRestore, - new System.Collections.ObjectModel.ReadOnlyDictionary(hashes), declarations.AsReadOnly(), restoreRequests.AsReadOnly()); + return new TaskRuntimeRequestSnapshot( + Convert.ToHexString(digest.GetHashAndReset()), + needsRestore, + new System.Collections.ObjectModel.ReadOnlyDictionary(hashes), + declarations.AsReadOnly(), + restoreRequests.AsReadOnly() + ); } private static bool IsInputProperty(string name) diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestSnapshot.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestSnapshot.cs index 171151387..8100ece66 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestSnapshot.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestSnapshot.cs @@ -14,12 +14,22 @@ IReadOnlyList restoreRequests internal string DescribeChanges(TaskRuntimeRequestSnapshot current) { string[] changed = inputs.Keys.Union(current.inputs.Keys, StringComparer.Ordinal) - .Where(path => !inputs.TryGetValue(path, out string? planned) - || !current.inputs.TryGetValue(path, out string? actual) || planned != actual).Take(8).ToArray(); + .Where(path => ( + !inputs.TryGetValue(path, out string? planned) + || !current.inputs.TryGetValue(path, out string? actual) || planned != actual + )) + .Take(8) + .ToArray(); if (changed.Length > 0) + { return "Changed files: " + string.Join("; ", changed); - return "Changed declarations: " + string.Join("; ", declarations.Except(current.declarations) - .Concat(current.declarations.Except(declarations)).Take(8)); + } + return "Changed declarations: " + string.Join( + "; ", + declarations.Except(current.declarations) + .Concat(current.declarations.Except(declarations)) + .Take(8) + ); } } diff --git a/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs b/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs index f5481b72c..b56fb0b77 100644 --- a/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs +++ b/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs @@ -12,6 +12,7 @@ using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.IO; using Inno.Rendering; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.Tasks; @@ -87,14 +88,18 @@ public override bool Execute() { m_cancellation = cancellation; if (m_canceled) + { cancellation.Cancel(); + } } try { var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); BgfxShaderTargetProfile platform = StandardBuildDistribution.Create(execution).ResolveShaderTarget(new BuildTargetId(Target)); if (!GraphicsApi.TryParse(Renderer, out GraphicsApi renderer)) + { throw new ArgumentException("The shader platform or rendering API is invalid."); + } ToolRunner tools = PrepareTools(cancellation.Token, out string compilerFingerprint, out BuildArtifactReadLease toolLease); using BuildArtifactReadLease toolOwnership = toolLease; CompileProduct(tools, compilerFingerprint, platform, renderer, cancellation.Token); @@ -108,7 +113,9 @@ public override bool Execute() finally { lock (m_gate) + { m_cancellation = null; + } } } @@ -137,49 +144,102 @@ out BuildArtifactReadLease reading NativeBuildContext context = new(EngineRoot, "release"); var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); context = context.WithBindingGenerator(StandardBuildDistribution.Create(execution).build.ResolveBindingGenerator(ToolTarget)); - string cacheKey = "Inno.Build.ShaderTools|" + context.engineRoot + "|" + context.configuration + "|" + ToolTarget + "|" + NativeDependencyManifestPath; + string cacheKey = "Inno.Build.ShaderTools|" + + context.engineRoot + + "|" + + context.configuration + + "|" + + ToolTarget + + "|" + + NativeDependencyManifestPath; IBuildEngine4 engine = BuildEngine as IBuildEngine4 ?? throw new InvalidOperationException("Offline tool preparation requires MSBuild's build-lifetime task ownership."); - string leasePath = Path.Combine(context.engineRoot, "artifacts", "build-tools", "tasks", - "native", ToolTarget + "-" + context.configuration + ".lock"); + string leasePath = Path.Combine( + context.engineRoot, + "artifacts", + "build-tools", + "tasks", + "native", + ToolTarget + "-" + context.configuration + ".lock" + ); using FileLease lease = FileLease.AcquireAsync(leasePath, Timeout.InfiniteTimeSpan, cancellationToken) - .GetAwaiter().GetResult(); - using FileLease publicationUse = new BuildCachePublisher(Path.Combine(context.engineRoot, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact) - .AcquireUseAsync(cancellationToken).AsTask().GetAwaiter().GetResult(); + .GetAwaiter() + .GetResult(); + using FileLease publicationUse = new BuildCachePublisher( + Path.Combine(context.engineRoot, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ) + .AcquireUseAsync(cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult(); if (NativeDependencyManifestPath.Length != 0) { - var selected = NativeDependencyManifest.SelectAsync(EngineRoot, NativeDependencyManifestPath, ToolTarget, - context.configuration, StandardBuildDistribution.Create(execution).build.ResolveNativeProduct(ToolTarget, "shader-tools").plan, - cancellationToken).GetAwaiter().GetResult(); + var selected = NativeDependencyManifest.SelectAsync( + EngineRoot, + NativeDependencyManifestPath, + ToolTarget, + context.configuration, + StandardBuildDistribution.Create(execution).build.ResolveNativeProduct(ToolTarget, "shader-tools").plan, + cancellationToken + ).GetAwaiter().GetResult(); cacheKey += "|" + string.Join("|", selected.Select(static asset => asset.sha256).Order(StringComparer.Ordinal)); } // Only neutral file names cross task load contexts. MSBuild releases the record when this build ends. string[]? record = engine.GetRegisteredTaskObject(cacheKey, RegisteredTaskObjectLifetime.Build) as string[]; if (record is not null && (record.Length < 3 || !BuildArtifactManifest.IsComplete(record[0], record[1], ["Outputs", "Metadata"]))) + { throw new InvalidDataException("The build-owned offline tool product changed after preparation."); + } if (record is null) { var distribution = StandardBuildDistribution.Create(execution).build; if (NativeDependencyManifestPath.Length == 0) - context = context.WithToolchain(distribution.ResolveNativeToolchain(ToolTarget) - .ResolveAsync(context, execution.host, ToolTarget, cancellationToken).AsTask().GetAwaiter().GetResult()); + { + context = context.WithToolchain( + distribution.ResolveNativeToolchain(ToolTarget) + .ResolveAsync(context, execution.host, ToolTarget, cancellationToken) + .AsTask() + .GetAwaiter() + .GetResult() + ); + } NativeProductContribution contribution = distribution.ResolveNativeProduct(ToolTarget, "shader-tools"); ProductNativeBuildPlan plan = contribution.plan; StandardBuildCaches.CreateOwners(context.engineRoot, plan.steps.Select(static step => step.component).ToArray()); using ProductNativeBuildResult products = NativeDependencyManifestPath.Length == 0 - ? contribution.BuildAsync(context, cancellationToken).GetAwaiter().GetResult() - : NativeDependencyManifest.AcquireAsync(EngineRoot, NativeDependencyManifestPath, ToolTarget, - context.configuration, plan, cancellationToken).GetAwaiter().GetResult(); + ? contribution.BuildAsync(context, cancellationToken).GetAwaiter().GetResult() + : NativeDependencyManifest.AcquireAsync( + EngineRoot, + NativeDependencyManifestPath, + ToolTarget, + context.configuration, + plan, + cancellationToken + ).GetAwaiter().GetResult(); NativeBuildProduct product = products.Single(); record = [product.directory, product.fingerprint, .. product.files]; engine.RegisterTaskObject(cacheKey, record, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: false); - Log.LogMessage(MessageImportance.High, + Log.LogMessage( + MessageImportance.High, "INNO-SHADER-TOOLS prepared {0}; hashedFiles={1}; hashedBytes={2}; nativeProcesses={3}", - product.fingerprint, context.statistics.hashedFiles, context.statistics.hashedBytes, - context.statistics.nativeProcesses); + product.fingerprint, + context.statistics.hashedFiles, + context.statistics.hashedBytes, + context.statistics.nativeProcesses + ); } - reading = BuildArtifactReadLease.AcquireAsync(record[0], Path.Combine(EngineRoot, "artifacts", "native"), record[1], ["Outputs", "Metadata"], cancellationToken) - .AsTask().GetAwaiter().GetResult(); + reading = BuildArtifactReadLease + .AcquireAsync( + record[0], + Path.Combine(EngineRoot, "artifacts", "native"), + record[1], + ["Outputs", "Metadata"], + cancellationToken + ) + .AsTask() + .GetAwaiter() + .GetResult(); try { string extension = execution.host.services.executableExtension; @@ -210,16 +270,30 @@ CancellationToken cancellationToken string output = Path.GetFullPath(OutputFile); string outputs = Path.GetDirectoryName(output)!; if (Path.GetFileName(outputs) != "Outputs") + { throw new ArgumentException("A shader product must be published inside its owned Outputs directory.", nameof(OutputFile)); + } string directory = Path.GetDirectoryName(outputs)!; string runtime = Path.GetDirectoryName(typeof(CompileShaderTask).Assembly.Location)!; using FileLease lease = FileLease.AcquireAsync(directory + ".lock", Timeout.InfiniteTimeSpan, cancellationToken) - .GetAwaiter().GetResult(); + .GetAwaiter() + .GetResult(); ShaderBuildInputs source = ShaderBuildInputs.Capture(AssetRoot, cancellationToken); - string[] declarations = [source.fingerprint, compilerFingerprint, platform.id, platform.Resolve(renderer).key, - Renderer, Configuration, ShaderPath, Path.GetFileName(output)]; - NativeBuildInput[] inputs = Directory.EnumerateFiles(runtime, "*.dll").Order(StringComparer.Ordinal) - .Select(path => new NativeBuildInput("compiler-runtime/" + Path.GetFileName(path), path)).ToArray(); + string[] declarations = + [ + source.fingerprint, + compilerFingerprint, + platform.id, + platform.Resolve(renderer).key, + Renderer, + Configuration, + ShaderPath, + Path.GetFileName(output) + ]; + NativeBuildInput[] inputs = Directory.EnumerateFiles(runtime, "*.dll") + .Order(StringComparer.Ordinal) + .Select(path => new NativeBuildInput("compiler-runtime/" + Path.GetFileName(path), path)) + .ToArray(); string fingerprint = NativeBuildFingerprint.Create(declarations, inputs, cancellationToken); if (BuildArtifactManifest.IsComplete(directory, fingerprint, ["Outputs", "Metadata"])) { @@ -227,21 +301,35 @@ CancellationToken cancellationToken return; } using ProcessOwnedDirectory candidateOwner = ProcessOwnedDirectory.CreateAsync(Path.GetDirectoryName(directory)!, cancellationToken) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); string candidate = candidateOwner.directory; string candidateOutputs = Path.Combine(candidate, "Outputs"); Directory.CreateDirectory(candidateOutputs); try { using (ProcessOwnedDirectory compilation = StandardBuildCaches.CreateShaderWorkspaceAsync(EngineRoot, cancellationToken) - .AsTask().GetAwaiter().GetResult()) - { - ShaderArtifactBuilder.CompileGraphicsProgram(source, compilation, ShaderPath, platform, renderer, - Path.Combine(candidateOutputs, Path.GetFileName(output)), tools, cancellationToken); + .AsTask() + .GetAwaiter() + .GetResult() + ) { + ShaderArtifactBuilder.CompileGraphicsProgram( + source, + compilation, + ShaderPath, + platform, + renderer, + Path.Combine(candidateOutputs, Path.GetFileName(output)), + tools, + cancellationToken + ); } source.VerifyUnchanged(cancellationToken); if (NativeBuildFingerprint.Create(declarations, inputs, cancellationToken) != fingerprint) + { throw new InvalidDataException("Shader inputs changed during compilation; the candidate was not published."); + } BuildArtifactManifest.Write(candidate, fingerprint, ["Outputs", "Metadata"]); cancellationToken.ThrowIfCancellationRequested(); try diff --git a/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs b/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs index fa66a29da..53f639d55 100644 --- a/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs +++ b/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs @@ -8,6 +8,7 @@ using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.Tasks; @@ -26,58 +27,70 @@ public sealed class GenerateBindingsTask : BuildTask, ICancelableTask /// [Required] public string EngineRoot { get; set; } = string.Empty; + /// /// Gets or sets the stable component identity declared by the sole binding definition. /// [Required] public string ComponentId { get; set; } = string.Empty; + /// /// Gets or sets the absolute Native owner project, which must belong to this checkout. /// [Required] public string ComponentProject { get; set; } = string.Empty; + /// /// Gets or sets the sole literal definition consumed by both the project and direct generation. /// [Required] public string BindingDefinition { get; set; } = string.Empty; + /// /// Gets or sets the explicit configuration identity selected from the definition. /// [Required] public string TargetId { get; set; } = string.Empty; + /// /// Gets or sets HostSource or TargetArtifacts without deriving publication from a path. /// [Required] public string OutputMode { get; set; } = string.Empty; + /// /// Gets or sets the explicitly selected managed SDK host used to compose the target toolchain. /// [Required] public string DotnetHost { get; set; } = string.Empty; + /// /// Gets or sets comparison without publication. /// public bool CheckOnly { get; set; } + /// /// Gets or sets an optional request-owned descriptor destination written only after success. /// public string DescriptorOutputPath { get; set; } = string.Empty; + /// /// Gets or sets an optional expected identity; stale requests fail before generation. /// public string ExpectedFingerprint { get; set; } = string.Empty; + /// /// Gets the single source selected after complete publication or successful comparison. /// [Output] public string GeneratedBindings { get; private set; } = string.Empty; + /// /// Gets the complete validated input identity. /// [Output] public string GenerationFingerprint { get; private set; } = string.Empty; + /// /// Gets whether the selected generated context requires runtime-import initialization. /// @@ -90,6 +103,7 @@ public sealed class GenerateBindingsTask : BuildTask, ICancelableTask /// [Output] public string LibraryKind { get; private set; } = string.Empty; + /// /// Gets the complete native artifacts and compilation requirements selected by this operation. /// @@ -114,8 +128,12 @@ public sealed class GenerateBindingsTask : BuildTask, ICancelableTask public void Cancel() { lock (m_lifecycle) + { if (!m_completed) + { m_cancellation.Cancel(); + } + } } /// @@ -146,31 +164,50 @@ public override bool Execute() CancellationToken cancellation = m_cancellation.Token; cancellation.ThrowIfCancellationRequested(); if (!Enum.TryParse(OutputMode, out NativeBindingOutputMode mode) || !Enum.IsDefined(mode)) + { throw new ArgumentException("Binding output mode must be explicitly declared.", nameof(OutputMode)); + } string root = Path.GetFullPath(EngineRoot); string project = Path.GetRelativePath(root, Path.GetFullPath(ComponentProject)).Replace('\\', '/'); string definition = Path.GetRelativePath(root, Path.GetFullPath(BindingDefinition)).Replace('\\', '/'); - var owner = new NativeComponentDescriptor(ComponentId, project, project, - bindingDefinition: definition); + var owner = new NativeComponentDescriptor(ComponentId, project, project, bindingDefinition: definition); var context = new NativeBuildContext(root, "release"); BuildCompositionContext captured = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(TargetId)); - var execution = new BuildCompositionContext(DotnetHost, captured.applicationDirectory, - captured.host, captured.toolsTarget); + var execution = new BuildCompositionContext( + DotnetHost, + captured.applicationDirectory, + captured.host, + captured.toolsTarget + ); BuildDistribution distribution = StandardBuildDistribution.Create(execution).build; if (NativeDependencyManifestPath.Length != 0) { if (string.IsNullOrWhiteSpace(ProductId)) + { throw new InvalidDataException("Consume-only binding generation requires its explicit product selection."); + } ProductNativeBuildPlan plan = distribution.ResolveNativeProduct(TargetId, ProductId).plan; - if (!plan.steps.Any(step => step.id == ComponentId && step.component.nativeProject == project - && step.component.bindingDefinition == definition)) + if (!plan.steps.Any(step => ( + step.id == ComponentId && step.component.nativeProject == project + && step.component.bindingDefinition == definition + ))) { throw new InvalidDataException("The selected product does not own this binding component: " + project); - using ProductNativeBuildResult products = NativeDependencyManifest.AcquireAsync(root, - NativeDependencyManifestPath, TargetId, Configuration.ToLowerInvariant(), plan, cancellation).GetAwaiter().GetResult(); + } + using ProductNativeBuildResult products = NativeDependencyManifest.AcquireAsync( + root, + NativeDependencyManifestPath, + TargetId, + Configuration.ToLowerInvariant(), + plan, + cancellation + ).GetAwaiter().GetResult(); NativeBindingGenerationDescriptor imported = products.bindingGenerations.TryGetValue(project, out var binding) - ? binding : throw new InvalidDataException("The selected dependency does not contain its required bindings."); + ? binding + : throw new InvalidDataException("The selected dependency does not contain its required bindings."); if (ExpectedFingerprint.Length != 0 && ExpectedFingerprint != imported.fingerprint) + { throw new InvalidDataException("The dependency binding identity differs from the managed build selection."); + } LibraryKind = plan.steps.Single(step => step.id == ComponentId).options.libraryKind.ToString(); SetOutputs(imported); return true; @@ -178,34 +215,54 @@ public override bool Execute() INativeBindingGenerator generator = distribution.ResolveBindingGenerator(TargetId); context = context.WithBindingGenerator(generator); NativeToolchainSelection toolchain = distribution.ResolveNativeToolchain(TargetId) - .ResolveAsync(context, execution.host, TargetId, cancellation).AsTask().GetAwaiter().GetResult(); + .ResolveAsync(context, execution.host, TargetId, cancellation) + .AsTask() + .GetAwaiter() + .GetResult(); context = context.WithToolchain(toolchain); - Dictionary? expected = ExpectedFingerprint.Length == 0 ? null - : new(StringComparer.Ordinal) { [owner.nativeProject] = ExpectedFingerprint }; + Dictionary? expected = ExpectedFingerprint.Length == 0 + ? null + : new(StringComparer.Ordinal) { [owner.nativeProject] = ExpectedFingerprint }; // A source project can also host an offline producer that owns no runtime bindings. NativeComponentBuildOptions[] configured = distribution.platforms .Where(platform => platform.descriptor.id.value == TargetId) .SelectMany(static platform => platform.nativeProducts.Values) .SelectMany(static product => product.plan.steps) - .Where(step => step.component.id == owner.id && step.component.nativeProject == owner.nativeProject - && step.component.bindingDefinition is not null) - .Select(static step => step.options).ToArray(); + .Where(step => ( + step.component.id == owner.id && step.component.nativeProject == owner.nativeProject + && step.component.bindingDefinition is not null + )) + .Select(static step => step.options) + .ToArray(); NativeComponentBuildOptions? selectedOptions = configured.FirstOrDefault(); - if (selectedOptions is not null && configured.Any(options => options.libraryKind != selectedOptions.libraryKind + if (selectedOptions is not null && configured.Any(options => ( + options.libraryKind != selectedOptions.libraryKind || options.bindingLibraryName != selectedOptions.bindingLibraryName - || !options.bindingIncludeDirectories.SequenceEqual(selectedOptions.bindingIncludeDirectories, StringComparer.Ordinal))) - throw new InvalidOperationException($"The registered products for target '{TargetId}' declare ambiguous binding inputs for component '{ComponentId}' in '{project}'."); - Dictionary? componentOptions = selectedOptions is null ? null + || !options.bindingIncludeDirectories.SequenceEqual(selectedOptions.bindingIncludeDirectories, StringComparer.Ordinal) + ))) { + throw new InvalidOperationException( + $"The registered products for target '{TargetId}' declare ambiguous binding inputs for component '{ComponentId}' in '{project}'." + ); + } + Dictionary? componentOptions = selectedOptions is null + ? null : new(StringComparer.Ordinal) { [owner.nativeProject] = selectedOptions }; var request = new NativeBindingGenerationRequest([owner], TargetId, mode, CheckOnly, expected, componentOptions); using NativeBindingGenerationResult closure = generator.GenerateAsync(context, request, cancellation) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); NativeBindingGenerationDescriptor result = closure[owner.nativeProject]; LibraryKind = selectedOptions?.libraryKind.ToString() ?? string.Empty; SetOutputs(result); - Log.LogMessage(MessageImportance.High, + Log.LogMessage( + MessageImportance.High, "INNO-BINDINGS-PREPARE project={0} fingerprint={1} batches={2} generations={3}", - project, result.fingerprint, context.statistics.bindingBatches, context.statistics.bindingGenerations); + project, + result.fingerprint, + context.statistics.bindingBatches, + context.statistics.bindingGenerations + ); return true; } catch (Exception failure) @@ -222,10 +279,13 @@ public override bool Execute() } } } + private void SetOutputs(NativeBindingGenerationDescriptor result) { if (DescriptorOutputPath.Length != 0) + { result.Write(DescriptorOutputPath); + } GeneratedBindings = result.bindingsPath; GenerationFingerprint = result.fingerprint; UsesRuntimeImports = result.usesRuntimeImports; @@ -233,5 +293,4 @@ private void SetOutputs(NativeBindingGenerationDescriptor result) ArtifactDirectory = result.artifactDirectory; ArtifactOwnerDirectory = result.artifactOwnerDirectory; } - } diff --git a/build/tasks/Inno.Build.Tasks/MaintainBuildCachesTask.cs b/build/tasks/Inno.Build.Tasks/MaintainBuildCachesTask.cs index 7b231fe0a..675fbd249 100644 --- a/build/tasks/Inno.Build.Tasks/MaintainBuildCachesTask.cs +++ b/build/tasks/Inno.Build.Tasks/MaintainBuildCachesTask.cs @@ -2,6 +2,7 @@ using System.Threading; using Microsoft.Build.Framework; using Inno.Build.Toolchains; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.Tasks; @@ -27,8 +28,14 @@ public override bool Execute() { try { - BuildMaintenanceApplication.CleanAsync(EngineRoot, new BuildCachePolicy(), false, false, null, - CancellationToken.None).GetAwaiter().GetResult(); + BuildMaintenanceApplication.CleanAsync( + EngineRoot, + new BuildCachePolicy(), + false, + false, + null, + CancellationToken.None + ).GetAwaiter().GetResult(); Log.LogMessage(MessageImportance.High, "INNO-CACHE-MAINTENANCE root=Editor budgetSeconds=5"); } catch (Exception failure) diff --git a/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs b/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs index cc8a87375..544441918 100644 --- a/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs +++ b/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs @@ -10,6 +10,7 @@ using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; using Inno.Core.IO; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.Tasks; @@ -81,7 +82,9 @@ public override bool Execute() { m_cancellation = cancellation; if (m_canceled) + { cancellation.Cancel(); + } } try { @@ -92,40 +95,62 @@ public override bool Execute() ProductNativeBuildPlan plan = contribution.plan; if (NativeDependencyManifestPath.Length != 0) { - using ProductNativeBuildResult imported = NativeDependencyManifest.AcquireAsync(EngineRoot, - NativeDependencyManifestPath, TargetId, Configuration.ToLowerInvariant(), plan, cancellation.Token) - .GetAwaiter().GetResult(); + using ProductNativeBuildResult imported = NativeDependencyManifest + .AcquireAsync( + EngineRoot, + NativeDependencyManifestPath, + TargetId, + Configuration.ToLowerInvariant(), + plan, + cancellation.Token + ) + .GetAwaiter() + .GetResult(); Deploy(imported, plan, cancellation.Token); - Log.LogMessage(MessageImportance.High, - $"INNO-NATIVE-CONSUME products={imported.Count} processes=0 bindingGenerations=0 elapsedMs={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F1}"); + Log.LogMessage( + MessageImportance.High, + $"INNO-NATIVE-CONSUME products={imported.Count} processes=0 bindingGenerations=0 elapsedMs={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F1}" + ); return true; } var context = new NativeBuildContext(EngineRoot, Configuration.ToLowerInvariant()) .WithBindingGenerator(distribution.ResolveBindingGenerator(TargetId)); NativeToolchainSelection toolchain = distribution.ResolveNativeToolchain(TargetId) - .ResolveAsync(context, execution.host, TargetId, cancellation.Token).AsTask().GetAwaiter().GetResult(); + .ResolveAsync(context, execution.host, TargetId, cancellation.Token) + .AsTask() + .GetAwaiter() + .GetResult(); context = context.WithToolchain(toolchain); StandardBuildCaches.CreateOwners(context.engineRoot, plan.steps.Select(static step => step.component).ToArray()); IBuildEngine4 engine = BuildEngine as IBuildEngine4 - ?? throw new InvalidOperationException("Native preparation requires MSBuild build-lifetime ownership."); + ?? throw new InvalidOperationException("Native preparation requires MSBuild build-lifetime ownership."); string scope = NativeBuildFingerprint.Create([context.engineRoot, context.configuration, TargetId, plan.productId], []); string cacheKey = "Inno.Build.NativePreparation/" + scope; - using FileLease preparation = AcquirePreparation(engine, - Path.Combine(context.engineRoot, "artifacts", "build-tools", "tasks", "native", scope + ".lock"), cancellation.Token); + using FileLease preparation = AcquirePreparation( + engine, + Path.Combine(context.engineRoot, "artifacts", "build-tools", "tasks", "native", scope + ".lock"), + cancellation.Token + ); string[][][] candidates = engine.GetRegisteredTaskObject(cacheKey, RegisteredTaskObjectLifetime.Build) as string[][][] ?? []; ProductNativeBuildResult? prepared = null; string requestIdentity = string.Empty; foreach (string[][] candidate in candidates) { string identity = candidate[0][1]; - prepared = ProductNativePreparation.TryAcquireAsync(context, plan, candidate, identity, cancellation.Token).GetAwaiter().GetResult(); + prepared = ProductNativePreparation.TryAcquireAsync(context, plan, candidate, identity, cancellation.Token) + .GetAwaiter() + .GetResult(); if (prepared is null) + { continue; + } requestIdentity = identity; break; } if (prepared is null) + { requestIdentity = ProductNativePreparation.FreezeAsync(context, plan, cancellation.Token).GetAwaiter().GetResult(); + } bool reused = prepared is not null; using var products = prepared ?? contribution.BuildAsync(context, cancellation.Token).GetAwaiter().GetResult(); cancellation.Token.ThrowIfCancellationRequested(); @@ -141,17 +166,23 @@ public override bool Execute() engine.RegisterTaskObject(cacheKey, retained, RegisteredTaskObjectLifetime.Build, allowEarlyCollection: false); } NativeBuildStatistics statistics = context.statistics; - Log.LogMessage(MessageImportance.High, + Log.LogMessage( + MessageImportance.High, $"INNO-NATIVE-PREPARE request={requestIdentity} elapsedMs={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F1} " + $"hashedFiles={statistics.hashedFiles} hashedBytes={statistics.hashedBytes} " + $"processes={statistics.nativeProcesses} products={products.Count} " + $"reusedPreparation={(reused ? 1 : 0)} " + $"bindingBatches={statistics.bindingBatches} bindingGenerations={statistics.bindingGenerations} " + $"outputFiles={statistics.outputFiles} outputBytes={statistics.outputBytes} " - + $"materializedBytes={statistics.materializedBytes} managedProcesses={statistics.managedProcesses}"); + + $"materializedBytes={statistics.materializedBytes} managedProcesses={statistics.managedProcesses}" + ); foreach (NativeBuildPhaseStatistics phase in statistics.phases) - Log.LogMessage(MessageImportance.High, - $"INNO-NATIVE-PHASE name={phase.phase} files={phase.files} bytes={phase.bytes} reusedReads={phase.reusedReads}"); + { + Log.LogMessage( + MessageImportance.High, + $"INNO-NATIVE-PHASE name={phase.phase} files={phase.files} bytes={phase.bytes} reusedReads={phase.reusedReads}" + ); + } return true; } catch (Exception failure) @@ -162,7 +193,9 @@ public override bool Execute() finally { lock (m_gate) + { m_cancellation = null; + } } } @@ -186,13 +219,20 @@ CancellationToken cancellationToken var generations = products.bindingGenerations; var linkage = plan.steps.Where(step => generations.ContainsKey(step.component.nativeProject)) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, - static group => group.Select(step => step.options.libraryKind).Distinct().Single(), StringComparer.Ordinal); + .ToDictionary( + static group => group.Key, + static group => group.Select(step => step.options.libraryKind).Distinct().Single(), + StringComparer.Ordinal + ); if (BindingSelectionInputPath.Length != 0) + { NativeBindingGenerationDescriptor.ValidateSelection(BindingSelectionInputPath, generations, linkage); + } ProductNativeDeployment.InstallAsync(products, plan, OutputDirectory, cancellationToken).GetAwaiter().GetResult(); if (BindingSelectionOutputPath.Length != 0) + { NativeBindingGenerationDescriptor.WriteSelection(BindingSelectionOutputPath, generations, linkage); + } } private static FileLease AcquirePreparation( @@ -202,7 +242,9 @@ CancellationToken cancellation ) { System.Threading.Tasks.Task pending = FileLease.AcquireAsync(path, Timeout.InfiniteTimeSpan, cancellation).AsTask(); if (pending.IsCompleted) + { return pending.GetAwaiter().GetResult(); + } engine.Yield(); try { diff --git a/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs b/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs index 175879237..e058f931a 100644 --- a/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs +++ b/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs @@ -7,6 +7,7 @@ using Inno.Build.Distribution.Standard; using Inno.Build.SupportPacks; using Inno.Build.Toolchains; + using BuildTask = Microsoft.Build.Utilities.Task; namespace Inno.Build.Tasks; @@ -62,19 +63,29 @@ public override bool Execute() { m_cancellation = cancellation; if (m_canceled) + { cancellation.Cancel(); + } } try { var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); - var context = new BuildCompositionContext(ToolchainEnvironment.ResolveExecutable(DotnetHost), - AppContext.BaseDirectory, execution.host, execution.toolsTarget); - using PlayerSupportPackPublication installed = StandardBuildDistribution.Create(context).build.supportPacks.PublishAsync( - EngineRoot, OutputRoot, new BuildTargetId(Target), DotnetHost, cancellation.Token) - .AsTask().GetAwaiter().GetResult(); + var context = new BuildCompositionContext( + ToolchainEnvironment.ResolveExecutable(DotnetHost), + AppContext.BaseDirectory, + execution.host, + execution.toolsTarget + ); + using PlayerSupportPackPublication installed = StandardBuildDistribution.Create(context).build.supportPacks + .PublishAsync(EngineRoot, OutputRoot, new BuildTargetId(Target), DotnetHost, cancellation.Token) + .AsTask() + .GetAwaiter() + .GetResult(); Log.LogMessage(MessageImportance.Normal, "Installed Player Support Pack: {0}", installed.directory); foreach (string diagnostic in installed.diagnostics) + { Log.LogWarning(diagnostic); + } return true; } catch (Exception failure) @@ -85,7 +96,9 @@ public override bool Execute() finally { lock (m_gate) + { m_cancellation = null; + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs b/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs index 0eac115e5..0b942e0d7 100644 --- a/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs +++ b/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs @@ -3,8 +3,8 @@ using System.IO; using System.Linq; using System.Security.Cryptography; -using System.Text.Json; using System.Text; +using System.Text.Json; using Inno.Core.IO; namespace Inno.Build.Toolchains; @@ -46,7 +46,9 @@ public static void Write( ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint); Dictionary files = ReadFiles(directory, outputDirectories, context); if (files.Count == 0) + { throw new InvalidDataException("A completed artifact must contain output files."); + } using var bytes = new MemoryStream(); using (var writer = new Utf8JsonWriter(bytes)) { @@ -54,7 +56,9 @@ public static void Write( writer.WriteString("fingerprint", fingerprint); writer.WriteStartObject("files"); foreach (var file in files.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) + { writer.WriteString(file.Key, file.Value); + } writer.WriteEndObject(); writer.WriteEndObject(); } @@ -93,17 +97,24 @@ public static bool IsComplete( ) { string path = Path.Combine(directory, C_FILE_NAME); if (!File.Exists(path)) + { return false; + } Dictionary expected; try { using JsonDocument manifest = JsonDocument.Parse(File.ReadAllBytes(path)); JsonElement data = manifest.RootElement; - if (!data.EnumerateObject().Select(static entry => entry.Name).Order(StringComparer.Ordinal) + if (!data.EnumerateObject() + .Select(static entry => entry.Name) + .Order(StringComparer.Ordinal) .SequenceEqual(new[] { "files", "fingerprint" }, StringComparer.Ordinal) - || data.GetProperty("fingerprint").GetString() != fingerprint) + || data.GetProperty("fingerprint").GetString() != fingerprint + ) { return false; - expected = data.GetProperty("files").EnumerateObject() + } + expected = data.GetProperty("files") + .EnumerateObject() .ToDictionary(static entry => entry.Name, static entry => entry.Value.GetString()!, StringComparer.Ordinal); } catch (Exception failure) when (failure is JsonException or InvalidOperationException or ArgumentException) @@ -111,11 +122,13 @@ public static bool IsComplete( return false; } if (expected.Count == 0) + { return false; + } Dictionary files = ReadFiles(directory, outputDirectories, context); return files.Count == expected.Count - && PathBoundary.EnumerateFiles(directory).Count() == files.Count + 1 - && files.All(pair => expected.TryGetValue(pair.Key, out string? value) && pair.Value == value); + && PathBoundary.EnumerateFiles(directory).Count() == files.Count + 1 + && files.All(pair => expected.TryGetValue(pair.Key, out string? value) && pair.Value == value); } private static Dictionary ReadFiles( @@ -132,30 +145,39 @@ private static Dictionary ReadFiles( string output = Path.GetFullPath(Path.Combine(root, relative)); string check = Path.GetRelativePath(root, output); if (Path.IsPathRooted(check) || check is "." or ".." - || check.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + || check.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) + ) { throw new ArgumentException("An artifact output directory must be contained in its root.", nameof(outputDirectories)); + } if (!Directory.Exists(output)) + { continue; + } foreach (string path in PathBoundary.EnumerateFiles(output).Order(StringComparer.Ordinal)) { using FileStream input = File.OpenRead(path); - files.Add(Path.GetRelativePath(root, path).Replace('\\', '/'), - Convert.ToHexStringLower(SHA256.HashData(input))); + files.Add( + Path.GetRelativePath(root, path).Replace('\\', '/'), + Convert.ToHexStringLower(SHA256.HashData(input)) + ); context?.RecordOutputRead(input.Position); } } if (files.Count == 0) + { return files; + } foreach (string path in PathBoundary.EnumerateFiles(root).Order(StringComparer.Ordinal)) { string relative = Path.GetRelativePath(root, path).Replace('\\', '/'); if (relative == C_FILE_NAME || files.ContainsKey(relative)) + { continue; + } using FileStream input = File.OpenRead(path); files.Add(relative, Convert.ToHexStringLower(SHA256.HashData(input))); context?.RecordOutputRead(input.Position); } return files; } - } diff --git a/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs b/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs index 68a849210..13beeb02f 100644 --- a/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs +++ b/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs @@ -61,7 +61,9 @@ BuildArtifactOptions options ) { var buildDir = Path.Combine(buildRoot, options.buildDirName); if (!Directory.Exists(buildDir)) + { throw new DirectoryNotFoundException($"Native artifact directory not found: {buildDir}"); + } var candidates = Directory.EnumerateFiles(buildDir, "*", SearchOption.AllDirectories) .Where(path => @@ -79,8 +81,8 @@ BuildArtifactOptions options var fileName = Path.GetFileName(path); if (!ToolchainEnvironment.ContainsAny(fileName, options.libraryTokens.ToArray()) - || !MatchesConfiguration(Path.GetRelativePath(buildDir, path), config)) - { + || !MatchesConfiguration(Path.GetRelativePath(buildDir, path), config) + ) { return false; } @@ -96,7 +98,9 @@ BuildArtifactOptions options .ToList(); if (candidates.Count == 0) + { throw new FileNotFoundException($"No {config} native artifacts found under {buildDir}."); + } var artifacts = candidates.Select(source => ( source, @@ -104,11 +108,15 @@ BuildArtifactOptions options var duplicate = artifacts.GroupBy(static artifact => artifact.name, StringComparer.OrdinalIgnoreCase) .FirstOrDefault(static group => group.Count() > 1); if (duplicate is not null) + { throw new InvalidOperationException($"Multiple native artifacts produce '{duplicate.Key}'."); + } Directory.CreateDirectory(outputDir); foreach (var artifact in artifacts) + { File.Copy(artifact.source, Path.Combine(outputDir, artifact.name), overwrite: true); + } } private static bool MatchesConfiguration( @@ -117,19 +125,29 @@ string config ) { string name = Path.GetFileNameWithoutExtension(path); if (name.EndsWith("Debug", StringComparison.OrdinalIgnoreCase)) + { return config.Equals("debug", StringComparison.OrdinalIgnoreCase); + } if (name.EndsWith("Release", StringComparison.OrdinalIgnoreCase)) + { return config.Equals("release", StringComparison.OrdinalIgnoreCase); + } string? directory = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(directory)) + { return true; + } string[] segments = directory.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); for (int index = segments.Length - 1; index >= 0; index--) { if (segments[index].Equals("Debug", StringComparison.OrdinalIgnoreCase)) + { return config.Equals("debug", StringComparison.OrdinalIgnoreCase); + } if (segments[index].Equals("Release", StringComparison.OrdinalIgnoreCase)) + { return config.Equals("release", StringComparison.OrdinalIgnoreCase); + } } return true; } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs index 7cace25cc..c6ea7f0a7 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs @@ -19,6 +19,7 @@ public static class BackendPrebuiltArchive private const string C_MANIFEST = "manifest.json"; private const long C_MAX_BYTES = 8L * 1024 * 1024 * 1024; private static readonly DateTimeOffset S_EPOCH = new(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); + private sealed record FileRecord( string owner, string configuration, @@ -26,6 +27,7 @@ private sealed record FileRecord( string path, string sha256 ); + private sealed record Inventory( int version, string target, @@ -65,7 +67,9 @@ public static void Create( using (var zip = new ZipArchive(stream, ZipArchiveMode.Create)) { using (Stream output = Entry(C_MANIFEST).Open()) + { JsonSerializer.Serialize(output, inventory); + } long total = 0; foreach (FileRecord file in inventory.files) { @@ -73,14 +77,19 @@ public static void Create( using FileStream input = File.OpenRead(source); total = checked(total + input.Length); if (total > C_MAX_BYTES) + { throw new InvalidDataException("Backend archive exceeds its size limit."); + } using Stream output = Entry(file.path).Open(); CopyVerified(input, output, file.sha256, input.Length, cancellationToken); } ZipArchiveEntry Entry(string path) { - ZipArchiveEntry entry = zip.CreateEntry(path, path.EndsWith(".zip", StringComparison.Ordinal) ? CompressionLevel.NoCompression : CompressionLevel.Fastest); + ZipArchiveEntry entry = zip.CreateEntry( + path, + path.EndsWith(".zip", StringComparison.Ordinal) ? CompressionLevel.NoCompression : CompressionLevel.Fastest + ); entry.LastWriteTime = S_EPOCH; entry.ExternalAttributes = 0; return entry; @@ -127,18 +136,27 @@ public static async Task ExtractAsync( string output = Path.GetFullPath(destination); string parent = Path.GetDirectoryName(output)!; using FileStream stream = File.OpenRead(archivePath); - if (!IsDigest(sha256) || Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, cancellationToken).ConfigureAwait(false)) != sha256) + if (!IsDigest(sha256) + || Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, cancellationToken).ConfigureAwait(false)) != sha256 + ) { throw new InvalidDataException("The backend platform ZIP differs from its receipt."); + } stream.Position = 0; using var zip = new ZipArchive(stream, ZipArchiveMode.Read); ZipArchiveEntry metadata = zip.GetEntry(C_MANIFEST) ?? throw new InvalidDataException("Missing backend inventory."); if (metadata.Length > 16 * 1024 * 1024 || zip.Entries.Count > 50001) + { throw new InvalidDataException("Backend ZIP inventory exceeds its limit."); + } Inventory inventory; using (Stream input = metadata.Open()) + { inventory = Read(input); + } if (inventory.target != target || zip.Entries.Count != inventory.files.Length + 1) + { throw new InvalidDataException("Backend target or inventory does not match the request."); + } using ProcessOwnedDirectory staging = await ProcessOwnedDirectory.CreateAsync(parent, cancellationToken).ConfigureAwait(false); string payload = Path.Combine(staging.directory, "payload"); Directory.CreateDirectory(payload); @@ -147,10 +165,15 @@ public static async Task ExtractAsync( foreach (ZipArchiveEntry entry in zip.Entries) { if (entry == metadata) + { continue; + } if (!expected.Remove(entry.FullName, out FileRecord? file) || ((entry.ExternalAttributes >> 16) & 0xf000) is not (0 or 0x8000) - || (entry.ExternalAttributes & (int)FileAttributes.ReparsePoint) != 0 || (total = checked(total + entry.Length)) > C_MAX_BYTES) + || (entry.ExternalAttributes & (int)FileAttributes.ReparsePoint) != 0 + || (total = checked(total + entry.Length)) > C_MAX_BYTES + ) { throw new InvalidDataException("Unexpected, duplicate, linked or excessive backend ZIP entry: " + entry.FullName); + } string path = PathBoundary.Resolve(payload, entry.FullName); Directory.CreateDirectory(Path.GetDirectoryName(path)!); using Stream input = entry.Open(); @@ -158,13 +181,20 @@ public static async Task ExtractAsync( CopyVerified(input, targetFile, file.sha256, entry.Length, cancellationToken); } if (expected.Count != 0) + { throw new InvalidDataException("Missing backend ZIP entries."); + } byte[] manifestBytes = JsonSerializer.SerializeToUtf8Bytes(inventory); AtomicFile.WriteAllBytes(Path.Combine(payload, C_MANIFEST), manifestBytes); - AtomicFile.WriteAllBytes(Path.Combine(payload, "receipt.json"), JsonSerializer.SerializeToUtf8Bytes(new - { - target, sha256, manifestSha256 = Convert.ToHexStringLower(SHA256.HashData(manifestBytes)) - })); + AtomicFile.WriteAllBytes( + Path.Combine(payload, "receipt.json"), + JsonSerializer.SerializeToUtf8Bytes(new + { + target, + sha256, + manifestSha256 = Convert.ToHexStringLower(SHA256.HashData(manifestBytes)) + }) + ); AtomicDirectory.Publish(payload, output, cancellationToken); } @@ -172,17 +202,29 @@ private static Inventory Read(Stream input) { Inventory inventory = JsonSerializer.Deserialize(input) ?? throw new InvalidDataException("Missing backend inventory."); if (inventory.version != 1 || string.IsNullOrWhiteSpace(inventory.target) || inventory.files is not { Length: > 0 and <= 50000 }) + { throw new InvalidDataException("Unsupported or empty backend inventory."); + } var paths = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (FileRecord file in inventory.files) { - if (file is null || string.IsNullOrWhiteSpace(file.owner) || string.IsNullOrWhiteSpace(file.configuration) || !IsDigest(file.input) - || !IsDigest(file.sha256) || string.IsNullOrEmpty(file.path) || !paths.Add(file.path) || file.path.Equals(C_MANIFEST, StringComparison.OrdinalIgnoreCase) + if (file is null + || string.IsNullOrWhiteSpace(file.owner) + || string.IsNullOrWhiteSpace(file.configuration) + || !IsDigest(file.input) + || !IsDigest(file.sha256) + || string.IsNullOrEmpty(file.path) + || !paths.Add(file.path) + || file.path.Equals(C_MANIFEST, StringComparison.OrdinalIgnoreCase) || file.path.Equals("receipt.json", StringComparison.OrdinalIgnoreCase) - || file.path.Split('/').Any(static part => part is "" or "." or ".." || part.EndsWith('.') || part.EndsWith(' ') + || file.path.Split('/').Any(static part => ( + part is "" or "." or ".." || part.EndsWith('.') || part.EndsWith(' ') || part.Any(static c => !char.IsAsciiLetterOrDigit(c) && c is not ('.' or '_' or '-')) - || IsReservedName(part))) + || IsReservedName(part) + )) + ) { throw new InvalidDataException("Invalid or duplicated backend file ownership: " + file?.path); + } } return inventory with { files = inventory.files.OrderBy(static file => file.path, StringComparer.Ordinal).ToArray() }; } @@ -191,10 +233,11 @@ private static bool IsReservedName(string part) { string name = part.Split('.')[0].ToUpperInvariant(); return name is "CON" or "PRN" or "AUX" or "NUL" - || name.Length == 4 && name[..3] is ("LPT" or "COM") && name[3] is >= '1' and <= '9'; + || name.Length == 4 && name[..3] is ("LPT" or "COM") && name[3] is >= '1' and <= '9'; } - private static bool IsDigest(string? value) => value is { Length: 64 } && value.All(static c => char.IsAsciiDigit(c) || c is >= 'a' and <= 'f'); + private static bool IsDigest(string? value) + => value is { Length: 64 } && value.All(static c => char.IsAsciiDigit(c) || c is >= 'a' and <= 'f'); private static void CopyVerified( Stream input, @@ -211,11 +254,15 @@ CancellationToken cancellation { cancellation.ThrowIfCancellationRequested(); if ((copied += read) > length) + { throw new InvalidDataException("Backend payload exceeds its declared length."); + } hash.AppendData(buffer, 0, read); output.Write(buffer, 0, read); } if (copied != length || Convert.ToHexStringLower(hash.GetHashAndReset()) != digest) + { throw new InvalidDataException("Backend payload does not match its inventory."); + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs index 1a8298c58..7d195253a 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs @@ -59,8 +59,15 @@ public static async ValueTask AcquireAsync( IReadOnlyList outputDirectories, CancellationToken cancellationToken = default, NativeBuildContext? statistics = null - ) => await TryAcquireAsync(directory, ownerDirectory, fingerprint, outputDirectories, statistics, cancellationToken).ConfigureAwait(false) - ?? throw new InvalidDataException($"Build artifact '{directory}' is missing, damaged or has a different identity."); + ) => await TryAcquireAsync( + directory, + ownerDirectory, + fingerprint, + outputDirectories, + statistics, + cancellationToken + ).ConfigureAwait(false) + ?? throw new InvalidDataException($"Build artifact '{directory}' is missing, damaged or has a different identity."); /// /// Ends artifact access and allows repair or retirement; repeated disposal has no effect. @@ -79,11 +86,18 @@ CancellationToken cancellationToken ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint); ArgumentNullException.ThrowIfNull(outputDirectories); if (!Path.IsPathFullyQualified(directory)) + { throw new ArgumentException("Artifact reading requires an absolute owner path.", nameof(directory)); + } string path = GetLeasePath(directory); BuildCacheCleanupPlan.RequireChild(ownerDirectory, directory); - CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync(Path.Combine(ownerDirectory, "owner.lock"), - path, TimeSpan.FromSeconds(30), shared: true, cancellationToken: cancellationToken).ConfigureAwait(false); + CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync( + Path.Combine(ownerDirectory, "owner.lock"), + path, + TimeSpan.FromSeconds(30), + shared: true, + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs index 1601fdcc1..b559fbb4e 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs @@ -46,10 +46,18 @@ public static async ValueTask AcquireAsync( ) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); if (!Path.IsPathFullyQualified(directory)) + { throw new ArgumentException("Artifact mutation requires an absolute owner path.", nameof(directory)); + } BuildCacheCleanupPlan.RequireChild(ownerDirectory, directory); - return new(await CoordinatedFileLease.AcquireAsync(Path.Combine(ownerDirectory, "owner.lock"), BuildArtifactReadLease.GetLeasePath(directory), - TimeSpan.FromSeconds(30), cancellationToken: cancellationToken).ConfigureAwait(false)); + return new( + await CoordinatedFileLease.AcquireAsync( + Path.Combine(ownerDirectory, "owner.lock"), + BuildArtifactReadLease.GetLeasePath(directory), + TimeSpan.FromSeconds(30), + cancellationToken: cancellationToken + ).ConfigureAwait(false) + ); } /// diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs index 2d750f158..1c45aab71 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs @@ -58,24 +58,35 @@ BuildCacheArtifactRole role ArgumentException.ThrowIfNullOrWhiteSpace(leasePath); ArgumentNullException.ThrowIfNull(dependencies); if (!Path.IsPathFullyQualified(directory) || !Path.IsPathFullyQualified(leasePath) - || dependencies.Any(static path => !Path.IsPathFullyQualified(path))) + || dependencies.Any(static path => !Path.IsPathFullyQualified(path)) + ) { throw new ArgumentException("Cache artifact paths must be absolute."); + } if (bytes < 0) + { throw new ArgumentOutOfRangeException(nameof(bytes)); + } if (targetId is not null && string.IsNullOrWhiteSpace(targetId)) + { throw new ArgumentException("A declared cache target cannot be blank.", nameof(targetId)); + } if (lastUseUtc.Kind != DateTimeKind.Utc) + { throw new ArgumentException("Cache use timestamps must be UTC.", nameof(lastUseUtc)); + } this.directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)); this.leasePath = Path.GetFullPath(leasePath); this.targetId = targetId; this.bytes = bytes; this.lastUseUtc = lastUseUtc; if (!Enum.IsDefined(role)) + { throw new ArgumentOutOfRangeException(nameof(role)); + } this.role = role; - this.dependencies = new ReadOnlyCollection(dependencies.Select(static path => - Path.TrimEndingDirectorySeparator(Path.GetFullPath(path))).ToArray()); + this.dependencies = new ReadOnlyCollection( + dependencies.Select(static path => Path.TrimEndingDirectorySeparator(Path.GetFullPath(path))).ToArray() + ); } /// diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactRole.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactRole.cs index e0d3faf4b..cbd3669a1 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactRole.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactRole.cs @@ -9,12 +9,10 @@ public enum BuildCacheArtifactRole /// A complete immutable generation remains protected by selected products and active readers. /// ImmutableArtifact, - /// /// A mutable compiler workspace may retire when no producer or consumer is active. /// ReusableWorkspace, - /// /// An operation directory remains protected until its exact process owners have exited. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs index 647d69105..c522e6ebd 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs @@ -108,7 +108,9 @@ public static BuildCacheCleanupPlan Create( { BuildCacheCleanupPlan plan = CreateCore(workspace, owners, policy, retireAll, targetId, bounded.Token, elapsed); if (elapsed.Elapsed >= policy.timeBudget) + { throw new TimeoutException("Cache inventory exceeded its operation time budget; no artifact was retired."); + } return plan; } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) @@ -130,7 +132,9 @@ Stopwatch elapsed ArgumentNullException.ThrowIfNull(owners); ArgumentNullException.ThrowIfNull(policy); if (!Path.IsPathFullyQualified(workspace)) + { throw new ArgumentException("Cache cleanup requires an absolute checkout boundary.", nameof(workspace)); + } cancellationToken.ThrowIfCancellationRequested(); string root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(workspace)); BuildCacheOwnerDescriptor[] frozen = owners.ToArray(); @@ -140,23 +144,33 @@ Stopwatch elapsed if (targetId is not null) { ArgumentException.ThrowIfNullOrWhiteSpace(targetId); - protectedPaths.UnionWith(inventory.Protect(inventory.artifacts.Values - .Where(entry => entry.artifact.targetId != targetId).Select(static entry => entry.artifact.directory))); + protectedPaths.UnionWith( + inventory.Protect( + inventory.artifacts.Values + .Where(entry => entry.artifact.targetId != targetId) + .Select(static entry => entry.artifact.directory) + ) + ); } long total = inventory.artifacts.Values.Sum(static entry => entry.artifact.bytes); long protectedSize = protectedPaths.Sum(path => inventory.artifacts[path].artifact.bytes); long free = new DriveInfo(Path.GetPathRoot(root)!).AvailableFreeSpace; - long requested = retireAll ? long.MaxValue : Math.Max(Math.Max(0, total - policy.maximumBytes), - Math.Max(0, policy.minimumFreeBytes - free)); + long requested = retireAll ? long.MaxValue : Math.Max( + Math.Max(0, total - policy.maximumBytes), + Math.Max(0, policy.minimumFreeBytes - free) + ); var selected = new List(); long proposed = 0; foreach (BuildCacheArtifactDescriptor artifact in inventory.artifacts.Values.Select(static entry => entry.artifact) .Where(entry => !protectedPaths.Contains(entry.directory)) - .OrderBy(static entry => entry.lastUseUtc).ThenBy(static entry => entry.directory, StringComparer.Ordinal)) - { + .OrderBy(static entry => entry.lastUseUtc) + .ThenBy(static entry => entry.directory, StringComparer.Ordinal) + ) { cancellationToken.ThrowIfCancellationRequested(); if (proposed >= requested && artifact.role != BuildCacheArtifactRole.ProcessWorkingDirectory) + { continue; + } selected.Add(artifact); proposed = checked(proposed + artifact.bytes); } @@ -188,13 +202,34 @@ public ValueTask ExecuteAsync( cancellationToken.ThrowIfCancellationRequested(); TimeSpan remaining = m_policy.timeBudget - m_elapsed.Elapsed; if (!dryRun && remaining <= TimeSpan.Zero) - return ValueTask.FromResult(new BuildCacheCleanupResult([], candidates.Select(static entry => entry.directory), - new Dictionary(), 0, true)); + { + return ValueTask.FromResult( + new BuildCacheCleanupResult( + [], + candidates.Select(static entry => entry.directory), + new Dictionary(), + 0, + true + ) + ); + } return dryRun - ? ValueTask.FromResult(new BuildCacheCleanupResult([], candidates.Select(static entry => entry.directory), - new Dictionary(), 0, false)) - : BuildCacheRetirement.ExecuteAsync(m_workspace, m_owners, - new BuildCachePolicy(m_policy.maximumBytes, m_policy.minimumFreeBytes, remaining), candidates, cancellationToken); + ? ValueTask.FromResult( + new BuildCacheCleanupResult( + [], + candidates.Select(static entry => entry.directory), + new Dictionary(), + 0, + false + ) + ) + : BuildCacheRetirement.ExecuteAsync( + m_workspace, + m_owners, + new BuildCachePolicy(m_policy.maximumBytes, m_policy.minimumFreeBytes, remaining), + candidates, + cancellationToken + ); } private static void ValidateOwners( @@ -206,12 +241,18 @@ IReadOnlyList owners { BuildCacheOwnerDescriptor owner = owners[index] ?? throw new ArgumentException("A cache owner is null.", nameof(owners)); if (!identities.Add(owner.id)) + { throw new ArgumentException("Cache owner identities must be unique.", nameof(owners)); + } RequireChild(workspace, owner.directory); RequireChild(owner.directory, owner.coordinationPath); for (int previous = 0; previous < index; previous++) + { if (IsContained(owners[previous].directory, owner.directory) || IsContained(owner.directory, owners[previous].directory)) + { throw new ArgumentException("Registered cache boundaries must not overlap.", nameof(owners)); + } + } } } @@ -220,9 +261,13 @@ internal static void RequireChild( string path ) { if (!Path.IsPathFullyQualified(path) || !IsContained(root, path) - || BuildCacheInventory.pathComparer.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)), - Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)))) + || BuildCacheInventory.pathComparer.Equals( + Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)), + Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)) + ) + ) { throw new IOException($"Cache path '{path}' is not a child of owner '{root}'."); + } PathBoundary.RequireUnlinkedPath(root, path); } @@ -232,6 +277,6 @@ string path ) { string relative = Path.GetRelativePath(root, path); return !Path.IsPathRooted(relative) && relative != ".." - && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal); + && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheFileInventory.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheFileInventory.cs index 64c313fab..432c819f0 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheFileInventory.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheFileInventory.cs @@ -28,15 +28,21 @@ CancellationToken cancellation if ((attributes & FileAttributes.ReparsePoint) != 0) { if (role != BuildCacheArtifactRole.ReusableWorkspace || (attributes & FileAttributes.Directory) != 0) + { throw new IOException($"Cache entry '{entry}' cannot contain this filesystem link."); + } ValidateFileLink(directory, entry, cancellation); // A compiler's library-name alias owns no second copy of its target's bytes. continue; } if ((attributes & FileAttributes.Directory) != 0) + { pending.Push(entry); + } else + { bytes = checked(bytes + new FileInfo(entry).Length); + } } } return bytes; @@ -54,14 +60,18 @@ CancellationToken cancellation entry = PathBoundary.RequireContained(directory, entry); PathBoundary.RequireUnlinkedPath(directory, Path.GetDirectoryName(entry)!); if (!visited.Add(entry)) + { throw new IOException($"Workspace file link '{entry}' forms a cycle."); + } var file = new FileInfo(entry); string? target = file.LinkTarget; if (target is null) { PathBoundary.RequireUnlinkedPath(directory, entry); if (!file.Exists || (file.Attributes & FileAttributes.Directory) != 0) + { throw new IOException($"Workspace file link '{entry}' has no regular owned target."); + } return; } entry = Path.GetFullPath(target, Path.GetDirectoryName(entry)!); diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs index c5b265e10..2525d2576 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs @@ -9,13 +9,15 @@ namespace Inno.Build.Toolchains; internal sealed class BuildCacheInventory { internal static readonly StringComparer pathComparer = OperatingSystem.IsWindows() - ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + ? StringComparer.OrdinalIgnoreCase + : StringComparer.Ordinal; - private BuildCacheInventory() - { - } + private BuildCacheInventory() {} + + internal Dictionary artifacts { get; } = new( + pathComparer + ); - internal Dictionary artifacts { get; } = new(pathComparer); internal List roots { get; } = []; internal List retirementOrder { get; } = []; @@ -33,13 +35,19 @@ CancellationToken cancellation foreach (BuildCacheArtifactDescriptor artifact in owner.ReadArtifacts(cancellation)) { if (artifact is null) + { throw new InvalidDataException($"Cache owner '{owner.id}' returned a null artifact."); + } BuildCacheCleanupPlan.RequireChild(owner.directory, artifact.directory); BuildCacheCleanupPlan.RequireChild(owner.directory, artifact.leasePath); if (BuildCacheCleanupPlan.IsContained(artifact.directory, owner.coordinationPath)) + { throw new InvalidDataException("An artifact cannot contain its owner's persistent coordination file."); + } if (!result.artifacts.TryAdd(artifact.directory, (owner, artifact))) + { throw new InvalidDataException("A cache artifact has repeated ownership."); + } } foreach (string path in owner.ReadProtectedArtifacts(cancellation)) { @@ -50,45 +58,72 @@ CancellationToken cancellation bool HasArtifactAncestor(string path) { for (string? current = path; current is not null; current = Path.GetDirectoryName(current)) + { if (result.artifacts.ContainsKey(current)) + { return true; + } + } return false; } foreach (string directory in result.artifacts.Keys) + { if (Path.GetDirectoryName(directory) is string parent && HasArtifactAncestor(parent)) + { throw new InvalidDataException("Cache artifacts must have disjoint ownership boundaries."); + } + } var leasePaths = new HashSet(pathComparer); foreach (var entry in result.artifacts.Values) { if (!leasePaths.Add(entry.artifact.leasePath) || owners.Any(owner => pathComparer.Equals(owner.coordinationPath, entry.artifact.leasePath)) - || HasArtifactAncestor(entry.artifact.leasePath)) + || HasArtifactAncestor(entry.artifact.leasePath) + ) { throw new InvalidDataException("Artifact leases must be distinct persistent files outside all retired directories."); + } } foreach (string root in result.roots) + { if (!result.artifacts.ContainsKey(root)) + { throw new InvalidDataException($"Protected cache root '{root}' has no registered artifact owner."); + } + } var incoming = result.artifacts.Keys.ToDictionary(static path => path, static _ => 0, pathComparer); foreach (var entry in result.artifacts.Values) + { foreach (string dependency in entry.artifact.dependencies.Distinct(pathComparer)) { if (!result.artifacts.ContainsKey(dependency)) + { throw new InvalidDataException($"Cache dependency '{dependency}' has no registered artifact owner."); + } incoming[dependency]++; } - var ready = new Queue(incoming.Where(static entry => entry.Value == 0) - .OrderBy(entry => result.artifacts[entry.Key].artifact.lastUseUtc) - .ThenBy(static entry => entry.Key, StringComparer.Ordinal).Select(static entry => entry.Key)); + } + var ready = new Queue( + incoming.Where(static entry => entry.Value == 0) + .OrderBy(entry => result.artifacts[entry.Key].artifact.lastUseUtc) + .ThenBy(static entry => entry.Key, StringComparer.Ordinal) + .Select(static entry => entry.Key) + ); while (ready.TryDequeue(out string? path)) { cancellation.ThrowIfCancellationRequested(); result.retirementOrder.Add(path); foreach (string dependency in result.artifacts[path].artifact.dependencies.Distinct(pathComparer)) + { if (--incoming[dependency] == 0) + { ready.Enqueue(dependency); + } + } } if (result.retirementOrder.Count != result.artifacts.Count) + { throw new ArgumentException("Cache dependency metadata must not contain cycles."); + } return result; } @@ -99,11 +134,17 @@ internal HashSet Protect(IEnumerable roots) while (pending.TryPop(out string? path)) { if (!artifacts.TryGetValue(path, out var entry)) + { throw new InvalidDataException($"Protected cache path '{path}' has no registered artifact owner."); + } if (!protectedPaths.Add(path)) + { continue; + } foreach (string dependency in entry.artifact.dependencies) + { pending.Push(dependency); + } } return protectedPaths; } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs index 8a4bca706..7b9899556 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs @@ -13,8 +13,7 @@ namespace Inno.Build.Toolchains; internal sealed class BuildCacheInventoryProgress( string workspace, bool readOnly -) -{ +) { internal static void PruneRetired( string workspace, IReadOnlyList owners, @@ -22,10 +21,14 @@ CancellationToken cancellation ) { string root = PathBoundary.RequireUnlinkedPath(workspace, Path.Combine(workspace, "artifacts", "cache-owners", "inventory")); if (!Directory.Exists(root)) + { return; + } // The retirement caller retains every selected publisher gate. Progress never authorizes payload removal. using FileLease writing = FileLease.AcquireAsync(Path.Combine(root, "progress.lock"), TimeSpan.Zero, cancellation) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); foreach (string checkpoint in Directory.EnumerateFiles(root, "*.inventory").Order(StringComparer.Ordinal)) { cancellation.ThrowIfCancellationRequested(); @@ -35,11 +38,15 @@ CancellationToken cancellation var role = (BuildCacheArtifactRole)saved.GetProperty("role").GetInt32(); string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(relative + "\0" + role))); if (Path.GetFileName(checkpoint) != key + ".inventory") + { throw new InvalidDataException("Inventory checkpoint does not match its registered path identity."); + } string directory = PathBoundary.Resolve(workspace, relative); if (!owners.Any(owner => owner.directory != directory && BuildCacheCleanupPlan.IsContained(owner.directory, directory)) - || Directory.Exists(directory)) + || Directory.Exists(directory) + ) { continue; + } File.Delete(checkpoint); } } @@ -64,19 +71,27 @@ CancellationToken cancellation using (reading) { string root = PathBoundary.RequireUnlinkedPath(workspace, Path.Combine(workspace, "artifacts", "cache-owners", "inventory")); - string identity = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(workspace, metadata)))); + string identity = Convert.ToHexStringLower( + SHA256.HashData(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(workspace, metadata))) + ); string relative = Path.GetRelativePath(workspace, directory).Replace('\\', '/'); string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(relative + "\0" + role))); string checkpoint = Path.Combine(root, key + ".inventory"); if (File.Exists(checkpoint)) { - using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(workspace, checkpoint))); + using JsonDocument document = JsonDocument.Parse( + File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(workspace, checkpoint)) + ); JsonElement saved = document.RootElement; if (saved.GetProperty("directory").GetString() != relative || saved.GetProperty("role").GetInt32() != (int)role - || saved.GetProperty("bytes").GetInt64() < 0) + || saved.GetProperty("bytes").GetInt64() < 0 + ) { throw new InvalidDataException("Cache inventory checkpoint has inconsistent ownership."); + } if (saved.GetProperty("identity").GetString() == identity) + { return saved.GetProperty("bytes").GetInt64(); + } } long bytes = BuildCacheFileInventory.Measure(directory, role, cancellation); cancellation.ThrowIfCancellationRequested(); @@ -85,8 +100,13 @@ CancellationToken cancellation // Only completed measurements are checkpoints. Dependencies, roots and retirement authority // are always read again from the publisher; the checkpoint never authorizes deletion. using FileLease writing = FileLease.AcquireAsync(Path.Combine(root, "progress.lock"), TimeSpan.Zero, cancellation) - .AsTask().GetAwaiter().GetResult(); - AtomicFile.WriteAllBytes(checkpoint, JsonSerializer.SerializeToUtf8Bytes(new { directory = relative, role = (int)role, identity, bytes })); + .AsTask() + .GetAwaiter() + .GetResult(); + AtomicFile.WriteAllBytes( + checkpoint, + JsonSerializer.SerializeToUtf8Bytes(new { directory = relative, role = (int)role, identity, bytes }) + ); } return bytes; } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerCatalog.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerCatalog.cs index 33ac5b0ec..37e9a7a46 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerCatalog.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerCatalog.cs @@ -51,20 +51,29 @@ public static void Register( ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); if (!Enum.IsDefined(role)) + { throw new ArgumentOutOfRangeException(nameof(role)); + } string root = Path.GetFullPath(engineRoot); string owned = PathBoundary.RequireUnlinkedPath(root, directory); if (owned == root) + { throw new ArgumentException("The checkout cannot be registered as a cache."); + } string relative = Path.GetRelativePath(root, owned).Replace('\\', '/'); string catalog = CatalogRoot(root); string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(relative))); string file = Path.Combine(catalog, key + ".json"); - using FileLease writing = FileLease.AcquireAsync(Path.Combine(catalog, "owner.lock"), - TimeSpan.FromSeconds(30), cancellationToken).AsTask().GetAwaiter().GetResult(); + using FileLease writing = FileLease.AcquireAsync( + Path.Combine(catalog, "owner.lock"), + TimeSpan.FromSeconds(30), + cancellationToken + ).AsTask().GetAwaiter().GetResult(); var registration = new Registration(id, relative, role); if (File.Exists(file) && Read(file) != registration) + { throw new InvalidDataException("A cache root cannot change its registered owner or lifetime."); + } cancellationToken.ThrowIfCancellationRequested(); AtomicFile.WriteAllBytes(file, JsonSerializer.SerializeToUtf8Bytes(registration)); } @@ -100,9 +109,14 @@ CancellationToken cancellationToken string root = Path.GetFullPath(engineRoot); string catalog = CatalogRoot(root); if (!Directory.Exists(catalog)) + { return []; - using FileLease reading = FileLease.AcquireSharedAsync(Path.Combine(catalog, "owner.lock"), - TimeSpan.FromSeconds(30), cancellationToken).AsTask().GetAwaiter().GetResult(); + } + using FileLease reading = FileLease.AcquireSharedAsync( + Path.Combine(catalog, "owner.lock"), + TimeSpan.FromSeconds(30), + cancellationToken + ).AsTask().GetAwaiter().GetResult(); var result = new List(); var identities = new HashSet(StringComparer.Ordinal); foreach (string file in PathBoundary.EnumerateFiles(catalog).Where(static file => file.EndsWith(".json", StringComparison.Ordinal))) @@ -110,10 +124,15 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); Registration value = Read(file); if (!identities.Add(value.id)) + { throw new InvalidDataException("Cache registration identities must be unique."); + } string owned = PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, value.directory)); - result.Add((progress is null ? new BuildCachePublisher(owned, value.role) - : new BuildCachePublisher(owned, value.role, progress)).Describe(value.id)); + result.Add( + (progress is null + ? new BuildCachePublisher(owned, value.role) + : new BuildCachePublisher(owned, value.role, progress)).Describe(value.id) + ); } return result.AsReadOnly(); } @@ -128,15 +147,21 @@ private static Registration Read(string path) if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Count() != 3 || !root.TryGetProperty("id", out JsonElement id) || id.ValueKind != JsonValueKind.String || !root.TryGetProperty("directory", out JsonElement directory) || directory.ValueKind != JsonValueKind.String - || !root.TryGetProperty("role", out JsonElement role) || !role.TryGetInt32(out int lifetime)) + || !root.TryGetProperty("role", out JsonElement role) || !role.TryGetInt32(out int lifetime) + ) { throw new InvalidDataException("A cache registration lacks its exact owner, directory and lifetime."); + } var value = new Registration(id.GetString()!, directory.GetString()!, (BuildCacheArtifactRole)lifetime); if (string.IsNullOrWhiteSpace(value.id) || string.IsNullOrWhiteSpace(value.directory) - || Path.IsPathRooted(value.directory) || value.directory == "." || !Enum.IsDefined(value.role)) + || Path.IsPathRooted(value.directory) || value.directory == "." || !Enum.IsDefined(value.role) + ) { throw new InvalidDataException("A cache registration has invalid ownership metadata."); + } string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(value.directory))); if (Path.GetFileName(path) != key + ".json") + { throw new InvalidDataException("A cache registration has a mismatched publisher key."); + } return value; } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerDescriptor.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerDescriptor.cs index ee0d88236..303dad40b 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerDescriptor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheOwnerDescriptor.cs @@ -58,7 +58,9 @@ public BuildCacheOwnerDescriptor( ArgumentNullException.ThrowIfNull(readArtifacts); ArgumentNullException.ThrowIfNull(readProtectedArtifacts); if (!Path.IsPathFullyQualified(directory) || !Path.IsPathFullyQualified(coordinationPath)) + { throw new ArgumentException("Cache registration requires absolute owner paths."); + } this.id = id; this.directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)); this.coordinationPath = Path.GetFullPath(coordinationPath); @@ -88,5 +90,6 @@ internal IReadOnlyList ReadArtifacts(CancellationT => m_readArtifacts(cancellation) ?? throw new InvalidDataException($"Cache owner '{id}' returned no inventory."); internal IReadOnlyList ReadProtectedArtifacts(CancellationToken cancellation) - => m_readProtectedArtifacts(cancellation) ?? throw new InvalidDataException($"Cache owner '{id}' returned no protection inventory."); + => m_readProtectedArtifacts(cancellation) + ?? throw new InvalidDataException($"Cache owner '{id}' returned no protection inventory."); } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs index 3d53ae2d5..bcd7fd211 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs @@ -28,12 +28,18 @@ public BuildCachePolicy( TimeSpan? timeBudget = null ) { if (maximumBytes < 0) + { throw new ArgumentOutOfRangeException(nameof(maximumBytes)); + } if (minimumFreeBytes < 0) + { throw new ArgumentOutOfRangeException(nameof(minimumFreeBytes)); + } TimeSpan duration = timeBudget ?? TimeSpan.FromSeconds(5); if (duration <= TimeSpan.Zero || duration == System.Threading.Timeout.InfiniteTimeSpan) + { throw new ArgumentOutOfRangeException(nameof(timeBudget)); + } this.maximumBytes = maximumBytes; this.minimumFreeBytes = minimumFreeBytes; this.timeBudget = duration; diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs index eb6f74594..18d1f9729 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs @@ -38,10 +38,14 @@ BuildCacheArtifactRole role ) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); if (!Path.IsPathFullyQualified(directory)) + { throw new ArgumentException("A cache publisher requires an absolute root.", nameof(directory)); + } m_root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)); if (!Enum.IsDefined(role)) + { throw new ArgumentOutOfRangeException(nameof(role)); + } m_role = role; } @@ -75,7 +79,9 @@ public async ValueTask AcquireUseAsync(CancellationToken cancellation { string path = Path.Combine(m_root, "owner.lock"); if (!File.Exists(path)) + { using (await FileLease.AcquireAsync(path, TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false)) { } + } return await FileLease.AcquireSharedAsync(path, TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false); } @@ -122,22 +128,34 @@ public void Record( ) { ArgumentNullException.ThrowIfNull(dependencies); if (targetId is not null) + { ArgumentException.ThrowIfNullOrWhiteSpace(targetId); + } BuildCacheCleanupPlan.RequireChild(m_root, directory); BuildCacheCleanupPlan.RequireChild(m_root, leasePath); if (!Directory.Exists(directory)) + { throw new DirectoryNotFoundException(directory); + } cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(m_root, directory).Replace('\\', '/'); long bytes = BuildCacheFileInventory.Measure(directory, m_role, cancellationToken); - var metadata = new Entry(relative, Path.GetRelativePath(m_root, leasePath), DateTime.UtcNow, - dependencies.Select(Path.GetFullPath).ToArray(), bytes, targetId); + var metadata = new Entry( + relative, + Path.GetRelativePath(m_root, leasePath), + DateTime.UtcNow, + dependencies.Select(Path.GetFullPath).ToArray(), + bytes, + targetId + ); AtomicFile.WriteAllBytes(Path.Combine(m_root, Key(relative) + ".cache.json"), WriteEntry(metadata)); if (currentKey is not null && m_role == BuildCacheArtifactRole.ImmutableArtifact) { string pointer = Path.Combine(m_root, Key(currentKey) + ".current"); if (!File.Exists(pointer) || File.ReadAllText(pointer) != relative) + { AtomicFile.WriteAllBytes(pointer, Encoding.UTF8.GetBytes(relative)); + } } } @@ -185,9 +203,13 @@ public void EnsureImmutableRegistration( ) { ArgumentNullException.ThrowIfNull(dependencies); if (targetId is not null) + { ArgumentException.ThrowIfNullOrWhiteSpace(targetId); + } if (m_role != BuildCacheArtifactRole.ImmutableArtifact) + { throw new InvalidOperationException("Only immutable artifacts can retain publication registration."); + } BuildCacheCleanupPlan.RequireChild(m_root, directory); BuildCacheCleanupPlan.RequireChild(m_root, leasePath); string relative = Path.GetRelativePath(m_root, directory).Replace('\\', '/'); @@ -203,8 +225,10 @@ public void EnsureImmutableRegistration( if (previous.directory != relative || !BuildCacheInventory.pathComparer.Equals(PathBoundary.Resolve(m_root, previous.leasePath), Path.GetFullPath(leasePath)) || !previous.dependencies.SequenceEqual(dependencies.Select(Path.GetFullPath), BuildCacheInventory.pathComparer) - || previous.targetId != targetId || previous.bytes != bytes) + || previous.targetId != targetId || previous.bytes != bytes + ) { throw new InvalidDataException("Immutable ownership differs from its completed publication registration."); + } } /// @@ -248,17 +272,26 @@ public void BeginWorkingDirectory( CancellationToken cancellationToken = default ) { if (m_role != BuildCacheArtifactRole.ReusableWorkspace) + { throw new InvalidOperationException("Working registration requires a reusable workspace publisher."); + } BuildCacheCleanupPlan.RequireChild(m_root, directory); BuildCacheCleanupPlan.RequireChild(m_root, leasePath); cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(m_root, directory).Replace('\\', '/'); string record = Path.Combine(m_root, Key(relative) + ".cache.json"); if (Directory.Exists(directory) && !File.Exists(record)) + { throw new InvalidOperationException($"An existing unregistered workspace cannot be adopted: '{directory}'."); + } if (File.Exists(record) && ReadEntry(record).directory != relative) + { throw new InvalidDataException("Working ownership has an inconsistent directory identity."); - AtomicFile.WriteAllBytes(record, WriteEntry(new(relative, Path.GetRelativePath(m_root, leasePath).Replace('\\', '/'), DateTime.UtcNow, [], 0, targetId))); + } + AtomicFile.WriteAllBytes( + record, + WriteEntry(new(relative, Path.GetRelativePath(m_root, leasePath).Replace('\\', '/'), DateTime.UtcNow, [], 0, targetId)) + ); Directory.CreateDirectory(directory); } @@ -296,7 +329,9 @@ public void RecordProcessUse( BuildCacheCleanupPlan.RequireChild(m_root, directory); BuildCacheCleanupPlan.RequireChild(m_root, leasePath); using FileLease writing = FileLease.AcquireAsync(leasePath, TimeSpan.FromSeconds(30), cancellationToken) - .AsTask().GetAwaiter().GetResult(); + .AsTask() + .GetAwaiter() + .GetResult(); string relative = Path.GetRelativePath(m_root, directory).Replace('\\', '/'); string record = Path.Combine(m_root, Key(relative) + ".cache.json"); string[] retained = []; @@ -304,12 +339,15 @@ public void RecordProcessUse( { Entry previous = ReadEntry(record); if (previous.directory != relative - || !BuildCacheInventory.pathComparer.Equals(PathBoundary.Resolve(m_root, previous.leasePath), Path.GetFullPath(leasePath))) + || !BuildCacheInventory.pathComparer.Equals(PathBoundary.Resolve(m_root, previous.leasePath), Path.GetFullPath(leasePath)) + ) { throw new InvalidDataException("Process ownership has an inconsistent directory or lease identity."); + } retained = previous.dependencies; } string[] closure = retained.Concat(dependencies.Select(Path.GetFullPath)) - .Distinct(BuildCacheInventory.pathComparer).ToArray(); + .Distinct(BuildCacheInventory.pathComparer) + .ToArray(); string owners = Path.Combine(directory, "owners"); Directory.CreateDirectory(owners); ProcessOwnerStamp stamp = ProcessOwnerStamp.CaptureCurrent(); @@ -336,34 +374,47 @@ IReadOnlyList dependencies ) { BuildCacheCleanupPlan.RequireChild(m_root, path); foreach (string dependency in dependencies) + { BuildCacheCleanupPlan.RequireChild(m_root, dependency); + } string relative = Path.GetRelativePath(m_root, path).Replace('\\', '/'); - AtomicFile.WriteAllBytes(Path.Combine(m_root, Key(relative) + ".metadata.json"), - JsonSerializer.SerializeToUtf8Bytes(new Index(relative, dependencies.ToArray()))); + AtomicFile.WriteAllBytes( + Path.Combine(m_root, Key(relative) + ".metadata.json"), + JsonSerializer.SerializeToUtf8Bytes(new Index(relative, dependencies.ToArray())) + ); } private void RetireMetadata(CancellationToken cancellation) { if (!Directory.Exists(m_root)) + { return; + } HashSet currents = ReadRoots(cancellation).ToHashSet(BuildCacheInventory.pathComparer); foreach (string pointer in m_role == BuildCacheArtifactRole.ImmutableArtifact - ? Directory.EnumerateFiles(m_root, "*.current") : Enumerable.Empty()) - { + ? Directory.EnumerateFiles(m_root, "*.current") + : Enumerable.Empty() + ) { string selected = PathBoundary.Resolve(m_root, File.ReadAllText(PathBoundary.RequireUnlinkedPath(m_root, pointer))); if (!Directory.Exists(selected)) + { throw new InvalidDataException($"Current cache publication is missing: '{selected}'."); + } } foreach (string record in Directory.EnumerateFiles(m_root, "*.cache.json").Order(StringComparer.Ordinal)) { cancellation.ThrowIfCancellationRequested(); Entry entry = ReadEntry(PathBoundary.RequireUnlinkedPath(m_root, record)); if (Path.GetFileName(record) != Key(entry.directory) + ".cache.json") + { throw new InvalidDataException("Cache metadata has an inconsistent owner identity."); + } string directory = PathBoundary.Resolve(m_root, entry.directory); string leaf = PathBoundary.Resolve(m_root, entry.leasePath); if (Directory.Exists(directory) || currents.Contains(directory)) + { continue; + } PathBoundary.RequireUnlinkedPath(m_root, leaf); using (FileLease.AcquireAsync(leaf, TimeSpan.Zero, cancellation).AsTask().GetAwaiter().GetResult()) { } File.Delete(leaf); @@ -374,15 +425,23 @@ private void RetireMetadata(CancellationToken cancellation) { cancellation.ThrowIfCancellationRequested(); Index index = JsonSerializer.Deserialize(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(m_root, record))) - ?? throw new InvalidDataException("Cache index ownership is incomplete."); - if (index.dependencies is null || index.dependencies.Length == 0 || Path.GetFileName(record) != Key(index.path) + ".metadata.json") + ?? throw new InvalidDataException("Cache index ownership is incomplete."); + if (index.dependencies is null + || index.dependencies.Length == 0 + || Path.GetFileName(record) != Key(index.path) + ".metadata.json" + ) { throw new InvalidDataException("Cache index ownership is inconsistent."); + } string path = PathBoundary.Resolve(m_root, index.path); BuildCacheCleanupPlan.RequireChild(m_root, path); foreach (string dependency in index.dependencies) + { BuildCacheCleanupPlan.RequireChild(m_root, dependency); + } if (index.dependencies.All(Directory.Exists)) + { continue; + } File.Delete(path); File.Delete(record); } @@ -398,7 +457,9 @@ private IReadOnlyList ReadArtifacts(CancellationTo { List result = []; if (!Directory.Exists(m_root)) + { return result; + } foreach (string path in Directory.EnumerateFiles(m_root, "*.cache.json").Order(StringComparer.Ordinal)) { cancellation.ThrowIfCancellationRequested(); @@ -407,26 +468,49 @@ private IReadOnlyList ReadArtifacts(CancellationTo string directory = PathBoundary.Resolve(m_root, entry.directory); string lease = PathBoundary.Resolve(m_root, entry.leasePath); if (Path.GetFileName(path) != Key(entry.directory) + ".cache.json") + { throw new InvalidDataException("Cache ownership metadata does not match its identity."); + } if (!Directory.Exists(directory)) + { continue; + } // Completed workspaces are measured by their sole writer. An unfinished registration // has zero bytes and must be inspected; this metadata never validates Native contents. long bytes = m_role == BuildCacheArtifactRole.ImmutableArtifact - || m_role == BuildCacheArtifactRole.ReusableWorkspace && entry.bytes > 0 - ? entry.bytes : m_inventoryProgress?.Measure(directory, path, lease, m_role, cancellation) - ?? BuildCacheFileInventory.Measure(directory, m_role, cancellation); + || m_role == BuildCacheArtifactRole.ReusableWorkspace && entry.bytes > 0 + ? entry.bytes + : m_inventoryProgress?.Measure(directory, path, lease, m_role, cancellation) + ?? BuildCacheFileInventory.Measure(directory, m_role, cancellation); result.Add(new(directory, lease, entry.targetId, bytes, entry.lastUseUtc, entry.dependencies, m_role)); } foreach (ProcessOwnedDirectoryDescriptor working in ProcessOwnedDirectory.ReadClaims(m_root, cancellation)) { if (result.Any(entry => BuildCacheInventory.pathComparer.Equals(entry.directory, working.directory))) + { continue; + } string metadata = Path.Combine(m_root, Key(Path.GetRelativePath(m_root, working.directory)) + ".work.json"); long bytes = working.ownerState == ProcessOwnerState.Exited && m_inventoryProgress is not null - ? m_inventoryProgress.Measure(working.directory, metadata, working.leasePath, BuildCacheArtifactRole.ProcessWorkingDirectory, cancellation) - : BuildCacheFileInventory.Measure(working.directory, BuildCacheArtifactRole.ProcessWorkingDirectory, cancellation); - result.Add(new(working.directory, working.leasePath, null, bytes, Directory.GetLastWriteTimeUtc(working.directory), [], BuildCacheArtifactRole.ProcessWorkingDirectory)); + ? m_inventoryProgress.Measure( + working.directory, + metadata, + working.leasePath, + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellation + ) + : BuildCacheFileInventory.Measure(working.directory, BuildCacheArtifactRole.ProcessWorkingDirectory, cancellation); + result.Add( + new( + working.directory, + working.leasePath, + null, + bytes, + Directory.GetLastWriteTimeUtc(working.directory), + [], + BuildCacheArtifactRole.ProcessWorkingDirectory + ) + ); } return result; } @@ -435,10 +519,13 @@ private IReadOnlyList ReadRoots(CancellationToken cancellation) { List result = []; if (!Directory.Exists(m_root)) + { return result; + } foreach (string path in m_role == BuildCacheArtifactRole.ImmutableArtifact - ? Directory.EnumerateFiles(m_root, "*.current").Order(StringComparer.Ordinal) : Enumerable.Empty()) - { + ? Directory.EnumerateFiles(m_root, "*.current").Order(StringComparer.Ordinal) + : Enumerable.Empty() + ) { cancellation.ThrowIfCancellationRequested(); PathBoundary.RequireUnlinkedPath(m_root, path); result.Add(PathBoundary.Resolve(m_root, File.ReadAllText(path))); @@ -451,12 +538,19 @@ private IReadOnlyList ReadRoots(CancellationToken cancellation) string directory = PathBoundary.Resolve(m_root, entry.directory); string owners = Path.Combine(directory, "owners"); if (m_role != BuildCacheArtifactRole.ReusableWorkspace && Directory.Exists(owners) && PathBoundary.EnumerateFiles(owners) - .Where(static file => Path.GetExtension(file) == ".pid").Any(IsProcessAlive)) + .Where(static file => Path.GetExtension(file) == ".pid") + .Any(IsProcessAlive) + ) { result.Add(directory); + } } foreach (ProcessOwnedDirectoryDescriptor working in ProcessOwnedDirectory.ReadClaims(m_root, cancellation)) + { if (working.ownerState != ProcessOwnerState.Exited) + { result.Add(working.directory); + } + } return result; } @@ -466,14 +560,18 @@ private static bool IsProcessAlive(string marker) { using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(marker)); JsonElement root = document.RootElement; - if (!root.EnumerateObject().Select(static property => property.Name).Order(StringComparer.Ordinal) - .SequenceEqual(new[] { "processId", "startedUtcTicks" }, StringComparer.Ordinal)) + if (!root.EnumerateObject() + .Select(static property => property.Name) + .Order(StringComparer.Ordinal) + .SequenceEqual(new[] { "processId", "startedUtcTicks" }, StringComparer.Ordinal) + ) { return true; + } var stamp = new ProcessOwnerStamp(root.GetProperty("processId").GetInt32(), root.GetProperty("startedUtcTicks").GetInt64()); return stamp.Query() != ProcessOwnerState.Exited; } catch (Exception exception) when (exception is JsonException or ArgumentException or InvalidOperationException - or IOException or UnauthorizedAccessException or FormatException or OverflowException) + or IOException or UnauthorizedAccessException or FormatException or OverflowException) { return true; } @@ -494,7 +592,9 @@ private static byte[] WriteEntry(Entry entry) writer.WriteString("targetId", entry.targetId); writer.WriteStartArray("dependencies"); foreach (string dependency in entry.dependencies) + { writer.WriteStringValue(dependency); + } writer.WriteEndArray(); writer.WriteEndObject(); } @@ -505,15 +605,29 @@ private static Entry ReadEntry(string path) { using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(path)); JsonElement root = document.RootElement; - if (!root.EnumerateObject().Select(static property => property.Name).Order(StringComparer.Ordinal) - .SequenceEqual(new[] { "bytes", "dependencies", "directory", "lastUseUtc", "leasePath", "targetId" }, StringComparer.Ordinal)) + if (!root.EnumerateObject() + .Select(static property => property.Name) + .Order(StringComparer.Ordinal) + .SequenceEqual(new[] { "bytes", "dependencies", "directory", "lastUseUtc", "leasePath", "targetId" }, StringComparer.Ordinal) + ) { throw new InvalidDataException("Cache ownership requires one complete current record."); + } long bytes = root.GetProperty("bytes").GetInt64(); if (bytes < 0) + { throw new InvalidDataException("Recorded cache size cannot be negative."); - return new(root.GetProperty("directory").GetString()!, root.GetProperty("leasePath").GetString()!, - root.GetProperty("lastUseUtc").GetDateTime(), root.GetProperty("dependencies").EnumerateArray() - .Select(static dependency => dependency.GetString()!).ToArray(), bytes, root.GetProperty("targetId").GetString()); + } + return new( + root.GetProperty("directory").GetString()!, + root.GetProperty("leasePath").GetString()!, + root.GetProperty("lastUseUtc").GetDateTime(), + root.GetProperty("dependencies") + .EnumerateArray() + .Select(static dependency => dependency.GetString()!) + .ToArray(), + bytes, + root.GetProperty("targetId").GetString() + ); } private sealed record Entry( diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs index 020341782..27235f26f 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs @@ -36,11 +36,15 @@ CancellationToken cancellation { cancellation.ThrowIfCancellationRequested(); if (elapsed.Elapsed >= policy.timeBudget) + { return new([], proposed.Keys, failures, 0, true); + } try { BuildCacheCleanupPlan.RequireChild(owner.directory, owner.coordinationPath); - ownerLeases.Add(await FileLease.AcquireAsync(owner.coordinationPath, TimeSpan.Zero, cancellation).ConfigureAwait(false)); + ownerLeases.Add( + await FileLease.AcquireAsync(owner.coordinationPath, TimeSpan.Zero, cancellation).ConfigureAwait(false) + ); } catch (TimeoutException) { @@ -52,16 +56,26 @@ CancellationToken cancellation HashSet protectedPaths = fresh.Protect(fresh.roots); protectedPaths.UnionWith(fresh.Protect(fresh.artifacts.Keys.Except(proposed.Keys, BuildCacheInventory.pathComparer))); var active = new List(); - foreach (string path in fresh.artifacts.Keys.Where(path => proposed.ContainsKey(path) && !protectedPaths.Contains(path)).Order(StringComparer.Ordinal)) - { + foreach (string path in fresh.artifacts.Keys + .Where(path => proposed.ContainsKey(path) && !protectedPaths.Contains(path)) + .Order(StringComparer.Ordinal) + ) { cancellation.ThrowIfCancellationRequested(); if (elapsed.Elapsed >= policy.timeBudget) + { return new([], proposed.Keys, failures, 0, true); + } try { BuildCacheCleanupPlan.RequireChild(fresh.artifacts[path].owner.directory, path); - artifactLeases.Add(path, await FileLease.AcquireAsync(fresh.artifacts[path].artifact.leasePath, - TimeSpan.Zero, cancellation).ConfigureAwait(false)); + artifactLeases.Add( + path, + await FileLease.AcquireAsync( + fresh.artifacts[path].artifact.leasePath, + TimeSpan.Zero, + cancellation + ).ConfigureAwait(false) + ); } catch (TimeoutException) { @@ -76,8 +90,12 @@ CancellationToken cancellation protectedPaths.UnionWith(fresh.Protect(active)); // An active parent keeps its dependencies available to the original owner. foreach (string path in protectedPaths) + { if (artifactLeases.Remove(path, out FileLease? lease)) + { lease.Dispose(); + } + } foreach (string path in fresh.retirementOrder.Where(proposed.ContainsKey)) { cancellation.ThrowIfCancellationRequested(); @@ -92,8 +110,8 @@ CancellationToken cancellation || original.bytes != current.artifact.bytes || original.lastUseUtc != current.artifact.lastUseUtc || original.targetId != current.artifact.targetId || original.role != current.artifact.role || !BuildCacheInventory.pathComparer.Equals(original.leasePath, current.artifact.leasePath) - || !original.dependencies.SequenceEqual(current.artifact.dependencies, BuildCacheInventory.pathComparer)) - { + || !original.dependencies.SequenceEqual(current.artifact.dependencies, BuildCacheInventory.pathComparer) + ) { skipped.Add(path); continue; } @@ -120,23 +138,31 @@ CancellationToken cancellation } // Close leaf handles before unlinking them, while every owner gate remains exclusive. foreach (FileLease lease in artifactLeases.Values) + { lease.Dispose(); + } artifactLeases.Clear(); foreach (BuildCacheOwnerDescriptor owner in owners.OrderBy(static owner => owner.coordinationPath, StringComparer.Ordinal)) { bounded.Token.ThrowIfCancellationRequested(); - try { owner.RetireMetadata(bounded.Token); } + try + { + owner.RetireMetadata(bounded.Token); + } catch (Exception failure) when (failure is IOException or UnauthorizedAccessException or TimeoutException - or InvalidDataException or JsonException) + or InvalidDataException or JsonException) { // Payload retirement has already committed. Keep invalid metadata and report // the failure without losing completed work or another owner's cleanup result. failures[owner.directory] = failure.Message; } } - try { BuildCacheInventoryProgress.PruneRetired(workspace, owners, bounded.Token); } + try + { + BuildCacheInventoryProgress.PruneRetired(workspace, owners, bounded.Token); + } catch (Exception failure) when (failure is IOException or UnauthorizedAccessException or TimeoutException - or InvalidDataException or JsonException) + or InvalidDataException or JsonException) { failures[Path.Combine(workspace, "artifacts", "cache-owners", "inventory")] = failure.Message; } @@ -150,9 +176,13 @@ CancellationToken cancellation finally { foreach (FileLease lease in artifactLeases.Values.Reverse()) + { lease.Dispose(); + } for (int index = ownerLeases.Count - 1; index >= 0; index--) + { ownerLeases[index].Dispose(); + } } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs index 79ec5bce8..b530cb930 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs @@ -54,31 +54,51 @@ public static async Task ExportAsync( using (var stream = new FileStream(candidate, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) { using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) - foreach (BuildCacheOwnerDescriptor owner in BuildCacheOwnerCatalog.ReadOwners(root, cancellationToken) - .Where(static owner => owner.id is "native" or "bindings")) { + foreach (BuildCacheOwnerDescriptor owner in BuildCacheOwnerCatalog.ReadOwners(root, cancellationToken) + .Where(static owner => owner.id is "native" or "bindings") + ) { if (owner.directory != Path.Combine(root, "artifacts", owner.id)) + { throw new InvalidDataException("Native transfer encountered a foreign publisher registration."); - if (selectedArtifacts is not null && !selectedArtifacts.Any(path => path.StartsWith(owner.id + "/", StringComparison.Ordinal))) + } + if (selectedArtifacts is not null + && !selectedArtifacts.Any(path => path.StartsWith(owner.id + "/", StringComparison.Ordinal)) + ) { continue; + } using FileLease activity = await new BuildCachePublisher(owner.directory, BuildCacheArtifactRole.ImmutableArtifact) - .AcquireUseAsync(cancellationToken).ConfigureAwait(false); + .AcquireUseAsync(cancellationToken) + .ConfigureAwait(false); foreach (BuildCacheArtifactDescriptor artifact in owner.ReadArtifacts(cancellationToken) - .Where(static artifact => artifact.role == BuildCacheArtifactRole.ImmutableArtifact).OrderBy(static artifact => artifact.directory, StringComparer.Ordinal)) - { + .Where(static artifact => artifact.role == BuildCacheArtifactRole.ImmutableArtifact) + .OrderBy(static artifact => artifact.directory, StringComparer.Ordinal) + ) { string relative = Path.GetRelativePath(Path.Combine(root, "artifacts"), artifact.directory).Replace('\\', '/'); if (selectedArtifacts is not null && !selectedArtifacts.Contains(relative)) + { continue; + } string[] parts = RequireArtifactPath(relative); - using BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(artifact.directory, owner.directory, - parts[3], OutputRoots(parts[0]), cancellationToken).ConfigureAwait(false); + using BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + artifact.directory, + owner.directory, + parts[3], + OutputRoots(parts[0]), + cancellationToken + ).ConfigureAwait(false); foreach (string file in PathBoundary.EnumerateFiles(artifact.directory).Order(StringComparer.Ordinal)) { cancellationToken.ThrowIfCancellationRequested(); - ZipArchiveEntry entry = zip.CreateEntry(relative + "/" + Path.GetRelativePath(artifact.directory, file).Replace('\\', '/'), CompressionLevel.Fastest); + ZipArchiveEntry entry = zip.CreateEntry( + relative + "/" + Path.GetRelativePath(artifact.directory, file).Replace('\\', '/'), + CompressionLevel.Fastest + ); entry.LastWriteTime = new DateTimeOffset(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); if (!OperatingSystem.IsWindows()) + { entry.ExternalAttributes = ((int)File.GetUnixFileMode(file) | 0x8000) << 16; + } using Stream output = entry.Open(); using FileStream input = File.OpenRead(file); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); @@ -86,12 +106,17 @@ public static async Task ExportAsync( count++; } } + } stream.Flush(flushToDisk: true); } if (selectedArtifacts is not null && count != selectedArtifacts.Count) + { throw new InvalidDataException("Native export did not find every selected registered generation."); + } if (count == 0) + { throw new InvalidDataException("No registered immutable native generations are available for export."); + } cancellationToken.ThrowIfCancellationRequested(); AtomicFile.Install(candidate, destination); return count; @@ -99,7 +124,9 @@ public static async Task ExportAsync( finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } } @@ -131,7 +158,13 @@ public static async Task ImportAsync( ) { string root = Path.GetFullPath(engineRoot); string stagingRoot = Path.Combine(root, "artifacts", "native-transfer"); - BuildCacheOwnerCatalog.Register(root, stagingRoot, "native-transfer", BuildCacheArtifactRole.ProcessWorkingDirectory, cancellationToken); + BuildCacheOwnerCatalog.Register( + root, + stagingRoot, + "native-transfer", + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ); using ProcessOwnedDirectory staging = await ProcessOwnedDirectory.CreateAsync(stagingRoot, cancellationToken).ConfigureAwait(false); var artifacts = new HashSet(StringComparer.Ordinal); var names = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -139,15 +172,19 @@ public static async Task ImportAsync( { long expanded = 0; if (zip.Entries.Count == 0 || zip.Entries.Count > 200000) + { throw new InvalidDataException("Native transfer contains an empty or excessive file inventory."); + } foreach (ZipArchiveEntry entry in zip.Entries) { cancellationToken.ThrowIfCancellationRequested(); string[] parts = entry.FullName.Split('/'); if (parts.Length < 5 || parts.Any(static part => part is "" or "." or ".." || part.Contains('\\') || part.Contains(':')) || !names.Add(entry.FullName) || ((entry.ExternalAttributes >> 16) & 0xf000) is not (0 or 0x8000) - || (expanded = checked(expanded + entry.Length)) > 32L * 1024 * 1024 * 1024) + || (expanded = checked(expanded + entry.Length)) > 32L * 1024 * 1024 * 1024 + ) { throw new InvalidDataException("Native transfer contains an invalid, linked, duplicate or excessive entry."); + } string artifact = string.Join('/', parts.Take(4)); _ = RequireArtifactPath(artifact); artifacts.Add(artifact); @@ -155,9 +192,13 @@ public static async Task ImportAsync( Directory.CreateDirectory(Path.GetDirectoryName(output)!); using (Stream input = entry.Open()) using (var destination = new FileStream(output, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { await input.CopyToAsync(destination, cancellationToken).ConfigureAwait(false); + } if (!OperatingSystem.IsWindows() && entry.ExternalAttributes != 0) + { File.SetUnixFileMode(output, (UnixFileMode)((entry.ExternalAttributes >> 16) & 0x1ff)); + } } } foreach (string artifact in artifacts) @@ -165,7 +206,9 @@ public static async Task ImportAsync( cancellationToken.ThrowIfCancellationRequested(); string[] parts = RequireArtifactPath(artifact); if (!BuildArtifactManifest.IsComplete(PathBoundary.Resolve(staging.directory, artifact), parts[3], OutputRoots(parts[0]))) + { throw new InvalidDataException("Native transfer failed exact manifest and payload verification: " + artifact); + } } int imported = 0; foreach (string artifact in artifacts.Order(StringComparer.Ordinal)) @@ -175,12 +218,21 @@ public static async Task ImportAsync( // An existing generation is never replaced by transport, including while a consumer reads it. // Its actual publisher remains responsible for completeness, repair and adoption. if (Directory.Exists(destination)) + { continue; - using CoordinatedFileLease writing = await CoordinatedFileLease.AcquireAsync(Path.Combine(root, "artifacts", parts[0], "owner.lock"), - destination + ".read.lock", TimeSpan.FromSeconds(30), shared: false, cancellationToken: cancellationToken).ConfigureAwait(false); + } + using CoordinatedFileLease writing = await CoordinatedFileLease.AcquireAsync( + Path.Combine(root, "artifacts", parts[0], "owner.lock"), + destination + ".read.lock", + TimeSpan.FromSeconds(30), + shared: false, + cancellationToken: cancellationToken + ).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (Directory.Exists(destination)) + { continue; + } Directory.CreateDirectory(Path.GetDirectoryName(destination)!); Directory.Move(PathBoundary.Resolve(staging.directory, artifact), destination); imported++; @@ -191,10 +243,14 @@ public static async Task ImportAsync( private static string[] RequireArtifactPath(string relative) { string[] parts = relative.Split('/'); - if (parts.Length != 4 || parts[0] is not ("native" or "bindings") || parts.Any(static part => - part is "" or "." or ".." || part.Any(static character => !char.IsAsciiLetterOrDigit(character) && character is not ('-' or '_' or '.'))) - || parts[3].Length != 64 || parts[3].Any(static character => !char.IsAsciiHexDigitLower(character))) + if (parts.Length != 4 || parts[0] is not ("native" or "bindings") || parts.Any(static part => ( + part is "" or "." or ".." + || part.Any(static character => !char.IsAsciiLetterOrDigit(character) && character is not ('-' or '_' or '.')) + )) + || parts[3].Length != 64 || parts[3].Any(static character => !char.IsAsciiHexDigitLower(character)) + ) { throw new InvalidDataException("Native transfer has an invalid publisher or content identity: " + relative); + } return parts; } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyAsset.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyAsset.cs index 0f5844226..4e074bdf5 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyAsset.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyAsset.cs @@ -1,4 +1,5 @@ namespace Inno.Build.Toolchains; + /// /// Identifies one immutable native archive selected for a backend product closure. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs index 0146610a6..1ab6aca20 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs @@ -9,12 +9,28 @@ using Inno.Core.IO; namespace Inno.Build.Toolchains; + /// /// Transfers aggregate native products and their exact binding generations through the dependency selection protocol. /// public static partial class NativeDependencyManifest { - private static string PlanOptions(ProductNativeBuildPlan plan) => JsonSerializer.Serialize(plan.steps.Select(step => new { step.id, step.component.nativeProject, step.component.toolchainProject, step.component.bindingDefinition, step.configuration, step.options, step.dependencies })); + private static string PlanOptions(ProductNativeBuildPlan plan) + => JsonSerializer.Serialize( + plan.steps.Select( + step => new + { + step.id, + step.component.nativeProject, + step.component.toolchainProject, + step.component.bindingDefinition, + step.configuration, + step.options, + step.dependencies + } + ) + ); + private static async Task ExportAggregateAsync( NativeBuildContext context, ProductNativeBuildPlan plan, @@ -22,24 +38,91 @@ private static async Task ExportAggregateAsync( string output, CancellationToken cancellation ) { - NativeBuildRecipe recipe = products.aggregateRecipe ?? throw new InvalidDataException("An aggregate export must retain its producer recipe."); + NativeBuildRecipe recipe = products.aggregateRecipe + ?? throw new InvalidDataException("An aggregate export must retain its producer recipe."); NativeBuildProduct product = products.Single(); - var sources = await NativeDependencySource.CaptureAsync(context.engineRoot, recipe.inputs.Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal)).Select(static input => input.logicalPath[7..]).Concat(context.inputState.CaptureRecordedInputs(context.engineRoot).entries.Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal)).Select(static input => input.logicalPath[7..])).Concat(plan.steps.SelectMany(static step => new[] { step.component.nativeProject, step.component.toolchainProject })).Append(recipe.owner.nativeProject).Append(recipe.owner.toolchainProject), cancellation).ConfigureAwait(false); - var bindings = products.bindingGenerations.ToDictionary(static pair => pair.Key, pair => new BindingAsset(pair.Value.fingerprint, pair.Value.usesRuntimeImports, Relative(pair.Value.artifactDirectory), Path.GetRelativePath(pair.Value.artifactDirectory, pair.Value.bindingsPath).Replace('\\', '/'), Path.GetRelativePath(pair.Value.artifactDirectory, pair.Value.nativeDirectory).Replace('\\', '/')), StringComparer.Ordinal); - var directories = bindings.Values.Select(static binding => binding.directory).Append(Relative(product.directory)).ToHashSet(StringComparer.Ordinal); + var sources = await NativeDependencySource.CaptureAsync( + context.engineRoot, + recipe.inputs + .Where( + static input => ( + input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) + && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal) + ) + ) + .Select(static input => input.logicalPath[7..]) + .Concat( + context.inputState + .CaptureRecordedInputs(context.engineRoot).entries + .Where( + static input => ( + input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) + && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal) + ) + ) + .Select(static input => input.logicalPath[7..]) + ) + .Concat(plan.steps.SelectMany(static step => new[] { step.component.nativeProject, step.component.toolchainProject })) + .Append(recipe.owner.nativeProject) + .Append(recipe.owner.toolchainProject), + cancellation + ).ConfigureAwait(false); + var bindings = products.bindingGenerations.ToDictionary( + static pair => pair.Key, + pair => new BindingAsset( + pair.Value.fingerprint, + pair.Value.usesRuntimeImports, + Relative(pair.Value.artifactDirectory), + Path.GetRelativePath(pair.Value.artifactDirectory, pair.Value.bindingsPath).Replace('\\', '/'), + Path.GetRelativePath(pair.Value.artifactDirectory, pair.Value.nativeDirectory).Replace('\\', '/') + ), + StringComparer.Ordinal + ); + var directories = bindings.Values + .Select(static binding => binding.directory) + .Append(Relative(product.directory)) + .ToHashSet(StringComparer.Ordinal); Directory.CreateDirectory(output); string assetName = product.component + "-" + product.targetId + "-" + product.fingerprint + ".zip"; string archive = Path.Combine(output, assetName); await NativeArtifactTransfer.ExportAsync(context.engineRoot, archive, cancellation, directories).ConfigureAwait(false); using FileStream payload = File.OpenRead(archive); string hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellation).ConfigureAwait(false)); - string revision = (await ToolchainEnvironment.CaptureOutputAsync("git", ["rev-parse", "HEAD"], context.engineRoot, cancellation).ConfigureAwait(false)).Trim(); - var asset = new AggregateAsset(plan.productId, product.component, product.targetId, context.configuration, PlanOptions(plan), Relative(product.directory), product.fingerprint, Path.GetRelativePath(product.directory, products.aggregateDirectory!).Replace('\\', '/'), product.sharedLibraryExtension, bindings, sources, context.RequireToolchain().declarations.ToArray(), assetName, hash, revision); + string revision = (await ToolchainEnvironment.CaptureOutputAsync( + "git", + ["rev-parse", "HEAD"], + context.engineRoot, + cancellation + ).ConfigureAwait(false)).Trim(); + var asset = new AggregateAsset( + plan.productId, + product.component, + product.targetId, + context.configuration, + PlanOptions(plan), + Relative(product.directory), + product.fingerprint, + Path.GetRelativePath(product.directory, products.aggregateDirectory!).Replace('\\', '/'), + product.sharedLibraryExtension, + bindings, + sources, + context.RequireToolchain().declarations.ToArray(), + assetName, + hash, + revision + ); string path = Path.Combine(output, plan.productId + "-" + product.targetId + "-" + context.configuration + ".json"); await VerifySourcesAsync(context.engineRoot, sources, cancellation).ConfigureAwait(false); - AtomicFile.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(new Selection([], [asset], "platform-packages"), new JsonSerializerOptions { WriteIndented = true })); + AtomicFile.WriteAllBytes( + path, + JsonSerializer.SerializeToUtf8Bytes( + new Selection([], [asset], "platform-packages"), + new JsonSerializerOptions { WriteIndented = true } + ) + ); return path; - string Relative(string directory) => Path.GetRelativePath(Path.Combine(context.engineRoot, "artifacts"), directory).Replace('\\', '/'); + string Relative(string directory) + => Path.GetRelativePath(Path.Combine(context.engineRoot, "artifacts"), directory).Replace('\\', '/'); } private static async Task AcquireAggregateAsync( @@ -49,9 +132,16 @@ private static async Task AcquireAggregateAsync( ProductNativeBuildPlan plan, CancellationToken cancellation ) { - string[] owners = plan.steps.Where(static step => step.component.bindingDefinition is not null).Select(static step => step.component.nativeProject).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + string[] owners = plan.steps + .Where(static step => step.component.bindingDefinition is not null) + .Select(static step => step.component.nativeProject) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); if (!owners.SequenceEqual(asset.bindings.Keys.Order(StringComparer.Ordinal), StringComparer.Ordinal)) + { throw new InvalidDataException("The aggregate dependency has a different binding closure."); + } await VerifySourcesAsync(root, asset.sources, cancellation).ConfigureAwait(false); RequireDigest(asset.fingerprint); RequireDigest(asset.sha256); @@ -60,8 +150,12 @@ CancellationToken cancellation if (!Directory.Exists(directory) || bindingDirectories.Any(path => !Directory.Exists(path))) { using (FileStream payload = File.OpenRead(archive)) + { if (Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellation).ConfigureAwait(false)) != asset.sha256) + { throw new InvalidDataException("Native aggregate archive differs from its pinned digest."); + } + } await NativeArtifactTransfer.ImportAsync(root, archive, cancellation).ConfigureAwait(false); } @@ -75,11 +169,31 @@ CancellationToken cancellation BindingAsset binding = pair.Value; string location = ResolveBinding(binding); string owner = Path.Combine(root, "artifacts", "bindings"); - readers.Add(await AcquireAsync(location, owner, "bindings", binding.fingerprint, ["Generated", "Native"], []).ConfigureAwait(false)); - bindings.Add(pair.Key, new() { fingerprint = binding.fingerprint, usesRuntimeImports = binding.runtimeImports, artifactDirectory = location, artifactOwnerDirectory = owner, bindingsPath = PathBoundary.Resolve(location, binding.managed), nativeDirectory = PathBoundary.Resolve(location, binding.native) }); + readers.Add( + await AcquireAsync(location, owner, "bindings", binding.fingerprint, ["Generated", "Native"], []).ConfigureAwait(false) + ); + bindings.Add( + pair.Key, + new() + { + fingerprint = binding.fingerprint, + usesRuntimeImports = binding.runtimeImports, + artifactDirectory = location, + artifactOwnerDirectory = owner, + bindingsPath = PathBoundary.Resolve(location, binding.managed), + nativeDirectory = PathBoundary.Resolve(location, binding.native) + } + ); } - BuildArtifactReadLease reading = await AcquireAsync(directory, Path.Combine(root, "artifacts", "native"), "native", asset.fingerprint, ["Outputs", "Metadata"], bindingDirectories).ConfigureAwait(false); + BuildArtifactReadLease reading = await AcquireAsync( + directory, + Path.Combine(root, "artifacts", "native"), + "native", + asset.fingerprint, + ["Outputs", "Metadata"], + bindingDirectories + ).ConfigureAwait(false); try { product = new(asset.component, asset.target, asset.fingerprint, directory, null, asset.extension, reading); @@ -97,7 +211,9 @@ CancellationToken cancellation { product?.Dispose(); foreach (IDisposable reader in readers) + { reader.Dispose(); + } throw; } @@ -106,7 +222,9 @@ string ResolveBinding(BindingAsset binding) RequireDigest(binding.fingerprint); string[] parts = binding.directory.Split('/'); if (parts.Length != 4) + { throw new InvalidDataException("Invalid binding aggregate path."); + } return Resolve(binding.directory, "bindings", parts[1], binding.fingerprint); } @@ -117,7 +235,9 @@ string Resolve( string fingerprint ) { if (component.Contains('/') || component.Contains('\\') || relative != $"{owner}/{component}/{asset.target}/{fingerprint}") + { throw new InvalidDataException("Aggregate dependency is outside its exact owner."); + } return PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(Path.Combine(root, "artifacts"), relative)); } @@ -130,7 +250,13 @@ async Task AcquireAsync( string[] dependencies ) { BuildCacheOwnerCatalog.Register(root, owner, id, BuildCacheArtifactRole.ImmutableArtifact, cancellation); - BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(location, owner, fingerprint, outputs, cancellation).ConfigureAwait(false); + BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + location, + owner, + fingerprint, + outputs, + cancellation + ).ConfigureAwait(false); try { var publisher = new BuildCachePublisher(owner, BuildCacheArtifactRole.ImmutableArtifact); @@ -151,9 +277,16 @@ private static async Task VerifySourcesAsync( Dictionary expected, CancellationToken cancellation ) { - Dictionary current = await NativeDependencySource.CaptureAsync(root, expected.Keys, cancellation).ConfigureAwait(false); - if (current.Count != expected.Count || current.Any(pair => !expected.TryGetValue(pair.Key, out string? value) || value != pair.Value)) + Dictionary current = await NativeDependencySource.CaptureAsync( + root, + expected.Keys, + cancellation + ).ConfigureAwait(false); + if (current.Count != expected.Count + || current.Any(pair => !expected.TryGetValue(pair.Key, out string? value) || value != pair.Value) + ) { throw new InvalidDataException("Native dependency sources changed. Produce the matching backend package for this target."); + } } private sealed record AggregateAsset( diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs index ac71defbd..00225c617 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs @@ -9,6 +9,7 @@ using Inno.Core.IO; namespace Inno.Build.Toolchains; + /// /// Publishes exact native dependency selections and acquires their immutable payloads without invoking producers. /// @@ -54,9 +55,20 @@ public static async Task> SelectAsync( ) { ToolchainEnvironment.ValidateConfiguration(configuration); Selection selection = ReadSelection(selectionPath); - AggregateAsset[] aggregate = selection.aggregates.Where(asset => asset.product == plan.productId && asset.target == target && asset.configuration == configuration && asset.options == PlanOptions(plan)).ToArray(); + AggregateAsset[] aggregate = selection.aggregates + .Where( + asset => ( + asset.product == plan.productId + && asset.target == target + && asset.configuration == configuration + && asset.options == PlanOptions(plan) + ) + ) + .ToArray(); if (aggregate.Length > 1) + { throw new InvalidDataException("Native aggregate dependency selection is ambiguous."); + } if (aggregate.Length == 1) { await VerifySourcesAsync(engineRoot, aggregate[0].sources, cancellationToken).ConfigureAwait(false); @@ -69,27 +81,59 @@ public static async Task> SelectAsync( var selectedComponents = new Dictionary(StringComparer.Ordinal); foreach (ProductNativeBuildStep step in plan.steps) { - DependencyAsset[] matches = selection.assets.Where(asset => asset.product == plan.productId && asset.component == step.id && asset.target == target && asset.configuration == (step.configuration ?? configuration) && asset.options == Options(step) && asset.nativeProject == step.component.nativeProject && asset.toolchainProject == step.component.toolchainProject).ToArray(); + DependencyAsset[] matches = selection.assets + .Where( + asset => ( + asset.product == plan.productId + && asset.component == step.id + && asset.target == target + && asset.configuration == (step.configuration ?? configuration) + && asset.options == Options(step) + && asset.nativeProject == step.component.nativeProject + && asset.toolchainProject == step.component.toolchainProject + ) + ) + .ToArray(); if (matches.Length != 1) - throw new InvalidDataException($"Missing or ambiguous native dependency: {step.id}/{target}/{step.configuration ?? configuration}. Produce the matching backend package for the requested target."); + { + throw new InvalidDataException( + $"Missing or ambiguous native dependency: {step.id}/{target}/{step.configuration ?? configuration}. Produce the matching backend package for the requested target." + ); + } DependencyAsset selected = matches[0]; if ((selected.binding is null) != (step.component.bindingDefinition is null)) + { throw new InvalidDataException("Native dependency binding ownership differs: " + step.id); + } selectedComponents.Add(step.id, selected); RequireDigest(selected.sha256); assets.Add(new(selected.asset, selected.sha256)); foreach (var pair in selected.sources) + { if (sources.TryGetValue(pair.Key, out string? previous) && previous != pair.Value) + { throw new InvalidDataException("Native packages disagree about their shared source inputs."); + } else + { sources[pair.Key] = pair.Value; + } + } } foreach (ProductNativeBuildStep step in plan.steps) { DependencyAsset selected = selectedComponents[step.id]; - if (selected.dependencies.Count != step.dependencies.Count || step.dependencies.Any(id => !selected.dependencies.TryGetValue(id, out string? fingerprint) || selectedComponents[id].fingerprint != fingerprint)) + if (selected.dependencies.Count != step.dependencies.Count + || step.dependencies.Any( + id => ( + !selected.dependencies.TryGetValue(id, out string? fingerprint) + || selectedComponents[id].fingerprint != fingerprint + ) + ) + ) { throw new InvalidDataException("Native dependency was built against a different closure: " + step.id); + } } await VerifySourcesAsync(engineRoot, sources, cancellationToken).ConfigureAwait(false); @@ -130,28 +174,85 @@ public static async Task ExportAsync( string root = context.engineRoot; string output = PathBoundary.RequireUnlinkedPath(root, Path.GetFullPath(outputDirectory)); if (products.aggregateDirectory is not null) + { return await ExportAggregateAsync(context, plan, products, output, cancellationToken).ConfigureAwait(false); + } if (products.Count != plan.steps.Count) + { throw new InvalidDataException("Dependency export requires the exact complete product closure."); + } Directory.CreateDirectory(output); IReadOnlyList recipes = plan.CreateRecipes(context); - string revision = (await ToolchainEnvironment.CaptureOutputAsync("git", ["rev-parse", "HEAD"], root, cancellationToken).ConfigureAwait(false)).Trim(); + string revision = (await ToolchainEnvironment.CaptureOutputAsync( + "git", + ["rev-parse", "HEAD"], + root, + cancellationToken + ).ConfigureAwait(false)).Trim(); var assets = new List(); for (int index = 0; index < products.Count; index++) { ProductNativeBuildStep step = plan.steps[index]; NativeBuildProduct product = products[index]; if (product.component != step.id || product.targetId != context.RequireToolchain().targetId) + { throw new InvalidDataException("Dependency export encountered a foreign product."); - string[] sourcePaths = recipes[index].inputs.Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal)).Select(static input => input.logicalPath["engine/".Length..]).Append(step.component.nativeProject).Append(step.component.toolchainProject).Concat(step.component.bindingDefinition is string definition ? [definition] : Array.Empty()).Distinct(StringComparer.Ordinal).ToArray(); + } + string[] sourcePaths = recipes[index].inputs + .Where( + static input => ( + input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) + && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal) + ) + ) + .Select(static input => input.logicalPath["engine/".Length..]) + .Append(step.component.nativeProject) + .Append(step.component.toolchainProject) + .Concat(step.component.bindingDefinition is string definition ? [definition] : Array.Empty()) + .Distinct(StringComparer.Ordinal) + .ToArray(); if (step.component.bindingDefinition is not null) { - var bindingContext = new NativeBuildContext(root, step.configuration ?? context.configuration).WithToolchain(context.RequireToolchain()).WithBindingGenerator(context.RequireBindingGenerator()); - await bindingContext.RequireBindingGenerator().ComputeInputFingerprintAsync(bindingContext, new NativeBindingGenerationRequest([step.component], product.targetId, NativeBindingOutputMode.TargetArtifacts, componentOptions: new Dictionary { [step.component.nativeProject] = step.options }), cancellationToken).ConfigureAwait(false); - sourcePaths = sourcePaths.Concat(bindingContext.inputState.CaptureRecordedInputs(root).entries.Where(input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal)).Select(static input => input.logicalPath[7..])).Distinct(StringComparer.Ordinal).ToArray(); + var bindingContext = new NativeBuildContext(root, step.configuration ?? context.configuration) + .WithToolchain(context.RequireToolchain()) + .WithBindingGenerator(context.RequireBindingGenerator()); + await bindingContext + .RequireBindingGenerator() + .ComputeInputFingerprintAsync( + bindingContext, + new NativeBindingGenerationRequest( + [step.component], + product.targetId, + NativeBindingOutputMode.TargetArtifacts, + componentOptions: new Dictionary + { + [step.component.nativeProject] = step.options + } + ), + cancellationToken + ) + .ConfigureAwait(false); + sourcePaths = sourcePaths + .Concat( + bindingContext.inputState + .CaptureRecordedInputs(root).entries + .Where( + input => ( + input.logicalPath.StartsWith("engine/", StringComparison.Ordinal) + && !input.logicalPath.StartsWith("engine/artifacts/", StringComparison.Ordinal) + ) + ) + .Select(static input => input.logicalPath[7..]) + ) + .Distinct(StringComparer.Ordinal) + .ToArray(); } - Dictionary sources = await NativeDependencySource.CaptureAsync(root, sourcePaths, cancellationToken).ConfigureAwait(false); + Dictionary sources = await NativeDependencySource.CaptureAsync( + root, + sourcePaths, + cancellationToken + ).ConfigureAwait(false); string directory = Relative(product.directory); var selected = new HashSet(StringComparer.Ordinal) { @@ -161,10 +262,18 @@ public static async Task ExportAsync( if (product.bindingGeneration is { } generation) { if (generation.artifactDirectory.Length == 0) + { throw new InvalidDataException("Dependency publication requires immutable target binding generations."); + } string bindingDirectory = Relative(generation.artifactDirectory); selected.Add(bindingDirectory); - binding = new(generation.fingerprint, generation.usesRuntimeImports, bindingDirectory, Path.GetRelativePath(generation.artifactDirectory, generation.bindingsPath).Replace('\\', '/'), Path.GetRelativePath(generation.artifactDirectory, generation.nativeDirectory).Replace('\\', '/')); + binding = new( + generation.fingerprint, + generation.usesRuntimeImports, + bindingDirectory, + Path.GetRelativePath(generation.artifactDirectory, generation.bindingsPath).Replace('\\', '/'), + Path.GetRelativePath(generation.artifactDirectory, generation.nativeDirectory).Replace('\\', '/') + ); } string asset = step.id + "-" + product.targetId + "-" + product.fingerprint + ".zip"; @@ -172,13 +281,48 @@ public static async Task ExportAsync( await NativeArtifactTransfer.ExportAsync(root, archive, cancellationToken, selected).ConfigureAwait(false); using FileStream payload = File.OpenRead(archive); string digest = Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellationToken).ConfigureAwait(false)); - assets.Add(new(plan.productId, step.id, product.targetId, step.configuration ?? context.configuration, step.component.nativeProject, step.component.toolchainProject, Options(step), directory, product.fingerprint, product.sharedLibraryExtension, binding, sources, context.RequireToolchain().declarations.ToArray(), step.dependencies.ToDictionary(id => id, id => products.Single(product => product.component == id).fingerprint, StringComparer.Ordinal), asset, digest, revision)); + assets.Add( + new( + plan.productId, + step.id, + product.targetId, + step.configuration ?? context.configuration, + step.component.nativeProject, + step.component.toolchainProject, + Options(step), + directory, + product.fingerprint, + product.sharedLibraryExtension, + binding, + sources, + context.RequireToolchain().declarations.ToArray(), + step.dependencies.ToDictionary( + id => id, + id => products.Single(product => product.component == id).fingerprint, + StringComparer.Ordinal + ), + asset, + digest, + revision + ) + ); } foreach (DependencyAsset asset in assets) + { await VerifySourcesAsync(root, asset.sources, cancellationToken).ConfigureAwait(false); - string destination = Path.Combine(output, plan.productId + "-" + context.RequireToolchain().targetId + "-" + context.configuration + ".json"); - AtomicFile.WriteAllBytes(destination, JsonSerializer.SerializeToUtf8Bytes(new Selection(assets.ToArray(), [], "platform-packages"), new JsonSerializerOptions { WriteIndented = true })); + } + string destination = Path.Combine( + output, + plan.productId + "-" + context.RequireToolchain().targetId + "-" + context.configuration + ".json" + ); + AtomicFile.WriteAllBytes( + destination, + JsonSerializer.SerializeToUtf8Bytes( + new Selection(assets.ToArray(), [], "platform-packages"), + new JsonSerializerOptions { WriteIndented = true } + ) + ); return destination; string Relative(string path) => Path.GetRelativePath(Path.Combine(root, "artifacts"), path).Replace('\\', '/'); } @@ -224,31 +368,62 @@ public static async Task AcquireAsync( ToolchainEnvironment.ValidateConfiguration(configuration); string root = Path.GetFullPath(engineRoot); Selection selection = ReadSelection(selectionPath); - AggregateAsset[] aggregates = selection.aggregates.Where(asset => asset.product == plan.productId && asset.target == target && asset.configuration == configuration && asset.options == PlanOptions(plan)).ToArray(); + AggregateAsset[] aggregates = selection.aggregates + .Where( + asset => ( + asset.product == plan.productId + && asset.target == target + && asset.configuration == configuration + && asset.options == PlanOptions(plan) + ) + ) + .ToArray(); if (aggregates.Length > 1) + { throw new InvalidDataException("Native dependency selection contains ambiguous aggregate products."); + } if (aggregates.Length == 1) - return await AcquireAggregateAsync(root, Archive(aggregates[0].sha256), aggregates[0], plan, cancellationToken).ConfigureAwait(false); + { + return await AcquireAggregateAsync( + root, + Archive(aggregates[0].sha256), + aggregates[0], + plan, + cancellationToken + ).ConfigureAwait(false); + } if (selection.assets is null) + { throw new InvalidDataException("Native dependency selection has no asset inventory."); + } var expectedSources = new Dictionary(StringComparer.Ordinal); foreach (ProductNativeBuildStep step in plan.steps) { DependencyAsset asset = Select(step); foreach (var pair in asset.sources) + { if (expectedSources.TryGetValue(pair.Key, out string? existing) && existing != pair.Value) + { throw new InvalidDataException("Dependency assets disagree about a shared source input: " + pair.Key); + } else + { expectedSources[pair.Key] = pair.Value; + } + } } string Archive(string digest) { RequireDigest(digest); if (selection.layout != "platform-packages") + { throw new InvalidDataException("Native acquisition requires a bound platform package store."); + } if (!target.All(static value => char.IsAsciiLetterOrDigit(value) || value == '-')) + { throw new InvalidDataException("The native payload requires a registered platform name."); + } string store = Path.GetDirectoryName(Path.GetFullPath(selectionPath))!; return PathBoundary.RequireUnlinkedPath(store, PathBoundary.Resolve(store, $"{target}/native/{digest}.zip")); } @@ -264,19 +439,43 @@ string Archive(string digest) cancellationToken.ThrowIfCancellationRequested(); string selectedConfiguration = step.configuration ?? configuration; DependencyAsset asset = Select(step); - if (asset.nativeProject != step.component.nativeProject || asset.toolchainProject != step.component.toolchainProject || (asset.binding is null) != (step.component.bindingDefinition is null)) + if (asset.nativeProject != step.component.nativeProject + || asset.toolchainProject != step.component.toolchainProject + || (asset.binding is null) != (step.component.bindingDefinition is null) + ) { throw new InvalidDataException("Native dependency component ownership differs from the current product: " + step.id); - if (asset.dependencies.Count != step.dependencies.Count || step.dependencies.Any(id => !asset.dependencies.TryGetValue(id, out string? fingerprint) || products.Single(product => product.component == id).fingerprint != fingerprint)) - throw new InvalidDataException("Native dependency artifacts were compiled against a different dependency closure: " + step.id); + } + if (asset.dependencies.Count != step.dependencies.Count + || step.dependencies.Any( + id => ( + !asset.dependencies.TryGetValue(id, out string? fingerprint) + || products.Single(product => product.component == id).fingerprint != fingerprint + ) + ) + ) { + throw new InvalidDataException( + "Native dependency artifacts were compiled against a different dependency closure: " + step.id + ); + } RequireDigest(asset.sha256); RequireDigest(asset.fingerprint); string directory = ResolveArtifact(asset.directory, "native", asset.component, target, asset.fingerprint); string archive = Archive(asset.sha256); - if (!Directory.Exists(directory) || asset.binding is { } requiredBinding && !Directory.Exists(PathBoundary.Resolve(Path.Combine(root, "artifacts"), requiredBinding.directory))) - { + if (!Directory.Exists(directory) + || asset.binding is { } requiredBinding + && !Directory.Exists(PathBoundary.Resolve(Path.Combine(root, "artifacts"), requiredBinding.directory)) + ) { using (FileStream payload = File.OpenRead(archive)) - if (Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellationToken).ConfigureAwait(false)) != asset.sha256) - throw new InvalidDataException("Native dependency archive digest differs from its pinned selection: " + asset.asset); + { + if (Convert.ToHexStringLower( + await SHA256.HashDataAsync(payload, cancellationToken).ConfigureAwait(false) + ) != asset.sha256 + ) { + throw new InvalidDataException( + "Native dependency archive digest differs from its pinned selection: " + asset.asset + ); + } + } await NativeArtifactTransfer.ImportAsync(root, archive, cancellationToken).ConfigureAwait(false); } @@ -286,13 +485,35 @@ string Archive(string digest) RequireDigest(binding.fingerprint); string[] parts = binding.directory.Split('/'); if (parts.Length != 4) + { throw new InvalidDataException("Invalid native binding artifact location."); + } string bindingDirectory = ResolveArtifact(binding.directory, "bindings", parts[1], target, binding.fingerprint); string owner = Path.Combine(root, "artifacts", "bindings"); BuildCacheOwnerCatalog.Register(root, owner, "bindings", BuildCacheArtifactRole.ImmutableArtifact, cancellationToken); - reading.Add(await BuildArtifactReadLease.AcquireAsync(bindingDirectory, owner, binding.fingerprint, ["Generated", "Native"], cancellationToken: cancellationToken).ConfigureAwait(false)); - using (FileLease activity = await new BuildCachePublisher(owner, BuildCacheArtifactRole.ImmutableArtifact).AcquireUseAsync(cancellationToken).ConfigureAwait(false)) - new BuildCachePublisher(owner, BuildCacheArtifactRole.ImmutableArtifact).Record(bindingDirectory, bindingDirectory + ".read.lock", [], null, target, cancellationToken); + reading.Add( + await BuildArtifactReadLease.AcquireAsync( + bindingDirectory, + owner, + binding.fingerprint, + ["Generated", "Native"], + cancellationToken: cancellationToken + ).ConfigureAwait(false) + ); + using (FileLease activity = await new BuildCachePublisher( + owner, + BuildCacheArtifactRole.ImmutableArtifact + ).AcquireUseAsync(cancellationToken).ConfigureAwait(false) + ) { + new BuildCachePublisher(owner, BuildCacheArtifactRole.ImmutableArtifact).Record( + bindingDirectory, + bindingDirectory + ".read.lock", + [], + null, + target, + cancellationToken + ); + } generation = new() { fingerprint = binding.fingerprint, @@ -302,18 +523,37 @@ string Archive(string digest) bindingsPath = PathBoundary.Resolve(bindingDirectory, binding.managed), nativeDirectory = PathBoundary.Resolve(bindingDirectory, binding.native) }; - if (bindings.TryGetValue(step.component.nativeProject, out var previous) && previous.fingerprint != generation.fingerprint) + if (bindings.TryGetValue(step.component.nativeProject, out var previous) + && previous.fingerprint != generation.fingerprint + ) { throw new InvalidDataException("A dependency closure selected conflicting binding generations."); + } bindings[step.component.nativeProject] = generation; } string nativeOwner = Path.Combine(root, "artifacts", "native"); BuildCacheOwnerCatalog.Register(root, nativeOwner, "native", BuildCacheArtifactRole.ImmutableArtifact, cancellationToken); - BuildArtifactReadLease lease = await BuildArtifactReadLease.AcquireAsync(directory, nativeOwner, asset.fingerprint, ["Outputs", "Metadata"], cancellationToken: cancellationToken).ConfigureAwait(false); + BuildArtifactReadLease lease = await BuildArtifactReadLease.AcquireAsync( + directory, + nativeOwner, + asset.fingerprint, + ["Outputs", "Metadata"], + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { - using FileLease activity = await new BuildCachePublisher(nativeOwner, BuildCacheArtifactRole.ImmutableArtifact).AcquireUseAsync(cancellationToken).ConfigureAwait(false); - new BuildCachePublisher(nativeOwner, BuildCacheArtifactRole.ImmutableArtifact).Record(directory, directory + ".read.lock", generation is null ? [] : [generation.artifactDirectory], step.id + "/" + target + "/" + selectedConfiguration, target, cancellationToken); + using FileLease activity = await new BuildCachePublisher( + nativeOwner, + BuildCacheArtifactRole.ImmutableArtifact + ).AcquireUseAsync(cancellationToken).ConfigureAwait(false); + new BuildCachePublisher(nativeOwner, BuildCacheArtifactRole.ImmutableArtifact).Record( + directory, + directory + ".read.lock", + generation is null ? [] : [generation.artifactDirectory], + step.id + "/" + target + "/" + selectedConfiguration, + target, + cancellationToken + ); products.Add(new(step.id, target, asset.fingerprint, directory, generation, asset.extension, lease)); } catch @@ -329,25 +569,52 @@ string Archive(string digest) catch { foreach (NativeBuildProduct product in products) + { product.Dispose(); + } foreach (IDisposable lease in reading) + { lease.Dispose(); + } throw; } DependencyAsset Select(ProductNativeBuildStep step) { - DependencyAsset[] matches = selection.assets.Where(asset => asset.product == plan.productId && asset.component == step.id && asset.target == target && asset.configuration == (step.configuration ?? configuration) && asset.options == Options(step)).ToArray(); + DependencyAsset[] matches = selection.assets + .Where( + asset => ( + asset.product == plan.productId + && asset.component == step.id + && asset.target == target + && asset.configuration == (step.configuration ?? configuration) + && asset.options == Options(step) + ) + ) + .ToArray(); if (matches.Length != 1) - throw new InvalidDataException($"Native dependency '{step.id}/{target}/{step.configuration ?? configuration}' requires exactly one matching artifact. Produce the matching backend package for the requested target."); + { + throw new InvalidDataException( + $"Native dependency '{step.id}/{target}/{step.configuration ?? configuration}' requires exactly one matching artifact. Produce the matching backend package for the requested target." + ); + } return matches[0]; } async Task VerifySourcesAsync() { - Dictionary current = await NativeDependencySource.CaptureAsync(root, expectedSources.Keys, cancellationToken).ConfigureAwait(false); - if (current.Count != expectedSources.Count || current.Any(pair => !expectedSources.TryGetValue(pair.Key, out string? value) || value != pair.Value)) - throw new InvalidDataException("Native dependency sources changed. Produce the matching backend package for the requested target."); + Dictionary current = await NativeDependencySource.CaptureAsync( + root, + expectedSources.Keys, + cancellationToken + ).ConfigureAwait(false); + if (current.Count != expectedSources.Count + || current.Any(pair => !expectedSources.TryGetValue(pair.Key, out string? value) || value != pair.Value) + ) { + throw new InvalidDataException( + "Native dependency sources changed. Produce the matching backend package for the requested target." + ); + } } string ResolveArtifact( @@ -358,7 +625,9 @@ string ResolveArtifact( string fingerprint ) { if (relative != $"{owner}/{component}/{abi}/{fingerprint}" || component.Contains('/') || component.Contains('\\')) + { throw new InvalidDataException("Native dependency artifact is outside its exact declared owner."); + } return PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(Path.Combine(root, "artifacts"), relative)); } } @@ -368,7 +637,8 @@ private static Selection ReadSelection(string path) Selection selection; try { - selection = JsonSerializer.Deserialize(File.ReadAllBytes(path)) ?? throw new InvalidDataException("Native dependency selection is empty."); + selection = JsonSerializer.Deserialize(File.ReadAllBytes(path)) + ?? throw new InvalidDataException("Native dependency selection is empty."); } catch (JsonException failure) { @@ -376,20 +646,47 @@ private static Selection ReadSelection(string path) } if (selection.layout is not (null or "platform-packages")) + { throw new InvalidDataException("Unknown native payload layout."); + } if (selection.assets is null || selection.aggregates is null) + { throw new InvalidDataException("Native dependency selection requires component and aggregate inventories."); + } foreach (DependencyAsset asset in selection.assets) { - if (asset is null || asset.sources is null || asset.producerTools is null || asset.dependencies is null || string.IsNullOrWhiteSpace(asset.product) || string.IsNullOrWhiteSpace(asset.component) || string.IsNullOrWhiteSpace(asset.target) || string.IsNullOrWhiteSpace(asset.nativeProject) || string.IsNullOrWhiteSpace(asset.toolchainProject) || string.IsNullOrWhiteSpace(asset.options) || string.IsNullOrWhiteSpace(asset.directory)) + if (asset is null + || asset.sources is null + || asset.producerTools is null + || asset.dependencies is null + || string.IsNullOrWhiteSpace(asset.product) + || string.IsNullOrWhiteSpace(asset.component) + || string.IsNullOrWhiteSpace(asset.target) + || string.IsNullOrWhiteSpace(asset.nativeProject) + || string.IsNullOrWhiteSpace(asset.toolchainProject) + || string.IsNullOrWhiteSpace(asset.options) + || string.IsNullOrWhiteSpace(asset.directory) + ) { throw new InvalidDataException("Native dependency asset is missing required provenance or ownership."); + } ValidateAsset(asset.asset, asset.sha256, asset.fingerprint, asset.sources, asset.producerRevision); } foreach (AggregateAsset asset in selection.aggregates) { - if (asset is null || asset.sources is null || asset.producerTools is null || asset.bindings is null || string.IsNullOrWhiteSpace(asset.product) || string.IsNullOrWhiteSpace(asset.component) || string.IsNullOrWhiteSpace(asset.target) || string.IsNullOrWhiteSpace(asset.options) || string.IsNullOrWhiteSpace(asset.directory) || string.IsNullOrWhiteSpace(asset.aggregate)) + if (asset is null + || asset.sources is null + || asset.producerTools is null + || asset.bindings is null + || string.IsNullOrWhiteSpace(asset.product) + || string.IsNullOrWhiteSpace(asset.component) + || string.IsNullOrWhiteSpace(asset.target) + || string.IsNullOrWhiteSpace(asset.options) + || string.IsNullOrWhiteSpace(asset.directory) + || string.IsNullOrWhiteSpace(asset.aggregate) + ) { throw new InvalidDataException("Native aggregate is missing required provenance or ownership."); + } ValidateAsset(asset.asset, asset.sha256, asset.fingerprint, asset.sources, asset.producerRevision); } @@ -402,21 +699,34 @@ static void ValidateAsset( string revision ) { if (revision is null || revision.Length != 40 || revision.Any(static character => !char.IsAsciiHexDigitLower(character))) + { throw new InvalidDataException("Native dependency producer revision must be an exact commit."); + } RequireDigest(digest); RequireDigest(fingerprint); - if (string.IsNullOrWhiteSpace(name) || name != Path.GetFileName(name) || name.Contains('\\') || !name.EndsWith(".zip", StringComparison.Ordinal) || sources.Count == 0) + if (string.IsNullOrWhiteSpace(name) + || name != Path.GetFileName(name) + || name.Contains('\\') + || !name.EndsWith(".zip", StringComparison.Ordinal) + || sources.Count == 0 + ) { throw new InvalidDataException("Native dependency requires a named native archive and nonempty source provenance."); + } foreach (string identity in sources.Values) + { RequireDigest(identity); + } } } private static string Options(ProductNativeBuildStep step) => JsonSerializer.Serialize(new { step.options, step.dependencies }); + private static void RequireDigest(string value) { if (value is null || value.Length != 64 || value.Any(static character => !char.IsAsciiHexDigitLower(character))) + { throw new InvalidDataException("Native dependency digest must be a complete lowercase SHA-256 identity."); + } } private sealed record Selection( @@ -424,6 +734,7 @@ private sealed record Selection( AggregateAsset[] aggregates, string? layout = null ); + private sealed record BindingAsset( string fingerprint, bool runtimeImports, @@ -431,6 +742,7 @@ private sealed record BindingAsset( string managed, string native ); + private sealed record DependencyAsset( string product, string component, diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs index c0e5628ff..dd3eff97c 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; namespace Inno.Build.Toolchains; + internal static class NativeDependencySource { internal static async Task> CaptureAsync( @@ -16,31 +17,54 @@ internal static async Task> CaptureAsync( CancellationToken cancellation ) { string index = await GitAsync(["ls-files", "--stage", "-z"]).ConfigureAwait(false); - string[] modules = index.Split('\0', StringSplitOptions.RemoveEmptyEntries).Where(static item => item.StartsWith("160000 ", StringComparison.Ordinal)).Select(static item => item[(item.IndexOf('\t') + 1)..]).ToArray(); - string[] roots = paths.Select(path => modules.FirstOrDefault(module => path == module || path.StartsWith(module + "/", StringComparison.Ordinal)) ?? path).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + string[] modules = index + .Split('\0', StringSplitOptions.RemoveEmptyEntries) + .Where(static item => item.StartsWith("160000 ", StringComparison.Ordinal)) + .Select(static item => item[(item.IndexOf('\t') + 1)..]) + .ToArray(); + string[] roots = paths + .Select( + path => modules.FirstOrDefault(module => path == module || path.StartsWith(module + "/", StringComparison.Ordinal)) ?? path + ) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); if (roots.Length == 0) + { throw new InvalidDataException("A native dependency must declare tracked source inputs."); + } foreach (string path in roots) + { _ = Inno.Core.IO.PathBoundary.Resolve(root, path); - string dirty = await GitAsync(["status", "--porcelain", "--untracked-files=all", "--ignore-submodules=none", "--", ..roots]).ConfigureAwait(false); + } + string dirty = await GitAsync( + ["status", "--porcelain", "--untracked-files=all", "--ignore-submodules=none", "--", ..roots] + ).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(dirty)) + { throw new InvalidDataException("Native dependency sources must match their committed input: " + dirty); + } var result = new Dictionary(StringComparer.Ordinal); foreach (string[] batch in roots.Chunk(80)) { string tree = await GitAsync(["ls-tree", "-t", "-z", "HEAD", "--", ..batch]).ConfigureAwait(false); - var entries = tree.Split('\0', StringSplitOptions.RemoveEmptyEntries).ToDictionary(entry => entry[(entry.IndexOf('\t') + 1)..], StringComparer.Ordinal); + var entries = tree + .Split('\0', StringSplitOptions.RemoveEmptyEntries) + .ToDictionary(entry => entry[(entry.IndexOf('\t') + 1)..], StringComparer.Ordinal); foreach (string path in batch) { if (!entries.TryGetValue(path, out string? entry)) + { throw new InvalidDataException("Native dependency input has no committed owner: " + path); + } result.Add(path, NativeBuildFingerprint.Create([entry], [])); } } await VerifyWorkingTreeAsync(root, "HEAD", roots, cancellation).ConfigureAwait(false); return result; - Task GitAsync(string[] arguments) => ToolchainEnvironment.CaptureOutputAsync("git", ["--literal-pathspecs", ..arguments], root, cancellation); + Task GitAsync(string[] arguments) + => ToolchainEnvironment.CaptureOutputAsync("git", ["--literal-pathspecs", ..arguments], root, cancellation); } private static async Task VerifyWorkingTreeAsync( @@ -56,13 +80,19 @@ CancellationToken cancellation foreach (string entry in tree.Split('\0', StringSplitOptions.RemoveEmptyEntries)) { if (string.IsNullOrWhiteSpace(entry)) + { continue; + } int separator = entry.IndexOf('\t'); if (separator < 0) + { throw new InvalidDataException("Native source tree returned invalid object metadata."); + } string[] metadata = entry[..separator].Split(' '); if (metadata.Length != 3) + { throw new InvalidDataException("Native source tree returned incomplete object metadata."); + } string relative = entry[(separator + 1)..]; string path = Inno.Core.IO.PathBoundary.Resolve(root, relative); Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, Path.GetDirectoryName(path)!); @@ -72,9 +102,16 @@ CancellationToken cancellation // A consumer does not need a third-party checkout. An initialized checkout is mutable and must be checked. if (File.Exists(Path.Combine(path, ".git")) || Directory.Exists(Path.Combine(path, ".git"))) { - string head = await ToolchainEnvironment.CaptureOutputAsync("git", ["rev-parse", "HEAD"], path, cancellation).ConfigureAwait(false); + string head = await ToolchainEnvironment.CaptureOutputAsync( + "git", + ["rev-parse", "HEAD"], + path, + cancellation + ).ConfigureAwait(false); if (head.Trim() != metadata[2]) + { throw new InvalidDataException("Native submodule revision differs from its committed owner: " + relative); + } await VerifyWorkingTreeAsync(path, metadata[2], ["."], cancellation).ConfigureAwait(false); } } @@ -84,15 +121,21 @@ CancellationToken cancellation byte[] bytes = target is null ? File.ReadAllBytes(path) : Encoding.UTF8.GetBytes(target.Replace('\\', '/')); byte[] prefix = Encoding.ASCII.GetBytes("blob " + bytes.Length + "\0"); byte[] content = [..prefix, ..bytes]; - string identity = Convert.ToHexStringLower(metadata[2].Length == 40 ? SHA1.HashData(content) : SHA256.HashData(content)); + string identity = Convert.ToHexStringLower( + metadata[2].Length == 40 ? SHA1.HashData(content) : SHA256.HashData(content) + ); if (identity != metadata[2]) + { throw new InvalidDataException("Native source link changed: " + relative); + } } else { Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, path); if (!File.Exists(path)) + { throw new InvalidDataException("Native source is missing: " + relative); + } blobs[relative] = metadata[2]; } } @@ -103,21 +146,31 @@ CancellationToken cancellation string[] hashes = (await GitAsync(["hash-object", "--", ..batch.Select(static pair => pair.Key)]).ConfigureAwait(false)) .Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); if (hashes.Length != batch.Length) + { throw new InvalidDataException("Native source hashing returned an incomplete input inventory."); + } var changed = batch.Where(( pair, index ) => hashes[index] != pair.Value).ToArray(); if (changed.Length == 0) + { continue; + } // Existing CRLF blobs can already match their checkout even when the current clean filter normalizes them. - string[] raw = (await GitAsync(["hash-object", "--no-filters", "--", ..changed.Select(static pair => pair.Key)]).ConfigureAwait(false)) + string[] raw = (await GitAsync( + ["hash-object", "--no-filters", "--", ..changed.Select(static pair => pair.Key)] + ).ConfigureAwait(false)) .Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); if (raw.Length != changed.Length || changed.Where(( pair, index - ) => raw[index] != pair.Value).Any()) - throw new InvalidDataException("Native dependency source bytes changed. Produce the matching backend package for the requested target."); + ) => raw[index] != pair.Value).Any() + ) { + throw new InvalidDataException( + "Native dependency source bytes changed. Produce the matching backend package for the requested target." + ); + } } Task GitAsync(string[] arguments) => ToolchainEnvironment.CaptureOutputAsync("git", ["--literal-pathspecs", ..arguments], root, cancellation); diff --git a/build/toolchains/Inno.Build.Toolchains/Host/BuildHostServices.cs b/build/toolchains/Inno.Build.Toolchains/Host/BuildHostServices.cs index a449a3fab..c9403aa35 100644 --- a/build/toolchains/Inno.Build.Toolchains/Host/BuildHostServices.cs +++ b/build/toolchains/Inno.Build.Toolchains/Host/BuildHostServices.cs @@ -41,14 +41,17 @@ public BuildHostServices( /// Gets the host's scoped execution path provider. /// public IToolchainWorkspaceProvider workspaces { get; } + /// /// Gets environment variable name semantics. /// public StringComparer environmentComparer { get; } + /// /// Gets checkout-relative execution implementation inputs. /// public IReadOnlyList inputPaths { get; } + /// /// Gets the host-owned executable suffix. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs b/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs index 8ecc4da78..eaefef319 100644 --- a/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs +++ b/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs @@ -20,7 +20,9 @@ public ValueTask OpenAsync( ) { cancellationToken.ThrowIfCancellationRequested(); if (!Path.IsPathFullyQualified(physicalPath)) + { throw new ArgumentException("Tool execution requires an absolute physical owner path.", nameof(physicalPath)); + } string physical = Path.GetFullPath(physicalPath); Directory.CreateDirectory(physical); return ValueTask.FromResult(new ToolchainWorkingDirectory(physical)); diff --git a/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs b/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs index 498c73a2f..54f77ca6c 100644 --- a/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs +++ b/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs @@ -34,7 +34,9 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(arguments); cancellationToken.ThrowIfCancellationRequested(); if (arguments.Length == 0 || arguments[0] != "clean") + { throw new ArgumentException("Maintenance requires the clean command."); + } var options = new Dictionary(StringComparer.Ordinal); var allowed = new HashSet(StringComparer.Ordinal) { @@ -45,32 +47,56 @@ CancellationToken cancellationToken { string argument = arguments[index]; if (!argument.StartsWith("--", StringComparison.Ordinal) || !allowed.Contains(argument[2..])) + { throw new ArgumentException($"Unknown maintenance option '{argument}'."); + } string value = "true"; if (argument != "--dry-run") { if (++index >= arguments.Length || arguments[index].StartsWith("--", StringComparison.Ordinal)) + { throw new ArgumentException($"Missing value for '{argument}'."); + } value = arguments[index]; } if (!options.TryAdd(argument[2..], value)) + { throw new ArgumentException($"Duplicate maintenance option '{argument}'."); + } } if (options.GetValueOrDefault("scope") != "cache" || !options.TryGetValue("engine-root", out string? root)) + { throw new ArgumentException("Cache maintenance requires --scope cache and --engine-root."); + } long Bytes( string name, long fallback ) => options.TryGetValue(name, out string? value) - ? checked(long.Parse(value, NumberStyles.None, CultureInfo.InvariantCulture) * (1L << 30)) : fallback; - double seconds = double.Parse(options.GetValueOrDefault("cache-time-seconds", "600"), - NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); - await CleanAsync(root, new BuildCachePolicy(Bytes("cache-budget-gib", 64L << 30), - Bytes("cache-min-free-gib", 20L << 30), TimeSpan.FromSeconds(seconds)), - true, options.ContainsKey("dry-run"), options.GetValueOrDefault("target"), cancellationToken).ConfigureAwait(false); + ? checked(long.Parse(value, NumberStyles.None, CultureInfo.InvariantCulture) * (1L << 30)) + : fallback; + double seconds = double.Parse( + options.GetValueOrDefault("cache-time-seconds", "600"), + NumberStyles.AllowDecimalPoint, + CultureInfo.InvariantCulture + ); + await CleanAsync( + root, + new BuildCachePolicy( + Bytes("cache-budget-gib", 64L << 30), + Bytes("cache-min-free-gib", 20L << 30), + TimeSpan.FromSeconds(seconds) + ), + true, + options.ContainsKey("dry-run"), + options.GetValueOrDefault("target"), + cancellationToken + ).ConfigureAwait(false); return 0; } - catch (OperationCanceledException) { return 2; } + catch (OperationCanceledException) + { + return 2; + } catch (Exception failure) { Console.Error.WriteLine(failure); @@ -130,7 +156,11 @@ CancellationToken cancellationToken inventoryBudget.CancelAfter(policy.timeBudget); try { - owners = BuildCacheOwnerCatalog.ReadOwners(engineRoot, new BuildCacheInventoryProgress(engineRoot, dryRun), inventoryBudget.Token); + owners = BuildCacheOwnerCatalog.ReadOwners( + engineRoot, + new BuildCacheInventoryProgress(engineRoot, dryRun), + inventoryBudget.Token + ); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { @@ -139,18 +169,36 @@ CancellationToken cancellationToken } TimeSpan remaining = policy.timeBudget - elapsed.Elapsed; if (remaining <= TimeSpan.Zero) + { throw new TimeoutException("Cache owner discovery exhausted its operation budget; no artifact was retired."); + } var remainingPolicy = new BuildCachePolicy(policy.maximumBytes, policy.minimumFreeBytes, remaining); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(engineRoot, - owners, remainingPolicy, retireAll, targetId, cancellationToken); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + engineRoot, + owners, + remainingPolicy, + retireAll, + targetId, + cancellationToken + ); if (dryRun) + { foreach (BuildCacheArtifactDescriptor artifact in plan.candidates) + { Console.WriteLine($"Would retire {artifact.directory} ({artifact.bytes} bytes)"); + } + } BuildCacheCleanupResult result = await plan.ExecuteAsync(dryRun, cancellationToken).ConfigureAwait(false); - Console.WriteLine($"Cache: {plan.totalBytes} bytes; protected {plan.protectedBytes}; reclaimed {result.retiredBytes}; skipped {result.skipped.Count}."); + Console.WriteLine( + $"Cache: {plan.totalBytes} bytes; protected {plan.protectedBytes}; reclaimed {result.retiredBytes}; skipped {result.skipped.Count}." + ); foreach (var failure in result.failures) + { Console.Error.WriteLine($"Cache retirement failed: {failure.Key}: {failure.Value}"); + } if (retireAll && result.failures.Count != 0) + { throw new InvalidOperationException("Explicit cache cleanup completed with failures."); + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkEnvironment.cs b/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkEnvironment.cs index 53f07e3f6..f40e223e6 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkEnvironment.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkEnvironment.cs @@ -45,10 +45,16 @@ public static class DotNetSdkEnvironment string host = ToolchainEnvironment.ResolveExecutable(hostPath); var selected = new Dictionary(StringComparer.OrdinalIgnoreCase); if (environment is not null) + { foreach ((string name, string value) in environment) + { selected[name] = value; + } + } foreach (string variable in AmbientSdkVariables) + { selected[variable] = null; + } selected["DOTNET_HOST_PATH"] = host; selected["DOTNET_ROOT"] = Path.GetDirectoryName(host)!; return new ReadOnlyDictionary(selected); diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkResolver.cs b/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkResolver.cs index 0b77850be..8431d6c07 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkResolver.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/DotNetSdkResolver.cs @@ -41,7 +41,9 @@ public static ValueTask ResolveAsync( ArgumentException.ThrowIfNullOrWhiteSpace(projectPath); string project = Path.GetFullPath(projectPath); if (!File.Exists(project)) + { throw new FileNotFoundException("The managed entry project is absent.", project); + } return ResolveDirectoryAsync(hostPath, Path.GetDirectoryName(project)!, cancellationToken); } @@ -81,30 +83,44 @@ public static async ValueTask ResolveDirectoryAsync( ArgumentException.ThrowIfNullOrWhiteSpace(ownerDirectory); string directory = Path.GetFullPath(ownerDirectory); if (!Directory.Exists(directory)) + { throw new DirectoryNotFoundException($"The managed SDK source owner is absent: '{directory}'."); + } hostPath = ToolchainEnvironment.ResolveExecutable(hostPath); - string information = await ToolchainEnvironment.CaptureOutputAsync(hostPath, ["--info"], - directory, cancellationToken, + string information = await ToolchainEnvironment.CaptureOutputAsync( + hostPath, + ["--info"], + directory, + cancellationToken, DotNetSdkEnvironment.Create(hostPath, new Dictionary { ["DOTNET_CLI_UI_LANGUAGE"] = "en-US" - })).ConfigureAwait(false); + }) + ).ConfigureAwait(false); string identity = string.Empty; string sdkDirectory = string.Empty; foreach (string outputLine in information.Split('\n')) { string line = outputLine.Trim(); if (identity.Length == 0 && line.StartsWith("Version:", StringComparison.Ordinal)) + { identity = line["Version:".Length..].Trim(); + } if (line.StartsWith("Base Path:", StringComparison.Ordinal)) + { sdkDirectory = line["Base Path:".Length..].Trim(); + } } string numericVersion = identity.Split('-', 2)[0]; if (!Version.TryParse(numericVersion, out _) || !Path.IsPathFullyQualified(sdkDirectory)) + { throw new InvalidOperationException("The managed host did not resolve a valid project SDK identity and base path."); + } string cli = Path.Combine(sdkDirectory, "dotnet.dll"); if (!File.Exists(cli)) + { throw new FileNotFoundException("The selected SDK managed CLI entry assembly is unavailable.", cli); + } return new DotNetSdkDescriptor(hostPath, identity, cli); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs index 973048219..1ae7afdae 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs @@ -78,7 +78,9 @@ public ValueTask VerifyAsync(CancellationToken cancellationToken = default) cancellationToken.ThrowIfCancellationRequested(); using FileStream stream = File.OpenRead(input.physicalPath); if (!SHA256.HashData(stream).AsSpan().SequenceEqual(input.hash)) + { throw new InvalidOperationException($"Fixed managed input '{input.logicalPath}' changed during execution."); + } } return ValueTask.CompletedTask; } @@ -115,34 +117,69 @@ CancellationToken cancellation ) { string entry = Path.GetRelativePath(context.engineRoot, project); if (Path.IsPathRooted(entry) || entry == ".." || entry.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { throw new ArgumentException("A managed execution entry must belong to its declared source root.", nameof(project)); - string identity = NativeBuildFingerprint.Create(new[] { "managed-workspace", context.engineRoot, project, - sdk.hostPath, sdk.sdkIdentity, sdk.cliPath }.Concat(properties.OrderBy(static pair => pair.Key, StringComparer.Ordinal) - .Select(static pair => pair.Key + "=" + pair.Value)), []); + } + string identity = NativeBuildFingerprint.Create( + new[] + { + "managed-workspace", + context.engineRoot, + project, + sdk.hostPath, + sdk.sdkIdentity, + sdk.cliPath + }.Concat( + properties.OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => pair.Key + "=" + pair.Value) + ), + [] + ); string workspace = Path.Combine(context.engineRoot, "artifacts", "managed", "workspaces", identity); - var cache = new BuildCachePublisher(Path.Combine(context.engineRoot, "artifacts", "managed", "workspaces"), BuildCacheArtifactRole.ReusableWorkspace); - BuildCacheOwnerCatalog.Register(context.engineRoot, Path.GetDirectoryName(workspace)!, "managed-workspaces", cache.role, cancellation); + var cache = new BuildCachePublisher( + Path.Combine(context.engineRoot, "artifacts", "managed", "workspaces"), + BuildCacheArtifactRole.ReusableWorkspace + ); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + Path.GetDirectoryName(workspace)!, + "managed-workspaces", + cache.role, + cancellation + ); using FileLease cacheUse = await cache.AcquireUseAsync(cancellation).ConfigureAwait(false); - CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync(Path.Combine(Path.GetDirectoryName(workspace)!, "owner.lock"), workspace + ".lock", Timeout.InfiniteTimeSpan, cancellationToken: cancellation).ConfigureAwait(false); + CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync( + Path.Combine(Path.GetDirectoryName(workspace)!, "owner.lock"), + workspace + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken: cancellation + ).ConfigureAwait(false); try { - cache.BeginWorkingDirectory(workspace, workspace + ".lock", - properties.TryGetValue("InnoNativeTarget", out string? selectedTarget) ? selectedTarget : context.toolchain?.targetId, cancellation); + cache.BeginWorkingDirectory( + workspace, + workspace + ".lock", + properties.TryGetValue("InnoNativeTarget", out string? selectedTarget) ? selectedTarget : context.toolchain?.targetId, + cancellation + ); string sourceRoot = Path.Combine(workspace, "Sources"); string metadata = Path.Combine(workspace, "inputs.json"); NativeInputSnapshot captured = context.inputState.CaptureRecordedInputs(context.engineRoot); var selected = captured.entries.Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal)) - .Where(input => IsSource(context.engineRoot, input.logicalPath["engine/".Length..])).ToArray(); + .Where(input => IsSource(context.engineRoot, input.logicalPath["engine/".Length..])) + .ToArray(); var paths = new HashSet(selected.Select(static input => input.logicalPath["engine/".Length..]), StringComparer.Ordinal); if (File.Exists(metadata)) { string[] previous = JsonSerializer.Deserialize(File.ReadAllText(metadata)) - ?? throw new InvalidDataException("A managed workspace has no owned input inventory."); + ?? throw new InvalidDataException("A managed workspace has no owned input inventory."); foreach (string removed in previous.Where(path => !paths.Contains(path))) { string file = PathBoundary.RequireUnlinkedPath(sourceRoot, PathBoundary.Resolve(sourceRoot, removed)); if (File.Exists(file)) + { File.Delete(file); + } } } var fixedInputs = new List(); @@ -155,11 +192,20 @@ CancellationToken cancellation } string marker = Path.Combine(sourceRoot, "InnoEngine.sln"); if (!File.Exists(marker)) + { File.WriteAllText(marker, "Managed execution source owner.", new UTF8Encoding(false)); + } AtomicFile.WriteAllBytes(metadata, JsonSerializer.SerializeToUtf8Bytes(paths.Order(StringComparer.Ordinal).ToArray())); - return new(ownership, sourceRoot, PathBoundary.Resolve(sourceRoot, entry), fixedInputs.AsReadOnly(), - cache, workspace, project + "/" + context.configuration, - properties.TryGetValue("InnoNativeTarget", out string? targetId) ? targetId : context.toolchain?.targetId); + return new( + ownership, + sourceRoot, + PathBoundary.Resolve(sourceRoot, entry), + fixedInputs.AsReadOnly(), + cache, + workspace, + project + "/" + context.configuration, + properties.TryGetValue("InnoNativeTarget", out string? targetId) ? targetId : context.toolchain?.targetId + ); } catch { @@ -176,9 +222,13 @@ string relative foreach (string segment in relative.Split('/')) { if (segment == ".git" || segment == "artifacts" && directory == root) + { return false; + } if (segment is "bin" or "obj" && Directory.EnumerateFiles(directory, "*.csproj").Any()) + { return false; + } directory = Path.Combine(directory, segment); } return true; diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs index 5da044ee1..630362b35 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using System.Text.Json; using System.Xml.Linq; using Inno.Core.IO; @@ -19,26 +19,62 @@ internal static async ValueTask CaptureAsync( IReadOnlyDictionary properties, CancellationToken cancellation ) { - using ManagedInputEvaluation evaluation = await ManagedInputEvaluation.OpenAsync(context, sdk, project, - properties, cancellation).ConfigureAwait(false); + using ManagedInputEvaluation evaluation = await ManagedInputEvaluation.OpenAsync( + context, + sdk, + project, + properties, + cancellation + ).ConfigureAwait(false); context.RecordManagedProcess(); - await ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "restore", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet", - .. evaluation.properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value)], - context.engineRoot, cancellation, DotNetSdkEnvironment.Create(sdk.hostPath, context.toolchain?.environment)).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [ + sdk.cliPath, + "restore", + project, + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--nologo", + "-v:quiet", + .. evaluation.properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value) + ], + context.engineRoot, + cancellation, + DotNetSdkEnvironment.Create(sdk.hostPath, context.toolchain?.environment) + ).ConfigureAwait(false); _ = await EvaluateAsync(context, sdk, project, evaluation.properties, true, cancellation).ConfigureAwait(false); XElement captured = await EvaluateAsync(context, sdk, project, evaluation.properties, false, cancellation).ConfigureAwait(false); - var inputs = captured.Elements("Input").Select(element => NativeBuildInput.FromPath(context.engineRoot, - (string?)element.Attribute("Path") ?? throw new InvalidDataException("A managed input has no physical location."))).ToList(); + var inputs = captured.Elements("Input").Select(element => NativeBuildInput.FromPath( + context.engineRoot, + (string?)element.Attribute("Path") ?? throw new InvalidDataException("A managed input has no physical location.") + )).ToList(); foreach (XElement assets in captured.Elements("Assets")) + { CollectPackageInputs(context, assets, inputs, cancellation); - inputs.AddRange(new[] { sdk.hostPath, sdk.cliPath, - Path.Combine(Path.GetDirectoryName(sdk.cliPath)!, "Roslyn", "bincore") } - .Select(path => NativeBuildInput.FromPath(context.engineRoot, path))); - string[] declarations = captured.Elements("Declaration").Select(static element => element.Value) - .Prepend("sdk=" + sdk.sdkIdentity).Prepend("project=" + project).ToArray(); + } + inputs.AddRange( + new[] + { + sdk.hostPath, + sdk.cliPath, + Path.Combine(Path.GetDirectoryName(sdk.cliPath)!, "Roslyn", "bincore") + } + .Select(path => NativeBuildInput.FromPath(context.engineRoot, path)) + ); + string[] declarations = captured.Elements("Declaration") + .Select(static element => element.Value) + .Prepend("sdk=" + sdk.sdkIdentity) + .Prepend("project=" + project) + .ToArray(); // Evaluator implementation participates without depending on unrelated tool assembly MVIDs. - declarations = declarations.Append("evaluator=" + ((string?)captured.Attribute("EvaluatorFingerprint") ?? throw new InvalidDataException("The evaluator identity is absent."))).ToArray(); + declarations = declarations + .Append( + "evaluator=" + + ((string?)captured.Attribute("EvaluatorFingerprint") ?? throw new InvalidDataException("The evaluator identity is absent.")) + ) + .ToArray(); string fingerprint = NativeBuildFingerprint.Create(context, declarations, inputs, cancellation); evaluation.Complete(cancellation); return new ManagedBuildInputCapture(fingerprint, declarations); @@ -53,7 +89,13 @@ private static async ValueTask EvaluateAsync( CancellationToken cancellation ) { string requests = Path.Combine(context.engineRoot, "artifacts", "build-tools", "managed-inputs", "requests"); - BuildCacheOwnerCatalog.Register(context.engineRoot, requests, "managed-input-requests", BuildCacheArtifactRole.ProcessWorkingDirectory, cancellation); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + requests, + "managed-input-requests", + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellation + ); using ProcessOwnedDirectory requestOwner = await ProcessOwnedDirectory.CreateAsync(requests, cancellation).ConfigureAwait(false); string request = requestOwner.directory; string manifest = Path.Combine(request, "Inputs.xml"); @@ -62,29 +104,54 @@ CancellationToken cancellation try { using ManagedInputEvaluatorPreparation.Result evaluator = await ManagedInputEvaluatorPreparation.PrepareAsync( - context, sdk, cancellation).ConfigureAwait(false); + context, + sdk, + cancellation + ).ConfigureAwait(false); using Stream template = typeof(ManagedBuildInputReader).Assembly.GetManifestResourceStream( - "Inno.Build.Toolchains.Managed.ManagedBuildInputs.targets") - ?? throw new InvalidOperationException("The managed graph evaluator resource is absent."); + "Inno.Build.Toolchains.Managed.ManagedBuildInputs.targets" + ) + ?? throw new InvalidOperationException("The managed graph evaluator resource is absent."); XElement document = XElement.Load(template); using Stream compilerInputs = typeof(ManagedBuildInputReader).Assembly.GetManifestResourceStream( - "Inno.Build.Toolchains.Managed.ManagedCompilerInputs.targets") - ?? throw new InvalidOperationException("The compiler input target resource is absent."); + "Inno.Build.Toolchains.Managed.ManagedCompilerInputs.targets" + ) + ?? throw new InvalidOperationException("The compiler input target resource is absent."); string compilerInputsPath = Path.Combine(request, "CompilerInputs.targets"); using (FileStream destination = File.Create(compilerInputsPath)) + { await compilerInputs.CopyToAsync(destination, cancellation).ConfigureAwait(false); - document.AddFirst(new XElement("PropertyGroup", - new XElement("InnoCompilerInputsTargets", compilerInputsPath), - new XElement("InnoInputProject", project), new XElement("InnoRestoreContributions", restoreContributions), new XElement("InnoInputOutput", manifest), - new XElement("InnoInputEvaluator", Path.Combine(evaluator.directory, "Outputs", "ManagedInputGraphTask.dll")))); - document.Add(new XElement("ItemGroup", properties.OrderBy(static pair => pair.Key, StringComparer.OrdinalIgnoreCase) - .Select(static pair => new XElement("InnoInputProperty", new XAttribute("Include", pair.Key), - new XElement("Value", pair.Value))))); + } + document.AddFirst( + new XElement( + "PropertyGroup", + new XElement("InnoCompilerInputsTargets", compilerInputsPath), + new XElement("InnoInputProject", project), + new XElement("InnoRestoreContributions", restoreContributions), + new XElement("InnoInputOutput", manifest), + new XElement("InnoInputEvaluator", Path.Combine(evaluator.directory, "Outputs", "ManagedInputGraphTask.dll")) + ) + ); + document.Add( + new XElement( + "ItemGroup", + properties.OrderBy(static pair => pair.Key, StringComparer.OrdinalIgnoreCase) + .Select(static pair => new XElement( + "InnoInputProperty", + new XAttribute("Include", pair.Key), + new XElement("Value", pair.Value) + )) + ) + ); await File.WriteAllTextAsync(entry, document.ToString(), cancellation).ConfigureAwait(false); context.RecordManagedProcess(); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "msbuild", entry, "-t:CaptureManagedInputs", "-nologo", "-v:quiet", "-m:1", "-nodeReuse:false"], - context.engineRoot, cancellation, DotNetSdkEnvironment.Create(sdk.hostPath, context.toolchain?.environment)).ConfigureAwait(false); + context.engineRoot, + cancellation, + DotNetSdkEnvironment.Create(sdk.hostPath, context.toolchain?.environment) + ).ConfigureAwait(false); XElement captured = XElement.Load(manifest); captured.SetAttributeValue("EvaluatorFingerprint", evaluator.fingerprint); return captured; @@ -103,47 +170,67 @@ CancellationToken cancellation ) { string assets = (string)selected.Attribute("Path")!; if (!File.Exists(assets)) + { throw new FileNotFoundException("Managed input planning requires the selected project's restored dependency graph.", assets); + } inputs.Add(NativeBuildInput.FromPath(context.engineRoot, assets)); using JsonDocument document = JsonDocument.Parse(File.ReadAllText(assets)); JsonElement root = document.RootElement; JsonElement targets = root.GetProperty("targets"); string selectedTarget = (string)selected.Attribute("Target")!; if (!targets.TryGetProperty(selectedTarget, out JsonElement target)) - throw new InvalidDataException($"Restored graph '{assets}' does not contain target '{selectedTarget}'. " - + "Available targets: " + string.Join(", ", targets.EnumerateObject().Select(static item => item.Name)) + "."); + { + throw new InvalidDataException( + $"Restored graph '{assets}' does not contain target '{selectedTarget}'. " + + "Available targets: " + string.Join(", ", targets.EnumerateObject().Select(static item => item.Name)) + "." + ); + } string[] folders = root.GetProperty("packageFolders").EnumerateObject().Select(static folder => folder.Name).ToArray(); JsonElement libraries = root.GetProperty("libraries"); foreach (JsonProperty dependency in target.EnumerateObject()) { cancellation.ThrowIfCancellationRequested(); if (dependency.Value.GetProperty("type").GetString() != "package") + { continue; + } JsonElement library = libraries.GetProperty(dependency.Name); string location = library.GetProperty("path").GetString() - ?? throw new InvalidDataException("A restored package has no physical location."); + ?? throw new InvalidDataException("A restored package has no physical location."); string directory = folders.Select(folder => PathBoundary.Resolve(folder, location)).FirstOrDefault(Directory.Exists) - ?? throw new DirectoryNotFoundException($"The restored package '{dependency.Name}' is unavailable."); + ?? throw new DirectoryNotFoundException($"The restored package '{dependency.Name}' is unavailable."); var files = new HashSet(StringComparer.Ordinal); foreach (string group in new[] { "compile", "runtime", "native", "resource", "runtimeTargets", "build", - "buildMultiTargeting", "buildTransitive", "contentFiles" }) + "buildMultiTargeting", "buildTransitive", "contentFiles" } + ) { if (dependency.Value.TryGetProperty(group, out JsonElement entries)) + { foreach (JsonProperty entry in entries.EnumerateObject()) + { files.Add(entry.Name); + } + } + } foreach (JsonElement entry in library.GetProperty("files").EnumerateArray()) { string file = entry.GetString()!; if (file.StartsWith("analyzers/", StringComparison.Ordinal) - && !file.Contains("/vb/", StringComparison.Ordinal) && !file.Contains("/fs/", StringComparison.Ordinal)) + && !file.Contains("/vb/", StringComparison.Ordinal) && !file.Contains("/fs/", StringComparison.Ordinal) + ) { files.Add(file); + } } foreach (string file in files) { if (Path.GetFileName(file) == "_._") + { continue; + } string path = PathBoundary.Resolve(directory, file); if (!File.Exists(path)) + { throw new FileNotFoundException($"The restored package input '{dependency.Name}/{file}' is absent.", path); + } inputs.Add(NativeBuildInput.FromPath(context.engineRoot, path)); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs index 141722a08..7f4711bf4 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs @@ -114,11 +114,19 @@ public static async ValueTask CaptureAsync( string selected = new PhysicalPathResolver().Resolve(Path.GetFullPath(project, context.engineRoot)); PathBoundary.RequireContained(context.engineRoot, selected); if (!File.Exists(selected)) + { throw new FileNotFoundException("The managed input entry project is absent.", selected); + } var frozen = new System.Collections.ObjectModel.ReadOnlyDictionary( - properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase)); - ManagedBuildInputCapture identity = await ManagedBuildInputReader.CaptureAsync(context, sdk, selected, frozen, - cancellationToken).ConfigureAwait(false); + properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase) + ); + ManagedBuildInputCapture identity = await ManagedBuildInputReader.CaptureAsync( + context, + sdk, + selected, + frozen, + cancellationToken + ).ConfigureAwait(false); return new(context, sdk, selected, frozen, identity); } @@ -140,8 +148,12 @@ public static async ValueTask CaptureAsync( public async ValueTask VerifyAsync(CancellationToken cancellationToken = default) { ManagedBuildInputCapture current = await ManagedBuildInputReader.CaptureAsync( - m_context.BeginInputVerification("managed-inputs"), m_sdk, m_project, m_properties, - cancellationToken).ConfigureAwait(false); + m_context.BeginInputVerification("managed-inputs"), + m_sdk, + m_project, + m_properties, + cancellationToken + ).ConfigureAwait(false); if (current.fingerprint != fingerprint) { var changed = new List(); @@ -149,17 +161,30 @@ public async ValueTask VerifyAsync(CancellationToken cancellationToken = default { cancellationToken.ThrowIfCancellationRequested(); if (!File.Exists(input.physicalPath)) + { changed.Add(input.logicalPath + " (missing)"); + } else { using FileStream stream = File.OpenRead(input.physicalPath); if (!SHA256.HashData(stream).AsSpan().SequenceEqual(input.hash)) + { changed.Add(input.logicalPath); + } } } - throw new InvalidOperationException("Managed compilation inputs changed after planning; the candidate cannot be accepted. " - + (changed.Count == 0 ? "Changed declarations: " + string.Join("; ", current.declarations.Except(m_declarations).Select(static item => "added " + item) - .Concat(m_declarations.Except(current.declarations).Select(static item => "removed " + item)).Take(20)) : "Changed files: " + string.Join(", ", changed))); + throw new InvalidOperationException( + "Managed compilation inputs changed after planning; the candidate cannot be accepted. " + + (changed.Count == 0 + ? "Changed declarations: " + string.Join( + "; ", + current.declarations.Except(m_declarations) + .Select(static item => "added " + item) + .Concat(m_declarations.Except(current.declarations).Select(static item => "removed " + item)) + .Take(20) + ) + : "Changed files: " + string.Join(", ", changed)) + ); } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs index 56f1fb5b1..4832919ea 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs @@ -44,18 +44,36 @@ CancellationToken cancellation ) { // An explicitly supplied SDK layout remains the caller's owned concurrency boundary. if (properties.Keys.Any(static name => name.Equals("ArtifactsPath", StringComparison.OrdinalIgnoreCase))) + { return new(properties, null, null, string.Empty, null); - string identity = NativeBuildFingerprint.Create(new[] { "managed-input-layout", context.engineRoot, - project, sdk.hostPath, sdk.cliPath, sdk.sdkIdentity } - .Concat(properties.OrderBy(static pair => pair.Key, StringComparer.OrdinalIgnoreCase) - .Select(static pair => pair.Key + "=" + pair.Value)), []); + } + string identity = NativeBuildFingerprint.Create( + new[] + { + "managed-input-layout", + context.engineRoot, + project, + sdk.hostPath, + sdk.cliPath, + sdk.sdkIdentity + } + .Concat( + properties.OrderBy(static pair => pair.Key, StringComparer.OrdinalIgnoreCase) + .Select(static pair => pair.Key + "=" + pair.Value) + ), + [] + ); string root = Path.Combine(context.engineRoot, "artifacts", "managed", "evaluations"); string directory = Path.Combine(root, identity); var cache = new BuildCachePublisher(root, BuildCacheArtifactRole.ReusableWorkspace); BuildCacheOwnerCatalog.Register(context.engineRoot, root, "managed-evaluations", cache.role, cancellation); using FileLease activity = await cache.AcquireUseAsync(cancellation).ConfigureAwait(false); - CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync(Path.Combine(root, "owner.lock"), - directory + ".lock", Timeout.InfiniteTimeSpan, cancellationToken: cancellation).ConfigureAwait(false); + CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync( + Path.Combine(root, "owner.lock"), + directory + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken: cancellation + ).ConfigureAwait(false); try { string? target = properties.TryGetValue("InnoNativeTarget", out string? selected) ? selected : context.toolchain?.targetId; diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs index 3de2eca65..54b0e29bf 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs @@ -15,9 +15,11 @@ internal sealed class Result( string directory, string fingerprint, BuildArtifactReadLease reading - ) : IDisposable { + ) : IDisposable + { internal string directory { get; } = directory; internal string fingerprint { get; } = fingerprint; + /// public void Dispose() => reading.Dispose(); } @@ -28,29 +30,56 @@ internal static async ValueTask PrepareAsync( CancellationToken cancellation ) { using Stream source = typeof(ManagedInputEvaluatorPreparation).Assembly.GetManifestResourceStream( - "Inno.Build.Toolchains.Managed.ManagedInputGraphTask.cs.txt") - ?? throw new InvalidOperationException("The managed graph evaluator source resource is absent."); + "Inno.Build.Toolchains.Managed.ManagedInputGraphTask.cs.txt" + ) + ?? throw new InvalidOperationException("The managed graph evaluator source resource is absent."); using var reader = new StreamReader(source); string code = await reader.ReadToEndAsync(cancellation).ConfigureAwait(false); using Stream compilerInputs = typeof(ManagedInputEvaluatorPreparation).Assembly.GetManifestResourceStream( - "Inno.Build.Toolchains.Managed.ManagedCompilerInputs.targets") - ?? throw new InvalidOperationException("The compiler input target resource is absent."); + "Inno.Build.Toolchains.Managed.ManagedCompilerInputs.targets" + ) + ?? throw new InvalidOperationException("The compiler input target resource is absent."); using var compilerInputsReader = new StreamReader(compilerInputs); string compilerInputsCode = await compilerInputsReader.ReadToEndAsync(cancellation).ConfigureAwait(false); string sdkRoot = Path.GetDirectoryName(sdk.cliPath)!; - string[] assemblies = ["Microsoft.Build.dll", "Microsoft.Build.Framework.dll", "Microsoft.Build.Utilities.Core.dll", "NuGet.Frameworks.dll"]; + string[] assemblies = [ + "Microsoft.Build.dll", + "Microsoft.Build.Framework.dll", + "Microsoft.Build.Utilities.Core.dll", + "NuGet.Frameworks.dll" + ]; NativeBuildInput[] inputs = assemblies.Select(name => NativeBuildInput.FromPath(context.engineRoot, Path.Combine(sdkRoot, name))) - .Concat(new[] { sdk.cliPath, sdk.hostPath, Path.Combine(sdkRoot, "Roslyn", "bincore"), - Path.Combine(sdkRoot, "Microsoft.NETCoreSdk.BundledVersions.props") } - .Select(path => NativeBuildInput.FromPath(context.engineRoot, path))).ToArray(); + .Concat( + new[] + { + sdk.cliPath, + sdk.hostPath, + Path.Combine(sdkRoot, "Roslyn", "bincore"), + Path.Combine(sdkRoot, "Microsoft.NETCoreSdk.BundledVersions.props") + } + .Select(path => NativeBuildInput.FromPath(context.engineRoot, path)) + ) + .ToArray(); string[] declarations = ["managed-input-evaluator", "net10.0", "Release", sdk.sdkIdentity, code, compilerInputsCode]; string fingerprint = NativeBuildFingerprint.Create(context, declarations, inputs, cancellation); string directory = Path.Combine(context.engineRoot, "artifacts", "build-tools", "managed-inputs", "evaluators", fingerprint); var cache = new BuildCachePublisher(Path.GetDirectoryName(directory)!, BuildCacheArtifactRole.ImmutableArtifact); - BuildCacheOwnerCatalog.Register(context.engineRoot, Path.GetDirectoryName(directory)!, "managed-evaluators", cache.role, cancellation); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + Path.GetDirectoryName(directory)!, + "managed-evaluators", + cache.role, + cancellation + ); using FileLease activity = await cache.AcquireUseAsync(cancellation).ConfigureAwait(false); - BuildArtifactReadLease? existing = await BuildArtifactReadLease.TryAcquireAsync(directory, Path.GetDirectoryName(directory)!, fingerprint, - ["Outputs"], context, cancellation).ConfigureAwait(false); + BuildArtifactReadLease? existing = await BuildArtifactReadLease.TryAcquireAsync( + directory, + Path.GetDirectoryName(directory)!, + fingerprint, + ["Outputs"], + context, + cancellation + ).ConfigureAwait(false); if (existing is not null) { try @@ -64,42 +93,91 @@ CancellationToken cancellation throw; } } - using (FileLease generation = await FileLease.AcquireAsync(directory + ".generation.lock", - Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false)) - { + using (FileLease generation = await FileLease.AcquireAsync( + directory + ".generation.lock", + Timeout.InfiniteTimeSpan, + cancellation + ).ConfigureAwait(false) + ) { Verify("managed-evaluator-lock"); if (!BuildArtifactManifest.IsComplete(directory, fingerprint, ["Outputs"], context)) { - using ProcessOwnedDirectory candidateOwner = await ProcessOwnedDirectory.CreateAsync(Path.GetDirectoryName(directory)!, cancellation).ConfigureAwait(false); + using ProcessOwnedDirectory candidateOwner = await ProcessOwnedDirectory.CreateAsync( + Path.GetDirectoryName(directory)!, + cancellation + ).ConfigureAwait(false); string candidate = candidateOwner.directory; try { Directory.CreateDirectory(candidate); string project = Path.Combine(candidate, "ManagedInputGraphTask.csproj"); - var definition = new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), new XElement("LangVersion", "14.0"), new XElement("OutputType", "Library"), - new XElement("ImplicitUsings", "disable"), new XElement("Nullable", "disable"), - new XElement("ImportDirectoryBuildProps", "false"), new XElement("ImportDirectoryBuildTargets", "false"), - new XElement("GenerateAssemblyInfo", "false"), new XElement("DebugType", "None"), - new XElement("DebugSymbols", "false")), - new XElement("ItemGroup", assemblies.Select(name => new XElement("Reference", - new XAttribute("Include", Path.GetFileNameWithoutExtension(name)), - new XElement("HintPath", Path.Combine(sdkRoot, name)), new XElement("Private", "false"))))); + var definition = new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("LangVersion", "14.0"), + new XElement("OutputType", "Library"), + new XElement("ImplicitUsings", "disable"), + new XElement("Nullable", "disable"), + new XElement("ImportDirectoryBuildProps", "false"), + new XElement("ImportDirectoryBuildTargets", "false"), + new XElement("GenerateAssemblyInfo", "false"), + new XElement("DebugType", "None"), + new XElement("DebugSymbols", "false") + ), + new XElement( + "ItemGroup", + assemblies.Select(name => new XElement( + "Reference", + new XAttribute("Include", Path.GetFileNameWithoutExtension(name)), + new XElement("HintPath", Path.Combine(sdkRoot, name)), + new XElement("Private", "false") + )) + ) + ); await File.WriteAllTextAsync(project, definition.ToString(), cancellation).ConfigureAwait(false); - await File.WriteAllTextAsync(Path.Combine(candidate, "ManagedInputGraphTask.cs"), code, cancellation).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(candidate, "ManagedInputGraphTask.cs"), + code, + cancellation + ).ConfigureAwait(false); context.RecordManagedProcess(); - await ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "build", project, "--configuration", "Release", "--output", Path.Combine(candidate, "Outputs"), - "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet"], - context.engineRoot, cancellation, DotNetSdkEnvironment.Create(sdk.hostPath)).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [ + sdk.cliPath, + "build", + project, + "--configuration", + "Release", + "--output", + Path.Combine(candidate, "Outputs"), + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--nologo", + "-v:quiet" + ], + context.engineRoot, + cancellation, + DotNetSdkEnvironment.Create(sdk.hostPath) + ).ConfigureAwait(false); Verify("managed-evaluator-build"); File.Delete(project); File.Delete(Path.Combine(candidate, "ManagedInputGraphTask.cs")); string intermediate = Path.Combine(candidate, "obj"); if (Directory.Exists(intermediate)) + { Directory.Delete(intermediate, recursive: true); + } BuildArtifactManifest.Write(candidate, fingerprint, ["Outputs"], context); - using BuildArtifactWriteLease mutation = await BuildArtifactWriteLease.AcquireAsync(directory, Path.GetDirectoryName(directory)!, cancellation).ConfigureAwait(false); + using BuildArtifactWriteLease mutation = await BuildArtifactWriteLease.AcquireAsync( + directory, + Path.GetDirectoryName(directory)!, + cancellation + ).ConfigureAwait(false); try { AtomicDirectory.Install(candidate, directory); @@ -115,8 +193,14 @@ await ToolchainEnvironment.RunAsync(sdk.hostPath, } } } - BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(directory, Path.GetDirectoryName(directory)!, - fingerprint, ["Outputs"], cancellation, context).ConfigureAwait(false); + BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + directory, + Path.GetDirectoryName(directory)!, + fingerprint, + ["Outputs"], + cancellation, + context + ).ConfigureAwait(false); try { cache.Record(directory, directory + ".read.lock", [], sdk.sdkIdentity, null, cancellation); @@ -131,7 +215,9 @@ await ToolchainEnvironment.RunAsync(sdk.hostPath, void Verify(string phase) { if (NativeBuildFingerprint.Create(context.BeginInputVerification(phase), declarations, inputs, cancellation) != fingerprint) + { throw new InvalidOperationException("The managed evaluator's selected SDK changed; no candidate was published."); + } } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs index 67472809a..3d9abe9cf 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs @@ -59,7 +59,11 @@ public static async Task CaptureAsync( bool resolveReferences = false ) { ValidateProjects(projects, properties); - DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync(dotnetHost, engineRoot, cancellationToken).ConfigureAwait(false); + DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync( + dotnetHost, + engineRoot, + cancellationToken + ).ConfigureAwait(false); return await EvaluateAsync(engineRoot, sdk, projects, properties, cancellationToken, resolveReferences).ConfigureAwait(false); } @@ -119,10 +123,16 @@ IReadOnlyDictionary properties ArgumentNullException.ThrowIfNull(projects); ArgumentNullException.ThrowIfNull(properties); if (projects.Count == 0 || projects.Any(static project => !Path.IsPathFullyQualified(project))) + { throw new ArgumentException("SDK capture requires nonempty absolute project paths.", nameof(projects)); + } foreach (string project in projects) + { if (!File.Exists(project)) + { throw new FileNotFoundException("The SDK project input is missing.", project); + } + } } private static async Task EvaluateAsync( @@ -134,45 +144,99 @@ private static async Task EvaluateAsync( bool resolveReferences ) { var context = new NativeBuildContext(engineRoot, "debug"); - using ManagedInputEvaluatorPreparation.Result evaluator = await ManagedInputEvaluatorPreparation.PrepareAsync(context, sdk, cancellationToken).ConfigureAwait(false); + using ManagedInputEvaluatorPreparation.Result evaluator = await ManagedInputEvaluatorPreparation.PrepareAsync( + context, + sdk, + cancellationToken + ).ConfigureAwait(false); string requests = Path.Combine(context.engineRoot, "artifacts", "build-tools", "managed-inputs", "requests"); - BuildCacheOwnerCatalog.Register(context.engineRoot, requests, "managed-input-requests", BuildCacheArtifactRole.ProcessWorkingDirectory, cancellationToken); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + requests, + "managed-input-requests", + BuildCacheArtifactRole.ProcessWorkingDirectory, + cancellationToken + ); using ProcessOwnedDirectory request = await ProcessOwnedDirectory.CreateAsync(requests, cancellationToken).ConfigureAwait(false); string output = Path.Combine(request.directory, "Graph.json"); string entry = Path.Combine(request.directory, "Graph.proj"); string compilerTargets = Path.Combine(request.directory, "RepositoryReferences.targets"); - var compiler = new XElement("Project", - new XElement("Import", new XAttribute("Project", "$(InnoOriginalCustomAfterMicrosoftCommonTargets)"), - new XAttribute("Condition", "'$(InnoOriginalCustomAfterMicrosoftCommonTargets)' != '' and Exists('$(InnoOriginalCustomAfterMicrosoftCommonTargets)')")), - new XElement("Target", new XAttribute("Name", "KeepInnoReferenceCaptureReadOnly"), + var compiler = new XElement( + "Project", + new XElement( + "Import", + new XAttribute("Project", "$(InnoOriginalCustomAfterMicrosoftCommonTargets)"), + new XAttribute( + "Condition", + "'$(InnoOriginalCustomAfterMicrosoftCommonTargets)' != '' and Exists('$(InnoOriginalCustomAfterMicrosoftCommonTargets)')" + ) + ), + new XElement( + "Target", + new XAttribute("Name", "KeepInnoReferenceCaptureReadOnly"), new XAttribute("BeforeTargets", "ResolveProjectReferences"), - new XElement("PropertyGroup", new XElement("BuildProjectReferences", "false"))), - new XElement("Target", new XAttribute("Name", "CaptureInnoRepositoryReferences"), + new XElement("PropertyGroup", new XElement("BuildProjectReferences", "false")) + ), + new XElement( + "Target", + new XAttribute("Name", "CaptureInnoRepositoryReferences"), new XAttribute("DependsOnTargets", "ResolveReferences;AddImplicitDefineConstants"), new XAttribute("Returns", "@(_InnoRepositoryCapture)"), - new XElement("ItemGroup", - new[] { "ReferencePath", "Compile" }.Select(name => new XElement("_InnoRepositoryCapture", - new XAttribute("Include", name == "Compile" ? "@(Compile->'%(FullPath)')" : "@(ReferencePath)"), new XElement("CaptureKind", name))), + new XElement( + "ItemGroup", + new[] { "ReferencePath", "Compile" }.Select(name => new XElement( + "_InnoRepositoryCapture", + new XAttribute("Include", name == "Compile" ? "@(Compile->'%(FullPath)')" : "@(ReferencePath)"), + new XElement("CaptureKind", name) + )), new[] { "TargetPath", "DefineConstants", "LangVersion", "Nullable", "AllowUnsafeBlocks" }.Select(name => - new XElement("_InnoRepositoryCapture", new XAttribute("Include", name), - new XElement("CaptureKind", "Property"), new XElement("Value", "$(" + name + ")")))))); - var document = new XElement("Project", - new XElement("UsingTask", new XAttribute("TaskName", "Inno.Build.Toolchains.ManagedInputGraphTask"), - new XAttribute("AssemblyFile", Path.Combine(evaluator.directory, "Outputs", "ManagedInputGraphTask.dll"))), - new XElement("ItemGroup", + new XElement( + "_InnoRepositoryCapture", + new XAttribute("Include", name), + new XElement("CaptureKind", "Property"), + new XElement("Value", "$(" + name + ")") + )) + ) + ) + ); + var document = new XElement( + "Project", + new XElement( + "UsingTask", + new XAttribute("TaskName", "Inno.Build.Toolchains.ManagedInputGraphTask"), + new XAttribute("AssemblyFile", Path.Combine(evaluator.directory, "Outputs", "ManagedInputGraphTask.dll")) + ), + new XElement( + "ItemGroup", projects.Select(project => new XElement("RepositoryProject", new XAttribute("Include", project))), - properties.Select(pair => new XElement("InputProperty", new XAttribute("Include", pair.Key), new XElement("Value", pair.Value)))), - new XElement("Target", new XAttribute("Name", "Capture"), - new XElement("Inno.Build.Toolchains.ManagedInputGraphTask", new XAttribute("ProjectPath", projects[0]), - new XAttribute("OutputPath", output), new XAttribute("CompilerInputsTargets", compilerTargets), + properties.Select( + pair => new XElement("InputProperty", new XAttribute("Include", pair.Key), new XElement("Value", pair.Value)) + ) + ), + new XElement( + "Target", + new XAttribute("Name", "Capture"), + new XElement( + "Inno.Build.Toolchains.ManagedInputGraphTask", + new XAttribute("ProjectPath", projects[0]), + new XAttribute("OutputPath", output), + new XAttribute("CompilerInputsTargets", compilerTargets), new XAttribute("ResolveRepositoryReferences", resolveReferences), - new XAttribute("RepositoryProjects", "@(RepositoryProject)"), new XAttribute("Properties", "@(InputProperty)")))); + new XAttribute("RepositoryProjects", "@(RepositoryProject)"), + new XAttribute("Properties", "@(InputProperty)") + ) + ) + ); Directory.CreateDirectory(request.directory); await File.WriteAllTextAsync(compilerTargets, compiler.ToString(), cancellationToken).ConfigureAwait(false); await File.WriteAllTextAsync(entry, document.ToString(), cancellationToken).ConfigureAwait(false); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "msbuild", entry, "-t:Capture", "-nologo", "-v:minimal", "-m:1", "-nodeReuse:false"], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(sdk.hostPath)).ConfigureAwait(false); + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(sdk.hostPath) + ).ConfigureAwait(false); return await File.ReadAllTextAsync(output, cancellationToken).ConfigureAwait(false); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs b/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs index a6b4ac8b9..3db86107e 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs @@ -22,27 +22,40 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(plan); cancellationToken.ThrowIfCancellationRequested(); if (plan.steps.Any(static step => step.build is null)) + { throw new NotSupportedException("This closure requires its platform's static aggregate executor."); + } NativeToolchainSelection toolchain = context.RequireToolchain(); plan.CreateRecipes(context); - NativeBindingGenerationResult bindings = await NativeBindingPreparation.PrepareAsync(context, - plan.steps.Select(static step => step.component).ToArray(), cancellationToken, + NativeBindingGenerationResult bindings = await NativeBindingPreparation.PrepareAsync( + context, + plan.steps.Select(static step => step.component).ToArray(), + cancellationToken, plan.steps.Where(static step => step.component.bindingDefinition is not null) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal)).ConfigureAwait(false); + .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal) + ).ConfigureAwait(false); var completed = new Dictionary(StringComparer.Ordinal); var borrowed = new ReadOnlyDictionary(completed); try { context = context.WithBindings(bindings); if (await ProductNativeCacheLookup.TryAcquireAsync(context, plan.steps, cancellationToken).ConfigureAwait(false) - is IReadOnlyList cached) + is IReadOnlyList cached + ) { return new ProductNativeBuildResult(cached, bindings); + } foreach (ProductNativeBuildStep step in plan.steps) { cancellationToken.ThrowIfCancellationRequested(); - NativeBuildContext configured = step.configuration is string configuration ? context.WithConfiguration(configuration) : context; - NativeBuildProduct product = await step.build!(configured.WithComponentOptions(step.component, step.options), borrowed, cancellationToken).ConfigureAwait(false); + NativeBuildContext configured = step.configuration is string configuration + ? context.WithConfiguration(configuration) + : context; + NativeBuildProduct product = await step.build!( + configured.WithComponentOptions(step.component, step.options), + borrowed, + cancellationToken + ).ConfigureAwait(false); if (product.component != step.id || product.targetId != toolchain.targetId) { product.Dispose(); @@ -60,11 +73,13 @@ CancellationToken cancellationToken } catch (Exception releaseFailure) { - throw new AggregateException("Native preparation failed and reading ownership could not be completely released.", - buildFailure, releaseFailure); + throw new AggregateException( + "Native preparation failed and reading ownership could not be completely released.", + buildFailure, + releaseFailure + ); } throw; } } - } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs index 785d72361..4d43a8f8e 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs @@ -57,7 +57,9 @@ NativeArtifactRole role ) { ArgumentException.ThrowIfNullOrWhiteSpace(logicalId); if (!Path.IsPathFullyQualified(file) || !Enum.IsDefined(role)) + { throw new ArgumentException("Native outputs require an absolute file and an explicit supported role."); + } this.logicalId = logicalId; this.file = Path.GetFullPath(file); this.role = role; @@ -67,10 +69,12 @@ NativeArtifactRole role /// Gets the producer-owned output identity. /// public string logicalId { get; } + /// /// Gets the exact absolute output path. /// public string file { get; } + /// /// Gets the explicit link or deployment role. /// @@ -81,25 +85,50 @@ internal static void Write( IReadOnlyList artifacts ) { string output = Path.Combine(directory, "Outputs"); - if (artifacts.Count == 0 || artifacts.Select(static item => item.logicalId).Distinct(StringComparer.Ordinal).Count() != artifacts.Count) + if (artifacts.Count == 0 + || artifacts.Select(static item => item.logicalId).Distinct(StringComparer.Ordinal).Count() != artifacts.Count + ) { throw new InvalidDataException("A Native output inventory must contain unique logical identities."); + } foreach (NativeArtifact artifact in artifacts) + { PathBoundary.RequireUnlinkedPath(output, artifact.file); - if (!artifacts.Select(static artifact => artifact.file).ToHashSet(StringComparer.Ordinal) - .SetEquals(PathBoundary.EnumerateFiles(output))) + } + if (!artifacts.Select(static artifact => artifact.file) + .ToHashSet(StringComparer.Ordinal) + .SetEquals(PathBoundary.EnumerateFiles(output)) + ) { throw new InvalidDataException("The declared Native output inventory must match every produced file exactly."); + } Directory.CreateDirectory(Path.Combine(directory, "Metadata")); - File.WriteAllBytes(Path.Combine(directory, "Metadata", "artifacts.json"), JsonSerializer.SerializeToUtf8Bytes( - artifacts.Select(artifact => new Entry(artifact.logicalId, Path.GetRelativePath(output, artifact.file).Replace('\\', '/'), artifact.role)).ToArray())); + File.WriteAllBytes( + Path.Combine(directory, "Metadata", "artifacts.json"), + JsonSerializer.SerializeToUtf8Bytes( + artifacts + .Select( + artifact => new Entry( + artifact.logicalId, + Path.GetRelativePath(output, artifact.file).Replace('\\', '/'), + artifact.role + ) + ) + .ToArray() + ) + ); } internal static IReadOnlyList Read(string directory) { Entry[] entries = JsonSerializer.Deserialize(File.ReadAllBytes(Path.Combine(directory, "Metadata", "artifacts.json"))) - ?? throw new InvalidDataException("The Native output inventory is absent."); + ?? throw new InvalidDataException("The Native output inventory is absent."); string output = Path.Combine(directory, "Outputs"); - return Array.AsReadOnly(entries.Select(entry => new NativeArtifact(entry.logicalId, - PathBoundary.Resolve(output, entry.path), entry.role)).ToArray()); + return Array.AsReadOnly( + entries.Select(entry => new NativeArtifact( + entry.logicalId, + PathBoundary.Resolve(output, entry.path), + entry.role + )).ToArray() + ); } private sealed record Entry( diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs index 29ccbcf06..d4139125a 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs @@ -61,9 +61,12 @@ public static async Task PublishAsync( cancellationToken.ThrowIfCancellationRequested(); NativeComponentDescriptor owner = recipe.owner; NativeBindingGenerationDescriptor? bindingGeneration = owner.bindingDefinition is null - ? null : context.RequireBindings(owner); + ? null + : context.RequireBindings(owner); if (bindingGeneration is not null) + { recipe = recipe.WithBindingGeneration(context.engineRoot, bindingGeneration); + } string component = recipe.component; string targetId = recipe.targetId; NativeInputSnapshot snapshot = context.inputState.CaptureInitial(recipe.inputs, cancellationToken); @@ -72,53 +75,105 @@ public static async Task PublishAsync( NativeBuildContext scoped = context.WithIdentity(owner, targetId, workspaceIdentity); string intermediate = scoped.GetNativeBuildRoot(owner); string destination = Path.Combine(context.engineRoot, "artifacts", "native", component, targetId, fingerprint); - var cache = new BuildCachePublisher(Path.Combine(context.engineRoot, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); - BuildCacheOwnerCatalog.Register(context.engineRoot, Path.Combine(context.engineRoot, "artifacts", "native"), "native", cache.role, cancellationToken); + var cache = new BuildCachePublisher( + Path.Combine(context.engineRoot, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + Path.Combine(context.engineRoot, "artifacts", "native"), + "native", + cache.role, + cancellationToken + ); using FileLease cacheUse = await cache.AcquireUseAsync(cancellationToken).ConfigureAwait(false); - var workspaces = new BuildCachePublisher(Path.Combine(owner.GetToolchainRoot(context.engineRoot), "obj", "native"), BuildCacheArtifactRole.ReusableWorkspace); - BuildCacheOwnerCatalog.Register(context.engineRoot, Path.Combine(owner.GetToolchainRoot(context.engineRoot), "obj", "native"), - "workspace:" + owner.toolchainProject, workspaces.role, cancellationToken); + var workspaces = new BuildCachePublisher( + Path.Combine(owner.GetToolchainRoot(context.engineRoot), "obj", "native"), + BuildCacheArtifactRole.ReusableWorkspace + ); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + Path.Combine(owner.GetToolchainRoot(context.engineRoot), "obj", "native"), + "workspace:" + owner.toolchainProject, + workspaces.role, + cancellationToken + ); using FileLease workspaceUse = await workspaces.AcquireUseAsync(cancellationToken).ConfigureAwait(false); - using FileLease ownership = await FileLease.AcquireAsync(intermediate + ".lock", - Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + using FileLease ownership = await FileLease.AcquireAsync( + intermediate + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); - if (NativeBuildFingerprint.Create(context.BeginInputVerification("native-lock:" + component), - recipe.declarations, recipe.inputs, cancellationToken) != fingerprint) + if (NativeBuildFingerprint.Create( + context.BeginInputVerification("native-lock:" + component), + recipe.declarations, + recipe.inputs, + cancellationToken + ) != fingerprint + ) { throw new InvalidOperationException($"Native inputs for '{component}' changed while waiting for ownership."); + } workspaces.BeginWorkingDirectory(intermediate, intermediate + ".lock", targetId, cancellationToken); - AtomicFile.WriteAllBytes(Path.Combine(intermediate, "recipe.json"), JsonSerializer.SerializeToUtf8Bytes(new - { - component, - targetId, - context.configuration, - workspaceIdentity, - artifactFingerprint = fingerprint, - recipe.owner.nativeProject, - recipe.owner.toolchainProject, - recipe.declarations, - inputs = snapshot.entries.Select(static entry => new + AtomicFile.WriteAllBytes( + Path.Combine(intermediate, "recipe.json"), + JsonSerializer.SerializeToUtf8Bytes(new { - entry.logicalPath, - hash = Convert.ToHexStringLower(entry.hash) + component, + targetId, + context.configuration, + workspaceIdentity, + artifactFingerprint = fingerprint, + recipe.owner.nativeProject, + recipe.owner.toolchainProject, + recipe.declarations, + inputs = snapshot.entries.Select(static entry => new + { + entry.logicalPath, + hash = Convert.ToHexStringLower(entry.hash) + }) }) - })); + ); BuildArtifactReadLease? cached = await BuildArtifactReadLease.TryAcquireAsync( - destination, Path.Combine(context.engineRoot, "artifacts", "native"), fingerprint, ["Outputs", "Metadata"], context, cancellationToken).ConfigureAwait(false); + destination, + Path.Combine(context.engineRoot, "artifacts", "native"), + fingerprint, + ["Outputs", "Metadata"], + context, + cancellationToken + ).ConfigureAwait(false); if (cached is not null) { Record(cached); - return new(component, targetId, fingerprint, destination, bindingGeneration, context.toolchain?.linkPlan.sharedLibraryExtension, cached); + return new( + component, + targetId, + fingerprint, + destination, + bindingGeneration, + context.toolchain?.linkPlan.sharedLibraryExtension, + cached + ); } if (Directory.Exists(destination)) - Console.Error.WriteLine($"Rejected incomplete or modified Native cache '{destination}'; it remains isolated from consumers until verified replacement succeeds."); + { + Console.Error.WriteLine( + $"Rejected incomplete or modified Native cache '{destination}'; it remains isolated from consumers until verified replacement succeeds." + ); + } void Record(BuildArtifactReadLease reading) { try { - cache.Record(destination, destination + ".read.lock", + cache.Record( + destination, + destination + ".read.lock", bindingGeneration is { artifactDirectory.Length: > 0 } ? [bindingGeneration.artifactDirectory] : [], - component + "/" + targetId + "/" + context.configuration, targetId, cancellationToken); + component + "/" + targetId + "/" + context.configuration, + targetId, + cancellationToken + ); } catch { @@ -127,7 +182,10 @@ void Record(BuildArtifactReadLease reading) } } - using ProcessOwnedDirectory candidateOwner = await ProcessOwnedDirectory.CreateAsync(Path.Combine(context.engineRoot, "artifacts", "native"), cancellationToken).ConfigureAwait(false); + using ProcessOwnedDirectory candidateOwner = await ProcessOwnedDirectory.CreateAsync( + Path.Combine(context.engineRoot, "artifacts", "native"), + cancellationToken + ).ConfigureAwait(false); string staging = candidateOwner.directory; string output = Path.Combine(staging, "Outputs"); Directory.CreateDirectory(output); @@ -135,25 +193,56 @@ void Record(BuildArtifactReadLease reading) { IToolchainWorkspaceProvider execution = context.toolchain?.host.services.workspaces ?? new PhysicalToolchainWorkspaceProvider(); using (ToolchainWorkingDirectory workspace = await execution.OpenAsync( - intermediate, cancellationToken).ConfigureAwait(false)) - await build(scoped.WithToolDirectory(workspace.toolPath).WithExecutionInputs(snapshot), - output, cancellationToken).ConfigureAwait(false); + intermediate, + cancellationToken + ).ConfigureAwait(false) + ) { + await build( + scoped.WithToolDirectory(workspace.toolPath).WithExecutionInputs(snapshot), + output, + cancellationToken + ).ConfigureAwait(false); + } cancellationToken.ThrowIfCancellationRequested(); if (!PathBoundary.EnumerateFiles(output).Any()) + { throw new InvalidOperationException($"Native component '{component}' produced no output files."); - if (NativeBuildFingerprint.Create(context.BeginInputVerification("native-build:" + component), - recipe.declarations, recipe.inputs, cancellationToken) != fingerprint) - throw new InvalidOperationException($"Native inputs for '{component}' changed during preparation; the candidate was not published."); + } + if (NativeBuildFingerprint.Create( + context.BeginInputVerification("native-build:" + component), + recipe.declarations, + recipe.inputs, + cancellationToken + ) != fingerprint + ) { + throw new InvalidOperationException( + $"Native inputs for '{component}' changed during preparation; the candidate was not published." + ); + } // Validate compiler workspace links before publishing the immutable candidate. - workspaces.Record(intermediate, intermediate + ".lock", [], - targetId + "/" + context.configuration, targetId, cancellationToken); - NativeArtifact.Write(staging, describeOutputs?.Invoke(scoped, output) - ?? PathBoundary.EnumerateFiles(output).Select(file => new NativeArtifact(Path.GetRelativePath(output, file), file, NativeArtifactRole.SupportFile)).ToArray()); + workspaces.Record( + intermediate, + intermediate + ".lock", + [], + targetId + "/" + context.configuration, + targetId, + cancellationToken + ); + NativeArtifact.Write( + staging, + describeOutputs?.Invoke(scoped, output) + ?? PathBoundary.EnumerateFiles(output) + .Select(file => new NativeArtifact(Path.GetRelativePath(output, file), file, NativeArtifactRole.SupportFile)) + .ToArray() + ); BuildArtifactManifest.Write(staging, fingerprint, ["Outputs", "Metadata"], context); cancellationToken.ThrowIfCancellationRequested(); - using (BuildArtifactWriteLease publication = await BuildArtifactWriteLease.AcquireAsync(destination, Path.Combine(context.engineRoot, "artifacts", "native"), - cancellationToken).ConfigureAwait(false)) - { + using (BuildArtifactWriteLease publication = await BuildArtifactWriteLease.AcquireAsync( + destination, + Path.Combine(context.engineRoot, "artifacts", "native"), + cancellationToken + ).ConfigureAwait(false) + ) { try { AtomicDirectory.Install(staging, destination); @@ -163,15 +252,29 @@ await build(scoped.WithToolDirectory(workspace.toolPath).WithExecutionInputs(sna Console.Error.WriteLine(cleanupFailure.Message); } } - BuildArtifactReadLease reading = await BuildArtifactReadLease.TryAcquireAsync(destination, Path.Combine(context.engineRoot, "artifacts", "native"), fingerprint, ["Outputs", "Metadata"], context, cancellationToken).ConfigureAwait(false) + BuildArtifactReadLease reading = await BuildArtifactReadLease.TryAcquireAsync( + destination, + Path.Combine(context.engineRoot, "artifacts", "native"), + fingerprint, + ["Outputs", "Metadata"], + context, + cancellationToken + ).ConfigureAwait(false) ?? throw new InvalidDataException("The published Native artifact changed before reading ownership was acquired."); Record(reading); - return new(component, targetId, fingerprint, destination, bindingGeneration, context.toolchain?.linkPlan.sharedLibraryExtension, reading); + return new( + component, + targetId, + fingerprint, + destination, + bindingGeneration, + context.toolchain?.linkPlan.sharedLibraryExtension, + reading + ); } finally { candidateOwner.Dispose(); } } - } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs index 16fa3b123..ba84a26c9 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs @@ -19,13 +19,16 @@ CancellationToken cancellationToken ) { var text = new StringBuilder("include_guard(GLOBAL)\nfunction(inno_apply_binding target owner)\n"); foreach (var entry in context.selectedBindings.Where(entry => target is null || entry.Key == owner.nativeProject) - .OrderBy(static entry => entry.Key, StringComparer.Ordinal)) - { + .OrderBy(static entry => entry.Key, StringComparer.Ordinal) + ) { NativeBindingGenerationDescriptor generation = entry.Value; if (generation.nativeDirectory.Length == 0) + { continue; + } NativeBindingCompilation compilation = NativeBindingCompilation.Load(generation.nativeDirectory); - string ResolveRoot(string id) => sources.ResolvePath(compilation.ResolveRoot(context.engineRoot, generation.nativeDirectory, id)); + string ResolveRoot(string id) + => sources.ResolvePath(compilation.ResolveRoot(context.engineRoot, generation.nativeDirectory, id)); compilation.VerifyInputs(ResolveRoot, cancellationToken); text.AppendLine("if(owner STREQUAL " + Literal(Path.GetFileNameWithoutExtension(entry.Key)) + ")"); NativeBindingSourceFile[] units = compilation.files.Where(static file => file.compile).ToArray(); @@ -41,47 +44,81 @@ CancellationToken cancellationToken text.AppendLine("target_sources(${binding_target} PRIVATE " + source + ")"); } foreach (string define in compilation.defines) + { text.AppendLine("target_compile_definitions(${binding_target} PRIVATE " + Literal(define) + ")"); + } foreach (NativeBindingIncludeDirectory include in compilation.includeDirectories) { NativeBindingSourceRoot root = compilation.roots.Single(root => root.id == include.rootId); // SDK search roots are requirements of the selected compiler, not duplicate -isystem flags. if (!root.frozen && include.system && !include.framework) + { continue; - string directory = include.relativePath.Length == 0 ? ResolveRoot(include.rootId) - : sources.ResolvePath(PathBoundary.Resolve(compilation.ResolveRoot(context.engineRoot, generation.nativeDirectory, include.rootId), include.relativePath)); + } + string directory = include.relativePath.Length == 0 + ? ResolveRoot(include.rootId) + : sources.ResolvePath( + PathBoundary.Resolve( + compilation.ResolveRoot(context.engineRoot, generation.nativeDirectory, include.rootId), + include.relativePath + ) + ); if (include.framework) - text.AppendLine("target_compile_options(${binding_target} PRIVATE " + Literal("SHELL:-iframework \"" + directory.Replace('\\', '/') + "\"") + ")"); + { + text.AppendLine( + "target_compile_options(${binding_target} PRIVATE " + + Literal("SHELL:-iframework \"" + directory.Replace('\\', '/') + "\"") + + ")" + ); + } else - text.AppendLine("target_include_directories(${binding_target} " + (include.system ? "SYSTEM " : string.Empty) - + "PRIVATE " + Literal(directory) + ")"); + { + text.AppendLine( + "target_include_directories(${binding_target} " + (include.system ? "SYSTEM " : string.Empty) + + "PRIVATE " + Literal(directory) + ")" + ); + } } if (compilation.cxxStandard > 0) + { text.AppendLine("target_compile_features(${binding_target} PRIVATE cxx_std_" + compilation.cxxStandard + ")"); + } if (compilation.cStandard > 0) + { text.AppendLine("target_compile_features(${binding_target} PRIVATE c_std_" + compilation.cStandard + ")"); + } text.AppendLine("target_sources(${target} PRIVATE $)"); } text.Append("set_property(TARGET ${target} PROPERTY INNO_REQUIRED_EXPORTS"); foreach (string symbol in compilation.requiredExports.Concat(compilation.staticExportSymbols).Distinct(StringComparer.Ordinal)) + { text.Append(' ').Append(Literal(symbol)); + } text.AppendLine(")\nreturn()\nendif()"); } text.AppendLine("message(FATAL_ERROR \"No selected native binding requirements for ${owner}\")\nendfunction()"); if (target is not null && context.selectedBindings.ContainsKey(owner.nativeProject)) - text.AppendLine("cmake_language(DEFER DIRECTORY \"${CMAKE_SOURCE_DIR}\" CALL inno_apply_binding " - + Literal(target) + " " + Literal(Path.GetFileNameWithoutExtension(owner.nativeProject)) + ")"); + { + text.AppendLine( + "cmake_language(DEFER DIRECTORY \"${CMAKE_SOURCE_DIR}\" CALL inno_apply_binding " + + Literal(target) + " " + Literal(Path.GetFileNameWithoutExtension(owner.nativeProject)) + ")" + ); + } AtomicFile.WriteAllBytes(path, Encoding.UTF8.GetBytes(text.ToString())); } private static string Literal(string value) { if (value.Contains(';') || value.AsSpan().IndexOfAnyInRange('\0', '\x1f') >= 0) + { throw new InvalidDataException("A native CMake requirement cannot contain a list separator or control character."); + } string portable = value.Replace('\\', '/'); string delimiter = "="; while (portable.Contains("]" + delimiter + "]", StringComparison.Ordinal)) + { delimiter += "="; + } return "[" + delimiter + "[" + portable + "]" + delimiter + "]"; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCompilation.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCompilation.cs index ae7c43129..4b0c93cee 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCompilation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCompilation.cs @@ -97,8 +97,10 @@ public sealed class NativeBindingCompilation public static NativeBindingCompilation Load(string nativeDirectory) { NativeBindingCompilation result = JsonSerializer.Deserialize( - File.ReadAllBytes(Path.Combine(nativeDirectory, "compilation.json")), S_OPTIONS) - ?? throw new InvalidDataException("A native compilation description is required."); + File.ReadAllBytes(Path.Combine(nativeDirectory, "compilation.json")), + S_OPTIONS + ) + ?? throw new InvalidDataException("A native compilation description is required."); result.Validate(); return result; } @@ -127,7 +129,7 @@ public string ResolveRoot( string rootId ) { NativeBindingSourceRoot root = roots.SingleOrDefault(root => root.id == rootId) - ?? throw new InvalidDataException("Unknown native compilation root: " + rootId); + ?? throw new InvalidDataException("Unknown native compilation root: " + rootId); return root.generated ? Path.GetFullPath(nativeDirectory) : Path.GetFullPath(root.directory, engineRoot); } @@ -160,7 +162,9 @@ public void VerifyInputs( string path = PathBoundary.Resolve(resolveRoot(input.rootId), input.relativePath); using FileStream stream = File.OpenRead(path); if (stream.Length != input.length || Convert.ToHexStringLower(SHA256.HashData(stream)) != input.sha256) + { throw new InvalidDataException("Native compilation input changed: " + path); + } } } @@ -179,47 +183,70 @@ public void VerifyInputs( public IEnumerable GetInputs( string engineRoot, string nativeDirectory - ) => files.Select(input => NativeBuildInput.FromPath(engineRoot, - PathBoundary.Resolve(ResolveRoot(engineRoot, nativeDirectory, input.rootId), input.relativePath))); + ) => files.Select(input => NativeBuildInput.FromPath( + engineRoot, + PathBoundary.Resolve(ResolveRoot(engineRoot, nativeDirectory, input.rootId), input.relativePath) + )); private void Validate() { - if (roots is null || files is null || includeDirectories is null || defines is null || compilerDefines is null || requiredExports is null - || staticExportSymbols is null || staticExportNames is null || staticExportAbi is null) + if (roots is null + || files is null + || includeDirectories is null + || defines is null + || compilerDefines is null + || requiredExports is null + || staticExportSymbols is null || staticExportNames is null || staticExportAbi is null + ) { throw new InvalidDataException("Native compilation requirements are incomplete."); + } var ids = new HashSet(StringComparer.Ordinal); foreach (NativeBindingSourceRoot root in roots) { if (root is null || string.IsNullOrWhiteSpace(root.id) || !ids.Add(root.id) || root.directory is null || root.generated && (!root.frozen || root.directory.Length != 0) - || !root.generated && string.IsNullOrWhiteSpace(root.directory)) + || !root.generated && string.IsNullOrWhiteSpace(root.directory) + ) { throw new InvalidDataException("Native compilation roots must have unique, complete identities."); + } } if (roots.Count(static root => root.generated) != 1) + { throw new InvalidDataException("A native compilation must identify exactly one generated root."); + } var paths = new HashSet<(string, string)>(); foreach (NativeBindingSourceFile file in files) { if (file is null || !ids.Contains(file.rootId) || !IsRelative(file.relativePath, false) || !paths.Add((file.rootId, file.relativePath)) || file.length < 0 || file.sha256 is null - || file.sha256.Length != 64 || file.sha256.Any(static value => value is not (>= '0' and <= '9' or >= 'a' and <= 'f'))) + || file.sha256.Length != 64 || file.sha256.Any(static value => value is not (>= '0' and <= '9' or >= 'a' and <= 'f')) + ) { throw new InvalidDataException("Native compilation files require unique paths and exact content identities."); + } } - if (includeDirectories.Any(directory => directory is null || !ids.Contains(directory.rootId) - || !IsRelative(directory.relativePath, true)) || defines.Any(string.IsNullOrWhiteSpace) - || compilerDefines.Any(string.IsNullOrWhiteSpace) || requiredExports.Any(string.IsNullOrWhiteSpace) || staticExportSymbols.Any(string.IsNullOrWhiteSpace) + if (includeDirectories.Any(directory => ( + directory is null || !ids.Contains(directory.rootId) + || !IsRelative(directory.relativePath, true) + )) || defines.Any(string.IsNullOrWhiteSpace) + || compilerDefines.Any(string.IsNullOrWhiteSpace) + || requiredExports.Any(string.IsNullOrWhiteSpace) + || staticExportSymbols.Any(string.IsNullOrWhiteSpace) || staticExportNames.Any(string.IsNullOrWhiteSpace) || cxxStandard < 0 || cStandard < 0 || staticExportSymbols.Length == 0 && (staticExportAbi.Length != 0 || staticExportNames.Length != 0) || staticExportSymbols.Length != 0 && (staticExportAbi.Length != 64 || staticExportSymbols.Length != 5 - || staticExportAbi.Any(static value => value is not (>= '0' and <= '9' or >= 'a' and <= 'f')))) + || staticExportAbi.Any(static value => value is not (>= '0' and <= '9' or >= 'a' and <= 'f'))) + ) { throw new InvalidDataException("Native compilation search, language or export requirements are invalid."); + } } private static bool IsRelative( string? value, bool allowEmpty ) => value is not null && (allowEmpty && value.Length == 0 - || value.Length > 0 && !Path.IsPathRooted(value) && !value.Contains('\\') && !value.Contains(':') - && value.Split('/').All(static segment => segment.Length > 0 && segment is not ("." or "..") - && segment.AsSpan().IndexOfAnyInRange('\0', '\x1f') < 0)); + || value.Length > 0 && !Path.IsPathRooted(value) && !value.Contains('\\') && !value.Contains(':') + && value.Split('/').All(static segment => ( + segment.Length > 0 && segment is not ("." or "..") + && segment.AsSpan().IndexOfAnyInRange('\0', '\x1f') < 0 + ))); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs index e3f644d04..43530364e 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs @@ -46,7 +46,9 @@ IReadOnlyDictionary linkage document.Save(buffer); byte[] content = buffer.ToArray(); if (File.Exists(destination) && File.ReadAllBytes(destination).AsSpan().SequenceEqual(content)) + { return; + } Directory.CreateDirectory(Path.GetDirectoryName(destination)!); AtomicFile.WriteAllBytes(destination, content); } @@ -84,7 +86,9 @@ public static void ValidateSelection( IReadOnlyDictionary linkage ) { if (!XNode.DeepEquals(XDocument.Load(path), CreateSelection(generations, linkage))) + { throw new InvalidDataException("Native publication must preserve the exact binding selection used by managed compilation."); + } } /// @@ -140,7 +144,8 @@ IReadOnlyDictionary linkage public static NativeBindingGenerationDescriptor Load(string path) { NativeBindingGenerationDescriptor descriptor = JsonSerializer.Deserialize( - File.ReadAllText(path)) ?? throw new InvalidDataException("The binding generation descriptor is empty."); + File.ReadAllText(path) + ) ?? throw new InvalidDataException("The binding generation descriptor is empty."); descriptor.Validate(); return descriptor; } @@ -164,7 +169,9 @@ public void Write(string path) finally { if (File.Exists(staging)) + { File.Delete(staging); + } } } @@ -178,12 +185,20 @@ internal void Validate() || descriptor.artifactDirectory.Length == 0 && descriptor.artifactOwnerDirectory.Length != 0 || descriptor.artifactDirectory.Length > 0 && !Path.IsPathFullyQualified(descriptor.artifactOwnerDirectory) || descriptor.artifactDirectory.Length > 0 && (!Path.IsPathFullyQualified(descriptor.artifactDirectory) - || Path.GetFullPath(descriptor.bindingsPath) != Path.Combine(Path.GetFullPath(descriptor.artifactDirectory), "Generated", "Bindings.cs")) + || Path.GetFullPath(descriptor.bindingsPath) != Path.Combine( + Path.GetFullPath(descriptor.artifactDirectory), + "Generated", + "Bindings.cs" + )) || descriptor.nativeDirectory.Length > 0 && (!Path.IsPathFullyQualified(descriptor.nativeDirectory) - || !Directory.Exists(descriptor.nativeDirectory))) + || !Directory.Exists(descriptor.nativeDirectory)) + ) { throw new InvalidDataException("The binding generation descriptor does not identify complete outputs."); + } if (descriptor.artifactDirectory.Length > 0) + { BuildCacheCleanupPlan.RequireChild(descriptor.artifactOwnerDirectory, descriptor.artifactDirectory); + } } private static XDocument CreateSelection( @@ -193,25 +208,37 @@ IReadOnlyDictionary linkage ArgumentNullException.ThrowIfNull(generations); ArgumentNullException.ThrowIfNull(linkage); if (generations.Count != linkage.Count || generations.Keys.Any(key => !linkage.ContainsKey(key))) + { throw new ArgumentException("Binding selections require exact component linkage coverage.", nameof(linkage)); + } var names = new HashSet(StringComparer.OrdinalIgnoreCase); var document = new XElement("Project"); foreach (var entry in generations.OrderBy(static entry => entry.Key, StringComparer.Ordinal)) { string name = Path.GetFileNameWithoutExtension(entry.Key); - if (string.IsNullOrWhiteSpace(name) || name.Any(static value => !char.IsAsciiLetterOrDigit(value) - && value is not ('.' or '_' or '-')) || !names.Add(name)) + if (string.IsNullOrWhiteSpace(name) || name.Any(static value => ( + !char.IsAsciiLetterOrDigit(value) + && value is not ('.' or '_' or '-') + )) || !names.Add(name) + ) { throw new ArgumentException("Binding selections require unique portable project names.", nameof(generations)); + } if (!Enum.IsDefined(linkage[entry.Key])) + { throw new ArgumentException("A selected native component requires supported linkage.", nameof(linkage)); - document.Add(new XElement("PropertyGroup", - new XAttribute("Condition", "'$(MSBuildProjectName)' == '" + name + "'"), - new XElement("BindGenExpectedFingerprint", entry.Value.fingerprint), - new XElement("BindGenArtifactDirectory", entry.Value.artifactDirectory), - new XElement("BindGenArtifactOwnerDirectory", entry.Value.artifactOwnerDirectory), - new XElement("InnoNativeLibraryKind", linkage[entry.Key]), - new XElement("InnoNativeRuntimeImports", entry.Value.usesRuntimeImports ? "true" : "false"), - new XElement("BindGenOutputDirectory", Path.GetDirectoryName(entry.Value.bindingsPath)))); + } + document.Add( + new XElement( + "PropertyGroup", + new XAttribute("Condition", "'$(MSBuildProjectName)' == '" + name + "'"), + new XElement("BindGenExpectedFingerprint", entry.Value.fingerprint), + new XElement("BindGenArtifactDirectory", entry.Value.artifactDirectory), + new XElement("BindGenArtifactOwnerDirectory", entry.Value.artifactOwnerDirectory), + new XElement("InnoNativeLibraryKind", linkage[entry.Key]), + new XElement("InnoNativeRuntimeImports", entry.Value.usesRuntimeImports ? "true" : "false"), + new XElement("BindGenOutputDirectory", Path.GetDirectoryName(entry.Value.bindingsPath)) + ) + ); } return new XDocument(document); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs index e3e991a1d..2eff11305 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs @@ -60,42 +60,59 @@ public NativeBindingGenerationRequest( ArgumentNullException.ThrowIfNull(components); ArgumentException.ThrowIfNullOrWhiteSpace(targetId); if (!Enum.IsDefined(outputMode) || targetId is "." or ".." - || targetId.Any(static character => !char.IsAsciiLetterOrDigit(character) - && character is not ('-' or '_' or '.'))) + || targetId.Any(static character => ( + !char.IsAsciiLetterOrDigit(character) + && character is not ('-' or '_' or '.') + )) + ) { throw new ArgumentException("Binding requests require a portable target and a supported output mode."); + } NativeComponentDescriptor[] owners = components.ToArray(); if (owners.Any(static owner => owner is null || owner.bindingDefinition is null) - || owners.Select(static owner => owner.nativeProject).Distinct(StringComparer.Ordinal).Count() != owners.Length) + || owners.Select(static owner => owner.nativeProject).Distinct(StringComparer.Ordinal).Count() != owners.Length + ) { throw new ArgumentException("Binding owners must be distinct and declare their sole definition.", nameof(components)); + } this.components = Array.AsReadOnly(owners); this.targetId = targetId; this.outputMode = outputMode; this.checkOnly = checkOnly; Dictionary expected = new(expectedFingerprints ?? new Dictionary(), StringComparer.Ordinal); - if (expected.Any(pair => !owners.Any(owner => owner.nativeProject == pair.Key) - || string.IsNullOrWhiteSpace(pair.Value))) + if (expected.Any(pair => ( + !owners.Any(owner => owner.nativeProject == pair.Key) + || string.IsNullOrWhiteSpace(pair.Value) + ))) { throw new ArgumentException("An expected identity must belong to the requested binding closure.", nameof(expectedFingerprints)); + } this.expectedFingerprints = new ReadOnlyDictionary(expected); this.componentOptions = new ReadOnlyDictionary( - new Dictionary(componentOptions ?? new Dictionary(), StringComparer.Ordinal)); + new Dictionary( + componentOptions ?? new Dictionary(), + StringComparer.Ordinal + ) + ); } /// /// Gets the immutable component closure owned by this request. /// public IReadOnlyList components { get; } + /// /// Gets the explicit configuration target, independent of the build execution host. /// public string targetId { get; } + /// /// Gets the selected output ownership policy. /// public NativeBindingOutputMode outputMode { get; } + /// /// Gets whether publication is forbidden and current output must match fresh generation. /// public bool checkOnly { get; } + /// /// Gets the expected identities which must match before any candidate is generated. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs index b9f9b0f4d..cf8848360 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs @@ -40,7 +40,9 @@ IEnumerable ownership var copy = new Dictionary(generations, StringComparer.Ordinal); IDisposable[] owners = ownership.ToArray(); if (copy.Values.Any(static value => value is null) || owners.Any(static value => value is null)) + { throw new ArgumentException("Generation and ownership entries must be non-null."); + } m_generations = new ReadOnlyDictionary(copy); m_ownership = owners; } @@ -123,7 +125,9 @@ public void Dispose() { IDisposable[]? owners = Interlocked.Exchange(ref m_ownership, null); if (owners is null) + { return; + } List failures = []; for (int index = owners.Length - 1; index >= 0; index--) { @@ -137,7 +141,9 @@ public void Dispose() } } if (failures.Count != 0) + { throw new AggregateException("Binding reading ownership could not be completely released.", failures); + } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs index 54f2e895b..a56bc89a3 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs @@ -18,8 +18,10 @@ internal sealed class NativeBindingInputPaths private readonly HashSet m_generationDeclarations = new(StringComparer.Ordinal); private readonly List m_sourceRoots = []; private readonly string m_engineRoot; + private readonly StringComparison m_comparison = OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; internal NativeBindingInputPaths(NativeBuildContext context) { @@ -30,18 +32,24 @@ internal NativeBindingInputPaths(NativeBuildContext context) string root = ".inno-bindings/" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(entry.Key))); m_generationDeclarations.Add(entry.Key + "=" + generation.fingerprint); if (generation.artifactDirectory.Length > 0) + { Add(generation.artifactDirectory, root, false); + } else { Add(generation.bindingsPath, root + "/Generated/Bindings.cs", true); if (generation.nativeDirectory.Length > 0) + { Add(generation.nativeDirectory, root + "/Native", false); + } } if (generation.nativeDirectory.Length > 0) { NativeBindingCompilation compilation = NativeBindingCompilation.Load(generation.nativeDirectory); foreach (NativeBindingSourceRoot source in compilation.roots.Where(static source => source.frozen && !source.generated)) + { m_sourceRoots.Add(compilation.ResolveRoot(context.engineRoot, generation.nativeDirectory, source.id)); + } } } } @@ -52,18 +60,24 @@ internal NativeBindingInputPaths(NativeBuildContext context) foreach (var entry in m_roots) { if (string.Equals(absolute, entry.physical, m_comparison)) + { return entry.relative; + } if (!entry.file && absolute.StartsWith(entry.physical + Path.DirectorySeparatorChar, m_comparison)) + { return entry.relative + "/" + Path.GetRelativePath(entry.physical, absolute).Replace('\\', '/'); + } } string checkoutRelative = Path.GetRelativePath(m_engineRoot, absolute); if ((checkoutRelative == ".." || checkoutRelative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) - || Path.IsPathRooted(checkoutRelative)) && m_sourceRoots.Any(root => string.Equals(root, absolute, m_comparison) - || absolute.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, m_comparison))) - { + || Path.IsPathRooted(checkoutRelative)) && m_sourceRoots.Any(root => ( + string.Equals(root, absolute, m_comparison) + || absolute.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, m_comparison) + )) + ) { string volume = Path.GetPathRoot(absolute)!; return ".inno-source-roots/" + Base64Url.EncodeToString(SHA256.HashData(Encoding.UTF8.GetBytes(volume))) - + "/" + Path.GetRelativePath(volume, absolute).Replace('\\', '/'); + + "/" + Path.GetRelativePath(volume, absolute).Replace('\\', '/'); } return null; } @@ -71,25 +85,34 @@ internal NativeBindingInputPaths(NativeBuildContext context) internal string NormalizeDeclaration(string declaration) { if (m_generationDeclarations.Contains(declaration)) + { return declaration[..(declaration.IndexOf('=') + 1)] + "selected-generation"; + } const string nativePrefix = "bindingNativeRoot="; if (declaration.StartsWith(nativePrefix, StringComparison.Ordinal)) { string path = declaration[nativePrefix.Length..]; return path.Length > 0 && ResolveRelative(path) is { } native - ? nativePrefix + "workspace-input:" + native : declaration; + ? nativePrefix + "workspace-input:" + native + : declaration; } int start = declaration.IndexOf("-D", StringComparison.Ordinal); if (start < 0 || start > 0 && declaration[start - 1] != '=') + { return declaration; + } int separator = declaration.IndexOf('=', start); if (separator < 0) + { return declaration; + } string[] values = declaration[(separator + 1)..].Split(';'); for (int index = 0; index < values.Length; index++) { if (Path.IsPathFullyQualified(values[index]) && ResolveRelative(values[index]) is { } relative) + { values[index] = "workspace-input:" + relative; + } } return declaration[..(separator + 1)] + string.Join(';', values); } @@ -100,10 +123,13 @@ private void Add( bool file ) { string absolute = Path.TrimEndingDirectorySeparator(Path.GetFullPath(physical)); - if (m_roots.Any(entry => string.Equals(entry.physical, absolute, m_comparison) + if (m_roots.Any(entry => ( + string.Equals(entry.physical, absolute, m_comparison) || !entry.file && absolute.StartsWith(entry.physical + Path.DirectorySeparatorChar, m_comparison) - || !file && entry.physical.StartsWith(absolute + Path.DirectorySeparatorChar, m_comparison))) + || !file && entry.physical.StartsWith(absolute + Path.DirectorySeparatorChar, m_comparison) + ))) { throw new InvalidOperationException("Selected binding owners cannot share or contain each other's output roots."); + } m_roots.Add((absolute, relative, file)); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingPreparation.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingPreparation.cs index 6de72e4e4..ea5c8340a 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingPreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingPreparation.cs @@ -42,11 +42,18 @@ public static async Task PrepareAsync( ArgumentNullException.ThrowIfNull(components); cancellationToken.ThrowIfCancellationRequested(); NativeComponentDescriptor[] owners = components.Where(static owner => owner.bindingDefinition is not null) - .DistinctBy(static owner => owner.nativeProject).ToArray(); + .DistinctBy(static owner => owner.nativeProject) + .ToArray(); if (owners.Length == 0) + { return new(new Dictionary(), []); - var request = new NativeBindingGenerationRequest(owners, context.RequireToolchain().targetId, - NativeBindingOutputMode.TargetArtifacts, componentOptions: componentOptions); + } + var request = new NativeBindingGenerationRequest( + owners, + context.RequireToolchain().targetId, + NativeBindingOutputMode.TargetArtifacts, + componentOptions: componentOptions + ); return await context.RequireBindingGenerator().GenerateAsync(context, request, cancellationToken).ConfigureAwait(false); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs index 439588935..c45e26beb 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs @@ -83,7 +83,9 @@ NativeInputSnapshot snapshot ) { using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (string declaration in declarations) + { Append(hash, declaration); + } foreach (NativeInputSnapshot.Entry entry in snapshot.entries) { Append(hash, entry.logicalPath); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInput.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInput.cs index 284cefa22..f534778b3 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInput.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInput.cs @@ -27,12 +27,18 @@ string physicalPath ArgumentException.ThrowIfNullOrWhiteSpace(logicalPath); ArgumentException.ThrowIfNullOrWhiteSpace(physicalPath); if (logicalPath.Contains('\\') || logicalPath.AsSpan().IndexOfAnyInRange('\0', '\x1f') >= 0) + { throw new ArgumentException("A native input identity must use portable, printable path segments.", nameof(logicalPath)); + } if (!Path.IsPathFullyQualified(physicalPath)) + { throw new ArgumentException("A native input reading location must be absolute.", nameof(physicalPath)); + } this.logicalPath = logicalPath.TrimEnd('/'); if (this.logicalPath.Length == 0) + { throw new ArgumentException("A native input identity requires a logical root.", nameof(logicalPath)); + } this.physicalPath = Path.GetFullPath(physicalPath); } @@ -67,9 +73,9 @@ string path string physical = Path.GetFullPath(path, engineRoot); string relative = Path.GetRelativePath(engineRoot, physical).Replace('\\', '/'); string logical = relative != ".." && !relative.StartsWith("../", StringComparison.Ordinal) - && !Path.IsPathRooted(relative) - ? "engine/" + relative - : "external/" + physical.Replace('\\', '/').TrimStart('/'); + && !Path.IsPathRooted(relative) + ? "engine/" + relative + : "external/" + physical.Replace('\\', '/').TrimStart('/'); return new NativeBuildInput(logical, physical); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs index b1b4cb255..9c2a07e83 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs @@ -1,6 +1,6 @@ using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using System.Threading; namespace Inno.Build.Toolchains; @@ -22,7 +22,8 @@ internal sealed class NativeBuildInputState internal NativeBuildInputState() => m_initialInputs = new(this); - internal NativeBuildStatistics statistics => new() + internal NativeBuildStatistics statistics + => new() { hashedFiles = Interlocked.Read(ref m_hashedFiles), hashedBytes = Interlocked.Read(ref m_hashedBytes), @@ -41,7 +42,9 @@ internal NativeInputSnapshot CaptureInitial( CancellationToken cancellationToken ) { lock (m_gate) + { return NativeInputSnapshot.Capture(inputs, m_initialInputs, cancellationToken); + } } internal NativeInputSnapshot CaptureVerification( @@ -65,19 +68,25 @@ string phase internal byte[] GetFrozenHash(string path) { lock (m_gate) + { return m_initialInputs.GetFrozenHash(path); + } } internal NativeInputSnapshot CaptureRecordedInputs(string engineRoot) { lock (m_gate) + { return m_initialInputs.CaptureRecordedInputs(engineRoot); + } } internal string[][] CaptureRootMembership() { lock (m_gate) + { return m_initialInputs.CaptureRootMembership(); + } } internal void RecordReuse(string phase) @@ -90,7 +99,9 @@ internal void RecordReuse(string phase) } internal void RecordBindingBatch() => Interlocked.Increment(ref m_bindingBatches); + internal void RecordBindingGeneration() => Interlocked.Increment(ref m_bindingGenerations); + internal void RecordMaterialization(long bytes) => Interlocked.Add(ref m_materializedBytes, bytes); internal void RecordOutput(long bytes) @@ -104,11 +115,19 @@ internal void RecordOutput(long bytes) private IReadOnlyList CapturePhases() { lock (m_gate) - return Array.AsReadOnly(m_phases.OrderBy(static pair => pair.Key, StringComparer.Ordinal) - .Select(static pair => new NativeBuildPhaseStatistics - { - phase = pair.Key, files = pair.Value.files, bytes = pair.Value.bytes, reusedReads = pair.Value.reused - }).ToArray()); + { + return Array.AsReadOnly( + m_phases.OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => new NativeBuildPhaseStatistics + { + phase = pair.Key, + files = pair.Value.files, + bytes = pair.Value.bytes, + reusedReads = pair.Value.reused + }) + .ToArray() + ); + } } internal void RecordProcess() => Interlocked.Increment(ref m_nativeProcesses); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildPhaseStatistics.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildPhaseStatistics.cs index 505117559..f43d9fbe9 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildPhaseStatistics.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildPhaseStatistics.cs @@ -9,14 +9,17 @@ public sealed record NativeBuildPhaseStatistics /// Gets the named operation phase which owns these read results. /// public required string phase { get; init; } + /// /// Gets the number of complete physical file reads. /// public long files { get; init; } + /// /// Gets the number of bytes actually read for hashing. /// public long bytes { get; init; } + /// /// Gets repeated physical hash requests satisfied from this phase's cache. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs index 280b19bb5..87fc889d7 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs @@ -11,6 +11,7 @@ namespace Inno.Build.Toolchains; public sealed class NativeBuildRecipe { internal NativeToolchainSelection? toolchain { get; private init; } + /// /// Creates a complete recipe without inferring implementation identity from an assembly MVID. /// @@ -50,8 +51,10 @@ IEnumerable declarations NativeBuildInput[] frozenInputs = inputs.ToArray(); string[] frozenDeclarations = declarations.ToArray(); if (frozenInputs.Any(static input => input is null) - || frozenDeclarations.Any(static declaration => declaration is null)) + || frozenDeclarations.Any(static declaration => declaration is null) + ) { throw new ArgumentException("A recipe cannot contain null inputs or declarations."); + } this.owner = owner; this.component = component; this.targetId = targetId; @@ -135,24 +138,74 @@ IEnumerable implementationPaths context.toolchain?.linkPlan.GetFileExtension(options.libraryKind); string projectFile = Path.GetFullPath(owner.toolchainProject, context.engineRoot); if (!File.Exists(projectFile)) + { throw new FileNotFoundException("A native recipe owner project is unavailable.", projectFile); - List paths = [..inputPaths, ..options.inputPaths.Select(path => Path.GetFullPath(path, context.engineRoot)), ..(context.toolchain?.inputPaths ?? []), projectFile]; + } + List paths = + [ + ..inputPaths, + ..options.inputPaths.Select(path => Path.GetFullPath(path, context.engineRoot)), + ..(context.toolchain?.inputPaths ?? []), + projectFile + ]; paths.AddRange(implementationPaths); string commonRoot = Path.Combine(context.engineRoot, "build", "toolchains", "Inno.Build.Toolchains"); - paths.AddRange(new[] { "NativeBuildContext.cs", "ToolchainEnvironment.cs", "ToolchainLayout.cs", "BuildArtifactManifest.cs", "ToolchainWorkingDirectory.cs" } - .Select(file => Path.Combine(commonRoot, file))); - paths.AddRange(new[] - { - "NativeArtifactPublisher.cs", "ProductNativeCacheLookup.cs", "NativeBuildFingerprint.cs", "NativeBuildInput.cs", "NativeWorkspaceIdentity.cs", "NativeBindingInputPaths.cs", - "NativeBuildInputState.cs", "NativeInputSnapshot.cs", "NativeInputReadCache.cs", "NativeInputVerificationScope.cs", "NativeBuildPhaseStatistics.cs", "NativeBuildProduct.cs", - "NativeBuildStatistics.cs", "NativeToolchainSelection.cs", "NativeBuildRecipe.cs", "ProductNativeBuildResult.cs", "NativeArtifact.cs", "NativeCompilerInputs.cs", "NativeLinkPlan.cs", - "NativeCMakeExecutor.cs", "NativeCMakeSource.cs", "NativeComponentBuildOptions.cs", "ProductNativeBuildStep.cs", "ProductNativeBuildPlan.cs", "NativeInputMaterializer.cs", "NativeBindingGenerationDescriptor.cs", - "NativeBindingGenerationResult.cs", "NativeBindingPreparation.cs", "NativeComponentDescriptor.cs", "NativeStaticBuildDefinition.cs", - "NativeToolchainPreparation.cs", "BuildHostDescriptor.cs", - "NativeBindingCompilation.cs", "NativeBindingSourceRoot.cs", "NativeBindingSourceFile.cs", "NativeBindingIncludeDirectory.cs", "NativeBindingCMake.cs" - }.Select(file => Path.Combine(commonRoot, "Native", file))); - paths.AddRange(new[] { "BuildHostServices.cs", "IToolchainWorkspaceProvider.cs", "PhysicalToolchainWorkspaceProvider.cs" } - .Select(file => Path.Combine(commonRoot, "Host", file))); + paths.AddRange( + new[] { + "NativeBuildContext.cs", + "ToolchainEnvironment.cs", + "ToolchainLayout.cs", + "BuildArtifactManifest.cs", + "ToolchainWorkingDirectory.cs" + } + .Select(file => Path.Combine(commonRoot, file)) + ); + paths.AddRange( + new[] + { + "NativeArtifactPublisher.cs", + "ProductNativeCacheLookup.cs", + "NativeBuildFingerprint.cs", + "NativeBuildInput.cs", + "NativeWorkspaceIdentity.cs", + "NativeBindingInputPaths.cs", + "NativeBuildInputState.cs", + "NativeInputSnapshot.cs", + "NativeInputReadCache.cs", + "NativeInputVerificationScope.cs", + "NativeBuildPhaseStatistics.cs", + "NativeBuildProduct.cs", + "NativeBuildStatistics.cs", + "NativeToolchainSelection.cs", + "NativeBuildRecipe.cs", + "ProductNativeBuildResult.cs", + "NativeArtifact.cs", + "NativeCompilerInputs.cs", + "NativeLinkPlan.cs", + "NativeCMakeExecutor.cs", + "NativeCMakeSource.cs", + "NativeComponentBuildOptions.cs", + "ProductNativeBuildStep.cs", + "ProductNativeBuildPlan.cs", + "NativeInputMaterializer.cs", + "NativeBindingGenerationDescriptor.cs", + "NativeBindingGenerationResult.cs", + "NativeBindingPreparation.cs", + "NativeComponentDescriptor.cs", + "NativeStaticBuildDefinition.cs", + "NativeToolchainPreparation.cs", + "BuildHostDescriptor.cs", + "NativeBindingCompilation.cs", + "NativeBindingSourceRoot.cs", + "NativeBindingSourceFile.cs", + "NativeBindingIncludeDirectory.cs", + "NativeBindingCMake.cs" + }.Select(file => Path.Combine(commonRoot, "Native", file)) + ); + paths.AddRange( + new[] { "BuildHostServices.cs", "IToolchainWorkspaceProvider.cs", "PhysicalToolchainWorkspaceProvider.cs" } + .Select(file => Path.Combine(commonRoot, "Host", file)) + ); paths.AddRange((context.toolchain?.host.services.inputPaths ?? []).Select(path => Path.GetFullPath(path, context.engineRoot))); paths.Add(Path.Combine(commonRoot, "Managed", "DotNetSdkEnvironment.cs")); paths.Add(Path.Combine(commonRoot, "Cache", "BuildArtifactReadLease.cs")); @@ -160,13 +213,32 @@ IEnumerable implementationPaths paths.Add(Path.Combine(commonRoot, "Cache", "BuildCachePublisher.cs")); paths.Add(Path.Combine(commonRoot, "Cache", "BuildCacheFileInventory.cs")); string ioRoot = Path.Combine(context.engineRoot, "src", "foundation", "core", "Inno.Core.IO"); - paths.AddRange(new[] { "AtomicDirectory.cs", "AtomicFile.cs", "DirectoryCleanupException.cs", "FileSystemRename.cs", "FileLease.cs", "PathBoundary.cs", - "ProcessOwnerStamp.cs", "ProcessOwnerState.cs", "ProcessOwnedDirectory.cs", "ProcessOwnedDirectoryDescriptor.cs", "CoordinatedFileLease.cs" } - .Select(file => Path.Combine(ioRoot, file))); - return new NativeBuildRecipe(owner, component, targetId, + paths.AddRange( + new[] + { + "AtomicDirectory.cs", + "AtomicFile.cs", + "DirectoryCleanupException.cs", + "FileSystemRename.cs", + "FileLease.cs", + "PathBoundary.cs", + "ProcessOwnerStamp.cs", + "ProcessOwnerState.cs", + "ProcessOwnedDirectory.cs", + "ProcessOwnedDirectoryDescriptor.cs", + "CoordinatedFileLease.cs" + } + .Select(file => Path.Combine(ioRoot, file)) + ); + return new NativeBuildRecipe( + owner, + component, + targetId, paths.Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), new[] { component, targetId, context.configuration, "executionRoot=" + context.engineRoot }.Concat(declarations) - .Concat(options.declarations).Concat(context.toolchain?.declarations ?? [])) { toolchain = context.toolchain }; + .Concat(options.declarations) + .Concat(context.toolchain?.declarations ?? []) + ) { toolchain = context.toolchain }; } /// @@ -193,7 +265,13 @@ string fingerprint ) { ArgumentNullException.ThrowIfNull(input); ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint); - return new(owner, component, targetId, inputs.Append(input), declarations.Append("dependency=" + fingerprint)) { toolchain = this.toolchain }; + return new( + owner, + component, + targetId, + inputs.Append(input), + declarations.Append("dependency=" + fingerprint) + ) { toolchain = this.toolchain }; } /// @@ -205,18 +283,28 @@ NativeBindingGenerationDescriptor generation ) { IEnumerable generated = [NativeBuildInput.FromPath(engineRoot, generation.bindingsPath)]; if (generation.nativeDirectory.Length > 0) + { generated = generated.Append(NativeBuildInput.FromPath(engineRoot, generation.nativeDirectory)) .Concat(NativeBindingCompilation.Load(generation.nativeDirectory).GetInputs(engineRoot, generation.nativeDirectory)); - return new NativeBuildRecipe(owner, component, targetId, inputs.Concat(generated), + } + return new NativeBuildRecipe( + owner, + component, + targetId, + inputs.Concat(generated), declarations.Append("bindings=" + generation.fingerprint) - .Append("bindingNativeRoot=" + generation.nativeDirectory)) { toolchain = this.toolchain }; + .Append("bindingNativeRoot=" + generation.nativeDirectory) + ) { toolchain = this.toolchain }; } private static void ValidateSegment(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); - if (value is "." or ".." || value.Any(static character => !char.IsAsciiLetterOrDigit(character) - && character is not ('-' or '_' or '.'))) + if (value is "." or ".." || value.Any(static character => ( + !char.IsAsciiLetterOrDigit(character) + && character is not ('-' or '_' or '.') + ))) { throw new ArgumentException("Native component and target identities must be single path segments.", nameof(value)); + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildStatistics.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildStatistics.cs index c014c93ee..2fc257b89 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildStatistics.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildStatistics.cs @@ -57,5 +57,4 @@ public sealed record NativeBuildStatistics /// Gets managed SDK processes started for generator extension preparation and managed input evaluation. /// public long managedProcesses { get; init; } - } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs index e715633f2..b02ecbc42 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs @@ -96,19 +96,28 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(componentArguments); ArgumentException.ThrowIfNullOrWhiteSpace(sourceDirectory); if (target is not null) + { ArgumentException.ThrowIfNullOrWhiteSpace(target); + } NativeToolchainSelection selection = context.RequireToolchain(); NativeComponentBuildOptions options = context.RequireComponentOptions(component); var reserved = new HashSet(StringComparer.Ordinal); foreach (string argument in componentArguments) { if (argument.StartsWith("-D", StringComparison.Ordinal) && argument.Contains('=')) + { reserved.Add(argument[2..argument.IndexOf('=')].Split(':')[0]); + } } foreach (string argument in options.cmakeArguments) { if (reserved.Contains(argument[2..argument.IndexOf('=')].Split(':')[0])) - throw new ArgumentException("Product configuration cannot override a recipe-owned component definition.", nameof(componentArguments)); + { + throw new ArgumentException( + "Product configuration cannot override a recipe-owned component definition.", + nameof(componentArguments) + ); + } } string buildType = context.configuration == "debug" ? "Debug" : "Release"; string buildDirectory = Path.Combine(context.GetNativeBuildRoot(component), "CMake"); @@ -119,7 +128,9 @@ CancellationToken cancellationToken configure.Add("-DINNO_ROOT=" + sources.root); configure.Add("-DINNO_NATIVE_TARGET=" + selection.targetId); if (!selection.multiConfiguration) + { configure.Add("-DCMAKE_BUILD_TYPE=" + buildType); + } configure.Add("-DINNO_LIBRARY_KIND=" + options.libraryKind.ToString().ToUpperInvariant()); configure.AddRange(componentArguments.Select(sources.ResolveDefinition)); configure.AddRange(options.cmakeArguments.Select(sources.ResolveDefinition)); @@ -140,13 +151,27 @@ CancellationToken cancellationToken // A different SDK source identity selects another workspace and cannot reuse stale bytecode. environment["PYTHONPYCACHEPREFIX"] = Path.Combine(buildDirectory, "PythonCache"); } - await ToolchainEnvironment.RunAsync(context, selection.ResolveExecutable("cmake"), configure, - sources.root, cancellationToken, environment).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + context, + selection.ResolveExecutable("cmake"), + configure, + sources.root, + cancellationToken, + environment + ).ConfigureAwait(false); List build = ["--build", buildDirectory, "--config", buildType]; if (target is not null) + { build.AddRange(["--target", target]); - await ToolchainEnvironment.RunAsync(context, selection.ResolveExecutable("cmake"), build, - sources.root, cancellationToken, environment).ConfigureAwait(false); + } + await ToolchainEnvironment.RunAsync( + context, + selection.ResolveExecutable("cmake"), + build, + sources.root, + cancellationToken, + environment + ).ConfigureAwait(false); return buildDirectory; } @@ -177,10 +202,13 @@ string filePattern string buildType = context.configuration == "debug" ? "Debug" : "Release"; string[] candidates = Directory.EnumerateFiles(buildDirectory, filePattern, SearchOption.AllDirectories) .Where(path => !Path.GetRelativePath(buildDirectory, path).Split(Path.DirectorySeparatorChar).Contains("CMakeFiles")) - .Where(path => !selection.multiConfiguration - || Path.GetRelativePath(buildDirectory, path).Split(Path.DirectorySeparatorChar).Contains(buildType)) + .Where(path => ( + !selection.multiConfiguration + || Path.GetRelativePath(buildDirectory, path).Split(Path.DirectorySeparatorChar).Contains(buildType) + )) .ToArray(); - return candidates.Length == 1 ? candidates[0] - : throw new FileNotFoundException($"Expected one native output '{filePattern}' but found {candidates.Length}."); + return candidates.Length == 1 + ? candidates[0] + : throw new FileNotFoundException($"Expected one native output '{filePattern}' but found {candidates.Length}."); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs index ed48135c2..b15fbad0f 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs @@ -33,13 +33,17 @@ PhysicalPathResolver resolver { string path = Path.GetFullPath(entry.physicalPath); while (GetSourceRelative(m_engineRoot, bindings, resolver, path) is string relative - && m_paths.TryAdd(path, relative)) - { + && m_paths.TryAdd(path, relative) + ) { // Keep the source spelling for verification and also accept its declared physical counterpart. if (!IsCheckoutPath(m_engineRoot, path) && bindings.ResolveRelative(path) is null) + { m_paths.TryAdd(resolver.Resolve(path), relative); + } if (relative == ".") + { break; + } path = Path.GetDirectoryName(path)!; } } @@ -70,12 +74,18 @@ public string ResolvePath(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); if (!Path.IsPathFullyQualified(path)) + { throw new ArgumentException("A CMake input path must be absolute.", nameof(path)); + } string absolute = Path.GetFullPath(path); if (m_paths.TryGetValue(absolute, out string? relative)) + { return PathBoundary.Resolve(root, relative); + } if (!IsCheckoutPath(m_engineRoot, absolute) && m_bindings.ResolveRelative(absolute) is null) + { return absolute; + } throw new InvalidOperationException("A CMake source was not declared by the native recipe: " + absolute); } @@ -96,13 +106,17 @@ public string ResolveDefinition(string argument) ArgumentNullException.ThrowIfNull(argument); int separator = argument.IndexOf('='); if (!argument.StartsWith("-D", StringComparison.Ordinal) || separator < 0) + { return argument; + } string[] values = argument[(separator + 1)..].Split(';'); for (int index = 0; index < values.Length; index++) { string value = values[index]; if (Path.IsPathFullyQualified(value) && m_paths.ContainsKey(Path.GetFullPath(value))) + { values[index] = ResolvePath(value); + } } return argument[..(separator + 1)] + string.Join(';', values); } @@ -121,21 +135,30 @@ CancellationToken cancellationToken .GroupBy(static entry => entry.physicalPath, comparer) .Select(group => new NativeInputSnapshot.Entry( "engine/" + GetSourceRelative(context.engineRoot, bindings, resolver, group.Key)!.Replace('\\', '/'), - group.Key, group.First().hash)) - .OrderBy(static entry => entry.logicalPath, StringComparer.Ordinal).ToArray(); + group.Key, + group.First().hash + )) + .OrderBy(static entry => entry.logicalPath, StringComparer.Ordinal) + .ToArray(); NativeInputSnapshot.Entry[] entries = declared.GroupBy(static entry => entry.logicalPath, comparer).Select(group => { NativeInputSnapshot.Entry first = group.First(); string physical = resolver.Resolve(first.physicalPath); if (group.Any(entry => resolver.Resolve(entry.physicalPath) != physical || !entry.hash.AsSpan().SequenceEqual(first.hash))) + { throw new InvalidOperationException("Native source aliases disagree about one copied workspace location."); + } return first; }).ToArray(); if (entries.Length == 0) + { throw new InvalidOperationException("The native recipe declares no checkout or selected binding inputs."); + } string root = Path.Combine(context.GetNativeBuildRoot(component), "Sources"); if (Directory.Exists(root) && IsComplete(context, root, entries, cancellationToken)) + { return new(context.engineRoot, root, declared, bindings, resolver); + } Directory.CreateDirectory(root); var expected = new HashSet(entries.Select(static entry => entry.logicalPath["engine/".Length..]), comparer); foreach (string file in PathBoundary.EnumerateFiles(root)) @@ -143,7 +166,9 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(root, file).Replace('\\', '/'); if (!expected.Contains(relative)) + { File.Delete(file); + } } foreach (NativeInputSnapshot.Entry entry in entries) { @@ -163,12 +188,16 @@ string path ) { string? binding = bindings.ResolveRelative(path); if (binding is not null) + { return binding; + } if (IsCheckoutPath(engineRoot, path)) + { return Path.GetRelativePath(engineRoot, path); + } string physical = resolver.Resolve(path); return bindings.ResolveRelative(physical) - ?? (IsCheckoutPath(engineRoot, physical) ? Path.GetRelativePath(engineRoot, physical) : null); + ?? (IsCheckoutPath(engineRoot, physical) ? Path.GetRelativePath(engineRoot, physical) : null); } private static bool IsCheckoutPath( @@ -177,7 +206,7 @@ string path ) { string relative = Path.GetRelativePath(engineRoot, path); return relative != ".." && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) - && !Path.IsPathRooted(relative); + && !Path.IsPathRooted(relative); } private static bool IsComplete( @@ -188,17 +217,25 @@ CancellationToken cancellationToken ) { string[] files = PathBoundary.EnumerateFiles(root).ToArray(); if (files.Length != expected.Count) + { return false; - NativeInputSnapshot actual = context.inputState.CaptureVerification(files.Select(path => - new NativeBuildInput("engine/" + Path.GetRelativePath(root, path).Replace('\\', '/'), path)), cancellationToken); + } + NativeInputSnapshot actual = context.inputState.CaptureVerification( + files.Select(path => + new NativeBuildInput("engine/" + Path.GetRelativePath(root, path).Replace('\\', '/'), path)), + cancellationToken + ); for (int index = 0; index < expected.Count; index++) { if (actual.entries[index].logicalPath != expected[index].logicalPath - || !actual.entries[index].hash.AsSpan().SequenceEqual(expected[index].hash)) + || !actual.entries[index].hash.AsSpan().SequenceEqual(expected[index].hash) + ) { return false; + } } return true; } + internal sealed class Preparation { private readonly object m_gate = new(); @@ -213,7 +250,9 @@ internal Task GetAsync( CancellationToken cancellationToken ) { lock (m_gate) + { return m_task ??= CreateAsync(context, component, m_inputs, cancellationToken); + } } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeCompilerInputs.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeCompilerInputs.cs index 4c9da217f..7432b0f3f 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeCompilerInputs.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeCompilerInputs.cs @@ -59,41 +59,50 @@ public NativeCompilerInputs( /// Gets the explicit C compiler, or null when unavailable. /// public string? cCompiler { get; } + /// /// Gets the explicit C++ compiler, or null when unavailable. /// public string? cppCompiler { get; } + /// /// Gets the target SDK root, or null when unnecessary. /// public string? sysRoot { get; } + /// /// Gets ordered SDK header directories. /// public IReadOnlyList systemIncludeDirectories { get; } + /// /// Gets ordered C++ standard library directories. /// public IReadOnlyList cppSystemIncludeDirectories { get; } + /// /// Gets ordered target definitions. /// public IReadOnlyList defines { get; } + /// /// Gets ordered target parser arguments. /// public IReadOnlyList arguments { get; } - internal IEnumerable declarations => new[] { "cCompiler=" + cCompiler, "cppCompiler=" + cppCompiler, "sysRoot=" + sysRoot } - .Concat(systemIncludeDirectories.Select(static path => "systemInclude=" + path)) - .Concat(cppSystemIncludeDirectories.Select(static path => "cppSystemInclude=" + path)) - .Concat(defines.Select(static value => "compilerDefine=" + value)) - .Concat(arguments.Select(static value => "compilerArgument=" + value)); + internal IEnumerable declarations + => new[] { "cCompiler=" + cCompiler, "cppCompiler=" + cppCompiler, "sysRoot=" + sysRoot } + .Concat(systemIncludeDirectories.Select(static path => "systemInclude=" + path)) + .Concat(cppSystemIncludeDirectories.Select(static path => "cppSystemInclude=" + path)) + .Concat(defines.Select(static value => "compilerDefine=" + value)) + .Concat(arguments.Select(static value => "compilerArgument=" + value)); private static string? Validate(string? path) { if (path is not null && (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path))) + { throw new ArgumentException("Native compiler inputs require explicit absolute paths.", nameof(path)); + } return path; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs index 7df645a16..40ec0e992 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs @@ -14,7 +14,6 @@ public enum NativeLibraryKind /// Produces archives for the selected final linker. /// Static, - /// /// Produces libraries loaded by the deployed product. /// @@ -26,7 +25,10 @@ public enum NativeLibraryKind /// public sealed class NativeComponentBuildOptions { - private static readonly Regex S_DEFINITION = new("^-D[A-Za-z_][A-Za-z0-9_]*(?::(?:BOOL|STRING|PATH|FILEPATH|INTERNAL))?=", RegexOptions.CultureInvariant); + private static readonly Regex S_DEFINITION = new( + "^-D[A-Za-z_][A-Za-z0-9_]*(?::(?:BOOL|STRING|PATH|FILEPATH|INTERNAL))?=", + RegexOptions.CultureInvariant + ); /// /// Captures component configuration without selecting an SDK or starting a build. @@ -61,25 +63,37 @@ public NativeComponentBuildOptions( NativeLinkPlan? linkPlan = null ) { if (!Enum.IsDefined(libraryKind)) + { throw new ArgumentException("A supported native library kind is required.", nameof(libraryKind)); + } string[] arguments = (cmakeArguments ?? []).ToArray(); var names = new HashSet(StringComparer.Ordinal); foreach (string argument in arguments) { if (argument is null || !S_DEFINITION.IsMatch(argument) || argument.Contains('\0')) + { throw new ArgumentException("Component arguments must be explicit CMake definitions.", nameof(cmakeArguments)); + } string name = argument[2..argument.IndexOf('=')].Split(':')[0]; if (name.StartsWith("CMAKE_", StringComparison.Ordinal) || name is "INNO_ROOT" or "INNO_NATIVE_TARGET" or "INNO_LIBRARY_KIND" || name.StartsWith("INNO_COMPONENT_", StringComparison.Ordinal) - || !names.Add(name)) - throw new ArgumentException("Component definitions must be unique and cannot override SDK or linkage selection.", nameof(cmakeArguments)); + || !names.Add(name) + ) { + throw new ArgumentException( + "Component definitions must be unique and cannot override SDK or linkage selection.", + nameof(cmakeArguments) + ); + } } string[] inputs = (inputPaths ?? []).Select(ValidatePath).Distinct(StringComparer.Ordinal).ToArray(); this.libraryKind = libraryKind; this.cmakeArguments = Array.AsReadOnly(arguments); this.inputPaths = Array.AsReadOnly(inputs); - if (bindingLibraryName is not null && (string.IsNullOrWhiteSpace(bindingLibraryName) || bindingLibraryName.IndexOfAny(['/', '\\', ':']) >= 0)) + if (bindingLibraryName is not null + && (string.IsNullOrWhiteSpace(bindingLibraryName) || bindingLibraryName.IndexOfAny(['/', '\\', ':']) >= 0) + ) { throw new ArgumentException("A binding import identity must be a library name.", nameof(bindingLibraryName)); + } this.bindingLibraryName = bindingLibraryName; this.linkPlan = linkPlan; this.bindingIncludeDirectories = Array.AsReadOnly((bindingIncludeDirectories ?? []).Select(ValidatePath).ToArray()); @@ -115,18 +129,21 @@ public NativeComponentBuildOptions( /// public IReadOnlyList bindingIncludeDirectories { get; } - internal IEnumerable declarations => new[] { "libraryKind=" + libraryKind } - .Concat(cmakeArguments.Select(static argument => "componentArgument=" + argument)) - .Concat(linkPlan?.declarations ?? []) - .Append("bindingLibrary=" + bindingLibraryName) - .Concat(bindingIncludeDirectories.Select(static path => "bindingInclude=" + path)); + internal IEnumerable declarations + => new[] { "libraryKind=" + libraryKind } + .Concat(cmakeArguments.Select(static argument => "componentArgument=" + argument)) + .Concat(linkPlan?.declarations ?? []) + .Append("bindingLibrary=" + bindingLibraryName) + .Concat(bindingIncludeDirectories.Select(static path => "bindingInclude=" + path)); private static string ValidatePath(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); string portable = path.Replace('\\', '/'); if (portable.StartsWith('/') || portable.Contains(':') || portable.Split('/').Any(static segment => segment is "" or "." or "..")) + { throw new ArgumentException("A component input must be a portable checkout-relative path.", nameof(path)); + } return portable; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentDescriptor.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentDescriptor.cs index ac52bb29e..e1707f8b5 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentDescriptor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentDescriptor.cs @@ -39,17 +39,25 @@ public NativeComponentDescriptor( ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); if (id is "." or "..") + { throw new ArgumentException("A component identity must be a portable path segment.", nameof(id)); + } foreach (char character in id) + { if (!char.IsAsciiLetterOrDigit(character) && character is not ('-' or '_' or '.')) + { throw new ArgumentException("A component identity must be a portable path segment.", nameof(id)); + } + } this.id = id; this.nativeProject = ValidateProject(nativeProject); this.toolchainProject = ValidateProject(toolchainProject); this.staticBuild = staticBuild; if (bindingDefinition is not null && (bindingDefinition.StartsWith('/') || bindingDefinition.Contains(':') - || bindingDefinition.Split('/').Any(static segment => segment is "" or "." or ".."))) + || bindingDefinition.Split('/').Any(static segment => segment is "" or "." or "..")) + ) { throw new ArgumentException("A binding definition must remain within its checkout.", nameof(bindingDefinition)); + } this.bindingDefinition = bindingDefinition; } @@ -106,7 +114,9 @@ string project ) { ArgumentException.ThrowIfNullOrWhiteSpace(engineRoot); if (!Path.IsPathFullyQualified(engineRoot)) + { throw new ArgumentException("The operation checkout must be absolute.", nameof(engineRoot)); + } return Path.GetDirectoryName(Path.GetFullPath(project, engineRoot))!; } @@ -115,10 +125,16 @@ private static string ValidateProject(string project) ArgumentException.ThrowIfNullOrWhiteSpace(project); string portable = project.Replace('\\', '/'); if (portable.StartsWith('/') || portable.Contains(':') || !portable.EndsWith(".csproj", StringComparison.Ordinal)) + { throw new ArgumentException("A component owner must be a checkout-relative project file.", nameof(project)); + } foreach (string segment in portable.Split('/')) + { if (segment is "" or "." or "..") + { throw new ArgumentException("A component owner cannot escape its checkout.", nameof(project)); + } + } return portable; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs index e01d375dd..7664e3b0b 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs @@ -51,26 +51,39 @@ public static async ValueTask CopyAsync( { byte[] existing = context.inputState.CaptureVerification([output], cancellationToken).entries.Single().hash; if (expected.AsSpan().SequenceEqual(existing)) + { return false; + } } Directory.CreateDirectory(Path.GetDirectoryName(output.physicalPath)!); string candidate = output.physicalPath + ".staging-" + Guid.NewGuid().ToString("N"); try { await using (FileStream read = File.OpenRead(input.physicalPath)) - await using (FileStream write = new(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None, - 64 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan)) - { + await using (FileStream write = new( + candidate, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 64 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan + )) { await read.CopyToAsync(write, cancellationToken).ConfigureAwait(false); await write.FlushAsync(cancellationToken).ConfigureAwait(false); write.Flush(flushToDisk: true); } byte[] copied = context.inputState.CaptureVerification( - [new NativeBuildInput(input.logicalPath, candidate)], cancellationToken).entries.Single().hash; + [new NativeBuildInput(input.logicalPath, candidate)], + cancellationToken + ).entries.Single().hash; if (!expected.AsSpan().SequenceEqual(copied)) + { throw new InvalidOperationException($"Native input '{input.logicalPath}' changed during materialization."); + } if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(candidate, File.GetUnixFileMode(input.physicalPath)); + } cancellationToken.ThrowIfCancellationRequested(); AtomicFile.Install(candidate, output.physicalPath); context.inputState.RecordMaterialization(new FileInfo(output.physicalPath).Length); @@ -79,7 +92,9 @@ public static async ValueTask CopyAsync( finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputReadCache.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputReadCache.cs index 55926f297..d6356115e 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputReadCache.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputReadCache.cs @@ -35,30 +35,47 @@ internal NativeInputReadCache( internal StringComparer pathComparer => OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; internal byte[] GetFrozenHash(string path) - => m_hashes.TryGetValue(m_physicalPaths.Resolve(path), out byte[]? hash) ? hash - : throw new InvalidOperationException($"Native input '{path}' was not frozen by this operation's recipe."); + => m_hashes.TryGetValue(m_physicalPaths.Resolve(path), out byte[]? hash) + ? hash + : throw new InvalidOperationException($"Native input '{path}' was not frozen by this operation's recipe."); internal NativeInputSnapshot CaptureRecordedInputs(string engineRoot) - => new(m_readingPaths.Select(entry => new NativeInputSnapshot.Entry( - NativeBuildInput.FromPath(engineRoot, entry.Key).logicalPath, entry.Key, m_hashes[entry.Value]))); + => new( + m_readingPaths.Select(entry => new NativeInputSnapshot.Entry( + NativeBuildInput.FromPath(engineRoot, entry.Key).logicalPath, + entry.Key, + m_hashes[entry.Value] + )) + ); internal string[][] CaptureRootMembership() => m_roots.OrderBy(static pair => pair.Key, pathComparer) - .Select(pair => new[] { pair.Key }.Concat(pair.Value.Select(static entry => entry.relative).Order(StringComparer.Ordinal)).ToArray()).ToArray(); + .Select( + pair => new[] { pair.Key }.Concat(pair.Value.Select(static entry => entry.relative).Order(StringComparer.Ordinal)).ToArray() + ) + .ToArray(); internal IReadOnlyList<(string relative, string physical)> Enumerate( string path, CancellationToken cancellationToken ) { if (m_roots.TryGetValue(path, out IReadOnlyList<(string relative, string physical)>? cached)) + { return cached; + } List<(string relative, string physical)> files = []; if (File.Exists(path)) + { files.Add((string.Empty, path)); + } else if (Directory.Exists(path)) + { EnumerateDirectory(path, string.Empty, files, new HashSet(pathComparer), cancellationToken); + } else + { throw new FileNotFoundException("A declared native build input is unavailable.", path); + } cached = files.AsReadOnly(); m_roots.Add(path, cached); return cached; @@ -79,9 +96,13 @@ CancellationToken cancellationToken m_readingPaths[readingPath] = physical; physicalPaths[index] = physical; if (m_hashes.ContainsKey(physical) || !unique.Add(physical)) + { m_state.RecordReuse(m_phase); + } else + { pending.Add(physical); + } } var hashes = new byte[pending.Count][]; var bytes = new long[pending.Count]; @@ -90,26 +111,36 @@ CancellationToken cancellationToken try { if (pending.Count == 1) + { Read(0); + } else if (pending.Count > 1) - Parallel.For(0, pending.Count, new ParallelOptions - { - MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), - CancellationToken = cancellationToken - }, ( - index, - loop - ) => { - try + { + Parallel.For( + 0, + pending.Count, + new ParallelOptions { - Read(index); - } - catch (Exception exception) + MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), + CancellationToken = cancellationToken + }, + ( + index, + loop + ) => { - Interlocked.CompareExchange(ref failure, ExceptionDispatchInfo.Capture(exception), null); - loop.Stop(); + try + { + Read(index); + } + catch (Exception exception) + { + Interlocked.CompareExchange(ref failure, ExceptionDispatchInfo.Capture(exception), null); + loop.Stop(); + } } - }); + ); + } failure?.Throw(); cancellationToken.ThrowIfCancellationRequested(); } @@ -117,12 +148,18 @@ CancellationToken cancellationToken { // Initial capture holds the state gate. Workers only read bytes; record after all workers drain. for (int index = 0; index < pending.Count; index++) + { if (opened[index]) + { m_state.RecordHash(bytes[index], m_phase); + } + } } // Publish this batch only after every read succeeds; failed/canceled batches never become frozen inputs. for (int index = 0; index < pending.Count; index++) + { m_hashes.Add(pending[index], hashes[index]); + } return physicalPaths.Select(path => m_hashes[path]).ToArray(); void Read(int index) @@ -149,6 +186,7 @@ void Read(int index) } } } + private void EnumerateDirectory( string directory, string relativeRoot, @@ -159,20 +197,26 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); string physicalRoot = m_physicalPaths.Resolve(directory); if (!ancestors.Add(physicalRoot)) + { throw new IOException($"A native input contains a directory link cycle at '{directory}'."); + } try { foreach (string file in Directory.EnumerateFiles(physicalRoot)) { cancellationToken.ThrowIfCancellationRequested(); if (Path.GetFileName(file) != ".git") + { files.Add((relativeRoot + Path.GetFileName(file), Path.Combine(directory, Path.GetFileName(file)))); + } } foreach (string child in Directory.EnumerateDirectories(physicalRoot)) { string name = Path.GetFileName(child); if (name is ".git" or ".build" or "bin" or "obj" or "__pycache__") + { continue; + } EnumerateDirectory(Path.Combine(directory, name), relativeRoot + name + "/", files, ancestors, cancellationToken); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs index cd98b3cc1..08085350a 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs @@ -33,7 +33,9 @@ CancellationToken cancellationToken if (paths.TryGetValue(logical, out string? previous)) { if (!cache.pathComparer.Equals(previous, physical)) + { throw new ArgumentException($"Native input identity '{logical}' maps to different reading locations."); + } continue; } paths.Add(logical, physical); @@ -41,9 +43,11 @@ CancellationToken cancellationToken } var ordered = paths.OrderBy(static pair => pair.Key, StringComparer.Ordinal).ToArray(); byte[][] hashes = cache.Hash(ordered.Select(static pair => pair.Value).ToArray(), cancellationToken); - return new NativeInputSnapshot(ordered.Select(( - pair, - index - ) => new Entry(pair.Key, pair.Value, hashes[index]))); + return new NativeInputSnapshot( + ordered.Select(( + pair, + index + ) => new Entry(pair.Key, pair.Value, hashes[index])) + ); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs index 89f50d906..6e49971af 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs @@ -18,6 +18,8 @@ internal NativeInputSnapshot Capture( CancellationToken cancellationToken ) { lock (m_gate) + { return NativeInputSnapshot.Capture(inputs, m_inputs, cancellationToken); + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeLinkPlan.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeLinkPlan.cs index 9107e04fa..7b53770d2 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeLinkPlan.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeLinkPlan.cs @@ -34,15 +34,21 @@ public NativeLinkPlan( IEnumerable? cmakeArguments = null ) { if (sharedLibraryExtension is null && staticLibraryExtension is null) + { throw new ArgumentException("A linker plan must contribute at least one library format."); + } if (importLibraryExtension is not null && sharedLibraryExtension is null) + { throw new ArgumentException("Import libraries require a shared-library format.", nameof(importLibraryExtension)); + } this.sharedLibraryExtension = sharedLibraryExtension is null ? null : Validate(sharedLibraryExtension); this.importLibraryExtension = importLibraryExtension is null ? null : Validate(importLibraryExtension); this.staticLibraryExtension = staticLibraryExtension is null ? null : Validate(staticLibraryExtension); string[] arguments = (cmakeArguments ?? []).ToArray(); if (arguments.Any(static argument => argument is null)) + { throw new ArgumentException("Linker arguments cannot contain null entries.", nameof(cmakeArguments)); + } this.cmakeArguments = Array.AsReadOnly(arguments); } @@ -50,14 +56,17 @@ public NativeLinkPlan( /// Gets the shared-library suffix, or null when shared linkage is unsupported. /// public string? sharedLibraryExtension { get; } + /// /// Gets the separate import suffix, or null when no separate import library is used. /// public string? importLibraryExtension { get; } + /// /// Gets the static archive suffix, or null when static linkage is unavailable. /// public string? staticLibraryExtension { get; } + /// /// Gets ordered platform linker definitions. /// @@ -92,20 +101,28 @@ public NativeLinkPlan( /// /// The linkage kind is not defined. /// - public string GetFileExtension(NativeLibraryKind kind) => (kind switch - { - NativeLibraryKind.Shared => sharedLibraryExtension, - NativeLibraryKind.Static => staticLibraryExtension, - _ => throw new ArgumentOutOfRangeException(nameof(kind)) - }) ?? throw new NotSupportedException($"This target does not contribute '{kind}' linkage."); + public string GetFileExtension(NativeLibraryKind kind) + => (kind switch + { + NativeLibraryKind.Shared => sharedLibraryExtension, + NativeLibraryKind.Static => staticLibraryExtension, + _ => throw new ArgumentOutOfRangeException(nameof(kind)) + }) ?? throw new NotSupportedException($"This target does not contribute '{kind}' linkage."); - internal IEnumerable declarations => new[] { "sharedSuffix=" + sharedLibraryExtension, - "importSuffix=" + importLibraryExtension, "staticSuffix=" + staticLibraryExtension }.Concat(cmakeArguments); + internal IEnumerable declarations + => new[] + { + "sharedSuffix=" + sharedLibraryExtension, + "importSuffix=" + importLibraryExtension, + "staticSuffix=" + staticLibraryExtension + }.Concat(cmakeArguments); private static string Validate(string value) { if (string.IsNullOrWhiteSpace(value) || !value.StartsWith('.') || value.IndexOfAny(['/', '\\', ':']) >= 0) + { throw new ArgumentException("A native output format requires a file suffix.", nameof(value)); + } return value; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeStaticBuildDefinition.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeStaticBuildDefinition.cs index dc81c0d12..cff101aff 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeStaticBuildDefinition.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeStaticBuildDefinition.cs @@ -41,15 +41,22 @@ public NativeStaticBuildDefinition( this.cmakeFile = ValidatePath(cmakeFile); this.inputPaths = Array.AsReadOnly(inputPaths.Select(ValidatePath).Distinct(StringComparer.Ordinal).ToArray()); this.nativeSourceDirectory = nativeSourceDirectory is null ? null : ValidatePath(nativeSourceDirectory); - if (this.nativeSourceDirectory is not null && !this.inputPaths.Any(path => path == this.nativeSourceDirectory - || path.StartsWith(this.nativeSourceDirectory + "/", StringComparison.Ordinal))) - throw new ArgumentException("The native source root must contain declared static recipe inputs.", nameof(nativeSourceDirectory)); + if (this.nativeSourceDirectory is not null && !this.inputPaths.Any(path => ( + path == this.nativeSourceDirectory + || path.StartsWith(this.nativeSourceDirectory + "/", StringComparison.Ordinal) + ))) { + throw new ArgumentException( + "The native source root must contain declared static recipe inputs.", + nameof(nativeSourceDirectory) + ); + } string[] archives = logicalOutputs.Select(ValidatePath).ToArray(); if (archives.Length == 0 || archives.Any(static name => name.Contains('/')) - || archives.Distinct(StringComparer.OrdinalIgnoreCase).Count() != archives.Length) + || archives.Distinct(StringComparer.OrdinalIgnoreCase).Count() != archives.Length + ) { throw new ArgumentException("A static recipe requires unique portable archive file names.", nameof(logicalOutputs)); + } this.logicalOutputs = Array.AsReadOnly(archives); - } /// @@ -72,13 +79,14 @@ public NativeStaticBuildDefinition( /// public IReadOnlyList logicalOutputs { get; } - private static string ValidatePath(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); string portable = path.Replace('\\', '/'); if (portable.StartsWith('/') || portable.Contains(':') || portable.Split('/').Any(static part => part is "" or "." or "..")) + { throw new ArgumentException("A static recipe path must remain within its declared root.", nameof(path)); + } return portable; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs index 98053fd57..cf60634d9 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs @@ -24,8 +24,12 @@ public static class NativeToolchainPreparation /// /// A caller-owned dictionary to populate with explicitly selected SDK variables. /// - public static Dictionary CreateEnvironment() => AmbientCompilerVariables.ToDictionary( - static variable => variable, static _ => string.Empty, StringComparer.OrdinalIgnoreCase); + public static Dictionary CreateEnvironment() + => AmbientCompilerVariables.ToDictionary( + static variable => variable, + static _ => string.Empty, + StringComparer.OrdinalIgnoreCase + ); /// /// Validates and freezes a provider's complete tool selection before product staging, @@ -84,13 +88,28 @@ public static NativeToolchainSelection Freeze( string physicalCMake = new PhysicalPathResolver().Resolve(cmake); string modules = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(physicalCMake)!, "..", "share")); if (Directory.Exists(modules)) + { complete.Add(modules); + } } complete.AddRange(tools.Values); foreach (string input in complete) + { if (!File.Exists(input) && !Directory.Exists(input)) + { throw new FileNotFoundException("A selected native toolchain input is unavailable.", input); - return new(targetId, host, tools, environment, complete, cmakeArguments, - linkPlan, multiConfiguration, compilerInputs); + } + } + return new( + targetId, + host, + tools, + environment, + complete, + cmakeArguments, + linkPlan, + multiConfiguration, + compilerInputs + ); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs index 924cec27e..052a2c85e 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs @@ -70,43 +70,64 @@ public NativeToolchainSelection( ArgumentNullException.ThrowIfNull(inputPaths); ArgumentNullException.ThrowIfNull(cmakeArguments); ArgumentNullException.ThrowIfNull(linkPlan); - if (tools.Count == 0 || tools.Any(static entry => string.IsNullOrWhiteSpace(entry.Key) - || string.IsNullOrWhiteSpace(entry.Value) || !Path.IsPathFullyQualified(entry.Value))) + if (tools.Count == 0 || tools.Any(static entry => ( + string.IsNullOrWhiteSpace(entry.Key) + || string.IsNullOrWhiteSpace(entry.Value) || !Path.IsPathFullyQualified(entry.Value) + ))) { throw new ArgumentException("A native tool selection requires explicit executables.", nameof(tools)); + } string[] inputs = inputPaths.Concat(tools.Values).Distinct(StringComparer.Ordinal).ToArray(); string[] arguments = cmakeArguments.ToArray(); if (inputs.Any(static path => string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path))) + { throw new ArgumentException("Native SDK inputs require absolute locations.", nameof(inputPaths)); + } if (arguments.Any(static argument => argument is null)) + { throw new ArgumentException("CMake arguments cannot contain null entries.", nameof(cmakeArguments)); + } if (environment.Any(static entry => string.IsNullOrWhiteSpace(entry.Key) || entry.Value is null)) + { throw new ArgumentException("Native environments require assigned names and values.", nameof(environment)); + } foreach (string executable in tools.Values) + { if (!File.Exists(executable)) + { throw new FileNotFoundException("A selected native executable is unavailable.", executable); + } + } foreach (string input in inputs) + { if (!File.Exists(input) && !Directory.Exists(input)) + { throw new FileNotFoundException("A selected native SDK input is unavailable.", input); + } + } this.targetId = targetId; this.host = host; m_tools = new ReadOnlyDictionary(new Dictionary(tools, StringComparer.Ordinal)); this.environment = new ReadOnlyDictionary( - new Dictionary(environment, - host.services.environmentComparer)); + new Dictionary(environment, host.services.environmentComparer) + ); this.inputPaths = Array.AsReadOnly(inputs); this.cmakeArguments = Array.AsReadOnly(arguments); this.multiConfiguration = multiConfiguration; this.compilerInputs = compilerInputs ?? new NativeCompilerInputs(); this.linkPlan = linkPlan; - declarations = Array.AsReadOnly(this.environment.OrderBy(static entry => entry.Key, StringComparer.Ordinal) - .Select(static entry => entry.Key + "=" + entry.Value) - .Concat(m_tools.OrderBy(static entry => entry.Key, StringComparer.Ordinal) - .Select(static entry => entry.Key + "=" + entry.Value)) - .Concat(this.cmakeArguments) - .Concat(this.compilerInputs.declarations) - .Concat(this.linkPlan.declarations) - .Concat([targetId, host.system, host.architecture, multiConfiguration.ToString()]) - .ToArray()); + declarations = Array.AsReadOnly( + this.environment.OrderBy(static entry => entry.Key, StringComparer.Ordinal) + .Select(static entry => entry.Key + "=" + entry.Value) + .Concat( + m_tools.OrderBy(static entry => entry.Key, StringComparer.Ordinal) + .Select(static entry => entry.Key + "=" + entry.Value) + ) + .Concat(this.cmakeArguments) + .Concat(this.compilerInputs.declarations) + .Concat(this.linkPlan.declarations) + .Concat([targetId, host.system, host.architecture, multiConfiguration.ToString()]) + .ToArray() + ); } /// @@ -190,11 +211,22 @@ IEnumerable inputs foreach ((string name, string executable) in tools) { if (combined.TryGetValue(name, out string? existing) && existing != executable) + { throw new ArgumentException($"Integration tool '{name}' conflicts with the frozen SDK selection.", nameof(tools)); + } combined[name] = executable; } - return new NativeToolchainSelection(targetId, host, combined, environment, inputPaths.Concat(inputs), - cmakeArguments, linkPlan, multiConfiguration, compilerInputs); + return new NativeToolchainSelection( + targetId, + host, + combined, + environment, + inputPaths.Concat(inputs), + cmakeArguments, + linkPlan, + multiConfiguration, + compilerInputs + ); } /// @@ -209,9 +241,10 @@ IEnumerable inputs /// /// The provider did not register the requested command. /// - public string ResolveExecutable(string name) => m_tools.TryGetValue(name, out string? executable) - ? executable - : throw new InvalidOperationException($"Native target '{targetId}' has no '{name}' executable."); + public string ResolveExecutable(string name) + => m_tools.TryGetValue(name, out string? executable) + ? executable + : throw new InvalidOperationException($"Native target '{targetId}' has no '{name}' executable."); /// /// Checks an optional tool capability without discovering a command from the process environment. diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeWorkspaceIdentity.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeWorkspaceIdentity.cs index c1c9eadfb..45f9416b4 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeWorkspaceIdentity.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeWorkspaceIdentity.cs @@ -13,14 +13,22 @@ NativeInputSnapshot snapshot ) { string[] tools = (recipe.toolchain ?? context.toolchain)?.inputPaths.Select(Path.GetFullPath).ToArray() ?? []; StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - var configuration = new NativeInputSnapshot(snapshot.entries.Where(entry => tools.Any(tool => - string.Equals(entry.physicalPath, tool, comparison) - || entry.physicalPath.StartsWith(Path.TrimEndingDirectorySeparator(tool) + Path.DirectorySeparatorChar, comparison)))); + var configuration = new NativeInputSnapshot( + snapshot.entries.Where(entry => tools.Any(tool => ( + string.Equals(entry.physicalPath, tool, comparison) + || entry.physicalPath.StartsWith(Path.TrimEndingDirectorySeparator(tool) + Path.DirectorySeparatorChar, comparison) + ))) + ); var bindings = new NativeBindingInputPaths(context); - return NativeBuildFingerprint.Create(recipe.declarations.Where(static value => - !value.StartsWith("bindings=", StringComparison.Ordinal)) - .Select(bindings.NormalizeDeclaration) - .Prepend("executionRoot=" + (context.toolchain?.host.services.workspaces.identity ?? "physical")) - .Prepend(context.configuration).Prepend(recipe.targetId).Prepend("workspace"), configuration); + return NativeBuildFingerprint.Create( + recipe.declarations + .Where(static value => !value.StartsWith("bindings=", StringComparison.Ordinal)) + .Select(bindings.NormalizeDeclaration) + .Prepend("executionRoot=" + (context.toolchain?.host.services.workspaces.identity ?? "physical")) + .Prepend(context.configuration) + .Prepend(recipe.targetId) + .Prepend("workspace"), + configuration + ); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildPlan.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildPlan.cs index bb890e988..31e1c4bfc 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildPlan.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildPlan.cs @@ -42,11 +42,15 @@ public ProductNativeBuildPlan( ArgumentNullException.ThrowIfNull(steps); var completed = new HashSet(StringComparer.Ordinal); if (steps.Count == 0) + { throw new ArgumentException("A native product requires an explicit component closure.", nameof(steps)); + } foreach (ProductNativeBuildStep step in steps) { if (step is null || step.dependencies.Any(dependency => !completed.Contains(dependency)) || !completed.Add(step.id)) + { throw new ArgumentException("Native steps must be unique and ordered after every dependency.", nameof(steps)); + } } this.productId = productId; m_steps = steps.ToArray(); @@ -100,19 +104,28 @@ public IReadOnlyList CreateRecipes(NativeBuildContext context NativeBuildContext selected = configured.WithComponentOptions(step.component, step.options); NativeBuildRecipe recipe; if (step.createRecipe is not null) + { recipe = step.createRecipe(selected); + } else { NativeStaticBuildDefinition definition = step.component.staticBuild!; - recipe = NativeBuildRecipe.CreateForComponent(selected, step.component, step.id, tools.targetId, + recipe = NativeBuildRecipe.CreateForComponent( + selected, + step.component, + step.id, + tools.targetId, definition.inputPaths.Append(definition.cmakeFile).Select(path => Path.GetFullPath(path, context.engineRoot)), definition.logicalOutputs.Select(static archive => "archive=" + archive).Prepend("static=" + definition.cmakeFile), - [Path.GetFullPath(definition.cmakeFile, context.engineRoot)]); + [Path.GetFullPath(definition.cmakeFile, context.engineRoot)] + ); } if (recipe is null || recipe.component != step.id || recipe.targetId != tools.targetId || recipe.owner.nativeProject != step.component.nativeProject - || recipe.owner.toolchainProject != step.component.toolchainProject) + || recipe.owner.toolchainProject != step.component.toolchainProject + ) { throw new InvalidOperationException($"Native step '{step.id}' returned a foreign source declaration."); + } recipes.Add(recipe); } return recipes.AsReadOnly(); @@ -134,25 +147,33 @@ public IReadOnlyDictionary CreateDeploymentFiles(IReadOnlyList(StringComparer.OrdinalIgnoreCase); for (int index = 0; index < m_steps.Length; index++) { ProductNativeBuildStep step = m_steps[index]; NativeBuildProduct product = products[index]; if (step.id != product.component) + { throw new ArgumentException("The products do not match this plan's declaration order.", nameof(products)); + } foreach (string file in product.files) { string relative = Path.GetRelativePath(Path.Combine(product.directory, "Outputs"), file); string? output = step.deploymentPath(relative, product.targetId); if (output is null) + { continue; + } string portable = output.Replace('\\', '/'); if (Path.IsPathFullyQualified(portable) || portable.Contains(':') || portable.Split('/').Any(static segment => segment is "" or "." or "..") - || !files.TryAdd(portable.Replace('/', Path.DirectorySeparatorChar), file)) + || !files.TryAdd(portable.Replace('/', Path.DirectorySeparatorChar), file) + ) { throw new ArgumentException("Native deployment paths must be portable, contained and unique.", nameof(products)); + } } } return new ReadOnlyDictionary(files); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildResult.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildResult.cs index f28fe662d..97107be7d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildResult.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildResult.cs @@ -72,7 +72,6 @@ public IReadOnlyDictionary bindingGen /// public NativeBuildRecipe? aggregateRecipe { get; } - /// /// Borrows a product whose lease is owned by this result until disposal. /// @@ -119,7 +118,9 @@ public IEnumerator GetEnumerator() public void Dispose() { if (Interlocked.Exchange(ref m_disposed, 1) != 0) + { return; + } Release(m_products, m_bindings); } @@ -148,7 +149,9 @@ NativeBindingGenerationResult bindings failures.Add(failure); } if (failures.Count != 0) + { throw new AggregateException("Native product reading ownership could not be completely released.", failures); + } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildStep.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildStep.cs index 6b6fbd7ef..2b56be339 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildStep.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeBuildStep.cs @@ -58,23 +58,41 @@ public ProductNativeBuildStep( Func? createRecipe, Func deploymentPath, string? configuration = null, - Func, NativeBuildRecipe>? bindDependencies = null + Func< + NativeBuildContext, + NativeBuildRecipe, + IReadOnlyDictionary, + NativeBuildRecipe + >? bindDependencies = null ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); ArgumentNullException.ThrowIfNull(component); ArgumentNullException.ThrowIfNull(options); if (build is null && options.libraryKind != NativeLibraryKind.Static) + { throw new ArgumentException("Aggregate-only steps require explicit static linkage.", nameof(options)); + } ArgumentNullException.ThrowIfNull(dependencies); if (build is null && component.staticBuild is null) + { throw new ArgumentException("Aggregate-only steps require a real static build definition.", nameof(build)); + } if ((build is null) != (createRecipe is null)) - throw new ArgumentException("A standalone producer requires its own source declaration; aggregate steps use their static definition.", nameof(createRecipe)); + { + throw new ArgumentException( + "A standalone producer requires its own source declaration; aggregate steps use their static definition.", + nameof(createRecipe) + ); + } ArgumentNullException.ThrowIfNull(deploymentPath); if (configuration is not null) + { ToolchainEnvironment.ValidateConfiguration(configuration); + } if (dependencies.Any(string.IsNullOrWhiteSpace) || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Count) + { throw new ArgumentException("Component dependencies must be assigned and unique.", nameof(dependencies)); + } this.id = id; this.component = component; this.options = options; @@ -109,7 +127,12 @@ public ProductNativeBuildStep( /// /// Gets the standalone producer, or null for a component owned by a static aggregate executor. /// - public Func, CancellationToken, Task>? build { get; } + public Func< + NativeBuildContext, + IReadOnlyDictionary, + CancellationToken, + Task + >? build { get; } /// /// Gets the producer's source declaration, or null when a static aggregate owns the component recipe. @@ -131,5 +154,10 @@ public ProductNativeBuildStep( /// Gets the backend-owned dependency transformation, or null for an independent source recipe. /// The supplied products are borrowed only during recipe construction. /// - public Func, NativeBuildRecipe>? bindDependencies { get; } + public Func< + NativeBuildContext, + NativeBuildRecipe, + IReadOnlyDictionary, + NativeBuildRecipe + >? bindDependencies { get; } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeCacheLookup.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeCacheLookup.cs index d58aa2b89..7e410d2af 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeCacheLookup.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeCacheLookup.cs @@ -15,11 +15,23 @@ internal static class ProductNativeCacheLookup IReadOnlyList steps, CancellationToken cancellation ) { - if (steps.Any(static step => step.createRecipe is null - || step.dependencies.Count != 0 && step.bindDependencies is null)) + if (steps.Any(static step => ( + step.createRecipe is null + || step.dependencies.Count != 0 && step.bindDependencies is null + ))) { return null; - var cache = new BuildCachePublisher(Path.Combine(context.engineRoot, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); - BuildCacheOwnerCatalog.Register(context.engineRoot, Path.Combine(context.engineRoot, "artifacts", "native"), "native", cache.role, cancellation); + } + var cache = new BuildCachePublisher( + Path.Combine(context.engineRoot, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); + BuildCacheOwnerCatalog.Register( + context.engineRoot, + Path.Combine(context.engineRoot, "artifacts", "native"), + "native", + cache.role, + cancellation + ); var activities = new List(); var ownership = new List(); var products = new Dictionary(StringComparer.Ordinal); @@ -29,26 +41,45 @@ CancellationToken cancellation { activities.Add(await cache.AcquireUseAsync(cancellation).ConfigureAwait(false)); foreach (string root in steps.Select(step => Path.Combine(step.component.GetToolchainRoot(context.engineRoot), "obj", "native")) - .Distinct(PathComparer).Order(PathComparer)) - activities.Add(await new BuildCachePublisher(root, BuildCacheArtifactRole.ReusableWorkspace) - .AcquireUseAsync(cancellation).ConfigureAwait(false)); + .Distinct(PathComparer) + .Order(PathComparer) + ) { + activities.Add( + await new BuildCachePublisher(root, BuildCacheArtifactRole.ReusableWorkspace) + .AcquireUseAsync(cancellation) + .ConfigureAwait(false) + ); + } foreach (ProductNativeBuildStep step in steps) { cancellation.ThrowIfCancellationRequested(); NativeBuildContext selected = (step.configuration is string configuration - ? context.WithConfiguration(configuration) : context).WithComponentOptions(step.component, step.options); + ? context.WithConfiguration(configuration) + : context).WithComponentOptions(step.component, step.options); NativeBuildRecipe recipe = step.createRecipe!(selected); if (recipe.component != step.id || recipe.targetId != context.RequireToolchain().targetId - || recipe.owner.nativeProject != step.component.nativeProject || recipe.owner.toolchainProject != step.component.toolchainProject) + || recipe.owner.nativeProject != step.component.nativeProject + || recipe.owner.toolchainProject != step.component.toolchainProject + ) { throw new InvalidOperationException($"Native step '{step.id}' returned a foreign source declaration."); + } if (step.bindDependencies is not null) + { recipe = step.bindDependencies(selected, recipe, products); + } if (recipe.component != step.id || recipe.targetId != context.RequireToolchain().targetId - || recipe.owner.nativeProject != step.component.nativeProject || recipe.owner.toolchainProject != step.component.toolchainProject) + || recipe.owner.nativeProject != step.component.nativeProject + || recipe.owner.toolchainProject != step.component.toolchainProject + ) { throw new InvalidOperationException($"Native step '{step.id}' returned a foreign dependency declaration."); - NativeBindingGenerationDescriptor? binding = step.component.bindingDefinition is null ? null : selected.RequireBindings(step.component); + } + NativeBindingGenerationDescriptor? binding = step.component.bindingDefinition is null + ? null + : selected.RequireBindings(step.component); if (binding is not null) + { recipe = recipe.WithBindingGeneration(context.engineRoot, binding); + } NativeInputSnapshot snapshot = context.inputState.CaptureInitial(recipe.inputs, cancellation); string fingerprint = NativeBuildFingerprint.Create(recipe.declarations, snapshot); string identity = NativeWorkspaceIdentity.Create(selected, recipe, snapshot); @@ -57,45 +88,83 @@ CancellationToken cancellation var candidate = new Candidate(selected, recipe, fingerprint, directory, workspace, binding); NativeBuildProduct? product = await AcquireProduct(candidate, cancellation).ConfigureAwait(false); if (product is null) + { return null; + } products.Add(step.id, product); candidates.Add(candidate); } // Preliminary readers freeze dependency selection. Release them before waiting for // compiler ownership, so repair holding a workspace never waits for this batch's reader. foreach (NativeBuildProduct product in products.Values) + { product.Dispose(); + } products.Clear(); - foreach (string workspace in candidates.Select(static candidate => candidate.workspace).Distinct(PathComparer).Order(PathComparer)) - ownership.Add(await FileLease.AcquireAsync(workspace + ".lock", Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false)); + foreach (string workspace in candidates + .Select(static candidate => candidate.workspace) + .Distinct(PathComparer) + .Order(PathComparer) + ) { + ownership.Add( + await FileLease.AcquireAsync(workspace + ".lock", Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false) + ); + } foreach (Candidate candidate in candidates) { NativeBuildProduct? product = await AcquireProduct(candidate, cancellation).ConfigureAwait(false); if (product is null) + { return null; + } products.Add(candidate.recipe.component, product); } NativeBuildContext verification = context.BeginInputVerification("native-product-lock"); foreach (Candidate candidate in candidates) - if (NativeBuildFingerprint.Create(verification, candidate.recipe.declarations, candidate.recipe.inputs, cancellation) != candidate.fingerprint) - throw new InvalidOperationException($"Native inputs for '{candidate.recipe.component}' changed during product ownership acquisition."); + { + if (NativeBuildFingerprint.Create( + verification, + candidate.recipe.declarations, + candidate.recipe.inputs, + cancellation + ) != candidate.fingerprint + ) { + throw new InvalidOperationException( + $"Native inputs for '{candidate.recipe.component}' changed during product ownership acquisition." + ); + } + } foreach (Candidate candidate in candidates) - cache.Record(candidate.directory, candidate.directory + ".read.lock", + { + cache.Record( + candidate.directory, + candidate.directory + ".read.lock", candidate.binding is { artifactDirectory.Length: > 0 } ? [candidate.binding.artifactDirectory] : [], candidate.recipe.component + "/" + candidate.recipe.targetId + "/" + candidate.context.configuration, - candidate.recipe.targetId, cancellation); + candidate.recipe.targetId, + cancellation + ); + } transferred = true; return steps.Select(step => products[step.id]).ToArray(); } finally { if (!transferred) + { foreach (NativeBuildProduct product in products.Values) + { product.Dispose(); + } + } for (int index = ownership.Count - 1; index >= 0; index--) + { ownership[index].Dispose(); + } for (int index = activities.Count - 1; index >= 0; index--) + { activities[index].Dispose(); + } } } @@ -105,10 +174,23 @@ CancellationToken cancellation Candidate candidate, CancellationToken cancellation ) { - BuildArtifactReadLease? reading = await BuildArtifactReadLease.TryAcquireAsync(candidate.directory, Path.Combine(candidate.context.engineRoot, "artifacts", "native"), - candidate.fingerprint, ["Outputs", "Metadata"], candidate.context, cancellation).ConfigureAwait(false); - return reading is null ? null : new NativeBuildProduct(candidate.recipe.component, candidate.recipe.targetId, - candidate.fingerprint, candidate.directory, candidate.binding, candidate.context.RequireToolchain().linkPlan.sharedLibraryExtension, reading); + BuildArtifactReadLease? reading = await BuildArtifactReadLease.TryAcquireAsync( + candidate.directory, + Path.Combine(candidate.context.engineRoot, "artifacts", "native"), + candidate.fingerprint, + ["Outputs", "Metadata"], + candidate.context, + cancellation + ).ConfigureAwait(false); + return reading is null ? null : new NativeBuildProduct( + candidate.recipe.component, + candidate.recipe.targetId, + candidate.fingerprint, + candidate.directory, + candidate.binding, + candidate.context.RequireToolchain().linkPlan.sharedLibraryExtension, + reading + ); } private sealed record Candidate( diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs index 8e505b085..7ae4d3429 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs @@ -104,24 +104,36 @@ CancellationToken cancellationToken NativeBuildProduct[] closure = products.ToArray(); if (closure.Length == 0 || closure.Any(static product => product is null) || closure.Select(static product => product.targetId).Distinct().Count() != 1 - || closure.Select(static product => product.component).Distinct().Count() != closure.Length) - throw new ArgumentException("Native deployment requires a nonempty closure of unique components for one target.", nameof(products)); + || closure.Select(static product => product.component).Distinct().Count() != closure.Length + ) { + throw new ArgumentException( + "Native deployment requires a nonempty closure of unique components for one target.", + nameof(products) + ); + } string destination = Path.Combine(Path.GetFullPath(applicationDirectory), "native"); if (ownedCandidate) { if (!Directory.Exists(applicationDirectory)) + { throw new DirectoryNotFoundException("Native staging requires an existing caller-owned candidate."); + } PathBoundary.RequireUnlinkedPath(Path.GetFullPath(applicationDirectory), destination); if (Directory.Exists(destination) || File.Exists(destination)) + { throw new IOException("Native staging requires a candidate without a native subtree."); + } } - using FileLease? ownership = ownedCandidate ? null : await FileLease.AcquireAsync(destination + ".lock", - Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + using FileLease? ownership = ownedCandidate ? null : await FileLease.AcquireAsync( + destination + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); ValidateProducts(closure, cancellationToken); IReadOnlyDictionary files = plan.CreateDeploymentFiles(closure); IReadOnlyDictionary contributed = plan.deploymentMetadata?.Invoke(closure, files) - ?? new Dictionary(); + ?? new Dictionary(); var metadata = new Dictionary(StringComparer.Ordinal); StringComparer paths = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; var payloadPaths = files.Keys.Select(relative => PathBoundary.Resolve(destination, relative)).ToHashSet(paths); @@ -129,10 +141,14 @@ CancellationToken cancellationToken foreach ((string relative, byte[] content) in contributed) { if (string.IsNullOrWhiteSpace(relative) || relative.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..")) + { throw new InvalidDataException("Native deployment metadata must use literal relative file paths."); + } string path = PathBoundary.Resolve(destination, relative); if (payloadPaths.Contains(path) || !metadataPaths.Add(path)) + { throw new InvalidDataException("Native deployment metadata cannot replace a payload file."); + } metadata.Add(relative, content?.ToArray() ?? throw new InvalidDataException("Native deployment metadata has no bytes.")); } if (!ownedCandidate && HasSameFiles(destination, files, metadata, cancellationToken)) @@ -141,11 +157,14 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); return; } - using ProcessOwnedDirectory? stagingOwner = ownedCandidate ? null + using ProcessOwnedDirectory? stagingOwner = ownedCandidate + ? null : await ProcessOwnedDirectory.CreateAsync(Path.GetDirectoryName(destination)!, cancellationToken).ConfigureAwait(false); string staging = stagingOwner?.directory ?? destination; if (ownedCandidate) + { Directory.CreateDirectory(staging); + } try { foreach ((string relative, string file) in files) @@ -155,9 +174,13 @@ CancellationToken cancellationToken Directory.CreateDirectory(Path.GetDirectoryName(output)!); await using (FileStream source = File.OpenRead(file)) await using (FileStream target = new(output, FileMode.CreateNew)) + { await source.CopyToAsync(target, cancellationToken).ConfigureAwait(false); + } if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(output, File.GetUnixFileMode(file)); + } } foreach ((string relative, byte[] bytes) in metadata) { @@ -170,7 +193,9 @@ CancellationToken cancellationToken try { if (!ownedCandidate) + { AtomicDirectory.Install(staging, destination); + } } catch (DirectoryCleanupException cleanupFailure) { @@ -191,7 +216,9 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); if (!BuildArtifactManifest.IsComplete(product.directory, product.fingerprint, ["Outputs", "Metadata"])) + { throw new InvalidDataException($"Native product '{product.component}' changed after publication."); + } } } @@ -202,7 +229,9 @@ private static bool HasSameFiles( CancellationToken cancellationToken ) { if (!Directory.Exists(directory)) + { return false; + } int count = 0; foreach (string deployed in PathBoundary.EnumerateFiles(directory)) { @@ -211,19 +240,27 @@ CancellationToken cancellationToken if (metadata.TryGetValue(relative, out byte[]? bytes)) { if (!File.ReadAllBytes(deployed).AsSpan().SequenceEqual(bytes)) + { return false; + } count++; continue; } if (!files.TryGetValue(relative, out string? source) - || new FileInfo(deployed).Length != new FileInfo(source).Length) + || new FileInfo(deployed).Length != new FileInfo(source).Length + ) { return false; + } using FileStream deployedStream = File.OpenRead(deployed); using FileStream sourceStream = File.OpenRead(source); if (!SHA256.HashData(deployedStream).AsSpan().SequenceEqual(SHA256.HashData(sourceStream))) + { return false; + } if (!OperatingSystem.IsWindows() && File.GetUnixFileMode(deployed) != File.GetUnixFileMode(source)) + { return false; + } count++; } cancellationToken.ThrowIfCancellationRequested(); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs index 9ebba5c3d..d86b79f53 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs @@ -41,24 +41,47 @@ public static async Task FreezeAsync( NativeToolchainSelection tools = context.RequireToolchain(); var identities = new List { - NativeBuildFingerprint.Create(context, tools.declarations, - tools.inputPaths.Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), cancellationToken) + NativeBuildFingerprint.Create( + context, + tools.declarations, + tools.inputPaths.Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), + cancellationToken + ) }; foreach (NativeBuildRecipe recipe in plan.CreateRecipes(context)) + { identities.Add(NativeBuildFingerprint.Create(context, recipe.declarations, recipe.inputs, cancellationToken)); + } NativeComponentDescriptor[] components = plan.steps.Select(static step => step.component) - .Where(static component => component.bindingDefinition is not null).DistinctBy(static component => component.nativeProject).ToArray(); + .Where(static component => component.bindingDefinition is not null) + .DistinctBy(static component => component.nativeProject) + .ToArray(); if (components.Length != 0) { var options = plan.steps.Where(static step => step.component.bindingDefinition is not null) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal); - var request = new NativeBindingGenerationRequest(components, tools.targetId, NativeBindingOutputMode.TargetArtifacts, componentOptions: options); - identities.Add(await context.RequireBindingGenerator().ComputeInputFingerprintAsync(context, request, cancellationToken).ConfigureAwait(false)); + var request = new NativeBindingGenerationRequest( + components, + tools.targetId, + NativeBindingOutputMode.TargetArtifacts, + componentOptions: options + ); + identities.Add( + await context + .RequireBindingGenerator() + .ComputeInputFingerprintAsync(context, request, cancellationToken) + .ConfigureAwait(false) + ); } IEnumerable declarations = new[] { context.engineRoot, context.configuration, plan.productId, tools.targetId } - .Concat(tools.environment.OrderBy(static pair => pair.Key, StringComparer.Ordinal).Select(static pair => pair.Key + "=" + pair.Value)) - .Concat(tools.cmakeArguments).Concat(tools.inputPaths) + .Concat( + tools.environment + .OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => pair.Key + "=" + pair.Value) + ) + .Concat(tools.cmakeArguments) + .Concat(tools.inputPaths) .Concat(plan.steps.Select(static step => step.id + "|" + step.configuration + "|" + JsonSerializer.Serialize(step.options))) .Concat(identities); return NativeBuildFingerprint.Create(declarations, []); @@ -94,21 +117,40 @@ string requestIdentity ArgumentNullException.ThrowIfNull(products); ArgumentException.ThrowIfNullOrWhiteSpace(requestIdentity); if (products.aggregateDirectory is not null || products.Count != plan.steps.Count - || products.Any(static product => product.bindingGeneration is { artifactDirectory.Length: 0 })) + || products.Any(static product => product.bindingGeneration is { artifactDirectory.Length: 0 }) + ) { return null; + } var rows = new List { new[] { "request", requestIdentity } }; foreach (NativeInputSnapshot.Entry input in context.inputState.CaptureRecordedInputs(context.engineRoot).entries) + { rows.Add(["input", input.physicalPath, Convert.ToHexStringLower(input.hash)]); + } foreach (string[] root in context.inputState.CaptureRootMembership()) + { rows.Add(["root", ..root]); + } for (int index = 0; index < products.Count; index++) { NativeBuildProduct product = products[index]; if (product.component != plan.steps[index].id) + { throw new ArgumentException("The prepared products do not match their declaration order.", nameof(products)); - rows.Add(["product", product.component, product.targetId, product.fingerprint, product.directory, product.sharedLibraryExtension ?? string.Empty]); + } + rows.Add( + [ + "product", + product.component, + product.targetId, + product.fingerprint, + product.directory, + product.sharedLibraryExtension ?? string.Empty + ] + ); if (product.bindingGeneration is NativeBindingGenerationDescriptor binding) + { rows.Add(["binding", product.component, plan.steps[index].component.nativeProject, JsonSerializer.Serialize(binding)]); + } } return rows.ToArray(); } @@ -150,10 +192,14 @@ string requestIdentity ArgumentNullException.ThrowIfNull(rows); ArgumentException.ThrowIfNullOrWhiteSpace(requestIdentity); cancellationToken.ThrowIfCancellationRequested(); - if (rows.Length == 0 || rows.Any(static row => row is null || row.Length == 0 - || row[0] is not ("request" or "input" or "root" or "product" or "binding")) - || rows[0].Length != 2 || rows[0][0] != "request" || rows[0][1] != requestIdentity) + if (rows.Length == 0 || rows.Any(static row => ( + row is null || row.Length == 0 + || row[0] is not ("request" or "input" or "root" or "product" or "binding") + )) + || rows[0].Length != 2 || rows[0][0] != "request" || rows[0][1] != requestIdentity + ) { return null; + } var products = new List(); var leases = new List(); var generations = new Dictionary(StringComparer.Ordinal); @@ -164,79 +210,139 @@ string requestIdentity foreach (string[] row in rows.Where(static row => row[0] == "binding")) { if (row.Length != 4) + { return null; + } NativeBindingGenerationDescriptor? binding = JsonSerializer.Deserialize(row[3]); if (binding is null || string.IsNullOrEmpty(binding.artifactDirectory)) + { return null; + } binding.Validate(); BuildCacheCleanupPlan.RequireChild(context.engineRoot, binding.artifactOwnerDirectory); if (!generations.TryGetValue(row[2], out NativeBindingGenerationDescriptor? shared)) { - BuildArtifactReadLease? lease = await BuildArtifactReadLease.TryAcquireAsync(binding.artifactDirectory, - binding.artifactOwnerDirectory, binding.fingerprint, ["Generated", "Native"], context, cancellationToken).ConfigureAwait(false); + BuildArtifactReadLease? lease = await BuildArtifactReadLease.TryAcquireAsync( + binding.artifactDirectory, + binding.artifactOwnerDirectory, + binding.fingerprint, + ["Generated", "Native"], + context, + cancellationToken + ).ConfigureAwait(false); if (lease is null) + { return null; + } leases.Add(lease); generations.Add(row[2], binding); } else if (JsonSerializer.Serialize(shared) != row[3]) + { return null; + } byComponent.Add(row[1], binding); } string[][] productRows = rows.Where(static row => row[0] == "product").ToArray(); if (productRows.Length != plan.steps.Count) + { return null; + } for (int index = 0; index < productRows.Length; index++) { string[] row = productRows[index]; if (row.Length != 6 || row[1] != plan.steps[index].id || row[2] != context.RequireToolchain().targetId) + { return null; + } string owner = Path.Combine(context.engineRoot, "artifacts", "native"); - BuildArtifactReadLease? lease = await BuildArtifactReadLease.TryAcquireAsync(row[4], owner, row[3], - ["Outputs", "Metadata"], context, cancellationToken).ConfigureAwait(false); + BuildArtifactReadLease? lease = await BuildArtifactReadLease.TryAcquireAsync( + row[4], + owner, + row[3], + ["Outputs", "Metadata"], + context, + cancellationToken + ).ConfigureAwait(false); if (lease is null) + { return null; - products.Add(new NativeBuildProduct(row[1], row[2], row[3], row[4], byComponent.GetValueOrDefault(row[1]), - row[5].Length == 0 ? null : row[5], lease)); + } + products.Add( + new NativeBuildProduct( + row[1], + row[2], + row[3], + row[4], + byComponent.GetValueOrDefault(row[1]), + row[5].Length == 0 ? null : row[5], + lease + ) + ); } NativeBuildContext verification = context.BeginInputVerification("prepared-consumer"); if (await FreezeAsync(verification, plan, cancellationToken).ConfigureAwait(false) != requestIdentity) + { return null; + } foreach (string[] row in rows.Where(static row => row[0] == "root")) { if (row.Length < 2) + { return null; + } NativeBuildInput root = NativeBuildInput.FromPath(context.engineRoot, row[1]); NativeInputSnapshot membership = verification.CaptureInputs([root], cancellationToken); - if (!membership.entries.Select(entry => entry.logicalPath == root.logicalPath - ? string.Empty : entry.logicalPath[(root.logicalPath.Length + 1)..]) - .Order(StringComparer.Ordinal).SequenceEqual(row.Skip(2), StringComparer.Ordinal)) + if (!membership.entries + .Select(entry => ( + entry.logicalPath == root.logicalPath + ? string.Empty + : entry.logicalPath[(root.logicalPath.Length + 1)..] + )) + .Order(StringComparer.Ordinal) + .SequenceEqual(row.Skip(2), StringComparer.Ordinal) + ) { return null; + } } foreach (string[] row in rows.Where(static row => row[0] == "input")) { if (row.Length != 3) + { return null; - NativeInputSnapshot input = verification.CaptureInputs([NativeBuildInput.FromPath(context.engineRoot, row[1])], cancellationToken); + } + NativeInputSnapshot input = verification.CaptureInputs( + [NativeBuildInput.FromPath(context.engineRoot, row[1])], + cancellationToken + ); if (input.entries.Count != 1 || Convert.ToHexStringLower(input.entries[0].hash) != row[2]) + { return null; + } } if (!rows.Any(static row => row[0] == "input")) + { return null; + } cancellationToken.ThrowIfCancellationRequested(); var bindings = new NativeBindingGenerationResult(generations, leases); var result = new ProductNativeBuildResult(products, bindings); transferred = true; return result; } - catch (Exception failure) when (failure is FileNotFoundException or DirectoryNotFoundException or InvalidDataException or JsonException) + catch (Exception failure) when (failure is FileNotFoundException + or DirectoryNotFoundException + or InvalidDataException + or JsonException) { return null; } finally { if (!transferred) + { ProductNativeBuildResult.Release(products, new NativeBindingGenerationResult(generations, leases)); + } } } } diff --git a/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs b/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs index 7ffe6ebf8..181bbf5a5 100644 --- a/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs +++ b/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs @@ -1,7 +1,7 @@ using System; -using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.IO; using Inno.Core.IO; namespace Inno.Build.Toolchains; @@ -21,8 +21,10 @@ public sealed class NativeBuildContext private readonly string? m_targetId; private readonly string? m_fingerprint; private readonly string? m_toolDirectory; + private IReadOnlyDictionary m_bindings = new ReadOnlyDictionary(new Dictionary()); + /// /// Creates a build context without consulting the tool assembly's checkout. /// @@ -44,7 +46,7 @@ public sealed class NativeBuildContext public NativeBuildContext( string engineRoot, string configuration - ) : this(ResolveRoot(engineRoot, configuration), configuration, new NativeBuildInputState()) { } + ) : this(ResolveRoot(engineRoot, configuration), configuration, new NativeBuildInputState()) {} private NativeBuildContext( string engineRoot, @@ -54,7 +56,9 @@ NativeBuildInputState inputState ToolchainEnvironment.ValidateConfiguration(configuration); this.engineRoot = engineRoot; if (!File.Exists(Path.Combine(this.engineRoot, ToolchainLayout.C_REPOSITORY_MARKER_FILE))) + { throw new DirectoryNotFoundException($"Engine checkout is unavailable at '{this.engineRoot}'."); + } this.configuration = configuration; m_inputState = inputState; } @@ -64,7 +68,8 @@ private NativeBuildContext( string buildOwner, string targetId, string fingerprint - ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { + ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) + { sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; @@ -80,7 +85,8 @@ string fingerprint private NativeBuildContext( NativeBuildContext origin, NativeToolchainSelection toolchain - ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { + ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) + { sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; @@ -98,7 +104,8 @@ private NativeBuildContext( NativeBuildContext origin, string configuration, NativeToolchainSelection? toolchain - ) : this(origin.engineRoot, configuration, origin.m_inputState) { + ) : this(origin.engineRoot, configuration, origin.m_inputState) + { sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; @@ -108,12 +115,12 @@ private NativeBuildContext( m_bindings = origin.m_bindings; } - private NativeBuildContext( NativeBuildContext origin, NativeComponentDescriptor component, NativeComponentBuildOptions options - ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { + ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) + { sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; @@ -130,7 +137,8 @@ NativeComponentBuildOptions options private NativeBuildContext( NativeBuildContext origin, string? toolDirectory - ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { + ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) + { sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; @@ -183,12 +191,18 @@ public string GetNativeBuildRoot(NativeComponentDescriptor component) string projectRoot = component.GetToolchainRoot(engineRoot); string projectName = Path.GetFileNameWithoutExtension(component.toolchainProject); if (!File.Exists(Path.Combine(projectRoot, projectName + ".csproj"))) + { throw new InvalidOperationException($"Native build owner '{projectName}' is unavailable in '{engineRoot}'."); + } string root = Path.Combine(projectRoot, "obj", "native"); if (m_buildOwner is null) + { return root; + } if (component.toolchainProject != m_buildOwner) + { throw new InvalidOperationException($"The native operation belongs to '{m_buildOwner}', not '{projectName}'."); + } return m_toolDirectory ?? Path.Combine(root, m_targetId!, m_fingerprint!); } @@ -264,7 +278,6 @@ public NativeBuildContext WithToolchain(NativeToolchainSelection toolchain) /// public NativeBuildContext WithConfiguration(string configuration) => new(this, configuration, toolchain); - /// /// Requires an explicit selection before a component can build or start a native tool. /// @@ -274,8 +287,9 @@ public NativeBuildContext WithToolchain(NativeToolchainSelection toolchain) /// /// Composition has not resolved a toolchain. /// - public NativeToolchainSelection RequireToolchain() => toolchain - ?? throw new InvalidOperationException("Native composition must provide an explicit target toolchain before building."); + public NativeToolchainSelection RequireToolchain() + => toolchain + ?? throw new InvalidOperationException("Native composition must provide an explicit target toolchain before building."); /// /// Scopes one component's explicit product configuration without changing the frozen SDK. @@ -317,8 +331,9 @@ public NativeComponentBuildOptions RequireComponentOptions(NativeComponentDescri { ArgumentNullException.ThrowIfNull(component); return m_component?.nativeProject == component.nativeProject - && m_component.toolchainProject == component.toolchainProject && m_componentOptions is not null - ? m_componentOptions : throw new InvalidOperationException("The native component requires explicit product configuration."); + && m_component.toolchainProject == component.toolchainProject && m_componentOptions is not null + ? m_componentOptions + : throw new InvalidOperationException("The native component requires explicit product configuration."); } /// @@ -353,9 +368,10 @@ public NativeBuildContext WithBindings(NativeBindingGenerationResult bindings) /// /// The caller released the borrowed binding result before this operation finished. /// - public NativeBindingGenerationDescriptor RequireBindings(NativeComponentDescriptor component) => - m_bindings.TryGetValue(component.nativeProject, out NativeBindingGenerationDescriptor? generation) - ? generation : throw new InvalidOperationException($"No target binding generation was prepared for '{component.nativeProject}'."); + public NativeBindingGenerationDescriptor RequireBindings(NativeComponentDescriptor component) + => m_bindings.TryGetValue(component.nativeProject, out NativeBindingGenerationDescriptor? generation) + ? generation + : throw new InvalidOperationException($"No target binding generation was prepared for '{component.nativeProject}'."); /// /// Borrows a generator while preserving this operation's input and tool ownership. @@ -383,8 +399,9 @@ public NativeBuildContext WithBindingGenerator(INativeBindingGenerator generator /// /// Composition has not supplied a binding generator. /// - public INativeBindingGenerator RequireBindingGenerator() => m_bindingGenerator - ?? throw new InvalidOperationException("Native composition must provide a binding generator."); + public INativeBindingGenerator RequireBindingGenerator() + => m_bindingGenerator + ?? throw new InvalidOperationException("Native composition must provide a binding generator."); /// /// Starts a fresh verification phase whose reads can be shared only within this derived context. @@ -410,7 +427,7 @@ internal NativeInputSnapshot CaptureInputs( IEnumerable inputs, System.Threading.CancellationToken cancellationToken ) => m_verification?.Capture(inputs, cancellationToken) - ?? m_inputState.CaptureInitial(inputs, cancellationToken); + ?? m_inputState.CaptureInitial(inputs, cancellationToken); internal NativeBuildContext WithToolDirectory(string toolDirectory) => new(this, toolDirectory); @@ -429,7 +446,9 @@ string configuration ToolchainEnvironment.ValidateConfiguration(configuration); string root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(engineRoot)); if (!File.Exists(Path.Combine(root, ToolchainLayout.C_REPOSITORY_MARKER_FILE))) + { throw new DirectoryNotFoundException($"Engine checkout is unavailable at '{root}'."); + } return new PhysicalPathResolver().Resolve(root); } } diff --git a/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs b/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs index 35fc8c16e..50d6d5901 100644 --- a/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs +++ b/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs @@ -6,7 +6,6 @@ using System.Threading; using System.Threading.Tasks; - namespace Inno.Build.Toolchains; /// @@ -58,7 +57,9 @@ IReadOnlyDictionary environment ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(environment); if (!Path.IsPathFullyQualified(fileName)) + { throw new ArgumentException("An explicit SDK tool must have an absolute path.", nameof(fileName)); + } context.inputState.RecordProcess(); return RunAsync(fileName, arguments, workingDirectory, cancellationToken, CaptureEnvironmentOverrides(environment)); } @@ -98,7 +99,7 @@ public static Task RunAsync( CancellationToken cancellationToken ) { NativeToolchainSelection tools = context.toolchain - ?? throw new InvalidOperationException("Host native tools must be resolved before execution."); + ?? throw new InvalidOperationException("Host native tools must be resolved before execution."); string executable = Path.IsPathFullyQualified(fileName) ? fileName : tools.ResolveExecutable(fileName); context.inputState.RecordProcess(); return RunAsync(executable, arguments, workingDirectory, cancellationToken, CaptureEnvironmentOverrides(tools.environment)); @@ -139,7 +140,7 @@ public static Task RunAsync( CancellationToken cancellationToken ) { NativeToolchainSelection tools = context.toolchain - ?? throw new InvalidOperationException("Host native tools must be resolved before execution."); + ?? throw new InvalidOperationException("Host native tools must be resolved before execution."); string executable = Path.IsPathFullyQualified(fileName) ? fileName : tools.ResolveExecutable(fileName); var start = new ProcessStartInfo(executable) { Arguments = arguments, WorkingDirectory = workingDirectory }; context.inputState.RecordProcess(); @@ -165,19 +166,27 @@ public static string ResolveExecutable(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); if (File.Exists(name)) + { return Path.GetFullPath(name); + } if (Path.IsPathRooted(name) || name.Contains(Path.DirectorySeparatorChar) - || name.Contains(Path.AltDirectorySeparatorChar)) + || name.Contains(Path.AltDirectorySeparatorChar) + ) { throw new FileNotFoundException($"Cannot locate toolchain executable '{name}'.", name); + } string fileName = OperatingSystem.IsWindows() && !Path.HasExtension(name) ? name + ".exe" : name; foreach (string directory in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator)) { if (string.IsNullOrWhiteSpace(directory)) + { continue; + } string candidate = Path.Combine(directory.Trim('"'), fileName); if (File.Exists(candidate)) + { return Path.GetFullPath(candidate); + } } throw new FileNotFoundException($"Cannot locate toolchain executable '{name}'.", name); } @@ -271,7 +280,9 @@ TextWriter standardError ArgumentNullException.ThrowIfNull(standardError); var start = new ProcessStartInfo(fileName) { WorkingDirectory = workingDirectory }; foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } return RunProcessAsync(start, cancellationToken, environment, standardOutput, standardError); } @@ -337,7 +348,9 @@ public static async Task CaptureOutputAsync( public static void ValidateConfiguration(string configuration) { if (configuration is not (ToolchainLayout.C_DEBUG_CONFIGURATION or ToolchainLayout.C_RELEASE_CONFIGURATION)) + { throw new ArgumentException("Native configuration must be 'debug' or 'release'.", nameof(configuration)); + } } /// @@ -539,7 +552,9 @@ TextWriter standardOutput ) { var start = new ProcessStartInfo(fileName) { WorkingDirectory = workingDirectory }; foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } await RunProcessAsync(start, cancellationToken, environment, standardOutput).ConfigureAwait(false); } @@ -556,17 +571,25 @@ private static async Task RunProcessAsync( start.RedirectStandardError = true; start.CreateNoWindow = true; if (environment is not null) + { foreach ((string name, string? value) in environment) { if (value is null) + { start.Environment.Remove(name); + } else + { start.Environment[name] = value; + } } + } cancellationToken.ThrowIfCancellationRequested(); using var process = new Process { StartInfo = start }; if (!process.Start()) + { throw new InvalidOperationException($"Cannot start '{start.FileName}'."); + } Task output = ForwardAsync(process.StandardOutput, standardOutput); Task error = ForwardAsync(process.StandardError, standardError ?? Console.Error); Task exited = process.WaitForExitAsync(cancellationToken); @@ -585,7 +608,9 @@ private static async Task RunProcessAsync( try { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } } catch (InvalidOperationException) when (process.HasExited) { @@ -603,7 +628,9 @@ private static async Task RunProcessAsync( throw; } if (process.ExitCode != 0) + { throw new InvalidOperationException($"'{start.FileName}' failed with exit code {process.ExitCode}."); + } } private static async Task ForwardAsync( @@ -611,6 +638,8 @@ private static async Task ForwardAsync( TextWriter destination ) { while (await source.ReadLineAsync().ConfigureAwait(false) is { } line) + { await destination.WriteLineAsync(line).ConfigureAwait(false); + } } } diff --git a/build/toolchains/Inno.Build.Toolchains/ToolchainWorkingDirectory.cs b/build/toolchains/Inno.Build.Toolchains/ToolchainWorkingDirectory.cs index 9ab70acd8..2dcc3e0d8 100644 --- a/build/toolchains/Inno.Build.Toolchains/ToolchainWorkingDirectory.cs +++ b/build/toolchains/Inno.Build.Toolchains/ToolchainWorkingDirectory.cs @@ -28,7 +28,9 @@ public ToolchainWorkingDirectory( IDisposable? ownership = null ) { if (!Path.IsPathFullyQualified(toolPath)) + { throw new ArgumentException("Tool execution paths must be absolute.", nameof(toolPath)); + } this.toolPath = toolPath; m_ownership = ownership; } diff --git a/entry/InnoEngine.Build/Program.cs b/entry/InnoEngine.Build/Program.cs index 3d3d70ab7..9d1cfd739 100644 --- a/entry/InnoEngine.Build/Program.cs +++ b/entry/InnoEngine.Build/Program.cs @@ -43,17 +43,23 @@ private static async Task Main(string[] arguments) private static string[] CreateArguments(string[] arguments) { if (arguments.Length > 0 && arguments[0] is "help" or "--help" or "-h") + { return arguments; + } bool implicitSupport = arguments.Length == 0 || arguments[0].StartsWith("--", StringComparison.Ordinal); var result = new List { implicitSupport ? "support" : arguments[0] }; result.AddRange(implicitSupport ? arguments : arguments[1..]); if (result[0] is not ("support" or "editor" or "clean" or "bindings" or "support-pack" or "shader")) + { return result.ToArray(); + } string target = ReadDevelopmentTarget(); int scope = result.IndexOf("--scope"); bool allCaches = result[0] == "clean" && scope >= 0 && scope + 1 < result.Count && result[scope + 1] == "cache"; if (!allCaches) + { AddDefault(result, "--target", target); + } AddDefault(result, "--tools-target", target); string configuration = typeof(Program).Assembly.GetCustomAttribute()!.Configuration; AddDefault(result, "--configuration", result[0] is "support" or "editor" or "clean" ? configuration : "Release"); @@ -63,8 +69,12 @@ private static string[] CreateArguments(string[] arguments) private static string ReadDevelopmentTarget() { foreach (AssemblyMetadataAttribute metadata in typeof(Program).Assembly.GetCustomAttributes()) + { if (metadata.Key == "Inno.Build.DevelopmentTarget" && !string.IsNullOrWhiteSpace(metadata.Value)) + { return metadata.Value; + } + } throw new PlatformNotSupportedException("No build host is registered for the selected SDK."); } @@ -74,7 +84,9 @@ private static void AddDefault( string value ) { if (arguments.Contains(name)) + { return; + } arguments.Add(name); arguments.Add(value); } diff --git a/entry/InnoEngine.Editor/Program.cs b/entry/InnoEngine.Editor/Program.cs index 19a783c83..c9ed41fdc 100644 --- a/entry/InnoEngine.Editor/Program.cs +++ b/entry/InnoEngine.Editor/Program.cs @@ -29,10 +29,15 @@ private static int Main(string[] arguments) string ownership = ReadProductLock(); // Product clean must wait until the running Editor has released its deployment. if (!System.IO.File.Exists(ownership)) + { FileLease.AcquireAsync(ownership, TimeSpan.FromSeconds(10), cancellation.Token) - .GetAwaiter().GetResult().Dispose(); + .GetAwaiter() + .GetResult() + .Dispose(); + } using FileLease reading = FileLease.AcquireSharedAsync(ownership, TimeSpan.FromSeconds(10), cancellation.Token) - .GetAwaiter().GetResult(); + .GetAwaiter() + .GetResult(); #if INNO_HOST_WINDOWS_X64 return WindowsX64EditorComposition.Run(arguments, cancellation.Token); #elif INNO_HOST_MACOS_ARM64 @@ -59,8 +64,12 @@ private static int Main(string[] arguments) private static string ReadProductLock() { foreach (AssemblyMetadataAttribute metadata in typeof(Program).Assembly.GetCustomAttributes()) + { if (metadata.Key == "Inno.Editor.ProductLock" && !string.IsNullOrWhiteSpace(metadata.Value)) + { return metadata.Value; + } + } throw new InvalidOperationException("The Editor build did not declare its product ownership path."); } } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/BrowserWasm32BuildModule.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/BrowserWasm32BuildModule.cs index 1432aa1c3..81ee4b080 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/BrowserWasm32BuildModule.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/BrowserWasm32BuildModule.cs @@ -14,7 +14,13 @@ public static class BrowserWasm32BuildModule /// Gets the explicit implemented product target, independent of the tool execution host. /// public static PlatformTargetDescriptor target { get; } = new( - new BuildTargetId("browser-wasm"), "Browser", "wasm32", "emscripten-wasm32", "browser-wasm", false); + new BuildTargetId("browser-wasm"), + "Browser", + "wasm32", + "emscripten-wasm32", + "browser-wasm", + false + ); /// /// Contributes the platform's target, product inputs and SDK resolver as one registration. @@ -42,11 +48,14 @@ INativeBindingGenerator bindingGenerator ) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(nativePlan); - return new(target, + return new( + target, () => new BrowserWasm32GameBuildTarget(supportPackValidator), new BrowserWasm32PlayerSupportPackSource(context.host, context.toolsTarget, nativePlan, bindingGenerator, supportPackValidator), new EmscriptenNativeToolchainProvider(context.dotnetHost), - nativeProducts: [nativePlan], bindingGenerator: bindingGenerator, - managedDeployments: [ManagedDeploymentId.monoWasm, ManagedDeploymentId.monoWasmAot]); + nativeProducts: [nativePlan], + bindingGenerator: bindingGenerator, + managedDeployments: [ManagedDeploymentId.monoWasm, ManagedDeploymentId.monoWasmAot] + ); } } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs index 1add23e18..af3ef3cae 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs @@ -58,29 +58,48 @@ public static async Task> ResolveAsync( host = File.ResolveLinkTarget(host, returnFinalTarget: true)?.FullName ?? host; string project = Path.GetFullPath(projectPath); if (!File.Exists(project)) + { throw new FileNotFoundException("The browser toolchain project is missing.", project); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", project, "-nologo", "-nodeReuse:false", - "-getProperty:EmscriptenSdkToolsPath,EmscriptenNodeToolsPath,EmscriptenPythonToolsPath,EmscriptenCacheSdkCacheDir"], - Path.GetDirectoryName(project)!, cancellationToken, - DotNetSdkEnvironment.Create(host, new Dictionary { ["DOTNET_NOLOGO"] = "true" })).ConfigureAwait(false); + } + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + project, + "-nologo", + "-nodeReuse:false", + "-getProperty:EmscriptenSdkToolsPath,EmscriptenNodeToolsPath,EmscriptenPythonToolsPath,EmscriptenCacheSdkCacheDir" + ], + Path.GetDirectoryName(project)!, + cancellationToken, + DotNetSdkEnvironment.Create(host, new Dictionary { ["DOTNET_NOLOGO"] = "true" }) + ).ConfigureAwait(false); using JsonDocument document = JsonDocument.Parse(output); JsonElement properties = document.RootElement.GetProperty("Properties"); string root = Path.GetDirectoryName(host)!; string sdk = ReadToolPath(properties, "EmscriptenSdkToolsPath"); string cache = ReadToolPath(properties, "EmscriptenCacheSdkCacheDir"); - string node = Path.Combine(ReadToolPath(properties, "EmscriptenNodeToolsPath"), "bin", - OperatingSystem.IsWindows() ? "node.exe" : "node"); + string node = Path.Combine( + ReadToolPath(properties, "EmscriptenNodeToolsPath"), + "bin", + OperatingSystem.IsWindows() ? "node.exe" : "node" + ); string python = OperatingSystem.IsWindows() - ? Path.Combine(ReadToolPath(properties, "EmscriptenPythonToolsPath"), "python.exe") - : ToolchainEnvironment.ResolveExecutable("python3"); + ? Path.Combine(ReadToolPath(properties, "EmscriptenPythonToolsPath"), "python.exe") + : ToolchainEnvironment.ResolveExecutable("python3"); string clang = Path.Combine(sdk, "bin", OperatingSystem.IsWindows() ? "clang.exe" : "clang"); string clangCpp = Path.Combine(sdk, "bin", OperatingSystem.IsWindows() ? "clang++.exe" : "clang++"); foreach (string file in new[] { host, node, python, clang, clangCpp }) + { if (!File.Exists(file)) + { throw new FileNotFoundException("An installed WebAssembly toolchain executable is missing.", file); + } + } if (!Directory.Exists(Path.Combine(cache, "sysroot"))) + { throw new DirectoryNotFoundException($"The WebAssembly SDK sysroot is missing at '{cache}'."); + } return new Dictionary(StringComparer.Ordinal) { ["DOTNET_HOST_PATH"] = host, @@ -100,11 +119,16 @@ private static string ReadToolPath( string name ) { if (!properties.TryGetProperty(name, out JsonElement value) || string.IsNullOrWhiteSpace(value.GetString())) - throw new InvalidOperationException($"The browser application SDK did not select '{name}'. Verify its WebAssembly SDK and the selected host's wasm-tools workload."); + { + throw new InvalidOperationException( + $"The browser application SDK did not select '{name}'. Verify its WebAssembly SDK and the selected host's wasm-tools workload." + ); + } string path = Path.GetFullPath(value.GetString()!); if (!Directory.Exists(path)) + { throw new DirectoryNotFoundException($"The browser SDK's '{name}' directory is missing at '{path}'."); + } return path; } - } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32LinkerSettings.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32LinkerSettings.cs index 6b13560c0..93de9a245 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32LinkerSettings.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32LinkerSettings.cs @@ -13,6 +13,5 @@ public static class BrowserWasm32LinkerSettings /// /// The immutable target linker plan. /// - public static NativeLinkPlan Create() - => new(staticLibraryExtension: ".a"); + public static NativeLinkPlan Create() => new(staticLibraryExtension: ".a"); } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs index 3d75983cc..9411db772 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs @@ -20,7 +20,8 @@ public sealed class BrowserWasm32NativeProductExecutor : INativeProductExecutor public static NativeComponentDescriptor componentDescriptor { get; } = new( "browser", "platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Inno.Build.BrowserWasm32.csproj", - "platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Inno.Build.BrowserWasm32.csproj"); + "platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Inno.Build.BrowserWasm32.csproj" + ); /// /// Publishes one exact static closure without discovering components or reselecting tools. @@ -56,71 +57,137 @@ public async Task BuildAsync( cancellationToken.ThrowIfCancellationRequested(); NativeToolchainSelection tools = context.RequireToolchain(); if (tools.targetId != Inno.Build.BrowserWasm32.BrowserWasm32BuildModule.target.id.value || context.configuration != "release") + { throw new InvalidOperationException("Browser static publication requires an explicit Release wasm32 selection."); + } foreach (ProductNativeBuildStep step in plan.steps) + { if (step.options.libraryKind != NativeLibraryKind.Static || step.component.staticBuild is null) + { throw new InvalidOperationException($"Component '{step.id}' has no selected static build capability."); + } + } NativeBindingGenerationResult generations = await NativeBindingPreparation.PrepareAsync( - context, plan.steps.Select(static step => step.component).ToArray(), cancellationToken, - plan.steps.ToDictionary(static step => step.component.nativeProject, static step => step.options, StringComparer.Ordinal)).ConfigureAwait(false); + context, + plan.steps.Select(static step => step.component).ToArray(), + cancellationToken, + plan.steps.ToDictionary(static step => step.component.nativeProject, static step => step.options, StringComparer.Ordinal) + ).ConfigureAwait(false); try { context = context.WithBindings(generations).WithComponentOptions(componentDescriptor, new(NativeLibraryKind.Static)); string owner = componentDescriptor.GetToolchainRoot(context.engineRoot); - string[] inputs = plan.steps.SelectMany(step => step.component.staticBuild!.inputPaths + string[] inputs = plan.steps + .SelectMany(step => step.component.staticBuild!.inputPaths .Append(step.component.staticBuild.cmakeFile) .Select(path => Path.GetFullPath(path, context.engineRoot)) .Concat(step.options.inputPaths.Select(path => Path.GetFullPath(path, context.engineRoot)))) .Concat(generations.Values.Select(static generation => generation.bindingsPath)) - .Concat(generations.Values.Where(static generation => generation.nativeDirectory.Length != 0) - .Select(static generation => generation.nativeDirectory)) - .Concat(generations.Values.Where(static generation => generation.nativeDirectory.Length != 0) - .SelectMany(generation => NativeBindingCompilation.Load(generation.nativeDirectory) - .GetInputs(context.engineRoot, generation.nativeDirectory).Select(static input => input.physicalPath))) + .Concat( + generations.Values.Where(static generation => generation.nativeDirectory.Length != 0) + .Select(static generation => generation.nativeDirectory) + ) + .Concat( + generations.Values.Where(static generation => generation.nativeDirectory.Length != 0) + .SelectMany(generation => NativeBindingCompilation.Load(generation.nativeDirectory) + .GetInputs(context.engineRoot, generation.nativeDirectory) + .Select(static input => input.physicalPath)) + ) .Append(Path.Combine(owner, "Native", "CMakeLists.txt")) - .Distinct(StringComparer.Ordinal).ToArray(); + .Distinct(StringComparer.Ordinal) + .ToArray(); string[] declarations = plan.steps.Select(step => step.id + "=" + step.component.staticBuild!.cmakeFile) - .Concat(plan.steps.SelectMany(step => step.component.staticBuild!.logicalOutputs.Select(BrowserWasm32LinkerSettings.Create().GetStaticFileName) - .Select(name => step.id + ":archive=" + name))) - .Concat(plan.steps.SelectMany(static step => new[] { step.id + ":library=" + step.options.libraryKind, - step.id + ":native-source=" + step.component.staticBuild!.nativeSourceDirectory } - .Concat(step.options.cmakeArguments.Select(argument => step.id + ":argument=" + argument)))) - .Concat(generations.OrderBy(static pair => pair.Key, StringComparer.Ordinal) - .Select(static pair => pair.Key + "=" + pair.Value.fingerprint)) - .Append("product=" + plan.productId).ToArray(); + .Concat( + plan.steps.SelectMany(step => step.component.staticBuild!.logicalOutputs + .Select(BrowserWasm32LinkerSettings.Create().GetStaticFileName) + .Select(name => step.id + ":archive=" + name)) + ) + .Concat( + plan.steps.SelectMany(static step => new[] + { + step.id + ":library=" + step.options.libraryKind, + step.id + ":native-source=" + step.component.staticBuild!.nativeSourceDirectory + } + .Concat(step.options.cmakeArguments.Select(argument => step.id + ":argument=" + argument))) + ) + .Concat( + generations.OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => pair.Key + "=" + pair.Value.fingerprint) + ) + .Append("product=" + plan.productId) + .ToArray(); NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent( - context, componentDescriptor, "browser", tools.targetId, inputs, declarations, - [Path.Combine(owner, "Native", "BrowserWasm32NativeProductExecutor.cs")]); - NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(context, recipe, + context, + componentDescriptor, + "browser", + tools.targetId, + inputs, + declarations, + [Path.Combine(owner, "Native", "BrowserWasm32NativeProductExecutor.cs")] + ); + NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, token - ) => { + ) => + { string intermediate = scoped.GetNativeBuildRoot(componentDescriptor); Directory.CreateDirectory(intermediate); string selection = Path.Combine(intermediate, "Components.cmake"); NativeCMakeSource sources = await NativeCMakeExecutor.PrepareSourceAsync( - @scoped, componentDescriptor, token).ConfigureAwait(false); + @scoped, + componentDescriptor, + token + ).ConfigureAwait(false); WriteComponentSelection(selection, scoped.engineRoot, sources, plan, generations); - string build = await NativeCMakeExecutor.BuildAsync(scoped, componentDescriptor, - Path.Combine(owner, "Native"), null, - ["-DINNO_COMPONENT_SELECTION=" + selection, "-DCMAKE_INSTALL_PREFIX=" + output, - "-DPython3_EXECUTABLE=" + tools.ResolveExecutable("python")], token).ConfigureAwait(false); - await ToolchainEnvironment.RunAsync(scoped, tools.ResolveExecutable("cmake"), - ["--install", build, "--component", "Inno"], scoped.engineRoot, token, - tools.environment).ConfigureAwait(false); + string build = await NativeCMakeExecutor.BuildAsync( + scoped, + componentDescriptor, + Path.Combine(owner, "Native"), + null, + [ + "-DINNO_COMPONENT_SELECTION=" + selection, + "-DCMAKE_INSTALL_PREFIX=" + output, + "-DPython3_EXECUTABLE=" + tools.ResolveExecutable("python") + ], + token + ).ConfigureAwait(false); + await ToolchainEnvironment.RunAsync( + scoped, + tools.ResolveExecutable("cmake"), + ["--install", build, "--component", "Inno"], + scoped.engineRoot, + token, + tools.environment + ).ConfigureAwait(false); ValidateNativeOutputs(output, tools.targetId, plan); - NativeBindingGenerationDescriptor.WriteSelection(Path.Combine(output, "Metadata", "BindingSelection.props"), generations, + NativeBindingGenerationDescriptor.WriteSelection( + Path.Combine(output, "Metadata", "BindingSelection.props"), + generations, plan.steps.Where(step => generations.ContainsKey(step.component.nativeProject)) - .ToDictionary(static step => step.component.nativeProject, static step => step.options.libraryKind, StringComparer.Ordinal)); - }, cancellationToken, describeOutputs: static ( + .ToDictionary( + static step => step.component.nativeProject, + static step => step.options.libraryKind, + StringComparer.Ordinal + ) + ); + }, + cancellationToken, + describeOutputs: static ( @scoped, output ) => Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories) - .Select(file => new NativeArtifact(Path.GetRelativePath(output, file), file, - Path.GetExtension(file) == ".a" ? NativeArtifactRole.StaticArchive : NativeArtifactRole.SupportFile)).ToArray()).ConfigureAwait(false); + .Select(file => new NativeArtifact( + Path.GetRelativePath(output, file), + file, + Path.GetExtension(file) == ".a" ? NativeArtifactRole.StaticArchive : NativeArtifactRole.SupportFile + )) + .ToArray() + ).ConfigureAwait(false); return new ProductNativeBuildResult([product], generations, Path.Combine(product.directory, "Outputs"), recipe); } catch @@ -153,8 +220,14 @@ IReadOnlyDictionary generations } text.AppendLine("set(INNO_COMPONENT_ID " + CMakeLiteral(step.id) + ")"); if (step.component.staticBuild!.nativeSourceDirectory is string nativeSource) - text.AppendLine("set(INNO_COMPONENT_NATIVE " + CMakeLiteral(sources.ResolvePath(Path.GetFullPath(nativeSource, engineRoot))) + ")"); - text.AppendLine("include(" + CMakeLiteral(sources.ResolvePath(Path.GetFullPath(step.component.staticBuild!.cmakeFile, engineRoot))) + ")"); + { + text.AppendLine( + "set(INNO_COMPONENT_NATIVE " + CMakeLiteral(sources.ResolvePath(Path.GetFullPath(nativeSource, engineRoot))) + ")" + ); + } + text.AppendLine( + "include(" + CMakeLiteral(sources.ResolvePath(Path.GetFullPath(step.component.staticBuild!.cmakeFile, engineRoot))) + ")" + ); text.AppendLine("endfunction()"); text.AppendLine(scope + "()"); } @@ -169,16 +242,21 @@ ProductNativeBuildPlan plan var expected = new HashSet(StringComparer.Ordinal); foreach (ProductNativeBuildStep step in plan.steps) { - foreach (string archive in step.component.staticBuild!.logicalOutputs.Select(BrowserWasm32LinkerSettings.Create().GetStaticFileName)) - { + foreach (string archive in step.component.staticBuild!.logicalOutputs.Select( + BrowserWasm32LinkerSettings.Create().GetStaticFileName + )) { string path = Path.Combine(directory, step.id, targetId, archive); if (!File.Exists(path) || new FileInfo(path).Length == 0) + { throw new InvalidDataException($"Component '{step.id}' did not produce its required archive '{archive}'."); + } expected.Add(path); } } if (!expected.SetEquals(Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories))) + { throw new InvalidDataException("The static candidate contains outputs outside its frozen component closure."); + } } private static string CMakeLiteral(string value) @@ -186,7 +264,9 @@ private static string CMakeLiteral(string value) string portable = value.Replace('\\', '/'); int delimiter = 0; while (portable.Contains("]" + new string('=', delimiter) + "]", StringComparison.Ordinal)) + { delimiter++; + } string equals = new('=', delimiter); return "[" + equals + "[" + portable + "]" + equals + "]"; } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs index 3e75fc6b5..04222bc9b 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs @@ -74,39 +74,82 @@ CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); cancellationToken.ThrowIfCancellationRequested(); - string project = Path.Combine(context.engineRoot, "platforms", "BrowserWasm32", "player", - "Inno.Player.BrowserWasm32", "Inno.Player.BrowserWasm32.csproj"); - string template = Path.Combine(BrowserWasm32NativeProductExecutor.componentDescriptor.GetToolchainRoot(context.engineRoot), - "Templates", "BrowserWasm32Player.project.xml"); + string project = Path.Combine( + context.engineRoot, + "platforms", + "BrowserWasm32", + "player", + "Inno.Player.BrowserWasm32", + "Inno.Player.BrowserWasm32.csproj" + ); + string template = Path.Combine( + BrowserWasm32NativeProductExecutor.componentDescriptor.GetToolchainRoot(context.engineRoot), + "Templates", + "BrowserWasm32Player.project.xml" + ); if (!File.Exists(template)) + { throw new FileNotFoundException("The Browser publication template is absent.", template); + } var nativeContext = new NativeBuildContext(context.engineRoot, "release").WithBindingGenerator(m_bindingGenerator); NativeToolchainSelection tools = await new EmscriptenNativeToolchainProvider(context.dotnetHost) - .ResolveAsync(nativeContext, m_host, target.value, cancellationToken).ConfigureAwait(false); + .ResolveAsync(nativeContext, m_host, target.value, cancellationToken) + .ConfigureAwait(false); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync( - tools.ResolveExecutable("dotnet"), project, cancellationToken).ConfigureAwait(false); + tools.ResolveExecutable("dotnet"), + project, + cancellationToken + ).ConfigureAwait(false); nativeContext = nativeContext.WithToolchain(tools); var properties = new Dictionary { - ["Configuration"] = "Release", ["InnoNativeTarget"] = target.value, ["InnoToolTarget"] = m_toolsTarget.value, + ["Configuration"] = "Release", + ["InnoNativeTarget"] = target.value, + ["InnoToolTarget"] = m_toolsTarget.value, ["InnoShaderToolSourceRoot"] = context.engineRoot, - ["DebugType"] = "None", ["DebugSymbols"] = "false" + ["DebugType"] = "None", + ["DebugSymbols"] = "false" }; if (context.nativeDependencies is not null) + { properties["InnoNativeDependencyManifest"] = context.nativeDependencies; - await ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "restore", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet", - .. properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value)], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(sdk.hostPath, tools.environment)).ConfigureAwait(false); + } + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [ + sdk.cliPath, + "restore", + project, + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--nologo", + "-v:quiet", + .. properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value) + ], + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(sdk.hostPath, tools.environment) + ).ConfigureAwait(false); string owner = BrowserWasm32NativeProductExecutor.componentDescriptor.GetToolchainRoot(context.engineRoot); PlayerSupportPackPreparationIdentity identity = await PlayerSupportPackPreparationIdentity.CaptureAsync( - nativeContext, m_nativeProduct.plan, sdk, project, properties, - [template, Path.Combine(Path.GetDirectoryName(project)!, "wwwroot", "index.html"), + nativeContext, + m_nativeProduct.plan, + sdk, + project, + properties, + [ + template, + Path.Combine(Path.GetDirectoryName(project)!, "wwwroot", "index.html"), Path.Combine(Path.GetDirectoryName(project)!, "wwwroot", "main.js"), Path.Combine(owner, "Native", "BrowserWasm32NativeProductExecutor.cs"), - Path.Combine(owner, "Native", "CMakeLists.txt"), Path.Combine(owner, "Native", "wasm_sjlj_shim.c"), + Path.Combine(owner, "Native", "CMakeLists.txt"), + Path.Combine(owner, "Native", "wasm_sjlj_shim.c"), Path.Combine(owner, "SupportPacks", "BrowserWasm32PlayerSupportPackSource.cs"), - Path.Combine(owner, "SupportPacks", "BrowserWasm32SupportPackValidator.cs")], cancellationToken).ConfigureAwait(false); + Path.Combine(owner, "SupportPacks", "BrowserWasm32SupportPackValidator.cs") + ], + cancellationToken + ).ConfigureAwait(false); return new PreparationPlan(this, context.engineRoot, project, sdk, nativeContext, identity); } @@ -119,35 +162,72 @@ CancellationToken cancellationToken ) { NativeToolchainSelection tools = nativeContext.RequireToolchain(); using ProductNativeBuildResult artifacts = identity.nativeDependencies is string manifest - ? await NativeDependencyManifest.AcquireAsync(nativeContext.engineRoot, manifest, target.value, - nativeContext.configuration, m_nativeProduct.plan, cancellationToken).ConfigureAwait(false) + ? await NativeDependencyManifest.AcquireAsync( + nativeContext.engineRoot, + manifest, + target.value, + nativeContext.configuration, + m_nativeProduct.plan, + cancellationToken + ).ConfigureAwait(false) : await m_nativeProduct.BuildAsync(nativeContext, cancellationToken).ConfigureAwait(false); using ManagedBuildExecution execution = await identity.CreateExecutionAsync(cancellationToken).ConfigureAwait(false); context = new PlayerSupportPackBuildContext(execution.engineRoot, context.stagingDirectory, context.sdk); project = execution.project; string profileRoot = Path.Combine(context.engineRoot, "artifacts", "managed", "browser-references", artifacts[0].fingerprint); using FileLease ownership = await FileLease.AcquireAsync( - profileRoot + ".lock", Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + profileRoot + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); string bindingSelection = Path.Combine(profileRoot, "BindingSelection.props"); - NativeBindingGenerationDescriptor.WriteSelection(bindingSelection, artifacts.bindingGenerations, + NativeBindingGenerationDescriptor.WriteSelection( + bindingSelection, + artifacts.bindingGenerations, m_nativeProduct.plan.steps.Where(step => artifacts.bindingGenerations.ContainsKey(step.component.nativeProject)) - .ToDictionary(static step => step.component.nativeProject, static step => step.options.libraryKind, StringComparer.Ordinal)); - string[] properties = ["-p:Configuration=Release", "-p:InnoNativeTarget=" + target.value, - "-p:InnoToolTarget=" + m_toolsTarget.value, "-p:InnoNativeBuildFingerprint=" + artifacts[0].fingerprint, + .ToDictionary(static step => step.component.nativeProject, static step => step.options.libraryKind, StringComparer.Ordinal) + ); + string[] properties = + [ + "-p:Configuration=Release", + "-p:InnoNativeTarget=" + target.value, + "-p:InnoToolTarget=" + m_toolsTarget.value, + "-p:InnoNativeBuildFingerprint=" + artifacts[0].fingerprint, "-p:InnoShaderToolSourceRoot=" + nativeContext.engineRoot, "-p:InnoNativeBindingSelection=" + bindingSelection, - ..(identity.nativeDependencies is string selection ? new[] { "-p:InnoNativeDependencyManifest=" + selection } : Array.Empty()), - "-p:DebugType=None", "-p:DebugSymbols=false"]; - await ToolchainEnvironment.RunAsync(context.sdk.hostPath, + ..(identity.nativeDependencies is string selection + ? new[] { "-p:InnoNativeDependencyManifest=" + selection } + : Array.Empty()), + "-p:DebugType=None", + "-p:DebugSymbols=false" + ]; + await ToolchainEnvironment.RunAsync( + context.sdk.hostPath, [context.sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", .. properties], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(context.sdk.hostPath, tools.environment)).ConfigureAwait(false); - string buildOutput = (await ToolchainEnvironment.CaptureOutputAsync(context.sdk.hostPath, + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(context.sdk.hostPath, tools.environment) + ).ConfigureAwait(false); + string buildOutput = (await ToolchainEnvironment.CaptureOutputAsync( + context.sdk.hostPath, [context.sdk.cliPath, "msbuild", project, "-getProperty:TargetDir", "-p:DesignTimeBuild=true", "-nologo", .. properties], - context.engineRoot, cancellationToken, DotNetSdkEnvironment.Create(context.sdk.hostPath, tools.environment)).ConfigureAwait(false)).Trim(); - PlayerSupportPackFiles.CopyReferences(buildOutput, Path.Combine(context.stagingDirectory, "References"), "Inno.Player.BrowserWasm32"); + context.engineRoot, + cancellationToken, + DotNetSdkEnvironment.Create(context.sdk.hostPath, tools.environment) + ).ConfigureAwait(false)).Trim(); + PlayerSupportPackFiles.CopyReferences( + buildOutput, + Path.Combine(context.stagingDirectory, "References"), + "Inno.Player.BrowserWasm32" + ); CopyLinkTemplate(context.engineRoot, context.stagingDirectory, artifacts, project); - await PlayerSupportPackFiles.CopyPlayerSourcesAsync(context, project, - Path.Combine(context.stagingDirectory, "PlayerLink"), cancellationToken, tools.environment).ConfigureAwait(false); + await PlayerSupportPackFiles.CopyPlayerSourcesAsync( + context, + project, + Path.Combine(context.stagingDirectory, "PlayerLink"), + cancellationToken, + tools.environment + ).ConfigureAwait(false); await execution.VerifyAsync(cancellationToken).ConfigureAwait(false); } @@ -171,7 +251,9 @@ string productProject CopyRequired(Path.Combine(owner, "Templates", "BrowserWasm32Player.project.xml"), Path.Combine(template, "Player.csproj")); PlayerSupportPackFiles.CopyCompositionInputs(engineRoot, template); foreach (string asset in new[] { "index.html", "main.js" }) + { CopyRequired(Path.Combine(Path.GetDirectoryName(productProject)!, "wwwroot", asset), Path.Combine(webRoot, asset)); + } foreach (string archive in Directory.EnumerateFiles(artifacts.aggregateDirectory!, "*.a", SearchOption.AllDirectories)) { string destination = PathBoundary.Resolve(native, Path.GetRelativePath(artifacts.aggregateDirectory!, archive)); @@ -180,7 +262,9 @@ string productProject } CopyRequired(Path.Combine(owner, "Native", "wasm_sjlj_shim.c"), Path.Combine(native, "wasm_sjlj_shim.c")); foreach (string file in Directory.EnumerateFiles(Path.Combine(staging, "References"), "*.dll")) + { CopyRequired(file, Path.Combine(references, Path.GetFileName(file))); + } } private static void CopyRequired( @@ -188,9 +272,12 @@ private static void CopyRequired( string destination ) { if (!File.Exists(source)) + { throw new FileNotFoundException($"Browser Support Pack input is missing: '{source}'.", source); + } File.Copy(source, destination, overwrite: true); } + private sealed class PreparationPlan( BrowserWasm32PlayerSupportPackSource owner, string engineRoot, @@ -198,7 +285,8 @@ private sealed class PreparationPlan( DotNetSdkDescriptor sdk, NativeBuildContext native, PlayerSupportPackPreparationIdentity identity - ) : PlayerSupportPackPlan(owner.target, identity.fingerprint) { + ) : PlayerSupportPackPlan(owner.target, identity.fingerprint) + { /// public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => identity.VerifyAsync(cancellationToken); @@ -206,8 +294,12 @@ PlayerSupportPackPreparationIdentity identity public override ValueTask PrepareAsync( string stagingDirectory, CancellationToken cancellationToken - ) => owner.ExecuteAsync(new PlayerSupportPackBuildContext(engineRoot, stagingDirectory, sdk), - project, native, identity, cancellationToken); + ) => owner.ExecuteAsync( + new PlayerSupportPackBuildContext(engineRoot, stagingDirectory, sdk), + project, + native, + identity, + cancellationToken + ); } - } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32SupportPackValidator.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32SupportPackValidator.cs index b96c9feb8..f8168febc 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32SupportPackValidator.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32SupportPackValidator.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; -using System.Globalization; using System.Text; using Inno.Build.Toolchains; @@ -28,16 +28,23 @@ public void Validate(string directory) string linker = Path.Combine(directory, "PlayerLink"); foreach (string input in new[] { - "Player.csproj", "Program.cs", "BrowserWasm32PlayerComposition.cs", "HttpPlayerContentSource.cs", "BrowserWasm32Bridge.cs", "global.json", + "Player.csproj", + "Program.cs", + "BrowserWasm32PlayerComposition.cs", + "HttpPlayerContentSource.cs", + "BrowserWasm32Bridge.cs", + "global.json", Path.Combine("Analyzers", "Inno.Runtime.Generators.dll"), Path.Combine("Analyzers", "Inno.Core.Serialization.Generators.dll"), - Path.Combine("wwwroot", "index.html"), Path.Combine("wwwroot", "main.js"), + Path.Combine("wwwroot", "index.html"), + Path.Combine("wwwroot", "main.js"), Path.Combine("Native", "wasm_sjlj_shim.c"), Path.Combine("References", "Inno.Player.Runtime.dll") - }) - { + }) { if (!File.Exists(Path.Combine(linker, input))) + { throw new InvalidDataException($"The browser Support Pack lacks linker input '{input}'."); + } } string nativeDirectory = Path.Combine(linker, "Native"); string[] foreignBinaries = Directory.EnumerateFiles(nativeDirectory, "*", SearchOption.AllDirectories) @@ -46,9 +53,15 @@ public void Validate(string directory) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); if (foreignBinaries.Length != 0) - throw new InvalidDataException($"The browser Support Pack contains a foreign native binary '{Path.GetFileName(foreignBinaries[0])}'."); + { + throw new InvalidDataException( + $"The browser Support Pack contains a foreign native binary '{Path.GetFileName(foreignBinaries[0])}'." + ); + } foreach (string archive in Directory.EnumerateFiles(nativeDirectory, "*.a", SearchOption.AllDirectories)) + { ValidateArchive(archive); + } } private static void ValidateArchive(string file) @@ -56,24 +69,36 @@ private static void ValidateArchive(string file) using FileStream input = File.OpenRead(file); Span magic = stackalloc byte[8]; if (input.Length < magic.Length) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' has no archive header."); + } input.ReadExactly(magic); if (!magic.SequenceEqual("!\n"u8)) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' is not an owned object archive."); + } Span header = stackalloc byte[60]; Span objectHeader = stackalloc byte[8]; bool containsObject = false; while (input.Position < input.Length) { if (input.Length - input.Position < header.Length) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' has a truncated member header."); + } input.ReadExactly(header); string name = Encoding.ASCII.GetString(header[..16]).TrimEnd(); if (!header[58..].SequenceEqual("`\n"u8) - || !long.TryParse(Encoding.ASCII.GetString(header.Slice(48, 10)).Trim(), - NumberStyles.None, CultureInfo.InvariantCulture, out long length) - || length < 0 || length > input.Length - input.Position) + || !long.TryParse( + Encoding.ASCII.GetString(header.Slice(48, 10)).Trim(), + NumberStyles.None, + CultureInfo.InvariantCulture, + out long length + ) + || length < 0 || length > input.Length - input.Position + ) { throw new InvalidDataException($"BrowserWasm32 archive '{file}' has an invalid member size."); + } long end = input.Position + length; bool metadata = name is "/" or "//" or "/SYM64/" || name.StartsWith("__.SYMDEF", StringComparison.Ordinal); if (!metadata) @@ -81,22 +106,32 @@ private static void ValidateArchive(string file) if (name.StartsWith("#1/", StringComparison.Ordinal)) { if (!int.TryParse(name[3..], NumberStyles.None, CultureInfo.InvariantCulture, out int prefix) - || prefix < 0 || prefix > length - objectHeader.Length) + || prefix < 0 || prefix > length - objectHeader.Length + ) { throw new InvalidDataException($"BrowserWasm32 archive '{file}' has an invalid member name."); + } input.Position += prefix; } if (end - input.Position < objectHeader.Length) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' contains a truncated object."); + } input.ReadExactly(objectHeader); if (!objectHeader.SequenceEqual("\0asm\u0001\0\0\0"u8)) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' contains a foreign object ABI."); + } containsObject = true; } input.Position = end + (length & 1); if (input.Position > input.Length) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' lacks member alignment padding."); + } } if (!containsObject) + { throw new InvalidDataException($"BrowserWasm32 archive '{file}' contains no Wasm objects."); + } } } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs index a930e7b1d..85b489ead 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs @@ -13,7 +13,6 @@ public sealed class BrowserWasm32GameBuildTarget : IGameBuildTarget { private readonly IPlayerSupportPackValidator m_supportPackValidator; - /// /// Creates a site packager bound to the selected native closure validator. /// @@ -56,8 +55,6 @@ public BrowserWasm32GameBuildTarget(IPlayerSupportPackValidator supportPackValid /// public string displayName => "Web (WebGL 2)"; - - /// /// Composes an independently hostable site from a verified browser Support Pack and content pack. /// @@ -79,14 +76,19 @@ public async ValueTask PackageAsync( await CopyDirectoryAsync( Path.Combine(context.managedDeployment.outputDirectory, "wwwroot"), site, - cancellationToken); + cancellationToken + ); if (!File.Exists(Path.Combine(site, "index.html"))) + { throw new InvalidDataException("The browser Support Pack has no index.html entry point."); + } string contentDirectory = Path.Combine(site, "Content"); await CopyDirectoryAsync(context.contentDirectory, contentDirectory, cancellationToken); string[] packs = Directory.GetFiles(contentDirectory, "content-*.pack", SearchOption.TopDirectoryOnly); if (packs.Length != 1) + { throw new InvalidDataException("The browser deployment must contain exactly one content pack."); + } return site; } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs index 963793496..78383d725 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs @@ -40,14 +40,28 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(host); cancellationToken.ThrowIfCancellationRequested(); if (targetId != BrowserWasm32BuildModule.target.id.value || host.system is not ("Windows" or "MacOS")) + { throw new PlatformNotSupportedException($"Emscripten cannot build '{targetId}' on {host.system}/{host.architecture}."); - string project = Path.Combine(context.engineRoot, "platforms", "BrowserWasm32", "build", - "Inno.Build.BrowserWasm32", "Templates", "BrowserWasm32Player.project.xml"); + } + string project = Path.Combine( + context.engineRoot, + "platforms", + "BrowserWasm32", + "build", + "Inno.Build.BrowserWasm32", + "Templates", + "BrowserWasm32Player.project.xml" + ); IReadOnlyDictionary sdk = await EmscriptenToolchainResolver.ResolveAsync( - m_dotnetHost, project, cancellationToken).ConfigureAwait(false); + m_dotnetHost, + project, + cancellationToken + ).ConfigureAwait(false); Dictionary environment = NativeToolchainPreparation.CreateEnvironment(); foreach ((string name, string value) in sdk) + { environment[name] = value; + } var tools = new Dictionary(StringComparer.Ordinal) { ["clang"] = Path.Combine(sdk["DOTNET_EMSCRIPTEN_LLVM_ROOT"], "clang" + host.services.executableExtension), @@ -59,13 +73,25 @@ CancellationToken cancellationToken ["node"] = sdk["EMSDK_NODE"] }; string toolchain = Path.Combine(sdk["EMSCRIPTEN"], "cmake", "Modules", "Platform", "Emscripten.cmake"); - return NativeToolchainPreparation.Freeze(targetId, host, tools, environment, - [Path.GetDirectoryName(sdk["EMSCRIPTEN"])!, + return NativeToolchainPreparation.Freeze( + targetId, + host, + tools, + environment, + [ + Path.GetDirectoryName(sdk["EMSCRIPTEN"])!, Path.Combine(Path.GetDirectoryName(sdk["EMSCRIPTEN"])!, "bin"), Path.GetDirectoryName(sdk["EMSDK_PYTHON"])!, - Path.Combine(sdk["EM_CACHE"], "sysroot", "include")], + Path.Combine(sdk["EM_CACHE"], "sysroot", "include") + ], ["-G", "Ninja", "-DCMAKE_MAKE_PROGRAM=" + tools["ninja"], "-DCMAKE_TOOLCHAIN_FILE=" + toolchain], - BrowserWasm32LinkerSettings.Create(), multiConfiguration: false, compilerInputs: new NativeCompilerInputs( - tools["clang"], tools["clang++"], Path.Combine(sdk["EM_CACHE"], "sysroot"))); + BrowserWasm32LinkerSettings.Create(), + multiConfiguration: false, + compilerInputs: new NativeCompilerInputs( + tools["clang"], + tools["clang++"], + Path.Combine(sdk["EM_CACHE"], "sysroot") + ) + ); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx.Runtime/BrowserWasm32BgfxSurfaceIntegration.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx.Runtime/BrowserWasm32BgfxSurfaceIntegration.cs index 1ca710ec3..e6b172338 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx.Runtime/BrowserWasm32BgfxSurfaceIntegration.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx.Runtime/BrowserWasm32BgfxSurfaceIntegration.cs @@ -37,12 +37,17 @@ public BgfxSurfaceDescriptor Resolve( BgfxSurfaceRole role ) { if (role != BgfxSurfaceRole.Primary && role != BgfxSurfaceRole.Additional) + { throw new ArgumentOutOfRangeException(nameof(role)); + } if (role == BgfxSurfaceRole.Additional) + { throw new NotSupportedException("The browser canvas host does not support additional BGFX windows."); + } if (handles.handleKind != PlatformNativeHandleId.browserCanvas) + { throw new NotSupportedException("The Browser BGFX integration requires its explicit browserCanvas surface ABI."); - return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, - supportsSrgbReset: false); + } + return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, supportsSrgbReset: false); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs index 95b884d7a..e834a5595 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs @@ -17,10 +17,13 @@ public static class BrowserWasm32BgfxIntegration /// public static NativeComponentBuildOptions nativeOptions { get; } = new( NativeLibraryKind.Static, - ["-DINNO_BGFX_RENDERER_DEFINITIONS=BGFX_CONFIG_RENDERER_OPENGLES=30", + [ + "-DINNO_BGFX_RENDERER_DEFINITIONS=BGFX_CONFIG_RENDERER_OPENGLES=30", "-DINNO_BGFX_SDK_DEFINITIONS=__EMSCRIPTEN_MAJOR__=__EMSCRIPTEN_major__;__EMSCRIPTEN_MINOR__=__EMSCRIPTEN_minor__;__EMSCRIPTEN_TINY__=__EMSCRIPTEN_tiny__", - "-DINNO_BGFX_SDK_OPTIONS=-include;emscripten/version.h"], - ["platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs"]); + "-DINNO_BGFX_SDK_OPTIONS=-include;emscripten/version.h" + ], + ["platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxIntegration.cs"] + ); /// /// Gets the explicit shader configuration used by this integration. diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs index 8fad73629..cedc25214 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs @@ -1,8 +1,7 @@ +using Inno.Build.BrowserWasm32; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering; -using Inno.Build.BrowserWasm32; - namespace Inno.Integration.BrowserWasm32.Bgfx; /// @@ -13,19 +12,38 @@ public static class BrowserWasm32BgfxShaderProfiles /// /// Gets the immutable configuration shared by this platform's products and publication module. /// - public static BgfxShaderTargetProfile target { get; } = new(BrowserWasm32BuildModule.target.id.value, - [ - new(CreateCapabilities(), "asm.js", "300_es", "300_es", "") - ]); + public static BgfxShaderTargetProfile target { get; } = new( + BrowserWasm32BuildModule.target.id.value, + [ + new(CreateCapabilities(), "asm.js", "300_es", "300_es", "") + ] + ); private static GraphicsCapabilities CreateCapabilities() { - RenderTextureFormat[] color = [RenderTextureFormat.R8, RenderTextureFormat.RG8, - RenderTextureFormat.RGBA8, RenderTextureFormat.RGBA8Srgb, RenderTextureFormat.RGB10A2]; + RenderTextureFormat[] color = + [ + RenderTextureFormat.R8, + RenderTextureFormat.RG8, + RenderTextureFormat.RGBA8, + RenderTextureFormat.RGBA8Srgb, + RenderTextureFormat.RGB10A2 + ]; RenderTextureFormat[] sampled = [.. color, RenderTextureFormat.Depth24Stencil8]; - return new(GraphicsApi.OpenGLES, GraphicsCapability.Index32 | GraphicsCapability.Instancing + return new( + GraphicsApi.OpenGLES, + GraphicsCapability.Index32 | GraphicsCapability.Instancing | GraphicsCapability.Texture2DArray | GraphicsCapability.Texture3D | GraphicsCapability.FragmentDepth, - new GraphicsLimits(256, 4, 2048, 0), sampled, sampled, [], [], true, true, - color, color, sampled); + new GraphicsLimits(256, 4, 2048, 0), + sampled, + sampled, + [], + [], + true, + true, + color, + color, + sampled + ); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs index 94f6acc7c..4c4ed43da 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs @@ -9,11 +9,13 @@ namespace Inno.Integration.BrowserWasm32.Build; internal static class BrowserWasm32BindingProfile { - internal static NativeBindingProfile Create() => new( - BrowserWasm32BuildModule.target.id.value, - new TargetConfiguration { id = "emscripten-wasm32-emscripten" }, - new ManagedRuntimeId("dotnet.mono-wasm"), - ["platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs"], - static builder => builder.AddPlugin(), - BindingImportMode.LibraryImport); + internal static NativeBindingProfile Create() + => new( + BrowserWasm32BuildModule.target.id.value, + new TargetConfiguration { id = "emscripten-wasm32-emscripten" }, + new ManagedRuntimeId("dotnet.mono-wasm"), + ["platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Bindings/BrowserWasm32BindingProfile.cs"], + static builder => builder.AddPlugin(), + BindingImportMode.LibraryImport + ); } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/BrowserWasm32BuildIntegration.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/BrowserWasm32BuildIntegration.cs index 4463db1a3..66a630be4 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/BrowserWasm32BuildIntegration.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/BrowserWasm32BuildIntegration.cs @@ -27,11 +27,20 @@ public static BuildPlatformContribution Create(BuildCompositionContext context) { ArgumentNullException.ThrowIfNull(context); var generator = new NativeBindingGenerator(BrowserWasm32BindingProfile.Create()); - ProductNativeBuildPlan player = StandardNativeComponents.CreateStaticPlayer(BrowserWasm32NativeProducts.Options, BrowserWasm32NativeLayout.Map); + ProductNativeBuildPlan player = StandardNativeComponents.CreateStaticPlayer( + BrowserWasm32NativeProducts.Options, + BrowserWasm32NativeLayout.Map + ); var validator = new PlayerSupportPackClosureValidator( StandardSupportPackRequirements.CreateStatic(player, BrowserWasm32BuildModule.target.id, BrowserWasm32LinkerSettings.Create()), - new BrowserWasm32SupportPackValidator(), null); - return BrowserWasm32BuildModule.CreateContribution(context, - new NativeProductContribution(player, new BrowserWasm32NativeProductExecutor()), validator, generator); + new BrowserWasm32SupportPackValidator(), + null + ); + return BrowserWasm32BuildModule.CreateContribution( + context, + new NativeProductContribution(player, new BrowserWasm32NativeProductExecutor()), + validator, + generator + ); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Deployment/BrowserWasm32NativeLayout.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Deployment/BrowserWasm32NativeLayout.cs index fe77a8ce8..6e83c36ff 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Deployment/BrowserWasm32NativeLayout.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Deployment/BrowserWasm32NativeLayout.cs @@ -11,10 +11,15 @@ internal static class BrowserWasm32NativeLayout string target ) { if (relative.Split(Path.DirectorySeparatorChar)[0] == "Link") + { return null; + } if (component == "bgfx-tools") + { return relative.StartsWith("includes" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? Path.Combine("bgfx", relative) : Path.Combine("bgfx", target, "tools", relative); + ? Path.Combine("bgfx", relative) + : Path.Combine("bgfx", target, "tools", relative); + } return Path.Combine(component, target, relative); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Products/BrowserWasm32NativeProducts.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Products/BrowserWasm32NativeProducts.cs index 955fca50f..c1877179e 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Products/BrowserWasm32NativeProducts.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Build/Products/BrowserWasm32NativeProducts.cs @@ -12,7 +12,8 @@ internal static class BrowserWasm32NativeProducts internal static NativeComponentBuildOptions Options(string component) { NativeComponentBuildOptions graphics = BrowserWasm32BgfxIntegration.nativeOptions; - return new(NativeLibraryKind.Static, + return new( + NativeLibraryKind.Static, component == "bgfx" ? graphics.cmakeArguments : [], [C_INPUT, ..(component == "bgfx" ? graphics.inputPaths : [])], bindingLibraryName: component switch @@ -23,6 +24,7 @@ internal static NativeComponentBuildOptions Options(string component) "text" => "libinno-text", "ui" => "libinno-ui", _ => throw new ArgumentException("This component is outside the Browser product closure.", nameof(component)) - }); + } + ); } } diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs index 13b6eadbb..18fc215d5 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs @@ -15,9 +15,7 @@ public sealed class BrowserWasm32Sdl3HostIntegration : ISdl3HostIntegration public Sdl3HostCapabilities capabilities { get; } = new(multipleWindows: false, liveResize: false); /// - public void ConfigureInitialization() - { - } + public void ConfigureInitialization() {} /// public nint CreateWindow(PlatformWindowOptions options) @@ -29,14 +27,18 @@ public nint CreateWindow(PlatformWindowOptions options) public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) { if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } uint properties = SDL.Raw.GetWindowProperties((SDLWindow*)windowHandle); ReadOnlySpan propertyName = "SDL.window.emscripten.canvas_id\0"u8; fixed (byte* name = propertyName) { nint selector = (nint)SDL.Raw.GetStringProperty(properties, (sbyte*)name, null); if (selector == 0) + { throw new InvalidOperationException("SDL did not provide a browser canvas selector."); + } return new PlatformNativeHandles(selector, handleKind: PlatformNativeHandleId.browserCanvas); } } @@ -45,7 +47,9 @@ public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) public bool GetInitialFocus(nint windowHandle) { if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } return false; } } diff --git a/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/BrowserWasm32PlayerComposition.cs b/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/BrowserWasm32PlayerComposition.cs index 52829b446..483fdfec1 100644 --- a/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/BrowserWasm32PlayerComposition.cs +++ b/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/BrowserWasm32PlayerComposition.cs @@ -1,18 +1,18 @@ -using Inno.Adapter.Rendering; -using Inno.Adapter.Rendering.Bgfx; -using Inno.Integration.BrowserWasm32.Bgfx.Runtime; -using Inno.Adapter.Platform; -using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.BrowserWasm32.Sdl3; using System; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using System.Net.Http; using Inno.Adapter; using Inno.Adapter.Default; +using Inno.Adapter.Platform; +using Inno.Adapter.Platform.Sdl3; +using Inno.Adapter.Rendering; +using Inno.Adapter.Rendering.Bgfx; using Inno.Adapter.Storage; using Inno.Adapter.Storage.BrowserWasm32; using Inno.Core.Logging; +using Inno.Integration.BrowserWasm32.Bgfx.Runtime; +using Inno.Integration.BrowserWasm32.Sdl3; using Inno.Player.Runtime; using Inno.Runtime; using Inno.Shell; @@ -50,8 +50,10 @@ internal static async Task RunAsync(string[] arguments) }), adapterSelection = StandardAdapterSelection.Create(StorageBackendId.browser), contentSource = new HttpPlayerContentSource(client), - createStorage = manifest => storage.CreateStorage(StorageBackendId.browser, - new StorageScope(manifest.applicationId)), + createStorage = manifest => storage.CreateStorage( + StorageBackendId.browser, + new StorageScope(manifest.applicationId) + ), moduleActivator = Generated.PlayerMetadataComposition.CreateActivator(), frameDriver = new ScheduledShellFrameDriver(NextFrameAsync), graphicsApi = command.graphicsApi, diff --git a/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/HttpPlayerContentSource.cs b/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/HttpPlayerContentSource.cs index d8c160f2b..0e110c2fd 100644 --- a/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/HttpPlayerContentSource.cs +++ b/platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/HttpPlayerContentSource.cs @@ -38,8 +38,10 @@ public async ValueTask ReadMetadataAsync(CancellationToke { using MemoryStream manifest = await DownloadAsync("runtime.manifest", C_METADATA_LIMIT, cancellationToken); using MemoryStream catalog = await DownloadAsync("catalog.inno", C_METADATA_LIMIT, cancellationToken); - return new PlayerContentMetadata(manifest.GetBuffer().AsSpan(0, checked((int)manifest.Length)), - catalog.GetBuffer().AsSpan(0, checked((int)catalog.Length))); + return new PlayerContentMetadata( + manifest.GetBuffer().AsSpan(0, checked((int)manifest.Length)), + catalog.GetBuffer().AsSpan(0, checked((int)catalog.Length)) + ); } /// @@ -74,7 +76,9 @@ public async ValueTask PrepareAsync( ) { ArgumentNullException.ThrowIfNull(pack); if (!scope.isValid) + { throw new ArgumentException("Content preparation requires an application namespace.", nameof(scope)); + } MemoryStream stream = await DownloadAsync(pack.fileName, m_limits.packBytes, cancellationToken); return ContentPackReader.Open(stream, pack, serialization, m_limits, cancellationToken); } @@ -84,12 +88,17 @@ private async Task DownloadAsync( long budget, CancellationToken cancellationToken ) { - using HttpResponseMessage response = await m_client.GetAsync("Content/" + fileName, - HttpCompletionOption.ResponseHeadersRead, cancellationToken); + using HttpResponseMessage response = await m_client.GetAsync( + "Content/" + fileName, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken + ); response.EnsureSuccessStatusCode(); long? length = response.Content.Headers.ContentLength; if (length is < 0 || length > budget) + { throw new InvalidDataException($"Deployment content '{fileName}' exceeds its download budget."); + } var output = new MemoryStream(); byte[] buffer = ArrayPool.Shared.Rent(64 * 1024); try @@ -99,11 +108,15 @@ CancellationToken cancellationToken while ((count = await input.ReadAsync(buffer, cancellationToken)) != 0) { if (output.Length + count > budget) + { throw new InvalidDataException($"Deployment content '{fileName}' exceeds its download budget."); + } await output.WriteAsync(buffer.AsMemory(0, count), cancellationToken); } if (length is not null && output.Length != length) + { throw new InvalidDataException($"Deployment content '{fileName}' has a truncated HTTP body."); + } cancellationToken.ThrowIfCancellationRequested(); output.Position = 0; return output; diff --git a/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32ApplicationStorage.cs b/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32ApplicationStorage.cs index a039bc324..2326dcb42 100644 --- a/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32ApplicationStorage.cs +++ b/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32ApplicationStorage.cs @@ -27,7 +27,9 @@ public sealed partial class BrowserWasm32ApplicationStorage : IApplicationStorag public BrowserWasm32ApplicationStorage(StorageScope scope) { if (!scope.isValid) + { throw new ArgumentException("Browser storage requires an assigned namespace.", nameof(scope)); + } m_prefix = scope.value + ":"; } @@ -116,7 +118,9 @@ public ValueTask DeleteAsync( cancellationToken.ThrowIfCancellationRequested(); string storageKey = Resolve(key); if (GetItem(storageKey) is null) + { return ValueTask.FromResult(false); + } RemoveItem(storageKey); return ValueTask.FromResult(true); } @@ -143,24 +147,29 @@ public ValueTask> ListAsync( { string? browserKey = GetKeyAt(index); if (browserKey is null || !browserKey.StartsWith(m_prefix, StringComparison.Ordinal)) + { continue; + } var key = new StorageKey(browserKey[m_prefix.Length..]); if (prefix is { } requested && key != requested - && !key.value.StartsWith(requested.value + "/", StringComparison.Ordinal)) - { + && !key.value.StartsWith(requested.value + "/", StringComparison.Ordinal) + ) { continue; } keys.Add(key); } return ValueTask.FromResult>( - keys.OrderBy(static key => key.value, StringComparer.Ordinal).ToArray()); + keys.OrderBy(static key => key.value, StringComparer.Ordinal).ToArray() + ); } private string Resolve(StorageKey key) { if (!key.isValid) + { throw new ArgumentException("A valid storage key is required.", nameof(key)); + } return m_prefix + key.value; } diff --git a/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs b/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs index a5a031bd1..f90c110ad 100644 --- a/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs +++ b/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs @@ -11,7 +11,8 @@ public sealed class BrowserWasm32StorageBackendProvider : StorageBackendProvider /// /// Creates an explicitly composed registration for the bundled implementation. /// - public BrowserWasm32StorageBackendProvider() : base(StorageBackendId.browser) { } + public BrowserWasm32StorageBackendProvider() + : base(StorageBackendId.browser) {} /// public override IApplicationStorage CreateStorage(StorageScope scope) @@ -19,4 +20,3 @@ public override IApplicationStorage CreateStorage(StorageScope scope) return new BrowserWasm32ApplicationStorage(scope); } } - diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs index fb27c34c6..ea70703e7 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs @@ -10,8 +10,16 @@ namespace Inno.Build.MacOSArm64; public sealed class MacOSArm64BuildHostProvider : IBuildHostProvider { /// - public BuildHostDescriptor? TryCapture() => !OperatingSystem.IsMacOS() - || RuntimeInformation.ProcessArchitecture != Architecture.Arm64 ? null - : new("MacOS", "arm64", new BuildHostServices(new PhysicalToolchainWorkspaceProvider(), - inputPaths: ["platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs"])); + public BuildHostDescriptor? TryCapture() + => !OperatingSystem.IsMacOS() + || RuntimeInformation.ProcessArchitecture != Architecture.Arm64 + ? null + : new( + "MacOS", + "arm64", + new BuildHostServices( + new PhysicalToolchainWorkspaceProvider(), + inputPaths: ["platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs"] + ) + ); } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/MacOSArm64BuildModule.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/MacOSArm64BuildModule.cs index b7745ff09..61e2a7e0e 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/MacOSArm64BuildModule.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/MacOSArm64BuildModule.cs @@ -14,7 +14,13 @@ public static class MacOSArm64BuildModule /// Gets the explicit implemented product target, independent of the tool execution host. /// public static PlatformTargetDescriptor target { get; } = new( - new BuildTargetId("macos-arm64"), "MacOS", "arm64", "darwin-arm64", "osx-arm64", true); + new BuildTargetId("macos-arm64"), + "MacOS", + "arm64", + "darwin-arm64", + "osx-arm64", + true + ); /// /// Contributes the platform's target, product inputs and SDK resolver as one registration. @@ -51,11 +57,15 @@ INativeBindingGenerator bindingGenerator ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(nativePlan); ArgumentNullException.ThrowIfNull(editorNativePlan); - return new(target, + return new( + target, () => new MacOSArm64GameBuildTarget(supportPackValidator), - new MacOSArm64PlayerSupportPackSource(nativePlan, context.host, context.dotnetHost, bindingGenerator, supportPackValidator), new MacOSArm64NativeToolchainProvider(context.dotnetHost), + new MacOSArm64PlayerSupportPackSource(nativePlan, context.host, context.dotnetHost, bindingGenerator, supportPackValidator), + new MacOSArm64NativeToolchainProvider(context.dotnetHost), "platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/Inno.Editor.MacOSArm64.csproj", - [nativePlan, editorNativePlan, shaderToolsPlan], bindingGenerator, - [ManagedDeploymentId.coreClr, ManagedDeploymentId.nativeAot]); + [nativePlan, editorNativePlan, shaderToolsPlan], + bindingGenerator, + [ManagedDeploymentId.coreClr, ManagedDeploymentId.nativeAot] + ); } } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Native/MacOSArm64LinkerSettings.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Native/MacOSArm64LinkerSettings.cs index 002df7f5d..98483a8ef 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Native/MacOSArm64LinkerSettings.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Native/MacOSArm64LinkerSettings.cs @@ -18,5 +18,14 @@ public static class MacOSArm64LinkerSettings /// The immutable target linker plan. /// public static NativeLinkPlan Create(IEnumerable? runtimeSearchPaths = null) - => new(".dylib", null, ".a", ["-DCMAKE_BUILD_WITH_INSTALL_NAME_DIR=ON", "-DCMAKE_INSTALL_NAME_DIR=@rpath", "-DCMAKE_BUILD_RPATH=" + string.Join(';', runtimeSearchPaths ?? [])]); + => new( + ".dylib", + null, + ".a", + [ + "-DCMAKE_BUILD_WITH_INSTALL_NAME_DIR=ON", + "-DCMAKE_INSTALL_NAME_DIR=@rpath", + "-DCMAKE_BUILD_RPATH=" + string.Join(';', runtimeSearchPaths ?? []) + ] + ); } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs index 80a58a76d..b077025c6 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs @@ -39,13 +39,21 @@ public MacOSArm64PlayerSupportPackSource( IPlayerSupportPackValidator supportPackValidator ) { m_preparation = new FilePlayerSupportPackPreparation( - Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, "osx-arm64", Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id.value, ".dylib", + Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, + "osx-arm64", + Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id.value, + ".dylib", supportPackValidator, "platforms/MacOSArm64/player/Inno.Player.MacOSArm64/Inno.Player.MacOSArm64.csproj", "platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Templates/MacOSArm64Player.project.xml", - nativePlan.plan, nativePlan.executor, new MacOSArm64NativeToolchainProvider(dotnetHost), host, bindingGenerator, + nativePlan.plan, + nativePlan.executor, + new MacOSArm64NativeToolchainProvider(dotnetHost), + host, + bindingGenerator, ["platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs", - "platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs"]); + "platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs"] + ); } /// diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs index 0507b14ab..c57926231 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs @@ -29,30 +29,44 @@ public void Validate(string directory) if (foreignNativeExtensions.Contains(Path.GetExtension(file), StringComparer.OrdinalIgnoreCase)) { throw new InvalidDataException( - $"Player Support Pack '{Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'."); + $"Player Support Pack '{Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'." + ); } if (Path.GetExtension(file).Equals(".dylib", StringComparison.OrdinalIgnoreCase)) + { ValidateLibrary(file); + } } foreach (string input in new[] { - "Player.csproj", "Program.cs", "MacOSArm64PlayerComposition.cs", "MacOSArm64PlayerContentSource.cs", "global.json", + "Player.csproj", + "Program.cs", + "MacOSArm64PlayerComposition.cs", + "MacOSArm64PlayerContentSource.cs", + "global.json", Path.Combine("Analyzers", "Inno.Runtime.Generators.dll"), Path.Combine("Analyzers", "Inno.Core.Serialization.Generators.dll"), Path.Combine("References", "Inno.Player.Runtime.dll") - }) + }) { if (!File.Exists(Path.Combine(directory, "PlayerLink", input))) + { throw new InvalidDataException($"The MacOS Support Pack lacks publication input '{input}'."); + } + } } private static void ValidateLibrary(string file) { using var input = new BinaryReader(File.OpenRead(file)); if (input.BaseStream.Length < 32 || input.ReadUInt32() != 0xfeedfacf - || input.ReadUInt32() != 0x0100000c) + || input.ReadUInt32() != 0x0100000c + ) { throw new InvalidDataException($"MacOSArm64 native library '{file}' does not target the Mach-O ARM64 ABI."); + } _ = input.ReadUInt32(); if (input.ReadUInt32() != 6) + { throw new InvalidDataException($"MacOSArm64 native library '{file}' is not a dynamic library."); + } } } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs index c405a1a7d..784006065 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs @@ -28,7 +28,6 @@ public MacOSArm64GameBuildTarget(IPlayerSupportPackValidator supportPackValidato m_supportPackValidator = supportPackValidator ?? throw new ArgumentNullException(nameof(supportPackValidator)); } - /// /// Validates the target closure before runtime script compilation. /// @@ -56,8 +55,6 @@ public MacOSArm64GameBuildTarget(IPlayerSupportPackValidator supportPackValidato /// public string displayName => "macOS (Apple silicon)"; - - /// /// Composes a macOS application bundle in isolated staging. /// @@ -79,20 +76,31 @@ public async ValueTask PackageAsync( string contents = Path.Combine(application, "Contents"); string executableRoot = Path.Combine(contents, "MacOS"); string resources = Path.Combine(contents, "Resources"); - await CopyDirectoryAsync(context.managedDeployment.outputDirectory, executableRoot, cancellationToken, - excludeCompilerReferences: true) + await CopyDirectoryAsync( + context.managedDeployment.outputDirectory, + executableRoot, + cancellationToken, + excludeCompilerReferences: true + ) .ConfigureAwait(false); string player = Path.Combine(executableRoot, "Inno.Player.MacOSArm64"); if (!File.Exists(player)) + { throw new InvalidDataException("The macOS managed publication does not contain Inno.Player.MacOSArm64."); + } File.Move(player, Path.Combine(executableRoot, context.profile.productName)); - await CopyDirectoryAsync(context.contentDirectory, Path.Combine(resources, "Content"), cancellationToken, - excludeCompilerReferences: false) + await CopyDirectoryAsync( + context.contentDirectory, + Path.Combine(resources, "Content"), + cancellationToken, + excludeCompilerReferences: false + ) .ConfigureAwait(false); Directory.CreateDirectory(contents); string product = SecurityElement.Escape(context.profile.productName) ?? context.profile.productName; string identifier = SecurityElement.Escape(context.profile.applicationId) ?? context.profile.applicationId; - await File.WriteAllTextAsync( + await File + .WriteAllTextAsync( Path.Combine(contents, "Info.plist"), $""" @@ -105,7 +113,8 @@ await File.WriteAllTextAsync( NSHighResolutionCapable """, - cancellationToken) + cancellationToken + ) .ConfigureAwait(false); return application; } @@ -122,7 +131,9 @@ bool excludeCompilerReferences cancellationToken.ThrowIfCancellationRequested(); string relativePath = Path.GetRelativePath(source, directory); if (excludeCompilerReferences && IsCompilerReferencePath(relativePath)) + { continue; + } Directory.CreateDirectory(Path.Combine(destination, relativePath)); } foreach (string file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) @@ -130,14 +141,18 @@ bool excludeCompilerReferences cancellationToken.ThrowIfCancellationRequested(); string relativePath = Path.GetRelativePath(source, file); if (excludeCompilerReferences && IsCompilerReferencePath(relativePath)) + { continue; + } string target = Path.Combine(destination, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(target)!); await using FileStream input = new(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, true); await using FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131072, true); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); if (!OperatingSystem.IsWindows()) + { File.SetUnixFileMode(target, File.GetUnixFileMode(file)); + } } } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs index 0ec82acff..9ca7b72cb 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs @@ -41,25 +41,51 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(host); cancellationToken.ThrowIfCancellationRequested(); if (!(host.system == "MacOS" && host.architecture == "arm64" && targetId == "macos-arm64")) + { throw new PlatformNotSupportedException($"The MacOS SDK cannot build '{targetId}' on {host.system}/{host.architecture}."); - var tools = new Dictionary(StringComparer.Ordinal) { ["dotnet"] = ToolchainEnvironment.ResolveExecutable(m_dotnetHost) }; + } + var tools = new Dictionary(StringComparer.Ordinal) + { + ["dotnet"] = ToolchainEnvironment.ResolveExecutable(m_dotnetHost) + }; Dictionary environment = NativeToolchainPreparation.CreateEnvironment(); var inputs = new List(); var cmakeArguments = new List(); string xcrun = ToolchainEnvironment.ResolveExecutable("xcrun"); - tools["clang"] = (await ToolchainEnvironment.CaptureOutputAsync(xcrun, - ["--find", "clang"], context.engineRoot, cancellationToken).ConfigureAwait(false)).Trim(); - tools["clang++"] = (await ToolchainEnvironment.CaptureOutputAsync(xcrun, - ["--find", "clang++"], context.engineRoot, cancellationToken).ConfigureAwait(false)).Trim(); - string sdk = (await ToolchainEnvironment.CaptureOutputAsync(xcrun, - ["--sdk", "macosx", "--show-sdk-path"], context.engineRoot, cancellationToken).ConfigureAwait(false)).Trim(); + tools["clang"] = (await ToolchainEnvironment.CaptureOutputAsync( + xcrun, + ["--find", "clang"], + context.engineRoot, + cancellationToken + ).ConfigureAwait(false)).Trim(); + tools["clang++"] = (await ToolchainEnvironment.CaptureOutputAsync( + xcrun, + ["--find", "clang++"], + context.engineRoot, + cancellationToken + ).ConfigureAwait(false)).Trim(); + string sdk = (await ToolchainEnvironment.CaptureOutputAsync( + xcrun, + ["--sdk", "macosx", "--show-sdk-path"], + context.engineRoot, + cancellationToken + ).ConfigureAwait(false)).Trim(); environment["SDKROOT"] = sdk; inputs.AddRange([xcrun, Path.Combine(sdk, "usr", "include"), Path.Combine(sdk, "usr", "lib")]); cmakeArguments.AddRange(["-DCMAKE_OSX_SYSROOT=" + sdk, "-DCMAKE_OSX_ARCHITECTURES=arm64"]); ConfigureTools(tools, environment, cmakeArguments); - return NativeToolchainPreparation.Freeze(targetId, host, tools, environment, inputs, - cmakeArguments, MacOSArm64LinkerSettings.Create(), false, new NativeCompilerInputs(tools["clang"], tools["clang++"], sdk)); + return NativeToolchainPreparation.Freeze( + targetId, + host, + tools, + environment, + inputs, + cmakeArguments, + MacOSArm64LinkerSettings.Create(), + false, + new NativeCompilerInputs(tools["clang"], tools["clang++"], sdk) + ); } private static void ConfigureTools( @@ -71,7 +97,9 @@ List cmakeArguments tools["cmake"] = ToolchainEnvironment.ResolveExecutable("cmake"); environment["CC"] = tools["clang"]; environment["CXX"] = tools["clang++"]; - cmakeArguments.AddRange(["-DCMAKE_C_COMPILER=" + environment["CC"], - "-DCMAKE_CXX_COMPILER=" + environment["CXX"]]); + cmakeArguments.AddRange([ + "-DCMAKE_C_COMPILER=" + environment["CC"], + "-DCMAKE_CXX_COMPILER=" + environment["CXX"] + ]); } } diff --git a/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs b/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs index 10adacf6e..9d032d7e2 100644 --- a/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs +++ b/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs @@ -64,22 +64,30 @@ CancellationToken cancellationToken using var picker = new Sdl3PlatformApplication(new MacOSArm64Sdl3HostIntegration()); string? selected = Sdl3FolderDialog.SelectFolder(picker); if (selected is null) + { return 0; + } arguments = [selected]; } EditorCommandLineOptions command = EditorCommandLineOptions.Parse(arguments); _ = MacOSArm64ApplicationLocations.userDataRoot; string project = Path.GetFullPath(command.projectDirectory); string persistentRoot = Path.Combine(project, "Library", "PersistentData"); - var adapters = new DefaultAuthoringAdapterCatalog(new DefaultAdapterCatalogOptions - { - platform = new PlatformBackendCatalog([new Sdl3PlatformBackendProvider(new MacOSArm64Sdl3HostIntegration())]), - rendering = new RenderingBackendCatalog([new BgfxRenderingBackendProvider(new MacOSArm64BgfxSurfaceIntegration())]), - storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(persistentRoot)]) - }, [new BgfxAuthoringProvider(MacOSArm64BgfxIntegration.shaderProfile)], - [new ImGuiPresentationProvider(new ImGuiInteractionOptions(commandKeyBehavior: true, horizontalWheelDirection: -1))]); - var buildContext = StandardBuildEnvironment.Capture(Path.GetDirectoryName(typeof(MacOSArm64EditorComposition).Assembly.Location)!, - Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, nativeDependencies: command.nativeDependencies); + var adapters = new DefaultAuthoringAdapterCatalog( + new DefaultAdapterCatalogOptions + { + platform = new PlatformBackendCatalog([new Sdl3PlatformBackendProvider(new MacOSArm64Sdl3HostIntegration())]), + rendering = new RenderingBackendCatalog([new BgfxRenderingBackendProvider(new MacOSArm64BgfxSurfaceIntegration())]), + storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(persistentRoot)]) + }, + [new BgfxAuthoringProvider(MacOSArm64BgfxIntegration.shaderProfile)], + [new ImGuiPresentationProvider(new ImGuiInteractionOptions(commandKeyBehavior: true, horizontalWheelDirection: -1))] + ); + var buildContext = StandardBuildEnvironment.Capture( + Path.GetDirectoryName(typeof(MacOSArm64EditorComposition).Assembly.Location)!, + Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, + nativeDependencies: command.nativeDependencies + ); var launch = new EditorLaunchOptions { defaultBuildTarget = Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, @@ -105,14 +113,23 @@ CancellationToken cancellationToken frameDriver = new PollingShellFrameDriver(), distribution = StandardBuildDistribution.Create(buildContext).build, buildContext = buildContext, - supportPackRoot = Path.Combine(Path.GetDirectoryName(typeof(MacOSArm64EditorComposition).Assembly.Location)!, "SupportPacks"), + supportPackRoot = Path.Combine( + Path.GetDirectoryName(typeof(MacOSArm64EditorComposition).Assembly.Location)!, + "SupportPacks" + ), createEngineHost = CreateEngineHost, createScriptModuleSource = deployment => CreateScriptModuleSource(project, deployment), createSessionLogSink = ( kind, session - ) => new FileLogSink(Path.Combine(persistentRoot, - kind == RuntimeSessionKind.Play ? "inno.editor.play" : "inno.editor", "Logs", session.ToString())), + ) => new FileLogSink( + Path.Combine( + persistentRoot, + kind == RuntimeSessionKind.Play ? "inno.editor.play" : "inno.editor", + "Logs", + session.ToString() + ) + ), createHostLogSink = () => new ConsoleLogSink(useColors: true), smokeFrameLimit = command.smokeFrameLimit }; @@ -138,7 +155,8 @@ private static EngineHost CreateEngineHost() => new EngineHostBuilder().UseMetadataSources( new DotNetAssemblyCatalogSource(typeof(MacOSArm64EditorComposition).Assembly), new ReflectionTypeCatalogSource(), - new ReflectionSerializationMetadataSource()).Build(); + new ReflectionSerializationMetadataSource() + ).Build(); private static IModuleSource CreateScriptModuleSource( string project, diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx.Runtime/MacOSArm64BgfxSurfaceIntegration.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx.Runtime/MacOSArm64BgfxSurfaceIntegration.cs index 40aafcba5..2af50d0ab 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx.Runtime/MacOSArm64BgfxSurfaceIntegration.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx.Runtime/MacOSArm64BgfxSurfaceIntegration.cs @@ -37,10 +37,13 @@ public BgfxSurfaceDescriptor Resolve( BgfxSurfaceRole role ) { if (role != BgfxSurfaceRole.Primary && role != BgfxSurfaceRole.Additional) + { throw new ArgumentOutOfRangeException(nameof(role)); + } if (handles.handleKind != PlatformNativeHandleId.cocoa) + { throw new NotSupportedException("The MacOS BGFX integration requires its explicit cocoa surface ABI."); - return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, - supportsSrgbReset: true); + } + return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, supportsSrgbReset: true); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs index f35ce4889..551103819 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs @@ -1,6 +1,6 @@ using System; -using Inno.Build.MacOSArm64; using System.Collections.Generic; +using Inno.Build.MacOSArm64; using Inno.Build.Toolchains; using Inno.Build.Toolchains.Bgfx; @@ -16,8 +16,10 @@ bool includeTools /// public override string targetId => MacOSArm64BuildModule.target.id.value; + /// public override IReadOnlyList generatorArguments => ["--gcc=osx-arm64", "gmake"]; + /// public override string artifactPathToken => "/osx-arm64/bin/"; @@ -37,7 +39,11 @@ public override BgfxBuildInvocation CreateBuildInvocation( bool includeTools ) { string[] arguments = ["-C", ".build/projects/gmake-osx-arm64", "config=" + context.configuration]; - return new("make", includeTools - ? [.. arguments, "shaderc", "texturec", "geometryc", "geometryv", "texturev"] : arguments); + return new( + "make", + includeTools + ? [.. arguments, "shaderc", "texturec", "geometryc", "geometryv", "texturev"] + : arguments + ); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxShaderProfiles.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxShaderProfiles.cs index 9e4755a55..ed712e9de 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxShaderProfiles.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxShaderProfiles.cs @@ -1,8 +1,7 @@ +using Inno.Build.MacOSArm64; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering; -using Inno.Build.MacOSArm64; - namespace Inno.Integration.MacOSArm64.Bgfx; /// @@ -13,10 +12,12 @@ public static class MacOSArm64BgfxShaderProfiles /// /// Gets the immutable configuration shared by this platform's products and publication module. /// - public static BgfxShaderTargetProfile target { get; } = new(MacOSArm64BuildModule.target.id.value, - [ - new(BgfxTargetCapabilities.Create(GraphicsApi.Metal), "osx", "metal", "metal", "metal"), - new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "osx", "spirv", "spirv", "spirv", ["BGFX_SHADER_LANGUAGE_SPIRV=1"]), - new(BgfxTargetCapabilities.Create(GraphicsApi.OpenGL), "osx", "430", "430", "430") - ]); + public static BgfxShaderTargetProfile target { get; } = new( + MacOSArm64BuildModule.target.id.value, + [ + new(BgfxTargetCapabilities.Create(GraphicsApi.Metal), "osx", "metal", "metal", "metal"), + new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "osx", "spirv", "spirv", "spirv", ["BGFX_SHADER_LANGUAGE_SPIRV=1"]), + new(BgfxTargetCapabilities.Create(GraphicsApi.OpenGL), "osx", "430", "430", "430") + ] + ); } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxToolContribution.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxToolContribution.cs index 1a357ff46..f9178c272 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxToolContribution.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxToolContribution.cs @@ -14,7 +14,9 @@ bool includeTools ) { NativeToolchainSelection sdk = context.RequireToolchain(); if (sdk.host.system != "MacOS") + { throw new PlatformNotSupportedException("This BGFX integration requires a MacOS tool host."); + } string generator; if (!sdk.TryResolveExecutable("genie", out generator)) { @@ -31,10 +33,20 @@ bool includeTools string dotnet = sdk.ResolveExecutable("dotnet"); string cmake = sdk.ResolveExecutable("cmake"); if (!includeTools) + { tools.Add("cmake", cmake); - return new NativeToolchainSelection(sdk.targetId, sdk.host, tools, sdk.environment, + } + return new NativeToolchainSelection( + sdk.targetId, + sdk.host, + tools, + sdk.environment, sdk.inputPaths.Where(path => path != dotnet && (!includeTools || path != cmake)) .Concat([Path.Combine(owner, "MacOSArm64BgfxToolContribution.cs"), Path.Combine(owner, "MacOSArm64BgfxBuildProfile.cs")]), - includeTools ? [] : sdk.cmakeArguments, sdk.linkPlan, sdk.multiConfiguration, sdk.compilerInputs); + includeTools ? [] : sdk.cmakeArguments, + sdk.linkPlan, + sdk.multiConfiguration, + sdk.compilerInputs + ); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs index f11f87736..cd8062b3e 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs @@ -7,9 +7,11 @@ namespace Inno.Integration.MacOSArm64.Build; internal static class MacOSArm64BindingProfile { - internal static NativeBindingProfile Create() => new( - MacOSArm64BuildModule.target.id.value, - new TargetConfiguration { id = "macos-arm64-darwin" }, - new ManagedRuntimeId("dotnet.coreclr"), - ["platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs"]); + internal static NativeBindingProfile Create() + => new( + MacOSArm64BuildModule.target.id.value, + new TargetConfiguration { id = "macos-arm64-darwin" }, + new ManagedRuntimeId("dotnet.coreclr"), + ["platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Bindings/MacOSArm64BindingProfile.cs"] + ); } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Deployment/MacOSArm64NativeLayout.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Deployment/MacOSArm64NativeLayout.cs index 6aff43b06..dfba5ea17 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Deployment/MacOSArm64NativeLayout.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Deployment/MacOSArm64NativeLayout.cs @@ -11,10 +11,15 @@ internal static class MacOSArm64NativeLayout string target ) { if (relative.Split(Path.DirectorySeparatorChar)[0] == "Link") + { return null; + } if (component == "bgfx-tools") + { return relative.StartsWith("includes" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? Path.Combine("bgfx", relative) : Path.Combine("bgfx", target, "tools", relative); + ? Path.Combine("bgfx", relative) + : Path.Combine("bgfx", target, "tools", relative); + } return Path.Combine(component, target, relative); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/MacOSArm64BuildIntegration.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/MacOSArm64BuildIntegration.cs index 936ca4075..e3f917c16 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/MacOSArm64BuildIntegration.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/MacOSArm64BuildIntegration.cs @@ -27,13 +27,38 @@ public static BuildPlatformContribution Create(BuildCompositionContext context) { ArgumentNullException.ThrowIfNull(context); var generator = new NativeBindingGenerator(MacOSArm64BindingProfile.Create()); - ProductNativeBuildPlan player = StandardNativeComponents.CreatePlayer(MacOSArm64BgfxIntegration.nativeProfile, MacOSArm64NativeProducts.Options, MacOSArm64NativeLayout.Map); + ProductNativeBuildPlan player = StandardNativeComponents.CreatePlayer( + MacOSArm64BgfxIntegration.nativeProfile, + MacOSArm64NativeProducts.Options, + MacOSArm64NativeLayout.Map + ); var validator = new PlayerSupportPackClosureValidator( StandardSupportPackRequirements.CreateDynamic(player, MacOSArm64BuildModule.target.id, ".dylib"), - new MacOSArm64SupportPackValidator(), StandardNativeDeployment.CreateValidator(MacOSArm64BuildModule.target.id, ".dylib")); + new MacOSArm64SupportPackValidator(), + StandardNativeDeployment.CreateValidator(MacOSArm64BuildModule.target.id, ".dylib") + ); var executor = new ComponentNativeProductExecutor(); - return MacOSArm64BuildModule.CreateContribution(context, new NativeProductContribution(player, executor), - new NativeProductContribution(StandardNativeComponents.CreateEditor(MacOSArm64BgfxIntegration.nativeProfile, MacOSArm64NativeProducts.Options, MacOSArm64NativeLayout.Map), executor), - new NativeProductContribution(StandardNativeComponents.CreateShaderTools(MacOSArm64BgfxIntegration.nativeProfile, MacOSArm64NativeProducts.Options, MacOSArm64NativeLayout.Map), executor), validator, generator); + return MacOSArm64BuildModule.CreateContribution( + context, + new NativeProductContribution(player, executor), + new NativeProductContribution( + StandardNativeComponents.CreateEditor( + MacOSArm64BgfxIntegration.nativeProfile, + MacOSArm64NativeProducts.Options, + MacOSArm64NativeLayout.Map + ), + executor + ), + new NativeProductContribution( + StandardNativeComponents.CreateShaderTools( + MacOSArm64BgfxIntegration.nativeProfile, + MacOSArm64NativeProducts.Options, + MacOSArm64NativeLayout.Map + ), + executor + ), + validator, + generator + ); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs index 74c8a4ce5..1b1486eb8 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs @@ -11,9 +11,13 @@ internal static class MacOSArm64NativeProducts internal static NativeComponentBuildOptions Options(string component) { - return new(NativeLibraryKind.Shared, inputPaths: [C_INPUT], + return new( + NativeLibraryKind.Shared, + inputPaths: [C_INPUT], bindingIncludeDirectories: component == "bgfx" ? ["extern/bx/include/compat/osx"] : [], linkPlan: component == "cimguizmo" - ? MacOSArm64LinkerSettings.Create(["@loader_path/../../cimgui/" + MacOSArm64BuildModule.target.id.value]) : null); + ? MacOSArm64LinkerSettings.Create(["@loader_path/../../cimgui/" + MacOSArm64BuildModule.target.id.value]) + : null + ); } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs index 4b73d51e8..9fd6ef011 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs @@ -30,14 +30,20 @@ public nint CreateWindow(PlatformWindowOptions options) public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) { if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } uint properties = SDL.Raw.GetWindowProperties((SDLWindow*)windowHandle); ReadOnlySpan propertyName = "SDL.window.cocoa.window\0"u8; nint surface; fixed (byte* name = propertyName) + { surface = (nint)SDL.Raw.GetPointerProperty(properties, (sbyte*)name, null); + } if (surface == 0) + { throw new InvalidOperationException("SDL did not provide the required MacOS surface."); + } return new PlatformNativeHandles(surface, handleKind: PlatformNativeHandleId.cocoa); } diff --git a/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerComposition.cs b/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerComposition.cs index ed336a300..59e5005f9 100644 --- a/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerComposition.cs +++ b/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerComposition.cs @@ -1,23 +1,23 @@ -using Inno.Adapter.Rendering; -using Inno.Adapter.Rendering.Bgfx; -using Inno.Integration.MacOSArm64.Bgfx.Runtime; -using Inno.Adapter.Platform; -using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.MacOSArm64.Sdl3; using System; +using System.IO; using Inno.Adapter; using Inno.Adapter.Default; -using Inno.Rendering; -using System.IO; -using Inno.Player.Runtime; -using Inno.Shell; +using Inno.Adapter.Platform; +using Inno.Adapter.Platform.Sdl3; +using Inno.Adapter.Rendering; +using Inno.Adapter.Rendering.Bgfx; using Inno.Adapter.Storage; using Inno.Adapter.Storage.FileSystem; -using Inno.Core.Logging; using Inno.Core.Execution; +using Inno.Core.Logging; +using Inno.Integration.MacOSArm64.Bgfx.Runtime; +using Inno.Integration.MacOSArm64.Sdl3; +using Inno.Platform.MacOSArm64; +using Inno.Player.Runtime; +using Inno.Rendering; using Inno.Runtime; +using Inno.Shell; using Inno.Storage; -using Inno.Platform.MacOSArm64; namespace Inno.Player.MacOSArm64; @@ -49,12 +49,12 @@ internal static int Run(string[] arguments) adapterSelection = StandardAdapterSelection.Create(StorageBackendId.fileSystem), contentSource = new MacOSArm64PlayerContentSource(AppContext.BaseDirectory, dataRoot), createStorage = manifest => new FileSystemApplicationStorage( - Path.Combine(ResolveDataRoot(dataRoot, manifest), "Storage")), + Path.Combine(ResolveDataRoot(dataRoot, manifest), "Storage") + ), createLogSink = ( manifest, sessionId - ) => new FileLogSink( - Path.Combine(ResolveDataRoot(dataRoot, manifest), "Logs", sessionId.ToString())), + ) => new FileLogSink(Path.Combine(ResolveDataRoot(dataRoot, manifest), "Logs", sessionId.ToString())), moduleActivator = Generated.PlayerMetadataComposition.CreateActivator(), frameDriver = new PollingShellFrameDriver(), consoleColors = true, @@ -74,5 +74,4 @@ private static string ResolveDataRoot( string root, GameRuntimeManifest manifest ) => Path.Combine(root, manifest.persistentDataPath.Length == 0 ? manifest.applicationId : manifest.persistentDataPath); - } diff --git a/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs b/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs index 412f18f58..efdf96a7e 100644 --- a/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs +++ b/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs @@ -17,7 +17,9 @@ internal MacOSArm64PlayerContentSource( string applicationDirectory, string cacheRoot ) => m_files = new FileContentDeployment( - MacOSArm64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), cacheRoot); + MacOSArm64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), + cacheRoot + ); /// /// Reads independently owned deployment metadata from the platform's explicit content source. diff --git a/platforms/MacOSArm64/runtime/Inno.Platform.MacOSArm64/MacOSArm64ApplicationLocations.cs b/platforms/MacOSArm64/runtime/Inno.Platform.MacOSArm64/MacOSArm64ApplicationLocations.cs index 030b283bf..25f986ed6 100644 --- a/platforms/MacOSArm64/runtime/Inno.Platform.MacOSArm64/MacOSArm64ApplicationLocations.cs +++ b/platforms/MacOSArm64/runtime/Inno.Platform.MacOSArm64/MacOSArm64ApplicationLocations.cs @@ -22,10 +22,18 @@ public static string userDataRoot get { if (!OperatingSystem.IsMacOS()) + { throw new PlatformNotSupportedException("This product requires MacOS."); - string location = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Application Support"); + } + string location = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + "Library", + "Application Support" + ); if (string.IsNullOrWhiteSpace(location) || !Path.IsPathFullyQualified(location)) + { throw new InvalidOperationException("The system did not provide a usable application data root."); + } return location; } } @@ -46,7 +54,9 @@ public static string GetPlayerContentDirectory(string applicationDirectory) { ArgumentException.ThrowIfNullOrWhiteSpace(applicationDirectory); if (!Path.IsPathFullyQualified(applicationDirectory)) + { throw new ArgumentException("An application directory must be absolute.", nameof(applicationDirectory)); + } return Path.GetFullPath(Path.Combine(applicationDirectory, "..", "Resources", "Content")); } } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs index bc81340a7..fb98054ec 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs @@ -10,10 +10,19 @@ namespace Inno.Build.WindowsX64; public sealed class WindowsBuildHostProvider : IBuildHostProvider { /// - public BuildHostDescriptor? TryCapture() => !OperatingSystem.IsWindows() ? null - : new("Windows", RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(), - new BuildHostServices(new WindowsToolchainWorkspaceProvider(), StringComparer.OrdinalIgnoreCase, - ["platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs", - "platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs", - "platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs"], ".exe")); + public BuildHostDescriptor? TryCapture() + => !OperatingSystem.IsWindows() + ? null + : new( + "Windows", + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(), + new BuildHostServices( + new WindowsToolchainWorkspaceProvider(), + StringComparer.OrdinalIgnoreCase, + ["platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs", + "platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs", + "platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs"], + ".exe" + ) + ); } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs index ae25de827..298c19b51 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs @@ -39,8 +39,11 @@ internal static WindowsToolchainDirectory Create(string physicalPath) Directory.CreateDirectory(alias); try { - byte[] substitute = Encoding.Unicode.GetBytes(physicalPath.StartsWith("\\\\", StringComparison.Ordinal) - ? "\\??\\UNC\\" + physicalPath[2..] : "\\??\\" + physicalPath); + byte[] substitute = Encoding.Unicode.GetBytes( + physicalPath.StartsWith("\\\\", StringComparison.Ordinal) + ? "\\??\\UNC\\" + physicalPath[2..] + : "\\??\\" + physicalPath + ); byte[] printable = Encoding.Unicode.GetBytes(physicalPath); byte[] data = new byte[20 + substitute.Length + printable.Length]; Write(data, 0, C_MOUNT_POINT_TAG); @@ -53,10 +56,13 @@ internal static WindowsToolchainDirectory Create(string physicalPath) using SafeFileHandle handle = CreateFile(alias, 0x40000000, 7, nint.Zero, 3, 0x02200000, nint.Zero); if (handle.IsInvalid) + { throw new Win32Exception(Marshal.GetLastPInvokeError(), "Cannot open the owned toolchain directory alias."); - if (!DeviceIoControl(handle, C_SET_REPARSE_POINT, data, (uint)data.Length, - nint.Zero, 0, out _, nint.Zero)) + } + if (!DeviceIoControl(handle, C_SET_REPARSE_POINT, data, (uint)data.Length, nint.Zero, 0, out _, nint.Zero)) + { throw new Win32Exception(Marshal.GetLastPInvokeError(), "Cannot create the owned toolchain directory alias."); + } return new(physicalPath, alias); } catch @@ -70,7 +76,9 @@ internal static WindowsToolchainDirectory Create(string physicalPath) public void Dispose() { if (toolPath == m_physicalPath || !Directory.Exists(toolPath)) + { return; + } ValidateAlias(toolPath, m_physicalPath); Directory.Delete(toolPath, recursive: false); } @@ -81,7 +89,9 @@ string physicalPath ) { string? target = new DirectoryInfo(alias).LinkTarget; if (target is null || !Path.GetFullPath(target).Equals(physicalPath, StringComparison.OrdinalIgnoreCase)) + { throw new IOException($"Toolchain directory alias '{alias}' is occupied by a different directory."); + } } private static void Write( diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs index 91be8c1cc..24617f88a 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs @@ -23,14 +23,22 @@ public async ValueTask OpenAsync( CancellationToken cancellationToken = default ) { if (!OperatingSystem.IsWindows()) + { throw new PlatformNotSupportedException("Windows execution workspaces require a Windows host."); + } if (!Path.IsPathFullyQualified(physicalPath)) + { throw new ArgumentException("Toolchain workspaces require absolute owner paths.", nameof(physicalPath)); + } string physical = Path.TrimEndingDirectorySeparator(Path.GetFullPath(physicalPath)); string leaf = GetAliasPath(physical) + ".lock"; string owner = Path.Combine(Path.GetDirectoryName(leaf)!, "owner.lock"); - CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync(owner, leaf, - Timeout.InfiniteTimeSpan, cancellationToken: cancellationToken).ConfigureAwait(false); + CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync( + owner, + leaf, + Timeout.InfiniteTimeSpan, + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); @@ -47,7 +55,9 @@ public async ValueTask OpenAsync( internal static string GetAliasPath(string physicalPath) { string identity = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(physicalPath.ToUpperInvariant()))) - .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + .TrimEnd('=') + .Replace('+', '-') + .Replace('/', '_'); return Path.Combine(Path.GetTempPath(), "InnoTools", identity); } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Native/WindowsX64LinkerSettings.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Native/WindowsX64LinkerSettings.cs index fed649cb9..3a08bec8e 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Native/WindowsX64LinkerSettings.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Native/WindowsX64LinkerSettings.cs @@ -13,6 +13,5 @@ public static class WindowsX64LinkerSettings /// /// The immutable target linker plan. /// - public static NativeLinkPlan Create() - => new(".dll", ".lib", ".lib", []); + public static NativeLinkPlan Create() => new(".dll", ".lib", ".lib", []); } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs index 60379b732..f1502e623 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs @@ -39,13 +39,21 @@ public WindowsX64PlayerSupportPackSource( IPlayerSupportPackValidator supportPackValidator ) { m_preparation = new FilePlayerSupportPackPreparation( - Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, "win-x64", Inno.Build.WindowsX64.WindowsX64BuildModule.target.id.value, ".dll", + Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, + "win-x64", + Inno.Build.WindowsX64.WindowsX64BuildModule.target.id.value, + ".dll", supportPackValidator, "platforms/WindowsX64/player/Inno.Player.WindowsX64/Inno.Player.WindowsX64.csproj", "platforms/WindowsX64/build/Inno.Build.WindowsX64/Templates/WindowsX64Player.project.xml", - nativePlan.plan, nativePlan.executor, new WindowsX64NativeToolchainProvider(dotnetHost), host, bindingGenerator, + nativePlan.plan, + nativePlan.executor, + new WindowsX64NativeToolchainProvider(dotnetHost), + host, + bindingGenerator, ["platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs", - "platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs"]); + "platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs"] + ); } /// diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs index 4ed16d067..fb8e8fe96 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs @@ -29,36 +29,54 @@ public void Validate(string directory) if (foreignNativeExtensions.Contains(Path.GetExtension(file), StringComparer.OrdinalIgnoreCase)) { throw new InvalidDataException( - $"Player Support Pack '{Inno.Build.WindowsX64.WindowsX64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'."); + $"Player Support Pack '{Inno.Build.WindowsX64.WindowsX64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'." + ); } if (Path.GetExtension(file).Equals(".dll", StringComparison.OrdinalIgnoreCase)) + { ValidateLibrary(file); + } } foreach (string input in new[] { - "Player.csproj", "Program.cs", "WindowsX64PlayerComposition.cs", "WindowsX64PlayerContentSource.cs", "global.json", + "Player.csproj", + "Program.cs", + "WindowsX64PlayerComposition.cs", + "WindowsX64PlayerContentSource.cs", + "global.json", Path.Combine("Analyzers", "Inno.Runtime.Generators.dll"), Path.Combine("Analyzers", "Inno.Core.Serialization.Generators.dll"), Path.Combine("References", "Inno.Player.Runtime.dll") - }) + }) { if (!File.Exists(Path.Combine(directory, "PlayerLink", input))) + { throw new InvalidDataException($"The Windows Support Pack lacks publication input '{input}'."); + } + } } private static void ValidateLibrary(string file) { using var input = new BinaryReader(File.OpenRead(file)); if (input.BaseStream.Length < 64 || input.ReadUInt16() != 0x5a4d) + { throw new InvalidDataException($"WindowsX64 native library '{file}' has no PE header."); + } input.BaseStream.Position = 60; int offset = input.ReadInt32(); if (offset < 64 || offset > input.BaseStream.Length - 26) + { throw new InvalidDataException($"WindowsX64 native library '{file}' has an invalid PE header offset."); + } input.BaseStream.Position = offset; if (input.ReadUInt32() != 0x00004550 || input.ReadUInt16() != 0x8664) + { throw new InvalidDataException($"WindowsX64 native library '{file}' does not target the AMD64 ABI."); + } input.BaseStream.Position = offset + 22; if ((input.ReadUInt16() & 0x2000) == 0 || input.ReadUInt16() != 0x020b) + { throw new InvalidDataException($"WindowsX64 native library '{file}' is not a PE32+ dynamic library."); + } } } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs index 639a0a14c..929b7ce72 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs @@ -27,7 +27,6 @@ public WindowsX64GameBuildTarget(IPlayerSupportPackValidator supportPackValidato m_supportPackValidator = supportPackValidator ?? throw new ArgumentNullException(nameof(supportPackValidator)); } - /// /// Validates the target closure before runtime script compilation. /// @@ -55,8 +54,6 @@ public WindowsX64GameBuildTarget(IPlayerSupportPackValidator supportPackValidato /// public string displayName => "Windows (x64)"; - - /// /// Composes a Windows application directory in isolated staging. /// @@ -75,14 +72,24 @@ public async ValueTask PackageAsync( ) { ArgumentNullException.ThrowIfNull(context); string application = Path.Combine(context.outputDirectory, context.profile.productName + "-Windows-x64"); - await CopyDirectoryAsync(context.managedDeployment.outputDirectory, application, cancellationToken, - excludeCompilerReferences: true).ConfigureAwait(false); + await CopyDirectoryAsync( + context.managedDeployment.outputDirectory, + application, + cancellationToken, + excludeCompilerReferences: true + ).ConfigureAwait(false); string player = Path.Combine(application, "Inno.Player.WindowsX64.exe"); if (!File.Exists(player)) + { throw new InvalidDataException("The Windows managed publication does not contain Inno.Player.WindowsX64.exe."); + } File.Move(player, Path.Combine(application, context.profile.productName + ".exe")); - await CopyDirectoryAsync(context.contentDirectory, Path.Combine(application, "Content"), cancellationToken, - excludeCompilerReferences: false) + await CopyDirectoryAsync( + context.contentDirectory, + Path.Combine(application, "Content"), + cancellationToken, + excludeCompilerReferences: false + ) .ConfigureAwait(false); return application; } @@ -99,7 +106,9 @@ bool excludeCompilerReferences cancellationToken.ThrowIfCancellationRequested(); string relativePath = Path.GetRelativePath(source, directory); if (excludeCompilerReferences && IsCompilerReferencePath(relativePath)) + { continue; + } Directory.CreateDirectory(Path.Combine(destination, relativePath)); } foreach (string file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) @@ -107,7 +116,9 @@ bool excludeCompilerReferences cancellationToken.ThrowIfCancellationRequested(); string relativePath = Path.GetRelativePath(source, file); if (excludeCompilerReferences && IsCompilerReferencePath(relativePath)) + { continue; + } string target = Path.Combine(destination, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(target)!); await using FileStream input = new(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, true); diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs index ea563b162..2b053122d 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs @@ -41,60 +41,107 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(host); cancellationToken.ThrowIfCancellationRequested(); if (!(host.system == "Windows" && host.architecture == "x64" && targetId == "windows-x64")) + { throw new PlatformNotSupportedException($"The Windows SDK cannot build '{targetId}' on {host.system}/{host.architecture}."); - var tools = new Dictionary(StringComparer.Ordinal) { ["dotnet"] = ToolchainEnvironment.ResolveExecutable(m_dotnetHost) }; + } + var tools = new Dictionary(StringComparer.Ordinal) + { + ["dotnet"] = ToolchainEnvironment.ResolveExecutable(m_dotnetHost) + }; Dictionary environment = NativeToolchainPreparation.CreateEnvironment(); var inputs = new List(); var cmakeArguments = new List(); - string locator = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), - "Microsoft Visual Studio", "Installer", "vswhere.exe"); - string installation = (await ToolchainEnvironment.CaptureOutputAsync(locator, + string locator = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), + "Microsoft Visual Studio", + "Installer", + "vswhere.exe" + ); + string installation = (await ToolchainEnvironment.CaptureOutputAsync( + locator, ["-latest", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", - "-property", "installationPath"], context.engineRoot, cancellationToken).ConfigureAwait(false)).Trim(); + "-property", "installationPath"], + context.engineRoot, + cancellationToken + ).ConfigureAwait(false)).Trim(); if (!Directory.Exists(installation)) + { throw new InvalidOperationException("No Visual Studio installation with the x64 C++ tools was found."); + } string setup = Path.Combine(installation, "Common7", "Tools", "VsDevCmd.bat"); var query = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "cmd.exe")) { Arguments = $"/d /s /c \"call \"{setup}\" -arch=x64 -host_arch=x64 >nul && set\"" }; - query.Environment["PATH"] = string.Join(Path.PathSeparator, Environment.SystemDirectory, + query.Environment["PATH"] = string.Join( + Path.PathSeparator, + Environment.SystemDirectory, Environment.GetFolderPath(Environment.SpecialFolder.Windows), - Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0")); + Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0") + ); string output = await ToolchainEnvironment.CaptureOutputAsync(query, cancellationToken).ConfigureAwait(false); var selected = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string line in output.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)) { int separator = line.IndexOf('='); if (separator > 0) + { selected[line[..separator]] = line[(separator + 1)..]; + } } foreach (string name in new[] { "PATH", "INCLUDE", "LIB", "LIBPATH", "VCToolsInstallDir", - "VCToolsVersion", "WindowsSdkDir", "WindowsSDKVersion" }) + "VCToolsVersion", "WindowsSdkDir", "WindowsSDKVersion" } + ) { environment[name] = RequireVariable(selected, name); + } string compilerDirectory = Path.Combine(environment["VCToolsInstallDir"], "bin", "Hostx64", "x64"); tools["cl"] = Path.Combine(compilerDirectory, "cl.exe"); tools["msbuild"] = Path.Combine(installation, "MSBuild", "Current", "Bin", "MSBuild.exe"); - tools["cmake"] = Path.Combine(installation, "Common7", "IDE", "CommonExtensions", "Microsoft", - "CMake", "CMake", "bin", "cmake.exe"); + tools["cmake"] = Path.Combine( + installation, + "Common7", + "IDE", + "CommonExtensions", + "Microsoft", + "CMake", + "CMake", + "bin", + "cmake.exe" + ); inputs.AddRange([locator, setup, compilerDirectory, Path.GetDirectoryName(tools["msbuild"])!]); foreach (string name in new[] { "INCLUDE", "LIB" }) + { inputs.AddRange(environment[name].Split(';', StringSplitOptions.RemoveEmptyEntries)); + } cmakeArguments.AddRange([ "-DCMAKE_GENERATOR_INSTANCE=" + installation, - "-T", "version=" + environment["VCToolsVersion"], - "-DCMAKE_SYSTEM_VERSION=" + environment["WindowsSDKVersion"].TrimEnd('\\', '/')]); + "-T", + "version=" + environment["VCToolsVersion"], + "-DCMAKE_SYSTEM_VERSION=" + environment["WindowsSDKVersion"].TrimEnd('\\', '/') + ]); cmakeArguments.InsertRange(0, ["-G", "Visual Studio 17 2022", "-A", "x64"]); - return NativeToolchainPreparation.Freeze(targetId, host, tools, environment, inputs, - cmakeArguments, WindowsX64LinkerSettings.Create(), true, new NativeCompilerInputs(tools["cl"], tools["cl"], - systemIncludeDirectories: environment["INCLUDE"].Split(';', StringSplitOptions.RemoveEmptyEntries))); + return NativeToolchainPreparation.Freeze( + targetId, + host, + tools, + environment, + inputs, + cmakeArguments, + WindowsX64LinkerSettings.Create(), + true, + new NativeCompilerInputs( + tools["cl"], + tools["cl"], + systemIncludeDirectories: environment["INCLUDE"].Split(';', StringSplitOptions.RemoveEmptyEntries) + ) + ); } private static string RequireVariable( IReadOnlyDictionary selected, string name ) => selected.TryGetValue(name, out string? value) && !string.IsNullOrWhiteSpace(value) - ? value - : throw new InvalidOperationException($"The selected C++ toolchain did not define '{name}'."); + ? value + : throw new InvalidOperationException($"The selected C++ toolchain did not define '{name}'."); } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/WindowsX64BuildModule.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/WindowsX64BuildModule.cs index 182b9d833..fe761e212 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/WindowsX64BuildModule.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/WindowsX64BuildModule.cs @@ -14,7 +14,13 @@ public static class WindowsX64BuildModule /// Gets the explicit implemented product target, independent of the tool execution host. /// public static PlatformTargetDescriptor target { get; } = new( - new BuildTargetId("windows-x64"), "Windows", "x64", "msvc-x64", "win-x64", true); + new BuildTargetId("windows-x64"), + "Windows", + "x64", + "msvc-x64", + "win-x64", + true + ); /// /// Contributes the platform's target, product inputs and SDK resolver as one registration. @@ -51,11 +57,15 @@ INativeBindingGenerator bindingGenerator ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(nativePlan); ArgumentNullException.ThrowIfNull(editorNativePlan); - return new(target, + return new( + target, () => new WindowsX64GameBuildTarget(supportPackValidator), - new WindowsX64PlayerSupportPackSource(nativePlan, context.host, context.dotnetHost, bindingGenerator, supportPackValidator), new WindowsX64NativeToolchainProvider(context.dotnetHost), + new WindowsX64PlayerSupportPackSource(nativePlan, context.host, context.dotnetHost, bindingGenerator, supportPackValidator), + new WindowsX64NativeToolchainProvider(context.dotnetHost), "platforms/WindowsX64/editor/Inno.Editor.WindowsX64/Inno.Editor.WindowsX64.csproj", - [nativePlan, editorNativePlan, shaderToolsPlan], bindingGenerator, - [ManagedDeploymentId.coreClr, ManagedDeploymentId.nativeAot]); + [nativePlan, editorNativePlan, shaderToolsPlan], + bindingGenerator, + [ManagedDeploymentId.coreClr, ManagedDeploymentId.nativeAot] + ); } } diff --git a/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs b/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs index 596f6d4cc..9314a97d9 100644 --- a/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs +++ b/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs @@ -64,22 +64,30 @@ CancellationToken cancellationToken using var picker = new Sdl3PlatformApplication(new WindowsX64Sdl3HostIntegration()); string? selected = Sdl3FolderDialog.SelectFolder(picker); if (selected is null) + { return 0; + } arguments = [selected]; } EditorCommandLineOptions command = EditorCommandLineOptions.Parse(arguments); _ = WindowsX64ApplicationLocations.userDataRoot; string project = Path.GetFullPath(command.projectDirectory); string persistentRoot = Path.Combine(project, "Library", "PersistentData"); - var adapters = new DefaultAuthoringAdapterCatalog(new DefaultAdapterCatalogOptions - { - platform = new PlatformBackendCatalog([new Sdl3PlatformBackendProvider(new WindowsX64Sdl3HostIntegration())]), - rendering = new RenderingBackendCatalog([new BgfxRenderingBackendProvider(new WindowsX64BgfxSurfaceIntegration())]), - storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(persistentRoot)]) - }, [new BgfxAuthoringProvider(WindowsX64BgfxIntegration.shaderProfile)], - [new ImGuiPresentationProvider(new ImGuiInteractionOptions(commandKeyBehavior: false, horizontalWheelDirection: 1))]); - var buildContext = StandardBuildEnvironment.Capture(Path.GetDirectoryName(typeof(WindowsX64EditorComposition).Assembly.Location)!, - Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, nativeDependencies: command.nativeDependencies); + var adapters = new DefaultAuthoringAdapterCatalog( + new DefaultAdapterCatalogOptions + { + platform = new PlatformBackendCatalog([new Sdl3PlatformBackendProvider(new WindowsX64Sdl3HostIntegration())]), + rendering = new RenderingBackendCatalog([new BgfxRenderingBackendProvider(new WindowsX64BgfxSurfaceIntegration())]), + storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(persistentRoot)]) + }, + [new BgfxAuthoringProvider(WindowsX64BgfxIntegration.shaderProfile)], + [new ImGuiPresentationProvider(new ImGuiInteractionOptions(commandKeyBehavior: false, horizontalWheelDirection: 1))] + ); + var buildContext = StandardBuildEnvironment.Capture( + Path.GetDirectoryName(typeof(WindowsX64EditorComposition).Assembly.Location)!, + Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, + nativeDependencies: command.nativeDependencies + ); var launch = new EditorLaunchOptions { defaultBuildTarget = Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, @@ -105,14 +113,23 @@ CancellationToken cancellationToken frameDriver = new PollingShellFrameDriver(), distribution = StandardBuildDistribution.Create(buildContext).build, buildContext = buildContext, - supportPackRoot = Path.Combine(Path.GetDirectoryName(typeof(WindowsX64EditorComposition).Assembly.Location)!, "SupportPacks"), + supportPackRoot = Path.Combine( + Path.GetDirectoryName(typeof(WindowsX64EditorComposition).Assembly.Location)!, + "SupportPacks" + ), createEngineHost = CreateEngineHost, createScriptModuleSource = deployment => CreateScriptModuleSource(project, deployment), createSessionLogSink = ( kind, session - ) => new FileLogSink(Path.Combine(persistentRoot, - kind == RuntimeSessionKind.Play ? "inno.editor.play" : "inno.editor", "Logs", session.ToString())), + ) => new FileLogSink( + Path.Combine( + persistentRoot, + kind == RuntimeSessionKind.Play ? "inno.editor.play" : "inno.editor", + "Logs", + session.ToString() + ) + ), createHostLogSink = () => new ConsoleLogSink(useColors: true), smokeFrameLimit = command.smokeFrameLimit }; @@ -138,7 +155,8 @@ private static EngineHost CreateEngineHost() => new EngineHostBuilder().UseMetadataSources( new DotNetAssemblyCatalogSource(typeof(WindowsX64EditorComposition).Assembly), new ReflectionTypeCatalogSource(), - new ReflectionSerializationMetadataSource()).Build(); + new ReflectionSerializationMetadataSource() + ).Build(); private static IModuleSource CreateScriptModuleSource( string project, diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime/WindowsX64BgfxSurfaceIntegration.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime/WindowsX64BgfxSurfaceIntegration.cs index 8b2a7b105..783ab2aa7 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime/WindowsX64BgfxSurfaceIntegration.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime/WindowsX64BgfxSurfaceIntegration.cs @@ -37,10 +37,13 @@ public BgfxSurfaceDescriptor Resolve( BgfxSurfaceRole role ) { if (role != BgfxSurfaceRole.Primary && role != BgfxSurfaceRole.Additional) + { throw new ArgumentOutOfRangeException(nameof(role)); + } if (handles.handleKind != PlatformNativeHandleId.win32) + { throw new NotSupportedException("The Windows BGFX integration requires its explicit win32 surface ABI."); - return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, - supportsSrgbReset: true); + } + return new BgfxSurfaceDescriptor(handles.windowHandle, handles.displayHandle, supportsSrgbReset: true); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs index 0f7560add..9e3fcfdbc 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs @@ -1,9 +1,9 @@ using System; -using Inno.Build.WindowsX64; using System.Collections.Generic; using System.IO; using Inno.Build.Toolchains; using Inno.Build.Toolchains.Bgfx; +using Inno.Build.WindowsX64; namespace Inno.Integration.WindowsX64.Bgfx; @@ -17,14 +17,16 @@ bool includeTools /// public override string targetId => WindowsX64BuildModule.target.id.value; + /// public override IReadOnlyList generatorArguments => ["vs2022"]; + /// public override string artifactPathToken => "/win64_vs2022/bin/"; /// - public override IReadOnlyList bindingCmakeArguments => - ["-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded$<$:Debug>"]; + public override IReadOnlyList bindingCmakeArguments + => ["-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded$<$:Debug>"]; /// public override (string reference, IReadOnlyList arguments) CreateBindingLinkSettings(string archivePath) @@ -41,7 +43,13 @@ bool includeTools ) { string sdk = context.RequireToolchain().environment["WindowsSDKVersion"].TrimEnd('\\', '/'); string configuration = context.configuration == "debug" ? "Debug" : "Release"; - return new("msbuild", [".build/projects/vs2022/bgfx.sln", "/m:1", "/nodeReuse:false", - "/p:Configuration=" + configuration, "/p:Platform=x64", "/p:WindowsTargetPlatformVersion=" + sdk]); + return new("msbuild", [ + ".build/projects/vs2022/bgfx.sln", + "/m:1", + "/nodeReuse:false", + "/p:Configuration=" + configuration, + "/p:Platform=x64", + "/p:WindowsTargetPlatformVersion=" + sdk + ]); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxIntegration.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxIntegration.cs index 648fa4dd2..9757bc1d7 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxIntegration.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxIntegration.cs @@ -40,6 +40,13 @@ public static GameContentCompilerFactory CreateContentCompilerFactory(ToolRunner assets, serialization, types - ) => new BgfxGameContentCompiler(assets, serialization, types, shaderProfile, [GraphicsApi.Direct3D11, GraphicsApi.Direct3D12, GraphicsApi.Vulkan, GraphicsApi.OpenGL], tools); + ) => new BgfxGameContentCompiler( + assets, + serialization, + types, + shaderProfile, + [GraphicsApi.Direct3D11, GraphicsApi.Direct3D12, GraphicsApi.Vulkan, GraphicsApi.OpenGL], + tools + ); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxShaderProfiles.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxShaderProfiles.cs index 93bc03a5e..165fe26ce 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxShaderProfiles.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxShaderProfiles.cs @@ -1,7 +1,6 @@ using Inno.Build.Toolchains.Bgfx.Tools; -using Inno.Rendering; - using Inno.Build.WindowsX64; +using Inno.Rendering; namespace Inno.Integration.WindowsX64.Bgfx; @@ -13,11 +12,13 @@ public static class WindowsX64BgfxShaderProfiles /// /// Gets the immutable configuration shared by this platform's products and publication module. /// - public static BgfxShaderTargetProfile target { get; } = new(WindowsX64BuildModule.target.id.value, - [ - new(BgfxTargetCapabilities.Create(GraphicsApi.Direct3D11), "windows", "s_5_0", "s_5_0", "s_5_0"), - new(BgfxTargetCapabilities.Create(GraphicsApi.Direct3D12), "windows", "s_5_0", "s_5_0", "s_5_0"), - new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "windows", "spirv", "spirv", "spirv"), - new(BgfxTargetCapabilities.Create(GraphicsApi.OpenGL), "windows", "430", "430", "430") - ]); + public static BgfxShaderTargetProfile target { get; } = new( + WindowsX64BuildModule.target.id.value, + [ + new(BgfxTargetCapabilities.Create(GraphicsApi.Direct3D11), "windows", "s_5_0", "s_5_0", "s_5_0"), + new(BgfxTargetCapabilities.Create(GraphicsApi.Direct3D12), "windows", "s_5_0", "s_5_0", "s_5_0"), + new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "windows", "spirv", "spirv", "spirv"), + new(BgfxTargetCapabilities.Create(GraphicsApi.OpenGL), "windows", "430", "430", "430") + ] + ); } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxToolContribution.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxToolContribution.cs index 5db89d040..272143275 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxToolContribution.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxToolContribution.cs @@ -14,7 +14,9 @@ bool includeTools ) { NativeToolchainSelection sdk = context.RequireToolchain(); if (sdk.host.system != "Windows") + { throw new PlatformNotSupportedException("This BGFX integration requires a Windows tool host."); + } string generator; if (!sdk.TryResolveExecutable("genie", out generator)) { @@ -30,10 +32,20 @@ bool includeTools string dotnet = sdk.ResolveExecutable("dotnet"); string cmake = sdk.ResolveExecutable("cmake"); if (!includeTools) + { tools.Add("cmake", cmake); - return new NativeToolchainSelection(sdk.targetId, sdk.host, tools, sdk.environment, + } + return new NativeToolchainSelection( + sdk.targetId, + sdk.host, + tools, + sdk.environment, sdk.inputPaths.Where(path => path != dotnet && (!includeTools || path != cmake)) .Concat([Path.Combine(owner, "WindowsX64BgfxToolContribution.cs"), Path.Combine(owner, "WindowsX64BgfxBuildProfile.cs")]), - includeTools ? [] : sdk.cmakeArguments, sdk.linkPlan, sdk.multiConfiguration, sdk.compilerInputs); + includeTools ? [] : sdk.cmakeArguments, + sdk.linkPlan, + sdk.multiConfiguration, + sdk.compilerInputs + ); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs index 4fc9eb096..1e5ffd0b0 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs @@ -7,9 +7,11 @@ namespace Inno.Integration.WindowsX64.Build; internal static class WindowsX64BindingProfile { - internal static NativeBindingProfile Create() => new( - WindowsX64BuildModule.target.id.value, - new TargetConfiguration { id = "windows-x64-msvc" }, - new ManagedRuntimeId("dotnet.coreclr"), - ["platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs"]); + internal static NativeBindingProfile Create() + => new( + WindowsX64BuildModule.target.id.value, + new TargetConfiguration { id = "windows-x64-msvc" }, + new ManagedRuntimeId("dotnet.coreclr"), + ["platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Bindings/WindowsX64BindingProfile.cs"] + ); } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Deployment/WindowsX64NativeLayout.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Deployment/WindowsX64NativeLayout.cs index ca5bf4bd0..88d52b1b2 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Deployment/WindowsX64NativeLayout.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Deployment/WindowsX64NativeLayout.cs @@ -11,10 +11,15 @@ internal static class WindowsX64NativeLayout string target ) { if (relative.Split(Path.DirectorySeparatorChar)[0] == "Link") + { return null; + } if (component == "bgfx-tools") + { return relative.StartsWith("includes" + Path.DirectorySeparatorChar, StringComparison.Ordinal) - ? Path.Combine("bgfx", relative) : Path.Combine("bgfx", target, "tools", relative); + ? Path.Combine("bgfx", relative) + : Path.Combine("bgfx", target, "tools", relative); + } return Path.Combine(component, target, relative); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs index f2f9c1f18..50d631d15 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs @@ -8,8 +8,10 @@ internal static class WindowsX64NativeProducts internal static NativeComponentBuildOptions Options(string component) { - return new(NativeLibraryKind.Shared, + return new( + NativeLibraryKind.Shared, cmakeArguments: component == "cimgui" ? ["-DINNO_CIMGUI_COMPILE_DEFINITIONS=IMGUI_API=__declspec(dllexport)"] : [], - inputPaths: [C_INPUT]); + inputPaths: [C_INPUT] + ); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/WindowsX64BuildIntegration.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/WindowsX64BuildIntegration.cs index d015f4b2b..9195b7a3b 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/WindowsX64BuildIntegration.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/WindowsX64BuildIntegration.cs @@ -27,13 +27,38 @@ public static BuildPlatformContribution Create(BuildCompositionContext context) { ArgumentNullException.ThrowIfNull(context); var generator = new NativeBindingGenerator(WindowsX64BindingProfile.Create()); - ProductNativeBuildPlan player = StandardNativeComponents.CreatePlayer(WindowsX64BgfxIntegration.nativeProfile, WindowsX64NativeProducts.Options, WindowsX64NativeLayout.Map); + ProductNativeBuildPlan player = StandardNativeComponents.CreatePlayer( + WindowsX64BgfxIntegration.nativeProfile, + WindowsX64NativeProducts.Options, + WindowsX64NativeLayout.Map + ); var validator = new PlayerSupportPackClosureValidator( StandardSupportPackRequirements.CreateDynamic(player, WindowsX64BuildModule.target.id, ".dll"), - new WindowsX64SupportPackValidator(), StandardNativeDeployment.CreateValidator(WindowsX64BuildModule.target.id, ".dll")); + new WindowsX64SupportPackValidator(), + StandardNativeDeployment.CreateValidator(WindowsX64BuildModule.target.id, ".dll") + ); var executor = new ComponentNativeProductExecutor(); - return WindowsX64BuildModule.CreateContribution(context, new NativeProductContribution(player, executor), - new NativeProductContribution(StandardNativeComponents.CreateEditor(WindowsX64BgfxIntegration.nativeProfile, WindowsX64NativeProducts.Options, WindowsX64NativeLayout.Map), executor), - new NativeProductContribution(StandardNativeComponents.CreateShaderTools(WindowsX64BgfxIntegration.nativeProfile, WindowsX64NativeProducts.Options, WindowsX64NativeLayout.Map), executor), validator, generator); + return WindowsX64BuildModule.CreateContribution( + context, + new NativeProductContribution(player, executor), + new NativeProductContribution( + StandardNativeComponents.CreateEditor( + WindowsX64BgfxIntegration.nativeProfile, + WindowsX64NativeProducts.Options, + WindowsX64NativeLayout.Map + ), + executor + ), + new NativeProductContribution( + StandardNativeComponents.CreateShaderTools( + WindowsX64BgfxIntegration.nativeProfile, + WindowsX64NativeProducts.Options, + WindowsX64NativeLayout.Map + ), + executor + ), + validator, + generator + ); } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs index 31062aa38..02d334181 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs @@ -15,9 +15,7 @@ public sealed class WindowsX64Sdl3HostIntegration : ISdl3HostIntegration public Sdl3HostCapabilities capabilities { get; } = new(multipleWindows: true, liveResize: true); /// - public void ConfigureInitialization() - { - } + public void ConfigureInitialization() {} /// public nint CreateWindow(PlatformWindowOptions options) @@ -29,14 +27,20 @@ public nint CreateWindow(PlatformWindowOptions options) public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) { if (windowHandle == 0) + { throw new ArgumentException("A live SDL window is required.", nameof(windowHandle)); + } uint properties = SDL.Raw.GetWindowProperties((SDLWindow*)windowHandle); ReadOnlySpan propertyName = "SDL.window.win32.hwnd\0"u8; nint surface; fixed (byte* name = propertyName) + { surface = (nint)SDL.Raw.GetPointerProperty(properties, (sbyte*)name, null); + } if (surface == 0) + { throw new InvalidOperationException("SDL did not provide the required Windows surface."); + } return new PlatformNativeHandles(surface, handleKind: PlatformNativeHandleId.win32); } diff --git a/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerComposition.cs b/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerComposition.cs index 60e6b6657..633f8d55f 100644 --- a/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerComposition.cs +++ b/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerComposition.cs @@ -1,23 +1,23 @@ -using Inno.Adapter.Rendering; -using Inno.Adapter.Rendering.Bgfx; -using Inno.Integration.WindowsX64.Bgfx.Runtime; -using Inno.Adapter.Platform; -using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.WindowsX64.Sdl3; using System; +using System.IO; using Inno.Adapter; using Inno.Adapter.Default; -using Inno.Rendering; -using System.IO; -using Inno.Player.Runtime; -using Inno.Shell; +using Inno.Adapter.Platform; +using Inno.Adapter.Platform.Sdl3; +using Inno.Adapter.Rendering; +using Inno.Adapter.Rendering.Bgfx; using Inno.Adapter.Storage; using Inno.Adapter.Storage.FileSystem; -using Inno.Core.Logging; using Inno.Core.Execution; +using Inno.Core.Logging; +using Inno.Integration.WindowsX64.Bgfx.Runtime; +using Inno.Integration.WindowsX64.Sdl3; +using Inno.Platform.WindowsX64; +using Inno.Player.Runtime; +using Inno.Rendering; using Inno.Runtime; +using Inno.Shell; using Inno.Storage; -using Inno.Platform.WindowsX64; namespace Inno.Player.WindowsX64; @@ -49,12 +49,12 @@ internal static int Run(string[] arguments) adapterSelection = StandardAdapterSelection.Create(StorageBackendId.fileSystem), contentSource = new WindowsX64PlayerContentSource(AppContext.BaseDirectory, dataRoot), createStorage = manifest => new FileSystemApplicationStorage( - Path.Combine(ResolveDataRoot(dataRoot, manifest), "Storage")), + Path.Combine(ResolveDataRoot(dataRoot, manifest), "Storage") + ), createLogSink = ( manifest, sessionId - ) => new FileLogSink( - Path.Combine(ResolveDataRoot(dataRoot, manifest), "Logs", sessionId.ToString())), + ) => new FileLogSink(Path.Combine(ResolveDataRoot(dataRoot, manifest), "Logs", sessionId.ToString())), moduleActivator = Generated.PlayerMetadataComposition.CreateActivator(), frameDriver = new PollingShellFrameDriver(), consoleColors = true, @@ -74,5 +74,4 @@ private static string ResolveDataRoot( string root, GameRuntimeManifest manifest ) => Path.Combine(root, manifest.persistentDataPath.Length == 0 ? manifest.applicationId : manifest.persistentDataPath); - } diff --git a/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs b/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs index 8a8cb4b26..e0b0331d5 100644 --- a/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs +++ b/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs @@ -17,7 +17,9 @@ internal WindowsX64PlayerContentSource( string applicationDirectory, string cacheRoot ) => m_files = new FileContentDeployment( - WindowsX64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), cacheRoot); + WindowsX64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), + cacheRoot + ); /// /// Reads independently owned deployment metadata from the platform's explicit content source. diff --git a/platforms/WindowsX64/runtime/Inno.Platform.WindowsX64/WindowsX64ApplicationLocations.cs b/platforms/WindowsX64/runtime/Inno.Platform.WindowsX64/WindowsX64ApplicationLocations.cs index d5b13a59f..749667311 100644 --- a/platforms/WindowsX64/runtime/Inno.Platform.WindowsX64/WindowsX64ApplicationLocations.cs +++ b/platforms/WindowsX64/runtime/Inno.Platform.WindowsX64/WindowsX64ApplicationLocations.cs @@ -22,10 +22,14 @@ public static string userDataRoot get { if (!OperatingSystem.IsWindows()) + { throw new PlatformNotSupportedException("This product requires Windows."); + } string location = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (string.IsNullOrWhiteSpace(location) || !Path.IsPathFullyQualified(location)) + { throw new InvalidOperationException("The system did not provide a usable application data root."); + } return location; } } @@ -46,7 +50,9 @@ public static string GetPlayerContentDirectory(string applicationDirectory) { ArgumentException.ThrowIfNullOrWhiteSpace(applicationDirectory); if (!Path.IsPathFullyQualified(applicationDirectory)) + { throw new ArgumentException("An application directory must be absolute.", nameof(applicationDirectory)); + } return Path.Combine(applicationDirectory, "Content"); } } diff --git a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs index bdef70afd..cb65d7e8f 100644 --- a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs +++ b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs @@ -30,7 +30,9 @@ public AudioBackendCatalog(IEnumerable providers) foreach (AudioBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); } @@ -47,9 +49,10 @@ public IAudioDevice CreateDevice( AudioBackendOptions options ) { if (!m_providers.TryGetValue(backend, out AudioBackendProvider? provider)) + { throw new NotSupportedException("Audio backend '" + backend + "' is not registered."); + } return provider.CreateDevice(options) - ?? throw new InvalidOperationException("Audio provider '" + backend + "' returned no service."); + ?? throw new InvalidOperationException("Audio provider '" + backend + "' returned no service."); } } - diff --git a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendId.cs b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendId.cs index b70f39b1a..03266c671 100644 --- a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendId.cs +++ b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendId.cs @@ -20,8 +20,12 @@ public AudioBackendId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } @@ -48,4 +52,3 @@ public AudioBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendProvider.cs b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendProvider.cs index f45aab923..92ed7fba3 100644 --- a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendProvider.cs +++ b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendProvider.cs @@ -24,7 +24,9 @@ public abstract class AudioBackendProvider protected AudioBackendProvider(AudioBackendId id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } @@ -44,4 +46,3 @@ protected AudioBackendProvider(AudioBackendId id) /// public abstract IAudioDevice CreateDevice(AudioBackendOptions options); } - diff --git a/src/adapters/common/Inno.Adapter/AdapterSelection.cs b/src/adapters/common/Inno.Adapter/AdapterSelection.cs index 9393e803b..ef8a3a7bb 100644 --- a/src/adapters/common/Inno.Adapter/AdapterSelection.cs +++ b/src/adapters/common/Inno.Adapter/AdapterSelection.cs @@ -79,8 +79,11 @@ private static void Require( TBackend backend, IReadOnlyList available, string domain - ) where TBackend : struct, IEquatable { + ) where TBackend : struct, IEquatable + { if (backend.Equals(default) || !available.Contains(backend)) + { throw new NotSupportedException(domain + " backend '" + backend + "' is not registered."); + } } } diff --git a/src/adapters/common/Inno.Adapter/IAdapterCatalog.cs b/src/adapters/common/Inno.Adapter/IAdapterCatalog.cs index 158c8a7f3..bc121e606 100644 --- a/src/adapters/common/Inno.Adapter/IAdapterCatalog.cs +++ b/src/adapters/common/Inno.Adapter/IAdapterCatalog.cs @@ -47,5 +47,4 @@ public interface IAdapterCatalog /// Gets the retained-mode UI backend factory. /// IUiBackendFactory ui { get; } - } diff --git a/src/adapters/input/Inno.Adapter.Input/EventInputBackend.cs b/src/adapters/input/Inno.Adapter.Input/EventInputBackend.cs index c17154282..1955b823f 100644 --- a/src/adapters/input/Inno.Adapter.Input/EventInputBackend.cs +++ b/src/adapters/input/Inno.Adapter.Input/EventInputBackend.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Threading; - using Inno.Core.Events; using Inno.Core.Input; using Inno.Core.Mathematics; @@ -39,9 +38,7 @@ public sealed class EventInputBackend : IInputBackend /// The translated event window identifier, or zero to accept input from every window. /// public EventInputBackend(uint windowId) - : this(windowId, null) - { - } + : this(windowId, null) {} internal EventInputBackend( uint windowId, @@ -68,36 +65,50 @@ public void ProcessEvent(Event evnt) ArgumentNullException.ThrowIfNull(evnt); ObjectDisposedException.ThrowIf(m_disposed, this); if (evnt.isGlobalHandled || !Accepts(evnt)) + { return; + } lock (m_sync) { ObjectDisposedException.ThrowIf(m_disposed, this); if (evnt is ApplicationSuspensionChangedEvent suspension) + { m_suspended = suspension.isSuspended; + } if (m_suspended && evnt is KeyEvent or MouseEvent or TextInputEvent) + { return; + } switch (evnt) { case KeyPressedEvent key when !key.repeat: m_modifiers = key.modifiers; if (m_keysDown.Add(key.key)) + { m_keysPressed.Add(key.key); + } break; case KeyReleasedEvent key: m_modifiers = key.modifiers; if (m_keysDown.Remove(key.key)) + { m_keysReleased.Add(key.key); + } break; case TextInputEvent text: m_textInput.Add(text.text); break; case MouseButtonPressedEvent button: if (m_mouseButtonsDown.Add(button.button)) + { m_mouseButtonsPressed.Add(button.button); + } break; case MouseButtonReleasedEvent button: if (m_mouseButtonsDown.Remove(button.button)) + { m_mouseButtonsReleased.Add(button.button); + } break; case MouseMovedEvent movement: var nextPosition = new Vector2(movement.x, movement.y); @@ -151,7 +162,8 @@ public InputSnapshot Capture(long frameIndex) m_mouseDelta, m_scrollDelta, m_modifiers, - m_textInput); + m_textInput + ); m_keysPressed.Clear(); m_keysReleased.Clear(); m_mouseButtonsPressed.Clear(); @@ -169,7 +181,9 @@ public InputSnapshot Capture(long frameIndex) public void Dispose() { if (m_disposed) + { return; + } lock (m_sync) { m_disposed = true; diff --git a/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs b/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs index 60309bf4d..0d410802f 100644 --- a/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs +++ b/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs @@ -11,7 +11,8 @@ public sealed class EventInputBackendProvider : InputBackendProvider /// /// Creates an explicitly composed registration for the bundled implementation. /// - public EventInputBackendProvider() : base(InputBackendId.events) { } + public EventInputBackendProvider() + : base(InputBackendId.events) {} /// public override IInputEventSource CreateEventSource( @@ -22,4 +23,3 @@ bool acceptAllWindows return new EventInputSource(acceptAllWindows ? 0 : window.windowId); } } - diff --git a/src/adapters/input/Inno.Adapter.Input/EventInputSource.cs b/src/adapters/input/Inno.Adapter.Input/EventInputSource.cs index cc1dfdb86..a86de868a 100644 --- a/src/adapters/input/Inno.Adapter.Input/EventInputSource.cs +++ b/src/adapters/input/Inno.Adapter.Input/EventInputSource.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Events; using Inno.Input; @@ -72,13 +71,17 @@ public void ProcessEvent(Event evnt) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_inputHub.Dispose(); EventInputBackend[] snapshot = m_backends.ToArray(); m_backends.Clear(); foreach (EventInputBackend backend in snapshot) + { backend.DisconnectSource(); + } } private void RemoveBackend(EventInputBackend backend) => m_backends.Remove(backend); diff --git a/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs b/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs index 2fb5dc593..7626374f4 100644 --- a/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs +++ b/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs @@ -30,7 +30,9 @@ public InputBackendCatalog(IEnumerable providers) foreach (InputBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); } @@ -49,9 +51,10 @@ bool acceptAllWindows ) { ArgumentNullException.ThrowIfNull(window); if (!m_providers.TryGetValue(backend, out InputBackendProvider? provider)) + { throw new NotSupportedException("Input backend '" + backend + "' is not registered."); + } return provider.CreateEventSource(window, acceptAllWindows) - ?? throw new InvalidOperationException("Input provider '" + backend + "' returned no service."); + ?? throw new InvalidOperationException("Input provider '" + backend + "' returned no service."); } } - diff --git a/src/adapters/input/Inno.Adapter.Input/InputBackendId.cs b/src/adapters/input/Inno.Adapter.Input/InputBackendId.cs index 7a81b27a4..a3830487b 100644 --- a/src/adapters/input/Inno.Adapter.Input/InputBackendId.cs +++ b/src/adapters/input/Inno.Adapter.Input/InputBackendId.cs @@ -20,8 +20,12 @@ public InputBackendId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } @@ -48,4 +52,3 @@ public InputBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/input/Inno.Adapter.Input/InputBackendProvider.cs b/src/adapters/input/Inno.Adapter.Input/InputBackendProvider.cs index 3e9f958de..3a7945527 100644 --- a/src/adapters/input/Inno.Adapter.Input/InputBackendProvider.cs +++ b/src/adapters/input/Inno.Adapter.Input/InputBackendProvider.cs @@ -24,7 +24,9 @@ public abstract class InputBackendProvider protected InputBackendProvider(InputBackendId id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } @@ -50,4 +52,3 @@ public abstract IInputEventSource CreateEventSource( bool acceptAllWindows ); } - diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs index 43e4e1ec7..5dbdf68b5 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs @@ -30,7 +30,9 @@ public PlatformBackendCatalog(IEnumerable providers) foreach (PlatformBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); } @@ -42,11 +44,13 @@ public PlatformBackendCatalog(IEnumerable providers) /// /// The selected provider returned no service. /// - public IPlatformApplication CreateApplication(PlatformBackendId backend) { + public IPlatformApplication CreateApplication(PlatformBackendId backend) + { if (!m_providers.TryGetValue(backend, out PlatformBackendProvider? provider)) + { throw new NotSupportedException("Platform backend '" + backend + "' is not registered."); + } return provider.CreateApplication() - ?? throw new InvalidOperationException("Platform provider '" + backend + "' returned no service."); + ?? throw new InvalidOperationException("Platform provider '" + backend + "' returned no service."); } } - diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendId.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendId.cs index 1dc421a39..40c18deb0 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendId.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendId.cs @@ -20,8 +20,12 @@ public PlatformBackendId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } @@ -48,4 +52,3 @@ public PlatformBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendProvider.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendProvider.cs index 28b088fab..f21ae1409 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendProvider.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendProvider.cs @@ -24,7 +24,9 @@ public abstract class PlatformBackendProvider protected PlatformBackendProvider(PlatformBackendId id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } @@ -41,4 +43,3 @@ protected PlatformBackendProvider(PlatformBackendId id) /// public abstract IPlatformApplication CreateApplication(); } - diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandleId.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandleId.cs index 72254548a..b8235ff14 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandleId.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandleId.cs @@ -20,8 +20,12 @@ public PlatformNativeHandleId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A native surface identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationContext.cs b/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationContext.cs index 85680d068..00448c9bd 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationContext.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/IPresentationContext.cs @@ -115,5 +115,4 @@ void DrawImage( PresentationTextureHandle texture, Vector2 size ); - } diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs index 8f4987c24..19b2fbdac 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs @@ -29,7 +29,9 @@ public PresentationBackendCatalog(IEnumerable provi foreach (PresentationBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); } @@ -47,8 +49,10 @@ PresentationBackendOptions options ) { ArgumentNullException.ThrowIfNull(options); if (!m_providers.TryGetValue(backend, out PresentationBackendProvider? provider)) + { throw new NotSupportedException("Presentation backend '" + backend + "' is not registered."); + } return provider.CreateContext(options) - ?? throw new InvalidOperationException("Presentation provider '" + backend + "' returned no context."); + ?? throw new InvalidOperationException("Presentation provider '" + backend + "' returned no context."); } } diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendId.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendId.cs index d750462f3..b972117ac 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendId.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendId.cs @@ -20,8 +20,12 @@ public PresentationBackendId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } @@ -48,4 +52,3 @@ public PresentationBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendProvider.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendProvider.cs index eb729c16b..d00a7afc5 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendProvider.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendProvider.cs @@ -19,7 +19,9 @@ public abstract class PresentationBackendProvider protected PresentationBackendProvider(PresentationBackendId id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationFeatures.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationFeatures.cs index 34cad0644..564610aa2 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationFeatures.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationFeatures.cs @@ -12,17 +12,14 @@ public enum PresentationFeatures /// Requests no optional presentation features. /// None = 0, - /// /// Allows the presentation to create detached native windows. /// MultipleWindows = 1 << 0, - /// /// Enables dockable host surfaces when supported. /// Docking = 1 << 1, - /// /// Enables smooth rendering while native windows are being resized. /// diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationTextureHandle.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationTextureHandle.cs index d284d8d5b..f4278ccf2 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationTextureHandle.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationTextureHandle.cs @@ -16,7 +16,9 @@ public readonly record struct PresentationTextureHandle public PresentationTextureHandle(ulong value) { if (value == 0) + { throw new ArgumentOutOfRangeException(nameof(value)); + } this.value = value; } diff --git a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs index 11eb02450..a6b3f0c77 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs @@ -32,11 +32,17 @@ IEnumerable providers ArgumentNullException.ThrowIfNull(runtime); ArgumentNullException.ThrowIfNull(providers); foreach (RenderingAuthoringBackendProvider provider in providers) + { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Authoring providers require unique, assigned backend IDs.", nameof(providers)); + } + } var runtimeIds = new HashSet(runtime.supportedBackends); if (!runtimeIds.SetEquals(m_providers.Keys)) + { throw new ArgumentException("Runtime and authoring rendering providers must register the same backend IDs.", nameof(providers)); + } supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); } @@ -73,6 +79,6 @@ public ITextureTargetCompiler CreateTextureTargetCompiler(RenderingBackendId bac private RenderingAuthoringBackendProvider GetProvider(RenderingBackendId backend) => m_providers.TryGetValue(backend, out RenderingAuthoringBackendProvider? provider) - ? provider - : throw new NotSupportedException($"Rendering authoring backend '{backend}' is not registered."); + ? provider + : throw new NotSupportedException($"Rendering authoring backend '{backend}' is not registered."); } diff --git a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendProvider.cs b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendProvider.cs index e64fe10fd..7e5e4dff3 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendProvider.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendProvider.cs @@ -21,7 +21,9 @@ public abstract class RenderingAuthoringBackendProvider protected RenderingAuthoringBackendProvider(RenderingBackendId id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } diff --git a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs index 867a8a004..7cab6b876 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs @@ -27,7 +27,9 @@ public RenderingBackendCatalog(IEnumerable providers) foreach (RenderingBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Rendering providers require unique, assigned backend IDs.", nameof(providers)); + } } supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); } @@ -58,9 +60,11 @@ RenderingBackendOptions options ) { ArgumentNullException.ThrowIfNull(options); if (!m_providers.TryGetValue(backend, out RenderingBackendProvider? provider)) + { throw new NotSupportedException($"Rendering backend '{backend}' is not registered."); + } return provider.CreateDevice(options) - ?? throw new InvalidOperationException($"Rendering provider '{backend}' returned no device."); + ?? throw new InvalidOperationException($"Rendering provider '{backend}' returned no device."); } /// @@ -78,8 +82,10 @@ RenderingBackendOptions options public IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendId backend) { if (!m_providers.TryGetValue(backend, out RenderingBackendProvider? provider)) + { throw new NotSupportedException($"Rendering backend '{backend}' is not registered."); + } return provider.CreateCompositionProgramProvider() - ?? throw new InvalidOperationException($"Rendering provider '{backend}' returned no composition program provider."); + ?? throw new InvalidOperationException($"Rendering provider '{backend}' returned no composition program provider."); } } diff --git a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendId.cs b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendId.cs index cdb1dffdc..24ada6259 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendId.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendId.cs @@ -20,8 +20,12 @@ public RenderingBackendId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A rendering backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } diff --git a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendProvider.cs b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendProvider.cs index aff6a6519..9f97e4f99 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendProvider.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendProvider.cs @@ -20,7 +20,9 @@ public abstract class RenderingBackendProvider protected RenderingBackendProvider(RenderingBackendId id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } diff --git a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs index 0fe97394e..8c386d9ab 100644 --- a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs +++ b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs @@ -30,7 +30,9 @@ public StorageBackendCatalog(IEnumerable providers) foreach (StorageBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); } @@ -47,11 +49,14 @@ public IApplicationStorage CreateStorage( StorageScope scope ) { if (!scope.isValid) + { throw new ArgumentException("Storage requires an assigned application namespace.", nameof(scope)); + } if (!m_providers.TryGetValue(backend, out StorageBackendProvider? provider)) + { throw new NotSupportedException("Storage backend '" + backend + "' is not registered."); + } return provider.CreateStorage(scope) - ?? throw new InvalidOperationException("Storage provider '" + backend + "' returned no service."); + ?? throw new InvalidOperationException("Storage provider '" + backend + "' returned no service."); } } - diff --git a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendId.cs b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendId.cs index 785d8f680..eaa07edc6 100644 --- a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendId.cs +++ b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendId.cs @@ -20,8 +20,12 @@ public StorageBackendId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } @@ -53,4 +57,3 @@ public StorageBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendProvider.cs b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendProvider.cs index d0eef7d51..cc8af141c 100644 --- a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendProvider.cs +++ b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendProvider.cs @@ -24,7 +24,9 @@ public abstract class StorageBackendProvider protected StorageBackendProvider(StorageBackendId id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } @@ -44,4 +46,3 @@ protected StorageBackendProvider(StorageBackendId id) /// public abstract IApplicationStorage CreateStorage(StorageScope scope); } - diff --git a/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs b/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs index f037f2b29..a573be2ad 100644 --- a/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs +++ b/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs @@ -30,7 +30,9 @@ public TextBackendCatalog(IEnumerable providers) foreach (TextBackendProvider provider in providers) { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); + } } supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); } @@ -42,11 +44,13 @@ public TextBackendCatalog(IEnumerable providers) /// /// The selected provider returned no service. /// - public ITextBackend CreateBackend(TextBackendId backend) { + public ITextBackend CreateBackend(TextBackendId backend) + { if (!m_providers.TryGetValue(backend, out TextBackendProvider? provider)) + { throw new NotSupportedException("Text backend '" + backend + "' is not registered."); + } return provider.CreateBackend() - ?? throw new InvalidOperationException("Text provider '" + backend + "' returned no service."); + ?? throw new InvalidOperationException("Text provider '" + backend + "' returned no service."); } } - diff --git a/src/adapters/text/Inno.Adapter.Text/TextBackendId.cs b/src/adapters/text/Inno.Adapter.Text/TextBackendId.cs index f8dd92386..4025c7029 100644 --- a/src/adapters/text/Inno.Adapter.Text/TextBackendId.cs +++ b/src/adapters/text/Inno.Adapter.Text/TextBackendId.cs @@ -20,8 +20,12 @@ public TextBackendId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } @@ -48,4 +52,3 @@ public TextBackendId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/adapters/text/Inno.Adapter.Text/TextBackendProvider.cs b/src/adapters/text/Inno.Adapter.Text/TextBackendProvider.cs index ef8ca5f34..cd1ebb726 100644 --- a/src/adapters/text/Inno.Adapter.Text/TextBackendProvider.cs +++ b/src/adapters/text/Inno.Adapter.Text/TextBackendProvider.cs @@ -24,7 +24,9 @@ public abstract class TextBackendProvider protected TextBackendProvider(TextBackendId id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } @@ -41,4 +43,3 @@ protected TextBackendProvider(TextBackendId id) /// public abstract ITextBackend CreateBackend(); } - diff --git a/src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs b/src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs index e2e77e94f..21c4e2c64 100644 --- a/src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs +++ b/src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; - using Inno.UI; namespace Inno.Adapter.UI; @@ -23,8 +22,12 @@ public UiBackendCatalog(IEnumerable providers) { ArgumentNullException.ThrowIfNull(providers); foreach (UiBackendProvider provider in providers) + { if (provider is null || !provider.id.isValid || !m_providers.TryAdd(provider.id, provider)) + { throw new ArgumentException("UI providers require unique, assigned backend IDs.", nameof(providers)); + } + } supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } @@ -45,8 +48,10 @@ public UiBackendCatalog(IEnumerable providers) public IUiBackend CreateBackend(UiBackendId backend) { if (!m_providers.TryGetValue(backend, out UiBackendProvider? provider)) + { throw new NotSupportedException($"UI backend '{backend}' is not registered."); + } return provider.CreateBackend() - ?? throw new InvalidOperationException($"UI provider '{backend}' returned no backend."); + ?? throw new InvalidOperationException($"UI provider '{backend}' returned no backend."); } } diff --git a/src/adapters/ui/Inno.Adapter.UI/UiBackendId.cs b/src/adapters/ui/Inno.Adapter.UI/UiBackendId.cs index 3e311057d..0d57b4fe7 100644 --- a/src/adapters/ui/Inno.Adapter.UI/UiBackendId.cs +++ b/src/adapters/ui/Inno.Adapter.UI/UiBackendId.cs @@ -17,8 +17,12 @@ public UiBackendId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A UI backend identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } diff --git a/src/adapters/ui/Inno.Adapter.UI/UiBackendProvider.cs b/src/adapters/ui/Inno.Adapter.UI/UiBackendProvider.cs index bca128eee..1a5fcc58b 100644 --- a/src/adapters/ui/Inno.Adapter.UI/UiBackendProvider.cs +++ b/src/adapters/ui/Inno.Adapter.UI/UiBackendProvider.cs @@ -20,7 +20,9 @@ public abstract class UiBackendProvider protected UiBackendProvider(UiBackendId id) { if (!id.isValid) + { throw new ArgumentException("A provider requires an assigned backend ID.", nameof(id)); + } this.id = id; } diff --git a/src/composition/adapters/Inno.Adapter.Authoring.Default/DefaultAuthoringAdapterCatalog.cs b/src/composition/adapters/Inno.Adapter.Authoring.Default/DefaultAuthoringAdapterCatalog.cs index e31f15168..b0e8756cb 100644 --- a/src/composition/adapters/Inno.Adapter.Authoring.Default/DefaultAuthoringAdapterCatalog.cs +++ b/src/composition/adapters/Inno.Adapter.Authoring.Default/DefaultAuthoringAdapterCatalog.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Adapter.Audio; using Inno.Adapter.Default; using Inno.Adapter.Input; @@ -49,9 +48,7 @@ IEnumerable presentationProviders m_runtime = new DefaultAdapterCatalog(options); ArgumentNullException.ThrowIfNull(presentationProviders); m_presentation = new PresentationBackendCatalog(presentationProviders); - m_renderingAuthoring = new RenderingAuthoringBackendCatalog( - m_runtime.rendering, - authoringProviders); + m_renderingAuthoring = new RenderingAuthoringBackendCatalog(m_runtime.rendering, authoringProviders); } IReadOnlyList IRenderingAuthoringBackendFactory.supportedBackends @@ -102,12 +99,9 @@ IReadOnlyList IRenderingAuthoringBackendFactory.supportedBac /// public IPresentationBackendFactory presentation => m_presentation; - IShaderCompilerToolchain IRenderingAuthoringBackendFactory.CreateShaderCompilerToolchain( - RenderingBackendId backend) + IShaderCompilerToolchain IRenderingAuthoringBackendFactory.CreateShaderCompilerToolchain(RenderingBackendId backend) => m_renderingAuthoring.CreateShaderCompilerToolchain(backend); - ITextureTargetCompiler IRenderingAuthoringBackendFactory.CreateTextureTargetCompiler( - RenderingBackendId backend) + ITextureTargetCompiler IRenderingAuthoringBackendFactory.CreateTextureTargetCompiler(RenderingBackendId backend) => m_renderingAuthoring.CreateTextureTargetCompiler(backend); - } diff --git a/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalog.cs b/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalog.cs index 127c4bf5f..40e35ebf9 100644 --- a/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalog.cs +++ b/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalog.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Adapter.Audio; using Inno.Adapter.Audio.MiniAudio; using Inno.Adapter.Input; diff --git a/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalogOptions.cs b/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalogOptions.cs index 3daf267e6..9a0ee9ae0 100644 --- a/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalogOptions.cs +++ b/src/composition/adapters/Inno.Adapter.Default/DefaultAdapterCatalogOptions.cs @@ -1,6 +1,6 @@ -using Inno.Adapter.Storage; -using Inno.Adapter.Rendering; using Inno.Adapter.Platform; +using Inno.Adapter.Rendering; +using Inno.Adapter.Storage; namespace Inno.Adapter.Default; diff --git a/src/composition/adapters/Inno.Adapter.Default/StandardAdapterSelection.cs b/src/composition/adapters/Inno.Adapter.Default/StandardAdapterSelection.cs index e91ff9bd9..00e6994b5 100644 --- a/src/composition/adapters/Inno.Adapter.Default/StandardAdapterSelection.cs +++ b/src/composition/adapters/Inno.Adapter.Default/StandardAdapterSelection.cs @@ -22,7 +22,8 @@ public static class StandardAdapterSelection /// /// A fully assigned standard selection; its catalog must still be validated before creating resources. /// - public static AdapterSelection Create(StorageBackendId storage) => new() + public static AdapterSelection Create(StorageBackendId storage) + => new() { platform = PlatformBackendId.sdl3, input = InputBackendId.events, diff --git a/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs b/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs index 9780df7f3..aa1ddba59 100644 --- a/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs +++ b/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs @@ -10,8 +10,11 @@ internal static class AnimationSubsystem internal static IRuntimeSubsystemFactory Create(EngineSessionComposition context) => new AnimationRuntimeFactory(owner => { - var reporter = owner.resources.Own(owner.diagnostics.CreateReporter( - new DiagnosticSource($"inno.animation.bindings.{owner.identities.domainId}", "Animation"))); + var reporter = owner.resources.Own( + owner.diagnostics.CreateReporter( + new DiagnosticSource($"inno.animation.bindings.{owner.identities.domainId}", "Animation") + ) + ); var bindings = owner.resources.Own(new AnimationBindingRuntime(owner.types, reporter)); return new AnimationRuntime(owner.events, bindings); }); diff --git a/src/composition/default/Inno.Engine.Default/Audio/AudioSubsystem.cs b/src/composition/default/Inno.Engine.Default/Audio/AudioSubsystem.cs index 9f38f1ac2..b6ffc3277 100644 --- a/src/composition/default/Inno.Engine.Default/Audio/AudioSubsystem.cs +++ b/src/composition/default/Inno.Engine.Default/Audio/AudioSubsystem.cs @@ -17,8 +17,11 @@ private static AudioRuntime CreateRuntime( EngineSessionComposition composition, RuntimeSubsystemContext owner ) { - DiagnosticReporter diagnostics = owner.resources.Own(owner.diagnostics.CreateReporter( - new DiagnosticSource($"inno.audio.{composition.session.sessionId}", "Audio"))); + DiagnosticReporter diagnostics = owner.resources.Own( + owner.diagnostics.CreateReporter( + new DiagnosticSource($"inno.audio.{composition.session.sessionId}", "Audio") + ) + ); IAudioDevice device; try { @@ -26,17 +29,27 @@ RuntimeSubsystemContext owner } catch (Exception exception) { - diagnostics.Publish(new Diagnostic("AUDIO_DEVICE_INIT_FAILED", - $"Audio output could not start; this session is explicitly muted: {exception.Message}", - DiagnosticSeverity.Warning, composition.selection.audio.ToString())); + diagnostics.Publish( + new Diagnostic( + "AUDIO_DEVICE_INIT_FAILED", + $"Audio output could not start; this session is explicitly muted: {exception.Message}", + DiagnosticSeverity.Warning, + composition.selection.audio.ToString() + ) + ); device = new MutedAudioDevice(); } AudioRuntime? runtime = null; try { AudioProjectSettings settings = composition.audioSettings() - ?? throw new InvalidOperationException("The audio settings source returned null."); - runtime = new AudioRuntime(owner.types, device, composition.artifacts, owner.events, diagnostics, + ?? throw new InvalidOperationException("The audio settings source returned null."); + runtime = new AudioRuntime( + owner.types, + device, + composition.artifacts, + owner.events, + diagnostics, new AudioRuntimeOptions { maxVoices = settings.maxVoices, @@ -44,11 +57,16 @@ RuntimeSubsystemContext owner automaticStreamingThresholdBytes = settings.automaticStreamingThresholdBytes }, contentScopeProvider: () => SceneContentSource.CreateScope(composition.session.scenes), - deviceRecoveryFactory: () => composition.adapters.audio.CreateDevice(composition.selection.audio)); + deviceRecoveryFactory: () => composition.adapters.audio.CreateDevice(composition.selection.audio) + ); if (settings.defaultMixer is not null && !runtime.ApplyMixer(settings.defaultMixer)) + { throw new InvalidOperationException("The configured default mixer could not be activated."); + } if (!runtime.SetBusVolume(AudioBusId.master, settings.masterVolume)) + { throw new InvalidOperationException("The configured master volume could not be applied."); + } return runtime; } catch (Exception failure) @@ -56,9 +74,13 @@ RuntimeSubsystemContext owner try { if (runtime is null) + { device.Dispose(); + } else + { runtime.Dispose(); + } } catch (Exception cleanup) { diff --git a/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs b/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs index 275904d01..8e465bcfc 100644 --- a/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs +++ b/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs @@ -65,30 +65,37 @@ public EngineSessionComposition( /// Gets the isolated session selected by the product. /// public RuntimeSession session { get; } + /// /// Gets the backend-neutral adapter factory catalog. /// public IAdapterCatalog adapters { get; } + /// /// Gets portable backend selection values. /// public AdapterSelection selection { get; } + /// /// Gets the host input source shared by isolated session readers. /// public IInputEventSource inputSource { get; } + /// /// Gets immutable encoded content artifacts from the selected host environment. /// public IAssetArtifactLookup artifacts { get; } + /// /// Gets the control-thread source of portable audio defaults. /// public Func audioSettings { get; } + /// /// Gets the factory transferring storage ownership to this session. /// public Func createStorage { get; } + /// /// Gets an optional product-specific audio owner factory. /// diff --git a/src/composition/default/Inno.Engine.Default/Text/TextSubsystem.cs b/src/composition/default/Inno.Engine.Default/Text/TextSubsystem.cs index f4e091d81..cf5014e87 100644 --- a/src/composition/default/Inno.Engine.Default/Text/TextSubsystem.cs +++ b/src/composition/default/Inno.Engine.Default/Text/TextSubsystem.cs @@ -9,5 +9,6 @@ internal static class TextSubsystem internal static IRuntimeSubsystemFactory Create(EngineSessionComposition context) => new TextRuntimeFactory(_ => new TextRuntime( context.adapters.text.CreateBackend(context.selection.text), - context.artifacts)); + context.artifacts + )); } diff --git a/src/composition/default/Inno.Engine.Default/UI/UiSubsystem.cs b/src/composition/default/Inno.Engine.Default/UI/UiSubsystem.cs index 3a85e02dc..33190502d 100644 --- a/src/composition/default/Inno.Engine.Default/UI/UiSubsystem.cs +++ b/src/composition/default/Inno.Engine.Default/UI/UiSubsystem.cs @@ -9,5 +9,6 @@ internal static class UiSubsystem internal static IRuntimeSubsystemFactory Create(EngineSessionComposition context) => new UiRuntimeFactory(_ => new UiRuntime( context.adapters.ui.CreateBackend(context.selection.ui), - context.artifacts)); + context.artifacts + )); } diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs index b4b0c31cf..21f7ed8e7 100644 --- a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs @@ -171,9 +171,13 @@ public RangeAttribute( double maximum ) { if (!double.IsFinite(minimum)) + { throw new ArgumentOutOfRangeException(nameof(minimum)); + } if (!double.IsFinite(maximum) || maximum < minimum) + { throw new ArgumentOutOfRangeException(nameof(maximum)); + } this.minimum = minimum; this.maximum = maximum; } @@ -193,9 +197,7 @@ double maximum /// Makes an otherwise writable serialized property read-only in the Inspector. /// [Conditional("INNO_EDITOR")] -public sealed class InspectorReadOnlyAttribute : InspectorPresentationAttribute -{ -} +public sealed class InspectorReadOnlyAttribute : InspectorPresentationAttribute; /// /// Defines the comparison used by conditional Inspector presentation. @@ -206,37 +208,30 @@ public enum InspectorCondition /// Shows a value when it evaluates as true or non-empty. /// Truthy, - /// /// Shows a value when it evaluates as false, null, or empty. /// Falsy, - /// /// Compares the value with the supplied expected constant. /// Equal, - /// /// Requires the value to differ from the supplied expected constant. /// NotEqual, - /// /// Requires a null value. /// Null, - /// /// Requires a non-null value. /// NotNull, - /// /// Requires a reference-like value to expose an assigned resource. /// Assigned, - /// /// Requires a reference-like value not to expose an assigned resource. /// @@ -256,9 +251,7 @@ public sealed class ShowIfAttribute : InspectorPresentationAttribute /// Sibling field or property name. /// public ShowIfAttribute(string memberName) - : this(memberName, InspectorCondition.Truthy, null) - { - } + : this(memberName, InspectorCondition.Truthy, null) {} /// /// Creates an equality condition. @@ -272,10 +265,7 @@ public ShowIfAttribute(string memberName) public ShowIfAttribute( string memberName, object? expectedValue - ) - : this(memberName, InspectorCondition.Equal, expectedValue) - { - } + ) : this(memberName, InspectorCondition.Equal, expectedValue) {} /// /// Creates a named condition that does not require an expected value. @@ -289,10 +279,7 @@ public ShowIfAttribute( public ShowIfAttribute( string memberName, InspectorCondition condition - ) - : this(memberName, condition, null) - { - } + ) : this(memberName, condition, null) {} private ShowIfAttribute( string memberName, @@ -334,9 +321,7 @@ public sealed class HideIfAttribute : InspectorPresentationAttribute /// Sibling field or property name. /// public HideIfAttribute(string memberName) - : this(memberName, InspectorCondition.Truthy, null) - { - } + : this(memberName, InspectorCondition.Truthy, null) {} /// /// Creates an equality condition. @@ -350,10 +335,7 @@ public HideIfAttribute(string memberName) public HideIfAttribute( string memberName, object? expectedValue - ) - : this(memberName, InspectorCondition.Equal, expectedValue) - { - } + ) : this(memberName, InspectorCondition.Equal, expectedValue) {} /// /// Creates a named condition that does not require an expected value. @@ -367,10 +349,7 @@ public HideIfAttribute( public HideIfAttribute( string memberName, InspectorCondition condition - ) - : this(memberName, condition, null) - { - } + ) : this(memberName, condition, null) {} private HideIfAttribute( string memberName, @@ -408,12 +387,10 @@ public enum InspectorMessageType /// Neutral explanatory information. /// Info, - /// /// A non-blocking configuration warning. /// Warning, - /// /// An invalid or unusable configuration. /// @@ -438,10 +415,7 @@ public sealed class HelpBoxAttribute : InspectorPresentationAttribute public HelpBoxAttribute( string text, InspectorMessageType messageType = InspectorMessageType.Info - ) - : this(text, messageType, string.Empty, InspectorCondition.Truthy, null) - { - } + ) : this(text, messageType, string.Empty, InspectorCondition.Truthy, null) {} /// /// Creates an Inspector help message shown when a sibling satisfies a named condition. @@ -463,10 +437,7 @@ public HelpBoxAttribute( string conditionMember, InspectorCondition condition, InspectorMessageType messageType = InspectorMessageType.Info - ) - : this(text, messageType, conditionMember, condition, null) - { - } + ) : this(text, messageType, conditionMember, condition, null) {} /// /// Creates an Inspector help message shown when a sibling equals a compile-time value. @@ -488,10 +459,7 @@ public HelpBoxAttribute( string conditionMember, object? expectedValue, InspectorMessageType messageType = InspectorMessageType.Info - ) - : this(text, messageType, conditionMember, InspectorCondition.Equal, expectedValue) - { - } + ) : this(text, messageType, conditionMember, InspectorCondition.Equal, expectedValue) {} private HelpBoxAttribute( string text, diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/Properties/ScriptingApi.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/Properties/ScriptingApi.cs index b856737d2..57c54aac7 100644 --- a/src/composition/editor/contracts/Inno.Editor.Annotations/Properties/ScriptingApi.cs +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Annotations; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Annotations", "Inno.Editor.Annotations", ScriptingApiScope.Authoring)] [assembly: ScriptingApiExport(typeof(InspectorPresentationAttribute), ScriptingApiScope.Authoring)] diff --git a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs index faa653ec0..2c5da03bd 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs @@ -53,21 +53,24 @@ public AssetCreationMenuAttribute( ArgumentException.ThrowIfNullOrWhiteSpace(extension); ArgumentException.ThrowIfNullOrWhiteSpace(defaultName); if (extension.Length == 0 || extension[0] != '.' - || extension.IndexOfAny(['/', '\\']) >= 0) - { + || extension.IndexOfAny(['/', '\\']) >= 0 + ) { throw new ArgumentException( "A native source extension beginning with a dot is required.", - nameof(extension)); + nameof(extension) + ); } string normalizedPath = menuPath.Replace('\\', '/').Trim('/'); if (normalizedPath.Length == 0 - || Array.Exists(normalizedPath.Split('/'), static segment => string.IsNullOrWhiteSpace(segment))) - { + || Array.Exists(normalizedPath.Split('/'), static segment => string.IsNullOrWhiteSpace(segment)) + ) { throw new ArgumentException("A valid menu path is required.", nameof(menuPath)); } if (defaultName.IndexOfAny(['/', '\\']) >= 0) + { throw new ArgumentException("The default name cannot contain a path separator.", nameof(defaultName)); + } this.id = id; this.menuPath = normalizedPath; diff --git a/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs b/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs index 46af4351e..50b551990 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs @@ -10,13 +10,15 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Assets; + /// /// Owns detached native asset drafts with shared document, History, recovery and explicit-save semantics. /// /// /// Native source type edited by the consuming feature. /// -public sealed class AssetDraftDocuments : IDisposable where TAsset : AssetObject +public sealed class AssetDraftDocuments : IDisposable + where TAsset : AssetObject { private readonly Dictionary m_drafts = []; private readonly HashSet m_imports = []; @@ -30,6 +32,7 @@ public sealed class AssetDraftDocuments : IDisposable where TAsset : Ass private readonly string m_label; private IDisposable? m_provider; private long m_sourceRevision = -1; + /// /// Creates a feature-owned draft store; call Start after document services become available. /// @@ -70,9 +73,13 @@ string label ArgumentException.ThrowIfNullOrWhiteSpace(historyKind); ArgumentException.ThrowIfNullOrWhiteSpace(label); if (string.IsNullOrWhiteSpace(extension) || !extension.StartsWith('.') || extension.IndexOfAny(['/', '\\']) >= 0) + { throw new ArgumentException("A native file extension is required.", nameof(extension)); + } if (providerId is "." or ".." || providerId.IndexOfAny(['/', '\\', ':']) >= 0) + { throw new ArgumentException("The provider identifier must be a safe single directory name.", nameof(providerId)); + } m_assets = assets; m_interactions = interactions; m_serialization = serialization; @@ -93,6 +100,7 @@ string label /// Read-only presentation state; it contains no live asset or extension objects. /// public Draft GetDraft(Guid assetId) => m_drafts[assetId]; + /// /// Opens a native asset source in the shared document service without revealing a second Inspector. /// @@ -105,9 +113,13 @@ string label public Guid Open(AssetPath path) { if (!path.localPath.EndsWith(m_extension, StringComparison.OrdinalIgnoreCase)) + { throw new ArgumentException("The source extension does not belong to this document provider.", nameof(path)); + } if (!m_assets.TryGetInfo(path, out AssetInfo? info) || info is null) + { throw new IOException("The asset identity is unavailable."); + } m_interactions.documents.Open(path.ToString(), info.persistentId); return info.persistentId; } @@ -122,6 +134,7 @@ public Guid Open(AssetPath path) /// A detached editable asset whose changes have not been published. /// public TAsset Read(Guid assetId) => m_sources.Decode(m_drafts[assetId].bytes); + /// /// Updates the open draft through shared History without saving or publishing a runtime asset. /// @@ -141,7 +154,9 @@ public void Replace( ) { Draft draft = m_drafts[assetId]; if (draft.readOnly) + { throw new InvalidOperationException("Copy this installed asset to the project before editing."); + } RecordReplace(draft, m_sources.Encode(candidate), mergeKey); } @@ -163,13 +178,17 @@ public void ReplaceMany( foreach (var pair in candidates) { if (m_drafts[pair.Key].readOnly) + { throw new InvalidOperationException("The selection contains a read-only asset."); + } encoded.Add(pair.Key, m_sources.Encode(pair.Value)); } using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction("Edit " + m_label + " Selection"); foreach (var pair in encoded) + { RecordReplace(m_drafts[pair.Key], pair.Value, mergeKey); + } transaction.Commit(); } @@ -180,7 +199,9 @@ private void RecordReplace( ) { byte[] before = draft.bytes; if (before.AsSpan().SequenceEqual(next)) + { return; + } var payload = new ChangeData { assetId = draft.id, @@ -225,18 +246,26 @@ out EditorHistoryChange? merged ) { merged = null; if (older.kind != m_historyKind || newer.kind != m_historyKind || older.mergeKey is null || older.mergeKey != newer.mergeKey) + { return false; + } ChangeData first = m_serialization.Deserialize(older.payload.ReadBytes()); ChangeData last = m_serialization.Deserialize(newer.payload.ReadBytes()); if (first.assetId != last.assetId || !first.after.AsSpan().SequenceEqual(last.before)) + { return false; + } var combined = new ChangeData { assetId = first.assetId, before = first.before, after = last.after }; - merged = new EditorHistoryChange(m_historyKind, EditorHistoryPayload.FromBytes(m_serialization.Serialize(combined)), older.mergeKey); + merged = new EditorHistoryChange( + m_historyKind, + EditorHistoryPayload.FromBytes(m_serialization.Serialize(combined)), + older.mergeKey + ); return true; } @@ -255,7 +284,9 @@ EditorHistoryDirection direction ) { ChangeData data = m_serialization.Deserialize(change.payload.ReadBytes()); if (!m_drafts.ContainsKey(data.assetId)) + { throw new InvalidOperationException("Reopen the asset document to use its history."); + } } /// @@ -282,10 +313,14 @@ EditorHistoryDirection direction ) { ChangeData data = m_serialization.Deserialize(change.payload.ReadBytes()); if (!m_drafts.TryGetValue(data.assetId, out Draft? draft)) + { throw new InvalidOperationException("Reopen the asset document to use its history."); + } byte[] expected = direction == EditorHistoryDirection.Undo ? data.after : data.before; if (!draft.bytes.AsSpan().SequenceEqual(expected)) + { throw new InvalidOperationException("The asset draft changed outside this history entry."); + } return (draft, data); } @@ -302,10 +337,14 @@ private void Changed(Draft draft) AtomicFile.WriteAllBytes( RecoveryPath(draft.id), - m_serialization.Serialize(new Recovery { assetId = draft.id, hash = draft.hash, baseline = draft.baseline, bytes = draft.bytes }) + m_serialization.Serialize( + new Recovery { assetId = draft.id, hash = draft.hash, baseline = draft.baseline, bytes = draft.bytes } + ) ); if (draft.error.StartsWith("Recovery write failed:", StringComparison.Ordinal)) + { draft.error = ""; + } } catch (Exception error) when (Recoverable(error)) { @@ -356,7 +395,9 @@ private bool Revert(Draft draft) private void RefreshPath(Draft draft) { if (!m_assets.TryGetInfo(draft.id, out AssetInfo? info) || info is null || info.status == AssetImportStatus.Missing) + { throw new IOException("Asset source is missing. Draft and history are retained."); + } draft.path = info.assetPath; m_interactions.documents.UpdateAssetPath(draft.documentId, draft.path.ToString()); } @@ -364,13 +405,21 @@ private void RefreshPath(Draft draft) private void Open(EditorDocumentContext document) { if (m_drafts.ContainsKey(document.assetId)) + { return; + } AssetPath path = AssetPath.Parse(document.assetPath); if (m_assets.TryGetInfo(document.assetId, out AssetInfo? info) && info is not null) + { path = info.assetPath; - Recovery? recovery = File.Exists(RecoveryPath(document.assetId)) ? m_serialization.Deserialize(File.ReadAllBytes(RecoveryPath(document.assetId))) : null; + } + Recovery? recovery = File.Exists(RecoveryPath(document.assetId)) + ? m_serialization.Deserialize(File.ReadAllBytes(RecoveryPath(document.assetId))) + : null; if (recovery is not null && recovery.assetId != document.assetId) + { throw new InvalidDataException("Asset recovery identity does not match its document."); + } AssetSourceSnapshot? source = null; try { @@ -390,10 +439,14 @@ private void Open(EditorDocumentContext document) source?.isReadOnly ?? true ); if (recovery is not null && source?.contentHash != recovery.hash) + { draft.error = "Source changed externally. Recovery retained; resolve or Revert explicitly."; + } m_drafts.Add(draft.id, draft); if (draft.isDirty) + { m_interactions.documents.SetDirty(draft.documentId); + } } /// @@ -402,7 +455,9 @@ private void Open(EditorDocumentContext document) public void Start() { if (m_provider is not null) + { throw new InvalidOperationException("This draft provider is already started."); + } m_provider = m_interactions.documents.RegisterProvider(new Provider(this)); } @@ -418,29 +473,31 @@ public void Update() { if (!m_assets.Import(path)) { - string diagnostics = m_assets.TryGetInfo( - path, - out AssetInfo? info - ) - && info is not null ? string.Join( - "\n", - info.diagnostics - ) : "The asset importer did not publish this asset."; + string diagnostics = m_assets.TryGetInfo(path, out AssetInfo? info) + && info is not null + ? string.Join("\n", info.diagnostics) + : "The asset importer did not publish this asset."; foreach (Draft draft in m_drafts.Values.Where(value => value.path == path)) + { draft.error = "Saved; import failed: " + diagnostics; + } } } catch (Exception error) when (Recoverable(error)) { foreach (Draft draft in m_drafts.Values.Where(value => value.path == path)) + { draft.error = "Saved; import failed: " + error.Message; + } } } if (m_sourceRevision != m_assets.revision) { foreach (Draft draft in m_drafts.Values) + { SynchronizeSource(draft); + } m_sourceRevision = m_assets.revision; } } @@ -453,7 +510,9 @@ private void SynchronizeSource(Draft draft) AssetSourceSnapshot source = m_sources.Read(draft.path); draft.readOnly = source.isReadOnly; if (draft.hash == source.contentHash) + { return; + } if (draft.isDirty) { draft.error = "Source changed externally. Your draft is retained; Revert reloads it without overwriting the external edit."; @@ -480,23 +539,31 @@ public void Dispose() foreach (Draft draft in m_drafts.Values) { if (draft.isDirty) + { Changed(draft); + } } m_provider?.Dispose(); m_provider = null; } - private string RecoveryPath(Guid id) => Path.Combine(m_assets.libraryRoot, "Editor", "AssetDrafts", m_providerId, id.ToString("N") + ".inno"); + private string RecoveryPath(Guid id) + => Path.Combine(m_assets.libraryRoot, "Editor", "AssetDrafts", m_providerId, id.ToString("N") + ".inno"); + private void DeleteRecovery(Guid id) { string path = RecoveryPath(id); if (File.Exists(path)) + { File.Delete(path); + } } - private static bool Recoverable(Exception error) => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException - && Inno.Core.Execution.RetirementPendingException.Find(error) is null; + private static bool Recoverable(Exception error) + => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException + && Inno.Core.Execution.RetirementPendingException.Find(error) is null; + private sealed class Provider(AssetDraftDocuments owner) : EditorDocumentProvider { /// @@ -514,6 +581,7 @@ private sealed class Provider(AssetDraftDocuments owner) : EditorDocumen /// when the documented condition is satisfied; otherwise, . /// public override bool CanOpen(string assetPath) => assetPath.EndsWith(owner.m_extension, StringComparison.OrdinalIgnoreCase); + /// /// Opens the requested resource and establishes its active lifetime. /// @@ -521,6 +589,7 @@ private sealed class Provider(AssetDraftDocuments owner) : EditorDocumen /// The operation scope that provides state, services, and ownership boundaries. /// public override void Open(EditorDocumentContext context) => owner.Open(context); + /// /// Persists the supplied value through the configured storage contract. /// @@ -531,6 +600,7 @@ private sealed class Provider(AssetDraftDocuments owner) : EditorDocumen /// when the documented condition is satisfied; otherwise, . /// public override bool Save(EditorDocumentContext context) => owner.Save(owner.m_drafts[context.assetId]); + /// /// Restores the draft from the latest imported asset state. /// @@ -541,6 +611,7 @@ private sealed class Provider(AssetDraftDocuments owner) : EditorDocumen /// when the documented condition is satisfied; otherwise, . /// public override bool Revert(EditorDocumentContext context) => owner.Revert(owner.m_drafts[context.assetId]); + /// /// Closes the active resource and releases its operation-scoped state. /// @@ -562,6 +633,7 @@ public sealed class Draft internal byte[] bytes; internal byte[] baseline; internal string hash; + internal Draft( Guid id, Guid documentId, @@ -584,22 +656,27 @@ bool readOnly /// Gets the persistent source identity. /// public Guid id { get; } + /// /// Gets the shared document identity used for Save/Revert and close confirmation. /// public Guid documentId { get; } + /// /// Gets the current resolved source path. /// public AssetPath path { get; internal set; } + /// /// Gets whether this source is installed read-only content. /// public bool readOnly { get; internal set; } + /// /// Gets the latest source, save or import diagnostic. /// public string error { get; internal set; } = ""; + /// /// Gets whether detached bytes differ from the saved baseline. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetCreationRegistry.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetCreationRegistry.cs index a6f4895c8..c275f2274 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetCreationRegistry.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetCreationRegistry.cs @@ -7,11 +7,11 @@ using Inno.Extensibility.Types; namespace Inno.Editor.Assets; + internal sealed class AssetCreationRegistry : TypeRegistry { - internal AssetCreationRegistry(TypeCatalog types) : base(types) - { - } + internal AssetCreationRegistry(TypeCatalog types) + : base(types) {} internal IReadOnlyList templates => current.registrations; @@ -19,6 +19,7 @@ internal bool TryGet( string id, out Registration? registration ) => current.byId.TryGetValue(id, out registration); + /// /// Builds a validated result from the current immutable input snapshot. /// @@ -33,27 +34,37 @@ protected override Snapshot Build(TypeCacheSnapshot types) var registrations = new List(); var byId = new Dictionary(StringComparer.Ordinal); var byMenuPath = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (Type type in types.GetSubTypesOf().Select(typeRef => typeRef.Resolve(types)).Where(static type => !type.IsAbstract).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - )) - { - AssetCreationMenuAttribute declaration = type.GetCustomAttribute(false) ?? throw new InvalidOperationException($"Asset creation template '{type.FullName}' requires " + $"'{typeof(AssetCreationMenuAttribute).FullName}' source metadata."); + foreach (Type type in types + .GetSubTypesOf() + .Select(typeRef => typeRef.Resolve(types)) + .Where(static type => !type.IsAbstract) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { + AssetCreationMenuAttribute declaration = type.GetCustomAttribute(false) + ?? throw new InvalidOperationException( + $"Asset creation template '{type.FullName}' requires " + $"'{typeof(AssetCreationMenuAttribute).FullName}' source metadata." + ); AssetCreationTemplate template = CreateExtension(type); if (!typeof(AssetObject).IsAssignableFrom(template.assetType) || template.assetType.IsAbstract) { - throw new InvalidOperationException($"Asset creation template '{type.FullName}' declares invalid asset type " + $"'{template.assetType.FullName}'."); + throw new InvalidOperationException( + $"Asset creation template '{type.FullName}' declares invalid asset type " + $"'{template.assetType.FullName}'." + ); } var registration = new Registration(type, template, declaration); if (!byId.TryAdd(declaration.id, registration)) { - throw new InvalidOperationException($"Asset creation template id '{declaration.id}' is registered by both " + $"'{byId[declaration.id].implementationType.FullName}' and '{type.FullName}'."); + throw new InvalidOperationException( + $"Asset creation template id '{declaration.id}' is registered by both " + $"'{byId[declaration.id].implementationType.FullName}' and '{type.FullName}'." + ); } if (!byMenuPath.TryAdd(declaration.menuPath, registration)) { - throw new InvalidOperationException($"Asset creation menu path '{declaration.menuPath}' is registered by both " + $"'{byMenuPath[declaration.menuPath].implementationType.FullName}' and '{type.FullName}'."); + throw new InvalidOperationException( + $"Asset creation menu path '{declaration.menuPath}' is registered by both " + $"'{byMenuPath[declaration.menuPath].implementationType.FullName}' and '{type.FullName}'." + ); } registrations.Add(registration); @@ -75,12 +86,15 @@ protected override Snapshot Build(TypeCacheSnapshot types) /// /// The immutable state snapshot consumed by this operation. /// - protected override void DisposeSnapshot(Snapshot snapshot) => DisposeExtensions(snapshot.registrations.Select(static value => value.template)); + protected override void DisposeSnapshot(Snapshot snapshot) + => DisposeExtensions(snapshot.registrations.Select(static value => value.template)); + internal sealed record Registration( Type implementationType, AssetCreationTemplate template, AssetCreationMenuAttribute declaration ); + internal sealed record Snapshot( Registration[] registrations, IReadOnlyDictionary byId diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs index 7775c5406..6093a69fe 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs @@ -7,6 +7,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Assets; + /// /// Handles asset creation actions in the Editor file browser. /// @@ -26,9 +27,12 @@ public sealed partial class AssetEditingModule /// public AssetFileEntry CreateDirectory(AssetPath parent) { - AssetSourceMount mount = m_pipeline.sourceMounts.SingleOrDefault(source => source.id == parent.source) ?? throw new InvalidOperationException("The asset source mount is unavailable."); + AssetSourceMount mount = m_pipeline.sourceMounts.SingleOrDefault(source => source.id == parent.source) + ?? throw new InvalidOperationException("The asset source mount is unavailable."); if (mount.isReadOnly) + { throw new InvalidOperationException("Installed asset sources are read-only."); + } string prefix = parent.localPath.Length == 0 ? string.Empty : parent.localPath + "/"; int suffix = 0; AssetPath candidate; @@ -51,7 +55,9 @@ public AssetFileEntry CreateDirectory(AssetPath parent) RollbackAndRethrow(failure, () => m_pipeline.Delete(candidate)); } - return m_pipeline.TryGetFileSystemEntry(candidate, out AssetFileEntry entry) ? entry : throw new InvalidOperationException("The created directory was not indexed."); + return m_pipeline.TryGetFileSystemEntry(candidate, out AssetFileEntry entry) + ? entry + : throw new InvalidOperationException("The created directory was not indexed."); } /// @@ -76,14 +82,21 @@ public AssetFileEntry CreateSource( AssetPath path, ReadOnlySpan bytes ) { - AssetSourceMount mount = m_pipeline.sourceMounts.SingleOrDefault(source => source.id == path.source) ?? throw new InvalidOperationException("The asset source mount is unavailable."); + AssetSourceMount mount = m_pipeline.sourceMounts.SingleOrDefault(source => source.id == path.source) + ?? throw new InvalidOperationException("The asset source mount is unavailable."); if (mount.isReadOnly) + { throw new InvalidOperationException("Installed asset sources are read-only."); + } string destination = mount.Resolve(path.localPath); if (!Directory.Exists(Path.GetDirectoryName(destination))) + { throw new IOException("The asset's parent directory does not exist."); + } if (File.Exists(destination + ".imeta")) + { throw new IOException("The new asset path already has an identity sidecar."); + } AtomicFile.WriteAllBytes(destination, bytes, overwrite: false); try { @@ -107,6 +120,8 @@ ReadOnlySpan bytes throw; } - return m_pipeline.TryGetFileSystemEntry(path, out AssetFileEntry entry) ? entry : throw new InvalidOperationException("The created asset was not indexed."); + return m_pipeline.TryGetFileSystemEntry(path, out AssetFileEntry entry) + ? entry + : throw new InvalidOperationException("The created asset was not indexed."); } } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Selection.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Selection.cs index 7b440e600..be1d1e825 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Selection.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Selection.cs @@ -7,6 +7,7 @@ using Inno.Scripting.Api; namespace Inno.Editor.Assets; + /// /// Applies validated selection operations through the authoritative asset and History owners. /// @@ -32,21 +33,23 @@ IReadOnlyList targets ArgumentNullException.ThrowIfNull(editor); ArgumentNullException.ThrowIfNull(targets); if (targets.Count == 0) + { return AssetOperationValidation.Invalid("The selection contains unavailable entries."); + } foreach (AssetFileEntry target in targets) { if (target.isReadOnly || target.identity.runtimeIdentity is null - || !TryCreateContext( - editor, - target.assetPath.ToString(), - out AssetEditorContext? context - ) - || context is null) + || !TryCreateContext(editor, target.assetPath.ToString(), out AssetEditorContext? context) + || context is null + ) { return AssetOperationValidation.Invalid("Every selected source must be available and writable."); + } AssetOperationValidation validation = m_editors.Resolve(context.assetType).ValidateDelete(context); if (!validation.isValid) + { return validation; + } } return AssetOperationValidation.valid; @@ -71,13 +74,19 @@ IReadOnlyList targets ) { AssetOperationValidation validation = ValidateDeleteSelection(editor, targets); if (!validation.isValid) + { throw new InvalidOperationException(validation.message); + } string[] roots = SelectedRoots(targets); using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction("Delete Assets"); foreach (string path in roots) { - if (!TryCreateContext(editor, path, out AssetEditorContext? context) || context is null || !DeleteWithHistory(context, m_interactions.history)) + if (!TryCreateContext(editor, path, out AssetEditorContext? context) + || context is null + || !DeleteWithHistory(context, m_interactions.history) + ) { throw new InvalidOperationException($"Selected source '{path}' could not be deleted."); + } } transaction.Commit(); @@ -102,11 +111,17 @@ string targetDirectory ) { ArgumentNullException.ThrowIfNull(targets); if (targets.Count == 0 || targets.Any(value => value.isReadOnly || value.identity.runtimeIdentity is null)) + { return false; + } var destinations = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (string source in SelectedRoots(targets)) + { if (!TryPrepareMove(source, targetDirectory, true, out _, out _, out string destination) || !destinations.Add(destination)) + { return false; + } + } return true; } @@ -128,17 +143,23 @@ public void MoveSelection( string targetDirectory ) { if (!CanMoveSelection(targets, targetDirectory)) + { throw new InvalidOperationException("The selected assets cannot move to this directory."); + } string[] roots = SelectedRoots(targets); using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction("Move Assets"); foreach (string source in roots) + { _ = MoveToDirectoryWithHistory(source, targetDirectory, m_interactions.history); + } transaction.Commit(); } private static string[] SelectedRoots(IReadOnlyList targets) { string[] paths = targets.Select(value => value.assetPath.ToString()).Distinct(StringComparer.Ordinal).ToArray(); - return paths.Where(path => !paths.Any(parent => parent != path && path.StartsWith(parent + "/", StringComparison.Ordinal))).ToArray(); + return paths + .Where(path => !paths.Any(parent => parent != path && path.StartsWith(parent + "/", StringComparison.Ordinal))) + .ToArray(); } } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs index 6f10882ca..ff5e496c7 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs @@ -6,13 +6,14 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Editor.Core; using Inno.Editor.Assets; +using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Plugins.Authoring; namespace Inno.Editor.Assets; + /// /// Owns source mutations, asset extension dispatch and neutral shared-history records independently of presentation. /// @@ -26,6 +27,7 @@ public sealed partial class AssetEditingModule : EditorModule private readonly Logger m_log; private readonly PluginEnvironment m_plugins; private EditorContext? m_context; + /// /// Creates the asset editing service for one authoring generation. /// @@ -75,10 +77,12 @@ LogRouter logs /// [Inno.Scripting.Api.ScriptingApiIgnore] public AssetPipeline pipeline => m_pipeline; + /// /// Gets the current immutable creation menu declarations without retaining template instances. /// - public IReadOnlyList creationTemplates => m_creations.templates.Select(static registration => registration.declaration).ToArray(); + public IReadOnlyList creationTemplates + => m_creations.templates.Select(static registration => registration.declaration).ToArray(); /// /// Checks that a creation template and writable destination are available. @@ -98,10 +102,14 @@ public bool CanCreateAsset( string templateId ) { if (!m_pipeline.isInitialized || !m_creations.TryGet(templateId, out _)) + { return false; + } AssetPath path = AssetPath.Parse(directory); AssetSourceMount? mount = m_pipeline.sourceMounts.FirstOrDefault(source => source.id == path.source); - return mount is { isReadOnly: false } && (string.IsNullOrEmpty(path.localPath) || m_pipeline.TryGetFileSystemEntry(path, out AssetFileEntry entry) && entry.isDirectory); + return mount is { isReadOnly: false } + && (string.IsNullOrEmpty(path.localPath) + || m_pipeline.TryGetFileSystemEntry(path, out AssetFileEntry entry) && entry.isDirectory); } /// @@ -127,13 +135,17 @@ string templateId } if (!CanCreateAsset(directory, templateId)) + { throw new InvalidOperationException("The selected Asset directory is not writable."); + } AssetCreationMenuAttribute declaration = registration.declaration; AssetPath parent = AssetPath.Parse(directory); AssetSourceMount mount = m_pipeline.sourceMounts.Single(source => source.id == parent.source); string prefix = parent.localPath.TrimEnd('/'); if (prefix.Length != 0) + { prefix += "/"; + } int suffix = 1; AssetPath path; do @@ -143,10 +155,13 @@ string templateId suffix++; } while (File.Exists(mount.Resolve(path.localPath)) || File.Exists(mount.Resolve(path.localPath) + ".imeta")); - AssetObject candidate = registration.template.Create() ?? throw new InvalidOperationException($"Asset creation template '{templateId}' returned no asset."); + AssetObject candidate = registration.template.Create() + ?? throw new InvalidOperationException($"Asset creation template '{templateId}' returned no asset."); if (candidate.GetType() != registration.template.assetType) { - throw new InvalidOperationException($"Asset creation template '{templateId}' returned '{candidate.GetType().FullName}' " + $"instead of '{registration.template.assetType.FullName}'."); + throw new InvalidOperationException( + $"Asset creation template '{templateId}' returned '{candidate.GetType().FullName}' " + $"instead of '{registration.template.assetType.FullName}'." + ); } AssetSourceStore sources = m_pipeline.CreateSourceStore(); @@ -168,6 +183,7 @@ string templateId /// [Inno.Scripting.Api.ScriptingApiIgnore] public bool IsPluginSource(AssetSourceId source) => m_plugins.TryGet(source, out _); + /// /// Determines whether an indexed entry is the root of an installed Plugin. /// @@ -213,7 +229,16 @@ out AssetEditorContext? context _ = m_pipeline.TryGetInfo(AssetPath.Parse(relativePath), out AssetInfo? info); _ = m_pipeline.TryGetAssetType(AssetPath.Parse(relativePath), out Type? assetType); - context = new AssetEditorContext(editor, m_interactions, entry.assetPath.ToString(), entry.name, entry.isDirectory, info, assetType, () => CreateDefaultDragData(entry)); + context = new AssetEditorContext( + editor, + m_interactions, + entry.assetPath.ToString(), + entry.name, + entry.isDirectory, + info, + assetType, + () => CreateDefaultDragData(entry) + ); return true; } @@ -231,7 +256,9 @@ public bool Open(AssetEditorContext context) { AssetEditor editor = m_editors.Resolve(context.assetType); if (!editor.CanOpen(context)) + { return false; + } try { editor.Open(context); @@ -280,17 +307,37 @@ public void Rename( string newName ) { AssetEditor editor = m_editors.Resolve(context.assetType); - AssetOperationValidation validation = ValidateRename(editor, context, Normalize(context.relativePath), newName, validateEditor: false, out string targetPath); + AssetOperationValidation validation = ValidateRename( + editor, + context, + Normalize(context.relativePath), + newName, + validateEditor: false, + out string targetPath + ); if (!validation.isValid) + { throw new InvalidOperationException(validation.message); + } string sourcePath = Normalize(context.relativePath); EditorHistoryResult result = MoveAsset(editor, context, sourcePath, targetPath); if (!result.succeeded) + { throw new InvalidOperationException(result.message); - var data = new AssetHistoryData(AssetHistoryOperationKind.Move, sourcePath, targetPath, isDirectory: context.isDirectory, archive: []); + } + var data = new AssetHistoryData( + AssetHistoryOperationKind.Move, + sourcePath, + targetPath, + isDirectory: context.isDirectory, + archive: [] + ); try { - m_interactions.history.RecordApplied("Rename Asset", new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode()))); + m_interactions.history.RecordApplied( + "Rename Asset", + new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode())) + ); } catch (Exception exception) { @@ -315,6 +362,7 @@ public bool CanMoveToDirectory( string sourcePath, string targetDirectory ) => TryPrepareMove(sourcePath, targetDirectory, validateEditor: true, out _, out _, out _); + /// /// Moves a source and records the committed mutation in the supplied history. /// @@ -346,19 +394,24 @@ IEditorHistory history out string targetPath ) || context is null - || editor is null) - { + || editor is null + ) { throw new InvalidOperationException($"Asset '{sourcePath}' cannot be moved to '{targetDirectory}'."); } string normalizedSource = Normalize(sourcePath); EditorHistoryResult result = MoveAsset(editor, context, normalizedSource, targetPath); if (!result.succeeded) + { throw new InvalidOperationException(result.message); + } var data = new AssetHistoryData(AssetHistoryOperationKind.Move, normalizedSource, targetPath, context.isDirectory, archive: []); try { - history.RecordApplied("Move Asset", new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode()))); + history.RecordApplied( + "Move Asset", + new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode())) + ); } catch (Exception exception) { @@ -416,15 +469,29 @@ IEditorHistory history ArgumentNullException.ThrowIfNull(asset); byte[] archive = AssetSourceArchive.Capture(m_pipeline, asset.relativePath, out bool isDirectory); if (!Delete(asset)) + { return false; - var data = new AssetHistoryData(AssetHistoryOperationKind.Delete, Normalize(asset.relativePath), string.Empty, isDirectory, archive); + } + var data = new AssetHistoryData( + AssetHistoryOperationKind.Delete, + Normalize(asset.relativePath), + string.Empty, + isDirectory, + archive + ); try { - history.RecordApplied("Delete Asset", new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode()))); + history.RecordApplied( + "Delete Asset", + new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode())) + ); } catch (Exception exception) { - RollbackAndRethrow(exception, () => AssetSourceArchive.Restore(m_pipeline, Normalize(asset.relativePath), isDirectory, archive)); + RollbackAndRethrow( + exception, + () => AssetSourceArchive.Restore(m_pipeline, Normalize(asset.relativePath), isDirectory, archive) + ); } return true; @@ -436,20 +503,28 @@ string targetPath ) { EditorContext editorContext = m_context ?? throw new InvalidOperationException("Asset editor module is not attached."); if (!TryCreateContext(editorContext, sourcePath, out AssetEditorContext? context) || context is null) + { throw new InvalidOperationException($"Asset '{sourcePath}' is no longer available."); + } AssetEditor editor = m_editors.Resolve(context.assetType); EditorHistoryResult result = MoveAsset(editor, context, sourcePath, targetPath); if (!result.succeeded) + { throw new InvalidOperationException(result.message); + } } internal void DeleteFromHistory(string relativePath) { EditorContext editorContext = m_context ?? throw new InvalidOperationException("Asset editor module is not attached."); if (!TryCreateContext(editorContext, relativePath, out AssetEditorContext? context) || context is null) + { throw new InvalidOperationException($"Asset '{relativePath}' is no longer available."); + } if (!Delete(context)) + { throw new InvalidOperationException($"Asset '{relativePath}' could not be deleted."); + } } /// @@ -535,7 +610,9 @@ out string targetPath newName = newName.Trim(); targetPath = string.Empty; if (string.IsNullOrEmpty(newName)) + { return AssetOperationValidation.Invalid("An asset name is required."); + } if (newName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || newName.Contains('/') || newName.Contains('\\')) { return AssetOperationValidation.Invalid("Asset names cannot contain path separators or invalid file-name characters."); @@ -544,8 +621,9 @@ out string targetPath string renamedEntry = context.isDirectory ? newName : newName + Path.GetExtension(sourcePath); string parent = Normalize(Path.GetDirectoryName(sourcePath)); targetPath = string.IsNullOrEmpty(parent) ? renamedEntry : $"{parent}/{renamedEntry}"; - if (!string.Equals(sourcePath, targetPath, StringComparison.OrdinalIgnoreCase) && m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _)) - { + if (!string.Equals(sourcePath, targetPath, StringComparison.OrdinalIgnoreCase) + && m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _) + ) { return AssetOperationValidation.Invalid($"Asset '{targetPath}' already exists."); } @@ -573,28 +651,38 @@ out string targetPath } EditorContext? editorContext = m_context; - if (editorContext is null || string.IsNullOrEmpty(source) || !TryCreateContext(editorContext, source, out context) || context is null) - { + if (editorContext is null + || string.IsNullOrEmpty(source) + || !TryCreateContext(editorContext, source, out context) + || context is null + ) { return false; } - if (!string.IsNullOrEmpty(directory) && (!m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(directory), out AssetFileEntry destination) || !destination.isDirectory)) - { + if (!string.IsNullOrEmpty(directory) + && (!m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(directory), out AssetFileEntry destination) || !destination.isDirectory) + ) { return false; } string parent = Normalize(Path.GetDirectoryName(source)); if (string.Equals(parent, directory, StringComparison.OrdinalIgnoreCase)) - return false; - if (context.isDirectory && (string.Equals(source, directory, StringComparison.OrdinalIgnoreCase) || directory.StartsWith(source + "/", StringComparison.OrdinalIgnoreCase))) { return false; } + if (context.isDirectory + && (string.Equals(source, directory, StringComparison.OrdinalIgnoreCase) + || directory.StartsWith(source + "/", StringComparison.OrdinalIgnoreCase)) + ) { + return false; + } string name = Path.GetFileName(source); targetPath = string.IsNullOrEmpty(directory) ? name : $"{directory}/{name}"; if (m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _)) + { return false; + } editor = m_editors.Resolve(context.assetType); return !validateEditor || editor.ValidateRename(context, targetPath).isValid; } @@ -626,7 +714,9 @@ string targetPath ) { EditorHistoryResult result = MoveAsset(editor, context, sourcePath, targetPath); if (!result.succeeded) + { throw new InvalidOperationException(result.message); + } } private static void RollbackAndRethrow( @@ -639,13 +729,20 @@ Action rollback } catch (Exception rollbackException) { - throw new AggregateException("An Asset mutation could not be recorded and its compensation also failed.", failure, rollbackException); + throw new AggregateException( + "An Asset mutation could not be recorded and its compensation also failed.", + failure, + rollbackException + ); } ExceptionDispatchInfo.Capture(failure).Throw(); } - private static EditorValidationResult ToEditorValidation(AssetOperationValidation validation) => new(validation.isValid, validation.message); + private static EditorValidationResult ToEditorValidation(AssetOperationValidation validation) + => new(validation.isValid, validation.message); + private static string Normalize(string? path) => string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim('/'); + private static EditorDragData CreateDefaultDragData(AssetFileEntry entry) => new(entry, entry.name); } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditor.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditor.cs index 97199c762..a2a47b16a 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditor.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditor.cs @@ -1,6 +1,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Assets; + /// /// Customizes editor interactions for one imported asset type. /// @@ -16,15 +17,14 @@ public abstract class AssetEditor /// when can handle the entry; otherwise, . /// public virtual bool CanOpen(AssetEditorContext context) => false; + /// /// Opens the supplied asset entry when no more specific typed open action handled it. /// /// /// The immutable source and catalog snapshot for the operation. /// - public virtual void Open(AssetEditorContext context) - { - } + public virtual void Open(AssetEditorContext context) {} /// /// Validates a requested asset move before the AssetPipeline transaction begins. @@ -42,6 +42,7 @@ public virtual AssetOperationValidation ValidateRename( AssetEditorContext context, string targetPath ) => AssetOperationValidation.valid; + /// /// Runs after an asset move transaction commits successfully. /// @@ -58,8 +59,7 @@ public virtual void OnRenamed( AssetEditorContext context, string oldPath, string newPath - ) { - } + ) {} /// /// Validates a requested asset deletion before the AssetPipeline transaction begins. @@ -71,15 +71,14 @@ string newPath /// A valid result when the transaction may proceed, or a diagnostic describing the rejection. /// public virtual AssetOperationValidation ValidateDelete(AssetEditorContext context) => AssetOperationValidation.valid; + /// /// Runs after an asset deletion transaction commits successfully. /// /// /// The immutable snapshot captured before the entry was deleted. /// - public virtual void OnDeleted(AssetEditorContext context) - { - } + public virtual void OnDeleted(AssetEditorContext context) {} /// /// Gets whether the supplied entry can begin a managed editor drag operation. @@ -91,6 +90,7 @@ public virtual void OnDeleted(AssetEditorContext context) /// when drag data can be created; otherwise, . /// public virtual bool CanStartDrag(AssetEditorContext context) => true; + /// /// Creates the managed source, preview label, and validity predicate for an asset drag. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorAttribute.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorAttribute.cs index c770bfcf0..9a78e4c93 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorAttribute.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorAttribute.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.Assets; + /// /// Associates an asset editor with an imported asset type. /// @@ -36,10 +37,12 @@ public AssetEditorAttribute( /// Gets the imported asset type handled by the editor. /// public Type assetType { get; } + /// /// Gets whether derived asset types are accepted. /// public bool useForChildren { get; } + /// /// Gets the tie-breaking priority. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorContext.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorContext.cs index 4d5c0fc25..008b7dfb1 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorContext.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorContext.cs @@ -4,12 +4,14 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Assets; + /// /// Provides an immutable snapshot for an asset editor operation. /// public sealed class AssetEditorContext { private readonly Func m_createDefaultDragData; + /// /// Creates an immutable snapshot used by one asset-editor operation. /// @@ -64,26 +66,32 @@ Func createDefaultDragData /// Gets the shared editor context. /// public EditorContext editorContext { get; } + /// /// Gets the active editor interaction entry point. /// public EditorInteractions interactions { get; } + /// /// Gets the source-relative path. /// public string relativePath { get; } + /// /// Gets the final source path segment. /// public string name { get; } + /// /// Gets whether the source represents a directory. /// public bool isDirectory { get; } + /// /// Gets the cataloged asset information when available. /// public AssetInfo? info { get; } + /// /// Gets the resolved imported asset type when available. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorRegistry.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorRegistry.cs index 36398d252..2bb0f49c1 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorRegistry.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditorRegistry.cs @@ -1,30 +1,37 @@ -using Inno.Editor.Core; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using Inno.Editor.Core; using Inno.Extensibility.Types; namespace Inno.Editor.Assets; + internal sealed class AssetEditorRegistry : TypeRegistry { private static readonly AssetEditor S_DEFAULT_EDITOR = new DefaultAssetEditor(); - internal AssetEditorRegistry(TypeCatalog types) : base(types) - { - } + + internal AssetEditorRegistry(TypeCatalog types) + : base(types) {} internal AssetEditor Resolve(Type? assetType) { if (assetType is null) + { return S_DEFAULT_EDITOR; + } Registration? best = null; int bestDistance = int.MaxValue; foreach (Registration registration in current.registrations) { if (!EditorTypeSpecificity.TryGet(assetType, registration.assetType, out int distance)) + { continue; + } if (distance > 0 && !registration.useForChildren) + { continue; + } if (best is null || distance < bestDistance || distance == bestDistance && registration.priority > best.priority) { best = registration; @@ -51,15 +58,21 @@ protected override Snapshot Build(TypeCacheSnapshot types) foreach (Type type in types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( static value => value.FullName, StringComparer.Ordinal - )) - { + )) { AssetEditor editor = instances.TryGetValue(type, out AssetEditor? existing) ? existing : CreateExtension(type); instances[type] = editor; foreach (AssetEditorAttribute attribute in type.GetCustomAttributes(false)) { - if (registrations.Any(value => value.assetType == attribute.assetType && value.useForChildren == attribute.useForChildren && value.priority == attribute.priority)) - { - throw new InvalidOperationException($"Asset editor registration for '{attribute.assetType.FullName}' conflicts at " + $"priority {attribute.priority}."); + if (registrations.Any( + value => ( + value.assetType == attribute.assetType + && value.useForChildren == attribute.useForChildren + && value.priority == attribute.priority + ) + )) { + throw new InvalidOperationException( + $"Asset editor registration for '{attribute.assetType.FullName}' conflicts at " + $"priority {attribute.priority}." + ); } registrations.Add(new Registration(attribute.assetType, attribute.useForChildren, attribute.priority, type, editor)); @@ -75,8 +88,11 @@ protected override Snapshot Build(TypeCacheSnapshot types) /// /// The immutable state snapshot consumed by this operation. /// - protected override void DisposeSnapshot(Snapshot snapshot) => DisposeExtensions(snapshot.registrations.Select(static registration => registration.editor)); + protected override void DisposeSnapshot(Snapshot snapshot) + => DisposeExtensions(snapshot.registrations.Select(static registration => registration.editor)); + internal sealed record Snapshot(Registration[] registrations); + internal sealed record Registration( Type assetType, bool useForChildren, @@ -84,5 +100,6 @@ internal sealed record Registration( Type implementationType, AssetEditor editor ); + private sealed class DefaultAssetEditor : AssetEditor; } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetOperationValidation.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetOperationValidation.cs index 7715e2c0c..33f41081f 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetOperationValidation.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetOperationValidation.cs @@ -1,4 +1,5 @@ namespace Inno.Editor.Assets; + /// /// Describes whether an editor asset operation may proceed. /// @@ -25,10 +26,12 @@ string message /// Gets whether the operation may proceed. /// public bool isValid { get; } + /// /// Gets the validation diagnostic. /// public string message { get; } + /// /// Gets a successful validation result. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs index 7142d0fb5..6242aa3f6 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs @@ -3,14 +3,14 @@ using System.Text; namespace Inno.Editor.Assets; + internal sealed record AssetHistoryData( AssetHistoryOperationKind operationKind, string sourcePath, string targetPath, bool isDirectory, byte[] archive -) -{ +) { internal byte[] Encode() { using var stream = new MemoryStream(); @@ -31,18 +31,26 @@ internal static AssetHistoryData Decode(ReadOnlySpan bytes) using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); var kind = (AssetHistoryOperationKind)reader.ReadByte(); if (!Enum.IsDefined(kind)) + { throw new InvalidDataException($"Unknown asset history operation kind '{kind}'."); + } string sourcePath = reader.ReadString(); string targetPath = reader.ReadString(); bool isDirectory = reader.ReadBoolean(); int archiveLength = reader.ReadInt32(); if (archiveLength < 0 || archiveLength > stream.Length - stream.Position) + { throw new InvalidDataException("Asset history archive length is invalid."); + } byte[] archive = reader.ReadBytes(archiveLength); if (archive.Length != archiveLength) + { throw new EndOfStreamException("Asset history archive is truncated."); + } if (stream.Position != stream.Length) + { throw new InvalidDataException("Asset history payload contains trailing data."); + } return new AssetHistoryData(kind, sourcePath, targetPath, isDirectory, archive); } } diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryHandler.cs index ee2638df3..aa99e6642 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryHandler.cs @@ -4,6 +4,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Assets; + [EditorHistoryHandler(AssetHistoryKinds.SourceOperation)] internal sealed class AssetHistoryHandler( AssetEditingModule assets, @@ -11,6 +12,7 @@ LogRouter logs ) : EditorHistoryHandler { private readonly Logger m_log = (logs ?? throw new ArgumentNullException(nameof(logs))).CreateLogger(); + /// /// Evaluates whether the requested change can be applied to the current generation. /// @@ -40,7 +42,8 @@ EditorHistoryDirection direction AssetHistoryOperationKind.CreateDirectory => QueryCreateDirectory(data, direction), AssetHistoryOperationKind.Delete => QueryDelete(data, direction), AssetHistoryOperationKind.CreateAsset => QueryCreateAsset(data, direction), - _ => EditorHistoryAvailability.Unavailable("Unknown asset history operation.")}; + _ => EditorHistoryAvailability.Unavailable("Unknown asset history operation.") + }; } catch (Exception exception) { @@ -95,7 +98,9 @@ EditorHistoryDirection direction } if (!result.succeeded) + { return result; + } try { assets.SelectPath(selectionPath); @@ -124,15 +129,18 @@ string targetPath } catch (Exception exception) { - if (!assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(sourcePath), out _) && assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _)) - { + if (!assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(sourcePath), out _) + && assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _) + ) { try { assets.MoveFromHistory(targetPath, sourcePath); } catch (Exception rollbackException) { - return StateIntegrityFailure($"Asset move failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}"); + return StateIntegrityFailure( + $"Asset move failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}" + ); } } @@ -148,12 +156,18 @@ EditorHistoryDirection direction try { if (shouldExist) + { assets.pipeline.CreateDirectory(AssetPath.Parse(data.sourcePath)); + } else + { assets.pipeline.Delete(AssetPath.Parse(data.sourcePath)); + } bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (exists != shouldExist) + { throw new InvalidOperationException("The folder operation did not reach its requested state."); + } return EditorHistoryResult.Success(); } catch (Exception exception) @@ -162,13 +176,19 @@ EditorHistoryDirection direction { bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (shouldExist && exists) + { assets.pipeline.Delete(AssetPath.Parse(data.sourcePath)); + } else if (!shouldExist && !exists) + { assets.pipeline.CreateDirectory(AssetPath.Parse(data.sourcePath)); + } } catch (Exception rollbackException) { - return StateIntegrityFailure($"Asset folder operation failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}"); + return StateIntegrityFailure( + $"Asset folder operation failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); @@ -183,12 +203,18 @@ EditorHistoryDirection direction try { if (shouldExist) + { AssetSourceArchive.Restore(assets.pipeline, data.sourcePath, data.isDirectory, data.archive); + } else + { assets.DeleteFromHistory(data.sourcePath); + } bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (exists != shouldExist) + { throw new InvalidOperationException("The Asset delete operation did not reach its requested state."); + } return EditorHistoryResult.Success(); } catch (Exception exception) @@ -197,13 +223,19 @@ EditorHistoryDirection direction { bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (shouldExist && exists) + { assets.pipeline.Delete(AssetPath.Parse(data.sourcePath)); + } else if (!shouldExist && !exists) + { AssetSourceArchive.Restore(assets.pipeline, data.sourcePath, data.isDirectory, data.archive); + } } catch (Exception rollbackException) { - return StateIntegrityFailure($"Asset delete operation failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}"); + return StateIntegrityFailure( + $"Asset delete operation failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); @@ -218,12 +250,18 @@ EditorHistoryDirection direction try { if (shouldExist) + { AssetSourceArchive.Restore(assets.pipeline, data.sourcePath, data.isDirectory, data.archive); + } else + { assets.DeleteFromHistory(data.sourcePath); + } bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (exists != shouldExist) + { throw new InvalidOperationException("The created Asset did not reach its requested history state."); + } return EditorHistoryResult.Success(); } catch (Exception exception) @@ -232,13 +270,19 @@ EditorHistoryDirection direction { bool exists = assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(data.sourcePath), out _); if (shouldExist && exists) + { assets.DeleteFromHistory(data.sourcePath); + } else if (!shouldExist && !exists) + { AssetSourceArchive.Restore(assets.pipeline, data.sourcePath, data.isDirectory, data.archive); + } } catch (Exception rollbackException) { - return StateIntegrityFailure($"Asset creation history failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}"); + return StateIntegrityFailure( + $"Asset creation history failed: {exception.Message} " + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); @@ -252,7 +296,9 @@ EditorHistoryDirection direction string source = direction == EditorHistoryDirection.Undo ? data.targetPath : data.sourcePath; string target = direction == EditorHistoryDirection.Undo ? data.sourcePath : data.targetPath; if (!assets.pipeline.TryGetFileSystemEntry(AssetPath.Parse(source), out _)) + { return EditorHistoryAvailability.Unavailable($"Asset '{source}' no longer exists."); + } return !assets.pipeline.TryGetFileSystemEntry( AssetPath.Parse(target), out _ @@ -262,31 +308,39 @@ out _ private EditorHistoryAvailability QueryCreateDirectory( AssetHistoryData data, EditorHistoryDirection direction - ) => direction == EditorHistoryDirection.Undo ? assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Folder '{data.sourcePath}' no longer exists.") : !assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Folder '{data.sourcePath}' already exists."); + ) => direction == EditorHistoryDirection.Undo + ? assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Folder '{data.sourcePath}' no longer exists.") + : !assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Folder '{data.sourcePath}' already exists."); + private EditorHistoryAvailability QueryDelete( AssetHistoryData data, EditorHistoryDirection direction - ) => direction == EditorHistoryDirection.Undo ? !assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' already exists.") : assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' no longer exists."); + ) => direction == EditorHistoryDirection.Undo + ? !assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' already exists.") + : assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' no longer exists."); + private EditorHistoryAvailability QueryCreateAsset( AssetHistoryData data, EditorHistoryDirection direction - ) => direction == EditorHistoryDirection.Undo ? assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' no longer exists.") : !assets.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(data.sourcePath), - out _ - ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' already exists."); + ) => direction == EditorHistoryDirection.Undo + ? assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' no longer exists.") + : !assets.pipeline.TryGetFileSystemEntry( + AssetPath.Parse(data.sourcePath), + out _ + ) ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable($"Asset '{data.sourcePath}' already exists."); } diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryKinds.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryKinds.cs index 645f029df..8918d50af 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryKinds.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryKinds.cs @@ -1,4 +1,5 @@ namespace Inno.Editor.Assets; + internal static class AssetHistoryKinds { internal const string SourceOperation = "inno.assets/source-operation"; diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryOperationKind.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryOperationKind.cs index a9a478a7e..57f3ae119 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryOperationKind.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryOperationKind.cs @@ -1,4 +1,5 @@ namespace Inno.Editor.Assets; + internal enum AssetHistoryOperationKind : byte { Move = 1, diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs index ea5a253ae..eab30b895 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs @@ -6,10 +6,12 @@ using Inno.Assets.Pipeline; namespace Inno.Editor.Assets; + internal static class AssetSourceArchive { private const string C_SOURCE_ENTRY = "source"; private const string C_META_ENTRY = "source.imeta"; + internal static byte[] Capture( AssetPipeline assets, string relativePath, @@ -19,7 +21,9 @@ out bool isDirectory string source = GetSourcePath(assets, relativePath); isDirectory = Directory.Exists(source); if (!isDirectory && !File.Exists(source)) + { throw new FileNotFoundException($"Asset source '{relativePath}' does not exist.", source); + } return CapturePhysical(source, isDirectory, CancellationToken.None); } @@ -58,7 +62,9 @@ CancellationToken cancellationToken string meta = source + ".imeta"; if (File.Exists(meta)) + { WriteEntry(archive, meta, C_META_ENTRY, cancellationToken); + } } return stream.ToArray(); @@ -92,10 +98,14 @@ ReadOnlySpan data ArgumentNullException.ThrowIfNull(assets); string target = GetSourcePath(assets, relativePath); if (File.Exists(target) || Directory.Exists(target)) + { throw new IOException($"Asset source '{relativePath}' already exists."); + } string? parent = Path.GetDirectoryName(target); if (!string.IsNullOrEmpty(parent)) + { Directory.CreateDirectory(parent); + } string stagingDirectory = Path.Combine(Path.GetTempPath(), "InnoAssetHistory", Guid.NewGuid().ToString("N")); string stagingSource = Path.Combine(stagingDirectory, C_SOURCE_ENTRY); string stagingMeta = Path.Combine(stagingDirectory, C_META_ENTRY); @@ -114,7 +124,9 @@ ReadOnlySpan data string destination = ResolveDestination(stagingSource, stagingMeta, isDirectory, entry.FullName); string fullDestination = Path.GetFullPath(destination); if (!fullDestination.StartsWith(stagingRoot, StringComparison.Ordinal)) + { throw new InvalidDataException("Asset history archive escapes its staging directory."); + } if (entry.FullName.EndsWith("/", StringComparison.Ordinal)) { Directory.CreateDirectory(fullDestination); @@ -123,13 +135,17 @@ ReadOnlySpan data string? destinationParent = Path.GetDirectoryName(fullDestination); if (!string.IsNullOrEmpty(destinationParent)) + { Directory.CreateDirectory(destinationParent); + } entry.ExtractToFile(fullDestination, overwrite: false); } } if (isDirectory ? !Directory.Exists(stagingSource) : !File.Exists(stagingSource)) + { throw new InvalidDataException("Asset history archive does not contain its source payload."); + } MoveSource(stagingSource, target, isDirectory); sourceCommitted = true; if (File.Exists(stagingMeta)) @@ -144,9 +160,13 @@ ReadOnlySpan data catch { if (metaCommitted && File.Exists(target + ".imeta")) + { File.Move(target + ".imeta", stagingMeta); + } if (sourceCommitted && (isDirectory ? Directory.Exists(target) : File.Exists(target))) + { MoveSource(target, stagingSource, isDirectory); + } if (sourceCommitted) { try @@ -164,7 +184,9 @@ ReadOnlySpan data finally { if (Directory.Exists(stagingDirectory)) + { Directory.Delete(stagingDirectory, recursive: true); + } } } @@ -175,9 +197,13 @@ private static string ResolveDestination( string entryName ) { if (string.Equals(entryName, C_META_ENTRY, StringComparison.Ordinal)) + { return stagingMeta; + } if (!isDirectory && string.Equals(entryName, C_SOURCE_ENTRY, StringComparison.Ordinal)) + { return stagingSource; + } string prefix = C_SOURCE_ENTRY + "/"; if (isDirectory && entryName.StartsWith(prefix, StringComparison.Ordinal)) { @@ -194,7 +220,9 @@ string relativePath string root = Path.GetFullPath(assets.assetRoot) + Path.DirectorySeparatorChar; string result = Path.GetFullPath(Path.Combine(assets.assetRoot, relativePath.Replace('/', Path.DirectorySeparatorChar))); if (!result.StartsWith(root, StringComparison.Ordinal)) + { throw new InvalidDataException($"Asset history path '{relativePath}' escapes the asset root."); + } return result; } @@ -204,8 +232,12 @@ private static void MoveSource( bool isDirectory ) { if (isDirectory) + { Directory.Move(source, target); + } else + { File.Move(source, target); + } } } diff --git a/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs index 28e73c575..30446c334 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs @@ -8,6 +8,7 @@ using Inno.Extensibility.Types; namespace Inno.Editor.Assets; + /// /// Applies importer configuration through the common sidecar pipeline and stable-identity Editor history. /// @@ -19,6 +20,7 @@ public sealed partial class AssetImportSettingsEdits : EditorModule private readonly SerializationRegistry m_serialization; private readonly TypeCatalog m_types; private readonly EditorInteractions m_interactions; + /// /// Uses the authoring owners responsible for source identity, converter generations and shared undo. /// @@ -70,11 +72,17 @@ string expectedFingerprint ArgumentNullException.ThrowIfNull(settings); AssetImportSettingsSnapshot before = m_assets.GetImportSettings(path); if (before.fingerprint != expectedFingerprint) + { throw new IOException("Import settings changed externally. Reload before applying."); + } if (before.value is null || before.value.GetType() != settings.GetType()) + { throw new InvalidOperationException("The importer settings type changed. Reload the editor."); + } if (!m_assets.TryGetPersistentId(path, out Guid id)) + { throw new InvalidOperationException("The source has no persistent identity."); + } var data = new ChangeData { assetId = id, @@ -83,7 +91,9 @@ string expectedFingerprint after = Capture(settings) }; if (data.before.AsSpan().SequenceEqual(data.after)) + { return m_assets.TryGetInfo(id, out AssetInfo? info) && info?.status == AssetImportStatus.Imported; + } bool imported = m_assets.SaveImportSettings(path, settings, expectedFingerprint); var change = new EditorHistoryChange(C_HISTORY, EditorHistoryPayload.FromBytes(m_serialization.Serialize(data))); try @@ -138,19 +148,29 @@ EditorHistoryDirection direction EditorHistoryDirection direction ) { if (!m_assets.TryGetInfo(data.assetId, out AssetInfo? info) || info is null || info.status == AssetImportStatus.Missing) + { throw new IOException("The import-settings source is missing. History is retained until it returns."); + } if (!m_assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) || entry.isReadOnly) + { throw new IOException("The import-settings source is not writable."); + } AssetImportSettingsSnapshot current = m_assets.GetImportSettings(info.assetPath); if (current.value is null || m_types.GetTypeRef(current.value.GetType()).stableId != data.typeId) + { throw new InvalidOperationException("The importer settings extension is unavailable or changed type."); + } byte[] expected = direction == EditorHistoryDirection.Undo ? data.after : data.before; if (!Capture(current.value).AsSpan().SequenceEqual(expected)) + { throw new IOException("Import settings changed outside this history operation."); + } return (info.assetPath, current); } - private byte[] Capture(ISerializable value) => m_serialization.Encode(writer => writer.WriteProperties(value), AssetSerializationContext.Create(m_assets)); + private byte[] Capture(ISerializable value) + => m_serialization.Encode(writer => writer.WriteProperties(value), AssetSerializationContext.Create(m_assets)); + private sealed class ChangeData : ISerializable { [SerializableProperty] @@ -196,7 +216,7 @@ EditorHistoryDirection direction return EditorHistoryAvailability.Available(); } catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { return EditorHistoryAvailability.Unavailable(failure.Message); } @@ -228,7 +248,7 @@ EditorHistoryDirection direction return EditorHistoryResult.Success(); } catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { return EditorHistoryResult.Failure(failure.Message); } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Properties/ScriptingApi.cs b/src/composition/editor/features/Inno.Editor.Assets/Properties/ScriptingApi.cs index b628355d7..84cb17b32 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Properties/ScriptingApi.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Editor.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Assets", "Inno.Editor.Assets", ScriptingApiScope.Editor)] diff --git a/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs b/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs index 7be6f4c3c..6f6432263 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs @@ -1,4 +1,3 @@ -using Inno.Editor.Assets; using System; using System.IO; using System.Linq; @@ -7,12 +6,14 @@ using Inno.Assets.Pipeline; using Inno.Core.Execution; using Inno.Core.Logging; +using Inno.Editor.Assets; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scripting; using Inno.Scripting.Compiler; namespace Inno.Editor.Assets; + /// /// Owns sample import validation, publication and rollback independently of its progress window. /// @@ -33,6 +34,7 @@ public sealed class AssetSampleImportModule : EditorModule private AssetSampleImportProgress m_progress = new(0, 0f, string.Empty, false); private long m_operation; private bool m_acceptProgress; + internal AssetSampleImportModule( AssetEditingModule assets, ScriptCompiler compiler, @@ -49,14 +51,17 @@ LogRouter logs /// Defers later modules while the import pins their generation or requires a Host restart. /// public override bool blocksFollowingUpdates => isBusy || m_faulted; + /// /// Gets whether an import still owns validation or publication work. /// public bool isBusy => !m_faulted && m_import is not null; + /// /// Gets whether the current authoring generation admits a new sample import. /// - public bool canImport => !m_faulted && !isBusy && m_scripting.state is EditorScriptCompilationState.Ready or EditorScriptCompilationState.Failed; + public bool canImport + => !m_faulted && !isBusy && m_scripting.state is EditorScriptCompilationState.Ready or EditorScriptCompilationState.Failed; /// /// Gets a complete immutable progress snapshot under the existing owner lock. @@ -66,7 +71,9 @@ public AssetSampleImportProgress progress get { lock (m_progressLock) + { return m_progress; + } } } @@ -82,7 +89,9 @@ public AssetSampleImportProgress progress public void Request(AssetPath source) { if (!canImport) + { throw new InvalidOperationException("Sample import requires an idle authoring generation."); + } m_import = m_assets.pipeline.PrepareSampleImport(source); m_canceled = false; lock (m_progressLock) @@ -98,10 +107,14 @@ public void Request(AssetPath source) private void CancelCurrent() { if (m_import is null) + { return; + } m_canceled = true; lock (m_progressLock) + { m_progress = m_progress with { status = "Canceling sample import...", cancellationRequested = true }; + } m_import.Cancel(); } @@ -114,7 +127,9 @@ private void CancelCurrent() public void Cancel(long operationId) { if (progress.operationId == operationId) + { CancelCurrent(); + } } /// @@ -126,7 +141,9 @@ public void Cancel(long operationId) protected override void OnUpdate(EditorContext context) { if (!isBusy) + { return; + } try { if (m_canceled || m_failure is not null) @@ -139,7 +156,9 @@ protected override void OnUpdate(EditorContext context) if (!m_validating) { if (!import.Advance()) + { return; + } m_validating = true; SetProgress(0.2f, "Validating sample scripts..."); string physicalSource = Path.Combine(m_assets.pipeline.assetRoot, import.target.localPath); @@ -150,14 +169,30 @@ protected override void OnUpdate(EditorContext context) cancellationToken ) => { - ScriptCompilationResult result = await m_compiler.CompileAuthoringGenerationAsync(new ImportProgress(this, operation), cancellationToken, sources).ConfigureAwait(false); + ScriptCompilationResult result = await m_compiler.CompileAuthoringGenerationAsync( + new ImportProgress(this, operation), + cancellationToken, + sources + ).ConfigureAwait(false); if (!result.success) - throw new InvalidOperationException("Sample script preflight failed:" + Environment.NewLine + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message))); + { + throw new InvalidOperationException( + "Sample script preflight failed:" + + Environment.NewLine + + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message)) + ); + } SetProgress(0.85f, "Preparing sample history...", operation); m_historyPayload = await Task.Run(() => { byte[] archive = AssetSourceArchive.CapturePhysical(physicalSource, isDirectory: true, cancellationToken); - var data = new AssetHistoryData(AssetHistoryOperationKind.CreateAsset, targetPath, string.Empty, isDirectory: true, archive); + var data = new AssetHistoryData( + AssetHistoryOperationKind.CreateAsset, + targetPath, + string.Empty, + isDirectory: true, + archive + ); cancellationToken.ThrowIfCancellationRequested(); return EditorHistoryPayload.FromBytes(data.Encode()); }, cancellationToken).ConfigureAwait(false); @@ -166,12 +201,17 @@ protected override void OnUpdate(EditorContext context) } if (!import.isValidationComplete) + { return; + } import.Commit(_ => { m_assets.interactions.history.RecordApplied( "Import Sample", - new EditorHistoryChange(AssetHistoryKinds.SourceOperation, m_historyPayload ?? throw new InvalidOperationException("Validated sample history is missing.")) + new EditorHistoryChange( + AssetHistoryKinds.SourceOperation, + m_historyPayload ?? throw new InvalidOperationException("Validated sample history is missing.") + ) ); }); m_log.Write(LogLevel.Info, "Imported sample to '{0}'.", [import.target]); @@ -181,7 +221,9 @@ protected override void OnUpdate(EditorContext context) catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { if (m_import?.isFaulted == true) + { ReportFault(pending); + } // The next frame retries retirement while the modal and dependency ownership remain intact. } catch (Exception failure) @@ -189,7 +231,9 @@ protected override void OnUpdate(EditorContext context) m_failure = failure; CancelCurrent(); if (m_import?.isFaulted == true) + { ReportFault(failure); + } } } @@ -209,13 +253,18 @@ protected override void OnStop(EditorContext context) /// Retries retirement without releasing dependencies still used by background work. /// protected override void OnDispose() => RetireImport(); + private void RetireImport() { m_import?.Rollback(); if (m_failure is not null) + { m_log.Write(LogLevel.Error, "Sample import failed: {0}", [m_failure]); + } else if (m_import is not null) + { m_log.Write(LogLevel.Info, "Sample import was canceled; no copy was published."); + } ClearImport(); } @@ -252,8 +301,12 @@ private void SetProgress( ) { lock (m_progressLock) { - if (!m_acceptProgress || m_progress.cancellationRequested || (operationId is long expected && expected != m_progress.operationId)) + if (!m_acceptProgress + || m_progress.cancellationRequested + || (operationId is long expected && expected != m_progress.operationId) + ) { return; + } m_progress = m_progress with { fraction = progress, status = status }; } } diff --git a/src/composition/editor/features/Inno.Editor.Audio/EditorAudioHost.cs b/src/composition/editor/features/Inno.Editor.Audio/EditorAudioHost.cs index 2fed5fe66..39d542df3 100644 --- a/src/composition/editor/features/Inno.Editor.Audio/EditorAudioHost.cs +++ b/src/composition/editor/features/Inno.Editor.Audio/EditorAudioHost.cs @@ -1,14 +1,14 @@ -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; using System.Linq; using Inno.Assets; using Inno.Audio; using Inno.Audio.Runtime; +using Inno.Core.Diagnostics; using Inno.Core.Logging; using Inno.Extensibility.Types; using Inno.Runtime; +using Inno.Runtime.Contracts; using Inno.Scene; namespace Inno.Editor.Audio; @@ -80,42 +80,54 @@ RuntimeSubsystemContext context ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(session); if (m_sessions.ContainsKey(session)) - throw new InvalidOperationException("The runtime session already owns an Editor audio generation."); - if (session.options.kind == RuntimeSessionKind.Play && - m_sessions.Keys.Any(static active => active.options.kind == RuntimeSessionKind.Play)) { + throw new InvalidOperationException("The runtime session already owns an Editor audio generation."); + } + if (session.options.kind == RuntimeSessionKind.Play + && m_sessions.Keys.Any(static active => active.options.kind == RuntimeSessionKind.Play) + ) { throw new InvalidOperationException("Only one isolated Play Mode audio generation may be active."); } AudioProjectSettings settings = m_settingsProvider() - ?? throw new InvalidOperationException("The audio settings provider returned null."); - DiagnosticReporter diagnostics = context.resources.Own(m_diagnostics.CreateReporter( - new DiagnosticSource($"inno.editor.audio.{session.sessionId}", $"Audio ({session.options.kind})"))); + ?? throw new InvalidOperationException("The audio settings provider returned null."); + DiagnosticReporter diagnostics = context.resources.Own( + m_diagnostics.CreateReporter( + new DiagnosticSource($"inno.editor.audio.{session.sessionId}", $"Audio ({session.options.kind})") + ) + ); IAudioDevice device = CreateDevice(diagnostics); AudioRuntime? runtime = null; try { runtime = new AudioRuntime( - m_types, - device, - m_artifacts, - session.events, - diagnostics, - new AudioRuntimeOptions - { - maxVoices = settings.maxVoices, - decodedCacheBudgetBytes = settings.decodedCacheBudgetBytes, - automaticStreamingThresholdBytes = settings.automaticStreamingThresholdBytes - }, - contentScopeProvider: () => SceneContentSource.CreateScope(session.scenes), - deviceRecoveryFactory: m_deviceFactory); + m_types, + device, + m_artifacts, + session.events, + diagnostics, + new AudioRuntimeOptions + { + maxVoices = settings.maxVoices, + decodedCacheBudgetBytes = settings.decodedCacheBudgetBytes, + automaticStreamingThresholdBytes = settings.automaticStreamingThresholdBytes + }, + contentScopeProvider: () => SceneContentSource.CreateScope(session.scenes), + deviceRecoveryFactory: m_deviceFactory + ); if (settings.defaultMixer is not null && !runtime.ApplyMixer(settings.defaultMixer)) + { throw new InvalidOperationException("The configured default Editor audio mixer could not be activated."); + } if (!runtime.SetBusVolume(AudioBusId.master, settings.masterVolume)) + { throw new InvalidOperationException("The configured Editor master audio volume could not be applied."); + } m_sessions.Add(session, runtime); if (session.options.kind == RuntimeSessionKind.Play) + { SetEditModePaused(true); + } return runtime; } catch (Exception failure) @@ -123,9 +135,13 @@ RuntimeSubsystemContext context try { if (runtime is not null) + { runtime.Dispose(); + } else + { device.Dispose(); + } } catch (Exception cleanup) { @@ -169,7 +185,9 @@ public AudioVoiceHandle PlayPreview( ArgumentNullException.ThrowIfNull(session); ArgumentNullException.ThrowIfNull(clip); if (session.options.kind != RuntimeSessionKind.Edit) + { throw new ArgumentException("Audio previews require an Edit Mode runtime session.", nameof(session)); + } return GetRuntime(session).Play(clip, options ?? AudioPlayOptions.defaultValue); } @@ -191,7 +209,9 @@ AudioVoiceHandle voice ) { ArgumentNullException.ThrowIfNull(session); if (session.options.kind != RuntimeSessionKind.Edit) + { return false; + } return GetRuntime(session).Stop(voice); } @@ -201,7 +221,9 @@ AudioVoiceHandle voice public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; List? failures = null; foreach (AudioRuntime runtime in m_sessions.Values.Reverse().ToArray()) @@ -218,7 +240,9 @@ public void Dispose() } m_sessions.Clear(); if (failures is not null) + { throw new AggregateException("One or more Editor audio generations could not be released.", failures); + } } private IAudioDevice CreateDevice(IDiagnosticReporter diagnostics) @@ -229,11 +253,14 @@ private IAudioDevice CreateDevice(IDiagnosticReporter diagnostics) } catch (Exception exception) { - diagnostics.Publish(new Diagnostic( - "AUDIO_DEVICE_INIT_FAILED", - $"The Editor audio output could not start; this audio generation is explicitly muted: {exception.Message}", - DiagnosticSeverity.Warning, - "AudioAdapter")); + diagnostics.Publish( + new Diagnostic( + "AUDIO_DEVICE_INIT_FAILED", + $"The Editor audio output could not start; this audio generation is explicitly muted: {exception.Message}", + DiagnosticSeverity.Warning, + "AudioAdapter" + ) + ); return new MutedAudioDevice(); } } @@ -243,23 +270,25 @@ private AudioRuntime GetRuntime(RuntimeSession session) ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(session); return m_sessions.TryGetValue(session, out AudioRuntime? runtime) - ? runtime - : throw new InvalidOperationException("The runtime session has no active Editor audio lease."); + ? runtime + : throw new InvalidOperationException("The runtime session has no active Editor audio lease."); } private void ReleaseRuntime( RuntimeSession session, AudioRuntime runtime ) { - if (!m_sessions.TryGetValue(session, out AudioRuntime? active) || - !ReferenceEquals(active, runtime)) - { + if (!m_sessions.TryGetValue(session, out AudioRuntime? active) + || !ReferenceEquals(active, runtime) + ) { return; } m_sessions.Remove(session); bool wasPlayMode = session.options.kind == RuntimeSessionKind.Play; if (wasPlayMode) + { SetEditModePaused(false); + } } private void SetEditModePaused(bool paused) @@ -267,15 +296,16 @@ private void SetEditModePaused(bool paused) foreach ((RuntimeSession session, AudioRuntime runtime) in m_sessions) { if (session.options.kind == RuntimeSessionKind.Edit) + { _ = runtime.SetBusPaused(AudioBusId.master, paused); + } } } private sealed class EditorAudioRuntimeFactory( EditorAudioHost owner, RuntimeSession session - ) - : IRuntimeSubsystemFactory + ) : IRuntimeSubsystemFactory { /// /// Gets the stable audio feature descriptor shared by every Editor session. @@ -283,7 +313,8 @@ RuntimeSession session public RuntimeSubsystemDescriptor descriptor { get; } = new( new RuntimeSubsystemId("inno.runtime.audio"), order: 500, - dependencies: [new RuntimeSubsystemId("inno.runtime.scene")]); + dependencies: [new RuntimeSubsystemId("inno.runtime.scene")] + ); /// /// Creates one Editor-owned audio generation for the supplied runtime session. @@ -303,9 +334,6 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) } } - - - private sealed class SessionAudioRegistration( EditorAudioHost owner, RuntimeSession session, diff --git a/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs b/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs index 0accdc29f..cf7bcbd96 100644 --- a/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs +++ b/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs @@ -1,7 +1,7 @@ -using Inno.Runtime.Contracts; using System; using Inno.Audio; using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Editor.Audio; diff --git a/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs b/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs index e5f1194d4..67b177782 100644 --- a/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs +++ b/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs @@ -7,12 +7,13 @@ using System.Threading.Tasks; using Inno.Build; using Inno.Build.Managed; -using Inno.Core.Logging; using Inno.Core.Execution; +using Inno.Core.Logging; using Inno.Core.Settings; using Inno.Editor.Core; namespace Inno.Editor.Exporting; + /// /// Owns asynchronous export, progress, cancellation and retirement independently from presentation. /// @@ -31,6 +32,7 @@ public sealed class EditorExportService : EditorModule private Task? m_gameExport; private Task? m_pluginExport; private GameBuildRequest? m_pendingGameRequest; + internal EditorExportService( BuildPipeline buildPipeline, LogRouter logs @@ -44,15 +46,24 @@ LogRouter logs /// Gets whether a Plugin source export still owns build resources. /// public bool isPluginBusy => m_pluginExport is not null; + /// /// Gets whether a game export or its Support Pack preparation is active. /// public bool isGameBusy => m_gamePreparation is not null || m_gameExport is not null; + /// /// Gets one owner-thread snapshot for the current export, including cancellation and action identity. /// - public EditorExportProgress progress => new(m_operation, m_fraction, m_status, m_error, - isGameBusy || isPluginBusy, m_cancellation?.IsCancellationRequested == true); + public EditorExportProgress progress + => new( + m_operation, + m_fraction, + m_status, + m_error, + isGameBusy || isPluginBusy, + m_cancellation?.IsCancellationRequested == true + ); /// /// Cancels the observed export only while that operation still owns this service. @@ -63,7 +74,9 @@ LogRouter logs public void Cancel(long operationId) { if (operationId == m_operation) + { CancelCurrent(); + } } /// @@ -81,6 +94,7 @@ public void Cancel(long operationId) /// The registered deployment choices; no host fallback is introduced. /// public IReadOnlyList GetManagedDeployments(BuildTargetId target) => m_buildPipeline.GetManagedDeployments(target); + /// /// Gets a registered target label or a diagnostic for an unavailable target. /// @@ -90,10 +104,12 @@ public void Cancel(long operationId) /// /// A presentation label; never used as a routing identity. /// - public string GetGameTargetDisplayName(BuildTargetId target) => m_buildPipeline.TryGetGameTargetDisplayName( - target, - out string displayName - ) ? displayName : $"Missing ({target})"; + public string GetGameTargetDisplayName(BuildTargetId target) + => m_buildPipeline.TryGetGameTargetDisplayName( + target, + out string displayName + ) ? displayName : $"Missing ({target})"; + /// /// Starts a source-package export using the existing Build pipeline. /// @@ -110,7 +126,9 @@ public void StartPlugin(PluginBuildRequest request) StartCancellation(); m_status = "Capturing the current Plugin source and dependency generation..."; m_error = string.Empty; - m_pluginExport = m_buildPipeline.BuildPluginAsync(request, new BuildProgressSink(m_progress, m_operation), m_cancellation!.Token).AsTask(); + m_pluginExport = m_buildPipeline + .BuildPluginAsync(request, new BuildProgressSink(m_progress, m_operation), m_cancellation!.Token) + .AsTask(); } /// @@ -133,7 +151,9 @@ public void StartGame(GameBuildRequest request) m_pendingGameRequest = request; try { - m_gamePreparation = m_buildPipeline.EnsurePlayerSupportPackAsync(request.profile.target, request.profile.managedDeployment, m_cancellation!.Token).AsTask(); + m_gamePreparation = m_buildPipeline + .EnsurePlayerSupportPackAsync(request.profile.target, request.profile.managedDeployment, m_cancellation!.Token) + .AsTask(); } catch (Exception exception) { @@ -144,7 +164,9 @@ public void StartGame(GameBuildRequest request) private void EnsureIdle() { if (isPluginBusy || isGameBusy) + { throw new InvalidOperationException("An export still owns the build service."); + } } /// @@ -158,11 +180,15 @@ protected override void OnUpdate(EditorContext context) while (m_progress.TryDequeue(out var update)) { if (update.operation != m_operation || m_cancellation is null || m_cancellation.IsCancellationRequested) + { continue; + } BuildProgress progress = update.value; m_status = progress.message; if (isGameBusy || isPluginBusy) + { m_fraction = MathF.Max(m_fraction ?? 0f, (float)progress.fraction); + } } CompletePluginExport(); @@ -192,8 +218,10 @@ protected override void OnDispose() private void RetireExports() { m_cancellation?.Cancel(); - if (m_gamePreparation is { IsCompleted: false } || m_gameExport is { IsCompleted: false } || m_pluginExport is { IsCompleted: false }) - { + if (m_gamePreparation is { IsCompleted: false } + || m_gameExport is { IsCompleted: false } + || m_pluginExport is { IsCompleted: false } + ) { throw new RetirementPendingException("Canceled export work still owns build services; retry retirement after it drains."); } @@ -231,14 +259,18 @@ private void RetireExports() private static void RequireRetiredOutcome(Task? task) { if (task?.Exception is Exception failure && RetirementPendingException.Find(failure) is not null) + { throw failure; + } } private void CompletePluginExport() { Task? export = m_pluginExport; if (export is null || !export.IsCompleted) + { return; + } m_pluginExport = null; try { @@ -250,7 +282,8 @@ private void CompletePluginExport() } string outputPath = result.outputPath ?? throw new InvalidOperationException("A successful Plugin build has no output path."); - string contentHash = result.contentHash ?? throw new InvalidOperationException("A successful Plugin build has no content identity."); + string contentHash = result.contentHash + ?? throw new InvalidOperationException("A successful Plugin build has no content identity."); m_fraction = 1f; m_status = $"Exported {result.assetCount} source files to {outputPath}"; m_error = string.Empty; @@ -282,7 +315,9 @@ private void CompleteGameExport() { Task? export = m_gameExport; if (export is null || !export.IsCompleted) + { return; + } m_gameExport = null; try { @@ -300,7 +335,13 @@ private void CompleteGameExport() m_log.Write( LogLevel.Info, "Exported game to '{0}' ({1}, {2} assets, {3} artifact bundles, {4} runtime assemblies).", - [outputPath, result.target?.ToString() ?? "unknown", result.assetCount, result.artifactBundleCount, result.runtimeAssemblyCount] + [ + outputPath, + result.target?.ToString() ?? "unknown", + result.assetCount, + result.artifactBundleCount, + result.runtimeAssemblyCount + ] ); } catch (OperationCanceledException) @@ -325,16 +366,21 @@ private void CompleteGamePreparation() { Task? preparation = m_gamePreparation; if (preparation is null || !preparation.IsCompleted) + { return; + } m_gamePreparation = null; try { using PlayerSupportPackLease prepared = preparation.GetAwaiter().GetResult(); m_cancellation!.Token.ThrowIfCancellationRequested(); - GameBuildRequest request = m_pendingGameRequest ?? throw new InvalidOperationException("The prepared game build has no request."); + GameBuildRequest request = m_pendingGameRequest + ?? throw new InvalidOperationException("The prepared game build has no request."); m_pendingGameRequest = null; m_status = "Capturing the authoring generation and compiling runtime scripts..."; - m_gameExport = m_buildPipeline.BuildGameAsync(request, new BuildProgressSink(m_progress, m_operation), m_cancellation.Token).AsTask(); + m_gameExport = m_buildPipeline + .BuildGameAsync(request, new BuildProgressSink(m_progress, m_operation), m_cancellation.Token) + .AsTask(); } catch (OperationCanceledException) { @@ -365,7 +411,9 @@ private void StartCancellation() private void CancelCurrent() { if (m_cancellation is null) + { return; + } m_status = "Canceling export..."; m_cancellation.Cancel(); } @@ -380,7 +428,10 @@ private void ReportBuildFailure( string operation, BuildResult result ) { - string message = string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => $"[{diagnostic.code}] {diagnostic.message}")); + string message = string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"[{diagnostic.code}] {diagnostic.message}") + ); m_status = string.Empty; m_error = message; m_log.Write(LogLevel.Error, "{0} failed:{1}{2}", [operation, Environment.NewLine, message]); diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/EditorPlayModeState.cs b/src/composition/editor/features/Inno.Editor.PlayMode/EditorPlayModeState.cs index a60e90e29..5fa40e391 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/EditorPlayModeState.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/EditorPlayModeState.cs @@ -9,27 +9,22 @@ public enum EditorPlayModeState /// Editable scene documents are loaded and game simulation is stopped. /// Editing, - /// /// Play Mode is waiting for the requested script generation to become active. /// Compiling, - /// /// The active script generation is ready and isolated runtime state is being prepared. /// Preparing, - /// /// Isolated runtime scenes are receiving the game update lifecycle. /// Playing, - /// /// The isolated runtime session is stopping and releasing its owned state. /// Stopping, - /// /// The most recent transition failed and its diagnostic remains available for inspection. /// diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/IEditorPlayMode.cs b/src/composition/editor/features/Inno.Editor.PlayMode/IEditorPlayMode.cs index 28127edb0..be749c6bf 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/IEditorPlayMode.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/IEditorPlayMode.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Logging; namespace Inno.Editor.PlayMode; diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/TogglePlayModeAction.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/TogglePlayModeAction.cs index 77dfbff39..f314671bf 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/TogglePlayModeAction.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Interactions/TogglePlayModeAction.cs @@ -8,7 +8,8 @@ namespace Inno.Editor.PlayMode; PlayModeInteractionIds.C_MAIN_MENU_AREA, EditorToolbarIcon.Play, "Enter Play Mode", - activeIcon: EditorToolbarIcon.Stop)] + activeIcon: EditorToolbarIcon.Stop +)] [EditorShortcut(KeyCode.P, primary: true)] internal sealed class TogglePlayModeAction(IEditorPlayMode playMode) : EditorAction { @@ -23,34 +24,35 @@ internal sealed class TogglePlayModeAction(IEditorPlayMode playMode) : EditorAct /// protected override EditorActionState Query(EditorActionContext context) => playMode.state switch - { - EditorPlayModeState.Editing => new EditorActionState(true, true, displayName: "Enter Play Mode"), - EditorPlayModeState.Compiling => new EditorActionState( - true, - true, - isChecked: true, - displayName: "Cancel Script Compilation Wait"), - EditorPlayModeState.Preparing => new EditorActionState( - true, - false, - isChecked: true, - displayName: "Preparing Play Mode"), - EditorPlayModeState.Playing => new EditorActionState( - true, - true, - isChecked: true, - displayName: "Return to Edit Mode"), - EditorPlayModeState.Stopping => new EditorActionState( - true, - false, - isChecked: true, - displayName: "Restoring Edit Mode"), - EditorPlayModeState.Failed => new EditorActionState( - true, - true, - displayName: "Retry Play Mode"), - _ => EditorActionState.hidden - }; + { + EditorPlayModeState.Editing => new EditorActionState(true, true, displayName: "Enter Play Mode"), + EditorPlayModeState.Compiling => new EditorActionState( + true, + true, + isChecked: true, + displayName: "Cancel Script Compilation Wait" + ), + EditorPlayModeState.Preparing => new EditorActionState( + true, + false, + isChecked: true, + displayName: "Preparing Play Mode" + ), + EditorPlayModeState.Playing => new EditorActionState( + true, + true, + isChecked: true, + displayName: "Return to Edit Mode" + ), + EditorPlayModeState.Stopping => new EditorActionState( + true, + false, + isChecked: true, + displayName: "Restoring Edit Mode" + ), + EditorPlayModeState.Failed => new EditorActionState(true, true, displayName: "Retry Play Mode"), + _ => EditorActionState.hidden + }; /// /// Executes the prepared operation and publishes only a completed result. @@ -61,8 +63,12 @@ protected override EditorActionState Query(EditorActionContext context) protected override void Execute(EditorActionContext context) { if (playMode.state is EditorPlayModeState.Compiling or EditorPlayModeState.Preparing or EditorPlayModeState.Playing) + { _ = playMode.ExitPlayMode(); + } else + { _ = playMode.EnterPlayMode(); + } } } diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Properties/ScriptingApi.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Properties/ScriptingApi.cs index 99641b4d2..79abc14e3 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Properties/ScriptingApi.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Editor.PlayMode; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.PlayMode", - "Inno.Editor.PlayMode", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.PlayMode", "Inno.Editor.PlayMode", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorPlayModeState), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(IEditorPlayMode), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs index 1d9ad489e..5c13858a1 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs @@ -1,20 +1,19 @@ -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Extensibility.Reload; using System; -using Inno.Core.Events; using System.Collections.Generic; - +using Inno.Core.Diagnostics; +using Inno.Core.Events; +using Inno.Core.Execution; using Inno.Core.Logging; -using Inno.Extensibility.Modules; -using Inno.Scripting.Api; using Inno.Editor.Audio; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Scripting; -using Inno.Scripting.Compiler; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; using Inno.Runtime; +using Inno.Scripting.Api; +using Inno.Scripting.Compiler; using Inno.UI.Runtime; namespace Inno.Editor.PlayMode; @@ -99,7 +98,8 @@ public EditorPlayModeController( { throw new ArgumentException( "Editor Play Mode requires RuntimeSessionKind.Play options.", - nameof(runtimeOptions)); + nameof(runtimeOptions) + ); } m_scenes = scenes ?? throw new ArgumentNullException(nameof(scenes)); m_scripting = scripting ?? throw new ArgumentNullException(nameof(scripting)); @@ -124,13 +124,16 @@ public EditorPlayModeController( bool IEditorReloadGuard.canRequestReload => !m_disposed && m_state == EditorPlayModeState.Editing; /// - bool IEditorReloadGuard.canActivateReload => !m_disposed - && m_state is EditorPlayModeState.Editing or EditorPlayModeState.Compiling - && m_runtimeSession is null && m_sceneLease is null && m_generationLease is null; + bool IEditorReloadGuard.canActivateReload + => !m_disposed + && m_state is EditorPlayModeState.Editing or EditorPlayModeState.Compiling + && m_runtimeSession is null && m_sceneLease is null && m_generationLease is null; /// - string? IEditorReloadGuard.blockingReason => m_state == EditorPlayModeState.Editing - ? null : "Stop Play Mode and wait for its runtime session to retire before reloading scripts or Plugins."; + string? IEditorReloadGuard.blockingReason + => m_state == EditorPlayModeState.Editing + ? null + : "Stop Play Mode and wait for its runtime session to retire before reloading scripts or Plugins."; /// /// Gets the most recent transition or simulation failure. @@ -173,7 +176,9 @@ public bool EnterPlayMode() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_state is not (EditorPlayModeState.Editing or EditorPlayModeState.Failed)) + { return false; + } m_engineHost.generations.EnsureReady("enter Play Mode"); m_entryFailed = false; m_retirement = null; @@ -251,7 +256,8 @@ public void Tick(float deltaTime) m_playTime += Math.Max(0f, deltaTime); session.Tick(deltaTime); }, - "frame update"); + "frame update" + ); /// /// Releases the isolated runtime session and history scope owned by this controller. @@ -259,16 +265,24 @@ public void Tick(float deltaTime) public void Dispose() { if (m_disposed) + { return; + } if (m_startupRetirementFailure is not null) + { throw m_startupRetirementFailure; + } try { if (m_runtimeSession is not null) + { SetState(EditorPlayModeState.Stopping); + } ReleasePlayResources(); if (m_state != EditorPlayModeState.Editing) + { CompleteEditingTransition(); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -304,7 +318,9 @@ private void AdvanceCompilation() return; case ScriptCompilationTicketState.Canceled: case ScriptCompilationTicketState.Superseded: - Fail($"Play Mode did not start because its script request was {ticket.state.ToString().ToLowerInvariant()}. {ticket.status}"); + Fail( + $"Play Mode did not start because its script request was {ticket.state.ToString().ToLowerInvariant()}. {ticket.status}" + ); return; default: throw new ArgumentOutOfRangeException(); @@ -319,7 +335,9 @@ private void PrepareRuntimeSession() m_runtimeSession = m_engineHost.CreateSession(m_runtimeOptions); m_generationLease = m_engineHost.generations.AcquireRead("active Play Mode session"); using (m_runtimeSession.EnterExecutionScope()) + { m_sceneLease = m_scenes.BeginPlayMode(m_runtimeSession); + } m_activeSessionId = m_runtimeSession.sessionId; m_playTime = 0f; SetState(EditorPlayModeState.Playing); @@ -345,9 +363,13 @@ private void StopRuntimeSession() { ReleasePlayResources(); if (m_entryFailed) + { SetState(EditorPlayModeState.Failed); + } else + { CompleteEditingTransition(); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is RetirementTimeoutException) { @@ -368,20 +390,28 @@ private void StopRuntimeSession() private void ReleasePlayResources() { if (m_startupRetirementFailure is not null) + { throw m_startupRetirementFailure; + } // The owner thread hands admission to the retirement reservation before it can process another frame. m_generationLease?.Dispose(); m_generationLease = null; if (m_sceneLease is null && m_runtimeSession is null && m_historyIsolation is null) + { return; + } if (m_retirementReservation is null && m_engineHost.generations.state == GenerationState.Ready) { if (!m_engineHost.generations.TryAcquireChange("retire Play Mode", out m_retirementReservation)) + { throw new RetirementPendingException("Play Mode retirement is waiting for the active generation reader."); + } } m_retirement ??= new RetirementBarrier("Editor Play Mode"); if (!m_retirement.TryComplete(ReleasePlayResourcesCore)) + { throw new RetirementPendingException("Play Mode is still draining its runtime session."); + } m_retirementReservation?.Dispose(); m_retirementReservation = null; } @@ -402,7 +432,9 @@ private void ReleasePlayResourcesCore() internal void Quiesce() { if (m_disposed) + { return; + } SetState(EditorPlayModeState.Stopping); List? failures = null; try @@ -413,7 +445,9 @@ internal void Quiesce() { m_engineHost.generations.Fault(exception); if (RetirementPendingException.Find(exception) is not null) + { throw; + } failures = [exception]; m_lastFailure = $"Play Mode could not release its runtime generation: {exception.Message}"; } @@ -431,7 +465,8 @@ internal void Quiesce() { throw new InvalidOperationException( "Assembly reload cannot continue because Play Mode still owns generation-bound runtime state.", - new AggregateException(failures)); + new AggregateException(failures) + ); } } @@ -440,9 +475,11 @@ private void RunSimulation( string phase ) { if (m_state != EditorPlayModeState.Playing) + { return; + } RuntimeSession session = m_runtimeSession - ?? throw new InvalidOperationException("Playing state has no active runtime session."); + ?? throw new InvalidOperationException("Playing state has no active runtime session."); try { callback(session); @@ -453,7 +490,8 @@ string phase m_log.Write( LogLevel.Error, "Play Mode {0} failed; isolated runtime disposal was requested: {1}", - [phase, exception]); + [phase, exception] + ); SetState(EditorPlayModeState.Stopping); } } @@ -461,7 +499,9 @@ string phase internal IDisposable? EnterPresentationScope() { if (m_state != EditorPlayModeState.Playing || m_runtimeSession is not RuntimeSession session) + { return null; + } IDisposable? sessionScope = null; IDisposable? audioScope = null; IDisposable? uiScope = null; @@ -500,12 +540,16 @@ private static string CreateCompilationFailure(IScriptCompilationTicket ticket) { ScriptCompilationResult? compilation = ticket.result; if (compilation is null) + { return $"Play Mode requires a valid script generation. {ticket.status}"; + } for (int i = 0; i < compilation.diagnostics.Count; i++) { ScriptDiagnostic diagnostic = compilation.diagnostics[i]; if (diagnostic.severity == DiagnosticSeverity.Error) + { return $"Play Mode is unavailable because scripts did not compile: {diagnostic.message}"; + } } return "Play Mode is unavailable because the active script compilation failed."; } @@ -513,12 +557,16 @@ private static string CreateCompilationFailure(IScriptCompilationTicket ticket) private void SetState(EditorPlayModeState value) { if (m_state == value) + { return; + } m_state = value; var notification = new StateTransitionEvent(value); m_stateDispatcher.Emit(notification); if (notification.failures.Count != 0) + { throw new AggregateException("One or more Play Mode state observers failed.", notification.failures); + } } private sealed class StateTransitionEvent(EditorPlayModeState state) : Event @@ -530,12 +578,13 @@ private sealed class StateTransitionEvent(EditorPlayModeState state) : Event private static void DisposeResource( ref T? resource, ref List? failures - ) - where T : class, IDisposable + ) where T : class, IDisposable { T? owned = resource; if (owned is null) + { return; + } try { owned.Dispose(); diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeLoop.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeLoop.cs index 7ebd98d2e..6c6903e3a 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeLoop.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeLoop.cs @@ -39,14 +39,18 @@ public sealed class EditorPlayModeLoop internal void Attach(EditorPlayModeController owner) { if (m_owner is not null && !ReferenceEquals(m_owner, owner)) + { throw new InvalidOperationException("The editor host already owns an active Play Mode module."); + } m_owner = owner; } internal void Detach(EditorPlayModeController owner) { if (ReferenceEquals(m_owner, owner)) + { m_owner = null; + } } private sealed class EmptyScope : IDisposable @@ -54,8 +58,6 @@ private sealed class EmptyScope : IDisposable /// /// Completes the inert presentation scope. /// - public void Dispose() - { - } + public void Dispose() {} } } diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs index 500a3fe98..dc0cd7807 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Logging; using Inno.Editor.Audio; using Inno.Editor.Core; @@ -38,7 +37,8 @@ IEditorAudioHost audio scripting, interactions, engineHost.logs, - audio); + audio + ); } /// diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs index 353827ed4..98864c8e7 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs @@ -3,9 +3,9 @@ using System.IO; using System.Linq; using System.Threading; +using Inno.Assets; using Inno.Core.Diagnostics; using Inno.Core.Graphs; -using Inno.Assets; using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; @@ -27,19 +27,23 @@ internal EditorShaderDraftCompilationSnapshot RequestDraft( GraphicsCapabilities capabilities ) { if (documentId == Guid.Empty) + { throw new ArgumentException("A preview requires a document identity.", nameof(documentId)); + } ArgumentNullException.ThrowIfNull(graph); lock (m_sync) { EnsureActive(); ShaderCompileTarget target = m_shaderCompiler.CreateTarget(capabilities, optimize: false, debugInformation: true); if (!m_drafts.TryGetValue(documentId, out DraftEntry? draft)) + { m_drafts.Add(documentId, draft = new()); + } ShaderEntry entry = draft.compilation; string targetVariant = target.key + "\n" + variant.value; if (!draft.attempted || draft.revision != revision || draft.assetRevision != m_assets.revision - || entry.extensionGeneration != m_types.current.version || draft.targetVariant != targetVariant) - { + || entry.extensionGeneration != m_types.current.version || draft.targetVariant != targetVariant + ) { draft.attempted = true; draft.revision = revision; draft.assetRevision = m_assets.revision; @@ -48,26 +52,40 @@ GraphicsCapabilities capabilities draft.targetVariant = targetVariant; try { - byte[] captured = ShaderGraphArtifact.Capture(graph, m_types, m_serialization, AssetSerializationContext.Create(m_assets), + byte[] captured = ShaderGraphArtifact.Capture( + graph, + m_types, + m_serialization, + AssetSerializationContext.Create(m_assets), ( id, _ ) => { - if (!m_assets.TryGetInfo(id, out AssetInfo? source) || source is null || source.status != AssetImportStatus.Imported) - throw new InvalidDataException($"Shader function '{id}' has no current successful import. Preview cannot hide its source error with an old bundle."); + if (!m_assets.TryGetInfo(id, out AssetInfo? source) + || source is null + || source.status != AssetImportStatus.Imported + ) { + throw new InvalidDataException( + $"Shader function '{id}' has no current successful import. Preview cannot hide its source error with an old bundle." + ); + } using ArtifactLease lease = m_assets.AcquireArtifact(id, ShaderSourceBundle.outputName); return lease.ReadAllBytes(); - }, m_lifetime.Token, + }, + m_lifetime.Token, ( id, _ ) => { if (!m_assets.TryLoad(id, out ShaderAsset? node) || node is null || node.isMissing) + { throw new InvalidDataException($"Shader graph node '{id}' has no current successful import."); + } return ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(node, m_assets), m_serialization); - }); + } + ); string hash = ShaderGraphArtifact.GetSemanticHash(captured, m_serialization); if (environmentChanged || entry.semanticHash != hash) { @@ -75,8 +93,15 @@ GraphicsCapabilities capabilities entry.pending = null; entry.cancellation = CancellationTokenSource.CreateLinkedTokenSource(m_lifetime.Token); entry.semanticHash = hash; - entry.pending = RunOwned(token => m_shaderCompiler.CompileGraphAsync(captured, target, variant, m_types, - m_serialization, AssetSerializationContext.Create(m_assets), token), entry.cancellation.Token); + entry.pending = RunOwned(token => m_shaderCompiler.CompileGraphAsync( + captured, + target, + variant, + m_types, + m_serialization, + AssetSerializationContext.Create(m_assets), + token + ), entry.cancellation.Token); } } catch (Exception failure) when (Inno.Core.Execution.RetirementPendingException.Find(failure) is null) @@ -90,19 +115,34 @@ GraphicsCapabilities capabilities if (entry.pending is { IsCompleted: true } pending) { if (pending.Exception is Exception failure && Inno.Core.Execution.RetirementPendingException.Find(failure) is not null) + { throw failure; + } entry.pending = null; entry.cancellation?.Dispose(); entry.cancellation = null; - ShaderCompilationResult result = pending.IsCompletedSuccessfully ? pending.Result : new(null, - [new("SHADER_PREVIEW_COMPILE", DiagnosticSeverity.Error, pending.Exception?.GetBaseException().Message ?? "Preview compilation cancelled.")]); + ShaderCompilationResult result = pending.IsCompletedSuccessfully ? pending.Result : new( + null, + [new( + "SHADER_PREVIEW_COMPILE", + DiagnosticSeverity.Error, + pending.Exception?.GetBaseException().Message ?? "Preview compilation cancelled." + )] + ); entry.latestSucceeded = result.succeeded; entry.sourceDiagnostics = Array.AsReadOnly(result.diagnostics.ToArray()); if (result.succeeded) + { entry.artifact = result.artifact!.CreateRuntimeArtifact(); + } } - return new(entry.pending is not null ? EditorShaderCompilationState.Compiling + return new( + entry.pending is not null + ? EditorShaderCompilationState.Compiling : entry.latestSucceeded ? EditorShaderCompilationState.Succeeded : EditorShaderCompilationState.Failed, - entry.artifact is not null && (entry.pending is not null || !entry.latestSucceeded), entry.sourceDiagnostics, entry.artifact); + entry.artifact is not null && (entry.pending is not null || !entry.latestSucceeded), + entry.sourceDiagnostics, + entry.artifact + ); } } @@ -112,7 +152,9 @@ internal void ReleaseDraft(Guid documentId) { EnsureActive(); if (!m_drafts.Remove(documentId, out DraftEntry? draft)) + { return; + } Retire(draft.compilation.pending, draft.compilation.cancellation); } } diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs index 3532f0aba..0d00a85ee 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs @@ -1,12 +1,12 @@ -using Inno.Core.Diagnostics; using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Diagnostics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; @@ -115,7 +115,8 @@ out RenderShaderArtifact? artifact ShaderCompileTarget target = m_shaderCompiler.CreateTarget( capabilities, optimize: false, - debugInformation: true); + debugInformation: true + ); var key = new ShaderKey(shader.identity.persistentId, target.key, variant.value); if (!m_shaders.TryGetValue(key, out ShaderEntry? entry)) { @@ -137,8 +138,8 @@ out RenderShaderArtifact? artifact CompleteShader(key, entry); artifact = entry.artifact; return artifact is not null - ? RenderTargetArtifactStatus.Ready - : entry.status; + ? RenderTargetArtifactStatus.Ready + : entry.status; } } @@ -155,8 +156,10 @@ public ShaderDefinition ReadShaderDefinition(RenderShaderArtifact artifact) { ArgumentNullException.ThrowIfNull(artifact); EnsureActive(); - return m_serialization.Deserialize(artifact.definitionData.Span, - AssetSerializationContext.Create(m_assets)); + return m_serialization.Deserialize( + artifact.definitionData.Span, + AssetSerializationContext.Create(m_assets) + ); } /// @@ -184,9 +187,15 @@ GraphicsCapabilities capabilities _ = GetShaderArtifact(shader, variant, capabilities, out _); ShaderCompileTarget target = m_shaderCompiler.CreateTarget(capabilities, optimize: false, debugInformation: true); ShaderEntry entry = m_shaders[new(shader.identity.persistentId, target.key, variant.value)]; - return new(entry.pending is not null ? EditorShaderCompilationState.Compiling : entry.latestSucceeded - ? EditorShaderCompilationState.Succeeded : EditorShaderCompilationState.Failed, - entry.artifact is not null && (entry.pending is not null || !entry.latestSucceeded), entry.sourceDiagnostics); + return new( + entry.pending is not null + ? EditorShaderCompilationState.Compiling + : entry.latestSucceeded + ? EditorShaderCompilationState.Succeeded + : EditorShaderCompilationState.Failed, + entry.artifact is not null && (entry.pending is not null || !entry.latestSucceeded), + entry.sourceDiagnostics + ); } } @@ -214,7 +223,9 @@ public RenderTargetArtifactStatus GetTextureArtifact( out ReadOnlyMemory artifact ) { if (texture.assetId == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + { throw new ArgumentException("A valid texture artifact reference is required.", nameof(texture)); + } lock (m_sync) { EnsureActive(); @@ -226,11 +237,13 @@ out ReadOnlyMemory artifact } CompleteTexture(key, entry); if (entry.attemptedContentVersion != texture.contentRevision) + { StartTexture(texture, entry); + } artifact = entry.artifact ?? ReadOnlyMemory.Empty; return !artifact.IsEmpty - ? RenderTargetArtifactStatus.Ready - : entry.status; + ? RenderTargetArtifactStatus.Ready + : entry.status; } } @@ -242,11 +255,15 @@ public void Dispose() lock (m_sync) { if (m_disposed) + { return; + } m_stopping = true; m_lifetime.Cancel(); foreach (DraftEntry draft in m_drafts.Values) + { Retire(draft.compilation.pending, draft.compilation.cancellation); + } m_drafts.Clear(); foreach (ShaderEntry entry in m_shaders.Values) { @@ -279,24 +296,32 @@ ShaderEntry entry entry.cancellation = CancellationTokenSource.CreateLinkedTokenSource(m_lifetime.Token); entry.attemptedContentVersion = shader.contentVersion; entry.status = entry.artifact is null - ? RenderTargetArtifactStatus.Pending - : RenderTargetArtifactStatus.Ready; + ? RenderTargetArtifactStatus.Pending + : RenderTargetArtifactStatus.Ready; try { CancellationToken token = entry.cancellation.Token; - entry.pending = RunOwned(token => m_shaderCompiler.CompileGraphAsync(shader, target, variant, m_types, m_serialization, - AssetSerializationContext.Create(m_assets), m_assets, token), token); + entry.pending = RunOwned(token => m_shaderCompiler.CompileGraphAsync( + shader, + target, + variant, + m_types, + m_serialization, + AssetSerializationContext.Create(m_assets), + m_assets, + token + ), token); } catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) { entry.cancellation.Dispose(); entry.cancellation = null; - entry.pending = Task.FromResult(new ShaderCompilationResult( - null, - [new ShaderDiagnostic( - "SHADER_COMPILE_EXCEPTION", - DiagnosticSeverity.Error, - exception.Message)])); + entry.pending = Task.FromResult( + new ShaderCompilationResult( + null, + [new ShaderDiagnostic("SHADER_COMPILE_EXCEPTION", DiagnosticSeverity.Error, exception.Message)] + ) + ); } } @@ -306,14 +331,20 @@ ShaderEntry entry ) { Task? pending = entry.pending; if (pending is null || !pending.IsCompleted) + { return; + } if (pending.Exception is Exception failure && Inno.Core.Execution.RetirementPendingException.Find(failure) is not null) + { throw failure; + } entry.pending = null; entry.cancellation?.Dispose(); entry.cancellation = null; if (pending.IsCanceled) + { return; + } ShaderCompilationResult result = pending.IsCompletedSuccessfully ? pending.Result : new ShaderCompilationResult( @@ -321,7 +352,9 @@ ShaderEntry entry [new ShaderDiagnostic( "SHADER_COMPILE_EXCEPTION", DiagnosticSeverity.Error, - pending.Exception?.GetBaseException().Message ?? "Shader compilation failed without an exception.")]); + pending.Exception?.GetBaseException().Message ?? "Shader compilation failed without an exception." + )] + ); entry.latestSucceeded = result.succeeded; entry.sourceDiagnostics = Array.AsReadOnly(result.diagnostics.ToArray()); var diagnostics = result.diagnostics @@ -329,11 +362,12 @@ [new ShaderDiagnostic( diagnostic.code, diagnostic.message, diagnostic.severity == DiagnosticSeverity.Error - ? DiagnosticSeverity.Error - : diagnostic.severity == DiagnosticSeverity.Warning - ? DiagnosticSeverity.Warning - : DiagnosticSeverity.Info, - diagnostic.location?.assetPath ?? key.shaderId.ToString("D"))) + ? DiagnosticSeverity.Error + : diagnostic.severity == DiagnosticSeverity.Warning + ? DiagnosticSeverity.Warning + : DiagnosticSeverity.Info, + diagnostic.location?.assetPath ?? key.shaderId.ToString("D") + )) .ToList(); if (result.succeeded) { @@ -342,11 +376,14 @@ [new ShaderDiagnostic( } else if (entry.artifact is not null) { - diagnostics.Add(new Diagnostic( - "RENDER_SHADER_USING_LAST_GOOD", - $"Shader '{key.shaderId:D}' kept its last-good target artifact.", - DiagnosticSeverity.Warning, - key.shaderId.ToString("D"))); + diagnostics.Add( + new Diagnostic( + "RENDER_SHADER_USING_LAST_GOOD", + $"Shader '{key.shaderId:D}' kept its last-good target artifact.", + DiagnosticSeverity.Warning, + key.shaderId.ToString("D") + ) + ); entry.status = RenderTargetArtifactStatus.Ready; } else @@ -365,8 +402,8 @@ TextureEntry entry entry.cancellation = CancellationTokenSource.CreateLinkedTokenSource(m_lifetime.Token); entry.attemptedContentVersion = texture.contentRevision; entry.status = entry.artifact is null - ? RenderTargetArtifactStatus.Pending - : RenderTargetArtifactStatus.Ready; + ? RenderTargetArtifactStatus.Pending + : RenderTargetArtifactStatus.Ready; try { CancellationToken token = entry.cancellation.Token; @@ -380,8 +417,10 @@ TextureEntry entry return await m_textureCompiler.CompileKtxAsync( encoded, texture.slot.colorSpace, - token).ConfigureAwait(false); - }).ConfigureAwait(false); + token + ).ConfigureAwait(false); + } + ).ConfigureAwait(false); }, token); } catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) @@ -398,9 +437,13 @@ TextureEntry entry ) { Task? pending = entry.pending; if (pending is null || !pending.IsCompleted) + { return; + } if (pending.Exception is Exception failure && Inno.Core.Execution.RetirementPendingException.Find(failure) is not null) + { throw failure; + } entry.pending = null; entry.cancellation?.Dispose(); entry.cancellation = null; @@ -412,23 +455,26 @@ TextureEntry entry return; } if (pending.IsCanceled) + { return; + } string message = pending.IsCompletedSuccessfully - ? "The texture compiler produced an empty target artifact." - : pending.Exception?.GetBaseException().Message ?? "Texture compilation failed without an exception."; + ? "The texture compiler produced an empty target artifact." + : pending.Exception?.GetBaseException().Message ?? "Texture compilation failed without an exception."; ReplaceDiagnostics(entry.diagnostics, [new Diagnostic( "RENDER_TEXTURE_PREWARM_FAILED", $"Texture '{key.textureId:D}' kept its last-good target artifact: {message}", DiagnosticSeverity.Error, - key.textureId.ToString("D"))]); + key.textureId.ToString("D") + )]); entry.status = entry.artifact is null - ? RenderTargetArtifactStatus.Failed - : RenderTargetArtifactStatus.Ready; + ? RenderTargetArtifactStatus.Failed + : RenderTargetArtifactStatus.Ready; } private AssetSourceMount GetMount(AssetSourceId source) => m_assets.sourceMounts.FirstOrDefault(mount => mount.id == source) - ?? throw new InvalidOperationException($"Asset source mount '{source}' is not active."); + ?? throw new InvalidOperationException($"Asset source mount '{source}' is not active."); private Task RunOwned( Func> operation, @@ -436,23 +482,27 @@ CancellationToken token ) { // Admit before starting work or acquiring leases. Ordinary compilation errors are data; // retirement-pending failures stay in the lifetime and retain every dependent owner. - return Unwrap(m_work.RunAsync<(T value, Exception? failure)>(async cancellation => - { - try + return Unwrap( + m_work.RunAsync<(T value, Exception? failure)>(async cancellation => { - return (await operation(cancellation).ConfigureAwait(false), null); - } - catch (Exception failure) when (Inno.Core.Execution.RetirementPendingException.Find(failure) is null) - { - return (default!, failure); - } - }, token)); + try + { + return (await operation(cancellation).ConfigureAwait(false), null); + } + catch (Exception failure) when (Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + { + return (default!, failure); + } + }, token) + ); static async Task Unwrap(Task<(T value, Exception? failure)> task) { var result = await task.ConfigureAwait(false); if (result.failure is not null) + { System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(result.failure).Throw(); + } return result.value; } } @@ -462,7 +512,9 @@ private static void Retire( CancellationTokenSource? cancellation ) { if (cancellation is null) + { return; + } cancellation.Cancel(); if (task is null) { @@ -481,7 +533,8 @@ private static void Retire( cancellation, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); + TaskScheduler.Default + ); } private void ReplaceDiagnostics( @@ -499,7 +552,9 @@ IEnumerable diagnostics private void ClearDiagnostics(ISet active) { foreach (DiagnosticIdentity diagnostic in active) + { m_diagnostics.Resolve(diagnostic.code, diagnostic.semanticId); + } active.Clear(); } @@ -507,7 +562,9 @@ private void EnsureActive() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("A retiring artifact provider cannot accept compilation requests."); + } } private readonly record struct ShaderKey( @@ -515,11 +572,13 @@ private readonly record struct ShaderKey( string targetKey, string variantKey ); + private readonly record struct TextureKey( Guid textureId, string slotId, TextureColorSpace colorSpace ); + private readonly record struct DiagnosticIdentity( string code, string? semanticId diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs index 395b5f34f..c235358eb 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs @@ -74,6 +74,7 @@ public sealed class EditorShaderCompilation private readonly EditorRenderTargetArtifactProvider m_provider; private readonly GraphicsCapabilities m_capabilities; private readonly IEditorShaderArtifactValidator? m_validator; + /// /// Pairs the authoring artifact owner with the active device's immutable capability snapshot. /// @@ -108,6 +109,7 @@ IEditorShaderArtifactValidator validator m_validator = validator ?? throw new ArgumentNullException(nameof(validator)); m_capabilities = validator.capabilities; } + /// /// Requests current compilation and reads its explicit last-good status. /// @@ -123,8 +125,7 @@ IEditorShaderArtifactValidator validator public EditorShaderCompilationSnapshot Request( ShaderAsset shader, RenderShaderVariant variant - ) - => m_provider.RequestShaderCompilation(shader, variant, m_capabilities); + ) => m_provider.RequestShaderCompilation(shader, variant, m_capabilities); /// /// Reads the canonical Shader candidate for an isolated Material preview without modifying Material values. @@ -187,15 +188,15 @@ RenderShaderVariant variant graph, revision, variant, - m_capabilities); + m_capabilities + ); if (m_validator is null || compiled.state != EditorShaderCompilationState.Succeeded - || compiled.artifact is null) + || compiled.artifact is null + ) { return compiled; + } - EditorShaderArtifactValidationSnapshot validated = m_validator.Request( - documentId, - revision, - compiled.artifact); + EditorShaderArtifactValidationSnapshot validated = m_validator.Request(documentId, revision, compiled.artifact); IReadOnlyList diagnostics = compiled.diagnostics .Concat(validated.diagnostics) .ToArray(); diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs index 2df8ea56b..638639ec1 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs @@ -42,14 +42,17 @@ int pixelHeight /// Gets the scene roots visible in this Editor viewport. /// public ContentReadScope content { get; } + /// /// Gets the transient selected identity. /// public RuntimeIdentity? selected { get; } + /// /// Gets the viewport width in physical pixels. /// public int pixelWidth { get; } + /// /// Gets the viewport height in physical pixels. /// @@ -182,6 +185,7 @@ public sealed class EditorGizmoFrame : IEditorGizmoSink /// Gets the ordered selectable icons. /// public IReadOnlyList icons => m_icons; + /// /// Gets the ordered non-interactive lines. /// diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderRegistry.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderRegistry.cs index 0fb6f92bd..d771a6bb5 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderRegistry.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderRegistry.cs @@ -8,7 +8,8 @@ namespace Inno.Editor.Rendering; internal sealed class EditorGizmoProviderRegistry : TypeRegistry { - internal EditorGizmoProviderRegistry(TypeCatalog types) : base(types) { } + internal EditorGizmoProviderRegistry(TypeCatalog types) + : base(types) {} internal Snapshot providers => current; @@ -28,13 +29,16 @@ protected override Snapshot Build(TypeCacheSnapshot types) .OrderBy(static type => type.FullName, StringComparer.Ordinal) .Select(type => new Registration( type.GetCustomAttribute(false)!.id, - CreateExtension(type))) + CreateExtension(type) + )) .OrderBy(static entry => entry.id, StringComparer.Ordinal) .ToArray(); string? duplicate = providers.GroupBy(static entry => entry.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) + { throw new InvalidOperationException($"Editor gizmo provider ID '{duplicate}' is duplicated."); + } return new Snapshot(providers); } @@ -45,9 +49,10 @@ protected override Snapshot Build(TypeCacheSnapshot types) /// The immutable state snapshot consumed by this operation. /// protected override void DisposeSnapshot(Snapshot snapshot) - => DisposeExtensions(snapshot.registrations.Select(static entry => entry.provider)); + => DisposeExtensions(snapshot.registrations.Select(static entry => entry.provider)); internal sealed record Snapshot(Registration[] registrations); + internal sealed record Registration( string id, EditorGizmoProvider provider diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewService.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewService.cs index 8455f7bfa..ffa523916 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewService.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewService.cs @@ -32,7 +32,9 @@ public EditorPreviewHandle( int pixelHeight ) { if (value == 0 || deviceGeneration == 0) + { throw new ArgumentOutOfRangeException(nameof(value), "Preview identity and device generation must be non-zero."); + } ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); this.value = value; diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorRenderingModule.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorRenderingModule.cs index 3790f728f..e020054bc 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorRenderingModule.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorRenderingModule.cs @@ -1,17 +1,17 @@ -using Inno.References; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; - -using Inno.Scripting.Api; -using Inno.Extensibility.Types; using Inno.Core.Identity; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Rendering; -using EngineColor = Inno.Core.Mathematics.Color; using Inno.Rendering.Runtime; +using Inno.Scripting.Api; + +using EngineColor = Inno.Core.Mathematics.Color; namespace Inno.Editor.Rendering; @@ -28,10 +28,13 @@ public sealed class EditorRenderingModule : EditorModule private readonly Dictionary m_contentScopes = new(StringComparer.Ordinal); private readonly Dictionary m_compositionErrors = new(StringComparer.Ordinal); private readonly Dictionary m_controllerIds = new(StringComparer.Ordinal); + private readonly Dictionary m_manipulationSpaces = new(StringComparer.Ordinal); + private readonly Dictionary m_presentations = new(StringComparer.Ordinal); + private readonly Dictionary m_outputInputs = new(StringComparer.Ordinal); private readonly Dictionary m_outputRoutes = new(StringComparer.Ordinal); private readonly IEditorRenderingHost m_host; @@ -60,8 +63,7 @@ TypeCatalog types ) { m_host = host ?? throw new ArgumentNullException(nameof(host)); m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); - m_contributors = new EditorViewportContributorRegistry( - types ?? throw new ArgumentNullException(nameof(types))); + m_contributors = new EditorViewportContributorRegistry(types ?? throw new ArgumentNullException(nameof(types))); m_gizmos = new EditorGizmoProviderRegistry(types); } @@ -89,12 +91,16 @@ int pixelHeight ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); var frame = new EditorGizmoFrame(); if (!m_contentScopes.TryGetValue(viewportId, out ContentReadScope? content)) + { return frame; + } RuntimeIdentity? selected = (m_interactions.selection.selectedTarget as IdentityObject)? .identity.runtimeIdentity; var context = new EditorGizmoContext(content, selected, pixelWidth, pixelHeight); foreach (EditorGizmoProviderRegistry.Registration provider in m_gizmos.providers.registrations) + { provider.provider.Collect(context, frame); + } return frame; } @@ -141,9 +147,13 @@ public void SetOutputRoute( ) { ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); if (route is null) + { m_outputRoutes.Remove(viewportId); + } else + { m_outputRoutes[viewportId] = route; + } } /// @@ -199,7 +209,9 @@ ContentReadScope content ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); ArgumentNullException.ThrowIfNull(content); if (m_contentScopes.Remove(viewportId, out ContentReadScope? previous)) + { previous.Dispose(); + } m_contentScopes[viewportId] = content ?? throw new ArgumentNullException(nameof(content)); } @@ -233,19 +245,23 @@ out EditorViewportNavigationProfile profile ) { profile = EditorViewportNavigationProfile.disabled; if (!TryCreateContext(kind, viewportId, pixelWidth, pixelHeight, out EditorViewportContext? context)) + { return false; + } var failures = new List(); EditorViewportContributorRegistry.Registration[] contributors = GetApplicableContributors(context!, failures); foreach (EditorViewportContributorRegistry.Registration registration in contributors - .OrderByDescending(static value => value.attribute.controllerPriority) - .ThenBy(static value => value.attribute.id, StringComparer.Ordinal)) - { + .OrderByDescending(static value => value.attribute.controllerPriority) + .ThenBy(static value => value.attribute.id, StringComparer.Ordinal) + ) { try { EditorViewportNavigationProfile candidate = registration.contributor.ConfigureNavigation(context!) ?? throw new InvalidOperationException("Viewport contributor returned a null navigation profile."); if (!candidate.id.isValid) + { continue; + } profile = candidate; m_controllerIds[viewportId] = registration.attribute.id; SetCompositionFailures(viewportId, failures); @@ -254,7 +270,8 @@ out EditorViewportNavigationProfile profile catch (Exception exception) { failures.Add( - $"Viewport contributor '{registration.attribute.id}' navigation failed: {exception.Message}"); + $"Viewport contributor '{registration.attribute.id}' navigation failed: {exception.Message}" + ); } } m_controllerIds.Remove(viewportId); @@ -323,7 +340,9 @@ public void DrawControllerToolbar( int pixelHeight ) { if (!TryCreateContext(kind, viewportId, pixelWidth, pixelHeight, out EditorViewportContext? context)) + { return; + } var failures = new List(); EditorViewportContributorRegistry.Registration[] contributors = GetApplicableContributors(context!, failures); EditorViewportContributorRegistry.Registration? registration = SelectController(viewportId, contributors); @@ -338,8 +357,7 @@ int pixelHeight } catch (Exception exception) { - failures.Add( - $"Viewport contributor '{registration.attribute.id}' toolbar failed: {exception.Message}"); + failures.Add($"Viewport contributor '{registration.attribute.id}' toolbar failed: {exception.Message}"); } SetCompositionFailures(viewportId, failures); } @@ -374,18 +392,14 @@ out EditorViewportOutput output ) { output = default; if (!TryCreateContext(kind, viewportId, pixelWidth, pixelHeight, out EditorViewportContext? context)) + { return false; + } var failures = new List(); EditorViewportContributorRegistry.Registration[] contributors = GetApplicableContributors(context!, failures); if (contributors.Length == 0) { - PublishViewportStatistics( - kind, - viewportId, - pixelWidth, - pixelHeight, - "Unavailable", - contributorIds: "None"); + PublishViewportStatistics(kind, viewportId, pixelWidth, pixelHeight, "Unavailable", contributorIds: "None"); m_host.Release(viewportId); m_controllerIds.Remove(viewportId); m_manipulationSpaces.Remove(viewportId); @@ -399,10 +413,12 @@ out EditorViewportOutput output { if (!m_outputRoutes.TryGetValue(viewportId, out route) || route.layers.Count != contributors.Length - || route.layers.Any(layer => contributors.All(entry => entry.attribute.id != layer.modelId))) - { - failures.Add("Multiple rendering models accept this output; configure a RenderOutputRoute naming every contributor exactly once: " - + string.Join(", ", contributors.Select(static entry => entry.attribute.id))); + || route.layers.Any(layer => contributors.All(entry => entry.attribute.id != layer.modelId)) + ) { + failures.Add( + "Multiple rendering models accept this output; configure a RenderOutputRoute naming every contributor exactly once: " + + string.Join(", ", contributors.Select(static entry => entry.attribute.id)) + ); HandleViewportFailure(kind, viewportId, pixelWidth, pixelHeight, contributors, failures); return false; } @@ -418,16 +434,17 @@ out EditorViewportOutput output try { EditorViewportContext modelContext = route is null - ? context! - : context!.ForLayer(route.layers[index]); + ? context! + : context!.ForLayer(route.layers[index]); EditorViewportContribution contribution = registration.contributor.Build(modelContext) ?? throw new InvalidOperationException("Viewport contributor returned a null contribution."); if (targetFormat is RenderTextureFormat selectedFormat - && contribution.targetFormat != selectedFormat) - { + && contribution.targetFormat != selectedFormat + ) { failures.Add( - $"Viewport contributor '{registration.attribute.id}' requested target format " + - $"'{contribution.targetFormat}' while the composition uses '{selectedFormat}'."); + $"Viewport contributor '{registration.attribute.id}' requested target format " + + $"'{contribution.targetFormat}' while the composition uses '{selectedFormat}'." + ); continue; } targetFormat ??= contribution.targetFormat; @@ -451,27 +468,35 @@ out EditorViewportOutput output try { - output = m_host.Submit(new EditorViewportComposition( - viewportId, - pixelWidth, - pixelHeight, - targetFormat!.Value, - accepted.Select(( - value, - index - ) => new EditorViewportLayer( - value.registration.attribute.id, - value.contribution.pipeline, - value.contribution.data, - route is null ? value.registration.attribute.order : index)))); + output = m_host.Submit( + new EditorViewportComposition( + viewportId, + pixelWidth, + pixelHeight, + targetFormat!.Value, + accepted.Select(( + value, + index + ) => new EditorViewportLayer( + value.registration.attribute.id, + value.contribution.pipeline, + value.contribution.data, + route is null ? value.registration.attribute.order : index + )) + ) + ); EditorViewportContributorRegistry.Registration? controller = SelectController(viewportId, contributors); EditorViewportContribution? controllerContribution = controller is null ? null : accepted.FirstOrDefault(value => ReferenceEquals(value.registration, controller))?.contribution; if (controllerContribution?.manipulationSpace is EditorViewportManipulationSpace manipulationSpace) + { m_manipulationSpaces[viewportId] = manipulationSpace; + } else + { m_manipulationSpaces.Remove(viewportId); + } PublishViewportStatistics( kind, viewportId, @@ -479,7 +504,8 @@ out EditorViewportOutput output pixelHeight, output.isReady ? "Ready" : "Preparing", string.Join(", ", accepted.Select(static value => value.registration.attribute.id)), - accepted); + accepted + ); SetCompositionFailures(viewportId, failures); return true; } @@ -525,7 +551,9 @@ public void HandlePointer( int button ) { if (!TryCreateContext(kind, viewportId, pixelWidth, pixelHeight, out EditorViewportContext? context)) + { return; + } var failures = new List(); EditorViewportContributorRegistry.Registration[] contributors = GetApplicableContributors(context!, failures); EditorViewportContributorRegistry.Registration? registration = SelectController(viewportId, contributors); @@ -541,7 +569,8 @@ int button catch (Exception exception) { failures.Add( - $"Viewport contributor '{registration.attribute.id}' pointer handler failed: {exception.Message}"); + $"Viewport contributor '{registration.attribute.id}' pointer handler failed: {exception.Message}" + ); } SetCompositionFailures(viewportId, failures); } @@ -573,7 +602,9 @@ public void Release(string viewportId) m_outputRoutes.Remove(viewportId); m_manipulationSpaces.Remove(viewportId); if (m_contentScopes.Remove(viewportId, out ContentReadScope? content)) + { content.Dispose(); + } m_controllerIds.Remove(viewportId); m_host.Release(viewportId); } @@ -600,7 +631,9 @@ protected override void OnUpdate(EditorContext context) { RenderFrameStatistics? statistics = GraphicsSettings.frameStatistics; if (statistics is null) + { return; + } var groupId = new EditorStatisticGroupId("inno.rendering.frame"); context.statistics.Publish(new EditorStatistic[] { @@ -617,7 +650,12 @@ protected override void OnUpdate(EditorContext context) CreateStatistic("allocation-generation", "Allocation Generation", allocations.deviceGeneration.ToString(), 50), CreateStatistic("texture-allocations", "Transient Textures (lifetime)", allocations.textureAllocations.ToString(), 60), CreateStatistic("buffer-allocations", "Transient Buffers (lifetime)", allocations.bufferAllocations.ToString(), 70), - CreateStatistic("framebuffer-allocations", "Transient Framebuffers (lifetime)", allocations.frameBufferAllocations.ToString(), 80) + CreateStatistic( + "framebuffer-allocations", + "Transient Framebuffers (lifetime)", + allocations.frameBufferAllocations.ToString(), + 80 + ) }); } else @@ -634,15 +672,15 @@ EditorStatistic CreateStatistic( string label, string value, int order - ) - => new( - new EditorStatisticId($"inno.rendering.frame.{id}"), - groupId, - "Rendering", - label, - value, - C_RENDERING_STATISTICS_ORDER, - order); + ) => new( + new EditorStatisticId($"inno.rendering.frame.{id}"), + groupId, + "Rendering", + label, + value, + C_RENDERING_STATISTICS_ORDER, + order + ); } /// @@ -687,7 +725,9 @@ protected override void OnDispose() private void ClearContentScopes() { foreach (ContentReadScope scope in m_contentScopes.Values) + { scope.Dispose(); + } m_contentScopes.Clear(); } @@ -715,12 +755,11 @@ out EditorViewportContext? context pixelHeight, GetNavigationState(viewportId), m_contentScopes.GetValueOrDefault(viewportId, ContentReadScope.empty), - m_presentations.GetValueOrDefault( - viewportId, - new EditorViewportPresentation(EngineColor.DARKGRAY)), + m_presentations.GetValueOrDefault(viewportId, new EditorViewportPresentation(EngineColor.DARKGRAY)), m_host.viewContent, m_host.currentFrameIndex, - m_outputInputs.GetValueOrDefault(viewportId, RenderOutputInput.empty)); + m_outputInputs.GetValueOrDefault(viewportId, RenderOutputInput.empty) + ); return true; } @@ -734,7 +773,9 @@ private void PublishViewportStatistics( IReadOnlyList? contributions = null ) { if (m_context is null) + { return; + } string groupKey = $"inno.rendering.viewport.{viewportId}"; var groupId = new EditorStatisticGroupId(groupKey); string groupName = GetDisplayName(viewportId); @@ -747,26 +788,30 @@ private void PublishViewportStatistics( }; if (contributions is { Count: > 0 }) { - string pipeline = string.Join(", ", contributions.Select(static contribution => - string.IsNullOrWhiteSpace(contribution.contribution.pipeline?.pipelineTypeId) + string pipeline = string.Join( + ", ", + contributions.Select(static contribution => ( + string.IsNullOrWhiteSpace(contribution.contribution.pipeline?.pipelineTypeId) ? GraphicsSettings.defaultPipeline?.pipelineTypeId ?? "Project Default" - : contribution.contribution.pipeline.pipelineTypeId)); - statistics.Add(CreateStatistic( - "pipelines", - "Pipelines", - pipeline, - 40)); - statistics.Add(CreateStatistic( - "format", - "Target Format", - contributions[0].contribution.targetFormat.ToString(), - 50)); - statistics.Add(CreateStatistic( - "order", - "Composition Order", - string.Join(", ", contributions.Select(static contribution => - contribution.registration.attribute.order.ToString())), - 60)); + : contribution.contribution.pipeline.pipelineTypeId + )) + ); + statistics.Add(CreateStatistic("pipelines", "Pipelines", pipeline, 40)); + statistics.Add( + CreateStatistic("format", "Target Format", contributions[0].contribution.targetFormat.ToString(), 50) + ); + statistics.Add( + CreateStatistic( + "order", + "Composition Order", + string.Join( + ", ", + contributions.Select(static contribution => + contribution.registration.attribute.order.ToString()) + ), + 60 + ) + ); } m_context.statistics.Publish(statistics); return; @@ -776,15 +821,15 @@ EditorStatistic CreateStatistic( string label, string value, int order - ) - => new( - new EditorStatisticId($"{groupKey}.{id}"), - groupId, - groupName, - label, - value, - C_VIEWPORT_STATISTICS_ORDER, - order); + ) => new( + new EditorStatisticId($"{groupKey}.{id}"), + groupId, + groupName, + label, + value, + C_VIEWPORT_STATISTICS_ORDER, + order + ); } private EditorViewportContributorRegistry.Registration[] GetApplicableContributors( @@ -792,9 +837,9 @@ private EditorViewportContributorRegistry.Registration[] GetApplicableContributo List failures ) { if (!m_contributors.contributors.byKind.TryGetValue( - context.kind, - out EditorViewportContributorRegistry.Registration[]? registrations)) - { + context.kind, + out EditorViewportContributorRegistry.Registration[]? registrations + )) { return []; } @@ -804,13 +849,16 @@ List failures try { if (registration.contributor.CanContribute(context)) + { applicable.Add(registration); + } } catch (Exception exception) { failures.Add( - $"Viewport contributor '{registration.attribute.id}' participation check failed: " + - exception.Message); + $"Viewport contributor '{registration.attribute.id}' participation check failed: " + + exception.Message + ); } } return applicable.ToArray(); @@ -823,12 +871,12 @@ List failures if (m_controllerIds.TryGetValue(viewportId, out string? controllerId)) { EditorViewportContributorRegistry.Registration? selected = contributors.FirstOrDefault( - contributor => string.Equals( - contributor.attribute.id, - controllerId, - StringComparison.Ordinal)); + contributor => string.Equals(contributor.attribute.id, controllerId, StringComparison.Ordinal) + ); if (selected is not null) + { return selected; + } } return contributors @@ -851,7 +899,8 @@ List failures pixelWidth, pixelHeight, "Failed", - string.Join(", ", contributors.Select(static contributor => contributor.attribute.id))); + string.Join(", ", contributors.Select(static contributor => contributor.attribute.id)) + ); m_host.Release(viewportId); m_controllerIds.Remove(viewportId); m_manipulationSpaces.Remove(viewportId); @@ -864,9 +913,13 @@ IReadOnlyList failures ) { string[] distinct = failures.Distinct(StringComparer.Ordinal).ToArray(); if (distinct.Length == 0) + { m_compositionErrors.Remove(viewportId); + } else + { m_compositionErrors[viewportId] = string.Join(Environment.NewLine, distinct); + } } private sealed record AcceptedContribution( @@ -886,7 +939,9 @@ private static string GetDisplayName(string identifier) continue; } if (!capitalize) + { continue; + } characters[i] = char.ToUpperInvariant(characters[i]); capitalize = false; } diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs index 112f6145a..142e33e6f 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs @@ -1,9 +1,8 @@ -using Inno.References; using System; - using Inno.Core.Mathematics; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.References; using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Runtime; @@ -138,9 +137,20 @@ RenderOutputInput input internal EditorViewportContext ForLayer(RenderOutputLayer layer) { ArgumentNullException.ThrowIfNull(layer); - return new EditorViewportContext(editor, interactions, kind, viewportId, - pixelWidth, pixelHeight, navigation, content, presentation, - new SelectedViewContentCollector(viewContent, layer.sourceIds), frameIndex, input); + return new EditorViewportContext( + editor, + interactions, + kind, + viewportId, + pixelWidth, + pixelHeight, + navigation, + content, + presentation, + new SelectedViewContentCollector(viewContent, layer.sourceIds), + frameIndex, + input + ); } /// @@ -197,6 +207,7 @@ internal EditorViewportContext ForLayer(RenderOutputLayer layer) /// Gets the frame index shared by all Editor views in this output frame. /// public ulong frameIndex { get; } + /// /// Gets input located in this viewport's physical pixels. /// @@ -222,7 +233,9 @@ public EditorViewportPresentation( float pixelDensity = 1f ) { if (!float.IsFinite(pixelDensity) || pixelDensity <= 0f) + { throw new ArgumentOutOfRangeException(nameof(pixelDensity)); + } this.backgroundColor = backgroundColor; this.pixelDensity = pixelDensity; } @@ -247,17 +260,14 @@ public enum EditorViewportManipulationPlane /// Keeps the full three-dimensional translation, rotation, and scale controls. /// Spatial, - /// /// Uses the X/Y translation and scale axes with the Z rotation handle. /// XY, - /// /// Uses the X/Z translation and scale axes with the Y rotation handle. /// XZ, - /// /// Uses the Y/Z translation and scale axes with the X rotation handle. /// @@ -295,7 +305,9 @@ public EditorViewportManipulationSpace( EditorViewportManipulationPlane plane = EditorViewportManipulationPlane.Spatial ) { if (!Enum.IsDefined(plane)) + { throw new ArgumentOutOfRangeException(nameof(plane)); + } this.viewMatrix = viewMatrix; this.projectionMatrix = projectionMatrix; this.isOrthographic = isOrthographic; @@ -422,9 +434,7 @@ public abstract class EditorViewportContributor /// /// Creates a parameterless reloadable viewport contributor. /// - protected EditorViewportContributor() - { - } + protected EditorViewportContributor() {} /// /// Determines whether this rendering model participates in the supplied viewport content. @@ -466,9 +476,7 @@ public virtual EditorViewportNavigationProfile ConfigureNavigation(EditorViewpor /// /// Frame-only Editor and viewport context. /// - public virtual void DrawToolbar(EditorViewportContext context) - { - } + public virtual void DrawToolbar(EditorViewportContext context) {} /// /// Handles one pointer click when this contributor owns viewport interaction. @@ -476,7 +484,5 @@ public virtual void DrawToolbar(EditorViewportContext context) /// /// Normalized frame-only pointer context. /// - public virtual void HandlePointer(EditorViewportPointerContext context) - { - } + public virtual void HandlePointer(EditorViewportPointerContext context) {} } diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorRegistry.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorRegistry.cs index d261127da..8be9c509f 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorRegistry.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorRegistry.cs @@ -2,18 +2,14 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Inno.Extensibility.Types; namespace Inno.Editor.Rendering; -internal sealed class EditorViewportContributorRegistry - : TypeRegistry +internal sealed class EditorViewportContributorRegistry : TypeRegistry { internal EditorViewportContributorRegistry(TypeCatalog types) - : base(types) - { - } + : base(types) {} internal Snapshot contributors => current; @@ -40,7 +36,9 @@ protected override Snapshot Build(TypeCacheSnapshot types) .GroupBy(static registration => registration.attribute.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicateId is not null) + { throw new InvalidOperationException($"Editor viewport contributor ID '{duplicateId}' is duplicated."); + } IReadOnlyDictionary byKind = registrations .GroupBy(static registration => registration.attribute.kind) .ToDictionary(static group => group.Key, static group => group.ToArray()); @@ -59,7 +57,8 @@ protected override void DisposeSnapshot(Snapshot snapshot) private Registration CreateRegistration(Type type) => new( type.GetCustomAttribute(inherit: false)!, - CreateExtension(type)); + CreateExtension(type) + ); internal sealed record Snapshot( long revision, diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigation.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigation.cs index 23ab6ed7b..7b2a72e3d 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigation.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigation.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Mathematics; namespace Inno.Editor.Rendering; @@ -13,7 +12,6 @@ public enum EditorViewportProjection /// Uses a parallel projection controlled by an orthographic half-height. /// Orthographic, - /// /// Uses a perspective projection controlled by a vertical field of view. /// @@ -29,12 +27,10 @@ public enum EditorViewportNavigationMode /// Pans and zooms over a provider-defined plane. /// Planar, - /// /// Rotates around a focus pivot and dollies along the view direction. /// Orbit, - /// /// Moves and looks freely from the current view position. /// @@ -51,32 +47,26 @@ public enum EditorViewportNavigationCapabilities /// Disables host-owned navigation. /// None = 0, - /// /// Allows translating the view parallel to its image plane. /// Pan = 1 << 0, - /// /// Allows changing orthographic size or perspective focus distance. /// Zoom = 1 << 1, - /// /// Allows the complete plane-oriented pan and zoom interaction model. /// Planar = Pan | Zoom, - /// /// Allows pivot-oriented orbit and dolly. /// Orbit = 1 << 2, - /// /// Allows free-look movement. /// Fly = 1 << 3, - /// /// Allows framing a provider-supplied or host-derived selection bound. /// @@ -144,9 +134,13 @@ public EditorViewportFocusBounds( float radius ) { if (!IsFinite(center)) + { throw new ArgumentException("Focus center components must be finite.", nameof(center)); + } if (!float.IsFinite(radius) || radius < 0f) + { throw new ArgumentOutOfRangeException(nameof(radius)); + } this.center = center; this.radius = radius; } @@ -187,21 +181,26 @@ public EditorViewportNavigationProfile( EditorViewportNavigationMode defaultMode ) { if (!id.isValid) + { throw new ArgumentException("A valid navigation profile ID is required.", nameof(id)); + } const EditorViewportNavigationCapabilities validCapabilities = EditorViewportNavigationCapabilities.Pan - | EditorViewportNavigationCapabilities.Zoom - | EditorViewportNavigationCapabilities.Orbit - | EditorViewportNavigationCapabilities.Fly - | EditorViewportNavigationCapabilities.FrameSelection; + | EditorViewportNavigationCapabilities.Zoom + | EditorViewportNavigationCapabilities.Orbit + | EditorViewportNavigationCapabilities.Fly + | EditorViewportNavigationCapabilities.FrameSelection; if ((capabilities & ~validCapabilities) != 0) + { throw new ArgumentOutOfRangeException(nameof(capabilities)); + } if (capabilities != EditorViewportNavigationCapabilities.None - && !SupportsMode(capabilities, defaultMode)) - { + && !SupportsMode(capabilities, defaultMode) + ) { throw new ArgumentException( "The default navigation mode must be enabled by the profile capabilities.", - nameof(defaultMode)); + nameof(defaultMode) + ); } this.id = id; this.capabilities = capabilities; @@ -279,22 +278,22 @@ const EditorViewportNavigationCapabilities validCapabilities public static EditorViewportNavigationProfile disabled { get; } = new( new EditorViewportNavigationProfileId("inno.editor.navigation.disabled"), EditorViewportNavigationCapabilities.None, - EditorViewportNavigationMode.Planar); + EditorViewportNavigationMode.Planar + ); private static bool SupportsMode( EditorViewportNavigationCapabilities capabilities, EditorViewportNavigationMode mode - ) - => mode switch - { - EditorViewportNavigationMode.Planar => - (capabilities & EditorViewportNavigationCapabilities.Planar) != 0, - EditorViewportNavigationMode.Orbit => - capabilities.HasFlag(EditorViewportNavigationCapabilities.Orbit), - EditorViewportNavigationMode.Fly => - capabilities.HasFlag(EditorViewportNavigationCapabilities.Fly), - _ => false - }; + ) => mode switch + { + EditorViewportNavigationMode.Planar => + (capabilities & EditorViewportNavigationCapabilities.Planar) != 0, + EditorViewportNavigationMode.Orbit => + capabilities.HasFlag(EditorViewportNavigationCapabilities.Orbit), + EditorViewportNavigationMode.Fly => + capabilities.HasFlag(EditorViewportNavigationCapabilities.Fly), + _ => false + }; } /// @@ -332,7 +331,9 @@ public EditorViewportProjection projection set { if (!Enum.IsDefined(value)) + { throw new ArgumentOutOfRangeException(nameof(value)); + } m_projection = value; isInitialized = true; } @@ -347,7 +348,9 @@ public EditorViewportNavigationMode mode set { if (!Enum.IsDefined(value)) + { throw new ArgumentOutOfRangeException(nameof(value)); + } m_mode = value; isInitialized = true; } @@ -377,7 +380,9 @@ public Quaternion rotation { ValidateFinite(value, nameof(value)); if (value.LengthSquared() < 0.000001f) + { throw new ArgumentException("Navigation rotation must have a usable magnitude.", nameof(value)); + } m_rotation = value.normalized; isInitialized = true; } @@ -406,7 +411,9 @@ public float orthographicSize set { if (!float.IsFinite(value) || value < C_MINIMUM_ORTHOGRAPHIC_SIZE) + { throw new ArgumentOutOfRangeException(nameof(value)); + } m_orthographicSize = value; isInitialized = true; } @@ -421,7 +428,9 @@ public float fieldOfView set { if (!float.IsFinite(value) || value < C_MINIMUM_FIELD_OF_VIEW || value > C_MAXIMUM_FIELD_OF_VIEW) + { throw new ArgumentOutOfRangeException(nameof(value)); + } m_fieldOfView = value; isInitialized = true; } @@ -436,7 +445,9 @@ public float nearClip set { if (!float.IsFinite(value) || value <= 0f || value >= m_farClip) + { throw new ArgumentOutOfRangeException(nameof(value)); + } m_nearClip = value; isInitialized = true; } @@ -451,7 +462,9 @@ public float farClip set { if (!float.IsFinite(value) || value <= m_nearClip) + { throw new ArgumentOutOfRangeException(nameof(value)); + } m_farClip = value; isInitialized = true; } @@ -466,7 +479,9 @@ public float focusDistance set { if (!float.IsFinite(value) || value <= 0f) + { throw new ArgumentOutOfRangeException(nameof(value)); + } m_focusDistance = value; isInitialized = true; } @@ -481,7 +496,9 @@ public float movementSpeed set { if (!float.IsFinite(value) || value <= 0f) + { throw new ArgumentOutOfRangeException(nameof(value)); + } m_movementSpeed = value; } } @@ -506,8 +523,8 @@ float orthographicSize ValidateFinite(position, nameof(position)); ValidateRotation(rotation, nameof(rotation)); if (!float.IsFinite(orthographicSize) - || orthographicSize < C_MINIMUM_ORTHOGRAPHIC_SIZE) - { + || orthographicSize < C_MINIMUM_ORTHOGRAPHIC_SIZE + ) { throw new ArgumentOutOfRangeException(nameof(orthographicSize)); } m_position = position; @@ -546,14 +563,18 @@ float farClip ValidateRotation(rotation, nameof(rotation)); if (!float.IsFinite(fieldOfView) || fieldOfView < C_MINIMUM_FIELD_OF_VIEW - || fieldOfView > C_MAXIMUM_FIELD_OF_VIEW) - { + || fieldOfView > C_MAXIMUM_FIELD_OF_VIEW + ) { throw new ArgumentOutOfRangeException(nameof(fieldOfView)); } if (!float.IsFinite(nearClip) || nearClip <= 0f) + { throw new ArgumentOutOfRangeException(nameof(nearClip)); + } if (!float.IsFinite(farClip) || farClip <= nearClip) + { throw new ArgumentOutOfRangeException(nameof(farClip)); + } m_position = position; m_rotation = rotation.normalized; m_fieldOfView = fieldOfView; @@ -568,7 +589,9 @@ private static void ValidateFinite( string parameterName ) { if (!float.IsFinite(value.x) || !float.IsFinite(value.y) || !float.IsFinite(value.z)) + { throw new ArgumentException("Navigation position components must be finite.", parameterName); + } } private static void ValidateFinite( @@ -578,8 +601,8 @@ string parameterName if (!float.IsFinite(value.x) || !float.IsFinite(value.y) || !float.IsFinite(value.z) - || !float.IsFinite(value.w)) - { + || !float.IsFinite(value.w) + ) { throw new ArgumentException("Navigation rotation components must be finite.", parameterName); } } @@ -590,6 +613,8 @@ string parameterName ) { ValidateFinite(value, parameterName); if (value.LengthSquared() < 0.000001f) + { throw new ArgumentException("Navigation rotation must have a usable magnitude.", parameterName); + } } } diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs index a51cdf3e8..fe192f557 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs @@ -217,18 +217,24 @@ IEnumerable layers ArgumentNullException.ThrowIfNull(layers); EditorViewportLayer[] materializedLayers = layers.ToArray(); if (materializedLayers.Length == 0) + { throw new ArgumentException("A viewport composition requires at least one model layer.", nameof(layers)); + } if (materializedLayers.Any(static layer => layer is null)) + { throw new ArgumentException("A viewport composition cannot contain null model layers.", nameof(layers)); + } if (materializedLayers.Select(static layer => layer.contributorId).Distinct(StringComparer.Ordinal).Count() - != materializedLayers.Length) - { + != materializedLayers.Length + ) { throw new ArgumentException("Viewport contributor identities must be unique.", nameof(layers)); } - m_layers = Array.AsReadOnly(materializedLayers - .OrderBy(static layer => layer.order) - .ThenBy(static layer => layer.contributorId, StringComparer.Ordinal) - .ToArray()); + m_layers = Array.AsReadOnly( + materializedLayers + .OrderBy(static layer => layer.order) + .ThenBy(static layer => layer.contributorId, StringComparer.Ordinal) + .ToArray() + ); this.viewportId = viewportId; this.pixelWidth = pixelWidth; this.pixelHeight = pixelHeight; diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs index 55c7eb5e6..d0d3cd23d 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs @@ -11,6 +11,7 @@ using Inno.Rendering.Assets; namespace Inno.Editor.Rendering; + /// /// Edits Pipeline sources and typed extension settings without changing canonical rendering assets before Save. /// @@ -19,6 +20,7 @@ public sealed class PipelineDocuments : EditorModule { internal const string C_HISTORY = "inno.pipeline/draft"; private readonly TypeCatalog m_types; + /// /// Gets the authoritative asset pipeline used by source inspectors. /// @@ -59,6 +61,7 @@ EditorInteractions interactions /// The persistent source identity used by draft operations. /// public Guid Open(AssetPath path) => drafts.Open(path); + /// /// Reads a detached current-generation Pipeline value; its referenced canonical assets must not be mutated. /// @@ -69,6 +72,7 @@ EditorInteractions interactions /// The unsaved native Pipeline value. /// public RenderPipelineAsset Read(Guid assetId) => drafts.Read(assetId); + /// /// Changes a draft through shared History without publishing it to Scene/Game. /// @@ -86,6 +90,7 @@ public void Replace( RenderPipelineAsset candidate, string? mergeKey = null ) => drafts.Replace(assetId, candidate, mergeKey); + /// /// Captures typed Pipeline settings with this source owner's complete reference and dependency context. /// @@ -105,8 +110,7 @@ public void ReplaceSettings( Guid assetId, TSettings settings, string? mergeKey = null - ) - where TSettings : class, ISerializable + ) where TSettings : class, ISerializable { RenderPipelineAsset pipeline = Read(assetId); pipeline.pipelineState = new SerializedRenderExtensionState(assets.CaptureProperties(settings)); @@ -126,16 +130,22 @@ public void ReplaceSettings( public ISerializable? RestoreSettings(SerializedRenderExtensionState state) { if (state.stableTypeId == Guid.Empty) + { return null; + } Type type = m_types.Resolve(new TypeRef(state.stableTypeId)); if (Activator.CreateInstance(type) is not ISerializable settings) + { throw new InvalidOperationException("Pipeline settings must be a constructible native serializable type."); + } assets.RestoreProperties(state.stableTypeId, state.propertyData, settings); return settings; } - internal static bool Recoverable(Exception error) => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException - && Inno.Core.Execution.RetirementPendingException.Find(error) is null; + internal static bool Recoverable(Exception error) + => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException + && Inno.Core.Execution.RetirementPendingException.Find(error) is null; + /// /// Initializes this feature when its owning runtime becomes active. /// @@ -143,6 +153,7 @@ internal static bool Recoverable(Exception error) => error is IOException or Una /// The context that supplies state and services for this operation. /// protected override void OnStart(EditorContext context) => drafts.Start(); + /// /// Advances this feature using the current runtime state. /// @@ -150,6 +161,7 @@ internal static bool Recoverable(Exception error) => error is IOException or Una /// The context that supplies state and services for this operation. /// protected override void OnUpdate(EditorContext context) => drafts.Update(); + /// /// Stops this feature before its owning runtime releases the active generation. /// diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/RenderPipelineAssetCreationTemplate.cs b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/RenderPipelineAssetCreationTemplate.cs index b076b7f2d..52c3f1c9f 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/RenderPipelineAssetCreationTemplate.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/RenderPipelineAssetCreationTemplate.cs @@ -11,5 +11,6 @@ namespace Inno.Editor.Rendering; "New Render Pipeline", groupOrder: 200, itemOrder: 200, - separatorBeforeGroup: true)] + separatorBeforeGroup: true +)] internal sealed class RenderPipelineAssetCreationTemplate : AssetCreationTemplate; diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Properties/ScriptingApi.cs b/src/composition/editor/features/Inno.Editor.Rendering/Properties/ScriptingApi.cs index 93569ee9e..018ac3288 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Properties/ScriptingApi.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Editor.Rendering; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Rendering", - "Inno.Editor.Rendering", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Rendering", "Inno.Editor.Rendering", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorViewportKindId), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(PipelineDocuments), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticPublisher.cs b/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticPublisher.cs index b23c2aacb..d804d5cfb 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticPublisher.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; using Inno.Scene; @@ -22,18 +21,14 @@ internal static void PublishMissingElements(IReadOnlyList scenes) { foreach (MissingGameComponent missing in gameObject.GetComponents().OfType()) { - diagnostics.Add(CreateMissingDiagnostic( - scene, - missing.identity.persistentId, - missing.missingTypeName)); + diagnostics.Add( + CreateMissingDiagnostic(scene, missing.identity.persistentId, missing.missingTypeName) + ); } } foreach (MissingGameSystem missing in scene.GetSystems().OfType()) { - diagnostics.Add(CreateMissingDiagnostic( - scene, - missing.identity.persistentId, - missing.missingTypeName)); + diagnostics.Add(CreateMissingDiagnostic(scene, missing.identity.persistentId, missing.missingTypeName)); } } Diagnostics.Set(C_MISSING_ELEMENTS, diagnostics); @@ -46,11 +41,10 @@ internal static void PublishReload(IReadOnlyList diagnost C_RELOAD, diagnostics.Select(static diagnostic => diagnostic.severity switch { - DiagnosticSeverity.Warning => Diagnostic.Warning( - diagnostic.code, - diagnostic.message), + DiagnosticSeverity.Warning => Diagnostic.Warning(diagnostic.code, diagnostic.message), _ => Diagnostic.Error(diagnostic.code, diagnostic.message) - })); + }) + ); } internal static void ClearAll() @@ -63,9 +57,9 @@ private static Diagnostic CreateMissingDiagnostic( GameScene scene, Guid elementId, string missingTypeName - ) - => Diagnostic.Warning( - "INNOHR0002", - $"'{missingTypeName}' is unavailable in scene '{scene.name}' " + - $"({scene.identity.persistentId:D}), element {elementId:D}. Its identity and serialized state are preserved."); + ) => Diagnostic.Warning( + "INNOHR0002", + $"'{missingTypeName}' is unavailable in scene '{scene.name}' " + + $"({scene.identity.persistentId:D}), element {elementId:D}. Its identity and serialized state are preserved." + ); } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticTracker.cs b/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticTracker.cs index 96112aff7..07ecf4452 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticTracker.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Diagnostics/SceneStateDiagnosticTracker.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Extensibility.Types; using Inno.Scene; @@ -25,16 +24,16 @@ internal void Reconcile(bool force = false) { IReadOnlyList scenes = m_world.loadedScenes; long typeCacheVersion = m_types.isInitialized - ? m_types.current.version - : -1; + ? m_types.current.version + : -1; bool scenesChanged = scenes.Count != m_scenes.Length; if (!scenesChanged) { for (int i = 0; i < scenes.Count; i++) { - if (m_scenes[i].TryGetTarget(out GameScene? tracked) && - ReferenceEquals(scenes[i], tracked)) - { + if (m_scenes[i].TryGetTarget(out GameScene? tracked) + && ReferenceEquals(scenes[i], tracked) + ) { continue; } scenesChanged = true; @@ -42,12 +41,16 @@ internal void Reconcile(bool force = false) } } if (!force && !scenesChanged && typeCacheVersion == m_typeCacheVersion) + { return; + } SceneStateDiagnosticPublisher.PublishMissingElements(scenes); var references = new WeakReference[scenes.Count]; for (int i = 0; i < scenes.Count; i++) + { references[i] = new WeakReference(scenes[i]); + } m_scenes = references; m_typeCacheVersion = typeCacheVersion; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneDiagnosticPublisher.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneDiagnosticPublisher.cs index 6a0fe268e..02dceb7ef 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneDiagnosticPublisher.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; using Inno.Scene; @@ -25,7 +24,9 @@ string message ArgumentException.ThrowIfNullOrWhiteSpace(message); string state = $"{code}:{message}"; if (string.Equals(m_restoreState, state, StringComparison.Ordinal)) + { return false; + } Diagnostics.Set(C_RESTORE_GROUP, Diagnostic.Error(code, message)); m_restoreState = state; return true; @@ -34,7 +35,9 @@ string message internal void ResolveRestore() { if (string.IsNullOrEmpty(m_restoreState)) + { return; + } Diagnostics.Clear(C_RESTORE_GROUP); m_restoreState = string.Empty; } @@ -47,16 +50,17 @@ Exception exception ArgumentNullException.ThrowIfNull(exception); Guid targetId = scene.identity.persistentId; string state = exception.ToString(); - if (m_synchronizationStates.TryGetValue(targetId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_synchronizationStates.TryGetValue(targetId, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return false; } Diagnostics.Set( targetId, C_SYNCHRONIZATION_GROUP, Diagnostic.Error("SCENE-SYNCHRONIZATION", exception.Message), - scene.name); + scene.name + ); m_synchronizationStates[targetId] = state; return true; } @@ -67,18 +71,29 @@ string sourcePath ) { Guid sceneId = scene.identity.persistentId; string state = "SCENE-SOURCE-MISSING:" + sourcePath; - if (m_synchronizationStates.TryGetValue(sceneId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) + if (m_synchronizationStates.TryGetValue(sceneId, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return; - Diagnostics.Set(sceneId, C_SYNCHRONIZATION_GROUP, - Diagnostic.Warning("SCENE-SOURCE-MISSING", $"Scene source '{sourcePath}' is unavailable; its assignment and current edits are preserved."), scene.name); + } + Diagnostics.Set( + sceneId, + C_SYNCHRONIZATION_GROUP, + Diagnostic.Warning( + "SCENE-SOURCE-MISSING", + $"Scene source '{sourcePath}' is unavailable; its assignment and current edits are preserved." + ), + scene.name + ); m_synchronizationStates[sceneId] = state; } internal void ResolveSynchronization(Guid sceneId) { if (!m_synchronizationStates.Remove(sceneId)) + { return; + } Diagnostics.Clear(sceneId, C_SYNCHRONIZATION_GROUP); } @@ -90,11 +105,17 @@ Exception exception ArgumentNullException.ThrowIfNull(exception); Guid targetId = scene.identity.persistentId; string state = exception.ToString(); - if (m_dirtyCheckStates.TryGetValue(targetId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) + if (m_dirtyCheckStates.TryGetValue(targetId, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return false; - Diagnostics.Set(targetId, C_DIRTY_CHECK_GROUP, - Diagnostic.Error("SCENE-DIRTY-CHECK", exception.Message), scene.name); + } + Diagnostics.Set( + targetId, + C_DIRTY_CHECK_GROUP, + Diagnostic.Error("SCENE-DIRTY-CHECK", exception.Message), + scene.name + ); m_dirtyCheckStates[targetId] = state; return true; } @@ -102,7 +123,9 @@ Exception exception internal void ResolveDirtyCheck(Guid sceneId) { if (!m_dirtyCheckStates.Remove(sceneId)) + { return; + } Diagnostics.Clear(sceneId, C_DIRTY_CHECK_GROUP); } @@ -113,12 +136,16 @@ internal void RetainSynchronizationTargets(IReadOnlySet sceneIds) .Where(id => !sceneIds.Contains(id)) .ToArray(); for (int i = 0; i < removed.Length; i++) + { ResolveSynchronization(removed[i]); + } Guid[] removedDirtyChecks = m_dirtyCheckStates.Keys .Where(id => !sceneIds.Contains(id)) .ToArray(); for (int i = 0; i < removedDirtyChecks.Length; i++) + { ResolveDirtyCheck(removedDirtyChecks[i]); + } } /// @@ -128,8 +155,12 @@ public void Dispose() { ResolveRestore(); foreach (Guid sceneId in m_synchronizationStates.Keys.ToArray()) + { ResolveSynchronization(sceneId); + } foreach (Guid sceneId in m_dirtyCheckStates.Keys.ToArray()) + { ResolveDirtyCheck(sceneId); + } } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.History.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.History.cs index ad1f8f7c6..76b743092 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.History.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.History.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,7 +25,6 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - internal SceneDocumentSnapshot CaptureDocumentSnapshot(GameScene scene) { ArgumentNullException.ThrowIfNull(scene); @@ -36,15 +34,15 @@ internal SceneDocumentSnapshot CaptureDocumentSnapshot(GameScene scene) SceneDocumentSnapshot? playBaseline = null; if (m_playModeSession is PlayModeLease playModeSession) { - if (playModeSession.TryGetSnapshot( - scene.identity.persistentId, - out SceneDocumentSnapshot snapshot)) + if (playModeSession.TryGetSnapshot(scene.identity.persistentId, out SceneDocumentSnapshot snapshot)) { playBaseline = snapshot; } } else + { document = GetOrCreateDocument(scene); + } SerializationContext serializationContext = AssetSerializationContext.Create(m_assets); return new SceneDocumentSnapshot( scene.identity.persistentId, @@ -54,7 +52,8 @@ internal SceneDocumentSnapshot CaptureDocumentSnapshot(GameScene scene) document?.savedHash.ToArray() ?? playBaseline?.savedHash.ToArray() ?? [], document?.isDirty ?? false, world.GetSceneIndex(scene), - document?.nextRefreshTimestamp ?? 0); + document?.nextRefreshTimestamp ?? 0 + ); } internal GameScene RestoreDocumentSnapshot(SceneDocumentSnapshot snapshot) @@ -71,7 +70,8 @@ internal GameScene RestoreDocumentSnapshot(SceneDocumentSnapshot snapshot) scene, snapshot.sourcePath, snapshot.sourceAssetId, - snapshot.savedHash.ToArray()) + snapshot.savedHash.ToArray() + ) { isDirty = snapshot.isDirty, nextRefreshTimestamp = snapshot.nextRefreshTimestamp @@ -99,9 +99,13 @@ internal void RestoreActiveScene(Guid? activeSceneId) { using IDisposable scope = EnterPresentationScope(); if (activeSceneId is Guid sceneId && FindEngineObject(sceneId) is GameScene { isLoaded: true } active) + { world.SetActiveScene(active); + } else if (world.loadedScenes.Count > 0 && world.activeScene is null) + { world.SetActiveScene(world.loadedScenes[0]); + } } internal void RestoreSelection( @@ -109,10 +113,14 @@ internal void RestoreSelection( bool selectActiveSceneWhenMissing = true ) { if (m_selection is null) + { return; + } object? target = selectedId is Guid id ? FindEngineObject(id) : null; if (target is null && selectActiveSceneWhenMissing) + { target = world.activeScene; + } m_selection.SetSelection(target); } @@ -120,8 +128,8 @@ internal void RestoreSelection( private Guid? GetSelectedSceneObjectId() => m_selection?.selectedTarget is EngineObject { isDestroyed: false } selected - ? selected.identity.persistentId - : null; + ? selected.identity.persistentId + : null; internal sealed record SceneDocumentSnapshot( Guid sceneId, @@ -133,5 +141,4 @@ internal sealed record SceneDocumentSnapshot( int sceneIndex, long nextRefreshTimestamp = 0 ); - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs index 16cff4faa..aab674f14 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,7 +25,6 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - /// /// Gets whether a scene contains unsaved serialized changes. /// @@ -49,17 +47,23 @@ public bool IsDirty(GameScene scene) try { if (!SynchronizeSource(scene, document)) + { return true; + } } catch (Exception exception) { document.isDirty = true; if (m_diagnostics.PublishSynchronizationFailure(scene, exception)) + { m_log.Write(LogLevel.Error, "Scene document synchronization failed: {0}", [exception]); + } return true; } if (string.IsNullOrEmpty(document.sourcePath)) + { return true; + } if (!string.Equals(scene.name, GetAssetName(document.sourcePath), StringComparison.Ordinal)) { document.isDirty = true; @@ -68,7 +72,9 @@ public bool IsDirty(GameScene scene) long now = Stopwatch.GetTimestamp(); if (now < document.nextRefreshTimestamp) + { return document.isDirty; + } document.nextRefreshTimestamp = now + (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); try @@ -80,7 +86,9 @@ public bool IsDirty(GameScene scene) { document.isDirty = true; if (m_diagnostics.PublishDirtyCheckFailure(scene, exception)) + { m_log.Write(LogLevel.Error, "Scene dirty check failed: {0}", [exception]); + } } return document.isDirty; } @@ -142,9 +150,9 @@ string currentDirectory string currentParent = NormalizePath(Path.GetDirectoryName(currentPath)); string targetDirectory = NormalizePath(currentDirectory); string relativePath; - if (!string.IsNullOrEmpty(currentPath) && - string.Equals(currentParent, targetDirectory, StringComparison.Ordinal)) - { + if (!string.IsNullOrEmpty(currentPath) + && string.Equals(currentParent, targetDirectory, StringComparison.Ordinal) + ) { relativePath = RenameSceneSourceIfNeeded(scene, document); } else @@ -175,10 +183,10 @@ string currentDirectory EnsureCanPersist(); EnsureEditable(gameObject.scene); string relativePath = CreateUniquePath(currentDirectory, gameObject.name, C_PREFAB_EXTENSION); - if (!m_assets.Save( - AssetPath.Project(relativePath), - PrefabAsset.Capture(gameObject, m_serialization, m_assets))) + if (!m_assets.Save(AssetPath.Project(relativePath), PrefabAsset.Capture(gameObject, m_serialization, m_assets))) + { throw new InvalidOperationException($"No asset importer could save prefab '{relativePath}'."); + } return relativePath; } @@ -196,10 +204,11 @@ public GameScene Open(string relativePath) ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); EnsureCanPersist(); string normalizedPath = NormalizePath(relativePath); - SceneDocument? existing = m_documents.Values.FirstOrDefault(document => - document.scene.isLoaded && - !document.scene.isDestroyed && - string.Equals(document.sourcePath, normalizedPath, StringComparison.OrdinalIgnoreCase)); + SceneDocument? existing = m_documents.Values.FirstOrDefault(document => ( + document.scene.isLoaded + && !document.scene.isDestroyed + && string.Equals(document.sourcePath, normalizedPath, StringComparison.OrdinalIgnoreCase) + )); if (existing is not null) { m_runtimeSession.scenes.SetActiveScene(existing.scene); @@ -213,7 +222,8 @@ public GameScene Open(string relativePath) m_runtimeSession.scenes.LoadSceneAdditive(scene); m_documents.Add( scene.identity.persistentId, - new SceneDocument(scene, normalizedPath, asset.identity.persistentId, savedHash)); + new SceneDocument(scene, normalizedPath, asset.identity.persistentId, savedHash) + ); return scene; } @@ -239,9 +249,10 @@ out string relativePath EnsurePresentedScene(scene); relativePath = playModeSession.TryGetSnapshot( scene.identity.persistentId, - out SceneDocumentSnapshot snapshot) - ? snapshot.sourcePath - : string.Empty; + out SceneDocumentSnapshot snapshot + ) + ? snapshot.sourcePath + : string.Empty; return !string.IsNullOrEmpty(relativePath); } SceneDocument document = GetOrCreateDocument(scene); @@ -262,26 +273,32 @@ private void SaveSceneAtPath( string relativePath ) { SceneDocument document = GetOrCreateDocument(scene); - if (document.sourceAssetId != Guid.Empty && - string.Equals(document.sourcePath, relativePath, StringComparison.Ordinal) && !SynchronizeSource(scene, document)) - throw new InvalidOperationException($"Scene source '{relativePath}' is unavailable. Restore its source or explicitly save to another directory."); + if (document.sourceAssetId != Guid.Empty + && string.Equals(document.sourcePath, relativePath, StringComparison.Ordinal) && !SynchronizeSource(scene, document) + ) { + throw new InvalidOperationException( + $"Scene source '{relativePath}' is unavailable. Restore its source or explicitly save to another directory." + ); + } scene.name = GetAssetName(relativePath); bool exists = m_assets.TryLoad(AssetPath.Parse(relativePath), out SceneAsset? sceneAsset); sceneAsset ??= new SceneAsset(); sceneAsset.CaptureFrom(scene, m_serialization, m_assets); bool saved = exists - ? m_assets.Save(sceneAsset) - : m_assets.Save(AssetPath.Parse(relativePath), sceneAsset); + ? m_assets.Save(sceneAsset) + : m_assets.Save(AssetPath.Parse(relativePath), sceneAsset); if (!saved) + { throw new InvalidOperationException($"No asset importer could save scene '{relativePath}'."); + } byte[] savedHash = ComputeSceneHash(scene); document.sourcePath = relativePath; document.sourceAssetId = sceneAsset.identity.persistentId; document.savedHash = savedHash; document.isDirty = false; - document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + - (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); + document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + + (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); } private SceneDocument GetOrCreateDocument(GameScene scene) @@ -302,7 +319,8 @@ private void EnsureCanPersist() if (!canPersist) { throw new InvalidOperationException( - "Scene and prefab persistence is unavailable while Play Mode runtime copies are active."); + "Scene and prefab persistence is unavailable while Play Mode runtime copies are active." + ); } } @@ -314,11 +332,15 @@ private byte[] ComputeSceneHash( SerializationContext context = AssetSerializationContext.Create(m_assets, dependencies); SerializationSnapshot captured = m_serialization.CaptureSnapshot(scene, context, document?.observedSnapshot); if (document is not null && ReferenceEquals(captured, document.observedSnapshot)) + { return document.observedHash!; + } using var algorithm = SHA256.Create(); using (var digest = new CryptoStream(Stream.Null, algorithm, CryptoStreamMode.Write, leaveOpen: true)) using (var output = new BufferedStream(digest, 64 * 1024)) + { captured.WriteTo(output); + } byte[] hash = algorithm.Hash ?? throw new InvalidOperationException("Scene content hashing did not complete."); if (document is not null) { @@ -331,8 +353,7 @@ private byte[] ComputeSceneHash( private bool HasSerializedChanges( GameScene scene, SceneDocument document - ) - => !ComputeSceneHash(scene, document).AsSpan().SequenceEqual(document.savedHash); + ) => !ComputeSceneHash(scene, document).AsSpan().SequenceEqual(document.savedHash); private string CreateUniquePath( string directory, @@ -343,7 +364,9 @@ string extension string fileName = SanitizeFileName(name); string candidate = Combine(directory, fileName + extension); for (int suffix = 1; m_assets.TryGetFileSystemEntry(AssetPath.Parse(candidate), out _); suffix++) + { candidate = Combine(directory, $"{fileName} {suffix}{extension}"); + } return candidate; } @@ -352,12 +375,16 @@ private static string CreateUniqueSceneName(IReadOnlyList scenes) const string c_baseName = "Untitled Scene"; var names = scenes.Select(static scene => scene.name).ToHashSet(StringComparer.Ordinal); if (!names.Contains(c_baseName)) + { return c_baseName; + } for (int suffix = 1; ; suffix++) { string candidate = $"{c_baseName} {suffix}"; if (!names.Contains(candidate)) + { return candidate; + } } } @@ -370,23 +397,24 @@ private static string GetAssetName(string relativePath) private static string SanitizeFileName(string value) { char[] invalid = Path.GetInvalidFileNameChars(); - string sanitized = new((value ?? string.Empty) - .Trim() - .Select(character => invalid.Contains(character) ? '_' : character) - .ToArray()); + string sanitized = new( + (value ?? string.Empty) + .Trim() + .Select(character => invalid.Contains(character) ? '_' : character) + .ToArray() + ); return string.IsNullOrWhiteSpace(sanitized) ? "Untitled" : sanitized; } private static string Combine( string directory, string fileName - ) - => string.IsNullOrEmpty(directory) ? fileName : $"{directory}/{fileName}"; + ) => string.IsNullOrEmpty(directory) ? fileName : $"{directory}/{fileName}"; private static string NormalizePath(string? path) => string.IsNullOrWhiteSpace(path) - ? string.Empty - : path.Replace('\\', '/').Trim('/'); + ? string.Empty + : path.Replace('\\', '/').Trim('/'); private sealed class SceneDocument( GameScene scene, @@ -401,26 +429,30 @@ byte[] savedHash /// The scene value used as part of this type's public representation. /// public GameScene scene = scene; + /// /// The source path value used as part of this type's public representation. /// public string sourcePath = sourcePath; + /// /// The source asset id value used as part of this type's public representation. /// public Guid sourceAssetId = sourceAssetId; + /// /// The saved hash value used as part of this type's public representation. /// public byte[] savedHash = savedHash; + /// /// The is dirty value used as part of this type's public representation. /// public bool isDirty; + /// /// The next refresh timestamp value used as part of this type's public representation. /// public long nextRefreshTimestamp; } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.PlayMode.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.PlayMode.cs index 412083e54..095bbae99 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.PlayMode.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.PlayMode.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,7 +25,6 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - IDisposable IEditorScenePlayMode.BeginPlayMode(RuntimeSession runtimeSession) { ArgumentNullException.ThrowIfNull(runtimeSession); @@ -34,13 +32,18 @@ IDisposable IEditorScenePlayMode.BeginPlayMode(RuntimeSession runtimeSession) { throw new ArgumentException( "An editor Play Mode scene session requires a Play runtime session.", - nameof(runtimeSession)); + nameof(runtimeSession) + ); } SceneWorld runtimeWorld = runtimeSession.scenes; if (m_isPreparingPlayMode || m_playModeSession is not null) + { throw new InvalidOperationException("An editor Play Mode scene session is already active."); + } if (runtimeWorld.loadedScenes.Count != 0) + { throw new InvalidOperationException("A Play Mode scene snapshot requires an empty runtime world."); + } m_isPreparingPlayMode = true; try @@ -58,13 +61,16 @@ IDisposable IEditorScenePlayMode.BeginPlayMode(RuntimeSession runtimeSession) snapshots, activeSceneId, selectedSceneObjectId, - m_selection?.RegisterIdentityDomain(runtimeSession.identities)); + m_selection?.RegisterIdentityDomain(runtimeSession.identities) + ); try { MaterializeRuntimeSceneSet(session); m_playModeSession = session; if (selectedSceneObjectId is not null) + { RestoreSelection(selectedSceneObjectId); + } return session; } catch (Exception startupFailure) @@ -75,7 +81,11 @@ IDisposable IEditorScenePlayMode.BeginPlayMode(RuntimeSession runtimeSession) } catch (Exception cleanupFailure) { - throw new AggregateException("Play scene preparation and identity routing retirement failed.", startupFailure, cleanupFailure); + throw new AggregateException( + "Play scene preparation and identity routing retirement failed.", + startupFailure, + cleanupFailure + ); } throw; } @@ -89,20 +99,24 @@ IDisposable IEditorScenePlayMode.BeginPlayMode(RuntimeSession runtimeSession) private void ReleasePlayModeLease(PlayModeLease session) { if (!ReferenceEquals(m_playModeSession, session)) + { return; + } object? runtimeSelection = m_selection?.selectedTarget; Guid? runtimeSelectionId = runtimeSelection is EngineObject { isDestroyed: false } selected - ? selected.identity.persistentId - : null; + ? selected.identity.persistentId + : null; m_playModeSession = null; - Guid? editSelectionId = runtimeSelectionId is Guid currentId && - m_runtimeSession.scenes.Find(currentId) is not null - ? currentId - : session.editSelectionId; + Guid? editSelectionId = runtimeSelectionId is Guid currentId + && m_runtimeSession.scenes.Find(currentId) is not null + ? currentId + : session.editSelectionId; try { if (runtimeSelection is EngineObject || runtimeSelection is null && session.editSelectionId is not null) + { RestoreSelection(editSelectionId, selectActiveSceneWhenMissing: false); + } } catch { @@ -123,18 +137,19 @@ private void MaterializeRuntimeSceneSet(PlayModeLease session) for (int i = 0; i < snapshots.Count; i++) { SceneDocumentSnapshot snapshot = snapshots[i]; - GameScene runtimeScene = m_serialization.Deserialize( - snapshot.payload, - serializationContext); + GameScene runtimeScene = m_serialization.Deserialize(snapshot.payload, serializationContext); runtimeWorld.LoadSceneAdditive(runtimeScene, makeActive: false); runtimeWorld.SetSceneIndex(runtimeScene, snapshot.sceneIndex); } if (session.activeSceneId is Guid activeSceneId) { GameScene? activeScene = runtimeWorld.loadedScenes.FirstOrDefault( - scene => scene.identity.persistentId == activeSceneId); + scene => scene.identity.persistentId == activeSceneId + ); if (activeScene is not null) + { runtimeWorld.SetActiveScene(activeScene); + } } } catch (Exception exception) @@ -148,11 +163,13 @@ private void MaterializeRuntimeSceneSet(PlayModeLease session) throw new AggregateException( "The Play Mode scene set could not be constructed and its partial state could not be released.", exception, - cleanupFailure); + cleanupFailure + ); } throw new InvalidOperationException( "The Play Mode start snapshot could not be materialized in its isolated runtime world.", - exception); + exception + ); } } @@ -186,7 +203,9 @@ private sealed class PlayModeLease( public void Dispose() { if (m_disposed) + { return; + } workspace.ReleasePlayModeLease(this); identityDomain?.Dispose(); m_disposed = true; @@ -199,19 +218,18 @@ internal void Capture(EditorState state) sceneSnapshots .Select(static snapshot => snapshot.sourcePath) .Where(static path => !string.IsNullOrEmpty(path)) - .ToArray()); - string activePath = activeSceneId is Guid activeId && - m_snapshotBySceneId.TryGetValue(activeId, out SceneDocumentSnapshot? active) - ? active.sourcePath - : string.Empty; + .ToArray() + ); + string activePath = activeSceneId is Guid activeId + && m_snapshotBySceneId.TryGetValue(activeId, out SceneDocumentSnapshot? active) + ? active.sourcePath + : string.Empty; state.Set("activeScene", activePath); } internal bool TryGetSnapshot( Guid sceneId, out SceneDocumentSnapshot snapshot - ) - => m_snapshotBySceneId.TryGetValue(sceneId, out snapshot!); + ) => m_snapshotBySceneId.TryGetValue(sceneId, out snapshot!); } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Reload.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Reload.cs index 44924bff3..8d391795f 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Reload.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Reload.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,7 +25,6 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - IGenerationChange IEditorReloadParticipant.Capture(AssemblyReloadContext context) { ArgumentNullException.ThrowIfNull(context); @@ -35,7 +33,8 @@ IGenerationChange IEditorReloadParticipant.Capture(AssemblyReloadContext context return new WorkspaceReloadTransaction( this, Array.Empty(), - preserveDocumentBaselines: true); + preserveDocumentBaselines: true + ); } ApplyPendingSourceChanges(); var documents = new List(m_documents.Count); @@ -43,20 +42,22 @@ IGenerationChange IEditorReloadParticipant.Capture(AssemblyReloadContext context { GameScene scene = document.scene; if (scene.isDestroyed) + { continue; + } bool sourceAvailable = SynchronizeSource(scene, document); - bool wasDirty = !sourceAvailable || string.IsNullOrEmpty(document.sourcePath) || - !string.Equals( - scene.name, - GetAssetName(document.sourcePath), - StringComparison.Ordinal) || - HasSerializedChanges(scene, document); - documents.Add(new ReloadDocumentState( - sceneId, - document.savedHash.ToArray(), - document.isDirty, - document.nextRefreshTimestamp, - wasDirty)); + bool wasDirty = !sourceAvailable || string.IsNullOrEmpty(document.sourcePath) + || !string.Equals(scene.name, GetAssetName(document.sourcePath), StringComparison.Ordinal) + || HasSerializedChanges(scene, document); + documents.Add( + new ReloadDocumentState( + sceneId, + document.savedHash.ToArray(), + document.isDirty, + document.nextRefreshTimestamp, + wasDirty + ) + ); } return new WorkspaceReloadTransaction(this, documents, preserveDocumentBaselines: false); } @@ -70,9 +71,7 @@ bool preserveDocumentBaselines /// /// Prepares candidate state without changing the active generation. /// - public void PrepareForActivation() - { - } + public void PrepareForActivation() {} /// /// Applies the prepared state at the caller-controlled commit point. @@ -81,11 +80,15 @@ public void Apply() { workspace.SynchronizeReplacedScenes(); if (preserveDocumentBaselines) + { return; + } foreach (ReloadDocumentState state in documents) { if (!workspace.m_documents.TryGetValue(state.sceneId, out SceneDocument? document)) + { continue; + } if (state.wasDirty) { document.isDirty = true; @@ -95,17 +98,15 @@ public void Apply() document.savedHash = workspace.ComputeSceneHash(document.scene); document.isDirty = false; - document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + - (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); + document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + + (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); } } /// /// Completes the committed operation and releases temporary state. /// - public void Complete() - { - } + public void Complete() {} /// /// Restores the state that existed before candidate activation began. @@ -123,7 +124,9 @@ private void RestoreBaseline() foreach (ReloadDocumentState state in documents) { if (!workspace.m_documents.TryGetValue(state.sceneId, out SceneDocument? document)) + { continue; + } document.savedHash = state.savedHash.ToArray(); document.isDirty = state.isDirty; document.nextRefreshTimestamp = state.nextRefreshTimestamp; @@ -138,5 +141,4 @@ private readonly record struct ReloadDocumentState( long nextRefreshTimestamp, bool wasDirty ); - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Restore.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Restore.cs index ab7555c81..1299dad2c 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Restore.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Restore.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,7 +25,6 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - /// /// Captures an immutable snapshot of the current observable state. /// @@ -52,7 +50,9 @@ protected override void Capture(EditorState state) .ToArray(); state.Set("openScenes", scenePaths); if (m_runtimeSession.scenes.activeScene is GameScene active && TryGetSourcePath(active, out string activePath)) + { state.Set("activeScene", activePath); + } } /// @@ -89,10 +89,14 @@ private void TryRestorePendingScenes() } long typeCatalogVersion = m_types.current.version; if (m_waitingTypeCatalogVersion == typeCatalogVersion) + { return; + } long now = Stopwatch.GetTimestamp(); if (now < m_nextRestoreAttemptTimestamp) + { return; + } m_nextRestoreAttemptTimestamp = now + Stopwatch.Frequency / 4; var candidates = new List<(GameScene Scene, string Path, Guid AssetId, byte[] Hash)>(); @@ -106,7 +110,8 @@ private void TryRestorePendingScenes() { string absolutePath = Path.Combine( m_assets.assetRoot, - path.Replace('/', Path.DirectorySeparatorChar)); + path.Replace('/', Path.DirectorySeparatorChar) + ); if (File.Exists(absolutePath)) { waitingForSourceIndex = true; @@ -118,11 +123,7 @@ private void TryRestorePendingScenes() SceneAsset asset = m_assets.Load(AssetPath.Parse(path)); GameScene scene = asset.Instantiate(m_serialization, m_assets); scene.name = GetAssetName(path); - candidates.Add(( - scene, - path, - asset.identity.persistentId, - ComputeSceneHash(scene))); + candidates.Add((scene, path, asset.identity.persistentId, ComputeSceneHash(scene))); } } catch (SceneTypeResolutionException exception) @@ -130,14 +131,15 @@ private void TryRestorePendingScenes() DisposeRestoreCandidates(candidates); m_waitingTypeCatalogVersion = typeCatalogVersion; string message = - $"{exception.elementKind} stable type id '{exception.stableTypeId}' " + - "is not present in the active type catalog."; + $"{exception.elementKind} stable type id '{exception.stableTypeId}' " + + "is not present in the active type catalog."; if (m_diagnostics.PublishRestoreFailure("SCENE-TYPE", message)) { m_log.Write( LogLevel.Error, "Editor scene workspace cannot restore saved scenes because {0}", - [message]); + [message] + ); } return; } @@ -146,10 +148,9 @@ private void TryRestorePendingScenes() DisposeRestoreCandidates(candidates); m_waitingTypeCatalogVersion = typeCatalogVersion; if (m_diagnostics.PublishRestoreFailure("SCENE-RESTORE", exception.Message)) - m_log.Write( - LogLevel.Error, - "Editor scene workspace could not restore saved scenes: {0}", - [exception]); + { + m_log.Write(LogLevel.Error, "Editor scene workspace could not restore saved scenes: {0}", [exception]); + } return; } if (waitingForSourceIndex) @@ -164,14 +165,14 @@ private void TryRestorePendingScenes() { (GameScene scene, string path, Guid assetId, byte[] hash) = candidates[i]; m_runtimeSession.scenes.LoadSceneAdditive(scene, makeActive: false); - m_documents.Add( - scene.identity.persistentId, - new SceneDocument(scene, path, assetId, hash)); + m_documents.Add(scene.identity.persistentId, new SceneDocument(scene, path, assetId, hash)); } SceneDocument? activeDocument = m_documents.Values.FirstOrDefault(document => string.Equals(document.sourcePath, m_pendingActivePath, StringComparison.OrdinalIgnoreCase)); if (activeDocument is not null && activeDocument.scene.isLoaded) + { m_runtimeSession.scenes.SetActiveScene(activeDocument.scene); + } m_selection?.SetSelection(null); m_pendingScenePaths = null; m_waitingTypeCatalogVersion = -1; @@ -183,10 +184,11 @@ private void DisposeRestoreCandidates(IReadOnlyList<(GameScene Scene, string Pat for (int i = candidates.Count - 1; i >= 0; i--) { if (candidates[i].Scene.isDestroyed) + { continue; + } m_runtimeSession.scenes.LoadSceneAdditive(candidates[i].Scene, makeActive: false); _ = m_runtimeSession.scenes.UnloadScene(candidates[i].Scene); } } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs index c97c7bc70..5d1807e51 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -26,7 +25,6 @@ namespace Inno.Editor.Scene; internal sealed partial class EditorSceneWorkspace { - private bool SynchronizeSource( GameScene scene, SceneDocument document @@ -36,10 +34,10 @@ SceneDocument document m_diagnostics.ResolveSynchronization(scene.identity.persistentId); return true; } - if (!m_assets.TryGetInfo(document.sourceAssetId, out AssetInfo? asset) || - asset is null || - asset.status == AssetImportStatus.Missing) - { + if (!m_assets.TryGetInfo(document.sourceAssetId, out AssetInfo? asset) + || asset is null + || asset.status == AssetImportStatus.Missing + ) { document.isDirty = true; m_diagnostics.PublishSourceUnavailable(scene, document.sourcePath); return false; @@ -50,16 +48,20 @@ asset is null || string sourceName = GetAssetName(sourcePath); bool pathChanged = !string.Equals(document.sourcePath, sourcePath, StringComparison.Ordinal); if (!pathChanged) + { return true; + } bool wasDirty = HasSerializedChanges(scene, document); document.sourcePath = sourcePath; scene.name = sourceName; if (!wasDirty) + { document.savedHash = ComputeSceneHash(scene); + } document.isDirty = wasDirty; - document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + - (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); + document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + + (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); return true; } @@ -69,9 +71,9 @@ string newRelativePath ) { string oldPath = NormalizePath(oldRelativePath); string newPath = NormalizePath(newRelativePath); - if (m_assets.TryGetFileSystemEntry(AssetPath.Parse(newPath), out Inno.Assets.Pipeline.AssetFileEntry entry) && - entry.isDirectory) - { + if (m_assets.TryGetFileSystemEntry(AssetPath.Parse(newPath), out Inno.Assets.Pipeline.AssetFileEntry entry) + && entry.isDirectory + ) { ApplyDirectoryRename(oldPath, newPath); return; } @@ -82,7 +84,9 @@ string newRelativePath return; } if (string.Equals(extension, C_PREFAB_EXTENSION, StringComparison.OrdinalIgnoreCase)) + { ApplyPrefabRename(oldPath, newPath); + } } private void ApplySceneRename( @@ -91,9 +95,9 @@ string newPath ) { foreach (SceneDocument document in m_documents.Values) { - if (!string.Equals(document.sourcePath, oldPath, StringComparison.OrdinalIgnoreCase) || - document.scene.isDestroyed) - { + if (!string.Equals(document.sourcePath, oldPath, StringComparison.OrdinalIgnoreCase) + || document.scene.isDestroyed + ) { continue; } @@ -108,9 +112,9 @@ string newPath string oldPrefix = oldPath + "/"; foreach (SceneDocument document in m_documents.Values) { - if (document.scene.isDestroyed || - !document.sourcePath.StartsWith(oldPrefix, StringComparison.OrdinalIgnoreCase)) - { + if (document.scene.isDestroyed + || !document.sourcePath.StartsWith(oldPrefix, StringComparison.OrdinalIgnoreCase) + ) { continue; } @@ -127,12 +131,16 @@ string newPath document.sourcePath = newPath; document.scene.name = GetAssetName(newPath); if (m_assets.TryGetPersistentId(AssetPath.Parse(newPath), out Guid sourceAssetId)) + { document.sourceAssetId = sourceAssetId; + } if (!wasDirty) + { document.savedHash = ComputeSceneHash(document.scene); + } document.isDirty = wasDirty; - document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + - (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); + document.nextRefreshTimestamp = Stopwatch.GetTimestamp() + + (long)(Stopwatch.Frequency * C_DIRTY_REFRESH_SECONDS); } private string RenameSceneSourceIfNeeded( @@ -143,11 +151,14 @@ SceneDocument document string directory = NormalizePath(Path.GetDirectoryName(currentPath)); string targetPath = Combine(directory, SanitizeFileName(scene.name) + C_SCENE_EXTENSION); if (string.Equals(currentPath, targetPath, StringComparison.Ordinal)) + { return currentPath; + } if (m_assets.TryGetFileSystemEntry(AssetPath.Parse(targetPath), out _)) { throw new IOException( - $"Scene asset '{targetPath}' already exists. Choose a different scene name before saving."); + $"Scene asset '{targetPath}' already exists. Choose a different scene name before saving." + ); } m_assets.Move(AssetPath.Parse(currentPath), AssetPath.Parse(targetPath)); @@ -160,7 +171,9 @@ private void ApplyPrefabRename( string newPath ) { if (!m_assets.TryGetPersistentId(AssetPath.Parse(newPath), out Guid sourceAssetId)) + { return; + } string oldName = GetAssetName(oldPath); string newName = GetAssetName(newPath); IReadOnlyList scenes = m_runtimeSession.scenes.loadedScenes; @@ -171,10 +184,10 @@ string newPath { GameObject gameObject = objects[objectIndex]; PrefabInstanceInfo? prefab = gameObject.prefabInstance; - if (prefab?.isRoot == true && - prefab.sourceAssetId == sourceAssetId && - string.Equals(gameObject.name, oldName, StringComparison.Ordinal)) - { + if (prefab?.isRoot == true + && prefab.sourceAssetId == sourceAssetId + && string.Equals(gameObject.name, oldName, StringComparison.Ordinal) + ) { gameObject.name = newName; } } @@ -185,7 +198,9 @@ private void OnAssetDatabaseChanged(AssetChangeSet changeSet) { m_waitingTypeCatalogVersion = -1; for (int i = 0; i < changeSet.changes.Count; i++) + { m_sourceChanges.Enqueue(changeSet.changes[i]); + } } private void ApplyPendingSourceChanges() @@ -195,9 +210,9 @@ private void ApplyPendingSourceChanges() try { if (change.kind == AssetChangeKind.Moved) - ApplyRename( - change.previousAssetPath?.ToString() ?? string.Empty, - change.assetPath.ToString()); + { + ApplyRename(change.previousAssetPath?.ToString() ?? string.Empty, change.assetPath.ToString()); + } } catch (Exception exception) { @@ -212,12 +227,11 @@ private void SynchronizeReplacedScenes() for (int i = 0; i < loaded.Count; i++) { GameScene scene = loaded[i]; - if (m_documents.TryGetValue(scene.identity.persistentId, out SceneDocument? document) && - !ReferenceEquals(document.scene, scene)) - { + if (m_documents.TryGetValue(scene.identity.persistentId, out SceneDocument? document) + && !ReferenceEquals(document.scene, scene) + ) { document.scene = scene; } } } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.cs index 7cb5304de..cdea92c2c 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.cs @@ -1,22 +1,21 @@ -using Inno.Extensibility.Reload; using System; -using Inno.References; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -116,7 +115,7 @@ internal EditorSceneWorkspace( internal TSceneObject? Find(Guid persistentId) where TSceneObject : IdentityObject - => world.Find(persistentId); + => world.Find(persistentId); /// /// Gets all scenes currently available to editor features. @@ -146,19 +145,23 @@ internal EditorSceneWorkspace( public bool CanEdit(GameScene scene) { ArgumentNullException.ThrowIfNull(scene); - if (m_isPreparingPlayMode || scene.isDestroyed || !scene.isLoaded || - !world.loadedScenes.Any(candidate => ReferenceEquals(candidate, scene))) + if (m_isPreparingPlayMode || scene.isDestroyed || !scene.isLoaded + || !world.loadedScenes.Any(candidate => ReferenceEquals(candidate, scene)) + ) { return false; + } if (m_playModeSession is PlayModeLease playModeSession) { if (!playModeSession.TryGetSnapshot(scene.identity.persistentId, out SceneDocumentSnapshot snapshot)) + { return true; + } return string.IsNullOrEmpty(snapshot.sourcePath) - || AssetPath.Parse(snapshot.sourcePath).source == AssetSourceId.project; + || AssetPath.Parse(snapshot.sourcePath).source == AssetSourceId.project; } return !m_documents.TryGetValue(scene.identity.persistentId, out SceneDocument? document) - || string.IsNullOrEmpty(document.sourcePath) - || AssetPath.Parse(document.sourcePath).source == AssetSourceId.project; + || string.IsNullOrEmpty(document.sourcePath) + || AssetPath.Parse(document.sourcePath).source == AssetSourceId.project; } /// @@ -175,9 +178,9 @@ public ContentReadScope Capture() .Where(static scene => !scene.isDestroyed) .ToArray(); GameScene? activeScene = presentedWorld.activeScene; - if (activeScene is { isDestroyed: true } || - activeScene is not null && !scenes.Contains(activeScene)) - { + if (activeScene is { isDestroyed: true } + || activeScene is not null && !scenes.Contains(activeScene) + ) { activeScene = null; } return SceneContentSource.CreateScope(scenes, activeScene); @@ -215,9 +218,7 @@ internal GameScene CreateScene() GameScene scene = world.LoadNewSceneAdditive(name); if (canPersist) { - m_documents.Add( - scene.identity.persistentId, - new SceneDocument(scene, string.Empty, Guid.Empty, [])); + m_documents.Add(scene.identity.persistentId, new SceneDocument(scene, string.Empty, Guid.Empty, [])); } return scene; } @@ -235,7 +236,9 @@ internal void Refresh() foreach (SceneDocument document in m_documents.Values) { if (document.scene.isDestroyed) + { continue; + } Guid sceneId = document.scene.identity.persistentId; synchronizedScenes.Add(sceneId); try @@ -246,7 +249,9 @@ internal void Refresh() { document.isDirty = true; if (m_diagnostics.PublishSynchronizationFailure(document.scene, exception)) + { m_log.Write(LogLevel.Error, "Scene document synchronization failed: {0}", [exception]); + } } } m_diagnostics.RetainSynchronizationTargets(synchronizedScenes); @@ -266,7 +271,9 @@ internal bool CloseScene(GameScene scene) { ArgumentNullException.ThrowIfNull(scene); if (scene.isDestroyed) + { return false; + } using IDisposable scope = EnterPresentationScope(); Guid sceneId = scene.identity.persistentId; bool closed = world.UnloadScene(scene); @@ -300,13 +307,11 @@ internal void Clear() protected override void OnStart(EditorContext context) { if (m_isAttached) + { return; + } m_assets.Changed += OnAssetDatabaseChanged; - m_reloadIntegration = SceneReloadIntegration.Acquire( - m_runtimeSession, - m_serialization, - m_assets, - m_reloads); + m_reloadIntegration = SceneReloadIntegration.Acquire(m_runtimeSession, m_serialization, m_assets, m_reloads); m_reloadRegistration = m_reloads.Register(this); m_isAttached = true; m_sceneStateDiagnostics.Reconcile(force: true); @@ -338,7 +343,9 @@ protected override void OnUpdate(EditorContext context) protected override void OnStop(EditorContext context) { if (!m_isAttached) + { return; + } try { m_playModeSession?.Dispose(); @@ -369,14 +376,16 @@ protected override void OnDispose() m_diagnostics.Dispose(); } - void IEditorReloadParticipant.RefreshDiagnostics() - => m_sceneStateDiagnostics.Reconcile(force: true); + void IEditorReloadParticipant.RefreshDiagnostics() => m_sceneStateDiagnostics.Reconcile(force: true); internal void EnsureEditable(GameScene scene) { if (!CanEdit(scene)) + { throw new InvalidOperationException( - "The scene is not editable in the current presentation or belongs to a read-only source."); + "The scene is not editable in the current presentation or belongs to a read-only source." + ); + } } private void EnsurePresentedScene(GameScene scene) @@ -385,9 +394,12 @@ private void EnsurePresentedScene(GameScene scene) for (int i = 0; i < presentedScenes.Count; i++) { if (ReferenceEquals(presentedScenes[i], scene)) + { return; + } } throw new InvalidOperationException( - "The scene is not owned by the Editor's active Edit or Play presentation session."); + "The scene is not owned by the Editor's active Edit or Play presentation session." + ); } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceFactory.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceFactory.cs index 62e494514..1a40fb92c 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceFactory.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceFactory.cs @@ -1,10 +1,10 @@ using System; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Types; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Runtime; namespace Inno.Editor.Scene; @@ -48,6 +48,5 @@ public static EditorSceneWorkspaceHost Create( SerializationRegistry serialization, LogRouter logs, IEditorSelectionCoordinator? selection = null - ) - => new(runtimeSession, assets, types, serialization, logs, selection); + ) => new(runtimeSession, assets, types, serialization, logs, selection); } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceHost.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceHost.cs index b0ff9bec0..cbea478b1 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceHost.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspaceHost.cs @@ -1,12 +1,11 @@ using System; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Types; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Runtime; namespace Inno.Editor.Scene; @@ -34,7 +33,8 @@ internal EditorSceneWorkspaceHost( serialization, new EditorReloadCoordinator(), logs, - selection); + selection + ); } /// @@ -58,7 +58,9 @@ internal EditorSceneWorkspaceHost( public void Dispose() { if (m_disposed) + { return; + } m_workspace.DisposeUnattached(); m_disposed = true; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorScenePlayMode.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorScenePlayMode.cs index 7e75bc641..a8b5de3a6 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorScenePlayMode.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorScenePlayMode.cs @@ -1,5 +1,4 @@ using System; - using Inno.Runtime; namespace Inno.Editor.Scene; diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorSceneWorkspace.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorSceneWorkspace.cs index 3e4e8e3dc..6538785ae 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorSceneWorkspace.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/IEditorSceneWorkspace.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; - using Inno.Scene; namespace Inno.Editor.Scene; diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs index 1806ec590..ef931eab1 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs @@ -1,16 +1,17 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; namespace Inno.Editor.Scene; + sealed partial class SceneEdits { /// @@ -66,7 +67,9 @@ public GameComponent AddComponent( RollbackAndRethrow(exception, () => { if (!component.isDestroyed && !owner.RemoveComponent(component)) + { throw new InvalidOperationException("The unrecorded component could not be removed."); + } }); throw; } @@ -91,7 +94,9 @@ public bool RemoveComponent( ArgumentNullException.ThrowIfNull(component); using IDisposable presentationScope = m_workspace.EnterPresentationScope(); if (component.isDestroyed) + { return false; + } m_workspace.EnsureEditable(component.gameObject.scene); GameObject owner = component.gameObject; GameScene scene = owner.scene; @@ -104,7 +109,9 @@ public bool RemoveComponent( try { if (!owner.RemoveComponent(component)) + { return false; + } RecordElement( historyName ?? $"Remove {componentType.Name}", new SceneElementHistoryData( @@ -132,7 +139,15 @@ public bool RemoveComponent( RollbackAndRethrow(exception, () => { - GameComponent restored = SceneElementSerialization.RestoreComponent(owner, typeRef, componentId, index, state, m_workspace.serialization, m_workspace.assets); + GameComponent restored = SceneElementSerialization.RestoreComponent( + owner, + typeRef, + componentId, + index, + state, + m_workspace.serialization, + m_workspace.assets + ); RequireElementRestore(restored, state); RequireReferenceRestore(SceneReferenceIndex.RestoreIncoming(incoming, m_workspace)); }); @@ -172,7 +187,9 @@ public void ResetComponent( } if (before.AsSpan().SequenceEqual(after)) + { return; + } int index = owner.GetComponentIndex(component); RecordWithRollback( () => RecordElement( @@ -232,7 +249,9 @@ public void SetComponentIndex( } if (beforeIndex == afterIndex) + { return; + } RecordWithRollback( () => RecordElement( historyName, @@ -306,7 +325,9 @@ public GameSystem AddSystem( RollbackAndRethrow(exception, () => { if (!system.isDestroyed && !scene.RemoveSystem(system)) + { throw new InvalidOperationException("The unrecorded system could not be removed."); + } }); throw; } @@ -330,12 +351,16 @@ public bool RemoveSystem( ) { ArgumentNullException.ThrowIfNull(system); if (system.isDestroyed) + { return false; + } GameScene scene = ResolveOwnerScene(system); using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(scene); if (system.isDestroyed) + { return false; + } byte[] state = SceneElementSerialization.CaptureState(system, m_workspace.serialization, m_workspace.assets); SceneIncomingReferenceState[] incoming = SceneReferenceIndex.CaptureIncoming(system, scene, m_workspace); int index = scene.GetSystemIndex(system); @@ -345,7 +370,9 @@ public bool RemoveSystem( try { if (!scene.RemoveSystem(system)) + { return false; + } RecordElement( historyName ?? $"Remove {systemType.Name}", new SceneElementHistoryData( @@ -373,7 +400,15 @@ public bool RemoveSystem( RollbackAndRethrow(exception, () => { - GameSystem restored = SceneElementSerialization.RestoreSystem(scene, typeRef, systemId, index, state, m_workspace.serialization, m_workspace.assets); + GameSystem restored = SceneElementSerialization.RestoreSystem( + scene, + typeRef, + systemId, + index, + state, + m_workspace.serialization, + m_workspace.assets + ); RequireElementRestore(restored, state); RequireReferenceRestore(SceneReferenceIndex.RestoreIncoming(incoming, m_workspace)); }); @@ -413,7 +448,9 @@ public void ResetSystem( } if (before.AsSpan().SequenceEqual(after)) + { return; + } int index = scene.GetSystemIndex(system); RecordWithRollback( () => RecordElement( @@ -477,7 +514,9 @@ public void SetSystemIndex( } if (beforeIndex == afterIndex) + { return; + } RecordWithRollback( () => RecordElement( historyName, @@ -500,11 +539,14 @@ public void SetSystemIndex( ); } - private TypeRef GetElementType(EngineObject element) => element switch + private TypeRef GetElementType(EngineObject element) + => element switch { MissingGameComponent missing => missing.missingType, MissingGameSystem missing => missing.missingType, - _ => GetTypeRef(element.GetType())}; + _ => GetTypeRef(element.GetType()) + }; + private void RequireElementRestore( EngineObject element, ReadOnlySpan data diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs index a0acc8336..a9347be17 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; - -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -48,15 +47,17 @@ public void SetSceneIndex( throw; } if (beforeIndex == afterIndex) + { return; + } var data = new SceneOrderHistoryData(scene.identity.persistentId, beforeIndex, afterIndex); RecordWithRollback( () => m_interactions.history.RecordApplied( historyName, - new EditorHistoryChange( - SceneHistoryKinds.Order, - EditorHistoryPayload.FromBytes(data.Encode()))), - () => m_workspace.world.SetSceneIndex(scene, beforeIndex)); + new EditorHistoryChange(SceneHistoryKinds.Order, EditorHistoryPayload.FromBytes(data.Encode())) + ), + () => m_workspace.world.SetSceneIndex(scene, beforeIndex) + ); } /// @@ -93,7 +94,9 @@ public bool ChangeHierarchy( .DistinctBy(static candidate => candidate.identity.persistentId) .ToArray(); foreach (GameObject affectedObject in affected) + { m_workspace.EnsureEditable(affectedObject.scene); + } SceneObjectPlacement[] before = CapturePlacements(affected); SceneObjectPlacement[] after; try @@ -107,14 +110,14 @@ public bool ChangeHierarchy( throw; } if (before.SequenceEqual(after)) + { return false; - var data = new SceneHierarchyHistoryData( - before, - after, - gameObject.identity.persistentId); + } + var data = new SceneHierarchyHistoryData(before, after, gameObject.identity.persistentId); RecordWithRollback( () => Record(historyName, SceneHistoryKinds.Hierarchy, data.Encode()), - () => RestorePlacements(before)); + () => RestorePlacements(before) + ); return true; } @@ -128,7 +131,8 @@ private static SceneObjectPlacement[] CapturePlacements(IReadOnlyList placements) { SceneObjectPlacement placement = placements[i]; GameObject gameObject = m_workspace.Find(placement.objectId) - ?? throw new InvalidOperationException($"GameObject '{placement.objectId}' is unavailable."); + ?? throw new InvalidOperationException($"GameObject '{placement.objectId}' is unavailable."); GameScene destination = m_workspace.Find(placement.sceneId) - ?? throw new InvalidOperationException($"Scene '{placement.sceneId}' is unavailable."); + ?? throw new InvalidOperationException($"Scene '{placement.sceneId}' is unavailable."); if (!ReferenceEquals(gameObject.scene, destination)) + { m_workspace.world.MoveGameObjectToScene(gameObject, destination); + } } for (int i = 0; i < placements.Count; i++) { SceneObjectPlacement placement = placements[i]; GameObject gameObject = m_workspace.Find(placement.objectId)!; Transform? parent = placement.parentId is Guid parentId - ? m_workspace.Find(parentId)?.transform - : null; + ? m_workspace.Find(parentId)?.transform + : null; gameObject.transform.SetParent(parent); } foreach (SceneObjectPlacement placement in placements.OrderBy(static value => value.siblingIndex)) @@ -160,5 +166,4 @@ private void RestorePlacements(IReadOnlyList placements) .transform.SetSiblingIndex(placement.siblingIndex); } } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs index 97c064e65..bbae50f7f 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; - -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -32,12 +31,12 @@ private void RecordDocument( activeBefore, activeAfter, selectedBefore, - selectedAfter); + selectedAfter + ); m_interactions.history.RecordApplied( name, - new EditorHistoryChange( - SceneHistoryKinds.Document, - EditorHistoryPayload.FromBytes(data.Encode()))); + new EditorHistoryChange(SceneHistoryKinds.Document, EditorHistoryPayload.FromBytes(data.Encode())) + ); } private void RecordSubtree( @@ -60,7 +59,8 @@ private void RecordSubtree( subtree, incoming, selectedBefore, - selectedAfter); + selectedAfter + ); Record(name, SceneHistoryKinds.Subtree, data.Encode()); } @@ -69,13 +69,10 @@ private void Record( string kind, byte[] data, string? mergeKey = null - ) - => m_interactions.history.RecordApplied( - name, - new EditorHistoryChange( - kind, - EditorHistoryPayload.FromBytes(data), - mergeKey)); + ) => m_interactions.history.RecordApplied( + name, + new EditorHistoryChange(kind, EditorHistoryPayload.FromBytes(data), mergeKey) + ); private void RecordElement( string name, @@ -84,25 +81,24 @@ SceneElementHistoryData data private Guid? GetActiveSceneId() => m_workspace.activeScene is { isDestroyed: false } scene - ? scene.identity.persistentId - : null; + ? scene.identity.persistentId + : null; private GameScene ResolveOwnerScene(EngineObject target) => target switch - { - GameScene scene => scene, - GameObject gameObject => gameObject.scene, - GameComponent component => component.gameObject.scene, - GameSystem system => m_workspace.scenes.FirstOrDefault(scene => - scene.GetSystems().Contains(system)) - ?? throw new InvalidOperationException("The system has no loaded scene."), - _ => throw new InvalidOperationException("The object has no loaded scene.") - }; + { + GameScene scene => scene, + GameObject gameObject => gameObject.scene, + GameComponent component => component.gameObject.scene, + GameSystem system => m_workspace.scenes.FirstOrDefault(scene => scene.GetSystems().Contains(system)) + ?? throw new InvalidOperationException("The system has no loaded scene."), + _ => throw new InvalidOperationException("The object has no loaded scene.") + }; private Guid? GetSelectionId() => m_interactions.selection.selectedTarget is EngineObject { isDestroyed: false } target - ? target.identity.persistentId - : null; + ? target.identity.persistentId + : null; private static void RecordWithRollback( Action record, @@ -131,15 +127,16 @@ Action rollback throw new AggregateException( "An editor mutation could not be recorded and its compensation also failed.", failure, - rollbackException); + rollbackException + ); } ExceptionDispatchInfo.Capture(failure).Throw(); } private TypeRef GetTypeRef(Type type) => m_workspace.types.TryGetTypeRef(type, out TypeRef typeRef) - ? typeRef - : throw new InvalidOperationException( - $"Scene element type '{type.FullName}' does not have an active StableTypeId."); - + ? typeRef + : throw new InvalidOperationException( + $"Scene element type '{type.FullName}' does not have an active StableTypeId." + ); } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs index fc09d6d77..e14bb7fbb 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; - -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -40,18 +39,23 @@ public GameObject CreateGameObject( using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(scene); if (parent is not null && !ReferenceEquals(parent.gameObject.scene, scene)) + { throw new ArgumentException("The parent belongs to another scene.", nameof(parent)); + } Guid? selectedBefore = GetSelectionId(); GameObject gameObject = scene.CreateObject(); RecordWithRollback( () => { if (parent is not null) + { gameObject.transform.SetParent(parent); + } byte[] subtree = SceneSubtreeSerialization.Capture( gameObject, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); RecordSubtree( historyName, gameObject, @@ -60,13 +64,17 @@ public GameObject CreateGameObject( subtree, [], selectedBefore, - gameObject.identity.persistentId); + gameObject.identity.persistentId + ); }, () => { if (gameObject.isRuntimeValid && !scene.DestroyObject(gameObject)) + { throw new InvalidOperationException("The unrecorded GameObject could not be removed."); - }); + } + } + ); return gameObject; } @@ -100,23 +108,24 @@ public GameObject InstantiatePrefab( using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(scene); if (!scene.isLoaded) + { throw new InvalidOperationException("A prefab can only be instantiated into a loaded scene."); + } if (parent is not null && !ReferenceEquals(parent.gameObject.scene, scene)) + { throw new ArgumentException("The parent belongs to another scene.", nameof(parent)); + } Guid? selectedBefore = GetSelectionId(); - GameObject instance = prefab.Instantiate( - scene, - m_workspace.serialization, - m_workspace.assets, - parent); + GameObject instance = prefab.Instantiate(scene, m_workspace.serialization, m_workspace.assets, parent); RecordWithRollback( () => { byte[] subtree = SceneSubtreeSerialization.Capture( instance, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); RecordSubtree( historyName, instance, @@ -125,13 +134,17 @@ public GameObject InstantiatePrefab( subtree, [], selectedBefore, - instance.identity.persistentId); + instance.identity.persistentId + ); }, () => { if (instance.isRuntimeValid && !scene.DestroyObject(instance)) + { throw new InvalidOperationException("The unrecorded prefab instance could not be removed."); - }); + } + } + ); return instance; } @@ -156,15 +169,12 @@ public bool DeleteGameObject( using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(gameObject.scene); if (!gameObject.isRuntimeValid) + { return false; + } GameScene scene = gameObject.scene; - byte[] subtree = SceneSubtreeSerialization.Capture( - gameObject, - m_workspace.serialization, - m_workspace.assets); - SceneIncomingReferenceState[] incoming = SceneReferenceIndex.CaptureIncoming( - gameObject, - m_workspace); + byte[] subtree = SceneSubtreeSerialization.Capture(gameObject, m_workspace.serialization, m_workspace.assets); + SceneIncomingReferenceState[] incoming = SceneReferenceIndex.CaptureIncoming(gameObject, m_workspace); Guid? parentId = gameObject.transform.parent?.gameObject.identity.persistentId; int siblingIndex = gameObject.transform.siblingIndex; Guid rootId = gameObject.identity.persistentId; @@ -172,7 +182,9 @@ public bool DeleteGameObject( try { if (!scene.DestroyObject(gameObject)) + { return false; + } var data = new SceneSubtreeHistoryData( scene.identity.persistentId, rootId, @@ -183,7 +195,8 @@ public bool DeleteGameObject( subtree, incoming, selectedBefore, - selectedAfter: null); + selectedAfter: null + ); Record(historyName, SceneHistoryKinds.Subtree, data.Encode()); } catch (Exception exception) @@ -195,19 +208,19 @@ public bool DeleteGameObject( RollbackAndRethrow(exception, () => { Transform? parent = parentId is Guid id - ? m_workspace.Find(id)?.transform - : null; + ? m_workspace.Find(id)?.transform + : null; _ = SceneSubtreeSerialization.Restore( scene, subtree, m_workspace.serialization, m_workspace.assets, parent, - siblingIndex); + siblingIndex + ); RequireReferenceRestore(SceneReferenceIndex.RestoreIncoming(incoming, m_workspace)); }); } return true; } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs index 10a06f34f..34ff62aac 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; - -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -43,7 +42,8 @@ public void RenameScene( name, value => scene.name = value, historyName, - $"scene-name:{scene.identity.persistentId:N}"); + $"scene-name:{scene.identity.persistentId:N}" + ); } /// @@ -74,7 +74,8 @@ public void RenameGameObject( name, value => gameObject.name = value, historyName, - $"game-object-name:{gameObject.identity.persistentId:N}"); + $"game-object-name:{gameObject.identity.persistentId:N}" + ); } /// @@ -106,7 +107,8 @@ public void SetGameObjectActive( after, value => gameObject.SetActive(string.Equals(value, "1", StringComparison.Ordinal)), historyName ?? (active ? "Activate GameObject" : "Deactivate GameObject"), - mergeKey: null); + mergeKey: null + ); } /// @@ -145,7 +147,8 @@ public void SetGameObjectTag( requestedTag, value => gameObject.tag = value, historyName, - $"game-object-tag:{gameObject.identity.persistentId:N}"); + $"game-object-tag:{gameObject.identity.persistentId:N}" + ); } /// @@ -181,9 +184,11 @@ public void SetGameObjectLayer( gameObject.layer.index.ToString(System.Globalization.CultureInfo.InvariantCulture), layer.index.ToString(System.Globalization.CultureInfo.InvariantCulture), value => gameObject.layer = new GameLayer( - int.Parse(value, System.Globalization.CultureInfo.InvariantCulture)), + int.Parse(value, System.Globalization.CultureInfo.InvariantCulture) + ), historyName, - $"game-object-layer:{gameObject.identity.persistentId:N}"); + $"game-object-layer:{gameObject.identity.persistentId:N}" + ); } /// @@ -221,16 +226,15 @@ public bool ChangeProperty( using IDisposable presentationScope = m_workspace.EnterPresentationScope(); m_workspace.EnsureEditable(ResolveOwnerScene(target)); IReadOnlyList before = OrderPropertySnapshots( - ScenePropertySerialization.CapturePropertySnapshots( - target, - m_workspace.serialization, - m_workspace.assets), - propertyName); + ScenePropertySerialization.CapturePropertySnapshots(target, m_workspace.serialization, m_workspace.assets), + propertyName + ); if (!before.Any(snapshot => string.Equals(snapshot.name, propertyName, StringComparison.Ordinal))) { throw new ArgumentException( $"Serializable property '{propertyName}' was not found on '{target.GetType().FullName}'.", - nameof(propertyName)); + nameof(propertyName) + ); } IReadOnlyList after; try @@ -240,8 +244,10 @@ public bool ChangeProperty( ScenePropertySerialization.CapturePropertySnapshots( target, m_workspace.serialization, - m_workspace.assets), - propertyName); + m_workspace.assets + ), + propertyName + ); } catch (Exception exception) { @@ -251,44 +257,57 @@ public bool ChangeProperty( IReadOnlyDictionary afterByName = after.ToDictionary( static snapshot => snapshot.name, - StringComparer.Ordinal); + StringComparer.Ordinal + ); var deltas = new List(); for (int index = 0; index < before.Count; index++) { SerializationPropertySnapshot previous = before[index]; if (!afterByName.TryGetValue(previous.name, out SerializationPropertySnapshot? current)) + { continue; + } if (previous.data.Span.SequenceEqual(current.data.Span)) + { continue; - deltas.Add(new ScenePropertyValueDelta( - previous.name, - m_workspace.serialization.EncodePropertySnapshots([previous]), - m_workspace.serialization.EncodePropertySnapshots([current]))); + } + deltas.Add( + new ScenePropertyValueDelta( + previous.name, + m_workspace.serialization.EncodePropertySnapshots([previous]), + m_workspace.serialization.EncodePropertySnapshots([current]) + ) + ); } if (deltas.Count == 0) + { return false; + } ScenePropertyHistoryData data = ScenePropertyHistoryData.Create( target.identity.persistentId, propertyName, - deltas); + deltas + ); RecordWithRollback( () => m_interactions.history.RecordApplied( historyName, new EditorHistoryChange( SceneHistoryKinds.Property, EditorHistoryPayload.FromBytes(data.Encode()), - mergeKey)), - () => RestorePropertyDeltas(target, deltas, useAfter: false)); + mergeKey + ) + ), + () => RestorePropertyDeltas(target, deltas, useAfter: false) + ); return true; } private static IReadOnlyList OrderPropertySnapshots( IReadOnlyList snapshots, string primaryPropertyName - ) - => snapshots - .OrderBy(snapshot => string.Equals(snapshot.name, primaryPropertyName, StringComparison.Ordinal) ? 0 : 1) - .ToArray(); + ) => snapshots + .OrderBy(snapshot => string.Equals(snapshot.name, primaryPropertyName, StringComparison.Ordinal) ? 0 : 1) + .ToArray(); private void RestoreSnapshots( EngineObject target, @@ -296,9 +315,7 @@ IReadOnlyList snapshots ) { for (int index = 0; index < snapshots.Count; index++) { - RequirePropertyRestore( - target, - m_workspace.serialization.EncodePropertySnapshots([snapshots[index]])); + RequirePropertyRestore(target, m_workspace.serialization.EncodePropertySnapshots([snapshots[index]])); } } @@ -308,7 +325,9 @@ private void RestorePropertyDeltas( bool useAfter ) { for (int index = 0; index < deltas.Count; index++) + { RequirePropertyRestore(target, useAfter ? deltas[index].after : deltas[index].before); + } } private void ChangeScalar( @@ -321,7 +340,9 @@ private void ChangeScalar( string? mergeKey ) { if (string.Equals(before, after, StringComparison.Ordinal)) + { return; + } RecordWithRollback( () => { @@ -330,10 +351,12 @@ private void ChangeScalar( target.identity.persistentId, scalarKind, before, - after); + after + ); Record(historyName, SceneHistoryKinds.Scalar, data.Encode(), mergeKey); }, - () => setter(before)); + () => setter(before) + ); } private void RequirePropertyRestore( @@ -344,15 +367,19 @@ ReadOnlySpan data target, data, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); if (!result.success || result.ignoredCount != 0 || result.restoredCount == 0) + { throw new InvalidOperationException("Scene property compensation was incomplete."); + } } private static void RequireReferenceRestore(SceneReferenceRestoreResult result) { if (!result.succeeded) + { throw new InvalidOperationException(result.message); + } } - } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs index 0443166d4..231a07ae4 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs @@ -8,6 +8,7 @@ using Inno.Scene; namespace Inno.Editor.Scene; + sealed partial class SceneEdits { /// @@ -28,14 +29,18 @@ public void DeleteGameObjects(IReadOnlyList targets) ArgumentNullException.ThrowIfNull(target); m_workspace.EnsureEditable(target.scene); if (!target.isRuntimeValid) + { throw new InvalidOperationException("A selected GameObject is no longer available."); + } } var selected = unique.Select(value => value.identity.persistentId).ToHashSet(); GameObject[] roots = unique.Where(value => !HasSelectedAncestor(value, selected)).ToArray(); using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction("Delete GameObjects"); foreach (GameObject target in roots) + { _ = DeleteGameObject(target); + } transaction.Commit(); } @@ -82,18 +87,27 @@ public bool ChangeProperties( ArgumentNullException.ThrowIfNull(mutation); ArgumentException.ThrowIfNullOrWhiteSpace(historyName); if (targets.Count == 0) + { throw new ArgumentException("A property edit requires at least one target.", nameof(targets)); + } foreach (EngineObject target in targets) { ArgumentNullException.ThrowIfNull(target); m_workspace.EnsureEditable(ResolveOwnerScene(target)); - if (!ScenePropertySerialization.CapturePropertySnapshots(target, m_workspace.serialization, m_workspace.assets).Any(value => value.name == propertyName)) + if (!ScenePropertySerialization.CapturePropertySnapshots(target, m_workspace.serialization, m_workspace.assets) + .Any(value => value.name == propertyName) + ) { throw new ArgumentException($"Selected target has no serialized property '{propertyName}'.", nameof(targets)); + } } if (componentName is not null) + { foreach (EngineObject target in targets) + { ValidateComponent(GetSelectionProperty(target, propertyName).propertyType, componentName); + } + } using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction(historyName); bool changed = ChangeProperty(targets[0], propertyName, mutation, historyName, mergeKey); SerializationPropertySnapshot snapshot = ScenePropertySerialization.CapturePropertySnapshots( @@ -108,12 +122,15 @@ public bool ChangeProperties( changed |= ChangeProperty(target, propertyName, () => { if (componentName is null) + { RequirePropertyRestore(target, value); + } else { SerializedProperty property = GetSelectionProperty(target, propertyName); object primary = GetSelectionProperty(targets[0], propertyName).GetValue()!; - object current = property.GetValue() ?? Activator.CreateInstance(Nullable.GetUnderlyingType(property.propertyType) ?? property.propertyType)!; + object current = property.GetValue() + ?? Activator.CreateInstance(Nullable.GetUnderlyingType(property.propertyType) ?? property.propertyType)!; property.SetValue(CopyComponent(primary, current, componentName)); } }, historyName, mergeKey); @@ -153,7 +170,9 @@ string propertyName m_workspace.assets ).Single(value => value.name == propertyName); if (first is not null && !first.data.Span.SequenceEqual(current.data.Span)) + { return false; + } first = current; } @@ -191,38 +210,54 @@ public void MoveGameObjects( ArgumentNullException.ThrowIfNull(destination); m_workspace.EnsureEditable(destination); if (parent is not null && !ReferenceEquals(parent.scene, destination)) + { throw new ArgumentException("The parent must belong to the destination scene.", nameof(parent)); + } GameObject[] unique = targets.Distinct().ToArray(); foreach (GameObject target in unique) { ArgumentNullException.ThrowIfNull(target); m_workspace.EnsureEditable(target.scene); if (!target.isRuntimeValid) + { throw new InvalidOperationException("A selected GameObject is no longer available."); + } } var selected = unique.Select(value => value.identity.persistentId).ToHashSet(); GameObject[] roots = unique.Where(value => !HasSelectedAncestor(value, selected)).ToArray(); if (roots.Length == 0) + { return; + } for (var ancestor = parent?.transform; ancestor is not null; ancestor = ancestor.parent) + { if (selected.Contains(ancestor.gameObject.identity.persistentId)) + { throw new InvalidOperationException("A selection cannot be moved beneath itself."); + } + } _ = ChangeHierarchy(roots[0], hierarchy => { foreach (GameObject target in roots) { if (!ReferenceEquals(target.scene, destination)) + { hierarchy.MoveToScene(target, destination); + } target.transform.SetParent(parent?.transform); target.transform.SetSiblingIndex(int.MaxValue); } - int available = parent is null ? destination.GetObjects().Count(value => value.transform.parent is null) - roots.Length : parent.transform.children.Count - roots.Length; + int available = parent is null + ? destination.GetObjects().Count(value => value.transform.parent is null) - roots.Length + : parent.transform.children.Count - roots.Length; int start = Math.Clamp(insertionIndex, 0, available); // Place from the end so intermediate sibling shifts cannot reverse the selection. for (int index = roots.Length - 1; index >= 0; index--) + { roots[index].transform.SetSiblingIndex(start); + } }, "Move GameObjects", roots); } @@ -237,10 +272,14 @@ string componentName ) { type = Nullable.GetUnderlyingType(type) ?? type; if (type == typeof(Quaternion) && componentName is "euler.x" or "euler.y" or "euler.z") + { return; + } FieldInfo? field = type.GetField(componentName, BindingFlags.Instance | BindingFlags.Public); if (!type.IsValueType || field is null || field.IsInitOnly || !field.FieldType.IsPrimitive) + { throw new ArgumentException("A batch component must be a writable public scalar value field.", nameof(componentName)); + } } private static object CopyComponent( @@ -271,8 +310,12 @@ private static bool HasSelectedAncestor( ISet selected ) { for (var parent = target.transform.parent; parent is not null; parent = parent.parent) + { if (selected.Contains(parent.gameObject.identity.persistentId)) + { return true; + } + } return false; } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.cs index 058fb3eb8..856877e7e 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; -using System.Runtime.ExceptionServices; using System.Linq; - -using Inno.Extensibility.Types; +using System.Runtime.ExceptionServices; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -64,7 +63,9 @@ public bool CanEdit(EngineObject target) { ArgumentNullException.ThrowIfNull(target); if (target.isDestroyed) + { return false; + } try { return m_workspace.CanEdit(ResolveOwnerScene(target)); @@ -104,14 +105,18 @@ public GameScene CreateScene(string historyName = "Create Scene") activeBefore, GetActiveSceneId(), selectedBefore, - scene.identity.persistentId); + scene.identity.persistentId + ); }, () => { if (!m_workspace.CloseScene(scene)) + { throw new InvalidOperationException("The unrecorded scene could not be removed."); + } m_workspace.RestoreActiveScene(activeBefore); - }); + } + ); return scene; } @@ -138,7 +143,9 @@ public bool CloseScene( Guid? activeBefore = GetActiveSceneId(); Guid? selectedBefore = GetSelectionId(); if (!m_workspace.CloseScene(scene)) + { return false; + } RecordWithRollback( () => RecordDocument( historyName, @@ -148,12 +155,14 @@ public bool CloseScene( activeBefore, GetActiveSceneId(), selectedBefore, - GetSelectionId()), + GetSelectionId() + ), () => { _ = m_workspace.RestoreDocumentSnapshot(snapshot); m_workspace.RestoreActiveScene(activeBefore); - }); + } + ); return true; } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneHierarchyEdit.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneHierarchyEdit.cs index 2a6453dbc..7d18770d8 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneHierarchyEdit.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneHierarchyEdit.cs @@ -1,5 +1,4 @@ using System; - using Inno.Scene; namespace Inno.Editor.Scene; diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs index 7cb8754dd..7e3d2cca6 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs @@ -40,7 +40,9 @@ internal static SceneDocumentHistoryData Decode(ReadOnlySpan bytes) Guid? selectedAfter = ReadGuid(reader); EditorSceneWorkspace.SceneDocumentSnapshot snapshot = ReadSnapshot(reader); if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene document history payload contains trailing data."); + } return new SceneDocumentHistoryData( existsBefore, existsAfter, @@ -48,7 +50,8 @@ internal static SceneDocumentHistoryData Decode(ReadOnlySpan bytes) activeBefore, activeAfter, selectedBefore, - selectedAfter); + selectedAfter + ); } private static void WriteSnapshot( @@ -82,7 +85,8 @@ private static EditorSceneWorkspace.SceneDocumentSnapshot ReadSnapshot(BinaryRea sourceAssetId, savedHash, isDirty, - sceneIndex); + sceneIndex + ); } private static byte[] ReadBytes( @@ -91,10 +95,14 @@ string name ) { int length = reader.ReadInt32(); if (length < 0 || length > reader.BaseStream.Length - reader.BaseStream.Position) + { throw new InvalidDataException($"Scene document history {name} length is invalid."); + } byte[] bytes = reader.ReadBytes(length); if (bytes.Length != length) + { throw new EndOfStreamException($"Scene document history {name} is truncated."); + } return bytes; } @@ -104,7 +112,9 @@ private static void WriteGuid( ) { writer.Write(value.HasValue); if (value.HasValue) + { writer.Write(value.Value.ToByteArray()); + } } private static Guid? ReadGuid(BinaryReader reader) => reader.ReadBoolean() ? new Guid(reader.ReadBytes(16)) : null; diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryHandler.cs index 379e9063c..12ca908db 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryHandler.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Scene; @@ -45,27 +44,28 @@ EditorHistoryDirection direction { SceneDocumentHistoryData data = SceneDocumentHistoryData.Decode(change.payload.ReadBytes()); bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; + ? data.existsBefore + : data.existsAfter; GameScene? current = m_workspace.Find(data.snapshot.sceneId); if (shouldExist) { return current is null || current is { isLoaded: true, isDestroyed: false } - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable( - $"Scene '{data.snapshot.sceneId}' exists but is not a live loaded scene."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable( + $"Scene '{data.snapshot.sceneId}' exists but is not a live loaded scene." + ); } if (current is not { isLoaded: true, isDestroyed: false }) { - return EditorHistoryAvailability.Unavailable( - $"Scene '{data.snapshot.sceneId}' is no longer loaded."); + return EditorHistoryAvailability.Unavailable($"Scene '{data.snapshot.sceneId}' is no longer loaded."); } return EditorHistoryAvailability.Available(); } catch (Exception exception) { return EditorHistoryAvailability.Unavailable( - $"Scene document history payload is invalid: {exception.Message}"); + $"Scene document history payload is invalid: {exception.Message}" + ); } } @@ -100,19 +100,19 @@ EditorHistoryDirection direction } bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; + ? data.existsBefore + : data.existsAfter; Guid? active = direction == EditorHistoryDirection.Undo - ? data.activeBefore - : data.activeAfter; + ? data.activeBefore + : data.activeAfter; Guid? selected = direction == EditorHistoryDirection.Undo - ? data.selectedBefore - : data.selectedAfter; + ? data.selectedBefore + : data.selectedAfter; GameScene? current = m_workspace.Find(data.snapshot.sceneId); bool existed = current is { isLoaded: true, isDestroyed: false }; EditorSceneWorkspace.SceneDocumentSnapshot? original = existed - ? m_workspace.CaptureDocumentSnapshot(current!) - : null; + ? m_workspace.CaptureDocumentSnapshot(current!) + : null; Guid? originalActive = m_workspace.activeScene?.identity.persistentId; DocumentMutation mutation = DocumentMutation.None; @@ -128,13 +128,16 @@ EditorHistoryDirection direction else if (current is not { isLoaded: true, isDestroyed: false }) { return EditorHistoryResult.Failure( - $"Scene '{data.snapshot.sceneId}' cannot be restored over an invalid live object."); + $"Scene '{data.snapshot.sceneId}' cannot be restored over an invalid live object." + ); } } else if (current is not null) { if (!m_workspace.CloseDocumentForHistory(current)) + { return EditorHistoryResult.Failure($"Scene '{data.snapshot.sceneId}' could not be closed."); + } mutation = DocumentMutation.Closed; } @@ -150,8 +153,9 @@ EditorHistoryDirection direction catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene document transition failed: {exception.Message} " + - $"Rollback failed: {rollbackException.Message}"); + $"Scene document transition failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } @@ -176,16 +180,17 @@ private static void RollbackDocument( if (mutation == DocumentMutation.Restored) { GameScene? restored = workspace.Find(sceneId); - if (restored is { isLoaded: true, isDestroyed: false } && - !workspace.CloseDocumentForHistory(restored)) - { + if (restored is { isLoaded: true, isDestroyed: false } + && !workspace.CloseDocumentForHistory(restored) + ) { throw new InvalidOperationException($"Restored scene '{sceneId}' could not be removed."); } } else if (mutation == DocumentMutation.Closed) { _ = workspace.RestoreDocumentSnapshot( - original ?? throw new InvalidOperationException("The original scene document snapshot is missing.")); + original ?? throw new InvalidOperationException("The original scene document snapshot is missing.") + ); } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs index f04b9e38a..5199c018b 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs @@ -1,7 +1,6 @@ using System; using System.IO; using System.Text; - using Inno.Extensibility.Types; namespace Inno.Editor.Scene; @@ -53,7 +52,9 @@ internal static SceneElementHistoryData Decode(ReadOnlySpan bytes) using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); var elementKind = (SceneElementKind)reader.ReadByte(); if (!Enum.IsDefined(elementKind)) + { throw new InvalidDataException($"Unknown scene element history kind '{elementKind}'."); + } Guid sceneId = new(reader.ReadBytes(16)); Guid ownerId = new(reader.ReadBytes(16)); Guid elementId = new(reader.ReadBytes(16)); @@ -66,17 +67,22 @@ internal static SceneElementHistoryData Decode(ReadOnlySpan bytes) byte[] afterState = ReadBytes(reader, "after state"); int referenceCount = reader.ReadInt32(); if (referenceCount < 0) + { throw new InvalidDataException("Scene element incoming reference count cannot be negative."); + } var references = new SceneIncomingReferenceState[referenceCount]; for (int i = 0; i < references.Length; i++) { references[i] = new SceneIncomingReferenceState( new Guid(reader.ReadBytes(16)), reader.ReadString(), - ReadBytes(reader, "incoming reference")); + ReadBytes(reader, "incoming reference") + ); } if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene element history payload contains trailing data."); + } return new SceneElementHistoryData( elementKind, sceneId, @@ -89,7 +95,8 @@ internal static SceneElementHistoryData Decode(ReadOnlySpan bytes) existsAfter, beforeState, afterState, - references); + references + ); } private static void WriteBytes( @@ -106,10 +113,14 @@ string name ) { int length = reader.ReadInt32(); if (length < 0 || length > reader.BaseStream.Length - reader.BaseStream.Position) + { throw new InvalidDataException($"Scene element history {name} length is invalid."); + } byte[] bytes = reader.ReadBytes(length); if (bytes.Length != length) + { throw new EndOfStreamException($"Scene element history {name} is truncated."); + } return bytes; } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs index a87871186..ee6797686 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Editor.Scene; @@ -43,17 +42,20 @@ EditorHistoryDirection direction SceneElementHistoryData data = SceneElementHistoryData.Decode(change.payload.ReadBytes()); GameScene? scene = m_workspace.Find(data.sceneId); if (scene is not { isLoaded: true, isDestroyed: false }) + { return EditorHistoryAvailability.Unavailable($"Scene '{data.sceneId}' is no longer loaded."); + } bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; + ? data.existsBefore + : data.existsAfter; EngineObject? current = m_workspace.Find(data.elementId); if (!shouldExist) { return current is { isDestroyed: false } - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable( - $"Scene element '{data.elementId}' is no longer available."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable( + $"Scene element '{data.elementId}' is no longer available." + ); } if (current is { isDestroyed: false }) { @@ -71,15 +73,17 @@ EditorHistoryDirection direction _ => false }; return typeMatches && kindMatches - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable( - $"Scene element '{data.elementId}' no longer matches stable type '{data.type.stableId}'."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable( + $"Scene element '{data.elementId}' no longer matches stable type '{data.type.stableId}'." + ); } - if (data.elementKind == SceneElementKind.Component && - m_workspace.Find(data.ownerId) is not { isRuntimeValid: true }) - { + if (data.elementKind == SceneElementKind.Component + && m_workspace.Find(data.ownerId) is not { isRuntimeValid: true } + ) { return EditorHistoryAvailability.Unavailable( - $"Component owner '{data.ownerId}' is no longer available."); + $"Component owner '{data.ownerId}' is no longer available." + ); } return EditorHistoryAvailability.Available(); } @@ -114,10 +118,12 @@ EditorHistoryDirection direction SceneElementHistoryData data = SceneElementHistoryData.Decode(change.payload.ReadBytes()); GameScene? scene = m_workspace.Find(data.sceneId); if (scene is not { isLoaded: true, isDestroyed: false }) + { return EditorHistoryResult.Failure($"Scene '{data.sceneId}' is no longer loaded."); + } bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; + ? data.existsBefore + : data.existsAfter; int index = direction == EditorHistoryDirection.Undo ? data.beforeIndex : data.afterIndex; byte[] state = direction == EditorHistoryDirection.Undo ? data.beforeState : data.afterState; EngineObject? current = m_workspace.Find(data.elementId); @@ -134,19 +140,24 @@ EditorHistoryDirection direction { EngineObject? partial = m_workspace.Find(data.elementId); if (partial is null || partial.isDestroyed) + { return EditorHistoryResult.Failure(exception.Message); + } SceneHistoryCompensationResult cleanup = SceneHistoryCompensation.Remove( partial, () => Remove(data, scene, partial), $"Partially restored scene element '{data.elementId}'", - m_workspace); + m_workspace + ); return cleanup.statePreserved - ? EditorHistoryResult.Failure(JoinFailures(exception.Message, cleanup.message)) - : StateIntegrityFailure(JoinFailures(exception.Message, cleanup.message)); + ? EditorHistoryResult.Failure(JoinFailures(exception.Message, cleanup.message)) + : StateIntegrityFailure(JoinFailures(exception.Message, cleanup.message)); } } if (current.isDestroyed) + { return EditorHistoryResult.Failure($"Scene element '{data.elementId}' is destroyed."); + } if (restored) { SceneReferenceRestoreResult referenceResult = @@ -157,11 +168,12 @@ EditorHistoryDirection direction current, () => Remove(data, scene, current), $"Restored scene element '{data.elementId}'", - m_workspace); + m_workspace + ); string failure = JoinFailures(referenceResult.message, cleanup.message); return referenceResult.statePreserved && cleanup.statePreserved - ? EditorHistoryResult.Failure(failure) - : StateIntegrityFailure(failure); + ? EditorHistoryResult.Failure(failure) + : StateIntegrityFailure(failure); } } else @@ -169,7 +181,8 @@ EditorHistoryDirection direction byte[] rollbackState = SceneElementSerialization.CaptureState( current, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); int rollbackIndex = GetIndex(data, scene, current); SceneReferenceRollbackState[] rollbackReferences = SceneReferenceIndex.CaptureCurrent(data.incomingReferences, m_workspace); @@ -178,10 +191,11 @@ EditorHistoryDirection direction if (state.Length > 0) { SceneElementSerialization.RestoreState( - current, - state, - m_workspace.serialization, - m_workspace.assets); + current, + state, + m_workspace.serialization, + m_workspace.assets + ); } SetIndex(data, scene, current, index); SceneReferenceRestoreResult referenceResult = @@ -195,7 +209,8 @@ EditorHistoryDirection direction rollbackState, rollbackIndex, rollbackReferences, - referenceResult.message); + referenceResult.message + ); } } catch (Exception exception) @@ -207,7 +222,8 @@ EditorHistoryDirection direction rollbackState, rollbackIndex, rollbackReferences, - exception.Message); + exception.Message + ); } } } @@ -216,34 +232,42 @@ EditorHistoryDirection direction byte[] rollbackState = SceneElementSerialization.CaptureState( current, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); int rollbackIndex = GetIndex(data, scene, current); SceneReferenceRollbackState[] rollbackReferences = SceneReferenceIndex.CaptureCurrent(data.incomingReferences, m_workspace); try { if (!Remove(data, scene, current)) + { return EditorHistoryResult.Failure($"Scene element '{data.elementId}' could not be removed."); + } } catch (Exception exception) { EngineObject? remaining = m_workspace.Find(data.elementId); if (remaining is { isDestroyed: false }) + { return EditorHistoryResult.Failure(exception.Message); + } try { EngineObject restored = Restore(data, scene, rollbackIndex, rollbackState); SceneReferenceRestoreResult references = SceneReferenceIndex.RestoreCurrent(rollbackReferences, m_workspace); if (!references.succeeded) + { throw new InvalidOperationException(references.message); + } _ = restored; } catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene element removal failed: {exception.Message} " + - $"Rollback failed: {rollbackException.Message}"); + $"Scene element removal failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } @@ -261,41 +285,41 @@ private EngineObject Restore( GameScene scene, int index, byte[] state - ) - => data.elementKind switch - { - SceneElementKind.Component => SceneElementSerialization.RestoreComponent( - m_workspace.Find(data.ownerId) - ?? throw new InvalidOperationException($"Component owner '{data.ownerId}' is unavailable."), - data.type, - data.elementId, - index, - state, - m_workspace.serialization, - m_workspace.assets), - SceneElementKind.System => SceneElementSerialization.RestoreSystem( - scene, - data.type, - data.elementId, - index, - state, - m_workspace.serialization, - m_workspace.assets), - _ => throw new InvalidOperationException($"Unsupported scene element kind '{data.elementKind}'.") - }; + ) => data.elementKind switch + { + SceneElementKind.Component => SceneElementSerialization.RestoreComponent( + m_workspace.Find(data.ownerId) + ?? throw new InvalidOperationException($"Component owner '{data.ownerId}' is unavailable."), + data.type, + data.elementId, + index, + state, + m_workspace.serialization, + m_workspace.assets + ), + SceneElementKind.System => SceneElementSerialization.RestoreSystem( + scene, + data.type, + data.elementId, + index, + state, + m_workspace.serialization, + m_workspace.assets + ), + _ => throw new InvalidOperationException($"Unsupported scene element kind '{data.elementKind}'.") + }; private static bool Remove( SceneElementHistoryData data, GameScene scene, EngineObject current - ) - => data.elementKind switch - { - SceneElementKind.Component when current is GameComponent component => - component.gameObject.RemoveComponent(component), - SceneElementKind.System when current is GameSystem system => scene.RemoveSystem(system), - _ => false - }; + ) => data.elementKind switch + { + SceneElementKind.Component when current is GameComponent component => + component.gameObject.RemoveComponent(component), + SceneElementKind.System when current is GameSystem system => scene.RemoveSystem(system), + _ => false + }; private static void SetIndex( SceneElementHistoryData data, @@ -304,24 +328,28 @@ private static void SetIndex( int index ) { if (data.elementKind == SceneElementKind.Component && current is GameComponent component) + { component.gameObject.SetComponentIndex(component, index); + } else if (data.elementKind == SceneElementKind.System && current is GameSystem system) + { scene.SetSystemIndex(system, index); + } } private static int GetIndex( SceneElementHistoryData data, GameScene scene, EngineObject current - ) - => data.elementKind switch - { - SceneElementKind.Component when current is GameComponent component => - component.gameObject.GetComponentIndex(component), - SceneElementKind.System when current is GameSystem system => scene.GetSystemIndex(system), - _ => throw new InvalidOperationException( - $"Scene element '{data.elementId}' does not match history kind '{data.elementKind}'.") - }; + ) => data.elementKind switch + { + SceneElementKind.Component when current is GameComponent component => + component.gameObject.GetComponentIndex(component), + SceneElementKind.System when current is GameSystem system => scene.GetSystemIndex(system), + _ => throw new InvalidOperationException( + $"Scene element '{data.elementId}' does not match history kind '{data.elementKind}'." + ) + }; private EditorHistoryResult RollbackExisting( SceneElementHistoryData data, @@ -336,10 +364,11 @@ string failure try { SceneElementSerialization.RestoreState( - current, - rollbackState, - m_workspace.serialization, - m_workspace.assets); + current, + rollbackState, + m_workspace.serialization, + m_workspace.assets + ); } catch (Exception exception) { @@ -355,18 +384,21 @@ string failure } SceneReferenceRestoreResult referenceResult = SceneReferenceIndex.RestoreCurrent( rollbackReferences, - m_workspace); + m_workspace + ); if (!referenceResult.succeeded) + { failures.Add($"reference rollback: {referenceResult.message}"); + } return failures.Count == 0 - ? EditorHistoryResult.Failure(failure) - : StateIntegrityFailure( - $"Scene element transition failed: {failure} Rollback failed: {string.Join("; ", failures)}"); + ? EditorHistoryResult.Failure(failure) + : StateIntegrityFailure( + $"Scene element transition failed: {failure} Rollback failed: {string.Join("; ", failures)}" + ); } private static string JoinFailures( string failure, string cleanup - ) - => string.IsNullOrWhiteSpace(cleanup) ? failure : $"{failure} {cleanup}"; + ) => string.IsNullOrWhiteSpace(cleanup) ? failure : $"{failure} {cleanup}"; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs index 2fdda5e2d..c5accbff4 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs @@ -34,7 +34,9 @@ internal static SceneHierarchyHistoryData Decode(ReadOnlySpan bytes) SceneObjectPlacement[] before = ReadPlacements(reader); SceneObjectPlacement[] after = ReadPlacements(reader); if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene hierarchy history payload contains trailing data."); + } return new SceneHierarchyHistoryData(before, after, selectedId); } @@ -50,7 +52,9 @@ SceneObjectPlacement[] placements writer.Write(placement.objectId.ToByteArray()); writer.Write(placement.parentId.HasValue); if (placement.parentId.HasValue) + { writer.Write(placement.parentId.Value.ToByteArray()); + } writer.Write(placement.siblingIndex); } } @@ -59,7 +63,9 @@ private static SceneObjectPlacement[] ReadPlacements(BinaryReader reader) { int count = reader.ReadInt32(); if (count < 0) + { throw new InvalidDataException("Scene hierarchy placement count cannot be negative."); + } var placements = new SceneObjectPlacement[count]; for (int i = 0; i < placements.Length; i++) { diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryHandler.cs index adb0a440d..8d0623f80 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryHandler.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Scene; @@ -48,23 +47,24 @@ EditorHistoryDirection direction { SceneHierarchyHistoryData data = SceneHierarchyHistoryData.Decode(change.payload.ReadBytes()); SceneObjectPlacement[] placements = direction == EditorHistoryDirection.Undo - ? data.before - : data.after; + ? data.before + : data.after; IReadOnlyDictionary destinationScenes = placements.ToDictionary( static placement => placement.objectId, - static placement => placement.sceneId); + static placement => placement.sceneId + ); for (int i = 0; i < placements.Length; i++) { SceneObjectPlacement placement = placements[i]; if (ResolveScene(placement.sceneId) is null) { - return EditorHistoryAvailability.Unavailable( - $"Scene '{placement.sceneId}' is no longer loaded."); + return EditorHistoryAvailability.Unavailable($"Scene '{placement.sceneId}' is no longer loaded."); } if (m_workspace.Find(placement.objectId) is not { isRuntimeValid: true }) { return EditorHistoryAvailability.Unavailable( - $"GameObject '{placement.objectId}' is no longer available."); + $"GameObject '{placement.objectId}' is no longer available." + ); } GameObject? parent = null; if (placement.parentId is Guid parentId) @@ -73,16 +73,18 @@ EditorHistoryDirection direction if (parent is not { isRuntimeValid: true }) { return EditorHistoryAvailability.Unavailable( - $"Parent GameObject '{parentId}' is no longer available."); + $"Parent GameObject '{parentId}' is no longer available." + ); } } - if (parent is not null && - parent.scene.identity.persistentId != placement.sceneId && - (!destinationScenes.TryGetValue(parent.identity.persistentId, out Guid parentDestination) || - parentDestination != placement.sceneId)) - { + if (parent is not null + && parent.scene.identity.persistentId != placement.sceneId + && (!destinationScenes.TryGetValue(parent.identity.persistentId, out Guid parentDestination) + || parentDestination != placement.sceneId) + ) { return EditorHistoryAvailability.Unavailable( - $"Parent GameObject '{parent.identity.persistentId}' does not belong to destination scene '{placement.sceneId}'."); + $"Parent GameObject '{parent.identity.persistentId}' does not belong to destination scene '{placement.sceneId}'." + ); } } return EditorHistoryAvailability.Available(); @@ -117,8 +119,8 @@ EditorHistoryDirection direction { SceneHierarchyHistoryData data = SceneHierarchyHistoryData.Decode(change.payload.ReadBytes()); SceneObjectPlacement[] destination = direction == EditorHistoryDirection.Undo - ? data.before - : data.after; + ? data.before + : data.after; SceneObjectPlacement[] rollback = Capture(destination); try { @@ -133,8 +135,9 @@ EditorHistoryDirection direction catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene hierarchy update failed: {exception.Message} " + - $"Placement rollback failed: {rollbackException.Message}"); + $"Scene hierarchy update failed: {exception.Message} " + + $"Placement rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } @@ -145,10 +148,7 @@ EditorHistoryDirection direction } catch (Exception exception) { - m_log.Write( - LogLevel.Error, - "Scene hierarchy selection notification failed: {0}", - [exception]); + m_log.Write(LogLevel.Error, "Scene hierarchy selection notification failed: {0}", [exception]); } return EditorHistoryResult.Success(); } @@ -162,24 +162,27 @@ private SceneObjectPlacement[] Capture(IEnumerable placeme => placements.Select(placement => { GameObject gameObject = m_workspace.Find(placement.objectId) - ?? throw new InvalidOperationException($"GameObject '{placement.objectId}' is no longer available."); + ?? throw new InvalidOperationException($"GameObject '{placement.objectId}' is no longer available."); return new SceneObjectPlacement( gameObject.scene.identity.persistentId, placement.objectId, gameObject.transform.parent?.gameObject.identity.persistentId, - gameObject.transform.siblingIndex); + gameObject.transform.siblingIndex + ); }).ToArray(); private void ApplyPlacements(IReadOnlyCollection placements) { foreach (SceneObjectPlacement placement in placements.OrderBy(placement => - GetHierarchyDepth(ResolveObject(placement.objectId).transform))) - { + GetHierarchyDepth(ResolveObject(placement.objectId).transform)) + ) { GameObject gameObject = ResolveObject(placement.objectId); GameScene destination = ResolveScene(placement.sceneId) - ?? throw new InvalidOperationException($"Scene '{placement.sceneId}' is no longer loaded."); + ?? throw new InvalidOperationException($"Scene '{placement.sceneId}' is no longer loaded."); if (!ReferenceEquals(gameObject.scene, destination)) + { m_workspace.world.MoveGameObjectToScene(gameObject, destination); + } } var pending = new List(placements); @@ -191,20 +194,26 @@ private void ApplyPlacements(IReadOnlyCollection placement SceneObjectPlacement placement = pending[i]; GameObject gameObject = ResolveObject(placement.objectId); Transform? parent = placement.parentId is Guid parentId - ? ResolveObject(parentId).transform - : null; + ? ResolveObject(parentId).transform + : null; if (parent is not null && IsDescendantOf(parent, gameObject.transform)) + { continue; + } gameObject.transform.SetParent(parent); pending.RemoveAt(i); progressed = true; } if (!progressed) + { throw new InvalidOperationException("Scene hierarchy history would create a parent cycle."); + } } foreach (SceneObjectPlacement placement in placements.OrderBy(static value => value.siblingIndex)) + { ResolveObject(placement.objectId).transform.SetSiblingIndex(placement.siblingIndex); + } } private static bool IsDescendantOf( @@ -214,7 +223,9 @@ Transform possibleAncestor for (Transform? current = transform; current is not null; current = current.parent) { if (ReferenceEquals(current, possibleAncestor)) + { return true; + } } return false; } @@ -223,17 +234,19 @@ private static int GetHierarchyDepth(Transform transform) { int depth = 0; for (Transform? current = transform.parent; current is not null; current = current.parent) + { depth++; + } return depth; } private GameObject ResolveObject(Guid objectId) => m_workspace.Find(objectId) is { isRuntimeValid: true } gameObject - ? gameObject - : throw new InvalidOperationException($"GameObject '{objectId}' is no longer available."); + ? gameObject + : throw new InvalidOperationException($"GameObject '{objectId}' is no longer available."); private GameScene? ResolveScene(Guid sceneId) => m_workspace.Find(sceneId) is { isLoaded: true, isDestroyed: false } scene - ? scene - : null; + ? scene + : null; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryCompensation.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryCompensation.cs index 346ec8a33..29a0a8960 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryCompensation.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHistoryCompensation.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Scene; namespace Inno.Editor.Scene; @@ -30,10 +29,13 @@ EditorSceneWorkspace workspace gameObject, () => scene.DestroyObject(gameObject), $"{description} GameObject '{gameObject.identity.persistentId}'", - workspace); + workspace + ); statePreserved &= result.statePreserved; if (!string.IsNullOrWhiteSpace(result.message)) + { messages.Add(result.message); + } } GameObject[] survivors = scene.GetObjects() @@ -45,8 +47,8 @@ EditorSceneWorkspace workspace messages.Add($"{description} left {survivors.Length} untracked GameObject(s) in the scene."); } return statePreserved - ? SceneHistoryCompensationResult.Preserved(string.Join(" ", messages)) - : SceneHistoryCompensationResult.Lost(string.Join(" ", messages)); + ? SceneHistoryCompensationResult.Preserved(string.Join(" ", messages)) + : SceneHistoryCompensationResult.Lost(string.Join(" ", messages)); } internal static SceneHistoryCompensationResult Remove( @@ -70,27 +72,28 @@ EditorSceneWorkspace workspace failure = exception; } - bool remainsRegistered = ReferenceEquals( - workspace.Find(persistentId), - target); + bool remainsRegistered = ReferenceEquals(workspace.Find(persistentId), target); if (target.isDestroyed && !remainsRegistered) { return SceneHistoryCompensationResult.Preserved( failure is null - ? string.Empty - : $"{description} was removed, but its destruction callback failed: {failure.Message}"); + ? string.Empty + : $"{description} was removed, but its destruction callback failed: {failure.Message}" + ); } if (failure is not null) { return SceneHistoryCompensationResult.Lost( - $"{description} did not reach the destroyed and unregistered postcondition " + - $"after removal threw: {failure.Message}"); + $"{description} did not reach the destroyed and unregistered postcondition " + + $"after removal threw: {failure.Message}" + ); } return SceneHistoryCompensationResult.Lost( reportedRemoved - ? $"{description} reported successful removal but did not reach the destroyed and unregistered postcondition." - : $"{description} could not be fully destroyed and unregistered."); + ? $"{description} reported successful removal but did not reach the destroyed and unregistered postcondition." + : $"{description} could not be fully destroyed and unregistered." + ); } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryData.cs index e689e01fe..2a0b5135d 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryData.cs @@ -22,10 +22,13 @@ internal byte[] Encode() internal static SceneOrderHistoryData Decode(ReadOnlySpan bytes) { if (bytes.Length != 24) + { throw new InvalidDataException("Scene order history payload must contain exactly 24 bytes."); + } return new SceneOrderHistoryData( new Guid(bytes[..16]), BitConverter.ToInt32(bytes[16..20]), - BitConverter.ToInt32(bytes[20..24])); + BitConverter.ToInt32(bytes[20..24]) + ); } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryHandler.cs index 1833d8af6..14587ad7d 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneOrderHistoryHandler.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Scene; @@ -45,8 +44,8 @@ EditorHistoryDirection direction { SceneOrderHistoryData data = SceneOrderHistoryData.Decode(change.payload.ReadBytes()); return m_workspace.Find(data.sceneId) is { isLoaded: true, isDestroyed: false } - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable($"Scene '{data.sceneId}' is no longer loaded."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable($"Scene '{data.sceneId}' is no longer loaded."); } catch (Exception exception) { @@ -79,13 +78,16 @@ EditorHistoryDirection direction SceneOrderHistoryData data = SceneOrderHistoryData.Decode(change.payload.ReadBytes()); GameScene? scene = m_workspace.Find(data.sceneId); if (scene is not { isLoaded: true, isDestroyed: false }) + { return EditorHistoryResult.Failure($"Scene '{data.sceneId}' is no longer loaded."); + } int rollbackIndex = m_workspace.world.GetSceneIndex(scene); try { m_workspace.world.SetSceneIndex( scene, - direction == EditorHistoryDirection.Undo ? data.beforeIndex : data.afterIndex); + direction == EditorHistoryDirection.Undo ? data.beforeIndex : data.afterIndex + ); } catch (Exception exception) { @@ -96,7 +98,8 @@ EditorHistoryDirection direction catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene reorder failed: {exception.Message} Rollback failed: {rollbackException.Message}"); + $"Scene reorder failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs index 013ffc461..b517badda 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs @@ -45,12 +45,10 @@ IReadOnlyList deltas ArgumentException.ThrowIfNullOrWhiteSpace(propertyName); ArgumentNullException.ThrowIfNull(deltas); if (deltas.Count == 0) + { throw new ArgumentException("A scene property history change requires at least one delta.", nameof(deltas)); - return new ScenePropertyHistoryData( - targetId, - propertyName, - [.. deltas], - Stopwatch.GetTimestamp()); + } + return new ScenePropertyHistoryData(targetId, propertyName, [.. deltas], Stopwatch.GetTimestamp()); } internal static ScenePropertyHistoryData Decode(ReadOnlySpan bytes) @@ -61,22 +59,29 @@ internal static ScenePropertyHistoryData Decode(ReadOnlySpan bytes) string propertyName = reader.ReadString(); int count = reader.ReadInt32(); if (count <= 0) + { throw new InvalidDataException("Scene property history delta count must be positive."); + } var deltas = new ScenePropertyValueDelta[count]; var names = new HashSet(StringComparer.Ordinal); for (int index = 0; index < count; index++) { string affectedProperty = reader.ReadString(); if (string.IsNullOrWhiteSpace(affectedProperty) || !names.Add(affectedProperty)) + { throw new InvalidDataException("Scene property history contains an invalid or duplicate property name."); + } deltas[index] = new ScenePropertyValueDelta( affectedProperty, ReadBytes(reader, $"{affectedProperty} before"), - ReadBytes(reader, $"{affectedProperty} after")); + ReadBytes(reader, $"{affectedProperty} after") + ); } long timestamp = reader.ReadInt64(); if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene property history payload contains trailing data."); + } return new ScenePropertyHistoryData(targetId, propertyName, deltas, timestamp); } @@ -94,10 +99,14 @@ string name ) { int length = reader.ReadInt32(); if (length < 0 || length > reader.BaseStream.Length - reader.BaseStream.Position) + { throw new InvalidDataException($"Scene property history {name} value length is invalid."); + } byte[] bytes = reader.ReadBytes(length); if (bytes.Length != length) + { throw new EndOfStreamException($"Scene property history {name} value is truncated."); + } return bytes; } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs index 9260ea18a..1e0fe00cb 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; - using Inno.Core.Serialization; using Inno.Editor.Interactions; using Inno.Scene; @@ -45,11 +44,14 @@ EditorHistoryDirection direction ScenePropertyHistoryData data = ScenePropertyHistoryData.Decode(change.payload.ReadBytes()); EngineObject? target = m_workspace.Find(data.targetId); if (target is null || target.isDestroyed) + { return EditorHistoryAvailability.Unavailable($"Scene object '{data.targetId}' is no longer available."); + } if (target is not ISerializable serializable) { return EditorHistoryAvailability.Unavailable( - $"Scene object '{data.targetId}' is not serializable in the current generation."); + $"Scene object '{data.targetId}' is not serializable in the current generation." + ); } HashSet currentProperties = ScenePropertySerialization .CapturePropertySnapshots(target, m_workspace.serialization, m_workspace.assets) @@ -57,10 +59,11 @@ EditorHistoryDirection direction .ToHashSet(StringComparer.Ordinal); bool propertiesExist = data.deltas.All(delta => currentProperties.Contains(delta.propertyName)); return propertiesExist - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable( - $"One or more properties affected by '{data.propertyName}' no longer exist on " + - $"scene object '{data.targetId}'."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable( + $"One or more properties affected by '{data.propertyName}' no longer exist on " + + $"scene object '{data.targetId}'." + ); } catch (Exception exception) { @@ -95,7 +98,9 @@ EditorHistoryDirection direction data = ScenePropertyHistoryData.Decode(change.payload.ReadBytes()); target = m_workspace.Find(data.targetId); if (target is null || target.isDestroyed) + { return EditorHistoryResult.Failure($"Scene object '{data.targetId}' is no longer available."); + } } catch (Exception exception) { @@ -110,7 +115,8 @@ EditorHistoryDirection direction target, delta.propertyName, m_workspace.serialization, - m_workspace.assets)) + m_workspace.assets + )) .ToArray(); } catch (Exception exception) @@ -128,12 +134,15 @@ EditorHistoryDirection direction try { for (int index = 0; index < rollback.Length; index++) + { RestoreOne(target, rollback[index]); + } } catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene property restore failed: {exception.Message} Rollback failed: {rollbackException.Message}"); + $"Scene property restore failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } @@ -148,7 +157,9 @@ private void RestoreDeltas( bool useAfter ) { for (int index = 0; index < deltas.Count; index++) + { RestoreOne(target, useAfter ? deltas[index].after : deltas[index].before); + } } private void RestoreOne( @@ -159,9 +170,12 @@ ReadOnlySpan data target, data, m_workspace.serialization, - m_workspace.assets); + m_workspace.assets + ); if (!IsComplete(result)) + { throw new InvalidOperationException("The scene property restore was incomplete."); + } } /// @@ -186,23 +200,27 @@ out EditorHistoryChange? merged ) { merged = null; if (!string.Equals(older.mergeKey, newer.mergeKey, StringComparison.Ordinal) || older.mergeKey is null) + { return false; + } try { ScenePropertyHistoryData previous = ScenePropertyHistoryData.Decode(older.payload.ReadBytes()); ScenePropertyHistoryData current = ScenePropertyHistoryData.Decode(newer.payload.ReadBytes()); - if (previous.targetId != current.targetId || - !string.Equals(previous.propertyName, current.propertyName, StringComparison.Ordinal) || - Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > C_MERGE_WINDOW_SECONDS) - { + if (previous.targetId != current.targetId + || !string.Equals(previous.propertyName, current.propertyName, StringComparison.Ordinal) + || Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > C_MERGE_WINDOW_SECONDS + ) { return false; } IReadOnlyDictionary previousByName = previous.deltas.ToDictionary( static delta => delta.propertyName, - StringComparer.Ordinal); + StringComparer.Ordinal + ); IReadOnlyDictionary currentByName = current.deltas.ToDictionary( static delta => delta.propertyName, - StringComparer.Ordinal); + StringComparer.Ordinal + ); string[] names = previous.deltas .Select(static delta => delta.propertyName) .Concat(current.deltas.Select(static delta => delta.propertyName)) @@ -212,24 +230,29 @@ out EditorHistoryChange? merged .Select(name => new ScenePropertyValueDelta( name, previousByName.TryGetValue(name, out ScenePropertyValueDelta? previousDelta) - ? previousDelta.before - : currentByName[name].before, + ? previousDelta.before + : currentByName[name].before, currentByName.TryGetValue(name, out ScenePropertyValueDelta? currentDelta) - ? currentDelta.after - : previousByName[name].after)) + ? currentDelta.after + : previousByName[name].after + )) .Where(static delta => !delta.before.AsSpan().SequenceEqual(delta.after)) .ToArray(); if (deltas.Length == 0) + { return false; + } var data = new ScenePropertyHistoryData( previous.targetId, previous.propertyName, deltas, - current.timestamp); + current.timestamp + ); merged = new EditorHistoryChange( SceneHistoryKinds.Property, EditorHistoryPayload.FromBytes(data.Encode()), - older.mergeKey); + older.mergeKey + ); return true; } catch diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs index b3560e23b..7ab0268ff 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs @@ -30,8 +30,7 @@ internal static SceneScalarHistoryData Create( SceneScalarKind scalarKind, string before, string after - ) - => new(targetId, scalarKind, before, after, Stopwatch.GetTimestamp()); + ) => new(targetId, scalarKind, before, after, Stopwatch.GetTimestamp()); internal static SceneScalarHistoryData Decode(ReadOnlySpan bytes) { @@ -40,12 +39,16 @@ internal static SceneScalarHistoryData Decode(ReadOnlySpan bytes) Guid targetId = new(reader.ReadBytes(16)); var scalarKind = (SceneScalarKind)reader.ReadByte(); if (!Enum.IsDefined(scalarKind)) + { throw new InvalidDataException($"Unknown scene scalar history kind '{scalarKind}'."); + } string before = reader.ReadString(); string after = reader.ReadString(); long timestamp = reader.ReadInt64(); if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene scalar history payload contains trailing data."); + } return new SceneScalarHistoryData(targetId, scalarKind, before, after, timestamp); } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs index f6cf76c90..5fdf664a1 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs @@ -1,6 +1,5 @@ using System; using System.Diagnostics; - using Inno.Editor.Interactions; using Inno.Scene; using Inno.Scene.Layers; @@ -42,9 +41,10 @@ EditorHistoryDirection direction { SceneScalarHistoryData data = SceneScalarHistoryData.Decode(change.payload.ReadBytes()); return Resolve(data) is not null - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable( - $"Scene target '{data.targetId}' is no longer available for '{data.scalarKind}'."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable( + $"Scene target '{data.targetId}' is no longer available for '{data.scalarKind}'." + ); } catch (Exception exception) { @@ -76,7 +76,7 @@ EditorHistoryDirection direction { SceneScalarHistoryData data = SceneScalarHistoryData.Decode(change.payload.ReadBytes()); EngineObject target = Resolve(data) - ?? throw new InvalidOperationException($"Scene target '{data.targetId}' is no longer available."); + ?? throw new InvalidOperationException($"Scene target '{data.targetId}' is no longer available."); string rollback = GetValue(target, data.scalarKind); string value = direction == EditorHistoryDirection.Undo ? data.before : data.after; try @@ -92,7 +92,8 @@ EditorHistoryDirection direction catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene scalar update failed: {exception.Message} Rollback failed: {rollbackException.Message}"); + $"Scene scalar update failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } @@ -126,15 +127,17 @@ out EditorHistoryChange? merged ) { merged = null; if (older.mergeKey is null || !string.Equals(older.mergeKey, newer.mergeKey, StringComparison.Ordinal)) + { return false; + } try { SceneScalarHistoryData previous = SceneScalarHistoryData.Decode(older.payload.ReadBytes()); SceneScalarHistoryData current = SceneScalarHistoryData.Decode(newer.payload.ReadBytes()); - if (previous.targetId != current.targetId || - previous.scalarKind != current.scalarKind || - Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > C_MERGE_WINDOW_SECONDS) - { + if (previous.targetId != current.targetId + || previous.scalarKind != current.scalarKind + || Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > C_MERGE_WINDOW_SECONDS + ) { return false; } var data = new SceneScalarHistoryData( @@ -142,11 +145,13 @@ out EditorHistoryChange? merged previous.scalarKind, previous.before, current.after, - current.timestamp); + current.timestamp + ); merged = new EditorHistoryChange( SceneHistoryKinds.Scalar, EditorHistoryPayload.FromBytes(data.Encode()), - older.mergeKey); + older.mergeKey + ); return true; } catch @@ -157,33 +162,33 @@ out EditorHistoryChange? merged private EngineObject? Resolve(SceneScalarHistoryData data) => data.scalarKind switch - { - SceneScalarKind.SceneName => m_workspace.Find(data.targetId) is - { isLoaded: true, isDestroyed: false } scene ? scene : null, - SceneScalarKind.GameObjectName or - SceneScalarKind.GameObjectActive or - SceneScalarKind.GameObjectTag or - SceneScalarKind.GameObjectLayer => - m_workspace.Find(data.targetId) is { isRuntimeValid: true } gameObject - ? gameObject - : null, - _ => null - }; + { + SceneScalarKind.SceneName => m_workspace.Find(data.targetId) is + { isLoaded: true, isDestroyed: false } scene ? scene : null, + SceneScalarKind.GameObjectName + or SceneScalarKind.GameObjectActive + or SceneScalarKind.GameObjectTag + or SceneScalarKind.GameObjectLayer => + m_workspace.Find(data.targetId) is { isRuntimeValid: true } gameObject + ? gameObject + : null, + _ => null + }; private static string GetValue( EngineObject target, SceneScalarKind kind - ) - => kind switch - { - SceneScalarKind.SceneName => ((GameScene)target).name, - SceneScalarKind.GameObjectName => ((GameObject)target).name, - SceneScalarKind.GameObjectActive => ((GameObject)target).activeSelf ? "1" : "0", - SceneScalarKind.GameObjectTag => ((GameObject)target).tag, - SceneScalarKind.GameObjectLayer => ((GameObject)target).layer.index.ToString( - System.Globalization.CultureInfo.InvariantCulture), - _ => throw new InvalidOperationException($"Unsupported scene scalar '{kind}'.") - }; + ) => kind switch + { + SceneScalarKind.SceneName => ((GameScene)target).name, + SceneScalarKind.GameObjectName => ((GameObject)target).name, + SceneScalarKind.GameObjectActive => ((GameObject)target).activeSelf ? "1" : "0", + SceneScalarKind.GameObjectTag => ((GameObject)target).tag, + SceneScalarKind.GameObjectLayer => ((GameObject)target).layer.index.ToString( + System.Globalization.CultureInfo.InvariantCulture + ), + _ => throw new InvalidOperationException($"Unsupported scene scalar '{kind}'.") + }; private static void SetValue( EngineObject target, @@ -206,7 +211,8 @@ string value break; case SceneScalarKind.GameObjectLayer: ((GameObject)target).layer = new GameLayer( - int.Parse(value, System.Globalization.CultureInfo.InvariantCulture)); + int.Parse(value, System.Globalization.CultureInfo.InvariantCulture) + ); break; default: throw new InvalidOperationException($"Unsupported scene scalar '{kind}'."); diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs index a4dd2f862..a3b6259c5 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs @@ -54,19 +54,24 @@ internal static SceneSubtreeHistoryData Decode(ReadOnlySpan bytes) byte[] subtree = ReadBytes(reader, "subtree"); int referenceCount = reader.ReadInt32(); if (referenceCount < 0) + { throw new InvalidDataException("Scene subtree incoming reference count cannot be negative."); + } var references = new SceneIncomingReferenceState[referenceCount]; for (int i = 0; i < references.Length; i++) { references[i] = new SceneIncomingReferenceState( new Guid(reader.ReadBytes(16)), reader.ReadString(), - ReadBytes(reader, "incoming reference")); + ReadBytes(reader, "incoming reference") + ); } Guid? selectedBefore = ReadGuid(reader); Guid? selectedAfter = ReadGuid(reader); if (stream.Position != stream.Length) + { throw new InvalidDataException("Scene subtree history payload contains trailing data."); + } return new SceneSubtreeHistoryData( sceneId, rootId, @@ -77,7 +82,8 @@ internal static SceneSubtreeHistoryData Decode(ReadOnlySpan bytes) subtree, references, selectedBefore, - selectedAfter); + selectedAfter + ); } private static void WriteBytes( @@ -94,10 +100,14 @@ string name ) { int length = reader.ReadInt32(); if (length < 0 || length > reader.BaseStream.Length - reader.BaseStream.Position) + { throw new InvalidDataException($"Scene subtree history {name} length is invalid."); + } byte[] bytes = reader.ReadBytes(length); if (bytes.Length != length) + { throw new EndOfStreamException($"Scene subtree history {name} is truncated."); + } return bytes; } @@ -107,7 +117,9 @@ private static void WriteGuid( ) { writer.Write(value.HasValue); if (value.HasValue) + { writer.Write(value.Value.ToByteArray()); + } } private static Guid? ReadGuid(BinaryReader reader) => reader.ReadBoolean() ? new Guid(reader.ReadBytes(16)) : null; diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryHandler.cs index 4e717ebcd..1469da8e2 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryHandler.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Scene; @@ -48,24 +47,27 @@ EditorHistoryDirection direction SceneSubtreeHistoryData data = SceneSubtreeHistoryData.Decode(change.payload.ReadBytes()); GameScene? scene = m_workspace.Find(data.sceneId); if (scene is not { isLoaded: true, isDestroyed: false }) + { return EditorHistoryAvailability.Unavailable($"Scene '{data.sceneId}' is no longer loaded."); + } bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; + ? data.existsBefore + : data.existsAfter; GameObject? current = m_workspace.Find(data.rootId); if (!shouldExist) { return current is { isRuntimeValid: true } - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable($"GameObject '{data.rootId}' is no longer available."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable($"GameObject '{data.rootId}' is no longer available."); } if (current is { isRuntimeValid: true }) - return EditorHistoryAvailability.Available(); - if (data.parentId is Guid parentId && - m_workspace.Find(parentId) is not { isRuntimeValid: true }) { - return EditorHistoryAvailability.Unavailable( - $"Parent GameObject '{parentId}' is no longer available."); + return EditorHistoryAvailability.Available(); + } + if (data.parentId is Guid parentId + && m_workspace.Find(parentId) is not { isRuntimeValid: true } + ) { + return EditorHistoryAvailability.Unavailable($"Parent GameObject '{parentId}' is no longer available."); } return EditorHistoryAvailability.Available(); } @@ -100,22 +102,22 @@ EditorHistoryDirection direction SceneSubtreeHistoryData data = SceneSubtreeHistoryData.Decode(change.payload.ReadBytes()); GameScene? scene = m_workspace.Find(data.sceneId); if (scene is not { isLoaded: true, isDestroyed: false }) + { return EditorHistoryResult.Failure($"Scene '{data.sceneId}' is no longer loaded."); + } bool shouldExist = direction == EditorHistoryDirection.Undo - ? data.existsBefore - : data.existsAfter; + ? data.existsBefore + : data.existsAfter; Guid? selected = direction == EditorHistoryDirection.Undo - ? data.selectedBefore - : data.selectedAfter; + ? data.selectedBefore + : data.selectedAfter; GameObject? root = m_workspace.Find(data.rootId); if (shouldExist && root is null) { - var existing = new HashSet( - scene.GetObjects(), - ReferenceEqualityComparer.Instance); + var existing = new HashSet(scene.GetObjects(), ReferenceEqualityComparer.Instance); Transform? parent = data.parentId is Guid parentId - ? m_workspace.Find(parentId)?.transform - : null; + ? m_workspace.Find(parentId)?.transform + : null; try { root = SceneSubtreeSerialization.Restore( @@ -124,7 +126,8 @@ EditorHistoryDirection direction m_workspace.serialization, m_workspace.assets, parent, - data.siblingIndex); + data.siblingIndex + ); } catch (Exception exception) { @@ -133,10 +136,11 @@ EditorHistoryDirection direction scene, existing, $"Partial scene subtree '{data.rootId}'", - m_workspace); + m_workspace + ); return cleanup.statePreserved - ? EditorHistoryResult.Failure(JoinFailures(exception.Message, cleanup.message)) - : StateIntegrityFailure(JoinFailures(exception.Message, cleanup.message)); + ? EditorHistoryResult.Failure(JoinFailures(exception.Message, cleanup.message)) + : StateIntegrityFailure(JoinFailures(exception.Message, cleanup.message)); } SceneReferenceRestoreResult referenceResult = SceneReferenceIndex.RestoreIncoming(data.incomingReferences, m_workspace); @@ -146,11 +150,12 @@ EditorHistoryDirection direction root, () => scene.DestroyObject(root), $"Restored scene subtree '{data.rootId}'", - m_workspace); + m_workspace + ); string failure = JoinFailures(referenceResult.message, cleanup.message); return referenceResult.statePreserved && cleanup.statePreserved - ? EditorHistoryResult.Failure(failure) - : StateIntegrityFailure(failure); + ? EditorHistoryResult.Failure(failure) + : StateIntegrityFailure(failure); } } else if (!shouldExist && root is { isRuntimeValid: true }) @@ -158,42 +163,50 @@ EditorHistoryDirection direction try { if (!scene.DestroyObject(root)) + { return EditorHistoryResult.Failure($"GameObject '{data.rootId}' could not be removed."); + } } catch (Exception exception) { if (root.isRuntimeValid) + { return EditorHistoryResult.Failure(exception.Message); + } try { Transform? parent = data.parentId is Guid parentId - ? m_workspace.Find(parentId)?.transform - : null; + ? m_workspace.Find(parentId)?.transform + : null; _ = SceneSubtreeSerialization.Restore( scene, data.subtree, m_workspace.serialization, m_workspace.assets, parent, - data.siblingIndex); + data.siblingIndex + ); SceneReferenceRestoreResult referenceRollback = SceneReferenceIndex.RestoreIncoming(data.incomingReferences, m_workspace); if (!referenceRollback.succeeded) + { throw new InvalidOperationException(referenceRollback.message); + } } catch (Exception rollbackException) { return StateIntegrityFailure( - $"Scene subtree removal failed: {exception.Message} " + - $"Rollback failed: {rollbackException.Message}"); + $"Scene subtree removal failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } root = null; } object? selection = selected is Guid selectionId - ? m_workspace.Find(selectionId) - : null; + ? m_workspace.Find(selectionId) + : null; try { _ = context.interactions.For(context.interactions.focusedArea, selection).Select(); @@ -213,6 +226,5 @@ EditorHistoryDirection direction private static string JoinFailures( string failure, string cleanup - ) - => string.IsNullOrWhiteSpace(cleanup) ? failure : $"{failure} {cleanup}"; + ) => string.IsNullOrWhiteSpace(cleanup) ? failure : $"{failure} {cleanup}"; } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Properties/ScriptingApi.cs b/src/composition/editor/features/Inno.Editor.Scene/Properties/ScriptingApi.cs index 818f9aeb2..9221ebced 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Properties/ScriptingApi.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Editor.Scene; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Scene", - "Inno.Editor.Scene", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Scene", "Inno.Editor.Scene", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(IEditorSceneWorkspace), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(SceneEdits), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs b/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs index c56a1b267..504553eb1 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs @@ -2,7 +2,6 @@ using System.Collections; using System.Collections.Generic; using System.Reflection; - using Inno.Core.Serialization; using Inno.Scene; using Inno.Scene.Components; @@ -23,24 +22,30 @@ EditorSceneWorkspace workspace foreach (EngineObject owner in EnumerateSceneObjects(root.scene)) { if (subtreeIds.Contains(owner.identity.persistentId) || owner is not ISerializable serializable) + { continue; + } IReadOnlyList properties = workspace.serialization.GetProperties(serializable); for (int i = 0; i < properties.Count; i++) { SerializedProperty property = properties[i]; - if (!property.canRead || - !ContainsReference(property.GetValue(), subtreeIds, new HashSet(ReferenceEqualityComparer.Instance))) - { + if (!property.canRead + || !ContainsReference(property.GetValue(), subtreeIds, new HashSet(ReferenceEqualityComparer.Instance)) + ) { continue; } - result.Add(new SceneIncomingReferenceState( - owner.identity.persistentId, - property.name, - ScenePropertySerialization.CaptureProperty( - owner, + result.Add( + new SceneIncomingReferenceState( + owner.identity.persistentId, property.name, - workspace.serialization, - workspace.assets))); + ScenePropertySerialization.CaptureProperty( + owner, + property.name, + workspace.serialization, + workspace.assets + ) + ) + ); } } return result.ToArray(); @@ -68,10 +73,7 @@ EditorSceneWorkspace workspace EngineObject? owner = workspace.Find(reference.ownerId); if (owner is null || owner.isDestroyed) { - return Rollback( - rollback, - $"Incoming reference owner '{reference.ownerId}' is unavailable.", - workspace); + return Rollback(rollback, $"Incoming reference owner '{reference.ownerId}' is unavailable.", workspace); } try { @@ -81,13 +83,15 @@ EditorSceneWorkspace workspace reference.data, workspace.serialization, workspace.assets, - SerializationPropertyRestoreMode.CollectFailures); + SerializationPropertyRestoreMode.CollectFailures + ); if (!IsComplete(result)) { return Rollback( rollback, $"Incoming property '{reference.propertyName}' on '{reference.ownerId}' was not restored completely.", - workspace); + workspace + ); } } catch (Exception exception) @@ -95,7 +99,8 @@ EditorSceneWorkspace workspace return Rollback( rollback, $"Incoming property '{reference.propertyName}' on '{reference.ownerId}' failed: {exception.Message}", - workspace); + workspace + ); } } return SceneReferenceRestoreResult.Success(); @@ -110,8 +115,9 @@ EditorSceneWorkspace workspace { SceneIncomingReferenceState reference = references[i]; EngineObject owner = workspace.Find(reference.ownerId) - ?? throw new InvalidOperationException( - $"Incoming reference owner '{reference.ownerId}' is unavailable."); + ?? throw new InvalidOperationException( + $"Incoming reference owner '{reference.ownerId}' is unavailable." + ); result[i] = CaptureRollback(owner, reference.propertyName, workspace); } return result; @@ -120,8 +126,7 @@ EditorSceneWorkspace workspace internal static SceneReferenceRestoreResult RestoreCurrent( IReadOnlyList references, EditorSceneWorkspace workspace - ) - => Rollback(references, failure: null, workspace); + ) => Rollback(references, failure: null, workspace); private static SceneReferenceRestoreResult Rollback( IReadOnlyList rollback, @@ -135,7 +140,7 @@ EditorSceneWorkspace workspace try { EngineObject owner = workspace.Find(reference.ownerId) - ?? throw new InvalidOperationException("The rollback owner is unavailable."); + ?? throw new InvalidOperationException("The rollback owner is unavailable."); if (reference.data is not null) { SerializationPropertyRestoreResult result = ScenePropertySerialization.RestoreProperties( @@ -143,9 +148,12 @@ EditorSceneWorkspace workspace reference.data, workspace.serialization, workspace.assets, - SerializationPropertyRestoreMode.Strict); + SerializationPropertyRestoreMode.Strict + ); if (!IsComplete(result)) + { rollbackFailures.Add($"'{reference.ownerId}.{reference.propertyName}' was incomplete"); + } } else { @@ -159,12 +167,13 @@ EditorSceneWorkspace workspace } } return rollbackFailures.Count == 0 - ? failure is null - ? SceneReferenceRestoreResult.Success() - : SceneReferenceRestoreResult.Failure(failure) - : SceneReferenceRestoreResult.StateIntegrityLost( - $"{failure ?? "Reference compensation failed."} " + - $"Reference rollback failed: {string.Join("; ", rollbackFailures)}"); + ? failure is null + ? SceneReferenceRestoreResult.Success() + : SceneReferenceRestoreResult.Failure(failure) + : SceneReferenceRestoreResult.StateIntegrityLost( + $"{failure ?? "Reference compensation failed."} " + + $"Reference rollback failed: {string.Join("; ", rollbackFailures)}" + ); } private static SceneReferenceRollbackState CaptureRollback( @@ -181,8 +190,10 @@ EditorSceneWorkspace workspace owner, propertyName, workspace.serialization, - workspace.assets), - runtimeValue: null); + workspace.assets + ), + runtimeValue: null + ); } catch (InvalidOperationException) { @@ -191,7 +202,8 @@ EditorSceneWorkspace workspace owner.identity.persistentId, propertyName, data: null, - property.GetValue()); + property.GetValue() + ); } } @@ -201,15 +213,20 @@ private static SerializedProperty ResolveProperty( SerializationRegistry serialization ) { if (owner is not ISerializable serializable) + { throw new InvalidOperationException($"Incoming reference owner '{owner.identity.persistentId}' is not serializable."); + } IReadOnlyList properties = serialization.GetProperties(serializable); for (int i = 0; i < properties.Count; i++) { if (string.Equals(properties[i].name, propertyName, StringComparison.Ordinal)) + { return properties[i]; + } } throw new InvalidOperationException( - $"Incoming property '{propertyName}' on '{owner.identity.persistentId}' is unavailable."); + $"Incoming property '{propertyName}' on '{owner.identity.persistentId}' is unavailable." + ); } private static bool IsComplete(SerializationPropertyRestoreResult result) @@ -221,20 +238,30 @@ private static bool ContainsReference( ISet visited ) { if (value is null) + { return false; + } if (value is EngineObject engineObject) + { return !engineObject.isDestroyed && targetIds.Contains(engineObject.identity.persistentId); + } Type type = value.GetType(); if (type.IsPrimitive || type.IsEnum || value is string or Type or Delegate or decimal or DateTime or Guid) + { return false; + } if (!type.IsValueType && !visited.Add(value)) + { return false; + } if (value is IEnumerable enumerable) { foreach (object? item in enumerable) { if (ContainsReference(item, targetIds, visited)) + { return true; + } } return false; } @@ -242,7 +269,8 @@ ISet visited for (Type? current = type; current is not null && current != typeof(object); current = current.BaseType) { FieldInfo[] fields = current.GetFields( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly + ); for (int i = 0; i < fields.Length; i++) { object? fieldValue; @@ -255,7 +283,9 @@ ISet visited continue; } if (ContainsReference(fieldValue, targetIds, visited)) + { return true; + } } } return false; @@ -270,24 +300,30 @@ EditorSceneWorkspace workspace foreach (EngineObject owner in EnumerateSceneObjects(scene)) { if (targetIds.Contains(owner.identity.persistentId) || owner is not ISerializable serializable) + { continue; + } IReadOnlyList properties = workspace.serialization.GetProperties(serializable); for (int i = 0; i < properties.Count; i++) { SerializedProperty property = properties[i]; - if (!property.canRead || - !ContainsReference(property.GetValue(), targetIds, new HashSet(ReferenceEqualityComparer.Instance))) - { + if (!property.canRead + || !ContainsReference(property.GetValue(), targetIds, new HashSet(ReferenceEqualityComparer.Instance)) + ) { continue; } - result.Add(new SceneIncomingReferenceState( - owner.identity.persistentId, - property.name, - ScenePropertySerialization.CaptureProperty( - owner, + result.Add( + new SceneIncomingReferenceState( + owner.identity.persistentId, property.name, - workspace.serialization, - workspace.assets))); + ScenePropertySerialization.CaptureProperty( + owner, + property.name, + workspace.serialization, + workspace.assets + ) + ) + ); } } return result.ToArray(); @@ -301,11 +337,15 @@ private static IEnumerable EnumerateSceneObjects(GameScene scene) yield return gameObjects[i]; IReadOnlyList components = gameObjects[i].GetComponents(); for (int componentIndex = 0; componentIndex < components.Count; componentIndex++) + { yield return components[componentIndex]; + } } IReadOnlyList systems = scene.GetSystems(); for (int i = 0; i < systems.Count; i++) + { yield return systems[i]; + } } private static void CollectSubtreeIds( @@ -315,10 +355,14 @@ ISet result _ = result.Add(gameObject.identity.persistentId); IReadOnlyList components = gameObject.GetComponents(); for (int i = 0; i < components.Count; i++) + { _ = result.Add(components[i].identity.persistentId); + } IReadOnlyList children = gameObject.transform.children; for (int i = 0; i < children.Count; i++) + { CollectSubtreeIds(children[i].gameObject, result); + } } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Reloading/SceneReloadIntegration.cs b/src/composition/editor/features/Inno.Editor.Scene/Reloading/SceneReloadIntegration.cs index cfb6b0e4b..03bb3cee5 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Reloading/SceneReloadIntegration.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Reloading/SceneReloadIntegration.cs @@ -1,11 +1,10 @@ -using Inno.Extensibility.Reload; using System; - using Inno.Assets; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; using Inno.Runtime; using Inno.Scene; @@ -55,9 +54,7 @@ public IGenerationChange Capture(AssemblyReloadContext context) ArgumentNullException.ThrowIfNull(context); using IDisposable scope = m_runtimeSession.EnterExecutionScope(); TypeCacheReloadContext typeReload = context.GetContext(); - return new SceneReloadTransaction( - m_runtimeSession, - m_reload.Capture(typeReload)); + return new SceneReloadTransaction(m_runtimeSession, m_reload.Capture(typeReload)); } /// @@ -83,7 +80,9 @@ public void PrepareForActivation() using IDisposable scope = runtimeSession.EnterExecutionScope(); migration.PrepareForActivation(); foreach (object retiredObject in migration.retiredObjects) + { runtimeSession.StopCoroutines(retiredObject); + } } /// @@ -103,8 +102,7 @@ public void Complete() using IDisposable scope = runtimeSession.EnterExecutionScope(); migration.Complete(); SceneStateDiagnosticPublisher.PublishReload(migration.diagnostics); - SceneStateDiagnosticPublisher.PublishMissingElements( - runtimeSession.scenes.loadedScenes); + SceneStateDiagnosticPublisher.PublishMissingElements(runtimeSession.scenes.loadedScenes); } /// @@ -123,8 +121,7 @@ public void RestorePreviousState() { using IDisposable scope = runtimeSession.EnterExecutionScope(); migration.RestorePreviousState(); - SceneStateDiagnosticPublisher.PublishMissingElements( - runtimeSession.scenes.loadedScenes); + SceneStateDiagnosticPublisher.PublishMissingElements(runtimeSession.scenes.loadedScenes); } } @@ -139,7 +136,9 @@ public void Dispose() { IDisposable? current = m_registration; if (current is null) + { return; + } m_registration = null; try { @@ -151,5 +150,4 @@ public void Dispose() } } } - } diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs index 9d1377c5a..6eb070eb5 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs @@ -2,15 +2,16 @@ using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; -using Inno.Extensibility.Modules; using Inno.Core.Logging; using Inno.Core.Settings; using Inno.Editor.Core; +using Inno.Extensibility.Modules; +using Inno.Plugins.Authoring; using Inno.Scripting.Compiler; using Inno.Scripting.Reload; namespace Inno.Editor.Scripting; + /// /// Owns script compilation and activation for one editor project. /// @@ -37,6 +38,7 @@ internal sealed class EditorScripting : EditorModule, IEditorScriptCompilation private bool m_reportedReloadWait; private string? m_activationFailure; private long m_nextRequestId; + internal EditorScripting( AssetPipeline assets, PluginEnvironment plugins, @@ -62,19 +64,24 @@ Func moduleSourceFactory /// Gets whether blocks following updates is enabled for this implementation. /// public override bool blocksFollowingUpdates => m_blockFollowingUpdates; + /// /// Gets whether script compilation is currently active. /// - internal bool isCompiling => m_manager?.isFaulted != true - && (m_showCompilation - || m_compilation is not null - || m_pendingCompletion is not null - || m_manager?.isCompiling == true - || m_manager?.isUnloadVerificationPending == true - || m_manager?.isCompilationPending == true); + internal bool isCompiling + => m_manager?.isFaulted != true + && (m_showCompilation + || m_compilation is not null + || m_pendingCompletion is not null + || m_manager?.isCompiling == true + || m_manager?.isUnloadVerificationPending == true + || m_manager?.isCompilationPending == true); + internal bool isAvailable => m_manager is not null; + /// public bool requiresExclusiveProgress => isCompiling && m_reloads.CanActivateReload(out _); + internal bool canReload => m_manager is not null && !isCompiling && !m_manager.isFaulted && m_reloads.CanRequestReload(out _); /// @@ -86,13 +93,21 @@ public EditorScriptCompilationState state { ScriptReloadHost? manager = m_manager; if (manager is null) + { return EditorScriptCompilationState.Initializing; + } if (manager.isFaulted) + { return EditorScriptCompilationState.Failed; + } if (isCompiling) + { return EditorScriptCompilationState.Compiling; + } if (m_activationFailure is not null) + { return EditorScriptCompilationState.Failed; + } return manager.lastCompilation switch { { success: true } => EditorScriptCompilationState.Ready, @@ -111,14 +126,22 @@ public EditorScriptCompilationProgress progress { ScriptReloadProgress? current = m_manager?.progress; string message = m_activationFailure ?? (!m_reloads.CanActivateReload(out string? reason) - ? reason ?? "Waiting for Play Mode to stop." - : current?.stage ?? "Initializing project scripting."); + ? reason ?? "Waiting for Play Mode to stop." + : current?.stage ?? "Initializing project scripting."); if (m_manager?.isCompilationTakingLong == true && m_activationFailure is null) + { message = $"Long-running compilation ({m_manager.compilationElapsed.TotalSeconds:F1}s). {message}"; - return new(current?.operationId ?? 0, current?.fraction ?? 0f, message, - current?.cancellationRequested ?? false, current?.canCancel ?? false); + } + return new( + current?.operationId ?? 0, + current?.fraction ?? 0f, + message, + current?.cancellationRequested ?? false, + current?.canCancel ?? false + ); } } + /// /// Gets the most recently completed compiler result, which may still await activation and retirement verification. /// @@ -163,13 +186,17 @@ public IScriptCompilationTicket RequestCompilation() internal void ReloadScripting() { if (canReload) + { QueueReload(static manager => manager.RecompileScripting(), supersedeCurrentTicket: true); + } } internal void ReloadPlugins() { if (canReload) + { QueueReload(static manager => manager.ReloadPlugins(), supersedeCurrentTicket: true); + } } /// @@ -179,8 +206,11 @@ internal void ReloadPlugins() public void CancelCompilation(long operationId) { if (m_manager?.progress.operationId == operationId) + { m_manager.CancelCompilation(operationId); + } } + /// /// Initializes this feature when its owning runtime becomes active. /// @@ -189,7 +219,16 @@ public void CancelCompilation(long operationId) /// protected override void OnStart(EditorContext context) { - m_manager = new ScriptReloadHost(new ScriptReloadOptions(), m_compiler, m_assets, m_plugins, m_modules, m_settings, m_reloads, m_moduleSourceFactory); + m_manager = new ScriptReloadHost( + new ScriptReloadOptions(), + m_compiler, + m_assets, + m_plugins, + m_modules, + m_settings, + m_reloads, + m_moduleSourceFactory + ); m_manager.Start(); if (m_manager.TryCompilePending(out Task? compilation)) { @@ -234,7 +273,9 @@ protected override void OnUpdate(EditorContext context) m_reportedReloadWait = false; CompleteCompilation(); if (m_manager is null || m_compilation is not null) + { return; + } if (m_pendingCompletion is not null || m_manager.isUnloadVerificationPending) { AdvanceUnloadVerification(); @@ -242,9 +283,13 @@ protected override void OnUpdate(EditorContext context) } if (m_manager.isFaulted) + { return; + } if (!context.isFocused && !m_explicitReloadPending) + { return; + } if (m_manager.TryCompilePending(out Task? compilation)) { m_explicitReloadPending = false; @@ -261,17 +306,23 @@ protected override void OnUpdate(EditorContext context) /// The context that supplies state and services for this operation. /// protected override void OnStop(EditorContext context) => DisposeManager(); + /// /// Releases resources retained by this feature after it has stopped. /// protected override void OnDispose() => DisposeManager(); + private void CompleteCompilation() { Task? compilation = m_compilation; if (compilation is null || !compilation.IsCompleted || m_manager is null) + { return; + } if (!m_reloads.CanActivateReload(out _)) + { return; + } ScriptCompilationTicket? ticket = m_compilationTicket; try { @@ -289,7 +340,9 @@ private void CompleteCompilation() m_activationFailure = null; ScriptDiagnosticPublisher.ClearReload(); - CompleteAfterRetirement(new PendingCompletion(ticket, result, true, "Script generation compiled, activated, and retired successfully.")); + CompleteAfterRetirement( + new PendingCompletion(ticket, result, true, "Script generation compiled, activated, and retired successfully.") + ); } else { @@ -299,7 +352,14 @@ private void CompleteCompilation() m_blockFollowingUpdates = true; m_activationFailure = null; ScriptDiagnosticPublisher.ClearReload(); - CompleteAfterRetirement(new PendingCompletion(ticket, result, false, "Script compilation failed after a Plugin availability change; unavailable types were " + "preserved as Missing.")); + CompleteAfterRetirement( + new PendingCompletion( + ticket, + result, + false, + "Script compilation failed after a Plugin availability change; unavailable types were " + "preserved as Missing." + ) + ); } else { @@ -318,7 +378,9 @@ private void CompleteCompilation() catch (Exception exception) { if (!m_manager.isFaulted) + { m_plugins.RollbackPending(); + } m_activationFailure = $"Script generation activation failed: {exception.Message}"; ticket?.MarkFailed(ticket.result, $"Script generation activation failed: {exception.Message}"); ScriptDiagnosticPublisher.PublishReloadFailure(exception); @@ -328,7 +390,9 @@ private void CompleteCompilation() { m_compilation = null; m_compilationTicket = null; - m_hideCompilationOnNextUpdate = m_pendingCompletion is null && m_manager?.isUnloadVerificationPending != true && m_manager?.isCompilationPending != true; + m_hideCompilationOnNextUpdate = m_pendingCompletion is null + && m_manager?.isUnloadVerificationPending != true + && m_manager?.isCompilationPending != true; } } @@ -346,11 +410,16 @@ private void CompleteAfterRetirement(PendingCompletion completion) private void FinishCompletion(PendingCompletion completion) { if (completion.succeeded) + { m_assets.CompleteExtensionDiscovery(); + } bool projected = GenerateIdeProjection(); if (completion.succeeded) { - completion.ticket?.MarkSucceeded(completion.result, projected ? completion.status : "Script generation retired successfully, but IDE project generation failed."); + completion.ticket?.MarkSucceeded( + completion.result, + projected ? completion.status : "Script generation retired successfully, but IDE project generation failed." + ); } else { @@ -362,7 +431,9 @@ private void AdvanceUnloadVerification() { ScriptReloadHost? manager = m_manager; if (manager is null || !manager.AdvanceUnloadVerification(out Exception? failure)) + { return; + } PendingCompletion? completion = m_pendingCompletion; m_pendingCompletion = null; if (failure is not null) @@ -383,7 +454,9 @@ private void AdvanceUnloadVerification() ScriptDiagnosticPublisher.ClearUnload(); if (completion is not null) + { FinishCompletion(completion); + } m_hideCompilationOnNextUpdate = true; } @@ -410,9 +483,13 @@ bool supersedeCurrentTicket ) { ScriptReloadHost? manager = m_manager; if (manager is null) + { return; + } if (supersedeCurrentTicket) + { m_currentTicket?.MarkSuperseded(); + } request(manager); m_explicitReloadPending = true; m_hideCompilationOnNextUpdate = false; @@ -423,7 +500,9 @@ private void BeginCompilationTicket() { ScriptCompilationTicket? ticket = m_currentTicket; if (ticket is null || ticket.state != ScriptCompilationTicketState.Queued) + { return; + } m_compilationTicket = ticket; ticket.MarkCompiling("Compiling and validating the requested script generation."); } diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs index 2318d9c19..faa477d6e 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs @@ -1,6 +1,7 @@ using Inno.Scripting.Compiler; namespace Inno.Editor.Scripting; + /// /// Identifies whether the active project script generation can safely start game simulation. /// @@ -46,6 +47,7 @@ public interface IEditorScriptCompilation /// The request observed by the presentation; stale requests have no effect. /// void CancelCompilation(long operationId); + /// /// Queues a fresh cache-aware compilation for a build or simulation workflow. /// @@ -54,6 +56,7 @@ public interface IEditorScriptCompilation /// a faulted host returns a failed ticket and requires restart. /// IScriptCompilationTicket RequestCompilation(); + /// /// Gets the most recently requested compilation ticket, or when no explicit request exists. /// @@ -64,7 +67,6 @@ public interface IEditorScriptCompilation /// EditorScriptCompilationState state { get; } - /// /// Gets the most recently completed compilation, or before the first attempt completes. /// diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicket.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicket.cs index a933117ff..ce650a9ba 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicket.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicket.cs @@ -1,6 +1,5 @@ using System; using System.Threading; - using Inno.Scripting.Compiler; namespace Inno.Editor.Scripting; @@ -45,23 +44,21 @@ string status /// public bool isCompleted => state is ScriptCompilationTicketState.Succeeded - or ScriptCompilationTicketState.Failed - or ScriptCompilationTicketState.Canceled - or ScriptCompilationTicketState.Superseded; + or ScriptCompilationTicketState.Failed + or ScriptCompilationTicketState.Canceled + or ScriptCompilationTicketState.Superseded; internal void MarkCompiling(string status) => Transition(ScriptCompilationTicketState.Compiling, status, result: null); internal void MarkSucceeded( ScriptCompilationResult result, string status - ) - => Transition(ScriptCompilationTicketState.Succeeded, status, result); + ) => Transition(ScriptCompilationTicketState.Succeeded, status, result); internal void MarkFailed( ScriptCompilationResult? result, string status - ) - => Transition(ScriptCompilationTicketState.Failed, status, result); + ) => Transition(ScriptCompilationTicketState.Failed, status, result); internal void MarkCanceled(string status) => Transition(ScriptCompilationTicketState.Canceled, status, result: null); @@ -69,7 +66,8 @@ internal void MarkSuperseded() => Transition( ScriptCompilationTicketState.Superseded, "A newer script compilation request replaced this ticket.", - result: null); + result: null + ); private void Transition( ScriptCompilationTicketState state, @@ -81,12 +79,14 @@ private void Transition( if (current is ScriptCompilationTicketState.Succeeded or ScriptCompilationTicketState.Failed or ScriptCompilationTicketState.Canceled - or ScriptCompilationTicketState.Superseded) - { + or ScriptCompilationTicketState.Superseded + ) { return; } if (result is not null) + { Volatile.Write(ref m_result, result); + } Volatile.Write(ref m_status, status); Volatile.Write(ref m_state, (int)state); } diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicketState.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicketState.cs index c2b0fb152..3ef78b15c 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicketState.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptCompilationTicketState.cs @@ -9,27 +9,22 @@ public enum ScriptCompilationTicketState /// The request is queued behind the active compiler operation. /// Queued, - /// /// The request owns the compiler pipeline or is activating its candidate generation. /// Compiling, - /// /// The request compiled and atomically activated its candidate generation. /// Succeeded, - /// /// Compilation or candidate activation failed without replacing the active generation. /// Failed, - /// /// The request was explicitly canceled before activation. /// Canceled, - /// /// A newer request replaced this request before its candidate could activate. /// diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptDiagnosticPublisher.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptDiagnosticPublisher.cs index f043a3d7e..09e6fa1ce 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptDiagnosticPublisher.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/ScriptDiagnosticPublisher.cs @@ -1,6 +1,5 @@ using System; using System.Linq; - using Inno.Core.Diagnostics; using Inno.Scripting.Compiler; @@ -16,33 +15,25 @@ internal static class ScriptDiagnosticPublisher internal static void PublishCompilation(ScriptCompilationResult result) { ArgumentNullException.ThrowIfNull(result); - Diagnostics.Set( - C_COMPILER_DIAGNOSTICS, - result.diagnostics.Select(CreateCompilationDiagnostic)); + Diagnostics.Set(C_COMPILER_DIAGNOSTICS, result.diagnostics.Select(CreateCompilationDiagnostic)); } internal static void PublishReloadFailure(Exception exception) { ArgumentNullException.ThrowIfNull(exception); - Diagnostics.Set( - C_RELOAD_DIAGNOSTICS, - Diagnostic.Error("INNO-RELOAD", exception.ToString())); + Diagnostics.Set(C_RELOAD_DIAGNOSTICS, Diagnostic.Error("INNO-RELOAD", exception.ToString())); } internal static void PublishIdeProjectionFailure(Exception exception) { ArgumentNullException.ThrowIfNull(exception); - Diagnostics.Set( - C_IDE_PROJECTION_DIAGNOSTICS, - Diagnostic.Warning("INNO-IDE-PROJECTION", exception.ToString())); + Diagnostics.Set(C_IDE_PROJECTION_DIAGNOSTICS, Diagnostic.Warning("INNO-IDE-PROJECTION", exception.ToString())); } internal static void PublishUnloadFailure(Exception exception) { ArgumentNullException.ThrowIfNull(exception); - Diagnostics.Set( - C_UNLOAD_DIAGNOSTICS, - Diagnostic.Error("INNO-ALC-UNLOAD", exception.Message)); + Diagnostics.Set(C_UNLOAD_DIAGNOSTICS, Diagnostic.Error("INNO-ALC-UNLOAD", exception.Message)); } internal static void ClearReload() => Diagnostics.Clear(C_RELOAD_DIAGNOSTICS); @@ -62,30 +53,14 @@ internal static void ClearAll() private static Diagnostic CreateCompilationDiagnostic(ScriptDiagnostic diagnostic) { DiagnosticLocation? location = string.IsNullOrWhiteSpace(diagnostic.filePath) - ? null - : new DiagnosticLocation( - diagnostic.filePath, - diagnostic.line, - diagnostic.column); + ? null + : new DiagnosticLocation(diagnostic.filePath, diagnostic.line, diagnostic.column); return diagnostic.severity switch { - DiagnosticSeverity.Info => Diagnostic.Info( - diagnostic.id, - diagnostic.message, - location), - DiagnosticSeverity.Warning => Diagnostic.Warning( - diagnostic.id, - diagnostic.message, - location), - DiagnosticSeverity.Error => Diagnostic.Error( - diagnostic.id, - diagnostic.message, - location), - _ => Diagnostic.Error( - diagnostic.id, - diagnostic.message, - location) + DiagnosticSeverity.Info => Diagnostic.Info(diagnostic.id, diagnostic.message, location), + DiagnosticSeverity.Warning => Diagnostic.Warning(diagnostic.id, diagnostic.message, location), + DiagnosticSeverity.Error => Diagnostic.Error(diagnostic.id, diagnostic.message, location), + _ => Diagnostic.Error(diagnostic.id, diagnostic.message, location) }; } - } diff --git a/src/composition/editor/features/Inno.Editor.Scripting/ScriptingReloadActions.cs b/src/composition/editor/features/Inno.Editor.Scripting/ScriptingReloadActions.cs index b910234d3..7e07308a0 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/ScriptingReloadActions.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/ScriptingReloadActions.cs @@ -1,6 +1,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Scripting; + [EditorAction(ScriptingInteractionIds.C_RELOAD_SCRIPTING, ScriptingInteractionIds.C_MAIN_MENU_AREA)] [EditorMenu(ScriptingInteractionIds.C_MAIN_MENU_AREA, "Tools/Scripting/Reload Scripts", order: 100)] internal sealed class ReloadScriptingAction(EditorScripting scripting) : EditorAction @@ -14,7 +15,9 @@ internal sealed class ReloadScriptingAction(EditorScripting scripting) : EditorA /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => scripting.canReload ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => scripting.canReload ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -37,7 +40,9 @@ internal sealed class ReloadPluginsAction(EditorScripting scripting) : EditorAct /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => scripting.canReload ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => scripting.canReload ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialAssetCreationTemplate.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialAssetCreationTemplate.cs index 5183619d7..17d62c720 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialAssetCreationTemplate.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialAssetCreationTemplate.cs @@ -11,5 +11,6 @@ namespace Inno.Editor.Shaders; "New Material", groupOrder: 200, itemOrder: 100, - separatorBeforeGroup: true)] + separatorBeforeGroup: true +)] internal sealed class MaterialAssetCreationTemplate : AssetCreationTemplate; diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs index 6829869d1..4648b5c37 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs @@ -4,18 +4,20 @@ using System.Runtime.CompilerServices; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Core.Serialization; using Inno.Core.Graphs; +using Inno.Core.Serialization; using Inno.Editor.Assets; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Rendering; using Inno.Rendering; using Inno.Rendering.Assets; -using Draft = Inno.Editor.Assets.AssetDraftDocuments.Draft; using Inno.Rendering.Assets.Authoring; +using Draft = Inno.Editor.Assets.AssetDraftDocuments.Draft; + namespace Inno.Editor.Shaders; + /// /// Owns Material authoring sessions; native source editing uses the shared asset draft lifecycle. /// @@ -26,6 +28,7 @@ public sealed class MaterialDocuments : EditorModule private readonly AssetDraftDocuments m_documents; private readonly SerializationRegistry m_serialization; private readonly ConditionalWeakTable m_presentations = new(); + /// /// Gets the authoritative asset catalog used by source-aware inspectors. /// @@ -33,6 +36,7 @@ public sealed class MaterialDocuments : EditorModule public AssetPipeline assets { get; } internal readonly EditorInteractions interactions; + /// /// Gets the generation-scoped preview service shared by material presentations. /// @@ -62,6 +66,7 @@ IEditorPreviewService previews /// The persistent identity used for subsequent draft operations. /// public Guid Open(AssetPath path) => m_documents.Open(path); + /// /// Reads a detached current-generation Material; referenced assets remain canonical read-only inputs. /// @@ -72,6 +77,7 @@ IEditorPreviewService previews /// The current unsaved Material value. /// public MaterialAsset Read(Guid assetId) => m_documents.Read(assetId); + /// /// Changes a draft through shared History without modifying its source or Scene/Game. /// @@ -89,6 +95,7 @@ public void Replace( MaterialAsset candidate, string? mergeKey = null ) => m_documents.Replace(assetId, candidate, mergeKey); + /// /// Changes compatible selected drafts within one shared gesture. /// @@ -102,6 +109,7 @@ public void ReplaceMany( IReadOnlyDictionary candidates, string? mergeKey = null ) => m_documents.ReplaceMany(candidates, mergeKey); + /// /// Opens the current source draft without publishing it. /// @@ -113,6 +121,7 @@ public void ReplaceMany( /// [Inno.Scripting.Api.ScriptingApiIgnore] public Draft OpenDraft(AssetPath path) => m_documents.GetDraft(Open(path)); + /// /// Resolves the source draft for a canonical Material identity. /// @@ -126,7 +135,9 @@ public void ReplaceMany( public Draft Open(MaterialAsset material) { if (!assets.TryGetInfo(material.identity.persistentId, out AssetInfo? info) || info is null) + { throw new IOException("The Material source identity is unavailable."); + } return OpenDraft(info.assetPath); } @@ -168,24 +179,31 @@ out string error } error = cache.error; - return cache.graph is null ? new() : ShaderParameterPresentation.Read(cache.graph, propertyId, m_serialization, AssetSerializationContext.Create(assets)); + return cache.graph is null + ? new() + : ShaderParameterPresentation.Read(cache.graph, propertyId, m_serialization, AssetSerializationContext.Create(assets)); } internal void ValidateHistory( EditorHistoryChange change, EditorHistoryDirection direction ) => m_documents.ValidateHistory(change, direction); + internal void ApplyHistory( EditorHistoryChange change, EditorHistoryDirection direction ) => m_documents.ApplyHistory(change, direction); + internal bool TryMergeHistory( EditorHistoryChange older, EditorHistoryChange newer, out EditorHistoryChange? merged ) => m_documents.TryMergeHistory(older, newer, out merged); - internal static bool Recoverable(Exception error) => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException - && Inno.Core.Execution.RetirementPendingException.Find(error) is null; + + internal static bool Recoverable(Exception error) + => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException + && Inno.Core.Execution.RetirementPendingException.Find(error) is null; + /// /// Initializes this feature when its owning runtime becomes active. /// @@ -193,6 +211,7 @@ internal static bool Recoverable(Exception error) => error is IOException or Una /// The context that supplies state and services for this operation. /// protected override void OnStart(EditorContext context) => m_documents.Start(); + /// /// Advances this feature using the current runtime state. /// @@ -200,6 +219,7 @@ internal static bool Recoverable(Exception error) => error is IOException or Una /// The context that supplies state and services for this operation. /// protected override void OnUpdate(EditorContext context) => m_documents.Update(); + /// /// Stops this feature before its owning runtime releases the active generation. /// diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs index 39fe22fa8..b851cfaf2 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs @@ -17,22 +17,27 @@ public sealed class ShaderParameterPresentation : ISerializable /// Gets or sets the Material Inspector section; empty uses the standard Parameters section. /// [SerializableProperty] public string group { get; set; } = ""; + /// /// Gets or sets the hover description without adding a permanent paragraph. /// [SerializableProperty] public string description { get; set; } = ""; + /// /// Gets or sets whether this Material-owned parameter appears in ordinary Material Inspectors. /// [SerializableProperty] public bool visible { get; set; } = true; + /// /// Gets or sets whether a scalar Float control uses the declared editing bounds. /// [SerializableProperty] public bool hasRange { get; set; } + /// /// Gets or sets the inclusive editing minimum; existing values are not changed by presentation metadata. /// [SerializableProperty] public double minimum { get; set; } + /// /// Gets or sets the inclusive editing maximum. /// @@ -64,8 +69,11 @@ SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); return graph.metadata.TryGetValue(C_PREFIX + propertyId.value, out GraphSerializedValue? encoded) - ? serialization.Deserialize(ShaderGraphDocument.Decode(encoded!, serialization, context), context) - : new(); + ? serialization.Deserialize( + ShaderGraphDocument.Decode(encoded!, serialization, context), + context + ) + : new(); } /// @@ -100,9 +108,13 @@ SerializationContext context ArgumentNullException.ThrowIfNull(presentation); if (!propertyId.isValid || !double.IsFinite(presentation.minimum) || !double.IsFinite(presentation.maximum) || presentation.minimum < -float.MaxValue || presentation.maximum > float.MaxValue - || presentation.minimum > presentation.maximum) + || presentation.minimum > presentation.maximum + ) { throw new ArgumentException("Parameter presentation requires a stable identity and finite ordered Float bounds."); - graph.SetMetadata(C_PREFIX + propertyId.value, - ShaderGraphDocument.Encode(serialization.Serialize(presentation, context), serialization, context)); + } + graph.SetMetadata( + C_PREFIX + propertyId.value, + ShaderGraphDocument.Encode(serialization.Serialize(presentation, context), serialization, context) + ); } } diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Nodes/ShaderInspectionSelection.cs b/src/composition/editor/features/Inno.Editor.Shaders/Nodes/ShaderInspectionSelection.cs index 03fefb781..76836b97a 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Nodes/ShaderInspectionSelection.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Nodes/ShaderInspectionSelection.cs @@ -11,6 +11,7 @@ namespace Inno.Editor.Shaders; public sealed class ShaderInspectionSelection { private readonly GraphNodeId[] m_nodes; + /// /// Creates a neutral Inspector selection separate from the Asset Browser's navigation. /// @@ -25,15 +26,19 @@ public ShaderInspectionSelection( IEnumerable nodes ) { if (assetId == Guid.Empty) + { throw new ArgumentException("A persistent shader identity is required.", nameof(assetId)); + } ArgumentNullException.ThrowIfNull(nodes); this.assetId = assetId; m_nodes = nodes.Distinct().OrderBy(static node => node.value, StringComparer.Ordinal).ToArray(); } + /// /// Gets the persistent shader identity. /// public Guid assetId { get; } + /// /// Gets selected stable node identities. /// diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs index 816236c42..10d17cd8d 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs @@ -20,7 +20,8 @@ public sealed class ShaderPreviewProviderAttribute(string contractId) : Attribut /// Gets the non-empty Shader contract consumed by this preview. /// public string contractId { get; } = string.IsNullOrWhiteSpace(contractId) - ? throw new ArgumentException("A preview contract is required.", nameof(contractId)) : contractId; + ? throw new ArgumentException("A preview contract is required.", nameof(contractId)) + : contractId; } /// @@ -79,37 +80,46 @@ public ShaderPreviewContext( int pixelHeight ) { if (!resourceId.isValid) + { throw new ArgumentException("A resource identity is required.", nameof(resourceId)); + } ArgumentNullException.ThrowIfNull(material); ArgumentNullException.ThrowIfNull(artifact); ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(diagnostics); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); this.resourceId = resourceId; this.material = material; this.artifact = artifact; this.definition = definition; this.diagnostics = diagnostics; this.pixelWidth = pixelWidth; this.pixelHeight = pixelHeight; } + /// /// Gets the publication scope released by the host when this preview closes. /// public RenderPersistentResourceId resourceId { get; } + /// /// Gets the invocation-local Material values. /// public MaterialAsset material { get; } + /// /// Gets the complete immutable GPU candidate. /// public RenderShaderArtifact artifact { get; } + /// /// Gets the candidate's exact contract, not the latest uncompiled source interface. /// public ShaderDefinition definition { get; } + /// /// Gets the host-owned, isolated diagnostic producer. /// public IDiagnosticReporter diagnostics { get; } + /// /// Gets target width in physical pixels. /// public int pixelWidth { get; } + /// /// Gets target height in physical pixels. /// diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs index 9b7bf5bf9..bdb316f92 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs @@ -1,5 +1,4 @@ using System.Numerics; - using Inno.Scripting.Api; namespace Inno.Editor.Core; @@ -88,9 +87,11 @@ public void Draw(EditorContext context) Vector2 availableContentSize ) { System.ArgumentNullException.ThrowIfNull(context); - if (!float.IsFinite(availableContentSize.X) || !float.IsFinite(availableContentSize.Y) || - availableContentSize.X <= 0f || availableContentSize.Y <= 0f) + if (!float.IsFinite(availableContentSize.X) || !float.IsFinite(availableContentSize.Y) + || availableContentSize.X <= 0f || availableContentSize.Y <= 0f + ) { throw new System.ArgumentOutOfRangeException(nameof(availableContentSize)); + } return OnPrepare(context, availableContentSize); } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModalAttribute.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModalAttribute.cs index b5fc20406..581c6c61c 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModalAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModalAttribute.cs @@ -29,9 +29,13 @@ public EditorModalAttribute( int order = 0 ) { if (string.IsNullOrWhiteSpace(id)) + { throw new ArgumentException("An editor modal identifier is required.", nameof(id)); + } if (string.IsNullOrWhiteSpace(title)) + { throw new ArgumentException("An editor modal title is required.", nameof(title)); + } this.id = id; this.title = title; this.order = order; diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs index 6d5494b39..2d3531cd5 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Execution; using Inno.Scripting.Api; @@ -48,7 +47,9 @@ public void Start(EditorContext context) ArgumentNullException.ThrowIfNull(context); ObjectDisposedException.ThrowIf(m_disposed, this); if (m_started) + { throw new InvalidOperationException($"Editor module '{GetType().FullName}' is already started."); + } m_context = context; m_started = true; OnStart(context); @@ -76,7 +77,9 @@ public void Update(EditorContext context) ArgumentNullException.ThrowIfNull(context); ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_active) + { throw new InvalidOperationException($"Editor module '{GetType().FullName}' is not started."); + } OnUpdate(context); } @@ -104,7 +107,9 @@ public void Stop(EditorContext context) ArgumentNullException.ThrowIfNull(context); ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_started) + { return; + } m_active = false; try { @@ -130,9 +135,7 @@ public void Stop(EditorContext context) /// /// The shared editor context for the active runtime. /// - protected virtual void OnStart(EditorContext context) - { - } + protected virtual void OnStart(EditorContext context) {} /// /// Runs once per editor frame before views are drawn. @@ -140,9 +143,7 @@ protected virtual void OnStart(EditorContext context) /// /// The shared editor context containing the current frame state. /// - protected virtual void OnUpdate(EditorContext context) - { - } + protected virtual void OnUpdate(EditorContext context) {} /// /// Runs before the module generation is released and its disposable instances are destroyed. @@ -154,9 +155,7 @@ protected virtual void OnUpdate(EditorContext context) /// /// The shared editor context for the runtime being stopped. /// - protected virtual void OnStop(EditorContext context) - { - } + protected virtual void OnStop(EditorContext context) {} /// /// Captures readable project state owned by this module. @@ -169,9 +168,7 @@ protected virtual void OnStop(EditorContext context) /// /// The writable parameter that receives the complete readable state for this module. /// - protected virtual void Capture(EditorState state) - { - } + protected virtual void Capture(EditorState state) {} /// /// Restores readable project state owned by this module. @@ -184,22 +181,20 @@ protected virtual void Capture(EditorState state) /// The read-only state parameter for this module. Missing or incompatible values return the /// fallback supplied to . /// - protected virtual void Restore(EditorState state) - { - } + protected virtual void Restore(EditorState state) {} /// /// Releases resources owned by this module after it has stopped and left the active extension /// generation. /// - protected virtual void OnDispose() - { - } + protected virtual void OnDispose() {} void IDisposable.Dispose() { if (m_disposed) + { return; + } if (m_context is not null) { try diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModuleAttribute.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModuleAttribute.cs index f45f45085..75945b9d5 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModuleAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModuleAttribute.cs @@ -26,7 +26,9 @@ public EditorModuleAttribute( int order = 0 ) { if (string.IsNullOrWhiteSpace(id)) + { throw new ArgumentException("An editor module identifier is required.", nameof(id)); + } this.id = id; this.order = order; } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs index 93ecfbd86..a369f3bcd 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs @@ -1,7 +1,5 @@ - using System; using System.Numerics; - using Inno.Core.Execution; using Inno.Scripting.Api; @@ -57,7 +55,9 @@ public void Attach(EditorContext context) { ArgumentNullException.ThrowIfNull(context); if (m_attached) + { throw new InvalidOperationException($"Editor panel '{GetType().FullName}' is already attached."); + } m_attached = true; OnAttach(context); m_ready = true; @@ -83,7 +83,9 @@ public void Detach(EditorContext context) { ArgumentNullException.ThrowIfNull(context); if (!m_attached) + { return; + } m_ready = false; try { @@ -118,7 +120,9 @@ public void Draw(EditorContext context) { ArgumentNullException.ThrowIfNull(context); if (!m_ready) + { throw new InvalidOperationException($"Editor panel '{GetType().FullName}' is not attached."); + } OnDraw(context); } @@ -136,9 +140,7 @@ public void Draw(EditorContext context) /// /// The shared editor context for the active runtime. /// - protected virtual void OnAttach(EditorContext context) - { - } + protected virtual void OnAttach(EditorContext context) {} /// /// Runs before the panel is detached from its active extension generation. @@ -150,9 +152,7 @@ protected virtual void OnAttach(EditorContext context) /// /// The shared editor context for the runtime being detached. /// - protected virtual void OnDetach(EditorContext context) - { - } + protected virtual void OnDetach(EditorContext context) {} /// /// Captures readable project state owned by this panel. @@ -165,9 +165,7 @@ protected virtual void OnDetach(EditorContext context) /// /// The writable parameter that receives the complete readable state for this panel. /// - protected virtual void Capture(EditorState state) - { - } + protected virtual void Capture(EditorState state) {} /// /// Restores readable project state owned by this panel. @@ -180,7 +178,5 @@ protected virtual void Capture(EditorState state) /// The read-only state parameter for this panel. Missing or incompatible values return the /// fallback supplied to . /// - protected virtual void Restore(EditorState state) - { - } + protected virtual void Restore(EditorState state) {} } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanelAttribute.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanelAttribute.cs index b0225d029..4574d6605 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanelAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanelAttribute.cs @@ -42,9 +42,13 @@ public EditorPanelAttribute( bool separatorBefore = false ) { if (string.IsNullOrWhiteSpace(id)) + { throw new ArgumentException("An editor panel identifier is required.", nameof(id)); + } if (string.IsNullOrWhiteSpace(title)) + { throw new ArgumentException("An editor panel title is required.", nameof(title)); + } this.id = id; this.title = title; this.order = order; @@ -86,16 +90,16 @@ public EditorPanelAttribute( private static string NormalizeMenuPath(string path) { if (string.IsNullOrWhiteSpace(path)) + { return string.Empty; + } string[] segments = path.Split('/'); for (int i = 0; i < segments.Length; i++) { segments[i] = segments[i].Trim(); if (segments[i].Length == 0) { - throw new ArgumentException( - "An editor panel menu path cannot contain an empty segment.", - nameof(path)); + throw new ArgumentException("An editor panel menu path cannot contain an empty segment.", nameof(path)); } } return string.Join('/', segments); diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorTypeSpecificity.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorTypeSpecificity.cs index 9cdc7b9ab..8e78776db 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorTypeSpecificity.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorTypeSpecificity.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.Core; + /// /// Ranks assignable editor extension targets by class ancestry, with interface registrations one step away. /// @@ -48,7 +49,9 @@ out int distance while (current is not null) { if (current == candidateType) + { return true; + } distance++; current = current.BaseType; } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Properties/ScriptingApi.cs b/src/composition/editor/framework/Inno.Editor.Core/Properties/ScriptingApi.cs index 694a08389..2a7edcd6b 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Properties/ScriptingApi.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Core; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Core", "Inno.Editor.Core", ScriptingApiScope.Editor)] diff --git a/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs b/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs index 98bb6de13..c79a4c950 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System.Diagnostics; using System.Runtime.ExceptionServices; - -using Inno.Extensibility.Modules; using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Scripting.Reload; @@ -85,9 +84,9 @@ public IDisposable Register(IEditorReloadParticipant participant) { RemoveCollectedParticipants(); var registration = new Registration(this, Guid.NewGuid(), participant); - m_participants.Add(new ParticipantReference( - registration.id, - new WeakReference(participant))); + m_participants.Add( + new ParticipantReference(registration.id, new WeakReference(participant)) + ); return registration; } } @@ -116,7 +115,9 @@ public IAssemblyUnloadProbe Execute( ) { ArgumentNullException.ThrowIfNull(reload); if (!CanActivateReload(out string? reason)) + { throw new InvalidOperationException(reason ?? "An editor owner still prevents generation activation."); + } IGenerationChange[] transactions = CaptureTransactions(reload.context); var publication = new EditorPublication(reload, externalChange); return reload.generations.Execute("editor assembly reload", publication, [publication, .. transactions]); @@ -142,7 +143,8 @@ public void RefreshDiagnostics() Trace.TraceError( "Editor reload participant '{0}' failed to refresh diagnostics: {1}", participant.GetType().FullName, - exception); + exception + ); } } } @@ -167,7 +169,9 @@ private List GetParticipants() foreach (ParticipantReference reference in m_participants) { if (reference.participant.TryGetTarget(out IEditorReloadParticipant? participant)) + { participants.Add(participant); + } } } return participants; @@ -184,8 +188,8 @@ out string? reason foreach (GuardReference reference in m_guards) { if (reference.guard.TryGetTarget(out IEditorReloadGuard? guard) - && !(manualRequest ? guard.canRequestReload : guard.canActivateReload)) - { + && !(manualRequest ? guard.canRequestReload : guard.canActivateReload) + ) { reason = guard.blockingReason ?? "Stop Play Mode before reloading scripts or Plugins."; return false; } @@ -198,8 +202,7 @@ out string? reason private sealed class EditorPublication( AssemblyReloadSession reload, IGenerationChange? external - ) - : IGenerationPublication, IGenerationChange + ) : IGenerationPublication, IGenerationChange { /// /// Publishes candidate assemblies before their external asset and settings generation. @@ -219,10 +222,14 @@ public void Activate() public IAssemblyUnloadProbe Complete() => reload.Complete(); void IGenerationChange.PrepareForActivation() => external?.PrepareForActivation(); - void IGenerationChange.Apply() { } + + void IGenerationChange.Apply() {} + void IGenerationChange.Complete() => external?.Complete(); + void IGenerationChange.RollbackStructure() => external?.RollbackStructure(); - void IGenerationChange.RestorePreviousState() { } + + void IGenerationChange.RestorePreviousState() {} /// /// Restores old assemblies and external resolvers before domains restore their previous property values. @@ -255,17 +262,19 @@ public void Rollback() failures.Add(exception); } if (failures.Count > 0) + { throw new AggregateException("Editor publication rollback was incomplete.", failures); + } } } private sealed class ParticipantChange( IEditorReloadParticipant participant, AssemblyReloadContext context - ) - : IGenerationChange + ) : IGenerationChange { private IGenerationChange? m_change; + /// /// Prepares candidate state without changing the active generation. /// @@ -275,10 +284,12 @@ public void PrepareForActivation() ?? throw new InvalidOperationException($"Editor reload participant '{participant.GetType().FullName}' returned no change."); m_change.PrepareForActivation(); } + /// /// Applies the prepared state at the caller-controlled commit point. /// public void Apply() => m_change!.Apply(); + /// /// Completes the committed operation and releases temporary state. /// @@ -287,10 +298,12 @@ public void Complete() m_change!.Complete(); m_change = null; } + /// /// Restores the state that existed before candidate activation began. /// public void RollbackStructure() => m_change?.RollbackStructure(); + /// /// Restores the state that existed before candidate activation began. /// @@ -304,7 +317,9 @@ public void RestorePreviousState() private void Unregister(Guid registrationId) { lock (m_sync) + { m_participants.RemoveAll(reference => reference.id == registrationId); + } } private readonly record struct ParticipantReference( @@ -332,9 +347,13 @@ public void Dispose() { IEditorReloadGuard? retained = m_guard; if (retained is null) + { return; + } lock (owner.m_sync) + { owner.m_guards.RemoveAll(reference => reference.id == id); + } m_guard = null; GC.KeepAlive(retained); } @@ -364,7 +383,9 @@ IEditorReloadParticipant participant public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; IEditorReloadParticipant? participant = m_participant; m_participant = null; diff --git a/src/composition/editor/framework/Inno.Editor.Core/Reloading/IEditorReloadParticipant.cs b/src/composition/editor/framework/Inno.Editor.Core/Reloading/IEditorReloadParticipant.cs index 91b2a191a..bb8e833f2 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Reloading/IEditorReloadParticipant.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Reloading/IEditorReloadParticipant.cs @@ -1,5 +1,5 @@ -using Inno.Extensibility.Reload; using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; namespace Inno.Editor.Core; diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs index c52027aa5..ce6ceae03 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; - using Inno.Scripting.Api; namespace Inno.Editor.Core; @@ -44,7 +43,9 @@ public EditorContext( string? initialLayoutDocument = null ) { if (string.IsNullOrWhiteSpace(projectDirectory)) + { throw new ArgumentException("A project directory is required.", nameof(projectDirectory)); + } ArgumentNullException.ThrowIfNull(keyboard); this.keyboard = keyboard; this.projectDirectory = Path.GetFullPath(projectDirectory); @@ -115,8 +116,7 @@ public EditorContext( public bool TryGetLayoutSection( string sectionName, out IReadOnlyDictionary values - ) - => layout.TryGetSection(sectionName, out values); + ) => layout.TryGetSection(sectionName, out values); /// /// Adds or replaces one human-readable editor layout section in memory. @@ -137,8 +137,7 @@ out IReadOnlyDictionary values public void SetLayoutSection( string sectionName, IEnumerable> values - ) - => layout.SetSection(sectionName, values); + ) => layout.SetSection(sectionName, values); /// /// Removes one editor layout section from the in-memory document. @@ -200,5 +199,4 @@ IEnumerable> values /// Gets whether any editor viewport currently owns application focus. /// public bool isFocused => frame.isFocused; - } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorKeyboardPolicy.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorKeyboardPolicy.cs index c0c6211e1..3adbe2a95 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorKeyboardPolicy.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorKeyboardPolicy.cs @@ -25,7 +25,9 @@ public EditorKeyboardPolicy( string superModifierLabel ) { if (primaryModifier is not (KeyModifier.Control or KeyModifier.Super or KeyModifier.Alt)) + { throw new ArgumentException("A primary shortcut requires one Control, Super or Alt modifier.", nameof(primaryModifier)); + } ArgumentException.ThrowIfNullOrWhiteSpace(superModifierLabel); this.primaryModifier = primaryModifier; this.superModifierLabel = superModifierLabel; diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorLayoutSettings.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorLayoutSettings.cs index 03d5bf18f..34f55078d 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorLayoutSettings.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorLayoutSettings.cs @@ -57,7 +57,9 @@ internal string imguiLayout get { lock (m_sync) + { return m_imguiLayout; + } } } @@ -125,7 +127,9 @@ internal void SetImGuiLayout(string? layout) { Parse(layout ?? string.Empty, out string parsedLayout, out _); lock (m_sync) + { m_imguiLayout = parsedLayout; + } } /// @@ -155,7 +159,9 @@ IEnumerable> values } lock (m_sync) + { m_sections[sectionName] = replacement; + } } /// @@ -174,7 +180,9 @@ internal bool RemoveSection(string sectionName) { ValidateSectionName(sectionName); lock (m_sync) + { return m_sections.Remove(sectionName); + } } /// @@ -189,7 +197,9 @@ internal bool SaveIfChanged() { string document = Compose(m_imguiLayout, m_sections); if (string.Equals(document, m_lastSavedDocument, StringComparison.Ordinal)) + { return false; + } WriteDocument(document); return true; } @@ -201,7 +211,9 @@ internal bool SaveIfChanged() internal void Save() { lock (m_sync) + { WriteDocument(Compose(m_imguiLayout, m_sections)); + } } private void WriteDocument(string document) @@ -213,9 +225,13 @@ private void WriteDocument(string document) private string ReadDocument(string? initialDocument) { if (File.Exists(m_path)) + { return File.ReadAllText(m_path); + } if (initialDocument is null) + { return string.Empty; + } try { AtomicFile.WriteAllBytes(m_path, Encoding.UTF8.GetBytes(initialDocument), overwrite: false); @@ -246,17 +262,23 @@ out Dictionary> sections } if (line.StartsWith("[", StringComparison.Ordinal)) + { currentEditorSection = null; + } if (currentEditorSection is not null) { int separator = line.IndexOf('='); if (separator <= 0) + { continue; + } string key = line[..separator].Trim(); string value = line[(separator + 1)..].Trim(); if (IsValidKey(key) && IsValidValue(value)) + { currentEditorSection[key] = value; + } continue; } @@ -273,7 +295,9 @@ IReadOnlyDictionary> sections var builder = new StringBuilder(); string normalizedLayout = NormalizeLayout(layout); if (normalizedLayout.Length > 0) + { builder.Append(normalizedLayout).AppendLine().AppendLine(); + } string[] names = sections.Keys.OrderBy(static name => name, StringComparer.Ordinal).ToArray(); for (int sectionIndex = 0; sectionIndex < names.Length; sectionIndex++) @@ -282,9 +306,13 @@ IReadOnlyDictionary> sections builder.Append(C_SECTION_PREFIX).Append(name).AppendLine("]"); Dictionary section = sections[name]; foreach (KeyValuePair pair in OrderValues(section)) + { builder.Append(pair.Key).Append('=').AppendLine(pair.Value); + } if (sectionIndex + 1 < names.Length) + { builder.AppendLine(); + } } return builder.ToString(); } @@ -296,9 +324,9 @@ private static bool TryParseEditorSectionHeader( string line, out string sectionName ) { - if (line.StartsWith(C_SECTION_PREFIX, StringComparison.Ordinal) && - line.EndsWith(']')) - { + if (line.StartsWith(C_SECTION_PREFIX, StringComparison.Ordinal) + && line.EndsWith(']') + ) { sectionName = line[C_SECTION_PREFIX.Length..^1]; return IsValidSectionName(sectionName); } @@ -313,7 +341,8 @@ private static void ValidateSectionName(string sectionName) { throw new ArgumentException( "Editor settings section names cannot contain brackets or line breaks.", - nameof(sectionName)); + nameof(sectionName) + ); } } @@ -324,7 +353,8 @@ private static void ValidateKey(string key) { throw new ArgumentException( "Editor settings keys cannot contain an equals sign or line break.", - nameof(key)); + nameof(key) + ); } } @@ -333,24 +363,22 @@ private static void ValidateValue(string value) ArgumentNullException.ThrowIfNull(value); if (!IsValidValue(value)) { - throw new ArgumentException( - "Editor settings values cannot contain line breaks.", - nameof(value)); + throw new ArgumentException("Editor settings values cannot contain line breaks.", nameof(value)); } } private static bool IsValidSectionName(string value) - => !string.IsNullOrWhiteSpace(value) && - value.IndexOfAny(['[', ']', '\r', '\n']) < 0; + => !string.IsNullOrWhiteSpace(value) + && value.IndexOfAny(['[', ']', '\r', '\n']) < 0; private static bool IsValidKey(string value) - => !string.IsNullOrWhiteSpace(value) && - value.IndexOfAny(['=', '\r', '\n']) < 0; + => !string.IsNullOrWhiteSpace(value) + && value.IndexOfAny(['=', '\r', '\n']) < 0; private static bool IsValidValue(string value) => value.IndexOfAny(['\r', '\n']) < 0; private static string NormalizeLayout(string? layout) => string.IsNullOrWhiteSpace(layout) - ? string.Empty - : layout.TrimEnd('\r', '\n'); + ? string.Empty + : layout.TrimEnd('\r', '\n'); } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorState.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorState.cs index ffce7cd7c..ad3998985 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorState.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorState.cs @@ -16,9 +16,7 @@ public abstract class EditorState /// /// Initializes the base contract for a runtime-owned editor state parameter. /// - protected EditorState() - { - } + protected EditorState() {} /// /// Reads a compatible value or returns the caller-provided fallback. diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs index 4b46f6946..90f67809f 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs @@ -124,9 +124,13 @@ public EditorStatistic( int order = 0 ) { if (!id.isValid) + { throw new ArgumentException("A statistic ID is required.", nameof(id)); + } if (!groupId.isValid) + { throw new ArgumentException("A statistic group ID is required.", nameof(groupId)); + } ArgumentException.ThrowIfNullOrWhiteSpace(groupName); ArgumentException.ThrowIfNullOrWhiteSpace(label); ArgumentException.ThrowIfNullOrWhiteSpace(value); @@ -206,7 +210,9 @@ public void Publish(EditorStatistic statistic) { EditorStatistic? previous = m_current.GetValueOrDefault(statistic.id) ?? m_completed.GetValueOrDefault(statistic.id); if (previous is null || !SameValue(previous, statistic)) + { m_snapshotDirty = true; + } m_current[statistic.id] = statistic; } } @@ -224,7 +230,9 @@ public void Publish(IEnumerable statistics) { ArgumentNullException.ThrowIfNull(statistics); foreach (EditorStatistic statistic in statistics) + { Publish(statistic); + } } /// @@ -240,10 +248,14 @@ public IReadOnlyList GetSnapshot() lock (m_sync) { if (!m_snapshotDirty && m_snapshot is not null) + { return m_snapshot; + } var merged = new Dictionary(m_completed); foreach ((EditorStatisticId id, EditorStatistic statistic) in m_current) + { merged[id] = statistic; + } EditorStatistic[] values = merged.Values .OrderBy(static value => value.groupOrder) .ThenBy(static value => value.groupName, StringComparer.OrdinalIgnoreCase) @@ -264,7 +276,9 @@ internal void AdvanceFrame() foreach (EditorStatisticId id in m_completed.Keys) { if (m_current.ContainsKey(id)) + { continue; + } m_snapshotDirty = true; break; } @@ -277,10 +291,10 @@ private static bool SameValue( EditorStatistic first, EditorStatistic second ) => ReferenceEquals(first, second) - || first.groupId == second.groupId - && first.groupOrder == second.groupOrder - && first.order == second.order - && string.Equals(first.groupName, second.groupName, StringComparison.Ordinal) - && string.Equals(first.label, second.label, StringComparison.Ordinal) - && string.Equals(first.value, second.value, StringComparison.Ordinal); + || first.groupId == second.groupId + && first.groupOrder == second.groupOrder + && first.order == second.order + && string.Equals(first.groupName, second.groupName, StringComparison.Ordinal) + && string.Equals(first.label, second.label, StringComparison.Ordinal) + && string.Equals(first.value, second.value, StringComparison.Ordinal); } diff --git a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsole.cs b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsole.cs index d34efea5a..aaa2c6f88 100644 --- a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsole.cs +++ b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsole.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading; - using Inno.Core.Diagnostics; using Inno.Core.Logging; using Inno.Editor.PlayMode; @@ -61,7 +60,9 @@ public int capacity get { lock (m_sync) + { return m_capacity; + } } set { @@ -69,7 +70,9 @@ public int capacity { int normalized = Math.Max(16, value); if (normalized == m_capacity) + { return; + } m_capacity = normalized; TrimLogsUnsafe(); m_revision++; @@ -93,7 +96,9 @@ public void Start() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_started) + { return; + } IDisposable subscription = m_playMode.ListenStateChanges(OnPlayModeStateChanged); try { @@ -138,7 +143,9 @@ public void Replace(DiagnosticReport report) ArgumentNullException.ThrowIfNull(report); var entries = new EditorConsoleOccurrence[report.diagnostics.Count]; for (int i = 0; i < entries.Length; i++) + { entries[i] = FromDiagnostic(NextSequence(), report, report.diagnostics[i]); + } lock (m_sync) { m_diagnostics[report.source.id] = entries; @@ -157,7 +164,9 @@ public void Clear(DiagnosticSource source) lock (m_sync) { if (m_diagnostics.Remove(source.id)) + { m_revision++; + } } } @@ -192,7 +201,9 @@ public void Clear() lock (m_sync) { if (m_logs.Count == 0) + { return; + } m_logs.Clear(); m_revision++; } @@ -204,7 +215,9 @@ public void Clear() public void Dispose() { if (m_disposed) + { return; + } if (m_started) { m_playModeSubscription?.Dispose(); @@ -219,7 +232,9 @@ public void Dispose() private void OnPlayModeStateChanged(EditorPlayModeState state) { if (state == EditorPlayModeState.Compiling && clearOnPlay) + { ClearLogsForPlay(); + } } private void ClearLogsForPlay() @@ -228,7 +243,9 @@ private void ClearLogsForPlay() lock (m_sync) { if (m_logs.Count == 0) + { return; + } m_logs.Clear(); m_revision++; } @@ -237,22 +254,22 @@ private void ClearLogsForPlay() private static EditorConsoleOccurrence FromLog( long sequence, LogEntry entry - ) - => new( - sequence, - EditorConsoleEntryKind.Log, - entry.level, - $"{entry.domain}/{entry.scope}", - string.Empty, - string.Empty, - entry.category, - entry.message, - entry.time, - entry.file, - entry.line, - 0, - entry.stackTrace, - entry.sessionId); + ) => new( + sequence, + EditorConsoleEntryKind.Log, + entry.level, + $"{entry.domain}/{entry.scope}", + string.Empty, + string.Empty, + entry.category, + entry.message, + entry.time, + entry.file, + entry.line, + 0, + entry.stackTrace, + entry.sessionId + ); private static EditorConsoleOccurrence FromDiagnostic( long sequence, @@ -280,7 +297,8 @@ Diagnostic diagnostic location?.line ?? 0, location?.column ?? 0, string.Empty, - LogSessionId.none); + LogSessionId.none + ); } private long NextSequence() => Interlocked.Increment(ref m_nextSequence); @@ -288,6 +306,8 @@ Diagnostic diagnostic private void TrimLogsUnsafe() { while (m_logs.Count > m_capacity) + { _ = m_logs.Dequeue(); + } } } diff --git a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleEntryKind.cs b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleEntryKind.cs index 1f5e488a3..31e11a4f1 100644 --- a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleEntryKind.cs +++ b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleEntryKind.cs @@ -9,7 +9,6 @@ public enum EditorConsoleEntryKind /// The occurrence was emitted through the runtime logging pipeline. /// Log, - /// /// The occurrence represents current state from a diagnostic producer. /// diff --git a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleOccurrence.cs b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleOccurrence.cs index abdf44300..4264310ee 100644 --- a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleOccurrence.cs +++ b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleOccurrence.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Logging; namespace Inno.Editor.Diagnostics; diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs index 565f4377d..2d2c65d42 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using Inno.Core.Graphs; using Inno.Editor.Interactions; @@ -60,7 +60,9 @@ public void SetViewport( float zoom ) { if (!float.IsFinite(pan.x) || !float.IsFinite(pan.y)) + { throw new ArgumentOutOfRangeException(nameof(pan)); + } if (!float.IsFinite(zoom)) { throw new ArgumentOutOfRangeException(nameof(zoom)); diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs index 648a7df84..1a67f38ee 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs @@ -36,8 +36,11 @@ public sealed class GraphClipboardData public sealed class GraphDocumentController { private readonly Identity m_identity; - private GraphDocumentSession session => m_identity.Resolve() - ?? throw new InvalidOperationException("The Graph document controller belongs to a closed identity generation."); + + private GraphDocumentSession session + => m_identity.Resolve() + ?? throw new InvalidOperationException("The Graph document controller belongs to a closed identity generation."); + private readonly IEditorHistory m_history; private readonly SerializationRegistry m_serialization; @@ -101,7 +104,11 @@ public void ReplaceDocument( ArgumentNullException.ThrowIfNull(replacement); ArgumentException.ThrowIfNullOrWhiteSpace(historyName); GraphDocument snapshot = replacement.Clone(); - Mutate(historyName, gestureId is null ? null : $"graph:{documentId}:document:{gestureId}", () => document.ReplaceContents(snapshot)); + Mutate( + historyName, + gestureId is null ? null : $"graph:{documentId}:document:{gestureId}", + () => document.ReplaceContents(snapshot) + ); } /// @@ -199,7 +206,8 @@ public void MoveNodes(IReadOnlyDictionary positions) { document.FindNode(id)!.position = position; } - }); + } + ); } /// @@ -289,7 +297,8 @@ public void SetNodeValue( Mutate( "Edit Node Property", gestureId is null ? null : $"graph:{documentId}:value:{nodeId.value}:{propertyId}:{gestureId}", - () => node.SetValue(propertyId, value.Clone())); + () => node.SetValue(propertyId, value.Clone()) + ); } /// @@ -339,8 +348,8 @@ public GraphClipboardData Copy(IEnumerable nodeIds) } foreach (GraphEdgeRecord edge in document.edges.Where( - edge => selected.Contains(edge.output.nodeId) && selected.Contains(edge.input.nodeId))) - { + edge => selected.Contains(edge.output.nodeId) && selected.Contains(edge.input.nodeId) + )) { fragment.AddEdge(new GraphEdgeRecord(edge.id, edge.output, edge.input)); } @@ -382,17 +391,21 @@ public IReadOnlyList Paste( GraphNodeRecord clone = CloneNode( source, remap[source.id], - new GraphPosition(source.position.x + offset.x, source.position.y + offset.y)); + new GraphPosition(source.position.x + offset.x, source.position.y + offset.y) + ); remapNode?.Invoke(clone, remap); document.AddNode(clone); } foreach (GraphEdgeRecord edge in fragment.edges) { - document.AddEdge(new GraphEdgeRecord( - NewEdgeId(), - new GraphEndpoint(remap[edge.output.nodeId], edge.output.portId), - new GraphEndpoint(remap[edge.input.nodeId], edge.input.portId))); + document.AddEdge( + new GraphEdgeRecord( + NewEdgeId(), + new GraphEndpoint(remap[edge.output.nodeId], edge.output.portId), + new GraphEndpoint(remap[edge.input.nodeId], edge.input.portId) + ) + ); } }); return fragment.nodes.Select(node => remap[node.id]).ToArray(); @@ -441,7 +454,7 @@ Action mutation private GraphNodeRecord RequireNode(GraphNodeId nodeId) => document.FindNode(nodeId) - ?? throw new ArgumentException($"Node '{nodeId}' is not present in '{documentId}'.", nameof(nodeId)); + ?? throw new ArgumentException($"Node '{nodeId}' is not present in '{documentId}'.", nameof(nodeId)); private static GraphNodeRecord CloneNode( GraphNodeRecord source, @@ -458,5 +471,6 @@ GraphPosition position } private static GraphNodeId NewNodeId() => new(Guid.NewGuid().ToString("N")); + private static GraphEdgeId NewEdgeId() => new(Guid.NewGuid().ToString("N")); } diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphEditorModule.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphEditorModule.cs index 141aeb2df..863e26e49 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphEditorModule.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphEditorModule.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Core.Identity; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Reload; -using Inno.References; using Inno.Core.Graphs; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.References; namespace Inno.Editor.Graph; @@ -60,14 +60,18 @@ public GraphDocumentController OpenDocument( IEditorHistory history ) { if (documentId == Guid.Empty) + { throw new ArgumentException("A graph document requires a persistent identity.", nameof(documentId)); + } ArgumentNullException.ThrowIfNull(document); ArgumentNullException.ThrowIfNull(history); GraphDocumentSession? session = m_identities.Get(documentId); if (session is null) { if (m_documents.Count >= C_DOCUMENT_CAPACITY) + { throw new InvalidOperationException("Graph document capacity has been reached; close unused documents explicitly."); + } session = new GraphDocumentSession(document); m_identities.Register(session, documentId); m_documents.Add(documentId); @@ -90,7 +94,9 @@ public bool CloseDocument(Guid documentId) { GraphDocumentSession? session = m_identities.Get(documentId); if (session is null) + { return false; + } m_identities.Unregister(session); m_documents.Remove(documentId); m_ownedSessions.Remove(session); @@ -157,7 +163,9 @@ public void RebindDocument( GraphDocument document ) { if (documentId == Guid.Empty) + { throw new ArgumentException("A graph document requires a persistent identity.", nameof(documentId)); + } ArgumentNullException.ThrowIfNull(document); GraphDocumentSession? session = m_identities.Get(documentId); if (session is null) @@ -210,7 +218,9 @@ protected override void OnDispose() { GraphDocumentSession? session = m_identities.Get(id); if (session is not null) + { m_identities.Unregister(session); + } } m_documents.Clear(); m_ownedSessions.Clear(); @@ -219,7 +229,7 @@ protected override void OnDispose() IGenerationChange IEditorReloadParticipant.Capture(AssemblyReloadContext context) => new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], [new Recovery(this)]); - void IEditorReloadParticipant.RefreshDiagnostics() { } + void IEditorReloadParticipant.RefreshDiagnostics() {} private sealed class Recovery(GraphEditorModule owner) : IReferenceRecoveryParticipant { @@ -234,20 +244,33 @@ public void PrepareForActivation() foreach (Guid id in owner.m_documents) { GraphDocumentSession session = owner.m_identities.Get(id)!; - m_previous.Add(id, new State(GraphDocumentCodec.Encode(session.document, owner.m_serialization), - session.revision, session.isDirty, session.available)); + m_previous.Add( + id, + new State( + GraphDocumentCodec.Encode(session.document, owner.m_serialization), + session.revision, + session.isDirty, + session.available + ) + ); } } + /// /// Applies the prepared state at the caller-controlled commit point. /// public void Apply() { foreach ((Guid id, State state) in m_previous) + { m_candidate.Add(id, GraphDocumentCodec.Decode(state.bytes, owner.m_serialization)); + } foreach ((Guid id, GraphDocument document) in m_candidate) + { owner.m_identities.Get(id)!.document = document; + } } + /// /// Rejects any recovery that changes captured nodes, edges, properties or order. /// @@ -257,10 +280,18 @@ public void Apply() public void Validate(IReadOnlyList changes) { foreach ((Guid id, State state) in m_previous) - if (!state.bytes.AsSpan().SequenceEqual(GraphDocumentCodec.Encode( - owner.m_identities.Get(id)!.document, owner.m_serialization))) + { + if (!state.bytes.AsSpan().SequenceEqual( + GraphDocumentCodec.Encode( + owner.m_identities.Get(id)!.document, + owner.m_serialization + ) + )) { throw new InvalidOperationException("Graph recovery changed neutral authored content."); + } + } } + /// /// Completes the committed operation and releases temporary state. /// @@ -269,10 +300,12 @@ public void Complete() m_previous.Clear(); m_candidate.Clear(); } + /// /// Restores the state that existed before candidate activation began. /// public void RollbackStructure() => m_candidate.Clear(); + /// /// Restores the state that existed before candidate activation began. /// @@ -289,6 +322,7 @@ public void RestorePreviousState() } Complete(); } + private sealed record State( byte[] bytes, ulong revision, diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs index da803d55c..2e02fb7fe 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs @@ -26,8 +26,7 @@ internal static class GraphHistoryDocumentCodec public static byte[] Encode( GraphDocument document, SerializationRegistry serialization - ) - => GraphDocumentCodec.Encode(document, serialization); + ) => GraphDocumentCodec.Encode(document, serialization); /// /// Decodes deterministic structured data into a validated value. @@ -44,8 +43,7 @@ SerializationRegistry serialization public static GraphDocument Decode( ReadOnlySpan bytes, SerializationRegistry serialization - ) - => GraphDocumentCodec.Decode(bytes, serialization); + ) => GraphDocumentCodec.Decode(bytes, serialization); } internal sealed record GraphHistoryData( @@ -58,6 +56,7 @@ long timestamp /// The c kind value used as part of this type's public representation. /// public const string C_KIND = "editor.graph.document"; + private static readonly UTF8Encoding S_UTF8 = new(false, true); /// @@ -134,7 +133,9 @@ SerializationRegistry serialization int idLength = ReadLength(payload, ref offset); Guid id = Guid.ParseExact(S_UTF8.GetString(ReadSlice(payload, ref offset, idLength)), "D"); if (id == Guid.Empty) + { throw new InvalidDataException("Graph history requires a persistent document identity."); + } int beforeLength = ReadLength(payload, ref offset); byte[] before = ReadSlice(payload, ref offset, beforeLength).ToArray(); int afterLength = ReadLength(payload, ref offset); @@ -209,22 +210,24 @@ EditorHistoryDirection direction ) { try { - GraphHistoryData data = GraphHistoryData.Decode( - change.payload.ReadBytes(), - module.serialization); + GraphHistoryData data = GraphHistoryData.Decode(change.payload.ReadBytes(), module.serialization); if (!module.TryResolve(data.documentId, out GraphDocumentSession? session) || session is null) { return new GraphHistoryTransitionResult( EditorHistoryResult.Failure($"Graph document '{data.documentId}' is not open."), - false); + false + ); } GraphDocument original = session.document.Clone(); try { - session.document.ReplaceContents(GraphHistoryDocumentCodec.Decode( - direction == EditorHistoryDirection.Undo ? data.before : data.after, - module.serialization)); + session.document.ReplaceContents( + GraphHistoryDocumentCodec.Decode( + direction == EditorHistoryDirection.Undo ? data.before : data.after, + module.serialization + ) + ); session.revision++; session.isDirty = true; return new GraphHistoryTransitionResult(EditorHistoryResult.Success(), false); @@ -239,8 +242,10 @@ EditorHistoryDirection direction { return new GraphHistoryTransitionResult( EditorHistoryResult.Failure( - $"Graph transition failed: {exception.Message} Rollback failed: {rollbackException.Message}"), - true); + $"Graph transition failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ), + true + ); } return new GraphHistoryTransitionResult(EditorHistoryResult.Failure(exception.Message), false); @@ -250,7 +255,8 @@ EditorHistoryDirection direction { return new GraphHistoryTransitionResult( EditorHistoryResult.Failure($"Graph History payload is invalid: {exception.Message}"), - false); + false + ); } } } @@ -282,12 +288,10 @@ EditorHistoryDirection direction _ = direction; try { - GraphHistoryData data = GraphHistoryData.Decode( - change.payload.ReadBytes(), - module.serialization); + GraphHistoryData data = GraphHistoryData.Decode(change.payload.ReadBytes(), module.serialization); return module.TryResolve(data.documentId, out _) - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable($"Graph document '{data.documentId}' is not open."); + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable($"Graph document '{data.documentId}' is not open."); } catch (Exception exception) { @@ -318,8 +322,8 @@ EditorHistoryDirection direction _ = context; GraphHistoryTransitionResult transition = GraphHistoryTransition.Apply(module, change, direction); return transition.stateIntegrityLost - ? StateIntegrityFailure(transition.result.message) - : transition.result; + ? StateIntegrityFailure(transition.result.message) + : transition.result; } /// @@ -350,27 +354,20 @@ out EditorHistoryChange? merged try { - GraphHistoryData previous = GraphHistoryData.Decode( - older.payload.ReadBytes(), - module.serialization); - GraphHistoryData current = GraphHistoryData.Decode( - newer.payload.ReadBytes(), - module.serialization); + GraphHistoryData previous = GraphHistoryData.Decode(older.payload.ReadBytes(), module.serialization); + GraphHistoryData current = GraphHistoryData.Decode(newer.payload.ReadBytes(), module.serialization); if (previous.documentId != current.documentId - || Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > 1.0) - { + || Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > 1.0 + ) { return false; } - var combined = new GraphHistoryData( - previous.documentId, - previous.before, - current.after, - current.timestamp); + var combined = new GraphHistoryData(previous.documentId, previous.before, current.after, current.timestamp); merged = new EditorHistoryChange( GraphHistoryData.C_KIND, EditorHistoryPayload.FromBytes(combined.Encode()), - older.mergeKey); + older.mergeKey + ); return true; } catch diff --git a/src/composition/editor/framework/Inno.Editor.Graph/Properties/ScriptingApi.cs b/src/composition/editor/framework/Inno.Editor.Graph/Properties/ScriptingApi.cs index 25911c73e..d34bf1b37 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/Properties/ScriptingApi.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Graph; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Graph", "Inno.Editor.Graph", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(GraphEditorModule), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs index 26ac1188f..e26cacf9a 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections; using System.Globalization; @@ -7,9 +6,12 @@ using Inno.Editor.Annotations; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [InspectorAttributeDrawer(typeof(HeaderAttribute))] internal sealed class HeaderInspectorAttributeDrawer : IInspectorAttributeDrawer { @@ -131,7 +133,11 @@ internal sealed class ShowIfInspectorAttributeDrawer : IInspectorAttributeDrawer public void Update(InspectorAttributeDrawContext context) { var condition = (ShowIfAttribute)context.attribute; - context.isVisible &= InspectorConditionEvaluator.Evaluate(context.GetSiblingValue(condition.memberName), condition.condition, condition.expectedValue); + context.isVisible &= InspectorConditionEvaluator.Evaluate( + context.GetSiblingValue(condition.memberName), + condition.condition, + condition.expectedValue + ); } } @@ -147,7 +153,11 @@ internal sealed class HideIfInspectorAttributeDrawer : IInspectorAttributeDrawer public void Update(InspectorAttributeDrawContext context) { var condition = (HideIfAttribute)context.attribute; - context.isVisible &= !InspectorConditionEvaluator.Evaluate(context.GetSiblingValue(condition.memberName), condition.condition, condition.expectedValue); + context.isVisible &= !InspectorConditionEvaluator.Evaluate( + context.GetSiblingValue(condition.memberName), + condition.condition, + condition.expectedValue + ); } } @@ -165,11 +175,11 @@ public void DrawBefore(InspectorAttributeDrawContext context) var help = (HelpBoxAttribute)context.attribute; if (!string.IsNullOrWhiteSpace(help.conditionMember) && !InspectorConditionEvaluator.Evaluate( - context.GetSiblingValue(help.conditionMember), - help.condition, - help.expectedValue - )) - { + context.GetSiblingValue(help.conditionMember), + help.condition, + help.expectedValue + ) + ) { return; } @@ -177,7 +187,8 @@ public void DrawBefore(InspectorAttributeDrawContext context) { InspectorMessageType.Warning => EditorPalette.warning, InspectorMessageType.Error => EditorPalette.error, - _ => new System.Numerics.Vector4(0.42f, 0.66f, 0.88f, EditorPalette.opacityOpaque)}; + _ => new System.Numerics.Vector4(0.42f, 0.66f, 0.88f, EditorPalette.opacityOpaque) + }; string icon = help.messageType switch { InspectorMessageType.Warning => ImGuiIcon.TriangleExclamation, @@ -205,7 +216,8 @@ internal static bool Evaluate( InspectorCondition.NotNull => value is not null, InspectorCondition.Assigned => IsAssigned(value), InspectorCondition.NotAssigned => !IsAssigned(value), - _ => throw new ArgumentOutOfRangeException(nameof(condition), condition, "Unknown Inspector condition.")}; + _ => throw new ArgumentOutOfRangeException(nameof(condition), condition, "Unknown Inspector condition.") + }; } private static bool IsTruthy(object? value) @@ -223,9 +235,15 @@ private static bool IsTruthy(object? value) private static bool IsAssigned(object? value) { if (value is null) + { return false; - PropertyInfo? property = value.GetType().GetProperty("isAssigned", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - return property?.PropertyType == typeof(bool) && property.GetIndexParameters().Length == 0 ? (bool)(property.GetValue(value) ?? false) : true; + } + PropertyInfo? property = value + .GetType() + .GetProperty("isAssigned", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + return property?.PropertyType == typeof(bool) && property.GetIndexParameters().Length == 0 + ? (bool)(property.GetValue(value) ?? false) + : true; } private static bool AreEqual( @@ -233,24 +251,21 @@ private static bool AreEqual( object? expected ) { if (Equals(value, expected)) + { return true; + } if (value is null || expected is null) + { return false; + } Type valueType = value.GetType(); try { - object converted = valueType.IsEnum ? expected is string name ? Enum.Parse( - valueType, - name, - ignoreCase: false - ) : Enum.ToObject( - valueType, - expected - ) : Convert.ChangeType( - expected, - valueType, - CultureInfo.InvariantCulture - ); + object converted = valueType.IsEnum + ? expected is string name + ? Enum.Parse(valueType, name, ignoreCase: false) + : Enum.ToObject(valueType, expected) + : Convert.ChangeType(expected, valueType, CultureInfo.InvariantCulture); return Equals(value, converted); } catch (Exception exception) when (exception is ArgumentException or InvalidCastException or FormatException or OverflowException) diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/IInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/IInspectorAttributeDrawer.cs index 24f29349f..5e45c9b07 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/IInspectorAttributeDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/IInspectorAttributeDrawer.cs @@ -11,9 +11,7 @@ public interface IInspectorAttributeDrawer /// /// Mutable presentation state for the annotated property. /// - void Update(InspectorAttributeDrawContext context) - { - } + void Update(InspectorAttributeDrawContext context) {} /// /// Draws a decorator immediately before the property row. @@ -21,9 +19,7 @@ void Update(InspectorAttributeDrawContext context) /// /// Current presentation state for the annotated property. /// - void DrawBefore(InspectorAttributeDrawContext context) - { - } + void DrawBefore(InspectorAttributeDrawContext context) {} /// /// Draws a decorator immediately after the property row. @@ -31,7 +27,5 @@ void DrawBefore(InspectorAttributeDrawContext context) /// /// Current presentation state for the annotated property. /// - void DrawAfter(InspectorAttributeDrawContext context) - { - } + void DrawAfter(InspectorAttributeDrawContext context) {} } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawContext.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawContext.cs index 3b463b045..644732c00 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawContext.cs @@ -23,8 +23,8 @@ bool isReadOnly this.member = member ?? throw new ArgumentNullException(nameof(member)); this.property = property; this.path = string.IsNullOrWhiteSpace(path) - ? throw new ArgumentException("The property path is required.", nameof(path)) - : path; + ? throw new ArgumentException("The property path is required.", nameof(path)) + : path; this.label = label ?? throw new ArgumentNullException(nameof(label)); this.isReadOnly = isReadOnly; } @@ -99,25 +99,31 @@ bool isReadOnly public object? GetSiblingValue(string memberName) { ArgumentException.ThrowIfNullOrWhiteSpace(memberName); - const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | - BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public + | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; for (Type? type = owner.GetType(); type is not null && type != typeof(object); type = type.BaseType) { FieldInfo? field = type.GetField(memberName, flags); if (field is not null) + { return field.GetValue(owner); + } PropertyInfo? candidate = type.GetProperty(memberName, flags); if (candidate is null) + { continue; + } if (candidate.GetIndexParameters().Length != 0 || candidate.GetGetMethod(true) is null) { throw new InvalidOperationException( - $"Inspector condition member '{type.FullName}.{memberName}' is not readable."); + $"Inspector condition member '{type.FullName}.{memberName}' is not readable." + ); } return candidate.GetValue(owner); } throw new InvalidOperationException( - $"Inspector condition member '{owner.GetType().FullName}.{memberName}' does not exist."); + $"Inspector condition member '{owner.GetType().FullName}.{memberName}' does not exist." + ); } internal void SelectAttribute(Attribute value) => m_attribute = value ?? throw new ArgumentNullException(nameof(value)); diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerAttribute.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerAttribute.cs index 370109030..cef004ca9 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerAttribute.cs @@ -27,7 +27,9 @@ public InspectorAttributeDrawerAttribute( ) { ArgumentNullException.ThrowIfNull(targetType); if (!typeof(Attribute).IsAssignableFrom(targetType)) + { throw new ArgumentException($"'{targetType.FullName}' is not an attribute type.", nameof(targetType)); + } this.targetType = targetType; this.useForChildren = useForChildren; this.priority = priority; diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerRegistry.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerRegistry.cs index 37d1b688c..820be4194 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerRegistry.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorAttributeDrawerRegistry.cs @@ -42,29 +42,26 @@ IEnumerable drawerServices internal void Update( InspectorAttributeDrawContext context, IReadOnlyList attributes - ) - => Apply(context, attributes, static ( - drawer, - value - ) => drawer.Update(value)); + ) => Apply(context, attributes, static ( + drawer, + value + ) => drawer.Update(value)); internal void DrawBefore( InspectorAttributeDrawContext context, IReadOnlyList attributes - ) - => Apply(context, attributes, static ( - drawer, - value - ) => drawer.DrawBefore(value)); + ) => Apply(context, attributes, static ( + drawer, + value + ) => drawer.DrawBefore(value)); internal void DrawAfter( InspectorAttributeDrawContext context, IReadOnlyList attributes - ) - => Apply(context, attributes, static ( - drawer, - value - ) => drawer.DrawAfter(value)); + ) => Apply(context, attributes, static ( + drawer, + value + ) => drawer.DrawAfter(value)); private void Apply( InspectorAttributeDrawContext context, @@ -76,7 +73,9 @@ Action callback Attribute attribute = attributes[index]; IInspectorAttributeDrawer? drawer = m_registry.Resolve(attribute.GetType()); if (drawer is null) + { continue; + } context.SelectAttribute(attribute); callback(drawer, context); } @@ -98,14 +97,17 @@ internal AttributeTypeRegistry( TypeCatalog types, SerializationRegistry serialization, IEnumerable services - ) - : base(types) + ) : base(types) { m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); ArgumentNullException.ThrowIfNull(services); - m_services = services.Select(static service => service ?? throw new ArgumentException( - "Inspector attribute drawer services cannot contain null.", nameof(services))).ToArray(); + m_services = services.Select(static service => ( + service ?? throw new ArgumentException( + "Inspector attribute drawer services cannot contain null.", + nameof(services) + ) + )).ToArray(); } internal IInspectorAttributeDrawer? Resolve(Type attributeType) @@ -115,14 +117,16 @@ IEnumerable services foreach (Registration registration in current) { if (!DrawerTypeUtility.TryGetDistance( - attributeType, - registration.targetType, - registration.useForChildren, - out int distance)) + attributeType, + registration.targetType, + registration.useForChildren, + out int distance + )) { continue; - if (best is null || distance < bestDistance || - distance == bestDistance && registration.priority > best.priority) - { + } + if (best is null || distance < bestDistance + || distance == bestDistance && registration.priority > best.priority + ) { best = registration; bestDistance = distance; } @@ -144,23 +148,26 @@ protected override Registration[] Build(TypeCacheSnapshot types) var drawers = new Dictionary(); var registrations = new List(); foreach (Type drawerType in types.GetTypesWithAttribute() - .Select(typeRef => typeRef.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal)) - { + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { IInspectorAttributeDrawer drawer = drawers.TryGetValue(drawerType, out IInspectorAttributeDrawer? existing) - ? existing - : OwnCandidateExtension(CreateDrawer(drawerType, types)); + ? existing + : OwnCandidateExtension(CreateDrawer(drawerType, types)); drawers[drawerType] = drawer; foreach (InspectorAttributeDrawerAttribute attribute in - drawerType.GetCustomAttributes(false)) - { + drawerType.GetCustomAttributes(false) + ) { EnsureNoConflict(registrations, attribute, drawerType); - registrations.Add(new Registration( - attribute.targetType, - attribute.useForChildren, - attribute.priority, - drawerType, - drawer)); + registrations.Add( + new Registration( + attribute.targetType, + attribute.useForChildren, + attribute.priority, + drawerType, + drawer + ) + ); } } return registrations.ToArray(); @@ -180,11 +187,13 @@ private IInspectorAttributeDrawer CreateDrawer( TypeCacheSnapshot types ) { ConstructorInfo[] constructors = drawerType.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); if (constructors.Length != 1) { throw new InvalidOperationException( - $"Inspector attribute drawer '{drawerType.FullName}' must declare exactly one constructor."); + $"Inspector attribute drawer '{drawerType.FullName}' must declare exactly one constructor." + ); } ParameterInfo[] parameters = constructors[0].GetParameters(); var arguments = new object?[parameters.Length]; @@ -204,17 +213,20 @@ TypeCacheSnapshot types { 1 => matches[0], 0 => throw new InvalidOperationException( - $"Inspector attribute drawer '{drawerType.FullName}' requests unavailable service " + - $"'{parameterType.FullName}'."), + $"Inspector attribute drawer '{drawerType.FullName}' requests unavailable service " + + $"'{parameterType.FullName}'." + ), _ => throw new InvalidOperationException( - $"Inspector attribute drawer '{drawerType.FullName}' requests ambiguous service " + - $"'{parameterType.FullName}'.") + $"Inspector attribute drawer '{drawerType.FullName}' requests ambiguous service " + + $"'{parameterType.FullName}'." + ) }; } return constructors[0].Invoke(arguments) as IInspectorAttributeDrawer ?? throw new InvalidOperationException( - $"Inspector attribute drawer '{drawerType.FullName}' does not implement " + - $"'{typeof(IInspectorAttributeDrawer).FullName}'."); + $"Inspector attribute drawer '{drawerType.FullName}' does not implement " + + $"'{typeof(IInspectorAttributeDrawer).FullName}'." + ); } } @@ -228,8 +240,9 @@ Type drawerType if (existing.targetType == attribute.targetType && existing.priority == attribute.priority) { throw new InvalidOperationException( - $"Inspector attribute drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + - $"conflict for '{attribute.targetType.FullName}'."); + $"Inspector attribute drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + + $"conflict for '{attribute.targetType.FullName}'." + ); } } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs index 69292130d..97e9bebb1 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs @@ -8,8 +8,9 @@ namespace Inno.Editor.Inspection; internal static class InspectorMemberMetadata { - private const BindingFlags C_DECLARED_MEMBERS = BindingFlags.Instance | BindingFlags.Public | - BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + private const BindingFlags C_DECLARED_MEMBERS = BindingFlags.Instance | BindingFlags.Public + | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + private static readonly ConditionalWeakTable S_MEMBERS = new(); private static readonly ConditionalWeakTable S_ATTRIBUTES = new(); @@ -38,9 +39,10 @@ private static Attribute[] BuildAttributes(MemberInfo member) ) => new OrderedAttribute( attribute, attribute is Inno.Editor.Annotations.InspectorPresentationAttribute presentation - ? presentation.order - : 0, - index)) + ? presentation.order + : 0, + index + )) .OrderBy(static value => value.order) .ThenBy(static value => value.index) .Select(static value => value.attribute) @@ -59,14 +61,18 @@ internal TypeMembers(Type runtimeType) { var hierarchy = new Stack(); for (Type? type = runtimeType; type is not null && type != typeof(object); type = type.BaseType) + { hierarchy.Push(type); + } var result = new Dictionary(StringComparer.Ordinal); while (hierarchy.Count > 0) { foreach (MemberInfo member in hierarchy.Pop().GetMembers(C_DECLARED_MEMBERS)) { if (member is FieldInfo or PropertyInfo) + { result[member.Name] = member; + } } } members = result; diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs index 561a43b2e..4e37481c1 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs @@ -1,8 +1,10 @@ -using Inno.Editor.ImGui; using System; +using Inno.Editor.ImGui; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [InspectionDrawer(typeof(object), useForChildren: true, priority: int.MinValue)] internal sealed class DefaultInspectionDrawer : InspectionDrawer { @@ -27,6 +29,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, object target ) => (target.GetType().Name, null); + /// /// Renders the header presentation for the current editor frame. /// @@ -40,6 +43,7 @@ protected override void DrawHeader( InspectionDrawContext context, object target ) => Ui.Text(target.GetType().FullName ?? target.GetType().Name); + /// /// Renders the value presentation for the current editor frame. /// diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawContext.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawContext.cs index ea60a692c..464267306 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawContext.cs @@ -1,11 +1,10 @@ using System; - -using Inno.Editor.Core; -using Inno.Editor.Interactions; -using Inno.Core.Serialization; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; +using Inno.Core.Serialization; +using Inno.Editor.Core; +using Inno.Editor.Interactions; namespace Inno.Editor.Inspection; @@ -16,6 +15,7 @@ public sealed class InspectionDrawContext { private readonly InspectionDrawerRegistry m_drawers; private readonly IReadOnlyList m_serializedProperties; + /// /// Gets the shared editor context. /// @@ -49,14 +49,15 @@ public bool TryDrawInline(object target) { ArgumentNullException.ThrowIfNull(target); if (!m_drawers.TryResolveExact( - editorContext, - target, - properties, - out IInspectionDrawer? drawer, - out InspectionDrawContext? context) + editorContext, + target, + properties, + out IInspectionDrawer? drawer, + out InspectionDrawContext? context + ) || drawer is null - || context is null) - { + || context is null + ) { return false; } drawer.Draw(context); @@ -96,9 +97,10 @@ public T GetProperty(string propertyName) SerializedProperty property = RequireProperty(propertyName); object? value = property.GetValue(); return value is T typed - ? typed - : throw new InvalidOperationException( - $"Property '{propertyName}' does not contain '{typeof(T).FullName}'."); + ? typed + : throw new InvalidOperationException( + $"Property '{propertyName}' does not contain '{typeof(T).FullName}'." + ); } /// @@ -110,11 +112,7 @@ public T GetProperty(string propertyName) public void DrawProperty(string propertyName) { SerializedProperty property = RequireProperty(propertyName); - properties.Draw( - editorContext, - target, - $"inline.{RuntimeHelpers.GetHashCode(target)}", - property); + properties.Draw(editorContext, target, $"inline.{RuntimeHelpers.GetHashCode(target)}", property); } /// @@ -131,14 +129,11 @@ public void DrawProperties() "inspection.", target.GetType().FullName ?? target.GetType().Name, ".", - RuntimeHelpers.GetHashCode(target).ToString("x8")); + RuntimeHelpers.GetHashCode(target).ToString("x8") + ); for (int index = 0; index < m_serializedProperties.Count; index++) { - properties.Draw( - editorContext, - target, - ownerPath, - m_serializedProperties[index]); + properties.Draw(editorContext, target, ownerPath, m_serializedProperties[index]); } } @@ -147,8 +142,9 @@ private SerializedProperty RequireProperty(string propertyName) ArgumentException.ThrowIfNullOrWhiteSpace(propertyName); return m_serializedProperties.FirstOrDefault(property => string.Equals(property.name, propertyName, StringComparison.Ordinal)) - ?? throw new InvalidOperationException( - $"Target '{target.GetType().FullName}' has no visible serialized property '{propertyName}'."); + ?? throw new InvalidOperationException( + $"Target '{target.GetType().FullName}' has no visible serialized property '{propertyName}'." + ); } internal InspectionDrawContext( @@ -165,6 +161,6 @@ IReadOnlyList serializedProperties this.properties = properties ?? throw new ArgumentNullException(nameof(properties)); m_drawers = drawers ?? throw new ArgumentNullException(nameof(drawers)); m_serializedProperties = serializedProperties - ?? throw new ArgumentNullException(nameof(serializedProperties)); + ?? throw new ArgumentNullException(nameof(serializedProperties)); } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs index 2a7e99f01..c4d756753 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs @@ -80,8 +80,7 @@ TTarget target protected virtual void DrawHeader( InspectionDrawContext context, TTarget target - ) { - } + ) {} /// /// Draws the target-specific Inspector body below the shared target header. @@ -97,25 +96,22 @@ protected abstract void Draw( TTarget target ); - string IInspectionDrawer.GetIcon(InspectionDrawContext context) - => GetIcon(context, GetTarget(context)); + string IInspectionDrawer.GetIcon(InspectionDrawContext context) => GetIcon(context, GetTarget(context)); - (string name, Action? setter) IInspectionDrawer.BindName( - InspectionDrawContext context) + (string name, Action? setter) IInspectionDrawer.BindName(InspectionDrawContext context) => BindName(context, GetTarget(context)); - void IInspectionDrawer.DrawHeader(InspectionDrawContext context) - => DrawHeader(context, GetTarget(context)); + void IInspectionDrawer.DrawHeader(InspectionDrawContext context) => DrawHeader(context, GetTarget(context)); - void IInspectionDrawer.Draw(InspectionDrawContext context) - => Draw(context, GetTarget(context)); + void IInspectionDrawer.Draw(InspectionDrawContext context) => Draw(context, GetTarget(context)); private static TTarget GetTarget(InspectionDrawContext context) { ArgumentNullException.ThrowIfNull(context); return context.target as TTarget ?? throw new InvalidOperationException( - $"Inspector drawer for '{typeof(TTarget).FullName}' cannot draw target " + - $"'{context.target.GetType().FullName}'."); + $"Inspector drawer for '{typeof(TTarget).FullName}' cannot draw target " + + $"'{context.target.GetType().FullName}'." + ); } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerRegistry.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerRegistry.cs index b6707f32c..ac435ebc9 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerRegistry.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawerRegistry.cs @@ -2,11 +2,10 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; +using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; -using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Editor.Inspection; @@ -95,7 +94,8 @@ out InspectionDrawContext? context target, renderer, this, - GetProperties(target)); + GetProperties(target) + ); return true; } @@ -146,14 +146,15 @@ out InspectionDrawContext? context target, renderer, this, - GetProperties(target)); + GetProperties(target) + ); return true; } private IReadOnlyList GetProperties(object target) => target is ISerializable serializable - ? m_serialization.GetProperties(serializable) - : Array.Empty(); + ? m_serialization.GetProperties(serializable) + : Array.Empty(); /// /// Releases every active drawer snapshot and unregisters the registry from type refreshes. @@ -170,8 +171,7 @@ internal InspectionTypeRegistry( EditorInteractions interactions, InspectionDrawerFactory factory, TypeCatalog types - ) - : base(types) + ) : base(types) { this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); m_factory = factory ?? throw new ArgumentNullException(nameof(factory)); @@ -188,28 +188,40 @@ TypeCatalog types foreach (Registration registration in current) { if (exactOnly && registration.targetType != targetType) + { continue; + } if (!DrawerTypeUtility.TryGetDistance( - targetType, - registration.targetType, - registration.useForChildren, - out int distance)) + targetType, + registration.targetType, + registration.useForChildren, + out int distance + )) { continue; + } if (!registration.drawer.CanInspect(target)) - continue; - if (best is null || distance < bestDistance || - distance == bestDistance && registration.priority > best.priority) { + continue; + } + if (best is null || distance < bestDistance + || distance == bestDistance && registration.priority > best.priority + ) { best = registration; bestDistance = distance; ambiguous = null; } else if (distance == bestDistance && registration.priority == best.priority - && registration.drawerType != best.drawerType) + && registration.drawerType != best.drawerType + ) { ambiguous = registration; + } } if (ambiguous is not null) - throw new InvalidOperationException($"Inspector drawers '{best!.drawerType.FullName}' and '{ambiguous.drawerType.FullName}' both accept '{targetType.FullName}' at equal specificity and priority."); + { + throw new InvalidOperationException( + $"Inspector drawers '{best!.drawerType.FullName}' and '{ambiguous.drawerType.FullName}' both accept '{targetType.FullName}' at equal specificity and priority." + ); + } return best?.drawer; } @@ -229,31 +241,35 @@ protected override Registration[] Build(TypeCacheSnapshot types) var drawers = new Dictionary(); var registrations = new List(); foreach (Type drawerType in types.GetTypesWithAttribute() - .Select(typeRef => typeRef.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal)) - { + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { IInspectionDrawer drawer = drawers.TryGetValue(drawerType, out IInspectionDrawer? existing) - ? existing - : OwnCandidateExtension(m_factory(drawerType)); + ? existing + : OwnCandidateExtension(m_factory(drawerType)); if (!drawerType.IsInstanceOfType(drawer)) { throw new InvalidOperationException( - $"Inspection drawer factory returned '{drawer.GetType().FullName}' for " + - $"'{drawerType.FullName}'."); + $"Inspection drawer factory returned '{drawer.GetType().FullName}' for " + + $"'{drawerType.FullName}'." + ); } drawers[drawerType] = drawer; foreach (InspectionDrawerAttribute attribute in - drawerType.GetCustomAttributes(false)) - { + drawerType.GetCustomAttributes(false) + ) { EnsureNoConflict(registrations, attribute, drawerType); - registrations.Add(new Registration( - attribute.targetType, - attribute.useForChildren, - attribute.priority, - attribute.conditional, - drawerType, - drawer)); + registrations.Add( + new Registration( + attribute.targetType, + attribute.useForChildren, + attribute.priority, + attribute.conditional, + drawerType, + drawer + ) + ); } } return registrations.ToArray(); @@ -277,11 +293,12 @@ Type drawerType foreach (Registration existing in registrations) { if (existing.targetType == attribute.targetType && existing.priority == attribute.priority - && (existing.drawerType == drawerType || !existing.conditional || !attribute.conditional)) - { + && (existing.drawerType == drawerType || !existing.conditional || !attribute.conditional) + ) { throw new InvalidOperationException( - $"Inspector drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + - $"conflict for '{attribute.targetType.FullName}'."); + $"Inspector drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + + $"conflict for '{attribute.targetType.FullName}'." + ); } } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/Properties/ScriptingApi.cs b/src/composition/editor/framework/Inno.Editor.Inspection/Properties/ScriptingApi.cs index a81860133..075744195 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/Properties/ScriptingApi.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Inspection; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Inspection", "Inno.Editor.Inspection", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(InspectionDrawer<>), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/BooleanPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/BooleanPropertyDrawer.cs index 8040d4c5c..9379c0aaa 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/BooleanPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/BooleanPropertyDrawer.cs @@ -1,6 +1,7 @@ using EditorUI = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(bool))] internal sealed class BooleanPropertyDrawer : IPropertyDrawer { diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/CollectionPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/CollectionPropertyDrawer.cs index 7f5fca8b7..8ec495c5e 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/CollectionPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/CollectionPropertyDrawer.cs @@ -1,13 +1,15 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using Inno.Core.Serialization; using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(IEnumerable<>), useForChildren: true, priority: -20)] [PropertyDrawer(typeof(IDictionary<, >), useForChildren: true, priority: 20)] [PropertyDrawer(typeof(IReadOnlyDictionary<, >), useForChildren: true, priority: 20)] @@ -60,12 +62,17 @@ Type elementType break; } - context.DrawChild($"Element {index}", elementType, () => EditorCollectionUtility.EnumerateSequence(context.GetValue())[index], value => - { - List updated = EditorCollectionUtility.EnumerateSequence(context.GetValue()); - updated[index] = value; - context.SetValue(EditorCollectionUtility.BuildSequence(context.propertyType, elementType, updated)); - }); + context.DrawChild( + $"Element {index}", + elementType, + () => EditorCollectionUtility.EnumerateSequence(context.GetValue())[index], + value => + { + List updated = EditorCollectionUtility.EnumerateSequence(context.GetValue()); + updated[index] = value; + context.SetValue(EditorCollectionUtility.BuildSequence(context.propertyType, elementType, updated)); + } + ); } Ui.TreePop(); @@ -175,8 +182,11 @@ Type valueType private static List> EnumerateMap(PropertyDrawContext context) { - if (EditorCollectionUtility.TryEnumerateMap(context.GetValue(), context.propertyType, out List> entries)) - { + if (EditorCollectionUtility.TryEnumerateMap( + context.GetValue(), + context.propertyType, + out List> entries + )) { return entries; } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/DrawerTypeUtility.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/DrawerTypeUtility.cs index 06b93e3d8..4b2fc8200 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/DrawerTypeUtility.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/DrawerTypeUtility.cs @@ -16,9 +16,9 @@ out int distance if (normalizedRegistered.IsGenericTypeDefinition) { - if (normalizedConcrete.IsGenericType && - normalizedConcrete.GetGenericTypeDefinition() == normalizedRegistered) - { + if (normalizedConcrete.IsGenericType + && normalizedConcrete.GetGenericTypeDefinition() == normalizedRegistered + ) { distance = 1; return true; } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs index a9ef64333..9de71168a 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs @@ -36,9 +36,9 @@ out Type elementType } Type candidateElementType = candidate.GetGenericArguments()[0]; - if (candidateElementType.IsGenericType && - candidateElementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) - { + if (candidateElementType.IsGenericType + && candidateElementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>) + ) { continue; } @@ -184,7 +184,8 @@ internal static object BuildSequence( ConstructorInfo? constructor = FindSingleArgumentConstructor( targetType, listType, - typeof(IEnumerable<>).MakeGenericType(elementType)); + typeof(IEnumerable<>).MakeGenericType(elementType) + ); if (constructor is not null) { return constructor.Invoke([list]); @@ -199,7 +200,7 @@ internal static object BuildSequence( if (!targetType.IsAbstract && ResolveSequenceAddMethod(targetType, elementType) is MethodInfo addMethod) { object instance = Activator.CreateInstance(targetType, nonPublic: true) - ?? throw new InvalidOperationException($"Cannot create sequence type '{targetType.FullName}'."); + ?? throw new InvalidOperationException($"Cannot create sequence type '{targetType.FullName}'."); for (int i = 0; i < values.Count; i++) { addMethod.Invoke(instance, [values[i]]); @@ -209,7 +210,8 @@ internal static object BuildSequence( } throw new InvalidOperationException( - $"Cannot construct sequence type '{targetType.FullName}'. Provide ctor(IEnumerable), static CreateRange/Create, or Add(T)."); + $"Cannot construct sequence type '{targetType.FullName}'. Provide ctor(IEnumerable), static CreateRange/Create, or Add(T)." + ); } internal static object BuildMap( @@ -231,7 +233,8 @@ internal static object BuildMap( ConstructorInfo? constructor = FindSingleArgumentConstructor( targetType, pairListType, - typeof(IEnumerable<>).MakeGenericType(pairType)); + typeof(IEnumerable<>).MakeGenericType(pairType) + ); if (constructor is not null) { return constructor.Invoke([pairList]); @@ -246,7 +249,7 @@ internal static object BuildMap( if (!targetType.IsAbstract && ResolveMapAddMethod(targetType, keyType, valueType) is MethodInfo addMethod) { object instance = Activator.CreateInstance(targetType, nonPublic: true) - ?? throw new InvalidOperationException($"Cannot create map type '{targetType.FullName}'."); + ?? throw new InvalidOperationException($"Cannot create map type '{targetType.FullName}'."); for (int i = 0; i < entries.Count; i++) { KeyValuePair entry = entries[i]; @@ -257,7 +260,8 @@ internal static object BuildMap( } throw new InvalidOperationException( - $"Cannot construct map type '{targetType.FullName}'. Provide ctor(IEnumerable>), static CreateRange/Create, or Add(K,V)."); + $"Cannot construct map type '{targetType.FullName}'. Provide ctor(IEnumerable>), static CreateRange/Create, or Add(K,V)." + ); } private static object BuildTypedList( @@ -282,9 +286,7 @@ private static object BuildTypedDictionary( for (int i = 0; i < entries.Count; i++) { KeyValuePair entry = entries[i]; - dictionary.Add( - entry.Key ?? throw new InvalidOperationException("Map keys cannot be null."), - entry.Value); + dictionary.Add(entry.Key ?? throw new InvalidOperationException("Map keys cannot be null."), entry.Value); } return dictionary; @@ -310,7 +312,8 @@ private static object BuildTypedKeyValueList( params Type[] candidateArgumentTypes ) { ConstructorInfo[] constructors = targetType.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); for (int i = 0; i < constructors.Length; i++) { ParameterInfo[] parameters = constructors[i].GetParameters(); @@ -337,11 +340,12 @@ Type argumentType ) { return targetType .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) - .FirstOrDefault(method => - (method.Name == "CreateRange" || method.Name == "Create") && - targetType.IsAssignableFrom(method.ReturnType) && - method.GetParameters().Length == 1 && - method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType)); + .FirstOrDefault(method => ( + (method.Name == "CreateRange" || method.Name == "Create") + && targetType.IsAssignableFrom(method.ReturnType) + && method.GetParameters().Length == 1 + && method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType) + )); } private static MethodInfo? ResolveSequenceAddMethod( @@ -353,7 +357,8 @@ Type elementType BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, binder: null, types: [elementType], - modifiers: null); + modifiers: null + ); if (direct is not null) { return direct; @@ -361,8 +366,8 @@ Type elementType Type collectionInterface = typeof(ICollection<>).MakeGenericType(elementType); return collectionInterface.IsAssignableFrom(targetType) - ? collectionInterface.GetMethod("Add", [elementType]) - : null; + ? collectionInterface.GetMethod("Add", [elementType]) + : null; } private static MethodInfo? ResolveMapAddMethod( @@ -375,7 +380,8 @@ Type valueType BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, binder: null, types: [keyType, valueType], - modifiers: null); + modifiers: null + ); if (direct is not null) { return direct; @@ -383,8 +389,8 @@ Type valueType Type dictionaryInterface = typeof(IDictionary<,>).MakeGenericType(keyType, valueType); return dictionaryInterface.IsAssignableFrom(targetType) - ? dictionaryInterface.GetMethod("Add", [keyType, valueType]) - : null; + ? dictionaryInterface.GetMethod("Add", [keyType, valueType]) + : null; } private static IEnumerable EnumerateSelfAndInterfaces(Type type) diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EnumPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EnumPropertyDrawer.cs index e6da674b5..bac686f71 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EnumPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EnumPropertyDrawer.cs @@ -1,10 +1,12 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; +using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(Enum), useForChildren: true, priority: 100)] internal sealed class EnumPropertyDrawer : IPropertyDrawer { @@ -90,6 +92,7 @@ object value TypeCode.UInt16 => Convert.ToUInt16(value), TypeCode.UInt32 => Convert.ToUInt32(value), TypeCode.UInt64 => Convert.ToUInt64(value), - _ => throw new InvalidOperationException($"Unsupported enum underlying type '{underlyingType.FullName}'.")}; + _ => throw new InvalidOperationException($"Unsupported enum underlying type '{underlyingType.FullName}'.") + }; } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/GuidPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/GuidPropertyDrawer.cs index 3ffb93f87..51bd6ab2f 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/GuidPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/GuidPropertyDrawer.cs @@ -1,13 +1,16 @@ -using Inno.Editor.ImGui; using System; +using Inno.Editor.ImGui; + using EditorImGui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(Guid))] internal sealed class GuidPropertyDrawer : IPropertyDrawer { private const int C_BUFFER_SIZE = 64; private const string C_TEXT_STATE = "guid"; + /// /// Renders the value presentation for the current editor frame. /// @@ -18,8 +21,9 @@ public void Draw(PropertyDrawContext context) { Guid value = context.GetValue() is Guid current ? current : Guid.Empty; string text = context.TryGetTextState(C_TEXT_STATE, out string? editing) ? editing! : value.ToString("D"); - if (EditorImGui.InputText($"##{context.path}", ref text, C_BUFFER_SIZE, ImGuiInputTextFlags.EnterReturnsTrue) && Guid.TryParse(text, out Guid parsed)) - { + if (EditorImGui.InputText($"##{context.path}", ref text, C_BUFFER_SIZE, ImGuiInputTextFlags.EnterReturnsTrue) + && Guid.TryParse(text, out Guid parsed) + ) { context.SetValue(parsed); context.ClearTextState(C_TEXT_STATE); return; diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/IInspectionPropertyEditService.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/IInspectionPropertyEditService.cs index 052087445..379ebb901 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/IInspectionPropertyEditService.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/IInspectionPropertyEditService.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.Inspection; + /// /// Applies one root serialized-property mutation through the history mechanism owned by a feature. /// diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs index 8a3b1b51e..a32785f4c 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs @@ -1,12 +1,14 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using Inno.Core.Mathematics; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using NumericsVector4 = System.Numerics.Vector4; +using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + internal static unsafe class ComponentFieldDrawer { internal static float GetWidth(int count) @@ -50,10 +52,14 @@ public void Draw(PropertyDrawContext context) Vector2 value = context.GetValue() is Vector2 current ? current : default; float width = ComponentFieldDrawer.GetWidth(2); if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { context.SetValue(value, "x"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { context.SetValue(value, "y"); + } } } @@ -71,13 +77,19 @@ public void Draw(PropertyDrawContext context) Vector3 value = context.GetValue() is Vector3 current ? current : default; float width = ComponentFieldDrawer.GetWidth(3); if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { context.SetValue(value, "x"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { context.SetValue(value, "y"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "Z", ref value.z, width)) + { context.SetValue(value, "z"); + } } } @@ -95,16 +107,24 @@ public void Draw(PropertyDrawContext context) Vector4 value = context.GetValue() is Vector4 current ? current : default; float width = ComponentFieldDrawer.GetWidth(4); if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { context.SetValue(value, "x"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { context.SetValue(value, "y"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "Z", ref value.z, width)) + { context.SetValue(value, "z"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "W", ref value.w, width)) + { context.SetValue(value, "w"); + } } } @@ -122,10 +142,14 @@ public void Draw(PropertyDrawContext context) Vector2Int value = context.GetValue() is Vector2Int current ? current : default; float width = ComponentFieldDrawer.GetWidth(2); if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { context.SetValue(value, "x"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { context.SetValue(value, "y"); + } } } @@ -143,13 +167,19 @@ public void Draw(PropertyDrawContext context) Vector3Int value = context.GetValue() is Vector3Int current ? current : default; float width = ComponentFieldDrawer.GetWidth(3); if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { context.SetValue(value, "x"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { context.SetValue(value, "y"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Int(context.path, "Z", ref value.z, width)) + { context.SetValue(value, "z"); + } } } @@ -167,16 +197,24 @@ public void Draw(PropertyDrawContext context) Vector4Int value = context.GetValue() is Vector4Int current ? current : default; float width = ComponentFieldDrawer.GetWidth(4); if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { context.SetValue(value, "x"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { context.SetValue(value, "y"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Int(context.path, "Z", ref value.z, width)) + { context.SetValue(value, "z"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Int(context.path, "W", ref value.w, width)) + { context.SetValue(value, "w"); + } } } @@ -194,16 +232,24 @@ public void Draw(PropertyDrawContext context) Rect value = context.GetValue() is Rect current ? current : default; float width = ComponentFieldDrawer.GetWidth(4); if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { context.SetValue(value, "x"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { context.SetValue(value, "y"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "W", ref value.width, width)) + { context.SetValue(value, "width"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "H", ref value.height, width)) + { context.SetValue(value, "height"); + } } } @@ -221,16 +267,24 @@ public void Draw(PropertyDrawContext context) RectInt value = context.GetValue() is RectInt current ? current : default; float width = ComponentFieldDrawer.GetWidth(4); if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { context.SetValue(value, "x"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { context.SetValue(value, "y"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Int(context.path, "W", ref value.width, width)) + { context.SetValue(value, "width"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Int(context.path, "H", ref value.height, width)) + { context.SetValue(value, "height"); + } } } @@ -247,7 +301,12 @@ public void Draw(PropertyDrawContext context) { Color value = context.GetValue() is Color current ? current : default; var nativeValue = new NumericsVector4(value.r, value.g, value.b, value.a); - var flags = context.hdrColor ? Inno.Editor.ImGui.ImGuiColorEditFlags.Hdr | Inno.Editor.ImGui.ImGuiColorEditFlags.Float | Inno.Editor.ImGui.ImGuiColorEditFlags.InputRgb | Inno.Editor.ImGui.ImGuiColorEditFlags.DisplayRgb : Inno.Editor.ImGui.ImGuiColorEditFlags.None; + var flags = context.hdrColor + ? Inno.Editor.ImGui.ImGuiColorEditFlags.Hdr + | Inno.Editor.ImGui.ImGuiColorEditFlags.Float + | Inno.Editor.ImGui.ImGuiColorEditFlags.InputRgb + | Inno.Editor.ImGui.ImGuiColorEditFlags.DisplayRgb + : Inno.Editor.ImGui.ImGuiColorEditFlags.None; if (Ui.ColorEditLinear4($"##{context.path}", ref nativeValue, flags)) { context.SetValue(new Color(nativeValue.X, nativeValue.Y, nativeValue.Z, nativeValue.W)); @@ -270,12 +329,18 @@ public void Draw(PropertyDrawContext context) Vector3 eulerDegrees = value.ToEulerAnglesXYZDegrees(); float width = ComponentFieldDrawer.GetWidth(3); if (ComponentFieldDrawer.Float(context.path, "X", ref eulerDegrees.x, width)) + { context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.x"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "Y", ref eulerDegrees.y, width)) + { context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.y"); + } ComponentFieldDrawer.Next(); if (ComponentFieldDrawer.Float(context.path, "Z", ref eulerDegrees.z, width)) + { context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.z"); + } } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NullablePropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NullablePropertyDrawer.cs index 950b3f7c9..02565d053 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NullablePropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NullablePropertyDrawer.cs @@ -1,8 +1,10 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(Nullable<>))] internal sealed class NullablePropertyDrawer : IPropertyDrawer { @@ -14,7 +16,8 @@ internal sealed class NullablePropertyDrawer : IPropertyDrawer /// public void Draw(PropertyDrawContext context) { - Type underlyingType = Nullable.GetUnderlyingType(context.propertyType) ?? throw new InvalidOperationException("Nullable drawer requires a nullable property type."); + Type underlyingType = Nullable.GetUnderlyingType(context.propertyType) + ?? throw new InvalidOperationException("Nullable drawer requires a nullable property type."); object? value = context.GetValue(); bool hasValue = value is not null; bool previousHasValue = hasValue; diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NumericPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NumericPropertyDrawer.cs index c2feafdc9..39d028cb9 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NumericPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/NumericPropertyDrawer.cs @@ -1,10 +1,12 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Globalization; +using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(byte))] [PropertyDrawer(typeof(sbyte))] [PropertyDrawer(typeof(short))] @@ -20,6 +22,7 @@ internal sealed class NumericPropertyDrawer : IPropertyDrawer { private const int C_BUFFER_SIZE = 128; private const string C_TEXT_STATE = "numeric"; + /// /// Renders the value presentation for the current editor frame. /// @@ -34,20 +37,14 @@ public void Draw(PropertyDrawContext context) { int value = rawValue is int current ? current : 0; bool changed = context.minimum is double minimum - && context.maximum is double maximum ? Ui.SliderInt( - $"##{context.path}", - ref value, - (int)Math.Clamp(Math.Ceiling(minimum), int.MinValue, int.MaxValue), - (int)Math.Clamp(Math.Floor(maximum), int.MinValue, int.MaxValue) - ) : Ui.DragInt( - $"##{context.path}", - ref value, - 1f, - 0, - 0, - "%d", - 0 - ); + && context.maximum is double maximum + ? Ui.SliderInt( + $"##{context.path}", + ref value, + (int)Math.Clamp(Math.Ceiling(minimum), int.MinValue, int.MaxValue), + (int)Math.Clamp(Math.Floor(maximum), int.MinValue, int.MaxValue) + ) + : Ui.DragInt($"##{context.path}", ref value, 1f, 0, 0, "%d", 0); if (changed) { context.SetValue(value); @@ -60,16 +57,14 @@ public void Draw(PropertyDrawContext context) { float value = rawValue is float current ? current : 0f; bool changed = context.minimum is double minimum - && context.maximum is double maximum ? EditorUI.current.widgets.CompactSliderFloat( - $"##{context.path}", - ref value, - (float)minimum, - (float)maximum - ) : EditorUI.current.widgets.CompactDragFloat( - $"##{context.path}", - ref value, - 0.1f - ); + && context.maximum is double maximum + ? EditorUI.current.widgets.CompactSliderFloat( + $"##{context.path}", + ref value, + (float)minimum, + (float)maximum + ) + : EditorUI.current.widgets.CompactDragFloat($"##{context.path}", ref value, 0.1f); if (changed) { context.SetValue(value); @@ -118,7 +113,9 @@ out object? value double? maximum ) { if (value is null || minimum is null || maximum is null) + { return value; + } double numeric = Convert.ToDouble(value, CultureInfo.InvariantCulture); double clamped = Math.Clamp(numeric, minimum.Value, maximum.Value); return Convert.ChangeType(clamped, type, CultureInfo.InvariantCulture); diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawContext.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawContext.cs index 7e9f742dd..492171264 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawContext.cs @@ -2,10 +2,11 @@ using System.Reflection; using Inno.Core.Serialization; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; +using Inno.Editor.Interactions; namespace Inno.Editor.Inspection; + /// /// Encapsulates one editable property path and its drawing services. /// @@ -18,50 +19,62 @@ public sealed class PropertyDrawContext private readonly object m_owner; private readonly string m_rootPropertyName; private readonly bool m_isReadOnly; + /// /// Gets the shared editor context. /// public EditorContext editorContext { get; } + /// /// Gets the active editor interaction entry point. /// public EditorInteractions interactions { get; } + /// /// Gets the stable control path. /// public string path { get; } + /// /// Gets the display label. /// public string label { get; } + /// /// Gets the declared property type. /// public Type propertyType { get; } + /// /// Gets the serialization visibility flags. /// public PropertyVisibility visibility { get; } + /// /// Gets whether assignments are disabled. /// public bool isReadOnly => m_isReadOnly; + /// /// Gets the optional inclusive numeric lower bound supplied by Inspector metadata. /// public double? minimum { get; } + /// /// Gets the optional inclusive numeric upper bound supplied by Inspector metadata. /// public double? maximum { get; } + /// /// Gets optional hover help supplied by Inspector metadata. /// public string? tooltip { get; } + /// /// Gets whether Color values are unclamped linear floating-point channels. /// public bool hdrColor { get; } + internal object owner => m_owner; internal PropertyDrawContext( @@ -87,10 +100,12 @@ internal PropertyDrawContext( this.interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); m_edits = edits ?? throw new ArgumentNullException(nameof(edits)); m_owner = owner ?? throw new ArgumentNullException(nameof(owner)); - m_rootPropertyName = string.IsNullOrWhiteSpace(rootPropertyName) ? throw new ArgumentException( - "The root property name is required.", - nameof(rootPropertyName) - ) : rootPropertyName; + m_rootPropertyName = string.IsNullOrWhiteSpace(rootPropertyName) + ? throw new ArgumentException( + "The root property name is required.", + nameof(rootPropertyName) + ) + : rootPropertyName; this.path = path; this.label = label; this.propertyType = propertyType; @@ -112,6 +127,7 @@ internal PropertyDrawContext( /// The latest value returned by the serialized property's getter. /// public object? GetValue() => m_getter(); + /// /// Tries to read text-edit state scoped to this renderer, inspected owner, and property path. /// @@ -128,6 +144,7 @@ public bool TryGetTextState( string key, out string? value ) => m_renderer.TryGetTextState(m_owner, path, key, out value); + /// /// Stores text-edit state scoped to this renderer, inspected owner, and property path. /// @@ -141,6 +158,7 @@ public void SetTextState( string key, string value ) => m_renderer.SetTextState(m_owner, path, key, value); + /// /// Removes text-edit state for this renderer, inspected owner, and property path. /// @@ -148,6 +166,7 @@ string value /// Drawer-local state identity within the current property path. /// public void ClearTextState(string key) => m_renderer.ClearTextState(m_owner, path, key); + /// /// Assigns a value when the property is writable. /// @@ -162,14 +181,25 @@ public void SetValue( string? componentName = null ) { if (isReadOnly) + { return; + } EditorUiSession ui = EditorUiSession.current; if (Equals(m_getter(), value) && !ui.widgets.isMixedValue) + { return; + } ui.widgets.BeginPropertyEdit(interactions.history, path, $"Change {label}"); try { - _ = m_edits.ChangeProperty(m_owner, m_rootPropertyName, () => m_setter(value), $"Change {label}", ui.widgets.editMergeKey, componentName); + _ = m_edits.ChangeProperty( + m_owner, + m_rootPropertyName, + () => m_setter(value), + $"Change {label}", + ui.widgets.editMergeKey, + componentName + ); } catch { @@ -204,7 +234,21 @@ public void DrawChild( bool readOnly = false ) { PropertyVisibility childVisibility = readOnly || isReadOnly ? PropertyVisibility.Readonly : PropertyVisibility.Show; - m_renderer.Draw(editorContext, m_owner, m_owner, null, null, m_rootPropertyName, $"{path}.{childName}", childName, childType, childVisibility, getter, setter, m_edits); + m_renderer.Draw( + editorContext, + m_owner, + m_owner, + null, + null, + m_rootPropertyName, + $"{path}.{childName}", + childName, + childType, + childVisibility, + getter, + setter, + m_edits + ); } /// @@ -214,6 +258,7 @@ public void DrawChild( /// Nested property. /// public void DrawChild(SerializedProperty property) => DrawChild(GetValue() ?? m_owner, property); + /// /// Draws a nested serialized property with presentation metadata resolved from its immediate owner. /// @@ -300,6 +345,19 @@ public void DrawInlineChild( bool readOnly = false ) { PropertyVisibility childVisibility = readOnly || isReadOnly ? PropertyVisibility.Readonly : PropertyVisibility.Show; - m_renderer.DrawInline(editorContext, m_owner, m_owner, null, m_rootPropertyName, $"{path}.{childName}", childName, childType, childVisibility, getter, setter, m_edits); + m_renderer.DrawInline( + editorContext, + m_owner, + m_owner, + null, + m_rootPropertyName, + $"{path}.{childName}", + childName, + childType, + childVisibility, + getter, + setter, + m_edits + ); } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs index 47aec1593..40be33cde 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; namespace Inno.Editor.Inspection; @@ -77,16 +76,17 @@ internal PropertyTypeRegistry( TypeCatalog types, SerializationRegistry serialization, IEnumerable drawerServices - ) - : base(types) + ) : base(types) { m_interactions = interactions ?? throw new ArgumentNullException(nameof(interactions)); m_serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); ArgumentNullException.ThrowIfNull(drawerServices); - m_drawerServices = drawerServices.Select(static service => + m_drawerServices = drawerServices.Select(static service => ( service ?? throw new ArgumentException( "Property drawer services cannot contain null.", - nameof(drawerServices))).ToArray(); + nameof(drawerServices) + ) + )).ToArray(); } internal IPropertyDrawer Resolve(Type propertyType) @@ -96,14 +96,16 @@ internal IPropertyDrawer Resolve(Type propertyType) foreach (Registration registration in current) { if (!DrawerTypeUtility.TryGetDistance( - propertyType, - registration.targetType, - registration.useForChildren, - out int distance)) + propertyType, + registration.targetType, + registration.useForChildren, + out int distance + )) { continue; - if (best is null || distance < bestDistance || - distance == bestDistance && registration.priority > best.priority) - { + } + if (best is null || distance < bestDistance + || distance == bestDistance && registration.priority > best.priority + ) { best = registration; bestDistance = distance; } @@ -125,29 +127,35 @@ protected override Registration[] Build(TypeCacheSnapshot types) var drawers = new Dictionary(); var registrations = new List(); foreach (Type drawerType in types.GetTypesWithAttribute() - .Select(typeRef => typeRef.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal)) - { + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { IPropertyDrawer drawer = drawers.TryGetValue(drawerType, out IPropertyDrawer? existing) - ? existing - : OwnCandidateExtension(CreateDrawer( - drawerType, - m_interactions, - types, - m_serialization, - m_drawerServices)); + ? existing + : OwnCandidateExtension( + CreateDrawer( + drawerType, + m_interactions, + types, + m_serialization, + m_drawerServices + ) + ); drawers[drawerType] = drawer; foreach (PropertyDrawerAttribute attribute in - drawerType.GetCustomAttributes(false)) - { + drawerType.GetCustomAttributes(false) + ) { EnsureNoConflict(registrations, attribute, drawerType); - registrations.Add(new Registration( - attribute.targetType, - attribute.useForChildren, - attribute.priority, - drawerType, - drawer)); + registrations.Add( + new Registration( + attribute.targetType, + attribute.useForChildren, + attribute.priority, + drawerType, + drawer + ) + ); } } return registrations.ToArray(); @@ -171,9 +179,12 @@ private static IPropertyDrawer CreateDrawer( IReadOnlyList drawerServices ) { ConstructorInfo[] constructors = type.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); if (constructors.Length != 1) + { throw new InvalidOperationException($"Property drawer '{type.FullName}' must declare exactly one constructor."); + } ParameterInfo[] parameters = constructors[0].GetParameters(); object?[] arguments = new object?[parameters.Length]; for (int index = 0; index < parameters.Length; index++) @@ -192,11 +203,13 @@ IReadOnlyList drawerServices { 1 => matches[0], 0 => throw new InvalidOperationException( - $"Property drawer '{type.FullName}' requests unavailable service " + - $"'{parameterType.FullName}'."), + $"Property drawer '{type.FullName}' requests unavailable service " + + $"'{parameterType.FullName}'." + ), _ => throw new InvalidOperationException( - $"Property drawer '{type.FullName}' requests ambiguous service " + - $"'{parameterType.FullName}'.") + $"Property drawer '{type.FullName}' requests ambiguous service " + + $"'{parameterType.FullName}'." + ) }; } return (IPropertyDrawer)constructors[0].Invoke(arguments); @@ -212,8 +225,9 @@ Type drawerType if (existing.targetType == attribute.targetType && existing.priority == attribute.priority) { throw new InvalidOperationException( - $"Property drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + - $"conflict for '{attribute.targetType.FullName}'."); + $"Property drawers '{existing.drawerType.FullName}' and '{drawerType.FullName}' " + + $"conflict for '{attribute.targetType.FullName}'." + ); } } } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializableObjectPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializableObjectPropertyDrawer.cs index c5d365de8..5668a888a 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializableObjectPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializableObjectPropertyDrawer.cs @@ -1,18 +1,21 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Extensibility.Types; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(ISerializable), useForChildren: true, priority: 20)] internal sealed class SerializableObjectPropertyDrawer : IPropertyDrawer { private readonly SerializationRegistry m_serialization; private readonly TypeCacheSnapshot m_types; + internal SerializableObjectPropertyDrawer( TypeCacheSnapshot types, SerializationRegistry serialization diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs index 1300a96e0..a27c63b47 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs @@ -1,18 +1,20 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using Inno.Core.Logging; -using Inno.Scripting.Api; using Inno.Core.Serialization; using Inno.Editor.Annotations; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; +using Inno.Scripting.Api; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.Inspection; + /// /// Resolves drawers and renders serialized property paths with isolated error handling. /// @@ -25,6 +27,7 @@ public sealed class SerializedPropertyRenderer private readonly EditorInteractions m_interactions; private readonly IInspectionPropertyEditService m_edits; private readonly Logger m_logger; + /// /// Creates a serialized property renderer over one drawer registry and feature-owned edit service. /// @@ -259,7 +262,9 @@ SerializedProperty property bool readOnly = (property.visibility & PropertyVisibility.RuntimeSet) == 0; MemberInfo? member = InspectorMemberMetadata.Resolve(owner.GetType(), property.name); if (member is null) + { return (true, readOnly); + } var context = new InspectorAttributeDrawContext(owner, member, property, property.name, property.name, readOnly); m_attributes.Update(context, InspectorMemberMetadata.GetAttributes(member)); return (context.isVisible, context.isReadOnly); @@ -294,14 +299,20 @@ internal void Draw( attributeContext = new InspectorAttributeDrawContext(metadataOwner, member, property, path, displayLabel, isReadOnly); m_attributes.Update(attributeContext, attributes); if (!attributeContext.isVisible) + { return; + } displayLabel = attributeContext.label; isReadOnly = attributeContext.isReadOnly; if (!beginsSection && !EditorUI.current.widgets.isSectionContentVisible) + { return; + } m_attributes.DrawBefore(attributeContext, attributes); if (!EditorUI.current.widgets.isSectionContentVisible) + { return; + } } else if (!EditorUI.current.widgets.isSectionContentVisible) { @@ -309,7 +320,9 @@ internal void Draw( } if (!beginsSection && !EditorUI.current.widgets.EnsureSection()) + { return; + } var context = new PropertyDrawContext( editorContext, m_interactions, @@ -329,9 +342,16 @@ internal void Draw( this, hdrColor ); - EditorUI.current.widgets.PropertyRow(path, context.label, () => DrawContent(context), tooltip: attributeContext?.tooltip ?? tooltip); + EditorUI.current.widgets.PropertyRow( + path, + context.label, + () => DrawContent(context), + tooltip: attributeContext?.tooltip ?? tooltip + ); if (attributeContext is not null) + { m_attributes.DrawAfter(attributeContext, attributes); + } } internal void DrawInline( @@ -383,8 +403,9 @@ private void DrawContent(PropertyDrawContext context) { EditorUI.current.widgets.ColoredText(EditorPalette.error, $"Error: {exception.Message}"); string failureState = $"{exception.GetType().FullName}|{exception.Message}"; - if (!failureStates.TryGetValue(context.path, out string? previous) || !string.Equals(previous, failureState, StringComparison.Ordinal)) - { + if (!failureStates.TryGetValue(context.path, out string? previous) + || !string.Equals(previous, failureState, StringComparison.Ordinal) + ) { m_logger.Write(LogLevel.Error, "Inspector failed to draw property '{0}': {1}", [context.path, exception]); failureStates[context.path] = failureState; } @@ -399,7 +420,8 @@ out string? value ) { ArgumentNullException.ThrowIfNull(owner); value = null; - return m_textStates.TryGetValue(owner, out Dictionary? states) && states.TryGetValue(CreateStateKey(path, key), out value); + return m_textStates.TryGetValue(owner, out Dictionary? states) + && states.TryGetValue(CreateStateKey(path, key), out value); } internal void SetTextState( @@ -420,7 +442,9 @@ string key ) { ArgumentNullException.ThrowIfNull(owner); if (m_textStates.TryGetValue(owner, out Dictionary? states)) + { states.Remove(CreateStateKey(path, key)); + } } private static string CreateStateKey( diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StringPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StringPropertyDrawer.cs index 83697be97..0cb6d8918 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StringPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StringPropertyDrawer.cs @@ -1,11 +1,14 @@ using Inno.Editor.ImGui; + using EditorImGui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(string))] internal sealed class StringPropertyDrawer : IPropertyDrawer { private const int C_BUFFER_SIZE = 1024; + /// /// Renders the value presentation for the current editor frame. /// diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs index 43b0f0361..e94f016e3 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs @@ -1,18 +1,21 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Inno.Core.Serialization; +using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Inspection; + [PropertyDrawer(typeof(ValueType), useForChildren: true, priority: -100)] internal sealed class StructPropertyDrawer : IPropertyDrawer { private static readonly ConditionalWeakTable S_MEMBER_CACHE = new(); + /// /// Renders the value presentation for the current editor frame. /// @@ -41,12 +44,20 @@ public void Draw(PropertyDrawContext context) MemberInfo member = members[i]; Type memberType = GetMemberType(member); bool memberReadOnly = !CanWrite(member) || (GetVisibility(member) & PropertyVisibility.RuntimeSet) == 0; - context.DrawChildMember(context.GetValue() ?? boxedValue, member, memberType, () => GetMemberValue(member, context.GetValue() ?? boxedValue), value => + context.DrawChildMember( + context.GetValue() + ?? boxedValue, + member, + memberType, + () => GetMemberValue(member, context.GetValue() ?? boxedValue), + value => { object updated = context.GetValue() ?? Activator.CreateInstance(context.propertyType)!; SetMemberValue(member, updated, value); context.SetValue(updated); - }, memberReadOnly); + }, + memberReadOnly + ); } }); Ui.TreePop(); @@ -56,7 +67,13 @@ private static MemberInfo[] GetMembers(Type type) { return S_MEMBER_CACHE.GetValue( type, - static value => new MembersBox(value.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(IsRuntimeVisibleMember).OrderBy(static member => member.MetadataToken).ToArray()) + static value => new MembersBox( + value + .GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(IsRuntimeVisibleMember) + .OrderBy(static member => member.MetadataToken) + .ToArray() + ) ).members; } @@ -65,14 +82,16 @@ private static bool IsRuntimeVisibleMember(MemberInfo member) SerializablePropertyAttribute? attribute = member.GetCustomAttribute(inherit: true); PropertyVisibility visibility = attribute?.propertyVisibility ?? PropertyVisibility.Show; if ((visibility & PropertyVisibility.RuntimeGet) == 0) + { return false; + } return member switch { FieldInfo field => !field.IsStatic && (attribute is not null || field.IsPublic && !field.IsInitOnly), PropertyInfo property => property.GetIndexParameters().Length == 0 - && (attribute is not null - || property.GetGetMethod(nonPublic: true)?.IsPublic == true - && property.GetSetMethod(nonPublic: true)?.IsPublic == true), + && (attribute is not null + || property.GetGetMethod(nonPublic: true)?.IsPublic == true + && property.GetSetMethod(nonPublic: true)?.IsPublic == true), _ => false }; } @@ -88,7 +107,8 @@ private static Type GetMemberType(MemberInfo member) { FieldInfo field => field.FieldType, PropertyInfo property => property.PropertyType, - _ => throw new InvalidOperationException($"Unsupported struct member '{member.MemberType}'.")}; + _ => throw new InvalidOperationException($"Unsupported struct member '{member.MemberType}'.") + }; } private static object? GetMemberValue( diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/UnsupportedPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/UnsupportedPropertyDrawer.cs index ad5daf22f..b859aa2da 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/UnsupportedPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/UnsupportedPropertyDrawer.cs @@ -1,7 +1,9 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Inno.Editor.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; + namespace Inno.Editor.Inspection; + internal sealed class UnsupportedPropertyDrawer : IPropertyDrawer { internal static UnsupportedPropertyDrawer instance { get; } = new(); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs index d758c28d6..5087a4b99 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs @@ -1,7 +1,8 @@ -using Inno.Editor.Core; using System; +using Inno.Editor.Core; namespace Inno.Editor.Interactions; + /// /// Defines one automatically discovered editor operation and owns its complete multi-frame lifecycle. /// @@ -11,14 +12,17 @@ public abstract class EditorAction : IDisposable private EditorInteractions? m_activeInteractions; private bool m_isActive; private bool m_isDisposed; + /// /// Gets whether the action currently owns an active multi-frame operation. /// public bool isActive => m_isActive; + /// /// Gets the required target type, or for a targetless action. /// public virtual Type? targetType => null; + internal virtual Type? argumentType => null; internal EditorActionState QueryInternal(EditorActionContext context) @@ -40,10 +44,13 @@ internal bool PresentInternal(EditorActionContext context) } internal void CancelInternal() => Cancel(); + internal void LosePresentationInternal() { if (!m_isActive) + { return; + } try { OnPresentationLost(); @@ -51,17 +58,18 @@ internal void LosePresentationInternal() finally { if (m_isActive) + { Cancel(); + } } } - internal bool IsActiveFor(object? target) => m_isActive - && m_activeTarget is not null - && m_activeInteractions is not null - && m_activeTarget.Matches( - m_activeInteractions, - target - ); + internal bool IsActiveFor(object? target) + => m_isActive + && m_activeTarget is not null + && m_activeInteractions is not null + && m_activeTarget.Matches(m_activeInteractions, target); + /// /// Resolves the active target afresh for this callback; null means the identity is unavailable. /// @@ -69,6 +77,7 @@ internal bool IsActiveFor(object? target) => m_isActive /// Do not retain the result across callbacks. Activation stores a domain-qualified reference rather than the live object. /// protected object? activeTarget => m_activeInteractions is null ? null : m_activeTarget?.Resolve(m_activeInteractions); + /// /// Gets the host-owned passive context of the active operation, or null after completion. /// @@ -99,7 +108,9 @@ protected void Activate(EditorActionContext context) protected void Complete() { if (!m_isActive) + { return; + } m_activeTarget = null; m_activeInteractions = null; activeEditorContext = null; @@ -113,7 +124,9 @@ protected void Complete() protected void Cancel() { if (!m_isActive) + { return; + } m_activeTarget = null; m_activeInteractions = null; activeEditorContext = null; @@ -131,6 +144,7 @@ protected void Cancel() /// The current presentation and availability state. /// protected virtual EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; + /// /// Executes the action for the supplied context. /// @@ -138,6 +152,7 @@ protected void Cancel() /// The editor, area, target, and optional argument for the operation. /// protected abstract void Execute(EditorActionContext context); + /// /// Presents an active action at the current target location. /// @@ -148,19 +163,16 @@ protected void Cancel() /// when the action replaced the target's normal content; otherwise, . /// protected virtual bool Present(EditorActionContext context) => false; + /// /// Runs after an active operation completes successfully. /// - protected virtual void OnCompleted() - { - } + protected virtual void OnCompleted() {} /// /// Runs after an active operation is cancelled. /// - protected virtual void OnCancelled() - { - } + protected virtual void OnCancelled() {} /// /// Runs when this action's active target loses editor presentation focus. @@ -171,13 +183,16 @@ protected virtual void OnCancelled() /// without calling or . /// protected virtual void OnPresentationLost() => Cancel(); + /// /// Cancels active work and releases this action instance. /// public void Dispose() { if (m_isDisposed) + { return; + } Cancel(); m_isDisposed = true; GC.SuppressFinalize(this); @@ -199,6 +214,7 @@ public abstract class EditorAction : EditorAction /// Gets the concrete type handled by this extension implementation. /// public sealed override Type targetType => typeof(TTarget); + internal sealed override Type argumentType => typeof(TArgument); /// @@ -210,10 +226,12 @@ public abstract class EditorAction : EditorAction /// /// The context that supplies state and services for this operation. /// - protected sealed override EditorActionState Query(EditorActionContext context) => TryCreate( - context, - out EditorActionContext typed - ) ? Query(typed) : EditorActionState.hidden; + protected sealed override EditorActionState Query(EditorActionContext context) + => TryCreate( + context, + out EditorActionContext typed + ) ? Query(typed) : EditorActionState.hidden; + /// /// Applies the editor action to the supplied interaction context. /// @@ -224,7 +242,9 @@ protected sealed override void Execute(EditorActionContext context) { if (!TryCreate(context, out EditorActionContext typed)) { - throw new InvalidOperationException($"Editor action '{GetType().FullName}' requires target '{typeof(TTarget).FullName}' " + $"and argument '{typeof(TArgument).FullName}'."); + throw new InvalidOperationException( + $"Editor action '{GetType().FullName}' requires target '{typeof(TTarget).FullName}' " + $"and argument '{typeof(TArgument).FullName}'." + ); } Execute(typed); @@ -239,7 +259,9 @@ protected sealed override void Execute(EditorActionContext context) /// /// The context that supplies state and services for this operation. /// - protected sealed override bool Present(EditorActionContext context) => TryCreate(context, out EditorActionContext typed) && Present(typed); + protected sealed override bool Present(EditorActionContext context) + => TryCreate(context, out EditorActionContext typed) && Present(typed); + /// /// Evaluates the action for a typed target and argument. /// @@ -250,6 +272,7 @@ protected sealed override void Execute(EditorActionContext context) /// The current presentation and availability state. /// protected virtual EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; + /// /// Executes the action for a typed target and argument. /// @@ -257,6 +280,7 @@ protected sealed override void Execute(EditorActionContext context) /// The typed contextual request. /// protected abstract void Execute(EditorActionContext context); + /// /// Presents an active action for a typed target and argument. /// @@ -267,6 +291,7 @@ protected sealed override void Execute(EditorActionContext context) /// when content was presented. /// protected virtual bool Present(EditorActionContext context) => false; + private static bool TryCreate( EditorActionContext context, out EditorActionContext typed @@ -301,8 +326,12 @@ public abstract class EditorArgumentAction : EditorAction /// /// The validated editor action state that represents the completed operation. /// - protected sealed override EditorActionState Query(EditorActionContext context) => context.target is null - && context.argument is TArgument argument ? Query(new EditorActionArgumentContext(context, argument)) : EditorActionState.hidden; + protected sealed override EditorActionState Query(EditorActionContext context) + => context.target is null + && context.argument is TArgument argument + ? Query(new EditorActionArgumentContext(context, argument)) + : EditorActionState.hidden; + /// /// Applies the editor action to the supplied interaction context. /// @@ -329,6 +358,7 @@ protected sealed override void Execute(EditorActionContext context) /// The current presentation and availability state. /// protected virtual EditorActionState Query(EditorActionArgumentContext context) => EditorActionState.enabled; + /// /// Executes the action for a typed argument. /// @@ -358,8 +388,10 @@ public abstract class EditorPresentationAction : EditorA /// /// when the operation succeeds or its condition is satisfied; otherwise, . /// - protected sealed override bool Present(EditorActionContext context) => context.argument is TPresentation presentation - && Present(new EditorActionContext(context, context.target, presentation)); + protected sealed override bool Present(EditorActionContext context) + => context.argument is TPresentation presentation + && Present(new EditorActionContext(context, context.target, presentation)); + /// /// Presents active content using strongly typed presentation data. /// @@ -442,6 +474,7 @@ protected sealed override bool Present(EditorActionContext context) /// The current presentation and availability state. /// protected virtual EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; + /// /// Executes the action for a strongly typed target. /// @@ -449,6 +482,7 @@ protected sealed override bool Present(EditorActionContext context) /// The contextual request containing the typed target. /// protected abstract void Execute(EditorActionContext context); + /// /// Presents an active action for a strongly typed target. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionAttribute.cs index f003ded47..60ff2b4ec 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionAttribute.cs @@ -23,10 +23,7 @@ public sealed class EditorActionAttribute : Attribute public EditorActionAttribute( string action, int priority = 0 - ) - : this(action, string.Empty, priority) - { - } + ) : this(action, string.Empty, priority) {} /// /// Creates an action registration restricted to one exact area. @@ -49,7 +46,9 @@ public EditorActionAttribute( int priority = 0 ) { if (string.IsNullOrWhiteSpace(action)) + { throw new ArgumentException("An editor action name is required.", nameof(action)); + } this.action = action; this.area = area ?? string.Empty; this.priority = priority; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs index 505563fa6..0aaa85f1b 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs @@ -2,6 +2,7 @@ using Inno.Editor.Core; namespace Inno.Editor.Interactions; + /// /// Provides contextual state to an editor action. /// @@ -50,22 +51,27 @@ internal EditorActionContext( /// Gets the shared passive editor context. /// public EditorContext editor { get; } + /// /// Gets the active interaction entry point. /// public EditorInteractions interactions { get; } + /// /// Gets the transactional history used to record reversible mutations performed by this action. /// public IEditorHistory history => interactions.history; + /// /// Gets the stable interaction area. /// public string area { get; } + /// /// Gets the contextual action target. /// public object? target { get; } + /// /// Gets the optional action argument. /// @@ -119,6 +125,7 @@ TArgument argument /// Gets the strongly typed action target. /// public new TTarget target { get; } + /// /// Gets the strongly typed action argument. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs index 7c18f3996..0c3e13f52 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs @@ -7,18 +7,19 @@ using Inno.Editor.Core; namespace Inno.Editor.Interactions; + internal sealed class EditorActionRouter( EditorExtensionCatalog catalog, EditorContext editor, EditorInteractions interactions, Logger log -) -{ +) { private readonly Queue m_pending = []; private readonly HashSet m_presentationFailures = new(StringComparer.Ordinal); private readonly HashSet m_queryFailures = new(StringComparer.Ordinal); private IReadOnlyDictionary? m_byId; private Dictionary<(KeyCode key, KeyModifier modifiers, string area), string[]>? m_shortcutIndex; + internal EditorActionState Query( string action, EditorActionContext context @@ -27,7 +28,9 @@ EditorActionContext context ArgumentNullException.ThrowIfNull(context); EditorExtensionCatalog.ActionRegistration? registration = Resolve(action, context); if (registration is null) + { return EditorActionState.hidden; + } try { EditorActionState state = registration.action.QueryInternal(context); @@ -37,7 +40,9 @@ EditorActionContext context catch (Exception exception) { if (m_queryFailures.Add(action)) + { log.Write(LogLevel.Error, "Editor action '{0}' query failed: {1}", [action, exception]); + } return EditorActionState.disabled; } } @@ -50,12 +55,16 @@ EditorActionContext context ArgumentNullException.ThrowIfNull(context); EditorExtensionCatalog.ActionRegistration? registration = Resolve(action, context); if (registration is null) + { return false; + } try { EditorActionState state = registration.action.QueryInternal(context); if (!state.isVisible || !state.isEnabled) + { return false; + } interactions.PrepareOperation(); registration.action.ExecuteInternal(context); return true; @@ -76,7 +85,9 @@ EditorActionContext context ArgumentNullException.ThrowIfNull(context); EditorExtensionCatalog.ActionRegistration? registration = Resolve(action, context); if (registration is null) + { return false; + } try { bool presented = registration.action.PresentInternal(context); @@ -87,7 +98,9 @@ EditorActionContext context { TryCancel(registration.action, action, "presentation cleanup"); if (m_presentationFailures.Add(action)) + { log.Write(LogLevel.Error, "Editor action '{0}' presentation failed: {1}", [action, exception]); + } return false; } } @@ -108,7 +121,16 @@ EditorActionContext context ) { ArgumentException.ThrowIfNullOrWhiteSpace(action); ArgumentNullException.ThrowIfNull(context); - m_pending.Enqueue(new PendingAction(action, context.area, EditorTargetReference.Capture(context.target), context.target is not null, EditorTargetReference.Capture(context.argument), context.argument is not null)); + m_pending.Enqueue( + new PendingAction( + action, + context.area, + EditorTargetReference.Capture(context.target), + context.target is not null, + EditorTargetReference.Capture(context.argument), + context.argument is not null + ) + ); } internal void Flush() @@ -118,7 +140,9 @@ internal void Flush() object? target = request.target.Resolve(interactions); object? argument = request.argument.Resolve(interactions); if (request.hasTarget && target is null || request.hasArgument && argument is null) + { continue; + } _ = Execute(request.action, new EditorActionContext(editor, interactions, request.area, target, argument)); } } @@ -150,6 +174,7 @@ internal void InvalidateDiscovery() m_byId = null; m_shortcutIndex = null; } + internal void LosePresentationExcept(object? target) { var visited = new HashSet(ReferenceEqualityComparer.Instance); @@ -157,14 +182,20 @@ internal void LosePresentationExcept(object? target) { EditorAction action = registration.action; if (!visited.Add(action) || !action.isActive || action.IsActiveFor(target)) + { continue; + } try { action.LosePresentationInternal(); } catch (Exception exception) { - log.Write(LogLevel.Error, "Editor action '{0}' failed while losing presentation focus: {1}", [registration.attribute.action, exception]); + log.Write( + LogLevel.Error, + "Editor action '{0}' failed while losing presentation focus: {1}", + [registration.attribute.action, exception] + ); } } } @@ -188,36 +219,50 @@ internal bool DispatchShortcut( object? target ) { if (keyEvent.repeat) + { return false; + } m_shortcutIndex ??= BuildShortcutIndex(); KeyModifier modifiers = new HotKeyGesture(keyEvent.key, keyEvent.modifiers).normalizedModifiers; _ = m_shortcutIndex.TryGetValue((keyEvent.key, modifiers, area), out string[]? exact); _ = m_shortcutIndex.TryGetValue((keyEvent.key, modifiers, string.Empty), out string[]? global); if (exact is null && global is null) + { return false; + } var context = new EditorActionContext(editor, interactions, area, target); var candidates = new List(); for (int pass = 0; pass < 2; pass++) { string[]? actionIds = pass == 0 ? exact : global; if (actionIds is null) + { continue; + } foreach (string action in actionIds) { if (pass == 1 && exact is not null && Array.IndexOf(exact, action) >= 0) + { continue; + } ResolvedAction? resolved = ResolveWithSpecificity(action, context); if (resolved is null) + { continue; + } EditorExtensionCatalog.ActionRegistration registration = resolved.Value.registration; bool hasExact = HasExactShortcut(registration, area); foreach (EditorShortcutAttribute shortcut in registration.shortcuts) { if (hasExact ? !string.Equals(shortcut.area, area, StringComparison.Ordinal) : !string.IsNullOrEmpty(shortcut.area)) + { continue; + } HotKeyGesture gesture = CreateGesture(shortcut); if (!gesture.Matches(keyEvent)) + { continue; + } candidates.Add(new ShortcutCandidate(action, resolved.Value, gesture)); break; } @@ -231,20 +276,30 @@ internal bool DispatchShortcut( { int areaComparison = right.resolved.exactArea.CompareTo(left.resolved.exactArea); if (areaComparison != 0) + { return areaComparison; + } int distanceComparison = left.resolved.targetDistance.CompareTo(right.resolved.targetDistance); if (distanceComparison != 0) + { return distanceComparison; - int priorityComparison = right.resolved.registration.attribute.priority.CompareTo(left.resolved.registration.attribute.priority); + } + int priorityComparison = right.resolved.registration.attribute.priority.CompareTo( + left.resolved.registration.attribute.priority + ); if (priorityComparison != 0) + { return priorityComparison; + } return string.Compare(left.action, right.action, StringComparison.Ordinal); }); for (int i = 0; i < candidates.Count; i++) { ShortcutCandidate candidate = candidates[i]; if (Execute(candidate.action, context)) + { return true; + } } return false; @@ -261,7 +316,9 @@ out HotKeyGesture gesture foreach (EditorShortcutAttribute shortcut in registration.shortcuts) { if (hasExact ? !string.Equals(shortcut.area, area, StringComparison.Ordinal) : !string.IsNullOrEmpty(shortcut.area)) + { continue; + } gesture = CreateGesture(shortcut); return true; } @@ -274,6 +331,7 @@ out HotKeyGesture gesture string action, EditorActionContext context ) => ResolveWithSpecificity(action, context)?.registration; + private ResolvedAction? ResolveWithSpecificity( string action, EditorActionContext context @@ -281,7 +339,9 @@ EditorActionContext context EditorExtensionCatalog.ActionRegistration? best = null; int bestDistance = int.MaxValue; if (!Index.TryGetValue(action, out EditorExtensionCatalog.ActionRegistration[]? registrations)) + { return null; + } foreach (EditorExtensionCatalog.ActionRegistration registration in registrations) { bool exactArea = registration.area is not null; @@ -309,19 +369,15 @@ EditorActionContext context bool bestExactArea = best?.area is not null; if (best is null || exactArea - && !bestExactArea + && !bestExactArea || exactArea == bestExactArea - && (distance < bestDistance - || distance == bestDistance - && registration.attribute.priority > best.attribute.priority - || distance == bestDistance - && registration.attribute.priority == best.attribute.priority - && string.Compare( - registration.type.FullName, - best.type.FullName, - StringComparison.Ordinal - ) < 0)) - { + && (distance < bestDistance + || distance == bestDistance + && registration.attribute.priority > best.attribute.priority + || distance == bestDistance + && registration.attribute.priority == best.attribute.priority + && string.Compare(registration.type.FullName, best.type.FullName, StringComparison.Ordinal) < 0) + ) { best = registration; bestDistance = distance; } @@ -338,10 +394,14 @@ IReadOnlySet placed foreach (string id in Index.Keys) { if (placed.Contains(id)) + { continue; + } EditorActionState state = Query(id, context); if (!state.isVisible) + { continue; + } string label = state.displayName ?? id; result.Add(new EditorMenuItem(label, id, 0, false, state)); } @@ -353,24 +413,17 @@ IReadOnlySet placed return result; } - private IReadOnlyDictionary Index => m_byId ??= catalog.extensions.actions.GroupBy( - static registration => registration.id, - StringComparer.Ordinal - ).ToDictionary( - static group => group.Key, - static group => group.ToArray(), - StringComparer.Ordinal - ); + private IReadOnlyDictionary Index + => m_byId ??= catalog.extensions.actions.GroupBy( + static registration => registration.id, + StringComparer.Ordinal + ).ToDictionary(static group => group.Key, static group => group.ToArray(), StringComparer.Ordinal); + + private HotKeyGesture CreateGesture(EditorShortcutAttribute shortcut) + => shortcut.primary + ? HotKeyGesture.Primary(shortcut.key, editor.keyboard, shortcut.modifiers) + : new HotKeyGesture(shortcut.key, shortcut.modifiers, editor.keyboard.superModifierLabel); - private HotKeyGesture CreateGesture(EditorShortcutAttribute shortcut) => shortcut.primary ? HotKeyGesture.Primary( - shortcut.key, - editor.keyboard, - shortcut.modifiers - ) : new HotKeyGesture( - shortcut.key, - shortcut.modifiers, - editor.keyboard.superModifierLabel - ); private Dictionary<(KeyCode key, KeyModifier modifiers, string area), string[]> BuildShortcutIndex() { var candidates = new Dictionary<(KeyCode key, KeyModifier modifiers, string area), HashSet>(); @@ -382,12 +435,16 @@ private HotKeyGesture CreateGesture(EditorShortcutAttribute shortcut) => shortcu string area = string.IsNullOrEmpty(shortcut.area) ? registration.area ?? string.Empty : shortcut.area; var key = (gesture.key, gesture.normalizedModifiers, area); if (!candidates.TryGetValue(key, out HashSet? actions)) + { candidates.Add(key, actions = new(StringComparer.Ordinal)); + } actions.Add(registration.id); } } - return candidates.ToDictionary(static pair => pair.Key, - static pair => pair.Value.OrderBy(static value => value, StringComparer.Ordinal).ToArray()); + return candidates.ToDictionary( + static pair => pair.Key, + static pair => pair.Value.OrderBy(static value => value, StringComparer.Ordinal).ToArray() + ); } private static bool HasExactShortcut( @@ -397,7 +454,9 @@ string area foreach (EditorShortcutAttribute shortcut in registration.shortcuts) { if (!string.IsNullOrEmpty(shortcut.area) && string.Equals(shortcut.area, area, StringComparison.Ordinal)) + { return true; + } } return false; } @@ -425,11 +484,13 @@ private sealed record PendingAction( EditorTargetReference argument, bool hasArgument ); + private readonly record struct ResolvedAction( EditorExtensionCatalog.ActionRegistration registration, int targetDistance, bool exactArea ); + private readonly record struct ShortcutCandidate( string action, ResolvedAction resolved, diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionState.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionState.cs index a0e834a59..2cb9a7110 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionState.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionState.cs @@ -1,4 +1,5 @@ namespace Inno.Editor.Interactions; + /// /// Describes the current presentation and availability of an editor action. /// @@ -40,30 +41,37 @@ public EditorActionState( /// Gets whether the action should be displayed. /// public bool isVisible { get; } + /// /// Gets whether the action can execute. /// public bool isEnabled { get; } + /// /// Gets whether the action is currently checked. /// public bool isChecked { get; } + /// /// Gets an optional contextual display name. /// public string? displayName { get; } + /// /// Gets the current execution barrier, or null when no specific explanation is available. /// public string? unavailableReason { get; } + /// /// Gets a visible and enabled action state. /// public static EditorActionState enabled => new(true, true); + /// /// Gets a visible but disabled action state. /// public static EditorActionState disabled => new(true, false); + /// /// Gets a hidden action state. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorShortcutAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorShortcutAttribute.cs index 41464dcf4..466522b81 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorShortcutAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorShortcutAttribute.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Input; namespace Inno.Editor.Interactions; @@ -26,10 +25,7 @@ public EditorShortcutAttribute( KeyCode key, KeyModifier modifiers = KeyModifier.None, bool primary = false - ) - : this(string.Empty, key, modifiers, primary) - { - } + ) : this(string.Empty, key, modifiers, primary) {} /// /// Creates a shortcut scoped to an exact interaction area. diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/HotKeyGesture.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/HotKeyGesture.cs index 834c45362..d12561e86 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/HotKeyGesture.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/HotKeyGesture.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Events; using Inno.Core.Input; using Inno.Editor.Core; @@ -83,13 +82,21 @@ public override string ToString() { string prefix = string.Empty; if ((modifiers & KeyModifier.Control) != 0) + { prefix += "Ctrl+"; + } if ((modifiers & KeyModifier.Super) != 0) + { prefix += (m_superModifierLabel ?? "Super") + "+"; + } if ((modifiers & KeyModifier.Alt) != 0) + { prefix += "Alt+"; + } if ((modifiers & KeyModifier.Shift) != 0) + { prefix += "Shift+"; + } return prefix + key; } @@ -104,9 +111,9 @@ public override string ToString() /// when the key and normalized modifiers match; otherwise, . /// internal bool Matches(KeyPressedEvent keyEvent) - => !keyEvent.repeat && - keyEvent.key == key && - Normalize(key, keyEvent.modifiers) == Normalize(key, modifiers); + => !keyEvent.repeat + && keyEvent.key == key + && Normalize(key, keyEvent.modifiers) == Normalize(key, modifiers); /// /// Gets the normalized modifiers used by generation-owned shortcut indexes. @@ -117,13 +124,13 @@ private static KeyModifier Normalize( KeyCode key, KeyModifier value ) { - KeyModifier normalized = value & - (KeyModifier.Alt | - KeyModifier.Control | - KeyModifier.Shift | - KeyModifier.Super); + KeyModifier normalized = value + & (KeyModifier.Alt + | KeyModifier.Control + | KeyModifier.Shift + | KeyModifier.Super); return key == KeyCode.Plus - ? normalized & ~KeyModifier.Shift - : normalized; + ? normalized & ~KeyModifier.Shift + : normalized; } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs index 01a941efd..44d737b55 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -31,15 +30,18 @@ internal EditorExtensionActivator( .OrderBy(static type => type.FullName, StringComparer.Ordinal) .ToArray(); m_hostServices = (hostServices ?? throw new ArgumentNullException(nameof(hostServices))).ToArray(); - var activeTypeSet = new HashSet( - activeTypes ?? throw new ArgumentNullException(nameof(activeTypes))); + var activeTypeSet = new HashSet(activeTypes ?? throw new ArgumentNullException(nameof(activeTypes))); if (retainedInstances is null) + { return; + } foreach (object instance in retainedInstances) { Type instanceType = instance.GetType(); if (activeTypeSet.Contains(instanceType)) + { m_instances.TryAdd(instanceType, instance); + } } } @@ -55,7 +57,7 @@ internal bool CanCreate(Type type) internal TExtension CreateExtension(Type type) where TExtension : class - => (TExtension)Create(type, typeof(TExtension)); + => (TExtension)Create(type, typeof(TExtension)); private bool CanCreate( Type type, @@ -72,7 +74,8 @@ HashSet visiting } ConstructorInfo[] constructors = type.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); if (constructors.Length != 1 || !visiting.Add(type)) { return true; @@ -84,8 +87,8 @@ HashSet visiting Type parameterType = parameter.ParameterType; if (parameterType == typeof(EditorContext) || IsInteractionContract(parameterType) - || parameterType == typeof(IEditorDocumentService)) - { + || parameterType == typeof(IEditorDocumentService) + ) { continue; } @@ -99,8 +102,8 @@ HashSet visiting .Where(parameterType.IsAssignableFrom) .ToArray(); if (matches.Length == 0 - || matches.Length == 1 && !CanCreate(matches[0], visiting)) - { + || matches.Length == 1 && !CanCreate(matches[0], visiting) + ) { result = false; break; } @@ -118,14 +121,21 @@ Type contract if (m_instances.TryGetValue(type, out object? existing)) { if (!contract.IsInstanceOfType(existing)) + { throw CreateContractException(type, contract); + } return existing; } if (type.IsAbstract || !contract.IsAssignableFrom(type)) + { throw CreateContractException(type, contract); + } if (!m_constructing.Add(type)) + { throw new InvalidOperationException( - $"Editor extension constructor dependency cycle contains '{type.FullName}'."); + $"Editor extension constructor dependency cycle contains '{type.FullName}'." + ); + } try { @@ -133,7 +143,9 @@ Type contract ParameterInfo[] parameters = constructor.GetParameters(); var arguments = new object?[parameters.Length]; for (int i = 0; i < parameters.Length; i++) + { arguments[i] = Resolve(parameters[i].ParameterType, type); + } object instance; try { @@ -143,7 +155,8 @@ Type contract { throw new InvalidOperationException( $"Editor extension '{type.FullName}' constructor failed.", - exception.InnerException ?? exception); + exception.InnerException ?? exception + ); } m_instances.Add(type, instance); return instance; @@ -159,51 +172,68 @@ private object Resolve( Type ownerType ) { if (parameterType == typeof(EditorContext)) + { return m_context; + } if (IsInteractionContract(parameterType)) + { return m_interactions; + } if (parameterType == typeof(IEditorDocumentService)) + { return m_interactions.documents; + } object[] services = m_hostServices .Where(parameterType.IsInstanceOfType) .ToArray(); if (services.Length == 1) + { return services[0]; + } if (services.Length > 1) { throw new InvalidOperationException( - $"Editor extension '{ownerType.FullName}' has ambiguous host service dependency " + - $"'{parameterType.FullName}'."); + $"Editor extension '{ownerType.FullName}' has ambiguous host service dependency " + + $"'{parameterType.FullName}'." + ); } Type[] matches = m_moduleTypes .Where(parameterType.IsAssignableFrom) .ToArray(); if (matches.Length == 1) + { return CreateModule(matches[0]); + } if (matches.Length == 0) { throw new InvalidOperationException( - $"Editor extension '{ownerType.FullName}' requests unsupported constructor dependency " + - $"'{parameterType.FullName}'. Only EditorContext, EditorInteractions, and discovered " + - "EditorModule types or explicit host services are injectable."); + $"Editor extension '{ownerType.FullName}' requests unsupported constructor dependency " + + $"'{parameterType.FullName}'. Only EditorContext, EditorInteractions, and discovered " + + "EditorModule types or explicit host services are injectable." + ); } throw new InvalidOperationException( - $"Editor extension '{ownerType.FullName}' has ambiguous module dependency " + - $"'{parameterType.FullName}': {string.Join(", ", matches.Select(static type => type.FullName))}."); + $"Editor extension '{ownerType.FullName}' has ambiguous module dependency " + + $"'{parameterType.FullName}': {string.Join(", ", matches.Select(static type => type.FullName))}." + ); } private static ConstructorInfo SelectConstructor(Type type) { ConstructorInfo[] constructors = type.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); if (constructors.Length == 0) + { throw new InvalidOperationException($"Editor extension '{type.FullName}' has no instance constructor."); + } if (constructors.Length > 1) { throw new InvalidOperationException( - $"Editor extension '{type.FullName}' must declare exactly one constructor."); + $"Editor extension '{type.FullName}' must declare exactly one constructor." + ); } return constructors[0]; } @@ -213,6 +243,5 @@ private static ConstructorInfo SelectConstructor(Type type) private static InvalidOperationException CreateContractException( Type type, Type contract - ) - => new($"Editor extension '{type.FullName}' must be a non-abstract '{contract.FullName}'."); + ) => new($"Editor extension '{type.FullName}' must be a non-abstract '{contract.FullName}'."); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs index b6c9fd6e5..ead1bdd6e 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs @@ -4,10 +4,11 @@ using System.Reflection; using Inno.Core.Execution; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Editor.Core; +using Inno.Extensibility.Types; namespace Inno.Editor.Interactions; + internal sealed class EditorExtensionCatalog : TypeRegistry { private readonly EditorContext m_context; @@ -22,6 +23,7 @@ internal sealed class EditorExtensionCatalog : TypeRegistry service ?? throw new ArgumentException("Host services cannot contain null.", nameof(hostServices))).ToArray(); + m_hostServices = hostServices + .Select(static service => service ?? throw new ArgumentException("Host services cannot contain null.", nameof(hostServices))) + .ToArray(); m_extensionsChanged = extensionsChanged ?? throw new ArgumentNullException(nameof(extensionsChanged)); m_state = new EditorExtensionStateStore(context, log); } @@ -46,7 +50,9 @@ internal Snapshot extensions { Snapshot snapshot = current; if (!ReferenceEquals(snapshot, m_active) && !ReferenceEquals(snapshot, m_staging)) + { throw new InvalidOperationException("The extension registry returned an unpublished snapshot."); + } return snapshot; } } @@ -56,12 +62,18 @@ internal bool TryGetModule(out TModule? module) { Snapshot? snapshot = m_active; if (snapshot is not null) + { foreach (ModuleRegistration registration in snapshot.modules) - if (registration.module is TModule candidate && snapshot.startedModules.Contains(candidate) && !snapshot.quarantinedModules.Contains(candidate)) - { + { + if (registration.module is TModule candidate + && snapshot.startedModules.Contains(candidate) + && !snapshot.quarantinedModules.Contains(candidate) + ) { module = candidate; return true; } + } + } module = null; return false; @@ -74,12 +86,16 @@ internal void UpdateModules() { ModuleRegistration registration = snapshot.modules[i]; if (snapshot.quarantinedModules.Contains(registration.module)) + { continue; + } try { registration.module.Update(m_context); if (registration.module.blocksFollowingUpdates) + { break; + } } catch (Exception exception) { @@ -95,7 +111,9 @@ internal void UpdateModules() internal void SaveState() { if (m_active is not null) + { m_state.Save(GetAvailableState(m_active), GetAvailablePanels(m_active)); + } } internal bool TryTogglePanel(string panelId) @@ -105,16 +123,21 @@ internal bool TryTogglePanel(string panelId) for (int i = 0; i < snapshot.panels.Length; i++) { PanelRegistration registration = snapshot.panels[i]; - if (!string.Equals(registration.attribute.id, panelId, StringComparison.Ordinal) || snapshot.quarantinedPanels.Contains(registration.panel)) - { + if (!string.Equals(registration.attribute.id, panelId, StringComparison.Ordinal) + || snapshot.quarantinedPanels.Contains(registration.panel) + ) { continue; } registration.panel.isOpen = !registration.panel.isOpen; if (registration.panel.isOpen) + { m_pendingPanelFocus.Add(panelId); + } else + { m_pendingPanelFocus.Remove(panelId); + } return true; } @@ -122,6 +145,7 @@ internal bool TryTogglePanel(string panelId) } internal IReadOnlyList GetPanelDeclarations() => extensions.panelDeclarations; + internal bool TryGetPanelState( string panelId, out bool isOpen @@ -130,7 +154,9 @@ out bool isOpen foreach (PanelRegistration registration in snapshot.panels) { if (registration.attribute.id != panelId || snapshot.quarantinedPanels.Contains(registration.panel)) + { continue; + } isOpen = registration.panel.isOpen; return true; } @@ -146,8 +172,9 @@ internal bool TryOpenPanel(string panelId) for (int i = 0; i < snapshot.panels.Length; i++) { PanelRegistration registration = snapshot.panels[i]; - if (!string.Equals(registration.attribute.id, panelId, StringComparison.Ordinal) || snapshot.quarantinedPanels.Contains(registration.panel)) - { + if (!string.Equals(registration.attribute.id, panelId, StringComparison.Ordinal) + || snapshot.quarantinedPanels.Contains(registration.panel) + ) { continue; } @@ -166,8 +193,9 @@ internal bool TryClosePanel(string panelId) for (int i = 0; i < snapshot.panels.Length; i++) { PanelRegistration registration = snapshot.panels[i]; - if (!string.Equals(registration.attribute.id, panelId, StringComparison.Ordinal) || snapshot.quarantinedPanels.Contains(registration.panel)) - { + if (!string.Equals(registration.attribute.id, panelId, StringComparison.Ordinal) + || snapshot.quarantinedPanels.Contains(registration.panel) + ) { continue; } @@ -180,13 +208,17 @@ internal bool TryClosePanel(string panelId) } internal bool TakePanelFocusRequest(string panelId) => m_pendingPanelFocus.Remove(panelId); + internal void PrepareShutdown() { if (m_active is not null) + { m_state.PrepareShutdown(GetAvailableState(m_active), GetAvailablePanels(m_active)); + } } internal ActionRegistration[] GetActionsForShutdown() => m_active?.actions ?? []; + internal void QuarantinePanel( Snapshot snapshot, PanelRegistration registration, @@ -196,7 +228,9 @@ Exception exception ArgumentNullException.ThrowIfNull(registration); ArgumentNullException.ThrowIfNull(exception); if (!ReferenceEquals(snapshot, m_active) || !snapshot.quarantinedPanels.Add(registration.panel)) + { return; + } registration.panel.isOpen = false; m_diagnostics.ReportPanelFailure(registration.attribute.id, exception); m_diagnostics.Commit(); @@ -212,7 +246,9 @@ Exception exception ArgumentNullException.ThrowIfNull(registration); ArgumentNullException.ThrowIfNull(exception); if (!ReferenceEquals(snapshot, m_active) || !snapshot.quarantinedModals.Add(registration.modal)) + { return; + } LogError("Editor modal '{0}' failed and was quarantined: {1}", registration.attribute.id, exception); } @@ -223,7 +259,9 @@ internal void Shutdown(bool saveState = true) { Snapshot active = m_active; if (saveState) + { AttemptCleanup(() => m_state.PrepareShutdown(GetAvailableState(active), GetAvailablePanels(active)), failures); + } AttemptCleanup(() => Deactivate(active), failures); } @@ -258,56 +296,66 @@ protected override Snapshot Build(TypeCacheSnapshot types) m_hostServices, m_active?.instances ); - ModuleRegistration[] modules = moduleTypes.Where(activator.CanCreate).Select(type => new ModuleRegistration(type.GetCustomAttribute(false)!, type, activator.CreateModule(type))).OrderBy(static value => value.attribute.order).ThenBy( - static value => value.type.FullName, - StringComparer.Ordinal - ).ToArray(); - ActionRegistration[] actions = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - ).Where(activator.CanCreate).Select(type => CreateActionRegistration(type, activator)).ToArray(); + ModuleRegistration[] modules = moduleTypes + .Where(activator.CanCreate) + .Select( + type => new ModuleRegistration(type.GetCustomAttribute(false)!, type, activator.CreateModule(type)) + ) + .OrderBy(static value => value.attribute.order) + .ThenBy(static value => value.type.FullName, StringComparer.Ordinal) + .ToArray(); + ActionRegistration[] actions = types + .GetTypesWithAttribute() + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + .Where(activator.CanCreate) + .Select(type => CreateActionRegistration(type, activator)) + .ToArray(); ValidateActions(actions); ValidateShortcuts(actions); ValidateToolbars(actions); - MenuSourceRegistration[] menuSources = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - ).Where(activator.CanCreate).SelectMany(type => CreateMenuSourceRegistrations(type, activator)).OrderByDescending(static value => value.priority).ThenBy( - static value => value.type.FullName, - StringComparer.Ordinal - ).ToArray(); + MenuSourceRegistration[] menuSources = types + .GetTypesWithAttribute() + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + .Where(activator.CanCreate) + .SelectMany(type => CreateMenuSourceRegistrations(type, activator)) + .OrderByDescending(static value => value.priority) + .ThenBy(static value => value.type.FullName, StringComparer.Ordinal) + .ToArray(); DropRegistration[] drops = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( static type => type.FullName, StringComparer.Ordinal ).Where(activator.CanCreate).SelectMany(type => CreateDropRegistrations(type, activator)).ToArray(); ValidateDrops(drops); - PanelRegistration[] panels = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - ).Where(activator.CanCreate).Select(type => CreatePanelRegistration(type, activator)).OrderBy(static value => value.attribute.order).ThenBy( - static value => value.type.FullName, - StringComparer.Ordinal - ).ToArray(); + PanelRegistration[] panels = types.GetTypesWithAttribute() + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + .Where(activator.CanCreate) + .Select(type => CreatePanelRegistration(type, activator)) + .OrderBy(static value => value.attribute.order) + .ThenBy(static value => value.type.FullName, StringComparer.Ordinal) + .ToArray(); ValidatePanels(panels); ValidateExtensionIds(modules, panels); - ModalRegistration[] modals = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - ).Where(activator.CanCreate).Select(type => CreateModalRegistration(type, activator)).OrderBy(static value => value.attribute.order).ThenBy( - static value => value.type.FullName, - StringComparer.Ordinal - ).ToArray(); + ModalRegistration[] modals = types.GetTypesWithAttribute() + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + .Where(activator.CanCreate) + .Select(type => CreateModalRegistration(type, activator)) + .OrderBy(static value => value.attribute.order) + .ThenBy(static value => value.type.FullName, StringComparer.Ordinal) + .ToArray(); ValidateModals(modals); - HistoryHandlerRegistration[] historyHandlers = types.GetTypesWithAttribute().Select(typeRef => typeRef.Resolve(types)).OrderBy( - static type => type.FullName, - StringComparer.Ordinal - ).Where(activator.CanCreate).Select(type => CreateHistoryHandlerRegistration(type, activator)).OrderBy( - static value => value.attribute.kind, - StringComparer.Ordinal - ).ThenBy( - static value => value.type.FullName, - StringComparer.Ordinal - ).ToArray(); + HistoryHandlerRegistration[] historyHandlers = types + .GetTypesWithAttribute() + .Select(typeRef => typeRef.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + .Where(activator.CanCreate) + .Select(type => CreateHistoryHandlerRegistration(type, activator)) + .OrderBy(static value => value.attribute.kind, StringComparer.Ordinal) + .ThenBy(static value => value.type.FullName, StringComparer.Ordinal) + .ToArray(); ValidateHistoryHandlers(historyHandlers); StateRegistration[] state = CreateStateRegistrations(modules, panels); return new Snapshot(modules, actions, menuSources, drops, panels, modals, historyHandlers, state, activator.instances.ToArray()); @@ -327,14 +375,24 @@ protected override void OnActivating( Snapshot candidate ) { if (m_activation is not null) + { throw new InvalidOperationException("An extension generation transition is already active."); + } m_interactions.PrepareOperation(); if (previous is not null) + { CapturePanelStates(previous); + } if (previous is not null) + { m_state.Save(GetAvailableState(previous), GetAvailablePanels(previous)); - var existing = previous is null ? new HashSet(ReferenceEqualityComparer.Instance) : new HashSet(previous.instances, ReferenceEqualityComparer.Instance); - EditorHistory.HandlerUpdate handlers = m_interactions.historyHost.PrepareHandlerUpdate(CreateHistoryHandlerMap(candidate.historyHandlers)); + } + var existing = previous is null + ? new HashSet(ReferenceEqualityComparer.Instance) + : new HashSet(previous.instances, ReferenceEqualityComparer.Instance); + EditorHistory.HandlerUpdate handlers = m_interactions.historyHost.PrepareHandlerUpdate( + CreateHistoryHandlerMap(candidate.historyHandlers) + ); var activation = new ActivationState(previous, candidate, existing, handlers); m_activation = activation; m_staging = candidate; @@ -345,30 +403,40 @@ Snapshot candidate foreach (ModuleRegistration registration in candidate.modules) { if (existing.Contains(registration.module) && previous.startedModules.Contains(registration.module)) + { candidate.startedModules.Add(registration.module); + } } foreach (PanelRegistration registration in candidate.panels) { if (existing.Contains(registration.panel) && previous.attachedPanels.Contains(registration.panel)) + { candidate.attachedPanels.Add(registration.panel); + } } } if (previous is not null) + { RetirePrevious(previous, candidate, activation); + } for (int i = 0; i < candidate.modules.Length; i++) { ModuleRegistration registration = candidate.modules[i]; if (existing.Contains(registration.module)) + { continue; + } activation.startedModules.Add(registration); candidate.startedModules.Add(registration.module); registration.module.Start(m_context); } var retainedPanelIds = new HashSet( - candidate.panels.Where(registration => existing.Contains(registration.panel)).Select(static registration => registration.attribute.id), + candidate.panels + .Where(registration => existing.Contains(registration.panel)) + .Select(static registration => registration.attribute.id), StringComparer.Ordinal ); m_diagnostics.RetainPanels(retainedPanelIds); @@ -376,7 +444,9 @@ Snapshot candidate { PanelRegistration registration = candidate.panels[i]; if (existing.Contains(registration.panel)) + { continue; + } activation.attachedPanels.Add(registration); candidate.attachedPanels.Add(registration.panel); try @@ -418,7 +488,9 @@ Snapshot candidate m_active = previous; m_staging = null; if (activation is null || !ReferenceEquals(activation.candidate, candidate)) + { return; + } List failures = []; AttemptCleanup(activation.handlers.Rollback, failures); AttemptCleanup(m_interactions.RollbackGenerationTransition, failures); @@ -462,7 +534,9 @@ Snapshot currentSnapshot ) { ActivationState? activation = m_activation; if (activation is null || !ReferenceEquals(activation.candidate, currentSnapshot)) + { return; + } activation.handlers.Complete(); m_interactions.CompleteGenerationTransition(); NotifyExtensionsChanged(); @@ -489,7 +563,9 @@ private void Deactivate(Snapshot snapshot) { PanelRegistration registration = snapshot.panels[i]; if (!snapshot.attachedPanels.Contains(registration.panel)) + { continue; + } AttemptCleanup(() => DetachPanel(registration, "shutdown"), failures); snapshot.attachedPanels.Remove(registration.panel); } @@ -498,13 +574,17 @@ private void Deactivate(Snapshot snapshot) { ModuleRegistration registration = snapshot.modules[i]; if (!snapshot.startedModules.Contains(registration.module)) + { continue; + } AttemptCleanup(() => StopModule(registration, "shutdown"), failures); snapshot.startedModules.Remove(registration.module); } if (ReferenceEquals(m_active, snapshot)) + { m_active = null; + } m_diagnostics.RetainPanels(new HashSet(StringComparer.Ordinal)); m_diagnostics.Commit(); ThrowCleanupFailures(failures); @@ -520,7 +600,9 @@ ActivationState activation { PanelRegistration registration = previous.panels[i]; if (retained.Contains(registration.panel) || !previous.attachedPanels.Contains(registration.panel)) + { continue; + } activation.detachedPreviousPanels.Add(registration); DetachPanel(registration, "generation retirement"); previous.attachedPanels.Remove(registration.panel); @@ -541,7 +623,9 @@ private void RestorePrevious(ActivationState activation) { Snapshot? previous = activation.previous; if (previous is null) + { return; + } List failures = []; for (int i = activation.stoppedPreviousModules.Count - 1; i >= 0; i--) { @@ -583,20 +667,41 @@ private void RestorePrevious(ActivationState activation) private void CapturePanelStates() { if (m_active is not null) + { CapturePanelStates(m_active); + } } private void CapturePanelStates(Snapshot snapshot) { foreach (PanelRegistration registration in snapshot.panels) { - ReadOnlyMemory payload = registration.panel is IEditorPanelReloadState reloadable ? reloadable.CaptureReloadState().ToArray() : ReadOnlyMemory.Empty; + ReadOnlyMemory payload = registration.panel is IEditorPanelReloadState reloadable + ? reloadable.CaptureReloadState().ToArray() + : ReadOnlyMemory.Empty; m_panelStates[registration.attribute.id] = new PanelState(registration.panel.isOpen, payload); } } - private static StateRegistration[] GetAvailableState(Snapshot snapshot) => snapshot.state.Where(registration => registration.kind != StateOwnerKind.Panel || !snapshot.quarantinedPanels.Contains((EditorPanel)registration.owner)).Where(registration => registration.kind != StateOwnerKind.Module || !snapshot.quarantinedModules.Contains((EditorModule)registration.owner)).ToArray(); - private static PanelRegistration[] GetAvailablePanels(Snapshot snapshot) => snapshot.panels.Where(registration => !snapshot.quarantinedPanels.Contains(registration.panel)).ToArray(); + private static StateRegistration[] GetAvailableState(Snapshot snapshot) + => snapshot.state + .Where( + registration => ( + registration.kind != StateOwnerKind.Panel + || !snapshot.quarantinedPanels.Contains((EditorPanel)registration.owner) + ) + ) + .Where( + registration => ( + registration.kind != StateOwnerKind.Module + || !snapshot.quarantinedModules.Contains((EditorModule)registration.owner) + ) + ) + .ToArray(); + + private static PanelRegistration[] GetAvailablePanels(Snapshot snapshot) + => snapshot.panels.Where(registration => !snapshot.quarantinedPanels.Contains(registration.panel)).ToArray(); + private void StopModule( ModuleRegistration registration, string phase @@ -650,7 +755,9 @@ List failures private void ThrowCleanupFailures(List failures) { if (failures.Count == 0) + { return; + } var failure = new AggregateException("Editor extension lifecycle cleanup failed.", failures); ReportRetirementFailure(failure); throw failure; @@ -684,12 +791,15 @@ private void LogError( string message, params object? [] arguments ) => m_log.Write(LogLevel.Error, message, arguments); + private static IEnumerable CreateMenuSourceRegistrations( Type type, EditorExtensionActivator activator ) { EditorMenuSource source = activator.CreateExtension(type); - return type.GetCustomAttributes(false).Select(attribute => new MenuSourceRegistration(attribute.area, attribute.priority, type, source)); + return type + .GetCustomAttributes(false) + .Select(attribute => new MenuSourceRegistration(attribute.area, attribute.priority, type, source)); } private static IEnumerable CreateDropRegistrations( @@ -699,7 +809,9 @@ EditorExtensionActivator activator EditorDrop drop = activator.CreateExtension(type); Type sourceType = drop.sourceType; Type targetType = drop.targetType; - return type.GetCustomAttributes(false).Select(attribute => new DropRegistration(sourceType, targetType, attribute.area, attribute.priority, type, drop)); + return type + .GetCustomAttributes(false) + .Select(attribute => new DropRegistration(sourceType, targetType, attribute.area, attribute.priority, type, drop)); } private PanelRegistration CreatePanelRegistration( @@ -712,7 +824,9 @@ EditorExtensionActivator activator { panel.isOpen = state.isOpen; if (panel is IEditorPanelReloadState reloadable && !state.payload.IsEmpty) + { reloadable.RestoreReloadState(state.payload); + } } else { @@ -726,17 +840,24 @@ private static ModalRegistration CreateModalRegistration( Type type, EditorExtensionActivator activator ) => new(type.GetCustomAttribute(false)!, type, activator.CreateExtension(type)); + private static HistoryHandlerRegistration CreateHistoryHandlerRegistration( Type type, EditorExtensionActivator activator ) => new(type.GetCustomAttribute(false)!, type, activator.CreateExtension(type)); + private static void ValidateActions(ActionRegistration[] actions) { - foreach (IGrouping<(string Action, string Area, Type? Target, int Priority), ActionRegistration> group in actions.GroupBy(static value => (value.attribute.action, value.attribute.area, value.targetType, value.attribute.priority))) - { + foreach (IGrouping<(string Action, string Area, Type? Target, int Priority), ActionRegistration> group in actions.GroupBy( + static value => (value.attribute.action, value.attribute.area, value.targetType, value.attribute.priority) + )) { if (group.Count() > 1) { - throw new InvalidOperationException($"Editor action '{group.Key.Action}' has conflicting registrations for area " + $"'{(string.IsNullOrEmpty(group.Key.Area) ? "*" : group.Key.Area)}' and target " + $"'{group.Key.Target?.FullName ?? "*"}'."); + throw new InvalidOperationException( + $"Editor action '{group.Key.Action}' has conflicting registrations for area " + + $"'{(string.IsNullOrEmpty(group.Key.Area) ? "*" : group.Key.Area)}' and target " + + $"'{group.Key.Target?.FullName ?? "*"}'." + ); } } } @@ -752,13 +873,11 @@ private void ValidateShortcuts(ActionRegistration[] actions) EditorShortcutAttribute shortcut = registration.shortcuts[shortcutIndex]; if (!string.IsNullOrEmpty(registration.attribute.area) && !string.IsNullOrEmpty(shortcut.area) - && !string.Equals( - registration.attribute.area, - shortcut.area, - StringComparison.Ordinal - )) - { - throw new InvalidOperationException($"Editor shortcut on '{registration.id}' targets area '{shortcut.area}', " + $"outside its action area '{registration.attribute.area}'."); + && !string.Equals(registration.attribute.area, shortcut.area, StringComparison.Ordinal) + ) { + throw new InvalidOperationException( + $"Editor shortcut on '{registration.id}' targets area '{shortcut.area}', " + $"outside its action area '{registration.attribute.area}'." + ); } string effectiveArea = string.IsNullOrEmpty(shortcut.area) ? registration.attribute.area : shortcut.area; @@ -775,25 +894,24 @@ private void ValidateShortcuts(ActionRegistration[] actions) bool sameAction = string.Equals(left.registration.id, right.registration.id, StringComparison.Ordinal); if (left.gesture != right.gesture || left.registration.attribute.priority != right.registration.attribute.priority - || !string.Equals( - left.area, - right.area, - StringComparison.Ordinal - ) - || !MayHaveEqualTargetSpecificity( - left.registration.targetType, - right.registration.targetType - )) - { + || !string.Equals(left.area, right.area, StringComparison.Ordinal) + || !MayHaveEqualTargetSpecificity(left.registration.targetType, right.registration.targetType) + ) { continue; } if (sameAction) { - throw new InvalidOperationException($"Editor action '{left.registration.id}' declares duplicate shortcut " + $"'{left.gesture}' for area '{(string.IsNullOrEmpty(left.area) ? "*" : left.area)}'."); + throw new InvalidOperationException( + $"Editor action '{left.registration.id}' declares duplicate shortcut " + $"'{left.gesture}' for area '{(string.IsNullOrEmpty(left.area) ? "*" : left.area)}'." + ); } - throw new InvalidOperationException($"Editor shortcut '{left.gesture}' is ambiguous between actions " + $"'{left.registration.id}' and '{right.registration.id}' for area " + $"'{(string.IsNullOrEmpty(left.area) ? "*" : left.area)}'."); + throw new InvalidOperationException( + $"Editor shortcut '{left.gesture}' is ambiguous between actions " + + $"'{left.registration.id}' and '{right.registration.id}' for area " + + $"'{(string.IsNullOrEmpty(left.area) ? "*" : left.area)}'." + ); } } } @@ -803,9 +921,13 @@ private static bool MayHaveEqualTargetSpecificity( Type? right ) { if (left == right) + { return true; + } if (left is null || right is null) + { return false; + } return left.IsInterface || right.IsInterface; } @@ -815,7 +937,9 @@ private static void ValidateToolbars(IReadOnlyList actions) { ActionRegistration registration = actions[actionIndex]; if (registration.toolbars.Length == 0) + { continue; + } if (registration.targetType is not null || registration.argumentType is not null) { throw new InvalidOperationException($"Editor toolbar action '{registration.id}' must not require a target or argument."); @@ -824,67 +948,84 @@ private static void ValidateToolbars(IReadOnlyList actions) for (int toolbarIndex = 0; toolbarIndex < registration.toolbars.Length; toolbarIndex++) { EditorToolbarItemAttribute toolbar = registration.toolbars[toolbarIndex]; - if (!string.IsNullOrEmpty(registration.attribute.area) && !string.Equals(registration.attribute.area, toolbar.area, StringComparison.Ordinal)) - { - throw new InvalidOperationException($"Editor toolbar placement on '{registration.id}' targets area '{toolbar.area}', " + $"outside its action area '{registration.attribute.area}'."); + if (!string.IsNullOrEmpty(registration.attribute.area) + && !string.Equals(registration.attribute.area, toolbar.area, StringComparison.Ordinal) + ) { + throw new InvalidOperationException( + $"Editor toolbar placement on '{registration.id}' targets area '{toolbar.area}', " + $"outside its action area '{registration.attribute.area}'." + ); } } } - IGrouping<(string id, string area), (string id, string area)>? duplicate = actions.SelectMany(static registration => registration.toolbars.Select(toolbar => (registration.id, toolbar.area))).GroupBy( - static placement => placement, - EqualityComparer<(string id, string area)>.Default - ).FirstOrDefault(static group => group.Count() > 1); + IGrouping<(string id, string area), (string id, string area)>? duplicate = actions + .SelectMany(static registration => registration.toolbars.Select(toolbar => (registration.id, toolbar.area))) + .GroupBy(static placement => placement, EqualityComparer<(string id, string area)>.Default) + .FirstOrDefault(static group => group.Count() > 1); if (duplicate is not null) + { throw new InvalidOperationException($"Editor action '{duplicate.Key.id}' has duplicate toolbar placements."); + } } - private HotKeyGesture CreateShortcutGesture(EditorShortcutAttribute shortcut) => shortcut.primary ? HotKeyGesture.Primary( - shortcut.key, - m_context.keyboard, - shortcut.modifiers - ) : new HotKeyGesture( - shortcut.key, - shortcut.modifiers, - m_context.keyboard.superModifierLabel - ); + private HotKeyGesture CreateShortcutGesture(EditorShortcutAttribute shortcut) + => shortcut.primary + ? HotKeyGesture.Primary(shortcut.key, m_context.keyboard, shortcut.modifiers) + : new HotKeyGesture(shortcut.key, shortcut.modifiers, m_context.keyboard.superModifierLabel); + private static void ValidateDrops(DropRegistration[] drops) { - foreach (IGrouping<(Type Source, Type Target, string Area, int Priority), DropRegistration> group in drops.GroupBy(static value => (value.sourceType, value.targetType, value.area, value.priority))) - { + foreach (IGrouping<(Type Source, Type Target, string Area, int Priority), DropRegistration> group in drops.GroupBy( + static value => (value.sourceType, value.targetType, value.area, value.priority) + )) { if (group.Count() > 1) + { throw new InvalidOperationException("Editor drop registrations contain an ambiguous match."); + } } } private static void ValidatePanels(PanelRegistration[] panels) { - string? duplicate = panels.GroupBy(static value => value.attribute.id, StringComparer.Ordinal).FirstOrDefault(static group => group.Count() > 1)?.Key; + string? duplicate = panels + .GroupBy(static value => value.attribute.id, StringComparer.Ordinal) + .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) + { throw new InvalidOperationException($"Editor panel id '{duplicate}' is registered more than once."); + } } private static void ValidateModals(ModalRegistration[] modals) { - string? duplicate = modals.GroupBy(static value => value.attribute.id, StringComparer.Ordinal).FirstOrDefault(static group => group.Count() > 1)?.Key; + string? duplicate = modals + .GroupBy(static value => value.attribute.id, StringComparer.Ordinal) + .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) + { throw new InvalidOperationException($"Editor modal id '{duplicate}' is registered more than once."); + } } private static void ValidateHistoryHandlers(HistoryHandlerRegistration[] handlers) { - string? duplicate = handlers.GroupBy(static value => value.attribute.kind, StringComparer.Ordinal).FirstOrDefault(static group => group.Count() > 1)?.Key; + string? duplicate = handlers + .GroupBy(static value => value.attribute.kind, StringComparer.Ordinal) + .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) { throw new InvalidOperationException($"Editor history handler kind '{duplicate}' is registered more than once."); } } - private static IReadOnlyDictionary CreateHistoryHandlerMap(IReadOnlyList handlers) - { + private static IReadOnlyDictionary CreateHistoryHandlerMap( + IReadOnlyList handlers + ) { var result = new Dictionary(handlers.Count, StringComparer.Ordinal); for (int i = 0; i < handlers.Count; i++) + { result.Add(handlers[i].attribute.kind, handlers[i].handler); + } return result; } @@ -892,12 +1033,15 @@ private static void ValidateExtensionIds( IReadOnlyList modules, IReadOnlyList panels ) { - string? duplicate = modules.Select(static value => value.attribute.id).Concat(panels.Select(static value => value.attribute.id)).GroupBy( - static id => id, - StringComparer.Ordinal - ).FirstOrDefault(static group => group.Count() > 1)?.Key; + string? duplicate = modules + .Select(static value => value.attribute.id) + .Concat(panels.Select(static value => value.attribute.id)) + .GroupBy(static id => id, StringComparer.Ordinal) + .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) + { throw new InvalidOperationException($"Editor extension id '{duplicate}' is registered more than once."); + } } private static StateRegistration[] CreateStateRegistrations( @@ -908,17 +1052,33 @@ IReadOnlyList panels for (int i = 0; i < modules.Count; i++) { ModuleRegistration module = modules[i]; - StateRegistration? registration = CreateStateRegistration(module.attribute.id, StateOwnerKind.Module, module.type, module.module, typeof(EditorModule)); + StateRegistration? registration = CreateStateRegistration( + module.attribute.id, + StateOwnerKind.Module, + module.type, + module.module, + typeof(EditorModule) + ); if (registration is not null) + { result.Add(registration); + } } for (int i = 0; i < panels.Count; i++) { PanelRegistration panel = panels[i]; - StateRegistration? registration = CreateStateRegistration(panel.attribute.id, StateOwnerKind.Panel, panel.type, panel.panel, typeof(EditorPanel)); + StateRegistration? registration = CreateStateRegistration( + panel.attribute.id, + StateOwnerKind.Panel, + panel.type, + panel.panel, + typeof(EditorPanel) + ); if (registration is not null) + { result.Add(registration); + } } return result.OrderBy(static value => value.id, StringComparer.Ordinal).ToArray(); @@ -940,7 +1100,9 @@ Type baseType modifiers: null ) ?? throw new InvalidOperationException($"Editor extension '{type.FullName}' has no state capture hook."); if (capture.DeclaringType == baseType) + { return null; + } MethodInfo restore = type.GetMethod( "Restore", flags, @@ -948,7 +1110,13 @@ Type baseType [typeof(EditorState)], modifiers: null ) ?? throw new InvalidOperationException($"Editor extension '{type.FullName}' has no state restore hook."); - return new StateRegistration(id, kind, owner, capture.CreateDelegate>(owner), restore.CreateDelegate>(owner)); + return new StateRegistration( + id, + kind, + owner, + capture.CreateDelegate>(owner), + restore.CreateDelegate>(owner) + ); } internal sealed record Snapshot( @@ -961,9 +1129,11 @@ internal sealed record Snapshot( HistoryHandlerRegistration[] historyHandlers, StateRegistration[] state, object[] instances - ) - { - internal IReadOnlyList panelDeclarations { get; } = Array.AsReadOnly(panels.Select(static registration => registration.attribute).ToArray()); + ) { + internal IReadOnlyList panelDeclarations { get; } = Array.AsReadOnly( + panels.Select(static registration => registration.attribute).ToArray() + ); + internal HashSet quarantinedModules { get; } = new(ReferenceEqualityComparer.Instance); internal HashSet quarantinedPanels { get; } = new(ReferenceEqualityComparer.Instance); internal HashSet quarantinedModals { get; } = new(ReferenceEqualityComparer.Instance); @@ -976,6 +1146,7 @@ internal sealed record ModuleRegistration( Type type, EditorModule module ); + internal sealed record ActionRegistration( EditorActionAttribute attribute, Type type, @@ -985,8 +1156,7 @@ internal sealed record ActionRegistration( EditorMenuAttribute[] menus, EditorToolbarItemAttribute[] toolbars, EditorShortcutAttribute[] shortcuts - ) - { + ) { internal string id { get; } = attribute.action; internal string? area { get; } = string.IsNullOrEmpty(attribute.area) ? null : attribute.area; } @@ -997,6 +1167,7 @@ internal sealed record MenuSourceRegistration( Type type, EditorMenuSource source ); + internal sealed record DropRegistration( Type sourceType, Type targetType, @@ -1005,21 +1176,25 @@ internal sealed record DropRegistration( Type type, EditorDrop drop ); + internal sealed record PanelRegistration( EditorPanelAttribute attribute, Type type, EditorPanel panel ); + internal sealed record ModalRegistration( EditorModalAttribute attribute, Type type, EditorModal modal ); + internal sealed record HistoryHandlerRegistration( EditorHistoryHandlerAttribute attribute, Type type, EditorHistoryHandler handler ); + internal sealed record StateRegistration( string id, StateOwnerKind kind, @@ -1027,6 +1202,7 @@ internal sealed record StateRegistration( Action capture, Action restore ); + internal enum StateOwnerKind { Module, @@ -1037,18 +1213,19 @@ private readonly record struct PanelState( bool isOpen, ReadOnlyMemory payload ); + private readonly record struct ShortcutValidationEntry( ActionRegistration registration, string area, HotKeyGesture gesture ); + private sealed class ActivationState( Snapshot? previous, Snapshot candidate, HashSet existing, EditorHistory.HandlerUpdate handlers - ) - { + ) { internal Snapshot? previous { get; } = previous; internal Snapshot candidate { get; } = candidate; internal HashSet existing { get; } = existing; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionDiagnosticPublisher.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionDiagnosticPublisher.cs index 75596c9bb..3fa6fafbb 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionDiagnosticPublisher.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; namespace Inno.Editor.Interactions; @@ -35,7 +34,9 @@ internal void RetainPanels(IReadOnlySet panelIds) .Where(id => !panelIds.Contains(id)) .ToArray(); for (int i = 0; i < removed.Length; i++) + { m_panelFailures.Remove(removed[i]); + } } internal void Commit() @@ -43,7 +44,9 @@ internal void Commit() if (m_panelFailures.Count == 0) { if (!string.IsNullOrEmpty(m_publishedState)) + { Diagnostics.Clear(C_PANEL_ACTIVATION_GROUP); + } m_publishedState = string.Empty; return; } @@ -53,12 +56,16 @@ internal void Commit() .ToArray(); string state = string.Join('\n', failures.Select(static pair => $"{pair.Key}:{pair.Value}")); if (string.Equals(m_publishedState, state, StringComparison.Ordinal)) + { return; + } Diagnostics.Set( C_PANEL_ACTIVATION_GROUP, failures.Select(static pair => Diagnostic.Error( "EDITOR-PANEL", - $"Panel '{pair.Key}' failed to attach: {pair.Value}"))); + $"Panel '{pair.Key}' failed to attach: {pair.Value}" + )) + ); m_publishedState = state; } @@ -69,7 +76,9 @@ public void Dispose() { m_panelFailures.Clear(); if (!string.IsNullOrEmpty(m_publishedState)) + { Diagnostics.Clear(C_PANEL_ACTIVATION_GROUP); + } m_publishedState = string.Empty; } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorTypeDistance.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorTypeDistance.cs index 865da8e5d..6b6523599 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorTypeDistance.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorTypeDistance.cs @@ -40,7 +40,9 @@ out int distance foreach (Type interfaceType in type.GetInterfaces()) { if (!visited.Add(interfaceType)) + { continue; + } if (interfaceType == registeredType) { distance = currentDistance + 1; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs index dc91c87d3..48a067593 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs @@ -101,5 +101,4 @@ out string value ArgumentException.ThrowIfNullOrWhiteSpace(key); return m_viewParameters.TryGetValue(key, out value!); } - } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs index c42f94cb9..1b7de32d4 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs @@ -4,12 +4,15 @@ using Inno.Core.Events; namespace Inno.Editor.Interactions; + internal sealed class EditorDocumentService : IEditorDocumentService { private readonly List m_documents = []; private readonly Dictionary m_providers = new(StringComparer.Ordinal); private readonly EventDispatcher m_events; + internal EditorDocumentService(EventDispatcher events) => m_events = events; + /// /// Gets an immutable snapshot of currently owned source documents. /// @@ -29,13 +32,17 @@ public IDisposable RegisterProvider(EditorDocumentProvider provider) ArgumentNullException.ThrowIfNull(provider); ArgumentException.ThrowIfNullOrWhiteSpace(provider.id); if (!m_providers.TryAdd(provider.id, provider)) + { throw new InvalidOperationException($"Editor document provider '{provider.id}' is already registered."); + } try { foreach (EditorDocumentContext document in m_documents.Where(document => document.providerId == provider.id).ToArray()) { if (!m_documents.Contains(document)) + { continue; + } document.isProviderAvailable = true; provider.Open(document); } @@ -66,10 +73,14 @@ public EditorDocumentContext Open( Guid assetId = default ) { string normalizedPath = NormalizePath(assetPath); - EditorDocumentContext? identityOwner = assetId == Guid.Empty ? null : m_documents.FirstOrDefault(document => document.assetId == assetId); + EditorDocumentContext? identityOwner = assetId == Guid.Empty + ? null + : m_documents.FirstOrDefault(document => document.assetId == assetId); EditorDocumentContext? pathOwner = FindPathOwner(normalizedPath); if (identityOwner is not null && pathOwner is not null && !ReferenceEquals(identityOwner, pathOwner)) + { RetireStalePathOwner(pathOwner, normalizedPath); + } EditorDocumentContext? existing = identityOwner ?? pathOwner; if (existing is not null && assetId != Guid.Empty && existing.assetId != assetId) { @@ -86,7 +97,8 @@ public EditorDocumentContext Open( EditorDocumentProvider provider = m_providers.Values.OrderBy( static candidate => candidate.id, StringComparer.Ordinal - ).FirstOrDefault(candidate => candidate.CanOpen(normalizedPath)) ?? throw new InvalidOperationException($"No editor document provider can open '{normalizedPath}'."); + ).FirstOrDefault(candidate => candidate.CanOpen(normalizedPath)) + ?? throw new InvalidOperationException($"No editor document provider can open '{normalizedPath}'."); var context = new EditorDocumentContext(Guid.NewGuid(), assetId, normalizedPath, provider.id) { isProviderAvailable = true @@ -123,17 +135,25 @@ string assetPath ) { EditorDocumentContext? document = Find(documentId); if (document is null) + { return false; + } string path = NormalizePath(assetPath); if (m_providers.TryGetValue(document.providerId, out EditorDocumentProvider? provider) && !provider.CanOpen(path)) + { throw new ArgumentException("The new source path is not supported by this document provider.", nameof(assetPath)); + } EditorDocumentContext? pathOwner = FindPathOwner(path, documentId); if (pathOwner is not null) + { RetireStalePathOwner(pathOwner, path); + } bool defaultTitle = document.title == System.IO.Path.GetFileName(document.assetPath); document.assetPath = path; if (defaultTitle) + { document.title = System.IO.Path.GetFileName(path); + } return true; } @@ -150,6 +170,7 @@ public void SetDirty( Guid documentId, bool isDirty = true ) => Get(documentId).isDirty = isDirty; + /// /// Persists the supplied value through the configured storage contract. /// @@ -159,10 +180,12 @@ public void SetDirty( /// /// when the owning provider saved the document. /// - public bool Save(Guid documentId) => Invoke(documentId, static ( - provider, - context - ) => provider.Save(context), clearDirty: true); + public bool Save(Guid documentId) + => Invoke(documentId, static ( + provider, + context + ) => provider.Save(context), clearDirty: true); + /// /// Saves every dirty document through its owning provider. /// @@ -175,7 +198,9 @@ public bool SaveAll() foreach (EditorDocumentContext document in m_documents.ToArray()) { if (document.isDirty && !Save(document.documentId)) + { succeeded = false; + } } return succeeded; @@ -190,10 +215,12 @@ public bool SaveAll() /// /// when the owning provider applied the staged state. /// - public bool Apply(Guid documentId) => Invoke(documentId, static ( - provider, - context - ) => provider.Apply(context), clearDirty: true); + public bool Apply(Guid documentId) + => Invoke(documentId, static ( + provider, + context + ) => provider.Apply(context), clearDirty: true); + /// /// Reverts one open document through its owning provider. /// @@ -203,10 +230,12 @@ public bool Apply(Guid documentId) => Invoke(documentId, static ( /// /// when the owning provider restored the saved state. /// - public bool Revert(Guid documentId) => Invoke(documentId, static ( - provider, - context - ) => provider.Revert(context), clearDirty: true); + public bool Revert(Guid documentId) + => Invoke(documentId, static ( + provider, + context + ) => provider.Revert(context), clearDirty: true); + /// /// Closes the requested resource and releases its operation-scoped state. /// @@ -226,13 +255,21 @@ EditorDocumentCloseMode mode m_events.Emit(new EditorOperationPreparingEvent()); EditorDocumentContext? document = Find(documentId); if (document is null || mode == EditorDocumentCloseMode.Cancel) + { return false; + } if (document.isDirty && mode == EditorDocumentCloseMode.Save && !Save(documentId)) + { return false; + } if (document.isDirty && mode != EditorDocumentCloseMode.Discard && mode != EditorDocumentCloseMode.Save) + { return false; + } if (m_providers.TryGetValue(document.providerId, out EditorDocumentProvider? provider)) + { provider.Close(document); + } m_documents.Remove(document); return true; } @@ -242,7 +279,9 @@ internal void Shutdown() foreach (EditorDocumentContext document in m_documents.ToArray()) { if (m_providers.TryGetValue(document.providerId, out EditorDocumentProvider? provider)) + { provider.Close(document); + } } m_documents.Clear(); @@ -257,32 +296,48 @@ bool clearDirty m_events.Emit(new EditorOperationPreparingEvent()); EditorDocumentContext document = Get(documentId); if (!m_providers.TryGetValue(document.providerId, out EditorDocumentProvider? provider)) + { return false; + } bool succeeded = operation(provider, document); if (succeeded && clearDirty) + { document.isDirty = false; + } return succeeded; } - private EditorDocumentContext Get(Guid documentId) => Find(documentId) ?? throw new ArgumentException($"Editor document '{documentId}' is not open.", nameof(documentId)); + private EditorDocumentContext Get(Guid documentId) + => Find(documentId) ?? throw new ArgumentException($"Editor document '{documentId}' is not open.", nameof(documentId)); + private EditorDocumentContext? Find(Guid documentId) => m_documents.FirstOrDefault(document => document.documentId == documentId); + private EditorDocumentContext? FindPathOwner( string assetPath, Guid excludedDocumentId = default - ) => m_documents.FirstOrDefault(document => document.documentId != excludedDocumentId && string.Equals(document.assetPath, assetPath, StringComparison.Ordinal)); + ) => m_documents.FirstOrDefault( + document => document.documentId != excludedDocumentId && string.Equals(document.assetPath, assetPath, StringComparison.Ordinal) + ); + private void RetireStalePathOwner( EditorDocumentContext document, string destinationPath ) { if (document.isDirty) { - throw new InvalidOperationException($"Open document '{document.title}' has unsaved changes for '{destinationPath}'. " + "Save, revert, or close it before assigning that source path to another asset identity."); + throw new InvalidOperationException( + $"Open document '{document.title}' has unsaved changes for '{destinationPath}'. " + "Save, revert, or close it before assigning that source path to another asset identity." + ); } if (m_providers.TryGetValue(document.providerId, out EditorDocumentProvider? provider)) + { provider.Close(document); + } if (!m_documents.Remove(document)) + { return; + } } private static string NormalizePath(string assetPath) @@ -290,7 +345,9 @@ private static string NormalizePath(string assetPath) ArgumentException.ThrowIfNullOrWhiteSpace(assetPath); string normalized = assetPath.Replace('\\', '/').Trim(); while (normalized.StartsWith("./", StringComparison.Ordinal)) + { normalized = normalized[2..]; + } return normalized; } @@ -303,7 +360,9 @@ private void Unregister(EditorDocumentProvider provider) m_providers.Remove(provider.id); foreach (EditorDocumentContext document in m_documents.Where(document => document.providerId == provider.id)) + { document.isProviderAvailable = false; + } } private sealed class ProviderLease( @@ -312,6 +371,7 @@ EditorDocumentProvider provider ) : IDisposable { private EditorDocumentService? m_owner = owner; + /// /// Releases the resources owned by this instance. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs index 8b217266a..2d05e4995 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs @@ -148,5 +148,4 @@ bool Close( Guid documentId, EditorDocumentCloseMode mode ); - } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragContext.cs index c5b581331..3156dee2f 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragContext.cs @@ -1,5 +1,4 @@ using System; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs index b09cc243d..325999da0 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Identity; namespace Inno.Editor.Interactions; @@ -30,8 +29,9 @@ string label ) { ArgumentNullException.ThrowIfNull(source); sourceIdentity = source.identity.runtimeIdentity - ?? throw new InvalidOperationException( - "An editor drag source must be registered in a live identity domain."); + ?? throw new InvalidOperationException( + "An editor drag source must be registered in a live identity domain." + ); this.label = label ?? string.Empty; } @@ -44,5 +44,4 @@ string label /// Gets the drag preview label. /// public string label { get; } - } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs index a0159c719..62428646c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Identity; using Inno.Editor.Core; @@ -79,8 +78,8 @@ public sealed override EditorDropStatus Query(EditorDropContext context) { ArgumentNullException.ThrowIfNull(context); return context.source is TSource source && context.target is TTarget target - ? Query(new EditorDropContext(context, source, target)) - : EditorDropStatus.rejected; + ? Query(new EditorDropContext(context, source, target)) + : EditorDropStatus.rejected; } /// @@ -96,7 +95,9 @@ public sealed override EditorDropResult Drop(EditorDropContext context) { ArgumentNullException.ThrowIfNull(context); if (context.source is not TSource source || context.target is not TTarget target) + { return EditorDropResult.rejected; + } return Drop(new EditorDropContext(context, source, target)); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropAttribute.cs index 123191354..3a244b14d 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropAttribute.cs @@ -15,9 +15,7 @@ public sealed class EditorDropAttribute : Attribute /// The tie-breaking priority used after source and target specificity. /// public EditorDropAttribute(int priority = 0) - : this(string.Empty, priority) - { - } + : this(string.Empty, priority) {} /// /// Creates a drop registration scoped to an exact interaction area. diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs index 369f8ac8d..dacbe9ae9 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Identity; using Inno.Editor.Core; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropPlacement.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropPlacement.cs index 1ecb5d6a2..079065745 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropPlacement.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropPlacement.cs @@ -9,17 +9,14 @@ public enum EditorDropPlacement /// No positional placement is requested. /// None, - /// /// Insert before the target. /// Before, - /// /// Drop into the target. /// Into, - /// /// Insert after the target. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropResult.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropResult.cs index db6529916..b2f7e5182 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropResult.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropResult.cs @@ -62,6 +62,5 @@ public EditorDropResult( public static EditorDropResult Accepted( object? selectionTarget = null, object? revealTarget = null - ) - => new(true, selectionTarget, revealTarget); + ) => new(true, selectionTarget, revealTarget); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropRouter.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropRouter.cs index 4c531762c..7c989517d 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropRouter.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropRouter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Identity; using Inno.Core.Logging; @@ -19,7 +18,9 @@ internal RuntimeIdentity Begin(EditorDragContext context) ArgumentNullException.ThrowIfNull(context); RuntimeIdentity identity = context.data.sourceIdentity; if (Resolve(identity) is null) + { throw new InvalidOperationException("The editor drag source is no longer registered."); + } m_activeIdentity = identity; return identity; } @@ -29,20 +30,24 @@ internal bool TryGetSource( out IdentityObject? source ) { source = m_activeIdentity == identity - ? Resolve(identity) - : null; + ? Resolve(identity) + : null; if (source is not null) + { return true; + } if (m_activeIdentity == identity) + { Cancel(); + } return false; } internal bool TryGetActiveIdentity(out RuntimeIdentity identity) { - if (m_activeIdentity is not RuntimeIdentity active || - Resolve(active) is null) - { + if (m_activeIdentity is not RuntimeIdentity active + || Resolve(active) is null + ) { Cancel(); identity = default; return false; @@ -55,9 +60,11 @@ internal EditorDropStatus Query( RuntimeIdentity identity, EditorDropContext context ) { - if (!TryResolve(identity, context, out EditorExtensionCatalog.DropRegistration? registration) || - registration is null) + if (!TryResolve(identity, context, out EditorExtensionCatalog.DropRegistration? registration) + || registration is null + ) { return EditorDropStatus.rejected; + } try { EditorDropStatus status = registration.drop.Query(context); @@ -69,7 +76,9 @@ EditorDropContext context { string dropName = registration.type.FullName ?? registration.type.Name; if (m_queryFailures.Add(dropName)) + { log.Write(LogLevel.Error, "Editor drop query failed: {0}", [exception]); + } return EditorDropStatus.rejected; } } @@ -78,16 +87,22 @@ internal EditorDropResult Drop( RuntimeIdentity identity, EditorDropContext context ) { - if (!TryResolve(identity, context, out EditorExtensionCatalog.DropRegistration? registration) || - registration is null) + if (!TryResolve(identity, context, out EditorExtensionCatalog.DropRegistration? registration) + || registration is null + ) { return EditorDropResult.rejected; + } try { if (!registration.drop.Query(context).canDrop) + { return EditorDropResult.rejected; + } EditorDropResult result = registration.drop.Drop(context); if (result.accepted) + { Cancel(); + } return result; } catch (Exception exception) @@ -124,20 +139,22 @@ out EditorExtensionCatalog.DropRegistration? best { bool exactArea = !string.IsNullOrEmpty(registration.area); if (exactArea && !string.Equals(registration.area, context.area, StringComparison.Ordinal)) - continue; - if (!EditorTypeDistance.TryGet(sourceType, registration.sourceType, out int sourceDistance) || - !EditorTypeDistance.TryGet(targetType, registration.targetType, out int targetDistance)) { continue; } - if (best is null || - exactArea && string.IsNullOrEmpty(best.area) || - exactArea == !string.IsNullOrEmpty(best.area) && - (sourceDistance < bestSourceDistance || - sourceDistance == bestSourceDistance && targetDistance < bestTargetDistance || - sourceDistance == bestSourceDistance && targetDistance == bestTargetDistance && - registration.priority > best.priority)) - { + if (!EditorTypeDistance.TryGet(sourceType, registration.sourceType, out int sourceDistance) + || !EditorTypeDistance.TryGet(targetType, registration.targetType, out int targetDistance) + ) { + continue; + } + if (best is null + || exactArea && string.IsNullOrEmpty(best.area) + || exactArea == !string.IsNullOrEmpty(best.area) + && (sourceDistance < bestSourceDistance + || sourceDistance == bestSourceDistance && targetDistance < bestTargetDistance + || sourceDistance == bestSourceDistance && targetDistance == bestTargetDistance + && registration.priority > best.priority) + ) { best = registration; bestSourceDistance = sourceDistance; bestTargetDistance = targetDistance; @@ -148,6 +165,6 @@ out EditorExtensionCatalog.DropRegistration? best private IdentityObject? Resolve(RuntimeIdentity identity) => identityDomains.TryGetValue(identity.domainId, out IdentityAllocator? allocator) - ? allocator.Get(identity) - : null; + ? allocator.Get(identity) + : null; } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropVisual.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropVisual.cs index 4bfcec4a1..5357bce08 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropVisual.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropVisual.cs @@ -9,22 +9,18 @@ public enum EditorDropVisual /// No visual is drawn. /// None, - /// /// Draw a content highlight. /// Highlight, - /// /// Draw an insertion line before the target. /// InsertBefore, - /// /// Draw an insertion line after the target. /// InsertAfter, - /// /// Draw a disabled target visual. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs index 5268bad6c..6abb262ff 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs @@ -1,12 +1,14 @@ using System; namespace Inno.Editor.Interactions; + /// /// Owns one continuous edit transaction without retaining edited objects, setters or extension instances. /// public sealed class EditorEditGesture : IDisposable { private EditorHistoryTransaction? m_transaction; + /// /// Begins an edit whose updates use the existing domain mutation and History protocols. /// @@ -35,6 +37,7 @@ string name /// Gets the transient merge boundary shared only by updates within this gesture. /// public string mergeKey { get; } + /// /// Gets whether this gesture still owns an active transaction, including a rejected completion. /// @@ -85,12 +88,17 @@ public EditorHistoryResult Cancel() public void Dispose() { if (m_transaction is null) + { return; + } EditorHistoryResult result = Cancel(); if (!result.succeeded) + { throw new InvalidOperationException($"The edit gesture could not roll back: {result.message}"); + } GC.SuppressFinalize(this); } - private EditorHistoryTransaction RequireTransaction() => m_transaction ?? throw new InvalidOperationException("The edit gesture has already finished."); + private EditorHistoryTransaction RequireTransaction() + => m_transaction ?? throw new InvalidOperationException("The edit gesture has already finished."); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorOperationPreparingEvent.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorOperationPreparingEvent.cs index a6472e6f0..25e278707 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorOperationPreparingEvent.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorOperationPreparingEvent.cs @@ -1,6 +1,7 @@ using Inno.Core.Events; namespace Inno.Editor.Interactions; + /// /// Synchronously closes transient edits before command execution or an extension-handler generation switch. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs index f46671a4f..a352f1108 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs @@ -5,6 +5,7 @@ using Inno.Editor.Core; namespace Inno.Editor.Interactions; + /// /// Owns the bounded, transactional Undo and Redo history for one editor runtime. /// @@ -16,13 +17,18 @@ internal sealed class EditorHistory : IEditorHistory, IDisposable private readonly EditorHistoryOptions m_options; private readonly EditorHistoryBlobStore m_blobStore; private readonly Logger m_log; - private IReadOnlyDictionary m_handlers = new Dictionary(StringComparer.Ordinal); + + private IReadOnlyDictionary m_handlers = new Dictionary( + StringComparer.Ordinal + ); + private EditorHistoryContext? m_context; private IsolationState? m_isolation; private bool m_isTransitioning; private bool m_isFaulted; private string? m_faultReason; private bool m_isDisposed; + /// /// Creates an empty history with explicit entry, resident-memory, and temporary-disk budgets. /// @@ -54,70 +60,72 @@ Logger log /// Gets the maximum number of committed top-level operations retained by this history. /// public int capacity { get; } + /// /// Gets whether a previous operation is currently available and permits Undo. /// public bool canUndo => !m_isFaulted && !m_isTransitioning && m_transactions.Count == 0 && m_undo.Count > 0 && m_undo[^1].canUndo; + /// /// Gets whether a reverted operation is currently available and permits Redo. /// public bool canRedo => !m_isFaulted && !m_isTransitioning && m_transactions.Count == 0 && m_redo.Count > 0 && m_redo[^1].canRedo; + /// /// Gets whether a failed compensation left the domain state indeterminate. /// public bool isFaulted => m_isFaulted; + /// /// Gets the diagnostic that faulted this history, or while the history is healthy. /// public string? faultReason => m_faultReason; + /// /// Gets the next operation name displayed by the Undo command, or when unavailable. /// public string? undoName => m_undo.Count == 0 ? null : m_undo[^1].name; + /// /// Gets the next operation name displayed by the Redo command, or when unavailable. /// public string? redoName => m_redo.Count == 0 ? null : m_redo[^1].name; + /// /// Gets the diagnostic explaining why the newest Undo entry is a barrier, or when available. /// public string? undoUnavailableReason => GetUnavailableReason(m_undo, EditorHistoryDirection.Undo); + /// /// Gets the diagnostic explaining why the newest Redo entry is a barrier, or when available. /// public string? redoUnavailableReason => GetUnavailableReason(m_redo, EditorHistoryDirection.Redo); + /// /// Gets the estimated resident payload bytes retained by committed Undo and Redo entries. /// - public long residentBytes => Sum( - m_undo, - static operation => operation.estimatedMemorySize - ) + Sum( - m_redo, - static operation => operation.estimatedMemorySize - ) + (m_isolation is IsolationState isolation ? Sum( - isolation.undo, - static operation => operation.estimatedMemorySize - ) + Sum( - isolation.redo, - static operation => operation.estimatedMemorySize - ) : 0L); + public long residentBytes + => Sum(m_undo, static operation => operation.estimatedMemorySize) + + Sum(m_redo, static operation => operation.estimatedMemorySize) + + (m_isolation is IsolationState isolation + ? Sum( + isolation.undo, + static operation => operation.estimatedMemorySize + ) + Sum(isolation.redo, static operation => operation.estimatedMemorySize) + : 0L); + /// /// Gets the estimated temporary disk payload bytes retained by committed Undo and Redo entries. /// - public long diskBytes => Sum( - m_undo, - static operation => operation.estimatedDiskSize - ) + Sum( - m_redo, - static operation => operation.estimatedDiskSize - ) + (m_isolation is IsolationState isolation ? Sum( - isolation.undo, - static operation => operation.estimatedDiskSize - ) + Sum( - isolation.redo, - static operation => operation.estimatedDiskSize - ) : 0L); + public long diskBytes + => Sum(m_undo, static operation => operation.estimatedDiskSize) + + Sum(m_redo, static operation => operation.estimatedDiskSize) + + (m_isolation is IsolationState isolation + ? Sum( + isolation.undo, + static operation => operation.estimatedDiskSize + ) + Sum(isolation.redo, static operation => operation.estimatedDiskSize) + : 0L); /// /// Begins an atomic group whose child operations appear as one Undo entry. @@ -175,7 +183,9 @@ internal EditorHistoryResult Execute( var operation = new DelegateOperation(name, undo, execute, mergeKey); EditorHistoryResult result = Invoke(operation.RedoInternal, name, "execute"); if (result.succeeded) + { Record(operation); + } else { ObserveFailure(result); @@ -222,7 +232,9 @@ EditorHistoryChange change EditorHistoryResult result = Invoke(operation.RedoInternal, name, "execute"); if (result.succeeded) + { Record(operation); + } else { ObserveFailure(result); @@ -322,6 +334,7 @@ object mergeKey /// The transition result. A failed operation remains available for retry. /// public EditorHistoryResult Undo() => Transition(m_undo, m_redo, undo: true); + /// /// Attempts to reapply the newest reverted operation. /// @@ -329,6 +342,7 @@ object mergeKey /// The transition result. A failed operation remains available for retry. /// public EditorHistoryResult Redo() => Transition(m_redo, m_undo, undo: false); + /// /// Starts a temporary empty history branch while retaining the current branch for restoration. /// @@ -342,9 +356,13 @@ internal IDisposable BeginIsolation() { EnsureMutable(); if (m_transactions.Count != 0) + { throw new InvalidOperationException("Editor history cannot be isolated during a transaction."); + } if (m_isolation is not null) + { throw new InvalidOperationException("Editor history already owns an isolated branch."); + } var isolation = new IsolationState(m_undo, m_redo, m_isFaulted, m_faultReason); m_isolation = isolation; m_undo = []; @@ -360,9 +378,13 @@ internal IDisposable BeginIsolation() internal void Clear() { if (m_isDisposed) + { return; + } if (m_isTransitioning) + { throw new InvalidOperationException("Editor history cannot be cleared during Undo or Redo."); + } DisposeAll(m_undo); DisposeAll(m_redo); if (m_isolation is IsolationState isolation) @@ -373,7 +395,9 @@ internal void Clear() } while (m_transactions.TryPop(out TransactionOperation? transaction)) + { transaction.Dispose(); + } m_isFaulted = false; m_faultReason = null; } @@ -384,7 +408,9 @@ internal void Clear() public void Dispose() { if (m_isDisposed) + { return; + } Clear(); m_blobStore.Dispose(); m_isDisposed = true; @@ -457,14 +483,22 @@ bool undo ) { EnsureMutable(); if (m_transactions.Count != 0) + { return EditorHistoryResult.Failure("Undo and Redo are unavailable while a transaction is active."); + } if (source.Count == 0) + { return EditorHistoryResult.Failure(undo ? "Nothing to undo." : "Nothing to redo."); + } EditorHistoryOperation operation = source[^1]; m_isTransitioning = true; try { - EditorHistoryResult result = Invoke(undo ? operation.UndoInternal : operation.RedoInternal, operation.name, undo ? "undo" : "redo"); + EditorHistoryResult result = Invoke( + undo ? operation.UndoInternal : operation.RedoInternal, + operation.name, + undo ? "undo" : "redo" + ); if (!result.succeeded) { ObserveFailure(result); @@ -491,7 +525,9 @@ private TransactionOperation PopTransaction(Guid id) private TransactionOperation PeekTransaction(Guid id) { if (!m_transactions.TryPeek(out TransactionOperation? operation) || operation.id != id) + { throw new InvalidOperationException("Editor history transactions must complete in stack order."); + } return operation; } @@ -504,13 +540,17 @@ private void EnsureMutable() } if (m_isTransitioning) + { throw new InvalidOperationException("History cannot be modified while Undo or Redo is executing."); + } } private void ObserveFailure(EditorHistoryResult result) { if (result.succeeded || result.statePreserved) + { return; + } m_isFaulted = true; m_faultReason = result.message; m_log.Write(LogLevel.Error, "Editor history was faulted because state integrity was lost: {0}", [result.message]); @@ -531,21 +571,26 @@ internal HandlerUpdate PrepareHandlerUpdate(IReadOnlyDictionary change.Retain( - m_blobStore, - m_options.inlinePayloadThreshold, - !string.IsNullOrWhiteSpace(m_options.cacheDirectory) - ); + private EditorHistoryChange RetainChange(EditorHistoryChange change) + => change.Retain( + m_blobStore, + m_options.inlinePayloadThreshold, + !string.IsNullOrWhiteSpace(m_options.cacheDirectory) + ); + private bool TryGetHandler( string kind, out EditorHistoryHandler? handler ) => m_handlers.TryGetValue(kind, out handler); + private EditorHistoryAvailability Query( EditorHistoryChange change, EditorHistoryDirection direction ) { if (m_context is null) + { return EditorHistoryAvailability.Unavailable("The editor history is not attached to an interaction runtime."); + } if (!TryGetHandler(change.kind, out EditorHistoryHandler? handler) || handler is null) { return EditorHistoryAvailability.Unavailable($"Required history handler '{change.kind}' is not loaded."); @@ -567,7 +612,9 @@ EditorHistoryDirection direction ) { EditorHistoryAvailability availability = Query(change, direction); if (!availability.isAvailable) + { return EditorHistoryResult.Failure(availability.message); + } EditorHistoryHandler handler = m_handlers[change.kind]; return handler.ApplyInternal(m_context!, change, direction); } @@ -578,23 +625,12 @@ private bool TryMerge( out EditorHistoryChange? merged ) { merged = null; - if (!string.Equals( - older.kind, - newer.kind, - StringComparison.Ordinal - ) + if (!string.Equals(older.kind, newer.kind, StringComparison.Ordinal) || older.mergeKey is null - || !string.Equals( - older.mergeKey, - newer.mergeKey, - StringComparison.Ordinal - ) - || !TryGetHandler( - older.kind, - out EditorHistoryHandler? handler - ) - || handler is null) - { + || !string.Equals(older.mergeKey, newer.mergeKey, StringComparison.Ordinal) + || !TryGetHandler(older.kind, out EditorHistoryHandler? handler) + || handler is null + ) { return false; } @@ -615,12 +651,16 @@ private void DiscardRuntimeBoundEntries() if (m_transactions.Count != 0) { while (m_transactions.TryPop(out TransactionOperation? transaction)) + { transaction.Dispose(); + } } DiscardRuntimeBoundEntries(m_undo, m_redo); if (m_isolation is IsolationState isolation) + { DiscardRuntimeBoundEntries(isolation.undo, isolation.redo); + } } private static void DiscardRuntimeBoundEntries( @@ -631,22 +671,30 @@ List redo if (newestUnsafe >= 0) { for (int i = newestUnsafe; i >= 0; i--) + { undo[i].Dispose(); + } undo.RemoveRange(0, newestUnsafe + 1); } if (redo.Exists(static operation => !operation.isReloadSafe)) + { DisposeAll(redo); + } } private void EndIsolation(IsolationState isolation) { if (m_isDisposed || !ReferenceEquals(m_isolation, isolation)) + { return; + } DisposeAll(m_undo); DisposeAll(m_redo); while (m_transactions.TryPop(out TransactionOperation? transaction)) + { transaction.Dispose(); + } m_undo = isolation.undo; m_redo = isolation.redo; m_isFaulted = isolation.isFaulted; @@ -659,7 +707,9 @@ private void EndIsolation(IsolationState isolation) EditorHistoryDirection direction ) { if (operations.Count == 0) + { return null; + } EditorHistoryOperation operation = operations[^1]; if (operation is DataOperation data) { @@ -677,7 +727,9 @@ Func selector ) { long total = 0L; for (int i = 0; i < operations.Count; i++) + { total = checked(total + selector(operations[i])); + } return total; } @@ -690,20 +742,26 @@ string transition { EditorHistoryResult result = callback(); if (!result.succeeded) + { m_log.Write(LogLevel.Warn, "Editor history operation '{0}' could not {1}: {2}", [name, transition, result.message]); + } return result; } catch (Exception exception) { m_log.Write(LogLevel.Error, "Editor history operation '{0}' failed to {1}: {2}", [name, transition, exception]); - return EditorHistoryResult.StateIntegrityLost($"The {transition} callback for '{name}' threw before it could prove rollback: {exception.Message}"); + return EditorHistoryResult.StateIntegrityLost( + $"The {transition} callback for '{name}' threw before it could prove rollback: {exception.Message}" + ); } } private static void DisposeAll(List operations) { for (int i = operations.Count - 1; i >= 0; i--) + { operations[i].Dispose(); + } operations.Clear(); } @@ -711,16 +769,20 @@ internal sealed class HandlerUpdate( EditorHistory owner, IReadOnlyDictionary previous, IReadOnlyDictionary candidate - ) - { + ) { private bool m_activated; private bool m_finished; + internal void Activate() { if (m_finished) + { throw new InvalidOperationException("History handler update is already finished."); + } if (m_activated) + { return; + } owner.m_handlers = candidate; m_activated = true; } @@ -728,18 +790,26 @@ internal void Activate() internal void Rollback() { if (m_finished) + { return; + } if (m_activated) + { owner.m_handlers = previous; + } m_finished = true; } internal void Complete() { if (m_finished) + { return; + } if (!m_activated) + { throw new InvalidOperationException("History handler update has not been activated."); + } m_finished = true; try { @@ -758,12 +828,14 @@ private sealed record IsolationState( bool isFaulted, string? faultReason ); + private sealed class Isolation( EditorHistory owner, IsolationState state ) : IDisposable { private EditorHistory? m_owner = owner; + /// /// Releases the resources owned by this instance. /// @@ -771,7 +843,9 @@ public void Dispose() { EditorHistory? current = m_owner; if (current is null) + { return; + } m_owner = null; current.EndIsolation(state); } @@ -782,6 +856,7 @@ private sealed class DelegateOperation : EditorHistoryOperation private readonly Func m_undo; private readonly object? m_mergeKey; private Func m_redo; + internal DelegateOperation( string operationName, Func undo, @@ -806,6 +881,7 @@ internal DelegateOperation( /// The validated editor history result that represents the completed operation. /// protected override EditorHistoryResult Undo() => m_undo(); + /// /// Reapplies the state represented by this history operation. /// @@ -813,6 +889,7 @@ internal DelegateOperation( /// The validated editor history result that represents the completed operation. /// protected override EditorHistoryResult Redo() => m_redo(); + /// /// Attempts to merge without changing state when the operation cannot complete. /// @@ -839,6 +916,7 @@ private sealed class DataOperation : EditorHistoryOperation private readonly EditorHistory m_owner; private readonly string m_name; private EditorHistoryChange m_change; + internal DataOperation( EditorHistory owner, string operationName, @@ -853,26 +931,32 @@ EditorHistoryChange change /// Gets the human-readable name used for presentation and diagnostics. /// public override string name => m_name; + /// /// Gets whether this value can undo. /// public override bool canUndo => m_owner.Query(m_change, EditorHistoryDirection.Undo).isAvailable; + /// /// Gets whether this value can redo. /// public override bool canRedo => m_owner.Query(m_change, EditorHistoryDirection.Redo).isAvailable; + /// /// Gets whether this value is reload safe. /// public override bool isReloadSafe => true; + /// /// Gets the estimated resident-memory cost in bytes. /// public override long estimatedMemorySize => m_change.residentSize; + /// /// Gets the estimated spill-file cost in bytes. /// public override long estimatedDiskSize => m_change.diskSize; + internal EditorHistoryChange change => m_change; /// @@ -882,6 +966,7 @@ EditorHistoryChange change /// The validated editor history result that represents the completed operation. /// protected override EditorHistoryResult Undo() => m_owner.Apply(m_change, EditorHistoryDirection.Undo); + /// /// Reapplies the state represented by this history operation. /// @@ -889,6 +974,7 @@ EditorHistoryChange change /// The validated editor history result that represents the completed operation. /// protected override EditorHistoryResult Redo() => m_owner.Apply(m_change, EditorHistoryDirection.Redo); + /// /// Attempts to merge without changing state when the operation cannot complete. /// @@ -900,8 +986,10 @@ EditorHistoryChange change /// protected override bool TryMerge(EditorHistoryOperation newer) { - if (newer is not DataOperation candidate || !m_owner.TryMerge(m_change, candidate.m_change, out EditorHistoryChange? merged) || merged is null) - { + if (newer is not DataOperation candidate + || !m_owner.TryMerge(m_change, candidate.m_change, out EditorHistoryChange? merged) + || merged is null + ) { return false; } @@ -929,7 +1017,9 @@ protected override bool TryMerge(EditorHistoryOperation newer) protected override void Dispose(bool disposing) { if (disposing) + { m_change.Dispose(); + } } } @@ -941,6 +1031,7 @@ private sealed class ValueOperation : EditorHistoryOperation private readonly object m_mergeKey; private T m_after; private long m_lastEditTimestamp; + internal ValueOperation( string operationName, T before, @@ -997,15 +1088,14 @@ protected override EditorHistoryResult Redo() protected override bool TryMerge(EditorHistoryOperation newer) { if (newer is not ValueOperation candidate - || !Equals( - m_mergeKey, - candidate.m_mergeKey - ) + || !Equals(m_mergeKey, candidate.m_mergeKey) || Stopwatch.GetElapsedTime( - m_lastEditTimestamp, - candidate.m_lastEditTimestamp - ).TotalSeconds > C_MERGE_WINDOW_SECONDS) + m_lastEditTimestamp, + candidate.m_lastEditTimestamp + ).TotalSeconds > C_MERGE_WINDOW_SECONDS + ) { return false; + } m_after = candidate.m_after; m_lastEditTimestamp = candidate.m_lastEditTimestamp; return true; @@ -1018,28 +1108,35 @@ Guid transactionId ) : EditorHistoryOperation { private readonly List m_children = []; + /// /// Gets the human-readable name used for presentation and diagnostics. /// public override string name => operationName; + internal Guid id => transactionId; internal int count => m_children.Count; + /// /// Gets whether this value is reload safe. /// public override bool isReloadSafe => m_children.TrueForAll(static operation => operation.isReloadSafe); + /// /// Gets whether this value can undo. /// public override bool canUndo => m_children.TrueForAll(static operation => operation.canUndo); + /// /// Gets whether this value can redo. /// public override bool canRedo => m_children.TrueForAll(static operation => operation.canRedo); + /// /// Gets the estimated resident-memory cost in bytes. /// public override long estimatedMemorySize => Sum(m_children, static operation => operation.estimatedMemorySize); + /// /// Gets the estimated spill-file cost in bytes. /// @@ -1069,12 +1166,20 @@ protected override EditorHistoryResult Undo() { EditorHistoryResult result = InvokeChild(m_children[i].UndoInternal, m_children[i].name, "undo"); if (result.succeeded) + { continue; + } for (int rollback = i + 1; rollback < m_children.Count; rollback++) { - EditorHistoryResult compensation = InvokeChild(m_children[rollback].RedoInternal, m_children[rollback].name, "redo compensation"); + EditorHistoryResult compensation = InvokeChild( + m_children[rollback].RedoInternal, + m_children[rollback].name, + "redo compensation" + ); if (!compensation.succeeded) + { compensationFailures.Add($"'{m_children[rollback].name}': {compensation.message}"); + } } return CombineFailure(result, compensationFailures, "undo"); @@ -1096,12 +1201,20 @@ protected override EditorHistoryResult Redo() { EditorHistoryResult result = InvokeChild(m_children[i].RedoInternal, m_children[i].name, "redo"); if (result.succeeded) + { continue; + } for (int rollback = i - 1; rollback >= 0; rollback--) { - EditorHistoryResult compensation = InvokeChild(m_children[rollback].UndoInternal, m_children[rollback].name, "undo compensation"); + EditorHistoryResult compensation = InvokeChild( + m_children[rollback].UndoInternal, + m_children[rollback].name, + "undo compensation" + ); if (!compensation.succeeded) + { compensationFailures.Add($"'{m_children[rollback].name}': {compensation.message}"); + } } return CombineFailure(result, compensationFailures, "redo"); @@ -1131,7 +1244,9 @@ private static EditorHistoryResult CombineFailure( string transition ) { if (original.statePreserved && compensationFailures.Count == 0) + { return original; + } string compensation = compensationFailures.Count == 0 ? "The failing child could not prove that it preserved its input state." : $"Compensation failures: {string.Join( "; ", compensationFailures @@ -1148,9 +1263,13 @@ string transition protected override void Dispose(bool disposing) { if (!disposing) + { return; + } for (int i = m_children.Count - 1; i >= 0; i--) + { m_children[i].Dispose(); + } m_children.Clear(); } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs index 005c65fe5..0dd0d1890 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs @@ -14,17 +14,19 @@ internal sealed class EditorHistoryBlobStore : IDisposable internal EditorHistoryBlobStore(string? cacheDirectory) { if (string.IsNullOrWhiteSpace(cacheDirectory)) + { return; - m_sessionDirectory = Path.Combine( - Path.GetFullPath(cacheDirectory), - Guid.NewGuid().ToString("N")); + } + m_sessionDirectory = Path.Combine(Path.GetFullPath(cacheDirectory), Guid.NewGuid().ToString("N")); } internal string Retain(ReadOnlySpan bytes) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_sessionDirectory is null) + { throw new InvalidOperationException("The history does not have a disk payload store."); + } Directory.CreateDirectory(m_sessionDirectory); string hash = Convert.ToHexStringLower(SHA256.HashData(bytes)); string path = Path.Combine(m_sessionDirectory, hash + ".bin"); @@ -48,7 +50,9 @@ internal string Retain(ReadOnlySpan bytes) internal void Release(string path) { if (m_disposed || !m_references.TryGetValue(path, out int count)) + { return; + } if (count > 1) { m_references[path] = count - 1; @@ -58,7 +62,9 @@ internal void Release(string path) try { if (File.Exists(path)) + { File.Delete(path); + } } catch { @@ -72,7 +78,9 @@ internal void Release(string path) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_references.Clear(); if (m_sessionDirectory is not null) @@ -80,7 +88,9 @@ public void Dispose() try { if (Directory.Exists(m_sessionDirectory)) + { Directory.Delete(m_sessionDirectory, recursive: true); + } } catch { diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryChange.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryChange.cs index addcafe80..d25c9a328 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryChange.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryChange.cs @@ -61,11 +61,7 @@ internal EditorHistoryChange Retain( EditorHistoryBlobStore store, int inlinePayloadThreshold, bool canStoreOnDisk - ) - => new( - kind, - payload.Retain(store, inlinePayloadThreshold, canStoreOnDisk), - mergeKey); + ) => new(kind, payload.Retain(store, inlinePayloadThreshold, canStoreOnDisk), mergeKey); /// /// Releases the payload storage owned by this history change. @@ -73,7 +69,9 @@ bool canStoreOnDisk public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; payload.Dispose(); GC.SuppressFinalize(this); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryContext.cs index bc3ef0dad..5bb31dded 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryContext.cs @@ -1,5 +1,4 @@ using System; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryDirection.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryDirection.cs index 5a0618b69..c7674ef18 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryDirection.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryDirection.cs @@ -9,7 +9,6 @@ public enum EditorHistoryDirection /// Restores the state that existed before the change was committed. /// Undo = 0, - /// /// Restores the state produced by the committed change. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandler.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandler.cs index 597f7fb70..040cad0ec 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandler.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandler.cs @@ -88,20 +88,17 @@ internal EditorHistoryAvailability QueryInternal( EditorHistoryContext context, EditorHistoryChange change, EditorHistoryDirection direction - ) - => Query(context, change, direction); + ) => Query(context, change, direction); internal EditorHistoryResult ApplyInternal( EditorHistoryContext context, EditorHistoryChange change, EditorHistoryDirection direction - ) - => Apply(context, change, direction); + ) => Apply(context, change, direction); internal bool TryMergeInternal( EditorHistoryChange older, EditorHistoryChange newer, out EditorHistoryChange? merged - ) - => TryMerge(older, newer, out merged); + ) => TryMerge(older, newer, out merged); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandlerAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandlerAttribute.cs index 025a69ef9..890d72929 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandlerAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryHandlerAttribute.cs @@ -27,5 +27,4 @@ public EditorHistoryHandlerAttribute(string kind) /// Gets the stable globally unique change protocol identifier. /// public string kind { get; } - } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOperation.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOperation.cs index 0f11dc79f..3152cc2e8 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOperation.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOperation.cs @@ -43,16 +43,16 @@ internal EditorHistoryResult UndoInternal() { ObjectDisposedException.ThrowIf(m_isDisposed, this); return canUndo - ? Undo() - : EditorHistoryResult.Failure($"'{name}' cannot currently be undone."); + ? Undo() + : EditorHistoryResult.Failure($"'{name}' cannot currently be undone."); } internal EditorHistoryResult RedoInternal() { ObjectDisposedException.ThrowIf(m_isDisposed, this); return canRedo - ? Redo() - : EditorHistoryResult.Failure($"'{name}' cannot currently be redone."); + ? Redo() + : EditorHistoryResult.Failure($"'{name}' cannot currently be redone."); } internal bool TryMergeInternal(EditorHistoryOperation newer) @@ -95,7 +95,9 @@ internal bool TryMergeInternal(EditorHistoryOperation newer) public void Dispose() { if (m_isDisposed) + { return; + } m_isDisposed = true; Dispose(true); GC.SuppressFinalize(this); @@ -107,7 +109,5 @@ public void Dispose() /// /// Whether managed resources may be released. /// - protected virtual void Dispose(bool disposing) - { - } + protected virtual void Dispose(bool disposing) {} } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOptions.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOptions.cs index ecbb37114..cd9eef136 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOptions.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryOptions.cs @@ -35,22 +35,28 @@ public sealed class EditorHistoryOptions internal void Validate() { if (maxEntries <= 0) + { throw new ArgumentOutOfRangeException(nameof(maxEntries), maxEntries, "History entry capacity must be positive."); + } if (maxResidentBytes <= 0) { throw new ArgumentOutOfRangeException( nameof(maxResidentBytes), maxResidentBytes, - "Resident history capacity must be positive."); + "Resident history capacity must be positive." + ); } if (maxDiskBytes <= 0) + { throw new ArgumentOutOfRangeException(nameof(maxDiskBytes), maxDiskBytes, "Disk history capacity must be positive."); + } if (inlinePayloadThreshold < 0) { throw new ArgumentOutOfRangeException( nameof(inlinePayloadThreshold), inlinePayloadThreshold, - "The inline payload threshold cannot be negative."); + "The inline payload threshold cannot be negative." + ); } } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs index b69fcd155..f23d6eccb 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs @@ -67,7 +67,9 @@ public byte[] ReadBytes() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_inlineBytes is not null) + { return (byte[])m_inlineBytes.Clone(); + } return File.ReadAllBytes(m_path!); } @@ -79,7 +81,9 @@ bool canStoreOnDisk ObjectDisposedException.ThrowIf(m_disposed, this); byte[] bytes = ReadBytes(); if (!canStoreOnDisk || bytes.Length < inlinePayloadThreshold) + { return new EditorHistoryPayload(bytes); + } string path = store.Retain(bytes); return new EditorHistoryPayload(store, path, bytes.LongLength); } @@ -90,10 +94,14 @@ bool canStoreOnDisk public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; if (m_store is not null && m_path is not null) + { m_store.Release(m_path); + } m_inlineBytes = null; m_store = null; m_path = null; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryTransaction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryTransaction.cs index 2cb4388c8..e0e1d7731 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryTransaction.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryTransaction.cs @@ -54,9 +54,13 @@ public EditorHistoryResult Rollback() EditorHistory owner = GetOwner(); EditorHistoryResult result = owner.RollbackTransaction(this); if (result.succeeded) + { Complete(); + } else if (!result.statePreserved) + { Complete(); + } return result; } @@ -66,7 +70,9 @@ public EditorHistoryResult Rollback() public void Dispose() { if (m_completed) + { return; + } EditorHistory? owner = m_owner; if (owner is null) { @@ -88,19 +94,21 @@ public void Dispose() Complete(); GC.SuppressFinalize(this); throw new InvalidOperationException( - $"Transaction '{name}' could not roll back and was committed to Undo instead: {result.message}"); + $"Transaction '{name}' could not roll back and was committed to Undo instead: {result.message}" + ); } Complete(); GC.SuppressFinalize(this); throw new InvalidOperationException( - $"Transaction '{name}' lost state integrity while rolling back. The history is faulted: {result.message}"); + $"Transaction '{name}' lost state integrity while rolling back. The history is faulted: {result.message}" + ); } private EditorHistory GetOwner() => !m_completed && m_owner is not null - ? m_owner - : throw new InvalidOperationException("The editor history transaction is no longer active."); + ? m_owner + : throw new InvalidOperationException("The editor history transaction is no longer active."); private void Complete() { diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuAttribute.cs index 63403f19f..9986d70ff 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuAttribute.cs @@ -33,10 +33,14 @@ public EditorMenuAttribute( bool separatorBefore = false ) { if (string.IsNullOrWhiteSpace(area)) + { throw new ArgumentException("An editor menu area is required.", nameof(area)); + } this.area = area; if (string.IsNullOrWhiteSpace(path)) + { throw new ArgumentException("An editor menu path is required.", nameof(path)); + } this.path = path; this.order = order; this.separatorBefore = separatorBefore; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs index 962cda222..956c318bb 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs @@ -29,7 +29,9 @@ public void AddGroup( bool separatorBefore = false ) { if (string.IsNullOrWhiteSpace(path)) + { throw new ArgumentException("A menu group path is required.", nameof(path)); + } m_groups.Add(new EditorMenuGroupPlacement(path, order, separatorBefore)); } @@ -62,7 +64,9 @@ public void Add( object? argument = null ) { if (string.IsNullOrWhiteSpace(path)) + { throw new ArgumentException("A menu path is required.", nameof(path)); + } ArgumentException.ThrowIfNullOrWhiteSpace(actionId); m_items.Add(new EditorMenuPlacement(path, actionId, order, separatorBefore, argument)); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs index 3f3ba1b03..303effd96 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs @@ -10,8 +10,7 @@ internal sealed class EditorMenuCatalog( EditorExtensionCatalog catalog, EditorActionRouter actions, Logger log -) -{ +) { private readonly HashSet m_sourceFailures = new(StringComparer.Ordinal); private Dictionary? m_templates; @@ -23,7 +22,9 @@ internal EditorMenuModel Build(EditorMenuContext context) foreach (EditorExtensionCatalog.MenuSourceRegistration registration in catalog.extensions.menuSources) { if (!string.Equals(registration.area, context.area, StringComparison.Ordinal)) + { continue; + } try { var builder = new EditorMenuBuilder(); @@ -31,25 +32,37 @@ internal EditorMenuModel Build(EditorMenuContext context) string sourceName = registration.type.FullName ?? registration.type.Name; m_sourceFailures.Remove(sourceName); if (builder.groups.Count == 0 && builder.items.Count == 0) + { continue; + } var placements = new List(builder.groups.Count + builder.items.Count); foreach (var group in builder.groups) + { placements.Add(CreatePlacement(group.path, null, group.order, group.separatorBefore, null)); + } foreach (var item in builder.items) + { placements.Add(CreatePlacement(item.path, item.actionId, item.order, item.separatorBefore, item.argument)); + } dynamicPlacements.AddRange(placements); } catch (Exception exception) { string sourceName = registration.type.FullName ?? registration.type.Name; if (m_sourceFailures.Add(sourceName)) + { log.Write(LogLevel.Error, "Editor menu source '{0}' failed: {1}", [sourceName, exception]); + } } } if (dynamicPlacements.Count > 0) { - foreach (Placement placement in dynamicPlacements.OrderBy(static value => value.order).ThenBy(static value => value.path, StringComparer.Ordinal)) + foreach (Placement placement in dynamicPlacements + .OrderBy(static value => value.order) + .ThenBy(static value => value.path, StringComparer.Ordinal) + ) { template = Merge(template, placement, 0); + } } return new EditorMenuModel(Resolve(template, context)); } @@ -70,7 +83,9 @@ private TemplateNode[] GetTemplate(string area) foreach (EditorMenuAttribute menu in registration.menus) { if (!placementsByArea.TryGetValue(menu.area, out List? placements)) + { placementsByArea.Add(menu.area, placements = []); + } placements.Add(CreatePlacement(menu.path, registration.id, menu.order, menu.separatorBefore, null)); } } @@ -78,8 +93,12 @@ private TemplateNode[] GetTemplate(string area) foreach ((string key, List placements) in placementsByArea) { var root = new MutableNode(string.Empty, 0, false); - foreach (Placement placement in placements.OrderBy(static value => value.order).ThenBy(static value => value.path, StringComparer.Ordinal)) + foreach (Placement placement in placements + .OrderBy(static value => value.order) + .ThenBy(static value => value.path, StringComparer.Ordinal) + ) { AddPlacement(root, placement); + } templates.Add(key, FreezeTemplate(root.children.Values)); } m_templates = templates; @@ -92,7 +111,9 @@ private IReadOnlyList Resolve( EditorMenuContext context ) { if (nodes.Length == 0) + { return Array.Empty(); + } var result = new List(nodes.Length); foreach (TemplateNode node in nodes) { @@ -107,7 +128,9 @@ EditorMenuContext context { EditorActionState candidate = actions.Query(action, context.CreateActionContext(placement.argument)); if (!candidate.isVisible) + { continue; + } actionPlacement = placement; state = candidate; } @@ -117,17 +140,30 @@ EditorMenuContext context if (actionPlacement is null) { if (children.Count == 0) + { continue; + } state = EditorActionState.enabled; } string label = string.IsNullOrWhiteSpace(state.displayName) ? node.label : state.displayName!; - result.Add(new EditorMenuItem(label, actionPlacement?.actionId ?? string.Empty, order, - separatorBefore, state, children, actionPlacement?.argument)); + result.Add( + new EditorMenuItem( + label, + actionPlacement?.actionId ?? string.Empty, + order, + separatorBefore, + state, + children, + actionPlacement?.argument + ) + ); } for (int index = 1; index < result.Count; index++) { if (result[index - 1].order <= result[index].order) + { continue; + } result.Sort(static ( left, right @@ -146,7 +182,9 @@ private static Placement CreatePlacement( ) { string[] segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (segments.Length == 0) + { throw new InvalidOperationException("An editor menu path must contain at least one segment."); + } return new Placement(string.Join('/', segments), segments, actionId, order, separatorBefore, argument); } @@ -160,8 +198,11 @@ Placement placement string segment = placement.segments[index]; if (!current.children.TryGetValue(segment, out MutableNode? child)) { - child = new MutableNode(segment, placement.order, - index == placement.segments.Length - 1 && placement.separatorBefore); + child = new MutableNode( + segment, + placement.order, + index == placement.segments.Length - 1 && placement.separatorBefore + ); current.children.Add(segment, child); } current = child; @@ -172,9 +213,16 @@ Placement placement } private static TemplateNode[] FreezeTemplate(IEnumerable nodes) - => nodes.OrderBy(static value => value.order).ThenBy(static value => value.label, StringComparer.Ordinal) - .Select(static node => new TemplateNode(node.label, node.order, node.separatorBefore, - node.placements.OrderBy(static placement => placement.order).ToArray(), FreezeTemplate(node.children.Values))).ToArray(); + => nodes.OrderBy(static value => value.order) + .ThenBy(static value => value.label, StringComparer.Ordinal) + .Select(static node => new TemplateNode( + node.label, + node.order, + node.separatorBefore, + node.placements.OrderBy(static placement => placement.order).ToArray(), + FreezeTemplate(node.children.Values) + )) + .ToArray(); private static TemplateNode[] Merge( TemplateNode[] nodes, @@ -186,7 +234,9 @@ int depth for (int candidate = 0; candidate < nodes.Length; candidate++) { if (!string.Equals(nodes[candidate].label, label, StringComparison.Ordinal)) + { continue; + } index = candidate; break; } @@ -197,14 +247,21 @@ int depth { int insertion = 0; while (insertion < placements.Length && placements[insertion].order <= placement.order) + { insertion++; + } placements = new Placement[current.placements.Length + 1]; Array.Copy(current.placements, placements, insertion); placements[insertion] = placement; Array.Copy(current.placements, insertion, placements, insertion + 1, current.placements.Length - insertion); } - TemplateNode replacement = new(label, current.order, current.separatorBefore, placements, - leaf ? current.children : Merge(current.children, placement, depth + 1)); + TemplateNode replacement = new( + label, + current.order, + current.separatorBefore, + placements, + leaf ? current.children : Merge(current.children, placement, depth + 1) + ); var result = new TemplateNode[nodes.Length + (index < 0 ? 1 : 0)]; Array.Copy(nodes, result, nodes.Length); result[index >= 0 ? index : nodes.Length] = replacement; @@ -236,8 +293,7 @@ private sealed class MutableNode( string label, int order, bool separatorBefore - ) - { + ) { internal string label = label; internal int order = order; internal bool separatorBefore = separatorBefore; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuContext.cs index 4c7f68e3c..b63ee67f4 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuContext.cs @@ -1,5 +1,4 @@ using System; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuItem.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuItem.cs index 10b595b37..87c4c3afc 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuItem.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuItem.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Scripting.Api; namespace Inno.Editor.Interactions; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuSourceAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuSourceAttribute.cs index de2fc14f2..07534a167 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuSourceAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuSourceAttribute.cs @@ -25,7 +25,9 @@ public EditorMenuSourceAttribute( int priority = 0 ) { if (string.IsNullOrWhiteSpace(area)) + { throw new ArgumentException("An editor menu area is required.", nameof(area)); + } this.area = area; this.priority = priority; } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Properties/ScriptingApi.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Properties/ScriptingApi.cs index d5b8f332f..ed033ac76 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Properties/ScriptingApi.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Interactions; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Interactions", "Inno.Editor.Interactions", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorInteractions), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteraction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteraction.cs index ce91feaeb..2885f6335 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteraction.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteraction.cs @@ -2,6 +2,7 @@ using Inno.Core.Identity; namespace Inno.Editor.Interactions; + /// /// Provides a fluent handle that borrows an optional target for a synchronous interaction request. /// @@ -14,6 +15,7 @@ namespace Inno.Editor.Interactions; public readonly struct EditorInteraction { private readonly EditorInteractions m_interactions; + internal EditorInteraction( EditorInteractions interactions, string area, @@ -29,10 +31,12 @@ internal EditorInteraction( /// Gets the stable interaction area. /// public string area { get; } + /// /// Gets the borrowed target without extending its validity or resolving a replacement generation. /// public object? target { get; } + /// /// Gets whether this handle's target is the current editor selection. /// @@ -42,6 +46,7 @@ internal EditorInteraction( /// Marks this area and target as the active keyboard context. /// public void Focus() => m_interactions.Focus(area, target); + /// /// Selects this target, or clears selection when the target is . /// @@ -49,6 +54,7 @@ internal EditorInteraction( /// when the built-in selection action executed; otherwise, . /// public bool Select() => Execute(target is null ? EditorBuiltInInteractionIds.C_CLEAR_SELECTION : EditorBuiltInInteractionIds.C_SELECT); + /// /// Queries an action for this area and target. /// @@ -68,6 +74,7 @@ public EditorActionState Query( string action, object? argument = null ) => m_interactions.Query(action, area, target, argument); + /// /// Executes an action for this area and target. /// @@ -87,6 +94,7 @@ public bool Execute( string action, object? argument = null ) => m_interactions.Execute(action, area, target, argument); + /// /// Queues an action until the current UI traversal completes. /// @@ -103,6 +111,7 @@ public void Enqueue( string action, object? argument = null ) => m_interactions.Enqueue(action, area, target, argument); + /// /// Presents an active action in place of this target's normal content. /// @@ -122,6 +131,7 @@ public bool Present( string action, object? argument = null ) => m_interactions.Present(action, area, target, argument); + /// /// Gets whether an action owns an active multi-frame operation for this target. /// @@ -135,6 +145,7 @@ public bool Present( /// Thrown when is empty. /// public bool IsActive(string action) => m_interactions.IsActive(action, area, target); + /// /// Builds the complete contextual menu for this area and target. /// @@ -142,6 +153,7 @@ public bool Present( /// The immutable resolved menu model. /// public EditorMenuModel BuildMenu() => m_interactions.BuildMenu(area, target); + /// /// Builds searchable commands from this area's menus and applicable unplaced Actions. /// @@ -149,6 +161,7 @@ public bool Present( /// Current command states and neutral placement arguments; execution revalidates their targets. /// public EditorMenuModel BuildCommands() => m_interactions.BuildCommands(area, target); + /// /// Builds the complete compact toolbar for this area and target. /// @@ -156,6 +169,7 @@ public bool Present( /// The immutable resolved toolbar model. /// public EditorToolbarModel BuildToolbar() => m_interactions.BuildToolbar(area, target); + /// /// Resolves the shortcut displayed for an action in this area. /// @@ -175,6 +189,7 @@ public bool TryGetShortcut( string action, out HotKeyGesture gesture ) => m_interactions.TryGetShortcut(action, area, target, out gesture); + /// /// Gets the currently active drag identity, if its source remains registered. /// @@ -185,6 +200,7 @@ out HotKeyGesture gesture /// when a live drag source exists; otherwise, . /// public bool TryGetActiveDragIdentity(out RuntimeIdentity identity) => m_interactions.TryGetActiveDragIdentity(out identity); + /// /// Begins a managed drag originating from this area. /// @@ -195,6 +211,7 @@ out HotKeyGesture gesture /// The source object's domain-qualified transient identity. /// public RuntimeIdentity BeginDrag(EditorDragData data) => m_interactions.BeginDrag(area, data); + /// /// Queries this handle as a drop target. /// @@ -211,6 +228,7 @@ public EditorDropStatus QueryDrop( RuntimeIdentity identity, EditorDropPlacement placement = EditorDropPlacement.None ) => m_interactions.QueryDrop(identity, area, target, placement); + /// /// Delivers a managed drop to this target. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs index 2e36ebe29..ee22a6fc7 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs @@ -1,13 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Events; using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Editor.Core; +using Inno.Extensibility.Types; namespace Inno.Editor.Interactions; @@ -48,10 +47,7 @@ public EditorInteractionRuntime( TypeCatalog types, LogRouter logs, EditorKeyboardPolicy keyboard - ) - : this(new EditorContext(projectDirectory, keyboard), types, logs) - { - } + ) : this(new EditorContext(projectDirectory, keyboard), types, logs) {} /// /// Creates an interaction runtime for an existing passive editor context. @@ -72,10 +68,7 @@ public EditorInteractionRuntime( EditorContext context, TypeCatalog types, LogRouter logs - ) - : this(context, types, logs, Array.Empty()) - { - } + ) : this(context, types, logs, Array.Empty()) {} /// /// Creates an interaction runtime with stable host-owned extension services. @@ -100,25 +93,22 @@ public EditorInteractionRuntime( TypeCatalog types, LogRouter logs, IEnumerable hostServices - ) - : base(context) + ) : base(context) { ArgumentNullException.ThrowIfNull(types); ArgumentNullException.ThrowIfNull(logs); ArgumentNullException.ThrowIfNull(hostServices); Logger logger = logs.CreateLogger(); object[] services = hostServices.ToArray(); - m_interactions = new EditorInteractions( - context, - services.OfType(), - logger); + m_interactions = new EditorInteractions(context, services.OfType(), logger); m_catalog = new EditorExtensionCatalog( types, context, m_interactions, logger, new object[] { logs }.Concat(services), - InvalidateDescriptions); + InvalidateDescriptions + ); m_interactions.Attach(m_catalog); } @@ -163,9 +153,13 @@ public override void Start() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("A retiring editor runtime cannot restart."); + } if (m_started) + { return; + } _ = m_catalog.extensions; m_started = true; } @@ -180,9 +174,13 @@ public override void Update(EditorFrame frame) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("A retiring editor runtime cannot update."); + } if (!m_started) + { Start(); + } SetFrame(frame); m_interactions.Update(); m_catalog.UpdateModules(); @@ -233,7 +231,9 @@ public void HandleKeyPressed(KeyPressedEvent keyEvent) { ArgumentNullException.ThrowIfNull(keyEvent); if (m_interactions.DispatchShortcut(keyEvent)) + { keyEvent.HandleInGlobal(); + } } /// @@ -248,7 +248,9 @@ public void HandleKeyPressed(KeyPressedEvent keyEvent) public override void Dispose() { if (m_disposed) + { return; + } if (!m_stopping) { m_stopping = true; @@ -275,7 +277,8 @@ public override void Dispose() { var failure = new AggregateException( "One or more editor interaction shutdown stages failed.", - m_shutdownFailures); + m_shutdownFailures + ); m_shutdownFailures.Clear(); throw failure; } @@ -285,21 +288,28 @@ private void RefreshDescriptions() { EditorExtensionCatalog.Snapshot snapshot = m_catalog.extensions; if (ReferenceEquals(snapshot, m_describedSnapshot)) + { return; + } var panels = new List(snapshot.panels.Length); for (int i = 0; i < snapshot.panels.Length; i++) { EditorExtensionCatalog.PanelRegistration registration = snapshot.panels[i]; if (snapshot.quarantinedPanels.Contains(registration.panel)) + { continue; - panels.Add(new EditorPanelExtension( - registration.attribute.id, - registration.attribute.title, - registration.attribute.order, - registration.panel, - () => m_catalog.TakePanelFocusRequest(registration.attribute.id), - exception => m_catalog.QuarantinePanel(snapshot, registration, exception))); + } + panels.Add( + new EditorPanelExtension( + registration.attribute.id, + registration.attribute.title, + registration.attribute.order, + registration.panel, + () => m_catalog.TakePanelFocusRequest(registration.attribute.id), + exception => m_catalog.QuarantinePanel(snapshot, registration, exception) + ) + ); } m_panels = panels.ToArray(); @@ -308,13 +318,18 @@ private void RefreshDescriptions() { EditorExtensionCatalog.ModalRegistration registration = snapshot.modals[i]; if (snapshot.quarantinedModals.Contains(registration.modal)) + { continue; - modals.Add(new EditorModalExtension( - registration.attribute.id, - registration.attribute.title, - registration.attribute.order, - registration.modal, - exception => m_catalog.QuarantineModal(snapshot, registration, exception))); + } + modals.Add( + new EditorModalExtension( + registration.attribute.id, + registration.attribute.title, + registration.attribute.order, + registration.modal, + exception => m_catalog.QuarantineModal(snapshot, registration, exception) + ) + ); } m_modals = modals.ToArray(); m_describedSnapshot = snapshot; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs index 5cd3b36d6..5d9eae810 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs @@ -5,10 +5,11 @@ using Inno.Core.Events; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Scripting.Api; using Inno.Editor.Core; +using Inno.Scripting.Api; namespace Inno.Editor.Interactions; + /// /// Provides the single presentation-independent entry point for editor actions, menus, selection, focus, and drag-and-drop. /// @@ -32,6 +33,7 @@ public sealed class EditorInteractions : IEditorSelectionCoordinator, IEditorHis private EditorTargetReference? m_previousGenerationFocus; private EditorTargetReference? m_previousGenerationAnchor; private bool m_generationTransitionPrepared; + internal EditorInteractions( EditorContext editor, IEnumerable identityDomains, @@ -43,7 +45,10 @@ Logger log m_log = log ?? throw new ArgumentNullException(nameof(log)); selection = new EditorSelectionState(this); m_documents = new EditorDocumentService(events); - m_history = new EditorHistory(new EditorHistoryOptions { cacheDirectory = Path.Combine(editor.projectDirectory, "Library", "Editor", "History") }, log); + m_history = new EditorHistory( + new EditorHistoryOptions { cacheDirectory = Path.Combine(editor.projectDirectory, "Library", "Editor", "History") }, + log + ); m_history.Attach(editor, this); } @@ -57,6 +62,7 @@ Logger log public EventDispatcher events { get; } = new(); internal void PrepareOperation() => events.Emit(new EditorOperationPreparingEvent()); + /// /// Gets the shared read-only editor selection state. /// @@ -68,10 +74,12 @@ Logger log public EditorKeyboardPolicy keyboard => m_editor.keyboard; object? IEditorSelectionCoordinator.selectedTarget => selection.selectedTarget; + /// /// Gets the transactional Undo and Redo history owned by this editor runtime. /// public IEditorHistory history => m_history; + /// /// Gets the headless reload-safe document lifetime used by dedicated asset editors and Inspectors. /// @@ -96,7 +104,9 @@ public bool TryGetModule(out TModule? module) where TModule : EditorModule { if (m_catalog is not null) + { return m_catalog.TryGetModule(out module); + } module = null; return false; } @@ -116,7 +126,9 @@ public bool TryGetModule(out TModule? module) /// [ScriptingApiIgnore] public IDisposable BeginHistoryIsolation() => m_history.BeginIsolation(); + internal EditorHistory historyHost => m_history; + /// /// Gets the area that most recently received keyboard focus. /// @@ -128,7 +140,9 @@ public bool TryGetModule(out TModule? module) /// /// Current panel declarations; the snapshot contains no panel or extension instances. /// - public IReadOnlyList GetPanelDeclarations() => m_catalog?.GetPanelDeclarations() ?? Array.Empty(); + public IReadOnlyList GetPanelDeclarations() + => m_catalog?.GetPanelDeclarations() ?? Array.Empty(); + /// /// Reads whether one available panel is currently open. /// @@ -174,6 +188,7 @@ public EditorInteraction For( string area, object? target = null ) => new(this, area, target); + /// /// Replaces the editor selection after closing presentations owned by other targets. /// @@ -184,9 +199,13 @@ public void SetSelection(object? target) { PrepareOperation(); if (target is null) + { selection.Clear(); + } else + { selection.Select(target); + } PrepareSelectionChange(target); } @@ -230,7 +249,9 @@ public void ToggleSelection(IdentityObject target) _ = selection.CopyTargets(values); bool removed = values.Remove(target); if (!removed) + { values.Add(target); + } SetSelection(values, selection.anchor as IdentityObject ?? target); } @@ -268,13 +289,19 @@ public void SelectRange( for (int i = 0; i < orderedTargets.Count; i++) { if (orderedTargets[i] == anchor.identity.runtimeIdentity) + { first = i; + } if (orderedTargets[i] == target.identity.runtimeIdentity) + { last = i; + } } if (last < 0) + { throw new ArgumentException("The selection endpoint is not in the visible order.", nameof(target)); + } if (first < 0) { first = last; @@ -283,14 +310,20 @@ public void SelectRange( var values = new List(); if (additive) + { _ = selection.CopyTargets(values); + } var included = new HashSet(values, ReferenceEqualityComparer.Instance); for (int i = Math.Min(first, last); i <= Math.Max(first, last); i++) { if (!TryResolveIdentity(orderedTargets[i], out IdentityObject? value) || value is null) + { throw new InvalidOperationException("The visible selection range contains an unavailable identity."); + } if (!ReferenceEquals(value, target) && included.Add(value)) + { values.Add(value); + } } _ = values.Remove(target); @@ -314,6 +347,7 @@ public bool TryGetDragSource( RuntimeIdentity identity, out IdentityObject? source ) => Drops.TryGetSource(identity, out source); + /// /// Gets the active drag identity used to select the matching native payload domain. /// @@ -324,6 +358,7 @@ out IdentityObject? source /// when a live drag source exists; otherwise, . /// public bool TryGetActiveDragIdentity(out RuntimeIdentity identity) => Drops.TryGetActiveIdentity(out identity); + /// /// Toggles one panel in the currently active extension generation. /// @@ -367,7 +402,9 @@ public IDisposable RegisterIdentityDomain(IdentityAllocator allocator) EnsureIdentityDomainOwner(); ObjectDisposedException.ThrowIf(m_identityDomainsRetired, this); if (!m_identityDomains.TryAdd(allocator.domainId, allocator)) + { throw new InvalidOperationException("The Editor identity domain is already registered."); + } return new IdentityDomainLease(this, allocator.domainId); } @@ -388,7 +425,9 @@ public bool TryResolveIdentity( RuntimeIdentity identity, out IdentityObject? target ) { - target = m_identityDomains.TryGetValue(identity.domainId, out IdentityAllocator? allocator) ? allocator.Get(identity) : null; + target = m_identityDomains.TryGetValue(identity.domainId, out IdentityAllocator? allocator) + ? allocator.Get(identity) + : null; return target is not null; } @@ -413,7 +452,9 @@ public bool TryResolveIdentity( Guid persistentId, out IdentityObject? target ) { - target = persistentId != Guid.Empty && m_identityDomains.TryGetValue(domainId, out IdentityAllocator? allocator) ? allocator.Get(persistentId) : null; + target = persistentId != Guid.Empty && m_identityDomains.TryGetValue(domainId, out IdentityAllocator? allocator) + ? allocator.Get(persistentId) + : null; return target is not null; } @@ -472,7 +513,9 @@ internal void Update() internal void PrepareGenerationTransition() { if (m_generationTransitionPrepared) + { throw new InvalidOperationException("An interaction generation transition is already active."); + } m_previousGenerationSelection = selection.CaptureReferences(); m_previousGenerationAnchor = selection.anchorReference; m_previousGenerationFocus = m_focus; @@ -485,7 +528,9 @@ internal void RollbackGenerationTransition() { Actions.ResetTransientState(); if (m_previousGenerationSelection is not null) + { selection.Restore(m_previousGenerationSelection, m_previousGenerationAnchor); + } m_focus = m_previousGenerationFocus; CompleteGenerationTransition(); } @@ -520,7 +565,9 @@ internal void Shutdown(IReadOnlyList m_identityDomainsRetired = true; } - internal bool DispatchShortcut(KeyPressedEvent keyEvent) => Actions.DispatchShortcut(keyEvent, m_focusedArea, focusedTarget ?? selection.selectedTarget); + internal bool DispatchShortcut(KeyPressedEvent keyEvent) + => Actions.DispatchShortcut(keyEvent, m_focusedArea, focusedTarget ?? selection.selectedTarget); + internal void Focus( string area, object? target @@ -530,39 +577,46 @@ internal void Focus( } internal void PrepareSelectionChange(object? target) => Actions.LosePresentationExcept(target); + internal EditorActionState Query( string action, string area, object? target, object? argument ) => Actions.Query(action, CreateActionContext(area, target, argument)); + internal bool Execute( string action, string area, object? target, object? argument ) => Actions.Execute(action, CreateActionContext(area, target, argument)); + internal void Enqueue( string action, string area, object? target, object? argument ) => Actions.Enqueue(action, CreateActionContext(area, target, argument)); + internal bool Present( string action, string area, object? target, object? argument ) => Actions.Present(action, CreateActionContext(area, target, argument)); + internal bool IsActive( string action, string area, object? target ) => Actions.IsActive(action, CreateActionContext(area, target, null)); + internal EditorMenuModel BuildMenu( string area, object? target ) => Menus.Build(new EditorMenuContext(m_editor, this, area, target)); + internal EditorMenuModel BuildCommands( string area, object? target @@ -577,7 +631,9 @@ void Collect(IReadOnlyList items) foreach (EditorMenuItem item in items) { if (item.actionId.Length != 0) + { _ = placed.Add(item.actionId); + } Collect(item.children); } } @@ -587,18 +643,22 @@ internal EditorToolbarModel BuildToolbar( string area, object? target ) => Toolbars.Build(CreateActionContext(area, target, argument: null)); + internal bool TryGetShortcut( string action, string area, object? target, out HotKeyGesture gesture ) => Actions.TryGetShortcut(action, area, target, out gesture); + internal RuntimeIdentity BeginDrag( string area, EditorDragData data ) { if (m_catalog is null) + { throw new InvalidOperationException("Editor interactions are not attached to a runtime."); + } _ = m_catalog.extensions; return Drops.Begin(new EditorDragContext(m_editor, this, area, data)); } @@ -610,8 +670,13 @@ internal EditorDropStatus QueryDrop( EditorDropPlacement placement ) { if (target is null || !Drops.TryGetSource(identity, out IdentityObject? source) || source is null) + { return EditorDropStatus.rejected; - return Drops.Query(identity, new EditorDropContext(m_editor, this, area, new EditorDragData(source, string.Empty), source, target, placement)); + } + return Drops.Query( + identity, + new EditorDropContext(m_editor, this, area, new EditorDragData(source, string.Empty), source, target, placement) + ); } internal EditorDropResult Drop( @@ -621,29 +686,42 @@ internal EditorDropResult Drop( EditorDropPlacement placement ) { if (target is null || !Drops.TryGetSource(identity, out IdentityObject? source) || source is null) + { return EditorDropResult.rejected; - return Drops.Drop(identity, new EditorDropContext(m_editor, this, area, new EditorDragData(source, string.Empty), source, target, placement)); + } + return Drops.Drop( + identity, + new EditorDropContext(m_editor, this, area, new EditorDragData(source, string.Empty), source, target, placement) + ); } - private EditorActionRouter Actions => m_actions ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); + private EditorActionRouter Actions + => m_actions ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); + private EditorMenuCatalog Menus => m_menus ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); private EditorDropRouter Drops => m_drops ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); - private EditorToolbarCatalog Toolbars => m_toolbars ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); + + private EditorToolbarCatalog Toolbars + => m_toolbars ?? throw new InvalidOperationException("Editor interactions are not attached to a runtime."); private EditorActionContext CreateActionContext( string area, object? target, object? argument ) => new(m_editor, this, area, target, argument); + private void ResolveGenerationTargets() { selection.Rebind(); m_focus = m_focus?.Rebind(this); } + private void EnsureIdentityDomainOwner() { if (Environment.CurrentManagedThreadId != m_identityOwnerThread) + { throw new InvalidOperationException("Editor identity domains must be changed on the owning thread."); + } } private sealed class IdentityDomainLease( @@ -652,16 +730,18 @@ IdentityDomainId domain ) : IDisposable { private EditorInteractions? m_owner = owner; + /// public void Dispose() { EditorInteractions? active = m_owner; if (active is null) + { return; + } active.EnsureIdentityDomainOwner(); active.m_identityDomains.Remove(domain); m_owner = null; } } - } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorModalExtension.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorModalExtension.cs index 1f0cfd394..8cbd12c52 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorModalExtension.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorModalExtension.cs @@ -1,6 +1,5 @@ using System; using System.Numerics; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -73,15 +72,21 @@ out Vector2? contentSize ArgumentNullException.ThrowIfNull(context); contentSize = null; if (m_isQuarantined) + { return false; + } try { contentSize = m_modal.Prepare(context, availableContentSize); - if (contentSize is Vector2 size && - (!float.IsFinite(size.X) || !float.IsFinite(size.Y) || size.X < 0f || size.Y < 0f)) + if (contentSize is Vector2 size + && (!float.IsFinite(size.X) || !float.IsFinite(size.Y) || size.X < 0f || size.Y < 0f) + ) { throw new InvalidOperationException("Modal preparation returned an invalid content extent."); + } if (presentation.initialSize.Y <= 0f && contentSize is null) + { throw new InvalidOperationException("A content-sized modal must measure its current content before drawing."); + } return true; } catch (Exception exception) @@ -118,12 +123,17 @@ public bool TryGetPresentation(out Presentation presentation) m_modal.canResize, m_modal.allowScrolling, m_modal.initialSize, - m_modal.minimumSize); + m_modal.minimumSize + ); Vector2 initial = presentation.initialSize; Vector2 minimum = presentation.minimumSize; - if (!float.IsFinite(initial.X) || !float.IsFinite(initial.Y) || initial.X < 0f || initial.Y < 0f || - !float.IsFinite(minimum.X) || !float.IsFinite(minimum.Y) || minimum.X < 0f || minimum.Y < 0f) - throw new InvalidOperationException("Modal dimensions must be finite and nonnegative; zero leaves that dimension unspecified."); + if (!float.IsFinite(initial.X) || !float.IsFinite(initial.Y) || initial.X < 0f || initial.Y < 0f + || !float.IsFinite(minimum.X) || !float.IsFinite(minimum.Y) || minimum.X < 0f || minimum.Y < 0f + ) { + throw new InvalidOperationException( + "Modal dimensions must be finite and nonnegative; zero leaves that dimension unspecified." + ); + } return true; } catch (Exception exception) @@ -151,7 +161,9 @@ public bool Draw(EditorContext context) { ArgumentNullException.ThrowIfNull(context); if (m_isQuarantined) + { return false; + } try { m_modal.Draw(context); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs index 9bbf7727a..6ebd6a8aa 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs @@ -1,6 +1,5 @@ using System; using System.Numerics; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -89,7 +88,9 @@ out Vector2 initialSize allowScrolling = m_panel.allowScrolling; initialSize = m_panel.initialSize; if (!float.IsFinite(initialSize.X) || !float.IsFinite(initialSize.Y) || initialSize.X < 0 || initialSize.Y < 0) + { throw new InvalidOperationException("A panel's initial size must contain finite nonnegative dimensions."); + } return true; } catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorTargetReference.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorTargetReference.cs index 790e2a766..bd3012841 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorTargetReference.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorTargetReference.cs @@ -2,10 +2,12 @@ using Inno.Core.Identity; namespace Inno.Editor.Interactions; + internal sealed class EditorTargetReference { private readonly object? m_value; private readonly WeakReference? m_target; + private EditorTargetReference( RuntimeIdentity? runtimeIdentity, Guid persistentId, @@ -25,16 +27,21 @@ internal static EditorTargetReference Capture(object? value) { if (value is IdentityObject target) { - RuntimeIdentity runtime = target.identity.runtimeIdentity ?? throw new InvalidOperationException("An editor interaction target must belong to a live identity domain."); + RuntimeIdentity runtime = target.identity.runtimeIdentity + ?? throw new InvalidOperationException("An editor interaction target must belong to a live identity domain."); return new EditorTargetReference(runtime, target.identity.persistentId, null, null); } if (value is null or string or decimal or Guid or DateTime or DateTimeOffset - or DateOnly or TimeOnly or TimeSpan or Half or Int128 or UInt128) + or DateOnly or TimeOnly or TimeSpan or Half or Int128 or UInt128 + ) { return new EditorTargetReference(null, Guid.Empty, value, null); + } Type type = value.GetType(); if (type.IsPrimitive || type.IsEnum && !type.IsCollectible) + { return new EditorTargetReference(null, Guid.Empty, value, null); + } // A host-defined struct can still contain extension objects; boxing does not make it neutral. return new EditorTargetReference(null, Guid.Empty, null, new WeakReference(value)); } @@ -42,14 +49,18 @@ internal static EditorTargetReference Capture(object? value) internal object? Resolve(EditorInteractions interactions) { if (runtimeIdentity is RuntimeIdentity runtime) + { return interactions.TryResolveIdentity(runtime, out IdentityObject? target) ? target : null; + } return m_target is not null ? m_target.TryGetTarget(out object? value) ? value : null : m_value; } internal EditorTargetReference Rebind(EditorInteractions interactions) { if (runtimeIdentity is not RuntimeIdentity runtime || interactions.TryResolveIdentity(runtime, out _)) + { return this; + } if (interactions.TryResolveIdentity(runtime.domainId, persistentId, out IdentityObject? replacement) && replacement is not null) { return Capture(replacement); @@ -63,7 +74,9 @@ internal bool Matches( object? target ) { if (target is IdentityObject identity && runtimeIdentity is RuntimeIdentity runtime) + { return identity.identity.runtimeIdentity == runtime; + } return Equals(Resolve(interactions), target); } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionSnapshot.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionSnapshot.cs index 2c07a9d0e..8ddf425ce 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionSnapshot.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionSnapshot.cs @@ -4,18 +4,22 @@ using Inno.Core.Identity; namespace Inno.Editor.Interactions; + /// /// Captures ordered selection identities without retaining any domain object or extension instance. /// public sealed class EditorSelectionSnapshot { private readonly EditorTargetReference[] m_targets; + internal EditorSelectionSnapshot( IEnumerable targets, RuntimeIdentity? anchor ) { m_targets = targets.ToArray(); - this.identities = Array.AsReadOnly(m_targets.Where(value => value.runtimeIdentity is not null).Select(value => value.runtimeIdentity!.Value).ToArray()); + this.identities = Array.AsReadOnly( + m_targets.Where(value => value.runtimeIdentity is not null).Select(value => value.runtimeIdentity!.Value).ToArray() + ); this.anchor = anchor; } @@ -23,6 +27,7 @@ internal EditorSelectionSnapshot( /// Gets unique selection identities in order; the final identity is the primary selection. /// public IReadOnlyList identities { get; } + /// /// Gets the range anchor identity, or null when there is no registered anchor. /// @@ -46,15 +51,18 @@ internal EditorSelectionSnapshot( public int CopyTargets( EditorInteractions interactions, ICollection destination - ) - where TTarget : class + ) where TTarget : class { ArgumentNullException.ThrowIfNull(interactions); ArgumentNullException.ThrowIfNull(destination); destination.Clear(); foreach (EditorTargetReference reference in m_targets) + { if (reference.Rebind(interactions).Resolve(interactions) is TTarget target) + { destination.Add(target); + } + } return destination.Count; } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionState.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionState.cs index 93647e5cb..4cf1bb645 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionState.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Selection/EditorSelectionState.cs @@ -4,6 +4,7 @@ using Inno.Core.Identity; namespace Inno.Editor.Interactions; + /// /// Owns ordered transient selection through domain-qualified identities instead of retaining live objects. /// @@ -14,6 +15,7 @@ public sealed class EditorSelectionState private HashSet m_identityMembership = []; private EditorTargetReference? m_anchor; private EditorSelectionSnapshot? m_snapshot; + internal EditorSelectionState(EditorInteractions interactions) { m_interactions = interactions; @@ -23,14 +25,17 @@ internal EditorSelectionState(EditorInteractions interactions) /// Gets the current primary target for this callback, or null when unavailable or unselected. /// public object? selectedTarget => m_targets.Length == 0 ? null : m_targets[^1].Resolve(m_interactions); + /// /// Gets the number of selected identities, including temporarily unavailable members. /// public int count => m_targets.Length; + /// /// Gets the current range anchor, or null when the anchor is unavailable. /// public object? anchor => m_anchor?.Resolve(m_interactions); + /// /// Gets the selection revision, incremented only when membership, order or resolved generation changes. /// @@ -48,13 +53,19 @@ internal EditorSelectionState(EditorInteractions interactions) public bool Contains(object? target) { if (target is null) + { return false; + } if (target is IdentityObject identity) + { return identity.identity.runtimeIdentity is RuntimeIdentity runtime && m_identityMembership.Contains(runtime); + } foreach (EditorTargetReference entry in m_targets) { if (entry.Matches(m_interactions, target)) + { return true; + } } return false; @@ -83,7 +94,9 @@ public int CopyTargets(ICollection destination) foreach (EditorTargetReference entry in m_targets) { if (entry.Resolve(m_interactions) is TTarget target) + { destination.Add(target); + } } return destination.Count; @@ -98,7 +111,9 @@ public int CopyTargets(ICollection destination) public EditorSelectionSnapshot Capture() { if (m_snapshot is not null) + { return m_snapshot; + } return m_snapshot = new EditorSelectionSnapshot(m_targets, m_anchor?.runtimeIdentity); } @@ -130,7 +145,9 @@ internal void Select(object target) { ArgumentNullException.ThrowIfNull(target); if (m_targets.Length == 1 && m_targets[0].Matches(m_interactions, target)) + { return; + } EditorTargetReference entry = EditorTargetReference.Capture(target); m_targets = [entry]; m_anchor = entry; @@ -149,15 +166,21 @@ internal void Replace( ArgumentNullException.ThrowIfNull(target); EditorTargetReference entry = EditorTargetReference.Capture(target); if (seen.Add(entry.runtimeIdentity!.Value)) + { entries.Add(entry); + } } EditorTargetReference? nextAnchor = anchor is null ? entries.Count == 0 ? null : entries[0] : EditorTargetReference.Capture(anchor); bool equal = entries.Count == m_targets.Length && nextAnchor?.runtimeIdentity == m_anchor?.runtimeIdentity; for (int i = 0; equal && i < entries.Count; i++) + { equal = entries[i].runtimeIdentity == m_targets[i].runtimeIdentity; + } if (equal) + { return; + } m_targets = entries.ToArray(); m_anchor = nextAnchor; Changed(seen); @@ -166,7 +189,9 @@ internal void Replace( internal void Clear() { if (m_targets.Length == 0) + { return; + } m_targets = []; m_anchor = null; Changed(); @@ -175,6 +200,7 @@ internal void Clear() internal EditorTargetReference? anchorReference => m_anchor; internal EditorTargetReference[] CaptureReferences() => (EditorTargetReference[])m_targets.Clone(); + internal void Restore( EditorTargetReference[] targets, EditorTargetReference? anchor @@ -191,15 +217,21 @@ internal void Rebind() { EditorTargetReference rebound = m_targets[i].Rebind(m_interactions); if (rebound.runtimeIdentity == m_targets[i].runtimeIdentity) + { continue; + } m_targets[i] = rebound; changed = true; } if (m_anchor is not null) + { m_anchor = m_anchor.Rebind(m_interactions); + } if (changed) + { Changed(); + } } private void Changed(HashSet? identities = null) @@ -208,8 +240,12 @@ private void Changed(HashSet? identities = null) { identities = new HashSet(m_targets.Length); foreach (EditorTargetReference target in m_targets) + { if (target.runtimeIdentity is RuntimeIdentity identity) + { identities.Add(identity); + } + } } m_identityMembership = identities; m_snapshot = null; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateDiagnosticPublisher.cs b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateDiagnosticPublisher.cs index f32a7692b..ba19c102e 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateDiagnosticPublisher.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; namespace Inno.Editor.Interactions; @@ -32,7 +31,9 @@ internal bool PublishSave(Exception exception) public void Dispose() { foreach (string group in m_states.Keys.ToArray()) + { Resolve(group); + } } private bool Publish( @@ -51,14 +52,12 @@ IReadOnlyList messages return false; } string state = string.Join('\n', current); - if (m_states.TryGetValue(group, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_states.TryGetValue(group, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return false; } - Diagnostics.Set( - group, - current.Select(message => Diagnostic.Error(code, message))); + Diagnostics.Set(group, current.Select(message => Diagnostic.Error(code, message))); m_states[group] = state; return true; } @@ -66,7 +65,9 @@ IReadOnlyList messages private void Resolve(string group) { if (!m_states.Remove(group)) + { return; + } Diagnostics.Clear(group); } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateStore.cs b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateStore.cs index 8015ae51b..6b663b5db 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateStore.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorExtensionStateStore.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; - using Inno.Core.Logging; using Inno.Editor.Core; @@ -36,10 +35,10 @@ internal bool TryGetPanelOpen( out bool isOpen ) { ArgumentException.ThrowIfNullOrWhiteSpace(panelId); - if (m_context.TryGetLayoutSection(C_PANELS_SECTION, out IReadOnlyDictionary values) && - values.TryGetValue(panelId, out string? stored) && - bool.TryParse(stored, out isOpen)) - { + if (m_context.TryGetLayoutSection(C_PANELS_SECTION, out IReadOnlyDictionary values) + && values.TryGetValue(panelId, out string? stored) + && bool.TryParse(stored, out isOpen) + ) { return true; } isOpen = false; @@ -54,38 +53,39 @@ internal void Capture( for (int i = 0; i < registrations.Count; i++) { EditorExtensionCatalog.StateRegistration registration = registrations[i]; - if (!m_restoredOwners.TryGetValue(registration.owner, out RestoredOwner? owner) || - !owner.isRestored) - { + if (!m_restoredOwners.TryGetValue(registration.owner, out RestoredOwner? owner) + || !owner.isRestored + ) { continue; } try { var state = new EditorJsonState(); registration.capture(state); - m_context.SetLayoutSection( - GetSectionName(registration), - state.Export()); + m_context.SetLayoutSection(GetSectionName(registration), state.Export()); } catch (Exception exception) { - failures.Add(( - $"Extension '{registration.id}' failed to capture state: {exception.Message}", - exception)); + failures.Add( + ( + $"Extension '{registration.id}' failed to capture state: {exception.Message}", + exception) + ); } } if (m_diagnostics.PublishCapture(failures.Select(static failure => failure.Message).ToArray())) { for (int i = 0; i < failures.Count; i++) - m_log.Write( - LogLevel.Error, - "{0} Full exception: {1}", - [failures[i].Message, failures[i].Exception]); + { + m_log.Write(LogLevel.Error, "{0} Full exception: {1}", [failures[i].Message, failures[i].Exception]); + } } var panelValues = new Dictionary(StringComparer.Ordinal); for (int i = 0; i < panels.Count; i++) + { panelValues[panels[i].attribute.id] = panels[i].panel.isOpen ? "true" : "false"; + } m_context.SetLayoutSection(C_PANELS_SECTION, panelValues); } @@ -95,11 +95,11 @@ internal void Restore(IReadOnlyList re for (int i = 0; i < registrations.Count; i++) { EditorExtensionCatalog.StateRegistration registration = registrations[i]; - RestoredOwner owner = m_restoredOwners.GetValue( - registration.owner, - static _ => new RestoredOwner()); + RestoredOwner owner = m_restoredOwners.GetValue(registration.owner, static _ => new RestoredOwner()); if (owner.isRestored || owner.isRestoring) + { continue; + } owner.isRestoring = true; try { @@ -109,9 +109,11 @@ internal void Restore(IReadOnlyList re catch (Exception exception) { _ = m_restoredOwners.Remove(registration.owner); - failures.Add(( - $"Extension '{registration.id}' failed to restore state: {exception.Message}", - exception)); + failures.Add( + ( + $"Extension '{registration.id}' failed to restore state: {exception.Message}", + exception) + ); } finally { @@ -121,10 +123,9 @@ internal void Restore(IReadOnlyList re if (m_diagnostics.PublishRestore(failures.Select(static failure => failure.Message).ToArray())) { for (int i = 0; i < failures.Count; i++) - m_log.Write( - LogLevel.Error, - "{0} Full exception: {1}", - [failures[i].Message, failures[i].Exception]); + { + m_log.Write(LogLevel.Error, "{0} Full exception: {1}", [failures[i].Message, failures[i].Exception]); + } } SaveIfChanged(); } @@ -137,7 +138,9 @@ internal void Update( IReadOnlyList panels ) { if (m_isShutdownPrepared || elapsedSeconds < m_nextSaveTime) + { return; + } m_nextSaveTime = elapsedSeconds + C_SAVE_INTERVAL_SECONDS; Capture(registrations, panels); SaveIfChanged(); @@ -161,7 +164,9 @@ internal void PrepareShutdown( IReadOnlyList panels ) { if (m_isShutdownPrepared) + { return; + } // Freeze periodic persistence before capturing the terminal extension snapshot. Module // shutdown may unload scenes and clear panels, and that transient teardown state must @@ -175,7 +180,9 @@ private EditorState CreateState(EditorExtensionCatalog.StateRegistration registr { string sectionName = GetSectionName(registration); if (!m_context.TryGetLayoutSection(sectionName, out IReadOnlyDictionary values)) + { return new EditorJsonState(values: null); + } return new EditorJsonState(values); } @@ -193,7 +200,8 @@ private void SaveIfChanged() m_log.Write( LogLevel.Error, "Editor extension state could not be saved to '{0}': {1}", - [m_context.layoutPath, exception]); + [m_context.layoutPath, exception] + ); } } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorJsonState.cs b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorJsonState.cs index 7a16b23d3..c716a0381 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorJsonState.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/State/EditorJsonState.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Text.Json; - using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -43,7 +42,9 @@ T fallback ) { ArgumentException.ThrowIfNullOrWhiteSpace(key); if (!m_values.TryGetValue(key, out string? payload)) + { return fallback; + } try { T? value = JsonSerializer.Deserialize(payload); @@ -78,8 +79,7 @@ T value ArgumentException.ThrowIfNullOrWhiteSpace(key); if (m_writableValues is null) { - throw new InvalidOperationException( - "Editor state supplied for restoration cannot be modified."); + throw new InvalidOperationException("Editor state supplied for restoration cannot be modified."); } try { @@ -87,13 +87,12 @@ T value } catch (JsonException exception) { - throw new NotSupportedException( - $"Editor state value '{key}' cannot be serialized.", - exception); + throw new NotSupportedException($"Editor state value '{key}' cannot be serialized.", exception); } } internal IReadOnlyDictionary Export() => m_writableValues ?? throw new InvalidOperationException( - "Only editor state captured by an extension can be exported."); + "Only editor state captured by an extension can be exported." + ); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarCatalog.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarCatalog.cs index ed5950316..c02e200d5 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarCatalog.cs @@ -19,20 +19,27 @@ internal EditorToolbarModel Build(EditorActionContext context) { EditorToolbarItemAttribute placement = registration.toolbars[toolbarIndex]; if (!string.Equals(placement.area, context.area, StringComparison.Ordinal)) + { continue; + } EditorActionState status = actions.Query(registration.id, context); if (!status.isVisible) + { continue; + } EditorToolbarIcon icon = status.isChecked && placement.activeIcon != EditorToolbarIcon.None - ? placement.activeIcon - : placement.icon; - items.Add((new EditorToolbarItem( - registration.id, - icon, - status.displayName ?? placement.tooltip, - placement.order, - status), registration.type.FullName ?? registration.type.Name)); + ? placement.activeIcon + : placement.icon; + items.Add( + (new EditorToolbarItem( + registration.id, + icon, + status.displayName ?? placement.tooltip, + placement.order, + status + ), registration.type.FullName ?? registration.type.Name) + ); } } @@ -43,11 +50,13 @@ internal EditorToolbarModel Build(EditorActionContext context) { int order = left.Item.order.CompareTo(right.Item.order); if (order != 0) + { return order; + } int action = string.Compare(left.Item.actionId, right.Item.actionId, StringComparison.Ordinal); return action != 0 - ? action - : string.Compare(left.TypeName, right.TypeName, StringComparison.Ordinal); + ? action + : string.Compare(left.TypeName, right.TypeName, StringComparison.Ordinal); }); return new EditorToolbarModel(items.ConvertAll(static value => value.Item)); } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarIcon.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarIcon.cs index e797a225a..642b470d1 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarIcon.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarIcon.cs @@ -9,27 +9,22 @@ public enum EditorToolbarIcon /// No symbol is requested. /// None, - /// /// Starts an operation or simulation. /// Play, - /// /// Stops an operation or simulation. /// Stop, - /// /// Pauses an operation or simulation. /// Pause, - /// /// Advances a paused operation by one step. /// Step, - /// /// Returns to an editing state. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItemAttribute.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItemAttribute.cs index 13cd4d4fa..55abb784c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItemAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Toolbars/EditorToolbarItemAttribute.cs @@ -42,15 +42,25 @@ public EditorToolbarItemAttribute( EditorToolbarIcon activeIcon = EditorToolbarIcon.None ) { if (string.IsNullOrWhiteSpace(area)) + { throw new ArgumentException("An editor toolbar area is required.", nameof(area)); + } if (!Enum.IsDefined(icon)) + { throw new ArgumentOutOfRangeException(nameof(icon), icon, "Unknown editor toolbar icon."); + } if (icon == EditorToolbarIcon.None) + { throw new ArgumentException("A visible editor toolbar icon is required.", nameof(icon)); + } if (string.IsNullOrWhiteSpace(tooltip)) + { throw new ArgumentException("An editor toolbar tooltip is required.", nameof(tooltip)); + } if (!Enum.IsDefined(activeIcon)) + { throw new ArgumentOutOfRangeException(nameof(activeIcon), activeIcon, "Unknown active toolbar icon."); + } this.area = area; this.icon = icon; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorPlanarNavigation.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorPlanarNavigation.cs index 35ac4c658..2a4fdc531 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorPlanarNavigation.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorPlanarNavigation.cs @@ -52,7 +52,9 @@ public bool Update( bool allowAltPrimary = true ) { if (isPanning && !(m_primary ? primaryDown : middleDown)) + { Cancel(); + } if (!isPanning && hovered && (middlePressed || allowAltPrimary && alt && primaryPressed)) { m_primary = !middlePressed; @@ -86,9 +88,13 @@ public static float WheelFactor( float sensitivity = 0.16f ) { if (!float.IsFinite(wheel)) + { throw new ArgumentOutOfRangeException(nameof(wheel)); + } if (!float.IsFinite(sensitivity) || sensitivity <= 0) + { throw new ArgumentOutOfRangeException(nameof(sensitivity)); + } return MathF.Exp(Math.Clamp(wheel * sensitivity, -20f, 20f)); } @@ -120,13 +126,21 @@ public static Vector2 ZoomOrigin( float nextScale ) { if (!float.IsFinite(origin.X) || !float.IsFinite(origin.Y)) + { throw new ArgumentOutOfRangeException(nameof(origin)); + } if (!float.IsFinite(pivot.X) || !float.IsFinite(pivot.Y)) + { throw new ArgumentOutOfRangeException(nameof(pivot)); + } if (!float.IsFinite(previousScale) || previousScale <= 0) + { throw new ArgumentOutOfRangeException(nameof(previousScale)); + } if (!float.IsFinite(nextScale) || nextScale <= 0) + { throw new ArgumentOutOfRangeException(nameof(nextScale)); + } return pivot - (pivot - origin) * (nextScale / previousScale); } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolContext.cs index 03308f701..d454b941c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolContext.cs @@ -2,6 +2,7 @@ using Inno.Core.Mathematics; namespace Inno.Editor.Interactions; + /// /// Coordinates pointer capture, transforms, and one history transaction for a viewport gesture. /// @@ -11,6 +12,7 @@ public sealed class EditorViewportToolContext private readonly IEditorViewportCoordinateConverter m_coordinates; private EditorEditGesture? m_transaction; private int? m_capturedPointerId; + internal EditorViewportToolContext( IEditorHistory history, IEditorViewportCoordinateConverter coordinates @@ -23,10 +25,12 @@ IEditorViewportCoordinateConverter coordinates /// Gets whether this tool owns a pointer. /// public bool hasPointerCapture => m_capturedPointerId.HasValue; + /// /// Gets the captured pointer identity, or . /// public int? capturedPointerId => m_capturedPointerId; + /// /// Gets whether a history transaction is active for the current gesture. /// @@ -41,7 +45,9 @@ IEditorViewportCoordinateConverter coordinates public void CapturePointer(int pointerId) { if (m_capturedPointerId.HasValue && m_capturedPointerId.Value != pointerId) + { throw new InvalidOperationException("A viewport tool cannot capture two pointers concurrently."); + } m_capturedPointerId = pointerId; } @@ -51,7 +57,9 @@ public void CapturePointer(int pointerId) public void ReleasePointer() { if (m_transaction is not null) + { throw new InvalidOperationException("Complete the viewport history gesture before releasing its pointer."); + } m_capturedPointerId = null; } @@ -65,9 +73,13 @@ public void BeginHistoryGesture(string name) { ArgumentException.ThrowIfNullOrWhiteSpace(name); if (!hasPointerCapture) + { throw new InvalidOperationException("A viewport history gesture requires pointer capture."); + } if (m_transaction is not null) + { throw new InvalidOperationException("The current viewport gesture already owns a history transaction."); + } m_transaction = new EditorEditGesture(m_history, name); } @@ -81,14 +93,20 @@ public void CompleteHistoryGesture(bool commit) { EditorEditGesture? transaction = m_transaction; if (transaction is null) + { return; + } if (commit) + { transaction.Commit(); + } else { EditorHistoryResult result = transaction.Cancel(); if (!result.succeeded) + { throw new InvalidOperationException($"The viewport gesture could not roll back: {result.message}"); + } } m_transaction = null; @@ -105,6 +123,7 @@ public void CompleteHistoryGesture(bool commit) /// World coordinates. /// public Vector2 ScreenToWorld(Vector2 screenPosition) => m_coordinates.ScreenToWorld(screenPosition); + /// /// Converts world coordinates to viewport-local pixel coordinates. /// @@ -115,7 +134,9 @@ public void CompleteHistoryGesture(bool commit) /// Viewport-local pixel coordinates. /// public Vector2 WorldToScreen(Vector2 worldPosition) => m_coordinates.WorldToScreen(worldPosition); + internal bool Accepts(int pointerId) => !m_capturedPointerId.HasValue || m_capturedPointerId.Value == pointerId; + internal void Cancel() { CompleteHistoryGesture(commit: false); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolSession.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolSession.cs index 57b582029..b1e9ec912 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolSession.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportToolSession.cs @@ -47,7 +47,9 @@ public void SetTool(EditorViewportTool? tool) { ObjectDisposedException.ThrowIf(m_disposed, this); if (ReferenceEquals(m_tool, tool)) + { return; + } m_context.Cancel(); m_tool = tool; } @@ -66,7 +68,9 @@ public bool HandlePointer(EditorViewportPointerEvent pointer) ObjectDisposedException.ThrowIf(m_disposed, this); EditorViewportTool? current = m_tool; if (current is null || !m_context.Accepts(pointer.pointerId)) + { return false; + } switch (pointer.phase) { case EditorViewportPointerPhase.Down: @@ -115,7 +119,9 @@ public void DrawOverlay() public void Dispose() { if (m_disposed) + { return; + } m_context.Cancel(); m_tool = null; m_disposed = true; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSetting.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSetting.cs index d1b16bb13..045b795db 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSetting.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSetting.cs @@ -20,9 +20,7 @@ public abstract class EditorSetting /// Creates a Settings definition. A field supplies its persisted default through /// ; a page keeps the base implementation. /// - protected EditorSetting() - { - } + protected EditorSetting() {} /// /// Gets the complete slash-delimited identity and placement path. @@ -85,9 +83,7 @@ protected EditorSetting() public bool Draw(EditorSettingObject setting) { ArgumentNullException.ThrowIfNull(setting); - EditorSettingObject baseline = m_drawBaselines.GetValue( - setting, - static value => value.Copy()); + EditorSettingObject baseline = m_drawBaselines.GetValue(setting, static value => value.Copy()); OnDraw(setting); return !setting.ValueEquals(baseline); } @@ -111,8 +107,7 @@ public bool IsDefault(EditorSettingObject setting) { ArgumentNullException.ThrowIfNull(setting); EditorSettingObject boundDefault = m_boundDefaultValue - ?? throw new InvalidOperationException( - $"Settings page '{path}' does not own a default value."); + ?? throw new InvalidOperationException($"Settings page '{path}' does not own a default value."); return boundDefault.ValueEquals(setting); } @@ -123,9 +118,7 @@ public bool IsDefault(EditorSettingObject setting) /// /// The isolated mutable object being edited. /// - protected virtual void OnDraw(EditorSettingObject setting) - { - } + protected virtual void OnDraw(EditorSettingObject setting) {} internal bool isPageDefinition { get; private set; } @@ -138,16 +131,15 @@ internal void BindPlacement( int placementOrder ) { string normalized = EditorSettingsPathUtility.Normalize(placementPath); - if (m_path is not null && - (!string.Equals(m_path, normalized, StringComparison.Ordinal) || m_order != placementOrder)) - { + if (m_path is not null + && (!string.Equals(m_path, normalized, StringComparison.Ordinal) || m_order != placementOrder) + ) { throw new InvalidOperationException( - $"Settings definition '{GetType().FullName}' was registered at more than one path."); + $"Settings definition '{GetType().FullName}' was registered at more than one path." + ); } - MethodInfo? drawMethod = GetType().GetMethod( - nameof(OnDraw), - BindingFlags.Instance | BindingFlags.NonPublic); + MethodInfo? drawMethod = GetType().GetMethod(nameof(OnDraw), BindingFlags.Instance | BindingFlags.NonPublic); isPageDefinition = drawMethod?.DeclaringType == typeof(EditorSetting); EditorSettingObject? declaredDefault = defaultValue; (string path, string parentPath, string label) = EditorSettingsPathUtility.Parse(normalized); @@ -155,13 +147,13 @@ int placementOrder { throw new InvalidOperationException( isPageDefinition - ? $"Settings page '{path}' cannot declare a persisted default value." - : $"Settings field '{path}' must declare a persisted default value."); + ? $"Settings page '{path}' cannot declare a persisted default value." + : $"Settings field '{path}' must declare a persisted default value." + ); } if (!isPageDefinition && parentPath.Length == 0) { - throw new InvalidOperationException( - $"Settings field '{path}' requires at least one parent page segment."); + throw new InvalidOperationException($"Settings field '{path}' requires at least one parent page segment."); } m_path = path; m_pagePath = isPageDefinition ? path : parentPath; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingObject.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingObject.cs index 67c9f4d75..92f26e45f 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingObject.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingObject.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; - using Inno.Core.Serialization; namespace Inno.Editor.Settings; @@ -18,9 +17,7 @@ public sealed class EditorSettingObject : ISerializable /// /// Creates an empty Settings object. /// - public EditorSettingObject() - { - } + public EditorSettingObject() {} private EditorSettingObject(Dictionary values) { @@ -216,7 +213,9 @@ public void SetAsSingle( float value ) { if (!float.IsFinite(value)) + { throw new ArgumentOutOfRangeException(nameof(value), "Settings numbers must be finite."); + } Set(name, value); } @@ -254,7 +253,9 @@ public void SetAsDouble( double value ) { if (!double.IsFinite(value)) + { throw new ArgumentOutOfRangeException(nameof(value), "Settings numbers must be finite."); + } Set(name, value); } @@ -479,7 +480,9 @@ internal EditorSettingObject Copy() { var values = new Dictionary(m_values.Count, StringComparer.Ordinal); foreach ((string name, EditorSettingValue value) in m_values) + { values.Add(name, value.Copy()); + } return new EditorSettingObject(values); } @@ -487,12 +490,14 @@ internal bool ValueEquals(EditorSettingObject other) { ArgumentNullException.ThrowIfNull(other); if (m_values.Count != other.m_values.Count) + { return false; + } foreach ((string name, EditorSettingValue value) in m_values) { if (!other.m_values.TryGetValue(name, out EditorSettingValue? candidate) - || !value.ValueEquals(candidate)) - { + || !value.ValueEquals(candidate) + ) { return false; } } @@ -502,12 +507,16 @@ internal bool ValueEquals(EditorSettingObject other) internal void Validate(string settingPath) { if (m_values is null) + { throw new InvalidDataException($"Settings path '{settingPath}' has no value map."); + } foreach ((string name, EditorSettingValue value) in m_values) { ValidateName(name); if (value is null) + { throw new InvalidDataException($"Settings property '{settingPath}/{name}' is null."); + } value.Validate($"{settingPath}/{name}"); } } @@ -518,7 +527,9 @@ T defaultValue ) { ValidateName(name); if (!m_values.TryGetValue(name, out EditorSettingValue? value)) + { return defaultValue; + } return value.Read(defaultValue, name); } @@ -534,8 +545,8 @@ T value ValidateName(name); EditorSettingValue next = EditorSettingValue.Create(value); if (m_values.TryGetValue(name, out EditorSettingValue? current) - && current.ValueEquals(next)) - { + && current.ValueEquals(next) + ) { return; } m_values[name] = next; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingPathAttribute.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingPathAttribute.cs index d8b8922f2..6a107be87 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingPathAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingPathAttribute.cs @@ -26,12 +26,13 @@ public EditorSettingPathAttribute( int order = 0 ) { string normalized = EditorSettingsPathUtility.Normalize(path); - if (!string.Equals(normalized, "Editor", StringComparison.Ordinal) && - !normalized.StartsWith("Editor/", StringComparison.Ordinal)) - { + if (!string.Equals(normalized, "Editor", StringComparison.Ordinal) + && !normalized.StartsWith("Editor/", StringComparison.Ordinal) + ) { throw new ArgumentException( "An Editor setting path must be 'Editor' or begin with 'Editor/'.", - nameof(path)); + nameof(path) + ); } this.path = normalized; this.order = order; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingValue.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingValue.cs index 70b0d1ccc..55a0f7b8d 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingValue.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingValue.cs @@ -1,7 +1,6 @@ using System; using System.IO; using System.Linq; - using Inno.Core.Serialization; namespace Inno.Editor.Settings; @@ -64,19 +63,33 @@ internal static EditorSettingValue Create(T value) { Type type = typeof(T); if (type == typeof(bool)) + { return new EditorSettingValue { kind = EditorSettingValueKind.Boolean, booleanValue = (bool)(object)value! }; + } if (type == typeof(int)) + { return new EditorSettingValue { kind = EditorSettingValueKind.Int32, int32Value = (int)(object)value! }; + } if (type == typeof(uint)) + { return new EditorSettingValue { kind = EditorSettingValueKind.UInt32, uint32Value = (uint)(object)value! }; + } if (type == typeof(long)) + { return new EditorSettingValue { kind = EditorSettingValueKind.Int64, int64Value = (long)(object)value! }; + } if (type == typeof(ulong)) + { return new EditorSettingValue { kind = EditorSettingValueKind.UInt64, uint64Value = (ulong)(object)value! }; + } if (type == typeof(float)) + { return new EditorSettingValue { kind = EditorSettingValueKind.Single, singleValue = (float)(object)value! }; + } if (type == typeof(double)) + { return new EditorSettingValue { kind = EditorSettingValueKind.Double, doubleValue = (double)(object)value! }; + } if (type == typeof(string)) { string? text = (string?)(object?)value; @@ -88,15 +101,25 @@ internal static EditorSettingValue Create(T value) }; } if (type == typeof(bool[])) + { return new EditorSettingValue { kind = EditorSettingValueKind.BooleanArray, booleanArrayValue = Clone((bool[])(object)value!) }; + } if (type == typeof(int[])) + { return new EditorSettingValue { kind = EditorSettingValueKind.Int32Array, int32ArrayValue = Clone((int[])(object)value!) }; + } if (type == typeof(uint[])) + { return new EditorSettingValue { kind = EditorSettingValueKind.UInt32Array, uint32ArrayValue = Clone((uint[])(object)value!) }; + } if (type == typeof(float[])) + { return new EditorSettingValue { kind = EditorSettingValueKind.SingleArray, singleArrayValue = Clone((float[])(object)value!) }; + } if (type == typeof(double[])) + { return new EditorSettingValue { kind = EditorSettingValueKind.DoubleArray, doubleArrayValue = Clone((double[])(object)value!) }; + } if (type == typeof(string[])) { string?[] source = (string?[])(object)value!; @@ -125,67 +148,98 @@ string propertyName Type type = typeof(T); object? value; if (type == typeof(bool) && kind == EditorSettingValueKind.Boolean) + { value = booleanValue; + } else if (type == typeof(int) && kind == EditorSettingValueKind.Int32) + { value = int32Value; + } else if (type == typeof(uint) && kind == EditorSettingValueKind.UInt32) + { value = uint32Value; + } else if (type == typeof(long) && kind == EditorSettingValueKind.Int64) + { value = int64Value; + } else if (type == typeof(ulong) && kind == EditorSettingValueKind.UInt64) + { value = uint64Value; + } else if (type == typeof(float) && kind == EditorSettingValueKind.Single) + { value = singleValue; + } else if (type == typeof(double) && kind == EditorSettingValueKind.Double) + { value = doubleValue; + } else if (type == typeof(string) && kind == EditorSettingValueKind.String) + { value = hasStringValue ? stringValue : defaultValue; + } else if (type == typeof(bool[]) && kind == EditorSettingValueKind.BooleanArray) + { value = Clone(booleanArrayValue); + } else if (type == typeof(int[]) && kind == EditorSettingValueKind.Int32Array) + { value = Clone(int32ArrayValue); + } else if (type == typeof(uint[]) && kind == EditorSettingValueKind.UInt32Array) + { value = Clone(uint32ArrayValue); + } else if (type == typeof(float[]) && kind == EditorSettingValueKind.SingleArray) + { value = Clone(singleArrayValue); + } else if (type == typeof(double[]) && kind == EditorSettingValueKind.DoubleArray) + { value = Clone(doubleArrayValue); + } else if (type == typeof(string[]) && kind == EditorSettingValueKind.StringArray) + { value = ReadStringArray(); + } else - throw new InvalidDataException( - $"Settings property '{propertyName}' contains {kind}, not {GetKind(type)}."); + { + throw new InvalidDataException($"Settings property '{propertyName}' contains {kind}, not {GetKind(type)}."); + } return (T)value!; } internal EditorSettingValue Copy() => new() - { - kind = kind, - booleanValue = booleanValue, - int32Value = int32Value, - uint32Value = uint32Value, - int64Value = int64Value, - uint64Value = uint64Value, - singleValue = singleValue, - doubleValue = doubleValue, - hasStringValue = hasStringValue, - stringValue = stringValue, - booleanArrayValue = Clone(booleanArrayValue), - int32ArrayValue = Clone(int32ArrayValue), - uint32ArrayValue = Clone(uint32ArrayValue), - singleArrayValue = Clone(singleArrayValue), - doubleArrayValue = Clone(doubleArrayValue), - stringArrayValue = Clone(stringArrayValue), - stringArrayNulls = Clone(stringArrayNulls) - }; + { + kind = kind, + booleanValue = booleanValue, + int32Value = int32Value, + uint32Value = uint32Value, + int64Value = int64Value, + uint64Value = uint64Value, + singleValue = singleValue, + doubleValue = doubleValue, + hasStringValue = hasStringValue, + stringValue = stringValue, + booleanArrayValue = Clone(booleanArrayValue), + int32ArrayValue = Clone(int32ArrayValue), + uint32ArrayValue = Clone(uint32ArrayValue), + singleArrayValue = Clone(singleArrayValue), + doubleArrayValue = Clone(doubleArrayValue), + stringArrayValue = Clone(stringArrayValue), + stringArrayNulls = Clone(stringArrayNulls) + }; internal bool ValueEquals(EditorSettingValue other) { ArgumentNullException.ThrowIfNull(other); if (kind != other.kind) + { return false; + } return kind switch { EditorSettingValueKind.Boolean => booleanValue == other.booleanValue, @@ -196,14 +250,14 @@ internal bool ValueEquals(EditorSettingValue other) EditorSettingValueKind.Single => singleValue.Equals(other.singleValue), EditorSettingValueKind.Double => doubleValue.Equals(other.doubleValue), EditorSettingValueKind.String => hasStringValue == other.hasStringValue - && string.Equals(stringValue, other.stringValue, StringComparison.Ordinal), + && string.Equals(stringValue, other.stringValue, StringComparison.Ordinal), EditorSettingValueKind.BooleanArray => booleanArrayValue.SequenceEqual(other.booleanArrayValue), EditorSettingValueKind.Int32Array => int32ArrayValue.SequenceEqual(other.int32ArrayValue), EditorSettingValueKind.UInt32Array => uint32ArrayValue.SequenceEqual(other.uint32ArrayValue), EditorSettingValueKind.SingleArray => singleArrayValue.SequenceEqual(other.singleArrayValue), EditorSettingValueKind.DoubleArray => doubleArrayValue.SequenceEqual(other.doubleArrayValue), EditorSettingValueKind.StringArray => stringArrayValue.SequenceEqual(other.stringArrayValue, StringComparer.Ordinal) - && stringArrayNulls.SequenceEqual(other.stringArrayNulls), + && stringArrayNulls.SequenceEqual(other.stringArrayNulls), _ => false }; } @@ -211,29 +265,33 @@ internal bool ValueEquals(EditorSettingValue other) internal void Validate(string propertyName) { if (!Enum.IsDefined(kind)) + { throw new InvalidDataException($"Settings property '{propertyName}' has an unknown value kind."); + } if (booleanArrayValue is null || int32ArrayValue is null || uint32ArrayValue is null || singleArrayValue is null || doubleArrayValue is null || stringArrayValue is null - || stringArrayNulls is null) - { + || stringArrayNulls is null + ) { throw new InvalidDataException($"Settings property '{propertyName}' has an invalid null array payload."); } if (stringValue is null) + { throw new InvalidDataException($"Settings property '{propertyName}' has an invalid null string payload."); + } if (kind == EditorSettingValueKind.StringArray - && stringArrayValue.Length != stringArrayNulls.Length) - { + && stringArrayValue.Length != stringArrayNulls.Length + ) { throw new InvalidDataException($"Settings property '{propertyName}' has inconsistent string-array payloads."); } if (kind == EditorSettingValueKind.Single && !float.IsFinite(singleValue) || kind == EditorSettingValueKind.Double && !double.IsFinite(doubleValue) || kind == EditorSettingValueKind.SingleArray && singleArrayValue.Any(static value => !float.IsFinite(value)) - || kind == EditorSettingValueKind.DoubleArray && doubleArrayValue.Any(static value => !double.IsFinite(value))) - { + || kind == EditorSettingValueKind.DoubleArray && doubleArrayValue.Any(static value => !double.IsFinite(value)) + ) { throw new InvalidDataException($"Settings property '{propertyName}' contains a non-finite number."); } } @@ -241,33 +299,61 @@ internal void Validate(string propertyName) private static EditorSettingValueKind GetKind(Type type) { if (type == typeof(bool)) + { return EditorSettingValueKind.Boolean; + } if (type == typeof(int)) + { return EditorSettingValueKind.Int32; + } if (type == typeof(uint)) + { return EditorSettingValueKind.UInt32; + } if (type == typeof(long)) + { return EditorSettingValueKind.Int64; + } if (type == typeof(ulong)) + { return EditorSettingValueKind.UInt64; + } if (type == typeof(float)) + { return EditorSettingValueKind.Single; + } if (type == typeof(double)) + { return EditorSettingValueKind.Double; + } if (type == typeof(string)) + { return EditorSettingValueKind.String; + } if (type == typeof(bool[])) + { return EditorSettingValueKind.BooleanArray; + } if (type == typeof(int[])) + { return EditorSettingValueKind.Int32Array; + } if (type == typeof(uint[])) + { return EditorSettingValueKind.UInt32Array; + } if (type == typeof(float[])) + { return EditorSettingValueKind.SingleArray; + } if (type == typeof(double[])) + { return EditorSettingValueKind.DoubleArray; + } if (type == typeof(string[])) + { return EditorSettingValueKind.StringArray; + } throw new NotSupportedException($"Editor Settings values do not support '{type.FullName}'."); } @@ -275,7 +361,9 @@ private static EditorSettingValueKind GetKind(Type type) { var result = new string?[stringArrayValue.Length]; for (int i = 0; i < result.Length; i++) + { result[i] = stringArrayNulls[i] ? null : stringArrayValue[i]; + } return result; } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingsPathUtility.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingsPathUtility.cs index 84b3b2618..c156914b1 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingsPathUtility.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/EditorSettingsPathUtility.cs @@ -9,8 +9,8 @@ internal static (string Path, string ParentPath, string Label) Parse(string path string normalized = Normalize(path); int separator = normalized.LastIndexOf('/'); return separator < 0 - ? (normalized, string.Empty, normalized) - : (normalized, normalized[..separator], normalized[(separator + 1)..]); + ? (normalized, string.Empty, normalized) + : (normalized, normalized[..separator], normalized[(separator + 1)..]); } internal static string Normalize(string path) @@ -18,7 +18,9 @@ internal static string Normalize(string path) ArgumentException.ThrowIfNullOrWhiteSpace(path); string[] segments = path.Split('/', StringSplitOptions.TrimEntries); if (segments.Length == 0 || Array.Exists(segments, static segment => segment.Length == 0)) + { throw new ArgumentException("Settings paths cannot contain empty segments.", nameof(path)); + } return string.Join('/', segments); } } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs index 0de86f374..a0cc314fe 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs @@ -1,9 +1,8 @@ using System; using System.Runtime.CompilerServices; - using Inno.Core.Serialization; -using Inno.Scripting.Api; using Inno.Core.Settings; +using Inno.Scripting.Api; namespace Inno.Editor.Settings; @@ -102,7 +101,8 @@ ISerializable right internal SerializationRegistry serialization => m_serialization ?? throw new InvalidOperationException( - $"Project setting editor '{GetType().FullName}' has not been bound to a serialization registry."); + $"Project setting editor '{GetType().FullName}' has not been bound to a serialization registry." + ); internal void BindSerialization(SerializationRegistry serializationRegistry) { @@ -110,7 +110,8 @@ internal void BindSerialization(SerializationRegistry serializationRegistry) if (m_serialization is not null && !ReferenceEquals(m_serialization, serializationRegistry)) { throw new InvalidOperationException( - $"Project setting editor '{GetType().FullName}' cannot be bound to more than one serialization registry."); + $"Project setting editor '{GetType().FullName}' cannot be bound to more than one serialization registry." + ); } m_serialization = serializationRegistry; } @@ -118,11 +119,14 @@ internal void BindSerialization(SerializationRegistry serializationRegistry) internal void BindSettingId(ProjectSettingId id) { if (!id.isValid) + { throw new ArgumentException("A project setting Editor requires a valid setting ID.", nameof(id)); + } if (m_settingId.isValid && m_settingId != id) { throw new InvalidOperationException( - $"Project setting editor '{GetType().FullName}' cannot be bound to more than one setting protocol."); + $"Project setting editor '{GetType().FullName}' cannot be bound to more than one setting protocol." + ); } m_settingId = id; } @@ -132,20 +136,24 @@ internal void BindPlacement( int placementOrder ) { string normalized = EditorSettingsPathUtility.Normalize(placementPath); - if (m_path is not null && - (!string.Equals(m_path, normalized, StringComparison.Ordinal) || m_order != placementOrder)) - { + if (m_path is not null + && (!string.Equals(m_path, normalized, StringComparison.Ordinal) || m_order != placementOrder) + ) { throw new InvalidOperationException( - $"Project setting editor '{GetType().FullName}' was registered at more than one path."); + $"Project setting editor '{GetType().FullName}' was registered at more than one path." + ); } if (!settingId.isValid) { throw new InvalidOperationException( - $"Project setting editor '{GetType().FullName}' returned an invalid setting ID."); + $"Project setting editor '{GetType().FullName}' returned an invalid setting ID." + ); } (string path, string parentPath, string label) = EditorSettingsPathUtility.Parse(normalized); if (parentPath.Length == 0) + { throw new InvalidOperationException($"Project setting editor '{path}' requires a parent page."); + } m_path = path; m_pagePath = parentPath; m_label = label; @@ -159,7 +167,8 @@ internal void ValidateValue(ISerializable value) { throw new ArgumentException( $"Project setting '{settingId}' requires '{valueType.FullName}', not '{value.GetType().FullName}'.", - nameof(value)); + nameof(value) + ); } } } @@ -191,10 +200,10 @@ internal sealed override bool DrawValue(ISerializable value) var setting = (TSetting)value; Baseline baseline = m_baselines.GetValue( setting, - candidate => new Baseline(serialization.CapturePropertiesData(candidate))); + candidate => new Baseline(serialization.CapturePropertiesData(candidate)) + ); OnDraw(setting); - return !baseline.propertyData.AsSpan().SequenceEqual( - serialization.CapturePropertiesData(setting)); + return !baseline.propertyData.AsSpan().SequenceEqual(serialization.CapturePropertiesData(setting)); } internal sealed override bool ValueEquals( @@ -204,7 +213,8 @@ ISerializable right ValidateValue(left); ValidateValue(right); return serialization.CapturePropertiesData(left).AsSpan().SequenceEqual( - serialization.CapturePropertiesData(right)); + serialization.CapturePropertiesData(right) + ); } private sealed record Baseline(byte[] propertyData); diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingPathAttribute.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingPathAttribute.cs index 365ba44e0..9e37c128e 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingPathAttribute.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingPathAttribute.cs @@ -27,9 +27,7 @@ public ProjectSettingPathAttribute( string normalized = EditorSettingsPathUtility.Normalize(path); if (!normalized.StartsWith("Project/", StringComparison.Ordinal)) { - throw new ArgumentException( - "A project setting editor path must begin with 'Project/'.", - nameof(path)); + throw new ArgumentException("A project setting editor path must begin with 'Project/'.", nameof(path)); } this.path = normalized; this.order = order; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Properties/ScriptingApi.cs b/src/composition/editor/framework/Inno.Editor.Settings/Properties/ScriptingApi.cs index 075e29161..cc6448278 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Properties/ScriptingApi.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Settings; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Settings", "Inno.Editor.Settings", ScriptingApiScope.Editor)] diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs index 87b97364f..d0e42463c 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs @@ -1,14 +1,15 @@ -using Inno.Core.Events; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Events; using Inno.Core.Logging; using Inno.Core.Serialization; -using Inno.Extensibility.Types; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; namespace Inno.Editor.Settings; + /// /// Owns the discovered Settings catalog and the project-root Settings document. /// @@ -21,6 +22,7 @@ public sealed class EditorSettings : EditorModule private readonly Logger m_log; private readonly object m_sync = new(); private readonly EditorSettingsStore m_store; + /// /// Creates the Settings service for one project and its shared editor history. /// @@ -84,7 +86,9 @@ public IDisposable ListenChanges(Action observer) hub.Listen(change => { if (!ReferenceEquals(change.settings, this)) + { return; + } try { observer(this); @@ -101,6 +105,7 @@ public IDisposable ListenChanges(Action observer) /// Gets the current discovered type-catalog revision. /// public long catalogRevision => m_catalog.snapshot.revision; + /// /// Gets all discovered path definitions in deterministic path order. /// @@ -123,7 +128,9 @@ public EditorSettingObject Get(string path) EditorSetting definition = ResolveField(path); lock (m_sync) { - return m_store.TryGet(definition.path, out EditorSettingObject? value) && value is not null ? value : definition.CreateDefault(); + return m_store.TryGet(definition.path, out EditorSettingObject? value) && value is not null + ? value + : definition.CreateDefault(); } } @@ -169,7 +176,9 @@ public bool Apply( { normalizedResets = new HashSet(StringComparer.Ordinal); foreach (string path in resets) + { _ = normalizedResets.Add(ResolveField(path).path); + } } byte[] before; @@ -181,13 +190,17 @@ public bool Apply( if (normalizedResets is not null) { foreach (string path in normalizedResets) + { storageChanged |= replacement.Remove(path); + } } foreach ((string path, EditorSettingObject candidate)in normalizedValues) { if (normalizedResets?.Contains(path) == true) + { continue; + } if (replacement.TryGetValue(path, out EditorSettingObject? current) && current.ValueEquals(candidate)) { continue; @@ -203,7 +216,9 @@ public bool Apply( } if (!storageChanged) + { return false; + } before = m_store.GetDocument(); m_store.Replace(replacement); after = m_store.GetDocument(); @@ -217,7 +232,9 @@ public bool Apply( catch { lock (m_sync) + { m_store.ReplaceDocument(before); + } throw; } @@ -229,32 +246,44 @@ public bool Apply( /// Releases resources retained by this feature after it has stopped. /// protected override void OnDispose() => m_catalog.Dispose(); + internal void RestoreFromHistory(ReadOnlySpan document) { lock (m_sync) + { m_store.ReplaceDocument(document); + } } internal byte[] CaptureDocument() { lock (m_sync) + { return m_store.GetDocument(); + } } internal void ValidateDocument(ReadOnlySpan document) { lock (m_sync) + { m_store.ValidateDocument(document); + } } internal void NotifyChanged() => m_events.Emit(new EditorSettingsChangedEvent(this)); + private EditorSetting ResolveField(string path) { string normalized = EditorSettingsPathUtility.Normalize(path); if (!m_catalog.snapshot.byPath.TryGetValue(normalized, out EditorSetting? setting)) + { throw new ArgumentException($"No editor setting is registered at '{normalized}'.", nameof(path)); + } if (!setting.hasValue) + { throw new ArgumentException($"Editor setting '{normalized}' describes a page.", nameof(path)); + } return setting; } } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs index 765bcbacb..ff13f4ca1 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Extensibility.Types; namespace Inno.Editor.Settings; @@ -9,9 +8,7 @@ namespace Inno.Editor.Settings; internal sealed class EditorSettingsCatalog : TypeRegistry { internal EditorSettingsCatalog(TypeCatalog types) - : base(types) - { - } + : base(types) {} internal Snapshot snapshot => current; @@ -40,13 +37,10 @@ protected override Snapshot Build(TypeCacheSnapshot types) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicatePath is not null) { - throw new InvalidOperationException( - $"Editor setting path '{duplicatePath}' is registered more than once."); + throw new InvalidOperationException($"Editor setting path '{duplicatePath}' is registered more than once."); } - var byPath = definitions.ToDictionary( - static setting => setting.path, - StringComparer.Ordinal); + var byPath = definitions.ToDictionary(static setting => setting.path, StringComparer.Ordinal); return new Snapshot(types.version, definitions, byPath); } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsChangedEvent.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsChangedEvent.cs index 74d805b2d..ffce43074 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsChangedEvent.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsChangedEvent.cs @@ -1,6 +1,7 @@ using Inno.Core.Events; namespace Inno.Editor.Settings; + internal sealed class EditorSettingsChangedEvent(EditorSettings settings) : Event { internal EditorSettings settings { get; } = settings; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsDocument.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsDocument.cs index 186cc76cd..dc2e3c0f5 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsDocument.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsDocument.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Serialization; namespace Inno.Editor.Settings; diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs index ec1d5a345..fb59f72a6 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs @@ -1,7 +1,6 @@ using System; using System.Buffers.Binary; using System.IO; - using Inno.Editor.Interactions; namespace Inno.Editor.Settings; @@ -25,10 +24,14 @@ internal static (ReadOnlyMemory Before, ReadOnlyMemory After) Read(E { byte[] payload = change.payload.ReadBytes(); if (payload.Length < sizeof(int)) + { throw new InvalidDataException("The Settings history payload is truncated."); + } int beforeLength = BinaryPrimitives.ReadInt32LittleEndian(payload); if (beforeLength < 0 || beforeLength > payload.Length - sizeof(int)) + { throw new InvalidDataException("The Settings history payload has an invalid boundary."); + } ReadOnlyMemory before = payload.AsMemory(sizeof(int), beforeLength); ReadOnlyMemory after = payload.AsMemory(sizeof(int) + beforeLength); return (before, after); @@ -96,8 +99,7 @@ EditorHistoryDirection direction try { (ReadOnlyMemory before, ReadOnlyMemory after) = EditorSettingsHistory.Read(change); - settings.RestoreFromHistory( - direction == EditorHistoryDirection.Undo ? before.Span : after.Span); + settings.RestoreFromHistory(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); settings.NotifyChanged(); return EditorHistoryResult.Success(); } @@ -111,7 +113,8 @@ EditorHistoryDirection direction catch (Exception rollbackException) { return StateIntegrityFailure( - $"Settings transition failed: {exception.Message} Rollback failed: {rollbackException.Message}"); + $"Settings transition failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsStore.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsStore.cs index e478c3fa0..19ccea9be 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsStore.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsStore.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; using System.IO; - +using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Core.IO; namespace Inno.Editor.Settings; @@ -26,7 +25,8 @@ SerializationRegistry serialization new FileByteDocumentStore(path), serialization, static () => new EditorSettingsDocument(), - ValidateDocumentValue); + ValidateDocumentValue + ); m_values = ValidateAndCopy(m_documents.Load().values); } @@ -75,13 +75,14 @@ private Dictionary ReadValues(ReadOnlySpan do return ValidateAndCopy(parsed.values); } catch (Exception exception) when (exception is ArgumentException - or InvalidDataException - or InvalidOperationException - or NotSupportedException) + or InvalidDataException + or InvalidOperationException + or NotSupportedException) { throw new InvalidDataException( "The editor Settings document is not a valid current-format document.", - exception); + exception + ); } } @@ -104,9 +105,13 @@ private static Dictionary ValidateAndCopy(IReadOnly throw new InvalidDataException("The editor Settings document contains an invalid path.", exception); } if (!string.Equals(path, normalized, StringComparison.Ordinal)) + { throw new InvalidDataException($"Settings path '{path}' is not normalized."); + } if (value is null) + { throw new InvalidDataException($"Settings path '{path}' has a null object."); + } value.Validate(path); result.Add(path, value.Copy()); } @@ -117,7 +122,9 @@ private static Dictionary Copy(IReadOnlyDictionary< { var result = new Dictionary(values.Count, StringComparer.Ordinal); foreach ((string path, EditorSettingObject value) in values) + { result.Add(path, value.Copy()); + } return result; } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingEditorCatalog.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingEditorCatalog.cs index e58f17e1c..80f925289 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingEditorCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingEditorCatalog.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Types; namespace Inno.Editor.Settings; @@ -16,8 +15,7 @@ internal sealed class ProjectSettingEditorCatalog : TypeRegistry definition.path, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicatePath is not null) + { throw new InvalidOperationException($"Project setting path '{duplicatePath}' is registered more than once."); + } IGrouping? incompatiblePresentations = definitions .GroupBy(static definition => definition.settingId) @@ -61,7 +61,8 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (incompatiblePresentations is not null) { throw new InvalidOperationException( - $"Project setting ID '{incompatiblePresentations.Key}' has Editor presentations for more than one value type."); + $"Project setting ID '{incompatiblePresentations.Key}' has Editor presentations for more than one value type." + ); } return new Snapshot(types.version, definitions); @@ -85,8 +86,9 @@ private ProjectSettingEditor CreateDefinition(Type type) ProjectSettingDefinitionAttribute setting = definition.valueType .GetCustomAttribute(inherit: false) ?? throw new InvalidOperationException( - $"Project setting editor '{type.FullName}' targets '{definition.valueType.FullName}', " + - $"which is missing {nameof(ProjectSettingDefinitionAttribute)}."); + $"Project setting editor '{type.FullName}' targets '{definition.valueType.FullName}', " + + $"which is missing {nameof(ProjectSettingDefinitionAttribute)}." + ); definition.BindSettingId(new ProjectSettingId(setting.id)); definition.BindSerialization(m_serialization); definition.BindPlacement(attribute.path, attribute.order); diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs index 4bc73a0d8..a87de9b23 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; using System.IO; - using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Extensibility.Types; using Inno.Editor.Core; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; namespace Inno.Editor.Settings; @@ -84,7 +83,8 @@ public ISerializable Get(ProjectSettingEditor definition) if (!m_settings.TryClone(definition.settingId, out ISerializable? setting) || setting is null) { throw new InvalidOperationException( - $"Project setting '{definition.settingId}' has no active runtime definition."); + $"Project setting '{definition.settingId}' has no active runtime definition." + ); } definition.ValidateValue(setting); return setting; @@ -108,12 +108,11 @@ public ISerializable Get(ProjectSettingEditor definition) public ISerializable GetComposedDefault(ProjectSettingEditor definition) { ArgumentNullException.ThrowIfNull(definition); - if (!m_settings.TryCloneComposedDefault( - definition.settingId, - out ISerializable? setting) || setting is null) + if (!m_settings.TryCloneComposedDefault(definition.settingId, out ISerializable? setting) || setting is null) { throw new InvalidOperationException( - $"Project setting '{definition.settingId}' has no active runtime definition."); + $"Project setting '{definition.settingId}' has no active runtime definition." + ); } definition.ValidateValue(setting); return setting; @@ -141,7 +140,9 @@ public bool Apply( ArgumentNullException.ThrowIfNull(values); byte[] before = m_settings.CaptureDocument(); if (!m_settings.ApplyProjectOverrides(values, resets)) + { return false; + } byte[] after = m_settings.CaptureDocument(); try { @@ -166,5 +167,4 @@ public bool Apply( internal void ValidateDocument(ReadOnlySpan document) => m_settings.ValidateDocument(document); internal void RestoreFromHistory(ReadOnlySpan document) => m_settings.RestoreDocument(document); - } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs index 5509b72e6..a35d28eac 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs @@ -1,7 +1,6 @@ using System; using System.Buffers.Binary; using System.IO; - using Inno.Editor.Interactions; namespace Inno.Editor.Settings; @@ -25,10 +24,14 @@ internal static (ReadOnlyMemory Before, ReadOnlyMemory After) Read(E { byte[] payload = change.payload.ReadBytes(); if (payload.Length < sizeof(int)) + { throw new InvalidDataException("The Project Settings history payload is truncated."); + } int beforeLength = BinaryPrimitives.ReadInt32LittleEndian(payload); if (beforeLength < 0 || beforeLength > payload.Length - sizeof(int)) + { throw new InvalidDataException("The Project Settings history payload has an invalid boundary."); + } ReadOnlyMemory before = payload.AsMemory(sizeof(int), beforeLength); ReadOnlyMemory after = payload.AsMemory(sizeof(int) + beforeLength); return (before, after); @@ -96,8 +99,7 @@ EditorHistoryDirection direction try { (ReadOnlyMemory before, ReadOnlyMemory after) = ProjectSettingsHistory.Read(change); - settings.RestoreFromHistory( - direction == EditorHistoryDirection.Undo ? before.Span : after.Span); + settings.RestoreFromHistory(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); return EditorHistoryResult.Success(); } catch (Exception exception) when ( @@ -110,8 +112,9 @@ EditorHistoryDirection direction catch (Exception rollbackException) { return StateIntegrityFailure( - $"Project Settings transition failed: {exception.Message} " + - $"Rollback failed: {rollbackException.Message}"); + $"Project Settings transition failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorApplication.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorApplication.cs index c0afd1b8c..70a126e5f 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorApplication.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorApplication.cs @@ -1,7 +1,7 @@ using System; +using System.Linq; using System.Threading; using System.Threading.Tasks; -using System.Linq; namespace Inno.Editor.Hosting; @@ -53,14 +53,22 @@ public static async Task RunAsync( ArgumentException.ThrowIfNullOrWhiteSpace(options.projectDirectory); ArgumentException.ThrowIfNullOrWhiteSpace(options.supportPackRoot); if (options.smokeFrameLimit is <= 0) + { throw new ArgumentOutOfRangeException(nameof(options), "A smoke frame limit must be positive."); + } if (!options.distribution.availableTargets.Contains(options.defaultBuildTarget)) + { throw new ArgumentException("The explicit default build target is absent from the distribution.", nameof(options)); + } options.shell.adapters.Validate(options.adapterCatalog); if (!options.presentation.isValid || !options.adapterCatalog.presentation.supportedBackends.Contains(options.presentation)) + { throw new NotSupportedException("The selected presentation backend is not registered."); + } if (!options.adapterCatalog.renderingAuthoring.supportedBackends.Contains(options.shell.adapters.rendering)) + { throw new NotSupportedException("The selected rendering backend requires a matching authoring provider."); + } cancellationToken.ThrowIfCancellationRequested(); EditorHost host = EditorHost.Create(options); int result; diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs index e40c64f20..38fce6f64 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs @@ -51,8 +51,19 @@ public sealed class EditorCommandLineOptions /// public static EditorCommandLineOptions Parse(string[] arguments) { - if (!TryGetRunOptions(arguments, out string? project, out int? smoke, out GraphicsApi? graphics, out bool visible, out string? dependencies)) - throw new ArgumentException("Usage: Editor [--graphics-api ] [--window-visible ] [--smoke-frames ] [--native-dependencies ].", nameof(arguments)); + if (!TryGetRunOptions( + arguments, + out string? project, + out int? smoke, + out GraphicsApi? graphics, + out bool visible, + out string? dependencies + )) { + throw new ArgumentException( + "Usage: Editor [--graphics-api ] [--window-visible ] [--smoke-frames ] [--native-dependencies ].", + nameof(arguments) + ); + } return new EditorCommandLineOptions(project) { smokeFrameLimit = smoke, @@ -61,6 +72,7 @@ public static EditorCommandLineOptions Parse(string[] arguments) nativeDependencies = dependencies }; } + private static bool TryGetRunOptions( string[] args, [NotNullWhen(true)] out string? projectDirectory, @@ -77,17 +89,21 @@ out string? nativeDependencies bool hasVisibility = false; projectDirectory = args.Length > 0 ? args[0] : null; if (projectDirectory is null) + { return false; + } for (int index = 1; index < args.Length; index += 2) { if (index + 1 >= args.Length) + { return false; + } if (string.Equals(args[index], "--smoke-frames", StringComparison.Ordinal)) { if (smokeFrameLimit is not null || !int.TryParse(args[index + 1], out int parsedFrameLimit) - || parsedFrameLimit <= 0) - { + || parsedFrameLimit <= 0 + ) { return false; } smokeFrameLimit = parsedFrameLimit; @@ -96,21 +112,27 @@ out string? nativeDependencies if (string.Equals(args[index], "--graphics-api", StringComparison.Ordinal)) { if (graphicsApi is not null || !TryParseGraphicsApi(args[index + 1], out GraphicsApi parsedApi)) + { return false; + } graphicsApi = parsedApi; continue; } if (string.Equals(args[index], "--window-visible", StringComparison.Ordinal)) { if (hasVisibility || !bool.TryParse(args[index + 1], out windowVisible)) + { return false; + } hasVisibility = true; continue; } if (string.Equals(args[index], "--native-dependencies", StringComparison.Ordinal)) { if (nativeDependencies is not null || !Path.IsPathFullyQualified(args[index + 1])) + { return false; + } nativeDependencies = Path.GetFullPath(args[index + 1]); continue; } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorLaunchOptions.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorLaunchOptions.cs index bff549b23..51c259b66 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorLaunchOptions.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorLaunchOptions.cs @@ -1,7 +1,7 @@ using System; using Inno.Adapter.Presentation; -using Inno.Build.Composition; using Inno.Build; +using Inno.Build.Composition; using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Extensibility.Modules; diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorAuthoringServices.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorAuthoringServices.cs index bfad6ab29..8f892cd32 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorAuthoringServices.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorAuthoringServices.cs @@ -1,15 +1,14 @@ -using Inno.Core.IO; -using Inno.Build; using System; using System.IO; using System.Linq; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; +using Inno.Build; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Logging; using Inno.Core.Settings; +using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scripting.Compiler; @@ -68,14 +67,12 @@ string dotnetHost PluginEnvironment? plugins = null; try { - var pluginSources = new PluginSourceService( - engineHost.serialization, - pluginRoot, - libraryRoot); + var pluginSources = new PluginSourceService(engineHost.serialization, pluginRoot, libraryRoot); PluginScanResult pluginScan = pluginSources.Scan(); AssetPipelineOptions defaultOptions = AssetPipelineOptions.Create(assetRoot, libraryRoot); AssetSourceMount projectMount = defaultOptions.sourceMounts!.Single( - static mount => mount.id == AssetSourceId.project); + static mount => mount.id == AssetSourceId.project + ); assets = new AssetPipeline( engineHost.modules, engineHost.types, @@ -91,13 +88,15 @@ defaultOptions with projectMount, .. PluginSourceService.GetActivatableMounts(pluginScan) ] - }); + } + ); settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, SettingsFileNames.project))), engineHost.types, engineHost.serialization, ProjectId.FromName(new DirectoryInfo(projectRoot).Name), - AssetSerializationContext.Create(assets)); + AssetSerializationContext.Create(assets) + ); plugins = new PluginEnvironment( assets, settings, @@ -105,13 +104,15 @@ .. PluginSourceService.GetActivatableMounts(pluginScan) pluginRoot, libraryRoot, pluginScan, - engineHost.modules.generations); + engineHost.modules.generations + ); foreach (PluginDiagnostic diagnostic in plugins.discovery.diagnostics) { log.Write( LogLevel.Warn, "Plugin source '{0}' was excluded from the active candidate: {1}", - [diagnostic.sourcePath, diagnostic.message]); + [diagnostic.sourcePath, diagnostic.message] + ); } var compiler = new ScriptCompiler( new ScriptCompilerOptions @@ -120,7 +121,8 @@ .. PluginSourceService.GetActivatableMounts(pluginScan) compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) }, assets, - plugins); + plugins + ); return new EditorAuthoringServices(settings, assets, identities, plugins, compiler); } catch @@ -145,7 +147,9 @@ internal void Update() public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; plugins.Dispose(); assets.Dispose(); diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs index b0cb47e6b..6f7636d46 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs @@ -1,9 +1,4 @@ -using Inno.Extensibility.Modules; -using Inno.Scripting.Compiler; -using Inno.Engine.Default; -using Inno.Runtime.Contracts; using System; -using Inno.Core.Diagnostics; using System.Collections.Generic; using System.IO; using System.Linq; @@ -11,14 +6,14 @@ using Inno.Adapter.Audio; using Inno.Adapter.Input; using Inno.Adapter.Presentation; +using Inno.Animation.Runtime; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Animation.Runtime; -using Inno.Audio.Runtime; using Inno.Audio; +using Inno.Audio.Runtime; using Inno.Build; using Inno.Build.Composition; -using Inno.UI.Runtime; +using Inno.Core.Diagnostics; using Inno.Core.Events; using Inno.Core.Layers; using Inno.Core.Logging; @@ -27,17 +22,23 @@ using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.Rendering; +using Inno.Engine.Default; +using Inno.Extensibility.Modules; using Inno.Input.Runtime; using Inno.Platform; using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Runtime; using Inno.Runtime; +using Inno.Runtime.Contracts; using Inno.Scene; +using Inno.Scripting.Compiler; using Inno.Shell; using Inno.Storage.Runtime; +using Inno.UI.Runtime; + using ShellHost = Inno.Shell.Shell; -using Inno.Rendering.Assets.Authoring; namespace Inno.Editor.Hosting; @@ -70,14 +71,16 @@ private EditorHost( EditorLaunchOptions launch, string projectDirectory, string bootLogPath - ) : base(launch.adapterCatalog, launch.shell) { + ) : base(launch.adapterCatalog, launch.shell) + { m_launch = launch; m_authoringAdapters = launch.adapterCatalog; m_presentationBackend = launch.presentation; this.projectDirectory = projectDirectory; m_bootLogPath = bootLogPath; m_resources = new EditorHostResourceStack( - exception => AppendBootLog(bootLogPath, $"Teardown failure: {exception}")); + exception => AppendBootLog(bootLogPath, $"Teardown failure: {exception}") + ); } /// @@ -89,11 +92,14 @@ internal static EditorHost Create(EditorLaunchOptions launch) { IAuthoringAdapterCatalog adapterCatalog = launch.adapterCatalog; AdapterSelection adapterSelection = launch.shell.adapters; - if (!adapterSelection.rendering.isValid || - !adapterCatalog.rendering.supportedBackends.Contains(adapterSelection.rendering) || - !adapterCatalog.renderingAuthoring.supportedBackends.Contains(adapterSelection.rendering)) + if (!adapterSelection.rendering.isValid + || !adapterCatalog.rendering.supportedBackends.Contains(adapterSelection.rendering) + || !adapterCatalog.renderingAuthoring.supportedBackends.Contains(adapterSelection.rendering) + ) { throw new NotSupportedException( - $"Rendering backend '{adapterSelection.rendering}' requires paired runtime and authoring providers."); + $"Rendering backend '{adapterSelection.rendering}' requires paired runtime and authoring providers." + ); + } string normalizedProject = PrepareProjectDirectory(launch.projectDirectory); string logDirectory = Path.Combine(normalizedProject, C_LOG_DIRECTORY_NAME); Directory.CreateDirectory(logDirectory); @@ -142,7 +148,9 @@ protected override bool ShouldExit(Event evnt) bool shouldExit = evnt is WindowCloseEvent closeEvent && closeEvent.windowId == primaryWindow.windowId; if (shouldExit) + { BootLog($"Exit requested by event: {evnt.GetType().Name}."); + } return shouldExit; } @@ -163,7 +171,9 @@ protected override bool ShouldExit(Event evnt) protected override void OnFrame(ShellFrame frame) { if (frame.frameIndex == 0) + { BootLog("About to execute first editor frame."); + } using (rendering.EnterExecutionScope()) using (audio.EnterExecutionScope(editSession)) @@ -185,13 +195,17 @@ protected override void OnFrame(ShellFrame frame) { uint resetWindowId = m_gameInputCapture?.CompleteFrame() ?? 0; if (resetWindowId != 0) + { m_gameInputSource?.ProcessEvent(new WindowFocusChangedEvent(resetWindowId, false)); + } } } } if (frame.frameIndex == 0) + { BootLog("First editor frame completed."); + } } /// @@ -209,10 +223,17 @@ protected override void OnSmokeCompleted(int frameCount) hub.UnregisterSink(snapshot); string[] errors = snapshot.errors; foreach (string error in errors) + { BootLog("Smoke diagnostic: " + error); + } if (errors.Length != 0) - throw new InvalidOperationException($"Native Editor smoke completed with {errors.Length} active error diagnostic(s). See the smoke diagnostics above."); + { + throw new InvalidOperationException( + $"Native Editor smoke completed with {errors.Length} active error diagnostic(s). See the smoke diagnostics above." + ); + } } + /// /// Submits product UI requests while the host output pipeline is open. /// @@ -282,42 +303,50 @@ private void Initialize() AppendBootLog(m_bootLogPath, "EditorHost creation start."); InitializeAdapterResources(); if (primaryWindow.isFocused) + { m_focusedWindowIds.Add(primaryWindow.windowId); + } - EngineHost engineHost = m_resources.Acquire( - m_launch.createEngineHost, - static host => host.Dispose()); + EngineHost engineHost = m_resources.Acquire(m_launch.createEngineHost, static host => host.Dispose()); ILogSink? hostLog = m_launch.createHostLogSink?.Invoke(); m_diagnostics = engineHost.diagnostics; if (hostLog is not null) { if (hostLog is IDisposable disposableLog) + { m_resources.Register(disposableLog.Dispose); + } engineHost.logs.RegisterSink(hostLog); m_resources.Register(() => engineHost.logs.UnregisterSink(hostLog)); } EditorAuthoringServices activeAuthoring = m_resources.Acquire( () => EditorAuthoringServices.Start(projectDirectory, engineHost, m_launch.buildContext.dotnetHost), - static services => services.Dispose()); + static services => services.Dispose() + ); m_authoring = activeAuthoring; _ = m_resources.Acquire( () => AssetExecutionContext.EnterScope(activeAuthoring.assets), - static scope => scope.Dispose()); + static scope => scope.Dispose() + ); _ = m_resources.Acquire( () => ProjectSettingsExecutionContext.EnterScope(activeAuthoring.settings), - static scope => scope.Dispose()); + static scope => scope.Dispose() + ); EditorAudioHost activeAudio = m_resources.Acquire( () => new EditorAudioHost( engineHost.types, activeAuthoring.assets, engineHost.diagnostics, () => adapters.audio.CreateDevice(adapterSelection.audio, new AudioBackendOptions()), - () => activeAuthoring.settings.TryGet( - AudioProjectSettings.settingId, - out AudioProjectSettings? configured) && configured is not null + () => ( + activeAuthoring.settings.TryGet(AudioProjectSettings.settingId, out AudioProjectSettings? configured) + && configured is not null ? configured - : new AudioProjectSettings()), - static host => host.Dispose()); + : new AudioProjectSettings() + ) + ), + static host => host.Dispose() + ); m_audio = activeAudio; RuntimeSession activeEditSession = m_resources.Acquire( () => engineHost.CreateSession(new RuntimeSessionOptions @@ -325,8 +354,8 @@ private void Initialize() kind = RuntimeSessionKind.Edit, applicationId = "inno.editor", createLogSink = m_launch.createSessionLogSink is null - ? null - : session => m_launch.createSessionLogSink(RuntimeSessionKind.Edit, session), + ? null + : session => m_launch.createSessionLogSink(RuntimeSessionKind.Edit, session), fixedDeltaTime = 1f / 60f, maxFrameDeltaTime = 0.25f, maxFixedStepsPerFrame = 8, @@ -334,11 +363,10 @@ private void Initialize() createSubsystems = owner => CreateStandardRuntimeSubsystems(activeAudio, inputSource, owner), referenceResolvers = [activeAuthoring.assets] }), - static session => session.Dispose()); + static session => session.Dispose() + ); m_editSession = activeEditSession; - _ = m_resources.Acquire( - activeEditSession.EnterExecutionScope, - static scope => scope.Dispose()); + _ = m_resources.Acquire(activeEditSession.EnterExecutionScope, static scope => scope.Dispose()); BuildPipeline buildPipeline = BuildPipelineFactory.Create( m_launch.buildContext, @@ -348,18 +376,22 @@ private void Initialize() activeAuthoring.plugins, activeAuthoring.settings, activeAuthoring.compiler, - m_launch.supportPackRoot); + m_launch.supportPackRoot + ); BuildSettings defaultBuildSettings = BuildSettings.CreateDefault( Path.GetFileName(Path.TrimEndingDirectorySeparator(projectDirectory)), FindDefaultStartupScene(activeAuthoring.assets), - m_launch.defaultBuildTarget); + m_launch.defaultBuildTarget + ); var buildSettings = new BuildSettingsStore( Path.Combine(projectDirectory, SettingsFileNames.build), engineHost.serialization, - defaultBuildSettings); + defaultBuildSettings + ); LayerStack activeLayers = m_resources.Acquire( () => new LayerStack(() => activeEditSession.events.CreateHub()), - static stack => stack.Dispose()); + static stack => stack.Dispose() + ); m_layers = activeLayers; m_resources.Register(() => { @@ -375,14 +407,14 @@ private void Initialize() }); var shaderCompiler = new ShaderCompiler( - m_authoringAdapters.renderingAuthoring.CreateShaderCompilerToolchain( - adapterSelection.rendering)); + m_authoringAdapters.renderingAuthoring.CreateShaderCompilerToolchain(adapterSelection.rendering) + ); ITextureTargetCompiler textureCompiler = - m_authoringAdapters.renderingAuthoring.CreateTextureTargetCompiler( - adapterSelection.rendering); + m_authoringAdapters.renderingAuthoring.CreateTextureTargetCompiler(adapterSelection.rendering); DiagnosticReporter renderDiagnostics = m_resources.Acquire( () => engineHost.diagnostics.CreateReporter(new DiagnosticSource("inno.editor.rendering", "Rendering")), - static sink => sink.Dispose()); + static sink => sink.Dispose() + ); var renderArtifacts = m_resources.Acquire( () => new EditorRenderTargetArtifactProvider( activeAuthoring.assets, @@ -390,8 +422,10 @@ private void Initialize() engineHost.types, shaderCompiler, textureCompiler, - renderDiagnostics), - static provider => provider.Dispose()); + renderDiagnostics + ), + static provider => provider.Dispose() + ); presentation = m_resources.Acquire( () => m_authoringAdapters.presentation.CreateContext( m_presentationBackend, @@ -403,16 +437,22 @@ private void Initialize() features = PresentationFeatures.MultipleWindows | PresentationFeatures.Docking | PresentationFeatures.SmoothResize - }), - static context => context.Dispose()); + } + ), + static context => context.Dispose() + ); m_gameInputCapture = new EditorGameInputCapture( - viewportId => presentation.TryGetWindowId(viewportId, out uint windowId) + viewportId => ( + presentation.TryGetWindowId(viewportId, out uint windowId) && m_focusedWindowIds.Contains(windowId) - ? windowId - : null); + ? windowId + : null + ) + ); IInputEventSource gameInputSource = m_resources.Acquire( () => adapters.input.CreateEventSource(adapterSelection.input, primaryWindow, acceptAllWindows: true), - static source => source.Dispose()); + static source => source.Dispose() + ); m_gameInputSource = gameInputSource; activeEditSession.events.dispatched += RouteGameInput; m_resources.Register(() => activeEditSession.events.dispatched -= RouteGameInput); @@ -422,19 +462,17 @@ private void Initialize() renderDiagnostics, contributors: [presentation], targetArtifacts: renderArtifacts, - compositionProgramProvider: adapters.rendering.CreateCompositionProgramProvider( - adapterSelection.rendering)); + compositionProgramProvider: adapters.rendering.CreateCompositionProgramProvider(adapterSelection.rendering) + ); m_rendering = renderingLayer; RuntimeSubsystemPipeline hostPipeline = engineHost.CreateHostPipeline(DefaultEngine.CreateHostSubsystems(renderingLayer)); m_resources.Register(hostPipeline.Dispose); UseHostPipeline(hostPipeline); var reloadCoordinator = new EditorReloadCoordinator(); var renderingHost = m_resources.Acquire( - () => new EditorRenderingHostService( - renderingLayer, - presentation, - reloadCoordinator), - static service => service.Dispose()); + () => new EditorRenderingHostService(renderingLayer, presentation, reloadCoordinator), + static service => service.Dispose() + ); var editorContext = new EditorContext(projectDirectory, m_launch.keyboard, EditorDefaultLayout.document); presentation.SetLayoutFile(null); presentation.LoadLayout(editorContext.imguiLayout); @@ -442,9 +480,9 @@ private void Initialize() { kind = RuntimeSessionKind.Play, applicationId = "inno.editor.play", - createLogSink = m_launch.createSessionLogSink is null - ? null - : session => m_launch.createSessionLogSink(RuntimeSessionKind.Play, session), + createLogSink = m_launch.createSessionLogSink is null + ? null + : session => m_launch.createSessionLogSink(RuntimeSessionKind.Play, session), fixedDeltaTime = 1f / 60f, maxFrameDeltaTime = 0.25f, maxFixedStepsPerFrame = 8, @@ -480,7 +518,8 @@ private void Initialize() activeAuthoring.identities, activeEditSession.identities, activeAudio - ]) + ] + ) { isFocused = primaryWindow.isFocused }; @@ -488,23 +527,31 @@ private void Initialize() m_resources.Register(() => { if (overlayPushed) + { activeLayers.PopOverlay(layer); + } else + { layer.DisposeUnattached(); + } }); activeLayers.PushOverlay(layer); overlayPushed = true; if (layer.panelCount == 0) + { throw new InvalidOperationException("No editor panels were discovered from the active host assemblies."); + } BootLog($"Editor layer attached with {layer.panelCount} panel(s)."); BootLog( $"Rendering initialized with {renderDevice.capabilities.backend} " - + $"(views={renderDevice.capabilities.limits.maxViews})."); + + $"(views={renderDevice.capabilities.limits.maxViews})." + ); BootLog($"Primary presentation encodes sRGB: {renderDevice.primaryPresentationEncodesSrgb}."); BootLog( $"AssetPipeline initialized={activeAuthoring.assets.isInitialized} " - + $"root='{activeAuthoring.assets.assetRoot}'."); + + $"root='{activeAuthoring.assets.assetRoot}'." + ); } private IModuleSource CreateScriptModuleSource(ScriptModuleDeployment deployment) @@ -517,22 +564,38 @@ RuntimeSession owner ) { ArgumentNullException.ThrowIfNull(activeAudio); ArgumentNullException.ThrowIfNull(activeInputSource); - return DefaultEngine.CreateSessionSubsystems(new EngineSessionComposition( - owner, adapters, adapterSelection, activeInputSource, authoring.assets, - () => authoring.settings.TryGet(AudioProjectSettings.settingId, out AudioProjectSettings? settings) && settings is not null - ? settings : new AudioProjectSettings(), - () => adapters.storage.CreateStorage(adapterSelection.storage, - new Inno.Storage.StorageScope(owner.options.applicationId)), - activeAudio.CreateRuntimeSubsystemFactory(owner))); + return DefaultEngine.CreateSessionSubsystems( + new EngineSessionComposition( + owner, + adapters, + adapterSelection, + activeInputSource, + authoring.assets, + () => ( + authoring.settings.TryGet(AudioProjectSettings.settingId, out AudioProjectSettings? settings) && settings is not null + ? settings + : new AudioProjectSettings() + ), + () => adapters.storage.CreateStorage( + adapterSelection.storage, + new Inno.Storage.StorageScope(owner.options.applicationId) + ), + activeAudio.CreateRuntimeSubsystemFactory(owner) + ) + ); } private static string PrepareProjectDirectory(string projectDirectory) { if (string.IsNullOrWhiteSpace(projectDirectory)) + { throw new ArgumentException("Project directory is required.", nameof(projectDirectory)); + } string normalizedPath = Path.GetFullPath(projectDirectory); if (File.Exists(normalizedPath)) + { throw new IOException($"Project directory '{normalizedPath}' points to a file."); + } Directory.CreateDirectory(normalizedPath); return normalizedPath; } @@ -540,12 +603,14 @@ private static string PrepareProjectDirectory(string projectDirectory) private static string FindDefaultStartupScene(AssetPipeline assets) { foreach (AssetFileEntry entry in assets.GetFileSystemEntries(includeDirectories: false) - .Where(static entry => entry.source == AssetSourceId.project) - .Where(static entry => !AssetSample.IsRuntimeExcluded(entry.assetPath, isDirectory: false)) - .OrderBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal)) - { + .Where(static entry => entry.source == AssetSourceId.project) + .Where(static entry => !AssetSample.IsRuntimeExcluded(entry.assetPath, isDirectory: false)) + .OrderBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal) + ) { if (assets.TryGetAssetType(entry.assetPath, out Type? type) && type == typeof(SceneAsset)) + { return entry.assetPath.ToString(); + } } return string.Empty; } @@ -554,7 +619,9 @@ private void RouteGameInput(Event evnt) { Event? gameEvent = m_gameInputCapture?.Route(evnt); if (gameEvent is not null) + { m_gameInputSource?.ProcessEvent(gameEvent); + } } private bool HasEditorFocus() => m_focusedWindowIds.Count > 0; @@ -562,11 +629,15 @@ private void RouteGameInput(Event evnt) private void SaveBeforeShutdown() { if (m_shutdownStateSaved || m_editorLayer is null) + { return; + } m_shutdownStateSaved = m_editorLayer.PrepareShutdown(); - BootLog(m_shutdownStateSaved + BootLog( + m_shutdownStateSaved ? "Project editor state frozen and saved before shutdown." - : "Project editor state save failed before shutdown."); + : "Project editor state save failed before shutdown." + ); } private void UpdateFocusedWindows(Event evnt) @@ -574,9 +645,13 @@ private void UpdateFocusedWindows(Event evnt) if (evnt is WindowFocusChangedEvent focusChanged) { if (focusChanged.isFocused) + { m_focusedWindowIds.Add(focusChanged.windowId); + } else + { m_focusedWindowIds.Remove(focusChanged.windowId); + } } else if (evnt is WindowCloseEvent closeEvent) { diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs index 0d3c4d1f9..a7edf4bbf 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs @@ -40,7 +40,9 @@ internal void Register(Action cleanup) public void Dispose() { if (m_disposed) + { return; + } List failures = []; for (int i = m_cleanup.Count - 1; i >= 0; i--) { @@ -70,6 +72,8 @@ public void Dispose() m_disposed = true; m_cleanup.Clear(); if (failures.Count > 0) + { throw new AggregateException("Editor resources could not all retire cleanly.", failures); + } } } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs index e850923d7..7cc66db2d 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs @@ -1,17 +1,18 @@ using System; using System.Collections.Generic; +using Inno.Adapter.Presentation; using Inno.Core.Events; using Inno.Core.Execution; using Inno.Core.Layers; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Adapter.Presentation; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.PlayMode; +using Inno.Extensibility.Types; namespace Inno.Editor.Hosting; + /// /// Bridges the engine layer lifecycle to the attribute-discovered editor runtime. /// @@ -29,6 +30,7 @@ internal sealed class EditorLayer : Layer private bool m_isShutdownPrepared; private float m_totalTime; private double m_nextPersistenceRetryTime; + internal EditorLayer( IPresentationContext presentation, EditorContext context, @@ -47,7 +49,11 @@ internal EditorLayer( internal int panelCount => m_runtime.panelCount; internal bool isFocused { get; set; } - internal float totalTime { set => m_totalTime = value; } + + internal float totalTime + { + set => m_totalTime = value; + } internal void DisposeUnattached() { @@ -55,6 +61,7 @@ internal void DisposeUnattached() } internal void QuiescePlayMode() => m_playModeLoop.Quiesce(); + /// /// Starts the editor extension runtime and subscribes its host-level input handling. /// @@ -80,6 +87,7 @@ public override void OnDetach() /// The elapsed frame time in seconds. /// public override void OnUpdate(float deltaTime) => m_playModeLoop.Tick(deltaTime); + /// /// Updates editor presentation after the active Play Mode session has advanced. /// @@ -101,7 +109,9 @@ private void HandleKeyPressed(KeyPressedEvent keyEvent) internal bool PrepareShutdown() { if (m_isShutdownPrepared) + { return true; + } try { // Extension-state capture freezes its periodic writer before reading module state. Layout is @@ -151,7 +161,9 @@ private void SaveLayoutIfChanged() private bool CaptureLayout(bool force) { if (!m_presentation.TryCaptureLayout(out string layout, force)) + { return false; + } m_context.SetImGuiLayout(layout); return true; } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorProjectDiagnosticPublisher.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorProjectDiagnosticPublisher.cs index dbd964784..f9fc5932d 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorProjectDiagnosticPublisher.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorProjectDiagnosticPublisher.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Diagnostics; namespace Inno.Editor.Hosting; @@ -17,10 +16,10 @@ internal bool PublishPersistenceFailure(Exception exception) ArgumentNullException.ThrowIfNull(exception); string state = exception.ToString(); if (string.Equals(m_state, state, StringComparison.Ordinal)) + { return false; - Diagnostics.Set( - C_PERSISTENCE_GROUP, - Diagnostic.Error("EDITOR-PERSISTENCE", exception.Message)); + } + Diagnostics.Set(C_PERSISTENCE_GROUP, Diagnostic.Error("EDITOR-PERSISTENCE", exception.Message)); m_state = state; return true; } @@ -28,7 +27,9 @@ internal bool PublishPersistenceFailure(Exception exception) internal void ResolvePersistence() { if (string.IsNullOrEmpty(m_state)) + { return; + } Diagnostics.Clear(C_PERSISTENCE_GROUP); m_state = string.Empty; } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs index dfbd1fedc..30d01ef7b 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs @@ -1,18 +1,17 @@ -using Inno.Extensibility.Reload; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; - -using Inno.Extensibility.Modules; using Inno.Adapter.Presentation; -using Inno.Editor.Core; -using Inno.Editor.Rendering; using Inno.Core.Diagnostics; using Inno.Core.Execution; +using Inno.Editor.Core; +using Inno.Editor.Rendering; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; using Inno.Rendering; -using Inno.Rendering.Runtime; using Inno.Rendering.Assets; +using Inno.Rendering.Runtime; namespace Inno.Editor.Hosting; @@ -91,14 +90,16 @@ RenderShaderArtifact artifact ) { ObjectDisposedException.ThrowIf(m_disposed, this); if (documentId == Guid.Empty) + { throw new ArgumentException("Shader validation requires a document identity.", nameof(documentId)); + } ArgumentNullException.ThrowIfNull(artifact); lock (m_shaderValidationLock) { if (!m_shaderValidations.TryGetValue(documentId, out ShaderValidationState? state) || state.revision != revision - || !string.Equals(state.contentHash, artifact.contentHash, StringComparison.Ordinal)) - { + || !string.Equals(state.contentHash, artifact.contentHash, StringComparison.Ordinal) + ) { state = new ShaderValidationState(documentId, revision, artifact); m_shaderValidations[documentId] = state; } @@ -115,9 +116,13 @@ RenderShaderArtifact artifact public void Release(Guid documentId) { if (documentId == Guid.Empty) + { return; + } lock (m_shaderValidationLock) + { m_shaderValidations.Remove(documentId); + } } /// @@ -131,9 +136,11 @@ public void PrepareFrame(ulong frameIndex) _ = frameIndex; ShaderValidationState[] pending; lock (m_shaderValidationLock) + { pending = m_shaderValidations.Values .Where(static state => state.artifact is not null) .ToArray(); + } foreach (ShaderValidationState state in pending) { EditorShaderArtifactValidationSnapshot snapshot; @@ -148,14 +155,16 @@ public void PrepareFrame(ulong frameIndex) } catch (Exception failure) { - snapshot = new(EditorShaderCompilationState.Failed, - [new ShaderDiagnostic("SHADER_DEVICE_VALIDATION", DiagnosticSeverity.Error, failure.Message)]); + snapshot = new( + EditorShaderCompilationState.Failed, + [new ShaderDiagnostic("SHADER_DEVICE_VALIDATION", DiagnosticSeverity.Error, failure.Message)] + ); } lock (m_shaderValidationLock) { if (m_shaderValidations.TryGetValue(state.documentId, out ShaderValidationState? current) - && ReferenceEquals(current, state)) - { + && ReferenceEquals(current, state) + ) { state.snapshot = snapshot; state.artifact = null; } @@ -200,21 +209,27 @@ out EditorPreviewHandle handle if (!output.isReady) { if (m_renderedPreviews.Remove(composition.viewportId, out PreviewState? stale)) + { m_previewsById.Remove(stale.handle.value); + } handle = default; return false; } if (m_renderedPreviews.TryGetValue(composition.viewportId, out PreviewState? current) - && current.presentationTexture == output.texture && current.handle.deviceGeneration == deviceGeneration) - { + && current.presentationTexture == output.texture && current.handle.deviceGeneration == deviceGeneration + ) { handle = current.handle; return true; } if (current is not null) + { m_previewsById.Remove(current.handle.value); + } ulong value = ++m_nextPreviewId; if (value == 0) + { value = ++m_nextPreviewId; + } handle = new(value, deviceGeneration, output.pixelWidth, output.pixelHeight); var preview = new PreviewState(default, handle, default, output.texture, composition.viewportId); m_renderedPreviews[composition.viewportId] = preview; @@ -247,11 +262,7 @@ public bool TryGetTexture( out EditorPreviewHandle handle ) { ArgumentNullException.ThrowIfNull(texture); - return TryGetTextureArtifact( - texture.GetTextureArtifactReference(), - texture.width, - texture.height, - out handle); + return TryGetTextureArtifact(texture.GetTextureArtifactReference(), texture.width, texture.height, out handle); } /// @@ -290,8 +301,8 @@ out EditorPreviewHandle handle if (m_previews.TryGetValue(texture, out PreviewState? existing)) { if (existing.residentTexture == resident && existing.handle.deviceGeneration == deviceGeneration - && existing.handle.pixelWidth == pixelWidth && existing.handle.pixelHeight == pixelHeight) - { + && existing.handle.pixelWidth == pixelWidth && existing.handle.pixelHeight == pixelHeight + ) { handle = existing.handle; return true; } @@ -299,12 +310,15 @@ out EditorPreviewHandle handle } ulong value = ++m_nextPreviewId; if (value == 0) + { value = ++m_nextPreviewId; + } var preview = new PreviewState( texture, new EditorPreviewHandle(value, deviceGeneration, pixelWidth, pixelHeight), resident, - m_presentation.RegisterTexture(resident)); + m_presentation.RegisterTexture(resident) + ); m_previews.Add(texture, preview); m_previewsById.Add(value, preview); handle = preview.handle; @@ -327,12 +341,14 @@ Vector2 logicalSize ObjectDisposedException.ThrowIf(m_disposed, this); if (!handle.isValid || handle.deviceGeneration != deviceGeneration || !m_previewsById.TryGetValue(handle.value, out PreviewState? preview) - || preview.handle != handle) - { + || preview.handle != handle + ) { throw new InvalidOperationException("The editor preview handle is stale or does not belong to this host."); } if (logicalSize.X <= 0f || logicalSize.Y <= 0f) + { throw new ArgumentOutOfRangeException(nameof(logicalSize), "Preview size must be positive."); + } m_presentation.DrawImage(preview.presentationTexture, logicalSize); } @@ -349,12 +365,14 @@ public bool Release(EditorPreviewHandle handle) { if (!handle.isValid || handle.deviceGeneration != deviceGeneration || !m_previewsById.Remove(handle.value, out PreviewState? preview) - || preview.handle != handle) - { + || preview.handle != handle + ) { return false; } if (preview.viewportId is not null) + { ReleaseRendered(preview.viewportId); + } else { m_previews.Remove(preview.reference); @@ -371,9 +389,13 @@ public bool Release(EditorPreviewHandle handle) private void ReleaseAllPreviews() { foreach (string viewportId in new List(m_renderedPreviews.Keys)) + { ReleaseRendered(viewportId); + } foreach (PreviewState preview in m_previews.Values) + { _ = m_presentation.UnregisterTexture(preview.presentationTexture); + } m_previews.Clear(); m_previewsById.Clear(); } @@ -412,16 +434,26 @@ public EditorViewportOutput Submit(EditorViewportComposition composition) viewport, layer.pipeline, layer.data, - layer.order)).ToArray(); + layer.order + )).ToArray(); if (layers.Length == 1) + { m_runtime.Submit(layers[0]); + } else - m_runtime.SubmitComposition($"Editor:{composition.viewportId}", target, - viewport, composition.targetFormat, layers); + { + m_runtime.SubmitComposition( + $"Editor:{composition.viewportId}", + target, + viewport, + composition.targetFormat, + layers + ); + } if (m_runtime.targets.TryGetTexture(state.target, out PersistentTextureHandle resident) - && resident != state.residentTexture) - { + && resident != state.residentTexture + ) { Unregister(state); state.presentationTexture = m_presentation.RegisterTexture(resident); state.residentTexture = resident; @@ -431,7 +463,8 @@ public EditorViewportOutput Submit(EditorViewportComposition composition) composition.viewportId, state.presentationTexture, composition.pixelWidth, - composition.pixelHeight); + composition.pixelHeight + ); } /// @@ -451,7 +484,8 @@ Vector2 logicalSize if (!output.isReady) { throw new InvalidOperationException( - $"Editor viewport '{output.viewportId}' has no completed render texture yet."); + $"Editor viewport '{output.viewportId}' has no completed render texture yet." + ); } m_presentation.DrawImage(output.texture, logicalSize); } @@ -467,10 +501,14 @@ public void Release(string viewportId) ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentException.ThrowIfNullOrWhiteSpace(viewportId); if (m_renderedPreviews.Remove(viewportId, out PreviewState? preview)) + { m_previewsById.Remove(preview.handle.value); + } m_runtime.resources.Release(new RenderPersistentResourceId(viewportId)); if (!m_viewports.Remove(viewportId, out ViewportState? state)) + { return; + } Unregister(state); m_runtime.targets.Release(state.target); } @@ -481,16 +519,22 @@ public void Release(string viewportId) public void ReleaseAll() { if (m_disposed) + { return; + } foreach (ViewportState state in m_viewports.Values) { Unregister(state); m_runtime.targets.Release(state.target); } foreach (string viewportId in m_viewports.Keys) + { m_runtime.resources.Release(new RenderPersistentResourceId(viewportId)); + } foreach (PreviewState preview in m_renderedPreviews.Values) + { m_previewsById.Remove(preview.handle.value); + } m_renderedPreviews.Clear(); m_viewports.Clear(); } @@ -501,13 +545,17 @@ public void ReleaseAll() public void Dispose() { if (m_disposed) + { return; + } _ = m_runtime.UnregisterContributor(this); m_reloadRegistration.Dispose(); ReleaseAll(); ReleaseAllPreviews(); lock (m_shaderValidationLock) + { m_shaderValidations.Clear(); + } m_disposed = true; } @@ -517,21 +565,22 @@ IGenerationChange IEditorReloadParticipant.Capture(AssemblyReloadContext context return new RenderingReloadTransaction(this, m_runtime.BeginExtensionReload()); } - void IEditorReloadParticipant.RefreshDiagnostics() - { - } + void IEditorReloadParticipant.RefreshDiagnostics() {} private static RenderTextureDescriptor CreateDescriptor(EditorViewportComposition composition) => new( composition.pixelWidth, composition.pixelHeight, composition.targetFormat, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ); private void Unregister(ViewportState state) { if (state.presentationTexture.isValid) + { _ = m_presentation.UnregisterTexture(state.presentationTexture); + } state.presentationTexture = default; state.residentTexture = default; } @@ -556,7 +605,9 @@ public void PrepareForActivation() owner.ReleaseAll(); owner.ReleaseAllPreviews(); lock (owner.m_shaderValidationLock) + { owner.m_shaderValidations.Clear(); + } } /// @@ -581,9 +632,7 @@ public void Apply() /// /// Restores the state captured before the current transaction began. /// - public void RestorePreviousState() - { - } + public void RestorePreviousState() {} } private sealed record PreviewState( diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Layout/EditorDefaultLayout.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Layout/EditorDefaultLayout.cs index dfd2e0adf..da1945a8b 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Layout/EditorDefaultLayout.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Layout/EditorDefaultLayout.cs @@ -12,7 +12,7 @@ internal static class EditorDefaultLayout private static string ReadDocument() { using Stream stream = typeof(EditorDefaultLayout).Assembly.GetManifestResourceStream(C_RESOURCE_NAME) - ?? throw new InvalidOperationException("The standard Editor layout resource is missing."); + ?? throw new InvalidOperationException("The standard Editor layout resource is missing."); using var reader = new StreamReader(stream); return reader.ReadToEnd(); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs index 269c627d4..211b3f609 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs @@ -1,15 +1,17 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.IO; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; namespace Inno.Editor.Panel.FileBrowser; + internal sealed class FileBrowserChangeTracker(AssetBrowserModule assets) { private EditorContext? m_context; + internal void Attach(EditorContext context) { ArgumentNullException.ThrowIfNull(context); @@ -31,27 +33,40 @@ private void OnSourceMountsChanged() { EditorContext? context = m_context; if (context is null) + { return; + } string currentDirectory = FileBrowserUtility.NormalizePath(assets.browser.currentDirectory); - if (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(currentDirectory), out AssetFileEntry current) || !current.isDirectory) + if (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(currentDirectory), out AssetFileEntry current) + || !current.isDirectory + ) { assets.browser.SetCurrentDirectory(string.Empty); + } string selectedPath = FileBrowserUtility.NormalizePath(assets.browser.GetSelectedPath(context)); if (!string.IsNullOrEmpty(selectedPath) && !assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(selectedPath), out _)) + { assets.browser.Select(context, null); + } } private void OnAssetsChanged(AssetChangeSet changes) { EditorContext? context = m_context; if (context is null) + { return; + } for (int i = 0; i < changes.changes.Count; i++) { AssetChange change = changes.changes[i]; if (change.kind == AssetChangeKind.Moved) + { ApplyMove(context, change.previousAssetPath?.ToString() ?? string.Empty, change.assetPath.ToString()); + } else if (change.kind is AssetChangeKind.Missing or AssetChangeKind.Removed) + { ApplyRemoval(context, change.assetPath.ToString()); + } } } @@ -63,7 +78,9 @@ string newPath oldPath = Normalize(oldPath); newPath = Normalize(newPath); if (string.IsNullOrEmpty(oldPath) || string.IsNullOrEmpty(newPath)) + { return; + } string currentDirectory = Normalize(assets.browser.currentDirectory); if (IsSameOrDescendant(currentDirectory, oldPath)) { @@ -73,7 +90,9 @@ string newPath string selectedPath = Normalize(assets.browser.GetSelectedPath(context)); if (!IsSameOrDescendant(selectedPath, oldPath)) + { return; + } string selectedSuffix = selectedPath.Length == oldPath.Length ? string.Empty : selectedPath[oldPath.Length..].TrimStart('/'); assets.browser.Select(context, Combine(newPath, selectedSuffix)); } @@ -84,40 +103,44 @@ string removedPath ) { removedPath = Normalize(removedPath); if (string.IsNullOrEmpty(removedPath)) + { return; + } string selectedPath = Normalize(assets.browser.GetSelectedPath(context)); if (IsSameOrDescendant(selectedPath, removedPath)) + { assets.browser.Select(context, null); + } string currentDirectory = Normalize(assets.browser.currentDirectory); if (!IsSameOrDescendant(currentDirectory, removedPath)) + { return; + } string fallback = FileBrowserUtility.GetParentDirectory(removedPath); - while (!string.Equals( - fallback, - FileBrowserUtility.GetParentDirectory(fallback), - StringComparison.Ordinal - ) - && (!assets.edits.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(fallback), - out var entry - ) - || !entry.isDirectory)) - { + while (!string.Equals(fallback, FileBrowserUtility.GetParentDirectory(fallback), StringComparison.Ordinal) + && (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(fallback), out var entry) + || !entry.isDirectory) + ) { fallback = FileBrowserUtility.GetParentDirectory(fallback); } if (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(fallback), out AssetFileEntry available) || !available.isDirectory) + { fallback = string.Empty; + } assets.browser.SetCurrentDirectory(fallback); } private static bool IsSameOrDescendant( string path, string ancestor - ) => string.Equals(path, ancestor, StringComparison.OrdinalIgnoreCase) || path.StartsWith(ancestor + "/", StringComparison.OrdinalIgnoreCase); + ) => string.Equals(path, ancestor, StringComparison.OrdinalIgnoreCase) + || path.StartsWith(ancestor + "/", StringComparison.OrdinalIgnoreCase); + private static string Combine( string left, string right ) => string.IsNullOrEmpty(right) ? left : $"{left}/{right}"; + private static string Normalize(string? path) => string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim('/'); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs index 05b93ec91..a1bd3ff2e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs @@ -1,19 +1,21 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed class FileBrowserContextMenu( AssetBrowserModule assets, FileBrowserRename rename -) -{ +) { internal void DrawEntry( EditorContext context, string id, @@ -21,13 +23,23 @@ internal void DrawEntry( FileBrowserPresentation presentation ) { if (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(relativePath), out AssetFileEntry entry)) + { return; + } if (Ui.IsItemClicked(ImGuiMouseButton.Right) && !assets.edits.interactions.selection.Contains(entry)) + { assets.edits.interactions.SetSelection(entry); + } string creationDirectory = entry.isDirectory ? entry.assetPath.ToString() : GetParentDirectory(entry.assetPath.ToString()); - bool isOpen = EditorUI.current.menus.ContextMenu(id, CreateDirectoryInteraction(creationDirectory), assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, entry)); + bool isOpen = EditorUI.current.menus.ContextMenu( + id, + CreateDirectoryInteraction(creationDirectory), + assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, entry) + ); if (isOpen) + { rename.MarkInteraction(presentation); + } } internal void DrawDirectory( @@ -37,10 +49,14 @@ internal void DrawDirectory( FileBrowserPresentation presentation ) { if (IsReadOnlySource(assets.edits.pipeline, relativePath)) + { return; + } bool isOpen = EditorUI.current.menus.ContextMenu(id, CreateDirectoryInteraction(relativePath)); if (isOpen) + { rename.MarkInteraction(presentation); + } } internal void DrawBackground( @@ -49,14 +65,16 @@ internal void DrawBackground( FileBrowserPresentation presentation ) { if (IsReadOnlyLocation(assets.edits.pipeline, assets.browser)) + { return; + } bool isOpen = EditorUI.current.menus.WindowContextMenu(id, CreateDirectoryInteraction(assets.browser.currentDirectory)); if (isOpen) + { rename.MarkInteraction(presentation); + } } - private Inno.Editor.Interactions.EditorInteraction CreateDirectoryInteraction(string relativePath) => assets.edits.interactions.For( - FileBrowserInteractionIds.C_AREA, - NormalizePath(relativePath) - ); + private Inno.Editor.Interactions.EditorInteraction CreateDirectoryInteraction(string relativePath) + => assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, NormalizePath(relativePath)); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs index af616c7e4..28dd20ef8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs @@ -1,14 +1,15 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; -using System.Linq; using System.Diagnostics.CodeAnalysis; -using Inno.Core.Identity; +using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal enum FileBrowserEntryTypeFilter { All, @@ -30,6 +31,7 @@ internal readonly record struct FileBrowserDisplayEntry( bool isDirectory, bool isPluginRoot = false ); + internal sealed class FileBrowserData(AssetBrowserModule assets) { private ViewInput? m_input; @@ -41,9 +43,18 @@ internal IReadOnlyList CollectVisibleEntries( FileBrowserEntryScopeFilter scopeFilter, string searchFilter ) { - var input = new ViewInput(assets.edits.pipeline.revision, assets.browser.root, assets.browser.currentDirectory, typeFilter, scopeFilter, searchFilter); + var input = new ViewInput( + assets.edits.pipeline.revision, + assets.browser.root, + assets.browser.currentDirectory, + typeFilter, + scopeFilter, + searchFilter + ); if (m_input == input) + { return m_entries; + } List entries = []; if (assets.browser.root == AssetBrowserRoot.Plugins && string.IsNullOrEmpty(assets.browser.currentDirectory)) { @@ -53,10 +64,14 @@ string searchFilter { IReadOnlyList children = GetVisibleChildren(assets.browser.currentDirectory); for (int i = 0; i < children.Count; i++) + { entries.Add(Describe(children[i], children[i].name)); + } } else + { CollectEntriesRecursive(assets.browser.currentDirectory, entries); + } ApplyTypeFilter(entries, typeFilter); ApplySearchFilter(entries, searchFilter); entries.Sort(static ( @@ -66,7 +81,9 @@ string searchFilter { int byName = string.Compare(left.displayName, right.displayName, StringComparison.OrdinalIgnoreCase); if (byName != 0) + { return byName; + } int byExtension = string.Compare(left.extension, right.extension, StringComparison.OrdinalIgnoreCase); return byExtension != 0 ? byExtension : string.CompareOrdinal(left.path.ToString(), right.path.ToString()); }); @@ -81,8 +98,8 @@ internal bool TryResolve( [NotNullWhen(true)] out AssetFileEntry? entry ) { if (assets.edits.interactions.TryResolveIdentity(item.identity, out IdentityObject? target) - && target is AssetFileEntry resolved && resolved.assetPath == item.path) - { + && target is AssetFileEntry resolved && resolved.assetPath == item.path + ) { entry = resolved; return true; } @@ -94,8 +111,14 @@ private static FileBrowserDisplayEntry Describe( AssetFileEntry entry, string label, bool pluginRoot = false - ) => new(entry.identity.runtimeIdentity ?? throw new InvalidOperationException("A visible asset requires a registered identity."), - entry.assetPath, label, entry.extension, entry.isDirectory, pluginRoot); + ) => new( + entry.identity.runtimeIdentity ?? throw new InvalidOperationException("A visible asset requires a registered identity."), + entry.assetPath, + label, + entry.extension, + entry.isDirectory, + pluginRoot + ); private static void ApplyTypeFilter( List entries, @@ -136,10 +159,14 @@ FileBrowserEntryScopeFilter scopeFilter AssetSourceMount mount = mounts[i]; var rootPath = new AssetPath(mount.id, string.Empty); if (!assets.edits.pipeline.TryGetFileSystemEntry(rootPath, out AssetFileEntry root)) + { continue; + } entries.Add(Describe(root, mount.id.value, pluginRoot: true)); if (scopeFilter == FileBrowserEntryScopeFilter.Recursive) + { CollectEntriesRecursive(root.assetPath.ToString(), entries); + } } } @@ -155,7 +182,9 @@ List entries { entries.Add(Describe(child, child.name)); if (child.isDirectory) + { pending.Push(child.assetPath.ToString()); + } } } } @@ -169,7 +198,9 @@ internal List SortTreeEntries(IReadOnlyList entr ) => { if (left.isDirectory != right.isDirectory) + { return left.isDirectory ? -1 : 1; + } return string.Compare(left.name, right.name, StringComparison.OrdinalIgnoreCase); }); return sorted; @@ -180,12 +211,16 @@ internal IReadOnlyList GetVisibleChildren(string relativePath) AssetSourceId source = AssetPath.Parse(relativePath).source; IReadOnlyList children = assets.edits.pipeline.GetFileSystemChildren(AssetPath.Parse(relativePath)); if (children.Count == 0) + { return children; + } List isolated = []; for (int i = 0; i < children.Count; i++) { if (children[i].source == source) + { isolated.Add(children[i]); + } } return isolated; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs index f1236289b..262703d01 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs @@ -1,14 +1,16 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + /// /// Binds managed File Browser drag sessions to native entry and directory items. /// @@ -30,19 +32,18 @@ internal void DrawAssetSource( EditorContext context, AssetFileEntry entry ) { - if (!assets.edits.TryCreateContext( - context, - entry.assetPath.ToString(), - out AssetEditorContext? assetContext - ) + if (!assets.edits.TryCreateContext(context, entry.assetPath.ToString(), out AssetEditorContext? assetContext) || assetContext is null - || !assets.edits.TryCreateDragData( - assetContext, - out EditorDragData? data - ) - || data is null) + || !assets.edits.TryCreateDragData(assetContext, out EditorDragData? data) + || data is null + ) { return; - _ = EditorDragDropRenderer.Source(assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, entry), data, () => Ui.Text(data.label)); + } + _ = EditorDragDropRenderer.Source( + assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, entry), + data, + () => Ui.Text(data.label) + ); } /// @@ -59,12 +60,18 @@ internal void DrawDirectoryTarget( string relativePath ) { if (FileBrowserUtility.IsReadOnlySource(assets.edits.pipeline, relativePath)) + { return; + } System.Numerics.Vector2 minimum = Ui.GetItemMinimum(); System.Numerics.Vector2 maximum = Ui.GetItemMaximum(); - EditorDropWidgetResult result = EditorDragDropRenderer.Target(assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, relativePath)); + EditorDropWidgetResult result = EditorDragDropRenderer.Target( + assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, relativePath) + ); if (!result.isPreviewing || !result.status.canDrop) + { return; + } EditorUI.current.widgets.DropTargetHighlight(minimum, maximum); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserNavigation.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserNavigation.cs index fb76db4da..d87412497 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserNavigation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserNavigation.cs @@ -1,14 +1,16 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.Interactions; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; namespace Inno.Editor.Panel.FileBrowser; + internal sealed class FileBrowserNavigation(AssetBrowserModule assets) { private readonly Stack m_backHistory = []; @@ -23,15 +25,21 @@ internal void NavigateTo( string? selectedPathAfterNavigation = null ) { directory = NormalizePath(directory); - AssetBrowserRoot root = string.IsNullOrEmpty(directory) ? assets.browser.root : AssetPath.Parse(directory).source == AssetSourceId.project ? AssetBrowserRoot.Assets : AssetBrowserRoot.Plugins; + AssetBrowserRoot root = string.IsNullOrEmpty(directory) + ? assets.browser.root + : AssetPath.Parse(directory).source == AssetSourceId.project ? AssetBrowserRoot.Assets : AssetBrowserRoot.Plugins; var target = new BrowserLocation(root, directory); if (CurrentLocation == target) + { return; + } m_backHistory.Push(CurrentLocation); m_forwardHistory.Clear(); ApplyLocation(context, target); if (selectedPathAfterNavigation is not null) + { assets.browser.Select(context, selectedPathAfterNavigation); + } } internal void NavigateToRoot( @@ -40,7 +48,9 @@ AssetBrowserRoot root ) { var target = new BrowserLocation(root, string.Empty); if (CurrentLocation == target) + { return; + } m_backHistory.Push(CurrentLocation); m_forwardHistory.Clear(); ApplyLocation(context, target); @@ -51,7 +61,9 @@ internal void SwitchRoot( AssetBrowserRoot root ) { if (assets.browser.root == root) + { return; + } m_backHistory.Clear(); m_forwardHistory.Clear(); ApplyLocation(context, new BrowserLocation(root, assets.browser.GetDirectory(root))); @@ -60,7 +72,9 @@ AssetBrowserRoot root internal void GoBack(EditorContext context) { if (m_backHistory.Count == 0) + { return; + } m_forwardHistory.Push(CurrentLocation); ApplyLocation(context, m_backHistory.Pop()); } @@ -68,7 +82,9 @@ internal void GoBack(EditorContext context) internal void GoForward(EditorContext context) { if (m_forwardHistory.Count == 0) + { return; + } m_backHistory.Push(CurrentLocation); ApplyLocation(context, m_forwardHistory.Pop()); } @@ -103,7 +119,9 @@ string directory ) { var location = new BrowserLocation(root, NormalizePath(directory)); if (m_historyCurrent == location) + { return; + } m_historyCurrent = location; m_backHistory.Clear(); m_forwardHistory.Clear(); @@ -114,8 +132,7 @@ string directory private readonly record struct BrowserLocation( AssetBrowserRoot root, string directory - ) - { + ) { internal static BrowserLocation AssetsRoot { get; } = new(AssetBrowserRoot.Assets, string.Empty); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs index d766dd373..dc8b560d5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs @@ -1,6 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -8,19 +5,27 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserPanel { private void DrawEntryFilterCombo() { if (!EditorUI.current.widgets.BeginBoundedCombo("##AssetEntryFilter", "Filter", ImGuiComboFlags.WidthFitPreview)) + { return; + } DrawEntryTypeFilterOption("All", FileBrowserEntryTypeFilter.All); DrawEntryTypeFilterOption("Folders", FileBrowserEntryTypeFilter.FoldersOnly); DrawEntryTypeFilterOption("Files", FileBrowserEntryTypeFilter.FilesOnly); @@ -38,9 +43,13 @@ FileBrowserEntryTypeFilter filter if (Ui.Checkbox(label, ref selected)) { if (selected) + { m_entryTypeFilter = filter; + } else if (m_entryTypeFilter == filter) + { m_entryTypeFilter = FileBrowserEntryTypeFilter.All; + } } } @@ -52,9 +61,13 @@ FileBrowserEntryScopeFilter filter if (Ui.Checkbox(label, ref selected)) { if (selected) + { m_entryScopeFilter = filter; + } else if (m_entryScopeFilter == filter) + { m_entryScopeFilter = FileBrowserEntryScopeFilter.CurrentOnly; + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs index a83e65438..233996039 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs @@ -1,6 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -8,13 +5,19 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserPanel { private void DrawGridRegion( @@ -29,7 +32,9 @@ IReadOnlyList entries if (entriesVisible) { if (Ui.IsWindowFocused()) + { m_rename.MarkInteraction(FileBrowserPresentation.Grid); + } float cellSize = GetGridCellSize(); int columns = Math.Max(1, (int)(Ui.GetContentRegionAvailable().X / cellSize)); int rows = Math.Max(1, (int)(Ui.GetContentRegionAvailable().Y / cellSize)); @@ -87,7 +92,9 @@ IReadOnlyList entries 0f ); if (!tableStarted) + { return; + } try { int rowCount = (entries.Count + columns - 1) / columns; @@ -106,7 +113,9 @@ IReadOnlyList entries { int index = row * state.columns + column; if (index >= state.entries.Count) + { break; + } _ = Ui.TableSetColumnIndex(column); state.panel.DrawGridItem(state.context, state.entries[index]); } @@ -142,7 +151,9 @@ FileBrowserDisplayEntry item { ImGuiSelectableFlags selectableFlags = ImGuiSelectableFlags.AllowDoubleClick; if (editing) + { selectableFlags |= ImGuiSelectableFlags.AllowOverlap; + } RequestEntryKeyboardFocus(entry); bool activated = Ui.Selectable("##GridItem", selected, selectableFlags, itemSize); bool itemHovered = Ui.IsItemHovered(); @@ -161,7 +172,9 @@ FileBrowserDisplayEntry item m_dragDrop.DrawAssetSource(context, entry); m_contextMenu.DrawEntry(context, "##asset_grid_context", entry.assetPath.ToString(), FileBrowserPresentation.Grid); if (entry.isDirectory && !entry.isReadOnly) + { m_dragDrop.DrawDirectoryTarget(context, entry.assetPath.ToString()); + } } DrawGridItemVisual(icon, name, selected, m_gridScale, itemHovered, itemActive, itemMin, itemMax, drawName: !editing); @@ -174,7 +187,14 @@ FileBrowserDisplayEntry item float labelAreaTop = itemMax.Y - CurrentBrowserStyle.gridLabelBottomPadding - labelAreaHeight; float y = labelAreaTop + (labelAreaHeight - lineHeight) * 0.5f; Ui.SetCursorScreenPosition(new Vector2(itemMin.X + CurrentBrowserStyle.gridLabelHorizontalPadding * 0.5f, y)); - m_rename.Draw(context, $"grid_{entry.assetPath.ToString()}", entry.assetPath.ToString(), FileBrowserPresentation.Grid, width, lineHeight); + m_rename.Draw( + context, + $"grid_{entry.assetPath.ToString()}", + entry.assetPath.ToString(), + FileBrowserPresentation.Grid, + width, + lineHeight + ); Ui.SetCursorScreenPosition(layoutCursor); Ui.Dummy(Vector2.Zero); } @@ -200,16 +220,24 @@ bool drawName Vector2 size = max - min; Vector4 bg = selected ? EditorPalette.contentAccent : EditorPalette.collectionHeader; if (active) + { bg = EditorPalette.GetActive(bg); + } else if (hovered) + { bg = EditorPalette.GetHovered(bg); + } uint bgColor = Ui.ToPackedColor(bg); Ui.DrawFilledRectangle(min, max, bgColor, CurrentBrowserStyle.frameRounding); float fontSize = Ui.GetFontSize(); float iconFontSize = fontSize * scale; Vector4 iconBounds = EditorUI.current.widgets.GetGlyphVisualBounds(iconFontSize, icon); Vector2 iconSize = new(iconBounds.Z - iconBounds.X, iconBounds.W - iconBounds.Y); - string[] nameLines = FitTextToLines(name, MathF.Max(1f, size.X - CurrentBrowserStyle.gridLabelHorizontalPadding), C_GRID_LABEL_LINE_COUNT); + string[] nameLines = FitTextToLines( + name, + MathF.Max(1f, size.X - CurrentBrowserStyle.gridLabelHorizontalPadding), + C_GRID_LABEL_LINE_COUNT + ); float lineHeight = Ui.GetTextLineHeight(); float lineAdvance = MathF.Max(1f, lineHeight + CurrentBrowserStyle.gridLabelLineSpacing); float labelAreaHeight = lineHeight + lineAdvance * (C_GRID_LABEL_LINE_COUNT - 1); @@ -229,7 +257,10 @@ bool drawName } float horizontalCenter = min.X + size.X * 0.5f; - Vector2 iconAreaCenter = new(horizontalCenter + C_GRID_ICON_HORIZONTAL_OPTICAL_OFFSET * EditorUI.current.widgets.style.zoom, iconAreaTop + maximumIconHeight * 0.5f); + Vector2 iconAreaCenter = new( + horizontalCenter + C_GRID_ICON_HORIZONTAL_OPTICAL_OFFSET * EditorUI.current.widgets.style.zoom, + iconAreaTop + maximumIconHeight * 0.5f + ); uint textColor = Ui.ToPackedColor(EditorPalette.contentText); Ui.PushClipRect(min, max, true); EditorUI.current.widgets.AddGlyphCentered(iconFontSize, icon, iconAreaCenter, textColor); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs index 56dc7d379..111144916 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs @@ -1,7 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Core.Identity; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -9,13 +5,20 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserPanel { private void DrawBrowser(EditorContext context) @@ -24,12 +27,20 @@ private void DrawBrowser(EditorContext context) EditorUiLayout style = Ui.GetLayout(); float breadcrumbBarHeight = GetBreadcrumbBarHeight(m_assets.browser.root, m_assets.browser.currentDirectory); Vector2 bodySize = new(0f, -(breadcrumbBarHeight + style.itemSpacing.Y)); - bool mainVisible = Ui.BeginChild("##FileBrowserMain", bodySize, ImGuiChildFlags.None, (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)); + bool mainVisible = Ui.BeginChild( + "##FileBrowserMain", + bodySize, + ImGuiChildFlags.None, + (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse) + ); try { if (mainVisible) { - ImGuiTableFlags splitFlags = ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoKeepColumnsVisible | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.NoSavedSettings; + ImGuiTableFlags splitFlags = ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.NoKeepColumnsVisible + | ImGuiTableFlags.SizingFixedFit + | ImGuiTableFlags.NoSavedSettings; float splitterWidth = GetTreeSplitterWidth(style); float availableWidth = MathF.Max(0f, Ui.GetContentRegionAvailable().X); float treeWidth = ResolveTreeWidth(m_treePaneRatio, availableWidth, splitterWidth); @@ -42,7 +53,11 @@ private void DrawBrowser(EditorContext context) if (splitStarted) { Ui.TableSetupColumn("##Tree", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), treeWidth); - Ui.TableSetupColumn("##Splitter", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), splitterWidth); + Ui.TableSetupColumn( + "##Splitter", + (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), + splitterWidth + ); Ui.TableSetupColumn("##Content", ImGuiTableColumnFlags.WidthStretch); Ui.TableNextRow(); _ = Ui.TableSetColumnIndex(0); @@ -56,7 +71,9 @@ private void DrawBrowser(EditorContext context) finally { if (splitStarted) + { Ui.EndTable(); + } } } finally @@ -88,7 +105,9 @@ float treeWidth bool hovered = Ui.IsItemHovered(); bool active = Ui.IsItemActive(); if (hovered || active) + { Ui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + } if (active) { Vector2 delta = Ui.GetMouseDragDelta(ImGuiMouseButton.Left); @@ -142,13 +161,23 @@ private void DrawTreePane(EditorContext context) { EditorUiLayout style = Ui.GetLayout(); Vector2 treePaneSize = new(-style.windowPadding.X, 0f); - bool treeVisible = Ui.BeginChild("##TreePane", treePaneSize, ImGuiChildFlags.None, (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)); + bool treeVisible = Ui.BeginChild( + "##TreePane", + treePaneSize, + ImGuiChildFlags.None, + (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse) + ); try { if (treeVisible) { float footerHeight = Ui.GetFrameHeight() + style.windowPadding.Y * 2f + style.itemSpacing.Y; - bool treeScrollVisible = Ui.BeginChild("##TreeScroll", new Vector2(0f, -footerHeight), ImGuiChildFlags.None, ImGuiWindowFlags.HorizontalScrollbar); + bool treeScrollVisible = Ui.BeginChild( + "##TreeScroll", + new Vector2(0f, -footerHeight), + ImGuiChildFlags.None, + ImGuiWindowFlags.HorizontalScrollbar + ); try { if (treeScrollVisible) @@ -182,7 +211,9 @@ private void DrawTreePane(EditorContext context) } if (!IsReadOnlyLocation(m_assets.edits.pipeline, m_assets.browser)) + { m_dragDrop.DrawDirectoryTarget(context, m_assets.browser.currentDirectory); + } } finally { @@ -214,7 +245,12 @@ private void DrawContentPane(EditorContext context) Ui.PushStyleColor(ImGuiCol.ChildBg, EditorPalette.collectionHeader); try { - bool contentVisible = Ui.BeginChild("##ContentPane", Vector2.Zero, ImGuiChildFlags.None, (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)); + bool contentVisible = Ui.BeginChild( + "##ContentPane", + Vector2.Zero, + ImGuiChildFlags.None, + (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse) + ); try { if (contentVisible) @@ -229,7 +265,9 @@ private void DrawContentPane(EditorContext context) } if (!IsReadOnlyLocation(m_assets.edits.pipeline, m_assets.browser)) + { m_dragDrop.DrawDirectoryTarget(context, m_assets.browser.currentDirectory); + } } finally { @@ -248,9 +286,13 @@ IReadOnlyList entries try { if (m_viewMode == ViewMode.List) + { DrawListRegion(context, entries); + } else + { DrawGridRegion(context, entries); + } } finally { @@ -261,8 +303,10 @@ IReadOnlyList entries m_pendingActivation = null; if (activation is RuntimeIdentity identity && m_assets.edits.interactions.TryResolveIdentity(identity, out Inno.Core.Identity.IdentityObject? target) - && target is AssetFileEntry entry) + && target is AssetFileEntry entry + ) { m_navigation.OpenEntry(context, entry, m_tree); + } } private static void DrawFooterTopSplitter() diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs index f89ad1f9e..70521cb4a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs @@ -1,6 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -8,13 +5,19 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserPanel { private void DrawListRegion( @@ -27,7 +30,9 @@ IReadOnlyList entries if (entriesVisible) { if (Ui.IsWindowFocused()) + { m_rename.MarkInteraction(FileBrowserPresentation.List); + } float rowHeight = Ui.GetTextLineHeight() + Ui.GetLayout().cellPadding.Y * 2f + CurrentBrowserStyle.listRowSpacing; HandleEntryKeyboardNavigation(Math.Max(1, (int)(Ui.GetContentRegionAvailable().Y / rowHeight))); DrawEntriesTable(context, entries, m_assets.browser.currentDirectory); @@ -46,7 +51,10 @@ private void DrawEntriesTable( IReadOnlyList entries, string currentDirectory ) { - ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings; + ImGuiTableFlags flags = ImGuiTableFlags.RowBg + | ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.SizingStretchProp + | ImGuiTableFlags.NoSavedSettings; EditorUiLayout style = Ui.GetLayout(); Vector2 tableOrigin = Ui.GetCursorScreenPosition(); Vector2 tableSize = Ui.GetContentRegionAvailable(); @@ -62,17 +70,32 @@ string currentDirectory try { - Ui.TableSetupColumn("Name", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), m_listNameSeparatorPosition); - Ui.TableSetupColumn("Type", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), m_listTypeSeparatorPosition - m_listNameSeparatorPosition); - Ui.TableSetupColumn("Source", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), 1f - m_listTypeSeparatorPosition); + Ui.TableSetupColumn( + "Name", + (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), + m_listNameSeparatorPosition + ); + Ui.TableSetupColumn( + "Type", + (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), + m_listTypeSeparatorPosition - m_listNameSeparatorPosition + ); + Ui.TableSetupColumn( + "Source", + (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize), + 1f - m_listTypeSeparatorPosition + ); DrawHeaderRow(); uint rowBg = Ui.ToPackedColor(EditorPalette.collectionRow); uint rowAltBg = Ui.ToPackedColor(EditorPalette.collectionRowAlternate); float entryRowHeight = Ui.GetTextLineHeight() + style.cellPadding.Y * 2f + CurrentBrowserStyle.listRowSpacing; Span preserved = stackalloc int[3]; int preservedCount = CollectPreservedEntryRows(entries, preserved); - m_ui.widgets.ClippedRows(entries.Count, -1f, - (panel: this, context, entries, currentDirectory, rowBg, rowAltBg, entryRowHeight), static ( + m_ui.widgets.ClippedRows( + entries.Count, + -1f, + (panel: this, context, entries, currentDirectory, rowBg, rowAltBg, entryRowHeight), + static ( state, start, end @@ -83,13 +106,17 @@ string currentDirectory FileBrowserDisplayEntry item = state.entries[index]; Ui.TableNextRow(ImGuiTableRowFlags.None, state.entryRowHeight); if (!state.panel.m_data.TryResolve(item, out AssetFileEntry? entry)) + { continue; + } Ui.TableSetBgColor(ImGuiTableBgTarget.RowBg0, index % 2 == 0 ? state.rowBg : state.rowAltBg); state.panel.DrawNameCell(state.context, item, entry); DrawTextCell(item.isPluginRoot ? "IPLUGIN" : GetTypeText(entry), EditorPalette.contentText); DrawTextCell(item.isPluginRoot ? "~" : GetSourceText(entry, state.currentDirectory), EditorPalette.contentText); } - }, preserved[..preservedCount]); + }, + preserved[..preservedCount] + ); } finally { @@ -130,7 +157,9 @@ Vector2 size nameHovered = Ui.IsItemHovered(); nameActive = Ui.IsItemActive(); if (nameHovered || nameActive) + { Ui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + } if (nameActive) { float requested = (Ui.GetMousePos().X - origin.X) / width; @@ -144,7 +173,9 @@ Vector2 size typeHovered = Ui.IsItemHovered(); typeActive = Ui.IsItemActive(); if (typeHovered || typeActive) + { Ui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + } if (typeActive) { float requested = (Ui.GetMousePos().X - origin.X) / width; @@ -221,7 +252,9 @@ AssetFileEntry entry try { Vector2 iconTextPos = Ui.GetCursorScreenPosition(); - ImGuiSelectableFlags selectableFlags = ImGuiSelectableFlags.SpanAllColumns | ImGuiSelectableFlags.AllowDoubleClick | ImGuiSelectableFlags.AllowOverlap; + ImGuiSelectableFlags selectableFlags = ImGuiSelectableFlags.SpanAllColumns + | ImGuiSelectableFlags.AllowDoubleClick + | ImGuiSelectableFlags.AllowOverlap; RequestEntryKeyboardFocus(entry); bool activated = Ui.Selectable($"##entry_{entry.assetPath.ToString()}", selected, selectableFlags); bool itemHovered = Ui.IsItemHovered(); @@ -234,7 +267,12 @@ AssetFileEntry entry bool itemActive = Ui.IsItemActive(); if (!editing) { - m_contextMenu.DrawEntry(context, $"##asset_context_{entry.assetPath.ToString()}", entry.assetPath.ToString(), FileBrowserPresentation.List); + m_contextMenu.DrawEntry( + context, + $"##asset_context_{entry.assetPath.ToString()}", + entry.assetPath.ToString(), + FileBrowserPresentation.List + ); } if (selected || itemHovered) @@ -247,7 +285,9 @@ AssetFileEntry entry { m_dragDrop.DrawAssetSource(context, entry); if (entry.isDirectory && !entry.isReadOnly) + { m_dragDrop.DrawDirectoryTarget(context, entry.assetPath.ToString()); + } } Ui.SameLine(iconTextPos.X - Ui.GetWindowPos().X, 0f); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Navigation.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Navigation.cs index 1282efbca..f5de7c453 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Navigation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Navigation.cs @@ -1,8 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Core.Identity; -using Inno.Editor.Interactions; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -10,13 +5,21 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserPanel { private int CollectPreservedEntryRows( @@ -27,13 +30,17 @@ private int CollectPreservedEntryRows( RuntimeIdentity? editing = m_rename.activeTarget; RuntimeIdentity? dragging = m_assets.edits.interactions.TryGetActiveDragIdentity(out RuntimeIdentity source) ? source : null; if (editing is null && dragging is null && m_drawKeyboardFocus is null) + { return 0; + } int count = 0; for (int index = 0; index < entries.Count; index++) { RuntimeIdentity identity = entries[index].identity; if (identity == editing || identity == dragging || identity == m_drawKeyboardFocus) + { rows[count++] = index / columns; + } } return count; } @@ -52,7 +59,9 @@ private void DrawNavigationBar(EditorContext context) PushButtonColors(canGoBack ? EditorPalette.contentAccent : EditorPalette.contentBorderSoft); Ui.BeginDisabled(!canGoBack); if (Ui.SmallButton($"{ImGuiIcon.AngleLeft}##Back")) + { m_navigation.GoBack(context); + } Ui.EndDisabled(); Ui.PopStyleColor(3); Ui.SameLine(0f, EditorUI.current.widgets.style.toolbarTightSpacing); @@ -60,7 +69,9 @@ private void DrawNavigationBar(EditorContext context) PushButtonColors(canGoForward ? EditorPalette.contentAccent : EditorPalette.contentBorderSoft); Ui.BeginDisabled(!canGoForward); if (Ui.SmallButton($"{ImGuiIcon.AngleRight}##Forward")) + { m_navigation.GoForward(context); + } Ui.EndDisabled(); Ui.PopStyleColor(3); Ui.SameLine(0f, EditorUI.current.widgets.style.toolbarSectionSpacing); @@ -75,7 +86,9 @@ private void DrawViewAndSearchBar() Ui.PushStyleVar((ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.toolbarFramePadding); PushButtonColors(EditorPalette.contentAccent); if (Ui.SmallButton($"{m_viewMode}##ViewMode")) + { m_viewMode = m_viewMode == ViewMode.List ? ViewMode.Grid : ViewMode.List; + } Ui.PopStyleColor(3); Ui.SameLine(0f, EditorUI.current.widgets.style.toolbarSpacing); DrawEntryFilterCombo(); @@ -118,17 +131,23 @@ private void HandleEntryKeyboardNavigation(int pageSize) break; } if (candidate == selected) + { selectedIndex = i; + } } if (focus < 0) + { focus = selectedIndex; + } ListNavigationResult navigation = m_ui.widgets.NavigateList(interactions, m_visibleSelection.Count, focus, pageSize); m_keyboardHandled = navigation.focusChanged || navigation.selectionRequested || navigation.activate || navigation.cancel; if (navigation.focusedIndex >= 0 && m_keyboardHandled) { RuntimeIdentity identity = m_visibleSelection[navigation.focusedIndex]; if (!interactions.TryResolveIdentity(identity, out IdentityObject? target) || target is null) + { return; + } m_keyboardFocus = identity; if (navigation.focusChanged) { @@ -138,24 +157,36 @@ private void HandleEntryKeyboardNavigation(int pageSize) if (navigation.selectionRequested) { if (navigation.extendRange) + { interactions.SelectRange(m_visibleSelection, target, navigation.additive); + } else if (navigation.toggle) + { interactions.ToggleSelection(target); + } else + { interactions.SetSelection(target); + } } interactions.For(FileBrowserInteractionIds.C_AREA, interactions.selection.selectedTarget).Focus(); if (navigation.activate) + { m_pendingActivation = m_keyboardFocus; + } } if (navigation.cancel) + { m_keyboardFocus = null; + } } private void RequestEntryKeyboardFocus(AssetFileEntry entry) { if (entry.identity.runtimeIdentity == m_drawKeyboardFocus && Ui.IsWindowFocused(ImGuiFocusedFlags.ChildWindows)) + { Ui.FocusNextItem(); + } } private void DrawBreadcrumbBar( @@ -190,9 +221,13 @@ float height if (EditorUI.current.widgets.ClickableText($"crumb_{part.root}_{part.directory}", part.label, itemSize)) { if (string.IsNullOrEmpty(part.directory)) + { m_navigation.NavigateToRoot(context, part.root); + } else + { m_navigation.NavigateTo(context, part.directory); + } } } @@ -223,13 +258,17 @@ private static float CalculateBreadcrumbContentWidth( Vector2 framePadding ) { if (parts.Count == 0) + { return 0f; + } float width = 0f; float separatorWidth = Ui.MeasureText(">").X; for (int i = 0; i < parts.Count; i++) { if (i > 0) + { width += separatorWidth + CurrentBrowserStyle.breadcrumbSpacing * 2f; + } width += Ui.MeasureText(parts[i].label).X + framePadding.X * 2f; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs index 7e92fc74d..6f3bc355b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs @@ -1,6 +1,3 @@ -using Inno.Core.Identity; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.IO; @@ -8,12 +5,17 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; namespace Inno.Editor.Panel.FileBrowser; + /// /// Asset browser panel with a tree pane and filtered table view. /// @@ -46,6 +48,7 @@ internal sealed partial class FileBrowserPanel : EditorPanel private float m_gridScale; private float m_listNameSeparatorPosition; private float m_listTypeSeparatorPosition; + private enum ViewMode { List, @@ -86,7 +89,9 @@ protected override void Capture(EditorState state) protected override void Restore(EditorState state) { if (Enum.TryParse(state.Get("viewMode", string.Empty), out ViewMode viewMode)) + { m_viewMode = viewMode; + } if (Enum.TryParse(state.Get("entryTypeFilter", string.Empty), out FileBrowserEntryTypeFilter typeFilter)) { m_entryTypeFilter = typeFilter; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs index adfd71578..d4e9f63a4 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs @@ -1,13 +1,14 @@ +using System; +using Inno.Assets.Pipeline; using Inno.Core.Identity; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; -using System; -using Inno.Assets.Pipeline; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; + internal enum FileBrowserPresentation { Tree, @@ -21,12 +22,16 @@ internal sealed class FileBrowserRename(AssetBrowserModule assets) private FileBrowserPresentation m_lastPresentation = FileBrowserPresentation.List; private FileBrowserPresentation m_activePresentation; internal RuntimeIdentity? activeTarget => m_activeTarget; + internal void Update(EditorContext context) { AssetFileEntry? target = assets.edits.interactions.selection.selectedTarget as AssetFileEntry; - bool isActive = target is not null && assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, target).IsActive(FileBrowserInteractionIds.C_RENAME); + bool isActive = target is not null + && assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, target).IsActive(FileBrowserInteractionIds.C_RENAME); if (isActive && target?.identity.runtimeIdentity == m_activeTarget) + { return; + } m_activeTarget = isActive ? target!.identity.runtimeIdentity : null; m_activePresentation = m_lastPresentation; } @@ -43,12 +48,8 @@ FileBrowserPresentation presentation ) { Update(context); return ResolveTarget() is AssetFileEntry target - && m_activePresentation == presentation - && string.Equals( - target.assetPath.ToString(), - relativePath, - StringComparison.Ordinal - ); + && m_activePresentation == presentation + && string.Equals(target.assetPath.ToString(), relativePath, StringComparison.Ordinal); } internal void Draw( @@ -60,19 +61,19 @@ internal void Draw( float rowHeight ) { if (!IsEditing(context, relativePath, presentation) || m_activeTarget is null) + { return; - _ = assets.edits.interactions.For( - FileBrowserInteractionIds.C_AREA, - ResolveTarget() - ).Present( + } + _ = assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, ResolveTarget()).Present( FileBrowserInteractionIds.C_RENAME, new InlineRenamePresentation(id, MathF.Max(1f, width), MathF.Max(1f, rowHeight)) ); } - private AssetFileEntry? ResolveTarget() => m_activeTarget is RuntimeIdentity identity - && assets.edits.interactions.TryResolveIdentity( - identity, - out IdentityObject? target - ) ? target as AssetFileEntry : null; + private AssetFileEntry? ResolveTarget() + => m_activeTarget is RuntimeIdentity identity + && assets.edits.interactions.TryResolveIdentity( + identity, + out IdentityObject? target + ) ? target as AssetFileEntry : null; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Navigation.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Navigation.cs index 3bc7c020b..aa102ce2f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Navigation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Navigation.cs @@ -3,12 +3,13 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Identity; -using Inno.Editor.Assets.ImGui; using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; @@ -32,16 +33,20 @@ internal void CompleteNavigation(EditorContext context) { EditorInteractions interactions = m_assets.edits.interactions; if (m_pendingSelection is RuntimeIdentity pending - && interactions.TryResolveIdentity(pending, out IdentityObject? resolved) && resolved is AssetFileEntry entry) - { + && interactions.TryResolveIdentity(pending, out IdentityObject? resolved) && resolved is AssetFileEntry entry + ) { if (m_pendingActivation) { if (!interactions.selection.Contains(entry)) + { interactions.SetSelection(entry); + } m_navigation.OpenEntry(context, entry, this); } else + { EditorUiSession.current.widgets.SelectTarget(interactions, entry, m_visibleSelection); + } m_keyboardFocus = pending; m_rootFocused = false; interactions.For(FileBrowserInteractionIds.C_AREA, entry).Focus(); @@ -66,11 +71,20 @@ internal void CompleteNavigation(EditorContext context) break; } if (row.identity is not null && row.identity == selectedIdentity) + { selectedIndex = index; + } } if (focus < 0) + { focus = selectedIndex; - ListNavigationResult navigation = EditorUiSession.current.widgets.NavigateList(interactions, m_navigationRows.Count, focus, m_keyboardPageSize); + } + ListNavigationResult navigation = EditorUiSession.current.widgets.NavigateList( + interactions, + m_navigationRows.Count, + focus, + m_keyboardPageSize + ); if (navigation.focusedIndex >= 0 && (navigation.focusChanged || navigation.selectionRequested || navigation.activate)) { TreeNavigationRow row = m_navigationRows[navigation.focusedIndex]; @@ -82,19 +96,27 @@ internal void CompleteNavigation(EditorContext context) m_requestedRootFocus = m_rootFocused; } if (row.identity is RuntimeIdentity identity - && interactions.TryResolveIdentity(identity, out IdentityObject? target) && target is AssetFileEntry asset) - { + && interactions.TryResolveIdentity(identity, out IdentityObject? target) && target is AssetFileEntry asset + ) { if (navigation.selectionRequested) { if (navigation.extendRange) + { interactions.SelectRange(m_visibleSelection, asset, navigation.additive); + } else if (navigation.toggle) + { interactions.ToggleSelection(asset); + } else + { interactions.SetSelection(asset); + } } if (navigation.activate) + { m_navigation.OpenEntry(context, asset, this); + } } else if (navigation.activate) { @@ -113,7 +135,9 @@ internal void CompleteNavigation(EditorContext context) private void BeginNavigation() { if (Ui.IsWindowFocused()) + { m_rename.MarkInteraction(FileBrowserPresentation.Tree); + } ClearNavigationFrame(); m_drawKeyboardFocus = m_requestedKeyboardFocus; m_drawRootFocus = m_requestedRootFocus; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs index e75b98273..6c9a38a99 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs @@ -7,6 +7,7 @@ using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; + using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; @@ -41,8 +42,10 @@ internal void Draw(EditorContext context) { BrowserTreeRow row = m_rows[index]; if (row.identity is { } identity && (identity == dragging || identity == editing || identity == m_drawKeyboardFocus) - || row.isRoot && m_drawRootFocus) + || row.isRoot && m_drawRootFocus + ) { preserved[preservedCount++] = index; + } } EditorUI.current.widgets.ClippedRows(m_rows.Count, -1f, (tree: this, context), static ( state, @@ -51,7 +54,9 @@ internal void Draw(EditorContext context) ) => { for (int index = start; index < end; index++) + { state.tree.DrawRow(state.context, state.tree.m_rows[index]); + } }, preserved[..preservedCount]); } @@ -60,44 +65,73 @@ private void RefreshRows() var widgets = EditorUI.current.widgets; AssetPipeline pipeline = m_assets.edits.pipeline; if (!m_rootOpenRequest && !m_currentDirectoryOpenRequest && m_rowsRoot == m_assets.browser.root - && m_sourceRevision == pipeline.revision && m_expansionRevision == widgets.treeExpansionRevision) + && m_sourceRevision == pipeline.revision && m_expansionRevision == widgets.treeExpansionRevision + ) { return; + } var rows = new List(); var pending = new Stack<(string path, string label, bool root, int depth)>(); if (m_assets.browser.root == AssetBrowserRoot.Assets) + { pending.Push((string.Empty, "Assets", true, 0)); + } else { const string rootId = "tree_virtual_plugins"; if (m_rootOpenRequest || m_currentDirectoryOpenRequest) + { widgets.SetTreeNodeOpen(rootId, true); + } rows.Add(new(string.Empty, "Plugins", rootId, 0, true, true, false, null)); if (widgets.IsTreeNodeOpen(rootId)) { AssetSourceMount[] mounts = pipeline.sourceMounts.Where(mount => m_assets.edits.IsPluginSource(mount.id)) - .OrderBy(static mount => mount.id.value, StringComparer.OrdinalIgnoreCase).ToArray(); + .OrderBy(static mount => mount.id.value, StringComparer.OrdinalIgnoreCase) + .ToArray(); for (int index = mounts.Length - 1; index >= 0; index--) + { pending.Push((new AssetPath(mounts[index].id, string.Empty).ToString(), mounts[index].id.value, false, 1)); + } } } while (pending.TryPop(out var next)) { AssetFileEntry? entry = null; if (!next.root && (!pipeline.TryGetFileSystemEntry(AssetPath.Parse(next.path), out entry) || entry is null)) + { continue; + } bool directory = next.root || entry!.isDirectory; - IReadOnlyList children = directory ? m_data.SortTreeEntries(m_data.GetVisibleChildren(next.path)) : Array.Empty(); + IReadOnlyList children = directory + ? m_data.SortTreeEntries(m_data.GetVisibleChildren(next.path)) + : Array.Empty(); string id = next.root ? "tree_root_" + next.path : "tree_" + next.path; if (ShouldOpenTreeEntry(next.path, next.root, directory)) + { widgets.SetTreeNodeOpen(id, true); + } RuntimeIdentity? identity = next.root ? null : entry!.identity.runtimeIdentity ?? throw new InvalidOperationException("A visible asset tree entry requires a registered identity."); - rows.Add(new(next.path, next.label, id, next.depth, next.root, false, - !directory || !next.root && children.Count == 0, identity)); + rows.Add( + new( + next.path, + next.label, + id, + next.depth, + next.root, + false, + !directory || !next.root && children.Count == 0, + identity + ) + ); if (!directory || !widgets.IsTreeNodeOpen(id)) + { continue; + } for (int index = children.Count - 1; index >= 0; index--) + { pending.Push((children[index].assetPath.ToString(), children[index].name, false, next.depth + 1)); + } } m_rows.Clear(); m_rows.AddRange(rows); @@ -107,7 +141,9 @@ private void RefreshRows() { m_navigationRows.Add(new TreeNavigationRow(row.identity)); if (row.identity is RuntimeIdentity identity) + { m_visibleSelection.Add(identity); + } } m_rowsRoot = m_assets.browser.root; m_sourceRevision = pipeline.revision; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs index 568aa0283..55b48e3f5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs @@ -1,19 +1,22 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Core.Identity; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal sealed partial class FileBrowserTree { private readonly FileBrowserData m_data; @@ -26,6 +29,7 @@ internal sealed partial class FileBrowserTree private bool m_currentDirectoryOpenRequest; private string m_currentDirectoryOpenTarget = string.Empty; private string? m_lastCurrentDirectoryOpenTarget; + internal FileBrowserTree( FileBrowserData data, FileBrowserNavigation navigation, @@ -50,26 +54,36 @@ BrowserTreeRow row if (row.identity is { } identity) { if (!m_assets.edits.interactions.TryResolveIdentity(identity, out Inno.Core.Identity.IdentityObject? resolved) - || resolved is not AssetFileEntry current) - { + || resolved is not AssetFileEntry current + ) { Ui.Dummy(new(1f, Ui.GetFrameHeight())); return; } entry = current; } bool selected = entry is not null && m_assets.edits.interactions.selection.Contains(entry); - bool currentDirectory = row.virtualRoot ? string.IsNullOrEmpty(m_assets.browser.currentDirectory) + bool currentDirectory = row.virtualRoot + ? string.IsNullOrEmpty(m_assets.browser.currentDirectory) : (entry?.isDirectory ?? row.isRoot) && string.Equals(m_assets.browser.currentDirectory, row.path, StringComparison.Ordinal) - && (m_assets.browser.root == AssetBrowserRoot.Assets) == (AssetPath.Parse(row.path).source == AssetSourceId.project); + && (m_assets.browser.root == AssetBrowserRoot.Assets) == (AssetPath.Parse(row.path).source == AssetSourceId.project); string icon = entry is { isDirectory: false } ? m_assets.GetIcon(entry) : m_assets.folderIcon; bool editing = !row.isRoot && m_rename.IsEditing(context, row.path, FileBrowserPresentation.Tree); TreeNodeResult result = EditorUI.current.widgets.TreeNode( row.nodeId, drawContext => DrawRowContent(context, row.nodeId, row.path, row.label, icon, currentDirectory, editing, drawContext.rowHeight), - new TreeNodeOptions { depth = row.depth, selected = selected, isLeaf = row.isLeaf, - requestFocus = RequestsKeyboardFocus(entry, row.isRoot), keepContentActive = editing }); + new TreeNodeOptions + { + depth = row.depth, + selected = selected, + isLeaf = row.isLeaf, + requestFocus = RequestsKeyboardFocus(entry, row.isRoot), + keepContentActive = editing + } + ); if (!result.isSubmitted) + { return; + } if (entry is not null && result.isDoubleClicked) { m_rename.MarkInteraction(FileBrowserPresentation.Tree); @@ -82,13 +96,17 @@ BrowserTreeRow row m_pendingSelection = entry.identity.runtimeIdentity; } else if (row.isRoot && (result.isClicked || result.isDoubleClicked)) + { m_pendingRootNavigation = true; + } if (entry is not null && !editing) { m_dragDrop.DrawAssetSource(context, entry); m_contextMenu.DrawEntry(context, "##asset_tree_context_" + row.path, row.path, FileBrowserPresentation.Tree); if (entry.isDirectory && !entry.isReadOnly) + { m_dragDrop.DrawDirectoryTarget(context, row.path); + } } else if (row.isRoot && !row.virtualRoot) { @@ -138,6 +156,7 @@ internal void ClearOpenRequests() } internal void RequestOpenRoot() => m_rootOpenRequest = true; + internal void RequestOpenTreeToPath(string path) { string normalizedPath = NormalizePath(path); @@ -153,7 +172,9 @@ private bool ShouldOpenTreeEntry( bool isDirectory ) { if (!isDirectory) + { return false; + } if (isRoot) { if (string.IsNullOrEmpty(relativePath)) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs index 72d39922e..f9b130296 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs @@ -1,6 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Collections.Generic; using System.Globalization; @@ -8,11 +5,16 @@ using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal static class FileBrowserUtility { internal static AssetBrowserStyle CurrentBrowserStyle => new(EditorUI.current.widgets.style); @@ -22,6 +24,7 @@ internal readonly record struct BreadcrumbPart( AssetBrowserRoot root, string directory ); + internal static void PushBrowserStyle() { Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.contentText); @@ -60,15 +63,20 @@ internal static bool IsDirectoryPath( AssetPipeline assets, string relativePath ) => assets.TryGetFileSystemEntry(AssetPath.Parse(relativePath), out AssetFileEntry entry) && entry.isDirectory; + internal static string GetDirectoryLabel( AssetBrowserRoot root, string relativePath ) { if (root == AssetBrowserRoot.Plugins && string.IsNullOrEmpty(relativePath)) + { return "Plugins"; + } AssetPath path = AssetPath.Parse(NormalizePath(relativePath)); if (string.IsNullOrEmpty(path.localPath)) + { return GetSourceRootLabel(path.source); + } string name = Path.GetFileName(path.localPath); return string.IsNullOrEmpty(name) ? GetSourceRootLabel(path.source) : name; } @@ -82,11 +90,17 @@ string currentDirectory string directory = GetLocalParent(entryPath.localPath); string result; if (entryPath.source != current.source) + { result = FormatSourcePath(entryPath.source, directory); + } else if (string.Equals(directory, current.localPath, StringComparison.Ordinal)) + { result = "~"; + } else if (string.IsNullOrEmpty(current.localPath)) + { result = string.IsNullOrEmpty(directory) ? "~" : $"~/{directory}"; + } else { string prefix = current.localPath + "/"; @@ -107,9 +121,13 @@ string currentDirectory internal static string GetTypeText(AssetFileEntry entry) { if (entry.isDirectory && AssetSample.HasSampleDirectoryName(entry.assetPath)) + { return AssetSample.fileType.TrimStart('.').ToUpperInvariant(); + } if (entry.isDirectory) + { return "FOLDER"; + } string extension = string.IsNullOrEmpty(entry.extension) ? Path.GetExtension(entry.assetPath.localPath) : entry.extension; return string.IsNullOrEmpty(extension) ? "FILE" : extension.TrimStart('.').ToUpperInvariant(); } @@ -119,7 +137,9 @@ internal static IReadOnlyList BuildBreadcrumbParts( string relativePath ) { if (root == AssetBrowserRoot.Plugins && string.IsNullOrEmpty(relativePath)) + { return[new BreadcrumbPart("Plugins", AssetBrowserRoot.Plugins, string.Empty)]; + } AssetPath sourcePath = AssetPath.Parse(NormalizePath(relativePath)); string sourceRoot = new AssetPath(sourcePath.source, string.Empty).ToString(); var parts = new List(); @@ -134,7 +154,9 @@ string relativePath } if (string.IsNullOrEmpty(sourcePath.localPath)) + { return parts; + } string[] segments = sourcePath.localPath.Split('/', StringSplitOptions.RemoveEmptyEntries); string path = string.Empty; for (int i = 0; i < segments.Length; i++) @@ -150,7 +172,10 @@ internal static bool IsReadOnlyLocation( AssetPipeline assets, AssetBrowserState browser ) => browser.root == AssetBrowserRoot.Plugins || IsReadOnlySource(assets, browser.currentDirectory); - internal static string NormalizePath(string? path) => AssetPath.Parse(string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim()).ToString(); + + internal static string NormalizePath(string? path) + => AssetPath.Parse(string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim()).ToString(); + internal static string GetParentDirectory(string relativePath) { AssetPath path = AssetPath.Parse(NormalizePath(relativePath)); @@ -166,7 +191,9 @@ string relativePath { AssetSourceMount mount = assets.sourceMounts[i]; if (mount.id == source) + { return mount.isReadOnly; + } } return true; @@ -189,7 +216,9 @@ internal static string GetEditableName( bool isDirectory ) { if (isDirectory) + { return name; + } string extension = Path.GetExtension(name); return string.IsNullOrEmpty(extension) ? name : name[..^extension.Length]; } @@ -214,6 +243,7 @@ internal static string ComposeRenamedEntryName( string editedName, bool isDirectory ) => isDirectory ? editedName : editedName + Path.GetExtension(sourcePath); + internal static string[] FitTextToLines( string text, float maxWidth, @@ -221,11 +251,15 @@ int maxLines ) { ArgumentOutOfRangeException.ThrowIfLessThan(maxLines, 1); if (string.IsNullOrEmpty(text)) + { return[string.Empty]; + } List elements = []; TextElementEnumerator enumerator = StringInfo.GetTextElementEnumerator(text); while (enumerator.MoveNext()) + { elements.Add(enumerator.GetTextElement()); + } List lines = new(maxLines); int offset = 0; for (int lineIndex = 0; lineIndex < maxLines && offset < elements.Count; lineIndex++) @@ -245,7 +279,9 @@ int maxLines { string next = candidate + elements[offset + count]; if (Ui.MeasureText(next + suffix).X > maxWidth) + { break; + } candidate = next; count++; } @@ -271,18 +307,20 @@ string path AssetPath ancestor = AssetPath.Parse(NormalizePath(candidateAncestor)); AssetPath descendant = AssetPath.Parse(NormalizePath(path)); if (ancestor.source != descendant.source) + { return false; + } if (ancestor.localPath.Length == 0 || string.Equals(ancestor.localPath, descendant.localPath, StringComparison.Ordinal)) + { return true; + } return descendant.localPath.Length > ancestor.localPath.Length - && descendant.localPath.StartsWith( - ancestor.localPath, - StringComparison.Ordinal - ) - && descendant.localPath[ancestor.localPath.Length] == '/'; + && descendant.localPath.StartsWith(ancestor.localPath, StringComparison.Ordinal) + && descendant.localPath[ancestor.localPath.Length] == '/'; } private static string GetSourceRootLabel(AssetSourceId source) => source == AssetSourceId.project ? "Assets" : source.value; + private static string FormatSourcePath( AssetSourceId source, string localPath diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/FileBrowserInteractionIds.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/FileBrowserInteractionIds.cs index 9a7526c75..777d8a3ae 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/FileBrowserInteractionIds.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/FileBrowserInteractionIds.cs @@ -2,6 +2,7 @@ using Inno.Editor.Assets.ImGui; namespace Inno.Editor.Panel.FileBrowser; + internal static class FileBrowserInteractionIds { internal const string C_AREA = "panel/asset.file-browser"; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs index ffb94a2c9..e045677f6 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs @@ -9,6 +9,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; + [EditorAction(FileBrowserInteractionIds.C_CREATE_ASSET, FileBrowserInteractionIds.C_AREA)] internal sealed class CreateAssetCommand(AssetBrowserModule assets) : EditorAction { @@ -21,10 +22,12 @@ internal sealed class CreateAssetCommand(AssetBrowserModule assets) : EditorActi /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => assets.edits.CanCreateAsset( - context.target, - context.argument - ) ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => assets.edits.CanCreateAsset( + context.target, + context.argument + ) ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -73,11 +76,18 @@ EditorMenuBuilder builder { string group = "Create/" + string.Join('/', segments.Take(depth + 1)); if (declaredGroups.Add(group)) + { builder.AddGroup(group, declaration.itemOrder); + } } } - builder.Add("Create/" + declaration.menuPath, FileBrowserInteractionIds.C_CREATE_ASSET, declaration.itemOrder, argument: declaration.id); + builder.Add( + "Create/" + declaration.menuPath, + FileBrowserInteractionIds.C_CREATE_ASSET, + declaration.itemOrder, + argument: declaration.id + ); } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetFolderCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetFolderCommand.cs index c63999f5d..730eb2561 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetFolderCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetFolderCommand.cs @@ -1,12 +1,13 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; + [EditorAction(FileBrowserInteractionIds.C_CREATE_FOLDER, FileBrowserInteractionIds.C_AREA)] [EditorMenu(FileBrowserInteractionIds.C_AREA, "Create/Folder", order: 100)] internal sealed class CreateAssetFolderCommand(AssetBrowserModule assets) : EditorAction @@ -20,8 +21,10 @@ internal sealed class CreateAssetFolderCommand(AssetBrowserModule assets) : Edit /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => assets.edits.pipeline.isInitialized - && IsWritableDirectory(context.target) ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => assets.edits.pipeline.isInitialized + && IsWritableDirectory(context.target) ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -40,19 +43,20 @@ private static string Combine( string parent, string name ) => string.IsNullOrEmpty(parent) ? name : $"{parent}/{name}"; + private static string Normalize(string? path) => string.IsNullOrWhiteSpace(path) ? string.Empty : path.Replace('\\', '/').Trim('/'); + private bool IsWritableDirectory(string relativePath) { string normalized = Normalize(relativePath); AssetSourceId source = AssetPath.Parse(normalized).source; AssetSourceMount? mount = assets.edits.pipeline.sourceMounts.FirstOrDefault(candidate => candidate.id == source); if (mount is null || mount.isReadOnly) + { return false; + } return string.IsNullOrEmpty(AssetPath.Parse(normalized).localPath) - || assets.edits.pipeline.TryGetFileSystemEntry( - AssetPath.Parse(normalized), - out AssetFileEntry entry - ) - && entry.isDirectory; + || assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(normalized), out AssetFileEntry entry) + && entry.isDirectory; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/DeleteAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/DeleteAssetCommand.cs index eff199328..a07816e0b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/DeleteAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/DeleteAssetCommand.cs @@ -1,11 +1,12 @@ using System.Collections.Generic; +using Inno.Assets.Pipeline; +using Inno.Core.Input; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; -using Inno.Assets.Pipeline; using Inno.Editor.Interactions; -using Inno.Core.Input; namespace Inno.Editor.Panel.FileBrowser; + [EditorAction(FileBrowserInteractionIds.C_DELETE, priority: 100)] [EditorMenu(FileBrowserInteractionIds.C_AREA, "Delete", order: 200)] [EditorShortcut(FileBrowserInteractionIds.C_AREA, KeyCode.Delete)] @@ -41,7 +42,9 @@ protected override void Execute(EditorActionContext context) private static IReadOnlyList Targets(EditorActionContext context) { if (!context.interactions.selection.Contains(context.target)) + { return[context.target]; + } var values = new List(); context.interactions.selection.CopyTargets(values); return values.Count == context.interactions.selection.count ? values : []; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/ImportAssetSampleCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/ImportAssetSampleCommand.cs index fc4f2cc11..d7f66695d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/ImportAssetSampleCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/ImportAssetSampleCommand.cs @@ -1,11 +1,12 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; + [EditorAction(FileBrowserInteractionIds.C_IMPORT_SAMPLE, FileBrowserInteractionIds.C_AREA)] [EditorMenu(FileBrowserInteractionIds.C_AREA, "Import Sample", order: 120)] internal sealed class ImportAssetSampleCommand( @@ -25,9 +26,13 @@ AssetSampleImportModule imports protected override EditorActionState Query(EditorActionContext context) { if (!context.target.isSample) + { return EditorActionState.hidden; + } if (!imports.canImport) + { return EditorActionState.disabled; + } try { AssetPath target = AssetPath.Project(AssetSample.GetImportName(context.target.assetPath)); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs index ac60f5765..46529a161 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs @@ -1,10 +1,11 @@ using System.Collections.Generic; +using Inno.Assets.Pipeline; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; -using Inno.Assets.Pipeline; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; + /// /// Moves directory drag payloads into File Browser directory targets. /// @@ -23,10 +24,12 @@ internal sealed class MoveAssetEntryDropHandler(AssetBrowserModule assets) : Edi /// /// The context that supplies state and services for this operation. /// - protected override EditorDropStatus Query(EditorDropContext context) => assets.edits.CanMoveSelection( - SelectedSources(context), - context.target - ) ? EditorDropStatus.Accept() : EditorDropStatus.rejected; + protected override EditorDropStatus Query(EditorDropContext context) + => assets.edits.CanMoveSelection( + SelectedSources(context), + context.target + ) ? EditorDropStatus.Accept() : EditorDropStatus.rejected; + /// /// Validates and applies the current editor drag-and-drop interaction atomically. /// @@ -39,7 +42,9 @@ protected override EditorDropStatus Query(EditorDropContext context) { if (!Query(context).canDrop) + { return EditorDropResult.rejected; + } assets.edits.MoveSelection(SelectedSources(context), context.target); return EditorDropResult.Accepted(context.source, context.target); } @@ -47,7 +52,9 @@ protected override EditorDropResult Drop(EditorDropContext SelectedSources(EditorDropContext context) { if (!context.interactions.selection.Contains(context.source)) + { return[context.source]; + } var values = new List(); context.interactions.selection.CopyTargets(values); return values.Count == context.interactions.selection.count ? values : []; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/OpenAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/OpenAssetCommand.cs index 98c547ef0..1c9652a5e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/OpenAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/OpenAssetCommand.cs @@ -1,10 +1,11 @@ -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; + [EditorAction(FileBrowserInteractionIds.C_OPEN, FileBrowserInteractionIds.C_AREA, priority: 100)] internal sealed class OpenAssetCommand(AssetBrowserModule assets) : EditorAction { @@ -20,7 +21,9 @@ internal sealed class OpenAssetCommand(AssetBrowserModule assets) : EditorAction protected override EditorActionState Query(EditorActionContext context) { if (!TryGetAssetContext(context, out AssetEditorContext? assetContext) || assetContext is null) + { return EditorActionState.hidden; + } return assetContext.isDirectory ? EditorActionState.hidden : EditorActionState.enabled; } @@ -33,20 +36,18 @@ protected override EditorActionState Query(EditorActionContext c protected override void Execute(EditorActionContext context) { if (!TryGetAssetContext(context, out AssetEditorContext? assetContext) || assetContext is null) + { return; + } if (assets.edits.pipeline.TryLoad( AssetPath.Parse(assetContext.relativePath), out AssetObject? asset ) && asset is not null - && context.interactions.For( - FileBrowserInteractionIds.C_AREA, - asset - ).Execute( - FileBrowserInteractionIds.C_OPEN, - assetContext.relativePath - )) - { + && context.interactions + .For(FileBrowserInteractionIds.C_AREA, asset) + .Execute(FileBrowserInteractionIds.C_OPEN, assetContext.relativePath) + ) { return; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/RenameAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/RenameAssetCommand.cs index 0eeae9549..0fc3acdc8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/RenameAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/RenameAssetCommand.cs @@ -1,15 +1,18 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using System; using Inno.Assets.Pipeline; using Inno.Core.Input; using Inno.Core.Logging; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; + using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; + namespace Inno.Editor.Panel.FileBrowser; + [EditorAction(FileBrowserInteractionIds.C_RENAME, priority: 100)] [EditorMenu(FileBrowserInteractionIds.C_AREA, "Rename", order: 100)] [EditorShortcut(FileBrowserInteractionIds.C_AREA, KeyCode.F2)] @@ -21,6 +24,7 @@ LogRouter logs private readonly Logger m_log = (logs ?? throw new ArgumentNullException(nameof(logs))).CreateLogger(); private string m_buffer = string.Empty; private bool m_requestFocus; + /// /// Evaluates whether the requested change can be applied to the current generation. /// @@ -30,11 +34,10 @@ LogRouter logs /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => !context.target.isReadOnly - && TryGetAssetContext( - context, - out _ - ) ? EditorActionState.enabled : EditorActionState.hidden; + protected override EditorActionState Query(EditorActionContext context) + => !context.target.isReadOnly + && TryGetAssetContext(context, out _) ? EditorActionState.enabled : EditorActionState.hidden; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -44,7 +47,9 @@ out _ protected override void Execute(EditorActionContext context) { if (!TryGetAssetContext(context, out AssetEditorContext? assetContext) || assetContext is null) + { return; + } Activate(context); m_buffer = GetEditableName(assetContext.name, assetContext.isDirectory); m_requestFocus = true; @@ -62,7 +67,9 @@ protected override void Execute(EditorActionContext context) protected override bool Present(EditorActionContext context) { if (!TryResolveAsset(out AssetEditorContext? asset) || asset is null) + { return false; + } InlineRenamePresentation presentation = context.argument; InlineRenameResult result = EditorUI.current.widgets.InlineRename( presentation.id, @@ -85,7 +92,9 @@ protected override bool Present(EditorActionContext protected override void OnCompleted() => ClearState(); + /// /// Cancels the interaction without committing its pending value. /// protected override void OnCancelled() => ClearState(); + /// /// Cancels pending presentation state when its editor surface disappears. /// protected override void OnPresentationLost() => _ = TryCommit(keepActiveWhenInvalid: false); + private bool TryCommit(bool keepActiveWhenInvalid) { if (!TryResolveAsset(out AssetEditorContext? asset) || asset is null) @@ -115,9 +127,13 @@ private bool TryCommit(bool keepActiveWhenInvalid) { m_log.Write(LogLevel.Warn, "Asset rename was rejected: {0}", [validation.message]); if (keepActiveWhenInvalid) + { m_requestFocus = true; + } else + { Cancel(); + } return false; } @@ -130,7 +146,9 @@ private bool TryCommit(bool keepActiveWhenInvalid) private bool TryResolveAsset(out AssetEditorContext? asset) { asset = null; - return activeTarget is AssetFileEntry entry && activeEditorContext is { } editor && assets.edits.TryCreateContext(editor, entry.assetPath.ToString(), out asset); + return activeTarget is AssetFileEntry entry + && activeEditorContext is { } editor + && assets.edits.TryCreateContext(editor, entry.assetPath.ToString(), out asset); } private void ClearState() diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs index f7f5ed54a..5bf4b2ae2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs @@ -1,19 +1,24 @@ using System.Numerics; +using Inno.Editor.Assets; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; -using Inno.Editor.Assets; + namespace Inno.Editor.Panel.FileBrowser; + [EditorModal("asset-sample-import.progress", "Importing Sample", order: 110)] internal sealed class AssetSampleImportModal(AssetSampleImportModule imports) : EditorModal { private DialogPresentation m_content; private DialogLayout m_layout; private long m_operation; + /// public override bool isVisible => imports.isBusy; + /// public override bool allowScrolling => false; + /// protected override Vector2? OnPrepare( EditorContext context, @@ -21,14 +26,23 @@ Vector2 availableContentSize ) { var snapshot = imports.progress; m_operation = snapshot.operationId; - m_content = new(snapshot.status, snapshot.fraction, actionLabel: "Cancel", actionEnabled: !snapshot.cancellationRequested, cancelOnEscape: true); + m_content = new( + snapshot.status, + snapshot.fraction, + actionLabel: "Cancel", + actionEnabled: !snapshot.cancellationRequested, + cancelOnEscape: true + ); m_layout = EditorUiSession.current.widgets.MeasureDialog(m_content, availableContentSize); return m_layout.size; } + /// protected override void OnDraw(EditorContext context) { if (EditorUiSession.current.widgets.DrawDialog(m_content, m_layout)) + { imports.Cancel(m_operation); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GamePresentationSetting.cs b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GamePresentationSetting.cs index ba83d4480..1367a9919 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GamePresentationSetting.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GamePresentationSetting.cs @@ -2,9 +2,11 @@ using Inno.Core.Settings; using Inno.Editor.Settings; using Inno.Runtime; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.GameView; + [ProjectSettingPath("Project/Player/Presentation")] internal sealed class GamePresentationSetting : ProjectSettingEditor { @@ -12,6 +14,7 @@ internal sealed class GamePresentationSetting : ProjectSettingEditor public override string section => "Display"; + /// /// Gets the explanation shared by Game View and deployed Player presentation. /// @@ -27,16 +30,22 @@ protected override void OnDraw(GamePresentationSettings setting) { bool preserve = setting.preserveAspectRatio; if (Ui.Checkbox("Preserve Aspect Ratio", ref preserve)) + { setting.preserveAspectRatio = preserve; + } int width = Math.Max(1, setting.referenceWidth); int height = Math.Max(1, setting.referenceHeight); Ui.BeginDisabled(!preserve); try { if (Ui.InputInt("Reference Width", ref width, 1, 100, 0)) + { setting.referenceWidth = Math.Max(1, width); + } if (Ui.InputInt("Reference Height", ref height, 1, 100, 0)) + { setting.referenceHeight = Math.Max(1, height); + } } finally { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewBackgroundSetting.cs b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewBackgroundSetting.cs index 6a51af7ee..c43cd8d17 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewBackgroundSetting.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewBackgroundSetting.cs @@ -1,22 +1,27 @@ using System.Numerics; using Inno.Editor.ImGui; using Inno.Editor.Settings; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.GameView; + [EditorSettingPath(C_PATH)] internal sealed class GameViewBackgroundSetting : EditorSetting { internal const string C_PATH = "Editor/Appearance/Viewports/Game Background"; private static readonly float[] S_DEFAULT = [0.035f, 0.04f, 0.05f, EditorPalette.opacityOpaque]; + /// /// Gets a new value initialized to this setting's canonical default state. /// public override EditorSettingObject defaultValue => CreateDefault(); + /// /// Gets the presentation section that groups this setting. /// public override string section => "Viewport Backgrounds"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -33,10 +38,13 @@ protected override void OnDraw(EditorSettingObject setting) Vector4 value = ReadVector(setting); Ui.SetNextItemWidth(-1f); if (Ui.ColorEditLinear4("##game_view_background", ref value)) + { setting.SetAsSingleArray("value", [value.X, value.Y, value.Z, value.W]); + } } internal static Vector4 Read(EditorSettings settings) => ReadVector(settings.Get(C_PATH)); + private static EditorSettingObject CreateDefault() { var result = new EditorSettingObject(); @@ -47,6 +55,8 @@ private static EditorSettingObject CreateDefault() private static Vector4 ReadVector(EditorSettingObject setting) { float[] values = setting.GetAsSingleArray("value", S_DEFAULT); - return values.Length == 4 ? new Vector4(values[0], values[1], values[2], values[3]) : new Vector4(S_DEFAULT[0], S_DEFAULT[1], S_DEFAULT[2], S_DEFAULT[3]); + return values.Length == 4 + ? new Vector4(values[0], values[1], values[2], values[3]) + : new Vector4(S_DEFAULT[0], S_DEFAULT[1], S_DEFAULT[2], S_DEFAULT[3]); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs index 00544e39b..11bec9a02 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs @@ -1,22 +1,24 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.References; using System; using System.Collections.Generic; using System.Numerics; -using Inno.Core.Settings; using Inno.Core.Input; +using Inno.Core.Settings; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.PlayMode; using Inno.Editor.Rendering; using Inno.Editor.Scene; using Inno.Editor.Settings; +using Inno.References; using Inno.Rendering; +using Inno.Rendering.Runtime; using Inno.Runtime; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; -using Inno.Rendering.Runtime; namespace Inno.Editor.Panel.GameView; + /// /// Presents the active Plugin provider for the open Game viewport purpose. /// @@ -38,6 +40,7 @@ internal sealed class GameViewPanel : EditorPanel private GamePresentationSettings m_presentation = new(); private long m_presentationRevision = -1; private bool m_leftPointerActive; + internal GameViewPanel( EditorRenderingModule rendering, IEditorGameScenePresentation scenePresentation, @@ -60,6 +63,7 @@ ProjectSettingsStore projectSettings /// Gets whether use window padding is enabled for this implementation. /// public override bool useWindowPadding => false; + /// /// Gets whether allow scrolling is enabled for this implementation. /// @@ -77,15 +81,22 @@ protected override void OnDraw(EditorContext context) _ = context; Vector2 available = Ui.GetContentRegionAvailable(); if (available.X <= 0f || available.Y <= 0f) + { return; + } RefreshPresentationSettings(); float framebufferScale = Ui.GetInput().framebufferScale.X; if (!float.IsFinite(framebufferScale) || framebufferScale <= 0f) + { framebufferScale = 1f; + } GameViewportLayout layout = CalculateLayout(available, m_presentation, framebufferScale); m_rendering.SetPresentation( C_VIEWPORT_ID, - new EditorViewportPresentation(new Inno.Core.Mathematics.Color(m_backgroundColor.X, m_backgroundColor.Y, m_backgroundColor.Z, m_backgroundColor.W), framebufferScale) + new EditorViewportPresentation( + new Inno.Core.Mathematics.Color(m_backgroundColor.X, m_backgroundColor.Y, m_backgroundColor.Z, m_backgroundColor.W), + framebufferScale + ) ); m_rendering.SetContentScope(C_VIEWPORT_ID, CreateContentScope()); Vector2 outputOrigin = Ui.GetCursorScreenPosition() + layout.offset; @@ -104,24 +115,40 @@ protected override void OnDraw(EditorContext context) bool leftPressed = acceptsPointer && Ui.IsMouseClicked(ImGuiMouseButton.Left); if (leftPressed) + { m_leftPointerActive = true; + } bool leftReleased = m_leftPointerActive && Ui.IsMouseReleased(ImGuiMouseButton.Left); if (leftReleased || !focused) + { m_leftPointerActive = false; + } var io = Ui.GetInput(); KeyModifier modifiers = KeyModifier.None; if (io.alt) + { modifiers |= KeyModifier.Alt; + } if (io.control) + { modifiers |= KeyModifier.Control; + } if (io.shift) + { modifiers |= KeyModifier.Shift; + } if (io.super) + { modifiers |= KeyModifier.Super; + } m_rendering.SetOutputInput( C_VIEWPORT_ID, - focused ? new RenderOutputInput( - new Inno.Core.Mathematics.Vector2(local.X * layout.pixelWidth / layout.size.X, local.Y * layout.pixelHeight / layout.size.Y), + focused + ? new RenderOutputInput( + new Inno.Core.Mathematics.Vector2( + local.X * layout.pixelWidth / layout.size.X, + local.Y * layout.pixelHeight / layout.size.Y + ), acceptsPointer, acceptsPointer ? new Inno.Core.Mathematics.Vector2(0f, io.wheel) : default, modifiers, @@ -130,7 +157,8 @@ protected override void OnDraw(EditorContext context) leftPressed ? [MouseButton.Left] : [], leftReleased ? [MouseButton.Left] : [], [] - ) : RenderOutputInput.suspended + ) + : RenderOutputInput.suspended ); if (!m_rendering.TrySubmit(S_KIND, C_VIEWPORT_ID, layout.pixelWidth, layout.pixelHeight, out EditorViewportOutput output)) { @@ -186,10 +214,13 @@ protected override void OnDetach(EditorContext context) } private void ApplyEditorSettings(EditorSettings settings) => m_backgroundColor = GameViewBackgroundSetting.Read(settings); + private void RefreshPresentationSettings() { if (m_presentationRevision == m_projectSettings.revision) + { return; + } m_presentation = m_projectSettings.Get(GamePresentationSettings.settingId); m_presentationRevision = m_projectSettings.revision; } @@ -211,6 +242,7 @@ float framebufferScale } private ContentReadScope CreateContentScope() => m_scenePresentation.Capture(); + private void DrawUnavailable( Vector2 size, string message diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateChildGameObjectCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateChildGameObjectCommand.cs index 9a2a62da8..04d981469 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateChildGameObjectCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateChildGameObjectCommand.cs @@ -19,8 +19,8 @@ internal sealed class CreateChildGameObjectCommand(SceneEdits edits) : EditorAct /// protected override EditorActionState Query(EditorActionContext context) => context.target.isRuntimeValid - ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled - : EditorActionState.hidden; + ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateGameObjectCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateGameObjectCommand.cs index e5176f2dd..54c06d88c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateGameObjectCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/CreateGameObjectCommand.cs @@ -19,8 +19,8 @@ internal sealed class CreateGameObjectCommand(SceneEdits edits) : EditorAction protected override EditorActionState Query(EditorActionContext context) => context.target.isLoaded - ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled - : EditorActionState.hidden; + ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/DeleteGameObjectCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/DeleteGameObjectCommand.cs index 1f7a00942..feb0f0926 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/DeleteGameObjectCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/DeleteGameObjectCommand.cs @@ -1,11 +1,12 @@ using System.Collections.Generic; using System.Linq; +using Inno.Core.Input; using Inno.Editor.Interactions; using Inno.Editor.Scene; -using Inno.Core.Input; using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; + [EditorAction(HierarchyInteractionIds.C_DELETE_GAME_OBJECT, priority: 100)] [EditorMenu(HierarchyInteractionIds.C_AREA, "Delete", order: 300)] [EditorShortcut(HierarchyInteractionIds.C_AREA, KeyCode.Delete)] @@ -23,14 +24,16 @@ internal sealed class DeleteGameObjectCommand(SceneEdits edits) : EditorAction context) { if (!context.target.isRuntimeValid) + { return EditorActionState.hidden; + } GameObject[] targets = Targets(context); return targets.Length != 0 - && targets.All(edits.CanEdit) ? EditorActionState.enabled : new EditorActionState( - isVisible: true, - isEnabled: false, - unavailableReason: "Every selected object must belong to an editable scene." - ); + && targets.All(edits.CanEdit) ? EditorActionState.enabled : new EditorActionState( + isVisible: true, + isEnabled: false, + unavailableReason: "Every selected object must belong to an editable scene." + ); } /// @@ -48,7 +51,9 @@ protected override void Execute(EditorActionContext context) private static GameObject[] Targets(EditorActionContext context) { if (!context.interactions.selection.Contains(context.target)) + { return[context.target]; + } var values = new List(); context.interactions.selection.CopyTargets(values); return values.Count == context.interactions.selection.count ? values.ToArray() : []; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchyObjectDropTarget.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchyObjectDropTarget.cs index 6862e08af..07ec32559 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchyObjectDropTarget.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchyObjectDropTarget.cs @@ -1,6 +1,4 @@ - using System; - using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchySceneDropTarget.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchySceneDropTarget.cs index b90b9e523..99fa02365 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchySceneDropTarget.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/HierarchySceneDropTarget.cs @@ -1,6 +1,4 @@ - using System; - using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/InstantiatePrefabAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/InstantiatePrefabAssetCommand.cs index 199fabba1..76bd8e858 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/InstantiatePrefabAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/InstantiatePrefabAssetCommand.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets.Pipeline; using Inno.Editor.Interactions; using Inno.Editor.Scene; @@ -20,11 +19,11 @@ internal sealed class InstantiatePrefabAssetCommand(IEditorSceneWorkspace worksp /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) - => string.Equals(context.target.extension, ".iprefab", StringComparison.OrdinalIgnoreCase) - ? workspace.canPersist && workspace.activeScene is { } scene && workspace.CanEdit(scene) - ? EditorActionState.enabled - : EditorActionState.disabled - : EditorActionState.hidden; + => string.Equals(context.target.extension, ".iprefab", StringComparison.OrdinalIgnoreCase) + ? workspace.canPersist && workspace.activeScene is { } scene && workspace.CanEdit(scene) + ? EditorActionState.enabled + : EditorActionState.disabled + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. @@ -33,7 +32,7 @@ protected override EditorActionState Query(EditorActionContext c /// The operation scope that provides state, services, and ownership boundaries. /// protected override void Execute(EditorActionContext context) - => _ = context.interactions - .For(HierarchyInteractionIds.C_FILE_BROWSER_AREA, context.target) - .Execute(HierarchyInteractionIds.C_OPEN); + => _ = context.interactions + .For(HierarchyInteractionIds.C_FILE_BROWSER_AREA, context.target) + .Execute(HierarchyInteractionIds.C_OPEN); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/LoadSceneAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/LoadSceneAssetCommand.cs index eb6ecbf88..7ce0f4dda 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/LoadSceneAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/LoadSceneAssetCommand.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets.Pipeline; using Inno.Editor.Interactions; using Inno.Editor.Scene; @@ -20,11 +19,11 @@ internal sealed class LoadSceneAssetCommand(IEditorSceneWorkspace workspace) : E /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) - => string.Equals(context.target.extension, ".iscene", StringComparison.OrdinalIgnoreCase) - ? workspace.canPersist - ? EditorActionState.enabled - : EditorActionState.disabled - : EditorActionState.hidden; + => string.Equals(context.target.extension, ".iscene", StringComparison.OrdinalIgnoreCase) + ? workspace.canPersist + ? EditorActionState.enabled + : EditorActionState.disabled + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. @@ -33,7 +32,7 @@ protected override EditorActionState Query(EditorActionContext c /// The operation scope that provides state, services, and ownership boundaries. /// protected override void Execute(EditorActionContext context) - => _ = context.interactions - .For(HierarchyInteractionIds.C_FILE_BROWSER_AREA, context.target) - .Execute(HierarchyInteractionIds.C_OPEN); + => _ = context.interactions + .For(HierarchyInteractionIds.C_FILE_BROWSER_AREA, context.target) + .Execute(HierarchyInteractionIds.C_OPEN); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/MoveGameObjectToSceneDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/MoveGameObjectToSceneDropHandler.cs index fbb131719..562608665 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/MoveGameObjectToSceneDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/MoveGameObjectToSceneDropHandler.cs @@ -7,6 +7,7 @@ using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; + [EditorDrop(HierarchyInteractionIds.C_AREA)] internal sealed class MoveGameObjectToSceneDropHandler(SceneEdits edits) : EditorDrop { @@ -24,9 +25,9 @@ protected override EditorDropStatus Query(EditorDropContext 0 - && sources.All(value => value.isRuntimeValid && edits.CanEdit(value)) - && edits.CanEdit(target) - && target is { isLoaded: true, isDestroyed: false } ? EditorDropStatus.Accept() : EditorDropStatus.rejected; + && sources.All(value => value.isRuntimeValid && edits.CanEdit(value)) + && edits.CanEdit(target) + && target is { isLoaded: true, isDestroyed: false } ? EditorDropStatus.Accept() : EditorDropStatus.rejected; } /// @@ -41,7 +42,9 @@ protected override EditorDropStatus Query(EditorDropContext context) { if (!Query(context).canDrop) + { return EditorDropResult.rejected; + } edits.MoveGameObjects(SelectedSources(context), context.target.scene); return EditorDropResult.Accepted(context.source, context.target); } @@ -49,7 +52,9 @@ protected override EditorDropResult Drop(EditorDropContext context) { if (!context.interactions.selection.Contains(context.source)) + { return[context.source]; + } var values = new List(); context.interactions.selection.CopyTargets(values); return values.Count == context.interactions.selection.count ? values.ToArray() : []; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenPrefabAssetAction.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenPrefabAssetAction.cs index 1c0f076bf..38b641603 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenPrefabAssetAction.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenPrefabAssetAction.cs @@ -20,9 +20,9 @@ SceneEdits edits /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) - => workspace.canPersist && workspace.activeScene is not null - ? EditorActionState.enabled - : EditorActionState.disabled; + => workspace.canPersist && workspace.activeScene is not null + ? EditorActionState.enabled + : EditorActionState.disabled; /// /// Applies the editor action to the supplied interaction context. @@ -34,7 +34,9 @@ protected override void Execute(EditorActionContext context { GameScene? scene = workspace.activeScene; if (scene is null) + { return; + } GameObject instance = edits.InstantiatePrefab(context.target, scene); _ = context.interactions.For(HierarchyInteractionIds.C_AREA, instance).Select(); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenSceneAssetAction.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenSceneAssetAction.cs index c569191d3..78d45e5e9 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenSceneAssetAction.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/OpenSceneAssetAction.cs @@ -17,9 +17,9 @@ internal sealed class OpenSceneAssetAction(IEditorSceneWorkspace workspace) : Ed /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) - => workspace.canPersist - ? EditorActionState.enabled - : EditorActionState.disabled; + => workspace.canPersist + ? EditorActionState.enabled + : EditorActionState.disabled; /// /// Executes the prepared operation and publishes only a completed result. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/RenameHierarchyTargetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/RenameHierarchyTargetCommand.cs index 5bae41e51..bc07dc035 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/RenameHierarchyTargetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/RenameHierarchyTargetCommand.cs @@ -1,12 +1,14 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using Inno.Core.Input; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene; -using Inno.Editor.ImGui.ImGuiWidget; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.Panel.Hierarchy; + [EditorAction(HierarchyInteractionIds.C_RENAME, priority: 100)] [EditorMenu(HierarchyInteractionIds.C_AREA, "Rename", order: 200)] [EditorShortcut(HierarchyInteractionIds.C_AREA, KeyCode.F2)] @@ -15,6 +17,7 @@ internal sealed class RenameHierarchyTargetCommand(SceneEdits edits) : EditorPre private string m_buffer = string.Empty; private bool m_requestFocus; private string m_originalName = string.Empty; + /// /// Evaluates whether the requested change can be applied to the current generation. /// @@ -24,7 +27,11 @@ internal sealed class RenameHierarchyTargetCommand(SceneEdits edits) : EditorPre /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => IsAvailable(context.target) ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled : EditorActionState.hidden; + protected override EditorActionState Query(EditorActionContext context) + => IsAvailable(context.target) + ? edits.CanEdit(context.target) ? EditorActionState.enabled : EditorActionState.disabled + : EditorActionState.hidden; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -34,7 +41,9 @@ internal sealed class RenameHierarchyTargetCommand(SceneEdits edits) : EditorPre protected override void Execute(EditorActionContext context) { if (!TryGetName(context.target, out string name)) + { return; + } Activate(context); m_buffer = name; m_originalName = name; @@ -53,7 +62,9 @@ protected override void Execute(EditorActionContext context) protected override bool Present(EditorActionContext context) { if (activeTarget is not EngineObject target) + { return false; + } InlineRenamePresentation presentation = context.argument; InlineRenameResult result = EditorUI.current.widgets.InlineRename( presentation.id, @@ -70,7 +81,9 @@ protected override bool Present(EditorActionContext protected override void OnCompleted() => ClearState(); + /// /// Cancels the interaction without committing its pending value. /// protected override void OnCancelled() => ClearState(); + /// /// Cancels pending presentation state when its editor surface disappears. /// @@ -99,7 +114,9 @@ protected override void OnPresentationLost() private void CommitName() { if (activeTarget is not EngineObject target) + { return; + } string fallback = target is GameScene ? "Scene" : "GameObject"; string name = string.IsNullOrWhiteSpace(m_buffer) ? fallback : m_buffer.Trim(); if (!string.Equals(m_originalName, name, StringComparison.Ordinal)) @@ -125,12 +142,14 @@ private void ClearState() m_originalName = string.Empty; } - private static bool IsAvailable(EngineObject target) => target switch + private static bool IsAvailable(EngineObject target) + => target switch { GameScene scene => scene.isLoaded && !scene.isDestroyed, GameObject gameObject => gameObject.isRuntimeValid, _ => false }; + private static bool TryGetName( EngineObject target, out string name diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs index 7b16b46fe..d17f1b1a1 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs @@ -1,5 +1,4 @@ using System; - using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scene; @@ -11,8 +10,7 @@ namespace Inno.Editor.Panel.Hierarchy; internal sealed class ReorderSceneDropHandler( IEditorSceneWorkspace workspace, SceneEdits edits -) - : EditorDrop +) : EditorDrop { /// /// Evaluates whether the requested change can be applied to the current generation. @@ -28,11 +26,14 @@ protected override EditorDropStatus Query(EditorDropContext @@ -52,7 +53,9 @@ protected override EditorDropResult Drop(EditorDropContext { @@ -24,20 +25,33 @@ protected override EditorDropStatus Query(EditorDropContext !value.isRuntimeValid || !edits.CanEdit(value))) + if (sources.Length == 0 + || !target.isRuntimeValid + || !edits.CanEdit(target) + || sources.Any(value => !value.isRuntimeValid || !edits.CanEdit(value)) + ) { return EditorDropStatus.rejected; + } Transform? parent = context.placement == EditorDropPlacement.Into ? target.transform : target.transform.parent; for (Transform? ancestor = parent; ancestor is not null; ancestor = ancestor.parent) + { if (sources.Any(value => ReferenceEquals(value.transform, ancestor))) + { return EditorDropStatus.rejected; + } + } if (sources.Contains(target)) - return EditorDropStatus.rejected; - return EditorDropStatus.Accept(context.placement switch { - EditorDropPlacement.Before => EditorDropVisual.InsertBefore, - EditorDropPlacement.After => EditorDropVisual.InsertAfter, - _ => EditorDropVisual.Highlight - }); + return EditorDropStatus.rejected; + } + return EditorDropStatus.Accept( + context.placement switch + { + EditorDropPlacement.Before => EditorDropVisual.InsertBefore, + EditorDropPlacement.After => EditorDropVisual.InsertAfter, + _ => EditorDropVisual.Highlight + } + ); } /// @@ -52,7 +66,9 @@ protected override EditorDropStatus Query(EditorDropContext context) { if (!Query(context).canDrop) + { return EditorDropResult.rejected; + } GameObject target = context.target.gameObject; GameObject[] sources = SelectedSources(context); Transform? parent = context.placement == EditorDropPlacement.Into ? target.transform : target.transform.parent; @@ -60,9 +76,17 @@ protected override EditorDropResult Drop(EditorDropContext ReferenceEquals(value.transform.parent, parent) && ReferenceEquals(value.scene, target.scene) && value.transform.siblingIndex < target.transform.siblingIndex); + insertionIndex -= sources.Count( + value => ( + ReferenceEquals(value.transform.parent, parent) + && ReferenceEquals(value.scene, target.scene) + && value.transform.siblingIndex < target.transform.siblingIndex + ) + ); if (context.placement == EditorDropPlacement.After) + { insertionIndex++; + } } edits.MoveGameObjects(sources, target.scene, parent?.gameObject, insertionIndex); @@ -72,7 +96,9 @@ protected override EditorDropResult Drop(EditorDropContext context) { if (!context.interactions.selection.Contains(context.source)) + { return[context.source]; + } var values = new List(); context.interactions.selection.CopyTargets(values); return values.Count == context.interactions.selection.count ? values.ToArray() : []; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveCommand.cs index 139fef8ab..9558dde24 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveCommand.cs @@ -1,12 +1,13 @@ using System; using System.Collections.Generic; -using Inno.Core.Logging; using Inno.Core.Input; +using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; + [EditorAction(HierarchyInteractionIds.C_SAVE)] [EditorMenu(HierarchyInteractionIds.C_MAIN_MENU_AREA, "File/Save", order: 100)] [EditorShortcut(KeyCode.S, primary: true)] @@ -16,6 +17,7 @@ LogRouter logs ) : EditorAction { private readonly Logger m_log = (logs ?? throw new ArgumentNullException(nameof(logs))).CreateLogger(); + /// /// Evaluates whether the requested change can be applied to the current generation. /// @@ -25,8 +27,10 @@ LogRouter logs /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => workspace.canPersist - && workspace.activeScene is not null ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => workspace.canPersist + && workspace.activeScene is not null ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs index b3c0c56ac..a2c4a2d52 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs @@ -1,6 +1,5 @@ using Inno.Assets; using Inno.Assets.Pipeline; - using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scene; @@ -9,8 +8,7 @@ namespace Inno.Editor.Panel.Hierarchy; [EditorDrop(HierarchyInteractionIds.C_FILE_BROWSER_AREA)] -internal sealed class SavePrefabAssetDropHandler - : EditorDrop +internal sealed class SavePrefabAssetDropHandler : EditorDrop { private readonly IEditorSceneWorkspace m_workspace; private readonly AssetPipeline m_assets; @@ -34,8 +32,8 @@ AssetPipeline assets /// protected override EditorDropStatus Query(EditorDropContext context) => m_workspace.canPersist && context.source.isRuntimeValid - ? EditorDropStatus.Accept() - : EditorDropStatus.rejected; + ? EditorDropStatus.Accept() + : EditorDropStatus.rejected; /// /// Validates and applies the current editor drag-and-drop interaction atomically. @@ -50,7 +48,9 @@ protected override EditorDropResult Drop(EditorDropContext c { string path = m_workspace.SavePrefab(context.source, context.target); if (!m_assets.TryGetFileSystemEntry(AssetPath.Parse(path), out AssetFileEntry selection)) + { return EditorDropResult.rejected; + } _ = context.interactions.For(context.area, selection).Select(); return EditorDropResult.Accepted(selection); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs index 5c655fbf5..6d3efefd8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs @@ -1,6 +1,5 @@ using Inno.Assets; using Inno.Assets.Pipeline; - using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scene; @@ -9,8 +8,7 @@ namespace Inno.Editor.Panel.Hierarchy; [EditorDrop(HierarchyInteractionIds.C_FILE_BROWSER_AREA)] -internal sealed class SaveSceneAssetDropHandler - : EditorDrop +internal sealed class SaveSceneAssetDropHandler : EditorDrop { private readonly IEditorSceneWorkspace m_workspace; private readonly AssetPipeline m_assets; @@ -34,8 +32,8 @@ AssetPipeline assets /// protected override EditorDropStatus Query(EditorDropContext context) => m_workspace.canPersist && context.source.isLoaded - ? EditorDropStatus.Accept() - : EditorDropStatus.rejected; + ? EditorDropStatus.Accept() + : EditorDropStatus.rejected; /// /// Validates and applies the current editor drag-and-drop interaction atomically. @@ -50,7 +48,9 @@ protected override EditorDropResult Drop(EditorDropContext co { string path = m_workspace.SaveToDirectory(context.source, context.target); if (!m_assets.TryGetFileSystemEntry(AssetPath.Parse(path), out AssetFileEntry selection)) + { return EditorDropResult.rejected; + } _ = context.interactions.For(context.area, selection).Select(); return EditorDropResult.Accepted(selection); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SetActiveSceneCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SetActiveSceneCommand.cs index d7104e693..00d45b868 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SetActiveSceneCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SetActiveSceneCommand.cs @@ -19,8 +19,8 @@ internal sealed class SetActiveSceneCommand(IEditorSceneWorkspace workspace) : E /// protected override EditorActionState Query(EditorActionContext context) => context.target.isLoaded - ? new EditorActionState(true, !ReferenceEquals(context.target, workspace.activeScene)) - : EditorActionState.hidden; + ? new EditorActionState(true, !ReferenceEquals(context.target, workspace.activeScene)) + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/UnloadSceneCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/UnloadSceneCommand.cs index 984ebe360..924dfbafe 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/UnloadSceneCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/UnloadSceneCommand.cs @@ -1,6 +1,6 @@ +using Inno.Core.Input; using Inno.Editor.Interactions; using Inno.Editor.Scene; -using Inno.Core.Input; using Inno.Scene; namespace Inno.Editor.Panel.Hierarchy; @@ -21,8 +21,8 @@ internal sealed class UnloadSceneCommand(SceneEdits edits) : EditorAction protected override EditorActionState Query(EditorActionContext context) => context.target is { isLoaded: true, isDestroyed: false } - ? EditorActionState.enabled - : EditorActionState.disabled; + ? EditorActionState.enabled + : EditorActionState.disabled; /// /// Executes the prepared operation and publishes only a completed result. @@ -33,8 +33,12 @@ protected override EditorActionState Query(EditorActionContext contex protected override void Execute(EditorActionContext context) { if (!edits.CloseScene(context.target)) + { return; + } if (context.interactions.selection.TryGet(out GameScene? selected) && ReferenceEquals(selected, context.target)) + { _ = context.interactions.For(context.area).Select(); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyDropVisual.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyDropVisual.cs index 2c9913245..d2abfb7cd 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyDropVisual.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyDropVisual.cs @@ -1,19 +1,22 @@ -using UiDrawing = Inno.Editor.ImGui.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using UiDrawing = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Hierarchy; + internal sealed class HierarchyDropVisual { internal EditorDropPlacement GetScenePlacement( in TreeNodeResult result, float mouseY ) => mouseY >= (result.min.Y + result.max.Y) * 0.5f ? EditorDropPlacement.After : EditorDropPlacement.Before; + internal EditorDropPlacement GetObjectPlacement( in TreeNodeResult result, float mouseY @@ -21,7 +24,9 @@ float mouseY float height = MathF.Max(1f, result.max.Y - result.min.Y); float relativeY = (mouseY - result.min.Y) / height; if (relativeY < 0.25f) + { return EditorDropPlacement.Before; + } return relativeY > 0.75f ? EditorDropPlacement.After : EditorDropPlacement.Into; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs index 3b9dc8e31..46dd44cb9 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs @@ -4,6 +4,7 @@ using Inno.Editor.Core; using Inno.Scene; using Inno.Scene.Components; + using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; @@ -24,20 +25,32 @@ private void RefreshRows(IReadOnlyList scenes) { var widgets = EditorUI.current.widgets; foreach (GameScene scene in scenes) + { if (m_initializedSceneIds.Add(scene.identity.persistentId)) + { widgets.SetTreeNodeOpen("scene_" + scene.identity.persistentId.ToString("N"), true); + } + } foreach (Guid id in m_forceOpenSceneIds) + { widgets.SetTreeNodeOpen("scene_" + id.ToString("N"), true); + } foreach (Guid id in m_forceOpenIds) + { widgets.SetTreeNodeOpen("hierarchy_" + id.ToString("N"), true); + } m_forceOpenSceneIds.Clear(); m_forceOpenIds.Clear(); bool changed = m_expansionRevision != widgets.treeExpansionRevision || m_sceneInputs.Count != scenes.Count; for (int index = 0; !changed && index < scenes.Count; index++) + { changed = m_sceneInputs[index] != (RequireIdentity(scenes[index]), scenes[index].hierarchyRevision); + } if (!changed) + { return; + } var rows = new List(); var inputs = new List<(RuntimeIdentity, ulong)>(); @@ -49,23 +62,35 @@ private void RefreshRows(IReadOnlyList scenes) inputs.Add((sceneId, scene.hierarchyRevision)); rows.Add(new(sceneId, 0)); if (!widgets.IsTreeNodeOpen("scene_" + scene.identity.persistentId.ToString("N"))) + { continue; + } IReadOnlyList roots = m_selection.GetRootObjects(scene); for (int index = roots.Count - 1; index >= 0; index--) + { pending.Push((roots[index], 1)); + } while (pending.TryPop(out var next)) { if (!next.target.isRuntimeValid) + { continue; + } RuntimeIdentity identity = RequireIdentity(next.target); if (!visited.Add(identity)) + { throw new InvalidOperationException("A hierarchy view encountered a duplicate object identity."); + } rows.Add(new(identity, next.depth)); if (!widgets.IsTreeNodeOpen("hierarchy_" + next.target.identity.persistentId.ToString("N"))) + { continue; + } IReadOnlyList children = next.target.transform.children; for (int index = children.Count - 1; index >= 0; index--) + { pending.Push((children[index].gameObject, next.depth + 1)); + } } } @@ -75,7 +100,9 @@ private void RefreshRows(IReadOnlyList scenes) m_sceneInputs.AddRange(inputs); m_visibleSelection.Clear(); foreach (HierarchyRow row in rows) + { m_visibleSelection.Add(row.identity); + } m_expansionRevision = widgets.treeExpansionRevision; } @@ -86,8 +113,12 @@ private void DrawRows(EditorContext context) Span preserved = stackalloc int[3]; int count = 0; for (int index = 0; index < m_rows.Count; index++) + { if (m_rows[index].identity == selected || m_rows[index].identity == dragging || m_rows[index].identity == m_drawKeyboardFocus) + { preserved[count++] = index; + } + } EditorUI.current.widgets.ClippedRows(m_rows.Count, -1f, (panel: this, context), static ( state, start, @@ -101,18 +132,27 @@ private void DrawRows(EditorContext context) if (state.panel.m_interactions.TryResolveIdentity(row.identity, out IdentityObject? target)) { if (target is GameScene scene) + { state.panel.DrawScene(state.context, scene, row.depth); + } else if (target is GameObject gameObject) + { state.panel.DrawObject(state.context, gameObject, row.depth); + } else + { Ui.Dummy(new(1f, Ui.GetFrameHeight())); + } } else + { Ui.Dummy(new(1f, Ui.GetFrameHeight())); + } } }, preserved[..count]); } private static RuntimeIdentity RequireIdentity(IdentityObject target) - => target.identity.runtimeIdentity ?? throw new InvalidOperationException("A visible hierarchy row requires a registered identity."); + => target.identity.runtimeIdentity + ?? throw new InvalidOperationException("A visible hierarchy row requires a registered identity."); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs index 8603953df..29806aed3 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs @@ -1,19 +1,21 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Numerics; using Inno.Core.Identity; using Inno.Editor.Core; +using Inno.Editor.ImGui; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Settings; -using Inno.Editor.ImGui; -using Inno.Editor.ImGui.ImGuiWidget; using Inno.Scene; using Inno.Scene.Components; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Hierarchy; + /// /// Edits the active scene object hierarchy. /// @@ -39,10 +41,12 @@ internal sealed partial class HierarchyPanel : EditorPanel private readonly HashSet m_initializedSceneIds = []; private ulong m_lastRevealedSelectionVersion = ulong.MaxValue; private int m_visibleRowIndex; + /// /// Gets whether use window padding is enabled for this implementation. /// public override bool useWindowPadding => false; + /// /// Lets the hierarchy content child own both scroll directions. /// @@ -72,7 +76,12 @@ EditorSettings settings /// protected override void OnDraw(EditorContext context) { - bool visible = Ui.BeginChild("##HierarchyContent", Vector2.Zero, (ImGuiChildFlags.None), (ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.HorizontalScrollbar)); + bool visible = Ui.BeginChild( + "##HierarchyContent", + Vector2.Zero, + (ImGuiChildFlags.None), + (ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.HorizontalScrollbar) + ); try { if (visible) @@ -112,8 +121,10 @@ private void DrawContent(EditorContext context) DrawRows(context); DrawBlankArea(context); - if (m_pendingSelection is RuntimeIdentity pending && m_interactions.TryResolveIdentity(pending, out IdentityObject? target) && target is not null) - { + if (m_pendingSelection is RuntimeIdentity pending + && m_interactions.TryResolveIdentity(pending, out IdentityObject? target) + && target is not null + ) { EditorUI.current.widgets.SelectTarget(m_interactions, target, m_visibleSelection); m_keyboardFocus = pending; m_interactions.For(HierarchyInteractionIds.C_AREA, target).Focus(); @@ -136,40 +147,65 @@ private void HandleKeyboardNavigation() { RuntimeIdentity item = m_visibleSelection[index]; if (item == m_keyboardFocus) + { focused = index; + } if (item == selectedTarget) + { selected = index; + } } if (focused < 0) + { focused = selected; - ListNavigationResult navigation = EditorUI.current.widgets.NavigateList(m_interactions, m_visibleSelection.Count, focused, m_keyboardPageSize); + } + ListNavigationResult navigation = EditorUI.current.widgets.NavigateList( + m_interactions, + m_visibleSelection.Count, + focused, + m_keyboardPageSize + ); if (navigation.focusedIndex >= 0 && (navigation.focusChanged || navigation.selectionRequested || navigation.activate)) { RuntimeIdentity identity = m_visibleSelection[navigation.focusedIndex]; if (!m_interactions.TryResolveIdentity(identity, out IdentityObject? target) || target is null) + { return; + } m_keyboardFocus = identity; if (navigation.focusChanged) + { m_requestedKeyboardFocus = m_keyboardFocus; + } if (navigation.selectionRequested) { if (navigation.extendRange) + { m_interactions.SelectRange(m_visibleSelection, target, navigation.additive); + } else if (navigation.toggle) + { m_interactions.ToggleSelection(target); + } else + { m_interactions.SetSelection(target); + } } m_interactions.For(HierarchyInteractionIds.C_AREA, m_interactions.selection.selectedTarget).Focus(); if (navigation.activate) { if (!m_interactions.selection.Contains(target)) + { m_interactions.SetSelection(target); + } _ = m_interactions.For(HierarchyInteractionIds.C_AREA, target).Execute(HierarchyInteractionIds.C_RENAME); } } if (navigation.cancel) + { m_keyboardFocus = null; + } } private void DrawScene( @@ -182,24 +218,42 @@ int depth TreeNodeResult result = EditorUI.current.widgets.TreeNode( $"scene_{id}", drawContext => DrawSceneRowContent(scene, id, drawContext.rowHeight), - new TreeNodeOptions { - depth = depth, selected = selected, requestFocus = scene.identity.runtimeIdentity == m_drawKeyboardFocus, + new TreeNodeOptions + { + depth = depth, + selected = selected, + requestFocus = scene.identity.runtimeIdentity == m_drawKeyboardFocus, keepContentActive = m_interactions.For(HierarchyInteractionIds.C_AREA, scene).IsActive(HierarchyInteractionIds.C_RENAME), - showBackground = true, backgroundColor = EditorPalette.title - }); + showBackground = true, + backgroundColor = EditorPalette.title + } + ); if (!result.isSubmitted) + { return; + } if (result.isClicked || result.isDoubleClicked) + { m_pendingSelection = scene.identity.runtimeIdentity; + } if (result.isDoubleClicked) + { _ = m_interactions.For(HierarchyInteractionIds.C_AREA, scene).Execute(HierarchyInteractionIds.C_RENAME); - _ = EditorDragDropRenderer.Source(m_interactions.For(HierarchyInteractionIds.C_AREA, scene), - new EditorDragData(scene, scene.name), () => Ui.Text(scene.name)); + } + _ = EditorDragDropRenderer.Source( + m_interactions.For(HierarchyInteractionIds.C_AREA, scene), + new EditorDragData(scene, scene.name), + () => Ui.Text(scene.name) + ); EditorDropPlacement placement = m_dropVisual.GetScenePlacement(result, Ui.GetMousePos().Y); EditorDropWidgetResult drop = EditorDragDropRenderer.Target( - m_interactions.For(HierarchyInteractionIds.C_AREA, new HierarchySceneDropTarget(scene)), placement); + m_interactions.For(HierarchyInteractionIds.C_AREA, new HierarchySceneDropTarget(scene)), + placement + ); if (drop.isPreviewing && drop.status.canDrop) + { m_dropVisual.Draw(result, drop.status.visual); + } ApplyDropResult(drop.result); DrawSceneContextMenu(context, scene, id); } @@ -210,32 +264,53 @@ private void DrawObject( int depth ) { if (!gameObject.isRuntimeValid) + { return; + } string id = gameObject.identity.persistentId.ToString("N"); TreeNodeResult result = EditorUI.current.widgets.TreeNode( $"hierarchy_{id}", drawContext => DrawRowContent(context, gameObject, drawContext.rowHeight), - new TreeNodeOptions { - depth = depth, selected = m_interactions.selection.Contains(gameObject), + new TreeNodeOptions + { + depth = depth, + selected = m_interactions.selection.Contains(gameObject), requestFocus = gameObject.identity.runtimeIdentity == m_drawKeyboardFocus, - keepContentActive = m_interactions.For(HierarchyInteractionIds.C_AREA, gameObject).IsActive(HierarchyInteractionIds.C_RENAME), - isLeaf = gameObject.transform.children.Count == 0, showBackground = true, + keepContentActive = m_interactions + .For(HierarchyInteractionIds.C_AREA, gameObject) + .IsActive(HierarchyInteractionIds.C_RENAME), + isLeaf = gameObject.transform.children.Count == 0, + showBackground = true, backgroundColor = m_visibleRowIndex % 2 == 0 ? EditorPalette.collectionRow : EditorPalette.collectionRowAlternate, drawViewportOverlay = () => DrawVisibilityButton(gameObject, id) - }); + } + ); if (!result.isSubmitted) + { return; + } if (result.isClicked || result.isDoubleClicked) + { m_pendingSelection = gameObject.identity.runtimeIdentity; + } if (result.isDoubleClicked) + { _ = m_interactions.For(HierarchyInteractionIds.C_AREA, gameObject).Execute(HierarchyInteractionIds.C_RENAME); - _ = EditorDragDropRenderer.Source(m_interactions.For(HierarchyInteractionIds.C_AREA, gameObject), - new EditorDragData(gameObject, gameObject.name), () => Ui.Text(gameObject.name)); + } + _ = EditorDragDropRenderer.Source( + m_interactions.For(HierarchyInteractionIds.C_AREA, gameObject), + new EditorDragData(gameObject, gameObject.name), + () => Ui.Text(gameObject.name) + ); EditorDropPlacement placement = m_dropVisual.GetObjectPlacement(result, Ui.GetMousePos().Y); EditorDropWidgetResult drop = EditorDragDropRenderer.Target( - m_interactions.For(HierarchyInteractionIds.C_AREA, new HierarchyObjectDropTarget(gameObject)), placement); + m_interactions.For(HierarchyInteractionIds.C_AREA, new HierarchyObjectDropTarget(gameObject)), + placement + ); if (drop.isPreviewing && drop.status.canDrop) + { m_dropVisual.Draw(result, drop.status.visual); + } ApplyDropResult(drop.result); DrawObjectContextMenu(context, gameObject, id); } @@ -258,24 +333,37 @@ float rowHeight bool isRenaming = interaction.IsActive(HierarchyInteractionIds.C_RENAME); if (isRenaming) { - EditorUI.current.widgets.IconText(m_settings.Get("Editor/Appearance/Icons/GameObject").GetAsString("value", ImGuiIcon.Cube)!, string.Empty, false); + EditorUI.current.widgets.IconText( + m_settings.Get("Editor/Appearance/Icons/GameObject").GetAsString("value", ImGuiIcon.Cube)!, + string.Empty, + false + ); Ui.SameLine(0f, 0f); float visibilityWidth = GetVisibilityButtonWidth(); float renameWidth = MathF.Max( hierarchyStyle.renameMinimumWidth, Ui.GetContentRegionAvailable().X - visibilityWidth - hierarchyStyle.renameTrailingGap ); - _ = interaction.Present(HierarchyInteractionIds.C_RENAME, new InlineRenamePresentation($"hierarchy_{id}", renameWidth, rowHeight, C_NAME_BUFFER_SIZE)); + _ = interaction.Present( + HierarchyInteractionIds.C_RENAME, + new InlineRenamePresentation($"hierarchy_{id}", renameWidth, rowHeight, C_NAME_BUFFER_SIZE) + ); } else { - EditorUI.current.widgets.IconText(m_settings.Get("Editor/Appearance/Icons/GameObject").GetAsString("value", ImGuiIcon.Cube)!, gameObject.name, false); + EditorUI.current.widgets.IconText( + m_settings.Get("Editor/Appearance/Icons/GameObject").GetAsString("value", ImGuiIcon.Cube)!, + gameObject.name, + false + ); } } finally { if (dimmed) + { Ui.PopStyleColor(); + } } } @@ -301,7 +389,10 @@ float rowHeight hierarchyStyle.renameMinimumWidth, Ui.GetContentRegionAvailable().X - hierarchyStyle.renameTrailingGap ); - _ = interaction.Present(HierarchyInteractionIds.C_RENAME, new InlineRenamePresentation($"scene_{id}", renameWidth, rowHeight, C_NAME_BUFFER_SIZE)); + _ = interaction.Present( + HierarchyInteractionIds.C_RENAME, + new InlineRenamePresentation($"scene_{id}", renameWidth, rowHeight, C_NAME_BUFFER_SIZE) + ); } private void DrawVisibilityButton( @@ -321,13 +412,16 @@ string id } private static float GetVisibilityButtonWidth() => EditorUI.current.widgets.GetCompactIconSize().X; + private void DrawSceneContextMenu( EditorContext context, GameScene scene, string id ) { if (Ui.IsItemClicked(ImGuiMouseButton.Right) && !m_interactions.selection.Contains(scene)) + { m_interactions.SetSelection(scene); + } _ = EditorUI.current.menus.ContextMenu($"##scene_context_{id}", m_interactions.For(HierarchyInteractionIds.C_AREA, scene)); } @@ -337,7 +431,9 @@ private void DrawObjectContextMenu( string id ) { if (Ui.IsItemClicked(ImGuiMouseButton.Right) && !m_interactions.selection.Contains(gameObject)) + { m_interactions.SetSelection(gameObject); + } _ = EditorUI.current.menus.ContextMenu($"##hierarchy_context_{id}", m_interactions.For(HierarchyInteractionIds.C_AREA, gameObject)); } @@ -363,7 +459,9 @@ private void DrawBlankArea(EditorContext context) _ = EditorUI.current.menus.ContextMenu( "##hierarchy_blank_context", - activeScene is null ? m_interactions.For(HierarchyInteractionIds.C_AREA) : m_interactions.For(HierarchyInteractionIds.C_AREA, activeScene) + activeScene is null + ? m_interactions.For(HierarchyInteractionIds.C_AREA) + : m_interactions.For(HierarchyInteractionIds.C_AREA, activeScene) ); } @@ -371,22 +469,30 @@ private void RevealSelection() { ulong selectionVersion = m_interactions.selection.version; if (m_lastRevealedSelectionVersion == selectionVersion) + { return; + } m_lastRevealedSelectionVersion = selectionVersion; if (!m_interactions.selection.TryGet(out GameObject? gameObject) || !gameObject.isRuntimeValid) + { return; + } m_forceOpenSceneIds.Add(gameObject.scene.identity.persistentId); for (Transform? current = gameObject.transform.parent; current is not null; current = current.parent) { if (current.gameObject is not null) + { m_forceOpenIds.Add(current.gameObject.identity.persistentId); + } } } private void ApplyDropResult(EditorDropResult result) { if (!result.accepted) + { return; + } if (result.revealTarget is GameScene scene) { m_forceOpenSceneIds.Add(scene.identity.persistentId); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchySelection.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchySelection.cs index 89405238e..c17097451 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchySelection.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchySelection.cs @@ -1,14 +1,16 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System.Collections.Generic; +using Inno.Editor.ImGui; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Settings; -using Inno.Editor.ImGui; -using Inno.Editor.ImGui.ImGuiWidget; using Inno.Scene; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Hierarchy; + internal sealed class HierarchySelection( IEditorSceneWorkspace workspace, EditorInteractions interactions, @@ -16,14 +18,18 @@ EditorSettings settings ) { internal void Prune() { - if (interactions.selection.TryGet(out GameScene? selectedScene) && (!selectedScene.isLoaded || !ContainsScene(workspace.scenes, selectedScene))) - { + if (interactions.selection.TryGet(out GameScene? selectedScene) + && (!selectedScene.isLoaded || !ContainsScene(workspace.scenes, selectedScene)) + ) { _ = interactions.For(HierarchyInteractionIds.C_AREA).Select(); return; } - if (interactions.selection.TryGet(out GameObject? gameObject) && (!gameObject.isRuntimeValid || !ContainsScene(workspace.scenes, gameObject.scene))) + if (interactions.selection.TryGet(out GameObject? gameObject) + && (!gameObject.isRuntimeValid || !ContainsScene(workspace.scenes, gameObject.scene)) + ) { _ = interactions.For(HierarchyInteractionIds.C_AREA).Select(); + } } internal IReadOnlyList GetRootObjects(GameScene scene) @@ -33,7 +39,9 @@ internal IReadOnlyList GetRootObjects(GameScene scene) for (int i = 0; i < objects.Count; i++) { if (objects[i].transform.parent is null) + { roots.Add(objects[i]); + } } roots.Sort(static ( @@ -51,7 +59,9 @@ internal void DrawSceneRowContent(GameScene scene) ReferenceEquals(scene, workspace.activeScene) ); if (!workspace.IsDirty(scene)) + { return; + } Ui.SameLine(0f, 0f); using ImGuiFontScope font = ImGuiFont.PushStyle(ImGuiFontStyle.Italic); Ui.Text(" *"); @@ -64,7 +74,9 @@ GameScene scene for (int i = 0; i < scenes.Count; i++) { if (ReferenceEquals(scenes[i], scene)) + { return true; + } } return false; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Properties/ScriptingApi.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Properties/ScriptingApi.cs index 65f0e4c62..c8fc2803b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Properties/ScriptingApi.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Editor.Panel.Hierarchy; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Hierarchy", - "Inno.Editor.Panel.Hierarchy", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Hierarchy", "Inno.Editor.Panel.Hierarchy", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(HierarchyObjectDropTarget), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(HierarchySceneDropTarget), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs index 0bc25f4b2..a0d994d55 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs @@ -5,8 +5,7 @@ namespace Inno.Editor.Panel.Inspector; [EditorDrop(InspectorInteractionIds.C_ASSET_REFERENCE_AREA, priority: 100)] -internal sealed class AssetReferenceDropHandler(AssetPipeline assets) - : EditorDrop +internal sealed class AssetReferenceDropHandler(AssetPipeline assets) : EditorDrop { /// /// Evaluates whether the requested change can be applied to the current generation. @@ -19,12 +18,12 @@ internal sealed class AssetReferenceDropHandler(AssetPipeline assets) /// protected override EditorDropStatus Query(EditorDropContext context) { - if (!assets.TryGetPersistentId(context.source.assetPath, out System.Guid persistentId) || - persistentId == System.Guid.Empty || - !assets.TryGetAssetType(context.source.assetPath, out System.Type? assetType) || - assetType is null || - !context.target.expectedType.IsAssignableFrom(assetType)) - { + if (!assets.TryGetPersistentId(context.source.assetPath, out System.Guid persistentId) + || persistentId == System.Guid.Empty + || !assets.TryGetAssetType(context.source.assetPath, out System.Type? assetType) + || assetType is null + || !context.target.expectedType.IsAssignableFrom(assetType) + ) { return EditorDropStatus.rejected; } return EditorDropStatus.Accept(); @@ -42,9 +41,13 @@ assetType is null || protected override EditorDropResult Drop(EditorDropContext context) { if (!Query(context).canDrop) + { return EditorDropResult.rejected; + } if (!assets.TryGetPersistentId(context.source.assetPath, out System.Guid persistentId)) + { return EditorDropResult.rejected; + } context.target.Assign(persistentId); return EditorDropResult.Accepted(); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropHandler.cs index 747106aec..137cce368 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropHandler.cs @@ -1,7 +1,4 @@ - - using System.Collections.Generic; - using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Runtime; @@ -24,8 +21,8 @@ internal sealed class EngineObjectReferenceDropHandler(RuntimeSession runtimeSes /// protected override EditorDropStatus Query(EditorDropContext context) => Resolve(context) is null - ? EditorDropStatus.rejected - : EditorDropStatus.Accept(); + ? EditorDropStatus.rejected + : EditorDropStatus.Accept(); /// /// Validates and applies the current editor drag-and-drop interaction atomically. @@ -40,7 +37,9 @@ protected override EditorDropResult Drop(EditorDropContext components = gameObject.GetComponents(); for (int i = 0; i < components.Count; i++) { if (context.target.expectedType.IsInstanceOfType(components[i])) + { return components[i]; + } } return null; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropTarget.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropTarget.cs index 443c58f84..5e522c719 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropTarget.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/EngineObjectReferenceDropTarget.cs @@ -1,6 +1,4 @@ - using System; - using Inno.Scene; namespace Inno.Editor.Panel.Inspector; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentCommand.cs index ce240b94a..72e5d36d5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentCommand.cs @@ -1,11 +1,12 @@ using System.Collections.Generic; using System.Linq; -using Inno.Extensibility.Types; using Inno.Editor.Interactions; using Inno.Editor.Scene; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Editor.Panel.Inspector; + [EditorAction(InspectorInteractionIds.C_ADD_COMPONENT, InspectorInteractionIds.C_COMPONENT_AREA)] internal sealed class AddComponentCommand( SceneEdits edits, @@ -21,9 +22,11 @@ TypeCatalog types /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => Targets(context).Count > 0 - && Targets(context).All(value => value.isRuntimeValid && edits.CanEdit(value)) - && context.argument.IsValid(types) ? EditorActionState.enabled : EditorActionState.hidden; + protected override EditorActionState Query(EditorActionContext context) + => Targets(context).Count > 0 + && Targets(context).All(value => value.isRuntimeValid && edits.CanEdit(value)) + && context.argument.IsValid(types) ? EditorActionState.enabled : EditorActionState.hidden; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -34,14 +37,18 @@ protected override void Execute(EditorActionContext context { using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Add Components"); foreach (GameObject target in Targets(context)) + { _ = edits.AddComponent(target, context.argument.Resolve(types)); + } transaction.Commit(); } private static IReadOnlyList Targets(EditorActionContext context) { if (!context.interactions.selection.Contains(context.target)) + { return[context.target]; + } var targets = new List(); context.interactions.selection.CopyTargets(targets); return targets.Count == context.interactions.selection.count ? targets : []; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentMenuProvider.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentMenuProvider.cs index 68eb90f64..2e51608ac 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentMenuProvider.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddComponentMenuProvider.cs @@ -1,9 +1,8 @@ using System; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Editor.Panel.Inspector; @@ -25,13 +24,17 @@ public override void Build( EditorMenuBuilder builder ) { if (context.target is not GameObject gameObject) + { return; + } TypeCacheSnapshot snapshot = types.current; foreach (TypeRef typeRef in snapshot.GetSubTypesOf()) { Type type = typeRef.Resolve(snapshot); if (!IsAddable(type, gameObject)) + { continue; + } builder.Add(type.Name, InspectorInteractionIds.C_ADD_COMPONENT, argument: typeRef); } } @@ -41,12 +44,15 @@ private static bool IsAddable( GameObject gameObject ) { if (type.IsAbstract || type.GetConstructor( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - binder: null, - Type.EmptyTypes, - modifiers: null) is null) + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + binder: null, + Type.EmptyTypes, + modifiers: null + ) is null + ) { return false; - return type.IsDefined(typeof(AllowMultipleComponentAttribute), inherit: false) || - !gameObject.GetComponents().Any(component => component.GetType() == type); + } + return type.IsDefined(typeof(AllowMultipleComponentAttribute), inherit: false) + || !gameObject.GetComponents().Any(component => component.GetType() == type); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemCommand.cs index 39deb4460..d07e6fd9f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemCommand.cs @@ -1,6 +1,6 @@ -using Inno.Extensibility.Types; using Inno.Editor.Interactions; using Inno.Editor.Scene; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Editor.Panel.Inspector; @@ -9,8 +9,7 @@ namespace Inno.Editor.Panel.Inspector; internal sealed class AddSystemCommand( SceneEdits edits, TypeCatalog types -) - : EditorAction +) : EditorAction { /// /// Evaluates whether the requested change can be applied to the current generation. @@ -23,8 +22,8 @@ TypeCatalog types /// protected override EditorActionState Query(EditorActionContext context) => context.target.isLoaded && context.argument.IsValid(types) - ? EditorActionState.enabled - : EditorActionState.hidden; + ? EditorActionState.enabled + : EditorActionState.hidden; /// /// Executes the prepared operation and publishes only a completed result. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemMenuProvider.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemMenuProvider.cs index bd0f5cb61..48af2248a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemMenuProvider.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/AddSystemMenuProvider.cs @@ -1,9 +1,8 @@ using System; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Editor.Panel.Inspector; @@ -25,13 +24,17 @@ public override void Build( EditorMenuBuilder builder ) { if (context.target is not GameScene scene) + { return; + } TypeCacheSnapshot snapshot = types.current; foreach (TypeRef typeRef in snapshot.GetSubTypesOf()) { Type type = typeRef.Resolve(snapshot); if (!IsAddable(type, scene)) + { continue; + } builder.Add(type.Name, InspectorInteractionIds.C_ADD_SYSTEM, argument: typeRef); } } @@ -41,12 +44,15 @@ private static bool IsAddable( GameScene scene ) { if (type.IsAbstract || type.GetConstructor( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - binder: null, - Type.EmptyTypes, - modifiers: null) is null) + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + binder: null, + Type.EmptyTypes, + modifiers: null + ) is null + ) { return false; - return type.IsDefined(typeof(AllowMultipleSystemAttribute), inherit: false) || - !scene.GetSystems().Any(system => system.GetType() == type); + } + return type.IsDefined(typeof(AllowMultipleSystemAttribute), inherit: false) + || !scene.GetSystems().Any(system => system.GetType() == type); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveComponentCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveComponentCommand.cs index f3ce5e32a..c3197aea7 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveComponentCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveComponentCommand.cs @@ -1,9 +1,10 @@ -using Inno.Scene; using Inno.Editor.Interactions; using Inno.Editor.Scene; +using Inno.Scene; using Inno.Scene.Components; namespace Inno.Editor.Panel.Inspector; + [EditorAction(InspectorInteractionIds.C_REMOVE_COMPONENT, priority: 100)] [EditorMenu(InspectorInteractionIds.C_COMPONENT_AREA, "Remove Component", order: 200)] internal sealed class RemoveComponentCommand(SceneEdits edits) : EditorAction @@ -17,7 +18,9 @@ internal sealed class RemoveComponentCommand(SceneEdits edits) : EditorAction /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => context.target is not Transform ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => context.target is not Transform ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -27,6 +30,8 @@ internal sealed class RemoveComponentCommand(SceneEdits edits) : EditorAction context) { if (context.target is not Transform) + { _ = edits.RemoveComponent(context.target); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveSystemCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveSystemCommand.cs index 57ec6d7ce..3aaafe74c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveSystemCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/RemoveSystemCommand.cs @@ -1,8 +1,9 @@ -using Inno.Scene; using Inno.Editor.Interactions; using Inno.Editor.Scene; +using Inno.Scene; namespace Inno.Editor.Panel.Inspector; + [EditorAction(InspectorInteractionIds.C_REMOVE_SYSTEM, priority: 100)] [EditorMenu(InspectorInteractionIds.C_SYSTEM_AREA, "Remove System", order: 200)] internal sealed class RemoveSystemCommand(SceneEdits edits) : EditorAction @@ -16,7 +17,9 @@ internal sealed class RemoveSystemCommand(SceneEdits edits) : EditorAction /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => !context.target.isDestroyed ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => !context.target.isDestroyed ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetComponentCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetComponentCommand.cs index 4c900abca..464666285 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetComponentCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetComponentCommand.cs @@ -3,6 +3,7 @@ using Inno.Scene; namespace Inno.Editor.Panel.Inspector; + [EditorAction(InspectorInteractionIds.C_RESET_COMPONENT, priority: 100)] [EditorMenu(InspectorInteractionIds.C_COMPONENT_AREA, "Reset Component", order: 100)] internal sealed class ResetComponentCommand(SceneEdits edits) : EditorAction @@ -16,8 +17,10 @@ internal sealed class ResetComponentCommand(SceneEdits edits) : EditorAction /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => !context.target.isDestroyed - && context.target is not MissingGameComponent ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => !context.target.isDestroyed + && context.target is not MissingGameComponent ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetSystemCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetSystemCommand.cs index 0f7b5c51d..0b707d0ce 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetSystemCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Interactions/ResetSystemCommand.cs @@ -3,6 +3,7 @@ using Inno.Scene; namespace Inno.Editor.Panel.Inspector; + [EditorAction(InspectorInteractionIds.C_RESET_SYSTEM, priority: 100)] [EditorMenu(InspectorInteractionIds.C_SYSTEM_AREA, "Reset System", order: 100)] internal sealed class ResetSystemCommand(SceneEdits edits) : EditorAction @@ -16,8 +17,10 @@ internal sealed class ResetSystemCommand(SceneEdits edits) : EditorAction /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => !context.target.isDestroyed - && context.target is not MissingGameSystem ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => !context.target.isDestroyed + && context.target is not MissingGameSystem ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayerDiagnosticPublisher.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayerDiagnosticPublisher.cs index 705b788d3..1620d4f85 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayerDiagnosticPublisher.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayerDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; using Inno.Scene; using Inno.Scene.Layers; @@ -45,21 +44,29 @@ internal void Refresh(GameLayerCatalog stack) { GameObject gameObject = objects[objectIndex]; if (stack.IsDefined(gameObject.layer)) + { continue; + } Guid targetId = gameObject.identity.persistentId; currentTargets.Add(targetId); if (m_activeTargets.Contains(targetId)) + { continue; + } m_diagnostics.Set( CreateSource(targetId, gameObject.name), [Diagnostic.Error( "GAMEOBJECT-LAYER-UNDEFINED", - $"GameObject '{gameObject.name}' uses undefined layer slot {gameObject.layer.index}.")]); + $"GameObject '{gameObject.name}' uses undefined layer slot {gameObject.layer.index}." + )] + ); } } foreach (Guid targetId in m_activeTargets.Where(id => !currentTargets.Contains(id)).ToArray()) + { m_diagnostics.Clear(CreateSource(targetId, targetId.ToString("D"))); + } m_activeTargets.Clear(); m_activeTargets.UnionWith(currentTargets); } @@ -70,13 +77,14 @@ internal void Refresh(GameLayerCatalog stack) internal void Clear() { foreach (Guid targetId in m_activeTargets) + { m_diagnostics.Clear(CreateSource(targetId, targetId.ToString("D"))); + } m_activeTargets.Clear(); } private static DiagnosticSource CreateSource( Guid targetId, string displayName - ) - => new($"editor.scene.layer:{targetId:N}", $"{C_DIAGNOSTIC_GROUP}: {displayName}"); + ) => new($"editor.scene.layer:{targetId:N}", $"{C_DIAGNOSTIC_GROUP}: {displayName}"); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayersSetting.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayersSetting.cs index b4d38694c..099300d87 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayersSetting.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameLayersSetting.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Globalization; @@ -9,9 +8,12 @@ using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; using Inno.Scene.Layers; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [ProjectSettingPath("Project/Scene/Layers")] internal sealed class GameLayersSetting : ProjectSettingEditor { @@ -19,14 +21,17 @@ internal sealed class GameLayersSetting : ProjectSettingEditor private readonly string[] m_nameBuffers = new string[GameLayer.C_MAX_COUNT]; private string m_error = string.Empty; private string? []? m_observedNames; + /// /// Gets the presentation section that groups this setting. /// public override string section => "Definitions"; + /// /// Gets the user-facing explanation of this feature or setting. /// - public override string description => "Define layer names and slots. Stable IDs are generated as projectId.name and are never authored manually."; + public override string description + => "Define layer names and slots. Stable IDs are generated as projectId.name and are never authored manually."; /// /// Draws this feature using the current editor presentation context. @@ -40,7 +45,9 @@ protected override void OnDraw(GameLayerCatalog setting) SynchronizeBuffers(names); DrawLayerRows(setting, names); if (!string.IsNullOrEmpty(m_error)) + { EditorUI.current.widgets.ColoredText(EditorPalette.error, m_error); + } } private void DrawLayerRows( @@ -50,7 +57,12 @@ private void DrawLayerRows( int definedCount = names.Count(static name => !string.IsNullOrWhiteSpace(name)); DrawLayerToolbar(setting, names, definedCount); Ui.Spacing(); - ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoSavedSettings; + ImGuiTableFlags flags = ImGuiTableFlags.RowBg + | ImGuiTableFlags.BordersInnerH + | ImGuiTableFlags.BordersInnerV + | ImGuiTableFlags.SizingStretchProp + | ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.NoSavedSettings; Ui.PushStyleVar(ImGuiStyleVar.CellPadding, EditorUI.current.widgets.style.cellPadding); if (!Ui.BeginTable("##game_layer_definitions", 3, flags, default(System.Numerics.Vector2), 0f)) { @@ -60,14 +72,24 @@ private void DrawLayerRows( try { - Ui.TableSetupColumn("Slot", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), 48f * EditorUI.current.widgets.style.zoom); + Ui.TableSetupColumn( + "Slot", + (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), + 48f * EditorUI.current.widgets.style.zoom + ); Ui.TableSetupColumn("Name", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize)); - Ui.TableSetupColumn("Action", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), 72f * EditorUI.current.widgets.style.zoom); + Ui.TableSetupColumn( + "Action", + (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), + 72f * EditorUI.current.widgets.style.zoom + ); DrawLayerTableHeader(); for (int index = 0; index < GameLayer.C_MAX_COUNT; index++) { if (!string.IsNullOrWhiteSpace(names[index])) + { DrawLayerRow(setting, names, index); + } } } finally @@ -106,12 +128,18 @@ int index bool committed = DrawTextField("##layer_name", "Layer name", ref name); m_nameBuffers[index] = name; if (committed) + { CommitDefinition(setting, layer, name); + } _ = Ui.TableSetColumnIndex(2); InsetPlainCell(); Vector2 removeSize = new(Ui.MeasureText("Remove").X, Ui.GetFrameHeight()); - if (EditorUI.current.widgets.ClickableText($"remove_layer_{index}", "Remove", removeSize, "Remove this definition while preserving Scene slot assignments.")) - { + if (EditorUI.current.widgets.ClickableText( + $"remove_layer_{index}", + "Remove", + removeSize, + "Remove this definition while preserving Scene slot assignments." + )) { _ = setting.Remove(layer); SynchronizeSlot(setting, layer); m_error = string.Empty; @@ -166,7 +194,13 @@ float width Ui.Dummy(size); Vector2 maximum = minimum + size; Ui.DrawFilledRectangle(minimum, maximum, Ui.GetStyleColor(ImGuiCol.FrameBg), style.frameRounding); - Ui.DrawRectangle(minimum, maximum, Ui.GetStyleColor(ImGuiCol.Border), style.frameRounding, EditorUI.current.widgets.style.borderSize); + Ui.DrawRectangle( + minimum, + maximum, + Ui.GetStyleColor(ImGuiCol.Border), + style.frameRounding, + EditorUI.current.widgets.style.borderSize + ); Vector2 textSize = Ui.MeasureText(value); Ui.DrawText(minimum + (size - textSize) * 0.5f, Ui.GetStyleColor(ImGuiCol.Text), value); } @@ -192,6 +226,7 @@ string label } private static void InsetPlainCell() => Ui.SetCursorPosX(Ui.GetCursorPosX() + Ui.GetLayout().framePadding.X); + private void DrawAddLayer( GameLayerCatalog setting, string? [] names, @@ -211,10 +246,14 @@ int definedCount for (int index = 1; index < GameLayer.C_MAX_COUNT; index++) { if (!string.IsNullOrWhiteSpace(names[index])) + { continue; + } string slot = index.ToString("00", CultureInfo.InvariantCulture); if (Ui.Selectable($"{slot} Layer {index}")) + { CommitDefinition(setting, new GameLayer(index), $"Layer {index}"); + } } } finally @@ -254,7 +293,9 @@ private void SynchronizeBuffers(IReadOnlyList names) } for (int index = 0; index < GameLayer.C_MAX_COUNT; index++) + { m_nameBuffers[index] = names[index] ?? string.Empty; + } m_observedNames = names.ToArray(); } @@ -270,7 +311,9 @@ GameLayer layer { var result = new string? [GameLayer.C_MAX_COUNT]; for (int index = 0; index < GameLayer.C_MAX_COUNT; index++) + { result[index] = stack.GetName(new GameLayer(index)); + } return result; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameObjectLayerSelector.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameObjectLayerSelector.cs index c7cc565ac..7c3eea39c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameObjectLayerSelector.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/GameObjectLayerSelector.cs @@ -1,16 +1,18 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene; using Inno.Scene.Layers; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + /// /// Draws the project layer picker used by GameObject target headers. /// @@ -18,6 +20,7 @@ internal sealed class GameObjectLayerSelector { private readonly SceneProjectSettingsModule m_settings; private readonly SceneEdits m_edits; + /// /// Creates a layer selector backed by the project Settings layer catalog. /// @@ -57,18 +60,26 @@ float width ) { ArgumentNullException.ThrowIfNull(targets); if (targets.Count == 0) + { return; + } GameObject target = targets[0]; bool mixed = targets.Any(value => value.layer != target.layer); GameLayerCatalog stack = m_settings.layerStack; string preview = FormatLayerPreview(stack.GetName(target.layer)); if (mixed) + { preview = "Mixed values"; + } EditorUI.current.widgets.LabelChip("Layer", InspectorTargetStyle.layerLabel); Ui.SameLine(0f, 0f); float selectorWidth = MathF.Max(1f, width); - if (!EditorUI.current.widgets.BeginMenuSelector($"game_object_layer_{target.identity.persistentId:N}", preview, selectorWidth, selectorWidth)) - { + if (!EditorUI.current.widgets.BeginMenuSelector( + $"game_object_layer_{target.identity.persistentId:N}", + preview, + selectorWidth, + selectorWidth + )) { return; } @@ -83,7 +94,9 @@ float width { using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Set Selection Layer"); foreach (GameObject selected in targets) + { m_edits.SetGameObjectLayer(selected, definition.layer); + } transaction.Commit(); } } @@ -104,9 +117,11 @@ float width /// when the layer can be selected. /// internal bool IsLayerDefined(GameLayer layer) => m_settings.layerStack.IsDefined(layer); + private static string FormatLayerLabel( GameLayer layer, string name ) => $"({layer.index}) {name}"; + private static string FormatLayerPreview(string? name) => name ?? "Undefined"; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/SceneProjectSettingsModule.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/SceneProjectSettingsModule.cs index 935eb2405..bdd28150f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/SceneProjectSettingsModule.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Layers/SceneProjectSettingsModule.cs @@ -1,11 +1,10 @@ using System; - using Inno.Core.Diagnostics; using Inno.Core.Settings; using Inno.Editor.Core; +using Inno.Runtime; using Inno.Scene; using Inno.Scene.Layers; -using Inno.Runtime; namespace Inno.Editor.Panel.Inspector; @@ -40,8 +39,9 @@ DiagnosticHub diagnostics /// /// Thrown before the module has started. /// - internal GameLayerCatalog layerStack => m_layerStack - ?? throw new InvalidOperationException("The project layer settings are not available."); + internal GameLayerCatalog layerStack + => m_layerStack + ?? throw new InvalidOperationException("The project layer settings are not available."); /// /// Gets the effective project tag catalog snapshot. @@ -49,8 +49,9 @@ DiagnosticHub diagnostics /// /// Thrown before the module has started. /// - internal GameTagCatalog tagCatalog => m_tagCatalog - ?? throw new InvalidOperationException("The project tag settings are not available."); + internal GameTagCatalog tagCatalog + => m_tagCatalog + ?? throw new InvalidOperationException("The project tag settings are not available."); /// /// Initializes this feature when its owning runtime becomes active. @@ -69,7 +70,9 @@ DiagnosticHub diagnostics protected override void OnUpdate(EditorContext context) { if (m_observedRevision != m_settings.revision) + { RefreshSettings(); + } m_layerDiagnostics.Refresh(layerStack); m_tagDiagnostics.Refresh(tagCatalog); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorCardControls.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorCardControls.cs index 8a9721041..d9f696310 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorCardControls.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorCardControls.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; using Inno.Core.Identity; @@ -9,14 +8,18 @@ using Inno.Editor.Scene; using Inno.Scene; using Inno.Scene.Components; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + internal sealed class InspectorCardControls { private const string C_COMPONENT_PAYLOAD = "INNO_INSPECTOR_COMPONENT"; private const string C_SYSTEM_PAYLOAD = "INNO_INSPECTOR_SYSTEM"; private readonly Logger m_log; + internal InspectorCardControls(LogRouter logs) { ArgumentNullException.ThrowIfNull(logs); @@ -24,6 +27,7 @@ internal InspectorCardControls(LogRouter logs) } internal float GetWidth(bool canRemove) => EditorUI.current.widgets.GetCompactClickableTextSize().X * (canRemove ? 2f : 1f); + internal void DrawComponent( SceneEdits edits, GameComponent component, @@ -40,7 +44,9 @@ Action requestRemove } if (!canRemove) + { return; + } Ui.SameLine(0f, 0f); if (EditorUI.current.widgets.ClickableText($"remove_Component_{componentId:N}", ImGuiIcon.Xmark, "Remove Component")) { @@ -79,8 +85,15 @@ bool dimmed ArgumentNullException.ThrowIfNull(component); ArgumentNullException.ThrowIfNull(title); if (component.identity.runtimeIdentity is not RuntimeIdentity identity) + { return; - _ = EditorUI.current.widgets.DragDropSource(C_COMPONENT_PAYLOAD, identity, () => DrawDragPreview(title, dimmed), allowHoldToOpenOthers: false); + } + _ = EditorUI.current.widgets.DragDropSource( + C_COMPONENT_PAYLOAD, + identity, + () => DrawDragPreview(title, dimmed), + allowHoldToOpenOthers: false + ); } internal void DrawSystemDragSource( @@ -91,8 +104,15 @@ bool dimmed ArgumentNullException.ThrowIfNull(system); ArgumentNullException.ThrowIfNull(title); if (system.identity.runtimeIdentity is not RuntimeIdentity identity) + { return; - _ = EditorUI.current.widgets.DragDropSource(C_SYSTEM_PAYLOAD, identity, () => DrawDragPreview(title, dimmed), allowHoldToOpenOthers: false); + } + _ = EditorUI.current.widgets.DragDropSource( + C_SYSTEM_PAYLOAD, + identity, + () => DrawDragPreview(title, dimmed), + allowHoldToOpenOthers: false + ); } internal void DrawComponentDropTarget( @@ -106,25 +126,30 @@ Vector2 cardMaximum ArgumentNullException.ThrowIfNull(interactions); ArgumentNullException.ThrowIfNull(edits); ArgumentNullException.ThrowIfNull(target); - DrawDropTarget(C_COMPONENT_PAYLOAD, $"component_{target.identity.persistentId:N}", interactions, cardMinimum, cardMaximum, source => source is GameComponent component - && ReferenceEquals( - component.gameObject, - target.gameObject - ) - && !ReferenceEquals( - component, - target - ), ( - source, - insertAfter - ) => + DrawDropTarget( + C_COMPONENT_PAYLOAD, + $"component_{target.identity.persistentId:N}", + interactions, + cardMinimum, + cardMaximum, + source => ( + source is GameComponent component + && ReferenceEquals(component.gameObject, target.gameObject) + && !ReferenceEquals(component, target) + ), + ( + source, + insertAfter + ) => { var component = (GameComponent)source; int sourceIndex = component.gameObject.GetComponentIndex(component); int insertionBoundary = targetIndex + (insertAfter ? 1 : 0); int destinationIndex = insertionBoundary > sourceIndex ? insertionBoundary - 1 : insertionBoundary; edits.SetComponentIndex(component, destinationIndex); - }, "Component reorder"); + }, + "Component reorder" + ); } internal void DrawSystemDropTarget( @@ -140,25 +165,30 @@ Vector2 cardMaximum ArgumentNullException.ThrowIfNull(edits); ArgumentNullException.ThrowIfNull(scene); ArgumentNullException.ThrowIfNull(target); - DrawDropTarget(C_SYSTEM_PAYLOAD, $"system_{target.identity.persistentId:N}", interactions, cardMinimum, cardMaximum, source => source is GameSystem system - && !ReferenceEquals( - system, - target - ) - && IsOwnedBy( - scene, - system - ), ( - source, - insertAfter - ) => + DrawDropTarget( + C_SYSTEM_PAYLOAD, + $"system_{target.identity.persistentId:N}", + interactions, + cardMinimum, + cardMaximum, + source => ( + source is GameSystem system + && !ReferenceEquals(system, target) + && IsOwnedBy(scene, system) + ), + ( + source, + insertAfter + ) => { var system = (GameSystem)source; int sourceIndex = scene.GetSystemIndex(system); int insertionBoundary = targetIndex + (insertAfter ? 1 : 0); int destinationIndex = insertionBoundary > sourceIndex ? insertionBoundary - 1 : insertionBoundary; edits.SetSystemIndex(scene, system, destinationIndex); - }, "System reorder"); + }, + "System reorder" + ); } private void DrawDropTarget( @@ -187,7 +217,9 @@ string operation drawDefaultHighlight: false ); if (!isPreviewing && !delivered) + { return; + } if (!interactions.TryResolveIdentity(identity, out IdentityObject? source) || source is null || !accepts(source)) { return; @@ -196,9 +228,13 @@ string operation bool insertAfter = Ui.GetMousePos().Y >= (cardMinimum.Y + cardMaximum.Y) * 0.5f; float markerY = insertAfter ? cardMaximum.Y : cardMinimum.Y; if (isPreviewing) + { EditorUI.current.widgets.InsertionLine(cardMinimum.X, cardMaximum.X, markerY); + } if (delivered) + { TryEdit(() => move(source, insertAfter), operation); + } } private static void DrawDragPreview( @@ -213,11 +249,20 @@ bool dimmed padding.X * 2f + gripSize.X + EditorUI.current.widgets.style.headerControlSpacing + titleSize.X, MathF.Max(gripSize.Y, titleSize.Y) + padding.Y * 2f ); - Ui.DrawFilledRectangle(origin, origin + size, Ui.ToPackedColor(EditorPalette.cardHeader), EditorUI.current.widgets.style.frameRounding); + Ui.DrawFilledRectangle( + origin, + origin + size, + Ui.ToPackedColor(EditorPalette.cardHeader), + EditorUI.current.widgets.style.frameRounding + ); uint color = Ui.ToPackedColor(dimmed ? EditorPalette.cardDisabledText : EditorPalette.text); Vector2 textOrigin = origin + padding; Ui.DrawText(textOrigin, color, ImGuiIcon.GripVertical); - Ui.DrawText(new Vector2(textOrigin.X + gripSize.X + EditorUI.current.widgets.style.headerControlSpacing, textOrigin.Y), color, title); + Ui.DrawText( + new Vector2(textOrigin.X + gripSize.X + EditorUI.current.widgets.style.headerControlSpacing, textOrigin.Y), + color, + title + ); Ui.Dummy(size); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorLockControl.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorLockControl.cs index c8cdcc93e..9cf8e8597 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorLockControl.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorLockControl.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Identity; using Inno.Editor.Interactions; using Inno.Scene; @@ -70,7 +69,9 @@ object displayedTarget } if (!IsValid(displayedTarget)) + { return; + } m_isLocked = true; if (displayedTarget is IdentityObject identityObject) { @@ -105,14 +106,18 @@ private void Clear() if (m_lockedIdentity is RuntimeIdentity identity) { if (interactions.TryResolveIdentity(identity, out IdentityObject? target)) + { return target; + } return interactions.TryResolveIdentity(identity.domainId, m_lockedPersistentId, out target) - ? target - : null; + ? target + : null; } if (m_collectibleTarget is not null) + { return m_collectibleTarget.TryGetTarget(out object? target) ? target : null; + } return m_lockedTarget; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorPanel.cs index aa7077e08..44fe08ff1 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorPanel.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; using Inno.Core.Logging; @@ -10,9 +9,12 @@ using Inno.Editor.PlayMode; using Inno.Editor.Scene; using Inno.Scene; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + /// /// Draws the registered inspector for the current editor selection. /// @@ -26,10 +28,12 @@ internal sealed class InspectorPanel : EditorPanel private readonly InspectorTargetHeader m_targetHeader; private readonly Logger m_log; private string m_failureState = string.Empty; + /// /// Gets whether use window padding is enabled for this implementation. /// public override bool useWindowPadding => false; + /// /// Lets the inspector content child own vertical scrolling. /// @@ -96,7 +100,10 @@ protected override void OnDraw(EditorContext context) private void DrawContent(EditorContext context) { - object? target = m_targetHeader.Resolve(m_interactions, m_interactions.selection.count > 1 ? m_interactions.selection.Capture() : m_interactions.selection.selectedTarget); + object? target = m_targetHeader.Resolve( + m_interactions, + m_interactions.selection.count > 1 ? m_interactions.selection.Capture() : m_interactions.selection.selectedTarget + ); if (target is null) { m_failureState = string.Empty; @@ -104,8 +111,10 @@ private void DrawContent(EditorContext context) return; } - if (!m_inspection.TryResolve(context, target, out IInspectionDrawer? drawer, out InspectionDrawContext? drawContext) || drawer is null || drawContext is null) - { + if (!m_inspection.TryResolve(context, target, out IInspectionDrawer? drawer, out InspectionDrawContext? drawContext) + || drawer is null + || drawContext is null + ) { m_failureState = string.Empty; EditorUI.current.widgets.Hint($"No inspector drawer is registered for {target.GetType().Name}."); return; @@ -136,7 +145,11 @@ private void DrawContent(EditorContext context) string failureState = $"{target.GetType().FullName}:{exception}"; if (!string.Equals(m_failureState, failureState, StringComparison.Ordinal)) { - m_log.Write(LogLevel.Error, "Inspector failed for target '{0}': {1}", [target.GetType().FullName ?? target.GetType().Name, exception]); + m_log.Write( + LogLevel.Error, + "Inspector failed for target '{0}': {1}", + [target.GetType().FullName ?? target.GetType().Name, exception] + ); m_failureState = failureState; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs index 8a571c9a9..1d3279970 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs @@ -1,13 +1,15 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; -using Inno.Editor.Inspection; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + /// /// Draws the persistent identity header shared by every Inspector target type. /// @@ -15,6 +17,7 @@ internal sealed class InspectorTargetHeader { private const int C_NAME_BUFFER_SIZE = 512; private readonly InspectorLockControl m_lock = new(); + /// /// Resolves the target that should be presented after applying Inspector lock state. /// @@ -31,6 +34,7 @@ internal sealed class InspectorTargetHeader EditorInteractions interactions, object? selectedTarget ) => m_lock.Resolve(interactions, selectedTarget); + /// /// Draws the common framed header for a resolved Inspector target. /// @@ -67,7 +71,9 @@ internal void Draw( } if (notice is null) + { return; + } Ui.Spacing(); EditorUI.current.widgets.HelpBox(notice, ImGuiIcon.CircleInfo, new Vector4(0.42f, 0.66f, 0.88f, EditorPalette.opacityOpaque)); }, spanWindowPadding: true); @@ -116,8 +122,12 @@ float rowHeight if (nameSetter is not null) { Ui.SetNextItemWidth(nameWidth); - if (Ui.InputText($"##inspector_target_name_{GetTargetId(context.target)}", ref name, C_NAME_BUFFER_SIZE, ImGuiInputTextFlags.None)) - { + if (Ui.InputText( + $"##inspector_target_name_{GetTargetId(context.target)}", + ref name, + C_NAME_BUFFER_SIZE, + ImGuiInputTextFlags.None + )) { nameSetter(name); } @@ -145,7 +155,9 @@ float rowHeight string lockIcon = m_lock.isLocked ? ImGuiIcon.Lock : ImGuiIcon.LockOpen; string tooltip = m_lock.isLocked ? "Unlock Inspector" : "Lock Inspector"; if (EditorUI.current.widgets.ClickableIcon("inspector_target_lock", lockIcon, tooltip)) + { m_lock.Toggle(context.interactions, context.target); + } } private static void DrawIcon( @@ -168,11 +180,18 @@ private static void DrawCustomRow( float rowHeight ) { ImGuiWindowFlags flags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoSavedSettings; - bool visible = Ui.BeginChild($"##inspector_target_custom_{GetTargetId(context.target)}", new Vector2(0f, rowHeight), ImGuiChildFlags.None, flags); + bool visible = Ui.BeginChild( + $"##inspector_target_custom_{GetTargetId(context.target)}", + new Vector2(0f, rowHeight), + ImGuiChildFlags.None, + flags + ); try { if (visible) + { drawer.DrawHeader(context); + } } finally { @@ -180,5 +199,6 @@ float rowHeight } } - private static string GetTargetId(object target) => $"{target.GetType().FullName}_{System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(target)}"; + private static string GetTargetId(object target) + => $"{target.GetType().FullName}_{System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(target)}"; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTypeOrigin.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTypeOrigin.cs index b500609c3..49d559b11 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTypeOrigin.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTypeOrigin.cs @@ -1,12 +1,14 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Reflection; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Extensibility.Modules; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + internal static class InspectorTypeOrigin { internal static void Draw(Type type) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Properties/ScriptingApi.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Properties/ScriptingApi.cs index 7113b8c79..b94f0077b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Properties/ScriptingApi.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Editor.Panel.Inspector; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Inspection", - "Inno.Editor.Panel.Inspector", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Inspection", "Inno.Editor.Panel.Inspector", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EngineObjectReferenceDropTarget), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(AssetReferenceDropTarget), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/AssetReferencePropertyDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/AssetReferencePropertyDrawer.cs index 6734731c7..da7e2c97c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/AssetReferencePropertyDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/AssetReferencePropertyDrawer.cs @@ -1,19 +1,21 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.IO; -using System.Runtime.CompilerServices; using System.Numerics; +using System.Runtime.CompilerServices; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Core; -using Inno.Editor.Inspection; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [PropertyDrawer(typeof(AssetObject), useForChildren: true, priority: 100)] internal sealed class AssetReferencePropertyDrawer : IPropertyDrawer, IDisposable { @@ -22,6 +24,7 @@ internal sealed class AssetReferencePropertyDrawer : IPropertyDrawer, IDisposabl private readonly AssetPipeline m_assets; private ConditionalWeakTable m_candidatesByType = new(); private readonly Dictionary m_searchByPath = new(StringComparer.Ordinal); + internal AssetReferencePropertyDrawer(AssetPipeline assets) { m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); @@ -54,40 +57,51 @@ public void Draw(PropertyDrawContext context) object? currentValue = context.GetValue(); Guid persistentId = ReadPersistentId(currentValue); AssetCandidate? selected = Array.Find(candidates, candidate => candidate.persistentId == persistentId); - string preview = persistentId == Guid.Empty ? "None" : currentValue is AssetObject { isMissing: true } missing ? $"Missing {missing.GetType().Name} [{persistentId}]" : selected is null ? $"Missing ({persistentId})" : selected.displayName; + string preview = persistentId == Guid.Empty + ? "None" + : currentValue is AssetObject { isMissing: true } missing + ? $"Missing {missing.GetType().Name} [{persistentId}]" + : selected is null ? $"Missing ({persistentId})" : selected.displayName; bool open = EditorUI.current.widgets.BeginBoundedCombo($"##{context.path}", preview); Vector2 dropMinimum = Ui.GetItemMinimum(); Vector2 dropMaximum = Ui.GetItemMaximum(); - EditorDropWidgetResult drop = EditorDragDropRenderer.Target(context.interactions.For(InspectorInteractionIds.C_ASSET_REFERENCE_AREA, new AssetReferenceDropTarget(assetType, persistentIdToAssign => - { - AssetCandidate? dropped = Array.Find(candidates, candidate => candidate.persistentId == persistentIdToAssign); - if (dropped is not null) - AssignAsset(context, assetType, dropped); - }))); + EditorDropWidgetResult drop = EditorDragDropRenderer.Target( + context.interactions.For( + InspectorInteractionIds.C_ASSET_REFERENCE_AREA, + new AssetReferenceDropTarget(assetType, persistentIdToAssign => + { + AssetCandidate? dropped = Array.Find(candidates, candidate => candidate.persistentId == persistentIdToAssign); + if (dropped is not null) + { + AssignAsset(context, assetType, dropped); + } + }) + ) + ); if (drop.isPreviewing && drop.status.canDrop) + { EditorUI.current.widgets.DropTargetHighlight(dropMinimum, dropMaximum); + } if (!open) + { return; + } try { string search = m_searchByPath.TryGetValue(context.path, out string? existingSearch) ? existingSearch : string.Empty; _ = EditorUI.current.widgets.SearchInput(context.path, "Search assets...", ref search, C_SEARCH_BUFFER_SIZE); m_searchByPath[context.path] = search; if (Ui.Selectable("None", persistentId == Guid.Empty)) + { context.SetValue(null); + } for (int i = 0; i < candidates.Length; i++) { AssetCandidate candidate = candidates[i]; if (!string.IsNullOrWhiteSpace(search) - && candidate.displayName.IndexOf( - search, - StringComparison.OrdinalIgnoreCase - ) < 0 - && candidate.fullPath.IndexOf( - search, - StringComparison.OrdinalIgnoreCase - ) < 0) - { + && candidate.displayName.IndexOf(search, StringComparison.OrdinalIgnoreCase) < 0 + && candidate.fullPath.IndexOf(search, StringComparison.OrdinalIgnoreCase) < 0 + ) { continue; } @@ -114,14 +128,18 @@ private AssetCandidate[] GetCandidates(Type targetAssetType) lock (m_sync) { if (m_candidatesByType.TryGetValue(targetAssetType, out CandidatesBox? cached)) + { return cached.candidates; + } IReadOnlyList entries = m_assets.GetFileSystemEntries(includeDirectories: false); var candidates = new List(entries.Count); for (int i = 0; i < entries.Count; i++) { AssetFileEntry entry = entries[i]; - if (!m_assets.TryGetAssetType(entry.assetPath, out Type? assetType) || assetType is null || !targetAssetType.IsAssignableFrom(assetType)) - { + if (!m_assets.TryGetAssetType(entry.assetPath, out Type? assetType) + || assetType is null + || !targetAssetType.IsAssignableFrom(assetType) + ) { continue; } @@ -144,13 +162,16 @@ private AssetCandidate[] GetCandidates(Type targetAssetType) } private static Guid ReadPersistentId(object? reference) => reference is AssetObject asset ? asset.identity.persistentId : Guid.Empty; + private void AssignAsset( PropertyDrawContext context, Type assetType, AssetCandidate candidate ) { if (ReadPersistentId(context.GetValue()) == candidate.persistentId) + { return; + } object asset = m_assets.Load(candidate.assetPath, assetType); context.SetValue(asset); } @@ -158,7 +179,9 @@ AssetCandidate candidate private void OnAssetsChanged(AssetChangeSet changes) { lock (m_sync) + { m_candidatesByType = new ConditionalWeakTable(); + } } private sealed record AssetCandidate( @@ -167,5 +190,6 @@ private sealed record AssetCandidate( string displayName, string fullPath ); + private sealed record CandidatesBox(AssetCandidate[] candidates); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs index 1a1d05064..9176e24a9 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs @@ -1,17 +1,19 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using Inno.Editor.Core; -using Inno.Editor.Inspection; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; +using Inno.Editor.Interactions; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [PropertyDrawer(typeof(GameObject), useForChildren: true, priority: 100)] [PropertyDrawer(typeof(GameComponent), useForChildren: true, priority: 100)] internal sealed class EngineObjectReferencePropertyDrawer : IPropertyDrawer @@ -19,6 +21,7 @@ internal sealed class EngineObjectReferencePropertyDrawer : IPropertyDrawer private const nuint C_SEARCH_BUFFER_SIZE = 256; private readonly Dictionary m_searchByPath = new(StringComparer.Ordinal); private readonly RuntimeSession m_runtimeSession; + internal EngineObjectReferencePropertyDrawer(RuntimeSession runtimeSession) { m_runtimeSession = runtimeSession ?? throw new ArgumentNullException(nameof(runtimeSession)); @@ -37,16 +40,25 @@ public void Draw(PropertyDrawContext context) List candidates = CollectCandidates(targetType); string preview = selected is null || selected.isDestroyed ? "None" : GetDisplayName(selected); bool open = EditorUI.current.widgets.BeginBoundedCombo($"##{context.path}", preview); - _ = EditorDragDropRenderer.Target(context.interactions.For(InspectorInteractionIds.C_ENGINE_OBJECT_REFERENCE_AREA, new EngineObjectReferenceDropTarget(targetType, value => context.SetValue(value)))); + _ = EditorDragDropRenderer.Target( + context.interactions.For( + InspectorInteractionIds.C_ENGINE_OBJECT_REFERENCE_AREA, + new EngineObjectReferenceDropTarget(targetType, value => context.SetValue(value)) + ) + ); if (!open) + { return; + } try { string search = m_searchByPath.TryGetValue(context.path, out string? currentSearch) ? currentSearch : string.Empty; _ = EditorUI.current.widgets.SearchInput(context.path, "Search scene objects...", ref search, C_SEARCH_BUFFER_SIZE); m_searchByPath[context.path] = search; if (Ui.Selectable("None", selected is null)) + { context.SetValue(null); + } for (int i = 0; i < candidates.Count; i++) { EngineObject candidate = candidates[i]; @@ -57,7 +69,9 @@ public void Draw(PropertyDrawContext context) } if (Ui.Selectable(displayName, ReferenceEquals(candidate, selected))) + { context.SetValue(candidate); + } } } finally @@ -75,12 +89,16 @@ private List CollectCandidates(Type targetType) { GameObject gameObject = objects[objectIndex]; if (targetType.IsInstanceOfType(gameObject)) + { candidates.Add(gameObject); + } IReadOnlyList components = gameObject.GetComponents(); for (int componentIndex = 0; componentIndex < components.Count; componentIndex++) { if (targetType.IsInstanceOfType(components[componentIndex])) + { candidates.Add(components[componentIndex]); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs index 735f32075..763da8164 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs @@ -4,12 +4,14 @@ using Inno.Scene; namespace Inno.Editor.Panel.Inspector; + /// /// Adapts generic inspection property edits to compact Scene history records. /// internal sealed class SceneInspectionPropertyEditService : IInspectionPropertyEditService { private readonly SceneEdits m_edits; + /// /// Creates the Scene property edit adapter. /// @@ -31,7 +33,8 @@ public bool ChangeProperty( string? componentName ) { ArgumentNullException.ThrowIfNull(owner); - EngineObject sceneObject = owner as EngineObject ?? throw new ArgumentException($"Scene property edits require an '{typeof(EngineObject).FullName}' owner.", nameof(owner)); + EngineObject sceneObject = owner as EngineObject + ?? throw new ArgumentException($"Scene property edits require an '{typeof(EngineObject).FullName}' owner.", nameof(owner)); return m_edits.ChangeProperty(sceneObject, propertyName, mutation, historyName, mergeKey); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/InspectionDrawerActivator.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/InspectionDrawerActivator.cs index 4784c6831..75d5ab1eb 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/InspectionDrawerActivator.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/InspectionDrawerActivator.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Reflection; - using Inno.Editor.Inspection; namespace Inno.Editor.Panel.Inspector; @@ -23,7 +22,9 @@ internal InspectionDrawerActivator(params object[] dependencies) { ArgumentNullException.ThrowIfNull(dependencies); if (dependencies.Any(static dependency => dependency is null)) + { throw new ArgumentException("Inspection drawer dependencies cannot contain null.", nameof(dependencies)); + } m_dependencies = [.. dependencies]; } @@ -40,21 +41,26 @@ internal IInspectionDrawer Create(Type drawerType) { ArgumentNullException.ThrowIfNull(drawerType); ConstructorInfo[] constructors = drawerType.GetConstructors( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic + ); if (constructors.Length != 1) { throw new InvalidOperationException( - $"Inspection drawer '{drawerType.FullName}' must declare exactly one constructor."); + $"Inspection drawer '{drawerType.FullName}' must declare exactly one constructor." + ); } ParameterInfo[] parameters = constructors[0].GetParameters(); var arguments = new object?[parameters.Length]; for (int i = 0; i < parameters.Length; i++) + { arguments[i] = Resolve(drawerType, parameters[i].ParameterType); + } return constructors[0].Invoke(arguments) as IInspectionDrawer ?? throw new InvalidOperationException( - $"Inspection drawer '{drawerType.FullName}' does not implement " + - $"'{typeof(IInspectionDrawer).FullName}'."); + $"Inspection drawer '{drawerType.FullName}' does not implement " + + $"'{typeof(IInspectionDrawer).FullName}'." + ); } private object Resolve( @@ -68,12 +74,14 @@ Type dependencyType { 1 => matches[0], 0 => throw new InvalidOperationException( - $"Inspection drawer '{drawerType.FullName}' requests unavailable dependency " + - $"'{dependencyType.FullName}'. Drawers should normally use InspectionDrawContext, " + - "or request one dependency supplied by the Inspector composition root."), + $"Inspection drawer '{drawerType.FullName}' requests unavailable dependency " + + $"'{dependencyType.FullName}'. Drawers should normally use InspectionDrawContext, " + + "or request one dependency supplied by the Inspector composition root." + ), _ => throw new InvalidOperationException( - $"Inspection drawer '{drawerType.FullName}' has ambiguous dependency " + - $"'{dependencyType.FullName}'.") + $"Inspection drawer '{drawerType.FullName}' has ambiguous dependency " + + $"'{dependencyType.FullName}'." + ) }; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs index b7ecd068c..37a0e1061 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs @@ -1,8 +1,6 @@ using System; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Types; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Core; @@ -10,6 +8,7 @@ using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Settings; +using Inno.Extensibility.Types; using Inno.Runtime; namespace Inno.Editor.Panel.Inspector; @@ -94,24 +93,23 @@ LogRouter logs classificationSettings, settings, serialization, - logs); + logs + ); m_inspectors = new InspectionDrawerRegistry(interactions, activator.Create, types, serialization); - m_properties = new PropertyDrawerRegistry( - interactions, - types, - serialization, - [assets, runtimeSession]); + m_properties = new PropertyDrawerRegistry(interactions, types, serialization, [assets, runtimeSession]); m_attributes = new InspectorAttributeDrawerRegistry( interactions, types, serialization, - [assets, runtimeSession]); + [assets, runtimeSession] + ); m_renderer = new SerializedPropertyRenderer( m_properties, m_attributes, interactions, new SceneInspectionPropertyEditService(edits), - logs); + logs + ); } internal bool TryResolve( @@ -120,24 +118,14 @@ internal bool TryResolve( out IInspectionDrawer? drawer, out InspectionDrawContext? drawContext ) { - if (target is AssetFileEntry { isDirectory: false } entry && - m_assets.TryLoad(entry.assetPath, out AssetObject? asset) && - asset is not null && - m_inspectors.TryResolveExact( - editorContext, - asset, - m_renderer, - out drawer, - out drawContext)) - { + if (target is AssetFileEntry { isDirectory: false } entry + && m_assets.TryLoad(entry.assetPath, out AssetObject? asset) + && asset is not null + && m_inspectors.TryResolveExact(editorContext, asset, m_renderer, out drawer, out drawContext) + ) { return true; } - return m_inspectors.TryResolve( - editorContext, - target, - m_renderer, - out drawer, - out drawContext); + return m_inspectors.TryResolve(editorContext, target, m_renderer, out drawer, out drawContext); } /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs index d35ee1c92..f1b852bbd 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs @@ -1,21 +1,23 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Numerics; -using Inno.Core.Serialization; using Inno.Core.Logging; +using Inno.Core.Serialization; using Inno.Editor.Core; -using Inno.Editor.Inspection; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; +using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Settings; using Inno.Scene; using Inno.Scene.Components; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [InspectionDrawer(typeof(GameObject))] internal sealed class GameObjectInspectionDrawer : InspectionDrawer { @@ -27,6 +29,7 @@ internal sealed class GameObjectInspectionDrawer : InspectionDrawer private readonly GameObjectLayerSelector m_layerSelector; private readonly EditorSettings m_settings; private string m_componentSearch = string.Empty; + /// /// Creates a GameObject drawer backed by the current project classification settings. /// @@ -86,6 +89,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, GameObject target ) => (target.name, name => m_edits.RenameGameObject(target, name)); + /// /// Renders the header presentation for the current editor frame. /// @@ -100,8 +104,11 @@ protected override void DrawHeader( GameObject target ) { bool active = target.activeSelf; - if (EditorUI.current.widgets.CompactCheckbox($"target_active_{target.identity.persistentId:N}", ref active, tooltip: "Enable or disable this GameObject.")) - { + if (EditorUI.current.widgets.CompactCheckbox( + $"target_active_{target.identity.persistentId:N}", + ref active, + tooltip: "Enable or disable this GameObject." + )) { m_edits.SetGameObjectActive(target, active); } @@ -111,7 +118,10 @@ GameObject target float available = Ui.GetContentRegionAvailable().X; float tagLabelWidth = EditorUI.current.widgets.GetLabelChipSize("Tag").X; float layerLabelWidth = EditorUI.current.widgets.GetLabelChipSize("Layer").X; - float controlWidth = MathF.Max(1f, (available - tagLabelWidth - layerLabelWidth - EditorUI.current.widgets.style.headerSectionSpacing) * 0.5f); + float controlWidth = MathF.Max( + 1f, + (available - tagLabelWidth - layerLabelWidth - EditorUI.current.widgets.style.headerSectionSpacing) * 0.5f + ); m_tagSelector.Draw([target], context.interactions, controlWidth); Ui.SameLine(0f, EditorUI.current.widgets.style.headerSectionSpacing); m_layerSelector.Draw([target], context.interactions, controlWidth); @@ -140,7 +150,9 @@ GameObject gameObject if (!m_layerSelector.IsLayerDefined(gameObject.layer)) { Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); - EditorUI.current.widgets.WrappedText($"Layer slot {gameObject.layer.index} is not defined in the current project settings. " + "Choose Default or restore that layer definition."); + EditorUI.current.widgets.WrappedText( + $"Layer slot {gameObject.layer.index} is not defined in the current project settings. " + "Choose Default or restore that layer definition." + ); Ui.PopStyleColor(); Ui.Spacing(); } @@ -148,7 +160,9 @@ GameObject gameObject if (!m_tagSelector.IsTagDefined(gameObject.tag)) { Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); - EditorUI.current.widgets.WrappedText($"Tag '{gameObject.tag}' is not defined in the current Project Settings. " + "Choose another tag or restore that tag definition."); + EditorUI.current.widgets.WrappedText( + $"Tag '{gameObject.tag}' is not defined in the current Project Settings. " + "Choose another tag or restore that tag definition." + ); Ui.PopStyleColor(); Ui.Spacing(); } @@ -176,7 +190,9 @@ GameObject gameObject GameComponent component = components[i]; Type componentType = component.GetType(); MissingGameComponent? missing = component as MissingGameComponent; - IReadOnlyList properties = missing is null ? m_serialization.GetProperties(component) : Array.Empty(); + IReadOnlyList properties = missing is null + ? m_serialization.GetProperties(component) + : Array.Empty(); string componentId = component.identity.persistentId.ToString("N"); GameBehavior? behavior = component as GameBehavior; var editorTarget = component; @@ -185,25 +201,49 @@ GameObject gameObject bool dimmed = behavior is { enabled: false }; Vector2 cardMinimum = default; Vector2 headerMaximum = default; - bool open = EditorUI.current.widgets.CollapsingCard(componentId, title, behavior is not null ? () => - { - bool enabled = behavior.enabled; - if (EditorUI.current.widgets.CompactCheckbox($"enabled_{componentId}", ref enabled, tooltip: "Enable or disable this component.")) + bool open = EditorUI.current.widgets.CollapsingCard( + componentId, + title, + behavior is not null + ? () => + { + bool enabled = behavior.enabled; + if (EditorUI.current.widgets.CompactCheckbox( + $"enabled_{componentId}", + ref enabled, + tooltip: "Enable or disable this component." + )) { + _ = m_edits.ChangeProperty( + behavior, + "enabled", + () => behavior.enabled = enabled, + enabled ? "Enable Component" : "Disable Component", + mergeKey: null + ); + } + } + : null, + () => m_cardControls.DrawComponent( + m_edits, + component, + canRemove, + () => context.interactions + .For(InspectorInteractionIds.C_COMPONENT_AREA, editorTarget) + .Enqueue(InspectorInteractionIds.C_REMOVE_COMPONENT) + ), + dimmed: dimmed, + trailingControlWidth: m_cardControls.GetWidth(canRemove), + drawContextMenu: () => { - _ = m_edits.ChangeProperty(behavior, "enabled", () => behavior.enabled = enabled, enabled ? "Enable Component" : "Disable Component", mergeKey: null); + cardMinimum = Ui.GetItemMinimum(); + headerMaximum = Ui.GetItemMaximum(); + _ = EditorUI.current.menus.ContextMenu( + $"##component_menu_{componentId}", + context.interactions.For(InspectorInteractionIds.C_COMPONENT_AREA, editorTarget) + ); + m_cardControls.DrawComponentDragSource(component, title, dimmed); } - } : null, () => m_cardControls.DrawComponent( - m_edits, - component, - canRemove, - () => context.interactions.For(InspectorInteractionIds.C_COMPONENT_AREA, editorTarget).Enqueue(InspectorInteractionIds.C_REMOVE_COMPONENT) - ), dimmed: dimmed, trailingControlWidth: m_cardControls.GetWidth(canRemove), drawContextMenu: () => - { - cardMinimum = Ui.GetItemMinimum(); - headerMaximum = Ui.GetItemMaximum(); - _ = EditorUI.current.menus.ContextMenu($"##component_menu_{componentId}", context.interactions.For(InspectorInteractionIds.C_COMPONENT_AREA, editorTarget)); - m_cardControls.DrawComponentDragSource(component, title, dimmed); - }); + ); Vector2 cardMaximum = headerMaximum; if (open) { @@ -213,13 +253,17 @@ GameObject gameObject if (missing is not null) { Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); - EditorUI.current.widgets.WrappedText($"Missing component script ({missing.missingType.stableId:D}). " + "Its serialized state is preserved and will recover automatically when the type returns."); + EditorUI.current.widgets.WrappedText( + $"Missing component script ({missing.missingType.stableId:D}). " + "Its serialized state is preserved and will recover automatically when the type returns." + ); Ui.PopStyleColor(); return; } if (context.TryDrawInline(component)) + { return; + } if (properties.Count == 0) { InspectorTypeOrigin.Draw(componentType); @@ -228,7 +272,12 @@ GameObject gameObject for (int propertyIndex = 0; propertyIndex < properties.Count; propertyIndex++) { - context.properties.Draw(context.editorContext, component, $"gameObject.{gameObject.identity.persistentId:N}.{componentId}", properties[propertyIndex]); + context.properties.Draw( + context.editorContext, + component, + $"gameObject.{gameObject.identity.persistentId:N}.{componentId}", + properties[propertyIndex] + ); } }), dimmed: dimmed); cardMaximum = Ui.GetItemMaximum(); @@ -251,8 +300,12 @@ GameObject gameObject Ui.OpenPopup("##add_component_popup"); } - if (!EditorUI.current.widgets.BeginSearchPopup("##add_component_popup", ref m_componentSearch, "Search components...", C_SEARCH_BUFFER_SIZE)) - { + if (!EditorUI.current.widgets.BeginSearchPopup( + "##add_component_popup", + ref m_componentSearch, + "Search components...", + C_SEARCH_BUFFER_SIZE + )) { return; } @@ -260,7 +313,9 @@ GameObject gameObject { EditorInteraction interaction = context.interactions.For(InspectorInteractionIds.C_COMPONENT_AREA, gameObject); if (EditorUI.current.menus.DrawSearchItems(interaction, interaction.BuildMenu().items, m_componentSearch)) + { Ui.CloseCurrentPopup(); + } } finally { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectTagSelector.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectTagSelector.cs index 1478f8a5f..262f777d0 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectTagSelector.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectTagSelector.cs @@ -1,15 +1,17 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + /// /// Draws the project-defined tag picker used by GameObject target headers. /// @@ -17,6 +19,7 @@ internal sealed class GameObjectTagSelector { private readonly SceneProjectSettingsModule m_settings; private readonly SceneEdits m_edits; + /// /// Creates a tag selector backed by the effective Project Settings snapshot. /// @@ -56,18 +59,26 @@ float width ) { ArgumentNullException.ThrowIfNull(targets); if (targets.Count == 0) + { return; + } GameObject target = targets[0]; bool mixed = targets.Any(value => value.tag != target.tag); IReadOnlyList tags = m_settings.tagCatalog.GetTags(); string preview = m_settings.tagCatalog.IsDefined(target.tag) ? target.tag : $"{target.tag} (Undefined)"; if (mixed) + { preview = "Mixed values"; + } EditorUI.current.widgets.LabelChip("Tag", InspectorTargetStyle.tagLabel); Ui.SameLine(0f, 0f); float selectorWidth = MathF.Max(1f, width); - if (!EditorUI.current.widgets.BeginMenuSelector($"game_object_tag_{target.identity.persistentId:N}", preview, selectorWidth, selectorWidth)) - { + if (!EditorUI.current.widgets.BeginMenuSelector( + $"game_object_tag_{target.identity.persistentId:N}", + preview, + selectorWidth, + selectorWidth + )) { return; } @@ -80,7 +91,9 @@ float width { using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Set Selection Tag"); foreach (GameObject selected in targets) + { m_edits.SetGameObjectTag(selected, tag); + } transaction.Commit(); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs index 08f698ef5..979d8b89c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs @@ -1,20 +1,22 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Numerics; -using Inno.Core.Serialization; using Inno.Core.Logging; +using Inno.Core.Serialization; using Inno.Editor.Core; -using Inno.Editor.Inspection; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; +using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Settings; using Inno.Scene; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [InspectionDrawer(typeof(GameScene))] internal sealed class GameSceneInspectionDrawer : InspectionDrawer { @@ -24,6 +26,7 @@ internal sealed class GameSceneInspectionDrawer : InspectionDrawer private readonly EditorSettings m_settings; private readonly SerializationRegistry m_serialization; private string m_systemSearch = string.Empty; + /// /// Creates a Scene drawer backed by the Scene editing service. /// @@ -75,6 +78,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, GameScene target ) => (target.name, name => m_edits.RenameScene(target, name)); + /// /// Renders the header presentation for the current editor frame. /// @@ -88,6 +92,7 @@ protected override void DrawHeader( InspectionDrawContext context, GameScene target ) => Ui.Text(target.isLoaded ? "Loaded Scene" : "Scene"); + /// /// Renders the value presentation for the current editor frame. /// @@ -130,32 +135,58 @@ GameScene scene { GameSystem system = systems[i]; MissingGameSystem? missing = system as MissingGameSystem; - IReadOnlyList properties = missing is null ? m_serialization.GetProperties(system) : Array.Empty(); + IReadOnlyList properties = missing is null + ? m_serialization.GetProperties(system) + : Array.Empty(); string systemId = system.identity.persistentId.ToString("N"); var editorTarget = system; string title = missing?.missingTypeName ?? system.GetType().Name; bool dimmed = !system.enabled; Vector2 cardMinimum = default; Vector2 headerMaximum = default; - bool open = EditorUI.current.widgets.CollapsingCard(systemId, title, missing is null ? () => - { - bool enabled = system.enabled; - if (EditorUI.current.widgets.CompactCheckbox($"enabled_{systemId}", ref enabled, tooltip: "Enable or disable this system.")) + bool open = EditorUI.current.widgets.CollapsingCard( + systemId, + title, + missing is null + ? () => { - _ = m_edits.ChangeProperty(system, "enabled", () => system.enabled = enabled, enabled ? "Enable System" : "Disable System", mergeKey: null); + bool enabled = system.enabled; + if (EditorUI.current.widgets.CompactCheckbox( + $"enabled_{systemId}", + ref enabled, + tooltip: "Enable or disable this system." + )) { + _ = m_edits.ChangeProperty( + system, + "enabled", + () => system.enabled = enabled, + enabled ? "Enable System" : "Disable System", + mergeKey: null + ); + } } - } : null, () => m_cardControls.DrawSystem( - m_edits, - scene, - system, - () => context.interactions.For(InspectorInteractionIds.C_SYSTEM_AREA, editorTarget).Enqueue(InspectorInteractionIds.C_REMOVE_SYSTEM) - ), dimmed: dimmed, trailingControlWidth: m_cardControls.GetWidth(canRemove: true), drawContextMenu: () => - { - cardMinimum = Ui.GetItemMinimum(); - headerMaximum = Ui.GetItemMaximum(); - _ = EditorUI.current.menus.ContextMenu($"##system_menu_{systemId}", context.interactions.For(InspectorInteractionIds.C_SYSTEM_AREA, editorTarget)); - m_cardControls.DrawSystemDragSource(system, title, dimmed); - }); + : null, + () => m_cardControls.DrawSystem( + m_edits, + scene, + system, + () => context.interactions + .For(InspectorInteractionIds.C_SYSTEM_AREA, editorTarget) + .Enqueue(InspectorInteractionIds.C_REMOVE_SYSTEM) + ), + dimmed: dimmed, + trailingControlWidth: m_cardControls.GetWidth(canRemove: true), + drawContextMenu: () => + { + cardMinimum = Ui.GetItemMinimum(); + headerMaximum = Ui.GetItemMaximum(); + _ = EditorUI.current.menus.ContextMenu( + $"##system_menu_{systemId}", + context.interactions.For(InspectorInteractionIds.C_SYSTEM_AREA, editorTarget) + ); + m_cardControls.DrawSystemDragSource(system, title, dimmed); + } + ); Vector2 cardMaximum = headerMaximum; if (open) { @@ -165,7 +196,9 @@ GameScene scene if (missing is not null) { Ui.PushStyleColor((ImGuiCol.Text), EditorPalette.error); - EditorUI.current.widgets.WrappedText($"Missing system script ({missing.missingType.stableId:D}). " + "Its serialized state is preserved and will recover automatically when the type returns."); + EditorUI.current.widgets.WrappedText( + $"Missing system script ({missing.missingType.stableId:D}). " + "Its serialized state is preserved and will recover automatically when the type returns." + ); Ui.PopStyleColor(); return; } @@ -178,7 +211,12 @@ GameScene scene for (int propertyIndex = 0; propertyIndex < properties.Count; propertyIndex++) { - context.properties.Draw(context.editorContext, system, $"scene.{scene.identity.persistentId:N}.{systemId}", properties[propertyIndex]); + context.properties.Draw( + context.editorContext, + system, + $"scene.{scene.identity.persistentId:N}.{systemId}", + properties[propertyIndex] + ); } }), dimmed: dimmed); cardMaximum = Ui.GetItemMaximum(); @@ -202,12 +240,16 @@ GameScene scene } if (!EditorUI.current.widgets.BeginSearchPopup("##add_system_popup", ref m_systemSearch, "Search systems...", C_SEARCH_BUFFER_SIZE)) + { return; + } try { EditorInteraction interaction = context.interactions.For(InspectorInteractionIds.C_SYSTEM_AREA, scene); if (EditorUI.current.menus.DrawSearchItems(interaction, interaction.BuildMenu().items, m_systemSearch)) + { Ui.CloseCurrentPopup(); + } } finally { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagDiagnosticPublisher.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagDiagnosticPublisher.cs index b4a25678f..2162e3ab5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagDiagnosticPublisher.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagDiagnosticPublisher.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Diagnostics; using Inno.Scene; @@ -44,21 +43,29 @@ internal void Refresh(GameTagCatalog catalog) { GameObject gameObject = objects[objectIndex]; if (catalog.IsDefined(gameObject.tag)) + { continue; + } Guid targetId = gameObject.identity.persistentId; currentTargets.Add(targetId); if (m_activeTargets.Contains(targetId)) + { continue; + } m_diagnostics.Set( CreateSource(targetId, gameObject.name), [Diagnostic.Error( "GAMEOBJECT-TAG-UNDEFINED", - $"GameObject '{gameObject.name}' uses undefined tag '{gameObject.tag}'.")]); + $"GameObject '{gameObject.name}' uses undefined tag '{gameObject.tag}'." + )] + ); } } foreach (Guid targetId in m_activeTargets.Where(id => !currentTargets.Contains(id)).ToArray()) + { m_diagnostics.Clear(CreateSource(targetId, targetId.ToString("D"))); + } m_activeTargets.Clear(); m_activeTargets.UnionWith(currentTargets); } @@ -69,13 +76,14 @@ internal void Refresh(GameTagCatalog catalog) internal void Clear() { foreach (Guid targetId in m_activeTargets) + { m_diagnostics.Clear(CreateSource(targetId, targetId.ToString("D"))); + } m_activeTargets.Clear(); } private static DiagnosticSource CreateSource( Guid targetId, string displayName - ) - => new($"editor.scene.tag:{targetId:N}", $"{C_DIAGNOSTIC_GROUP}: {displayName}"); + ) => new($"editor.scene.tag:{targetId:N}", $"{C_DIAGNOSTIC_GROUP}: {displayName}"); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs index 79ed086e7..ab626157f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Numerics; @@ -7,19 +6,24 @@ using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; using Inno.Scene; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [ProjectSettingPath("Project/Scene/Tags")] internal sealed class GameTagsSetting : ProjectSettingEditor { private const int C_TAG_BUFFER_SIZE = 128; private string m_error = string.Empty; private string m_newTag = string.Empty; + /// /// Gets the presentation section that groups this setting. /// public override string section => "Definitions"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -37,7 +41,9 @@ protected override void OnDraw(GameTagCatalog setting) Ui.Spacing(); DrawTags(setting); if (!string.IsNullOrEmpty(m_error)) + { EditorUI.current.widgets.ColoredText(EditorPalette.error, m_error); + } } private void DrawAddRow(GameTagCatalog setting) @@ -45,17 +51,29 @@ private void DrawAddRow(GameTagCatalog setting) float spacing = Ui.GetLayout().itemSpacing.X; float actionWidth = EditorUI.current.widgets.GetCompactIconSize().X; Ui.SetNextItemWidth(MathF.Max(1f, Ui.GetContentRegionAvailable().X - actionWidth - spacing)); - bool submit = Ui.InputTextWithHint("##new_project_tag", "New tag", ref m_newTag, C_TAG_BUFFER_SIZE, ImGuiInputTextFlags.EnterReturnsTrue); + bool submit = Ui.InputTextWithHint( + "##new_project_tag", + "New tag", + ref m_newTag, + C_TAG_BUFFER_SIZE, + ImGuiInputTextFlags.EnterReturnsTrue + ); Ui.SameLine(0f, spacing); submit |= EditorUI.current.widgets.ClickableIcon("add_project_tag", ImGuiIcon.Plus, "Add project tag"); if (!submit || string.IsNullOrWhiteSpace(m_newTag)) + { return; + } try { if (!setting.Add(m_newTag)) + { m_error = $"Tag '{m_newTag.Trim()}' is already defined."; + } else + { m_error = string.Empty; + } m_newTag = string.Empty; } catch (ArgumentException exception) @@ -67,7 +85,12 @@ private void DrawAddRow(GameTagCatalog setting) private static void DrawTags(GameTagCatalog setting) { IReadOnlyList tags = setting.GetTags(); - ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoSavedSettings; + ImGuiTableFlags flags = ImGuiTableFlags.RowBg + | ImGuiTableFlags.BordersInnerH + | ImGuiTableFlags.BordersInnerV + | ImGuiTableFlags.SizingStretchProp + | ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.NoSavedSettings; Ui.PushStyleVar((ImGuiStyleVar.CellPadding), EditorUI.current.widgets.style.cellPadding); if (!Ui.BeginTable("##project_tag_definitions", 2, flags, default(System.Numerics.Vector2), 0f)) { @@ -78,7 +101,11 @@ private static void DrawTags(GameTagCatalog setting) try { Ui.TableSetupColumn("Tag", (ImGuiTableColumnFlags.WidthStretch | ImGuiTableColumnFlags.NoResize)); - Ui.TableSetupColumn("Action", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), 72f * EditorUI.current.widgets.style.zoom); + Ui.TableSetupColumn( + "Action", + (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), + 72f * EditorUI.current.widgets.style.zoom + ); DrawTagTableHeader(); for (int i = 0; i < tags.Count; i++) { @@ -102,8 +129,7 @@ private static void DrawTags(GameTagCatalog setting) "Remove", new Vector2(Ui.MeasureText("Remove").X, Ui.GetFrameHeight()), "Remove this definition. Existing scene assignments are preserved and become undefined." - )) - { + )) { _ = setting.Remove(tag); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs index 0ef4ddaa8..ac1d5888d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs @@ -1,18 +1,20 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Rendering; using System; using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Serialization; using Inno.Editor.Assets; +using Inno.Editor.ImGui; using Inno.Editor.Inspection; +using Inno.Editor.Rendering; using Inno.Rendering; -using ImGuiApi = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using ImGuiApi = Inno.Editor.ImGui.ImGui; + namespace Inno.Editor.Panel.Inspector; + [InspectionDrawer(typeof(RenderPipelineAsset))] internal sealed class PipelineInspectionDrawer(IInspectionIconProvider icons) : InspectionDrawer { @@ -37,16 +39,14 @@ protected override string GetIcon( InspectionDrawContext context, RenderPipelineAsset target ) => context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetInfo( - target.identity.persistentId, - out AssetInfo? info - ) - && info is not null - && documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; + && documents is not null + && documents.assets.TryGetInfo(target.identity.persistentId, out AssetInfo? info) + && info is not null + && documents.assets.TryGetFileSystemEntry( + info.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; + /// /// Binds a caller-visible label to the current inspection target. /// @@ -63,6 +63,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, RenderPipelineAsset target ) => (target.name, null); + /// /// Renders the header presentation for the current editor frame. /// @@ -78,12 +79,11 @@ RenderPipelineAsset target ) { if (context.interactions.TryGetModule(out var documents) && documents is not null - && documents.assets.TryGetInfo( - target.identity.persistentId, - out AssetInfo? info - ) - && info is not null) + && documents.assets.TryGetInfo(target.identity.persistentId, out AssetInfo? info) + && info is not null + ) { PipelineInspector.DrawHeader(context, documents, documents.Open(info.assetPath)); + } } /// @@ -101,12 +101,11 @@ RenderPipelineAsset target ) { if (context.interactions.TryGetModule(out var documents) && documents is not null - && documents.assets.TryGetInfo( - target.identity.persistentId, - out AssetInfo? info - ) - && info is not null) + && documents.assets.TryGetInfo(target.identity.persistentId, out AssetInfo? info) + && info is not null + ) { PipelineInspector.Draw(context, documents, documents.Open(info.assetPath)); + } } } @@ -134,6 +133,7 @@ protected override string GetIcon( InspectionDrawContext context, AssetFileEntry target ) => icons.GetIcon(target); + /// /// Checks whether this drawer supports the selected Inspector target. /// @@ -143,7 +143,9 @@ AssetFileEntry target /// /// when the documented condition is satisfied; otherwise, . /// - protected override bool CanInspect(AssetFileEntry target) => !target.isDirectory && target.extension.Equals(".irenderpipeline", StringComparison.OrdinalIgnoreCase); + protected override bool CanInspect(AssetFileEntry target) + => !target.isDirectory && target.extension.Equals(".irenderpipeline", StringComparison.OrdinalIgnoreCase); + /// /// Binds a caller-visible label to the current inspection target. /// @@ -160,6 +162,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, AssetFileEntry target ) => (target.nameWithoutExtension, null); + /// /// Renders the header presentation for the current editor frame. /// @@ -174,7 +177,9 @@ protected override void DrawHeader( AssetFileEntry target ) { if (context.interactions.TryGetModule(out var documents) && documents is not null) + { PipelineInspector.DrawHeader(context, documents, documents.Open(target.assetPath)); + } } /// @@ -191,7 +196,9 @@ protected override void Draw( AssetFileEntry target ) { if (context.interactions.TryGetModule(out var documents) && documents is not null) + { PipelineInspector.Draw(context, documents, documents.Open(target.assetPath)); + } } } @@ -207,10 +214,14 @@ Guid id try { if (ImGuiApi.Button("Save")) + { _ = context.interactions.documents.Save(draft.documentId); + } ImGuiApi.SameLine(0f, -1f); if (ImGuiApi.Button("Revert")) + { _ = context.interactions.documents.Revert(draft.documentId); + } } finally { @@ -232,13 +243,18 @@ Guid id if (EditorUI.current.widgets.SectionHeader( "Render Pipeline", "This source is the configuration authority. Unsaved settings do not change Scene, Game or Player content." - )) - { - EditorUI.current.widgets.Hint(draft.isDirty ? "Unsaved changes · rendering unchanged" : "Saved · import and activation are separate"); + )) { + EditorUI.current.widgets.Hint( + draft.isDirty ? "Unsaved changes · rendering unchanged" : "Saved · import and activation are separate" + ); if (draft.error.Length != 0) + { EditorUI.current.widgets.Hint(draft.error); + } if (draft.readOnly) + { EditorUI.current.widgets.Hint("Installed Pipeline · copy into the project to edit"); + } EditorUI.current.widgets.Hint("Pipeline: " + pipeline.pipelineTypeId); DrawSettings("pipeline.settings", pipeline.pipelineState, value => pipeline.pipelineState = value); } @@ -255,11 +271,23 @@ Guid id try { RenderFeatureConfiguration feature = features[slot]; - context.properties.DrawValue(context.editorContext, draft, "pipeline.features." + slot + ".enabled", feature.featureTypeId, typeof(bool), () => features[slot].enabled, value => + context.properties.DrawValue( + context.editorContext, + draft, + "pipeline.features." + + slot + + ".enabled", + feature.featureTypeId, + typeof(bool), + () => features[slot].enabled, + value => { features[slot].enabled = (bool)value!; pipeline.features = features; - }, edits, draft.readOnly); + }, + edits, + draft.readOnly + ); DrawSettings("pipeline.features." + slot, feature.state, value => { features[slot].state = value; @@ -279,7 +307,9 @@ Guid id if (slot + 1 < features.Length) { if (slot > 0) + { ImGuiApi.SameLine(0f, -1f); + } if (ImGuiApi.SmallButton("Move Down")) { (features[slot + 1], features[slot]) = (features[slot], features[slot + 1]); @@ -301,7 +331,9 @@ Guid id } if (featuresOpen && features.Length == 0) + { EditorUI.current.widgets.Hint("No additional features"); + } } finally { @@ -324,12 +356,28 @@ Action assign var settingsEdits = new SettingsEdits(edits, () => assign(new(documents.assets.CaptureProperties(settings)))); foreach (SerializedProperty property in documents.serialization.GetProperties(settings)) - context.properties.DrawDraftProperty(context.editorContext, draft, settings, path, property, settingsEdits, draft.readOnly); + { + context.properties.DrawDraftProperty( + context.editorContext, + draft, + settings, + path, + property, + settingsEdits, + draft.readOnly + ); + } } - catch (Exception error) when ((error is System.IO.IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(error) is null) + catch (Exception error) when ((error is System.IO.IOException + or UnauthorizedAccessException + or InvalidOperationException + or ArgumentException + or FormatException) + && Inno.Core.Execution.RetirementPendingException.Find(error) is null) { - EditorUI.current.widgets.Hint("Settings unavailable · " + state.stableTypeId + " · " + error.Message + " · Stored properties and dependencies are retained."); + EditorUI.current.widgets.Hint( + "Settings unavailable · " + state.stableTypeId + " · " + error.Message + " · Stored properties and dependencies are retained." + ); } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs index 5d926093a..d70906fbe 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs @@ -10,6 +10,7 @@ using Inno.Scene; namespace Inno.Editor.Panel.Inspector; + [InspectionDrawer(typeof(EditorSelectionSnapshot))] internal sealed class SelectionInspectionDrawer( SceneEdits edits, @@ -20,6 +21,7 @@ SceneProjectSettingsModule settings private readonly GameObjectTagSelector m_tags = new(settings, edits); private readonly GameObjectLayerSelector m_layers = new(settings, edits); private string m_componentSearch = ""; + /// public override string icon => ImGuiIcon.LayerGroup; @@ -28,6 +30,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, EditorSelectionSnapshot target ) => ($"{target.identities.Count} Selected", null); + /// protected override void Draw( InspectionDrawContext context, @@ -37,12 +40,16 @@ EditorSelectionSnapshot target target.CopyTargets(context.interactions, values); if (values.Count != target.identities.Count) { - EditorUiSession.current.widgets.Hint("The selection includes unavailable or different content. Select compatible scene objects or assets to edit common values."); + EditorUiSession.current.widgets.Hint( + "The selection includes unavailable or different content. Select compatible scene objects or assets to edit common values." + ); return; } if (values.Count == 0) + { return; + } int primaryIndex = values.FindIndex(value => value.identity.runtimeIdentity == target.primary); if (primaryIndex > 0) { @@ -52,13 +59,23 @@ EditorSelectionSnapshot target } bool readOnly = values.Any(value => !edits.CanEdit(value)); if (readOnly) - EditorUiSession.current.widgets.HelpBox("The selection includes a read-only owner. No batch changes will be applied.", ImGuiIcon.Lock, EditorPalette.warning); + { + EditorUiSession.current.widgets.HelpBox( + "The selection includes a read-only owner. No batch changes will be applied.", + ImGuiIcon.Lock, + EditorPalette.warning + ); + } EditorUiSession.current.widgets.Disabled(readOnly, () => { if (values.All(value => value is GameObject)) + { DrawGameObjects(context, target, values.Cast().ToArray()); + } else + { DrawCommon(context, target, values, "selection"); + } }); } @@ -71,11 +88,18 @@ IReadOnlyList targets bool mixed = targets.Any(value => value.activeSelf != active); EditorUiSession.current.widgets.MixedValue(mixed, () => { - if (!EditorUiSession.current.widgets.CompactCheckbox("selection.active", ref active, tooltip: "Set the active state of every selected object.")) + if (!EditorUiSession.current.widgets.CompactCheckbox( + "selection.active", + ref active, + tooltip: "Set the active state of every selected object." + )) { return; + } using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Set Selected Active"); foreach (GameObject target in targets) + { edits.SetGameObjectActive(target, active); + } transaction.Commit(); }); EditorUiSession.current.widgets.Hint(mixed ? "Active \u00b7 Mixed values" : "Active"); @@ -89,18 +113,26 @@ IReadOnlyList targets Type type = component.GetType(); int occurrence = occurrences.GetValueOrDefault(type); occurrences[type] = occurrence + 1; - GameComponent? [] matches = targets.Select(value => value.GetComponents().Where(candidate => candidate.GetType() == type).Skip(occurrence).FirstOrDefault()).ToArray(); + GameComponent? [] matches = targets + .Select(value => value.GetComponents().Where(candidate => candidate.GetType() == type).Skip(occurrence).FirstOrDefault()) + .ToArray(); if (matches.Any(value => value is null)) - continue; - if (EditorUiSession.current.widgets.SectionHeader($"{type.Name} ({occurrence + 1})", "Common component values. Changes apply atomically to the entire selection.")) { + continue; + } + if (EditorUiSession.current.widgets.SectionHeader( + $"{type.Name} ({occurrence + 1})", + "Common component values. Changes apply atomically to the entire selection." + )) { string id = $"selection.{type.FullName}.{occurrence}"; DrawCommon(context, state, matches.Cast().ToArray(), id); if (Inno.Editor.ImGui.ImGui.Button("Reset Selected##" + id)) { using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Reset Components"); foreach (GameComponent match in matches.Cast()) + { edits.ResetComponent(match); + } transaction.Commit(); } @@ -111,7 +143,9 @@ IReadOnlyList targets { using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Remove Components"); foreach (GameComponent match in matches.Cast()) + { edits.RemoveComponent(match); + } transaction.Commit(); return; } @@ -134,12 +168,16 @@ GameObject primary } if (!widgets.BeginSearchPopup("selection.add-component", ref m_componentSearch, "Search components...", 256)) + { return; + } try { EditorInteraction interaction = context.interactions.For(InspectorInteractionIds.C_COMPONENT_AREA, primary); if (EditorUiSession.current.menus.DrawSearchItems(interaction, interaction.BuildMenu().items, m_componentSearch)) + { Inno.Editor.ImGui.ImGui.CloseCurrentPopup(); + } } finally { @@ -159,32 +197,52 @@ string path return; } - IReadOnlyList[] properties = targets.Select(value => serialization.GetProperties((ISerializable)value)).ToArray(); + IReadOnlyList[] properties = targets + .Select(value => serialization.GetProperties((ISerializable)value)) + .ToArray(); int common = 0; foreach (SerializedProperty property in properties[0]) { if (properties.Any(values => !values.Any(value => value.name == property.name && value.propertyType == property.propertyType))) + { continue; + } var availability = properties.Select(( values, index ) => context.properties.GetPropertyAvailability( - targets[index], values.Single(value => value.name == property.name && value.propertyType == property.propertyType))).ToArray(); + targets[index], + values.Single(value => value.name == property.name && value.propertyType == property.propertyType) + )).ToArray(); if (availability.Any(value => !value.isVisible)) + { continue; + } bool readOnly = availability.Any(value => value.isReadOnly); common++; bool mixed = !edits.HaveSamePropertyValues(targets, property.name); EditorUiSession.current.widgets.MixedValue( mixed, - () => context.properties.DrawDraftProperty(context.editorContext, state, targets[0], path, property, new SelectionEdits(edits, targets), readOnly) + () => context.properties.DrawDraftProperty( + context.editorContext, + state, + targets[0], + path, + property, + new SelectionEdits(edits, targets), + readOnly + ) ); if (mixed) + { EditorUiSession.current.widgets.Hint("Mixed values"); + } } if (common == 0) + { EditorUiSession.current.widgets.Hint("No common editable properties."); + } } private sealed class SelectionEdits( diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/TransformInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/TransformInspectionDrawer.cs index 919a295e9..6d47745d5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/TransformInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/TransformInspectionDrawer.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using Inno.Core.Mathematics; using Inno.Editor.ImGui; @@ -6,9 +5,12 @@ using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene.Components; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; + [InspectionDrawer(typeof(Transform))] internal sealed class TransformInspectionDrawer( SceneEdits edits, @@ -16,6 +18,7 @@ EditorInteractions interactions ) : InspectionDrawer { private bool m_world; + /// /// Gets the icon glyph used to represent this item in the editor. /// @@ -37,6 +40,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, Transform target ) => ("Transform", null); + /// /// Renders the value presentation for the current editor frame. /// @@ -53,9 +57,12 @@ Transform target if (!EditorUI.current.widgets.SectionHeader( m_world ? "World Space" : "Local Space", m_world ? "Position, rotation, and scale include the parent hierarchy. Edits are stored as local values and support Undo/Redo." : "Position, rotation, and scale are relative to the parent. Rotation is expressed in degrees.", - () => _ = EditorUI.current.widgets.CompactCheckbox("##transform_space", ref m_world, tooltip: m_world ? "Switch to Local Space." : "Switch to World Space.") - )) - { + () => _ = EditorUI.current.widgets.CompactCheckbox( + "##transform_space", + ref m_world, + tooltip: m_world ? "Switch to Local Space." : "Switch to World Space." + ) + )) { return; } @@ -73,11 +80,13 @@ Transform target } if (!invertible) + { EditorUI.current.widgets.HelpBox( "World editing requires an invertible parent transform. Edit in Local Space or restore the parent's zero scale.", ImGuiIcon.TriangleExclamation, EditorPalette.warning ); + } Ui.BeginDisabled(!invertible); try { @@ -85,28 +94,58 @@ Transform target Quaternion rotation = m_world ? target.worldRotation : target.localRotation; Vector3 euler = rotation.ToEulerAnglesZYXDegrees(); Vector3 scale = m_world ? target.worldScale : target.localScale; - DrawVector(EditPath(target, "localPosition"), "Position", "Translation in world units.", position, value => Change(target, "localPosition", () => - { - if (m_world) - target.worldPosition = value; - else - target.localPosition = value; - })); - DrawVector(EditPath(target, "localRotation"), "Rotation", "Euler rotation in degrees.", euler, value => Change(target, "localRotation", () => - { - Quaternion next = Quaternion.FromEulerAnglesZYXDegrees(value); - if (m_world) - target.worldRotation = next; - else - target.localRotation = next; - })); - DrawVector(EditPath(target, "localScale"), "Scale", "Scale along each axis. One preserves the original size.", scale, value => Change(target, "localScale", () => - { - if (m_world) - target.worldScale = value; - else - target.localScale = value; - })); + DrawVector( + EditPath(target, "localPosition"), + "Position", + "Translation in world units.", + position, + value => Change(target, "localPosition", () => + { + if (m_world) + { + target.worldPosition = value; + } + else + { + target.localPosition = value; + } + }) + ); + DrawVector( + EditPath(target, "localRotation"), + "Rotation", + "Euler rotation in degrees.", + euler, + value => Change(target, "localRotation", () => + { + Quaternion next = Quaternion.FromEulerAnglesZYXDegrees(value); + if (m_world) + { + target.worldRotation = next; + } + else + { + target.localRotation = next; + } + }) + ); + DrawVector( + EditPath(target, "localScale"), + "Scale", + "Scale along each axis. One preserves the original size.", + scale, + value => Change(target, "localScale", () => + { + if (m_world) + { + target.worldScale = value; + } + else + { + target.localScale = value; + } + }) + ); } finally { @@ -136,6 +175,7 @@ private string EditPath( Transform target, string property ) => $"transform:{target.identity.persistentId:N}:{property}:{m_world}"; + private static void DrawVector( string path, string label, @@ -152,7 +192,9 @@ Action apply Ui.SameLine(0f, -1f); changed |= EditorUI.current.widgets.AxisDragFloat(label, "Z", ref value.z, width); if (changed) + { apply(value); + } }, tooltip: tooltip); EditorUI.current.widgets.CompletePropertyEdit(path); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryCopyTarget.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryCopyTarget.cs index 684f70cdf..f87f831eb 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryCopyTarget.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryCopyTarget.cs @@ -3,10 +3,12 @@ using Inno.Editor.Diagnostics; namespace Inno.Editor.Panel.Logging; + internal readonly struct ConsoleEntryCopyTarget { private readonly EditorConsoleOccurrence m_entry; private readonly int m_repeatCount; + internal ConsoleEntryCopyTarget( EditorConsoleOccurrence entry, int repeatCount @@ -23,10 +25,21 @@ private static string FormatFullText( int repeatCount ) { var builder = new StringBuilder(); - builder.Append('[').Append(entry.time.ToString("yyyy-MM-dd HH:mm:ss.fff")).Append("] [").Append(entry.kind).Append("] [").Append(entry.level).Append("] [").Append(entry.category).Append(']'); + builder + .Append('[') + .Append(entry.time.ToString("yyyy-MM-dd HH:mm:ss.fff")) + .Append("] [") + .Append(entry.kind) + .Append("] [") + .Append(entry.level) + .Append("] [") + .Append(entry.category) + .Append(']'); builder.Append(' ').Append(entry.displayMessage); if (repeatCount > 1) + { builder.Append(" (x").Append(repeatCount).Append(')'); + } if (!string.IsNullOrWhiteSpace(entry.file)) { builder.AppendLine(); @@ -35,7 +48,9 @@ int repeatCount { builder.Append('(').Append(entry.line); if (entry.column > 0) + { builder.Append(',').Append(entry.column); + } builder.Append(')'); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs index 1f4c557ba..ed397134f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs @@ -1,6 +1,7 @@ using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; + internal static class ConsoleEntryImGuiIdentity { internal static void Push(string identity) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs index fdeced606..8b592d596 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs @@ -1,8 +1,9 @@ using System; using System.Collections.Generic; using System.Numerics; -using Ui = Inno.Editor.ImGui.ImGui; + using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; @@ -60,8 +61,12 @@ private void RetireCardWindows() { m_retiredCardKeys.Clear(); foreach (var entry in m_cardSlots) + { if (entry.Value.lastFrame != m_cardFrame) + { m_retiredCardKeys.Add(entry.Key); + } + } foreach (string key in m_retiredCardKeys) { m_freeCardWindows.Push(m_cardSlots[key].index); @@ -73,7 +78,9 @@ private void RetireCardWindows() private void ToggleEntry(string key) { if (!m_openEntries.Remove(key)) + { m_openEntries.Add(key); + } m_openRevision++; } @@ -89,7 +96,9 @@ private void ClearLayout() m_cardSlots.Clear(); m_freeCardWindows.Clear(); for (int index = m_cardWindowNames.Count - 1; index >= 0; index--) + { m_freeCardWindows.Push(index); + } } private void RefreshLayout() @@ -98,7 +107,9 @@ private void RefreshLayout() var shape = (width: Ui.GetContentRegionAvailable().X, frameHeight: Ui.GetFrameHeight(), padding: layout.framePadding.Y, spacing: layout.itemSpacing.Y, zoom: EditorUI.current.widgets.style.zoom); if (ReferenceEquals(m_layoutRows, m_view.rows) && m_layoutShape == shape && m_layoutOpenRevision == m_openRevision) + { return; + } bool sameShape = m_layoutShape == shape; float collapsedHeight = MathF.Truncate(shape.frameHeight + shape.padding * 2f); var measurements = new Dictionary(m_view.rows.Count, StringComparer.Ordinal); @@ -108,8 +119,9 @@ private void RefreshLayout() ConsoleView.Row row = m_view.rows[index]; bool open = m_openEntries.Contains(row.key); EntryMeasurement measurement = sameShape && m_measurements.TryGetValue(row.key, out EntryMeasurement? previous) - && ReferenceEquals(previous.row, row) && previous.open == open - ? previous : new(row, open, collapsedHeight); + && ReferenceEquals(previous.row, row) && previous.open == open + ? previous + : new(row, open, collapsedHeight); entries[index] = measurement; measurements.Add(row.key, measurement); } @@ -117,8 +129,12 @@ private void RefreshLayout() m_layout = entries; m_pendingMeasurements.Clear(); for (int index = 0; index < entries.Length; index++) + { if (entries[index].remainingMeasurements > 0) + { m_pendingMeasurements.Add(index); + } + } m_offsets = new float[entries.Length + 1]; m_layoutRows = m_view.rows; m_layoutShape = shape; @@ -130,14 +146,18 @@ private void RefreshOffsets(int start) { float spacing = Ui.GetLayout().itemSpacing.Y; for (int index = start; index < m_layout.Length; index++) + { m_offsets[index + 1] = m_offsets[index] + m_layout[index].height + spacing; + } } private void DrawVisibleEntries() { var clip = Ui.GetClipBounds(); if (clip.maximum.Y <= clip.minimum.Y || clip.maximum.X <= clip.minimum.X) + { return; + } RefreshLayout(); m_cardFrame++; Vector2 origin = Ui.GetCursorScreenPosition(); @@ -151,24 +171,38 @@ private void DrawVisibleEntries() bool focusPending = focused >= 0; while (visibleIndex <= last || pendingIndex < m_pendingMeasurements.Count || focusPending) { - int index = Math.Min(visibleIndex <= last ? visibleIndex : int.MaxValue, - pendingIndex < m_pendingMeasurements.Count ? m_pendingMeasurements[pendingIndex] : int.MaxValue); + int index = Math.Min( + visibleIndex <= last ? visibleIndex : int.MaxValue, + pendingIndex < m_pendingMeasurements.Count ? m_pendingMeasurements[pendingIndex] : int.MaxValue + ); if (focusPending) + { index = Math.Min(index, focused); + } if (index == visibleIndex) + { visibleIndex++; + } if (pendingIndex < m_pendingMeasurements.Count && index == m_pendingMeasurements[pendingIndex]) + { pendingIndex++; + } if (index == focused) + { focusPending = false; + } EntryMeasurement entry = m_layout[index]; bool measure = entry.remainingMeasurements > 0; Ui.SetCursorScreenPosition(origin + new Vector2(0f, m_offsets[index] + adjustment)); float height = DrawConsoleEntry(entry.row, measure); if (!float.IsFinite(height) || height <= 0f) + { throw new InvalidOperationException("Console row measurement did not produce a finite positive height."); + } if (measure) + { entry.remainingMeasurements--; + } if (height != entry.height) { adjustment += height - entry.height; @@ -179,16 +213,26 @@ private void DrawVisibleEntries() { float top = origin.Y + m_offsets[index] + adjustment; if (top < clip.minimum.Y) + { Ui.SetScrollHereY(0f); + } else if (top + height > clip.maximum.Y) + { Ui.SetScrollHereY(1f); + } } } for (int index = m_pendingMeasurements.Count - 1; index >= 0; index--) + { if (m_layout[m_pendingMeasurements[index]].remainingMeasurements == 0) + { m_pendingMeasurements.RemoveAt(index); + } + } if (changedFrom < m_layout.Length) + { RefreshOffsets(changedFrom); + } m_scrollFocusedRow = false; // A slot is reusable only after all rows have finished submitting this frame. RetireCardWindows(); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs index df1122689..2fa7a7b94 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; @@ -6,12 +5,15 @@ using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Editor.Diagnostics; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; + /// /// Displays append-only logs and current diagnostics in the unified editor Console. /// @@ -104,7 +106,12 @@ protected override void OnDetach(EditorContext context) /// protected override void OnDraw(EditorContext context) { - Ui.BeginChild("ConsoleChild", Vector2.Zero, (ImGuiChildFlags.None), (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse)); + Ui.BeginChild( + "ConsoleChild", + Vector2.Zero, + (ImGuiChildFlags.None), + (ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse) + ); try { DrawToolbar(); @@ -124,7 +131,9 @@ protected override void OnDraw(EditorContext context) private void DrawToolbar() { if (EditorUI.current.widgets.SearchInput("console", "Search messages, sources and files", ref m_query, 1024)) + { m_requestScrollToBottom = false; + } bool collapseChanged = Ui.Checkbox("Collapse", ref m_collapse); if (collapseChanged) { @@ -190,7 +199,9 @@ private void DrawConsoleRegion() { EditorConsoleSnapshot snapshot = m_console.Capture(); if (m_lastRevision != snapshot.revision) + { RemoveStaleOpenEntries(snapshot); + } bool viewChanged = m_view.Update(snapshot, m_query, m_filterLevels, m_collapse); if (viewChanged) { @@ -200,7 +211,9 @@ private void DrawConsoleRegion() ClearFocus(); } else if (m_interactions.focusedArea == LoggingInteractionIds.C_ENTRY_AREA) + { FocusRow(m_view.rows[focused], select: false); + } } bool hasNewEntries = m_lastRevision >= 0 && snapshot.revision != m_lastRevision; m_lastRevision = snapshot.revision; @@ -208,7 +221,9 @@ private void DrawConsoleRegion() bool shouldScrollToBottom = m_requestScrollToBottom || (hasNewEntries && scrollAtBottom); HandleKeyboardNavigation(); if (m_keyboardHandled) + { m_requestScrollToBottom = false; + } DrawEntries(snapshot); DrawEntryContextMenu(); if (shouldScrollToBottom && !m_keyboardHandled) @@ -233,7 +248,9 @@ private void ClearFocus() m_contextKey = null; m_requestContextMenu = false; if (m_interactions.focusedArea == LoggingInteractionIds.C_ENTRY_AREA) + { m_interactions.For(LoggingInteractionIds.C_ENTRY_AREA).Focus(); + } } private void DrawEntries(EditorConsoleSnapshot snapshot) @@ -272,8 +289,9 @@ bool measure ) { bool open = m_openEntries.Contains(row.key); Vector4 cardBg = open ? m_content.GetExpandedBgColor(levelColor) : m_content.GetCollapsedBgColor(); - Vector4 cardBorder = row.key == m_selectedKey ? EditorPalette.contentAccent - : open ? ConsoleStyle.GetExpandedBorder(levelColor) : m_content.GetCollapsedBorderColor(); + Vector4 cardBorder = row.key == m_selectedKey + ? EditorPalette.contentAccent + : open ? ConsoleStyle.GetExpandedBorder(levelColor) : m_content.GetCollapsedBorderColor(); Ui.PushStyleColor((ImGuiCol.FrameBg), cardBg); Ui.PushStyleColor((ImGuiCol.Border), cardBorder); Ui.PushStyleVar((ImGuiStyleVar.FrameRounding), Ui.GetLayout().frameRounding); @@ -283,8 +301,12 @@ bool measure { ImGuiChildFlags childFlags = ImGuiChildFlags.FrameStyle | (open ? ImGuiChildFlags.AutoResizeY : ImGuiChildFlags.None); if (open && measure) + { childFlags |= ImGuiChildFlags.AlwaysAutoResize; - ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoSavedSettings; + } + ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar + | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoSavedSettings; float height = open ? 0f : Ui.GetFrameHeight() + Ui.GetLayout().framePadding.Y * 2f; bool visible = Ui.BeginChild(AcquireCardWindow(row.key), new Vector2(0f, height), childFlags, windowFlags); try @@ -296,9 +318,13 @@ bool measure { DrawHeader(row.latest, row.occurrences.Count, levelColor, levelIcon, open, cardBg, out bool toggled); if (toggled) + { ToggleEntry(row.key); + } if (open) + { DrawOccurrences(row.occurrences, cardBg); + } } finally { @@ -312,7 +338,9 @@ bool measure } float measuredHeight = Ui.GetItemMaximum().Y - Ui.GetItemMinimum().Y; if (Ui.IsItemClicked(ImGuiMouseButton.Left) || Ui.IsItemClicked(ImGuiMouseButton.Right)) + { FocusRow(row, select: true); + } if (Ui.IsItemHovered() && Ui.IsMouseReleased(ImGuiMouseButton.Right)) { m_contextKey = row.key; @@ -338,7 +366,9 @@ Vector4 cardBackground for (int i = 0; i < occurrences.Count; i++) { if (i > 0) + { Ui.Separator(); + } Ui.PushId(unchecked((int)occurrences[i].sequence)); try { @@ -385,7 +415,11 @@ out bool toggled } Vector2 tableOuterSize = new(tableOuterW, 0f); - ImGuiTableFlags flags = ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.NoHostExtendX | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoPadInnerX | ImGuiTableFlags.NoSavedSettings; + ImGuiTableFlags flags = ImGuiTableFlags.SizingFixedFit + | ImGuiTableFlags.NoHostExtendX + | ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.NoPadInnerX + | ImGuiTableFlags.NoSavedSettings; if (Ui.BeginTable("##HeaderTable", 3, flags, tableOuterSize)) { try @@ -412,7 +446,6 @@ out bool toggled { toggled = true; } - } finally { @@ -439,7 +472,6 @@ out bool toggled Ui.SetCursorPosX(Ui.GetCursorPosX() + suffixOffsetX); Ui.Text(repeatText); } - } finally { @@ -468,11 +500,17 @@ private static void DrawDetail(EditorConsoleOccurrence entry) DrawStackedField("File:", fileWithLineText); DrawStackedField("Source:", sourceText); if (entry.sessionId.isAssigned) + { DrawStackedField("Session:", entry.sessionId.ToString()); + } DrawStackedField("Time:", timeText); } - else if (Ui.BeginTable("##ConsoleEntryDetails", 2, (ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings), new Vector2(availableWidth, 0))) - { + else if (Ui.BeginTable( + "##ConsoleEntryDetails", + 2, + (ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings), + new Vector2(availableWidth, 0) + )) { try { Ui.TableSetupColumn("##label", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), labelWidth); @@ -481,7 +519,9 @@ private static void DrawDetail(EditorConsoleOccurrence entry) DrawDetailFieldRow("File:", fileWithLineText); DrawDetailFieldRow("Source:", sourceText); if (entry.sessionId.isAssigned) + { DrawDetailFieldRow("Session:", entry.sessionId.ToString()); + } DrawDetailFieldRow("Time:", timeText); } finally @@ -514,7 +554,9 @@ private void HandleKeyboardNavigation() } } if (navigation.cancel) + { ClearFocus(); + } } private void FocusRow( @@ -523,7 +565,9 @@ bool select ) { m_focusedKey = row.key; if (select) + { m_selectedKey = row.key; + } // The view owns this neutral boxed payload while Core keeps only a weak action target. m_focusedCopyTarget = row.copyTarget; m_interactions.For(LoggingInteractionIds.C_ENTRY_AREA, m_focusedCopyTarget).Focus(); @@ -533,7 +577,9 @@ private void DrawEntryContextMenu() { const string popupId = "##ConsoleEntryContextMenu"; if (m_contextKey is null) + { return; + } int index = m_view.FindIndex(m_contextKey); if (index < 0) { @@ -557,20 +603,29 @@ private void DrawEntryContextMenu() Ui.OpenPopup(popupId); m_requestContextMenu = false; } - if (!EditorUI.current.menus.ContextMenu(popupId, - m_interactions.For(LoggingInteractionIds.C_ENTRY_AREA, m_view.rows[index].copyTarget))) + if (!EditorUI.current.menus.ContextMenu( + popupId, + m_interactions.For(LoggingInteractionIds.C_ENTRY_AREA, m_view.rows[index].copyTarget) + )) { m_contextKey = null; + } } private void RemoveStaleOpenEntries(EditorConsoleSnapshot snapshot) { if (m_openEntries.Count == 0) + { return; + } var activeIds = new HashSet(StringComparer.Ordinal); for (int i = 0; i < snapshot.groups.Count; i++) + { activeIds.Add($"group/{snapshot.groups[i].identity}"); + } for (int i = 0; i < snapshot.occurrences.Count; i++) + { activeIds.Add($"occurrence/{snapshot.occurrences[i].sequence}"); + } m_openEntries.RemoveWhere(id => !activeIds.Contains(id)); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs index 33604dca3..543486339 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs @@ -2,9 +2,11 @@ using System.Numerics; using Inno.Core.Logging; using Inno.Editor.ImGui; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; + internal sealed class ConsolePanelContent { private const string C_ICON_BUG = ImGuiIcon.Bug; @@ -13,6 +15,7 @@ internal sealed class ConsolePanelContent private const string C_ICON_ERROR = ImGuiIcon.CircleXmark; private const string C_ICON_FATAL = ImGuiIcon.SkullCrossbones; private const string C_ICON_DEFAULT = ImGuiIcon.FileLines; + internal void DrawDisabledHint(string text) { Ui.BeginDisabled(true); @@ -29,20 +32,28 @@ internal void DrawDisabledHint(string text) LogLevel.Warn => (ConsoleStyle.warning, C_ICON_WARN), LogLevel.Error => (ConsoleStyle.error, C_ICON_ERROR), LogLevel.Fatal => (ConsoleStyle.fatal, C_ICON_FATAL), - _ => (EditorPalette.text, C_ICON_DEFAULT)}; + _ => (EditorPalette.text, C_ICON_DEFAULT) + }; } internal Vector4 GetCollapsedBgColor() => ConsoleStyle.collapsedCard; + internal Vector4 GetCollapsedBorderColor() => ConsoleStyle.collapsedBorder; + internal Vector4 GetExpandedBgColor(Vector4 levelColor) => ConsoleStyle.GetExpandedCard(levelColor); + internal string GetFirstLine(string text) { if (string.IsNullOrEmpty(text)) + { return string.Empty; + } for (int i = 0; i < text.Length; i++) { if (text[i] is '\n' or '\r') + { return text[..i]; + } } return text; @@ -54,14 +65,22 @@ float maxWidth ) { const string c_ellipsis = "..."; if (string.IsNullOrEmpty(text)) + { return string.Empty; + } if (maxWidth <= 1f) + { return c_ellipsis; + } if (Ui.MeasureText(text).X <= maxWidth) + { return text; + } float ellipsisWidth = Ui.MeasureText(c_ellipsis).X; if (ellipsisWidth >= maxWidth) + { return c_ellipsis; + } float maxTextWidth = maxWidth - ellipsisWidth; int low = 0; int high = text.Length; @@ -69,9 +88,13 @@ float maxWidth { int middle = (low + high + 1) / 2; if (Ui.MeasureText(text[..middle]).X <= maxTextWidth) + { low = middle; + } else + { high = middle - 1; + } } return low <= 0 ? c_ellipsis : text[..low] + c_ellipsis; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs index 5a17c1422..618f91075 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs @@ -24,10 +24,14 @@ bool collapsed ) { ulong mask = 0; foreach (LogLevel level in levels) + { mask |= 1UL << (int)level; + } if (m_revision == snapshot.revision && m_levels == mask && m_collapsed == collapsed - && string.Equals(m_query, query, StringComparison.Ordinal)) + && string.Equals(m_query, query, StringComparison.Ordinal) + ) { return false; + } var filtered = new List(); if (collapsed) { @@ -37,10 +41,14 @@ bool collapsed foreach (EditorConsoleOccurrence occurrence in group.occurrences) { if (Matches(occurrence, query, levels)) + { matches.Add(occurrence); + } } if (matches.Count > 0) + { filtered.Add(new Row("group/" + group.identity, matches[^1], matches.AsReadOnly())); + } } } else @@ -48,7 +56,9 @@ bool collapsed foreach (EditorConsoleOccurrence occurrence in snapshot.occurrences) { if (Matches(occurrence, query, levels)) + { filtered.Add(new Row("occurrence/" + occurrence.sequence, occurrence, Array.AsReadOnly(new[] { occurrence }))); + } } } if (collapsed) @@ -65,12 +75,16 @@ bool collapsed { Row previous = rows[previousIndex]; if (ReferenceEquals(previous.latest, candidate.latest) && previous.occurrences.SequenceEqual(candidate.occurrences)) + { filtered[index] = previous; + } } } m_indices.Clear(); for (int index = 0; index < filtered.Count; index++) + { m_indices.Add(filtered[index].key, index); + } rows = filtered.AsReadOnly(); m_revision = snapshot.revision; m_query = query; @@ -96,13 +110,13 @@ private static bool Matches( string query, IReadOnlySet levels ) => levels.Contains(occurrence.level) - && (query.Length == 0 - || occurrence.message.Contains(query, StringComparison.OrdinalIgnoreCase) - || occurrence.source.Contains(query, StringComparison.OrdinalIgnoreCase) - || occurrence.file.Contains(query, StringComparison.OrdinalIgnoreCase) - || occurrence.code.Contains(query, StringComparison.OrdinalIgnoreCase) - || occurrence.category.Contains(query, StringComparison.OrdinalIgnoreCase) - || occurrence.stackTrace.Contains(query, StringComparison.OrdinalIgnoreCase)); + && (query.Length == 0 + || occurrence.message.Contains(query, StringComparison.OrdinalIgnoreCase) + || occurrence.source.Contains(query, StringComparison.OrdinalIgnoreCase) + || occurrence.file.Contains(query, StringComparison.OrdinalIgnoreCase) + || occurrence.code.Contains(query, StringComparison.OrdinalIgnoreCase) + || occurrence.category.Contains(query, StringComparison.OrdinalIgnoreCase) + || occurrence.stackTrace.Contains(query, StringComparison.OrdinalIgnoreCase)); internal sealed class Row { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleDetailsCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleDetailsCommand.cs index 7fa3f4ac3..c8a5cdab1 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleDetailsCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleDetailsCommand.cs @@ -1,8 +1,10 @@ -using Inno.Editor.Interactions; using Inno.Core.Input; +using Inno.Editor.Interactions; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; + [EditorAction(LoggingInteractionIds.C_COPY_DETAILS, LoggingInteractionIds.C_ENTRY_AREA)] [EditorMenu(LoggingInteractionIds.C_ENTRY_AREA, "Copy Full Entry", order: 110)] [EditorShortcut(LoggingInteractionIds.C_ENTRY_AREA, KeyCode.C, KeyModifier.Shift, primary: true)] diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleMessageCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleMessageCommand.cs index 3352f1666..b297d34b4 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleMessageCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/CopyConsoleMessageCommand.cs @@ -1,8 +1,10 @@ -using Inno.Editor.Interactions; using Inno.Core.Input; +using Inno.Editor.Interactions; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; + [EditorAction(LoggingInteractionIds.C_COPY_MESSAGE, LoggingInteractionIds.C_ENTRY_AREA)] [EditorMenu(LoggingInteractionIds.C_ENTRY_AREA, "Copy Message", order: 100)] [EditorShortcut(LoggingInteractionIds.C_ENTRY_AREA, KeyCode.C, primary: true)] diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Logging/LoggingModule.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Logging/LoggingModule.cs index 852bfebe8..b3c970f7e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Logging/LoggingModule.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Logging/LoggingModule.cs @@ -7,12 +7,14 @@ using Inno.Editor.Settings; namespace Inno.Editor.Panel.Logging; + [EditorModule("diagnostics-logging", order: int.MinValue)] internal sealed class LoggingModule : EditorModule, IEditorConsole { private IDisposable? m_settingsSubscription; private readonly EditorConsole m_console; private readonly EditorSettings m_settings; + internal LoggingModule( LogRouter logRouter, DiagnosticHub diagnosticHub, @@ -58,10 +60,20 @@ protected override void OnDispose() } private void ApplySettings(EditorSettings settings) => m_console.clearOnPlay = ClearConsoleOnPlaySetting.Read(settings); - int IEditorConsole.capacity { get => m_console.capacity; set => m_console.capacity = value; } - bool IEditorConsole.clearOnPlay { get => m_console.clearOnPlay; set => m_console.clearOnPlay = value; } + int IEditorConsole.capacity + { + get => m_console.capacity; + set => m_console.capacity = value; + } + + bool IEditorConsole.clearOnPlay + { + get => m_console.clearOnPlay; + set => m_console.clearOnPlay = value; + } EditorConsoleSnapshot IEditorConsole.Capture() => m_console.Capture(); + void IEditorConsole.Clear() => m_console.Clear(); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettings.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettings.cs index ef1b31961..a1345b1c2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettings.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettings.cs @@ -1,7 +1,9 @@ using Inno.Editor.Settings; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Logging; + [EditorSettingPath("Editor/Diagnostics")] internal sealed class DiagnosticsSettingsPage : EditorSetting { @@ -24,6 +26,7 @@ internal sealed class ConsoleSettingsPage : EditorSetting internal sealed class ClearConsoleOnPlaySetting : EditorSetting { internal const string C_PATH = "Editor/Diagnostics/Console/Clear on Play"; + /// /// Gets a new value initialized to the canonical Console retention policy. /// @@ -41,10 +44,12 @@ public override EditorSettingObject defaultValue /// Gets the presentation section that groups this setting. /// public override string section => "Play Mode"; + /// /// Gets the user-facing explanation of this feature or setting. /// - public override string description => "Clear ordinary Console logs when a new Play Mode request begins while retaining active diagnostics."; + public override string description + => "Clear ordinary Console logs when a new Play Mode request begins while retaining active diagnostics."; /// /// Draws the staged Console retention preference. @@ -56,7 +61,9 @@ protected override void OnDraw(EditorSettingObject setting) { bool value = setting.GetAsBoolean("value", true); if (Ui.Checkbox("Clear ordinary logs when entering Play Mode", ref value)) + { setting.SetAsBoolean("value", value); + } } internal static bool Read(EditorSettings settings) => settings.Get(C_PATH).GetAsBoolean("value", true); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewBackgroundSetting.cs b/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewBackgroundSetting.cs index a69226a30..e708802d4 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewBackgroundSetting.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewBackgroundSetting.cs @@ -1,22 +1,27 @@ using System.Numerics; using Inno.Editor.ImGui; using Inno.Editor.Settings; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.SceneView; + [EditorSettingPath(C_PATH)] internal sealed class SceneViewBackgroundSetting : EditorSetting { internal const string C_PATH = "Editor/Appearance/Viewports/Scene Background"; private static readonly float[] S_DEFAULT = [0.11f, 0.12f, 0.14f, EditorPalette.opacityOpaque]; + /// /// Gets a new value initialized to this setting's canonical default state. /// public override EditorSettingObject defaultValue => CreateDefault(); + /// /// Gets the presentation section that groups this setting. /// public override string section => "Viewport Backgrounds"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -33,10 +38,13 @@ protected override void OnDraw(EditorSettingObject setting) Vector4 value = ReadVector(setting); Ui.SetNextItemWidth(-1f); if (Ui.ColorEditLinear4("##scene_view_background", ref value)) + { setting.SetAsSingleArray("value", [value.X, value.Y, value.Z, value.W]); + } } internal static Vector4 Read(EditorSettings settings) => ReadVector(settings.Get(C_PATH)); + private static EditorSettingObject CreateDefault() { var result = new EditorSettingObject(); @@ -47,6 +55,8 @@ private static EditorSettingObject CreateDefault() private static Vector4 ReadVector(EditorSettingObject setting) { float[] values = setting.GetAsSingleArray("value", S_DEFAULT); - return values.Length == 4 ? new Vector4(values[0], values[1], values[2], values[3]) : new Vector4(S_DEFAULT[0], S_DEFAULT[1], S_DEFAULT[2], S_DEFAULT[3]); + return values.Length == 4 + ? new Vector4(values[0], values[1], values[2], values[3]) + : new Vector4(S_DEFAULT[0], S_DEFAULT[1], S_DEFAULT[2], S_DEFAULT[3]); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs index 8417a698b..1af843a9c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs @@ -1,10 +1,8 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.References; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; +using Inno.Core.Identity; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; @@ -13,17 +11,21 @@ using Inno.Editor.Rendering; using Inno.Editor.Scene; using Inno.Editor.Settings; +using Inno.References; +using Inno.Rendering; using Inno.Scene; using Inno.Scene.Components; -using ImGuizmoMode = Inno.Editor.ImGui.ImGuiWidget.TransformGizmoSpace; -using ImGuizmoOperation = Inno.Editor.ImGui.ImGuiWidget.TransformGizmoOperation; -using Inno.Rendering; -using Ui = Inno.Editor.ImGui.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using EngineMatrix = Inno.Core.Mathematics.Matrix; using EngineQuaternion = Inno.Core.Mathematics.Quaternion; using EngineVector3 = Inno.Core.Mathematics.Vector3; +using ImGuizmoMode = Inno.Editor.ImGui.ImGuiWidget.TransformGizmoSpace; +using ImGuizmoOperation = Inno.Editor.ImGui.ImGuiWidget.TransformGizmoOperation; +using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.SceneView; + /// /// Presents the active Plugin provider and host-owned transform manipulation for the Scene viewport. /// @@ -52,6 +54,7 @@ internal sealed class SceneViewPanel : EditorPanel private RuntimeIdentity? m_gestureTarget; private RuntimeIdentity[] m_gestureTargets = []; private Identity[] m_popupGizmoOwners = []; + internal SceneViewPanel( EditorRenderingModule rendering, EditorInteractions interactions, @@ -72,6 +75,7 @@ EditorSettings settings /// Gets whether use window padding is enabled for this implementation. /// public override bool useWindowPadding => false; + /// /// Gets whether allow scrolling is enabled for this implementation. /// @@ -88,10 +92,14 @@ protected override void OnDraw(EditorContext context) using IDisposable presentationScope = m_playModeLoop.EnterPresentationScope(); _ = context; if (m_gestureTarget is not null && !Ui.IsMouseButtonDown(ImGuiMouseButton.Left)) + { CommitGesture(); + } Vector2 available = Ui.GetContentRegionAvailable(); if (available.X <= 0f || available.Y <= 0f) + { return; + } int width = Math.Max(1, (int)MathF.Floor(available.X)); int height = Math.Max(1, (int)MathF.Floor(available.Y)); m_rendering.SetPresentation(C_VIEWPORT_ID, new EditorViewportPresentation(ToEngineColor(m_backgroundColor))); @@ -142,9 +150,14 @@ protected override void OnDraw(EditorContext context) drawList.MergeChannels(); } - bool iconOwnsPointer = SelectGizmoIcons(icons, viewportClicked && !toolbarOwnsPointer && !gizmoOwnsPointer && !navigationOwnsPointer); + bool iconOwnsPointer = SelectGizmoIcons( + icons, + viewportClicked && !toolbarOwnsPointer && !gizmoOwnsPointer && !navigationOwnsPointer + ); if (!viewportClicked || toolbarOwnsPointer || gizmoOwnsPointer || iconOwnsPointer || navigationOwnsPointer || Ui.GetInput().alt) + { return; + } Vector2 mouse = Ui.GetMousePos(); float x = (mouse.X - minimum.X) / Math.Max(1f, maximum.X - minimum.X); float y = (mouse.Y - minimum.Y) / Math.Max(1f, maximum.Y - minimum.Y); @@ -191,7 +204,9 @@ protected override void Capture(EditorState state) EditorViewportNavigationState navigation = m_rendering.GetNavigationState(C_VIEWPORT_ID); state.Set("navigation.initialized", navigation.isInitialized); if (!navigation.isInitialized) + { return; + } state.Set("navigation.position.x", navigation.position.x); state.Set("navigation.position.y", navigation.position.y); state.Set("navigation.position.z", navigation.position.z); @@ -221,16 +236,29 @@ protected override void Capture(EditorState state) protected override void Restore(EditorState state) { if (!state.Get("navigation.initialized", false)) + { return; - var position = new EngineVector3(state.Get("navigation.position.x", 0f), state.Get("navigation.position.y", 0f), state.Get("navigation.position.z", 0f)); + } + var position = new EngineVector3( + state.Get("navigation.position.x", 0f), + state.Get("navigation.position.y", 0f), + state.Get("navigation.position.z", 0f) + ); var rotation = new EngineQuaternion( state.Get("navigation.rotation.x", 0f), state.Get("navigation.rotation.y", 0f), state.Get("navigation.rotation.z", 0f), state.Get("navigation.rotation.w", 1f) ); - var pivot = new EngineVector3(state.Get("navigation.pivot.x", 0f), state.Get("navigation.pivot.y", 0f), state.Get("navigation.pivot.z", 0f)); - EditorViewportProjection projection = (EditorViewportProjection)state.Get("navigation.projection", (int)EditorViewportProjection.Orthographic); + var pivot = new EngineVector3( + state.Get("navigation.pivot.x", 0f), + state.Get("navigation.pivot.y", 0f), + state.Get("navigation.pivot.z", 0f) + ); + EditorViewportProjection projection = (EditorViewportProjection)state.Get( + "navigation.projection", + (int)EditorViewportProjection.Orthographic + ); try { EditorViewportNavigationState navigation = m_rendering.GetNavigationState(C_VIEWPORT_ID); @@ -261,13 +289,17 @@ protected override void Restore(EditorState state) } private void ApplySettings(EditorSettings settings) => m_backgroundColor = SceneViewBackgroundSetting.Read(settings); + private ContentReadScope CreateContentScope() => m_scenePresentation.Capture(); + private IReadOnlyList<(Vector2 center, EditorGizmoIcon icon)> DrawGizmos( Vector2 minimum, Vector2 maximum ) { if (!m_rendering.TryGetManipulationSpace(C_VIEWPORT_ID, out EditorViewportManipulationSpace space)) + { return[]; + } int width = Math.Max(1, (int)(maximum.X - minimum.X)); int height = Math.Max(1, (int)(maximum.Y - minimum.Y)); EditorGizmoFrame frame = m_rendering.CollectGizmos(C_VIEWPORT_ID, width, height); @@ -278,7 +310,9 @@ Vector2 maximum foreach (EditorGizmoLine line in frame.lines) { if (!TryProject(line.start, out Vector2 start) || !TryProject(line.end, out Vector2 end)) + { continue; + } Ui.DrawLine(start + Vector2.One, end + Vector2.One, outline, 3.5f); Ui.DrawLine(start, end, white, 2.5f); } @@ -288,7 +322,9 @@ Vector2 maximum foreach (EditorGizmoIcon icon in frame.icons) { if (!TryProject(icon.position, out Vector2 center)) + { continue; + } displayIcons.Add((center, icon)); string glyph = GizmoIconGlyph(icon.iconId); float fontScale = iconSize / Ui.GetFontSize(); @@ -303,7 +339,10 @@ bool TryProject( EngineVector3 world, out Vector2 screen ) { - Inno.Core.Mathematics.Vector4 clip = Inno.Core.Mathematics.Vector4.Transform(new Inno.Core.Mathematics.Vector4(world.x, world.y, world.z, 1f), worldToClip); + Inno.Core.Mathematics.Vector4 clip = Inno.Core.Mathematics.Vector4.Transform( + new Inno.Core.Mathematics.Vector4(world.x, world.y, world.z, 1f), + worldToClip + ); if (clip.w <= 0.000001f) { screen = default; @@ -324,7 +363,11 @@ bool maySelect { Vector2 mouse = Ui.GetMousePos(); float radius = 20f * EditorUI.current.widgets.style.zoom; - Identity[] owners = displayIcons.Where(icon => Vector2.DistanceSquared(mouse, icon.center) <= radius * radius).Select(static icon => icon.icon.owner).DistinctBy(static owner => owner.persistentId).ToArray(); + Identity[] owners = displayIcons + .Where(icon => Vector2.DistanceSquared(mouse, icon.center) <= radius * radius) + .Select(static icon => icon.icon.owner) + .DistinctBy(static owner => owner.persistentId) + .ToArray(); if (owners.Length == 1 && owners[0].Resolve() is { isDestroyed: false } owner) { m_interactions.SetSelection(owner); @@ -345,15 +388,21 @@ bool maySelect private void DrawGizmoClusterPopup() { if (!Ui.BeginPopup(C_GIZMO_CLUSTER_POPUP)) + { return; + } foreach (Identity identity in m_popupGizmoOwners) { GameObject? owner = identity.Resolve(); if (owner is null || owner.isDestroyed) + { continue; + } string label = $"{owner.name}##{identity.runtimeIdentity}"; if (!Ui.MenuItem(label, string.Empty, false, true)) + { continue; + } m_interactions.SetSelection(owner); Ui.CloseCurrentPopup(); break; @@ -362,13 +411,15 @@ private void DrawGizmoClusterPopup() Ui.EndPopup(); } - private static string GizmoIconGlyph(string iconId) => iconId switch + private static string GizmoIconGlyph(string iconId) + => iconId switch { "camera" => ImGuiIcon.Camera, "light" => ImGuiIcon.Lightbulb, "canvas" => ImGuiIcon.VectorSquare, _ => ImGuiIcon.CircleQuestion }; + private bool HandleNavigation( EditorViewportNavigationProfile profile, bool hovered, @@ -384,7 +435,9 @@ Vector2 maximum } if (!SupportsMode(profile, navigation.mode)) + { navigation.mode = profile.defaultMode; + } EditorUiInput io = Ui.GetInput(); if (m_navigationDrag != NavigationDrag.None && !Ui.IsMouseButtonDown(m_navigationDragButton)) { @@ -426,7 +479,9 @@ Vector2 maximum bool ownsPointer = panning || m_navigationDrag != NavigationDrag.None; if (!hovered && !ownsPointer) + { return false; + } float width = MathF.Max(1f, maximum.X - minimum.X); float height = MathF.Max(1f, maximum.Y - minimum.Y); float aspect = width / height; @@ -447,14 +502,22 @@ Vector2 maximum } if (hovered && profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.Zoom) && io.wheel != 0f) - Zoom(navigation, profile, io.wheel, minimum, width, height, aspect); - if (hovered && profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.FrameSelection) && Ui.IsKeyPressed(ImGuiKey.F, repeat: false)) { + Zoom(navigation, profile, io.wheel, minimum, width, height, aspect); + } + if (hovered + && profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.FrameSelection) + && Ui.IsKeyPressed(ImGuiKey.F, repeat: false) + ) { EditorViewportFocusBounds? bounds = profile.focusBounds; if (bounds is null && TryGetSelectedTransform(out Transform? selected)) + { bounds = new EditorViewportFocusBounds(selected!.worldPosition, 0.5f); + } if (bounds is EditorViewportFocusBounds focus) + { Frame(navigation, profile, focus); + } } return ownsPointer; @@ -465,7 +528,9 @@ private static void Pan( Vector2 mouseDelta, float height ) { - float verticalSpan = navigation.projection == EditorViewportProjection.Orthographic ? navigation.orthographicSize * 2f : 2f * navigation.focusDistance * MathF.Tan(navigation.fieldOfView * MathF.PI / 360f); + float verticalSpan = navigation.projection == EditorViewportProjection.Orthographic + ? navigation.orthographicSize * 2f + : 2f * navigation.focusDistance * MathF.Tan(navigation.fieldOfView * MathF.PI / 360f); float unitsPerPixel = verticalSpan / height; EngineVector3 right = EngineVector3.Transform(EngineVector3.RIGHT, navigation.rotation); EngineVector3 up = EngineVector3.Transform(EngineVector3.UP, navigation.rotation); @@ -506,17 +571,29 @@ EditorUiInput io EngineVector3 forward = EngineVector3.Transform(EngineVector3.FORWARD, navigation.rotation); right = EngineVector3.Transform(EngineVector3.RIGHT, navigation.rotation); if (Ui.IsKeyDown(ImGuiKey.W)) + { movement += forward; + } if (Ui.IsKeyDown(ImGuiKey.S)) + { movement -= forward; + } if (Ui.IsKeyDown(ImGuiKey.D)) + { movement += right; + } if (Ui.IsKeyDown(ImGuiKey.A)) + { movement -= right; + } if (Ui.IsKeyDown(ImGuiKey.E)) + { movement += worldUp; + } if (Ui.IsKeyDown(ImGuiKey.Q)) + { movement -= worldUp; + } if (movement.LengthSquared() > 0.000001f) { float multiplier = io.shift ? GetPositive(profile.fastMovementMultiplier, 4f) : 1f; @@ -544,7 +621,11 @@ float aspect EngineVector3 previousOffset = GetViewportOffset(normalizedX, normalizedY, previousSize, aspect, navigation.rotation); float minimumSize = GetPositive(profile.minimumOrthographicSize, 0.001f); float maximumSize = MathF.Max(minimumSize, GetPositive(profile.maximumOrthographicSize, 100000f)); - float nextSize = Math.Clamp(previousSize / EditorPlanarNavigation.WheelFactor(wheel, zoomSensitivity), minimumSize, maximumSize); + float nextSize = Math.Clamp( + previousSize / EditorPlanarNavigation.WheelFactor(wheel, zoomSensitivity), + minimumSize, + maximumSize + ); EngineVector3 nextOffset = GetViewportOffset(normalizedX, normalizedY, nextSize, aspect, navigation.rotation); EngineVector3 delta = previousOffset - nextOffset; navigation.position += delta; @@ -555,7 +636,11 @@ float aspect float minimumDistance = GetPositive(profile.minimumFocusDistance, 0.01f); float maximumDistance = MathF.Max(minimumDistance, GetPositive(profile.maximumFocusDistance, 1000000f)); - navigation.focusDistance = Math.Clamp(navigation.focusDistance / EditorPlanarNavigation.WheelFactor(wheel, zoomSensitivity), minimumDistance, maximumDistance); + navigation.focusDistance = Math.Clamp( + navigation.focusDistance / EditorPlanarNavigation.WheelFactor(wheel, zoomSensitivity), + minimumDistance, + maximumDistance + ); EngineVector3 direction = EngineVector3.Transform(EngineVector3.FORWARD, navigation.rotation); navigation.position = navigation.pivot - direction * navigation.focusDistance; } @@ -580,7 +665,11 @@ EditorViewportFocusBounds focus { float halfFov = navigation.fieldOfView * MathF.PI / 360f; float distance = radius * padding / MathF.Max(0.001f, MathF.Tan(halfFov)); - navigation.focusDistance = Math.Clamp(distance, GetPositive(profile.minimumFocusDistance, 0.01f), GetPositive(profile.maximumFocusDistance, 1000000f)); + navigation.focusDistance = Math.Clamp( + distance, + GetPositive(profile.minimumFocusDistance, 0.01f), + GetPositive(profile.maximumFocusDistance, 1000000f) + ); } navigation.position = focus.center - forward * navigation.focusDistance; @@ -595,6 +684,7 @@ EditorViewportNavigationMode mode EditorViewportNavigationMode.Fly => profile.capabilities.HasFlag(EditorViewportNavigationCapabilities.Fly), _ => (profile.capabilities & EditorViewportNavigationCapabilities.Planar) != 0 }; + private static EngineQuaternion ApplyConstrainedPitch( EngineQuaternion yawed, EngineVector3 right, @@ -607,11 +697,14 @@ float angle return MathF.Abs(EngineVector3.Dot(forward, worldUp)) < 0.999f ? candidate : yawed; } - private static EngineVector3 GetWorldUp(EditorViewportNavigationProfile profile) => profile.worldUp.LengthSquared() > 0.000001f ? profile.worldUp.normalized : EngineVector3.UP; + private static EngineVector3 GetWorldUp(EditorViewportNavigationProfile profile) + => profile.worldUp.LengthSquared() > 0.000001f ? profile.worldUp.normalized : EngineVector3.UP; + private static float GetPositive( float value, float fallback ) => float.IsFinite(value) && value > 0f ? value : fallback; + private static EngineVector3 GetViewportOffset( float normalizedX, float normalizedY, @@ -643,6 +736,7 @@ string message } private static Inno.Core.Mathematics.Color ToEngineColor(Vector4 value) => new(value.X, value.Y, value.Z, value.W); + private bool DrawManipulationToolbar(ManipulationToolbarLayout layout) { EditorDrawList drawList = Ui.GetDrawList(); @@ -653,20 +747,38 @@ private bool DrawManipulationToolbar(ManipulationToolbarLayout layout) float itemY = layout.minimum.Y + layout.padding; try { - if (DrawManipulationTool("move", ImGuiIcon.UpDownLeftRight, "Move", new Vector2(itemX, itemY), layout.itemSize, m_operation == ImGuizmoOperation.Translate)) - { + if (DrawManipulationTool( + "move", + ImGuiIcon.UpDownLeftRight, + "Move", + new Vector2(itemX, itemY), + layout.itemSize, + m_operation == ImGuizmoOperation.Translate + )) { m_operation = ImGuizmoOperation.Translate; } itemY += layout.itemSize.Y + layout.spacing; - if (DrawManipulationTool("rotate", ImGuiIcon.Rotate, "Rotate", new Vector2(itemX, itemY), layout.itemSize, m_operation == ImGuizmoOperation.Rotate)) - { + if (DrawManipulationTool( + "rotate", + ImGuiIcon.Rotate, + "Rotate", + new Vector2(itemX, itemY), + layout.itemSize, + m_operation == ImGuizmoOperation.Rotate + )) { m_operation = ImGuizmoOperation.Rotate; } itemY += layout.itemSize.Y + layout.spacing; - if (DrawManipulationTool("scale", ImGuiIcon.UpRightAndDownLeftFromCenter, "Scale", new Vector2(itemX, itemY), layout.itemSize, m_operation == ImGuizmoOperation.Scale)) - { + if (DrawManipulationTool( + "scale", + ImGuiIcon.UpRightAndDownLeftFromCenter, + "Scale", + new Vector2(itemX, itemY), + layout.itemSize, + m_operation == ImGuizmoOperation.Scale + )) { m_operation = ImGuizmoOperation.Scale; } @@ -680,22 +792,37 @@ private bool DrawManipulationToolbar(ManipulationToolbarLayout layout) ); bool supportsCoordinateSpace = m_operation != ImGuizmoOperation.Scale; string modeIcon = supportsCoordinateSpace && m_mode == ImGuizmoMode.World ? ImGuiIcon.Globe : ImGuiIcon.Cube; - string modeTooltip = !supportsCoordinateSpace ? "Coordinate Space: Local (Scale is always local)" : m_mode == ImGuizmoMode.Local ? "Coordinate Space: Local (axes follow the selected transform)" : "Coordinate Space: World (axes follow the world)"; + string modeTooltip = !supportsCoordinateSpace + ? "Coordinate Space: Local (Scale is always local)" + : m_mode == ImGuizmoMode.Local ? "Coordinate Space: Local (axes follow the selected transform)" : "Coordinate Space: World (axes follow the world)"; if (!supportsCoordinateSpace) + { Ui.BeginDisabled(true); + } bool toggleCoordinateSpace; try { - toggleCoordinateSpace = DrawManipulationTool("coordinate_space", modeIcon, modeTooltip, new Vector2(itemX, itemY), layout.itemSize, selected: false); + toggleCoordinateSpace = DrawManipulationTool( + "coordinate_space", + modeIcon, + modeTooltip, + new Vector2(itemX, itemY), + layout.itemSize, + selected: false + ); } finally { if (!supportsCoordinateSpace) + { Ui.EndDisabled(); + } } - if (!supportsCoordinateSpace && Ui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled) && EditorUI.current.widgets.BeginMenuTooltip()) - { + if (!supportsCoordinateSpace + && Ui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled) + && EditorUI.current.widgets.BeginMenuTooltip() + ) { Ui.Text(modeTooltip); EditorUI.current.widgets.EndMenuTooltip(); } @@ -724,7 +851,9 @@ bool selected ) { Ui.SetCursorScreenPosition(position); if (selected) + { Ui.PushStyleColor(ImGuiCol.Text, Vector4.One); + } bool pressed; try { @@ -733,7 +862,9 @@ bool selected finally { if (selected) + { Ui.PopStyleColor(); + } } if (selected) @@ -779,18 +910,18 @@ Vector2 viewportMaximum return new ManipulationToolbarLayout(minimum, maximum, viewportMaximum, itemSize, padding, spacing, sectionSpacing); } - private static bool IsManipulationToolbarHovered(ManipulationToolbarLayout layout) => Ui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows) - && Ui.IsMouseHoveringRect( - layout.minimum, - layout.maximum - ); + private static bool IsManipulationToolbarHovered(ManipulationToolbarLayout layout) + => Ui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows) + && Ui.IsMouseHoveringRect(layout.minimum, layout.maximum); + private bool DrawTransformGizmo( Vector2 minimum, Vector2 maximum, bool canInteract ) { - if (!m_rendering.TryGetManipulationSpace(C_VIEWPORT_ID, out EditorViewportManipulationSpace manipulationSpace) || !TryGetSelectedTransform(out Transform? selected)) - { + if (!m_rendering.TryGetManipulationSpace(C_VIEWPORT_ID, out EditorViewportManipulationSpace manipulationSpace) + || !TryGetSelectedTransform(out Transform? selected) + ) { return false; } @@ -801,17 +932,16 @@ bool canInteract } Transform target = m_gestureTarget is RuntimeIdentity identity - && m_interactions.TryResolveIdentity( - identity, - out IdentityObject? resolved - ) - && resolved is Transform active ? active : selected!; + && m_interactions.TryResolveIdentity(identity, out IdentityObject? resolved) + && resolved is Transform active ? active : selected!; EngineMatrix world = target.localToWorldMatrix; ImGuizmoOperation operation = SelectManipulationOperation(manipulationSpace.plane, m_operation); - bool planarTranslation = manipulationSpace.plane != EditorViewportManipulationPlane.Spatial && m_operation == ImGuizmoOperation.Translate; + bool planarTranslation = manipulationSpace.plane != EditorViewportManipulationPlane.Spatial + && m_operation == ImGuizmoOperation.Translate; TransformGizmoResult result = EditorUI.current.widgets.TransformGizmo( world, - new TransformGizmoOptions { + new TransformGizmoOptions + { minimum = minimum, maximum = maximum, view = manipulationSpace.viewMatrix, @@ -852,10 +982,15 @@ out IdentityObject? resolved foreach (RuntimeIdentity current in m_gestureTargets) { if (!m_interactions.TryResolveIdentity(current, out IdentityObject? value) || value is not Transform transform) + { throw new InvalidOperationException("A transform gesture target is no longer available."); + } EngineMatrix next = delta * transform.localToWorldMatrix; - if (!TryReadManipulatedTransform(next, transform, m_operation, out var position, out var rotation, out var scale) || !IsUsable(position, rotation, scale)) + if (!TryReadManipulatedTransform(next, transform, m_operation, out var position, out var rotation, out var scale) + || !IsUsable(position, rotation, scale) + ) { throw new InvalidOperationException("The manipulated transform is not invertible or finite."); + } _ = m_sceneEdits.ChangeProperty( transform, nameof(Transform.localPosition), @@ -875,7 +1010,9 @@ out IdentityObject? resolved } if (!result.isUsing && m_gestureTarget is not null) + { CommitGesture(); + } return result.isUsing || result.isOver; } @@ -898,8 +1035,12 @@ private static bool HasSelectedAncestor( ISet selected ) { for (Transform? parent = transform.parent; parent is not null; parent = parent.parent) + { if (selected.Contains(parent)) + { return true; + } + } return false; } @@ -918,6 +1059,7 @@ ImGuizmoOperation operation }, _ => operation }; + private static bool TryReadManipulatedTransform( EngineMatrix matrix, Transform target, @@ -930,7 +1072,9 @@ out Inno.Core.Mathematics.Vector3 scale rotation = target.worldRotation; scale = target.worldScale; if (operation == ImGuizmoOperation.Translate) + { return true; + } if (operation == ImGuizmoOperation.Scale) { EngineMatrix original = target.localToWorldMatrix; @@ -943,7 +1087,9 @@ out Inno.Core.Mathematics.Vector3 scale } if (MathF.Abs(scale.x) <= 0.00001f || MathF.Abs(scale.y) <= 0.00001f || MathF.Abs(scale.z) <= 0.00001f) + { return false; + } EngineMatrix normalized = new( matrix.m11 / scale.x, matrix.m12 / scale.y, @@ -993,9 +1139,13 @@ private bool TryGetSelectedTransform(out Transform? transform) private void CommitGesture() { if (m_gestureTarget is null) + { return; + } if (EditorUI.current.widgets.IsEditing(C_TRANSFORM_EDIT)) + { EditorUI.current.widgets.CommitEdits(); + } m_gestureTarget = null; m_gestureTargets = []; } @@ -1005,18 +1155,19 @@ private static bool IsUsable( EngineQuaternion rotation, Inno.Core.Mathematics.Vector3 scale ) => float.IsFinite(position.x) - && float.IsFinite(position.y) - && float.IsFinite(position.z) - && float.IsFinite(rotation.x) - && float.IsFinite(rotation.y) - && float.IsFinite(rotation.z) - && float.IsFinite(rotation.w) - && float.IsFinite(scale.x) - && float.IsFinite(scale.y) - && float.IsFinite(scale.z) - && MathF.Abs(scale.x) > 0.00001f - && MathF.Abs(scale.y) > 0.00001f - && MathF.Abs(scale.z) > 0.00001f; + && float.IsFinite(position.y) + && float.IsFinite(position.z) + && float.IsFinite(rotation.x) + && float.IsFinite(rotation.y) + && float.IsFinite(rotation.z) + && float.IsFinite(rotation.w) + && float.IsFinite(scale.x) + && float.IsFinite(scale.y) + && float.IsFinite(scale.z) + && MathF.Abs(scale.x) > 0.00001f + && MathF.Abs(scale.y) > 0.00001f + && MathF.Abs(scale.z) > 0.00001f; + private readonly record struct ManipulationToolbarLayout( Vector2 minimum, Vector2 maximum, @@ -1026,6 +1177,7 @@ private readonly record struct ManipulationToolbarLayout( float spacing, float sectionSpacing ); + private enum NavigationDrag { None, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs index d5647db0a..c3522c4de 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs @@ -1,12 +1,14 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using Inno.Build; using Inno.Build.Managed; +using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Settings; + internal enum BuildSettingsKey { GameProductName, @@ -25,6 +27,7 @@ internal enum BuildSettingsKey internal sealed class BuildSettingsField { private const int C_TEXT_CAPACITY = 4096; + internal BuildSettingsField( BuildSettingsKey key, string path, @@ -52,7 +55,10 @@ BuildPipeline buildPipeline ) => key switch { BuildSettingsKey.GameProductName => DrawTextValue(settings.gameProductName, value => settings.gameProductName = value), - BuildSettingsKey.GamePersistentDataPath => DrawTextValue(settings.gamePersistentDataPath, value => settings.gamePersistentDataPath = value), + BuildSettingsKey.GamePersistentDataPath => DrawTextValue( + settings.gamePersistentDataPath, + value => settings.gamePersistentDataPath = value + ), BuildSettingsKey.GameStartupScene => DrawTextValue(settings.gameStartupScene, value => settings.gameStartupScene = value), BuildSettingsKey.GameWindowWidth => DrawPositiveInt(settings.gameWindowWidth, value => settings.gameWindowWidth = value), BuildSettingsKey.GameWindowHeight => DrawPositiveInt(settings.gameWindowHeight, value => settings.gameWindowHeight = value), @@ -62,7 +68,9 @@ BuildPipeline buildPipeline BuildSettingsKey.PluginDisplayName => DrawTextValue(settings.pluginDisplayName, value => settings.pluginDisplayName = value), BuildSettingsKey.PluginOutputPath => DrawTextValue(settings.pluginOutputPath, value => settings.pluginOutputPath = value), BuildSettingsKey.IncludePluginDependencies => DrawIncludeDependencies(settings), - _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.")}; + _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.") + }; + internal bool IsDefault( BuildSettings settings, BuildSettings defaults @@ -79,7 +87,9 @@ BuildSettings defaults BuildSettingsKey.PluginDisplayName => settings.pluginDisplayName == defaults.pluginDisplayName, BuildSettingsKey.PluginOutputPath => settings.pluginOutputPath == defaults.pluginOutputPath, BuildSettingsKey.IncludePluginDependencies => settings.includePluginDependencies == defaults.includePluginDependencies, - _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.")}; + _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.") + }; + internal void Reset( BuildSettings settings, BuildSettings defaults @@ -127,48 +137,27 @@ BuildSettings defaults internal static bool ValuesEqual( BuildSettings left, BuildSettings right - ) => string.Equals( - left.gameProductName, - right.gameProductName, - StringComparison.Ordinal - ) - && string.Equals( - left.gamePersistentDataPath, - right.gamePersistentDataPath, - StringComparison.Ordinal - ) - && string.Equals( - left.gameStartupScene, - right.gameStartupScene, - StringComparison.Ordinal - ) - && string.Equals( - left.gameOutputDirectory, - right.gameOutputDirectory, - StringComparison.Ordinal - ) - && left.gameWindowWidth == right.gameWindowWidth - && left.gameWindowHeight == right.gameWindowHeight - && left.gameTarget == right.gameTarget - && left.gameManagedDeployment == right.gameManagedDeployment - && string.Equals( - left.pluginDisplayName, - right.pluginDisplayName, - StringComparison.Ordinal - ) - && string.Equals( - left.pluginOutputPath, - right.pluginOutputPath, - StringComparison.Ordinal - ) - && left.includePluginDependencies == right.includePluginDependencies; + ) => string.Equals(left.gameProductName, right.gameProductName, StringComparison.Ordinal) + && string.Equals(left.gamePersistentDataPath, right.gamePersistentDataPath, StringComparison.Ordinal) + && string.Equals(left.gameStartupScene, right.gameStartupScene, StringComparison.Ordinal) + && string.Equals(left.gameOutputDirectory, right.gameOutputDirectory, StringComparison.Ordinal) + && left.gameWindowWidth == right.gameWindowWidth + && left.gameWindowHeight == right.gameWindowHeight + && left.gameTarget == right.gameTarget + && left.gameManagedDeployment == right.gameManagedDeployment + && string.Equals(left.pluginDisplayName, right.pluginDisplayName, StringComparison.Ordinal) + && string.Equals(left.pluginOutputPath, right.pluginOutputPath, StringComparison.Ordinal) + && left.includePluginDependencies == right.includePluginDependencies; + private static bool DrawTextValue( string value, Action apply ) { Ui.SetNextItemWidth(-1f); if (!Ui.InputText("##value", ref value, C_TEXT_CAPACITY)) + { return false; + } apply(value); return true; } @@ -179,7 +168,9 @@ Action apply ) { Ui.SetNextItemWidth(-1f); if (!Ui.InputInt("##value", ref value, 1, 100, 0)) + { return false; + } apply(Math.Max(1, value)); return true; } @@ -191,7 +182,9 @@ BuildPipeline buildPipeline bool changed = false; Ui.SetNextItemWidth(-1f); if (!EditorUI.current.widgets.BeginBoundedCombo("##value", settings.gameManagedDeployment?.value ?? "Platform default")) + { return false; + } try { if (Ui.Selectable("Platform default", settings.gameManagedDeployment is null)) @@ -203,7 +196,9 @@ BuildPipeline buildPipeline foreach (ManagedDeploymentId deployment in buildPipeline.GetManagedDeployments(settings.gameTarget)) { if (!Ui.Selectable(deployment.value, settings.gameManagedDeployment == deployment)) + { continue; + } settings.gameManagedDeployment = deployment; changed = true; } @@ -223,11 +218,15 @@ BuildPipeline buildPipeline bool changed = false; Ui.SetNextItemWidth(-1f); if (!EditorUI.current.widgets.BeginBoundedCombo("##value", GetTargetLabel(settings.gameTarget, buildPipeline))) + { return false; + } try { foreach (BuildTargetId target in buildPipeline.availableGameTargets) + { changed |= DrawTargetChoice(settings, target, buildPipeline); + } } finally { @@ -241,7 +240,9 @@ private static bool DrawIncludeDependencies(BuildSettings settings) { bool value = settings.includePluginDependencies; if (!Ui.Checkbox("##value", ref value)) + { return false; + } settings.includePluginDependencies = value; return true; } @@ -254,9 +255,13 @@ BuildPipeline buildPipeline bool selected = settings.gameTarget == target; bool changed = Ui.Selectable(GetTargetLabel(target, buildPipeline), selected); if (changed) + { settings.gameTarget = target; + } if (selected) + { Ui.SetItemDefaultFocus(); + } return changed; } @@ -268,8 +273,14 @@ BuildPipeline buildPipeline internal static class BuildSettingsPresentation { - internal static IReadOnlyList fields { get; } = [ - new BuildSettingsField(BuildSettingsKey.GameProductName, "Build/Game/Product Name", "Game Export Defaults", "Player-facing product name copied into each game export."), + internal static IReadOnlyList fields { get; } = + [ + new BuildSettingsField( + BuildSettingsKey.GameProductName, + "Build/Game/Product Name", + "Game Export Defaults", + "Player-facing product name copied into each game export." + ), new BuildSettingsField( BuildSettingsKey.GamePersistentDataPath, "Build/Game/Persistent Data Folder", @@ -282,9 +293,24 @@ internal static class BuildSettingsPresentation "Game Export Defaults", "Mount-qualified Scene path loaded when the exported Player starts." ), - new BuildSettingsField(BuildSettingsKey.GameWindowWidth, "Build/Game/Initial Window Width", "Game Export Defaults", "Initial logical Player window width."), - new BuildSettingsField(BuildSettingsKey.GameWindowHeight, "Build/Game/Initial Window Height", "Game Export Defaults", "Initial logical Player window height."), - new BuildSettingsField(BuildSettingsKey.GameTarget, "Build/Game/Target", "Game Export Defaults", "Platform target selected when the game export window opens."), + new BuildSettingsField( + BuildSettingsKey.GameWindowWidth, + "Build/Game/Initial Window Width", + "Game Export Defaults", + "Initial logical Player window width." + ), + new BuildSettingsField( + BuildSettingsKey.GameWindowHeight, + "Build/Game/Initial Window Height", + "Game Export Defaults", + "Initial logical Player window height." + ), + new BuildSettingsField( + BuildSettingsKey.GameTarget, + "Build/Game/Target", + "Game Export Defaults", + "Platform target selected when the game export window opens." + ), new BuildSettingsField( BuildSettingsKey.GameManagedDeployment, "Build/Game/Managed Deployment", diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/ProjectIdentitySettingsEditor.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/ProjectIdentitySettingsEditor.cs index 97ebdacc5..40dd0a6c6 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/ProjectIdentitySettingsEditor.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/ProjectIdentitySettingsEditor.cs @@ -1,20 +1,24 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using Inno.Core.Settings; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; + using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.Panel.Settings; + [ProjectSettingPath("Project/Identity/Project ID")] internal sealed class ProjectIdentitySettingsEditor : ProjectSettingEditor { private string m_error = string.Empty; + /// /// Gets the presentation section that groups this setting. /// public override string section => "Identity"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -43,6 +47,8 @@ protected override void OnDraw(ProjectIdentitySettings setting) } if (!string.IsNullOrEmpty(m_error)) + { EditorUI.current.widgets.ColoredText(EditorPalette.error, m_error); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs index 38b33cbd6..61d027607 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs @@ -1,15 +1,17 @@ using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Numerics; +using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; -using Inno.Core.Logging; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Settings; + [EditorModal("editor.settings", "Settings", order: 100)] internal sealed class SettingsModal( EditorSettings editorSettings, @@ -25,26 +27,32 @@ LogRouter logs private float m_treePaneRatio = 0.25f; private readonly Logger m_log = logs.CreateLogger(); private string m_applyError = string.Empty; + /// /// Gets whether this implementation is visible. /// public override bool isVisible => window.isVisible; + /// /// Gets whether this implementation can move. /// public override bool canMove => true; + /// /// Gets whether this implementation can resize. /// public override bool canResize => true; + /// /// Lets the navigation tree and current settings page own their scrolling. /// public override bool allowScrolling => false; + /// /// Gets the preferred initial window size in logical editor units. /// public override Vector2 initialSize => new(1050f, 700f); + /// /// Gets the smallest editor window size that keeps every setting control usable. /// @@ -80,13 +88,18 @@ private void DrawWindow() { SettingsEditSession? session = window.session; if (session is null) - return; - if (session.editorCatalogRevision != editorSettings.catalogRevision || session.projectCatalogRevision != projectSettings.catalogRevision) { + return; + } + if (session.editorCatalogRevision != editorSettings.catalogRevision + || session.projectCatalogRevision != projectSettings.catalogRevision + ) { window.Refresh(); session = window.session; if (session is null) + { return; + } } IReadOnlyList pages = session.pages; @@ -94,19 +107,27 @@ private void DrawWindow() SettingsPage? selected = SettingsTree.FindPage(pages, m_navigation.currentPath); selected ??= SettingsTree.FindFirstMatch(pages, m_query); if (selected is not null) + { m_navigation.Replace(selected.path); + } float footerHeight = Ui.GetFrameHeightWithSpacing() + Ui.GetLayout().itemSpacing.Y; if (m_applyError.Length != 0) + { footerHeight += Ui.GetFrameHeightWithSpacing(); + } Vector2 available = Ui.GetContentRegionAvailable(); DrawBody(session, pages, new Vector2(available.X, MathF.Max(1f, available.Y - footerHeight))); Ui.Separator(); if (m_applyError.Length != 0) { - EditorUiSession.current.widgets.ColoredText(EditorPalette.error, - session.isHistoryFaulted ? "History integrity was lost. Restart the Editor." - : session.canApply ? "Apply failed. Edits remain staged; retry or Cancel." - : "Settings recovery is required. See Console for details."); + EditorUiSession.current.widgets.ColoredText( + EditorPalette.error, + session.isHistoryFaulted + ? "History integrity was lost. Restart the Editor." + : session.canApply + ? "Apply failed. Edits remain staged; retry or Cancel." + : "Settings recovery is required. See Console for details." + ); EditorUiSession.current.widgets.DrawItemTooltip(m_applyError); } DrawButtons(session); @@ -117,7 +138,10 @@ private void DrawBody( IReadOnlyList pages, Vector2 size ) { - ImGuiTableFlags flags = ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoKeepColumnsVisible | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.NoSavedSettings; + ImGuiTableFlags flags = ImGuiTableFlags.NoPadOuterX + | ImGuiTableFlags.NoKeepColumnsVisible + | ImGuiTableFlags.SizingFixedFit + | ImGuiTableFlags.NoSavedSettings; float splitterWidth = MathF.Max(5f * EditorUiSession.current.widgets.style.zoom, Ui.GetLayout().dockingSeparatorSize); float treeWidth = ResolveTreeWidth(size.X, splitterWidth); Ui.PushStyleVar(ImGuiStyleVar.CellPadding, Vector2.Zero); @@ -128,7 +152,11 @@ Vector2 size if (tableStarted) { Ui.TableSetupColumn("##settings_tree", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), treeWidth); - Ui.TableSetupColumn("##settings_splitter", (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), splitterWidth); + Ui.TableSetupColumn( + "##settings_splitter", + (ImGuiTableColumnFlags.WidthFixed | ImGuiTableColumnFlags.NoResize), + splitterWidth + ); Ui.TableSetupColumn("##settings_page", ImGuiTableColumnFlags.WidthStretch); Ui.TableNextRow(); _ = Ui.TableSetColumnIndex(0); @@ -142,7 +170,9 @@ Vector2 size finally { if (tableStarted) + { Ui.EndTable(); + } Ui.PopStyleVar(); } } @@ -160,7 +190,9 @@ float height try { if (!visible) + { return; + } DrawNavigationButtons(); Ui.SameLine(0f, EditorUiSession.current.widgets.style.toolbarSectionSpacing); bool wasSearching = !string.IsNullOrWhiteSpace(m_query); @@ -172,9 +204,13 @@ float height if (first is not null) { if (wasSearching) + { m_navigation.Replace(first.path); + } else + { m_navigation.NavigateTo(first.path); + } } else { @@ -207,11 +243,17 @@ private void DrawPagePane( IReadOnlyList pages, float height ) { - bool visible = Ui.BeginChild("##settings_page_pane", new Vector2(0f, height), (ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding)); + bool visible = Ui.BeginChild( + "##settings_page_pane", + new Vector2(0f, height), + (ImGuiChildFlags.Borders | ImGuiChildFlags.AlwaysUseWindowPadding) + ); try { if (!visible) + { return; + } SettingsPage? page = SettingsTree.FindPage(pages, m_navigation.currentPath); if (page is not null) { @@ -243,7 +285,9 @@ float height bool hovered = Ui.IsItemHovered(); bool active = Ui.IsItemActive(); if (hovered || active) + { Ui.SetMouseCursor(ImGuiMouseCursor.ResizeEw); + } if (active) { Vector2 delta = Ui.GetMouseDragDelta(ImGuiMouseButton.Left); @@ -258,9 +302,16 @@ float height Vector2 minimum = Ui.GetItemMinimum(); Vector2 maximum = Ui.GetItemMaximum(); - System.Numerics.Vector4 color = active ? EditorPalette.contentAccent : hovered ? EditorPalette.contentBorder : EditorPalette.contentBorderSoft; + System.Numerics.Vector4 color = active + ? EditorPalette.contentAccent + : hovered ? EditorPalette.contentBorder : EditorPalette.contentBorderSoft; float centerX = (minimum.X + maximum.X) * 0.5f; - Ui.DrawLine(new Vector2(centerX, minimum.Y), new Vector2(centerX, maximum.Y), Ui.ToPackedColor(color), EditorUiSession.current.widgets.style.borderSize); + Ui.DrawLine( + new Vector2(centerX, minimum.Y), + new Vector2(centerX, maximum.Y), + Ui.ToPackedColor(color), + EditorUiSession.current.widgets.style.borderSize + ); } private float ResolveTreeWidth( @@ -288,7 +339,9 @@ private void DrawButtons(SettingsEditSession session) float okWidth = Ui.MeasureText("OK").X + style.framePadding.X * 2f; Ui.SetCursorPosX(Ui.GetCursorPosX() + MathF.Max(0f, Ui.GetContentRegionAvailable().X - okWidth)); if (Ui.Button("OK")) + { TryClose(); + } return; } @@ -297,7 +350,9 @@ private void DrawButtons(SettingsEditSession session) float totalWidth = cancelWidth + style.itemSpacing.X + applyWidth; Ui.SetCursorPosX(Ui.GetCursorPosX() + MathF.Max(0f, Ui.GetContentRegionAvailable().X - totalWidth)); if (Ui.Button("Cancel")) + { TryClose(); + } Ui.SameLine(0f, -1f); Ui.BeginDisabled(!session.canApply); try @@ -367,7 +422,9 @@ private void DrawNavigationButtons() private void EnsureNavigationSession(IReadOnlyList pages) { if (m_navigationRevision == window.sessionRevision) + { return; + } m_navigationRevision = window.sessionRevision; m_applyError = string.Empty; SettingsPage? first = SettingsTree.FindFirstMatch(pages, m_query); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsNavigation.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsNavigation.cs index 9e4612e5e..4ba3e9f28 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsNavigation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsNavigation.cs @@ -25,9 +25,13 @@ internal void NavigateTo(string path) { ArgumentNullException.ThrowIfNull(path); if (string.Equals(currentPath, path, StringComparison.Ordinal)) + { return; + } if (!string.IsNullOrEmpty(currentPath)) + { m_back.Push(currentPath); + } currentPath = path; m_forward.Clear(); } @@ -41,18 +45,26 @@ internal void Replace(string path) internal void GoBack() { if (!m_back.TryPop(out string? path)) + { return; + } if (!string.IsNullOrEmpty(currentPath)) + { m_forward.Push(currentPath); + } currentPath = path; } internal void GoForward() { if (!m_forward.TryPop(out string? path)) + { return; + } if (!string.IsNullOrEmpty(currentPath)) + { m_back.Push(currentPath); + } currentPath = path; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs index bda719e53..e94cc77ad 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs @@ -1,13 +1,15 @@ -using System.Numerics; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Settings; + internal sealed class SettingsPageView(SettingsEditSession session) { private static SettingsStyle settingsStyle => new(EditorUI.current.widgets.style); @@ -31,15 +33,21 @@ Action navigate if (!page.hasSettings) { if (page.children.Count == 0) + { DrawOverview(page.children, navigate); + } return; } int fieldIndex = 0; - foreach (IGrouping group in page.settings.GroupBy(static setting => setting.section ?? string.Empty, StringComparer.OrdinalIgnoreCase)) - { + foreach (IGrouping group in page.settings.GroupBy( + static setting => setting.section ?? string.Empty, + StringComparer.OrdinalIgnoreCase + )) { if (!string.IsNullOrEmpty(group.Key)) + { Ui.SeparatorText(group.Key); + } DrawSection(group, ref fieldIndex); Ui.Spacing(); } @@ -49,7 +57,9 @@ private void DrawPageHeader(SettingsPage page) { ImGuiTableFlags flags = ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.NoPadOuterX; if (!Ui.BeginTable("##settings_page_header", 2, flags, default(System.Numerics.Vector2), 0f)) + { return; + } try { Ui.TableSetupColumn("##settings_page_title", ImGuiTableColumnFlags.WidthStretch, 1f); @@ -64,7 +74,9 @@ private void DrawPageHeader(SettingsPage page) { bool canReset = session.CanReset(page); if (DrawResetButton(canReset)) + { session.Reset(page); + } } finally { @@ -94,7 +106,9 @@ Action navigate SettingsPage child = children[i]; bool clicked = EditorUI.current.widgets.HoverText($"settings_overview_{child.path}", child.label); if (clicked) + { navigate(child); + } EditorUI.current.widgets.DrawItemTooltip(child.description); Ui.Spacing(); } @@ -112,16 +126,22 @@ ref int fieldIndex { tableStarted = Ui.BeginTable("##settings_section", 3, flags, new System.Numerics.Vector2(tableWidth, 0f)); if (!tableStarted) + { return; + } EditorUI.current.widgets.SetupPropertyColumns(); Ui.TableSetupColumn("##settings_reset", ImGuiTableColumnFlags.WidthFixed, GetResetColumnWidth()); foreach (SettingsField setting in settings) + { DrawFieldRow(setting, fieldIndex++); + } } finally { if (tableStarted) + { Ui.EndTable(); + } Ui.PopStyleVar(); } } @@ -152,12 +172,16 @@ int fieldIndex _ = Ui.TableSetColumnIndex(2); bool canReset = session.CanReset(setting); if (DrawResetButton(canReset)) + { session.Reset(setting); + } } finally { if (groupStarted) + { Ui.EndGroup(); + } } } finally @@ -179,19 +203,31 @@ private static void DrawFieldBackgroundGutters(uint background) float windowMinimumX = window.minimumX; float windowMaximumX = window.maximumX; if (rowMaximumY <= rowMinimumY) + { return; + } EditorDrawList drawList = Ui.GetDrawList(); drawList.PushClip(new Vector2(windowMinimumX, rowMinimumY), new Vector2(windowMaximumX, rowMaximumY), false); try { if (tableMinimumX > windowMinimumX) { - Ui.DrawFilledRectangle(new System.Numerics.Vector2(windowMinimumX, rowMinimumY), new System.Numerics.Vector2(tableMinimumX, rowMaximumY), background, 0); + Ui.DrawFilledRectangle( + new System.Numerics.Vector2(windowMinimumX, rowMinimumY), + new System.Numerics.Vector2(tableMinimumX, rowMaximumY), + background, + 0 + ); } if (tableMaximumX < windowMaximumX) { - Ui.DrawFilledRectangle(new System.Numerics.Vector2(tableMaximumX, rowMinimumY), new System.Numerics.Vector2(windowMaximumX, rowMaximumY), background, 0); + Ui.DrawFilledRectangle( + new System.Numerics.Vector2(tableMaximumX, rowMinimumY), + new System.Numerics.Vector2(windowMaximumX, rowMaximumY), + background, + 0 + ); } } finally diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsTree.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsTree.cs index 53a35da01..8521e97c4 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsTree.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsTree.cs @@ -1,14 +1,17 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; +using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Settings; + internal sealed class SettingsTree { private string? m_revealPath; + internal void Reveal(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); @@ -27,7 +30,9 @@ Action select for (int i = 0; i < pages.Count; i++) { if (Matches(pages[i], query)) + { DrawPage(pages[i], query, selectedPath, revealPath, select); + } } } finally @@ -46,10 +51,14 @@ string path { SettingsPage page = pages[i]; if (string.Equals(page.path, path, StringComparison.Ordinal)) + { return page; + } SettingsPage? nested = FindPage(page.children, path); if (nested is not null) + { return nested; + } } return null; @@ -60,17 +69,25 @@ string path string query ) { if (string.IsNullOrWhiteSpace(query)) + { return pages.Count > 0 ? pages[0] : null; + } SettingsPage? fieldMatch = FindFirstFieldMatch(pages, query); if (fieldMatch is not null) + { return fieldMatch; + } for (int i = 0; i < pages.Count; i++) { if (MatchesSelf(pages[i], query)) + { return pages[i]; + } SettingsPage? nested = FindFirstMatch(pages[i].children, query); if (nested is not null) + { return nested; + } } return null; @@ -85,22 +102,37 @@ Action select ) { bool hasVisibleChildren = false; for (int i = 0; i < page.children.Count; i++) + { hasVisibleChildren |= Matches(page.children[i], query); + } if ((!string.IsNullOrWhiteSpace(query) && hasVisibleChildren) || (hasVisibleChildren && IsRevealed(page.path, revealPath))) + { EditorUI.current.widgets.SetNextTreeNodeOpen(true); + } TreeNodeResult result = EditorUI.current.widgets.TreeNode( $"settings_tree_{page.path}", _ => Ui.Text(page.label), - new TreeNodeOptions { selected = string.Equals(page.path, selectedPath, StringComparison.Ordinal), isLeaf = !hasVisibleChildren, hideGuideLines = false } + new TreeNodeOptions + { + selected = string.Equals(page.path, selectedPath, StringComparison.Ordinal), + isLeaf = !hasVisibleChildren, + hideGuideLines = false + } ); if (result.isClicked) + { select(page); + } if (!result.isOpen) + { return; + } for (int i = 0; i < page.children.Count; i++) { if (Matches(page.children[i], query)) + { DrawPage(page.children[i], query, selectedPath, revealPath, select); + } } Ui.TreePop(); @@ -109,19 +141,28 @@ Action select private static bool IsRevealed( string pagePath, string? revealPath - ) => revealPath is not null && (string.Equals(pagePath, revealPath, StringComparison.Ordinal) || revealPath.StartsWith(pagePath + "/", StringComparison.Ordinal)); + ) => revealPath is not null + && (string.Equals(pagePath, revealPath, StringComparison.Ordinal) + || revealPath.StartsWith(pagePath + "/", StringComparison.Ordinal)); + private static bool Matches( SettingsPage page, string query ) { if (string.IsNullOrWhiteSpace(query)) + { return true; + } if (MatchesSelf(page, query)) + { return true; + } for (int i = 0; i < page.children.Count; i++) { if (Matches(page.children[i], query)) + { return true; + } } return false; @@ -131,38 +172,20 @@ private static bool MatchesSelf( SettingsPage page, string query ) { - if (page.label.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) - || page.path.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) - || page.description.Contains( - query, - StringComparison.OrdinalIgnoreCase - )) - { + if (page.label.Contains(query, StringComparison.OrdinalIgnoreCase) + || page.path.Contains(query, StringComparison.OrdinalIgnoreCase) + || page.description.Contains(query, StringComparison.OrdinalIgnoreCase) + ) { return true; } for (int i = 0; i < page.settings.Count; i++) { SettingsField setting = page.settings[i]; - if (setting.label.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) - || (setting.section?.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) ?? false) - || setting.description.Contains( - query, - StringComparison.OrdinalIgnoreCase - )) - { + if (setting.label.Contains(query, StringComparison.OrdinalIgnoreCase) + || (setting.section?.Contains(query, StringComparison.OrdinalIgnoreCase) ?? false) + || setting.description.Contains(query, StringComparison.OrdinalIgnoreCase) + ) { return true; } } @@ -180,26 +203,19 @@ string query for (int settingIndex = 0; settingIndex < page.settings.Count; settingIndex++) { SettingsField setting = page.settings[settingIndex]; - if (setting.label.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) - || (setting.section?.Contains( - query, - StringComparison.OrdinalIgnoreCase - ) ?? false) - || setting.description.Contains( - query, - StringComparison.OrdinalIgnoreCase - )) - { + if (setting.label.Contains(query, StringComparison.OrdinalIgnoreCase) + || (setting.section?.Contains(query, StringComparison.OrdinalIgnoreCase) ?? false) + || setting.description.Contains(query, StringComparison.OrdinalIgnoreCase) + ) { return page; } } SettingsPage? nested = FindFirstFieldMatch(page.children, query); if (nested is not null) + { return nested; + } } return null; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs index d1ecd7898..5830de8e8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs @@ -1,7 +1,6 @@ using System; using System.Buffers.Binary; using System.IO; - using Inno.Build; using Inno.Editor.Interactions; @@ -26,10 +25,14 @@ internal static (ReadOnlyMemory Before, ReadOnlyMemory After) Read(E { byte[] payload = change.payload.ReadBytes(); if (payload.Length < sizeof(int)) + { throw new InvalidDataException("The Build Settings history payload is truncated."); + } int beforeLength = BinaryPrimitives.ReadInt32LittleEndian(payload); if (beforeLength < 0 || beforeLength > payload.Length - sizeof(int)) + { throw new InvalidDataException("The Build Settings history payload has an invalid boundary."); + } return ( payload.AsMemory(sizeof(int), beforeLength), payload.AsMemory(sizeof(int) + beforeLength)); @@ -97,8 +100,7 @@ EditorHistoryDirection direction try { (ReadOnlyMemory before, ReadOnlyMemory after) = BuildSettingsHistory.Read(change); - settings.RestoreDocument( - direction == EditorHistoryDirection.Undo ? before.Span : after.Span); + settings.RestoreDocument(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); return EditorHistoryResult.Success(); } catch (Exception exception) when ( @@ -111,8 +113,9 @@ EditorHistoryDirection direction catch (Exception rollbackException) { return StateIntegrityFailure( - $"Build Settings transition failed: {exception.Message} " + - $"Rollback failed: {rollbackException.Message}"); + $"Build Settings transition failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); } return EditorHistoryResult.Failure(exception.Message); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs index 098e8f7aa..c4618ba50 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Build; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -116,32 +115,44 @@ IEditorHistory history foreach (EditorSetting definition in editorSettings.definitions) { if (!definition.hasValue) + { continue; + } fields.Add(new SettingsField(definition)); EditorSettingObject value = editorSettings.Get(definition.path); m_editorValues.Add(definition.path, value); if (!definition.IsDefault(value)) + { m_editorInitiallyNonDefault.Add(definition.path); + } } foreach (ProjectSettingEditor definition in projectSettings.definitions) { fields.Add(new SettingsField(definition)); if (m_projectValues.ContainsKey(definition.settingId)) + { continue; + } ISerializable value = projectSettings.Get(definition); m_projectValues.Add(definition.settingId, value); m_projectOriginalValues.Add(definition.settingId, projectSettings.Get(definition)); if (!definition.ValuesEqual(value, projectSettings.GetComposedDefault(definition))) + { m_projectInitiallyNonDefault.Add(definition.settingId); + } } foreach (BuildSettingsField definition in BuildSettingsPresentation.fields) + { fields.Add(new SettingsField(definition)); + } string? duplicatePath = fields .GroupBy(static field => field.path, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicatePath is not null) + { throw new InvalidOperationException($"Settings field path '{duplicatePath}' is registered more than once."); + } definitions = fields .OrderBy(static field => field.path, StringComparer.Ordinal) @@ -171,25 +182,36 @@ public void Dispose() internal bool Draw(SettingsField field) { if (field.editor is EditorSetting editor) + { return editor.Draw(m_editorValues[editor.path]); + } if (field.project is ProjectSettingEditor project) + { return project.Draw(m_projectValues[project.settingId]); + } if (field.build is BuildSettingsField build) + { return build.Draw(m_buildValue, m_buildPipeline); + } throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); } internal bool CanReset(SettingsField field) { if (field.editor is EditorSetting editor) + { return !editor.IsDefault(m_editorValues[editor.path]); + } if (field.build is BuildSettingsField build) + { return !build.IsDefault(m_buildValue, m_buildDefault); + } ProjectSettingEditor project = field.project - ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); + ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); bool differsFromDefault = !project.ValuesEqual( m_projectValues[project.settingId], - m_projectSettings.GetComposedDefault(project)); + m_projectSettings.GetComposedDefault(project) + ); return differsFromDefault; } @@ -198,12 +220,16 @@ internal bool CanReset(SettingsPage page) for (int i = 0; i < page.settings.Count; i++) { if (CanReset(page.settings[i])) + { return true; + } } for (int i = 0; i < page.children.Count; i++) { if (CanReset(page.children[i])) + { return true; + } } return false; } @@ -211,7 +237,9 @@ internal bool CanReset(SettingsPage page) internal void Reset(SettingsField field) { if (!CanReset(field)) + { return; + } if (field.editor is EditorSetting editor) { m_editorValues[editor.path] = editor.defaultValue; @@ -219,7 +247,8 @@ internal void Reset(SettingsField field) editor.path, m_editorInitiallyNonDefault.Contains(editor.path), m_editorResetIntent, - m_editorResets); + m_editorResets + ); _ = m_editorModified.Remove(editor.path); return; } @@ -229,22 +258,27 @@ internal void Reset(SettingsField field) return; } ProjectSettingEditor project = field.project - ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); + ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); m_projectValues[project.settingId] = m_projectSettings.GetComposedDefault(project); SetResetState( project.settingId, m_projectInitiallyNonDefault.Contains(project.settingId), m_projectResetIntent, - m_projectResets); + m_projectResets + ); _ = m_projectModified.Remove(project.settingId); } internal void Reset(SettingsPage page) { for (int i = 0; i < page.settings.Count; i++) + { Reset(page.settings[i]); + } for (int i = 0; i < page.children.Count; i++) + { Reset(page.children[i]); + } } internal void UpdateDirty( @@ -252,19 +286,16 @@ internal void UpdateDirty( bool differsFromDrawBaseline ) { if (field.build is not null) + { return; + } if (field.editor is EditorSetting editor) { - UpdateDirty( - editor.path, - differsFromDrawBaseline, - m_editorModified, - m_editorResets, - m_editorResetIntent); + UpdateDirty(editor.path, differsFromDrawBaseline, m_editorModified, m_editorResets, m_editorResetIntent); return; } ProjectSettingId id = field.project?.settingId - ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); + ?? throw new InvalidOperationException($"Settings field '{field.path}' has no owner."); ProjectSettingEditor project = field.project; ISerializable value = m_projectValues[id]; if (m_projectResetIntent.Contains(id)) @@ -281,15 +312,23 @@ bool differsFromDrawBaseline bool differsFromOriginal = !project.ValuesEqual(value, m_projectOriginalValues[id]); if (differsFromOriginal) + { _ = m_projectModified.Add(id); + } else + { _ = m_projectModified.Remove(id); + } } internal bool Apply() { if (!canApply) - throw new InvalidOperationException("Settings cannot be applied while their previous transaction or History requires recovery."); + { + throw new InvalidOperationException( + "Settings cannot be applied while their previous transaction or History requires recovery." + ); + } bool editorDirty = isEditorDirty; bool projectDirty = isProjectDirty; bool buildDirty = isBuildDirty; @@ -298,11 +337,17 @@ internal bool Apply() try { if (editorDirty) + { changed |= ApplyEditor(); + } if (projectDirty) + { changed |= ApplyProject(); + } if (buildDirty) + { changed |= ApplyBuild(); + } m_applyTransaction.Commit(); m_applyTransaction = null; } @@ -317,25 +362,29 @@ internal bool Apply() throw new AggregateException( "Settings Apply failed and its History transaction could not retire. Recovery is required before further editing.", failure, - rollbackFailure); + rollbackFailure + ); } throw; } if (editorDirty) + { AcceptEditorValues(); + } if (projectDirty) + { AcceptProjectValues(); + } if (buildDirty) + { AcceptBuildValues(); + } return changed; } private bool ApplyEditor() { - var values = m_editorModified.ToDictionary( - path => path, - path => m_editorValues[path], - StringComparer.Ordinal); + var values = m_editorModified.ToDictionary(path => path, path => m_editorValues[path], StringComparer.Ordinal); return m_editorSettings.Apply(values, m_editorResets); } @@ -351,7 +400,9 @@ private void AcceptEditorValues() EditorSettingObject value = m_editorSettings.Get(field.path); m_editorValues[field.path] = value; if (!definition.IsDefault(value)) + { m_editorInitiallyNonDefault.Add(field.path); + } } } @@ -368,16 +419,18 @@ private void AcceptProjectValues() m_projectResetIntent.Clear(); m_projectResets.Clear(); foreach (SettingsField field in definitions - .Where(static field => field.scope == SettingsScope.Project) - .GroupBy(static field => field.project!.settingId) - .Select(static group => group.First())) - { + .Where(static field => field.scope == SettingsScope.Project) + .GroupBy(static field => field.project!.settingId) + .Select(static group => group.First()) + ) { ProjectSettingEditor definition = field.project!; ISerializable value = m_projectSettings.Get(definition); m_projectValues[definition.settingId] = value; m_projectOriginalValues[definition.settingId] = m_projectSettings.Get(definition); if (!definition.ValuesEqual(value, m_projectSettings.GetComposedDefault(definition))) + { m_projectInitiallyNonDefault.Add(definition.settingId); + } } } @@ -413,8 +466,7 @@ private static void UpdateDirty( ISet modified, ISet resets, ISet resetIntent - ) - where T : notnull + ) where T : notnull { if (differs) { @@ -424,7 +476,9 @@ ISet resetIntent } _ = modified.Remove(id); if (resetIntent.Contains(id)) + { _ = resets.Add(id); + } } private static void SetResetState( @@ -432,8 +486,7 @@ private static void SetResetState( bool changesEffectiveValue, ISet resetIntent, ISet resets - ) - where T : notnull + ) where T : notnull { if (changesEffectiveValue) { @@ -461,11 +514,15 @@ IReadOnlyList fields page.description = definition.description; } foreach (SettingsField field in fields) + { EnsurePage(field.pagePath, byPath).settings.Add(field); + } string? collision = fields.Select(static field => field.path).FirstOrDefault(byPath.ContainsKey); if (collision is not null) + { throw new InvalidOperationException($"Settings path '{collision}' cannot be a field and a page."); + } return root.children .OrderBy(static page => page.label, StringComparer.OrdinalIgnoreCase) @@ -478,7 +535,9 @@ private static MutablePage EnsurePage( IDictionary byPath ) { if (byPath.TryGetValue(path, out MutablePage? existing)) + { return existing; + } string[] segments = path.Split('/'); string currentPath = string.Empty; MutablePage parent = byPath[string.Empty]; @@ -531,7 +590,8 @@ internal SettingsPage Build() label, string.IsNullOrWhiteSpace(description) ? fallback : description, orderedSettings, - orderedChildren); + orderedChildren + ); } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs index 0ed225df8..45460dfa5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs @@ -32,7 +32,9 @@ EditorReloadCoordinator reloads internal void Open() { if (!canOpen) + { throw new InvalidOperationException(C_PRESENTATION_FAILURE); + } if (!isVisible) { m_session = new SettingsEditSession( @@ -40,7 +42,8 @@ internal void Open() projectSettings, buildPipeline, buildSettings, - interactions.history); + interactions.history + ); sessionRevision++; } isVisible = true; @@ -62,7 +65,8 @@ internal void Refresh() projectSettings, buildPipeline, buildSettings, - interactions.history); + interactions.history + ); sessionRevision++; } @@ -90,6 +94,7 @@ protected override void OnStop(EditorContext context) bool IEditorReloadGuard.canRequestReload => !isVisible; bool IEditorReloadGuard.canActivateReload => !isVisible; + string? IEditorReloadGuard.blockingReason => isVisible ? "Close Settings before reloading scripts to retire its current-generation editing state." : null; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs index e57e0c728..fab3759af 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs @@ -1,27 +1,34 @@ -using Inno.Editor.Core; -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Linq; using Inno.Assets.Pipeline; using Inno.Core.Graphs; +using Inno.Editor.Core; +using Inno.Editor.ImGui; using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Shaders; + using EditorImGui = Inno.Editor.ImGui.ImGui; -using Inno.Rendering.Assets.Authoring; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void Controls(GraphNodeRecord node) { - if (owner.drawers?.TryDraw(node.definitionId, new(node, owner.serialization, owner.context, ( - key, - value, - continuous - ) => SetEncoded(node, key, value, continuous), owner.previews, m_inspection!, draft.readOnly)) == true) + if (owner.drawers?.TryDraw( + node.definitionId, + new(node, owner.serialization, owner.context, ( + key, + value, + continuous + ) => SetEncoded(node, key, value, continuous), owner.previews, m_inspection!, draft.readOnly) + ) == true + ) { return; + } switch (node.definitionId) { case "inno.shader.constant": @@ -32,7 +39,12 @@ private void Controls(GraphNodeRecord node) Choice(node, "type", "float", ["float", "float2", "float3", "float4", "int", "uint"]); break; case "inno.shader.construct": - Choice(node, "type", "float4", ["float2", "float3", "float4", "int2", "int3", "int4", "uint2", "uint3", "uint4", "float3x3", "float4x4"]); + Choice( + node, + "type", + "float4", + ["float2", "float3", "float4", "int2", "int3", "int4", "uint2", "uint3", "uint4", "float3x3", "float4x4"] + ); break; case "inno.shader.select": Choice(node, "type", "float", ["float", "float2", "float3", "float4", "int", "uint", "bool"]); @@ -54,16 +66,25 @@ private void Controls(GraphNodeRecord node) InspectorRow("extract.component", "Component", () => { if (EditorImGui.InputInt("##component", ref index, 1, 100, 0) && index >= 0) + { Set(node, "index", index); + } }); break; case "inno.shader.sample": - Choice(node, "type", "sampled-texture2d", ["sampled-texture2d", "sampled-texture2d-array", "sampled-texture3d", "sampled-texture-cube"]); + Choice( + node, + "type", + "sampled-texture2d", + ["sampled-texture2d", "sampled-texture2d-array", "sampled-texture3d", "sampled-texture-cube"] + ); bool level = Read(node, "explicitLevel", false); InspectorRow("sample.explicit-level", "Explicit LOD", () => { if (EditorImGui.Checkbox("##explicit-level", ref level)) + { Set(node, "explicitLevel", level); + } }); break; case "inno.shader.stage-input": @@ -90,15 +111,24 @@ private void Controls(GraphNodeRecord node) ShaderGraphType resource = Read( node, "resource", - new ShaderGraphType { isStorage = true, storageElement = new() { id = "float4" }, access = RenderStorageAccess.ReadWrite } + new ShaderGraphType + { + isStorage = true, + storageElement = new() { id = "float4" }, + access = RenderStorageAccess.ReadWrite + } ); InspectorRow("storage.contract", "Contract", () => { if (EditorImGui.Button("Storage Contract…")) + { EditorImGui.OpenPopup("##storage"); + } }); if (StoragePopup(ref resource)) + { Set(node, "resource", resource); + } EditorUI.current.widgets.WrappedText("Connect then → after to order memory effects."); break; case "inno.shader.discard": @@ -117,31 +147,39 @@ private void GraphCall(GraphNodeRecord node) ShaderGraphNodeInterface nodeInterface = Read(node, ShaderGraphNodes.interfaceKey, new ShaderGraphNodeInterface()); InspectorRow("graph-node.asset", "Node Graph", () => { - if (!EditorUI.current.widgets.BeginBoundedCombo("##graph-node", selected == Guid.Empty ? "Choose Shader node…" : System.IO.Path.GetFileName(path))) + if (!EditorUI.current.widgets.BeginBoundedCombo( + "##graph-node", + selected == Guid.Empty ? "Choose Shader node…" : System.IO.Path.GetFileName(path) + )) { return; + } try { - foreach (AssetFileEntry entry in owner.assets.GetFileSystemEntries(includeDirectories: false).Where(static entry => entry.extension == ".ishader").OrderBy( - static entry => entry.assetPath.ToString(), - StringComparer.Ordinal - )) - { + foreach (AssetFileEntry entry in owner.assets + .GetFileSystemEntries(includeDirectories: false) + .Where(static entry => entry.extension == ".ishader") + .OrderBy(static entry => entry.assetPath.ToString(), StringComparer.Ordinal) + ) { Guid id = owner.AssetId(entry); if (id == draft.id) + { continue; + } ShaderGraphNodeInterface candidate; try { candidate = owner.LoadGraphNodeInterface(id); } catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { continue; } if (!EditorImGui.Selectable(candidate.displayName + " · " + entry.assetPath.localPath, id == selected)) + { continue; + } using var transaction = owner.interactions.history.BeginTransaction("Assign Graph Node"); Set(node, "sourceId", id); Set(node, "sourcePath", entry.assetPath.ToString()); @@ -158,10 +196,24 @@ private void GraphCall(GraphNodeRecord node) } }); EditorUI.current.widgets.DrawItemTooltip(path); - InspectorRow("graph-node.kind", "Kind", () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.kind.ToString())); - InspectorRow("graph-node.effect", "Effect", () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.effect.ToString())); + InspectorRow( + "graph-node.kind", + "Kind", + () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.kind.ToString()) + ); + InspectorRow( + "graph-node.effect", + "Effect", + () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.effect.ToString()) + ); if (nodeInterface.kind == ShaderGraphNodeKind.DomainOutput) - InspectorRow("graph-node.role", "Target Role", () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.role)); + { + InspectorRow( + "graph-node.role", + "Target Role", + () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.role) + ); + } RepairPorts(node); } @@ -226,15 +278,19 @@ private void GraphInterfaceMetadata() InspectorRow("node-interface.kind", "Kind", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##kind", settings.kind.ToString())) + { return; + } try { foreach (ShaderGraphNodeKind kind in Enum.GetValues()) + { if (EditorImGui.Selectable(kind.ToString(), settings.kind == kind)) { settings.kind = kind; SetGraphNodeSettings(settings); } + } } finally { @@ -246,15 +302,19 @@ private void GraphInterfaceMetadata() InspectorRow("node-interface.effect", "Effect", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##effect", settings.effect.ToString())) + { return; + } try { foreach (ShaderGraphNodeEffect effect in Enum.GetValues()) + { if (EditorImGui.Selectable(effect.ToString(), settings.effect == effect)) { settings.effect = effect; SetGraphNodeSettings(settings); } + } } finally { @@ -322,7 +382,9 @@ Action apply InspectorRow("node-port.type", "Type", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##type", port.type.id)) + { return; + } try { foreach (string type in new[] @@ -348,7 +410,7 @@ Action apply "sampled-texture-cube" } - ) + ) { if (EditorImGui.Selectable(type, port.type.id == type)) { ShaderGraphNodePortDefinition[] changedPorts = ports.ToArray(); @@ -363,6 +425,7 @@ Action apply }; apply(changedPorts); } + } } finally { @@ -375,7 +438,9 @@ Action apply InspectorRow("node-port.required", "Required", () => { if (!EditorImGui.Checkbox("##required", ref required)) + { return; + } ShaderGraphNodePortDefinition[] changedPorts = ports.ToArray(); changedPorts[index] = new() { @@ -390,10 +455,14 @@ Action apply InspectorRow("node-port.remove", "", () => { if (EditorImGui.SmallButton("Remove")) - apply(ports.Where(( - _, - item - ) => item != index).ToArray()); + { + apply( + ports.Where(( + _, + item + ) => item != index).ToArray() + ); + } }); } finally @@ -407,7 +476,9 @@ Action apply string prefix = inputs ? "input" : "output"; string id = prefix; for (int suffix = 2; ports.Any(port => port.id == id); suffix++) + { id = prefix + suffix; + } apply([..ports, new() { id = id, type = new() { id = "float" }, required = false }]); } @@ -420,7 +491,9 @@ private void Scalar(GraphNodeRecord node) InspectorRow("constant.type", "Type", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##constant-type", type)) + { return; + } try { foreach (string candidate in new[] @@ -431,7 +504,7 @@ private void Scalar(GraphNodeRecord node) "bool" } - ) + ) { if (EditorImGui.Selectable(candidate, type == candidate)) { using var transaction = owner.interactions.history.BeginTransaction("Change Constant Type"); @@ -455,6 +528,7 @@ private void Scalar(GraphNodeRecord node) transaction.Commit(); type = candidate; } + } } finally { @@ -470,7 +544,9 @@ private void Scalar(GraphNodeRecord node) bool changed = EditorUI.current.widgets.CompactDragFloat("##value", ref number, 0.01f); Gesture(); if (changed) + { Set(node, "value", number, true); + } }); break; case "bool": @@ -478,7 +554,9 @@ private void Scalar(GraphNodeRecord node) InspectorRow("constant.value", "Value", () => { if (EditorImGui.Checkbox("##value", ref boolean)) + { Set(node, "value", boolean); + } }); break; case "int": @@ -488,7 +566,9 @@ private void Scalar(GraphNodeRecord node) bool integerChanged = EditorImGui.InputInt("##value", ref integer, 1, 100, 0); Gesture(); if (integerChanged) + { Set(node, "value", integer, true); + } }); break; case "uint": @@ -498,7 +578,9 @@ private void Scalar(GraphNodeRecord node) bool unsignedChanged = EditorImGui.InputText("##value", ref unsigned, 32, ImGuiInputTextFlags.CharsDecimal); Gesture(); if (unsignedChanged && uint.TryParse(unsigned, out uint value)) + { Set(node, "value", value, true); + } }); break; } @@ -511,20 +593,30 @@ private void Source(GraphNodeRecord node) string selectedFunction = Read(node, "function", ""); InspectorRow("source.library", "Library", () => { - if (!EditorUI.current.widgets.BeginBoundedCombo("##library", selected == Guid.Empty ? "Choose source library…" : System.IO.Path.GetFileName(path))) + if (!EditorUI.current.widgets.BeginBoundedCombo( + "##library", + selected == Guid.Empty ? "Choose source library…" : System.IO.Path.GetFileName(path) + )) { return; + } try { - foreach (AssetFileEntry entry in owner.assets.GetFileSystemEntries(includeDirectories: false).Where(static entry => entry.assetPath.localPath.EndsWith(".ishadersource", StringComparison.OrdinalIgnoreCase))) + foreach (AssetFileEntry entry in owner.assets + .GetFileSystemEntries(includeDirectories: false) + .Where(static entry => entry.assetPath.localPath.EndsWith(".ishadersource", StringComparison.OrdinalIgnoreCase)) + ) { if (EditorImGui.Selectable(entry.assetPath.ToString(), owner.AssetId(entry) == selected)) { using var transaction = owner.interactions.history.BeginTransaction("Assign Shader Function"); Set(node, "sourceId", owner.AssetId(entry)); Set(node, "sourcePath", entry.assetPath.ToString()); if (owner.assets.TryLoad(entry.assetPath, out ShaderFunctionAsset? library) && library is not null) + { Set(node, "function", library.exports.FirstOrDefault() ?? ""); + } transaction.Commit(); } + } } finally { @@ -533,20 +625,33 @@ private void Source(GraphNodeRecord node) }); EditorUI.current.widgets.DrawItemTooltip(path); if (selected == Guid.Empty) - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Choose a library and one of its explicitly exported functions."); + { + EditorUI.current.widgets.ColoredText( + Inno.Editor.ImGui.EditorPalette.textDisabled, + "Choose a library and one of its explicitly exported functions." + ); + } else { if (owner.assets.TryLoad(selected, out ShaderFunctionAsset? library) && library is not null && !library.isMissing) { InspectorRow("source.function", "Function", () => { - if (!EditorUI.current.widgets.BeginBoundedCombo("##function", selectedFunction.Length == 0 ? "Choose exported function…" : selectedFunction)) + if (!EditorUI.current.widgets.BeginBoundedCombo( + "##function", + selectedFunction.Length == 0 ? "Choose exported function…" : selectedFunction + )) { return; + } try { foreach (string function in library.exports) + { if (EditorImGui.Selectable(function, function == selectedFunction)) + { Set(node, "function", function); + } + } } finally { @@ -577,14 +682,18 @@ private void Input(GraphNodeRecord node) InspectorRow("input.source", "Source", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##source", input.kind.ToString())) + { return; + } try { foreach (ShaderIrInputKind kind in Enum.GetValues()) + { if (EditorImGui.Selectable(kind.ToString(), input.kind == kind)) { input.kind = kind; if (kind == ShaderIrInputKind.Storage) + { input.type = new() { isStorage = true, @@ -594,16 +703,21 @@ private void Input(GraphNodeRecord node) }, access = RenderStorageAccess.ReadWrite }; + } else if (kind == ShaderIrInputKind.SampledTexture) + { input.type = new() { id = "sampled-texture2d" }; + } else if (input.type.isStorage || input.type.id.StartsWith("sampled-texture", StringComparison.Ordinal)) + { input.type = new() { id = "float4" }; + } if (kind == ShaderIrInputKind.Builtin) { string stageId = Read(node, "stage", ""); @@ -620,6 +734,7 @@ private void Input(GraphNodeRecord node) Set(node, "settings", input); } + } } finally { @@ -632,7 +747,9 @@ private void Input(GraphNodeRecord node) InspectorRow("input.storage", "Contract", () => { if (EditorImGui.Button("Storage Contract…")) + { EditorImGui.OpenPopup("##storage"); + } }); ShaderGraphType resource = input.type; if (StoragePopup(ref resource)) @@ -642,10 +759,13 @@ private void Input(GraphNodeRecord node) } } else + { InspectorRow("input.type", "Type", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##type", type)) + { return; + } try { foreach (string candidate in new[] @@ -671,7 +791,7 @@ private void Input(GraphNodeRecord node) "sampled-texture-cube" } - ) + ) { if (EditorImGui.Selectable(candidate, type == candidate)) { input.type = new() @@ -680,12 +800,14 @@ private void Input(GraphNodeRecord node) }; Set(node, "settings", input); } + } } finally { EditorUI.current.widgets.EndBoundedCombo(); } }); + } string semantic = input.semantic; bool semanticChanged = false; InspectorRow("input.semantic", "Semantic", () => semanticChanged = EditorImGui.InputText("##semantic", ref semantic, 256)); @@ -696,7 +818,9 @@ private void Input(GraphNodeRecord node) Set(node, "settings", input, true); } - EditorUI.current.widgets.DrawItemTooltip("Stage semantic, not a native expression. Builtins must be supported by the selected stage and target; compute invocation IDs use uint3."); + EditorUI.current.widgets.DrawItemTooltip( + "Stage semantic, not a native expression. Builtins must be supported by the selected stage and target; compute invocation IDs use uint3." + ); int location = input.location; bool locationChanged = false; InspectorRow("input.location", "Location", () => locationChanged = EditorImGui.InputInt("##location", ref location, 1, 100, 0)); @@ -720,9 +844,13 @@ private void Input(GraphNodeRecord node) if (EditorImGui.Checkbox("##preview", ref expanded)) { if (expanded) + { draft.expandedPreviews.Add(node.id); + } else + { draft.expandedPreviews.Remove(node.id); + } } }); if (expanded) @@ -730,9 +858,16 @@ private void Input(GraphNodeRecord node) ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(Controller.document, owner.serialization, owner.context); TextureAsset? texture = definition.properties.FirstOrDefault(value => value.id.value == input.id).defaultValue.texture; if (texture is not null && owner.previews.TryGetTexture(texture, out var preview)) + { owner.previews.Draw(preview, new(120 * Canvas.zoom, 120 * Canvas.zoom)); + } else - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, texture is null ? "No default texture" : "Preparing preview…"); + { + EditorUI.current.widgets.ColoredText( + Inno.Editor.ImGui.EditorPalette.textDisabled, + texture is null ? "No default texture" : "Preparing preview…" + ); + } } } } @@ -747,18 +882,19 @@ private void Output(GraphNodeRecord node) Inno.Editor.ImGui.EditorPalette.textDisabled, string.Join( ", ", - ShaderGraphPrograms.Read( - Controller.document, - owner.serialization, - owner.context - ).Where(program => program.stages.Contains(node.id.value, StringComparer.Ordinal)).Select(static program => program.pass) + ShaderGraphPrograms + .Read(Controller.document, owner.serialization, owner.context) + .Where(program => program.stages.Contains(node.id.value, StringComparer.Ordinal)) + .Select(static program => program.pass) ) ) ); InspectorRow("output.settings", "Settings", () => { if (EditorImGui.Button("Stage & Pass Settings…")) + { EditorImGui.OpenPopup("##stage-settings"); + } }); StageSettingsPopup(node, stage); if (stage.stage == ShaderStage.Compute) @@ -801,12 +937,18 @@ string[] values InspectorRow("choice." + key, EditorDisplayNames.Nicify(key), () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##" + key, current)) + { return; + } try { foreach (string candidate in values) + { if (EditorImGui.Selectable(candidate, current == candidate)) + { Set(node, key, candidate); + } + } } finally { @@ -818,6 +960,8 @@ string[] values private void Gesture() { if (EditorImGui.IsItemActivated()) + { draft.valueGesture = Guid.NewGuid().ToString("N"); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.InputDefaults.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.InputDefaults.cs index efa53e84a..b0c72b6d4 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.InputDefaults.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.InputDefaults.cs @@ -1,11 +1,13 @@ -using Inno.Editor.Core; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System.Linq; using Inno.Core.Graphs; +using Inno.Editor.Core; using Inno.Rendering.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void DrawInputDefault( @@ -30,13 +32,23 @@ ShaderNodePort port } if (m_inspectionNodes is { Length: > 1 } selected - && selected.Any(value => !draft.ports[value.id].Any(candidate => candidate.id == port.id && candidate.type.IsEquivalentTo(port.type)) || Controller.document.edges.Any(connection => connection.input == new GraphEndpoint(value.id, new(port.id))))) - { + && selected.Any( + value => ( + !draft.ports[value.id].Any(candidate => candidate.id == port.id && candidate.type.IsEquivalentTo(port.type)) + || Controller.document.edges.Any(connection => connection.input == new GraphEndpoint(value.id, new(port.id))) + ) + ) + ) { InspectorPortStatusRow("port." + port.id, port, null, "Mixed connections or types"); return; } - InspectorPortStatusRow("port." + port.id, port, null, port.required ? "Required · Connect a Constant or compatible output" : "Optional · Zero when unconnected"); + InspectorPortStatusRow( + "port." + port.id, + port, + null, + port.required ? "Required · Connect a Constant or compatible output" : "Optional · Zero when unconnected" + ); } finally { @@ -54,9 +66,11 @@ string status PortLabel(port, component), () => EditorUI.current.widgets.MetadataValue(DisplayType(port.type.id), status, "Shader value type · " + port.type.id) ); + private static string PortLabel( ShaderNodePort port, string? component ) => component is null ? port.id : port.id + " " + component; + private static string DisplayType(string typeId) => EditorDisplayNames.Nicify(typeId); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs index 4195f7257..2ceefcb61 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs @@ -1,13 +1,15 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using Inno.Core.Graphs; using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private const float C_MINI_MAP_WIDTH = 220f; @@ -15,11 +17,11 @@ internal sealed partial class ShaderEditorCanvas private const float C_MINI_MAP_MARGIN = 14f; private const float C_MINI_MAP_PADDING = 9f; private readonly Dictionary m_miniMapGeometry = []; + private readonly record struct MiniMapNodeGeometry( Vector2 minimum, Vector2 maximum - ) - { + ) { internal Vector2 center => (minimum + maximum) * 0.5f; } @@ -27,16 +29,18 @@ private readonly record struct MiniMapLayout( Vector2 worldMinimum, Vector2 screenOrigin, float scale - ) - { + ) { internal Vector2 ToScreen(Vector2 position) => screenOrigin + (position - worldMinimum) * scale; + internal Vector2 ToWorld(Vector2 position) => worldMinimum + (position - screenOrigin) / scale; } private bool MiniMapContains(Vector2 point) { if (!TryGetMiniMapBounds(out Vector2 minimum, out Vector2 maximum)) + { return false; + } return point.X >= minimum.X && point.X <= maximum.X && point.Y >= minimum.Y && point.Y <= maximum.Y; } @@ -46,7 +50,9 @@ out Vector2 maximum ) { minimum = maximum = default; if (m_size.X < 320f || m_size.Y < 220f) + { return false; + } float zoom = EditorUI.current.widgets.style.zoom; Vector2 size = new(MathF.Min(C_MINI_MAP_WIDTH * zoom, m_size.X * 0.30f), MathF.Min(C_MINI_MAP_HEIGHT * zoom, m_size.Y * 0.30f)); maximum = m_origin + new Vector2(m_size.X - C_MINI_MAP_MARGIN * zoom, C_MINI_MAP_MARGIN * zoom + size.Y); @@ -57,7 +63,9 @@ out Vector2 maximum private void DrawMiniMap() { if (!TryGetMiniMapBounds(out Vector2 minimum, out Vector2 maximum)) + { return; + } Vector2 size = maximum - minimum; Vector2 cursor = ImGuiApi.GetCursorScreenPosition(); ImGuiApi.SetCursorScreenPosition(minimum); @@ -74,13 +82,22 @@ private void DrawMiniMap() ); began = true; if (!visible) + { return; + } MiniMapLayout layout = CreateMiniMapLayout(minimum, maximum); - ImGuiApi.InvisibleButton("##mini-map-navigation", Vector2.Max(ImGuiApi.GetContentRegionAvailable(), Vector2.One), ImGuiButtonFlags.MouseButtonLeft); + ImGuiApi.InvisibleButton( + "##mini-map-navigation", + Vector2.Max(ImGuiApi.GetContentRegionAvailable(), Vector2.One), + ImGuiButtonFlags.MouseButtonLeft + ); if (ImGuiApi.IsItemActive() && ImGuiApi.IsMouseButtonDown(ImGuiMouseButton.Left)) { Vector2 graphPoint = layout.ToWorld(Vector2.Clamp(ImGuiApi.GetMousePos(), minimum, maximum)); - Canvas.SetViewport(new(m_size.X * 0.5f - graphPoint.X * Canvas.zoom, m_size.Y * 0.5f - graphPoint.Y * Canvas.zoom), Canvas.zoom); + Canvas.SetViewport( + new(m_size.X * 0.5f - graphPoint.X * Canvas.zoom, m_size.Y * 0.5f - graphPoint.Y * Canvas.zoom), + Canvas.zoom + ); } DrawMiniMapContents(Inno.Editor.ImGui.ImGui.GetDrawList(), layout); @@ -88,7 +105,9 @@ private void DrawMiniMap() finally { if (began) + { ImGuiApi.EndChild(); + } ImGuiApi.PopStyleColor(); ImGuiApi.PopStyleVar(); ImGuiApi.SetCursorScreenPosition(cursor); @@ -128,15 +147,11 @@ MiniMapLayout layout ) { foreach (GraphEdgeRecord edge in Controller.document.edges) { - if (!m_miniMapGeometry.TryGetValue( - edge.output.nodeId, - out MiniMapNodeGeometry source - ) - || !m_miniMapGeometry.TryGetValue( - edge.input.nodeId, - out MiniMapNodeGeometry target - )) + if (!m_miniMapGeometry.TryGetValue(edge.output.nodeId, out MiniMapNodeGeometry source) + || !m_miniMapGeometry.TryGetValue(edge.input.nodeId, out MiniMapNodeGeometry target) + ) { continue; + } draw.Line(layout.ToScreen(source.center), layout.ToScreen(target.center), Color(0.55f, 0.42f, 0.76f, 0.65f), 1f); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs index 566435989..ced227d93 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs @@ -1,23 +1,27 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Linq; using Inno.Core.Graphs; -using Inno.Rendering; -using Inno.Rendering.Shaders; +using Inno.Editor.ImGui; using Inno.Editor.Shaders; using Inno.Editor.Shaders.ImGui; -using EditorImGui = Inno.Editor.ImGui.ImGui; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Rendering.Shaders; + +using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private bool StoragePopup(ref ShaderGraphType type) { EditorImGui.SetNextWindowSize(new(490, 390), (ImGuiCond.Appearing)); if (!EditorImGui.BeginPopup("##storage")) + { return false; + } bool changed = false; try { @@ -75,7 +79,9 @@ private bool StoragePopup(ref ShaderGraphType type) InspectorRow("storage.element", "Element", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##element", current)) + { return; + } try { foreach (string candidate in new[] @@ -94,9 +100,12 @@ private bool StoragePopup(ref ShaderGraphType type) "uint4" } - ) + ) { if (EditorImGui.Selectable(candidate, current == candidate)) + { selected = candidate; + } + } } finally { @@ -113,7 +122,9 @@ private bool StoragePopup(ref ShaderGraphType type) } } - EditorUI.current.widgets.WrappedText("Storage resources are bound by the render pass. The graph declares types and access; the Render Graph owns resource lifetime and synchronization."); + EditorUI.current.widgets.WrappedText( + "Storage resources are bound by the render pass. The graph declares types and access; the Render Graph owns resource lifetime and synchronization." + ); } finally { @@ -126,7 +137,9 @@ private bool StoragePopup(ref ShaderGraphType type) private void DrawParameter(ShaderGraphInputSettings input) { if (m_inspection is null) + { return; + } ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(Controller.document, owner.serialization, owner.context); int index = Array.FindIndex(definition.properties, value => value.id.value == input.id); if (index < 0) @@ -144,7 +157,11 @@ private void DrawParameter(ShaderGraphInputSettings input) { string displayName = property.displayName; bool changed = false; - InspectorRow("parameter.display-name", "Display Name", () => changed = EditorImGui.InputText("##display-name", ref displayName, 256)); + InspectorRow( + "parameter.display-name", + "Display Name", + () => changed = EditorImGui.InputText("##display-name", ref displayName, 256) + ); Gesture(); if (changed) { @@ -179,23 +196,33 @@ private void DrawParameter(ShaderGraphInputSettings input) if (property.bindingOwner != ShaderPropertyBindingOwner.Material) { if (parameterOpen) + { EditorUI.current.widgets.Hint("Supplied by the Render Pass. This binding is read-only in Material Inspectors."); + } return; } if (property.bindingKind is not (ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture)) { if (parameterOpen) + { EditorUI.current.widgets.Hint("Storage resources require a Render Pass owner."); + } return; } - ShaderParameterPresentation presentation = ShaderParameterPresentation.Read(Controller.document, property.id, owner.serialization, owner.context); + ShaderParameterPresentation presentation = ShaderParameterPresentation.Read( + Controller.document, + property.id, + owner.serialization, + owner.context + ); if (!EditorUI.current.widgets.SectionHeader( "Material Inspector", "Presentation belongs only to this Shader's authoring graph. It does not modify existing Material values or enter the Player." - )) + )) { return; + } string group = presentation.group; bool groupChanged = false; InspectorRow("parameter.group", "Group", () => groupChanged = EditorImGui.InputText("##group", ref group, 256)); @@ -208,7 +235,11 @@ private void DrawParameter(ShaderGraphInputSettings input) Gesture(); string description = presentation.description; bool descriptionChanged = false; - InspectorRow("parameter.description", "Description", () => descriptionChanged = EditorImGui.InputText("##description", ref description, 2048)); + InspectorRow( + "parameter.description", + "Description", + () => descriptionChanged = EditorImGui.InputText("##description", ref description, 2048) + ); if (descriptionChanged) { presentation.description = description; @@ -238,20 +269,52 @@ private void DrawParameter(ShaderGraphInputSettings input) }); if (range) { - m_inspection.properties.DrawValue(m_inspection.editorContext, draft, "shader.parameter." + property.id.value + ".minimum", "Minimum", typeof(double), () => presentation.minimum, value => + m_inspection.properties.DrawValue( + m_inspection.editorContext, + draft, + "shader.parameter." + + property.id.value + + ".minimum", + "Minimum", + typeof(double), + () => presentation.minimum, + value => { if (!double.IsFinite((double)value!)) + { return; + } presentation.minimum = Math.Clamp((double)value!, -float.MaxValue, presentation.maximum); SavePresentation(true); - }, new ParameterEdits(this), draft.readOnly, minimum: -float.MaxValue, maximum: presentation.maximum); - m_inspection.properties.DrawValue(m_inspection.editorContext, draft, "shader.parameter." + property.id.value + ".maximum", "Maximum", typeof(double), () => presentation.maximum, value => + }, + new ParameterEdits(this), + draft.readOnly, + minimum: -float.MaxValue, + maximum: presentation.maximum + ); + m_inspection.properties.DrawValue( + m_inspection.editorContext, + draft, + "shader.parameter." + + property.id.value + + ".maximum", + "Maximum", + typeof(double), + () => presentation.maximum, + value => { if (!double.IsFinite((double)value!)) + { return; + } presentation.maximum = Math.Clamp((double)value!, presentation.minimum, float.MaxValue); SavePresentation(true); - }, new ParameterEdits(this), draft.readOnly, minimum: presentation.minimum, maximum: float.MaxValue); + }, + new ParameterEdits(this), + draft.readOnly, + minimum: presentation.minimum, + maximum: float.MaxValue + ); EditorUI.current.widgets.Hint("Editing bounds only · existing defaults and overrides are not clamped on display"); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs index 87d5b9fab..8e131390e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs @@ -1,14 +1,16 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Linq; using Inno.Core.Graphs; +using Inno.Editor.ImGui; using Inno.Rendering; +using Inno.Rendering.Assets; using Inno.Rendering.Shaders; + using EditorImGui = Inno.Editor.ImGui.ImGui; -using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void StageSettingsPopup( @@ -17,7 +19,9 @@ ShaderGraphStageSettings stage ) { EditorImGui.SetNextWindowSize(new(540, 600), (ImGuiCond.Appearing)); if (!EditorImGui.BeginPopup("##stage-settings")) + { return; + } try { ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(Controller.document, owner.serialization, owner.context); @@ -37,19 +41,27 @@ ShaderGraphStageSettings stage ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(Controller.document, owner.serialization, owner.context); string activePass = draft.inspectedPass; if (!definition.passes.Any(pass => pass.name == activePass)) - activePass = programs.FirstOrDefault(program => program.stages.Contains(node.id.value, StringComparer.Ordinal)).pass ?? definition.passes.FirstOrDefault().name ?? ""; + { + activePass = programs.FirstOrDefault(program => program.stages.Contains(node.id.value, StringComparer.Ordinal)).pass + ?? definition.passes.FirstOrDefault().name + ?? ""; + } InspectorRow("settings.pass", "Pass State", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##pass-state", activePass)) + { return; + } try { foreach (ShaderPassDefinition available in definition.passes) + { if (EditorImGui.Selectable(available.name, activePass == available.name)) { activePass = available.name; draft.inspectedPass = activePass; } + } } finally { @@ -60,17 +72,31 @@ ShaderGraphStageSettings stage bool assigned = assignment.stages?.Contains(node.id.value, StringComparer.Ordinal) == true; bool assignmentChanged = false; if (activePass.Length != 0) - InspectorRow("settings.shared-stage", "Shared Stage", () => assignmentChanged = EditorImGui.Checkbox("##shared-stage", ref assigned)); + { + InspectorRow( + "settings.shared-stage", + "Shared Stage", + () => assignmentChanged = EditorImGui.Checkbox("##shared-stage", ref assigned) + ); + } if (assignmentChanged) { var stageIds = (assignment.stages ?? []).Where(id => id != node.id.value).Select(static id => new GraphNodeId(id)).ToList(); if (assigned) { - stageIds.RemoveAll(id => Controller.document.FindNode(id) is GraphNodeRecord existing && Read(existing, "settings", new ShaderGraphStageSettings()).stage == stage.stage); + stageIds.RemoveAll( + id => ( + Controller.document.FindNode(id) is GraphNodeRecord existing + && Read(existing, "settings", new ShaderGraphStageSettings()).stage == stage.stage + ) + ); stageIds.Add(node.id); } - Controller.ReplaceDocument(ShaderGraphPrograms.Bind(Controller.document, activePass, stageIds, owner.serialization, owner.context), "Assign Shared Shader Stage"); + Controller.ReplaceDocument( + ShaderGraphPrograms.Bind(Controller.document, activePass, stageIds, owner.serialization, owner.context), + "Assign Shared Shader Stage" + ); owner.Changed(draft); } @@ -100,7 +126,11 @@ ShaderGraphStageSettings stage string semantic = output.semantic ?? ""; bool semanticChanged = false; - InspectorRow("output.semantic", "Semantic", () => semanticChanged = EditorImGui.InputText("##semantic", ref semantic, 128)); + InspectorRow( + "output.semantic", + "Semantic", + () => semanticChanged = EditorImGui.InputText("##semantic", ref semantic, 128) + ); if (semanticChanged) { output.semantic = semantic; @@ -110,7 +140,11 @@ ShaderGraphStageSettings stage Gesture(); int location = output.location; bool locationChanged = false; - InspectorRow("output.location", "Location", () => locationChanged = EditorImGui.InputInt("##location", ref location, 1, 100, 0)); + InspectorRow( + "output.location", + "Location", + () => locationChanged = EditorImGui.InputInt("##location", ref location, 1, 100, 0) + ); if (locationChanged) { output.location = location; @@ -144,14 +178,16 @@ ShaderGraphStageSettings stage if (CenteredAddButton("Add Output")) { - stage.outputs = [..stage.outputs, new() - { - id = "output-" + Guid.NewGuid().ToString("N"), - kind = stage.stage == ShaderStage.Vertex ? ShaderIrOutputKind.Varying : ShaderIrOutputKind.Color, - semantic = "texcoord", - location = stage.outputs.Length - } - + stage.outputs = + [ + ..stage.outputs, + new() + { + id = "output-" + Guid.NewGuid().ToString("N"), + kind = stage.stage == ShaderStage.Vertex ? ShaderIrOutputKind.Varying : ShaderIrOutputKind.Color, + semantic = "texcoord", + location = stage.outputs.Length + } ]; Set(node, "settings", stage); } @@ -192,8 +228,16 @@ ShaderGraphStageSettings stage bool depthWrite = state.depthWrite, multisampling = state.multisampling; bool depthWriteChanged = false, multisamplingChanged = false; - InspectorRow("state.depth-write", "Depth Write", () => depthWriteChanged = EditorImGui.Checkbox("##depth-write", ref depthWrite)); - InspectorRow("state.multisampling", "Multisampling", () => multisamplingChanged = EditorImGui.Checkbox("##multisampling", ref multisampling)); + InspectorRow( + "state.depth-write", + "Depth Write", + () => depthWriteChanged = EditorImGui.Checkbox("##depth-write", ref depthWrite) + ); + InspectorRow( + "state.multisampling", + "Multisampling", + () => multisamplingChanged = EditorImGui.Checkbox("##multisampling", ref multisampling) + ); if (depthWriteChanged) { state.depthWrite = depthWrite; @@ -209,7 +253,9 @@ ShaderGraphStageSettings stage InspectorRow("state.blend-preset", "Blend Preset", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##blend-preset", state.blend.enabled ? "Blended" : "Opaque")) + { return; + } try { if (EditorImGui.Selectable("Opaque")) @@ -243,7 +289,11 @@ ShaderGraphStageSettings stage }); int mask = state.colorWriteMask; bool maskChanged = false; - InspectorRow("state.write-mask", "RGBA Write Mask", () => maskChanged = EditorImGui.InputInt("##write-mask", ref mask, 1, 100, 0)); + InspectorRow( + "state.write-mask", + "RGBA Write Mask", + () => maskChanged = EditorImGui.InputInt("##write-mask", ref mask, 1, 100, 0) + ); if (maskChanged) { state.colorWriteMask = (byte)Math.Clamp(mask, 0, 15); @@ -262,7 +312,10 @@ ShaderGraphStageSettings stage changed = true; } - RenderBlendFactor colorSource = blend.colorSource, colorDestination = blend.colorDestination, alphaSource = blend.alphaSource, alphaDestination = blend.alphaDestination; + RenderBlendFactor colorSource = blend.colorSource; + RenderBlendFactor colorDestination = blend.colorDestination; + RenderBlendFactor alphaSource = blend.alphaSource; + RenderBlendFactor alphaDestination = blend.alphaDestination; RenderBlendEquation colorEquation = blend.colorEquation, alphaEquation = blend.alphaEquation; if (EnumControl("RGB Source", ref colorSource)) { @@ -416,23 +469,26 @@ ShaderGraphStageSettings stage private bool EnumControl( string label, ref T value - ) - where T : struct, Enum + ) where T : struct, Enum { bool changed = false; T current = value; InspectorRow("enum." + label, label, () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##enum", current.ToString())) + { return; + } try { foreach (T candidate in Enum.GetValues()) + { if (EditorImGui.Selectable(candidate.ToString(), candidate.Equals(current))) { current = candidate; changed = true; } + } } finally { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs index 54cb928bc..10540b7e0 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs @@ -1,25 +1,35 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Linq; using Inno.Core.Graphs; using Inno.Rendering.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void RepairPorts(GraphNodeRecord node) { GraphEndpoint[] missing = draft.missingPorts.Where(endpoint => endpoint.nodeId == node.id).ToArray(); if (missing.Length == 0) + { return; + } if (ImGuiApi.SmallButton("Repair Ports…")) + { ImGuiApi.OpenPopup("##repair-ports"); + } if (!ImGuiApi.BeginPopup("##repair-ports")) + { return; + } try { - EditorUI.current.widgets.WrappedText("Removed ports retain their connections. Choose a replacement explicitly; occupied inputs are not overwritten."); + EditorUI.current.widgets.WrappedText( + "Removed ports retain their connections. Choose a replacement explicitly; occupied inputs are not overwritten." + ); foreach (GraphEndpoint endpoint in missing) { ShaderNodePort old = Port(endpoint); @@ -28,24 +38,39 @@ private void RepairPorts(GraphNodeRecord node) { ImGuiApi.Text(endpoint.portId.value + " · " + old.type.id); if (!EditorUI.current.widgets.BeginBoundedCombo("##replacement", "Reconnect to…")) + { continue; + } foreach (ShaderNodePort replacement in draft.ports[node.id]) { var target = new GraphEndpoint(node.id, new(replacement.id)); if (replacement.direction != old.direction || draft.missingPorts.Contains(target)) + { continue; - bool occupied = replacement.direction == GraphPortDirection.Input && Controller.document.edges.Any(edge => edge.input == target); - bool compatible = old.type.id == "missing" || replacement.type.id == "any" || old.type.IsEquivalentTo(replacement.type); + } + bool occupied = replacement.direction == GraphPortDirection.Input + && Controller.document.edges.Any(edge => edge.input == target); + bool compatible = old.type.id == "missing" + || replacement.type.id == "any" + || old.type.IsEquivalentTo(replacement.type); ImGuiApi.BeginDisabled(occupied || !compatible); - bool selected = ImGuiApi.Selectable(replacement.id + (occupied ? " · connected" : !compatible ? " · different type" : "")); + bool selected = ImGuiApi.Selectable( + replacement.id + (occupied ? " · connected" : !compatible ? " · different type" : "") + ); ImGuiApi.EndDisabled(); if (!selected) + { continue; + } GraphDocument candidate = Controller.document.Clone(); - foreach (GraphEdgeRecord edge in candidate.edges.Where(edge => edge.input == endpoint || edge.output == endpoint).ToArray()) - { + foreach (GraphEdgeRecord edge in candidate.edges + .Where(edge => edge.input == endpoint || edge.output == endpoint) + .ToArray() + ) { candidate.RemoveEdge(edge.id); - candidate.AddEdge(new(edge.id, edge.output == endpoint ? target : edge.output, edge.input == endpoint ? target : edge.input)); + candidate.AddEdge( + new(edge.id, edge.output == endpoint ? target : edge.output, edge.input == endpoint ? target : edge.input) + ); } // Keep the retired declaration in metadata for a future source restoration and Undo. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs index 9e711558a..6d8fcc6c2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs @@ -1,27 +1,33 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.IO; using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; using Inno.Rendering.Assets; -using EditorImGui = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets.Authoring; +using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; + namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void SourceSettings(Guid sourceId) { if (!owner.assets.TryGetInfo(sourceId, out AssetInfo? info) || info is null) + { return; + } InspectorRow("source.actions", "Source", () => { if (EditorImGui.SmallButton("Show in File Browser") && owner.interactions.TryGetModule(out var browser) - && browser is not null) + && browser is not null + ) { RevealShaderFunction.Reveal(owner, browser, sourceId); + } EditorImGui.SameLine(0f, -1f); if (EditorImGui.SmallButton("Import Settings…")) { @@ -31,13 +37,17 @@ private void SourceSettings(Guid sourceId) }); EditorImGui.SetNextWindowSize(new(580, 470), (ImGuiCond.Appearing)); if (!EditorImGui.BeginPopup("##source-settings")) + { return; + } try { EditorImGui.Text(info.assetPath.ToString()); EditorImGui.Separator(); if (draft.settingsSource != sourceId) + { LoadSourceSettings(info.assetPath, sourceId); + } bool readOnly = !owner.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) || entry.isReadOnly; EditorImGui.BeginDisabled(readOnly); try @@ -47,15 +57,19 @@ private void SourceSettings(Guid sourceId) InspectorRow("source.language", "Language", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##language", settings.languageId)) + { return; + } try { foreach (string language in owner.frontends.languageIds) + { if (EditorImGui.Selectable(language, settings.languageId == language)) { settings.languageId = language; changed = true; } + } } finally { @@ -64,7 +78,11 @@ private void SourceSettings(Guid sourceId) }); string implementation = settings.implementationId; bool implementationChanged = false; - InspectorRow("source.adapter", "Adapter", () => implementationChanged = EditorImGui.InputText("##adapter", ref implementation, 256)); + InspectorRow( + "source.adapter", + "Adapter", + () => implementationChanged = EditorImGui.InputText("##adapter", ref implementation, 256) + ); if (implementationChanged) { settings.implementationId = implementation; @@ -82,14 +100,20 @@ private void SourceSettings(Guid sourceId) int catalogOrder = settings.catalogOrder; bool orderChanged = false; - InspectorRow("source.catalog-order", "Catalog Order", () => orderChanged = EditorImGui.InputInt("##catalog-order", ref catalogOrder, 1, 100, 0)); + InspectorRow( + "source.catalog-order", + "Catalog Order", + () => orderChanged = EditorImGui.InputInt("##catalog-order", ref catalogOrder, 1, 100, 0) + ); if (orderChanged) { settings.catalogOrder = catalogOrder; changed = true; } - EditorUI.current.widgets.WrappedText("Catalog paths are declared by the source library and group its exported functions in Shader creation tools. They do not affect compilation or runtime assets."); + EditorUI.current.widgets.WrappedText( + "Catalog paths are declared by the source library and group its exported functions in Shader creation tools. They do not affect compilation or runtime assets." + ); EditorImGui.SeparatorText("Exported Functions"); for (int i = 0; i < settings.exports.Length; i++) { @@ -132,7 +156,9 @@ private void SourceSettings(Guid sourceId) changed = true; } - EditorUI.current.widgets.WrappedText("Every listed name is exported as an independent graph function. All other functions remain private helpers. Ports are parsed from each exported declaration; alternative implementations must expose matching interfaces."); + EditorUI.current.widgets.WrappedText( + "Every listed name is exported as an independent graph function. All other functions remain private helpers. Ports are parsed from each exported declaration; alternative implementations must expose matching interfaces." + ); EditorImGui.SeparatorText("Alternative Implementations"); for (int i = 0; i < settings.implementations.Length; i++) { @@ -143,26 +169,30 @@ private void SourceSettings(Guid sourceId) bool remove = false; InspectorRow("source.implementation", "Implementation " + (i + 1), () => { - if (EditorUI.current.widgets.BeginBoundedCombo("##implementation", current?.assetPath.ToString() ?? "Missing source")) - { + if (EditorUI.current.widgets.BeginBoundedCombo( + "##implementation", + current?.assetPath.ToString() ?? "Missing source" + )) { try { foreach (AssetFileEntry source in owner.assets.GetFileSystemEntries(includeDirectories: false)) + { if (source.extension == ".ishadersource" && source.assetPath != info.assetPath && EditorImGui.Selectable( - source.assetPath.ToString(), - current?.assetPath == source.assetPath - ) + source.assetPath.ToString(), + current?.assetPath == source.assetPath + ) && owner.assets.TryLoad( - source.assetPath, - out ShaderFunctionAsset? replacement - ) - && replacement is not null) - { + source.assetPath, + out ShaderFunctionAsset? replacement + ) + && replacement is not null + ) { settings.implementations[i] = replacement; changed = true; } + } } finally { @@ -196,7 +226,9 @@ out ShaderFunctionAsset? replacement } if (changed) + { draft.sourceSettings = owner.serialization.Serialize(settings, owner.context); + } EditorImGui.Separator(); if (EditorImGui.Button("Apply Import Settings")) { @@ -213,14 +245,23 @@ out ShaderFunctionAsset? replacement EditorImGui.SameLine(0f, -1f); if (EditorImGui.Button("Reload")) + { LoadSourceSettings(info.assetPath, sourceId); + } if (readOnly) - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Installed source settings are read-only."); + { + EditorUI.current.widgets.ColoredText( + Inno.Editor.ImGui.EditorPalette.textDisabled, + "Installed source settings are read-only." + ); + } if (draft.sourceSettingsStatus.Length != 0) + { EditorUI.current.widgets.WrappedText(draft.sourceSettingsStatus); + } } catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { draft.sourceSettingsStatus = failure.Message; EditorUI.current.widgets.WrappedText(draft.sourceSettingsStatus); @@ -237,7 +278,9 @@ Guid sourceId ) { AssetImportSettingsSnapshot snapshot = owner.assets.GetImportSettings(path); if (snapshot.value is not ShaderSourceImportSettings settings) + { throw new InvalidOperationException("The source importer settings are unavailable."); + } draft.settingsSource = sourceId; draft.sourceSettingsFingerprint = snapshot.fingerprint; draft.sourceSettings = owner.serialization.Serialize(settings, owner.context); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs index 90888483c..e75056e6e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs @@ -1,9 +1,11 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Inno.Core.Graphs; using Inno.Rendering.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private void DrawTarget() @@ -15,15 +17,25 @@ private void DrawTarget() InspectorRow("target", "Target", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##target", current.Length == 0 ? "Explicit Stages" : current)) + { return; + } try { if (ImGuiApi.Selectable("Explicit Stages", current.Length == 0)) + { Assign(""); + } if (owner.targets is { } targets) + { foreach (string id in targets.ids) + { if (ImGuiApi.Selectable(id, current == id)) + { Assign(id); + } + } + } } finally { @@ -39,7 +51,9 @@ private void DrawTarget() void Assign(string id) { if (id == current) + { return; + } GraphDocument candidate = Controller.document.Clone(); ShaderGraphDocument.SetTarget(candidate, id, owner.serialization, owner.context); Controller.ReplaceDocument(candidate, "Change Shader Target"); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs index 1d3d1d50b..c26447814 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs @@ -1,18 +1,24 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Linq; using Inno.Rendering; -using EditorImGui = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; +using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; + namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas { private bool TechniqueControls(ShaderDefinition definition) { if (!EditorImGui.CollapsingHeader("Techniques & Roles")) + { return false; - EditorUI.current.widgets.WrappedText("Techniques map pipeline-defined roles to this shader's passes. Contract and role identities are supplied by the rendering pipeline."); + } + EditorUI.current.widgets.WrappedText( + "Techniques map pipeline-defined roles to this shader's passes. Contract and role identities are supplied by the rendering pipeline." + ); bool changed = false; for (int i = 0; i < definition.techniques.Length; i++) { @@ -34,7 +40,11 @@ private bool TechniqueControls(ShaderDefinition definition) Gesture(); bool contractChanged = false; - InspectorRow("technique.contract", "Contract", () => contractChanged = EditorImGui.InputText("##contract", ref contract, 256)); + InspectorRow( + "technique.contract", + "Contract", + () => contractChanged = EditorImGui.InputText("##contract", ref contract, 256) + ); if (contractChanged) { technique.contract = new() @@ -75,15 +85,19 @@ private bool TechniqueControls(ShaderDefinition definition) InspectorRow("technique.pass", "Pass", () => { if (!EditorUI.current.widgets.BeginBoundedCombo("##pass", mapping.passName)) + { return; + } try { foreach (ShaderPassDefinition pass in definition.passes) + { if (EditorImGui.Selectable(pass.name, pass.name == mapping.passName)) { mapping.passName = pass.name; passChanged = true; } + } } finally { @@ -110,12 +124,14 @@ private bool TechniqueControls(ShaderDefinition definition) if (CenteredAddButton("Add Role")) { - technique.passes = [..technique.passes, new() - { - role = new("role-" + technique.passes.Length), - passName = definition.passes.FirstOrDefault().name ?? "" - } - + technique.passes = + [ + ..technique.passes, + new() + { + role = new("role-" + technique.passes.Length), + passName = definition.passes.FirstOrDefault().name ?? "" + } ]; changed = true; } @@ -141,13 +157,15 @@ private bool TechniqueControls(ShaderDefinition definition) if (CenteredAddButton("Add Technique")) { - definition.techniques = [..definition.techniques, new() - { - id = new("technique-" + Guid.NewGuid().ToString("N")), - contract = default, - passes = [] - } - + definition.techniques = + [ + ..definition.techniques, + new() + { + id = new("technique-" + Guid.NewGuid().ToString("N")), + contract = default, + passes = [] + } ]; changed = true; } @@ -158,7 +176,9 @@ private bool TechniqueControls(ShaderDefinition definition) private static bool FeatureControls(ref GraphicsCapability features) { if (!EditorImGui.TreeNode("Required Capabilities", 0)) + { return false; + } try { bool changed = false; @@ -167,10 +187,16 @@ private static bool FeatureControls(ref GraphicsCapability features) { ulong bits = Convert.ToUInt64(feature); if (bits == 0 || (bits & (bits - 1)) != 0) + { continue; + } bool enabled = (updated & feature) != 0; bool featureChanged = false; - InspectorRow("feature." + feature, feature.ToString(), () => featureChanged = EditorImGui.Checkbox("##enabled", ref enabled)); + InspectorRow( + "feature." + feature, + feature.ToString(), + () => featureChanged = EditorImGui.Checkbox("##enabled", ref enabled) + ); if (featureChanged) { updated = enabled ? updated | feature : updated & ~feature; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs index 2cd28d719..ccc0bdff0 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs @@ -1,13 +1,12 @@ -using Inno.Editor.Core; -using Inno.Editor.Graph.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using Inno.Assets.Pipeline; using Inno.Core.Graphs; +using Inno.Editor.Core; using Inno.Editor.Graph; +using Inno.Editor.Graph.ImGui; using Inno.Editor.ImGui; using Inno.Editor.Interactions; using Inno.Editor.Rendering; @@ -15,9 +14,12 @@ using Inno.Editor.Shaders.ImGui; using Inno.Rendering.Assets; using Inno.Rendering.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using ImGuiApi = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.ShaderEditor; + internal sealed partial class ShaderEditorCanvas( ShaderEditorDocuments owner, ShaderEditorDocuments.Draft draft @@ -26,6 +28,7 @@ private readonly record struct PortHandle( GraphEndpoint endpoint, GraphPortDirection direction ); + internal const string C_AREA = "panel/rendering.shader-editor"; private static readonly Vector4 C_EMPTY_GROUP_HEADER = new(0.16f, 0.17f, 0.20f, EditorPalette.opacityOpaque); private const string C_NODE_WIDTH = "editor.width"; @@ -41,6 +44,7 @@ GraphPortDirection direction private Vector2 m_origin; private Vector2 m_size; + internal void Draw() { DrawHeader(owner, draft); @@ -57,7 +61,11 @@ internal void Draw() } ImGuiApi.SetNextItemAllowOverlap(); - _ = ImGuiApi.InvisibleButton("##shader-canvas", m_size, (ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonMiddle | ImGuiButtonFlags.MouseButtonRight)); + _ = ImGuiApi.InvisibleButton( + "##shader-canvas", + m_size, + (ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonMiddle | ImGuiButtonFlags.MouseButtonRight) + ); bool hovered = ImGuiApi.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem); Vector2 mouse = ImGuiApi.GetMousePos(); bool miniMapHovered = MiniMapContains(mouse); @@ -75,9 +83,13 @@ internal void Draw() GraphNodeRecord? hit = hitGroup is null ? HitNode(mouse) : null; draft.selectedEdge = hit is null ? HitEdge(mouse) : null; if (draft.selectedEdge is not null) + { Canvas.ClearSelection(); + } if (hit is not null && !Canvas.selectedNodes.Contains(hit.id)) + { Canvas.SelectNodes([hit.id]); + } SetStage(hit); } @@ -85,7 +97,9 @@ internal void Draw() { EditorInteraction interaction = owner.interactions.For(C_AREA, entry); if (ImGuiApi.IsWindowFocused(ImGuiFocusedFlags.RootAndChildWindows)) + { interaction.Focus(); + } _ = EditorUI.current.menus.ContextMenu("##shader-menu", interaction); } @@ -99,7 +113,9 @@ internal void Draw() Groups(draw); Edges(draw); foreach (GraphNodeRecord node in Controller.document.nodes) + { Node(draw, node, mouse); + } Pointer(hovered && !miniMapHovered); if (draft.pointer.isBoxSelecting) { @@ -115,7 +131,9 @@ internal void Draw() } if (draft.compilationDiagnostics.Length != 0 && mouse.Y < m_origin.Y + 32 && hovered) + { EditorUI.current.widgets.DrawTooltip(draft.compilationDiagnostics); + } if (draft.error.Length != 0) { draw.Text(m_origin + new Vector2(12, 34), Color(1f, 0.47f, 0.44f), draft.error, 1f); @@ -137,7 +155,9 @@ internal void Draw() private void SynchronizeInspection() { if (Canvas.selectedNodes.SequenceEqual(draft.inspectedNodes)) + { return; + } draft.inspectedNodes = Canvas.selectedNodes.ToArray(); draft.inspectionSelection = new ShaderInspectionSelection(draft.id, draft.inspectedNodes); owner.interactions.SetSelection(draft.inspectionSelection); @@ -164,8 +184,10 @@ private void DrawInspectorContents(IReadOnlyList selected) bool graphNode = ShaderGraphNodes.IsNodeGraph(Controller.document); if (!graphNode) { - if (EditorUI.current.widgets.SectionHeader("Preview", "The preview uses the current draft without publishing it to Scene or Game views.")) - { + if (EditorUI.current.widgets.SectionHeader( + "Preview", + "The preview uses the current draft without publishing it to Scene or Game views." + )) { var preview = owner.Preview(draft); if (preview is null) { @@ -176,10 +198,10 @@ private void DrawInspectorContents(IReadOnlyList selected) EditorUI.current.widgets.Hint("Shader check failed. See Console."); } else if (preview.state == EditorShaderCompilationState.Succeeded - && preview.artifact is not null - && owner.interactions.TryGetModule(out var images) - && images is not null) - { + && preview.artifact is not null + && owner.interactions.TryGetModule(out var images) + && images is not null + ) { var shader = owner.assets.Load(draft.path); images.Draw( draft.id, @@ -195,18 +217,26 @@ private void DrawInspectorContents(IReadOnlyList selected) if (EditorUI.current.widgets.SectionHeader( "Graph Node", "Function Inputs and Function Outputs independently define the reusable typed interface. Check validates the interface; callers validate the inlined computation." - )) - { + )) { try { - ShaderGraphNodeInterface nodeInterface = ShaderGraphNodes.ReadInterface(Controller.document, owner.serialization, owner.context); + ShaderGraphNodeInterface nodeInterface = ShaderGraphNodes.ReadInterface( + Controller.document, + owner.serialization, + owner.context + ); InspectorRow( "graph-node.summary", "Interface", - () => EditorUI.current.widgets.WrappedText($"{nodeInterface.inputs.Length} input(s) · {nodeInterface.outputs.Length} output(s) · {nodeInterface.kind}") + () => EditorUI.current.widgets.WrappedText( + $"{nodeInterface.inputs.Length} input(s) · {nodeInterface.outputs.Length} output(s) · {nodeInterface.kind}" + ) ); } - catch (Exception failure) when (failure is InvalidOperationException or ArgumentException or FormatException or NotSupportedException) + catch (Exception failure) when (failure is InvalidOperationException + or ArgumentException + or FormatException + or NotSupportedException) { EditorUI.current.widgets.Hint(failure.Message); } @@ -218,19 +248,22 @@ private void DrawInspectorContents(IReadOnlyList selected) if (EditorUI.current.widgets.SectionHeader( graphNode ? "Node Definition" : "Shader", graphNode ? "Select Function Inputs or Function Outputs to edit this reusable node's public interface." : "Target and public interface belong to this Shader, not to any Material override." - )) - { + )) { if (!graphNode) + { DrawTarget(); + } if (Controller.document.metadata.ContainsKey(ShaderGraphDocument.definitionKey)) { var definition = ShaderGraphDocument.ReadDefinition(Controller.document, owner.serialization, owner.context); foreach (var property in definition.properties) + { InspectorRow( "definition." + property.id.value, property.displayName, () => EditorUI.current.widgets.WrappedText(property.type + " · " + property.bindingOwner) ); + } } owner.RefreshCompilation(draft); @@ -242,9 +275,13 @@ private void DrawInspectorContents(IReadOnlyList selected) GraphNodeRecord[] nodes = selected.Select(Controller.document.FindNode).OfType().ToArray(); if (nodes.Length != selected.Count) + { EditorUI.current.widgets.Hint("Some selected nodes are unavailable. Stable identities are retained."); + } if (nodes.Length == 0) + { return; + } if (nodes.Any(node => node.definitionId != nodes[0].definitionId)) { EditorUI.current.widgets.Hint("Select nodes of the same kind to edit common settings."); @@ -260,22 +297,25 @@ private void DrawInspectorContents(IReadOnlyList selected) if (EditorUI.current.widgets.SectionHeader( Title(nodes[0]), "Inputs, defaults and output configuration are edited here. Changes remain in the Shader draft until Save." - )) - { + )) { if (nodes.Length > 1) + { EditorUI.current.widgets.Hint("Editing " + nodes.Length + " nodes · differing values are replaced together"); + } Controls(nodes[0]); } ShaderNodePort[] inputs = draft.ports[nodes[0].id].Where(port => port.direction == GraphPortDirection.Input).ToArray(); if (inputs.Length != 0 && EditorUI.current.widgets.SectionHeader( - "Inputs", - "Connected inputs show their source. Optional inputs use an automatic zero; required inputs must be connected in the graph." - )) - { + "Inputs", + "Connected inputs show their source. Optional inputs use an automatic zero; required inputs must be connected in the graph." + ) + ) { foreach (ShaderNodePort port in inputs) + { DrawInputDefault(nodes[0], port); + } } } finally @@ -289,11 +329,13 @@ private void DrawInspectorContents(IReadOnlyList selected) private GraphNodeRecord[]? m_inspectionNodes; private Inno.Editor.Inspection.InspectionDrawContext? m_inspection; + private static void InspectorRow( string id, string label, Action draw ) => EditorUI.current.widgets.PropertyRow("shader." + id, label, draw); + internal static void DrawHeader( ShaderEditorDocuments owner, ShaderEditorDocuments.Draft? draft @@ -302,16 +344,18 @@ internal static void DrawHeader( EditorUI.current.widgets.HeaderSurface("##shader-header", () => { ImGuiApi.SetNextItemWidth(-1f); - string title = draft is null ? "Select Shader" : System.IO.Path.GetFileName(draft.path.localPath) + (owner.Controller(draft).isDirty ? " *" : ""); + string title = draft is null + ? "Select Shader" + : System.IO.Path.GetFileName(draft.path.localPath) + (owner.Controller(draft).isDirty ? " *" : ""); if (EditorUI.current.widgets.BeginBoundedCombo("##shader-header-select", title)) { try { - foreach (AssetFileEntry candidate in owner.assets.GetFileSystemEntries(includeDirectories: false).Where(static candidate => candidate.extension.Equals(".ishader", StringComparison.OrdinalIgnoreCase)).OrderBy( - static candidate => candidate.assetPath.ToString(), - StringComparer.Ordinal - )) - { + foreach (AssetFileEntry candidate in owner.assets + .GetFileSystemEntries(includeDirectories: false) + .Where(static candidate => candidate.extension.Equals(".ishader", StringComparison.OrdinalIgnoreCase)) + .OrderBy(static candidate => candidate.assetPath.ToString(), StringComparer.Ordinal) + ) { bool selected = draft is not null && candidate.assetPath == draft.path; if (ImGuiApi.Selectable(candidate.assetPath.ToString(), selected)) { @@ -320,7 +364,9 @@ internal static void DrawHeader( } if (selected) + { ImGuiApi.SetItemDefaultFocus(); + } } } finally @@ -332,77 +378,133 @@ internal static void DrawHeader( bool noDocument = draft is null; ImGuiApi.BeginDisabled(noDocument || draft!.readOnly); if (ImGuiApi.Button("Save") && draft is not null && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry entry)) + { _ = owner.interactions.For(C_AREA, entry).Execute("shader/save"); - EditorUI.current.widgets.DrawItemTooltip("Save this shader and apply its changes (Command/Ctrl + S). Invalid graphs can be saved; rendering retains the last successful programs."); + } + EditorUI.current.widgets.DrawItemTooltip( + "Save this shader and apply its changes (Command/Ctrl + S). Invalid graphs can be saved; rendering retains the last successful programs." + ); ImGuiApi.SameLine(0f, -1f); if (ImGuiApi.Button("Revert") && draft is not null) + { _ = owner.interactions.documents.Revert(draft.documentId); + } EditorUI.current.widgets.DrawItemTooltip("Restore the saved shader. This draft change can be undone."); ImGuiApi.EndDisabled(); ImGuiApi.SameLine(0f, -1f); ImGuiApi.BeginDisabled(noDocument); - if (ImGuiApi.Button("Format") && draft is not null && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry formatEntry)) + if (ImGuiApi.Button("Format") + && draft is not null + && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry formatEntry) + ) { _ = owner.interactions.For(C_AREA, formatEntry).Execute("shader/format"); - EditorUI.current.widgets.DrawItemTooltip("Arrange the graph from inputs on the left to outputs on the right. This changes only authoring positions and is undoable."); + } + EditorUI.current.widgets.DrawItemTooltip( + "Arrange the graph from inputs on the left to outputs on the right. This changes only authoring positions and is undoable." + ); ImGuiApi.SameLine(0f, -1f); - if (ImGuiApi.Button("Check") && draft is not null && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry checkEntry)) + if (ImGuiApi.Button("Check") + && draft is not null + && owner.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry checkEntry) + ) { _ = owner.interactions.For(C_AREA, checkEntry).Execute("shader/check"); - EditorUI.current.widgets.DrawItemTooltip("Compile-check the current draft without saving or publishing it, and show diagnostics with source locations."); + } + EditorUI.current.widgets.DrawItemTooltip( + "Compile-check the current draft without saving or publishing it, and show diagnostics with source locations." + ); ImGuiApi.EndDisabled(); }, spanWindowPadding: true); } private void RefreshPorts() { - if (draft.portRevision == Controller.revision && draft.assetRevision == owner.assets.revision && draft.typeRevision == owner.typeVersion) + if (draft.portRevision == Controller.revision + && draft.assetRevision == owner.assets.revision + && draft.typeRevision == owner.typeVersion + ) { return; + } draft.ports.Clear(); draft.missingPorts.Clear(); draft.nodeErrors.Clear(); foreach (GraphNodeRecord node in Controller.document.nodes) { if (!draft.portSnapshots.ContainsKey(node.id)) + { draft.portSnapshots[node.id] = Read(node, ShaderEditorDocuments.C_PORT_SNAPSHOT, Array.Empty()); + } var ports = new List(); try { if (node.definitionId == ShaderGraphDocument.outputDefinitionId) { ShaderGraphStageSettings settings = Read(node, "settings", new ShaderGraphStageSettings()); - ports.AddRange(settings.outputs.Select(static output => new ShaderNodePort(output.id, ShaderSourceType.Atomic(output.kind == ShaderIrOutputKind.Depth ? "float" : output.kind == ShaderIrOutputKind.Varying ? "any" : "float4"), GraphPortDirection.Input))); + ports.AddRange( + settings.outputs.Select( + static output => new ShaderNodePort( + output.id, + ShaderSourceType.Atomic( + output.kind == ShaderIrOutputKind.Depth + ? "float" + : output.kind == ShaderIrOutputKind.Varying ? "any" : "float4" + ), + GraphPortDirection.Input + ) + ) + ); } else + { ports.AddRange(owner.Describe(node)); + } } catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { draft.nodeErrors[node.id] = failure.Message; } foreach (ShaderPortSnapshot old in draft.portSnapshots[node.id]) + { if (!ports.Any(port => port.id == old.id)) { ports.Add(new(old.id, old.type.CreateType(), old.direction, old.required)); draft.missingPorts.Add(new(node.id, new(old.id))); } + } foreach (GraphEdgeRecord edge in Controller.document.edges) { if (edge.input.nodeId == node.id) + { KeepEndpoint(edge.input, GraphPortDirection.Input); + } if (edge.output.nodeId == node.id) + { KeepEndpoint(edge.output, GraphPortDirection.Output); + } } - draft.portSnapshots[node.id] = ports.Select(static port => new ShaderPortSnapshot { id = port.id, type = ShaderGraphType.Capture(port.type), direction = port.direction, required = port.required }).ToArray(); + draft.portSnapshots[node.id] = ports + .Select( + static port => new ShaderPortSnapshot + { + id = port.id, + type = ShaderGraphType.Capture(port.type), + direction = port.direction, + required = port.required + } + ) + .ToArray(); draft.ports.Add(node.id, ports.ToArray()); void KeepEndpoint( GraphEndpoint endpoint, GraphPortDirection direction ) { if (ports.Any(port => port.id == endpoint.portId.value)) + { return; + } ports.Add(new(endpoint.portId.value, ShaderSourceType.Atomic("missing"), direction, false)); draft.missingPorts.Add(endpoint); } @@ -462,7 +564,9 @@ private void Navigate(bool hovered) private void Pointer(bool hovered) { if (ImGuiApi.IsAnyPopupOpen()) + { return; + } if (draft.navigation.isPanning || ImGuiApi.GetInput().alt) { owner.CompleteCanvasEdit(draft); @@ -479,7 +583,11 @@ private void Pointer(bool hovered) ImGuiApi.SetMouseCursor(ImGuiMouseCursor.ResizeNwse); if (ImGuiApi.IsMouseButtonDown(ImGuiMouseButton.Left)) { - draft.resizePreviewWidth = Math.Clamp(draft.resizeStartWidth + (mouse.X - draft.resizePointerStart.X) / Canvas.zoom, C_MINIMUM_WIDTH, C_MAXIMUM_WIDTH); + draft.resizePreviewWidth = Math.Clamp( + draft.resizeStartWidth + (mouse.X - draft.resizePointerStart.X) / Canvas.zoom, + C_MINIMUM_WIDTH, + C_MAXIMUM_WIDTH + ); } else { @@ -491,7 +599,9 @@ private void Pointer(bool hovered) GraphNodeRecord? resizeTarget = !draft.readOnly && hovered ? HitResizeHandle(mouse) : null; if (resizeTarget is not null) + { ImGuiApi.SetMouseCursor(ImGuiMouseCursor.ResizeNwse); + } if (hovered && ImGuiApi.IsMouseClicked(ImGuiMouseButton.Left)) { if (resizeTarget is not null) @@ -515,7 +625,9 @@ private void Pointer(bool hovered) Canvas.SelectNodes(selectedGroup.nodes.Select(static id => new GraphNodeId(id))); SynchronizeInspection(); if (!draft.readOnly) + { draft.pointer.BeginMove(draft.layout, Canvas.selectedNodes, mouse); + } return; } if (hitNode is null && HitPort(mouse) is null) @@ -525,7 +637,9 @@ private void Pointer(bool hovered) if (draft.selectedEdge is not null) { if (!ImGuiApi.GetInput().shift) + { Canvas.ClearSelection(); + } return; } } @@ -548,7 +662,9 @@ private void Pointer(bool hovered) SetStage(node); SynchronizeInspection(); if (!draft.readOnly && !draft.pointer.isMoving) + { draft.pointer.BeginMove(draft.layout, Canvas.selectedNodes, mouse); + } } if (intent.movedNodes is { } positions) { @@ -580,41 +696,74 @@ Vector2 mouse ) { var rect = Rect(node); if (rect.max.X < m_origin.X || rect.min.X > m_origin.X + m_size.X || rect.max.Y < m_origin.Y || rect.min.Y > m_origin.Y + m_size.Y) + { return; + } float zoom = Canvas.zoom; if (!draft.layout.TryGetNode(node.id, out GraphCanvasNode? presentation)) + { return; - _ = View.DrawNode(draw, presentation, ImGuiApi.ToPackedColor(NodeHeaderColor(node)), Canvas.selectedNodes.Contains(node.id), - previewPosition: draft.pointer.previewPositions.TryGetValue(node.id, out GraphPosition preview) ? preview : null); + } + _ = View.DrawNode( + draw, + presentation, + ImGuiApi.ToPackedColor(NodeHeaderColor(node)), + Canvas.selectedNodes.Contains(node.id), + previewPosition: draft.pointer.previewPositions.TryGetValue(node.id, out GraphPosition preview) ? preview : null + ); ShaderNodePort[] nodePorts = draft.ports[node.id]; if (UsesSplitPortLayout(nodePorts)) { float divider = (rect.min.X + rect.max.X) * 0.5f; float padding = 7f * zoom; - draw.Line(new(divider, rect.min.Y + C_HEADER * zoom + padding), new(divider, rect.max.Y - padding), - Color(0.62f, 0.63f, 0.69f, EditorPalette.opacityFaint), 1f); + draw.Line( + new(divider, rect.min.Y + C_HEADER * zoom + padding), + new(divider, rect.max.Y - padding), + Color(0.62f, 0.63f, 0.69f, EditorPalette.opacityFaint), + 1f + ); } foreach (ShaderNodePort port in nodePorts) { var endpoint = new GraphEndpoint(node.id, new GraphPortId(port.id)); if (!TryPortPosition(endpoint, port.direction, out Vector2 point)) + { continue; + } if (Vector2.DistanceSquared(point, mouse) <= 64f) { bool missing = draft.missingPorts.Contains(endpoint); bool optional = port.direction == GraphPortDirection.Input && !port.required; - EditorUI.current.widgets.DrawTooltip(port.type.id + (missing ? " · missing port; reconnect explicitly" - : optional ? " · optional input" : port.direction == GraphPortDirection.Input ? " · required input" : "")); + EditorUI.current.widgets.DrawTooltip( + port.type.id + (missing + ? " · missing port; reconnect explicitly" + : optional ? " · optional input" : port.direction == GraphPortDirection.Input ? " · required input" : "") + ); } } if (!draft.readOnly) { bool resizeHovered = ContainsResizeHandle(rect, ImGuiApi.GetMousePos()); - uint gripColor = Color(0.62f, 0.63f, 0.69f, resizeHovered || draft.resizingNode == node.id ? EditorPalette.opacityEmphasized : EditorPalette.opacityMedium); + uint gripColor = Color( + 0.62f, + 0.63f, + 0.69f, + resizeHovered || draft.resizingNode == node.id ? EditorPalette.opacityEmphasized : EditorPalette.opacityMedium + ); const float inset = 4f; - draw.Line(rect.max - new Vector2(C_RESIZE_HANDLE, inset) * zoom, rect.max - new Vector2(inset, C_RESIZE_HANDLE) * zoom, gripColor, 1f); - draw.Line(rect.max - new Vector2(C_RESIZE_HANDLE * 0.62f, inset) * zoom, rect.max - new Vector2(inset, C_RESIZE_HANDLE * 0.62f) * zoom, gripColor, 1f); + draw.Line( + rect.max - new Vector2(C_RESIZE_HANDLE, inset) * zoom, + rect.max - new Vector2(inset, C_RESIZE_HANDLE) * zoom, + gripColor, + 1f + ); + draw.Line( + rect.max - new Vector2(C_RESIZE_HANDLE * 0.62f, inset) * zoom, + rect.max - new Vector2(inset, C_RESIZE_HANDLE * 0.62f) * zoom, + gripColor, + 1f + ); } if (draft.ports[node.id].Length == 0 && node.definitionId == ShaderGraphNodes.inputDefinitionId) @@ -631,27 +780,27 @@ Vector2 mouse { draw.FilledCircle(new(rect.max.X - 14 * zoom, rect.min.Y + 16 * zoom), 4 * zoom, Color(1, 0.4f, 0.35f)); if (Contains(rect, ImGuiApi.GetMousePos())) + { EditorUI.current.widgets.DrawTooltip(error); + } } } private void Grid(EditorDrawList draw) => View.DrawGrid(Color(0.105f, 0.115f, 0.135f)); + private void Groups(EditorDrawList draw) { foreach (ShaderCanvasGroup group in draft.groups) { if (GroupRect(group) is not { } bounds) + { continue; + } Vector2 min = bounds.min, max = bounds.max; bool selected = draft.selectedGroupId == group.id; Vector4 headerColor = GroupHeaderColor(group); Vector4 bodyColor = EditorPalette.WithOpacity(headerColor, EditorPalette.opacitySoft); - Vector4 borderColor = selected ? new( - 0.65f, - 0.47f, - 0.88f, - EditorPalette.opacityOpaque - ) : new( + Vector4 borderColor = selected ? new(0.65f, 0.47f, 0.88f, EditorPalette.opacityOpaque) : new( MathF.Min(1f, headerColor.X * 1.22f), MathF.Min(1f, headerColor.Y * 1.22f), MathF.Min(1f, headerColor.Z * 1.22f), @@ -676,8 +825,16 @@ private void Groups(EditorDrawList draw) private ShaderCanvasGroup? HitGroupHeader(Vector2 point) { foreach (ShaderCanvasGroup group in draft.groups.Reverse()) - if (GroupRect(group) is { } bounds && point.X >= bounds.min.X && point.X <= bounds.max.X && point.Y >= bounds.min.Y && point.Y <= bounds.min.Y + 32f * Canvas.zoom) + { + if (GroupRect(group) is { } bounds + && point.X >= bounds.min.X + && point.X <= bounds.max.X + && point.Y >= bounds.min.Y + && point.Y <= bounds.min.Y + 32f * Canvas.zoom + ) { return group; + } + } return null; } @@ -685,35 +842,45 @@ private void Groups(EditorDrawList draw) { Vector2 min = new(float.MaxValue), max = new(float.MinValue); foreach (string id in group.nodes) + { if (Controller.document.FindNode(new(id)) is GraphNodeRecord node) { var rect = Rect(node); min = Vector2.Min(min, rect.min); max = Vector2.Max(max, rect.max); } + } if (min.X == float.MaxValue) + { return null; + } return (min - new Vector2(20, 40) * Canvas.zoom, max + new Vector2(20) * Canvas.zoom); } private void RefreshGeometry() { bool changed = draft.layoutRevision != Controller.revision - || draft.layoutAssetRevision != owner.assets.revision || draft.layoutTypeRevision != owner.typeVersion; + || draft.layoutAssetRevision != owner.assets.revision || draft.layoutTypeRevision != owner.typeVersion; if (!changed && draft.resizingNode is GraphNodeId resizing && draft.layout.TryGetNode(resizing, out GraphCanvasNode? current) - && Controller.document.FindNode(resizing) is { } resizedNode) - { + && Controller.document.FindNode(resizing) is { } resizedNode + ) { if (current.size.X != NodeWidth(resizedNode)) + { _ = draft.layout.SetNodes(draft.layout.nodes.Select(node => node.id == resizing ? DescribeNode(resizedNode) : node)); + } return; } if (!changed) + { return; + } var nodes = new List(Controller.document.nodes.Count); foreach (GraphNodeRecord node in Controller.document.nodes) + { nodes.Add(DescribeNode(node)); + } _ = draft.layout.SetNodes(nodes); draft.layoutRevision = Controller.revision; draft.layoutAssetRevision = owner.assets.revision; @@ -732,13 +899,27 @@ GraphCanvasNode DescribeNode(GraphNodeRecord node) int row = input ? left++ : right++; float y = C_HEADER + C_ROW * (row + 0.5f); var endpoint = new GraphEndpoint(node.id, new GraphPortId(port.id)); - ports.Add(new GraphCanvasPort(endpoint, port.direction, new(input ? 0f : width, y), port.id, - input && !port.required, draft.missingPorts.Contains(endpoint), - (new(split && !input ? width * 0.5f : 0f, y - C_ROW * 0.5f), - new(split && input ? width * 0.5f : width, y + C_ROW * 0.5f)))); + ports.Add( + new GraphCanvasPort( + endpoint, + port.direction, + new(input ? 0f : width, y), + port.id, + input && !port.required, + draft.missingPorts.Contains(endpoint), + (new(split && !input ? width * 0.5f : 0f, y - C_ROW * 0.5f), + new(split && input ? width * 0.5f : width, y + C_ROW * 0.5f)) + ) + ); } - return new GraphCanvasNode(node.id, node.position, - new(width, C_HEADER + Rows(node) * C_ROW + 20f), C_HEADER, Title(node), ports); + return new GraphCanvasNode( + node.id, + node.position, + new(width, C_HEADER + Rows(node) * C_ROW + 20f), + C_HEADER, + Title(node), + ports + ); } } @@ -748,12 +929,17 @@ private bool TryPortPosition( out Vector2 position ) { if (draft.layout.TryGetNode(endpoint.nodeId, out GraphCanvasNode? node)) + { foreach (GraphCanvasPort port in node.ports) + { if (port.endpoint == endpoint && port.direction == direction) { - position = View.ToScreen(draft.pointer.previewPositions.GetValueOrDefault(node.id, node.position)) + port.position * Canvas.zoom; + position = View.ToScreen(draft.pointer.previewPositions.GetValueOrDefault(node.id, node.position)) + + port.position * Canvas.zoom; return true; } + } + } position = default; return false; } @@ -761,20 +947,25 @@ out Vector2 position private void Edges(EditorDrawList draw) { foreach (GraphEdgeRecord edge in Controller.document.edges) - if (TryPortPosition(edge.output, GraphPortDirection.Output, out Vector2 a) && TryPortPosition(edge.input, GraphPortDirection.Input, out Vector2 b)) + { + if (TryPortPosition(edge.output, GraphPortDirection.Output, out Vector2 a) + && TryPortPosition(edge.input, GraphPortDirection.Input, out Vector2 b) + ) { Curve(a, b, edge.id == draft.selectedEdge); + } + } if (Canvas.pendingConnection is GraphEndpoint pending && Canvas.pendingConnectionDirection is GraphPortDirection direction - && TryPortPosition( - pending, - direction, - out Vector2 start - )) - { + && TryPortPosition(pending, direction, out Vector2 start) + ) { if (direction == GraphPortDirection.Output) + { Curve(start, ImGuiApi.GetMousePos()); + } else + { Curve(ImGuiApi.GetMousePos(), start); + } } void Curve( @@ -790,10 +981,15 @@ void Curve( { foreach (GraphEdgeRecord edge in Controller.document.edges) { - if (!TryPortPosition(edge.output, GraphPortDirection.Output, out Vector2 a) || !TryPortPosition(edge.input, GraphPortDirection.Input, out Vector2 b)) + if (!TryPortPosition(edge.output, GraphPortDirection.Output, out Vector2 a) + || !TryPortPosition(edge.input, GraphPortDirection.Input, out Vector2 b) + ) { continue; + } if (GraphCanvasView.HitConnection(mouse, a, b)) + { return edge.id; + } } return null; @@ -802,7 +998,12 @@ void Curve( private (Vector2 min, Vector2 max) Rect(GraphNodeRecord node) { if (draft.layout.TryGetNode(node.id, out GraphCanvasNode? presentation)) - return View.NodeBounds(presentation, draft.pointer.previewPositions.TryGetValue(node.id, out GraphPosition preview) ? preview : null); + { + return View.NodeBounds( + presentation, + draft.pointer.previewPositions.TryGetValue(node.id, out GraphPosition preview) ? preview : null + ); + } Vector2 minimum = View.ToScreen(node.position); return (minimum, minimum + new Vector2(NodeWidth(node), C_HEADER + Rows(node) * C_ROW + 20f) * Canvas.zoom); } @@ -816,12 +1017,15 @@ private int Rows(GraphNodeRecord node) return rows == 0 && node.definitionId is ShaderGraphNodes.inputDefinitionId or ShaderGraphNodes.outputDefinitionId ? 1 : rows; } - private static bool UsesSplitPortLayout(IEnumerable ports) => ports.Any(static port => port.direction == GraphPortDirection.Input) - && ports.Any(static port => port.direction == GraphPortDirection.Output); + private static bool UsesSplitPortLayout(IEnumerable ports) + => ports.Any(static port => port.direction == GraphPortDirection.Input) + && ports.Any(static port => port.direction == GraphPortDirection.Output); + private GraphNodeRecord? HitNode(Vector2 point) => View.HitNode(draft.layout, point) is { } node ? Controller.document.FindNode(node.id) : null; - private PortHandle? HitPort(Vector2 point) => View.HitPort(draft.layout, point) is { } port ? new PortHandle(port.endpoint, port.direction) : null; + private PortHandle? HitPort(Vector2 point) + => View.HitPort(draft.layout, point) is { } port ? new PortHandle(port.endpoint, port.direction) : null; private GraphNodeRecord? HitResizeHandle(Vector2 point) { @@ -829,7 +1033,9 @@ private static bool UsesSplitPortLayout(IEnumerable ports) => po { (Vector2 min, Vector2 max) rect = Rect(node); if (ContainsResizeHandle(rect, point)) + { return node; + } } return null; @@ -848,24 +1054,34 @@ private float NodeWidth( bool includePreview = true ) { if (includePreview && draft.resizingNode == node.id) + { return draft.resizePreviewWidth; + } float width = Read(node, C_NODE_WIDTH, C_DEFAULT_WIDTH); return float.IsFinite(width) ? Math.Clamp(width, C_MINIMUM_WIDTH, C_MAXIMUM_WIDTH) : C_DEFAULT_WIDTH; } - private ShaderNodePort Port(PortHandle handle) => draft.ports[handle.endpoint.nodeId].Single(port => port.id == handle.endpoint.portId.value && port.direction == handle.direction); + private ShaderNodePort Port(PortHandle handle) + => draft.ports[handle.endpoint.nodeId].Single( + port => port.id == handle.endpoint.portId.value && port.direction == handle.direction + ); + private ShaderNodePort Port(GraphEndpoint endpoint) => draft.ports[endpoint.nodeId].Single(port => port.id == endpoint.portId.value); + private GraphPosition ToGraph(Vector2 point) => View.ToGraph(point); + private static bool Contains( (Vector2 min, Vector2 max) rect, Vector2 point ) => point.X >= rect.min.X && point.Y >= rect.min.Y && point.X <= rect.max.X && point.Y <= rect.max.Y; + private static uint Color( float r, float g, float b, float a = EditorPalette.opacityOpaque ) => ImGuiApi.ToPackedColor(new(r, g, b, a)); + private Vector4 NodeHeaderColor(GraphNodeRecord node) { string key = node.definitionId + "/" + Title(node); @@ -877,10 +1093,16 @@ private Vector4 NodeHeaderColor(GraphNodeRecord node) "inno.shader.sample" => StableHeaderColor(key, 158f, 30f), "inno.shader.source" => StableHeaderColor(key, 198f, 42f), "inno.shader.binary" => StableHeaderColor(key, 205f, 45f), - "inno.shader.construct" or "inno.shader.extract" or "inno.shader.select" or "inno.shader.reroute" => StableHeaderColor(key, 178f, 58f), - "inno.shader.storage-load" or "inno.shader.storage-store" or "inno.shader.storage-atomic-add" => StableHeaderColor(key, 105f, 42f), + "inno.shader.construct" + or "inno.shader.extract" + or "inno.shader.select" + or "inno.shader.reroute" => StableHeaderColor(key, 178f, 58f), + "inno.shader.storage-load" + or "inno.shader.storage-store" + or "inno.shader.storage-atomic-add" => StableHeaderColor(key, 105f, 42f), "inno.shader.discard" => StableHeaderColor(key, 350f, 22f), - _ => StableHeaderColor(key, 0f, 360f)}; + _ => StableHeaderColor(key, 0f, 360f) + }; } private Vector4 GroupHeaderColor(ShaderCanvasGroup group) @@ -890,13 +1112,17 @@ private Vector4 GroupHeaderColor(ShaderCanvasGroup group) foreach (string id in group.nodes) { if (Controller.document.FindNode(new(id)) is not GraphNodeRecord node) + { continue; + } total += NodeHeaderColor(node); count++; } if (count == 0) + { return C_EMPTY_GROUP_HEADER; + } Vector4 average = total / count; return EditorPalette.WithOpacity(average, EditorPalette.opacityNearOpaque); } @@ -926,23 +1152,33 @@ float hueRange < 3f => (0f, chroma, secondary), < 4f => (0f, secondary, chroma), < 5f => (secondary, 0f, chroma), - _ => (chroma, 0f, secondary)}; + _ => (chroma, 0f, secondary) + }; float match = brightness - chroma; return new(red + match, green + match, blue + match, EditorPalette.opacityOpaque); } - private static bool CenteredAddButton(string label) => EditorUI.current.widgets.CenteredButton(label, EditorUI.current.widgets.style.addButtonTopPadding); + private static bool CenteredAddButton(string label) + => EditorUI.current.widgets.CenteredButton(label, EditorUI.current.widgets.style.addButtonTopPadding); + private T Read( GraphNodeRecord node, string key, T value ) => ShaderGraphDocument.Read(node, key, value, owner.serialization, owner.context); + private void Set( GraphNodeRecord node, string key, T value, bool continuous = false - ) => SetEncoded(node, key, ShaderGraphDocument.Encode(value, owner.serialization, owner.context), continuous ? draft.valueGesture : null); + ) => SetEncoded( + node, + key, + ShaderGraphDocument.Encode(value, owner.serialization, owner.context), + continuous ? draft.valueGesture : null + ); + private void SetEncoded( GraphNodeRecord node, string key, @@ -955,6 +1191,7 @@ private void SetEncoded( foreach (GraphNodeRecord target in selected) { if (key == "settings" && target.definitionId == "inno.shader.stage-input") + { candidate = ShaderGraphBindings.ChangeInput( candidate, target.id, @@ -962,13 +1199,17 @@ private void SetEncoded( owner.serialization, owner.context ); + } else + { candidate.FindNode(target.id)!.SetValue(key, value.Clone()); + } } Controller.ReplaceDocument(candidate, "Edit Shader Nodes", mergeKey); } else if (key == "settings" && node.definitionId == "inno.shader.stage-input") + { Controller.ReplaceDocument( ShaderGraphBindings.ChangeInput( Controller.document, @@ -980,40 +1221,61 @@ private void SetEncoded( "Edit Shader Input", mergeKey ); + } else + { Controller.SetNodeValue(node.id, key, value, mergeKey); + } owner.Changed(draft); } private void SetStage(GraphNodeRecord? node) { if (node is null) + { return; + } string stage = node.definitionId == ShaderGraphDocument.outputDefinitionId ? node.id.value : Read(node, "stage", ""); if (stage.Length != 0) + { draft.activeStage = new(stage); + } } private void Frame() { - GraphNodeRecord[] selection = Controller.document.nodes.Where(node => Canvas.selectedNodes.Count == 0 || Canvas.selectedNodes.Contains(node.id)).ToArray(); + GraphNodeRecord[] selection = Controller.document.nodes + .Where(node => Canvas.selectedNodes.Count == 0 || Canvas.selectedNodes.Contains(node.id)) + .ToArray(); if (selection.Length == 0) + { return; + } float minX = selection.Min(static node => node.position.x), minY = selection.Min(static node => node.position.y); float maxX = selection.Max(node => node.position.x + NodeWidth(node)); float maxY = selection.Max(node => node.position.y + C_HEADER + Rows(node) * C_ROW + 20); - float scale = Math.Clamp(MathF.Min(MathF.Max(1, m_size.X - 80) / MathF.Max(1, maxX - minX), MathF.Max(1, m_size.Y - 80) / MathF.Max(1, maxY - minY)), 0.1f, 1f); + float scale = Math.Clamp( + MathF.Min(MathF.Max(1, m_size.X - 80) / MathF.Max(1, maxX - minX), MathF.Max(1, m_size.Y - 80) / MathF.Max(1, maxY - minY)), + 0.1f, + 1f + ); Canvas.SetViewport(new(m_size.X / 2 - (minX + maxX) / 2 * scale, m_size.Y / 2 - (minY + maxY) / 2 * scale), scale); } internal string Title(GraphNodeRecord node) { if (owner.drawers?.GetDisplayName(node.definitionId) is { } displayName) + { return displayName; + } if (node.definitionId == ShaderGraphDocument.outputDefinitionId) + { return Read(node, "settings", new ShaderGraphStageSettings()).stage + " Output"; + } if (node.definitionId == "inno.shader.binary") + { return EditorDisplayNames.Nicify(Read(node, "operation", "add").Replace('-', ' ')); + } if (node.definitionId == "inno.shader.stage-input") { ShaderGraphInputSettings input = Read(node, "settings", new ShaderGraphInputSettings()); @@ -1027,15 +1289,21 @@ internal string Title(GraphNodeRecord node) } if (node.definitionId == ShaderGraphNodes.callDefinitionId) + { return Read(node, ShaderGraphNodes.interfaceKey, new ShaderGraphNodeInterface()).displayName; + } if (node.definitionId == ShaderGraphNodes.inputDefinitionId) + { return ShaderGraphNodes.ReadSettings( Controller.document, owner.serialization, owner.context ).kind == ShaderGraphNodeKind.DomainOutput ? "Domain Inputs" : "Function Inputs"; + } if (node.definitionId == ShaderGraphNodes.outputDefinitionId) + { return "Function Outputs"; + } return EditorDisplayNames.Nicify(node.definitionId.Replace("inno.shader.", "", StringComparison.Ordinal).Replace('-', ' ')); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs index c1b20ea5e..f17f9a89e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs @@ -14,13 +14,15 @@ internal void CompleteCanvasEdit(Draft draft) // A preview remains presentation-only until this atomic domain edit succeeds. // Preserve a released intent when History rejects the operation so it can be retried. draft.pendingMove ??= draft.pointer.previewPositions.Count == 0 - ? null - : new Dictionary(draft.pointer.previewPositions); + ? null + : new Dictionary(draft.pointer.previewPositions); if (draft.pendingMove is { } positions) { bool changed = false; foreach (var entry in positions) + { changed |= controller.document.FindNode(entry.Key) is not { } current || current.position != entry.Value; + } if (changed) { controller.MoveNodes(positions); @@ -29,10 +31,12 @@ internal void CompleteCanvasEdit(Draft draft) draft.pendingMove = null; } if (draft.resizingNode is GraphNodeId resizing - && controller.document.FindNode(resizing) is { } node) - { + && controller.document.FindNode(resizing) is { } node + ) { GraphDocument replacement = controller.document.Clone(); - replacement.FindNode(node.id)!.SetValue("editor.width", ShaderGraphDocument.Encode(draft.resizePreviewWidth, serialization, context)); + replacement + .FindNode(node.id)! + .SetValue("editor.width", ShaderGraphDocument.Encode(draft.resizePreviewWidth, serialization, context)); controller.ReplaceDocument(replacement, "Resize Shader Node"); Changed(draft); } @@ -42,7 +46,9 @@ internal void CompleteCanvasEdit(Draft draft) private void CompleteCanvasEdits() { foreach (Draft draft in m_drafts.Values) + { CompleteCanvasEdit(draft); + } } internal static void CancelCanvasEdit(Draft draft) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs index 5bc8afbdf..e082cc263 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs @@ -14,7 +14,13 @@ Guid owner internal sealed partial class ShaderEditorDocuments { internal ShaderClipboardData Copy(Draft draft) - => new(GraphDocumentCodec.Encode(ShaderGraphClipboard.Copy(Controller(draft).document, draft.canvas.selectedNodes, serialization, context), serialization), draft.id); + => new( + GraphDocumentCodec.Encode( + ShaderGraphClipboard.Copy(Controller(draft).document, draft.canvas.selectedNodes, serialization, context), + serialization + ), + draft.id + ); internal bool CanPaste( Draft draft, @@ -35,10 +41,18 @@ internal void Paste( ShaderClipboardData clipboard ) { if (!CanPaste(draft, clipboard)) + { throw new InvalidOperationException("The shader already contains an output for one of the copied stages."); + } GraphDocumentController controller = Controller(draft); - ShaderGraphPasteResult result = ShaderGraphClipboard.Paste(controller.document, - GraphDocumentCodec.Decode(clipboard.graph, serialization), clipboard.owner == draft.id, draft.activeStage, serialization, context); + ShaderGraphPasteResult result = ShaderGraphClipboard.Paste( + controller.document, + GraphDocumentCodec.Decode(clipboard.graph, serialization), + clipboard.owner == draft.id, + draft.activeStage, + serialization, + context + ); controller.ReplaceDocument(result.document, "Paste Shader Nodes"); draft.canvas.SelectNodes(result.insertedNodes); Changed(draft); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs index e79f5c5dc..44f39f85e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs @@ -6,8 +6,8 @@ using Inno.Core.Graphs; using Inno.Rendering; using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; @@ -26,37 +26,63 @@ ShaderNodeCreation creation GraphDocument graph = Controller(draft).document; GraphNodeId? stage = draft.createFromPort is GraphEndpoint endpoint ? new(ShaderGraphDocument.Read(graph.FindNode(endpoint.nodeId)!, "stage", "", serialization, context)) - : draft.activeStage ?? graph.nodes.FirstOrDefault(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId)?.id; + : draft.activeStage + ?? graph.nodes.FirstOrDefault(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId)?.id; var node = new GraphNodeRecord(new(Guid.NewGuid().ToString("N")), creation.definitionId) { position = draft.menuPosition }; if (stage is GraphNodeId id) + { node.SetValue("stage", ShaderGraphDocument.Encode(id.value, serialization, context)); + } if (creation.definitionId == "inno.shader.stage-input") { HashSet names = graph.nodes.Where(static value => value.definitionId == "inno.shader.stage-input") - .Select(value => ShaderGraphDocument.Read(value, "settings", new ShaderGraphInputSettings(), serialization, context).id).ToHashSet(StringComparer.Ordinal); + .Select(value => ShaderGraphDocument.Read(value, "settings", new ShaderGraphInputSettings(), serialization, context).id) + .ToHashSet(StringComparer.Ordinal); string name = "parameter"; for (int suffix = 2; names.Contains(name); suffix++) + { name = "parameter" + suffix; - node.SetValue("settings", ShaderGraphDocument.Encode(new ShaderGraphInputSettings - { id = name, kind = ShaderIrInputKind.Uniform, type = new() { id = "float4" }, semantic = "" }, serialization, context)); + } + node.SetValue( + "settings", + ShaderGraphDocument.Encode(new ShaderGraphInputSettings + { + id = name, + kind = ShaderIrInputKind.Uniform, + type = new() { id = "float4" }, + semantic = "" + }, serialization, context) + ); } else if (creation.definitionId == ShaderGraphNodes.inputDefinitionId) - node.SetValue(ShaderGraphDocument.settingsKey, - ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings(), serialization, context)); + { + node.SetValue( + ShaderGraphDocument.settingsKey, + ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings(), serialization, context) + ); + } else if (creation.definitionId == ShaderGraphNodes.outputDefinitionId) - node.SetValue(ShaderGraphDocument.settingsKey, - ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings(), serialization, context)); + { + node.SetValue( + ShaderGraphDocument.settingsKey, + ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings(), serialization, context) + ); + } if (draft.createFromPort is GraphEndpoint source) { ShaderNodePort port = draft.ports[source.nodeId].Single(value => value.id == source.portId.value); node.SetValue("type", ShaderGraphDocument.Encode(port.type.id, serialization, context)); if (creation.definitionId == "inno.shader.reroute") + { node.SetValue("valueType", ShaderGraphDocument.Encode(ShaderGraphType.Capture(port.type), serialization, context)); + } } if (creation.sourceId != Guid.Empty) { if (!assets.TryGetInfo(creation.sourceId, out AssetInfo? info) || info is null) + { throw new IOException("Referenced Shader authoring asset is unavailable."); + } node.SetValue("sourceId", ShaderGraphDocument.Encode(creation.sourceId, serialization, context)); node.SetValue("sourcePath", ShaderGraphDocument.Encode(info.assetPath.ToString(), serialization, context)); if (creation.definitionId == "inno.shader.source") @@ -65,8 +91,12 @@ ShaderNodeCreation creation node.SetValue("function", ShaderGraphDocument.Encode(creation.function, serialization, context)); } else if (creation.definitionId == ShaderGraphNodes.callDefinitionId) - node.SetValue(ShaderGraphNodes.interfaceKey, - ShaderGraphDocument.Encode(LoadGraphNodeInterface(creation.sourceId), serialization, context)); + { + node.SetValue( + ShaderGraphNodes.interfaceKey, + ShaderGraphDocument.Encode(LoadGraphNodeInterface(creation.sourceId), serialization, context) + ); + } } return node; } @@ -76,16 +106,24 @@ internal IReadOnlyList Describe(GraphNodeRecord node) ShaderSourceModuleAnalysis? module = null; string implementation = ""; ShaderIrStageInput? input = node.definitionId == "inno.shader.stage-input" - ? ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context).CreateBinding() : null; + ? ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context).CreateBinding() + : null; if (node.definitionId == "inno.shader.source") { Guid id = ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, serialization, context); - if (id != Guid.Empty && assets.TryGetInfo(id, out AssetInfo? info) && info is not null && info.status != AssetImportStatus.Imported) + if (id != Guid.Empty + && assets.TryGetInfo(id, out AssetInfo? info) + && info is not null + && info.status != AssetImportStatus.Imported + ) { throw new InvalidOperationException("Source function " + info.status + ": " + string.Join("\n", info.diagnostics)); + } if (id != Guid.Empty && assets.TryLoad(id, out ShaderFunctionAsset? function) && function is not null && !function.isMissing) { string selected = ShaderGraphDocument.Read(node, "function", "", serialization, context); - module = frontends.AnalyzeModule(ShaderSourceBundle.Decode(ShaderSourceBundle.Read(function, assets), selected, serialization)); + module = frontends.AnalyzeModule( + ShaderSourceBundle.Decode(ShaderSourceBundle.Read(function, assets), selected, serialization) + ); implementation = function.implementationId; } } @@ -97,9 +135,13 @@ internal IReadOnlyList Describe(GraphNodeRecord node) { described = new GraphNodeRecord(node.id, node.definitionId) { position = node.position }; foreach ((string key, GraphSerializedValue value) in node.values) + { described.SetValue(key, value); - described.SetValue(ShaderGraphNodes.interfaceKey, - ShaderGraphDocument.Encode(nodeInterface!, serialization, context)); + } + described.SetValue( + ShaderGraphNodes.interfaceKey, + ShaderGraphDocument.Encode(nodeInterface!, serialization, context) + ); } } return nodes.DescribePorts(described, serialization, context, module, implementation, input); @@ -108,8 +150,8 @@ internal IReadOnlyList Describe(GraphNodeRecord node) internal ShaderGraphNodeInterface LoadGraphNodeInterface(Guid id) { return TryLoadGraphNodeInterface(id, out ShaderGraphNodeInterface? nodeInterface) - ? nodeInterface! - : throw new InvalidOperationException("Graph node Shader is unavailable or has import diagnostics."); + ? nodeInterface! + : throw new InvalidOperationException("Graph node Shader is unavailable or has import diagnostics."); } private bool TryLoadGraphNodeInterface( @@ -118,8 +160,10 @@ out ShaderGraphNodeInterface? nodeInterface ) { nodeInterface = null; if (!assets.TryGetInfo(id, out AssetInfo? info) || info is null || info.status != AssetImportStatus.Imported - || !assets.TryLoad(id, out ShaderAsset? shader) || shader is null || shader.isMissing) + || !assets.TryLoad(id, out ShaderAsset? shader) || shader is null || shader.isMissing + ) { return false; + } GraphDocument graph = ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(shader, assets), serialization); nodeInterface = ShaderGraphNodes.ReadInterface(graph, serialization, context); return true; @@ -130,9 +174,13 @@ out ShaderGraphNodeInterface? nodeInterface GraphNodeRecord node ) { if (draft.createFromPort is not GraphEndpoint source) + { return null; + } ShaderNodePort output = draft.ports[source.nodeId].Single(value => value.id == source.portId.value); - return Describe(node).FirstOrDefault(value => value.direction == GraphPortDirection.Input && value.type.IsEquivalentTo(output.type)); + return Describe(node).FirstOrDefault( + value => value.direction == GraphPortDirection.Input && value.type.IsEquivalentTo(output.type) + ); } internal bool CanCreate( @@ -140,17 +188,24 @@ internal bool CanCreate( ShaderNodeCreation creation ) { if (draft.readOnly) + { return false; + } if (creation.definitionId is ShaderGraphNodes.inputDefinitionId or ShaderGraphNodes.outputDefinitionId - && Controller(draft).document.nodes.Any(node => node.definitionId == creation.definitionId)) + && Controller(draft).document.nodes.Any(node => node.definitionId == creation.definitionId) + ) { return false; + } if (draft.createFromPort is null) + { return true; + } try { return CompatibleInput(draft, PrepareNode(draft, creation)) is not null; } - catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or IOException or FormatException) && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or IOException or FormatException) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { return false; } @@ -165,13 +220,24 @@ ShaderNodeCreation creation GraphDocument graph = Controller(draft).document.Clone(); graph.AddNode(node); if (node.definitionId is ShaderGraphNodes.inputDefinitionId or ShaderGraphNodes.outputDefinitionId - && !ShaderGraphNodes.IsNodeGraph(graph)) + && !ShaderGraphNodes.IsNodeGraph(graph) + ) { ShaderGraphNodes.WriteSettings(graph, new ShaderGraphNodeSettings(), serialization, context); + } if (node.definitionId == "inno.shader.stage-input") - graph = ShaderGraphBindings.ChangeInput(graph, node.id, - ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context), serialization, context); + { + graph = ShaderGraphBindings.ChangeInput( + graph, + node.id, + ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context), + serialization, + context + ); + } if (input is not null && draft.createFromPort is GraphEndpoint source) + { graph.AddEdge(new(new(Guid.NewGuid().ToString("N")), source, new(node.id, new(input.id)))); + } Controller(draft).ReplaceDocument(graph, "Create Shader Node"); draft.createFromPort = null; draft.canvas.SelectNodes([node.id]); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs index e36ca273e..b7a97feb5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs @@ -1,4 +1,3 @@ -using Inno.Editor.Graph.ImGui; using System; using System.Collections.Generic; using System.Diagnostics; @@ -6,25 +5,27 @@ using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Core.Graphs; using Inno.Core.Diagnostics; +using Inno.Core.Graphs; using Inno.Core.IO; using Inno.Core.Serialization; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.Graph; +using Inno.Editor.Graph.ImGui; using Inno.Editor.Interactions; using Inno.Editor.Rendering; using Inno.Editor.Shaders; using Inno.Editor.Shaders.ImGui; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; -using Inno.Rendering; using Inno.Extensibility.Types; +using Inno.Rendering; using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; + [EditorModule("rendering.shader-documents", order: 170)] internal sealed partial class ShaderEditorDocuments : EditorModule { @@ -51,6 +52,7 @@ internal sealed partial class ShaderEditorDocuments : EditorModule internal readonly SerializationRegistry serialization; internal readonly EditorInteractions interactions; internal ShaderClipboardData? clipboard; + internal ShaderEditorDocuments( AssetPipeline assets, SerializationRegistry serialization, @@ -75,7 +77,10 @@ IEditorPreviewService previews internal string checkStatus { get; private set; } = "Checking the current Shader draft…"; internal SerializationContext context => AssetSerializationContext.Create(assets); internal ShaderNodeCompilerRegistry nodes => m_nodes ?? throw new InvalidOperationException("Shader documents have not started."); - internal ShaderSourceFrontendRegistry frontends => m_frontends ?? throw new InvalidOperationException("Shader documents have not started."); + + internal ShaderSourceFrontendRegistry frontends + => m_frontends ?? throw new InvalidOperationException("Shader documents have not started."); + internal long typeVersion => m_types.current.version; internal EditorShaderDraftCompilationSnapshot? Preview(Draft draft) @@ -95,8 +100,11 @@ internal EditorShaderDraftCompilationSnapshot Check(Draft draft) _ = ShaderGraphNodes.ReadInterface(controller.document, serialization, context); nodeSnapshot = new(EditorShaderCompilationState.Succeeded, false, [], null); } - catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException or NotSupportedException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when ((failure is InvalidOperationException + or ArgumentException + or FormatException + or NotSupportedException) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { nodeSnapshot = new( EditorShaderCompilationState.Failed, @@ -111,9 +119,16 @@ [new ShaderDiagnostic("SHADER_GRAPH_NODE_INTERFACE", DiagnosticSeverity.Error, f return draft.preview = nodeSnapshot; } - EditorShaderDraftCompilationSnapshot snapshot = m_compilation.RequestDraft(draft.id, controller.document, controller.revision, RenderShaderVariant.empty); + EditorShaderDraftCompilationSnapshot snapshot = m_compilation.RequestDraft( + draft.id, + controller.document, + controller.revision, + RenderShaderVariant.empty + ); if (snapshot.state == EditorShaderCompilationState.Compiling) + { return snapshot; + } draft.checkedRevision = controller.revision; draft.checkedState = snapshot.state; if (snapshot.state == EditorShaderCompilationState.Failed) @@ -132,6 +147,7 @@ internal void ShowCheck(Draft draft) m_checkDraftId = draft.id; checkStatus = "Checking the current Shader draft…"; } + internal bool TryGetCheckDraft(out Draft draft) { draft = null!; @@ -139,6 +155,7 @@ internal bool TryGetCheckDraft(out Draft draft) } internal void CloseCheck() => m_checkDraftId = null; + internal void ReleasePreview(Draft draft) { m_compilation.ReleaseDraft(draft.id); @@ -149,7 +166,18 @@ internal void ReleasePreview(Draft draft) internal void PublishNodeDiagnostics(Draft draft) { - Diagnostic[] diagnostics = draft.nodeErrors.Select(pair => new Diagnostic("SHADER_NODE_INVALID", $"Node '{pair.Key.value}' cannot be evaluated: {pair.Value}", DiagnosticSeverity.Error, semanticId: pair.Key.value, objectId: draft.id, location: new DiagnosticLocation(draft.path.ToString()))).ToArray(); + Diagnostic[] diagnostics = draft.nodeErrors + .Select( + pair => new Diagnostic( + "SHADER_NODE_INVALID", + $"Node '{pair.Key.value}' cannot be evaluated: {pair.Value}", + DiagnosticSeverity.Error, + semanticId: pair.Key.value, + objectId: draft.id, + location: new DiagnosticLocation(draft.path.ToString()) + ) + ) + .ToArray(); Diagnostics.Set(draft.id, C_NODE_DIAGNOSTIC_GROUP, diagnostics, draft.path.ToString()); } @@ -161,34 +189,44 @@ EditorShaderDraftCompilationSnapshot snapshot for (int index = 0; index < snapshot.diagnostics.Count; index++) { ShaderDiagnostic shader = snapshot.diagnostics[index]; - DiagnosticLocation? location = shader.location is ShaderSourceLocation source ? new(source.assetPath, source.line, source.column) : null; - diagnostics.Add(shader.severity switch - { - DiagnosticSeverity.Info => Diagnostic.Info(shader.code, shader.message, location), - DiagnosticSeverity.Warning => Diagnostic.Warning(shader.code, shader.message, location), - DiagnosticSeverity.Error => Diagnostic.Error(shader.code, shader.message, location), - _ => Diagnostic.Error(shader.code, shader.message, location) - }); + DiagnosticLocation? location = shader.location is ShaderSourceLocation source + ? new(source.assetPath, source.line, source.column) + : null; + diagnostics.Add( + shader.severity switch + { + DiagnosticSeverity.Info => Diagnostic.Info(shader.code, shader.message, location), + DiagnosticSeverity.Warning => Diagnostic.Warning(shader.code, shader.message, location), + DiagnosticSeverity.Error => Diagnostic.Error(shader.code, shader.message, location), + _ => Diagnostic.Error(shader.code, shader.message, location) + } + ); } if (diagnostics.Count == 0) { - diagnostics.Add(snapshot.state == EditorShaderCompilationState.Succeeded + diagnostics.Add( + snapshot.state == EditorShaderCompilationState.Succeeded ? Diagnostic.Info("SHADER_CHECK_SUCCEEDED", "Shader check completed without diagnostics.") - : Diagnostic.Error("SHADER_CHECK_FAILED", "Shader check failed without a compiler diagnostic.")); + : Diagnostic.Error("SHADER_CHECK_FAILED", "Shader check failed without a compiler diagnostic.") + ); } Diagnostics.Set(draft.id, "Shader Check", diagnostics, draft.path.ToString()); } private static void ClearNodeDiagnostics(Draft draft) => Diagnostics.Clear(draft.id, C_NODE_DIAGNOSTIC_GROUP); + internal Draft Open(AssetFileEntry entry) => Open(entry, AssetId(entry)); + private Draft Open( AssetFileEntry entry, Guid id ) { if (m_drafts.TryGetValue(id, out Draft? existing)) + { return existing; + } EditorDocumentContext document = interactions.documents.Open(entry.assetPath.ToString(), id); return m_drafts[document.assetId]; } @@ -199,34 +237,41 @@ out Draft draft ) { draft = null!; if (!assets.TryGetInfo(entry.assetPath, out AssetInfo? info) || info is null) + { return false; + } draft = Open(entry, info.persistentId); return true; } - internal GraphDocumentController Controller(Draft draft) => m_graphs.TryOpenDocument( - draft.id, - interactions.history, - out GraphDocumentController? controller - ) ? controller! : throw new InvalidOperationException("The Shader graph document is not available."); - internal Guid AssetId(AssetFileEntry entry) => assets.TryGetInfo( - entry.assetPath, - out AssetInfo? info - ) - && info is not null ? info.persistentId : throw new InvalidOperationException("The shader asset identity is not available yet."); + internal GraphDocumentController Controller(Draft draft) + => m_graphs.TryOpenDocument( + draft.id, + interactions.history, + out GraphDocumentController? controller + ) ? controller! : throw new InvalidOperationException("The Shader graph document is not available."); + + internal Guid AssetId(AssetFileEntry entry) + => assets.TryGetInfo(entry.assetPath, out AssetInfo? info) + && info is not null ? info.persistentId : throw new InvalidOperationException("The shader asset identity is not available yet."); + internal bool TryGet( AssetFileEntry entry, out Draft draft ) { draft = null!; - return assets.TryGetInfo(entry.assetPath, out AssetInfo? info) && info is not null && m_drafts.TryGetValue(info.persistentId, out draft!); + return assets.TryGetInfo(entry.assetPath, out AssetInfo? info) + && info is not null + && m_drafts.TryGetValue(info.persistentId, out draft!); } internal void RefreshCompilation(Draft draft) { long now = Stopwatch.GetTimestamp(); if (now < draft.nextCompilationPoll) + { return; + } draft.nextCompilationPoll = now + Stopwatch.Frequency / 4; draft.diagnostics = []; try @@ -267,11 +312,14 @@ internal void RefreshCompilation(Draft draft) EditorShaderCompilationState.Succeeded => "Compiled", _ => "Compilation failed" }; - draft.compilationDiagnostics = string.Join("\n", snapshot.diagnostics.Select(static value => value.code + ": " + value.message)); + draft.compilationDiagnostics = string.Join( + "\n", + snapshot.diagnostics.Select(static value => value.code + ": " + value.message) + ); draft.diagnostics = snapshot.diagnostics.ToArray(); } catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { draft.compilationStatus = "Compilation unavailable"; draft.compilationDiagnostics = failure.Message; @@ -281,7 +329,9 @@ internal void RefreshCompilation(Draft draft) internal void RemoveNodes(Draft draft) { if (draft.canvas.selectedNodes.Count == 0) + { return; + } GraphDocumentController controller = Controller(draft); GraphDocument candidate = ShaderGraphBindings.RemoveNodes(controller.document, draft.canvas.selectedNodes, serialization, context); ShaderCanvasGroup[] groups = GroupShaderNodes.Read(this, candidate).Select(group => @@ -291,10 +341,14 @@ internal void RemoveNodes(Draft draft) }).Where(static group => group.nodes.Length != 0).ToArray(); candidate.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, serialization, context)); if (draft.selectedGroupId.Length != 0 && !groups.Any(group => group.id == draft.selectedGroupId)) + { draft.selectedGroupId = ""; + } controller.ReplaceDocument(candidate, "Delete Shader Nodes"); if (draft.activeStage is GraphNodeId stage && controller.document.FindNode(stage) is null) + { draft.activeStage = null; + } draft.navigation.Cancel(); draft.pointer.Cancel(); } @@ -303,14 +357,18 @@ internal void Changed(Draft draft) { GraphDocumentController controller = Controller(draft); if (draft.checkedRevision != ulong.MaxValue && draft.checkedRevision != controller.revision) + { ReleasePreview(draft); + } draft.observedRevision = controller.revision; interactions.documents.SetDirty(draft.documentId, controller.isDirty); if (!controller.isDirty) { string recovery = RecoveryPath(draft.id); if (File.Exists(recovery)) + { File.Delete(recovery); + } return; } @@ -320,7 +378,7 @@ internal void Changed(Draft draft) draft.error = ""; } catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { draft.error = "Recovery could not be written: " + failure.Message; } @@ -330,12 +388,16 @@ internal bool Save(Draft draft) { GraphDocumentController controller = Controller(draft); if (!controller.isDirty) + { return true; + } try { PreserveRecovery(draft, controller); if (!controller.isAvailable) + { throw new IOException("The shader source is unavailable. Recovery and history are retained until it returns."); + } draft.hash = m_sources.Save(draft.path, CaptureSource(draft, controller.document), draft.hash); controller.MarkSaved(); draft.observedRevision = controller.revision; @@ -345,12 +407,14 @@ internal bool Save(Draft draft) draft.nextCompilationPoll = 0; string recovery = RecoveryPath(draft.id); if (File.Exists(recovery)) + { File.Delete(recovery); + } // Import runs at the next editor update, independently of persistence success and watcher timing. return true; } catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { draft.error = failure.Message; draft.status = "Not saved · recovery retained"; @@ -373,11 +437,13 @@ internal bool Reload(Draft draft) draft.status = "Reloaded · compilation is separate"; string recovery = RecoveryPath(draft.id); if (File.Exists(recovery)) + { File.Delete(recovery); + } return true; } catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { draft.error = failure.Message; return false; @@ -434,7 +500,8 @@ protected override void OnUpdate(EditorContext editor) { PublishCheck(checking, result); checkStatus = result.state == EditorShaderCompilationState.Succeeded - ? "Shader check completed." : "Shader check failed. See Console diagnostics."; + ? "Shader check completed." + : "Shader check failed. See Console diagnostics."; CloseCheck(); } } @@ -445,8 +512,11 @@ protected override void OnUpdate(EditorContext editor) { _ = assets.Import(path); } - catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when ((failure is IOException + or UnauthorizedAccessException + or InvalidOperationException + or FormatException) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { foreach (Draft draft in m_drafts.Values.Where(draft => draft.path == path)) { @@ -466,7 +536,9 @@ protected override void OnUpdate(EditorContext editor) { GraphDocumentController controller = Controller(draft); if (controller.revision != draft.observedRevision) + { Changed(draft); + } } } @@ -479,7 +551,9 @@ protected override void OnUpdate(EditorContext editor) protected override void Capture(EditorState state) { foreach (Draft draft in m_drafts.Values) + { RememberView(draft); + } state.Set("views", m_views.Values.ToArray()); } @@ -493,8 +567,12 @@ protected override void Restore(EditorState state) { m_views.Clear(); foreach (ViewState view in state.Get("views", Array.Empty())) + { if (view.assetId != Guid.Empty && float.IsFinite(view.x) && float.IsFinite(view.y) && float.IsFinite(view.zoom)) + { m_views[view.assetId] = view; + } + } } /// @@ -511,7 +589,9 @@ protected override void OnStop(EditorContext editor) { CancelCanvasEdit(draft); if (Controller(draft).isDirty) + { PreserveRecovery(draft, Controller(draft)); + } ClearNodeDiagnostics(draft); ReleasePreview(draft); } @@ -528,7 +608,9 @@ protected override void OnStop(EditorContext editor) private void Open(EditorDocumentContext document) { if (m_drafts.ContainsKey(document.assetId)) + { return; + } AssetPath path = AssetPath.Parse(document.assetPath); string recoveryPath = RecoveryPath(document.assetId); RecoveryData? recovery = null; @@ -536,7 +618,9 @@ private void Open(EditorDocumentContext document) { recovery = serialization.Deserialize(File.ReadAllBytes(recoveryPath)); if (recovery.assetId != document.assetId) + { throw new InvalidDataException("Shader recovery identity does not match its document."); + } } if (assets.TryGetInfo(document.assetId, out AssetInfo? info) && info is not null && info.status != AssetImportStatus.Missing) @@ -552,30 +636,50 @@ private void Open(EditorDocumentContext document) source = m_sources.Read(path); } catch (Exception failure) when ((recovery is not null - && failure is IOException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && failure is IOException or InvalidOperationException or FormatException) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { missing = failure.Message; } - GraphDocumentController controller = m_graphs.OpenDocument(document.assetId, source?.document ?? new GraphDocument(), interactions.history); + GraphDocumentController controller = m_graphs.OpenDocument( + document.assetId, + source?.document ?? new GraphDocument(), + interactions.history + ); string staleRecovery = ""; bool canRecover = recovery is not null && (source is null || recovery.hash == source.contentHash); if (canRecover && !controller.isDirty) + { controller.ReplaceDocument(GraphDocumentCodec.Decode(recovery!.graph, serialization), "Recover Shader Edits"); + } else if (recovery is not null) + { staleRecovery = ArchiveStaleRecovery(document.assetId, recoveryPath); - var draft = new Draft(document.assetId, document.documentId, path, recovery?.hash ?? source!.contentHash, source?.isReadOnly ?? true) + } + var draft = new Draft( + document.assetId, + document.documentId, + path, + recovery?.hash ?? source!.contentHash, + source?.isReadOnly ?? true + ) { observedRevision = controller.revision }; if (m_views.TryGetValue(draft.id, out ViewState view)) + { draft.canvas.SetViewport(new(view.x, view.y), view.zoom); + } else + { draft.frameRequested = true; + } m_drafts.Add(draft.id, draft); if (canRecover) + { Changed(draft); + } else if (staleRecovery.Length != 0) { draft.hash = source!.contentHash; @@ -595,25 +699,40 @@ private void PreserveRecovery( GraphDocumentController controller ) => AtomicFile.WriteAllBytes( RecoveryPath(draft.id), - serialization.Serialize(new RecoveryData { assetId = draft.id, path = draft.path.ToString(), hash = draft.hash, graph = GraphDocumentCodec.Encode(CaptureSource(draft, controller.document), serialization) }) + serialization.Serialize( + new RecoveryData + { + assetId = draft.id, + path = draft.path.ToString(), + hash = draft.hash, + graph = GraphDocumentCodec.Encode(CaptureSource(draft, controller.document), serialization) + } + ) ); + private GraphDocument CaptureSource( Draft draft, GraphDocument graph ) { GraphDocument snapshot = graph.Clone(); foreach (GraphNodeRecord node in snapshot.nodes) + { if (draft.portSnapshots.TryGetValue(node.id, out ShaderPortSnapshot[]? ports)) + { node.SetValue(C_PORT_SNAPSHOT, ShaderGraphDocument.Encode(ports, serialization, context)); + } + } return snapshot; } private string RecoveryPath(Guid id) => Path.Combine(assets.libraryRoot, "Editor", "ShaderRecovery", id.ToString("N") + ".inno"); + private static string ArchiveStaleRecovery( Guid id, string recoveryPath ) { - string directory = Path.GetDirectoryName(recoveryPath) ?? throw new InvalidOperationException("The Shader recovery directory is unavailable."); + string directory = Path.GetDirectoryName(recoveryPath) + ?? throw new InvalidOperationException("The Shader recovery directory is unavailable."); string archive = Path.Combine(directory, id.ToString("N") + "." + DateTime.UtcNow.ToString("yyyyMMddHHmmssfff") + ".stale.inno"); File.Move(recoveryPath, archive); return archive; @@ -622,11 +741,17 @@ string recoveryPath private void SynchronizeSources() { if (m_drafts.Count == 0) + { return; + } Dictionary entries = []; foreach (AssetFileEntry entry in assets.GetFileSystemEntries(includeDirectories: false)) + { if (entry.extension == ".ishader" && assets.TryGetInfo(entry.assetPath, out AssetInfo? info) && info is not null) + { entries.Add(info.persistentId, entry); + } + } foreach (Draft draft in m_drafts.Values) { GraphDocumentController controller = Controller(draft); @@ -649,7 +774,9 @@ private void SynchronizeSources() if (source.contentHash == draft.hash) { if (wasMissing) + { draft.error = ""; + } continue; } @@ -666,8 +793,11 @@ private void SynchronizeSources() draft.error = ""; draft.status = "Source updated · compilation is separate"; } - catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when ((failure is IOException + or UnauthorizedAccessException + or InvalidOperationException + or FormatException) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { draft.error = failure.Message; } @@ -675,12 +805,14 @@ private void SynchronizeSources() } private void RememberView(Draft draft) => m_views[draft.id] = new(draft.id, draft.canvas.pan.x, draft.canvas.pan.y, draft.canvas.zoom); + private readonly record struct ViewState( Guid assetId, float x, float y, float zoom ); + private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvider { /// @@ -698,6 +830,7 @@ private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvi /// when the documented condition is satisfied; otherwise, . /// public override bool CanOpen(string assetPath) => assetPath.EndsWith(".ishader", StringComparison.OrdinalIgnoreCase); + /// /// Opens the requested resource and establishes its active lifetime. /// @@ -705,6 +838,7 @@ private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvi /// The operation scope that provides state, services, and ownership boundaries. /// public override void Open(EditorDocumentContext context) => owner.Open(context); + /// /// Persists the supplied value through the configured storage contract. /// @@ -715,6 +849,7 @@ private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvi /// when the documented condition is satisfied; otherwise, . /// public override bool Save(EditorDocumentContext context) => owner.Save(owner.m_drafts[context.assetId]); + /// /// Restores the draft from the latest imported asset state. /// @@ -725,6 +860,7 @@ private sealed class Provider(ShaderEditorDocuments owner) : EditorDocumentProvi /// when the documented condition is satisfied; otherwise, . /// public override bool Revert(EditorDocumentContext context) => owner.Reload(owner.m_drafts[context.assetId]); + /// /// Closes the active resource and releases its operation-scoped state. /// @@ -735,10 +871,14 @@ public override void Close(EditorDocumentContext context) { // The shared host already applied Save/Discard/Cancel policy. Close must never turn Discard into Save. if (!owner.m_drafts.TryGetValue(context.assetId, out Draft? draft)) + { return; + } string recovery = owner.RecoveryPath(draft.id); if (File.Exists(recovery)) + { File.Delete(recovery); + } owner.RememberView(draft); CancelCanvasEdit(draft); ClearNodeDiagnostics(draft); @@ -755,8 +895,7 @@ internal sealed class Draft( AssetPath path, string hash, bool readOnly - ) - { + ) { internal readonly Guid id = id; internal readonly Guid documentId = documentId; internal AssetPath path = path; @@ -844,14 +983,17 @@ internal struct ShaderPortSnapshot /// Gets the stable identity used to reference this value across subsystem boundaries. /// public string id { get; set; } + /// /// Gets the graph port's shader value type. /// public ShaderGraphType type { get; set; } + /// /// Gets the graph port's input or output direction. /// public GraphPortDirection direction { get; set; } + /// /// Gets whether required is active for the current instance. /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs index 7c71b5f09..8cf8dad58 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs @@ -1,4 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.IO; using Inno.Assets; @@ -10,7 +9,10 @@ using Inno.Rendering; using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; + namespace Inno.Editor.Panel.ShaderEditor; + [InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] internal sealed class ShaderSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer { @@ -35,6 +37,7 @@ protected override string GetIcon( InspectionDrawContext context, AssetFileEntry target ) => icons.GetIcon(target); + /// /// Checks whether this drawer supports the selected Inspector target. /// @@ -44,7 +47,9 @@ AssetFileEntry target /// /// when the documented condition is satisfied; otherwise, . /// - protected override bool CanInspect(AssetFileEntry target) => !target.isDirectory && target.extension.Equals(".ishader", StringComparison.OrdinalIgnoreCase); + protected override bool CanInspect(AssetFileEntry target) + => !target.isDirectory && target.extension.Equals(".ishader", StringComparison.OrdinalIgnoreCase); + /// /// Binds a caller-visible label to the current inspection target. /// @@ -61,6 +66,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, AssetFileEntry target ) => (target.nameWithoutExtension, null); + /// /// Renders the value presentation for the current editor frame. /// @@ -77,9 +83,13 @@ AssetFileEntry target if (context.interactions.TryGetModule(out var documents)) { if (documents!.TryOpen(target, out ShaderEditorDocuments.Draft draft)) + { new ShaderEditorCanvas(documents, draft).DrawInspector(context, []); + } else + { EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Waiting for Shader asset import…"); + } } } } @@ -108,16 +118,14 @@ protected override string GetIcon( InspectionDrawContext context, ShaderInspectionSelection target ) => context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetInfo( - target.assetId, - out AssetInfo? info - ) - && info is not null - && documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; + && documents is not null + && documents.assets.TryGetInfo(target.assetId, out AssetInfo? info) + && info is not null + && documents.assets.TryGetFileSystemEntry( + info.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; + /// /// Binds a caller-visible label to the current inspection target. /// @@ -136,12 +144,11 @@ ShaderInspectionSelection target ) { if (context.interactions.TryGetModule(out var documents) && documents is not null - && documents.assets.TryGetInfo( - target.assetId, - out AssetInfo? info - ) - && info is not null) + && documents.assets.TryGetInfo(target.assetId, out AssetInfo? info) + && info is not null + ) { return (Path.GetFileName(info.assetPath.localPath), null); + } return ("Shader", null); } @@ -160,16 +167,10 @@ ShaderInspectionSelection target ) { if (!context.interactions.TryGetModule(out var documents) || documents is null - || !documents.assets.TryGetInfo( - target.assetId, - out AssetInfo? info - ) + || !documents.assets.TryGetInfo(target.assetId, out AssetInfo? info) || info is null - || !documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - )) - { + || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) + ) { EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Node selection unavailable"); return; } @@ -181,9 +182,16 @@ out AssetFileEntry entry } if (target.nodes.Count == 1 && documents.Controller(draft).document.FindNode(target.nodes[0]) is GraphNodeRecord node) - EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Node: " + new ShaderEditorCanvas(documents, draft).Title(node)); + { + EditorUI.current.widgets.ColoredText( + EditorPalette.contextText, + "Node: " + new ShaderEditorCanvas(documents, draft).Title(node) + ); + } else + { EditorUI.current.widgets.ColoredText(EditorPalette.contextText, $"Nodes: {target.nodes.Count} selected"); + } } /// @@ -200,17 +208,25 @@ protected override void Draw( ShaderInspectionSelection target ) { if (!context.interactions.TryGetModule(out var documents) || documents is null) - return; - if (!documents.assets.TryGetInfo(target.assetId, out AssetInfo? info) || info is null || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry)) { + return; + } + if (!documents.assets.TryGetInfo(target.assetId, out AssetInfo? info) + || info is null + || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) + ) { EditorUI.current.widgets.WrappedText("Shader source unavailable. Selection identities are retained."); return; } if (documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) + { new ShaderEditorCanvas(documents, draft).DrawInspector(context, target.nodes); + } else + { EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Waiting for Shader asset import…"); + } } } @@ -238,11 +254,12 @@ protected override string GetIcon( InspectionDrawContext context, ShaderAsset target ) => context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetFileSystemEntry( - target.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; + && documents is not null + && documents.assets.TryGetFileSystemEntry( + target.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; + /// /// Binds a caller-visible label to the current inspection target. /// @@ -259,6 +276,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, ShaderAsset target ) => (target.name, null); + /// /// Renders the value presentation for the current editor frame. /// @@ -273,12 +291,20 @@ protected override void Draw( ShaderAsset target ) { if (!context.interactions.TryGetModule(out var documents) || documents is null) + { return; + } if (!documents.assets.TryGetFileSystemEntry(target.assetPath, out AssetFileEntry entry)) + { return; + } if (documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) + { new ShaderEditorCanvas(documents, draft).DrawInspector(context, []); + } else + { EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Waiting for Shader asset import…"); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs index b4b964f10..088f8a537 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs @@ -4,12 +4,13 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Graphs; -using Inno.Editor.Interactions; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; +using Inno.Editor.Interactions; using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; + [EditorAction("shader/create-asset", "panel/asset.file-browser")] internal sealed class CreateShaderAsset( ShaderEditorDocuments documents, @@ -28,7 +29,9 @@ AssetEditingModule browser protected override EditorActionState Query(EditorActionContext context) { AssetPath path = AssetPath.Parse(context.target); - return documents.assets.sourceMounts.Any(mount => mount.id == path.source && !mount.isReadOnly) ? EditorActionState.enabled : EditorActionState.disabled; + return documents.assets.sourceMounts.Any(mount => mount.id == path.source && !mount.isReadOnly) + ? EditorActionState.enabled + : EditorActionState.disabled; } /// @@ -43,7 +46,9 @@ protected override void Execute(EditorActionContext context) AssetSourceMount mount = documents.assets.sourceMounts.Single(mount => mount.id == parent.source); string prefix = parent.localPath.TrimEnd('/'); if (prefix.Length != 0) + { prefix += "/"; + } int index = 0; AssetPath path; do @@ -80,10 +85,14 @@ public override void Build( EditorMenuBuilder builder ) { if (documents.templates is null) + { return; + } builder.AddGroup("Create/Rendering", order: 200, separatorBefore: true); builder.AddGroup("Create/Rendering/Shaders", order: 0); foreach (ShaderGraphTemplateInfo template in documents.templates.templates) + { builder.Add("Create/Rendering/Shaders/" + template.displayName, "shader/create-asset", argument: template.id, order: 0); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs index 158fe9913..ea636e9b5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs @@ -1,6 +1,3 @@ -using Inno.Editor.Core; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Shaders.ImGui; using System; using System.Collections.Generic; using System.Linq; @@ -8,13 +5,18 @@ using Inno.Assets.Pipeline; using Inno.Core.Graphs; using Inno.Core.Input; +using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Shaders; +using Inno.Editor.Shaders.ImGui; using Inno.Rendering.Assets; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.Panel.ShaderEditor; + [EditorMenuSource(ShaderEditorCanvas.C_AREA)] internal sealed class ShaderCanvasMenu(ShaderEditorDocuments documents) : EditorMenuSource { @@ -32,11 +34,17 @@ public override void Build( EditorMenuBuilder builder ) { if (context.target is not AssetFileEntry entry || !documents.TryGet(entry, out var draft)) + { return; + } builder.AddGroup("Create/Functions", order: 500, separatorBefore: true); builder.AddGroup("Create/Graph Nodes", order: 550, separatorBefore: true); builder.AddGroup("Create/Domain Outputs", order: 800, separatorBefore: true); - bool explicitStages = ShaderGraphDocument.ReadTarget(documents.Controller(draft).document, documents.serialization, documents.context).Length == 0; + bool explicitStages = ShaderGraphDocument.ReadTarget( + documents.Controller(draft).document, + documents.serialization, + documents.context + ).Length == 0; if (draft.createFromPort is null && explicitStages) { builder.Add("Create/Outputs/Vertex Output", "shader/create-output", order: 0, argument: "Vertex"); @@ -45,53 +53,62 @@ EditorMenuBuilder builder } foreach (string definition in documents.nodes.definitionIds) - if (definition is not ("inno.shader.source" or ShaderGraphNodes.callDefinitionId) && documents.CanCreate(draft, new(definition))) - { + { + if (definition is not ("inno.shader.source" or ShaderGraphNodes.callDefinitionId) + && documents.CanCreate(draft, new(definition)) + ) { string category = Category(definition); int order = CategoryOrder(category); - if (documents.drawers?.TryGetPresentation(definition, out ShaderNodePresentation presentation) == true && presentation.createPath.Length != 0) - { + if (documents.drawers?.TryGetPresentation(definition, out ShaderNodePresentation presentation) == true + && presentation.createPath.Length != 0 + ) { category = presentation.createPath; order = presentation.createOrder; builder.AddGroup("Create/" + category, order, presentation.separatorBefore); } builder.Add( - "Create/" + category + "/" + (documents.drawers?.GetDisplayName(definition) ?? EditorDisplayNames.Nicify(definition.Replace("inno.shader.", "", StringComparison.Ordinal).Replace('-', ' '))), + "Create/" + + category + + "/" + + (documents.drawers?.GetDisplayName(definition) + ?? EditorDisplayNames.Nicify(definition.Replace("inno.shader.", "", StringComparison.Ordinal).Replace('-', ' '))), "shader/create-node", order, argument: new ShaderNodeCreation(definition) ); } + } var functionLibraries = new List<(AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)>(); foreach (AssetFileEntry source in documents.assets.GetFileSystemEntries(includeDirectories: false)) + { if (source.extension == ".ishadersource" - && documents.assets.TryGetInfo( - source.assetPath, - out var info - ) + && documents.assets.TryGetInfo(source.assetPath, out var info) && info is not null - && documents.assets.TryLoad( - info.persistentId, - out ShaderFunctionAsset? library - ) + && documents.assets.TryLoad(info.persistentId, out ShaderFunctionAsset? library) && library is not null - && !library.isMissing) + && !library.isMissing + ) { functionLibraries.Add((source, info, library)); - foreach (var catalog in functionLibraries.Select(static value => (path: NormalizeCatalog(value.library.catalogPath), value.library.catalogOrder)).Where(static value => value.path.Length != 0).GroupBy( - static value => value.path.Split('/')[0], - StringComparer.Ordinal - ).Select(static group => (name: group.Key, order: group.Min(static value => value.catalogOrder))).OrderBy(static value => value.order).ThenBy( - static value => value.name, - StringComparer.Ordinal - )) + } + } + foreach (var catalog in functionLibraries + .Select(static value => (path: NormalizeCatalog(value.library.catalogPath), value.library.catalogOrder)) + .Where(static value => value.path.Length != 0) + .GroupBy(static value => value.path.Split('/')[0], StringComparer.Ordinal) + .Select(static group => (name: group.Key, order: group.Min(static value => value.catalogOrder))) + .OrderBy(static value => value.order) + .ThenBy(static value => value.name, StringComparer.Ordinal) + ) { builder.AddGroup("Create/Functions/" + catalog.name, order: 500 + catalog.order, separatorBefore: true); - foreach ((AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)in functionLibraries.OrderBy(static value => value.library.catalogOrder).ThenBy( - static value => value.source.nameWithoutExtension, - StringComparer.Ordinal - )) + } + foreach ((AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)in functionLibraries + .OrderBy(static value => value.library.catalogOrder) + .ThenBy(static value => value.source.nameWithoutExtension, StringComparer.Ordinal) + ) { foreach (string function in library.exports) + { if (documents.CanCreate(draft, new("inno.shader.source", info.persistentId, function))) { string catalog = NormalizeCatalog(library.catalogPath); @@ -103,33 +120,51 @@ out ShaderFunctionAsset? library argument: new ShaderNodeCreation("inno.shader.source", info.persistentId, function) ); } + } + } - foreach (AssetFileEntry source in documents.assets.GetFileSystemEntries(includeDirectories: false).Where(static entry => entry.extension == ".ishader").OrderBy( - static entry => entry.assetPath.ToString(), - StringComparer.Ordinal - )) - { - if (!documents.assets.TryGetInfo(source.assetPath, out AssetInfo? info) || info is null || info.persistentId == draft.id || info.status != AssetImportStatus.Imported) + foreach (AssetFileEntry source in documents.assets + .GetFileSystemEntries(includeDirectories: false) + .Where(static entry => entry.extension == ".ishader") + .OrderBy(static entry => entry.assetPath.ToString(), StringComparer.Ordinal) + ) { + if (!documents.assets.TryGetInfo(source.assetPath, out AssetInfo? info) + || info is null + || info.persistentId == draft.id + || info.status != AssetImportStatus.Imported + ) { continue; + } ShaderGraphNodeInterface nodeInterface; try { nodeInterface = documents.LoadGraphNodeInterface(info.persistentId); } catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { continue; } var creation = new ShaderNodeCreation(ShaderGraphNodes.callDefinitionId, info.persistentId); if (!documents.CanCreate(draft, creation)) + { continue; + } string catalog = NormalizeCatalog(nodeInterface.createPath); string root = nodeInterface.kind == ShaderGraphNodeKind.DomainOutput ? "Domain Outputs" : "Graph Nodes"; string group = "Create/" + root + (catalog.Length == 0 ? "" : "/" + catalog); - builder.AddGroup(group, order: nodeInterface.createOrder, separatorBefore: nodeInterface.kind == ShaderGraphNodeKind.DomainOutput); - builder.Add(group + "/" + nodeInterface.displayName, "shader/create-node", order: nodeInterface.createOrder, argument: creation); + builder.AddGroup( + group, + order: nodeInterface.createOrder, + separatorBefore: nodeInterface.kind == ShaderGraphNodeKind.DomainOutput + ); + builder.Add( + group + "/" + nodeInterface.displayName, + "shader/create-node", + order: nodeInterface.createOrder, + argument: creation + ); } builder.Add("View/Focus Selection", "shader/focus", order: 900); @@ -146,7 +181,8 @@ out ShaderFunctionAsset? library builder.Add("Assets/Show Shader in File Browser", "shader/reveal-shader", order: 1900); builder.Add("Assets/Show Source in File Browser", "shader/reveal-source", order: 1910); builder.Add("Assets/Copy Shader To Project", "shader/copy-to-project", order: 1920, separatorBefore: true); - static string Category(string definition) => definition switch + static string Category(string definition) + => definition switch { "inno.shader.constant" or "inno.shader.stage-input" => "Inputs", ShaderGraphNodes.inputDefinitionId or ShaderGraphNodes.outputDefinitionId => "Interface", @@ -158,7 +194,8 @@ out ShaderFunctionAsset? library _ when definition.Contains("surface-output", StringComparison.Ordinal) => "Domain Outputs", _ => "Domain" }; - static int CategoryOrder(string category) => category switch + static int CategoryOrder(string category) + => category switch { "Outputs" => 0, "Interface" => 50, @@ -171,7 +208,8 @@ _ when definition.Contains("surface-output", StringComparison.Ordinal) => "Domai "Domain Outputs" => 800, _ => 850 }; - static string NormalizeCatalog(string value) => string.Join('/', value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + static string NormalizeCatalog(string value) + => string.Join('/', value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); } } @@ -189,12 +227,30 @@ internal sealed class CreateShaderOutput(ShaderEditorDocuments documents) : Edit /// protected override EditorActionState Query(EditorActionContext context) { - if (!documents.TryGet(context.target, out var draft) || draft.readOnly || !Enum.TryParse(context.argument, out Inno.Rendering.ShaderStage stage)) + if (!documents.TryGet(context.target, out var draft) + || draft.readOnly + || !Enum.TryParse(context.argument, out Inno.Rendering.ShaderStage stage) + ) { return EditorActionState.disabled; + } GraphDocument graph = documents.Controller(draft).document; if (ShaderGraphDocument.ReadTarget(graph, documents.serialization, documents.context).Length != 0) + { return EditorActionState.disabled; - bool exists = graph.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId).Any(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphStageSettings(), documents.serialization, documents.context).stage == stage); + } + bool exists = graph.nodes + .Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) + .Any( + node => ( + ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphStageSettings(), + documents.serialization, + documents.context + ).stage == stage + ) + ); return exists ? EditorActionState.disabled : EditorActionState.enabled; } @@ -209,11 +265,37 @@ protected override void Execute(EditorActionContext cont var draft = documents.Open(context.target); var controller = documents.Controller(draft); GraphDocument graph = controller.document.Clone(); - Inno.Rendering.Assets.ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, documents.serialization, documents.context); + Inno.Rendering.Assets.ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + graph, + documents.serialization, + documents.context + ); Inno.Rendering.ShaderStage stage = Enum.Parse(context.argument); - Inno.Rendering.ShaderProgramKind kind = stage == Inno.Rendering.ShaderStage.Compute ? Inno.Rendering.ShaderProgramKind.Compute : Inno.Rendering.ShaderProgramKind.Raster; + Inno.Rendering.ShaderProgramKind kind = stage == Inno.Rendering.ShaderStage.Compute + ? Inno.Rendering.ShaderProgramKind.Compute + : Inno.Rendering.ShaderProgramKind.Raster; ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(graph, documents.serialization, documents.context); - ShaderGraphPassProgram? incomplete = kind == Inno.Rendering.ShaderProgramKind.Raster ? programs.FirstOrDefault(program => definition.passes.Any(pass => pass.name == program.pass && pass.programKind == kind) && !program.stages.Select(id => graph.FindNode(new(id))).OfType().Any(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphStageSettings(), documents.serialization, documents.context).stage == stage)) : null; + ShaderGraphPassProgram? incomplete = kind == Inno.Rendering.ShaderProgramKind.Raster + ? programs.FirstOrDefault( + program => ( + definition.passes.Any(pass => pass.name == program.pass && pass.programKind == kind) + && !program.stages + .Select(id => graph.FindNode(new(id))) + .OfType() + .Any( + node => ( + ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphStageSettings(), + documents.serialization, + documents.context + ).stage == stage + ) + ) + ) + ) + : null; string name; string[] stages; if (incomplete is ShaderGraphPassProgram existing && existing.pass is not null) @@ -226,11 +308,17 @@ protected override void Execute(EditorActionContext cont string prefix = kind.ToString(); name = prefix; for (int suffix = 2; definition.passes.Any(pass => pass.name == name); suffix++) + { name = prefix + " " + suffix; + } definition.passes = [..definition.passes, new(name, kind)]; graph.SetMetadata( ShaderGraphDocument.definitionKey, - ShaderGraphDocument.Encode(documents.serialization.Serialize(definition, documents.context), documents.serialization, documents.context) + ShaderGraphDocument.Encode( + documents.serialization.Serialize(definition, documents.context), + documents.serialization, + documents.context + ) ); stages = []; } @@ -243,16 +331,29 @@ protected override void Execute(EditorActionContext cont node.SetValue( "settings", ShaderGraphDocument.Encode( - new ShaderGraphStageSettings { + new ShaderGraphStageSettings + { stage = stage, - outputs = stage == Inno.Rendering.ShaderStage.Compute ? [] : [new() { id = stage == Inno.Rendering.ShaderStage.Vertex ? "position" : "color", kind = stage == Inno.Rendering.ShaderStage.Vertex ? ShaderIrOutputKind.ClipPosition : ShaderIrOutputKind.Color }] + outputs = stage == Inno.Rendering.ShaderStage.Compute + ? [] + : [new() + { + id = stage == Inno.Rendering.ShaderStage.Vertex ? "position" : "color", + kind = stage == Inno.Rendering.ShaderStage.Vertex ? ShaderIrOutputKind.ClipPosition : ShaderIrOutputKind.Color + }] }, documents.serialization, documents.context ) ); graph.AddNode(node); - graph = ShaderGraphPrograms.Bind(graph, name, stages.Select(static value => new GraphNodeId(value)).Append(id), documents.serialization, documents.context); + graph = ShaderGraphPrograms.Bind( + graph, + name, + stages.Select(static value => new GraphNodeId(value)).Append(id), + documents.serialization, + documents.context + ); controller.ReplaceDocument(graph, "Create " + stage + " Output"); draft.canvas.SelectNodes([id]); draft.activeStage = id; @@ -272,21 +373,18 @@ internal sealed class CreateShaderNode(ShaderEditorDocuments documents) : Editor /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => documents.TryGet( - context.target, - out var draft - ) - && documents.CanCreate( - draft, - context.argument - ) ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => documents.TryGet(context.target, out var draft) + && documents.CanCreate(draft, context.argument) ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// /// /// The context that supplies state and services for this operation. /// - protected override void Execute(EditorActionContext context) => documents.Create(documents.Open(context.target), context.argument); + protected override void Execute(EditorActionContext context) + => documents.Create(documents.Open(context.target), context.argument); } internal abstract class ShaderSelectionAction(ShaderEditorDocuments documents) : EditorAction @@ -295,10 +393,12 @@ internal abstract class ShaderSelectionAction(ShaderEditorDocuments documents) : /// Gets documents presented by this Shader Editor action. /// protected ShaderEditorDocuments documents { get; } = documents; + /// /// Gets whether writes is active for the current instance. /// protected virtual bool writes => true; + /// /// Gets whether needs selection is active for the current instance. /// @@ -313,14 +413,12 @@ internal abstract class ShaderSelectionAction(ShaderEditorDocuments documents) : /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => documents.TryGet( - context.target, - out var draft - ) - && (!writes - || !draft.readOnly) - && (!needsSelection - || draft.canvas.selectedNodes.Count != 0) ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => documents.TryGet(context.target, out var draft) + && (!writes + || !draft.readOnly) + && (!needsSelection + || draft.canvas.selectedNodes.Count != 0) ? EditorActionState.enabled : EditorActionState.disabled; } [EditorAction("shader/copy", ShaderEditorCanvas.C_AREA)] @@ -367,7 +465,9 @@ protected override void Execute(EditorActionContext context) var controller = documents.Controller(draft); using var transaction = context.history.BeginTransaction("Delete Shader Selection"); if (draft.selectedEdge is GraphEdgeId edge) + { controller.Disconnect(edge); + } documents.RemoveNodes(draft); transaction.Commit(); draft.selectedEdge = null; @@ -414,16 +514,12 @@ internal sealed class PasteShaderNodes(ShaderEditorDocuments documents) : Shader /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => base.Query(context).isEnabled - && documents.clipboard is not null - && documents.TryGet( - context.target, - out var draft - ) - && documents.CanPaste( - draft, - documents.clipboard - ) ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => base.Query(context).isEnabled + && documents.clipboard is not null + && documents.TryGet(context.target, out var draft) + && documents.CanPaste(draft, documents.clipboard) ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -434,7 +530,9 @@ protected override void Execute(EditorActionContext context) { var draft = documents.Open(context.target); if (documents.clipboard is not null) + { documents.Paste(draft, documents.clipboard); + } } } @@ -454,8 +552,14 @@ internal sealed class DuplicateShaderNodes(ShaderEditorDocuments documents) : Sh protected override EditorActionState Query(EditorActionContext context) { if (!base.Query(context).isEnabled || !documents.TryGet(context.target, out var draft)) + { return EditorActionState.disabled; - return draft.canvas.selectedNodes.Any(id => documents.Controller(draft).document.FindNode(id)?.definitionId == ShaderGraphDocument.outputDefinitionId) ? EditorActionState.disabled : EditorActionState.enabled; + } + return draft.canvas.selectedNodes.Any( + id => documents.Controller(draft).document.FindNode(id)?.definitionId == ShaderGraphDocument.outputDefinitionId + ) + ? EditorActionState.disabled + : EditorActionState.enabled; } /// @@ -485,8 +589,14 @@ protected override void Execute(EditorActionContext context) var draft = documents.Open(context.target); var controller = documents.Controller(draft); using var transaction = context.history.BeginTransaction("Disconnect Nodes"); - foreach (GraphEdgeRecord edge in controller.document.edges.Where(edge => draft.canvas.selectedNodes.Contains(edge.input.nodeId) || draft.canvas.selectedNodes.Contains(edge.output.nodeId)).ToArray()) + foreach (GraphEdgeRecord edge in controller.document.edges + .Where( + edge => draft.canvas.selectedNodes.Contains(edge.input.nodeId) || draft.canvas.selectedNodes.Contains(edge.output.nodeId) + ) + .ToArray() + ) { controller.Disconnect(edge.id); + } transaction.Commit(); documents.Changed(draft); } @@ -507,7 +617,8 @@ internal sealed class SaveShader(ShaderEditorDocuments documents) : ShaderSelect /// /// The context that supplies state and services for this operation. /// - protected override void Execute(EditorActionContext context) => context.interactions.documents.Save(documents.Open(context.target).documentId); + protected override void Execute(EditorActionContext context) + => context.interactions.documents.Save(documents.Open(context.target).documentId); } [EditorAction("shader/format", ShaderEditorCanvas.C_AREA)] @@ -528,7 +639,10 @@ protected override void Execute(EditorActionContext context) { var draft = documents.Open(context.target); var controller = documents.Controller(draft); - controller.ReplaceDocument(ShaderGraphAutoLayout.Apply(controller.document, documents.serialization, documents.context, documents.Describe), "Format Shader Graph"); + controller.ReplaceDocument( + ShaderGraphAutoLayout.Apply(controller.document, documents.serialization, documents.context, documents.Describe), + "Format Shader Graph" + ); draft.frameRequested = true; documents.Changed(draft); } @@ -541,6 +655,7 @@ internal sealed class ReloadShaderSource(ShaderEditorDocuments documents) : Shad /// Gets whether needs selection is active for the current instance. /// protected override bool needsSelection => false; + /// /// Gets whether writes is active for the current instance. /// @@ -552,5 +667,6 @@ internal sealed class ReloadShaderSource(ShaderEditorDocuments documents) : Shad /// /// The context that supplies state and services for this operation. /// - protected override void Execute(EditorActionContext context) => context.interactions.documents.Revert(documents.Open(context.target).documentId); + protected override void Execute(EditorActionContext context) + => context.interactions.documents.Revert(documents.Open(context.target).documentId); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs index 29a18c26b..22bfd7b9e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs @@ -5,25 +5,28 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Graphs; -using Inno.Editor.Graph; -using Inno.Editor.Interactions; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; using Inno.Rendering; -using Inno.Rendering.Shaders; using Inno.Rendering.Assets; +using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; + internal struct ShaderCanvasGroup { /// /// Gets the stable identity used to reference this value across subsystem boundaries. /// public string id { get; set; } + /// /// Gets the title text used by the current instance. /// public string title { get; set; } + /// /// Gets graph nodes affected by this organization action. /// @@ -37,6 +40,7 @@ internal sealed class FocusShaderNodes(ShaderEditorDocuments documents) : Shader /// Gets whether writes is active for the current instance. /// protected override bool writes => false; + /// /// Gets whether needs selection is active for the current instance. /// @@ -68,8 +72,10 @@ internal sealed class InsertShaderReroute(ShaderEditorDocuments documents) : Sha /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => base.Query(context).isEnabled - && documents.Open(context.target).selectedEdge is not null ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => base.Query(context).isEnabled + && documents.Open(context.target).selectedEdge is not null ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -87,8 +93,17 @@ protected override void Execute(EditorActionContext context) { position = draft.menuPosition }; - node.SetValue("valueType", ShaderGraphDocument.Encode(ShaderGraphType.Capture(source.type), documents.serialization, documents.context)); - string stage = ShaderGraphDocument.Read(graph.FindNode(edge.output.nodeId)!, "stage", "", documents.serialization, documents.context); + node.SetValue( + "valueType", + ShaderGraphDocument.Encode(ShaderGraphType.Capture(source.type), documents.serialization, documents.context) + ); + string stage = ShaderGraphDocument.Read( + graph.FindNode(edge.output.nodeId)!, + "stage", + "", + documents.serialization, + documents.context + ); node.SetValue("stage", ShaderGraphDocument.Encode(stage, documents.serialization, documents.context)); graph.AddNode(node); graph.RemoveEdge(edge.id); @@ -105,17 +120,15 @@ protected override void Execute(EditorActionContext context) internal sealed class GroupShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) { internal const string C_GROUPS = "inno.editor.shader.groups"; + internal static ShaderCanvasGroup[] Read( ShaderEditorDocuments documents, GraphDocument graph ) => graph.metadata.TryGetValue( C_GROUPS, out GraphSerializedValue? value - ) ? ShaderGraphDocument.Decode( - value, - documents.serialization, - documents.context - ) : []; + ) ? ShaderGraphDocument.Decode(value, documents.serialization, documents.context) : []; + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -127,13 +140,15 @@ protected override void Execute(EditorActionContext context) var draft = documents.Open(context.target); GraphDocument graph = documents.Controller(draft).document.Clone(); ShaderCanvasGroup[] groups = Read(documents, graph); - groups = [..groups, new() - { - id = Guid.NewGuid().ToString("N"), - title = "Group " + (groups.Length + 1), - nodes = draft.canvas.selectedNodes.Select(static id => id.value).ToArray() - } - + groups = + [ + ..groups, + new() + { + id = Guid.NewGuid().ToString("N"), + title = "Group " + (groups.Length + 1), + nodes = draft.canvas.selectedNodes.Select(static id => id.value).ToArray() + } ]; graph.SetMetadata(C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); documents.Controller(draft).ReplaceDocument(graph, "Group Shader Nodes"); @@ -155,10 +170,16 @@ protected override void Execute(EditorActionContext context) { var draft = documents.Open(context.target); GraphDocument graph = documents.Controller(draft).document.Clone(); - var groups = GroupShaderNodes.Read( - documents, - graph - ).Where(group => draft.selectedGroupId.Length != 0 ? group.id != draft.selectedGroupId : !group.nodes.All(id => draft.canvas.selectedNodes.Contains(new(id)))).ToArray(); + var groups = GroupShaderNodes + .Read(documents, graph) + .Where( + group => ( + draft.selectedGroupId.Length != 0 + ? group.id != draft.selectedGroupId + : !group.nodes.All(id => draft.canvas.selectedNodes.Contains(new(id))) + ) + ) + .ToArray(); graph.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); documents.Controller(draft).ReplaceDocument(graph, "Ungroup Shader Nodes"); draft.selectedGroupId = ""; @@ -184,18 +205,35 @@ AssetBrowserModule browser protected override EditorActionState Query(EditorActionContext context) { if (!base.Query(context).isEnabled) + { return EditorActionState.disabled; + } ShaderEditorDocuments.Draft draft = documents.Open(context.target); GraphDocument graph = documents.Controller(draft).document; GraphNodeRecord[] selected = draft.canvas.selectedNodes.Select(graph.FindNode).OfType().ToArray(); if (selected.Length != draft.canvas.selectedNodes.Count - || selected.Any(static node => node.definitionId is ShaderGraphDocument.outputDefinitionId or ShaderGraphNodes.inputDefinitionId or ShaderGraphNodes.outputDefinitionId)) + || selected.Any( + static node => ( + node.definitionId is ShaderGraphDocument.outputDefinitionId + or ShaderGraphNodes.inputDefinitionId + or ShaderGraphNodes.outputDefinitionId + ) + ) + ) { return EditorActionState.disabled; - string[] stages = selected.Select(node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", documents.serialization, documents.context)).Distinct(StringComparer.Ordinal).ToArray(); + } + string[] stages = selected + .Select(node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", documents.serialization, documents.context)) + .Distinct(StringComparer.Ordinal) + .ToArray(); if (stages.Length != 1 || stages[0].Length == 0) + { return EditorActionState.disabled; + } HashSet ids = selected.Select(static node => node.id).ToHashSet(); - return graph.edges.Any(edge => ids.Contains(edge.input.nodeId) != ids.Contains(edge.output.nodeId)) ? EditorActionState.enabled : EditorActionState.disabled; + return graph.edges.Any(edge => ids.Contains(edge.input.nodeId) != ids.Contains(edge.output.nodeId)) + ? EditorActionState.enabled + : EditorActionState.disabled; } /// @@ -211,18 +249,57 @@ protected override void Execute(EditorActionContext context) GraphDocument parent = controller.document; HashSet selected = [..draft.canvas.selectedNodes]; GraphNodeRecord[] nodes = parent.nodes.Where(node => selected.Contains(node.id)).ToArray(); - string stage = nodes.Select(node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", documents.serialization, documents.context)).Distinct(StringComparer.Ordinal).Single(); - GraphEdgeRecord[] incomingEdges = parent.edges.Where(edge => selected.Contains(edge.input.nodeId) && !selected.Contains(edge.output.nodeId)).ToArray(); - GraphEdgeRecord[] outgoingEdges = parent.edges.Where(edge => selected.Contains(edge.output.nodeId) && !selected.Contains(edge.input.nodeId)).ToArray(); + string stage = nodes + .Select(node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", documents.serialization, documents.context)) + .Distinct(StringComparer.Ordinal) + .Single(); + GraphEdgeRecord[] incomingEdges = parent.edges + .Where(edge => selected.Contains(edge.input.nodeId) && !selected.Contains(edge.output.nodeId)) + .ToArray(); + GraphEdgeRecord[] outgoingEdges = parent.edges + .Where(edge => selected.Contains(edge.output.nodeId) && !selected.Contains(edge.input.nodeId)) + .ToArray(); var inputGroups = incomingEdges.GroupBy(static edge => edge.output).ToArray(); var outputGroups = outgoingEdges.GroupBy(static edge => edge.output).ToArray(); var inputNames = new HashSet(StringComparer.Ordinal); var outputNames = new HashSet(StringComparer.Ordinal); - ShaderGraphNodePortDefinition[] inputs = inputGroups.Select(group => Port(Unique(group.First().input.portId.value, "input", inputNames), draft.ports[group.First().input.nodeId].Single(port => port.id == group.First().input.portId.value).type, required: true)).ToArray(); - ShaderGraphNodePortDefinition[] outputs = outputGroups.Select(group => Port(Unique(group.Key.portId.value, "output", outputNames), draft.ports[group.Key.nodeId].Single(port => port.id == group.Key.portId.value).type, required: false)).ToArray(); + ShaderGraphNodePortDefinition[] inputs = inputGroups + .Select( + group => Port( + Unique(group.First().input.portId.value, "input", inputNames), + draft.ports[group.First().input.nodeId].Single(port => port.id == group.First().input.portId.value).type, + required: true + ) + ) + .ToArray(); + ShaderGraphNodePortDefinition[] outputs = outputGroups + .Select( + group => Port( + Unique(group.Key.portId.value, "output", outputNames), + draft.ports[group.Key.nodeId].Single(port => port.id == group.Key.portId.value).type, + required: false + ) + ) + .ToArray(); ShaderDefinition parentDefinition = ShaderGraphDocument.ReadDefinition(parent, documents.serialization, documents.context); - HashSet ownedBindings = nodes.Where(static node => node.definitionId == "inno.shader.stage-input").Select(node => ShaderGraphDocument.Read(node, ShaderGraphDocument.settingsKey, new ShaderGraphInputSettings(), documents.serialization, documents.context).id).ToHashSet(StringComparer.Ordinal); - ShaderDefinition childDefinition = new("Graph Node", parentDefinition.properties.Where(property => ownedBindings.Contains(property.id.value)), [], []); + HashSet ownedBindings = nodes + .Where(static node => node.definitionId == "inno.shader.stage-input") + .Select( + node => ShaderGraphDocument.Read( + node, + ShaderGraphDocument.settingsKey, + new ShaderGraphInputSettings(), + documents.serialization, + documents.context + ).id + ) + .ToHashSet(StringComparer.Ordinal); + ShaderDefinition childDefinition = new( + "Graph Node", + parentDefinition.properties.Where(property => ownedBindings.Contains(property.id.value)), + [], + [] + ); GraphDocument child = ShaderGraphDocument.Create(childDefinition, documents.serialization, documents.context); string displayName = SuggestedName(documents, draft, selected); var nodeSettings = new ShaderGraphNodeSettings @@ -244,14 +321,27 @@ protected override void Execute(EditorActionContext context) position = new(source.position.x - minX + 280, source.position.y - minY + 80) }; foreach ((string key, GraphSerializedValue value)in source.values) + { if (key != ShaderGraphDocument.stageKey) + { copy.SetValue(key, value.Clone()); + } + } child.AddNode(copy); remap.Add(source.id, id); } - foreach (GraphEdgeRecord edge in parent.edges.Where(edge => selected.Contains(edge.output.nodeId) && selected.Contains(edge.input.nodeId))) - child.AddEdge(new(new("body/" + edge.id.value), new(remap[edge.output.nodeId], edge.output.portId), new(remap[edge.input.nodeId], edge.input.portId))); + foreach (GraphEdgeRecord edge in parent.edges.Where( + edge => selected.Contains(edge.output.nodeId) && selected.Contains(edge.input.nodeId) + )) { + child.AddEdge( + new( + new("body/" + edge.id.value), + new(remap[edge.output.nodeId], edge.output.portId), + new(remap[edge.input.nodeId], edge.input.portId) + ) + ); + } if (inputs.Length != 0) { var boundary = new GraphNodeRecord(new("function-inputs"), ShaderGraphNodes.inputDefinitionId) @@ -264,8 +354,18 @@ protected override void Execute(EditorActionContext context) ); child.AddNode(boundary); for (int index = 0; index < inputGroups.Length; index++) + { foreach (GraphEdgeRecord edge in inputGroups[index]) - child.AddEdge(new(new("input/" + edge.id.value), new(boundary.id, new(inputs[index].id)), new(remap[edge.input.nodeId], edge.input.portId))); + { + child.AddEdge( + new( + new("input/" + edge.id.value), + new(boundary.id, new(inputs[index].id)), + new(remap[edge.input.nodeId], edge.input.portId) + ) + ); + } + } } if (outputs.Length != 0) @@ -276,11 +376,23 @@ protected override void Execute(EditorActionContext context) }; boundary.SetValue( ShaderGraphDocument.settingsKey, - ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings { ports = outputs }, documents.serialization, documents.context) + ShaderGraphDocument.Encode( + new ShaderGraphNodeOutputSettings { ports = outputs }, + documents.serialization, + documents.context + ) ); child.AddNode(boundary); for (int index = 0; index < outputGroups.Length; index++) - child.AddEdge(new(new("output/" + index), new(remap[outputGroups[index].Key.nodeId], outputGroups[index].Key.portId), new(boundary.id, new(outputs[index].id)))); + { + child.AddEdge( + new( + new("output/" + index), + new(remap[outputGroups[index].Key.nodeId], outputGroups[index].Key.portId), + new(boundary.id, new(outputs[index].id)) + ) + ); + } } AssetPath path = UniquePath(draft.path, displayName, documents); @@ -290,7 +402,9 @@ protected override void Execute(EditorActionContext context) ShaderGraphNodeInterface nodeInterface = ShaderGraphNodes.ReadInterface(child, documents.serialization, documents.context); GraphDocument candidate = parent.Clone(); foreach (GraphNodeId id in selected) + { candidate.RemoveNode(id); + } var call = new GraphNodeRecord(new(Guid.NewGuid().ToString("N")), ShaderGraphNodes.callDefinitionId) { position = new(nodes.Average(static node => node.position.x), nodes.Average(static node => node.position.y)) @@ -301,10 +415,16 @@ protected override void Execute(EditorActionContext context) call.SetValue(ShaderGraphNodes.interfaceKey, ShaderGraphDocument.Encode(nodeInterface, documents.serialization, documents.context)); candidate.AddNode(call); for (int index = 0; index < inputGroups.Length; index++) + { candidate.AddEdge(new(new(Guid.NewGuid().ToString("N")), inputGroups[index].Key, new(call.id, new(inputs[index].id)))); + } for (int index = 0; index < outputGroups.Length; index++) + { foreach (GraphEdgeRecord edge in outputGroups[index]) + { candidate.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(call.id, new(outputs[index].id)), edge.input)); + } + } ShaderCanvasGroup[] groups = GroupShaderNodes.Read(documents, candidate).Select(group => { group.nodes = group.nodes.Where(id => !selected.Contains(new(id))).ToArray(); @@ -328,6 +448,7 @@ bool required type = ShaderGraphType.Capture(type), required = required }; + private static string Unique( string candidate, string fallback, @@ -336,7 +457,9 @@ HashSet used string root = string.IsNullOrWhiteSpace(candidate) ? fallback : candidate; string value = root; for (int suffix = 2; !used.Add(value); suffix++) + { value = root + suffix; + } return value; } @@ -359,13 +482,18 @@ ShaderEditorDocuments documents ) { AssetSourceMount mount = documents.assets.sourceMounts.Single(value => value.id == source.source); string directory = Path.GetDirectoryName(source.localPath)?.Replace('\\', '/') ?? ""; - string safeName = string.Concat(name.Select(character => Path.GetInvalidFileNameChars().Contains(character) ? '_' : character)).Trim(); + string safeName = string.Concat(name.Select(character => Path.GetInvalidFileNameChars().Contains(character) ? '_' : character)) + .Trim(); if (safeName.Length == 0) + { safeName = "Shader Node"; + } string prefix = directory.Length == 0 ? "" : directory + "/"; AssetPath path = new(source.source, prefix + safeName + ".ishader"); for (int suffix = 2; File.Exists(mount.Resolve(path.localPath)) || File.Exists(mount.Resolve(path.localPath) + ".imeta"); suffix++) + { path = new(source.source, prefix + safeName + " " + suffix + ".ishader"); + } return path; } } @@ -393,10 +521,16 @@ AssetBrowserModule browser protected override EditorActionState Query(EditorActionContext context) { if (!base.Query(context).isEnabled) + { return EditorActionState.disabled; + } var draft = documents.Open(context.target); - string? definition = draft.canvas.selectedNodes.Count == 1 ? documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())?.definitionId : null; - return definition is "inno.shader.source" or ShaderGraphNodes.callDefinitionId ? EditorActionState.enabled : EditorActionState.disabled; + string? definition = draft.canvas.selectedNodes.Count == 1 + ? documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())?.definitionId + : null; + return definition is "inno.shader.source" or ShaderGraphNodes.callDefinitionId + ? EditorActionState.enabled + : EditorActionState.disabled; } /// @@ -418,9 +552,16 @@ internal static void Reveal( Guid sourceId ) { if (!documents.assets.TryGetInfo(sourceId, out AssetInfo? info) || info is null) + { throw new IOException("Referenced Shader authoring asset is missing. Select a replacement in the node."); + } if (!documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry)) - throw new FileNotFoundException("Referenced Shader authoring asset is missing from the Asset Browser.", info.assetPath.ToString()); + { + throw new FileNotFoundException( + "Referenced Shader authoring asset is missing from the Asset Browser.", + info.assetPath.ToString() + ); + } string parent = Path.GetDirectoryName(info.assetPath.localPath)?.Replace('\\', '/') ?? string.Empty; browser.browser.SetCurrentDirectory(new AssetPath(info.assetPath.source, parent).ToString()); documents.interactions.SetSelection(entry); @@ -438,6 +579,7 @@ AssetBrowserModule browser /// Gets whether writes is active for the current instance. /// protected override bool writes => false; + /// /// Gets whether needs selection is active for the current instance. /// @@ -455,7 +597,9 @@ protected override void Execute(EditorActionContext context) string parent = Path.GetDirectoryName(draft.path.localPath)?.Replace('\\', '/') ?? string.Empty; browser.browser.SetCurrentDirectory(new AssetPath(draft.path.source, parent).ToString()); if (!documents.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry entry)) + { throw new FileNotFoundException("Shader source is missing from the Asset Browser.", draft.path.ToString()); + } documents.interactions.SetSelection(entry); documents.interactions.OpenPanel("asset.file-browser"); } @@ -468,6 +612,7 @@ internal sealed class ShowShaderDiagnostics(ShaderEditorDocuments documents) : S /// Gets whether writes is active for the current instance. /// protected override bool writes => false; + /// /// Gets whether needs selection is active for the current instance. /// @@ -492,6 +637,7 @@ AssetBrowserModule browser /// Gets whether writes is active for the current instance. /// protected override bool writes => false; + /// /// Gets whether needs selection is active for the current instance. /// @@ -509,9 +655,15 @@ protected override void Execute(EditorActionContext context) AssetSourceMount mount = documents.assets.sourceMounts.Single(value => value.id == AssetSourceId.project); string name = Path.GetFileNameWithoutExtension(draft.path.localPath) + " Copy"; AssetPath destination = AssetPath.Project(name + ".ishader"); - for (int index = 2; File.Exists(mount.Resolve(destination.localPath)) || File.Exists(mount.Resolve(destination.localPath) + ".imeta"); index++) + for (int index = 2; File.Exists(mount.Resolve(destination.localPath)) + || File.Exists(mount.Resolve(destination.localPath) + ".imeta"); index++ + ) { destination = AssetPath.Project(name + " " + index + ".ishader"); - AssetFileEntry entry = browser.edits.CreateSource(destination, GraphDocumentCodec.Encode(documents.Controller(draft).document, documents.serialization)); + } + AssetFileEntry entry = browser.edits.CreateSource( + destination, + GraphDocumentCodec.Encode(documents.Controller(draft).document, documents.serialization) + ); _ = context.interactions.For("panel/asset.file-browser", entry).Select(); _ = context.interactions.For("panel/asset.file-browser", entry).Execute("file-browser/rename"); context.interactions.OpenPanel("rendering.shader-editor"); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs index 8eb667f2f..e334487a2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs @@ -31,21 +31,32 @@ Func> describePorts float laneY = 70f; GraphNodeRecord[] outputs = graph.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) .OrderBy(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphStageSettings(), serialization, context).stage) - .ThenBy(static node => node.id.value, StringComparer.Ordinal).ToArray(); + .ThenBy(static node => node.id.value, StringComparer.Ordinal) + .ToArray(); if (outputs.Length == 0) - outputs = graph.nodes.Where(static node => node.definitionId == ShaderGraphNodes.outputDefinitionId - || node.definitionId.EndsWith("-output", StringComparison.Ordinal)) - .OrderBy(static node => node.id.value, StringComparer.Ordinal).ToArray(); + { + outputs = graph.nodes + .Where(static node => ( + node.definitionId == ShaderGraphNodes.outputDefinitionId + || node.definitionId.EndsWith("-output", StringComparison.Ordinal) + )) + .OrderBy(static node => node.id.value, StringComparer.Ordinal) + .ToArray(); + } foreach (GraphNodeRecord output in outputs) { GraphNodeRecord[] members = output.definitionId == ShaderGraphDocument.outputDefinitionId - ? graph.nodes.Where(node => node.id == output.id - || ShaderGraphDocument.Read(node, "stage", "", serialization, context) == output.id.value).ToArray() - : graph.nodes.Where(node => !placed.Contains(node.id)).ToArray(); + ? graph.nodes.Where(node => ( + node.id == output.id + || ShaderGraphDocument.Read(node, "stage", "", serialization, context) == output.id.value + )).ToArray() + : graph.nodes.Where(node => !placed.Contains(node.id)).ToArray(); LayoutLane(output, members, ref laneY); } GraphNodeRecord[] remaining = graph.nodes.Where(node => !placed.Contains(node.id)) - .OrderBy(static node => node.position.y).ThenBy(static node => node.id.value, StringComparer.Ordinal).ToArray(); + .OrderBy(static node => node.position.y) + .ThenBy(static node => node.id.value, StringComparer.Ordinal) + .ToArray(); for (int i = 0; i < remaining.Length; i++) { remaining[i].position = new((i % 4) * C_COLUMN + 70f, laneY + i / 4 * C_ROW); @@ -65,15 +76,19 @@ ref float y while (queue.Count != 0) { GraphNodeId current = queue.Dequeue(); - foreach (GraphNodeId predecessor in graph.edges.Where(edge => edge.input.nodeId == current && memberIds.Contains(edge.output.nodeId)) - .Select(static edge => edge.output.nodeId).Distinct()) - { + foreach (GraphNodeId predecessor in graph.edges + .Where(edge => edge.input.nodeId == current && memberIds.Contains(edge.output.nodeId)) + .Select(static edge => edge.output.nodeId) + .Distinct() + ) { int next = distance[current] + 1; // A draft may be invalid and contain a cycle. Layout must still terminate; // compilation owns cycle diagnostics, while the first reverse-BFS rank gives // every reachable node a stable visual column. if (distance.ContainsKey(predecessor)) + { continue; + } distance[predecessor] = next; queue.Enqueue(predecessor); } @@ -84,7 +99,8 @@ ref float y .GroupBy(node => distance[node.id]) .ToDictionary(static group => group.Key, static group => group .OrderBy(static node => node.position.y) - .ThenBy(static node => node.id.value, StringComparer.Ordinal).ToList()); + .ThenBy(static node => node.id.value, StringComparer.Ordinal) + .ToList()); // Alternating barycentric sweeps are the crossing-reduction phase of a layered graph // layout. Port order participates in the score, so values feeding ordered inputs do @@ -92,9 +108,13 @@ ref float y for (int sweep = 0; sweep < C_SWEEPS; sweep++) { for (int rank = 1; rank <= maximumDistance; rank++) + { Order(rank, towardOutput: true); + } for (int rank = maximumDistance - 1; rank >= 0; rank--) + { Order(rank, towardOutput: false); + } } int maximumRows = ranks.Values.Select(static rank => rank.Count).DefaultIfEmpty(1).Max(); @@ -114,7 +134,9 @@ void Order( bool towardOutput ) { if (!ranks.TryGetValue(rank, out List? nodes) || nodes.Count < 2) + { return; + } var oldOrder = nodes.Select(static ( node, index @@ -126,7 +148,9 @@ bool towardOutput { int comparison = Score(left, towardOutput).CompareTo(Score(right, towardOutput)); if (comparison != 0) + { return comparison; + } comparison = oldOrder[left.id].CompareTo(oldOrder[right.id]); return comparison != 0 ? comparison : StringComparer.Ordinal.Compare(left.id.value, right.id.value); }); @@ -146,11 +170,15 @@ bool towardOutput foreach ((GraphNodeId neighborId, GraphPortId port) in endpoints) { if (!distance.TryGetValue(neighborId, out int neighborRank) - || !ranks.TryGetValue(neighborRank, out List? neighbors)) + || !ranks.TryGetValue(neighborRank, out List? neighbors) + ) { continue; + } int index = neighbors.FindIndex(candidate => candidate.id == neighborId); if (index < 0) + { continue; + } IReadOnlyList ports; try { @@ -163,8 +191,9 @@ bool towardOutput GraphPortDirection direction = towardOutput ? GraphPortDirection.Input : GraphPortDirection.Output; ShaderNodePort[] matching = ports.Where(candidate => candidate.direction == direction).ToArray(); int portIndex = Array.FindIndex(matching, candidate => candidate.id == port.value); - double portOffset = portIndex < 0 || matching.Length < 2 ? 0d - : ((double)portIndex / (matching.Length - 1) - 0.5d) * 0.8d; + double portOffset = portIndex < 0 || matching.Length < 2 + ? 0d + : ((double)portIndex / (matching.Length - 1) - 0.5d) * 0.8d; total += index + portOffset; count++; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs index 0d3a73495..a0d6830b2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs @@ -2,6 +2,7 @@ using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + namespace Inno.Editor.Panel.ShaderEditor; [EditorModal("shader.check", "Checking Shader", order: 220)] @@ -9,10 +10,13 @@ internal sealed class ShaderCheckModal(ShaderEditorDocuments documents) : Editor { private DialogPresentation m_content; private DialogLayout m_layout; + /// public override bool isVisible => documents.TryGetCheckDraft(out _); + /// public override bool allowScrolling => false; + /// protected override Vector2? OnPrepare( EditorContext context, @@ -22,6 +26,7 @@ Vector2 availableContentSize m_layout = EditorUiSession.current.widgets.MeasureDialog(m_content, availableContentSize); return m_layout.size; } + /// protected override void OnDraw(EditorContext context) => EditorUiSession.current.widgets.DrawDialog(m_content, m_layout); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs index f958f61a8..f45471b51 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs @@ -1,17 +1,19 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Core; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; using Inno.Editor.Shaders; -using Inno.Editor.ImGui.ImGuiWidget; using Inno.Rendering; -using Ui = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using Ui = Inno.Editor.ImGui.ImGui; + namespace Inno.Editor.Panel.ShaderEditor; + [EditorPanel("rendering.shader-editor", "Shader Editor", order: 230, menuPath: "Authoring")] internal sealed class ShaderEditorPanel(ShaderEditorDocuments documents) : EditorPanel { @@ -19,10 +21,12 @@ internal sealed class ShaderEditorPanel(ShaderEditorDocuments documents) : Edito /// Gets whether use window padding is enabled for this implementation. /// public override bool useWindowPadding => true; + /// /// Gets whether allow scrolling is enabled for this implementation. /// public override bool allowScrolling => false; + /// /// Gets the preferred initial window size in logical editor units. /// @@ -38,14 +42,15 @@ protected override void OnDraw(EditorContext context) { AssetFileEntry? entry = documents.interactions.selection.selectedTarget as AssetFileEntry; if (documents.interactions.selection.selectedTarget is ShaderAsset shader) + { _ = documents.assets.TryGetFileSystemEntry(shader.assetPath, out entry); + } if (documents.interactions.selection.selectedTarget is ShaderInspectionSelection selection - && documents.assets.TryGetInfo( - selection.assetId, - out AssetInfo? info - ) - && info is not null) + && documents.assets.TryGetInfo(selection.assetId, out AssetInfo? info) + && info is not null + ) { _ = documents.assets.TryGetFileSystemEntry(info.assetPath, out entry); + } if (entry is null || entry.isDirectory || !entry.assetPath.localPath.EndsWith(".ishader", StringComparison.OrdinalIgnoreCase)) { ShaderEditorCanvas.DrawHeader(documents, null); @@ -62,7 +67,7 @@ out AssetInfo? info new ShaderEditorCanvas(documents, documents.Open(entry)).Draw(); } catch (Exception failure) when ((failure is System.IO.IOException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) { EditorUI.current.widgets.WrappedText(failure.Message); } @@ -82,6 +87,7 @@ internal sealed class OpenShaderEditorAction : EditorAction /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; + /// /// Applies the editor action to the supplied interaction context. /// @@ -92,6 +98,8 @@ protected override void Execute(EditorActionContext context { context.interactions.SetSelection(context.target); if (!context.interactions.OpenPanel("rendering.shader-editor")) + { throw new InvalidOperationException("Shader Editor is unavailable."); + } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Stats/FrameStatisticsSampler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Stats/FrameStatisticsSampler.cs index 81d04bdf5..6d9a3b98a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Stats/FrameStatisticsSampler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Stats/FrameStatisticsSampler.cs @@ -27,24 +27,34 @@ internal bool Update( float frameDeltaTime ) { if (!float.IsFinite(totalTime) || !float.IsFinite(frameDeltaTime) || frameDeltaTime <= 0f) + { return false; + } if (float.IsFinite(m_lastFrameTime) && (totalTime < m_lastFrameTime || totalTime - m_lastFrameTime > C_SAMPLE_RESET_SECONDS - || totalTime - m_lastFrameTime > frameDeltaTime * 1.5f + 0.0001f)) + || totalTime - m_lastFrameTime > frameDeltaTime * 1.5f + 0.0001f) + ) { Reset(); + } m_lastFrameTime = totalTime; int expired = 0; while (expired < m_count && m_sampleTimes[expired] < totalTime - C_SAMPLE_WINDOW_SECONDS) + { expired++; + } RemoveOldest(expired); m_duration += frameDeltaTime; m_frames++; if (m_count > 0 && totalTime < m_nextSampleTime) + { return false; + } deltaTime = (float)(m_duration / m_frames); framesPerSecond = (float)(m_frames / m_duration); if (m_count == C_SAMPLE_CAPACITY) + { RemoveOldest(1); + } m_frameTimes[m_count] = deltaTime * 1000f; m_frameRates[m_count] = framesPerSecond; m_sampleTimes[m_count++] = totalTime; @@ -67,7 +77,9 @@ internal void Reset() private void RemoveOldest(int count) { if (count == 0) + { return; + } m_count -= count; Array.Copy(m_frameTimes, count, m_frameTimes, 0, m_count); Array.Copy(m_frameRates, count, m_frameRates, 0, m_count); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs index 3839f690c..eb782d298 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs @@ -1,13 +1,15 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Stats; + /// /// Shows lightweight runtime metrics. /// @@ -20,6 +22,7 @@ internal sealed class StatsPanel : EditorPanel private IReadOnlyList? m_previousStatistics; private StatisticGroup[] m_groups = []; private (string label, string value)[] m_frameValues = []; + /// /// Gets whether use window padding is active for the current instance. /// @@ -28,9 +31,7 @@ internal sealed class StatsPanel : EditorPanel /// /// Creates the panel. /// - internal StatsPanel() - { - } + internal StatsPanel() {} /// /// Draws this feature using the current editor presentation context. @@ -56,8 +57,11 @@ protected override void OnDraw(EditorContext context) if (!ReferenceEquals(statistics, m_previousStatistics)) { m_groups = statistics.GroupBy(static statistic => statistic.groupId) - .Select(static group => new StatisticGroup(group.First().groupName, - group.Select(static value => (value.label, value.value)).ToArray())).ToArray(); + .Select(static group => new StatisticGroup( + group.First().groupName, + group.Select(static value => (value.label, value.value)).ToArray() + )) + .ToArray(); m_previousStatistics = statistics; } if (m_groups.Length == 0) @@ -66,7 +70,9 @@ protected override void OnDraw(EditorContext context) return; } foreach (StatisticGroup group in m_groups) + { DrawGroup(group.title, group.values); + } } /// @@ -84,14 +90,22 @@ private static void DrawGroup( ) { EditorUI.current.widgets.CollectionSectionHeader(title); System.Numerics.Vector2 padding = EditorUI.current.widgets.style.sectionPadding; - ImGuiTableFlags flags = ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.RowBg | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.PadOuterX; - Ui.PushStyleVar((ImGuiStyleVar.CellPadding), new System.Numerics.Vector2(padding.X, C_ROW_PADDING * EditorUI.current.widgets.style.zoom)); + ImGuiTableFlags flags = ImGuiTableFlags.SizingStretchProp + | ImGuiTableFlags.RowBg + | ImGuiTableFlags.NoSavedSettings + | ImGuiTableFlags.PadOuterX; + Ui.PushStyleVar( + (ImGuiStyleVar.CellPadding), + new System.Numerics.Vector2(padding.X, C_ROW_PADDING * EditorUI.current.widgets.style.zoom) + ); Ui.PushStyleColor((ImGuiCol.TableRowBg), EditorPalette.collectionRow); Ui.PushStyleColor((ImGuiCol.TableRowBgAlt), EditorPalette.collectionRowAlternate); try { if (!Ui.BeginTable($"##stats_{title}", 2, flags, default(System.Numerics.Vector2), 0f)) + { return; + } try { Ui.TableSetupColumn("##label", (ImGuiTableColumnFlags.WidthStretch), 0.42f); diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconAttribute.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconAttribute.cs index ea598c569..dd853e41b 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconAttribute.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconAttribute.cs @@ -1,8 +1,9 @@ +using System; using Inno.Editor.Assets; using Inno.Editor.Core; -using System; namespace Inno.Editor.Assets.ImGui; + /// /// Declares the icon used by the Asset Browser for an imported asset type or source extension. /// @@ -10,7 +11,11 @@ namespace Inno.Editor.Assets.ImGui; /// Apply one or more declarations to a container type. The container has no runtime responsibility; /// it only keeps related icon declarations together so the type catalog can discover them. /// -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false)] +[AttributeUsage( + AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Delegate, + AllowMultiple = true, + Inherited = false +)] public sealed class AssetIconAttribute : Attribute { /// @@ -77,20 +82,24 @@ public AssetIconAttribute( /// an extension declaration. /// public Type? assetType { get; } + /// /// Gets the normalized source extension represented by this declaration, or /// for a type declaration. /// public string? extension { get; } + /// /// Gets the Editor icon glyph to render. /// public string icon { get; } + /// /// Gets whether a type declaration may also represent derived asset types. Extension declarations /// always return . /// public bool useForChildren { get; } + /// /// Gets the tie-breaking priority after target specificity. /// @@ -99,21 +108,31 @@ public AssetIconAttribute( private static string NormalizeExtension(string extension) { if (string.IsNullOrWhiteSpace(extension)) + { throw new ArgumentException("A source file extension is required.", nameof(extension)); + } string normalized = extension.Trim(); if (normalized.Contains('/') || normalized.Contains('\\')) + { throw new ArgumentException("A source file extension cannot contain path separators.", nameof(extension)); + } if (!normalized.StartsWith(".", StringComparison.Ordinal)) + { normalized = "." + normalized; + } if (normalized.Length == 1) + { throw new ArgumentException("A source file extension must contain a suffix.", nameof(extension)); + } return normalized.ToLowerInvariant(); } private static string ValidateIcon(string icon) { if (string.IsNullOrWhiteSpace(icon)) + { throw new ArgumentException("An Editor icon glyph is required.", nameof(icon)); + } return icon; } } diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconRegistry.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconRegistry.cs index 8428eff48..e9fcde1f6 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconRegistry.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/AssetIconRegistry.cs @@ -1,16 +1,18 @@ -using Inno.Editor.Assets; -using Inno.Editor.Core; using System; using System.Collections.Generic; using System.Linq; using Inno.Assets; -using Inno.Extensibility.Types; +using Inno.Editor.Assets; +using Inno.Editor.Core; using Inno.Editor.Settings; +using Inno.Extensibility.Types; namespace Inno.Editor.Assets.ImGui; + internal sealed class AssetIconRegistry : TypeRegistry { private readonly EditorSettings m_settings; + internal AssetIconRegistry( EditorSettings settings, TypeCatalog types @@ -58,23 +60,22 @@ protected override Snapshot Build(TypeCacheSnapshot types) foreach (Type declarationType in types.types.Select(typeRef => typeRef.Resolve(types)).OrderBy( static type => type.Assembly.GetName().Name, StringComparer.Ordinal - ).ThenBy( - static type => type.FullName, - StringComparer.Ordinal - )) - { + ).ThenBy(static type => type.FullName, StringComparer.Ordinal) + ) { foreach (AssetIconAttribute attribute in declarationType.GetCustomAttributes( typeof(AssetIconAttribute), inherit: false ).Cast().OrderBy( static value => value.assetType?.FullName ?? value.extension, StringComparer.Ordinal - ).ThenBy(static value => value.priority)) - { + ).ThenBy(static value => value.priority) + ) { if (attribute.assetType is Type assetType) { ValidateType(attribute, declarationType, assetType, typeRegistrations); - typeRegistrations.Add(new TypeRegistration(assetType, attribute.useForChildren, attribute.priority, declarationType, attribute.icon)); + typeRegistrations.Add( + new TypeRegistration(assetType, attribute.useForChildren, attribute.priority, declarationType, attribute.icon) + ); } else if (attribute.extension is string extension) { @@ -97,8 +98,9 @@ out string icon { foreach (TypeRegistration registration in current.typeRegistrations) { - if (!EditorTypeSpecificity.TryGet(assetType, registration.assetType, out int distance) || distance > 0 && !registration.useForChildren) - { + if (!EditorTypeSpecificity.TryGet(assetType, registration.assetType, out int distance) + || distance > 0 && !registration.useForChildren + ) { continue; } @@ -122,12 +124,14 @@ out string icon foreach (ExtensionRegistration registration in current.extensionRegistrations) { if (!relativePath.EndsWith(registration.extension, StringComparison.OrdinalIgnoreCase)) + { continue; + } if (best is null || registration.extension.Length > best.extension.Length || registration.extension.Length == best.extension.Length - && registration.priority > best.priority) - { + && registration.priority > best.priority + ) { best = registration; } } @@ -144,12 +148,21 @@ IReadOnlyList registrations ) { if (!typeof(AssetObject).IsAssignableFrom(assetType)) { - throw new InvalidOperationException($"Asset icon declaration on '{declarationType.FullName}' targets " + $"'{assetType.FullName}', " + $"which does not derive from '{typeof(AssetObject).FullName}'."); + throw new InvalidOperationException( + $"Asset icon declaration on '{declarationType.FullName}' targets " + $"'{assetType.FullName}', " + $"which does not derive from '{typeof(AssetObject).FullName}'." + ); } - if (registrations.Any(value => value.assetType == assetType && value.useForChildren == attribute.useForChildren && value.priority == attribute.priority)) - { - throw new InvalidOperationException($"Asset icon registration for '{assetType.FullName}' conflicts at priority " + $"{attribute.priority}."); + if (registrations.Any( + value => ( + value.assetType == assetType + && value.useForChildren == attribute.useForChildren + && value.priority == attribute.priority + ) + )) { + throw new InvalidOperationException( + $"Asset icon registration for '{assetType.FullName}' conflicts at priority " + $"{attribute.priority}." + ); } } @@ -159,9 +172,12 @@ private static void ValidateExtension( string extension, IReadOnlyList registrations ) { - if (registrations.Any(value => string.Equals(value.extension, extension, StringComparison.OrdinalIgnoreCase) && value.priority == attribute.priority)) - { - throw new InvalidOperationException($"Asset icon declaration on '{declarationType.FullName}' for extension '{extension}' " + $"conflicts at priority {attribute.priority}."); + if (registrations.Any( + value => string.Equals(value.extension, extension, StringComparison.OrdinalIgnoreCase) && value.priority == attribute.priority + )) { + throw new InvalidOperationException( + $"Asset icon declaration on '{declarationType.FullName}' for extension '{extension}' " + $"conflicts at priority {attribute.priority}." + ); } } @@ -169,6 +185,7 @@ internal sealed record Snapshot( TypeRegistration[] typeRegistrations, ExtensionRegistration[] extensionRegistrations ); + internal sealed record TypeRegistration( Type assetType, bool useForChildren, @@ -176,6 +193,7 @@ internal sealed record TypeRegistration( Type declarationType, string icon ); + internal sealed record ExtensionRegistration( string extension, int priority, diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/BuiltInAssetIcons.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/BuiltInAssetIcons.cs index 5079b01f9..5b85f49aa 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/BuiltInAssetIcons.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Icons/BuiltInAssetIcons.cs @@ -1,9 +1,10 @@ -using Inno.Editor.ImGui; using Inno.Editor.Assets; using Inno.Editor.Core; +using Inno.Editor.ImGui; using Inno.Editor.Settings; namespace Inno.Editor.Assets.ImGui; + [AssetIcon(".txt", ImGuiIcon.FileLines)] [AssetIcon(".json", ImGuiIcon.FileLines)] [AssetIcon(".yaml", ImGuiIcon.FileLines)] diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs index 27a7a6550..c02c7eb58 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs @@ -1,18 +1,21 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Assets; using System; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; using Inno.Editor.Core; -using Inno.Editor.Inspection; -using Inno.Editor.Interactions; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Inspection; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.Assets.ImGui; + [InspectionDrawer(typeof(AssetFileEntry))] internal sealed class AssetSelectionInspectionDrawer : InspectionDrawer { private readonly AssetBrowserModule m_assets; + /// /// Creates an Asset source drawer that shares the Asset Browser presentation registry. /// @@ -48,6 +51,7 @@ protected override string GetIcon( InspectionDrawContext context, AssetFileEntry target ) => m_assets.GetIcon(target); + /// /// Binds a caller-visible label to the current inspection target. /// @@ -64,6 +68,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, AssetFileEntry target ) => (target.nameWithoutExtension, null); + /// /// Renders the header presentation for the current editor frame. /// @@ -77,6 +82,7 @@ protected override void DrawHeader( InspectionDrawContext context, AssetFileEntry target ) => EditorUI.current.widgets.ColoredText(EditorPalette.contextText, target.assetPath.ToString()); + /// /// Renders the value presentation for the current editor frame. /// @@ -90,15 +96,17 @@ protected override void Draw( InspectionDrawContext context, AssetFileEntry entry ) { - if (!EditorUI.current.widgets.SectionHeader("Asset", "This view describes the selected source entry. Structured assets may replace it with a dedicated authoring drawer.")) - { + if (!EditorUI.current.widgets.SectionHeader( + "Asset", + "This view describes the selected source entry. Structured assets may replace it with a dedicated authoring drawer." + )) { return; } DrawMetadata( "Type", m_assets.edits.IsPluginRoot(entry) ? "IPlugin" : entry.isDirectory - && AssetSample.HasSampleDirectoryName(entry.assetPath) ? "ISample" : entry.isDirectory ? "Directory" : "File" + && AssetSample.HasSampleDirectoryName(entry.assetPath) ? "ISample" : entry.isDirectory ? "Directory" : "File" ); if (!entry.isDirectory) { diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs index bfbe2a40e..0eb3e0ed0 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs @@ -1,15 +1,16 @@ -using Inno.Editor.ImGui; using System; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Assets; using Inno.Editor.Core; +using Inno.Editor.ImGui; using Inno.Editor.Inspection; using Inno.Editor.Interactions; using Inno.Editor.Settings; using Inno.Extensibility.Types; namespace Inno.Editor.Assets.ImGui; + /// /// Owns asset navigation and icon presentation independently from source mutations. /// @@ -18,6 +19,7 @@ public sealed class AssetBrowserModule : EditorModule, IInspectionIconProvider /// Creates the asset presentation module for the current editor generation. /// @@ -53,10 +55,12 @@ TypeCatalog types /// Gets the source editing service; this module does not implement source transactions. /// public AssetEditingModule edits { get; } + /// /// Gets navigation state; object selection belongs to the shared interaction owner. /// public AssetBrowserState browser { get; } + /// /// Gets the configured folder glyph used by asset navigation. /// @@ -83,7 +87,9 @@ protected override void Capture(EditorState state) /// protected override void Restore(EditorState state) { - AssetBrowserRoot restoredRoot = Enum.TryParse(state.Get("root", string.Empty), out AssetBrowserRoot parsedRoot) ? parsedRoot : AssetBrowserRoot.Assets; + AssetBrowserRoot restoredRoot = Enum.TryParse(state.Get("root", string.Empty), out AssetBrowserRoot parsedRoot) + ? parsedRoot + : AssetBrowserRoot.Assets; string assetsDirectory = RestoreDirectory(AssetBrowserRoot.Assets, state.Get("assetsDirectory", string.Empty)); string pluginsDirectory = RestoreDirectory(AssetBrowserRoot.Plugins, state.Get("pluginsDirectory", string.Empty)); browser.Restore(restoredRoot, assetsDirectory, pluginsDirectory); @@ -95,22 +101,30 @@ string path ) { string directory = AssetPath.Parse(path).ToString(); if (string.IsNullOrEmpty(directory)) + { return string.Empty; + } AssetPath isolated = AssetPath.Parse(directory); if ((root == AssetBrowserRoot.Assets) != (isolated.source == AssetSourceId.project)) + { return string.Empty; + } while (!IsAvailableDirectory(directory)) { string parent = ParentDirectory(directory); if (string.Equals(parent, directory, StringComparison.Ordinal)) + { return string.Empty; + } directory = parent; } return directory; } - private bool IsAvailableDirectory(string path) => edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(path), out AssetFileEntry entry) && entry.isDirectory; + private bool IsAvailableDirectory(string path) + => edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(path), out AssetFileEntry entry) && entry.isDirectory; + /// /// Resolves the presentation icon registered for an asset type or source extension. /// @@ -128,7 +142,9 @@ public string GetIcon(AssetFileEntry entry) { ArgumentNullException.ThrowIfNull(entry); if (entry.isDirectory) + { return folderIcon; + } _ = edits.pipeline.TryGetAssetType(entry.assetPath, out Type? assetType); if (m_icons.TryResolve(assetType, entry.assetPath.ToString(), out string icon)) { @@ -140,6 +156,7 @@ public string GetIcon(AssetFileEntry entry) /// protected override void OnDispose() => m_icons.Dispose(); + private static string ParentDirectory(string value) { AssetPath path = AssetPath.Parse(value); diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs index edc2981d1..308241d10 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs @@ -1,13 +1,14 @@ -using Inno.Editor.Assets; using System; using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.Inspection; +using Inno.Editor.Interactions; namespace Inno.Editor.Assets.ImGui; + /// /// Identifies the authoring or installed-content root displayed by the Asset Browser. /// @@ -32,6 +33,7 @@ public sealed class AssetBrowserState private readonly AssetPipeline m_assets; private string m_assetsDirectory = string.Empty; private string m_pluginsDirectory = string.Empty; + /// /// Creates Asset Browser navigation state. /// @@ -56,10 +58,12 @@ AssetPipeline assets /// Gets the root currently displayed by the Asset Browser. /// public AssetBrowserRoot root { get; private set; } + /// /// Gets the current directory inside . An empty value identifies that root's overview. /// public string currentDirectory => root == AssetBrowserRoot.Assets ? m_assetsDirectory : m_pluginsDirectory; + /// /// Gets the most recently visited writable project directory, independently of the displayed root. /// @@ -99,6 +103,7 @@ public bool IsSelected( EditorContext context, AssetFileEntry entry ) => m_interactions.selection.Contains(entry); + /// /// Adds or removes an asset from the current selection without retaining runtime asset objects. /// @@ -122,6 +127,7 @@ AssetFileEntry entry /// The authoring or installed-content root to display. /// public void SetRoot(AssetBrowserRoot value) => root = value; + /// /// Sets the current Asset Browser directory and infers its root from the isolated source identity. /// @@ -163,8 +169,10 @@ public void Select( object? target = null; if (!string.IsNullOrWhiteSpace(relativePath)) { - if (m_assets.TryGetFileSystemEntry(Inno.Assets.AssetPath.Parse(Normalize(relativePath)), out Inno.Assets.Pipeline.AssetFileEntry entry)) - { + if (m_assets.TryGetFileSystemEntry( + Inno.Assets.AssetPath.Parse(Normalize(relativePath)), + out Inno.Assets.Pipeline.AssetFileEntry entry + )) { target = entry; } } @@ -181,7 +189,9 @@ public void Select( /// /// The source-relative directory, or an empty string for the root. /// - public string GetDirectory(AssetBrowserRoot targetRoot) => targetRoot == AssetBrowserRoot.Assets ? m_assetsDirectory : m_pluginsDirectory; + public string GetDirectory(AssetBrowserRoot targetRoot) + => targetRoot == AssetBrowserRoot.Assets ? m_assetsDirectory : m_pluginsDirectory; + internal void Restore( AssetBrowserRoot restoredRoot, string assetsDirectory, @@ -228,15 +238,21 @@ private void SetDirectory( string directory ) { if (targetRoot == AssetBrowserRoot.Assets) + { m_assetsDirectory = directory; + } else + { m_pluginsDirectory = directory; + } } private static string Normalize(string? relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) + { return string.Empty; + } return AssetPath.Parse(relativePath.Replace('\\', '/').Trim()).ToString(); } } diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasLayout.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasLayout.cs index 64eb02377..d8b0e2cdc 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasLayout.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasLayout.cs @@ -45,15 +45,23 @@ public int SetNodes(IEnumerable nodes) GraphCanvasNode node = candidate[index]; ArgumentNullException.ThrowIfNull(node); if (m_byId.TryGetValue(node.id, out GraphCanvasNode? current) && Equivalent(current, node)) + { candidate[index] = node = current; + } else + { changes++; + } if (!byId.TryAdd(node.id, node)) + { throw new ArgumentException("A graph layout cannot contain duplicate node identities.", nameof(nodes)); + } } changes += m_byId.Keys.Count(id => !byId.ContainsKey(id)); if (changes == 0 && m_nodes.SequenceEqual(candidate)) + { return 0; + } m_nodes = Array.AsReadOnly(candidate); m_byId = byId; return changes; diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasNode.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasNode.cs index 61df6f786..7a8e520f4 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasNode.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasNode.cs @@ -53,15 +53,23 @@ IEnumerable ports ArgumentNullException.ThrowIfNull(title); ArgumentNullException.ThrowIfNull(ports); if (!float.IsFinite(position.x) || !float.IsFinite(position.y)) + { throw new ArgumentOutOfRangeException(nameof(position)); + } if (!float.IsFinite(size.X) || !float.IsFinite(size.Y) || size.X <= 0f || size.Y <= 0f) + { throw new ArgumentOutOfRangeException(nameof(size)); + } if (!float.IsFinite(headerHeight) || headerHeight < 0f || headerHeight > size.Y) + { throw new ArgumentOutOfRangeException(nameof(headerHeight)); + } GraphCanvasPort[] frozen = ports.ToArray(); if (frozen.Any(port => port.endpoint.nodeId != id) - || frozen.Select(static port => (port.endpoint, port.direction)).Distinct().Count() != frozen.Length) + || frozen.Select(static port => (port.endpoint, port.direction)).Distinct().Count() != frozen.Length + ) { throw new ArgumentException("Node ports require unique endpoint/direction pairs owned by the same node.", nameof(ports)); + } this.id = id; this.position = position; this.size = size; diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs index 9dc09c562..9e9fe5b5d 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs @@ -91,11 +91,17 @@ Vector2 pointer ArgumentNullException.ThrowIfNull(nodes); var starts = new Dictionary(); foreach (GraphNodeId id in nodes) + { if (layout.TryGetNode(id, out GraphCanvasNode? node)) + { starts.TryAdd(id, node.position); + } + } Cancel(); foreach (var entry in starts) + { m_starts.Add(entry.Key, entry.Value); + } m_dragging = m_starts.Count != 0; m_pointerStart = pointer; } @@ -125,20 +131,26 @@ GraphCanvasPointerInput input ) { ArgumentNullException.ThrowIfNull(layout); if (!float.IsFinite(input.position.X) || !float.IsFinite(input.position.Y)) + { throw new ArgumentOutOfRangeException(nameof(input)); + } if (input.cancel) { Cancel(); return default; } if (input.readOnly && (m_dragging || m_state.pendingConnection is not null)) + { Cancel(); + } GraphNodeId? pressed = null; if (input.isPressed && input.isHovered) { GraphCanvasPort? port = view.HitPort(layout, input.position); if (!input.readOnly && port is { isMissing: false } endpoint) + { m_state.BeginConnection(endpoint.endpoint, endpoint.direction); + } else { GraphCanvasNode? node = view.HitNode(layout, input.position); @@ -146,16 +158,24 @@ GraphCanvasPointerInput input { pressed = node.id; if (input.shift) + { m_state.ToggleNode(node.id); + } else if (!m_state.selectedNodes.Contains(node.id)) + { m_state.SelectNodes([node.id]); + } if (!input.readOnly) + { BeginMove(layout, m_state.selectedNodes, input.position); + } } else if (node is null) { if (!input.shift) + { m_state.ClearSelection(); + } m_boxSelecting = true; m_boxSelection = input.shift ? m_state.selectedNodes.ToArray() : []; m_pointerStart = input.position; @@ -167,22 +187,30 @@ GraphCanvasPointerInput input GraphPosition start = view.ToGraph(m_pointerStart); GraphPosition current = view.ToGraph(input.position); foreach ((GraphNodeId id, GraphPosition position) in m_starts) + { m_preview[id] = new(position.x + current.x - start.x, position.y + current.y - start.y); + } } if (!input.isReleased) + { return new(pressed, null, null, null, null); + } IReadOnlyDictionary? moved = null; if (m_dragging && m_preview.Any(entry => m_starts[entry.Key] != entry.Value)) + { moved = new ReadOnlyDictionary(new Dictionary(m_preview)); + } if (m_boxSelecting) + { m_state.SelectNodes(m_boxSelection.Concat(view.BoxNodes(layout, m_pointerStart, input.position)).Distinct()); + } GraphEndpoint? output = null; GraphEndpoint? targetInput = null; GraphEndpoint? released = null; if (!input.readOnly && input.isHovered && m_state.pendingConnection is GraphEndpoint source - && m_state.pendingConnectionDirection is GraphPortDirection direction) - { + && m_state.pendingConnectionDirection is GraphPortDirection direction + ) { GraphCanvasPort? destination = view.HitPort(layout, input.position); if (destination is { isMissing: false } target && target.direction != direction) { @@ -190,8 +218,10 @@ GraphCanvasPointerInput input targetInput = direction == GraphPortDirection.Input ? source : target.endpoint; } else if (destination is null && direction == GraphPortDirection.Output - && input.isHovered && view.HitNode(layout, input.position) is null) + && input.isHovered && view.HitNode(layout, input.position) is null + ) { released = source; + } } Cancel(); return new(pressed, moved, output, targetInput, released); diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPort.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPort.cs index 59fe75f61..7bbfe8d44 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPort.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPort.cs @@ -55,13 +55,19 @@ public GraphCanvasPort( ArgumentException.ThrowIfNullOrWhiteSpace(endpoint.portId.value); ArgumentNullException.ThrowIfNull(label); if (!float.IsFinite(position.X) || !float.IsFinite(position.Y)) + { throw new ArgumentOutOfRangeException(nameof(position)); + } if (direction is not GraphPortDirection.Input and not GraphPortDirection.Output) + { throw new ArgumentOutOfRangeException(nameof(direction)); + } if (labelBounds is { } bounds && (!float.IsFinite(bounds.minimum.X) || !float.IsFinite(bounds.minimum.Y) - || !float.IsFinite(bounds.maximum.X) || !float.IsFinite(bounds.maximum.Y) - || bounds.maximum.X < bounds.minimum.X || bounds.maximum.Y < bounds.minimum.Y)) + || !float.IsFinite(bounds.maximum.X) || !float.IsFinite(bounds.maximum.Y) + || bounds.maximum.X < bounds.minimum.X || bounds.maximum.Y < bounds.minimum.Y) + ) { throw new ArgumentOutOfRangeException(nameof(labelBounds)); + } this.endpoint = endpoint; this.direction = direction; this.position = position; diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs index 60371d316..93b26d028 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs @@ -3,6 +3,7 @@ using System.Numerics; using Inno.Core.Graphs; using Inno.Editor.ImGui; + using CanvasDrawing = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Graph.ImGui; @@ -55,7 +56,9 @@ Vector2 point GraphCanvasNode node = layout.nodes[index]; var bounds = NodeBounds(node); if (Contains(bounds, point)) + { return node; + } } return null; } @@ -85,21 +88,34 @@ Vector2 point ) { ArgumentNullException.ThrowIfNull(layout); if (!float.IsFinite(radius) || radius < 0f) + { throw new ArgumentOutOfRangeException(nameof(radius)); + } float hitRadius = MathF.Max(radius, 7f * zoom); for (int index = layout.nodes.Count - 1; index >= 0; index--) { GraphCanvasNode node = layout.nodes[index]; Vector2 minimum = ToScreen(node.position); foreach (GraphCanvasPort port in node.ports) + { if (Vector2.DistanceSquared(point, minimum + port.position * m_zoom) <= hitRadius * hitRadius) + { return port; + } + } if (!Contains(NodeBounds(node), point)) + { continue; + } foreach (GraphCanvasPort port in node.ports) + { if (port.labelBounds is { } label && Contains( - (ToScreen(node.position) + label.minimum * m_zoom, ToScreen(node.position) + label.maximum * m_zoom), point)) + (ToScreen(node.position) + label.minimum * m_zoom, ToScreen(node.position) + label.maximum * m_zoom), + point + )) { return port; + } + } // Covered nodes must not receive interaction through the frontmost node's body. return null; } @@ -134,8 +150,10 @@ Vector2 second { var bounds = NodeBounds(node); if (bounds.maximum.X >= minimum.X && bounds.minimum.X <= maximum.X - && bounds.maximum.Y >= minimum.Y && bounds.minimum.Y <= maximum.Y) + && bounds.maximum.Y >= minimum.Y && bounds.minimum.Y <= maximum.Y + ) { nodes.Add(node.id); + } } return nodes.AsReadOnly(); } @@ -182,20 +200,39 @@ public bool DrawNode( Vector2 minimum = bounds.minimum; Vector2 maximum = bounds.maximum; if (m_size.X == 0f || m_size.Y == 0f || maximum.X < m_origin.X || minimum.X > m_origin.X + m_size.X - || maximum.Y < m_origin.Y || minimum.Y > m_origin.Y + m_size.Y) + || maximum.Y < m_origin.Y || minimum.Y > m_origin.Y + m_size.Y + ) { return false; + } var clip = CanvasDrawing.GetClipBounds(); if (maximum.X < clip.minimum.X || minimum.X > clip.maximum.X || maximum.Y < clip.minimum.Y || minimum.Y > clip.maximum.Y) + { return false; + } float zoom = this.zoom; - draw.PushClip(Vector2.Max(m_origin, minimum - new Vector2(6f * zoom)), - Vector2.Min(m_origin + m_size, maximum + new Vector2(6f * zoom)), true); + draw.PushClip( + Vector2.Max(m_origin, minimum - new Vector2(6f * zoom)), + Vector2.Min(m_origin + m_size, maximum + new Vector2(6f * zoom)), + true + ); try { - draw.FilledRectangle(minimum + new Vector2(3, 5), maximum + new Vector2(3, 5), Pack(0f, 0f, 0f, EditorPalette.opacityMuted), 6f * zoom, false); + draw.FilledRectangle( + minimum + new Vector2(3, 5), + maximum + new Vector2(3, 5), + Pack(0f, 0f, 0f, EditorPalette.opacityMuted), + 6f * zoom, + false + ); draw.FilledRectangle(minimum, maximum, Pack(0.115f, 0.12f, 0.14f), 6f * zoom, false); draw.FilledRectangle(minimum, new(maximum.X, minimum.Y + node.headerHeight * zoom), headerColor, 6f * zoom, true); - draw.Rectangle(minimum, maximum, selected ? Pack(0.65f, 0.47f, 0.88f) : Pack(0.26f, 0.27f, 0.31f), 6f * zoom, selected ? 2f : 1f); + draw.Rectangle( + minimum, + maximum, + selected ? Pack(0.65f, 0.47f, 0.88f) : Pack(0.26f, 0.27f, 0.31f), + 6f * zoom, + selected ? 2f : 1f + ); draw.Text(minimum + new Vector2(10f, 7f) * zoom, CanvasDrawing.GetStyleColor(ImGuiCol.Text), node.title, zoom); foreach (GraphCanvasPort port in node.ports) { @@ -203,20 +240,29 @@ public bool DrawNode( uint color = port.isMissing ? Pack(0.95f, 0.35f, 0.3f) : Pack(0.60f, 0.48f, 0.84f); draw.FilledCircle(point, 5f * zoom, color); if (port.isOptional && !port.isMissing) + { draw.FilledCircle(point, 2.75f * zoom, Pack(0.115f, 0.12f, 0.14f)); + } if (port.labelBounds is not { } labelBounds) + { continue; + } Vector2 labelMinimum = minimum + labelBounds.minimum * zoom; Vector2 labelMaximum = minimum + labelBounds.maximum * zoom; float padding = 12f * zoom; var label = FitLabel(port.label, labelMaximum.X - labelMinimum.X - padding * 2f, zoom); - float textX = port.direction == GraphPortDirection.Input ? labelMinimum.X + padding - : labelMaximum.X - padding - label.width; + float textX = port.direction == GraphPortDirection.Input + ? labelMinimum.X + padding + : labelMaximum.X - padding - label.width; draw.PushClip(labelMinimum, labelMaximum, true); try { - draw.Text(new Vector2(textX, point.Y - 8f * zoom), - CanvasDrawing.ToPackedColor(port.isOptional ? EditorPalette.textDisabled : EditorPalette.text), label.text, zoom); + draw.Text( + new Vector2(textX, point.Y - 8f * zoom), + CanvasDrawing.ToPackedColor(port.isOptional ? EditorPalette.textDisabled : EditorPalette.text), + label.text, + zoom + ); } finally { @@ -239,23 +285,33 @@ float zoom ) { float measuredWidth = CanvasDrawing.MeasureText(label).X * zoom; if (measuredWidth <= width) + { return (label, measuredWidth); + } const string ellipsis = "…"; if (CanvasDrawing.MeasureText(ellipsis).X * zoom > width) + { return (string.Empty, 0f); + } int low = 0; int high = label.Length; while (low < high) { int length = (low + high + 1) / 2; if (CanvasDrawing.MeasureText(label[..length] + ellipsis).X * zoom <= width) + { low = length; + } else + { high = length - 1; + } } // Avoid splitting a UTF-16 surrogate pair when a label contains supplementary characters. if (low > 0 && low < label.Length && char.IsHighSurrogate(label[low - 1])) + { low--; + } string text = label[..low] + ellipsis; return (text, CanvasDrawing.MeasureText(text).X * zoom); } @@ -264,7 +320,7 @@ private static bool Contains( (Vector2 minimum, Vector2 maximum) bounds, Vector2 point ) => point.X >= bounds.minimum.X && point.X <= bounds.maximum.X - && point.Y >= bounds.minimum.Y && point.Y <= bounds.maximum.Y; + && point.Y >= bounds.minimum.Y && point.Y <= bounds.maximum.Y; private static uint Pack( float red, diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs index 13c531469..33503b49d 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs @@ -3,9 +3,11 @@ using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.ImGui; + using CanvasDrawing = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Graph.ImGui; + /// /// Projects and presents an arbitrary graph viewport without owning document mutations or domain semantics. /// @@ -16,6 +18,7 @@ public readonly partial struct GraphCanvasView private readonly float m_zoom; private readonly Vector2 m_origin; private readonly Vector2 m_size; + /// /// Creates a frame-local graph presenter over navigation owned by its document. /// @@ -41,9 +44,13 @@ Vector2 size ) { ArgumentNullException.ThrowIfNull(state); if (!float.IsFinite(origin.X) || !float.IsFinite(origin.Y)) + { throw new ArgumentOutOfRangeException(nameof(origin)); + } if (!float.IsFinite(size.X) || !float.IsFinite(size.Y) || size.X < 0f || size.Y < 0f) + { throw new ArgumentOutOfRangeException(nameof(size)); + } m_pan = state.pan; m_zoom = state.zoom; m_origin = origin; @@ -56,7 +63,8 @@ Vector2 size /// /// The view was not initialized through its constructor. /// - public float zoom => m_zoom > 0f ? m_zoom : throw new InvalidOperationException("A graph canvas view requires an initialized projection."); + public float zoom + => m_zoom > 0f ? m_zoom : throw new InvalidOperationException("A graph canvas view requires an initialized projection."); /// /// Projects a graph-space location into the current screen rectangle. @@ -68,6 +76,7 @@ Vector2 size /// The corresponding screen coordinate. /// public Vector2 ToScreen(GraphPosition point) => m_origin + new Vector2(m_pan.x, m_pan.y) + new Vector2(point.x, point.y) * zoom; + /// /// Converts a screen location back into graph coordinates. /// @@ -78,6 +87,7 @@ Vector2 size /// The graph coordinate under the pointer. /// public GraphPosition ToGraph(Vector2 point) => new((point.X - m_origin.X - m_pan.x) / zoom, (point.Y - m_origin.Y - m_pan.y) / zoom); + /// /// Draws a bounded graph-space grid through the current UI drawing context. /// @@ -95,12 +105,18 @@ public void DrawGrid( float spacing = 32f ) { if (!float.IsFinite(spacing) || spacing <= 0f) + { throw new ArgumentOutOfRangeException(nameof(spacing)); + } float step = MathF.Max(MathF.Max(4f, spacing * zoom), MathF.Max(m_size.X, m_size.Y) / C_MAX_GRID_LINES_PER_AXIS); for (float x = ((m_pan.x % step) + step) % step; x < m_size.X; x += step) + { CanvasDrawing.DrawLine(m_origin + new Vector2(x, 0f), m_origin + new Vector2(x, m_size.Y), color); + } for (float y = ((m_pan.y % step) + step) % step; y < m_size.Y; y += step) + { CanvasDrawing.DrawLine(m_origin + new Vector2(0f, y), m_origin + new Vector2(m_size.X, y), color); + } } /// @@ -136,22 +152,32 @@ public void DrawConnection( ) { _ = zoom; if (!float.IsFinite(thickness) || thickness <= 0f) + { throw new ArgumentOutOfRangeException(nameof(thickness)); + } if (!float.IsFinite(output.X) || !float.IsFinite(output.Y) || !float.IsFinite(input.X) || !float.IsFinite(input.Y)) + { throw new ArgumentOutOfRangeException(nameof(output), "Connection endpoints must be finite screen coordinates."); + } if (m_size.X == 0f || m_size.Y == 0f) + { return; + } float tangent = Tangent(output, input); Vector2 first = output + new Vector2(tangent, 0f); Vector2 second = input - new Vector2(tangent, 0f); if (!float.IsFinite(first.X) || !float.IsFinite(second.X)) + { throw new ArgumentOutOfRangeException(nameof(input), "Connection controls exceed finite screen coordinates."); + } var clip = CanvasDrawing.GetClipBounds(); Vector2 minimum = Vector2.Min(Vector2.Min(output, input), Vector2.Min(first, second)) - new Vector2(thickness); Vector2 maximum = Vector2.Max(Vector2.Max(output, input), Vector2.Max(first, second)) + new Vector2(thickness); if (maximum.X < MathF.Max(m_origin.X, clip.minimum.X) || minimum.X > MathF.Min(m_origin.X + m_size.X, clip.maximum.X) - || maximum.Y < MathF.Max(m_origin.Y, clip.minimum.Y) || minimum.Y > MathF.Min(m_origin.Y + m_size.Y, clip.maximum.Y)) + || maximum.Y < MathF.Max(m_origin.Y, clip.minimum.Y) || minimum.Y > MathF.Min(m_origin.Y + m_size.Y, clip.maximum.Y) + ) { return; + } draw.PushClip(m_origin, m_origin + m_size, true); try { @@ -191,7 +217,9 @@ public static bool HitConnection( float radius = 6f ) { if (!float.IsFinite(radius) || radius < 0f) + { throw new ArgumentOutOfRangeException(nameof(radius)); + } float tangent = Tangent(output, input); Vector2 first = output + new Vector2(tangent, 0f); Vector2 second = input - new Vector2(tangent, 0f); @@ -204,7 +232,9 @@ public static bool HitConnection( Vector2 line = next - previous; float projection = Math.Clamp(Vector2.Dot(point - previous, line) / MathF.Max(0.001f, line.LengthSquared()), 0f, 1f); if (Vector2.DistanceSquared(point, previous + projection * line) <= radius * radius) + { return true; + } previous = next; } diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Properties/ScriptingApi.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Properties/ScriptingApi.cs index 0fc54eb12..5a548aaa1 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Properties/ScriptingApi.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Properties/ScriptingApi.cs @@ -1,5 +1,5 @@ -using Inno.Scripting.Api; using Inno.Editor.Graph.ImGui; +using Inno.Scripting.Api; [assembly: ScriptingApiNamespace("InnoEditor.Graph", "Inno.Editor.Graph.ImGui", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(GraphCanvasView), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Controls.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Controls.cs index c7ac2ca73..98def74f3 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Controls.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Controls.cs @@ -1,8 +1,10 @@ using System.Numerics; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Provides pointer-free controls within the active Editor UI session. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Drawing.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Drawing.cs index 0345dfa35..b2c6a6157 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Drawing.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Drawing.cs @@ -1,8 +1,10 @@ using System.Numerics; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Provides frame-bounded drawing access and copied presentation values. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs index bf8a53a6a..2dcb9f1ec 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs @@ -1,8 +1,10 @@ using System.Numerics; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Reads copied input values from the active Editor UI session. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Layout.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Layout.cs index 0143391de..35ad0dafa 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Layout.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Layout.cs @@ -1,8 +1,10 @@ using System.Numerics; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Provides scoped layout operations without exposing native context storage. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Tables.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Tables.cs index 8ecf5a21e..04f15a996 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Tables.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Tables.cs @@ -1,8 +1,10 @@ using System.Numerics; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Presents tables through the active Editor UI context. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs index 791a9be6f..67c32ca27 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported button flags choices at the Editor presentation boundary. /// @@ -30,5 +31,5 @@ public enum ImGuiButtonFlags : int /// /// InvisibleButton(): do not disable navigation/tabbing. Otherwise disabled by default. /// - EnableNav = (int)Inno.Native.ImGui.ImGuiButtonFlags.EnableNav, + EnableNav = (int)Inno.Native.ImGui.ImGuiButtonFlags.EnableNav } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs index 47cb3cc84..072b8a9c5 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported child flags choices at the Editor presentation boundary. /// @@ -46,5 +47,5 @@ public enum ImGuiChildFlags : int /// /// Share focus scope, allow keyboard/gamepad navigation to cross over parent border to this child or between sibling child windows. /// - NavFlattened = (int)Inno.Native.ImGui.ImGuiChildFlags.NavFlattened, + NavFlattened = (int)Inno.Native.ImGui.ImGuiChildFlags.NavFlattened } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs index eeee906c8..2fb8941b2 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported col choices at the Editor presentation boundary. /// @@ -257,5 +258,5 @@ public enum ImGuiCol : int /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiCol.Count, + Count = (int)Inno.Native.ImGui.ImGuiCol.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs index 6db099ef5..6c48a6ce5 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported color edit flags choices at the Editor presentation boundary. /// @@ -134,5 +135,5 @@ public enum ImGuiColorEditFlags : int /// /// Selects the input mask presentation behavior. /// - InputMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.InputMask, + InputMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.InputMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs index 535401069..865868618 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported combo flags choices at the Editor presentation boundary. /// @@ -46,5 +47,5 @@ public enum ImGuiComboFlags : int /// /// Selects the height mask presentation behavior. /// - HeightMask = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightMask, + HeightMask = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs index 67cbbf90e..f4adddfff 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported cond choices at the Editor presentation boundary. /// @@ -26,5 +27,5 @@ public enum ImGuiCond : int /// /// Set the variable if the object/window is appearing after being hidden/inactive (or the first time) /// - Appearing = (int)Inno.Native.ImGui.ImGuiCond.Appearing, + Appearing = (int)Inno.Native.ImGui.ImGuiCond.Appearing } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs index 04bcc642c..79f4ca86f 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported focused flags choices at the Editor presentation boundary. /// @@ -34,5 +35,5 @@ public enum ImGuiFocusedFlags : int /// /// Selects the root and child windows presentation behavior. /// - RootAndChildWindows = (int)Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows, + RootAndChildWindows = (int)Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs index 0a8025156..7ad713732 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported hovered flags choices at the Editor presentation boundary. /// @@ -90,5 +91,5 @@ public enum ImGuiHoveredFlags : int /// /// IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) /// - NoSharedDelay = (int)Inno.Native.ImGui.ImGuiHoveredFlags.NoSharedDelay, + NoSharedDelay = (int)Inno.Native.ImGui.ImGuiHoveredFlags.NoSharedDelay } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs index 57a99f283..bd5c2b265 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported input text flags choices at the Editor presentation boundary. /// @@ -110,5 +111,5 @@ public enum ImGuiInputTextFlags : int /// /// InputTextMultiline(): word-wrap lines that are too long. /// - WordWrap = (int)Inno.Native.ImGui.ImGuiInputTextFlags.WordWrap, + WordWrap = (int)Inno.Native.ImGui.ImGuiInputTextFlags.WordWrap } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs index 0120f2fa9..619bd27a0 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported key choices at the Editor presentation boundary. /// @@ -665,5 +666,5 @@ public enum ImGuiKey : int /// /// Identifies the ImGuiModMask presentation key or modifier. /// - ImGuiModMask = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModMask, + ImGuiModMask = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs index 5afa25489..bc0c575a4 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported mouse button choices at the Editor presentation boundary. /// @@ -21,5 +22,5 @@ public enum ImGuiMouseButton : int /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiMouseButton.Count, + Count = (int)Inno.Native.ImGui.ImGuiMouseButton.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs index 86180b833..dc05ca6b4 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported mouse cursor choices at the Editor presentation boundary. /// @@ -57,5 +58,5 @@ public enum ImGuiMouseCursor : int /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiMouseCursor.Count, + Count = (int)Inno.Native.ImGui.ImGuiMouseCursor.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs index 017a77d2a..91d52d6d3 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported popup flags choices at the Editor presentation boundary. /// @@ -58,5 +59,5 @@ public enum ImGuiPopupFlags : int /// /// Selects the invalid mask presentation behavior. /// - InvalidMask = (int)Inno.Native.ImGui.ImGuiPopupFlags.InvalidMask, + InvalidMask = (int)Inno.Native.ImGui.ImGuiPopupFlags.InvalidMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs index e8ba440f5..fd2ffdee7 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported selectable flags choices at the Editor presentation boundary. /// @@ -38,5 +39,5 @@ public enum ImGuiSelectableFlags : int /// /// Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block. /// - SelectOnNav = (int)Inno.Native.ImGui.ImGuiSelectableFlags.SelectOnNav, + SelectOnNav = (int)Inno.Native.ImGui.ImGuiSelectableFlags.SelectOnNav } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs index 6eadc7060..08715d4a0 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported slider flags choices at the Editor presentation boundary. /// @@ -50,5 +51,5 @@ public enum ImGuiSliderFlags : int /// /// Selects the invalid mask presentation behavior. /// - InvalidMask = (int)Inno.Native.ImGui.ImGuiSliderFlags.InvalidMask, + InvalidMask = (int)Inno.Native.ImGui.ImGuiSliderFlags.InvalidMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs index b61d56d6b..2b333d75a 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported style var choices at the Editor presentation boundary. /// @@ -173,5 +174,5 @@ public enum ImGuiStyleVar : int /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiStyleVar.Count, + Count = (int)Inno.Native.ImGui.ImGuiStyleVar.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs index 0664d4257..f0501d2a3 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported tab bar flags choices at the Editor presentation boundary. /// @@ -58,5 +59,5 @@ public enum ImGuiTabBarFlags : int /// /// Selects the fitting policy default presentation behavior. /// - FittingPolicyDefault = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyDefault, + FittingPolicyDefault = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyDefault } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs index 58d858b6b..d270585b0 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported tab item flags choices at the Editor presentation boundary. /// @@ -46,5 +47,5 @@ public enum ImGuiTabItemFlags : int /// /// Tab is selected when trying to close + closure is not immediately assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. /// - NoAssumedClosure = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoAssumedClosure, + NoAssumedClosure = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoAssumedClosure } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs index db6dbba57..580b5379d 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported table bg target choices at the Editor presentation boundary. /// @@ -21,5 +22,5 @@ public enum ImGuiTableBgTarget : int /// /// Set cell background color (top-most color) /// - CellBg = (int)Inno.Native.ImGui.ImGuiTableBgTarget.CellBg, + CellBg = (int)Inno.Native.ImGui.ImGuiTableBgTarget.CellBg } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs index 99b9b6ec3..b3c41f574 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported table column flags choices at the Editor presentation boundary. /// @@ -118,5 +119,5 @@ public enum ImGuiTableColumnFlags : int /// /// Selects the no direct resize presentation behavior. /// - NoDirectResize = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoDirectResize, + NoDirectResize = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoDirectResize } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs index e483ba5fa..086e9ee5c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported table flags choices at the Editor presentation boundary. /// @@ -154,5 +155,5 @@ public enum ImGuiTableFlags : int /// /// Selects the sizing mask presentation behavior. /// - SizingMask = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingMask, + SizingMask = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs index c664e0e69..b5d5d8db8 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported table row flags choices at the Editor presentation boundary. /// @@ -14,5 +15,5 @@ public enum ImGuiTableRowFlags : int /// /// Identify header row (set default background color + width of its contents accounted differently for auto column width) /// - Headers = (int)Inno.Native.ImGui.ImGuiTableRowFlags.Headers, + Headers = (int)Inno.Native.ImGui.ImGuiTableRowFlags.Headers } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs index 2179ce729..1558c82f8 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported tree node flags choices at the Editor presentation boundary. /// @@ -94,5 +95,5 @@ public enum ImGuiTreeNodeFlags : int /// /// Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). /// - DrawLinesToNodes = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.DrawLinesToNodes, + DrawLinesToNodes = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.DrawLinesToNodes } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs index 4fc22b7c6..54b4f4811 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Editor.ImGui; + /// /// Defines the supported window flags choices at the Editor presentation boundary. /// @@ -126,5 +127,5 @@ public enum ImGuiWindowFlags : int /// /// Don't use! For internal use by BeginMenu() /// - ChildMenu = (int)Inno.Native.ImGui.ImGuiWindowFlags.ChildMenu, + ChildMenu = (int)Inno.Native.ImGui.ImGuiWindowFlags.ChildMenu } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs index 8ba5a9a2a..dddf45269 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs @@ -2,9 +2,11 @@ using System.Numerics; using BGCS.Runtime; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// A pointer-free drawing borrow valid only in its original window, UI session and frame. /// @@ -13,6 +15,7 @@ public readonly unsafe struct EditorDrawList private readonly EditorUiSession m_session; private readonly int m_frame; private readonly uint m_window; + internal EditorDrawList(EditorUiSession session) { ImGuiNativeContext* context = session.RequireDrawingFrame(); @@ -42,6 +45,7 @@ public void Line( uint color, float thickness = 1f ) => ImGui.DrawNativeLine(Resolve(), start, end, color, thickness); + /// /// Adds a filled rectangular surface. /// @@ -66,7 +70,15 @@ public void FilledRectangle( uint color, float rounding = 0f, bool topCornersOnly = false - ) => ImGui.DrawNativeFilledRectangle(Resolve(), minimum, maximum, color, rounding, topCornersOnly ? (int)ImDrawFlags.RoundCornersTop : 0); + ) => ImGui.DrawNativeFilledRectangle( + Resolve(), + minimum, + maximum, + color, + rounding, + topCornersOnly ? (int)ImDrawFlags.RoundCornersTop : 0 + ); + /// /// Adds a rectangular outline. /// @@ -92,6 +104,7 @@ public void Rectangle( float rounding = 0f, float thickness = 1f ) => ImGui.DrawNativeRectangle(Resolve(), minimum, maximum, color, rounding, 0, thickness); + /// /// Adds a filled circle with backend-selected tessellation. /// @@ -139,7 +152,17 @@ public void Text( ArgumentOutOfRangeException.ThrowIfNegativeOrZero(scale); ImVec2C native = ImGui.ToNative(position); using NativeStringLease encoded = Utf8Codec.EncodeNullTerminated(text, allowsNull: false); - NativeImGui.Raw.AddText(draw, NativeImGui.Raw.GetFont(), NativeImGui.GetFontSize() * scale, &native, color, (sbyte*)encoded.pointer, null, 0f, null); + NativeImGui.Raw.AddText( + draw, + NativeImGui.Raw.GetFont(), + NativeImGui.GetFontSize() * scale, + &native, + color, + (sbyte*)encoded.pointer, + null, + 0f, + null + ); } /// @@ -167,6 +190,7 @@ public void PushClip( /// Restores the enclosing clip after a matching PushClip. /// public void PopClip() => NativeImGui.Raw.PopClipRect(Resolve()); + /// /// Begins ordered draw channels within this window. /// @@ -186,17 +210,23 @@ public void SplitChannels(int count) /// The zero-based channel. /// public void SetChannel(int index) => NativeImGui.Raw.ChannelsSetCurrent(Resolve(), index); + /// /// Merges the current split back into ordered draw commands. /// public void MergeChannels() => NativeImGui.Raw.ChannelsMerge(Resolve()); + private ImDrawList* Resolve() { if (m_session is null) + { throw new InvalidOperationException("A default drawing borrow has no owner."); + } ImGuiNativeContext* context = m_session.RequireDrawingFrame(); if (context->FrameCount != m_frame || context->CurrentWindow->ID != m_window) + { throw new InvalidOperationException("The drawing borrow belongs to a different window or frame."); + } return NativeImGui.Raw.GetWindowDrawList(); } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs index 85cc436ef..5d3c904b3 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs @@ -1,7 +1,9 @@ using System.Numerics; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Copies presentation values and creates frame-bounded drawing borrows. /// @@ -73,7 +75,9 @@ public static (float minimumX, float maximumX, float rowMinimum, float rowMaximu _ = EditorUiSession.current.RequireDrawingFrame(); var table = NativeImGui.Raw.GetCurrentTable(); if (table is null) + { throw new System.InvalidOperationException("A table row layout requires an active table."); + } return (table->OuterRect.Min.X, table->OuterRect.Max.X, table->RowPosY1, table->RowPosY2); } @@ -116,6 +120,7 @@ public static (Vector2 minimum, Vector2 maximum) GetClipBounds() /// A value that rejects use after a window, frame, context or session change. /// public static EditorDrawList GetDrawList() => new(EditorUiSession.current); + /// /// Checks the active payload's logical protocol without exposing its native buffer. /// @@ -130,7 +135,9 @@ public static bool HasDragPayload(string protocol) EditorUiSession.current.EnsureDrawing(); var payload = NativeImGui.Raw.GetDragDropPayload(); if (payload is null) + { return false; + } using var text = BGCS.Runtime.Utf8Codec.EncodeNullTerminated(protocol, allowsNull: false); return NativeImGui.Raw.IsDataType(payload, (sbyte*)text.pointer) != 0; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs index 781a6a53c..6a28adf1d 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs @@ -2,9 +2,11 @@ using System.Numerics; using BGCS.Runtime; using Inno.Native.ImGui; + using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Exposes a script-safe, pointer-free subset of Dear ImGui for custom Editor tools. /// Every call is valid only while an Editor drawing callback is active. @@ -311,11 +313,15 @@ public static bool ColorEditLinear4( ImGuiColorEditFlags flags = ImGuiColorEditFlags.None ) { if ((flags & ImGuiColorEditFlags.InputHsv) != 0) + { throw new ArgumentException("Linear RGBA editing requires RGB input storage.", nameof(flags)); + } Vector4 display = new(LinearToSrgb(value.X), LinearToSrgb(value.Y), LinearToSrgb(value.Z), value.W); Vector4 original = display; if (!ColorEdit4(label, ref display, flags | ImGuiColorEditFlags.InputRgb)) + { return false; + } value = new Vector4( display.X == original.X ? value.X : SrgbToLinear(display.X), display.Y == original.Y ? value.Y : SrgbToLinear(display.Y), @@ -1077,7 +1083,9 @@ float wrapWidth EditorUiSession.current.EnsureDrawing(); ArgumentNullException.ThrowIfNull(text); if (!float.IsFinite(wrapWidth) || wrapWidth <= 0f) + { throw new ArgumentOutOfRangeException(nameof(wrapWidth)); + } return ImGuiUtf8Buffer.MeasureText(text, wrapWidth); } @@ -1310,20 +1318,26 @@ string text ImGui.DrawNativeText(RawImGui.Raw.GetWindowDrawList(), position, color, text); } - internal static ImVec2C ToNative(Vector2 value) => new() + internal static ImVec2C ToNative(Vector2 value) + => new() { X = value.X, Y = value.Y }; - internal static ImVec4C ToNative(Vector4 value) => new() + + internal static ImVec4C ToNative(Vector4 value) + => new() { X = value.X, Y = value.Y, Z = value.Z, W = value.W }; + internal static Vector2 FromNative(ImVec2C value) => new(value.X, value.Y); + internal static Vector4 FromNative(ImVec4C value) => new(value.X, value.Y, value.Z, value.W); + internal static void DrawNativeLine( ImDrawList* drawList, Vector2 start, @@ -1446,7 +1460,9 @@ internal static bool BeginNativeWindow( bool modal ) { using NativeStringLease nativeLabel = Utf8Codec.EncodeNullTerminated(label, allowsNull: false); - return (modal ? RawImGui.Raw.BeginPopupModal((sbyte*)nativeLabel.pointer, null, (int)flags) : RawImGui.Raw.Begin((sbyte*)nativeLabel.pointer, null, (int)flags)) != 0; + return (modal + ? RawImGui.Raw.BeginPopupModal((sbyte*)nativeLabel.pointer, null, (int)flags) + : RawImGui.Raw.Begin((sbyte*)nativeLabel.pointer, null, (int)flags)) != 0; } internal static uint HashNativeId( @@ -1458,5 +1474,6 @@ internal static uint HashNativeId( } private static float LinearToSrgb(float value) => value <= 0.0031308f ? value * 12.92f : 1.055f * MathF.Pow(value, 1f / 2.4f) - 0.055f; + private static float SrgbToLinear(float value) => value <= 0.04045f ? value / 12.92f : MathF.Pow((value + 0.055f) / 1.055f, 2.4f); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs index 69a33c42f..9b2887d60 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs @@ -1,6 +1,7 @@ -using Inno.Scripting.Api; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Scripting.Api; + using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; [assembly: ScriptingApiNamespace("InnoEditor.ImGui", "Inno.Editor.ImGui", ScriptingApiScope.Editor)] diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs index b6cfab1b8..59814e8ad 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs @@ -1,17 +1,20 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Globalization; using Inno.Core.Identity; -using Inno.Editor.Interactions; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.ImGui; + /// /// Bridges managed editor drag sessions to the native ImGui payload API. /// public static class EditorDragDropRenderer { private const string C_IDENTITY_PAYLOAD_PREFIX = "INNO_ID_"; + /// /// Publishes managed drag data for the most recently submitted ImGui item. /// @@ -33,7 +36,11 @@ public static bool Source( Action? drawPreview = null ) { ArgumentNullException.ThrowIfNull(data); - return EditorUI.current.widgets.DragDropSource(GetPayloadType(data.sourceIdentity.domainId), () => interaction.BeginDrag(data).runtimeId, drawPreview); + return EditorUI.current.widgets.DragDropSource( + GetPayloadType(data.sourceIdentity.domainId), + () => interaction.BeginDrag(data).runtimeId, + drawPreview + ); } /// @@ -53,19 +60,31 @@ public static EditorDropWidgetResult Target( EditorDropPlacement placement = EditorDropPlacement.None ) { if (!interaction.TryGetActiveDragIdentity(out RuntimeIdentity activeIdentity)) + { return EditorDropWidgetResult.none; - bool delivered = EditorUI.current.widgets.DragDropTarget(GetPayloadType(activeIdentity.domainId), out int runtimeId, out bool isPreviewing, drawDefaultHighlight: false); + } + bool delivered = EditorUI.current.widgets.DragDropTarget( + GetPayloadType(activeIdentity.domainId), + out int runtimeId, + out bool isPreviewing, + drawDefaultHighlight: false + ); if (!isPreviewing && !delivered) + { return EditorDropWidgetResult.none; + } if (runtimeId <= 0) + { return EditorDropWidgetResult.none; + } var identity = new RuntimeIdentity(activeIdentity.domainId, runtimeId); EditorDropStatus status = interaction.QueryDrop(identity, placement); EditorDropResult result = delivered && status.canDrop ? interaction.Drop(identity, placement) : EditorDropResult.rejected; return new EditorDropWidgetResult(isPreviewing, status, result); } - private static string GetPayloadType(IdentityDomainId domainId) => C_IDENTITY_PAYLOAD_PREFIX + domainId.value.ToString("X8", CultureInfo.InvariantCulture); + private static string GetPayloadType(IdentityDomainId domainId) + => C_IDENTITY_PAYLOAD_PREFIX + domainId.value.ToString("X8", CultureInfo.InvariantCulture); } /// @@ -99,14 +118,17 @@ EditorDropResult result /// Gets whether a compatible native payload is hovering the target. /// public bool isPreviewing { get; } + /// /// Gets the managed drop compatibility status. /// public EditorDropStatus status { get; } + /// /// Gets the delivered drop result. /// public EditorDropResult result { get; } + /// /// Gets an inactive drop target result. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs index 73fbc687e..cf8f11468 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Numerics; - using Inno.Core.Events; using Inno.Core.Input; @@ -97,8 +96,10 @@ public uint CompleteFrame() } if (m_deliveredWindowId == 0 - || m_focused && m_deliveredWindowId == m_targetWindowId) + || m_focused && m_deliveredWindowId == m_targetWindowId + ) { return 0; + } uint formerWindowId = m_deliveredWindowId; m_deliveredWindowId = 0; @@ -127,12 +128,14 @@ public uint CompleteFrame() { ArgumentNullException.ThrowIfNull(evnt); if (evnt is MouseMovedEvent observed && observed.windowId == m_targetWindowId) + { UpdatePointerBounds(observed); + } if (evnt.isGlobalHandled) { if (m_deliveredWindowId != 0 && IsReleaseFromWindow(evnt, m_deliveredWindowId) - || IsWindowExit(evnt, m_targetWindowId)) - { + || IsWindowExit(evnt, m_targetWindowId) + ) { uint formerWindowId = m_deliveredWindowId; ReleaseCapture(); return formerWindowId != 0 ? new WindowFocusChangedEvent(formerWindowId, false) : null; @@ -140,21 +143,23 @@ public uint CompleteFrame() return null; } if (evnt is WindowFocusChangedEvent { isFocused: false } lostFocus - && (lostFocus.windowId == m_deliveredWindowId || lostFocus.windowId == m_targetWindowId)) - { + && (lostFocus.windowId == m_deliveredWindowId || lostFocus.windowId == m_targetWindowId) + ) { bool needsReset = m_deliveredWindowId != 0; ReleaseCapture(); return needsReset ? lostFocus : null; } if (evnt is WindowCloseEvent closed - && (closed.windowId == m_deliveredWindowId || closed.windowId == m_targetWindowId)) - { + && (closed.windowId == m_deliveredWindowId || closed.windowId == m_targetWindowId) + ) { bool needsReset = m_deliveredWindowId != 0; ReleaseCapture(); return needsReset ? new WindowFocusChangedEvent(closed.windowId, false) : null; } if (!m_focused || m_targetWindowId == 0) + { return null; + } Event? routed = evnt switch { @@ -167,7 +172,9 @@ public uint CompleteFrame() _ => null }; if (routed is not null) + { m_deliveredWindowId = m_targetWindowId; + } return routed; } @@ -204,21 +211,23 @@ uint windowId { Vector2 local = new(moved.x - m_origin.X, moved.y - m_origin.Y); return m_pointerInside || m_pressedButtons.Count > 0 - ? moved.WithPosition(local.X, local.Y) - : null; + ? moved.WithPosition(local.X, local.Y) + : null; } private void UpdatePointerBounds(MouseMovedEvent moved) { Vector2 local = new(moved.x - m_origin.X, moved.y - m_origin.Y); m_pointerInside = m_hovered && local.X >= 0f && local.Y >= 0f - && local.X < m_size.X && local.Y < m_size.Y; + && local.X < m_size.X && local.Y < m_size.Y; } private Event? RoutePress(MouseButtonPressedEvent pressed) { if (!m_pointerInside) + { return null; + } m_pressedButtons.Add(pressed.button); return pressed; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs index bf661b25f..3d374103a 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs @@ -1,14 +1,16 @@ -using System.Linq; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; +using System.Linq; using System.Numerics; -using Inno.Editor.Interactions; using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Renders immutable editor menu models through ImGui. /// @@ -16,18 +18,24 @@ public sealed unsafe class EditorMenuRenderer { private readonly EditorUiSession m_session; private readonly Dictionary<(string Owner, uint Popup), string> m_contextSearches = []; + internal EditorMenuRenderer(EditorUiSession session) => m_session = session; + internal void RetireOwner(string owner) { foreach (var key in m_contextSearches.Keys.Where(value => value.Owner == owner).ToArray()) + { m_contextSearches.Remove(key); + } } internal void Clear() => m_contextSearches.Clear(); + private readonly record struct MenuSection( EditorInteraction interaction, IReadOnlyList items ); + /// /// Draws a resolved right-click menu for the most recently submitted ImGui item. /// @@ -55,9 +63,13 @@ EditorInteraction interaction EditorMenuModel menu = interaction.BuildMenu(); if (menu.items.Count == 0) + { return false; + } if (!EditorUI.current.widgets.BeginContextMenu(id)) + { return false; + } try { DrawContextMenuContents(popupId, [new MenuSection(interaction, menu.items)]); @@ -102,12 +114,19 @@ EditorInteraction itemInteraction EditorMenuModel scopeMenu = scopeInteraction.BuildMenu(); EditorMenuModel itemMenu = itemInteraction.BuildMenu(); if (scopeMenu.items.Count == 0 && itemMenu.items.Count == 0) + { return false; + } if (!EditorUI.current.widgets.BeginContextMenu(id)) + { return false; + } try { - DrawContextMenuContents(popupId, [new MenuSection(scopeInteraction, scopeMenu.items), new MenuSection(itemInteraction, itemMenu.items)]); + DrawContextMenuContents( + popupId, + [new MenuSection(scopeInteraction, scopeMenu.items), new MenuSection(itemInteraction, itemMenu.items)] + ); } finally { @@ -144,9 +163,13 @@ EditorInteraction interaction EditorMenuModel menu = interaction.BuildMenu(); if (menu.items.Count == 0) + { return false; + } if (!EditorUI.current.widgets.BeginWindowContextMenu(id)) + { return false; + } try { DrawContextMenuContents(popupId, [new MenuSection(interaction, menu.items)]); @@ -163,12 +186,16 @@ private void DrawContextMenuContents( uint popupId, IReadOnlyList sections ) { - string search = NativeImGui.IsWindowAppearing() ? string.Empty : m_contextSearches.GetValueOrDefault((m_session.owner, popupId), string.Empty); + string search = NativeImGui.IsWindowAppearing() + ? string.Empty + : m_contextSearches.GetValueOrDefault((m_session.owner, popupId), string.Empty); NativeImGui.PushStyleVar((int)(ImGuiStyleVar.FramePadding), EditorUI.current.widgets.style.menuSearchFramePadding); try { if (NativeImGui.IsWindowAppearing()) + { NativeImGui.SetKeyboardFocusHere(); + } _ = EditorUI.current.widgets.SearchInput($"context-menu-{popupId}", "Search commands…", ref search, width: -1f); } finally @@ -183,13 +210,19 @@ IReadOnlyList sections foreach (MenuSection section in sections) { if (section.items.Count == 0) + { continue; + } if (!searching && drewSection) + { NativeImGui.Separator(); + } if (searching) { if (!DrawSearchItems(section.interaction, section.items, search)) + { continue; + } NativeImGui.CloseCurrentPopup(); return; } @@ -199,13 +232,17 @@ IReadOnlyList sections } } - private bool ShouldResolveItemContextMenu(string id) => NativeImGui.IsPopupOpen(id) - || NativeImGui.IsItemHovered() - && NativeImGui.IsMouseReleased((int)(Inno.Native.ImGui.ImGuiMouseButton.Right)); - private bool ShouldResolveWindowContextMenu(string id) => NativeImGui.IsPopupOpen(id) - || NativeImGui.IsWindowHovered() - && !NativeImGui.IsAnyItemHovered() - && NativeImGui.IsMouseReleased((int)(Inno.Native.ImGui.ImGuiMouseButton.Right)); + private bool ShouldResolveItemContextMenu(string id) + => NativeImGui.IsPopupOpen(id) + || NativeImGui.IsItemHovered() + && NativeImGui.IsMouseReleased((int)(Inno.Native.ImGui.ImGuiMouseButton.Right)); + + private bool ShouldResolveWindowContextMenu(string id) + => NativeImGui.IsPopupOpen(id) + || NativeImGui.IsWindowHovered() + && !NativeImGui.IsAnyItemHovered() + && NativeImGui.IsMouseReleased((int)(Inno.Native.ImGui.ImGuiMouseButton.Right)); + /// /// Draws the complete editor main menu bar for the supplied menu context. /// @@ -216,7 +253,9 @@ public void MainMenu(EditorInteraction interaction) { m_session.EnsureDrawing(); if (!NativeImGui.BeginMainMenuBar()) + { return; + } try { DrawItems(interaction, interaction.BuildMenu().items); @@ -233,7 +272,9 @@ private void DrawCenteredToolbar( IReadOnlyList items ) { if (items.Count == 0) + { return; + } ImGuiStyle* style = NativeImGui.Raw.GetStyle(); float extent = NativeImGui.GetFrameHeight(); float width = extent * items.Count + style->ItemSpacing.X * (items.Count - 1); @@ -243,7 +284,9 @@ IReadOnlyList items for (int i = 0; i < items.Count; i++) { if (i > 0) + { NativeImGui.SameLine(0f, style->ItemSpacing.X); + } DrawToolbarItem(interaction, items[i], new Vector2(extent, extent)); } } @@ -255,13 +298,17 @@ Vector2 size ) { bool disabled = !item.status.isEnabled; if (disabled) + { NativeImGui.BeginDisabled(true); + } Vector2 minimum = NativeImGui.GetCursorScreenPos(); bool pressed = NativeImGui.InvisibleButton($"##editor_toolbar_{item.actionId}", size); bool hovered = NativeImGui.IsItemHovered(); bool active = NativeImGui.IsItemActive(); if (disabled) + { NativeImGui.EndDisabled(); + } if (item.status.isChecked || hovered || active) { Vector4 background = active ? EditorPalette.accentActive : hovered ? EditorPalette.accentHovered : EditorPalette.accent; @@ -279,16 +326,21 @@ Vector2 size EditorUI.current.widgets.AddGlyphCentered(NativeImGui.GetFontSize(), GetToolbarIcon(item.icon), minimum + size * 0.5f, color); if (hovered && EditorUI.current.widgets.BeginMenuTooltip()) { - string tooltip = interaction.TryGetShortcut(item.actionId, out HotKeyGesture shortcut) ? $"{item.tooltip} ({shortcut})" : item.tooltip; + string tooltip = interaction.TryGetShortcut(item.actionId, out HotKeyGesture shortcut) + ? $"{item.tooltip} ({shortcut})" + : item.tooltip; NativeImGui.TextUnformatted(tooltip); EditorUI.current.widgets.EndMenuTooltip(); } if (pressed && item.status.isEnabled) + { interaction.Enqueue(item.actionId); + } } - private string GetToolbarIcon(EditorToolbarIcon icon) => icon switch + private string GetToolbarIcon(EditorToolbarIcon icon) + => icon switch { EditorToolbarIcon.Play => ImGuiIcon.Play, EditorToolbarIcon.Stop => ImGuiIcon.Stop, @@ -297,6 +349,7 @@ Vector2 size EditorToolbarIcon.Edit => ImGuiIcon.Pen, _ => string.Empty }; + /// /// Recursively draws resolved menu nodes into the currently open popup or menu. /// @@ -319,11 +372,15 @@ IReadOnlyList items // visible item of a popup or submenu. Enforcing that here keeps every menu surface // consistent even when a type-specific query hides the commands that preceded it. if (i > 0 && item.separatorBefore) + { NativeImGui.Separator(); + } if (item.children.Count > 0) { if (!NativeImGui.BeginMenu(item.label, item.status.isEnabled)) + { continue; + } try { DrawItems(interaction, item.children); @@ -384,7 +441,9 @@ string parentPath if (item.children.Count > 0) { if (DrawSearchItems(interaction, item.children, search, path)) + { return true; + } continue; } @@ -417,8 +476,12 @@ string parentPath private void DrawUnavailableReason(EditorActionState state) { - if (state.isEnabled || string.IsNullOrWhiteSpace(state.unavailableReason) || !NativeImGui.IsItemHovered((int)ImGuiHoveredFlags.AllowWhenDisabled)) + if (state.isEnabled + || string.IsNullOrWhiteSpace(state.unavailableReason) + || !NativeImGui.IsItemHovered((int)ImGuiHoveredFlags.AllowWhenDisabled) + ) { return; + } NativeImGui.BeginTooltip(); try { diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalHost.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalHost.cs index d3f9772a8..31470ad7b 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalHost.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalHost.cs @@ -1,14 +1,17 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using Inno.Editor.Core; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; + namespace Inno.Editor.ImGui; + internal sealed class EditorModalHost { private readonly Dictionary m_transitions = new(StringComparer.Ordinal); + internal bool Update( IReadOnlyList modals, double now @@ -16,8 +19,10 @@ double now bool newBlockingModalRequested = false; for (int i = 0; i < modals.Count; i++) { - if (modals[i].TryGetPresentation(out EditorModalExtension.Presentation candidate) && candidate.isVisible && candidate.blocksInteraction) - { + if (modals[i].TryGetPresentation(out EditorModalExtension.Presentation candidate) + && candidate.isVisible + && candidate.blocksInteraction + ) { newBlockingModalRequested = true; break; } @@ -28,14 +33,22 @@ double now { EditorModalExtension extension = modals[i]; if (!extension.TryGetPresentation(out EditorModalExtension.Presentation presentation)) + { continue; + } Transition transition = GetTransition(extension.id); if (newBlockingModalRequested && !presentation.isVisible) + { transition.HideImmediately(); + } else + { transition.Update(presentation.isVisible, now); + } if (presentation.blocksInteraction && transition.isVisible) + { blocksInteraction = true; + } } return blocksInteraction; @@ -67,10 +80,13 @@ double now } internal void Clear() => m_transitions.Clear(); + private Transition GetTransition(string id) { if (m_transitions.TryGetValue(id, out Transition? transition)) + { return transition; + } transition = new Transition(); m_transitions.Add(id, transition); return transition; @@ -99,7 +115,9 @@ double now if (!m_requested) { if (!isVisible) + { m_visibleAt = now; + } isVisible = true; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs index 23e29023f..4b590ceb5 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs @@ -1,14 +1,16 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; -using BGCS.Runtime; using System.Numerics; using System.Runtime.CompilerServices; +using BGCS.Runtime; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Renders centered editor modals consistently on the main viewport. /// @@ -65,13 +67,22 @@ EditorContext context using NativeStringLease nativeTitle = Utf8Codec.EncodeNullTerminated(popupId, allowsNull: false); ImGuiWindow* existing = NativeImGui.Raw.FindWindowByName((sbyte*)nativeTitle.pointer); if (existing != null && existing->WasActive != 0) + { initialSize = ImGui.FromNative(existing->SizeFull); + } } - float width = MathF.Floor(Math.Clamp(initialSize.X > 0f ? initialSize.X : EditorUI.current.widgets.style.modalWidth, - MathF.Max(1f, minimumSize.X), maximumSize.X)); + float width = MathF.Floor( + Math.Clamp( + initialSize.X > 0f ? initialSize.X : EditorUI.current.widgets.style.modalWidth, + MathF.Max(1f, minimumSize.X), + maximumSize.X + ) + ); float decorations = NativeImGui.GetFrameHeight(); - Vector2 available = new(MathF.Max(1f, width - padding.X * 2f), - MathF.Max(1f, (initialSize.Y > 0f ? MathF.Min(initialSize.Y, maximumSize.Y) : maximumSize.Y) - padding.Y * 2f - decorations)); + Vector2 available = new( + MathF.Max(1f, width - padding.X * 2f), + MathF.Max(1f, (initialSize.Y > 0f ? MathF.Min(initialSize.Y, maximumSize.Y) : maximumSize.Y) - padding.Y * 2f - decorations) + ); // Explicit resizable windows commit current input in Begin; measure their actual content area afterwards. bool prepareInside = presentation.canResize && initialSize.Y > 0f; Vector2? measured = null; @@ -81,7 +92,9 @@ EditorContext context return; } if (!ReferenceEquals(EditorUI.current, session)) + { throw new InvalidOperationException("Modal preparation changed the active UI session."); + } session.EnsureDrawing(); bool horizontalOverflow = false; if (presentation.allowScrolling && measured is Vector2 content) @@ -92,47 +105,58 @@ EditorContext context } float height = initialSize.Y > 0f ? initialSize.Y : measured!.Value.Y + padding.Y * 2f + decorations; if (horizontalOverflow && initialSize.Y <= 0f) + { height += style->ScrollbarSize; + } Vector2 windowSize = new(width, MathF.Ceiling(Math.Clamp(height, MathF.Max(1f, minimumSize.Y), maximumSize.Y))); Vector2 center = ImGui.FromNative(viewport->WorkPos) + workSize * 0.5f; if (presentation.blocksInteraction) + { NativeImGui.OpenPopup(popupId, (int)ImGuiPopupFlags.NoReopen); + } NativeImGui.SetNextWindowViewport(viewport->ID); ImGuiCond placementCondition = presentation.canMove || presentation.canResize ? ImGuiCond.Appearing : ImGuiCond.Always; NativeImGui.SetNextWindowPos(center, (int)placementCondition, new Vector2(0.5f)); NativeImGui.SetNextWindowSize(windowSize, (int)(presentation.canResize ? ImGuiCond.Appearing : ImGuiCond.Always)); ImGui.ConstrainNativeWindowSize(minimumSize, maximumSize, null, null); if (measured is Vector2 extent) + { NativeImGui.SetNextWindowContentSize(extent); + } NativeImGui.PushStyleVar((int)(ImGuiStyleVar.Alpha), alpha); ImGuiWindowFlags flags = ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoCollapse; if (horizontalOverflow) + { flags |= ImGuiWindowFlags.HorizontalScrollbar; + } if (!presentation.allowScrolling) + { flags |= ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse; + } if (!presentation.canMove) + { flags |= ImGuiWindowFlags.NoMove; + } if (!presentation.canResize) + { flags |= ImGuiWindowFlags.NoResize; + } bool beganWindow = false; try { - bool visible = presentation.blocksInteraction ? ImGui.BeginNativeWindow( - popupId, - flags, - modal: true - ) : ImGui.BeginNativeWindow( - popupId, - flags | ImGuiWindowFlags.NoSavedSettings, - modal: false - ); + bool visible = presentation.blocksInteraction + ? ImGui.BeginNativeWindow(popupId, flags, modal: true) + : ImGui.BeginNativeWindow(popupId, flags | ImGuiWindowFlags.NoSavedSettings, modal: false); beganWindow = !presentation.blocksInteraction || visible; if (visible) { - if (!prepareInside || modal.TryPrepare(context, presentation, Vector2.Max(Vector2.One, NativeImGui.GetContentRegionAvail()), out _)) + if (!prepareInside + || modal.TryPrepare(context, presentation, Vector2.Max(Vector2.One, NativeImGui.GetContentRegionAvail()), out _) + ) { _ = modal.Draw(context); + } } } finally @@ -140,9 +164,13 @@ EditorContext context if (beganWindow) { if (presentation.blocksInteraction) + { NativeImGui.EndPopup(); + } else + { NativeImGui.End(); + } } NativeImGui.PopStyleVar(); @@ -164,7 +192,9 @@ string title ) { string popupId = $"{title}##{id}"; if (!NativeImGui.IsPopupOpen(popupId) || !ImGui.BeginNativeWindow(popupId, ImGuiWindowFlags.None, modal: true)) + { return; + } try { NativeImGui.CloseCurrentPopup(); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs index 95581416c..f8009343a 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs @@ -2,6 +2,7 @@ using Inno.Native.ImGui; namespace Inno.Editor.ImGui; + /// /// Copies frame input facts used by presentation without exposing native input storage. /// @@ -11,34 +12,42 @@ public readonly struct EditorUiInput /// Gets whether Alt is held. /// public bool alt { get; } + /// /// Gets whether the physical Control modifier is held, independently of native shortcut conventions. /// public bool control { get; } + /// /// Gets whether Shift is held. /// public bool shift { get; } + /// /// Gets whether the physical Super modifier is held, independently of native shortcut conventions. /// public bool super { get; } + /// /// Gets whether an active control owns text input. /// public bool wantsText { get; } + /// /// Gets the current pointer movement in UI units. /// public Vector2 mouseDelta { get; } + /// /// Gets the vertical scroll movement. /// public float wheel { get; } + /// /// Gets the frame duration in seconds. /// public float deltaTime { get; } + /// /// Gets the drawable pixel scale relative to logical UI coordinates. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs index 89bed97a7..3ad147f9c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs @@ -1,11 +1,13 @@ +using System; using Inno.Core.Events; using Inno.Editor.Interactions; -using EditorControls = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; -using System; using Inno.Native.ImGui; + +using EditorControls = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Owns editor controls and transient presentation state for one host, independently from other ImGui contexts. /// @@ -13,6 +15,7 @@ public sealed unsafe class EditorUiSession : IDisposable { [ThreadStatic] private static EditorUiSession? s_current; + private readonly int m_ownerThread = Environment.CurrentManagedThreadId; private EventHub? m_lifecycleHub; private Scope? m_scope; @@ -21,6 +24,7 @@ public sealed unsafe class EditorUiSession : IDisposable private int m_styleInputFrame = -1; private bool m_disposed; private string m_owner = "root"; + /// /// Creates independent controls and style state; the presentation backend retains its native context ownership. /// @@ -36,7 +40,9 @@ public EditorUiSession() /// /// No UI drawing scope is active on the calling thread. /// - public static EditorUiSession current => s_current ?? throw new InvalidOperationException("Editor drawing requires an active UI session scope."); + public static EditorUiSession current + => s_current ?? throw new InvalidOperationException("Editor drawing requires an active UI session scope."); + /// /// Gets the controls whose transient state belongs exclusively to this session. /// @@ -47,10 +53,12 @@ public EditorUiSession() /// [Inno.Scripting.Api.ScriptingApiIgnore] public EditorMenuRenderer menus { get; } + /// /// Gets whether this session has successfully retired its presentation state. /// public bool isDisposed => m_disposed; + internal string owner => m_owner; internal bool shouldDeferStyleChanges @@ -60,7 +68,9 @@ internal bool shouldDeferStyleChanges EnsureOwner(); ObjectDisposedException.ThrowIf(m_disposed, this); if (m_nativeContext == 0) + { return false; + } ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); return context is null || (nint)context != m_nativeContext || context->WithinFrameScope != 0; } @@ -98,9 +108,13 @@ public void Dispose() { EnsureOwner(); if (m_disposed) + { return; + } if (m_scope is not null) + { throw new InvalidOperationException("The UI session still owns an active drawing scope."); + } widgets.Retire(); menus.Clear(); m_lifecycleHub?.Dispose(); @@ -113,7 +127,9 @@ internal void Connect(EditorInteractions interactions) { EnsureOwner(); if (m_lifecycleHub is not null) + { throw new InvalidOperationException("The UI session already belongs to an interaction runtime."); + } m_lifecycleHub = interactions.events.CreateHub(int.MaxValue); m_lifecycleHub.Listen(_ => widgets.CommitEdits()); } @@ -142,25 +158,33 @@ internal void PrepareStyleInput() if (context->WithinFrameScope != 0) { if (m_styleInputFrame == context->FrameCount) + { return; + } m_styleInputFrame = context->FrameCount; } else + { m_styleInputFrame = context->FrameCount + 1; + } widgets.style.CommitPending(); } internal void RequireFramePreparation() { if (RequireContext()->WithinFrameScope != 0) + { throw new InvalidOperationException("Style preparation must run before native frame creation."); + } } internal ImGuiNativeContext* RequireDrawingFrame() { ImGuiNativeContext* context = RequireContext(); if (context->WithinFrameScope == 0 || context->CurrentWindow is null) + { throw new InvalidOperationException("Drawing requires an active native frame and window."); + } return context; } @@ -173,21 +197,31 @@ internal void RequireFramePreparation() EnsureOwner(); ObjectDisposedException.ThrowIf(m_disposed, this); if (!ReferenceEquals(s_current, this)) + { throw new InvalidOperationException("Controls must be drawn within their owning UI session scope."); + } nint context = (nint)NativeImGui.Raw.GetCurrentContext(); if (context == 0) + { throw new InvalidOperationException("Editor controls require a live ImGui context."); + } if (m_nativeContext == 0) + { m_nativeContext = context; + } else if (m_nativeContext != context) + { throw new InvalidOperationException("The UI session belongs to a different ImGui context."); + } return (ImGuiNativeContext*)context; } private void EnsureOwner() { if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Editor UI sessions must be used and retired on their owner thread."); + } } private sealed class Scope( @@ -197,14 +231,19 @@ private sealed class Scope( ) : IDisposable { private bool m_disposed; + /// public void Dispose() { owner.EnsureOwner(); if (m_disposed) + { return; + } if (!ReferenceEquals(s_current, owner) || !ReferenceEquals(owner.m_scope, this)) + { throw new InvalidOperationException("UI drawing scopes must retire in reverse activation order."); + } owner.m_scope = previousScope; s_current = previous; m_disposed = true; @@ -218,14 +257,19 @@ private sealed class OwnerScope( ) : IDisposable { private bool m_disposed; + /// public void Dispose() { if (m_disposed) + { return; + } session.EnsureOwner(); if (!ReferenceEquals(session.m_ownerScope, this)) + { throw new InvalidOperationException("UI owner scopes must retire in reverse activation order."); + } session.m_owner = previous; session.m_ownerScope = previousScope; m_disposed = true; diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs index 3b3f5f53d..faf70a31f 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs @@ -1,20 +1,22 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Diagnostics; using System.Numerics; using Inno.Core.Events; using Inno.Core.Execution; -using Inno.Core.Logging; using Inno.Core.Input; -using Inno.Extensibility.Types; +using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Presents the backend-independent editor interaction runtime through ImGui. /// @@ -30,6 +32,7 @@ public sealed unsafe class ImGuiEditorRuntime : EditorRuntime private uint m_dockspaceId; private Vector2 m_dockspaceSize; private bool m_disposed; + /// /// Creates an ImGui editor runtime with stable host-owned extension services. /// @@ -73,6 +76,7 @@ IEnumerable hostServices /// Gets the active presentation-independent interaction entry point. /// public EditorInteractions interactions => m_runtime.interactions; + /// /// Gets the number of active dockable panels. /// @@ -161,7 +165,9 @@ public void Draw() double now = m_timer.Elapsed.TotalSeconds; bool blocksInteraction = m_modals.Update(modals, now); if (blocksInteraction) + { NativeImGui.BeginDisabled(true); + } try { // The main menu must reserve the viewport work area before the dockspace snapshots it. @@ -174,7 +180,9 @@ public void Draw() finally { if (blocksInteraction) + { NativeImGui.EndDisabled(); + } } m_ui.widgets.CompleteEditingFrame(); @@ -196,13 +204,18 @@ private void DrawDockSpace() m_dockspaceId = ImGui.HashNativeId("DockSpace", hostId); ImGuiDockNode* loaded = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceId); if (loaded != null) + { ResizeDockSplits(loaded, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); + } } - else if (m_dockspaceSize != Vector2.Zero && (MathF.Abs(size.X - m_dockspaceSize.X) >= 0.5f || MathF.Abs(size.Y - m_dockspaceSize.Y) >= 0.5f)) - { + else if (m_dockspaceSize != Vector2.Zero + && (MathF.Abs(size.X - m_dockspaceSize.X) >= 0.5f || MathF.Abs(size.Y - m_dockspaceSize.Y) >= 0.5f) + ) { ImGuiDockNode* root = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceId); if (root != null) + { ResizeDockSplits(root, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); + } } NativeImGui.PushStyleColor((int)(ImGuiCol.ResizeGripHovered), EditorPalette.accentHovered); @@ -211,7 +224,9 @@ private void DrawDockSpace() { uint submittedId = NativeImGui.Raw.DockSpaceOverViewport(0, null, 0, null); if (submittedId != m_dockspaceId) + { throw new InvalidOperationException("The ImGui viewport dockspace identity changed before layout could be resized."); + } } finally { @@ -222,7 +237,9 @@ private void DrawDockSpace() { ImGuiDockNode* root = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceId); if (root != null) + { ResizeDockSplits(root, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); + } } m_dockspaceSize = size; @@ -237,20 +254,30 @@ Vector2 minimumWindowSize ImGuiDockNode* first = node->ChildNodes[0]; ImGuiDockNode* second = node->ChildNodes[1]; if (first == null || second == null || node->SplitAxis is not (ImGuiAxis.X or ImGuiAxis.Y)) + { return; + } bool horizontal = node->SplitAxis == ImGuiAxis.X; float firstReference = horizontal ? first->Size.X : first->Size.Y; float secondReference = horizontal ? second->Size.X : second->Size.Y; float previousAvailable = (horizontal ? node->Size.X : node->Size.Y) - separator; - if (firstReference <= 0f || secondReference <= 0f || MathF.Abs(firstReference + secondReference - previousAvailable) > MathF.Max(1f, separator)) - { + if (firstReference <= 0f + || secondReference <= 0f + || MathF.Abs(firstReference + secondReference - previousAvailable) > MathF.Max(1f, separator) + ) { firstReference = horizontal ? first->SizeRef.X : first->SizeRef.Y; secondReference = horizontal ? second->SizeRef.X : second->SizeRef.Y; } float available = (horizontal ? size.X : size.Y) - separator; - if (!float.IsFinite(firstReference) || !float.IsFinite(secondReference) || firstReference <= 0f || secondReference <= 0f || available <= 1f) + if (!float.IsFinite(firstReference) + || !float.IsFinite(secondReference) + || firstReference <= 0f + || secondReference <= 0f + || available <= 1f + ) { return; + } float minimum = MathF.Min(available * 0.5f, horizontal ? minimumWindowSize.X : minimumWindowSize.Y); float firstExtent = Math.Clamp(available * firstReference / (firstReference + secondReference), minimum, available - minimum); Vector2 firstSize = size; @@ -283,12 +310,16 @@ public void HandleKeyPressed(KeyPressedEvent keyEvent) using IDisposable uiScope = m_ui.Enter(); ArgumentNullException.ThrowIfNull(keyEvent); if (m_modals.Update(m_runtime.modals, m_timer.Elapsed.TotalSeconds)) + { return; + } // Text widgets own editing keys, including Backspace and clipboard/history gestures. // Explicit document save remains available without first leaving an input field. HotKeyGesture save = HotKeyGesture.Primary(KeyCode.S, context.keyboard); if (NativeImGui.Raw.GetIO()->WantTextInput != 0 && (keyEvent.key != save.key || keyEvent.modifiers != save.modifiers)) + { return; + } m_ui.widgets.CommitEdits(); m_runtime.HandleKeyPressed(keyEvent); } @@ -302,7 +333,9 @@ public void HandleKeyPressed(KeyPressedEvent keyEvent) public override void Dispose() { if (m_disposed) + { return; + } m_modals.Clear(); try { @@ -338,22 +371,32 @@ private void DrawPanels(IReadOnlyList panels) if (!extension.isOpen) { if (m_openOwners.Remove(extension.id)) + { m_ui.RetireOwner(extension.id); + } continue; } m_openOwners.Add(extension.id); using IDisposable ownerScope = m_ui.EnterOwner(extension.id); if (!extension.TryGetWindowPresentation(out bool useWindowPadding, out bool allowScrolling, out Vector2 initialSize)) + { continue; + } bool isOpen = extension.isOpen; if (initialSize.X > 0 && initialSize.Y > 0) + { NativeImGui.SetNextWindowSize(initialSize, (int)(ImGuiCond.FirstUseEver)); + } ImGuiWindowFlags flags = ImGuiWindowFlags.NoCollapse; if (!allowScrolling) + { flags |= ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse; + } if (extension.TakeFocusRequest()) + { NativeImGui.SetNextWindowFocus(); + } EditorUI.current.widgets.PanelWindow(extension.title, ref isOpen, () => { if (extension.Draw(context) && NativeImGui.IsWindowFocused((int)(Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows))) @@ -366,8 +409,12 @@ private void DrawPanels(IReadOnlyList panels) m_retiredOwners.Clear(); foreach (string owner in m_openOwners) + { if (!m_currentOwners.Contains(owner)) + { m_retiredOwners.Add(owner); + } + } foreach (string owner in m_retiredOwners) { m_ui.RetireOwner(owner); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs index 5dfe8ceca..4d303eb82 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs @@ -1,6 +1,5 @@ using System; using System.Numerics; - using Inno.Native.ImGui; namespace Inno.Editor.ImGui; @@ -447,7 +446,8 @@ float amount from.X + (to.X - from.X) * value, from.Y + (to.Y - from.Y) * value, from.Z + (to.Z - from.Z) * value, - from.W + (to.W - from.W) * value); + from.W + (to.W - from.W) * value + ); } internal static void Apply(ImGuiStyle* style) @@ -523,6 +523,5 @@ internal static void Apply(ImGuiStyle* style) public static Vector4 WithOpacity( Vector4 color, float opacity - ) - => new(color.X, color.Y, color.Z, Math.Clamp(opacity, opacityNone, opacityOpaque)); + ) => new(color.X, color.Y, color.Z, Math.Clamp(opacity, opacityNone, opacityOpaque)); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs index 21146dd06..96e8453be 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs @@ -37,7 +37,7 @@ public sealed class EditorStyleMetrics /// /// Creates independent metrics whose changes apply immediately without a native context. /// - public EditorStyleMetrics() { } + public EditorStyleMetrics() {} internal EditorStyleMetrics(EditorUiSession owner) { @@ -81,7 +81,9 @@ public bool SetCompactMode(bool value) bool changed = m_requestedCompactMode != value; m_requestedCompactMode = value; if (!defer) + { CommitPending(); + } return changed; } @@ -106,13 +108,17 @@ public bool SetCompactMode(bool value) public bool SetZoom(float value) { if (!float.IsFinite(value)) + { throw new ArgumentOutOfRangeException(nameof(value), value, "UI zoom must be finite."); + } bool defer = ShouldDeferChanges(); float clamped = Math.Clamp(value, C_MIN_ZOOM, C_MAX_ZOOM); bool changed = MathF.Abs(m_requestedZoom - clamped) >= 0.0001f; m_requestedZoom = clamped; if (!defer) + { CommitPending(); + } return changed; } @@ -505,9 +511,13 @@ internal void CommitPending() private bool ShouldDeferChanges() { if (m_owner is null) + { return false; + } if (!m_owner.TryGetTarget(out EditorUiSession? owner)) + { throw new ObjectDisposedException(nameof(EditorUiSession)); + } return owner.shouldDeferStyleChanges; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs index f26d83e9c..7e3796397 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs @@ -2,6 +2,7 @@ using Inno.Native.ImGui; namespace Inno.Editor.ImGui; + /// /// Copies the presentation metrics needed by custom layouts without retaining native style memory. /// @@ -11,30 +12,37 @@ public readonly struct EditorUiLayout /// Gets spacing between neighboring controls. /// public Vector2 itemSpacing { get; } + /// /// Gets the current window inset. /// public Vector2 windowPadding { get; } + /// /// Gets table cell padding. /// public Vector2 cellPadding { get; } + /// /// Gets spacing between parts of a compound control. /// public Vector2 itemInnerSpacing { get; } + /// /// Gets padding inside a control. /// public Vector2 framePadding { get; } + /// /// Gets dock splitter thickness. /// public float dockingSeparatorSize { get; } + /// /// Gets scrollbar width. /// public float scrollbarSize { get; } + /// /// Gets control corner radius. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs index 511dc310f..541fd8426 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs @@ -3,6 +3,7 @@ using System.Reflection; namespace Inno.Editor.ImGui; + /// /// Describes the host's complete standard glyph vocabulary as immutable presentation values. /// @@ -11,5 +12,12 @@ public static class EditorIconCatalog /// /// Gets all named glyphs supplied by the installed UI font, in deterministic name order. /// - public static IReadOnlyList<(string Name, string Glyph)> standard { get; } = System.Array.AsReadOnly(typeof(Inno.Adapter.Presentation.ImGui.ImGuiIcon).GetFields(BindingFlags.Public | BindingFlags.Static).Where(static field => field.IsLiteral && field.FieldType == typeof(string)).Select(static field => (field.Name, (string)field.GetRawConstantValue()!)).OrderBy(static value => value.Name, System.StringComparer.Ordinal).ToArray()); + public static IReadOnlyList<(string Name, string Glyph)> standard { get; } = System.Array.AsReadOnly( + typeof(Inno.Adapter.Presentation.ImGui.ImGuiIcon) + .GetFields(BindingFlags.Public | BindingFlags.Static) + .Where(static field => field.IsLiteral && field.FieldType == typeof(string)) + .Select(static field => (field.Name, (string)field.GetRawConstantValue()!)) + .OrderBy(static value => value.Name, System.StringComparer.Ordinal) + .ToArray() + ); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs index f65210df6..ee4dc1a37 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs @@ -1,9 +1,11 @@ using System; -using NativeImGui = Inno.Native.ImGui.ImGui; + using HostFont = Inno.Adapter.Presentation.ImGui.ImGuiFont; using HostStyle = Inno.Adapter.Presentation.ImGui.ImGuiFontStyle; +using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + /// /// Chooses composable font emphasis while leaving actual font ownership with the presentation host. /// @@ -71,6 +73,7 @@ public static ImGuiFontScope PushStyle(ImGuiFontStyle style) private Inno.Adapter.Presentation.ImGui.ImGuiFontScope m_scope; private readonly int m_frame; private readonly int m_depth; + internal ImGuiFontScope( EditorUiSession session, Inno.Adapter.Presentation.ImGui.ImGuiFontScope scope, @@ -92,10 +95,14 @@ int depth public void Dispose() { if (m_session is null) + { return; + } m_session.EnsureDrawing(); if (NativeImGui.GetFrameCount() != m_frame || NativeImGui.Raw.GetCurrentContext()->FontStack.Size != m_depth) + { throw new InvalidOperationException("Font scopes must retire in their original frame and reverse stack order."); + } m_scope.Dispose(); m_session = null; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiIcon.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiIcon.cs index 17f59b64d..f4455814a 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiIcon.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiIcon.cs @@ -1,6 +1,7 @@ using BackendIcon = Inno.Adapter.Presentation.ImGui.ImGuiIcon; namespace Inno.Editor.ImGui; + /// /// Provides the standard Editor glyph vocabulary; extension controls may also supply their own glyph text. /// @@ -15,170 +16,212 @@ public static class ImGuiIcon /// Gets the angle left glyph used by standard Editor controls. /// public const string AngleLeft = BackendIcon.AngleLeft; + /// /// Gets the angle right glyph used by standard Editor controls. /// public const string AngleRight = BackendIcon.AngleRight; + /// /// Gets the arrow rotate left glyph used by standard Editor controls. /// public const string ArrowRotateLeft = BackendIcon.ArrowRotateLeft; + /// /// Gets the arrows up down left right glyph used by standard Editor controls. /// public const string ArrowsUpDownLeftRight = BackendIcon.ArrowsUpDownLeftRight; + /// /// Gets the bug glyph used by standard Editor controls. /// public const string Bug = BackendIcon.Bug; + /// /// Gets the camera glyph used by standard Editor controls. /// public const string Camera = BackendIcon.Camera; + /// /// Gets the circle info glyph used by standard Editor controls. /// public const string CircleInfo = BackendIcon.CircleInfo; + /// /// Gets the circle question glyph used by standard Editor controls. /// public const string CircleQuestion = BackendIcon.CircleQuestion; + /// /// Gets the circle xmark glyph used by standard Editor controls. /// public const string CircleXmark = BackendIcon.CircleXmark; + /// /// Gets the cube glyph used by standard Editor controls. /// public const string Cube = BackendIcon.Cube; + /// /// Gets the cubes glyph used by standard Editor controls. /// public const string Cubes = BackendIcon.Cubes; + /// /// Gets the dice d6 glyph used by standard Editor controls. /// public const string DiceD6 = BackendIcon.DiceD6; + /// /// Gets the eye glyph used by standard Editor controls. /// public const string Eye = BackendIcon.Eye; + /// /// Gets the eye slash glyph used by standard Editor controls. /// public const string EyeSlash = BackendIcon.EyeSlash; + /// /// Gets the file glyph used by standard Editor controls. /// public const string File = BackendIcon.File; + /// /// Gets the file code glyph used by standard Editor controls. /// public const string FileCode = BackendIcon.FileCode; + /// /// Gets the file lines glyph used by standard Editor controls. /// public const string FileLines = BackendIcon.FileLines; + /// /// Gets the folder glyph used by standard Editor controls. /// public const string Folder = BackendIcon.Folder; + /// /// Gets the forward step glyph used by standard Editor controls. /// public const string ForwardStep = BackendIcon.ForwardStep; + /// /// Gets the gears glyph used by standard Editor controls. /// public const string Gears = BackendIcon.Gears; + /// /// Gets the globe glyph used by standard Editor controls. /// public const string Globe = BackendIcon.Globe; + /// /// Gets the grip vertical glyph used by standard Editor controls. /// public const string GripVertical = BackendIcon.GripVertical; + /// /// Gets the layer group glyph used by standard Editor controls. /// public const string LayerGroup = BackendIcon.LayerGroup; + /// /// Gets the lightbulb glyph used by standard Editor controls. /// public const string Lightbulb = BackendIcon.Lightbulb; + /// /// Gets the lock glyph used by standard Editor controls. /// public const string Lock = BackendIcon.Lock; + /// /// Gets the lock open glyph used by standard Editor controls. /// public const string LockOpen = BackendIcon.LockOpen; + /// /// Gets the magnifying glass glyph used by standard Editor controls. /// public const string MagnifyingGlass = BackendIcon.MagnifyingGlass; + /// /// Gets the palette glyph used by standard Editor controls. /// public const string Palette = BackendIcon.Palette; + /// /// Gets the pause glyph used by standard Editor controls. /// public const string Pause = BackendIcon.Pause; + /// /// Gets the pen glyph used by standard Editor controls. /// public const string Pen = BackendIcon.Pen; + /// /// Gets the play glyph used by standard Editor controls. /// public const string Play = BackendIcon.Play; + /// /// Gets the plus glyph used by standard Editor controls. /// public const string Plus = BackendIcon.Plus; + /// /// Gets the rotate glyph used by standard Editor controls. /// public const string Rotate = BackendIcon.Rotate; + /// /// Gets the rupee sign glyph used by standard Editor controls. /// public const string RupeeSign = BackendIcon.RupeeSign; + /// /// Gets the rupiah sign glyph used by standard Editor controls. /// public const string RupiahSign = BackendIcon.RupiahSign; + /// /// Gets the shader glyph used by standard Editor controls. /// public const string Shader = BackendIcon.Shader; + /// /// Gets the skull crossbones glyph used by standard Editor controls. /// public const string SkullCrossbones = BackendIcon.SkullCrossbones; + /// /// Gets the stop glyph used by standard Editor controls. /// public const string Stop = BackendIcon.Stop; + /// /// Gets the triangle exclamation glyph used by standard Editor controls. /// public const string TriangleExclamation = BackendIcon.TriangleExclamation; + /// /// Gets the up down left right glyph used by standard Editor controls. /// public const string UpDownLeftRight = BackendIcon.UpDownLeftRight; + /// /// Gets the up right and down left from center glyph used by standard Editor controls. /// public const string UpRightAndDownLeftFromCenter = BackendIcon.UpRightAndDownLeftFromCenter; + /// /// Gets the vector square glyph used by standard Editor controls. /// public const string VectorSquare = BackendIcon.VectorSquare; + /// /// Gets the xmark glyph used by standard Editor controls. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiUtf8Buffer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiUtf8Buffer.cs index a51621f2f..131ca30ec 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiUtf8Buffer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiUtf8Buffer.cs @@ -1,14 +1,16 @@ using System; +using System.Buffers; using System.Numerics; using System.Runtime.CompilerServices; using System.Text; -using System.Buffers; using System.Text.Unicode; using BGCS.Runtime; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; + internal static unsafe class ImGuiUtf8Buffer { private static readonly UTF8Encoding S_TEXT_ENCODING = new(false, true); @@ -29,7 +31,9 @@ bool measure ) { ArgumentNullException.ThrowIfNull(text); if (text.AsSpan().Contains('\0')) + { throw new ArgumentException("Literal native text cannot contain zero code units.", nameof(text)); + } int length = checked(S_TEXT_ENCODING.GetByteCount(text) + 1); byte[]? rented = length > 1024 ? ArrayPool.Shared.Rent(length) : null; Span buffer = rented is null ? stackalloc byte[length] : rented.AsSpan(0, length); @@ -41,16 +45,22 @@ bool measure { ImVec2C size = default; if (measure) + { NativeImGui.Raw.CalcTextSize((sbyte*)value, (sbyte*)value + count, 0, wrapWidth, &size); + } else + { NativeImGui.Raw.TextUnformatted((sbyte*)value, (sbyte*)value + count); + } return new Vector2(size.X, size.Y); } } finally { if (rented is not null) + { ArrayPool.Shared.Return(rented, clearArray: true); + } } } @@ -63,10 +73,19 @@ ImGuiInputTextFlags flags ) { ArgumentException.ThrowIfNullOrWhiteSpace(label); if (capacity is 0 or > int.MaxValue) + { throw new ArgumentOutOfRangeException(nameof(capacity)); - const ImGuiInputTextFlags callbacks = ImGuiInputTextFlags.CallbackCompletion | ImGuiInputTextFlags.CallbackHistory | ImGuiInputTextFlags.CallbackAlways | ImGuiInputTextFlags.CallbackCharFilter | ImGuiInputTextFlags.CallbackResize | ImGuiInputTextFlags.CallbackEdit; + } + const ImGuiInputTextFlags callbacks = ImGuiInputTextFlags.CallbackCompletion + | ImGuiInputTextFlags.CallbackHistory + | ImGuiInputTextFlags.CallbackAlways + | ImGuiInputTextFlags.CallbackCharFilter + | ImGuiInputTextFlags.CallbackResize + | ImGuiInputTextFlags.CallbackEdit; if ((flags & callbacks) != 0) + { throw new ArgumentException("Managed text controls do not accept native callback flags.", nameof(flags)); + } int length = (int)capacity; byte[]? rented = length > 1024 ? ArrayPool.Shared.Rent(length) : null; Span buffer = rented is null ? stackalloc byte[length] : rented.AsSpan(0, length); @@ -79,22 +98,24 @@ ImGuiInputTextFlags flags using NativeStringLease nativeHint = Utf8Codec.EncodeNullTerminated(hint, allowsNull: true); fixed (byte* nativeBuffer = buffer) { - changed = hint is null ? NativeImGui.Raw.InputText( - (sbyte*)nativeLabel.pointer, - (sbyte*)nativeBuffer, - (uint)capacity, - (int)flags, - null, - null - ) != 0 : NativeImGui.Raw.InputTextWithHint( - (sbyte*)nativeLabel.pointer, - (sbyte*)nativeHint.pointer, - (sbyte*)nativeBuffer, - (uint)capacity, - (int)flags, - null, - null - ) != 0; + changed = hint is null + ? NativeImGui.Raw.InputText( + (sbyte*)nativeLabel.pointer, + (sbyte*)nativeBuffer, + (uint)capacity, + (int)flags, + null, + null + ) != 0 + : NativeImGui.Raw.InputTextWithHint( + (sbyte*)nativeLabel.pointer, + (sbyte*)nativeHint.pointer, + (sbyte*)nativeBuffer, + (uint)capacity, + (int)flags, + null, + null + ) != 0; } if (changed) @@ -108,7 +129,9 @@ ImGuiInputTextFlags flags finally { if (rented is not null) + { ArrayPool.Shared.Return(rented, clearArray: true); + } } } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs index d99726228..2ff00ca7c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs @@ -1,9 +1,11 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -54,12 +56,18 @@ public bool CollapsingCard( ArgumentNullException.ThrowIfNull(title); if (trailingControlWidth < 0f) { - throw new ArgumentOutOfRangeException(nameof(trailingControlWidth), trailingControlWidth, "Trailing control width cannot be negative."); + throw new ArgumentOutOfRangeException( + nameof(trailingControlWidth), + trailingControlWidth, + "Trailing control width cannot be negative." + ); } ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags.SpanAvailWidth | ImGuiTreeNodeFlags.AllowOverlap | ImGuiTreeNodeFlags.OpenOnArrow; if (defaultOpen) + { flags |= ImGuiTreeNodeFlags.DefaultOpen; + } NativeImGui.PushStyleColor((int)(ImGuiCol.Header), EditorPalette.cardHeader); NativeImGui.PushStyleColor((int)(ImGuiCol.HeaderHovered), EditorPalette.cardHeader); NativeImGui.PushStyleColor((int)(ImGuiCol.HeaderActive), EditorPalette.cardHeader); @@ -112,10 +120,14 @@ public bool CollapsingCard( float contentX = itemHeaderMin.X + NativeImGui.GetTreeNodeToLabelSpacing(); DrawDisclosureIndicator(new Vector2(itemHeaderMin.X, headerMin.Y), new Vector2(contentX, headerMax.Y), open, dimmed); float contentY = headerMin.Y + MathF.Max(0f, (headerMax.Y - headerMin.Y - NativeImGui.GetFrameHeight()) * 0.5f); - float trailingWidth = drawTrailingControl is null ? 0f : trailingControlWidth > 0f ? trailingControlWidth : NativeImGui.GetFrameHeight(); + float trailingWidth = drawTrailingControl is null + ? 0f + : trailingControlWidth > 0f ? trailingControlWidth : NativeImGui.GetFrameHeight(); float titleRight = headerMax.X - trailingWidth; if (drawTrailingControl is not null) + { titleRight -= style.headerControlSpacing; + } NativeImGui.SetCursorScreenPos(new Vector2(contentX, contentY)); bool dimmedColorPushed = false; bool groupStarted = false; @@ -161,9 +173,13 @@ public bool CollapsingCard( finally { if (groupStarted) + { NativeImGui.EndGroup(); + } if (dimmedColorPushed) + { NativeImGui.PopStyleColor(); + } NativeImGui.SetCursorScreenPos(contentCursor); } @@ -172,7 +188,9 @@ public bool CollapsingCard( catch { if (open) + { NativeImGui.TreePop(); + } throw; } } @@ -253,7 +271,12 @@ public void CardBody( NativeImGui.PushStyleVar((int)(ImGuiStyleVar.FramePadding), style.cardBodyPadding); ImGuiChildFlags childFlags = ImGuiChildFlags.FrameStyle | ImGuiChildFlags.AutoResizeY; ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoSavedSettings; - bool visible = NativeImGui.BeginChild($"##card_body_{id}", new Vector2(MathF.Max(1f, cardRight - cardLeft), 0f), (int)(childFlags), (int)(windowFlags)); + bool visible = NativeImGui.BeginChild( + $"##card_body_{id}", + new Vector2(MathF.Max(1f, cardRight - cardLeft), 0f), + (int)(childFlags), + (int)(windowFlags) + ); bool disabled = false; try { @@ -264,12 +287,16 @@ public void CardBody( } if (visible) + { drawContent(); + } } finally { if (disabled) + { NativeImGui.EndDisabled(); + } NativeImGui.EndChild(); float nextY = NativeImGui.GetCursorScreenPos().Y; NativeImGui.PopStyleVar(3); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs index a4d40f645..48efe9ebc 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs @@ -1,5 +1,6 @@ using System; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; @@ -49,26 +50,44 @@ public void ClippedRows( m_session.EnsureDrawing(); ArgumentNullException.ThrowIfNull(drawRange); if (itemCount < 0) + { throw new ArgumentOutOfRangeException(nameof(itemCount)); + } if (!float.IsFinite(itemHeight) || (itemHeight <= 0f && itemHeight != -1f)) + { throw new ArgumentOutOfRangeException(nameof(itemHeight)); + } foreach (int row in preservedRows) + { if (row < 0 || row >= itemCount) + { throw new ArgumentOutOfRangeException(nameof(preservedRows)); + } + } if (NativeImGui.Raw.GetCurrentContext()->WithinFrameScope == 0) + { throw new InvalidOperationException("Row clipping requires an active native frame."); + } if (itemCount == 0) + { return; + } ImGuiListClipper* clipper = NativeImGui.Raw.ImGuiListClipper(); if (clipper == null) + { throw new OutOfMemoryException("The native row clipper could not be allocated."); + } try { NativeImGui.Raw.Begin(clipper, itemCount, itemHeight); foreach (int row in preservedRows) + { NativeImGui.Raw.IncludeItemByIndex(clipper, row); + } while (NativeImGui.Raw.Step(clipper) != 0) + { drawRange(state, clipper->DisplayStart, clipper->DisplayEnd); + } } finally { diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs index d29200af9..62ee3a9fe 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs @@ -3,9 +3,11 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -13,6 +15,7 @@ public sealed unsafe partial class ImGuiWidget { private const float C_TOOLTIP_MINIMUM_WIDTH = 300f; private const float C_TOOLTIP_WRAP_WIDTH = 440f; + /// /// Begins an explicitly opened popup using the editor context-menu presentation contract. /// The popup stays in its parent viewport, sizes itself to submitted content, and scrolls when @@ -36,7 +39,9 @@ public bool BeginMenuPopup(string id) NativeImGui.SetNextWindowViewport(NativeImGui.Raw.GetWindowViewport()->ID); ImGuiWindowFlags flags = ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoSavedSettings; if (NativeImGui.BeginPopup(id, (int)(flags))) + { return true; + } PopContextMenuStyle(); return false; } @@ -64,7 +69,9 @@ public bool BeginMenuTooltip() PushContextMenuStyle(); NativeImGui.SetNextWindowViewport(NativeImGui.Raw.GetWindowViewport()->ID); if (NativeImGui.BeginTooltip()) + { return true; + } PopContextMenuStyle(); return false; } @@ -106,7 +113,9 @@ public void DrawTooltip(string? text) { m_session.EnsureDrawing(); if (string.IsNullOrWhiteSpace(text)) + { return; + } ImGuiViewport* viewport = NativeImGui.Raw.GetWindowViewport(); Vector2 margin = new(6f * style.zoom); Vector2 available = Vector2.Max(Vector2.One, ImGui.FromNative(viewport->WorkSize) - margin * 2f); @@ -114,7 +123,10 @@ public void DrawTooltip(string? text) float outerWidth = MathF.Min(C_TOOLTIP_WRAP_WIDTH * style.zoom, available.X); float innerWidth = MathF.Max(1f, outerWidth - padding.X * 2f - style.menuBorderSize * 2f); Vector2 textSize = NativeImGui.CalcTextSize(text, false, innerWidth); - outerWidth = MathF.Min(outerWidth, MathF.Max(MathF.Min(C_TOOLTIP_MINIMUM_WIDTH * style.zoom, available.X), textSize.X + padding.X * 2f + style.menuBorderSize * 2f)); + outerWidth = MathF.Min( + outerWidth, + MathF.Max(MathF.Min(C_TOOLTIP_MINIMUM_WIDTH * style.zoom, available.X), textSize.X + padding.X * 2f + style.menuBorderSize * 2f) + ); innerWidth = MathF.Max(1f, outerWidth - padding.X * 2f - style.menuBorderSize * 2f); textSize = NativeImGui.CalcTextSize(text, false, innerWidth); Vector2 size = new(outerWidth, MathF.Min(available.Y, textSize.Y + padding.Y * 2f + style.menuBorderSize * 2f)); @@ -123,14 +135,20 @@ public void DrawTooltip(string? text) Vector2 mouse = NativeImGui.GetMousePos(); Vector2 position = mouse + new Vector2(16f, 20f) * style.zoom; if (position.X + size.X > workMax.X) + { position.X = mouse.X - size.X - 12f * style.zoom; + } if (position.Y + size.Y > workMax.Y) + { position.Y = mouse.Y - size.Y - 12f * style.zoom; + } position = Vector2.Clamp(position, workMin, Vector2.Max(workMin, workMax - size)); NativeImGui.SetNextWindowPos(position); NativeImGui.SetNextWindowSize(size); if (!BeginMenuTooltip()) + { return; + } try { NativeImGui.PushTextWrapPos(NativeImGui.GetCursorPosX() + MathF.Max(1f, NativeImGui.GetContentRegionAvail().X)); @@ -166,7 +184,9 @@ public bool BeginContextMenu(string id) NativeImGui.SetNextWindowViewport(NativeImGui.Raw.GetWindowViewport()->ID); ConstrainContextMenu(); if (NativeImGui.BeginPopupContextItem(id, (int)(ImGuiPopupFlags.MouseButtonRight))) + { return true; + } PopContextMenuStyle(); return false; } @@ -206,6 +226,7 @@ public void EndContextMenu() } private bool IsPopupBlockingInteraction() => ImGui.IsAnyPopupOpen(); + private void ConstrainContextMenu() { Vector2 workSize = ImGui.FromNative(NativeImGui.Raw.GetWindowViewport()->WorkSize); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs index b04c223a1..323565312 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs @@ -1,9 +1,11 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -26,7 +28,10 @@ public Vector2 GetLabelChipSize(string label) m_session.EnsureDrawing(); ArgumentNullException.ThrowIfNull(label); Vector2 textSize = NativeImGui.CalcTextSize(label); - return new Vector2(textSize.X + style.labelChipPadding.X * 2f, MathF.Max(NativeImGui.GetFrameHeight(), textSize.Y + style.labelChipPadding.Y * 2f)); + return new Vector2( + textSize.X + style.labelChipPadding.X * 2f, + MathF.Max(NativeImGui.GetFrameHeight(), textSize.Y + style.labelChipPadding.Y * 2f) + ); } /// @@ -51,7 +56,14 @@ Vector4 background Vector2 minimum = NativeImGui.GetCursorScreenPos(); Vector2 textSize = NativeImGui.CalcTextSize(label); ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); - ImGui.DrawNativeFilledRectangle(drawList, minimum, minimum + size, NativeImGui.ColorConvertFloat4ToU32(background), style.labelChipRounding, 0); + ImGui.DrawNativeFilledRectangle( + drawList, + minimum, + minimum + size, + NativeImGui.ColorConvertFloat4ToU32(background), + style.labelChipRounding, + 0 + ); ImGui.DrawNativeText(drawList, minimum + (size - textSize) * 0.5f, NativeImGui.GetColorU32((int)(ImGuiCol.Text)), label); NativeImGui.Dummy(size); } @@ -106,8 +118,23 @@ public void TypeBadge( background.W = EditorPalette.opacityOpaque; Vector4 outline = accent; outline.W = EditorPalette.opacityStrong; - ImGui.DrawNativeFilledRectangle(draw, minimum, minimum + size, NativeImGui.ColorConvertFloat4ToU32(background), style.typeBadgeRounding, 0); - ImGui.DrawNativeRectangle(draw, minimum, minimum + size, NativeImGui.ColorConvertFloat4ToU32(outline), style.typeBadgeRounding, (int)(ImDrawFlags.None), style.borderSize); + ImGui.DrawNativeFilledRectangle( + draw, + minimum, + minimum + size, + NativeImGui.ColorConvertFloat4ToU32(background), + style.typeBadgeRounding, + 0 + ); + ImGui.DrawNativeRectangle( + draw, + minimum, + minimum + size, + NativeImGui.ColorConvertFloat4ToU32(outline), + style.typeBadgeRounding, + (int)(ImDrawFlags.None), + style.borderSize + ); ImGui.DrawNativeText(draw, minimum + (size - textSize) * 0.5f, NativeImGui.ColorConvertFloat4ToU32(accent), label); NativeImGui.Dummy(size); DrawItemTooltip(tooltip); @@ -140,7 +167,9 @@ public bool CompactCheckbox( m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(id); if (size < 0f) + { size = style.compactCheckboxSize; + } if (size <= 0f) { throw new ArgumentOutOfRangeException(nameof(size), size, "Checkbox size must be positive."); @@ -164,8 +193,20 @@ public bool CompactCheckbox( { ImGui.DrawNativeFilledRectangle(drawList, min, max, textColor, 1f, 0); uint checkColor = NativeImGui.ColorConvertFloat4ToU32(EditorPalette.cardHeader); - ImGui.DrawNativeLine(drawList, min + new Vector2(size * 0.22f, size * 0.52f), min + new Vector2(size * 0.43f, size * 0.72f), checkColor, 1.5f); - ImGui.DrawNativeLine(drawList, min + new Vector2(size * 0.43f, size * 0.72f), min + new Vector2(size * 0.80f, size * 0.28f), checkColor, 1.5f); + ImGui.DrawNativeLine( + drawList, + min + new Vector2(size * 0.22f, size * 0.52f), + min + new Vector2(size * 0.43f, size * 0.72f), + checkColor, + 1.5f + ); + ImGui.DrawNativeLine( + drawList, + min + new Vector2(size * 0.43f, size * 0.72f), + min + new Vector2(size * 0.80f, size * 0.28f), + checkColor, + 1.5f + ); } else { @@ -174,7 +215,15 @@ public bool CompactCheckbox( if (hovered) { - ImGui.DrawNativeRectangle(drawList, min - Vector2.One, max + Vector2.One, NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered), 1f, 0, 1.5f); + ImGui.DrawNativeRectangle( + drawList, + min - Vector2.One, + max + Vector2.One, + NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered), + 1f, + 0, + 1.5f + ); } DrawItemTooltip(tooltip); @@ -235,7 +284,12 @@ public bool CenteredButton( } float width = ImGuiUtf8Buffer.MeasureText(label, -1f).X + NativeImGui.Raw.GetStyle()->FramePadding.X * 2f; - return DrawCenteredButton(label, NativeImGui.GetCursorScreenPos() + new Vector2(0f, topPadding), NativeImGui.GetContentRegionAvail().X, width); + return DrawCenteredButton( + label, + NativeImGui.GetCursorScreenPos() + new Vector2(0f, topPadding), + NativeImGui.GetContentRegionAvail().X, + width + ); } /// @@ -263,7 +317,9 @@ string overlay ImVec2C nativeSize = ImGui.ToNative(size); ReadOnlySpan emptyOverlay = "\0"u8; fixed (byte* empty = emptyOverlay) + { NativeImGui.Raw.ProgressBar(fraction, &nativeSize, (sbyte*)empty); + } Vector2 minimum = NativeImGui.GetItemRectMin(); Vector2 maximum = NativeImGui.GetItemRectMax(); Vector2 textSize = NativeImGui.CalcTextSize(overlay); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs index 36d0de6d9..60acb9047 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs @@ -2,6 +2,7 @@ using System.Numerics; using System.Runtime.CompilerServices; using Inno.Native.ImGui; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; @@ -67,6 +68,7 @@ float actionWidth /// Gets the content extent, excluding the window title, border and padding. /// public Vector2 size { get; } + internal float textWidth { get; } internal float bodyHeight { get; } internal float bodyContentHeight { get; } @@ -122,12 +124,18 @@ Vector2 availableSize ) { ImGuiNativeContext* native = m_session.RequireContext(); if (native->WithinFrameScope == 0 || native->Font == null || native->FontBaked == null) + { throw new InvalidOperationException("Dialog measurement requires an active native frame and font."); + } ArgumentNullException.ThrowIfNull(presentation.message); if (presentation.progress is float fraction && (!float.IsFinite(fraction) || fraction < 0f || fraction > 1f)) + { throw new ArgumentOutOfRangeException(nameof(presentation), "A determinate progress fraction must be between zero and one."); + } if (!float.IsFinite(availableSize.X) || !float.IsFinite(availableSize.Y) || availableSize.X <= 0f || availableSize.Y <= 0f) + { throw new ArgumentOutOfRangeException(nameof(availableSize)); + } float width = MathF.Max(1f, MathF.Floor(availableSize.X)); ImGuiStyle* nativeStyle = &native->Style; float spacing = nativeStyle->ItemSpacing.Y; @@ -137,19 +145,38 @@ Vector2 availableSize ImFont* font = native->Font; ImFontBaked* baked = native->FontBaked; // Only value data is retained. Shared or remapped native fonts are measured on every request. - bool memoize = font->OwnerAtlas->OwnerContext == native && font->RemapPairs.Data.Size == 0 && - (long)presentation.message.Length + (presentation.details?.Length ?? 0) + (presentation.actionLabel?.Length ?? 0) <= C_MAX_CACHED_DIALOG_CHARS; - DialogMeasurementKey key = new(presentation.message, presentation.details, presentation.actionLabel, - availableSize, hasProgress, font->FontId, baked->BakedId, baked->Glyphs.Size, - baked->IndexAdvanceX.Size, font->Sources.Size, font->OwnerAtlas->FontNextUniqueId, - native->FontSize, baked->RasterizerDensity, baked->FallbackAdvanceX, - nativeStyle->ItemSpacing.Y, ImGui.FromNative(nativeStyle->FramePadding), nativeStyle->ScrollbarSize); + bool memoize = font->OwnerAtlas->OwnerContext == native && font->RemapPairs.Data.Size == 0 + && (long)presentation.message.Length + (presentation.details?.Length ?? 0) + (presentation.actionLabel?.Length ?? 0) + <= C_MAX_CACHED_DIALOG_CHARS; + DialogMeasurementKey key = new( + presentation.message, + presentation.details, + presentation.actionLabel, + availableSize, + hasProgress, + font->FontId, + baked->BakedId, + baked->Glyphs.Size, + baked->IndexAdvanceX.Size, + font->Sources.Size, + font->OwnerAtlas->FontNextUniqueId, + native->FontSize, + baked->RasterizerDensity, + baked->FallbackAdvanceX, + nativeStyle->ItemSpacing.Y, + ImGui.FromNative(nativeStyle->FramePadding), + nativeStyle->ScrollbarSize + ); if (memoize) { if (m_dialogLayout.size.X > 0f && m_dialogKey == key) + { return m_dialogLayout; + } if (m_previousDialogLayout.size.X > 0f && m_previousDialogKey == key) + { return m_previousDialogLayout; + } } float footer = (hasProgress ? frame : 0f) + (hasAction ? frame : 0f) + (hasProgress && hasAction ? spacing : 0f); float body = MeasureDialogBody(presentation, width, spacing); @@ -162,7 +189,9 @@ Vector2 availableSize } float visibleBody = MathF.Min(body, availableBody); float height = visibleBody + footer + (visibleBody > 0f && footer > 0f ? spacing : 0f); - float actionWidth = hasAction ? ImGuiUtf8Buffer.MeasureText(presentation.actionLabel!, -1f).X + nativeStyle->FramePadding.X * 2f : 0f; + float actionWidth = hasAction + ? ImGuiUtf8Buffer.MeasureText(presentation.actionLabel!, -1f).X + nativeStyle->FramePadding.X * 2f + : 0f; DialogLayout result = new(new Vector2(width, MathF.Ceiling(height)), textWidth, visibleBody, body, spacing, frame, actionWidth); if (memoize) { @@ -206,7 +235,9 @@ DialogLayout layout m_session.EnsureDrawing(); ArgumentNullException.ThrowIfNull(presentation.message); if (!float.IsFinite(layout.size.X) || !float.IsFinite(layout.size.Y) || layout.size.X <= 0f || layout.size.Y < 0f) + { throw new ArgumentOutOfRangeException(nameof(layout)); + } Vector2 origin = NativeGui.GetCursorScreenPos(); bool scrolling = layout.bodyContentHeight > layout.bodyHeight; if (layout.bodyHeight > 0f) @@ -222,11 +253,15 @@ DialogLayout layout ReadOnlySpan bodyId = "##dialog-body\0"u8; bool visible; fixed (byte* id = bodyId) + { visible = NativeGui.Raw.BeginChild((sbyte*)id, &bodySize, 0, 0) != 0; + } try { if (visible) + { DrawDialogBody(presentation, layout.textWidth); + } } finally { @@ -239,17 +274,24 @@ DialogLayout layout } } else + { DrawDialogBody(presentation, layout.textWidth); + } } float y = layout.bodyHeight; if (y > 0f && (presentation.progress.HasValue || presentation.indeterminate || !string.IsNullOrEmpty(presentation.actionLabel))) + { y += layout.spacing; + } if (presentation.progress.HasValue || presentation.indeterminate) { NativeGui.SetCursorScreenPos(origin + new Vector2(0f, y)); float fraction = presentation.progress ?? 0f; - CenteredProgressBar(presentation.indeterminate ? -(float)NativeGui.GetTime() : fraction, - new Vector2(layout.size.X, layout.frameHeight), presentation.indeterminate ? "Working…" : $"{fraction:P0}"); + CenteredProgressBar( + presentation.indeterminate ? -(float)NativeGui.GetTime() : fraction, + new Vector2(layout.size.X, layout.frameHeight), + presentation.indeterminate ? "Working…" : $"{fraction:P0}" + ); y += layout.frameHeight + layout.spacing; } bool activated = false; @@ -257,18 +299,27 @@ DialogLayout layout { bool disabled = !presentation.actionEnabled; if (disabled) + { NativeGui.BeginDisabled(true); + } try { activated = DrawCenteredButton(presentation.actionLabel, origin + new Vector2(0f, y), layout.size.X, layout.actionWidth); - if (presentation.cancelOnEscape && presentation.actionEnabled && NativeGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows) && - NativeGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Escape, false)) + if (presentation.cancelOnEscape + && presentation.actionEnabled + && NativeGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows) + && + NativeGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Escape, false) + ) { activated = true; + } } finally { if (disabled) + { NativeGui.EndDisabled(); + } } } return activated; @@ -309,7 +360,9 @@ float spacing ) { float height = presentation.message.Length == 0 ? 0f : ImGuiUtf8Buffer.MeasureText(presentation.message, width).Y; if (!string.IsNullOrEmpty(presentation.details)) + { height += (height > 0f ? spacing : 0f) + ImGuiUtf8Buffer.MeasureText(presentation.details, width).Y; + } return MathF.Ceiling(height); } @@ -321,7 +374,9 @@ float width try { if (presentation.message.Length != 0) + { ImGuiUtf8Buffer.DrawText(presentation.message); + } if (!string.IsNullOrEmpty(presentation.details)) { // Native text already contributes the same inter-item spacing used by measurement. diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs index 2ed173cbb..7d3fcd7e3 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs @@ -1,10 +1,12 @@ using System; -using BGCS.Runtime; using System.Numerics; +using BGCS.Runtime; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -39,8 +41,7 @@ public bool DragDropSource( in TPayload payload, Action? drawPreview = null, bool allowHoldToOpenOthers = true - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { ArgumentException.ThrowIfNullOrWhiteSpace(payloadType); ImGuiDragDropFlags sourceFlags = allowHoldToOpenOthers ? ImGuiDragDropFlags.None : ImGuiDragDropFlags.SourceNoHoldToOpenOthers; @@ -87,8 +88,7 @@ public bool DragDropSource( Func payloadFactory, Action? drawPreview = null, bool allowHoldToOpenOthers = true - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { ArgumentException.ThrowIfNullOrWhiteSpace(payloadType); ArgumentNullException.ThrowIfNull(payloadFactory); @@ -123,8 +123,7 @@ public bool DragDropSource( public bool DragDropTarget( string payloadType, out TPayload payload - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { return DragDropTarget(payloadType, out payload, out _); } @@ -151,8 +150,7 @@ public bool DragDropTarget( string payloadType, out TPayload payload, out bool isPreviewing - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { return DragDropTarget(payloadType, out payload, out isPreviewing, drawDefaultHighlight: true); } @@ -183,8 +181,7 @@ public bool DragDropTarget( out TPayload payload, out bool isPreviewing, bool drawDefaultHighlight - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { ArgumentException.ThrowIfNullOrWhiteSpace(payloadType); payload = default; @@ -196,12 +193,16 @@ bool drawDefaultHighlight ImGuiDragDropFlags flags = ImGuiDragDropFlags.AcceptBeforeDelivery; if (!drawDefaultHighlight) + { flags |= ImGuiDragDropFlags.AcceptNoDrawDefaultRect; + } using NativeStringLease nativeType = Utf8Codec.EncodeNullTerminated(payloadType, allowsNull: false); ImGuiPayload* nativePayload = NativeImGui.Raw.AcceptDragDropPayload((sbyte*)nativeType.pointer, (int)flags); bool compatible = TryReadDragDropPayload(nativePayload, out payload); if (compatible) + { isPreviewing = nativePayload->Preview != 0; + } bool delivered = compatible && nativePayload->Delivery != 0; NativeImGui.EndDragDropTarget(); return delivered; @@ -248,31 +249,38 @@ public bool DragDropTarget( out TPayload payload, out bool isPreviewing, bool drawDefaultHighlight = true - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { ArgumentException.ThrowIfNullOrWhiteSpace(payloadType); payload = default; isPreviewing = false; if (maximum.X <= minimum.X || maximum.Y <= minimum.Y) + { return false; + } ImRect bounds = new() { Min = ImGui.ToNative(minimum), Max = ImGui.ToNative(maximum) }; if (NativeImGui.Raw.BeginDragDropTargetCustom(&bounds, targetId) == 0) + { return false; + } try { ImGuiDragDropFlags flags = ImGuiDragDropFlags.AcceptBeforeDelivery; if (!drawDefaultHighlight) + { flags |= ImGuiDragDropFlags.AcceptNoDrawDefaultRect; + } using NativeStringLease nativeType = Utf8Codec.EncodeNullTerminated(payloadType, allowsNull: false); ImGuiPayload* nativePayload = NativeImGui.Raw.AcceptDragDropPayload((sbyte*)nativeType.pointer, (int)flags); bool compatible = TryReadDragDropPayload(nativePayload, out payload); if (compatible) + { isPreviewing = nativePayload->Preview != 0; + } return compatible && nativePayload->Delivery != 0; } finally @@ -284,8 +292,7 @@ public bool DragDropTarget( private unsafe void SetDragDropPayload( string payloadType, in TPayload payload - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { TPayload payloadCopy = payload; using NativeStringLease nativeType = Utf8Codec.EncodeNullTerminated(payloadType, allowsNull: false); @@ -295,12 +302,13 @@ in TPayload payload private unsafe bool TryReadDragDropPayload( ImGuiPayload* nativePayload, out TPayload payload - ) - where TPayload : unmanaged + ) where TPayload : unmanaged { payload = default; if ((nativePayload == null) || nativePayload->DataSize != sizeof(TPayload) || nativePayload->Data == null) + { return false; + } payload = *(TPayload*)nativePayload->Data; return true; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs index c8600bfa4..1aad2e10b 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs @@ -1,10 +1,12 @@ using System; using Inno.Editor.Interactions; -using Inno.Scripting.Api; using Inno.Native.ImGui; +using Inno.Scripting.Api; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Owns session-local controls, native adaptation and reversible edit gestures. /// @@ -13,6 +15,7 @@ public sealed unsafe partial class ImGuiWidget private EditorEditGesture? m_propertyGesture; private (string Owner, string Path) m_propertyEditKey; private bool m_propertyEditTouched; + /// /// Gets the current continuous-edit merge boundary, or null for a discrete edit. /// @@ -43,7 +46,9 @@ string name m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(path); if (NativeImGui.IsAnyItemActive()) + { BeginEdit(history, path, name); + } } /// @@ -69,7 +74,9 @@ string name ArgumentException.ThrowIfNullOrWhiteSpace(path); var key = (m_session.owner, path); if (m_propertyGesture is not null && m_propertyEditKey != key) + { CommitEdits(); + } if (m_propertyGesture is null) { m_propertyGesture = new EditorEditGesture(history, name); @@ -90,6 +97,7 @@ string name /// [ScriptingApiIgnore] public bool IsEditing(string path) => m_propertyGesture is not null && m_propertyEditKey == (m_session.owner, path); + /// /// Observes the current property after drawing, including release and cancellation without a new value sample. /// @@ -101,12 +109,18 @@ public void CompletePropertyEdit(string path) { m_session.EnsureDrawing(); if (m_propertyGesture is null || m_propertyEditKey != (m_session.owner, path)) + { return; + } m_propertyEditTouched = true; if (NativeImGui.IsKeyPressed((Inno.Native.ImGui.ImGuiKey)ImGuiKey.Escape, false)) + { CancelEdits(); + } else if (!NativeImGui.IsAnyItemActive()) + { CommitEdits(); + } } /// @@ -119,7 +133,9 @@ public void CompletePropertyEdit(string path) public void CommitEdits() { if (m_propertyGesture is null) + { return; + } m_propertyGesture.Commit(); m_propertyGesture.Dispose(); m_propertyGesture = null; @@ -135,18 +151,25 @@ public void CommitEdits() public void CancelEdits() { if (m_propertyGesture is null) + { return; + } EditorHistoryResult result = m_propertyGesture.Cancel(); if (!result.succeeded) + { throw new InvalidOperationException($"The property gesture could not roll back: {result.message}"); + } m_propertyGesture.Dispose(); m_propertyGesture = null; } internal void BeginEditingFrame() => m_propertyEditTouched = false; + internal void CompleteEditingFrame() { if (m_propertyGesture is not null && !m_propertyEditTouched) + { CancelEdits(); + } } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs index 34816bca5..c6729e752 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs @@ -1,12 +1,14 @@ using System; using System.Numerics; + using Matrix = Inno.Core.Mathematics.Matrix; -using NativeImGui = Inno.Native.ImGui.ImGui; using NativeGizmo = Inno.Native.ImGuizmo.ImGuizmo; +using NativeImGui = Inno.Native.ImGui.ImGui; using NativeOperation = Inno.Native.ImGuizmo.ImGuizmoOperation; using NativeSpace = Inno.Native.ImGuizmo.ImGuizmoMode; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Chooses the transform handles rendered by the viewport presenter. /// @@ -63,42 +65,52 @@ public readonly record struct TransformGizmoOptions /// Gets the viewport's screen-space minimum. /// public Vector2 minimum { get; init; } + /// /// Gets the viewport's screen-space maximum. /// public Vector2 maximum { get; init; } + /// /// Gets the column-vector view matrix. /// public Matrix view { get; init; } + /// /// Gets the projection matrix supplied by the viewport owner. /// public Matrix projection { get; init; } + /// /// Gets whether this viewport uses an orthographic projection. /// public bool orthographic { get; init; } + /// /// Gets whether manipulation can consume pointer input. /// public bool enabled { get; init; } + /// /// Gets the requested handles. /// public TransformGizmoOperation operation { get; init; } + /// /// Gets the handle coordinate space. /// public TransformGizmoSpace space { get; init; } + /// /// Gets whether the X translation axis is excluded by the viewport plane. /// public bool maskX { get; init; } + /// /// Gets whether the Y translation axis is excluded by the viewport plane. /// public bool maskY { get; init; } + /// /// Gets whether the Z translation axis is excluded by the viewport plane. /// @@ -126,6 +138,7 @@ public readonly record struct TransformGizmoResult( bool isUsing, bool isOver ); + /// /// Owns session-local controls, native adaptation and reversible edit gestures. /// @@ -157,7 +170,12 @@ TransformGizmoOptions options NativeOperation operation = ToNativeOperation(options.operation); NativeGizmo.BeginFrame(); NativeGizmo.Raw.SetDrawlist((Inno.Native.ImGuizmo.ImDrawList*)(nint)NativeImGui.Raw.GetWindowDrawList()); - NativeGizmo.SetRect(options.minimum.X, options.minimum.Y, MathF.Max(1f, options.maximum.X - options.minimum.X), MathF.Max(1f, options.maximum.Y - options.minimum.Y)); + NativeGizmo.SetRect( + options.minimum.X, + options.minimum.Y, + MathF.Max(1f, options.maximum.X - options.minimum.X), + MathF.Max(1f, options.maximum.Y - options.minimum.Y) + ); NativeGizmo.SetOrthographic(options.orthographic); NativeGizmo.SetGizmoSizeClipSpace(0.21f); var style = NativeGizmo.Raw.GetStyle(); @@ -199,18 +217,30 @@ TransformGizmoOptions options private static NativeOperation ToNativeOperation(TransformGizmoOperation operation) { if (operation == TransformGizmoOperation.Translate) + { return NativeOperation.Translate; + } if (operation == TransformGizmoOperation.Rotate) + { return NativeOperation.Rotate; + } NativeOperation result = 0; if (operation.HasFlag(TransformGizmoOperation.ScaleX)) + { result |= NativeOperation.ScaleX; + } if (operation.HasFlag(TransformGizmoOperation.ScaleY)) + { result |= NativeOperation.ScaleY; + } if (operation.HasFlag(TransformGizmoOperation.ScaleZ)) + { result |= NativeOperation.ScaleZ; + } if (result == 0) + { throw new ArgumentOutOfRangeException(nameof(operation)); + } return result; } @@ -236,22 +266,23 @@ private static unsafe void WriteColumnMajor( destination[15] = matrix.m44; } - private static unsafe Matrix ReadColumnMajor(float* source) => new( - source[0], - source[4], - source[8], - source[12], - source[1], - source[5], - source[9], - source[13], - source[2], - source[6], - source[10], - source[14], - source[3], - source[7], - source[11], - source[15] - ); + private static unsafe Matrix ReadColumnMajor(float* source) + => new( + source[0], + source[4], + source[8], + source[12], + source[1], + source[5], + source[9], + source[13], + source[2], + source[6], + source[10], + source[14], + source[3], + source[7], + source[11], + source[15] + ); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs index eebd74b85..1459dbe0d 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs @@ -1,15 +1,18 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides standard help box presentation in the Editor UI. /// public sealed unsafe partial class ImGuiWidget { private SectionLayoutState? m_sectionLayout; + /// /// Draws a wrapped contextual message with a semantic icon and a subdued status surface. /// @@ -43,9 +46,31 @@ Vector4 color background.W = EditorPalette.opacityOpaque; Vector4 outline = color; outline.W = EditorPalette.opacityMuted; - ImGui.DrawNativeFilledRectangle(draw, origin, origin + new Vector2(width, height), NativeImGui.ColorConvertFloat4ToU32(background), 4f * style.zoom, 0); - ImGui.DrawNativeRectangle(draw, origin, origin + new Vector2(width, height), NativeImGui.ColorConvertFloat4ToU32(outline), 4f * style.zoom, 0, 1f); - ImGui.DrawNativeFilledRectangle(draw, origin, origin + new Vector2(2f * style.zoom, height), NativeImGui.ColorConvertFloat4ToU32(color), 0, 0); + ImGui.DrawNativeFilledRectangle( + draw, + origin, + origin + new Vector2(width, height), + NativeImGui.ColorConvertFloat4ToU32(background), + 4f * style.zoom, + 0 + ); + ImGui.DrawNativeRectangle( + draw, + origin, + origin + new Vector2(width, height), + NativeImGui.ColorConvertFloat4ToU32(outline), + 4f * style.zoom, + 0, + 1f + ); + ImGui.DrawNativeFilledRectangle( + draw, + origin, + origin + new Vector2(2f * style.zoom, height), + NativeImGui.ColorConvertFloat4ToU32(color), + 0, + 0 + ); ImGui.DrawNativeText(draw, origin + padding, NativeImGui.ColorConvertFloat4ToU32(color), icon); NativeImGui.SetCursorScreenPos(origin + padding + new Vector2(iconWidth + gap, 0f)); NativeImGui.PushTextWrapPos(NativeImGui.GetCursorPosX() + textWidth); @@ -158,7 +183,9 @@ public bool EnsureSection( ArgumentNullException.ThrowIfNull(title); SectionLayoutState? layout = m_sectionLayout; if (layout is null) + { return true; + } return layout.sectionIndex == 0 ? SectionHeader(title, description) : layout.contentVisible; } @@ -218,7 +245,12 @@ public bool SectionHeader( NativeImGui.SameLine(0f, style.headerControlSpacing); } - titlePressed = ClickableText($"inspector_section_title_{sectionIndex}", title, new Vector2(MathF.Max(1f, titleSize.X), frameHeight), description); + titlePressed = ClickableText( + $"inspector_section_title_{sectionIndex}", + title, + new Vector2(MathF.Max(1f, titleSize.X), frameHeight), + description + ); } finally { @@ -291,7 +323,9 @@ uint color private void CompleteSection(SectionLayoutState layout) { if (!layout.active) + { return; + } NativeImGui.Dummy(new Vector2(0f, style.sectionPadding.Y)); NativeImGui.Unindent(style.sectionPadding.X); float bottom = MathF.Max(NativeImGui.GetCursorScreenPos().Y, layout.top + NativeImGui.GetFrameHeight()); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs index db25fd6ab..68f4a6292 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs @@ -1,15 +1,18 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// public sealed unsafe partial class ImGuiWidget { private const float C_INLINE_RENAME_FOCUS_OFFSET = 1f; + /// /// Draws a compact single-line rename editor inside an existing row. /// @@ -77,7 +80,13 @@ public InlineRenameResult InlineRename( NativeImGui.PushStyleColor((int)(ImGuiCol.NavCursor), EditorPalette.transparent); try { - submitted = ImGuiUtf8Buffer.InputText(controlId, null, ref text, (nuint)capacity, ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.AutoSelectAll); + submitted = ImGuiUtf8Buffer.InputText( + controlId, + null, + ref text, + (nuint)capacity, + ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.AutoSelectAll + ); } finally { @@ -114,9 +123,13 @@ public InlineRenameResult InlineRename( } if (escapePressed) + { return InlineRenameResult.Cancel; + } if (submitted) + { return InlineRenameResult.Commit; + } if (contextMenuRequested) { // A context menu transfers focus into a popup after this item has already been @@ -169,7 +182,9 @@ public InlineRenamePresentation( nuint bufferSize = 512 ) { if (string.IsNullOrWhiteSpace(id)) + { throw new ArgumentException("An inline rename identifier is required.", nameof(id)); + } if (!float.IsFinite(width) || width <= 0f) { throw new ArgumentOutOfRangeException(nameof(width), width, "The inline rename width must be finite and positive."); @@ -177,7 +192,11 @@ public InlineRenamePresentation( if (!float.IsFinite(rowHeight) || rowHeight <= 0f) { - throw new ArgumentOutOfRangeException(nameof(rowHeight), rowHeight, "The inline rename row height must be finite and positive."); + throw new ArgumentOutOfRangeException( + nameof(rowHeight), + rowHeight, + "The inline rename row height must be finite and positive." + ); } if (bufferSize == 0) @@ -195,14 +214,17 @@ public InlineRenamePresentation( /// Gets the stable ImGui identifier used by the input field. /// public string id { get; } + /// /// Gets the requested input width in logical pixels. /// public float width { get; } + /// /// Gets the height of the row area in which the input field is centered. /// public float rowHeight { get; } + /// /// Gets the maximum UTF-8 buffer size accepted by the input. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs index 09bc0526b..8b956d885 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs @@ -2,12 +2,14 @@ using System.Collections.Generic; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Owns and retires transient controls by session and stable presentation owner. /// public sealed unsafe partial class ImGuiWidget { private readonly EditorUiSession m_session; + internal ImGuiWidget(EditorUiSession session) { m_session = session ?? throw new ArgumentNullException(nameof(session)); @@ -17,16 +19,22 @@ internal ImGuiWidget(EditorUiSession session) internal void RetireOwner(string owner) { if (m_propertyGesture is not null && m_propertyEditKey.Owner == owner) + { CancelEdits(); + } var retired = new List<(string Owner, uint Window)>(); foreach (var key in m_treeStatesByWindow.Keys) { if (string.Equals(key.Owner, owner, StringComparison.Ordinal)) + { retired.Add(key); + } } foreach (var key in retired) + { m_treeStatesByWindow.Remove(key); + } } internal void Retire() diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.MixedValue.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.MixedValue.cs index 4b2880b0a..998f6c274 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.MixedValue.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.MixedValue.cs @@ -1,8 +1,10 @@ using System; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Presents mixed values using the same controls and shared History. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs index c6e85ce7a..047cdf6d1 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs @@ -1,10 +1,12 @@ using System; using System.Numerics; -using Inno.Scripting.Api; using Inno.Native.ImGui; +using Inno.Scripting.Api; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Reusable editor widgets built on top of . /// @@ -38,7 +40,9 @@ public void PanelWindow( ) { m_session.EnsureDrawing(); if (!isOpen) + { return; + } bool pushedPadding = false; bool beganWindow = false; try @@ -76,17 +80,25 @@ public void PanelWindow( if (visible) { if (DrawPanelCloseButton(title)) + { isOpen = false; + } if (isOpen) + { drawBody(); + } } } finally { if (pushedPadding) + { NativeImGui.PopStyleVar(); + } if (beganWindow) + { NativeImGui.End(); + } } } @@ -122,14 +134,18 @@ public void ConstrainedContent( float contentWidth = MathF.Max(1f, width - padding.X * 2f); ImGuiChildFlags childFlags = ImGuiChildFlags.AutoResizeY | ImGuiChildFlags.AlwaysAutoResize; if (useWindowPadding) + { childFlags |= ImGuiChildFlags.AlwaysUseWindowPadding; + } ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoSavedSettings; NativeImGui.SetNextWindowContentSize(new Vector2(contentWidth, 0f)); bool visible = NativeImGui.BeginChild(id, new Vector2(width, 0f), (int)(childFlags), (int)(windowFlags)); try { if (visible) + { drawContent(); + } } finally { @@ -178,7 +194,9 @@ public void HeaderSurface( try { ImGuiChildFlags childFlags = ImGuiChildFlags.FrameStyle | ImGuiChildFlags.AutoResizeY; - ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoSavedSettings; + ImGuiWindowFlags windowFlags = ImGuiWindowFlags.NoScrollbar + | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoSavedSettings; bool visible = NativeImGui.BeginChild(id, new Vector2(width, 0f), (int)(childFlags), (int)(windowFlags)); // FrameStyle consumed the square outer-container rounding in BeginChild. Restore the // normal editor rounding before drawing controls inside the header. @@ -186,7 +204,9 @@ public void HeaderSurface( try { if (visible) + { drawContent(); + } } finally { @@ -205,16 +225,22 @@ public void HeaderSurface( private bool DrawPanelCloseButton(string title) { if (!NativeImGui.IsWindowDocked()) + { return DrawFloatingPanelCloseButton(title); + } uint dockId = NativeImGui.GetWindowDockID(); ImGuiDockNode* dockNode = NativeImGui.Raw.DockBuilderGetNode(dockId); if (dockNode == null || NativeImGui.Raw.DockNodeBeginAmendTabBar(dockNode) == 0) + { return false; + } try { ImGuiTabBar* tabBar = dockNode->TabBar; if (tabBar == null) + { return false; + } ImRect tabBarBounds = tabBar->BarRect; float tabBarHeight = MathF.Max(1f, tabBarBounds.Max.Y - tabBarBounds.Min.Y); float iconSlotSize = MathF.Min(GetCompactIconSize().X, tabBarHeight); @@ -229,15 +255,21 @@ private bool DrawPanelCloseButton(string title) uint itemId = NativeImGui.GetID($"##panel_close_{dockId}"); bool hovered = false; bool held = false; - ImGuiButtonFlags buttonFlags = (ImGuiButtonFlags)((int)ImGuiButtonFlagsPrivate.AllowOverlap | (int)ImGuiButtonFlagsPrivate.NoNavFocus | (int)ImGuiButtonFlagsPrivate.PressedOnClickRelease); + ImGuiButtonFlags buttonFlags = (ImGuiButtonFlags)((int)ImGuiButtonFlagsPrivate.AllowOverlap + | (int)ImGuiButtonFlagsPrivate.NoNavFocus + | (int)ImGuiButtonFlagsPrivate.PressedOnClickRelease); ImGuiWindow* hoveredWindow = NativeImGui.Raw.GetCurrentContext()->HoveredWindow; bool hostHovered = hoveredWindow != null && hoveredWindow->RootWindowDockTree == dockNode->HostWindow->RootWindowDockTree; bool mouseHovered = hostHovered && NativeImGui.IsMouseHoveringRect(itemMinimum, itemMaximum); bool itemAdded = NativeImGui.Raw.ItemAdd(&itemBounds, itemId, null, 0) != 0; - bool pressed = hostHovered && itemAdded && NativeImGui.ButtonBehavior(itemBounds, itemId, out hovered, out held, (int)buttonFlags); + bool pressed = hostHovered + && itemAdded + && NativeImGui.ButtonBehavior(itemBounds, itemId, out hovered, out held, (int)buttonFlags); hovered |= mouseHovered; pressed |= mouseHovered && NativeImGui.IsMouseClicked((int)(ImGuiMouseButton.Left)); - uint iconColor = hovered || held ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); + uint iconColor = hovered || held + ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) + : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); DrawPanelCloseMark(NativeImGui.Raw.GetWindowDrawList(), itemCenter, iconSlotSize, iconColor); if (hovered && BeginMenuTooltip()) { @@ -257,10 +289,15 @@ private bool DrawFloatingPanelCloseButton(string title) { ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); if ((window->Flags & (int)ImGuiWindowFlags.NoTitleBar) != 0) + { return false; + } ImGuiStyle* nativeStyle = NativeImGui.Raw.GetStyle(); float size = GetCompactIconSize().X; - Vector2 maximum = new(window->Pos.X + window->Size.X - nativeStyle->WindowBorderSize - nativeStyle->FramePadding.X, window->Pos.Y + (window->TitleBarHeight + size) * 0.5f); + Vector2 maximum = new( + window->Pos.X + window->Size.X - nativeStyle->WindowBorderSize - nativeStyle->FramePadding.X, + window->Pos.Y + (window->TitleBarHeight + size) * 0.5f + ); Vector2 minimum = maximum - new Vector2(size); ImRect bounds = new() { @@ -280,23 +317,22 @@ private bool DrawFloatingPanelCloseButton(string title) { uint id = NativeImGui.GetID("##floating_panel_close"); bool hovered = false, held = false; - bool pressed = NativeImGui.Raw.ItemAdd( - &bounds, - id, - null, - 0 - ) != 0 - && NativeImGui.ButtonBehavior( - bounds, - id, - out hovered, - out held, - (int)ImGuiButtonFlagsPrivate.NoNavFocus | (int)ImGuiButtonFlagsPrivate.PressedOnClickRelease - ); - uint iconColor = hovered || held ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); + bool pressed = NativeImGui.Raw.ItemAdd(&bounds, id, null, 0) != 0 + && NativeImGui.ButtonBehavior( + bounds, + id, + out hovered, + out held, + (int)ImGuiButtonFlagsPrivate.NoNavFocus | (int)ImGuiButtonFlagsPrivate.PressedOnClickRelease + ); + uint iconColor = hovered || held + ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) + : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); DrawPanelCloseMark(draw, minimum + new Vector2(size * 0.5f), size, iconColor); if (hovered) + { DrawItemTooltip($"Close {title}"); + } return pressed; } finally diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs index 5c4439f5a..9009ea618 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs @@ -1,9 +1,11 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -11,6 +13,7 @@ public sealed unsafe partial class ImGuiWidget { private const string C_COMPACT_FLOAT_FORMAT = "%.1f"; private const string C_PRECISE_FLOAT_FORMAT = "%.9g"; + /// /// Draws a two-column property row with a stable internal identifier. /// @@ -382,7 +385,13 @@ float y ) { m_session.EnsureDrawing(); uint color = NativeImGui.GetColorU32((int)(ImGuiCol.DragDropTarget)); - ImGui.DrawNativeLine(NativeImGui.Raw.GetForegroundDrawList((ImGuiViewport*)null), new Vector2(fromX, y), new Vector2(toX, y), color, style.interactionOverlayThickness); + ImGui.DrawNativeLine( + NativeImGui.Raw.GetForegroundDrawList((ImGuiViewport*)null), + new Vector2(fromX, y), + new Vector2(toX, y), + color, + style.interactionOverlayThickness + ); } /// @@ -422,10 +431,22 @@ float width float axisWidth = MathF.Min(MathF.Max(style.axisPrefixMinimumWidth, height), width * style.axisPrefixWidthRatio); Vector2 prefixMin = NativeImGui.GetCursorScreenPos(); Vector2 prefixMax = prefixMin + new Vector2(axisWidth, height); - ImGui.DrawNativeFilledRectangle(NativeImGui.Raw.GetWindowDrawList(), prefixMin, prefixMax, NativeImGui.ColorConvertFloat4ToU32(GetAxisColor(axis)), 1f, 0); + ImGui.DrawNativeFilledRectangle( + NativeImGui.Raw.GetWindowDrawList(), + prefixMin, + prefixMax, + NativeImGui.ColorConvertFloat4ToU32(GetAxisColor(axis)), + 1f, + 0 + ); Vector2 textSize = NativeImGui.CalcTextSize(axis); Vector2 textPosition = prefixMin + (new Vector2(axisWidth, height) - textSize) * 0.5f; - ImGui.DrawNativeText(NativeImGui.Raw.GetWindowDrawList(), textPosition, NativeImGui.ColorConvertFloat4ToU32(EditorPalette.text), axis); + ImGui.DrawNativeText( + NativeImGui.Raw.GetWindowDrawList(), + textPosition, + NativeImGui.ColorConvertFloat4ToU32(EditorPalette.text), + axis + ); NativeImGui.Dummy(new Vector2(axisWidth, height)); NativeImGui.SameLine(0f, 0f); NativeImGui.SetNextItemWidth(MathF.Max(1f, width - axisWidth)); @@ -434,13 +455,16 @@ float width private bool WantsPreciseFloatInput(string label) { bool inputRequested = NativeImGui.IsMouseDoubleClicked((int)(ImGuiMouseButton.Left)) - || (NativeImGui.Raw.GetIO()->KeyCtrl != 0 - && NativeImGui.IsMouseClicked((int)(ImGuiMouseButton.Left))); + || (NativeImGui.Raw.GetIO()->KeyCtrl != 0 + && NativeImGui.IsMouseClicked((int)(ImGuiMouseButton.Left))); if (!inputRequested) + { return false; + } Vector2 minimum = NativeImGui.GetCursorScreenPos(); Vector2 maximum = minimum + new Vector2(MathF.Max(1f, NativeImGui.CalcItemWidth()), NativeImGui.GetFrameHeight()); - return NativeImGui.IsWindowHovered((int)(ImGuiHoveredFlags.RootAndChildWindows)) && NativeImGui.IsMouseHoveringRect(minimum, maximum, true); + return NativeImGui.IsWindowHovered((int)(ImGuiHoveredFlags.RootAndChildWindows)) + && NativeImGui.IsMouseHoveringRect(minimum, maximum, true); } private void ValidateFloatBounds( @@ -453,9 +477,13 @@ private void ValidateFloatBounds( } if (minimum is not float lower || maximum is not float upper) + { return; + } if (!float.IsFinite(lower) || !float.IsFinite(upper) || lower > upper) + { throw new ArgumentOutOfRangeException(nameof(maximum), "Floating-point bounds must be finite and ordered."); + } } private Vector4 GetAxisColor(string axis) diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs index 692b20460..dfc6acd73 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs @@ -1,8 +1,10 @@ using System; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -76,11 +78,17 @@ public bool BeginSearchPopup( m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(id); if (width < 0f) + { width = style.searchPopupWidth; + } if (!BeginMenuPopup(id)) + { return false; + } if (NativeImGui.IsWindowAppearing()) + { NativeImGui.SetKeyboardFocusHere(); + } _ = SearchInput(id, hint, ref query, capacity, width); NativeImGui.Separator(); return true; diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs index 2d1d62f43..ff1d5b649 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs @@ -5,9 +5,11 @@ using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Applies ordered selection gestures through the authoritative interaction owner. /// @@ -37,11 +39,17 @@ IReadOnlyList visibleTargets ImGuiIO* io = NativeImGui.Raw.GetIO(); bool additive = HasPrimaryModifier(interactions.keyboard, io); if (io->KeyShift != 0) + { interactions.SelectRange(visibleTargets, target, additive); + } else if (additive) + { interactions.ToggleSelection(target); + } else + { interactions.SetSelection(target); + } } /// @@ -82,43 +90,71 @@ public ListNavigationResult NavigateList( ArgumentOutOfRangeException.ThrowIfNegative(itemCount); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize); if (focusedIndex < -1 || focusedIndex >= itemCount && focusedIndex != -1) + { throw new ArgumentOutOfRangeException(nameof(focusedIndex)); + } ImGuiIO* io = NativeImGui.Raw.GetIO(); ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); bool ownsActiveRow = RouteTreeNavigationKeys(context); if (!NativeImGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows) - || io->WantTextInput != 0 || (context->ActiveId != 0 && !ownsActiveRow) || ImGui.IsAnyPopupOpen()) + || io->WantTextInput != 0 || (context->ActiveId != 0 && !ownsActiveRow) || ImGui.IsAnyPopupOpen() + ) { return new(focusedIndex, false, false, false, false, false, false, false); + } int next = focusedIndex; bool navigation = false; if (itemCount > 0) { navigation = true; if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.DownArrow)) + { next = focusedIndex < 0 ? 0 : Math.Min(itemCount - 1, focusedIndex + 1); + } else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.UpArrow)) + { next = focusedIndex < 0 ? itemCount - 1 : Math.Max(0, focusedIndex - 1); + } else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Home)) + { next = 0; + } else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.End)) + { next = itemCount - 1; + } else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.PageDown)) + { next = focusedIndex < 0 ? 0 : (int)Math.Min(itemCount - 1L, (long)focusedIndex + pageSize); + } else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.PageUp)) + { next = focusedIndex < 0 ? 0 : Math.Max(0, focusedIndex - pageSize); + } else + { navigation = false; + } } bool primary = HasPrimaryModifier(interactions.keyboard, io); bool extend = io->KeyShift != 0; bool space = itemCount > 0 && NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Space, false); bool activate = itemCount > 0 && (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Enter, false) - || NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.KeypadEnter, false)); + || NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.KeypadEnter, false)); bool cancel = NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Escape, false); if ((space || activate) && next < 0) + { next = 0; - return new(next, next != focusedIndex, space || navigation && (!primary || extend), - extend, primary, space && primary, activate, cancel); + } + return new( + next, + next != focusedIndex, + space || navigation && (!primary || extend), + extend, + primary, + space && primary, + activate, + cancel + ); } private bool RouteTreeNavigationKeys(ImGuiNativeContext* context) @@ -127,10 +163,12 @@ private bool RouteTreeNavigationKeys(ImGuiNativeContext* context) if (!m_treeStatesByWindow.TryGetValue((m_session.owner, window), out TreeWidgetWindowState? state) || state.lastFrame != NativeImGui.GetFrameCount() || !NativeImGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows) - || NativeImGui.Raw.GetIO()->WantTextInput != 0 || ImGui.IsAnyPopupOpen()) + || NativeImGui.Raw.GetIO()->WantTextInput != 0 || ImGui.IsAnyPopupOpen() + ) { return false; + } bool ownsActiveRow = context->ActiveId != 0 - && context->ActiveIdSource == ImGuiInputSource.Keyboard && state.navigationItemIds.Contains(context->ActiveId); + && context->ActiveIdSource == ImGuiInputSource.Keyboard && state.navigationItemIds.Contains(context->ActiveId); if (state.navigationItemIds.Contains(context->NavId) && (context->ActiveId == 0 || ownsActiveRow)) { // Native navigation must not activate the disclosure while the list owns selection/activation. @@ -150,13 +188,21 @@ private static bool HasPrimaryModifier( var input = new EditorUiInput(io); KeyModifier modifiers = KeyModifier.None; if (input.control) + { modifiers |= KeyModifier.Control; + } if (input.super) + { modifiers |= KeyModifier.Super; + } if (input.alt) + { modifiers |= KeyModifier.Alt; + } if (input.shift) + { modifiers |= KeyModifier.Shift; + } return (modifiers & keyboard.primaryModifier) == keyboard.primaryModifier; } } @@ -190,30 +236,37 @@ bool cancel /// Gets the resulting visible focus index, or minus one for no focus. /// public int focusedIndex { get; } + /// /// Gets whether the visible focus index changed. /// public bool focusChanged { get; } + /// /// Gets whether the caller should apply a domain selection operation. /// public bool selectionRequested { get; } + /// /// Gets whether the selection should extend from its existing anchor. /// public bool extendRange { get; } + /// /// Gets whether the product's primary modifier requests preserving other selected entries. /// public bool additive { get; } + /// /// Gets whether Space with the primary modifier requests toggling the focused entry. /// public bool toggle { get; } + /// /// Gets whether Enter requests activation of the focused entry. /// public bool activate { get; } + /// /// Gets whether Escape requests canceling the current list workflow. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs index 70cf5fe24..4434cdbef 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs @@ -1,9 +1,11 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -43,9 +45,13 @@ public bool BeginBoundedCombo( ArgumentException.ThrowIfNullOrWhiteSpace(id); ArgumentNullException.ThrowIfNull(preview); if ((flags & ~ImGuiComboFlags.WidthFitPreview) != 0) + { throw new ArgumentOutOfRangeException(nameof(flags), flags, "The combo flag is not supported by the editor selector."); + } ImGuiStyle* nativeStyle = NativeImGui.Raw.GetStyle(); - float width = (flags & ImGuiComboFlags.WidthFitPreview) != 0 ? NativeImGui.CalcTextSize(preview).X + NativeImGui.GetFrameHeight() + nativeStyle->FramePadding.X * 2f : NativeImGui.CalcItemWidth(); + float width = (flags & ImGuiComboFlags.WidthFitPreview) != 0 + ? NativeImGui.CalcTextSize(preview).X + NativeImGui.GetFrameHeight() + nativeStyle->FramePadding.X * 2f + : NativeImGui.CalcItemWidth(); return BeginMenuSelector(id, preview, MathF.Max(1f, width), MathF.Max(1f, width)); } @@ -53,6 +59,7 @@ public bool BeginBoundedCombo( /// Ends a combo opened by . /// public void EndBoundedCombo() => EndMenuSelector(); + /// /// Draws a compact selector control and begins a work-area-bounded menu popup. /// @@ -91,7 +98,9 @@ float minimumPopupWidth ArgumentException.ThrowIfNullOrWhiteSpace(id); ArgumentNullException.ThrowIfNull(preview); if (width <= 0f) + { throw new ArgumentOutOfRangeException(nameof(width), width, "Selector width must be positive."); + } if (minimumPopupWidth <= 0f) { throw new ArgumentOutOfRangeException(nameof(minimumPopupWidth), minimumPopupWidth, "Popup width must be positive."); @@ -106,7 +115,9 @@ float minimumPopupWidth bool active = NativeImGui.IsItemActive(); bool open = NativeImGui.IsPopupOpen(popupId); if (pressed) + { NativeImGui.OpenPopup(popupId); + } DrawMenuSelectorFrame(minimum, size, preview, hovered, active || open); Vector2 popupOrigin = new(minimum.X, minimum.Y + height); NativeImGui.SetNextWindowPos(popupOrigin, (int)ImGuiCond.Always, Vector2.Zero); @@ -120,6 +131,7 @@ float minimumPopupWidth /// Ends a selector popup opened by . /// public void EndMenuSelector() => EndMenuPopup(); + private void SetWorkAreaPopupSize( float requestedWidth, Vector2 popupOrigin, @@ -143,13 +155,22 @@ private void DrawMenuSelectorFrame( bool active ) { ImGuiStyle* nativeStyle = NativeImGui.Raw.GetStyle(); - uint background = NativeImGui.GetColorU32((int)(active ? ImGuiCol.FrameBgActive : hovered ? ImGuiCol.FrameBgHovered : ImGuiCol.FrameBg)); + uint background = NativeImGui.GetColorU32( + (int)(active ? ImGuiCol.FrameBgActive : hovered ? ImGuiCol.FrameBgHovered : ImGuiCol.FrameBg) + ); ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); Vector2 maximum = minimum + size; float arrowSlot = size.Y; float arrowMinimumX = MathF.Max(minimum.X, maximum.X - arrowSlot); ImDrawFlags previewRounding = size.X <= arrowSlot ? ImDrawFlags.RoundCornersAll : ImDrawFlags.RoundCornersLeft; - ImGui.DrawNativeFilledRectangle(drawList, minimum, new Vector2(arrowMinimumX, maximum.Y), background, nativeStyle->FrameRounding, (int)(previewRounding)); + ImGui.DrawNativeFilledRectangle( + drawList, + minimum, + new Vector2(arrowMinimumX, maximum.Y), + background, + nativeStyle->FrameRounding, + (int)(previewRounding) + ); uint arrowBackground = NativeImGui.GetColorU32((int)(active || hovered ? ImGuiCol.ButtonHovered : ImGuiCol.Button)); ImGui.DrawNativeFilledRectangle( drawList, diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Style.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Style.cs index 0f0ca7bbd..3d8a69fc6 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Style.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Style.cs @@ -1,9 +1,11 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -11,6 +13,7 @@ public sealed unsafe partial class ImGuiWidget { private float m_appliedZoom = float.NaN; private bool? m_appliedCompactMode; + /// /// Gets the centralized editor layout metrics shared by every widget and feature panel. /// @@ -34,7 +37,9 @@ internal void ApplyPendingStyle() { m_session.PrepareStyleInput(); if (float.IsNaN(m_appliedZoom) || MathF.Abs(m_appliedZoom - style.zoom) > 0.0001f || m_appliedCompactMode != style.isCompact) + { SetupStyle(); + } } private void ApplyLayoutStyle(ImGuiStyle* nativeStyle) diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs index 562167eff..fbcdf5e45 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs @@ -1,10 +1,12 @@ using System; using System.Numerics; -using Inno.Scripting.Api; using Inno.Native.ImGui; +using Inno.Scripting.Api; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -12,6 +14,7 @@ public sealed unsafe partial class ImGuiWidget { private int m_iconCatalogFrame = -1; private float m_iconCatalogWidth; + /// /// Measures the standard glyph column once per native frame in this UI session. /// @@ -23,7 +26,9 @@ public float GetIconCatalogWidth() m_session.EnsureDrawing(); int frame = NativeImGui.GetFrameCount(); if (m_iconCatalogFrame == frame) + { return m_iconCatalogWidth; + } float fontSize = NativeImGui.GetFontSize(); float width = NativeImGui.GetTextLineHeight(); foreach (var entry in EditorIconCatalog.standard) @@ -111,12 +116,16 @@ string text ) { m_session.EnsureDrawing(); if (string.IsNullOrEmpty(text)) + { throw new ArgumentException("Glyph text cannot be empty.", nameof(text)); + } int codepoint = char.ConvertToUtf32(text, 0); ImFontBaked* baked = NativeImGui.Raw.GetFontBaked(font, fontSize, -1f); ImFontGlyph* glyph = codepoint <= ushort.MaxValue ? NativeImGui.Raw.FindGlyph(baked, (ushort)codepoint) : null; if (glyph != null) + { return new Vector4(glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); + } NativeImGui.Raw.PushFont(font, fontSize); Vector2 fallbackSize = NativeImGui.CalcTextSize(text); NativeImGui.PopFont(); @@ -184,6 +193,7 @@ public bool ClickableText( string text, string? tooltip = null ) => ClickableText(id, text, GetCompactClickableTextSize(), tooltip); + /// /// Draws a text link with no button background and highlights it only through text presentation. /// @@ -221,7 +231,13 @@ string text { NativeImGui.SetMouseCursor((int)(ImGuiMouseCursor.Hand)); float underlineY = cursor.Y + size.Y; - ImGui.DrawNativeLine(NativeImGui.Raw.GetWindowDrawList(), new Vector2(cursor.X, underlineY), new Vector2(cursor.X + size.X, underlineY), packedColor, 1f); + ImGui.DrawNativeLine( + NativeImGui.Raw.GetWindowDrawList(), + new Vector2(cursor.X, underlineY), + new Vector2(cursor.X + size.X, underlineY), + packedColor, + 1f + ); } return pressed; @@ -262,8 +278,17 @@ public bool ClickableIcon( bool pressed = NativeImGui.InvisibleButton($"##clickable_icon_{id}", controlSize); bool hovered = NativeImGui.IsItemHovered(); bool active = NativeImGui.IsItemActive(); - uint color = hovered || active ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); - AddGlyphCenteredNative(NativeImGui.Raw.GetWindowDrawList(), NativeImGui.Raw.GetFont(), NativeImGui.GetFontSize(), icon, cursor + controlSize * 0.5f, color); + uint color = hovered || active + ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) + : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); + AddGlyphCenteredNative( + NativeImGui.Raw.GetWindowDrawList(), + NativeImGui.Raw.GetFont(), + NativeImGui.GetFontSize(), + icon, + cursor + controlSize * 0.5f, + color + ); if (!string.IsNullOrWhiteSpace(tooltip) && hovered && BeginMenuTooltip()) { NativeImGui.TextUnformatted(tooltip); @@ -357,7 +382,12 @@ Vector2 areaSize Vector2 cursor = NativeImGui.GetCursorScreenPos(); Vector2 textSize = NativeImGui.CalcTextSize(text); - ImGui.DrawNativeText(NativeImGui.Raw.GetWindowDrawList(), cursor + (areaSize - textSize) * 0.5f, NativeImGui.GetColorU32((int)(ImGuiCol.Text)), text); + ImGui.DrawNativeText( + NativeImGui.Raw.GetWindowDrawList(), + cursor + (areaSize - textSize) * 0.5f, + NativeImGui.GetColorU32((int)(ImGuiCol.Text)), + text + ); NativeImGui.Dummy(areaSize); } @@ -397,7 +427,10 @@ Vector2 padding } Vector2 origin = NativeImGui.GetCursorScreenPos(); - Vector2 effectivePadding = new(MathF.Min(padding.X, MathF.Max(0f, (areaSize.X - 1f) * 0.5f)), MathF.Min(padding.Y, MathF.Max(0f, (areaSize.Y - 1f) * 0.5f))); + Vector2 effectivePadding = new( + MathF.Min(padding.X, MathF.Max(0f, (areaSize.X - 1f) * 0.5f)), + MathF.Min(padding.Y, MathF.Max(0f, (areaSize.Y - 1f) * 0.5f)) + ); float wrapWidth = MathF.Max(1f, areaSize.X - effectivePadding.X * 2f); Vector2 textSize = NativeImGui.CalcTextSize(text, hide_text_after_double_hash: false, wrapWidth); Vector2 textPosition = origin + new Vector2( @@ -408,7 +441,15 @@ Vector2 padding ImGui.PushNativeClipRectangle(drawList, origin + effectivePadding, origin + areaSize - effectivePadding, 1); try { - ImGui.DrawNativeText(drawList, NativeImGui.Raw.GetFont(), NativeImGui.GetFontSize(), textPosition, NativeImGui.GetColorU32((int)(ImGuiCol.Text)), text, wrapWidth); + ImGui.DrawNativeText( + drawList, + NativeImGui.Raw.GetFont(), + NativeImGui.GetFontSize(), + textPosition, + NativeImGui.GetColorU32((int)(ImGuiCol.Text)), + text, + wrapWidth + ); } finally { @@ -498,7 +539,9 @@ float wrapWidth m_session.EnsureDrawing(); ArgumentNullException.ThrowIfNull(text); if (!float.IsFinite(wrapWidth) || wrapWidth <= 0f) + { throw new ArgumentOutOfRangeException(nameof(wrapWidth)); + } DrawWrappedText(text, wrapWidth); } @@ -585,7 +628,9 @@ private void DrawClickableTextPresentation( bool hovered, bool active ) { - uint color = hovered || active ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); + uint color = hovered || active + ? NativeImGui.ColorConvertFloat4ToU32(EditorPalette.compactControlHovered) + : NativeImGui.GetColorU32((int)(ImGuiCol.Text)); ImGui.DrawNativeText(drawList, minimum + (controlSize - textSize) * 0.5f, color, text); } @@ -622,12 +667,25 @@ bool highlight Vector2 textPos = new(cursor.X + iconSlotWidth + style->ItemInnerSpacing.X, cursor.Y); uint color = NativeImGui.GetColorU32((int)(ImGuiCol.Text)); ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); - AddGlyphCenteredNative(drawList, font, fontSize, icon, new Vector2(cursor.X + iconSlotWidth * 0.5f, cursor.Y + lineHeight * 0.5f), color); + AddGlyphCenteredNative( + drawList, + font, + fontSize, + icon, + new Vector2(cursor.X + iconSlotWidth * 0.5f, cursor.Y + lineHeight * 0.5f), + color + ); ImGui.DrawNativeText(drawList, textPos, color, text); if (highlight) { float lineY = cursor.Y + NativeImGui.GetTextLineHeight() - this.style.textDecorationOffset; - ImGui.DrawNativeLine(drawList, new Vector2(cursor.X, lineY), new Vector2(textPos.X + textSize.X, lineY), color, this.style.borderSize); + ImGui.DrawNativeLine( + drawList, + new Vector2(cursor.X, lineY), + new Vector2(textPos.X + textSize.X, lineY), + color, + this.style.borderSize + ); } NativeImGui.Dummy(new Vector2(iconSlotWidth + style->ItemInnerSpacing.X + textSize.X, lineHeight)); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs index b2bc23807..533a1a3d4 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs @@ -2,9 +2,11 @@ using System.Collections.Generic; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; + /// /// Provides reusable editor controls and rendering helpers built on the native ImGui API. /// @@ -18,7 +20,12 @@ public sealed unsafe partial class ImGuiWidget private List m_lineSegments => GetTreeWindowState().lineSegments; private Dictionary m_hasNextSiblingById => GetTreeWindowState().hasNextSiblingById; private Dictionary m_openStatesById => GetTreeWindowState().openStatesById; - private int m_lastFrame { get => GetTreeWindowState().lastFrame; set => GetTreeWindowState().lastFrame = value; } + + private int m_lastFrame + { + get => GetTreeWindowState().lastFrame; + set => GetTreeWindowState().lastFrame = value; + } /// /// Draws a full-width interactive tree row whose non-leaf content toggles expansion when @@ -46,10 +53,14 @@ in TreeNodeOptions options ) { m_session.EnsureDrawing(); if (options.depth < 0) + { throw new ArgumentOutOfRangeException(nameof(options), "A flattened tree depth cannot be negative."); + } float indentation = (options.depth ?? 0) * NativeImGui.Raw.GetStyle()->IndentSpacing; if (indentation > 0f) + { NativeImGui.Indent(indentation); + } try { return DrawTreeRow(id, onDraw, options); @@ -57,7 +68,9 @@ in TreeNodeOptions options finally { if (indentation > 0f) + { NativeImGui.Unindent(indentation); + } } } @@ -120,7 +133,9 @@ bool open m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(id); if (m_openStatesById.GetValueOrDefault(id) == open) + { return; + } m_openStatesById[id] = open; GetTreeWindowState().expansionRevision++; } @@ -139,12 +154,14 @@ in TreeNodeOptions options Vector2 cursor = NativeImGui.GetCursorScreenPos(); TreeWidgetWindowState state = GetTreeWindowState(); bool visible = cursor.Y <= window->ClipRect.Max.Y - && cursor.Y + NativeImGui.GetFrameHeight() >= window->ClipRect.Min.Y; + && cursor.Y + NativeImGui.GetFrameHeight() >= window->ClipRect.Min.Y; bool drawContent = visible || options.requestFocus || options.keepContentActive - || state.activeContentOwner == id; + || state.activeContentOwner == id; uint activeBefore = NativeImGui.Raw.GetCurrentContext()->ActiveId; if (!drawContent) + { return DrawTreeNode(id, onDraw, options, isLeaf, null, false); + } ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); NativeImGui.Raw.ChannelsSplit(drawList, 2); NativeImGui.Raw.ChannelsSetCurrent(drawList, 1); @@ -186,30 +203,44 @@ bool drawContent // Each disclosure, content row and overlay owns its own hit region. ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags.None; if (isLeaf) + { flags |= ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.NoTreePushOnOpen; + } else + { flags |= ImGuiTreeNodeFlags.OpenOnArrow; + } if (options.depth is not null) + { flags |= ImGuiTreeNodeFlags.NoTreePushOnOpen; + } int depth = options.depth ?? Math.Max(0, NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth); PruneTreeNodeStack(depth); bool hasNextSibling = TrackSiblingState(id, depth); if (drawContent && !options.hideGuideLines) + { DrawTreeGuideLines(nodeCursor, hasNextSibling, !isLeaf); + } if (drawContent) + { PushTransparentTreeNodeHeaderColors(); + } bool isOpen; try { if (options.requestFocus && NativeImGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows)) + { NativeImGui.SetKeyboardFocusHere(); + } isOpen = NativeImGui.TreeNodeEx($"##{id}", (int)(flags)); GetTreeWindowState().navigationItemIds.Add(NativeImGui.Raw.GetCurrentContext()->LastItemData.ID); } finally { if (drawContent) + { NativeImGui.PopStyleColor(3); + } } float nativeRowMaxY = NativeImGui.GetItemRectMax().Y; @@ -217,37 +248,80 @@ bool drawContent { ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); if (isOpen && !isLeaf) - m_treeNodeStack.Add(new TreeWidgetNodeState { id = id, cursor = nodeCursor, rowMaxY = nativeRowMaxY, hasNextSibling = hasNextSibling }); - return new TreeNodeResult(isOpen && !isLeaf, false, false, false, - new Vector2(window->Pos.X, nodeCursor.Y), new Vector2(window->WorkRect.Max.X, nativeRowMaxY), - new Vector2(nodeCursor.X + NativeImGui.GetTreeNodeToLabelSpacing(), nodeCursor.Y), false); + { + m_treeNodeStack.Add( + new TreeWidgetNodeState { id = id, cursor = nodeCursor, rowMaxY = nativeRowMaxY, hasNextSibling = hasNextSibling } + ); + } + return new TreeNodeResult( + isOpen && !isLeaf, + false, + false, + false, + new Vector2(window->Pos.X, nodeCursor.Y), + new Vector2(window->WorkRect.Max.X, nativeRowMaxY), + new Vector2(nodeCursor.X + NativeImGui.GetTreeNodeToLabelSpacing(), nodeCursor.Y), + false + ); } try { if (!isLeaf && NativeImGui.IsItemToggledOpen()) + { SetTreeNodeOpen(id, isOpen); - TreeWidgetHighlightRect contentRect = DrawTreeNodeContentContainer(id, nodeCursor, nativeRowMaxY, onDraw, options.drawViewportOverlay, out Vector2 interactionMin); + } + TreeWidgetHighlightRect contentRect = DrawTreeNodeContentContainer( + id, + nodeCursor, + nativeRowMaxY, + onDraw, + options.drawViewportOverlay, + out Vector2 interactionMin + ); bool hovered = NativeImGui.IsItemHovered((int)(ImGuiHoveredFlags.AllowWhenOverlappedByItem)); bool clicked = hovered && NativeImGui.IsItemClicked((int)(ImGuiMouseButton.Left)); bool doubleClicked = hovered && NativeImGui.IsMouseDoubleClicked((int)(ImGuiMouseButton.Left)); if (!isLeaf && doubleClicked) + { SetTreeNodeOpen(id, !isOpen); + } bool showHoverHighlight = hovered && !options.suppressHoverHighlight && NativeImGui.Raw.IsDragDropActive() == 0; if (options.selected || showHoverHighlight) - DrawTreeRowBackground(drawList, contentRect, NativeImGui.GetColorU32((int)(options.selected ? ImGuiCol.Header : ImGuiCol.HeaderHovered))); + { + DrawTreeRowBackground( + drawList, + contentRect, + NativeImGui.GetColorU32((int)(options.selected ? ImGuiCol.Header : ImGuiCol.HeaderHovered)) + ); + } else if (options.showBackground) + { DrawTreeRowBackground(drawList, contentRect, NativeImGui.ColorConvertFloat4ToU32(options.backgroundColor)); + } if (isOpen && !isLeaf) { - m_treeNodeStack.Add(new TreeWidgetNodeState { id = id, cursor = nodeCursor, rowMaxY = contentRect.max.Y, hasNextSibling = hasNextSibling }); + m_treeNodeStack.Add( + new TreeWidgetNodeState { id = id, cursor = nodeCursor, rowMaxY = contentRect.max.Y, hasNextSibling = hasNextSibling } + ); } - return new TreeNodeResult(isOpen && !isLeaf, clicked, doubleClicked, hovered, contentRect.min, contentRect.max, interactionMin, true); + return new TreeNodeResult( + isOpen && !isLeaf, + clicked, + doubleClicked, + hovered, + contentRect.min, + contentRect.max, + interactionMin, + true + ); } catch { if (isOpen && !isLeaf && options.depth is null) + { NativeImGui.TreePop(); + } throw; } } @@ -329,7 +403,9 @@ private void DrawTreeNodeViewportOverlay( Action? drawViewportOverlay ) { if (drawViewportOverlay is null) + { return; + } float contentBoundaryX = window->DC.CursorMaxPos.X; float idealBoundaryX = window->DC.IdealMaxPos.X; try @@ -354,7 +430,9 @@ private void BeginTreeFrameIfNeeded() { int frame = NativeImGui.GetFrameCount(); if (frame == m_lastFrame) + { return; + } TreeWidgetWindowState state = GetTreeWindowState(); state.treeNodeStack.Clear(); state.lastNodeIdsByDepth.Clear(); @@ -371,7 +449,9 @@ private void BeginTreeFrameIfNeeded() private void PruneTreeNodeStack(int nativeDepth) { while (m_treeNodeStack.Count > nativeDepth) + { m_treeNodeStack.RemoveAt(m_treeNodeStack.Count - 1); + } } private bool TrackSiblingState( @@ -380,14 +460,20 @@ int depth ) { bool hasNextSibling = m_hasNextSiblingById.TryGetValue(id, out bool cachedHasNextSibling) && cachedHasNextSibling; while (m_lastNodeIdsByDepth.Count <= depth) + { m_lastNodeIdsByDepth.Add(string.Empty); + } string previousId = m_lastNodeIdsByDepth[depth]; if (!string.IsNullOrEmpty(previousId) && !string.Equals(previousId, id, StringComparison.Ordinal)) + { m_hasNextSiblingById[previousId] = true; + } m_hasNextSiblingById[id] = false; m_lastNodeIdsByDepth[depth] = id; for (int i = depth + 1; i < m_lastNodeIdsByDepth.Count; i++) + { m_lastNodeIdsByDepth[i] = string.Empty; + } return hasNextSibling; } @@ -397,7 +483,9 @@ private void DrawTreeGuideLines( bool hasDisclosureArrow ) { if (m_treeNodeStack.Count == 0) + { return; + } ImGuiStyle* style = NativeImGui.Raw.GetStyle(); float textLineHeight = NativeImGui.GetTextLineHeight(); float lineOverlap = this.style.treeGuideLineOverlap; @@ -426,7 +514,9 @@ bool hasDisclosureArrow float branchStartY = MathF.Max(parentState.rowMaxY, nodeCursor.Y); AddTreeLine(new Vector2(branchX, branchStartY), new Vector2(branchX, hasNextSibling ? rowMaxY : rowCenterY)); if (targetX > branchX) + { AddTreeLine(new Vector2(branchX, rowCenterY), new Vector2(targetX, rowCenterY)); + } } private void AddTreeLine( @@ -439,7 +529,13 @@ Vector2 to to = SnapTreeLinePoint(to) }; m_lineSegments.Add(line); - ImGui.DrawNativeLine(NativeImGui.Raw.GetWindowDrawList(), line.from, line.to, NativeImGui.ColorConvertFloat4ToU32(EditorPalette.treeGuide), this.style.borderSize); + ImGui.DrawNativeLine( + NativeImGui.Raw.GetWindowDrawList(), + line.from, + line.to, + NativeImGui.ColorConvertFloat4ToU32(EditorPalette.treeGuide), + this.style.borderSize + ); } private Vector2 SnapTreeLinePoint(Vector2 point) @@ -484,6 +580,7 @@ public readonly struct TreeNodeOptions /// Explicit-depth rows never push a native tree scope; callers must not call TreePop for them. /// public int? depth { get; init; } + /// /// Gets whether this row should receive keyboard focus during this submission when its tree window is focused. /// @@ -498,26 +595,32 @@ public readonly struct TreeNodeOptions /// Gets whether the row is selected. /// public bool selected { get; init; } + /// /// Gets whether the row has no expandable children. /// public bool isLeaf { get; init; } + /// /// Gets whether a custom background is drawn behind an unselected row. /// public bool showBackground { get; init; } + /// /// Gets the custom background color used when is enabled. /// public Vector4 backgroundColor { get; init; } + /// /// Gets whether the row keeps its configured background while hovered. /// public bool suppressHoverHighlight { get; init; } + /// /// Gets whether ancestor and branch guide lines are omitted for this row. /// public bool hideGuideLines { get; init; } + /// /// Gets the callback that draws controls fixed to the current viewport without extending the /// tree's horizontal content boundary. @@ -559,27 +662,33 @@ bool isSubmitted /// Gets whether child content should be rendered. /// public bool isOpen { get; } + /// /// Gets whether the content row was clicked. /// public bool isClicked { get; } + /// /// Gets whether the content row was double-clicked. Double-clicking a non-leaf content row /// also toggles its retained expansion state for the next frame. /// public bool isDoubleClicked { get; } + /// /// Gets whether the full row is hovered. /// public bool isHovered { get; } + /// /// Gets the row minimum screen coordinate. /// public Vector2 min { get; } + /// /// Gets the row maximum screen coordinate. /// public Vector2 max { get; } + /// /// Gets the minimum screen coordinate of the row's interactive content, excluding tree indentation. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs index a62cd51f7..287a90b6f 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs @@ -1,6 +1,7 @@ using System; using System.Numerics; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; @@ -39,13 +40,17 @@ public void Trend( m_session.EnsureDrawing(); ArgumentException.ThrowIfNullOrWhiteSpace(label); if (offset < 0 || (values.Length == 0 ? offset != 0 : offset >= values.Length)) + { throw new ArgumentOutOfRangeException(nameof(offset)); + } float maximum = 0f; float minimum = 0f; foreach (float value in values) { if (!float.IsFinite(value)) + { throw new ArgumentException("Trend samples must be finite.", nameof(values)); + } maximum = MathF.Max(maximum, value); minimum = MathF.Min(minimum, value); } @@ -65,7 +70,9 @@ public void Trend( float normalized = (float)(((double)value - minimum) / range); Vector2 point = origin + new Vector2(x * size.X, (1f - normalized) * size.Y); if (index > 0) + { draw.Line(previous, point, color); + } previous = point; } } diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs index 839cca60a..7457e9966 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs @@ -1,15 +1,17 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Shaders; using System; using System.Linq; using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; using Inno.Editor.Inspection; +using Inno.Editor.Shaders; using Inno.Rendering; -using Ui = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using Ui = Inno.Editor.ImGui.ImGui; + namespace Inno.Editor.Shaders.ImGui; + [InspectionDrawer(typeof(MaterialAsset))] internal sealed class MaterialInspectionDrawer(IInspectionIconProvider icons) : InspectionDrawer { @@ -34,11 +36,12 @@ protected override string GetIcon( InspectionDrawContext context, MaterialAsset target ) => context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetFileSystemEntry( - target.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; + && documents is not null + && documents.assets.TryGetFileSystemEntry( + target.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; + /// /// Binds a caller-visible label to the current inspection target. /// @@ -55,6 +58,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, MaterialAsset target ) => (target.name, null); + /// /// Renders the header presentation for the current editor frame. /// @@ -69,7 +73,9 @@ protected override void DrawHeader( MaterialAsset target ) { if (context.interactions.TryGetModule(out var documents) && documents is not null) + { MaterialInspector.DrawHeader(context, documents, documents.Open(target)); + } } /// @@ -86,7 +92,9 @@ protected override void Draw( MaterialAsset target ) { if (context.interactions.TryGetModule(out var documents) && documents is not null) + { MaterialInspector.Draw(context, documents, documents.Open(target)); + } } } @@ -114,6 +122,7 @@ protected override string GetIcon( InspectionDrawContext context, AssetFileEntry target ) => icons.GetIcon(target); + /// /// Checks whether this drawer supports the selected Inspector target. /// @@ -123,7 +132,9 @@ AssetFileEntry target /// /// when the documented condition is satisfied; otherwise, . /// - protected override bool CanInspect(AssetFileEntry target) => !target.isDirectory && target.extension.Equals(".imaterial", StringComparison.OrdinalIgnoreCase); + protected override bool CanInspect(AssetFileEntry target) + => !target.isDirectory && target.extension.Equals(".imaterial", StringComparison.OrdinalIgnoreCase); + /// /// Binds a caller-visible label to the current inspection target. /// @@ -140,6 +151,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, AssetFileEntry target ) => (target.nameWithoutExtension, null); + /// /// Renders the header presentation for the current editor frame. /// @@ -154,7 +166,9 @@ protected override void DrawHeader( AssetFileEntry target ) { if (context.interactions.TryGetModule(out var documents) && documents is not null) + { MaterialInspector.DrawHeader(context, documents, documents.OpenDraft(target.assetPath)); + } } /// @@ -171,7 +185,9 @@ protected override void Draw( AssetFileEntry target ) { if (context.interactions.TryGetModule(out var documents) && documents is not null) + { MaterialInspector.Draw(context, documents, documents.OpenDraft(target.assetPath)); + } } } @@ -185,10 +201,14 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft EditorUI.current.widgets.Disabled(draft.readOnly, () => { if (Ui.Button("Save")) + { _ = context.interactions.documents.Save(draft.documentId); + } Ui.SameLine(0f, -1f); if (Ui.Button("Revert")) + { _ = context.interactions.documents.Revert(draft.documentId); + } }); } @@ -205,11 +225,17 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft if (EditorUI.current.widgets.SectionHeader("Preview", "Shows an isolated preview of the current Material draft.")) { if (material.shader is null || material.shader.isMissing) + { EditorUI.current.widgets.Hint("Choose an available Shader to preview this Material."); + } else if (context.interactions.TryGetModule(out var shaderPreviews) && shaderPreviews is not null) + { shaderPreviews.DrawMaterial(draft.id, material, MathF.Max(1f, MathF.Min(256f, Ui.GetContentRegionAvailable().X))); + } else + { EditorUI.current.widgets.Hint("Material preview is unavailable."); + } } bool materialOpen = EditorUI.current.widgets.SectionHeader( @@ -218,11 +244,17 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft ); if (materialOpen) { - EditorUI.current.widgets.Hint(draft.isDirty ? "Unsaved changes · Scene/Game unchanged" : "Saved · compilation and import are separate"); + EditorUI.current.widgets.Hint( + draft.isDirty ? "Unsaved changes · Scene/Game unchanged" : "Saved · compilation and import are separate" + ); if (draft.error.Length != 0) + { EditorUI.current.widgets.Hint(draft.error); + } if (draft.readOnly) + { EditorUI.current.widgets.Hint("Installed material · copy to the project to edit"); + } Draw("shader", "Shader", typeof(ShaderAsset), () => material.shader, value => material.shader = (ShaderAsset? )value); } @@ -230,7 +262,11 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft if (material.shader is null || material.shader.isMissing || definition is null) { if (materialOpen) - EditorUI.current.widgets.Hint("Choose an available Shader. Existing overrides are retained until its interface can be resolved."); + { + EditorUI.current.widgets.Hint( + "Choose an available Shader. Existing overrides are retained until its interface can be resolved." + ); + } return; } @@ -243,14 +279,19 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft if (materialOpen) { Ui.SameLine(0f, -1f); - if (Ui.SmallButton("Locate Shader") && documents.assets.TryGetFileSystemEntry(material.shader.assetPath, out AssetFileEntry shaderEntry)) + if (Ui.SmallButton("Locate Shader") + && documents.assets.TryGetFileSystemEntry(material.shader.assetPath, out AssetFileEntry shaderEntry) + ) { context.interactions.SetSelection(shaderEntry); + } } if (materialOpen && (definition.techniques.Length > 1 || material.techniqueId.isValid)) { - if (EditorUI.current.widgets.BeginBoundedCombo("##technique", material.techniqueId.isValid ? material.techniqueId.value : "Automatic")) - { + if (EditorUI.current.widgets.BeginBoundedCombo( + "##technique", + material.techniqueId.isValid ? material.techniqueId.value : "Automatic" + )) { try { if (Ui.Selectable("Automatic", !material.techniqueId.isValid) && !draft.readOnly) @@ -260,11 +301,13 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft } foreach (ShaderTechniqueDefinition technique in definition.techniques) + { if (Ui.Selectable(technique.id.value, material.techniqueId == technique.id) && !draft.readOnly) { material.techniqueId = technique.id; documents.Replace(draft.id, material); } + } } finally { @@ -282,11 +325,19 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft int visibleParameters = 0; foreach (ShaderPropertyDefinition property in definition.properties.Where(IsEditable)) { - ShaderParameterPresentation presentation = documents.Presentation(material.shader, property.id, out string presentationError); + ShaderParameterPresentation presentation = documents.Presentation( + material.shader, + property.id, + out string presentationError + ); if (presentationError.Length != 0) + { EditorUI.current.widgets.Hint("Parameter presentation unavailable: " + presentationError); + } if (!presentation.visible) + { continue; + } visibleParameters++; if (presentation.group != currentGroup) { @@ -295,12 +346,18 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft } if (!groupOpen) + { continue; + } bool overridden = material.TryGet(property.id, out MaterialValue value); if (overridden && !ShaderPropertyInspector.Compatible(property.type, value.kind)) + { continue; + } if (!overridden) + { value = property.defaultValue; + } Ui.PushId(property.id.value); try { @@ -345,7 +402,9 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft } if (parametersOpen && visibleParameters == 0 && definition.keywords.Length == 0) + { EditorUI.current.widgets.Hint("No editable parameters."); + } if (parametersOpen && material.properties.Count != 0 && !draft.readOnly && Ui.Button("Reset all overrides")) { material.ReplaceProperties([]); @@ -356,14 +415,22 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft { string selected = keyword.options.FirstOrDefault(option => material.keywords.Contains(option)) ?? "None"; if (!EditorUI.current.widgets.BeginBoundedCombo(keyword.id, selected)) + { continue; + } try { if (Ui.Selectable("None", selected == "None")) + { SetOption(null); + } foreach (string option in keyword.options) + { if (Ui.Selectable(option, selected == option)) + { SetOption(option); + } + } } finally { @@ -373,21 +440,34 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft void SetOption(string? next) { if (draft.readOnly) + { return; + } foreach (string option in keyword.options) + { material.SetKeyword(option, option == next); + } documents.Replace(draft.id, material); } } - MaterialPropertyEntry[] orphaned = material.properties.Where(entry => !definition.properties.Any(property => property.id == entry.id && IsEditable(property) && ShaderPropertyInspector.Compatible(property.type, entry.value.kind))).ToArray(); + MaterialPropertyEntry[] orphaned = material.properties + .Where( + entry => !definition.properties.Any( + property => ( + property.id == entry.id + && IsEditable(property) + && ShaderPropertyInspector.Compatible(property.type, entry.value.kind) + ) + ) + ) + .ToArray(); if (orphaned.Length != 0) { if (EditorUI.current.widgets.SectionHeader( "Unresolved Overrides", "These values were retained after an interface change. Remove them explicitly or restore a compatible Shader before publishing." - )) - { + )) { foreach (MaterialPropertyEntry entry in orphaned) { Ui.Text(entry.id.value + " · " + entry.value.kind); @@ -401,14 +481,15 @@ void SetOption(string? next) } ShaderPropertyDefinition[] passBindings = definition.properties.Where(property => !IsEditable(property)).ToArray(); - string[] unknownKeywords = material.keywords.Where(value => !definition.keywords.Any(keyword => keyword.options.Contains(value))).ToArray(); + string[] unknownKeywords = material.keywords + .Where(value => !definition.keywords.Any(keyword => keyword.options.Contains(value))) + .ToArray(); if (unknownKeywords.Length != 0) { if (EditorUI.current.widgets.SectionHeader( "Unresolved Keywords", "These overrides no longer belong to the Shader interface. They remain until explicitly removed." - )) - { + )) { foreach (string keyword in unknownKeywords) { Ui.Text(keyword); @@ -423,10 +504,14 @@ void SetOption(string? next) if (passBindings.Length != 0) { - if (EditorUI.current.widgets.SectionHeader("Pipeline Bindings", "These resources are supplied by the Render Pass, not by this Material.")) - { + if (EditorUI.current.widgets.SectionHeader( + "Pipeline Bindings", + "These resources are supplied by the Render Pass, not by this Material." + )) { foreach (ShaderPropertyDefinition property in passBindings) + { EditorUI.current.widgets.Hint(property.displayName + " · " + property.type + " · " + property.bindingOwner); + } } } } @@ -441,11 +526,23 @@ void Draw( Type type, Func getter, Action setter - ) => context.properties.DrawValue(context.editorContext, draft, "material." + path, label, type, getter, setter, edits, draft.readOnly); + ) => context.properties.DrawValue( + context.editorContext, + draft, + "material." + path, + label, + type, + getter, + setter, + edits, + draft.readOnly + ); } - private static bool IsEditable(ShaderPropertyDefinition property) => property.bindingOwner == ShaderPropertyBindingOwner.Material - && property.bindingKind is ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture; + private static bool IsEditable(ShaderPropertyDefinition property) + => property.bindingOwner == ShaderPropertyBindingOwner.Material + && property.bindingKind is ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture; + private sealed class DraftEdits( MaterialDocuments documents, Inno.Editor.Assets.AssetDraftDocuments.Draft draft, diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs index fc5373a7d..cc6ddab17 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs @@ -1,19 +1,21 @@ -using Inno.Editor.ImGui; -using Inno.Editor.Interactions; -using Inno.Core.Identity; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Shaders; using System; using System.Collections.Generic; using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; +using Inno.Editor.ImGui; using Inno.Editor.Inspection; +using Inno.Editor.Interactions; +using Inno.Editor.Shaders; using Inno.Rendering; -using ImGuiApi = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using ImGuiApi = Inno.Editor.ImGui.ImGui; + namespace Inno.Editor.Shaders.ImGui; + [InspectionDrawer(typeof(EditorSelectionSnapshot), priority: 100, conditional: true)] internal sealed class MaterialSelectionDrawer( IInspectionIconProvider icons, @@ -43,17 +45,14 @@ EditorSelectionSnapshot target ) { Guid id = GetAssetIds(target).FirstOrDefault(); return id != Guid.Empty - && context.interactions.TryGetModule(out var documents) - && documents is not null - && documents.assets.TryGetInfo( - id, - out AssetInfo? info - ) - && info is not null - && documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; + && context.interactions.TryGetModule(out var documents) + && documents is not null + && documents.assets.TryGetInfo(id, out AssetInfo? info) + && info is not null + && documents.assets.TryGetFileSystemEntry( + info.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; } /// @@ -72,6 +71,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, EditorSelectionSnapshot target ) => (GetAssetIds(target).Count + " Assets", null); + /// /// Renders the header presentation for the current editor frame. /// @@ -86,7 +86,9 @@ protected override void DrawHeader( EditorSelectionSnapshot target ) { if (!TryOpenDrafts(context, target, out MaterialDocuments? documents, out var drafts)) + { return; + } bool readOnly = drafts.Any(value => value.readOnly); ImGuiApi.BeginDisabled(readOnly); try @@ -95,7 +97,9 @@ EditorSelectionSnapshot target { EditorUiSession.current.widgets.CommitEdits(); foreach (var draft in drafts) + { _ = context.interactions.documents.Save(draft.documentId); + } } ImGuiApi.SameLine(0f, -1f); @@ -104,7 +108,9 @@ EditorSelectionSnapshot target EditorUiSession.current.widgets.CommitEdits(); using var transaction = context.interactions.history.BeginTransaction("Revert Materials"); foreach (var draft in drafts) + { _ = context.interactions.documents.Revert(draft.documentId); + } transaction.Commit(); } } @@ -142,9 +148,13 @@ EditorSelectionSnapshot target { EditorUI.current.widgets.Hint("Save runs per document. Unsaved edits do not change Scene/Game."); if (readOnly) + { EditorUI.current.widgets.Hint("Selection includes installed read-only content. Copy it to the project before editing."); + } foreach (var draft in drafts.Where(value => value.error.Length != 0)) + { EditorUI.current.widgets.Hint(draft.path.localPath + ": " + draft.error); + } var edits = new SelectionEdits(owner, materials); MaterialAsset first = materials.Values.First(); bool selectionOpen = EditorUI.current.widgets.SectionHeader( @@ -154,22 +164,48 @@ EditorSelectionSnapshot target if (selectionOpen) { if (materials.Values.Any(value => value.shader?.identity.persistentId != first.shader?.identity.persistentId)) - EditorUI.current.widgets.Hint("Shader · Mixed values"); - context.properties.DrawValue(context.editorContext, target, "materials.shader", "Shader", typeof(ShaderAsset), () => first.shader, value => { - foreach (MaterialAsset material in materials.Values) - material.shader = (ShaderAsset? )value; - }, edits, readOnly); + EditorUI.current.widgets.Hint("Shader · Mixed values"); + } + context.properties.DrawValue( + context.editorContext, + target, + "materials.shader", + "Shader", + typeof(ShaderAsset), + () => first.shader, + value => + { + foreach (MaterialAsset material in materials.Values) + { + material.shader = (ShaderAsset? )value; + } + }, + edits, + readOnly + ); } if (first.shader is null || first.shader.isMissing || first.shader.definition is not { } firstDefinition) { if (selectionOpen) + { EditorUI.current.widgets.Hint("A selected Shader is unavailable."); + } return; } - ShaderTechniqueId[] commonTechniques = firstDefinition.techniques.Select(value => value.id).Where(id => materials.Values.All(material => material.shader is { isMissing: false, definition: { } definition } && definition.techniques.Any(technique => technique.id == id))).ToArray(); + ShaderTechniqueId[] commonTechniques = firstDefinition.techniques + .Select(value => value.id) + .Where( + id => materials.Values.All( + material => ( + material.shader is { isMissing: false, definition: { } definition } + && definition.techniques.Any(technique => technique.id == id) + ) + ) + ) + .ToArray(); bool mixedTechnique = materials.Values.Any(value => value.techniqueId != first.techniqueId); if (selectionOpen && (commonTechniques.Length > 1 || materials.Values.Any(value => value.techniqueId.isValid))) { @@ -179,10 +215,16 @@ EditorSelectionSnapshot target try { if (ImGuiApi.Selectable("Automatic", !mixedTechnique && !first.techniqueId.isValid)) + { SetTechnique(default); + } foreach (ShaderTechniqueId technique in commonTechniques) + { if (ImGuiApi.Selectable(technique.value, !mixedTechnique && first.techniqueId == technique)) + { SetTechnique(technique); + } + } } finally { @@ -193,20 +235,34 @@ EditorSelectionSnapshot target foreach (ShaderKeywordDefinition keyword in selectionOpen ? firstDefinition.keywords : []) { - if (!materials.Values.All(material => material.shader is { isMissing: false, definition: { } definition } && definition.keywords.Any(value => value.id == keyword.id && value.options.SequenceEqual(keyword.options)))) + if (!materials.Values.All( + material => ( + material.shader is { isMissing: false, definition: { } definition } + && definition.keywords.Any(value => value.id == keyword.id && value.options.SequenceEqual(keyword.options)) + ) + )) { continue; + } string Option(MaterialAsset material) => keyword.options.FirstOrDefault(material.keywords.Contains) ?? "None"; string selected = Option(first); bool mixed = materials.Values.Any(material => Option(material) != selected); if (!EditorUI.current.widgets.BeginBoundedCombo(keyword.id, mixed ? "Mixed values" : selected)) + { continue; + } try { if (ImGuiApi.Selectable("None", !mixed && selected == "None")) + { SetOption(null); + } foreach (string option in keyword.options) + { if (ImGuiApi.Selectable(option, !mixed && selected == option)) + { SetOption(option); + } + } } finally { @@ -216,8 +272,12 @@ EditorSelectionSnapshot target void SetOption(string? next) { foreach (MaterialAsset material in materials.Values) + { foreach (string option in keyword.options) + { material.SetKeyword(option, option == next); + } + } owner.ReplaceMany(materials); } } @@ -231,21 +291,34 @@ void SetOption(string? next) foreach (ShaderPropertyDefinition property in firstDefinition.properties) { if (property.bindingOwner != ShaderPropertyBindingOwner.Material - || property.bindingKind is not (ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture)) + || property.bindingKind is not (ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture) + ) { continue; + } var values = new List(); ShaderParameterPresentation presentation = owner.Presentation(first.shader, property.id, out string presentationError); if (presentationError.Length != 0) + { EditorUI.current.widgets.Hint("Parameter presentation unavailable: " + presentationError); + } if (!presentation.visible) + { continue; + } bool compatible = true; foreach (MaterialAsset material in materials.Values) { - ShaderPropertyDefinition[] declarations = material.shader is { isMissing: false } shader ? shader.definition?.properties ?? [] : []; + ShaderPropertyDefinition[] declarations = material.shader is { isMissing: false } shader + ? shader.definition?.properties ?? [] + : []; int index = Array.FindIndex( declarations, - value => value.id == property.id && value.type == property.type && value.bindingKind == property.bindingKind && value.bindingOwner == property.bindingOwner + value => ( + value.id == property.id + && value.type == property.type + && value.bindingKind == property.bindingKind + && value.bindingOwner == property.bindingOwner + ) ); if (index < 0) { @@ -291,7 +364,9 @@ void SetOption(string? next) } if (!compatible) + { continue; + } if (presentation.group != currentGroup) { currentGroup = presentation.group; @@ -299,30 +374,43 @@ void SetOption(string? next) } if (!groupOpen) + { continue; + } bool mixed = values.Skip(1).Any(value => !value.Equals(values[0])); ImGuiApi.PushId(property.id.value); try { if (mixed) + { EditorUI.current.widgets.Hint(property.displayName + " · Mixed values (editing applies to all selected Materials)"); + } ShaderPropertyInspector.Draw(context, target, "materials." + property.id.value, property, values[0], value => { int selectedIndex = 0; foreach (MaterialAsset material in materials.Values) - material.Set(property.id, ShaderPropertyInspector.ApplyEdit(property.type, values[0], value, values[selectedIndex++])); + { + material.Set( + property.id, + ShaderPropertyInspector.ApplyEdit(property.type, values[0], value, values[selectedIndex++]) + ); + } }, edits, readOnly, presentation); if (mixed && ImGuiApi.SmallButton("Use First Value for Selection")) { foreach (MaterialAsset material in materials.Values) + { material.Set(property.id, values[0]); + } owner.ReplaceMany(materials); } if (ImGuiApi.SmallButton("Reset Selected Overrides")) { foreach (MaterialAsset material in materials.Values) + { material.ReplaceProperties(material.properties.Where(value => value.id != property.id).ToArray()); + } owner.ReplaceMany(materials); } } @@ -332,17 +420,23 @@ void SetOption(string? next) } } - if (parametersOpen && materials.Values.Any(value => value.properties.Count != 0) && ImGuiApi.Button("Reset All Selected Overrides")) - { + if (parametersOpen + && materials.Values.Any(value => value.properties.Count != 0) + && ImGuiApi.Button("Reset All Selected Overrides") + ) { foreach (MaterialAsset material in materials.Values) + { material.ReplaceProperties([]); + } owner.ReplaceMany(materials); } void SetTechnique(ShaderTechniqueId technique) { foreach (MaterialAsset material in materials.Values) + { material.techniqueId = technique; + } owner.ReplaceMany(materials); } } @@ -354,30 +448,32 @@ void SetTechnique(ShaderTechniqueId technique) } /// - protected override bool CanInspect(EditorSelectionSnapshot target) => target.identities.Count > 1 && GetAssetIds(target).Count == target.identities.Count; + protected override bool CanInspect(EditorSelectionSnapshot target) + => target.identities.Count > 1 && GetAssetIds(target).Count == target.identities.Count; + private IReadOnlyList GetAssetIds(EditorSelectionSnapshot target) { if (!interactions.TryGetModule(out var materials) || materials is null) + { return Array.Empty(); + } var ids = new List(target.identities.Count); var entries = new List(target.identities.Count); target.CopyTargets(interactions, entries); if (entries.Count != target.identities.Count) + { return Array.Empty(); + } entries.Reverse(); foreach (AssetFileEntry entry in entries) { if (entry.isDirectory - || !entry.extension.Equals( - ".imaterial", - StringComparison.OrdinalIgnoreCase - ) - || !materials.assets.TryGetInfo( - entry.assetPath, - out AssetInfo? info - ) - || info is null) + || !entry.extension.Equals(".imaterial", StringComparison.OrdinalIgnoreCase) + || !materials.assets.TryGetInfo(entry.assetPath, out AssetInfo? info) + || info is null + ) { return Array.Empty(); + } ids.Add(info.persistentId); } @@ -392,23 +488,18 @@ out List.Draft> drafts ) { drafts = []; if (!context.interactions.TryGetModule(out documents) || documents is null) + { return false; + } foreach (Guid id in GetAssetIds(target)) { - if (!documents.assets.TryGetInfo( - id, - out AssetInfo? info - ) + if (!documents.assets.TryGetInfo(id, out AssetInfo? info) || info is null - || !documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - ) - || !entry.extension.Equals( - ".imaterial", - StringComparison.OrdinalIgnoreCase - )) + || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) + || !entry.extension.Equals(".imaterial", StringComparison.OrdinalIgnoreCase) + ) { return false; + } var draft = documents.OpenDraft(info.assetPath); drafts.Add(draft); } diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs index 4b63d7825..b15ea1e28 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs @@ -1,12 +1,14 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Shaders; using System; using Inno.Core.Mathematics; using Inno.Editor.Inspection; +using Inno.Editor.Shaders; using Inno.Rendering; using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; + namespace Inno.Editor.Shaders.ImGui; + /// /// Uses the shared Inspector drawers for both Shader defaults and Material overrides. /// @@ -69,15 +71,30 @@ public static void Draw( maximum: property.type == ShaderPropertyType.Float && presentation?.hasRange == true ? presentation.maximum : null ); if (property.type == ShaderPropertyType.Color) + { EditorUI.current.widgets.Hint("Linear RGBA · HDR values are preserved"); + } if (property.bindingKind == ShaderPropertyBindingKind.SampledTexture) - context.properties.DrawValue(context.editorContext, owner, path + ".sampler", "Sampler", typeof(RenderSamplerState), () => value.sampler, next => + { + context.properties.DrawValue( + context.editorContext, + owner, + path + + ".sampler", + "Sampler", + typeof(RenderSamplerState), + () => value.sampler, + next => { var candidate = value; candidate.kind = MaterialValueKind.Texture; candidate.sampler = (RenderSamplerState)next!; setter(candidate); - }, edits, readOnly); + }, + edits, + readOnly + ); + } } /// @@ -101,9 +118,13 @@ MaterialValueKind kind ShaderPropertyType.Vector2 or ShaderPropertyType.Vector3 or ShaderPropertyType.Vector4 => kind == MaterialValueKind.Vector, ShaderPropertyType.Color => kind == MaterialValueKind.Color, ShaderPropertyType.Matrix4x4 => kind == MaterialValueKind.Matrix, - ShaderPropertyType.Texture2D or ShaderPropertyType.Texture2DArray or ShaderPropertyType.Texture3D or ShaderPropertyType.TextureCube => kind == MaterialValueKind.Texture, + ShaderPropertyType.Texture2D + or ShaderPropertyType.Texture2DArray + or ShaderPropertyType.Texture3D + or ShaderPropertyType.TextureCube => kind == MaterialValueKind.Texture, _ => false }; + /// /// Applies the edited components of a representative value without replacing unrelated mixed components. /// @@ -129,13 +150,19 @@ public static MaterialValue ApplyEdit( MaterialValue target ) { if (!Compatible(type, before.kind) || !Compatible(type, edited.kind) || !Compatible(type, target.kind)) + { throw new ArgumentException("A multi-Material edit requires exactly matching value kinds."); + } if (type == ShaderPropertyType.Float) + { return edited; + } if (edited.kind == MaterialValueKind.Texture) { if (!ReferenceEquals(before.texture, edited.texture)) + { target.texture = edited.texture; + } target.sampler = new( before.sampler.filter == edited.sampler.filter ? target.sampler.filter : edited.sampler.filter, before.sampler.addressU == edited.sampler.addressU ? target.sampler.addressU : edited.sampler.addressU, @@ -179,7 +206,8 @@ float current ) => BitConverter.SingleToUInt32Bits(previous) == BitConverter.SingleToUInt32Bits(next) ? current : next; } - private static Type ValueType(ShaderPropertyType type) => type switch + private static Type ValueType(ShaderPropertyType type) + => type switch { ShaderPropertyType.Float => typeof(float), ShaderPropertyType.Vector2 => typeof(Vector2), @@ -187,8 +215,13 @@ float current ShaderPropertyType.Vector4 => typeof(Vector4), ShaderPropertyType.Color => typeof(Color), ShaderPropertyType.Matrix4x4 => typeof(Matrix), - ShaderPropertyType.Texture2D or ShaderPropertyType.Texture2DArray or ShaderPropertyType.Texture3D or ShaderPropertyType.TextureCube => typeof(TextureAsset), - _ => throw new InvalidOperationException("No material editor exists for " + type)}; + ShaderPropertyType.Texture2D + or ShaderPropertyType.Texture2DArray + or ShaderPropertyType.Texture3D + or ShaderPropertyType.TextureCube => typeof(TextureAsset), + _ => throw new InvalidOperationException("No material editor exists for " + type) + }; + private static object? Unbox( ShaderPropertyType type, MaterialValue value @@ -202,6 +235,7 @@ MaterialValue value ShaderPropertyType.Matrix4x4 => value.matrix, _ => value.texture }; + private static MaterialValue Box( ShaderPropertyType type, object? value, @@ -210,7 +244,9 @@ MaterialValue previous { ShaderPropertyType.Float => MaterialValue.FromFloat((float)value!), ShaderPropertyType.Vector2 => MaterialValue.FromVector(new Vector4(((Vector2)value!).x, ((Vector2)value!).y, 0, 0)), - ShaderPropertyType.Vector3 => MaterialValue.FromVector(new Vector4(((Vector3)value!).x, ((Vector3)value!).y, ((Vector3)value!).z, 0)), + ShaderPropertyType.Vector3 => MaterialValue.FromVector( + new Vector4(((Vector3)value!).x, ((Vector3)value!).y, ((Vector3)value!).z, 0) + ), ShaderPropertyType.Vector4 => MaterialValue.FromVector((Vector4)value!), ShaderPropertyType.Color => MaterialValue.FromColor((Color)value!), ShaderPropertyType.Matrix4x4 => MaterialValue.FromMatrix((Matrix)value!), diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs index ac92c4ee0..83692563e 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs @@ -1,11 +1,12 @@ -using Inno.Editor.Shaders; using System; using Inno.Core.Graphs; using Inno.Core.Serialization; -using Inno.Editor.Rendering; using Inno.Editor.Inspection; +using Inno.Editor.Rendering; +using Inno.Editor.Shaders; namespace Inno.Editor.Shaders.ImGui; + /// /// Registers Editor-only node controls independently from a node's shader compiler. /// @@ -49,18 +50,22 @@ public ShaderNodeDrawerAttribute( /// Gets the stable node identity handled by this drawer. /// public string definitionId { get; } + /// /// Gets the optional presentation-only name; it does not participate in Shader compilation or identity. /// public string displayName { get; } + /// /// Gets the optional creation-menu path below Create. /// public string createPath { get; } + /// /// Gets the creation-menu order. /// public int createOrder { get; } + /// /// Gets whether the contributed creation group starts a new visual section. /// @@ -103,14 +108,17 @@ bool separatorBefore /// Gets the optional artist-facing node name. /// public string displayName { get; } + /// /// Gets the optional slash-delimited creation-menu path. /// public string createPath { get; } + /// /// Gets the stable ordering value within the creation menu. /// public int createOrder { get; } + /// /// Gets whether the contributed group starts a visual section. /// @@ -142,6 +150,7 @@ public sealed class ShaderNodeDrawContext private readonly Action m_write; private readonly InspectionDrawContext m_inspection; private readonly bool m_readOnly; + /// /// Creates invocation-scoped access for a graph or Inspector host. /// @@ -188,6 +197,7 @@ bool readOnly /// Gets the shared generation-scoped preview service for optional inline texture previews; valid only during this draw. /// public IEditorPreviewService previews { get; } + /// /// Gets the stable node identity for Editor widget IDs. /// @@ -212,6 +222,7 @@ public T Read( string key, T defaultValue ) => Inno.Rendering.Shaders.ShaderGraphDocument.Read(m_node, key, defaultValue, m_serialization, m_context); + /// /// Records an unsaved draft edit through shared history; only an explicit document save applies it to the asset. /// @@ -233,7 +244,9 @@ public void Write( string? mergeKey = null ) { if (m_readOnly) + { throw new InvalidOperationException("Copy this installed Shader into the project before editing."); + } m_write(key, Inno.Rendering.Shaders.ShaderGraphDocument.Encode(value, m_serialization, m_context), mergeKey); } @@ -258,14 +271,24 @@ public void DrawProperty( T defaultValue ) { T value = Read(key, defaultValue); - m_inspection.properties.DrawValue(m_inspection.editorContext, m_node, "shader.node." + key, label, typeof(T), () => value, edited => value = (T)edited!, new Edits(( - mutation, - mergeKey - ) => - { - mutation(); - Write(key, value, mergeKey); - }), m_readOnly); + m_inspection.properties.DrawValue( + m_inspection.editorContext, + m_node, + "shader.node." + key, + label, + typeof(T), + () => value, + edited => value = (T)edited!, + new Edits(( + mutation, + mergeKey + ) => + { + mutation(); + Write(key, value, mergeKey); + }), + m_readOnly + ); } private sealed class Edits(Action apply) : IInspectionPropertyEditService diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerRegistry.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerRegistry.cs index 6ffb0b791..da93185f1 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerRegistry.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerRegistry.cs @@ -1,11 +1,12 @@ -using Inno.Editor.Shaders; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using Inno.Editor.Shaders; using Inno.Extensibility.Types; namespace Inno.Editor.Shaders.ImGui; + /// /// Shares generation-scoped node presentation between graph and Inspector hosts. /// @@ -13,6 +14,7 @@ public sealed class ShaderNodeDrawerRegistry : IDisposable { private readonly TypeCatalog m_types; private readonly Registry m_registry; + /// /// Creates a presentation registry owned by the current editor feature lifetime. /// @@ -43,7 +45,9 @@ ShaderNodeDrawContext context ) { using IDisposable operation = m_types.AcquireOperation("Draw shader node controls"); if (!m_registry.snapshot.drawers.TryGetValue(definitionId, out ShaderNodeDrawer? drawer)) + { return false; + } drawer.Draw(context); return true; } @@ -87,6 +91,7 @@ out ShaderNodePresentation presentation /// Retires the current presentation providers through the shared lifecycle. /// public void Dispose() => m_registry.Dispose(); + private sealed class Registry(TypeCatalog types) : TypeRegistry(types) { internal Snapshot snapshot => current; @@ -107,15 +112,22 @@ protected override Snapshot Build(TypeCacheSnapshot snapshot) var presentations = new Dictionary(StringComparer.Ordinal); try { - foreach (Type type in snapshot.GetTypesWithAttribute().Select(reference => reference.Resolve(snapshot))) - { + foreach (Type type in snapshot + .GetTypesWithAttribute() + .Select(reference => reference.Resolve(snapshot)) + ) { ShaderNodeDrawerAttribute attribute = type.GetCustomAttribute()!; string id = attribute.definitionId; if (result.ContainsKey(id)) + { throw new InvalidOperationException($"Shader node drawer '{id}' is registered twice."); + } result.Add(id, CreateExtension(type)); names.Add(id, attribute.displayName); - presentations.Add(id, new(attribute.displayName, Normalize(attribute.createPath), attribute.createOrder, attribute.separatorBefore)); + presentations.Add( + id, + new(attribute.displayName, Normalize(attribute.createPath), attribute.createOrder, attribute.separatorBefore) + ); } return new(result, names, presentations); @@ -144,7 +156,9 @@ protected override Snapshot Build(TypeCacheSnapshot snapshot) protected override void DisposeSnapshot(Snapshot snapshot) => DisposeExtensions(snapshot.drawers.Values); } - private static string Normalize(string value) => string.Join('/', value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + private static string Normalize(string value) + => string.Join('/', value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + private sealed record Snapshot( IReadOnlyDictionary drawers, IReadOnlyDictionary names, diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs index 286b829e2..b8f2732c8 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs @@ -1,5 +1,3 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using Inno.Editor.Shaders; using System; using System.Collections.Generic; using System.Linq; @@ -8,12 +6,16 @@ using Inno.Core.Execution; using Inno.Editor.Core; using Inno.Editor.Rendering; +using Inno.Editor.Shaders; using Inno.Extensibility.Types; using Inno.Rendering; -using ImGuiApi = Inno.Editor.ImGui.ImGui; using Inno.Rendering.Assets; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using ImGuiApi = Inno.Editor.ImGui.ImGui; + namespace Inno.Editor.Shaders.ImGui; + /// /// Hosts isolated Shader and Material images using domain-contributed preview pipelines. /// @@ -26,6 +28,7 @@ public sealed class ShaderPreviews : EditorModule private readonly EditorShaderCompilation m_compilation; private readonly Dictionary m_states = []; private ulong m_frame; + internal ShaderPreviews( TypeCatalog types, IEditorPreviewService previews, @@ -62,7 +65,12 @@ float logicalSize try { - Draw(ownerId, material, m_compilation.RequestArtifact(material.shader, RenderShaderVariant.FromMaterial(material)), logicalSize); + Draw( + ownerId, + material, + m_compilation.RequestArtifact(material.shader, RenderShaderVariant.FromMaterial(material)), + logicalSize + ); } catch (Exception error) when (Recoverable(error)) { @@ -92,11 +100,15 @@ public void Draw( float logicalSize ) { if (ownerId == Guid.Empty) + { throw new ArgumentException("A preview owner identity is required.", nameof(ownerId)); + } ArgumentNullException.ThrowIfNull(material); ArgumentNullException.ThrowIfNull(compilation); if (!(logicalSize > 0f) || !float.IsFinite(logicalSize)) + { throw new ArgumentOutOfRangeException(nameof(logicalSize)); + } if (compilation.artifact is not { } artifact) { EditorUI.current.widgets.Hint("Preview: " + compilation.state); @@ -104,13 +116,20 @@ float logicalSize } if (!m_states.TryGetValue(ownerId, out State? state)) + { m_states.Add(ownerId, state = new("shader-preview/" + ownerId.ToString("N"))); + } state.frame = m_frame; try { using IDisposable operation = m_types.AcquireOperation("Build isolated Shader preview"); ShaderDefinition definition = m_compilation.ReadDefinition(artifact); - string[] contracts = definition.techniques.Where(value => !material.techniqueId.isValid || value.id == material.techniqueId).Select(value => value.contract.value).Distinct(StringComparer.Ordinal).Where(m_registry.providers.ContainsKey).ToArray(); + string[] contracts = definition.techniques + .Where(value => !material.techniqueId.isValid || value.id == material.techniqueId) + .Select(value => value.contract.value) + .Distinct(StringComparer.Ordinal) + .Where(m_registry.providers.ContainsKey) + .ToArray(); if (contracts.Length == 0) { EditorUI.current.widgets.Hint("No preview provider for this Shader contract."); @@ -127,12 +146,20 @@ float logicalSize var context = new ShaderPreviewContext(new(state.viewportId), material, artifact, definition, state, pixels, pixels); EditorViewportLayer layer = m_registry.providers[contracts[0]].CreateLayer(context); if (m_previews.TryRender(new(state.viewportId, pixels, pixels, RenderTextureFormat.RGBA8, [layer]), out var handle)) + { m_previews.Draw(handle, new(logicalSize, logicalSize)); + } else + { ImGuiApi.Dummy(new(logicalSize, logicalSize)); - EditorUI.current.widgets.Hint(compilation.usingLastGood ? "Draft preview · last-good candidate · Scene/Game unchanged" : "Isolated preview · Scene/Game unchanged"); + } + EditorUI.current.widgets.Hint( + compilation.usingLastGood ? "Draft preview · last-good candidate · Scene/Game unchanged" : "Isolated preview · Scene/Game unchanged" + ); foreach (Diagnostic error in state.errors.Values) + { EditorUI.current.widgets.WrappedText(error.message); + } } catch (Exception error) when (Recoverable(error)) { @@ -149,7 +176,9 @@ float logicalSize public void Release(Guid ownerId) { if (m_states.Remove(ownerId, out State? state)) + { m_previews.ReleaseRendered(state.viewportId); + } } /// @@ -162,7 +191,9 @@ protected override void OnUpdate(EditorContext context) { m_frame++; foreach (Guid id in m_states.Where(pair => m_frame - pair.Value.frame > 2).Select(pair => pair.Key).ToArray()) + { Release(id); + } } /// @@ -174,17 +205,22 @@ protected override void OnUpdate(EditorContext context) protected override void OnStop(EditorContext context) { foreach (Guid id in m_states.Keys.ToArray()) + { Release(id); + } m_registry.Dispose(); } - private static bool Recoverable(Exception error) => RetirementPendingException.Find(error) is null - && error is InvalidOperationException or ArgumentException or FormatException; + private static bool Recoverable(Exception error) + => RetirementPendingException.Find(error) is null + && error is InvalidOperationException or ArgumentException or FormatException; + private sealed class State(string viewportId) : IDiagnosticReporter { internal readonly string viewportId = viewportId; internal readonly Dictionary<(string code, string? semanticId, Guid? objectId), Diagnostic> errors = []; internal ulong frame; + /// /// Publishes the supplied diagnostic to the configured observers. /// @@ -192,6 +228,7 @@ private sealed class State(string viewportId) : IDiagnosticReporter /// The diagnostic consumed by publish; ownership remains with the caller unless explicitly stated otherwise. /// public void Publish(Diagnostic diagnostic) => errors[(diagnostic.code, diagnostic.semanticId, diagnostic.objectId)] = diagnostic; + /// /// Resolves the requested stable identity to its current-generation value. /// @@ -209,6 +246,7 @@ public void Resolve( string? semanticId = null, Guid? objectId = null ) => errors.Remove((code, semanticId, objectId)); + /// /// Records errors from the current diagnostic report. /// @@ -219,7 +257,9 @@ public void Replace(IEnumerable diagnostics) { errors.Clear(); foreach (Diagnostic value in diagnostics) + { Publish(value); + } } } @@ -241,11 +281,15 @@ protected override IReadOnlyDictionary Build(Type var result = new Dictionary(StringComparer.Ordinal); try { - foreach (Type type in snapshot.GetTypesWithAttribute().Select(value => value.Resolve(snapshot))) - { + foreach (Type type in snapshot + .GetTypesWithAttribute() + .Select(value => value.Resolve(snapshot)) + ) { string id = type.GetCustomAttribute()!.contractId; if (result.ContainsKey(id)) + { throw new InvalidOperationException("Duplicate Shader preview contract: " + id); + } result.Add(id, CreateExtension(type)); } @@ -272,6 +316,7 @@ protected override IReadOnlyDictionary Build(Type /// /// The immutable state snapshot consumed by this operation. /// - protected override void DisposeSnapshot(IReadOnlyDictionary snapshot) => DisposeExtensions(snapshot.Values); + protected override void DisposeSnapshot(IReadOnlyDictionary snapshot) + => DisposeExtensions(snapshot.Values); } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/HistoryActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/HistoryActions.cs index 5202c7bc9..cbcbfca23 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/HistoryActions.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/HistoryActions.cs @@ -2,6 +2,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; + [EditorAction(GlobalInteractionIds.C_UNDO, priority: 1000)] [EditorMenu(GlobalInteractionIds.C_MAIN_MENU_AREA, "Edit/Undo", order: 100)] [EditorShortcut(KeyCode.Z, primary: true)] @@ -16,12 +17,14 @@ internal sealed class UndoEditorAction : EditorAction /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => new( - isVisible: true, - isEnabled: context.history.canUndo, - displayName: context.history.undoName is { } name ? $"Undo {name}" : "Undo", - unavailableReason: context.history.undoUnavailableReason - ); + protected override EditorActionState Query(EditorActionContext context) + => new( + isVisible: true, + isEnabled: context.history.canUndo, + displayName: context.history.undoName is { } name ? $"Undo {name}" : "Undo", + unavailableReason: context.history.undoUnavailableReason + ); + /// /// Executes the prepared operation and publishes only a completed result. /// @@ -46,12 +49,14 @@ internal sealed class RedoEditorAction : EditorAction /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => new( - isVisible: true, - isEnabled: context.history.canRedo, - displayName: context.history.redoName is { } name ? $"Redo {name}" : "Redo", - unavailableReason: context.history.redoUnavailableReason - ); + protected override EditorActionState Query(EditorActionContext context) + => new( + isVisible: true, + isEnabled: context.history.canRedo, + displayName: context.history.redoName is { } name ? $"Redo {name}" : "Redo", + unavailableReason: context.history.redoUnavailableReason + ); + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectionActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectionActions.cs index e5a24c756..3a2aa2b48 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectionActions.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectionActions.cs @@ -1,6 +1,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; + [EditorAction(GlobalInteractionIds.C_CLEAR_SELECTION)] internal sealed class ClearEditorSelectionAction : EditorAction { diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/TogglePanelAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/TogglePanelAction.cs index 14ab346e4..06c4378a2 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/TogglePanelAction.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/TogglePanelAction.cs @@ -1,18 +1,17 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; + [EditorAction(GlobalInteractionIds.C_TOGGLE_PANEL, GlobalInteractionIds.C_MAIN_MENU_AREA)] internal sealed class TogglePanelAction : EditorArgumentAction { /// - protected override EditorActionState Query(EditorActionArgumentContext context) => context.interactions.TryGetPanelState( - context.argument, - out bool isOpen - ) ? new EditorActionState( - true, - true, - isChecked: isOpen - ) : EditorActionState.hidden; + protected override EditorActionState Query(EditorActionArgumentContext context) + => context.interactions.TryGetPanelState( + context.argument, + out bool isOpen + ) ? new EditorActionState(true, true, isChecked: isOpen) : EditorActionState.hidden; + /// /// Executes the prepared operation and publishes only a completed result. /// diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchAction.cs index c38394789..5589af89b 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchAction.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchAction.cs @@ -2,13 +2,16 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; + [EditorAction(GlobalInteractionIds.C_FIND_COMMAND)] [EditorMenu(GlobalInteractionIds.C_MAIN_MENU_AREA, "Tools/Find Command...", order: 0)] [EditorShortcut(KeyCode.P, KeyModifier.Shift, primary: true)] internal sealed class CommandSearchAction(CommandSearchModule commands) : EditorAction { /// - protected override EditorActionState Query(EditorActionContext context) => commands.isOpen ? EditorActionState.disabled : EditorActionState.enabled; + protected override EditorActionState Query(EditorActionContext context) + => commands.isOpen ? EditorActionState.disabled : EditorActionState.enabled; + /// protected override void Execute(EditorActionContext context) => commands.Open(); } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModal.cs index 7bb0bc72d..84c2299e8 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModal.cs @@ -1,9 +1,11 @@ using System.Numerics; using Inno.Editor.Core; using Inno.Editor.ImGui; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; + [EditorModal(GlobalInteractionIds.C_COMMAND_SEARCH_MODAL, "Find Command", order: 50)] internal sealed class CommandSearchModal( CommandSearchModule commands, @@ -12,8 +14,10 @@ EditorUiSession ui { /// public override bool isVisible => commands.isOpen; + /// public override bool allowScrolling => false; + /// public override Vector2 initialSize => new(620f, 440f); @@ -29,12 +33,19 @@ protected override void OnDraw(EditorContext context) string search = commands.search; _ = ui.widgets.SearchInput("commands", "Search commands...", ref search); commands.search = search; - bool opened = Ui.BeginChild("##command-results", new Vector2(0f, -Ui.GetFrameHeightWithSpacing()), 0, ImGuiWindowFlags.NoSavedSettings); + bool opened = Ui.BeginChild( + "##command-results", + new Vector2(0f, -Ui.GetFrameHeightWithSpacing()), + 0, + ImGuiWindowFlags.NoSavedSettings + ); bool chosen = false; try { if (opened) + { chosen = commands.Draw(ui); + } } finally { @@ -42,6 +53,8 @@ protected override void OnDraw(EditorContext context) } if (chosen || ui.widgets.CenteredButton("Close") || Ui.IsKeyPressed(ImGuiKey.Escape, false)) + { commands.Close(); + } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs index 3f093368c..ddd2e7cbe 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs @@ -7,6 +7,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; + [EditorModule(GlobalInteractionIds.C_COMMAND_SEARCH_MODULE, order: 20)] internal sealed class CommandSearchModule(EditorInteractions interactions) : EditorModule { @@ -39,7 +40,9 @@ internal bool Draw(EditorUiSession ui) var globalIds = new HashSet(StringComparer.Ordinal); Collect(globalMenu.items); if (ui.menus.DrawSearchItems(global, globalMenu.items, search)) + { return true; + } object? target = m_target is RuntimeIdentity id && interactions.TryResolveIdentity(id, out IdentityObject? live) ? live : null; EditorInteraction local = interactions.For(m_area, target); EditorMenuModel commands = local.BuildCommands(); @@ -50,7 +53,9 @@ void Collect(IReadOnlyList items) foreach (EditorMenuItem item in items) { if (item.actionId.Length != 0) + { _ = globalIds.Add(item.actionId); + } Collect(item.children); } } @@ -58,16 +63,21 @@ void Collect(IReadOnlyList items) /// protected override void OnStop(EditorContext context) => Close(); + private static IEnumerable Leaves(IReadOnlyList items) { foreach (EditorMenuItem item in items) { if (item.children.Count == 0) + { yield return item; + } else { foreach (EditorMenuItem child in Leaves(item.children)) + { yield return child; + } } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportActions.cs index 75dcf1557..bb30b0c66 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportActions.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportActions.cs @@ -1,6 +1,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; + [EditorAction(ExportInteractionIds.C_EXPORT_PLUGIN)] [EditorMenu(ExportInteractionIds.C_MAIN_MENU_AREA, "File/Export as Plugin...", order: 800, separatorBefore: true)] internal sealed class ExportPluginAction(ExportWindowModule window) : EditorAction diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportInteractionIds.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportInteractionIds.cs index e27e00e2b..1e8e95e0a 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportInteractionIds.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportInteractionIds.cs @@ -1,4 +1,5 @@ namespace Inno.Editor.Workbench; + internal static class ExportInteractionIds { internal const string C_EXPORT_GAME = "export/game"; diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportWindowModule.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportWindowModule.cs index 945dd8a6b..c07890d4f 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportWindowModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportWindowModule.cs @@ -8,6 +8,7 @@ using Inno.Editor.Exporting; namespace Inno.Editor.Workbench; + [EditorModule("export.windows", order: 310)] internal sealed class ExportWindowModule( EditorContext m_editor, @@ -43,10 +44,13 @@ ProjectSettingsStore m_projectSettings internal bool includePluginDependencies { get; set; } internal string GetGameTargetDisplayName(BuildTargetId target) => m_exports.GetGameTargetDisplayName(target); + internal void OpenPlugin() { if (isPluginBusy || isGameBusy) + { return; + } CloseGame(); BuildSettings defaults = LoadBuildSettings(); pluginDisplayName = defaults.pluginDisplayName; @@ -58,7 +62,9 @@ internal void OpenPlugin() internal void OpenGame() { if (isPluginBusy || isGameBusy) + { return; + } ClosePlugin(); m_gameProgressVisible = false; BuildSettings defaults = LoadBuildSettings(); @@ -76,30 +82,60 @@ internal void OpenGame() internal void BeginPluginExport() { m_formError = string.Empty; - m_exports.StartPlugin(new PluginBuildRequest { pluginId = pluginId, displayName = pluginDisplayName, outputPath = ResolveOutputPath(pluginOutputPath), includeDependencies = includePluginDependencies }); + m_exports.StartPlugin( + new PluginBuildRequest + { + pluginId = pluginId, + displayName = pluginDisplayName, + outputPath = ResolveOutputPath(pluginOutputPath), + includeDependencies = includePluginDependencies + } + ); } internal void BeginGameExport() { m_formError = string.Empty; - m_exports.StartGame(new GameBuildRequest { profile = new BuildProfile { applicationId = gameApplicationId, productName = gameProductName, persistentDataPath = gamePersistentDataPath, startupScene = gameStartupScene, target = gameTarget, managedDeployment = gameManagedDeployment, windowWidth = gameWindowWidth, windowHeight = gameWindowHeight }, outputDirectory = ResolveOutputPath(gameOutputDirectory) }); + m_exports.StartGame( + new GameBuildRequest + { + profile = new BuildProfile + { + applicationId = gameApplicationId, + productName = gameProductName, + persistentDataPath = gamePersistentDataPath, + startupScene = gameStartupScene, + target = gameTarget, + managedDeployment = gameManagedDeployment, + windowWidth = gameWindowWidth, + windowHeight = gameWindowHeight + }, + outputDirectory = ResolveOutputPath(gameOutputDirectory) + } + ); isGameVisible = false; m_gameProgressVisible = true; } internal void CancelPluginExport(long operationId) => m_exports.Cancel(operationId); + internal void CancelGameExport(long operationId) => m_exports.Cancel(operationId); + internal void ClosePlugin() { if (isPluginBusy) + { m_exports.Cancel(m_exports.progress.operationId); + } isPluginVisible = false; } internal void CloseGame() { if (isGameBusy) + { m_exports.Cancel(m_exports.progress.operationId); + } isGameVisible = false; } @@ -109,7 +145,10 @@ private BuildSettings LoadBuildSettings() { return m_buildSettings.Load(); } - catch (Exception exception) when (exception is IOException or InvalidDataException or InvalidOperationException or UnauthorizedAccessException) + catch (Exception exception) when (exception is IOException + or InvalidDataException + or InvalidOperationException + or UnauthorizedAccessException) { m_formError = exception.Message; return m_buildSettings.defaultSettings; @@ -119,7 +158,9 @@ private BuildSettings LoadBuildSettings() private string ResolveOutputPath(string path) { if (string.IsNullOrWhiteSpace(path)) + { return path; + } return Path.IsPathFullyQualified(path) ? Path.GetFullPath(path) : Path.GetFullPath(path, m_editor.projectDirectory); } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs index 76940a130..39520cea2 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs @@ -1,33 +1,40 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Numerics; using Inno.Build; using Inno.Build.Managed; using Inno.Editor.Core; using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; + [EditorModal("export.game", "Export as Game", order: 310)] internal sealed class GameExportModal(ExportWindowModule window) : EditorModal { private const int C_TEXT_CAPACITY = 4096; + /// /// Gets whether this implementation is visible. /// public override bool isVisible => window.isGameVisible; + /// /// Gets whether this implementation can move. /// public override bool canMove => true; + /// /// Gets whether this implementation can resize. /// public override bool canResize => true; + /// /// Gets the preferred initial window size in logical editor units. /// public override Vector2 initialSize => new(760f, 540f); + /// /// Gets the smallest size that keeps the export form usable. /// @@ -41,7 +48,9 @@ internal sealed class GameExportModal(ExportWindowModule window) : EditorModal /// protected override void OnDraw(EditorContext context) { - EditorUI.current.widgets.WrappedText("Build a standalone Player from the current project. Only imported runtime content " + "is deployed; source files stay in the project."); + EditorUI.current.widgets.WrappedText( + "Build a standalone Player from the current project. Only imported runtime content " + "is deployed; source files stay in the project." + ); Ui.SeparatorText("Application"); if (BeginFields("##application_fields")) { @@ -50,7 +59,12 @@ protected override void OnDraw(EditorContext context) EditorUI.current.widgets.SetupPropertyColumns(); DrawReadOnly("Application ID", window.gameApplicationId); DrawText("Product Name", "game_name", window.gameProductName, value => window.gameProductName = value); - DrawText("Persistent Data Folder", "game_data", window.gamePersistentDataPath, value => window.gamePersistentDataPath = value); + DrawText( + "Persistent Data Folder", + "game_data", + window.gamePersistentDataPath, + value => window.gamePersistentDataPath = value + ); DrawText("Startup Scene", "game_scene", window.gameStartupScene, value => window.gameStartupScene = value); } finally @@ -101,12 +115,14 @@ protected override void OnDraw(EditorContext context) DrawButtons(); } - private static bool BeginFields(string id) => Ui.BeginTable( - id, - 2, - ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.NoPadOuterX, - default(Vector2), - 0f); + private static bool BeginFields(string id) + => Ui.BeginTable( + id, + 2, + ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.NoPadOuterX, + default(Vector2), + 0f + ); private static void BeginField(string label) { @@ -139,11 +155,15 @@ private void DrawWindowSize() BeginField("Initial Width"); Ui.SetNextItemWidth(-1f); if (Ui.InputInt("##game_window_width", ref width, 1, 100, 0)) + { window.gameWindowWidth = Math.Max(1, width); + } BeginField("Initial Height"); Ui.SetNextItemWidth(-1f); if (Ui.InputInt("##game_window_height", ref height, 1, 100, 0)) + { window.gameWindowHeight = Math.Max(1, height); + } } private void DrawManagedDeployment() @@ -151,14 +171,22 @@ private void DrawManagedDeployment() BeginField("Managed Deployment"); Ui.SetNextItemWidth(-1f); if (!EditorUI.current.widgets.BeginBoundedCombo("##game_deployment", window.gameManagedDeployment?.value ?? "Platform default")) + { return; + } try { if (Ui.Selectable("Platform default", window.gameManagedDeployment is null)) + { window.gameManagedDeployment = null; + } foreach (ManagedDeploymentId deployment in window.availableManagedDeployments) + { if (Ui.Selectable(deployment.value, window.gameManagedDeployment == deployment)) + { window.gameManagedDeployment = deployment; + } + } } finally { @@ -172,11 +200,15 @@ private void DrawTarget() Ui.SetNextItemWidth(-1f); string preview = window.GetGameTargetDisplayName(window.gameTarget); if (!EditorUI.current.widgets.BeginBoundedCombo("##game_target", preview)) + { return; + } try { foreach (BuildTargetId target in window.availableGameTargets) + { DrawTargetChoice(target); + } } finally { @@ -188,9 +220,13 @@ private void DrawTargetChoice(BuildTargetId target) { bool selected = window.gameTarget == target; if (Ui.Selectable(window.GetGameTargetDisplayName(target), selected)) + { window.gameTarget = target; + } if (selected) + { Ui.SetItemDefaultFocus(); + } } private void DrawButtons() @@ -200,12 +236,18 @@ private void DrawButtons() EditorUiLayout style = Ui.GetLayout(); float closeWidth = Ui.MeasureText("Close").X + style.framePadding.X * 2f; float primaryWidth = Ui.MeasureText(primaryLabel).X + style.framePadding.X * 2f; - Ui.SetCursorPosX(Ui.GetCursorPosX() + MathF.Max(0f, Ui.GetContentRegionAvailable().X - closeWidth - style.itemSpacing.X - primaryWidth)); + Ui.SetCursorPosX( + Ui.GetCursorPosX() + MathF.Max(0f, Ui.GetContentRegionAvailable().X - closeWidth - style.itemSpacing.X - primaryWidth) + ); if (Ui.Button("Close")) + { window.CloseGame(); + } Ui.SameLine(0f, -1f); if (Ui.Button(primaryLabel)) + { window.BeginGameExport(); + } } private static void DrawText( diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs index a3d7b9cf8..5ee0a48ae 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs @@ -2,17 +2,22 @@ using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; + namespace Inno.Editor.Workbench; + [EditorModal("export.game.progress", "Exporting Game", order: 311)] internal sealed class GameExportProgressModal(ExportWindowModule window) : EditorModal { private DialogPresentation m_content; private DialogLayout m_layout; private long m_operation; + /// public override bool isVisible => window.isGameProgressVisible; + /// public override bool allowScrolling => false; + /// protected override Vector2? OnPrepare( EditorContext context, @@ -31,10 +36,13 @@ Vector2 availableContentSize m_layout = EditorUiSession.current.widgets.MeasureDialog(m_content, availableContentSize); return m_layout.size; } + /// protected override void OnDraw(EditorContext context) { if (EditorUiSession.current.widgets.DrawDialog(m_content, m_layout)) + { window.CancelGameExport(m_operation); + } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs index dcf5d8d11..1a822089b 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs @@ -3,6 +3,7 @@ using System.Numerics; using Inno.Editor.Core; using Inno.Editor.ImGui; + using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; @@ -22,12 +23,16 @@ internal sealed class PluginExportModal(ExportWindowModule window) : EditorModal private bool m_dependencies; private long m_operation; private float m_wrapWidth; + /// public override bool isVisible => window.isPluginVisible; + /// public override bool canMove => true; + /// public override Vector2 initialSize => new(680f, 0f); + /// protected override Vector2? OnPrepare( EditorContext context, @@ -43,8 +48,8 @@ Vector2 availableContentSize m_outcome = string.IsNullOrEmpty(progress.error) ? progress.status : progress.error; float width = availableContentSize.X; float scrollbar = Ui.GetLayout().scrollbarSize; - float checkboxWidth = Ui.GetFrameHeight() + Ui.GetLayout().itemInnerSpacing.X + - Ui.MeasureText("Include dependency Plugin packages").X; + float checkboxWidth = Ui.GetFrameHeight() + Ui.GetLayout().itemInnerSpacing.X + + Ui.MeasureText("Include dependency Plugin packages").X; float height = Present(false, width); float availableHeight = availableContentSize.Y - (checkboxWidth > width ? scrollbar : 0f); if (height > availableHeight) @@ -55,6 +60,7 @@ Vector2 availableContentSize m_wrapWidth = width; return new Vector2(MathF.Max(width, checkboxWidth), height); } + /// protected override void OnDraw(EditorContext context) => Present(true, m_wrapWidth); @@ -66,7 +72,9 @@ float width int row = 0; Vector2 origin = draw ? Ui.GetCursorPosition() : Vector2.Zero; if (!draw) + { m_rows.Clear(); + } var layout = Ui.GetLayout(); float gap = layout.itemSpacing.Y; float frame = Ui.MeasureText("M").Y + layout.framePadding.Y * 2f; @@ -82,7 +90,9 @@ float width try { if (Ui.Checkbox("Include dependency Plugin packages", ref m_dependencies)) + { window.includePluginDependencies = m_dependencies; + } } finally { @@ -91,7 +101,9 @@ float width } Text(C_HINT, true); if (m_outcome.Length != 0) + { Text(m_outcome, true); + } Row(frame); if (draw) { @@ -102,7 +114,9 @@ float width try { if (Ui.Button("Close")) + { window.ClosePlugin(); + } } finally { @@ -112,9 +126,13 @@ float width if (Ui.Button(m_busy ? "Cancel" : "Export")) { if (m_busy) + { window.CancelPluginExport(m_operation); + } else + { window.BeginPluginExport(); + } } } return MathF.Ceiling(height); @@ -122,11 +140,15 @@ float width void Row(float extent) { if (draw) + { Ui.SetCursorPosition(origin + new Vector2(0f, m_rows[row++])); + } else { if (m_rows.Count != 0) + { height += gap; + } m_rows.Add(height); height += extent; } @@ -137,11 +159,17 @@ void Text( ) { Row(draw ? 0f : (wrapped ? Ui.MeasureWrappedText(text, width) : Ui.MeasureText(text)).Y); if (!draw) + { return; + } if (wrapped) + { EditorUiSession.current.widgets.WrappedText(text, width); + } else + { Ui.Text(text); + } } void Field( string label, @@ -151,7 +179,9 @@ ref string value Text(label); Row(frame); if (!draw) + { return; + } Ui.BeginDisabled(m_busy); try { @@ -159,9 +189,13 @@ ref string value if (Ui.InputText(id, ref value, C_TEXT_CAPACITY)) { if (id == "##plugin_name") + { window.pluginDisplayName = value; + } else + { window.pluginOutputPath = value; + } } } finally diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/GlobalInteractionIds.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/GlobalInteractionIds.cs index 2e2ba8575..bf4ac7139 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/GlobalInteractionIds.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/GlobalInteractionIds.cs @@ -1,4 +1,5 @@ namespace Inno.Editor.Workbench; + internal static class GlobalInteractionIds { internal const string C_MAIN_MENU_AREA = "editor/main-menu"; diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Menus/WorkbenchMenuSource.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Menus/WorkbenchMenuSource.cs index adad5c98e..0a0d2d617 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Menus/WorkbenchMenuSource.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Menus/WorkbenchMenuSource.cs @@ -2,6 +2,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; + [EditorMenuSource(GlobalInteractionIds.C_MAIN_MENU_AREA)] internal sealed class WorkbenchMenuSource : EditorMenuSource { diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs index 621165937..28a7e7625 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs @@ -3,17 +3,22 @@ using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Scripting; + namespace Inno.Editor.Workbench; + [EditorModal("scripting.compilation", "Compiling Scripts", order: 100)] internal sealed class ScriptCompilationModal(IEditorScriptCompilation scripting) : EditorModal { private DialogPresentation m_content; private DialogLayout m_layout; private long m_operation; + /// public override bool isVisible => scripting.requiresExclusiveProgress; + /// public override bool allowScrolling => false; + /// protected override Vector2? OnPrepare( EditorContext context, @@ -25,10 +30,13 @@ Vector2 availableContentSize m_layout = EditorUiSession.current.widgets.MeasureDialog(m_content, availableContentSize); return m_layout.size; } + /// protected override void OnDraw(EditorContext context) { if (EditorUiSession.current.widgets.DrawDialog(m_content, m_layout)) + { scripting.CancelCompilation(m_operation); + } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/DensitySetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/DensitySetting.cs index b9eac6bc9..26d6c4363 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/DensitySetting.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/DensitySetting.cs @@ -1,9 +1,11 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; + [EditorSettingPath("Editor/Appearance/Density", order: 50)] internal sealed class DensitySetting : EditorSetting { @@ -11,10 +13,12 @@ internal sealed class DensitySetting : EditorSetting /// Gets the comfortable default density. /// public override EditorSettingObject defaultValue => CreateDefault(); + /// /// Gets the appearance section containing this setting. /// public override string section => "Layout"; + /// /// Gets the user-facing density description. /// @@ -32,13 +36,19 @@ protected override void OnDraw(EditorSettingObject setting) string preview = compact ? "Compact" : "Comfortable"; Ui.SetNextItemWidth(-1f); if (!EditorUI.current.widgets.BeginBoundedCombo("##editor_density", preview)) + { return; + } try { if (Ui.Selectable("Comfortable", !compact)) + { setting.SetAsBoolean("compact", false); + } if (Ui.Selectable("Compact", compact)) + { setting.SetAsBoolean("compact", true); + } } finally { diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs index 57b0598db..e33260a5e 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs @@ -1,11 +1,13 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using Inno.Editor.Core; using Inno.Editor.Settings; using Inno.Platform; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; + [EditorSettingPath("Editor/Rendering")] internal sealed class EditorRenderingSettingsPage : EditorSetting { @@ -35,6 +37,7 @@ public override EditorSettingObject defaultValue /// Gets the presentation section that groups this setting. /// public override string section => "Frame Rate"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -50,7 +53,9 @@ protected override void OnDraw(EditorSettingObject setting) { bool enabled = setting.GetAsBoolean("enabled", false); if (Ui.Checkbox("##vsync", ref enabled)) + { setting.SetAsBoolean("enabled", enabled); + } } } @@ -74,6 +79,7 @@ public override EditorSettingObject defaultValue /// Gets the presentation section that groups this setting. /// public override string section => "Frame Rate"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -89,9 +95,13 @@ protected override void OnDraw(EditorSettingObject setting) { int rate = setting.GetAsInt32("value", 0); if (Ui.InputInt("##maximum_fps", ref rate, 1, 100, 0)) + { setting.SetAsInt32("value", Math.Clamp(rate, 0, 1000)); + } if (rate == 0) + { EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Unlimited"); + } } } @@ -102,6 +112,7 @@ FramePacingOptions pacing ) : EditorModule { private IDisposable? m_settingsSubscription; + /// /// Initializes this feature when its owning runtime becomes active. /// @@ -121,6 +132,7 @@ protected override void OnStart(EditorContext context) /// The context that supplies state and services for this operation. /// protected override void OnStop(EditorContext context) => m_settingsSubscription?.Dispose(); + private void Apply(EditorSettings current) { pacing.verticalSync = current.Get("Editor/Rendering/Vertical Sync").GetAsBoolean("enabled", false); diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs index 401cdb0f1..6e6249528 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs @@ -1,6 +1,7 @@ using Inno.Editor.Settings; namespace Inno.Editor.Workbench; + [EditorSettingPath("Editor")] internal sealed class GlobalSettingsPage : EditorSetting { diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs index e9d68e178..ef379f21d 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs @@ -1,18 +1,21 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; +using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; + internal abstract class IconSetting : EditorSetting { private static readonly IReadOnlyList<(string Name, string Glyph)> C_ICONS = EditorIconCatalog.standard; private readonly string m_glyph; + /// /// Creates a validated icon setting instance. /// @@ -29,6 +32,7 @@ protected IconSetting(string glyph) /// Gets a new value initialized to this setting's canonical default state. /// public override EditorSettingObject defaultValue => CreateDefault(m_glyph); + /// /// Gets the presentation section that groups this setting. /// @@ -69,13 +73,18 @@ protected override void OnDraw(EditorSettingObject setting) float lineHeight = Ui.GetTextLineHeight(); DrawIconTextAt( Ui.GetDrawList(), - new Vector2(minimum.X + style.framePadding.X, minimum.Y + MathF.Max(0f, (maximum.Y - minimum.Y - lineHeight) * 0.5f)), + new Vector2( + minimum.X + style.framePadding.X, + minimum.Y + MathF.Max(0f, (maximum.Y - minimum.Y - lineHeight) * 0.5f) + ), candidate, name, iconSlotWidth ); if (selected) + { Ui.SetItemDefaultFocus(); + } } finally { @@ -99,12 +108,15 @@ private static EditorSettingObject CreateDefault(string glyph) } private static float GetIconSlotWidth() => EditorUI.current.widgets.GetIconCatalogWidth(); + private static string GetIconName(string glyph) { for (int i = 0; i < C_ICONS.Count; i++) { if (string.Equals(C_ICONS[i].Glyph, glyph, StringComparison.Ordinal)) + { return C_ICONS[i].Name; + } } return glyph; @@ -121,7 +133,12 @@ float iconSlotWidth float fontSize = Ui.GetFontSize(); float lineHeight = Ui.GetTextLineHeight(); uint color = Ui.GetStyleColor(ImGuiCol.Text); - EditorUI.current.widgets.AddGlyphCentered(fontSize, glyph, new Vector2(origin.X + iconSlotWidth * 0.5f, origin.Y + lineHeight * 0.5f), color); + EditorUI.current.widgets.AddGlyphCentered( + fontSize, + glyph, + new Vector2(origin.X + iconSlotWidth * 0.5f, origin.Y + lineHeight * 0.5f), + color + ); Inno.Editor.ImGui.ImGui.DrawText(new Vector2(origin.X + iconSlotWidth + style.itemInnerSpacing.X, origin.Y), color, text); } } @@ -195,7 +212,8 @@ internal sealed class ShaderSourceIconSetting() : IconSetting(ImGuiIcon.RupeeSig /// /// Gets the user-facing explanation of this feature or setting. /// - public override string description => "Selects the icon used consistently for Shader source-function libraries. The default function symbol distinguishes reusable code from complete Shader graphs."; + public override string description + => "Selects the icon used consistently for Shader source-function libraries. The default function symbol distinguishes reusable code from complete Shader graphs."; } [EditorSettingPath("Editor/Appearance/Icons/Material")] diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeSetting.cs index 7b46f0185..e878bbac4 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeSetting.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeSetting.cs @@ -1,23 +1,36 @@ -using Inno.Editor.ImGui; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; using System; +using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Workbench; + [EditorSettingPath("Editor/Appearance/Accessibility/Actual Size")] internal sealed class ActualSizeSetting : EditorSetting { - private static readonly (float Value, string Label)[] C_CHOICES = [(0.75f, "75%"), (0.9f, "90%"), (1f, "100%"), (1.1f, "110%"), (1.25f, "125%"), (1.5f, "150%")]; + private static readonly (float Value, string Label)[] C_CHOICES = + [ + (0.75f, "75%"), + (0.9f, "90%"), + (1f, "100%"), + (1.1f, "110%"), + (1.25f, "125%"), + (1.5f, "150%") + ]; + /// /// Gets a new value initialized to this setting's canonical default state. /// public override EditorSettingObject defaultValue => CreateDefault(); + /// /// Gets the presentation section that groups this setting. /// public override string section => "Font"; + /// /// Gets the user-facing explanation of this feature or setting. /// @@ -35,14 +48,18 @@ protected override void OnDraw(EditorSettingObject setting) string preview = GetLabel(value); Ui.SetNextItemWidth(-1f); if (!EditorUI.current.widgets.BeginBoundedCombo("##actual_size", preview)) + { return; + } try { for (int i = 0; i < C_CHOICES.Length; i++) { (float candidate, string label) = C_CHOICES[i]; if (Ui.Selectable(label, MathF.Abs(candidate - value) < 0.0001f)) + { setting.SetAsSingle("value", candidate); + } } } finally @@ -63,7 +80,9 @@ private static string GetLabel(float value) for (int i = 0; i < C_CHOICES.Length; i++) { if (MathF.Abs(C_CHOICES[i].Value - value) < 0.0001f) + { return C_CHOICES[i].Label; + } } return $"{value * 100f:0}%"; diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs index 92f399fc5..ad2d29b9a 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs @@ -4,6 +4,7 @@ using Inno.Editor.Settings; namespace Inno.Editor.Workbench; + /// /// Applies the configured actual UI size and preserves project-local zoom multiples around it. /// @@ -30,8 +31,11 @@ EditorUiSession ui internal bool isActualSize => m_zoomStep == 0; internal bool ZoomIn() => SetStep(m_zoomStep + 1); + internal bool ZoomOut() => SetStep(m_zoomStep - 1); + internal bool UseActualSize() => SetStep(0); + /// /// Initializes this feature when its owning runtime becomes active. /// @@ -95,10 +99,13 @@ private bool SetStep(int step) { float resolved = ResolveZoom(step); if (MathF.Abs(resolved - ResolveZoom(m_zoomStep)) < 0.0001f) + { return false; + } m_zoomStep = step; return ui.widgets.style.SetZoom(resolved); } - private static float NormalizeActualSize(float value) => float.IsFinite(value) ? Math.Clamp(value, EditorStyleMetrics.C_MIN_ZOOM, EditorStyleMetrics.C_MAX_ZOOM) : 1f; + private static float NormalizeActualSize(float value) + => float.IsFinite(value) ? Math.Clamp(value, EditorStyleMetrics.C_MIN_ZOOM, EditorStyleMetrics.C_MAX_ZOOM) : 1f; } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs index 8b9e31b64..e303075a9 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs @@ -2,6 +2,7 @@ using Inno.Editor.Interactions; namespace Inno.Editor.Workbench; + /// /// Increases UI zoom by one multiple of the configured actual size. /// @@ -22,7 +23,9 @@ internal sealed class ZoomInEditorAction(EditorZoomModule zoom) : EditorAction /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => zoom.canZoomIn ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => zoom.canZoomIn ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Applies the editor action to the supplied interaction context. /// @@ -52,7 +55,9 @@ internal sealed class ZoomOutEditorAction(EditorZoomModule zoom) : EditorAction /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => zoom.canZoomOut ? EditorActionState.enabled : EditorActionState.disabled; + protected override EditorActionState Query(EditorActionContext context) + => zoom.canZoomOut ? EditorActionState.enabled : EditorActionState.disabled; + /// /// Applies the editor action to the supplied interaction context. /// @@ -82,7 +87,9 @@ internal sealed class ActualSizeEditorAction(EditorZoomModule zoom) : EditorActi /// /// The validated editor action state that represents the completed operation. /// - protected override EditorActionState Query(EditorActionContext context) => zoom.isActualSize ? EditorActionState.disabled : EditorActionState.enabled; + protected override EditorActionState Query(EditorActionContext context) + => zoom.isActualSize ? EditorActionState.disabled : EditorActionState.enabled; + /// /// Applies the editor action to the supplied interaction context. /// diff --git a/src/composition/player/Inno.Player.Runtime/Deployment/PlayerContentMetadata.cs b/src/composition/player/Inno.Player.Runtime/Deployment/PlayerContentMetadata.cs index de68bfe67..e515e037d 100644 --- a/src/composition/player/Inno.Player.Runtime/Deployment/PlayerContentMetadata.cs +++ b/src/composition/player/Inno.Player.Runtime/Deployment/PlayerContentMetadata.cs @@ -24,7 +24,9 @@ public PlayerContentMetadata( ReadOnlySpan catalog ) { if (manifest.IsEmpty || catalog.IsEmpty) + { throw new ArgumentException("A Player deployment requires nonempty manifest and catalog documents."); + } this.manifest = manifest.ToArray(); this.catalog = catalog.ToArray(); } diff --git a/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs b/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs index ef426889f..55dc29b29 100644 --- a/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs +++ b/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs @@ -35,17 +35,24 @@ IReadOnlyDictionary> assemblies ArgumentNullException.ThrowIfNull(deployment); ArgumentNullException.ThrowIfNull(assemblies); if (assemblies.Count != deployment.modules.Count) + { throw new InvalidDataException("Linked module ownership differs from the code deployment."); + } var sources = new List(deployment.modules.Count); foreach (GameCodeModule module in deployment.modules) { if (!assemblies.TryGetValue(module.name, out IReadOnlyList? linked) || linked is null || linked.Any(static assembly => assembly is null) || !module.assemblies.Select(static assembly => assembly.name).SequenceEqual( - linked.Select(static assembly => assembly.GetName().Name), StringComparer.Ordinal)) + linked.Select(static assembly => assembly.GetName().Name), + StringComparer.Ordinal + ) + ) { throw new InvalidDataException($"Linked code for module '{module.name}' differs from its deployment."); - sources.Add(new StaticModuleSource(module.name, module.domain, - AssemblyScope.Runtime, linked, module.dependencies)); + } + sources.Add( + new StaticModuleSource(module.name, module.domain, AssemblyScope.Runtime, linked, module.dependencies) + ); } m_linkedDeployment = deployment; m_sources = sources.AsReadOnly(); @@ -60,7 +67,9 @@ GameCodeDeployment deployment ArgumentNullException.ThrowIfNull(deployment); deployment.ValidateMatches(m_linkedDeployment); if (m_sources.Count == 0) + { return; + } using AssemblyReloadSession activation = modules.BeginReload(m_sources); activation.Activate(); _ = activation.Complete(); diff --git a/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs b/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs index 763360fe8..486ec9bc2 100644 --- a/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs +++ b/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs @@ -1,5 +1,3 @@ -using Inno.Core.IO; -using Inno.Content; using System; using System.Collections.Generic; using System.IO; @@ -8,30 +6,33 @@ using System.Threading.Tasks; using Inno.Adapter; using Inno.Adapter.Audio; -using Inno.Assets; using Inno.Animation; using Inno.Animation.Runtime; +using Inno.Assets; using Inno.Audio; using Inno.Audio.Runtime; -using Inno.Core.Events; +using Inno.Content; using Inno.Core.Diagnostics; +using Inno.Core.Events; using Inno.Core.Execution; +using Inno.Core.IO; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Extensibility.Modules; using Inno.Engine.Default; +using Inno.Extensibility.Modules; using Inno.Input.Runtime; -using Inno.Runtime; -using Inno.Runtime.Contracts; -using Inno.Scene; using Inno.Platform; using Inno.Rendering; using Inno.Rendering.Runtime; +using Inno.Runtime; +using Inno.Runtime.Contracts; +using Inno.Scene; using Inno.Shell; -using Inno.Storage.Runtime; using Inno.Storage; +using Inno.Storage.Runtime; using Inno.UI.Runtime; + using ShellHost = Inno.Shell.Shell; namespace Inno.Player.Runtime; @@ -51,8 +52,7 @@ private GamePlayerHost( ShellOptions shellOptions, EngineHost engine, PlayerLaunchOptions options - ) - : base(adapterCatalog, shellOptions) + ) : base(adapterCatalog, shellOptions) { m_engine = engine; m_engine.logs.RegisterSink(new ConsoleLogSink(options.consoleColors)); @@ -77,21 +77,29 @@ CancellationToken cancellationToken RuntimeContentCatalog catalog = serialization.Deserialize(metadata.catalog.Span); catalog.Validate(); if (catalog.runtimeAssemblyCount != manifest.modules.Sum(static module => module.assemblies.Length)) + { throw new InvalidDataException("The content catalog and runtime manifest have different code closures."); + } ActivateRuntimeModules( options.moduleActivator, engine.modules, - GameCodeDeployment.FromManifest(manifest.modules)); + GameCodeDeployment.FromManifest(manifest.modules) + ); var pack = new ContentPackDescriptor(catalog.contentHash, catalog.packFileName); content = await options.contentSource.PrepareAsync( pack, new StorageScope(manifest.applicationId), serialization, - cancellationToken); + cancellationToken + ); if (content is null) + { throw new InvalidOperationException("The Player content source returned no prepared store."); + } if (content.descriptor != pack) + { throw new InvalidDataException("The prepared Player content store differs from the selected deployment pack."); + } cancellationToken.ThrowIfCancellationRequested(); host = new GamePlayerHost( options.adapters, @@ -113,7 +121,9 @@ CancellationToken cancellationToken forceSingleThreadedRendering = options.renderOnCallingThread, suspendWhenHidden = options.windowVisible }, - engine, options); + engine, + options + ); host.m_content = content; content = null; host.InitializeRuntime(manifest, options); @@ -160,7 +170,9 @@ internal async Task RunGameAsync( protected override void OnEvent(Event evnt) { if (evnt is not ApplicationSuspensionChangedEvent) + { session.events.Enqueue(evnt); + } } /// @@ -187,16 +199,23 @@ protected override void OnSmokeCompleted(int frameCount) m_engine.diagnostics.RegisterSink(diagnostics); m_engine.diagnostics.UnregisterSink(diagnostics); if (diagnostics.errors.Count != 0) - throw new InvalidOperationException("Player smoke completed with active errors:" + Environment.NewLine - + string.Join(Environment.NewLine, diagnostics.errors)); + { + throw new InvalidOperationException( + "Player smoke completed with active errors:" + Environment.NewLine + + string.Join(Environment.NewLine, diagnostics.errors) + ); + } RenderFrameStatistics? statistics; using (rendering.EnterExecutionScope()) + { statistics = GraphicsSettings.frameStatistics; + } Console.WriteLine( $"INNO-SMOKE frames={frameCount} " + $"views={statistics?.viewCount ?? 0} " + $"draws={statistics?.drawCount ?? 0} " - + $"dispatches={statistics?.dispatchCount ?? 0}"); + + $"dispatches={statistics?.dispatchCount ?? 0}" + ); } /// @@ -218,7 +237,9 @@ protected override void DisposeProductResources() Attempt(() => m_diagnosticLogs?.Dispose()); m_diagnosticLogs = null; if (failures.Count > 0) + { throw new AggregateException("Player retirement failed after all available owners were attempted.", failures); + } void Attempt(Action cleanup) { @@ -275,16 +296,28 @@ PlayerLaunchOptions options documentStream.ReadExactly(documentBytes); m_settings = new ProjectSettingsStore( new ReadOnlyByteDocumentStore(document.entry.key.value!, documentBytes), - m_engine.types, m_engine.serialization, new ProjectId(manifest.applicationId), - AssetSerializationContext.Create(owner.assets)); + m_engine.types, + m_engine.serialization, + new ProjectId(manifest.applicationId), + AssetSerializationContext.Create(owner.assets) + ); settings.SetContributors(manifest.CreateSettingContributors()); settings.RebuildCurrent(); if (!string.Equals(settings.projectId.value, manifest.applicationId, StringComparison.Ordinal)) + { throw new InvalidDataException("Runtime manifest and Project Settings identities do not match."); - return DefaultEngine.CreateSessionSubsystems(new EngineSessionComposition( - owner, adapters, adapterSelection, inputSource, owner.assets, - () => settings.Get(AudioProjectSettings.settingId), - () => options.createStorage(manifest))); + } + return DefaultEngine.CreateSessionSubsystems( + new EngineSessionComposition( + owner, + adapters, + adapterSelection, + inputSource, + owner.assets, + () => settings.Get(AudioProjectSettings.settingId), + () => options.createStorage(manifest) + ) + ); } }); GamePresentationSettings presentation = settings.Get(GamePresentationSettings.settingId); @@ -294,16 +327,25 @@ PlayerLaunchOptions options .GetRequiredSubsystem(); InputRuntime inputRuntime = session.subsystems .GetRequiredSubsystem(); - m_rendering = new RenderRuntime(m_engine.types, renderDevice, m_renderDiagnostics, - targetArtifacts: new ContentRenderTargetArtifactProvider(m_content!, m_engine.serialization, - AssetSerializationContext.Create(session.assets)), + m_rendering = new RenderRuntime( + m_engine.types, + renderDevice, + m_renderDiagnostics, + targetArtifacts: new ContentRenderTargetArtifactProvider( + m_content!, + m_engine.serialization, + AssetSerializationContext.Create(session.assets) + ), contentScopeProvider: () => SceneContentSource.CreateScope(session.scenes), primaryPresentationViewportProvider: size => CreatePresentationViewport(presentation, size), inputSnapshotProvider: () => inputRuntime.snapshot, - primaryInputSurfaceSizeProvider: () => primaryWindow.width > 0 && primaryWindow.height > 0 - ? new RenderPresentationSize(primaryWindow.width, primaryWindow.height) : null, - compositionProgramProvider: adapters.rendering.CreateCompositionProgramProvider( - adapterSelection.rendering)); + primaryInputSurfaceSizeProvider: () => ( + primaryWindow.width > 0 && primaryWindow.height > 0 + ? new RenderPresentationSize(primaryWindow.width, primaryWindow.height) + : null + ), + compositionProgramProvider: adapters.rendering.CreateCompositionProgramProvider(adapterSelection.rendering) + ); UseHostPipeline(m_engine.CreateHostPipeline(DefaultEngine.CreateHostSubsystems(m_rendering))); using (settings.EnterExecutionScope()) using (AnimationExecutionContext.EnterScope(animation)) @@ -311,11 +353,8 @@ PlayerLaunchOptions options using (rendering.EnterExecutionScope()) using (session.EnterExecutionScope()) { - SceneAsset startupAsset = session.assets.Load( - AssetPath.Parse(manifest.startupScene)); - session.scenes.LoadScene(startupAsset.Instantiate( - m_engine.serialization, - session.assets)); + SceneAsset startupAsset = session.assets.Load(AssetPath.Parse(manifest.startupScene)); + session.scenes.LoadScene(startupAsset.Instantiate(m_engine.serialization, session.assets)); } } @@ -329,16 +368,21 @@ GameCodeDeployment deployment ArgumentNullException.ThrowIfNull(deployment); activator.Activate(modules, deployment); string[] activeNames = modules.modules.Select(static module => module.moduleName) - .Order(StringComparer.Ordinal).ToArray(); + .Order(StringComparer.Ordinal) + .ToArray(); string[] expectedNames = deployment.modules.Select(static module => module.name) - .Order(StringComparer.Ordinal).ToArray(); + .Order(StringComparer.Ordinal) + .ToArray(); if (!activeNames.SequenceEqual(expectedNames, StringComparer.Ordinal)) + { throw new InvalidOperationException("The frozen runtime code generation was not activated completely."); + } } private sealed class SmokeDiagnostics : IDiagnosticSink { internal readonly List errors = []; + /// /// Records errors from the current diagnostic report. /// @@ -348,15 +392,20 @@ private sealed class SmokeDiagnostics : IDiagnosticSink public void Replace(DiagnosticReport report) { foreach (Diagnostic diagnostic in report.diagnostics) + { if (diagnostic.severity == DiagnosticSeverity.Error) + { errors.Add(report.source.id + "/" + diagnostic.code + ": " + diagnostic.message); + } + } } + /// /// Removes all retained entries and returns the instance to an empty reusable state. /// /// /// The source value or location read by this operation. /// - public void Clear(DiagnosticSource source) { } + public void Clear(DiagnosticSource source) {} } } diff --git a/src/composition/player/Inno.Player.Runtime/PlayerCommandLineOptions.cs b/src/composition/player/Inno.Player.Runtime/PlayerCommandLineOptions.cs index 0b9ab0bae..ad542089d 100644 --- a/src/composition/player/Inno.Player.Runtime/PlayerCommandLineOptions.cs +++ b/src/composition/player/Inno.Player.Runtime/PlayerCommandLineOptions.cs @@ -8,7 +8,7 @@ namespace Inno.Player.Runtime; /// public sealed class PlayerCommandLineOptions { - private PlayerCommandLineOptions() { } + private PlayerCommandLineOptions() {} /// /// Gets an optional positive bounded run length. @@ -48,6 +48,7 @@ public static PlayerCommandLineOptions Parse(string[] arguments) windowVisible = visible }; } + private static void ParseValues( string[] arguments, out int? smokeFrameLimit, @@ -61,13 +62,15 @@ out bool windowVisible for (int index = 0; index < arguments.Length; index += 2) { if (index + 1 >= arguments.Length) + { throw Usage(); + } if (string.Equals(arguments[index], "--smoke-frames", StringComparison.Ordinal)) { if (smokeFrameLimit is not null || !int.TryParse(arguments[index + 1], out int frameCount) - || frameCount <= 0) - { + || frameCount <= 0 + ) { throw Usage(); } smokeFrameLimit = frameCount; @@ -76,14 +79,18 @@ out bool windowVisible if (string.Equals(arguments[index], "--graphics-api", StringComparison.Ordinal)) { if (graphicsApi is not null || !TryParseGraphicsApi(arguments[index + 1], out GraphicsApi api)) + { throw Usage(); + } graphicsApi = api; continue; } if (string.Equals(arguments[index], "--window-visible", StringComparison.Ordinal)) { if (visibilitySpecified || !bool.TryParse(arguments[index + 1], out windowVisible)) + { throw Usage(); + } visibilitySpecified = true; continue; } @@ -112,6 +119,8 @@ out GraphicsApi api return api.isValid && api != GraphicsApi.Noop; } - private static ArgumentException Usage() => new( - "Usage: Player [--graphics-api ] [--window-visible ] [--smoke-frames ]."); + private static ArgumentException Usage() + => new( + "Usage: Player [--graphics-api ] [--window-visible ] [--smoke-frames ]." + ); } diff --git a/src/composition/shell/Inno.Shell/PollingShellFrameDriver.cs b/src/composition/shell/Inno.Shell/PollingShellFrameDriver.cs index 4b3dba8a2..40b53e0ff 100644 --- a/src/composition/shell/Inno.Shell/PollingShellFrameDriver.cs +++ b/src/composition/shell/Inno.Shell/PollingShellFrameDriver.cs @@ -41,7 +41,9 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); if (!advanceFrame()) + { return ValueTask.CompletedTask; + } } } } diff --git a/src/composition/shell/Inno.Shell/ScheduledShellFrameDriver.cs b/src/composition/shell/Inno.Shell/ScheduledShellFrameDriver.cs index 50db2552c..08cd0e43e 100644 --- a/src/composition/shell/Inno.Shell/ScheduledShellFrameDriver.cs +++ b/src/composition/shell/Inno.Shell/ScheduledShellFrameDriver.cs @@ -59,7 +59,9 @@ CancellationToken cancellationToken await m_nextFrame(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); if (!advanceFrame()) + { return; + } } } } diff --git a/src/composition/shell/Inno.Shell/Shell.cs b/src/composition/shell/Inno.Shell/Shell.cs index b0a35f0ae..7b27a8bf6 100644 --- a/src/composition/shell/Inno.Shell/Shell.cs +++ b/src/composition/shell/Inno.Shell/Shell.cs @@ -142,12 +142,14 @@ public async Task RunAsync( { state = ShellState.Faulted; failure = failure is null - ? stoppingFailure - : new AggregateException("Shell execution and stopping both failed.", failure, stoppingFailure); + ? stoppingFailure + : new AggregateException("Shell execution and stopping both failed.", failure, stoppingFailure); } } if (failure is not null) + { ExceptionDispatchInfo.Capture(failure).Throw(); + } return 0; } @@ -157,18 +159,28 @@ public async Task RunAsync( public void Dispose() { if (m_disposed) + { return; + } List? failures = null; Release(NotifyStopping, ref failures); Release(RetireProductResources, ref failures); if (m_renderDevice is not null) + { Release(m_renderDevice.Dispose, ref failures); + } if (m_inputSource is not null) + { Release(m_inputSource.Dispose, ref failures); + } if (m_primaryWindow is not null) + { Release(m_primaryWindow.Dispose, ref failures); + } if (m_platformApplication is not null) + { Release(m_platformApplication.Dispose, ref failures); + } m_disposed = true; if (failures is not null) { @@ -240,7 +252,9 @@ protected void UseHostPipeline(RuntimeSubsystemPipeline pipeline) { ArgumentNullException.ThrowIfNull(pipeline); if (m_subsystems is not null) + { throw new InvalidOperationException("The Shell already has a host subsystem pipeline."); + } m_subsystems = pipeline; } @@ -254,7 +268,9 @@ protected void InitializeAdapterResources() { ObjectDisposedException.ThrowIf(m_disposed, this); if (state != ShellState.Created) + { throw new InvalidOperationException("The composition shell cannot initialize adapter resources in its current state."); + } m_adapterSelection.Validate(m_adapterCatalog); try @@ -264,7 +280,8 @@ protected void InitializeAdapterResources() m_inputSource = m_adapterCatalog.input.CreateEventSource( m_adapterSelection.input, m_primaryWindow, - acceptAllWindows: false); + acceptAllWindows: false + ); m_renderDevice = m_adapterCatalog.rendering.CreateDevice( m_adapterSelection.rendering, new RenderingBackendOptions @@ -274,7 +291,8 @@ protected void InitializeAdapterResources() verticalSync = options.verticalSync, sRgbBackbuffer = options.sRgbBackbuffer, forceSingleThreaded = options.forceSingleThreadedRendering - }); + } + ); UpdatePrimaryPresentationSize(); state = ShellState.Ready; } @@ -283,16 +301,24 @@ protected void InitializeAdapterResources() state = ShellState.Faulted; List? failures = null; if (m_renderDevice is not null) + { Release(m_renderDevice.Dispose, ref failures); + } m_renderDevice = null; if (m_inputSource is not null) + { Release(m_inputSource.Dispose, ref failures); + } m_inputSource = null; if (m_primaryWindow is not null) + { Release(m_primaryWindow.Dispose, ref failures); + } m_primaryWindow = null; if (m_platformApplication is not null) + { Release(m_platformApplication.Dispose, ref failures); + } m_platformApplication = null; if (failures is not null) { @@ -311,9 +337,7 @@ protected void InitializeAdapterResources() /// /// Runs once immediately before the common event and frame loop starts. /// - protected virtual void OnStarting() - { - } + protected virtual void OnStarting() {} /// /// Receives one backend-neutral platform event after shared input routing and close evaluation. @@ -321,9 +345,7 @@ protected virtual void OnStarting() /// /// Event produced by the active platform adapter. /// - protected virtual void OnEvent(Event evnt) - { - } + protected virtual void OnEvent(Event evnt) {} /// /// Receives an effective application suspension change at an event-pump safety point. @@ -332,7 +354,7 @@ protected virtual void OnEvent(Event evnt) /// /// Whether product frames and their clock are suspended after the change. /// - protected virtual void OnSuspensionChanged(bool isSuspended) { } + protected virtual void OnSuspensionChanged(bool isSuspended) {} /// /// Determines whether one event requests orderly product shutdown. @@ -361,7 +383,7 @@ protected virtual bool ShouldExit(Event evnt) /// /// The current application frame. /// - protected virtual void OnPresentation(ShellFrame frame) { } + protected virtual void OnPresentation(ShellFrame frame) {} /// /// Receives the final frame count only when a bounded smoke run reaches its requested frame limit. @@ -370,35 +392,37 @@ protected virtual void OnPresentation(ShellFrame frame) { } /// /// Number of product frames completed by the smoke run. /// - protected virtual void OnSmokeCompleted(int frameCount) - { - } + protected virtual void OnSmokeCompleted(int frameCount) {} /// /// Runs once when the main loop is stopping while all product and adapter resources remain alive. /// - protected virtual void OnStopping() - { - } + protected virtual void OnStopping() {} /// /// Releases resources owned by the derived product before common adapter resources are destroyed. /// - protected virtual void DisposeProductResources() - { - } + protected virtual void DisposeProductResources() {} private bool AdvanceFrame() { if (m_exitRequested || primaryWindow.isClosed) + { return false; + } PumpEvents(); if (m_exitRequested || primaryWindow.isClosed) + { return false; + } if (state == ShellState.Running) + { DrawFrame(); + } else if (m_allowBlockingPacing) + { Thread.Sleep(10); + } return !m_exitRequested && !primaryWindow.isClosed; } @@ -407,15 +431,19 @@ private void PrepareRun( bool allowBlockingPacing ) { ObjectDisposedException.ThrowIf(m_disposed, this); - if (m_platformApplication is null || m_primaryWindow is null || - m_inputSource is null || m_renderDevice is null) - { + if (m_platformApplication is null || m_primaryWindow is null + || m_inputSource is null || m_renderDevice is null + ) { throw new InvalidOperationException("The composition shell adapter resources are not initialized."); } if (smokeFrameLimit is <= 0) + { throw new ArgumentOutOfRangeException(nameof(smokeFrameLimit)); + } if (m_hasRun || state != ShellState.Ready) + { throw new InvalidOperationException("A composition shell can run only once."); + } m_hasRun = true; m_timer = Stopwatch.StartNew(); m_smokeFrameLimit = smokeFrameLimit; @@ -425,9 +453,13 @@ bool allowBlockingPacing private void Redraw(uint windowId) { if (state != ShellState.Running || !hasCompletedFrame || m_frameActive || m_exitRequested || primaryWindow.isClosed) + { return; + } if (windowId == primaryWindow.windowId) + { UpdatePrimaryPresentationSize(); + } DrawFrame(); } @@ -445,8 +477,15 @@ private void DrawFrame() double totalTime = m_timer!.Elapsed.TotalSeconds; float deltaTime = Math.Max(0f, (float)(totalTime - m_previousTime)); var frame = new ShellFrame(m_frameCount, totalTime, deltaTime); - var runtimeFrame = new RuntimeFrame(m_frameCount, (float)totalTime, (float)totalTime, - deltaTime, deltaTime, 1f, false); + var runtimeFrame = new RuntimeFrame( + m_frameCount, + (float)totalTime, + (float)totalTime, + deltaTime, + deltaTime, + 1f, + false + ); try { m_subsystems?.BeginFrame(runtimeFrame); @@ -454,9 +493,13 @@ private void DrawFrame() m_subsystems?.Update(runtimeFrame); m_subsystems?.LateUpdate(runtimeFrame); if (m_subsystems is not null) + { m_subsystems.RenderFrame(runtimeFrame, () => OnPresentation(frame)); + } else + { OnPresentation(frame); + } } finally { @@ -466,13 +509,17 @@ private void DrawFrame() m_frameCount++; hasCompletedFrame = true; if (m_smokeFrameLimit.HasValue && m_frameCount >= m_smokeFrameLimit.Value) + { RequestExit(); + } int maximumRate = framePacing.maximumFrameRate; if (m_allowBlockingPacing && maximumRate > 0) { double remaining = 1d / maximumRate - (m_timer.Elapsed.TotalSeconds - totalTime); if (remaining > 0d) + { Thread.Sleep(TimeSpan.FromSeconds(remaining)); + } } } finally @@ -484,7 +531,9 @@ private void DrawFrame() private void CompleteSmokeRun() { if (m_smokeFrameLimit.HasValue && m_frameCount >= m_smokeFrameLimit.Value) + { OnSmokeCompleted(m_frameCount); + } } private void PumpEvents() @@ -492,14 +541,22 @@ private void PumpEvents() while (platformApplication.PollEvent(out Event? evnt)) { if (evnt is null) + { continue; + } ApplySuspension(evnt); if (state == ShellState.Suspended && evnt is KeyEvent or MouseEvent or TextInputEvent) + { continue; + } if (evnt is not ApplicationSuspensionChangedEvent) + { inputSource.ProcessEvent(evnt); + } if (evnt is WindowResizeEvent resize && resize.windowId == primaryWindow.windowId) + { UpdatePrimaryPresentationSize(); + } if (ShouldExit(evnt)) { RequestExit(); @@ -538,7 +595,9 @@ private void ApplySuspension(Event evnt) UpdatePrimaryPresentationSize(); bool suspended = m_applicationSuspended || (m_suspendWhenHidden && m_primaryWindowHidden); if (suspended == (state == ShellState.Suspended)) + { return; + } if (suspended) { m_timer!.Stop(); @@ -559,13 +618,17 @@ private void UpdatePrimaryPresentationSize() int height = primaryWindow.pixelHeight; renderDevice.SetPrimaryPresentationSize( !primaryWindow.isClosed && !m_primaryWindowHidden && !m_applicationSuspended && width > 0 && height > 0 - ? new RenderPresentationSize(width, height) : null); + ? new RenderPresentationSize(width, height) + : null + ); } private void NotifyStopping() { if (m_stoppingNotified) + { return; + } m_stoppingNotified = true; bool faulted = state == ShellState.Faulted; state = ShellState.Stopping; diff --git a/src/composition/shell/Inno.Shell/ShellState.cs b/src/composition/shell/Inno.Shell/ShellState.cs index 1ed238822..507266e2e 100644 --- a/src/composition/shell/Inno.Shell/ShellState.cs +++ b/src/composition/shell/Inno.Shell/ShellState.cs @@ -9,37 +9,30 @@ public enum ShellState /// Adapter resources have not been initialized. /// Created, - /// /// Adapter resources are ready for the single permitted run. /// Ready, - /// /// Platform events and product frames are advancing. /// Running, - /// /// Platform events continue while product frames and their clock are suspended. /// Suspended, - /// /// The stopping callback is executing while resources remain alive. /// Stopping, - /// /// The run ended or was canceled and the stopping callback completed. /// Stopped, - /// /// Initialization, execution, or retirement failed; another run is prohibited. /// Faulted, - /// /// All owned resources were released successfully. /// diff --git a/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs b/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs index 098c4d0fe..b67ea07dc 100644 --- a/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs +++ b/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets.Pipeline; using Inno.Core.Serialization; @@ -43,7 +42,8 @@ CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); AnimationClipSource source = context.serialization.Deserialize( - context.sourceBytes.ToArray()); + context.sourceBytes.ToArray() + ); var clip = new AnimationClipAsset { duration = source.duration, @@ -52,10 +52,7 @@ CancellationToken cancellationToken }; clip.Validate(); output.SetAsset(clip); - await output.WriteArtifactAsync( - "runtime", - context.sourceBytes, - cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken).ConfigureAwait(false); } /// diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs b/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs index e8b980613..01bbae2a2 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs @@ -59,22 +59,30 @@ public void Apply(ReadOnlySpan samples) { ObjectDisposedException.ThrowIf(m_disposed, this); if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Animation bindings must run on their owner thread."); + } Snapshot snapshot = m_registry.snapshot; var issues = new Dictionary<(string, Guid), Diagnostic>(); foreach (AnimationSample sample in samples) { if (sample.target.isSamplingOnly) + { continue; + } string? message = null; if (!snapshot.providers.TryGetValue((sample.binding, sample.value.kind), out AnimationBindingProvider? provider)) + { message = "The animation binding provider is missing; the playback remains available."; + } else { try { if (!provider.TryApply(sample.target, sample.value)) + { message = "The animation destination is missing or incompatible."; + } } catch (Exception exception) { @@ -82,9 +90,15 @@ public void Apply(ReadOnlySpan samples) } } if (message is not null) + { issues[(sample.binding.value, sample.target.persistentId)] = new Diagnostic( - "animation.binding.unavailable", message, DiagnosticSeverity.Warning, - sample.binding.value, sample.target.persistentId); + "animation.binding.unavailable", + message, + DiagnosticSeverity.Warning, + sample.binding.value, + sample.target.persistentId + ); + } } m_diagnostics.Replace(issues.Values); } @@ -95,7 +109,9 @@ public void Apply(ReadOnlySpan samples) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_registry.Dispose(); m_diagnostics.Replace([]); @@ -123,13 +139,24 @@ protected override Snapshot Build(TypeCacheSnapshot types) foreach (TypeRef reference in types.GetTypesWithAttribute()) { Type type = reference.Resolve(types); - AnimationBindingProviderAttribute declaration = types.GetAttribute(reference, false)!; + AnimationBindingProviderAttribute declaration = types.GetAttribute( + reference, + false + )!; if (type.IsAbstract || type.ContainsGenericParameters || !typeof(AnimationBindingProvider).IsAssignableFrom(type) - || !types.CanCreateInstance(reference)) - throw new InvalidOperationException($"Animation provider '{declaration.id}' requires a concrete public parameterless implementation."); + || !types.CanCreateInstance(reference) + ) { + throw new InvalidOperationException( + $"Animation provider '{declaration.id}' requires a concrete public parameterless implementation." + ); + } var key = (declaration.bindingId, declaration.kind); if (!ids.Add(declaration.id) || result.providers.ContainsKey(key)) - throw new InvalidOperationException($"Animation provider '{declaration.id}' duplicates an extension ID or binding protocol."); + { + throw new InvalidOperationException( + $"Animation provider '{declaration.id}' duplicates an extension ID or binding protocol." + ); + } result.providers.Add(key, CreateExtension(type)); } return result; @@ -173,7 +200,9 @@ public void Dispose() } providers.Clear(); if (failures is not null) + { throw new AggregateException("Animation provider retirement failed.", failures); + } } } } diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs b/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs index 61250c6a4..c7ed15dd9 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs @@ -8,7 +8,10 @@ private AnimationClipSnapshot(AnimationClipAsset clip) { duration = clip.duration; tracks = clip.tracks.Select(static track => new AnimationTrack( - track.bindingId, track.interpolation, track.keyframes)).ToArray(); + track.bindingId, + track.interpolation, + track.keyframes + )).ToArray(); events = clip.events.Select(static marker => new AnimationEventMarker { time = marker.time, diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs b/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs index 9f341b4d1..3c44208ed 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs @@ -1,10 +1,9 @@ -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; - using Inno.Core.Events; +using Inno.Runtime.Contracts; namespace Inno.Animation.Runtime; @@ -24,6 +23,7 @@ public sealed class AnimationRuntime : RuntimeSubsystem, IAnimationService private bool m_disposed; private readonly int m_maxPlaybacks; private long m_rejectedPlaybacks; + /// /// Captures snapshots and binds service façades. /// @@ -31,6 +31,7 @@ public sealed class AnimationRuntime : RuntimeSubsystem, IAnimationService /// The variable frame timing. /// protected override void OnBeginFrame(RuntimeFrame frame) => OwnFrameScope(AnimationExecutionContext.EnterScope(this)); + /// /// Advances domain state on the variable clock. /// @@ -87,8 +88,7 @@ public AnimationRuntime( public AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target - ) - => Play(clip, target, AnimationPlayOptions.defaultValue); + ) => Play(clip, target, AnimationPlayOptions.defaultValue); /// /// Starts one clip with an explicit clock, looping, speed, layer, and blend policy. @@ -125,7 +125,9 @@ AnimationPlayOptions options ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(clip); if (!target.isValid) + { throw new ArgumentException("An explicit animation destination is required.", nameof(target)); + } clip.Validate(); ValidateOptions(options); if (m_playbacks.Count - m_freeSlots.Count >= m_maxPlaybacks) @@ -147,9 +149,13 @@ AnimationPlayOptions options } var playback = new Playback(snapshot, target, options, generation); if (slot == m_playbacks.Count) + { m_playbacks.Add(playback); + } else + { m_playbacks[slot] = playback; + } return m_handles.Create(slot, generation); } @@ -175,7 +181,9 @@ AnimationPlayOptions options public bool Stop(AnimationPlaybackHandle handle) { if (!TryGetPlayback(handle, out Playback? playback)) + { return false; + } var identity = m_handles.Decode(handle); Retire(identity.slot, playback); return true; @@ -193,7 +201,9 @@ public bool Stop(AnimationPlaybackHandle handle) public bool Pause(AnimationPlaybackHandle handle) { if (!TryGetPlayback(handle, out Playback? playback) || playback.state == AnimationPlaybackState.Paused) + { return false; + } playback.state = AnimationPlaybackState.Paused; return true; } @@ -210,7 +220,9 @@ public bool Pause(AnimationPlaybackHandle handle) public bool Resume(AnimationPlaybackHandle handle) { if (!TryGetPlayback(handle, out Playback? playback) || playback.state == AnimationPlaybackState.Playing) + { return false; + } playback.state = AnimationPlaybackState.Playing; return true; } @@ -235,9 +247,13 @@ public bool Seek( float time ) { if (!float.IsFinite(time)) + { throw new ArgumentOutOfRangeException(nameof(time)); + } if (!TryGetPlayback(handle, out Playback? playback)) + { return false; + } playback.time = Math.Clamp(time, 0f, playback.clip.duration); return true; } @@ -288,33 +304,35 @@ float unscaledDeltaTime ) { ObjectDisposedException.ThrowIf(m_disposed, this); if (!float.IsFinite(scaledDeltaTime) || scaledDeltaTime < 0f) + { throw new ArgumentOutOfRangeException(nameof(scaledDeltaTime)); + } if (!float.IsFinite(unscaledDeltaTime) || unscaledDeltaTime < 0f) + { throw new ArgumentOutOfRangeException(nameof(unscaledDeltaTime)); + } var samples = new Dictionary<(AnimationTarget target, AnimationBindingId binding), BlendAccumulator>(); for (int slot = 0; slot < m_playbacks.Count; slot++) { Playback? playback = m_playbacks[slot]; if (playback is null) + { continue; - AnimationPlaybackHandle handle = m_handles.Create( - slot, - playback.generation); + } + AnimationPlaybackHandle handle = m_handles.Create(slot, playback.generation); float previousTime = playback.time; if (playback.state == AnimationPlaybackState.Playing) { float delta = playback.options.clock == AnimationClock.Scaled - ? scaledDeltaTime - : unscaledDeltaTime; - bool completed = Advance( - handle, - playback, - previousTime, - delta * playback.options.speed); + ? scaledDeltaTime + : unscaledDeltaTime; + bool completed = Advance(handle, playback, previousTime, delta * playback.options.speed); Sample(playback, samples); if (completed) + { Retire(slot, playback); + } continue; } Sample(playback, samples); @@ -334,7 +352,9 @@ float unscaledDeltaTime protected override void OnStop() { if (m_disposed) + { return; + } m_disposed = true; m_playbacks.Clear(); m_slotGenerations.Clear(); @@ -348,7 +368,9 @@ private bool Advance( float delta ) { if (delta <= 0f) + { return false; + } float duration = playback.clip.duration; float total = previousTime + delta; if (!playback.options.loop && total >= duration) @@ -374,7 +396,9 @@ float delta remaining -= segment; cursor += segment; if (cursor >= duration) + { cursor = 0f; + } } playback.time = cursor; return false; @@ -391,10 +415,7 @@ float endInclusive AnimationEventMarker marker = clip.events[index]; if (marker.time > startExclusive && marker.time <= endInclusive) { - m_events.Enqueue(new AnimationMarkerEvent( - handle, - marker.eventId, - marker.payload)); + m_events.Enqueue(new AnimationMarkerEvent(handle, marker.eventId, marker.payload)); } } } @@ -404,20 +425,19 @@ private static void Sample( IDictionary<(AnimationTarget target, AnimationBindingId binding), BlendAccumulator> samples ) { if (playback.options.weight <= 0f) + { return; + } for (int index = 0; index < playback.clip.tracks.Length; index++) { AnimationTrack track = playback.clip.tracks[index]; var binding = new AnimationBindingId(track.bindingId); var destination = (playback.target, binding); AnimationValue value = SampleTrack(track, playback.time); - if (!samples.TryGetValue(destination, out BlendAccumulator accumulator) || - playback.options.layer > accumulator.layer) - { - samples[destination] = new BlendAccumulator( - playback.options.layer, - value, - playback.options.weight); + if (!samples.TryGetValue(destination, out BlendAccumulator accumulator) + || playback.options.layer > accumulator.layer + ) { + samples[destination] = new BlendAccumulator(playback.options.layer, value, playback.options.weight); continue; } if (playback.options.layer == accumulator.layer) @@ -434,19 +454,26 @@ float time ) { AnimationKeyframe[] keys = track.keyframes; if (time <= keys[0].time) + { return keys[0].value; + } for (int index = 1; index < keys.Length; index++) { if (time > keys[index].time) + { continue; + } AnimationKeyframe left = keys[index - 1]; AnimationKeyframe right = keys[index]; if (track.interpolation == AnimationInterpolation.Step || right.time <= left.time) + { return left.value; + } return AnimationSampling.Interpolate( left.value, right.value, - (time - left.time) / (right.time - left.time)); + (time - left.time) / (right.time - left.time) + ); } return keys[^1].value; } @@ -457,9 +484,9 @@ private bool TryGetPlayback( ) { playback = null; var identity = m_handles.Decode(handle); - if (m_disposed || !handle.isValid || handle.runtimeGeneration != m_runtimeGeneration || - identity.slot < 0 || identity.slot >= m_playbacks.Count) - { + if (m_disposed || !handle.isValid || handle.runtimeGeneration != m_runtimeGeneration + || identity.slot < 0 || identity.slot >= m_playbacks.Count + ) { return false; } playback = m_playbacks[identity.slot]; @@ -472,7 +499,9 @@ Playback playback ) { uint next = unchecked(playback.generation + 1); if (next == 0) + { next = 1; + } m_slotGenerations[slot] = next; m_playbacks[slot] = null; m_freeSlots.Push(slot); @@ -481,9 +510,13 @@ Playback playback private static void ValidateOptions(AnimationPlayOptions options) { if (!float.IsFinite(options.speed) || options.speed < 0f) + { throw new ArgumentOutOfRangeException(nameof(options), "Animation speed must be finite and non-negative."); + } if (!float.IsFinite(options.weight) || options.weight < 0f || options.weight > 1f) + { throw new ArgumentOutOfRangeException(nameof(options), "Animation weight must be between zero and one."); + } } private sealed class Playback( @@ -528,13 +561,6 @@ float weight private static AnimationValue Multiply( AnimationValue value, float weight - ) - => new( - value.kind, - value.x * weight, - value.y * weight, - value.z * weight, - value.w * weight); + ) => new(value.kind, value.x * weight, value.y * weight, value.z * weight, value.w * weight); } - } diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationRuntimeFactory.cs b/src/content/animation/Inno.Animation.Runtime/AnimationRuntimeFactory.cs index 1bd14c190..02752e8b0 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationRuntimeFactory.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationRuntimeFactory.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Animation.Runtime; @@ -29,7 +28,8 @@ public AnimationRuntimeFactory(Func r public RuntimeSubsystemDescriptor descriptor { get; } = new( new RuntimeSubsystemId("inno.runtime.animation"), order: 400, - dependencies: [new RuntimeSubsystemId("inno.runtime.scene")]); + dependencies: [new RuntimeSubsystemId("inno.runtime.scene")] + ); /// /// Creates a feature over a newly allocated animation runtime. @@ -44,7 +44,7 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); AnimationRuntime runtime = m_runtimeFactory(context) - ?? throw new InvalidOperationException("The animation runtime factory returned null."); + ?? throw new InvalidOperationException("The animation runtime factory returned null."); return runtime; } } diff --git a/src/content/animation/Inno.Animation/Animation.cs b/src/content/animation/Inno.Animation/Animation.cs index fffd3e743..cab9c35bb 100644 --- a/src/content/animation/Inno.Animation/Animation.cs +++ b/src/content/animation/Inno.Animation/Animation.cs @@ -1,6 +1,6 @@ -using Inno.Core.Execution; using System; using System.Threading; +using Inno.Core.Execution; namespace Inno.Animation; @@ -30,7 +30,6 @@ public static IDisposable EnterScope(IAnimationService animation) ArgumentNullException.ThrowIfNull(animation); return S_CURRENT_SCOPE.Enter(animation); } - } /// @@ -53,8 +52,7 @@ public static class Animation public static AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target - ) - => AnimationExecutionContext.current.Play(clip, target); + ) => AnimationExecutionContext.current.Play(clip, target); /// /// Starts one clip with explicit playback options. @@ -75,8 +73,7 @@ public static AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target, AnimationPlayOptions options - ) - => AnimationExecutionContext.current.Play(clip, target, options); + ) => AnimationExecutionContext.current.Play(clip, target, options); /// /// Stops one live playback. @@ -147,6 +144,5 @@ public static bool TryGetState( AnimationPlaybackHandle handle, out AnimationPlaybackState state, out float time - ) - => AnimationExecutionContext.current.TryGetState(handle, out state, out time); + ) => AnimationExecutionContext.current.TryGetState(handle, out state, out time); } diff --git a/src/content/animation/Inno.Animation/AnimationBindingProvider.cs b/src/content/animation/Inno.Animation/AnimationBindingProvider.cs index 425dd6037..60bda7bb9 100644 --- a/src/content/animation/Inno.Animation/AnimationBindingProvider.cs +++ b/src/content/animation/Inno.Animation/AnimationBindingProvider.cs @@ -27,5 +27,5 @@ AnimationValue value /// /// Releases subscriptions and resources owned by this extension generation. /// - public virtual void Dispose() { } + public virtual void Dispose() {} } diff --git a/src/content/animation/Inno.Animation/AnimationBindingProviderAttribute.cs b/src/content/animation/Inno.Animation/AnimationBindingProviderAttribute.cs index 7febb51b9..71ddbce76 100644 --- a/src/content/animation/Inno.Animation/AnimationBindingProviderAttribute.cs +++ b/src/content/animation/Inno.Animation/AnimationBindingProviderAttribute.cs @@ -31,7 +31,9 @@ AnimationValueKind kind ArgumentException.ThrowIfNullOrWhiteSpace(id); ArgumentException.ThrowIfNullOrWhiteSpace(bindingId); if (!Enum.IsDefined(kind)) + { throw new ArgumentException("A defined animation value kind is required.", nameof(kind)); + } this.id = id; this.bindingId = new AnimationBindingId(bindingId); this.kind = kind; diff --git a/src/content/animation/Inno.Animation/AnimationClipAsset.cs b/src/content/animation/Inno.Animation/AnimationClipAsset.cs index c318521d7..4a411bf21 100644 --- a/src/content/animation/Inno.Animation/AnimationClipAsset.cs +++ b/src/content/animation/Inno.Animation/AnimationClipAsset.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; @@ -27,7 +26,9 @@ public AnimationKeyframe( AnimationValue value ) { if (!float.IsFinite(time) || time < 0f) + { throw new ArgumentOutOfRangeException(nameof(time)); + } this.time = time; this.value = value; } @@ -53,9 +54,7 @@ public sealed class AnimationTrack : ISerializable /// /// Creates an empty track for structured deserialization. /// - public AnimationTrack() - { - } + public AnimationTrack() {} /// /// Creates one validated animation track. @@ -104,16 +103,22 @@ internal void Validate(float duration) { ArgumentException.ThrowIfNullOrWhiteSpace(bindingId); if (keyframes is null || keyframes.Length == 0) + { throw new InvalidOperationException($"Animation track '{bindingId}' requires at least one keyframe."); + } AnimationValueKind kind = keyframes[0].value.kind; float previous = -1f; for (int index = 0; index < keyframes.Length; index++) { AnimationKeyframe keyframe = keyframes[index]; if (!float.IsFinite(keyframe.time) || keyframe.time < previous || keyframe.time > duration) + { throw new InvalidOperationException($"Animation track '{bindingId}' contains invalid keyframe times."); + } if (keyframe.value.kind != kind) + { throw new InvalidOperationException($"Animation track '{bindingId}' mixes incompatible value kinds."); + } previous = keyframe.time; } } @@ -176,27 +181,37 @@ public sealed class AnimationClipAsset : AssetObject public void Validate() { if (!float.IsFinite(duration) || duration <= 0f) + { throw new InvalidOperationException("An animation clip requires a positive finite duration."); + } if (tracks is null || events is null) + { throw new InvalidOperationException("Animation clip collections cannot be null."); + } var bindings = new HashSet(StringComparer.Ordinal); for (int index = 0; index < tracks.Length; index++) { AnimationTrack track = tracks[index] - ?? throw new InvalidOperationException("Animation clip tracks cannot contain null entries."); + ?? throw new InvalidOperationException("Animation clip tracks cannot contain null entries."); track.Validate(duration); if (!bindings.Add(track.bindingId)) + { throw new InvalidOperationException($"Animation binding '{track.bindingId}' is duplicated."); + } } float previous = -1f; for (int index = 0; index < events.Length; index++) { AnimationEventMarker marker = events[index] - ?? throw new InvalidOperationException("Animation clip events cannot contain null entries."); + ?? throw new InvalidOperationException("Animation clip events cannot contain null entries."); if (!float.IsFinite(marker.time) || marker.time < previous || marker.time > duration) + { throw new InvalidOperationException("Animation clip event markers must be ordered within its duration."); + } if (string.IsNullOrWhiteSpace(marker.eventId)) + { throw new InvalidOperationException("Animation event markers require stable event identifiers."); + } marker.payload ??= []; previous = marker.time; } diff --git a/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs b/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs index 944c47f5f..a0498752b 100644 --- a/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs +++ b/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs @@ -20,7 +20,9 @@ public AnimationPlaybackAllocator() { int next = Interlocked.Increment(ref S_NEXT_GENERATION); if (next <= 0) + { throw new InvalidOperationException("Animation owner generations are exhausted."); + } generation = (uint)next; } @@ -50,7 +52,9 @@ uint slotGeneration ) { ArgumentOutOfRangeException.ThrowIfNegative(slot); if (slotGeneration == 0) + { throw new ArgumentOutOfRangeException(nameof(slotGeneration)); + } return new AnimationPlaybackHandle(((ulong)slotGeneration << 32) | ((uint)slot + 1U), generation); } @@ -66,7 +70,9 @@ uint slotGeneration public (int slot, uint generation) Decode(AnimationPlaybackHandle handle) { if (!handle.isValid || handle.runtimeGeneration != generation) + { return (-1, 0); + } uint encodedSlot = (uint)(handle.value & uint.MaxValue); return (checked((int)(encodedSlot - 1U)), (uint)(handle.value >> 32)); } diff --git a/src/content/animation/Inno.Animation/AnimationSampling.cs b/src/content/animation/Inno.Animation/AnimationSampling.cs index 92b3b2be9..4e46fd0e8 100644 --- a/src/content/animation/Inno.Animation/AnimationSampling.cs +++ b/src/content/animation/Inno.Animation/AnimationSampling.cs @@ -24,8 +24,7 @@ public static AnimationValue Interpolate( AnimationValue left, AnimationValue right, float amount - ) - => AnimationValue.Lerp(left, right, amount); + ) => AnimationValue.Lerp(left, right, amount); /// /// Adds one weighted value to an accumulation of the same kind. @@ -46,8 +45,7 @@ public static AnimationValue AddWeighted( AnimationValue sum, AnimationValue value, float weight - ) - => AnimationValue.AddWeighted(sum, value, weight); + ) => AnimationValue.AddWeighted(sum, value, weight); /// /// Normalizes a weighted sum, including quaternion normalization. @@ -64,6 +62,5 @@ float weight public static AnimationValue CompleteWeighted( AnimationValue sum, float inverseWeight - ) - => AnimationValue.WeightedAverage(sum, inverseWeight); + ) => AnimationValue.WeightedAverage(sum, inverseWeight); } diff --git a/src/content/animation/Inno.Animation/AnimationTarget.cs b/src/content/animation/Inno.Animation/AnimationTarget.cs index b9eea0c61..5f6ef56e1 100644 --- a/src/content/animation/Inno.Animation/AnimationTarget.cs +++ b/src/content/animation/Inno.Animation/AnimationTarget.cs @@ -24,7 +24,7 @@ namespace Inno.Animation; public AnimationTarget(Identity identity) { m_runtimeIdentity = identity.runtimeIdentity - ?? throw new ArgumentException("Animation targets require a live identity.", nameof(identity)); + ?? throw new ArgumentException("Animation targets require a live identity.", nameof(identity)); m_identity = identity; m_samplingOnly = false; } @@ -65,7 +65,8 @@ private AnimationTarget(bool samplingOnly) /// /// The live destination, or null for a missing, retired, or incompatible target. /// - public TObject? Resolve() where TObject : IdentityObject => m_identity.Resolve(); + public TObject? Resolve() + where TObject : IdentityObject => m_identity.Resolve(); /// /// Compares runtime destinations, including their identity domain. diff --git a/src/content/animation/Inno.Animation/AnimationTypes.cs b/src/content/animation/Inno.Animation/AnimationTypes.cs index 105710d8a..550b22510 100644 --- a/src/content/animation/Inno.Animation/AnimationTypes.cs +++ b/src/content/animation/Inno.Animation/AnimationTypes.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Serialization; namespace Inno.Animation; @@ -49,22 +48,18 @@ public enum AnimationValueKind /// A single scalar component. /// Scalar, - /// /// Two independent components. /// Vector2, - /// /// Three independent components. /// Vector3, - /// /// Four independent components. /// Vector4, - /// /// Four normalized rotation components. /// @@ -144,14 +139,17 @@ internal static AnimationValue Lerp( float amount ) { if (left.kind != right.kind) + { throw new InvalidOperationException("Animation values with different kinds cannot be interpolated."); + } float t = Math.Clamp(amount, 0f, 1f); var value = new AnimationValue( left.kind, left.x + ((right.x - left.x) * t), left.y + ((right.y - left.y) * t), left.z + ((right.z - left.z) * t), - left.w + ((right.w - left.w) * t)); + left.w + ((right.w - left.w) * t) + ); return left.kind == AnimationValueKind.Quaternion ? NormalizeQuaternion(value) : value; } @@ -164,7 +162,8 @@ float inverseWeight sum.x * inverseWeight, sum.y * inverseWeight, sum.z * inverseWeight, - sum.w * inverseWeight); + sum.w * inverseWeight + ); return sum.kind == AnimationValueKind.Quaternion ? NormalizeQuaternion(value) : value; } @@ -174,7 +173,9 @@ internal static AnimationValue AddWeighted( float weight ) { if (sum.kind != value.kind) + { throw new InvalidOperationException("Animation tracks targeting one binding must use one value kind."); + } sum.x += value.x * weight; sum.y += value.y * weight; sum.z += value.z * weight; @@ -185,18 +186,20 @@ float weight private static AnimationValue NormalizeQuaternion(AnimationValue value) { float length = MathF.Sqrt( - (value.x * value.x) + - (value.y * value.y) + - (value.z * value.z) + - (value.w * value.w)); + (value.x * value.x) + + (value.y * value.y) + + (value.z * value.z) + + (value.w * value.w) + ); return length <= float.Epsilon - ? new AnimationValue(AnimationValueKind.Quaternion, 0f, 0f, 0f, 1f) - : new AnimationValue( - AnimationValueKind.Quaternion, - value.x / length, - value.y / length, - value.z / length, - value.w / length); + ? new AnimationValue(AnimationValueKind.Quaternion, 0f, 0f, 0f, 1f) + : new AnimationValue( + AnimationValueKind.Quaternion, + value.x / length, + value.y / length, + value.z / length, + value.w / length + ); } } @@ -209,7 +212,6 @@ public enum AnimationInterpolation /// Holds the previous keyframe value until the next keyframe. /// Step, - /// /// Blends linearly between adjacent keyframes. /// @@ -225,7 +227,6 @@ public enum AnimationClock /// Uses scaled simulation time and stops while the session is paused. /// Scaled, - /// /// Uses unscaled session time and continues while simulation is paused. /// @@ -241,7 +242,6 @@ public enum AnimationPlaybackState /// The playback is advancing and producing samples. /// Playing, - /// /// The playback retains its position without advancing. /// @@ -256,7 +256,8 @@ public struct AnimationPlayOptions /// /// Gets the default playback options. /// - public static AnimationPlayOptions defaultValue => new() + public static AnimationPlayOptions defaultValue + => new() { speed = 1f, weight = 1f, @@ -339,9 +340,13 @@ public AnimationSample( AnimationValue value ) { if (!target.isValid) + { throw new ArgumentException("A valid animation destination is required.", nameof(target)); + } if (!binding.isValid) + { throw new ArgumentException("A valid animation binding is required.", nameof(binding)); + } this.binding = binding; this.target = target; this.value = value; diff --git a/src/content/animation/Inno.Animation/IAnimationService.cs b/src/content/animation/Inno.Animation/IAnimationService.cs index 60ed77c09..ccd9d7997 100644 --- a/src/content/animation/Inno.Animation/IAnimationService.cs +++ b/src/content/animation/Inno.Animation/IAnimationService.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Events; namespace Inno.Animation; @@ -142,7 +141,9 @@ public AnimationMarkerEvent( ReadOnlyMemory payload ) { if (!playback.isValid) + { throw new ArgumentException("A valid animation playback handle is required.", nameof(playback)); + } ArgumentException.ThrowIfNullOrWhiteSpace(eventId); this.playback = playback; this.eventId = eventId; diff --git a/src/content/animation/Inno.Animation/Properties/ScriptingApi.cs b/src/content/animation/Inno.Animation/Properties/ScriptingApi.cs index 825c1bf78..217f76fa6 100644 --- a/src/content/animation/Inno.Animation/Properties/ScriptingApi.cs +++ b/src/content/animation/Inno.Animation/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Animation; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Animation", - "Inno.Animation", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Animation", "Inno.Animation", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Animation), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AnimationBindingId), ScriptingApiScope.Runtime)] diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs index 677abc7f8..b77ba5163 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs @@ -4,18 +4,17 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -40,8 +39,7 @@ public bool TryGetArtifact( Guid persistentId, string outputName, out AssetArtifactInfo? artifact - ) - => GetLoader().TryGetArtifact(persistentId, outputName, out artifact); + ) => GetLoader().TryGetArtifact(persistentId, outputName, out artifact); /// /// Acquires one verified authoring artifact generation for an explicit lifetime. @@ -111,10 +109,7 @@ public AssetRuntimeContentInfo ExportRuntimeArtifacts(string destinationContentR using IDisposable operationScope = AcquireOperation(); WaitForIdle(); using SerializationGeneration serialization = m_serialization.CaptureGeneration(); - return GetLoader().ExportRuntimeArtifacts( - destinationContentRoot, - serialization, - CancellationToken.None); + return GetLoader().ExportRuntimeArtifacts(destinationContentRoot, serialization, CancellationToken.None); } /// @@ -152,7 +147,8 @@ public async Task ExportRuntimeArtifactsAsync( using SerializationGeneration serialization = m_serialization.CaptureGeneration(); return await Task.Run( () => loader.ExportRuntimeArtifacts(destinationContentRoot, serialization, cancellationToken), - CancellationToken.None).ConfigureAwait(false); + CancellationToken.None + ).ConfigureAwait(false); } private void CollectArtifactsIfDue( @@ -160,14 +156,15 @@ private void CollectArtifactsIfDue( bool force ) { if (m_options.mode == AssetPipelineMode.RuntimeArtifacts) + { return; + } long now = Environment.TickCount64; if (!force && now - m_lastArtifactCollectionTimestamp < 60_000) + { return; + } m_lastArtifactCollectionTimestamp = now; - _ = loader.CollectArtifacts( - m_cacheOptions.garbageCollectionGracePeriod, - m_cacheOptions.maximumSizeBytes); + _ = loader.CollectArtifacts(m_cacheOptions.garbageCollectionGracePeriod, m_cacheOptions.maximumSizeBytes); } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs index ac5ba6a11..bdfa855d6 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs @@ -4,18 +4,17 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -40,7 +39,9 @@ public void Update() { EnsureInitializationThread(); if (m_sampleImport is not null) + { return; + } using IDisposable operationScope = AcquireOperation(); PruneRetiredObservers(); AssetFileSystem fileSystem = GetFileSystem(); @@ -108,7 +109,9 @@ bool requiresFullRescan ) { AssetLoader? loader = m_loader; if (loader is null) + { return; + } Dictionary previousIds = CapturePreviousIds(loader, changes); try { @@ -118,7 +121,9 @@ bool requiresFullRescan GetFileSystem().Refresh(); } else + { loader.ApplySourceChanges(changes); + } m_diagnostics.ResolveSourceDatabase(); } catch (Exception exception) @@ -131,17 +136,17 @@ bool requiresFullRescan m_log.Write( LogLevel.Warn, "Asset source refresh failed and was recovered by a full rescan: {0}", - [exception]); + [exception] + ); } catch (Exception recoveryException) { m_log.Write( LogLevel.Error, "Asset source refresh and recovery rescan both failed. Refresh: {0} Recovery: {1}", - [exception, recoveryException]); - m_diagnostics.PublishSourceDatabaseFailure( - exception, - recoveryException); + [exception, recoveryException] + ); + m_diagnostics.PublishSourceDatabaseFailure(exception, recoveryException); } } AssetChange[] committed = CreateCommittedChanges(loader, changes, previousIds, requiresFullRescan); @@ -151,10 +156,14 @@ bool requiresFullRescan private void DrainPendingChanges(AssetFileSystem fileSystem) { if (!fileSystem.isWatching) + { return; + } IReadOnlyList pending = fileSystem.WaitForIdle(out bool requiresFullRescan); if (pending.Count > 0 || requiresFullRescan) + { ApplySourceChanges(pending, requiresFullRescan); + } } private AssetChangedEvent[] CreateDeletionEvents( @@ -163,9 +172,10 @@ string sourcePath ) { string prefix = sourcePath + "/"; return fileSystem.GetEntries() - .Where(entry => - string.Equals(entry.assetPath.ToString(), sourcePath, StringComparison.OrdinalIgnoreCase) || - entry.assetPath.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + .Where(entry => ( + string.Equals(entry.assetPath.ToString(), sourcePath, StringComparison.OrdinalIgnoreCase) + || entry.assetPath.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + )) .OrderBy(static entry => entry.assetPath.ToString().Length) .Select(static entry => new AssetChangedEvent(entry.assetPath.ToString(), WatcherChangeTypes.Deleted)) .DefaultIfEmpty(new AssetChangedEvent(sourcePath, WatcherChangeTypes.Deleted)) @@ -179,7 +189,9 @@ private void InvokeObservers( T value ) { if (handlers is null) + { return; + } foreach (Delegate handler in handlers.GetInvocationList()) { try @@ -196,7 +208,9 @@ T value private void InvokeObservers(Action? handlers) { if (handlers is null) + { return; + } foreach (Delegate handler in handlers.GetInvocationList()) { try @@ -214,8 +228,8 @@ private AssetFileSystem GetFileSystem() { EnsureAccess(); return isInitialized && m_fileSystem is not null - ? m_fileSystem - : throw new InvalidOperationException("AssetPipeline is not initialized."); + ? m_fileSystem + : throw new InvalidOperationException("AssetPipeline is not initialized."); } private Dictionary CapturePreviousIds( @@ -227,10 +241,12 @@ IReadOnlyList changes { AssetChangedEvent change = changes[i]; string path = string.IsNullOrWhiteSpace(change.oldRelativePath) - ? change.relativePath - : change.oldRelativePath; + ? change.relativePath + : change.oldRelativePath; if (loader.TryGetPersistentId(AssetPath.Parse(path), out Guid id)) + { result[path] = id; + } } return result; } @@ -242,7 +258,9 @@ private AssetChange[] CreateCommittedChanges( bool requiresFullRescan ) { if (requiresFullRescan && changes.Count == 0) + { return [new AssetChange(AssetChangeKind.StatusChanged, Guid.Empty, AssetPath.Project(string.Empty))]; + } var result = new List(changes.Count); for (int i = 0; i < changes.Count; i++) @@ -257,28 +275,28 @@ bool requiresFullRescan _ = previousIds.TryGetValue(previousPath, out id); } AssetChangeKind kind = moved - ? AssetChangeKind.Moved - : deleted - ? System.IO.File.Exists(Path.Combine(assetRoot, change.relativePath + ".imeta")) - ? AssetChangeKind.Missing - : AssetChangeKind.Removed - : change.changeType.HasFlag(WatcherChangeTypes.Created) - ? AssetChangeKind.Added - : AssetChangeKind.Modified; - result.Add(new AssetChange( - kind, - id, - AssetPath.Parse(change.relativePath), - string.IsNullOrWhiteSpace(change.oldRelativePath) + ? AssetChangeKind.Moved + : deleted + ? System.IO.File.Exists(Path.Combine(assetRoot, change.relativePath + ".imeta")) + ? AssetChangeKind.Missing + : AssetChangeKind.Removed + : change.changeType.HasFlag(WatcherChangeTypes.Created) + ? AssetChangeKind.Added + : AssetChangeKind.Modified; + result.Add( + new AssetChange( + kind, + id, + AssetPath.Parse(change.relativePath), + string.IsNullOrWhiteSpace(change.oldRelativePath) ? null - : AssetPath.Parse(change.oldRelativePath))); + : AssetPath.Parse(change.oldRelativePath) + ) + ); } return result.ToArray(); } private void PublishMutation(AssetChange change) - => InvokeObservers( - Changed, - new AssetChangeSet(Interlocked.Increment(ref m_revision), [change])); - + => InvokeObservers(Changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), [change])); } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs index a7e51f366..c74eab238 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs @@ -4,18 +4,17 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -119,12 +118,14 @@ public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) { ArgumentNullException.ThrowIfNull(catalog); if (!owner.isInitialized || owner.m_catalogParticipantRegistration is null) + { return new AssetCatalogTransaction(null, false, AssetImportHealthSnapshot.empty); + } owner.EnsureOwnerThread(); AssetImportHealthSnapshot existingFailures = owner.m_loader!.CaptureWritableImportHealth(); bool ownsCandidate = owner.m_sourceMountCandidate is null; AssetSourceMountTransaction candidate = owner.m_sourceMountCandidate - ?? owner.PrepareSourceMounts(owner.sourceMounts); + ?? owner.PrepareSourceMounts(owner.sourceMounts); return new AssetCatalogTransaction(candidate, ownsCandidate, existingFailures); } } @@ -157,13 +158,18 @@ public void Activate() candidate.candidateLoader.FindIntroducedImportFailures(existingFailures); if (failures.Count != 0) { - string details = string.Join("; ", failures.Select(static failure => - $"{failure.assetPath}: {failure.diagnostics}")); + string details = string.Join( + "; ", + failures.Select(static failure => $"{failure.assetPath}: {failure.diagnostics}") + ); throw new InvalidDataException( - "The candidate assembly catalog introduced or changed writable Asset import failures: " + details); + "The candidate assembly catalog introduced or changed writable Asset import failures: " + details + ); } if (ownsCandidate) + { candidate.Activate(); + } } m_activated = true; } @@ -175,9 +181,13 @@ public void Complete() { EnsureNotFinished(); if (!m_activated) + { throw new InvalidOperationException("Asset catalog transaction has not been activated."); + } if (ownsCandidate) + { candidate!.Complete(); + } m_finished = true; } @@ -187,17 +197,22 @@ public void Complete() public void Rollback() { if (m_finished) + { return; + } if (ownsCandidate) + { candidate!.Rollback(); + } m_finished = true; } private void EnsureNotFinished() { if (m_finished) + { throw new InvalidOperationException("Asset catalog transaction is already finished."); + } } } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs index 91f358c8a..25f2e1654 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs @@ -4,18 +4,17 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -33,11 +32,13 @@ sealed partial class AssetPipeline /// /// The canonical asset instance. /// - public TAsset Load(AssetPath path) where TAsset : AssetObject + public TAsset Load(AssetPath path) + where TAsset : AssetObject { AssetObject? asset = GetLoader().Load(path, typeof(TAsset)); return asset as TAsset ?? throw new InvalidOperationException( - $"Asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'."); + $"Asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'." + ); } /// @@ -71,10 +72,12 @@ Type assetType { throw new ArgumentException( $"Asset type '{assetType.FullName}' must derive from '{typeof(AssetObject).FullName}'.", - nameof(assetType)); + nameof(assetType) + ); } return GetLoader().Load(path, assetType) ?? throw new InvalidOperationException( - $"Asset '{path}' cannot be loaded as '{assetType.FullName}'."); + $"Asset '{path}' cannot be loaded as '{assetType.FullName}'." + ); } /// @@ -92,11 +95,13 @@ Type assetType /// /// Thrown when no compatible asset can be loaded. /// - public TAsset Load(Guid persistentId) where TAsset : AssetObject + public TAsset Load(Guid persistentId) + where TAsset : AssetObject { AssetObject? asset = GetLoader().Load(persistentId, typeof(TAsset)); return asset as TAsset ?? throw new InvalidOperationException( - $"Asset '{persistentId}' cannot be loaded as '{typeof(TAsset).FullName}'."); + $"Asset '{persistentId}' cannot be loaded as '{typeof(TAsset).FullName}'." + ); } /// @@ -167,15 +172,15 @@ out TAsset? asset public async ValueTask LoadAsync( AssetPath path, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { AssetLoader loader = GetLoader(); AssetObject? asset = await loader .LoadAsync(path, typeof(TAsset), cancellationToken) .ConfigureAwait(false); return asset as TAsset ?? throw new InvalidOperationException( - $"Asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'."); + $"Asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'." + ); } /// @@ -196,15 +201,15 @@ public async ValueTask LoadAsync( public async ValueTask LoadAsync( Guid persistentId, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { AssetLoader loader = GetLoader(); AssetObject? asset = await loader .LoadAsync(persistentId, typeof(TAsset), cancellationToken) .ConfigureAwait(false); return asset as TAsset ?? throw new InvalidOperationException( - $"Asset '{persistentId}' cannot be loaded as '{typeof(TAsset).FullName}'."); + $"Asset '{persistentId}' cannot be loaded as '{typeof(TAsset).FullName}'." + ); } /// @@ -225,11 +230,10 @@ public async ValueTask LoadAsync( public async ValueTask> AcquireAsync( AssetPath path, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { TAsset asset = await LoadAsync(path, cancellationToken).ConfigureAwait(false); - return CreateAssetLease(asset, static () => { }); + return CreateAssetLease(asset, static () => {}); } /// @@ -250,11 +254,10 @@ public async ValueTask> AcquireAsync( public async ValueTask> AcquireAsync( Guid persistentId, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { TAsset asset = await LoadAsync(persistentId, cancellationToken).ConfigureAwait(false); - return CreateAssetLease(asset, static () => { }); + return CreateAssetLease(asset, static () => {}); } AssetObject IAssetReferenceResolver.Resolve( @@ -266,18 +269,15 @@ string propertyPath ) { try { - return GetLoader().ResolveReference( - persistentId, - stableTypeId, - lastKnownPath, - expectedType); + return GetLoader().ResolveReference(persistentId, stableTypeId, lastKnownPath, expectedType); } catch (Exception exception) { throw new InvalidOperationException( - $"Asset reference '{persistentId:D}' at '{propertyPath}' cannot be resolved as " + - $"'{expectedType.FullName}'.", - exception); + $"Asset reference '{persistentId:D}' at '{propertyPath}' cannot be resolved as " + + $"'{expectedType.FullName}'.", + exception + ); } } @@ -304,8 +304,7 @@ string propertyPath public IReadOnlyList GetDependencies( AssetObject asset, bool recursive = false - ) - => GetLoader().GetDependencies(asset, recursive); + ) => GetLoader().GetDependencies(asset, recursive); /// /// Gets source import dependencies that invalidate an asset artifact. @@ -322,8 +321,7 @@ public IReadOnlyList GetDependencies( public IReadOnlyList GetImportDependencies( AssetObject asset, bool recursive = false - ) - => GetLoader().GetImportDependencies(asset, recursive); + ) => GetLoader().GetImportDependencies(asset, recursive); /// /// Gets an engine-known reference diagnostic snapshot. @@ -341,9 +339,8 @@ private AssetLoader GetLoader() EnsureAccess(); _ = m_types.current; AssetLoader loader = isInitialized && m_loader is not null - ? m_loader - : throw new InvalidOperationException("AssetPipeline is not initialized."); + ? m_loader + : throw new InvalidOperationException("AssetPipeline is not initialized."); return loader; } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs index 20fa7f55e..dc8f5d64c 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs @@ -4,18 +4,17 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -137,10 +136,9 @@ AssetObject asset { GetFileSystem().Refresh(); _ = loader.TryGetPersistentId(path, out Guid persistentId); - PublishMutation(new AssetChange( - existed ? AssetChangeKind.Modified : AssetChangeKind.Added, - persistentId, - path)); + PublishMutation( + new AssetChange(existed ? AssetChangeKind.Modified : AssetChangeKind.Added, persistentId, path) + ); } return saved; } @@ -169,7 +167,9 @@ AssetPath target string sourcePath = NormalizeMutationPath(source, nameof(source)); string targetPath = NormalizeMutationPath(target, nameof(target)); if (string.Equals(sourcePath, targetPath, StringComparison.Ordinal)) + { return; + } AssetFileSystem fileSystem = GetFileSystem(); AssetLoader loader = GetLoader(); @@ -177,18 +177,26 @@ AssetPath target { IReadOnlyList pending = fileSystem.WaitForIdle(out bool requiresFullRescan); if (pending.Count > 0 || requiresFullRescan) + { ApplySourceChanges(pending, requiresFullRescan); + } } string absoluteSource = Path.Combine(assetRoot, sourcePath); string absoluteTarget = Path.Combine(assetRoot, targetPath); bool isDirectory = Directory.Exists(absoluteSource); if (!isDirectory && !System.IO.File.Exists(absoluteSource)) + { throw new FileNotFoundException($"Asset source '{sourcePath}' does not exist.", absoluteSource); + } if (Directory.Exists(absoluteTarget) || System.IO.File.Exists(absoluteTarget)) + { throw new IOException($"Asset move target '{targetPath}' already exists."); + } if (System.IO.File.Exists(absoluteTarget + ".imeta")) + { throw new IOException($"Asset move target metadata '{targetPath}.imeta' already exists."); + } bool restartWatcher = fileSystem.isWatching; fileSystem.Stop(); @@ -214,7 +222,9 @@ AssetPath target finally { if (restartWatcher) + { fileSystem.Start(); + } } } @@ -239,7 +249,9 @@ public void Delete(AssetPath path) string absoluteSource = Path.Combine(assetRoot, sourcePath); bool isDirectory = Directory.Exists(absoluteSource); if (!isDirectory && !System.IO.File.Exists(absoluteSource)) + { throw new FileNotFoundException($"Asset source '{sourcePath}' does not exist.", absoluteSource); + } AssetChangedEvent[] changes = CreateDeletionEvents(fileSystem, sourcePath); Dictionary previousIds = CapturePreviousIds(loader, changes); @@ -247,7 +259,8 @@ public void Delete(AssetPath path) libraryRoot, "AssetDatabase", "Transactions", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); string stagedSource = Path.Combine(transactionRoot, "source"); string sourceMeta = absoluteSource + ".imeta"; string stagedMeta = Path.Combine(transactionRoot, "source.imeta"); @@ -259,7 +272,9 @@ public void Delete(AssetPath path) { MovePhysicalSource(absoluteSource, stagedSource, isDirectory); if (System.IO.File.Exists(sourceMeta)) + { System.IO.File.Move(sourceMeta, stagedMeta); + } loader.ApplySourceChanges(changes); fileSystem.Refresh(); committed = CreateCommittedChanges(loader, changes, previousIds, requiresFullRescan: false); @@ -276,7 +291,9 @@ public void Delete(AssetPath path) finally { if (restartWatcher) + { fileSystem.Start(); + } } DeleteTransactionDirectorySafely(transactionRoot); InvokeObservers(Changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), committed)); @@ -309,12 +326,17 @@ public void CreateDirectory(AssetPath path) if (!Directory.Exists(parentPath)) { throw new DirectoryNotFoundException( - $"Asset directory parent '{Path.GetDirectoryName(sourcePath)}' does not exist."); + $"Asset directory parent '{Path.GetDirectoryName(sourcePath)}' does not exist." + ); } if (Directory.Exists(absolutePath) || System.IO.File.Exists(absolutePath)) + { throw new IOException($"Asset directory target '{sourcePath}' already exists."); + } if (System.IO.File.Exists(absolutePath + ".imeta")) + { throw new IOException($"Asset directory target metadata '{sourcePath}.imeta' already exists."); + } bool restartWatcher = fileSystem.isWatching; fileSystem.Stop(); @@ -328,15 +350,20 @@ public void CreateDirectory(AssetPath path) loader, [change], new Dictionary(StringComparer.OrdinalIgnoreCase), - requiresFullRescan: false); + requiresFullRescan: false + ); InvokeObservers(Changed, new AssetChangeSet(Interlocked.Increment(ref m_revision), committed)); } catch { if (Directory.Exists(absolutePath)) + { Directory.Delete(absolutePath, recursive: true); + } if (System.IO.File.Exists(absolutePath + ".imeta")) + { System.IO.File.Delete(absolutePath + ".imeta"); + } loader.Rescan(); fileSystem.Refresh(); throw; @@ -344,7 +371,9 @@ public void CreateDirectory(AssetPath path) finally { if (restartWatcher) + { fileSystem.Start(); + } } } @@ -353,9 +382,13 @@ private string NormalizeMutationPath( string parameterName ) { if (!path.isValid || string.IsNullOrWhiteSpace(path.localPath)) + { throw new ArgumentException("Asset source path is required.", parameterName); + } if (path.source != AssetSourceId.project) + { throw new InvalidOperationException($"Asset source '{path.source}' is read-only."); + } return path.localPath; } @@ -365,9 +398,13 @@ private void MovePhysicalSource( bool isDirectory ) { if (isDirectory) + { Directory.Move(sourcePath, targetPath); + } else + { System.IO.File.Move(sourcePath, targetPath); + } } private void TryRollbackPhysicalMove( @@ -380,7 +417,9 @@ bool isDirectory bool targetExists = isDirectory ? Directory.Exists(targetPath) : System.IO.File.Exists(targetPath); bool sourceExists = isDirectory ? Directory.Exists(sourcePath) : System.IO.File.Exists(sourcePath); if (targetExists && !sourceExists) + { MovePhysicalSource(targetPath, sourcePath, isDirectory); + } } catch { @@ -395,7 +434,9 @@ string targetPath try { if (System.IO.File.Exists(targetPath) && !System.IO.File.Exists(sourcePath)) + { System.IO.File.Move(targetPath, sourcePath); + } } catch { @@ -420,7 +461,9 @@ private void RestoreStagedMetadata( string stagedMetaPath ) { if (!System.IO.File.Exists(stagedMetaPath)) + { return; + } Directory.CreateDirectory(Path.GetDirectoryName(metaPath)!); System.IO.File.Move(stagedMetaPath, metaPath); } @@ -430,7 +473,9 @@ private static void DeleteTransactionDirectorySafely(string transactionRoot) try { if (Directory.Exists(transactionRoot)) + { Directory.Delete(transactionRoot, recursive: true); + } } catch (IOException) { @@ -441,5 +486,4 @@ private static void DeleteTransactionDirectorySafely(string transactionRoot) // Read-only transaction debris must not roll back an already committed deletion. } } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs index 45339170e..80831f51e 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs @@ -4,18 +4,17 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -27,7 +26,9 @@ sealed partial class AssetPipeline public void Dispose() { lock (m_lifecycleLock) + { ShutdownLocked(); + } GC.SuppressFinalize(this); } @@ -50,11 +51,15 @@ private void RemoveRetiredObservers( Action> remove ) { if (handlers is null) + { return; + } foreach (Delegate observer in handlers.GetInvocationList()) { if (!IsRetiredCollectibleObserver(observer)) + { continue; + } remove((Action)observer); } } @@ -63,15 +68,15 @@ private bool IsRetiredCollectibleObserver(Delegate observer) { Type? declaringType = observer.Method.DeclaringType; Type? targetType = observer.Target?.GetType(); - return IsRetiredCollectibleType(declaringType) || - IsRetiredCollectibleType(targetType); + return IsRetiredCollectibleType(declaringType) + || IsRetiredCollectibleType(targetType); } private bool IsRetiredCollectibleType(Type? type) { - if (type is null || - !type.Assembly.IsCollectible) - { + if (type is null + || !type.Assembly.IsCollectible + ) { return false; } return !m_types.TryGetTypeRef(type, out _); @@ -92,11 +97,17 @@ private void ShutdownLocked() m_shutdown.Own(m_loader); } if (m_fileSystem is not null) + { m_shutdown.Own(m_fileSystem); + } if (m_catalogParticipantRegistration is not null) + { m_shutdown.Own(m_catalogParticipantRegistration); + } if (m_failedPreparation is not null) + { m_shutdown.Own(m_failedPreparation); + } } try { @@ -136,5 +147,4 @@ private void FinishShutdown() AssetReloaded = null; SourceMountsChanged = null; } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs index 5e4648b2e..b31700217 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs @@ -4,18 +4,17 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; -using Inno.Core.Execution; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -113,7 +112,8 @@ public sealed partial class AssetPipeline : AssetResidencyProvider, /// /// Complete stable properties and dependencies without writing or importing an asset. /// - public AssetPropertySnapshot CaptureProperties(TValue value) where TValue : class, ISerializable + public AssetPropertySnapshot CaptureProperties(TValue value) + where TValue : class, ISerializable { EnsureOwnerThread(); using IDisposable operationScope = AcquireOperation(); @@ -144,7 +144,9 @@ TValue target ArgumentNullException.ThrowIfNull(target); using IDisposable operationScope = AcquireOperation(); if (m_types.GetTypeRef(target.GetType()).stableId != stableTypeId) + { throw new InvalidOperationException("The asset property payload has an incompatible stable type identity."); + } m_serialization.Decode(propertyData, reader => { reader.RestoreProperties(target); @@ -212,9 +214,13 @@ AssetPipelineOptions options ArgumentNullException.ThrowIfNull(diagnostics); ArgumentNullException.ThrowIfNull(logs); if (string.IsNullOrWhiteSpace(options.assetRoot)) + { throw new ArgumentException("Asset root is required.", nameof(options)); + } if (string.IsNullOrWhiteSpace(options.libraryRoot)) + { throw new ArgumentException("Library root is required.", nameof(options)); + } m_types = types; m_generations = modules.generations; @@ -227,11 +233,13 @@ AssetPipelineOptions options lock (m_lifecycleLock) { AssetSourceMount[] mounts = options.sourceMounts?.ToArray() - ?? [new AssetSourceMount(AssetSourceId.project, options.assetRoot, isReadOnly: false)]; + ?? [new AssetSourceMount(AssetSourceId.project, options.assetRoot, isReadOnly: false)]; AssetSourceMount projectMount = mounts.SingleOrDefault(static mount => mount.id == AssetSourceId.project) - ?? throw new ArgumentException("A project asset source mount is required.", nameof(options)); + ?? throw new ArgumentException("A project asset source mount is required.", nameof(options)); if (projectMount.isReadOnly && options.mode != AssetPipelineMode.RuntimeArtifacts) + { throw new ArgumentException("The project asset source mount must be writable.", nameof(options)); + } assetRoot = projectMount.rootPath; libraryRoot = Path.GetFullPath(options.libraryRoot); DeleteCandidateCatalogRoots(libraryRoot); @@ -246,9 +254,12 @@ AssetPipelineOptions options mounts, libraryRoot, options.sourcePolicy, - runtimeArtifactsOnly: options.mode == AssetPipelineMode.RuntimeArtifacts); + runtimeArtifactsOnly: options.mode == AssetPipelineMode.RuntimeArtifacts + ); if (options.deferUnavailableExtensions) + { loader.DeferUnavailableExtensions(); + } AssetFileSystem fileSystem = new( mounts, autoStart: false, @@ -256,11 +267,13 @@ AssetPipelineOptions options options.sourcePolicy, requireWritableProject: options.mode == AssetPipelineMode.Authoring, identities, - persistentIdentityResolver: path => + persistentIdentityResolver: path => ( loader.TryGetPersistentId(path, out Guid persistentId) - ? persistentId - : null, - activateIdentities: true); + ? persistentId + : null + ), + activateIdentities: true + ); loader.AssetReloaded += OnAssetReloaded; m_loader = loader; m_fileSystem = fileSystem; @@ -276,9 +289,10 @@ AssetPipelineOptions options CollectArtifactsIfDue(loader, force: true); fileSystem.Refresh(); if (options.enableFileSystemWatcher && options.mode == AssetPipelineMode.Authoring) + { fileSystem.Start(); - m_catalogParticipantRegistration = modules.RegisterCatalogParticipant( - m_catalogParticipant); + } + m_catalogParticipantRegistration = modules.RegisterCatalogParticipant(m_catalogParticipant); } catch { @@ -298,7 +312,9 @@ public void WaitForIdle() AssetFileSystem fileSystem = GetFileSystem(); IReadOnlyList changes = fileSystem.WaitForIdle(out bool requiresFullRescan); if (changes.Count > 0 || requiresFullRescan) + { ApplySourceChanges(changes, requiresFullRescan); + } GetLoader().WaitForIdle(); CollectArtifactsIfDue(GetLoader(), force: true); } @@ -314,26 +330,35 @@ private void EnsureAccess() { m_generations.EnsureRetirementSafe(); if (m_generations.state == GenerationState.Faulted) + { m_generations.EnsureReady("access Asset Pipeline"); + } if (m_shutdown is not null || m_failedPreparation is not null) + { throw new InvalidOperationException("The Asset Pipeline is retiring and cannot accept operations."); + } } private void EnsureOwnerThread() { EnsureInitializationThread(); if (m_sampleImport is not null) + { throw new InvalidOperationException("Asset mutations are deferred until the pending sample import finishes."); + } } private void EnsureInitializationThread() { if (!isInitialized) + { throw new InvalidOperationException("AssetPipeline is not initialized."); + } if (Environment.CurrentManagedThreadId != m_ownerThreadId) { throw new InvalidOperationException( - "Asset database mutations must run on the thread that initialized AssetPipeline."); + "Asset database mutations must run on the thread that initialized AssetPipeline." + ); } } } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipelineMode.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipelineMode.cs index 22fbd6490..83b3ba93d 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipelineMode.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipelineMode.cs @@ -9,7 +9,6 @@ public enum AssetPipelineMode /// Reconciles writable source files and produces immutable artifacts. /// Authoring, - /// /// Loads a read-only deployed catalog and its content-addressed artifacts without source files. /// diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs index ec6f311b9..7dc04020c 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets.Pipeline; namespace Inno.Assets.Pipeline; @@ -75,9 +74,13 @@ public static AssetPipelineOptions Create( string libraryRoot ) { if (string.IsNullOrWhiteSpace(assetRoot)) + { throw new ArgumentException("Asset root is required.", nameof(assetRoot)); + } if (string.IsNullOrWhiteSpace(libraryRoot)) + { throw new ArgumentException("Library root is required.", nameof(libraryRoot)); + } return new AssetPipelineOptions { diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountRecovery.cs b/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountRecovery.cs index 09669ad80..d5aef9ae2 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountRecovery.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountRecovery.cs @@ -9,13 +9,12 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetSourceMountRecovery( AssetPipeline owner, AssetSourceMountTransaction transaction -) - : IReferenceRecoveryParticipant +) : IReferenceRecoveryParticipant { /// /// Keeps the previous loader and its canonical instances intact until provisional publication. /// - public void PrepareForActivation() { } + public void PrepareForActivation() {} /// /// Publishes the candidate identity domain before shared reference slots are resolved. @@ -34,13 +33,18 @@ public void Validate(IReadOnlyList changes) { ReferenceResolution result = change.resolution; if (result.state is ReferenceResolutionState.Invalid or ReferenceResolutionState.TypeMismatch) + { throw new InvalidDataException(result.diagnostic ?? "Asset recovery has an invalid identity."); - if (result.state == ReferenceResolutionState.Missing && - transaction.candidateLoader.TryGetInfo(result.descriptor.targetPersistentId, out AssetInfo? info) && - info!.status == AssetImportStatus.Imported && - !transaction.candidateLoader.IsSourceBackedTypeUnavailable( - result.descriptor.targetPersistentId)) - throw new InvalidDataException($"Imported asset '{info.assetPath}' could not recover its canonical state: {result.diagnostic}"); + } + if (result.state == ReferenceResolutionState.Missing + && transaction.candidateLoader.TryGetInfo(result.descriptor.targetPersistentId, out AssetInfo? info) + && info!.status == AssetImportStatus.Imported + && !transaction.candidateLoader.IsSourceBackedTypeUnavailable(result.descriptor.targetPersistentId) + ) { + throw new InvalidDataException( + $"Imported asset '{info.assetPath}' could not recover its canonical state: {result.diagnostic}" + ); + } } } @@ -61,5 +65,5 @@ public void Complete() /// /// Finishes compensation without decoding old objects through candidate serializers. /// - public void RestorePreviousState() { } + public void RestorePreviousState() {} } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs b/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs index f571efd7a..b737d7771 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs @@ -3,9 +3,9 @@ using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Scripting.Api; -using Inno.References; using Inno.Core.Execution; +using Inno.References; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -32,8 +32,10 @@ long generation this.catalogCandidate = catalogCandidate; this.candidateFileSystem = candidateFileSystem; m_recovery = new ReferenceRecoveryTransaction( - ReferenceCatalog.Create(generation, [candidateLoader]), previousStates, - [new AssetSourceMountRecovery(owner, this)]); + ReferenceCatalog.Create(generation, [candidateLoader]), + previousStates, + [new AssetSourceMountRecovery(owner, this)] + ); } internal AssetCatalogCandidate catalogCandidate { get; } @@ -102,12 +104,14 @@ public IReadOnlyList GetFileSystemEntries(bool includeDirectorie /// Thrown when no compatible candidate asset exists. /// [ScriptingApiIgnore] - public TAsset Load(AssetPath path) where TAsset : AssetObject + public TAsset Load(AssetPath path) + where TAsset : AssetObject { EnsureOpen(); AssetObject? asset = candidateLoader.Load(path, typeof(TAsset)); return asset as TAsset ?? throw new InvalidOperationException( - $"Candidate asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'."); + $"Candidate asset '{path}' cannot be loaded as '{typeof(TAsset).FullName}'." + ); } /// @@ -174,7 +178,9 @@ public void Activate() { EnsureOpen(); if (m_activationComplete) + { return; + } if (!m_prepared) { m_prepared = true; @@ -198,7 +204,9 @@ public void Complete() { EnsureOpen(); if (!m_activationComplete) + { throw new InvalidOperationException("A source-mount candidate must finish activation before completion."); + } try { m_recovery.Complete(); @@ -223,9 +231,13 @@ public void Complete() public void Rollback() { if (isFinished) + { return; + } if (m_terminalFailure is not null) + { throw m_terminalFailure; + } if (!m_prepared) { m_prepared = true; @@ -255,8 +267,12 @@ public void Dispose() private void EnsureOpen() { if (m_terminalFailure is not null) + { throw m_terminalFailure; + } if (isFinished) + { throw new ObjectDisposedException(nameof(AssetSourceMountTransaction)); + } } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Diagnostics/AssetPipelineDiagnosticPublisher.cs b/src/content/assets/Inno.Assets.Pipeline/Diagnostics/AssetPipelineDiagnosticPublisher.cs index 44ce3b1e0..e5ecf4420 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Diagnostics/AssetPipelineDiagnosticPublisher.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Diagnostics/AssetPipelineDiagnosticPublisher.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Diagnostics; namespace Inno.Assets.Pipeline; @@ -7,9 +6,11 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetPipelineDiagnosticPublisher { private const string C_SOURCE_DATABASE_GROUP = "Asset Source Database"; + private static readonly DiagnosticSource S_SOURCE_DATABASE = new( "inno.assets.pipeline/source-database", - C_SOURCE_DATABASE_GROUP); + C_SOURCE_DATABASE_GROUP + ); private readonly DiagnosticHub m_diagnostics; @@ -30,9 +31,11 @@ Exception recoveryException [ Diagnostic.Error( "ASSET-SOURCE", - $"Incremental refresh failed: {refreshException.Message} " + - $"Recovery rescan failed: {recoveryException.Message}") - ]); + $"Incremental refresh failed: {refreshException.Message} " + + $"Recovery rescan failed: {recoveryException.Message}" + ) + ] + ); } internal void ResolveSourceDatabase() => m_diagnostics.Clear(S_SOURCE_DATABASE); diff --git a/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs index 28b76541c..f0211b5cd 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs @@ -50,7 +50,8 @@ public AssetSourceSnapshot Read(AssetPath path) /// /// Native source bytes, with no canonical asset mutation. /// - public byte[] Encode(TAsset asset) where TAsset : AssetObject => NativeAssetSourceSerialization.Export(asset, m_serialization); + public byte[] Encode(TAsset asset) + where TAsset : AssetObject => NativeAssetSourceSerialization.Export(asset, m_serialization); /// /// Restores a detached native value using current-generation asset references. @@ -64,8 +65,9 @@ public AssetSourceSnapshot Read(AssetPath path) /// /// A detached value; referenced assets remain canonical read-only inputs. /// - public TAsset Decode(ReadOnlySpan bytes) where TAsset : AssetObject - => NativeAssetSourceSerialization.Import(bytes, m_serialization, out _); + public TAsset Decode(ReadOnlySpan bytes) + where TAsset : AssetObject + => NativeAssetSourceSerialization.Import(bytes, m_serialization, out _); /// /// Atomically saves bytes after checking the source fingerprint; import is a separate operation. @@ -90,15 +92,25 @@ public string Save( ArgumentNullException.ThrowIfNull(bytes); AssetSourceMount mount = Mount(path); if (mount.isReadOnly) + { throw new InvalidOperationException("Installed assets are read-only. Copy the asset to the project before editing."); + } string destination = mount.Resolve(path.localPath); bool exists = File.Exists(destination); if (expectedHash is null ? exists : !exists || Hash(File.ReadAllBytes(destination)) != expectedHash) - throw new IOException("The asset source changed externally. Draft and history are retained; reload or save a project copy explicitly."); + { + throw new IOException( + "The asset source changed externally. Draft and history are retained; reload or save a project copy explicitly." + ); + } if (expectedHash is null) + { AtomicFile.WriteAllBytes(destination, bytes, overwrite: false); + } else + { ReplaceExisting(destination, bytes, expectedHash); + } return Hash(bytes); } @@ -118,23 +130,29 @@ string expectedHash { string conflict = destination + ".external-conflict-" + token; File.Move(replaced, conflict, overwrite: false); - throw new IOException($"A concurrent external edit was preserved at '{conflict}'. Resolve both versions before saving again."); + throw new IOException( + $"A concurrent external edit was preserved at '{conflict}'. Resolve both versions before saving again." + ); } File.Delete(replaced); } finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } } private AssetSourceMount Mount(AssetPath path) { if (!path.isValid) + { throw new ArgumentException("A valid mounted asset path is required.", nameof(path)); + } return m_assets.sourceMounts.SingleOrDefault(mount => mount.id == path.source) - ?? throw new InvalidOperationException($"Asset source mount '{path.source}' is unavailable."); + ?? throw new InvalidOperationException($"Asset source mount '{path.source}' is unavailable."); } private static string Hash(ReadOnlySpan bytes) => Convert.ToHexString(SHA256.HashData(bytes)); @@ -146,6 +164,7 @@ private AssetSourceMount Mount(AssetPath path) public sealed class AssetSourceSnapshot { private readonly byte[] m_bytes; + internal AssetSourceSnapshot( byte[] bytes, string hash, @@ -155,14 +174,17 @@ bool readOnly contentHash = hash; isReadOnly = readOnly; } + /// /// Gets a copy of the captured native source bytes. /// public byte[] bytes => (byte[])m_bytes.Clone(); + /// /// Gets the source fingerprint required by a subsequent save. /// public string contentHash { get; } + /// /// Gets whether the installation source cannot be edited in place. /// diff --git a/src/content/assets/Inno.Assets.Pipeline/EditorAssets.cs b/src/content/assets/Inno.Assets.Pipeline/EditorAssets.cs index 6931e9e82..7abaa0db3 100644 --- a/src/content/assets/Inno.Assets.Pipeline/EditorAssets.cs +++ b/src/content/assets/Inno.Assets.Pipeline/EditorAssets.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; using Inno.Core.Serialization; @@ -23,8 +22,11 @@ public static byte[] EncodeNative(AssetObject asset) { ArgumentNullException.ThrowIfNull(asset); if (AssetExecutionContext.current is not AssetPipeline pipeline) + { throw new InvalidOperationException( - "Encoding an authoring asset requires an asset pipeline execution context."); + "Encoding an authoring asset requires an asset pipeline execution context." + ); + } return pipeline.CreateSourceStore().Encode(asset); } @@ -40,12 +42,16 @@ public static byte[] EncodeNative(AssetObject asset) /// /// A detached asset value that can be edited without publishing it. /// - public static TAsset DecodeNative(byte[] bytes) where TAsset : AssetObject + public static TAsset DecodeNative(byte[] bytes) + where TAsset : AssetObject { ArgumentNullException.ThrowIfNull(bytes); if (AssetExecutionContext.current is not AssetPipeline pipeline) + { throw new InvalidOperationException( - "Decoding an authoring asset requires an asset pipeline execution context."); + "Decoding an authoring asset requires an asset pipeline execution context." + ); + } return pipeline.CreateSourceStore().Decode(bytes); } @@ -61,12 +67,16 @@ public static TAsset DecodeNative(byte[] bytes) where TAsset : AssetObje /// /// Native properties, stable type identity and automatically collected dependencies. /// - public static AssetPropertySnapshot CaptureProperties(TValue value) where TValue : class, ISerializable + public static AssetPropertySnapshot CaptureProperties(TValue value) + where TValue : class, ISerializable { if (AssetExecutionContext.current is not AssetPipeline pipeline) + { throw new InvalidOperationException("Capturing authoring settings requires an asset pipeline execution context."); + } return pipeline.CaptureProperties(value); } + /// /// Creates or replaces a writable project asset source and imports the committed result. /// @@ -93,7 +103,8 @@ AssetObject asset if (AssetExecutionContext.current is not AssetPipeline pipeline) { throw new InvalidOperationException( - "Editor asset mutation requires an authoring asset pipeline execution context."); + "Editor asset mutation requires an authoring asset pipeline execution context." + ); } return pipeline.Save(path, asset); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs index abab51d83..af4276bb6 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Security.Cryptography; using System.Text; - using Inno.Assets; using Inno.Core.IO; using Inno.Core.Serialization; @@ -42,12 +41,16 @@ internal AssetArtifactKey Commit( SerializationGeneration? serialization = null ) { if (outputs.Count == 0) + { throw new InvalidOperationException("An artifact bundle requires at least one output."); + } AssetArtifactKey key = ComputeKey(inputFingerprint, outputs, authoringOutputs); string finalPath = GetBundlePath(key); if (Directory.Exists(finalPath)) + { return key; + } string stagingPath = Path.Combine(m_stagingRoot, Guid.NewGuid().ToString("N")); string outputRoot = Path.Combine(stagingPath, "outputs"); @@ -59,8 +62,13 @@ internal AssetArtifactKey Commit( .Select(( pair, index - ) => WriteOutput(outputRoot, pair.Key, pair.Value, index, - authoringOutputs?.Contains(pair.Key) == true ? AssetDeploymentScope.AuthoringOnly : AssetDeploymentScope.Runtime)) + ) => WriteOutput( + outputRoot, + pair.Key, + pair.Value, + index, + authoringOutputs?.Contains(pair.Key) == true ? AssetDeploymentScope.AuthoringOnly : AssetDeploymentScope.Runtime + )) .ToArray(); var manifest = new AssetArtifactManifest { @@ -69,7 +77,8 @@ internal AssetArtifactKey Commit( }; AtomicFile.WriteAllBytes( Path.Combine(stagingPath, "manifest"), - serialization is null ? m_serialization.Serialize(manifest) : serialization.Serialize(manifest)); + serialization is null ? m_serialization.Serialize(manifest) : serialization.Serialize(manifest) + ); Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!); try @@ -85,7 +94,9 @@ internal AssetArtifactKey Commit( catch { if (Directory.Exists(stagingPath)) + { Directory.Delete(stagingPath, recursive: true); + } throw; } } @@ -94,8 +105,7 @@ internal bool TryGet( AssetArtifactKey key, string outputName, out AssetArtifactInfo? artifact - ) - => TryGet(key, outputName, serialization: null, out artifact); + ) => TryGet(key, outputName, serialization: null, out artifact); internal bool TryGet( AssetArtifactKey key, @@ -105,17 +115,25 @@ out AssetArtifactInfo? artifact ) { artifact = null; if (key.isEmpty || string.IsNullOrWhiteSpace(outputName)) + { return false; + } AssetArtifactManifest? manifest = ReadManifest(key, serialization); AssetArtifactOutputData output = manifest?.outputs.FirstOrDefault(value => string.Equals(value.name, outputName, StringComparison.Ordinal)) ?? default; if (string.IsNullOrEmpty(output.fileName)) + { return false; + } string path = PathBoundary.Resolve(Path.Combine(GetBundlePath(key), "outputs"), output.fileName); if (!IOFile.Exists(path)) + { return false; + } if (new FileInfo(path).Length != output.length) + { throw new InvalidDataException($"Artifact '{key}/{output.name}' has an invalid output length."); + } artifact = new AssetArtifactInfo(key, output.name, output.contentHash, output.length); return true; } @@ -125,8 +143,8 @@ internal byte[] Read( string outputName ) { return TryGet(key, outputName, out AssetArtifactInfo? artifact) && artifact is not null - ? ReadOutputBytes(artifact, ResolveOutput(artifact)) - : []; + ? ReadOutputBytes(artifact, ResolveOutput(artifact)) + : []; } internal Func CreateReadFactory(AssetArtifactInfo artifact) @@ -138,8 +156,10 @@ internal Func CreateReadFactory(AssetArtifactInfo artifact) try { if (input.Length != artifact.length - || Convert.ToHexString(SHA256.HashData(input)) != artifact.contentHash) + || Convert.ToHexString(SHA256.HashData(input)) != artifact.contentHash + ) { throw new InvalidDataException($"Artifact '{artifact.key}/{artifact.outputName}' failed integrity validation."); + } input.Position = 0; return input; } @@ -154,10 +174,12 @@ internal Func CreateReadFactory(AssetArtifactInfo artifact) private string ResolveOutput(AssetArtifactInfo artifact) { AssetArtifactManifest manifest = ReadManifest(artifact.key, serialization: null) - ?? throw new InvalidDataException($"Artifact bundle '{artifact.key}' has no manifest."); + ?? throw new InvalidDataException($"Artifact bundle '{artifact.key}' has no manifest."); AssetArtifactOutputData output = manifest.outputs.Single(value => value.name == artifact.outputName); if (output.length != artifact.length || output.contentHash != artifact.contentHash) + { throw new InvalidDataException($"Artifact '{artifact.key}/{artifact.outputName}' changed its metadata."); + } return PathBoundary.Resolve(Path.Combine(GetBundlePath(artifact.key), "outputs"), output.fileName); } @@ -171,12 +193,14 @@ long maximumSizeBytes long totalSize = bundles.Sum(static bundle => bundle.size); int removed = 0; foreach (ArtifactDirectory bundle in bundles - .Where(bundle => !reachableKeys.Contains(bundle.key)) - .OrderBy(static bundle => bundle.lastWriteUtc)) - { + .Where(bundle => !reachableKeys.Contains(bundle.key)) + .OrderBy(static bundle => bundle.lastWriteUtc) + ) { bool exceededLimit = maximumSizeBytes > 0 && totalSize > maximumSizeBytes; if (!exceededLimit && bundle.lastWriteUtc > cutoff) + { continue; + } try { Directory.Delete(bundle.path, recursive: true); @@ -201,38 +225,47 @@ long maximumSizeBytes ) { string path = Path.Combine(GetBundlePath(key), "manifest"); if (!IOFile.Exists(path)) + { return null; + } try { byte[] bytes = IOFile.ReadAllBytes(path); AssetArtifactManifest manifest = serialization is null - ? m_serialization.Deserialize(bytes) - : serialization.Deserialize(bytes); + ? m_serialization.Deserialize(bytes) + : serialization.Deserialize(bytes); if (!string.Equals(manifest.key, key.value, StringComparison.Ordinal) || manifest.outputs.Length == 0 - || manifest.outputs.Any(static output => + || manifest.outputs.Any(static output => ( string.IsNullOrWhiteSpace(output.name) || string.IsNullOrWhiteSpace(output.fileName) || output.fileName is "." or ".." || output.fileName.IndexOfAny(['/', '\\', ':']) >= 0 || !IsContentHash(output.contentHash) - || output.length < 0 || !Enum.IsDefined(output.deploymentScope))) - { + || output.length < 0 || !Enum.IsDefined(output.deploymentScope) + )) + ) { throw new InvalidDataException($"Artifact bundle '{key}' has an invalid manifest contract."); } if (manifest.outputs.Select(static output => output.name).Distinct(StringComparer.Ordinal).Count() != manifest.outputs.Length - || manifest.outputs.Select(static output => output.fileName).Distinct(StringComparer.Ordinal).Count() != manifest.outputs.Length) + || manifest.outputs + .Select(static output => output.fileName) + .Distinct(StringComparer.Ordinal) + .Count() != manifest.outputs.Length + ) { throw new InvalidDataException($"Artifact bundle '{key}' contains duplicate output identities."); + } return manifest; } catch (Exception exception) when (exception is IOException - or InvalidDataException - or InvalidOperationException - or ArgumentException) + or InvalidDataException + or InvalidOperationException + or ArgumentException) { throw new InvalidDataException( $"Artifact bundle '{key}' has a corrupt current-format manifest.", - exception); + exception + ); } } @@ -242,21 +275,21 @@ private ArtifactDirectory[] EnumerateBundles() foreach (string firstLevel in Directory.EnumerateDirectories(m_root)) { if (string.Equals(Path.GetFileName(firstLevel), ".staging", StringComparison.Ordinal)) + { continue; + } foreach (string secondLevel in Directory.EnumerateDirectories(firstLevel)) { foreach (string bundlePath in Directory.EnumerateDirectories(secondLevel)) { string key = Path.GetFileName(bundlePath).ToUpperInvariant(); if (key.Length != C_SHA256_HEX_LENGTH) + { continue; + } long size = Directory.EnumerateFiles(bundlePath, "*", SearchOption.AllDirectories) .Sum(static path => new FileInfo(path).Length); - result.Add(new ArtifactDirectory( - key, - bundlePath, - Directory.GetLastWriteTimeUtc(bundlePath), - size)); + result.Add(new ArtifactDirectory(key, bundlePath, Directory.GetLastWriteTimeUtc(bundlePath), size)); } } } @@ -267,7 +300,9 @@ private string GetBundlePath(AssetArtifactKey key) { string value = key.value; if (key.isEmpty) + { throw new ArgumentException("Artifact keys must contain a SHA-256 value.", nameof(key)); + } return Path.Combine(m_root, value[..2].ToLowerInvariant(), value[2..4].ToLowerInvariant(), value); } @@ -300,8 +335,8 @@ private static AssetArtifactKey ComputeKey( Append(hash, "Inno.AssetArtifact"); Append(hash, inputFingerprint); foreach (KeyValuePair> output in outputs - .OrderBy(static pair => pair.Key, StringComparer.Ordinal)) - { + .OrderBy(static pair => pair.Key, StringComparer.Ordinal) + ) { Append(hash, output.Key); Append(hash, authoringOutputs?.Contains(output.Key) == true ? "authoring" : "runtime"); hash.AppendData(output.Value.Span); @@ -316,13 +351,15 @@ internal AssetArtifactKey ExportRuntime( System.Threading.CancellationToken cancellationToken ) { AssetArtifactManifest manifest = ReadManifest(key, serialization) - ?? throw new InvalidDataException($"Artifact bundle '{key}' has no manifest."); + ?? throw new InvalidDataException($"Artifact bundle '{key}' has no manifest."); var outputs = new Dictionary>(StringComparer.Ordinal); foreach (AssetArtifactOutputData output in manifest.outputs) { cancellationToken.ThrowIfCancellationRequested(); if (output.deploymentScope == AssetDeploymentScope.AuthoringOnly) + { continue; + } string path = PathBoundary.Resolve(Path.Combine(GetBundlePath(key), "outputs"), output.fileName); byte[] bytes = ReadOutputBytes(new AssetArtifactInfo(key, output.name, output.contentHash, output.length), path); outputs.Add(output.name, bytes); @@ -333,21 +370,28 @@ System.Threading.CancellationToken cancellationToken private static bool IsContentHash(string value) { if (string.IsNullOrEmpty(value) || value.Length != C_SHA256_HEX_LENGTH) + { return false; + } foreach (char digit in value) + { if (digit is not (>= '0' and <= '9') and not (>= 'A' and <= 'F')) + { return false; + } + } return true; } private static byte[] ReadOutputBytes( AssetArtifactInfo artifact, string path - ) - { + ) { byte[] bytes = IOFile.ReadAllBytes(path); if (bytes.LongLength != artifact.length || Convert.ToHexString(SHA256.HashData(bytes)) != artifact.contentHash) + { throw new InvalidDataException($"Artifact '{artifact.key}/{artifact.outputName}' failed integrity validation."); + } return bytes; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs index 0c5feb6f8..9d39ab9b7 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs @@ -12,6 +12,7 @@ public sealed class AssetArtifactWriter { private readonly Dictionary> m_outputs = new(StringComparer.Ordinal); + private readonly List m_diagnostics = []; private readonly HashSet m_authoringOutputs = new(StringComparer.Ordinal); @@ -41,13 +42,22 @@ public ValueTask WriteAsync( ) { cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(outputName)) + { throw new ArgumentException("An artifact output name is required.", nameof(outputName)); - if (!Enum.IsDefined(deploymentScope) || (deploymentScope == AssetDeploymentScope.AuthoringOnly && outputName is "runtime" or "asset-state")) + } + if (!Enum.IsDefined(deploymentScope) + || (deploymentScope == AssetDeploymentScope.AuthoringOnly && outputName is "runtime" or "asset-state") + ) { throw new ArgumentException("The output deployment scope is invalid.", nameof(deploymentScope)); + } if (!m_outputs.TryAdd(outputName, bytes.ToArray())) + { throw new InvalidOperationException($"Artifact output '{outputName}' was written more than once."); + } if (deploymentScope == AssetDeploymentScope.AuthoringOnly) + { m_authoringOutputs.Add(outputName); + } return ValueTask.CompletedTask; } @@ -60,7 +70,9 @@ public ValueTask WriteAsync( public void ReportDiagnostic(string message) { if (string.IsNullOrWhiteSpace(message)) + { throw new ArgumentException("A diagnostic message is required.", nameof(message)); + } m_diagnostics.Add(message); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs index 230b303c3..5109418aa 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs @@ -49,7 +49,9 @@ public void Commit() { EnsureOpen(); if (m_committed) + { throw new InvalidOperationException("The Asset catalog candidate has already been committed."); + } loader.PromoteCatalogTo(m_activeLibraryRoot); m_committed = true; } @@ -60,7 +62,9 @@ public void Commit() public void Dispose() { if (m_disposed) + { return; + } DeleteCandidateRoot(m_candidateLibraryRoot); m_disposed = true; GC.SuppressFinalize(this); @@ -74,10 +78,14 @@ private void EnsureOpen() private static void DeleteCandidateRoot(string candidateLibraryRoot) { if (!Directory.Exists(candidateLibraryRoot)) + { return; + } Directory.Delete(candidateLibraryRoot, recursive: true); string? parent = Directory.GetParent(candidateLibraryRoot)?.FullName; if (parent is not null && Directory.Exists(parent) && !Directory.EnumerateFileSystemEntries(parent).Any()) + { Directory.Delete(parent); + } } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetDeploymentScope.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetDeploymentScope.cs index cc834c6ff..b9cb72110 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetDeploymentScope.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetDeploymentScope.cs @@ -9,7 +9,6 @@ public enum AssetDeploymentScope /// The asset is deployed and must produce a named runtime artifact output. /// Runtime, - /// /// The asset exists only for authoring workflows and is omitted from deployed catalogs. /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs index 28abbde7b..ea31e7293 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs @@ -1,7 +1,6 @@ using System; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs index d37a9ed2d..94e0ba061 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Text; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -82,9 +81,10 @@ IAssetArtifactLookup artifacts types, serialization, references, - dependency => m_runtimeDependencies.Add(dependency)); + dependency => m_runtimeDependencies.Add(dependency) + ); m_dependencyResolver = dependencyResolver - ?? throw new ArgumentNullException(nameof(dependencyResolver)); + ?? throw new ArgumentNullException(nameof(dependencyResolver)); m_sourceReader = sourceReader ?? throw new ArgumentNullException(nameof(sourceReader)); m_artifacts = artifacts ?? throw new ArgumentNullException(nameof(artifacts)); } @@ -199,7 +199,9 @@ public string ReadUtf8Text() public ReadOnlyMemory ReadSourceBytes(AssetPath path) { if (!path.isValid) + { throw new ArgumentException("An import source dependency path is required.", nameof(path)); + } DependsOnSource(path); return m_sourceReader(path.ToString()); } @@ -230,7 +232,9 @@ private static string DecodeUtf8(ReadOnlySpan bytes) public void DependsOnAsset(AssetPath path) { if (!path.isValid) + { throw new ArgumentException("A runtime dependency path is required.", nameof(path)); + } m_runtimeDependencyPaths.Add(path.ToString()); } @@ -272,8 +276,9 @@ public TAsset ResolveDependency(AssetPath path) DependsOnAsset(path); AssetObject? resolved = m_dependencyResolver(normalized, typeof(TAsset)); return resolved as TAsset - ?? throw new InvalidOperationException( - $"Asset dependency '{normalized}' cannot be resolved as '{typeof(TAsset).FullName}'."); + ?? throw new InvalidOperationException( + $"Asset dependency '{normalized}' cannot be resolved as '{typeof(TAsset).FullName}'." + ); } /// @@ -285,11 +290,12 @@ public TAsset ResolveDependency(AssetPath path) public void DependsOnSource(AssetPath path) { if (!path.isValid) + { throw new ArgumentException("An import source dependency path is required.", nameof(path)); - m_importDependencies.Add(new AssetImportDependency( - AssetImportDependencyKind.Source, - path.ToString(), - string.Empty)); + } + m_importDependencies.Add( + new AssetImportDependency(AssetImportDependencyKind.Source, path.ToString(), string.Empty) + ); } /// @@ -301,11 +307,12 @@ public void DependsOnSource(AssetPath path) public void DependsOnArtifact(Guid persistentId) { if (persistentId == Guid.Empty) + { throw new ArgumentException("An artifact dependency identity is required.", nameof(persistentId)); - m_importDependencies.Add(new AssetImportDependency( - AssetImportDependencyKind.Artifact, - persistentId.ToString("D"), - string.Empty)); + } + m_importDependencies.Add( + new AssetImportDependency(AssetImportDependencyKind.Artifact, persistentId.ToString("D"), string.Empty) + ); } /// @@ -322,17 +329,17 @@ public void DependsOnCustomInput( string fingerprint ) { if (string.IsNullOrWhiteSpace(key)) + { throw new ArgumentException("A custom dependency key is required.", nameof(key)); - m_importDependencies.Add(new AssetImportDependency( - AssetImportDependencyKind.Custom, - key, - fingerprint ?? string.Empty)); + } + m_importDependencies.Add( + new AssetImportDependency(AssetImportDependencyKind.Custom, key, fingerprint ?? string.Empty) + ); } internal IReadOnlyList runtimeDependencyPaths => m_runtimeDependencyPaths; internal IReadOnlyList runtimeDependencies => m_runtimeDependencies; internal IReadOnlyList importDependencies => m_importDependencies; - } internal enum AssetImportDependencyKind diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportExtensionUnavailableException.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportExtensionUnavailableException.cs index 249935e1d..24e111603 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportExtensionUnavailableException.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportExtensionUnavailableException.cs @@ -22,8 +22,7 @@ public sealed class AssetImportExtensionUnavailableException : InvalidOperationE public AssetImportExtensionUnavailableException( string extensionKind, string extensionId - ) - : base($"Required authoring extension '{extensionKind}/{extensionId}' is unavailable. Source and last-good artifacts are retained.") + ) : base($"Required authoring extension '{extensionKind}/{extensionId}' is unavailable. Source and last-good artifacts are retained.") { ArgumentException.ThrowIfNullOrWhiteSpace(extensionKind); ArgumentException.ThrowIfNullOrWhiteSpace(extensionId); diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportHealthSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportHealthSnapshot.cs index 06c8db1ca..6d0739be9 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportHealthSnapshot.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportHealthSnapshot.cs @@ -13,8 +13,7 @@ namespace Inno.Assets.Pipeline; /// public sealed class AssetImportHealthSnapshot { - private static readonly AssetImportHealthSnapshot S_EMPTY = new( - new HashSet()); + private static readonly AssetImportHealthSnapshot S_EMPTY = new(new HashSet()); private readonly IReadOnlySet m_failures; diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs index 9c5322a49..7d93b3a1e 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Core.Serialization; @@ -42,9 +41,11 @@ public abstract class AssetImporter /// /// Gets the stable importer implementation identifier. /// - public string importerId => m_importerId - ?? throw new InvalidOperationException( - $"Asset importer '{GetType().FullName}' has not been bound to discovery metadata."); + public string importerId + => m_importerId + ?? throw new InvalidOperationException( + $"Asset importer '{GetType().FullName}' has not been bound to discovery metadata." + ); /// /// Gets whether imported assets are deployed or retained only for authoring workflows. @@ -74,6 +75,7 @@ internal abstract ValueTask ImportInternalAsync( AssetImportContext context, CancellationToken cancellationToken ); + internal abstract ValueTask?> ExportInternalAsync( AssetExportContext context, AssetObject asset, @@ -86,7 +88,8 @@ internal void BindImporterId(string id) if (m_importerId is not null && !string.Equals(m_importerId, id, StringComparison.Ordinal)) { throw new InvalidOperationException( - $"Asset importer '{GetType().FullName}' cannot be bound to more than one protocol ID."); + $"Asset importer '{GetType().FullName}' cannot be bound to more than one protocol ID." + ); } m_importerId = id; } @@ -98,7 +101,8 @@ internal void BindImporterId(string id) /// /// The concrete imported asset type. /// -public abstract class AssetImporter : AssetImporter where TAsset : AssetObject +public abstract class AssetImporter : AssetImporter + where TAsset : AssetObject { /// /// Gets the runtime asset type accepted by this importer implementation. @@ -145,8 +149,7 @@ CancellationToken cancellationToken AssetExportContext context, TAsset asset, CancellationToken cancellationToken - ) - => ValueTask.FromResult?>(null); + ) => ValueTask.FromResult?>(null); internal sealed override async ValueTask ImportInternalAsync( AssetImportContext context, @@ -163,7 +166,9 @@ CancellationToken cancellationToken CancellationToken cancellationToken ) { if (asset is TAsset typed) + { return ExportAsync(context, typed, cancellationToken); + } return ValueTask.FromResult?>(null); } } @@ -183,6 +188,6 @@ internal readonly struct AssetImportProduct( internal ReadOnlyMemory runtimePayload => outputs.TryGetValue("runtime", out ReadOnlyMemory bytes) - ? bytes - : ReadOnlyMemory.Empty; + ? bytes + : ReadOnlyMemory.Empty; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs index 0ac52b0fc..fd4d5b348 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -55,7 +54,8 @@ public AssetCatalogCandidate PrepareCatalogCandidate( libraryRoot, "AssetDatabase", "Candidates", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); AssetLoader? candidateLoader = null; try { @@ -69,7 +69,8 @@ public AssetCatalogCandidate PrepareCatalogCandidate( mounts, libraryRoot, candidateLibraryRoot, - sourcePolicy ?? m_sourcePolicy); + sourcePolicy ?? m_sourcePolicy + ); candidateLoader.m_identitiesActive = false; candidateLoader.m_deferUnavailableExtensions = true; candidateLoader.m_preserveInitialExtensionDiscovery = m_deferUnavailableExtensions; @@ -81,7 +82,9 @@ public AssetCatalogCandidate PrepareCatalogCandidate( { candidateLoader?.Dispose(); if (Directory.Exists(candidateLibraryRoot)) + { Directory.Delete(candidateLibraryRoot, recursive: true); + } throw; } }); @@ -96,7 +99,9 @@ internal void PromoteCatalogTo(string destinationLibraryRoot) m_sourceMetadataStage = null; } else + { m_catalog.PromoteTo(destinationLibraryRoot); + } }); /// @@ -141,9 +146,11 @@ public bool TryGetInfo( Guid persistentId, out AssetInfo? info ) { - AssetInfo? result = Execute(() => m_recordsById.TryGetValue(persistentId, out AssetRecord? record) + AssetInfo? result = Execute(() => ( + m_recordsById.TryGetValue(persistentId, out AssetRecord? record) ? CreateInfo(record) - : null); + : null + )); info = result; return result is not null; } @@ -224,41 +231,47 @@ private void LoadCatalogLocked() catch (Exception exception) { if (m_diagnostics.PublishCatalogFailure(exception)) + { m_log.Write(LogLevel.Error, "Asset catalog load failed: {0}", [exception]); + } throw; } for (int i = 0; i < catalogEntries.Length; i++) + { MergeCatalogMetaLocked(catalogEntries[i]); + } foreach (AssetSourceMount mount in m_mounts.Values) { foreach (string metaPath in Directory.GetFiles( - mount.rootPath, - "*" + C_META_POSTFIX, - SearchOption.AllDirectories)) - { + mount.rootPath, + "*" + C_META_POSTFIX, + SearchOption.AllDirectories + )) { string localMeta = Path.GetRelativePath(mount.rootPath, metaPath).Replace('\\', '/'); - string relative = new AssetPath( - mount.id, - localMeta[..^C_META_POSTFIX.Length]).ToString(); + string relative = new AssetPath(mount.id, localMeta[..^C_META_POSTFIX.Length]).ToString(); string sourcePath = GetSourcePath(relative); if (Directory.Exists(sourcePath)) + { continue; + } try { AssetSourceMeta sourceMeta = m_serialization.Deserialize( - ReadMetadata(metaPath) ?? throw new IOException("Source metadata is no longer available.")); + ReadMetadata(metaPath) ?? throw new IOException("Source metadata is no longer available.") + ); if (sourceMeta.persistentId != Guid.Empty) { AssetRecord? existing = FindRecordByIdWithoutLoading(sourceMeta.persistentId); - if (existing is not null && - !string.Equals(existing.relativePath, relative, StringComparison.OrdinalIgnoreCase) && - IOFile.Exists(GetSourcePath(existing.relativePath))) - { + if (existing is not null + && !string.Equals(existing.relativePath, relative, StringComparison.OrdinalIgnoreCase) + && IOFile.Exists(GetSourcePath(existing.relativePath)) + ) { if (mount.isReadOnly) { throw new InvalidDataException( - $"Read-only source '{relative}' duplicates persistent ID '{sourceMeta.persistentId}'."); + $"Read-only source '{relative}' duplicates persistent ID '{sourceMeta.persistentId}'." + ); } sourceMeta.persistentId = Guid.NewGuid(); WriteAtomic(metaPath, m_serialization.Serialize(sourceMeta)); @@ -283,23 +296,30 @@ private void LoadCatalogLocked() m_recordsByPath.TryGetValue(relativePath, out AssetRecord? record); string metaPath = GetMetaPath(relativePath); if (!TryReadSourceMeta(metaPath, out AssetSourceMeta sourceMeta)) + { return record; + } if (sourceMeta.persistentId == Guid.Empty) + { return record; + } if (record is not null && record.persistentId == sourceMeta.persistentId) + { return record; + } if (record is not null && record.persistentId != Guid.Empty) { // The source sidecar owns path identity. A catalog entry at the same path can be // historical after an interrupted save or catalog promotion and must not replace it. RetireRecordLocked( record, - $"Source '{relativePath}' now declares persistent id '{sourceMeta.persistentId}'."); + $"Source '{relativePath}' now declares persistent id '{sourceMeta.persistentId}'." + ); record = null; } - if (m_recordsById.TryGetValue(sourceMeta.persistentId, out AssetRecord? tombstone) && - tombstone.meta.isTombstone) - { + if (m_recordsById.TryGetValue(sourceMeta.persistentId, out AssetRecord? tombstone) + && tombstone.meta.isTombstone + ) { tombstone.relativePath = relativePath; tombstone.persistentId = sourceMeta.persistentId; tombstone.meta = new AssetMeta @@ -312,12 +332,12 @@ record = null; AddOrReplaceRecordLocked(tombstone); return tombstone; } - if (m_recordsById.TryGetValue(sourceMeta.persistentId, out AssetRecord? sameId) && - !string.Equals(sameId.relativePath, relativePath, StringComparison.OrdinalIgnoreCase)) - { - if (IOFile.Exists(GetSourcePath(sameId.relativePath)) || - Directory.Exists(GetSourcePath(sameId.relativePath))) - { + if (m_recordsById.TryGetValue(sourceMeta.persistentId, out AssetRecord? sameId) + && !string.Equals(sameId.relativePath, relativePath, StringComparison.OrdinalIgnoreCase) + ) { + if (IOFile.Exists(GetSourcePath(sameId.relativePath)) + || Directory.Exists(GetSourcePath(sameId.relativePath)) + ) { sourceMeta.persistentId = Guid.NewGuid(); WriteAtomic(metaPath, m_serialization.Serialize(sourceMeta)); } @@ -351,13 +371,14 @@ private void AddOrReplaceRecordLocked(AssetRecord record) m_recordsByPath[record.relativePath] = record; return; } - if (m_recordsById.TryGetValue(record.persistentId, out AssetRecord? sameId) && - !ReferenceEquals(sameId, record) && - !string.Equals(sameId.relativePath, record.relativePath, StringComparison.OrdinalIgnoreCase)) - { + if (m_recordsById.TryGetValue(record.persistentId, out AssetRecord? sameId) + && !ReferenceEquals(sameId, record) + && !string.Equals(sameId.relativePath, record.relativePath, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException( - $"Asset persistent id '{record.persistentId}' is used by both " + - $"'{sameId.relativePath}' and '{record.relativePath}'."); + $"Asset persistent id '{record.persistentId}' is used by both " + + $"'{sameId.relativePath}' and '{record.relativePath}'." + ); } m_recordsByPath[record.relativePath] = record; m_recordsById[record.persistentId] = record; @@ -386,19 +407,25 @@ private void RemoveRecordLocked( } m_importGraph.RemoveNode(record.relativePath); if (removeGeneratedFiles) + { DeleteIfExists(GetMetaPath(record.relativePath)); + } } private Type? ResolveRecordType(AssetRecord? record) { if (record is null) + { return null; + } if (record.asset is not null) + { return record.asset.GetType(); + } TypeRef typeRef = new(record.stableTypeId); return m_types.TryResolve(typeRef, out Type? type) && typeof(AssetObject).IsAssignableFrom(type) - ? type - : m_importers.FindById(record.meta.importerId)?.targetAssetType; + ? type + : m_importers.FindById(record.meta.importerId)?.targetAssetType; } private Type ResolveDependencyExpectedType(AssetDependency dependency) @@ -416,7 +443,9 @@ private bool TryNormalizeCatalogPath( out string normalized ) { if (!path.isValid) + { throw new ArgumentException("A valid isolated asset path is required.", nameof(path)); + } _ = GetMount(path); if (string.IsNullOrWhiteSpace(path.localPath)) { @@ -430,19 +459,22 @@ out string normalized private AssetInfo? CreateInfo(AssetRecord? record) { if (record is null) + { return null; + } return new AssetInfo( record.persistentId, AssetPath.Parse(record.relativePath), record.meta.isDirectory ? AssetSourceKind.Directory : AssetSourceKind.File, Enum.IsDefined(typeof(AssetImportStatus), record.meta.importStatus) - ? (AssetImportStatus)record.meta.importStatus - : AssetImportStatus.Failed, + ? (AssetImportStatus)record.meta.importStatus + : AssetImportStatus.Failed, record.meta.importerId, record.stableTypeId, new AssetArtifactKey(record.meta.artifactKey), new AssetArtifactKey(record.meta.lastSuccessfulArtifactKey), - record.meta.diagnostics); + record.meta.diagnostics + ); } private void CommitCatalogLocked() @@ -461,7 +493,9 @@ private void CommitCatalogLocked() catch (Exception exception) { if (m_diagnostics.PublishCatalogFailure(exception)) + { m_log.Write(LogLevel.Error, "Asset catalog commit failed: {0}", [exception]); + } throw; } m_diagnostics.SynchronizeImports(entries); @@ -470,16 +504,20 @@ private void CommitCatalogLocked() private void MergeCatalogMetaLocked(AssetMeta meta) { if (string.IsNullOrWhiteSpace(meta.relativePath)) + { return; + } if (meta.isTombstone) { if (meta.persistentId == Guid.Empty) + { return; + } AssetRecord tombstone = FindRecordByIdWithoutLoading(meta.persistentId) ?? new AssetRecord(); - if (!string.IsNullOrWhiteSpace(tombstone.relativePath) && - m_recordsByPath.TryGetValue(tombstone.relativePath, out AssetRecord? pathRecord) && - ReferenceEquals(pathRecord, tombstone)) - { + if (!string.IsNullOrWhiteSpace(tombstone.relativePath) + && m_recordsByPath.TryGetValue(tombstone.relativePath, out AssetRecord? pathRecord) + && ReferenceEquals(pathRecord, tombstone) + ) { m_recordsByPath.Remove(tombstone.relativePath); } tombstone.relativePath = meta.relativePath; @@ -491,14 +529,14 @@ private void MergeCatalogMetaLocked(AssetMeta meta) return; } AssetRecord record = meta.persistentId == Guid.Empty - ? m_recordsByPath.GetValueOrDefault(meta.relativePath) ?? new AssetRecord() - : FindRecordByIdWithoutLoading(meta.persistentId) ?? new AssetRecord(); - if (!string.IsNullOrWhiteSpace(record.relativePath) && - !string.Equals(record.relativePath, meta.relativePath, StringComparison.OrdinalIgnoreCase)) - { - if (m_recordsByPath.TryGetValue(record.relativePath, out AssetRecord? pathRecord) && - ReferenceEquals(pathRecord, record)) - { + ? m_recordsByPath.GetValueOrDefault(meta.relativePath) ?? new AssetRecord() + : FindRecordByIdWithoutLoading(meta.persistentId) ?? new AssetRecord(); + if (!string.IsNullOrWhiteSpace(record.relativePath) + && !string.Equals(record.relativePath, meta.relativePath, StringComparison.OrdinalIgnoreCase) + ) { + if (m_recordsByPath.TryGetValue(record.relativePath, out AssetRecord? pathRecord) + && ReferenceEquals(pathRecord, record) + ) { m_recordsByPath.Remove(record.relativePath); } } @@ -510,7 +548,9 @@ private void MergeCatalogMetaLocked(AssetMeta meta) record.importerGeneration = m_importers.GetGeneration(meta.importerId); AddOrReplaceRecordLocked(record); if (record.persistentId != Guid.Empty) + { UpdateGraphsLocked(record); + } } private AssetRecord? FindRecordByIdWithoutLoading(Guid persistentId) @@ -529,5 +569,4 @@ private sealed class AssetRecord internal long failedTypeGeneration; internal AssetSourceFileStamp settingsStamp; } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs index a1f51f645..f2db586a3 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -92,17 +91,20 @@ public AssetReferenceInfo GetReferenceInfo(AssetObject asset) private void AttachDependenciesLocked(AssetRecord record) { if (record.asset is null) + { return; + } var dependencies = new List(); foreach (AssetDependency dependency in GetDirectDependencies(record.meta)) { AssetRecord? dependencyRecord = FindDependencyRecordLocked(dependency); AssetObject dependencyAsset = dependencyRecord?.asset - ?? ResolveReferenceLocked( - dependency.persistentId, - dependency.type.stableId, - dependency.lastKnownPath, - ResolveDependencyExpectedType(dependency)); + ?? ResolveReferenceLocked( + dependency.persistentId, + dependency.type.stableId, + dependency.lastKnownPath, + ResolveDependencyExpectedType(dependency) + ); dependencies.Add(dependencyAsset); } m_dependencyRetention.Remove(record.asset); @@ -119,13 +121,12 @@ private AssetDependency[] ResolveDeclaredDependenciesLocked(AssetImportContext c if (m_recordsById.TryGetValue(dependency.persistentId, out AssetRecord? record)) { dependencyPath = record.relativePath; - result[persistentId] = new AssetDependency( - dependency.persistentId, - dependency.type, - dependencyPath); + result[persistentId] = new AssetDependency(dependency.persistentId, dependency.type, dependencyPath); } if (!string.IsNullOrWhiteSpace(dependencyPath)) + { ValidateSourceReferenceLocked(context.assetPath.ToString(), NormalizeRelativePath(dependencyPath)); + } } foreach (string path in context.runtimeDependencyPaths.Distinct(StringComparer.OrdinalIgnoreCase)) { @@ -135,27 +136,29 @@ private AssetDependency[] ResolveDeclaredDependenciesLocked(AssetImportContext c { Guid pendingId = m_pendingImportIds[normalized]; AssetImporter? pendingImporter = m_importers.FindByPath(normalized); - TypeRef typeRef = pendingImporter is not null && - m_types.TryGetTypeRef(pendingImporter.targetAssetType, out TypeRef pendingTypeRef) - ? pendingTypeRef - : default; + TypeRef typeRef = pendingImporter is not null + && m_types.TryGetTypeRef(pendingImporter.targetAssetType, out TypeRef pendingTypeRef) + ? pendingTypeRef + : default; result[pendingId] = new AssetDependency(pendingId, typeRef, normalized); continue; } AssetRecord? dependencyRecord = FindRecordLocked(normalized); - bool dependencyStale = dependencyRecord is null || - IsStale(dependencyRecord, out _); + bool dependencyStale = dependencyRecord is null + || IsStale(dependencyRecord, out _); if (dependencyStale && !ImportLocked(normalized)) { throw new InvalidOperationException( - $"Runtime dependency '{normalized}' referenced by '{context.assetPath}' cannot be imported."); + $"Runtime dependency '{normalized}' referenced by '{context.assetPath}' cannot be imported." + ); } dependencyRecord = FindRecordLocked(normalized) - ?? throw new InvalidOperationException($"Runtime dependency '{normalized}' has no metadata."); + ?? throw new InvalidOperationException($"Runtime dependency '{normalized}' has no metadata."); result[dependencyRecord.persistentId] = new AssetDependency( dependencyRecord.persistentId, new TypeRef(dependencyRecord.stableTypeId), - dependencyRecord.relativePath); + dependencyRecord.relativePath + ); } return result.Values.OrderBy(static value => value.persistentId).ToArray(); } @@ -173,7 +176,8 @@ private void ValidateImportDependenciesLocked(AssetMeta candidate) { m_importGraph.ReplaceDependencies(node, previous); throw new InvalidOperationException( - $"Asset import dependency cycle detected: {string.Join(" -> ", cycle)}."); + $"Asset import dependency cycle detected: {string.Join(" -> ", cycle)}." + ); } } @@ -182,17 +186,18 @@ private void ValidateImportDependencySnapshotsLocked(AssetMeta candidate) for (int i = 0; i < candidate.importDependencies.Length; i++) { AssetImportDependencyData dependency = candidate.importDependencies[i]; - string fingerprint = ComputeImportDependencyFingerprintLocked( - ref dependency, - out bool metadataChanged); + string fingerprint = ComputeImportDependencyFingerprintLocked(ref dependency, out bool metadataChanged); if (!string.Equals(dependency.fingerprint, fingerprint, StringComparison.Ordinal)) { throw new IOException( - $"Import dependency '{dependency.key}' changed while " + - $"'{candidate.relativePath}' was importing."); + $"Import dependency '{dependency.key}' changed while " + + $"'{candidate.relativePath}' was importing." + ); } if (metadataChanged) + { candidate.importDependencies[i] = dependency; + } } } @@ -201,13 +206,18 @@ private IReadOnlyList GetDependenciesLocked( bool recursive ) { if (!m_recordsById.TryGetValue(persistentId, out AssetRecord? record)) + { return Array.Empty(); + } IEnumerable ids = recursive - ? m_runtimeGraph.GetDependencies(persistentId, recursive: true) - : m_runtimeGraph.GetDependencies(persistentId); - return ids.Select(id => m_recordsById.TryGetValue(id, out AssetRecord? dependency) + ? m_runtimeGraph.GetDependencies(persistentId, recursive: true) + : m_runtimeGraph.GetDependencies(persistentId); + return ids + .Select(id => ( + m_recordsById.TryGetValue(id, out AssetRecord? dependency) ? new AssetDependency(id, new TypeRef(dependency.stableTypeId), dependency.relativePath) - : FindDescriptor(record.meta, id)) + : FindDescriptor(record.meta, id) + )) .Where(static descriptor => descriptor.persistentId != Guid.Empty) .ToArray(); } @@ -219,12 +229,17 @@ private AssetReferenceInfo GetReferenceInfoLocked(AssetObject asset) foreach (Guid dependentId in m_runtimeGraph.GetDependents(id)) { if (!m_recordsById.TryGetValue(dependentId, out AssetRecord? dependent)) + { continue; - locations.Add(new AssetReferenceLocation( - AssetReferenceKind.AssetDependency, - dependentId, - dependent.relativePath, - "runtimeDependencies")); + } + locations.Add( + new AssetReferenceLocation( + AssetReferenceKind.AssetDependency, + dependentId, + dependent.relativePath, + "runtimeDependencies" + ) + ); } m_recordsById.TryGetValue(id, out AssetRecord? record); return new AssetReferenceInfo( @@ -233,25 +248,30 @@ private AssetReferenceInfo GetReferenceInfoLocked(AssetObject asset) asset.contentVersion, record?.asset is not null, record?.lastSweepReachability, - locations.ToArray()); + locations.ToArray() + ); } private void UpdateGraphsLocked(AssetRecord record) { m_runtimeGraph.ReplaceDependencies( record.persistentId, - record.meta.runtimeDependencies.Select(static value => value.persistentId)); + record.meta.runtimeDependencies.Select(static value => value.persistentId) + ); m_importGraph.ReplaceDependencies( record.relativePath, record.meta.importDependencies .Where(static value => (AssetImportDependencyKind)value.kind == AssetImportDependencyKind.Source) - .Select(static value => value.key)); + .Select(static value => value.key) + ); } private AssetRecord? FindDependencyRecordLocked(AssetDependency dependency) { if (m_recordsById.TryGetValue(dependency.persistentId, out AssetRecord? record)) + { return record; + } return null; } @@ -260,7 +280,9 @@ private AssetImportDependencyData CreateImportDependencyDataLocked( AssetImportDependency dependency ) { if (dependency.kind == AssetImportDependencyKind.Source) + { ValidateSourceReferenceLocked(ownerPath, NormalizeRelativePath(dependency.key)); + } var result = new AssetImportDependencyData { kind = (int)dependency.kind, @@ -278,20 +300,28 @@ string dependencyPath AssetPath owner = AssetPath.Parse(ownerPath); AssetPath dependency = AssetPath.Parse(dependencyPath); if (owner.source == dependency.source || owner.source == AssetSourceId.project) + { return; + } if (dependency.source == AssetSourceId.project) { throw new InvalidOperationException( - $"Plugin source '{owner.source}' cannot reference project asset '{dependency.localPath}'."); + $"Plugin source '{owner.source}' cannot reference project asset '{dependency.localPath}'." + ); } if (!m_mounts.TryGetValue(owner.source, out AssetSourceMount? ownerMount)) + { throw new InvalidOperationException($"Asset source '{owner.source}' is not mounted."); + } if (!m_mounts.ContainsKey(dependency.source)) + { throw new InvalidOperationException($"Asset source dependency '{dependency.source}' is not mounted."); + } if (!ownerMount.dependencySourceIds.Contains(dependency.source)) { throw new InvalidOperationException( - $"Plugin source '{owner.source}' did not declare dependency '{dependency.source}'."); + $"Plugin source '{owner.source}' did not declare dependency '{dependency.source}'." + ); } } @@ -306,10 +336,14 @@ out bool metadataChanged { string sourcePath = GetSourcePath(NormalizeRelativePath(dependency.key)); if (!AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp sourceStamp)) + { return "MISSING"; + } bool stampChanged = !SourceStampMatches(dependency, sourceStamp); if (GetMount(dependency.key).isReadOnly && !stampChanged) + { return dependency.fingerprint; + } string hash = ReadStableSourceHash(sourcePath, out sourceStamp); if (stampChanged) { @@ -319,10 +353,10 @@ out bool metadataChanged return hash; } case AssetImportDependencyKind.Artifact: - return Guid.TryParse(dependency.key, out Guid id) && - m_recordsById.TryGetValue(id, out AssetRecord? record) - ? record.meta.artifactKey - : "MISSING"; + return Guid.TryParse(dependency.key, out Guid id) + && m_recordsById.TryGetValue(id, out AssetRecord? record) + ? record.meta.artifactKey + : "MISSING"; case AssetImportDependencyKind.Custom: return dependency.fingerprint; default: @@ -334,11 +368,11 @@ private static AssetDependency[] GetDirectDependencies(AssetMeta meta) => meta.runtimeDependencies.Select(static value => new AssetDependency( value.persistentId, new TypeRef(value.stableTypeId), - value.lastKnownPath)).ToArray(); + value.lastKnownPath + )).ToArray(); private sealed class AssetDependencySet(AssetObject[] assets) { internal AssetObject[] assets { get; } = assets; } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs index ede735863..fa32d6f19 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -33,19 +32,23 @@ sealed partial class AssetLoader /// An immutable health snapshot suitable for validating a later candidate generation. /// public AssetImportHealthSnapshot CaptureWritableImportHealth() - => new(Execute(() => m_recordsByPath.Values - .Where(record => - IsMounted(record.relativePath) - && !GetMount(record.relativePath).isReadOnly - && record.meta.importStatus is (int)AssetImportStatus.Failed - or (int)AssetImportStatus.Conflict) - .Select(static record => new AssetImportFailureFingerprint( - record.relativePath, - record.meta.importStatus, - record.meta.sourceHash, - record.meta.importerId, - string.Join("\n", record.meta.diagnostics))) - .ToHashSet())); + => new( + Execute(() => m_recordsByPath.Values + .Where(record => ( + IsMounted(record.relativePath) + && !GetMount(record.relativePath).isReadOnly + && record.meta.importStatus is (int)AssetImportStatus.Failed + or (int)AssetImportStatus.Conflict + )) + .Select(static record => new AssetImportFailureFingerprint( + record.relativePath, + record.meta.importStatus, + record.meta.sourceHash, + record.meta.importerId, + string.Join("\n", record.meta.diagnostics) + )) + .ToHashSet()) + ); /// /// Finds writable-source failures that are new or changed relative to an earlier health snapshot. @@ -60,22 +63,22 @@ public IReadOnlyList FindIntroducedImportFailures(AssetImpor { ArgumentNullException.ThrowIfNull(baseline); return Execute(() => m_recordsByPath.Values - .Where(record => + .Where(record => ( IsMounted(record.relativePath) && !GetMount(record.relativePath).isReadOnly && record.meta.importStatus is (int)AssetImportStatus.Failed - or (int)AssetImportStatus.Conflict) + or (int)AssetImportStatus.Conflict + )) .Select(static record => new AssetImportFailureFingerprint( record.relativePath, record.meta.importStatus, record.meta.sourceHash, record.meta.importerId, - string.Join("\n", record.meta.diagnostics))) + string.Join("\n", record.meta.diagnostics) + )) .Where(failure => !baseline.failures.Contains(failure)) .OrderBy(static failure => failure.relativePath, StringComparer.Ordinal) - .Select(static failure => new AssetImportFailure( - failure.relativePath, - failure.diagnostics)) + .Select(static failure => new AssetImportFailure(failure.relativePath, failure.diagnostics)) .ToArray()); } @@ -101,8 +104,8 @@ private void RecordImportFailureLocked( settingsHash = ComputeSha256Hex(ReadImportSettingsBytesLocked(relativePath, importer)); } catch (Exception secondaryFailure) when ( - secondaryFailure is not OutOfMemoryException && - RetirementPendingException.Find(secondaryFailure) is null) + secondaryFailure is not OutOfMemoryException + && RetirementPendingException.Find(secondaryFailure) is null) { settingsHash = string.Empty; settingsFailure = $"{secondaryFailure.GetType().Name}: {secondaryFailure.Message}"; @@ -114,16 +117,21 @@ secondaryFailure is not OutOfMemoryException && .ToArray() ?? []; string diagnostic = $"{exception.GetType().Name}: {exception.Message}"; if (settingsFailure is not null) + { diagnostic += $" Import settings could not be inspected: {settingsFailure}"; + } bool repeatedFailure = record.meta.importStatus == (int)AssetImportStatus.Failed - && string.Equals(record.meta.sourceHash, sourceHash, StringComparison.Ordinal) - && string.Equals(record.meta.importerSettingsHash, settingsHash, StringComparison.Ordinal) - && record.importerGeneration == m_importers.GetGeneration(importer.importerId) - && string.Equals(record.meta.importerImplementationFingerprint, - GetImporterImplementationFingerprint(importer), StringComparison.Ordinal) - && record.meta.diagnostics.Length == 1 - && string.Equals(record.meta.diagnostics[0], diagnostic, StringComparison.Ordinal) - && record.meta.importDependencies.SequenceEqual(dependencies); + && string.Equals(record.meta.sourceHash, sourceHash, StringComparison.Ordinal) + && string.Equals(record.meta.importerSettingsHash, settingsHash, StringComparison.Ordinal) + && record.importerGeneration == m_importers.GetGeneration(importer.importerId) + && string.Equals( + record.meta.importerImplementationFingerprint, + GetImporterImplementationFingerprint(importer), + StringComparison.Ordinal + ) + && record.meta.diagnostics.Length == 1 + && string.Equals(record.meta.diagnostics[0], diagnostic, StringComparison.Ordinal) + && record.meta.importDependencies.SequenceEqual(dependencies); record.relativePath = relativePath; record.persistentId = persistentId; record.meta.relativePath = relativePath; @@ -136,9 +144,9 @@ secondaryFailure is not OutOfMemoryException && record.importerGeneration = m_importers.GetGeneration(importer.importerId); ApplySourceStamp(record.meta, sourceStamp); record.meta.deploymentScope = (int)importer.deploymentScope; - if (record.meta.stableAssetTypeId == Guid.Empty && - m_types.TryGetTypeRef(importer.targetAssetType, out TypeRef importerTypeRef)) - { + if (record.meta.stableAssetTypeId == Guid.Empty + && m_types.TryGetTypeRef(importer.targetAssetType, out TypeRef importerTypeRef) + ) { record.meta.stableAssetTypeId = importerTypeRef.stableId; record.stableTypeId = importerTypeRef.stableId; } @@ -148,14 +156,16 @@ secondaryFailure is not OutOfMemoryException && record.meta.importStatus = (int)(pending ? AssetImportStatus.Pending : AssetImportStatus.Failed); record.failedTypeGeneration = m_types.current.version; record.meta.diagnostics = [pending - ? $"Waiting for authoring extension publication (or recovery after compilation failure). {exception.Message}" + - (settingsFailure is null ? string.Empty : $" Import settings could not be inspected: {settingsFailure}") + ? $"Waiting for authoring extension publication (or recovery after compilation failure). {exception.Message}" + + (settingsFailure is null ? string.Empty : $" Import settings could not be inspected: {settingsFailure}") : diagnostic]; AddOrReplaceRecordLocked(record); // Failure belongs to the writable catalog, not the immutable source being rejected. - if (!GetMount(relativePath).isReadOnly && - (ReadMetadata(GetMetaPath(relativePath)) is null || TryReadSourceMeta(GetMetaPath(relativePath), out _))) + if (!GetMount(relativePath).isReadOnly + && (ReadMetadata(GetMetaPath(relativePath)) is null || TryReadSourceMeta(GetMetaPath(relativePath), out _)) + ) { WriteSourceMeta(record.meta); + } CommitCatalogLocked(); if (extensionUnavailable) { @@ -165,13 +175,14 @@ secondaryFailure is not OutOfMemoryException && unavailable!.extensionKind, unavailable.extensionId); } else + { m_unavailableImports.Remove(relativePath); + } if (pending || repeatedFailure) + { return; - m_log.Write( - LogLevel.Error, - "Asset import for '{0}' failed: {1}", - [relativePath, exception]); + } + m_log.Write(LogLevel.Error, "Asset import for '{0}' failed: {1}", [relativePath, exception]); } private AssetImportDependencyData? TryCaptureFailedImportDependency( @@ -202,10 +213,10 @@ private void TrackUnsupportedSourceLocked(string relativePath) // cataloged source verbatim so a scan cannot erase its persistent identity, stable type, // dependency graph, or immutable artifact closure. A source that has never been imported // still follows the Unsupported path below. - if (record.persistentId != Guid.Empty && - !record.meta.isTombstone && - !string.IsNullOrWhiteSpace(record.meta.importerId)) - { + if (record.persistentId != Guid.Empty + && !record.meta.isTombstone + && !string.IsNullOrWhiteSpace(record.meta.importerId) + ) { record.relativePath = relativePath; record.meta.relativePath = relativePath; AddOrReplaceRecordLocked(record); @@ -213,7 +224,9 @@ private void TrackUnsupportedSourceLocked(string relativePath) return; } if (record.persistentId != Guid.Empty) + { m_recordsById.Remove(record.persistentId); + } record.relativePath = relativePath; record.persistentId = Guid.Empty; record.stableTypeId = Guid.Empty; @@ -233,15 +246,16 @@ int matchCount ) { AssetRecord? record = FindRecordLocked(relativePath); if (record is null) + { return; + } string diagnostic = - $"Warning: source '{relativePath}' matched {matchCount} removed assets; " + - "a new persistent identity was assigned instead of guessing a rename."; + $"Warning: source '{relativePath}' matched {matchCount} removed assets; " + + "a new persistent identity was assigned instead of guessing a rename."; record.meta.diagnostics = record.meta.diagnostics .Append(diagnostic) .Distinct(StringComparer.Ordinal) .ToArray(); CommitCatalogLocked(); } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs index 50f8f1946..c1b5de3a9 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs @@ -1,7 +1,6 @@ using System; using System.IO; using System.Linq; - using Inno.Assets; using Inno.Core.Execution; using Inno.Core.Serialization; @@ -37,7 +36,8 @@ public AssetImportSettingsSnapshot GetImportSettings(AssetPath path) byte[] settings = ReadImportSettingsBytes(importer, metadata); return new AssetImportSettingsSnapshot( RestoreImportSettingsLocked(importer, settings, null, normalized), - ComputeSha256Hex(metadata ?? [])); + ComputeSha256Hex(metadata ?? []) + ); }); /// @@ -69,82 +69,98 @@ public bool SaveImportSettings( AssetPath path, ISerializable? settings, string expectedFingerprint - ) - => Execute(() => + ) => Execute(() => + { + ArgumentException.ThrowIfNullOrWhiteSpace(expectedFingerprint); + string normalized = NormalizeAssetPath(path); + if (m_sourceMetadataStage is not null || GetMount(normalized).isReadOnly) { - ArgumentException.ThrowIfNullOrWhiteSpace(expectedFingerprint); - string normalized = NormalizeAssetPath(path); - if (m_sourceMetadataStage is not null || GetMount(normalized).isReadOnly) - throw new InvalidOperationException("Import settings can only be edited in the active writable source mount."); - AssetImporter importer = RequireSettingsImporterLocked(normalized); - ISerializable? defaults = importer.CreateImportSettings(); - if (settings is not null && (defaults is null || settings.GetType() != defaults.GetType())) - throw new ArgumentException($"Settings do not match importer '{importer.importerId}'.", nameof(settings)); - byte[] encoded = settings is null ? [] : CaptureImportSettingsLocked(settings, normalized, null); - string metaPath = GetMetaPath(normalized); - byte[]? metadata = ReadMetadata(metaPath); - if (!string.Equals(expectedFingerprint, ComputeSha256Hex(metadata ?? []), StringComparison.Ordinal)) - throw new IOException($"Import settings for '{normalized}' changed externally. Reload before saving."); - AssetSourceMeta source = metadata is null - ? new AssetSourceMeta - { - persistentId = FindRecordLocked(normalized)?.persistentId ?? Guid.NewGuid(), - importerId = importer.importerId - } - : m_serialization.Deserialize(metadata); - if (source.persistentId == Guid.Empty || - !string.Equals(source.importerId, importer.importerId, StringComparison.Ordinal)) - throw new InvalidDataException($"Source metadata for '{normalized}' does not match its importer."); - source.importerSettingsBytes = encoded; - WriteAtomic(metaPath, m_serialization.Serialize(source)); + throw new InvalidOperationException("Import settings can only be edited in the active writable source mount."); + } + AssetImporter importer = RequireSettingsImporterLocked(normalized); + ISerializable? defaults = importer.CreateImportSettings(); + if (settings is not null && (defaults is null || settings.GetType() != defaults.GetType())) + { + throw new ArgumentException($"Settings do not match importer '{importer.importerId}'.", nameof(settings)); + } + byte[] encoded = settings is null ? [] : CaptureImportSettingsLocked(settings, normalized, null); + string metaPath = GetMetaPath(normalized); + byte[]? metadata = ReadMetadata(metaPath); + if (!string.Equals(expectedFingerprint, ComputeSha256Hex(metadata ?? []), StringComparison.Ordinal)) + { + throw new IOException($"Import settings for '{normalized}' changed externally. Reload before saving."); + } + AssetSourceMeta source = metadata is null + ? new AssetSourceMeta + { + persistentId = FindRecordLocked(normalized)?.persistentId ?? Guid.NewGuid(), + importerId = importer.importerId + } + : m_serialization.Deserialize(metadata); + if (source.persistentId == Guid.Empty + || !string.Equals(source.importerId, importer.importerId, StringComparison.Ordinal) + ) { + throw new InvalidDataException($"Source metadata for '{normalized}' does not match its importer."); + } + source.importerSettingsBytes = encoded; + WriteAtomic(metaPath, m_serialization.Serialize(source)); + try + { + return ImportLocked(normalized); + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is null) + { + // A reported failed import is a saved authoring state. An exceptional transaction is not: + // restore the exact sidecar and refresh its old publication before the history caller retries. try { - return ImportLocked(normalized); - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is null) - { - // A reported failed import is a saved authoring state. An exceptional transaction is not: - // restore the exact sidecar and refresh its old publication before the history caller retries. - try + if (metadata is null) { - if (metadata is null) - System.IO.File.Delete(metaPath); - else - WriteAtomic(metaPath, metadata); - _ = ImportLocked(normalized); + System.IO.File.Delete(metaPath); } - catch (Exception rollback) + else { - throw new AggregateException("Import settings rollback failed.", failure, rollback); + WriteAtomic(metaPath, metadata); } - throw; + _ = ImportLocked(normalized); } - }); + catch (Exception rollback) + { + throw new AggregateException("Import settings rollback failed.", failure, rollback); + } + throw; + } + }); private AssetImporter RequireSettingsImporterLocked(string path) { if (!System.IO.File.Exists(GetSourcePath(path))) + { throw new FileNotFoundException($"Import settings source '{path}' does not exist."); + } return m_importers.FindByPath(path) - ?? throw new NotSupportedException($"No importer is registered for '{path}'."); + ?? throw new NotSupportedException($"No importer is registered for '{path}'."); } private byte[] ReadImportSettingsBytesLocked( string path, AssetImporter importer - ) - => ReadImportSettingsBytes(importer, ReadMetadata(GetMetaPath(path))); + ) => ReadImportSettingsBytes(importer, ReadMetadata(GetMetaPath(path))); private byte[] ReadImportSettingsBytes( AssetImporter importer, byte[]? metadata ) { if (metadata is null) + { return []; + } AssetSourceMeta source = m_serialization.Deserialize(metadata); - if (source.importerSettingsBytes.Length > 0 && - !string.Equals(source.importerId, importer.importerId, StringComparison.Ordinal)) + if (source.importerSettingsBytes.Length > 0 + && !string.Equals(source.importerId, importer.importerId, StringComparison.Ordinal) + ) { throw new InvalidDataException($"Stored import settings belong to '{source.importerId}', not '{importer.importerId}'."); + } return source.importerSettingsBytes; } @@ -159,7 +175,9 @@ private byte[] ReadImportSettingsBytes( if (value is null) { if (bytes.Length != 0) + { throw new InvalidDataException($"Importer '{importer.importerId}' no longer declares the persisted settings type."); + } return null; } Guid typeId = m_types.GetTypeRef(value.GetType()).stableId; @@ -167,7 +185,9 @@ private byte[] ReadImportSettingsBytes( { SerializedImportSettings saved = m_serialization.Deserialize(bytes); if (saved.stableTypeId != typeId) + { throw new InvalidDataException($"Import settings type '{saved.stableTypeId}' does not match '{typeId}'."); + } DeclareSettingsDependenciesLocked(saved.dependencies, ownerPath, null); m_serialization.Decode(saved.properties, reader => { @@ -186,8 +206,10 @@ private byte[] CaptureImportSettingsLocked( AssetImportContext? context ) { var dependencies = new AssetDependencyCollection(); - byte[] properties = m_serialization.Encode(writer => writer.WriteProperties(settings), - AssetSerializationContext.Create(this, dependencies)); + byte[] properties = m_serialization.Encode( + writer => writer.WriteProperties(settings), + AssetSerializationContext.Create(this, dependencies) + ); AssetDependency[] descriptors = dependencies.dependencies.ToArray(); DeclareSettingsDependenciesLocked(descriptors, ownerPath, context); return m_serialization.Serialize(new SerializedImportSettings @@ -223,21 +245,25 @@ AssetImporter importer string path = GetMetaPath(record.relativePath); bool exists = AssetSourceFileStamp.TryCapture(path, out AssetSourceFileStamp stamp); if (m_sourceMetadataStage is null && exists && record.settingsStamp.Equals(stamp)) + { return false; + } string hash; try { hash = ComputeSha256Hex(ReadImportSettingsBytesLocked(record.relativePath, importer)); } catch (Exception exception) when ( - exception is IOException or ArgumentException or InvalidOperationException or FormatException && - RetirementPendingException.Find(exception) is null) + exception is IOException or ArgumentException or InvalidOperationException or FormatException + && RetirementPendingException.Find(exception) is null) { // Reimport owns the diagnostic and last-good policy; a read check never repairs source bytes. return true; } if (!string.Equals(hash, record.meta.importerSettingsHash, StringComparison.Ordinal)) + { return true; + } record.settingsStamp = stamp; return false; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs index f25bec383..02facb3e7 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -61,22 +60,25 @@ public ValueTask BuildAsync( ArgumentNullException.ThrowIfNull(inputs); Guid targetId = definition.identity.persistentId; string displayName = string.IsNullOrWhiteSpace(definition.assetPath.ToString()) - ? definition.GetType().Name - : definition.assetPath.ToString(); + ? definition.GetType().Name + : definition.assetPath.ToString(); AssetArtifactKey key = Execute(() => { try { AssetBuildProcessor processor = m_buildProcessors.Find(definition.GetType()) - ?? throw new InvalidOperationException( - $"No asset build processor accepts '{definition.GetType().FullName}'."); + ?? throw new InvalidOperationException( + $"No asset build processor accepts '{definition.GetType().FullName}'." + ); var output = new AssetArtifactWriter(); processor.BuildInternalAsync(definition, inputs, output, cancellationToken) .AsTask() .GetAwaiter() .GetResult(); if (output.outputs.Count == 0) + { throw new InvalidOperationException("An asset build processor produced no outputs."); + } string fingerprint = CreateBuildFingerprint(processor, definition, inputs); AssetArtifactKey result = m_artifacts.Commit(fingerprint, output.outputs, output.authoringOutputs); m_diagnostics.PublishBuild(targetId, displayName, output.diagnostics); @@ -85,10 +87,7 @@ public ValueTask BuildAsync( catch (Exception exception) { m_diagnostics.PublishBuildFailure(targetId, displayName, exception); - m_log.Write( - LogLevel.Error, - "Asset build for '{0}' failed: {1}", - [displayName, exception]); + m_log.Write(LogLevel.Error, "Asset build for '{0}' failed: {1}", [displayName, exception]); throw; } }); @@ -100,35 +99,46 @@ private bool ImportLocked( bool force = false ) { if (m_activeImports.Contains(relativePath)) + { return true; + } if (!force && IsExtensionImportUnchanged(relativePath)) + { return false; + } if (IsSourceIgnored(relativePath, isDirectory: false)) + { return false; + } string sourcePath = GetSourcePath(relativePath); if (!IOFile.Exists(sourcePath)) + { return false; + } AssetImporter? importer = m_importers.FindByPath(relativePath); if (importer is null) + { return false; + } AssetRecord? existingRecord = FindRecordLocked(relativePath); AssetSourceMount sourceMount = GetMount(relativePath); if (sourceMount.isReadOnly && !IOFile.Exists(GetMetaPath(relativePath))) { throw new InvalidDataException( - $"Read-only source '{relativePath}' requires a valid '{C_META_POSTFIX}' sidecar."); + $"Read-only source '{relativePath}' requires a valid '{C_META_POSTFIX}' sidecar." + ); } Guid persistentId = existingRecord?.persistentId - ?? m_pendingImportIds.GetValueOrDefault(relativePath); - if (persistentId == Guid.Empty && - TryReadSourceMeta(GetMetaPath(relativePath), out AssetSourceMeta sourceMeta)) - { + ?? m_pendingImportIds.GetValueOrDefault(relativePath); + if (persistentId == Guid.Empty + && TryReadSourceMeta(GetMetaPath(relativePath), out AssetSourceMeta sourceMeta) + ) { persistentId = sourceMeta.persistentId; AssetRecord? sameId = FindRecordByIdWithoutLoading(persistentId); - if (sameId is not null && - !string.Equals(sameId.relativePath, relativePath, StringComparison.OrdinalIgnoreCase)) - { + if (sameId is not null + && !string.Equals(sameId.relativePath, relativePath, StringComparison.OrdinalIgnoreCase) + ) { if (sameId.meta.isTombstone) { RebindTombstoneLocked(sameId, relativePath); @@ -137,7 +147,8 @@ private bool ImportLocked( else if (sourceMount.isReadOnly) { throw new InvalidDataException( - $"Read-only source '{relativePath}' duplicates persistent ID '{persistentId}'."); + $"Read-only source '{relativePath}' duplicates persistent ID '{persistentId}'." + ); } else { @@ -146,7 +157,9 @@ private bool ImportLocked( } } if (persistentId == Guid.Empty) + { persistentId = Guid.NewGuid(); + } m_pendingImportIds[relativePath] = persistentId; m_activeImports.Add(relativePath); try @@ -161,7 +174,8 @@ private bool ImportLocked( importer, persistentId, sourceStamp, - context => attemptedContext = context); + context => attemptedContext = context + ); try { CommitBuildLocked(build, writeSource: false, sourceBytes); @@ -169,8 +183,11 @@ private bool ImportLocked( { foreach (string dependent in m_unavailableImports .Where(pair => pair.Value.kind == recovered.kind && pair.Value.id == recovered.id) - .Select(static pair => pair.Key).ToArray()) + .Select(static pair => pair.Key) + .ToArray() + ) { m_unavailableImports.Remove(dependent); + } } } finally @@ -188,7 +205,8 @@ private bool ImportLocked( persistentId, exception, sourceStamp, - attemptedContext); + attemptedContext + ); return false; } } @@ -211,22 +229,30 @@ private bool ImportLocked( private bool IsExtensionImportUnchanged(string relativePath) { - if (!m_unavailableImports.TryGetValue(relativePath, out var previous) || - previous.generation != m_types.current.version || - !AssetSourceFileStamp.TryCapture(GetSourcePath(relativePath), out AssetSourceFileStamp sourceStamp) || - sourceStamp != previous.source) + if (!m_unavailableImports.TryGetValue(relativePath, out var previous) + || previous.generation != m_types.current.version + || !AssetSourceFileStamp.TryCapture(GetSourcePath(relativePath), out AssetSourceFileStamp sourceStamp) + || sourceStamp != previous.source + ) { return false; + } AssetSourceFileStamp.TryCapture(GetMetaPath(relativePath), out AssetSourceFileStamp metadataStamp); if (metadataStamp != previous.metadata) + { return false; + } AssetRecord? record = FindRecordLocked(relativePath); if (record is null) + { return false; + } foreach (AssetImportDependencyData value in record.meta.importDependencies) { AssetImportDependencyData dependency = value; if (ComputeImportDependencyFingerprintLocked(ref dependency, out _) != value.fingerprint) + { return false; + } } return true; } @@ -267,10 +293,13 @@ private ImportBuild BuildImportLocked( { throw new FileNotFoundException( $"Import source dependency '{normalizedDependency}' does not exist.", - physicalPath); + physicalPath + ); } return ReadStableSourceBytes(physicalPath, out _); - }, this); + }, + this + ); onContextCreated?.Invoke(context); byte[] settingsBytes = ReadImportSettingsBytesLocked(relativePath, importer); context.importSettings = RestoreImportSettingsLocked(importer, settingsBytes, context); @@ -283,29 +312,34 @@ private ImportBuild BuildImportLocked( if (!Enum.IsDefined(deploymentScope)) { throw new InvalidOperationException( - $"Importer '{importer.GetType().FullName}' declares an unsupported deployment scope."); + $"Importer '{importer.GetType().FullName}' declares an unsupported deployment scope." + ); } bool hasRuntimeOutput = product.outputs.ContainsKey("runtime"); if (deploymentScope == AssetDeploymentScope.Runtime && !hasRuntimeOutput) { throw new InvalidOperationException( - $"Runtime importer '{importer.GetType().FullName}' must write a 'runtime' artifact output."); + $"Runtime importer '{importer.GetType().FullName}' must write a 'runtime' artifact output." + ); } if (deploymentScope == AssetDeploymentScope.AuthoringOnly && hasRuntimeOutput) { throw new InvalidOperationException( - $"Authoring-only importer '{importer.GetType().FullName}' cannot write a 'runtime' artifact output."); + $"Authoring-only importer '{importer.GetType().FullName}' cannot write a 'runtime' artifact output." + ); } if (!importer.targetAssetType.IsInstanceOfType(product.asset)) { throw new InvalidOperationException( - $"Importer '{importer.GetType().FullName}' returned '{product.asset.GetType().FullName}' " + - $"instead of '{importer.targetAssetType.FullName}'."); + $"Importer '{importer.GetType().FullName}' returned '{product.asset.GetType().FullName}' " + + $"instead of '{importer.targetAssetType.FullName}'." + ); } if (!m_types.TryGetTypeRef(product.asset.GetType(), out TypeRef assetTypeRef)) { throw new InvalidOperationException( - $"Imported asset type '{product.asset.GetType().FullName}' requires a StableTypeId."); + $"Imported asset type '{product.asset.GetType().FullName}' requires a StableTypeId." + ); } AssetDependency[] runtimeDependencies = ResolveDeclaredDependenciesLocked(context); @@ -316,10 +350,13 @@ private ImportBuild BuildImportLocked( sourceHash, product.runtimePayload, false, - 1); + 1 + ); var outputs = new Dictionary>(product.outputs, StringComparer.Ordinal); if (!outputs.TryAdd("asset-state", state)) + { throw new InvalidOperationException("The artifact output name 'asset-state' is reserved."); + } string implementationFingerprint = GetImporterImplementationFingerprint(importer); var meta = new AssetMeta { @@ -347,7 +384,8 @@ private ImportBuild BuildImportLocked( product.runtimePayload.ToArray(), outputs, product.authoringOutputs, - runtimeDependencies); + runtimeDependencies + ); } private void CommitBuildLocked( @@ -356,7 +394,9 @@ private void CommitBuildLocked( byte[] sourceBytes ) { if (writeSource && m_sourceMetadataStage is not null) + { throw new InvalidOperationException("An isolated Asset candidate cannot edit authoring source content."); + } AssetRecord? existing = FindRecordLocked(build.meta.relativePath); AssetObject? canonical = existing?.asset; byte[]? previousState = null; @@ -376,7 +416,8 @@ byte[] sourceBytes build.meta.sourceHash, replaced.runtimePayload, true, - replaced.contentVersion + 1); + replaced.contentVersion + 1 + ); m_runtimeOwner.Release(replaced); m_identities.Unregister(replaced); existing!.asset = null; @@ -401,7 +442,8 @@ byte[] sourceBytes build.meta.sourceHash, build.payload, false, - previousVersion + 1); + previousVersion + 1 + ); } catch { @@ -412,7 +454,8 @@ byte[] sourceBytes previousPath, previousHash, previousMissing, - previousVersion); + previousVersion + ); throw; } } @@ -424,24 +467,33 @@ byte[] sourceBytes try { if (writeSource) + { WriteAtomic(sourcePath, sourceBytes); + } if (!AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp sourceStamp)) + { throw new IOException($"Source '{build.meta.relativePath}' changed while its import was committing."); + } if (!writeSource && !SourceStampMatches(build.meta, sourceStamp)) { - throw new IOException( - $"Source '{build.meta.relativePath}' changed while its importer was running."); + throw new IOException($"Source '{build.meta.relativePath}' changed while its importer was running."); } ApplySourceStamp(build.meta, sourceStamp); - if (!string.Equals(build.meta.importerSettingsHash, - ComputeSha256Hex(ReadImportSettingsBytesLocked(build.meta.relativePath, - m_importers.FindById(build.meta.importerId)!)), StringComparison.Ordinal)) + if (!string.Equals( + build.meta.importerSettingsHash, + ComputeSha256Hex( + ReadImportSettingsBytesLocked(build.meta.relativePath, m_importers.FindById(build.meta.importerId)!) + ), + StringComparison.Ordinal + )) { throw new IOException($"Import settings for '{build.meta.relativePath}' changed during import."); + } ValidateImportDependencySnapshotsLocked(build.meta); AssetArtifactKey artifactKey = m_artifacts.Commit( CreateImportFingerprint(build.meta), build.outputs, - build.authoringOutputs); + build.authoringOutputs + ); build.meta.artifactKey = artifactKey.value; build.meta.lastSuccessfulArtifactKey = artifactKey.value; WriteSourceMeta(build.meta); @@ -449,7 +501,9 @@ byte[] sourceBytes catch { if (writeSource) + { RestoreFile(sourcePath, sourceSnapshot); + } RestoreFile(metaPath, metaSnapshot); if (canonical is not null && previousState is not null && previousPayload is not null) { @@ -460,7 +514,8 @@ byte[] sourceBytes previousPath, previousHash, previousMissing, - previousVersion); + previousVersion + ); } throw; } @@ -473,7 +528,9 @@ byte[] sourceBytes record.payload = build.payload; record.importerGeneration = m_importers.GetGeneration(build.meta.importerId); if (canonical is not null) + { record.asset = canonical; + } AddOrReplaceRecordLocked(record); UpdateGraphsLocked(record); CommitCatalogLocked(); @@ -492,5 +549,4 @@ private readonly record struct ImportBuild( IReadOnlySet authoringOutputs, AssetDependency[] dependencies ); - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs index 3e8bf4f1d..ad2ffae59 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -153,7 +152,8 @@ out AssetObject? asset _ => RemovePathOperation(normalized, operation), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); + TaskScheduler.Default + ); } } return AwaitSharedLoad(operation, requestedAssetType, cancellationToken); @@ -192,7 +192,8 @@ out AssetObject? asset _ => RemoveIdOperation(persistentId, operation), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); + TaskScheduler.Default + ); } } return AwaitSharedLoad(operation, requestedAssetType, cancellationToken); @@ -224,7 +225,9 @@ Type expectedType ) { ArgumentNullException.ThrowIfNull(expectedType); if (persistentId == Guid.Empty) + { throw new InvalidOperationException("A serialized asset reference has an empty persistent identity."); + } return Execute(() => ResolveReferenceLocked(persistentId, stableTypeId, lastKnownPath, expectedType)); } @@ -246,9 +249,10 @@ string propertyPath catch (Exception exception) { throw new InvalidOperationException( - $"Asset reference '{persistentId:D}' at '{propertyPath}' cannot be resolved as " + - $"'{expectedType.FullName}'.", - exception); + $"Asset reference '{persistentId:D}' at '{propertyPath}' cannot be resolved as " + + $"'{expectedType.FullName}'.", + exception + ); } } @@ -273,7 +277,9 @@ Type requestedAssetType } } if (catalogChanged && !stale) + { CommitCatalogLocked(); + } if (record is null || stale) { if (!ImportLocked(relativePath)) @@ -291,18 +297,22 @@ record = FindRecordLocked(relativePath); Type requestedAssetType ) { if (persistentId == Guid.Empty) + { return null; + } if (!m_recordsById.TryGetValue(persistentId, out AssetRecord? record)) { LoadCatalogLocked(); if (!m_recordsById.TryGetValue(persistentId, out record)) + { return null; + } } if (record.meta.isTombstone) { return record.asset is null - ? null - : LoadRecordLocked(record, requestedAssetType); + ? null + : LoadRecordLocked(record, requestedAssetType); } // A source-side identity can be indexed before its body is imported. Route identity loads @@ -310,11 +320,11 @@ Type requestedAssetType // or stale artifact merely because their sidecar was discovered first. The sidecar check // keeps a newly created asset at the same path from satisfying an older identity lookup. bool ownsCurrentSource = IOFile.Exists(GetSourcePath(record.relativePath)) - && TryReadSourceMeta(GetMetaPath(record.relativePath), out AssetSourceMeta sourceMeta) - && sourceMeta.persistentId == persistentId; + && TryReadSourceMeta(GetMetaPath(record.relativePath), out AssetSourceMeta sourceMeta) + && sourceMeta.persistentId == persistentId; return ownsCurrentSource - ? LoadPathLocked(record.relativePath, requestedAssetType) - : LoadRecordLocked(record, requestedAssetType); + ? LoadPathLocked(record.relativePath, requestedAssetType) + : LoadRecordLocked(record, requestedAssetType); } private AssetObject? LoadRecordLocked( @@ -324,23 +334,33 @@ Type requestedAssetType if (string.IsNullOrEmpty(record.meta.artifactKey) && record.meta.assetStateBytes.Length == 0) { if (m_activeImports.Count != 0 && m_unavailableImports.TryGetValue(record.relativePath, out var unavailable)) + { throw new AssetImportExtensionUnavailableException(unavailable.kind, unavailable.id); + } return null; } Type? actualType = ResolveRecordType(record); if (actualType is null || !requestedAssetType.IsAssignableFrom(actualType)) + { return null; + } if (record.asset is not null) + { return requestedAssetType.IsInstanceOfType(record.asset) ? record.asset : null; + } var transaction = new AssetLoadTransaction(); try { PrepareShellsLocked(record, transaction); foreach (AssetRecord created in transaction.createdRecords) + { HydrateRecordLocked(created); + } foreach (AssetRecord created in transaction.createdRecords) + { AttachDependenciesLocked(created); + } return record.asset; } catch @@ -355,24 +375,31 @@ private void PrepareShellsLocked( AssetLoadTransaction transaction ) { if (record.asset is not null) + { return; + } Type type = ResolveRecordType(record) - ?? throw new InvalidOperationException( - $"Asset '{record.relativePath}' has unknown stable type '{record.stableTypeId}'."); + ?? throw new InvalidOperationException( + $"Asset '{record.relativePath}' has unknown stable type '{record.stableTypeId}'." + ); AssetObject shell; try { shell = (AssetObject)(Activator.CreateInstance(type, nonPublic: true) - ?? throw new InvalidOperationException("Activator returned null.")); + ?? throw new InvalidOperationException("Activator returned null.")); } catch (Exception exception) { throw new InvalidOperationException( - $"Asset type '{type.FullName}' requires a parameterless constructor.", exception); + $"Asset type '{type.FullName}' requires a parameterless constructor.", + exception + ); } m_identities.InitializePersistentIdentity(shell, record.persistentId); if (m_identitiesActive) + { m_identities.Register(shell, record.persistentId); + } record.asset = shell; transaction.createdRecords.Add(record); @@ -383,9 +410,11 @@ AssetLoadTransaction transaction // activated yet. Do not let that temporary type gap abort the entire object graph; // AttachDependenciesLocked installs the identity-preserving placeholder and a later // registry generation rehydrates the reference from the retained catalog record. - if (dependencyRecord is not null && ResolveRecordType(dependencyRecord) is not null && - (dependencyRecord.meta.assetStateBytes.Length != 0 || !string.IsNullOrEmpty(dependencyRecord.meta.artifactKey))) + if (dependencyRecord is not null && ResolveRecordType(dependencyRecord) is not null + && (dependencyRecord.meta.assetStateBytes.Length != 0 || !string.IsNullOrEmpty(dependencyRecord.meta.artifactKey)) + ) { PrepareShellsLocked(dependencyRecord, transaction); + } } } @@ -393,11 +422,11 @@ private void HydrateRecordLocked(AssetRecord record) { AssetObject asset = record.asset!; RestoreAssetState(asset, record.meta.assetStateBytes); - byte[] payload = m_artifacts.Read( - new AssetArtifactKey(record.meta.artifactKey), - "runtime"); + byte[] payload = m_artifacts.Read(new AssetArtifactKey(record.meta.artifactKey), "runtime"); if (payload.Length == 0 && record.payload.Length > 0) + { payload = record.payload; + } record.payload = payload; bool isMissing = record.meta.importStatus == (int)AssetImportStatus.Missing; m_runtimeOwner.Initialize( @@ -406,7 +435,8 @@ private void HydrateRecordLocked(AssetRecord record) record.meta.sourceHash, payload, isMissing, - 1); + 1 + ); } private AssetObject ResolveReferenceLocked( @@ -417,31 +447,37 @@ Type expectedType ) { AssetObject? loaded = LoadIdLocked(persistentId, expectedType); if (loaded is not null) + { return loaded; + } // A cataloged source whose importer/type belongs to a later module generation is // unavailable, not missing. Startup and atomic reload may legitimately observe this // state before the corresponding generation is activated; publishing a missing-reference // diagnostic here would turn a healthy last-good asset into a false warning. if (!IsSourceBackedTypeUnavailableLocked(persistentId)) - m_diagnostics.PublishMissingReference(persistentId, lastKnownPath, expectedType); - if (m_missingAssets.TryGetValue(persistentId, out WeakReference? weak) && - weak.TryGetTarget(out AssetObject? existing) && expectedType.IsInstanceOfType(existing)) { + m_diagnostics.PublishMissingReference(persistentId, lastKnownPath, expectedType); + } + if (m_missingAssets.TryGetValue(persistentId, out WeakReference? weak) + && weak.TryGetTarget(out AssetObject? existing) && expectedType.IsInstanceOfType(existing) + ) { return existing; } Type type = ResolveDependencyExpectedType( - new AssetDependency(persistentId, new TypeRef(stableTypeId), lastKnownPath)); - if (type == typeof(MissingAsset) && - !expectedType.IsAbstract && - !expectedType.IsInterface && - typeof(AssetObject).IsAssignableFrom(expectedType)) - { + new AssetDependency(persistentId, new TypeRef(stableTypeId), lastKnownPath) + ); + if (type == typeof(MissingAsset) + && !expectedType.IsAbstract + && !expectedType.IsInterface + && typeof(AssetObject).IsAssignableFrom(expectedType) + ) { type = expectedType; } if (!expectedType.IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Missing asset type '{type.FullName}' cannot be assigned to '{expectedType.FullName}'."); + $"Missing asset type '{type.FullName}' cannot be assigned to '{expectedType.FullName}'." + ); } AssetObject missing = (AssetObject)(Activator.CreateInstance(type, nonPublic: true) ?? throw new InvalidOperationException($"Missing asset type '{type.FullName}' cannot be created.")); @@ -452,7 +488,8 @@ Type expectedType string.Empty, ReadOnlyMemory.Empty, true, - 0); + 0 + ); m_missingAssets[persistentId] = new WeakReference(missing); return missing; } @@ -473,7 +510,9 @@ private void RollbackLoadLocked(AssetLoadTransaction transaction) private T Execute(Func action) { if (ReferenceEquals(t_activeLoader, this)) + { return action(); + } using IDisposable generation = m_types.AcquireOperation("access Asset loader"); lock (m_asyncSync) { @@ -498,7 +537,9 @@ private T Execute(Func action) finally { lock (m_asyncSync) + { m_admittedOperations--; + } } } @@ -524,9 +565,9 @@ private void RemovePathOperation( ) { lock (m_asyncSync) { - if (m_inFlightPathLoads.TryGetValue(relativePath, out Task? current) && - ReferenceEquals(current, operation)) - { + if (m_inFlightPathLoads.TryGetValue(relativePath, out Task? current) + && ReferenceEquals(current, operation) + ) { m_inFlightPathLoads.Remove(relativePath); } } @@ -538,9 +579,9 @@ private void RemoveIdOperation( ) { lock (m_asyncSync) { - if (m_inFlightIdLoads.TryGetValue(persistentId, out Task? current) && - ReferenceEquals(current, operation)) - { + if (m_inFlightIdLoads.TryGetValue(persistentId, out Task? current) + && ReferenceEquals(current, operation) + ) { m_inFlightIdLoads.Remove(persistentId); } } @@ -550,5 +591,4 @@ private sealed class AssetLoadTransaction { internal List createdRecords { get; } = []; } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs index 1033ac3bd..99fec9704 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -28,13 +27,13 @@ sealed partial class AssetLoader { private bool IsSourceBackedTypeUnavailableLocked(Guid persistentId) { - if (!m_recordsById.TryGetValue(persistentId, out AssetRecord? record) || - record.meta.isTombstone || - record.persistentId == Guid.Empty || - string.IsNullOrWhiteSpace(record.meta.importerId) || - !IsMounted(record.relativePath) || - !IOFile.Exists(GetSourcePath(record.relativePath))) - { + if (!m_recordsById.TryGetValue(persistentId, out AssetRecord? record) + || record.meta.isTombstone + || record.persistentId == Guid.Empty + || string.IsNullOrWhiteSpace(record.meta.importerId) + || !IsMounted(record.relativePath) + || !IOFile.Exists(GetSourcePath(record.relativePath)) + ) { return false; } return ResolveRecordType(record) is null || m_unavailableImports.ContainsKey(record.relativePath); @@ -50,7 +49,9 @@ private void RefreshLoadedAssetReferencesLocked() AssetRecord record = loaded[i]; AssetObject asset = record.asset!; if (record.meta.assetStateBytes.Length == 0) + { continue; + } byte[] rollback = CaptureAssetState(asset); try { @@ -63,7 +64,9 @@ private void RefreshLoadedAssetReferencesLocked() } } for (int i = 0; i < loaded.Length; i++) + { AttachDependenciesLocked(loaded[i]); + } } internal IReadOnlyList CaptureRecoveryStates() @@ -76,10 +79,14 @@ internal IReadOnlyList CaptureRecoveryStates() // roots. Only a materialized canonical asset belongs to the active generation; // retained missing placeholders are captured separately below. if (record.asset is not null) + { Capture(record.persistentId, record.relativePath, record.stableTypeId, record.meta.assetStateBytes); + } } foreach ((Guid id, SerializedMissingState state) in m_preservedMissingStates) + { states.TryAdd(id, state); + } foreach ((Guid id, WeakReference reference) in m_missingAssets) { if (!states.ContainsKey(id) && reference.TryGetTarget(out AssetObject? missing)) @@ -96,9 +103,14 @@ void Capture( Guid stableTypeId, byte[] payload ) { - states.Add(id, new SerializedMissingState(new ReferenceKey(id, "$asset"), - new ReferenceDescriptor(AssetReferenceProtocol.id, id, stableTypeId, - lastKnownPath: path), payload)); + states.Add( + id, + new SerializedMissingState( + new ReferenceKey(id, "$asset"), + new ReferenceDescriptor(AssetReferenceProtocol.id, id, stableTypeId, lastKnownPath: path), + payload + ) + ); } }); @@ -109,7 +121,9 @@ internal void PreserveMissingRecoveryStates(IReadOnlyList Execute(() => { if (m_identitiesActive == active) + { return; + } var attempted = new List(); try { foreach (AssetRecord record in m_recordsById.Values) { if (record.asset is null) + { continue; + } attempted.Add(record.asset); if (active) + { m_identities.Register(record.asset, record.persistentId); + } else + { m_identities.Unregister(record.asset); + } } m_identitiesActive = active; m_diagnostics.SetActive(active); @@ -150,9 +172,13 @@ internal void SetIdentitiesActive(bool active) try { if (active) + { m_identities.Unregister(asset); + } else + { m_identities.Register(asset, asset.identity.persistentId); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -164,11 +190,12 @@ internal void SetIdentitiesActive(bool active) } } if (failures.Count > 1) + { throw new AggregateException("Asset identity publication and compensation failed.", failures); + } throw; } }); private sealed class MissingAsset : AssetObject; - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs index 7722488fe..1cb1723e4 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -46,7 +45,9 @@ long maximumSizeBytes { HashSet reachable = []; foreach (AssetArtifactKey retained in m_artifactRetention.GetRetainedKeys()) + { AddArtifactKey(reachable, retained.value); + } foreach (AssetRecord record in m_recordsByPath.Values) { AddArtifactKey(reachable, record.meta.artifactKey); @@ -79,13 +80,16 @@ out AssetArtifactInfo? artifact AssetArtifactInfo? result = Execute(() => { if (!m_recordsById.TryGetValue(persistentId, out AssetRecord? record)) + { return null; + } return m_artifacts.TryGet( new AssetArtifactKey(record.meta.artifactKey), outputName, - out AssetArtifactInfo? found) - ? found - : null; + out AssetArtifactInfo? found + ) + ? found + : null; }); artifact = result; return result is not null; @@ -109,13 +113,14 @@ out AssetArtifactInfo? artifact public ArtifactLease AcquireArtifact( Guid persistentId, string outputName - ) - => Execute(() => + ) => Execute(() => + { + if (!TryGetArtifact(persistentId, outputName, out AssetArtifactInfo? artifact) || artifact is null) { - if (!TryGetArtifact(persistentId, outputName, out AssetArtifactInfo? artifact) || artifact is null) - throw new InvalidOperationException($"Asset '{persistentId:D}' has no output '{outputName}'."); - return m_artifactRetention.Retain(artifact, m_artifacts.CreateReadFactory(artifact)); - }); + throw new InvalidOperationException($"Asset '{persistentId:D}' has no output '{outputName}'."); + } + return m_artifactRetention.Retain(artifact, m_artifacts.CreateReadFactory(artifact)); + }); /// /// Collects canonical assets that have no external managed references. @@ -130,7 +135,9 @@ private int UnloadUnusedAssetsLocked() { SweepCandidate[] candidates = DetachSweepCandidatesLocked(); if (candidates.Length == 0) + { return 0; + } GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); GC.WaitForPendingFinalizers(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); @@ -157,7 +164,9 @@ private SweepCandidate[] DetachSweepCandidatesLocked() foreach (AssetRecord record in m_recordsByPath.Values) { if (record.asset is null) + { continue; + } result.Add(new SweepCandidate(record, new WeakReference(record.asset))); record.asset = null; } @@ -169,12 +178,13 @@ private static void AddArtifactKey( string value ) { if (!string.IsNullOrWhiteSpace(value)) + { reachable.Add(value.ToUpperInvariant()); + } } private readonly record struct SweepCandidate( AssetRecord record, WeakReference reference ); - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs index a9f8beafb..e3c71bbb7 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -40,13 +39,17 @@ public void Dispose() lock (m_asyncSync) { if (m_disposed) + { return; + } m_disposeRequested = true; bool pending = m_inFlightPathLoads.Values .Concat(m_inFlightIdLoads.Values) .Any(static task => !task.IsCompleted); if (pending || m_admittedOperations > 0 || m_retirementActive) + { throw new RetirementPendingException("Asset operations must complete before their loader retires."); + } m_retirementActive = true; } AssetLoader? previous = t_activeLoader; @@ -59,16 +62,18 @@ public void Dispose() { t_activeLoader = previous; if (m_disposed) + { m_operationGate.Dispose(); + } lock (m_asyncSync) + { m_retirementActive = false; + } } } private void RetireUnmountedRecordLocked(AssetRecord record) - => RetireRecordLocked( - record, - $"Asset source mount for '{record.relativePath}' is not active."); + => RetireRecordLocked(record, $"Asset source mount for '{record.relativePath}' is not active."); private void RetireRecordLocked( AssetRecord record, @@ -101,7 +106,8 @@ string diagnostic record.meta.sourceHash, ReadOnlyMemory.Empty, true, - record.asset.contentVersion + 1); + record.asset.contentVersion + 1 + ); PublishReloaded(record.asset); } @@ -112,14 +118,16 @@ private bool ReleaseRetiredCanonicalAssetsLocked() { AssetObject? asset = record.asset; if (asset is null) + { continue; + } bool isCurrent = m_types.TryGetTypeRef(asset.GetType(), out _); TypeRef persistedType = new(record.stableTypeId); - if (isCurrent && - (record.stableTypeId == Guid.Empty || - !m_types.TryResolve(persistedType, out Type? resolvedType) || - resolvedType == asset.GetType())) - { + if (isCurrent + && (record.stableTypeId == Guid.Empty + || !m_types.TryResolve(persistedType, out Type? resolvedType) + || resolvedType == asset.GetType()) + ) { continue; } @@ -135,7 +143,8 @@ private bool ReleaseRetiredCanonicalAssetsLocked() m_log.Write( LogLevel.Error, "Retired asset '{0}' was released, but an identity observer failed: {1}", - [record.relativePath, exception]); + [record.relativePath, exception] + ); } finally { @@ -149,7 +158,9 @@ private bool ReleaseRetiredCanonicalAssetsLocked() private void DisposeLocked() { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new LifetimeScope(); @@ -159,7 +170,9 @@ private void DisposeLocked() foreach (AssetRecord record in m_recordsById.Values) { if (record.asset is not null) + { m_retirement.Own(new AssetRecordRetirement(this, record)); + } } } try @@ -209,7 +222,9 @@ AssetRecord record public void Dispose() { if (record.asset is null) + { return; + } if (!m_released) { try @@ -240,8 +255,9 @@ public void Dispose() } record.asset = null; if (m_failures.Count > 0) + { throw new AggregateException("Canonical Asset retirement failed after releasing its registration.", m_failures); + } } } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs index 4dd6e5dac..58ad739c2 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -66,8 +65,7 @@ public AssetRuntimeContentInfo ExportRuntimeArtifacts(string destinationLibraryR public AssetRuntimeContentInfo ExportRuntimeArtifacts( string destinationLibraryRoot, CancellationToken cancellationToken - ) - => Execute(() => ExportRuntimeArtifactsLocked(destinationLibraryRoot, cancellationToken)); + ) => Execute(() => ExportRuntimeArtifactsLocked(destinationLibraryRoot, cancellationToken)); internal AssetRuntimeContentInfo ExportRuntimeArtifacts( string destinationLibraryRoot, @@ -75,10 +73,7 @@ internal AssetRuntimeContentInfo ExportRuntimeArtifacts( CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(serialization); - return Execute(() => ExportRuntimeArtifactsLocked( - destinationLibraryRoot, - cancellationToken, - serialization)); + return Execute(() => ExportRuntimeArtifactsLocked(destinationLibraryRoot, cancellationToken, serialization)); } private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( @@ -90,16 +85,19 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( ArgumentException.ThrowIfNullOrWhiteSpace(destinationLibraryRoot); string destination = Path.GetFullPath(destinationLibraryRoot); if (Directory.Exists(destination) && Directory.EnumerateFileSystemEntries(destination).Any()) + { throw new IOException("Runtime asset content destination must be empty."); + } AssetRecord[] imported = m_recordsByPath.Values - .Where(static record => + .Where(static record => ( !record.meta.isDirectory && !record.meta.isTombstone && !AssetSample.IsRuntimeExcluded(AssetPath.Parse(record.relativePath), isDirectory: false) && (record.meta.importStatus == (int)AssetImportStatus.Imported || !string.IsNullOrEmpty(record.meta.artifactKey) || (!string.IsNullOrEmpty(record.meta.importerId) - && record.meta.importStatus is (int)AssetImportStatus.Pending or (int)AssetImportStatus.Failed))) + && record.meta.importStatus is (int)AssetImportStatus.Pending or (int)AssetImportStatus.Failed)) + )) .OrderBy(static record => record.relativePath, StringComparer.Ordinal) .ToArray(); AssetRecord? invalidScope = imported.FirstOrDefault(static record => @@ -107,14 +105,17 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( if (invalidScope is not null) { throw new InvalidOperationException( - $"Asset '{invalidScope.relativePath}' has an invalid deployment scope."); + $"Asset '{invalidScope.relativePath}' has an invalid deployment scope." + ); } AssetRecord[] exported = imported .Where(static record => record.meta.deploymentScope == (int)AssetDeploymentScope.Runtime) .ToArray(); var validated = new HashSet(); foreach (AssetRecord record in exported) + { ValidateExportInputsLocked(record, record.relativePath, validated, cancellationToken); + } string[] keys = exported .Select(static record => record.meta.artifactKey) .Distinct(StringComparer.Ordinal) @@ -124,10 +125,11 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( { AssetArtifactKey key = new(record.meta.artifactKey); if (!m_artifacts.TryGet(key, "asset-state", serialization, out _) - || !m_artifacts.TryGet(key, "runtime", serialization, out _)) - { + || !m_artifacts.TryGet(key, "runtime", serialization, out _) + ) { throw new InvalidOperationException( - $"Asset '{record.relativePath}' has no complete runtime artifact bundle '{key}'."); + $"Asset '{record.relativePath}' has no complete runtime artifact bundle '{key}'." + ); } } HashSet exportedIds = exported @@ -140,24 +142,29 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( if (unavailable.persistentId != Guid.Empty) { throw new InvalidOperationException( - $"Runtime asset '{record.relativePath}' depends on non-runtime asset " + - $"'{unavailable.lastKnownPath}'."); + $"Runtime asset '{record.relativePath}' depends on non-runtime asset " + + $"'{unavailable.lastKnownPath}'." + ); } } Directory.CreateDirectory(destination); AssetCatalogStore catalog = serialization is null - ? new AssetCatalogStore(destination, m_serialization) - : new AssetCatalogStore(destination, serialization); + ? new AssetCatalogStore(destination, m_serialization) + : new AssetCatalogStore(destination, serialization); var destinationArtifacts = new AssetArtifactStore(destination, m_serialization); var projectedKeys = new Dictionary(StringComparer.Ordinal); foreach (string key in keys) + { projectedKeys.Add(key, m_artifacts.ExportRuntime(new(key), destinationArtifacts, serialization, cancellationToken)); + } var deployed = new List(); foreach (AssetRecord record in exported) { byte[] bytes = serialization is null ? m_serialization.Serialize(record.meta) : serialization.Serialize(record.meta); - AssetMeta meta = serialization is null ? m_serialization.Deserialize(bytes) : serialization.Deserialize(bytes); + AssetMeta meta = serialization is null + ? m_serialization.Deserialize(bytes) + : serialization.Deserialize(bytes); meta.artifactKey = projectedKeys[record.meta.artifactKey].value; meta.lastSuccessfulArtifactKey = meta.artifactKey; meta.importDependencies = []; @@ -167,7 +174,8 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( long totalBytes = Directory .EnumerateFiles(Path.Combine(destination, "AssetDatabase"), "*", SearchOption.AllDirectories) .Sum(static path => new FileInfo(path).Length); - totalBytes += Directory.EnumerateFiles(destinationArtifacts.root, "*", SearchOption.AllDirectories).Sum(static path => new FileInfo(path).Length); + totalBytes += Directory.EnumerateFiles(destinationArtifacts.root, "*", SearchOption.AllDirectories) + .Sum(static path => new FileInfo(path).Length); AssetSourceId[] sources = exported .Select(static record => AssetPath.Parse(record.relativePath).source) @@ -176,7 +184,9 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( .OrderBy(static source => source.value, StringComparer.Ordinal) .ToArray(); foreach (AssetSourceId source in sources) + { Directory.CreateDirectory(Path.Combine(destination, "Sources", source.value)); + } return new AssetRuntimeContentInfo(sources, exported.Length, keys.Length, totalBytes); } @@ -188,13 +198,16 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); if (!validated.Add(record.persistentId)) + { return; + } if (record.meta.isTombstone || record.meta.importStatus != (int)AssetImportStatus.Imported) { throw new InvalidOperationException( - $"Runtime export requires successful current inputs: {dependencyChain}. " + - $"Status: {(AssetImportStatus)record.meta.importStatus}. " + - string.Join(" | ", record.meta.diagnostics)); + $"Runtime export requires successful current inputs: {dependencyChain}. " + + $"Status: {(AssetImportStatus)record.meta.importStatus}. " + + string.Join(" | ", record.meta.diagnostics) + ); } // Validate authoring inputs as well as deployed references. Editor last-good artifacts @@ -202,12 +215,15 @@ CancellationToken cancellationToken foreach (AssetImportDependencyData dependency in record.meta.importDependencies) { if ((AssetImportDependencyKind)dependency.kind != AssetImportDependencyKind.Artifact) + { continue; + } if (!Guid.TryParse(dependency.key, out Guid id) - || !m_recordsById.TryGetValue(id, out AssetRecord? input)) - { + || !m_recordsById.TryGetValue(id, out AssetRecord? input) + ) { throw new InvalidOperationException( - $"Runtime export has a missing artifact input: {dependencyChain} -> {dependency.key}."); + $"Runtime export has a missing artifact input: {dependencyChain} -> {dependency.key}." + ); } ValidateExportInputsLocked(input, $"{dependencyChain} -> {input.relativePath}", validated, cancellationToken); } @@ -216,7 +232,8 @@ CancellationToken cancellationToken if (IsStale(record, out _)) { throw new InvalidOperationException( - $"Runtime export has stale source inputs: {dependencyChain}. Reimport current sources and rebuild."); + $"Runtime export has stale source inputs: {dependencyChain}. Reimport current sources and rebuild." + ); } } @@ -227,26 +244,32 @@ private void ValidateRuntimeArtifactsLocked() if (!IsMounted(record.relativePath)) { throw new InvalidDataException( - $"Runtime asset '{record.relativePath}' references an undeclared source mount."); + $"Runtime asset '{record.relativePath}' references an undeclared source mount." + ); } if (record.meta.isDirectory || record.meta.isTombstone) + { continue; + } if (record.meta.deploymentScope != (int)AssetDeploymentScope.Runtime) { throw new InvalidDataException( - $"Runtime catalog contains authoring-only asset '{record.relativePath}'."); + $"Runtime catalog contains authoring-only asset '{record.relativePath}'." + ); } if (record.meta.importStatus != (int)AssetImportStatus.Imported) { throw new InvalidDataException( - $"Runtime asset '{record.relativePath}' was not successfully imported before export."); + $"Runtime asset '{record.relativePath}' was not successfully imported before export." + ); } AssetArtifactKey key = new(record.meta.artifactKey); if (!m_artifacts.TryGet(key, "asset-state", out _) - || !m_artifacts.TryGet(key, "runtime", out _)) - { + || !m_artifacts.TryGet(key, "runtime", out _) + ) { throw new InvalidDataException( - $"Runtime asset '{record.relativePath}' has an incomplete artifact bundle '{key}'."); + $"Runtime asset '{record.relativePath}' has an incomplete artifact bundle '{key}'." + ); } } } @@ -254,10 +277,11 @@ private void ValidateRuntimeArtifactsLocked() private void EnsureReadOnlyImportsSucceededLocked() { AssetRecord[] failed = m_recordsByPath.Values - .Where(record => + .Where(record => ( GetMount(record.relativePath).isReadOnly && record.meta.importStatus is (int)AssetImportStatus.Failed - or (int)AssetImportStatus.Conflict) + or (int)AssetImportStatus.Conflict + )) .OrderBy(static record => record.relativePath, StringComparer.Ordinal) .ToArray(); if (failed.Length == 0) @@ -267,10 +291,8 @@ private void EnsureReadOnlyImportsSucceededLocked() string details = string.Join( "; ", - failed.Select(record => - $"{record.relativePath}: {string.Join(" | ", record.meta.diagnostics)}")); - throw new InvalidDataException( - $"Read-only Asset Source candidate contains failed imports: {details}"); + failed.Select(record => $"{record.relativePath}: {string.Join(" | ", record.meta.diagnostics)}") + ); + throw new InvalidDataException($"Read-only Asset Source candidate contains failed imports: {details}"); } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs index 55cfee824..d809b2ec2 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -39,7 +38,9 @@ public bool Save(AssetObject asset) { ArgumentNullException.ThrowIfNull(asset); if (string.IsNullOrWhiteSpace(asset.assetPath.ToString())) + { throw new InvalidOperationException("An unsaved asset requires an explicit source-relative path."); + } return Save(asset.assetPath, asset); } @@ -69,40 +70,47 @@ private bool SaveLocked( AssetObject asset ) { if (GetMount(relativePath).isReadOnly) - throw new InvalidOperationException($"Asset source '{relativePath}' is read-only."); - if (!string.IsNullOrWhiteSpace(asset.assetPath.ToString()) && - !string.Equals(NormalizeRelativePath(asset.assetPath.ToString()), relativePath, StringComparison.OrdinalIgnoreCase)) { + throw new InvalidOperationException($"Asset source '{relativePath}' is read-only."); + } + if (!string.IsNullOrWhiteSpace(asset.assetPath.ToString()) + && !string.Equals(NormalizeRelativePath(asset.assetPath.ToString()), relativePath, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException( - $"Asset '{asset.assetPath.ToString()}' cannot be saved to unrelated path '{relativePath}' without creating a new asset."); + $"Asset '{asset.assetPath.ToString()}' cannot be saved to unrelated path '{relativePath}' without creating a new asset." + ); } AssetImporter? importer = m_importers.FindByPath(relativePath); if (importer is null || !importer.targetAssetType.IsInstanceOfType(asset)) + { return false; + } ReadOnlyMemory? exported = importer - .ExportInternalAsync( - new AssetExportContext(m_types, m_serialization, this), - asset, - CancellationToken.None) + .ExportInternalAsync(new AssetExportContext(m_types, m_serialization, this), asset, CancellationToken.None) .AsTask() .GetAwaiter() .GetResult(); if (exported is null) + { return false; + } byte[] sourceBytes = exported.Value.ToArray(); AssetRecord? destinationRecord = FindRecordLocked(relativePath); bool destinationOwnsIdentity = destinationRecord is not null - && destinationRecord.persistentId != Guid.Empty; + && destinationRecord.persistentId != Guid.Empty; Guid persistentId = destinationOwnsIdentity - ? destinationRecord!.persistentId - : asset.identity.persistentId; + ? destinationRecord!.persistentId + : asset.identity.persistentId; if (persistentId == Guid.Empty) + { persistentId = Guid.NewGuid(); + } if (asset.identity.runtimeId is not null && asset.identity.persistentId != persistentId) { throw new InvalidOperationException( - $"Registered asset '{asset.identity.persistentId:D}' cannot replace destination identity " + - $"'{persistentId:D}' at '{relativePath}'."); + $"Registered asset '{asset.identity.persistentId:D}' cannot replace destination identity " + + $"'{persistentId:D}' at '{relativePath}'." + ); } ImportBuild build = BuildImportLocked(relativePath, sourceBytes, importer, persistentId); AssetRecord? provisionalRecord = null; @@ -136,26 +144,35 @@ AssetObject asset catch { if (provisionalRecord is not null) + { RemoveRecordLocked(provisionalRecord, removeGeneratedFiles: false); + } if (registeredHere) + { m_identities.Unregister(asset); + } throw; } AssetRecord committed = m_recordsByPath[relativePath]; if (committed.asset is null) { if (asset.identity.persistentId != persistentId) + { m_identities.InitializePersistentIdentity(asset, persistentId); + } committed.asset = asset; if (m_identitiesActive && asset.identity.runtimeId is null) + { m_identities.Register(asset, persistentId); + } m_runtimeOwner.Initialize( asset, AssetPath.Parse(relativePath), build.meta.sourceHash, build.payload, false, - 1); + 1 + ); AttachDependenciesLocked(committed); } return true; @@ -171,19 +188,11 @@ private void RestoreCanonical( long version ) { RestoreAssetState(canonical, state); - m_runtimeOwner.Initialize( - canonical, - AssetPath.Parse(sourcePath), - sourceHash, - payload, - isMissing, - version); + m_runtimeOwner.Initialize(canonical, AssetPath.Parse(sourcePath), sourceHash, payload, isMissing, version); } private byte[] CaptureAssetState(AssetObject asset) - => m_serialization.Encode( - writer => writer.WriteProperties(asset), - m_serializationContext); + => m_serialization.Encode(writer => writer.WriteProperties(asset), m_serializationContext); private void RestoreAssetState( AssetObject asset, @@ -195,5 +204,4 @@ ReadOnlySpan state return true; }, m_serializationContext); } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs index 4359eba75..4bdb744b8 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -68,14 +67,16 @@ private void RescanLocked() m_importCancellation.ThrowIfCancellationRequested(); LoadCatalogLocked(); bool registriesChanged = - m_importerRegistryVersion != m_importers.snapshotVersion || - m_buildProcessorRegistryVersion != m_buildProcessors.snapshotVersion; + m_importerRegistryVersion != m_importers.snapshotVersion + || m_buildProcessorRegistryVersion != m_buildProcessors.snapshotVersion; bool releasedRetiredAssets = ReleaseRetiredCanonicalAssetsLocked(); if (m_runtimeArtifactsOnly) { ValidateRuntimeArtifactsLocked(); if (releasedRetiredAssets || registriesChanged) + { RefreshLoadedAssetReferencesLocked(); + } m_importerRegistryVersion = m_importers.snapshotVersion; m_buildProcessorRegistryVersion = m_buildProcessors.snapshotVersion; return; @@ -83,9 +84,7 @@ private void RescanLocked() EnsureDirectoryMetadataLocked(); AssetPath[] sourceFiles = m_mounts.Values .SelectMany(mount => Directory.GetFiles(mount.rootPath, "*", SearchOption.AllDirectories) - .Select(path => new AssetPath( - mount.id, - Path.GetRelativePath(mount.rootPath, path).Replace('\\', '/')))) + .Select(path => new AssetPath(mount.id, Path.GetRelativePath(mount.rootPath, path).Replace('\\', '/')))) .Where(path => !IsSourceIgnored(path, isDirectory: false)) .ToArray(); foreach (AssetPath sourceFile in sourceFiles) @@ -101,14 +100,15 @@ private void RescanLocked() } TryAssociateUntrackedRenameLocked(relative, absoluteSource); AssetRecord? record = FindRecordLocked(relative); - if (record is null || - record.asset?.isMissing == true || - IsStale(record, out _) || - (record.meta.importStatus == (int)AssetImportStatus.Imported && !m_artifacts.TryGet( + if (record is null + || record.asset?.isMissing == true + || IsStale(record, out _) + || (record.meta.importStatus == (int)AssetImportStatus.Imported && !m_artifacts.TryGet( new AssetArtifactKey(record.meta.artifactKey), "asset-state", - out _))) - { + out _ + )) + ) { ImportLocked(relative); } } @@ -121,13 +121,17 @@ private void RescanLocked() continue; } - if (IOFile.Exists(GetSourcePath(record.relativePath)) || - Directory.Exists(GetSourcePath(record.relativePath))) + if (IOFile.Exists(GetSourcePath(record.relativePath)) + || Directory.Exists(GetSourcePath(record.relativePath)) + ) { continue; + } HandleDeletedLocked(record.relativePath); } if (releasedRetiredAssets || registriesChanged) + { RefreshLoadedAssetReferencesLocked(); + } CommitCatalogLocked(); EnsureReadOnlyImportsSucceededLocked(); m_importerRegistryVersion = m_importers.snapshotVersion; @@ -138,10 +142,11 @@ private void RescanLocked() private void ApplySourceChangesLocked(IReadOnlyList changes) { - if (changes.Any(change => - IsSampleChangePath(change.relativePath) || - IsSampleChangePath(change.oldRelativePath))) - { + if (changes.Any(change => ( + IsSampleChangePath(change.relativePath) + || IsSampleChangePath(change.oldRelativePath) + )) + ) { RescanLocked(); return; } @@ -153,11 +158,15 @@ private void ApplySourceChangesLocked(IReadOnlyList changes) string ownerPath = NormalizeRelativePath(change.relativePath[..^C_META_POSTFIX.Length]); AssetRecord? owner = FindRecordLocked(ownerPath); if (owner is not null && !owner.meta.isDirectory && IsStale(owner, out _)) + { ImportLocked(ownerPath); + } continue; } if (IsInternalGeneratedPath(change.relativePath)) + { continue; + } if (change.changeType.HasFlag(WatcherChangeTypes.Renamed)) { HandleRenameLocked(change.oldRelativePath, change.relativePath); @@ -171,7 +180,9 @@ private void ApplySourceChangesLocked(IReadOnlyList changes) ImportLocked(NormalizeRelativePath(change.relativePath)); } foreach ((string path, int matchCount) in ambiguousRenames) + { RecordAmbiguousRenameDiagnosticLocked(path, matchCount); + } } private void HandleRenameLocked( @@ -193,21 +204,23 @@ string newPath } string oldMeta = GetMetaPath(oldNormalized); string newMeta = GetMetaPath(newNormalized); - if (TryReadSourceMeta(newMeta, out AssetSourceMeta targetMeta) && - targetMeta.persistentId != record.persistentId) - { + if (TryReadSourceMeta(newMeta, out AssetSourceMeta targetMeta) + && targetMeta.persistentId != record.persistentId + ) { record.meta.importStatus = (int)AssetImportStatus.Conflict; record.meta.diagnostics = [ - $"Rename target '{newNormalized}' already owns persistent id " + - $"'{targetMeta.persistentId}'." + $"Rename target '{newNormalized}' already owns persistent id " + + $"'{targetMeta.persistentId}'." ]; CommitCatalogLocked(); return; } if (IOFile.Exists(oldMeta) && !IOFile.Exists(newMeta)) + { MoveGeneratedFile(oldMeta, newMeta); + } m_recordsByPath.Remove(oldNormalized); m_importGraph.RemoveNode(oldNormalized); record.relativePath = newNormalized; @@ -229,7 +242,8 @@ string newPath record.meta.sourceHash, ReadOnlyMemory.Empty, true, - replaced.contentVersion + 1); + replaced.contentVersion + 1 + ); m_runtimeOwner.Release(replaced); m_identities.Unregister(replaced); record.asset = null; @@ -241,22 +255,26 @@ string newPath record.meta.importStatus = (int)AssetImportStatus.Imported; record.meta.diagnostics = []; if (record.asset is not null) + { m_runtimeOwner.UpdateAssetPath(record.asset, AssetPath.Parse(newNormalized)); + } } m_recordsByPath[newNormalized] = record; // A renamed source may deliberately carry a different importer and its matching settings. // The source sidecar is authoritative; cached importer state must not relabel those bytes. if (ReadMetadata(newMeta) is null) + { WriteSourceMeta(record.meta); + } UpdateGraphsLocked(record); CommitCatalogLocked(); bool catalogChanged = false; bool stale = importer is not null && IsStale(record, out catalogChanged); - if (importer is not null && - (!string.Equals(importer.importerId, record.meta.importerId, StringComparison.Ordinal) || - stale)) - { + if (importer is not null + && (!string.Equals(importer.importerId, record.meta.importerId, StringComparison.Ordinal) + || stale) + ) { ImportLocked(newNormalized); } else if (catalogChanged) @@ -270,13 +288,16 @@ private void HandleDeletedLocked(string relativePath) string normalized = NormalizeRelativePath(relativePath); string prefix = normalized + "/"; AssetRecord[] records = m_recordsByPath.Values - .Where(record => - string.Equals(record.relativePath, normalized, StringComparison.OrdinalIgnoreCase) || - record.relativePath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + .Where(record => ( + string.Equals(record.relativePath, normalized, StringComparison.OrdinalIgnoreCase) + || record.relativePath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + )) .OrderByDescending(static record => record.relativePath.Length) .ToArray(); if (records.Length == 0) + { return; + } for (int i = 0; i < records.Length; i++) { @@ -287,7 +308,9 @@ private void HandleDeletedLocked(string relativePath) m_importGraph.RemoveNode(recordPath); if (record.persistentId == Guid.Empty) + { continue; + } record.meta.isTombstone = true; record.meta.importStatus = (int)AssetImportStatus.Missing; @@ -305,7 +328,8 @@ private void HandleDeletedLocked(string relativePath) record.meta.sourceHash, ReadOnlyMemory.Empty, true, - record.asset.contentVersion + 1); + record.asset.contentVersion + 1 + ); PublishReloaded(record.asset); } } @@ -317,16 +341,21 @@ private int TryAssociateUntrackedRenameLocked( string absoluteSourcePath ) { if (m_recordsByPath.ContainsKey(relativePath) || IOFile.Exists(GetMetaPath(relativePath))) + { return 0; + } string fingerprint = ComputeSha256Hex(IOFile.ReadAllBytes(absoluteSourcePath)); AssetRecord[] matches = m_recordsByPath.Values - .Where(record => - !record.meta.isDirectory && - !IOFile.Exists(GetSourcePath(record.relativePath)) && - string.Equals(record.meta.sourceHash, fingerprint, StringComparison.Ordinal)) + .Where(record => ( + !record.meta.isDirectory + && !IOFile.Exists(GetSourcePath(record.relativePath)) + && string.Equals(record.meta.sourceHash, fingerprint, StringComparison.Ordinal) + )) .ToArray(); if (matches.Length == 1) + { HandleRenameLocked(matches[0].relativePath, relativePath); + } return matches.Length; } @@ -336,10 +365,10 @@ private IReadOnlyDictionary AssociateUntrackedRenamesLocked(IReadOn for (int i = 0; i < changes.Count; i++) { AssetChangedEvent change = changes[i]; - if (change.changeType.HasFlag(WatcherChangeTypes.Deleted) || - change.changeType.HasFlag(WatcherChangeTypes.Renamed) || - IsInternalGeneratedPath(change.relativePath)) - { + if (change.changeType.HasFlag(WatcherChangeTypes.Deleted) + || change.changeType.HasFlag(WatcherChangeTypes.Renamed) + || IsInternalGeneratedPath(change.relativePath) + ) { continue; } @@ -349,7 +378,9 @@ private IReadOnlyDictionary AssociateUntrackedRenamesLocked(IReadOn { int matches = TryAssociateUntrackedRenameLocked(relativePath, absolutePath); if (matches > 1) + { ambiguous[relativePath] = matches; + } } } return ambiguous; @@ -361,9 +392,10 @@ string newPath ) { string oldPrefix = oldPath + "/"; AssetRecord[] records = m_recordsByPath.Values - .Where(record => - string.Equals(record.relativePath, oldPath, StringComparison.OrdinalIgnoreCase) || - record.relativePath.StartsWith(oldPrefix, StringComparison.OrdinalIgnoreCase)) + .Where(record => ( + string.Equals(record.relativePath, oldPath, StringComparison.OrdinalIgnoreCase) + || record.relativePath.StartsWith(oldPrefix, StringComparison.OrdinalIgnoreCase) + )) .OrderBy(static record => record.relativePath.Length) .ToArray(); if (records.Length == 0) @@ -376,14 +408,16 @@ string newPath string oldFolderMeta = GetMetaPath(oldPath); string newFolderMeta = GetMetaPath(newPath); if (IOFile.Exists(oldFolderMeta) && !IOFile.Exists(newFolderMeta)) + { MoveGeneratedFile(oldFolderMeta, newFolderMeta); + } for (int i = 0; i < records.Length; i++) { AssetRecord record = records[i]; string suffix = record.relativePath.Length == oldPath.Length - ? string.Empty - : record.relativePath[oldPath.Length..]; + ? string.Empty + : record.relativePath[oldPath.Length..]; string destination = newPath + suffix; m_recordsByPath.Remove(record.relativePath); m_importGraph.RemoveNode(record.relativePath); @@ -392,7 +426,9 @@ string newPath record.meta.importStatus = (int)AssetImportStatus.Imported; record.meta.diagnostics = []; if (record.asset is not null) + { m_runtimeOwner.UpdateAssetPath(record.asset, AssetPath.Parse(destination)); + } m_recordsByPath[destination] = record; UpdateGraphsLocked(record); } @@ -413,7 +449,9 @@ bool isDirectory for (int i = 0; i < segments.Length - (isDirectory ? 0 : 1); i++) { if (m_sourcePolicy.IsIgnored(segments[i], isDirectory: true)) + { return true; + } } return m_sourcePolicy.IsIgnored(localPath, isDirectory); } @@ -421,9 +459,10 @@ bool isDirectory private static bool IsSampleChangePath(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) + { return false; + } AssetPath path = AssetPath.Parse(relativePath); return AssetSample.IsRoot(path) || AssetSample.Contains(path, isDirectory: false); } - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs index 8d62ba4be..9ed8653d9 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -33,47 +32,61 @@ out bool catalogChanged catalogChanged = false; string sourcePath = GetSourcePath(record.relativePath); if (!IOFile.Exists(sourcePath)) + { return true; + } AssetImporter? importer = m_importers.FindById(record.meta.importerId); - if (importer is null || - !string.Equals( + if (importer is null + || !string.Equals( record.meta.importerImplementationFingerprint, GetImporterImplementationFingerprint(importer), - StringComparison.Ordinal)) - { + StringComparison.Ordinal + ) + ) { return true; } if (record.importerGeneration != m_importers.GetGeneration(record.meta.importerId)) + { return true; - if (record.meta.importStatus != (int)AssetImportStatus.Imported && - record.meta.importStatus != (int)AssetImportStatus.Failed) + } + if (record.meta.importStatus != (int)AssetImportStatus.Imported + && record.meta.importStatus != (int)AssetImportStatus.Failed + ) { return true; + } // A failed dependency can recover when another extension becomes available, even when // this importer's implementation and source bytes are unchanged. Retry once per catalog // generation; the transient observation deliberately does not survive a loader restart. if (record.meta.importStatus == (int)AssetImportStatus.Failed - && record.failedTypeGeneration != m_types.current.version) + && record.failedTypeGeneration != m_types.current.version + ) { return true; - if (record.meta.importStatus == (int)AssetImportStatus.Failed && - record.meta.diagnostics.Any(static diagnostic => - diagnostic.StartsWith("IOException:", StringComparison.Ordinal) || - diagnostic.StartsWith("UnauthorizedAccessException:", StringComparison.Ordinal))) - { + } + if (record.meta.importStatus == (int)AssetImportStatus.Failed + && record.meta.diagnostics.Any(static diagnostic => ( + diagnostic.StartsWith("IOException:", StringComparison.Ordinal) + || diagnostic.StartsWith("UnauthorizedAccessException:", StringComparison.Ordinal) + )) + ) { // File locks and access checks may clear without any source or importer change. return true; } if (AreImportSettingsStaleLocked(record, importer)) + { return true; + } if (!AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp sourceStamp)) + { return true; + } bool stampChanged = !SourceStampMatches(record.meta, sourceStamp); if (!GetMount(record.relativePath).isReadOnly || stampChanged) { if (!string.Equals( - record.meta.sourceHash, - ReadStableSourceHash(sourcePath, out sourceStamp), - StringComparison.Ordinal)) - { + record.meta.sourceHash, + ReadStableSourceHash(sourcePath, out sourceStamp), + StringComparison.Ordinal + )) { return true; } if (stampChanged) @@ -86,12 +99,11 @@ out bool catalogChanged { AssetImportDependencyData dependency = record.meta.importDependencies[i]; if (record.meta.importStatus == (int)AssetImportStatus.Failed - && dependency.fingerprint.StartsWith(C_REJECTED_SOURCE_REFERENCE, StringComparison.Ordinal)) - { + && dependency.fingerprint.StartsWith(C_REJECTED_SOURCE_REFERENCE, StringComparison.Ordinal) + ) { try { - ValidateSourceReferenceLocked(record.relativePath, - NormalizeRelativePath(dependency.key)); + ValidateSourceReferenceLocked(record.relativePath, NormalizeRelativePath(dependency.key)); return true; } catch (Exception exception) when (exception is InvalidOperationException or ArgumentException) @@ -99,18 +111,13 @@ out bool catalogChanged continue; } } - string fingerprint = ComputeImportDependencyFingerprintLocked( - ref dependency, - out bool dependencyChanged); + string fingerprint = ComputeImportDependencyFingerprintLocked(ref dependency, out bool dependencyChanged); if (dependencyChanged) { record.meta.importDependencies[i] = dependency; catalogChanged = true; } - if (!string.Equals( - dependency.fingerprint, - fingerprint, - StringComparison.Ordinal)) + if (!string.Equals(dependency.fingerprint, fingerprint, StringComparison.Ordinal)) { return true; } @@ -121,7 +128,9 @@ out bool catalogChanged private string NormalizeRelativePath(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) + { throw new ArgumentException("An asset-relative path is required.", nameof(relativePath)); + } AssetPath path = AssetPath.Parse(relativePath); _ = GetMount(path); return path.ToString(); @@ -130,7 +139,9 @@ private string NormalizeRelativePath(string relativePath) private string NormalizeAssetPath(AssetPath path) { if (!path.isValid || string.IsNullOrWhiteSpace(path.localPath)) + { throw new ArgumentException("An isolated asset path is required.", nameof(path)); + } _ = GetMount(path); return path.ToString(); } @@ -139,15 +150,14 @@ private void EnsureDirectoryMetadataLocked() { foreach (AssetSourceMount mount in m_mounts.Values) { - foreach (string directoryPath in Directory.GetDirectories( - mount.rootPath, - "*", - SearchOption.AllDirectories)) + foreach (string directoryPath in Directory.GetDirectories(mount.rootPath, "*", SearchOption.AllDirectories)) { string localPath = Path.GetRelativePath(mount.rootPath, directoryPath).Replace('\\', '/'); string relativePath = new AssetPath(mount.id, localPath).ToString(); if (IsSourceIgnored(new AssetPath(mount.id, localPath), isDirectory: true)) + { continue; + } string metaPath = GetMetaPath(relativePath); AssetSourceMeta sourceMeta; if (!TryReadSourceMeta(metaPath, out sourceMeta!)) @@ -155,7 +165,8 @@ private void EnsureDirectoryMetadataLocked() if (mount.isReadOnly) { throw new InvalidDataException( - $"Read-only source directory '{relativePath}' requires a valid '{C_META_POSTFIX}' sidecar."); + $"Read-only source directory '{relativePath}' requires a valid '{C_META_POSTFIX}' sidecar." + ); } sourceMeta = new AssetSourceMeta { @@ -166,14 +177,15 @@ private void EnsureDirectoryMetadataLocked() } AssetRecord? record = FindRecordByIdWithoutLoading(sourceMeta.persistentId); - if (record is not null && - !string.Equals(record.relativePath, relativePath, StringComparison.OrdinalIgnoreCase) && - Directory.Exists(GetSourcePath(record.relativePath))) - { + if (record is not null + && !string.Equals(record.relativePath, relativePath, StringComparison.OrdinalIgnoreCase) + && Directory.Exists(GetSourcePath(record.relativePath)) + ) { if (mount.isReadOnly) { throw new InvalidDataException( - $"Read-only source directory '{relativePath}' duplicates persistent ID '{sourceMeta.persistentId}'."); + $"Read-only source directory '{relativePath}' duplicates persistent ID '{sourceMeta.persistentId}'." + ); } sourceMeta.persistentId = Guid.NewGuid(); WriteAtomic(metaPath, m_serialization.Serialize(sourceMeta)); @@ -198,13 +210,14 @@ private void WriteSourceMeta(AssetMeta meta) string metaPath = GetMetaPath(meta.relativePath); byte[]? existingBytes = ReadMetadata(metaPath); AssetSourceMeta? existing = existingBytes is null - ? null : m_serialization.Deserialize(existingBytes); + ? null + : m_serialization.Deserialize(existingBytes); var sourceMeta = new AssetSourceMeta { persistentId = meta.persistentId, sourceKind = meta.isDirectory - ? (int)AssetSourceKind.Directory - : (int)AssetSourceKind.File, + ? (int)AssetSourceKind.Directory + : (int)AssetSourceKind.File, importerId = meta.importerId, importerSettingsBytes = existing?.importerSettingsBytes ?? [] }; @@ -214,7 +227,8 @@ private void WriteSourceMeta(AssetMeta meta) if (!IOFile.Exists(metaPath) || !IOFile.ReadAllBytes(metaPath).AsSpan().SequenceEqual(data)) { throw new InvalidDataException( - $"Read-only source metadata for '{meta.relativePath}' is missing or inconsistent."); + $"Read-only source metadata for '{meta.relativePath}' is missing or inconsistent." + ); } return; } @@ -228,7 +242,9 @@ out AssetSourceMeta sourceMeta sourceMeta = null!; byte[]? bytes = ReadMetadata(metaPath); if (bytes is null) + { return false; + } try { sourceMeta = m_serialization.Deserialize(bytes); @@ -251,16 +267,18 @@ private string CreateImportFingerprint(AssetMeta meta) meta.importerSettingsHash }; foreach (AssetDependencyData dependency in meta.runtimeDependencies - .OrderBy(static value => value.persistentId)) - { + .OrderBy(static value => value.persistentId) + ) { parts.Add(dependency.persistentId.ToString("D")); if (m_recordsById.TryGetValue(dependency.persistentId, out AssetRecord? record)) + { parts.Add(record.meta.artifactKey); + } } foreach (AssetImportDependencyData dependency in meta.importDependencies - .OrderBy(static value => value.kind) - .ThenBy(static value => value.key, StringComparer.Ordinal)) - { + .OrderBy(static value => value.kind) + .ThenBy(static value => value.key, StringComparer.Ordinal) + ) { parts.Add(dependency.kind.ToString()); parts.Add(dependency.key); parts.Add(dependency.fingerprint); @@ -269,8 +287,8 @@ private string CreateImportFingerprint(AssetMeta meta) } private static string GetImporterImplementationFingerprint(AssetImporter importer) - => $"{importer.GetType().Assembly.ManifestModule.ModuleVersionId:D}:" + - $"{importer.GetType().FullName}:{importer.deploymentScope}"; + => $"{importer.GetType().Assembly.ManifestModule.ModuleVersionId:D}:" + + $"{importer.GetType().FullName}:{importer.deploymentScope}"; private string CreateBuildFingerprint( AssetBuildProcessor processor, @@ -307,8 +325,8 @@ private string GetSourcePath(string relativePath) private AssetSourceMount GetMount(AssetPath path) => m_mounts.TryGetValue(path.source, out AssetSourceMount? mount) - ? mount - : throw new ArgumentException($"Asset source mount '{path.source}' is not active.", nameof(path)); + ? mount + : throw new ArgumentException($"Asset source mount '{path.source}' is not active.", nameof(path)); private string GetMetaPath(string relativePath) => GetSourcePath(relativePath) + C_META_POSTFIX; @@ -320,12 +338,14 @@ out AssetSourceFileStamp sourceStamp for (int attempt = 0; attempt < C_MAX_ATTEMPTS; attempt++) { if (!AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp before)) + { throw new FileNotFoundException("Asset source is unavailable.", sourcePath); + } using FileStream source = IOFile.OpenRead(sourcePath); string hash = Convert.ToHexString(SHA256.HashData(source)); if (AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp after) - && before == after && source.Length == after.length) - { + && before == after && source.Length == after.length + ) { sourceStamp = after; return hash; } @@ -341,12 +361,14 @@ out AssetSourceFileStamp sourceStamp for (int attempt = 0; attempt < C_MAX_ATTEMPTS; attempt++) { if (!AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp before)) + { throw new FileNotFoundException("Asset source is unavailable.", sourcePath); + } byte[] bytes = IOFile.ReadAllBytes(sourcePath); - if (AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp after) && - before == after && - bytes.LongLength == after.length) - { + if (AssetSourceFileStamp.TryCapture(sourcePath, out AssetSourceFileStamp after) + && before == after + && bytes.LongLength == after.length + ) { sourceStamp = after; return bytes; } @@ -358,21 +380,19 @@ out AssetSourceFileStamp sourceStamp private static bool SourceStampMatches( AssetMeta meta, AssetSourceFileStamp sourceStamp - ) - => sourceStamp.isValid && - meta.sourceLength == sourceStamp.length && - meta.sourceLastWriteUtcTicks == sourceStamp.lastWriteUtcTicks && - meta.sourceCreationTimeUtcTicks == sourceStamp.creationTimeUtcTicks; + ) => sourceStamp.isValid + && meta.sourceLength == sourceStamp.length + && meta.sourceLastWriteUtcTicks == sourceStamp.lastWriteUtcTicks + && meta.sourceCreationTimeUtcTicks == sourceStamp.creationTimeUtcTicks; private static bool SourceStampMatches( AssetImportDependencyData dependency, AssetSourceFileStamp sourceStamp - ) - => dependency.sourceStampValid && - sourceStamp.isValid && - dependency.sourceLength == sourceStamp.length && - dependency.sourceLastWriteUtcTicks == sourceStamp.lastWriteUtcTicks && - dependency.sourceCreationTimeUtcTicks == sourceStamp.creationTimeUtcTicks; + ) => dependency.sourceStampValid + && sourceStamp.isValid + && dependency.sourceLength == sourceStamp.length + && dependency.sourceLastWriteUtcTicks == sourceStamp.lastWriteUtcTicks + && dependency.sourceCreationTimeUtcTicks == sourceStamp.creationTimeUtcTicks; private static void ApplySourceStamp( AssetMeta meta, @@ -407,8 +427,8 @@ AssetSourceFileStamp sourceStamp private byte[]? ReadMetadata(string path) => m_sourceMetadataStage is not null - ? m_sourceMetadataStage.Read(path) - : IOFile.Exists(path) ? IOFile.ReadAllBytes(path) : null; + ? m_sourceMetadataStage.Read(path) + : IOFile.Exists(path) ? IOFile.ReadAllBytes(path) : null; private bool IsStagedMetadata(string path) => m_sourceMetadataStage is not null && path.EndsWith(C_META_POSTFIX, StringComparison.Ordinal); @@ -418,9 +438,13 @@ private void WriteAtomic( byte[] bytes ) { if (IsStagedMetadata(targetPath)) + { m_sourceMetadataStage!.Write(targetPath, bytes); + } else + { AtomicFile.WriteAllBytes(targetPath, bytes); + } } private FileSnapshot CaptureFile(string path) @@ -450,18 +474,26 @@ string targetPath { byte[]? bytes = ReadMetadata(sourcePath); if (bytes is null) + { return; + } if (ReadMetadata(targetPath) is not null) + { throw new IOException($"Generated metadata target '{targetPath}' already exists."); + } m_sourceMetadataStage!.Write(targetPath, bytes); m_sourceMetadataStage.Write(sourcePath, null); return; } if (!IOFile.Exists(sourcePath)) + { return; + } Directory.CreateDirectory(Path.GetDirectoryName(targetPath)!); if (IOFile.Exists(targetPath)) + { throw new IOException($"Generated metadata target '{targetPath}' already exists."); + } IOFile.Move(sourcePath, targetPath); } @@ -473,10 +505,13 @@ private void DeleteIfExists(string path) return; } if (IOFile.Exists(path)) + { IOFile.Delete(path); + } } - private static AssetDependencyData ToData(AssetDependency dependency) => new() + private static AssetDependencyData ToData(AssetDependency dependency) + => new() { persistentId = dependency.persistentId, stableTypeId = dependency.type.stableId, @@ -487,5 +522,4 @@ private readonly record struct FileSnapshot( bool existed, byte[] bytes ); - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs index 5b385cbc4..5b32e68fc 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs @@ -7,18 +7,17 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.References; using Inno.Core.Execution; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Extensibility.Types; +using Inno.References; using IOFile = System.IO.File; @@ -40,8 +39,10 @@ public sealed partial class AssetLoader : IDisposable, IAssetReferenceResolver, private readonly ArtifactRetention m_artifactRetention = new(); private readonly SemaphoreSlim m_operationGate = new(1, 1); private readonly object m_asyncSync = new(); + private readonly Dictionary> m_inFlightPathLoads = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary> m_inFlightIdLoads = []; private readonly AssetImporterRegistry m_importers; private readonly AssetBuildProcessorRegistry m_buildProcessors; @@ -54,8 +55,10 @@ public sealed partial class AssetLoader : IDisposable, IAssetReferenceResolver, private readonly ConditionalWeakTable m_dependencyRetention = new(); private readonly HashSet m_activeImports = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary m_pendingImportIds = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary m_unavailableImports = new(StringComparer.OrdinalIgnoreCase); + private readonly AssetArtifactStore m_artifacts; private readonly AssetCatalogStore m_catalog; private readonly AssetDiagnosticPublisher m_diagnostics; @@ -107,7 +110,9 @@ TValue target ObjectDisposedException.ThrowIf(m_disposed || m_disposeRequested, this); ArgumentNullException.ThrowIfNull(target); if (m_types.GetTypeRef(target.GetType()).stableId != stableTypeId) + { throw new InvalidOperationException("The asset property payload has an incompatible stable type identity."); + } m_serialization.Decode(propertyData, reader => { reader.RestoreProperties(target); @@ -151,18 +156,16 @@ public AssetLoader( string assetRoot, string libraryRoot, AssetSourcePolicy? sourcePolicy = null - ) - : this( - types, - serialization, - identities, - diagnostics, - logs, - [new AssetSourceMount(AssetSourceId.project, assetRoot, isReadOnly: false)], - libraryRoot, - sourcePolicy) - { - } + ) : this( + types, + serialization, + identities, + diagnostics, + logs, + [new AssetSourceMount(AssetSourceId.project, assetRoot, isReadOnly: false)], + libraryRoot, + sourcePolicy + ) {} /// /// Creates an asset loader over one project source and zero or more isolated sources. @@ -204,20 +207,18 @@ public AssetLoader( string libraryRoot, AssetSourcePolicy? sourcePolicy = null, bool runtimeArtifactsOnly = false - ) - : this( - types, - serialization, - identities, - diagnostics, - logs, - mounts, - libraryRoot, - libraryRoot, - sourcePolicy, - runtimeArtifactsOnly) - { - } + ) : this( + types, + serialization, + identities, + diagnostics, + logs, + mounts, + libraryRoot, + libraryRoot, + sourcePolicy, + runtimeArtifactsOnly + ) {} internal AssetLoader( TypeCatalog types, @@ -239,22 +240,31 @@ internal AssetLoader( ArgumentNullException.ThrowIfNull(logs); ArgumentNullException.ThrowIfNull(mounts); if (mounts.Count == 0) + { throw new ArgumentException("At least one asset source mount is required.", nameof(mounts)); + } if (string.IsNullOrWhiteSpace(libraryRoot)) + { throw new ArgumentException("Library root is required.", nameof(libraryRoot)); + } if (string.IsNullOrWhiteSpace(catalogLibraryRoot)) + { throw new ArgumentException("Catalog Library root is required.", nameof(catalogLibraryRoot)); + } Dictionary byId = mounts.ToDictionary(static mount => mount.id); if (byId.Count != mounts.Count) + { throw new ArgumentException("Asset source mount IDs must be unique.", nameof(mounts)); + } if (!byId.TryGetValue(AssetSourceId.project, out AssetSourceMount? project) - || project.isReadOnly && !runtimeArtifactsOnly) - { + || project.isReadOnly && !runtimeArtifactsOnly + ) { throw new ArgumentException( runtimeArtifactsOnly - ? "A project asset source mount is required." - : "A writable project asset source mount is required.", - nameof(mounts)); + ? "A project asset source mount is required." + : "A writable project asset source mount is required.", + nameof(mounts) + ); } m_types = types; @@ -275,8 +285,7 @@ internal AssetLoader( { if (mount.isReadOnly && !Directory.Exists(mount.rootPath)) { - throw new DirectoryNotFoundException( - $"Read-only asset source root '{mount.rootPath}' does not exist."); + throw new DirectoryNotFoundException($"Read-only asset source root '{mount.rootPath}' does not exist."); } Directory.CreateDirectory(mount.rootPath); @@ -307,16 +316,19 @@ internal AssetLoader( /// public event Action? AssetReloaded; - internal void DeferUnavailableExtensions() => Execute(() => - { - m_deferUnavailableExtensions = true; - }); + internal void DeferUnavailableExtensions() + => Execute(() => + { + m_deferUnavailableExtensions = true; + }); internal void CompleteExtensionDiscovery() => Execute(() => { if (!m_deferUnavailableExtensions) + { return; + } m_deferUnavailableExtensions = false; m_unavailableImports.Clear(); RescanLocked(); @@ -327,13 +339,15 @@ internal void ActivateExtensionDiscovery() // Assembly discovery may publish built-in catalogs before the initial script compilation. // Only the composition host can close that initial discovery boundary. if (!m_preserveInitialExtensionDiscovery) + { CompleteExtensionDiscovery(); + } } /// /// Waits for pending import and build work. /// - public void WaitForIdle() => Execute(static () => { }); + public void WaitForIdle() => Execute(static () => {}); /// /// Refreshes extension registries and reimports affected sources when their snapshot changed. @@ -347,9 +361,11 @@ public bool RefreshRegistries() { long version = m_importers.snapshotVersion; long buildVersion = m_buildProcessors.snapshotVersion; - if (version == m_importerRegistryVersion && - buildVersion == m_buildProcessorRegistryVersion) + if (version == m_importerRegistryVersion + && buildVersion == m_buildProcessorRegistryVersion + ) { return false; + } RescanLocked(); return true; }); @@ -359,7 +375,9 @@ private void PublishReloaded(AssetObject asset) { Action? handlers = AssetReloaded; if (handlers is null) + { return; + } foreach (Delegate handler in handlers.GetInvocationList()) { try @@ -379,7 +397,7 @@ Guid persistentId ) { AssetDependencyData data = meta.runtimeDependencies.FirstOrDefault(value => value.persistentId == persistentId); return data.persistentId == Guid.Empty - ? default - : new AssetDependency(data.persistentId, new TypeRef(data.stableTypeId), data.lastKnownPath); + ? default + : new AssetDependency(data.persistentId, new TypeRef(data.stableTypeId), data.lastKnownPath); } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSerializationServices.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSerializationServices.cs index cb4c4ecf8..5eaaacd52 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSerializationServices.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSerializationServices.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; @@ -18,15 +17,18 @@ public sealed class AssetSerializationServices internal IAssetReferenceResolver references => m_references - ?? throw new InvalidOperationException( - "Asset reference resolution is unavailable outside an import transaction."); + ?? throw new InvalidOperationException( + "Asset reference resolution is unavailable outside an import transaction." + ); internal SerializationRegistry serialization => m_serialization; internal TypeCatalog types => m_types; - internal SerializationContext context => m_references is null - ? SerializationContext.empty : AssetSerializationContext.Create(m_references); + internal SerializationContext context + => m_references is null + ? SerializationContext.empty + : AssetSerializationContext.Create(m_references); internal AssetSerializationServices( TypeCatalog types, @@ -66,15 +68,20 @@ internal AssetSerializationServices( /// /// Frozen native properties with exact stable type identity and collected direct dependencies. /// - public AssetPropertySnapshot CaptureProperties(TValue value) where TValue : class, ISerializable + public AssetPropertySnapshot CaptureProperties(TValue value) + where TValue : class, ISerializable { ArgumentNullException.ThrowIfNull(value); using IDisposable operation = m_types.AcquireOperation("Capture asset properties"); var dependencies = new AssetDependencyCollection(); byte[] data = m_serialization.Encode(writer => writer.WriteProperties(value), context.With(dependencies)); if (m_dependencySink is not null) + { foreach (AssetDependency dependency in dependencies.dependencies) + { m_dependencySink(dependency); + } + } return new(m_types.GetTypeRef(value.GetType()).stableId, data, dependencies.dependencies); } @@ -103,7 +110,9 @@ public byte[] Serialize(TValue value) if (m_dependencySink is not null) { foreach (AssetDependency dependency in dependencies.dependencies) + { m_dependencySink(dependency); + } } return result; } @@ -127,8 +136,8 @@ public TValue Deserialize(ReadOnlySpan bytes) where TValue : class, ISerializable { SerializationContext context = m_references is null - ? SerializationContext.empty - : AssetSerializationContext.Create(m_references); + ? SerializationContext.empty + : AssetSerializationContext.Create(m_references); return m_serialization.Deserialize(bytes, context); } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSourceMetadataStage.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSourceMetadataStage.cs index 7e83c7221..7304f4b24 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSourceMetadataStage.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetSourceMetadataStage.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using Inno.Core.IO; + using IOFile = System.IO.File; namespace Inno.Assets.Pipeline; @@ -24,7 +25,9 @@ internal void Commit(Action publishCatalog) foreach (Entry entry in snapshot) { if (!Equal(entry.original, ReadPhysical(entry.path))) + { throw new IOException($"Asset source metadata '{entry.path}' changed while its candidate was being prepared."); + } } var applied = new List(); try @@ -32,7 +35,9 @@ internal void Commit(Action publishCatalog) foreach (Entry entry in snapshot) { if (Equal(entry.original, entry.value)) + { continue; + } applied.Add(entry); WritePhysical(entry.path, entry.value); } @@ -54,7 +59,9 @@ internal void Commit(Action publishCatalog) } } if (failures.Count > 1) + { throw new AggregateException("Asset catalog publication and source metadata compensation failed.", failures); + } throw; } } @@ -73,8 +80,7 @@ private Entry GetEntry(string path) private static bool Equal( byte[]? left, byte[]? right - ) - => left is null ? right is null : right is not null && left.AsSpan().SequenceEqual(right); + ) => left is null ? right is null : right is not null && left.AsSpan().SequenceEqual(right); private static byte[]? ReadPhysical(string path) => IOFile.Exists(path) ? IOFile.ReadAllBytes(path) : null; @@ -83,9 +89,13 @@ private static void WritePhysical( byte[]? value ) { if (value is not null) + { AtomicFile.WriteAllBytes(path, value); + } else if (IOFile.Exists(path)) + { IOFile.Delete(path); + } } private sealed class Entry( diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildContext.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildContext.cs index 5f06fa501..fc7de58b5 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildContext.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildContext.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -11,7 +10,8 @@ namespace Inno.Assets.Pipeline; /// /// The build definition asset type. /// -public sealed class AssetBuildContext where TDefinition : AssetObject +public sealed class AssetBuildContext + where TDefinition : AssetObject { /// /// Creates a build context. diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs index 9fffd0928..ebe685e64 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -41,9 +40,11 @@ public abstract class AssetBuildProcessor /// /// Gets the stable processor identifier used by build cache keys. /// - public string processorId => m_processorId - ?? throw new InvalidOperationException( - $"Asset build processor '{GetType().FullName}' has not been bound to discovery metadata."); + public string processorId + => m_processorId + ?? throw new InvalidOperationException( + $"Asset build processor '{GetType().FullName}' has not been bound to discovery metadata." + ); /// /// Gets the definition type accepted by this processor. @@ -63,7 +64,8 @@ internal void BindProcessorId(string id) if (m_processorId is not null && !string.Equals(m_processorId, id, StringComparison.Ordinal)) { throw new InvalidOperationException( - $"Asset build processor '{GetType().FullName}' cannot be bound to more than one protocol ID."); + $"Asset build processor '{GetType().FullName}' cannot be bound to more than one protocol ID." + ); } m_processorId = id; } @@ -114,7 +116,8 @@ CancellationToken cancellationToken { throw new ArgumentException( $"Build definition must be assignable to '{typeof(TDefinition).FullName}'.", - nameof(definition)); + nameof(definition) + ); } return BuildAsync(new AssetBuildContext(typed, inputs), output, cancellationToken); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorRegistry.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorRegistry.cs index 96332757e..7bf360367 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorRegistry.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorRegistry.cs @@ -3,13 +3,11 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Inno.Extensibility.Types; namespace Inno.Assets.Pipeline; -internal sealed class AssetBuildProcessorRegistry - : TypeRegistry +internal sealed class AssetBuildProcessorRegistry : TypeRegistry { private readonly TypeCatalog m_types; @@ -50,7 +48,8 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (type.IsAbstract || !typeof(AssetBuildProcessor).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Asset build processor metadata on '{type.FullName}' requires a concrete {nameof(AssetBuildProcessor)} subtype."); + $"Asset build processor metadata on '{type.FullName}' requires a concrete {nameof(AssetBuildProcessor)} subtype." + ); } return (type, type.GetCustomAttribute(inherit: false)!.id); }).ToArray(); @@ -58,7 +57,9 @@ protected override Snapshot Build(TypeCacheSnapshot types) .GroupBy(static registration => registration.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicateId is not null) + { throw new InvalidOperationException($"Asset build processor ID '{duplicateId}' is registered more than once."); + } var processors = new Dictionary(); foreach ((Type type, string processorId) in registrations) @@ -68,7 +69,8 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (!processors.TryAdd(processor.definitionType, processor)) { throw new InvalidOperationException( - $"Asset build definition '{processor.definitionType.FullName}' has multiple processors."); + $"Asset build definition '{processor.definitionType.FullName}' has multiple processors." + ); } } return new Snapshot(processors.ToFrozenDictionary()); diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs index 0b54eec6e..e96806e25 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.IO; using Inno.Core.Serialization; @@ -46,13 +45,17 @@ internal AssetMeta[] Load() { string path = IOFile.Exists(m_journalPath) ? m_journalPath : m_snapshotPath; if (!IOFile.Exists(path)) + { return []; + } try { AssetCatalogSnapshot snapshot = Deserialize(IOFile.ReadAllBytes(path)); m_revision = snapshot.revision; if (string.Equals(path, m_journalPath, StringComparison.Ordinal)) + { Commit(DeserializeEntries(snapshot.entries)); + } return DeserializeEntries(snapshot.entries); } catch @@ -72,7 +75,9 @@ internal void Commit(AssetMeta[] entries) AtomicFile.WriteAllBytes(m_journalPath, bytes); AtomicFile.WriteAllBytes(m_snapshotPath, bytes); if (IOFile.Exists(m_journalPath)) + { IOFile.Delete(m_journalPath); + } } internal void CopyLatestTo(string destinationLibraryRoot) @@ -80,12 +85,12 @@ internal void CopyLatestTo(string destinationLibraryRoot) ArgumentException.ThrowIfNullOrWhiteSpace(destinationLibraryRoot); string? sourcePath = LatestPathOrNull(); if (sourcePath is null) + { return; + } string destinationRoot = GetDatabaseRoot(destinationLibraryRoot); Directory.CreateDirectory(destinationRoot); - AtomicFile.WriteAllBytes( - Path.Combine(destinationRoot, "Catalog.snapshot"), - IOFile.ReadAllBytes(sourcePath)); + AtomicFile.WriteAllBytes(Path.Combine(destinationRoot, "Catalog.snapshot"), IOFile.ReadAllBytes(sourcePath)); } internal void PromoteTo(string destinationLibraryRoot) @@ -102,9 +107,13 @@ internal void PromoteTo(string destinationLibraryRoot) try { if (candidate is null) + { IOFile.Delete(destinationSnapshot); + } else + { AtomicFile.WriteAllBytes(destinationSnapshot, candidate); + } snapshotChanged = true; IOFile.Delete(destinationJournal); } @@ -115,9 +124,13 @@ internal void PromoteTo(string destinationLibraryRoot) try { if (previous is null) + { IOFile.Delete(destinationSnapshot); + } else + { AtomicFile.WriteAllBytes(destinationSnapshot, previous); + } } catch (Exception rollback) { @@ -145,7 +158,9 @@ private void Bind(string libraryRoot) private string? LatestPathOrNull() { if (IOFile.Exists(m_journalPath)) + { return m_journalPath; + } return IOFile.Exists(m_snapshotPath) ? m_snapshotPath : null; } @@ -155,7 +170,9 @@ private byte[][] SerializeEntries(AssetMeta[] entries) { var result = new byte[entries.Length][]; for (int i = 0; i < entries.Length; i++) + { result[i] = Serialize(entries[i]); + } return result; } @@ -163,19 +180,21 @@ private AssetMeta[] DeserializeEntries(byte[][] entries) { var result = new AssetMeta[entries.Length]; for (int i = 0; i < entries.Length; i++) + { result[i] = Deserialize(entries[i]); + } return result; } private byte[] Serialize(T value) where T : class, ISerializable - => m_serializationGeneration is null - ? m_serialization!.Serialize(value) - : m_serializationGeneration.Serialize(value); + => m_serializationGeneration is null + ? m_serialization!.Serialize(value) + : m_serializationGeneration.Serialize(value); private T Deserialize(ReadOnlySpan bytes) where T : class, ISerializable - => m_serializationGeneration is null - ? m_serialization!.Deserialize(bytes) - : m_serializationGeneration.Deserialize(bytes); + => m_serializationGeneration is null + ? m_serialization!.Deserialize(bytes) + : m_serializationGeneration.Deserialize(bytes); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs index d5a030391..1103904ee 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs @@ -35,10 +35,7 @@ out AssetSourceFileStamp stamp return false; } - stamp = new AssetSourceFileStamp( - info.Length, - info.LastWriteTimeUtc.Ticks, - info.CreationTimeUtc.Ticks); + stamp = new AssetSourceFileStamp(info.Length, info.LastWriteTimeUtc.Ticks, info.CreationTimeUtc.Ticks); return true; } catch (IOException) @@ -63,10 +60,10 @@ out AssetSourceFileStamp stamp /// when the requested condition is satisfied; otherwise, . /// public bool Equals(AssetSourceFileStamp other) - => isValid == other.isValid && - length == other.length && - lastWriteUtcTicks == other.lastWriteUtcTicks && - creationTimeUtcTicks == other.creationTimeUtcTicks; + => isValid == other.isValid + && length == other.length + && lastWriteUtcTicks == other.lastWriteUtcTicks + && creationTimeUtcTicks == other.creationTimeUtcTicks; /// /// Determines whether this value and the supplied value represent the same logical state. diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs index 02c1c7f2f..cc4d79df3 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; using Inno.Core.Serialization; diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Diagnostics/AssetDiagnosticPublisher.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Diagnostics/AssetDiagnosticPublisher.cs index 8844dc72e..3ec372c64 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Diagnostics/AssetDiagnosticPublisher.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Diagnostics/AssetDiagnosticPublisher.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; - using Inno.Assets; using Inno.Core.Diagnostics; @@ -38,26 +37,30 @@ internal void SynchronizeImports(IReadOnlyList entries) { AssetMeta entry = entries[i]; if (entry.persistentId == Guid.Empty || entry.isDirectory) + { continue; + } if (entry.importStatus != (int)AssetImportStatus.Missing) + { ResolveReference(entry.persistentId); + } Diagnostic[] diagnostics = CreateImportDiagnostics(entry); if (diagnostics.Length == 0) + { continue; + } currentIds.Add(entry.persistentId); string state = CreateState(entry, diagnostics); - if (m_importStates.TryGetValue(entry.persistentId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_importStates.TryGetValue(entry.persistentId, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { continue; } - Set( - CreateSource(C_IMPORT_GROUP, entry.persistentId, entry.relativePath), - diagnostics); + Set(CreateSource(C_IMPORT_GROUP, entry.persistentId, entry.relativePath), diagnostics); m_importStates[entry.persistentId] = state; } @@ -78,7 +81,9 @@ IReadOnlyList messages ) { ArgumentNullException.ThrowIfNull(messages); if (targetId == Guid.Empty) + { return; + } if (messages.Count == 0) { ResolveBuild(targetId); @@ -96,9 +101,9 @@ IReadOnlyList messages } string state = string.Join('\n', diagnostics.Select(static diagnostic => diagnostic.message)); - if (m_buildStates.TryGetValue(targetId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_buildStates.TryGetValue(targetId, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return; } Set(CreateSource(C_BUILD_GROUP, targetId, displayName), diagnostics); @@ -112,16 +117,16 @@ Exception exception ) { ArgumentNullException.ThrowIfNull(exception); if (targetId == Guid.Empty) + { return; + } string state = exception.ToString(); - if (m_buildStates.TryGetValue(targetId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_buildStates.TryGetValue(targetId, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return; } - Set( - CreateSource(C_BUILD_GROUP, targetId, displayName), - [Diagnostic.Error("ASSET-BUILD", exception.Message)]); + Set(CreateSource(C_BUILD_GROUP, targetId, displayName), [Diagnostic.Error("ASSET-BUILD", exception.Message)]); m_buildStates[targetId] = state; } @@ -130,10 +135,10 @@ internal bool PublishCatalogFailure(Exception exception) ArgumentNullException.ThrowIfNull(exception); string state = exception.ToString(); if (string.Equals(m_catalogState, state, StringComparison.Ordinal)) + { return false; - Set( - CreateSource(C_CATALOG_GROUP), - [Diagnostic.Error("ASSET-CATALOG", exception.Message)]); + } + Set(CreateSource(C_CATALOG_GROUP), [Diagnostic.Error("ASSET-CATALOG", exception.Message)]); m_catalogState = state; return true; } @@ -144,29 +149,35 @@ internal void PublishMissingReference( Type expectedType ) { if (targetId == Guid.Empty) + { return; + } ArgumentNullException.ThrowIfNull(expectedType); string resolvedDisplayName = string.IsNullOrWhiteSpace(displayName) - ? targetId.ToString() - : displayName; + ? targetId.ToString() + : displayName; string state = $"{resolvedDisplayName}:{expectedType.FullName}"; - if (m_referenceStates.TryGetValue(targetId, out string? previous) && - string.Equals(previous, state, StringComparison.Ordinal)) - { + if (m_referenceStates.TryGetValue(targetId, out string? previous) + && string.Equals(previous, state, StringComparison.Ordinal) + ) { return; } Set( CreateSource(C_REFERENCE_GROUP, targetId, resolvedDisplayName), [Diagnostic.Warning( "ASSET-REFERENCE", - $"Asset '{resolvedDisplayName}' required as '{expectedType.FullName}' is missing.")]); + $"Asset '{resolvedDisplayName}' required as '{expectedType.FullName}' is missing." + )] + ); m_referenceStates[targetId] = state; } internal void ResolveCatalog() { if (string.IsNullOrEmpty(m_catalogState)) + { return; + } Clear(CreateSource(C_CATALOG_GROUP)); m_catalogState = string.Empty; } @@ -187,17 +198,23 @@ public void Dispose() internal void SetActive(bool active) { if (m_active == active) + { return; + } m_active = active; if (active) { foreach (Report report in m_reports.Values) + { Publish(report); + } } else { foreach (DiagnosticReporter reporter in m_reporters.Values) + { reporter.Dispose(); + } m_reporters.Clear(); } } @@ -207,30 +224,43 @@ private void Set( IReadOnlyList diagnostics ) { if (m_reporters.Remove(source.id, out DiagnosticReporter? previous)) + { previous.Dispose(); + } var report = new Report(source, diagnostics.ToArray()); m_reports[source.id] = report; if (m_active) + { Publish(report); + } } private void Clear(DiagnosticSource source) { m_reports.Remove(source.id); if (m_reporters.Remove(source.id, out DiagnosticReporter? reporter)) + { reporter.Dispose(); + } } private void Publish(Report report) { DiagnosticReporter reporter = m_diagnostics.CreateReporter(report.source); m_reporters.Add(report.source.id, reporter); - reporter.Replace(report.diagnostics.Select(static ( - issue, - index - ) => new Diagnostic( - issue.code, issue.message, issue.severity, index.ToString(CultureInfo.InvariantCulture), - issue.objectId, issue.location))); + reporter.Replace( + report.diagnostics.Select(static ( + issue, + index + ) => new Diagnostic( + issue.code, + issue.message, + issue.severity, + index.ToString(CultureInfo.InvariantCulture), + issue.objectId, + issue.location + )) + ); } private sealed record Report( @@ -241,14 +271,18 @@ Diagnostic[] diagnostics private void ResolveBuild(Guid targetId) { if (!m_buildStates.Remove(targetId)) + { return; + } Clear(CreateSource(C_BUILD_GROUP, targetId)); } private void ResolveReference(Guid targetId) { if (!m_referenceStates.Remove(targetId)) + { return; + } Clear(CreateSource(C_REFERENCE_GROUP, targetId)); } @@ -258,26 +292,26 @@ private static DiagnosticSource CreateSource( string? displayName = null ) { string id = targetId.HasValue - ? $"inno.assets.pipeline/{group}/{targetId.Value:N}" - : $"inno.assets.pipeline/{group}"; - return new DiagnosticSource( - id, - string.IsNullOrWhiteSpace(displayName) ? group : displayName); + ? $"inno.assets.pipeline/{group}/{targetId.Value:N}" + : $"inno.assets.pipeline/{group}"; + return new DiagnosticSource(id, string.IsNullOrWhiteSpace(displayName) ? group : displayName); } private static Diagnostic[] CreateImportDiagnostics(AssetMeta entry) { AssetImportStatus status = Enum.IsDefined(typeof(AssetImportStatus), entry.importStatus) - ? (AssetImportStatus)entry.importStatus - : AssetImportStatus.Failed; + ? (AssetImportStatus)entry.importStatus + : AssetImportStatus.Failed; DiagnosticLocation? location = string.IsNullOrWhiteSpace(entry.relativePath) - ? null - : new DiagnosticLocation(entry.relativePath); + ? null + : new DiagnosticLocation(entry.relativePath); string[] messages = entry.diagnostics .Where(static message => !string.IsNullOrWhiteSpace(message)) .ToArray(); if (messages.Length == 0 || status == AssetImportStatus.Missing) + { return []; + } return messages.Select(message => status switch { AssetImportStatus.Pending => Diagnostic.Info("ASSET-IMPORT-PENDING", message, location), @@ -290,6 +324,5 @@ private static Diagnostic[] CreateImportDiagnostics(AssetMeta entry) private static string CreateState( AssetMeta entry, IReadOnlyList diagnostics - ) - => $"{entry.importStatus}:{entry.relativePath}:{string.Join('\n', diagnostics.Select(static value => value.message))}"; + ) => $"{entry.importStatus}:{entry.relativePath}:{string.Join('\n', diagnostics.Select(static value => value.message))}"; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs index 51f76ba86..a96eebf89 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; @@ -61,6 +60,5 @@ CancellationToken cancellationToken AssetExportContext context, BinaryAsset asset, CancellationToken cancellationToken - ) - => ValueTask.FromResult?>(asset.runtimePayload); + ) => ValueTask.FromResult?>(asset.runtimePayload); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs index 631470847..e1241a73a 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs @@ -3,7 +3,6 @@ using System.Text; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; @@ -54,7 +53,8 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", Encoding.UTF8.GetBytes(content), - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); } /// @@ -76,6 +76,5 @@ await output.WriteArtifactAsync( AssetExportContext context, TextAsset asset, CancellationToken cancellationToken - ) - => ValueTask.FromResult?>(Encoding.UTF8.GetBytes(asset.content)); + ) => ValueTask.FromResult?>(Encoding.UTF8.GetBytes(asset.content)); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs index 9ce73acc9..6eb58df8c 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -13,11 +12,14 @@ namespace Inno.Assets.Pipeline; /// /// The imported asset type. /// -public sealed class AssetImportWriter where TAsset : AssetObject +public sealed class AssetImportWriter + where TAsset : AssetObject { private readonly AssetImportContext m_context; + private readonly Dictionary> m_outputs = new(StringComparer.Ordinal); + private readonly List m_diagnostics = []; private readonly HashSet m_authoringOutputs = new(StringComparer.Ordinal); private AssetDeploymentScope? m_deploymentScope; @@ -43,9 +45,13 @@ internal AssetImportWriter(AssetImportContext context) public void SetDeploymentScope(AssetDeploymentScope deploymentScope) { if (!Enum.IsDefined(deploymentScope)) + { throw new ArgumentOutOfRangeException(nameof(deploymentScope)); + } if (m_deploymentScope.HasValue) + { throw new InvalidOperationException("An importer can select its deployment scope only once."); + } m_deploymentScope = deploymentScope; } @@ -59,7 +65,9 @@ public void SetAsset(TAsset asset) { ArgumentNullException.ThrowIfNull(asset); if (this.asset is not null) + { throw new InvalidOperationException("An importer can assign its asset only once."); + } this.asset = asset; } @@ -89,13 +97,22 @@ public ValueTask WriteArtifactAsync( ) { cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(outputName)) + { throw new ArgumentException("An artifact output name is required.", nameof(outputName)); - if (!Enum.IsDefined(deploymentScope) || (deploymentScope == AssetDeploymentScope.AuthoringOnly && outputName is "runtime" or "asset-state")) + } + if (!Enum.IsDefined(deploymentScope) + || (deploymentScope == AssetDeploymentScope.AuthoringOnly && outputName is "runtime" or "asset-state") + ) { throw new ArgumentException("The output deployment scope is invalid.", nameof(deploymentScope)); + } if (!m_outputs.TryAdd(outputName, bytes.ToArray())) + { throw new InvalidOperationException($"Artifact output '{outputName}' was written more than once."); + } if (deploymentScope == AssetDeploymentScope.AuthoringOnly) + { m_authoringOutputs.Add(outputName); + } return ValueTask.CompletedTask; } @@ -154,14 +171,18 @@ string fingerprint public void ReportDiagnostic(string message) { if (string.IsNullOrWhiteSpace(message)) + { throw new ArgumentException("A diagnostic message is required.", nameof(message)); + } m_diagnostics.Add(message); } internal AssetImportProduct Complete() { if (asset is null) + { throw new InvalidOperationException("The importer did not assign an asset."); + } return new AssetImportProduct(asset, m_outputs, m_diagnostics, m_authoringOutputs, m_deploymentScope); } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImporterRegistry.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImporterRegistry.cs index acab6a270..c3b5e1ad6 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImporterRegistry.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImporterRegistry.cs @@ -1,16 +1,14 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; - using Inno.Extensibility.Types; namespace Inno.Assets.Pipeline; -internal sealed class AssetImporterRegistry - : TypeRegistry +internal sealed class AssetImporterRegistry : TypeRegistry { private readonly object m_generationSync = new(); private readonly TypeCatalog m_types; @@ -35,7 +33,9 @@ internal long GetGeneration(string importerId) { _ = current; lock (m_generationSync) + { return m_generations.GetValueOrDefault(importerId); + } } internal long snapshotVersion @@ -67,7 +67,8 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (type.IsAbstract || !typeof(AssetImporter).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Asset importer metadata on '{type.FullName}' requires a concrete {nameof(AssetImporter)} subtype."); + $"Asset importer metadata on '{type.FullName}' requires a concrete {nameof(AssetImporter)} subtype." + ); } return (type, type.GetCustomAttribute(inherit: false)!.id); }).ToArray(); @@ -75,7 +76,9 @@ protected override Snapshot Build(TypeCacheSnapshot types) .GroupBy(static registration => registration.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicateId is not null) + { throw new InvalidOperationException($"Asset importer id '{duplicateId}' is registered by multiple importers."); + } var byExtension = new Dictionary(StringComparer.OrdinalIgnoreCase); var byId = new Dictionary(StringComparer.Ordinal); @@ -93,8 +96,9 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (!byExtension.TryAdd(extension, importer)) { throw new InvalidOperationException( - $"Asset extension '{extension}' is registered by both " + - $"'{byExtension[extension].GetType().FullName}' and '{type.FullName}'."); + $"Asset extension '{extension}' is registered by both " + + $"'{byExtension[extension].GetType().FullName}' and '{type.FullName}'." + ); } } } @@ -102,7 +106,8 @@ protected override Snapshot Build(TypeCacheSnapshot types) return new Snapshot( byExtension.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase), byId.ToFrozenDictionary(StringComparer.Ordinal), - typesById.ToFrozenDictionary(StringComparer.Ordinal)); + typesById.ToFrozenDictionary(StringComparer.Ordinal) + ); } /// @@ -123,10 +128,10 @@ Snapshot candidate m_generationRollback = new Dictionary(m_generations, StringComparer.Ordinal); foreach ((string importerId, Type importerType) in candidate.typesById) { - if (previous is null || - !previous.typesById.TryGetValue(importerId, out Type? previousType) || - previousType != importerType) - { + if (previous is null + || !previous.typesById.TryGetValue(importerId, out Type? previousType) + || previousType != importerType + ) { m_generations[importerId] = m_generations.GetValueOrDefault(importerId) + 1; } } @@ -149,10 +154,14 @@ Snapshot candidate lock (m_generationSync) { if (m_generationRollback is null) + { return; + } m_generations.Clear(); foreach ((string importerId, long generation) in m_generationRollback) + { m_generations.Add(importerId, generation); + } m_generationRollback = null; } } @@ -171,7 +180,9 @@ protected override void OnActivationCompleted( Snapshot currentSnapshot ) { lock (m_generationSync) + { m_generationRollback = null; + } } /// @@ -185,7 +196,9 @@ Snapshot currentSnapshot private static string NormalizeExtension(string extension) { if (string.IsNullOrWhiteSpace(extension)) + { throw new InvalidOperationException("Asset importer extensions cannot be empty."); + } string normalized = extension.Trim().ToLowerInvariant(); return normalized[0] == '.' ? normalized : "." + normalized; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs index 56207f144..f1403e83c 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; using Inno.Core.Serialization; diff --git a/src/content/assets/Inno.Assets.Pipeline/Properties/ScriptingApi.cs b/src/content/assets/Inno.Assets.Pipeline/Properties/ScriptingApi.cs index a4e518ea6..ee1c7126a 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Properties/ScriptingApi.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Assets.Pipeline; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Assets", - "Inno.Assets.Pipeline", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Assets", "Inno.Assets.Pipeline", ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(AssetImportContext), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(AssetImportExtensionUnavailableException), ScriptingApiScope.Editor)] diff --git a/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs b/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs index 58dfc2246..7ddad144f 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs @@ -30,17 +30,14 @@ public static partial class NativeAssetSourceSerialization public static byte[] Export( TAsset asset, AssetSerializationServices services - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { ArgumentNullException.ThrowIfNull(asset); ArgumentNullException.ThrowIfNull(services); TypeRef type = services.types.GetTypeRef(asset.GetType()); var dependencies = new AssetDependencyCollection(); SerializationContext context = services.context.With(dependencies); - byte[] propertyData = services.serialization.Encode( - writer => writer.WriteProperties(asset), - context); + byte[] propertyData = services.serialization.Encode(writer => writer.WriteProperties(asset), context); return services.serialization.Serialize(new NativeAssetSourceDocument { stableAssetTypeId = type.stableId, @@ -74,8 +71,7 @@ public static TAsset Import( ReadOnlySpan bytes, AssetSerializationServices services, out IReadOnlyList dependencies - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { ArgumentNullException.ThrowIfNull(services); NativeAssetSourceDocument document = services.serialization.Deserialize(bytes); @@ -83,11 +79,12 @@ out IReadOnlyList dependencies if (document.stableAssetTypeId != expectedType.stableId) { throw new InvalidOperationException( - $"Native asset source type '{document.stableAssetTypeId:D}' does not match " + - $"'{expectedType.stableId:D}'."); + $"Native asset source type '{document.stableAssetTypeId:D}' does not match " + + $"'{expectedType.stableId:D}'." + ); } var asset = (TAsset)(Activator.CreateInstance(typeof(TAsset), nonPublic: true) - ?? throw new InvalidOperationException($"Asset type '{typeof(TAsset).FullName}' could not be created.")); + ?? throw new InvalidOperationException($"Asset type '{typeof(TAsset).FullName}' could not be created.")); SerializationContext context = AssetSerializationContext.Create(services.references); _ = services.serialization.Decode(document.propertyData, reader => { diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs index 886cd0a0a..ad78493e8 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs @@ -24,7 +24,9 @@ public static AssetChangedEvent[] Normalize( IReadOnlyList rawBatch ) { if (rawBatch.Count == 0) + { return []; + } var byPath = new Dictionary(StringComparer.OrdinalIgnoreCase); var renameOldPaths = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -34,10 +36,14 @@ IReadOnlyList rawBatch AssetChangedEvent e = rawBatch[i]; string path = NormalizeRelativePath(e.relativePath); if (string.IsNullOrWhiteSpace(path)) + { continue; + } if (!byPath.TryGetValue(path, out Accumulator acc)) + { acc = new Accumulator(path); + } if (!string.IsNullOrWhiteSpace(e.oldRelativePath)) { @@ -51,13 +57,21 @@ IReadOnlyList rawBatch WatcherChangeTypes type = e.changeType; if (type.HasFlag(WatcherChangeTypes.Renamed)) + { acc.renamed = true; + } if (type.HasFlag(WatcherChangeTypes.Created)) + { acc.created = true; + } if (type.HasFlag(WatcherChangeTypes.Changed)) + { acc.changed = true; + } if (type.HasFlag(WatcherChangeTypes.Deleted)) + { acc.deleted = true; + } byPath[path] = acc; } @@ -66,10 +80,14 @@ IReadOnlyList rawBatch foreach (Accumulator acc in byPath.Values) { if (renameOldPaths.Contains(acc.path) && !acc.renamed) + { continue; + } if (TryBuildNormalized(rootPath, acc, out AssetChangedEvent normalizedEvent)) + { normalized.Add(normalizedEvent); + } } return normalized @@ -88,9 +106,13 @@ out AssetChangedEvent normalized { WatcherChangeTypes type = WatcherChangeTypes.Renamed; if (acc.changed) + { type |= WatcherChangeTypes.Changed; + } if (acc.created) + { type |= WatcherChangeTypes.Created; + } normalized = new AssetChangedEvent(acc.path, type, acc.renameOldPath); return true; @@ -100,17 +122,29 @@ out AssetChangedEvent normalized WatcherChangeTypes foldedType; if (acc.deleted && (acc.created || acc.changed)) + { foldedType = exists ? WatcherChangeTypes.Changed : WatcherChangeTypes.Deleted; + } else if (acc.deleted) + { foldedType = WatcherChangeTypes.Deleted; + } else if (acc.created && acc.changed) + { foldedType = WatcherChangeTypes.Created | WatcherChangeTypes.Changed; + } else if (acc.created) + { foldedType = WatcherChangeTypes.Created; + } else if (acc.changed) + { foldedType = WatcherChangeTypes.Changed; + } else + { foldedType = 0; + } if (foldedType == 0) { @@ -133,15 +167,23 @@ string relativePath private static string NormalizeRelativePath(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) + { return string.Empty; + } string path = relativePath.Replace('\\', '/').Trim(); while (path.StartsWith("./", StringComparison.Ordinal)) + { path = path[2..]; + } while (path.StartsWith("/", StringComparison.Ordinal)) + { path = path[1..]; + } while (path.EndsWith("/", StringComparison.Ordinal)) + { path = path[..^1]; + } return path == "." ? string.Empty : path; } @@ -152,22 +194,27 @@ private struct Accumulator(string path) /// The path value used as part of this type's public representation. /// public string path = path; + /// /// The created value used as part of this type's public representation. /// public bool created; + /// /// The changed value used as part of this type's public representation. /// public bool changed; + /// /// The deleted value used as part of this type's public representation. /// public bool deleted; + /// /// The renamed value used as part of this type's public representation. /// public bool renamed; + /// /// The rename old path value used as part of this type's public representation. /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileEntry.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileEntry.cs index 39fbfd2e7..c6068cd23 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileEntry.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileEntry.cs @@ -1,5 +1,4 @@ using System.IO; - using Inno.Assets; using Inno.Core.Identity; @@ -13,11 +12,12 @@ public sealed class AssetFileEntry : IdentityObject /// /// Gets the final source path segment, or the semantic mount-root label when this entry is a source root. /// - public string name => string.IsNullOrEmpty(assetPath.localPath) - ? assetPath.source == AssetSourceId.project - ? "Assets" - : assetPath.source.value - : Path.GetFileName(assetPath.localPath); + public string name + => string.IsNullOrEmpty(assetPath.localPath) + ? assetPath.source == AssetSourceId.project + ? "Assets" + : assetPath.source.value + : Path.GetFileName(assetPath.localPath); /// /// Gets the final source path segment without its last extension. @@ -58,6 +58,7 @@ public sealed class AssetFileEntry : IdentityObject /// Gets whether the entry represents a directory. /// public bool isDirectory { get; internal set; } + /// /// Gets the normalized lower-case file extension. /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs index 60a9ceca2..99be8b3ff 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs @@ -5,10 +5,9 @@ using System.Security.Cryptography; using System.Text; using System.Threading; - using Inno.Assets; -using Inno.Core.Identity; using Inno.Core.Collections; +using Inno.Core.Identity; namespace Inno.Assets.Pipeline; @@ -42,7 +41,7 @@ bool isDirectory /// Gets the absolute source asset root. /// public string assetRoot { get; } - + /// /// Gets whether source file watching is active. /// @@ -68,18 +67,16 @@ public AssetFileSystem( bool autoStart = true, int flushDelayMs = 80, AssetSourcePolicy? sourcePolicy = null - ) - : this( - [new AssetSourceMount(AssetSourceId.project, assetRoot, isReadOnly: false)], - autoStart, - flushDelayMs, - sourcePolicy, - requireWritableProject: true, - identities: new IdentityAllocator(), - persistentIdentityResolver: null, - activateIdentities: true) - { - } + ) : this( + [new AssetSourceMount(AssetSourceId.project, assetRoot, isReadOnly: false)], + autoStart, + flushDelayMs, + sourcePolicy, + requireWritableProject: true, + identities: new IdentityAllocator(), + persistentIdentityResolver: null, + activateIdentities: true + ) {} /// /// Creates an indexed file system over isolated source mounts. @@ -106,18 +103,16 @@ public AssetFileSystem( int flushDelayMs = 80, AssetSourcePolicy? sourcePolicy = null, bool requireWritableProject = true - ) - : this( - mounts, - autoStart, - flushDelayMs, - sourcePolicy, - requireWritableProject, - identities: new IdentityAllocator(), - persistentIdentityResolver: null, - activateIdentities: true) - { - } + ) : this( + mounts, + autoStart, + flushDelayMs, + sourcePolicy, + requireWritableProject, + identities: new IdentityAllocator(), + persistentIdentityResolver: null, + activateIdentities: true + ) {} internal AssetFileSystem( IReadOnlyList mounts, @@ -132,21 +127,28 @@ bool activateIdentities ArgumentNullException.ThrowIfNull(mounts); ArgumentNullException.ThrowIfNull(identities); if (mounts.Count == 0) + { throw new ArgumentException("At least one asset source mount is required.", nameof(mounts)); + } Dictionary byId = mounts.ToDictionary(static mount => mount.id); if (byId.Count != mounts.Count) + { throw new ArgumentException("Asset source mount IDs must be unique.", nameof(mounts)); + } if (!byId.TryGetValue(AssetSourceId.project, out AssetSourceMount? project) - || project.isReadOnly && requireWritableProject) - { + || project.isReadOnly && requireWritableProject + ) { throw new ArgumentException( requireWritableProject - ? "A writable project asset source mount is required." - : "A project asset source mount is required.", - nameof(mounts)); + ? "A writable project asset source mount is required." + : "A project asset source mount is required.", + nameof(mounts) + ); } if (project.isReadOnly && autoStart) + { throw new ArgumentException("A read-only project source cannot be watched for authoring changes.", nameof(autoStart)); + } assetRoot = project.rootPath; m_identities = identities; @@ -154,7 +156,9 @@ bool activateIdentities m_persistentIdentityResolver = persistentIdentityResolver; m_identitiesActive = activateIdentities; foreach (AssetSourceMount mount in mounts) + { Directory.CreateDirectory(mount.rootPath); + } m_sourcePolicy = sourcePolicy ?? AssetSourcePolicy.defaultPolicy; m_pathKey = m_entries.DefineKey("filesystem.path", IndexedObjectKeyFlags.Unique); @@ -166,7 +170,9 @@ bool activateIdentities m_watcher = new AssetWatcher(assetRoot, flushDelayMs); if (autoStart) + { m_watcher.Start(); + } } /// @@ -184,7 +190,9 @@ public void Start() public void Stop() { if (m_disposed) + { return; + } m_watcher.Stop(); } @@ -228,11 +236,15 @@ public void Refresh() if (m_identitiesActive) { if (!m_identities.Register(entry, source.persistentId)) + { throw new InvalidOperationException($"Asset source entry '{source.path}' could not acquire its identity."); + } registered.Add(entry); } else + { m_identities.InitializePersistentIdentity(entry, source.persistentId); + } } prepared.Add((source, entry)); } @@ -240,7 +252,9 @@ public void Refresh() catch { foreach (AssetFileEntry entry in registered) + { _ = m_identities.Unregister(entry); + } throw; } m_entries.RemoveAll(); @@ -250,8 +264,12 @@ public void Refresh() existing.Remove(source.persistentId); } if (m_identitiesActive) + { foreach (AssetFileEntry removed in existing.Values) + { _ = m_identities.Unregister(removed); + } + } } } @@ -321,8 +339,8 @@ public IReadOnlyList GetEntries(bool includeDirectories = true) lock (m_sync) { IReadOnlyList all = includeDirectories - ? m_entries.All() - : m_entries.Find(m_isDirectoryKey, false); + ? m_entries.All() + : m_entries.Find(m_isDirectoryKey, false); return all .OrderBy(static x => x.assetPath.ToString(), StringComparer.OrdinalIgnoreCase) @@ -379,7 +397,9 @@ public IReadOnlyList PollChanges(out bool requiresFullRescan) WatcherPollResult result = m_watcher.Poll(force: false); requiresFullRescan = result.requiresFullRescan; if (result.changes.Count > 0 || requiresFullRescan) + { RefreshSafely(); + } return result.changes; } @@ -413,7 +433,9 @@ public IReadOnlyList WaitForIdle(out bool requiresFullRescan) WatcherPollResult result = m_watcher.WaitForIdle(); requiresFullRescan = result.requiresFullRescan; if (result.changes.Count > 0 || requiresFullRescan) + { RefreshSafely(); + } return result.changes; } @@ -423,7 +445,9 @@ public IReadOnlyList WaitForIdle(out bool requiresFullRescan) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_watcher.Dispose(); @@ -440,7 +464,9 @@ internal void ActivateIdentities() lock (m_sync) { if (m_identitiesActive) + { return; + } var registered = new List(); try { @@ -449,7 +475,8 @@ internal void ActivateIdentities() if (!m_identities.Register(entry, entry.identity.persistentId)) { throw new InvalidOperationException( - $"Asset source entry '{entry.assetPath}' was already registered."); + $"Asset source entry '{entry.assetPath}' was already registered." + ); } registered.Add(entry); } @@ -458,7 +485,9 @@ internal void ActivateIdentities() catch { foreach (AssetFileEntry entry in registered) + { _ = m_identities.Unregister(entry); + } throw; } } @@ -467,13 +496,17 @@ internal void ActivateIdentities() internal void DeactivateIdentities() { lock (m_sync) + { DeactivateIdentitiesLocked(); + } } private void RefreshSafely() { if (m_disposed) + { return; + } try { @@ -508,13 +541,17 @@ private List CollectEntries() { string path = CombineLocalPath(directory, Path.GetFileName(child)); if (!m_sourcePolicy.IsIgnored(path, isDirectory: true)) + { pending.Push(path); + } } foreach (string child in Directory.EnumerateFiles(absoluteDirectory)) { string path = CombineLocalPath(directory, Path.GetFileName(child)); if (!m_sourcePolicy.IsIgnored(path, isDirectory: false)) + { Add(new AssetPath(mount.id, path), mount.isReadOnly, isDirectory: false); + } } } } @@ -528,7 +565,9 @@ bool isDirectory Guid sourceId = m_persistentIdentityResolver?.Invoke(path) ?? CreateFallbackPersistentId(path.ToString()); Guid entryId = CreateEntryPersistentId(sourceId); if (!identities.Add(entryId)) + { throw new InvalidDataException($"Asset source path '{path}' duplicates a persistent entry identity."); + } entries.Add(new(path, entryId, isReadOnly, isDirectory)); } } @@ -547,8 +586,8 @@ SourceEntry source existing.parentAssetPath = AssetPath.Parse(GetParentPath(path)); existing.isDirectory = isDirectory; existing.extension = isDirectory - ? string.Empty - : Path.GetExtension(path).ToLowerInvariant(); + ? string.Empty + : Path.GetExtension(path).ToLowerInvariant(); m_entries.Add(existing) .Set(m_pathKey, existing.assetPath.ToString()) @@ -581,13 +620,17 @@ private static Guid CreateEntryPersistentId(Guid sourcePersistentId) private void UnregisterEntries() { foreach (AssetFileEntry entry in m_entries.All()) + { _ = m_identities.Unregister(entry); + } } private void DeactivateIdentitiesLocked() { if (!m_identitiesActive) + { return; + } UnregisterEntries(); m_identitiesActive = false; } @@ -596,7 +639,9 @@ private static string GetParentPath(string relativePath) { AssetPath path = AssetPath.Parse(relativePath ?? string.Empty); if (string.IsNullOrWhiteSpace(path.localPath)) + { return string.Empty; + } int lastSeparator = path.localPath.LastIndexOf('/'); string parent = lastSeparator < 0 ? string.Empty : path.localPath[..lastSeparator]; @@ -607,15 +652,18 @@ private static string GetParentPath(string relativePath) private static string CombineLocalPath( string a, string b - ) - => NormalizeLocalPath(Path.Combine(NormalizeLocalPath(a), NormalizeLocalPath(b))); + ) => NormalizeLocalPath(Path.Combine(NormalizeLocalPath(a), NormalizeLocalPath(b))); private string NormalizeAssetPath(AssetPath path) { if (!path.isValid) + { throw new ArgumentException("An isolated asset path is required.", nameof(path)); + } if (!m_mounts.ContainsKey(path.source)) + { throw new ArgumentException($"Asset source mount '{path.source}' is not indexed.", nameof(path)); + } return path.ToString(); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs index 479d14350..1e660b065 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs @@ -4,13 +4,12 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Core.Execution; using Inno.Core.Serialization; -using Inno.Scripting.Api; using Inno.Extensibility.Reload; using Inno.References; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -50,10 +49,14 @@ public AssetSampleImportTransaction PrepareSampleImport(AssetPath source) EnsureOwnerThread(); m_generations.EnsureReady("import an Asset sample"); if (m_sourceMountCandidate is not null) + { throw new InvalidOperationException("A source-mount candidate is already pending."); + } AssetFileSystem fileSystem = GetFileSystem(); if (!fileSystem.TryGetEntry(source, out AssetFileEntry entry) || !entry.isDirectory || !entry.isSample) + { throw new ArgumentException($"Asset source '{source}' is not an installed Plugin sample directory.", nameof(source)); + } AssetPath target = AssetPath.Project(AssetSample.GetImportName(source)); RequireSampleDestination(target); AssetSourceMount sourceMount = sourceMounts.Single(mount => mount.id == source.source); @@ -65,19 +68,29 @@ public AssetSampleImportTransaction PrepareSampleImport(AssetPath source) { serialization = m_serialization.CaptureGeneration(); foreach (Type type in m_types.GetTypesWithAttribute() - .Select(reference => reference.Resolve(m_types)) - .OrderBy(type => type.GetCustomAttributes(typeof(AssetSampleSourceRewriterAttribute), false) - .Cast().Single().id, StringComparer.Ordinal)) - { + .Select(reference => reference.Resolve(m_types)) + .OrderBy(type => type.GetCustomAttributes(typeof(AssetSampleSourceRewriterAttribute), false) + .Cast() + .Single().id, StringComparer.Ordinal) + ) { if (type.IsAbstract || !typeof(IAssetSampleSourceRewriter).IsAssignableFrom(type) - || Activator.CreateInstance(type) is not IAssetSampleSourceRewriter rewriter) + || Activator.CreateInstance(type) is not IAssetSampleSourceRewriter rewriter + ) { throw new InvalidOperationException($"Sample transformer '{type.FullName}' is not a concrete source rewriter."); + } rewriters.Add(rewriter); } m_sampleImport = new AssetSampleImportTransaction( - this, source, target, sourceMount.Resolve(source.localPath), transactionRoot, + this, + source, + target, + sourceMount.Resolve(source.localPath), + transactionRoot, m_options.sourcePolicy ?? AssetSourcePolicy.defaultPolicy, - generation, serialization, rewriters.ToArray()); + generation, + serialization, + rewriters.ToArray() + ); return m_sampleImport; } catch (Exception failure) @@ -85,9 +98,13 @@ public AssetSampleImportTransaction PrepareSampleImport(AssetPath source) var cleanup = new LifetimeScope(); cleanup.Own(generation); if (serialization is not null) + { cleanup.Own(serialization); + } foreach (IDisposable rewriter in rewriters.OfType()) + { cleanup.Own(rewriter); + } try { cleanup.Dispose(); @@ -104,7 +121,9 @@ internal void EnsureSampleImportOwner(AssetSampleImportTransaction transaction) { EnsureInitializationThread(); if (!ReferenceEquals(m_sampleImport, transaction)) + { throw new InvalidOperationException("The sample transaction no longer belongs to this pipeline."); + } } internal Task PrepareSampleCatalogAsync( @@ -139,10 +158,14 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); AssetPath candidate = AssetPath.Project(localPath); if (!loader.TryGetAssetType(candidate, out Type? assetType) || assetType is null) + { continue; + } AssetObject? imported = loader.Load(candidate, assetType); if (imported is null || imported.isMissing) + { throw new InvalidDataException($"Sample asset '{candidate}' failed pre-publication import validation."); + } } cancellationToken.ThrowIfCancellationRequested(); return prepared; @@ -183,7 +206,11 @@ internal void CommitSampleImport( }; changes.AddRange(transaction.entries.Select(static path => new AssetChangedEvent(path, WatcherChangeTypes.Created))); AssetChange[] committed = CreateCommittedChanges( - transaction.candidate!.candidateLoader, changes, new Dictionary(StringComparer.OrdinalIgnoreCase), requiresFullRescan: false); + transaction.candidate!.candidateLoader, + changes, + new Dictionary(StringComparer.OrdinalIgnoreCase), + requiresFullRescan: false + ); transaction.candidate!.Activate(); beforePublish?.Invoke(transaction.target); transaction.candidate.Complete(); @@ -207,7 +234,9 @@ internal void RollbackSampleImport(AssetSampleImportTransaction transaction) transaction.sourceMoved = false; } if (!transaction.TryCleanPrivateCopy()) + { throw new RetirementPendingException("Sample import private storage is still being removed."); + } FinishSampleImport(transaction); } @@ -230,6 +259,8 @@ private void RequireSampleDestination(AssetPath target) { string destination = Path.Combine(assetRoot, target.localPath); if (Directory.Exists(destination) || System.IO.File.Exists(destination) || System.IO.File.Exists(destination + ".imeta")) + { throw new IOException($"Sample import target '{target}' already exists."); + } } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs index 4b700f5e8..57a5f44f2 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs @@ -1,22 +1,21 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Threading; - -using Inno.Assets; -using Inno.Core.Execution; -using Inno.References; -using System.IO; using System.Threading.Tasks; +using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; -using Inno.Scripting.Api; using Inno.Core.Serialization; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.References; +using Inno.Scripting.Api; namespace Inno.Assets.Pipeline; @@ -32,16 +31,24 @@ private AssetSourceMountTransaction PrepareSourceMountsCore(IReadOnlyList mount.id == AssetSourceId.project) - ?? throw new ArgumentException("A project asset source mount is required.", nameof(mounts)); + ?? throw new ArgumentException("A project asset source mount is required.", nameof(mounts)); if (projectMount.isReadOnly) + { throw new ArgumentException("The project asset source mount must be writable.", nameof(mounts)); + } if (snapshot.Select(static mount => mount.id).Distinct().Count() != snapshot.Length) + { throw new ArgumentException("Asset source mount IDs must be unique.", nameof(mounts)); + } PreparedSourceMounts prepared = PrepareSourceMountCatalog(GetLoader(), snapshot, CancellationToken.None); try { @@ -75,10 +82,15 @@ CancellationToken cancellationToken catalog = activeLoader.PrepareCatalogCandidate(mounts, m_options.sourcePolicy); AssetLoader loader = catalog.loader; files = new AssetFileSystem( - mounts, autoStart: false, m_options.fileWatcherFlushDelayMs, m_options.sourcePolicy, - requireWritableProject: true, m_identities, + mounts, + autoStart: false, + m_options.fileWatcherFlushDelayMs, + m_options.sourcePolicy, + requireWritableProject: true, + m_identities, persistentIdentityResolver: path => loader.TryGetPersistentId(path, out Guid id) ? id : null, - activateIdentities: false); + activateIdentities: false + ); loader.Rescan(cancellationToken); files.Refresh(); cancellationToken.ThrowIfCancellationRequested(); @@ -104,9 +116,17 @@ IReadOnlyList recovery ) { EnsureInitializationThread(); if (m_sourceMountCandidate is not null) + { throw new InvalidOperationException("Another source-mount candidate is already pending."); + } var transaction = new AssetSourceMountTransaction( - this, prepared.mounts, prepared.catalog, prepared.files, recovery, Math.Max(1, m_revision + 1)); + this, + prepared.mounts, + prepared.catalog, + prepared.files, + recovery, + Math.Max(1, m_revision + 1) + ); m_sourceMountCandidate = transaction; return transaction; } @@ -125,7 +145,9 @@ private void RetireSourcePreparation( resources.Own(catalog.loader); } if (files is not null) + { resources.Own(files); + } try { Retire(resources, new RetirementBarrier("Asset source preparation")); @@ -133,7 +155,9 @@ private void RetireSourcePreparation( catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { lock (m_lifecycleLock) + { m_failedPreparation = resources; + } throw; } } @@ -185,7 +209,9 @@ internal void ActivatePreparedSourceMounts(AssetSourceMountTransaction transacti { EnsurePendingSourceMountTransaction(transaction); if (transaction.isActivated) + { return; + } transaction.candidateLoader.ActivateExtensionDiscovery(); _ = transaction.candidateLoader.RefreshRegistries(); transaction.candidateFileSystem.Refresh(); @@ -193,14 +219,19 @@ internal void ActivatePreparedSourceMounts(AssetSourceMountTransaction transacti transaction.previousFileSystem = m_fileSystem; transaction.previousMounts = sourceMounts; transaction.previousOptions = m_options; - SwitchSourceIdentities(transaction.previousLoader!, transaction.previousFileSystem!, - transaction.candidateLoader, transaction.candidateFileSystem); + SwitchSourceIdentities( + transaction.previousLoader!, + transaction.previousFileSystem!, + transaction.candidateLoader, + transaction.candidateFileSystem + ); transaction.candidateLoader.AssetReloaded += OnAssetReloaded; m_loader = transaction.candidateLoader; m_fileSystem = transaction.candidateFileSystem; sourceMounts = transaction.sourceMounts; AssetSourceMount project = transaction.sourceMounts.Single( - static mount => mount.id == AssetSourceId.project); + static mount => mount.id == AssetSourceId.project + ); assetRoot = project.rootPath; m_options = m_options with { assetRoot = assetRoot, sourceMounts = transaction.sourceMounts }; m_revision++; @@ -219,12 +250,16 @@ internal void CompletePreparedSourceMounts(AssetSourceMountTransaction transacti m_generations.EnsureRetirementSafe(); EnsurePendingSourceMountTransaction(transaction); if (!transaction.isActivated) + { throw new InvalidOperationException("A source-mount candidate must be activated before completion."); + } try { transaction.catalogCandidate.Commit(); if (m_options.enableFileSystemWatcher) + { transaction.candidateFileSystem.Start(); + } } catch (Exception failure) { @@ -239,7 +274,9 @@ internal void CompletePreparedSourceMounts(AssetSourceMountTransaction transacti transaction.retirement.Own(transaction.previousLoader); } if (transaction.previousFileSystem is not null) + { transaction.retirement.Own(transaction.previousFileSystem); + } RetireSourceMounts(transaction); changed = SourceMountsChanged; } @@ -250,7 +287,9 @@ internal void RollbackPreparedSourceMounts(AssetSourceMountTransaction transacti { ArgumentNullException.ThrowIfNull(transaction); if (transaction.isFinished) + { return; + } EnsureInitializationThread(); using IDisposable operationScope = AcquireOperation(); lock (m_lifecycleLock) @@ -260,14 +299,19 @@ internal void RollbackPreparedSourceMounts(AssetSourceMountTransaction transacti if (transaction.isActivated) { transaction.candidateLoader.AssetReloaded -= OnAssetReloaded; - SwitchSourceIdentities(transaction.candidateLoader, transaction.candidateFileSystem, - transaction.previousLoader!, transaction.previousFileSystem!); + SwitchSourceIdentities( + transaction.candidateLoader, + transaction.candidateFileSystem, + transaction.previousLoader!, + transaction.previousFileSystem! + ); m_loader = transaction.previousLoader; m_fileSystem = transaction.previousFileSystem; sourceMounts = transaction.previousMounts ?? []; m_options = transaction.previousOptions; AssetSourceMount? project = sourceMounts.SingleOrDefault( - static mount => mount.id == AssetSourceId.project); + static mount => mount.id == AssetSourceId.project + ); assetRoot = project?.rootPath ?? string.Empty; m_revision++; transaction.isActivated = false; @@ -327,7 +371,9 @@ private void DeleteCandidateCatalogRoots(string activeLibraryRoot) { string root = Path.Combine(activeLibraryRoot, "AssetDatabase", "Candidates"); if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } private void SwitchSourceIdentities( @@ -389,6 +435,8 @@ Action compensate private void EnsurePendingSourceMountTransaction(AssetSourceMountTransaction transaction) { if (!ReferenceEquals(m_sourceMountCandidate, transaction)) + { throw new InvalidOperationException("The source-mount transaction is not the current candidate."); + } } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs index 985a9a868..b33115ce2 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -28,7 +27,9 @@ public static class AssetSample public static bool HasSampleDirectoryName(AssetPath path) { if (!path.isValid || string.IsNullOrEmpty(path.localPath)) + { return false; + } return Path.GetFileName(path.localPath).StartsWith('~'); } @@ -84,10 +85,14 @@ bool isDirectory public static string GetImportName(AssetPath path) { if (!IsRoot(path)) + { throw new ArgumentException("The path must identify an installed Plugin sample directory.", nameof(path)); + } string name = Path.GetFileName(path.localPath); if (string.IsNullOrWhiteSpace(name.TrimStart('~'))) + { throw new ArgumentException("A sample directory requires a name after its '~' prefix.", nameof(path)); + } return name; } @@ -115,13 +120,17 @@ private static bool ContainsTildeDirectory( bool isDirectory ) { if (!path.isValid || string.IsNullOrEmpty(path.localPath)) + { return false; + } string[] segments = path.localPath.Split('/', StringSplitOptions.RemoveEmptyEntries); int directoryCount = isDirectory ? segments.Length : segments.Length - 1; for (int index = 0; index < directoryCount; index++) { if (segments[index].StartsWith('~')) + { return true; + } } return false; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs index 84b602c41..4b9d03804 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs @@ -3,7 +3,6 @@ using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Core.Execution; using Inno.Core.Serialization; @@ -53,7 +52,9 @@ IAssetSampleSourceRewriter[] rewriters foreach (IAssetSampleSourceRewriter rewriter in rewriters) { if (rewriter is IDisposable disposable) + { m_preparationResources.Own(disposable); + } } m_preparation = m_lifetime.RunAsync(async cancellationToken => { @@ -62,16 +63,27 @@ IAssetSampleSourceRewriter[] rewriters return await Task.Run(() => { List entries = AssetSampleSnapshot.Capture( - absoluteSource, stagedSource, target.localPath, policy, cancellationToken); + absoluteSource, + stagedSource, + target.localPath, + policy, + cancellationToken + ); AssetSampleSnapshot.RemapIdentities( - stagedSource, source, target, serialization, context => + stagedSource, + source, + target, + serialization, + context => { foreach (IAssetSampleSourceRewriter rewriter in rewriters) { cancellationToken.ThrowIfCancellationRequested(); rewriter.Transform(context); } - }, cancellationToken); + }, + cancellationToken + ); return new Preparation(entries, null); }, cancellationToken).ConfigureAwait(false); } @@ -115,14 +127,20 @@ public bool Advance() EnsureOpen(); m_owner.EnsureSampleImportOwner(this); if (isIndexed) + { return true; + } Task preparation = m_preparation!; if (!preparation.IsCompleted) + { return false; + } Preparation outcome = preparation.GetAwaiter().GetResult(); m_preparationResources.Dispose(); if (outcome.failure is not null) + { ExceptionDispatchInfo.Capture(outcome.failure).Throw(); + } entries = outcome.entries; if (m_indexing is null) { @@ -131,7 +149,9 @@ public bool Advance() try { AssetPipeline.PreparedSourceMounts prepared = await m_owner.PrepareSampleCatalogAsync( - this, cancellationToken).ConfigureAwait(false); + this, + cancellationToken + ).ConfigureAwait(false); return new Indexing(prepared, null); } catch (Exception failure) @@ -143,10 +163,14 @@ public bool Advance() return false; } if (!m_indexing.IsCompleted) + { return false; + } Indexing indexed = m_indexing.GetAwaiter().GetResult(); if (indexed.failure is not null) + { ExceptionDispatchInfo.Capture(indexed.failure).Throw(); + } m_owner.AdoptSampleCatalog(this, indexed.prepared!); isIndexed = true; return true; @@ -170,7 +194,9 @@ public void BeginValidation(Func(async cancellationToken => { try @@ -205,10 +231,14 @@ public void Commit(Action? beforePublish = null) EnsureOpen(); m_owner.EnsureSampleImportOwner(this); if (!isValidationComplete) + { throw new InvalidOperationException("Sample validation has not completed."); + } Exception? failure = m_validation!.GetAwaiter().GetResult(); if (failure is not null) + { ExceptionDispatchInfo.Capture(failure).Throw(); + } m_lifetime.cancellationToken.ThrowIfCancellationRequested(); m_owner.CommitSampleImport(this, beforePublish); } @@ -230,7 +260,9 @@ public void Commit(Action? beforePublish = null) public void Rollback() { if (m_finished) + { return; + } m_owner.EnsureSampleImportOwner(this); Cancel(); try @@ -238,20 +270,26 @@ public void Rollback() if (!m_retirement.TryComplete(() => { if (!m_lifetime.isQuiescent) + { throw new RetirementPendingException("Sample import work must drain before rollback releases its generation."); + } if (candidate is null && m_indexing is { IsCompletedSuccessfully: true }) { Indexing indexed = m_indexing.GetAwaiter().GetResult(); if (indexed.prepared is not null) + { m_owner.DiscardSampleCatalog(indexed.prepared); + } m_indexing = null; } m_owner.RollbackSampleImport(this); - })) + }) + ) { throw new RetirementPendingException("Sample import retirement is waiting for canceled work."); + } } catch (Exception pending) when (RetirementPendingException.Find(pending) is not RetirementTimeoutException - && RetirementPendingException.Find(pending) is not null) + && RetirementPendingException.Find(pending) is not null) { throw; } @@ -309,23 +347,31 @@ internal bool TryCleanPrivateCopy() } }); if (!m_cleanup.IsCompleted) + { return false; + } Exception? failure = m_cleanup.GetAwaiter().GetResult(); if (failure is not null) + { ExceptionDispatchInfo.Capture(failure).Throw(); + } return true; } private void EnsureOpen() { if (m_finished) + { throw new InvalidOperationException("The sample import transaction is finished."); + } } private void EnsureFailureDrained(Exception failure) { if (RetirementPendingException.Find(failure) is null) + { return; + } // A completed task reporting pending ownership must stay retained by the Core lifetime. m_owner.FaultSampleImport(failure); ExceptionDispatchInfo.Capture(failure).Throw(); diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs index 5f2a22d9f..d4f7c8295 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs @@ -21,7 +21,9 @@ CancellationToken cancellationToken List copied = CopyDirectory(source, target, targetLocalPath, sourcePolicy, cancellationToken); string sourceMeta = source + ".imeta"; if (File.Exists(sourceMeta)) + { CopyStableFile(sourceMeta, target + ".imeta", cancellationToken); + } return copied; } @@ -38,42 +40,62 @@ CancellationToken cancellationToken var sourceIdentities = new Dictionary(StringComparer.Ordinal); string[] metadata = Directory.GetFiles(stagedSource, "*.imeta", SearchOption.AllDirectories); if (File.Exists(stagedSource + ".imeta")) + { metadata = [.. metadata, stagedSource + ".imeta"]; + } foreach (string path in metadata.Order(StringComparer.Ordinal)) { cancellationToken.ThrowIfCancellationRequested(); AssetSourceMeta meta = serialization.Deserialize(File.ReadAllBytes(path)); if (meta.persistentId == Guid.Empty) + { throw new InvalidDataException($"Sample metadata '{path}' has no persistent identity."); + } if (!identities.TryAdd(meta.persistentId, Guid.NewGuid())) + { throw new InvalidDataException($"Sample contains duplicate persistent identity '{meta.persistentId:D}'."); + } Guid oldId = meta.persistentId; meta.persistentId = identities[oldId]; File.WriteAllBytes(path, serialization.Serialize(meta)); string relative = Path.GetRelativePath(stagedSource, path); string suffix = string.Equals(path, stagedSource + ".imeta", StringComparison.Ordinal) - ? string.Empty - : relative[..^".imeta".Length].Replace('\\', '/'); + ? string.Empty + : relative[..^".imeta".Length].Replace('\\', '/'); sourceIdentities.Add(suffix, (oldId, meta.persistentId)); string oldLocal = string.IsNullOrEmpty(suffix) - ? source.localPath : source.localPath + "/" + suffix; + ? source.localPath + : source.localPath + "/" + suffix; string newLocal = string.IsNullOrEmpty(suffix) - ? target.localPath : target.localPath + "/" + suffix; + ? target.localPath + : target.localPath + "/" + suffix; paths[new AssetPath(source.source, oldLocal).ToString()] = newLocal; paths[oldLocal] = newLocal; } - transform(new AssetSampleTransformContext( - stagedSource, source, target, identities, sourceIdentities, cancellationToken)); + transform( + new AssetSampleTransformContext( + stagedSource, + source, + target, + identities, + sourceIdentities, + cancellationToken + ) + ); IEnumerable stagedFiles = Directory.GetFiles(stagedSource, "*", SearchOption.AllDirectories); if (File.Exists(stagedSource + ".imeta")) + { stagedFiles = stagedFiles.Append(stagedSource + ".imeta"); + } foreach (string path in stagedFiles) { cancellationToken.ThrowIfCancellationRequested(); byte[] original = File.ReadAllBytes(path); byte[] rewritten = SerializedIdentityRemapper.Rewrite(original, identities, paths); if (!original.AsSpan().SequenceEqual(rewritten)) + { File.WriteAllBytes(path, rewritten); + } } } @@ -101,19 +123,24 @@ CancellationToken cancellationToken string name = Path.GetFileName(directories[index]); string childLocalPath = targetLocalPath + "/" + name; copied.Add(childLocalPath); - copied.AddRange(CopyDirectory( - directories[index], - Path.Combine(target, name), - childLocalPath, - sourcePolicy, - cancellationToken)); + copied.AddRange( + CopyDirectory( + directories[index], + Path.Combine(target, name), + childLocalPath, + sourcePolicy, + cancellationToken + ) + ); } for (int index = 0; index < files.Length; index++) { string name = Path.GetFileName(files[index]); CopyStableFile(files[index], Path.Combine(target, name), cancellationToken); if (!AssetSourcePolicy.IsGeneratedPath(name)) + { copied.Add(targetLocalPath + "/" + name); + } } string[] currentDirectories = Directory.GetDirectories(source) @@ -124,9 +151,9 @@ CancellationToken cancellationToken .Where(path => ShouldCopyFile(path, sourcePolicy)) .Order(StringComparer.Ordinal) .ToArray(); - if (!directories.SequenceEqual(currentDirectories, StringComparer.Ordinal) || - !files.SequenceEqual(currentFiles, StringComparer.Ordinal)) - { + if (!directories.SequenceEqual(currentDirectories, StringComparer.Ordinal) + || !files.SequenceEqual(currentFiles, StringComparer.Ordinal) + ) { throw new IOException($"Sample source '{source}' changed while it was being imported."); } return copied; @@ -138,9 +165,13 @@ AssetSourcePolicy sourcePolicy ) { string name = Path.GetFileName(path); if (name.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase)) + { return true; + } if (name.EndsWith(".abin", StringComparison.OrdinalIgnoreCase)) + { return false; + } return !sourcePolicy.IsIgnored(name, isDirectory: false); } @@ -168,11 +199,15 @@ CancellationToken cancellationToken EnsureRegularFile(source); FileInfo after = new(source); if (after.Length != beforeLength || after.LastWriteTimeUtc != beforeWriteTime) + { throw new IOException($"Sample source file '{source}' changed while it was being imported."); + } byte[] sourceHash = HashFile(source, cancellationToken); byte[] targetHash = HashFile(target, cancellationToken); if (!sourceHash.AsSpan().SequenceEqual(targetHash)) + { throw new IOException($"Sample source file '{source}' changed while it was being imported."); + } } private static byte[] HashFile( @@ -194,16 +229,24 @@ CancellationToken cancellationToken private static void EnsureRegularDirectory(string path) { if (!Directory.Exists(path)) + { throw new DirectoryNotFoundException($"Sample directory '{path}' does not exist."); + } if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) + { throw new IOException($"Sample directory '{path}' cannot be a symbolic link."); + } } private static void EnsureRegularFile(string path) { if (!File.Exists(path)) + { throw new FileNotFoundException("Sample source file does not exist.", path); + } if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) + { throw new IOException($"Sample source file '{path}' cannot be a symbolic link."); + } } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs index f9ceb4a48..c959408be 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs @@ -104,9 +104,13 @@ public void MapType( Guid newId ) { if (oldId == Guid.Empty || newId == Guid.Empty) + { throw new ArgumentException("Sample type identities must be non-empty."); + } if (m_identityMap.TryGetValue(oldId, out Guid existing) && existing != newId) + { throw new InvalidDataException($"Sample type identity '{oldId:D}' has conflicting clone mappings."); + } m_identityMap[oldId] = newId; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs index f7e5528b1..cc0b42ed8 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using System.IO; using System.Linq; using Inno.Assets; @@ -35,7 +35,9 @@ public AssetSourceMount( IEnumerable? dependencies = null ) { if (!id.isValid) + { throw new ArgumentException("An asset source ID must be valid.", nameof(id)); + } ArgumentException.ThrowIfNullOrWhiteSpace(rootPath); this.id = id; this.rootPath = Path.GetFullPath(rootPath); diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/Filtering/AssetSourcePolicy.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/Filtering/AssetSourcePolicy.cs index 243eaabd5..4bbb6b4a6 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/Filtering/AssetSourcePolicy.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/Filtering/AssetSourcePolicy.cs @@ -34,6 +34,7 @@ public sealed class AssetSourcePolicy ]; private static readonly string[] S_DEFAULT_PREFIXES = [".#", "._", "~$"]; + private static readonly string[] S_DEFAULT_SUFFIXES = [".bak", ".deps.json", ".orig", ".pdb", ".swo", ".swp", ".temp", ".tmp", "~"]; @@ -46,9 +47,7 @@ public sealed class AssetSourcePolicy /// Creates a source policy using the engine's default noise filters. /// public AssetSourcePolicy() - : this(null, null, null, null) - { - } + : this(null, null, null, null) {} /// /// Creates a source policy with additional ignored names and affixes. @@ -102,20 +101,30 @@ bool isDirectory ) { string name = Path.GetFileName(relativePath); if (string.IsNullOrEmpty(name)) + { return false; + } if (isDirectory && m_directoryNames.Contains(name)) + { return true; + } if (!isDirectory && (m_fileNames.Contains(name) || IsGeneratedPath(name) || AtomicFile.IsCandidatePath(name))) + { return true; + } for (int i = 0; i < m_prefixes.Length; i++) { if (name.StartsWith(m_prefixes[i], StringComparison.OrdinalIgnoreCase)) + { return true; + } } for (int i = 0; i < m_suffixes.Length; i++) { if (name.EndsWith(m_suffixes[i], StringComparison.OrdinalIgnoreCase)) + { return true; + } } return false; } @@ -130,19 +139,23 @@ bool isDirectory /// when the operation succeeds or its condition is satisfied; otherwise, . /// public static bool IsGeneratedPath(string relativePath) - => relativePath.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase) || - relativePath.EndsWith(".abin", StringComparison.OrdinalIgnoreCase); + => relativePath.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase) + || relativePath.EndsWith(".abin", StringComparison.OrdinalIgnoreCase); private static void AddNonEmpty( HashSet target, IEnumerable? values ) { if (values is null) + { return; + } foreach (string value in values) { if (!string.IsNullOrWhiteSpace(value)) + { target.Add(value.Trim()); + } } } @@ -156,7 +169,9 @@ private static string[] Combine( foreach (string value in additional) { if (!string.IsNullOrWhiteSpace(value)) + { values.Add(value.Trim()); + } } } return values.ToArray(); diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSourceSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSourceSnapshot.cs index c6d02e17a..33571b922 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSourceSnapshot.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSourceSnapshot.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -45,7 +44,8 @@ public interface IAssetSourceSnapshot : IAssetArtifactLookup /// /// No compatible asset can be loaded from this view. /// - TAsset Load(AssetPath path) where TAsset : AssetObject; + TAsset Load(AssetPath path) + where TAsset : AssetObject; /// /// Resolves immutable catalog information by source path. @@ -63,5 +63,4 @@ bool TryGetInfo( AssetPath path, out AssetInfo? info ); - } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs index 4110039b8..2780e3d36 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs @@ -52,7 +52,9 @@ internal void Start() internal void Stop() { if (!m_disposed) + { m_watcher.EnableRaisingEvents = false; + } } internal WatcherPollResult Poll(bool force) @@ -63,7 +65,9 @@ internal WatcherPollResult Poll(bool force) lock (m_sync) { if (!force && m_pending.Count > 0 && !HasQuietPeriodElapsed()) + { return new WatcherPollResult(Array.Empty(), false); + } raw = m_pending.ToArray(); m_pending.Clear(); requiresFullRescan = m_requiresFullRescan; @@ -82,16 +86,20 @@ internal WatcherPollResult WaitForIdle() lock (m_sync) { if ((m_pending.Count > 0 || m_requiresFullRescan) && HasQuietPeriodElapsed()) - return PollWhileLocked(); - if (m_pending.Count == 0 && - !m_requiresFullRescan && - stopwatch.ElapsedMilliseconds >= Math.Max(m_flushDelayMs * 2L, 50L)) { + return PollWhileLocked(); + } + if (m_pending.Count == 0 + && !m_requiresFullRescan + && stopwatch.ElapsedMilliseconds >= Math.Max(m_flushDelayMs * 2L, 50L) + ) { return new WatcherPollResult(Array.Empty(), false); } } if (stopwatch.Elapsed > S_DEFAULT_IDLE_WAIT_TIMEOUT) + { throw new TimeoutException("Timed out waiting for AssetWatcher to become idle."); + } Thread.Sleep(Math.Min(m_flushDelayMs, 20)); } } @@ -102,7 +110,9 @@ internal WatcherPollResult WaitForIdle() public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_watcher.EnableRaisingEvents = false; m_watcher.Changed -= OnChanged; @@ -124,9 +134,7 @@ private WatcherPollResult PollWhileLocked() m_pending.Clear(); bool requiresFullRescan = m_requiresFullRescan; m_requiresFullRescan = false; - return new WatcherPollResult( - AssetChangeBatchNormalizer.Normalize(m_root, raw), - requiresFullRescan); + return new WatcherPollResult(AssetChangeBatchNormalizer.Normalize(m_root, raw), requiresFullRescan); } private bool HasQuietPeriodElapsed() @@ -155,7 +163,9 @@ ErrorEventArgs args lock (m_sync) { if (m_disposed) + { return; + } m_requiresFullRescan = true; m_lastEventTimestamp = Stopwatch.GetTimestamp(); } @@ -167,15 +177,21 @@ private void Enqueue( string oldRelativePath = "" ) { if (m_disposed) + { return; + } string relativePath = NormalizeRelativePath(Path.GetRelativePath(m_root, fullPath)); - if (AssetSourcePolicy.IsGeneratedPath(relativePath) && - !relativePath.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase)) + if (AssetSourcePolicy.IsGeneratedPath(relativePath) + && !relativePath.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase) + ) { return; + } lock (m_sync) { if (m_disposed) + { return; + } m_pending.Add(new AssetChangedEvent(relativePath, changeType, oldRelativePath)); m_lastEventTimestamp = Stopwatch.GetTimestamp(); } @@ -184,7 +200,9 @@ private void Enqueue( private void ThrowIfDisposed() { if (m_disposed) + { throw new ObjectDisposedException(nameof(AssetWatcher)); + } } private static string NormalizeRelativePath(string relativePath) diff --git a/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs b/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs index 811ce2596..622f9e3bd 100644 --- a/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs +++ b/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; using Inno.Core.IO; namespace Inno.Assets; @@ -29,8 +29,7 @@ public sealed class ArtifactRetention : AssetResidencyProvider public ArtifactLease Retain( AssetArtifactInfo artifact, Func openRead - ) - { + ) { ArgumentNullException.ThrowIfNull(artifact); ArgumentNullException.ThrowIfNull(openRead); AddPin(artifact.key); @@ -55,7 +54,9 @@ private void AddPin(AssetArtifactKey key) public IReadOnlyList GetRetainedKeys() { lock (m_sync) + { return Array.AsReadOnly(m_counts.Keys.ToArray()); + } } private Stream OpenPinned( @@ -80,9 +81,13 @@ private void Release(AssetArtifactKey key) { int remaining = m_counts[key] - 1; if (remaining == 0) + { m_counts.Remove(key); + } else + { m_counts[key] = remaining; + } } } diff --git a/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs b/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs index 04de82183..ac7923ca9 100644 --- a/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs +++ b/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs @@ -22,15 +22,21 @@ namespace Inno.Assets; public AssetArtifactKey(string value) { string normalized = string.IsNullOrWhiteSpace(value) - ? string.Empty - : value.Trim().ToUpperInvariant(); + ? string.Empty + : value.Trim().ToUpperInvariant(); if (normalized.Length != 0) { if (normalized.Length != C_SHA256_HEX_LENGTH) + { throw new ArgumentException("An artifact key must be a complete SHA-256 hexadecimal fingerprint.", nameof(value)); + } foreach (char digit in normalized) + { if (digit is not (>= '0' and <= '9') and not (>= 'A' and <= 'F')) + { throw new ArgumentException("An artifact key cannot contain non-hexadecimal characters.", nameof(value)); + } + } } m_value = normalized; } diff --git a/src/content/assets/Inno.Assets/AssetDependency.cs b/src/content/assets/Inno.Assets/AssetDependency.cs index 6a95d47d6..79ca8d6d1 100644 --- a/src/content/assets/Inno.Assets/AssetDependency.cs +++ b/src/content/assets/Inno.Assets/AssetDependency.cs @@ -1,5 +1,4 @@ using System; - using Inno.Extensibility.Types; using Inno.Scripting.Api; @@ -32,7 +31,9 @@ public AssetDependency( string lastKnownPath ) { if (persistentId == Guid.Empty) + { throw new ArgumentException("An asset dependency requires a persistent identity.", nameof(persistentId)); + } this.persistentId = persistentId; this.type = type; this.lastKnownPath = lastKnownPath ?? string.Empty; diff --git a/src/content/assets/Inno.Assets/AssetImportStatus.cs b/src/content/assets/Inno.Assets/AssetImportStatus.cs index c1cecdc4b..a569d6e7b 100644 --- a/src/content/assets/Inno.Assets/AssetImportStatus.cs +++ b/src/content/assets/Inno.Assets/AssetImportStatus.cs @@ -9,27 +9,22 @@ public enum AssetImportStatus /// No importer currently accepts the source. /// Unsupported, - /// /// The source is waiting for import or commit. /// Pending, - /// /// A valid artifact is committed for the source. /// Imported, - /// /// The latest import failed and diagnostics are available. /// Failed, - /// /// The source is unavailable while its persistent identity is retained. /// Missing, - /// /// The source cannot be reconciled without resolving an identity conflict. /// diff --git a/src/content/assets/Inno.Assets/AssetInfo.cs b/src/content/assets/Inno.Assets/AssetInfo.cs index 4277d9a04..923553553 100644 --- a/src/content/assets/Inno.Assets/AssetInfo.cs +++ b/src/content/assets/Inno.Assets/AssetInfo.cs @@ -54,7 +54,9 @@ public AssetInfo( ) { this.persistentId = persistentId; if (!assetPath.isValid) + { throw new ArgumentException("An asset information snapshot requires a valid path.", nameof(assetPath)); + } this.assetPath = assetPath; this.sourceKind = sourceKind; this.status = status; diff --git a/src/content/assets/Inno.Assets/AssetObject.cs b/src/content/assets/Inno.Assets/AssetObject.cs index 1906d3ef4..810d4ccf1 100644 --- a/src/content/assets/Inno.Assets/AssetObject.cs +++ b/src/content/assets/Inno.Assets/AssetObject.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Serialization; @@ -29,9 +28,10 @@ public abstract class AssetObject : IdentityObject, ISerializable /// /// Gets a display name derived from the source-local path. /// - public string name => string.IsNullOrWhiteSpace(assetPath.localPath) - ? GetType().Name - : Path.GetFileName(assetPath.localPath); + public string name + => string.IsNullOrWhiteSpace(assetPath.localPath) + ? GetType().Name + : Path.GetFileName(assetPath.localPath); /// /// Gets whether this instance represents an unavailable persistent asset. @@ -73,7 +73,9 @@ TValue target ) where TValue : class, ISerializable { if (m_runtimeResourcesReleased || m_propertyStateOwner is null || !m_propertyStateOwner.TryGetTarget(out var owner)) + { throw new InvalidOperationException("The asset's property-state owner is unavailable."); + } owner.RestoreProperties(stableTypeId, propertyData, target); } @@ -89,8 +91,7 @@ TValue target protected virtual void OnRuntimePayloadChanged( ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload - ) { - } + ) {} /// /// Releases the runtime resources owned by this asset without clearing its payload before quiescence. @@ -102,9 +103,7 @@ ReadOnlyMemory currentPayload /// /// Owned work has not quiesced; runtime payload and ownership must remain intact until a later attempt. /// - protected virtual void OnUnloading() - { - } + protected virtual void OnUnloading() {} internal string sourceHash => m_sourceHash; @@ -114,7 +113,9 @@ internal void ClaimRuntimeOwner( ) { object? previous = System.Threading.Interlocked.CompareExchange(ref m_runtimeOwner, authority, null); if (previous is not null && !ReferenceEquals(previous, authority)) + { throw new InvalidOperationException("The asset belongs to another runtime owner."); + } m_propertyStateOwner = properties; } @@ -161,7 +162,9 @@ internal void UpdateAssetPath(AssetPath assetPath) internal void ReleaseRuntimeResources() { if (m_runtimeResourcesReleased) + { return; + } try { OnUnloading(); diff --git a/src/content/assets/Inno.Assets/AssetPath.cs b/src/content/assets/Inno.Assets/AssetPath.cs index 858cc1495..b067bcfac 100644 --- a/src/content/assets/Inno.Assets/AssetPath.cs +++ b/src/content/assets/Inno.Assets/AssetPath.cs @@ -27,11 +27,12 @@ public AssetSourceId(string value) if (normalized.Any(static character => !(character is >= 'a' and <= 'z' || character is >= '0' and <= '9' - || character is '.' or '_' or '-'))) - { + || character is '.' or '_' or '-')) + ) { throw new ArgumentException( "An asset source ID may contain lowercase ASCII letters, digits, '.', '_', and '-' only.", - nameof(value)); + nameof(value) + ); } this.value = normalized; } @@ -76,7 +77,9 @@ public AssetPath( string localPath ) { if (!source.isValid) + { throw new ArgumentException("An asset source ID must be valid.", nameof(source)); + } this.source = source; this.localPath = NormalizeLocalPath(localPath); } @@ -121,8 +124,8 @@ public static AssetPath Parse(string value) ArgumentNullException.ThrowIfNull(value); int separator = value.IndexOf(C_SOURCE_SEPARATOR, StringComparison.Ordinal); return separator < 0 - ? Project(value) - : new AssetPath(new AssetSourceId(value[..separator]), value[(separator + C_SOURCE_SEPARATOR.Length)..]); + ? Project(value) + : new AssetPath(new AssetSourceId(value[..separator]), value[(separator + C_SOURCE_SEPARATOR.Length)..]); } /// @@ -133,8 +136,8 @@ public static AssetPath Parse(string value) /// public readonly override string ToString() => source == AssetSourceId.project - ? localPath ?? string.Empty - : $"{source}{C_SOURCE_SEPARATOR}{localPath}"; + ? localPath ?? string.Empty + : $"{source}{C_SOURCE_SEPARATOR}{localPath}"; private static string NormalizeLocalPath(string value) { @@ -142,17 +145,19 @@ private static string NormalizeLocalPath(string value) if (Path.IsPathRooted(value) || value.StartsWith("/", StringComparison.Ordinal) || value.StartsWith('\\') - || value.Length >= 2 && char.IsAsciiLetter(value[0]) && value[1] == ':') - { + || value.Length >= 2 && char.IsAsciiLetter(value[0]) && value[1] == ':' + ) { throw new ArgumentException("An asset path must be source-relative.", nameof(value)); } string path = value.Replace('\\', '/').Trim(); while (path.StartsWith("./", StringComparison.Ordinal)) + { path = path[2..]; + } path = path.Trim('/'); if (path.Split('/', StringSplitOptions.RemoveEmptyEntries) - .Any(static segment => segment is "." or "..")) - { + .Any(static segment => segment is "." or "..") + ) { throw new ArgumentException("An asset path cannot contain traversal segments.", nameof(value)); } return path; diff --git a/src/content/assets/Inno.Assets/AssetReferenceKind.cs b/src/content/assets/Inno.Assets/AssetReferenceKind.cs index a95d7459b..f0a8335b4 100644 --- a/src/content/assets/Inno.Assets/AssetReferenceKind.cs +++ b/src/content/assets/Inno.Assets/AssetReferenceKind.cs @@ -1,4 +1,5 @@ using Inno.Runtime.Contracts; + namespace Inno.Assets; /// diff --git a/src/content/assets/Inno.Assets/AssetSourceKind.cs b/src/content/assets/Inno.Assets/AssetSourceKind.cs index c49702179..fbeed432d 100644 --- a/src/content/assets/Inno.Assets/AssetSourceKind.cs +++ b/src/content/assets/Inno.Assets/AssetSourceKind.cs @@ -9,7 +9,6 @@ public enum AssetSourceKind /// A regular imported source file. /// File, - /// /// A source directory with persistent identity but no runtime artifact. /// diff --git a/src/content/assets/Inno.Assets/Changes/AssetChangeKind.cs b/src/content/assets/Inno.Assets/Changes/AssetChangeKind.cs index 5a57a4618..815bc378e 100644 --- a/src/content/assets/Inno.Assets/Changes/AssetChangeKind.cs +++ b/src/content/assets/Inno.Assets/Changes/AssetChangeKind.cs @@ -9,32 +9,26 @@ public enum AssetChangeKind /// A source was added to the database. /// Added, - /// /// An existing source or artifact changed. /// Modified, - /// /// A source moved while retaining its persistent identity. /// Moved, - /// /// A source and its persistent metadata were removed. /// Removed, - /// /// A source became unavailable while retaining its identity. /// Missing, - /// /// A canonical runtime object was replaced by an incompatible imported type. /// Replaced, - /// /// An import status or diagnostic changed without replacing the source. /// diff --git a/src/content/assets/Inno.Assets/Properties/ScriptingApi.cs b/src/content/assets/Inno.Assets/Properties/ScriptingApi.cs index 65e762588..6fdb33b0c 100644 --- a/src/content/assets/Inno.Assets/Properties/ScriptingApi.cs +++ b/src/content/assets/Inno.Assets/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Assets; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Assets", - "Inno.Assets", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Assets", "Inno.Assets", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AssetDependency), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AssetPropertySnapshot), ScriptingApiScope.Runtime)] diff --git a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs index c74485b1a..5ea5e88a4 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs @@ -35,8 +35,18 @@ public AssetPreparationStatistics preparationStatistics get { lock (m_sync) - return new(m_pendingLoads.Count, m_peakPendingLoads, m_rejectedLoads, m_payloadReads.Count, - m_payloadReadsStarted, m_payloadReadsShared, m_preparingBytes, m_peakPreparingBytes); + { + return new( + m_pendingLoads.Count, + m_peakPendingLoads, + m_rejectedLoads, + m_payloadReads.Count, + m_payloadReadsStarted, + m_payloadReadsShared, + m_preparingBytes, + m_peakPreparingBytes + ); + } } } @@ -48,7 +58,9 @@ public long preparingBytes get { lock (m_sync) + { return m_preparingBytes; + } } } @@ -110,7 +122,9 @@ CancellationToken cancellationToken throw new InvalidOperationException("Runtime asset preparation is at capacity; retry after the next completion safety point."); } if (!typeof(TAsset).IsAssignableFrom(ResolveType(record))) + { throw new InvalidOperationException($"Runtime asset '{record.path}' is not compatible with '{typeof(TAsset).FullName}'."); + } if (!m_preparations.TryGetValue(record.persistentId, out SharedPreparation? shared)) { @@ -136,7 +150,9 @@ CancellationToken cancellationToken m_payloadReadsStarted++; } else + { m_payloadReadsShared++; + } payload.owners++; payloads.Add(payload); } @@ -147,20 +163,31 @@ CancellationToken cancellationToken catch { foreach (SharedPayload payload in payloads) + { ReleasePayload(payload); + } throw; } } shared.waiters++; var completion = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); - m_pendingLoads.Add(new PendingAcquisition(shared.preparation, cancellationToken, payloads => - { - TAsset asset = LoadRecord(record, pin: false, payloads); - record.leaseCount++; - completion.SetResult(CreateResidencyLease(record, asset)); - }, exception => completion.TrySetException(exception), - () => completion.TrySetCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)), - () => ReleasePreparation(record.persistentId, shared))); + m_pendingLoads.Add( + new PendingAcquisition( + shared.preparation, + cancellationToken, + payloads => + { + TAsset asset = LoadRecord(record, pin: false, payloads); + record.leaseCount++; + completion.SetResult(CreateResidencyLease(record, asset)); + }, + exception => completion.TrySetException(exception), + () => completion.TrySetCanceled( + cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true) + ), + () => ReleasePreparation(record.persistentId, shared) + ) + ); m_peakPendingLoads = Math.Max(m_peakPendingLoads, m_pendingLoads.Count); return new ValueTask>(completion.Task); } @@ -168,8 +195,7 @@ CancellationToken cancellationToken private AssetLease CreateResidencyLease( RuntimeAssetRecord record, TAsset asset - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { bool released = false; return CreateAssetLease(asset, () => ReleaseLease(record, ref released)); @@ -181,14 +207,26 @@ private void CollectPayloadReads( List reads ) { if (!visited.Add(record.persistentId)) + { return; + } RuntimeArtifactOutput output = ReadArtifactManifest(record).outputs.Single(candidate => candidate.name == "runtime"); if (output.length < 0 || output.length > int.MaxValue) + { throw new InvalidDataException("A runtime payload length is outside the supported allocation range."); - reads.Add(new PayloadRead(record.persistentId, - GetVerifiedOutputKey(record, output), output.length, output.contentHash)); + } + reads.Add( + new PayloadRead( + record.persistentId, + GetVerifiedOutputKey(record, output), + output.length, + output.contentHash + ) + ); foreach (AssetDependency dependency in record.dependencies) + { CollectPayloadReads(m_recordsById[dependency.persistentId], visited, reads); + } } private static async Task ReadPayloadAsync( @@ -217,18 +255,24 @@ CancellationToken token byte[] bytes = new byte[checked((int)read.length)]; await stream.ReadExactlyAsync(bytes, token).ConfigureAwait(false); token.ThrowIfCancellationRequested(); - if (stream.ReadByte() != -1 || bytes.LongLength != read.length || - !string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), read.hash, StringComparison.OrdinalIgnoreCase)) + if (stream.ReadByte() != -1 || bytes.LongLength != read.length + || !string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), read.hash, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidDataException($"Runtime payload '{read.id:D}' failed integrity verification."); + } return bytes; } private static Task> StartPayloadPreparation(SharedPayload[] reads) { if (ExecutionContext.IsFlowSuppressed()) + { return AssemblePayloadsAsync(reads); + } using (ExecutionContext.SuppressFlow()) + { return AssemblePayloadsAsync(reads); + } } private static async Task> AssemblePayloadsAsync(SharedPayload[] reads) @@ -241,9 +285,13 @@ private static async Task> AssemblePayloadsAsync(Shared private void CancelPendingLoads() { foreach (SharedPayload preparation in m_payloadReads.Values) + { preparation.cancellation.Cancel(); + } foreach (PendingAcquisition request in m_pendingLoads) + { request.Cancel(); + } m_pendingLoads.Clear(); } @@ -252,16 +300,22 @@ private void ReleasePreparation( SharedPreparation preparation ) { if (--preparation.waiters != 0) + { return; + } m_preparations.Remove(id); foreach (SharedPayload payload in preparation.payloads) + { ReleasePayload(payload); + } } private void ReleasePayload(SharedPayload payload) { if (--payload.owners != 0) + { return; + } payload.cancellation.Cancel(); try { @@ -276,7 +330,9 @@ private void ReleasePayload(SharedPayload payload) private void EnsureResidencyOwner() { if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Runtime asset acquisition and publication require the database owner thread."); + } } private sealed record PayloadRead( @@ -306,11 +362,15 @@ SemaphoreSlim slots try { if (ExecutionContext.IsFlowSuppressed()) + { preparation = Task.Run(() => PrepareAsync(read, lease, cancellation.Token, slots)); + } else { using (ExecutionContext.SuppressFlow()) + { preparation = Task.Run(() => PrepareAsync(read, lease, cancellation.Token, slots)); + } } } catch @@ -333,7 +393,9 @@ private static async Task PrepareAsync( SemaphoreSlim slots ) { using (lease) + { return await ReadPayloadAsync(read, lease, cancellation, slots).ConfigureAwait(false); + } } } diff --git a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs index 5480227d3..95bef6776 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs @@ -6,11 +6,11 @@ using System.Threading; using System.Threading.Tasks; using Inno.Assets; +using Inno.Content; using Inno.Core.Execution; using Inno.Core.Identity; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Inno.Content; +using Inno.Extensibility.Types; namespace Inno.Assets; @@ -70,7 +70,9 @@ TValue target ObjectDisposedException.ThrowIf(m_disposed, this); ArgumentNullException.ThrowIfNull(target); if (m_types!.GetTypeRef(target.GetType()).stableId != stableTypeId) + { throw new InvalidOperationException("The asset property payload has an incompatible stable type identity."); + } m_serialization.Decode(propertyData, reader => { reader.RestoreProperties(target); @@ -128,15 +130,20 @@ public AssetDatabase( m_residencyBudgetBytes = residencyBudgetBytes; m_preparationBudgetBytes = preparationBudgetBytes; RuntimeAssetCatalog catalog = m_serialization.Deserialize( - ReadContent(new ContentKey("AssetDatabase/Catalog.snapshot"))); + ReadContent(new ContentKey("AssetDatabase/Catalog.snapshot")) + ); for (int index = 0; index < catalog.entries.Length; index++) { RuntimeAssetData data = m_serialization.Deserialize(catalog.entries[index]); RuntimeAssetRecord record = ValidateRecord(data, index); if (!m_recordsByPath.TryAdd(record.path, record)) + { throw new InvalidDataException($"Runtime catalog repeats asset path '{record.path}'."); + } if (!m_recordsById.TryAdd(record.persistentId, record)) + { throw new InvalidDataException($"Runtime catalog repeats asset identity '{record.persistentId:D}'."); + } } foreach (RuntimeAssetRecord record in m_recordsByPath.Values) { @@ -145,8 +152,9 @@ public AssetDatabase( if (!m_recordsById.ContainsKey(record.dependencies[index].persistentId)) { throw new InvalidDataException( - $"Runtime asset '{record.path}' depends on missing asset " + - $"'{record.dependencies[index].persistentId:D}'."); + $"Runtime asset '{record.path}' depends on missing asset " + + $"'{record.dependencies[index].persistentId:D}'." + ); } } ValidateArtifactBundle(record); @@ -179,7 +187,9 @@ public TAsset Load(AssetPath path) { EnsureActive(); if (!m_recordsByPath.TryGetValue(path, out RuntimeAssetRecord? record)) + { throw new InvalidOperationException($"Runtime asset '{path}' is not present in the deployed catalog."); + } return LoadRecord(record, pin: true); } } @@ -210,7 +220,9 @@ public TAsset Load(Guid persistentId) { EnsureActive(); if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record)) + { throw new InvalidOperationException($"Runtime asset '{persistentId:D}' is not present in the deployed catalog."); + } return LoadRecord(record, pin: true); } } @@ -237,15 +249,14 @@ public TAsset Load(Guid persistentId) public bool TryLoad( AssetPath path, out TAsset? asset - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { lock (m_sync) { EnsureActive(); if (!m_recordsByPath.TryGetValue(path, out RuntimeAssetRecord? record) - || !typeof(TAsset).IsAssignableFrom(ResolveType(record))) - { + || !typeof(TAsset).IsAssignableFrom(ResolveType(record)) + ) { asset = null; return false; } @@ -276,15 +287,14 @@ out TAsset? asset public bool TryLoad( Guid persistentId, out TAsset? asset - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { lock (m_sync) { EnsureActive(); if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record) - || !typeof(TAsset).IsAssignableFrom(ResolveType(record))) - { + || !typeof(TAsset).IsAssignableFrom(ResolveType(record)) + ) { asset = null; return false; } @@ -306,7 +316,8 @@ public AssetResidencyStatistics residencyStatistics return new AssetResidencyStatistics( m_recordsByPath.Values.Count(static record => record.asset is not null), m_residentBytes, - m_residencyBudgetBytes); + m_residencyBudgetBytes + ); } } } @@ -329,15 +340,16 @@ public AssetResidencyStatistics residencyStatistics public ValueTask> AcquireAsync( AssetPath path, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { cancellationToken.ThrowIfCancellationRequested(); lock (m_sync) { EnsureActive(); if (!m_recordsByPath.TryGetValue(path, out RuntimeAssetRecord? record)) + { throw new InvalidOperationException($"Runtime asset '{path}' is not present in the deployed catalog."); + } return QueueAcquisition(record, cancellationToken); } } @@ -360,8 +372,7 @@ public ValueTask> AcquireAsync( public ValueTask> AcquireAsync( Guid persistentId, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { cancellationToken.ThrowIfCancellationRequested(); lock (m_sync) @@ -370,7 +381,8 @@ public ValueTask> AcquireAsync( if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record)) { throw new InvalidOperationException( - $"Runtime asset '{persistentId:D}' is not present in the deployed catalog."); + $"Runtime asset '{persistentId:D}' is not present in the deployed catalog." + ); } return QueueAcquisition(record, cancellationToken); } @@ -398,8 +410,8 @@ public IReadOnlyList GetDependencies(AssetObject asset) { EnsureActive(); if (!m_recordsById.TryGetValue(asset.identity.persistentId, out RuntimeAssetRecord? record) - || !ReferenceEquals(record.asset, asset)) - { + || !ReferenceEquals(record.asset, asset) + ) { throw new InvalidOperationException("Only an asset owned by this database has runtime dependencies."); } return record.dependencies.ToArray(); @@ -436,17 +448,22 @@ out AssetArtifactInfo? artifact EnsureActive(); artifact = null; if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record)) + { return false; + } RuntimeArtifactOutput output = ReadArtifactManifest(record).outputs.FirstOrDefault(candidate => string.Equals(candidate.name, outputName, StringComparison.Ordinal)); if (string.IsNullOrWhiteSpace(output.name)) + { return false; + } _ = GetVerifiedOutputKey(record, output); artifact = new AssetArtifactInfo( new AssetArtifactKey(record.artifactKey), output.name, output.contentHash, - output.length); + output.length + ); return true; } } @@ -472,7 +489,8 @@ string outputName if (!TryGetArtifact(persistentId, outputName, out AssetArtifactInfo? artifact) || artifact is null) { throw new InvalidOperationException( - $"Runtime asset '{persistentId:D}' has no verified artifact output '{outputName}'."); + $"Runtime asset '{persistentId:D}' has no verified artifact output '{outputName}'." + ); } RuntimeAssetRecord record = m_recordsById[persistentId]; RuntimeArtifactOutput output = ReadArtifactManifest(record).outputs.Single(candidate => candidate.name == outputName); @@ -510,14 +528,20 @@ public void Dispose() lock (m_sync) { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new LifetimeScope(); m_retirement.Own(m_payloadReadSlots); foreach (RuntimeAssetRecord record in m_recordsById.Values) + { if (record.asset is not null) + { m_retirement.Own(new RuntimeAssetRetirement(this, record)); + } + } } CancelPendingLoads(); try @@ -551,30 +575,38 @@ private TAsset LoadRecord( RuntimeAssetRecord record, bool pin, IReadOnlyDictionary? preparedPayloads = null - ) - where TAsset : AssetObject + ) where TAsset : AssetObject { if (record.isRetiring) + { Evict(record); + } Type actualType = ResolveType(record); if (!typeof(TAsset).IsAssignableFrom(actualType)) { throw new InvalidOperationException( - $"Runtime asset '{record.path}' has type '{actualType.FullName}', not '{typeof(TAsset).FullName}'."); + $"Runtime asset '{record.path}' has type '{actualType.FullName}', not '{typeof(TAsset).FullName}'." + ); } record.isPinned |= pin; record.lastAccess = ++m_accessSequence; if (record.asset is TAsset loaded) + { return loaded; + } var created = new List(); try { PrepareShells(record, created); for (int index = 0; index < created.Count; index++) + { Hydrate(created[index], preparedPayloads); + } for (int index = 0; index < created.Count; index++) + { RetainDependencies(created[index]); + } return (TAsset)record.asset!; } catch @@ -583,7 +615,9 @@ private TAsset LoadRecord( { RuntimeAssetRecord createdRecord = created[index]; if (createdRecord.asset is null) + { continue; + } m_dependencyRetention.Remove(createdRecord.asset); m_residentBytes -= createdRecord.runtimeBytes; createdRecord.runtimeBytes = 0; @@ -600,7 +634,9 @@ private void PrepareShells( ICollection created ) { if (record.asset is not null) + { return; + } Type type = ResolveType(record); AssetObject asset; try @@ -611,14 +647,17 @@ ICollection created { throw new InvalidOperationException( $"Runtime asset type '{type.FullName}' requires a parameterless constructor.", - exception); + exception + ); } m_identities.InitializePersistentIdentity(asset, record.persistentId); m_identities.Register(asset, record.persistentId); record.asset = asset; created.Add(record); for (int index = 0; index < record.dependencies.Length; index++) + { PrepareShells(m_recordsById[record.dependencies[index].persistentId], created); + } } private void Hydrate( @@ -633,7 +672,9 @@ private void Hydrate( }, m_serializationContext); byte[] payload; if (preparedPayloads is not null) + { payload = preparedPayloads[record.persistentId]; + } else { RuntimeArtifactOutput output = ReadArtifactManifest(record).outputs.Single(candidate => @@ -648,8 +689,10 @@ private void Hydrate( private void RetainDependencies(RuntimeAssetRecord record) { AssetObject[] dependencies = record.dependencies - .Select(dependency => m_recordsById[dependency.persistentId].asset - ?? throw new InvalidOperationException("A runtime dependency was not prepared.")) + .Select(dependency => ( + m_recordsById[dependency.persistentId].asset + ?? throw new InvalidOperationException("A runtime dependency was not prepared.") + )) .ToArray(); m_dependencyRetention[record.asset!] = dependencies; } @@ -661,11 +704,15 @@ ref bool released lock (m_sync) { if (m_disposed || m_retirement is not null) + { return; + } if (!released) { if (record.leaseCount <= 0) + { throw new InvalidOperationException("Runtime asset residency has no matching lease to release."); + } record.leaseCount--; released = true; record.lastAccess = ++m_accessSequence; @@ -685,7 +732,9 @@ private int TrimToBudgetLocked() .ThenBy(static record => record.path.ToString(), StringComparer.Ordinal) .FirstOrDefault(); if (candidate is null) + { break; + } Evict(candidate); released++; } @@ -696,11 +745,15 @@ private bool CanEvict(RuntimeAssetRecord record) { AssetObject? asset = record.asset; if (asset is null || record.isPinned || record.leaseCount != 0) + { return false; + } foreach ((AssetObject owner, AssetObject[] dependencies) in m_dependencyRetention) { if (!ReferenceEquals(owner, asset) && dependencies.Contains(asset, ReferenceEqualityComparer.Instance)) + { return false; + } } return true; } @@ -708,7 +761,7 @@ private bool CanEvict(RuntimeAssetRecord record) private void Evict(RuntimeAssetRecord record) { AssetObject asset = record.asset - ?? throw new InvalidOperationException("Only a materialized asset can be evicted."); + ?? throw new InvalidOperationException("Only a materialized asset can be evicted."); record.isRetiring = true; List failures = []; try @@ -741,7 +794,9 @@ private void Evict(RuntimeAssetRecord record) record.runtimeBytes = 0; record.isRetiring = false; if (failures.Count > 0) + { throw new AggregateException("Runtime asset retirement failed after releasing its registration.", failures); + } } AssetObject IAssetReferenceResolver.Resolve( @@ -750,8 +805,7 @@ AssetObject IAssetReferenceResolver.Resolve( string lastKnownPath, Type expectedType, string propertyPath - ) - => ResolveReference(persistentId, stableTypeId, expectedType, propertyPath, requirePrepared: false); + ) => ResolveReference(persistentId, stableTypeId, expectedType, propertyPath, requirePrepared: false); private AssetObject ResolveReference( Guid persistentId, @@ -763,16 +817,25 @@ bool requirePrepared lock (m_sync) { EnsureActive(); - if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record) || - (requirePrepared && record.asset is null)) + if (!m_recordsById.TryGetValue(persistentId, out RuntimeAssetRecord? record) + || (requirePrepared && record.asset is null) + ) { throw new InvalidDataException( - $"Asset reference '{persistentId:D}' at '{propertyPath}' is outside the deployed runtime closure."); + $"Asset reference '{persistentId:D}' at '{propertyPath}' is outside the deployed runtime closure." + ); + } if (stableTypeId != Guid.Empty && record.stableTypeId != stableTypeId) + { throw new InvalidDataException( - $"Asset reference '{persistentId:D}' at '{propertyPath}' has a mismatched stable type identity."); + $"Asset reference '{persistentId:D}' at '{propertyPath}' has a mismatched stable type identity." + ); + } if (!expectedType.IsAssignableFrom(ResolveType(record))) + { throw new InvalidDataException( - $"Asset reference '{persistentId:D}' at '{propertyPath}' is incompatible with '{expectedType.FullName}'."); + $"Asset reference '{persistentId:D}' at '{propertyPath}' is incompatible with '{expectedType.FullName}'." + ); + } return requirePrepared ? record.asset! : LoadRecord(record, pin: true); } } @@ -782,17 +845,29 @@ private RuntimeAssetRecord ValidateRecord( int index ) { if (data.persistentId == Guid.Empty) + { throw new InvalidDataException($"Runtime catalog entry {index} has no persistent identity."); + } if (data.stableAssetTypeId == Guid.Empty) + { throw new InvalidDataException($"Runtime catalog entry {index} has no stable asset type identity."); + } if (data.isDirectory || data.isTombstone) + { throw new InvalidDataException($"Runtime catalog entry {index} is not a live deployable asset."); + } if (data.deploymentScope != 0 || data.importStatus != (int)AssetImportStatus.Imported) + { throw new InvalidDataException($"Runtime catalog entry {index} is not a successfully imported runtime asset."); + } if (data.assetStateBytes.Length == 0) + { throw new InvalidDataException($"Runtime catalog entry {index} has no serialized asset state."); + } if (data.artifactKey.Length != 64 || data.artifactKey.Any(static character => !Uri.IsHexDigit(character))) + { throw new InvalidDataException($"Runtime catalog entry {index} has an invalid artifact identity."); + } AssetPath path; try { @@ -805,7 +880,8 @@ int index AssetDependency[] dependencies = data.runtimeDependencies.Select(dependency => new AssetDependency( dependency.persistentId, new TypeRef(dependency.stableTypeId), - dependency.lastKnownPath ?? string.Empty)).ToArray(); + dependency.lastKnownPath ?? string.Empty + )).ToArray(); return new RuntimeAssetRecord( data.persistentId, path, @@ -813,7 +889,8 @@ int index data.stableAssetTypeId, data.artifactKey.ToUpperInvariant(), data.assetStateBytes, - dependencies); + dependencies + ); } private Type ResolveType(RuntimeAssetRecord record) @@ -822,7 +899,8 @@ private Type ResolveType(RuntimeAssetRecord record) if (!typeof(AssetObject).IsAssignableFrom(type) || type.IsAbstract) { throw new InvalidDataException( - $"Runtime asset '{record.path}' resolves to invalid type '{type.FullName}'."); + $"Runtime asset '{record.path}' resolves to invalid type '{type.FullName}'." + ); } return type; } @@ -831,17 +909,22 @@ private void ValidateArtifactBundle(RuntimeAssetRecord record) { RuntimeArtifactManifest manifest = ReadArtifactManifest(record); if (!string.Equals(manifest.key, record.artifactKey, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidDataException($"Runtime artifact bundle '{record.artifactKey}' has a mismatched manifest identity."); + } string[] names = manifest.outputs.Select(static output => output.name).ToArray(); if (names.Distinct(StringComparer.Ordinal).Count() != names.Length || !names.Contains("asset-state", StringComparer.Ordinal) - || !names.Contains("runtime", StringComparer.Ordinal)) - { + || !names.Contains("runtime", StringComparer.Ordinal) + ) { throw new InvalidDataException( - $"Runtime artifact bundle '{record.artifactKey}' does not contain one complete asset-state/runtime pair."); + $"Runtime artifact bundle '{record.artifactKey}' does not contain one complete asset-state/runtime pair." + ); } foreach (RuntimeArtifactOutput output in manifest.outputs) + { _ = GetVerifiedOutputKey(record, output); + } } private RuntimeArtifactManifest ReadArtifactManifest(RuntimeAssetRecord record) @@ -855,17 +938,23 @@ private ContentKey GetVerifiedOutputKey( RuntimeArtifactOutput output ) { if (string.IsNullOrWhiteSpace(output.name) || string.IsNullOrWhiteSpace(output.fileName) - || output.fileName.Contains('/') || output.fileName.Contains('\\')) - { + || output.fileName.Contains('/') || output.fileName.Contains('\\') + ) { throw new InvalidDataException($"Runtime artifact bundle '{record.artifactKey}' contains an invalid output path."); } ContentKey key = new(GetBundleRoot(record.artifactKey) + "/outputs/" + output.fileName); if (!m_content.index.TryGetEntry(key, out ContentEntry? entry)) + { throw new InvalidDataException($"Runtime artifact output '{record.artifactKey}/{output.name}' is missing."); + } if (entry!.length != output.length) + { throw new InvalidDataException($"Runtime artifact output '{record.artifactKey}/{output.name}' has an invalid length."); + } if (!string.Equals(entry.contentHash, output.contentHash, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidDataException($"Runtime artifact output '{record.artifactKey}/{output.name}' failed hash verification."); + } return key; } @@ -876,13 +965,19 @@ private byte[] ReadContent(ContentKey key) { using ContentReadLease lease = m_content.Acquire(key); if (lease.entry.length > Array.MaxLength) + { throw new InvalidDataException($"Content '{key}' exceeds the supported array budget."); + } using Stream input = lease.OpenRead(); byte[] bytes = new byte[(int)lease.entry.length]; input.ReadExactly(bytes); - if (input.ReadByte() != -1 || !string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), - lease.entry.contentHash, StringComparison.Ordinal)) + if (input.ReadByte() != -1 || !string.Equals( + Convert.ToHexString(SHA256.HashData(bytes)), + lease.entry.contentHash, + StringComparison.Ordinal + )) { throw new InvalidDataException($"Content '{key}' failed integrity verification."); + } return bytes; } @@ -917,8 +1012,7 @@ public AssetObject Resolve( string lastKnownPath, Type expectedType, string propertyPath - ) - => owner.ResolveReference(persistentId, stableTypeId, expectedType, propertyPath, requirePrepared: true); + ) => owner.ResolveReference(persistentId, stableTypeId, expectedType, propertyPath, requirePrepared: true); } private sealed class RuntimeAssetRetirement( @@ -932,7 +1026,9 @@ RuntimeAssetRecord record public void Dispose() { if (record.asset is not null) + { owner.Evict(record); + } } } diff --git a/src/content/assets/Inno.Assets/Runtime/AssetExecutionContext.cs b/src/content/assets/Inno.Assets/Runtime/AssetExecutionContext.cs index 72872f766..bdd8accaa 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetExecutionContext.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetExecutionContext.cs @@ -1,6 +1,6 @@ -using Inno.Core.Execution; using System; using System.Threading; +using Inno.Core.Execution; namespace Inno.Assets; @@ -40,5 +40,4 @@ public static IDisposable EnterScope(IAssetLookup assets) ArgumentNullException.ThrowIfNull(assets); return S_CURRENT_SCOPE.Enter(assets); } - } diff --git a/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs b/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs index d1209c872..6201b0fa6 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs @@ -29,8 +29,7 @@ public interface IAssetResidency ValueTask> AcquireAsync( AssetPath path, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject; + ) where TAsset : AssetObject; /// /// Acquires a canonical asset by persistent identity and keeps it resident until release. @@ -50,8 +49,7 @@ ValueTask> AcquireAsync( ValueTask> AcquireAsync( Guid persistentId, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject; + ) where TAsset : AssetObject; /// /// Acquires one verified immutable artifact output. @@ -97,8 +95,7 @@ public abstract class AssetResidencyProvider protected static AssetLease CreateAssetLease( TAsset asset, Action release - ) - where TAsset : AssetObject + ) where TAsset : AssetObject => new(asset, release); /// @@ -216,12 +213,16 @@ public byte[] ReadAllBytes() { long length = info.length; if (length < 0 || length > Array.MaxLength) + { throw new InvalidDataException("The artifact payload exceeds the supported array budget."); + } using Stream input = OpenRead(); byte[] bytes = new byte[(int)length]; input.ReadExactly(bytes); if (input.ReadByte() != -1) + { throw new InvalidDataException("The artifact payload exceeds its indexed length."); + } return bytes; } @@ -242,7 +243,9 @@ public byte[] ReadAllBytes() public void Dispose() { lock (m_sync) + { m_openRead = null; + } m_residency.Dispose(); } } diff --git a/src/content/assets/Inno.Assets/Runtime/Assets.cs b/src/content/assets/Inno.Assets/Runtime/Assets.cs index d04393cce..77d0541c3 100644 --- a/src/content/assets/Inno.Assets/Runtime/Assets.cs +++ b/src/content/assets/Inno.Assets/Runtime/Assets.cs @@ -39,7 +39,9 @@ public static AssetPath LocalPath( ArgumentNullException.ThrowIfNull(localPath); ArgumentNullException.ThrowIfNull(sourceFile); if (!sourceFile.Contains("::", StringComparison.Ordinal)) + { throw new InvalidOperationException("Source-local Asset paths require a compiler-supplied canonical source location."); + } AssetSourceId source; try { @@ -69,7 +71,7 @@ public static AssetPath LocalPath( /// public static TAsset Load(AssetPath path) where TAsset : AssetObject - => AssetExecutionContext.current.Load(path); + => AssetExecutionContext.current.Load(path); /// /// Loads the canonical asset with a persistent identity in the current session. @@ -88,7 +90,7 @@ public static TAsset Load(AssetPath path) /// public static TAsset Load(Guid persistentId) where TAsset : AssetObject - => AssetExecutionContext.current.Load(persistentId); + => AssetExecutionContext.current.Load(persistentId); /// /// Tries to load the canonical asset at a logical catalog path in the current session. @@ -112,8 +114,7 @@ public static TAsset Load(Guid persistentId) public static bool TryLoad( AssetPath path, out TAsset? asset - ) - where TAsset : AssetObject + ) where TAsset : AssetObject => AssetExecutionContext.current.TryLoad(path, out asset); /// @@ -138,8 +139,7 @@ out TAsset? asset public static bool TryLoad( Guid persistentId, out TAsset? asset - ) - where TAsset : AssetObject + ) where TAsset : AssetObject => AssetExecutionContext.current.TryLoad(persistentId, out asset); /// @@ -160,8 +160,7 @@ out TAsset? asset public static ValueTask> AcquireAsync( AssetPath path, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject => GetResidency().AcquireAsync(path, cancellationToken); /// @@ -182,8 +181,7 @@ public static ValueTask> AcquireAsync( public static ValueTask> AcquireAsync( Guid persistentId, CancellationToken cancellationToken = default - ) - where TAsset : AssetObject + ) where TAsset : AssetObject => GetResidency().AcquireAsync(persistentId, cancellationToken); /// @@ -201,11 +199,11 @@ public static ValueTask> AcquireAsync( public static ArtifactLease AcquireArtifact( Guid persistentId, string outputName - ) - => GetResidency().AcquireArtifact(persistentId, outputName); + ) => GetResidency().AcquireArtifact(persistentId, outputName); private static IAssetResidency GetResidency() => AssetExecutionContext.current as IAssetResidency - ?? throw new InvalidOperationException( - "The current asset lookup does not provide explicit residency ownership."); + ?? throw new InvalidOperationException( + "The current asset lookup does not provide explicit residency ownership." + ); } diff --git a/src/content/assets/Inno.Assets/Runtime/IAssetLookup.cs b/src/content/assets/Inno.Assets/Runtime/IAssetLookup.cs index f8f3e3ba0..a3f7031f0 100644 --- a/src/content/assets/Inno.Assets/Runtime/IAssetLookup.cs +++ b/src/content/assets/Inno.Assets/Runtime/IAssetLookup.cs @@ -62,8 +62,7 @@ TAsset Load(Guid persistentId) bool TryLoad( AssetPath path, out TAsset? asset - ) - where TAsset : AssetObject; + ) where TAsset : AssetObject; /// /// Tries to load the canonical asset with a persistent identity. @@ -84,6 +83,5 @@ out TAsset? asset bool TryLoad( Guid persistentId, out TAsset? asset - ) - where TAsset : AssetObject; + ) where TAsset : AssetObject; } diff --git a/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs b/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs index d9bd15f9d..79f8bf920 100644 --- a/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs +++ b/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs @@ -4,7 +4,8 @@ namespace Inno.Assets; -internal sealed class ResidencyLease : IDisposable where TValue : class +internal sealed class ResidencyLease : IDisposable + where TValue : class { private readonly object m_sync = new(); private TValue? m_value; @@ -25,7 +26,9 @@ internal TValue value get { lock (m_sync) + { return m_value ?? throw new ObjectDisposedException("Residency lease"); + } } } @@ -41,9 +44,13 @@ public void Dispose() lock (m_sync) { if (m_release is null) + { return; + } if (m_releasing) + { throw new RetirementPendingException("Residency release is already being advanced by another invocation."); + } m_releasing = true; release = m_release; } @@ -56,7 +63,9 @@ public void Dispose() m_completedFailures ??= []; RetirementPendingException.CollectCompletedFailures(pendingRetirement, m_completedFailures); lock (m_sync) + { m_releasing = false; + } throw; } catch (Exception exception) @@ -71,7 +80,9 @@ public void Dispose() } Finish(); if (m_completedFailures is { Count: > 0 }) + { throw TakeCompletedFailure(); + } } private void Finish() diff --git a/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs b/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs index 5931938c6..d1d71a218 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; using Inno.Extensibility.Types; @@ -22,9 +21,7 @@ public sealed class AssetDependencyCollection /// Creates a dependency collector that preserves last-known source paths in serialized references. /// public AssetDependencyCollection() - : this(includeLastKnownPaths: true) - { - } + : this(includeLastKnownPaths: true) {} /// /// Creates a dependency collector with an explicit location-hint policy. @@ -48,8 +45,8 @@ public AssetDependencyCollection(bool includeLastKnownPaths) /// public IReadOnlyList dependencies => m_dependencies is null || m_dependencies.Count == 0 - ? Array.Empty() - : m_dependencies.Values.OrderBy(static dependency => dependency.persistentId).ToArray(); + ? Array.Empty() + : m_dependencies.Values.OrderBy(static dependency => dependency.persistentId).ToArray(); internal void Add( AssetObject asset, @@ -59,17 +56,21 @@ TypeCatalog types ArgumentNullException.ThrowIfNull(types); Guid persistentId = asset.identity.persistentId; if (persistentId == Guid.Empty) + { throw new InvalidOperationException($"Asset '{asset.GetType().FullName}' has no persistent identity."); + } if (!types.TryGetTypeRef(asset.GetType(), out TypeRef typeRef)) { throw new InvalidOperationException( - $"Asset type '{asset.GetType().FullName}' requires a StableTypeId before it can be referenced persistently."); + $"Asset type '{asset.GetType().FullName}' requires a StableTypeId before it can be referenced persistently." + ); } (m_dependencies ??= [])[persistentId] = new AssetDependency( persistentId, typeRef, - includeLastKnownPaths ? asset.assetPath.ToString() : string.Empty); + includeLastKnownPaths ? asset.assetPath.ToString() : string.Empty + ); } /// @@ -81,8 +82,11 @@ TypeCatalog types public void Add(AssetDependency dependency) { if (dependency.persistentId == Guid.Empty) + { throw new ArgumentException("A dependency requires a persistent asset identity.", nameof(dependency)); - (m_dependencies ??= [])[dependency.persistentId] = includeLastKnownPaths ? dependency - : new AssetDependency(dependency.persistentId, dependency.type, string.Empty); + } + (m_dependencies ??= [])[dependency.persistentId] = includeLastKnownPaths + ? dependency + : new AssetDependency(dependency.persistentId, dependency.type, string.Empty); } } diff --git a/src/content/assets/Inno.Assets/Serialization/AssetDependencyConverter.cs b/src/content/assets/Inno.Assets/Serialization/AssetDependencyConverter.cs index bf31909b5..9a6eff2f8 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetDependencyConverter.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetDependencyConverter.cs @@ -1,9 +1,8 @@ using System; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Assets; @@ -43,6 +42,7 @@ public override AssetDependency Read(SerializationReader reader) return new AssetDependency( reader.Read("persistentId"), new TypeRef(reader.Read("stableTypeId")), - reader.Read("lastKnownPath")); + reader.Read("lastKnownPath") + ); } } diff --git a/src/content/assets/Inno.Assets/Serialization/AssetObjectConverter.cs b/src/content/assets/Inno.Assets/Serialization/AssetObjectConverter.cs index d77cc4b77..cbd1f049e 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetObjectConverter.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetObjectConverter.cs @@ -1,9 +1,8 @@ using System; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Assets; @@ -30,24 +29,29 @@ AssetObject value ArgumentNullException.ThrowIfNull(value); Guid persistentId = value.identity.persistentId; if (persistentId == Guid.Empty) + { throw new InvalidOperationException($"Asset '{value.GetType().FullName}' has no persistent identity at '{writer.path}'."); + } TypeCacheSnapshot types = writer.typeSnapshot; if (!types.TryGetTypeRef(value.GetType(), out TypeRef typeRef)) { throw new InvalidOperationException( - $"Asset type '{value.GetType().FullName}' requires a StableTypeId at '{writer.path}'."); + $"Asset type '{value.GetType().FullName}' requires a StableTypeId at '{writer.path}'." + ); } - bool hasDependencies = writer.context.TryGet(out AssetDependencyCollection? dependencies) && - dependencies is not null; + bool hasDependencies = writer.context.TryGet(out AssetDependencyCollection? dependencies) + && dependencies is not null; string lastKnownPath = !hasDependencies || dependencies!.includeLastKnownPaths - ? value.assetPath.ToString() - : string.Empty; + ? value.assetPath.ToString() + : string.Empty; writer.Write(C_PERSISTENT_ID, persistentId); writer.Write(C_STABLE_TYPE_ID, typeRef.stableId); writer.Write(C_LAST_KNOWN_PATH, lastKnownPath); if (hasDependencies) + { dependencies!.Add(new AssetDependency(persistentId, typeRef, lastKnownPath)); + } } /// @@ -67,6 +71,7 @@ public override AssetObject Read(SerializationReader reader) reader.Read(C_STABLE_TYPE_ID), reader.Read(C_LAST_KNOWN_PATH), reader.valueType, - reader.path); + reader.path + ); } } diff --git a/src/content/assets/Inno.Assets/Serialization/AssetPropertySnapshot.cs b/src/content/assets/Inno.Assets/Serialization/AssetPropertySnapshot.cs index ddd26ed3a..055c4f5bc 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetPropertySnapshot.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetPropertySnapshot.cs @@ -10,6 +10,7 @@ namespace Inno.Assets; public sealed class AssetPropertySnapshot { private readonly byte[] m_data; + /// /// Freezes a complete owner-produced property value. /// @@ -28,20 +29,25 @@ public AssetPropertySnapshot( IEnumerable dependencies ) { if (stableTypeId == Guid.Empty) + { throw new ArgumentException("A property snapshot requires a stable type identity.", nameof(stableTypeId)); + } ArgumentNullException.ThrowIfNull(dependencies); this.stableTypeId = stableTypeId; m_data = data.ToArray(); this.dependencies = Array.AsReadOnly(dependencies.ToArray()); } + /// /// Gets the persistent settings type identity. /// public Guid stableTypeId { get; } + /// /// Gets the frozen native property bytes. /// public ReadOnlyMemory data => m_data; + /// /// Gets the frozen direct dependency declarations. /// diff --git a/src/content/assets/Inno.Assets/Serialization/AssetSerializationContext.cs b/src/content/assets/Inno.Assets/Serialization/AssetSerializationContext.cs index 54380530c..a35c3359a 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetSerializationContext.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetSerializationContext.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Serialization; namespace Inno.Assets; diff --git a/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs b/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs index d8a6f08fd..2034982e6 100644 --- a/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs +++ b/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs @@ -1,8 +1,7 @@ using System; - using Inno.Assets; -using Inno.Core.Identity; using Inno.Core.Execution; +using Inno.Core.Identity; using Inno.References; namespace Inno.Assets; @@ -37,10 +36,13 @@ ReferenceResolution IReferenceResolver.Resolve(ReferenceDescriptor descriptor) return new ReferenceResolution( descriptor, ReferenceResolutionState.Invalid, - diagnostic: $"Asset resolver cannot process reference kind '{descriptor.kindId}'."); + diagnostic: $"Asset resolver cannot process reference kind '{descriptor.kindId}'." + ); } if (descriptor.isUnassigned) + { return new ReferenceResolution(descriptor, ReferenceResolutionState.Unassigned); + } try { AssetObject asset = Resolve( @@ -48,30 +50,33 @@ ReferenceResolution IReferenceResolver.Resolve(ReferenceDescriptor descriptor) descriptor.expectedStableTypeId, descriptor.lastKnownPath ?? string.Empty, typeof(AssetObject), - "$reference"); + "$reference" + ); if (asset.identity.persistentId != descriptor.targetPersistentId) { - return new ReferenceResolution(descriptor, ReferenceResolutionState.Invalid, - diagnostic: "The asset resolver returned a different persistent identity."); + return new ReferenceResolution( + descriptor, + ReferenceResolutionState.Invalid, + diagnostic: "The asset resolver returned a different persistent identity." + ); } if (asset.isMissing) { return new ReferenceResolution( descriptor, ReferenceResolutionState.Missing, - diagnostic: $"Asset '{descriptor.targetPersistentId:D}' is unavailable in the current generation."); + diagnostic: $"Asset '{descriptor.targetPersistentId:D}' is unavailable in the current generation." + ); } if (asset.identity.runtimeIdentity is not RuntimeIdentity runtimeIdentity) { return new ReferenceResolution( descriptor, ReferenceResolutionState.Invalid, - diagnostic: $"Asset '{descriptor.targetPersistentId:D}' is not registered in a runtime identity domain."); + diagnostic: $"Asset '{descriptor.targetPersistentId:D}' is not registered in a runtime identity domain." + ); } - return new ReferenceResolution( - descriptor, - ReferenceResolutionState.Resolved, - runtimeIdentity); + return new ReferenceResolution(descriptor, ReferenceResolutionState.Resolved, runtimeIdentity); } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -79,10 +84,7 @@ ReferenceResolution IReferenceResolver.Resolve(ReferenceDescriptor descriptor) } catch (Exception exception) when (exception is InvalidOperationException or System.IO.InvalidDataException) { - return new ReferenceResolution( - descriptor, - ReferenceResolutionState.Missing, - diagnostic: exception.Message); + return new ReferenceResolution(descriptor, ReferenceResolutionState.Missing, diagnostic: exception.Message); } } diff --git a/src/content/assets/Inno.Assets/Types/BinaryAsset.cs b/src/content/assets/Inno.Assets/Types/BinaryAsset.cs index cfc3120df..f3fe2ff9f 100644 --- a/src/content/assets/Inno.Assets/Types/BinaryAsset.cs +++ b/src/content/assets/Inno.Assets/Types/BinaryAsset.cs @@ -1,6 +1,6 @@ using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Assets; @@ -19,9 +19,7 @@ public sealed class BinaryAsset : AssetObject /// /// Creates an empty binary asset descriptor. /// - public BinaryAsset() - { - } + public BinaryAsset() {} /// /// Creates a binary asset descriptor with a byte length. diff --git a/src/content/assets/Inno.Assets/Types/TextAsset.cs b/src/content/assets/Inno.Assets/Types/TextAsset.cs index 3e0afe351..f3539a4c2 100644 --- a/src/content/assets/Inno.Assets/Types/TextAsset.cs +++ b/src/content/assets/Inno.Assets/Types/TextAsset.cs @@ -1,6 +1,6 @@ using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Assets; @@ -25,9 +25,7 @@ public sealed class TextAsset : AssetObject /// /// Creates an empty text asset. /// - public TextAsset() - { - } + public TextAsset() {} /// /// Creates a text asset with content and an optional language hint. diff --git a/src/content/deployment/Inno.Content/ContentEntry.cs b/src/content/deployment/Inno.Content/ContentEntry.cs index 1cf4636c6..f35587f1b 100644 --- a/src/content/deployment/Inno.Content/ContentEntry.cs +++ b/src/content/deployment/Inno.Content/ContentEntry.cs @@ -28,7 +28,9 @@ public ContentEntry( string contentHash ) { if (key.value is null) + { throw new ArgumentException("Content metadata requires an assigned key.", nameof(key)); + } ArgumentOutOfRangeException.ThrowIfNegative(length); this.key = key; this.length = length; @@ -53,11 +55,15 @@ string contentHash internal static string NormalizeHash(string value) { if (value is not { Length: 64 }) + { throw new ArgumentException("Content identity requires a SHA-256 value.", nameof(value)); + } foreach (char character in value) { if (!Uri.IsHexDigit(character)) + { throw new ArgumentException("Content identity requires hexadecimal digits.", nameof(value)); + } } return value.ToUpperInvariant(); } diff --git a/src/content/deployment/Inno.Content/ContentKey.cs b/src/content/deployment/Inno.Content/ContentKey.cs index 661999990..cd20c859d 100644 --- a/src/content/deployment/Inno.Content/ContentKey.cs +++ b/src/content/deployment/Inno.Content/ContentKey.cs @@ -22,12 +22,16 @@ public ContentKey(string value) foreach (string segment in value.Split('/')) { if (segment.Length == 0 || segment is "." or ".." || segment.EndsWith('.') - || segment.EndsWith(' ') || IsReserved(segment)) + || segment.EndsWith(' ') || IsReserved(segment) + ) { throw new ArgumentException("Content keys require portable relative segments.", nameof(value)); + } foreach (char character in segment) { if (char.IsControl(character) || character is '\\' or ':' or '*' or '?' or '"' or '<' or '>' or '|') + { throw new ArgumentException("Content keys contain a nonportable character.", nameof(value)); + } } } this.value = value; @@ -46,13 +50,15 @@ private static bool IsReserved(string segment) ReadOnlySpan stem = segment.AsSpan(); int extension = stem.IndexOf('.'); if (extension >= 0) + { stem = stem[..extension]; + } return stem.Equals("CON", StringComparison.OrdinalIgnoreCase) - || stem.Equals("PRN", StringComparison.OrdinalIgnoreCase) - || stem.Equals("AUX", StringComparison.OrdinalIgnoreCase) - || stem.Equals("NUL", StringComparison.OrdinalIgnoreCase) - || (stem.Length == 4 && stem[3] is >= '1' and <= '9' - && (stem[..3].Equals("COM", StringComparison.OrdinalIgnoreCase) - || stem[..3].Equals("LPT", StringComparison.OrdinalIgnoreCase))); + || stem.Equals("PRN", StringComparison.OrdinalIgnoreCase) + || stem.Equals("AUX", StringComparison.OrdinalIgnoreCase) + || stem.Equals("NUL", StringComparison.OrdinalIgnoreCase) + || (stem.Length == 4 && stem[3] is >= '1' and <= '9' + && (stem[..3].Equals("COM", StringComparison.OrdinalIgnoreCase) + || stem[..3].Equals("LPT", StringComparison.OrdinalIgnoreCase))); } } diff --git a/src/content/deployment/Inno.Content/ContentPackDescriptor.cs b/src/content/deployment/Inno.Content/ContentPackDescriptor.cs index 98f29e932..91ebf26fb 100644 --- a/src/content/deployment/Inno.Content/ContentPackDescriptor.cs +++ b/src/content/deployment/Inno.Content/ContentPackDescriptor.cs @@ -25,7 +25,9 @@ string fileName ) { this.contentHash = ContentEntry.NormalizeHash(contentHash); if (!string.Equals(fileName, $"content-{this.contentHash}.pack", StringComparison.Ordinal)) + { throw new ArgumentException("The pack file name must match its content identity.", nameof(fileName)); + } this.fileName = fileName; } diff --git a/src/content/deployment/Inno.Content/ContentPackIndex.cs b/src/content/deployment/Inno.Content/ContentPackIndex.cs index 93c242125..a204687e8 100644 --- a/src/content/deployment/Inno.Content/ContentPackIndex.cs +++ b/src/content/deployment/Inno.Content/ContentPackIndex.cs @@ -36,7 +36,9 @@ public ContentPackIndex(IEnumerable entries) { ArgumentNullException.ThrowIfNull(entry); if (!folded.Add(entry.key.value!)) + { throw new ArgumentException($"Content repeats a reserved or ambiguous key '{entry.key}'.", nameof(entries)); + } m_byKey.Add(entry.key, entry); ordered.Add(entry); totalLength = checked(totalLength + entry.length); @@ -86,7 +88,9 @@ private static void ValidateTree(List entries) for (int separator = key.IndexOf('/'); separator >= 0; separator = key.IndexOf('/', separator + 1)) { if (files.Contains(key[..separator])) + { throw new ArgumentException($"Content uses '{key[..separator]}' as both a file and directory.", nameof(entries)); + } } } } diff --git a/src/content/deployment/Inno.Content/ContentPackIndexCodec.cs b/src/content/deployment/Inno.Content/ContentPackIndexCodec.cs index 96bfa11c7..102e80697 100644 --- a/src/content/deployment/Inno.Content/ContentPackIndexCodec.cs +++ b/src/content/deployment/Inno.Content/ContentPackIndexCodec.cs @@ -28,15 +28,19 @@ SerializationGeneration serialization ) { ArgumentNullException.ThrowIfNull(index); ArgumentNullException.ThrowIfNull(serialization); - return serialization.Encode(writer => writer.WriteObjectArray("entries", index.entries, + return serialization.Encode(writer => writer.WriteObjectArray( + "entries", + index.entries, static ( entryWriter, entry - ) => { + ) => + { entryWriter.Write("key", entry.key.value!); entryWriter.Write("length", entry.length); entryWriter.Write("hash", entry.contentHash); - })); + } + )); } /// @@ -61,9 +65,14 @@ SerializationGeneration serialization ArgumentNullException.ThrowIfNull(serialization); try { - return serialization.Decode(data, reader => new ContentPackIndex(reader.ReadObjectArray("entries") - .Select(static entry => new ContentEntry(new ContentKey(entry.Read("key")), - entry.Read("length"), entry.Read("hash"))))); + return serialization.Decode(data, reader => new ContentPackIndex( + reader.ReadObjectArray("entries") + .Select(static entry => new ContentEntry( + new ContentKey(entry.Read("key")), + entry.Read("length"), + entry.Read("hash") + )) + )); } catch (Exception failure) when (failure is ArgumentException or InvalidOperationException or OverflowException) { diff --git a/src/content/deployment/Inno.Content/ContentPackReader.cs b/src/content/deployment/Inno.Content/ContentPackReader.cs index 948c2058f..aa592649d 100644 --- a/src/content/deployment/Inno.Content/ContentPackReader.cs +++ b/src/content/deployment/Inno.Content/ContentPackReader.cs @@ -57,41 +57,59 @@ public static PackContentStore Open( limits ??= new ContentReadLimits(); cancellationToken.ThrowIfCancellationRequested(); if (!pack.CanRead || !pack.CanSeek) + { throw new ArgumentException("A content pack requires an owned readable seekable stream.", nameof(pack)); + } if (pack.Length > limits.packBytes) + { throw new InvalidDataException("The encoded content pack exceeds its reading budget."); + } pack.Position = 0; string actualHash = Hash(pack, pack.Length, cancellationToken); if (!string.Equals(actualHash, descriptor.contentHash, StringComparison.Ordinal)) + { throw new InvalidDataException("The complete pack bytes do not match their content identity."); + } pack.Position = 0; archive = new ZipArchive(pack, ZipArchiveMode.Read, leaveOpen: false); Dictionary payloads = ReadInventory(archive, limits); ContentKey indexKey = new(ContentPackIndex.C_INDEX_KEY); if (!payloads.Remove(indexKey, out ZipArchiveEntry? indexEntry)) + { throw new InvalidDataException("The content pack has no inventory document."); + } if (indexEntry.Length > limits.indexBytes) + { throw new InvalidDataException("The content inventory exceeds its reading budget."); + } byte[] indexBytes = new byte[checked((int)indexEntry.Length)]; using (Stream indexStream = indexEntry.Open()) { indexStream.ReadExactly(indexBytes); if (indexStream.ReadByte() != -1) + { throw new InvalidDataException("The content inventory exceeds its declared length."); + } } ContentPackIndex index = ContentPackIndexCodec.Decode(indexBytes, serialization); if (index.entries.Count != payloads.Count || index.entries.Count > limits.entryCount - || index.totalLength > limits.totalBytes) + || index.totalLength > limits.totalBytes + ) { throw new InvalidDataException("The content inventory is incomplete or exceeds its expansion budget."); + } foreach (ContentEntry entry in index.entries) { cancellationToken.ThrowIfCancellationRequested(); if (!payloads.TryGetValue(entry.key, out ZipArchiveEntry? payload) - || payload.Length != entry.length || entry.length > limits.entryBytes) + || payload.Length != entry.length || entry.length > limits.entryBytes + ) { throw new InvalidDataException($"Content entry '{entry.key}' is missing or has an invalid length."); + } using Stream input = payload.Open(); if (!string.Equals(Hash(input, entry.length, cancellationToken), entry.contentHash, StringComparison.Ordinal)) + { throw new InvalidDataException($"Content entry '{entry.key}' does not match its decoded identity."); + } } cancellationToken.ThrowIfCancellationRequested(); return new PackContentStore(archive, descriptor, index, payloads); @@ -99,9 +117,13 @@ public static PackContentStore Open( catch { if (archive is not null) + { archive.Dispose(); + } else + { pack.Dispose(); + } throw; } } @@ -111,14 +133,18 @@ private static Dictionary ReadInventory( ContentReadLimits limits ) { if (archive.Entries.Count > limits.entryCount + 1L) + { throw new InvalidDataException("The archive contains too many entries."); + } Dictionary entries = new(); HashSet folded = new(StringComparer.OrdinalIgnoreCase); foreach (ZipArchiveEntry entry in archive.Entries) { int mode = (entry.ExternalAttributes >> 16) & 0xF000; if ((mode != 0 && mode != 0x8000) || (entry.ExternalAttributes & 0x10) != 0) + { throw new InvalidDataException($"Archive entry '{entry.FullName}' is not a regular file."); + } ContentKey key; try { @@ -129,7 +155,9 @@ ContentReadLimits limits throw new InvalidDataException($"Archive entry '{entry.FullName}' is not portable.", failure); } if (!folded.Add(key.value!) || !entries.TryAdd(key, entry)) + { throw new InvalidDataException($"The archive repeats an ambiguous content key '{key}'."); + } } return entries; } @@ -149,13 +177,17 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); int read = input.Read(buffer, 0, (int)Math.Min(buffer.Length, remaining)); if (read == 0) + { throw new InvalidDataException("Content ended before its declared length."); + } hash.AppendData(buffer.AsSpan(0, read)); remaining -= read; } cancellationToken.ThrowIfCancellationRequested(); if (input.ReadByte() != -1) + { throw new InvalidDataException("Content exceeds its declared length."); + } return Convert.ToHexString(hash.GetHashAndReset()); } finally diff --git a/src/content/deployment/Inno.Content/ContentReadLease.cs b/src/content/deployment/Inno.Content/ContentReadLease.cs index 6146fca5b..f7ecbc7ed 100644 --- a/src/content/deployment/Inno.Content/ContentReadLease.cs +++ b/src/content/deployment/Inno.Content/ContentReadLease.cs @@ -57,7 +57,7 @@ public Stream OpenRead() { Func openRead = m_openRead ?? throw new ObjectDisposedException(nameof(ContentReadLease)); Stream input = openRead() - ?? throw new InvalidOperationException("The content provider returned a null stream."); + ?? throw new InvalidOperationException("The content provider returned a null stream."); if (!input.CanRead) { input.Dispose(); diff --git a/src/content/deployment/Inno.Content/PackContentStore.cs b/src/content/deployment/Inno.Content/PackContentStore.cs index a9a405f56..bc11ee8c9 100644 --- a/src/content/deployment/Inno.Content/PackContentStore.cs +++ b/src/content/deployment/Inno.Content/PackContentStore.cs @@ -41,7 +41,9 @@ public ContentReadLease Acquire(ContentKey key) { ObjectDisposedException.ThrowIf(m_closed, this); if (!index.TryGetEntry(key, out ContentEntry? entry)) + { throw new FileNotFoundException($"Content '{key}' does not exist in pack '{descriptor.contentHash}'."); + } m_pins = checked(m_pins + 1); return new ContentReadLease(entry!, () => OpenPinned(key), ReleasePin); } @@ -55,7 +57,9 @@ public void Dispose() lock (m_sync) { if (m_closed) + { return; + } m_closed = true; ReleasePin(); } @@ -76,7 +80,9 @@ private void ReleasePin() lock (m_sync) { if (--m_pins == 0) + { m_archive.Dispose(); + } } } @@ -95,12 +101,16 @@ Stream input /// public override bool CanRead => m_input is not null; + /// public override bool CanSeek => false; + /// public override bool CanWrite => false; + /// public override long Length => throw new NotSupportedException(); + /// public override long Position { @@ -119,25 +129,32 @@ int count public override int Read(Span buffer) { lock (m_owner.m_sync) + { return (m_input ?? throw new ObjectDisposedException(nameof(EntryReadStream))).Read(buffer); + } } /// public override int ReadByte() { lock (m_owner.m_sync) + { return (m_input ?? throw new ObjectDisposedException(nameof(EntryReadStream))).ReadByte(); + } } /// public override void Flush() => throw new NotSupportedException(); + /// public override long Seek( long offset, SeekOrigin origin ) => throw new NotSupportedException(); + /// public override void SetLength(long value) => throw new NotSupportedException(); + /// public override void Write( byte[] buffer, diff --git a/src/content/references/Inno.References/ContentReadScope.cs b/src/content/references/Inno.References/ContentReadScope.cs index 982012a27..1e6bacdc0 100644 --- a/src/content/references/Inno.References/ContentReadScope.cs +++ b/src/content/references/Inno.References/ContentReadScope.cs @@ -36,11 +36,17 @@ public ContentReadScope( ArgumentNullException.ThrowIfNull(contents); Identity[] snapshot = contents.ToArray(); if (snapshot.Any(static identity => identity.runtimeIdentity is null)) + { throw new ArgumentException("Content roots must belong to live identity domains.", nameof(contents)); + } if (snapshot.Select(static identity => identity.persistentId).Distinct().Count() != snapshot.Length) + { throw new ArgumentException("Content root persistent identities must be unique.", nameof(contents)); + } if (activeContent is Guid active && !snapshot.Any(identity => identity.persistentId == active)) + { throw new ArgumentException("The active content must belong to this scope.", nameof(activeContent)); + } m_contents = Array.AsReadOnly(snapshot); this.activeContent = activeContent; } @@ -75,11 +81,15 @@ public ContentReadScope( /// /// Lookup occurs off the owning control thread. /// - public IReadOnlyList GetValues() where TValue : IdentityObject + public IReadOnlyList GetValues() + where TValue : IdentityObject { EnsureActive(); - return Array.AsReadOnly(m_contents.Select(static identity => identity.Resolve()) - .OfType().ToArray()); + return Array.AsReadOnly( + m_contents.Select(static identity => identity.Resolve()) + .OfType() + .ToArray() + ); } /// @@ -112,7 +122,9 @@ out TValue? value foreach (Identity identity in m_contents) { if (identity.persistentId != id) + { continue; + } value = identity.Resolve(); return value is not null; } @@ -129,6 +141,8 @@ private void EnsureActive() { ObjectDisposedException.ThrowIf(m_disposed, this); if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Content lookup requires its owning control thread."); + } } } diff --git a/src/content/references/Inno.References/IReferenceRecoveryParticipant.cs b/src/content/references/Inno.References/IReferenceRecoveryParticipant.cs index de411a4fd..2efd98eb8 100644 --- a/src/content/references/Inno.References/IReferenceRecoveryParticipant.cs +++ b/src/content/references/Inno.References/IReferenceRecoveryParticipant.cs @@ -15,5 +15,4 @@ public interface IReferenceRecoveryParticipant : IGenerationChange /// The complete immutable set of candidate recovery changes; optional missing slots remain preserved. /// void Validate(IReadOnlyList changes); - } diff --git a/src/content/references/Inno.References/ReferenceCatalog.cs b/src/content/references/Inno.References/ReferenceCatalog.cs index 02ee68e77..595a844cf 100644 --- a/src/content/references/Inno.References/ReferenceCatalog.cs +++ b/src/content/references/Inno.References/ReferenceCatalog.cs @@ -54,16 +54,22 @@ public static ReferenceCatalog Create( IEnumerable resolvers ) { if (generation <= 0) + { throw new ArgumentOutOfRangeException(nameof(generation), "A published reference catalog requires a positive generation."); + } ArgumentNullException.ThrowIfNull(resolvers); var byKind = new Dictionary(); foreach (IReferenceResolver? resolver in resolvers) { ArgumentNullException.ThrowIfNull(resolver); if (!resolver.kindId.isValid) + { throw new InvalidOperationException("A reference resolver declared an invalid kind identifier."); + } if (!byKind.TryAdd(resolver.kindId, resolver)) + { throw new InvalidOperationException($"Reference kind '{resolver.kindId}' has more than one resolver."); + } } return new ReferenceCatalog(generation, byKind); } @@ -87,18 +93,23 @@ public ReferenceResolution Resolve(ReferenceDescriptor descriptor) { ArgumentNullException.ThrowIfNull(descriptor); if (descriptor.isUnassigned) + { return new ReferenceResolution(descriptor, ReferenceResolutionState.Unassigned); + } if (!m_resolvers.TryGetValue(descriptor.kindId, out IReferenceResolver? resolver)) { return new ReferenceResolution( descriptor, ReferenceResolutionState.Missing, - diagnostic: $"No resolver for reference kind '{descriptor.kindId}' is active in generation {generation}."); + diagnostic: $"No resolver for reference kind '{descriptor.kindId}' is active in generation {generation}." + ); } ReferenceResolution result = resolver.Resolve(descriptor) - ?? throw new InvalidOperationException($"Reference resolver '{descriptor.kindId}' returned null."); + ?? throw new InvalidOperationException($"Reference resolver '{descriptor.kindId}' returned null."); if (!ReferenceEquals(result.descriptor, descriptor)) + { throw new InvalidOperationException($"Reference resolver '{descriptor.kindId}' replaced the supplied descriptor."); + } return result; } } diff --git a/src/content/references/Inno.References/ReferenceDescriptor.cs b/src/content/references/Inno.References/ReferenceDescriptor.cs index a159add7a..c34d53904 100644 --- a/src/content/references/Inno.References/ReferenceDescriptor.cs +++ b/src/content/references/Inno.References/ReferenceDescriptor.cs @@ -36,7 +36,9 @@ public ReferenceDescriptor( string? lastKnownPath = null ) { if (!kindId.isValid) + { throw new ArgumentException("A reference descriptor requires a valid kind identifier.", nameof(kindId)); + } this.kindId = kindId; this.targetPersistentId = targetPersistentId; this.expectedStableTypeId = expectedStableTypeId; diff --git a/src/content/references/Inno.References/ReferenceKey.cs b/src/content/references/Inno.References/ReferenceKey.cs index 576a6963b..b4a2c46e2 100644 --- a/src/content/references/Inno.References/ReferenceKey.cs +++ b/src/content/references/Inno.References/ReferenceKey.cs @@ -24,9 +24,13 @@ public ReferenceKey( string path ) { if (ownerPersistentId == Guid.Empty) + { throw new ArgumentException("A reference key requires a non-empty owner identity.", nameof(ownerPersistentId)); + } if (string.IsNullOrWhiteSpace(path)) + { throw new ArgumentException("A reference key requires a non-empty stable path.", nameof(path)); + } this.ownerPersistentId = ownerPersistentId; this.path = path; } diff --git a/src/content/references/Inno.References/ReferenceKindId.cs b/src/content/references/Inno.References/ReferenceKindId.cs index ace24aa1c..0aefc1fbf 100644 --- a/src/content/references/Inno.References/ReferenceKindId.cs +++ b/src/content/references/Inno.References/ReferenceKindId.cs @@ -19,7 +19,9 @@ namespace Inno.References; public ReferenceKindId(string value) { if (string.IsNullOrWhiteSpace(value) || !string.Equals(value, value.Trim(), StringComparison.Ordinal)) + { throw new ArgumentException("A reference kind identifier must be non-empty and trimmed.", nameof(value)); + } this.value = value; } diff --git a/src/content/references/Inno.References/ReferenceRecoveryTransaction.cs b/src/content/references/Inno.References/ReferenceRecoveryTransaction.cs index fd5685cd4..65b272f56 100644 --- a/src/content/references/Inno.References/ReferenceRecoveryTransaction.cs +++ b/src/content/references/Inno.References/ReferenceRecoveryTransaction.cs @@ -56,12 +56,16 @@ IEnumerable participants foreach (SerializedMissingState state in m_states) { ArgumentNullException.ThrowIfNull(state); - if (state.key.ownerPersistentId == Guid.Empty || string.IsNullOrWhiteSpace(state.key.path) || - !keys.Add(state.key)) + if (state.key.ownerPersistentId == Guid.Empty || string.IsNullOrWhiteSpace(state.key.path) + || !keys.Add(state.key) + ) { throw new ArgumentException($"Invalid or duplicate recovery slot '{state.key}'.", nameof(missingStates)); + } } foreach (IReferenceRecoveryParticipant participant in m_participants) + { ArgumentNullException.ThrowIfNull(participant); + } m_catalog = catalog; } @@ -99,11 +103,16 @@ public void Apply() RequirePhase(Phase.Prepared); m_phase = Phase.Applying; foreach (IReferenceRecoveryParticipant participant in m_participants) + { Invoke(participant.Apply); - Invoke(() => m_changes = Array.AsReadOnly(m_states.Select(state => - new ReferenceRecoveryChange(state, m_catalog!.Resolve(state.descriptor))).ToArray())); + } + Invoke(() => m_changes = Array.AsReadOnly( + m_states.Select(state => new ReferenceRecoveryChange(state, m_catalog!.Resolve(state.descriptor))).ToArray() + )); foreach (IReferenceRecoveryParticipant participant in m_participants) + { Invoke(() => participant.Validate(m_changes)); + } m_phase = Phase.Applied; } @@ -142,13 +151,19 @@ public void RollbackStructure() { EnsureOwner(); if (m_phase == Phase.RolledBack) + { return; + } if (m_phase is Phase.Finished or Phase.Finalizing or Phase.RollingBack) + { throw new InvalidOperationException("A completed recovery transaction cannot be rolled back."); + } m_phase = Phase.RollingBack; List failures = []; for (int index = m_preparedCount - 1; index >= 0; index--) + { Attempt(m_participants[index].RollbackStructure, failures); + } m_phase = Phase.RolledBack; m_changes = Array.Empty(); ThrowFailures(failures, "Reference recovery structure rollback failed."); @@ -179,12 +194,16 @@ private void RunTerminalPhase(bool restore) if (restore) { for (int index = m_preparedCount - 1; index >= 0; index--) + { Attempt(m_participants[index].RestorePreviousState, failures); + } } else { foreach (IReferenceRecoveryParticipant participant in m_participants) + { Attempt(participant.Complete, failures); + } } m_phase = Phase.Finished; m_catalog = null; @@ -218,7 +237,10 @@ ICollection failures { if (failures.Count > 0) { - m_retirementFailure = new AggregateException("Reference recovery remains pending after earlier cleanup failures.", [.. failures, pendingRetirement]); + m_retirementFailure = new AggregateException( + "Reference recovery remains pending after earlier cleanup failures.", + [.. failures, pendingRetirement] + ); throw m_retirementFailure; } throw; @@ -234,22 +256,30 @@ private static void ThrowFailures( string message ) { if (failures.Count > 0) + { throw new AggregateException(message, failures); + } } private void RequirePhase(Phase phase) { EnsureOwner(); if (m_phase != phase) + { throw new InvalidOperationException($"Recovery phase is '{m_phase}', expected '{phase}'."); + } } private void EnsureOwner() { if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Reference recovery must run on its capture thread."); + } if (m_retirementFailure is not null) + { throw m_retirementFailure; + } } private enum Phase { Captured, Preparing, Prepared, Applying, Applied, RollingBack, RolledBack, Finalizing, Finished } diff --git a/src/content/references/Inno.References/ReferenceResolution.cs b/src/content/references/Inno.References/ReferenceResolution.cs index 8fc087be3..73b3b5154 100644 --- a/src/content/references/Inno.References/ReferenceResolution.cs +++ b/src/content/references/Inno.References/ReferenceResolution.cs @@ -37,7 +37,9 @@ public ReferenceResolution( ) { ArgumentNullException.ThrowIfNull(descriptor); if ((state == ReferenceResolutionState.Resolved) != runtimeIdentity.HasValue) + { throw new ArgumentException("Only a resolved reference can carry a runtime identity.", nameof(runtimeIdentity)); + } this.descriptor = descriptor; this.state = state; this.runtimeIdentity = runtimeIdentity; diff --git a/src/content/references/Inno.References/ReferenceResolutionState.cs b/src/content/references/Inno.References/ReferenceResolutionState.cs index e72f69010..bae901c56 100644 --- a/src/content/references/Inno.References/ReferenceResolutionState.cs +++ b/src/content/references/Inno.References/ReferenceResolutionState.cs @@ -9,22 +9,18 @@ public enum ReferenceResolutionState /// The slot has no assigned target. /// Unassigned, - /// /// The current generation resolved a compatible live target. /// Resolved, - /// /// The intended target is temporarily unavailable. /// Missing, - /// /// The intended target exists but does not satisfy the stable type constraint. /// TypeMismatch, - /// /// The descriptor or authoritative source is invalid. /// diff --git a/src/content/scene/Inno.Scene.Assets/EngineResourceEnvelope.cs b/src/content/scene/Inno.Scene.Assets/EngineResourceEnvelope.cs index 4c2f4792a..fc8cbfd7c 100644 --- a/src/content/scene/Inno.Scene.Assets/EngineResourceEnvelope.cs +++ b/src/content/scene/Inno.Scene.Assets/EngineResourceEnvelope.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; using Inno.Core.Serialization; @@ -24,9 +23,12 @@ internal void Validate(string expectedKind) if (!string.Equals(resourceKind, expectedKind, StringComparison.Ordinal)) { throw new InvalidOperationException( - $"Engine resource kind '{resourceKind}' does not match expected kind '{expectedKind}'."); + $"Engine resource kind '{resourceKind}' does not match expected kind '{expectedKind}'." + ); } if (payload.Length == 0) + { throw new InvalidOperationException($"Engine resource '{resourceKind}' has an empty graph payload."); + } } } diff --git a/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs b/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs index 6f28d9d2c..2c3fef2bc 100644 --- a/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs +++ b/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Serialization; @@ -44,12 +43,15 @@ protected override async ValueTask ImportAsync( CancellationToken cancellationToken ) { EngineResourceEnvelope envelope = context.serialization.Deserialize( - context.sourceBytes.ToArray()); + context.sourceBytes.ToArray() + ); envelope.Validate(EngineResourceEnvelope.C_PREFAB_KIND); AssetDependency[] dependencies = envelope.dependencies; PrefabAsset asset = PrefabAsset.CreateImported(envelope.payload, dependencies); for (int i = 0; i < dependencies.Length; i++) + { output.DependsOnAsset(dependencies[i]); + } output.SetAsset(asset); await output.WriteArtifactAsync("runtime", envelope.payload, cancellationToken).ConfigureAwait(false); } @@ -75,12 +77,15 @@ CancellationToken cancellationToken CancellationToken cancellationToken ) { EngineAssetContent content = asset.CaptureContent(); - return ValueTask.FromResult?>(context.serialization.Serialize( - new EngineResourceEnvelope - { - resourceKind = EngineResourceEnvelope.C_PREFAB_KIND, - payload = content.GetPayload(), - dependencies = content.GetDependencies() - })); + return ValueTask.FromResult?>( + context.serialization.Serialize( + new EngineResourceEnvelope + { + resourceKind = EngineResourceEnvelope.C_PREFAB_KIND, + payload = content.GetPayload(), + dependencies = content.GetDependencies() + } + ) + ); } } diff --git a/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs b/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs index cad2100bf..cf2d95da7 100644 --- a/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs +++ b/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Serialization; @@ -44,12 +43,15 @@ protected override async ValueTask ImportAsync( CancellationToken cancellationToken ) { EngineResourceEnvelope envelope = context.serialization.Deserialize( - context.sourceBytes.ToArray()); + context.sourceBytes.ToArray() + ); envelope.Validate(EngineResourceEnvelope.C_SCENE_KIND); AssetDependency[] dependencies = envelope.dependencies; SceneAsset asset = SceneAsset.CreateImported(envelope.payload, dependencies); for (int i = 0; i < dependencies.Length; i++) + { output.DependsOnAsset(dependencies[i]); + } output.SetAsset(asset); await output.WriteArtifactAsync("runtime", envelope.payload, cancellationToken).ConfigureAwait(false); } @@ -75,12 +77,15 @@ CancellationToken cancellationToken CancellationToken cancellationToken ) { EngineAssetContent content = asset.CaptureContent(); - return ValueTask.FromResult?>(context.serialization.Serialize( - new EngineResourceEnvelope - { - resourceKind = EngineResourceEnvelope.C_SCENE_KIND, - payload = content.GetPayload(), - dependencies = content.GetDependencies() - })); + return ValueTask.FromResult?>( + context.serialization.Serialize( + new EngineResourceEnvelope + { + resourceKind = EngineResourceEnvelope.C_SCENE_KIND, + payload = content.GetPayload(), + dependencies = content.GetDependencies() + } + ) + ); } } diff --git a/src/content/scene/Inno.Scene/Assets/EngineAssetContent.cs b/src/content/scene/Inno.Scene/Assets/EngineAssetContent.cs index a608a7b55..0d7757ea2 100644 --- a/src/content/scene/Inno.Scene/Assets/EngineAssetContent.cs +++ b/src/content/scene/Inno.Scene/Assets/EngineAssetContent.cs @@ -31,7 +31,9 @@ IReadOnlyList dependencies ) { ArgumentNullException.ThrowIfNull(dependencies); if (payload.IsEmpty) + { throw new ArgumentException("Engine asset content cannot be empty.", nameof(payload)); + } m_payload = payload.ToArray(); m_dependencies = dependencies.ToArray(); } diff --git a/src/content/scene/Inno.Scene/Assets/PrefabAsset.cs b/src/content/scene/Inno.Scene/Assets/PrefabAsset.cs index b2ddcb9b3..d154da65d 100644 --- a/src/content/scene/Inno.Scene/Assets/PrefabAsset.cs +++ b/src/content/scene/Inno.Scene/Assets/PrefabAsset.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene.Components; using Inno.Scripting.Api; @@ -18,6 +17,7 @@ namespace Inno.Scene; public sealed class PrefabAsset : AssetObject { private byte[] m_pendingPayload = []; + [SerializableProperty] internal AssetDependency[] sourceDependencies { get; set; } = []; @@ -84,15 +84,21 @@ public GameObject Instantiate( ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (parent is not null && !ReferenceEquals(parent.gameObject.scene, scene)) + { throw new InvalidOperationException("The prefab parent must belong to the target scene."); + } SerializationContext context = AssetSerializationContext.Create(assets) .With(scene) .With(this); GameObject root = serialization.Deserialize(GetPayload(), context); if (parent is not null) + { scene.SetParent(root.transform, parent, worldPositionStays: false); + } if (!string.IsNullOrWhiteSpace(assetPath.localPath)) + { root.name = Path.GetFileNameWithoutExtension(assetPath.localPath); + } return root; } @@ -115,7 +121,9 @@ IReadOnlyList dependencies ) { ArgumentNullException.ThrowIfNull(dependencies); if (payload.IsEmpty) + { throw new ArgumentException("Imported prefab content cannot be empty.", nameof(payload)); + } return new PrefabAsset { m_pendingPayload = payload.ToArray(), @@ -135,10 +143,13 @@ IReadOnlyList dependencies private byte[] GetPayload() { if (!runtimePayload.IsEmpty) + { return runtimePayload.ToArray(); + } if (m_pendingPayload.Length != 0) + { return (byte[])m_pendingPayload.Clone(); + } throw new InvalidOperationException($"Prefab asset '{assetPath}' does not contain an imported or pending prefab payload."); } - } diff --git a/src/content/scene/Inno.Scene/Assets/SceneAsset.cs b/src/content/scene/Inno.Scene/Assets/SceneAsset.cs index a447a4100..670fb0c8d 100644 --- a/src/content/scene/Inno.Scene/Assets/SceneAsset.cs +++ b/src/content/scene/Inno.Scene/Assets/SceneAsset.cs @@ -2,11 +2,11 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scripting.Api; + namespace Inno.Scene; /// @@ -16,6 +16,7 @@ namespace Inno.Scene; public sealed class SceneAsset : AssetObject { private byte[] m_pendingPayload = []; + [SerializableProperty] internal AssetDependency[] sourceDependencies { get; set; } = []; @@ -95,7 +96,9 @@ IAssetReferenceResolver assets .With(this); GameScene scene = serialization.Deserialize(GetPayload(), context); if (!string.IsNullOrWhiteSpace(assetPath.localPath)) + { scene.name = Path.GetFileNameWithoutExtension(assetPath.localPath); + } return scene; } @@ -118,7 +121,9 @@ IReadOnlyList dependencies ) { ArgumentNullException.ThrowIfNull(dependencies); if (payload.IsEmpty) + { throw new ArgumentException("Imported scene content cannot be empty.", nameof(payload)); + } return new SceneAsset { m_pendingPayload = payload.ToArray(), @@ -138,9 +143,13 @@ IReadOnlyList dependencies private byte[] GetPayload() { if (m_pendingPayload.Length != 0) + { return (byte[])m_pendingPayload.Clone(); + } if (!runtimePayload.IsEmpty) + { return runtimePayload.ToArray(); + } throw new InvalidOperationException($"Scene asset '{assetPath}' does not contain an imported or pending scene payload."); } diff --git a/src/content/scene/Inno.Scene/Concrete/MissingGameComponent.cs b/src/content/scene/Inno.Scene/Concrete/MissingGameComponent.cs index e6c78fbb4..0ec79af2b 100644 --- a/src/content/scene/Inno.Scene/Concrete/MissingGameComponent.cs +++ b/src/content/scene/Inno.Scene/Concrete/MissingGameComponent.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; using Inno.Extensibility.Types; @@ -20,6 +19,7 @@ public sealed class MissingGameComponent : GameComponent { private byte[] m_serializedState; private AssetDependency[] m_dependencies; + private IReadOnlyDictionary m_referenceAliases = new Dictionary(); @@ -30,11 +30,13 @@ internal MissingGameComponent( IReadOnlyList? dependencies = null ) { if (missingType.stableId == Guid.Empty) + { throw new ArgumentException("The missing component type identity cannot be empty.", nameof(missingType)); + } this.missingType = missingType; this.missingTypeName = string.IsNullOrWhiteSpace(missingTypeName) - ? missingType.stableId.ToString("D") - : missingTypeName; + ? missingType.stableId.ToString("D") + : missingTypeName; m_serializedState = serializedState.ToArray(); m_dependencies = dependencies?.ToArray() ?? []; } diff --git a/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs b/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs index 24ccc44eb..454e9fd90 100644 --- a/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs +++ b/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; using Inno.Extensibility.Types; @@ -20,6 +19,7 @@ public sealed class MissingGameSystem : GameSystem { private byte[] m_serializedState; private AssetDependency[] m_dependencies; + private IReadOnlyDictionary m_referenceAliases = new Dictionary(); @@ -30,11 +30,13 @@ internal MissingGameSystem( IReadOnlyList? dependencies = null ) { if (missingType.stableId == Guid.Empty) + { throw new ArgumentException("The missing system type identity cannot be empty.", nameof(missingType)); + } this.missingType = missingType; this.missingTypeName = string.IsNullOrWhiteSpace(missingTypeName) - ? missingType.stableId.ToString("D") - : missingTypeName; + ? missingType.stableId.ToString("D") + : missingTypeName; m_serializedState = serializedState.ToArray(); m_dependencies = dependencies?.ToArray() ?? []; enabled = false; diff --git a/src/content/scene/Inno.Scene/Concrete/Transform.cs b/src/content/scene/Inno.Scene/Concrete/Transform.cs index c5d6cad09..c6a699205 100644 --- a/src/content/scene/Inno.Scene/Concrete/Transform.cs +++ b/src/content/scene/Inno.Scene/Concrete/Transform.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; - using Inno.Core.Mathematics; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Scene.Components; @@ -222,7 +221,9 @@ internal bool IsDescendantOf(Transform ancestor) for (Transform? current = m_parent; current is not null; current = current.m_parent) { if (ReferenceEquals(current, ancestor)) + { return true; + } } return false; } @@ -232,7 +233,9 @@ internal bool IsDescendantOf(Transform ancestor) internal void AddChildDirect(Transform child) { if (!m_children.Contains(child)) + { m_children.Add(child); + } } internal void RemoveChildDirect(Transform child) => m_children.Remove(child); @@ -271,7 +274,8 @@ Vector3 scale m_localScale = new Vector3( SafeDivide(scale.x, parentScale.x), SafeDivide(scale.y, parentScale.y), - SafeDivide(scale.z, parentScale.z)); + SafeDivide(scale.z, parentScale.z) + ); } RecomputeWorldFromLocal(); @@ -291,53 +295,57 @@ internal void RecomputeWorldFromLocal(bool notifyChildren = true) m_worldScale = new Vector3( m_localScale.x * m_parent.m_worldScale.x, m_localScale.y * m_parent.m_worldScale.y, - m_localScale.z * m_parent.m_worldScale.z); + m_localScale.z * m_parent.m_worldScale.z + ); } RecomputeMatrixFromLocal(); - m_worldPosition = new Vector3( - m_localToWorldMatrix.m14, - m_localToWorldMatrix.m24, - m_localToWorldMatrix.m34); + m_worldPosition = new Vector3(m_localToWorldMatrix.m14, m_localToWorldMatrix.m24, m_localToWorldMatrix.m34); if (notifyChildren) + { NotifyChildrenWorldChanged(); + } } private void AdvanceCaptureRevision() { if (m_serializationRevision is { } revision) + { m_serializationRevision = revision == ulong.MaxValue ? null : revision + 1; + } } private void RecomputeMatrixFromLocal() { Matrix localMatrix = Matrix.CreateTranslation(m_localPosition) - * Matrix.CreateFromQuaternion(m_localRotation) - * Matrix.CreateScale(m_localScale); + * Matrix.CreateFromQuaternion(m_localRotation) + * Matrix.CreateScale(m_localScale); m_localToWorldMatrix = m_parent is null - ? localMatrix - : m_parent.m_localToWorldMatrix * localMatrix; + ? localMatrix + : m_parent.m_localToWorldMatrix * localMatrix; } private void NotifyChildrenWorldChanged() { for (int i = 0; i < m_children.Count; i++) + { m_children[i].RecomputeWorldFromLocal(); + } } private static float SafeDivide( float numerator, float denominator - ) - => MathHelper.AlmostEquals(denominator, 0f) ? 0f : numerator / denominator; + ) => MathHelper.AlmostEquals(denominator, 0f) ? 0f : numerator / denominator; private static void EnsureInvertible(Matrix matrix) { if (MathF.Abs(Matrix.Determinant(matrix)) < MathHelper.C_TOLERANCE) { throw new InvalidOperationException( - "A transform hierarchy with zero scale cannot be converted from world space."); + "A transform hierarchy with zero scale cannot be converted from world space." + ); } } } diff --git a/src/content/scene/Inno.Scene/Core/EngineObject.cs b/src/content/scene/Inno.Scene/Core/EngineObject.cs index 2f5f8886b..b1b1a8ccc 100644 --- a/src/content/scene/Inno.Scene/Core/EngineObject.cs +++ b/src/content/scene/Inno.Scene/Core/EngineObject.cs @@ -1,6 +1,5 @@ using System; using System.Runtime.CompilerServices; - using Inno.Core.Identity; namespace Inno.Scene; @@ -34,11 +33,17 @@ public abstract class EngineObject : IdentityObject EngineObject? right ) { if (ReferenceEquals(left, right)) + { return true; + } if (ReferenceEquals(left, null)) + { return right!.m_isDestroyed; + } if (ReferenceEquals(right, null)) + { return left.m_isDestroyed; + } return ReferenceEquals(left, right); } @@ -81,15 +86,21 @@ public abstract class EngineObject : IdentityObject internal void RegisterIdentity(Guid? persistentId = null) { if (m_isDestroyed) + { throw new InvalidOperationException($"Destroyed object '{GetType().FullName}' cannot be registered."); + } if (!IdentityAllocator.current.Register(this, persistentId)) + { throw new InvalidOperationException($"Identity registration failed for '{GetType().FullName}'."); + } } internal void MarkDestroyed() { if (m_isDestroyed) + { return; + } try { IdentityAllocator.current.Unregister(this); @@ -105,22 +116,27 @@ internal Guid ReleaseIdentityForReplacement() ValidateIdentityForReplacement(); Guid persistentId = identity.persistentId; if (!IdentityAllocator.current.Unregister(this)) + { throw new InvalidOperationException($"Identity release failed for '{GetType().FullName}'."); + } return persistentId; } internal void ValidateIdentityForReplacement() { if (m_isDestroyed) + { throw new InvalidOperationException($"Destroyed object '{GetType().FullName}' cannot be replaced."); + } RuntimeIdentity? owner = identity.runtimeIdentity; IdentityAllocator allocator = IdentityAllocator.current; if (owner is not RuntimeIdentity registered || registered.domainId != allocator.domainId - || !ReferenceEquals(allocator.Get(registered), this)) - { + || !ReferenceEquals(allocator.Get(registered), this) + ) { throw new InvalidOperationException( $"Identity replacement for '{GetType().FullName}' requires its owning domain " - + $"'{owner?.domainId.ToString() ?? "detached"}', but the current domain is '{allocator.domainId}'."); + + $"'{owner?.domainId.ToString() ?? "detached"}', but the current domain is '{allocator.domainId}'." + ); } } } diff --git a/src/content/scene/Inno.Scene/Core/GameBehavior.cs b/src/content/scene/Inno.Scene/Core/GameBehavior.cs index de35eb4ad..133ea1336 100644 --- a/src/content/scene/Inno.Scene/Core/GameBehavior.cs +++ b/src/content/scene/Inno.Scene/Core/GameBehavior.cs @@ -25,11 +25,15 @@ public bool enabled set { if (m_enabled == value) + { return; + } m_enabled = value; GameObject? owner = ownerOrNull; if (owner is { isRuntimeValid: true }) + { owner.scene.NotifyGameBehaviorActivationChanged(this); + } } } @@ -41,58 +45,42 @@ public bool enabled /// /// Called once before this behavior first becomes active. /// - protected virtual void Awake() - { - } + protected virtual void Awake() {} /// /// Called once immediately before the first update of this behavior. /// - protected virtual void Start() - { - } + protected virtual void Start() {} /// /// Called when this component becomes active and enabled. /// - protected virtual void OnEnable() - { - } + protected virtual void OnEnable() {} /// /// Called when this component stops being active and enabled. /// - protected virtual void OnDisable() - { - } + protected virtual void OnDisable() {} /// /// Called during the variable-rate update stage. Use Time.deltaTime for frame timing. /// - protected virtual void Update() - { - } + protected virtual void Update() {} /// /// Called during the fixed-rate update stage. Use Time.fixedDeltaTime for step timing. /// - protected virtual void FixedUpdate() - { - } + protected virtual void FixedUpdate() {} /// /// Called during the late update stage. Use Time.deltaTime for frame timing. /// - protected virtual void LateUpdate() - { - } + protected virtual void LateUpdate() {} /// /// Called immediately before this behavior is detached and destroyed. /// - protected virtual void OnDestroy() - { - } + protected virtual void OnDestroy() {} internal bool lifecycleAwakeCalled { get; set; } internal bool lifecycleStartCalled { get; set; } @@ -101,12 +89,19 @@ protected virtual void OnDestroy() internal GameBehaviorLifecyclePhase lifecyclePhases { get; set; } internal void DispatchAwake() => Awake(); + internal void DispatchStart() => Start(); + internal void DispatchEnable() => OnEnable(); + internal void DispatchDisable() => OnDisable(); + internal void DispatchUpdate() => Update(); + internal void DispatchFixedUpdate() => FixedUpdate(); + internal void DispatchLateUpdate() => LateUpdate(); + internal void DispatchDestroy() => OnDestroy(); bool ISceneLifecycleObject.lifecycleAwakeCalled @@ -114,26 +109,35 @@ bool ISceneLifecycleObject.lifecycleAwakeCalled get => lifecycleAwakeCalled; set => lifecycleAwakeCalled = value; } + bool ISceneLifecycleObject.lifecycleStartCalled { get => lifecycleStartCalled; set => lifecycleStartCalled = value; } + bool ISceneLifecycleObject.lifecycleDestroyCalled { get => lifecycleDestroyCalled; set => lifecycleDestroyCalled = value; } + bool ISceneLifecycleObject.lifecycleIsActive => isActiveAndEnabled; bool ISceneLifecycleObject.lifecycleIsDestroyed => isDestroyed; + bool ISceneLifecycleObject.lifecycleWasEnabled { get => lifecycleWasEnabled; set => lifecycleWasEnabled = value; } + void ISceneLifecycleObject.DispatchAwake() => Awake(); + void ISceneLifecycleObject.DispatchStart() => Start(); + void ISceneLifecycleObject.DispatchEnable() => OnEnable(); + void ISceneLifecycleObject.DispatchDisable() => OnDisable(); + void ISceneLifecycleObject.DispatchDestroy() => OnDestroy(); } diff --git a/src/content/scene/Inno.Scene/Core/GameComponent.cs b/src/content/scene/Inno.Scene/Core/GameComponent.cs index 254a47d36..00a7edcb3 100644 --- a/src/content/scene/Inno.Scene/Core/GameComponent.cs +++ b/src/content/scene/Inno.Scene/Core/GameComponent.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Serialization; using Inno.Scene.Components; @@ -20,8 +19,8 @@ public abstract class GameComponent : EngineObject, ISerializable /// public GameObject gameObject => m_gameObject is not null && !isDestroyed - ? m_gameObject - : throw new InvalidOperationException($"GameComponent '{GetType().FullName}' is detached or destroyed."); + ? m_gameObject + : throw new InvalidOperationException($"GameComponent '{GetType().FullName}' is detached or destroyed."); /// /// Gets the owning game object's transform. @@ -34,9 +33,7 @@ public GameObject gameObject /// /// Restores this component to its default state when it is added or explicitly reset. /// - protected virtual void Reset() - { - } + protected virtual void Reset() {} internal GameObject? ownerOrNull => m_gameObject; @@ -44,7 +41,9 @@ internal void Attach(GameObject owner) { ArgumentNullException.ThrowIfNull(owner); if (m_gameObject is not null) + { throw new InvalidOperationException($"GameComponent '{GetType().FullName}' is already attached."); + } m_gameObject = owner; } diff --git a/src/content/scene/Inno.Scene/Core/GameObject.cs b/src/content/scene/Inno.Scene/Core/GameObject.cs index e3b9aed50..5d950f485 100644 --- a/src/content/scene/Inno.Scene/Core/GameObject.cs +++ b/src/content/scene/Inno.Scene/Core/GameObject.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Serialization; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -67,7 +66,9 @@ public string name GameScene owner = EnsureAlive(); string requestedName = value ?? string.Empty; if (string.Equals(m_name, requestedName, StringComparison.Ordinal)) + { return; + } AdvanceCaptureRevision(); m_name = requestedName; owner.NotifyObjectMetadataChanged(this); @@ -96,7 +97,9 @@ public string tag GameScene owner = EnsureAlive(); string requestedTag = NormalizeTag(value); if (string.Equals(m_tag, requestedTag, StringComparison.Ordinal)) + { return; + } AdvanceCaptureRevision(); m_tag = requestedTag; owner.NotifyObjectMetadataChanged(this); @@ -121,7 +124,9 @@ public GameLayer layer { GameScene owner = EnsureAlive(); if (m_layer == value) + { return; + } AdvanceCaptureRevision(); m_layer = value; owner.NotifyObjectMetadataChanged(this); @@ -192,7 +197,8 @@ public bool activeSelf /// /// The attached component. /// - public TComponent AddComponent() where TComponent : GameComponent => (TComponent)AddComponent(typeof(TComponent)); + public TComponent AddComponent() + where TComponent : GameComponent => (TComponent)AddComponent(typeof(TComponent)); /// /// Creates and attaches a component of the requested runtime type. @@ -218,11 +224,16 @@ public GameComponent AddComponent(Type componentType) /// /// Thrown when no matching component exists. /// - public TComponent GetComponent() where TComponent : GameComponent + public TComponent GetComponent() + where TComponent : GameComponent { if (TryGetComponent(out TComponent? component) && component is not null) + { return component; - throw new InvalidOperationException($"GameObject '{m_name}' does not contain component '{typeof(TComponent).FullName}'. Add it explicitly before calling GetComponent."); + } + throw new InvalidOperationException( + $"GameObject '{m_name}' does not contain component '{typeof(TComponent).FullName}'. Add it explicitly before calling GetComponent." + ); } /// @@ -241,8 +252,12 @@ public GameComponent GetComponent(Type componentType) { ArgumentNullException.ThrowIfNull(componentType); if (EnsureAlive().TryGetComponent(this, componentType, out GameComponent? component) && component is not null) + { return component; - throw new InvalidOperationException($"GameObject '{m_name}' does not contain component '{componentType.FullName}'. Add it explicitly before calling GetComponent."); + } + throw new InvalidOperationException( + $"GameObject '{m_name}' does not contain component '{componentType.FullName}'. Add it explicitly before calling GetComponent." + ); } /// @@ -257,7 +272,8 @@ public GameComponent GetComponent(Type componentType) /// /// when a matching component exists. /// - public bool TryGetComponent(out TComponent? component) where TComponent : GameComponent + public bool TryGetComponent(out TComponent? component) + where TComponent : GameComponent { if (!isRuntimeValid) { @@ -277,7 +293,8 @@ public bool TryGetComponent(out TComponent? component) where TCompon /// /// when a matching component exists. /// - public bool HasComponent() where TComponent : GameComponent => TryGetComponent(out _); + public bool HasComponent() + where TComponent : GameComponent => TryGetComponent(out _); /// /// Gets all attached components assignable to the requested type in attachment order. @@ -288,8 +305,9 @@ public bool TryGetComponent(out TComponent? component) where TCompon /// /// A stable component snapshot. /// - public IReadOnlyList GetComponents() where TComponent : GameComponent - => EnsureAlive().GetComponents(this); + public IReadOnlyList GetComponents() + where TComponent : GameComponent + => EnsureAlive().GetComponents(this); /// /// Gets all attached components in attachment order. @@ -377,7 +395,9 @@ public bool RemoveComponent(GameComponent component) internal void BindTransform(Transform transform) { if (m_transform is not null) + { throw new InvalidOperationException("GameObject transform is already initialized."); + } m_transform = transform; } @@ -385,7 +405,9 @@ internal void SetNameDirect(string value) { string requestedName = value ?? string.Empty; if (string.Equals(m_name, requestedName, StringComparison.Ordinal)) + { return; + } AdvanceCaptureRevision(); m_name = requestedName; m_scene?.NotifyObjectMetadataChanged(this); @@ -395,7 +417,9 @@ internal void SetTagDirect(string value) { string requestedTag = NormalizeTag(value); if (string.Equals(m_tag, requestedTag, StringComparison.Ordinal)) + { return; + } AdvanceCaptureRevision(); m_tag = requestedTag; m_scene?.NotifyObjectMetadataChanged(this); @@ -404,7 +428,9 @@ internal void SetTagDirect(string value) internal void SetLayerDirect(GameLayer value) { if (m_layer == value) + { return; + } AdvanceCaptureRevision(); m_layer = value; m_scene?.NotifyObjectMetadataChanged(this); @@ -415,6 +441,7 @@ internal void SetActiveSelfDirect(bool value) AdvanceCaptureRevision(); m_activeSelf = value; } + internal void SetActiveInHierarchyDirect(bool value) => m_activeInHierarchy = value; /// @@ -426,19 +453,25 @@ internal void SetActiveSelfDirect(bool value) internal void AttachRecord(SceneObjectRecord record) { if (m_attachment is not null) + { throw new InvalidOperationException("The object already owns a scene-store attachment."); + } m_attachment = record; } internal void ReleaseRecord(SceneObjectRecord record) { if (!ReferenceEquals(m_attachment, record)) + { throw new InvalidOperationException("The object no longer owns the retiring scene-store attachment."); + } m_attachment = null; } internal void SetSceneDirect(GameScene scene) => m_scene = scene ?? throw new ArgumentNullException(nameof(scene)); + internal void SetPrefabInstanceDirect(PrefabInstanceInfo? value) => m_prefabInstance = value; + internal void SetPrefabConnectionDirect(PrefabConnectionRecord? value) => m_prefabConnection = value; internal void DestroyDirect() @@ -453,7 +486,9 @@ internal void DestroyDirect() private GameScene EnsureAlive() { if (isDestroyed || m_scene is null || !m_scene.Contains(this)) + { throw new InvalidOperationException($"GameObject '{m_name}' is destroyed or detached from its scene."); + } return m_scene; } @@ -474,11 +509,12 @@ internal static string NormalizeTag(string value) ArgumentException.ThrowIfNullOrWhiteSpace(value); return value.Trim(); } + private void AdvanceCaptureRevision() { if (m_serializationRevision is { } revision) + { m_serializationRevision = revision == ulong.MaxValue ? null : revision + 1; + } } - - } diff --git a/src/content/scene/Inno.Scene/Core/GameScene.cs b/src/content/scene/Inno.Scene/Core/GameScene.cs index 3a3fc8cf1..0b73b9125 100644 --- a/src/content/scene/Inno.Scene/Core/GameScene.cs +++ b/src/content/scene/Inno.Scene/Core/GameScene.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -34,9 +33,7 @@ public sealed class GameScene : EngineObject, ISerializable /// Initial scene name. /// public GameScene(string name = "Untitled Scene") - : this(SceneWorld.current.typeCatalog, name, persistentId: null) - { - } + : this(SceneWorld.current.typeCatalog, name, persistentId: null) {} internal GameScene( SceneTypeCatalog types, @@ -114,9 +111,8 @@ public GameObject CreateObject(string name = "GameObject") public GameObject InstantiatePrefab( PrefabAsset prefab, Transform? parent = null - ) - => (m_ownerWorld ?? throw new InvalidOperationException("The scene is not loaded in a world.")) - .InstantiatePrefab(prefab, this, parent); + ) => (m_ownerWorld ?? throw new InvalidOperationException("The scene is not loaded in a world.")) + .InstantiatePrefab(prefab, this, parent); /// /// Recursively destroys a game object and its complete child subtree. @@ -131,7 +127,9 @@ public bool DestroyObject(GameObject gameObject) { ArgumentNullException.ThrowIfNull(gameObject); if (!Contains(gameObject)) + { return false; + } Guid persistentId = gameObject.identity.persistentId; Exception? firstException = null; @@ -156,7 +154,9 @@ public bool DestroyObject(GameObject gameObject) try { if (removed[i].wasCommitted && component is GameBehavior behavior) + { m_systems.DestroyGameBehavior(behavior); + } } catch (Exception exception) { @@ -165,14 +165,18 @@ public bool DestroyObject(GameObject gameObject) finally { if (!component.isDestroyed) + { component.Detach(); + } } } m_systems.NotifyGameBehaviorStructureChanged(); gameObject.DestroyDirect(); if (firstException is not null) + { throw new InvalidOperationException($"A destruction callback failed for GameObject '{persistentId}'.", firstException); + } return true; } @@ -294,7 +298,8 @@ public IReadOnlyList FindObjectsWithLayers(GameLayerMask layers) /// /// The registered system. /// - public TSystem AddSystem() where TSystem : GameSystem, new() + public TSystem AddSystem() + where TSystem : GameSystem, new() { EnsureNotDestroyed(); return m_systems.Add(); @@ -316,7 +321,8 @@ public GameSystem AddSystem(Type systemType) { throw new ArgumentException( $"{nameof(MissingGameSystem)} instances are created only by scene restoration.", - nameof(systemType)); + nameof(systemType) + ); } return m_systems.Add(systemType, persistentId: null, invokeReset: true); } @@ -414,8 +420,7 @@ internal GameSystem AddSystem( Type systemType, Guid? persistentId, bool invokeReset - ) - => m_systems.Add(systemType, persistentId, invokeReset); + ) => m_systems.Add(systemType, persistentId, invokeReset); internal MissingGameSystem AddMissingSystem( TypeRef missingType, @@ -423,13 +428,7 @@ internal MissingGameSystem AddMissingSystem( ReadOnlySpan serializedState, Guid? persistentId, IReadOnlyList? dependencies = null - ) - => m_systems.AddMissing( - missingType, - missingTypeName, - serializedState, - persistentId, - dependencies); + ) => m_systems.AddMissing(missingType, missingTypeName, serializedState, persistentId, dependencies); internal bool Contains(GameObject gameObject) => !isDestroyed && m_store.Contains(gameObject); @@ -451,23 +450,29 @@ bool invokeReset { throw new ArgumentException( $"{nameof(MissingGameComponent)} instances are created only by scene restoration.", - nameof(componentType)); + nameof(componentType) + ); } if (!typeof(GameComponent).IsAssignableFrom(componentType)) + { throw new ArgumentException($"Type '{componentType.FullName}' is not a scene component.", nameof(componentType)); + } - if (!m_types.TryGetComponent(componentType, out SceneComponentTypeDescriptor? descriptor) || - !descriptor!.isConcrete) - { + if (!m_types.TryGetComponent(componentType, out SceneComponentTypeDescriptor? descriptor) + || !descriptor!.isConcrete + ) { throw new ArgumentException( $"Type '{componentType.FullName}' is not an active concrete scene component.", - nameof(componentType)); + nameof(componentType) + ); } bool allowsMultiple = descriptor.allowsMultiple; GameComponent component = ComponentFactory.Create(componentType, m_types.snapshot); if (component is GameBehavior createdBehavior) + { createdBehavior.lifecyclePhases = descriptor.behaviorPhases; + } component.Attach(owner); bool addedToStore = false; bool registeredHierarchy = false; @@ -485,19 +490,29 @@ bool invokeReset } if (invokeReset) + { component.DispatchReset(); + } if (component is GameBehavior behavior) + { m_systems.NotifyGameBehaviorActivationChanged(behavior); + } return component; } catch { if (registeredHierarchy && component is Transform transform) + { m_hierarchy.Unregister(transform); + } if (addedToStore) + { m_store.RemoveComponent(owner, component); + } if (!component.isDestroyed) + { component.Detach(); + } throw; } } @@ -508,22 +523,32 @@ GameComponent component ) { EnsureOwned(owner); if (!ReferenceEquals(component.ownerOrNull, owner)) + { return false; + } if (component is Transform) + { throw new InvalidOperationException("The mandatory Transform component cannot be removed."); + } SceneStoreRemovalKind removal = m_store.RemoveComponent(owner, component); if (removal == SceneStoreRemovalKind.None) + { return false; + } try { if (removal == SceneStoreRemovalKind.RemovedCommitted && component is GameBehavior behavior) + { m_systems.DestroyGameBehavior(behavior); + } } finally { if (!component.isDestroyed) + { component.Detach(); + } m_systems.NotifyGameBehaviorStructureChanged(); } return true; @@ -538,11 +563,7 @@ internal MissingGameComponent AddMissingComponent( IReadOnlyList? dependencies = null ) { EnsureOwned(owner); - var component = new MissingGameComponent( - missingType, - missingTypeName, - serializedState, - dependencies); + var component = new MissingGameComponent(missingType, missingTypeName, serializedState, dependencies); component.Attach(owner); bool addedToStore = false; try @@ -556,9 +577,13 @@ internal MissingGameComponent AddMissingComponent( catch { if (addedToStore) + { m_store.RemoveComponent(owner, component); + } if (!component.isDestroyed) + { component.Detach(); + } throw; } } @@ -570,7 +595,11 @@ GameComponent component EnsureOwned(owner); ArgumentNullException.ThrowIfNull(component); if (!ReferenceEquals(component.ownerOrNull, owner)) - throw new InvalidOperationException($"GameComponent '{component.GetType().FullName}' is not attached to GameObject '{owner.name}'."); + { + throw new InvalidOperationException( + $"GameComponent '{component.GetType().FullName}' is not attached to GameObject '{owner.name}'." + ); + } component.DispatchReset(); } @@ -604,20 +633,17 @@ internal IReadOnlyList GetComponents(GameObject owner) return m_store.GetComponents(owner, m_types.GetComponent(typeof(TComponent))); } - internal IReadOnlyList GetComponents() where TComponent : GameComponent - => m_store.GetComponents(m_types.GetComponent(typeof(TComponent))); + internal IReadOnlyList GetComponents() + where TComponent : GameComponent + => m_store.GetComponents(m_types.GetComponent(typeof(TComponent))); internal bool TryGetComponent( GameObject owner, out TComponent? component - ) - where TComponent : GameComponent + ) where TComponent : GameComponent { EnsureOwned(owner); - return m_store.TryGetComponent( - owner, - m_types.GetComponent(typeof(TComponent)), - out component); + return m_store.TryGetComponent(owner, m_types.GetComponent(typeof(TComponent)), out component); } internal bool TryGetComponent( @@ -635,23 +661,23 @@ out GameComponent? component return m_store.TryGetComponent(owner, descriptor!, out component); } - internal IReadOnlyList Query() where T1 : GameComponent => m_store.Query(m_types.GetComponent(typeof(T1))); + internal IReadOnlyList Query() + where T1 : GameComponent => m_store.Query(m_types.GetComponent(typeof(T1))); internal IReadOnlyList Query() where T1 : GameComponent where T2 : GameComponent - => m_store.Query( - m_types.GetComponent(typeof(T1)), - m_types.GetComponent(typeof(T2))); + => m_store.Query(m_types.GetComponent(typeof(T1)), m_types.GetComponent(typeof(T2))); internal IReadOnlyList Query() where T1 : GameComponent where T2 : GameComponent where T3 : GameComponent - => m_store.Query( - m_types.GetComponent(typeof(T1)), - m_types.GetComponent(typeof(T2)), - m_types.GetComponent(typeof(T3))); + => m_store.Query( + m_types.GetComponent(typeof(T1)), + m_types.GetComponent(typeof(T2)), + m_types.GetComponent(typeof(T3)) + ); internal IDisposable BeginExecutionPhase() => m_store.BeginExecutionPhase(); @@ -669,23 +695,31 @@ internal void ReplaceComponentForReload( int replacementRuntimeTypeId ) { GameObject owner = previous.ownerOrNull - ?? throw new InvalidOperationException("The component being replaced is detached."); + ?? throw new InvalidOperationException("The component being replaced is detached."); if (!Contains(owner) || previous is Transform || replacement is Transform) + { throw new InvalidOperationException("Only attached non-Transform components can be hot reloaded."); + } previous.ValidateIdentityForReplacement(); if (replacement.identity.runtimeId is not null) + { throw new InvalidOperationException("The replacement component already has a registered identity."); + } bool attachedHere = replacement.ownerOrNull is null; if (attachedHere) + { replacement.Attach(owner); + } else if (!ReferenceEquals(replacement.ownerOrNull, owner)) + { throw new InvalidOperationException("The replacement component belongs to another GameObject."); + } Guid persistentId = previous.identity.persistentId; try { - if (replacement is GameBehavior replacementBehavior && - m_types.TryGetComponent(replacement.GetType(), out SceneComponentTypeDescriptor? replacementDescriptor)) - { + if (replacement is GameBehavior replacementBehavior + && m_types.TryGetComponent(replacement.GetType(), out SceneComponentTypeDescriptor? replacementDescriptor) + ) { replacementBehavior.lifecyclePhases = replacementDescriptor!.behaviorPhases; } _ = previous.ReleaseIdentityForReplacement(); @@ -733,10 +767,13 @@ int replacementRuntimeTypeId } } if (rollbackFailures is null) + { throw; + } throw new InvalidOperationException( "Component hot-reload replacement failed and its identity rollback was incomplete.", - new AggregateException([exception, .. rollbackFailures])); + new AggregateException([exception, .. rollbackFailures]) + ); } } @@ -744,8 +781,7 @@ internal void ReplaceSystemForReload( GameSystem previous, GameSystem replacement, int replacementRuntimeTypeId - ) - => m_systems.ReplaceForReload(previous, replacement, replacementRuntimeTypeId); + ) => m_systems.ReplaceForReload(previous, replacement, replacementRuntimeTypeId); internal bool canDispatch => m_isLoaded && !m_isUnloading && !isDestroyed; @@ -761,16 +797,21 @@ internal void PrepareRestoreTarget(Guid persistentId) if (identity.persistentId != persistentId) { throw new InvalidOperationException( - $"Scene identity '{identity.persistentId}' does not match serialized identity '{persistentId}'."); + $"Scene identity '{identity.persistentId}' does not match serialized identity '{persistentId}'." + ); } foreach (GameSystem system in GetSystems().ToArray()) + { RemoveSystem(system); + } GameObject[] objects = GetObjects().ToArray(); for (int i = 0; i < objects.Length; i++) { if (objects[i].isRuntimeValid) + { DestroyObject(objects[i]); + } } } @@ -796,14 +837,18 @@ internal void NotifyGameBehaviorActivationChanged(GameBehavior behavior) { ArgumentNullException.ThrowIfNull(behavior); if (behavior.ownerOrNull is GameObject owner && Contains(owner)) + { m_systems.NotifyGameBehaviorActivationChanged(behavior); + } } internal void NotifyGameSystemActivationChanged(GameSystem system) { ArgumentNullException.ThrowIfNull(system); if (ReferenceEquals(system.ownerScene, this)) + { m_systems.NotifyGameSystemActivationChanged(system); + } } internal void SetParent( @@ -837,12 +882,15 @@ GameScene destination ArgumentNullException.ThrowIfNull(destination); destination.EnsureNotDestroyed(); if (ReferenceEquals(this, destination)) - return; - if (m_store.isExecuting || m_store.hasPendingChanges || - destination.m_store.isExecuting || destination.m_store.hasPendingChanges) { + return; + } + if (m_store.isExecuting || m_store.hasPendingChanges + || destination.m_store.isExecuting || destination.m_store.hasPendingChanges + ) { throw new InvalidOperationException( - "A GameObject cannot move between scenes during a scene execution phase or while structural changes are pending."); + "A GameObject cannot move between scenes during a scene execution phase or while structural changes are pending." + ); } Transform rootTransform = gameObject.transform; @@ -851,10 +899,14 @@ GameScene destination GameObject[] subtree = EnumerateSubtree(rootTransform).ToArray(); var components = new Dictionary(ReferenceEqualityComparer.Instance); for (int i = 0; i < subtree.Length; i++) + { components.Add(subtree[i], m_store.GetComponents(subtree[i]).ToArray()); + } if (previousParent is not null) + { m_hierarchy.SetParent(rootTransform, parent: null, worldPositionStays: true); + } m_hierarchy.Unregister(rootTransform); int transferredCount = 0; @@ -875,7 +927,8 @@ GameScene destination current, component, m_types.GetComponent(component.GetType()), - allowsMultiple: true); + allowsMultiple: true + ); } current.SetSceneDirect(destination); } @@ -887,7 +940,9 @@ GameScene destination catch { if (registeredDestinationHierarchy) + { destination.m_hierarchy.Unregister(rootTransform); + } for (int i = transferredCount - 1; i >= 0; i--) { GameObject current = subtree[i]; @@ -901,14 +956,17 @@ GameScene destination current, component, m_types.GetComponent(component.GetType()), - allowsMultiple: true); + allowsMultiple: true + ); } current.SetSceneDirect(this); } m_hierarchy.Register(rootTransform); if (previousParent is not null) + { m_hierarchy.SetParent(rootTransform, previousParent, worldPositionStays: true); + } m_hierarchy.SetSiblingIndex(rootTransform, previousSiblingIndex); m_activation.RecomputeSubtree(gameObject); throw; @@ -933,9 +991,13 @@ bool invokeReset catch { if (Contains(gameObject)) + { DestroyObject(gameObject); + } else if (!gameObject.isDestroyed) + { gameObject.DestroyDirect(); + } throw; } } @@ -945,7 +1007,9 @@ internal void Load(SceneWorld ownerWorld) ArgumentNullException.ThrowIfNull(ownerWorld); EnsureNotDestroyed(); if (m_isLoaded) + { throw new InvalidOperationException($"Scene '{m_name}' is already loaded."); + } m_ownerWorld = ownerWorld; m_isLoaded = true; m_systems.NotifyHierarchyActivationChanged(); @@ -954,7 +1018,9 @@ internal void Load(SceneWorld ownerWorld) internal void Unload() { if (isDestroyed || m_isUnloading) + { return; + } m_isUnloading = true; m_isLoaded = false; @@ -966,7 +1032,9 @@ internal void Unload() try { if (Contains(objects[i])) + { DestroyObject(objects[i]); + } } catch (Exception exception) { @@ -980,25 +1048,33 @@ internal void Unload() m_sourceAsset = null; MarkDestroyed(); if (firstException is not null) + { throw new InvalidOperationException($"Scene '{m_name}' encountered an error while unloading.", firstException); + } } internal void FixedUpdate(float fixedDeltaTime) { if (canDispatch) + { m_systems.FixedUpdate(); + } } internal void Update(float deltaTime) { if (canDispatch) + { m_systems.Update(); + } } internal void LateUpdate(float deltaTime) { if (canDispatch) + { m_systems.LateUpdate(); + } } private void EnsureOwned(GameObject gameObject) @@ -1006,13 +1082,17 @@ private void EnsureOwned(GameObject gameObject) ArgumentNullException.ThrowIfNull(gameObject); EnsureNotDestroyed(); if (!m_store.Contains(gameObject)) + { throw new InvalidOperationException($"GameObject does not belong to scene '{m_name}'."); + } } private void EnsureNotDestroyed() { if (isDestroyed) + { throw new InvalidOperationException($"Scene '{m_name}' has been destroyed and cannot be reused."); + } } private static IEnumerable EnumerateSubtree(Transform root) @@ -1022,7 +1102,9 @@ private static IEnumerable EnumerateSubtree(Transform root) for (int i = 0; i < children.Count; i++) { foreach (GameObject descendant in EnumerateSubtree(children[i])) + { yield return descendant; + } } } } diff --git a/src/content/scene/Inno.Scene/Core/GameSystem.cs b/src/content/scene/Inno.Scene/Core/GameSystem.cs index 8a7c8e9c1..0505a6cc9 100644 --- a/src/content/scene/Inno.Scene/Core/GameSystem.cs +++ b/src/content/scene/Inno.Scene/Core/GameSystem.cs @@ -1,8 +1,7 @@ using System; using System.Collections.Generic; - -using Inno.Scripting.Api; using Inno.Core.Serialization; +using Inno.Scripting.Api; namespace Inno.Scene; @@ -26,10 +25,14 @@ public bool enabled { bool next = value && this is not MissingGameSystem; if (m_enabled == next) + { return; + } m_enabled = next; if (m_scene is { isLoaded: true }) + { m_scene.NotifyGameSystemActivationChanged(this); + } } } @@ -48,70 +51,53 @@ public bool enabled /// protected GameScene scene => m_scene ?? throw new InvalidOperationException( - $"System '{GetType().FullName}' is not registered with a scene."); + $"System '{GetType().FullName}' is not registered with a scene." + ); /// /// Restores this system to defaults when added or explicitly reset. /// - protected virtual void Reset() - { - } + protected virtual void Reset() {} /// /// Called once before the system first becomes active. /// - protected virtual void Awake() - { - } + protected virtual void Awake() {} /// /// Called once immediately before the first update. /// - protected virtual void Start() - { - } + protected virtual void Start() {} /// /// Called when the system becomes active and enabled. /// - protected virtual void OnEnable() - { - } + protected virtual void OnEnable() {} /// /// Called when the system stops being active and enabled. /// - protected virtual void OnDisable() - { - } + protected virtual void OnDisable() {} /// /// Called before a system that entered runtime lifecycle is destroyed. /// - protected virtual void OnDestroy() - { - } + protected virtual void OnDestroy() {} /// /// Called during the fixed-rate scene stage. Use Time.fixedDeltaTime for step timing. /// - protected virtual void OnFixedUpdate() - { - } + protected virtual void OnFixedUpdate() {} /// /// Called during the variable-rate scene stage. Use Time.deltaTime for frame timing. /// - protected virtual void OnUpdate() - { - } + protected virtual void OnUpdate() {} /// /// Called during the late scene stage. Use Time.deltaTime for frame timing. /// - protected virtual void OnLateUpdate() - { - } + protected virtual void OnLateUpdate() {} /// /// Gets all scene components assignable to a requested type. @@ -122,7 +108,8 @@ protected virtual void OnLateUpdate() /// /// An immutable snapshot of the values selected by the operation. /// - protected IReadOnlyList GetComponents() where TComponent : GameComponent => scene.GetComponents(); + protected IReadOnlyList GetComponents() + where TComponent : GameComponent => scene.GetComponents(); /// /// Gets all committed live game objects in deterministic scene storage order. @@ -141,7 +128,8 @@ protected virtual void OnLateUpdate() /// /// An immutable snapshot of the values selected by the operation. /// - protected IReadOnlyList Query() where T1 : GameComponent => scene.Query(); + protected IReadOnlyList Query() + where T1 : GameComponent => scene.Query(); /// /// Queries game objects containing two required component types. @@ -158,7 +146,7 @@ protected virtual void OnLateUpdate() protected IReadOnlyList Query() where T1 : GameComponent where T2 : GameComponent - => scene.Query(); + => scene.Query(); /// /// Queries game objects containing three required component types. @@ -179,7 +167,7 @@ protected IReadOnlyList Query() where T1 : GameComponent where T2 : GameComponent where T3 : GameComponent - => scene.Query(); + => scene.Query(); internal bool lifecycleAwakeCalled { get; set; } internal bool lifecycleStartCalled { get; set; } @@ -191,7 +179,9 @@ internal void Attach(GameScene owner) { ArgumentNullException.ThrowIfNull(owner); if (m_scene is not null) + { throw new InvalidOperationException($"System '{GetType().FullName}' is already registered."); + } m_scene = owner; } @@ -202,35 +192,47 @@ internal void Detach() } internal void DispatchReset() => Reset(); + internal void DispatchFixedUpdate() => OnFixedUpdate(); + internal void DispatchUpdate() => OnUpdate(); + internal void DispatchLateUpdate() => OnLateUpdate(); bool ISceneLifecycleObject.lifecycleIsActive => isActiveAndEnabled; bool ISceneLifecycleObject.lifecycleIsDestroyed => isDestroyed; + bool ISceneLifecycleObject.lifecycleAwakeCalled { get => lifecycleAwakeCalled; set => lifecycleAwakeCalled = value; } + bool ISceneLifecycleObject.lifecycleStartCalled { get => lifecycleStartCalled; set => lifecycleStartCalled = value; } + bool ISceneLifecycleObject.lifecycleWasEnabled { get => lifecycleWasEnabled; set => lifecycleWasEnabled = value; } + bool ISceneLifecycleObject.lifecycleDestroyCalled { get => lifecycleDestroyCalled; set => lifecycleDestroyCalled = value; } + void ISceneLifecycleObject.DispatchAwake() => Awake(); + void ISceneLifecycleObject.DispatchStart() => Start(); + void ISceneLifecycleObject.DispatchEnable() => OnEnable(); + void ISceneLifecycleObject.DispatchDisable() => OnDisable(); + void ISceneLifecycleObject.DispatchDestroy() => OnDestroy(); } diff --git a/src/content/scene/Inno.Scene/Core/GameTagCatalog.cs b/src/content/scene/Inno.Scene/Core/GameTagCatalog.cs index 3275706aa..059c90b90 100644 --- a/src/content/scene/Inno.Scene/Core/GameTagCatalog.cs +++ b/src/content/scene/Inno.Scene/Core/GameTagCatalog.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Types; namespace Inno.Scene; @@ -53,7 +52,9 @@ public ProjectLocalId GetLocalId(string tag) { string normalized = Normalize(tag); if (!IsDefined(normalized)) + { throw new KeyNotFoundException($"Game tag '{normalized}' is not defined."); + } return ProjectLocalId.FromName(normalized); } @@ -110,7 +111,9 @@ public bool Add(string tag) string normalized = Normalize(tag); ValidateState(); if (m_tags.Contains(normalized, StringComparer.Ordinal)) + { return false; + } m_tags = m_tags .Append(normalized) .OrderBy(static value => string.Equals(value, GameObject.defaultTag, StringComparison.Ordinal) ? 0 : 1) @@ -136,12 +139,17 @@ public bool Remove(string tag) string normalized = Normalize(tag); ValidateState(); if (string.Equals(normalized, GameObject.defaultTag, StringComparison.Ordinal)) + { return false; + } int index = Array.FindIndex( m_tags, - candidate => string.Equals(candidate, normalized, StringComparison.Ordinal)); + candidate => string.Equals(candidate, normalized, StringComparison.Ordinal) + ); if (index < 0) + { return false; + } m_tags = m_tags.Where(candidate => !string.Equals(candidate, normalized, StringComparison.Ordinal)).ToArray(); return true; } @@ -166,29 +174,38 @@ internal static string Normalize(string tag) ArgumentException.ThrowIfNullOrWhiteSpace(tag); string normalized = tag.Trim(); if (normalized.Contains('\r') || normalized.Contains('\n')) + { throw new ArgumentException("Tags cannot contain line breaks.", nameof(tag)); + } return normalized; } private void ValidateState() { if (m_tags is null || m_tags.Length == 0) + { throw new InvalidOperationException("A tag catalog must contain the built-in default tag."); + } string[] normalized = m_tags .Select(Normalize) .OrderBy(static value => string.Equals(value, GameObject.defaultTag, StringComparison.Ordinal) ? 0 : 1) .ThenBy(static value => value, StringComparer.Ordinal) .ToArray(); if (!string.Equals(normalized[0], GameObject.defaultTag, StringComparison.Ordinal)) + { throw new InvalidOperationException("The built-in default tag must be the first project tag."); + } if (normalized.Distinct(StringComparer.Ordinal).Count() != normalized.Length) + { throw new InvalidOperationException("Project tag definitions must be unique."); + } if (normalized.Select(ProjectLocalId.FromName).Distinct().Count() != normalized.Length) { - throw new InvalidOperationException( - "Project tag names must produce unique project-local identities."); + throw new InvalidOperationException("Project tag names must produce unique project-local identities."); } if (!normalized.SequenceEqual(m_tags, StringComparer.Ordinal)) + { throw new InvalidOperationException("Project tag definitions are not normalized and deterministically ordered."); + } } } diff --git a/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs b/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs index cf55dfeee..1c15784a8 100644 --- a/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs +++ b/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Serialization; using Inno.Core.Settings; @@ -11,8 +10,7 @@ namespace Inno.Scene; /// Composes sparse tag additions and removals from multiple setting contributors. /// [ProjectSettingComposer("inno.scene.tags")] -internal sealed class GameTagSettingsComposer - : ProjectSettingComposer +internal sealed class GameTagSettingsComposer : ProjectSettingComposer { /// /// Captures the contribution introduced by the supplied project setting value. @@ -74,25 +72,31 @@ IReadOnlyList> contributi foreach (string tag in contribution.value.removals) { if (!target.IsDefined(tag)) + { continue; + } string owner = owners[tag]; if (!contribution.context.CanOverride(owner)) { throw new InvalidOperationException( - $"GameTag contribution '{contribution.context.contributorId}' cannot remove tag '{tag}' " + - $"owned by '{owner}'."); + $"GameTag contribution '{contribution.context.contributorId}' cannot remove tag '{tag}' " + + $"owned by '{owner}'." + ); } if (!target.Remove(tag)) { throw new InvalidOperationException( - $"GameTag contribution '{contribution.context.contributorId}' cannot remove built-in tag '{tag}'."); + $"GameTag contribution '{contribution.context.contributorId}' cannot remove built-in tag '{tag}'." + ); } owners.Remove(tag); } foreach (string tag in contribution.value.additions) { if (target.IsDefined(tag)) + { continue; + } _ = target.Add(tag); owners.Add(tag, contribution.context.contributorId); } @@ -114,20 +118,24 @@ internal sealed class GameTagSettingContribution : ISerializable internal void Validate() { if (additions is null || removals is null) + { throw new InvalidOperationException("GameTag contribution arrays cannot be null."); + } string[] normalizedAdditions = additions.Select(GameTagCatalog.Normalize).Order(StringComparer.Ordinal).ToArray(); string[] normalizedRemovals = removals.Select(GameTagCatalog.Normalize).Order(StringComparer.Ordinal).ToArray(); if (!normalizedAdditions.SequenceEqual(additions, StringComparer.Ordinal) - || normalizedAdditions.Distinct(StringComparer.Ordinal).Count() != normalizedAdditions.Length) - { + || normalizedAdditions.Distinct(StringComparer.Ordinal).Count() != normalizedAdditions.Length + ) { throw new InvalidOperationException("GameTag additions must be unique, normalized, and ordered."); } if (!normalizedRemovals.SequenceEqual(removals, StringComparer.Ordinal) - || normalizedRemovals.Distinct(StringComparer.Ordinal).Count() != normalizedRemovals.Length) - { + || normalizedRemovals.Distinct(StringComparer.Ordinal).Count() != normalizedRemovals.Length + ) { throw new InvalidOperationException("GameTag removals must be unique, normalized, and ordered."); } if (normalizedAdditions.Intersect(normalizedRemovals, StringComparer.Ordinal).Any()) + { throw new InvalidOperationException("A GameTag contribution cannot add and remove the same tag."); + } } } diff --git a/src/content/scene/Inno.Scene/Layers/GameLayer.cs b/src/content/scene/Inno.Scene/Layers/GameLayer.cs index 8a47248ed..be619ee6f 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayer.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayer.cs @@ -29,7 +29,9 @@ namespace Inno.Scene.Layers; public GameLayer(int index) { if ((uint)index >= C_MAX_COUNT) + { throw new ArgumentOutOfRangeException(nameof(index), index, "A layer index must be between 0 and 31."); + } this.index = index; } diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerCatalog.cs b/src/content/scene/Inno.Scene/Layers/GameLayerCatalog.cs index 6e0736953..974d78b66 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerCatalog.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerCatalog.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Types; namespace Inno.Scene.Layers; @@ -76,10 +75,7 @@ public IReadOnlyList GetDefinitions() { if (m_names[index] is string name) { - result.Add(new GameLayerDefinition( - new ProjectLocalId(m_localIds[index]!), - new GameLayer(index), - name)); + result.Add(new GameLayerDefinition(new ProjectLocalId(m_localIds[index]!), new GameLayer(index), name)); } } return result; @@ -168,12 +164,16 @@ public bool TryGetLayer( out GameLayer layer ) { if (string.IsNullOrEmpty(localId.value)) + { throw new ArgumentException("A valid project-local layer ID is required.", nameof(localId)); + } ValidateState(); for (int index = 0; index < m_localIds.Length; index++) { if (!string.Equals(m_localIds[index], localId.value, StringComparison.Ordinal)) + { continue; + } layer = new GameLayer(index); return true; } @@ -202,15 +202,21 @@ public bool TryGetLayer( out GameLayer layer ) { if (!id.isValid) + { throw new ArgumentException("A valid GameLayer ID is required.", nameof(id)); + } ValidateState(); for (int index = 0; index < m_localIds.Length; index++) { if (m_localIds[index] is not string local) + { continue; + } var candidate = new GameLayerId(projectId, new ProjectLocalId(local)); if (candidate != id) + { continue; + } layer = new GameLayer(index); return true; } @@ -239,7 +245,9 @@ out GameLayer layer for (int index = 0; index < m_names.Length; index++) { if (!string.Equals(m_names[index], normalized, StringComparison.Ordinal)) + { continue; + } layer = new GameLayer(index); return true; } @@ -259,7 +267,9 @@ out GameLayer layer public GameLayer GetLayer(string name) { if (TryGetLayer(name, out GameLayer layer)) + { return layer; + } throw new KeyNotFoundException($"GameLayer '{name}' is not defined."); } @@ -277,7 +287,9 @@ public GameLayerMask GetMask(IEnumerable names) ArgumentNullException.ThrowIfNull(names); GameLayerMask result = GameLayerMask.none; foreach (string name in names) + { result = result.With(GetLayer(name)); + } return result; } @@ -295,7 +307,7 @@ public void Define( string name ) { ProjectLocalId localId = GetLocalId(layer) - ?? new ProjectLocalId($"layer.{layer.index.ToString("00", CultureInfo.InvariantCulture)}"); + ?? new ProjectLocalId($"layer.{layer.index.ToString("00", CultureInfo.InvariantCulture)}"); DefineLocal(layer, localId, name); } @@ -305,30 +317,34 @@ internal void DefineLocal( string name ) { if (string.IsNullOrEmpty(localId.value)) + { throw new ArgumentException("A valid project-local layer ID is required.", nameof(localId)); + } string normalized = NormalizeName(name); ValidateState(); for (int index = 0; index < m_names.Length; index++) { if (index != layer.index - && string.Equals(m_localIds[index], localId.value, StringComparison.Ordinal)) - { + && string.Equals(m_localIds[index], localId.value, StringComparison.Ordinal) + ) { throw new ArgumentException( $"GameLayer local ID '{localId}' is already assigned to slot {index}.", - nameof(localId)); + nameof(localId) + ); } if (index != layer.index - && string.Equals(m_names[index], normalized, StringComparison.Ordinal)) - { + && string.Equals(m_names[index], normalized, StringComparison.Ordinal) + ) { throw new ArgumentException( $"GameLayer name '{normalized}' is already assigned to slot {index}.", - nameof(name)); + nameof(name) + ); } } if (layer == GameLayer.defaultLayer && (localId != new ProjectLocalId("default") - || !string.Equals(normalized, C_DEFAULT_LAYER_NAME, StringComparison.Ordinal))) - { + || !string.Equals(normalized, C_DEFAULT_LAYER_NAME, StringComparison.Ordinal)) + ) { throw new ArgumentException("The built-in default layer cannot be replaced.", nameof(layer)); } m_localIds[layer.index] = localId.value; @@ -348,9 +364,13 @@ public bool Remove(GameLayer layer) { ValidateState(); if (layer == GameLayer.defaultLayer) + { throw new InvalidOperationException("The built-in default layer cannot be removed."); + } if (m_names[layer.index] is null) + { return false; + } m_localIds[layer.index] = null; m_names[layer.index] = null; return true; @@ -445,7 +465,9 @@ internal static string NormalizeName(string name) ArgumentException.ThrowIfNullOrWhiteSpace(name); string normalized = name.Trim(); if (normalized.Contains('\r') || normalized.Contains('\n')) + { throw new ArgumentException("GameLayer names cannot contain line breaks.", nameof(name)); + } return normalized; } @@ -488,14 +510,20 @@ uint[] interactionMasks private void ValidateState() { if (m_localIds is null || m_localIds.Length != GameLayer.C_MAX_COUNT) + { throw new InvalidOperationException("A layer stack must contain exactly thirty-two local ID slots."); + } if (m_names is null || m_names.Length != GameLayer.C_MAX_COUNT) + { throw new InvalidOperationException("A layer stack must contain exactly thirty-two name slots."); + } if (m_interactionMasks is null || m_interactionMasks.Length != GameLayer.C_MAX_COUNT) + { throw new InvalidOperationException("A layer stack must contain exactly thirty-two interaction masks."); + } if (!string.Equals(m_localIds[0], "default", StringComparison.Ordinal) - || !string.Equals(m_names[0], C_DEFAULT_LAYER_NAME, StringComparison.Ordinal)) - { + || !string.Equals(m_names[0], C_DEFAULT_LAYER_NAME, StringComparison.Ordinal) + ) { throw new InvalidOperationException("GameLayer slot zero must contain the built-in Default layer."); } @@ -506,17 +534,27 @@ private void ValidateState() string? localId = m_localIds[index]; string? name = m_names[index]; if ((localId is null) != (name is null)) + { throw new InvalidOperationException($"GameLayer slot {index} must define both a local ID and a name."); + } if (localId is null || name is null) + { continue; + } var normalizedId = new ProjectLocalId(localId); if (!ids.Add(normalizedId.value)) + { throw new InvalidOperationException($"GameLayer local ID '{localId}' is assigned more than once."); + } string normalizedName = NormalizeName(name); if (!string.Equals(name, normalizedName, StringComparison.Ordinal)) + { throw new InvalidOperationException($"GameLayer name in slot {index} is not normalized."); + } if (!names.Add(name)) + { throw new InvalidOperationException($"GameLayer name '{name}' is assigned more than once."); + } } for (int first = 0; first < m_interactionMasks.Length; first++) { @@ -527,7 +565,8 @@ private void ValidateState() if (forward != reverse) { throw new InvalidOperationException( - $"GameLayer interaction between slots {first} and {second} is not symmetric."); + $"GameLayer interaction between slots {first} and {second} is not symmetric." + ); } } } diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerCatalogConverter.cs b/src/content/scene/Inno.Scene/Layers/GameLayerCatalogConverter.cs index 65e4d955d..415dda84d 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerCatalogConverter.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerCatalogConverter.cs @@ -1,9 +1,8 @@ using System; using System.Linq; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Scene.Layers; @@ -27,12 +26,8 @@ GameLayerCatalog value ) { ArgumentNullException.ThrowIfNull(writer); ArgumentNullException.ThrowIfNull(value); - writer.Write( - "localIds", - value.CaptureLocalIds().Select(static id => id ?? string.Empty).ToArray()); - writer.Write( - "names", - value.CaptureNames().Select(static name => name ?? string.Empty).ToArray()); + writer.Write("localIds", value.CaptureLocalIds().Select(static id => id ?? string.Empty).ToArray()); + writer.Write("names", value.CaptureNames().Select(static name => name ?? string.Empty).ToArray()); writer.Write("interactionMasks", value.CaptureInteractionMasks()); } diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerConverter.cs b/src/content/scene/Inno.Scene/Layers/GameLayerConverter.cs index 44d6d3e6e..941089625 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerConverter.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerConverter.cs @@ -1,8 +1,7 @@ using System; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Scene.Layers; diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerDefinition.cs b/src/content/scene/Inno.Scene/Layers/GameLayerDefinition.cs index 1d6fed578..7080ad576 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerDefinition.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerDefinition.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Settings; namespace Inno.Scene.Layers; @@ -27,7 +26,9 @@ public GameLayerDefinition( string name ) { if (string.IsNullOrEmpty(localId.value)) + { throw new ArgumentException("A layer definition requires a valid local identity.", nameof(localId)); + } this.localId = localId; this.layer = layer; this.name = GameLayerCatalog.NormalizeName(name); diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerId.cs b/src/content/scene/Inno.Scene/Layers/GameLayerId.cs index 7ef968808..bcfef5660 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerId.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerId.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Settings; namespace Inno.Scene.Layers; @@ -18,7 +17,9 @@ public readonly record struct GameLayerId public GameLayerId(ProjectScopedId value) { if (string.IsNullOrEmpty(value.name.value)) + { throw new ArgumentException("A GameLayer ID requires a valid project-local name.", nameof(value)); + } this.value = value.value; } @@ -34,17 +35,16 @@ public GameLayerId(ProjectScopedId value) public GameLayerId( ProjectId projectId, ProjectLocalId name - ) - : this(projectId.Qualify(name)) - { - } + ) : this(projectId.Qualify(name)) {} internal GameLayerId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); string normalized = value.Trim(); if (!normalized.Contains('.', StringComparison.Ordinal)) + { throw new ArgumentException("A GameLayer ID must contain project and local name segments.", nameof(value)); + } for (int index = 0; index < normalized.Length; index++) { char character = normalized[index]; @@ -52,7 +52,9 @@ internal GameLayerId(string value) || character is >= '0' and <= '9' || character is '.' or '-' or '_'; if (!valid) + { throw new ArgumentException("A GameLayer ID is not portable.", nameof(value)); + } } this.value = normalized; } diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerIdConverter.cs b/src/content/scene/Inno.Scene/Layers/GameLayerIdConverter.cs index 019cc059e..931ec1352 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerIdConverter.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerIdConverter.cs @@ -1,8 +1,7 @@ using System; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Scene.Layers; diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs b/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs index b49ef99d8..ab69c7a3c 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs @@ -51,7 +51,9 @@ public static GameLayerMask FromLayers(IEnumerable layers) ArgumentNullException.ThrowIfNull(layers); uint bits = 0u; foreach (GameLayer layer in layers) + { bits |= 1u << layer.index; + } return new GameLayerMask(bits); } diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerMaskConverter.cs b/src/content/scene/Inno.Scene/Layers/GameLayerMaskConverter.cs index 26d36aadb..6bba57529 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerMaskConverter.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerMaskConverter.cs @@ -1,8 +1,7 @@ using System; - -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Scene.Layers; diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs b/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs index 95a3ee12d..cefbe7968 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Serialization; using Inno.Core.Settings; @@ -10,8 +9,7 @@ namespace Inno.Scene.Layers; /// Composes sparse project-local layer and interaction contributions into one compact runtime stack. /// [ProjectSettingComposer("inno.scene.layers")] -internal sealed class GameLayerSettingsComposer - : ProjectSettingComposer +internal sealed class GameLayerSettingsComposer : ProjectSettingComposer { /// /// Captures project-local layer and interaction changes relative to the baseline stack. @@ -48,8 +46,8 @@ GameLayerCatalog value } if (valueId is ProjectLocalId newId && (baselineId != valueId - || !string.Equals(baselineName, valueName, StringComparison.Ordinal))) - { + || !string.Equals(baselineName, valueName, StringComparison.Ordinal)) + ) { upsertSlots.Add(index); upsertLocalIds.Add(newId.value); upsertNames.Add(valueName!); @@ -68,7 +66,9 @@ GameLayerCatalog value bool baselineValue = baseline.CanInteract(firstLayer, secondLayer); bool authoredValue = value.CanInteract(firstLayer, secondLayer); if (baselineValue == authoredValue) + { continue; + } interactionFirstSlots.Add(first); interactionSecondSlots.Add(second); interactionValues.Add(authoredValue); @@ -130,7 +130,9 @@ IReadOnlyList> contribu localIdOwners.Add(localId, "host"); } for (int second = 0; second < GameLayer.C_MAX_COUNT; second++) + { interactionOwners[index, second] = "host"; + } } foreach (ProjectSettingContribution contribution in contributions) @@ -154,16 +156,21 @@ Dictionary localIdOwners var expected = new ProjectLocalId(contribution.value.removedLocalIds[index]); ProjectLocalId? current = target.GetLocalId(layer); if (current is null) + { continue; + } if (current != expected) { throw Conflict( contribution.context, - $"cannot remove layer '{expected}' from slot {layer.index} because it contains '{current}'."); + $"cannot remove layer '{expected}' from slot {layer.index} because it contains '{current}'." + ); } string owner = slotOwners[layer.index] ?? "host"; if (!contribution.context.CanOverride(owner)) + { throw Conflict(contribution.context, $"cannot remove layer '{expected}' owned by '{owner}'."); + } _ = target.Remove(layer); slotOwners[layer.index] = null; localIdOwners.Remove(expected); @@ -184,7 +191,9 @@ Dictionary localIdOwners ProjectLocalId? currentId = target.GetLocalId(layer); string? currentName = target.GetName(layer); if (currentId == localId && string.Equals(currentName, name, StringComparison.Ordinal)) + { continue; + } if (target.TryGetLayer(localId, out GameLayer existingLayer) && existingLayer != layer) { @@ -193,7 +202,8 @@ Dictionary localIdOwners { throw Conflict( contribution.context, - $"cannot move layer '{localId}' from slot {existingLayer.index}; it is owned by '{existingOwner}'."); + $"cannot move layer '{localId}' from slot {existingLayer.index}; it is owned by '{existingOwner}'." + ); } _ = target.Remove(existingLayer); slotOwners[existingLayer.index] = null; @@ -207,7 +217,8 @@ Dictionary localIdOwners { throw Conflict( contribution.context, - $"cannot replace slot {layer.index} layer '{replacedId}' owned by '{owner}'."); + $"cannot replace slot {layer.index} layer '{replacedId}' owned by '{owner}'." + ); } localIdOwners.Remove(replacedId); } @@ -228,13 +239,16 @@ private static void ApplyInteractions( var second = new GameLayer(contribution.value.interactionSecondSlots[index]); bool value = contribution.value.interactionValues[index]; if (target.CanInteract(first, second) == value) + { continue; + } string owner = interactionOwners[first.index, second.index]; if (!contribution.context.CanOverride(owner)) { throw Conflict( contribution.context, - $"cannot replace interaction ({first.index}, {second.index}) owned by '{owner}'."); + $"cannot replace interaction ({first.index}, {second.index}) owned by '{owner}'." + ); } target.SetInteraction(first, second, value); interactionOwners[first.index, second.index] = contribution.context.contributorId; @@ -245,8 +259,7 @@ private static void ApplyInteractions( private static InvalidOperationException Conflict( ProjectSettingContributionContext context, string message - ) - => new($"GameLayer contribution '{context.contributorId}' {message}"); + ) => new($"GameLayer contribution '{context.contributorId}' {message}"); } /// @@ -287,17 +300,21 @@ internal void Validate() || upsertNames is null || interactionFirstSlots is null || interactionSecondSlots is null - || interactionValues is null) - { + || interactionValues is null + ) { throw new InvalidOperationException("GameLayer contribution arrays cannot be null."); } if (removedSlots.Length != removedLocalIds.Length) + { throw new InvalidOperationException("GameLayer removal contribution arrays must have equal lengths."); + } if (upsertSlots.Length != upsertLocalIds.Length || upsertSlots.Length != upsertNames.Length) + { throw new InvalidOperationException("GameLayer upsert contribution arrays must have equal lengths."); + } if (interactionFirstSlots.Length != interactionSecondSlots.Length - || interactionFirstSlots.Length != interactionValues.Length) - { + || interactionFirstSlots.Length != interactionValues.Length + ) { throw new InvalidOperationException("GameLayer interaction contribution arrays must have equal lengths."); } @@ -307,7 +324,9 @@ internal void Validate() _ = new GameLayer(removedSlots[index]); _ = new ProjectLocalId(removedLocalIds[index]); if (!slots.Add(removedSlots[index])) + { throw new InvalidOperationException($"GameLayer slot {removedSlots[index]} is removed more than once."); + } } slots.Clear(); for (int index = 0; index < upsertSlots.Length; index++) @@ -316,7 +335,9 @@ internal void Validate() _ = new ProjectLocalId(upsertLocalIds[index]); _ = GameLayerCatalog.NormalizeName(upsertNames[index]); if (!slots.Add(upsertSlots[index])) + { throw new InvalidOperationException($"GameLayer slot {upsertSlots[index]} is upserted more than once."); + } } var pairs = new HashSet<(int first, int second)>(); for (int index = 0; index < interactionFirstSlots.Length; index++) @@ -326,11 +347,14 @@ internal void Validate() _ = new GameLayer(first); _ = new GameLayer(second); if (first > second) + { throw new InvalidOperationException("GameLayer interaction pairs must use canonical slot order."); + } if (!pairs.Add((first, second))) { throw new InvalidOperationException( - $"GameLayer interaction ({first}, {second}) is contributed more than once."); + $"GameLayer interaction ({first}, {second}) is contributed more than once." + ); } } } diff --git a/src/content/scene/Inno.Scene/Lifecycle/GameBehaviorLifecycleRunner.cs b/src/content/scene/Inno.Scene/Lifecycle/GameBehaviorLifecycleRunner.cs index 9e6358f6e..80a01ded7 100644 --- a/src/content/scene/Inno.Scene/Lifecycle/GameBehaviorLifecycleRunner.cs +++ b/src/content/scene/Inno.Scene/Lifecycle/GameBehaviorLifecycleRunner.cs @@ -33,10 +33,14 @@ internal void FixedUpdate() for (int i = 0; i < behaviors.Count; i++) { if (!m_scene.canDispatch) + { break; + } GameBehavior behavior = behaviors[i]; if (behavior.isActiveAndEnabled) + { behavior.DispatchFixedUpdate(); + } } } @@ -49,10 +53,14 @@ internal void Update() for (int i = 0; i < behaviors.Count; i++) { if (!m_scene.canDispatch) + { break; + } GameBehavior behavior = behaviors[i]; if (!behavior.isActiveAndEnabled || !behavior.lifecycleStartCalled) + { continue; + } behavior.DispatchUpdate(); } } @@ -65,10 +73,14 @@ internal void LateUpdate() for (int i = 0; i < behaviors.Count; i++) { if (!m_scene.canDispatch) + { break; + } GameBehavior behavior = behaviors[i]; if (behavior.isActiveAndEnabled && behavior.lifecycleStartCalled) + { behavior.DispatchLateUpdate(); + } } } @@ -77,7 +89,9 @@ internal void Refresh(GameBehavior behavior) EnsureIndexes(); GameBehaviorLifecyclePhase phases = GetPhases(behavior); if ((phases & GameBehaviorLifecyclePhase.Activation) != 0) + { SynchronizeActivation(behavior); + } UpdateStartEligibility(behavior, phases); } @@ -85,7 +99,9 @@ internal void RefreshAll() { EnsureIndexes(); for (int index = 0; index < m_activationBehaviors.Length; index++) + { SynchronizeActivation(m_activationBehaviors[index]); + } for (int index = 0; index < m_variableFrameBehaviors.Length; index++) { GameBehavior behavior = m_variableFrameBehaviors[index]; @@ -97,7 +113,9 @@ internal void Destroy(GameBehavior behavior) { GameBehaviorLifecyclePhase phases = GetPhases(behavior); if ((phases & GameBehaviorLifecyclePhase.Activation) != 0) + { SceneLifecycle.Destroy(behavior); + } } internal void Invalidate() @@ -118,7 +136,9 @@ internal void Invalidate() private void PreparePendingActivation() { if (m_pendingActivation.Count == 0) + { return; + } GameBehavior[] pending = [.. m_pendingActivation]; m_pendingActivation.Clear(); @@ -128,23 +148,31 @@ private void PreparePendingActivation() if (!m_scene.canDispatch) { for (; index < pending.Length; index++) + { QueueActivation(pending[index]); + } break; } GameBehavior behavior = pending[index]; if (!NeedsActivationPreparation(behavior)) + { continue; + } _ = SceneLifecycle.Prepare(behavior, m_scene); if (NeedsActivationPreparation(behavior)) + { QueueActivation(behavior); + } } } private void DispatchPendingStart() { if (m_pendingStart.Count == 0) + { return; + } GameBehavior[] pending = [.. m_pendingStart]; m_pendingStart.Clear(); @@ -154,13 +182,17 @@ private void DispatchPendingStart() if (!m_scene.canDispatch) { for (; index < pending.Length; index++) + { UpdateStartEligibility(pending[index], GetPhases(pending[index])); + } break; } GameBehavior behavior = pending[index]; if (behavior.isDestroyed || behavior.lifecycleStartCalled || !behavior.isActiveAndEnabled) + { continue; + } behavior.lifecycleStartCalled = true; behavior.DispatchStart(); } @@ -171,7 +203,9 @@ private void EnsureIndexes() long sceneRevision = m_scene.structureRevision; long typeGeneration = m_scene.typeCatalog.generation; if (m_indexedSceneRevision == sceneRevision && m_indexedTypeGeneration == typeGeneration) + { return; + } IReadOnlyList behaviors = m_scene.GetComponents(); var activation = new List(); @@ -184,17 +218,29 @@ private void EnsureIndexes() GameBehavior behavior = behaviors[index]; GameBehaviorLifecyclePhase phases = GetPhases(behavior); if (phases == GameBehaviorLifecyclePhase.None) + { continue; + } if ((phases & GameBehaviorLifecyclePhase.Activation) != 0) + { activation.Add(behavior); + } if ((phases & GameBehaviorLifecyclePhase.VariableFrame) != 0) + { variableFrame.Add(behavior); + } if ((phases & GameBehaviorLifecyclePhase.Update) != 0) + { update.Add(behavior); + } if ((phases & GameBehaviorLifecyclePhase.FixedUpdate) != 0) + { fixedUpdate.Add(behavior); + } if ((phases & GameBehaviorLifecyclePhase.LateUpdate) != 0) + { lateUpdate.Add(behavior); + } } m_pendingActivation.Clear(); @@ -210,7 +256,9 @@ private void EnsureIndexes() { GameBehavior behavior = m_activationBehaviors[index]; if (NeedsActivationPreparation(behavior)) + { QueueActivation(behavior); + } } for (int index = 0; index < m_variableFrameBehaviors.Length; index++) { @@ -231,38 +279,48 @@ private void SynchronizeActivation(GameBehavior behavior) _ = SceneLifecycle.Prepare(behavior, m_scene); if (NeedsActivationPreparation(behavior)) + { QueueActivation(behavior); + } else + { m_pendingActivationSet.Remove(behavior); + } } private void UpdateStartEligibility( GameBehavior behavior, GameBehaviorLifecyclePhase phases ) { - if ((phases & GameBehaviorLifecyclePhase.VariableFrame) == 0 || - behavior.isDestroyed || - behavior.lifecycleStartCalled || - !behavior.isActiveAndEnabled) - { + if ((phases & GameBehaviorLifecyclePhase.VariableFrame) == 0 + || behavior.isDestroyed + || behavior.lifecycleStartCalled + || !behavior.isActiveAndEnabled + ) { m_pendingStartSet.Remove(behavior); return; } if (m_pendingStartSet.Add(behavior)) + { m_pendingStart.Add(behavior); + } } private void QueueActivation(GameBehavior behavior) { if (!behavior.isDestroyed && m_pendingActivationSet.Add(behavior)) + { m_pendingActivation.Add(behavior); + } } private static bool NeedsActivationPreparation(GameBehavior behavior) { if (behavior.isDestroyed || behavior.lifecycleDestroyCalled) + { return false; + } bool active = behavior.isActiveAndEnabled; return (active && !behavior.lifecycleAwakeCalled) || active != behavior.lifecycleWasEnabled; } diff --git a/src/content/scene/Inno.Scene/Lifecycle/ISceneLifecycleObject.cs b/src/content/scene/Inno.Scene/Lifecycle/ISceneLifecycleObject.cs index 9ad20455d..13e827f5d 100644 --- a/src/content/scene/Inno.Scene/Lifecycle/ISceneLifecycleObject.cs +++ b/src/content/scene/Inno.Scene/Lifecycle/ISceneLifecycleObject.cs @@ -21,10 +21,12 @@ internal interface ISceneLifecycleObject /// Gets or sets whether the one-time Awake callback has already been dispatched. /// bool lifecycleAwakeCalled { get; set; } + /// /// Gets or sets whether the one-time Start callback has already been dispatched. /// bool lifecycleStartCalled { get; set; } + /// /// Gets or sets whether the terminal destruction callback has already been dispatched. /// diff --git a/src/content/scene/Inno.Scene/Lifecycle/SceneLifecycle.cs b/src/content/scene/Inno.Scene/Lifecycle/SceneLifecycle.cs index 981ea1a20..441aa695a 100644 --- a/src/content/scene/Inno.Scene/Lifecycle/SceneLifecycle.cs +++ b/src/content/scene/Inno.Scene/Lifecycle/SceneLifecycle.cs @@ -7,7 +7,9 @@ internal static bool Prepare( GameScene scene ) { if (target.lifecycleIsDestroyed || target.lifecycleDestroyCalled) + { return false; + } bool active = target.lifecycleIsActive; if (active && !target.lifecycleAwakeCalled) @@ -15,7 +17,9 @@ GameScene scene target.lifecycleAwakeCalled = true; target.DispatchAwake(); if (!scene.canDispatch || target.lifecycleIsDestroyed) + { return false; + } } return PrepareActivation(target, scene); @@ -31,14 +35,18 @@ GameScene scene target.lifecycleWasEnabled = true; target.DispatchEnable(); if (!scene.canDispatch || target.lifecycleIsDestroyed) + { return false; + } } else if (!active && target.lifecycleWasEnabled) { target.lifecycleWasEnabled = false; target.DispatchDisable(); if (!scene.canDispatch || target.lifecycleIsDestroyed) + { return false; + } } return true; @@ -49,7 +57,9 @@ GameScene scene private static void Disable(ISceneLifecycleObject target) { if (!target.lifecycleWasEnabled) + { return; + } target.lifecycleWasEnabled = false; target.DispatchDisable(); } @@ -57,7 +67,9 @@ private static void Disable(ISceneLifecycleObject target) internal static void Destroy(ISceneLifecycleObject target) { if (target.lifecycleDestroyCalled) + { return; + } target.lifecycleDestroyCalled = true; if (target.lifecycleWasEnabled) { @@ -65,7 +77,8 @@ internal static void Destroy(ISceneLifecycleObject target) target.DispatchDisable(); } if (target.lifecycleAwakeCalled) + { target.DispatchDestroy(); + } } - } diff --git a/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs b/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs index 3db87882b..715ced862 100644 --- a/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs +++ b/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Collections; +using Inno.Extensibility.Types; namespace Inno.Scene; @@ -33,14 +32,13 @@ SceneTypeCatalog types m_types = types; m_behaviors = new GameBehaviorLifecycleRunner(scene); m_systemKey = m_systems.DefineKey("scene.system", IndexedObjectKeyFlags.Unique); - m_persistentIdKey = m_systems.DefineKey( - "scene.system.persistent-id", - IndexedObjectKeyFlags.Unique); + m_persistentIdKey = m_systems.DefineKey("scene.system.persistent-id", IndexedObjectKeyFlags.Unique); m_typeKey = m_systems.DefineKey("scene.system.type"); } - internal TSystem Add() where TSystem : GameSystem, new() - => (TSystem)Add(typeof(TSystem), persistentId: null, invokeReset: true); + internal TSystem Add() + where TSystem : GameSystem, new() + => (TSystem)Add(typeof(TSystem), persistentId: null, invokeReset: true); internal GameSystem Add( Type systemType, @@ -48,12 +46,13 @@ internal GameSystem Add( bool invokeReset ) { ArgumentNullException.ThrowIfNull(systemType); - if (!m_types.TryGetSystem(systemType, out SceneSystemTypeDescriptor? descriptor) || - !descriptor!.isConcrete) - { + if (!m_types.TryGetSystem(systemType, out SceneSystemTypeDescriptor? descriptor) + || !descriptor!.isConcrete + ) { throw new ArgumentException( $"Type '{systemType.FullName}' is not an active concrete GameSystem.", - nameof(systemType)); + nameof(systemType) + ); } var system = (GameSystem)m_types.snapshot.CreateInstance(systemType); @@ -68,16 +67,8 @@ internal MissingGameSystem AddMissing( Guid? persistentId, IReadOnlyList? dependencies = null ) { - var system = new MissingGameSystem( - missingType, - missingTypeName, - serializedState, - dependencies); - Add( - system, - m_types.GetSystem(typeof(MissingGameSystem)), - persistentId, - invokeReset: false); + var system = new MissingGameSystem(missingType, missingTypeName, serializedState, dependencies); + Add(system, m_types.GetSystem(typeof(MissingGameSystem)), persistentId, invokeReset: false); return system; } @@ -94,7 +85,9 @@ internal void Add( internal bool Remove(GameSystem system) { if (!TryGetEntry(system, out SystemEntry? entry)) + { return false; + } m_systems.Remove(entry!); m_displayOrder.Remove(entry!); RefreshDisplayIndices(); @@ -106,7 +99,9 @@ internal bool Remove(GameSystem system) finally { if (!system.isDestroyed) + { system.Detach(); + } } return true; } @@ -114,25 +109,33 @@ internal bool Remove(GameSystem system) internal void Reset(GameSystem system) { if (!TryGetEntry(system, out _)) + { throw new InvalidOperationException($"GameSystem '{system.GetType().FullName}' is not registered."); + } system.DispatchReset(); } internal IReadOnlyList GetSystems() { if (m_displayView is not null) + { return m_displayView; + } var snapshot = new GameSystem[m_displayOrder.Count]; for (int i = 0; i < snapshot.Length; i++) + { snapshot[i] = m_displayOrder[i].system; + } return m_displayView = Array.AsReadOnly(snapshot); } internal int GetIndex(GameSystem system) { if (!TryGetEntry(system, out SystemEntry? entry)) + { throw new InvalidOperationException("The GameSystem is not registered with this scene."); + } return entry!.displayIndex; } @@ -141,11 +144,15 @@ internal void SetIndex( int systemIndex ) { if (!TryGetEntry(system, out SystemEntry? entry)) + { throw new InvalidOperationException("The GameSystem is not registered with this scene."); + } int currentIndex = entry!.displayIndex; int targetIndex = Math.Clamp(systemIndex, 0, m_displayOrder.Count - 1); if (currentIndex == targetIndex) + { return; + } m_displayOrder.RemoveAt(currentIndex); m_displayOrder.Insert(targetIndex, entry); RefreshDisplayIndices(); @@ -158,18 +165,28 @@ internal void ReplaceForReload( int replacementRuntimeTypeId ) { if (!TryGetEntry(previous, out SystemEntry? entry)) + { throw new InvalidOperationException("The GameSystem being replaced is not registered."); + } if (TryGetEntry(replacement, out _)) + { throw new InvalidOperationException("The replacement GameSystem is already registered."); + } previous.ValidateIdentityForReplacement(); if (replacement.identity.runtimeId is not null) + { throw new InvalidOperationException("The replacement GameSystem already has a registered identity."); + } bool attachedHere = replacement.ownerScene is null; if (attachedHere) + { replacement.Attach(m_scene); + } else if (!ReferenceEquals(replacement.ownerScene, m_scene)) + { throw new InvalidOperationException("The replacement GameSystem belongs to another scene."); + } Guid persistentId = previous.identity.persistentId; try { @@ -222,10 +239,13 @@ int replacementRuntimeTypeId } } if (rollbackFailures is null) + { throw; + } throw new InvalidOperationException( "GameSystem hot-reload replacement failed and its identity rollback was incomplete.", - new AggregateException([exception, .. rollbackFailures])); + new AggregateException([exception, .. rollbackFailures]) + ); } } @@ -234,7 +254,9 @@ int replacementRuntimeTypeId internal void NotifyGameSystemActivationChanged(GameSystem system) { if (TryGetEntry(system, out _)) + { _ = SceneLifecycle.Prepare(system, m_scene); + } } internal void NotifyHierarchyActivationChanged() => m_behaviors.RefreshAll(); @@ -252,9 +274,13 @@ internal void FixedUpdate() { GameSystem system = systems[i].system; if (!m_scene.canDispatch) + { break; + } if (SceneLifecycle.Prepare(system, m_scene) && system.isActiveAndEnabled) + { system.DispatchFixedUpdate(); + } } } @@ -267,15 +293,21 @@ internal void Update() { GameSystem system = systems[i].system; if (!m_scene.canDispatch) + { break; + } if (!SceneLifecycle.Prepare(system, m_scene) || !system.isActiveAndEnabled) + { continue; + } if (!system.lifecycleStartCalled) { system.lifecycleStartCalled = true; ((ISceneLifecycleObject)system).DispatchStart(); if (!m_scene.canDispatch || system.isDestroyed) + { break; + } } system.DispatchUpdate(); } @@ -290,11 +322,13 @@ internal void LateUpdate() { GameSystem system = systems[i].system; if (!m_scene.canDispatch) - break; - if (SceneLifecycle.Prepare(system, m_scene) && - system.isActiveAndEnabled && - system.lifecycleStartCalled) { + break; + } + if (SceneLifecycle.Prepare(system, m_scene) + && system.isActiveAndEnabled + && system.lifecycleStartCalled + ) { system.DispatchLateUpdate(); } } @@ -316,7 +350,9 @@ internal void Clear() finally { if (!system.isDestroyed) + { system.Detach(); + } } } } @@ -330,12 +366,14 @@ bool invokeReset if (TryGetEntry(system, out _)) { throw new InvalidOperationException( - $"System '{descriptor.displayName}' is already registered with scene '{m_scene.name}'."); + $"System '{descriptor.displayName}' is already registered with scene '{m_scene.name}'." + ); } if (!descriptor.allowsMultiple && m_systems.First(m_typeKey, descriptor.runtimeTypeId) is not null) { throw new InvalidOperationException( - $"Scene '{m_scene.name}' already contains GameSystem '{descriptor.displayName}'."); + $"Scene '{m_scene.name}' already contains GameSystem '{descriptor.displayName}'." + ); } system.Attach(m_scene); @@ -351,7 +389,9 @@ bool invokeReset m_displayOrder.Add(entry); InvalidateSnapshots(); if (invokeReset) + { system.DispatchReset(); + } } catch { @@ -363,7 +403,9 @@ bool invokeReset InvalidateSnapshots(); } if (!system.isDestroyed) + { system.Detach(); + } throw; } } @@ -379,7 +421,9 @@ out SystemEntry? entry private SystemEntry[] GetExecutionSnapshot() { if (m_executionSnapshot is null) + { m_executionSnapshot = [.. m_displayOrder]; + } bool needsSort = false; for (int i = 0; i < m_executionSnapshot.Length; i++) @@ -387,12 +431,16 @@ private SystemEntry[] GetExecutionSnapshot() SystemEntry entry = m_executionSnapshot[i]; int executionOrder = entry.system.order; if (entry.executionOrder == executionOrder) + { continue; + } entry.executionOrder = executionOrder; needsSort = true; } if (needsSort || !IsExecutionOrderValid(m_executionSnapshot)) + { Array.Sort(m_executionSnapshot, SystemEntryExecutionComparer.instance); + } return m_executionSnapshot; } @@ -401,7 +449,9 @@ private static bool IsExecutionOrderValid(SystemEntry[] entries) for (int i = 1; i < entries.Length; i++) { if (SystemEntryExecutionComparer.instance.Compare(entries[i - 1], entries[i]) > 0) + { return false; + } } return true; } @@ -409,7 +459,9 @@ private static bool IsExecutionOrderValid(SystemEntry[] entries) private void RefreshDisplayIndices() { for (int i = 0; i < m_displayOrder.Count; i++) + { m_displayOrder[i].displayIndex = i; + } } private void InvalidateSnapshots() @@ -450,15 +502,21 @@ public int Compare( SystemEntry? right ) { if (ReferenceEquals(left, right)) + { return 0; + } if (left is null) + { return -1; + } if (right is null) + { return 1; + } int orderComparison = left.executionOrder.CompareTo(right.executionOrder); return orderComparison != 0 - ? orderComparison - : left.displayIndex.CompareTo(right.displayIndex); + ? orderComparison + : left.displayIndex.CompareTo(right.displayIndex); } } } diff --git a/src/content/scene/Inno.Scene/Prefabs/PrefabConnectionRecord.cs b/src/content/scene/Inno.Scene/Prefabs/PrefabConnectionRecord.cs index 37dacf8a5..3fb45fd54 100644 --- a/src/content/scene/Inno.Scene/Prefabs/PrefabConnectionRecord.cs +++ b/src/content/scene/Inno.Scene/Prefabs/PrefabConnectionRecord.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets; namespace Inno.Scene; @@ -46,5 +45,6 @@ GameComponent component } internal void RemoveObject(Guid sourceId) => m_objectIdentities.Remove(sourceId); + internal void RemoveComponent(Guid sourceId) => m_componentIdentities.Remove(sourceId); } diff --git a/src/content/scene/Inno.Scene/Prefabs/PrefabInstanceInfo.cs b/src/content/scene/Inno.Scene/Prefabs/PrefabInstanceInfo.cs index 9b8f97b2f..796adc590 100644 --- a/src/content/scene/Inno.Scene/Prefabs/PrefabInstanceInfo.cs +++ b/src/content/scene/Inno.Scene/Prefabs/PrefabInstanceInfo.cs @@ -1,5 +1,4 @@ using System; - using Inno.Assets; namespace Inno.Scene; diff --git a/src/content/scene/Inno.Scene/Prefabs/PrefabOverrideSet.cs b/src/content/scene/Inno.Scene/Prefabs/PrefabOverrideSet.cs index 03b3755a4..825a6a3ad 100644 --- a/src/content/scene/Inno.Scene/Prefabs/PrefabOverrideSet.cs +++ b/src/content/scene/Inno.Scene/Prefabs/PrefabOverrideSet.cs @@ -8,6 +8,7 @@ internal sealed class PrefabOverrideSet { private readonly Dictionary<(Guid sourceComponentId, string propertyName), PrefabPropertyOverride> m_properties = []; + private readonly Dictionary m_structures = []; private readonly HashSet m_removedObjects = []; private readonly HashSet m_removedComponents = []; @@ -20,24 +21,25 @@ internal sealed class PrefabOverrideSet internal IReadOnlyCollection removedComponents => m_removedComponents; internal IReadOnlyCollection addedObjects => m_addedObjects; internal IReadOnlyCollection addedComponents => m_addedComponents; - internal int count => - m_properties.Count + m_structures.Count + - m_removedObjects.Count + m_removedComponents.Count + - m_addedObjects.Count + m_addedComponents.Count; - internal int orphanedCount => - m_properties.Values.Count(static item => item.isOrphaned) + - m_structures.Values.Count(static item => item.isOrphaned); + + internal int count + => m_properties.Count + m_structures.Count + + m_removedObjects.Count + m_removedComponents.Count + + m_addedObjects.Count + m_addedComponents.Count; + + internal int orphanedCount + => m_properties.Values.Count(static item => item.isOrphaned) + + m_structures.Values.Count(static item => item.isOrphaned); internal bool IsPropertyOverridden( Guid sourceComponentId, string propertyName - ) - => m_properties.ContainsKey((sourceComponentId, propertyName)); + ) => m_properties.ContainsKey((sourceComponentId, propertyName)); internal PrefabObjectOverrideKind GetStructureOverride(Guid sourceObjectId) => m_structures.TryGetValue(sourceObjectId, out PrefabStructureOverride? value) - ? value.kind - : PrefabObjectOverrideKind.None; + ? value.kind + : PrefabObjectOverrideKind.None; internal void SetProperty(PrefabPropertyOverride value) { @@ -59,10 +61,14 @@ internal void SetStructure( } internal void MarkObjectRemoved(Guid sourceObjectId) => m_removedObjects.Add(sourceObjectId); + internal void MarkComponentRemoved(Guid sourceComponentId) => m_removedComponents.Add(sourceComponentId); + internal void MarkObjectAdded(Guid instanceObjectId) => m_addedObjects.Add(instanceObjectId); + internal void MarkComponentAdded(Guid instanceComponentId) => m_addedComponents.Add(instanceComponentId); internal bool IsObjectRemoved(Guid sourceObjectId) => m_removedObjects.Contains(sourceObjectId); + internal bool IsComponentRemoved(Guid sourceComponentId) => m_removedComponents.Contains(sourceComponentId); } diff --git a/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs b/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs index 931804777..eddbe7b21 100644 --- a/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs +++ b/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs @@ -10,7 +10,7 @@ internal enum PrefabObjectOverrideKind ActiveSelf = 1 << 1, Parent = 1 << 2, SiblingIndex = 1 << 3, - Tag = 1 << 4, + Tag = 1 << 4 } internal sealed record PrefabStructureOverride( diff --git a/src/content/scene/Inno.Scene/Properties/ScriptingApi.cs b/src/content/scene/Inno.Scene/Properties/ScriptingApi.cs index dff7af06d..fa7281b5c 100644 --- a/src/content/scene/Inno.Scene/Properties/ScriptingApi.cs +++ b/src/content/scene/Inno.Scene/Properties/ScriptingApi.cs @@ -1,20 +1,11 @@ -using Inno.Scripting.Api; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Scene", - "Inno.Scene", - ScriptingApiScope.Runtime)] -[assembly: ScriptingApiNamespace( - "InnoEngine.Scene", - "Inno.Scene.Components", - ScriptingApiScope.Runtime)] -[assembly: ScriptingApiNamespace( - "InnoEngine.Scene", - "Inno.Scene.Layers", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Scene", "Inno.Scene", ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Scene", "Inno.Scene.Components", ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Scene", "Inno.Scene.Layers", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AllowMultipleComponentAttribute), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AllowMultipleSystemAttribute), ScriptingApiScope.Runtime)] diff --git a/src/content/scene/Inno.Scene/Reloading/SceneElementReferenceResolver.cs b/src/content/scene/Inno.Scene/Reloading/SceneElementReferenceResolver.cs index ede0b9487..d24d7e851 100644 --- a/src/content/scene/Inno.Scene/Reloading/SceneElementReferenceResolver.cs +++ b/src/content/scene/Inno.Scene/Reloading/SceneElementReferenceResolver.cs @@ -17,12 +17,22 @@ ReferenceResolution IReferenceResolver.Resolve(ReferenceDescriptor descriptor) { EngineObject? target = world.Find(descriptor.targetPersistentId); if (target is null || target.isDestroyed || target is MissingGameComponent or MissingGameSystem) - return new ReferenceResolution(descriptor, ReferenceResolutionState.Missing, - diagnostic: $"Scene element '{descriptor.targetPersistentId:D}' or its type is unavailable."); - if (descriptor.expectedStableTypeId != Guid.Empty && - types.GetTypeRef(target.GetType()).stableId != descriptor.expectedStableTypeId) - return new ReferenceResolution(descriptor, ReferenceResolutionState.TypeMismatch, - diagnostic: $"Scene element '{descriptor.targetPersistentId:D}' does not implement stable type '{descriptor.expectedStableTypeId:D}'."); + { + return new ReferenceResolution( + descriptor, + ReferenceResolutionState.Missing, + diagnostic: $"Scene element '{descriptor.targetPersistentId:D}' or its type is unavailable." + ); + } + if (descriptor.expectedStableTypeId != Guid.Empty + && types.GetTypeRef(target.GetType()).stableId != descriptor.expectedStableTypeId + ) { + return new ReferenceResolution( + descriptor, + ReferenceResolutionState.TypeMismatch, + diagnostic: $"Scene element '{descriptor.targetPersistentId:D}' does not implement stable type '{descriptor.expectedStableTypeId:D}'." + ); + } return new ReferenceResolution(descriptor, ReferenceResolutionState.Resolved, target.identity.runtimeIdentity); } } diff --git a/src/content/scene/Inno.Scene/Reloading/SceneReloadDiagnostic.cs b/src/content/scene/Inno.Scene/Reloading/SceneReloadDiagnostic.cs index 8f8857662..fc70e7c06 100644 --- a/src/content/scene/Inno.Scene/Reloading/SceneReloadDiagnostic.cs +++ b/src/content/scene/Inno.Scene/Reloading/SceneReloadDiagnostic.cs @@ -1,5 +1,5 @@ -using Inno.Core.Diagnostics; using System; +using Inno.Core.Diagnostics; namespace Inno.Scene; diff --git a/src/content/scene/Inno.Scene/Reloading/SceneReloadRecovery.cs b/src/content/scene/Inno.Scene/Reloading/SceneReloadRecovery.cs index 62da62f2a..539a75c7a 100644 --- a/src/content/scene/Inno.Scene/Reloading/SceneReloadRecovery.cs +++ b/src/content/scene/Inno.Scene/Reloading/SceneReloadRecovery.cs @@ -22,22 +22,31 @@ IAssetReferenceResolver assets ) { m_transfer = transfer; m_recovery = new ReferenceRecoveryTransaction( - ReferenceCatalog.Create(context.candidate.version, - [new SceneElementReferenceResolver(world, context.candidate), assets]), - transfer.CaptureRecoveryStates(), [transfer]); + ReferenceCatalog.Create( + context.candidate.version, + [new SceneElementReferenceResolver(world, context.candidate), assets] + ), + transfer.CaptureRecoveryStates(), + [transfer] + ); } IReadOnlyList ISceneReloadStateTransfer.retiredObjects => m_transfer?.retiredObjects ?? Array.Empty(); IReadOnlyList ISceneReloadStateTransfer.diagnostics => m_diagnostics; IReadOnlyList ISceneReloadStateTransfer.recoveryChanges => m_recovery.changes; + void ISceneReloadStateTransfer.PrepareForActivation() => m_recovery.PrepareForActivation(); + void ISceneReloadStateTransfer.Apply() { m_recovery.Apply(); CaptureDiagnostics(); } + void ISceneReloadStateTransfer.RollbackStructure() => m_recovery.RollbackStructure(); + void ISceneReloadStateTransfer.RestorePreviousState() => FinalizeRecovery(restore: true); + void ISceneReloadStateTransfer.Complete() => FinalizeRecovery(restore: false); private void FinalizeRecovery(bool restore) @@ -46,9 +55,13 @@ private void FinalizeRecovery(bool restore) try { if (restore) + { m_recovery.RestorePreviousState(); + } else + { m_recovery.Complete(); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -59,13 +72,17 @@ private void FinalizeRecovery(bool restore) { CaptureDiagnostics(); if (!pending) + { m_transfer = null; + } } } private void CaptureDiagnostics() { if (m_transfer is not null) + { m_diagnostics = Array.AsReadOnly(m_transfer.diagnostics.ToArray()); + } } } diff --git a/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs b/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs index 5da57bb9e..62927b0d3 100644 --- a/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs +++ b/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs @@ -1,8 +1,7 @@ using System; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Scene; @@ -55,6 +54,9 @@ public ISceneReloadStateTransfer Capture(TypeCacheReloadContext context) ArgumentNullException.ThrowIfNull(context); return new SceneReloadRecovery( SceneReloadStateTransfer.Capture(m_world, context, m_serialization, m_assets), - m_world, context, m_assets); + m_world, + context, + m_assets + ); } } diff --git a/src/content/scene/Inno.Scene/SceneManager.cs b/src/content/scene/Inno.Scene/SceneManager.cs index 577845bf8..57a4473e2 100644 --- a/src/content/scene/Inno.Scene/SceneManager.cs +++ b/src/content/scene/Inno.Scene/SceneManager.cs @@ -72,8 +72,7 @@ int sceneIndex public static void LoadSceneAdditive( GameScene scene, bool makeActive = true - ) - => SceneWorld.current.LoadSceneAdditive(scene, makeActive); + ) => SceneWorld.current.LoadSceneAdditive(scene, makeActive); /// /// Creates and loads a new active scene in the current runtime session. @@ -101,8 +100,7 @@ public static void LoadSceneAdditive( public static GameScene LoadNewSceneAdditive( string name = "Untitled Scene", bool makeActive = true - ) - => SceneWorld.current.LoadNewSceneAdditive(name, makeActive); + ) => SceneWorld.current.LoadNewSceneAdditive(name, makeActive); /// /// Makes a loaded scene active in the current runtime session. @@ -124,8 +122,7 @@ public static GameScene LoadNewSceneAdditive( public static void MoveGameObjectToScene( GameObject gameObject, GameScene destination - ) - => SceneWorld.current.MoveGameObjectToScene(gameObject, destination); + ) => SceneWorld.current.MoveGameObjectToScene(gameObject, destination); /// /// Unloads the active scene in the current runtime session when one exists. diff --git a/src/content/scene/Inno.Scene/SceneWorld.cs b/src/content/scene/Inno.Scene/SceneWorld.cs index 8a4d98f1e..ca351e0a0 100644 --- a/src/content/scene/Inno.Scene/SceneWorld.cs +++ b/src/content/scene/Inno.Scene/SceneWorld.cs @@ -1,10 +1,10 @@ using System; -using Inno.Core.Execution; using System.Collections.Generic; using System.Threading; +using Inno.Assets; +using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Serialization; -using Inno.Assets; using Inno.Extensibility.Types; using Inno.Scene.Components; @@ -78,7 +78,9 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (m_prefabSerialization is not null) + { throw new InvalidOperationException("Prefab instantiation is already configured for this scene world."); + } m_prefabSerialization = serialization; m_prefabAssets = assets; } @@ -92,11 +94,13 @@ internal GameObject InstantiatePrefab( ArgumentNullException.ThrowIfNull(prefab); ArgumentNullException.ThrowIfNull(scene); if (!m_loadedScenes.Contains(scene)) + { throw new InvalidOperationException("A prefab can only be instantiated into a loaded scene in the current world."); + } SerializationRegistry serialization = m_prefabSerialization ?? throw new InvalidOperationException("The current scene world has no prefab serialization context."); IAssetReferenceResolver assets = m_prefabAssets - ?? throw new InvalidOperationException("The current scene world has no prefab asset resolver."); + ?? throw new InvalidOperationException("The current scene world has no prefab asset resolver."); using IDisposable scope = EnterScope(); return prefab.Instantiate(scene, serialization, assets, parent); } @@ -130,7 +134,7 @@ internal GameObject InstantiatePrefab( /// public TObject? Find(Guid persistentId) where TObject : IdentityObject - => m_identities.Get(persistentId); + => m_identities.Get(persistentId); /// /// Binds this world and its identity allocator to the current asynchronous execution context. @@ -166,8 +170,8 @@ public int GetSceneIndex(GameScene scene) ArgumentNullException.ThrowIfNull(scene); int index = m_loadedScenes.IndexOf(scene); return index >= 0 - ? index - : throw new InvalidOperationException("Only a loaded scene has a hierarchy index."); + ? index + : throw new InvalidOperationException("Only a loaded scene has a hierarchy index."); } /// @@ -190,10 +194,14 @@ int sceneIndex ArgumentNullException.ThrowIfNull(scene); int currentIndex = m_loadedScenes.IndexOf(scene); if (currentIndex < 0) + { throw new InvalidOperationException("Only a loaded scene can be reordered."); + } int targetIndex = Math.Clamp(sceneIndex, 0, m_loadedScenes.Count - 1); if (currentIndex == targetIndex) + { return; + } m_loadedScenes.RemoveAt(currentIndex); m_loadedScenes.Insert(targetIndex, scene); InvalidateSnapshot(); @@ -210,7 +218,9 @@ public void LoadScene(GameScene scene) EnsureActive(); ArgumentNullException.ThrowIfNull(scene); if (ReferenceEquals(m_activeScene, scene) && m_loadedScenes.Count == 1) + { return; + } UnloadAllScenes(); m_loadedScenes.Add(scene); InvalidateSnapshot(); @@ -240,7 +250,9 @@ public void LoadSceneAdditive( scene.Load(this); } if (makeActive || m_activeScene is null) + { m_activeScene = scene; + } } /// @@ -296,7 +308,9 @@ public void SetActiveScene(GameScene scene) EnsureActive(); ArgumentNullException.ThrowIfNull(scene); if (!m_loadedScenes.Contains(scene)) + { throw new InvalidOperationException("Only a loaded scene can become active."); + } m_activeScene = scene; } @@ -320,12 +334,18 @@ GameScene destination ArgumentNullException.ThrowIfNull(gameObject); ArgumentNullException.ThrowIfNull(destination); if (!gameObject.isRuntimeValid) + { throw new InvalidOperationException("Only a live GameObject can move between scenes."); + } GameScene source = gameObject.scene; if (!m_loadedScenes.Contains(source) || !m_loadedScenes.Contains(destination)) + { throw new InvalidOperationException("Both source and destination scenes must be loaded by this world."); + } if (!ReferenceEquals(source, destination)) + { source.TransferObjectTo(gameObject, destination); + } } /// @@ -335,7 +355,9 @@ public void UnloadActiveScene() { EnsureActive(); if (m_activeScene is GameScene scene) + { UnloadScene(scene); + } } /// @@ -352,7 +374,9 @@ public bool UnloadScene(GameScene scene) EnsureActive(); ArgumentNullException.ThrowIfNull(scene); if (!m_loadedScenes.Remove(scene)) + { return false; + } InvalidateSnapshot(); try { @@ -361,7 +385,9 @@ public bool UnloadScene(GameScene scene) finally { if (ReferenceEquals(m_activeScene, scene)) + { m_activeScene = m_loadedScenes.Count > 0 ? m_loadedScenes[^1] : null; + } } return true; } @@ -388,7 +414,9 @@ public void UnloadAllScenes() InvalidateSnapshot(); m_activeScene = null; if (firstException is not null) + { throw new InvalidOperationException("One or more scenes failed while unloading.", firstException); + } } /// @@ -402,7 +430,9 @@ public void FixedUpdate(float fixedDeltaTime) EnsureActive(); GameScene[] scenes = GetLoadedSceneSnapshot(); for (int index = 0; index < scenes.Length; index++) + { scenes[index].FixedUpdate(fixedDeltaTime); + } } /// @@ -416,7 +446,9 @@ public void Update(float deltaTime) EnsureActive(); GameScene[] scenes = GetLoadedSceneSnapshot(); for (int index = 0; index < scenes.Length; index++) + { scenes[index].Update(deltaTime); + } } /// @@ -430,7 +462,9 @@ public void LateUpdate(float deltaTime) EnsureActive(); GameScene[] scenes = GetLoadedSceneSnapshot(); for (int index = 0; index < scenes.Length; index++) + { scenes[index].LateUpdate(deltaTime); + } } /// @@ -439,7 +473,9 @@ public void LateUpdate(float deltaTime) public void Dispose() { if (m_disposed) + { return; + } using IDisposable scope = EnterScope(); try { @@ -471,7 +507,9 @@ IDisposable identityScope public void Dispose() { if (m_disposed) + { return; + } worldScope.Dispose(); m_disposed = true; identityScope.Dispose(); diff --git a/src/content/scene/Inno.Scene/Serialization/Converters/GameComponentReferenceConverter.cs b/src/content/scene/Inno.Scene/Serialization/Converters/GameComponentReferenceConverter.cs index dfd05f4ae..975be2378 100644 --- a/src/content/scene/Inno.Scene/Serialization/Converters/GameComponentReferenceConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/Converters/GameComponentReferenceConverter.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; using Inno.Scene; @@ -43,9 +42,12 @@ public override GameComponent Read(SerializationReader reader) ArgumentNullException.ThrowIfNull(reader); var token = new EngineReferenceToken( (EngineReferenceKind)reader.Read("kind"), - reader.Read("sourceId")); + reader.Read("sourceId") + ); if (token.kind != EngineReferenceKind.GameComponent) + { throw new InvalidDataException($"Reference token at '{reader.path}' is not a GameComponent reference."); + } return (GameComponent)SceneReferenceScope.current.Resolve(token, reader.valueType, reader.path); } } diff --git a/src/content/scene/Inno.Scene/Serialization/Converters/GameObjectConverter.cs b/src/content/scene/Inno.Scene/Serialization/Converters/GameObjectConverter.cs index 3cf6d2ffd..1db8a6c78 100644 --- a/src/content/scene/Inno.Scene/Serialization/Converters/GameObjectConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/Converters/GameObjectConverter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; @@ -37,7 +36,9 @@ GameObject value } if (!value.isRuntimeValid) + { throw new InvalidOperationException("A destroyed or detached GameObject cannot be captured as a prefab root."); + } var subtree = new List(); CollectSubtree(value, subtree); @@ -55,17 +56,22 @@ GameObject value if (existingConnection is not null) { foreach ((Guid sourceId, Guid runtimeId) in existingConnection.objectIdentities) + { mappedIds[runtimeId] = sourceId; + } foreach ((Guid sourceId, Guid runtimeId) in existingConnection.componentIdentities) + { mappedIds[runtimeId] = sourceId; + } } for (int i = 0; i < engineObjects.Length; i++) { sourceIds.Add( engineObjects[i], mappedIds.TryGetValue(engineObjects[i].identity.persistentId, out Guid mappedId) - ? mappedId - : Guid.NewGuid()); + ? mappedId + : Guid.NewGuid() + ); } var references = new SceneGraphReferenceMap(value.scene, sourceIds, value); @@ -77,7 +83,8 @@ GameObject value entries, sourceIds, included.Contains, - preserveRootSiblingOrder: false); + preserveRootSiblingOrder: false + ); } } @@ -94,14 +101,20 @@ public override GameObject Read(SerializationReader reader) { ArgumentNullException.ThrowIfNull(reader); if (SceneReferenceScope.TryGetCurrent(out SceneReferenceScope? activeReferences)) + { return (GameObject)ReadReference(reader, activeReferences!); + } GameScene scene = reader.context.GetRequired(); Transform? parent = null; if (reader.context.TryGet(out Transform? configuredParent)) + { parent = configuredParent; + } if (parent is not null && !ReferenceEquals(parent.gameObject.scene, scene)) + { throw new InvalidOperationException("The prefab parent must belong to the target scene."); + } ValidatePrefab(reader); var existingObjects = new HashSet(scene.GetOwnedObjects(), ReferenceEqualityComparer.Instance); @@ -114,43 +127,48 @@ public override GameObject Read(SerializationReader reader) preservePersistentIds: false, references, SceneGraphSerialization.ReadMissingReferenceAliases(reader), - reader.context); + reader.context + ); Guid sourceRootId = reader.Read(C_SOURCE_ROOT_ID_KEY); if (!restored.objects.TryGetValue(sourceRootId, out GameObject? root)) + { throw new InvalidDataException($"Prefab root '{sourceRootId}' is missing at '{reader.path}'."); + } if (reader.context.TryGet(out AssetObject? sourceAsset) && sourceAsset is not null) { PrefabConnectionRecord? embeddedConnection = root.prefabConnection; - bool sourceRepresentsVariant = embeddedConnection is not null && - root.prefabInstance?.isRoot == true; + bool sourceRepresentsVariant = embeddedConnection is not null + && root.prefabInstance?.isRoot == true; if (sourceRepresentsVariant) { - PrefabOverrideProcessor.Reconcile( - embeddedConnection!, - root, - reader.context); + PrefabOverrideProcessor.Reconcile(embeddedConnection!, root, reader.context); } - var connection = new PrefabConnectionRecord( - sourceAsset, - sourceRootId, - sourceRepresentsVariant); + var connection = new PrefabConnectionRecord(sourceAsset, sourceRootId, sourceRepresentsVariant); foreach ((Guid sourceObjectId, GameObject gameObject) in restored.objects) + { connection.MapObject(sourceObjectId, gameObject); + } foreach ((Guid sourceComponentId, GameComponent component) in restored.components) + { connection.MapComponent(sourceComponentId, component); + } if (sourceRepresentsVariant) { foreach ((Guid sourceObjectId, Guid runtimeId) in embeddedConnection!.objectIdentities) { GameObject? mappedObject = scene.FindObject(runtimeId); if (mappedObject is not null) + { connection.MapObject(sourceObjectId, mappedObject); + } } foreach ((Guid sourceComponentId, Guid runtimeId) in embeddedConnection.componentIdentities) { GameComponent? mappedComponent = scene.FindComponent(runtimeId); if (mappedComponent is not null) + { connection.MapComponent(sourceComponentId, mappedComponent); + } } } root.SetPrefabConnectionDirect(connection); @@ -159,28 +177,35 @@ public override GameObject Read(SerializationReader reader) { GameObject? gameObject = scene.FindObject(runtimeId); if (gameObject is null) + { continue; + } PrefabInstanceInfo? existingConnection = gameObject.prefabInstance; - if (existingConnection is not null && - !ReferenceEquals(existingConnection.instanceRoot, root)) - { + if (existingConnection is not null + && !ReferenceEquals(existingConnection.instanceRoot, root) + ) { continue; } - gameObject.SetPrefabInstanceDirect(new PrefabInstanceInfo( - sourceAsset.identity.persistentId, - sourceObjectId, - root, - ReferenceEquals(gameObject, root), - sourceRepresentsVariant, - sourceAsset.isMissing, - existingConnection?.overrideCount ?? 0, - existingConnection?.orphanedOverrideCount ?? 0, - sourceAsset)); + gameObject.SetPrefabInstanceDirect( + new PrefabInstanceInfo( + sourceAsset.identity.persistentId, + sourceObjectId, + root, + ReferenceEquals(gameObject, root), + sourceRepresentsVariant, + sourceAsset.isMissing, + existingConnection?.overrideCount ?? 0, + existingConnection?.orphanedOverrideCount ?? 0, + sourceAsset + ) + ); } } SceneGraphSerialization.ReconcilePrefabConnections(scene, reader.context, root); if (parent is not null) + { scene.SetParent(root.transform, parent, worldPositionStays: false); + } return root; } catch @@ -191,7 +216,9 @@ public override GameObject Read(SerializationReader reader) for (int i = 0; i < createdObjects.Length; i++) { if (createdObjects[i].isRuntimeValid) + { scene.DestroyObject(createdObjects[i]); + } } throw; } @@ -213,9 +240,12 @@ SceneReferenceScope references ) { var token = new EngineReferenceToken( (EngineReferenceKind)reader.Read("kind"), - reader.Read("sourceId")); + reader.Read("sourceId") + ); if (token.kind != EngineReferenceKind.GameObject) + { throw new InvalidDataException($"Reference token at '{reader.path}' is not a GameObject reference."); + } return references.Resolve(token, reader.valueType, reader.path); } @@ -224,13 +254,16 @@ private static void ValidatePrefab(SerializationReader reader) SceneGraphSerialization.ValidateMissingReferenceAliases(reader); Guid rootId = reader.Read(C_SOURCE_ROOT_ID_KEY); if (rootId == Guid.Empty) + { throw new InvalidDataException($"Prefab source root identity at '{reader.path}' cannot be empty."); + } IReadOnlyList objectReaders = reader.ReadObjectArray(SceneGraphSerialization.C_OBJECTS_KEY); SceneGraphSerialization.ValidateObjects(objectReaders); - if (!objectReaders.Any(objectReader => - objectReader.Read(SceneGraphSerialization.C_OBJECT_ID_KEY) == rootId)) - { + if (!objectReaders.Any(objectReader => ( + objectReader.Read(SceneGraphSerialization.C_OBJECT_ID_KEY) == rootId + )) + ) { throw new InvalidDataException($"Prefab root '{rootId}' is missing at '{reader.path}'."); } } @@ -242,6 +275,8 @@ ICollection result result.Add(gameObject); IReadOnlyList children = gameObject.transform.children; for (int i = 0; i < children.Count; i++) + { CollectSubtree(children[i].gameObject, result); + } } } diff --git a/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs b/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs index 89c5378a2..77adecdd7 100644 --- a/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; @@ -27,7 +26,9 @@ GameScene value ArgumentNullException.ThrowIfNull(writer); ArgumentNullException.ThrowIfNull(value); if (value.isDestroyed) + { throw new InvalidOperationException("A destroyed scene cannot be serialized."); + } SceneStructureSnapshot snapshot = value.CaptureStructure(); IReadOnlyList systems = value.GetSystems(); @@ -43,7 +44,8 @@ GameScene value snapshot.objects, sourceIds, gameObject => sourceIds.ContainsKey(gameObject), - preserveRootSiblingOrder: true); + preserveRootSiblingOrder: true + ); SceneGraphSerialization.WriteSystems(writer, systems, sourceIds); } } @@ -66,9 +68,12 @@ public override GameScene Read(SerializationReader reader) var scene = new GameScene( SceneWorld.current.typeCatalog, reader.Read(SceneGraphSerialization.C_NAME_KEY), - instantiateFromAsset ? null : sceneId); + instantiateFromAsset ? null : sceneId + ); if (sourceAsset is not null) + { scene.SetSourceAsset(sourceAsset); + } try { RestoreSceneGraph(scene, reader, preservePersistentIds: !instantiateFromAsset); @@ -78,13 +83,13 @@ public override GameScene Read(SerializationReader reader) catch { if (!scene.isDestroyed) + { scene.Unload(); + } throw; } } - - /// /// Restores the supplied snapshot while preserving current invariants. /// @@ -112,12 +117,16 @@ GameScene target catch { foreach (GameSystem system in target.GetSystems().ToArray()) + { target.RemoveSystem(system); + } GameObject[] createdObjects = target.GetObjects().ToArray(); for (int i = 0; i < createdObjects.Length; i++) { if (createdObjects[i].isRuntimeValid) + { target.DestroyObject(createdObjects[i]); + } } throw; } @@ -136,7 +145,8 @@ bool preservePersistentIds references, SceneGraphSerialization.ReadMissingReferenceAliases(reader), reader.context, - restoreProperties: false); + restoreProperties: false + ); IReadOnlyList systemReaders = reader.ReadObjectArray(SceneGraphSerialization.C_SYSTEMS_KEY); var missingPlaceholders = graph.missingPlaceholders.ToList(); @@ -146,18 +156,23 @@ bool preservePersistentIds systemReaders, preservePersistentIds, references, - missingPlaceholders); + missingPlaceholders + ); SceneGraphSerialization.RestoreMissingReferenceAliases( graph with { missingPlaceholders = missingPlaceholders }, - references); + references + ); using (references.Enter()) { SerializationRegistry serialization = reader.context.GetRequired(); foreach ((GameComponent component, byte[] state) in graph.componentStates) + { serialization.RestorePropertiesData(component, state, context: reader.context); + } foreach ((GameSystem system, byte[] state) in systemStates) + { serialization.RestorePropertiesData(system, state, context: reader.context); + } } } - } diff --git a/src/content/scene/Inno.Scene/Serialization/Converters/GameSystemReferenceConverter.cs b/src/content/scene/Inno.Scene/Serialization/Converters/GameSystemReferenceConverter.cs index 6b99c30ac..bae154d55 100644 --- a/src/content/scene/Inno.Scene/Serialization/Converters/GameSystemReferenceConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/Converters/GameSystemReferenceConverter.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; using Inno.Scene; @@ -43,9 +42,12 @@ public override GameSystem Read(SerializationReader reader) ArgumentNullException.ThrowIfNull(reader); var token = new EngineReferenceToken( (EngineReferenceKind)reader.Read("kind"), - reader.Read("sourceId")); + reader.Read("sourceId") + ); if (token.kind != EngineReferenceKind.GameSystem) + { throw new InvalidDataException($"Reference token at '{reader.path}' is not a GameSystem reference."); + } return (GameSystem)SceneReferenceScope.current.Resolve(token, reader.valueType, reader.path); } } diff --git a/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs b/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs index e1f528530..635ec6e3e 100644 --- a/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs +++ b/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Scene; @@ -23,7 +22,9 @@ SceneReferenceScope storageReferences ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(storageReferences); if (connection.sourceAsset.isMissing || connection.sourceAsset.runtimePayload.IsEmpty) + { return connection.overrides; + } (GameScene sourceScene, _, PrefabConnectionRecord sourceConnection) = InstantiateSource(connection.sourceAsset, context); @@ -33,12 +34,7 @@ SceneReferenceScope storageReferences SceneGraphReferenceMap sourceReferences = CreateComparisonReferences(sourceScene, sourceConnection); var overrides = new PrefabOverrideSet(); - CaptureObjectOverrides( - connection, - sourceConnection, - scene, - sourceScene, - overrides); + CaptureObjectOverrides(connection, sourceConnection, scene, sourceScene, overrides); CaptureAdditions(connection, scene, overrides); CaptureComponentOverrides( connection, @@ -49,7 +45,8 @@ SceneReferenceScope storageReferences currentReferences, sourceReferences, storageReferences, - overrides); + overrides + ); PreserveOrphanedOverrides(connection.overrides, sourceConnection, overrides); connection.overrides = overrides; return overrides; @@ -57,7 +54,9 @@ SceneReferenceScope storageReferences finally { if (!sourceScene.isDestroyed) + { sourceScene.Unload(); + } } } @@ -95,14 +94,17 @@ SerializationContext context sourceScene, context, sourceReferences, - targetReferences); + targetReferences + ); RestoreSourceObjectState(connection, sourceConnection, scene, sourceScene, instanceRoot); RefreshInstanceInfo(connection, instanceRoot); } finally { if (!sourceScene.isDestroyed) + { sourceScene.Unload(); + } } } @@ -117,10 +119,12 @@ PrefabOverrideSet overrides { GameObject? sourceObject = sourceScene.FindObject(sourceRuntimeId); GameObject? currentObject = connection.objectIdentities.TryGetValue(sourceId, out Guid currentRuntimeId) - ? scene.FindObject(currentRuntimeId) - : null; + ? scene.FindObject(currentRuntimeId) + : null; if (sourceObject is null) + { continue; + } if (currentObject is null) { overrides.MarkObjectRemoved(sourceId); @@ -129,15 +133,25 @@ PrefabOverrideSet overrides PrefabObjectOverrideKind kind = PrefabObjectOverrideKind.None; if (!string.Equals(currentObject.name, sourceObject.name, StringComparison.Ordinal)) + { kind |= PrefabObjectOverrideKind.Name; + } if (!string.Equals(currentObject.tag, sourceObject.tag, StringComparison.Ordinal)) + { kind |= PrefabObjectOverrideKind.Tag; + } if (currentObject.activeSelf != sourceObject.activeSelf) + { kind |= PrefabObjectOverrideKind.ActiveSelf; + } if (GetMappedParentId(currentObject, connection) != GetMappedParentId(sourceObject, sourceConnection)) + { kind |= PrefabObjectOverrideKind.Parent; + } if (currentObject.transform.siblingIndex != sourceObject.transform.siblingIndex) + { kind |= PrefabObjectOverrideKind.SiblingIndex; + } overrides.SetStructure(sourceId, kind); } } @@ -157,10 +171,12 @@ PrefabOverrideSet overrides { GameComponent? sourceComponent = sourceScene.FindComponent(sourceRuntimeId); GameComponent? currentComponent = connection.componentIdentities.TryGetValue(sourceId, out Guid currentRuntimeId) - ? scene.FindComponent(currentRuntimeId) - : null; + ? scene.FindComponent(currentRuntimeId) + : null; if (sourceComponent is null) + { continue; + } if (currentComponent is null || currentComponent.GetType() != sourceComponent.GetType()) { overrides.MarkComponentRemoved(sourceId); @@ -180,23 +196,28 @@ PrefabOverrideSet overrides member, sourceComponent, context, - sourceReferences); + sourceReferences + ); currentValue = SerializedPropertyValueCodec.Encode( member, currentComponent, context, - currentReferences); + currentReferences + ); } catch (Exception exception) { throw new InvalidOperationException( - $"Failed to compare prefab override for GameComponent " + - $"'{currentComponent.GetType().FullName}.{member.name}' on GameObject " + - $"'{currentComponent.gameObject.name}'.", - exception); + $"Failed to compare prefab override for GameComponent " + + $"'{currentComponent.GetType().FullName}.{member.name}' on GameObject " + + $"'{currentComponent.gameObject.name}'.", + exception + ); } if (sourceValue.AsSpan().SequenceEqual(currentValue)) + { continue; + } byte[] persistedValue; try { @@ -204,15 +225,17 @@ PrefabOverrideSet overrides member, currentComponent, context, - storageReferences); + storageReferences + ); } catch (Exception exception) { throw new InvalidOperationException( - $"Failed to persist prefab override for GameComponent " + - $"'{currentComponent.GetType().FullName}.{member.name}' on GameObject " + - $"'{currentComponent.gameObject.name}'.", - exception); + $"Failed to persist prefab override for GameComponent " + + $"'{currentComponent.GetType().FullName}.{member.name}' on GameObject " + + $"'{currentComponent.gameObject.name}'.", + exception + ); } overrides.SetProperty(new PrefabPropertyOverride(sourceId, member.name, persistedValue)); } @@ -225,10 +248,14 @@ private static void CaptureAdditions( PrefabOverrideSet overrides ) { if (!connection.objectIdentities.TryGetValue(connection.sourceRootId, out Guid rootRuntimeId)) + { return; + } GameObject? root = scene.FindObject(rootRuntimeId); if (root is null) + { return; + } var mappedObjectIds = connection.objectIdentities.Values.ToHashSet(); var mappedComponentIds = connection.componentIdentities.Values.ToHashSet(); var stack = new Stack(); @@ -237,14 +264,20 @@ PrefabOverrideSet overrides { GameObject gameObject = stack.Pop(); if (!mappedObjectIds.Contains(gameObject.identity.persistentId)) + { overrides.MarkObjectAdded(gameObject.identity.persistentId); + } foreach (GameComponent component in gameObject.GetComponents()) { if (!mappedComponentIds.Contains(component.identity.persistentId)) + { overrides.MarkComponentAdded(component.identity.persistentId); + } } foreach (Transform child in gameObject.transform.children) + { stack.Push(child.gameObject); + } } } @@ -257,17 +290,21 @@ PrefabOverrideSet current { if (!sourceConnection.componentIdentities.ContainsKey(property.sourceComponentId)) { - current.SetProperty(property with - { - value = (byte[])property.value.Clone(), - isOrphaned = true - }); + current.SetProperty( + property with + { + value = (byte[])property.value.Clone(), + isOrphaned = true + } + ); } } foreach (PrefabStructureOverride structure in previous.structures) { if (!sourceConnection.objectIdentities.ContainsKey(structure.sourceObjectId)) + { current.SetStructure(structure.sourceObjectId, structure.kind, isOrphaned: true); + } } } @@ -280,29 +317,23 @@ SerializationContext context foreach (PrefabPropertyOverride property in connection.overrides.properties.ToArray()) { bool hasProperty = false; - if (sourceConnection.componentIdentities.TryGetValue( - property.sourceComponentId, - out Guid sourceRuntimeId) && - sourceScene.FindComponent(sourceRuntimeId) is GameComponent sourceComponent) - { + if (sourceConnection.componentIdentities.TryGetValue(property.sourceComponentId, out Guid sourceRuntimeId) + && sourceScene.FindComponent(sourceRuntimeId) is GameComponent sourceComponent + ) { hasProperty = SerializedPropertyValueCodec.GetMembers(sourceComponent.GetType(), context) - .Any(member => string.Equals( - member.name, - property.propertyName, - StringComparison.Ordinal)); + .Any(member => string.Equals(member.name, property.propertyName, StringComparison.Ordinal)); } if (!hasProperty && !property.isOrphaned) + { connection.overrides.SetProperty(property with { isOrphaned = true }); + } } foreach (PrefabStructureOverride structure in connection.overrides.structures.ToArray()) { - if (!sourceConnection.objectIdentities.ContainsKey(structure.sourceObjectId) && - !structure.isOrphaned) - { - connection.overrides.SetStructure( - structure.sourceObjectId, - structure.kind, - isOrphaned: true); + if (!sourceConnection.objectIdentities.ContainsKey(structure.sourceObjectId) + && !structure.isOrphaned + ) { + connection.overrides.SetStructure(structure.sourceObjectId, structure.kind, isOrphaned: true); } } } @@ -314,25 +345,32 @@ private static void RemoveDeletedSourceObjects( GameObject instanceRoot ) { Guid[] removedSourceIds = connection.objectIdentities.Keys - .Where(sourceId => - connection.overrides.IsObjectRemoved(sourceId) || - !sourceConnection.objectIdentities.ContainsKey(sourceId)) + .Where(sourceId => ( + connection.overrides.IsObjectRemoved(sourceId) + || !sourceConnection.objectIdentities.ContainsKey(sourceId) + )) .ToArray(); for (int i = 0; i < removedSourceIds.Length; i++) { Guid sourceId = removedSourceIds[i]; if (!connection.objectIdentities.TryGetValue(sourceId, out Guid runtimeId)) + { continue; + } GameObject? target = scene.FindObject(runtimeId); if (target is null || ReferenceEquals(target, instanceRoot)) + { continue; + } GameObject[] addedChildren = target.transform.children .Select(static child => child.gameObject) .Where(child => !connection.objectIdentities.Values.Contains(child.identity.persistentId)) .ToArray(); for (int childIndex = 0; childIndex < addedChildren.Length; childIndex++) + { scene.SetParent(addedChildren[childIndex].transform, instanceRoot.transform, worldPositionStays: false); + } scene.DestroyObject(target); connection.RemoveObject(sourceId); } @@ -347,20 +385,24 @@ GameScene sourceScene foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.objectIdentities) { if (connection.objectIdentities.ContainsKey(sourceId) || connection.overrides.IsObjectRemoved(sourceId)) + { continue; + } GameObject sourceObject = sourceScene.FindObject(sourceRuntimeId) ?? throw new InvalidOperationException($"Prefab source object '{sourceId}' disappeared during reconciliation."); GameObject target = scene.CreateObject( sourceObject.name, persistentId: null, transformPersistentId: null, - invokeReset: false); + invokeReset: false + ); target.SetTagDirect(sourceObject.tag); target.SetActiveSelfDirect(sourceObject.activeSelf); connection.MapObject(sourceId, target); Guid sourceTransformId = sourceConnection.componentIdentities.Single( - pair => pair.Value == sourceObject.transform.identity.persistentId).Key; + pair => pair.Value == sourceObject.transform.identity.persistentId + ).Key; connection.MapComponent(sourceTransformId, target.transform); } } @@ -371,18 +413,23 @@ private static void RemoveDeletedSourceComponents( GameScene scene ) { Guid[] removedSourceIds = connection.componentIdentities.Keys - .Where(sourceId => - connection.overrides.IsComponentRemoved(sourceId) || - !sourceConnection.componentIdentities.ContainsKey(sourceId)) + .Where(sourceId => ( + connection.overrides.IsComponentRemoved(sourceId) + || !sourceConnection.componentIdentities.ContainsKey(sourceId) + )) .ToArray(); for (int i = 0; i < removedSourceIds.Length; i++) { Guid sourceId = removedSourceIds[i]; if (!connection.componentIdentities.TryGetValue(sourceId, out Guid runtimeId)) + { continue; + } GameComponent? target = scene.FindComponent(runtimeId); if (target is not null && target is not Transform) + { scene.RemoveComponent(target.gameObject, target); + } connection.RemoveComponent(sourceId); } } @@ -395,22 +442,25 @@ GameScene sourceScene ) { foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.componentIdentities) { - if (connection.componentIdentities.ContainsKey(sourceId) || - connection.overrides.IsComponentRemoved(sourceId)) - { + if (connection.componentIdentities.ContainsKey(sourceId) + || connection.overrides.IsComponentRemoved(sourceId) + ) { continue; } GameComponent sourceComponent = sourceScene.FindComponent(sourceRuntimeId) ?? throw new InvalidOperationException($"Prefab source component '{sourceId}' disappeared during reconciliation."); Guid sourceOwnerId = sourceConnection.objectIdentities.Single( - pair => pair.Value == sourceComponent.gameObject.identity.persistentId).Key; + pair => pair.Value == sourceComponent.gameObject.identity.persistentId + ).Key; if (!connection.objectIdentities.TryGetValue(sourceOwnerId, out Guid targetOwnerId)) + { continue; + } GameObject targetOwner = scene.FindObject(targetOwnerId) ?? throw new InvalidOperationException($"Prefab target owner for source object '{sourceOwnerId}' is unavailable."); GameComponent target = sourceComponent is Transform - ? targetOwner.transform - : scene.AddComponent(targetOwner, sourceComponent.GetType(), persistentId: null, invokeReset: false); + ? targetOwner.transform + : scene.AddComponent(targetOwner, sourceComponent.GetType(), persistentId: null, invokeReset: false); connection.MapComponent(sourceId, target); } } @@ -427,12 +477,14 @@ SceneGraphReferenceMap targetReferences foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.componentIdentities) { if (!connection.componentIdentities.TryGetValue(sourceId, out Guid targetRuntimeId)) + { continue; + } GameComponent? sourceComponent = sourceScene.FindComponent(sourceRuntimeId); GameComponent? targetComponent = scene.FindComponent(targetRuntimeId); - if (sourceComponent is null || targetComponent is null || - sourceComponent.GetType() != targetComponent.GetType()) - { + if (sourceComponent is null || targetComponent is null + || sourceComponent.GetType() != targetComponent.GetType() + ) { continue; } @@ -442,18 +494,11 @@ SceneGraphReferenceMap targetReferences { SerializationMemberMetadata member = members[memberIndex]; if (connection.overrides.IsPropertyOverridden(sourceId, member.name)) + { continue; - byte[] value = SerializedPropertyValueCodec.Encode( - member, - sourceComponent, - context, - sourceReferences); - SerializedPropertyValueCodec.Decode( - member, - targetComponent, - value, - context, - targetReferences); + } + byte[] value = SerializedPropertyValueCodec.Encode(member, sourceComponent, context, sourceReferences); + SerializedPropertyValueCodec.Decode(member, targetComponent, value, context, targetReferences); } } } @@ -468,45 +513,61 @@ GameObject instanceRoot foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.objectIdentities) { if (!connection.objectIdentities.TryGetValue(sourceId, out Guid targetRuntimeId)) + { continue; + } GameObject? sourceObject = sourceScene.FindObject(sourceRuntimeId); GameObject? targetObject = scene.FindObject(targetRuntimeId); if (sourceObject is null || targetObject is null) + { continue; + } PrefabObjectOverrideKind kind = connection.overrides.GetStructureOverride(sourceId); if ((kind & PrefabObjectOverrideKind.Name) == 0) + { targetObject.SetNameDirect(sourceObject.name); + } if ((kind & PrefabObjectOverrideKind.Tag) == 0) + { targetObject.SetTagDirect(sourceObject.tag); + } if ((kind & PrefabObjectOverrideKind.ActiveSelf) == 0) - targetObject.SetActiveSelfDirect(sourceObject.activeSelf); - if (!ReferenceEquals(targetObject, instanceRoot) && - (kind & PrefabObjectOverrideKind.Parent) == 0) { + targetObject.SetActiveSelfDirect(sourceObject.activeSelf); + } + if (!ReferenceEquals(targetObject, instanceRoot) + && (kind & PrefabObjectOverrideKind.Parent) == 0 + ) { Guid sourceParentId = GetMappedParentId(sourceObject, sourceConnection); Transform? targetParent = sourceParentId == Guid.Empty - ? instanceRoot.transform - : connection.objectIdentities.TryGetValue(sourceParentId, out Guid parentRuntimeId) - ? scene.FindObject(parentRuntimeId)?.transform - : null; + ? instanceRoot.transform + : connection.objectIdentities.TryGetValue(sourceParentId, out Guid parentRuntimeId) + ? scene.FindObject(parentRuntimeId)?.transform + : null; scene.SetParent(targetObject.transform, targetParent, worldPositionStays: false); } } foreach ((Guid sourceId, Guid sourceRuntimeId) in sourceConnection.objectIdentities - .OrderBy(pair => sourceScene.FindObject(pair.Value)?.transform.siblingIndex ?? int.MaxValue)) - { + .OrderBy(pair => sourceScene.FindObject(pair.Value)?.transform.siblingIndex ?? int.MaxValue) + ) { if (!connection.objectIdentities.TryGetValue(sourceId, out Guid targetRuntimeId)) + { continue; + } GameObject? targetObject = scene.FindObject(targetRuntimeId); if (targetObject is null || ReferenceEquals(targetObject, instanceRoot)) + { continue; + } if ((connection.overrides.GetStructureOverride(sourceId) & PrefabObjectOverrideKind.SiblingIndex) == 0) { GameObject? sourceObject = sourceScene.FindObject(sourceRuntimeId); if (sourceObject is not null) + { scene.SetSiblingIndex(targetObject.transform, sourceObject.transform.siblingIndex); + } } scene.RecomputeActiveSubtree(targetObject); } @@ -522,17 +583,22 @@ GameObject instanceRoot { GameObject? gameObject = scene.FindObject(runtimeId); if (gameObject is null) + { continue; - gameObject.SetPrefabInstanceDirect(new PrefabInstanceInfo( - connection.sourceAsset.identity.persistentId, - sourceId, - instanceRoot, - ReferenceEquals(gameObject, instanceRoot), - connection.isVariant, - connection.sourceAsset.isMissing, - connection.overrides.count, - connection.overrides.orphanedCount, - connection.sourceAsset)); + } + gameObject.SetPrefabInstanceDirect( + new PrefabInstanceInfo( + connection.sourceAsset.identity.persistentId, + sourceId, + instanceRoot, + ReferenceEquals(gameObject, instanceRoot), + connection.isVariant, + connection.sourceAsset.isMissing, + connection.overrides.count, + connection.overrides.orphanedCount, + connection.sourceAsset + ) + ); } instanceRoot.SetPrefabConnectionDirect(connection); } @@ -546,18 +612,24 @@ PrefabConnectionRecord connection .ToArray(); var ids = new Dictionary(ReferenceEqualityComparer.Instance); for (int objectIndex = 0; objectIndex < allObjects.Length; objectIndex++) + { ids.Add(allObjects[objectIndex], allObjects[objectIndex].identity.persistentId); + } foreach ((Guid sourceId, Guid runtimeId) in connection.objectIdentities) { GameObject? gameObject = scene.FindObject(runtimeId); if (gameObject is not null) + { ids[gameObject] = sourceId; + } } foreach ((Guid sourceId, Guid runtimeId) in connection.componentIdentities) { GameComponent? component = scene.FindComponent(runtimeId); if (component is not null) + { ids[component] = sourceId; + } } return new SceneGraphReferenceMap(scene, ids); } @@ -571,13 +643,17 @@ PrefabConnectionRecord connection { GameObject? gameObject = scene.FindObject(runtimeId); if (gameObject is not null) + { references.Register(sourceId, gameObject); + } } foreach ((Guid sourceId, Guid runtimeId) in connection.componentIdentities) { GameComponent? component = scene.FindComponent(runtimeId); if (component is not null) + { references.Register(sourceId, component); + } } return references; } @@ -588,12 +664,16 @@ PrefabConnectionRecord connection ) { Transform? parent = gameObject.transform.parent; if (parent is null) + { return Guid.Empty; + } Guid parentRuntimeId = parent.gameObject.identity.persistentId; foreach ((Guid sourceId, Guid runtimeId) in connection.objectIdentities) { if (runtimeId == parentRuntimeId) + { return sourceId; + } } return parentRuntimeId; } @@ -602,10 +682,7 @@ private static (GameScene scene, GameObject root, PrefabConnectionRecord connect AssetObject sourceAsset, SerializationContext context ) { - var sourceScene = new GameScene( - SceneWorld.current.typeCatalog, - "Prefab Source Comparison", - persistentId: null); + var sourceScene = new GameScene(SceneWorld.current.typeCatalog, "Prefab Source Comparison", persistentId: null); SerializationContext sourceContext = context .With(sourceScene) .With(sourceAsset); @@ -615,19 +692,25 @@ SerializationContext context { GameObject sourceRoot = context.GetRequired().Deserialize( sourceAsset.runtimePayload.Span, - sourceContext); + sourceContext + ); if (!string.IsNullOrWhiteSpace(sourceAsset.assetPath.ToString())) + { sourceRoot.name = Path.GetFileNameWithoutExtension(sourceAsset.assetPath.ToString()); + } PrefabConnectionRecord connection = sourceRoot.prefabConnection ?? throw new InvalidOperationException( - $"Prefab source asset '{sourceAsset.identity.persistentId}' did not create a source mapping."); + $"Prefab source asset '{sourceAsset.identity.persistentId}' did not create a source mapping." + ); return (sourceScene, sourceRoot, connection); } } catch { if (!sourceScene.isDestroyed) + { sourceScene.Unload(); + } throw; } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneElementSerialization.cs b/src/content/scene/Inno.Scene/Serialization/SceneElementSerialization.cs index 291d2a29d..9775dde86 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneElementSerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneElementSerialization.cs @@ -1,11 +1,10 @@ using System; using System.IO; using System.Runtime.ExceptionServices; - using Inno.Assets; using Inno.Core.Identity; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Scene; @@ -65,13 +64,19 @@ IAssetReferenceResolver assets else { if (target is not GameComponent and not GameSystem) + { throw new ArgumentException("Element state requires a component or system.", nameof(target)); + } state.typeId = scene.typeCatalog.GetTypeRef(target.GetType()).stableId; state.typeName = target.GetType().FullName ?? target.GetType().Name; var dependencies = new AssetDependencyCollection(); using (ScenePropertySerialization.CreateReferences(scene).Enter()) - state.properties = serialization.CapturePropertiesData((ISerializable)target, - AssetSerializationContext.Create(assets, dependencies)); + { + state.properties = serialization.CapturePropertiesData( + (ISerializable)target, + AssetSerializationContext.Create(assets, dependencies) + ); + } state.SetDependencies(dependencies.dependencies); } return serialization.Serialize(state, AssetSerializationContext.Create(assets)); @@ -115,14 +120,27 @@ IAssetReferenceResolver assets }; RequireType(state, logicalType); if (target is MissingGameComponent component) + { component.RestoreState(state); + } else if (target is MissingGameSystem system) + { system.RestoreState(state); + } else { using (ScenePropertySerialization.CreateReferences(scene, state.GetAliases()).Enter()) - RequireComplete(serialization.RestorePropertiesData((ISerializable)target, state.properties, - SerializationPropertyRestoreMode.Strict, AssetSerializationContext.Create(assets)), "element"); + { + RequireComplete( + serialization.RestorePropertiesData( + (ISerializable)target, + state.properties, + SerializationPropertyRestoreMode.Strict, + AssetSerializationContext.Create(assets) + ), + "element" + ); + } } } @@ -179,9 +197,15 @@ IAssetReferenceResolver assets RequireType(state, type.stableId); Type? componentType = ResolveType(owner.scene.typeCatalog, type, "component"); GameComponent component = componentType is null - ? owner.scene.AddMissingComponent(owner, new TypeRef(state.typeId), state.typeName, - state.properties, persistentId, state.GetDependencies()) - : owner.scene.AddComponent(owner, componentType, persistentId, invokeReset: false); + ? owner.scene.AddMissingComponent( + owner, + new TypeRef(state.typeId), + state.typeName, + state.properties, + persistentId, + state.GetDependencies() + ) + : owner.scene.AddComponent(owner, componentType, persistentId, invokeReset: false); try { owner.SetComponentIndex(component, componentIndex); @@ -190,11 +214,7 @@ IAssetReferenceResolver assets } catch (Exception exception) { - RethrowAfterCleanup( - exception, - component, - () => owner.RemoveComponent(component), - "component"); + RethrowAfterCleanup(exception, component, () => owner.RemoveComponent(component), "component"); throw; } } @@ -262,11 +282,7 @@ IAssetReferenceResolver assets } catch (Exception exception) { - RethrowAfterCleanup( - exception, - system, - () => scene.RemoveSystem(system), - "system"); + RethrowAfterCleanup(exception, system, () => scene.RemoveSystem(system), "system"); throw; } } @@ -276,11 +292,14 @@ private static void RequireComplete( string kind ) { if (result.success && result.ignoredCount == 0) + { return; + } throw new InvalidOperationException( - $"Scene {kind} property restoration was incomplete: " + - $"{result.restoredCount} restored, {result.ignoredCount} ignored, " + - $"{result.failures.Count} failed."); + $"Scene {kind} property restoration was incomplete: " + + $"{result.restoredCount} restored, {result.ignoredCount} ignored, " + + $"{result.failures.Count} failed." + ); } internal static void RethrowAfterCleanup( @@ -303,22 +322,24 @@ string kind cleanupFailure = exception; } } - bool remainsRegistered = ReferenceEquals( - IdentityAllocator.current.Get(persistentId), - element); + bool remainsRegistered = ReferenceEquals(IdentityAllocator.current.Get(persistentId), element); if ((!element.isDestroyed || remainsRegistered) && cleanupFailure is null) { cleanupFailure = new InvalidOperationException( reportedRemoved - ? $"The partially restored scene {kind} reported successful removal but did not reach the destroyed and unregistered postcondition." - : $"The partially restored scene {kind} could not be fully destroyed and unregistered."); + ? $"The partially restored scene {kind} reported successful removal but did not reach the destroyed and unregistered postcondition." + : $"The partially restored scene {kind} could not be fully destroyed and unregistered." + ); } if (cleanupFailure is null) + { ExceptionDispatchInfo.Capture(restoreFailure).Throw(); + } throw new InvalidOperationException( $"Scene {kind} restoration failed and its cleanup did not complete successfully.", - new AggregateException(restoreFailure, cleanupFailure)); + new AggregateException(restoreFailure, cleanupFailure) + ); } private static SceneElementState ReadState( @@ -329,7 +350,7 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); SceneElementState state = serialization.Deserialize(bytes, AssetSerializationContext.Create(assets)) - ?? throw new InvalidDataException("Scene element state is null."); + ?? throw new InvalidDataException("Scene element state is null."); state.Validate(); return state; } @@ -339,15 +360,16 @@ private static void RequireType( Guid typeId ) { if (state.typeId != typeId) + { throw new InvalidDataException($"Element state type '{state.typeId}' does not match logical type '{typeId}'."); + } } private static Type? ResolveType( SceneTypeCatalog types, TypeRef typeRef, string kind - ) - where TElement : EngineObject + ) where TElement : EngineObject { Type type; try @@ -361,7 +383,8 @@ string kind if (!typeof(TElement).IsAssignableFrom(type) || type.IsAbstract) { throw new InvalidDataException( - $"Stable type id '{typeRef.stableId}' resolves to invalid scene {kind} '{type.FullName}'."); + $"Stable type id '{typeRef.stableId}' resolves to invalid scene {kind} '{type.FullName}'." + ); } return type; } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs b/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs index 4519e52f8..31962193e 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs @@ -37,8 +37,11 @@ internal AssetDependency[] GetDependencies() => dependencyIds.Select(( id, index - ) => new AssetDependency(id, - new Inno.Extensibility.Types.TypeRef(dependencyTypes[index]), dependencyPaths[index])).ToArray(); + ) => new AssetDependency( + id, + new Inno.Extensibility.Types.TypeRef(dependencyTypes[index]), + dependencyPaths[index] + )).ToArray(); internal IReadOnlyDictionary GetAliases() => aliasIds.Select(( @@ -48,15 +51,17 @@ internal IReadOnlyDictionary GetAliases() internal void Validate() { - if (typeId == Guid.Empty || string.IsNullOrWhiteSpace(typeName) || properties is null || - dependencyIds is null || dependencyTypes is null || dependencyPaths is null || - aliasIds is null || aliasTargets is null || - dependencyIds.Length != dependencyTypes.Length || dependencyIds.Length != dependencyPaths.Length || - aliasIds.Length != aliasTargets.Length || - dependencyIds.Any(static id => id == Guid.Empty) || - dependencyIds.Distinct().Count() != dependencyIds.Length || - aliasIds.Any(static id => id == Guid.Empty) || aliasTargets.Any(static id => id == Guid.Empty) || - aliasIds.Distinct().Count() != aliasIds.Length) + if (typeId == Guid.Empty || string.IsNullOrWhiteSpace(typeName) || properties is null + || dependencyIds is null || dependencyTypes is null || dependencyPaths is null + || aliasIds is null || aliasTargets is null + || dependencyIds.Length != dependencyTypes.Length || dependencyIds.Length != dependencyPaths.Length + || aliasIds.Length != aliasTargets.Length + || dependencyIds.Any(static id => id == Guid.Empty) + || dependencyIds.Distinct().Count() != dependencyIds.Length + || aliasIds.Any(static id => id == Guid.Empty) || aliasTargets.Any(static id => id == Guid.Empty) + || aliasIds.Distinct().Count() != aliasIds.Length + ) { throw new InvalidDataException("Scene element state contains invalid type, dependency or alias metadata."); + } } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/RestoredSceneGraph.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/RestoredSceneGraph.cs index 91d2f75f9..1c270e0ee 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/RestoredSceneGraph.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/RestoredSceneGraph.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Scene; namespace Inno.Scene; diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs index 292656f14..151da9bad 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Scene; namespace Inno.Scene; @@ -17,7 +16,8 @@ internal SceneGraphReferenceMap( GameScene scene, IReadOnlyDictionary? sourceIds = null, GameObject? captureRoot = null - ) : base(scene, captureRoot) { + ) : base(scene, captureRoot) + { // Capture callers own the complete map and keep it fixed for this synchronous scope. m_sourceIdByObject = sourceIds; } @@ -26,9 +26,9 @@ internal void Register( Guid sourceId, EngineObject engineObject ) { - if (!m_objectBySourceId.TryAdd(sourceId, engineObject) && - !ReferenceEquals(m_objectBySourceId[sourceId], engineObject)) - { + if (!m_objectBySourceId.TryAdd(sourceId, engineObject) + && !ReferenceEquals(m_objectBySourceId[sourceId], engineObject) + ) { throw new InvalidOperationException($"Duplicate scene graph local identity '{sourceId}'."); } } @@ -40,16 +40,19 @@ internal Dictionary CaptureRemappedAliases() { Guid persistentId = engineObject.identity.persistentId; if (sourceId != persistentId) + { aliases.Add(sourceId, persistentId); + } } return aliases; } internal EngineObject GetRegistered(Guid sourceId) => m_objectBySourceId.TryGetValue(sourceId, out EngineObject? engineObject) - ? engineObject - : throw new InvalidOperationException( - $"Scene graph reference alias target '{sourceId}' could not be resolved."); + ? engineObject + : throw new InvalidOperationException( + $"Scene graph reference alias target '{sourceId}' could not be resolved." + ); /// protected override bool TryGetSourceId( diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs index 1f515d513..df4699c09 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs @@ -2,10 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -73,84 +72,92 @@ bool preserveRootSiblingOrder component ) => WriteComponent(componentWriter, component, sourceIds); WriteMissingReferenceAliases(writer, sourceIds); - writer.WriteObjectArray(C_OBJECTS_KEY, entries, ( - objectWriter, - entry - ) => - { - GameObject gameObject = entry.gameObject; - Transform? parent = gameObject.transform.parent; - bool parentIsIncluded = parent is not null && containsObject(parent.gameObject); - objectWriter.Write(C_OBJECT_ID_KEY, GetSourceId(sourceIds, gameObject)); - objectWriter.Write(C_NAME_KEY, gameObject.name); - objectWriter.Write(C_TAG_KEY, gameObject.tag); - objectWriter.Write(C_LAYER_KEY, gameObject.layer.index); - objectWriter.Write(C_ACTIVE_SELF_KEY, gameObject.activeSelf); - objectWriter.Write( - C_PARENT_ID_KEY, - parentIsIncluded ? GetSourceId(sourceIds, parent!.gameObject) : Guid.Empty); - objectWriter.Write( - C_SIBLING_INDEX_KEY, - parentIsIncluded || preserveRootSiblingOrder ? gameObject.transform.siblingIndex : 0); - PrefabInstanceInfo? prefab = gameObject.prefabInstance; - bool hasPrefabConnection = prefab is not null && containsObject(prefab.instanceRoot); - objectWriter.Write(C_HAS_PREFAB_CONNECTION_KEY, hasPrefabConnection); - if (hasPrefabConnection) + writer.WriteObjectArray( + C_OBJECTS_KEY, + entries, + ( + objectWriter, + entry + ) => { - AssetObject sourceAsset = prefab!.sourceAsset; - objectWriter.Write(C_PREFAB_SOURCE_ASSET_KEY, sourceAsset); - objectWriter.Write(C_PREFAB_SOURCE_ASSET_ID_KEY, prefab!.sourceAssetId); - objectWriter.Write(C_PREFAB_SOURCE_OBJECT_ID_KEY, prefab.sourceObjectId); - objectWriter.Write(C_PREFAB_INSTANCE_ROOT_ID_KEY, GetSourceId(sourceIds, prefab.instanceRoot)); - objectWriter.Write(C_PREFAB_IS_VARIANT_KEY, prefab.isVariant); - objectWriter.Write(C_PREFAB_IS_MISSING_KEY, prefab.isMissing); - PrefabOverrideSet? capturedOverrides = null; - if (prefab.isRoot) - { - PrefabConnectionRecord connection = gameObject.prefabConnection - ?? throw new InvalidOperationException( - $"Prefab instance root '{gameObject.identity.persistentId}' has no connection mapping."); - capturedOverrides = PrefabOverrideProcessor.Capture( - connection, - gameObject.scene, - objectWriter.context, - SceneReferenceScope.current); - WritePrefabConnection( - objectWriter, - connection, - capturedOverrides, - sourceIds, - gameObject.scene); - } + GameObject gameObject = entry.gameObject; + Transform? parent = gameObject.transform.parent; + bool parentIsIncluded = parent is not null && containsObject(parent.gameObject); + objectWriter.Write(C_OBJECT_ID_KEY, GetSourceId(sourceIds, gameObject)); + objectWriter.Write(C_NAME_KEY, gameObject.name); + objectWriter.Write(C_TAG_KEY, gameObject.tag); + objectWriter.Write(C_LAYER_KEY, gameObject.layer.index); + objectWriter.Write(C_ACTIVE_SELF_KEY, gameObject.activeSelf); objectWriter.Write( - C_PREFAB_OVERRIDE_COUNT_KEY, - capturedOverrides?.count ?? prefab.overrideCount); + C_PARENT_ID_KEY, + parentIsIncluded ? GetSourceId(sourceIds, parent!.gameObject) : Guid.Empty + ); objectWriter.Write( - C_PREFAB_ORPHANED_OVERRIDE_COUNT_KEY, - capturedOverrides?.orphanedCount ?? prefab.orphanedOverrideCount); - } - objectWriter.WriteObjectArray(C_COMPONENTS_KEY, entry.components, writeComponent); - }, captureKey: ( - entry, - key - ) => { - GameObject gameObject = entry.gameObject; - if (gameObject.prefabInstance is not null || !key.TryAddOwner(gameObject, gameObject.captureRevision)) - return false; - Transform? parent = gameObject.transform.parent; - bool parentIsIncluded = parent is not null && containsObject(parent.gameObject); - key.AddValue(GetSourceId(sourceIds, gameObject)); - key.AddValue(parentIsIncluded ? GetSourceId(sourceIds, parent!.gameObject) : Guid.Empty); - key.AddValue((ulong)(parentIsIncluded || preserveRootSiblingOrder ? gameObject.transform.siblingIndex : 0)); - for (int componentIndex = 0; componentIndex < entry.components.Count; componentIndex++) - { - GameComponent component = entry.components[componentIndex]; - if (component is MissingGameComponent || !key.TryAddProperties(component)) + C_SIBLING_INDEX_KEY, + parentIsIncluded || preserveRootSiblingOrder ? gameObject.transform.siblingIndex : 0 + ); + PrefabInstanceInfo? prefab = gameObject.prefabInstance; + bool hasPrefabConnection = prefab is not null && containsObject(prefab.instanceRoot); + objectWriter.Write(C_HAS_PREFAB_CONNECTION_KEY, hasPrefabConnection); + if (hasPrefabConnection) + { + AssetObject sourceAsset = prefab!.sourceAsset; + objectWriter.Write(C_PREFAB_SOURCE_ASSET_KEY, sourceAsset); + objectWriter.Write(C_PREFAB_SOURCE_ASSET_ID_KEY, prefab!.sourceAssetId); + objectWriter.Write(C_PREFAB_SOURCE_OBJECT_ID_KEY, prefab.sourceObjectId); + objectWriter.Write(C_PREFAB_INSTANCE_ROOT_ID_KEY, GetSourceId(sourceIds, prefab.instanceRoot)); + objectWriter.Write(C_PREFAB_IS_VARIANT_KEY, prefab.isVariant); + objectWriter.Write(C_PREFAB_IS_MISSING_KEY, prefab.isMissing); + PrefabOverrideSet? capturedOverrides = null; + if (prefab.isRoot) + { + PrefabConnectionRecord connection = gameObject.prefabConnection + ?? throw new InvalidOperationException( + $"Prefab instance root '{gameObject.identity.persistentId}' has no connection mapping." + ); + capturedOverrides = PrefabOverrideProcessor.Capture( + connection, + gameObject.scene, + objectWriter.context, + SceneReferenceScope.current + ); + WritePrefabConnection(objectWriter, connection, capturedOverrides, sourceIds, gameObject.scene); + } + objectWriter.Write(C_PREFAB_OVERRIDE_COUNT_KEY, capturedOverrides?.count ?? prefab.overrideCount); + objectWriter.Write( + C_PREFAB_ORPHANED_OVERRIDE_COUNT_KEY, + capturedOverrides?.orphanedCount ?? prefab.orphanedOverrideCount + ); + } + objectWriter.WriteObjectArray(C_COMPONENTS_KEY, entry.components, writeComponent); + }, + captureKey: ( + entry, + key + ) => + { + GameObject gameObject = entry.gameObject; + if (gameObject.prefabInstance is not null || !key.TryAddOwner(gameObject, gameObject.captureRevision)) + { return false; - key.AddValue(GetSourceId(sourceIds, component)); + } + Transform? parent = gameObject.transform.parent; + bool parentIsIncluded = parent is not null && containsObject(parent.gameObject); + key.AddValue(GetSourceId(sourceIds, gameObject)); + key.AddValue(parentIsIncluded ? GetSourceId(sourceIds, parent!.gameObject) : Guid.Empty); + key.AddValue((ulong)(parentIsIncluded || preserveRootSiblingOrder ? gameObject.transform.siblingIndex : 0)); + for (int componentIndex = 0; componentIndex < entry.components.Count; componentIndex++) + { + GameComponent component = entry.components[componentIndex]; + if (component is MissingGameComponent || !key.TryAddProperties(component)) + { + return false; + } + key.AddValue(GetSourceId(sourceIds, component)); + } + return true; } - return true; - }); + ); } internal static RestoredSceneGraph RestoreObjects( @@ -183,9 +190,9 @@ internal static RestoredSceneGraph RestoreObjects( objectReader.Read(C_NAME_KEY), preservePersistentIds ? sourceObjectId : null, preservePersistentIds ? sourceTransformId : null, - invokeReset: false); - gameObject.SetTagDirect( - objectReader.Read(C_TAG_KEY)); + invokeReset: false + ); + gameObject.SetTagDirect(objectReader.Read(C_TAG_KEY)); gameObject.SetLayerDirect(new GameLayer(objectReader.Read(C_LAYER_KEY))); gameObject.SetActiveSelfDirect(objectReader.Read(C_ACTIVE_SELF_KEY)); gameObjectBySourceId.Add(sourceObjectId, gameObject); @@ -204,9 +211,9 @@ internal static RestoredSceneGraph RestoreObjects( { SerializationReader componentReader = componentReaders[componentIndex]; Guid stableTypeId = componentReader.Read(C_STABLE_TYPE_ID_KEY); - if (TryResolveComponentType(stableTypeId, componentReader.context, out Type? componentType) && - componentType == typeof(Transform)) - { + if (TryResolveComponentType(stableTypeId, componentReader.context, out Type? componentType) + && componentType == typeof(Transform) + ) { transformIndex = componentIndex; continue; } @@ -223,7 +230,8 @@ internal static RestoredSceneGraph RestoreObjects( componentReader.Read(C_TYPE_NAME_KEY), state, preservePersistentIds ? sourceComponentId : null, - dependencies); + dependencies + ); missingPlaceholders.Add(component); } else @@ -232,7 +240,8 @@ internal static RestoredSceneGraph RestoreObjects( gameObject, componentType, preservePersistentIds ? sourceComponentId : null, - invokeReset: false); + invokeReset: false + ); componentRestores.Add((component, state)); } componentBySourceId.Add(sourceComponentId, component); @@ -240,15 +249,20 @@ internal static RestoredSceneGraph RestoreObjects( if (transformIndex < 0) { throw new InvalidDataException( - $"Scene graph object '{sourceObjectId}' does not contain its validated Transform component."); + $"Scene graph object '{sourceObjectId}' does not contain its validated Transform component." + ); } gameObject.SetComponentIndex(gameObject.transform, transformIndex); } foreach ((Guid sourceId, GameObject gameObject) in gameObjectBySourceId) + { references.Register(sourceId, gameObject); + } foreach ((Guid sourceId, GameComponent component) in componentBySourceId) + { references.Register(sourceId, component); + } if (restoreProperties) { @@ -261,7 +275,8 @@ internal static RestoredSceneGraph RestoreObjects( serialization.RestorePropertiesData( componentRestores[i].component, componentRestores[i].state, - context: context); + context: context + ); } } } @@ -272,23 +287,25 @@ internal static RestoredSceneGraph RestoreObjects( Guid sourceObjectId = objectReader.Read(C_OBJECT_ID_KEY); Guid parentId = objectReader.Read(C_PARENT_ID_KEY); Transform? parent = parentId == Guid.Empty - ? null - : gameObjectBySourceId.TryGetValue(parentId, out GameObject? parentObject) - ? parentObject.transform - : throw new InvalidDataException( - $"Parent object '{parentId}' for object '{sourceObjectId}' is outside the restored boundary."); + ? null + : gameObjectBySourceId.TryGetValue(parentId, out GameObject? parentObject) + ? parentObject.transform + : throw new InvalidDataException( + $"Parent object '{parentId}' for object '{sourceObjectId}' is outside the restored boundary." + ); scene.SetParent(gameObjectBySourceId[sourceObjectId].transform, parent, worldPositionStays: false); } foreach (IGrouping siblingGroup in objectReaders.GroupBy( - objectReader => objectReader.Read(C_PARENT_ID_KEY))) - { + objectReader => objectReader.Read(C_PARENT_ID_KEY) + )) { foreach (SerializationReader objectReader in siblingGroup.OrderBy( - reader => reader.Read(C_SIBLING_INDEX_KEY))) - { + reader => reader.Read(C_SIBLING_INDEX_KEY) + )) { scene.SetSiblingIndex( gameObjectBySourceId[objectReader.Read(C_OBJECT_ID_KEY)].transform, - objectReader.Read(C_SIBLING_INDEX_KEY)); + objectReader.Read(C_SIBLING_INDEX_KEY) + ); } } @@ -297,22 +314,28 @@ internal static RestoredSceneGraph RestoreObjects( { SerializationReader objectReader = objectReaders[objectIndex]; if (!objectReader.Read(C_HAS_PREFAB_CONNECTION_KEY)) + { continue; + } Guid serializedObjectId = objectReader.Read(C_OBJECT_ID_KEY); Guid instanceRootId = objectReader.Read(C_PREFAB_INSTANCE_ROOT_ID_KEY); if (serializedObjectId != instanceRootId) + { continue; + } if (!gameObjectBySourceId.TryGetValue(instanceRootId, out GameObject? instanceRoot)) { throw new InvalidDataException( - $"Prefab instance root '{instanceRootId}' at '{objectReader.path}' is outside the restored graph."); + $"Prefab instance root '{instanceRootId}' at '{objectReader.path}' is outside the restored graph." + ); } AssetObject sourceAsset = objectReader.Read(C_PREFAB_SOURCE_ASSET_KEY); Guid sourceAssetId = objectReader.Read(C_PREFAB_SOURCE_ASSET_ID_KEY); if (sourceAsset.identity.persistentId != sourceAssetId) { throw new InvalidDataException( - $"Prefab source token and source identity disagree at '{objectReader.path}'."); + $"Prefab source token and source identity disagree at '{objectReader.path}'." + ); } PrefabOverrideSet overrides = ReadPrefabOverrides(objectReader); @@ -320,16 +343,18 @@ internal static RestoredSceneGraph RestoreObjects( sourceAsset, objectReader.Read(C_PREFAB_SOURCE_OBJECT_ID_KEY), objectReader.Read(C_PREFAB_IS_VARIANT_KEY), - overrides); + overrides + ); foreach (SerializationReader mappingReader in - objectReader.ReadObjectArray(C_PREFAB_COMPONENT_MAPPINGS_KEY)) - { + objectReader.ReadObjectArray(C_PREFAB_COMPONENT_MAPPINGS_KEY) + ) { Guid componentSourceId = mappingReader.Read(C_PREFAB_MAPPING_SOURCE_ID_KEY); Guid componentInstanceId = mappingReader.Read(C_PREFAB_MAPPING_INSTANCE_ID_KEY); if (!componentBySourceId.TryGetValue(componentInstanceId, out GameComponent? component)) { throw new InvalidDataException( - $"Prefab component mapping '{componentInstanceId}' at '{mappingReader.path}' does not resolve."); + $"Prefab component mapping '{componentInstanceId}' at '{mappingReader.path}' does not resolve." + ); } connection.MapComponent(componentSourceId, component); } @@ -341,33 +366,39 @@ internal static RestoredSceneGraph RestoreObjects( { SerializationReader objectReader = objectReaders[objectIndex]; if (!objectReader.Read(C_HAS_PREFAB_CONNECTION_KEY)) + { continue; + } Guid serializedObjectId = objectReader.Read(C_OBJECT_ID_KEY); Guid instanceRootId = objectReader.Read(C_PREFAB_INSTANCE_ROOT_ID_KEY); - if (!gameObjectBySourceId.TryGetValue(instanceRootId, out GameObject? instanceRoot) || - !connectionByRootId.TryGetValue(instanceRootId, out PrefabConnectionRecord? connection)) - { + if (!gameObjectBySourceId.TryGetValue(instanceRootId, out GameObject? instanceRoot) + || !connectionByRootId.TryGetValue(instanceRootId, out PrefabConnectionRecord? connection) + ) { throw new InvalidDataException( - $"Prefab instance root '{instanceRootId}' at '{objectReader.path}' has no connection record."); + $"Prefab instance root '{instanceRootId}' at '{objectReader.path}' has no connection record." + ); } GameObject gameObject = gameObjectBySourceId[serializedObjectId]; Guid prefabSourceObjectId = objectReader.Read(C_PREFAB_SOURCE_OBJECT_ID_KEY); connection.MapObject(prefabSourceObjectId, gameObject); - gameObject.SetPrefabInstanceDirect(new PrefabInstanceInfo( - connection.sourceAsset.identity.persistentId, - prefabSourceObjectId, - instanceRoot, - ReferenceEquals(gameObject, instanceRoot), - connection.isVariant, - connection.sourceAsset.isMissing, - connection.overrides.count, - connection.overrides.orphanedCount, - connection.sourceAsset)); + gameObject.SetPrefabInstanceDirect( + new PrefabInstanceInfo( + connection.sourceAsset.identity.persistentId, + prefabSourceObjectId, + instanceRoot, + ReferenceEquals(gameObject, instanceRoot), + connection.isVariant, + connection.sourceAsset.isMissing, + connection.overrides.count, + connection.overrides.orphanedCount, + connection.sourceAsset + ) + ); } foreach (GameObject root in gameObjectBySourceId.Values.Where( - static candidate => candidate.transform.parent is null)) - { + static candidate => candidate.transform.parent is null + )) { scene.RecomputeActiveSubtree(root); } return new RestoredSceneGraph( @@ -375,7 +406,8 @@ internal static RestoredSceneGraph RestoreObjects( componentBySourceId, componentRestores, missingPlaceholders, - missingReferenceAliases); + missingReferenceAliases + ); } internal static void ValidateScene(SerializationReader reader) @@ -433,18 +465,16 @@ IReadOnlyDictionary sourceIds { system = scene.AddMissingSystem( new TypeRef(stableTypeId), - systemReader.Read(C_TYPE_NAME_KEY), - state, - preservePersistentIds ? sourceId : null, - dependencies); + systemReader.Read(C_TYPE_NAME_KEY), + state, + preservePersistentIds ? sourceId : null, + dependencies + ); missingPlaceholders?.Add(system); } else { - system = scene.AddSystem( - systemType, - preservePersistentIds ? sourceId : null, - invokeReset: false); + system = scene.AddSystem(systemType, preservePersistentIds ? sourceId : null, invokeReset: false); result.Add((system, state)); } references.Register(sourceId, system); @@ -455,8 +485,7 @@ IReadOnlyDictionary sourceIds internal static void RestoreMissingReferenceAliases( RestoredSceneGraph graph, SceneGraphReferenceMap references - ) - => RestoreMissingReferenceAliases(graph.missingReferenceAliases, references, graph.missingPlaceholders); + ) => RestoreMissingReferenceAliases(graph.missingReferenceAliases, references, graph.missingPlaceholders); private static void ValidateSystems(IReadOnlyList systemReaders) { @@ -466,7 +495,9 @@ private static void ValidateSystems(IReadOnlyList systemRea Guid systemId = systemReader.Read(C_SYSTEM_ID_KEY); EnsurePersistentId(systemId, $"{systemReader.path}.{C_SYSTEM_ID_KEY}"); if (!identities.Add(systemId)) + { throw new InvalidDataException($"Duplicate GameSystem identity '{systemId}' at '{systemReader.path}'."); + } Guid stableTypeId = systemReader.Read(C_STABLE_TYPE_ID_KEY); EnsurePersistentId(stableTypeId, $"{systemReader.path}.{C_STABLE_TYPE_ID_KEY}"); _ = TryResolveSystemType(stableTypeId, systemReader.context, out _); @@ -485,17 +516,17 @@ internal static void ReconcilePrefabConnections( ArgumentNullException.ThrowIfNull(scene); ArgumentNullException.ThrowIfNull(context); IEnumerable candidates = restoredRoot is null - ? scene.GetOwnedObjects() - : EnumerateRestoredObjects(restoredRoot, includeRestoredRoot); + ? scene.GetOwnedObjects() + : EnumerateRestoredObjects(restoredRoot, includeRestoredRoot); GameObject[] roots = candidates - .Where(gameObject => - gameObject.prefabInstance?.isRoot == true && - gameObject.prefabConnection is not null) + .Where(gameObject => gameObject.prefabInstance?.isRoot == true && gameObject.prefabConnection is not null) .ToArray(); for (int i = 0; i < roots.Length; i++) { if (!roots[i].isRuntimeValid || roots[i].prefabConnection is null) + { continue; + } PrefabOverrideProcessor.Reconcile(roots[i].prefabConnection!, roots[i], context); } } @@ -506,18 +537,24 @@ bool includeRoot ) { var pending = new Stack(); if (includeRoot) + { pending.Push(root.transform); + } else { foreach (Transform child in root.transform.children) + { pending.Push(child); + } } while (pending.Count != 0) { Transform current = pending.Pop(); yield return current.gameObject; foreach (Transform child in current.children) + { pending.Push(child); + } } } @@ -531,10 +568,14 @@ internal static void ValidateObjects(IReadOnlyList objectRe Guid objectId = objectReader.Read(C_OBJECT_ID_KEY); EnsurePersistentId(objectId, $"{objectReader.path}.{C_OBJECT_ID_KEY}"); if (!objectIds.Add(objectId)) + { throw new InvalidDataException($"Duplicate GameObject local identity '{objectId}' at '{objectReader.path}'."); + } _ = objectReader.Read(C_NAME_KEY); if (objectReader.Contains(C_TAG_KEY)) + { _ = GameObject.NormalizeTag(objectReader.Read(C_TAG_KEY)); + } _ = objectReader.Read(C_ACTIVE_SELF_KEY); _ = objectReader.Read(C_PARENT_ID_KEY); _ = objectReader.Read(C_SIBLING_INDEX_KEY); @@ -543,18 +584,20 @@ internal static void ValidateObjects(IReadOnlyList objectRe { if (!objectReader.Contains(C_PREFAB_SOURCE_ASSET_KEY)) { - throw new InvalidDataException( - $"Prefab source token is missing at '{objectReader.path}'."); + throw new InvalidDataException($"Prefab source token is missing at '{objectReader.path}'."); } EnsurePersistentId( objectReader.Read(C_PREFAB_SOURCE_ASSET_ID_KEY), - $"{objectReader.path}.{C_PREFAB_SOURCE_ASSET_ID_KEY}"); + $"{objectReader.path}.{C_PREFAB_SOURCE_ASSET_ID_KEY}" + ); EnsurePersistentId( objectReader.Read(C_PREFAB_SOURCE_OBJECT_ID_KEY), - $"{objectReader.path}.{C_PREFAB_SOURCE_OBJECT_ID_KEY}"); + $"{objectReader.path}.{C_PREFAB_SOURCE_OBJECT_ID_KEY}" + ); EnsurePersistentId( objectReader.Read(C_PREFAB_INSTANCE_ROOT_ID_KEY), - $"{objectReader.path}.{C_PREFAB_INSTANCE_ROOT_ID_KEY}"); + $"{objectReader.path}.{C_PREFAB_INSTANCE_ROOT_ID_KEY}" + ); _ = objectReader.Read(C_PREFAB_IS_VARIANT_KEY); _ = objectReader.Read(C_PREFAB_IS_MISSING_KEY); _ = objectReader.Read(C_PREFAB_OVERRIDE_COUNT_KEY); @@ -579,12 +622,16 @@ internal static void ValidateObjects(IReadOnlyList objectRe Guid componentId = componentReader.Read(C_COMPONENT_ID_KEY); EnsurePersistentId(componentId, $"{componentReader.path}.{C_COMPONENT_ID_KEY}"); if (!componentIds.Add(componentId)) + { throw new InvalidDataException($"Duplicate GameComponent local identity '{componentId}' at '{componentReader.path}'."); + } Guid stableTypeId = componentReader.Read(C_STABLE_TYPE_ID_KEY); EnsurePersistentId(stableTypeId, $"{componentReader.path}.{C_STABLE_TYPE_ID_KEY}"); - if (TryResolveComponentType(stableTypeId, componentReader.context, out Type? componentType) && - componentType == typeof(Transform)) + if (TryResolveComponentType(stableTypeId, componentReader.context, out Type? componentType) + && componentType == typeof(Transform) + ) { transformCount++; + } EnsureTypeName(componentReader.Read(C_TYPE_NAME_KEY), componentReader.path); _ = componentReader.Read(C_STATE_KEY); _ = ReadStateDependencies(componentReader); @@ -593,7 +640,8 @@ internal static void ValidateObjects(IReadOnlyList objectRe if (transformCount != 1) { throw new InvalidDataException( - $"Scene graph object '{objectId}' must contain exactly one Transform, but found '{transformCount}'."); + $"Scene graph object '{objectId}' must contain exactly one Transform, but found '{transformCount}'." + ); } } @@ -603,7 +651,8 @@ internal static void ValidateObjects(IReadOnlyList objectRe if (parentId != Guid.Empty && !objectIds.Contains(parentId)) { throw new InvalidDataException( - $"Parent object '{parentId}' at '{objectReaders[objectIndex].path}' is outside the serialized boundary."); + $"Parent object '{parentId}' at '{objectReaders[objectIndex].path}' is outside the serialized boundary." + ); } } } @@ -611,11 +660,11 @@ internal static void ValidateObjects(IReadOnlyList objectRe private static Guid GetSourceId( IReadOnlyDictionary sourceIds, EngineObject engineObject - ) - => sourceIds.TryGetValue(engineObject, out Guid sourceId) - ? sourceId - : throw new InvalidOperationException( - $"Engine object '{engineObject.identity.persistentId}' has no source-local identity."); + ) => sourceIds.TryGetValue(engineObject, out Guid sourceId) + ? sourceId + : throw new InvalidOperationException( + $"Engine object '{engineObject.identity.persistentId}' has no source-local identity." + ); private static void WriteMissingReferenceAliases( SerializationWriter writer, @@ -633,12 +682,15 @@ IReadOnlyDictionary sourceIds var targetByPersistentId = sourceIds.Keys.ToDictionary( static engineObject => engineObject.identity.persistentId, - engineObject => sourceIds[engineObject]); + engineObject => sourceIds[engineObject] + ); var aliases = new Dictionary(); foreach ((Guid persistentId, Guid sourceId) in targetByPersistentId) { if (persistentId != sourceId) + { aliases[persistentId] = sourceId; + } } for (int i = 0; i < missing.Length; i++) { @@ -650,9 +702,9 @@ IReadOnlyDictionary sourceIds }; foreach ((Guid alias, Guid runtimePersistentId) in retained) { - if (targetByPersistentId.TryGetValue(runtimePersistentId, out Guid targetSourceId) && - alias != targetSourceId) - { + if (targetByPersistentId.TryGetValue(runtimePersistentId, out Guid targetSourceId) + && alias != targetSourceId + ) { aliases[alias] = targetSourceId; } } @@ -670,7 +722,9 @@ internal static IReadOnlyList> ReadMissingReferenceAlia Guid[] targets = rootReader.Read(C_MISSING_REFERENCE_TARGET_IDS_KEY); var result = new KeyValuePair[aliases.Length]; for (int i = 0; i < aliases.Length; i++) + { result[i] = new KeyValuePair(aliases[i], targets[i]); + } return result; } @@ -689,9 +743,13 @@ IReadOnlyList missingPlaceholders for (int i = 0; i < missingPlaceholders.Count; i++) { if (missingPlaceholders[i] is MissingGameComponent component) + { component.SetReferenceAliases(retained); + } else if (missingPlaceholders[i] is MissingGameSystem system) + { system.SetReferenceAliases(retained); + } } } @@ -700,11 +758,17 @@ internal static void ValidateMissingReferenceAliases(SerializationReader reader) Guid[] aliases = reader.Read(C_MISSING_REFERENCE_SOURCE_IDS_KEY); Guid[] targets = reader.Read(C_MISSING_REFERENCE_TARGET_IDS_KEY); if (aliases.Length != targets.Length) + { throw new InvalidDataException($"Missing scene reference alias arrays disagree at '{reader.path}'."); + } if (aliases.Any(static value => value == Guid.Empty) || targets.Any(static value => value == Guid.Empty)) + { throw new InvalidDataException($"Missing scene reference aliases contain an empty identity at '{reader.path}'."); + } if (aliases.Distinct().Count() != aliases.Length) + { throw new InvalidDataException($"Missing scene reference aliases contain duplicates at '{reader.path}'."); + } } private static void WritePrefabConnection( @@ -728,7 +792,8 @@ GameScene scene GameComponent component = scene.FindComponent(pair.Value)!; mappingWriter.Write(C_PREFAB_MAPPING_SOURCE_ID_KEY, pair.Key); mappingWriter.Write(C_PREFAB_MAPPING_INSTANCE_ID_KEY, GetSourceId(serializedIds, component)); - }); + } + ); writer.WriteObjectArray( C_PREFAB_PROPERTY_OVERRIDES_KEY, overrides.properties, @@ -741,7 +806,8 @@ GameScene scene overrideWriter.Write(C_PREFAB_PROPERTY_NAME_KEY, property.propertyName); overrideWriter.Write(C_PREFAB_PROPERTY_VALUE_KEY, property.value); overrideWriter.Write(C_PREFAB_OVERRIDE_ORPHANED_KEY, property.isOrphaned); - }); + } + ); writer.WriteObjectArray( C_PREFAB_STRUCTURE_OVERRIDES_KEY, overrides.structures, @@ -753,7 +819,8 @@ GameScene scene overrideWriter.Write(C_PREFAB_MAPPING_SOURCE_ID_KEY, structure.sourceObjectId); overrideWriter.Write(C_PREFAB_STRUCTURE_KIND_KEY, (int)structure.kind); overrideWriter.Write(C_PREFAB_OVERRIDE_ORPHANED_KEY, structure.isOrphaned); - }); + } + ); writer.Write(C_PREFAB_REMOVED_OBJECTS_KEY, overrides.removedObjects.ToArray()); writer.Write(C_PREFAB_REMOVED_COMPONENTS_KEY, overrides.removedComponents.ToArray()); writer.Write(C_PREFAB_ADDED_OBJECTS_KEY, overrides.addedObjects.ToArray()); @@ -764,39 +831,48 @@ private static PrefabOverrideSet ReadPrefabOverrides(SerializationReader reader) { var result = new PrefabOverrideSet(); foreach (SerializationReader propertyReader in - reader.ReadObjectArray(C_PREFAB_PROPERTY_OVERRIDES_KEY)) - { - result.SetProperty(new PrefabPropertyOverride( - propertyReader.Read(C_PREFAB_MAPPING_SOURCE_ID_KEY), - propertyReader.Read(C_PREFAB_PROPERTY_NAME_KEY), - propertyReader.Read(C_PREFAB_PROPERTY_VALUE_KEY), - propertyReader.Read(C_PREFAB_OVERRIDE_ORPHANED_KEY))); + reader.ReadObjectArray(C_PREFAB_PROPERTY_OVERRIDES_KEY) + ) { + result.SetProperty( + new PrefabPropertyOverride( + propertyReader.Read(C_PREFAB_MAPPING_SOURCE_ID_KEY), + propertyReader.Read(C_PREFAB_PROPERTY_NAME_KEY), + propertyReader.Read(C_PREFAB_PROPERTY_VALUE_KEY), + propertyReader.Read(C_PREFAB_OVERRIDE_ORPHANED_KEY) + ) + ); } foreach (SerializationReader structureReader in - reader.ReadObjectArray(C_PREFAB_STRUCTURE_OVERRIDES_KEY)) - { + reader.ReadObjectArray(C_PREFAB_STRUCTURE_OVERRIDES_KEY) + ) { result.SetStructure( structureReader.Read(C_PREFAB_MAPPING_SOURCE_ID_KEY), (PrefabObjectOverrideKind)structureReader.Read(C_PREFAB_STRUCTURE_KIND_KEY), - structureReader.Read(C_PREFAB_OVERRIDE_ORPHANED_KEY)); + structureReader.Read(C_PREFAB_OVERRIDE_ORPHANED_KEY) + ); } foreach (Guid sourceId in reader.Read(C_PREFAB_REMOVED_OBJECTS_KEY)) + { result.MarkObjectRemoved(sourceId); + } foreach (Guid sourceId in reader.Read(C_PREFAB_REMOVED_COMPONENTS_KEY)) + { result.MarkComponentRemoved(sourceId); + } foreach (Guid instanceId in reader.Read(C_PREFAB_ADDED_OBJECTS_KEY)) + { result.MarkObjectAdded(instanceId); + } foreach (Guid instanceId in reader.Read(C_PREFAB_ADDED_COMPONENTS_KEY)) + { result.MarkComponentAdded(instanceId); + } return result; } private static bool IsTransform(SerializationReader reader) - => TryResolveComponentType( - reader.Read(C_STABLE_TYPE_ID_KEY), - reader.context, - out Type? type) && - type == typeof(Transform); + => TryResolveComponentType(reader.Read(C_STABLE_TYPE_ID_KEY), reader.context, out Type? type) + && type == typeof(Transform); private static bool TryResolveComponentType( Guid stableTypeId, @@ -804,12 +880,15 @@ private static bool TryResolveComponentType( out Type? componentType ) { if (!TryResolve(new TypeRef(stableTypeId), context, out componentType)) + { return false; + } Type resolved = componentType!; if (!typeof(GameComponent).IsAssignableFrom(resolved) || resolved.IsAbstract) { throw new InvalidDataException( - $"Stable type id '{stableTypeId}' resolves to invalid component type '{resolved.FullName}'."); + $"Stable type id '{stableTypeId}' resolves to invalid component type '{resolved.FullName}'." + ); } return true; } @@ -820,10 +899,14 @@ private static bool TryResolveSystemType( out Type? systemType ) { if (!TryResolve(new TypeRef(stableTypeId), context, out systemType)) + { return false; + } Type resolved = systemType!; if (!typeof(GameSystem).IsAssignableFrom(resolved) || resolved.IsAbstract) + { throw new InvalidDataException($"Stable type id '{stableTypeId}' resolves to invalid system '{resolved.FullName}'."); + } return true; } @@ -860,9 +943,10 @@ IReadOnlyDictionary sourceIds catch (Exception exception) { throw new InvalidOperationException( - $"Failed to serialize GameComponent '{component.GetType().FullName}' on " + - $"GameObject '{gameObject.name}' at '{writer.path}'. {exception.Message}", - exception); + $"Failed to serialize GameComponent '{component.GetType().FullName}' on " + + $"GameObject '{gameObject.name}' at '{writer.path}'. {exception.Message}", + exception + ); } } @@ -871,9 +955,9 @@ private static AssetDependency[] WriteState( ISerializable value ) { SerializationContext outerContext = writer.context; - bool includeLastKnownPaths = !outerContext.TryGet(out AssetDependencyCollection? outerDependencies) || - outerDependencies is null || - outerDependencies.includeLastKnownPaths; + bool includeLastKnownPaths = !outerContext.TryGet(out AssetDependencyCollection? outerDependencies) + || outerDependencies is null + || outerDependencies.includeLastKnownPaths; var dependencies = new AssetDependencyCollection(includeLastKnownPaths); writer.WritePropertiesData(C_STATE_KEY, value, outerContext.With(dependencies)); return dependencies.dependencies.ToArray(); @@ -899,7 +983,8 @@ IReadOnlyList dependencies dependency.type.stableId, dependency.lastKnownPath, typeof(AssetObject), - "scene.state.dependencies"); + "scene.state.dependencies" + ); } writer.Write(C_STATE_DEPENDENCY_ASSETS_KEY, assets); } @@ -911,14 +996,16 @@ private static AssetDependency[] ReadStateDependencies(SerializationReader reade if (dependencies.Length != assets.Length) { throw new InvalidDataException( - $"Scene state dependency descriptors and assets disagree at '{reader.path}'."); + $"Scene state dependency descriptors and assets disagree at '{reader.path}'." + ); } for (int i = 0; i < dependencies.Length; i++) { if (dependencies[i].persistentId != assets[i].identity.persistentId) { throw new InvalidDataException( - $"Scene state dependency '{dependencies[i].persistentId}' does not match its asset token at '{reader.path}'."); + $"Scene state dependency '{dependencies[i].persistentId}' does not match its asset token at '{reader.path}'." + ); } } return dependencies; @@ -929,7 +1016,9 @@ private static void EnsurePersistentId( string path ) { if (persistentId == Guid.Empty) + { throw new InvalidDataException($"Persistent or local identity at '{path}' cannot be empty."); + } } private static void EnsureTypeName( @@ -937,7 +1026,8 @@ private static void EnsureTypeName( string path ) { if (string.IsNullOrWhiteSpace(typeName)) + { throw new InvalidDataException($"Scene element type name at '{path}' cannot be empty."); + } } - } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs index df1b197e8..47386c4ca 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs @@ -19,7 +19,9 @@ IReadOnlyList systems m_objects = objects; // Systems have a separate lifecycle owner; the structural cache must not retain them. if (systems.Count == 0) + { return; + } m_systems = new Dictionary(systems.Count, ReferenceEqualityComparer.Instance); for (int index = 0; index < systems.Count; index++) { @@ -49,9 +51,13 @@ public bool TryGetValue( out Guid value ) { if (m_objects.TryGetValue(key, out value)) + { return true; + } if (m_systems is not null) + { return m_systems.TryGetValue(key, out value); + } value = default; return false; } @@ -60,10 +66,16 @@ out Guid value public IEnumerator> GetEnumerator() { foreach (KeyValuePair entry in m_objects) + { yield return entry; + } if (m_systems is not null) + { foreach (KeyValuePair entry in m_systems) + { yield return entry; + } + } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); @@ -71,12 +83,16 @@ public IEnumerator> GetEnumerator() private IEnumerable EnumerateKeys() { foreach (KeyValuePair entry in this) + { yield return entry.Key; + } } private IEnumerable EnumerateValues() { foreach (KeyValuePair entry in this) + { yield return entry.Value; + } } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs index 1b98620ee..f807987ad 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs @@ -16,23 +16,32 @@ internal sealed class ScenePropertyReferenceScope : SceneReferenceScope internal ScenePropertyReferenceScope( GameScene scene, IReadOnlyDictionary? aliases = null - ) : base(scene) { + ) : base(scene) + { m_identities = IdentityAllocator.current; - if (scene.identity.runtimeIdentity is not { } owner || owner.domainId != m_identities.domainId || - scene.isDestroyed || !ReferenceEquals(m_identities.Get(owner), scene)) + if (scene.identity.runtimeIdentity is not { } owner || owner.domainId != m_identities.domainId + || scene.isDestroyed || !ReferenceEquals(m_identities.Get(owner), scene) + ) { throw new InvalidOperationException("Scene property serialization requires its current owning identity domain."); + } m_sceneIdentity = owner; if (aliases is not { Count: > 0 }) + { return; + } m_aliases = new Dictionary(aliases.Count); foreach ((Guid alias, Guid targetId) in aliases) { EngineObject? target = m_identities.Get(targetId); if (target is null || !BelongsToScene(target)) + { throw new InvalidOperationException($"Scene reference alias '{alias}' targets missing object '{targetId}'."); + } EngineObject? previous = m_identities.Get(alias); if (previous is not null && BelongsToScene(previous) && !ReferenceEquals(previous, target)) + { throw new InvalidOperationException($"Duplicate scene graph local identity '{alias}'."); + } m_aliases.Add(alias, targetId); } } @@ -46,10 +55,12 @@ protected override bool TryGetSourceId( out Guid sourceId ) { sourceId = default; - if (!HasCurrentOwner() || engineObject.identity.runtimeIdentity is not { } identity || - identity.domainId != m_identities.domainId || !ReferenceEquals(m_identities.Get(identity), engineObject) || - !BelongsToScene(engineObject)) + if (!HasCurrentOwner() || engineObject.identity.runtimeIdentity is not { } identity + || identity.domainId != m_identities.domainId || !ReferenceEquals(m_identities.Get(identity), engineObject) + || !BelongsToScene(engineObject) + ) { return false; + } sourceId = engineObject.identity.persistentId; return true; } @@ -64,18 +75,22 @@ out EngineObject? engineObject ) { engineObject = null; if (!HasCurrentOwner()) + { return false; + } Guid target = m_aliases is not null && m_aliases.TryGetValue(sourceId, out Guid alias) ? alias : sourceId; EngineObject? candidate = m_identities.Get(target); if (candidate is null || !BelongsToScene(candidate)) + { return false; + } engineObject = candidate; return true; } private bool HasCurrentOwner() - => IdentityAllocator.hasCurrent && ReferenceEquals(IdentityAllocator.current, m_identities) && - !scene.isDestroyed && ReferenceEquals(m_identities.Get(m_sceneIdentity), scene); + => IdentityAllocator.hasCurrent && ReferenceEquals(IdentityAllocator.current, m_identities) + && !scene.isDestroyed && ReferenceEquals(m_identities.Get(m_sceneIdentity), scene); private bool BelongsToScene(EngineObject value) => !value.isDestroyed && value switch diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneReferenceScope.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneReferenceScope.cs index 91ca42435..b32cf80fd 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneReferenceScope.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneReferenceScope.cs @@ -32,13 +32,13 @@ protected SceneReferenceScope( } internal static SceneReferenceScope current => C_CURRENT.current; + /// /// Gets the Scene that owns the references admitted by this boundary. /// protected GameScene scene { get; } - internal static bool TryGetCurrent(out SceneReferenceScope? references) - => C_CURRENT.TryGet(out references); + internal static bool TryGetCurrent(out SceneReferenceScope? references) => C_CURRENT.TryGet(out references); internal static IDisposable Suspend() => C_CURRENT.Suspend(); @@ -52,23 +52,27 @@ string path if (engineObject.isDestroyed || !TryGetSourceId(engineObject, out Guid sourceId)) { throw new InvalidOperationException( - $"Reference to '{engineObject.GetType().FullName}' with identity " + - $"'{engineObject.identity.persistentId}' at '{path}' is outside the serialized graph boundary" + - (m_captureRoot is null - ? "." - : $" rooted at GameObject '{m_captureRoot.name}' ({m_captureRoot.identity.persistentId}).")); + $"Reference to '{engineObject.GetType().FullName}' with identity " + + $"'{engineObject.identity.persistentId}' at '{path}' is outside the serialized graph boundary" + + (m_captureRoot is null + ? "." + : $" rooted at GameObject '{m_captureRoot.name}' ({m_captureRoot.identity.persistentId}).") + ); } GameScene ownerScene = engineObject switch { GameObject gameObject => gameObject.scene, GameComponent component => component.gameObject.scene, GameSystem system => system.ownerScene - ?? throw new InvalidOperationException($"Detached GameSystem reference at '{path}' cannot be serialized."), + ?? throw new InvalidOperationException($"Detached GameSystem reference at '{path}' cannot be serialized."), _ => throw new InvalidOperationException( - $"Engine object type '{engineObject.GetType().FullName}' cannot be serialized as a scene reference at '{path}'.") + $"Engine object type '{engineObject.GetType().FullName}' cannot be serialized as a scene reference at '{path}'." + ) }; if (!ReferenceEquals(ownerScene, scene)) + { throw new InvalidOperationException($"Cross-scene object reference at '{path}' cannot be serialized."); + } EngineReferenceKind kind = engineObject switch { GameObject => EngineReferenceKind.GameObject, @@ -85,12 +89,15 @@ internal EngineObject Resolve( string path ) { if (!TryResolve(token.sourceId, out EngineObject? engineObject) || engineObject is null) + { throw new InvalidOperationException($"Scene graph reference '{token.sourceId}' at '{path}' could not be resolved."); + } if (!expectedType.IsInstanceOfType(engineObject)) { throw new InvalidOperationException( - $"Scene graph reference '{token.sourceId}' at '{path}' resolves to " + - $"'{engineObject.GetType().FullName}', expected '{expectedType.FullName}'."); + $"Scene graph reference '{token.sourceId}' at '{path}' resolves to " + + $"'{engineObject.GetType().FullName}', expected '{expectedType.FullName}'." + ); } return engineObject; } diff --git a/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs b/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs index 8870b8345..005fc6458 100644 --- a/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Scene; @@ -55,11 +54,15 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (target is not ISerializable serializable) + { throw new ArgumentException($"Scene object '{target.GetType().FullName}' is not serializable.", nameof(target)); + } ScenePropertyReferenceScope references = CreateReferences(ResolveScene(target)); SerializationContext context = AssetSerializationContext.Create(assets); using (references.Enter()) + { return serialization.CapturePropertyData(serializable, propertyName, context); + } } /// @@ -92,11 +95,15 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (target is not ISerializable serializable) + { throw new ArgumentException($"Scene object '{target.GetType().FullName}' is not serializable.", nameof(target)); + } ScenePropertyReferenceScope references = CreateReferences(ResolveScene(target)); SerializationContext context = AssetSerializationContext.Create(assets); using (references.Enter()) + { return serialization.CapturePropertiesData(serializable, context); + } } /// @@ -123,11 +130,15 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (target is not ISerializable serializable) + { throw new ArgumentException($"Scene object '{target.GetType().FullName}' is not serializable.", nameof(target)); + } ScenePropertyReferenceScope references = CreateReferences(ResolveScene(target)); SerializationContext context = AssetSerializationContext.Create(assets); using (references.Enter()) + { return serialization.CaptureProperties(serializable, context); + } } /// @@ -168,11 +179,15 @@ public static SerializationPropertyRestoreResult RestoreProperties( ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (target is not ISerializable serializable) + { throw new ArgumentException($"Scene object '{target.GetType().FullName}' is not serializable.", nameof(target)); + } ScenePropertyReferenceScope references = CreateReferences(ResolveScene(target)); SerializationContext context = AssetSerializationContext.Create(assets); using (references.Enter()) + { return serialization.RestorePropertiesData(serializable, data, mode, context); + } } internal static ScenePropertyReferenceScope CreateReferences( @@ -183,7 +198,9 @@ internal static ScenePropertyReferenceScope CreateReferences( internal static GameScene ResolveScene(EngineObject target) { if (target.isDestroyed) + { throw new InvalidOperationException($"Destroyed scene object '{target.identity.persistentId}' cannot be serialized."); + } return target switch { GameScene scene when scene.isLoaded => scene, @@ -191,8 +208,8 @@ internal static GameScene ResolveScene(EngineObject target) GameComponent component when !component.isDestroyed => component.gameObject.scene, GameSystem system when system.ownerScene is { isLoaded: true } owner => owner, _ => throw new InvalidOperationException( - $"Scene object '{target.identity.persistentId}' is not owned by a loaded scene.") + $"Scene object '{target.identity.persistentId}' is not owned by a loaded scene." + ) }; } - } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneReloadStateTransfer.cs b/src/content/scene/Inno.Scene/Serialization/SceneReloadStateTransfer.cs index 098123d90..2c1b671e9 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneReloadStateTransfer.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneReloadStateTransfer.cs @@ -1,13 +1,12 @@ -using Inno.Core.Diagnostics; -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.Linq; - using Inno.Assets; -using Inno.Extensibility.Types; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; using Inno.References; namespace Inno.Scene; @@ -35,11 +34,12 @@ List scenes m_scenes = scenes; } - internal IReadOnlyList retiredObjects => m_scenes - .SelectMany(static scene => scene.states) - .Where(state => m_context.IsRetired(state.activeType)) - .Select(static state => (object)state.target) - .ToArray(); + internal IReadOnlyList retiredObjects + => m_scenes + .SelectMany(static scene => scene.states) + .Where(state => m_context.IsRetired(state.activeType)) + .Select(static state => (object)state.target) + .ToArray(); internal IReadOnlyList diagnostics => m_diagnostics; @@ -63,15 +63,21 @@ IAssetReferenceResolver assets .ToArray(); var sourceIds = new Dictionary(ReferenceEqualityComparer.Instance); foreach (EngineObject target in engineObjects) + { sourceIds.Add(target, target.identity.persistentId); + } var references = new SceneGraphReferenceMap(scene, sourceIds); var states = new List(); using (references.Enter()) { foreach (GameComponent component in structure.objects.SelectMany(static entry => entry.components)) + { states.Add(CaptureState(component, context.previous, serialization, assets)); + } foreach (GameSystem system in scene.GetSystems()) + { states.Add(CaptureState(system, context.previous, serialization, assets)); + } } ValidateMultiplicity(scene, structure, context); @@ -86,7 +92,9 @@ internal void PrepareForActivation() foreach (ObjectState state in RetiredStates()) { if (state.target is ISceneLifecycleObject lifecycle) + { SceneLifecycle.DisableForReload(lifecycle); + } } } @@ -94,45 +102,49 @@ internal void Apply() { EnsureActive(); if (m_applied) + { return; + } foreach (SceneState sceneState in m_scenes) { foreach (ObjectState state in sceneState.states) { Type? replacementType = ResolveCandidateType(state, m_context); bool retired = m_context.IsRetired(state.activeType); - bool recovering = state.target is MissingGameComponent or MissingGameSystem && - replacementType is not null; + bool recovering = state.target is MissingGameComponent or MissingGameSystem + && replacementType is not null; if (!retired && !recovering) + { continue; + } Type effectiveType = replacementType ?? (state.target is GameSystem - ? typeof(MissingGameSystem) - : typeof(MissingGameComponent)); + ? typeof(MissingGameSystem) + : typeof(MissingGameComponent)); TypeRef replacementTypeRef = m_context.candidate.GetTypeRef(effectiveType); EngineObject replacement = CreateReplacement(state, effectiveType); if (replacement is not MissingGameComponent and not MissingGameSystem) + { CopyLifecycle(state.target, replacement); + } if (state.target is GameComponent previousComponent) { sceneState.scene.ReplaceComponentForReload( previousComponent, (GameComponent)replacement, - replacementTypeRef.runtimeId); + replacementTypeRef.runtimeId + ); } else { sceneState.scene.ReplaceSystemForReload( (GameSystem)state.target, (GameSystem)replacement, - replacementTypeRef.runtimeId); + replacementTypeRef.runtimeId + ); } state.currentTarget = replacement; - m_replacements.Add(new Replacement( - sceneState.scene, - state.target, - replacement, - state.activeType)); + m_replacements.Add(new Replacement(sceneState.scene, state.target, replacement, state.activeType)); } RestoreState(sceneState, useCurrentTargets: true); } @@ -142,7 +154,9 @@ internal void Apply() internal void RollbackStructure() { if (m_finished) + { return; + } for (int i = m_replacements.Count - 1; i >= 0; i--) { Replacement replacement = m_replacements[i]; @@ -151,20 +165,24 @@ internal void RollbackStructure() replacement.scene.ReplaceComponentForReload( (GameComponent)replacement.current, previousComponent, - replacement.previousType.runtimeId); + replacement.previousType.runtimeId + ); } else { replacement.scene.ReplaceSystemForReload( (GameSystem)replacement.current, (GameSystem)replacement.previous, - replacement.previousType.runtimeId); + replacement.previousType.runtimeId + ); } } foreach (SceneState sceneState in m_scenes) { foreach (ObjectState state in sceneState.states) + { state.currentTarget = state.target; + } } m_replacements.Clear(); m_applied = false; @@ -192,7 +210,9 @@ internal void RestorePreviousState() RestorePreviousLifecycleState(sceneState, ref failures); } if (failures is not null) + { throw new AggregateException("Previous scene state restoration was incomplete.", failures); + } } internal void Complete() @@ -204,9 +224,13 @@ internal void Complete() try { if (replacement.previous is GameComponent component && !component.isDestroyed) + { component.Detach(); + } else if (replacement.previous is GameSystem system && !system.isDestroyed) + { system.Detach(); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -215,22 +239,27 @@ internal void Complete() catch (Exception exception) { failures.Add(exception); - m_diagnostics.Add(new SceneReloadDiagnostic( - "INNOHR0004", - DiagnosticSeverity.Error, - $"Retired scene element '{replacement.previous.GetType().FullName}' failed during cleanup: {exception.Message}", - replacement.scene.identity.persistentId, - replacement.previous.identity.persistentId, - string.Empty, - replacement.previous.GetType().FullName ?? replacement.previous.GetType().Name, - string.Empty)); + m_diagnostics.Add( + new SceneReloadDiagnostic( + "INNOHR0004", + DiagnosticSeverity.Error, + $"Retired scene element '{replacement.previous.GetType().FullName}' failed during cleanup: {exception.Message}", + replacement.scene.identity.persistentId, + replacement.previous.identity.persistentId, + string.Empty, + replacement.previous.GetType().FullName ?? replacement.previous.GetType().Name, + string.Empty + ) + ); } } m_replacements.Clear(); m_scenes.Clear(); m_finished = true; if (failures.Count > 0) + { throw new AggregateException("Retired scene elements failed cleanup after all elements were attempted.", failures); + } } internal IEnumerable CaptureRecoveryStates() @@ -242,23 +271,39 @@ internal IEnumerable CaptureRecoveryStates() Guid elementId = state.target.identity.persistentId; yield return new SerializedMissingState( new ReferenceKey(elementId, "element"), - new ReferenceDescriptor(SceneElementReferenceResolver.id, elementId, - state.logicalType.stableId, state.typeName), state.data); + new ReferenceDescriptor( + SceneElementReferenceResolver.id, + elementId, + state.logicalType.stableId, + state.typeName + ), + state.data + ); foreach (AssetDependency dependency in state.dependencies.Distinct()) { yield return new SerializedMissingState( new ReferenceKey(elementId, $"assets/{dependency.persistentId:D}"), - new ReferenceDescriptor(AssetReferenceProtocol.id, dependency.persistentId, - dependency.type.stableId, lastKnownPath: dependency.lastKnownPath), []); + new ReferenceDescriptor( + AssetReferenceProtocol.id, + dependency.persistentId, + dependency.type.stableId, + lastKnownPath: dependency.lastKnownPath + ), + [] + ); } } } } void IGenerationChange.PrepareForActivation() => PrepareForActivation(); + void IGenerationChange.Apply() => Apply(); + void IGenerationChange.RollbackStructure() => RollbackStructure(); + void IGenerationChange.RestorePreviousState() => RestorePreviousState(); + void IGenerationChange.Complete() => Complete(); void IReferenceRecoveryParticipant.Validate(IReadOnlyList changes) @@ -267,7 +312,9 @@ void IReferenceRecoveryParticipant.Validate(IReadOnlyList? failures ) { foreach (ObjectState state in sceneState.states) { - if (state.target is not ISceneLifecycleObject lifecycle || - lifecycle.lifecycleWasEnabled == state.lifecycleWasEnabled) - { + if (state.target is not ISceneLifecycleObject lifecycle + || lifecycle.lifecycleWasEnabled == state.lifecycleWasEnabled + ) { continue; } @@ -327,9 +378,13 @@ ref List? failures try { if (state.lifecycleWasEnabled) + { lifecycle.DispatchEnable(); + } else + { lifecycle.DispatchDisable(); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -338,9 +393,12 @@ ref List? failures catch (Exception exception) { failures ??= []; - failures.Add(new InvalidOperationException( - $"Lifecycle compensation failed for '{state.target.GetType().FullName}'.", - exception)); + failures.Add( + new InvalidOperationException( + $"Lifecycle compensation failed for '{state.target.GetType().FullName}'.", + exception + ) + ); } } } @@ -350,28 +408,25 @@ private EngineObject CreateReplacement( Type replacementType ) { if (replacementType == typeof(MissingGameComponent)) - return new MissingGameComponent( - state.logicalType, - state.typeName, - state.data, - state.dependencies); + { + return new MissingGameComponent(state.logicalType, state.typeName, state.data, state.dependencies); + } if (replacementType == typeof(MissingGameSystem)) - return new MissingGameSystem( - state.logicalType, - state.typeName, - state.data, - state.dependencies); + { + return new MissingGameSystem(state.logicalType, state.typeName, state.data, state.dependencies); + } try { return state.target is GameComponent - ? ComponentFactory.Create(replacementType, m_context.candidate) - : (EngineObject)m_context.candidate.CreateInstance(replacementType); + ? ComponentFactory.Create(replacementType, m_context.candidate) + : (EngineObject)m_context.candidate.CreateInstance(replacementType); } catch (Exception exception) { throw new InvalidOperationException( $"Hot-reload replacement '{replacementType.FullName}' requires a parameterless constructor.", - exception); + exception + ); } } @@ -408,19 +463,26 @@ TypeCacheReloadContext context { ActiveTypeInfo type = ResolveActiveType(component, context); if (!groups.TryGetValue(type.typeRef, out MultiplicityGroup? group)) + { groups.Add(type.typeRef, new MultiplicityGroup(type.displayName, type.allowsMultiple)); + } else + { group.count++; + } } foreach (MultiplicityGroup group in groups.Values) { if (group.count <= 1 || group.allowsMultiple) + { continue; + } throw new InvalidOperationException( - $"Script reload would leave GameObject '{entry.gameObject.name}' " + - $"({entry.gameObject.identity.persistentId}) with {group.count} instances of unique component " + - $"'{group.displayName}'. Remove duplicate components or restore " + - $"[{nameof(AllowMultipleComponentAttribute)}] before reloading."); + $"Script reload would leave GameObject '{entry.gameObject.name}' " + + $"({entry.gameObject.identity.persistentId}) with {group.count} instances of unique component " + + $"'{group.displayName}'. Remove duplicate components or restore " + + $"[{nameof(AllowMultipleComponentAttribute)}] before reloading." + ); } } @@ -429,18 +491,25 @@ TypeCacheReloadContext context { ActiveTypeInfo type = ResolveActiveType(system, context); if (!systemGroups.TryGetValue(type.typeRef, out MultiplicityGroup? group)) + { systemGroups.Add(type.typeRef, new MultiplicityGroup(type.displayName, type.allowsMultiple)); + } else + { group.count++; + } } foreach (MultiplicityGroup group in systemGroups.Values) { if (group.count <= 1 || group.allowsMultiple) + { continue; + } throw new InvalidOperationException( - $"Script reload would leave scene '{scene.name}' ({scene.identity.persistentId}) with " + - $"{group.count} instances of unique system '{group.displayName}'. Remove duplicate systems or restore " + - $"[{nameof(AllowMultipleSystemAttribute)}] before reloading."); + $"Script reload would leave scene '{scene.name}' ({scene.identity.persistentId}) with " + + $"{group.count} instances of unique system '{group.displayName}'. Remove duplicate systems or restore " + + $"[{nameof(AllowMultipleSystemAttribute)}] before reloading." + ); } } @@ -454,14 +523,14 @@ TypeCacheReloadContext context if (target is MissingGameComponent missingComponent) { activeType = TryResolve(missingComponent.missingType, context.candidate, out Type? recovered) - ? recovered! - : typeof(MissingGameComponent); + ? recovered! + : typeof(MissingGameComponent); } else if (target is MissingGameSystem missingSystem) { activeType = TryResolve(missingSystem.missingType, context.candidate, out Type? recovered) - ? recovered! - : typeof(MissingGameSystem); + ? recovered! + : typeof(MissingGameSystem); } else { @@ -469,18 +538,16 @@ TypeCacheReloadContext context if (context.IsRetired(previousType)) { activeType = context.TryResolveReplacement(previousType, out TypeRef replacement) - ? replacement.Resolve(context.candidate) - : isSystem ? typeof(MissingGameSystem) : typeof(MissingGameComponent); + ? replacement.Resolve(context.candidate) + : isSystem ? typeof(MissingGameSystem) : typeof(MissingGameComponent); } } TypeRef activeTypeRef = context.candidate.GetTypeRef(activeType); bool allowsMultiple = activeType.IsDefined( isSystem ? typeof(AllowMultipleSystemAttribute) : typeof(AllowMultipleComponentAttribute), - inherit: !isSystem); - return new ActiveTypeInfo( - activeTypeRef, - activeType.FullName ?? activeType.Name, - allowsMultiple); + inherit: !isSystem + ); + return new ActiveTypeInfo(activeTypeRef, activeType.FullName ?? activeType.Name, allowsMultiple); } private void RestoreState( @@ -488,10 +555,12 @@ private void RestoreState( bool useCurrentTargets ) { EngineObject[] currentObjects = sceneState.engineObjects - .Select(engineObject => sceneState.states.FirstOrDefault(state => ReferenceEquals(state.target, engineObject)) - is ObjectState state - ? useCurrentTargets ? state.currentTarget : state.target - : engineObject) + .Select(engineObject => ( + sceneState.states.FirstOrDefault(state => ReferenceEquals(state.target, engineObject)) + is ObjectState state + ? useCurrentTargets ? state.currentTarget : state.target + : engineObject + )) .ToArray(); var references = new SceneGraphReferenceMap(sceneState.scene); var currentByPersistentId = new Dictionary(); @@ -509,13 +578,16 @@ is ObjectState state _ => null }; if (aliases is null) + { continue; + } foreach ((Guid alias, Guid targetPersistentId) in aliases) { if (!currentByPersistentId.TryGetValue(targetPersistentId, out EngineObject? target)) { throw new InvalidOperationException( - $"Missing scene state reference alias '{alias}' targets unavailable identity '{targetPersistentId}'."); + $"Missing scene state reference alias '{alias}' targets unavailable identity '{targetPersistentId}'." + ); } references.Register(alias, target); } @@ -527,7 +599,9 @@ is ObjectState state { ISerializable target = (ISerializable)(useCurrentTargets ? state.currentTarget : state.target); if (target is MissingGameComponent or MissingGameSystem) + { continue; + } SerializationPropertyRestoreResult result; try { @@ -535,45 +609,59 @@ is ObjectState state target, state.data, useCurrentTargets && state.target is not MissingGameComponent and not MissingGameSystem - ? SerializationPropertyRestoreMode.CollectFailures - : SerializationPropertyRestoreMode.Strict, - AssetSerializationContext.Create(m_assets)); + ? SerializationPropertyRestoreMode.CollectFailures + : SerializationPropertyRestoreMode.Strict, + AssetSerializationContext.Create(m_assets) + ); } catch (Exception exception) when (!useCurrentTargets && exception is not RetirementPendingException) { restoreFailures ??= []; - restoreFailures.Add(new InvalidOperationException( - $"Previous state restoration failed for '{target.GetType().FullName}'.", - exception)); + restoreFailures.Add( + new InvalidOperationException( + $"Previous state restoration failed for '{target.GetType().FullName}'.", + exception + ) + ); continue; } if (!useCurrentTargets) + { continue; - if (state.target is MissingGameComponent or MissingGameSystem && - (!result.success || result.ignoredCount != 0)) + } + if (state.target is MissingGameComponent or MissingGameSystem + && (!result.success || result.ignoredCount != 0) + ) { throw new InvalidOperationException( - $"Missing scene element '{state.target.identity.persistentId}' could not restore its complete preserved state."); + $"Missing scene element '{state.target.identity.persistentId}' could not restore its complete preserved state." + ); + } for (int i = 0; i < result.failures.Count; i++) { SerializationPropertyRestoreFailure failure = result.failures[i]; string previousType = GetTypeDisplayName(failure.previousPropertyType); string currentType = GetTypeDisplayName(failure.currentPropertyType); - m_diagnostics.Add(new SceneReloadDiagnostic( - "INNOHR0001", - DiagnosticSeverity.Warning, - $"Hot reload skipped '{target.GetType().FullName}.{failure.name}' because " + - $"serialized type '{previousType}' is incompatible with '{currentType}'. " + - $"The new member default value was preserved. {failure.message}", - sceneState.scene.identity.persistentId, - ((EngineObject)target).identity.persistentId, - failure.name, - previousType, - currentType)); + m_diagnostics.Add( + new SceneReloadDiagnostic( + "INNOHR0001", + DiagnosticSeverity.Warning, + $"Hot reload skipped '{target.GetType().FullName}.{failure.name}' because " + + $"serialized type '{previousType}' is incompatible with '{currentType}'. " + + $"The new member default value was preserved. {failure.message}", + sceneState.scene.identity.persistentId, + ((EngineObject)target).identity.persistentId, + failure.name, + previousType, + currentType + ) + ); } } } if (restoreFailures is not null) + { throw new AggregateException("One or more previous scene objects could not be restored.", restoreFailures); + } } private static string GetTypeDisplayName(Type type) => type.FullName ?? type.Name; @@ -585,7 +673,9 @@ private IEnumerable RetiredStates() private void EnsureActive() { if (m_finished) + { throw new InvalidOperationException("Scene hot-reload migration is already finished."); + } } private sealed record SceneState( @@ -609,8 +699,10 @@ AssetDependency[] dependencies internal string typeName { get; } = typeName; internal byte[] data { get; } = data; internal AssetDependency[] dependencies { get; } = dependencies; + internal bool lifecycleWasEnabled { get; } = target is ISceneLifecycleObject lifecycle && lifecycle.lifecycleWasEnabled; + internal EngineObject currentTarget { get; set; } = target; } @@ -643,17 +735,24 @@ TypeCacheReloadContext context Type requiredBase = state.target is GameSystem ? typeof(GameSystem) : typeof(GameComponent); Type? candidate = null; if (state.target is MissingGameComponent or MissingGameSystem) + { _ = TryResolve(state.logicalType, context.candidate, out candidate); - else if (context.IsRetired(state.activeType) && - context.TryResolveReplacement(state.activeType, out TypeRef replacement)) + } + else if (context.IsRetired(state.activeType) + && context.TryResolveReplacement(state.activeType, out TypeRef replacement) + ) { candidate = replacement.Resolve(context.candidate); + } if (candidate is null) - return null; - if (!requiredBase.IsAssignableFrom(candidate) || candidate.IsAbstract || - candidate == typeof(MissingGameComponent) || candidate == typeof(MissingGameSystem)) { + return null; + } + if (!requiredBase.IsAssignableFrom(candidate) || candidate.IsAbstract + || candidate == typeof(MissingGameComponent) || candidate == typeof(MissingGameSystem) + ) { throw new InvalidOperationException( - $"Stable type id '{state.logicalType.stableId:D}' resolves to invalid replacement '{candidate.FullName}'."); + $"Stable type id '{state.logicalType.stableId:D}' resolves to invalid replacement '{candidate.FullName}'." + ); } return candidate; } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneRestoreCompensation.cs b/src/content/scene/Inno.Scene/Serialization/SceneRestoreCompensation.cs index 69a83728b..693c7fcea 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneRestoreCompensation.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneRestoreCompensation.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.ExceptionServices; - using Inno.Core.Identity; using Inno.Scene; @@ -29,7 +28,9 @@ string description { GameObject gameObject = created[i]; if (!gameObject.isRuntimeValid) + { continue; + } try { _ = scene.DestroyObject(gameObject); @@ -43,36 +44,45 @@ string description var survivorSet = new HashSet( created.Where(static gameObject => gameObject.isRuntimeValid), - ReferenceEqualityComparer.Instance); + ReferenceEqualityComparer.Instance + ); survivorSet.UnionWith(scene.GetObjects().Where(gameObject => !existing.Contains(gameObject))); GameObject[] survivors = [.. survivorSet]; for (int i = 0; i < created.Length; i++) { GameObject gameObject = created[i]; if (!ReferenceEquals( - IdentityAllocator.current.Get(gameObject.identity.persistentId), - gameObject)) - { + IdentityAllocator.current.Get(gameObject.identity.persistentId), + gameObject + )) { continue; } if (!survivors.Contains(gameObject, ReferenceEqualityComparer.Instance)) + { survivors = [.. survivors, gameObject]; + } } if (survivors.Length != 0) { cleanupFailures ??= []; - cleanupFailures.Add(new InvalidOperationException( - $"{description} left {survivors.Length} created GameObject(s) live or identity-registered.")); + cleanupFailures.Add( + new InvalidOperationException( + $"{description} left {survivors.Length} created GameObject(s) live or identity-registered." + ) + ); } if (cleanupFailures is null) + { ExceptionDispatchInfo.Capture(restoreFailure).Throw(); + } throw new InvalidOperationException( survivors.Length == 0 - ? $"{description} failed; created objects were removed, but one or more destruction callbacks also failed." - : $"{description} failed and could not restore the exact prior scene state.", - new AggregateException([restoreFailure, .. cleanupFailures])); + ? $"{description} failed; created objects were removed, but one or more destruction callbacks also failed." + : $"{description} failed and could not restore the exact prior scene state.", + new AggregateException([restoreFailure, .. cleanupFailures]) + ); } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs b/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs index a782395ac..b3b5c8998 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Assets; using Inno.Core.Serialization; using Inno.Scene; @@ -43,7 +42,9 @@ IAssetReferenceResolver assets ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (!root.isRuntimeValid) + { throw new InvalidOperationException("A destroyed or detached GameObject subtree cannot be captured."); + } SerializationContext context = AssetSerializationContext.Create(assets); return serialization.Serialize(new SceneSubtreeState(root), context); } @@ -90,12 +91,14 @@ int siblingIndex ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(assets); if (!scene.isLoaded || scene.isDestroyed) + { throw new InvalidOperationException("A scene subtree can only be restored into a live loaded scene."); + } if (parent is not null && !ReferenceEquals(parent.gameObject.scene, scene)) + { throw new ArgumentException("The requested parent belongs to another scene.", nameof(parent)); - var existing = new HashSet( - scene.GetObjects(), - ReferenceEqualityComparer.Instance); + } + var existing = new HashSet(scene.GetObjects(), ReferenceEqualityComparer.Instance); try { SerializationContext context = AssetSerializationContext.Create(assets) @@ -111,7 +114,8 @@ int siblingIndex exception, scene, existing, - "Scene subtree restoration"); + "Scene subtree restoration" + ); throw; } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneSubtreeStateConverter.cs b/src/content/scene/Inno.Scene/Serialization/SceneSubtreeStateConverter.cs index 9faa25916..3a35d7434 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneSubtreeStateConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneSubtreeStateConverter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; using Inno.Scene; @@ -40,7 +39,9 @@ SceneSubtreeState value EngineObject[] allObjects = GetAllObjects(scene); var sourceIds = new Dictionary(ReferenceEqualityComparer.Instance); for (int i = 0; i < allObjects.Length; i++) + { sourceIds.Add(allObjects[i], allObjects[i].identity.persistentId); + } var references = new SceneGraphReferenceMap(scene, sourceIds, root); writer.Write(C_ROOT_ID_KEY, root.identity.persistentId); @@ -51,7 +52,8 @@ SceneSubtreeState value entries, sourceIds, included.Contains, - preserveRootSiblingOrder: true); + preserveRootSiblingOrder: true + ); } } @@ -79,21 +81,22 @@ public override SceneSubtreeState Read(SerializationReader reader) var references = new SceneGraphReferenceMap(scene); EngineObject[] externalObjects = GetAllObjects(scene); for (int i = 0; i < externalObjects.Length; i++) + { references.Register(externalObjects[i].identity.persistentId, externalObjects[i]); + } RestoredSceneGraph restored = SceneGraphSerialization.RestoreObjects( scene, objectReaders, preservePersistentIds: true, references, SceneGraphSerialization.ReadMissingReferenceAliases(reader), - reader.context); + reader.context + ); if (!restored.objects.TryGetValue(rootId, out GameObject? root)) + { throw new InvalidDataException($"Scene subtree root '{rootId}' is missing."); - SceneGraphSerialization.ReconcilePrefabConnections( - scene, - reader.context, - root, - includeRestoredRoot: true); + } + SceneGraphSerialization.ReconcilePrefabConnections(scene, reader.context, root, includeRestoredRoot: true); return new SceneSubtreeState(root); } catch (Exception exception) @@ -102,15 +105,15 @@ public override SceneSubtreeState Read(SerializationReader reader) exception, scene, existing, - "Scene subtree deserialization"); + "Scene subtree deserialization" + ); throw; } } private static EngineObject[] GetAllObjects(GameScene scene) => scene.GetObjects() - .SelectMany(static gameObject => - gameObject.GetComponents().Cast().Prepend(gameObject)) + .SelectMany(static gameObject => gameObject.GetComponents().Cast().Prepend(gameObject)) .Concat(scene.GetSystems()) .ToArray(); @@ -121,6 +124,8 @@ ISet result _ = result.Add(gameObject); IReadOnlyList children = gameObject.transform.children; for (int i = 0; i < children.Count; i++) + { CollectSubtree(children[i].gameObject, result); + } } } diff --git a/src/content/scene/Inno.Scene/Serialization/SceneTypeResolutionException.cs b/src/content/scene/Inno.Scene/Serialization/SceneTypeResolutionException.cs index 5f419b06a..45b8d2b78 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneTypeResolutionException.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneTypeResolutionException.cs @@ -23,11 +23,12 @@ public sealed class SceneTypeResolutionException : Exception public SceneTypeResolutionException( Guid stableTypeId, string elementKind - ) - : base($"Scene {elementKind} stable type id '{stableTypeId}' is not loaded.") + ) : base($"Scene {elementKind} stable type id '{stableTypeId}' is not loaded.") { if (stableTypeId == Guid.Empty) + { throw new ArgumentException("A stable scene type identity is required.", nameof(stableTypeId)); + } ArgumentException.ThrowIfNullOrWhiteSpace(elementKind); this.stableTypeId = stableTypeId; this.elementKind = elementKind; diff --git a/src/content/scene/Inno.Scene/Serialization/SerializedPropertyValueCodec.cs b/src/content/scene/Inno.Scene/Serialization/SerializedPropertyValueCodec.cs index ddb43ad1d..fbb13f9c4 100644 --- a/src/content/scene/Inno.Scene/Serialization/SerializedPropertyValueCodec.cs +++ b/src/content/scene/Inno.Scene/Serialization/SerializedPropertyValueCodec.cs @@ -14,8 +14,10 @@ SerializationContext context ArgumentNullException.ThrowIfNull(componentType); ArgumentNullException.ThrowIfNull(context); const PropertyVisibility persistent = PropertyVisibility.Serialize | PropertyVisibility.Deserialize; - return context.GetRequired().GetMetadata(componentType).members - .Where(static member => (member.visibility & persistent) == persistent).ToArray(); + return context.GetRequired() + .GetMetadata(componentType).members + .Where(static member => (member.visibility & persistent) == persistent) + .ToArray(); } internal static byte[] Encode( @@ -31,7 +33,9 @@ SceneReferenceScope references object? value = member.GetValue(component); SerializationRegistry serialization = context.GetRequired(); using (references.Enter()) + { return serialization.Encode(writer => writer.Write("value", value, member.type), context); + } } internal static void Decode( diff --git a/src/content/scene/Inno.Scene/Service/ActivationService.cs b/src/content/scene/Inno.Scene/Service/ActivationService.cs index b4ff9e9a0..71111c77b 100644 --- a/src/content/scene/Inno.Scene/Service/ActivationService.cs +++ b/src/content/scene/Inno.Scene/Service/ActivationService.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; - using Inno.Scene.Components; namespace Inno.Scene; @@ -14,7 +13,9 @@ internal void SetActive( bool active ) { if (gameObject.activeSelf == active) + { return; + } gameObject.SetActiveSelfDirect(active); RecomputeSubtree(gameObject); } @@ -33,6 +34,8 @@ bool parentActive gameObject.SetActiveInHierarchyDirect(active); IReadOnlyList children = gameObject.transform.children; for (int i = 0; i < children.Count; i++) + { Recompute(children[i].gameObject, active); + } } } diff --git a/src/content/scene/Inno.Scene/Service/HierarchyService.cs b/src/content/scene/Inno.Scene/Service/HierarchyService.cs index 0308770d5..35d75a9ba 100644 --- a/src/content/scene/Inno.Scene/Service/HierarchyService.cs +++ b/src/content/scene/Inno.Scene/Service/HierarchyService.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Mathematics; using Inno.Scene.Components; @@ -35,9 +34,13 @@ internal void Unregister(Transform transform) { Transform? parent = transform.parent; if (parent is null) + { RemoveRoot(transform); + } else + { parent.RemoveChildDirect(transform); + } transform.SetParentDirect(null); revision++; } @@ -49,19 +52,28 @@ bool worldPositionStays ) { ArgumentNullException.ThrowIfNull(transform); if (ReferenceEquals(transform, parent)) + { throw new InvalidOperationException("A transform cannot parent itself."); + } if (parent is not null && parent.IsDescendantOf(transform)) + { throw new InvalidOperationException("The requested transform parent would create a hierarchy cycle."); + } if (parent is not null && !ReferenceEquals(parent.gameObject.scene, m_scene)) + { throw new InvalidOperationException("Transforms from different scenes cannot share a hierarchy."); + } if (ReferenceEquals(transform.parent, parent)) + { return; + } if (worldPositionStays && parent is not null - && MathF.Abs(Matrix.Determinant(parent.localToWorldMatrix)) < MathHelper.C_TOLERANCE) - { + && MathF.Abs(Matrix.Determinant(parent.localToWorldMatrix)) < MathHelper.C_TOLERANCE + ) { throw new InvalidOperationException( - "A transform cannot preserve world space under a parent hierarchy with zero scale."); + "A transform cannot preserve world space under a parent hierarchy with zero scale." + ); } Vector3 worldPosition = transform.worldPosition; @@ -73,15 +85,23 @@ bool worldPositionStays Transform? previousParent = transform.parent; if (previousParent is null) + { RemoveRoot(transform); + } else + { previousParent.RemoveChildDirect(transform); + } transform.SetParentDirect(parent); if (parent is null) + { Register(transform); + } else + { parent.AddChildDirect(transform); + } if (worldPositionStays) { @@ -102,7 +122,9 @@ bool worldPositionStays internal int GetSiblingIndex(Transform transform) { if (transform.parent is Transform parent) + { return parent.IndexOfChild(transform); + } return m_rootIndices.GetValueOrDefault(transform, -1); } @@ -114,7 +136,9 @@ int siblingIndex { int current = parent.IndexOfChild(transform); if (current < 0) + { throw new InvalidOperationException("Transform is missing from its parent child collection."); + } int target = Math.Clamp(siblingIndex, 0, parent.children.Count - 1); if (current != target) { @@ -126,10 +150,14 @@ int siblingIndex int rootIndex = m_rootIndices.GetValueOrDefault(transform, -1); if (rootIndex < 0) + { throw new InvalidOperationException("Transform is missing from the scene hierarchy index."); + } int rootTarget = Math.Clamp(siblingIndex, 0, m_roots.Count - 1); if (rootIndex == rootTarget) + { return; + } m_roots.RemoveAt(rootIndex); m_roots.Insert(rootTarget, transform); RefreshRootIndices(Math.Min(rootIndex, rootTarget), Math.Max(rootIndex, rootTarget) + 1); @@ -146,7 +174,9 @@ internal void Clear() private void RemoveRoot(Transform transform) { if (!m_rootIndices.Remove(transform, out int index)) + { return; + } m_roots.RemoveAt(index); RefreshRootIndices(index, m_roots.Count); } @@ -156,6 +186,8 @@ private void RefreshRootIndices( int end ) { for (int index = start; index < end; index++) + { m_rootIndices[m_roots[index]] = index; + } } } diff --git a/src/content/scene/Inno.Scene/Storage/ComponentFactory.cs b/src/content/scene/Inno.Scene/Storage/ComponentFactory.cs index 9e11a811e..d60645558 100644 --- a/src/content/scene/Inno.Scene/Storage/ComponentFactory.cs +++ b/src/content/scene/Inno.Scene/Storage/ComponentFactory.cs @@ -15,7 +15,9 @@ TypeCacheSnapshot types ArgumentNullException.ThrowIfNull(componentType); ArgumentNullException.ThrowIfNull(types); if (!typeof(GameComponent).IsAssignableFrom(componentType) || componentType.IsAbstract || !componentType.IsClass) + { throw new ArgumentException($"Type '{componentType.FullName}' is not a concrete GameComponent.", nameof(componentType)); + } return (GameComponent)types.CreateInstance(componentType); } } diff --git a/src/content/scene/Inno.Scene/Storage/SceneStore.cs b/src/content/scene/Inno.Scene/Storage/SceneStore.cs index cf794091c..a143e3fe9 100644 --- a/src/content/scene/Inno.Scene/Storage/SceneStore.cs +++ b/src/content/scene/Inno.Scene/Storage/SceneStore.cs @@ -3,9 +3,8 @@ using System.Collections.ObjectModel; using System.Linq; using System.Threading; - -using Inno.Extensibility.Types; using Inno.Core.Collections; +using Inno.Extensibility.Types; using Inno.Scene.Layers; namespace Inno.Scene; @@ -26,7 +25,7 @@ internal enum SceneStoreRemovalKind /// /// The removed committed key. /// - RemovedCommitted, + RemovedCommitted } internal readonly record struct SceneStoreRemovedComponent( @@ -88,12 +87,14 @@ internal SceneStore(SceneTypeCatalog types) m_objectOrderKey = m_objects.DefineKey( "scene.object.order", IndexedObjectKeyFlags.Ordered | IndexedObjectKeyFlags.Unique, - Comparer.Default); + Comparer.Default + ); m_componentKey = m_components.DefineKey("scene.component", IndexedObjectKeyFlags.Unique); m_componentPersistentIdKey = m_components.DefineKey( "scene.component.persistent-id", - IndexedObjectKeyFlags.Unique); + IndexedObjectKeyFlags.Unique + ); m_componentOwnerKey = m_components.DefineKey("scene.component.owner"); m_componentTypeKey = m_components.DefineKey("scene.component.type"); m_componentCommittedKey = m_components.DefineKey("scene.component.committed"); @@ -101,12 +102,13 @@ internal SceneStore(SceneTypeCatalog types) internal bool isExecuting => m_executionDepth != 0; internal long structureRevision => m_structureRevision; - internal bool hasPendingChanges => - m_pendingObjectAdditions.Count != 0 || - m_pendingObjectRemovals.Count != 0 || - m_pendingComponentAdditions.Count != 0 || - m_pendingComponentRemovals.Count != 0 || - m_clearRequested; + + internal bool hasPendingChanges + => m_pendingObjectAdditions.Count != 0 + || m_pendingObjectRemovals.Count != 0 + || m_pendingComponentAdditions.Count != 0 + || m_pendingComponentRemovals.Count != 0 + || m_clearRequested; internal void AddObject(GameObject gameObject) { @@ -114,7 +116,8 @@ internal void AddObject(GameObject gameObject) if (TryGetRecord(gameObject, out _)) { throw new InvalidOperationException( - $"GameObject '{gameObject.identity.persistentId}' is already owned by this scene store."); + $"GameObject '{gameObject.identity.persistentId}' is already owned by this scene store." + ); } var record = new SceneObjectRecord(this, gameObject); @@ -158,7 +161,8 @@ bool allowsMultiple if (TryGetEntry(component, out _)) { throw new InvalidOperationException( - $"GameComponent '{descriptor.displayName}' is already owned by this scene store."); + $"GameComponent '{descriptor.displayName}' is already owned by this scene store." + ); } if (!allowsMultiple) @@ -170,8 +174,9 @@ bool allowsMultiple if (duplicate is { isAlive: true }) { throw new InvalidOperationException( - $"GameObject '{owner.identity.persistentId}' already owns unique component " + - $"'{descriptor.displayName}'."); + $"GameObject '{owner.identity.persistentId}' already owns unique component " + + $"'{descriptor.displayName}'." + ); } } @@ -204,12 +209,12 @@ internal SceneStoreRemovalKind RemoveComponent( GameObject owner, GameComponent component ) { - if (!TryGetRecord(owner, out SceneObjectRecord? record) || - !record!.isAlive || - !TryGetEntry(component, out ComponentEntry? entry) || - !entry!.isAlive || - !ReferenceEquals(entry.owner, record)) - { + if (!TryGetRecord(owner, out SceneObjectRecord? record) + || !record!.isAlive + || !TryGetEntry(component, out ComponentEntry? entry) + || !entry!.isAlive + || !ReferenceEquals(entry.owner, record) + ) { return SceneStoreRemovalKind.None; } @@ -223,9 +228,13 @@ GameComponent component } if (isExecuting) + { m_pendingComponentRemovals.Add(new PendingComponentRemoval(entry)); + } else + { CommitComponentRemoval(entry); + } return SceneStoreRemovalKind.RemovedCommitted; } @@ -237,15 +246,23 @@ int replacementRuntimeTypeId ArgumentNullException.ThrowIfNull(previous); ArgumentNullException.ThrowIfNull(replacement); if (isExecuting || hasPendingChanges) + { throw new InvalidOperationException("Components cannot be replaced during a scene execution phase."); + } if (!TryGetEntry(previous, out ComponentEntry? entry) || !entry!.isAlive) + { throw new InvalidOperationException("The component being replaced is not attached to this scene."); + } if (TryGetEntry(replacement, out _)) + { throw new InvalidOperationException("The replacement component is already attached to this scene."); + } int index = entry.owner.components.IndexOf(previous); if (index < 0) + { throw new InvalidOperationException("The component attachment order is inconsistent."); + } m_components.Add(entry) .Set(m_componentKey, replacement) @@ -259,7 +276,9 @@ int replacementRuntimeTypeId internal IReadOnlyList RemoveObject(GameObject gameObject) { if (!TryGetRecord(gameObject, out SceneObjectRecord? record) || !record!.isAlive) + { return Array.Empty(); + } record.isAlive = false; gameObject.ReleaseRecord(record); @@ -281,9 +300,13 @@ internal IReadOnlyList RemoveObject(GameObject gameO } if (isExecuting) + { m_pendingObjectRemovals.Add(new PendingObjectRemoval(record)); + } else + { CommitObjectRemoval(record); + } return removed; } @@ -292,7 +315,9 @@ internal IReadOnlyList RemoveObject(GameObject gameO internal IReadOnlyList GetObjects() { if (m_objectSnapshotCache is not null) + { return m_objectSnapshotCache; + } IReadOnlyList records = m_objects.Query() .Find(m_objectCommittedKey, true) @@ -301,7 +326,9 @@ internal IReadOnlyList GetObjects() .Get(); var result = new GameObject[records.Count]; for (int i = 0; i < records.Count; i++) + { result[i] = records[i].gameObject; + } m_objectSnapshotCache = result; return result; } @@ -329,12 +356,14 @@ internal IReadOnlyList GetObjects() .First()?.gameObject; internal IReadOnlyList FindObjectsWithTag(string tag) - => SelectObjects(m_objects.Query() - .Find(m_objectTagKey, tag) - .Find(m_objectCommittedKey, true) - .Where(static record => record.isAlive) - .OrderBy(m_objectOrderKey) - .Get()); + => SelectObjects( + m_objects.Query() + .Find(m_objectTagKey, tag) + .Find(m_objectCommittedKey, true) + .Where(static record => record.isAlive) + .OrderBy(m_objectOrderKey) + .Get() + ); internal GameObject? FindObjectWithLayer(GameLayer layer) => m_objects.Query() @@ -345,17 +374,21 @@ internal IReadOnlyList FindObjectsWithTag(string tag) .First()?.gameObject; internal IReadOnlyList FindObjectsWithLayer(GameLayer layer) - => SelectObjects(m_objects.Query() - .Find(m_objectLayerKey, layer) - .Find(m_objectCommittedKey, true) - .Where(static record => record.isAlive) - .OrderBy(m_objectOrderKey) - .Get()); + => SelectObjects( + m_objects.Query() + .Find(m_objectLayerKey, layer) + .Find(m_objectCommittedKey, true) + .Where(static record => record.isAlive) + .OrderBy(m_objectOrderKey) + .Get() + ); internal IReadOnlyList FindObjectsWithLayers(GameLayerMask layers) { if (layers == GameLayerMask.none) + { return Array.Empty(); + } return GetObjects().Where(gameObject => layers.Contains(gameObject.layer)).ToArray(); } @@ -393,10 +426,10 @@ out TComponent? component for (int i = 0; i < record.components.Count; i++) { GameComponent candidate = record.components[i]; - if (TryGetEntry(candidate, out ComponentEntry? entry) && - entry!.isAlive && - requestedType.IsAssignableFrom(entry.runtimeTypeId)) - { + if (TryGetEntry(candidate, out ComponentEntry? entry) + && entry!.isAlive + && requestedType.IsAssignableFrom(entry.runtimeTypeId) + ) { component = (TComponent)candidate; return true; } @@ -414,10 +447,10 @@ out GameComponent? component for (int i = 0; i < record.components.Count; i++) { GameComponent candidate = record.components[i]; - if (TryGetEntry(candidate, out ComponentEntry? entry) && - entry!.isAlive && - requestedType.IsAssignableFrom(entry.runtimeTypeId)) - { + if (TryGetEntry(candidate, out ComponentEntry? entry) + && entry!.isAlive + && requestedType.IsAssignableFrom(entry.runtimeTypeId) + ) { component = candidate; return true; } @@ -434,8 +467,8 @@ GameComponent component SceneObjectRecord record = GetAliveRecord(owner); int index = record.components.IndexOf(component); return index >= 0 && IsLocallyVisible(component) - ? index - : throw new InvalidOperationException("The component is not attached to the requested GameObject."); + ? index + : throw new InvalidOperationException("The component is not attached to the requested GameObject."); } internal void SetComponentIndex( @@ -445,11 +478,15 @@ int componentIndex ) { SceneObjectRecord record = GetAliveRecord(owner); if (record.isCommitted && (isExecuting || hasPendingChanges)) + { throw new InvalidOperationException("Components cannot be reordered during a scene execution phase."); + } int currentIndex = GetComponentIndex(owner, component); int targetIndex = Math.Clamp(componentIndex, 0, record.components.Count - 1); if (currentIndex == targetIndex) + { return; + } record.components.RemoveAt(currentIndex); record.components.Insert(targetIndex, component); m_structureSnapshotCache = null; @@ -465,10 +502,10 @@ SceneComponentTypeDescriptor requestedType for (int i = 0; i < record.components.Count; i++) { GameComponent candidate = record.components[i]; - if (TryGetEntry(candidate, out ComponentEntry? entry) && - entry!.isAlive && - requestedType.IsAssignableFrom(entry.runtimeTypeId)) - { + if (TryGetEntry(candidate, out ComponentEntry? entry) + && entry!.isAlive + && requestedType.IsAssignableFrom(entry.runtimeTypeId) + ) { result.Add((TComponent)candidate); } } @@ -479,12 +516,16 @@ internal IReadOnlyList GetComponents( SceneComponentTypeDescriptor requestedType) where TComponent : GameComponent { if (m_typedComponentQueryCache.TryGetValue(requestedType.runtimeTypeId, out object? cached)) + { return (ReadOnlyCollection)cached; + } GameComponent[] untyped = GetCommittedComponents(requestedType); var typed = new TComponent[untyped.Length]; for (int i = 0; i < untyped.Length; i++) + { typed[i] = (TComponent)untyped[i]; + } ReadOnlyCollection view = Array.AsReadOnly(typed); m_typedComponentQueryCache.Add(requestedType.runtimeTypeId, view); return view; @@ -496,43 +537,44 @@ internal IReadOnlyList Query(SceneComponentTypeDescriptor requestedT internal IReadOnlyList Query( SceneComponentTypeDescriptor first, SceneComponentTypeDescriptor second - ) - => Query(ComponentQueryKey.Create(first.runtimeTypeId, second.runtimeTypeId)); + ) => Query(ComponentQueryKey.Create(first.runtimeTypeId, second.runtimeTypeId)); internal IReadOnlyList Query( SceneComponentTypeDescriptor first, SceneComponentTypeDescriptor second, SceneComponentTypeDescriptor third - ) - => Query(ComponentQueryKey.Create( - first.runtimeTypeId, - second.runtimeTypeId, - third.runtimeTypeId)); + ) => Query(ComponentQueryKey.Create(first.runtimeTypeId, second.runtimeTypeId, third.runtimeTypeId)); private IReadOnlyList Query(ComponentQueryKey query) { if (m_objectQueryCache.TryGetValue(query, out ReadOnlyCollection? cached)) + { return cached; + } SceneComponentTypeDescriptor first = m_types.GetComponent(query.first); SceneComponentTypeDescriptor? second = query.count >= 2 - ? m_types.GetComponent(query.second) - : null; + ? m_types.GetComponent(query.second) + : null; SceneComponentTypeDescriptor? third = query.count >= 3 - ? m_types.GetComponent(query.third) - : null; + ? m_types.GetComponent(query.third) + : null; GameComponent[] candidates = GetCommittedComponents(first); if (second is not null) { GameComponent[] secondCandidates = GetCommittedComponents(second); if (secondCandidates.Length < candidates.Length) + { candidates = secondCandidates; + } } if (third is not null) { GameComponent[] thirdCandidates = GetCommittedComponents(third); if (thirdCandidates.Length < candidates.Length) + { candidates = thirdCandidates; + } } var seen = new HashSet(ReferenceEqualityComparer.Instance); @@ -540,17 +582,17 @@ private IReadOnlyList Query(ComponentQueryKey query) for (int i = 0; i < candidates.Length; i++) { GameComponent candidate = candidates[i]; - if (!TryGetEntry(candidate, out ComponentEntry? entry) || - !IsVisible(entry!) || - !seen.Add(entry!.owner.gameObject)) - { + if (!TryGetEntry(candidate, out ComponentEntry? entry) + || !IsVisible(entry!) + || !seen.Add(entry!.owner.gameObject) + ) { continue; } - if (HasVisibleComponent(entry.owner, first) && - (second is null || HasVisibleComponent(entry.owner, second)) && - (third is null || HasVisibleComponent(entry.owner, third))) - { + if (HasVisibleComponent(entry.owner, first) + && (second is null || HasVisibleComponent(entry.owner, second)) + && (third is null || HasVisibleComponent(entry.owner, third)) + ) { result.Add(entry.owner.gameObject); } } @@ -563,7 +605,9 @@ private IReadOnlyList Query(ComponentQueryKey query) internal IDisposable BeginExecutionPhase() { if (m_clearRequested) + { throw new InvalidOperationException("A scene execution phase cannot begin while the store is pending clear."); + } m_executionDepth++; return new ExecutionScope(this); } @@ -573,11 +617,14 @@ internal SceneStructureSnapshot CaptureStructure() if (isExecuting || hasPendingChanges) { throw new InvalidOperationException( - "A scene cannot be captured during an execution phase with uncommitted structural changes."); + "A scene cannot be captured during an execution phase with uncommitted structural changes." + ); } if (m_structureSnapshotCache is not null) + { return m_structureSnapshotCache; + } SceneObjectStructureSnapshot[] objects = GetObjects() .Select(gameObject => new SceneObjectStructureSnapshot(gameObject, GetComponents(gameObject))) .ToArray(); @@ -598,9 +645,13 @@ internal static void InvalidateAllTypeCaches() for (int i = S_STORES.Count - 1; i >= 0; i--) { if (S_STORES[i].TryGetTarget(out SceneStore? store)) + { store.InvalidateTypeCaches(); + } else + { S_STORES.RemoveAt(i); + } } } } @@ -619,18 +670,20 @@ internal void Clear() private GameComponent[] GetCommittedComponents(SceneComponentTypeDescriptor requestedType) { if (m_componentQueryCache.TryGetValue(requestedType.runtimeTypeId, out GameComponent[]? cached)) + { return cached; + } var result = new List(); int[] concreteTypes = requestedType.assignableConcreteRuntimeTypeIds; for (int i = 0; i < concreteTypes.Length; i++) { - foreach (ComponentEntry entry in m_components.FindFast( - m_componentTypeKey, - concreteTypes[i])) + foreach (ComponentEntry entry in m_components.FindFast(m_componentTypeKey, concreteTypes[i])) { if (IsVisible(entry)) + { result.Add(entry.component); + } } } @@ -645,10 +698,10 @@ SceneComponentTypeDescriptor requestedType ) { for (int i = 0; i < owner.components.Count; i++) { - if (TryGetEntry(owner.components[i], out ComponentEntry? entry) && - IsVisible(entry!) && - requestedType.IsAssignableFrom(entry!.runtimeTypeId)) - { + if (TryGetEntry(owner.components[i], out ComponentEntry? entry) + && IsVisible(entry!) + && requestedType.IsAssignableFrom(entry!.runtimeTypeId) + ) { return true; } } @@ -666,7 +719,8 @@ private SceneObjectRecord GetAliveRecord(GameObject owner) if (!TryGetRecord(owner, out SceneObjectRecord? record) || !record!.isAlive) { throw new InvalidOperationException( - $"GameObject '{owner.identity.persistentId}' does not belong to this scene store."); + $"GameObject '{owner.identity.persistentId}' does not belong to this scene store." + ); } return record; } @@ -692,7 +746,9 @@ private void RemoveComponentEntry( GameComponent component ) { if (!TryGetEntry(component, out ComponentEntry? entry) || !entry!.isAlive) + { return; + } entry.isAlive = false; record.components.Remove(component); @@ -703,9 +759,13 @@ GameComponent component } if (isExecuting) + { m_pendingComponentRemovals.Add(new PendingComponentRemoval(entry)); + } else + { CommitComponentRemoval(entry); + } } private void CommitPendingChanges() @@ -714,25 +774,33 @@ private void CommitPendingChanges() { SceneObjectRecord record = m_pendingObjectAdditions[i].record; if (record.isAlive && !record.isCommitted) + { CommitObjectAddition(record); + } } for (int i = 0; i < m_pendingComponentAdditions.Count; i++) { ComponentEntry entry = m_pendingComponentAdditions[i].entry; if (entry.isAlive && entry.owner.isAlive && !entry.isCommitted) + { CommitComponentAddition(entry); + } } for (int i = 0; i < m_pendingComponentRemovals.Count; i++) { ComponentEntry entry = m_pendingComponentRemovals[i].entry; if (entry.isCommitted) + { CommitComponentRemoval(entry); + } } for (int i = 0; i < m_pendingObjectRemovals.Count; i++) { SceneObjectRecord record = m_pendingObjectRemovals[i].record; if (record.isCommitted) + { CommitObjectRemoval(record); + } } m_pendingObjectAdditions.Clear(); @@ -780,15 +848,23 @@ private void InvalidateStructureCaches() private void EndExecutionPhase() { if (m_executionDepth <= 0) + { throw new InvalidOperationException("Scene execution phase scopes are unbalanced."); + } m_executionDepth--; if (m_executionDepth != 0) + { return; + } if (m_clearRequested) + { ClearImmediately(); + } else + { CommitPendingChanges(); + } } private void ClearImmediately() @@ -816,7 +892,9 @@ private static IReadOnlyList SelectObjects(IReadOnlyList first == second - ? Create(first) - : Compare(first, second) < 0 - ? new ComponentQueryKey(first, second, default, 2) - : new ComponentQueryKey(second, first, default, 2); + ) => first == second + ? Create(first) + : Compare(first, second) < 0 + ? new ComponentQueryKey(first, second, default, 2) + : new ComponentQueryKey(second, first, default, 2); internal static ComponentQueryKey Create( int first, @@ -868,17 +948,29 @@ internal static ComponentQueryKey Create( int third ) { if (Compare(first, second) > 0) + { (first, second) = (second, first); + } if (Compare(second, third) > 0) + { (second, third) = (third, second); + } if (Compare(first, second) > 0) + { (first, second) = (second, first); + } if (first == third) + { return Create(first); + } if (first == second) + { return Create(first, third); + } if (second == third) + { return Create(first, second); + } return new ComponentQueryKey(first, second, third, 3); } diff --git a/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs b/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs index 5ec9d6a3e..5e5b33dfa 100644 --- a/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs +++ b/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs @@ -33,11 +33,15 @@ internal sealed class SceneStructureSnapshot internal IReadOnlyDictionary CaptureObjectSourceIds() { if (m_sourceIds is not null && HasCurrentIdentities(m_sourceIds)) + { return m_frozenSourceIds!; + } int count = objects.Count; foreach (SceneObjectStructureSnapshot entry in objects) + { count = checked(count + entry.components.Count); + } var sourceIds = new Dictionary(count, ReferenceEqualityComparer.Instance); foreach (SceneObjectStructureSnapshot entry in objects) { @@ -59,8 +63,12 @@ private static bool HasCurrentIdentities(Dictionary sourceId { // Core registry rebinding can replace an identity without changing the structural snapshot. foreach ((EngineObject value, Guid persistentId) in sourceIds) + { if (value.identity.persistentId != persistentId) + { return false; + } + } return true; } } diff --git a/src/content/scene/Inno.Scene/Storage/SceneTypeCatalog.cs b/src/content/scene/Inno.Scene/Storage/SceneTypeCatalog.cs index a42d80432..47a09ad0f 100644 --- a/src/content/scene/Inno.Scene/Storage/SceneTypeCatalog.cs +++ b/src/content/scene/Inno.Scene/Storage/SceneTypeCatalog.cs @@ -3,10 +3,8 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - -using Inno.Extensibility.Types; - using Inno.Extensibility.Catalogs; +using Inno.Extensibility.Types; namespace Inno.Scene; @@ -28,28 +26,32 @@ out SceneComponentTypeDescriptor? descriptor ) { ArgumentNullException.ThrowIfNull(type); descriptor = null; - return m_types.TryGetTypeRef(type, out TypeRef typeRef) && - m_registry.snapshot.componentsByRuntimeId.TryGetValue(typeRef.runtimeId, out descriptor); + return m_types.TryGetTypeRef(type, out TypeRef typeRef) + && m_registry.snapshot.componentsByRuntimeId.TryGetValue(typeRef.runtimeId, out descriptor); } internal SceneComponentTypeDescriptor GetComponent(Type type) { if (TryGetComponent(type, out SceneComponentTypeDescriptor? descriptor)) + { return descriptor!; + } throw new InvalidOperationException( - $"GameComponent type '{type.FullName}' is not part of the active TypeCache generation."); + $"GameComponent type '{type.FullName}' is not part of the active TypeCache generation." + ); } internal SceneComponentTypeDescriptor GetComponent(int runtimeTypeId) { if (m_registry.snapshot.componentsByRuntimeId.TryGetValue( - runtimeTypeId, - out SceneComponentTypeDescriptor? descriptor)) - { + runtimeTypeId, + out SceneComponentTypeDescriptor? descriptor + )) { return descriptor; } throw new InvalidOperationException( - $"Component runtime type ID '{runtimeTypeId}' is not part of the active TypeCache generation."); + $"Component runtime type ID '{runtimeTypeId}' is not part of the active TypeCache generation." + ); } internal bool TryGetSystem( @@ -58,20 +60,25 @@ out SceneSystemTypeDescriptor? descriptor ) { ArgumentNullException.ThrowIfNull(type); descriptor = null; - return m_types.TryGetTypeRef(type, out TypeRef typeRef) && - m_registry.snapshot.systemsByRuntimeId.TryGetValue(typeRef.runtimeId, out descriptor); + return m_types.TryGetTypeRef(type, out TypeRef typeRef) + && m_registry.snapshot.systemsByRuntimeId.TryGetValue(typeRef.runtimeId, out descriptor); } internal SceneSystemTypeDescriptor GetSystem(Type type) { if (TryGetSystem(type, out SceneSystemTypeDescriptor? descriptor)) + { return descriptor!; + } throw new InvalidOperationException( - $"GameSystem type '{type.FullName}' is not part of the active TypeCache generation."); + $"GameSystem type '{type.FullName}' is not part of the active TypeCache generation." + ); } internal Type Resolve(TypeRef typeRef) => m_types.Resolve(typeRef); + internal TypeRef GetTypeRef(Type type) => m_types.GetTypeRef(type); + internal TypeCacheSnapshot snapshot => m_types.current; internal long generation => m_registry.snapshot.generation; @@ -84,9 +91,7 @@ internal SceneSystemTypeDescriptor GetSystem(Type type) private sealed class SceneTypeRegistry : TypeRegistry { internal SceneTypeRegistry(TypeCatalog types) - : base(types) - { - } + : base(types) {} internal SceneTypeSnapshot snapshot => current; @@ -126,7 +131,8 @@ protected override SceneTypeSnapshot Build(TypeCacheSnapshot types) types.GetAttribute(componentTypeRef, inherit: true) is not null, GetBehaviorPhases(types.GetMetadata(componentTypeRef)), assignableConcreteRuntimeTypeIds, - assignableConcreteRuntimeTypeIds.ToFrozenSet()); + assignableConcreteRuntimeTypeIds.ToFrozenSet() + ); componentsByRuntimeId.Add(descriptor.runtimeTypeId, descriptor); } @@ -142,14 +148,16 @@ protected override SceneTypeSnapshot Build(TypeCacheSnapshot types) systemTypeRef.runtimeId, systemType.FullName ?? systemType.Name, systemType.IsClass && !systemType.IsAbstract, - types.GetAttribute(systemTypeRef, inherit: false) is not null); + types.GetAttribute(systemTypeRef, inherit: false) is not null + ); systemsByRuntimeId.Add(descriptor.runtimeTypeId, descriptor); } return new SceneTypeSnapshot( types.version, componentsByRuntimeId.ToFrozenDictionary(), - systemsByRuntimeId.ToFrozenDictionary()); + systemsByRuntimeId.ToFrozenDictionary() + ); } /// @@ -164,8 +172,7 @@ protected override SceneTypeSnapshot Build(TypeCacheSnapshot types) protected override void OnActivating( SceneTypeSnapshot? previous, SceneTypeSnapshot candidate - ) - => SceneStore.InvalidateAllTypeCaches(); + ) => SceneStore.InvalidateAllTypeCaches(); /// /// Restores state retained for the previous snapshot after candidate activation fails. @@ -179,13 +186,14 @@ SceneTypeSnapshot candidate protected override void OnActivationRolledBack( SceneTypeSnapshot? previous, SceneTypeSnapshot candidate - ) - => SceneStore.InvalidateAllTypeCaches(); + ) => SceneStore.InvalidateAllTypeCaches(); private static GameBehaviorLifecyclePhase GetBehaviorPhases(TypeCatalogMetadata metadata) { if (!typeof(GameBehavior).IsAssignableFrom(metadata.type)) + { return GameBehaviorLifecyclePhase.None; + } GameBehaviorLifecyclePhase phases = GameBehaviorLifecyclePhase.None; AddOverride("Awake", GameBehaviorLifecyclePhase.Awake); @@ -208,7 +216,6 @@ GameBehaviorLifecyclePhase phase } } } - } } diff --git a/src/foundation/core/Inno.Core.Collections/DependencyGraph/DependencyGraph.cs b/src/foundation/core/Inno.Core.Collections/DependencyGraph/DependencyGraph.cs index 3b2fde4a3..179fae2a5 100644 --- a/src/foundation/core/Inno.Core.Collections/DependencyGraph/DependencyGraph.cs +++ b/src/foundation/core/Inno.Core.Collections/DependencyGraph/DependencyGraph.cs @@ -16,7 +16,8 @@ namespace Inno.Core.Collections; /// dependency. The graph accepts cycles; operations that require an acyclic graph, /// such as , report them explicitly. /// -public sealed class DependencyGraph where TKey : notnull +public sealed class DependencyGraph + where TKey : notnull { private sealed class Node { @@ -47,7 +48,9 @@ NodePriority y { int keyComparison = orderingComparer.Compare(x.key, y.key); if (keyComparison != 0) + { return keyComparison; + } } return x.order.CompareTo(y.order); @@ -167,7 +170,9 @@ public bool AddNode(TKey node) try { if (!AddNodeLocked(node)) + { return false; + } m_version++; return true; @@ -193,18 +198,24 @@ public bool RemoveNode(TKey node) try { if (!m_nodes.Remove(node, out Node? removed)) + { return false; + } foreach (TKey dependency in removed.dependencies) { if (m_nodes.TryGetValue(dependency, out Node? dependencyNode)) + { dependencyNode.dependents.Remove(node); + } } foreach (TKey dependent in removed.dependents) { if (m_nodes.TryGetValue(dependent, out Node? dependentNode)) + { dependentNode.dependencies.Remove(node); + } } m_version++; @@ -238,7 +249,9 @@ TKey dependency AddNodeLocked(node); AddNodeLocked(dependency); if (!m_nodes[node].dependencies.Add(dependency)) + { return false; + } m_nodes[dependency].dependents.Add(node); m_version++; @@ -269,14 +282,16 @@ TKey dependency m_sync.EnterWriteLock(); try { - if (!m_nodes.TryGetValue(node, out Node? dependentNode) || - !dependentNode.dependencies.Remove(dependency)) - { + if (!m_nodes.TryGetValue(node, out Node? dependentNode) + || !dependentNode.dependencies.Remove(dependency) + ) { return false; } if (m_nodes.TryGetValue(dependency, out Node? dependencyNode)) + { dependencyNode.dependents.Remove(node); + } m_version++; return true; @@ -311,14 +326,20 @@ IEnumerable dependencies { bool changed = AddNodeLocked(node); foreach (TKey dependency in replacement) + { changed |= AddNodeLocked(dependency); + } Node target = m_nodes[node]; if (!changed && target.dependencies.SetEquals(replacement)) + { return; + } foreach (TKey previous in target.dependencies) + { m_nodes[previous].dependents.Remove(node); + } target.dependencies.Clear(); foreach (TKey dependency in replacement) @@ -350,8 +371,7 @@ IEnumerable dependencies public IReadOnlyList GetDependencies( TKey node, bool recursive = false - ) - => GetConnectedNodes(node, recursive, static value => value.dependencies); + ) => GetConnectedNodes(node, recursive, static value => value.dependencies); /// /// Gets direct or transitive dependents of a node. @@ -368,8 +388,7 @@ public IReadOnlyList GetDependencies( public IReadOnlyList GetDependents( TKey node, bool recursive = false - ) - => GetConnectedNodes(node, recursive, static value => value.dependents); + ) => GetConnectedNodes(node, recursive, static value => value.dependents); /// /// Determines whether one node directly or transitively depends on another. @@ -395,9 +414,13 @@ public bool DependsOn( try { if (!m_nodes.TryGetValue(node, out Node? start)) + { return false; + } if (!recursive) + { return start.dependencies.Contains(dependency); + } var visited = new HashSet(m_equalityComparer); var pending = new Stack(start.dependencies); @@ -405,11 +428,17 @@ public bool DependsOn( { TKey current = pending.Pop(); if (m_equalityComparer.Equals(current, dependency)) + { return true; + } if (!visited.Add(current) || !m_nodes.TryGetValue(current, out Node? currentNode)) + { continue; + } foreach (TKey next in currentNode.dependencies) + { pending.Push(next); + } } return false; @@ -440,7 +469,9 @@ public IReadOnlyList TopologicalSort() { remaining.Add(key, value.dependencies.Count); if (value.dependencies.Count == 0) + { ready.Enqueue(key, new NodePriority(key, value.order)); + } } var result = new List(m_nodes.Count); @@ -450,18 +481,21 @@ public IReadOnlyList TopologicalSort() foreach (TKey dependent in OrderNodes(m_nodes[current].dependents)) { if (--remaining[dependent] != 0) + { continue; + } Node dependentNode = m_nodes[dependent]; ready.Enqueue(dependent, new NodePriority(dependent, dependentNode.order)); } } if (result.Count == m_nodes.Count) + { return result.ToArray(); + } IReadOnlyList cycle = FindCycleLocked(); - throw new InvalidOperationException( - $"Dependency graph contains a cycle: {string.Join(" -> ", cycle)}."); + throw new InvalidOperationException($"Dependency graph contains a cycle: {string.Join(" -> ", cycle)}."); } finally { @@ -513,7 +547,9 @@ public IReadOnlyList> GetStronglyConnectedComponents() foreach (TKey node in OrderNodes(m_nodes.Keys)) { if (!indexes.ContainsKey(node)) + { Visit(node); + } } components.Sort(( @@ -544,7 +580,9 @@ void Visit(TKey node) } if (lowLinks[node] != indexes[node]) + { return; + } var component = new List(); TKey current; @@ -575,7 +613,9 @@ public void Clear() try { if (m_nodes.Count == 0) + { return; + } m_nodes.Clear(); m_version++; } @@ -588,7 +628,9 @@ public void Clear() private bool AddNodeLocked(TKey node) { if (m_nodes.ContainsKey(node)) + { return false; + } m_nodes.Add(node, new Node { order = m_nextNodeOrder++, @@ -607,9 +649,13 @@ Func> selector try { if (!m_nodes.TryGetValue(node, out Node? start)) + { return Array.Empty(); + } if (!recursive) + { return OrderNodes(selector(start)); + } var result = new HashSet(m_equalityComparer); var pending = new Stack(selector(start)); @@ -617,9 +663,13 @@ Func> selector { TKey current = pending.Pop(); if (!result.Add(current) || !m_nodes.TryGetValue(current, out Node? currentNode)) + { continue; + } foreach (TKey connected in selector(currentNode)) + { pending.Push(connected); + } } result.Remove(node); @@ -640,7 +690,9 @@ private IReadOnlyList FindCycleLocked() foreach (TKey node in OrderNodes(m_nodes.Keys)) { if (!states.ContainsKey(node) && Visit(node, out IReadOnlyList? cycle)) + { return cycle; + } } return Array.Empty(); @@ -656,14 +708,18 @@ out IReadOnlyList cycle if (!states.TryGetValue(dependency, out byte state)) { if (Visit(dependency, out cycle)) + { return true; + } } else if (state == 1) { int start = pathIndexes[dependency]; var found = new List(path.Count - start + 1); for (int i = start; i < path.Count; i++) + { found.Add(path[i]); + } found.Add(dependency); cycle = found.ToArray(); return true; @@ -693,7 +749,9 @@ TKey right { int comparison = m_orderingComparer.Compare(left, right); if (comparison != 0) + { return comparison; + } } return m_nodes[left].order.CompareTo(m_nodes[right].order); } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectEntry.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectEntry.cs index c9e5f20dc..051afc07e 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectEntry.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectEntry.cs @@ -8,7 +8,8 @@ namespace Inno.Core.Collections; /// /// Item type. /// -public readonly struct IndexedObjectEntry where T : class +public readonly struct IndexedObjectEntry + where T : class { private readonly IndexedObjectStore m_store; private readonly T m_item; diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs index b562731c0..de2b99e8e 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs @@ -4,16 +4,19 @@ namespace Inno.Core.Collections; -internal interface IIndexedObjectIndex where T : class +internal interface IIndexedObjectIndex + where T : class { /// /// Gets the human-readable name used for presentation and diagnostics. /// string name { get; } + /// /// Gets the key type accepted by this index implementation. /// Type keyType { get; } + /// /// Adds a new keyed value or atomically replaces the existing value for that key. /// @@ -27,6 +30,7 @@ void AddOrUpdate( T item, object key ); + /// /// Removes the requested value while preserving the collection's invariants. /// @@ -34,10 +38,12 @@ object key /// The stored item associated with the validated handle. /// void Remove(T item); + /// /// Removes all retained entries and returns the instance to an empty reusable state. /// void Clear(); + /// /// Retrieves the requested count value from current authoritative state. /// @@ -48,6 +54,7 @@ object key /// The scalar result calculated from the supplied inputs. /// int GetCount(object key); + /// /// Attempts to get single without changing state when the operation cannot complete. /// @@ -64,6 +71,7 @@ bool TryGetSingle( object key, out T? item ); + /// /// Determines whether current state contains the requested value value. /// @@ -80,6 +88,7 @@ bool Contains( object key, T item ); + /// /// Retrieves the requested set value from current authoritative state. /// @@ -92,7 +101,9 @@ T item HashSet? GetSet(object key); } -internal sealed class IndexedObjectIndex : IIndexedObjectIndex where T : class where TKey : notnull +internal sealed class IndexedObjectIndex : IIndexedObjectIndex + where T : class + where TKey : notnull { private readonly IKeyStorage m_storage; private readonly IKeyOrdering m_ordering; @@ -103,10 +114,12 @@ internal sealed class IndexedObjectIndex : IIndexedObjectIndex where /// Gets the human-readable name used for presentation and diagnostics. /// public string name { get; } + /// /// Gets the key type accepted by this index implementation. /// public Type keyType => typeof(TKey); + /// /// Gets the index capabilities supported by this key declaration. /// @@ -121,13 +134,13 @@ internal IndexedObjectIndex( this.flags = flags; m_storage = (flags & IndexedObjectKeyFlags.Unique) != 0 - ? new UniqueKeyStorage() - : new MultiKeyStorage(); + ? new UniqueKeyStorage() + : new MultiKeyStorage(); m_orderComparer = orderComparer ?? Comparer.Default; m_ordering = (flags & IndexedObjectKeyFlags.Ordered) != 0 - ? new SortedKeyOrdering(m_orderComparer) - : new NullKeyOrdering(); + ? new SortedKeyOrdering(m_orderComparer) + : new NullKeyOrdering(); m_keyByItem = new Dictionary(IndexedObjectStore.ReferenceEqualityComparer.INSTANCE); } @@ -135,32 +148,25 @@ internal IndexedObjectIndex( void IIndexedObjectIndex.AddOrUpdate( T item, object key - ) - => AddOrUpdate(item, (TKey)key); + ) => AddOrUpdate(item, (TKey)key); - void IIndexedObjectIndex.Remove(T item) - => Remove(item); + void IIndexedObjectIndex.Remove(T item) => Remove(item); - void IIndexedObjectIndex.Clear() - => Clear(); + void IIndexedObjectIndex.Clear() => Clear(); - int IIndexedObjectIndex.GetCount(object key) - => GetCount((TKey)key); + int IIndexedObjectIndex.GetCount(object key) => GetCount((TKey)key); bool IIndexedObjectIndex.TryGetSingle( object key, out T? item - ) - => TryGetSingle((TKey)key, out item); + ) => TryGetSingle((TKey)key, out item); bool IIndexedObjectIndex.Contains( object key, T item - ) - => Contains((TKey)key, item); + ) => Contains((TKey)key, item); - HashSet? IIndexedObjectIndex.GetSet(object key) - => FindUnsafe((TKey)key); + HashSet? IIndexedObjectIndex.GetSet(object key) => FindUnsafe((TKey)key); /// /// Adds a new keyed value or atomically replaces the existing value for that key. @@ -178,21 +184,29 @@ TKey key if (m_keyByItem.TryGetValue(item, out var oldKey)) { if (EqualityComparer.Default.Equals(oldKey, key)) + { return; + } // Add first so a rejected unique key leaves the previous mapping intact. bool addedKey = m_storage.Add(key, item); m_storage.Remove(oldKey, item); if (m_storage.IsKeyEmpty(oldKey)) + { m_ordering.RemoveKey(oldKey); + } if (addedKey) + { m_ordering.AddKey(key); + } m_keyByItem[item] = key; return; } if (m_storage.Add(key, item)) + { m_ordering.AddKey(key); + } m_keyByItem[item] = key; } @@ -205,12 +219,16 @@ TKey key public void Remove(T item) { if (!m_keyByItem.TryGetValue(item, out var key)) + { return; + } m_keyByItem.Remove(item); m_storage.Remove(key, item); if (m_storage.IsKeyEmpty(key)) + { m_ordering.RemoveKey(key); + } } /// diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs index 9d44625a6..32eb7111e 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs @@ -20,7 +20,7 @@ public enum IndexedObjectKeyFlags /// /// Allows at most one item for each key value. /// - Unique = 1 << 2, + Unique = 1 << 2 } /// @@ -33,12 +33,12 @@ public readonly struct IndexedObjectKey { internal readonly WeakReference? storeRef; internal readonly int id; - + /// /// Key name /// public readonly string name; - + /// /// Returns true if the store key is still valid in its owning store. /// @@ -48,7 +48,9 @@ public bool isValid get { if (storeRef == null || !storeRef.TryGetTarget(out var store)) + { return false; + } return store.IsValidKey(id, typeof(TKey)); } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs index 7588262e9..c842a4589 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs @@ -9,7 +9,8 @@ namespace Inno.Core.Collections; /// /// The stored reference type. /// -public sealed class IndexedObjectQuery where T : class +public sealed class IndexedObjectQuery + where T : class { private readonly IndexedObjectStore m_store; private readonly List> m_conditions = new(); @@ -34,7 +35,9 @@ internal IndexedObjectQuery(IndexedObjectStore store) public IndexedObjectQuery Where(IIndexedObjectQueryCondition condition) { if (condition == null) + { throw new ArgumentNullException(nameof(condition)); + } m_conditions.Add(condition); return this; @@ -50,7 +53,7 @@ public IndexedObjectQuery Where(IIndexedObjectQueryCondition condition) /// The same query instance. /// public IndexedObjectQuery Where(Func predicate) => Where(new IndexedObjectPredicateCondition(predicate)); - + /// /// Adds a key equality condition. /// @@ -83,10 +86,13 @@ TKey value /// /// The same query instance. /// - public IndexedObjectQuery OrderBy(IndexedObjectKey key) where TKey : notnull + public IndexedObjectQuery OrderBy(IndexedObjectKey key) + where TKey : notnull { if (!m_store.IsOrderedKey(key)) + { throw new InvalidOperationException($"Key '{key.name}' is not ordered."); + } m_orderedFastExec = () => m_store.ExecuteOrderedQueryFast(key, m_conditions); m_orderedSnapshotExec = () => m_store.ExecuteOrderedQuerySnapshot(key, m_conditions); diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs index 2acff0ec4..216e0560f 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs @@ -6,13 +6,15 @@ namespace Inno.Core.Collections; sealed partial class IndexedObjectStore -where T : class + where T : class { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool IsValidItem(T item) { if (item == null) + { return false; + } m_lock.EnterReadLock(); try @@ -146,13 +148,16 @@ private bool IsHandleValidNoLock(IndexedObjectRuntimeHandle handle) { int slot = handle.slot; if ((uint)slot >= (uint)m_generations.Count) + { return false; + } if (m_generations[slot] != handle.generation) + { return false; + } int denseIndex = m_sparseToDense[slot]; return denseIndex >= 0 && denseIndex < m_activeList.Count; } - } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs index 336b7248f..d53795f53 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs @@ -6,7 +6,7 @@ namespace Inno.Core.Collections; sealed partial class IndexedObjectStore -where T : class + where T : class { /// /// Defines a query key over stored items. @@ -33,16 +33,25 @@ public IndexedObjectKey DefineKey( ) where TKey : notnull { if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("Key name is required.", nameof(name)); + } m_lock.EnterWriteLock(); try { if (m_indexByName.TryGetValue(name, out _)) + { throw new InvalidOperationException($"Key '{name}' already exists."); + } if ((flags & IndexedObjectKeyFlags.Ordered) != 0 && orderComparer == null) - throw new ArgumentNullException(nameof(orderComparer), $"{nameof(orderComparer)} cannot be null when {nameof(flags)} is set to {nameof(IndexedObjectKeyFlags.Ordered)}.)"); + { + throw new ArgumentNullException( + nameof(orderComparer), + $"{nameof(orderComparer)} cannot be null when {nameof(flags)} is set to {nameof(IndexedObjectKeyFlags.Ordered)}.)" + ); + } var index = new IndexedObjectIndex(name, flags, orderComparer); var id = m_nextIndexId++; @@ -76,7 +85,9 @@ public bool RemoveKey(IndexedObjectKey key) try { if (!m_indexes.Remove(key.id, out var removed)) + { return false; + } m_indexByName.Remove(removed.name); BumpVersion(); @@ -109,7 +120,9 @@ out IndexedObjectKey key ) where TKey : notnull { if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("Key name is required.", nameof(name)); + } m_lock.EnterReadLock(); try @@ -172,19 +185,27 @@ private IEnumerable EnumerateKeys() } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool IsOrderedKey(IndexedObjectKey key) where TKey : notnull - => (GetIndex(key).flags & IndexedObjectKeyFlags.Ordered) != 0; + internal bool IsOrderedKey(IndexedObjectKey key) + where TKey : notnull + => (GetIndex(key).flags & IndexedObjectKeyFlags.Ordered) != 0; - private IndexedObjectIndex GetIndex(IndexedObjectKey handle) where TKey : notnull + private IndexedObjectIndex GetIndex(IndexedObjectKey handle) + where TKey : notnull { if (handle.storeRef == null || !handle.storeRef.TryGetTarget(out var owner) || !ReferenceEquals(owner, this)) + { throw new InvalidOperationException($"Key '{handle.name}' does not belong to this store."); + } if (!m_indexes.TryGetValue(handle.id, out var index)) + { throw new InvalidOperationException($"Key '{handle.name}' not found."); + } if (index.keyType != typeof(TKey)) + { throw new InvalidOperationException($"Key '{handle.name}' type mismatch."); + } return (IndexedObjectIndex)index; } @@ -199,7 +220,9 @@ TKey value try { if (!m_activeIndex.ContainsKey(item)) + { throw new InvalidOperationException("Item is not in the store."); + } GetIndex(key).AddOrUpdate(item, value); BumpVersion(); @@ -235,5 +258,4 @@ internal bool ContainsInSet( TKey value, T item ) where TKey : notnull => GetIndex(key).Contains(value, item); - } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs index 20fd94e13..fd5a7df8b 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs @@ -6,7 +6,7 @@ namespace Inno.Core.Collections; sealed partial class IndexedObjectStore -where T : class + where T : class { internal IEnumerable ExecuteOrderedQueryFast( IndexedObjectKey orderKey, @@ -29,7 +29,9 @@ List> conditions } if (TryBuildOrderedCandidates(index, conditions, out List>? candidates)) + { return SelectOrderedItems(candidates); + } return ScanOrderedSnapshot(index, conditions); } @@ -47,7 +49,9 @@ List> conditions var version = Volatile.Read(ref m_version); var index = GetIndex(orderKey); if ((index.flags & IndexedObjectKeyFlags.Ordered) == 0) + { throw new InvalidOperationException($"Key '{orderKey.name}' is not ordered."); + } if (TryBuildOrderedCandidates(index, conditions, out List>? candidates)) { @@ -75,14 +79,18 @@ List> conditions } if (ok) + { yield return single; + } continue; } var set = index.FindUnsafe(key); if (set == null || set.Count == 0) + { continue; + } foreach (var item in set) { @@ -115,12 +123,16 @@ List> conditions { var index = GetIndex(orderKey); if ((index.flags & IndexedObjectKeyFlags.Ordered) == 0) + { throw new InvalidOperationException($"Key '{orderKey.name}' is not ordered."); + } if (TryGetOrderedCandidateSeed(conditions, out int seedIndex, out int seedCount)) { if (seedCount == 0) + { return null; + } if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out T single)) { return ValidateConditions(conditions, single) ? single : null; @@ -134,10 +146,10 @@ List> conditions int firstDenseIndex = int.MaxValue; foreach (T item in seed) { - if (!ValidateConditions(conditions, item) || - !index.TryGetKey(item, out TKey itemKey) || - !m_activeIndex.TryGetValue(item, out int denseIndex)) - { + if (!ValidateConditions(conditions, item) + || !index.TryGetKey(item, out TKey itemKey) + || !m_activeIndex.TryGetValue(item, out int denseIndex) + ) { continue; } @@ -169,9 +181,13 @@ out List> candidates { candidates = []; if (!TryGetOrderedCandidateSeed(conditions, out int seedIndex, out int seedCount)) + { return false; + } if (seedCount == 0) + { return true; + } if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out T single)) { @@ -181,9 +197,13 @@ out List> candidates HashSet? seed = conditions[seedIndex].GetSet(this); if (seed is null) + { return false; + } foreach (T item in seed) + { AddOrderedCandidate(orderIndex, conditions, candidates, item); + } SortOrderedCandidates(orderIndex, candidates); return true; } @@ -199,7 +219,9 @@ out int seedCount { int candidateCount = conditions[i].GetCandidateCount(this); if (candidateCount >= seedCount) + { continue; + } seedCount = candidateCount; seedIndex = i; } @@ -213,19 +235,22 @@ private void AddOrderedCandidate( T item ) where TKey : notnull { - if (ValidateConditions(conditions, item) && - orderIndex.TryGetKey(item, out TKey itemKey) && - m_activeIndex.TryGetValue(item, out int denseIndex)) - { + if (ValidateConditions(conditions, item) + && orderIndex.TryGetKey(item, out TKey itemKey) + && m_activeIndex.TryGetValue(item, out int denseIndex) + ) { candidates.Add(new OrderedCandidate(item, itemKey, denseIndex)); } } - private static IReadOnlyList SelectOrderedItems(List> candidates) where TKey : notnull + private static IReadOnlyList SelectOrderedItems(List> candidates) + where TKey : notnull { var result = new T[candidates.Count]; for (int i = 0; i < candidates.Count; i++) + { result[i] = candidates[i].item; + } return result; } @@ -240,17 +265,23 @@ List> conditions if (index.TryGetSingle(key, out T? single) && single is not null) { if (ValidateConditions(conditions, single)) + { result.Add(single); + } continue; } HashSet? set = index.FindUnsafe(key); if (set is null) + { continue; + } foreach (T item in set) { if (ValidateConditions(conditions, item)) + { result.Add(item); + } } } return result; @@ -266,17 +297,23 @@ List> conditions if (index.TryGetSingle(key, out T? single) && single is not null) { if (ValidateConditions(conditions, single)) + { return single; + } continue; } HashSet? set = index.FindUnsafe(key); if (set is null) + { continue; + } foreach (T item in set) { if (ValidateConditions(conditions, item)) + { return item; + } } } return null; @@ -293,15 +330,13 @@ List> candidates { int comparison = index.CompareKeys(left.key, right.key); return comparison != 0 - ? comparison - : left.denseIndex.CompareTo(right.denseIndex); + ? comparison + : left.denseIndex.CompareTo(right.denseIndex); }); private readonly record struct OrderedCandidate( T item, TKey key, int denseIndex - ) - where TKey : notnull; - + ) where TKey : notnull; } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs index bafe5caee..91eafa928 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs @@ -6,7 +6,7 @@ namespace Inno.Core.Collections; sealed partial class IndexedObjectStore -where T : class + where T : class { /// /// Finds items by key and returns a lazy fail-fast enumerable. @@ -85,7 +85,9 @@ TKey value var set = index.FindUnsafe(value); if (set == null || set.Count == 0) + { yield break; + } foreach (var item in set) { @@ -144,7 +146,9 @@ TKey value try { if (GetIndex(key).TryGetSingle(value, out var item)) + { return item; + } return null; } finally @@ -332,7 +336,9 @@ private IEnumerable EnumerateQuery(List> cond } if (seedCount == 0) + { yield break; + } if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out var single)) { @@ -347,7 +353,9 @@ private IEnumerable EnumerateQuery(List> cond } if (ok) + { yield return single; + } yield break; } @@ -378,7 +386,9 @@ private IEnumerable EnumerateQuery(List> cond } if (seed.Count == 0) + { yield break; + } foreach (var item in seed) { @@ -406,7 +416,9 @@ private IEnumerable EnumerateQuery(List> cond try { if (conditions.Count == 0) + { return m_activeList.Count > 0 ? m_activeList[0] : null; + } int seedIndex = 0; int seedCount = conditions[0].GetCandidateCount(this); @@ -422,14 +434,18 @@ private IEnumerable EnumerateQuery(List> cond } if (seedCount == 0) + { return null; + } if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out var single)) { for (int i = 0; i < conditions.Count; i++) { if (!conditions[i].Validate(this, single)) + { return null; + } } return single; @@ -451,14 +467,18 @@ private IEnumerable EnumerateQuery(List> cond } if (ok) + { return item; + } } return null; } if (seed.Count == 0) + { return null; + } foreach (var item in seed) { @@ -473,7 +493,9 @@ private IEnumerable EnumerateQuery(List> cond } if (ok) + { return item; + } } return null; @@ -492,9 +514,10 @@ T item for (int i = 0; i < conditions.Count; i++) { if (!conditions[i].Validate(this, item)) + { return false; + } } return true; } - } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs index cf86b683a..5e6afd63e 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs @@ -34,7 +34,8 @@ Type keyType /// /// The stored reference type. /// -public sealed partial class IndexedObjectStore : IIndexedObjectStore where T : class +public sealed partial class IndexedObjectStore : IIndexedObjectStore + where T : class { private readonly WeakReference m_storeRef; private readonly List m_activeList = new(); @@ -130,7 +131,9 @@ public void RemoveAll() m_handleByItem.Clear(); m_denseToSlot.Clear(); foreach (var index in m_indexes.Values) + { index.Clear(); + } BumpVersion(); } finally @@ -151,7 +154,9 @@ public void RemoveAll() public IndexedObjectEntry Add(T item) { if (item == null) + { throw new ArgumentNullException(nameof(item)); + } m_lock.EnterWriteLock(); try @@ -188,16 +193,22 @@ public IndexedObjectEntry Add(T item) public bool Remove(T item) { if (item == null) + { throw new ArgumentNullException(nameof(item)); + } m_lock.EnterWriteLock(); try { if (!m_activeIndex.TryGetValue(item, out var index)) + { return false; + } foreach (var objectIndex in m_indexes.Values) + { objectIndex.Remove(item); + } var lastIndex = m_activeList.Count - 1; var lastItem = m_activeList[lastIndex]; @@ -233,10 +244,13 @@ public bool Remove(T item) private void EnsureVersion(int expected) { if (Volatile.Read(ref m_version) != expected) + { throw new InvalidOperationException("Collection was modified during enumeration."); + } } - internal sealed class ReferenceEqualityComparer : IEqualityComparer where TItem : class + internal sealed class ReferenceEqualityComparer : IEqualityComparer + where TItem : class { /// /// The instance value used as part of this type's public representation. diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/IKeyOrdering.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/IKeyOrdering.cs index d5a0d04cd..7daf4f976 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/IKeyOrdering.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/IKeyOrdering.cs @@ -2,7 +2,8 @@ namespace Inno.Core.Collections; -internal interface IKeyOrdering where TKey : notnull +internal interface IKeyOrdering + where TKey : notnull { /// /// Adds one key to the indexed membership set. @@ -11,6 +12,7 @@ internal interface IKeyOrdering where TKey : notnull /// The backend-neutral physical key associated with this event. /// void AddKey(TKey key); + /// /// Removes one key from the indexed membership set. /// @@ -18,10 +20,12 @@ internal interface IKeyOrdering where TKey : notnull /// The backend-neutral physical key associated with this event. /// void RemoveKey(TKey key); + /// /// Removes all retained entries and returns the instance to an empty reusable state. /// void Clear(); + /// /// Enumerates a stable view of the currently indexed keys. /// diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/NullKeyOrdering.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/NullKeyOrdering.cs index 757bb3b35..7ae8aecaf 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/NullKeyOrdering.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/NullKeyOrdering.cs @@ -2,7 +2,8 @@ namespace Inno.Core.Collections; -internal sealed class NullKeyOrdering : IKeyOrdering where TKey : notnull +internal sealed class NullKeyOrdering : IKeyOrdering + where TKey : notnull { /// /// Adds one key to the indexed membership set. @@ -10,18 +11,21 @@ internal sealed class NullKeyOrdering : IKeyOrdering where TKey : no /// /// The backend-neutral physical key associated with this event. /// - public void AddKey(TKey key) { } + public void AddKey(TKey key) {} + /// /// Removes one key from the indexed membership set. /// /// /// The backend-neutral physical key associated with this event. /// - public void RemoveKey(TKey key) { } + public void RemoveKey(TKey key) {} + /// /// Removes all retained entries and returns the instance to an empty reusable state. /// - public void Clear() { } + public void Clear() {} + /// /// Enumerates a stable view of the currently indexed keys. /// diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs index b8b874a47..e25b2e289 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs @@ -2,7 +2,8 @@ namespace Inno.Core.Collections; -internal sealed class SortedKeyOrdering : IKeyOrdering where TKey : notnull +internal sealed class SortedKeyOrdering : IKeyOrdering + where TKey : notnull { private readonly SortedSet m_keys; @@ -47,6 +48,8 @@ public SortedKeyOrdering(IComparer comparer) public IEnumerable Enumerate() { foreach (var key in m_keys) + { yield return key; + } } } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/IKeyStorage.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/IKeyStorage.cs index 63ad64a69..e48811d70 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/IKeyStorage.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/IKeyStorage.cs @@ -2,7 +2,9 @@ namespace Inno.Core.Collections; -internal interface IKeyStorage where T : class where TKey : notnull +internal interface IKeyStorage + where T : class + where TKey : notnull { /// /// Adds the supplied value while preserving the collection's invariants. @@ -20,6 +22,7 @@ bool Add( TKey key, T item ); + /// /// Removes the requested value while preserving the collection's invariants. /// @@ -33,6 +36,7 @@ void Remove( TKey key, T item ); + /// /// Attempts to get single without changing state when the operation cannot complete. /// @@ -49,6 +53,7 @@ bool TryGetSingle( TKey key, out T? item ); + /// /// Retrieves the requested count value from current authoritative state. /// @@ -59,6 +64,7 @@ out T? item /// The scalar result calculated from the supplied inputs. /// int GetCount(TKey key); + /// /// Determines whether current state contains the requested value value. /// @@ -75,6 +81,7 @@ bool Contains( TKey key, T item ); + /// /// Determines whether a key currently has no indexed values. /// @@ -85,6 +92,7 @@ T item /// when the requested condition is satisfied; otherwise, . /// bool IsKeyEmpty(TKey key); + /// /// Retrieves the requested set value from current authoritative state. /// @@ -95,6 +103,7 @@ T item /// The validated hash sett? that represents the completed operation. /// HashSet? GetSet(TKey key); + /// /// Removes all retained entries and returns the instance to an empty reusable state. /// diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs index 32f8d6afa..b44fe9b23 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs @@ -3,7 +3,9 @@ namespace Inno.Core.Collections; -internal sealed class MultiKeyStorage : IKeyStorage where T : class where TKey : notnull +internal sealed class MultiKeyStorage : IKeyStorage + where T : class + where TKey : notnull { private readonly Dictionary> m_map = new(EqualityComparer.Default); private static readonly HashSet EMPTY_SET = new(IndexedObjectStore.ReferenceEqualityComparer.INSTANCE); @@ -48,11 +50,15 @@ public void Remove( T item ) { if (!m_map.TryGetValue(key, out var set)) + { return; + } set.Remove(item); if (set.Count == 0) + { m_map.Remove(key); + } } /// @@ -73,11 +79,15 @@ out T? item ) { item = null; if (!m_map.TryGetValue(key, out var set) || set.Count == 0) + { return false; + } using var e = set.GetEnumerator(); if (!e.MoveNext()) + { return false; + } item = e.Current; return true; diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs index 54dbe6f4b..b83fecdbf 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs @@ -4,7 +4,9 @@ namespace Inno.Core.Collections; -internal sealed class UniqueKeyStorage : IKeyStorage where T : class where TKey : notnull +internal sealed class UniqueKeyStorage : IKeyStorage + where T : class + where TKey : notnull { private readonly Dictionary m_map = new(EqualityComparer.Default); @@ -25,7 +27,9 @@ public bool Add( T item ) { if (m_map.TryGetValue(key, out var existing) && !ReferenceEquals(existing, item)) + { throw new InvalidOperationException($"Duplicate key '{key}' in unique index."); + } m_map[key] = item; return true; @@ -45,7 +49,9 @@ public void Remove( T item ) { if (m_map.TryGetValue(key, out var existing) && ReferenceEquals(existing, item)) + { m_map.Remove(key); + } } /// diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IIndexedObjectQueryCondition.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IIndexedObjectQueryCondition.cs index 2b442b274..13b2e86f3 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IIndexedObjectQueryCondition.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IIndexedObjectQueryCondition.cs @@ -8,7 +8,8 @@ namespace Inno.Core.Collections; /// /// The stored reference type. /// -public interface IIndexedObjectQueryCondition where T : class +public interface IIndexedObjectQueryCondition + where T : class { /// /// Returns the estimated match count for this condition. diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs index 4d90cd2b8..0a6c8506d 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs @@ -12,7 +12,9 @@ namespace Inno.Core.Collections; /// /// The indexed key type. /// -public sealed class IndexedObjectKeyCondition : IIndexedObjectQueryCondition where T : class where TKey : notnull +public sealed class IndexedObjectKeyCondition : IIndexedObjectQueryCondition + where T : class + where TKey : notnull { private readonly IndexedObjectKey m_key; private readonly TKey m_value; diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs index 579df11fe..29e421172 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs @@ -10,7 +10,8 @@ namespace Inno.Core.Collections; /// /// The stored reference type. /// -public sealed class IndexedObjectPredicateCondition : IIndexedObjectQueryCondition where T : class +public sealed class IndexedObjectPredicateCondition : IIndexedObjectQueryCondition + where T : class { private readonly Func m_predicate; diff --git a/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs b/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs index c8a108e49..2bdcd3a4e 100644 --- a/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs +++ b/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs @@ -158,7 +158,9 @@ public void Dispose() lock (m_tickGate) { if (Interlocked.Exchange(ref m_disposed, 1) != 0) + { return; + } m_operationDepth++; try @@ -204,7 +206,9 @@ public void Tick(float deltaTime) ObjectDisposedException.ThrowIf(Volatile.Read(ref m_disposed) != 0, this); if (m_ticking || m_operationDepth != 0) + { throw new InvalidOperationException("A coroutine callback cannot recursively advance its scheduler."); + } m_operationDepth++; m_ticking = true; @@ -243,7 +247,9 @@ private void ApplyPendingCommands() { // Cleanup callbacks may enqueue commands, but must not recursively drain the queue. if (m_applyingCommands) + { return; + } m_applyingCommands = true; try @@ -254,23 +260,31 @@ private void ApplyPendingCommands() { case CommandKind.Start: if (cmd.routine is null) + { break; + } CoroutineState state = new(cmd.id, cmd.owner, cmd.routine); m_states.Add(state.id, state); m_active.Add(state.id); if (Volatile.Read(ref m_disposed) != 0) + { Retire(state); + } break; case CommandKind.Stop: if (m_states.TryGetValue(cmd.id, out CoroutineState? stopped)) + { Retire(stopped); + } break; case CommandKind.StopByOwner: for (int i = 0; i < m_active.Count; i++) { if (m_states.TryGetValue(m_active[i], out CoroutineState? owned) - && ReferenceEquals(owned.owner, cmd.owner)) + && ReferenceEquals(owned.owner, cmd.owner) + ) { Retire(owned); + } } break; case CommandKind.StopAll: @@ -283,7 +297,9 @@ private void ApplyPendingCommands() { m_applyingCommands = false; if (!m_ticking) + { PruneInactive(); + } } } @@ -295,13 +311,17 @@ private void TickActiveCoroutines() for (int i = 0; i < count; i++) { if (!m_states.TryGetValue(m_active[i], out CoroutineState? state)) + { continue; + } state.executing = true; try { if (!StepCoroutine(state)) + { Retire(state); + } } catch (Exception failure) { @@ -312,7 +332,9 @@ private void TickActiveCoroutines() { state.executing = false; if (state.retired) + { DisposeStack(state); + } } } } @@ -324,9 +346,13 @@ private bool StepCoroutine(CoroutineState state) { bool waiting = state.waiter.Invoke(this); if (state.retired) + { return false; + } if (waiting) + { return true; + } state.waiter = null; } @@ -340,18 +366,24 @@ private bool AdvanceCoroutine(CoroutineState state) IEnumerator current = state.stack.Peek(); bool moved = current.MoveNext(); if (state.retired) + { return false; + } if (!moved) { state.stack.Pop(); if (!DisposeEnumerator(current)) + { return false; + } continue; } object? yielded = current.Current; if (state.retired) + { return false; + } if (yielded is null) { ulong targetFrame = m_frame + 1; @@ -364,7 +396,9 @@ private bool AdvanceCoroutine(CoroutineState state) foreach (IEnumerator ancestor in state.stack) { if (ReferenceEquals(ancestor, nested)) + { throw new InvalidOperationException("A coroutine cannot yield an enumerator already on its stack."); + } } state.stack.Push(nested); continue; @@ -397,14 +431,18 @@ private bool AdvanceCoroutine(CoroutineState state) private void Retire(CoroutineState state) { if (state.retired) + { return; + } state.retired = true; m_needsPruning = true; m_states.Remove(state.id); m_liveIds.TryRemove(state.id, out _); state.waiter = null; if (!state.executing) + { DisposeStack(state); + } } private void RetireAll() @@ -412,7 +450,9 @@ private void RetireAll() for (int i = 0; i < m_active.Count; i++) { if (m_states.TryGetValue(m_active[i], out CoroutineState? state)) + { Retire(state); + } } } @@ -424,7 +464,9 @@ private void DisposeStack(CoroutineState state) try { while (state.stack.TryPop(out IEnumerator? routine)) + { DisposeEnumerator(routine); + } } finally { @@ -436,7 +478,9 @@ private void DisposeStack(CoroutineState state) private bool DisposeEnumerator(IEnumerator routine) { if (routine is not IDisposable disposable) + { return true; + } try { disposable.Dispose(); @@ -452,16 +496,22 @@ private bool DisposeEnumerator(IEnumerator routine) private void PruneInactive() { if (!m_needsPruning || m_ticking || m_applyingCommands) + { return; + } int retained = 0; for (int i = 0; i < m_active.Count; i++) { long id = m_active[i]; if (m_states.ContainsKey(id)) + { m_active[retained++] = id; + } } if (retained != m_active.Count) + { m_active.RemoveRange(retained, m_active.Count - retained); + } m_needsPruning = false; } @@ -470,7 +520,9 @@ private void PruneInactive() private void CompleteOperation() { if (--m_operationDepth != 0 || m_failures is null) + { return; + } List failures = m_failures; m_failures = null; throw new AggregateException("Coroutine execution or retirement failed; all eligible cleanup was attempted.", failures); @@ -494,14 +546,17 @@ private readonly struct Command( /// Gets the operation kind that determines how this value is interpreted. /// public CommandKind kind { get; } = kind; + /// /// Gets the stable identity used to reference this value across subsystem boundaries. /// public long id { get; } = id; + /// /// Gets the object that owns the coroutine lifetime. /// public object? owner { get; } = owner; + /// /// Gets the root enumerator advanced by this coroutine. /// @@ -568,22 +623,27 @@ IEnumerator routine /// Gets the stable identity used to reference this value across subsystem boundaries. /// public long id { get; } = id; + /// /// Gets the object that owns the coroutine lifetime. /// public object? owner { get; set; } = owner; + /// /// Gets the nested enumerator stack retained by this coroutine. /// public Stack stack { get; } = new([routine]); + /// /// Gets the current continuation predicate, or null when the coroutine can advance. /// public CoroutineWaitDelegate? waiter { get; set; } + /// /// Gets whether a user callback is borrowing the enumerator stack. /// public bool executing { get; set; } + /// /// Gets whether call admission has closed and the remaining stack must retire. /// diff --git a/src/foundation/core/Inno.Core.Diagnostics/Diagnostic.cs b/src/foundation/core/Inno.Core.Diagnostics/Diagnostic.cs index f479adc90..9add761d8 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/Diagnostic.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/Diagnostic.cs @@ -41,12 +41,13 @@ public Diagnostic( string? semanticId = null, Guid? objectId = null, DiagnosticLocation? location = null - ) - : this(severity, code, message, location) + ) : this(severity, code, message, location) { ArgumentException.ThrowIfNullOrWhiteSpace(code); if (objectId == Guid.Empty) + { throw new ArgumentException("A diagnostic object identity cannot be empty.", nameof(objectId)); + } this.semanticId = semanticId; this.objectId = objectId; } @@ -83,8 +84,7 @@ public static Diagnostic Info( string code, string message, DiagnosticLocation? location = null - ) - => new(DiagnosticSeverity.Info, code, message, location); + ) => new(DiagnosticSeverity.Info, code, message, location); /// /// Creates a warning diagnostic value without publishing it. @@ -108,8 +108,7 @@ public static Diagnostic Warning( string code, string message, DiagnosticLocation? location = null - ) - => new(DiagnosticSeverity.Warning, code, message, location); + ) => new(DiagnosticSeverity.Warning, code, message, location); /// /// Creates an error diagnostic value without publishing it. @@ -133,8 +132,7 @@ public static Diagnostic Error( string code, string message, DiagnosticLocation? location = null - ) - => new(DiagnosticSeverity.Error, code, message, location); + ) => new(DiagnosticSeverity.Error, code, message, location); private Diagnostic( DiagnosticSeverity severity, diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticCallerResolver.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticCallerResolver.cs index 94ce98331..44f92078f 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticCallerResolver.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticCallerResolver.cs @@ -22,13 +22,15 @@ internal static DiagnosticSource Resolve( ) { ArgumentException.ThrowIfNullOrWhiteSpace(group); if (targetId == Guid.Empty) + { throw new ArgumentException("A diagnostic target identifier cannot be empty.", nameof(targetId)); + } Type callerType = ResolveCallerType(); CallerInfo caller = CALLERS.GetValue(callerType, static type => { string assemblyName = type.Assembly.GetName().Name - ?? throw new InvalidOperationException("The diagnostic caller assembly has no simple name."); + ?? throw new InvalidOperationException("The diagnostic caller assembly has no simple name."); string typeName = type.FullName ?? type.Name; return new CallerInfo { @@ -37,11 +39,11 @@ internal static DiagnosticSource Resolve( }); string id = targetId.HasValue - ? $"{caller.sourcePrefix}/{group}/{targetId.Value:N}" - : $"{caller.sourcePrefix}/{group}"; + ? $"{caller.sourcePrefix}/{group}/{targetId.Value:N}" + : $"{caller.sourcePrefix}/{group}"; string resolvedDisplayName = string.IsNullOrWhiteSpace(displayName) - ? group - : displayName; + ? group + : displayName; return new DiagnosticSource(id, resolvedDisplayName); } @@ -55,7 +57,9 @@ private static Type ResolveCallerType() { Type? declaringType = frames[i].GetMethod()?.DeclaringType; if (declaringType is null || declaringType.Assembly == infrastructureAssembly) + { continue; + } return NormalizeCompilerGeneratedType(declaringType); } @@ -65,9 +69,9 @@ private static Type ResolveCallerType() private static Type NormalizeCompilerGeneratedType(Type type) { Type current = type; - while (current.DeclaringType is not null && - current.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false)) - { + while (current.DeclaringType is not null + && current.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false) + ) { current = current.DeclaringType; } return current; diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs index c32486827..4e421f515 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs @@ -1,8 +1,8 @@ -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.Linq; using System.Threading; +using Inno.Core.Execution; namespace Inno.Core.Diagnostics; @@ -65,7 +65,9 @@ IReadOnlyList diagnostics lock (m_sync) { if (!m_producerEpochs.TryGetValue(source.id, out long current) || current != epoch) + { throw new ObjectDisposedException(nameof(DiagnosticReporter), "The diagnostic producer generation has retired."); + } Set(source, diagnostics); } } @@ -77,7 +79,9 @@ long epoch lock (m_sync) { if (!m_producerEpochs.TryGetValue(source.id, out long current) || current != epoch) + { return; + } m_producerEpochs.Remove(source.id); Clear(source); } @@ -112,17 +116,22 @@ public void RegisterSink(IDiagnosticSink sink) lock (m_sync) { if (m_sinks.Contains(sink)) + { return; + } try { foreach (DiagnosticReport report in m_reports.Values) + { sink.Replace(report); + } } catch (Exception exception) { throw new InvalidOperationException( "The diagnostic sink rejected the active snapshot and was not registered.", - exception); + exception + ); } m_sinks.Add(sink); } @@ -141,7 +150,9 @@ public void UnregisterSink(IDiagnosticSink sink) { ArgumentNullException.ThrowIfNull(sink); lock (m_sync) + { m_sinks.Remove(sink); + } } /// @@ -172,7 +183,9 @@ IEnumerable diagnostics return; } if (entries.Any(static diagnostic => diagnostic is null)) + { throw new ArgumentException("A diagnostic collection cannot contain null entries.", nameof(diagnostics)); + } var report = new DiagnosticReport(source, Array.AsReadOnly(entries), DateTime.Now); lock (m_sync) { @@ -199,7 +212,9 @@ public void Clear(DiagnosticSource source) lock (m_sync) { if (!m_reports.Remove(source.id, out DiagnosticReport? report)) + { return; + } NotifySinks(static ( sink, value @@ -223,7 +238,9 @@ TValue value m_sinks.Remove(sinks[index]); Action? observer = sinkFailed; if (observer is null) + { Console.Error.WriteLine($"Diagnostic sink failed and was quarantined: {exception}"); + } else { foreach (Action handler in observer.GetInvocationList()) @@ -245,7 +262,8 @@ TValue value private static void ValidateSource(DiagnosticSource source) { if (string.IsNullOrWhiteSpace(source.id)) + { throw new ArgumentException("A valid diagnostic source is required.", nameof(source)); + } } - } diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs index c8ef6458f..7b4e49e3e 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs @@ -31,11 +31,17 @@ public DiagnosticLocation( int column = 0 ) { if (string.IsNullOrWhiteSpace(sourcePath)) + { throw new ArgumentException("A diagnostic source path is required.", nameof(sourcePath)); + } if (line < 0) + { throw new ArgumentOutOfRangeException(nameof(line), "A diagnostic line cannot be negative."); + } if (column < 0) + { throw new ArgumentOutOfRangeException(nameof(column), "A diagnostic column cannot be negative."); + } this.sourcePath = sourcePath; this.line = line; this.column = column; @@ -66,9 +72,9 @@ public DiagnosticLocation( /// The value to compare with this instance. /// public bool Equals(DiagnosticLocation other) - => string.Equals(sourcePath, other.sourcePath, StringComparison.Ordinal) && - line == other.line && - column == other.column; + => string.Equals(sourcePath, other.sourcePath, StringComparison.Ordinal) + && line == other.line + && column == other.column; /// /// Determines whether this instance and the supplied value represent the same logical state. diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs index c30584143..0c8906e4a 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs @@ -25,6 +25,7 @@ long epoch m_source = source; m_epoch = epoch; } + /// /// Replaces the issue with the same code and target, without using its message as identity. /// @@ -44,14 +45,15 @@ public void Publish(Diagnostic diagnostic) if (m_issues.TryGetValue(key, out Diagnostic? current) && current.severity == diagnostic.severity && string.Equals(current.message, diagnostic.message, StringComparison.Ordinal) - && Nullable.Equals(current.location, diagnostic.location)) - { + && Nullable.Equals(current.location, diagnostic.location) + ) { return; } m_issues[key] = diagnostic; hub.SetOwned(m_source, m_epoch, Ordered()); } } + /// /// Resolves an issue after the represented condition no longer exists. /// @@ -77,10 +79,13 @@ public void Resolve( { DiagnosticHub hub = GetHub(); if (!m_issues.Remove(new(code, semanticId, objectId))) + { return; + } hub.SetOwned(m_source, m_epoch, Ordered()); } } + /// /// Atomically replaces this producer's complete current issue set. /// @@ -101,7 +106,9 @@ public void Replace(IEnumerable diagnostics) { ArgumentNullException.ThrowIfNull(diagnostic); if (!candidate.TryAdd(new(diagnostic.code, diagnostic.semanticId, diagnostic.objectId), diagnostic)) + { throw new ArgumentException("A complete diagnostic report contains duplicate issue identities.", nameof(diagnostics)); + } } lock (m_sync) { @@ -109,7 +116,9 @@ public void Replace(IEnumerable diagnostics) hub.SetOwned(m_source, m_epoch, candidate.Values.ToArray()); m_issues.Clear(); foreach (var entry in candidate) + { m_issues.Add(entry.Key, entry.Value); + } } } @@ -129,10 +138,12 @@ public void Dispose() private DiagnosticHub GetHub() => m_hub ?? throw new ObjectDisposedException(nameof(DiagnosticReporter)); - private Diagnostic[] Ordered() => m_issues.Values - .OrderBy(static issue => issue.code, StringComparer.Ordinal) - .ThenBy(static issue => issue.semanticId, StringComparer.Ordinal) - .ThenBy(static issue => issue.objectId).ToArray(); + private Diagnostic[] Ordered() + => m_issues.Values + .OrderBy(static issue => issue.code, StringComparer.Ordinal) + .ThenBy(static issue => issue.semanticId, StringComparer.Ordinal) + .ThenBy(static issue => issue.objectId) + .ToArray(); private readonly record struct IssueKey( string code, diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSeverity.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSeverity.cs index 9d910e7db..ca48fc974 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSeverity.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSeverity.cs @@ -9,12 +9,10 @@ public enum DiagnosticSeverity /// Describes useful information that does not indicate a problem. /// Info, - /// /// Describes a recoverable issue that should be reviewed. /// Warning, - /// /// Describes an issue that prevents the associated operation from succeeding. /// diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs index efb8c92a6..d1ec35c23 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs @@ -24,9 +24,13 @@ public DiagnosticSource( string displayName ) { if (string.IsNullOrWhiteSpace(id)) + { throw new ArgumentException("A diagnostic source identifier is required.", nameof(id)); + } if (string.IsNullOrWhiteSpace(displayName)) + { throw new ArgumentException("A diagnostic source display name is required.", nameof(displayName)); + } this.id = id; this.displayName = displayName; } diff --git a/src/foundation/core/Inno.Core.Diagnostics/Diagnostics.cs b/src/foundation/core/Inno.Core.Diagnostics/Diagnostics.cs index 461973c57..c4d5f21c1 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/Diagnostics.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/Diagnostics.cs @@ -54,9 +54,7 @@ public static void Set( IEnumerable diagnostics ) { ArgumentNullException.ThrowIfNull(diagnostics); - DiagnosticHub.current.Set( - DiagnosticCallerResolver.Resolve(group), - diagnostics); + DiagnosticHub.current.Set(DiagnosticCallerResolver.Resolve(group), diagnostics); } /// @@ -120,9 +118,7 @@ public static void Set( string? displayName = null ) { ArgumentNullException.ThrowIfNull(diagnostics); - DiagnosticHub.current.Set( - DiagnosticCallerResolver.Resolve(group, targetId, displayName), - diagnostics); + DiagnosticHub.current.Set(DiagnosticCallerResolver.Resolve(group, targetId, displayName), diagnostics); } /// diff --git a/src/foundation/core/Inno.Core.Events/EventDispatcher.cs b/src/foundation/core/Inno.Core.Events/EventDispatcher.cs index b749c6b09..9a8925560 100644 --- a/src/foundation/core/Inno.Core.Events/EventDispatcher.cs +++ b/src/foundation/core/Inno.Core.Events/EventDispatcher.cs @@ -46,9 +46,13 @@ public EventDispatcher( int flushBudget = 4096 ) { if (queueCapacity <= 0) + { throw new ArgumentOutOfRangeException(nameof(queueCapacity)); + } if (flushBudget <= 0) + { throw new ArgumentOutOfRangeException(nameof(flushBudget)); + } m_queueCapacity = queueCapacity; m_flushBudget = flushBudget; } @@ -91,7 +95,9 @@ public EventHub CreateHub(int order = 0) public void Enqueue(Event e) { if (!TryEnqueue(e)) + { throw new InvalidOperationException("The event queue is full; the producer must defer or reject this operation explicitly."); + } } /// @@ -168,11 +174,15 @@ public void Emit(Event e) { EventHub hub = hubs[i]; if (!hub.isValid) + { continue; + } hub.Dispatch(e); if (e.isGlobalHandled) + { break; + } } } dispatched?.Invoke(e); diff --git a/src/foundation/core/Inno.Core.Events/EventHub.cs b/src/foundation/core/Inno.Core.Events/EventHub.cs index 8e6456ef0..f3db3ed55 100644 --- a/src/foundation/core/Inno.Core.Events/EventHub.cs +++ b/src/foundation/core/Inno.Core.Events/EventHub.cs @@ -91,8 +91,7 @@ public bool isValid public IDisposable Listen( Action handler, int priority = 0 - ) - where TEvent : Event + ) where TEvent : Event { ThrowIfInvalid(); ArgumentNullException.ThrowIfNull(handler); @@ -136,8 +135,7 @@ public IDisposable Listen( public IDisposable ListenOnce( Action handler, int priority = 0 - ) - where TEvent : Event + ) where TEvent : Event { ThrowIfInvalid(); ArgumentNullException.ThrowIfNull(handler); @@ -311,6 +309,7 @@ long order /// Gets the scalar measurement or identity associated with the current state. /// public int priority { get; } = priority; + /// /// Gets the scalar measurement or identity associated with the current state. /// @@ -505,6 +504,7 @@ private sealed class HubState(Dictionary buckets) /// The empty value used as part of this type's public representation. /// public static readonly HubState Empty = new(new Dictionary()); + /// /// Gets the immutable listener buckets captured for one dispatch operation. /// diff --git a/src/foundation/core/Inno.Core.Events/Events/ApplicationEvents.cs b/src/foundation/core/Inno.Core.Events/Events/ApplicationEvents.cs index 782d622c2..533aafe02 100644 --- a/src/foundation/core/Inno.Core.Events/Events/ApplicationEvents.cs +++ b/src/foundation/core/Inno.Core.Events/Events/ApplicationEvents.cs @@ -3,13 +3,9 @@ namespace Inno.Core.Events; /// /// Base class for application lifecycle events. /// -public abstract class ApplicationEvent : Event -{ -} +public abstract class ApplicationEvent : Event; /// /// Raised when the application requests shutdown. /// -public class ApplicationQuitEvent : ApplicationEvent -{ -} +public class ApplicationQuitEvent : ApplicationEvent; diff --git a/src/foundation/core/Inno.Core.Events/Events/Event.cs b/src/foundation/core/Inno.Core.Events/Events/Event.cs index 8205b1d70..d626beaab 100644 --- a/src/foundation/core/Inno.Core.Events/Events/Event.cs +++ b/src/foundation/core/Inno.Core.Events/Events/Event.cs @@ -10,6 +10,7 @@ public abstract class Event { private readonly Event m_consumptionOwner; private int m_globalHandled; + [ThreadStatic] private static HubFrameStack? t_hubFrames; diff --git a/src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs b/src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs index ad5a3f025..b0d5ef3ab 100644 --- a/src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs +++ b/src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Input; namespace Inno.Core.Events; @@ -20,8 +19,7 @@ public abstract class KeyEvent( uint windowId, KeyCode key, KeyModifier modifiers = KeyModifier.None -) - : Event +) : Event { /// /// Gets the source window id for this event. @@ -59,8 +57,7 @@ public class KeyPressedEvent( KeyCode key, KeyModifier modifiers = KeyModifier.None, bool repeat = false -) - : KeyEvent(windowId, key, modifiers) +) : KeyEvent(windowId, key, modifiers) { /// /// Gets whether this key press is an auto-repeat event. @@ -84,10 +81,7 @@ public class KeyReleasedEvent( uint windowId, KeyCode key, KeyModifier modifiers = KeyModifier.None -) - : KeyEvent(windowId, key, modifiers) -{ -} +) : KeyEvent(windowId, key, modifiers); /// /// Raised when the platform commits UTF-8 text through keyboard, IME, or virtual-keyboard input. @@ -112,6 +106,6 @@ string text /// Gets the committed Unicode text. /// public string text { get; } = string.IsNullOrEmpty(text) - ? throw new ArgumentException("Committed text cannot be empty.", nameof(text)) - : text; + ? throw new ArgumentException("Committed text cannot be empty.", nameof(text)) + : text; } diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs b/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs index c47345aa9..5a825e954 100644 --- a/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs +++ b/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs @@ -24,7 +24,8 @@ public abstract class MouseEvent : Event /// /// The source event is null. /// - protected MouseEvent(MouseEvent source) : base(source) => windowId = source.windowId; + protected MouseEvent(MouseEvent source) + : base(source) => windowId = source.windowId; /// /// Gets the source window id for this event. @@ -32,7 +33,6 @@ public abstract class MouseEvent : Event public uint windowId { get; } } - /// /// Raised when the cursor moves. /// @@ -54,7 +54,8 @@ public MouseMovedEvent( uint windowId, float x, float y - ) : base(windowId) { + ) : base(windowId) + { this.x = x; this.y = y; } @@ -90,7 +91,8 @@ private MouseMovedEvent( MouseMovedEvent source, float x, float y - ) : base(source) { + ) : base(source) + { this.x = x; this.y = y; } @@ -157,9 +159,7 @@ MouseButton button public class MouseButtonPressedEvent( uint windowId, MouseButton button -) : MouseButtonEvent(windowId, button) -{ -} +) : MouseButtonEvent(windowId, button); /// /// Raised when a mouse button is released. @@ -173,6 +173,4 @@ MouseButton button public class MouseButtonReleasedEvent( uint windowId, MouseButton button -) : MouseButtonEvent(windowId, button) -{ -} +) : MouseButtonEvent(windowId, button); diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs b/src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs index d26700d3e..dc495032a 100644 --- a/src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs +++ b/src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs @@ -14,7 +14,6 @@ public abstract class WindowEvent(uint windowId) : Event public uint windowId { get; } = windowId; } - /// /// Raised when the window size changes. /// @@ -50,9 +49,7 @@ int height /// /// The window id used to initialize this instance. /// -public class WindowCloseEvent(uint windowId) : WindowEvent(windowId) -{ -} +public class WindowCloseEvent(uint windowId) : WindowEvent(windowId); /// /// Raised when a window gains or loses input focus. diff --git a/src/foundation/core/Inno.Core.Execution/ExecutionSlot.cs b/src/foundation/core/Inno.Core.Execution/ExecutionSlot.cs index 1b5e7a2fc..edcde2fbb 100644 --- a/src/foundation/core/Inno.Core.Execution/ExecutionSlot.cs +++ b/src/foundation/core/Inno.Core.Execution/ExecutionSlot.cs @@ -36,9 +36,10 @@ public ExecutionSlot(string name) /// /// No live binding exists on the permitted thread. /// - public TValue current => TryGet(out TValue? value) - ? value - : throw new InvalidOperationException($"No active '{m_name}' execution scope is available to this caller."); + public TValue current + => TryGet(out TValue? value) + ? value + : throw new InvalidOperationException($"No active '{m_name}' execution scope is available to this caller."); /// /// Binds a value until the returned scope is retired in strict last-in-first-out order. @@ -91,7 +92,9 @@ public bool TryGet([MaybeNullWhen(false)] out TValue value) { Binding? binding = m_current.Value; if (binding is not null) + { return binding.TryGet(out value); + } value = default; return false; } @@ -145,11 +148,17 @@ public void Dispose() lock (m_sync) { if (!m_active) + { return; + } if (!ReferenceEquals(m_slot.m_current.Value, this)) + { throw new InvalidOperationException($"'{m_slot.m_name}' scopes must retire in last-in-first-out order."); + } if (m_threadId != 0 && m_threadId != Environment.CurrentManagedThreadId) + { throw new InvalidOperationException($"'{m_slot.m_name}' must retire on its owner thread."); + } m_slot.m_current.Value = m_parent; m_active = false; m_value = default!; diff --git a/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs b/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs index 5a773d0cd..aaa992d92 100644 --- a/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs +++ b/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs @@ -48,9 +48,12 @@ public int trackedWorkCount get { lock (m_sync) + { return m_tasks.Count(static task => !task.IsCompletedSuccessfully && !task.IsCanceled); + } } } + /// /// Gets the largest simultaneous retained work count. /// @@ -59,9 +62,12 @@ public int peakTrackedWorkCount get { lock (m_sync) + { return m_peakTrackedWork; + } } } + /// /// Gets work registrations rejected before ownership transfer by finite capacity. /// @@ -70,7 +76,9 @@ public long rejectedWorkCount get { lock (m_sync) + { return m_rejectedWork; + } } } @@ -87,8 +95,11 @@ public bool isQuiescent get { lock (m_sync) - return !m_canceling && !m_disposing && m_blockedWorkFailure is null && m_tasks.All(static task => - task.IsCompleted && (task.Exception is not Exception failure || RetirementPendingException.Find(failure) is null)); + { + return !m_canceling && !m_disposing && m_blockedWorkFailure is null && m_tasks.All(static task => ( + task.IsCompleted && (task.Exception is not Exception failure || RetirementPendingException.Find(failure) is null) + )); + } } } @@ -110,7 +121,8 @@ public bool isQuiescent /// /// Retirement has already started. /// - public TResource Own(TResource resource) where TResource : IDisposable + public TResource Own(TResource resource) + where TResource : IDisposable { ArgumentNullException.ThrowIfNull(resource); lock (m_sync) @@ -179,9 +191,13 @@ public void Cancel() lock (m_sync) { if (m_blockedWorkFailure is not null) + { throw m_blockedWorkFailure; + } if (m_disposed || m_stopping) + { return; + } m_stopping = true; m_canceling = true; } @@ -192,19 +208,25 @@ public void Cancel() catch (Exception exception) when (RetirementPendingException.Find(exception) is not null) { lock (m_sync) + { m_blockedWorkFailure = exception; + } throw; } catch (Exception exception) { lock (m_sync) + { RetirementPendingException.CollectCompletedFailures(exception, m_retirementFailures); + } throw; } finally { lock (m_sync) + { m_canceling = false; + } } } @@ -226,11 +248,17 @@ public void Dispose() lock (m_sync) { if (m_blockedWorkFailure is not null) + { throw m_blockedWorkFailure; + } if (m_disposed) + { return; + } if (m_disposing) + { throw new RetirementPendingException("Another retirement attempt still owns this lifetime's resources."); + } m_disposing = true; } try @@ -249,7 +277,9 @@ public void Dispose() finally { lock (m_sync) + { m_disposing = false; + } } } @@ -279,7 +309,9 @@ public async ValueTask DisposeAsync() catch (Exception) { /* Cancel retained ordinary callback failures for the final report. */ } Task[] pending; lock (m_sync) + { pending = m_tasks.ToArray(); + } try { await Task.WhenAll(pending).ConfigureAwait(false); @@ -293,9 +325,13 @@ private void RetireResources() lock (m_sync) { if (m_disposed) + { return; + } if (m_canceling || m_tasks.Any(static task => !task.IsCompleted)) + { throw new RetirementPendingException("Lifetime work is still active. Drain it before releasing its resources."); + } foreach (Task task in m_tasks) { if (task.Exception is not null) @@ -316,7 +352,9 @@ private void RetireResources() lock (m_sync) { if (m_resources.Count == 0) + { break; + } resource = m_resources[^1]; } try @@ -333,10 +371,14 @@ private void RetireResources() m_retirementFailures.Add(exception); } lock (m_sync) + { m_resources.RemoveAt(m_resources.Count - 1); + } } lock (m_sync) + { m_disposed = true; + } m_cancellation.Dispose(); if (m_retirementFailures.Count > 0) { @@ -356,18 +398,26 @@ bool observeCompletion EnsureAccepting(); m_tasks.RemoveAll(static completed => completed.IsCompletedSuccessfully || completed.IsCanceled); if (m_tasks.Contains(task)) + { return; + } if (m_tasks.Count >= m_maxTrackedWork) { m_rejectedWork++; - throw new InvalidOperationException("The lifetime's asynchronous work capacity has been reached; ownership was not transferred."); + throw new InvalidOperationException( + "The lifetime's asynchronous work capacity has been reached; ownership was not transferred." + ); } m_tasks.Add(task); m_peakTrackedWork = Math.Max(m_peakTrackedWork, m_tasks.Count); if (!observeCompletion) + { return; + } if (ExecutionContext.IsFlowSuppressed()) + { ObserveCompletion(task); + } else { using AsyncFlowControl flow = ExecutionContext.SuppressFlow(); @@ -383,16 +433,22 @@ private void ObserveCompletion(Task task) ) => { if (!completed.IsCompletedSuccessfully && !completed.IsCanceled) + { return; + } var owner = (LifetimeScope)state!; lock (owner.m_sync) + { owner.m_tasks.Remove(completed); + } }, this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); private void EnsureAccepting() { if (m_stopping || m_disposed) + { throw new InvalidOperationException("A retiring lifetime cannot accept resources or work."); + } } private async Task CompleteOperationAsync( @@ -404,7 +460,9 @@ TaskCompletionSource completion { TResult result; using (var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, m_cancellation.Token)) + { result = await operation(linked.Token).ConfigureAwait(false); + } lock (m_sync) { completion.SetResult(result); diff --git a/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs b/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs index 627d337a3..30719f897 100644 --- a/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs +++ b/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs @@ -43,7 +43,7 @@ public static TResult Run(Func> operation) try { Task completion = operation() - ?? throw new InvalidOperationException("The owned operation returned a null task."); + ?? throw new InvalidOperationException("The owned operation returned a null task."); context.Pump(completion); return completion.GetAwaiter().GetResult(); } @@ -108,11 +108,17 @@ public override void Send( internal void Pump(Task completion) { bool notified = false; - Task notification = completion.ContinueWith(_ => m_callbacks.Add(() => notified = true), - CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + Task notification = completion.ContinueWith( + _ => m_callbacks.Add(() => notified = true), + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default + ); // Observe completion on the owner, after the wake-up item has actually been consumed. while (!notified || m_callbacks.Count != 0) + { m_callbacks.Take()(); + } notification.GetAwaiter().GetResult(); } } diff --git a/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs b/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs index c84f50e94..79e140fc0 100644 --- a/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs +++ b/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs @@ -38,7 +38,9 @@ public RetirementBarrier( m_owner = owner; m_timeout = timeout ?? TimeSpan.FromSeconds(30); if (m_timeout <= TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(timeout)); + } } /// @@ -67,11 +69,17 @@ public bool TryComplete(Action retire) { ArgumentNullException.ThrowIfNull(retire); if (m_ownerThread != Environment.CurrentManagedThreadId) + { throw new InvalidOperationException("Retirement must advance on its owner thread."); + } if (m_failure is not null) + { throw m_failure; + } if (m_completed) + { return true; + } m_elapsed ??= Stopwatch.StartNew(); try { @@ -87,24 +95,33 @@ public bool TryComplete(Action retire) throw; } if (m_elapsed.Elapsed < m_timeout) + { return false; + } m_failure = new RetirementTimeoutException( $"Owner '{m_owner}' could not retire within {m_timeout}: {pending.Message}", m_completedFailures.Count == 0 ? exception : new AggregateException( - "Retirement has unfinished work and earlier completed failures.", [.. m_completedFailures, exception])); + "Retirement has unfinished work and earlier completed failures.", + [.. m_completedFailures, exception] + ) + ); throw m_failure; } catch (Exception exception) { m_completed = true; if (m_completedFailures.Count == 0) + { throw; + } RetirementPendingException.CollectCompletedFailures(exception, m_completedFailures); throw TakeCompletedFailure(); } m_completed = true; if (m_completedFailures.Count > 0) + { throw TakeCompletedFailure(); + } return true; } @@ -120,7 +137,9 @@ public bool TryComplete(Action retire) public void Wait(Action retire) { while (!TryComplete(retire)) + { Thread.Sleep(1); + } } private AggregateException TakeCompletedFailure() diff --git a/src/foundation/core/Inno.Core.Execution/RetirementPendingException.cs b/src/foundation/core/Inno.Core.Execution/RetirementPendingException.cs index f09efe466..2d53d4af4 100644 --- a/src/foundation/core/Inno.Core.Execution/RetirementPendingException.cs +++ b/src/foundation/core/Inno.Core.Execution/RetirementPendingException.cs @@ -20,7 +20,7 @@ public class RetirementPendingException : InvalidOperationException public RetirementPendingException( string message, Exception? innerException = null - ) : base(message, innerException) { } + ) : base(message, innerException) {} /// /// Finds unfinished retirement in an exception tree without discarding its contextual or sibling failures. @@ -39,16 +39,23 @@ public RetirementPendingException( { ArgumentNullException.ThrowIfNull(exception); if (exception is RetirementPendingException pending) + { return pending.InnerException is Exception detail && Find(detail) is RetirementTimeoutException terminal - ? terminal : pending; + ? terminal + : pending; + } if (exception is not AggregateException aggregate) + { return exception.InnerException is Exception cause ? Find(cause) : null; + } RetirementPendingException? result = null; foreach (Exception inner in aggregate.InnerExceptions) { RetirementPendingException? found = Find(inner); if (found is RetirementTimeoutException) + { return found; + } result ??= found; } return result; @@ -75,13 +82,17 @@ ICollection failures if (exception is RetirementPendingException pending) { if (pending.InnerException is Exception detail) + { CollectCompletedFailures(detail, failures); + } return; } if (exception is AggregateException aggregate) { foreach (Exception inner in aggregate.InnerExceptions) + { CollectCompletedFailures(inner, failures); + } return; } if (Find(exception) is not null && exception.InnerException is Exception cause) @@ -90,8 +101,12 @@ ICollection failures return; } foreach (Exception previous in failures) + { if (ReferenceEquals(previous, exception)) + { return; + } + } failures.Add(exception); } } diff --git a/src/foundation/core/Inno.Core.Execution/RetirementTimeoutException.cs b/src/foundation/core/Inno.Core.Execution/RetirementTimeoutException.cs index 8d1958787..b95e82e5c 100644 --- a/src/foundation/core/Inno.Core.Execution/RetirementTimeoutException.cs +++ b/src/foundation/core/Inno.Core.Execution/RetirementTimeoutException.cs @@ -19,5 +19,5 @@ public sealed class RetirementTimeoutException : RetirementPendingException public RetirementTimeoutException( string message, Exception? innerException = null - ) : base(message, innerException) { } + ) : base(message, innerException) {} } diff --git a/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs b/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs index dfe498956..6a683b7bd 100644 --- a/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs +++ b/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs @@ -282,7 +282,9 @@ public void ReplaceContents(GraphDocument source) m_nodes.AddRange(nodes); m_nodeIndex.Clear(); foreach ((GraphNodeId id, GraphNodeRecord node) in nodeIndex) + { m_nodeIndex.Add(id, node); + } m_edges.Clear(); m_edges.AddRange(edges); m_metadata.Clear(); diff --git a/src/foundation/core/Inno.Core.Graphs/GraphDocumentCodec.cs b/src/foundation/core/Inno.Core.Graphs/GraphDocumentCodec.cs index d470d1bb4..a03efce4a 100644 --- a/src/foundation/core/Inno.Core.Graphs/GraphDocumentCodec.cs +++ b/src/foundation/core/Inno.Core.Graphs/GraphDocumentCodec.cs @@ -48,7 +48,8 @@ SerializationRegistry serialization { valueWriter.Write("id", pair.Key); valueWriter.Write("data", pair.Value.ToArray()); - }); + } + ); }); writer.WriteObjectArray("edges", document.edges, static ( edgeWriter, @@ -71,7 +72,8 @@ SerializationRegistry serialization { metadataWriter.Write("id", pair.Key); metadataWriter.Write("data", pair.Value.ToArray()); - }); + } + ); }); } @@ -99,36 +101,45 @@ SerializationRegistry serialization { var node = new GraphNodeRecord( new GraphNodeId(nodeReader.Read("id")), - nodeReader.Read("definition")) + nodeReader.Read("definition") + ) { position = new GraphPosition( nodeReader.Read("positionX"), - nodeReader.Read("positionY")) + nodeReader.Read("positionY") + ) }; foreach (SerializationReader valueReader in nodeReader.ReadObjectArray("values")) { node.SetValue( valueReader.Read("id"), - new GraphSerializedValue(valueReader.Read("data"))); + new GraphSerializedValue(valueReader.Read("data")) + ); } document.AddNode(node); } foreach (SerializationReader edgeReader in reader.ReadObjectArray("edges")) { - document.AddEdge(new GraphEdgeRecord( - new GraphEdgeId(edgeReader.Read("id")), - new GraphEndpoint( - new GraphNodeId(edgeReader.Read("outputNode")), - new GraphPortId(edgeReader.Read("outputPort"))), - new GraphEndpoint( - new GraphNodeId(edgeReader.Read("inputNode")), - new GraphPortId(edgeReader.Read("inputPort"))))); + document.AddEdge( + new GraphEdgeRecord( + new GraphEdgeId(edgeReader.Read("id")), + new GraphEndpoint( + new GraphNodeId(edgeReader.Read("outputNode")), + new GraphPortId(edgeReader.Read("outputPort")) + ), + new GraphEndpoint( + new GraphNodeId(edgeReader.Read("inputNode")), + new GraphPortId(edgeReader.Read("inputPort")) + ) + ) + ); } foreach (SerializationReader metadataReader in reader.ReadObjectArray("metadata")) { document.SetMetadata( metadataReader.Read("id"), - new GraphSerializedValue(metadataReader.Read("data"))); + new GraphSerializedValue(metadataReader.Read("data")) + ); } return document; }); diff --git a/src/foundation/core/Inno.Core.Graphs/GraphSerializedValue.cs b/src/foundation/core/Inno.Core.Graphs/GraphSerializedValue.cs index b53620f4c..1d98f2b02 100644 --- a/src/foundation/core/Inno.Core.Graphs/GraphSerializedValue.cs +++ b/src/foundation/core/Inno.Core.Graphs/GraphSerializedValue.cs @@ -23,7 +23,9 @@ public sealed class GraphSerializedValue public GraphSerializedValue(ReadOnlySpan data) { if (data.IsEmpty) + { throw new ArgumentException("A graph value payload cannot be empty.", nameof(data)); + } m_data = data.ToArray(); } diff --git a/src/foundation/core/Inno.Core.Graphs/GraphValidation.cs b/src/foundation/core/Inno.Core.Graphs/GraphValidation.cs index f0869d9b1..4420acf5a 100644 --- a/src/foundation/core/Inno.Core.Graphs/GraphValidation.cs +++ b/src/foundation/core/Inno.Core.Graphs/GraphValidation.cs @@ -1,9 +1,8 @@ -using Inno.Core.Diagnostics; using System; -using System.Linq; using System.Collections.Generic; - +using System.Linq; using Inno.Core.Collections; +using Inno.Core.Diagnostics; namespace Inno.Core.Graphs; @@ -173,11 +172,14 @@ List diagnostics { if (!resolver.TryResolve(node.definitionId, out GraphNodeDefinition? definition) || definition is null) { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_MISSING_NODE", - $"Node definition '{node.definitionId}' is not active. The node and its connections were preserved.", - DiagnosticSeverity.Warning, - node.id)); + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_MISSING_NODE", + $"Node definition '{node.definitionId}' is not active. The node and its connections were preserved.", + DiagnosticSeverity.Warning, + node.id + ) + ); continue; } @@ -188,11 +190,14 @@ List diagnostics { if (!ports.TryAdd(port.id, port)) { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_DUPLICATE_PORT", - $"Node definition '{node.definitionId}' returned duplicate port '{port.id}'.", - DiagnosticSeverity.Error, - node.id)); + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_DUPLICATE_PORT", + $"Node definition '{node.definitionId}' returned duplicate port '{port.id}'.", + DiagnosticSeverity.Error, + node.id + ) + ); } } @@ -200,11 +205,14 @@ List diagnostics } catch (Exception exception) { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_NODE_RESOLUTION_FAILED", - $"Node '{node.id}' could not resolve its ports: {exception.Message}", - DiagnosticSeverity.Error, - node.id)); + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_NODE_RESOLUTION_FAILED", + $"Node '{node.id}' could not resolve its ports: {exception.Message}", + DiagnosticSeverity.Error, + node.id + ) + ); } } } @@ -223,24 +231,30 @@ List diagnostics GraphNodeRecord? inputNode = document.FindNode(edge.input.nodeId); if (outputNode is null || inputNode is null) { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_MISSING_ENDPOINT_NODE", - $"Edge '{edge.id}' references a node that is not present in the document.", - DiagnosticSeverity.Error, - edgeId: edge.id)); + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_MISSING_ENDPOINT_NODE", + $"Edge '{edge.id}' references a node that is not present in the document.", + DiagnosticSeverity.Error, + edgeId: edge.id + ) + ); continue; } if (!TryGetPort(portsByNode, edge.output, out GraphPortDefinition outputPort) - || !TryGetPort(portsByNode, edge.input, out GraphPortDefinition inputPort)) - { + || !TryGetPort(portsByNode, edge.input, out GraphPortDefinition inputPort) + ) { if (portsByNode.ContainsKey(edge.output.nodeId) && portsByNode.ContainsKey(edge.input.nodeId)) { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_MISSING_ENDPOINT_PORT", - $"Edge '{edge.id}' references a port that is not active on its node.", - DiagnosticSeverity.Error, - edgeId: edge.id)); + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_MISSING_ENDPOINT_PORT", + $"Edge '{edge.id}' references a port that is not active on its node.", + DiagnosticSeverity.Error, + edgeId: edge.id + ) + ); } continue; @@ -248,22 +262,28 @@ List diagnostics if (outputPort.direction != GraphPortDirection.Output || inputPort.direction != GraphPortDirection.Input) { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_INVALID_DIRECTION", - $"Edge '{edge.id}' must connect an output port to an input port.", - DiagnosticSeverity.Error, - edgeId: edge.id)); + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_INVALID_DIRECTION", + $"Edge '{edge.id}' must connect an output port to an input port.", + DiagnosticSeverity.Error, + edgeId: edge.id + ) + ); } bool compatible = StringComparer.Ordinal.Equals(outputPort.valueTypeId, inputPort.valueTypeId) - || (conversion?.CanConvert(outputPort.valueTypeId, inputPort.valueTypeId) ?? false); + || (conversion?.CanConvert(outputPort.valueTypeId, inputPort.valueTypeId) ?? false); if (!compatible) { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_INCOMPATIBLE_TYPES", - $"Edge '{edge.id}' cannot convert '{outputPort.valueTypeId}' to '{inputPort.valueTypeId}'.", - DiagnosticSeverity.Error, - edgeId: edge.id)); + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_INCOMPATIBLE_TYPES", + $"Edge '{edge.id}' cannot convert '{outputPort.valueTypeId}' to '{inputPort.valueTypeId}'.", + DiagnosticSeverity.Error, + edgeId: edge.id + ) + ); } CountConnection(edge.output, outputPort, connectionCounts, edge.id, diagnostics); @@ -283,12 +303,15 @@ List diagnostics connectionCounts[endpoint] = currentCount; if (port.capacity == GraphPortCapacity.Single && currentCount > 1) { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_PORT_CAPACITY", - $"Port '{endpoint.portId}' accepts only one connection.", - DiagnosticSeverity.Error, - endpoint.nodeId, - edgeId)); + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_PORT_CAPACITY", + $"Port '{endpoint.portId}' accepts only one connection.", + DiagnosticSeverity.Error, + endpoint.nodeId, + edgeId + ) + ); } } @@ -309,13 +332,16 @@ List diagnostics { if (port.direction == GraphPortDirection.Input && port.required - && !connectedInputs.Contains(new GraphEndpoint(nodeId, port.id))) - { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_REQUIRED_INPUT", - $"Required input '{port.displayName}' is not connected.", - DiagnosticSeverity.Error, - nodeId)); + && !connectedInputs.Contains(new GraphEndpoint(nodeId, port.id)) + ) { + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_REQUIRED_INPUT", + $"Required input '{port.displayName}' is not connected.", + DiagnosticSeverity.Error, + nodeId + ) + ); } } } @@ -327,21 +353,28 @@ List diagnostics ) { var graph = new DependencyGraph(); foreach (GraphNodeRecord node in document.nodes) + { graph.AddNode(node.id); + } foreach (GraphEdgeRecord edge in document.edges) { if (graph.ContainsNode(edge.output.nodeId) && graph.ContainsNode(edge.input.nodeId)) + { graph.AddDependency(edge.input.nodeId, edge.output.nodeId); + } } if (graph.TryFindCycle(out IReadOnlyList cycle)) { - diagnostics.Add(new GraphDiagnostic( - "GRAPH_CYCLE", - "The graph contains a directed cycle.", - DiagnosticSeverity.Error, - cycle[0])); + diagnostics.Add( + new GraphDiagnostic( + "GRAPH_CYCLE", + "The graph contains a directed cycle.", + DiagnosticSeverity.Error, + cycle[0] + ) + ); } } @@ -350,11 +383,9 @@ private static bool TryGetPort( GraphEndpoint endpoint, out GraphPortDefinition port ) { - if (portsByNode.TryGetValue( - endpoint.nodeId, - out IReadOnlyDictionary? ports) - && ports.TryGetValue(endpoint.portId, out GraphPortDefinition? resolved)) - { + if (portsByNode.TryGetValue(endpoint.nodeId, out IReadOnlyDictionary? ports) + && ports.TryGetValue(endpoint.portId, out GraphPortDefinition? resolved) + ) { port = resolved; return true; } diff --git a/src/foundation/core/Inno.Core.Graphs/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Graphs/Properties/ScriptingApi.cs index 3c3fefa98..4879f9e41 100644 --- a/src/foundation/core/Inno.Core.Graphs/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Graphs/Properties/ScriptingApi.cs @@ -2,10 +2,7 @@ using Inno.Core.Graphs; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Graphs", - "Inno.Core.Graphs", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Graphs", "Inno.Core.Graphs", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(GraphNodeId), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(GraphEdgeId), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs b/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs index 34f20eca0..989625f7d 100644 --- a/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs +++ b/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs @@ -52,13 +52,19 @@ public static void Publish( string candidate = Path.GetFullPath(source); string target = Path.GetFullPath(destination); if (IsContained(Path.GetRelativePath(candidate, target)) - || IsContained(Path.GetRelativePath(target, candidate))) + || IsContained(Path.GetRelativePath(target, candidate)) + ) { throw new ArgumentException("The candidate and destination directory trees must be disjoint.", nameof(destination)); + } if (!Directory.Exists(candidate)) + { throw new DirectoryNotFoundException($"Directory candidate '{candidate}' does not exist."); + } string? parent = Path.GetDirectoryName(target); if (string.IsNullOrEmpty(parent)) + { throw new IOException($"Directory path '{target}' has no owning directory."); + } Directory.CreateDirectory(parent); FileSystemRename.MoveDirectory(candidate, target, cancellationToken); } @@ -116,17 +122,25 @@ public static void Install( string relativeTarget = Path.GetRelativePath(candidate, target); string relativeCandidate = Path.GetRelativePath(target, candidate); if (IsContained(relativeTarget) || IsContained(relativeCandidate)) + { throw new ArgumentException("The candidate and destination directory trees must be disjoint.", nameof(destination)); + } if (!Directory.Exists(candidate)) + { throw new DirectoryNotFoundException($"Atomic directory candidate '{candidate}' does not exist."); + } string? parent = Path.GetDirectoryName(target); if (string.IsNullOrEmpty(parent)) + { throw new IOException($"Directory path '{target}' has no owning directory."); + } Directory.CreateDirectory(parent); string backup = target + ".backup-" + Guid.NewGuid().ToString("N"); if (Directory.Exists(target)) + { FileSystemRename.MoveDirectory(target, backup, cancellationToken); + } try { FileSystemRename.MoveDirectory(candidate, target, cancellationToken); @@ -144,14 +158,17 @@ public static void Install( throw new AggregateException( $"Directory installation failed; the previous tree remains at '{backup}' and could not be restored to '{target}'.", installationFailure, - restorationFailure); + restorationFailure + ); } } throw; } if (!Directory.Exists(backup)) + { return; + } try { Directory.Delete(backup, recursive: true); diff --git a/src/foundation/core/Inno.Core.IO/AtomicFile.cs b/src/foundation/core/Inno.Core.IO/AtomicFile.cs index 9d6d72289..e2f4eeb47 100644 --- a/src/foundation/core/Inno.Core.IO/AtomicFile.cs +++ b/src/foundation/core/Inno.Core.IO/AtomicFile.cs @@ -31,7 +31,7 @@ public static bool IsCandidatePath(string path) ReadOnlySpan name = Path.GetFileName(path.AsSpan()); int marker = name.Length - C_CANDIDATE_MARKER.Length - 32; return marker > 0 && name.Slice(marker, C_CANDIDATE_MARKER.Length).SequenceEqual(C_CANDIDATE_MARKER) - && Guid.TryParseExact(name[(marker + C_CANDIDATE_MARKER.Length)..], "N", out _); + && Guid.TryParseExact(name[(marker + C_CANDIDATE_MARKER.Length)..], "N", out _); } /// @@ -63,13 +63,13 @@ public static void WriteAllBytes( try { using (var stream = new FileStream( - candidate, - FileMode.CreateNew, - FileAccess.Write, - FileShare.None, - 32 * 1024, - FileOptions.WriteThrough)) - { + candidate, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + 32 * 1024, + FileOptions.WriteThrough + )) { stream.Write(data); stream.Flush(flushToDisk: true); } @@ -78,7 +78,9 @@ public static void WriteAllBytes( finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } } @@ -116,16 +118,23 @@ public static void Install( string candidate = Path.GetFullPath(source); string target = NormalizeDestination(destination); if (!File.Exists(candidate)) + { throw new FileNotFoundException("The atomic file candidate does not exist.", candidate); + } if (string.Equals(candidate, target, StringComparison.OrdinalIgnoreCase)) + { throw new ArgumentException("The atomic file candidate and destination must be different paths.", nameof(source)); + } string candidateDirectory = Path.GetDirectoryName(candidate)!; string targetDirectory = Path.GetDirectoryName(target)!; if (!string.Equals(candidateDirectory, targetDirectory, StringComparison.Ordinal)) + { throw new ArgumentException( "Atomic file installation requires the candidate and destination to share a directory.", - nameof(source)); + nameof(source) + ); + } FileSystemRename.MoveFile(candidate, target, overwrite); } @@ -136,9 +145,10 @@ private static string NormalizeDestination(string path) string destination = Path.GetFullPath(path); string? directory = Path.GetDirectoryName(destination); if (string.IsNullOrEmpty(directory)) + { throw new IOException($"File path '{destination}' has no owning directory."); + } Directory.CreateDirectory(directory); return destination; } - } diff --git a/src/foundation/core/Inno.Core.IO/CoordinatedFileLease.cs b/src/foundation/core/Inno.Core.IO/CoordinatedFileLease.cs index e1926d922..506e53716 100644 --- a/src/foundation/core/Inno.Core.IO/CoordinatedFileLease.cs +++ b/src/foundation/core/Inno.Core.IO/CoordinatedFileLease.cs @@ -60,26 +60,36 @@ public static async ValueTask AcquireAsync( CancellationToken cancellationToken = default ) { if (!Path.IsPathFullyQualified(coordinationPath) || !Path.IsPathFullyQualified(leafPath)) + { throw new ArgumentException("Coordinated leases require absolute owner and leaf paths."); + } string ownerPath = Path.GetFullPath(coordinationPath); string leaf = Path.GetFullPath(leafPath); string root = Path.GetDirectoryName(ownerPath)!; PathBoundary.RequireUnlinkedPath(root, leaf); if (string.Equals(ownerPath, leaf, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + { throw new ArgumentException("The leaf must differ from its persistent owner gate.", nameof(leafPath)); + } if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan) + { throw new ArgumentOutOfRangeException(nameof(timeout)); + } Stopwatch elapsed = Stopwatch.StartNew(); if (!File.Exists(ownerPath)) + { using (await FileLease.AcquireAsync(ownerPath, Remaining(), cancellationToken).ConfigureAwait(false)) { } + } FileLease owner = await FileLease.AcquireSharedAsync(ownerPath, Remaining(), cancellationToken).ConfigureAwait(false); try { if (shared && !File.Exists(leaf)) + { using (await FileLease.AcquireAsync(leaf, Remaining(), cancellationToken).ConfigureAwait(false)) { } + } FileLease acquired = shared - ? await FileLease.AcquireSharedAsync(leaf, Remaining(), cancellationToken).ConfigureAwait(false) - : await FileLease.AcquireAsync(leaf, Remaining(), cancellationToken).ConfigureAwait(false); + ? await FileLease.AcquireSharedAsync(leaf, Remaining(), cancellationToken).ConfigureAwait(false) + : await FileLease.AcquireAsync(leaf, Remaining(), cancellationToken).ConfigureAwait(false); return new(owner, acquired); } catch @@ -88,8 +98,10 @@ public static async ValueTask AcquireAsync( throw; } - TimeSpan Remaining() => timeout == Timeout.InfiniteTimeSpan ? timeout - : timeout > elapsed.Elapsed ? timeout - elapsed.Elapsed : TimeSpan.Zero; + TimeSpan Remaining() + => timeout == Timeout.InfiniteTimeSpan + ? timeout + : timeout > elapsed.Elapsed ? timeout - elapsed.Elapsed : TimeSpan.Zero; } /// @@ -99,7 +111,9 @@ public void Dispose() { FileLease? leaf = Interlocked.Exchange(ref m_leaf, null); if (leaf is null) + { return; + } try { leaf.Dispose(); diff --git a/src/foundation/core/Inno.Core.IO/DirectoryCleanupException.cs b/src/foundation/core/Inno.Core.IO/DirectoryCleanupException.cs index 2b96829d2..173d8e814 100644 --- a/src/foundation/core/Inno.Core.IO/DirectoryCleanupException.cs +++ b/src/foundation/core/Inno.Core.IO/DirectoryCleanupException.cs @@ -13,8 +13,12 @@ internal DirectoryCleanupException( string installedDirectory, string backupDirectory, Exception cleanupFailure - ) : base($"Directory '{installedDirectory}' was installed, but backup cleanup failed. " - + $"The remaining backup is at '{backupDirectory}'.", cleanupFailure) { + ) : base( + $"Directory '{installedDirectory}' was installed, but backup cleanup failed. " + + $"The remaining backup is at '{backupDirectory}'.", + cleanupFailure + ) + { this.installedDirectory = installedDirectory; this.backupDirectory = backupDirectory; } diff --git a/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs b/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs index 9c8695b7d..cdb4f140b 100644 --- a/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs +++ b/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs @@ -23,7 +23,9 @@ public FileByteDocumentStore(string path) { ArgumentException.ThrowIfNullOrWhiteSpace(path); if (!Path.IsPathFullyQualified(path)) + { throw new ArgumentException("A file document requires an absolute path.", nameof(path)); + } m_path = Path.GetFullPath(path); } @@ -54,7 +56,9 @@ public FileByteDocumentStore(string path) using var stream = new FileStream(m_path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); long length = stream.Length; if (length > Array.MaxLength) + { throw new IOException("The file document exceeds the maximum supported byte-array size."); + } byte[] data = GC.AllocateUninitializedArray((int)length); stream.ReadExactly(data); return data; diff --git a/src/foundation/core/Inno.Core.IO/FileLease.cs b/src/foundation/core/Inno.Core.IO/FileLease.cs index 5ca5b19b2..cf3709ef4 100644 --- a/src/foundation/core/Inno.Core.IO/FileLease.cs +++ b/src/foundation/core/Inno.Core.IO/FileLease.cs @@ -53,8 +53,14 @@ public static async ValueTask AcquireAsync( string path, TimeSpan timeout, CancellationToken cancellationToken = default - ) => await AcquireCoreAsync(path, timeout, FileMode.OpenOrCreate, FileAccess.ReadWrite, - FileShare.None, cancellationToken).ConfigureAwait(false); + ) => await AcquireCoreAsync( + path, + timeout, + FileMode.OpenOrCreate, + FileAccess.ReadWrite, + FileShare.None, + cancellationToken + ).ConfigureAwait(false); /// /// Pins an existing generation against exclusive retirement while permitting other readers. @@ -84,8 +90,14 @@ public static async ValueTask AcquireSharedAsync( string path, TimeSpan timeout, CancellationToken cancellationToken = default - ) => await AcquireCoreAsync(path, timeout, FileMode.Open, FileAccess.Read, - FileShare.Read, cancellationToken).ConfigureAwait(false); + ) => await AcquireCoreAsync( + path, + timeout, + FileMode.Open, + FileAccess.Read, + FileShare.Read, + cancellationToken + ).ConfigureAwait(false); /// /// Releases ownership; repeated disposal has no effect and the lease file is retained. @@ -102,9 +114,13 @@ CancellationToken cancellationToken ) { ArgumentException.ThrowIfNullOrWhiteSpace(path); if (!Path.IsPathFullyQualified(path)) + { throw new ArgumentException("A file lease requires an absolute path.", nameof(path)); + } if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan) + { throw new ArgumentOutOfRangeException(nameof(timeout)); + } cancellationToken.ThrowIfCancellationRequested(); Directory.CreateDirectory(Path.GetDirectoryName(path)!); Stopwatch elapsed = Stopwatch.StartNew(); @@ -124,19 +140,25 @@ CancellationToken cancellationToken catch (IOException failure) when (IsCompetingOwnership(failure)) { if (timeout != Timeout.InfiniteTimeSpan && elapsed.Elapsed >= timeout) + { throw new TimeoutException($"File ownership timed out at '{path}'.", failure); + } TimeSpan delay = TimeSpan.FromMilliseconds(20); if (timeout != Timeout.InfiniteTimeSpan && timeout - elapsed.Elapsed < delay) + { delay = timeout - elapsed.Elapsed; + } if (delay > TimeSpan.Zero) + { await Task.Delay(delay, cancellationToken).ConfigureAwait(false); + } } } } private static bool IsCompetingOwnership(IOException failure) // .NET reports Unix flock contention as raw errno; Darwin uses EWOULDBLOCK 35. - => OperatingSystem.IsWindows() ? (failure.HResult & 0xffff) is 32 or 33 - : failure.HResult == (OperatingSystem.IsMacOS() ? 35 : 11); - + => OperatingSystem.IsWindows() + ? (failure.HResult & 0xffff) is 32 or 33 + : failure.HResult == (OperatingSystem.IsMacOS() ? 35 : 11); } diff --git a/src/foundation/core/Inno.Core.IO/FileSystemRename.cs b/src/foundation/core/Inno.Core.IO/FileSystemRename.cs index 41cb8e0cd..5c6f1b74d 100644 --- a/src/foundation/core/Inno.Core.IO/FileSystemRename.cs +++ b/src/foundation/core/Inno.Core.IO/FileSystemRename.cs @@ -48,14 +48,18 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); if (Stopwatch.GetElapsedTime(started).TotalMilliseconds >= C_RETRY_WINDOW_MILLISECONDS) + { throw; + } // Windows readers and indexers may briefly open files without delete sharing. // Retry only the atomic rename; permanent access failures retain their original exception. if (cancellationToken.CanBeCanceled) { if (cancellationToken.WaitHandle.WaitOne(C_RETRY_INTERVAL_MILLISECONDS)) + { cancellationToken.ThrowIfCancellationRequested(); + } } else { @@ -69,5 +73,5 @@ private static bool IsTemporarilyBlocked(Exception exception) => OperatingSystem.IsWindows() && exception is IOException or UnauthorizedAccessException && exception.HResult is unchecked((int)0x80070005) - or unchecked((int)0x80070020) or unchecked((int)0x80070021); + or unchecked((int)0x80070020) or unchecked((int)0x80070021); } diff --git a/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs b/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs index eb142ee3b..45395d238 100644 --- a/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs +++ b/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs @@ -34,19 +34,25 @@ IDisposable owner ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(owner); if (!input.CanRead) + { throw new ArgumentException("An owned read stream requires readable input.", nameof(input)); + } m_input = input; m_owner = owner; } /// public override bool CanRead => !m_inputClosed && m_input.CanRead; + /// public override bool CanSeek => !m_inputClosed && m_input.CanSeek; + /// public override bool CanWrite => false; + /// public override long Length => m_input.Length; + /// public override long Position { @@ -60,15 +66,19 @@ public override int Read( int offset, int count ) => m_input.Read(buffer, offset, count); + /// public override int Read(Span buffer) => m_input.Read(buffer); + /// public override int ReadByte() => m_input.ReadByte(); + /// public override ValueTask ReadAsync( Memory buffer, CancellationToken cancellationToken = default ) => m_input.ReadAsync(buffer, cancellationToken); + /// public override Task ReadAsync( byte[] buffer, @@ -76,15 +86,19 @@ public override Task ReadAsync( int count, CancellationToken cancellationToken ) => m_input.ReadAsync(buffer, offset, count, cancellationToken); + /// public override long Seek( long offset, SeekOrigin origin ) => m_input.Seek(offset, origin); + /// public override void Flush() => throw new NotSupportedException(); + /// public override void SetLength(long value) => throw new NotSupportedException(); + /// public override void Write( byte[] buffer, diff --git a/src/foundation/core/Inno.Core.IO/PathBoundary.cs b/src/foundation/core/Inno.Core.IO/PathBoundary.cs index dab3ee47d..dd0c0e009 100644 --- a/src/foundation/core/Inno.Core.IO/PathBoundary.cs +++ b/src/foundation/core/Inno.Core.IO/PathBoundary.cs @@ -1,6 +1,6 @@ using System; -using System.IO; using System.Collections.Generic; +using System.IO; namespace Inno.Core.IO; @@ -33,7 +33,9 @@ string relativePath ArgumentException.ThrowIfNullOrWhiteSpace(root); ArgumentNullException.ThrowIfNull(relativePath); if (Path.IsPathRooted(relativePath)) + { throw new ArgumentException("A contained path must be relative.", nameof(relativePath)); + } string normalizedRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); string candidate = Path.GetFullPath(relativePath.Length == 0 ? "." : relativePath, normalizedRoot); EnsureContains(normalizedRoot, candidate); @@ -94,7 +96,8 @@ string path if (!string.Equals(normalizedRoot, candidate, StringComparison.Ordinal)) { string prefix = Path.EndsInDirectorySeparator(normalizedRoot) - ? normalizedRoot : normalizedRoot + Path.DirectorySeparatorChar; + ? normalizedRoot + : normalizedRoot + Path.DirectorySeparatorChar; string relative = candidate[prefix.Length..]; foreach (string segment in relative.Split(Path.DirectorySeparatorChar)) { @@ -135,7 +138,9 @@ public static IEnumerable EnumerateFiles(string root) ArgumentException.ThrowIfNullOrWhiteSpace(root); string normalizedRoot = Path.GetFullPath(root); if (!Directory.Exists(normalizedRoot)) + { throw new DirectoryNotFoundException($"Owned directory '{normalizedRoot}' does not exist."); + } var pending = new Stack(); pending.Push(normalizedRoot); while (pending.Count > 0) @@ -146,9 +151,13 @@ public static IEnumerable EnumerateFiles(string root) { FileAttributes attributes = RequireRegularEntry(entry); if ((attributes & FileAttributes.Directory) != 0) + { pending.Push(entry); + } else + { yield return entry; + } } } } @@ -157,7 +166,9 @@ private static FileAttributes RequireRegularEntry(string path) { FileAttributes attributes = File.GetAttributes(path); if ((attributes & FileAttributes.ReparsePoint) != 0) + { throw new IOException($"Owned filesystem entry '{path}' cannot be a link or reparse point."); + } return attributes; } @@ -167,8 +178,8 @@ string candidate ) { string prefix = Path.EndsInDirectorySeparator(root) ? root : root + Path.DirectorySeparatorChar; if (!string.Equals(candidate, root, StringComparison.Ordinal) - && !candidate.StartsWith(prefix, StringComparison.Ordinal)) - { + && !candidate.StartsWith(prefix, StringComparison.Ordinal) + ) { throw new IOException($"Path '{candidate}' escapes filesystem boundary '{root}'."); } } diff --git a/src/foundation/core/Inno.Core.IO/PhysicalPathResolver.cs b/src/foundation/core/Inno.Core.IO/PhysicalPathResolver.cs index 188c07d30..6e3d54a8c 100644 --- a/src/foundation/core/Inno.Core.IO/PhysicalPathResolver.cs +++ b/src/foundation/core/Inno.Core.IO/PhysicalPathResolver.cs @@ -61,9 +61,13 @@ public string Resolve(string path) private string ResolveCore(string path) { if (m_paths.TryGetValue(path, out string? cached)) + { return cached; + } if (!m_resolving.Add(path)) + { throw new IOException($"Filesystem alias '{path}' forms a resolution cycle."); + } try { string? parent = Path.GetDirectoryName(path); @@ -79,9 +83,14 @@ private string ResolveCore(string path) if ((attributes & FileAttributes.ReparsePoint) != 0) { FileSystemInfo entry = (attributes & FileAttributes.Directory) != 0 - ? new DirectoryInfo(candidate) : new FileInfo(candidate); - resolved = ResolveCore(Path.GetFullPath(entry.ResolveLinkTarget(returnFinalTarget: true)?.FullName - ?? throw new IOException($"Filesystem alias '{candidate}' has no resolvable target."))); + ? new DirectoryInfo(candidate) + : new FileInfo(candidate); + resolved = ResolveCore( + Path.GetFullPath( + entry.ResolveLinkTarget(returnFinalTarget: true)?.FullName + ?? throw new IOException($"Filesystem alias '{candidate}' has no resolvable target.") + ) + ); } m_paths.Add(path, resolved); return resolved; diff --git a/src/foundation/core/Inno.Core.IO/PosixFilePublication.cs b/src/foundation/core/Inno.Core.IO/PosixFilePublication.cs index 517daad74..3f4206bee 100644 --- a/src/foundation/core/Inno.Core.IO/PosixFilePublication.cs +++ b/src/foundation/core/Inno.Core.IO/PosixFilePublication.cs @@ -18,15 +18,19 @@ string destination } catch (Exception exception) when (exception is DllNotFoundException or EntryPointNotFoundException or PlatformNotSupportedException) { - throw new PlatformNotSupportedException("The host does not provide atomic create-only file publication through POSIX link.", exception); + throw new PlatformNotSupportedException( + "The host does not provide atomic create-only file publication through POSIX link.", + exception + ); } if (result != 0) { int error = Marshal.GetLastPInvokeError(); throw new IOException( - $"Atomic create-only publication of '{source}' at '{destination}' failed (errno {error}). " + - "The destination was not replaced; the filesystem must support same-directory hard links.", - new Win32Exception(error)); + $"Atomic create-only publication of '{source}' at '{destination}' failed (errno {error}). " + + "The destination was not replaced; the filesystem must support same-directory hard links.", + new Win32Exception(error) + ); } try diff --git a/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs b/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs index e2c98986d..586509ed6 100644 --- a/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs +++ b/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs @@ -72,25 +72,38 @@ public static async ValueTask CreateForProcessAsync( ) { ArgumentException.ThrowIfNullOrWhiteSpace(root); if (!Path.IsPathFullyQualified(root) || identity is null || identity.Length != 32 - || identity.Any(static character => !Uri.IsHexDigit(character))) + || identity.Any(static character => !Uri.IsHexDigit(character)) + ) { throw new ArgumentException("Process storage requires an absolute producer root and current operation identity."); + } root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); if (root == Path.GetPathRoot(root)) + { throw new ArgumentException("Process storage cannot manage a filesystem root.", nameof(root)); + } string path = PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, identity)); string record = RecordPath(root, identity); - using CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync(Path.Combine(root, "owner.lock"), path + ".work.lock", TimeSpan.FromSeconds(30), cancellationToken: cancellationToken).ConfigureAwait(false); + using CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync( + Path.Combine(root, "owner.lock"), + path + ".work.lock", + TimeSpan.FromSeconds(30), + cancellationToken: cancellationToken + ).ConfigureAwait(false); if (File.Exists(record)) { Claim claim = ReadClaim(record); if (claim.directory != identity || QueryOwners(record, null) != ProcessOwnerState.Active) + { throw new InvalidDataException("Process storage cannot reuse an exited or unverifiable operation claim."); + } RegisterProcess(root, path); } else { if (Directory.Exists(path)) + { throw new InvalidDataException("An existing unregistered process directory cannot be adopted."); + } ProcessOwnerStamp owner = ProcessOwnerStamp.CaptureCurrent(); WriteClaim(record, new Claim(identity, owner.processId, owner.startedUtcTicks)); Directory.CreateDirectory(path); @@ -125,23 +138,38 @@ public static async ValueTask CreateAsync( ) { ArgumentException.ThrowIfNullOrWhiteSpace(root); if (!Path.IsPathFullyQualified(root) || Path.TrimEndingDirectorySeparator(root) == Path.GetPathRoot(root)) + { throw new ArgumentException("Temporary ownership requires an explicit child root.", nameof(root)); + } root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); PathBoundary.RequireUnlinkedPath(root, root); string relative = Guid.NewGuid().ToString("N"); string path = Path.Combine(root, relative); string record = RecordPath(root, relative); - CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync(Path.Combine(root, "owner.lock"), path + ".work.lock", TimeSpan.FromSeconds(30), cancellationToken: cancellationToken).ConfigureAwait(false); + CoordinatedFileLease lease = await CoordinatedFileLease.AcquireAsync( + Path.Combine(root, "owner.lock"), + path + ".work.lock", + TimeSpan.FromSeconds(30), + cancellationToken: cancellationToken + ).ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); if (Directory.Exists(path) || File.Exists(record)) + { throw new IOException("A fresh temporary identity already exists and cannot be adopted."); + } ProcessOwnerStamp owner = ProcessOwnerStamp.CaptureCurrent(); WriteClaim(record, new Claim(relative, owner.processId, owner.startedUtcTicks)); Directory.CreateDirectory(path); lease.Dispose(); - CoordinatedFileLease reading = await CoordinatedFileLease.AcquireAsync(Path.Combine(root, "owner.lock"), path + ".work.lock", TimeSpan.FromSeconds(30), shared: true, cancellationToken: cancellationToken).ConfigureAwait(false); + CoordinatedFileLease reading = await CoordinatedFileLease.AcquireAsync( + Path.Combine(root, "owner.lock"), + path + ".work.lock", + TimeSpan.FromSeconds(30), + shared: true, + cancellationToken: cancellationToken + ).ConfigureAwait(false); return new(root, path, record, owner, reading); } catch @@ -174,8 +202,16 @@ public static void RegisterCurrentProcess( string directory ) { PathBoundary.RequireUnlinkedPath(root, directory); - using CoordinatedFileLease reading = CoordinatedFileLease.AcquireAsync(Path.Combine(root, "owner.lock"), directory + ".work.lock", TimeSpan.FromSeconds(30), shared: true) - .AsTask().GetAwaiter().GetResult(); + using CoordinatedFileLease reading = CoordinatedFileLease + .AcquireAsync( + Path.Combine(root, "owner.lock"), + directory + ".work.lock", + TimeSpan.FromSeconds(30), + shared: true + ) + .AsTask() + .GetAwaiter() + .GetResult(); RegisterProcess(root, directory); } @@ -203,16 +239,22 @@ public static IReadOnlyList ReadClaims( ) { var result = new List(); if (!Directory.Exists(root)) + { return result; + } foreach (string record in Directory.EnumerateFiles(root, "*.work.json")) { cancellationToken.ThrowIfCancellationRequested(); Claim claim = ReadClaim(record); string path = PathBoundary.Resolve(root, claim.directory); if (record != RecordPath(root, claim.directory)) + { throw new InvalidDataException("Temporary ownership has an inconsistent identity."); + } if (Directory.Exists(path)) + { result.Add(new(path, path + ".work.lock", QueryOwners(record, null))); + } } return result; } @@ -227,19 +269,27 @@ public void Dispose() { CoordinatedFileLease? lease = m_lease; if (lease is null) + { return; + } m_lease = null; lease.Dispose(); try { - using CoordinatedFileLease retirement = CoordinatedFileLease.AcquireAsync(Path.Combine(m_root, "owner.lock"), directory + ".work.lock", TimeSpan.FromSeconds(5)) - .AsTask().GetAwaiter().GetResult(); + using CoordinatedFileLease retirement = CoordinatedFileLease + .AcquireAsync(Path.Combine(m_root, "owner.lock"), directory + ".work.lock", TimeSpan.FromSeconds(5)) + .AsTask() + .GetAwaiter() + .GetResult(); if (QueryOwners(m_record, m_owner) != ProcessOwnerState.Exited) + { throw new IOException("A temporary directory still has an active or unverifiable subprocess owner."); + } if (Directory.Exists(directory)) + { Directory.Delete(PathBoundary.RequireUnlinkedPath(m_root, directory), recursive: true); + } // The claim authorizes later leaf retirement under the owner's exclusive gate. - } catch (TimeoutException failure) { @@ -268,22 +318,32 @@ public static int RetireMetadataUnderOwnership( ) { int retired = 0; if (!Directory.Exists(root)) + { return retired; + } foreach (string record in Directory.EnumerateFiles(root, "*.work.json").Order(StringComparer.Ordinal)) { cancellationToken.ThrowIfCancellationRequested(); Claim claim = ReadClaim(PathBoundary.RequireUnlinkedPath(root, record)); if (record != RecordPath(root, claim.directory)) + { throw new InvalidDataException("Temporary ownership has an inconsistent identity."); + } string path = PathBoundary.Resolve(root, claim.directory); if (Directory.Exists(path)) + { continue; + } if (QueryOwners(record, null) == ProcessOwnerState.Unknown) + { throw new InvalidDataException("Temporary metadata has an unverifiable process owner."); + } string leaf = PathBoundary.RequireUnlinkedPath(root, path + ".work.lock"); using (FileLease.AcquireAsync(leaf, TimeSpan.Zero, cancellationToken).AsTask().GetAwaiter().GetResult()) { } foreach (string marker in Directory.EnumerateFiles(root, Path.GetFileName(record) + ".*.process")) + { File.Delete(PathBoundary.RequireUnlinkedPath(root, marker)); + } File.Delete(leaf); File.Delete(record); retired++; @@ -298,8 +358,10 @@ string directory string relative = RequireClaim(root, directory); ProcessOwnerStamp owner = ProcessOwnerStamp.CaptureCurrent(); string record = RecordPath(root, relative); - WriteClaim(record + "." + owner.processId + ".process", - new Claim(relative, owner.processId, owner.startedUtcTicks)); + WriteClaim( + record + "." + owner.processId + ".process", + new Claim(relative, owner.processId, owner.startedUtcTicks) + ); } private static string RequireClaim( @@ -310,7 +372,9 @@ string directory string relative = Path.GetRelativePath(root, directory); Claim claim = ReadClaim(RecordPath(root, relative)); if (claim.directory != relative || !Directory.Exists(directory)) + { throw new InvalidDataException("The temporary directory has no matching current owner claim."); + } return relative; } @@ -331,11 +395,15 @@ private static Claim ReadClaim(string path) || !processId.TryGetInt32(out int id) || !root.TryGetProperty("startedUtcTicks", out JsonElement startedUtcTicks) || startedUtcTicks.ValueKind != JsonValueKind.Number - || !startedUtcTicks.TryGetInt64(out long ticks)) + || !startedUtcTicks.TryGetInt64(out long ticks) + ) { throw new InvalidDataException("Temporary ownership is incomplete."); + } var claim = new Claim(directory.GetString()!, id, ticks); if (claim.directory is null || claim.directory.Length != 32 || claim.directory.Any(static character => !Uri.IsHexDigit(character))) + { throw new InvalidDataException("Temporary ownership requires its current explicit directory identity."); + } _ = new ProcessOwnerStamp(claim.processId, claim.startedUtcTicks); return claim; } @@ -361,21 +429,32 @@ private static ProcessOwnerState QueryOwners( ProcessOwnerStamp? excluded ) { ProcessOwnerState combined = ProcessOwnerState.Exited; - foreach (string marker in new[] { record }.Concat(Directory.EnumerateFiles(Path.GetDirectoryName(record)!, Path.GetFileName(record) + ".*.process"))) - { + foreach (string marker in new[] { record }.Concat( + Directory.EnumerateFiles(Path.GetDirectoryName(record)!, Path.GetFileName(record) + ".*.process") + )) { try { Claim claim = ReadClaim(marker); var stamp = new ProcessOwnerStamp(claim.processId, claim.startedUtcTicks); if (stamp == excluded) + { continue; + } ProcessOwnerState state = stamp.Query(); if (state == ProcessOwnerState.Active) + { return state; + } if (state == ProcessOwnerState.Unknown) + { combined = state; + } } - catch (Exception exception) when (exception is IOException or InvalidDataException or JsonException or ArgumentException or UnauthorizedAccessException) + catch (Exception exception) when (exception is IOException + or InvalidDataException + or JsonException + or ArgumentException + or UnauthorizedAccessException) { combined = ProcessOwnerState.Unknown; } diff --git a/src/foundation/core/Inno.Core.IO/ProcessOwnerStamp.cs b/src/foundation/core/Inno.Core.IO/ProcessOwnerStamp.cs index 7255a0012..e3574ab49 100644 --- a/src/foundation/core/Inno.Core.IO/ProcessOwnerStamp.cs +++ b/src/foundation/core/Inno.Core.IO/ProcessOwnerStamp.cs @@ -28,7 +28,9 @@ long startedUtcTicks ArgumentOutOfRangeException.ThrowIfNegativeOrZero(processId); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(startedUtcTicks); if (startedUtcTicks > DateTime.MaxValue.Ticks) + { throw new ArgumentOutOfRangeException(nameof(startedUtcTicks)); + } this.processId = processId; this.startedUtcTicks = startedUtcTicks; } @@ -71,17 +73,33 @@ public static ProcessOwnerStamp CaptureCurrent() public ProcessOwnerState Query() { if (processId <= 0 || startedUtcTicks <= 0) + { return ProcessOwnerState.Unknown; + } try { using Process process = Process.GetProcessById(processId); if (process.HasExited || process.StartTime.ToUniversalTime().Ticks != startedUtcTicks) + { return ProcessOwnerState.Exited; + } return ProcessOwnerState.Active; } - catch (ArgumentException) { return ProcessOwnerState.Exited; } - catch (InvalidOperationException) { return ProcessOwnerState.Unknown; } - catch (Win32Exception) { return ProcessOwnerState.Unknown; } - catch (NotSupportedException) { return ProcessOwnerState.Unknown; } + catch (ArgumentException) + { + return ProcessOwnerState.Exited; + } + catch (InvalidOperationException) + { + return ProcessOwnerState.Unknown; + } + catch (Win32Exception) + { + return ProcessOwnerState.Unknown; + } + catch (NotSupportedException) + { + return ProcessOwnerState.Unknown; + } } } diff --git a/src/foundation/core/Inno.Core.IO/ProcessOwnerState.cs b/src/foundation/core/Inno.Core.IO/ProcessOwnerState.cs index 65cb3475a..e18df3732 100644 --- a/src/foundation/core/Inno.Core.IO/ProcessOwnerState.cs +++ b/src/foundation/core/Inno.Core.IO/ProcessOwnerState.cs @@ -9,12 +9,10 @@ public enum ProcessOwnerState /// The matching process lifetime is still running. /// Active, - /// /// The process exited or its identifier now belongs to another lifetime. /// Exited, - /// /// Ownership cannot be verified; dependent files must remain protected. /// diff --git a/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs b/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs index db732f70b..335ad11f6 100644 --- a/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs +++ b/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs @@ -40,6 +40,6 @@ ReadOnlySpan data public byte[] Read() => (byte[])m_data.Clone(); /// - public void Write(ReadOnlySpan data) => throw new NotSupportedException( - $"Document '{documentName}' is read-only."); + public void Write(ReadOnlySpan data) + => throw new NotSupportedException($"Document '{documentName}' is read-only."); } diff --git a/src/foundation/core/Inno.Core.Identity/Identity.cs b/src/foundation/core/Inno.Core.Identity/Identity.cs index 453ec0f26..997bdc468 100644 --- a/src/foundation/core/Inno.Core.Identity/Identity.cs +++ b/src/foundation/core/Inno.Core.Identity/Identity.cs @@ -23,7 +23,9 @@ public int? runtimeId get { if (m_registryRef == null || !m_registryRef.TryGetTarget(out IdentityRegistry? registry)) + { return null; + } return registry.TryGetRuntimeId(this, out int runtimeId) ? runtimeId : null; } @@ -40,10 +42,12 @@ public RuntimeIdentity? runtimeIdentity get { if (m_registryRef == null || !m_registryRef.TryGetTarget(out IdentityRegistry? registry)) + { return null; + } return registry.TryGetRuntimeId(this, out int runtimeId) - ? new RuntimeIdentity(registry.domainId, runtimeId) - : null; + ? new RuntimeIdentity(registry.domainId, runtimeId) + : null; } } @@ -68,7 +72,9 @@ internal void Bind( int runtimeId ) { if (persistentId == Guid.Empty) + { persistentId = Guid.NewGuid(); + } m_runtimeId = runtimeId; m_registryRef = new WeakReference(registry); @@ -76,10 +82,10 @@ int runtimeId internal void Unbind(IdentityRegistry registry) { - if (m_registryRef != null && - m_registryRef.TryGetTarget(out IdentityRegistry? current) && - ReferenceEquals(current, registry)) - { + if (m_registryRef != null + && m_registryRef.TryGetTarget(out IdentityRegistry? current) + && ReferenceEquals(current, registry) + ) { m_runtimeId = 0; m_registryRef = null; } @@ -96,8 +102,9 @@ internal void Unbind(IdentityRegistry registry) /// /// The current object, or null if the registry retired, the slot changed generation, or the type differs. /// - public TObject? Resolve() where TObject : IdentityObject - => m_registryRef is not null && m_registryRef.TryGetTarget(out IdentityRegistry? registry) - ? registry.Get(m_runtimeId) - : null; + public TObject? Resolve() + where TObject : IdentityObject + => m_registryRef is not null && m_registryRef.TryGetTarget(out IdentityRegistry? registry) + ? registry.Get(m_runtimeId) + : null; } diff --git a/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs b/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs index 392b0f47a..98e6f9063 100644 --- a/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs +++ b/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs @@ -1,7 +1,7 @@ -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.Threading; +using Inno.Core.Execution; namespace Inno.Core.Identity; @@ -25,7 +25,9 @@ public IdentityAllocator() { int nextDomainId = Interlocked.Increment(ref S_NEXT_DOMAIN_ID); if (nextDomainId <= 0) + { throw new InvalidOperationException("The process exhausted available identity domains."); + } domainId = new IdentityDomainId(nextDomainId); m_registry = new IdentityRegistry(domainId); } @@ -128,9 +130,13 @@ Guid persistentId ) { ArgumentNullException.ThrowIfNull(obj); if (persistentId == Guid.Empty) + { throw new ArgumentException("A detached persistent identity cannot be empty.", nameof(persistentId)); + } if (obj.identity.runtimeId is not null) + { throw new InvalidOperationException("A registered identity object cannot be reinitialized."); + } obj.SetIdentity(new Identity(persistentId)); } @@ -153,10 +159,14 @@ public bool Unregister(IdentityObject obj) { ArgumentNullException.ThrowIfNull(obj); if (!m_registry.Unregister(obj)) + { return false; + } Action? handlers = ObjectUnregistered; if (handlers is null) + { return true; + } List? failures = null; foreach (Delegate handler in handlers.GetInvocationList()) { @@ -171,7 +181,9 @@ public bool Unregister(IdentityObject obj) } } if (failures is not null) + { throw new AggregateException("One or more identity unregistration observers failed.", failures); + } return true; } @@ -189,7 +201,7 @@ public bool Unregister(IdentityObject obj) /// public TIdentity? Get(int runtimeId) where TIdentity : IdentityObject - => m_registry.Get(runtimeId); + => m_registry.Get(runtimeId); /// /// Resolves a domain-qualified runtime identity without allowing cross-session aliasing. @@ -205,9 +217,9 @@ public bool Unregister(IdentityObject obj) /// public TIdentity? Get(RuntimeIdentity identity) where TIdentity : IdentityObject - => identity.domainId == domainId - ? m_registry.Get(identity.runtimeId) - : null; + => identity.domainId == domainId + ? m_registry.Get(identity.runtimeId) + : null; /// /// Resolves a registered object by its persistent identity. @@ -223,6 +235,5 @@ public bool Unregister(IdentityObject obj) /// public TIdentity? Get(Guid persistentId) where TIdentity : IdentityObject - => m_registry.Get(persistentId); - + => m_registry.Get(persistentId); } diff --git a/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs b/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs index 21619b08b..10ec71cfe 100644 --- a/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs +++ b/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs @@ -90,10 +90,11 @@ public bool Register( if (TryGetSlotByPersistentNoLock(resolvedPersistentId, out int existingSlot)) { if (TryGetLiveObjectBySlotNoLock(existingSlot, out IdentityObject? existing, out _) - && !ReferenceEquals(existing, obj)) - { + && !ReferenceEquals(existing, obj) + ) { throw new InvalidOperationException( - $"Persistent id '{resolvedPersistentId}' is already registered."); + $"Persistent id '{resolvedPersistentId}' is already registered." + ); } RemoveSlotBySlotNoLock(existingSlot); @@ -159,7 +160,9 @@ public bool Unregister(IdentityObject obj) } if (!ReferenceEquals(activeObject, obj)) + { return false; + } RemoveSlotBySlotNoLock(objectSlot); identity.Unbind(this); @@ -311,7 +314,9 @@ out int runtimeId ) { runtimeId = 0; if (identity.persistentId == Guid.Empty || identity.rawRuntimeId == 0) + { return false; + } m_lock.EnterReadLock(); try @@ -343,7 +348,9 @@ out int runtimeId private int AllocateSlot() { if (m_freeSlots.Count > 0) + { return m_freeSlots.Pop(); + } int slot = m_generations.Count; m_generations.Add(1); @@ -505,9 +512,9 @@ private void CleanupStaleSlotBySlotNoLock(int slot) return; } - if (TryGetEntryByDenseNoLock(denseIndex, out RegistryEntry? entry) && - entry!.TryGetObject(out _)) - { + if (TryGetEntryByDenseNoLock(denseIndex, out RegistryEntry? entry) + && entry!.TryGetObject(out _) + ) { return; } @@ -517,11 +524,15 @@ private void CleanupStaleSlotBySlotNoLock(int slot) private Guid GetPersistentIdBySlotNoLock(int slot) { if (slot < 0 || slot >= m_sparseToDense.Count) + { return Guid.Empty; + } int denseIndex = m_sparseToDense[slot]; if (denseIndex < 0 || denseIndex >= m_active.Count) + { return Guid.Empty; + } return m_active[denseIndex].persistentId; } @@ -561,9 +572,9 @@ int denseIndex m_slotByObject.Remove(removedObj!); } - if (m_slotByPersistent.TryGetValue(removed.persistentId, out int mappedSlot) && - mappedSlot == slot) - { + if (m_slotByPersistent.TryGetValue(removed.persistentId, out int mappedSlot) + && mappedSlot == slot + ) { m_slotByPersistent.Remove(removed.persistentId); } @@ -603,6 +614,7 @@ private sealed class RegistryEntry /// The m object ref value used as part of this type's public representation. /// public WeakReference m_objectRef; + /// /// The persistent id value used as part of this type's public representation. /// diff --git a/src/foundation/core/Inno.Core.Identity/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Identity/Properties/ScriptingApi.cs index 8a88b3204..01a7d3895 100644 --- a/src/foundation/core/Inno.Core.Identity/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Identity/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Core.Identity; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Core", - "Inno.Core.Identity", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Core", "Inno.Core.Identity", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(IdentityObject), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Identity), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Identity/RuntimeIdCodec.cs b/src/foundation/core/Inno.Core.Identity/RuntimeIdCodec.cs index 0a5187d43..39e23b12d 100644 --- a/src/foundation/core/Inno.Core.Identity/RuntimeIdCodec.cs +++ b/src/foundation/core/Inno.Core.Identity/RuntimeIdCodec.cs @@ -11,6 +11,7 @@ internal static class RuntimeIdCodec /// The slot bits value used as part of this type's public representation. /// public const int SLOT_BITS = 20; + /// /// The generation bits value used as part of this type's public representation. /// @@ -20,6 +21,7 @@ internal static class RuntimeIdCodec /// The slot mask value used as part of this type's public representation. /// public const int SLOT_MASK = (1 << SLOT_BITS) - 1; + /// /// The generation mask value used as part of this type's public representation. /// @@ -42,9 +44,13 @@ public static int Pack( int generation ) { if ((uint)slot > SLOT_MASK) + { throw new ArgumentOutOfRangeException(nameof(slot)); + } if ((uint)generation > GENERATION_MASK) + { throw new ArgumentOutOfRangeException(nameof(generation)); + } return (generation << SLOT_BITS) | (slot & SLOT_MASK); } diff --git a/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs b/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs index 249408555..28fe582f4 100644 --- a/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs +++ b/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs @@ -28,9 +28,13 @@ public RuntimeIdentity( int runtimeId ) { if (!domainId.isValid) + { throw new ArgumentException("A runtime identity requires a valid domain.", nameof(domainId)); + } if (runtimeId <= 0) + { throw new ArgumentException("A runtime identity requires a positive runtime identifier.", nameof(runtimeId)); + } this.domainId = domainId; this.runtimeId = runtimeId; } diff --git a/src/foundation/core/Inno.Core.Input/KeyCode.cs b/src/foundation/core/Inno.Core.Input/KeyCode.cs index e39642f95..b1960d8e4 100644 --- a/src/foundation/core/Inno.Core.Input/KeyCode.cs +++ b/src/foundation/core/Inno.Core.Input/KeyCode.cs @@ -9,7 +9,6 @@ public enum KeyCode /// No recognized physical key. /// Unknown = 0, - /// /// The A letter key. /// @@ -114,7 +113,6 @@ public enum KeyCode /// The Z letter key. /// Z = 90, - /// /// The 0 key on the primary keyboard row. /// @@ -155,7 +153,6 @@ public enum KeyCode /// The 9 key on the primary keyboard row. /// D9 = 57, - /// /// The escape key. /// @@ -176,7 +173,6 @@ public enum KeyCode /// The backspace key. /// Backspace = 8, - /// /// The left arrow key. /// @@ -193,11 +189,10 @@ public enum KeyCode /// The down arrow key. /// DownArrow = 40, - /// /// The left super key. /// - LeftSuper = 91, + LeftSuper = 91, /// /// The right super key. /// @@ -226,7 +221,6 @@ public enum KeyCode /// The right alt key. /// RightAlt = 165, - /// /// The caps lock key. /// @@ -255,7 +249,6 @@ public enum KeyCode /// The page down key. /// PageDown = 34, - /// /// The 0 key on the numeric keypad. /// @@ -296,7 +289,6 @@ public enum KeyCode /// The 9 key on the numeric keypad. /// NumPad9 = 105, - /// /// The num lock key. /// @@ -305,7 +297,6 @@ public enum KeyCode /// The scroll lock key. /// ScrollLock = 145, - /// /// The F1 function key. /// @@ -354,7 +345,6 @@ public enum KeyCode /// The F12 function key. /// F12 = 123, - /// /// The plus key. /// @@ -399,4 +389,4 @@ public enum KeyCode /// The right bracket key. /// RightBracket = 221 // ']' key -} \ No newline at end of file +} diff --git a/src/foundation/core/Inno.Core.Input/KeyModifier.cs b/src/foundation/core/Inno.Core.Input/KeyModifier.cs index 8a958fda8..e81c06611 100644 --- a/src/foundation/core/Inno.Core.Input/KeyModifier.cs +++ b/src/foundation/core/Inno.Core.Input/KeyModifier.cs @@ -27,5 +27,5 @@ public enum KeyModifier /// /// The super key. /// - Super = 8, -} \ No newline at end of file + Super = 8 +} diff --git a/src/foundation/core/Inno.Core.Input/MouseButton.cs b/src/foundation/core/Inno.Core.Input/MouseButton.cs index 50a4006fb..eb984c912 100644 --- a/src/foundation/core/Inno.Core.Input/MouseButton.cs +++ b/src/foundation/core/Inno.Core.Input/MouseButton.cs @@ -25,4 +25,4 @@ public enum MouseButton /// The xbutton2 key. /// XButton2 = 4 -} \ No newline at end of file +} diff --git a/src/foundation/core/Inno.Core.Input/MouseCursor.cs b/src/foundation/core/Inno.Core.Input/MouseCursor.cs index 1d6d70b47..669b87735 100644 --- a/src/foundation/core/Inno.Core.Input/MouseCursor.cs +++ b/src/foundation/core/Inno.Core.Input/MouseCursor.cs @@ -9,7 +9,6 @@ public enum MouseCursor /// No concrete cursor shape; the consuming host defines visibility behavior. /// None = -1, - /// /// The standard arrow pointer. /// @@ -45,5 +44,5 @@ public enum MouseCursor /// /// A cursor indicating that an operation is unavailable. /// - NotAllowed = 8, + NotAllowed = 8 } diff --git a/src/foundation/core/Inno.Core.Input/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Input/Properties/ScriptingApi.cs index 06abb83a6..6cf4633cb 100644 --- a/src/foundation/core/Inno.Core.Input/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Input/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Core.Input; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Input", - "Inno.Core.Input", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Input", "Inno.Core.Input", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(KeyCode), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(KeyModifier), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Jobs/JobExecutionMode.cs b/src/foundation/core/Inno.Core.Jobs/JobExecutionMode.cs index 02b593ffb..fefe5dce6 100644 --- a/src/foundation/core/Inno.Core.Jobs/JobExecutionMode.cs +++ b/src/foundation/core/Inno.Core.Jobs/JobExecutionMode.cs @@ -9,7 +9,6 @@ public enum JobExecutionMode /// Executes jobs deterministically on the scheduler owner thread. /// SingleThread, - /// /// Executes ready jobs on a bounded work-stealing worker pool. /// diff --git a/src/foundation/core/Inno.Core.Jobs/JobScheduler.cs b/src/foundation/core/Inno.Core.Jobs/JobScheduler.cs index fc1a6cd6d..2784f7040 100644 --- a/src/foundation/core/Inno.Core.Jobs/JobScheduler.cs +++ b/src/foundation/core/Inno.Core.Jobs/JobScheduler.cs @@ -84,8 +84,7 @@ public JobHandle Schedule( Action job, object? state, ReadOnlySpan dependencies - ) - => m_implementation.Schedule(job, state, dependencies); + ) => m_implementation.Schedule(job, state, dependencies); /// /// Creates one handle that completes after every supplied dependency. diff --git a/src/foundation/core/Inno.Core.Jobs/JobSchedulerStatistics.cs b/src/foundation/core/Inno.Core.Jobs/JobSchedulerStatistics.cs index a38023bf2..4d12508d9 100644 --- a/src/foundation/core/Inno.Core.Jobs/JobSchedulerStatistics.cs +++ b/src/foundation/core/Inno.Core.Jobs/JobSchedulerStatistics.cs @@ -9,26 +9,32 @@ public readonly record struct JobSchedulerStatistics /// Gets jobs admitted in the current frame, including completed jobs awaiting EndFrame. /// public int frameJobs { get; init; } + /// /// Gets the largest admitted frame since scheduler creation. /// public int peakFrameJobs { get; init; } + /// /// Gets rejected job admissions caused by the finite frame capacity. /// public long rejectedJobs { get; init; } + /// /// Gets queued or retirement-pending owner-thread callbacks. /// public int mainThreadPending { get; init; } + /// /// Gets the largest simultaneous owner-thread queue occupancy. /// public int mainThreadPeak { get; init; } + /// /// Gets callbacks rejected because the queue was full or closed. /// public long mainThreadRejected { get; init; } + /// /// Gets accepted callbacks canceled before execution during shutdown. /// diff --git a/src/foundation/core/Inno.Core.Jobs/Systems/MainThreadWorkQueue.cs b/src/foundation/core/Inno.Core.Jobs/Systems/MainThreadWorkQueue.cs index a4781d8c8..3a18cd1d9 100644 --- a/src/foundation/core/Inno.Core.Jobs/Systems/MainThreadWorkQueue.cs +++ b/src/foundation/core/Inno.Core.Jobs/Systems/MainThreadWorkQueue.cs @@ -24,11 +24,15 @@ internal JobSchedulerStatistics statistics get { lock (m_sync) + { return new JobSchedulerStatistics { mainThreadPending = m_actions.Count + (m_pending is null ? 0 : 1), - mainThreadPeak = m_peak, mainThreadRejected = m_rejected, mainThreadCanceled = m_canceled + mainThreadPeak = m_peak, + mainThreadRejected = m_rejected, + mainThreadCanceled = m_canceled }; + } } } @@ -64,17 +68,23 @@ internal void Drain() } int count; lock (m_sync) + { count = Math.Min(drainBudget, m_actions.Count); + } for (int index = 0; index < count; index++) { Action action; lock (m_sync) { if (!m_actions.TryDequeue(out action!)) + { break; + } } lock (m_sync) + { m_pending = action; + } try { CompletePending(); @@ -82,7 +92,9 @@ internal void Drain() catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { if (m_failures.Count > 0) + { throw new AggregateException("Callbacks remain pending after completed failures.", [.. m_failures, pending]); + } throw; } catch (Exception exception) @@ -119,7 +131,9 @@ internal void Close() private void ReportFailures() { if (m_failures.Count == 0) + { return; + } var failure = new AggregateException("Main-thread callbacks completed with failures.", m_failures); m_failures.Clear(); throw failure; @@ -128,18 +142,26 @@ private void ReportFailures() private void CompletePending() { if (m_executing) + { throw new RetirementPendingException("A main-thread callback cannot retire itself reentrantly."); + } Action? action; lock (m_sync) + { action = m_pending; + } if (action is null) + { return; + } m_barrier ??= new RetirementBarrier("Job main-thread callback"); m_executing = true; try { if (!m_barrier.TryComplete(action)) + { throw new RetirementPendingException("An owner-thread job callback has unfinished retirement."); + } } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { @@ -160,7 +182,9 @@ private void CompletePending() private void ClearPending() { lock (m_sync) + { m_pending = null; + } m_barrier = null; } } diff --git a/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs b/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs index 495641acc..d21304f69 100644 --- a/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs +++ b/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs @@ -1,7 +1,7 @@ using System; -using Inno.Core.Execution; using System.Collections.Concurrent; using System.Collections.Generic; +using Inno.Core.Execution; using Inno.Core.Jobs.Internal; namespace Inno.Core.Jobs; @@ -11,12 +11,13 @@ namespace Inno.Core.Jobs; /// internal sealed class SingleThreadJobSystem : IJobSystem { - private static readonly Action s_noop = static _ => { }; + private static readonly Action s_noop = static _ => {}; private static readonly Action s_actionInvoker = static state => ((Action?)state)?.Invoke(); + private static readonly Action s_parallelRangeInvoker = static state => { var rangeState = (ParallelForRangeState?)state - ?? throw new InvalidOperationException("Parallel-for state cannot be null."); + ?? throw new InvalidOperationException("Parallel-for state cannot be null."); rangeState.body(rangeState.startInclusive, rangeState.endExclusive); }; @@ -53,10 +54,14 @@ public JobSchedulerStatistics statistics get { lock (m_jobsGate) + { return m_mainThreadQueue.statistics with { - frameJobs = m_frameJobs.Count, peakFrameJobs = m_peakFrameJobs, rejectedJobs = m_rejectedJobs + frameJobs = m_frameJobs.Count, + peakFrameJobs = m_peakFrameJobs, + rejectedJobs = m_rejectedJobs }; + } } } @@ -209,7 +214,9 @@ ReadOnlySpan dependencies foreach (JobHandle dependency in dependencies) { if (!dependency.isValid) + { throw new ArgumentException("Dependency handle is invalid.", nameof(dependencies)); + } _ = ResolveHandleNoLock(dependency); } var index = AllocateJobIndexNoLock(job, state); @@ -383,7 +390,9 @@ public void EnqueueMainThread(Action action) ArgumentNullException.ThrowIfNull(action); ThrowIfDisposed(); if (!m_mainThreadQueue.TryEnqueue(action)) + { throw new InvalidOperationException("The main-thread callback queue is at capacity or retiring."); + } } /// @@ -403,12 +412,16 @@ public void DrainMainThreadQueue() public void Dispose() { if (m_disposed) + { return; + } EnsureMainThread(); try { if (m_frameActive) + { EndFrame(); + } } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { diff --git a/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs b/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs index 7d93df797..8c405646c 100644 --- a/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs +++ b/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs @@ -1,8 +1,8 @@ using System; -using Inno.Core.Execution; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; +using Inno.Core.Execution; using Inno.Core.Jobs.Internal; namespace Inno.Core.Jobs; @@ -12,12 +12,13 @@ namespace Inno.Core.Jobs; /// internal sealed class WorkStealingJobSystem : IJobSystem { - private static readonly Action s_noop = static _ => { }; + private static readonly Action s_noop = static _ => {}; private static readonly Action s_actionInvoker = static state => ((Action?)state)?.Invoke(); + private static readonly Action s_parallelRangeInvoker = static state => { var rangeState = (ParallelForRangeState?)state - ?? throw new InvalidOperationException("Parallel-for state cannot be null."); + ?? throw new InvalidOperationException("Parallel-for state cannot be null."); rangeState.body(rangeState.startInclusive, rangeState.endExclusive); }; @@ -47,9 +48,7 @@ internal sealed class WorkStealingJobSystem : IJobSystem /// Creates a job system with default options. /// internal WorkStealingJobSystem() - : this(new JobSchedulerOptions()) - { - } + : this(new JobSchedulerOptions()) {} /// /// Creates a job system with explicit options. @@ -72,16 +71,22 @@ internal WorkStealingJobSystem(JobSchedulerOptions options) m_workers[i] = new WorkerRuntime(workerId, () => WorkerLoop(workerId)); } for (; started < m_workers.Length; started++) + { m_workers[started].thread.Start(); + } } catch { Interlocked.Exchange(ref m_running, 0); for (int index = 0; index < started; index++) + { m_wakeSignal.Release(); + } // No work can have been admitted before construction returns. for (int index = 0; index < started; index++) + { m_workers[index].thread.Join(); + } m_currentWorkerId.Dispose(); m_wakeSignal.Dispose(); m_completionSignal.Dispose(); @@ -97,10 +102,14 @@ public JobSchedulerStatistics statistics get { lock (m_jobsGate) + { return m_mainThreadQueue.statistics with { - frameJobs = m_frameJobs.Count, peakFrameJobs = m_peakFrameJobs, rejectedJobs = m_rejectedJobs + frameJobs = m_frameJobs.Count, + peakFrameJobs = m_peakFrameJobs, + rejectedJobs = m_rejectedJobs }; + } } } @@ -249,7 +258,9 @@ ReadOnlySpan dependencies foreach (JobHandle dependency in dependencies) { if (!dependency.isValid) + { throw new ArgumentException("Dependency handle is invalid.", nameof(dependencies)); + } _ = ResolveHandleNoLock(dependency); } var index = AllocateJobIndexNoLock(job, state); @@ -434,7 +445,9 @@ public void EnqueueMainThread(Action action) ArgumentNullException.ThrowIfNull(action); ThrowIfDisposed(); if (!m_mainThreadQueue.TryEnqueue(action)) + { throw new InvalidOperationException("The main-thread callback queue is at capacity or retiring."); + } } /// @@ -462,7 +475,9 @@ public void Dispose() try { if (m_frameActive) + { EndFrame(); + } } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { diff --git a/src/foundation/core/Inno.Core.Layers/Layer.cs b/src/foundation/core/Inno.Core.Layers/Layer.cs index 67e12497d..20bee78e7 100644 --- a/src/foundation/core/Inno.Core.Layers/Layer.cs +++ b/src/foundation/core/Inno.Core.Layers/Layer.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Runtime.ExceptionServices; - using Inno.Core.Events; using Inno.Core.Execution; @@ -29,7 +28,9 @@ public abstract class Layer protected Layer(string name = "Layer") { if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("A layer name is required.", nameof(name)); + } this.name = name; } @@ -41,9 +42,7 @@ protected Layer(string name = "Layer") /// /// Runs after the layer has received its event scope and joined a stack. /// - public virtual void OnAttach() - { - } + public virtual void OnAttach() {} /// /// Runs while the layer is leaving its stack and before its event scope is released. @@ -53,9 +52,7 @@ public virtual void OnAttach() /// retains ownership and permits a later cleanup retry. /// Completed cleanup steps must not be repeated on that retry. /// - public virtual void OnDetach() - { - } + public virtual void OnDetach() {} /// /// Advances fixed-step work for this layer. @@ -63,9 +60,7 @@ public virtual void OnDetach() /// /// The fixed simulation interval in seconds. /// - public virtual void OnFixedUpdate(float fixedDeltaTime) - { - } + public virtual void OnFixedUpdate(float fixedDeltaTime) {} /// /// Advances variable-step work for this layer. @@ -73,9 +68,7 @@ public virtual void OnFixedUpdate(float fixedDeltaTime) /// /// The elapsed frame time in seconds. /// - public virtual void OnUpdate(float deltaTime) - { - } + public virtual void OnUpdate(float deltaTime) {} /// /// Advances work that must run after the regular update phase. @@ -83,9 +76,7 @@ public virtual void OnUpdate(float deltaTime) /// /// The elapsed frame time in seconds. /// - public virtual void OnLateUpdate(float deltaTime) - { - } + public virtual void OnLateUpdate(float deltaTime) {} /// /// Prepares frame-scoped rendering state before render work is submitted. @@ -93,9 +84,7 @@ public virtual void OnLateUpdate(float deltaTime) /// /// The elapsed frame time in seconds. /// - public virtual void OnBeforeRender(float deltaTime) - { - } + public virtual void OnBeforeRender(float deltaTime) {} /// /// Submits rendering work without presenting a concrete graphics backend. @@ -103,9 +92,7 @@ public virtual void OnBeforeRender(float deltaTime) /// /// The elapsed frame time in seconds. /// - public virtual void OnRender(float deltaTime) - { - } + public virtual void OnRender(float deltaTime) {} /// /// Completes frame-scoped rendering state after render submission. @@ -117,9 +104,7 @@ public virtual void OnRender(float deltaTime) /// /// The elapsed frame time in seconds. /// - public virtual void OnAfterRender(float deltaTime) - { - } + public virtual void OnAfterRender(float deltaTime) {} /// /// Subscribes to an event for the lifetime of this layer attachment. @@ -142,8 +127,7 @@ public virtual void OnAfterRender(float deltaTime) protected IDisposable Listen( Action handler, int priority = 0 - ) - where TEvent : Event + ) where TEvent : Event { EventHub events = RequireActiveEvents(); IDisposable subscription = events.Listen(handler, priority); @@ -172,8 +156,7 @@ protected IDisposable Listen( protected IDisposable ListenOnce( Action handler, int priority = 0 - ) - where TEvent : Event + ) where TEvent : Event { EventHub events = RequireActiveEvents(); IDisposable subscription = events.ListenOnce(handler, priority); @@ -203,7 +186,9 @@ internal void Attach(EventHub events) { ArgumentNullException.ThrowIfNull(events); if (m_events is not null) + { throw new InvalidOperationException($"Layer '{name}' is already attached."); + } m_events = events; OnAttach(); @@ -212,7 +197,9 @@ internal void Attach(EventHub events) internal void Detach() { if (m_events is null) + { throw new InvalidOperationException($"Layer '{name}' is not attached."); + } if (!m_detaching) { @@ -238,16 +225,20 @@ internal void Detach() List? failures = m_detachFailures; m_detachFailures = null; if (failures is null) + { return; + } if (failures.Count == 1) + { ExceptionDispatchInfo.Capture(failures[0]).Throw(); + } throw new AggregateException($"Layer '{name}' encountered multiple detach failures.", failures); } private EventHub RequireActiveEvents() => !m_detaching && m_events is not null - ? m_events - : throw new InvalidOperationException("The layer has no active event scope or is already detaching."); + ? m_events + : throw new InvalidOperationException("The layer has no active event scope or is already detaching."); private List? ReleaseSubscriptions() { diff --git a/src/foundation/core/Inno.Core.Layers/LayerStack.cs b/src/foundation/core/Inno.Core.Layers/LayerStack.cs index 0e27bd9d7..74a7d86b6 100644 --- a/src/foundation/core/Inno.Core.Layers/LayerStack.cs +++ b/src/foundation/core/Inno.Core.Layers/LayerStack.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Runtime.ExceptionServices; - using Inno.Core.Events; using Inno.Core.Execution; @@ -110,7 +109,9 @@ public bool PopLayer(Layer layer) ArgumentNullException.ThrowIfNull(layer); int index = Find(layer); if (index < 0 || index >= m_baseLayerCount) + { return false; + } Remove(index); return true; } @@ -136,7 +137,9 @@ public bool PopOverlay(Layer overlay) ArgumentNullException.ThrowIfNull(overlay); int index = Find(overlay); if (index < m_baseLayerCount) + { return false; + } Remove(index); return true; } @@ -154,7 +157,9 @@ public void OnFixedUpdate(float fixedDeltaTime) { EnsureActive(); for (int index = 0; index < m_layers.Count; index++) + { m_layers[index].layer.OnFixedUpdate(fixedDeltaTime); + } } /// @@ -170,7 +175,9 @@ public void OnUpdate(float deltaTime) { EnsureActive(); for (int index = 0; index < m_layers.Count; index++) + { m_layers[index].layer.OnUpdate(deltaTime); + } } /// @@ -186,7 +193,9 @@ public void OnLateUpdate(float deltaTime) { EnsureActive(); for (int index = 0; index < m_layers.Count; index++) + { m_layers[index].layer.OnLateUpdate(deltaTime); + } } /// @@ -209,9 +218,13 @@ public void RenderFrame(float deltaTime) try { for (; preparedCount < m_layers.Count; preparedCount++) + { m_layers[preparedCount].layer.OnBeforeRender(deltaTime); + } for (int index = 0; index < preparedCount; index++) + { m_layers[index].layer.OnRender(deltaTime); + } } catch (Exception exception) { @@ -268,7 +281,9 @@ public void Clear() public void Dispose() { if (m_disposed) + { return; + } List? failures = DetachAll(); m_disposed = true; ThrowFailures(failures, "One or more layers failed to detach while disposing the stack."); @@ -282,13 +297,17 @@ bool isBaseLayer EnsureActive(); ArgumentNullException.ThrowIfNull(layer); if (layer.isAttached || Find(layer) >= 0) + { throw new InvalidOperationException($"Layer '{layer.name}' is already attached to this stack."); + } EventHub events = m_eventHubFactory() - ?? throw new InvalidOperationException("The layer event hub factory returned null."); + ?? throw new InvalidOperationException("The layer event hub factory returned null."); m_layers.Insert(index, new Entry(layer, events)); if (isBaseLayer) + { m_baseLayerCount++; + } try { UpdateEventOrder(); @@ -321,7 +340,9 @@ private void Remove(int index) try { if (entry.layer.isAttached) + { entry.layer.Detach(); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -342,7 +363,9 @@ private void Remove(int index) } m_layers.RemoveAt(index); if (index < m_baseLayerCount) + { m_baseLayerCount--; + } UpdateEventOrder(); ThrowFailures(failures, "Layer detachment and event-scope retirement failed."); } @@ -375,7 +398,9 @@ private int Find(Layer layer) for (int index = 0; index < m_layers.Count; index++) { if (ReferenceEquals(m_layers[index].layer, layer)) + { return index; + } } return -1; } @@ -383,14 +408,18 @@ private int Find(Layer layer) private void UpdateEventOrder() { for (int index = 0; index < m_layers.Count; index++) + { m_layers[index].events.order = index; + } } private void EnsureActive() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("Layer retirement is pending; resume Clear or Dispose before using this stack."); + } } private static void ThrowFailures( @@ -398,9 +427,13 @@ private static void ThrowFailures( string message ) { if (failures is null) + { return; + } if (failures.Count == 1) + { ExceptionDispatchInfo.Capture(failures[0]).Throw(); + } throw new AggregateException(message, failures); } diff --git a/src/foundation/core/Inno.Core.Logging/DiagnosticLogSink.cs b/src/foundation/core/Inno.Core.Logging/DiagnosticLogSink.cs index 0fe2e163f..c8e3b1ab6 100644 --- a/src/foundation/core/Inno.Core.Logging/DiagnosticLogSink.cs +++ b/src/foundation/core/Inno.Core.Logging/DiagnosticLogSink.cs @@ -33,6 +33,7 @@ LogRouter logs m_logs = logs ?? throw new ArgumentNullException(nameof(logs)); m_hub.RegisterSink(this); } + /// /// Replaces the current report for one diagnostic source. /// @@ -45,23 +46,36 @@ public void Replace(DiagnosticReport report) Diagnostic[] previous = m_previous.GetValueOrDefault(report.source.id, []); foreach (Diagnostic issue in report.diagnostics) { - if (previous.Any(old => old.code == issue.code && old.semanticId == issue.semanticId && - old.objectId == issue.objectId && old.message == issue.message && old.severity == issue.severity && - Equals(old.location, issue.location))) + if (previous.Any(old => ( + old.code == issue.code && old.semanticId == issue.semanticId + && old.objectId == issue.objectId && old.message == issue.message && old.severity == issue.severity + && Equals(old.location, issue.location) + ))) { continue; + } LogLevel level = issue.severity switch { DiagnosticSeverity.Error => LogLevel.Error, DiagnosticSeverity.Warning => LogLevel.Warn, _ => LogLevel.Info }; - m_logs.Dispatch(new LogEntry(level, AssemblyDomain.InnoInternal, AssemblyScope.Runtime, - report.source.displayName, $"{issue.code}: {issue.message}", - issue.location?.sourcePath ?? string.Empty, issue.location?.line ?? 0, - string.Empty, LogSessionContext.current)); + m_logs.Dispatch( + new LogEntry( + level, + AssemblyDomain.InnoInternal, + AssemblyScope.Runtime, + report.source.displayName, + $"{issue.code}: {issue.message}", + issue.location?.sourcePath ?? string.Empty, + issue.location?.line ?? 0, + string.Empty, + LogSessionContext.current + ) + ); } m_previous[report.source.id] = report.diagnostics.ToArray(); } + /// /// Removes the current report for one diagnostic source. /// @@ -76,7 +90,9 @@ public void Replace(DiagnosticReport report) public void Dispose() { if (m_disposed) + { return; + } m_hub.UnregisterSink(this); m_disposed = true; m_previous.Clear(); diff --git a/src/foundation/core/Inno.Core.Logging/FileLogSink.cs b/src/foundation/core/Inno.Core.Logging/FileLogSink.cs index 56350ae22..2bbd072d2 100644 --- a/src/foundation/core/Inno.Core.Logging/FileLogSink.cs +++ b/src/foundation/core/Inno.Core.Logging/FileLogSink.cs @@ -106,9 +106,11 @@ public void Receive(LogEntry entry) string line = FormatEntry(entry); int bytes = S_ENCODING.GetByteCount(line) + S_NEWLINE_BYTES; if (m_currentSize > 0 && bytes > m_maxFileSize - m_currentSize) + { RotateFile(); + } StreamWriter writer = m_writer - ?? throw new InvalidOperationException("The file log sink has no writable file after a failed rotation."); + ?? throw new InvalidOperationException("The file log sink has no writable file after a failed rotation."); writer.WriteLine(line); writer.Flush(); m_currentSize += bytes; @@ -126,7 +128,9 @@ public void Dispose() lock (m_lifecycleSync) { if (m_disposed) + { return; + } m_disposed = true; CloseWriter(); } @@ -160,7 +164,8 @@ private void CleanupOldFiles() FileAccess.Read, FileShare.None, bufferSize: 1, - FileOptions.DeleteOnClose); + FileOptions.DeleteOnClose + ); } catch (IOException) { @@ -186,7 +191,8 @@ private void OpenWriter() FileAccess.Write, FileShare.Read, bufferSize: 16 * 1024, - FileOptions.SequentialScan); + FileOptions.SequentialScan + ); try { m_writer = new StreamWriter(stream, S_ENCODING); diff --git a/src/foundation/core/Inno.Core.Logging/Log.cs b/src/foundation/core/Inno.Core.Logging/Log.cs index 834088b72..1dfdd1ea1 100644 --- a/src/foundation/core/Inno.Core.Logging/Log.cs +++ b/src/foundation/core/Inno.Core.Logging/Log.cs @@ -354,33 +354,40 @@ int lineNumber ArgumentNullException.ThrowIfNull(sourceType); LogRouter router = LogRouter.current; if (!router.IsEnabled(level)) + { return; + } AssemblyDomain domain = sourceType.Assembly.GetInnoAssemblyDomain(); AssemblyScope scope = sourceType.Assembly.GetInnoAssemblyScope(); string category = GetCategory(filePath); string rendered = arguments is null || arguments.Count == 0 - ? message : string.Format(message, arguments.ToArray()); - router.Dispatch(new LogEntry( - level, - domain, - scope, - category, - rendered, - string.IsNullOrWhiteSpace(filePath) ? C_DEFAULT_CATEGORY : filePath, - lineNumber, - new StackTrace(2, true).ToString(), - LogSessionContext.current)); + ? message + : string.Format(message, arguments.ToArray()); + router.Dispatch( + new LogEntry( + level, + domain, + scope, + category, + rendered, + string.IsNullOrWhiteSpace(filePath) ? C_DEFAULT_CATEGORY : filePath, + lineNumber, + new StackTrace(2, true).ToString(), + LogSessionContext.current + ) + ); } private static string GetCategory(string filePath) { if (string.IsNullOrWhiteSpace(filePath)) + { return C_DEFAULT_CATEGORY; + } // Compiler source paths belong to the authoring host, which can differ from the runtime host. int fileNameStart = Math.Max(filePath.LastIndexOf('/'), filePath.LastIndexOf('\\')) + 1; return Path.GetFileNameWithoutExtension(filePath.AsSpan(fileNameStart)).ToString(); } - } diff --git a/src/foundation/core/Inno.Core.Logging/LogDeliveryMode.cs b/src/foundation/core/Inno.Core.Logging/LogDeliveryMode.cs index 47d169ae6..5b0f2c115 100644 --- a/src/foundation/core/Inno.Core.Logging/LogDeliveryMode.cs +++ b/src/foundation/core/Inno.Core.Logging/LogDeliveryMode.cs @@ -9,7 +9,6 @@ public enum LogDeliveryMode /// Delivers queued entries through a dedicated background worker. /// Background, - /// /// Delivers entries synchronously on the producer's thread. /// diff --git a/src/foundation/core/Inno.Core.Logging/LogEntry.cs b/src/foundation/core/Inno.Core.Logging/LogEntry.cs index 68b9b27db..670f9b048 100644 --- a/src/foundation/core/Inno.Core.Logging/LogEntry.cs +++ b/src/foundation/core/Inno.Core.Logging/LogEntry.cs @@ -1,5 +1,4 @@ using System; - using Inno.Extensibility.Modules; namespace Inno.Core.Logging; diff --git a/src/foundation/core/Inno.Core.Logging/LogLevel.cs b/src/foundation/core/Inno.Core.Logging/LogLevel.cs index dd2b0dd5c..41eb3d861 100644 --- a/src/foundation/core/Inno.Core.Logging/LogLevel.cs +++ b/src/foundation/core/Inno.Core.Logging/LogLevel.cs @@ -9,22 +9,18 @@ public enum LogLevel /// Diagnostic logs intended for local debugging. /// Debug, - /// /// Informational logs for normal runtime flow. /// Info, - /// /// Warning logs for recoverable problems. /// Warn, - /// /// Error logs for failures that should be investigated. /// Error, - /// /// Fatal logs for unrecoverable failures. /// diff --git a/src/foundation/core/Inno.Core.Logging/LogRouter.cs b/src/foundation/core/Inno.Core.Logging/LogRouter.cs index b33bbb89c..800d98896 100644 --- a/src/foundation/core/Inno.Core.Logging/LogRouter.cs +++ b/src/foundation/core/Inno.Core.Logging/LogRouter.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; - using Inno.Core.Execution; using Inno.Extensibility.Modules; @@ -65,7 +64,9 @@ public LogRouter( ArgumentOutOfRangeException.ThrowIfNegativeOrZero(queueCapacity); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(drainBudget); if (!Enum.IsDefined(deliveryMode)) + { throw new ArgumentOutOfRangeException(nameof(deliveryMode)); + } m_queueCapacity = queueCapacity; m_drainBudget = drainBudget; if (deliveryMode == LogDeliveryMode.Background) @@ -143,7 +144,9 @@ public void UnregisterSink(ILogSink sink) lock (m_sinksLock) { if (m_sinks.Remove(sink)) + { Volatile.Write(ref m_sinkSnapshot, m_sinks.ToArray()); + } } } @@ -182,7 +185,8 @@ public Logger CreateLogger() this, ownerType.Assembly.GetInnoAssemblyDomain(), ownerType.Assembly.GetInnoAssemblyScope(), - ownerType.Name); + ownerType.Name + ); } /// @@ -200,7 +204,9 @@ public Logger CreateLogger() public void Dispatch(LogEntry entry) { if (!TryDispatch(entry)) + { throw new InvalidOperationException("The log queue is full; the producer must apply backpressure."); + } } /// @@ -225,13 +231,19 @@ public bool TryDispatch(LogEntry entry) { ObjectDisposedException.ThrowIf(m_disposed, this); if (!IsEnabled(entry.level)) + { return true; + } if (m_queue.Count >= m_queueCapacity) + { return false; + } Enqueue(WorkItem.ForEntry(entry)); } if (m_worker is null) + { DrainInline(); + } return true; } @@ -253,11 +265,15 @@ public void Flush() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_queue.Count >= m_queueCapacity) + { throw new InvalidOperationException("The log queue is full; retry the flush after the worker drains pending entries."); + } Enqueue(WorkItem.ForBarrier(completion)); } if (m_worker is null) + { DrainInline(); + } completion.Wait(); } @@ -274,7 +290,9 @@ public void Dispose() { EnsureOutsideDelivery("dispose"); lock (m_disposalSync) + { DisposeCore(); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -285,14 +303,18 @@ private void DisposeCore() lock (m_queueSync) { if (m_disposed) + { return; + } m_disposed = true; m_running = false; m_signal.Release(); } m_worker?.Join(); if (m_worker is null) + { DrainInline(); + } ILogSink[] sinks; lock (m_sinksLock) { @@ -305,7 +327,9 @@ private void DisposeCore() for (int index = 0; index < sinks.Length; index++) { if (sinks[index] is not IDisposable disposable) + { continue; + } try { disposable.Dispose(); @@ -318,7 +342,9 @@ private void DisposeCore() } m_signal.Dispose(); if (failures is not null) + { throw new AggregateException("One or more log sinks failed to dispose.", failures); + } } private void ProcessQueue() @@ -331,7 +357,9 @@ private void ProcessQueue() m_signal.Wait(); DrainQueue(); if (!m_running && m_queue.IsEmpty) + { return; + } } } finally @@ -345,12 +373,16 @@ private void DrainInline() lock (m_inlineDeliverySync) { if (m_deliveryThreadId != 0) + { return; + } Volatile.Write(ref m_deliveryThreadId, Environment.CurrentManagedThreadId); try { while (!m_queue.IsEmpty) + { DrainQueue(); + } } finally { @@ -362,14 +394,18 @@ private void DrainInline() private void EnsureOutsideDelivery(string operation) { if (Volatile.Read(ref m_deliveryThreadId) == Environment.CurrentManagedThreadId) + { throw new InvalidOperationException($"A log delivery callback cannot {operation} its own router."); + } } private void Enqueue(WorkItem item) { m_queue.Enqueue(item); if (m_worker is not null) + { m_signal.Release(); + } } private void DrainQueue() @@ -387,7 +423,9 @@ private void DrainQueue() for (int index = 0; index < sinks.Length; index++) { if (quarantined?.Contains(sinks[index]) == true) + { continue; + } try { sinks[index].Receive(item.entry); @@ -413,8 +451,7 @@ Exception exception Action? handlers = sinkFailed; if (handlers is null) { - ReportFailureToConsole( - $"Log sink '{sink.GetType().FullName}' failed and was quarantined: {exception}"); + ReportFailureToConsole($"Log sink '{sink.GetType().FullName}' failed and was quarantined: {exception}"); return; } foreach (Delegate handler in handlers.GetInvocationList()) @@ -426,7 +463,8 @@ Exception exception catch (Exception observerFailure) { ReportFailureToConsole( - $"Log sink failure observer '{handler.Method.DeclaringType?.FullName}' failed: {observerFailure}"); + $"Log sink failure observer '{handler.Method.DeclaringType?.FullName}' failed: {observerFailure}" + ); } } } @@ -451,5 +489,4 @@ private readonly record struct WorkItem( internal static WorkItem ForBarrier(ManualResetEventSlim completion) => new(default, completion); } - } diff --git a/src/foundation/core/Inno.Core.Logging/LogSessionContext.cs b/src/foundation/core/Inno.Core.Logging/LogSessionContext.cs index 9862b2f02..1a3af7996 100644 --- a/src/foundation/core/Inno.Core.Logging/LogSessionContext.cs +++ b/src/foundation/core/Inno.Core.Logging/LogSessionContext.cs @@ -1,6 +1,6 @@ -using Inno.Core.Execution; using System; using System.Threading; +using Inno.Core.Execution; namespace Inno.Core.Logging; @@ -9,7 +9,6 @@ namespace Inno.Core.Logging; /// public static class LogSessionContext { - private static readonly ExecutionSlot S_CURRENT = new("sessionId"); /// @@ -32,7 +31,9 @@ public static class LogSessionContext public static IDisposable Enter(LogSessionId sessionId) { if (!sessionId.isAssigned) + { throw new ArgumentException("A runtime log session identifier is required.", nameof(sessionId)); + } return S_CURRENT.Enter(sessionId); } } diff --git a/src/foundation/core/Inno.Core.Logging/Logger.cs b/src/foundation/core/Inno.Core.Logging/Logger.cs index 7ae0906c8..14d460fc2 100644 --- a/src/foundation/core/Inno.Core.Logging/Logger.cs +++ b/src/foundation/core/Inno.Core.Logging/Logger.cs @@ -63,19 +63,24 @@ public void Write( ) { ArgumentException.ThrowIfNullOrWhiteSpace(message); if (!m_router.IsEnabled(level)) + { return; + } string rendered = arguments is null || arguments.Count == 0 - ? message - : string.Format(message, arguments.ToArray()); - m_router.Dispatch(new LogEntry( - level, - m_domain, - m_scope, - m_category, - rendered, - string.IsNullOrWhiteSpace(filePath) ? "Unknown" : Path.GetFullPath(filePath), - lineNumber, - new StackTrace(1, true).ToString(), - LogSessionContext.current)); + ? message + : string.Format(message, arguments.ToArray()); + m_router.Dispatch( + new LogEntry( + level, + m_domain, + m_scope, + m_category, + rendered, + string.IsNullOrWhiteSpace(filePath) ? "Unknown" : Path.GetFullPath(filePath), + lineNumber, + new StackTrace(1, true).ToString(), + LogSessionContext.current + ) + ); } } diff --git a/src/foundation/core/Inno.Core.Logging/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Logging/Properties/ScriptingApi.cs index 951761f51..958e373bf 100644 --- a/src/foundation/core/Inno.Core.Logging/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Logging/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Core.Logging; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Logging", - "Inno.Core.Logging", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Logging", "Inno.Core.Logging", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Log), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(LogSessionId), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Mathematics/Color.cs b/src/foundation/core/Inno.Core.Mathematics/Color.cs index 0b39f96a4..f5815911a 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Color.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Color.cs @@ -16,14 +16,17 @@ public struct Color : IEquatable /// The red color component. /// public float r; + /// /// The green color component. /// public float g; + /// /// The blue color component. /// public float b; + /// /// The alpha color component. /// @@ -82,7 +85,7 @@ public static Color FromBytes( ) { return new Color(r / 255f, g / 255f, b / 255f, a / 255f); } - + /// /// Converts normalized color channels to bytes by multiplying by 255 and truncating. /// @@ -98,7 +101,7 @@ public static Color FromBytes( (byte)(a * 255) ); } - + /// /// Packs normalized channels into the existing unsigned 0xAABBGGRR representation. /// @@ -118,6 +121,7 @@ public uint ToUInt32ARGB() return (uint)((alpha << 24) | (blue << 16) | (green << 8) | red); } + /// /// Formats this value as a human-readable component list. /// @@ -125,78 +129,93 @@ public uint ToUInt32ARGB() /// The validated text representation owned by the caller. /// - public override string ToString() => $"Color({r:F2}, {g:F2}, {b:F2}, {a:F2})"; - + /// /// The transparent value used as part of this type's public representation. /// public static readonly Color TRANSPARENT = new(0, 0, 0, 0); + /// /// The white value used as part of this type's public representation. /// public static readonly Color WHITE = new(1, 1, 1, 1); + /// /// The black value used as part of this type's public representation. /// public static readonly Color BLACK = new(0, 0, 0, 1); + /// /// The red value used as part of this type's public representation. /// public static readonly Color RED = FromBytes(255, 0, 0); + /// /// The green value used as part of this type's public representation. /// public static readonly Color GREEN = FromBytes(0, 255, 0); + /// /// The blue value used as part of this type's public representation. /// public static readonly Color BLUE = FromBytes(0, 0, 255); + /// /// The yellow value used as part of this type's public representation. /// public static readonly Color YELLOW = FromBytes(255, 255, 0); + /// /// The magenta value used as part of this type's public representation. /// public static readonly Color MAGENTA = FromBytes(255, 0, 255); + /// /// The cyan value used as part of this type's public representation. /// public static readonly Color CYAN = FromBytes(0, 255, 255); + /// /// The gray value used as part of this type's public representation. /// public static readonly Color GRAY = FromBytes(128, 128, 128); + /// /// The lightgray value used as part of this type's public representation. /// public static readonly Color LIGHTGRAY = FromBytes(211, 211, 211); + /// /// The darkgray value used as part of this type's public representation. /// public static readonly Color DARKGRAY = FromBytes(64, 64, 64); + /// /// The orange value used as part of this type's public representation. /// public static readonly Color ORANGE = FromBytes(255, 165, 0); + /// /// The pink value used as part of this type's public representation. /// public static readonly Color PINK = FromBytes(255, 192, 203); + /// /// The purple value used as part of this type's public representation. /// public static readonly Color PURPLE = FromBytes(128, 0, 128); + /// /// The brown value used as part of this type's public representation. /// public static readonly Color BROWN = FromBytes(139, 69, 19); + /// /// The cornflowerblue value used as part of this type's public representation. /// public static readonly Color CORNFLOWERBLUE = FromBytes(100, 149, 237); - + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -213,12 +232,7 @@ public uint ToUInt32ARGB() Color c, float factor ) { - return new Color( - c.r * factor, - c.g * factor, - c.b * factor, - c.a * factor - ); + return new Color(c.r * factor, c.g * factor, c.b * factor, c.a * factor); } /// @@ -238,10 +252,10 @@ float factor Color a, Color b ) { - return MathHelper.AlmostEquals(a.r, b.r) && - MathHelper.AlmostEquals(a.g, b.g) && - MathHelper.AlmostEquals(a.b, b.b) && - MathHelper.AlmostEquals(a.a, b.a); + return MathHelper.AlmostEquals(a.r, b.r) + && MathHelper.AlmostEquals(a.g, b.g) + && MathHelper.AlmostEquals(a.b, b.b) + && MathHelper.AlmostEquals(a.a, b.a); } /// diff --git a/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs b/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs index b56daccbe..1c5f0a7b3 100644 --- a/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs +++ b/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs @@ -14,7 +14,7 @@ public static class MathHelper /// The c tolerance value used as part of this type's public representation. /// public const float C_TOLERANCE = 1e-6f; - + /// /// Determines whether two floating-point numbers are approximately equal, /// using a relative tolerance based on the magnitude of the numbers. @@ -44,7 +44,7 @@ public static bool AlmostEquals( ) { return MathF.Abs(a - b) <= relTolerance * MathF.Max(MathF.Abs(a), MathF.Abs(b)); } - + /// /// Returns the Cartesian coordinate for one axis of a point that is defined by a given triangle and two normalized barycentric (areal) coordinates. /// @@ -74,7 +74,9 @@ public static float Barycentric( float amount1, float amount2 ) { - return (float) ((double) value1 + ((double) value2 - (double) value1) * (double) amount1 + ((double) value3 - (double) value1) * (double) amount2); + return (float) ((double) value1 + + ((double) value2 - (double) value1) * (double) amount1 + + ((double) value3 - (double) value1) * (double) amount2); } /// @@ -108,7 +110,11 @@ float amount ) { double num1 = (double) amount * (double) amount; double num2 = num1 * (double) amount; - return (float) (0.5 * (2.0 * (double) value2 + ((double) value3 - (double) value1) * (double) amount + (2.0 * (double) value1 - 5.0 * (double) value2 + 4.0 * (double) value3 - (double) value4) * num1 + (3.0 * (double) value2 - (double) value1 - 3.0 * (double) value3 + (double) value4) * num2)); + return (float) (0.5 + * (2.0 * (double) value2 + + ((double) value3 - (double) value1) * (double) amount + + (2.0 * (double) value1 - 5.0 * (double) value2 + 4.0 * (double) value3 - (double) value4) * num1 + + (3.0 * (double) value2 - (double) value1 - 3.0 * (double) value3 + (double) value4) * num2)); } /// @@ -165,7 +171,14 @@ float amount double num5 = (double) amount; double num6 = num5 * num5 * num5; double num7 = num5 * num5; - return (double) amount != 0.0 ? ((double) amount != 1.0 ? (float) ((2.0 * num1 - 2.0 * num2 + num4 + num3) * num6 + (3.0 * num2 - 3.0 * num1 - 2.0 * num3 - num4) * num7 + num3 * num5 + num1) : value2) : value1; + return (double) amount != 0.0 + ? ((double) amount != 1.0 + ? (float) ((2.0 * num1 - 2.0 * num2 + num4 + num3) * num6 + + (3.0 * num2 - 3.0 * num1 - 2.0 * num3 - num4) * num7 + + num3 * num5 + + num1) + : value2) + : value1; } /// @@ -376,10 +389,14 @@ float max public static float WrapAngle(float angle) { if ((double) angle > -3.1415927410125732 && (double) angle <= 3.1415927410125732) + { return angle; + } angle %= 6.2831855f; if ((double) angle <= -3.1415927410125732) + { return angle + 6.2831855f; + } return (double) angle > 3.1415927410125732 ? angle - 6.2831855f : angle; } diff --git a/src/foundation/core/Inno.Core.Mathematics/Matrix.cs b/src/foundation/core/Inno.Core.Mathematics/Matrix.cs index 8a339f870..9ed83b2ef 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Matrix.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Matrix.cs @@ -1,8 +1,8 @@ using System; -using System.Runtime.Serialization; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; +using System.Runtime.Serialization; namespace Inno.Core.Mathematics; @@ -32,14 +32,17 @@ public struct Matrix : IEquatable /// Row 1, Column 1. /// [DataMember] public float m11; + /// /// Row 1, Column 2. /// [DataMember] public float m12; + /// /// Row 1, Column 3. /// [DataMember] public float m13; + /// /// Row 1, Column 4. /// @@ -49,14 +52,17 @@ public struct Matrix : IEquatable /// Row 2, Column 1. /// [DataMember] public float m21; + /// /// Row 2, Column 2. /// [DataMember] public float m22; + /// /// Row 2, Column 3. /// [DataMember] public float m23; + /// /// Row 2, Column 4. /// @@ -66,14 +72,17 @@ public struct Matrix : IEquatable /// Row 3, Column 1. /// [DataMember] public float m31; + /// /// Row 3, Column 2. /// [DataMember] public float m32; + /// /// Row 3, Column 3. /// [DataMember] public float m33; + /// /// Row 3, Column 4. /// @@ -83,14 +92,17 @@ public struct Matrix : IEquatable /// Row 4, Column 1 (translation X component for affine transforms). /// [DataMember] public float m41; + /// /// Row 4, Column 2 (translation Y component for affine transforms). /// [DataMember] public float m42; + /// /// Row 4, Column 3 (translation Z component for affine transforms). /// [DataMember] public float m43; + /// /// Row 4, Column 4. /// @@ -178,11 +190,7 @@ float m44 /// /// Gets the identity matrix. /// - public static Matrix identity => new Matrix( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); + public static Matrix identity => new Matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); #endregion @@ -208,11 +216,7 @@ public static Matrix CreateTranslation( float y, float z ) { - return new Matrix( - 1, 0, 0, x, - 0, 1, 0, y, - 0, 0, 1, z, - 0, 0, 0, 1); + return new Matrix(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); } /// @@ -257,11 +261,7 @@ public static Matrix CreateScale( float y, float z ) { - return new Matrix( - x, 0, 0, 0, - 0, y, 0, 0, - 0, 0, z, 0, - 0, 0, 0, 1); + return new Matrix(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); } /// @@ -288,11 +288,7 @@ public static Matrix CreateRotationX(float radians) { float c = MathF.Cos(radians); float s = MathF.Sin(radians); - return new Matrix( - 1, 0, 0, 0, - 0, c, -s, 0, - 0, s, c, 0, - 0, 0, 0, 1); + return new Matrix(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1); } /// @@ -308,11 +304,7 @@ public static Matrix CreateRotationY(float radians) { float c = MathF.Cos(radians); float s = MathF.Sin(radians); - return new Matrix( - c, 0, s, 0, - 0, 1, 0, 0, - -s, 0, c, 0, - 0, 0, 0, 1); + return new Matrix(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1); } /// @@ -328,11 +320,7 @@ public static Matrix CreateRotationZ(float radians) { float c = MathF.Cos(radians); float s = MathF.Sin(radians); - return new Matrix( - c, -s, 0, 0, - s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); + return new Matrix(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } /// @@ -351,10 +339,23 @@ public static Matrix CreateFromQuaternion(Quaternion q) float wx = q.w * q.x, wy = q.w * q.y, wz = q.w * q.z; return new Matrix( - 1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy), 0, - 2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx), 0, - 2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy), 0, - 0, 0, 0, 1); + 1 - 2 * (yy + zz), + 2 * (xy - wz), + 2 * (xz + wy), + 0, + 2 * (xy + wz), + 1 - 2 * (xx + zz), + 2 * (yz - wx), + 0, + 2 * (xz - wy), + 2 * (yz + wx), + 1 - 2 * (xx + yy), + 0, + 0, + 0, + 0, + 1 + ); } #endregion @@ -388,11 +389,7 @@ float far float f = 1f / MathF.Tan(fov * 0.5f); float nf = 1f / (far - near); - return new Matrix( - f / aspect, 0, 0, 0, - 0, f, 0, 0, - 0, 0, far * nf, -near * far * nf, - 0, 0, 1, 0); + return new Matrix(f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, far * nf, -near * far * nf, 0, 0, 1, 0); } /// @@ -422,11 +419,7 @@ float far float f = 1f / MathF.Tan(fov * 0.5f); float nf = 1f / (near - far); - return new Matrix( - f / aspect, 0, 0, 0, - 0, f, 0, 0, - 0, 0, far * nf, near * far * nf, - 0, 0, -1, 0); + return new Matrix(f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, far * nf, near * far * nf, 0, 0, -1, 0); } /// @@ -453,13 +446,7 @@ public static Matrix CreateOrthographic( float near, float far ) { - return CreateOrthographicOffCenter( - -width * 0.5f, - width * 0.5f, - -height * 0.5f, - height * 0.5f, - near, - far); + return CreateOrthographicOffCenter(-width * 0.5f, width * 0.5f, -height * 0.5f, height * 0.5f, near, far); } /// @@ -501,12 +488,7 @@ float far float m24 = -(top + bottom) / (top - bottom); float m34 = -near / (far - near); - return new Matrix( - m00, 0, 0, m14, - 0, m11, 0, m24, - 0, 0, m22, m34, - 0, 0, 0, 1 - ); + return new Matrix(m00, 0, 0, m14, 0, m11, 0, m24, 0, 0, m22, m34, 0, 0, 0, 1); } #endregion @@ -539,10 +521,23 @@ Vector3 up Vector3 y = Vector3.Cross(z, x); // up return new Matrix( - x.x, x.y, x.z, -Vector3.Dot(x, eye), - y.x, y.y, y.z, -Vector3.Dot(y, eye), - z.x, z.y, z.z, -Vector3.Dot(z, eye), - 0, 0, 0, 1); + x.x, + x.y, + x.z, + -Vector3.Dot(x, eye), + y.x, + y.y, + y.z, + -Vector3.Dot(y, eye), + z.x, + z.y, + z.z, + -Vector3.Dot(z, eye), + 0, + 0, + 0, + 1 + ); } /// @@ -571,13 +566,25 @@ Vector3 up Vector3 y = Vector3.Cross(z, x); // up return new Matrix( - x.x, x.y, x.z, -Vector3.Dot(x, eye), - y.x, y.y, y.z, -Vector3.Dot(y, eye), - z.x, z.y, z.z, -Vector3.Dot(z, eye), - 0, 0, 0, 1); + x.x, + x.y, + x.z, + -Vector3.Dot(x, eye), + y.x, + y.y, + y.z, + -Vector3.Dot(y, eye), + z.x, + z.y, + z.z, + -Vector3.Dot(z, eye), + 0, + 0, + 0, + 1 + ); } - #endregion #region Operations @@ -737,10 +744,23 @@ out Vector3 translation } var rot = new Matrix( - col0.x / scale.x, col1.x / scale.y, col2.x / scale.z, 0f, - col0.y / scale.x, col1.y / scale.y, col2.y / scale.z, 0f, - col0.z / scale.x, col1.z / scale.y, col2.z / scale.z, 0f, - 0f, 0f, 0f, 1f); + col0.x / scale.x, + col1.x / scale.y, + col2.x / scale.z, + 0f, + col0.y / scale.x, + col1.y / scale.y, + col2.y / scale.z, + 0f, + col0.z / scale.x, + col1.z / scale.y, + col2.z / scale.z, + 0f, + 0f, + 0f, + 0f, + 1f + ); rotation = Quaternion.FromRotationMatrix(rot); return true; @@ -757,12 +777,7 @@ out Vector3 translation /// public static Matrix Extract2DTransform(Matrix m) { - return new Matrix( - m.m11, m.m12, 0, m.m14, - m.m21, m.m22, 0, m.m24, - 0, 0, 1, 0, - 0, 0, 0, 1 - ); + return new Matrix(m.m11, m.m12, 0, m.m14, m.m21, m.m22, 0, m.m24, 0, 0, 1, 0, 0, 0, 0, 1); } /// @@ -777,10 +792,22 @@ public static Matrix Extract2DTransform(Matrix m) public static Matrix Transpose(Matrix a) { return new Matrix( - a.m11, a.m21, a.m31, a.m41, - a.m12, a.m22, a.m32, a.m42, - a.m13, a.m23, a.m33, a.m43, - a.m14, a.m24, a.m34, a.m44 + a.m11, + a.m21, + a.m31, + a.m41, + a.m12, + a.m22, + a.m32, + a.m42, + a.m13, + a.m23, + a.m33, + a.m43, + a.m14, + a.m24, + a.m34, + a.m44 ); } @@ -815,7 +842,9 @@ public static Matrix Invert(Matrix m) float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (MathF.Abs(det) < MathHelper.C_TOLERANCE) + { return identity; + } float invDet = 1f / det; @@ -939,22 +968,22 @@ Matrix b Matrix matrix2 ) { return - MathHelper.AlmostEquals(matrix1.m11, matrix2.m11) && - MathHelper.AlmostEquals(matrix1.m12, matrix2.m12) && - MathHelper.AlmostEquals(matrix1.m13, matrix2.m13) && - MathHelper.AlmostEquals(matrix1.m14, matrix2.m14) && - MathHelper.AlmostEquals(matrix1.m21, matrix2.m21) && - MathHelper.AlmostEquals(matrix1.m22, matrix2.m22) && - MathHelper.AlmostEquals(matrix1.m23, matrix2.m23) && - MathHelper.AlmostEquals(matrix1.m24, matrix2.m24) && - MathHelper.AlmostEquals(matrix1.m31, matrix2.m31) && - MathHelper.AlmostEquals(matrix1.m32, matrix2.m32) && - MathHelper.AlmostEquals(matrix1.m33, matrix2.m33) && - MathHelper.AlmostEquals(matrix1.m34, matrix2.m34) && - MathHelper.AlmostEquals(matrix1.m41, matrix2.m41) && - MathHelper.AlmostEquals(matrix1.m42, matrix2.m42) && - MathHelper.AlmostEquals(matrix1.m43, matrix2.m43) && - MathHelper.AlmostEquals(matrix1.m44, matrix2.m44); + MathHelper.AlmostEquals(matrix1.m11, matrix2.m11) + && MathHelper.AlmostEquals(matrix1.m12, matrix2.m12) + && MathHelper.AlmostEquals(matrix1.m13, matrix2.m13) + && MathHelper.AlmostEquals(matrix1.m14, matrix2.m14) + && MathHelper.AlmostEquals(matrix1.m21, matrix2.m21) + && MathHelper.AlmostEquals(matrix1.m22, matrix2.m22) + && MathHelper.AlmostEquals(matrix1.m23, matrix2.m23) + && MathHelper.AlmostEquals(matrix1.m24, matrix2.m24) + && MathHelper.AlmostEquals(matrix1.m31, matrix2.m31) + && MathHelper.AlmostEquals(matrix1.m32, matrix2.m32) + && MathHelper.AlmostEquals(matrix1.m33, matrix2.m33) + && MathHelper.AlmostEquals(matrix1.m34, matrix2.m34) + && MathHelper.AlmostEquals(matrix1.m41, matrix2.m41) + && MathHelper.AlmostEquals(matrix1.m42, matrix2.m42) + && MathHelper.AlmostEquals(matrix1.m43, matrix2.m43) + && MathHelper.AlmostEquals(matrix1.m44, matrix2.m44); } /// @@ -987,10 +1016,22 @@ Matrix b public static implicit operator System.Numerics.Matrix4x4(Matrix m) { return new System.Numerics.Matrix4x4( - m.m11, m.m12, m.m13, m.m14, - m.m21, m.m22, m.m23, m.m24, - m.m31, m.m32, m.m33, m.m34, - m.m41, m.m42, m.m43, m.m44 + m.m11, + m.m12, + m.m13, + m.m14, + m.m21, + m.m22, + m.m23, + m.m24, + m.m31, + m.m32, + m.m33, + m.m34, + m.m41, + m.m42, + m.m43, + m.m44 ); } @@ -1008,10 +1049,22 @@ public static implicit operator Matrix(System.Numerics.Matrix4x4 m) { return new Matrix { - m11 = m.M11, m12 = m.M12, m13 = m.M13, m14 = m.M14, - m21 = m.M21, m22 = m.M22, m23 = m.M23, m24 = m.M24, - m31 = m.M31, m32 = m.M32, m33 = m.M33, m34 = m.M34, - m41 = m.M41, m42 = m.M42, m43 = m.M43, m44 = m.M44 + m11 = m.M11, + m12 = m.M12, + m13 = m.M13, + m14 = m.M14, + m21 = m.M21, + m22 = m.M22, + m23 = m.M23, + m24 = m.M24, + m31 = m.M31, + m32 = m.M32, + m33 = m.M33, + m34 = m.M34, + m41 = m.M41, + m42 = m.M42, + m43 = m.M43, + m44 = m.M44 }; } @@ -1049,13 +1102,12 @@ public static implicit operator Matrix(System.Numerics.Matrix4x4 m) /// public override int GetHashCode() { - return this.m11.GetHashCode() + this.m12.GetHashCode() + this.m13.GetHashCode() + this.m14.GetHashCode() + - this.m21.GetHashCode() + this.m22.GetHashCode() + this.m23.GetHashCode() + this.m24.GetHashCode() + - this.m31.GetHashCode() + this.m32.GetHashCode() + this.m33.GetHashCode() + this.m34.GetHashCode() + - this.m41.GetHashCode() + this.m42.GetHashCode() + this.m43.GetHashCode() + this.m44.GetHashCode(); + return this.m11.GetHashCode() + this.m12.GetHashCode() + this.m13.GetHashCode() + this.m14.GetHashCode() + + this.m21.GetHashCode() + this.m22.GetHashCode() + this.m23.GetHashCode() + this.m24.GetHashCode() + + this.m31.GetHashCode() + this.m32.GetHashCode() + this.m33.GetHashCode() + this.m34.GetHashCode() + + this.m41.GetHashCode() + this.m42.GetHashCode() + this.m43.GetHashCode() + this.m44.GetHashCode(); } - /// /// Returns a multi-line string representation of the matrix in row-major layout. /// @@ -1064,11 +1116,11 @@ public override int GetHashCode() /// public override string ToString() { - return $"[{m11}, {m12}, {m13}, {m14}]\n" + - $"[{m21}, {m22}, {m23}, {m24}]\n" + - $"[{m31}, {m32}, {m33}, {m34}]\n" + - $"[{m41}, {m42}, {m43}, {m44}]"; + return $"[{m11}, {m12}, {m13}, {m14}]\n" + + $"[{m21}, {m22}, {m23}, {m24}]\n" + + $"[{m31}, {m32}, {m33}, {m34}]\n" + + $"[{m41}, {m42}, {m43}, {m44}]"; } - + #endregion } diff --git a/src/foundation/core/Inno.Core.Mathematics/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Mathematics/Properties/ScriptingApi.cs index cdf4ea6cf..e89a0d9a4 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Core.Mathematics; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Mathematics", - "Inno.Core.Mathematics", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Mathematics", "Inno.Core.Mathematics", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Color), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(MathHelper), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs b/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs index 149e260d1..a9b20a8b4 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs @@ -14,14 +14,17 @@ public struct Quaternion : IEquatable /// The horizontal or first component. /// [DataMember] public float x; + /// /// The vertical or second component. /// [DataMember] public float y; + /// /// The depth or third component. /// [DataMember] public float z; + /// /// The homogeneous or fourth component. /// @@ -96,7 +99,9 @@ public static Quaternion Normalize(Quaternion q) { float len = q.Length(); if (len < 1e-6f) + { return identity; + } return new Quaternion(q.x / len, q.y / len, q.z / len, q.w / len); } @@ -126,7 +131,9 @@ public static Quaternion Inverse(Quaternion q) { float lenSq = q.LengthSquared(); if (lenSq < 1e-6f) + { return identity; + } var conj = Conjugate(q); return new Quaternion(conj.x / lenSq, conj.y / lenSq, conj.z / lenSq, conj.w / lenSq); } @@ -179,12 +186,7 @@ float t float s0 = MathF.Cos(theta) - dot * sinTheta / sinTheta0; float s1 = sinTheta / sinTheta0; - return new Quaternion( - a.x * s0 + b.x * s1, - a.y * s0 + b.y * s1, - a.z * s0 + b.z * s1, - a.w * s0 + b.w * s1 - ); + return new Quaternion(a.x * s0 + b.x * s1, a.y * s0 + b.y * s1, a.z * s0 + b.z * s1, a.w * s0 + b.w * s1); } /// @@ -207,12 +209,7 @@ float angle axis = axis.normalized; float halfAngle = angle * 0.5f; float sin = MathF.Sin(halfAngle); - return new Quaternion( - axis.x * sin, - axis.y * sin, - axis.z * sin, - MathF.Cos(halfAngle) - ); + return new Quaternion(axis.x * sin, axis.y * sin, axis.z * sin, MathF.Cos(halfAngle)); } /// @@ -232,42 +229,39 @@ public static Quaternion FromRotationMatrix(Matrix m) { float s = MathF.Sqrt(trace + 1f) * 2f; float invS = 1f / s; - return Normalize(new Quaternion( - (m.m32 - m.m23) * invS, - (m.m13 - m.m31) * invS, - (m.m21 - m.m12) * invS, - 0.25f * s)); + return Normalize( + new Quaternion((m.m32 - m.m23) * invS, (m.m13 - m.m31) * invS, (m.m21 - m.m12) * invS, 0.25f * s) + ); } if (m.m11 > m.m22 && m.m11 > m.m33) { float s = MathF.Sqrt(1f + m.m11 - m.m22 - m.m33) * 2f; float invS = 1f / s; - return Normalize(new Quaternion( - 0.25f * s, - (m.m12 + m.m21) * invS, - (m.m13 + m.m31) * invS, - (m.m32 - m.m23) * invS)); + return Normalize( + new Quaternion(0.25f * s, (m.m12 + m.m21) * invS, (m.m13 + m.m31) * invS, (m.m32 - m.m23) * invS) + ); } if (m.m22 > m.m33) { float s = MathF.Sqrt(1f + m.m22 - m.m11 - m.m33) * 2f; float invS = 1f / s; - return Normalize(new Quaternion( - (m.m12 + m.m21) * invS, - 0.25f * s, - (m.m23 + m.m32) * invS, - (m.m13 - m.m31) * invS)); + return Normalize( + new Quaternion((m.m12 + m.m21) * invS, 0.25f * s, (m.m23 + m.m32) * invS, (m.m13 - m.m31) * invS) + ); } float sFinal = MathF.Sqrt(1f + m.m33 - m.m11 - m.m22) * 2f; float invFinal = 1f / sFinal; - return Normalize(new Quaternion( - (m.m13 + m.m31) * invFinal, - (m.m23 + m.m32) * invFinal, - 0.25f * sFinal, - (m.m21 - m.m12) * invFinal)); + return Normalize( + new Quaternion( + (m.m13 + m.m31) * invFinal, + (m.m23 + m.m32) * invFinal, + 0.25f * sFinal, + (m.m21 - m.m12) * invFinal + ) + ); } /// @@ -291,11 +285,7 @@ Vector3 up Vector3 x = Vector3.NormalizeSafe(Vector3.Cross(up, z)); Vector3 y = Vector3.Cross(z, x); - var m = new Matrix( - x.x, y.x, z.x, 0f, - x.y, y.y, z.y, 0f, - x.z, y.z, z.z, 0f, - 0f, 0f, 0f, 1f); + var m = new Matrix(x.x, y.x, z.x, 0f, x.y, y.y, z.y, 0f, x.z, y.z, z.z, 0f, 0f, 0f, 0f, 1f); return FromRotationMatrix(m); } @@ -329,8 +319,7 @@ public static Quaternion CreateFromYawPitchRoll( float yaw, float pitch, float roll - ) - => FromEulerAnglesZYX(new Vector3(pitch, yaw, roll)); + ) => FromEulerAnglesZYX(new Vector3(pitch, yaw, roll)); /// /// Converts this value to its euler angles xyz representation. @@ -341,20 +330,19 @@ float roll public Vector3 ToEulerAnglesXYZ() { Quaternion normalized = this.normalized; - float sinY = Math.Clamp( - 2f * (normalized.x * normalized.z + normalized.w * normalized.y), - -1f, - 1f); + float sinY = Math.Clamp(2f * (normalized.x * normalized.z + normalized.w * normalized.y), -1f, 1f); float angleY = MathF.Asin(sinY); float angleX = MathF.Atan2( 2f * (normalized.w * normalized.x - normalized.y * normalized.z), - 1f - 2f * (normalized.x * normalized.x + normalized.y * normalized.y)); + 1f - 2f * (normalized.x * normalized.x + normalized.y * normalized.y) + ); float angleZ = MathF.Atan2( 2f * (normalized.w * normalized.z - normalized.x * normalized.y), - 1f - 2f * (normalized.y * normalized.y + normalized.z * normalized.z)); + 1f - 2f * (normalized.y * normalized.y + normalized.z * normalized.z) + ); return new Vector3(angleX, angleY, angleZ); } - + /// /// Converts this value to its euler angles xyzdegrees representation. /// @@ -377,8 +365,8 @@ public Vector3 ToEulerAnglesZYX() float sinp = 2 * (w * y - z * x); float angleY = MathF.Abs(sinp) >= 1 - ? MathF.CopySign(MathF.PI / 2, sinp) - : MathF.Asin(sinp); + ? MathF.CopySign(MathF.PI / 2, sinp) + : MathF.Asin(sinp); float sinyCosp = 2 * (w * x + y * z); float cosyCosp = 1 - 2 * (x * x + y * y); @@ -386,7 +374,7 @@ public Vector3 ToEulerAnglesZYX() return new Vector3(angleX, angleY, angleZ); } - + /// /// Converts this value to its euler angles zyxdegrees representation. /// @@ -401,18 +389,14 @@ public Vector3 ToEulerAnglesZYXDegrees() float sinp = 2 * (w * y - z * x); float angleY = MathF.Abs(sinp) >= 1 - ? MathF.CopySign(MathF.PI / 2, sinp) - : MathF.Asin(sinp); + ? MathF.CopySign(MathF.PI / 2, sinp) + : MathF.Asin(sinp); float sinyCosp = 2 * (w * x + y * z); float cosyCosp = 1 - 2 * (x * x + y * y); float angleX = MathF.Atan2(sinyCosp, cosyCosp); - return new Vector3( - angleX * 180f / MathF.PI, - angleY * 180f / MathF.PI, - angleZ * 180f / MathF.PI - ); + return new Vector3(angleX * 180f / MathF.PI, angleY * 180f / MathF.PI, angleZ * 180f / MathF.PI); } /// @@ -441,7 +425,7 @@ public static Quaternion FromEulerAnglesXYZ(Vector3 euler) cx * cy * cz - sx * sy * sz ); } - + /// /// Creates the target representation from the supplied euler angles xyzdegrees value. /// @@ -497,7 +481,7 @@ public static Quaternion FromEulerAnglesZYX(Vector3 euler) cx * cy * cz + sx * sy * sz ); } - + /// /// Creates the target representation from the supplied euler angles zyxdegrees value. /// @@ -566,11 +550,10 @@ Quaternion b public static bool operator ==( Quaternion a, Quaternion b - ) - => MathHelper.AlmostEquals(a.x, b.x) && - MathHelper.AlmostEquals(a.y, b.y) && - MathHelper.AlmostEquals(a.z, b.z) && - MathHelper.AlmostEquals(a.w, b.w); + ) => MathHelper.AlmostEquals(a.x, b.x) + && MathHelper.AlmostEquals(a.y, b.y) + && MathHelper.AlmostEquals(a.z, b.z) + && MathHelper.AlmostEquals(a.w, b.w); /// /// Determines whether the supplied values differ under the type's equality tolerance. @@ -588,7 +571,7 @@ Quaternion b Quaternion a, Quaternion b ) => !(a == b); - + /// /// Converts the supplied value to . /// @@ -599,6 +582,7 @@ Quaternion b /// The validated system.numerics.quaternion that represents the completed operation. /// public static implicit operator System.Numerics.Quaternion(Quaternion q) => new(q.x, q.y, q.z, q.w); + /// /// Converts the supplied value to . /// diff --git a/src/foundation/core/Inno.Core.Mathematics/Rect.cs b/src/foundation/core/Inno.Core.Mathematics/Rect.cs index ca59e0775..288c9ffa0 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Rect.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Rect.cs @@ -18,14 +18,17 @@ public struct Rect : IEquatable /// Gets the scalar measurement or identity associated with the current state. /// public float left => x; + /// /// Gets the scalar measurement or identity associated with the current state. /// public float right => x + width; + /// /// Gets the scalar measurement or identity associated with the current state. /// public float top => y; + /// /// Gets the scalar measurement or identity associated with the current state. /// @@ -35,14 +38,17 @@ public struct Rect : IEquatable /// Gets the minimum corner of this axis-aligned rectangle. /// public Vector2 min => new(x, y); + /// /// Gets the maximum corner of this axis-aligned rectangle. /// public Vector2 max => new(x + width, y + height); + /// /// Gets the width and height derived from the rectangle bounds. /// public Vector2 size => new(width, height); + /// /// Gets the midpoint derived from the rectangle bounds. /// @@ -87,10 +93,10 @@ float height [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Overlaps(Rect other) { - return !(right <= other.left || - left >= other.right || - bottom <= other.top || - top >= other.bottom); + return !(right <= other.left + || left >= other.right + || bottom <= other.top + || top >= other.bottom); } /// @@ -105,10 +111,10 @@ public bool Overlaps(Rect other) [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(Rect other) { - return left <= other.left && - top <= other.top && - right >= other.right && - bottom >= other.bottom; + return left <= other.left + && top <= other.top + && right >= other.right + && bottom >= other.bottom; } /// @@ -128,8 +134,8 @@ public bool Contains( float px, float py ) { - return px >= left && px < right && - py >= top && py < bottom; + return px >= left && px < right + && py >= top && py < bottom; } /// @@ -241,6 +247,7 @@ out Rect intersection Rect a, Rect b ) => a.Equals(b); + /// /// Determines whether the supplied values differ under the type's equality tolerance. /// @@ -306,6 +313,7 @@ Rect b /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator System.Numerics.Vector4(Rect r) => new System.Numerics.Vector4(r.x, r.y, r.width, r.height); + /// /// Converts the supplied value to . /// @@ -317,7 +325,7 @@ Rect b /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Rect(System.Numerics.Vector4 v) => new Rect(v.X, v.Y, v.Z, v.W); - + /// /// Determines whether this value and the supplied value represent the same logical state. /// @@ -328,6 +336,7 @@ Rect b /// when the requested condition is satisfied; otherwise, . /// public override bool Equals(object? obj) => obj is Rect r && Equals(r); + /// /// Determines whether this value and the supplied value represent the same logical state. /// @@ -337,11 +346,12 @@ Rect b /// /// when the requested condition is satisfied; otherwise, . /// - public bool Equals(Rect other) => - MathHelper.AlmostEquals(x, other.x) && - MathHelper.AlmostEquals(y, other.y) && - MathHelper.AlmostEquals(width, other.width) && - MathHelper.AlmostEquals(height, other.height); + public bool Equals(Rect other) + => MathHelper.AlmostEquals(x, other.x) + && MathHelper.AlmostEquals(y, other.y) + && MathHelper.AlmostEquals(width, other.width) + && MathHelper.AlmostEquals(height, other.height); + /// /// Computes a hash code consistent with the implemented equality contract. /// @@ -349,6 +359,7 @@ public bool Equals(Rect other) => /// The scalar result calculated from the supplied inputs. /// public override int GetHashCode() => HashCode.Combine(x, y, width, height); + /// /// Formats this value as a human-readable component list. /// diff --git a/src/foundation/core/Inno.Core.Mathematics/RectInt.cs b/src/foundation/core/Inno.Core.Mathematics/RectInt.cs index acf5671ca..45b0a4f18 100644 --- a/src/foundation/core/Inno.Core.Mathematics/RectInt.cs +++ b/src/foundation/core/Inno.Core.Mathematics/RectInt.cs @@ -19,14 +19,17 @@ public struct RectInt : IEquatable /// Gets the scalar measurement or identity associated with the current state. /// public int left => x; + /// /// Gets the scalar measurement or identity associated with the current state. /// public int right => x + width; + /// /// Gets the scalar measurement or identity associated with the current state. /// public int top => y; + /// /// Gets the scalar measurement or identity associated with the current state. /// @@ -36,14 +39,17 @@ public struct RectInt : IEquatable /// Gets the minimum corner of this axis-aligned rectangle. /// public Vector2Int min => new(x, y); + /// /// Gets the maximum corner of this axis-aligned rectangle. /// public Vector2Int max => new(x + width, y + height); + /// /// Gets the width and height derived from the rectangle bounds. /// public Vector2Int size => new(width, height); + /// /// Gets the midpoint derived from the rectangle bounds. /// @@ -88,10 +94,10 @@ int height [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Overlaps(RectInt other) { - return !(right <= other.left || - left >= other.right || - bottom <= other.top || - top >= other.bottom); + return !(right <= other.left + || left >= other.right + || bottom <= other.top + || top >= other.bottom); } /// @@ -106,10 +112,10 @@ public bool Overlaps(RectInt other) [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(RectInt other) { - return left <= other.left && - top <= other.top && - right >= other.right && - bottom >= other.bottom; + return left <= other.left + && top <= other.top + && right >= other.right + && bottom >= other.bottom; } /// @@ -129,8 +135,8 @@ public bool Contains( int px, int py ) { - return px >= left && px < right && - py >= top && py < bottom; + return px >= left && px < right + && py >= top && py < bottom; } /// @@ -242,6 +248,7 @@ out RectInt intersection RectInt a, RectInt b ) => a.Equals(b); + /// /// Determines whether the supplied values differ under the type's equality tolerance. /// @@ -354,6 +361,7 @@ RectInt b /// when the requested condition is satisfied; otherwise, . /// public override bool Equals(object? obj) => obj is RectInt r && Equals(r); + /// /// Determines whether this value and the supplied value represent the same logical state. /// @@ -364,6 +372,7 @@ RectInt b /// when the requested condition is satisfied; otherwise, . /// public bool Equals(RectInt other) => x == other.x && y == other.y && width == other.width && height == other.height; + /// /// Computes a hash code consistent with the implemented equality contract. /// @@ -371,6 +380,7 @@ RectInt b /// The scalar result calculated from the supplied inputs. /// public override int GetHashCode() => HashCode.Combine(x, y, width, height); + /// /// Formats this value as a human-readable component list. /// diff --git a/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs b/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs index a31428efd..f3a8d1d25 100644 --- a/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs +++ b/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs @@ -37,9 +37,9 @@ Vector128 b } return a.GetElement(0) * b.GetElement(0) - + a.GetElement(1) * b.GetElement(1) - + a.GetElement(2) * b.GetElement(2) - + a.GetElement(3) * b.GetElement(3); + + a.GetElement(1) * b.GetElement(1) + + a.GetElement(2) * b.GetElement(2) + + a.GetElement(3) * b.GetElement(3); } /// diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector2.cs b/src/foundation/core/Inno.Core.Mathematics/Vector2.cs index 38cd00183..570bbacff 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector2.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector2.cs @@ -14,6 +14,7 @@ public struct Vector2 : IEquatable /// The horizontal or first component. /// [DataMember] public float x; + /// /// The vertical or second component. /// @@ -40,14 +41,17 @@ float y /// A value whose components are all zero. /// public static readonly Vector2 ZERO = new(0f, 0f); + /// /// A value whose components are all one. /// public static readonly Vector2 ONE = new(1f, 1f); + /// /// A unit value aligned with the x axis. /// public static readonly Vector2 UNIT_X = new(1f, 0f); + /// /// A unit value aligned with the y axis. /// @@ -273,7 +277,7 @@ public static Vector2 Reflect( Vector2 v, Vector2 n ) => v - 2f * Dot(v, n) * n; - + /// /// Transforms the supplied value by the requested transformation. /// @@ -319,11 +323,12 @@ Quaternion rotation float w = rotation.w; return new Vector2( value.x * (1f - 2f * (y * y + z * z)) - + value.y * (2f * (x * y - z * w)), + + value.y * (2f * (x * y - z * w)), value.x * (2f * (x * y + z * w)) - + value.y * (1f - 2f * (x * x + z * z)) + + value.y * (1f - 2f * (x * x + z * z)) ); } + /// /// Adds the supplied values component by component. /// @@ -343,6 +348,7 @@ Quaternion rotation Vector2 a, Vector2 b ) => new Vector2(a.x + b.x, a.y + b.y); + /// /// Subtracts or negates the supplied value component by component. /// @@ -360,6 +366,7 @@ Vector2 b Vector2 a, Vector2 b ) => new Vector2(a.x - b.x, a.y - b.y); + /// /// Subtracts or negates the supplied value component by component. /// @@ -371,6 +378,7 @@ Vector2 b /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator -(Vector2 v) => new Vector2(-v.x, -v.y); + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -388,6 +396,7 @@ Vector2 b Vector2 v, float scalar ) => new Vector2(v.x * scalar, v.y * scalar); + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -405,6 +414,7 @@ float scalar float scalar, Vector2 v ) => v * scalar; + /// /// Divides the supplied value by the scalar divisor component by component. /// @@ -440,6 +450,7 @@ float scalar Vector2 a, Vector2 b ) => MathHelper.AlmostEquals(a.x, b.x) && MathHelper.AlmostEquals(a.y, b.y); + /// /// Determines whether the supplied values differ under the type's equality tolerance. /// @@ -457,7 +468,7 @@ Vector2 b Vector2 a, Vector2 b ) => !(a == b); - + /// /// Converts the supplied value to . /// @@ -468,6 +479,7 @@ Vector2 b /// The validated system.numerics.vector2 that represents the completed operation. /// public static implicit operator System.Numerics.Vector2(Vector2 v) => new(v.x, v.y); + /// /// Converts the supplied value to . /// @@ -489,6 +501,7 @@ Vector2 b /// when the requested condition is satisfied; otherwise, . /// public override bool Equals(object? obj) => obj is Vector2 other && Equals(other); + /// /// Determines whether this value and the supplied value represent the same logical state. /// @@ -499,6 +512,7 @@ Vector2 b /// when the requested condition is satisfied; otherwise, . /// public bool Equals(Vector2 other) => MathHelper.AlmostEquals(x, other.x) && MathHelper.AlmostEquals(y, other.y); + /// /// Computes a hash code consistent with the implemented equality contract. /// @@ -506,6 +520,7 @@ Vector2 b /// The scalar result calculated from the supplied inputs. /// public override int GetHashCode() => HashCode.Combine(x, y); + /// /// Formats this value as a human-readable component list. /// diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs b/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs index 6bc86461b..59a44683f 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs @@ -14,6 +14,7 @@ public struct Vector2Int : IEquatable /// The horizontal or first component. /// [DataMember] public int x; + /// /// The vertical or second component. /// @@ -35,24 +36,29 @@ int y this.x = x; this.y = y; } + /// /// A value whose components are all zero. /// // Common constants public static readonly Vector2Int ZERO = new(0, 0); + /// /// A value whose components are all one. /// public static readonly Vector2Int ONE = new(1, 1); + /// /// A unit value aligned with the x axis. /// public static readonly Vector2Int UNIT_X = new(1, 0); + /// /// A unit value aligned with the y axis. /// public static readonly Vector2Int UNIT_Y = new(0, 1); + /// /// Adds the supplied values component by component. /// @@ -192,6 +198,7 @@ Vector2Int b Vector2Int a, Vector2Int b ) => !(a == b); + /// /// Converts the supplied value to . /// @@ -217,6 +224,7 @@ Vector2Int b /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Vector2Int(Vector2 v) => new((int)v.x, (int)v.y); + /// /// Determines whether this value and the supplied value represent the same logical state. /// diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector3.cs b/src/foundation/core/Inno.Core.Mathematics/Vector3.cs index 27a3e90f0..e183613b9 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector3.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector3.cs @@ -1,9 +1,9 @@ using System; using System.Runtime.CompilerServices; -using System.Runtime.Serialization; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; +using System.Runtime.Serialization; namespace Inno.Core.Mathematics; @@ -17,10 +17,12 @@ public struct Vector3 : IEquatable /// The horizontal or first component. /// [DataMember] public float x; + /// /// The vertical or second component. /// [DataMember] public float y; + /// /// The depth or third component. /// @@ -47,40 +49,49 @@ float z this.y = y; this.z = z; } + /// /// A value whose components are all zero. /// // Common static vectors public static readonly Vector3 ZERO = new(0, 0, 0); + /// /// A value whose components are all one. /// public static readonly Vector3 ONE = new(1, 1, 1); + /// /// The up value used as part of this type's public representation. /// public static readonly Vector3 UP = new(0, 1, 0); + /// /// The down value used as part of this type's public representation. /// public static readonly Vector3 DOWN = new(0, -1, 0); + /// /// The left value used as part of this type's public representation. /// public static readonly Vector3 LEFT = new(-1, 0, 0); + /// /// The right value used as part of this type's public representation. /// public static readonly Vector3 RIGHT = new(1, 0, 0); + /// /// The forward value used as part of this type's public representation. /// public static readonly Vector3 FORWARD = new(0, 0, 1); + /// /// The back value used as part of this type's public representation. /// public static readonly Vector3 BACK = new(0, 0, -1); + /// /// Calculates the Euclidean magnitude of this value. /// @@ -133,6 +144,7 @@ public static Vector3 NormalizeSafe( float len = value.Length(); return len > epsilon ? value / len : ZERO; } + /// /// Calculates the scalar dot product of two values. /// @@ -233,6 +245,7 @@ Vector3 onto return onto * (Dot(vector, onto) / denom); } + /// /// Calculates the vector perpendicular to both supplied vectors. /// @@ -251,11 +264,8 @@ Vector3 onto public static Vector3 Cross( Vector3 a, Vector3 b - ) => new( - a.y * b.z - a.z * b.y, - a.z * b.x - a.x * b.z, - a.x * b.y - a.y * b.x - ); + ) => new(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); + /// /// Calculates the Euclidean distance between two points. /// @@ -275,6 +285,7 @@ public static float Distance( Vector3 a, Vector3 b ) => (a - b).Length(); + /// /// Interpolates linearly after clamping the interpolation factor to [0, 1]. /// @@ -297,8 +308,8 @@ public static Vector3 Lerp( Vector3 a, Vector3 b, float t - ) => - a + (b - a) * Math.Clamp(t, 0f, 1f); + ) => a + (b - a) * Math.Clamp(t, 0f, 1f); + /// /// Reflects an incident value across the supplied normal. /// @@ -317,9 +328,8 @@ float t public static Vector3 Reflect( Vector3 dir, Vector3 normal - ) => - dir - 2f * Dot(dir, normal) * normal; - + ) => dir - 2f * Dot(dir, normal) * normal; + /// /// Transforms a position as a column vector with an implicit homogeneous coordinate of one. /// @@ -391,7 +401,7 @@ Matrix matrix float tz = matrix.m31 * normal.x + matrix.m32 * normal.y + matrix.m33 * normal.z; return new Vector3(tx, ty, tz); } - + /// /// Transforms the supplied value by the requested transformation. /// @@ -422,6 +432,7 @@ Quaternion rotation return new Vector3(rx, ry, rz); } + /// /// Adds the supplied values component by component. /// @@ -441,6 +452,7 @@ Quaternion rotation Vector3 a, Vector3 b ) => new(a.x + b.x, a.y + b.y, a.z + b.z); + /// /// Subtracts or negates the supplied value component by component. /// @@ -458,6 +470,7 @@ Vector3 b Vector3 a, Vector3 b ) => new(a.x - b.x, a.y - b.y, a.z - b.z); + /// /// Subtracts or negates the supplied value component by component. /// @@ -469,6 +482,7 @@ Vector3 b /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator -(Vector3 v) => new(-v.x, -v.y, -v.z); + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -486,6 +500,7 @@ Vector3 b Vector3 v, float s ) => new(v.x * s, v.y * s, v.z * s); + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -503,6 +518,7 @@ float s float s, Vector3 v ) => v * s; + /// /// Divides the supplied value by the scalar divisor component by component. /// @@ -537,10 +553,9 @@ float s public static bool operator ==( Vector3 a, Vector3 b - ) => - MathHelper.AlmostEquals(a.x, b.x) && - MathHelper.AlmostEquals(a.y, b.y) && - MathHelper.AlmostEquals(a.z, b.z); + ) => MathHelper.AlmostEquals(a.x, b.x) + && MathHelper.AlmostEquals(a.y, b.y) + && MathHelper.AlmostEquals(a.z, b.z); /// /// Determines whether the supplied values differ under the type's equality tolerance. @@ -559,7 +574,7 @@ Vector3 b Vector3 a, Vector3 b ) => !(a == b); - + /// /// Converts the supplied value to . /// @@ -570,6 +585,7 @@ Vector3 b /// The validated system.numerics.vector3 that represents the completed operation. /// public static implicit operator System.Numerics.Vector3(Vector3 v) => new(v.x, v.y, v.z); + /// /// Converts the supplied value to . /// @@ -591,6 +607,7 @@ Vector3 b /// when the requested condition is satisfied; otherwise, . /// public override bool Equals(object? obj) => obj is Vector3 other && this == other; + /// /// Determines whether this value and the supplied value represent the same logical state. /// @@ -601,6 +618,7 @@ Vector3 b /// when the requested condition is satisfied; otherwise, . /// public bool Equals(Vector3 other) => this == other; + /// /// Computes a hash code consistent with the implemented equality contract. /// @@ -608,6 +626,7 @@ Vector3 b /// The scalar result calculated from the supplied inputs. /// public override int GetHashCode() => HashCode.Combine(x, y, z); + /// /// Formats this value as a human-readable component list. /// diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs b/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs index 045a890bd..9fdee8d59 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs @@ -14,10 +14,12 @@ public struct Vector3Int : IEquatable /// The horizontal or first component. /// [DataMember] public int x; + /// /// The vertical or second component. /// [DataMember] public int y; + /// /// The depth or third component. /// @@ -49,30 +51,37 @@ int z /// A value whose components are all zero. /// public static readonly Vector3Int ZERO = new(0, 0, 0); + /// /// A value whose components are all one. /// public static readonly Vector3Int ONE = new(1, 1, 1); + /// /// The up value used as part of this type's public representation. /// public static readonly Vector3Int UP = new(0, 1, 0); + /// /// The down value used as part of this type's public representation. /// public static readonly Vector3Int DOWN = new(0, -1, 0); + /// /// The left value used as part of this type's public representation. /// public static readonly Vector3Int LEFT = new(-1, 0, 0); + /// /// The right value used as part of this type's public representation. /// public static readonly Vector3Int RIGHT = new(1, 0, 0); + /// /// The forward value used as part of this type's public representation. /// public static readonly Vector3Int FORWARD = new(0, 0, 1); + /// /// The back value used as part of this type's public representation. /// diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector4.cs b/src/foundation/core/Inno.Core.Mathematics/Vector4.cs index 5d1581066..3c2672c37 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector4.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector4.cs @@ -1,9 +1,9 @@ using System; using System.Runtime.CompilerServices; -using System.Runtime.Serialization; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; +using System.Runtime.Serialization; namespace Inno.Core.Mathematics; @@ -17,14 +17,17 @@ public struct Vector4 : IEquatable /// The horizontal or first component. /// [DataMember] public float x; + /// /// The vertical or second component. /// [DataMember] public float y; + /// /// The depth or third component. /// [DataMember] public float z; + /// /// The homogeneous or fourth component. /// @@ -56,32 +59,39 @@ float w this.z = z; this.w = w; } + /// /// A value whose components are all zero. /// // Common vectors public static readonly Vector4 ZERO = new(0, 0, 0, 0); + /// /// A value whose components are all one. /// public static readonly Vector4 ONE = new(1, 1, 1, 1); + /// /// A unit value aligned with the x axis. /// public static readonly Vector4 UNIT_X = new(1, 0, 0, 0); + /// /// A unit value aligned with the y axis. /// public static readonly Vector4 UNIT_Y = new(0, 1, 0, 0); + /// /// A unit value aligned with the z axis. /// public static readonly Vector4 UNIT_Z = new(0, 0, 1, 0); + /// /// A unit value aligned with the w axis. /// public static readonly Vector4 UNIT_W = new(0, 0, 0, 1); + /// /// Calculates the Euclidean magnitude of this value. /// @@ -113,6 +123,7 @@ public Vector4 normalized return len > 0 ? this / len : ZERO; } } + /// /// Calculates the scalar dot product of two values. /// @@ -131,8 +142,8 @@ public Vector4 normalized public static float Dot( Vector4 a, Vector4 b - ) => - SimdMath.Dot4(a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w); + ) => SimdMath.Dot4(a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w); + /// /// Interpolates linearly after clamping the interpolation factor to [0, 1]. /// @@ -155,8 +166,8 @@ public static Vector4 Lerp( Vector4 a, Vector4 b, float t - ) => - a + (b - a) * Math.Clamp(t, 0f, 1f); + ) => a + (b - a) * Math.Clamp(t, 0f, 1f); + /// /// Reflects an incident value across the supplied normal. /// @@ -175,8 +186,8 @@ float t public static Vector4 Reflect( Vector4 vec, Vector4 normal - ) => - vec - 2f * Dot(vec, normal) * normal; + ) => vec - 2f * Dot(vec, normal) * normal; + /// /// Transforms the supplied value by the requested transformation. /// @@ -217,6 +228,7 @@ Matrix m float sw = m.m41 * v.x + m.m42 * v.y + m.m43 * v.z + m.m44 * v.w; return new Vector4(sx, sy, sz, sw); } + /// /// Projects the supplied value onto the requested dimensional space. /// @@ -229,9 +241,12 @@ Matrix m public Vector3 ProjectToVector3() { if (w == 0f) + { return new Vector3(x, y, z); // Avoid division by zero + } return new Vector3(x / w, y / w, z / w); } + /// /// Adds the supplied values component by component. /// @@ -250,8 +265,7 @@ public Vector3 ProjectToVector3() public static Vector4 operator +( Vector4 a, Vector4 b - ) => - new(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); + ) => new(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); /// /// Subtracts or negates the supplied value component by component. @@ -269,8 +283,7 @@ Vector4 b public static Vector4 operator -( Vector4 a, Vector4 b - ) => - new(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); + ) => new(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); /// /// Subtracts or negates the supplied value component by component. @@ -282,8 +295,7 @@ Vector4 b /// The validated vector4 that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector4 operator -(Vector4 v) => - new(-v.x, -v.y, -v.z, -v.w); + public static Vector4 operator -(Vector4 v) => new(-v.x, -v.y, -v.z, -v.w); /// /// Multiplies the supplied values according to their algebraic contract. @@ -301,8 +313,7 @@ Vector4 b public static Vector4 operator *( Vector4 v, float s - ) => - new(v.x * s, v.y * s, v.z * s, v.w * s); + ) => new(v.x * s, v.y * s, v.z * s, v.w * s); /// /// Multiplies the supplied values according to their algebraic contract. @@ -321,7 +332,7 @@ float s float s, Vector4 v ) => v * s; - + /// /// Multiplies the supplied values according to their algebraic contract. /// @@ -363,8 +374,7 @@ Vector4 v public static Vector4 operator /( Vector4 v, float s - ) => - new(v.x / s, v.y / s, v.z / s, v.w / s); + ) => new(v.x / s, v.y / s, v.z / s, v.w / s); /// /// Determines whether the supplied values are equal under the type's equality tolerance. @@ -382,11 +392,10 @@ float s public static bool operator ==( Vector4 a, Vector4 b - ) => - MathHelper.AlmostEquals(a.x, b.x) && - MathHelper.AlmostEquals(a.y, b.y) && - MathHelper.AlmostEquals(a.z, b.z) && - MathHelper.AlmostEquals(a.w, b.w); + ) => MathHelper.AlmostEquals(a.x, b.x) + && MathHelper.AlmostEquals(a.y, b.y) + && MathHelper.AlmostEquals(a.z, b.z) + && MathHelper.AlmostEquals(a.w, b.w); /// /// Determines whether the supplied values differ under the type's equality tolerance. @@ -405,7 +414,7 @@ Vector4 b Vector4 a, Vector4 b ) => !(a == b); - + /// /// Converts the supplied value to . /// @@ -416,6 +425,7 @@ Vector4 b /// The validated system.numerics.vector4 that represents the completed operation. /// public static implicit operator System.Numerics.Vector4(Vector4 v) => new(v.x, v.y, v.z, v.w); + /// /// Converts the supplied value to . /// @@ -437,6 +447,7 @@ Vector4 b /// when the requested condition is satisfied; otherwise, . /// public override bool Equals(object? obj) => obj is Vector4 other && this == other; + /// /// Determines whether this value and the supplied value represent the same logical state. /// @@ -447,6 +458,7 @@ Vector4 b /// when the requested condition is satisfied; otherwise, . /// public bool Equals(Vector4 other) => this == other; + /// /// Computes a hash code consistent with the implemented equality contract. /// @@ -454,6 +466,7 @@ Vector4 b /// The scalar result calculated from the supplied inputs. /// public override int GetHashCode() => HashCode.Combine(x, y, z, w); + /// /// Formats this value as a human-readable component list. /// diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs b/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs index ea883a424..4a022e445 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs @@ -14,14 +14,17 @@ public struct Vector4Int : IEquatable /// The horizontal or first component. /// [DataMember] public int x; + /// /// The vertical or second component. /// [DataMember] public int y; + /// /// The depth or third component. /// [DataMember] public int z; + /// /// The homogeneous or fourth component. /// @@ -53,32 +56,39 @@ int w this.z = z; this.w = w; } + /// /// A value whose components are all zero. /// // Common vectors public static readonly Vector4Int ZERO = new(0, 0, 0, 0); + /// /// A value whose components are all one. /// public static readonly Vector4Int ONE = new(1, 1, 1, 1); + /// /// A unit value aligned with the x axis. /// public static readonly Vector4Int UNIT_X = new(1, 0, 0, 0); + /// /// A unit value aligned with the y axis. /// public static readonly Vector4Int UNIT_Y = new(0, 1, 0, 0); + /// /// A unit value aligned with the z axis. /// public static readonly Vector4Int UNIT_Z = new(0, 0, 1, 0); + /// /// A unit value aligned with the w axis. /// public static readonly Vector4Int UNIT_W = new(0, 0, 0, 1); + /// /// Calculates the scalar dot product of two values. /// @@ -97,8 +107,8 @@ int w public static int Dot( Vector4Int a, Vector4Int b - ) => - a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + ) => a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + /// /// Clamps the interpolation factor to [0, 1] and truncates each interpolated component to an integer. /// @@ -130,6 +140,7 @@ float t (int)(a.w + (b.w - a.w) * t) ); } + /// /// Reflects an incident value across the supplied normal. /// @@ -152,6 +163,7 @@ Vector4Int normal int dot = Dot(vec, normal); return vec - 2 * dot * normal; } + /// /// Transforms the supplied value by the requested transformation. /// @@ -177,6 +189,7 @@ Matrix m int tw = (int)(m.m41 * v.x + m.m42 * v.y + m.m43 * v.z + m.m44 * v.w); return new Vector4Int(tx, ty, tz, tw); } + /// /// Adds the supplied values component by component. /// @@ -195,8 +208,7 @@ Matrix m public static Vector4Int operator +( Vector4Int a, Vector4Int b - ) => - new(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); + ) => new(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); /// /// Subtracts or negates the supplied value component by component. @@ -214,8 +226,7 @@ Vector4Int b public static Vector4Int operator -( Vector4Int a, Vector4Int b - ) => - new(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); + ) => new(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); /// /// Subtracts or negates the supplied value component by component. @@ -227,8 +238,7 @@ Vector4Int b /// The validated vector4int that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Vector4Int operator -(Vector4Int v) => - new(-v.x, -v.y, -v.z, -v.w); + public static Vector4Int operator -(Vector4Int v) => new(-v.x, -v.y, -v.z, -v.w); /// /// Multiplies the supplied values according to their algebraic contract. @@ -246,8 +256,7 @@ Vector4Int b public static Vector4Int operator *( Vector4Int v, int s - ) => - new(v.x * s, v.y * s, v.z * s, v.w * s); + ) => new(v.x * s, v.y * s, v.z * s, v.w * s); /// /// Multiplies the supplied values according to their algebraic contract. @@ -266,7 +275,7 @@ int s int s, Vector4Int v ) => v * s; - + /// /// Divides the supplied value by the scalar divisor component by component. /// @@ -283,8 +292,7 @@ Vector4Int v public static Vector4Int operator /( Vector4Int v, int s - ) => - new(v.x / s, v.y / s, v.z / s, v.w / s); + ) => new(v.x / s, v.y / s, v.z / s, v.w / s); /// /// Determines whether the supplied values are equal under the type's equality tolerance. @@ -302,8 +310,7 @@ int s public static bool operator ==( Vector4Int a, Vector4Int b - ) => - a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; + ) => a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; /// /// Determines whether the supplied values differ under the type's equality tolerance. @@ -322,6 +329,7 @@ Vector4Int b Vector4Int a, Vector4Int b ) => !(a == b); + /// /// Converts the supplied value to . /// @@ -334,8 +342,7 @@ Vector4Int b // Conversions [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static explicit operator Vector4(Vector4Int v) => - new(v.x, v.y, v.z, v.w); + public static explicit operator Vector4(Vector4Int v) => new(v.x, v.y, v.z, v.w); /// /// Converts the supplied value to . @@ -347,8 +354,7 @@ public static explicit operator Vector4(Vector4Int v) => /// The validated vector4int that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static explicit operator Vector4Int(Vector4 v) => - new((int)v.x, (int)v.y, (int)v.z, (int)v.w); + public static explicit operator Vector4Int(Vector4 v) => new((int)v.x, (int)v.y, (int)v.z, (int)v.w); /// /// Determines whether this value and the supplied value represent the same logical state. @@ -360,6 +366,7 @@ public static explicit operator Vector4Int(Vector4 v) => /// when the requested condition is satisfied; otherwise, . /// public override bool Equals(object? obj) => obj is Vector4Int other && Equals(other); + /// /// Determines whether this value and the supplied value represent the same logical state. /// @@ -370,6 +377,7 @@ public static explicit operator Vector4Int(Vector4 v) => /// when the requested condition is satisfied; otherwise, . /// public bool Equals(Vector4Int other) => this == other; + /// /// Computes a hash code consistent with the implemented equality contract. /// @@ -377,6 +385,7 @@ public static explicit operator Vector4Int(Vector4 v) => /// The scalar result calculated from the supplied inputs. /// public override int GetHashCode() => HashCode.Combine(x, y, z, w); + /// /// Formats this value as a human-readable component list. /// diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationCollectionGenerator.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationCollectionGenerator.cs index 9ed38b39e..50b690959 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationCollectionGenerator.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationCollectionGenerator.cs @@ -19,34 +19,46 @@ ref int index if (type is IArrayTypeSymbol array) { if (array.Rank != 1) + { return null; + } pending.Enqueue(array.ElementType); string element = Name(array.ElementType); return "new global::Inno.Core.Serialization.SerializationCollectionMetadata(typeof(" + element - + "), null, static values => BuildArray<" + element + ">(values), null, null)"; + + "), null, static values => BuildArray<" + element + ">(values), null, null)"; } if (type is not INamedTypeSymbol named || type.SpecialType == SpecialType.System_String) + { return null; + } INamedTypeSymbol[] contracts = new[] { named }.Concat(named.AllInterfaces).ToArray(); - INamedTypeSymbol? map = contracts.FirstOrDefault(static contract => + INamedTypeSymbol? map = contracts.FirstOrDefault(static contract => ( contract.OriginalDefinition.ToDisplayString() is "System.Collections.Generic.IDictionary" - or "System.Collections.Generic.IReadOnlyDictionary"); - INamedTypeSymbol? sequence = contracts.FirstOrDefault(static contract => - contract.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T); + or "System.Collections.Generic.IReadOnlyDictionary" + )); + INamedTypeSymbol? sequence = contracts.FirstOrDefault(static contract => ( + contract.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T + )); if (map is null && sequence?.TypeArguments[0] is INamedTypeSymbol entry - && entry.OriginalDefinition.ToDisplayString() == "System.Collections.Generic.KeyValuePair") + && entry.OriginalDefinition.ToDisplayString() == "System.Collections.Generic.KeyValuePair" + ) { map = entry; + } if (map is not null) { ITypeSymbol key = map.TypeArguments[0]; ITypeSymbol value = map.TypeArguments[1]; pending.Enqueue(key); pending.Enqueue(value); - INamedTypeSymbol dictionary = compilation.GetTypeByMetadataName("System.Collections.Generic.Dictionary`2")!.Construct(key, value); + INamedTypeSymbol dictionary = compilation + .GetTypeByMetadataName("System.Collections.Generic.Dictionary`2")! + .Construct(key, value); INamedTypeSymbol pair = compilation.GetTypeByMetadataName("System.Collections.Generic.KeyValuePair`2")!.Construct(key, value); string? construction = Construct(named, dictionary, [key, value], pair, compilation, accessors, ref index); if (construction is null) + { return null; + } string keyName = Name(key); string valueName = Name(value); return "new global::Inno.Core.Serialization.SerializationCollectionMetadata(typeof(" + valueName @@ -56,20 +68,26 @@ ref int index + Name(pair) + ">)value) result.Add(new(entry.Key, entry.Value)); return result; })"; } if (sequence is null) + { return null; + } ITypeSymbol elementType = sequence.TypeArguments[0]; pending.Enqueue(elementType); INamedTypeSymbol standard = compilation.GetTypeByMetadataName("System.Collections.Generic.List`1")!.Construct(elementType); if (named.TypeKind == TypeKind.Interface && !compilation.ClassifyConversion(standard, named).IsImplicit) + { standard = compilation.GetTypeByMetadataName("System.Collections.Generic.HashSet`1")!.Construct(elementType); + } string? result = Construct(named, standard, [elementType], elementType, compilation, accessors, ref index); if (result is null) + { return null; + } string elementName = Name(elementType); return "new global::Inno.Core.Serialization.SerializationCollectionMetadata(typeof(" + elementName - + "), null, static values => { var result = new " + Name(standard) - + "(); foreach (var value in values) result.Add((" + elementName - + ")value!); return " + result + "; }, null, null)"; + + "), null, static values => { var result = new " + Name(standard) + + "(); foreach (var value in values) result.Add((" + elementName + + ")value!); return " + result + "; }, null, null)"; } private static string? Construct( @@ -82,64 +100,111 @@ ref int index ref int index ) { if (compilation.ClassifyConversion(standard, type).IsImplicit) + { return "result"; + } if (type.TypeKind == TypeKind.Interface || type.IsAbstract) + { return null; + } foreach (IMethodSymbol constructor in type.InstanceConstructors.Where(static constructor => constructor.Parameters.Length == 1)) { if (!compilation.ClassifyConversion(standard, constructor.Parameters[0].Type).IsImplicit) + { continue; + } if (IsAccessible(constructor, compilation)) + { return "new " + Name(type) + "(result)"; + } if (SymbolEqualityComparer.Default.Equals(type.ContainingAssembly, compilation.Assembly)) { string name = "ConstructCollection" + index++; - accessors.Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n") - .Append(" private static extern ").Append(Name(type)).Append(' ').Append(name).Append('(') - .Append(Name(constructor.Parameters[0].Type)).Append(" values);\n"); + accessors + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n" + ) + .Append(" private static extern ") + .Append(Name(type)) + .Append(' ') + .Append(name) + .Append('(') + .Append(Name(constructor.Parameters[0].Type)) + .Append(" values);\n"); return name + "(result)"; } } - foreach (IMethodSymbol factory in type.GetMembers().OfType().Where(static method => - method.IsStatic && !method.IsGenericMethod && method.Parameters.Length == 1 && method.Name is "CreateRange" or "Create")) - { + foreach (IMethodSymbol factory in type.GetMembers().OfType().Where(static method => ( + method.IsStatic && !method.IsGenericMethod && method.Parameters.Length == 1 && method.Name is "CreateRange" or "Create" + )) + ) { if (IsAccessible(factory, compilation) && compilation.ClassifyConversion(standard, factory.Parameters[0].Type).IsImplicit - && compilation.ClassifyConversion(factory.ReturnType, type).IsImplicit) + && compilation.ClassifyConversion(factory.ReturnType, type).IsImplicit + ) { return Name(type) + ".@" + factory.Name + "(result)"; + } } string definition = type.OriginalDefinition.ToDisplayString(); if (definition == "System.Collections.Immutable.ImmutableArray") + { return "global::System.Collections.Immutable.ImmutableArray.CreateRange<" + Name(elementType) + ">(result)"; + } if (definition == "System.Collections.Immutable.ImmutableList") + { return "global::System.Collections.Immutable.ImmutableList.CreateRange<" + Name(elementType) + ">(result)"; + } if (definition == "System.Collections.Immutable.ImmutableHashSet") + { return "global::System.Collections.Immutable.ImmutableHashSet.CreateRange<" + Name(elementType) + ">(result)"; + } if (definition == "System.Collections.Immutable.ImmutableDictionary") + { return "global::System.Collections.Immutable.ImmutableDictionary.CreateRange(result)"; + } - IMethodSymbol? emptyConstructor = type.InstanceConstructors.FirstOrDefault(static constructor => constructor.Parameters.Length == 0); + IMethodSymbol? emptyConstructor = type.InstanceConstructors.FirstOrDefault( + static constructor => constructor.Parameters.Length == 0 + ); if (emptyConstructor is null || !IsAccessible(emptyConstructor, compilation)) + { return null; - IMethodSymbol? add = Ancestors(type).SelectMany(static owner => owner.GetMembers("Add")).OfType() - .FirstOrDefault(method => !method.IsStatic && !method.IsGenericMethod && IsAccessible(method, compilation) + } + IMethodSymbol? add = Ancestors(type).SelectMany(static owner => owner.GetMembers("Add")) + .OfType() + .FirstOrDefault(method => ( + !method.IsStatic && !method.IsGenericMethod && IsAccessible(method, compilation) && method.Parameters.Length == addArguments.Length - && method.Parameters.Select(static parameter => parameter.Type).SequenceEqual(addArguments, SymbolEqualityComparer.Default)); + && method.Parameters + .Select(static parameter => parameter.Type) + .SequenceEqual(addArguments, SymbolEqualityComparer.Default) + )); INamedTypeSymbol? addContract = null; if (add is null) { string contractName = addArguments.Length == 2 ? "System.Collections.Generic.IDictionary`2" : "System.Collections.Generic.ICollection`1"; INamedTypeSymbol contract = compilation.GetTypeByMetadataName(contractName)!.Construct(addArguments); if (!compilation.ClassifyConversion(type, contract).IsImplicit) + { return null; + } addContract = contract; } string builder = "BuildCollection" + index++; string receiver = addContract is null ? "value" : "((" + Name(addContract) + ")value)"; string addCall = addArguments.Length == 2 ? "entry.Key, entry.Value" : "entry"; - accessors.Append(" private static ").Append(Name(type)).Append(' ').Append(builder).Append('(') - .Append(Name(standard)).Append(" values)\n {\n var value = new ").Append(Name(type)) - .Append("();\n foreach (var entry in values)\n ").Append(receiver).Append(".Add(") - .Append(addCall).Append(");\n return value;\n }\n"); + accessors.Append(" private static ") + .Append(Name(type)) + .Append(' ') + .Append(builder) + .Append('(') + .Append(Name(standard)) + .Append(" values)\n {\n var value = new ") + .Append(Name(type)) + .Append("();\n foreach (var entry in values)\n ") + .Append(receiver) + .Append(".Add(") + .Append(addCall) + .Append(");\n return value;\n }\n"); return builder + "(result)"; } @@ -147,15 +212,18 @@ private static bool IsAccessible( ISymbol symbol, Compilation compilation ) => symbol.DeclaredAccessibility == Accessibility.Public - || symbol.DeclaredAccessibility is Accessibility.Internal or Accessibility.ProtectedOrInternal + || symbol.DeclaredAccessibility is Accessibility.Internal or Accessibility.ProtectedOrInternal && SymbolEqualityComparer.Default.Equals(symbol.ContainingAssembly, compilation.Assembly); private static IEnumerable Ancestors(INamedTypeSymbol type) { for (INamedTypeSymbol? current = type; current is not null; current = current.BaseType) + { yield return current; + } } - private static string Name(ITypeSymbol type) => type.WithNullableAnnotation(NullableAnnotation.NotAnnotated) - .ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + private static string Name(ITypeSymbol type) + => type.WithNullableAnnotation(NullableAnnotation.NotAnnotated) + .ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); } diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs index 8f6c95119..de78b0e27 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs @@ -3,7 +3,6 @@ using System.Collections.Immutable; using System.Linq; using System.Text; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; @@ -18,8 +17,10 @@ public sealed class SerializationConverterGenerator : IIncrementalGenerator { private const string C_GENERATE_ATTRIBUTE = "Inno.Core.Serialization.GenerateSerializationConverterAttribute"; + private const string C_PROPERTY_ATTRIBUTE = "Inno.Core.Serialization.SerializablePropertyAttribute"; + private const string C_SERIALIZABLE_INTERFACE = "Inno.Core.Serialization.ISerializable"; @@ -29,7 +30,8 @@ public sealed class SerializationConverterGenerator : IIncrementalGenerator "Type '{0}' must be a non-abstract, non-generic class implementing ISerializable", "Inno.Serialization", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); private static readonly DiagnosticDescriptor s_missingConstructor = new( "INNOSER002", @@ -37,7 +39,8 @@ public sealed class SerializationConverterGenerator : IIncrementalGenerator "Type '{0}' must expose a parameterless constructor accessible to generated code", "Inno.Serialization", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); private static readonly DiagnosticDescriptor s_invalidMember = new( "INNOSER003", @@ -45,7 +48,8 @@ public sealed class SerializationConverterGenerator : IIncrementalGenerator "Member '{0}' cannot participate in generated {1}", "Inno.Serialization", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); private static readonly DiagnosticDescriptor s_duplicateKey = new( "INNOSER004", @@ -53,7 +57,8 @@ public sealed class SerializationConverterGenerator : IIncrementalGenerator "Type '{0}' declares serialization key '{1}' more than once across its inheritance chain", "Inno.Serialization", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); /// /// Registers the incremental syntax and source-production pipeline. @@ -73,7 +78,8 @@ public void Initialize(IncrementalGeneratorInitializationContext context) static ( attributeContext, _ - ) => (INamedTypeSymbol)attributeContext.TargetSymbol); + ) => (INamedTypeSymbol)attributeContext.TargetSymbol + ); context.RegisterSourceOutput(types, static ( productionContext, @@ -92,25 +98,35 @@ private static void GenerateCatalog( ImmutableArray types ) { if (types.IsEmpty) + { return; + } var source = new StringBuilder("// \n#nullable enable\n"); - source.Append("namespace ").Append(compilation.AssemblyName).Append(".Generated;\n") + source.Append("namespace ") + .Append(compilation.AssemblyName) + .Append(".Generated;\n") .Append("/// \n/// Contributes generated serialization declarations and direct factories.\n/// \n") .Append("public static class RuntimeSerializationCatalog\n{\n") - .Append(" /// \n /// Registers this assembly's generated converters without reflection discovery.\n /// \n") + .Append( + " /// \n /// Registers this assembly's generated converters without reflection discovery.\n /// \n" + ) .Append(" /// \n /// The composition callback; it is not retained.\n /// \n") .Append(" public static void Register(global::Inno.Extensibility.Catalogs.ITypeCatalogRegistrar register)\n {\n") .Append(" global::System.ArgumentNullException.ThrowIfNull(register);\n"); foreach (INamedTypeSymbol type in types.Distinct(SymbolEqualityComparer.Default) - .OrderBy(static type => type.ToDisplayString(), StringComparer.Ordinal)) - { + .OrderBy(static type => type.ToDisplayString(), StringComparer.Ordinal) + ) { string converter = "global::" + GetNamespace(type) + ".__InnoGeneratedSerializationConverter_" + GetGeneratedName(type); source.Append(" register.Register(new global::Inno.Extensibility.Catalogs.TypeCatalogMetadata(typeof(") - .Append(converter).Append("), new global::System.Type[] { typeof(global::Inno.Core.Serialization.Converters.SerializationConverter<") + .Append(converter) + .Append("), new global::System.Type[] { typeof(global::Inno.Core.Serialization.Converters.SerializationConverter<") .Append(type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)) .Append(" >), typeof(global::Inno.Core.Serialization.Converters.SerializationConverter) }, ") - .Append("global::System.Array.Empty(), global::System.Array.Empty(), global::System.Array.Empty(), global::System.Array.Empty<(string, global::System.Type)>()), static () => new ") - .Append(converter).Append("());\n"); + .Append( + "global::System.Array.Empty(), global::System.Array.Empty(), global::System.Array.Empty(), global::System.Array.Empty<(string, global::System.Type)>()), static () => new " + ) + .Append(converter) + .Append("());\n"); } source.Append(" }\n}\n"); output.AddSource("Registration/RuntimeSerialization.g.cs", source.ToString()); @@ -125,8 +141,8 @@ INamedTypeSymbol type || type.IsAbstract || type.IsGenericType || !ImplementsSerializable(type) - || !IsTypeAccessible(type)) - { + || !IsTypeAccessible(type) + ) { context.ReportDiagnostic(Diagnostic.Create(s_invalidType, location, type.ToDisplayString())); return; } @@ -140,14 +156,12 @@ INamedTypeSymbol type ImmutableArray members = CollectMembers(type); bool failed = false; foreach (IGrouping duplicate in members - .GroupBy(static member => member.name, StringComparer.Ordinal) - .Where(static group => group.Count() > 1)) - { - context.ReportDiagnostic(Diagnostic.Create( - s_duplicateKey, - duplicate.First().location, - type.ToDisplayString(), - duplicate.Key)); + .GroupBy(static member => member.name, StringComparer.Ordinal) + .Where(static group => group.Count() > 1) + ) { + context.ReportDiagnostic( + Diagnostic.Create(s_duplicateKey, duplicate.First().location, type.ToDisplayString(), duplicate.Key) + ); failed = true; } @@ -155,26 +169,34 @@ INamedTypeSymbol type { if (member.serialize && !member.canRead) { - context.ReportDiagnostic(Diagnostic.Create( - s_invalidMember, - member.location, - member.displayName, - "serialization because it is not readable by generated code")); + context.ReportDiagnostic( + Diagnostic.Create( + s_invalidMember, + member.location, + member.displayName, + "serialization because it is not readable by generated code" + ) + ); failed = true; } if (member.deserialize && !member.canWrite) { - context.ReportDiagnostic(Diagnostic.Create( - s_invalidMember, - member.location, - member.displayName, - "deserialization because it is not writable by generated code")); + context.ReportDiagnostic( + Diagnostic.Create( + s_invalidMember, + member.location, + member.displayName, + "deserialization because it is not writable by generated code" + ) + ); failed = true; } } if (failed) + { return; + } string source = BuildSource(type, members); context.AddSource(GetGeneratedName(type) + ".g.cs", SourceText.From(source, Encoding.UTF8)); @@ -184,7 +206,9 @@ private static ImmutableArray CollectMembers(INamedTypeSymbo { var hierarchy = new Stack(); for (INamedTypeSymbol? current = type; current is not null; current = current.BaseType) + { hierarchy.Push(current); + } var members = ImmutableArray.CreateBuilder(); while (hierarchy.Count > 0) @@ -192,39 +216,48 @@ private static ImmutableArray CollectMembers(INamedTypeSymbo INamedTypeSymbol current = hierarchy.Pop(); foreach (ISymbol symbol in current.GetMembers().OrderBy(GetSourceOrder)) { - AttributeData? attribute = symbol.GetAttributes().FirstOrDefault(static candidate => - candidate.AttributeClass?.ToDisplayString() == C_PROPERTY_ATTRIBUTE); + AttributeData? attribute = symbol.GetAttributes().FirstOrDefault(static candidate => ( + candidate.AttributeClass?.ToDisplayString() == C_PROPERTY_ATTRIBUTE + )); if (attribute is null) + { continue; + } int visibility = attribute.ConstructorArguments.Length == 0 - ? 15 - : (int)(attribute.ConstructorArguments[0].Value ?? 15); + ? 15 + : (int)(attribute.ConstructorArguments[0].Value ?? 15); bool serialize = (visibility & 1) != 0; bool deserialize = (visibility & 2) != 0; switch (symbol) { case IPropertySymbol property: - members.Add(new SerializableMember( - property.Name, - property.ToDisplayString(), - property.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), - serialize, - deserialize, - IsAccessible(property.GetMethod), - IsAccessible(property.SetMethod) && !property.IsReadOnly, - property.Locations.FirstOrDefault() ?? Location.None)); + members.Add( + new SerializableMember( + property.Name, + property.ToDisplayString(), + property.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + serialize, + deserialize, + IsAccessible(property.GetMethod), + IsAccessible(property.SetMethod) && !property.IsReadOnly, + property.Locations.FirstOrDefault() ?? Location.None + ) + ); break; case IFieldSymbol field: - members.Add(new SerializableMember( - field.Name, - field.ToDisplayString(), - field.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), - serialize, - deserialize, - IsAccessible(field), - IsAccessible(field) && !field.IsReadOnly && !field.IsConst, - field.Locations.FirstOrDefault() ?? Location.None)); + members.Add( + new SerializableMember( + field.Name, + field.ToDisplayString(), + field.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + serialize, + deserialize, + IsAccessible(field), + IsAccessible(field) && !field.IsReadOnly && !field.IsConst, + field.Locations.FirstOrDefault() ?? Location.None + ) + ); break; } } @@ -245,23 +278,32 @@ ImmutableArray members source.AppendLine("namespace " + GetNamespace(type)); source.AppendLine("{"); source.AppendLine(" [global::System.CodeDom.Compiler.GeneratedCode(\"Inno.Core.Serialization.Generators\", \"1\")]"); - source.Append(" internal sealed class ").Append(converterName) + source.Append(" internal sealed class ") + .Append(converterName) .Append(" : global::Inno.Core.Serialization.Converters.SerializationConverter<") - .Append(targetType).AppendLine(">"); + .Append(targetType) + .AppendLine(">"); source.AppendLine(" {"); source.Append(" public override void Write(global::Inno.Core.Serialization.SerializationWriter writer, ") - .Append(targetType).AppendLine(" value)"); + .Append(targetType) + .AppendLine(" value)"); source.AppendLine(" {"); source.AppendLine(" global::System.ArgumentNullException.ThrowIfNull(writer);"); source.AppendLine(" global::System.ArgumentNullException.ThrowIfNull(value);"); foreach (SerializableMember member in members.Where(static member => member.serialize)) { - source.Append(" writer.Write<").Append(member.typeName).Append(">(\"") - .Append(Escape(member.name)).Append("\", value.").Append(member.name).AppendLine(");"); + source.Append(" writer.Write<") + .Append(member.typeName) + .Append(">(\"") + .Append(Escape(member.name)) + .Append("\", value.") + .Append(member.name) + .AppendLine(");"); } source.AppendLine(" }"); source.AppendLine(); - source.Append(" public override ").Append(targetType) + source.Append(" public override ") + .Append(targetType) .AppendLine(" Read(global::Inno.Core.Serialization.SerializationReader reader)"); source.AppendLine(" {"); source.AppendLine(" global::System.ArgumentNullException.ThrowIfNull(reader);"); @@ -271,14 +313,20 @@ ImmutableArray members source.AppendLine(" }"); source.AppendLine(); source.Append(" public override void Restore(global::Inno.Core.Serialization.SerializationReader reader, ") - .Append(targetType).AppendLine(" target)"); + .Append(targetType) + .AppendLine(" target)"); source.AppendLine(" {"); source.AppendLine(" global::System.ArgumentNullException.ThrowIfNull(reader);"); source.AppendLine(" global::System.ArgumentNullException.ThrowIfNull(target);"); foreach (SerializableMember member in members.Where(static member => member.deserialize)) { - source.Append(" target.").Append(member.name).Append(" = reader.Read<") - .Append(member.typeName).Append(">(\"").Append(Escape(member.name)).AppendLine("\");"); + source.Append(" target.") + .Append(member.name) + .Append(" = reader.Read<") + .Append(member.typeName) + .Append(">(\"") + .Append(Escape(member.name)) + .AppendLine("\");"); } source.AppendLine(" }"); source.AppendLine(" }"); @@ -292,8 +340,13 @@ ImmutableArray members ) { foreach (SerializableMember member in members.Where(static member => member.deserialize)) { - source.Append(" value.").Append(member.name).Append(" = reader.Read<") - .Append(member.typeName).Append(">(\"").Append(Escape(member.name)).AppendLine("\");"); + source.Append(" value.") + .Append(member.name) + .Append(" = reader.Read<") + .Append(member.typeName) + .Append(">(\"") + .Append(Escape(member.name)) + .AppendLine("\");"); } } @@ -301,8 +354,9 @@ private static bool ImplementsSerializable(INamedTypeSymbol type) => type.AllInterfaces.Any(static contract => contract.ToDisplayString() == C_SERIALIZABLE_INTERFACE); private static bool HasAccessibleParameterlessConstructor(INamedTypeSymbol type) - => type.InstanceConstructors.Any(static constructor => - constructor.Parameters.Length == 0 && IsAccessible(constructor)); + => type.InstanceConstructors.Any(static constructor => ( + constructor.Parameters.Length == 0 && IsAccessible(constructor) + )); private static bool IsTypeAccessible(INamedTypeSymbol type) { @@ -310,8 +364,8 @@ private static bool IsTypeAccessible(INamedTypeSymbol type) { if (current.DeclaredAccessibility is Accessibility.Private or Accessibility.Protected - or Accessibility.ProtectedAndInternal) - { + or Accessibility.ProtectedAndInternal + ) { return false; } } @@ -320,23 +374,25 @@ or Accessibility.Protected private static bool IsAccessible(ISymbol? symbol) => symbol?.DeclaredAccessibility is Accessibility.Public - or Accessibility.Internal - or Accessibility.ProtectedOrInternal; + or Accessibility.Internal + or Accessibility.ProtectedOrInternal; private static int GetSourceOrder(ISymbol symbol) => symbol.Locations.FirstOrDefault(static location => location.IsInSource)?.SourceSpan.Start ?? int.MaxValue; private static string GetNamespace(INamedTypeSymbol type) => type.ContainingNamespace.IsGlobalNamespace - ? "InnoGeneratedSerialization" - : type.ContainingNamespace.ToDisplayString(); + ? "InnoGeneratedSerialization" + : type.ContainingNamespace.ToDisplayString(); private static string GetGeneratedName(INamedTypeSymbol type) { string name = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); var result = new StringBuilder(name.Length); foreach (char character in name) + { result.Append(char.IsLetterOrDigit(character) ? character : '_'); + } return result.ToString(); } diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs index f47a9933a..693b987c7 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs @@ -17,17 +17,33 @@ public sealed class SerializationMetadataGenerator : IIncrementalGenerator private const string C_SERIALIZABLE = "Inno.Core.Serialization.ISerializable"; private const string C_PROPERTY = "Inno.Core.Serialization.SerializablePropertyAttribute"; private const string C_RESTORED = "Inno.Core.Serialization.OnSerializableRestored"; + private static readonly DiagnosticDescriptor InvalidMember = new( - "INNOSER010", "Invalid static serialization declaration", "Serialization member '{0}' cannot supply its declared access: {1}", - "Inno.Serialization", DiagnosticSeverity.Error, isEnabledByDefault: true); + "INNOSER010", + "Invalid static serialization declaration", + "Serialization member '{0}' cannot supply its declared access: {1}", + "Inno.Serialization", + DiagnosticSeverity.Error, + isEnabledByDefault: true + ); + private static readonly DiagnosticDescriptor InvalidHook = new( - "INNOSER011", "Invalid static restoration callback", "Restoration declaration '{0}' must contain at most one nonstatic, nonvirtual void hook with zero arguments or one SerializationContext argument", - "Inno.Serialization", DiagnosticSeverity.Error, isEnabledByDefault: true); + "INNOSER011", + "Invalid static restoration callback", + "Restoration declaration '{0}' must contain at most one nonstatic, nonvirtual void hook with zero arguments or one SerializationContext argument", + "Inno.Serialization", + DiagnosticSeverity.Error, + isEnabledByDefault: true + ); private static readonly DiagnosticDescriptor InvalidOwner = new( - "INNOSER012", "Inaccessible static serialization declaration", + "INNOSER012", + "Inaccessible static serialization declaration", "Serialization declaration '{0}' requires a nongeneric partial containing owner; '{1}' cannot host its generated accessors", - "Inno.Serialization", DiagnosticSeverity.Error, isEnabledByDefault: true); + "Inno.Serialization", + DiagnosticSeverity.Error, + isEnabledByDefault: true + ); /// public void Initialize(IncrementalGeneratorInitializationContext context) @@ -43,24 +59,37 @@ private static void Generate( Compilation compilation ) { if (compilation.AssemblyName is null || compilation.GetTypeByMetadataName(C_SERIALIZABLE) is null) + { return; + } var pending = new Queue(); foreach (INamedTypeSymbol type in EnumerateTypes(compilation.Assembly.GlobalNamespace)) + { if (IsSerializable(type)) + { pending.Enqueue(type); + } + } INamespaceSymbol serializationNamespace = compilation.GlobalNamespace.GetNamespaceMembers() - .Single(static scope => scope.Name == "Inno").GetNamespaceMembers() - .Single(static scope => scope.Name == "Core").GetNamespaceMembers() + .Single(static scope => scope.Name == "Inno") + .GetNamespaceMembers() + .Single(static scope => scope.Name == "Core") + .GetNamespaceMembers() .Single(static scope => scope.Name == "Serialization"); - var genericMethodNames = new HashSet(EnumerateTypes(serializationNamespace) - .SelectMany(static type => type.GetMembers().OfType()) - .Where(static method => method.IsGenericMethod).Select(static method => method.Name), StringComparer.Ordinal); + var genericMethodNames = new HashSet( + EnumerateTypes(serializationNamespace) + .SelectMany(static type => type.GetMembers().OfType()) + .Where(static method => method.IsGenericMethod) + .Select(static method => method.Name), + StringComparer.Ordinal + ); foreach (SyntaxTree tree in compilation.SyntaxTrees) { SemanticModel model = compilation.GetSemanticModel(tree); - foreach (InvocationExpressionSyntax syntax in tree.GetRoot(output.CancellationToken).DescendantNodes() - .OfType()) - { + foreach (InvocationExpressionSyntax syntax in tree.GetRoot(output.CancellationToken) + .DescendantNodes() + .OfType() + ) { string? methodName = syntax.Expression switch { SimpleNameSyntax name => name.Identifier.ValueText, @@ -69,12 +98,18 @@ Compilation compilation _ => null }; if (methodName is null || !genericMethodNames.Contains(methodName)) + { continue; + } if (model.GetSymbolInfo(syntax, output.CancellationToken).Symbol is IMethodSymbol method && (method.ContainingNamespace.ToDisplayString() == "Inno.Core.Serialization" - || method.ContainingNamespace.ToDisplayString().StartsWith("Inno.Core.Serialization.", StringComparison.Ordinal))) + || method.ContainingNamespace.ToDisplayString().StartsWith("Inno.Core.Serialization.", StringComparison.Ordinal)) + ) { foreach (ITypeSymbol argument in method.TypeArguments) + { pending.Enqueue(argument); + } + } } } var shapes = new HashSet(SymbolEqualityComparer.Default); @@ -85,26 +120,36 @@ Compilation compilation { ITypeSymbol type = pending.Dequeue().WithNullableAnnotation(NullableAnnotation.NotAnnotated); if (!shapes.Add(type) || ContainsParameters(type) || type is INamedTypeSymbol { IsRefLikeType: true }) + { continue; + } if (type is INamedTypeSymbol nullable && nullable.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) { pending.Enqueue(nullable.TypeArguments[0]); continue; } if (type.SpecialType != SpecialType.None || type.ToDisplayString() is "System.Guid" or "System.Decimal") + { continue; + } if (IsSerializable(type) && !SymbolEqualityComparer.Default.Equals(type.ContainingAssembly, compilation.Assembly)) + { continue; + } ISymbol[] members = type is INamedTypeSymbol declaration ? CollectMembers(declaration, [declaration]).ToArray() : []; SerializationMetadataScope? scope = ResolveScope(type, members, compilation, root, scopes, rejectedOwners, output); if (scope is null) + { continue; + } GenerateMetadata(type, members, scope, compilation, pending, output); } output.AddSource("Registration/RuntimeSerializationMetadata.g.cs", root.Emit(compilation.AssemblyName)); int scopeIndex = 0; foreach (SerializationMetadataScope scope in scopes.Values) + { output.AddSource("Registration/RuntimeSerializationOwner" + scopeIndex++ + ".g.cs", scope.Emit(compilation.AssemblyName)); + } } private static void GenerateMetadata( @@ -119,19 +164,27 @@ SourceProductionContext output string typeName = Name(type); string? collection = SerializationCollectionGenerator.Generate(type, compilation, pending, accessors, ref scope.index); if (collection is null && !IsSerializable(type) && type.TypeKind != TypeKind.Struct) + { return; + } string creator = "CreateMetadata" + scope.index++; if (type is not INamedTypeSymbol named) { scope.registrations.Append(" register(").Append(creator).Append("());\n"); scope.creators.Append(" private static global::Inno.Core.Serialization.SerializationTypeMetadata ") - .Append(creator).Append("() => new(typeof(").Append(typeName) - .Append("), [], null, collection: ").Append(collection).Append(");\n"); + .Append(creator) + .Append("() => new(typeof(") + .Append(typeName) + .Append("), [], null, collection: ") + .Append(collection) + .Append(");\n"); scope.lookup.Append(" if (type == typeof(").Append(typeName).Append(")) return ").Append(creator).Append("();\n"); return; } if (members.Length == 0 && !IsSerializable(type) && collection is null) + { return; + } var memberCode = new List(); var keys = new HashSet(StringComparer.Ordinal); foreach (ISymbol member in members) @@ -139,8 +192,14 @@ SourceProductionContext output ITypeSymbol valueType = MemberType(member); if (!keys.Add(member.Name)) { - output.ReportDiagnostic(Diagnostic.Create(InvalidMember, member.Locations.FirstOrDefault(), - member.ToDisplayString(), "duplicate key")); + output.ReportDiagnostic( + Diagnostic.Create( + InvalidMember, + member.Locations.FirstOrDefault(), + member.ToDisplayString(), + "duplicate key" + ) + ); continue; } pending.Enqueue(valueType); @@ -149,33 +208,56 @@ SourceProductionContext output string? setter = (visibility & 10) != 0 ? CreateAccessor(member, false, scope.index++, accessors) : null; if (((visibility & 5) != 0 && getter is null) || ((visibility & 10) != 0 && setter is null)) { - output.ReportDiagnostic(Diagnostic.Create(InvalidMember, member.Locations.FirstOrDefault(), - member.ToDisplayString(), "required getter or writable setter is absent")); + output.ReportDiagnostic( + Diagnostic.Create( + InvalidMember, + member.Locations.FirstOrDefault(), + member.ToDisplayString(), + "required getter or writable setter is absent" + ) + ); continue; } - memberCode.Add("new global::Inno.Core.Serialization.SerializationMemberMetadata(" + Quote(member.Name) + memberCode.Add( + "new global::Inno.Core.Serialization.SerializationMemberMetadata(" + Quote(member.Name) + ", typeof(" + Name(valueType) + "), (global::Inno.Core.Serialization.PropertyVisibility)" - + visibility + ", " + (getter ?? "null") + ", " + (setter ?? "null") + ")"); + + visibility + ", " + (getter ?? "null") + ", " + (setter ?? "null") + ")" + ); } string factory = GenerateFactory(named, scope.index++, accessors); string hooks = GenerateHooks([named], ref scope.index, accessors, output); - bool requiresConverter = Ancestors(named).Any(static ancestor => ancestor.GetAttributes().Any(static attribute => - attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.RequiresSerializationConverterAttribute")); + bool requiresConverter = Ancestors(named).Any(static ancestor => ancestor.GetAttributes().Any(static attribute => ( + attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.RequiresSerializationConverterAttribute" + ))); string inherited = "null"; if (named.BaseType is INamedTypeSymbol baseType && IsSerializable(baseType)) { if (SymbolEqualityComparer.Default.Equals(baseType.ContainingAssembly, compilation.Assembly)) + { pending.Enqueue(baseType); + } inherited = "global::" + baseType.ContainingAssembly.Name - + ".Generated.RuntimeSerializationMetadataCatalog.GetMetadata(typeof(" + Name(baseType) + "))"; + + ".Generated.RuntimeSerializationMetadataCatalog.GetMetadata(typeof(" + Name(baseType) + "))"; } scope.registrations.Append(" register(").Append(creator).Append("());\n"); scope.lookup.Append(" if (type == typeof(").Append(typeName).Append(")) return ").Append(creator).Append("();\n"); scope.creators.Append(" private static global::Inno.Core.Serialization.SerializationTypeMetadata ") - .Append(creator).Append("() => new(typeof(") - .Append(typeName).Append("), [").Append(string.Join(", ", memberCode)).Append("], ") - .Append(factory).Append(", ").Append(hooks).Append(", ").Append(collection ?? "null") - .Append(", ").Append(requiresConverter ? "true" : "false").Append(", ").Append(inherited).Append(");\n"); + .Append(creator) + .Append("() => new(typeof(") + .Append(typeName) + .Append("), [") + .Append(string.Join(", ", memberCode)) + .Append("], ") + .Append(factory) + .Append(", ") + .Append(hooks) + .Append(", ") + .Append(collection ?? "null") + .Append(", ") + .Append(requiresConverter ? "true" : "false") + .Append(", ") + .Append(inherited) + .Append(");\n"); } private static SerializationMetadataScope? ResolveScope( @@ -189,15 +271,25 @@ SourceProductionContext output ) { ITypeSymbol[] referencedTypes = new[] { type }.Concat(members.Select(MemberType)).ToArray(); if (referencedTypes.All(value => IsAccessible(value, compilation.Assembly))) + { return root; + } INamedTypeSymbol? owner = FindInaccessibleOwner(type, compilation.Assembly) - ?? (type as INamedTypeSymbol); + ?? (type as INamedTypeSymbol); while (owner is not null && !referencedTypes.All(value => compilation.IsSymbolAccessibleWithin(value, owner))) + { owner = owner.ContainingType; + } if (owner is null) { - output.ReportDiagnostic(Diagnostic.Create(InvalidMember, type.Locations.FirstOrDefault(), - type.ToDisplayString(), "no source owner can access all serialized member types")); + output.ReportDiagnostic( + Diagnostic.Create( + InvalidMember, + type.Locations.FirstOrDefault(), + type.ToDisplayString(), + "no source owner can access all serialized member types" + ) + ); return null; } var chain = new Stack(); @@ -206,8 +298,16 @@ SourceProductionContext output if (!SerializationMetadataScope.CanExtend(current)) { if (rejectedOwners.Add(current)) - output.ReportDiagnostic(Diagnostic.Create(InvalidOwner, current.Locations.FirstOrDefault(), - type.ToDisplayString(), current.ToDisplayString())); + { + output.ReportDiagnostic( + Diagnostic.Create( + InvalidOwner, + current.Locations.FirstOrDefault(), + type.ToDisplayString(), + current.ToDisplayString() + ) + ); + } return null; } chain.Push(current); @@ -231,12 +331,20 @@ SourceProductionContext output IAssemblySymbol assembly ) { if (type is IArrayTypeSymbol array) + { return FindInaccessibleOwner(array.ElementType, assembly); + } if (type is not INamedTypeSymbol named) + { return null; + } foreach (ITypeSymbol argument in named.TypeArguments) + { if (FindInaccessibleOwner(argument, assembly) is INamedTypeSymbol owner) + { return owner; + } + } return IsAccessible(named, assembly) ? null : named.ContainingType; } @@ -249,26 +357,32 @@ IEnumerable hierarchy ) { foreach (INamedTypeSymbol ancestor in hierarchy.Reverse()) { - foreach (ISymbol member in ancestor.GetMembers().Where(static member => !member.IsStatic) - .OrderBy(GetOrder).ThenBy(static member => member.Locations.FirstOrDefault()?.SourceSpan.Start ?? int.MaxValue)) - { + foreach (ISymbol member in ancestor.GetMembers() + .Where(static member => !member.IsStatic) + .OrderBy(GetOrder) + .ThenBy(static member => member.Locations.FirstOrDefault()?.SourceSpan.Start ?? int.MaxValue) + ) { bool annotated = member.GetAttributes().Any(static attribute => attribute.AttributeClass?.ToDisplayString() == C_PROPERTY); bool defaultStructMember = type.TypeKind == TypeKind.Struct && (member is IFieldSymbol { DeclaredAccessibility: Accessibility.Public, IsReadOnly: false, IsConst: false } || member is IPropertySymbol { GetMethod.DeclaredAccessibility: Accessibility.Public, SetMethod.DeclaredAccessibility: Accessibility.Public, IsIndexer: false }); if ((annotated || defaultStructMember) && member is IFieldSymbol or IPropertySymbol { IsIndexer: false }) + { yield return member; + } } } } private static int GetOrder(ISymbol member) - => member.GetAttributes().FirstOrDefault(static attribute => attribute.AttributeClass?.ToDisplayString() == C_PROPERTY) + => member.GetAttributes() + .FirstOrDefault(static attribute => attribute.AttributeClass?.ToDisplayString() == C_PROPERTY) ?.NamedArguments.FirstOrDefault(static argument => argument.Key == "order").Value.Value as int? ?? int.MaxValue; private static int GetVisibility(ISymbol member) - => member.GetAttributes().FirstOrDefault(static attribute => attribute.AttributeClass?.ToDisplayString() == C_PROPERTY) + => member.GetAttributes() + .FirstOrDefault(static attribute => attribute.AttributeClass?.ToDisplayString() == C_PROPERTY) ?.ConstructorArguments.FirstOrDefault().Value as int? ?? 15; private static string? CreateAccessor( @@ -281,35 +395,65 @@ StringBuilder accessors ITypeSymbol valueType = member is IFieldSymbol field ? field.Type : ((IPropertySymbol)member).Type; string value = Name(valueType); bool isStruct = member.ContainingType.IsValueType; - string target = isStruct ? "ref global::System.Runtime.CompilerServices.Unsafe.Unbox<" + declaring + ">(target)" - : "(" + declaring + ")target"; + string target = isStruct + ? "ref global::System.Runtime.CompilerServices.Unsafe.Unbox<" + declaring + ">(target)" + : "(" + declaring + ")target"; if (member is IFieldSymbol fieldMember) { if (!read && (fieldMember.IsReadOnly || fieldMember.IsConst)) + { return null; - accessors.Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = ") - .Append(Quote(member.Name)).Append(")]\n private static extern ref ").Append(value) - .Append(" Access").Append(index).Append("(").Append(isStruct ? "ref " : "").Append(declaring).Append(" target);\n"); - return read ? "static target => Access" + index + "(" + target + ")" - : "static (target, value) => Access" + index + "(" + target + ") = (" + value + ")value!"; + } + accessors + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = " + ) + .Append(Quote(member.Name)) + .Append(")]\n private static extern ref ") + .Append(value) + .Append(" Access") + .Append(index) + .Append("(") + .Append(isStruct ? "ref " : "") + .Append(declaring) + .Append(" target);\n"); + return read + ? "static target => Access" + index + "(" + target + ")" + : "static (target, value) => Access" + index + "(" + target + ") = (" + value + ")value!"; } IPropertySymbol property = (IPropertySymbol)member; IMethodSymbol? method = read ? property.GetMethod : property.SetMethod; if (method is null || (!read && method.IsInitOnly)) + { return null; + } if (method.DeclaredAccessibility == Accessibility.Public) { - string receiver = isStruct ? "global::System.Runtime.CompilerServices.Unsafe.Unbox<" + declaring + ">(target)" - : "((" + declaring + ")target)"; - return read ? "static target => " + receiver + ".@" + member.Name - : "static (target, value) => " + receiver + ".@" + member.Name + " = (" + value + ")value!"; - } - accessors.Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Method, Name = ") - .Append(Quote(method.MetadataName)).Append(")]\n private static extern ").Append(read ? value : "void") - .Append(" Access").Append(index).Append("(").Append(isStruct ? "ref " : "").Append(declaring).Append(" target") - .Append(read ? "" : ", " + value + " value").Append(");\n"); - return read ? "static target => Access" + index + "(" + target + ")" - : "static (target, value) => Access" + index + "(" + target + ", (" + value + ")value!)"; + string receiver = isStruct + ? "global::System.Runtime.CompilerServices.Unsafe.Unbox<" + declaring + ">(target)" + : "((" + declaring + ")target)"; + return read + ? "static target => " + receiver + ".@" + member.Name + : "static (target, value) => " + receiver + ".@" + member.Name + " = (" + value + ")value!"; + } + accessors + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Method, Name = " + ) + .Append(Quote(method.MetadataName)) + .Append(")]\n private static extern ") + .Append(read ? value : "void") + .Append(" Access") + .Append(index) + .Append("(") + .Append(isStruct ? "ref " : "") + .Append(declaring) + .Append(" target") + .Append(read ? "" : ", " + value + " value") + .Append(");\n"); + return read + ? "static target => Access" + index + "(" + target + ")" + : "static (target, value) => Access" + index + "(" + target + ", (" + value + ")value!)"; } private static string GenerateFactory( @@ -318,17 +462,34 @@ private static string GenerateFactory( StringBuilder accessors ) { if (type.IsValueType) + { return "static () => default(" + Name(type) + ")"; + } if (type.IsAbstract || type.TypeKind != TypeKind.Class || Ancestors(type).Any(static ancestor => - ancestor.GetMembers().Any(static member => member is IPropertySymbol { IsRequired: true } or IFieldSymbol { IsRequired: true }))) + ancestor + .GetMembers() + .Any(static member => member is IPropertySymbol { IsRequired: true } or IFieldSymbol { IsRequired: true })) + ) { return "null"; + } IMethodSymbol? constructor = type.InstanceConstructors.FirstOrDefault(static constructor => constructor.Parameters.Length == 0); if (constructor is null) + { return "null"; + } if (constructor.DeclaredAccessibility == Accessibility.Public) + { return "static () => new " + Name(type) + "()"; - accessors.Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n") - .Append(" private static extern ").Append(Name(type)).Append(" Construct").Append(index).Append("();\n"); + } + accessors + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n" + ) + .Append(" private static extern ") + .Append(Name(type)) + .Append(" Construct") + .Append(index) + .Append("();\n"); return "static () => Construct" + index + "()"; } @@ -344,25 +505,36 @@ SourceProductionContext output IMethodSymbol[] hooks = ancestor.GetMembers().OfType().Where(static method => method.GetAttributes().Any(static attribute => attribute.AttributeClass?.ToDisplayString() == C_RESTORED)).ToArray(); if (hooks.Length > 1) + { output.ReportDiagnostic(Diagnostic.Create(InvalidHook, ancestor.Locations.FirstOrDefault(), ancestor.ToDisplayString())); + } foreach (IMethodSymbol hook in hooks) { if (hook.IsStatic || hook.IsVirtual || hook.IsOverride || hook.IsAbstract || hook.IsGenericMethod || !hook.ReturnsVoid || hook.Parameters.Length > 1 || hook.Parameters.Length == 1 && (hook.Parameters[0].RefKind != RefKind.None - || hook.Parameters[0].Type.ToDisplayString() != "Inno.Core.Serialization.SerializationContext")) - { + || hook.Parameters[0].Type.ToDisplayString() != "Inno.Core.Serialization.SerializationContext") + ) { output.ReportDiagnostic(Diagnostic.Create(InvalidHook, hook.Locations.FirstOrDefault(), hook.ToDisplayString())); continue; } string name = "Restore" + index++; - accessors.Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Method, Name = ") - .Append(Quote(hook.MetadataName)).Append(")]\n private static extern void ").Append(name) - .Append("(").Append(ancestor.IsValueType ? "ref " : "").Append(Name(ancestor)).Append(" target") + accessors + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Method, Name = " + ) + .Append(Quote(hook.MetadataName)) + .Append(")]\n private static extern void ") + .Append(name) + .Append("(") + .Append(ancestor.IsValueType ? "ref " : "") + .Append(Name(ancestor)) + .Append(" target") .Append(hook.Parameters.Length == 0 ? "" : ", global::Inno.Core.Serialization.SerializationContext context") .Append(");\n"); - string target = ancestor.IsValueType ? "ref global::System.Runtime.CompilerServices.Unsafe.Unbox<" + Name(ancestor) + ">(target)" - : "(" + Name(ancestor) + ")target"; + string target = ancestor.IsValueType + ? "ref global::System.Runtime.CompilerServices.Unsafe.Unbox<" + Name(ancestor) + ">(target)" + : "(" + Name(ancestor) + ")target"; calls.Add(name + "(" + target + (hook.Parameters.Length == 0 ? "" : ", context") + ");"); } } @@ -371,8 +543,11 @@ SourceProductionContext output private static IEnumerable Ancestors(INamedTypeSymbol type) { - for (INamedTypeSymbol? current = type; current is not null && current.SpecialType != SpecialType.System_Object; current = current.BaseType) + for (INamedTypeSymbol? current = type; current is not null + && current.SpecialType != SpecialType.System_Object; current = current.BaseType + ) { yield return current; + } } private static IEnumerable EnumerateTypes(INamespaceOrTypeSymbol scope) @@ -380,10 +555,16 @@ private static IEnumerable EnumerateTypes(INamespaceOrTypeSymb foreach (ISymbol member in scope.GetMembers()) { if (member is INamedTypeSymbol type) + { yield return type; + } if (member is INamespaceOrTypeSymbol nested) + { foreach (INamedTypeSymbol nestedType in EnumerateTypes(nested)) + { yield return nestedType; + } + } } } @@ -392,27 +573,36 @@ private static bool IsSerializable(ITypeSymbol type) private static bool ContainsParameters(ITypeSymbol type) => type.TypeKind == TypeKind.TypeParameter || type is INamedTypeSymbol named && (named.TypeArguments.Any(ContainsParameters) - || named.ContainingType is not null && ContainsParameters(named.ContainingType)) - || type is IArrayTypeSymbol array && ContainsParameters(array.ElementType); + || named.ContainingType is not null && ContainsParameters(named.ContainingType)) + || type is IArrayTypeSymbol array && ContainsParameters(array.ElementType); private static bool IsAccessible( ITypeSymbol type, IAssemblySymbol assembly ) { if (type is IArrayTypeSymbol array) + { return IsAccessible(array.ElementType, assembly); + } if (type is not INamedTypeSymbol named) + { return false; + } for (INamedTypeSymbol? current = named; current is not null; current = current.ContainingType) + { if (current.IsFileLocal || current.DeclaredAccessibility != Accessibility.Public && (current.ContainingAssembly is null || !SymbolEqualityComparer.Default.Equals(current.ContainingAssembly, assembly) - || current.DeclaredAccessibility is not (Accessibility.Internal or Accessibility.ProtectedOrInternal))) + || current.DeclaredAccessibility is not (Accessibility.Internal or Accessibility.ProtectedOrInternal)) + ) { return false; + } + } return named.TypeArguments.All(argument => argument.TypeKind == TypeKind.TypeParameter || IsAccessible(argument, assembly)); } - private static string Name(ITypeSymbol type) => type.WithNullableAnnotation(NullableAnnotation.NotAnnotated) - .ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + private static string Name(ITypeSymbol type) + => type.WithNullableAnnotation(NullableAnnotation.NotAnnotated) + .ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); private static string Quote(string value) => SymbolDisplay.FormatLiteral(value, quote: true); } diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs index d07ee5f0c..0fa74bccf 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs @@ -29,66 +29,103 @@ internal string Emit(string assemblyName) var code = new StringBuilder("// \n#nullable enable\n"); var owners = new Stack(); for (INamedTypeSymbol? current = owner; current is not null; current = current.ContainingType) + { owners.Push(current); - string namespaceName = owner is null ? assemblyName + ".Generated" - : owner.ContainingNamespace.IsGlobalNamespace ? "" : owner.ContainingNamespace.ToDisplayString(); + } + string namespaceName = owner is null + ? assemblyName + ".Generated" + : owner.ContainingNamespace.IsGlobalNamespace ? "" : owner.ContainingNamespace.ToDisplayString(); if (namespaceName.Length > 0) + { code.Append("namespace ").Append(namespaceName).Append(";\n"); + } foreach (INamedTypeSymbol declaration in owners) + { code.Append(Declaration(declaration)).Append("\n{\n"); + } bool root = owner is null; if (root) + { code.Append("/// \n/// Supplies closed serialization access and construction for this assembly.\n/// \n"); - code.Append(root ? "public" : "internal").Append(" static class ") - .Append(root ? "RuntimeSerializationMetadataCatalog" : C_CATALOG).Append("\n{\n") - .Append(" /// \n /// Contributes generated metadata without retaining the composition callback.\n /// \n") + } + code.Append(root ? "public" : "internal") + .Append(" static class ") + .Append(root ? "RuntimeSerializationMetadataCatalog" : C_CATALOG) + .Append("\n{\n") + .Append( + " /// \n /// Contributes generated metadata without retaining the composition callback.\n /// \n" + ) .Append(" /// \n /// The composition-owned registration callback.\n /// \n") - .Append(" /// \n /// The callback is null.\n /// \n") - .Append(" ").Append(root ? "public" : "internal") - .Append(" static void Register(global::System.Action register)\n {\n") + .Append( + " /// \n /// The callback is null.\n /// \n" + ) + .Append(" ") + .Append(root ? "public" : "internal") + .Append( + " static void Register(global::System.Action register)\n {\n" + ) .Append(" global::System.ArgumentNullException.ThrowIfNull(register);\n") .Append(registrations); foreach (SerializationMetadataScope child in m_children) + { code.Append(" ").Append(ChildName(child, root)).Append(".Register(register);\n"); + } code.Append(" }\n") .Append(" /// \n /// Creates metadata through its declaration's generated accessors.\n /// \n") .Append(" /// \n /// The exact closed declaration.\n /// \n") .Append(" /// \n /// Complete access metadata for an owned declaration.\n /// \n") - .Append(" /// \n /// The declaration is null.\n /// \n") - .Append(" ").Append(root ? "public" : "internal") + .Append( + " /// \n /// The declaration is null.\n /// \n" + ) + .Append(" ") + .Append(root ? "public" : "internal") .Append(" static global::Inno.Core.Serialization.SerializationTypeMetadata") - .Append(root ? " GetMetadata" : "? FindMetadata").Append("(global::System.Type type)\n {\n") + .Append(root ? " GetMetadata" : "? FindMetadata") + .Append("(global::System.Type type)\n {\n") .Append(" global::System.ArgumentNullException.ThrowIfNull(type);\n") .Append(lookup); if (m_children.Count > 0) { code.Append(" global::Inno.Core.Serialization.SerializationTypeMetadata? metadata;\n"); foreach (SerializationMetadataScope child in m_children) - code.Append(" metadata = ").Append(ChildName(child, root)).Append(".FindMetadata(type);\n") + { + code.Append(" metadata = ") + .Append(ChildName(child, root)) + .Append(".FindMetadata(type);\n") .Append(" if (metadata is not null) return metadata;\n"); + } } - code.Append(root + code + .Append( + root ? " throw new global::System.ArgumentException(\"The serialization declaration is not registered.\", nameof(type));\n" - : " return null;\n") - .Append(" }\n").Append(creators).Append(accessors) + : " return null;\n" + ) + .Append(" }\n") + .Append(creators) + .Append(accessors) .Append(" private static T[] BuildArray(global::System.Collections.Generic.IReadOnlyList values)\n {\n") .Append(" var result = new T[values.Count];\n for (int index = 0; index < result.Length; index++)\n") .Append(" result[index] = (T)values[index]!;\n return result;\n }\n}\n"); foreach (INamedTypeSymbol _ in owners) + { code.Append("}\n"); + } return code.ToString(); } internal static bool CanExtend(INamedTypeSymbol owner) => owner.TypeParameters.Length == 0 && !owner.IsFileLocal && owner.DeclaringSyntaxReferences.Length > 0 - && owner.DeclaringSyntaxReferences.All(static reference => reference.GetSyntax() is TypeDeclarationSyntax syntax - && syntax.Modifiers.Any(SyntaxKind.PartialKeyword)); + && owner.DeclaringSyntaxReferences.All(static reference => ( + reference.GetSyntax() is TypeDeclarationSyntax syntax + && syntax.Modifiers.Any(SyntaxKind.PartialKeyword) + )); private static string ChildName( SerializationMetadataScope child, bool root ) => (root ? child.owner!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) : "@" + child.owner!.Name) - + "." + C_CATALOG; + + "." + C_CATALOG; private static string Declaration(INamedTypeSymbol type) { @@ -102,8 +139,9 @@ private static string Declaration(INamedTypeSymbol type) _ => "internal" }; string modifiers = type.IsStatic ? " static" : type.IsReadOnly ? " readonly" : ""; - string kind = type.IsRecord ? type.IsValueType ? "record struct" : "record class" - : type.TypeKind == TypeKind.Struct ? "struct" : "class"; + string kind = type.IsRecord + ? type.IsValueType ? "record struct" : "record class" + : type.TypeKind == TypeKind.Struct ? "struct" : "class"; return visibility + modifiers + " partial " + kind + " @" + type.Name; } } diff --git a/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs b/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs index 6b5262e40..b57adce30 100644 --- a/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs +++ b/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs @@ -36,7 +36,8 @@ internal SerializationCaptureKeyBuilder( Type rootType, Inno.Core.Identity.Identity source, SerializationCaptureKey? previous - ) : this(operation, previous) { + ) : this(operation, previous) + { if (source.runtimeIdentity is not { } identity) { m_unavailable = true; @@ -110,7 +111,9 @@ public bool TryAddOwner( ArgumentNullException.ThrowIfNull(source); Inno.Core.Identity.Identity snapshot = source.identity; if (!revision.HasValue || snapshot.runtimeIdentity is not { } identity) + { return Decline(); + } Add(new(C_OWNER, identity, revision.Value, default, null)); AddIdentity(new(snapshot, identity)); return true; @@ -136,23 +139,35 @@ public bool TryAddProperties(ISerializable source) SerializationOperation operation = RequireOperation(); ArgumentNullException.ThrowIfNull(source); if (source is not IdentityObject identified) + { return Decline(); + } Inno.Core.Identity.Identity snapshot = identified.identity; if (snapshot.runtimeIdentity is not { } identity) + { return Decline(); + } ISerializationMetadataSource provider = operation.context.GetRequired(); SerializationTypeMetadata metadata = provider.GetMetadata(source.GetType()); if (metadata.captureRevision is null) { foreach (SerializationMemberMetadata member in metadata.members) + { if ((member.visibility & PropertyVisibility.Serialize) != 0) + { return Decline(); + } + } } if (!operation.converters.CanReuseRevision(metadata, provider)) + { return Decline(); + } ulong? revision = metadata.captureRevision is { } readRevision ? readRevision(source) : 0; if (!revision.HasValue) + { return Decline(); + } Add(new(C_OWNER, identity, revision.Value, metadata.captureIdentity, null)); AddIdentity(new(snapshot, identity)); return true; @@ -195,13 +210,17 @@ internal SerializationCaptureAttempt Complete() { RequireOperation(); if (m_unavailable || m_identityCount == 0) + { return SerializationCaptureAttempt.empty; + } SerializationCaptureKey key = m_parts is null && m_previous is not null && m_previous.parts.Length == m_count - ? m_previous - : new(m_parts is not null ? m_parts.ToArray() : m_previous!.parts.AsSpan(0, m_count).ToArray()); + ? m_previous + : new(m_parts is not null ? m_parts.ToArray() : m_previous!.parts.AsSpan(0, m_count).ToArray()); ReadOnlySpan identities = m_identities.AsSpan(0, m_identityCount); foreach (SerializationCaptureIdentity identity in identities) + { identity.Validate(); + } return new(key, ReferenceEquals(key, m_previous) ? [] : identities.ToArray()); } @@ -215,14 +234,19 @@ internal void Retire() m_identities = []; m_identityCount = 0; if (identities.Length > 0) + { ArrayPool.Shared.Return(identities, clearArray: true); + } } private SerializationOperation RequireOperation() { - SerializationOperation operation = m_operation ?? throw new InvalidOperationException("The serialization key callback has retired."); + SerializationOperation operation = m_operation + ?? throw new InvalidOperationException("The serialization key callback has retired."); if (Environment.CurrentManagedThreadId != m_threadId) + { throw new InvalidOperationException("The serialization key callback belongs to another thread."); + } operation.EnsureActive(); return operation; } @@ -242,13 +266,17 @@ private void AddIdentity(SerializationCaptureIdentity identity) private void EnsureIdentityCapacity(int capacity) { if (capacity <= m_identities.Length) + { return; + } SerializationCaptureIdentity[] identities = ArrayPool.Shared.Rent(capacity); m_identities.AsSpan(0, m_identityCount).CopyTo(identities); SerializationCaptureIdentity[] previous = m_identities; m_identities = identities; if (previous.Length > 0) + { ArrayPool.Shared.Return(previous, clearArray: true); + } } private void Add(SerializationCaptureKeyPart part) @@ -263,8 +291,12 @@ private void Add(SerializationCaptureKeyPart part) { m_parts = new(Math.Max(m_capacity, m_count + 1)); if (m_previous is not null) + { for (int index = 0; index < m_count; index++) + { m_parts.Add(m_previous.parts[index]); + } + } } m_parts.Add(part); m_count++; @@ -276,15 +308,19 @@ internal sealed record SerializationCaptureKey(SerializationCaptureKeyPart[] par internal bool HasSameInputs(SerializationCaptureKey other) { if (parts.Length != other.parts.Length) + { return false; + } for (int index = 0; index < parts.Length; index++) { SerializationCaptureKeyPart before = parts[index]; SerializationCaptureKeyPart after = other.parts[index]; - if (before.kind != after.kind || before.identity != after.identity || - before.revision != after.revision || !string.Equals(before.text, after.text, StringComparison.Ordinal) || - before.kind == SerializationCaptureKeyBuilder.C_GUID && before.metadata != after.metadata) + if (before.kind != after.kind || before.identity != after.identity + || before.revision != after.revision || !string.Equals(before.text, after.text, StringComparison.Ordinal) + || before.kind == SerializationCaptureKeyBuilder.C_GUID && before.metadata != after.metadata + ) { return false; + } } return true; } @@ -305,14 +341,22 @@ internal static SerializationCaptureAttempt Capture( Func? captureKey = null ) { if (!operation.isSnapshotCapture) + { return empty; + } SerializationCaptureKeyBuilder builder; if (captureKey is not null) + { builder = new(operation, previous); + } else if (value is IdentityObject identified && identified.identity.runtimeIdentity is not null) + { builder = new(operation, valueType, identified.identity, previous); + } else + { return empty; + } try { bool complete = captureKey is not null ? captureKey(value, builder) : converter!.CaptureKey(value, builder); @@ -327,7 +371,9 @@ internal static SerializationCaptureAttempt Capture( internal SerializationCaptureKey? Verify(SerializationCaptureAttempt after) { if (key is null || after.key is null || !key.HasSameInputs(after.key)) + { throw new InvalidOperationException("The declared serialization capture inputs changed during the write."); + } // Fresh equivalent metadata preserves ordinary capture without publishing a reusable hint. return ReferenceEquals(after.key, key) ? key : null; } @@ -335,9 +381,13 @@ internal static SerializationCaptureAttempt Capture( internal void ValidateIdentities() { if (identities is null) + { return; + } foreach (SerializationCaptureIdentity identity in identities) + { identity.Validate(); + } } } @@ -348,7 +398,9 @@ RuntimeIdentity expected internal void Validate() { if (identity.runtimeIdentity != expected) + { throw new InvalidOperationException($"Core identity '{expected}' changed during serialization capture."); + } } } diff --git a/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs b/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs index 4e9b73008..98f919c28 100644 --- a/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs +++ b/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs @@ -35,16 +35,21 @@ private SerializationContext(KeyValuePair[] values) /// /// Thrown when is null. /// - public SerializationContext With(TContext value) where TContext : class + public SerializationContext With(TContext value) + where TContext : class { ArgumentNullException.ThrowIfNull(value); Type key = typeof(TContext); for (int index = 0; index < m_values.Length; index++) { if (m_values[index].Key != key) + { continue; + } if (ReferenceEquals(m_values[index].Value, value)) + { return new SerializationContext(m_values); + } var updated = (KeyValuePair[])m_values.Clone(); updated[index] = new(key, value); return new SerializationContext(updated); @@ -67,7 +72,8 @@ public SerializationContext With(TContext value) where TContext : clas /// /// when a value is registered; otherwise, . /// - public bool TryGet(out TContext? value) where TContext : class + public bool TryGet(out TContext? value) + where TContext : class { foreach (KeyValuePair pair in m_values) { @@ -94,9 +100,11 @@ public bool TryGet(out TContext? value) where TContext : class /// /// Thrown when the requested context was not registered. /// - public TContext GetRequired() where TContext : class - => TryGet(out TContext? value) && value is not null - ? value - : throw new InvalidOperationException( - $"Serialization context '{typeof(TContext).FullName}' is not registered."); + public TContext GetRequired() + where TContext : class + => TryGet(out TContext? value) && value is not null + ? value + : throw new InvalidOperationException( + $"Serialization context '{typeof(TContext).FullName}' is not registered." + ); } diff --git a/src/foundation/core/Inno.Core.Serialization/Converters/SerializationConverter.cs b/src/foundation/core/Inno.Core.Serialization/Converters/SerializationConverter.cs index 44468ae38..28a55112d 100644 --- a/src/foundation/core/Inno.Core.Serialization/Converters/SerializationConverter.cs +++ b/src/foundation/core/Inno.Core.Serialization/Converters/SerializationConverter.cs @@ -58,9 +58,9 @@ T value public virtual void Restore( SerializationReader reader, T target - ) - => throw new NotSupportedException( - $"Serialization converter '{GetType().FullName}' does not support restoring existing '{typeof(T).FullName}' values."); + ) => throw new NotSupportedException( + $"Serialization converter '{GetType().FullName}' does not support restoring existing '{typeof(T).FullName}' values." + ); /// /// Optionally declares every input to a snapshot capture without writing data. diff --git a/src/foundation/core/Inno.Core.Serialization/Converters/TypeRefConverter.cs b/src/foundation/core/Inno.Core.Serialization/Converters/TypeRefConverter.cs index 766b124cf..98a05df1e 100644 --- a/src/foundation/core/Inno.Core.Serialization/Converters/TypeRefConverter.cs +++ b/src/foundation/core/Inno.Core.Serialization/Converters/TypeRefConverter.cs @@ -1,7 +1,6 @@ using System; - -using Inno.Extensibility.Types; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Core.Serialization; diff --git a/src/foundation/core/Inno.Core.Serialization/IO/SerializationReader.cs b/src/foundation/core/Inno.Core.Serialization/IO/SerializationReader.cs index 1017a968d..0971f4889 100644 --- a/src/foundation/core/Inno.Core.Serialization/IO/SerializationReader.cs +++ b/src/foundation/core/Inno.Core.Serialization/IO/SerializationReader.cs @@ -97,12 +97,7 @@ Type declaredType ) { ArgumentNullException.ThrowIfNull(declaredType); SerializationNode node = GetRequiredNode(name); - return ValuePipeline.Read( - node, - declaredType, - m_operation, - AppendPath(name), - allowDefaultObject: false); + return ValuePipeline.Read(node, declaredType, m_operation, AppendPath(name), allowDefaultObject: false); } /// @@ -136,7 +131,8 @@ out TValue value typeof(TValue), m_operation, AppendPath(name), - allowDefaultObject: false)!; + allowDefaultObject: false + )!; return true; } @@ -153,7 +149,9 @@ public SerializationReader ReadObject(string name) { SerializationNode node = GetRequiredNode(name); if (node is not ObjectSerializationNode child) + { throw new InvalidOperationException($"Serialization value '{AppendPath(name)}' must be an object."); + } return new SerializationReader(m_operation, child, AppendPath(name), typeof(object)); } @@ -170,13 +168,17 @@ public IReadOnlyList ReadObjectArray(string name) { SerializationNode node = GetRequiredNode(name); if (node is not ArraySerializationNode array) + { throw new InvalidOperationException($"Serialization value '{AppendPath(name)}' must be an array."); + } var readers = new SerializationReader[array.values.Count]; for (int i = 0; i < array.values.Count; i++) { if (array.values[i] is not ObjectSerializationNode child) + { throw new InvalidOperationException($"Serialization value '{AppendPath(name)}[{i}]' must be an object."); + } readers[i] = new SerializationReader(m_operation, child, $"{AppendPath(name)}[{i}]", typeof(object)); } @@ -218,9 +220,13 @@ private SerializationNode GetRequiredNode(string name) { m_operation.EnsureActive(); if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("A non-empty serialization member name is required.", nameof(name)); + } if (!m_node.values.TryGetValue(name, out SerializationNode? node)) + { throw new InvalidOperationException($"Required serialization value '{AppendPath(name)}' is missing."); + } return node; } diff --git a/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs b/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs index d2c427c8e..deec06e56 100644 --- a/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs +++ b/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs @@ -29,7 +29,9 @@ Type valueType m_operationGeneration = operation.writerGeneration; m_previous = previous; if (previous is null) + { m_node = new ObjectSerializationNode(); + } this.path = path; this.valueType = valueType; } @@ -96,10 +98,10 @@ TValue value if (m_previous is not null && m_previous.values.Count <= 64 && m_writtenCount < m_previous.values.Count) { KeyValuePair entry = m_previous.values.GetAt(m_writtenCount); - if (string.Equals(entry.Key, name, StringComparison.Ordinal) && entry.Value is ScalarSerializationNode scalar && - scalar.value.GetType() == typeof(TValue) && m_operation.ResolveConverter(typeof(TValue)) is null && - SerializationNodeReuse.SameScalar(value, scalar.value)) - { + if (string.Equals(entry.Key, name, StringComparison.Ordinal) && entry.Value is ScalarSerializationNode scalar + && scalar.value.GetType() == typeof(TValue) && m_operation.ResolveConverter(typeof(TValue)) is null + && SerializationNodeReuse.SameScalar(value, scalar.value) + ) { MarkWritten(name, m_writtenCount); return; } @@ -137,8 +139,10 @@ Type declaredType ValidateName(name); EnsureActive(); SerializationNode? previous = Previous(name); - AddNode(name, ValuePipeline.Write(value, declaredType, m_operation, AppendPath(name), - allowDefaultObject: false, previous)); + AddNode( + name, + ValuePipeline.Write(value, declaredType, m_operation, AppendPath(name), allowDefaultObject: false, previous) + ); } /// @@ -219,17 +223,24 @@ public void WriteObjectArray( if (values is TValue[] items) { for (int itemIndex = 0; itemIndex < items.Length; itemIndex++) + { WriteElement(items[itemIndex]); + } } else + { foreach (TValue value in values) + { WriteElement(value); + } + } ReplaceNode(name, array.Complete()); void WriteElement(TValue value) { ObjectSerializationNode? prior = array.Next as ObjectSerializationNode; - SerializationCaptureAttempt attempt = captureKey is null ? SerializationCaptureAttempt.empty + SerializationCaptureAttempt attempt = captureKey is null + ? SerializationCaptureAttempt.empty : SerializationCaptureAttempt.Capture(m_operation, typeof(TValue), value, prior?.captureKey, captureKey: captureKey); SerializationCaptureKey? key = attempt.key; if (key is not null && ReferenceEquals(key, prior?.captureKey)) @@ -238,8 +249,12 @@ void WriteElement(TValue value) index++; return; } - var child = new SerializationWriter(m_operation, prior, - array.Next?.capturePath ?? $"{AppendPath(name)}[{index}]", typeof(TValue)); + var child = new SerializationWriter( + m_operation, + prior, + array.Next?.capturePath ?? $"{AppendPath(name)}[{index}]", + typeof(TValue) + ); long converterWrites = m_operation.converterWrites; writeElement(child, value); ObjectSerializationNode result = child.Complete(); @@ -248,10 +263,14 @@ void WriteElement(TValue value) attempt.ValidateIdentities(); key = attempt.Verify(SerializationCaptureAttempt.Capture(m_operation, typeof(TValue), value, key, captureKey: captureKey)); if (m_operation.converterWrites != converterWrites) + { key = null; + } } if (ReferenceEquals(result, prior) && prior!.captureKey is null) + { key = null; + } array.Add(SerializationNodeReuse.WithCaptureKey(result, prior, key)); index++; } @@ -324,7 +343,9 @@ internal ObjectSerializationNode Complete() { string name = m_previous.values.GetAt(index).Key; if (m_previous.values.Count <= 64 ? (m_writtenMask & (1UL << index)) == 0 : m_writtenNames?.Contains(name) != true) + { m_node!.values.Remove(name); + } } } ObjectSerializationNode result = m_node ?? m_previous ?? new ObjectSerializationNode(); @@ -334,9 +355,11 @@ internal ObjectSerializationNode Complete() private SerializationNode? Previous(string name) { - if (m_previous is not null && m_writtenCount < m_previous.values.Count && - string.Equals(m_previous.values.GetAt(m_writtenCount).Key, name, StringComparison.Ordinal)) + if (m_previous is not null && m_writtenCount < m_previous.values.Count + && string.Equals(m_previous.values.GetAt(m_writtenCount).Key, name, StringComparison.Ordinal) + ) { return m_previous.values.GetAt(m_writtenCount).Value; + } return m_previous is not null && m_previous.values.TryGetValue(name, out SerializationNode? value) ? value : null; } @@ -349,17 +372,23 @@ SerializationNode node { m_node ??= new ObjectSerializationNode(); if (!m_node.values.TryAdd(name, node)) + { throw new InvalidOperationException($"Serialization object '{path}' already contains key '{name}'."); + } return; } int index = -1; if (m_previous.values.Count <= 64) { - if (m_writtenCount < m_previous.values.Count && - string.Equals(m_previous.values.GetAt(m_writtenCount).Key, name, StringComparison.Ordinal)) + if (m_writtenCount < m_previous.values.Count + && string.Equals(m_previous.values.GetAt(m_writtenCount).Key, name, StringComparison.Ordinal) + ) { index = m_writtenCount; + } else + { index = m_previous.values.IndexOf(name); + } } SerializationNode? previous = index >= 0 ? m_previous.values.GetAt(index).Value : Previous(name); MarkWritten(name, index); @@ -382,16 +411,22 @@ int previousIndex m_writtenMask |= bit; } else + { duplicate = !(m_writtenNames ??= new(StringComparer.Ordinal)).Add(name); + } if (duplicate) + { throw new InvalidOperationException($"Serialization object '{path}' already contains key '{name}'."); + } m_writtenCount++; } private void EnsureMutable() { if (m_node is not null) + { return; + } m_node = m_previous is null ? new ObjectSerializationNode() : SerializationNodeReuse.CopyObject(m_previous); } @@ -411,9 +446,13 @@ private void EnsureActive() { m_operation.EnsureActive(); if (m_operationGeneration != m_operation.writerGeneration) + { throw new InvalidOperationException("The serialization writer belongs to a completed property capture."); + } if (m_completed && m_operation.isSnapshotCapture) + { throw new InvalidOperationException("The serialization writer callback has already completed."); + } } private string AppendPath(string name) => Previous(name)?.capturePath ?? (path == "$" ? $"$.{name}" : $"{path}.{name}"); @@ -421,6 +460,8 @@ private void EnsureActive() private static void ValidateName(string name) { if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("A non-empty serialization member name is required.", nameof(name)); + } } } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Capture.cs b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Capture.cs index 5268a03c6..918c9f49a 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Capture.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Capture.cs @@ -9,9 +9,13 @@ internal static partial class BinarySerializationFormat private static byte[]? TryGetEncodedCapture(ObjectSerializationNode node) { if (node.encodedCapture is { } encoded) + { return encoded; + } if (node.captureKey is null || node.encodingTooLarge) + { return null; + } int length; try { diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Sizing.cs b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Sizing.cs index 668d72703..e0806546d 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Sizing.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.Sizing.cs @@ -11,7 +11,9 @@ internal static partial class BinarySerializationFormat private static int GetEncodedSize(SerializationNode node) { if (node is ObjectSerializationNode { encodedCapture: { } encoded }) + { return encoded.Length; + } int payload = node switch { NullSerializationNode => 0, @@ -25,7 +27,8 @@ private static int GetEncodedSize(SerializationNode node) return checked(sizeof(byte) + payload); } - private static int GetScalarSize(object value) => value switch + private static int GetScalarSize(object value) + => value switch { bool or byte or sbyte => 1, short or ushort => 2, @@ -47,7 +50,9 @@ private static int GetObjectSize(ObjectSerializationNode node) { int size = sizeof(int); foreach (KeyValuePair member in node.values) + { size = checked(size + GetEncodedStringSize(member.Key) + GetEncodedSize(member.Value)); + } return size; } @@ -55,7 +60,9 @@ private static int GetArraySize(ArraySerializationNode node) { int size = sizeof(int); foreach (SerializationNode value in node.values) + { size = checked(size + GetEncodedSize(value)); + } return size; } @@ -63,7 +70,9 @@ private static int GetMapSize(MapSerializationNode node) { int size = sizeof(int); foreach (KeyValuePair entry in node.values) + { size = checked(size + GetEncodedSize(entry.Key) + GetEncodedSize(entry.Value)); + } return size; } } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs index be6a56795..efbadee51 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs @@ -10,8 +10,7 @@ internal static partial class BinarySerializationFormat private const string C_MAGIC = "INNO-BINARY-CURRENT"; private const int C_MAX_COLLECTION_COUNT = 16_777_216; - internal static byte[] Encode(SerializationNode root) - => Encode(root, includeMagic: true); + internal static byte[] Encode(SerializationNode root) => Encode(root, includeMagic: true); internal static void WriteTo( Stream destination, @@ -31,11 +30,15 @@ internal static SerializationNode Decode(ReadOnlySpan bytes) using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); string magic = reader.ReadString(); if (!string.Equals(magic, C_MAGIC, StringComparison.Ordinal)) + { throw new InvalidDataException($"Invalid serialization magic '{magic}'."); + } SerializationNode root = ReadNode(reader, "$"); if (stream.Position != stream.Length) + { throw new InvalidDataException("Serialization payload at '$' contains trailing data."); + } return root; } catch (InvalidDataException) @@ -86,7 +89,9 @@ private static void WriteNode( writer.Write((byte)NodeKind.Array); writer.Write(array.values.Count); for (int i = 0; i < array.values.Count; i++) + { WriteNode(writer, array.values[i]); + } return; case MapSerializationNode map: writer.Write((byte)NodeKind.Map); @@ -178,7 +183,9 @@ string path string name = reader.ReadString(); string memberPath = AppendPath(path, name); if (!node.values.TryAdd(name, ReadNode(reader, memberPath))) + { throw new InvalidDataException($"Serialization object at '{path}' contains duplicate key '{name}'."); + } } return node; } @@ -191,7 +198,9 @@ string path var node = new ArraySerializationNode(); node.values.Capacity = count; for (int i = 0; i < count; i++) + { node.values.Add(ReadNode(reader, $"{path}[{i}]")); + } return node; } @@ -204,9 +213,12 @@ string path node.values.Capacity = count; for (int i = 0; i < count; i++) { - node.values.Add(new KeyValuePair( - ReadNode(reader, $"{path}[{i}].key"), - ReadNode(reader, $"{path}[{i}].value"))); + node.values.Add( + new KeyValuePair( + ReadNode(reader, $"{path}[{i}].key"), + ReadNode(reader, $"{path}[{i}].value") + ) + ); } return node; } @@ -218,7 +230,9 @@ string path int count = ReadCount(reader, "binary byte", path); byte[] bytes = reader.ReadBytes(count); if (bytes.Length != count) + { throw new InvalidDataException($"Serialization binary value at '{path}' is truncated."); + } return bytes; } @@ -228,7 +242,9 @@ string path ) { byte[] bytes = reader.ReadBytes(16); if (bytes.Length != 16) + { throw new InvalidDataException($"Serialization Guid value at '{path}' is truncated."); + } return new Guid(bytes); } @@ -239,7 +255,9 @@ string path ) { int count = reader.ReadInt32(); if (count < 0 || count > C_MAX_COLLECTION_COUNT) + { throw new InvalidDataException($"Invalid serialization {kind} count {count} at '{path}'."); + } return count; } @@ -248,8 +266,7 @@ private static string AppendPath( string name ) => path == "$" ? $"$.{name}" : $"{path}.{name}"; - private static byte[] EncodeNode(SerializationNode node) - => Encode(node, includeMagic: false); + private static byte[] EncodeNode(SerializationNode node) => Encode(node, includeMagic: false); private static byte[] Encode( SerializationNode node, @@ -261,11 +278,15 @@ private static byte[] Encode( using var stream = new MemoryStream(data, writable: true); using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); if (includeMagic) + { writer.Write(C_MAGIC); + } WriteNode(writer, node, useObjectCache); writer.Flush(); if (stream.Position != length) + { throw new InvalidDataException("The serialization encoder did not fill its calculated output size."); + } return data; } @@ -278,7 +299,9 @@ byte[] right { int comparison = left[i].CompareTo(right[i]); if (comparison != 0) + { return comparison; + } } return left.Length.CompareTo(right.Length); } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs index 1a8346ca3..5cdd63e5b 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs @@ -5,9 +5,8 @@ using System.Linq; using System.Reflection; using System.Threading; - -using Inno.Extensibility.Types; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; namespace Inno.Core.Serialization; @@ -31,7 +30,9 @@ internal ConverterRegistry(TypeCatalog types) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_registry.Dispose(); } @@ -52,11 +53,15 @@ Type valueType for (int i = 0; i < snapshot.registrations.Count; i++) { if (TryCreateCandidate(snapshot, snapshot.registrations[i], valueType, out ConverterCandidate? candidate)) + { candidates.Add(candidate!); + } } if (candidates.Count == 0) + { return null; + } int bestDistance = candidates.Min(static candidate => candidate.distance); ConverterCandidate[] best = candidates @@ -66,8 +71,9 @@ Type valueType if (best.Length > 1) { throw new InvalidOperationException( - $"Serialization type '{valueType.FullName}' has ambiguous converters " + - $"'{best[0].converterType.FullName}' and '{best[1].converterType.FullName}' at distance {bestDistance}."); + $"Serialization type '{valueType.FullName}' has ambiguous converters " + + $"'{best[0].converterType.FullName}' and '{best[1].converterType.FullName}' at distance {bestDistance}." + ); } return best[0].invoker; @@ -81,45 +87,57 @@ out ConverterCandidate? candidate ) { candidate = null; if (!TryGetConverterTargetPattern(registeredType, out Type targetPattern)) + { throw new InvalidOperationException( - $"Serialization extension '{registeredType.FullName}' must inherit SerializationConverter."); + $"Serialization extension '{registeredType.FullName}' must inherit SerializationConverter." + ); + } Type closedConverterType = registeredType; if (registeredType.ContainsGenericParameters) { if (!registeredType.IsGenericTypeDefinition) + { return false; + } var bindings = new Dictionary(); if (!TryUnify(targetPattern, valueType, bindings)) + { return false; + } Type[] parameters = registeredType.GetGenericArguments(); var arguments = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { if (!bindings.TryGetValue(parameters[i], out Type? argument)) + { return false; + } arguments[i] = argument; } Type? construction = snapshot.ConstructGenericType(registeredType, arguments); if (construction is null) + { return false; + } closedConverterType = construction; } if (!TryGetConverterTargetPattern(closedConverterType, out Type targetType) || targetType.ContainsGenericParameters) + { return false; + } if (!targetType.IsAssignableFrom(valueType)) + { return false; + } var converter = (SerializationConverter)GetOrCreateConverter(snapshot, closedConverterType); ConverterInvoker invoker = converter.CreateInvoker(); - candidate = new ConverterCandidate( - closedConverterType, - GetTypeDistance(valueType, targetType), - invoker); + candidate = new ConverterCandidate(closedConverterType, GetTypeDistance(valueType, targetType), invoker); return true; } @@ -128,7 +146,9 @@ private static object GetOrCreateConverter( Type converterType ) { if (snapshot.converterInstances.TryGetValue(converterType, out object? converter)) + { return converter; + } try { @@ -138,7 +158,8 @@ Type converterType { throw new InvalidOperationException( $"Serialization converter '{converterType.FullName}' must have a parameterless constructor.", - exception); + exception + ); } snapshot.converterInstances.Add(converterType, converter); @@ -152,7 +173,9 @@ out Type targetPattern for (Type? current = converterType; current is not null; current = current.BaseType) { if (!current.IsGenericType || current.GetGenericTypeDefinition() != typeof(SerializationConverter<>)) + { continue; + } targetPattern = current.GetGenericArguments()[0]; return true; @@ -170,29 +193,37 @@ Dictionary bindings if (pattern.IsGenericParameter) { if (bindings.TryGetValue(pattern, out Type? existing)) + { return existing == concrete; + } bindings.Add(pattern, concrete); return true; } if (pattern.IsArray) { - return concrete.IsArray && - pattern.GetArrayRank() == concrete.GetArrayRank() && - TryUnify(pattern.GetElementType()!, concrete.GetElementType()!, bindings); + return concrete.IsArray + && pattern.GetArrayRank() == concrete.GetArrayRank() + && TryUnify(pattern.GetElementType()!, concrete.GetElementType()!, bindings); } if (!pattern.IsGenericType) + { return pattern == concrete; + } if (!concrete.IsGenericType || pattern.GetGenericTypeDefinition() != concrete.GetGenericTypeDefinition()) + { return false; + } Type[] patternArguments = pattern.GetGenericArguments(); Type[] concreteArguments = concrete.GetGenericArguments(); for (int i = 0; i < patternArguments.Length; i++) { if (!TryUnify(patternArguments[i], concreteArguments[i], bindings)) + { return false; + } } return true; @@ -203,17 +234,23 @@ private static int GetTypeDistance( Type targetType ) { if (derivedType == targetType) + { return 0; + } // Assignability was validated by the caller. Implemented interfaces share one rank, // including variant constructions; class inheritance retains its exact depth. if (targetType.IsInterface) + { return 1; + } int distance = 1; for (Type? current = derivedType.BaseType; current is not null; current = current.BaseType) { if (current == targetType) + { return distance; + } distance++; } @@ -229,9 +266,7 @@ ConverterInvoker invoker private sealed class ConverterTypeRegistry : TypeRegistry { internal ConverterTypeRegistry(TypeCatalog types) - : base(types) - { - } + : base(types) {} internal ConverterRegistryLease Capture() { @@ -239,7 +274,9 @@ internal ConverterRegistryLease Capture() { ConverterRegistrySnapshot snapshot = current; if (snapshot.TryAcquire()) + { return new ConverterRegistryLease(snapshot); + } } } @@ -264,7 +301,8 @@ protected override ConverterRegistrySnapshot Build(TypeCacheSnapshot types) if (!TryGetConverterTargetPattern(registrations[i], out _)) { throw new InvalidOperationException( - $"Serialization extension '{registrations[i].FullName}' must inherit SerializationConverter."); + $"Serialization extension '{registrations[i].FullName}' must inherit SerializationConverter." + ); } } @@ -282,14 +320,13 @@ protected override ConverterRegistrySnapshot Build(TypeCacheSnapshot types) private ConverterTypeRegistry RequireRegistry() => !m_disposed - ? m_registry - : throw new ObjectDisposedException(nameof(ConverterRegistry)); + ? m_registry + : throw new ObjectDisposedException(nameof(ConverterRegistry)); internal sealed class ConverterRegistrySnapshot( IReadOnlyList registrations, TypeCacheSnapshot types - ) - { + ) { private TypeCacheSnapshot? m_types = types; internal readonly Guid captureIdentity = Guid.NewGuid(); internal readonly Lock sync = new(); @@ -314,7 +351,9 @@ internal bool TryAcquire() lock (sync) { if (m_referenceCount == 0) + { return false; + } m_referenceCount++; return true; } @@ -326,12 +365,16 @@ internal void Release() lock (sync) { if (m_referenceCount <= 0) + { throw new InvalidOperationException("The serialization converter generation was released twice."); + } m_referenceCount--; dispose = m_referenceCount == 0; } if (!dispose) + { return; + } foreach (object converter in converterInstances.Values.Distinct(ReferenceEqualityComparer.Instance)) { @@ -346,7 +389,8 @@ internal void Release() Trace.TraceError( "Serialization converter '{0}' failed while being disposed: {1}", converter.GetType().FullName, - exception); + exception + ); } } } @@ -385,21 +429,29 @@ ISerializationMetadataSource source plans = Interlocked.CompareExchange(ref m_revisionPlans, created, null) ?? created; } if (plans.TryGetValue(metadata, out var known) && ReferenceEquals(known.source, source)) + { return known.eligible; + } bool eligible = !metadata.requiresConverter; foreach (SerializationMemberMetadata member in metadata.members) { if (!eligible) + { break; + } if ((member.visibility & PropertyVisibility.Serialize) == 0) + { continue; + } if (!IsKnownDefault(member.type)) { eligible = false; break; } if (ValuePipeline.IsPrimitive(member.type) || member.type.IsEnum) + { continue; + } SerializationTypeMetadata nested = source.GetMetadata(member.type); if (!nested.hasPureFieldAccess) { @@ -407,33 +459,44 @@ ISerializationMetadataSource source break; } foreach (SerializationMemberMetadata field in nested.members) + { if ((field.visibility & PropertyVisibility.Serialize) != 0 && !IsKnownDefault(field.type)) { eligible = false; break; } + } } // An unresolved fact can become known through an ordinary write in this same operation. // Cache only positive proofs; a key query still never invokes the resolver itself. if (eligible) + { plans[metadata] = (source, true); + } return eligible; } + internal ConverterInvoker? Resolve(Type valueType) { ArgumentNullException.ThrowIfNull(valueType); ConverterRegistry.ConverterRegistrySnapshot snapshot = m_snapshot - ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); + ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); Type normalizedType = Nullable.GetUnderlyingType(valueType) ?? valueType; if (snapshot.cache.TryGetValue(normalizedType, out ConverterInvoker? cached)) + { return cached; + } lock (snapshot.sync) { if (snapshot.cache.TryGetValue(normalizedType, out cached)) + { return cached; + } ConverterInvoker? resolved = ConverterRegistry.ResolveSnapshot(snapshot, normalizedType); if (!snapshot.cache.TryAdd(normalizedType, resolved)) + { throw new InvalidOperationException("The serialization converter resolution was published twice."); + } return resolved; } } @@ -451,7 +514,7 @@ public void Dispose() private bool IsKnownDefault(Type type) { ConverterRegistry.ConverterRegistrySnapshot snapshot = m_snapshot - ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); + ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); Type normalized = Nullable.GetUnderlyingType(type) ?? type; // Reuse only facts established by the authoritative resolver. A key query must not // construct converters, change their execution order, or introduce another resolver. @@ -513,8 +576,7 @@ internal sealed class ConverterInvoker : ConverterInvoker internal ConverterInvoker( SerializationConverter converter, Type converterType - ) - : base(typeof(T), converterType) + ) : base(typeof(T), converterType) { m_converter = converter; } @@ -529,16 +591,25 @@ internal override SerializationNode Write( if (value is not T typed) { throw new InvalidOperationException( - $"Converter '{converterType.FullName}' cannot write runtime value '{value.GetType().FullName}' at '{path}'."); + $"Converter '{converterType.FullName}' cannot write runtime value '{value.GetType().FullName}' at '{path}'." + ); } ObjectSerializationNode? prior = previous as ObjectSerializationNode; operation.RecordConverterWrite(); long converterWrites = operation.converterWrites; - SerializationCaptureAttempt attempt = SerializationCaptureAttempt.Capture(operation, valueType, typed, prior?.captureKey, m_converter); + SerializationCaptureAttempt attempt = SerializationCaptureAttempt.Capture( + operation, + valueType, + typed, + prior?.captureKey, + m_converter + ); SerializationCaptureKey? key = attempt.key; if (key is not null && ReferenceEquals(key, prior?.captureKey)) + { return prior!; + } var writer = new SerializationWriter(operation, prior, path, valueType); m_converter.Write(writer, typed); ObjectSerializationNode result = writer.Complete(); @@ -547,7 +618,9 @@ internal override SerializationNode Write( attempt.ValidateIdentities(); key = attempt.Verify(SerializationCaptureAttempt.Capture(operation, valueType, typed, key, m_converter)); if (operation.converterWrites != converterWrites) + { key = null; + } } return SerializationNodeReuse.WithCaptureKey(result, prior, key); } @@ -560,14 +633,19 @@ ObjectSerializationNode node ) { T result = m_converter.Read(new SerializationReader(operation, node, path, valueType)); if (result is null) + { throw new InvalidOperationException($"Converter '{converterType.FullName}' returned null at '{path}'."); + } if (!valueType.IsInstanceOfType(result)) { throw new InvalidOperationException( - $"Converter '{converterType.FullName}' returned '{result.GetType().FullName}', which is incompatible with '{valueType.FullName}' at '{path}'."); + $"Converter '{converterType.FullName}' returned '{result.GetType().FullName}', which is incompatible with '{valueType.FullName}' at '{path}'." + ); } if (result is ISerializable serializable) + { operation.ScheduleRestoredObject(serializable); + } return result; } @@ -581,11 +659,14 @@ object target if (target is not T typed) { throw new InvalidOperationException( - $"Converter '{converterType.FullName}' cannot restore target '{target.GetType().FullName}' at '{path}'."); + $"Converter '{converterType.FullName}' cannot restore target '{target.GetType().FullName}' at '{path}'." + ); } m_converter.Restore(new SerializationReader(operation, node, path, valueType), typed); if (target is ISerializable serializable) + { operation.ScheduleRestoredObject(serializable); + } } } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs index e35ad6fa5..54eaf3047 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs @@ -49,24 +49,34 @@ internal static IReadOnlyList Decode(ReadOnlySpan using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); string magic = reader.ReadString(); if (!string.Equals(magic, C_MAGIC, StringComparison.Ordinal)) + { throw new InvalidDataException($"Invalid property snapshot magic '{magic}'."); + } int count = reader.ReadInt32(); if (count < 0) + { throw new InvalidDataException("Property snapshot count cannot be negative."); + } var snapshots = new SerializationPropertySnapshot[count]; for (int i = 0; i < count; i++) { string name = reader.ReadString(); int length = reader.ReadInt32(); if (length < 0 || length > stream.Length - stream.Position) + { throw new InvalidDataException($"Property snapshot '{name}' length is invalid."); + } byte[] data = reader.ReadBytes(length); if (data.Length != length) + { throw new EndOfStreamException($"Property snapshot '{name}' is truncated."); + } snapshots[i] = new SerializationPropertySnapshot(name, typeof(object), data); } if (stream.Position != stream.Length) + { throw new InvalidDataException("Property snapshot data contains trailing bytes."); + } return snapshots; } } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs index 93572b9cb..c4bacda6a 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs @@ -11,7 +11,9 @@ internal static BinarySerializationNode CaptureData( ConverterRegistryLease converters, BinarySerializationNode? previous ) { - IReadOnlyList members = context.GetRequired().GetMetadata(value.GetType()).members; + IReadOnlyList members = context + .GetRequired() + .GetMetadata(value.GetType()).members; KeyValuePair[]? before = previous?.properties?.members; List>? captured = before is null ? [] : null; int count = 0; @@ -22,13 +24,21 @@ internal static BinarySerializationNode CaptureData( { SerializationMemberMetadata member = members[index]; if ((member.visibility & PropertyVisibility.Serialize) == 0) + { continue; - SerializationNode? prior = before is not null && count < before.Length && - string.Equals(before[count].Key, member.name, StringComparison.Ordinal) - ? before[count].Value - : null; - SerializationNode node = ValuePipeline.Write(member.GetValue(value), member.type, operation, - prior?.capturePath ?? AppendPath(member.name), allowDefaultObject: false, prior); + } + SerializationNode? prior = before is not null && count < before.Length + && string.Equals(before[count].Key, member.name, StringComparison.Ordinal) + ? before[count].Value + : null; + SerializationNode node = ValuePipeline.Write( + member.GetValue(value), + member.type, + operation, + prior?.capturePath ?? AppendPath(member.name), + allowDefaultObject: false, + prior + ); operation.RetireCaptureMember(); if (captured is null && !ReferenceEquals(node, prior)) { @@ -44,11 +54,14 @@ internal static BinarySerializationNode CaptureData( operation.Fail(); } if (captured is null && before is not null && count == before.Length) - return previous!.properties!.hasConverters == (operation.converterWrites != 0) ? previous - : new BinarySerializationNode(previous.value) - { - properties = new(before) { hasConverters = operation.converterWrites != 0 } - }; + { + return previous!.properties!.hasConverters == (operation.converterWrites != 0) + ? previous + : new BinarySerializationNode(previous.value) + { + properties = new(before) { hasConverters = operation.converterWrites != 0 } + }; + } if (captured is null) { captured = new(before!); @@ -65,17 +78,22 @@ internal static SerializationPropertySnapshot CaptureProperty( ConverterRegistryLease converters ) { ArgumentException.ThrowIfNullOrWhiteSpace(propertyName); - IReadOnlyList members = context.GetRequired().GetMetadata(value.GetType()).members; + IReadOnlyList members = context + .GetRequired() + .GetMetadata(value.GetType()).members; for (int index = 0; index < members.Count; index++) { SerializationMemberMetadata member = members[index]; - if ((member.visibility & PropertyVisibility.Serialize) != 0 && - string.Equals(member.name, propertyName, StringComparison.Ordinal)) + if ((member.visibility & PropertyVisibility.Serialize) != 0 + && string.Equals(member.name, propertyName, StringComparison.Ordinal) + ) { return CaptureMember(value, member, context, converters); + } } throw new ArgumentException( $"Serializable property '{propertyName}' was not found on '{value.GetType().FullName}'.", - nameof(propertyName)); + nameof(propertyName) + ); } internal static IReadOnlyList Capture( @@ -83,13 +101,17 @@ internal static IReadOnlyList Capture( SerializationContext context, ConverterRegistryLease converters ) { - IReadOnlyList members = context.GetRequired().GetMetadata(value.GetType()).members; + IReadOnlyList members = context + .GetRequired() + .GetMetadata(value.GetType()).members; var snapshots = new List(members.Count); for (int i = 0; i < members.Count; i++) { SerializationMemberMetadata member = members[i]; if ((member.visibility & PropertyVisibility.Serialize) == 0) + { continue; + } snapshots.Add(CaptureMember(value, member, context, converters)); } @@ -103,13 +125,17 @@ internal static SerializationPropertyRestoreResult Restore( SerializationContext context, ConverterRegistryLease converters ) { - IReadOnlyList members = context.GetRequired().GetMetadata(target.GetType()).members; + IReadOnlyList members = context + .GetRequired() + .GetMetadata(target.GetType()).members; var membersByName = new Dictionary(members.Count, StringComparer.Ordinal); for (int i = 0; i < members.Count; i++) { SerializationMemberMetadata member = members[i]; if ((member.visibility & PropertyVisibility.Deserialize) != 0) + { membersByName.Add(member.name, member); + } } ValidateSnapshots(snapshots); @@ -137,20 +163,24 @@ ConverterRegistryLease converters member.type, operation, AppendPath(member.name), - allowDefaultObject: false); + allowDefaultObject: false + ); member.SetValue(target, value); restoredCount++; } catch (Exception exception) when ( - mode == SerializationPropertyRestoreMode.CollectFailures && - IsRecoverable(exception)) + mode == SerializationPropertyRestoreMode.CollectFailures + && IsRecoverable(exception)) { operation.Rollback(checkpoint); - failures.Add(new SerializationPropertyRestoreFailure( - member.name, - snapshot.propertyType, - member.type, - Unwrap(exception).Message)); + failures.Add( + new SerializationPropertyRestoreFailure( + member.name, + snapshot.propertyType, + member.type, + Unwrap(exception).Message + ) + ); } } @@ -176,7 +206,8 @@ private static void ValidateSnapshots(IReadOnlyList exception is not OutOfMemoryException and - not StackOverflowException and - not AccessViolationException and - not OperationCanceledException; + => exception is not OutOfMemoryException + and not StackOverflowException + and not AccessViolationException + and not OperationCanceledException; private static Exception Unwrap(Exception exception) => exception is System.Reflection.TargetInvocationException { InnerException: not null } invocation - ? invocation.InnerException! - : exception; + ? invocation.InnerException! + : exception; private static string AppendPath(string name) => "$." + name; } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationArrayCapture.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationArrayCapture.cs index 327c1118a..42037ef70 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationArrayCapture.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationArrayCapture.cs @@ -8,24 +8,33 @@ internal struct SerializationArrayCapture(ArraySerializationNode? previous) private List? m_values; private int m_count; - internal SerializationNode? Next => previous is not null && m_count < previous.values.Count - ? previous.values[m_count] - : null; + internal SerializationNode? Next + => previous is not null && m_count < previous.values.Count + ? previous.values[m_count] + : null; internal ArraySerializationNode? initialNode => m_initialNode; internal void Add(SerializationNode value) { if (m_initialNode is not null) + { m_values = m_initialNode.values; + } if (m_values is null && !ReferenceEquals(Next, value)) + { m_values = previous is null ? [] : new(previous.values); + } if (m_values is not null) { if (m_count < m_values.Count) + { m_values[m_count] = value; + } else + { m_values.Add(value); + } } m_count++; } @@ -33,12 +42,18 @@ internal void Add(SerializationNode value) internal ArraySerializationNode Complete() { if (m_initialNode is not null) + { return m_initialNode; + } if (previous is not null && m_count == previous.values.Count && m_values is null) + { return previous; + } m_values ??= previous is null ? [] : new(previous.values); if (m_values.Count > m_count) + { m_values.RemoveRange(m_count, m_values.Count - m_count); + } return new ArraySerializationNode(m_values); } } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs index 236ccaa0f..bec1016a3 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs @@ -13,7 +13,9 @@ internal abstract record SerializationNode internal void RememberPath(string path) { if (this is not NullSerializationNode) + { Interlocked.CompareExchange(ref m_capturePath, path, null); + } } } @@ -21,9 +23,7 @@ internal sealed record NullSerializationNode : SerializationNode { internal static NullSerializationNode instance { get; } = new(); - private NullSerializationNode() - { - } + private NullSerializationNode() {} } internal sealed record ScalarSerializationNode(object value) : SerializationNode; @@ -44,12 +44,14 @@ internal sealed record ObjectSerializationNode : SerializationNode internal bool encodingTooLarge => Volatile.Read(ref m_encodingTooLarge) != 0; internal byte[] PublishEncodedCapture(byte[] data) => Interlocked.CompareExchange(ref m_encodedCapture, data, null) ?? data; + internal void RejectEncodedCapture() => Volatile.Write(ref m_encodingTooLarge, 1); } internal sealed record ArraySerializationNode : SerializationNode { - internal ArraySerializationNode() : this([]) { } + internal ArraySerializationNode() + : this([]) {} internal ArraySerializationNode(List values) => this.values = values; diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs index 098fdd46d..fc2f16f45 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs @@ -14,7 +14,9 @@ internal static ObjectSerializationNode WithCaptureKey( if (!ReferenceEquals(result.captureKey, key)) { if (ReferenceEquals(result, previous)) + { result = CopyObject(result); + } result.captureKey = key; } return result; @@ -25,11 +27,17 @@ internal static bool SameScalar( object previous ) { if (typeof(T) == typeof(float)) + { return BitConverter.SingleToInt32Bits(Unsafe.As(ref value)) == BitConverter.SingleToInt32Bits((float)previous); + } if (typeof(T) == typeof(double)) + { return BitConverter.DoubleToInt64Bits(Unsafe.As(ref value)) == BitConverter.DoubleToInt64Bits((double)previous); + } if (typeof(T) == typeof(decimal)) + { return SameScalar((object)Unsafe.As(ref value), previous); + } return EqualityComparer.Default.Equals(value, (T)previous); } @@ -38,7 +46,9 @@ internal static ObjectSerializationNode CopyObject(ObjectSerializationNode previ var result = new ObjectSerializationNode(); result.values.EnsureCapacity(previous.values.Count); foreach (var pair in previous.values) + { result.values.Add(pair.Key, pair.Value); + } return result; } @@ -46,26 +56,32 @@ internal static SerializationNode Scalar( object value, SerializationNode? previous ) => previous is ScalarSerializationNode scalar && SameScalar(value, scalar.value) - ? scalar - : new ScalarSerializationNode(value); + ? scalar + : new ScalarSerializationNode(value); internal static SerializationNode Binary( byte[] value, SerializationNode? previous ) => previous is BinarySerializationNode binary && value.AsSpan().SequenceEqual(binary.value) - ? binary - : new BinarySerializationNode((byte[])value.Clone()); + ? binary + : new BinarySerializationNode((byte[])value.Clone()); internal static bool SameScalar( object value, object previous ) { if (value.GetType() != previous.GetType()) + { return false; + } if (value is float number) + { return BitConverter.SingleToInt32Bits(number) == BitConverter.SingleToInt32Bits((float)previous); + } if (value is double real) + { return BitConverter.DoubleToInt64Bits(real) == BitConverter.DoubleToInt64Bits((double)previous); + } if (value is decimal precision) { Span left = stackalloc int[4]; diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs index 83fbdfc1e..b7e0c019c 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs @@ -55,7 +55,9 @@ internal SerializationTypeMetadata GetMetadata(Type type) internal void EnsureActive() { if (!m_isActive) + { throw new InvalidOperationException("The serialization reader or writer is no longer active."); + } } internal void RecordConverterWrite() => m_converterWrites = checked(m_converterWrites + 1); @@ -68,7 +70,9 @@ internal BinarySerializationNode CapturePropertyData( EnsureActive(); BinarySerializationNode captured = PropertySnapshotPipeline.CaptureData(value, context, m_converters, previous); if (captured.properties?.hasConverters == true) + { RecordConverterWrite(); + } return captured; } @@ -83,12 +87,16 @@ internal void ScheduleRestoredObject(ISerializable value) { EnsureActive(); if (!(m_scheduledObjects ??= new(ReferenceEqualityComparer.Instance)).Add(value)) + { return; + } (m_scheduledObjectOrder ??= []).Add(value); Action? callback = GetMetadata(value.GetType()).restored; if (callback is not null) + { (m_completionCallbacks ??= []).Add(() => callback(value, context)); + } } internal void EnterCapture( @@ -100,7 +108,8 @@ string path if (captures.TryGetValue(value, out string? existingPath)) { throw new InvalidOperationException( - $"Serialization cycle detected at '{path}'. The same object is already being written at '{existingPath}'."); + $"Serialization cycle detected at '{path}'. The same object is already being written at '{existingPath}'." + ); } captures.Add(value, path); @@ -115,16 +124,18 @@ internal Checkpoint CreateCheckpoint() internal void Rollback(Checkpoint checkpoint) { EnsureActive(); - if (checkpoint.callbackCount < 0 || - checkpoint.callbackCount > (m_completionCallbacks?.Count ?? 0) || - checkpoint.scheduledObjectCount < 0 || - checkpoint.scheduledObjectCount > (m_scheduledObjectOrder?.Count ?? 0)) - { + if (checkpoint.callbackCount < 0 + || checkpoint.callbackCount > (m_completionCallbacks?.Count ?? 0) + || checkpoint.scheduledObjectCount < 0 + || checkpoint.scheduledObjectCount > (m_scheduledObjectOrder?.Count ?? 0) + ) { throw new InvalidOperationException("The serialization operation checkpoint is invalid."); } if (m_completionCallbacks is { } callbacks && callbacks.Count > checkpoint.callbackCount) + { callbacks.RemoveRange(checkpoint.callbackCount, callbacks.Count - checkpoint.callbackCount); + } if (m_scheduledObjectOrder is { } order) { for (int i = order.Count - 1; i >= checkpoint.scheduledObjectCount; i--) @@ -138,7 +149,9 @@ internal void Rollback(Checkpoint checkpoint) internal void ExitCapture(object value) { if (m_isActive) + { m_capturePaths?.Remove(value); + } } internal void Complete() @@ -147,8 +160,12 @@ internal void Complete() try { if (m_completionCallbacks is { } callbacks) + { for (int i = 0; i < callbacks.Count; i++) + { callbacks[i](); + } + } } finally { @@ -163,7 +180,9 @@ internal void Complete() internal void Fail() { if (!m_isActive) + { return; + } m_isActive = false; m_completionCallbacks?.Clear(); @@ -176,5 +195,4 @@ internal readonly record struct Checkpoint( int callbackCount, int scheduledObjectCount ); - } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ValuePipeline.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ValuePipeline.cs index 321ff7368..4625241cb 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/ValuePipeline.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ValuePipeline.cs @@ -18,15 +18,21 @@ internal static SerializationNode WriteRoot( { ConverterInvoker? converter = operation.ResolveConverter(declaredType); if (converter is not null) + { return converter.Write(operation, "$", declaredType, value, previous); + } if (operation.GetMetadata(declaredType).requiresConverter) + { throw new InvalidOperationException( - $"Serializable type '{declaredType.FullName}' requires an explicit serialization converter."); + $"Serializable type '{declaredType.FullName}' requires an explicit serialization converter." + ); + } if (value.GetType() != declaredType) { throw new InvalidOperationException( - $"Default root serialization requires exact type '{declaredType.FullName}', but the runtime value is '{value.GetType().FullName}'. Mark the root type with RequiresSerializationConverter and register a converter for polymorphism."); + $"Default root serialization requires exact type '{declaredType.FullName}', but the runtime value is '{value.GetType().FullName}'. Mark the root type with RequiresSerializationConverter and register a converter for polymorphism." + ); } EnsureDefaultSerializableType(declaredType, operation); var writer = new SerializationWriter(operation, previous as ObjectSerializationNode, "$", declaredType); @@ -46,10 +52,15 @@ SerializationOperation operation ) { ConverterInvoker? converter = operation.ResolveConverter(declaredType); if (converter is not null) + { return converter.Read(operation, "$", declaredType, RequireObject(node, declaredType, "$")); + } if (operation.GetMetadata(declaredType).requiresConverter) + { throw new InvalidOperationException( - $"Serializable type '{declaredType.FullName}' requires an explicit serialization converter."); + $"Serializable type '{declaredType.FullName}' requires an explicit serialization converter." + ); + } EnsureDefaultSerializableType(declaredType, operation); ISerializable instance = CreateSerializable(declaredType, operation); @@ -70,8 +81,11 @@ SerializationOperation operation return; } if (operation.GetMetadata(targetType).requiresConverter) + { throw new InvalidOperationException( - $"Serializable type '{targetType.FullName}' requires an explicit serialization converter."); + $"Serializable type '{targetType.FullName}' requires an explicit serialization converter." + ); + } EnsureDefaultSerializableType(targetType, operation); RestoreProperties(target, RequireObject(node, targetType, "$"), operation, "$" ); @@ -86,10 +100,12 @@ internal static SerializationNode Write( SerializationNode? previous = null ) { operation.EnsureActive(); - if (previous is ScalarSerializationNode scalar && value is not null && - scalar.value.GetType() == declaredType && value.GetType() == declaredType && - operation.ResolveConverter(declaredType) is null && SerializationNodeReuse.SameScalar(value, scalar.value)) + if (previous is ScalarSerializationNode scalar && value is not null + && scalar.value.GetType() == declaredType && value.GetType() == declaredType + && operation.ResolveConverter(declaredType) is null && SerializationNodeReuse.SameScalar(value, scalar.value) + ) { return scalar; + } SerializationNode node = WriteValue(value, declaredType, operation, path, allowDefaultObject, previous); node.RememberPath(path); return node; @@ -109,40 +125,61 @@ private static SerializationNode WriteValue( if (value is null) { if (valueType.IsValueType && nullableType is null) + { throw new InvalidOperationException($"Non-nullable value '{path}' of type '{valueType.FullName}' cannot be null."); + } return NullSerializationNode.instance; } bool trackReference = !value.GetType().IsValueType && value is not string && value is not byte[]; if (trackReference) + { operation.EnterCapture(value, path); + } try { ConverterInvoker? converter = operation.ResolveConverter(valueType); if (converter is not null) + { return converter.Write(operation, path, valueType, value, previous); + } if (IsPrimitive(valueType)) + { return SerializationNodeReuse.Scalar(NormalizePrimitive(value, valueType, path), previous); + } if (valueType.IsEnum) + { return SerializationNodeReuse.Scalar(Convert.ToInt64(value, CultureInfo.InvariantCulture), previous); + } if (valueType == typeof(byte[])) + { return SerializationNodeReuse.Binary((byte[])value, previous); + } if (valueType.IsArray) + { return WriteArray((Array)value, valueType, operation, path, previous as ArraySerializationNode); + } if (operation.GetMetadata(valueType).collection is { keyType: not null } map) + { return WriteMap(value, valueType, map.keyType, map.elementType, operation, path, previous); + } if (operation.GetMetadata(valueType).collection is { keyType: null } sequence) + { return WriteSequence(value, sequence.elementType, operation, path, previous as ArraySerializationNode); + } if (valueType.IsValueType) + { return WriteStruct(value, valueType, operation, path, previous as ObjectSerializationNode); + } if (allowDefaultObject && value is ISerializable serializable) { if (value.GetType() != valueType) { throw new InvalidOperationException( - $"Default serialization at '{path}' requires exact type '{valueType.FullName}', but the runtime value is '{value.GetType().FullName}'. Register a converter for polymorphic values."); + $"Default serialization at '{path}' requires exact type '{valueType.FullName}', but the runtime value is '{value.GetType().FullName}'. Register a converter for polymorphic values." + ); } EnsureDefaultSerializableType(valueType, operation); var writer = new SerializationWriter(operation, previous as ObjectSerializationNode, path, valueType); @@ -151,12 +188,15 @@ private static SerializationNode WriteValue( } throw new InvalidOperationException( - $"Class value '{path}' of type '{valueType.FullName}' requires an explicit SerializationConverter<{valueType.Name}>."); + $"Class value '{path}' of type '{valueType.FullName}' requires an explicit SerializationConverter<{valueType.Name}>." + ); } finally { if (trackReference) + { operation.ExitCapture(value); + } } } @@ -173,30 +213,48 @@ bool allowDefaultObject if (node is NullSerializationNode) { if (!valueType.IsValueType || nullableType is not null) + { return null; + } throw new InvalidOperationException($"Non-nullable value '{path}' of type '{valueType.FullName}' cannot be null."); } ConverterInvoker? converter = operation.ResolveConverter(valueType); if (converter is not null) + { return converter.Read(operation, path, valueType, RequireObject(node, valueType, path)); + } if (IsPrimitive(valueType)) + { return ReadPrimitive(node, valueType, path); + } if (valueType.IsEnum) + { return Enum.ToObject(valueType, Convert.ToInt64(ReadScalar(node, path), CultureInfo.InvariantCulture)); + } if (valueType == typeof(byte[])) + { return node is BinarySerializationNode binary - ? (byte[])binary.value.Clone() - : throw TypeMismatch(path, "binary", node); + ? (byte[])binary.value.Clone() + : throw TypeMismatch(path, "binary", node); + } if (valueType.IsArray) + { return ReadArray(node, valueType, operation, path); + } if (operation.GetMetadata(valueType).collection is { keyType: not null } map) + { return ReadMap(node, valueType, map.keyType, map.elementType, operation, path); + } if (operation.GetMetadata(valueType).collection is { keyType: null } sequence) + { return ReadSequence(node, valueType, sequence.elementType, operation, path); + } if (valueType.IsValueType) + { return ReadStruct(node, valueType, operation, path); + } if (allowDefaultObject && typeof(ISerializable).IsAssignableFrom(valueType)) { @@ -207,7 +265,8 @@ bool allowDefaultObject } throw new InvalidOperationException( - $"Class value '{path}' of type '{valueType.FullName}' requires an explicit SerializationConverter<{valueType.Name}>."); + $"Class value '{path}' of type '{valueType.FullName}' requires an explicit SerializationConverter<{valueType.Name}>." + ); } internal static void WriteProperties( @@ -220,7 +279,9 @@ SerializationOperation operation { SerializationMemberMetadata member = members[i]; if ((member.visibility & PropertyVisibility.Serialize) == 0) + { continue; + } writer.Write(member.name, member.GetValue(value), member.type); } } @@ -235,15 +296,16 @@ string path for (int i = 0; i < members.Count; i++) { SerializationMemberMetadata member = members[i]; - if ((member.visibility & PropertyVisibility.Deserialize) == 0 || - !node.values.TryGetValue(member.name, out SerializationNode? memberNode)) - { + if ((member.visibility & PropertyVisibility.Deserialize) == 0 + || !node.values.TryGetValue(member.name, out SerializationNode? memberNode) + ) { continue; } member.SetValue( target, - Read(memberNode, member.type, operation, AppendPath(path, member.name), allowDefaultObject: false)); + Read(memberNode, member.type, operation, AppendPath(path, member.name), allowDefaultObject: false) + ); } operation.ScheduleRestoredObject(target); @@ -257,11 +319,15 @@ private static SerializationNode WriteArray( ArraySerializationNode? previous ) { if (arrayType.GetArrayRank() != 1) + { throw new InvalidOperationException($"Only one-dimensional arrays are supported at '{path}'."); + } Type elementType = arrayType.GetElementType()!; var capture = new SerializationArrayCapture(previous); for (int i = 0; i < value.Length; i++) + { capture.Add(Write(value.GetValue(i), elementType, operation, capture.Next?.capturePath ?? $"{path}[{i}]", false, capture.Next)); + } return capture.Complete(); } @@ -272,13 +338,19 @@ private static object ReadArray( string path ) { if (arrayType.GetArrayRank() != 1) + { throw new InvalidOperationException($"Only one-dimensional arrays are supported at '{path}'."); + } if (node is not ArraySerializationNode array) + { throw TypeMismatch(path, "array", node); + } Type elementType = arrayType.GetElementType()!; var values = new object?[array.values.Count]; for (int i = 0; i < values.Length; i++) + { values[i] = Read(array.values[i], elementType, operation, $"{path}[{i}]", false); + } return operation.GetMetadata(arrayType).collection!.buildSequence!(values); } @@ -290,7 +362,9 @@ private static SerializationNode WriteSequence( ArraySerializationNode? previous ) { if (value is not IEnumerable enumerable) + { throw new InvalidOperationException($"Sequence value '{path}' is not enumerable."); + } var capture = new SerializationArrayCapture(previous); int index = 0; foreach (object? element in enumerable) @@ -309,10 +383,14 @@ private static object ReadSequence( string path ) { if (node is not ArraySerializationNode array) + { throw TypeMismatch(path, "array", node); + } var values = new object?[array.values.Count]; for (int i = 0; i < values.Length; i++) + { values[i] = Read(array.values[i], elementType, operation, $"{path}[{i}]", false); + } return operation.GetMetadata(sequenceType).collection!.buildSequence!(values); } @@ -331,15 +409,20 @@ private static SerializationNode WriteMap( { KeyValuePair entry = entries[i]; if (entry.Key is null) + { throw new InvalidOperationException($"Map key '{path}[{i}].key' cannot be null."); - node.values.Add(new KeyValuePair( - Write(entry.Key, keyType, operation, $"{path}[{i}].key", false), - Write(entry.Value, mapValueType, operation, $"{path}[{i}].value", false))); - } - return previous is MapSerializationNode && - BinarySerializationFormat.Encode(node).AsSpan().SequenceEqual(BinarySerializationFormat.Encode(previous)) - ? previous - : node; + } + node.values.Add( + new KeyValuePair( + Write(entry.Key, keyType, operation, $"{path}[{i}].key", false), + Write(entry.Value, mapValueType, operation, $"{path}[{i}].value", false) + ) + ); + } + return previous is MapSerializationNode + && BinarySerializationFormat.Encode(node).AsSpan().SequenceEqual(BinarySerializationFormat.Encode(previous)) + ? previous + : node; } private static object ReadMap( @@ -351,13 +434,16 @@ private static object ReadMap( string path ) { if (node is not MapSerializationNode map) + { throw TypeMismatch(path, "map", node); + } var entries = new KeyValuePair[map.values.Count]; for (int i = 0; i < entries.Length; i++) { entries[i] = new KeyValuePair( Read(map.values[i].Key, keyType, operation, $"{path}[{i}].key", false), - Read(map.values[i].Value, mapValueType, operation, $"{path}[{i}].value", false)); + Read(map.values[i].Value, mapValueType, operation, $"{path}[{i}].value", false) + ); } return operation.GetMetadata(mapType).collection!.buildMap!(entries); } @@ -376,12 +462,20 @@ private static SerializationNode WriteStruct( { SerializationMemberMetadata member = members[i]; if ((member.visibility & PropertyVisibility.Serialize) == 0) + { continue; + } SerializationNode? prior = previous is not null && previous.values.TryGetValue(member.name, out SerializationNode? found) - ? found - : null; - SerializationNode captured = Write(member.GetValue(value), member.type, operation, - prior?.capturePath ?? AppendPath(path, member.name), false, prior); + ? found + : null; + SerializationNode captured = Write( + member.GetValue(value), + member.type, + operation, + prior?.capturePath ?? AppendPath(path, member.name), + false, + prior + ); if (!ReferenceEquals(prior, captured)) { node ??= SerializationNodeReuse.CopyObject(previous!); @@ -396,13 +490,17 @@ private static SerializationNode WriteStruct( { bool included = false; for (int index = 0; index < members.Count; index++) + { if (members[index].name == name && (members[index].visibility & PropertyVisibility.Serialize) != 0) { included = true; break; } + } if (!included) + { node.values.Remove(name); + } } } return node ?? previous!; @@ -420,9 +518,9 @@ string path for (int i = 0; i < members.Count; i++) { SerializationMemberMetadata member = members[i]; - if ((member.visibility & PropertyVisibility.Deserialize) == 0 || - !objectNode.values.TryGetValue(member.name, out SerializationNode? memberNode)) - { + if ((member.visibility & PropertyVisibility.Deserialize) == 0 + || !objectNode.values.TryGetValue(member.name, out SerializationNode? memberNode) + ) { continue; } member.SetValue(result, Read(memberNode, member.type, operation, AppendPath(path, member.name), false)); @@ -440,19 +538,23 @@ private static void EnsureDefaultSerializableType( SerializationOperation operation ) { if (!typeof(ISerializable).IsAssignableFrom(valueType)) + { throw new InvalidOperationException($"Type '{valueType.FullName}' does not implement ISerializable."); + } if (valueType.IsAbstract || valueType.IsInterface || operation.GetMetadata(valueType).requiresConverter) + { throw new InvalidOperationException($"Serializable type '{valueType.FullName}' requires an explicit converter."); + } } private static ObjectSerializationNode RequireObject( SerializationNode node, Type valueType, string path - ) - => node as ObjectSerializationNode - ?? throw new InvalidOperationException( - $"Serialization value '{path}' for '{valueType.FullName}' must be an object, but was '{GetNodeKind(node)}'."); + ) => node as ObjectSerializationNode + ?? throw new InvalidOperationException( + $"Serialization value '{path}' for '{valueType.FullName}' must be an object, but was '{GetNodeKind(node)}'." + ); private static object ReadPrimitive( SerializationNode node, @@ -461,11 +563,17 @@ string path ) { object scalar = ReadScalar(node, path); if (valueType == typeof(string)) + { return scalar is string text ? text : throw TypeMismatch(path, "string", node); + } if (valueType == typeof(Guid)) + { return scalar is Guid guid ? guid : throw TypeMismatch(path, "Guid", node); + } if (scalar.GetType() == valueType) + { return scalar; + } try { return Convert.ChangeType(scalar, valueType, CultureInfo.InvariantCulture)!; @@ -474,17 +582,17 @@ string path { throw new InvalidOperationException( $"Serialization scalar '{path}' cannot be converted from '{scalar.GetType().FullName}' to '{valueType.FullName}'.", - exception); + exception + ); } } private static object ReadScalar( SerializationNode node, string path - ) - => node is ScalarSerializationNode scalar - ? scalar.value - : throw TypeMismatch(path, "scalar", node); + ) => node is ScalarSerializationNode scalar + ? scalar.value + : throw TypeMismatch(path, "scalar", node); private static object NormalizePrimitive( object value, @@ -492,7 +600,9 @@ private static object NormalizePrimitive( string path ) { if (value.GetType() == valueType) + { return value; + } try { return Convert.ChangeType(value, valueType, CultureInfo.InvariantCulture)!; @@ -501,44 +611,44 @@ string path { throw new InvalidOperationException( $"Primitive value '{path}' cannot be converted to '{valueType.FullName}'.", - exception); + exception + ); } } internal static bool IsPrimitive(Type type) - => type == typeof(bool) || - type == typeof(byte) || - type == typeof(sbyte) || - type == typeof(short) || - type == typeof(ushort) || - type == typeof(int) || - type == typeof(uint) || - type == typeof(long) || - type == typeof(ulong) || - type == typeof(float) || - type == typeof(double) || - type == typeof(decimal) || - type == typeof(string) || - type == typeof(Guid); + => type == typeof(bool) + || type == typeof(byte) + || type == typeof(sbyte) + || type == typeof(short) + || type == typeof(ushort) + || type == typeof(int) + || type == typeof(uint) + || type == typeof(long) + || type == typeof(ulong) + || type == typeof(float) + || type == typeof(double) + || type == typeof(decimal) + || type == typeof(string) + || type == typeof(Guid); private static InvalidOperationException TypeMismatch( string path, string expected, SerializationNode actual - ) - => new($"Serialization value '{path}' must be {expected}, but was '{GetNodeKind(actual)}'."); + ) => new($"Serialization value '{path}' must be {expected}, but was '{GetNodeKind(actual)}'."); private static string GetNodeKind(SerializationNode node) => node switch - { - NullSerializationNode => "null", - ScalarSerializationNode => "scalar", - BinarySerializationNode => "binary", - ObjectSerializationNode => "object", - ArraySerializationNode => "array", - MapSerializationNode => "map", - _ => node.GetType().Name - }; + { + NullSerializationNode => "null", + ScalarSerializationNode => "scalar", + BinarySerializationNode => "binary", + ObjectSerializationNode => "object", + ArraySerializationNode => "array", + MapSerializationNode => "map", + _ => node.GetType().Name + }; private static string AppendPath( string path, diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/PropertyVisibility.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/PropertyVisibility.cs index aed8c7ab6..054812f65 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/PropertyVisibility.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/PropertyVisibility.cs @@ -16,55 +16,45 @@ public enum PropertyVisibility /// No participation in serialization, deserialization, or runtime access. /// None = 0, - /// /// Participates in serialization output. /// Serialize = 1 << 0, - /// /// Participates in deserialization (restore/read). /// Deserialize = 1 << 1, - /// /// Allows runtime retrieval through the API. /// RuntimeGet = 1 << 2, - /// /// Allows runtime assignment through the API. /// RuntimeSet = 1 << 3, - /// /// Can serialize, deserialize, and allow runtime get/set. /// Show = Serialize | Deserialize | RuntimeGet | RuntimeSet, - /// /// Can serialize and deserialize, but runtime code cannot get or set through . /// Hide = Serialize | Deserialize, - /// /// Can serialize and deserialize, runtime can get but cannot set. /// Runtime set attempts should be rejected (see behavior). /// Readonly = Serialize | Deserialize | RuntimeGet, - /// /// Does not participate in serialization or deserialization, but runtime can get/set. /// Transient = RuntimeGet | RuntimeSet, - /// /// Participates in serialization only (no deserialization), runtime can get/set. /// SerializeOnly = Serialize | RuntimeGet | RuntimeSet, - /// /// Participates in deserialization only (no serialization), runtime can get/set. /// - DeserializeOnly = Deserialize | RuntimeGet | RuntimeSet, + DeserializeOnly = Deserialize | RuntimeGet | RuntimeSet } diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationCollectionMetadata.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationCollectionMetadata.cs index d74ce36aa..1a861978c 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationCollectionMetadata.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationCollectionMetadata.cs @@ -37,9 +37,12 @@ public SerializationCollectionMetadata( Func>>? enumerateMap ) { ArgumentNullException.ThrowIfNull(elementType); - if (keyType is null ? buildSequence is null || buildMap is not null || enumerateMap is not null - : buildSequence is not null || buildMap is null || enumerateMap is null) + if (keyType is null + ? buildSequence is null || buildMap is not null || enumerateMap is not null + : buildSequence is not null || buildMap is null || enumerateMap is null + ) { throw new ArgumentException("Collection metadata requires one complete sequence or map shape."); + } this.elementType = elementType; this.keyType = keyType; this.buildSequence = buildSequence; diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationMemberMetadata.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationMemberMetadata.cs index 8516cf784..7a0478fa8 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationMemberMetadata.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationMemberMetadata.cs @@ -41,9 +41,13 @@ public SerializationMemberMetadata( ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(type); if ((visibility & (PropertyVisibility.Serialize | PropertyVisibility.RuntimeGet)) != 0 && getter is null) + { throw new ArgumentException("Readable metadata requires a getter.", nameof(getter)); + } if ((visibility & (PropertyVisibility.Deserialize | PropertyVisibility.RuntimeSet)) != 0 && setter is null) + { throw new ArgumentException("Writable metadata requires a setter.", nameof(setter)); + } this.name = name; this.type = type; this.visibility = visibility; @@ -79,8 +83,9 @@ public SerializationMemberMetadata( /// Reading is not permitted by this metadata. /// public object? GetValue(object target) - => m_getter is not null ? m_getter(target) - : throw new InvalidOperationException($"Serialization member '{name}' does not permit reads."); + => m_getter is not null + ? m_getter(target) + : throw new InvalidOperationException($"Serialization member '{name}' does not permit reads."); /// /// Writes a value through the selected declaration accessor. @@ -99,7 +104,9 @@ public void SetValue( object? value ) { if (m_setter is null) + { throw new InvalidOperationException($"Serialization member '{name}' does not permit writes."); + } m_setter(target, value); } } diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs index 58ffff6fe..9b7c06d62 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs @@ -50,22 +50,29 @@ public SerializationTypeMetadata( ) { ArgumentNullException.ThrowIfNull(type); ArgumentNullException.ThrowIfNull(members); - SerializationMemberMetadata[] completeMembers = inherited is null ? members.ToArray() - : inherited.members.Concat(members).ToArray(); + SerializationMemberMetadata[] completeMembers = inherited is null + ? members.ToArray() + : inherited.members.Concat(members).ToArray(); var names = new HashSet(StringComparer.Ordinal); foreach (SerializationMemberMetadata member in completeMembers) + { if (member is null || !names.Add(member.name)) + { throw new ArgumentException("Serialization metadata requires nonnull members with unique keys.", nameof(members)); + } + } this.type = type; this.members = Array.AsReadOnly(completeMembers); - this.restored = inherited?.restored is not Action baseRestored ? restored - : restored is null ? baseRestored : ( - value, - context - ) => { - baseRestored(value, context); - restored(value, context); - }; + this.restored = inherited?.restored is not Action baseRestored + ? restored + : restored is null ? baseRestored : ( + value, + context + ) => + { + baseRestored(value, context); + restored(value, context); + }; this.collection = collection; this.requiresConverter = requiresConverter || inherited?.requiresConverter == true; m_factory = factory; @@ -107,9 +114,15 @@ public SerializationTypeMetadata( /// public SerializationTypeMetadata WithPureFieldAccess() { - if (!type.IsValueType || requiresConverter || collection is not null || - members.Any(static member => (member.visibility & PropertyVisibility.Serialize) != 0 && !ValuePipeline.IsPrimitive(member.type))) - throw new InvalidOperationException("Pure field capture requires a default value type containing only primitive serialized fields."); + if (!type.IsValueType || requiresConverter || collection is not null + || members.Any( + static member => (member.visibility & PropertyVisibility.Serialize) != 0 && !ValuePipeline.IsPrimitive(member.type) + ) + ) { + throw new InvalidOperationException( + "Pure field capture requires a default value type containing only primitive serialized fields." + ); + } return new SerializationTypeMetadata(type, members, m_factory, restored, collection, requiresConverter) { hasPureFieldAccess = true @@ -134,11 +147,12 @@ public SerializationTypeMetadata WithPureFieldAccess() public SerializationTypeMetadata WithCaptureRevision(Func readRevision) { ArgumentNullException.ThrowIfNull(readRevision); - if (!type.IsSealed || type.IsValueType || !typeof(ISerializable).IsAssignableFrom(type) || - !typeof(Inno.Core.Identity.IdentityObject).IsAssignableFrom(type)) - { + if (!type.IsSealed || type.IsValueType || !typeof(ISerializable).IsAssignableFrom(type) + || !typeof(Inno.Core.Identity.IdentityObject).IsAssignableFrom(type) + ) { throw new InvalidOperationException( - "Capture revision metadata requires a sealed serializable Core identity source."); + "Capture revision metadata requires a sealed serializable Core identity source." + ); } return new SerializationTypeMetadata(type, members, m_factory, restored, collection, requiresConverter) { @@ -159,7 +173,11 @@ public SerializationTypeMetadata WithCaptureRevision(Func readRe public object CreateInstance() { if (m_factory is null) - throw new InvalidOperationException($"Serialization type '{type}' requires a parameterless constructor or an explicit converter."); + { + throw new InvalidOperationException( + $"Serialization type '{type}' requires a parameterless constructor or an explicit converter." + ); + } try { return m_factory(); diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializedProperty.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializedProperty.cs index 5fa15cdf5..f26018a32 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializedProperty.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializedProperty.cs @@ -79,7 +79,9 @@ bool canWrite public object? GetValue() { if (!canRead) + { throw new InvalidOperationException($"Serialized property '{name}' does not permit runtime reads."); + } return m_getter(); } @@ -95,7 +97,9 @@ bool canWrite public void SetValue(object? value) { if (!canWrite) + { throw new InvalidOperationException($"Serialized property '{name}' does not permit runtime writes."); + } m_setter(value); } diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs index 2eb944c41..8433f3b15 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs @@ -33,26 +33,33 @@ public StaticSerializationMetadataSource(IReadOnlyList Strict, - /// /// Continues restoring independent properties and reports every rejected value. /// diff --git a/src/foundation/core/Inno.Core.Serialization/SerializationGeneration.cs b/src/foundation/core/Inno.Core.Serialization/SerializationGeneration.cs index 170086068..54aeed17e 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializationGeneration.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializationGeneration.cs @@ -48,8 +48,7 @@ ConverterRegistryLease converters public byte[] Serialize( T value, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable => m_owner.Serialize(value, GetConverters(), context); /// @@ -73,8 +72,7 @@ public byte[] Serialize( public T Deserialize( ReadOnlySpan bytes, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable => m_owner.Deserialize(bytes, GetConverters(), context); /// @@ -98,8 +96,7 @@ public T Deserialize( public byte[] Encode( Action write, SerializationContext? context = null - ) - => m_owner.Encode(write, GetConverters(), context); + ) => m_owner.Encode(write, GetConverters(), context); /// /// Decodes a manually defined structured root using the converter generation captured by this instance. @@ -129,8 +126,7 @@ public TResult Decode( ReadOnlySpan bytes, Func read, SerializationContext? context = null - ) - => m_owner.Decode(bytes, read, GetConverters(), context); + ) => m_owner.Decode(bytes, read, GetConverters(), context); /// /// Releases the pinned converter generation and every collectible type reference owned by this lease. diff --git a/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs b/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs index 90ac448cc..c76fa145b 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs @@ -45,7 +45,9 @@ ISerializationMetadataSource metadata public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_converters.Dispose(); GC.SuppressFinalize(this); @@ -116,10 +118,20 @@ public IReadOnlyList GetProperties(ISerializable value) foreach (SerializationMemberMetadata member in members) { if ((member.visibility & PropertyVisibility.RuntimeGet) == 0) + { continue; - properties.Add(new SerializedProperty(member.name, member.type, - () => member.GetValue(value), propertyValue => member.SetValue(value, propertyValue), - member.visibility, true, (member.visibility & PropertyVisibility.RuntimeSet) != 0)); + } + properties.Add( + new SerializedProperty( + member.name, + member.type, + () => member.GetValue(value), + propertyValue => member.SetValue(value, propertyValue), + member.visibility, + true, + (member.visibility & PropertyVisibility.RuntimeSet) != 0 + ) + ); } return properties; } @@ -189,7 +201,8 @@ public byte[] CapturePropertyData( value, propertyName, CreateContext(context), - converters); + converters + ); return PropertySnapshotBinaryFormat.Encode([snapshot]); } @@ -279,14 +292,11 @@ public SerializationPropertyRestoreResult RestoreProperties( ArgumentNullException.ThrowIfNull(target); ArgumentNullException.ThrowIfNull(snapshots); if (!Enum.IsDefined(mode)) + { throw new ArgumentOutOfRangeException(nameof(mode), mode, "Unknown property restore mode."); + } using ConverterRegistryLease converters = m_converters.Capture(); - return PropertySnapshotPipeline.Restore( - target, - snapshots, - mode, - CreateContext(context), - converters); + return PropertySnapshotPipeline.Restore(target, snapshots, mode, CreateContext(context), converters); } /// @@ -329,14 +339,17 @@ public SerializationPropertyRestoreResult RestorePropertiesData( EnsureInitialized(); ArgumentNullException.ThrowIfNull(target); if (!Enum.IsDefined(mode)) + { throw new ArgumentOutOfRangeException(nameof(mode), mode, "Unknown property restore mode."); + } using ConverterRegistryLease converters = m_converters.Capture(); return PropertySnapshotPipeline.Restore( target, PropertySnapshotBinaryFormat.Decode(data), mode, CreateContext(context), - converters); + converters + ); } /// @@ -363,8 +376,7 @@ public SerializationPropertyRestoreResult RestorePropertiesData( public byte[] Serialize( T value, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable { EnsureInitialized(); ArgumentNullException.ThrowIfNull(value); @@ -412,7 +424,8 @@ public SerializationSnapshot CaptureSnapshot( T value, SerializationContext? context = null, SerializationSnapshot? previous = null - ) where T : class, ISerializable { + ) where T : class, ISerializable + { EnsureInitialized(); ArgumentNullException.ThrowIfNull(value); using ConverterRegistryLease converters = m_converters.Capture(); @@ -432,8 +445,7 @@ internal byte[] Serialize( T value, ConverterRegistryLease converters, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable { ArgumentNullException.ThrowIfNull(value); ArgumentNullException.ThrowIfNull(converters); @@ -470,8 +482,7 @@ internal byte[] Serialize( public T Deserialize( ReadOnlySpan bytes, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable { EnsureInitialized(); using ConverterRegistryLease converters = m_converters.Capture(); @@ -482,8 +493,7 @@ internal T Deserialize( ReadOnlySpan bytes, ConverterRegistryLease converters, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable { ArgumentNullException.ThrowIfNull(converters); SerializationNode root = BinarySerializationFormat.Decode(bytes); @@ -526,8 +536,7 @@ public void Restore( T target, ReadOnlySpan bytes, SerializationContext? context = null - ) - where T : class, ISerializable + ) where T : class, ISerializable { EnsureInitialized(); ArgumentNullException.ThrowIfNull(target); @@ -639,7 +648,9 @@ internal TResult Decode( ArgumentNullException.ThrowIfNull(converters); SerializationNode decoded = BinarySerializationFormat.Decode(bytes); if (decoded is not ObjectSerializationNode root) + { throw new InvalidOperationException("The advanced serialization root must be an object."); + } var operation = new SerializationOperation(CreateContext(context), converters); try @@ -668,8 +679,11 @@ private SerializationContext CreateContext(SerializationContext? context) context ??= SerializationContext.empty; if (context.TryGet(out TypeCatalog? types) && ReferenceEquals(types, m_types) && context.TryGet(out SerializationRegistry? registry) && ReferenceEquals(registry, this) - && context.TryGet(out ISerializationMetadataSource? metadata) && ReferenceEquals(metadata, m_metadata)) + && context.TryGet(out ISerializationMetadataSource? metadata) + && ReferenceEquals(metadata, m_metadata) + ) { return context; + } return context.With(m_types).With(this).With(m_metadata); } } diff --git a/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs b/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs index 4c03dc4d3..f9ebf6c66 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs @@ -46,7 +46,9 @@ public void WriteTo(Stream destination) { ArgumentNullException.ThrowIfNull(destination); if (!destination.CanWrite) + { throw new ArgumentException("A writable serialization destination is required.", nameof(destination)); + } BinarySerializationFormat.WriteTo(destination, root); } diff --git a/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs b/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs index 81a73b941..94c18670a 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs @@ -38,13 +38,20 @@ public static byte[] Rewrite( ) { ArgumentNullException.ThrowIfNull(identities); if (HasMagic(source, s_valueMagic)) + { return BinarySerializationFormat.Encode(RewriteNode(BinarySerializationFormat.Decode(source), identities, paths)); + } if (HasMagic(source, s_propertyMagic)) { IReadOnlyList snapshots = PropertySnapshotBinaryFormat.Decode(source); - return PropertySnapshotBinaryFormat.Encode(snapshots.Select(snapshot => - new SerializationPropertySnapshot(snapshot.name, snapshot.propertyType, - Rewrite(snapshot.dataSpan, identities, paths))).ToArray()); + return PropertySnapshotBinaryFormat.Encode( + snapshots.Select(snapshot => + new SerializationPropertySnapshot( + snapshot.name, + snapshot.propertyType, + Rewrite(snapshot.dataSpan, identities, paths) + )).ToArray() + ); } return source.ToArray(); } @@ -59,7 +66,7 @@ private static SerializationNode RewriteNode( case ScalarSerializationNode { value: Guid id } when identities.TryGetValue(id, out Guid replacement): return new ScalarSerializationNode(replacement); case ScalarSerializationNode { value: string path } when paths is not null - && paths.TryGetValue(path, out string? replacement): + && paths.TryGetValue(path, out string? replacement): return new ScalarSerializationNode(replacement); case BinarySerializationNode binary: return new BinarySerializationNode(Rewrite(binary.value, identities, paths)); @@ -67,23 +74,32 @@ private static SerializationNode RewriteNode( { var rewritten = new ObjectSerializationNode(); foreach ((string name, SerializationNode child) in value.values) + { rewritten.values.Add(name, RewriteNode(child, identities, paths)); + } return rewritten; } case ArraySerializationNode value: { var rewritten = new ArraySerializationNode(); foreach (SerializationNode child in value.values) + { rewritten.values.Add(RewriteNode(child, identities, paths)); + } return rewritten; } case MapSerializationNode value: { var rewritten = new MapSerializationNode(); foreach (KeyValuePair entry in value.values) - rewritten.values.Add(new KeyValuePair( - RewriteNode(entry.Key, identities, paths), - RewriteNode(entry.Value, identities, paths))); + { + rewritten.values.Add( + new KeyValuePair( + RewriteNode(entry.Key, identities, paths), + RewriteNode(entry.Value, identities, paths) + ) + ); + } return rewritten; } default: @@ -94,7 +110,6 @@ private static SerializationNode RewriteNode( private static bool HasMagic( ReadOnlySpan source, ReadOnlySpan magic - ) - => source.Length > magic.Length && source[0] == magic.Length - && source.Slice(1, magic.Length).SequenceEqual(magic); + ) => source.Length > magic.Length && source[0] == magic.Length + && source.Slice(1, magic.Length).SequenceEqual(magic); } diff --git a/src/foundation/core/Inno.Core.Settings/IProjectSettingsLookup.cs b/src/foundation/core/Inno.Core.Settings/IProjectSettingsLookup.cs index 996e8515d..aaea6ecf3 100644 --- a/src/foundation/core/Inno.Core.Settings/IProjectSettingsLookup.cs +++ b/src/foundation/core/Inno.Core.Settings/IProjectSettingsLookup.cs @@ -53,6 +53,5 @@ TSetting Get(ProjectSettingId id) bool TryGet( ProjectSettingId id, out TSetting? setting - ) - where TSetting : class, ISerializable; + ) where TSetting : class, ISerializable; } diff --git a/src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs b/src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs index 848c621f2..2bcd734da 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs @@ -1,6 +1,5 @@ using System; using System.Text; - using Inno.Core.Serialization; using Inno.Extensibility.Types; @@ -42,21 +41,27 @@ public static ProjectId FromName(string name) foreach (char character in name.Trim()) { if (character is >= 'A' and <= 'Z') + { Append((char)(character + ('a' - 'A'))); + } else if (character is >= 'a' and <= 'z' or >= '0' and <= '9') + { Append(character); + } else + { pendingSeparator = builder.Length > 0; + } } string value = builder.Length == 0 ? "inno.project" : builder.ToString(); - return new ProjectId(string.Equals(value, "project", StringComparison.Ordinal) - ? "inno.project" - : value); + return new ProjectId(string.Equals(value, "project", StringComparison.Ordinal) ? "inno.project" : value); void Append(char character) { if (pendingSeparator) + { builder.Append('-'); + } pendingSeparator = false; builder.Append(character); } @@ -97,7 +102,9 @@ internal static void ValidatePortable( string parameterName ) { if (value.Length > 128) + { throw new ArgumentException($"{label} cannot exceed 128 characters.", parameterName); + } for (int index = 0; index < value.Length; index++) { char character = value[index]; @@ -108,13 +115,18 @@ string parameterName { throw new ArgumentException( $"{label} must use lowercase ASCII letters, digits, dots, hyphens, or underscores.", - parameterName); + parameterName + ); } } if (value[0] is '.' or '-' or '_' || value[^1] is '.' or '-' or '_') + { throw new ArgumentException($"{label} must begin and end with a letter or digit.", parameterName); + } if (value.Contains("..", StringComparison.Ordinal)) + { throw new ArgumentException($"{label} cannot contain empty namespace segments.", parameterName); + } } } @@ -176,11 +188,14 @@ public static ProjectLocalId FromName(string name) { throw new ArgumentException( "A project-scoped name must use ASCII letters, digits, spaces, dots, hyphens, or underscores.", - nameof(name)); + nameof(name) + ); } } if (builder.Length == 0) + { throw new ArgumentException("A project-scoped name must contain a letter or digit.", nameof(name)); + } return new ProjectLocalId(builder.ToString()); } @@ -197,7 +212,9 @@ private static void AppendSeparator( ref bool pendingSeparator ) { if (pendingSeparator && builder.Length > 0) + { builder.Append('-'); + } pendingSeparator = false; } } @@ -221,9 +238,13 @@ public ProjectScopedId( ProjectLocalId name ) { if (!projectId.isValid) + { throw new ArgumentException("A valid Project ID is required.", nameof(projectId)); + } if (string.IsNullOrEmpty(name.value)) + { throw new ArgumentException("A valid project-local ID is required.", nameof(name)); + } this.projectId = projectId; this.name = name; } diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingComposition.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingComposition.cs index 636d6e137..cd0cf0215 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingComposition.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingComposition.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Serialization; namespace Inno.Core.Settings; @@ -39,7 +38,6 @@ public enum ProjectSettingContributionSource /// The contribution is a default supplied by an activated Plugin. /// Plugin, - /// /// The contribution is the project-authored delta with highest precedence. /// @@ -218,11 +216,11 @@ out byte[] contributionData if (baseline is not TSetting typedBaseline || value is not TSetting typedValue) { throw new ArgumentException( - $"Composer '{GetType().FullName}' requires setting type '{typeof(TSetting).FullName}'."); + $"Composer '{GetType().FullName}' requires setting type '{typeof(TSetting).FullName}'." + ); } TContribution contribution = CaptureContribution(typedBaseline, typedValue) - ?? throw new InvalidOperationException( - $"Composer '{GetType().FullName}' returned a null contribution."); + ?? throw new InvalidOperationException($"Composer '{GetType().FullName}' returned a null contribution."); if (IsEmpty(contribution)) { contributionData = []; @@ -242,7 +240,8 @@ IReadOnlyList contributions { throw new ArgumentException( $"Composer '{GetType().FullName}' requires setting type '{typeof(TSetting).FullName}'.", - nameof(hostDefault)); + nameof(hostDefault) + ); } var decoded = new List>(contributions.Count); foreach (ProjectSettingCompositionEntry contribution in contributions) @@ -251,12 +250,11 @@ IReadOnlyList contributions if (IsEmpty(value)) { throw new InvalidOperationException( - $"Composer '{GetType().FullName}' received an empty persisted contribution from " + - $"'{contribution.context.contributorId}'."); + $"Composer '{GetType().FullName}' received an empty persisted contribution from " + + $"'{contribution.context.contributorId}'." + ); } - decoded.Add(new ProjectSettingContribution( - contribution.context, - value)); + decoded.Add(new ProjectSettingContribution(contribution.context, value)); } Compose(target, decoded); return target; diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs index 52d4c653f..7a853f687 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs @@ -99,9 +99,13 @@ public ProjectSettingRecord( ReadOnlySpan propertyData ) { if (!id.isValid) + { throw new ArgumentException("A project setting ID must be valid.", nameof(id)); + } if (stableTypeId == Guid.Empty) + { throw new ArgumentException("A project setting requires a stable type ID.", nameof(stableTypeId)); + } this.id = id; this.stableTypeId = stableTypeId; this.propertyData = propertyData.ToArray(); @@ -195,9 +199,9 @@ IEnumerable settings private static ProjectSettingRecord Clone(ProjectSettingRecord record) => new() - { - id = record.id, - stableTypeId = record.stableTypeId, - propertyData = record.propertyData?.ToArray()! - }; + { + id = record.id, + stableTypeId = record.stableTypeId, + propertyData = record.propertyData?.ToArray()! + }; } diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs index 47db38115..9b2b4e059 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs @@ -2,11 +2,10 @@ using System.Collections.Generic; using System.IO; using System.Linq; - -using Inno.Extensibility.Types; -using Inno.Core.Serialization; using Inno.Core.Collections; using Inno.Core.IO; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Core.Settings; @@ -59,7 +58,9 @@ public ProjectSettings( ArgumentNullException.ThrowIfNull(documentStore); ArgumentNullException.ThrowIfNull(types); if (!defaultProjectId.isValid) + { throw new ArgumentException("A default Project ID is required.", nameof(defaultProjectId)); + } ArgumentNullException.ThrowIfNull(serialization); ArgumentNullException.ThrowIfNull(serializationContext); m_serialization = serialization; @@ -70,7 +71,8 @@ public ProjectSettings( documentStore, serialization, static () => new ProjectSettingsDocument(), - ValidateDocument); + ValidateDocument + ); m_document = m_documents.Load(); Rebuild(contributors ?? [], allowUnresolvedContributions: true); } @@ -93,13 +95,17 @@ public ProjectSettings( /// /// Thrown when the definition does not implement the requested contract. /// - public TSetting Get(ProjectSettingId id) where TSetting : class, ISerializable + public TSetting Get(ProjectSettingId id) + where TSetting : class, ISerializable { ObjectDisposedException.ThrowIf(m_disposed, this); if (!TryClone(id, out ISerializable? value) || value is null) + { throw new KeyNotFoundException($"Project setting '{id}' is not defined."); + } return value as TSetting ?? throw new InvalidCastException( - $"Project setting '{id}' is '{value.GetType().FullName}', not '{typeof(TSetting).FullName}'."); + $"Project setting '{id}' is '{value.GetType().FullName}', not '{typeof(TSetting).FullName}'." + ); } /// @@ -120,8 +126,7 @@ public TSetting Get(ProjectSettingId id) where TSetting : class, ISeri public bool TryGet( ProjectSettingId id, out TSetting? setting - ) - where TSetting : class, ISerializable + ) where TSetting : class, ISerializable { ObjectDisposedException.ThrowIf(m_disposed, this); if (!TryClone(id, out ISerializable? value)) @@ -175,7 +180,9 @@ out ProjectSettingRecord record ArgumentNullException.ThrowIfNull(declaredOverrides); ArgumentNullException.ThrowIfNull(contributors); if (!declaredOverrides.All(declaredDependencies.Contains)) + { throw new ArgumentException("Every explicit override must identify a direct dependency.", nameof(declaredOverrides)); + } ValidateContributorOrder(contributors); ProjectSettingsRegistry.Snapshot registry = m_registry.settings; if (!registry.TryGet(id, out ProjectSettingsRegistry.Definition? definition)) @@ -199,13 +206,15 @@ record = default; if (contributors.Any(contributor => string.Equals(contributor.id, contributorId, StringComparison.Ordinal))) { throw new InvalidOperationException( - $"Cannot export Plugin '{contributorId}' while a Plugin with the same ID is active."); + $"Cannot export Plugin '{contributorId}' while a Plugin with the same ID is active." + ); } var prospective = new ProjectSettingsContributor( contributorId, declaredDependencies, declaredOverrides, - [authored]); + [authored] + ); ProjectSettingsContributor[] validationContributors = [.. contributors, prospective]; _ = ComposeSetting(id, definition, validationContributors, projectRecord: null); @@ -257,8 +266,8 @@ out ISerializable? setting ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_effective.TryGetValue(id, out ProjectSettingRecord value) || !m_registry.settings.TryGet(id, out ProjectSettingsRegistry.Definition? definition) - || definition.stableTypeId != value.stableTypeId) - { + || definition.stableTypeId != value.stableTypeId + ) { setting = null; return false; } @@ -335,13 +344,16 @@ public void Rebuild( if (!registry.TryGet(setting.id, out ProjectSettingsRegistry.Definition? definition)) { if (!allowUnresolvedContributions) + { throw new InvalidOperationException($"Project setting '{setting.id}' has no active definition."); + } continue; } if (!definition.allowPluginContributions) { throw new InvalidOperationException( - $"Project setting '{setting.id}' does not accept Plugin contributions."); + $"Project setting '{setting.id}' does not accept Plugin contributions." + ); } } } @@ -351,30 +363,46 @@ public void Rebuild( { ProjectSettingRecord? projectRecord = FindRecord(m_document.overrides, id); ISerializable value = ComposeSetting(id, definition, contributors, projectRecord); - candidate.Add(id, new ProjectSettingRecord(id, definition.stableTypeId, - m_serialization.CapturePropertiesData(value, m_serializationContext))); + candidate.Add( + id, + new ProjectSettingRecord( + id, + definition.stableTypeId, + m_serialization.CapturePropertiesData(value, m_serializationContext) + ) + ); } m_effective.Clear(); foreach ((ProjectSettingId id, ProjectSettingRecord value) in candidate) + { m_effective.Add(id, value); + } } internal ProjectSettingRecord[] CaptureEffective() => m_effective.Values.Select(static record => new ProjectSettingRecord( - record.id, record.stableTypeId, record.propertyData)).ToArray(); + record.id, + record.stableTypeId, + record.propertyData + )).ToArray(); internal void RestoreEffective(IEnumerable records) { m_effective.Clear(); foreach (ProjectSettingRecord record in records) + { m_effective.Add(record.id, new ProjectSettingRecord(record.id, record.stableTypeId, record.propertyData)); + } } internal IReadOnlyList GetUnavailable(IReadOnlyList contributors) - => Array.AsReadOnly(m_document.overrides.Concat(contributors.SelectMany(static item => item.settings)) - .Where(record => !m_registry.settings.TryGet(record.id, out _)) - .Select(static record => new ProjectSettingRecord(record.id, record.stableTypeId, record.propertyData)).ToArray()); + => Array.AsReadOnly( + m_document.overrides.Concat(contributors.SelectMany(static item => item.settings)) + .Where(record => !m_registry.settings.TryGet(record.id, out _)) + .Select(static record => new ProjectSettingRecord(record.id, record.stableTypeId, record.propertyData)) + .ToArray() + ); /// /// Persists one project-authored semantic contribution and rebuilds the effective value. @@ -396,7 +424,8 @@ IReadOnlyList contributors _ = ApplyProjectOverrides( new Dictionary { [id] = value }, resets: null, - contributors); + contributors + ); } /// @@ -430,20 +459,22 @@ IReadOnlyList contributors if (resets is not null) { foreach (ProjectSettingId id in resets) + { changed |= records.Remove(id); + } } foreach ((ProjectSettingId id, ISerializable value) in values) { ArgumentNullException.ThrowIfNull(value); if (resets?.Contains(id) == true) + { continue; + } if (!registry.TryGet(id, out ProjectSettingsRegistry.Definition? definition) - || definition.runtimeType != value.GetType()) - { - throw new ArgumentException( - $"Value type does not match project setting '{id}'.", - nameof(values)); + || definition.runtimeType != value.GetType() + ) { + throw new ArgumentException($"Value type does not match project setting '{id}'.", nameof(values)); } ISerializable baseline = ComposeSetting(id, definition, contributors, projectRecord: null); if (!TryCreateRecord(id, definition, baseline, value, out ProjectSettingRecord candidate)) @@ -452,13 +483,17 @@ IReadOnlyList contributors continue; } if (records.TryGetValue(id, out ProjectSettingRecord current) && RecordsEqual(current, candidate)) + { continue; + } records[id] = candidate; changed = true; } if (!changed) + { return false; + } var candidateDocument = new ProjectSettingsDocument { overrides = records.Values @@ -494,7 +529,9 @@ IReadOnlyList contributors public void Dispose() { if (m_disposed) + { return; + } m_effective.Clear(); m_registry.Dispose(); m_disposed = true; @@ -503,8 +540,7 @@ public void Dispose() private static ProjectSettingRecord? FindRecord( ProjectSettingsContributor contributor, ProjectSettingId id - ) - => FindRecord(contributor.settings, id); + ) => FindRecord(contributor.settings, id); private static ProjectSettingRecord? FindRecord( IEnumerable records, @@ -514,9 +550,13 @@ ProjectSettingId id foreach (ProjectSettingRecord record in records) { if (record.id != id) + { continue; + } if (result is not null) + { throw new InvalidOperationException($"Project setting '{id}' is contributed more than once by one owner."); + } result = record; } return result; @@ -532,7 +572,9 @@ IReadOnlyList contributors foreach (string id in directDependencies) { if (!byId.ContainsKey(id)) + { throw new InvalidOperationException($"Declared Plugin dependency '{id}' is not active."); + } result.Add(id); result.UnionWith(graph.GetDependencies(id, recursive: true)); } @@ -552,7 +594,9 @@ internal static void ValidateContributorOrder(IReadOnlyList contributor.id).SequenceEqual(ordered, StringComparer.Ordinal)) + { throw new InvalidOperationException("Project settings contributors are not dependency-ordered."); + } } private static DependencyGraph CreateContributorGraph(IReadOnlyList contributors) @@ -562,7 +606,9 @@ private static DependencyGraph CreateContributorGraph(IReadOnlyList CreateContributorGraph(IReadOnlyList CreateContributorGraph(IReadOnlyList left.id == right.id - && left.stableTypeId == right.stableTypeId - && (left.propertyData ?? []).AsSpan().SequenceEqual(right.propertyData ?? []); + ) => left.id == right.id + && left.stableTypeId == right.stableTypeId + && (left.propertyData ?? []).AsSpan().SequenceEqual(right.propertyData ?? []); private static void ValidateRecord( ProjectSettingId id, @@ -594,9 +640,13 @@ private static void ValidateRecord( ProjectSettingRecord record ) { if (record.stableTypeId != definition.stableTypeId) + { throw new InvalidOperationException($"Project setting '{id}' has an incompatible stable type."); + } if (record.propertyData is null || record.propertyData.Length == 0) + { throw new InvalidOperationException($"Project setting '{id}' contains an empty contribution payload."); + } } private ISerializable ComposeSetting( @@ -606,36 +656,52 @@ private ISerializable ComposeSetting( ProjectSettingRecord? projectRecord ) { if (definition.composer is null) + { return ComposeReplacement(id, definition, contributors, projectRecord); + } var entries = new List(); foreach (ProjectSettingsContributor contributor in contributors) { ProjectSettingRecord? record = FindRecord(contributor, id); if (record is not ProjectSettingRecord contribution) + { continue; + } ValidateRecord(id, definition, contribution); - entries.Add(new ProjectSettingCompositionEntry( - new ProjectSettingContributionContext( - contributor.id, - ProjectSettingContributionSource.Plugin, - contributor.dependencies.ToHashSet(StringComparer.Ordinal), - contributor.overrides.ToHashSet(StringComparer.Ordinal)), - contribution.propertyData)); + entries.Add( + new ProjectSettingCompositionEntry( + new ProjectSettingContributionContext( + contributor.id, + ProjectSettingContributionSource.Plugin, + contributor.dependencies.ToHashSet(StringComparer.Ordinal), + contributor.overrides.ToHashSet(StringComparer.Ordinal) + ), + contribution.propertyData + ) + ); } if (projectRecord is ProjectSettingRecord project) { ValidateRecord(id, definition, project); - entries.Add(new ProjectSettingCompositionEntry( - new ProjectSettingContributionContext( - "project", - ProjectSettingContributionSource.Project, - new HashSet(StringComparer.Ordinal), - new HashSet(StringComparer.Ordinal)), - project.propertyData)); - } - return definition.composer.Compose(m_serialization, m_serializationContext, - CreateHostDefault(id, definition), entries); + entries.Add( + new ProjectSettingCompositionEntry( + new ProjectSettingContributionContext( + "project", + ProjectSettingContributionSource.Project, + new HashSet(StringComparer.Ordinal), + new HashSet(StringComparer.Ordinal) + ), + project.propertyData + ) + ); + } + return definition.composer.Compose( + m_serialization, + m_serializationContext, + CreateHostDefault(id, definition), + entries + ); } private ISerializable CreateHostDefault( @@ -644,7 +710,9 @@ ProjectSettingsRegistry.Definition definition ) { ISerializable value = definition.Create(); if (id == ProjectIdentitySettings.settingId && value is ProjectIdentitySettings identity) + { identity.projectId = m_defaultProjectId.value; + } return value; } @@ -660,14 +728,17 @@ private ISerializable ComposeReplacement( { ProjectSettingRecord? record = FindRecord(contributor, id); if (record is not ProjectSettingRecord contribution) + { continue; + } ValidateRecord(id, definition, contribution); if (owner != "host" && (!contributor.dependencies.Contains(owner, StringComparer.Ordinal) - || !contributor.overrides.Contains(owner, StringComparer.Ordinal))) - { + || !contributor.overrides.Contains(owner, StringComparer.Ordinal)) + ) { throw new InvalidOperationException( - $"Settings contributors '{owner}' and '{contributor.id}' conflict on '{id}'."); + $"Settings contributors '{owner}' and '{contributor.id}' conflict on '{id}'." + ); } owner = contributor.id; selected = contribution; @@ -680,7 +751,9 @@ private ISerializable ComposeReplacement( ISerializable result = CreateHostDefault(id, definition); if (selected is ProjectSettingRecord value) + { _ = m_serialization.RestorePropertiesData(result, value.propertyData, context: m_serializationContext); + } return result; } @@ -692,7 +765,9 @@ private bool TryCreateRecord( out ProjectSettingRecord record ) { if (definition.runtimeType != baseline.GetType() || definition.runtimeType != value.GetType()) + { throw new ArgumentException($"Value type does not match project setting '{id}'.", nameof(value)); + } byte[] payload; if (definition.composer is null) @@ -718,7 +793,9 @@ private static void ValidateDocument(ProjectSettingsDocument document) { ArgumentNullException.ThrowIfNull(document); if (document.overrides is null) + { throw new InvalidDataException("A project Settings document requires an override collection."); + } } private void ReplaceDocument( diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsExecutionContext.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsExecutionContext.cs index ab4bbec39..a59655bf6 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingsExecutionContext.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsExecutionContext.cs @@ -1,6 +1,6 @@ -using Inno.Core.Execution; using System; using System.Threading; +using Inno.Core.Execution; namespace Inno.Core.Settings; @@ -40,5 +40,4 @@ public static IDisposable EnterScope(IProjectSettingsLookup settings) ArgumentNullException.ThrowIfNull(settings); return S_CURRENT_SCOPE.Enter(settings); } - } diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs index d4b6c6370..5fc8e878b 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs @@ -1,18 +1,16 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using System.Linq; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Core.Settings; internal sealed class ProjectSettingsRegistry : TypeRegistry { internal ProjectSettingsRegistry(TypeCatalog types) - : base(types) - { - } + : base(types) {} internal Snapshot settings => current; @@ -34,20 +32,26 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (type.IsAbstract || !typeof(ISerializable).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Project setting type '{type.FullName}' must be a non-abstract ISerializable class."); + $"Project setting type '{type.FullName}' must be a non-abstract ISerializable class." + ); } if (!types.CanCreateInstance(typeRef)) { throw new InvalidOperationException( - $"Project setting type '{type.FullName}' requires a factory in the current type catalog."); + $"Project setting type '{type.FullName}' requires a factory in the current type catalog." + ); } if (!types.TryGetTypeRef(type, out TypeRef stableType)) + { throw new InvalidOperationException($"Project setting type '{type.FullName}' requires StableTypeId."); + } ProjectSettingDefinitionAttribute attribute = types.GetAttribute(typeRef, inherit: false)!; var id = new ProjectSettingId(attribute.id); if (!settingTypes.TryAdd(id, (stableType.stableId, type, attribute.allowPluginContributions))) + { throw new InvalidOperationException($"Project setting ID '{id}' is declared more than once."); + } } var composers = new Dictionary(); @@ -57,31 +61,36 @@ protected override Snapshot Build(TypeCacheSnapshot types) if (type.IsAbstract || !typeof(ProjectSettingComposer).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Project setting composer '{type.FullName}' must be a non-abstract ProjectSettingComposer."); + $"Project setting composer '{type.FullName}' must be a non-abstract ProjectSettingComposer." + ); } if (!types.CanCreateInstance(typeRef)) { throw new InvalidOperationException( - $"Project setting composer '{type.FullName}' requires a factory in the current type catalog."); + $"Project setting composer '{type.FullName}' requires a factory in the current type catalog." + ); } ProjectSettingComposerAttribute attribute = types.GetAttribute(typeRef, inherit: false)!; if (!settingTypes.TryGetValue(attribute.settingId, out var setting)) { throw new InvalidOperationException( - $"Project setting composer '{type.FullName}' targets undefined setting '{attribute.settingId}'."); + $"Project setting composer '{type.FullName}' targets undefined setting '{attribute.settingId}'." + ); } var composer = OwnCandidateExtension((ProjectSettingComposer)types.CreateInstance(type)); if (composer.settingType != setting.runtimeType) { throw new InvalidOperationException( - $"Project setting composer '{type.FullName}' expects '{composer.settingType.FullName}', " + - $"but '{attribute.settingId}' is '{setting.runtimeType.FullName}'."); + $"Project setting composer '{type.FullName}' expects '{composer.settingType.FullName}', " + + $"but '{attribute.settingId}' is '{setting.runtimeType.FullName}'." + ); } if (!composers.TryAdd(attribute.settingId, composer)) { throw new InvalidOperationException( - $"Project setting '{attribute.settingId}' declares more than one composer."); + $"Project setting '{attribute.settingId}' declares more than one composer." + ); } } @@ -89,8 +98,16 @@ protected override Snapshot Build(TypeCacheSnapshot types) foreach ((ProjectSettingId id, (Guid stableTypeId, Type runtimeType, bool allowPluginContributions)) in settingTypes) { composers.TryGetValue(id, out ProjectSettingComposer? composer); - definitions.Add(id, new Definition(stableTypeId, runtimeType, composer, allowPluginContributions, - () => (ISerializable)types.CreateInstance(runtimeType))); + definitions.Add( + id, + new Definition( + stableTypeId, + runtimeType, + composer, + allowPluginContributions, + () => (ISerializable)types.CreateInstance(runtimeType) + ) + ); } return new Snapshot(types.version, definitions.ToFrozenDictionary()); } diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsStore.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsStore.cs index 6d9cdbfe8..b6fe60eb2 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingsStore.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsStore.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Extensibility.Types; -using Inno.Extensibility.Reload; +using Inno.Core.IO; using Inno.Core.Serialization; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; using Inno.Scripting.Api; -using Inno.Core.IO; namespace Inno.Core.Settings; @@ -19,6 +19,7 @@ public sealed class ProjectSettingsStore : IDisposable, IProjectSettingsLookup private IReadOnlyList m_contributors = []; private ProjectSettings? m_current; private long m_revision; + /// /// Gets the unique, non-persistent lifetime identity used with the effective snapshot revision. /// @@ -70,7 +71,9 @@ public IReadOnlyList unavailableSettings get { lock (m_sync) + { return RequireCurrent().GetUnavailable(m_contributors); + } } } @@ -108,7 +111,9 @@ public bool isInitialized get { lock (m_sync) + { return m_current is not null; + } } } @@ -125,7 +130,9 @@ public long revision get { lock (m_sync) + { return m_revision; + } } } @@ -163,7 +170,9 @@ public TSetting Get(ProjectSettingId id) where TSetting : class, ISerializable { lock (m_sync) + { return RequireCurrent().Get(id); + } } /// @@ -184,8 +193,7 @@ public TSetting Get(ProjectSettingId id) public bool TryGet( ProjectSettingId id, out TSetting? setting - ) - where TSetting : class, ISerializable + ) where TSetting : class, ISerializable { lock (m_sync) { @@ -211,7 +219,9 @@ out TSetting? setting public bool HasProjectOverride(ProjectSettingId id) { lock (m_sync) + { return RequireCurrent().HasProjectOverride(id); + } } /// @@ -254,7 +264,8 @@ out ProjectSettingRecord record declaredDependencies, declaredOverrides, m_contributors, - out record); + out record + ); } } @@ -324,7 +335,9 @@ out ISerializable? setting public byte[] CaptureDocument() { lock (m_sync) + { return RequireCurrent().CaptureDocument(); + } } /// @@ -430,7 +443,9 @@ public bool ApplyProjectOverrides( { bool changed = RequireCurrent().ApplyProjectOverrides(values, resets, m_contributors); if (changed) + { m_revision++; + } return changed; } } @@ -478,6 +493,7 @@ public void Dispose() private ProjectSettings RequireCurrent() => m_current ?? throw new InvalidOperationException("ProjectSettingsStore is not initialized."); + private sealed class SettingsChange(ProjectSettingsStore owner) : IGenerationChange { private ProjectSettingRecord[]? m_previous; @@ -492,7 +508,9 @@ public void PrepareForActivation() lock (owner.m_sync) { if (m_previous is not null) + { throw new InvalidOperationException("Settings change was already prepared."); + } m_previous = owner.RequireCurrent().CaptureEffective(); m_contributors = owner.m_contributors.ToArray(); m_revision = owner.m_revision; @@ -505,7 +523,9 @@ public void PrepareForActivation() public void Apply() { if (m_previous is null) + { throw new InvalidOperationException("Settings change was not prepared."); + } owner.RebuildCurrent(allowUnresolvedContributions: true); } @@ -521,7 +541,7 @@ public void Complete() /// /// Restores the state that existed before candidate activation began. /// - public void RollbackStructure() { } + public void RollbackStructure() {} /// /// Restores the state that existed before candidate activation began. @@ -529,7 +549,9 @@ public void RollbackStructure() { } public void RestorePreviousState() { if (m_previous is null) + { return; + } lock (owner.m_sync) { owner.RequireCurrent().RestoreEffective(m_previous); diff --git a/src/foundation/core/Inno.Core.Settings/Properties/ScriptingApi.cs b/src/foundation/core/Inno.Core.Settings/Properties/ScriptingApi.cs index e54f13a3a..14c3912c4 100644 --- a/src/foundation/core/Inno.Core.Settings/Properties/ScriptingApi.cs +++ b/src/foundation/core/Inno.Core.Settings/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ -using Inno.Scripting.Api; using Inno.Core.Settings; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Settings", - "Inno.Core.Settings", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Settings", "Inno.Core.Settings", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ProjectSettingId), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(ProjectId), ScriptingApiScope.Runtime)] diff --git a/src/foundation/core/Inno.Core.Settings/Settings.cs b/src/foundation/core/Inno.Core.Settings/Settings.cs index 34989670a..3c5884851 100644 --- a/src/foundation/core/Inno.Core.Settings/Settings.cs +++ b/src/foundation/core/Inno.Core.Settings/Settings.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Serialization; namespace Inno.Core.Settings; @@ -65,7 +64,7 @@ public static class Settings /// public static TSetting Get(ProjectSettingId id) where TSetting : class, ISerializable - => ProjectSettingsExecutionContext.current.Get(id); + => ProjectSettingsExecutionContext.current.Get(id); /// /// Tries to get an isolated effective setting from the current extension generation. @@ -89,7 +88,6 @@ public static TSetting Get(ProjectSettingId id) public static bool TryGet( ProjectSettingId id, out TSetting? setting - ) - where TSetting : class, ISerializable + ) where TSetting : class, ISerializable => ProjectSettingsExecutionContext.current.TryGet(id, out setting); } diff --git a/src/foundation/core/Inno.Core.Settings/SettingsDocumentStore.cs b/src/foundation/core/Inno.Core.Settings/SettingsDocumentStore.cs index 694c8c185..b81c7e545 100644 --- a/src/foundation/core/Inno.Core.Settings/SettingsDocumentStore.cs +++ b/src/foundation/core/Inno.Core.Settings/SettingsDocumentStore.cs @@ -1,6 +1,5 @@ using System; using System.IO; - using Inno.Core.IO; using Inno.Core.Serialization; @@ -47,7 +46,7 @@ public SettingsDocumentStore( m_document = document; m_serialization = serialization; m_createDefault = createDefault; - m_validate = validate ?? (static _ => { }); + m_validate = validate ?? (static _ => {}); } /// @@ -87,7 +86,8 @@ public TDocument Load() public TDocument LoadRequired() { byte[] data = m_document.Read() ?? throw new InvalidDataException( - $"Required settings document '{documentName}' does not exist."); + $"Required settings document '{documentName}' does not exist." + ); return Deserialize(data); } @@ -138,13 +138,14 @@ public TDocument Deserialize(ReadOnlySpan data) return document; } catch (Exception exception) when (exception is ArgumentException - or InvalidDataException - or InvalidOperationException - or NotSupportedException) + or InvalidDataException + or InvalidOperationException + or NotSupportedException) { throw new InvalidDataException( $"Settings document '{documentName}' is not a valid current-format {typeof(TDocument).Name}.", - exception); + exception + ); } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs index 53a298bed..5c2a682a3 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Execution; namespace Inno.Extensibility.Modules; @@ -18,9 +17,9 @@ internal CatalogParticipantRegistration Register(IAssemblyCatalogParticipant par { RemoveCollectedParticipants(); var registration = new CatalogParticipantRegistration(this, Guid.NewGuid()); - m_participants.Add(new ParticipantReference( - registration.id, - new WeakReference(participant))); + m_participants.Add( + new ParticipantReference(registration.id, new WeakReference(participant)) + ); return registration; } } @@ -39,7 +38,9 @@ internal AssemblyCatalogRefreshSet Prepare(AssemblyCatalogSnapshot catalog) foreach (ParticipantReference registration in m_participants) { if (registration.participant.TryGetTarget(out IAssemblyCatalogParticipant? participant)) + { participants.Add(participant); + } } } @@ -47,7 +48,9 @@ internal AssemblyCatalogRefreshSet Prepare(AssemblyCatalogSnapshot catalog) try { foreach (IAssemblyCatalogParticipant participant in participants) + { transactions.Add(participant.Prepare(catalog)); + } return new AssemblyCatalogRefreshSet(transactions); } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) @@ -67,7 +70,10 @@ internal AssemblyCatalogRefreshSet Prepare(AssemblyCatalogSnapshot catalog) } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { - m_retirementFailure = new AggregateException("Catalog preparation failed and rollback remains pending.", [.. failures, failure]); + m_retirementFailure = new AggregateException( + "Catalog preparation failed and rollback remains pending.", + [.. failures, failure] + ); m_retainedPreparation = (participants, transactions); throw m_retirementFailure; } @@ -77,7 +83,9 @@ internal AssemblyCatalogRefreshSet Prepare(AssemblyCatalogSnapshot catalog) } } if (failures.Count > 1) + { throw new AggregateException("Assembly catalog preparation and rollback failed.", failures); + } throw; } } @@ -85,7 +93,9 @@ internal AssemblyCatalogRefreshSet Prepare(AssemblyCatalogSnapshot catalog) internal void Unregister(Guid registrationId) { lock (m_sync) + { m_participants.RemoveAll(registration => registration.id == registrationId); + } } private void RemoveCollectedParticipants() @@ -112,7 +122,9 @@ Guid id public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; owner.Unregister(id); } @@ -132,7 +144,9 @@ internal IReadOnlyList contexts foreach (IAssemblyCatalogTransaction transaction in transactions) { if (transaction.context is not null) + { result.Add(transaction.context); + } } return result; } @@ -141,13 +155,19 @@ internal IReadOnlyList contexts internal void Activate() { if (m_failure is not null) + { throw m_failure; + } if (m_finished) + { throw new InvalidOperationException("Assembly catalog refresh set is already finished."); + } try { for (; m_activatedCount < transactions.Count; m_activatedCount++) + { transactions[m_activatedCount].Activate(); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { @@ -162,9 +182,15 @@ internal void Activate() } catch (Exception rollbackFailure) { - var combined = new AggregateException("Assembly catalog activation and rollback failed.", activationFailure, rollbackFailure); + var combined = new AggregateException( + "Assembly catalog activation and rollback failed.", + activationFailure, + rollbackFailure + ); if (RetirementPendingException.Find(combined) is not null) + { m_failure = combined; + } throw combined; } throw; @@ -174,31 +200,47 @@ internal void Activate() internal void Complete() { if (m_failure is not null) + { throw m_failure; + } if (m_finished) + { return; + } List failures = []; for (int i = 0; i < transactions.Count; i++) + { TryCleanup(transactions[i].Complete, failures); + } m_finished = true; transactions = Array.Empty(); if (failures.Count > 0) + { throw new AggregateException("Assembly catalog completion failed after all participants were attempted.", failures); + } } internal void Rollback() { if (m_failure is not null) + { throw m_failure; + } if (m_finished) + { return; + } List failures = []; for (int i = transactions.Count - 1; i >= 0; i--) + { TryCleanup(transactions[i].Rollback, failures); + } m_finished = true; transactions = Array.Empty(); if (failures.Count > 0) + { throw new AggregateException("Assembly catalog rollback failed after all participants were attempted.", failures); + } } private void TryCleanup( @@ -212,9 +254,13 @@ List failures catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { m_failure = failures.Count == 0 ? failure : new AggregateException( - "Catalog cleanup remains pending after earlier failures.", [.. failures, failure]); + "Catalog cleanup remains pending after earlier failures.", + [.. failures, failure] + ); if (ReferenceEquals(m_failure, failure)) + { throw; + } throw m_failure; } catch (Exception exception) diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs index c44defcaa..50e05c064 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs @@ -10,8 +10,10 @@ namespace Inno.Extensibility.Modules; internal sealed class CompositeAssemblyUnloadProbe : IAssemblyUnloadProbe { private readonly IAssemblyUnloadProbe[] m_children; + internal CompositeAssemblyUnloadProbe(IReadOnlyList children) => m_children = children.ToArray(); + /// public string description => string.Join(", ", m_children.Select(static child => child.description)); diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IAssemblyCatalogSource.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IAssemblyCatalogSource.cs index 15189de8e..938e41291 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IAssemblyCatalogSource.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IAssemblyCatalogSource.cs @@ -16,6 +16,7 @@ public interface IAssemblyCatalogSource : IDisposable /// Notifies the owner that the host assembly snapshot should be refreshed at a safe point. /// event Action? changed; + /// /// Gets the complete host assemblies that participate in extension discovery. /// @@ -23,6 +24,7 @@ public interface IAssemblyCatalogSource : IDisposable /// The current host snapshot; the caller must not retain it beyond its catalog generation. /// IReadOnlyList GetAssemblies(); + /// /// Gets host contracts and framework assemblies available to candidate modules. /// @@ -30,6 +32,7 @@ public interface IAssemblyCatalogSource : IDisposable /// A snapshot of shareable assemblies owned by the host implementation. /// IReadOnlyList GetSharedAssemblies(); + /// /// Determines whether a referenced simple name belongs to the selected managed framework. /// @@ -40,6 +43,7 @@ public interface IAssemblyCatalogSource : IDisposable /// Whether the framework owns this dependency. /// bool IsFrameworkReference(string assemblyName); + /// /// Determines whether an assembly is a framework contract rather than a contributed module. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IModuleSource.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IModuleSource.cs index 15456a3c5..d94cdd44c 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IModuleSource.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/IModuleSource.cs @@ -16,26 +16,32 @@ public interface IModuleSource /// Gets the stable logical name used by dependency ordering and replacement transactions. /// string moduleName { get; } + /// /// Gets the ownership domain of the contribution. /// AssemblyDomain domain { get; } + /// /// Gets the default dependency scope of contributed assemblies. /// AssemblyScope scope { get; } + /// /// Gets whether retirement can release this source's code generation. /// bool collectible { get; } + /// /// Gets the explicit logical upstream module names. /// IReadOnlyList upstreamModuleNames { get; } + /// /// Gets explicit scope overrides keyed by contributed assembly simple name. /// IReadOnlyDictionary assemblyScopes { get; } + /// /// Reads the complete owned assembly identities before any generation is acquired. /// @@ -43,6 +49,7 @@ public interface IModuleSource /// Distinct, nonempty simple names; invalid or unavailable source data causes an exception. /// IReadOnlyList GetAssemblyNames(); + /// /// Acquires a validated candidate and transfers its lifetime to the caller on success. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleCatalogContribution.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleCatalogContribution.cs index c40acbb8d..693094e3c 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleCatalogContribution.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleCatalogContribution.cs @@ -47,39 +47,48 @@ public ModuleCatalogContribution( ArgumentException.ThrowIfNullOrWhiteSpace(moduleName); ArgumentNullException.ThrowIfNull(assemblies); ArgumentNullException.ThrowIfNull(assemblyScopes); - if (assemblies.Count == 0 || assemblies.Any(static value => value is null || value.IsDynamic) || - assemblies.Distinct().Count() != assemblies.Count || - assemblies.Any(assembly => !assemblyScopes.ContainsKey(assembly)) || - assemblyScopes.Count != assemblies.Count) + if (assemblies.Count == 0 || assemblies.Any(static value => value is null || value.IsDynamic) + || assemblies.Distinct().Count() != assemblies.Count + || assemblies.Any(assembly => !assemblyScopes.ContainsKey(assembly)) + || assemblyScopes.Count != assemblies.Count + ) { throw new ArgumentException("A contribution requires distinct assemblies with complete scopes."); + } this.moduleName = moduleName; this.domain = domain; this.scope = scope; this.assemblies = Array.AsReadOnly(assemblies.ToArray()); this.assemblyScopes = new ReadOnlyDictionary( - assemblyScopes.ToDictionary(static pair => pair.Key, static pair => pair.Value)); + assemblyScopes.ToDictionary(static pair => pair.Key, static pair => pair.Value) + ); this.lifetime = lifetime; } + /// /// Gets the stable module name. /// public string moduleName { get; } + /// /// Gets the ownership domain. /// public AssemblyDomain domain { get; } + /// /// Gets the default dependency scope. /// public AssemblyScope scope { get; } + /// /// Gets the immutable owned assembly set. /// public IReadOnlyList assemblies { get; } + /// /// Gets the complete per-assembly scope map. /// public IReadOnlyDictionary assemblyScopes { get; } + /// /// Gets the owned generation lifetime, or null for externally owned code. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleSourceContext.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleSourceContext.cs index f03009749..84e937a68 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleSourceContext.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/ModuleSourceContext.cs @@ -27,30 +27,40 @@ Action trackRetirement this.upstreamModules = Array.AsReadOnly(upstreamModules.ToArray()); this.activeModules = Array.AsReadOnly(activeModules.ToArray()); this.plannedAssemblies = new ReadOnlyDictionary( - plannedAssemblies.ToDictionary(static pair => pair.Key, static pair => pair.Value, - StringComparer.OrdinalIgnoreCase)); + plannedAssemblies.ToDictionary( + static pair => pair.Key, + static pair => pair.Value, + StringComparer.OrdinalIgnoreCase + ) + ); m_trackRetirement = trackRetirement; } + /// /// Gets the candidate generation number. /// public int generation { get; } + /// /// Gets the borrowed host contract source. /// public IAssemblyCatalogSource host { get; } + /// /// Gets the validated direct upstream contributions for this candidate. /// public IReadOnlyList upstreamModules { get; } + /// /// Gets active contributions used to reject forbidden downstream references. /// public IReadOnlyList activeModules { get; } + /// /// Gets identities and classifications for the complete candidate closure. /// public IReadOnlyDictionary plannedAssemblies { get; } + /// /// Transfers a failed acquisition's non-owning retirement probe to the shared generation gate. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyDomain.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyDomain.cs index 5f4f71f32..aa14ee65d 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyDomain.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyDomain.cs @@ -9,12 +9,10 @@ public enum AssemblyDomain /// The assembly is engine-owned and remains in the default load context. /// InnoInternal, - /// /// The assembly contains project scripting code in a collectible load context. /// InnoScripting, - /// /// The assembly belongs to the project's unified collectible plugin generation. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyExtensions.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyExtensions.cs index 239f0caa8..2f29a988d 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyExtensions.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyExtensions.cs @@ -34,7 +34,8 @@ public static AssemblyDomain GetInnoAssemblyDomain(this Assembly assembly) ArgumentNullException.ThrowIfNull(assembly); AssemblyClassification classification = GetClassification(assembly); return classification.domain ?? throw new InvalidOperationException( - $"Assembly '{assembly.GetName().Name}' has no valid {C_ASSEMBLY_DOMAIN_KEY} metadata."); + $"Assembly '{assembly.GetName().Name}' has no valid {C_ASSEMBLY_DOMAIN_KEY} metadata." + ); } /// @@ -57,7 +58,8 @@ public static AssemblyScope GetInnoAssemblyScope(this Assembly assembly) ArgumentNullException.ThrowIfNull(assembly); AssemblyClassification classification = GetClassification(assembly); return classification.scope ?? throw new InvalidOperationException( - $"Assembly '{assembly.GetName().Name}' has no valid {C_ASSEMBLY_SCOPE_KEY} metadata."); + $"Assembly '{assembly.GetName().Name}' has no valid {C_ASSEMBLY_SCOPE_KEY} metadata." + ); } /// @@ -108,12 +110,14 @@ private static AssemblyClassification ResolveClassification(Assembly assembly) if (string.Equals(metadata.Key, C_ASSEMBLY_DOMAIN_KEY, StringComparison.Ordinal)) { if (Enum.TryParse(metadata.Value, ignoreCase: false, out AssemblyDomain parsedDomain)) + { domain = parsedDomain; + } continue; } - if (string.Equals(metadata.Key, C_ASSEMBLY_SCOPE_KEY, StringComparison.Ordinal) && - Enum.TryParse(metadata.Value, ignoreCase: false, out AssemblyScope parsedScope)) - { + if (string.Equals(metadata.Key, C_ASSEMBLY_SCOPE_KEY, StringComparison.Ordinal) + && Enum.TryParse(metadata.Value, ignoreCase: false, out AssemblyScope parsedScope) + ) { scope = parsedScope; } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyScope.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyScope.cs index d6dcc7aad..5f42eac7e 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyScope.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Metadata/AssemblyScope.cs @@ -9,7 +9,6 @@ public enum AssemblyScope /// The assembly is available to runtime and editor consumers. /// Runtime, - /// /// The assembly is available only to editor consumers. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs index 1b9a29a35..bb8582587 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs @@ -4,7 +4,6 @@ using System.IO; using System.Linq; using System.Reflection; - using Inno.Core.Collections; using Inno.Core.Execution; using Inno.Extensibility.Reload; @@ -124,7 +123,8 @@ public IDisposable RegisterCatalogParticipant(IAssemblyCatalogParticipant partic Trace.TraceError( "Assembly catalog participant '{0}' failed during initial cleanup: {1}", participant.GetType().FullName, - exception); + exception + ); throw; } return registration; @@ -151,7 +151,8 @@ public IDisposable RegisterCatalogParticipant(IAssemblyCatalogParticipant partic Trace.TraceError( "Assembly catalog participant '{0}' failed during initial rollback: {1}", participant.GetType().FullName, - exception); + exception + ); } registration.Dispose(); throw; @@ -177,7 +178,9 @@ public AssemblyModuleHandle Load(IModuleSource request) EnsureNoReloadInProgress(); ValidateUniqueModuleName(request.moduleName); if (request.domain != AssemblyDomain.InnoPlugin) + { ValidateUniqueReloadBoundary(request.domain, request.scope); + } AssemblyModuleHandle handle = new(Guid.NewGuid()); IReadOnlyDictionary plannedAssemblies = @@ -187,7 +190,8 @@ public AssemblyModuleHandle Load(IModuleSource request) request, generation: 1, upstreamModules: GetUpstreamModules(request, []), - plannedAssemblies); + plannedAssemblies + ); m_modules.Add(handle, module); try { @@ -220,12 +224,18 @@ public AssemblyModuleHandle Register( IReadOnlyList assemblies ) { if (string.IsNullOrWhiteSpace(moduleName)) + { throw new ArgumentException("Module name is required.", nameof(moduleName)); + } ArgumentNullException.ThrowIfNull(assemblies); if (assemblies.Count == 0) + { throw new ArgumentException("At least one assembly is required.", nameof(assemblies)); + } if (assemblies.Any(static assembly => assembly is null || assembly.IsDynamic)) + { throw new ArgumentException("External modules must contain non-dynamic assemblies.", nameof(assemblies)); + } lock (m_sync) { @@ -233,19 +243,20 @@ IReadOnlyList assemblies EnsureNoReloadInProgress(); ValidateUniqueModuleName(moduleName); - if (!assemblies[0].TryGetInnoAssemblyClassification( - out AssemblyDomain domain, - out AssemblyScope scope) || - assemblies.Any(assembly => + if (!assemblies[0].TryGetInnoAssemblyClassification(out AssemblyDomain domain, out AssemblyScope scope) + || assemblies.Any(assembly => ( !assembly.TryGetInnoAssemblyClassification( out AssemblyDomain candidateDomain, - out AssemblyScope candidateScope) || - candidateDomain != domain || - candidateScope != scope)) - { + out AssemblyScope candidateScope + ) + || candidateDomain != domain + || candidateScope != scope + )) + ) { throw new ArgumentException( "Every externally owned module assembly must declare the same valid domain and scope metadata.", - nameof(assemblies)); + nameof(assemblies) + ); } AssemblyModuleHandle handle = new(Guid.NewGuid()); @@ -260,9 +271,13 @@ IReadOnlyList assemblies scope = scope, assemblies = assemblies.Distinct().ToArray(), assemblyScopes = assemblies.Distinct().ToDictionary(static assembly => assembly, _ => scope), - contribution = new ModuleCatalogContribution(moduleName, domain, scope, + contribution = new ModuleCatalogContribution( + moduleName, + domain, + scope, assemblies.Distinct().ToArray(), - assemblies.Distinct().ToDictionary(static assembly => assembly, _ => scope)) + assemblies.Distinct().ToDictionary(static assembly => assembly, _ => scope) + ) }; m_modules.Add(handle, module); try @@ -300,19 +315,22 @@ IModuleSource request EnsureInitialized(); EnsureNoReloadInProgress(); if (!m_modules.TryGetValue(module, out AssemblyModuleEntry? previous)) + { throw new ArgumentException("The assembly module is not active.", nameof(module)); + } if (!string.Equals(previous.moduleName, request.moduleName, StringComparison.Ordinal)) { throw new ArgumentException( $"Reload request module name '{request.moduleName}' does not match '{previous.moduleName}'.", - nameof(request)); + nameof(request) + ); } return BeginReloadLocked( [request], removedModuleNames: [], - new Dictionary( - StringComparer.Ordinal) { [request.moduleName] = module }); + new Dictionary(StringComparer.Ordinal) { [request.moduleName] = module } + ); } } @@ -392,7 +410,9 @@ public IAssemblyUnloadProbe Unload(AssemblyModuleHandle module) EnsureNoReloadInProgress(); ValidateUnloadClosure([module]); if (!m_modules.Remove(module, out AssemblyModuleEntry? removed)) + { throw new ArgumentException("The assembly module is not active.", nameof(module)); + } try { RebuildLocked(); @@ -430,17 +450,23 @@ public IAssemblyUnloadProbe Unload(IReadOnlyList modules) EnsureInitialized(); EnsureNoReloadInProgress(); if (modules.Distinct().Count() != modules.Count) + { throw new ArgumentException("Module handles must be distinct.", nameof(modules)); + } ValidateUnloadClosure(modules); var removed = new List(modules.Count); foreach (AssemblyModuleHandle handle in modules) { if (!m_modules.TryGetValue(handle, out AssemblyModuleEntry? module)) + { throw new ArgumentException("An assembly module is not active.", nameof(modules)); + } removed.Add(module); } foreach (AssemblyModuleEntry module in removed) + { m_modules.Remove(module.handle); + } try { RebuildLocked(); @@ -448,19 +474,23 @@ public IAssemblyUnloadProbe Unload(IReadOnlyList modules) catch { foreach (AssemblyModuleEntry module in removed) + { m_modules.Add(module.handle, module); + } throw; } AssemblyModuleEntry[] unloadOrder = removed - .OrderByDescending(static module => module.domain == AssemblyDomain.InnoPlugin + .OrderByDescending(static module => ( + module.domain == AssemblyDomain.InnoPlugin ? 0 - : module.scope == AssemblyScope.Runtime ? 1 : 2) + : module.scope == AssemblyScope.Runtime ? 1 : 2 + )) .ToArray(); var monitors = unloadOrder.Select(BeginUnload).ToArray(); return monitors.Length == 1 - ? monitors[0] - : new CompositeAssemblyUnloadProbe(monitors); + ? monitors[0] + : new CompositeAssemblyUnloadProbe(monitors); } } @@ -509,7 +539,9 @@ public void Rebuild() public void Dispose() { lock (m_sync) + { ShutdownLocked(); + } GC.SuppressFinalize(this); } @@ -519,12 +551,18 @@ internal void Activate(ReloadState state) { EnsureActiveState(state); if (state.activated) + { return; + } foreach (AssemblyModuleEntry removed in state.removedModules) + { m_modules.Remove(removed.handle); + } for (int i = 0; i < state.candidateModules.Length; i++) + { m_modules[state.candidateModules[i].handle] = state.candidateModules[i]; + } m_currentCatalog = state.candidateCatalog; try { @@ -543,7 +581,9 @@ internal void Activate(ReloadState state) state.finished = true; m_reloadInProgress = false; if (activationFailure is AggregateException) + { generations.Fault(activationFailure); + } try { state.refresh.Rollback(); @@ -562,7 +602,9 @@ internal void Activate(ReloadState state) finally { if (m_retirementFailure is null) + { BeginUnloadReverse(state.candidateModules); + } } throw; } @@ -575,7 +617,9 @@ internal IAssemblyUnloadProbe Complete(ReloadState state) { EnsureActiveState(state); if (!state.activated) + { throw new InvalidOperationException("The reload session must be activated before completion."); + } state.finished = true; m_reloadInProgress = false; @@ -599,9 +643,15 @@ internal IAssemblyUnloadProbe Complete(ReloadState state) .OfType() .Concat(state.removedModules) .Distinct() - .ToArray()); + .ToArray() + ); if (cleanupFailure is not null) - throw new InvalidOperationException("The module generation committed but retirement failed; restart the host.", cleanupFailure); + { + throw new InvalidOperationException( + "The module generation committed but retirement failed; restart the host.", + cleanupFailure + ); + } return monitor; } } @@ -612,7 +662,9 @@ internal void Rollback(ReloadState state) { EnsureRetirementSafe(); if (state.finished) + { return; + } if (state.activated) { RestorePreviousModules(state); @@ -638,7 +690,9 @@ internal void Rollback(ReloadState state) finally { if (m_retirementFailure is null) + { BeginUnloadReverse(state.candidateModules); + } } } } @@ -649,29 +703,36 @@ private AssemblyReloadSession BeginReloadLocked( IReadOnlyDictionary? forcedHandles ) { if (requests.Count == 0 && removedModuleNames.Count == 0) + { throw new ArgumentException("At least one module change is required.", nameof(requests)); + } if (requests.Any(static request => request is null)) + { throw new ArgumentException("Module reload requests cannot contain null entries.", nameof(requests)); + } IModuleSource[] orderedRequests = OrderReloadRequests(requests); - if (orderedRequests.Select(static request => request.moduleName).Distinct(StringComparer.Ordinal).Count() != - orderedRequests.Length) - { + if (orderedRequests.Select(static request => request.moduleName).Distinct(StringComparer.Ordinal).Count() + != orderedRequests.Length + ) { throw new ArgumentException("A reload plan cannot contain duplicate module names.", nameof(requests)); } - if (removedModuleNames.Any(static name => string.IsNullOrWhiteSpace(name)) || - removedModuleNames.Distinct(StringComparer.Ordinal).Count() != removedModuleNames.Count) - { + if (removedModuleNames.Any(static name => string.IsNullOrWhiteSpace(name)) + || removedModuleNames.Distinct(StringComparer.Ordinal).Count() != removedModuleNames.Count + ) { throw new ArgumentException("Removed module names must be non-empty and distinct.", nameof(removedModuleNames)); } if (orderedRequests.Any(request => removedModuleNames.Contains(request.moduleName, StringComparer.Ordinal))) + { throw new ArgumentException("A module cannot be replaced and removed together.", nameof(removedModuleNames)); + } AssemblyModuleEntry[] removedModules = removedModuleNames.Select(name => { AssemblyModuleEntry? module = m_modules.Values.SingleOrDefault(candidate => string.Equals(candidate.moduleName, name, StringComparison.Ordinal)); return module ?? throw new ArgumentException( $"Removed assembly module '{name}' is not active.", - nameof(removedModuleNames)); + nameof(removedModuleNames) + ); }).ToArray(); ValidateReloadClosure(orderedRequests, removedModules); IReadOnlyDictionary plannedAssemblies = @@ -696,7 +757,8 @@ private AssemblyReloadSession BeginReloadLocked( AssemblyCatalogSnapshot previousCatalog = m_currentCatalog; AssemblyCatalogSnapshot candidateCatalog = BuildCatalog( replacements, - removedModules.Select(static module => module.handle).ToHashSet()); + removedModules.Select(static module => module.handle).ToHashSet() + ); AssemblyCatalogRefreshSet refresh = m_catalogs.Prepare(candidateCatalog); m_reloadInProgress = true; return new AssemblyReloadSession(this, new ReloadState @@ -726,15 +788,22 @@ private AssemblyReloadSession BeginReloadLocked( IReadOnlyDictionary? forcedHandles ) { if (forcedHandles is not null && forcedHandles.TryGetValue(request.moduleName, out AssemblyModuleHandle handle)) + { return m_modules[handle]; + } AssemblyModuleEntry? previous = m_modules.Values.SingleOrDefault(module => string.Equals(module.moduleName, request.moduleName, StringComparison.Ordinal)); if (previous is null && request.domain != AssemblyDomain.InnoPlugin) + { ValidateUniqueReloadBoundary(request.domain, request.scope); - else if (previous is not null && - (previous.domain != request.domain || previous.scope != request.scope)) + } + else if (previous is not null + && (previous.domain != request.domain || previous.scope != request.scope) + ) { throw new InvalidOperationException( - $"Module '{request.moduleName}' cannot change its domain or scope across generations."); + $"Module '{request.moduleName}' cannot change its domain or scope across generations." + ); + } return previous; } @@ -746,17 +815,21 @@ IReadOnlyList stagedCandidates .Where(active => stagedCandidates.All(candidate => candidate.handle != active.handle)) .Concat(stagedCandidates); if (request.upstreamModuleNames.Count == 0) + { return []; + } Dictionary byName = effectiveModules.ToDictionary( static module => module.moduleName, - StringComparer.Ordinal); + StringComparer.Ordinal + ); return request.upstreamModuleNames.Select(name => { if (!byName.TryGetValue(name, out AssemblyModuleEntry? module)) { throw new InvalidOperationException( - $"Module '{request.moduleName}' requires unavailable upstream module '{name}'."); + $"Module '{request.moduleName}' requires unavailable upstream module '{name}'." + ); } return module; }).ToArray(); @@ -764,18 +837,19 @@ IReadOnlyList stagedCandidates private int GetReloadOrder(IModuleSource request) => request.domain switch - { - AssemblyDomain.InnoPlugin => 0, - AssemblyDomain.InnoScripting when request.scope == AssemblyScope.Runtime => 1, - AssemblyDomain.InnoScripting => 2, - _ => throw new ArgumentException("InnoInternal assemblies cannot be loaded into a collectible module.") - }; + { + AssemblyDomain.InnoPlugin => 0, + AssemblyDomain.InnoScripting when request.scope == AssemblyScope.Runtime => 1, + AssemblyDomain.InnoScripting => 2, + _ => throw new ArgumentException("InnoInternal assemblies cannot be loaded into a collectible module.") + }; private IModuleSource[] OrderReloadRequests(IReadOnlyList requests) { Dictionary byName = requests.ToDictionary( static request => request.moduleName, - StringComparer.Ordinal); + StringComparer.Ordinal + ); IComparer ordering = Comparer.Create(( left, right @@ -783,23 +857,26 @@ private IModuleSource[] OrderReloadRequests(IReadOnlyList request { int domainOrder = GetReloadOrder(byName[left]).CompareTo(GetReloadOrder(byName[right])); return domainOrder != 0 - ? domainOrder - : StringComparer.Ordinal.Compare(left, right); + ? domainOrder + : StringComparer.Ordinal.Compare(left, right); }); var graph = new DependencyGraph(StringComparer.Ordinal, ordering); foreach (IModuleSource request in requests) { graph.AddNode(request.moduleName); foreach (string dependencyName in request.upstreamModuleNames - .OrderBy(static value => value, StringComparer.Ordinal)) - { + .OrderBy(static value => value, StringComparer.Ordinal) + ) { if (!byName.TryGetValue(dependencyName, out IModuleSource? dependency)) + { continue; + } if (GetReloadOrder(dependency) > GetReloadOrder(request)) { throw new ArgumentException( $"Module '{request.moduleName}' cannot depend on downstream module '{dependencyName}'.", - nameof(requests)); + nameof(requests) + ); } graph.AddDependency(request.moduleName, dependencyName); } @@ -821,12 +898,18 @@ private void RestorePreviousModules(ReloadState state) AssemblyModuleEntry candidate = state.candidateModules[i]; AssemblyModuleEntry? previous = state.previousModules[i]; if (previous is null) + { m_modules.Remove(candidate.handle); + } else + { m_modules[candidate.handle] = previous; + } } foreach (AssemblyModuleEntry removed in state.removedModules) + { m_modules[removed.handle] = removed; + } m_currentCatalog = state.previousCatalog; } @@ -843,7 +926,9 @@ private void RebuildLocked(bool deferWhileBusy = false) { m_hostCatalogDirty = true; if (deferWhileBusy) + { return; + } throw new InvalidOperationException("Catalog publication is blocked by a generation owner operation."); } using IDisposable publication = reservation!; @@ -870,7 +955,8 @@ private void RebuildOnceLocked() try { AssemblyCatalogSnapshot candidate = BuildCatalog( - new Dictionary()); + new Dictionary() + ); AssemblyCatalogRefreshSet refresh = m_catalogs.Prepare(candidate); m_currentCatalog = candidate; bool activated = false; @@ -888,7 +974,9 @@ private void RebuildOnceLocked() catch (Exception failure) { if (activated) + { generations.Fault(failure); + } else { m_currentCatalog = previous; @@ -914,7 +1002,9 @@ private void RebuildOnceLocked() catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { if (m_retirementFailure is null) + { RetainFailedRetirement(failure, (m_catalogs, previous)); + } throw; } } @@ -940,11 +1030,6 @@ IReadOnlySet removed return host.Concat(moduleAssemblies).Distinct().ToArray(); } - - - - - private AssemblyModuleEntry StageModule( AssemblyModuleHandle handle, IModuleSource source, @@ -954,34 +1039,50 @@ IReadOnlyDictionary plannedAssemblies ) { ValidateRequest(source); var context = new ModuleSourceContext( - generation, m_options.catalogSource, + generation, + m_options.catalogSource, upstreamModules.Select(static module => module.contribution).ToArray(), m_modules.Values.Select(static module => module.contribution).ToArray(), - plannedAssemblies.ToDictionary(static pair => pair.Key, + plannedAssemblies.ToDictionary( + static pair => pair.Key, static pair => new ModuleAssemblyDescriptor(pair.Value.domain, pair.Value.scope), - StringComparer.OrdinalIgnoreCase), - generations.TrackRetirement); + StringComparer.OrdinalIgnoreCase + ), + generations.TrackRetirement + ); ModuleCatalogContribution contribution = source.Prepare(context); try { - if (contribution.moduleName != source.moduleName || contribution.domain != source.domain || - contribution.scope != source.scope || (contribution.lifetime is not null) != source.collectible) + if (contribution.moduleName != source.moduleName || contribution.domain != source.domain + || contribution.scope != source.scope || (contribution.lifetime is not null) != source.collectible + ) { throw new InvalidOperationException("A module source changed its declared ownership during preparation."); + } foreach (Assembly assembly in contribution.assemblies) + { assembly.RegisterInnoAssemblyClassification(contribution.domain, contribution.assemblyScopes[assembly]); + } return new AssemblyModuleEntry { - handle = handle, moduleName = source.moduleName, generation = generation, - externallyOwned = contribution.lifetime is null, collectible = source.collectible, - domain = source.domain, scope = source.scope, assemblies = contribution.assemblies.ToArray(), - assemblyScopes = contribution.assemblyScopes, upstreamModuleNames = source.upstreamModuleNames.ToArray(), + handle = handle, + moduleName = source.moduleName, + generation = generation, + externallyOwned = contribution.lifetime is null, + collectible = source.collectible, + domain = source.domain, + scope = source.scope, + assemblies = contribution.assemblies.ToArray(), + assemblyScopes = contribution.assemblyScopes, + upstreamModuleNames = source.upstreamModuleNames.ToArray(), contribution = contribution }; } catch { if (contribution.lifetime is not null) + { generations.TrackRetirement(contribution.lifetime.BeginRetirement()); + } throw; } } @@ -991,7 +1092,7 @@ IReadOnlyDictionary plannedAssemblies private IAssemblyUnloadProbe BeginUnload(AssemblyModuleEntry module) { IAssemblyUnloadProbe probe = module.contribution.lifetime?.BeginRetirement() - ?? new CompositeAssemblyUnloadProbe([]); + ?? new CompositeAssemblyUnloadProbe([]); generations.TrackRetirement(probe); return probe; } @@ -1000,30 +1101,37 @@ private IAssemblyUnloadProbe BeginUnloadReverse(IReadOnlyList(modules.Count); for (int i = modules.Count - 1; i >= 0; i--) + { monitors.Add(BeginUnload(modules[i])); + } return monitors.Count == 1 - ? monitors[0] - : new CompositeAssemblyUnloadProbe(monitors); + ? monitors[0] + : new CompositeAssemblyUnloadProbe(monitors); } - - private void ValidateRequest(IModuleSource request) { if (string.IsNullOrWhiteSpace(request.moduleName)) + { throw new ArgumentException("Module name is required.", nameof(request)); + } if (!Enum.IsDefined(request.domain) || request.domain == AssemblyDomain.InnoInternal) + { throw new ArgumentException("A reloadable module must belong to InnoPlugin or InnoScripting.", nameof(request)); + } if (!Enum.IsDefined(request.scope) || request.assemblyScopes.Values.Any(static scope => !Enum.IsDefined(scope))) - throw new ArgumentException("A reloadable module contains an invalid assembly scope.", nameof(request)); - if (request.upstreamModuleNames.Any(static name => string.IsNullOrWhiteSpace(name)) || - request.upstreamModuleNames.Distinct(StringComparer.Ordinal).Count() != - request.upstreamModuleNames.Count || - request.upstreamModuleNames.Contains(request.moduleName, StringComparer.Ordinal)) { + throw new ArgumentException("A reloadable module contains an invalid assembly scope.", nameof(request)); + } + if (request.upstreamModuleNames.Any(static name => string.IsNullOrWhiteSpace(name)) + || request.upstreamModuleNames.Distinct(StringComparer.Ordinal).Count() + != request.upstreamModuleNames.Count + || request.upstreamModuleNames.Contains(request.moduleName, StringComparer.Ordinal) + ) { throw new ArgumentException( "Upstream module names must be non-empty, distinct, and cannot reference the owning module.", - nameof(request)); + nameof(request) + ); } _ = request.GetAssemblyNames(); @@ -1041,26 +1149,31 @@ private IReadOnlyDictionary BuildPlannedAssemblyMap(IRe ownedNames.Add(name); AssemblyScope scope = request.assemblyScopes.GetValueOrDefault(name, request.scope); if (!result.TryAdd(name, new PlannedAssembly(request.domain, scope))) + { throw new InvalidDataException($"Reload plan contains duplicate managed assembly name '{name}'."); + } } string? unknownScope = request.assemblyScopes.Keys.FirstOrDefault(name => !ownedNames.Contains(name)); if (unknownScope is not null) { throw new InvalidDataException( - $"Module '{request.moduleName}' declares a scope for unknown assembly '{unknownScope}'."); + $"Module '{request.moduleName}' declares a scope for unknown assembly '{unknownScope}'." + ); } } return result; } - - private void ValidateUniqueModuleName(string moduleName) { if (string.IsNullOrWhiteSpace(moduleName)) + { throw new ArgumentException("Module name is required.", nameof(moduleName)); + } if (m_modules.Values.Any(module => string.Equals(module.moduleName, moduleName, StringComparison.Ordinal))) + { throw new InvalidOperationException($"Assembly module '{moduleName}' is already active."); + } } private void ValidateUniqueReloadBoundary( @@ -1068,11 +1181,12 @@ private void ValidateUniqueReloadBoundary( AssemblyScope scope ) { if (domain == AssemblyDomain.InnoPlugin) + { return; + } if (m_modules.Values.Any(module => module.domain == domain && module.scope == scope)) { - throw new InvalidOperationException( - $"Only one {scope} scripting module can be active."); + throw new InvalidOperationException($"Only one {scope} scripting module can be active."); } } @@ -1080,32 +1194,39 @@ private void ValidateReloadClosure( IReadOnlyList requests, IReadOnlyList removedModules ) { - bool reloadsPlugins = requests.Any(static request => request.domain == AssemblyDomain.InnoPlugin) || - removedModules.Any(static module => module.domain == AssemblyDomain.InnoPlugin); - bool reloadsRuntime = requests.Any(static request => - request.domain == AssemblyDomain.InnoScripting && - request.scope == AssemblyScope.Runtime) || - removedModules.Any(static module => - module.domain == AssemblyDomain.InnoScripting && - module.scope == AssemblyScope.Runtime); - bool reloadsEditor = requests.Any(static request => - request.domain == AssemblyDomain.InnoScripting && - request.scope == AssemblyScope.Editor) || - removedModules.Any(static module => - module.domain == AssemblyDomain.InnoScripting && - module.scope == AssemblyScope.Editor); - if (reloadsPlugins && m_modules.Values.Any(static module => module.domain == AssemblyDomain.InnoScripting) && - (!reloadsRuntime || !reloadsEditor)) - { + bool reloadsPlugins = requests.Any(static request => request.domain == AssemblyDomain.InnoPlugin) + || removedModules.Any(static module => module.domain == AssemblyDomain.InnoPlugin); + bool reloadsRuntime = requests.Any(static request => ( + request.domain == AssemblyDomain.InnoScripting + && request.scope == AssemblyScope.Runtime + )) + || removedModules.Any(static module => ( + module.domain == AssemblyDomain.InnoScripting + && module.scope == AssemblyScope.Runtime + )); + bool reloadsEditor = requests.Any(static request => ( + request.domain == AssemblyDomain.InnoScripting + && request.scope == AssemblyScope.Editor + )) + || removedModules.Any(static module => ( + module.domain == AssemblyDomain.InnoScripting + && module.scope == AssemblyScope.Editor + )); + if (reloadsPlugins && m_modules.Values.Any(static module => module.domain == AssemblyDomain.InnoScripting) + && (!reloadsRuntime || !reloadsEditor) + ) { throw new InvalidOperationException( - "Reloading plugins requires both dependent scripting modules in the same transaction."); + "Reloading plugins requires both dependent scripting modules in the same transaction." + ); } - if (reloadsRuntime && m_modules.Values.Any(static module => - module.domain == AssemblyDomain.InnoScripting && module.scope == AssemblyScope.Editor) && - !reloadsEditor) - { + if (reloadsRuntime && m_modules.Values.Any(static module => ( + module.domain == AssemblyDomain.InnoScripting && module.scope == AssemblyScope.Editor + )) + && !reloadsEditor + ) { throw new InvalidOperationException( - "Reloading runtime scripts requires the editor scripting module in the same transaction."); + "Reloading runtime scripts requires the editor scripting module in the same transaction." + ); } HashSet reloadedNames = requests .Select(static request => request.moduleName) @@ -1115,102 +1236,119 @@ IReadOnlyList removedModules .Where(static request => request.domain == AssemblyDomain.InnoPlugin) .Select(static request => request.moduleName) .ToHashSet(StringComparer.Ordinal); - reloadedPlugins.UnionWith(removedModules - .Where(static module => module.domain == AssemblyDomain.InnoPlugin) - .Select(static module => module.moduleName)); - string? omittedDependent = m_modules.Values.FirstOrDefault(module => - module.domain == AssemblyDomain.InnoPlugin && - !reloadedNames.Contains(module.moduleName) && - module.upstreamModuleNames.Any(reloadedPlugins.Contains))?.moduleName; + reloadedPlugins.UnionWith( + removedModules + .Where(static module => module.domain == AssemblyDomain.InnoPlugin) + .Select(static module => module.moduleName) + ); + string? omittedDependent = m_modules.Values.FirstOrDefault(module => ( + module.domain == AssemblyDomain.InnoPlugin + && !reloadedNames.Contains(module.moduleName) + && module.upstreamModuleNames.Any(reloadedPlugins.Contains) + ))?.moduleName; if (omittedDependent is not null) { throw new InvalidOperationException( - $"Reloading a Plugin module also requires dependent module '{omittedDependent}'."); + $"Reloading a Plugin module also requires dependent module '{omittedDependent}'." + ); } } private void ValidateUnloadClosure(IReadOnlyList handles) { var removed = handles.ToHashSet(); - bool removesPlugin = m_modules.Values.Any(module => - removed.Contains(module.handle) && module.domain == AssemblyDomain.InnoPlugin); - bool removesRuntime = m_modules.Values.Any(module => - removed.Contains(module.handle) && - module.domain == AssemblyDomain.InnoScripting && - module.scope == AssemblyScope.Runtime); - if (removesPlugin && m_modules.Values.Any(module => - !removed.Contains(module.handle) && module.domain == AssemblyDomain.InnoScripting)) - { + bool removesPlugin = m_modules.Values.Any(module => ( + removed.Contains(module.handle) && module.domain == AssemblyDomain.InnoPlugin + )); + bool removesRuntime = m_modules.Values.Any(module => ( + removed.Contains(module.handle) + && module.domain == AssemblyDomain.InnoScripting + && module.scope == AssemblyScope.Runtime + )); + if (removesPlugin && m_modules.Values.Any(module => ( + !removed.Contains(module.handle) && module.domain == AssemblyDomain.InnoScripting + )) + ) { throw new InvalidOperationException( - "Plugin unload requires all dependent scripting modules in the same transaction."); + "Plugin unload requires all dependent scripting modules in the same transaction." + ); } HashSet removedNames = m_modules.Values .Where(module => removed.Contains(module.handle)) .Select(static module => module.moduleName) .ToHashSet(StringComparer.Ordinal); - if (m_modules.Values.Any(module => - !removed.Contains(module.handle) && - module.upstreamModuleNames.Any(removedNames.Contains))) - { - throw new InvalidOperationException( - "A module cannot unload while an active module depends on it."); + if (m_modules.Values.Any(module => ( + !removed.Contains(module.handle) + && module.upstreamModuleNames.Any(removedNames.Contains) + )) + ) { + throw new InvalidOperationException("A module cannot unload while an active module depends on it."); } - if (removesRuntime && m_modules.Values.Any(module => - !removed.Contains(module.handle) && - module.domain == AssemblyDomain.InnoScripting && - module.scope == AssemblyScope.Editor)) - { + if (removesRuntime && m_modules.Values.Any(module => ( + !removed.Contains(module.handle) + && module.domain == AssemblyDomain.InnoScripting + && module.scope == AssemblyScope.Editor + )) + ) { throw new InvalidOperationException( - "Runtime scripting unload requires the editor scripting module in the same transaction."); + "Runtime scripting unload requires the editor scripting module in the same transaction." + ); } } private void EnsureInitialized() { if (!isInitialized) + { throw new InvalidOperationException("ModuleHost is not initialized."); + } } private void EnsureNoReloadInProgress() { generations.EnsureReady("change the module generation"); if (m_reloadInProgress) + { throw new InvalidOperationException("Another assembly reload transaction is already active."); + } } private void EnsureActiveState(ReloadState state) { EnsureRetirementSafe(); if (state.finished) + { throw new InvalidOperationException("The reload session is already finished."); + } if (!m_reloadInProgress) + { throw new InvalidOperationException("The reload session is no longer current."); + } for (int i = 0; i < state.candidateModules.Length; i++) { AssemblyModuleEntry candidate = state.candidateModules[i]; AssemblyModuleEntry? expected = state.activated ? candidate : state.previousModules[i]; bool exists = m_modules.TryGetValue(candidate.handle, out AssemblyModuleEntry? current); if (expected is null ? exists : !exists || !ReferenceEquals(current, expected)) + { throw new InvalidOperationException("The reload session is no longer current."); + } } foreach (AssemblyModuleEntry removed in state.removedModules) { bool exists = m_modules.TryGetValue(removed.handle, out AssemblyModuleEntry? current); if (state.activated ? exists : !exists || !ReferenceEquals(current, removed)) + { throw new InvalidOperationException("The reload session removal set is no longer current."); + } } } - - - - private readonly record struct PlannedAssembly( AssemblyDomain domain, AssemblyScope scope ); - private void ShutdownLocked() { if (m_assemblyLoadSubscribed) @@ -1236,10 +1374,12 @@ private void ShutdownLocked() } foreach (AssemblyModuleEntry module in m_modules.Values - .OrderByDescending(static value => value.domain == AssemblyDomain.InnoPlugin - ? 0 - : value.scope == AssemblyScope.Runtime ? 1 : 2)) - { + .OrderByDescending(static value => ( + value.domain == AssemblyDomain.InnoPlugin + ? 0 + : value.scope == AssemblyScope.Runtime ? 1 : 2 + )) + ) { BeginUnload(module); } m_modules.Clear(); diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleEntry.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleEntry.cs index b517f8265..f9c718288 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleEntry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleEntry.cs @@ -32,8 +32,9 @@ internal AssemblyModuleInfo CreateInfo() assemblies .Select(static assembly => assembly.GetName().Name ?? assembly.FullName ?? "Unknown") .OrderBy(static name => name, StringComparer.Ordinal) - .ToArray()) - { - upstreamModuleNames = upstreamModuleNames - }; + .ToArray() + ) + { + upstreamModuleNames = upstreamModuleNames + }; } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadContext.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadContext.cs index 65ed8d473..7f6967f92 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadContext.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadContext.cs @@ -56,12 +56,16 @@ IReadOnlyList participantContexts /// /// Thrown when no participant supplied the requested context or the reload has completed. /// - public TContext GetContext() where TContext : class + public TContext GetContext() + where TContext : class { if (TryGetContext(out TContext? context)) + { return context!; + } throw new InvalidOperationException( - $"No assembly catalog participant supplied context '{typeof(TContext).FullName}'."); + $"No assembly catalog participant supplied context '{typeof(TContext).FullName}'." + ); } /// @@ -76,18 +80,22 @@ public TContext GetContext() where TContext : class /// /// when exactly one matching context exists. /// - public bool TryGetContext(out TContext? context) where TContext : class + public bool TryGetContext(out TContext? context) + where TContext : class { IReadOnlyList contexts = m_participantContexts ?? throw CreateCompletedException(); context = null; foreach (object candidate in contexts) { if (candidate is not TContext match) + { continue; + } if (context is not null) { throw new InvalidOperationException( - $"Multiple assembly catalog participants supplied context '{typeof(TContext).FullName}'."); + $"Multiple assembly catalog participants supplied context '{typeof(TContext).FullName}'." + ); } context = match; } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs index da965da85..cf7448fab 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs @@ -1,6 +1,5 @@ using System; using System.Linq; - using Inno.Core.Execution; using Inno.Extensibility.Reload; @@ -26,7 +25,8 @@ ReloadState state state.previousCatalog, state.candidateCatalog, state.candidateModules.Select(static module => module.handle).ToArray(), - state.refresh.contexts); + state.refresh.contexts + ); } /// @@ -95,7 +95,9 @@ public void Rollback() { EnsureRetirementSafe(); if (m_disposed) + { return; + } try { m_owner.Rollback(m_state!); @@ -131,7 +133,9 @@ public void Dispose() private void EnsureRetirementSafe() { if (m_retirementFailure is not null) + { throw m_retirementFailure; + } } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrier.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrier.cs index e19f5e153..d1e376964 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrier.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrier.cs @@ -43,21 +43,27 @@ public AssemblyUnloadBarrier( ArgumentNullException.ThrowIfNull(probes); m_probes = probes.ToArray(); if (m_probes.Any(static probe => probe is null)) + { throw new ArgumentNullException(nameof(probes), "Unload probe collections cannot contain null values."); + } options ??= new AssemblyUnloadBarrierOptions(); if (options.collectionInterval < TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(options), "The collection interval cannot be negative."); + } if (options.retentionTimeout <= TimeSpan.Zero && options.retentionTimeout != Timeout.InfiniteTimeSpan) + { throw new ArgumentOutOfRangeException(nameof(options), "The retention timeout must be positive or infinite."); + } m_collectionIntervalMilliseconds = checked((long)options.collectionInterval.TotalMilliseconds); m_retentionTimeoutMilliseconds = options.retentionTimeout == Timeout.InfiniteTimeSpan - ? long.MaxValue - : checked((long)options.retentionTimeout.TotalMilliseconds); + ? long.MaxValue + : checked((long)options.retentionTimeout.TotalMilliseconds); m_startedTimestamp = Environment.TickCount64; m_nextCollectionTimestamp = m_startedTimestamp; m_state = m_probes.All(static probe => probe.isCompleted) - ? AssemblyUnloadBarrierState.Completed - : AssemblyUnloadBarrierState.AwaitingCollection; + ? AssemblyUnloadBarrierState.Completed + : AssemblyUnloadBarrierState.AwaitingCollection; } /// @@ -68,7 +74,9 @@ public AssemblyUnloadBarrierState state get { lock (m_sync) + { return m_state; + } } } @@ -80,7 +88,9 @@ public int collectionAttempts get { lock (m_sync) + { return m_collectionAttempts; + } } } @@ -92,7 +102,9 @@ public AssemblyUnloadException? failure get { lock (m_sync) + { return m_failure; + } } } @@ -112,9 +124,13 @@ public bool Advance() lock (m_sync) { if (m_state == AssemblyUnloadBarrierState.Completed) + { return true; + } if (m_failure is not null) + { throw m_failure; + } now = Environment.TickCount64; collect = now >= m_nextCollectionTimestamp; if (collect) @@ -125,7 +141,9 @@ public bool Advance() } if (collect) + { ForceFullCollection(); + } lock (m_sync) { @@ -136,7 +154,9 @@ public bool Advance() } TimeSpan elapsed = TimeSpan.FromMilliseconds(Math.Max(0, now - m_startedTimestamp)); if (elapsed.TotalMilliseconds < m_retentionTimeoutMilliseconds) + { return false; + } string[] retained = m_probes .Where(static probe => !probe.isCompleted) .Select(static probe => probe.description) diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrierState.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrierState.cs index 197b5b982..b3d6f0930 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrierState.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadBarrierState.cs @@ -9,12 +9,10 @@ public enum AssemblyUnloadBarrierState /// At least one retired collectible generation remains reachable. /// AwaitingCollection, - /// /// Every retired generation is unreachable and cleaned up. /// Completed, - /// /// The retention threshold was reached and the owning reload subsystem must stop accepting work. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadException.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadException.cs index 7489e85ae..5b093934b 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadException.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/AssemblyUnloadException.cs @@ -31,12 +31,13 @@ public AssemblyUnloadException( IReadOnlyList retainedGenerations, TimeSpan elapsed, int collectionAttempts - ) - : base(CreateMessage(retainedGenerations, elapsed, collectionAttempts)) + ) : base(CreateMessage(retainedGenerations, elapsed, collectionAttempts)) { ArgumentNullException.ThrowIfNull(retainedGenerations); if (retainedGenerations.Count == 0) + { throw new ArgumentException("An unload failure requires at least one retained generation.", nameof(retainedGenerations)); + } this.retainedGenerations = retainedGenerations.ToArray(); this.elapsed = elapsed; this.collectionAttempts = collectionAttempts; @@ -64,11 +65,13 @@ int collectionAttempts ) { ArgumentNullException.ThrowIfNull(retainedGenerations); if (retainedGenerations.Count == 0) + { throw new ArgumentException("An unload failure requires at least one retained generation.", nameof(retainedGenerations)); + } return - $"Retired assembly generations remained reachable for {elapsed.TotalSeconds:F1} seconds across " + - $"{collectionAttempts} full garbage-collection attempts: {string.Join(", ", retainedGenerations)}. " + - "A Type, object, delegate, extension, task, subscription, thread, native callback, or other generation-bound " + - "reference is still retained. The reload subsystem is faulted and requires a host restart."; + $"Retired assembly generations remained reachable for {elapsed.TotalSeconds:F1} seconds across " + + $"{collectionAttempts} full garbage-collection attempts: {string.Join(", ", retainedGenerations)}. " + + "A Type, object, delegate, extension, task, subscription, thread, native callback, or other generation-bound " + + "reference is still retained. The reload subsystem is faulted and requires a host restart."; } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs index d58c68383..0d9671e8e 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs @@ -3,8 +3,8 @@ using System.Linq; using System.Runtime.ExceptionServices; using System.Threading; - using Inno.Core.Execution; + namespace Inno.Extensibility.Reload; /// @@ -32,7 +32,9 @@ public GenerationState state get { lock (m_sync) + { return m_state; + } } } @@ -44,7 +46,9 @@ public Exception? failure get { lock (m_sync) + { return m_failure; + } } } @@ -63,11 +67,13 @@ public void Configure(AssemblyUnloadBarrierOptions options) _ = new AssemblyUnloadBarrier([], options); EnsureReady("configure unload verification"); lock (m_sync) + { m_options = new AssemblyUnloadBarrierOptions { collectionInterval = options.collectionInterval, retentionTimeout = options.retentionTimeout }; + } } /// @@ -83,15 +89,23 @@ public void EnsureReady(string operation) { ArgumentException.ThrowIfNullOrWhiteSpace(operation); if (state == GenerationState.AwaitingCollection) + { _ = Advance(); + } lock (m_sync) { if (m_failure is not null) + { throw new InvalidOperationException($"Cannot {operation}: the generation owner is Faulted and must restart.", m_failure); + } if (m_state != GenerationState.Ready) + { throw new InvalidOperationException($"Cannot {operation}: generation state is {m_state}."); + } if (m_readers > 0) + { throw new InvalidOperationException($"Cannot {operation}: an owner operation holds a generation read lease."); + } } } @@ -111,11 +125,15 @@ public IDisposable AcquireRead(string operation) { ArgumentException.ThrowIfNullOrWhiteSpace(operation); if (state == GenerationState.AwaitingCollection) + { _ = Advance(); + } lock (m_sync) { if (m_state != GenerationState.Ready || m_failure is not null) + { throw new InvalidOperationException($"Cannot {operation}: generation state is {m_state}.", m_failure); + } m_readers++; return new ReadLease(this); } @@ -147,11 +165,15 @@ public IDisposable AcquireOperation(string operation) lock (m_sync) { if (m_failure is not null) + { throw new InvalidOperationException($"Cannot {operation}: the generation owner is Faulted.", m_failure); + } if (m_state == GenerationState.Transitioning) { if (m_publicationThread != Environment.CurrentManagedThreadId) + { throw new InvalidOperationException($"Cannot {operation}: another thread is publishing a generation."); + } return new ReadLease(null); } m_readers++; @@ -182,10 +204,14 @@ out IDisposable? reservation lock (m_sync) { if (m_failure is not null) + { throw new InvalidOperationException($"Cannot {operation}: restart the Faulted generation owner.", m_failure); + } reservation = null; if (m_state != GenerationState.Ready || m_readers != 0) + { return false; + } m_state = GenerationState.Transitioning; m_publicationThread = Environment.CurrentManagedThreadId; reservation = new ChangeReservation(this); @@ -205,10 +231,14 @@ public void TrackRetirement(IAssemblyUnloadProbe probe) lock (m_sync) { if (probe.isCompleted || m_pending.Contains(probe)) + { return; + } m_pending.Add(probe); if (m_state == GenerationState.Ready) + { m_state = GenerationState.AwaitingCollection; + } } } @@ -246,12 +276,16 @@ IReadOnlyList changes ArgumentNullException.ThrowIfNull(changes); IGenerationChange[] snapshot = changes.ToArray(); if (snapshot.Any(static change => change is null)) + { throw new ArgumentException("Generation changes cannot contain null entries.", nameof(changes)); + } EnsureReady(operation); lock (m_sync) { if (m_state != GenerationState.Ready || m_readers != 0 || m_failure is not null) + { throw new InvalidOperationException($"Cannot {operation}: generation admission changed while preparing the transaction."); + } m_state = GenerationState.Transitioning; m_publicationThread = Environment.CurrentManagedThreadId; } @@ -261,18 +295,26 @@ IReadOnlyList changes try { while (preparedCount < snapshot.Length) + { snapshot[preparedCount++].PrepareForActivation(); + } publication.Activate(); foreach (IGenerationChange change in snapshot) + { change.Apply(); + } committed = true; TProbe probe = publication.Complete(); TrackRetirement(probe); List cleanup = []; foreach (IGenerationChange change in snapshot) + { Attempt(change.Complete, cleanup); + } if (cleanup.Count > 0) + { throw new AggregateException($"Generation '{operation}' committed but retirement cleanup failed.", cleanup); + } return probe; } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) @@ -292,10 +334,14 @@ IReadOnlyList changes try { for (int index = preparedCount - 1; index >= 0; index--) + { Attempt(snapshot[index].RollbackStructure, rollback); + } Attempt(publication.Rollback, rollback); for (int index = preparedCount - 1; index >= 0; index--) + { Attempt(snapshot[index].RestorePreviousState, rollback); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { @@ -316,12 +362,16 @@ IReadOnlyList changes finally { if (!retirementBlocked) + { Array.Clear(snapshot); + } lock (m_sync) { m_publicationThread = 0; if (m_state != GenerationState.Faulted) + { m_state = m_pending.Count == 0 ? GenerationState.Ready : GenerationState.AwaitingCollection; + } } } } @@ -344,9 +394,13 @@ public bool Advance() lock (m_sync) { if (m_failure is not null) + { throw new InvalidOperationException("Generation retirement failed; restart the host.", m_failure); + } if (m_state == GenerationState.Transitioning || m_advancing) + { return false; + } if (m_pending.Count == 0) { m_state = GenerationState.Ready; @@ -367,7 +421,9 @@ public bool Advance() m_barrier = null; } if (m_pending.Count == 0) + { m_state = GenerationState.Ready; + } return m_pending.Count == 0; } } @@ -379,7 +435,9 @@ public bool Advance() finally { lock (m_sync) + { m_advancing = false; + } } } @@ -433,7 +491,9 @@ public void EnsureRetirementSafe() lock (m_sync) { if (m_retirementFailure is not null) + { throw m_retirementFailure; + } } } @@ -448,7 +508,12 @@ ICollection failures catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { if (failures.Count > 0) - throw new AggregateException("Generation retirement remains pending after earlier cleanup failures.", [.. failures, pendingRetirement]); + { + throw new AggregateException( + "Generation retirement remains pending after earlier cleanup failures.", + [.. failures, pendingRetirement] + ); + } throw; } catch (Exception exception) @@ -462,7 +527,9 @@ private void RetainFailedRetirement( object transaction ) { lock (m_sync) + { m_retainedTransaction = transaction; + } Fault(failure); GC.KeepAlive(m_retainedTransaction); } @@ -478,12 +545,16 @@ public void Dispose() { GenerationCoordinator? current = Interlocked.Exchange(ref m_owner, null); if (current is null) + { return; + } lock (current.m_sync) { current.m_publicationThread = 0; if (current.m_state != GenerationState.Faulted) + { current.m_state = current.m_pending.Count == 0 ? GenerationState.Ready : GenerationState.AwaitingCollection; + } } } } @@ -491,6 +562,7 @@ public void Dispose() private sealed class ReadLease(GenerationCoordinator? owner) : IDisposable { private GenerationCoordinator? m_owner = owner; + /// /// Releases this owner's registrations and resources exactly once. /// @@ -498,9 +570,13 @@ public void Dispose() { GenerationCoordinator? current = Interlocked.Exchange(ref m_owner, null); if (current is null) + { return; + } lock (current.m_sync) + { current.m_readers--; + } } } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationChange.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationChange.cs index c37d855f3..8e08c55f9 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationChange.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationChange.cs @@ -9,18 +9,22 @@ public interface IGenerationChange /// Quiesces old instances while the old publication remains active. /// void PrepareForActivation(); + /// /// Applies captured state after candidate publication; partial changes must be rollback-safe. /// void Apply(); + /// /// Releases old instances after irreversible publication; cleanup failures fault the owner. /// void Complete(); + /// /// Removes provisional structures before restoring the old publication. /// void RollbackStructure(); + /// /// Restores old values and lifecycle after the previous publication has been restored. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationPublication.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationPublication.cs index b2837226d..35ef43eaf 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationPublication.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/IGenerationPublication.cs @@ -6,16 +6,19 @@ namespace Inno.Extensibility.Reload; /// /// The non-owning probe used to verify retired collectible contexts. /// -public interface IGenerationPublication where TProbe : IAssemblyUnloadProbe +public interface IGenerationPublication + where TProbe : IAssemblyUnloadProbe { /// /// Makes the fully prepared candidate provisionally visible at an owner-thread safe point. /// void Activate(); + /// /// Restores the previous publication and retires discarded candidates. /// void Rollback(); + /// /// Commits publication after all dependent changes apply successfully. /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/Properties/ScriptingApi.cs b/src/foundation/extensibility/Inno.Extensibility.Types/Properties/ScriptingApi.cs index 623509ddf..94c1bd845 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/Properties/ScriptingApi.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/Properties/ScriptingApi.cs @@ -1,9 +1,6 @@ using Inno.Extensibility.Types; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Reflection", - "Inno.Extensibility.Types", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Reflection", "Inno.Extensibility.Types", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(StableTypeIdAttribute), ScriptingApiScope.Runtime)] diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/ITypeCatalogSource.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/ITypeCatalogSource.cs index 882344d7c..8ea32e8f8 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/ITypeCatalogSource.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/ITypeCatalogSource.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Reflection; - using Inno.Extensibility.Catalogs; namespace Inno.Extensibility.Types; diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheBuildException.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheBuildException.cs index 2743f2777..04b75ba3f 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheBuildException.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheBuildException.cs @@ -20,8 +20,7 @@ public sealed class TypeCacheBuildException : Exception public TypeCacheBuildException( string message, IReadOnlyList loaderExceptions - ) - : base(message, loaderExceptions.Count > 0 ? loaderExceptions[0] : null) + ) : base(message, loaderExceptions.Count > 0 ? loaderExceptions[0] : null) { this.loaderExceptions = loaderExceptions; } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheReloadContext.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheReloadContext.cs index 99a1d1411..af5c7d04a 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheReloadContext.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheReloadContext.cs @@ -40,7 +40,9 @@ TypeCacheSnapshot candidate public bool IsRetired(TypeRef typeRef) { if (!previous.TryResolve(typeRef, out Type? previousType)) + { return false; + } return !candidate.TryResolve(typeRef, out Type? replacement) || replacement != previousType; } @@ -60,10 +62,10 @@ public bool TryResolveReplacement( TypeRef previousType, out TypeRef replacement ) { - if (!previous.TryResolve(previousType, out Type? previousRuntimeType) || - !candidate.TryResolve(previousType, out Type? replacementType) || - replacementType == previousRuntimeType) - { + if (!previous.TryResolve(previousType, out Type? previousRuntimeType) + || !candidate.TryResolve(previousType, out Type? replacementType) + || replacementType == previousRuntimeType + ) { replacement = default; return false; } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs index 490ca681a..a5b90ec37 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Inno.Extensibility.Catalogs; namespace Inno.Extensibility.Types; @@ -88,8 +87,9 @@ public IReadOnlyList GetTypesImplementing() /// /// An immutable snapshot of the values selected by the operation. /// - public IReadOnlyList GetTypesWithAttribute() where TAttribute : Attribute - => m_queryRegistry.GetTypesWithAttribute(m_identityRegistry); + public IReadOnlyList GetTypesWithAttribute() + where TAttribute : Attribute + => m_queryRegistry.GetTypesWithAttribute(m_identityRegistry); /// /// Gets the reference for a CLR type in this snapshot. @@ -154,7 +154,9 @@ public object CreateInstance(Type type) ArgumentNullException.ThrowIfNull(type); Type declaration = type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : type; if (!m_identityRegistry.TryGetTypeRef(declaration, out _)) + { throw new InvalidOperationException($"Type '{type}' does not belong to this generation."); + } return m_source!.CreateInstance(type); } @@ -183,7 +185,9 @@ IReadOnlyList arguments ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(arguments); if (!m_identityRegistry.TryGetTypeRef(definition, out _)) + { throw new InvalidOperationException($"Type '{definition}' does not belong to this generation."); + } return m_source!.ConstructGenericType(definition, arguments); } @@ -220,7 +224,8 @@ IReadOnlyList arguments { TypeCatalogMetadata metadata = GetMetadata(type); return (inherit ? metadata.inheritedAttributes : metadata.declaredAttributes) - .OfType().SingleOrDefault(); + .OfType() + .SingleOrDefault(); } internal IReadOnlyList runtimeTypes => m_types; @@ -244,7 +249,9 @@ long version foreach (Assembly assembly in assemblies.Where(static value => !value.IsDynamic)) { if (typesByAssembly.ContainsKey(assembly)) + { continue; + } if (previous is not null && previous.m_typesByAssembly.TryGetValue(assembly, out Type[]? cachedTypes)) { typesByAssembly.Add(assembly, cachedTypes); @@ -275,7 +282,8 @@ long version { throw new TypeCacheBuildException( $"Type discovery failed with {loaderExceptions.Count} loader error(s).", - loaderExceptions); + loaderExceptions + ); } Type[] types = discoveredTypes @@ -284,9 +292,14 @@ long version .ThenBy(static type => type.FullName, StringComparer.Ordinal) .ToArray(); var identities = new TypeIdentityRegistry(); - Dictionary metadata = types.ToDictionary(static type => type, - type => previous is not null && previous.m_metadata.TryGetValue(type, out TypeCatalogMetadata? existing) - ? existing : source.GetMetadata(type)); + Dictionary metadata = types.ToDictionary( + static type => type, + type => ( + previous is not null && previous.m_metadata.TryGetValue(type, out TypeCatalogMetadata? existing) + ? existing + : source.GetMetadata(type) + ) + ); identities.Rebuild(metadata.Values, previous?.m_identityRegistry); var queries = new TypeQueryRegistry(); queries.Rebuild(metadata.Values, identities); diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs index d5a381386..fcbe3dc5e 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Threading; - using Inno.Core.Execution; using Inno.Extensibility.Modules; @@ -47,7 +46,9 @@ ITypeCatalogSource source ArgumentNullException.ThrowIfNull(modules); ArgumentNullException.ThrowIfNull(source); if (!modules.isInitialized) + { throw new InvalidOperationException("The module host must be active before creating a type catalog."); + } m_modules = modules; m_source = source; m_participant = new TypeCacheCatalogParticipant(this); @@ -90,7 +91,9 @@ public TypeCacheSnapshot current EnsureInitialized(); m_modules.Refresh(); lock (m_sync) + { return m_current; + } } } @@ -118,7 +121,9 @@ public void Dispose() lock (m_sync) { if (m_disposed) + { return; + } m_disposed = true; registries = m_registries.Prepare(TypeCacheSnapshot.empty); m_current = TypeCacheSnapshot.empty; @@ -167,8 +172,9 @@ public void Dispose() /// /// The matching concrete types in stable catalog order. /// - public IReadOnlyList GetTypesWithAttribute() where TAttribute : Attribute - => current.GetTypesWithAttribute(); + public IReadOnlyList GetTypesWithAttribute() + where TAttribute : Attribute + => current.GetTypesWithAttribute(); /// /// Gets the reference for an active CLR type. @@ -243,11 +249,14 @@ out Type? type public Type Resolve(TypeRef typeRef) { if (typeRef.stableId != Guid.Empty && TryResolve(typeRef, out Type? type)) + { return type!; + } throw new InvalidOperationException( typeRef.stableId == Guid.Empty - ? "An empty type reference cannot be resolved." - : $"Type reference '{typeRef.stableId:D}' is not available in the active type cache."); + ? "An empty type reference cannot be resolved." + : $"Type reference '{typeRef.stableId:D}' is not available in the active type cache." + ); } internal TypeRegistryRegistration Register(ITypeRegistry registry) @@ -271,7 +280,9 @@ internal void EnsureRetirementSafe() private void EnsureInitialized() { if (!isInitialized) + { throw new InvalidOperationException("TypeCatalog is not initialized."); + } } private void RetainFailedRetirement( @@ -299,12 +310,15 @@ public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) owner.EnsureRetirementSafe(); TypeCacheSnapshot previous; lock (owner.m_sync) + { previous = owner.m_current; + } TypeCacheSnapshot candidate = TypeCacheSnapshot.Build( catalog.assemblies, owner.m_source, previous, - Interlocked.Increment(ref owner.m_nextVersion)); + Interlocked.Increment(ref owner.m_nextVersion) + ); TypeRegistryRefreshSet registries = owner.m_registries.Prepare(candidate); return new TypeCacheCatalogTransaction(owner, previous, candidate, registries); } @@ -334,7 +348,9 @@ public void Activate() owner.EnsureRetirementSafe(); EnsureNotFinished(); lock (owner.m_sync) + { owner.m_current = candidate; + } try { registries.Activate(); @@ -348,7 +364,9 @@ public void Activate() catch { lock (owner.m_sync) + { owner.m_current = previous; + } registries.Rollback(); m_finished = true; m_context.Release(); @@ -364,7 +382,9 @@ public void Complete() owner.EnsureRetirementSafe(); EnsureNotFinished(); if (!m_activated) + { throw new InvalidOperationException("Type cache transaction has not been activated."); + } m_finished = true; try { @@ -378,7 +398,9 @@ public void Complete() finally { if (owner.m_retirementFailure is null) + { m_context.Release(); + } } } @@ -389,11 +411,15 @@ public void Rollback() { owner.EnsureRetirementSafe(); if (m_finished) + { return; + } if (m_activated) { lock (owner.m_sync) + { owner.m_current = previous; + } } m_finished = true; try @@ -408,14 +434,18 @@ public void Rollback() finally { if (owner.m_retirementFailure is null) + { m_context.Release(); + } } } private void EnsureNotFinished() { if (m_finished) + { throw new InvalidOperationException("Type cache transaction is already finished."); + } } } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs index 468ac089a..8e4e93bf3 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs @@ -5,7 +5,6 @@ using System.Security.Cryptography; using System.Text; using System.Threading; - using Inno.Extensibility.Catalogs; namespace Inno.Extensibility.Types; @@ -88,16 +87,18 @@ public void Rebuild( if (!Guid.TryParse(attr.id, out stableId)) { throw new InvalidOperationException( - $"Type '{type.FullName}' has invalid StableTypeId '{attr.id}'."); + $"Type '{type.FullName}' has invalid StableTypeId '{attr.id}'." + ); } } - else if (mappings.TryGetValue(type.Assembly, out IReadOnlyDictionary? assemblyMappings) && - assemblyMappings.TryGetValue(type.FullName ?? type.Name, out mapping)) - { + else if (mappings.TryGetValue(type.Assembly, out IReadOnlyDictionary? assemblyMappings) + && assemblyMappings.TryGetValue(type.FullName ?? type.Name, out mapping) + ) { if (!Guid.TryParse(mapping.id, out stableId)) { throw new InvalidOperationException( - $"Type '{type.FullName}' has invalid generated StableTypeId '{mapping.id}'."); + $"Type '{type.FullName}' has invalid generated StableTypeId '{mapping.id}'." + ); } } else @@ -109,7 +110,8 @@ public void Rebuild( { Type existing = typeByStable[stableId]; throw new InvalidOperationException( - $"StableTypeId '{stableId}' conflicts between '{existing.FullName}' and '{type.FullName}'."); + $"StableTypeId '{stableId}' conflicts between '{existing.FullName}' and '{type.FullName}'." + ); } stableByType[type] = stableId; @@ -124,7 +126,9 @@ public void Rebuild( if (previous is not null) { lock (previous.m_sync) + { previousRuntimeByType = new Dictionary(previous.m_runtimeByType); + } } var runtimeByType = new Dictionary(orderedTypes.Length); @@ -134,7 +138,9 @@ public void Rebuild( Type type = orderedTypes[i]; int runtimeId; if (!previousRuntimeByType.TryGetValue(type, out runtimeId)) + { runtimeId = AllocateRuntimeTypeId(); + } runtimeByType[type] = runtimeId; typeByRuntime[runtimeId] = type; @@ -194,9 +200,9 @@ out TypeRef typeRef lock (m_sync) { - if (m_stableByType.TryGetValue(type, out Guid stableId) && - m_runtimeByType.TryGetValue(type, out int runtimeId)) - { + if (m_stableByType.TryGetValue(type, out Guid stableId) + && m_runtimeByType.TryGetValue(type, out int runtimeId) + ) { typeRef = new TypeRef(stableId, runtimeId); return true; } @@ -218,7 +224,9 @@ out TypeRef typeRef public TypeRef GetTypeRef(Type type) { if (TryGetTypeRef(type, out TypeRef typeRef)) + { return typeRef; + } throw new InvalidOperationException($"Type '{type.FullName}' does not belong to this type-cache snapshot."); } @@ -354,11 +362,11 @@ out Type? type type = null; return false; } - if (typeRef.runtimeId > 0 && - m_typeByRuntime.TryGetValue(typeRef.runtimeId, out Type? runtimeType) && - m_stableByType.TryGetValue(runtimeType, out Guid runtimeStableId) && - runtimeStableId == typeRef.stableId) - { + if (typeRef.runtimeId > 0 + && m_typeByRuntime.TryGetValue(typeRef.runtimeId, out Type? runtimeType) + && m_stableByType.TryGetValue(runtimeType, out Guid runtimeStableId) + && runtimeStableId == typeRef.stableId + ) { type = runtimeType; return true; } @@ -377,7 +385,9 @@ private static int AllocateRuntimeTypeId() { int runtimeId = Interlocked.Increment(ref S_NEXT_RUNTIME_TYPE_ID); if (runtimeId <= 0) + { throw new InvalidOperationException("The process-wide runtime type identity space is exhausted."); + } return runtimeId; } @@ -435,32 +445,38 @@ private static IReadOnlyDictionary string.Equals( attribute.Key, C_GENERATED_STABLE_TYPE_METADATA_KEY, - StringComparison.Ordinal)) + StringComparison.Ordinal + )) .ToArray(); if (attributes.Length == 0) + { continue; + } - var availableTypes = group.ToDictionary( - static type => type.FullName ?? type.Name, - StringComparer.Ordinal); + var availableTypes = group.ToDictionary(static type => type.FullName ?? type.Name, StringComparer.Ordinal); var mappings = new Dictionary(StringComparer.Ordinal); foreach (AssemblyMetadataAttribute attribute in attributes) { GeneratedStableTypeMapping mapping = ParseGeneratedMapping( group.Key.GetName().Name ?? string.Empty, - attribute.Value); + attribute.Value + ); if (string.IsNullOrWhiteSpace(mapping.typeName)) + { throw new InvalidOperationException("A generated StableTypeId mapping requires a type name."); + } if (!availableTypes.ContainsKey(mapping.typeName)) { throw new InvalidOperationException( - $"Generated StableTypeId mapping refers to missing type '{mapping.typeName}' " + - $"in assembly '{group.Key.GetName().Name}'."); + $"Generated StableTypeId mapping refers to missing type '{mapping.typeName}' " + + $"in assembly '{group.Key.GetName().Name}'." + ); } if (!mappings.TryAdd(mapping.typeName, mapping)) { throw new InvalidOperationException( - $"Type '{mapping.typeName}' has more than one generated StableTypeId mapping."); + $"Type '{mapping.typeName}' has more than one generated StableTypeId mapping." + ); } } result.Add(group.Key, mappings); @@ -476,7 +492,8 @@ private static GeneratedStableTypeMapping ParseGeneratedMapping( if (parts.Length != 2) { throw new InvalidOperationException( - $"Assembly '{assemblyName}' has invalid generated StableTypeId metadata '{value}'."); + $"Assembly '{assemblyName}' has invalid generated StableTypeId metadata '{value}'." + ); } return new GeneratedStableTypeMapping(parts[1], parts[0]); } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs index 8419d474b..72a12ccf6 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Extensibility.Catalogs; namespace Inno.Extensibility.Types; @@ -78,10 +77,10 @@ TypeIdentityRegistry typeIdentityRegistry /// public IReadOnlyList GetSubTypesOf(TypeIdentityRegistry typeIdentityRegistry) { - return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(T), out int keyId) && - m_subclassCache.TryGetValue(keyId, out IReadOnlyList? set) - ? set - : []; + return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(T), out int keyId) + && m_subclassCache.TryGetValue(keyId, out IReadOnlyList? set) + ? set + : []; } /// @@ -98,10 +97,10 @@ public IReadOnlyList GetSubTypesOf(TypeIdentityRegistry typeIdentity /// public IReadOnlyList GetTypesImplementing(TypeIdentityRegistry typeIdentityRegistry) { - return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(TInterface), out int keyId) && - m_interfaceCache.TryGetValue(keyId, out IReadOnlyList? set) - ? set - : []; + return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(TInterface), out int keyId) + && m_interfaceCache.TryGetValue(keyId, out IReadOnlyList? set) + ? set + : []; } /// @@ -119,10 +118,10 @@ public IReadOnlyList GetTypesImplementing(TypeIdentityRegis public IReadOnlyList GetTypesWithAttribute(TypeIdentityRegistry typeIdentityRegistry) where TAttr : Attribute { - return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(TAttr), out int keyId) && - m_attributeCache.TryGetValue(keyId, out IReadOnlyList? set) - ? set - : []; + return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(TAttr), out int keyId) + && m_attributeCache.TryGetValue(keyId, out IReadOnlyList? set) + ? set + : []; } private static void AddToIndex( @@ -148,9 +147,7 @@ TypeIdentityRegistry typeIdentityRegistry var frozen = new Dictionary>(index.Count); foreach ((int key, HashSet value) in index) { - frozen[key] = Array.AsReadOnly(value - .Select(typeIdentityRegistry.GetTypeRef) - .ToArray()); + frozen[key] = Array.AsReadOnly(value.Select(typeIdentityRegistry.GetTypeRef).ToArray()); } return frozen; diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs index 1c5fefcff..d08985e38 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs @@ -18,9 +18,7 @@ namespace Inno.Extensibility.Types; /// The persistent type identity, or an empty value for an invalid reference. /// public TypeRef(Guid stableId) - : this(stableId, runtimeId: 0) - { - } + : this(stableId, runtimeId: 0) {} internal TypeRef( Guid stableId, @@ -101,7 +99,9 @@ public Type Resolve(TypeCacheSnapshot snapshot) { ArgumentNullException.ThrowIfNull(snapshot); if (stableId != Guid.Empty && snapshot.TryResolve(this, out Type? type)) + { return type!; + } throw CreateResolutionException(snapshot.version); } @@ -180,11 +180,12 @@ TypeRef right private InvalidOperationException CreateResolutionException(long? snapshotVersion = null) { string generation = snapshotVersion is long version - ? $" in type-cache snapshot {version}" - : string.Empty; + ? $" in type-cache snapshot {version}" + : string.Empty; return new InvalidOperationException( stableId == Guid.Empty - ? "An empty type reference cannot be resolved." - : $"Type reference '{stableId:D}' is not available{generation}."); + ? "An empty type reference cannot be resolved." + : $"Type reference '{stableId:D}' is not available{generation}." + ); } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs index 6c30faaf1..b67404f5c 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; - using Inno.Core.Execution; namespace Inno.Extensibility.Types; @@ -53,7 +52,9 @@ protected TypeRegistry( ArgumentNullException.ThrowIfNull(types); m_retirementTimeout = retirementTimeout ?? TimeSpan.FromSeconds(30); if (m_retirementTimeout <= TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(retirementTimeout)); + } m_types = types; m_registryAdapter = new RegistryAdapter(this); m_registration = types.Register(m_registryAdapter); @@ -67,7 +68,9 @@ public bool isInitialized get { lock (m_sync) + { return m_current is not null; + } } } @@ -84,9 +87,7 @@ public void Refresh() ObjectDisposedException.ThrowIf(m_disposed, this); while (true) { - ITypeRegistryTransaction transaction = Prepare( - m_types.current, - allowDisposed: false); + ITypeRegistryTransaction transaction = Prepare(m_types.current, allowDisposed: false); try { transaction.Activate(); @@ -112,9 +113,9 @@ public void Refresh() TypeCacheSnapshot latest = m_types.current; lock (m_sync) { - if (m_activationInProgress || - m_current is not null && m_typeCacheVersion == latest.version) - { + if (m_activationInProgress + || m_current is not null && m_typeCacheVersion == latest.version + ) { return; } } @@ -137,7 +138,8 @@ public void Clear() if (m_activationInProgress) { throw new InvalidOperationException( - "A registry snapshot cannot be cleared while a refresh transaction is active."); + "A registry snapshot cannot be cleared while a refresh transaction is active." + ); } snapshot = m_current; } @@ -145,7 +147,9 @@ public void Clear() try { if (snapshot is not null) + { ReleaseSnapshot(snapshot); + } } finally { @@ -173,7 +177,9 @@ public void Dispose() lock (m_sync) { if (m_disposed) + { return; + } m_disposed = true; snapshot = m_activationInProgress ? null : m_current; } @@ -181,7 +187,9 @@ public void Dispose() try { if (snapshot is not null) + { ReleaseSnapshot(snapshot); + } } finally { @@ -210,12 +218,16 @@ protected TSnapshot current lock (m_sync) { if (m_current is not null && m_typeCacheVersion == types.version) + { return m_current; + } } Refresh(); lock (m_sync) + { return m_current ?? throw new InvalidOperationException("Registry refresh produced no snapshot."); + } } } @@ -246,8 +258,7 @@ protected TSnapshot current protected virtual void OnActivating( TSnapshot? previous, TSnapshot candidate - ) { - } + ) {} /// /// Reverses lifecycle work performed while activating a candidate snapshot. @@ -265,8 +276,7 @@ TSnapshot candidate protected virtual void OnActivationRolledBack( TSnapshot? previous, TSnapshot candidate - ) { - } + ) {} /// /// Finalizes a successfully activated candidate after every coordinated registry has activated. @@ -284,8 +294,7 @@ TSnapshot candidate protected virtual void OnActivationCompleted( TSnapshot? previous, TSnapshot currentSnapshot - ) { - } + ) {} /// /// Releases resources owned by a registry snapshot. @@ -296,7 +305,9 @@ TSnapshot currentSnapshot protected virtual void DisposeSnapshot(TSnapshot snapshot) { if (snapshot is IDisposable disposable) + { disposable.Dispose(); + } } /// @@ -315,12 +326,7 @@ protected virtual void DisposeSnapshot(TSnapshot snapshot) protected virtual void OnCleanupFailed( string phase, Exception exception - ) - => Trace.TraceError( - "Type registry '{0}' failed during {1}: {2}", - GetType().FullName, - phase, - exception); + ) => Trace.TraceError("Type registry '{0}' failed during {1}: {2}", GetType().FullName, phase, exception); /// /// Faults the shared generation gate when a resource composed from this registry cannot retire safely. @@ -352,7 +358,8 @@ protected TExtension CreateExtension(Type type) if (type.IsAbstract || !typeof(TExtension).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Extension '{type.FullName}' must be a non-abstract {typeof(TExtension).FullName}."); + $"Extension '{type.FullName}' must be a non-abstract {typeof(TExtension).FullName}." + ); } try @@ -364,7 +371,8 @@ protected TExtension CreateExtension(Type type) { throw new InvalidOperationException( $"Extension '{type.FullName}' requires a parameterless constructor.", - exception); + exception + ); } } @@ -387,9 +395,13 @@ protected TExtension OwnCandidateExtension(TExtension extension) { ArgumentNullException.ThrowIfNull(extension); if (m_candidateResources is null) + { throw new InvalidOperationException("Candidate resources may only be owned while building a registry snapshot."); + } if (extension is IDisposable) + { m_candidateResources.Add(extension); + } return extension; } @@ -410,7 +422,9 @@ protected void DisposeExtensions(IEnumerable extensions) ArgumentNullException.ThrowIfNull(extensions); var resources = new LifetimeScope(); foreach (IDisposable resource in extensions.Distinct(ReferenceEqualityComparer.Instance).OfType()) + { resources.Own(resource); + } RetireResource("extension batch", resources.Dispose); } @@ -454,13 +468,19 @@ bool allowDisposed if (m_disposed) { if (allowDisposed) + { return TypeRegistryNoopTransaction.instance; + } throw new ObjectDisposedException(GetType().FullName); } if (m_activationInProgress) + { return TypeRegistryNoopTransaction.instance; + } if (m_current is not null && m_typeCacheVersion == types.version) + { return TypeRegistryNoopTransaction.instance; + } m_activationInProgress = true; m_candidateResources = []; @@ -468,12 +488,7 @@ bool allowDisposed try { TSnapshot candidate = Build(types); - return new RegistryTransaction( - this, - candidate, - types.version, - m_current, - m_typeCacheVersion); + return new RegistryTransaction(this, candidate, types.version, m_current, m_typeCacheVersion); } catch (Exception failure) { @@ -577,7 +592,9 @@ private void EnsureRetirementSafe() throw m_retirementFailure; } if (!m_disposed) + { m_types.EnsureRetirementSafe(); + } } private void RetainFailedRetirement( @@ -645,7 +662,9 @@ public void Activate() { owner.OnActivating(previous, candidate); lock (owner.m_sync) + { ObjectDisposedException.ThrowIf(owner.m_disposed, owner); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { @@ -662,7 +681,9 @@ public void Activate() { var combined = new AggregateException("Registry activation and rollback failed.", activationFailure, rollbackFailure); if (RetirementPendingException.Find(combined) is not null) + { owner.RetainFailedRetirement(combined, this, "activation rollback"); + } throw combined; } throw; @@ -679,9 +700,13 @@ public void Complete() lock (owner.m_sync) { if (m_finished) + { return; + } if (!m_activated) + { throw new InvalidOperationException("Registry transaction has not been activated."); + } m_finished = true; snapshotToRelease = previous; } @@ -689,7 +714,9 @@ public void Complete() List failures = []; Attempt(() => owner.CompleteActivation(previous, candidate), failures); if (snapshotToRelease is not null) + { Attempt(() => owner.ReleaseSnapshot(snapshotToRelease), failures); + } bool releaseCandidate; lock (owner.m_sync) { @@ -697,7 +724,9 @@ public void Complete() owner.m_activationInProgress = false; } if (releaseCandidate) + { Attempt(() => owner.ReleaseSnapshot(candidate), failures); + } previous = null; candidate = null!; ThrowCleanupFailures(failures); @@ -713,7 +742,9 @@ public void Rollback() lock (owner.m_sync) { if (m_finished) + { return; + } ownerWasDisposed = owner.m_disposed; if (m_activated && !ownerWasDisposed) { @@ -731,10 +762,14 @@ public void Rollback() List failures = []; if (m_activationStarted) + { Attempt(() => owner.RollbackActivation(previous, candidate), failures); + } Attempt(() => owner.ReleaseSnapshot(candidate), failures); if (ownerWasDisposed && previous is not null) + { Attempt(() => owner.ReleaseSnapshot(previous), failures); + } previous = null; candidate = null!; ThrowCleanupFailures(failures); @@ -751,7 +786,12 @@ List failures catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { if (failures.Count > 0) - throw new AggregateException("Registry retirement remains pending after earlier cleanup failures.", [.. failures, pendingRetirement]); + { + throw new AggregateException( + "Registry retirement remains pending after earlier cleanup failures.", + [.. failures, pendingRetirement] + ); + } throw; } catch (Exception exception) @@ -763,13 +803,17 @@ List failures private static void ThrowCleanupFailures(List failures) { if (failures.Count > 0) + { throw new AggregateException("Registry retirement or rollback failed after every resource was attempted.", failures); + } } private void EnsureNotFinished() { if (m_finished) + { throw new InvalidOperationException("Registry transaction is already finished."); + } } } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs index 61bfe9e35..af1475611 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Execution; namespace Inno.Extensibility.Types; @@ -25,10 +24,12 @@ internal interface ITypeRegistryTransaction /// Makes the prepared value active at the owning subsystem's safety point. /// void Activate(); + /// /// Finalizes candidate activation and releases temporary transaction state. /// void Complete(); + /// /// Restores the state captured before the current transaction began. /// @@ -42,23 +43,17 @@ internal sealed class TypeRegistryNoopTransaction : ITypeRegistryTransaction /// /// Makes the prepared value active at the owning subsystem's safety point. /// - public void Activate() - { - } + public void Activate() {} /// /// Finalizes candidate activation and releases temporary transaction state. /// - public void Complete() - { - } + public void Complete() {} /// /// Restores the state captured before the current transaction began. /// - public void Rollback() - { - } + public void Rollback() {} } internal sealed class TypeRegistryCoordinator @@ -74,9 +69,7 @@ internal TypeRegistryRegistration Register(ITypeRegistry registry) { RemoveCollectedRegistries(); var registration = new TypeRegistryRegistration(this, Guid.NewGuid()); - m_registries.Add(new RegistryReference( - registration.id, - new WeakReference(registry))); + m_registries.Add(new RegistryReference(registration.id, new WeakReference(registry))); return registration; } } @@ -95,7 +88,9 @@ internal TypeRegistryRefreshSet Prepare(TypeCacheSnapshot types) foreach (RegistryReference registration in m_registries) { if (registration.registry.TryGetTarget(out ITypeRegistry? registry)) + { registries.Add(registry); + } } } @@ -103,7 +98,9 @@ internal TypeRegistryRefreshSet Prepare(TypeCacheSnapshot types) try { foreach (ITypeRegistry registry in registries) + { transactions.Add(registry.Prepare(types)); + } return new TypeRegistryRefreshSet(transactions); } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) @@ -123,7 +120,10 @@ internal TypeRegistryRefreshSet Prepare(TypeCacheSnapshot types) } catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { - m_retirementFailure = new AggregateException("Registry preparation failed and rollback remains pending.", [.. failures, failure]); + m_retirementFailure = new AggregateException( + "Registry preparation failed and rollback remains pending.", + [.. failures, failure] + ); m_retainedPreparation = (registries, transactions); throw m_retirementFailure; } @@ -133,7 +133,9 @@ internal TypeRegistryRefreshSet Prepare(TypeCacheSnapshot types) } } if (failures.Count > 1) + { throw new AggregateException("Type registry preparation and rollback failed.", failures); + } throw; } } @@ -141,7 +143,9 @@ internal TypeRegistryRefreshSet Prepare(TypeCacheSnapshot types) internal void Unregister(Guid registrationId) { lock (m_sync) + { m_registries.RemoveAll(registration => registration.id == registrationId); + } } private void RemoveCollectedRegistries() => m_registries.RemoveAll(static registration => !registration.registry.TryGetTarget(out _)); @@ -167,7 +171,9 @@ Guid id public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; owner.Unregister(id); } @@ -182,13 +188,19 @@ internal sealed class TypeRegistryRefreshSet(IReadOnlyList failures = []; for (int i = 0; i < transactions.Count; i++) + { TryCleanup(transactions[i].Complete, failures); + } m_finished = true; transactions = Array.Empty(); if (failures.Count > 0) + { throw new AggregateException("Type registry completion failed after all participants were attempted.", failures); + } } internal void Rollback() { if (m_failure is not null) + { throw m_failure; + } if (m_finished) + { return; + } List failures = []; for (int i = transactions.Count - 1; i >= 0; i--) + { TryCleanup(transactions[i].Rollback, failures); + } m_finished = true; transactions = Array.Empty(); if (failures.Count > 0) + { throw new AggregateException("Type registry rollback failed after all participants were attempted.", failures); + } } private void TryCleanup( @@ -253,9 +283,13 @@ List failures catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { m_failure = failures.Count == 0 ? failure : new AggregateException( - "Registry cleanup remains pending after earlier failures.", [.. failures, failure]); + "Registry cleanup remains pending after earlier failures.", + [.. failures, failure] + ); if (ReferenceEquals(m_failure, failure)) + { throw; + } throw m_failure; } catch (Exception exception) diff --git a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiExportAttribute.cs b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiExportAttribute.cs index 8f1c843f4..4c4f2f7a4 100644 --- a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiExportAttribute.cs +++ b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiExportAttribute.cs @@ -28,10 +28,7 @@ public sealed class ScriptingApiExportAttribute : Attribute public ScriptingApiExportAttribute( Type type, ScriptingApiScope scope - ) - : this(type, GetDefaultName(type), scope) - { - } + ) : this(type, GetDefaultName(type), scope) {} /// /// Creates an explicit script API export with a script-facing type name. @@ -58,7 +55,9 @@ ScriptingApiScope scope ) { this.type = type ?? throw new ArgumentNullException(nameof(type)); if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("A script-facing type name is required.", nameof(name)); + } this.name = name; this.scope = scope; } @@ -81,7 +80,9 @@ ScriptingApiScope scope private static string GetDefaultName(Type? type) { if (type is null) + { return string.Empty; + } int aritySeparator = type.Name.IndexOf('`'); return aritySeparator < 0 ? type.Name : type.Name[..aritySeparator]; } diff --git a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiIgnoreAttribute.cs b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiIgnoreAttribute.cs index dc0f1c499..a70087dc3 100644 --- a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiIgnoreAttribute.cs +++ b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiIgnoreAttribute.cs @@ -6,13 +6,12 @@ namespace Inno.Scripting.Api; /// Explicitly excludes one otherwise visible member from generated scripting reference assemblies. /// [AttributeUsage( - AttributeTargets.Constructor | - AttributeTargets.Method | - AttributeTargets.Property | - AttributeTargets.Field | - AttributeTargets.Event, + AttributeTargets.Constructor + | AttributeTargets.Method + | AttributeTargets.Property + | AttributeTargets.Field + | AttributeTargets.Event, AllowMultiple = false, - Inherited = false)] -public sealed class ScriptingApiIgnoreAttribute : Attribute -{ -} + Inherited = false +)] +public sealed class ScriptingApiIgnoreAttribute : Attribute; diff --git a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiNamespaceAttribute.cs b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiNamespaceAttribute.cs index 6f8d303c4..f8890d24b 100644 --- a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiNamespaceAttribute.cs +++ b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiNamespaceAttribute.cs @@ -32,9 +32,13 @@ public ScriptingApiNamespaceAttribute( ScriptingApiScope scope ) { if (string.IsNullOrWhiteSpace(name)) + { throw new ArgumentException("A script API namespace is required.", nameof(name)); + } if (string.IsNullOrWhiteSpace(implementationNamespace)) + { throw new ArgumentException("An implementation namespace is required.", nameof(implementationNamespace)); + } this.name = name; this.implementationNamespace = implementationNamespace; this.scope = scope; diff --git a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiScope.cs b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiScope.cs index c3bdbd8ea..d72e5959e 100644 --- a/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiScope.cs +++ b/src/foundation/scripting/Inno.Scripting.Api/ScriptingApiScope.cs @@ -9,12 +9,10 @@ public enum ScriptingApiScope /// Exposes the API to both game and editor scripts. /// Runtime, - /// /// Exposes the API only to editor scripts. /// Editor, - /// /// Exposes compile-time annotations to game and editor scripts. Player compilation erases /// their applications and derived annotation declarations before binding to target assemblies. diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs index 2cec1be5f..e9d662dcd 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs @@ -28,6 +28,7 @@ public abstract class RuntimeSubsystem : IRuntimeSubsystem /// Gets resources and cancellation owned exclusively by this subsystem. /// protected LifetimeScope lifetime => m_lifetime; + /// /// Acquires session resources after every dependency has attached. /// @@ -42,7 +43,9 @@ public void Attach() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_started) + { throw new InvalidOperationException("A subsystem cannot be attached to multiple owners."); + } m_ownerThread = Environment.CurrentManagedThreadId; m_started = true; try @@ -56,6 +59,7 @@ public void Attach() throw; } } + /// /// Begins one frame before event dispatch and simulation. /// @@ -66,7 +70,9 @@ public void BeginFrame(RuntimeFrame frame) { EnsureStarted(); if (m_frameOpen) + { throw new InvalidOperationException("A subsystem frame is already open."); + } m_frameOpen = true; try { @@ -85,6 +91,7 @@ public void BeginFrame(RuntimeFrame frame) throw; } } + /// /// Advances one deterministic simulation step. /// @@ -96,6 +103,7 @@ public void FixedUpdate(RuntimeFixedFrame frame) EnsureFrame(); OnFixedUpdate(frame); } + /// /// Advances variable simulation state. /// @@ -107,6 +115,7 @@ public void Update(RuntimeFrame frame) EnsureFrame(); OnUpdate(frame); } + /// /// Advances state that depends on completed variable simulation. /// @@ -118,6 +127,7 @@ public void LateUpdate(RuntimeFrame frame) EnsureFrame(); OnLateUpdate(frame); } + /// /// Prepares frame output after simulation has completed. /// @@ -129,6 +139,7 @@ public void BeforeRender(RuntimeFrame frame) EnsureFrame(); OnPrepareOutput(frame); } + /// /// Produces frame output owned by this subsystem. /// @@ -140,6 +151,7 @@ public void Render(RuntimeFrame frame) EnsureFrame(); OnProduceOutput(frame); } + /// /// Finalizes frame output even when rendering fails. /// @@ -151,6 +163,7 @@ public void AfterRender(RuntimeFrame frame) EnsureFrame(); OnCompleteOutput(frame); } + /// /// Ends one frame and releases frame-scoped state. /// @@ -160,20 +173,26 @@ public void AfterRender(RuntimeFrame frame) public void EndFrame(RuntimeFrame frame) { if (!m_frameOpen) + { return; + } EnsureThread(); List failures = []; TryRelease(() => OnEndFrame(frame), failures); for (int index = m_frameScopes.Count - 1; index >= 0; index--) + { TryRelease(m_frameScopes[index].Dispose, failures); + } m_frameScopes.Clear(); m_frameOpen = false; ThrowFailures(failures); } + /// /// Releases attached session resources before dependencies detach. /// public void Detach() => Dispose(); + /// /// Releases this owner's registrations and resources exactly once. /// @@ -186,13 +205,19 @@ public void EndFrame(RuntimeFrame frame) public void Dispose() { if (m_disposed) + { return; + } EnsureThread(); m_stopping = true; TryRelease(() => EndFrame(default), m_retirementFailures); TryRelease(m_lifetime.Cancel, m_retirementFailures); if (!m_lifetime.isQuiescent) - throw new RetirementPendingException("Subsystem retirement is pending: tracked work must finish before domain resources can be released."); + { + throw new RetirementPendingException( + "Subsystem retirement is pending: tracked work must finish before domain resources can be released." + ); + } if (!m_stopCompleted) { TryRetire(OnStop); @@ -203,7 +228,9 @@ public void Dispose() Exception[] failures = m_retirementFailures.ToArray(); m_retirementFailures.Clear(); if (failures.Length > 0) + { throw new AggregateException("Subsystem retirement failed after all cleanup stages were attempted.", failures); + } } /// @@ -225,88 +252,108 @@ protected void OwnFrameScope(IDisposable scope) /// /// Acquires resources after dependencies have started. /// - protected virtual void OnStart() { } + protected virtual void OnStart() {} + /// /// Captures snapshots and binds service façades. /// /// /// The variable frame timing. /// - protected virtual void OnBeginFrame(RuntimeFrame frame) { } + protected virtual void OnBeginFrame(RuntimeFrame frame) {} + /// /// Advances one deterministic fixed step. /// /// /// The fixed-step timing. /// - protected virtual void OnFixedUpdate(RuntimeFixedFrame frame) { } + protected virtual void OnFixedUpdate(RuntimeFixedFrame frame) {} + /// /// Advances domain state on the variable clock. /// /// /// The variable frame timing. /// - protected virtual void OnUpdate(RuntimeFrame frame) { } + protected virtual void OnUpdate(RuntimeFrame frame) {} + /// /// Updates state that depends on completed simulation. /// /// /// The variable frame timing. /// - protected virtual void OnLateUpdate(RuntimeFrame frame) { } + protected virtual void OnLateUpdate(RuntimeFrame frame) {} + /// /// Opens resources required for this frame's output. /// /// /// The variable frame timing. /// - protected virtual void OnPrepareOutput(RuntimeFrame frame) { } + protected virtual void OnPrepareOutput(RuntimeFrame frame) {} + /// /// Collects output commands without executing managed code on a native realtime callback. /// /// /// The variable frame timing. /// - protected virtual void OnProduceOutput(RuntimeFrame frame) { } + protected virtual void OnProduceOutput(RuntimeFrame frame) {} + /// /// Submits output and closes output-specific temporary resources. /// /// /// The variable frame timing. /// - protected virtual void OnCompleteOutput(RuntimeFrame frame) { } + protected virtual void OnCompleteOutput(RuntimeFrame frame) {} + /// /// Finalizes control-thread frame state before execution bindings are revoked. /// /// /// The frame being closed. /// - protected virtual void OnEndFrame(RuntimeFrame frame) { } + protected virtual void OnEndFrame(RuntimeFrame frame) {} + /// /// Releases domain resources, including allocations made before attachment. /// - protected virtual void OnStop() { } + protected virtual void OnStop() {} private void EnsureStarted() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("The subsystem is retiring and cannot accept new work."); + } EnsureThread(); if (!m_started) + { throw new InvalidOperationException("The subsystem has not been attached."); + } } + private void EnsureFrame() { EnsureStarted(); if (!m_frameOpen) + { throw new InvalidOperationException("No subsystem frame is active."); + } } + private void EnsureThread() { if (m_ownerThread != 0 && m_ownerThread != Environment.CurrentManagedThreadId) + { throw new InvalidOperationException("Subsystem lifecycle operations require the owner thread."); + } } + private static void TryRelease( Action release, List failures @@ -320,6 +367,7 @@ List failures failures.Add(exception); } } + private void TryRetire(Action release) { try @@ -335,9 +383,12 @@ private void TryRetire(Action release) m_retirementFailures.Add(exception); } } + private static void ThrowFailures(List failures) { if (failures.Count > 0) + { throw new AggregateException("Subsystem retirement failed after all cleanup stages were attempted.", failures); + } } } diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemContext.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemContext.cs index 37748c22e..1187c5c64 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemContext.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemContext.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using System.Linq; using Inno.Core.Diagnostics; using Inno.Core.Events; @@ -64,33 +64,41 @@ public RuntimeSubsystemContext( this.isEditMode = isEditMode; this.capabilities = (capabilities ?? []).ToFrozenSet(); if (this.capabilities.Any(static capability => !capability.isValid)) + { throw new ArgumentException("Available capabilities must be valid.", nameof(capabilities)); + } } /// /// Gets the owner-thread event dispatcher. /// public EventDispatcher events { get; } + /// /// Gets the shared diagnostic state owner. /// public DiagnosticHub diagnostics { get; } + /// /// Gets the isolated live-object identity domain. /// public IdentityAllocator identities { get; } + /// /// Gets the current foundation type catalog. /// public TypeCatalog types { get; } + /// /// Gets resources owned by this pipeline, not by a global container. /// public LifetimeScope resources { get; } + /// /// Gets the owner scope used to validate factory lifetimes. /// public RuntimeSubsystemLifetime lifetime { get; } + /// /// Gets whether scaled simulation should be disabled for authoring. /// diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemDescriptor.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemDescriptor.cs index dbc7329b6..965c6e7dc 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemDescriptor.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemDescriptor.cs @@ -42,21 +42,35 @@ public RuntimeSubsystemDescriptor( IReadOnlyList? requiredCapabilities = null ) { if (!id.isValid) + { throw new ArgumentException("A runtime subsystem requires a valid ID.", nameof(id)); + } if (!Enum.IsDefined(lifetime)) + { throw new ArgumentOutOfRangeException(nameof(lifetime)); + } if (!Enum.IsDefined(requirement)) + { throw new ArgumentOutOfRangeException(nameof(requirement)); + } RuntimeCapabilityId[] capabilities = requiredCapabilities?.ToArray() ?? []; if (capabilities.Any(static capability => !capability.isValid) || capabilities.Distinct().Count() != capabilities.Length) + { throw new ArgumentException("Required capabilities must be valid and unique.", nameof(requiredCapabilities)); + } RuntimeSubsystemId[] dependencySnapshot = dependencies?.ToArray() ?? []; if (dependencySnapshot.Any(static dependency => !dependency.isValid)) + { throw new ArgumentException("Runtime subsystem dependencies must be valid.", nameof(dependencies)); + } if (dependencySnapshot.Contains(id)) + { throw new ArgumentException("A runtime subsystem cannot depend on itself.", nameof(dependencies)); + } if (dependencySnapshot.Distinct().Count() != dependencySnapshot.Length) + { throw new ArgumentException("Runtime subsystem dependencies must be unique.", nameof(dependencies)); + } this.id = id; this.order = order; this.dependencies = Array.AsReadOnly(dependencySnapshot); diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemRequirement.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemRequirement.cs index f72badedd..65dec2fe0 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemRequirement.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystemRequirement.cs @@ -9,7 +9,6 @@ public enum RuntimeSubsystemRequirement /// Missing capabilities, dependencies or failed startup reject the entire owner. /// Required, - /// /// A fully compensated startup may remain unavailable with diagnostics; cleanup failures still reject the owner. /// diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameCodeDeployment.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameCodeDeployment.cs index b9816dc16..4528b1957 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameCodeDeployment.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameCodeDeployment.cs @@ -27,13 +27,23 @@ public GameCodeDeployment(IReadOnlyList modules) foreach (GameCodeModule module in modules) { if (module is null || !accepted.Add(module.name)) + { throw new InvalidDataException("A code deployment contains a null or duplicate module."); + } foreach (string dependency in module.dependencies) + { if (!accepted.Contains(dependency)) + { throw new InvalidDataException($"Code module '{module.name}' precedes dependency '{dependency}'."); + } + } foreach (GameCodeAssembly assembly in module.assemblies) + { if (!assemblies.Add(assembly.name)) + { throw new InvalidDataException($"Code assembly '{assembly.name}' has multiple module owners."); + } + } } this.modules = Array.AsReadOnly(modules.ToArray()); } @@ -58,15 +68,25 @@ public GameCodeDeployment(IReadOnlyList modules) public static GameCodeDeployment FromManifest(IReadOnlyList modules) { ArgumentNullException.ThrowIfNull(modules); - return new GameCodeDeployment(modules.Select(static module => - { - if (module is null) - throw new InvalidDataException("A code deployment contains a null module declaration."); - module.Validate(); - return new GameCodeModule(module.name, module.domain, - module.assemblies.Select(static assembly => new GameCodeAssembly( - assembly.name, assembly.contentFingerprint)).ToArray(), module.dependencies); - }).ToArray()); + return new GameCodeDeployment( + modules.Select(static module => + { + if (module is null) + { + throw new InvalidDataException("A code deployment contains a null module declaration."); + } + module.Validate(); + return new GameCodeModule( + module.name, + module.domain, + module.assemblies.Select(static assembly => new GameCodeAssembly( + assembly.name, + assembly.contentFingerprint + )).ToArray(), + module.dependencies + ); + }).ToArray() + ); } /// @@ -82,15 +102,19 @@ public void ValidateMatches(GameCodeDeployment expected) { ArgumentNullException.ThrowIfNull(expected); if (modules.Count != expected.modules.Count) + { throw new InvalidDataException("The deployed code module count differs from the linked composition."); + } for (int index = 0; index < modules.Count; index++) { GameCodeModule actual = modules[index]; GameCodeModule linked = expected.modules[index]; if (actual.name != linked.name || actual.domain != linked.domain || !actual.dependencies.SequenceEqual(linked.dependencies, StringComparer.Ordinal) - || !actual.assemblies.SequenceEqual(linked.assemblies)) + || !actual.assemblies.SequenceEqual(linked.assemblies) + ) { throw new InvalidDataException($"Code module '{actual.name}' differs from the linked composition."); + } } } } diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs index 0da619a24..b5a65ba34 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs @@ -37,7 +37,9 @@ IReadOnlyList dependencies ArgumentNullException.ThrowIfNull(assemblies); ArgumentNullException.ThrowIfNull(dependencies); if (assemblies.Any(static assembly => assembly is null)) + { throw new System.IO.InvalidDataException("A code module contains a null assembly identity."); + } var declaration = new GameRuntimeModule { name = name, diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeAssembly.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeAssembly.cs index a3480152e..114cea188 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeAssembly.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeAssembly.cs @@ -32,10 +32,14 @@ public sealed class GameRuntimeAssembly : ISerializable public void Validate() { if (string.IsNullOrWhiteSpace(name) - || name.Any(static character => !(char.IsAsciiLetterOrDigit(character) || character is '.' or '_' or '-'))) + || name.Any(static character => !(char.IsAsciiLetterOrDigit(character) || character is '.' or '_' or '-')) + ) { throw new InvalidDataException("A code assembly requires a portable simple name."); + } if (contentFingerprint is null || contentFingerprint.Length != 64 - || contentFingerprint.Any(static character => !(character is >= '0' and <= '9' or >= 'a' and <= 'f'))) + || contentFingerprint.Any(static character => !(character is >= '0' and <= '9' or >= 'a' and <= 'f')) + ) { throw new InvalidDataException($"Code assembly '{name}' requires a lowercase SHA-256 fingerprint."); + } } } diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeManifest.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeManifest.cs index 8763b6a14..244f718e7 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeManifest.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeManifest.cs @@ -72,52 +72,71 @@ public void Validate() || applicationId.Any(static character => !(character is >= 'a' and <= 'z' || character is >= '0' and <= '9' - || character is '.' or '_' or '-'))) - { + || character is '.' or '_' or '-')) + ) { throw new InvalidDataException("A game application ID must use lowercase portable identifier characters."); } if (string.IsNullOrWhiteSpace(productName)) + { throw new InvalidDataException("A game product name is required."); + } if (persistentDataPath is null) + { throw new InvalidDataException("Game persistent data path cannot be null."); + } RuntimeManifestEnvelope.ValidatePersistentDataPath( - persistentDataPath.Length == 0 ? applicationId : persistentDataPath); + persistentDataPath.Length == 0 ? applicationId : persistentDataPath + ); if (string.IsNullOrWhiteSpace(startupScene)) + { throw new InvalidDataException("A game startup scene is required."); + } if (windowWidth <= 0 || windowHeight <= 0) + { throw new InvalidDataException("Game window dimensions must be positive."); + } if (plugins is null || modules is null) + { throw new InvalidDataException("Game Plugin contributions and runtime modules cannot be null."); + } var accepted = new HashSet(StringComparer.Ordinal); foreach (GameRuntimePlugin plugin in plugins) { plugin.Validate(); if (!accepted.Add(plugin.id)) + { throw new InvalidDataException($"Game Plugin '{plugin.id}' is declared more than once."); + } string? missing = plugin.dependencies.FirstOrDefault(dependency => !accepted.Contains(dependency)); if (missing is not null) { - throw new InvalidDataException( - $"Game Plugin '{plugin.id}' appears before dependency '{missing}'."); + throw new InvalidDataException($"Game Plugin '{plugin.id}' appears before dependency '{missing}'."); } } if (modules.Length == 0) + { throw new InvalidDataException("A game runtime manifest requires a managed module generation."); + } accepted.Clear(); foreach (GameRuntimeModule module in modules) { if (module is null) + { throw new InvalidDataException("A game runtime manifest contains a null module."); + } module.Validate(); if (!accepted.Add(module.name)) + { throw new InvalidDataException($"Runtime module '{module.name}' is declared more than once."); + } string? missing = module.dependencies.FirstOrDefault(dependency => !accepted.Contains(dependency)); if (missing is not null) { throw new InvalidDataException( - $"Runtime module '{module.name}' appears before dependency '{missing}'."); + $"Runtime module '{module.name}' appears before dependency '{missing}'." + ); } } _ = GameCodeDeployment.FromManifest(modules); @@ -136,6 +155,7 @@ public IReadOnlyList CreateSettingContributors() plugin.id, plugin.dependencies, plugin.overrides, - plugin.settings)).ToArray(); + plugin.settings + )).ToArray(); } } diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeModule.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeModule.cs index 524cc7844..e89390759 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeModule.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimeModule.cs @@ -45,26 +45,35 @@ public sealed class GameRuntimeModule : ISerializable public void Validate() { if (string.IsNullOrWhiteSpace(name)) + { throw new InvalidDataException("A runtime module requires a stable name."); + } if (domain is not (AssemblyDomain.InnoPlugin or AssemblyDomain.InnoScripting)) + { throw new InvalidDataException($"Runtime module '{name}' has an invalid ownership domain."); + } if (assemblies is null || dependencies is null || assemblies.Length == 0) + { throw new InvalidDataException($"Runtime module '{name}' requires code and dependency collections."); + } foreach (GameRuntimeAssembly assembly in assemblies) { if (assembly is null) + { throw new InvalidDataException($"Runtime module '{name}' contains a null code identity."); + } assembly.Validate(); } if (assemblies.Select(static assembly => assembly.name).Distinct(StringComparer.OrdinalIgnoreCase).Count() - != assemblies.Length) + != assemblies.Length + ) { throw new InvalidDataException($"Runtime module '{name}' contains duplicate code identities."); + } if (dependencies.Any(string.IsNullOrWhiteSpace) || dependencies.Contains(name, StringComparer.Ordinal) - || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Length) - { + || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Length + ) { throw new InvalidDataException($"Runtime module '{name}' contains invalid dependencies."); } } - } diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimePlugin.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimePlugin.cs index b4822cbf0..5332a3de6 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimePlugin.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameRuntimePlugin.cs @@ -45,24 +45,33 @@ public sealed class GameRuntimePlugin : ISerializable public void Validate() { if (string.IsNullOrWhiteSpace(id)) + { throw new InvalidDataException("A runtime Plugin contribution requires an ID."); + } if (dependencies is null || overrides is null || settings is null) + { throw new InvalidDataException($"Runtime Plugin '{id}' contains a null collection."); + } if (dependencies.Any(string.IsNullOrWhiteSpace) - || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Length) - { + || dependencies.Distinct(StringComparer.Ordinal).Count() != dependencies.Length + ) { throw new InvalidDataException($"Runtime Plugin '{id}' has invalid dependencies."); } if (overrides.Any(dependency => !dependencies.Contains(dependency, StringComparer.Ordinal))) + { throw new InvalidDataException($"Runtime Plugin '{id}' overrides an undeclared dependency."); + } if (settings.Select(static setting => setting.id).Distinct().Count() != settings.Length) - throw new InvalidDataException($"Runtime Plugin '{id}' has duplicate setting contributions."); - if (settings.Any(static setting => - !setting.id.isValid - || setting.stableTypeId == Guid.Empty - || setting.propertyData is null - || setting.propertyData.Length == 0)) { + throw new InvalidDataException($"Runtime Plugin '{id}' has duplicate setting contributions."); + } + if (settings.Any(static setting => ( + !setting.id.isValid + || setting.stableTypeId == Guid.Empty + || setting.propertyData is null + || setting.propertyData.Length == 0 + )) + ) { throw new InvalidDataException($"Runtime Plugin '{id}' has an invalid setting contribution."); } } diff --git a/src/runtime/engine/Inno.Runtime/Deployment/RuntimeContentCatalog.cs b/src/runtime/engine/Inno.Runtime/Deployment/RuntimeContentCatalog.cs index 1829573f8..6dc6d7299 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/RuntimeContentCatalog.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/RuntimeContentCatalog.cs @@ -55,11 +55,17 @@ public sealed class RuntimeContentCatalog : ISerializable public void Validate() { if (!IsSha256(contentHash) || !IsSha256(snapshotFingerprint)) + { throw new InvalidDataException("Runtime content identities must be SHA-256 values."); + } if (!string.Equals(packFileName, $"content-{contentHash}.pack", StringComparison.Ordinal)) + { throw new InvalidDataException("Runtime content pack file name does not match its content identity."); + } if (assetCount < 0 || artifactBundleCount < 0 || runtimeAssemblyCount <= 0) + { throw new InvalidDataException("Runtime content catalog contains invalid deployment counts."); + } } private static bool IsSha256(string value) => value is { Length: 64 } && value.All(static character => Uri.IsHexDigit(character)); diff --git a/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs b/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs index c21ce9fe2..3aca1fb53 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs @@ -40,10 +40,11 @@ SerializationGeneration serialization manifest.Validate(); byte[] applicationId = Encoding.UTF8.GetBytes(manifest.applicationId); byte[] persistentDataPath = Encoding.UTF8.GetBytes( - manifest.persistentDataPath.Length == 0 ? manifest.applicationId : manifest.persistentDataPath); + manifest.persistentDataPath.Length == 0 ? manifest.applicationId : manifest.persistentDataPath + ); byte[] payload = serialization.Serialize(manifest); - byte[] result = new byte[checked(magic.Length + sizeof(int) * 3 + - applicationId.Length + persistentDataPath.Length + payload.Length)]; + byte[] result = new byte[checked(magic.Length + sizeof(int) * 3 + + applicationId.Length + persistentDataPath.Length + payload.Length)]; int offset = 0; magic.CopyTo(result); offset += magic.Length; @@ -126,11 +127,16 @@ SerializationGeneration serialization GameRuntimeManifest manifest = serialization.Deserialize(payload); manifest.Validate(); if (!string.Equals(applicationId, manifest.applicationId, StringComparison.Ordinal)) + { throw new InvalidDataException("Runtime manifest application identities do not match."); + } string expectedPath = manifest.persistentDataPath.Length == 0 - ? manifest.applicationId : manifest.persistentDataPath; + ? manifest.applicationId + : manifest.persistentDataPath; if (!string.Equals(persistentDataPath, expectedPath, StringComparison.Ordinal)) + { throw new InvalidDataException("Runtime manifest persistent data paths do not match."); + } return manifest; } @@ -142,12 +148,16 @@ out ReadOnlySpan payload ) { int minimumLength = magic.Length + sizeof(int) * 3; if (data.Length < minimumLength || !data[..magic.Length].SequenceEqual(magic)) + { throw new InvalidDataException("Runtime manifest envelope has an invalid header."); + } int offset = magic.Length; int applicationIdLength = BinaryPrimitives.ReadInt32LittleEndian(data[offset..]); offset += sizeof(int); if (applicationIdLength <= 0 || applicationIdLength > 255 || applicationIdLength > data.Length - offset - sizeof(int) * 2) + { throw new InvalidDataException("Runtime manifest envelope has an invalid application identity length."); + } try { applicationId = new UTF8Encoding(false, true).GetString(data.Slice(offset, applicationIdLength)); @@ -159,9 +169,9 @@ out ReadOnlySpan payload offset += applicationIdLength; int persistentDataPathLength = BinaryPrimitives.ReadInt32LittleEndian(data[offset..]); offset += sizeof(int); - if (persistentDataPathLength <= 0 || persistentDataPathLength > 1024 || - persistentDataPathLength > data.Length - offset - sizeof(int)) - { + if (persistentDataPathLength <= 0 || persistentDataPathLength > 1024 + || persistentDataPathLength > data.Length - offset - sizeof(int) + ) { throw new InvalidDataException("Runtime manifest envelope has an invalid persistent data path length."); } try @@ -176,20 +186,24 @@ out ReadOnlySpan payload int payloadLength = BinaryPrimitives.ReadInt32LittleEndian(data[offset..]); offset += sizeof(int); if (payloadLength <= 0 || payloadLength != data.Length - offset) + { throw new InvalidDataException("Runtime manifest envelope has an invalid payload length."); + } payload = data[offset..]; } private static void ValidateApplicationId(string applicationId) { if (string.IsNullOrWhiteSpace(applicationId)) + { throw new InvalidDataException("Runtime manifest requires an application identity."); + } foreach (char character in applicationId) { if (!(character is >= 'a' and <= 'z' || character is >= '0' and <= '9' - || character is '.' or '_' or '-')) - { + || character is '.' or '_' or '-') + ) { throw new InvalidDataException("Runtime manifest contains an invalid application identity."); } } @@ -198,17 +212,23 @@ private static void ValidateApplicationId(string applicationId) internal static void ValidatePersistentDataPath(string persistentDataPath) { if (persistentDataPath is null) + { throw new InvalidDataException("Runtime manifest requires a persistent data path value."); + } if (persistentDataPath.Length == 0) + { return; + } foreach (string segment in persistentDataPath.Split('/')) { string stem = segment.Split('.', 2)[0]; if (segment is "." or ".." || string.IsNullOrEmpty(segment) || segment.EndsWith('.') || stem is "con" or "prn" or "aux" or "nul" || (stem.Length == 4 && (stem.StartsWith("com", StringComparison.Ordinal) - || stem.StartsWith("lpt", StringComparison.Ordinal)) && stem[3] is >= '1' and <= '9')) + || stem.StartsWith("lpt", StringComparison.Ordinal)) && stem[3] is >= '1' and <= '9') + ) { throw new InvalidDataException("Runtime manifest contains an invalid persistent data folder."); + } ValidateApplicationId(segment); } } diff --git a/src/runtime/engine/Inno.Runtime/Execution/Time.cs b/src/runtime/engine/Inno.Runtime/Execution/Time.cs index f451733ae..6ebcd1a68 100644 --- a/src/runtime/engine/Inno.Runtime/Execution/Time.cs +++ b/src/runtime/engine/Inno.Runtime/Execution/Time.cs @@ -1,7 +1,7 @@ -using Inno.Runtime.Contracts; -using Inno.Core.Execution; using System; using System.Threading; +using Inno.Core.Execution; +using Inno.Runtime.Contracts; namespace Inno.Runtime; @@ -132,14 +132,7 @@ internal RuntimeFrame Update(float unscaledDeltaTime) unscaledTime += unscaledDeltaTime; deltaTime = isPaused ? 0f : unscaledDeltaTime * timeScale; time += deltaTime; - var frame = new RuntimeFrame( - frameCount, - time, - unscaledTime, - deltaTime, - unscaledDeltaTime, - timeScale, - isPaused); + var frame = new RuntimeFrame(frameCount, time, unscaledTime, deltaTime, unscaledDeltaTime, timeScale, isPaused); frameCount++; return frame; } @@ -156,10 +149,11 @@ internal RuntimeFixedFrame BeginFixedStep(float fixedDeltaTime) internal void SetTimeScale(float value) { if (!float.IsFinite(value) || value < 0f) + { throw new ArgumentOutOfRangeException(nameof(value), "Time scale must be finite and non-negative."); + } timeScale = value; } internal void SetPaused(bool value) => isPaused = value; - } diff --git a/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs b/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs index 5f7f23e2c..a43449cfe 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs @@ -1,16 +1,15 @@ using System; using System.Collections.Generic; - -using Inno.Extensibility.Modules; using Inno.Core.Diagnostics; using Inno.Core.Events; using Inno.Core.Execution; using Inno.Core.Identity; -using Inno.Runtime.Contracts; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Runtime.Contracts; namespace Inno.Runtime; @@ -108,7 +107,9 @@ public RuntimeSession CreateSession(RuntimeSessionOptions options) { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("The engine host is retiring and cannot acquire new owners."); + } generations.EnsureReady("create a runtime session"); var session = new RuntimeSession(this, options); m_sessions.Add(session); @@ -149,10 +150,19 @@ public RuntimeSubsystemPipeline CreateHostPipeline( { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("The engine host is retiring and cannot acquire new owners."); + } generations.EnsureReady("create a host subsystem pipeline"); - var context = new RuntimeSubsystemContext(new EventDispatcher(), diagnostics, - new IdentityAllocator(), types, new LifetimeScope(), RuntimeSubsystemLifetime.Host, capabilities: capabilities); + var context = new RuntimeSubsystemContext( + new EventDispatcher(), + diagnostics, + new IdentityAllocator(), + types, + new LifetimeScope(), + RuntimeSubsystemLifetime.Host, + capabilities: capabilities + ); var pipeline = new RuntimeSubsystemPipeline(context, retirementTimeout, generations); m_hostPipelines.Add(pipeline); try @@ -178,14 +188,18 @@ public RuntimeSubsystemPipeline CreateHostPipeline( public void Dispose() { if (m_disposed) + { return; + } generations.EnsureRetirementSafe(); try { // Metadata-only hosts are thread-neutral; attached subsystems enforce their own control thread. m_retirement ??= new RetirementBarrier("EngineHost", retirementTimeout); if (!m_retirement.TryComplete(DisposeCore)) + { throw new RetirementPendingException("EngineHost is still draining owned sessions or pipelines."); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is RetirementTimeoutException) { @@ -209,7 +223,9 @@ private void DisposeCore() lock (m_sync) { if (m_disposed) + { return; + } m_stopping = true; sessions = [.. m_sessions]; } @@ -292,7 +308,9 @@ private void DisposeCore() internal void Release(RuntimeSession session) { lock (m_sync) + { m_sessions.Remove(session); + } } private void RetireFailedStartup( @@ -301,7 +319,9 @@ Exception startupFailure ) { IDisposable? reservation = null; if (generations.state == GenerationState.Ready) + { _ = generations.TryAcquireChange("retire failed runtime startup", out reservation); + } using IDisposable? generationReservation = reservation; try { @@ -312,7 +332,9 @@ Exception startupFailure var failure = new AggregateException("Runtime startup and retirement failed.", startupFailure, cleanupFailure); generations.Fault(failure); if (RetirementPendingException.Find(cleanupFailure) is not null) + { throw; + } throw failure; } } diff --git a/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs b/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs index 1220cd696..5294b15fd 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs @@ -32,7 +32,9 @@ public sealed class EngineHostBuilder public EngineHostBuilder UseRetirementTimeout(TimeSpan timeout) { if (timeout <= TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(timeout)); + } m_retirementTimeout = timeout; return this; } @@ -46,9 +48,16 @@ public EngineHostBuilder UseRetirementTimeout(TimeSpan timeout) public EngineHost Build() { if (m_moduleSource is null || m_typeSource is null || m_serializationMetadata is null) + { throw new InvalidOperationException("The composition root must select module, type and serialization metadata sources."); - EngineHost host = new(m_retirementTimeout, m_logDeliveryMode, - m_moduleSource, m_typeSource, m_serializationMetadata); + } + EngineHost host = new( + m_retirementTimeout, + m_logDeliveryMode, + m_moduleSource, + m_typeSource, + m_serializationMetadata + ); m_moduleSource = null; m_typeSource = null; m_serializationMetadata = null; @@ -79,7 +88,9 @@ ISerializationMetadataSource serialization ArgumentNullException.ThrowIfNull(types); ArgumentNullException.ThrowIfNull(serialization); if (m_moduleSource is not null) + { throw new InvalidOperationException("Metadata sources have already been selected."); + } m_moduleSource = modules; m_typeSource = types; m_serializationMetadata = serialization; @@ -101,7 +112,9 @@ ISerializationMetadataSource serialization public EngineHostBuilder UseLogDelivery(LogDeliveryMode deliveryMode) { if (!Enum.IsDefined(deliveryMode)) + { throw new ArgumentOutOfRangeException(nameof(deliveryMode)); + } m_logDeliveryMode = deliveryMode; return this; } diff --git a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeJobExecutionMode.cs b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeJobExecutionMode.cs index 24f8d97e5..7b35d0b06 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeJobExecutionMode.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeJobExecutionMode.cs @@ -9,7 +9,6 @@ public enum RuntimeJobExecutionMode /// Executes jobs deterministically on the session owner thread. /// SingleThread, - /// /// Executes ready jobs on a bounded worker pool owned by the session. /// diff --git a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs index ba9eaca98..7a596205d 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs @@ -1,4 +1,3 @@ -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; using System.Linq; @@ -12,6 +11,7 @@ using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.References; +using Inno.Runtime.Contracts; using Inno.Scene; namespace Inno.Runtime; @@ -59,17 +59,19 @@ internal void Start() _ => throw new ArgumentOutOfRangeException( nameof(options), options.jobExecutionMode, - "Unknown runtime job execution mode.") + "Unknown runtime job execution mode." + ) }, new JobSchedulerOptions { workerCount = options.jobWorkerCount - }); + } + ); scenes = new SceneWorld(m_identities, m_host.types); if (options.createLogSink is not null) { ILogSink sink = options.createLogSink(sessionId) - ?? throw new InvalidOperationException("The session log factory returned no sink."); + ?? throw new InvalidOperationException("The session log factory returned no sink."); m_sessionLog = new SessionLogSink(sessionId, sink); m_host.logs.RegisterSink(m_sessionLog); } @@ -83,21 +85,31 @@ internal void Start() m_host.types.current, m_identities, options.assetResidencyBudgetBytes, - options.assetPreparationBudgetBytes); + options.assetPreparationBudgetBytes + ); } IReferenceResolver[] referenceResolvers = m_assets is IReferenceResolver assetResolver - ? [.. options.referenceResolvers, assetResolver] - : [.. options.referenceResolvers]; + ? [.. options.referenceResolvers, assetResolver] + : [.. options.referenceResolvers]; IAssetReferenceResolver? prefabAssets = m_assets - ?? options.referenceResolvers.OfType().SingleOrDefault(); + ?? options.referenceResolvers.OfType().SingleOrDefault(); if (prefabAssets is not null) + { scenes.ConfigurePrefabInstantiation(m_host.serialization, prefabAssets); + } m_references = referenceResolvers.Length == 0 - ? ReferenceCatalog.empty - : ReferenceCatalog.Create(1, referenceResolvers); - var context = new RuntimeSubsystemContext(events, m_host.diagnostics, m_identities, m_host.types, - new LifetimeScope(), RuntimeSubsystemLifetime.Session, - options.kind == RuntimeSessionKind.Edit, options.capabilities); + ? ReferenceCatalog.empty + : ReferenceCatalog.Create(1, referenceResolvers); + var context = new RuntimeSubsystemContext( + events, + m_host.diagnostics, + m_identities, + m_host.types, + new LifetimeScope(), + RuntimeSubsystemLifetime.Session, + options.kind == RuntimeSessionKind.Edit, + options.capabilities + ); m_subsystems = new RuntimeSubsystemPipeline(context, m_host.retirementTimeout, m_host.generations); m_subsystems.Start([new SceneRuntimeSubsystemFactory(scenes, options.kind), .. options.createSubsystems(this)]); } @@ -167,7 +179,8 @@ public bool isPaused /// public AssetDatabase assets => m_assets ?? throw new InvalidOperationException( - "This runtime session was created without a deployed asset database."); + "This runtime session was created without a deployed asset database." + ); /// /// Binds this session's script façades to the current asynchronous execution context. @@ -190,13 +203,17 @@ public IDisposable EnterExecutionScope() scopes.Add(scenes.EnterScope()); scopes.Add(m_clock.EnterScope()); if (m_assets is not null) + { scopes.Add(AssetExecutionContext.EnterScope(m_assets)); + } return new ExecutionScope(scopes); } catch { for (int index = scopes.Count - 1; index >= 0; index--) + { scopes[index].Dispose(); + } throw; } } @@ -233,16 +250,16 @@ public void Tick(float deltaTime) m_fixedAccumulator += frame.deltaTime; int steps = 0; while (m_fixedAccumulator >= options.fixedDeltaTime - && steps < options.maxFixedStepsPerFrame) - { + && steps < options.maxFixedStepsPerFrame + ) { RuntimeFixedFrame fixedFrame = m_clock.BeginFixedStep(options.fixedDeltaTime); subsystems.FixedUpdate(fixedFrame); m_fixedAccumulator -= options.fixedDeltaTime; steps++; } if (steps == options.maxFixedStepsPerFrame - && m_fixedAccumulator >= options.fixedDeltaTime) - { + && m_fixedAccumulator >= options.fixedDeltaTime + ) { m_fixedAccumulator = 0f; } } @@ -255,7 +272,9 @@ public void Tick(float deltaTime) try { if (subsystemFrameActive) + { subsystems.EndFrame(frame); + } } finally { @@ -305,7 +324,9 @@ public void Dispose() finally { if (m_disposed) + { m_host.Release(this); + } } } @@ -314,12 +335,16 @@ public void Dispose() private void Retire() { if (m_disposed) + { return; + } m_host.generations.EnsureRetirementSafe(); try { if (!m_retirement.TryComplete(DisposeCore)) + { throw new RetirementPendingException($"Runtime session {sessionId} is still draining owned work."); + } } catch (Exception failure) when (RetirementPendingException.Find(failure) is RetirementTimeoutException) { @@ -340,16 +365,24 @@ private void Retire() private void DisposeCore() { if (m_disposed) + { return; + } try { using IDisposable? scope = scenes is null ? null : EnterExecutionScope(); if (m_subsystems is not null) + { DisposeStage(m_subsystems, ref m_retirementFailures); + } if (m_assets is not null) + { DisposeStage(m_assets, ref m_retirementFailures); + } if (scenes is not null) + { DisposeStage(scenes, ref m_retirementFailures); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -363,9 +396,13 @@ private void DisposeCore() m_disposed = true; DisposeStage(m_coroutines, ref m_retirementFailures); if (m_jobs is not null) + { DisposeStage(m_jobs, ref m_retirementFailures); + } if (m_serialization is not null) + { DisposeStage(m_serialization, ref m_retirementFailures); + } if (m_sessionLog is not null) { m_host.logs.UnregisterSink(m_sessionLog); @@ -384,15 +421,25 @@ private static RuntimeSessionOptions Validate(RuntimeSessionOptions options) ArgumentNullException.ThrowIfNull(options); ArgumentException.ThrowIfNullOrWhiteSpace(options.applicationId); if (!float.IsFinite(options.fixedDeltaTime) || options.fixedDeltaTime <= 0f) + { throw new ArgumentOutOfRangeException(nameof(options), "Fixed delta time must be positive."); + } if (options.assetResidencyBudgetBytes < 0) + { throw new ArgumentOutOfRangeException(nameof(options), "Asset residency budget cannot be negative."); + } if (options.assetPreparationBudgetBytes <= 0) + { throw new ArgumentOutOfRangeException(nameof(options), "Asset preparation budget must be positive."); + } if (!float.IsFinite(options.maxFrameDeltaTime) || options.maxFrameDeltaTime <= 0f) + { throw new ArgumentOutOfRangeException(nameof(options), "Maximum frame delta time must be positive."); + } if (options.maxFixedStepsPerFrame <= 0) + { throw new ArgumentOutOfRangeException(nameof(options), "Maximum fixed steps must be positive."); + } if (options.kind == RuntimeSessionKind.Player && options.contentStore is null) { throw new ArgumentException("A Player session requires an immutable content store.", nameof(options)); @@ -411,11 +458,13 @@ private static RuntimeSessionOptions Validate(RuntimeSessionOptions options) jobExecutionMode = options.jobExecutionMode, jobWorkerCount = options.jobWorkerCount, createSubsystems = options.createSubsystems - ?? throw new ArgumentException("Runtime subsystem factories cannot be null.", nameof(options)), - capabilities = Array.AsReadOnly(options.capabilities?.ToArray() - ?? throw new ArgumentException("Runtime capabilities cannot be null.", nameof(options))), + ?? throw new ArgumentException("Runtime subsystem factories cannot be null.", nameof(options)), + capabilities = Array.AsReadOnly( + options.capabilities?.ToArray() + ?? throw new ArgumentException("Runtime capabilities cannot be null.", nameof(options)) + ), referenceResolvers = options.referenceResolvers?.ToArray() - ?? throw new ArgumentException("Runtime reference resolvers cannot be null.", nameof(options)) + ?? throw new ArgumentException("Runtime reference resolvers cannot be null.", nameof(options)) }; } @@ -448,11 +497,14 @@ private sealed class ExecutionScope(IReadOnlyList scopes) : IDispos public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; for (int index = scopes.Count - 1; index >= 0; index--) + { scopes[index].Dispose(); + } } } - } diff --git a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionKind.cs b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionKind.cs index 5e33da03d..5ca061cb4 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionKind.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionKind.cs @@ -9,12 +9,10 @@ public enum RuntimeSessionKind /// An authoring session whose scene world remains editable. /// Edit, - /// /// A disposable Editor play-test session created from an immutable start snapshot. /// Play, - /// /// A deployed standalone game session backed only by runtime artifacts. /// diff --git a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionOptions.cs b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionOptions.cs index 9a20efe8e..49aece16b 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionOptions.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSessionOptions.cs @@ -1,10 +1,9 @@ -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; - -using Inno.References; using Inno.Content; using Inno.Core.Logging; +using Inno.References; +using Inno.Runtime.Contracts; namespace Inno.Runtime; diff --git a/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs b/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs index a5502c45e..667b115b2 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs @@ -20,14 +20,18 @@ ILogSink sink public void Receive(LogEntry entry) { if (entry.sessionId == m_sessionId) + { m_sink?.Receive(entry); + } } /// public void Dispose() { if (m_sink is IDisposable owner) + { owner.Dispose(); + } m_sink = null; } } diff --git a/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs b/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs index 660ae681b..ae666e2af 100644 --- a/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs +++ b/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Types; @@ -66,7 +65,9 @@ int availableHeight ArgumentOutOfRangeException.ThrowIfNegativeOrZero(referenceWidth); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(referenceHeight); if (!preserveAspectRatio) + { return new GamePresentationViewport(0, 0, availableWidth, availableHeight); + } double targetAspect = referenceWidth / (double)referenceHeight; int width = availableWidth; @@ -81,7 +82,8 @@ int availableHeight (availableWidth - width) / 2, (availableHeight - height) / 2, width, - height); + height + ); } } diff --git a/src/runtime/engine/Inno.Runtime/Properties/ScriptingApi.cs b/src/runtime/engine/Inno.Runtime/Properties/ScriptingApi.cs index ed98d10eb..5a385c4c3 100644 --- a/src/runtime/engine/Inno.Runtime/Properties/ScriptingApi.cs +++ b/src/runtime/engine/Inno.Runtime/Properties/ScriptingApi.cs @@ -1,11 +1,6 @@ -using Inno.Scripting.Api; using Inno.Runtime; +using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Core", - "Inno.Runtime", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Core", "Inno.Runtime", ScriptingApiScope.Runtime)] -[assembly: ScriptingApiExport( - typeof(Time), - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiExport(typeof(Time), ScriptingApiScope.Runtime)] diff --git a/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs b/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs index 804abdfed..323f1505b 100644 --- a/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs +++ b/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs @@ -33,8 +33,10 @@ IReadOnlyList frameworkAssemblies ArgumentNullException.ThrowIfNull(assemblies); ArgumentNullException.ThrowIfNull(frameworkAssemblies); if (assemblies.Any(static assembly => assembly is null || assembly.IsCollectible) - || frameworkAssemblies.Any(static assembly => assembly is null || assembly.IsCollectible)) + || frameworkAssemblies.Any(static assembly => assembly is null || assembly.IsCollectible) + ) { throw new ArgumentException("A static catalog requires noncollectible linked assemblies.", nameof(assemblies)); + } m_assemblies = Array.AsReadOnly(assemblies.Distinct().ToArray()); m_framework = frameworkAssemblies.ToHashSet(); m_frameworkNames = frameworkAssemblies.Select(static assembly => assembly.GetName().Name!) @@ -45,8 +47,11 @@ IReadOnlyList frameworkAssemblies /// public event Action? changed { - add { ObjectDisposedException.ThrowIf(m_disposed, this); } - remove { } + add + { + ObjectDisposedException.ThrowIf(m_disposed, this); + } + remove {} } /// @@ -70,6 +75,7 @@ public bool IsFrameworkReference(string assemblyName) ArgumentException.ThrowIfNullOrWhiteSpace(assemblyName); return m_frameworkNames.Contains(assemblyName); } + /// public bool IsFrameworkAssembly(Assembly assembly) { @@ -77,6 +83,7 @@ public bool IsFrameworkAssembly(Assembly assembly) ArgumentNullException.ThrowIfNull(assembly); return m_framework.Contains(assembly); } + /// public void Dispose() => m_disposed = true; } diff --git a/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs b/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs index eaf0a1eb1..5aaf28fa4 100644 --- a/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs +++ b/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs @@ -42,29 +42,44 @@ IReadOnlyList dependencies ArgumentNullException.ThrowIfNull(dependencies); ArgumentNullException.ThrowIfNull(assemblies); if (assemblies.Any(static assembly => assembly is null || assembly.IsCollectible)) + { throw new ArgumentException("A static module requires noncollectible linked assemblies.", nameof(assemblies)); - m_contribution = new ModuleCatalogContribution(moduleName, domain, scope, assemblies, - assemblies.ToDictionary(static assembly => assembly, _ => scope)); + } + m_contribution = new ModuleCatalogContribution( + moduleName, + domain, + scope, + assemblies, + assemblies.ToDictionary(static assembly => assembly, _ => scope) + ); upstreamModuleNames = Array.AsReadOnly(dependencies.ToArray()); assemblyScopes = new ReadOnlyDictionary( - assemblies.ToDictionary(static assembly => assembly.GetName().Name!, _ => scope, StringComparer.OrdinalIgnoreCase)); + assemblies.ToDictionary(static assembly => assembly.GetName().Name!, _ => scope, StringComparer.OrdinalIgnoreCase) + ); } /// public string moduleName => m_contribution.moduleName; + /// public AssemblyDomain domain => m_contribution.domain; + /// public AssemblyScope scope => m_contribution.scope; + /// public bool collectible => false; + /// public IReadOnlyList upstreamModuleNames { get; } + /// public IReadOnlyDictionary assemblyScopes { get; } + /// public IReadOnlyList GetAssemblyNames() => m_contribution.assemblies.Select(static assembly => assembly.GetName().Name!).ToArray(); + /// public ModuleCatalogContribution Prepare(ModuleSourceContext context) { diff --git a/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs b/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs index 779ca707d..849d93c8b 100644 --- a/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs +++ b/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs @@ -2,9 +2,8 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using Inno.Extensibility.Types; - using Inno.Extensibility.Catalogs; +using Inno.Extensibility.Types; namespace Inno.Runtime; @@ -52,7 +51,9 @@ public StaticTypeCatalogSource(IReadOnlyList> cata foreach (Type type in m_factories.Keys.Where(static type => type.IsConstructedGenericType)) { if (!m_metadata.ContainsKey(type.GetGenericTypeDefinition())) + { throw new ArgumentException($"Linked construction '{type}' has no registered declaration.", nameof(catalogs)); + } } m_constructions = m_factories.Keys.Where(static type => type.IsConstructedGenericType) .GroupBy(static type => type.GetGenericTypeDefinition()) @@ -60,28 +61,38 @@ public StaticTypeCatalogSource(IReadOnlyList> cata foreach ((Type definition, List arguments) in m_rejectedConstructions) { if (!m_metadata.ContainsKey(definition)) + { throw new ArgumentException($"Rejected construction '{definition}' has no registered declaration.", nameof(catalogs)); - if (m_constructions.TryGetValue(definition, out Type[]? constructions) && - constructions.Any(construction => arguments.Any(values => construction.GenericTypeArguments.SequenceEqual(values)))) + } + if (m_constructions.TryGetValue(definition, out Type[]? constructions) + && constructions.Any(construction => arguments.Any(values => construction.GenericTypeArguments.SequenceEqual(values))) + ) { throw new ArgumentException($"A linked construction of '{definition}' is also recorded as rejected.", nameof(catalogs)); + } } m_types = m_metadata.Keys.GroupBy(static type => type.Assembly).ToDictionary( static group => group.Key, - static group => (IReadOnlyList)Array.AsReadOnly(group.OrderBy(static type => type.FullName, - StringComparer.Ordinal).ToArray())); + static group => (IReadOnlyList)Array.AsReadOnly( + group.OrderBy(static type => type.FullName, StringComparer.Ordinal).ToArray() + ) + ); foreach (Assembly assembly in assemblies) + { m_types.TryAdd(assembly, Array.Empty()); + } } /// public IReadOnlyList GetTypes(Assembly assembly) - => m_types.TryGetValue(assembly, out IReadOnlyList? types) ? types - : throw new InvalidOperationException($"Linked assembly '{assembly.GetName().Name}' has no generated type catalog."); + => m_types.TryGetValue(assembly, out IReadOnlyList? types) + ? types + : throw new InvalidOperationException($"Linked assembly '{assembly.GetName().Name}' has no generated type catalog."); /// public TypeCatalogMetadata GetMetadata(Type type) - => m_metadata.TryGetValue(type, out TypeCatalogMetadata? metadata) ? metadata - : throw new InvalidOperationException($"Linked declaration '{type}' has no generated metadata."); + => m_metadata.TryGetValue(type, out TypeCatalogMetadata? metadata) + ? metadata + : throw new InvalidOperationException($"Linked declaration '{type}' has no generated metadata."); /// public Type? ConstructGenericType( @@ -91,19 +102,25 @@ IReadOnlyList arguments ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(arguments); ValidateArguments(definition, arguments); - if (m_rejectedConstructions.TryGetValue(definition, out List? rejected) && - rejected.Any(values => values.SequenceEqual(arguments))) + if (m_rejectedConstructions.TryGetValue(definition, out List? rejected) + && rejected.Any(values => values.SequenceEqual(arguments)) + ) { return null; + } if (m_constructions.TryGetValue(definition, out Type[]? constructions)) { foreach (Type construction in constructions) { if (construction.GenericTypeArguments.SequenceEqual(arguments)) + { return construction; + } } } - throw new NotSupportedException($"Generic construction '{definition}' with arguments " + - $"'{string.Join(", ", arguments)}' is absent from the linked factory catalog."); + throw new NotSupportedException( + $"Generic construction '{definition}' with arguments " + + $"'{string.Join(", ", arguments)}' is absent from the linked factory catalog." + ); } /// @@ -114,10 +131,13 @@ public bool CanCreateInstance(Type type) public object CreateInstance(Type type) { if (!m_factories.TryGetValue(type, out Func? factory) || factory is null) + { throw new InvalidOperationException($"Linked type '{type}' has no generated parameterless factory."); + } object instance = factory(); - return type.IsInstanceOfType(instance) ? instance - : throw new InvalidOperationException($"The linked factory for '{type}' returned an incompatible instance."); + return type.IsInstanceOfType(instance) + ? instance + : throw new InvalidOperationException($"The linked factory for '{type}' returned an incompatible instance."); } private static void ValidateArguments( @@ -127,10 +147,14 @@ IReadOnlyList arguments ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(arguments); if (!definition.IsGenericTypeDefinition) + { throw new ArgumentException("The declaration must be a generic type definition.", nameof(definition)); - if (arguments.Count != definition.GetGenericArguments().Length || - arguments.Any(static argument => argument is null || argument.ContainsGenericParameters)) + } + if (arguments.Count != definition.GetGenericArguments().Length + || arguments.Any(static argument => argument is null || argument.ContainsGenericParameters) + ) { throw new ArgumentException("The complete closed type argument set is required.", nameof(arguments)); + } } private sealed class Registration : ITypeCatalogRegistrar @@ -149,7 +173,9 @@ public void Register( RequireOpen(); ArgumentNullException.ThrowIfNull(metadata); if (!this.metadata.TryAdd(metadata.type, metadata)) + { throw new ArgumentException($"Static declaration '{metadata.type}' is registered more than once."); + } factories.Add(metadata.type, factory); } @@ -162,7 +188,9 @@ Func factory ArgumentNullException.ThrowIfNull(type); ArgumentNullException.ThrowIfNull(factory); if (!type.IsConstructedGenericType || type.ContainsGenericParameters) + { throw new ArgumentException("A linked factory requires a fully closed generic type.", nameof(type)); + } // Different assembly-local catalogs can link the same closed construction. factories.TryAdd(type, factory); } @@ -175,9 +203,13 @@ IReadOnlyList arguments RequireOpen(); ValidateArguments(definition, arguments); if (!rejectedConstructions.TryGetValue(definition, out List? rejected)) + { rejectedConstructions.Add(definition, rejected = []); + } if (!rejected.Any(values => values.SequenceEqual(arguments))) + { rejected.Add(arguments.ToArray()); + } } internal void Seal() => m_sealed = true; @@ -185,9 +217,13 @@ IReadOnlyList arguments private void RequireOpen() { if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Type catalog contributions must run on the composition thread."); + } if (m_sealed) + { throw new InvalidOperationException("The type catalog contribution has already completed."); + } } } } diff --git a/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs b/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs index 1c58b9aa9..950a8a514 100644 --- a/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs +++ b/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs @@ -1,10 +1,10 @@ -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; using System.Linq; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Extensibility.Reload; +using Inno.Runtime.Contracts; namespace Inno.Runtime; @@ -56,12 +56,22 @@ internal void Start(IReadOnlyList configuredFactories) ArgumentNullException.ThrowIfNull(configuredFactories); try { - IRuntimeSubsystemFactory[] ordered = Order(configuredFactories.Select(static factory => - (IRuntimeSubsystemFactory)new FactorySnapshot(factory)).ToArray()); + IRuntimeSubsystemFactory[] ordered = Order( + configuredFactories.Select(static factory => + (IRuntimeSubsystemFactory)new FactorySnapshot(factory)).ToArray() + ); if (ordered.Any(factory => factory.descriptor.lifetime != m_context.lifetime)) + { throw new InvalidOperationException($"Subsystem lifetime does not match its {m_context.lifetime} owner."); - m_reporter = m_resources.Own(m_context.diagnostics.CreateReporter(new DiagnosticSource( - $"inno.runtime.subsystems.{m_context.identities.domainId}", "Runtime subsystems"))); + } + m_reporter = m_resources.Own( + m_context.diagnostics.CreateReporter( + new DiagnosticSource( + $"inno.runtime.subsystems.{m_context.identities.domainId}", + "Runtime subsystems" + ) + ) + ); foreach (IRuntimeSubsystemFactory factory in ordered) { RuntimeSubsystemDescriptor descriptor = factory.descriptor; @@ -75,11 +85,18 @@ internal void Start(IReadOnlyList configuredFactories) m_entries.Add(entry); try { - var context = new RuntimeSubsystemContext(m_context.events, m_context.diagnostics, - m_context.identities, m_context.types, entry.resources, m_context.lifetime, - m_context.isEditMode, m_context.capabilities); + var context = new RuntimeSubsystemContext( + m_context.events, + m_context.diagnostics, + m_context.identities, + m_context.types, + entry.resources, + m_context.lifetime, + m_context.isEditMode, + m_context.capabilities + ); entry.subsystem = factory.Create(context) - ?? throw new InvalidOperationException($"Runtime subsystem factory '{descriptor.id}' returned null."); + ?? throw new InvalidOperationException($"Runtime subsystem factory '{descriptor.id}' returned null."); entry.subsystem.Attach(); entry.isAttached = true; } @@ -95,8 +112,13 @@ internal void Start(IReadOnlyList configuredFactories) } catch (Exception cleanupFailure) { - m_generations.Fault(new AggregateException( - $"Optional subsystem '{descriptor.id}' could not compensate startup.", failure, cleanupFailure)); + m_generations.Fault( + new AggregateException( + $"Optional subsystem '{descriptor.id}' could not compensate startup.", + failure, + cleanupFailure + ) + ); throw; } m_entries.RemoveAt(m_entries.Count - 1); @@ -148,10 +170,10 @@ public TFeature GetRequiredSubsystem() return matches.Length switch { 1 => matches[0], - 0 => throw new InvalidOperationException( - $"No runtime subsystem implements '{typeof(TFeature).FullName}'."), + 0 => throw new InvalidOperationException($"No runtime subsystem implements '{typeof(TFeature).FullName}'."), _ => throw new InvalidOperationException( - $"Multiple runtime subsystems implement '{typeof(TFeature).FullName}'.") + $"Multiple runtime subsystems implement '{typeof(TFeature).FullName}'." + ) }; } @@ -165,7 +187,9 @@ public void BeginFrame(RuntimeFrame frame) { EnsureActive(); if (m_frameOpen) + { throw new InvalidOperationException("A runtime subsystem frame is already active."); + } m_frameOpen = true; m_begunEntryCount = 0; for (int index = 0; index < m_entries.Count; index++) @@ -261,16 +285,21 @@ public void RenderFrame( state ) => subsystem.AfterRender(state), frame, - preparedCount); + preparedCount + ); } catch (Exception failure) { failures.Add(failure); } if (failures.Count == 1) + { System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failures[0]).Throw(); + } if (failures.Count > 1) + { throw new AggregateException("Subsystem output and cleanup failed.", failures); + } } /// @@ -282,7 +311,9 @@ public void RenderFrame( public void EndFrame(RuntimeFrame frame) { if (!m_frameOpen) + { return; + } try { ExecuteReverse( @@ -291,7 +322,8 @@ public void EndFrame(RuntimeFrame frame) state ) => subsystem.EndFrame(state), frame, - m_begunEntryCount); + m_begunEntryCount + ); } finally { @@ -309,7 +341,9 @@ public void EndFrame(RuntimeFrame frame) public void Dispose() { if (m_disposed) + { return; + } m_stopping = true; m_frameOpen = false; Release(); @@ -343,7 +377,9 @@ private static IRuntimeSubsystemFactory[] Order(IReadOnlyList factory.descriptor.id, - factory => factory.descriptor.dependencies.Count(byId.ContainsKey)); + factory => factory.descriptor.dependencies.Count(byId.ContainsKey) + ); var dependants = factories.ToDictionary( static factory => factory.descriptor.id, - static _ => new List()); + static _ => new List() + ); foreach (IRuntimeSubsystemFactory factory in factories) { foreach (RuntimeSubsystemId dependency in factory.descriptor.dependencies) + { if (dependants.TryGetValue(dependency, out List? consumers)) + { consumers.Add(factory); + } + } } var ready = new List( - factories.Where(factory => incoming[factory.descriptor.id] == 0)); + factories.Where(factory => incoming[factory.descriptor.id] == 0) + ); var result = new List(factories.Count); while (ready.Count > 0) { @@ -382,7 +426,9 @@ private static IRuntimeSubsystemFactory[] Order(IReadOnlyList pair.Value > 0) .Select(static pair => pair.Key.value) - .Order(StringComparer.Ordinal)); + .Order(StringComparer.Ordinal) + ); throw new InvalidOperationException($"Runtime subsystem dependencies contain a cycle: {unresolved}."); } return result.ToArray(); @@ -403,8 +450,8 @@ IRuntimeSubsystemFactory right ) { int order = left.descriptor.order.CompareTo(right.descriptor.order); return order != 0 - ? order - : StringComparer.Ordinal.Compare(left.descriptor.id.value, right.descriptor.id.value); + ? order + : StringComparer.Ordinal.Compare(left.descriptor.id.value, right.descriptor.id.value); } private void Release() @@ -486,9 +533,12 @@ private static void RetireEntry(Entry entry) { RuntimeCapabilityId[] missing = descriptor.requiredCapabilities.Where(id => !m_context.capabilities.Contains(id)).ToArray(); if (missing.Length > 0) + { return $"Missing capabilities: {string.Join(", ", missing)}."; + } RuntimeSubsystemId[] dependencies = descriptor.dependencies - .Where(id => !m_entries.Any(entry => entry.descriptor.id == id && entry.isAttached)).ToArray(); + .Where(id => !m_entries.Any(entry => entry.descriptor.id == id && entry.isAttached)) + .ToArray(); return dependencies.Length == 0 ? null : $"Unavailable dependencies: {string.Join(", ", dependencies)}."; } @@ -497,9 +547,15 @@ private void RejectOrReport( string reason ) { if (descriptor.requirement == RuntimeSubsystemRequirement.Required) + { throw new InvalidOperationException($"Required subsystem '{descriptor.id}' cannot start: {reason}"); - var diagnostic = new Diagnostic("runtime.subsystem.unavailable", reason, DiagnosticSeverity.Warning, - semanticId: descriptor.id.value); + } + var diagnostic = new Diagnostic( + "runtime.subsystem.unavailable", + reason, + DiagnosticSeverity.Warning, + semanticId: descriptor.id.value + ); m_startupDiagnostics.Add(diagnostic); m_reporter!.Publish(diagnostic); } @@ -509,7 +565,9 @@ private void ExecuteForward( TState state ) { foreach (Entry entry in m_entries) + { action(entry.subsystem, state); + } } private void ExecuteReverse( @@ -531,23 +589,31 @@ int count } } if (failures is not null) + { throw new AggregateException("One or more runtime subsystem phases failed.", failures); + } } private void EnsureActive() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping) + { throw new InvalidOperationException("The subsystem pipeline is retiring and cannot execute new work."); + } if (!m_started) + { throw new InvalidOperationException("The subsystem pipeline has not finished startup."); + } } private void EnsureFrame() { EnsureActive(); if (!m_frameOpen) + { throw new InvalidOperationException("No runtime subsystem frame is active."); + } } private sealed class Entry(RuntimeSubsystemDescriptor descriptor) diff --git a/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs b/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs index 972d38d14..efe341378 100644 --- a/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs +++ b/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs @@ -41,7 +41,9 @@ RuntimeSessionKind sessionKind protected override void OnFixedUpdate(RuntimeFixedFrame frame) { if (sessionKind != RuntimeSessionKind.Edit) + { scenes.FixedUpdate(frame.deltaTime); + } } /// @@ -53,7 +55,9 @@ protected override void OnFixedUpdate(RuntimeFixedFrame frame) protected override void OnUpdate(RuntimeFrame frame) { if (sessionKind != RuntimeSessionKind.Edit && !frame.isPaused) + { scenes.Update(frame.deltaTime); + } } /// @@ -65,6 +69,8 @@ protected override void OnUpdate(RuntimeFrame frame) protected override void OnLateUpdate(RuntimeFrame frame) { if (sessionKind != RuntimeSessionKind.Edit && !frame.isPaused) + { scenes.LateUpdate(frame.deltaTime); + } } } diff --git a/src/runtime/generators/Inno.Runtime.Generators/Diagnostics/RuntimeRegistrationDiagnostics.cs b/src/runtime/generators/Inno.Runtime.Generators/Diagnostics/RuntimeRegistrationDiagnostics.cs index 84d68659d..4b217bf3e 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/Diagnostics/RuntimeRegistrationDiagnostics.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/Diagnostics/RuntimeRegistrationDiagnostics.cs @@ -5,13 +5,24 @@ namespace Inno.Runtime.Generators; internal static class RuntimeRegistrationDiagnostics { private static readonly DiagnosticDescriptor UnavailableConstruction = new( - "INNORUN002", "Static converter construction is unavailable", - "Serialization converter '{0}' cannot be linked: {1}", "Architecture", DiagnosticSeverity.Error, true); + "INNORUN002", + "Static converter construction is unavailable", + "Serialization converter '{0}' cannot be linked: {1}", + "Architecture", + DiagnosticSeverity.Error, + true + ); internal static void ReportUnavailable( SourceProductionContext output, INamedTypeSymbol type, string reason - ) => output.ReportDiagnostic(Diagnostic.Create(UnavailableConstruction, - type.Locations.Length == 0 ? Location.None : type.Locations[0], type.ToDisplayString(), reason)); + ) => output.ReportDiagnostic( + Diagnostic.Create( + UnavailableConstruction, + type.Locations.Length == 0 ? Location.None : type.Locations[0], + type.ToDisplayString(), + reason + ) + ); } diff --git a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs index 1d62bd425..f2798f3d7 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs @@ -19,10 +19,13 @@ public void Initialize(IncrementalGeneratorInitializationContext context) context.RegisterSourceOutput(inputs, static ( output, input - ) => { + ) => + { if (!input.Right.GlobalOptions.TryGetValue("build_property.InnoGeneratePlayerComposition", out string? enabled) - || !string.Equals(enabled, "true", StringComparison.OrdinalIgnoreCase)) + || !string.Equals(enabled, "true", StringComparison.OrdinalIgnoreCase) + ) { return; + } Generate(output, input.Left); }); } @@ -33,15 +36,20 @@ Compilation compilation ) { string assemblyName = compilation.AssemblyName!; string? deploymentDefinition = compilation.GetTypeByMetadataName( - assemblyName + ".Generated.PlayerDeploymentDefinition")?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + assemblyName + ".Generated.PlayerDeploymentDefinition" + )?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); var catalogs = new List<(string name, bool host)>(); foreach (IAssemblySymbol assembly in compilation.SourceModule.ReferencedAssemblySymbols) { if (assembly.GetTypeByMetadataName(assembly.Name + ".Generated.RuntimeModuleCatalog") is null) + { continue; + } string? domain = assembly.GetAttributes() - .Where(static attribute => attribute.AttributeClass?.ToDisplayString() - == "System.Reflection.AssemblyMetadataAttribute" && attribute.ConstructorArguments.Length == 2) + .Where(static attribute => ( + attribute.AttributeClass?.ToDisplayString() == "System.Reflection.AssemblyMetadataAttribute" + && attribute.ConstructorArguments.Length == 2 + )) .Where(static attribute => attribute.ConstructorArguments[0].Value as string == "Inno.AssemblyDomain") .Select(static attribute => attribute.ConstructorArguments[1].Value as string) .FirstOrDefault(); @@ -53,37 +61,58 @@ Compilation compilation right ) => StringComparer.Ordinal.Compare(left.name, right.name)); var code = new StringBuilder("// \n#nullable enable\n"); - code.Append("namespace ").Append(assemblyName).Append(".Generated;\n\n") + code.Append("namespace ") + .Append(assemblyName) + .Append(".Generated;\n\n") .Append("internal static class PlayerMetadataComposition\n{\n") .Append(" internal static global::Inno.Extensibility.Modules.IAssemblyCatalogSource CreateModules() =>\n") .Append(" new global::Inno.Runtime.StaticAssemblyCatalogSource([\n"); foreach (var catalog in catalogs.Where(static catalog => catalog.host)) + { code.Append(" global::").Append(catalog.name).Append(".Generated.RuntimeModuleCatalog.assembly,\n"); + } code.Append(" ], [typeof(object).Assembly]);\n\n") .Append(" internal static global::Inno.Extensibility.Types.ITypeCatalogSource CreateTypes() =>\n") .Append(" new global::Inno.Runtime.StaticTypeCatalogSource([\n"); foreach (var catalog in catalogs) + { code.Append(" global::").Append(catalog.name).Append(".Generated.RuntimeModuleCatalog.Register,\n"); + } code.Append(" ]);\n\n") .Append(" internal static global::Inno.Core.Serialization.ISerializationMetadataSource CreateSerialization() =>\n") .Append(" new global::Inno.Core.Serialization.StaticSerializationMetadataSource([\n"); foreach (IAssemblySymbol assembly in compilation.SourceModule.ReferencedAssemblySymbols - .OrderBy(static assembly => assembly.Name, StringComparer.Ordinal)) + .OrderBy(static assembly => assembly.Name, StringComparer.Ordinal) + ) { if (assembly.GetTypeByMetadataName(assembly.Name + ".Generated.RuntimeSerializationMetadataCatalog") is not null) - code.Append(" global::").Append(assembly.Name).Append(".Generated.RuntimeSerializationMetadataCatalog.Register,\n"); - code.Append(" global::").Append(assemblyName).Append(".Generated.RuntimeSerializationMetadataCatalog.Register,\n") + { + code + .Append(" global::") + .Append(assembly.Name) + .Append(".Generated.RuntimeSerializationMetadataCatalog.Register,\n"); + } + } + code.Append(" global::") + .Append(assemblyName) + .Append(".Generated.RuntimeSerializationMetadataCatalog.Register,\n") .Append(" ]);\n\n") .Append(" internal static global::Inno.Player.Runtime.IPlayerModuleActivator CreateActivator() =>\n") .Append(" new global::Inno.Player.Runtime.StaticPlayerModuleActivator(\n"); if (deploymentDefinition is null) { code.Append(" new global::Inno.Runtime.GameCodeDeployment([]),\n") - .Append(" new global::System.Collections.Generic.Dictionary>());\n"); + .Append( + " new global::System.Collections.Generic.Dictionary>());\n" + ); } else { - code.Append(" ").Append(deploymentDefinition).Append(".CreateDeployment(),\n") - .Append(" ").Append(deploymentDefinition).Append(".CreateAssemblies());\n"); + code.Append(" ") + .Append(deploymentDefinition) + .Append(".CreateDeployment(),\n") + .Append(" ") + .Append(deploymentDefinition) + .Append(".CreateAssemblies());\n"); } code.Append("}\n"); output.AddSource("Registration/RuntimeFactories.g.cs", code.ToString()); diff --git a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs index 8ed0f4665..e4c8fff9d 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs @@ -32,19 +32,29 @@ private static void Generate( Compilation compilation ) { if (compilation.AssemblyName is null) + { return; + } INamedTypeSymbol[] types = EnumerateTypes(compilation.Assembly.GlobalNamespace) .Where(IsAccessible) .OrderBy(static type => type.ToDisplayString(), StringComparer.Ordinal) .ToArray(); var code = new StringBuilder("// \n#nullable enable\n"); - code.Append("namespace ").Append(compilation.AssemblyName).Append(".Generated;\n\n") - .Append("/// \n/// Publishes this assembly's explicit static metadata without scanning its runtime types.\n/// \n") + code.Append("namespace ") + .Append(compilation.AssemblyName) + .Append(".Generated;\n\n") + .Append( + "/// \n/// Publishes this assembly's explicit static metadata without scanning its runtime types.\n/// \n" + ) .Append("public static class RuntimeModuleCatalog\n{\n") .Append(" /// \n /// Gets the assembly owning these declarations.\n /// \n") .Append(" public static global::System.Reflection.Assembly assembly => typeof(RuntimeModuleCatalog).Assembly;\n\n") - .Append(" /// \n /// Contributes declared types and available parameterless factories to one composition.\n /// \n") - .Append(" /// \n /// The composition-owned callback; this catalog does not retain it.\n /// \n") + .Append( + " /// \n /// Contributes declared types and available parameterless factories to one composition.\n /// \n" + ) + .Append( + " /// \n /// The composition-owned callback; this catalog does not retain it.\n /// \n" + ) .Append(" public static void Register(global::Inno.Extensibility.Catalogs.ITypeCatalogRegistrar register)\n {\n") .Append(" global::System.ArgumentNullException.ThrowIfNull(register);\n"); var constructors = new List(); @@ -56,8 +66,8 @@ Compilation compilation { IMethodSymbol? constructor = type.InstanceConstructors.FirstOrDefault(static value => value.Parameters.Length == 0); if (constructor is not null && constructor.DeclaredAccessibility is not - (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal)) - { + (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal) + ) { factory = FormatConstructorCall(type, constructors.Count); constructors.Add(type); } @@ -67,27 +77,45 @@ Compilation compilation } } code.Append(" register.Register(new global::Inno.Extensibility.Catalogs.TypeCatalogMetadata(typeof(") - .Append(typeName).Append(")") - .Append(", ").Append(FormatTypes(GetBaseTypes(type))) - .Append(", ").Append(FormatTypes(type.AllInterfaces)) - .Append(", ").Append(FormatAttributes(type.GetAttributes())) - .Append(", ").Append(FormatAttributes(GetInheritedAttributes(type))) - .Append(", ").Append(FormatOverrides(type)).Append("), ").Append(factory).Append(");\n"); + .Append(typeName) + .Append(")") + .Append(", ") + .Append(FormatTypes(GetBaseTypes(type))) + .Append(", ") + .Append(FormatTypes(type.AllInterfaces)) + .Append(", ") + .Append(FormatAttributes(type.GetAttributes())) + .Append(", ") + .Append(FormatAttributes(GetInheritedAttributes(type))) + .Append(", ") + .Append(FormatOverrides(type)) + .Append("), ") + .Append(factory) + .Append(");\n"); } var constructions = RuntimeTypeCatalogGenerator.Analyze(compilation, output); - foreach (INamedTypeSymbol type in constructions.factories.Where(static type => !CanConstruct(type) && - GetBaseTypes(type).Any(static parent => parent.OriginalDefinition.ToDisplayString() == - "Inno.Core.Serialization.Converters.SerializationConverter"))) - RuntimeRegistrationDiagnostics.ReportUnavailable(output, type, - "a nonabstract converter with a parameterless constructor is required"); + foreach (INamedTypeSymbol type in constructions.factories.Where(static type => ( + !CanConstruct(type) + && GetBaseTypes(type).Any(static parent => ( + parent.OriginalDefinition.ToDisplayString() + == "Inno.Core.Serialization.Converters.SerializationConverter" + )) + )) + ) { + RuntimeRegistrationDiagnostics.ReportUnavailable( + output, + type, + "a nonabstract converter with a parameterless constructor is required" + ); + } foreach (INamedTypeSymbol type in constructions.factories.Where(CanConstruct)) { string name = GetTypeName(type); IMethodSymbol? constructor = type.InstanceConstructors.FirstOrDefault(static value => value.Parameters.Length == 0); string factory; if (constructor is not null && constructor.DeclaredAccessibility is not - (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal)) - { + (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal) + ) { factory = FormatConstructorCall(type, constructors.Count); constructors.Add(type); } @@ -99,29 +127,44 @@ Compilation compilation } foreach (var rejection in constructions.rejected) { - code.Append(" register.RejectGenericConstruction(typeof(").Append(GetTypeName(rejection.definition)) + code.Append(" register.RejectGenericConstruction(typeof(") + .Append(GetTypeName(rejection.definition)) .Append("), new global::System.Type[] { ") .Append(string.Join(", ", rejection.arguments.Select(argument => "typeof(" + FormatType(argument) + ")"))) .Append(" });\n"); } - if (types.Any(static type => type.GetAttributes().Any(static attribute => - attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.GenerateSerializationConverterAttribute"))) - { - code.Append(" global::").Append(compilation.AssemblyName) + if (types.Any(static type => type.GetAttributes().Any(static attribute => ( + attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.GenerateSerializationConverterAttribute" + ))) + ) { + code.Append(" global::") + .Append(compilation.AssemblyName) .Append(".Generated.RuntimeSerializationCatalog.Register(register);\n"); } code.Append(" }\n"); - code.Append("\n /// \n /// Resolves an explicitly registered declaration by its CLR metadata name.\n /// \n") + code + .Append( + "\n /// \n /// Resolves an explicitly registered declaration by its CLR metadata name.\n /// \n" + ) .Append(" /// \n /// The exact name emitted by the owning catalog.\n /// \n") - .Append(" /// \n /// The linked declaration; unknown names throw instead of probing assemblies.\n /// \n") - .Append(" /// \n /// The declaration is absent from this catalog.\n /// \n") + .Append( + " /// \n /// The linked declaration; unknown names throw instead of probing assemblies.\n /// \n" + ) + .Append( + " /// \n /// The declaration is absent from this catalog.\n /// \n" + ) .Append(" public static global::System.Type ResolveType(string metadataName) => metadataName switch\n {\n"); foreach (INamedTypeSymbol type in types) { - code.Append(" ").Append(Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true)) - .Append(" => typeof(").Append(GetTypeName(type)).Append("),\n"); + code.Append(" ") + .Append(Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true)) + .Append(" => typeof(") + .Append(GetTypeName(type)) + .Append("),\n"); } - code.Append(" _ => throw new global::System.ArgumentException(\"The declaration is not registered in this assembly.\", nameof(metadataName))\n };\n"); + code.Append( + " _ => throw new global::System.ArgumentException(\"The declaration is not registered in this assembly.\", nameof(metadataName))\n };\n" + ); for (int index = 0; index < constructors.Count; index++) { AppendConstructor(code, constructors[index], index); @@ -135,13 +178,17 @@ private static IEnumerable EnumerateTypes(INamespaceSymbol sou foreach (INamespaceSymbol child in source.GetNamespaceMembers()) { foreach (INamedTypeSymbol type in EnumerateTypes(child)) + { yield return type; + } } foreach (INamedTypeSymbol type in source.GetTypeMembers()) { yield return type; foreach (INamedTypeSymbol nested in EnumerateNestedTypes(type)) + { yield return nested; + } } } @@ -151,7 +198,9 @@ private static IEnumerable EnumerateNestedTypes(INamedTypeSymb { yield return type; foreach (INamedTypeSymbol nested in EnumerateNestedTypes(type)) + { yield return nested; + } } } @@ -160,10 +209,14 @@ private static bool IsAccessible(INamedTypeSymbol type) for (INamedTypeSymbol? current = type; current is not null; current = current.ContainingType) { if (current.IsExtension) + { return false; + } if (current.DeclaredAccessibility is not - (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal) || current.IsFileLocal) + (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal) || current.IsFileLocal + ) { return false; + } } return !type.IsImplicitlyDeclared && type.TypeKind != TypeKind.Error; } @@ -173,13 +226,17 @@ private static bool CanConstruct(INamedTypeSymbol type) for (INamedTypeSymbol? current = type; current is not null; current = current.ContainingType) { if (HasOpenArguments(current)) + { return false; + } } - return !type.IsAbstract && !type.IsStatic && type.TypeKind is TypeKind.Class or TypeKind.Struct && - !type.IsRefLikeType && !GetBaseTypes(type).Append(type).Any(static current => - current.GetMembers().Any(static member => member is IPropertySymbol { IsRequired: true } - or IFieldSymbol { IsRequired: true })) && - type.InstanceConstructors.Any(static constructor => constructor.Parameters.Length == 0); + return !type.IsAbstract && !type.IsStatic && type.TypeKind is TypeKind.Class or TypeKind.Struct + && !type.IsRefLikeType && !GetBaseTypes(type).Append(type).Any(static current => + current.GetMembers().Any(static member => ( + member is IPropertySymbol { IsRequired: true } + or IFieldSymbol { IsRequired: true } + ))) + && type.InstanceConstructors.Any(static constructor => constructor.Parameters.Length == 0); } private static string FormatConstructorCall( @@ -187,8 +244,9 @@ private static string FormatConstructorCall( int index ) { ITypeSymbol[] arguments = GetConstructionArguments(type).ToArray(); - return "static () => Constructor" + index + (arguments.Length == 0 ? string.Empty : - "<" + string.Join(", ", arguments.Select(FormatType)) + ">") + ".Create()"; + return "static () => Constructor" + index + (arguments.Length == 0 + ? string.Empty + : "<" + string.Join(", ", arguments.Select(FormatType)) + ">") + ".Create()"; } private static IEnumerable GetConstructionArguments(INamedTypeSymbol type) @@ -196,10 +254,14 @@ private static IEnumerable GetConstructionArguments(INamedTypeSymbo if (type.ContainingType is not null) { foreach (ITypeSymbol argument in GetConstructionArguments(type.ContainingType)) + { yield return argument; + } } foreach (ITypeSymbol argument in type.TypeArguments) + { yield return argument; + } } private static void AppendConstructor( @@ -211,66 +273,94 @@ int index ITypeParameterSymbol[] parameters = GetConstructionArguments(definition).Cast().ToArray(); var names = new Dictionary(SymbolEqualityComparer.Default); for (int parameterIndex = 0; parameterIndex < parameters.Length; parameterIndex++) + { names.Add(parameters[parameterIndex], "T" + parameterIndex); + } code.Append("\n private static class Constructor").Append(index); if (parameters.Length > 0) + { code.Append('<').Append(string.Join(", ", parameters.Select(parameter => names[parameter]))).Append('>'); + } foreach (ITypeParameterSymbol parameter in parameters) { var constraints = new List(); if (parameter.HasUnmanagedTypeConstraint) + { constraints.Add("unmanaged"); + } else if (parameter.HasValueTypeConstraint) + { constraints.Add("struct"); + } else if (parameter.HasReferenceTypeConstraint) + { constraints.Add(parameter.ReferenceTypeConstraintNullableAnnotation == NullableAnnotation.Annotated ? "class?" : "class"); + } else if (parameter.HasNotNullConstraint) + { constraints.Add("notnull"); + } constraints.AddRange(parameter.ConstraintTypes.Select(constraint => FormatConstructionType(constraint, names))); if (parameter.HasConstructorConstraint) + { constraints.Add("new()"); + } if (constraints.Count > 0) + { code.Append("\n where ").Append(names[parameter]).Append(" : ").Append(string.Join(", ", constraints)); + } } code.Append("\n {\n") - .Append(" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n") - .Append(" internal static extern ").Append(FormatConstructionType(definition, names)) + .Append( + " [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]\n" + ) + .Append(" internal static extern ") + .Append(FormatConstructionType(definition, names)) .Append(" Create();\n }\n"); } private static string FormatConstructionType( ITypeSymbol type, Dictionary names - ) => string.Concat(type.ToDisplayParts(SymbolDisplayFormat.FullyQualifiedFormat).Select(part => - part.Symbol is not null && names.TryGetValue(part.Symbol, out string? name) ? name : part.ToString())); + ) => string.Concat( + type.ToDisplayParts(SymbolDisplayFormat.FullyQualifiedFormat).Select(part => ( + part.Symbol is not null && names.TryGetValue(part.Symbol, out string? name) ? name : part.ToString() + )) + ); private static IEnumerable GetBaseTypes(INamedTypeSymbol type) { for (INamedTypeSymbol? current = type.BaseType; current is not null && current.SpecialType != SpecialType.System_Object; - current = current.BaseType) + current = current.BaseType + ) { yield return current; + } } private static string FormatTypes(IEnumerable types) - => "new global::System.Type[] { " + string.Join(", ", types.Where(IsAccessible) - .Select(FormatTypeReference)) + " }"; + => "new global::System.Type[] { " + string.Join( + ", ", + types.Where(IsAccessible) + .Select(FormatTypeReference) + ) + " }"; private static string FormatTypeReference(INamedTypeSymbol type) { bool isInternal = type.DeclaredAccessibility is Accessibility.Internal or Accessibility.ProtectedAndInternal; - if (isInternal && !type.Locations.Any(static location => location.IsInSource) && - type.ContainingAssembly.Name.StartsWith("Inno.", StringComparison.Ordinal)) - { - return "global::" + type.ContainingAssembly.Name + ".Generated.RuntimeModuleCatalog.ResolveType(" + - Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true) + ")"; + if (isInternal && !type.Locations.Any(static location => location.IsInSource) + && type.ContainingAssembly.Name.StartsWith("Inno.", StringComparison.Ordinal) + ) { + return "global::" + type.ContainingAssembly.Name + ".Generated.RuntimeModuleCatalog.ResolveType(" + + Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true) + ")"; } return "typeof(" + GetTypeName(type) + ")"; } private static string GetMetadataName(INamedTypeSymbol type) - => type.ContainingType is not null ? GetMetadataName(type.ContainingType) + "+" + type.MetadataName - : (type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString() + ".") + - type.MetadataName; + => type.ContainingType is not null + ? GetMetadataName(type.ContainingType) + "+" + type.MetadataName + : (type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString() + ".") + + type.MetadataName; private static string FormatOverrides(INamedTypeSymbol type) { @@ -278,17 +368,24 @@ private static string FormatOverrides(INamedTypeSymbol type) var declarations = new List(); foreach (INamedTypeSymbol owner in new[] { type }.Concat(GetBaseTypes(type))) { - foreach (IMethodSymbol method in owner.GetMembers().OfType().Where(static method => - !method.IsStatic && !method.IsGenericMethod && method.Parameters.Length == 0 && - method.MethodKind == MethodKind.Ordinary)) - { + foreach (IMethodSymbol method in owner.GetMembers().OfType().Where(static method => ( + !method.IsStatic && !method.IsGenericMethod && method.Parameters.Length == 0 + && method.MethodKind == MethodKind.Ordinary + )) + ) { if (!seen.Add(method.Name) || !method.IsOverride) + { continue; + } IMethodSymbol root = method; while (root.OverriddenMethod is not null) + { root = root.OverriddenMethod; - declarations.Add("(" + Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(method.Name, quote: true) + - ", typeof(" + GetTypeName(root.ContainingType) + "))"); + } + declarations.Add( + "(" + Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(method.Name, quote: true) + + ", typeof(" + GetTypeName(root.ContainingType) + "))" + ); } } return "new (string, global::System.Type)[] { " + string.Join(", ", declarations) + " }"; @@ -303,16 +400,24 @@ private static IEnumerable GetInheritedAttributes(INamedTypeSymbo foreach (AttributeData attribute in declaration.GetAttributes()) { if (attribute.AttributeClass is not INamedTypeSymbol attributeType) + { continue; + } AttributeData? usage = new[] { attributeType }.Concat(GetBaseTypes(attributeType)) .SelectMany(static source => source.GetAttributes()) .FirstOrDefault(static value => value.AttributeClass?.ToDisplayString() == "System.AttributeUsageAttribute"); - bool allowMultiple = usage?.NamedArguments.Any(static pair => pair.Key == "AllowMultiple" && - pair.Value.Value is true) ?? false; - bool canInherit = !(usage?.NamedArguments.Any(static pair => pair.Key == "Inherited" && - pair.Value.Value is false) ?? false); + bool allowMultiple = usage?.NamedArguments.Any(static pair => ( + pair.Key == "AllowMultiple" + && pair.Value.Value is true + )) ?? false; + bool canInherit = !(usage?.NamedArguments.Any(static pair => ( + pair.Key == "Inherited" + && pair.Value.Value is false + )) ?? false); if (inherited && (!canInherit || !allowMultiple && seen.Contains(attributeType))) + { continue; + } seen.Add(attributeType); yield return attribute; } @@ -321,52 +426,82 @@ private static IEnumerable GetInheritedAttributes(INamedTypeSymbo } private static string FormatAttributes(IEnumerable attributes) - => "new global::System.Attribute[] { " + string.Join(", ", attributes - .Where(static attribute => attribute.AttributeClass is not null && IsAccessible(attribute.AttributeClass) && - attribute.AttributeConstructor?.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal) - .Select(static attribute => "new " + GetTypeName(attribute.AttributeClass!) + "(" + - string.Join(", ", attribute.ConstructorArguments.Select(FormatConstant)) + ")" + - (attribute.NamedArguments.Length == 0 ? string.Empty : " { " + string.Join(", ", attribute.NamedArguments - .Select(static pair => pair.Key + " = " + FormatConstant(pair.Value))) + " }"))) + " }"; + => "new global::System.Attribute[] { " + string.Join( + ", ", + attributes + .Where(static attribute => ( + attribute.AttributeClass is not null && IsAccessible(attribute.AttributeClass) + && attribute.AttributeConstructor?.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal + )) + .Select(static attribute => ( + "new " + GetTypeName(attribute.AttributeClass!) + "(" + + string.Join(", ", attribute.ConstructorArguments.Select(FormatConstant)) + ")" + + (attribute.NamedArguments.Length == 0 ? string.Empty : " { " + string.Join( + ", ", + attribute.NamedArguments + .Select(static pair => pair.Key + " = " + FormatConstant(pair.Value)) + ) + " }") + )) + ) + " }"; private static string FormatConstant(TypedConstant constant) { if (constant.IsNull) + { return "null"; + } if (constant.Kind == TypedConstantKind.Type && constant.Value is ITypeSymbol type) + { return "typeof(" + FormatType(type) + ")"; + } if (constant.Kind == TypedConstantKind.Array && constant.Type is IArrayTypeSymbol array) - return "new " + array.ElementType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + "[] { " + - string.Join(", ", constant.Values.Select(FormatConstant)) + " }"; - string literal = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatPrimitive(constant.Value!, quoteStrings: true, - useHexadecimalNumbers: false) ?? throw new InvalidOperationException("The attribute constant cannot be represented as a C# literal."); - return constant.Kind == TypedConstantKind.Enum ? "(" + - constant.Type!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ")" + literal : literal; + { + return "new " + array.ElementType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + "[] { " + + string.Join(", ", constant.Values.Select(FormatConstant)) + " }"; + } + string literal = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatPrimitive( + constant.Value!, + quoteStrings: true, + useHexadecimalNumbers: false + ) ?? throw new InvalidOperationException("The attribute constant cannot be represented as a C# literal."); + return constant.Kind == TypedConstantKind.Enum + ? "(" + + constant.Type!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ")" + literal + : literal; } private static string GetTypeName(INamedTypeSymbol type) { if (!HasOpenArguments(type)) + { return type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + } string arguments = type.Arity == 0 ? string.Empty : "<" + new string(',', type.Arity - 1) + ">"; if (type.ContainingType is not null) + { return GetTypeName(type.ContainingType) + "." + type.Name + arguments; + } if (type.Arity > 0) - return "global::" + (type.ContainingNamespace.IsGlobalNamespace ? string.Empty : - type.ContainingNamespace.ToDisplayString() + ".") + type.Name + arguments; + { + return "global::" + (type.ContainingNamespace.IsGlobalNamespace + ? string.Empty + : type.ContainingNamespace.ToDisplayString() + ".") + type.Name + arguments; + } return type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); } private static bool HasOpenArguments(INamedTypeSymbol type) - => type.IsUnboundGenericType || type.TypeArguments.Any(static argument => argument is ITypeParameterSymbol || - argument is INamedTypeSymbol named && HasOpenArguments(named)) || - type.ContainingType is not null && HasOpenArguments(type.ContainingType); + => type.IsUnboundGenericType || type.TypeArguments.Any(static argument => ( + argument is ITypeParameterSymbol + || argument is INamedTypeSymbol named && HasOpenArguments(named) + )) + || type.ContainingType is not null && HasOpenArguments(type.ContainingType); private static string FormatType(ITypeSymbol type) => type switch - { - INamedTypeSymbol named => GetTypeName(named), - IArrayTypeSymbol array => FormatType(array.ElementType) + "[" + new string(',', array.Rank - 1) + "]", - _ => type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) - }; + { + INamedTypeSymbol named => GetTypeName(named), + IArrayTypeSymbol array => FormatType(array.ElementType) + "[" + new string(',', array.Rank - 1) + "]", + _ => type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + }; } diff --git a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeTypeCatalogGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeTypeCatalogGenerator.cs index 644edb5e1..f61b461e5 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeTypeCatalogGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeTypeCatalogGenerator.cs @@ -18,9 +18,10 @@ SourceProductionContext output var values = new HashSet(SymbolEqualityComparer.Default); foreach (INamedTypeSymbol owner in EnumerateTypes(compilation.Assembly.GlobalNamespace)) { - foreach (ISymbol member in owner.GetMembers().Where(static member => member.GetAttributes().Any(static attribute => - attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.SerializablePropertyAttribute"))) - { + foreach (ISymbol member in owner.GetMembers().Where(static member => member.GetAttributes().Any(static attribute => ( + attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.SerializablePropertyAttribute" + ))) + ) { ITypeSymbol? value = member switch { IPropertySymbol property => property.Type, @@ -28,7 +29,9 @@ SourceProductionContext output _ => null }; if (value is not null && !ContainsParameters(value)) + { AddValueClosure(value, values); + } } } foreach (SyntaxTree tree in compilation.SyntaxTrees) @@ -37,17 +40,24 @@ SourceProductionContext output foreach (GenericNameSyntax syntax in tree.GetRoot(output.CancellationToken).DescendantNodes().OfType()) { if (model.GetTypeInfo(syntax, output.CancellationToken).Type is INamedTypeSymbol type && !ContainsParameters(type)) + { AddValueClosure(type, values); + } if (model.GetSymbolInfo(syntax, output.CancellationToken).Symbol is IMethodSymbol method) { foreach (ITypeSymbol argument in method.TypeArguments.Where(static argument => !ContainsParameters(argument))) + { AddValueClosure(argument, values); + } } } } INamedTypeSymbol[] converters = new[] { compilation.Assembly } - .Concat(compilation.SourceModule.ReferencedAssemblySymbols.Where(static assembly => - assembly.GetTypeByMetadataName(assembly.Name + ".Generated.RuntimeModuleCatalog") is not null)) + .Concat( + compilation.SourceModule.ReferencedAssemblySymbols.Where(static assembly => ( + assembly.GetTypeByMetadataName(assembly.Name + ".Generated.RuntimeModuleCatalog") is not null + )) + ) .SelectMany(static assembly => EnumerateTypes(assembly.GlobalNamespace)) .Where(static type => type.IsGenericType && type.TypeParameters.Length != 0 && GetConverterPattern(type) is not null) .ToArray(); @@ -56,33 +66,47 @@ SourceProductionContext output foreach (ITypeSymbol value in values) { if (value is INamedTypeSymbol { IsGenericType: true } named && IsAvailable(named, compilation)) + { factories.Add(named); + } foreach (INamedTypeSymbol converter in converters) { var bindings = new Dictionary(SymbolEqualityComparer.Default); - if (!Unify(GetConverterPattern(converter)!, value, bindings) || - converter.TypeParameters.Any(parameter => !bindings.ContainsKey(parameter))) + if (!Unify(GetConverterPattern(converter)!, value, bindings) + || converter.TypeParameters.Any(parameter => !bindings.ContainsKey(parameter)) + ) { continue; + } ITypeSymbol[] arguments = converter.TypeParameters.Select(parameter => bindings[parameter]).ToArray(); if (SatisfiesConstraints(converter, bindings, compilation)) { INamedTypeSymbol construction = converter.Construct(arguments); if (IsAvailable(construction, compilation)) + { factories.Add(construction); + } else - RuntimeRegistrationDiagnostics.ReportUnavailable(output, construction, - "the converter or an argument is inaccessible from the generated assembly catalog"); + { + RuntimeRegistrationDiagnostics.ReportUnavailable( + output, + construction, + "the converter or an argument is inaccessible from the generated assembly catalog" + ); + } } - else if (IsAvailable(converter, compilation) && - arguments.All(argument => argument is not INamedTypeSymbol named || IsArgumentAccessible(named, compilation))) - { + else if (IsAvailable(converter, compilation) + && arguments.All(argument => argument is not INamedTypeSymbol named || IsArgumentAccessible(named, compilation)) + ) { rejected.Add((converter, arguments)); } } } return (factories.OrderBy(static type => type.ToDisplayString(), StringComparer.Ordinal).ToArray(), rejected.OrderBy(static value => value.definition.ToDisplayString(), StringComparer.Ordinal) - .ThenBy(static value => string.Join(",", value.arguments.Select(static argument => argument.ToDisplayString())), StringComparer.Ordinal) + .ThenBy( + static value => string.Join(",", value.arguments.Select(static argument => argument.ToDisplayString())), + StringComparer.Ordinal + ) .ToArray()); } @@ -91,16 +115,23 @@ private static void AddValueClosure( HashSet values ) { if (!values.Add(type)) + { return; + } if (type is IArrayTypeSymbol array) + { AddValueClosure(array.ElementType, values); + } if (type is INamedTypeSymbol named) { foreach (ITypeSymbol argument in named.TypeArguments) - AddValueClosure(argument, values); - foreach (ISymbol member in named.GetMembers().Where(static member => member.GetAttributes().Any(static attribute => - attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.SerializablePropertyAttribute"))) { + AddValueClosure(argument, values); + } + foreach (ISymbol member in named.GetMembers().Where(static member => member.GetAttributes().Any(static attribute => ( + attribute.AttributeClass?.ToDisplayString() == "Inno.Core.Serialization.SerializablePropertyAttribute" + ))) + ) { ITypeSymbol? value = member switch { IPropertySymbol property => property.Type, @@ -108,7 +139,9 @@ HashSet values _ => null }; if (value is not null && !ContainsParameters(value)) + { AddValueClosure(value, values); + } } } } @@ -117,17 +150,23 @@ private static bool IsAvailable( INamedTypeSymbol type, Compilation compilation ) { - if (!SymbolEqualityComparer.Default.Equals(type.ContainingAssembly, compilation.Assembly) && - type.ContainingAssembly.GetTypeByMetadataName(type.ContainingAssembly.Name + ".Generated.RuntimeModuleCatalog") is null) + if (!SymbolEqualityComparer.Default.Equals(type.ContainingAssembly, compilation.Assembly) + && type.ContainingAssembly.GetTypeByMetadataName(type.ContainingAssembly.Name + ".Generated.RuntimeModuleCatalog") is null + ) { return false; + } for (INamedTypeSymbol? owner = type; owner is not null; owner = owner.ContainingType) { if (owner.IsFileLocal || owner.DeclaredAccessibility is not - (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal)) + (Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal) + ) { return false; - if (owner.DeclaredAccessibility != Accessibility.Public && - !SymbolEqualityComparer.Default.Equals(owner.ContainingAssembly, compilation.Assembly)) + } + if (owner.DeclaredAccessibility != Accessibility.Public + && !SymbolEqualityComparer.Default.Equals(owner.ContainingAssembly, compilation.Assembly) + ) { return false; + } } return type.TypeArguments.All(argument => argument is not INamedTypeSymbol named || IsArgumentAccessible(named, compilation)); } @@ -138,10 +177,12 @@ Compilation compilation ) { for (INamedTypeSymbol? owner = type; owner is not null; owner = owner.ContainingType) { - if (owner.IsFileLocal || owner.DeclaredAccessibility != Accessibility.Public && - (!SymbolEqualityComparer.Default.Equals(owner.ContainingAssembly, compilation.Assembly) || - owner.DeclaredAccessibility is not (Accessibility.Internal or Accessibility.ProtectedOrInternal))) + if (owner.IsFileLocal || owner.DeclaredAccessibility != Accessibility.Public + && (!SymbolEqualityComparer.Default.Equals(owner.ContainingAssembly, compilation.Assembly) + || owner.DeclaredAccessibility is not (Accessibility.Internal or Accessibility.ProtectedOrInternal)) + ) { return false; + } } return type.TypeArguments.All(argument => argument is not INamedTypeSymbol named || IsArgumentAccessible(named, compilation)); } @@ -151,7 +192,9 @@ owner.DeclaredAccessibility is not (Accessibility.Internal or Accessibility.Prot for (INamedTypeSymbol? current = type.BaseType; current is not null; current = current.BaseType) { if (current.OriginalDefinition.ToDisplayString() == "Inno.Core.Serialization.Converters.SerializationConverter") + { return current.TypeArguments[0]; + } } return null; } @@ -164,22 +207,28 @@ Dictionary bindings if (pattern is ITypeParameterSymbol parameter) { if (bindings.TryGetValue(parameter, out ITypeSymbol? existing)) + { return SymbolEqualityComparer.Default.Equals(existing, value); + } bindings.Add(parameter, value); return true; } if (pattern is IArrayTypeSymbol array) - return value is IArrayTypeSymbol other && array.Rank == other.Rank && Unify(array.ElementType, other.ElementType, bindings); - if (pattern is INamedTypeSymbol named && value is INamedTypeSymbol concrete && - SymbolEqualityComparer.Default.Equals(named.OriginalDefinition, concrete.OriginalDefinition)) { + return value is IArrayTypeSymbol other && array.Rank == other.Rank && Unify(array.ElementType, other.ElementType, bindings); + } + if (pattern is INamedTypeSymbol named && value is INamedTypeSymbol concrete + && SymbolEqualityComparer.Default.Equals(named.OriginalDefinition, concrete.OriginalDefinition) + ) { for (int index = 0; index < named.TypeArguments.Length; index++) { if (!Unify(named.TypeArguments[index], concrete.TypeArguments[index], bindings)) + { return false; + } } - return named.ContainingType is null || concrete.ContainingType is not null && - Unify(named.ContainingType, concrete.ContainingType, bindings); + return named.ContainingType is null || concrete.ContainingType is not null + && Unify(named.ContainingType, concrete.ContainingType, bindings); } return SymbolEqualityComparer.Default.Equals(pattern, value); } @@ -192,18 +241,25 @@ Compilation compilation foreach (ITypeParameterSymbol parameter in definition.TypeParameters) { ITypeSymbol argument = bindings[parameter]; - if (parameter.HasReferenceTypeConstraint && !argument.IsReferenceType || - parameter.HasValueTypeConstraint && (!argument.IsValueType || argument.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) || - parameter.HasUnmanagedTypeConstraint && !argument.IsUnmanagedType || - parameter.HasConstructorConstraint && !argument.IsValueType && - (argument is not INamedTypeSymbol named || named.IsAbstract || !named.InstanceConstructors.Any(static constructor => - constructor.Parameters.Length == 0 && constructor.DeclaredAccessibility == Accessibility.Public))) + if (parameter.HasReferenceTypeConstraint && !argument.IsReferenceType + || parameter.HasValueTypeConstraint + && (!argument.IsValueType || argument.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) + || + parameter.HasUnmanagedTypeConstraint && !argument.IsUnmanagedType + || parameter.HasConstructorConstraint && !argument.IsValueType + && (argument is not INamedTypeSymbol named || named.IsAbstract || !named.InstanceConstructors.Any(static constructor => ( + constructor.Parameters.Length == 0 && constructor.DeclaredAccessibility == Accessibility.Public + ))) + ) { return false; + } foreach (ITypeSymbol constraint in parameter.ConstraintTypes) { ITypeSymbol substituted = Substitute(constraint, bindings, compilation); if (!compilation.ClassifyCommonConversion(argument, substituted).IsImplicit) + { return false; + } } } return true; @@ -217,16 +273,19 @@ Compilation compilation { ITypeParameterSymbol parameter => bindings[parameter], IArrayTypeSymbol array => compilation.CreateArrayTypeSymbol(Substitute(array.ElementType, bindings, compilation), array.Rank), - INamedTypeSymbol { IsGenericType: true } named => named.OriginalDefinition.Construct(named.TypeArguments - .Select(argument => Substitute(argument, bindings, compilation)).ToArray()), + INamedTypeSymbol { IsGenericType: true } named => named.OriginalDefinition.Construct( + named.TypeArguments + .Select(argument => Substitute(argument, bindings, compilation)) + .ToArray() + ), _ => type }; private static bool ContainsParameters(ITypeSymbol type) - => type is ITypeParameterSymbol || type is INamedTypeSymbol named && - (named.IsUnboundGenericType || named.TypeArguments.Any(ContainsParameters) || - named.ContainingType is not null && ContainsParameters(named.ContainingType)) || - type is IArrayTypeSymbol array && ContainsParameters(array.ElementType); + => type is ITypeParameterSymbol || type is INamedTypeSymbol named + && (named.IsUnboundGenericType || named.TypeArguments.Any(ContainsParameters) + || named.ContainingType is not null && ContainsParameters(named.ContainingType)) + || type is IArrayTypeSymbol array && ContainsParameters(array.ElementType); private static IEnumerable EnumerateTypes(INamespaceOrTypeSymbol scope) { @@ -234,13 +293,19 @@ private static IEnumerable EnumerateTypes(INamespaceOrTypeSymb { // Extension declarations group members but cannot be named as runtime types. if (member is INamedTypeSymbol { IsExtension: true }) + { continue; + } if (member is INamedTypeSymbol type) + { yield return type; + } if (member is INamespaceOrTypeSymbol child) { foreach (INamedTypeSymbol nested in EnumerateTypes(child)) + { yield return nested; + } } } } diff --git a/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs index a773be6d4..a701e57d6 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs @@ -14,8 +14,14 @@ namespace Inno.Runtime.Generators; [Generator] public sealed class RuntimeSubsystemGenerator : IIncrementalGenerator { - private static readonly DiagnosticDescriptor S_INVALID = new("INNORUN001", "Invalid subsystem composition", - "{0}", "Architecture", DiagnosticSeverity.Error, true); + private static readonly DiagnosticDescriptor S_INVALID = new( + "INNORUN001", + "Invalid subsystem composition", + "{0}", + "Architecture", + DiagnosticSeverity.Error, + true + ); /// /// Registers incremental discovery of composition methods and catalog declarations. @@ -34,8 +40,11 @@ public void Initialize(IncrementalGeneratorInitializationContext context) static ( entry, _ - ) => new Registration((IMethodSymbol)entry.TargetSymbol, - entry.Attributes[0].ConstructorArguments[0].Value as string ?? string.Empty)).Collect(); + ) => new Registration( + (IMethodSymbol)entry.TargetSymbol, + entry.Attributes[0].ConstructorArguments[0].Value as string ?? string.Empty + ) + ).Collect(); var catalogs = context.SyntaxProvider.ForAttributeWithMetadataName( "Inno.Runtime.Contracts.RuntimeSubsystemCatalogAttribute", static ( @@ -45,12 +54,15 @@ public void Initialize(IncrementalGeneratorInitializationContext context) static ( entry, _ - ) => (IMethodSymbol)entry.TargetSymbol).Collect(); - context.RegisterSourceOutput(catalogs.Combine(registrations), + ) => (IMethodSymbol)entry.TargetSymbol + ).Collect(); + context.RegisterSourceOutput( + catalogs.Combine(registrations), static ( output, data - ) => Generate(output, data.Left, data.Right)); + ) => Generate(output, data.Left, data.Right) + ); } private static void Generate( @@ -61,30 +73,50 @@ ImmutableArray registrations foreach (Registration registration in registrations) { if (!IsFactory(registration.method) || string.IsNullOrWhiteSpace(registration.id)) - Report(output, registration.method, "A subsystem declaration must be an accessible static method taking one composition parameter and returning IRuntimeSubsystemFactory with a non-empty ID."); + { + Report( + output, + registration.method, + "A subsystem declaration must be an accessible static method taking one composition parameter and returning IRuntimeSubsystemFactory with a non-empty ID." + ); + } } foreach (IMethodSymbol catalog in catalogs) { - if (!catalog.IsStatic || catalog.IsGenericMethod || catalog.Parameters.Length != 1 || - catalog.Parameters[0].RefKind != RefKind.None || catalog.Parameters[0].IsParams || - catalog.ContainingType.ContainingType is not null || catalog.ContainingType.Arity != 0 || - !catalog.ContainingType.IsStatic || catalog.ContainingNamespace.IsGlobalNamespace || - catalog.DeclaredAccessibility is not (Accessibility.Public or Accessibility.Internal) || - !catalog.IsPartialDefinition || catalog.ReturnType.ToDisplayString() != - "System.Collections.Generic.IReadOnlyList") - { - Report(output, catalog, "A catalog must be a static partial method on a non-nested partial class, take one composition parameter and return IReadOnlyList."); + if (!catalog.IsStatic || catalog.IsGenericMethod || catalog.Parameters.Length != 1 + || catalog.Parameters[0].RefKind != RefKind.None || catalog.Parameters[0].IsParams + || catalog.ContainingType.ContainingType is not null || catalog.ContainingType.Arity != 0 + || !catalog.ContainingType.IsStatic || catalog.ContainingNamespace.IsGlobalNamespace + || catalog.DeclaredAccessibility is not (Accessibility.Public or Accessibility.Internal) + || !catalog.IsPartialDefinition + || catalog.ReturnType.ToDisplayString() + != "System.Collections.Generic.IReadOnlyList" + ) { + Report( + output, + catalog, + "A catalog must be a static partial method on a non-nested partial class, take one composition parameter and return IReadOnlyList." + ); continue; } - Registration[] matches = registrations.Where(registration => IsFactory(registration.method) && - SymbolEqualityComparer.Default.Equals(registration.method.Parameters[0].Type, catalog.Parameters[0].Type)) - .OrderBy(static registration => registration.id, StringComparer.Ordinal).ToArray(); + Registration[] matches = registrations + .Where(registration => ( + IsFactory(registration.method) + && SymbolEqualityComparer.Default.Equals(registration.method.Parameters[0].Type, catalog.Parameters[0].Type) + )) + .OrderBy(static registration => registration.id, StringComparer.Ordinal) + .ToArray(); var duplicate = matches.GroupBy(static registration => registration.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1); if (matches.Length == 0 || duplicate is not null) { - Report(output, catalog, duplicate is null ? "A subsystem catalog has no declarations." : - $"Subsystem ID '{duplicate.Key}' is duplicated in this composition."); + Report( + output, + catalog, + duplicate is null + ? "A subsystem catalog has no declarations." + : $"Subsystem ID '{duplicate.Key}' is duplicated in this composition." + ); continue; } string typeName = Escape(catalog.ContainingType.Name); @@ -94,34 +126,65 @@ catalog.DeclaredAccessibility is not (Accessibility.Public or Accessibility.Inte string parameterType = catalog.Parameters[0].Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); string parameterName = Escape(catalog.Parameters[0].Name); var code = new StringBuilder("// \n#nullable enable\n"); - code.Append("namespace ").Append(ns).Append(";\n").Append(typeAccess).Append(" static partial class ") - .Append(typeName).Append("\n{\n ").Append(access) - .Append(" static partial global::System.Collections.Generic.IReadOnlyList ") - .Append(Escape(catalog.Name)).Append('(').Append(parameterType).Append(' ').Append(parameterName).Append(")\n {\n") - .Append(" global::System.ArgumentNullException.ThrowIfNull(").Append(parameterName).Append(");\n") + code.Append("namespace ") + .Append(ns) + .Append(";\n") + .Append(typeAccess) + .Append(" static partial class ") + .Append(typeName) + .Append("\n{\n ") + .Append(access) + .Append( + " static partial global::System.Collections.Generic.IReadOnlyList " + ) + .Append(Escape(catalog.Name)) + .Append('(') + .Append(parameterType) + .Append(' ') + .Append(parameterName) + .Append(")\n {\n") + .Append(" global::System.ArgumentNullException.ThrowIfNull(") + .Append(parameterName) + .Append(");\n") .Append(" var factories = new global::Inno.Runtime.Contracts.IRuntimeSubsystemFactory[]\n {\n"); foreach (Registration match in matches) - code.Append(" ").Append(match.method.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)) - .Append('.').Append(Escape(match.method.Name)).Append('(').Append(parameterName).Append("),\n"); + { + code.Append(" ") + .Append(match.method.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)) + .Append('.') + .Append(Escape(match.method.Name)) + .Append('(') + .Append(parameterName) + .Append("),\n"); + } code.Append(" };\n"); for (int index = 0; index < matches.Length; index++) { string id = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(matches[index].id, true); - code.Append(" if (factories[").Append(index).Append("].descriptor.id.value != ").Append(id) - .Append(")\n throw new global::System.InvalidOperationException(\"A subsystem declaration disagrees with its factory descriptor.\");\n"); + code.Append(" if (factories[") + .Append(index) + .Append("].descriptor.id.value != ") + .Append(id) + .Append( + ")\n throw new global::System.InvalidOperationException(\"A subsystem declaration disagrees with its factory descriptor.\");\n" + ); } code.Append(" return global::System.Array.AsReadOnly(factories);\n }\n}\n"); - output.AddSource(ns + "." + catalog.ContainingType.Name + "." + catalog.Name + "." + - catalogs.IndexOf(catalog) + ".g.cs", code.ToString()); + output.AddSource( + ns + "." + catalog.ContainingType.Name + "." + catalog.Name + "." + + catalogs.IndexOf(catalog) + ".g.cs", + code.ToString() + ); } } - private static bool IsFactory(IMethodSymbol method) => method.IsStatic && !method.IsGenericMethod && - method.ContainingType.Arity == 0 && method.ContainingType.ContainingType is null && - method.ContainingType.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal && - method.Parameters.Length == 1 && method.Parameters[0].RefKind == RefKind.None && !method.Parameters[0].IsParams && - method.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal && - method.ReturnType.ToDisplayString() == "Inno.Runtime.Contracts.IRuntimeSubsystemFactory"; + private static bool IsFactory(IMethodSymbol method) + => method.IsStatic && !method.IsGenericMethod + && method.ContainingType.Arity == 0 && method.ContainingType.ContainingType is null + && method.ContainingType.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal + && method.Parameters.Length == 1 && method.Parameters[0].RefKind == RefKind.None && !method.Parameters[0].IsParams + && method.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal + && method.ReturnType.ToDisplayString() == "Inno.Runtime.Contracts.IRuntimeSubsystemFactory"; private static string Escape(string name) => SyntaxFacts.GetKeywordKind(name) == SyntaxKind.None ? name : "@" + name; @@ -129,8 +192,7 @@ private static void Report( SourceProductionContext context, IMethodSymbol method, string message - ) - => context.ReportDiagnostic(Diagnostic.Create(S_INVALID, method.Locations.FirstOrDefault(), message)); + ) => context.ReportDiagnostic(Diagnostic.Create(S_INVALID, method.Locations.FirstOrDefault(), message)); private sealed class Registration( IMethodSymbol method, diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs index 0cb51c042..4d638e93d 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Collections.Frozen; +using System.Collections.Generic; using System.Linq; using Inno.Assets; using Inno.Core.Execution; @@ -30,7 +30,9 @@ public IReadOnlyList activePlugins get { lock (m_sync) + { return s_current.ordered; + } } } @@ -42,7 +44,9 @@ public long revision get { lock (m_sync) + { return s_revision; + } } } @@ -54,7 +58,9 @@ public PluginScanResult discovery get { lock (m_sync) + { return s_discovery; + } } } @@ -75,7 +81,9 @@ public bool TryGet( out PluginCandidate? plugin ) { lock (m_sync) + { return s_current.bySource.TryGetValue(source, out plugin); + } } /// @@ -90,7 +98,8 @@ public void Activate(PluginScanResult result) PluginCandidate[] ordered = PluginSourceService.GetActivatableCandidates(result).ToArray(); var bySource = ordered.ToFrozenDictionary( static candidate => candidate.sourceMount.id, - static candidate => candidate); + static candidate => candidate + ); Action? changed; lock (m_sync) { @@ -137,7 +146,9 @@ public void Shutdown() private static void InvokeObservers(Action? handlers) { if (handlers is null) + { return; + } List? failures = null; foreach (Delegate handler in handlers.GetInvocationList()) { @@ -148,7 +159,12 @@ private static void InvokeObservers(Action? handlers) catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { if (failures is not null) - throw new AggregateException("Plugin catalog observers reported unfinished retirement.", [.. failures, pendingRetirement]); + { + throw new AggregateException( + "Plugin catalog observers reported unfinished retirement.", + [.. failures, pendingRetirement] + ); + } throw; } catch (Exception exception) @@ -159,9 +175,7 @@ private static void InvokeObservers(Action? handlers) } if (failures is not null) { - throw new AggregateException( - "One or more Plugin catalog observers failed after publication.", - failures); + throw new AggregateException("One or more Plugin catalog observers failed after publication.", failures); } } @@ -171,6 +185,7 @@ FrozenDictionary bySource ) { internal static Snapshot empty { get; } = new( [], - new Dictionary().ToFrozenDictionary()); + new Dictionary().ToFrozenDictionary() + ); } } diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs index 54f8909a0..9c63b6911 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs @@ -8,11 +8,11 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Execution; -using Inno.Scripting.Api; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Reload; using Inno.References; +using Inno.Scripting.Api; namespace Inno.Plugins.Authoring; @@ -59,7 +59,9 @@ public bool isInitialized get { lock (m_sync) + { return m_sources is not null; + } } } @@ -128,7 +130,9 @@ GenerationCoordinator generations ArgumentException.ThrowIfNullOrWhiteSpace(libraryRoot); ArgumentNullException.ThrowIfNull(initialScan); if (!assets.isInitialized) + { throw new InvalidOperationException("PluginEnvironment requires AssetPipeline to be initialized first."); + } m_assets = assets; m_generations = generations ?? throw new ArgumentNullException(nameof(generations)); m_settings = settings; @@ -160,13 +164,17 @@ public void Update() lock (m_sync) { if (m_sources is null) + { return; + } long now = Environment.TickCount64; StartReconciliationLocked(now); refresh = m_refreshRequested - && now - m_lastChangeTimestamp >= C_CHANGE_DEBOUNCE_MILLISECONDS; + && now - m_lastChangeTimestamp >= C_CHANGE_DEBOUNCE_MILLISECONDS; if (!refresh) + { return; + } m_refreshRequested = false; } _ = Refresh(); @@ -185,26 +193,30 @@ public bool Refresh() ObjectDisposedException.ThrowIf(m_stopping, this); PluginSourceService sources; lock (m_sync) + { sources = m_sources ?? throw new InvalidOperationException("PluginEnvironment is not initialized."); + } PluginScanResult scan = sources.Scan(); m_catalog.PublishDiscovery(scan); string activeFingerprint = ComputeActiveFingerprint(scan); lock (m_sync) { if (m_pending is not null) + { return false; + } if (string.Equals(activeFingerprint, m_activeFingerprint, StringComparison.Ordinal)) + { return false; + } } PluginScanResult previous = CreateActiveScanSnapshot(); - AssetSourceMount project = m_assets.sourceMounts.Single( - static mount => mount.id == AssetSourceId.project); + AssetSourceMount project = m_assets.sourceMounts.Single(static mount => mount.id == AssetSourceId.project); AssetSourceMountTransaction assets; try { - assets = m_assets.PrepareSourceMounts( - [project, .. PluginSourceService.GetActivatableMounts(scan)]); + assets = m_assets.PrepareSourceMounts([project, .. PluginSourceService.GetActivatableMounts(scan)]); } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -218,17 +230,23 @@ public bool Refresh() .. scan.diagnostics, new PluginDiagnostic( m_pluginRoot, - $"Plugin Asset candidate validation failed; the installed Plugin generation is unavailable: " + - exception.Message) - ]); + $"Plugin Asset candidate validation failed; the installed Plugin generation is unavailable: " + + exception.Message + ) + ] + ); m_catalog.PublishDiscovery(scan); activeFingerprint = ComputeActiveFingerprint(scan); lock (m_sync) { if (m_pending is not null) + { return false; + } if (string.Equals(activeFingerprint, m_activeFingerprint, StringComparison.Ordinal)) + { return false; + } } assets = m_assets.PrepareSourceMounts([project]); } @@ -239,13 +257,10 @@ public bool Refresh() lock (m_sync) { if (m_pending is not null) + { throw new InvalidOperationException("Another Plugin activation candidate is already pending."); - m_pending = new PendingActivation( - previous, - scan, - assets, - m_activeFingerprint, - activeFingerprint); + } + m_pending = new PendingActivation(previous, scan, assets, m_activeFingerprint, activeFingerprint); pendingAssigned = true; } if (!requiresCodeReload) @@ -265,7 +280,9 @@ public bool Refresh() catch (Exception candidateFailure) { if (m_generations.state == GenerationState.Faulted) + { throw; + } try { if (pendingAssigned) @@ -273,7 +290,9 @@ public bool Refresh() RollbackPending(); } else + { assets.Rollback(); + } } catch (Exception rollbackFailure) { @@ -291,8 +310,11 @@ public bool Refresh() /// [ScriptingApiIgnore] public IGenerationChange CreateReloadChange() - => new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], - [new PluginRecoveryParticipant(this, m_assets, m_settings)]); + => new ReferenceRecoveryTransaction( + ReferenceCatalog.empty, + [], + [new PluginRecoveryParticipant(this, m_assets, m_settings)] + ); /// /// Commits a non-code availability change using the same generation gate and recovery phases as script reload. @@ -312,7 +334,9 @@ public bool hasPendingActivation get { lock (m_sync) + { return m_pending is not null; + } } } @@ -325,7 +349,9 @@ public AssetSourceMountTransaction? compilationAssets get { lock (m_sync) + { return m_pending?.assets; + } } } @@ -340,8 +366,8 @@ public IReadOnlyList compilationPlugins lock (m_sync) { return m_pending is null - ? m_catalog.activePlugins - : PluginSourceService.GetActivatableCandidates(m_pending.candidateScan).ToArray(); + ? m_catalog.activePlugins + : PluginSourceService.GetActivatableCandidates(m_pending.candidateScan).ToArray(); } } } @@ -392,9 +418,13 @@ public void ActivatePending() { PendingActivation? pending; lock (m_sync) + { pending = m_pending; + } if (pending is null || pending.isActivated) + { return; + } // The shared generation coordinator restores publication before participant state. // Retain the candidate on failure; local compensation here would violate that ordering. pending.assets.Activate(); @@ -414,15 +444,21 @@ public void CommitPending() { pending = m_pending; if (pending is null) + { return; + } if (!pending.isActivated) + { throw new InvalidOperationException("A Plugin candidate must be activated before commit."); + } } pending.assets.Complete(); lock (m_sync) { if (!ReferenceEquals(m_pending, pending)) + { throw new InvalidOperationException("The pending Plugin candidate changed during commit."); + } m_activeFingerprint = pending.candidateFingerprint; m_pending = null; } @@ -436,9 +472,13 @@ public void RollbackPending() { PendingActivation? pending; lock (m_sync) + { pending = m_pending; + } if (pending is null) + { return; + } pending.assets.Rollback(); if (pending.isActivated) { @@ -449,7 +489,9 @@ public void RollbackPending() lock (m_sync) { if (!ReferenceEquals(m_pending, pending)) + { throw new InvalidOperationException("The pending Plugin candidate changed during rollback."); + } m_activeFingerprint = pending.previousFingerprint; m_pending = null; } @@ -503,7 +545,9 @@ public void Dispose() m_catalog.Shutdown(); GC.SuppressFinalize(this); if (failures.Count > 0) + { throw new AggregateException("Plugin environment shutdown failed after its work retired.", failures); + } } private FileSystemWatcher CreateWatcher(string pluginRoot) @@ -512,9 +556,9 @@ private FileSystemWatcher CreateWatcher(string pluginRoot) { IncludeSubdirectories = false, NotifyFilter = NotifyFilters.FileName - | NotifyFilters.DirectoryName - | NotifyFilters.LastWrite - | NotifyFilters.Size, + | NotifyFilters.DirectoryName + | NotifyFilters.LastWrite + | NotifyFilters.Size, Filter = "*" }; watcher.Changed += OnPluginSourceChanged; @@ -535,7 +579,9 @@ FileSystemEventArgs arguments lock (m_sync) { if (m_sources is null || m_stopping) + { return; + } m_refreshRequested = true; m_lastChangeTimestamp = Environment.TickCount64; } @@ -550,7 +596,9 @@ ErrorEventArgs arguments lock (m_sync) { if (m_sources is null || m_stopping) + { return; + } m_refreshRequested = true; m_lastChangeTimestamp = Environment.TickCount64 - C_CHANGE_DEBOUNCE_MILLISECONDS; m_lastReconciliationTimestamp = 0; @@ -560,8 +608,8 @@ ErrorEventArgs arguments private void StartReconciliationLocked(long now) { if (m_reconciliation is not null - || now - m_lastReconciliationTimestamp < C_RECONCILIATION_INTERVAL_MILLISECONDS) - { + || now - m_lastReconciliationTimestamp < C_RECONCILIATION_INTERVAL_MILLISECONDS + ) { return; } string pluginRoot = m_pluginRoot; @@ -587,7 +635,9 @@ private void CompleteReconciliation() { reconciliation = m_reconciliation; if (reconciliation is null || !reconciliation.IsCompleted) + { return; + } m_reconciliation = null; } @@ -597,7 +647,9 @@ private void CompleteReconciliation() lock (m_sync) { if (m_sources is null) + { return; + } m_refreshRequested = true; m_lastChangeTimestamp = Environment.TickCount64 - C_CHANGE_DEBOUNCE_MILLISECONDS; } @@ -607,8 +659,8 @@ private void CompleteReconciliation() lock (m_sync) { if (m_sources is null - || string.Equals(fingerprint, m_reconciledFingerprint, StringComparison.Ordinal)) - { + || string.Equals(fingerprint, m_reconciledFingerprint, StringComparison.Ordinal) + ) { return; } m_reconciledFingerprint = fingerprint; @@ -624,14 +676,18 @@ private void PublishContributors(PluginScanResult scan) candidate.manifest.pluginId, candidate.manifest.dependencies, candidate.manifest.overrides, - candidate.manifest.settingContributions)) - .ToArray()); + candidate.manifest.settingContributions + )) + .ToArray() + ); private void InvokeCandidateObservers() { Action? handlers = ActivationCandidateChanged; if (handlers is null) + { return; + } List? failures = null; foreach (Delegate handler in handlers.GetInvocationList()) { @@ -642,7 +698,12 @@ private void InvokeCandidateObservers() catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { if (failures is not null) - throw new AggregateException("Plugin candidate observers reported unfinished retirement.", [.. failures, pendingRetirement]); + { + throw new AggregateException( + "Plugin candidate observers reported unfinished retirement.", + [.. failures, pendingRetirement] + ); + } throw; } catch (Exception exception) @@ -655,18 +716,17 @@ private void InvokeCandidateObservers() { throw new AggregateException( "One or more Plugin candidate observers rejected the staged generation.", - failures); + failures + ); } } private PluginScanResult ActivateInitialCandidate(PluginScanResult initialScan) { - AssetSourceMount project = m_assets.sourceMounts.Single( - static mount => mount.id == AssetSourceId.project); + AssetSourceMount project = m_assets.sourceMounts.Single(static mount => mount.id == AssetSourceId.project); try { - m_assets.ReplaceSourceMounts( - [project, .. PluginSourceService.GetActivatableMounts(initialScan)]); + m_assets.ReplaceSourceMounts([project, .. PluginSourceService.GetActivatableMounts(initialScan)]); m_catalog.Activate(initialScan); PublishContributors(initialScan); m_settings.RebuildCurrent(allowUnresolvedContributions: true); @@ -679,15 +739,9 @@ private PluginScanResult ActivateInitialCandidate(PluginScanResult initialScan) catch (Exception candidateFailure) { var rollbackFailures = new List { candidateFailure }; - TryInitialRollback( - () => m_assets.ReplaceSourceMounts([project]), - "asset mount rollback", - rollbackFailures); + TryInitialRollback(() => m_assets.ReplaceSourceMounts([project]), "asset mount rollback", rollbackFailures); var empty = new PluginScanResult([], []); - TryInitialRollback( - () => m_catalog.Activate(empty), - "Plugin catalog rollback", - rollbackFailures); + TryInitialRollback(() => m_catalog.Activate(empty), "Plugin catalog rollback", rollbackFailures); TryInitialRollback( () => { @@ -695,12 +749,14 @@ private PluginScanResult ActivateInitialCandidate(PluginScanResult initialScan) m_settings.RebuildCurrent(allowUnresolvedContributions: true); }, "project settings rollback", - rollbackFailures); + rollbackFailures + ); if (rollbackFailures.Count > 1) { throw new AggregateException( "Initial Plugin activation failed and the host-only generation could not be restored.", - rollbackFailures); + rollbackFailures + ); } var discovery = new PluginScanResult( @@ -709,8 +765,10 @@ private PluginScanResult ActivateInitialCandidate(PluginScanResult initialScan) .. initialScan.diagnostics, new PluginDiagnostic( m_pluginRoot, - $"Initial Plugin candidate activation failed and was isolated: {candidateFailure.Message}") - ]); + $"Initial Plugin candidate activation failed and was isolated: {candidateFailure.Message}" + ) + ] + ); m_catalog.PublishDiscovery(discovery); return empty; } @@ -748,8 +806,10 @@ PluginScanResult candidate .Where(static plugin => plugin.containsCode) .ToDictionary(static plugin => plugin.manifest.pluginId, static plugin => plugin.contentHash, StringComparer.Ordinal); return oldCode.Count != newCode.Count - || oldCode.Any(pair => !newCode.TryGetValue(pair.Key, out string? hash) - || !string.Equals(pair.Value, hash, StringComparison.Ordinal)); + || oldCode.Any(pair => ( + !newCode.TryGetValue(pair.Key, out string? hash) + || !string.Equals(pair.Value, hash, StringComparison.Ordinal) + )); } private string ComputeActiveFingerprint(PluginScanResult scan) @@ -767,10 +827,7 @@ private static string ComputeInstallationFingerprint(string pluginRoot) { Directory.CreateDirectory(pluginRoot); using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - string[] paths = Directory.EnumerateFileSystemEntries( - pluginRoot, - "*", - SearchOption.TopDirectoryOnly) + string[] paths = Directory.EnumerateFileSystemEntries(pluginRoot, "*", SearchOption.TopDirectoryOnly) .ToArray(); foreach (string path in paths.OrderBy(static value => value, StringComparer.OrdinalIgnoreCase)) { @@ -805,24 +862,29 @@ string candidateFingerprint internal string candidateFingerprint { get; } = candidateFingerprint; internal bool isActivated { get; set; } } + private sealed class AvailabilityPublication : IGenerationPublication, IAssemblyUnloadProbe { /// /// Gets the user-facing explanation of this feature or setting. /// public string description => "Plugin content publication without assembly retirement"; + /// /// Gets whether this implementation is completed. /// public bool isCompleted => true; + /// /// Leaves assembly publication unchanged while the content participant publishes its candidate. /// - public void Activate() { } + public void Activate() {} + /// /// Restores the state that existed before candidate activation began. /// - public void Rollback() { } + public void Rollback() {} + /// /// Completes the committed operation and releases temporary state. /// diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginRecoveryParticipant.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginRecoveryParticipant.cs index 734b5d1ed..e552828f9 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginRecoveryParticipant.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginRecoveryParticipant.cs @@ -53,8 +53,10 @@ public void Apply() public void Validate(IReadOnlyList changes) { if (m_owner.activePlugins.Select(static plugin => plugin.sourceMount.id).Distinct().Count() - != m_owner.activePlugins.Count) + != m_owner.activePlugins.Count + ) { throw new InvalidOperationException("Plugin publication contains duplicate source identities."); + } // Setting and Plugin IDs identify protocols, not live objects. Asset slots are validated by the mount // transaction; composing settings above restores their references with the owner's complete context. } @@ -80,7 +82,9 @@ public void RestorePreviousState() { m_owner.RollbackPending(); if (!m_prepared) + { return; + } m_assets.Update(); m_settings.RestorePreviousState(); } diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs index e2f57e6b9..0f086303e 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Core.Settings; using Inno.Assets.Pipeline; +using Inno.Core.Settings; using Inno.Plugins; namespace Inno.Plugins.Authoring; @@ -16,7 +16,6 @@ public enum PluginSourceKind /// The Plugin is installed as one top-level .iplugin package. /// Package, - /// /// The Plugin is embedded as one complete .iplugin dependency package. /// @@ -70,6 +69,7 @@ public sealed class PluginSourceLimits public sealed class PluginCandidate { private readonly PluginManifest m_manifest; + internal PluginCandidate( string sourcePath, PluginSourceKind sourceKind, @@ -116,15 +116,21 @@ bool containsCode /// public bool containsCode { get; } - private static PluginManifest CloneManifest(PluginManifest value) => new() + private static PluginManifest CloneManifest(PluginManifest value) + => new() { - pluginId = value.pluginId, displayName = value.displayName, - dependencies = value.dependencies.ToArray(), overrides = value.overrides.ToArray(), - contentRoots = value.contentRoots.ToArray(), assemblyDefinitions = value.assemblyDefinitions.ToArray(), + pluginId = value.pluginId, + displayName = value.displayName, + dependencies = value.dependencies.ToArray(), + overrides = value.overrides.ToArray(), + contentRoots = value.contentRoots.ToArray(), + assemblyDefinitions = value.assemblyDefinitions.ToArray(), settingContributions = value.settingContributions.Select(static record => new ProjectSettingRecord( - record.id, record.stableTypeId, record.propertyData)).ToArray() + record.id, + record.stableTypeId, + record.propertyData + )).ToArray() }; - } /// diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs index d65acc458..c4a06989c 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs @@ -7,11 +7,11 @@ using System.Security.Cryptography; using System.Text; using Inno.Assets; -using Inno.Plugins; using Inno.Assets.Pipeline; +using Inno.Core.Collections; using Inno.Core.IO; using Inno.Core.Serialization; -using Inno.Core.Collections; +using Inno.Plugins; namespace Inno.Plugins.Authoring; @@ -24,6 +24,7 @@ public sealed class PluginSourceService { ".dll", ".exe", ".dylib", ".so", ".a", ".lib" }; + private static readonly HashSet S_IGNORED_SYSTEM_FILE_NAMES = new(StringComparer.OrdinalIgnoreCase) { ".DS_Store", "Thumbs.db", "desktop.ini" @@ -78,9 +79,12 @@ public PluginScanResult Scan() var diagnostics = new List(); foreach (string unsupported in DiscoverUnsupportedSources()) { - diagnostics.Add(new PluginDiagnostic( - unsupported, - "Plugin installations must be .iplugin package files; directories and other file extensions are not supported.")); + diagnostics.Add( + new PluginDiagnostic( + unsupported, + "Plugin installations must be .iplugin package files; directories and other file extensions are not supported." + ) + ); } foreach (string packagePath in DiscoverPackages()) { @@ -133,7 +137,8 @@ private IEnumerable DiscoverPackages() .Where(static path => string.Equals( Path.GetExtension(path), ".iplugin", - StringComparison.OrdinalIgnoreCase)) + StringComparison.OrdinalIgnoreCase + )) .OrderBy(static path => path, StringComparer.OrdinalIgnoreCase); } @@ -145,9 +150,11 @@ private IEnumerable DiscoverUnsupportedSources() { string name = Path.GetFileName(path); if (name.StartsWith(".", StringComparison.Ordinal) || S_IGNORED_SYSTEM_FILE_NAMES.Contains(name)) + { return false; + } return Directory.Exists(path) - || !string.Equals(Path.GetExtension(path), ".iplugin", StringComparison.OrdinalIgnoreCase); + || !string.Equals(Path.GetExtension(path), ".iplugin", StringComparison.OrdinalIgnoreCase); }) .OrderBy(static path => path, StringComparer.OrdinalIgnoreCase); } @@ -165,7 +172,9 @@ private IReadOnlyList ValidatePackage( ref int embeddedCount ) { if (depth > m_limits.maximumEmbeddedDepth) + { throw new InvalidDataException("Plugin dependency packages exceed the configured nesting limit."); + } using ZipArchive archive = ZipFile.OpenRead(packagePath); ValidatedPackageEntry[] entries = ValidatePackageEntries(archive).ToArray(); ValidatedPackageEntry manifestEntry = entries.SingleOrDefault(static value => value.path == "Plugin.inno") @@ -178,40 +187,42 @@ ref int embeddedCount string destinationRoot = Path.Combine(m_cacheRoot, manifest.pluginId, contentHash); string contentRoot = Path.Combine(destinationRoot, "Assets"); if (!Directory.Exists(contentRoot)) + { ExtractAtomically(archive, entries, destinationRoot); + } ValidateMaterializedSnapshot(entries, destinationRoot); bool containsCode = ContainsCode(entries.Select(static entry => entry.path)); var candidates = new List { - CreateCandidate( - packagePath, - sourceKind, - contentHash, - manifest, - contentRoot, - containsCode) + CreateCandidate(packagePath, sourceKind, contentHash, manifest, contentRoot, containsCode) }; - foreach (ValidatedPackageEntry dependency in entries.Where(static entry => - entry.path.StartsWith("Dependencies/", StringComparison.Ordinal) - && entry.path.EndsWith(".iplugin", StringComparison.OrdinalIgnoreCase))) - { + foreach (ValidatedPackageEntry dependency in entries.Where(static entry => ( + entry.path.StartsWith("Dependencies/", StringComparison.Ordinal) + && entry.path.EndsWith(".iplugin", StringComparison.OrdinalIgnoreCase) + )) + ) { embeddedCount++; if (embeddedCount > m_limits.maximumEmbeddedPluginCount) + { throw new InvalidDataException("Plugin installation exceeds the embedded package-count limit."); + } string extractedPath = Path.Combine( destinationRoot, - dependency.path.Replace('/', Path.DirectorySeparatorChar)); + dependency.path.Replace('/', Path.DirectorySeparatorChar) + ); IReadOnlyList embedded = ValidatePackage( extractedPath, PluginSourceKind.EmbeddedPackage, depth + 1, - ref embeddedCount); + ref embeddedCount + ); PluginCandidate direct = embedded[0]; if (!manifest.dependencies.Contains(direct.manifest.pluginId, StringComparer.Ordinal)) { throw new InvalidDataException( - $"Embedded Plugin '{direct.manifest.pluginId}' is not declared by '{manifest.pluginId}'."); + $"Embedded Plugin '{direct.manifest.pluginId}' is not declared by '{manifest.pluginId}'." + ); } candidates.AddRange(embedded); } @@ -225,23 +236,26 @@ private PluginCandidate CreateCandidate( PluginManifest manifest, string contentRoot, bool containsCode - ) - => new( - Path.GetFullPath(sourcePath), - sourceKind, - contentHash, - manifest, - new AssetSourceMount( - new AssetSourceId(manifest.pluginId), - contentRoot, - isReadOnly: true, - manifest.dependencies.Select(static dependency => new AssetSourceId(dependency))), - containsCode); + ) => new( + Path.GetFullPath(sourcePath), + sourceKind, + contentHash, + manifest, + new AssetSourceMount( + new AssetSourceId(manifest.pluginId), + contentRoot, + isReadOnly: true, + manifest.dependencies.Select(static dependency => new AssetSourceId(dependency)) + ), + containsCode + ); private IEnumerable ValidatePackageEntries(ZipArchive archive) { if (archive.Entries.Count > m_limits.maximumEntryCount) + { throw new InvalidDataException("The .iplugin package exceeds the configured entry-count limit."); + } var paths = new PortablePathSet(".iplugin package"); long totalBytes = 0; @@ -249,18 +263,24 @@ private IEnumerable ValidatePackageEntries(ZipArchive arc { string path = ValidatePortablePath(entry.FullName); if (IsSymbolicLink(entry)) + { throw new InvalidDataException($"Plugin package entry '{path}' is a symbolic link."); + } if (IsIgnoredSystemFile(path)) + { continue; + } paths.Add(path); ValidateFileSize(path, entry.Length, ref totalBytes); if (entry.Length > 0) { double ratio = entry.CompressedLength == 0 - ? double.PositiveInfinity - : (double)entry.Length / entry.CompressedLength; + ? double.PositiveInfinity + : (double)entry.Length / entry.CompressedLength; if (ratio > m_limits.maximumCompressionRatio) + { throw new InvalidDataException($"Plugin package entry '{path}' exceeds the compression-ratio limit."); + } } ValidateSourceExtension(path); yield return new ValidatedPackageEntry(path, entry); @@ -273,17 +293,21 @@ private void ValidateFileSize( ref long totalBytes ) { if (length > m_limits.maximumFileBytes) + { throw new InvalidDataException($"Plugin source '{path}' exceeds the file-size limit."); + } totalBytes = checked(totalBytes + length); if (totalBytes > m_limits.maximumTotalBytes) + { throw new InvalidDataException("Plugin source exceeds the total uncompressed-size limit."); + } } private static void ValidateSourceExtension(string path) { if (!path.EndsWith("/", StringComparison.Ordinal) - && S_FORBIDDEN_BINARY_EXTENSIONS.Contains(Path.GetExtension(path))) - { + && S_FORBIDDEN_BINARY_EXTENSIONS.Contains(Path.GetExtension(path)) + ) { throw new InvalidDataException($"Plugin source '{path}' is a forbidden prebuilt binary."); } } @@ -299,35 +323,47 @@ private static void ValidateContent(IReadOnlyList entries) foreach (string path in paths) { if (path is "Plugin.inno" or "Assets/" or "Dependencies/" - || path.EndsWith("/", StringComparison.Ordinal)) + || path.EndsWith("/", StringComparison.Ordinal) + ) { continue; + } if (path.StartsWith("Dependencies/", StringComparison.Ordinal)) { string local = path["Dependencies/".Length..]; if (local.Contains('/') - || !local.EndsWith(".iplugin", StringComparison.OrdinalIgnoreCase)) - { + || !local.EndsWith(".iplugin", StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidDataException( - $"Plugin dependency entry '{path}' must be one direct .iplugin package."); + $"Plugin dependency entry '{path}' must be one direct .iplugin package." + ); } continue; } if (!path.StartsWith("Assets/", StringComparison.Ordinal)) + { throw new InvalidDataException($"Unexpected root .iplugin package entry '{path}'."); + } if (path.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase)) + { continue; + } if (!paths.Contains(path + ".imeta")) + { throw new InvalidDataException($"Plugin source '{path}' is missing its required .imeta sidecar."); + } } - foreach (string directory in paths.Where(static value => - value.StartsWith("Assets/", StringComparison.Ordinal) - && value.EndsWith("/", StringComparison.Ordinal) - && value != "Assets/")) - { + foreach (string directory in paths.Where(static value => ( + value.StartsWith("Assets/", StringComparison.Ordinal) + && value.EndsWith("/", StringComparison.Ordinal) + && value != "Assets/" + )) + ) { string sidecar = directory.TrimEnd('/') + ".imeta"; if (!paths.Contains(sidecar)) + { throw new InvalidDataException($"Plugin directory '{directory}' is missing its required .imeta sidecar."); + } } } @@ -338,9 +374,9 @@ List diagnostics var byId = new Dictionary(StringComparer.Ordinal); var rejected = new HashSet(StringComparer.Ordinal); foreach (IGrouping group in candidates.GroupBy( - static candidate => candidate.manifest.pluginId, - StringComparer.Ordinal)) - { + static candidate => candidate.manifest.pluginId, + StringComparer.Ordinal + )) { PluginCandidate[] installed = group.ToArray(); if (installed.Length == 1) { @@ -350,21 +386,21 @@ List diagnostics rejected.Add(group.Key); foreach (PluginCandidate duplicate in installed) { - diagnostics.Add(new PluginDiagnostic( - duplicate.sourcePath, - $"Plugin ID '{group.Key}' is installed more than once.")); + diagnostics.Add( + new PluginDiagnostic(duplicate.sourcePath, $"Plugin ID '{group.Key}' is installed more than once.") + ); } } foreach (PluginCandidate candidate in candidates.Where(candidate => - !rejected.Contains(candidate.manifest.pluginId))) - { + !rejected.Contains(candidate.manifest.pluginId)) + ) { string? missing = candidate.manifest.dependencies.FirstOrDefault(id => !byId.ContainsKey(id)); if (missing is not null) { rejected.Add(candidate.manifest.pluginId); - diagnostics.Add(new PluginDiagnostic( - candidate.sourcePath, - $"Plugin dependency '{missing}' is not installed.")); + diagnostics.Add( + new PluginDiagnostic(candidate.sourcePath, $"Plugin dependency '{missing}' is not installed.") + ); } } @@ -375,26 +411,32 @@ List diagnostics foreach (PluginCandidate candidate in byId.Values) { if (rejected.Contains(candidate.manifest.pluginId)) + { continue; + } string? blocked = candidate.manifest.dependencies.FirstOrDefault(rejected.Contains); if (blocked is null) + { continue; + } rejected.Add(candidate.manifest.pluginId); rejectionChanged = true; - diagnostics.Add(new PluginDiagnostic( - candidate.sourcePath, - $"Plugin dependency '{blocked}' is unavailable.")); + diagnostics.Add( + new PluginDiagnostic(candidate.sourcePath, $"Plugin dependency '{blocked}' is unavailable.") + ); } } while (rejectionChanged); var graph = new DependencyGraph(StringComparer.Ordinal, StringComparer.Ordinal); foreach (PluginCandidate candidate in byId.Values.Where(candidate => - !rejected.Contains(candidate.manifest.pluginId))) - { + !rejected.Contains(candidate.manifest.pluginId)) + ) { graph.AddNode(candidate.manifest.pluginId); foreach (string dependency in candidate.manifest.dependencies) + { graph.AddDependency(candidate.manifest.pluginId, dependency); + } } string[] cyclic = graph.GetStronglyConnectedComponents() .Where(component => component.Count > 1 || graph.DependsOn(component[0], component[0])) @@ -403,13 +445,18 @@ List diagnostics .ToArray(); var cycleBlocked = new HashSet(cyclic, StringComparer.Ordinal); foreach (string node in cyclic) + { cycleBlocked.UnionWith(graph.GetDependents(node, recursive: true)); + } foreach (string pluginId in cycleBlocked.OrderBy(static value => value, StringComparer.Ordinal)) { PluginCandidate candidate = byId[pluginId]; - diagnostics.Add(new PluginDiagnostic( - candidate.sourcePath, - $"Plugin dependency cycle prevents '{pluginId}' from loading.")); + diagnostics.Add( + new PluginDiagnostic( + candidate.sourcePath, + $"Plugin dependency cycle prevents '{pluginId}' from loading." + ) + ); graph.RemoveNode(pluginId); } return graph.TopologicalSort().Select(pluginId => byId[pluginId]).ToArray(); @@ -432,20 +479,23 @@ private PluginManifest ReadManifest(ZipArchiveEntry entry) private static bool IsManifestDataFailure(Exception exception) => exception is InvalidDataException - or InvalidOperationException - or ArgumentException - or NotSupportedException - or OverflowException; + or InvalidOperationException + or ArgumentException + or NotSupportedException + or OverflowException; private static bool ContainsCode(IEnumerable paths) - => paths.Any(static path => + => paths.Any(static path => ( path.StartsWith("Assets/", StringComparison.Ordinal) - && string.Equals(Path.GetExtension(path), ".cs", StringComparison.OrdinalIgnoreCase)); + && string.Equals(Path.GetExtension(path), ".cs", StringComparison.OrdinalIgnoreCase) + )); private static bool IsIgnoredSystemFile(string path) { if (path.EndsWith("/", StringComparison.Ordinal)) + { return false; + } int separator = path.LastIndexOf('/'); string fileName = separator < 0 ? path : path[(separator + 1)..]; return S_IGNORED_SYSTEM_FILE_NAMES.Contains(fileName); @@ -454,20 +504,26 @@ private static bool IsIgnoredSystemFile(string path) private static string ValidatePortablePath(string value) { if (string.IsNullOrWhiteSpace(value)) + { throw new InvalidDataException("Plugin source contains an empty entry path."); + } if (value.Contains('\\') || value.StartsWith("/", StringComparison.Ordinal) || Path.IsPathRooted(value)) + { throw new InvalidDataException($"Plugin source entry '{value}' is not a portable relative path."); + } string path = value.Normalize(NormalizationForm.FormC); if (!string.Equals(path, value, StringComparison.Ordinal)) + { throw new InvalidDataException($"Plugin source entry '{value}' is not Unicode-normalized."); + } string[] segments = path.TrimEnd('/').Split('/'); foreach (string segment in segments) { if (segment is "" or "." or ".." || segment.EndsWith(' ') || segment.EndsWith('.') || segment.IndexOfAny(['<', '>', ':', '"', '|', '?', '*']) >= 0 - || IsWindowsDeviceName(segment)) - { + || IsWindowsDeviceName(segment) + ) { throw new InvalidDataException($"Plugin source entry '{value}' has a non-portable segment."); } } @@ -478,9 +534,9 @@ private static bool IsWindowsDeviceName(string segment) { string name = Path.GetFileNameWithoutExtension(segment).ToUpperInvariant(); return name is "CON" or "PRN" or "AUX" or "NUL" - || name.Length == 4 - && (name.StartsWith("COM", StringComparison.Ordinal) || name.StartsWith("LPT", StringComparison.Ordinal)) - && name[3] is >= '1' and <= '9'; + || name.Length == 4 + && (name.StartsWith("COM", StringComparison.Ordinal) || name.StartsWith("LPT", StringComparison.Ordinal)) + && name[3] is >= '1' and <= '9'; } private static bool IsSymbolicLink(ZipArchiveEntry entry) => ((entry.ExternalAttributes >> 16) & 0xF000) == 0xA000; @@ -525,7 +581,9 @@ string destinationRoot finally { if (Directory.Exists(stagingRoot)) + { Directory.Delete(stagingRoot, recursive: true); + } } } @@ -534,26 +592,36 @@ private static void ValidateMaterializedSnapshot( string destinationRoot ) { ValidatedPackageEntry[] files = entries.Where(static item => !item.path.EndsWith("/", StringComparison.Ordinal)) - .OrderBy(static item => item.path, StringComparer.Ordinal).ToArray(); + .OrderBy(static item => item.path, StringComparer.Ordinal) + .ToArray(); string[] actual = PathBoundary.EnumerateFiles(destinationRoot) .Select(path => Path.GetRelativePath(destinationRoot, path).Replace('\\', '/')) - .Order(StringComparer.Ordinal).ToArray(); + .Order(StringComparer.Ordinal) + .ToArray(); if (!actual.SequenceEqual(files.Select(static item => item.path), StringComparer.Ordinal)) + { throw new InvalidDataException($"Plugin cache snapshot '{destinationRoot}' has an incomplete or unexpected file set."); + } foreach (ValidatedPackageEntry item in entries.Where(static item => item.path.EndsWith("/", StringComparison.Ordinal))) { if (!Directory.Exists(ResolveContainedPath(destinationRoot, item.path.TrimEnd('/')))) + { throw new InvalidDataException($"Plugin cache snapshot '{destinationRoot}' is missing directory '{item.path}'."); + } } foreach (ValidatedPackageEntry item in files) { string physical = ResolveContainedPath(destinationRoot, item.path); if (new FileInfo(physical).Length != item.entry.Length) + { throw new InvalidDataException($"Plugin cache snapshot '{destinationRoot}' has an invalid length for '{item.path}'."); + } using Stream expected = item.entry.Open(); using FileStream materialized = new(physical, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); if (!SHA256.HashData(materialized).AsSpan().SequenceEqual(SHA256.HashData(expected))) + { throw new InvalidDataException($"Plugin cache snapshot '{destinationRoot}' has invalid bytes for '{item.path}'."); + } } } @@ -567,9 +635,7 @@ string relativePath } catch (Exception exception) when (exception is ArgumentException or IOException) { - throw new InvalidDataException( - "Plugin source entry escaped its generation snapshot root.", - exception); + throw new InvalidDataException("Plugin source entry escaped its generation snapshot root.", exception); } } @@ -580,7 +646,9 @@ private static string ComputePackageContentHash(IReadOnlyList 0) + { hash.AppendData(buffer.AsSpan(0, read)); + } } private sealed class PortablePathSet(string sourceDescription) @@ -618,10 +688,11 @@ internal void Add(string path) { if (!m_ordinal.Add(path) || !m_portable.Add(path) - || !m_decomposed.Add(path.Normalize(NormalizationForm.FormD))) - { + || !m_decomposed.Add(path.Normalize(NormalizationForm.FormD)) + ) { throw new InvalidDataException( - $"Plugin {sourceDescription} contains a duplicate or non-portable path '{path}'."); + $"Plugin {sourceDescription} contains a duplicate or non-portable path '{path}'." + ); } } } diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/Properties/ScriptingApi.cs b/src/runtime/plugins/Inno.Plugins.Authoring/Properties/ScriptingApi.cs index 34f29919b..ab700a4d9 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/Properties/ScriptingApi.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/Properties/ScriptingApi.cs @@ -1,6 +1,3 @@ using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEditor.Plugins", - "Inno.Plugins.Authoring", - ScriptingApiScope.Editor)] +[assembly: ScriptingApiNamespace("InnoEditor.Plugins", "Inno.Plugins.Authoring", ScriptingApiScope.Editor)] diff --git a/src/runtime/plugins/Inno.Plugins/PluginManifest.cs b/src/runtime/plugins/Inno.Plugins/PluginManifest.cs index 5bf329d50..fdb2e32c1 100644 --- a/src/runtime/plugins/Inno.Plugins/PluginManifest.cs +++ b/src/runtime/plugins/Inno.Plugins/PluginManifest.cs @@ -1,8 +1,8 @@ using System; using System.IO; using System.Linq; -using Inno.Core.Settings; using Inno.Core.Serialization; +using Inno.Core.Settings; namespace Inno.Plugins; @@ -70,33 +70,47 @@ public void Validate() throw new InvalidDataException("Plugin.inno contains an invalid Plugin ID.", exception); } if (string.Equals(pluginId, Inno.Assets.AssetSourceId.project.value, StringComparison.Ordinal)) + { throw new InvalidDataException("Plugin ID 'project' is reserved by the writable project source."); + } if (string.IsNullOrWhiteSpace(displayName)) + { throw new InvalidDataException("Plugin.inno requires a display name."); + } EnsureUniquePluginIds(dependencies, nameof(dependencies)); EnsureUniquePluginIds(overrides, nameof(overrides)); EnsureUniquePaths(contentRoots, nameof(contentRoots)); EnsureUniquePaths(assemblyDefinitions, nameof(assemblyDefinitions)); if (dependencies.Contains(pluginId, StringComparer.Ordinal)) + { throw new InvalidDataException("A Plugin cannot depend on itself."); + } if (overrides.Any(value => !dependencies.Contains(value, StringComparer.Ordinal))) + { throw new InvalidDataException("Every explicit override must identify a declared dependency."); + } if (settingContributions is null) + { throw new InvalidDataException("Plugin setting contributions cannot be null."); + } if (settingContributions.Select(static value => value.id).Distinct().Count() != settingContributions.Length) + { throw new InvalidDataException("Plugin setting contributions must use unique setting IDs."); + } foreach (ProjectSettingRecord contribution in settingContributions) { if (!contribution.id.isValid || contribution.stableTypeId == Guid.Empty || contribution.propertyData is null - || contribution.propertyData.Length == 0) - { + || contribution.propertyData.Length == 0 + ) { throw new InvalidDataException("Plugin setting contribution contains invalid identity or payload data."); } } if (contentRoots.Length != 1 || !string.Equals(contentRoots[0], "Assets", StringComparison.Ordinal)) + { throw new InvalidDataException("The current local Plugin container requires the single content root 'Assets'."); + } } private static void EnsureUniquePluginIds( @@ -104,11 +118,17 @@ private static void EnsureUniquePluginIds( string name ) { if (values is null || values.Any(string.IsNullOrWhiteSpace)) + { throw new InvalidDataException($"Plugin manifest field '{name}' contains an empty value."); + } if (values.Distinct(StringComparer.Ordinal).Count() != values.Length) + { throw new InvalidDataException($"Plugin manifest field '{name}' contains duplicate values."); + } foreach (string value in values) + { _ = new Inno.Assets.AssetSourceId(value); + } } private static void EnsureUniquePaths( @@ -116,17 +136,25 @@ private static void EnsureUniquePaths( string name ) { if (values is null || values.Any(string.IsNullOrWhiteSpace)) + { throw new InvalidDataException($"Plugin manifest field '{name}' contains an empty path."); + } string[] normalized = values.Select(static value => { if (value.Contains('\\') || value.StartsWith("/", StringComparison.Ordinal)) + { throw new InvalidDataException("Plugin manifest paths must be portable container-relative paths."); + } string path = value.Trim('/'); if (path.Split('/').Any(static segment => segment is "" or "." or "..")) + { throw new InvalidDataException("Plugin manifest paths cannot contain traversal segments."); + } return path; }).ToArray(); if (normalized.Distinct(StringComparer.OrdinalIgnoreCase).Count() != normalized.Length) + { throw new InvalidDataException($"Plugin manifest field '{name}' contains duplicate paths."); + } } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyDefinitionAsset.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyDefinitionAsset.cs index b52485954..2986526eb 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyDefinitionAsset.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyDefinitionAsset.cs @@ -1,8 +1,7 @@ using System; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Scripting.Compiler; @@ -51,9 +50,7 @@ public sealed class ScriptAssemblyDefinitionAsset : AssetObject /// /// Creates an empty definition asset for deserialization. /// - public ScriptAssemblyDefinitionAsset() - { - } + public ScriptAssemblyDefinitionAsset() {} /// /// Creates a configured script assembly definition for native asset export. diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyScope.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyScope.cs index b6356b307..91d6ddff5 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyScope.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptAssemblyScope.cs @@ -9,7 +9,6 @@ public enum ScriptAssemblyScope /// The assembly can use runtime scripting APIs only. /// Runtime, - /// /// The assembly can use runtime and editor scripting APIs. /// diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceAsset.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceAsset.cs index fdb84cb9d..9a7876da6 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceAsset.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceAsset.cs @@ -1,6 +1,6 @@ using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Scripting.Compiler; @@ -31,9 +31,7 @@ public sealed class ScriptSourceAsset : AssetObject /// /// Creates an empty script source asset for deserialization. /// - public ScriptSourceAsset() - { - } + public ScriptSourceAsset() {} internal ScriptSourceAsset( ScriptAssemblyScope scope, diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs index 4f97870d2..a7aa654c9 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs @@ -8,9 +8,7 @@ internal sealed class ScriptSourceTypeManifest : ISerializable /// /// Creates a validated script source type manifest instance. /// - public ScriptSourceTypeManifest() - { - } + public ScriptSourceTypeManifest() {} /// /// Creates a validated script source type manifest instance. @@ -91,18 +89,22 @@ int column /// Gets text used for stable identity, presentation, or diagnostics by this contract. /// public string typeName { get; set; } + /// /// Gets text used for stable identity, presentation, or diagnostics by this contract. /// public string declarationKind { get; set; } + /// /// Gets whether the caller-visible condition represented by this property is satisfied. /// public bool partial { get; set; } + /// /// Gets the scalar measurement or identity associated with the current state. /// public int line { get; set; } + /// /// Gets the scalar measurement or identity associated with the current state. /// diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/CSharpSampleSourceRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/CSharpSampleSourceRewriter.cs index 916a943f2..99ce3479a 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/CSharpSampleSourceRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/CSharpSampleSourceRewriter.cs @@ -3,10 +3,10 @@ using System.IO; using System.Linq; using System.Text; -using Inno.Assets.Pipeline; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Inno.Assets.Pipeline; namespace Inno.Scripting.Compiler; @@ -26,24 +26,34 @@ public void Transform(AssetSampleTransformContext context) { ArgumentNullException.ThrowIfNull(context); foreach (string path in Directory.GetFiles(context.stagedRoot, "*.cs", SearchOption.AllDirectories) - .Order(StringComparer.Ordinal)) - { + .Order(StringComparer.Ordinal) + ) { context.cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(context.stagedRoot, path).Replace('\\', '/'); if (!context.TryGetSourceIdentity(relative, out Guid oldSourceId, out Guid newSourceId)) + { throw new InvalidDataException($"Sample C# source '{relative}' has no asset identity metadata."); - context.MapType(ScriptTypeIdentity.CreateCanonical(oldSourceId), - ScriptTypeIdentity.CreateCanonical(newSourceId)); + } + context.MapType( + ScriptTypeIdentity.CreateCanonical(oldSourceId), + ScriptTypeIdentity.CreateCanonical(newSourceId) + ); byte[] bytes = File.ReadAllBytes(path); bool hasBom = bytes.AsSpan().StartsWith(Encoding.UTF8.GetPreamble()); string source = File.ReadAllText(path, Encoding.UTF8); SyntaxNode root = CSharpSyntaxTree.ParseText( - source, cancellationToken: context.cancellationToken).GetRoot(context.cancellationToken); - AttributeSyntax[] attributes = root.DescendantNodes().OfType() - .Where(static attribute => IsStableTypeId(attribute.Name.ToString())).ToArray(); + source, + cancellationToken: context.cancellationToken + ).GetRoot(context.cancellationToken); + AttributeSyntax[] attributes = root.DescendantNodes() + .OfType() + .Where(static attribute => IsStableTypeId(attribute.Name.ToString())) + .ToArray(); if (attributes.Length == 0) + { continue; + } SyntaxNode rewritten = root.ReplaceNodes(attributes, ( original, _ @@ -53,19 +63,24 @@ public void Transform(AssetSampleTransformContext context) if (attribute.ArgumentList?.Arguments is not { Count: 1 } arguments || arguments[0].Expression is not LiteralExpressionSyntax literal || !literal.IsKind(SyntaxKind.StringLiteralExpression) - || !Guid.TryParse(literal.Token.ValueText, out Guid oldId)) - { + || !Guid.TryParse(literal.Token.ValueText, out Guid oldId) + ) { throw new InvalidDataException( - $"Sample C# source '{relative}' has a StableTypeId that cannot be cloned safely."); + $"Sample C# source '{relative}' has a StableTypeId that cannot be cloned safely." + ); } Guid newId = context.identityMap.TryGetValue(oldId, out Guid mapped) - ? mapped : Guid.NewGuid(); + ? mapped + : Guid.NewGuid(); context.MapType(oldId, newId); - LiteralExpressionSyntax replacement = SyntaxFactory.LiteralExpression( - SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(newId.ToString("D"))) + LiteralExpressionSyntax replacement = SyntaxFactory + .LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(newId.ToString("D"))) .WithTriviaFrom(literal); - return attribute.WithArgumentList(attribute.ArgumentList.WithArguments( - SyntaxFactory.SingletonSeparatedList(arguments[0].WithExpression(replacement)))); + return attribute.WithArgumentList( + attribute.ArgumentList.WithArguments( + SyntaxFactory.SingletonSeparatedList(arguments[0].WithExpression(replacement)) + ) + ); }); File.WriteAllText(path, rewritten.ToFullString(), new UTF8Encoding(hasBom)); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs index 8e51a2565..869bb76d0 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs @@ -6,7 +6,6 @@ using System.Security.Cryptography; using System.Text; using System.Threading; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -30,8 +29,8 @@ internal static ScriptCompilationEnvironment Resolve( typeof(FrameworkReferenceResolver).Module.ModuleVersionId.ToString("N"), inputs.sdkIdentity, string.Join(";", inputs.predefinedSymbols) - }) - { + } + ) { hash.AppendData(Encoding.UTF8.GetBytes(identity)); hash.AppendData([0]); } @@ -42,12 +41,16 @@ internal static ScriptCompilationEnvironment Resolve( hash.AppendData([0]); byte[] image = File.ReadAllBytes(path); hash.AppendData(SHA256.HashData(image)); - references.Add(MetadataReference.CreateFromImage( - ImmutableCollectionsMarshal.AsImmutableArray(image), filePath: path)); + references.Add( + MetadataReference.CreateFromImage(ImmutableCollectionsMarshal.AsImmutableArray(image), filePath: path) + ); names.Add(Path.GetFileNameWithoutExtension(path)); } return new ScriptCompilationEnvironment( - references.AsReadOnly(), names, Convert.ToHexStringLower(hash.GetHashAndReset()), inputs); + references.AsReadOnly(), + names, + Convert.ToHexStringLower(hash.GetHashAndReset()), + inputs + ); } - } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs index 40bcbf818..08cdb1017 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -14,8 +13,11 @@ namespace Inno.Scripting.Compiler; /// Enforces logical scripting namespaces and rejects direct implementation namespace access. /// [DiagnosticAnalyzer(LanguageNames.CSharp)] -[System.Diagnostics.CodeAnalysis.SuppressMessage("MicrosoftCodeAnalysisCorrectness", "RS1041", - Justification = "This analyzer is loaded only by the .NET 10 SDK compiler shared by authoring and generated IDE projects.")] +[System.Diagnostics.CodeAnalysis.SuppressMessage( + "MicrosoftCodeAnalysisCorrectness", + "RS1041", + Justification = "This analyzer is loaded only by the .NET 10 SDK compiler shared by authoring and generated IDE projects." +)] public sealed class LogicalScriptingApiAnalyzer : DiagnosticAnalyzer { /// @@ -39,7 +41,8 @@ public sealed class LogicalScriptingApiAnalyzer : DiagnosticAnalyzer "Use scripting namespace '{0}' instead of implementation namespace '{1}'", "Inno Scripting", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); private static readonly DiagnosticDescriptor s_missingLogicalNamespace = new( missingLogicalNamespaceDiagnosticId, @@ -47,7 +50,8 @@ public sealed class LogicalScriptingApiAnalyzer : DiagnosticAnalyzer "Type '{0}' requires 'using {1};'", "Inno Scripting", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); private static readonly DiagnosticDescriptor s_compilationWideUsing = new( compilationWideUsingDiagnosticId, @@ -55,16 +59,14 @@ public sealed class LogicalScriptingApiAnalyzer : DiagnosticAnalyzer "Use an ordinary using directive in each source file", "Inno Scripting", DiagnosticSeverity.Error, - isEnabledByDefault: true); + isEnabledByDefault: true + ); /// /// Gets the complete compiler diagnostic set enforced by this analyzer. /// public override ImmutableArray SupportedDiagnostics - => ImmutableArray.Create( - s_directImplementationNamespace, - s_missingLogicalNamespace, - s_compilationWideUsing); + => ImmutableArray.Create(s_directImplementationNamespace, s_missingLogicalNamespace, s_compilationWideUsing); /// /// Initializes owned resources and establishes the instance's active lifetime. @@ -78,25 +80,26 @@ public override void Initialize(AnalysisContext context) context.EnableConcurrentExecution(); context.RegisterCompilationStartAction(startContext => { - startContext.RegisterSyntaxNodeAction( - AnalyzeCompilationWideUsing, - SyntaxKind.UsingDirective); - ScriptApiMap map = ScriptApiMap.Read( - startContext.Options.AdditionalFiles, - startContext.CancellationToken); + startContext.RegisterSyntaxNodeAction(AnalyzeCompilationWideUsing, SyntaxKind.UsingDirective); + ScriptApiMap map = ScriptApiMap.Read(startContext.Options.AdditionalFiles, startContext.CancellationToken); if (map.namespaces.IsDefaultOrEmpty) + { return; + } startContext.RegisterSyntaxNodeAction( nodeContext => AnalyzeUsing(nodeContext, map), - SyntaxKind.UsingDirective); + SyntaxKind.UsingDirective + ); startContext.RegisterSyntaxNodeAction( nodeContext => AnalyzeTypeReference(nodeContext, map), SyntaxKind.IdentifierName, - SyntaxKind.GenericName); + SyntaxKind.GenericName + ); startContext.RegisterSyntaxNodeAction( nodeContext => AnalyzeQualifiedTypeReference(nodeContext, map), SyntaxKind.QualifiedName, - SyntaxKind.AliasQualifiedName); + SyntaxKind.AliasQualifiedName + ); }); } @@ -104,10 +107,10 @@ private static void AnalyzeCompilationWideUsing(SyntaxNodeAnalysisContext contex { var usingDirective = (UsingDirectiveSyntax)context.Node; if (usingDirective.GlobalKeyword == default) + { return; - context.ReportDiagnostic(Diagnostic.Create( - s_compilationWideUsing, - usingDirective.GlobalKeyword.GetLocation())); + } + context.ReportDiagnostic(Diagnostic.Create(s_compilationWideUsing, usingDirective.GlobalKeyword.GetLocation())); } private static void AnalyzeUsing( @@ -116,26 +119,36 @@ ScriptApiMap map ) { var usingDirective = (UsingDirectiveSyntax)context.Node; if (usingDirective.Name is null) + { return; + } string namespaceName = usingDirective.Name.ToString(); ScriptApiNamespaceMap? mapping = FindByImplementationNamespace(map, namespaceName); if (mapping is null) + { return; - context.ReportDiagnostic(Diagnostic.Create( - s_directImplementationNamespace, - usingDirective.Name.GetLocation(), - mapping.apiNamespace, - namespaceName)); + } + context.ReportDiagnostic( + Diagnostic.Create( + s_directImplementationNamespace, + usingDirective.Name.GetLocation(), + mapping.apiNamespace, + namespaceName + ) + ); } private static void AnalyzeTypeReference( SyntaxNodeAnalysisContext context, ScriptApiMap map ) { - if (context.Node.AncestorsAndSelf().OfType().Any() || - context.Node.Ancestors().Any(static ancestor => - ancestor is QualifiedNameSyntax or AliasQualifiedNameSyntax)) + if (context.Node.AncestorsAndSelf().OfType().Any() + || context.Node.Ancestors().Any(static ancestor => ( + ancestor is QualifiedNameSyntax or AliasQualifiedNameSyntax + )) + ) { return; + } ISymbol? symbol = context.SemanticModel.GetSymbolInfo(context.Node, context.CancellationToken).Symbol; INamedTypeSymbol? type = symbol switch { @@ -144,55 +157,69 @@ ScriptApiMap map _ => null }; if (type is null) + { return; + } string implementationNamespace = type.ContainingNamespace?.ToDisplayString() ?? string.Empty; ScriptApiNamespaceMap? mapping = FindByImplementationNamespace(map, implementationNamespace); if (mapping is null || HasLogicalUsing(context.Node, mapping.apiNamespace)) + { return; - context.ReportDiagnostic(Diagnostic.Create( - s_missingLogicalNamespace, - context.Node.GetLocation(), - type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), - mapping.apiNamespace)); + } + context.ReportDiagnostic( + Diagnostic.Create( + s_missingLogicalNamespace, + context.Node.GetLocation(), + type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), + mapping.apiNamespace + ) + ); } private static void AnalyzeQualifiedTypeReference( SyntaxNodeAnalysisContext context, ScriptApiMap map ) { - if (context.Node.AncestorsAndSelf().OfType().Any() || - context.Node.Parent is QualifiedNameSyntax or AliasQualifiedNameSyntax) - { + if (context.Node.AncestorsAndSelf().OfType().Any() + || context.Node.Parent is QualifiedNameSyntax or AliasQualifiedNameSyntax + ) { return; } if (context.SemanticModel.GetSymbolInfo(context.Node, context.CancellationToken).Symbol - is not INamedTypeSymbol type) - { + is not INamedTypeSymbol type + ) { return; } string implementationNamespace = type.ContainingNamespace?.ToDisplayString() ?? string.Empty; ScriptApiNamespaceMap? mapping = FindByImplementationNamespace(map, implementationNamespace); if (mapping is null) + { return; - context.ReportDiagnostic(Diagnostic.Create( - s_directImplementationNamespace, - context.Node.GetLocation(), - mapping.apiNamespace, - implementationNamespace)); + } + context.ReportDiagnostic( + Diagnostic.Create( + s_directImplementationNamespace, + context.Node.GetLocation(), + mapping.apiNamespace, + implementationNamespace + ) + ); } private static ScriptApiNamespaceMap? FindByImplementationNamespace( ScriptApiMap map, string namespaceName - ) - => map.namespaces - .SelectMany(mapping => mapping.implementationNamespaces.Select( - implementation => new { mapping, implementation })) - .Where(candidate => string.Equals(namespaceName, candidate.implementation, StringComparison.Ordinal) || - namespaceName.StartsWith(candidate.implementation + ".", StringComparison.Ordinal)) - .OrderByDescending(static candidate => candidate.implementation.Length) - .Select(static candidate => candidate.mapping) - .FirstOrDefault(); + ) => map.namespaces + .SelectMany(mapping => mapping.implementationNamespaces.Select( + implementation => new { mapping, implementation } + )) + .Where(candidate => ( + string.Equals(namespaceName, candidate.implementation, StringComparison.Ordinal) + || namespaceName.StartsWith(candidate.implementation + ".", StringComparison.Ordinal) + )) + .OrderByDescending(static candidate => candidate.implementation.Length) + .Select(static candidate => candidate.mapping) + .FirstOrDefault(); private static bool HasLogicalUsing( SyntaxNode node, @@ -200,12 +227,17 @@ string apiNamespace ) { var usings = new List(); if (node.SyntaxTree.GetRoot() is CompilationUnitSyntax compilationUnit) + { usings.AddRange(compilationUnit.Usings); + } foreach (BaseNamespaceDeclarationSyntax declaration in node.Ancestors().OfType()) + { usings.AddRange(declaration.Usings); - return usings.Any(usingDirective => - usingDirective.Alias is null && - usingDirective.Name is not null && - string.Equals(usingDirective.Name.ToString(), apiNamespace, StringComparison.Ordinal)); + } + return usings.Any(usingDirective => ( + usingDirective.Alias is null + && usingDirective.Name is not null + && string.Equals(usingDirective.Name.ToString(), apiNamespace, StringComparison.Ordinal) + )); } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs index 0380ca252..8facb6370 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs @@ -15,7 +15,9 @@ internal static int Collect( IEnumerable protectedDirectories ) { if (!Directory.Exists(root)) + { return 0; + } var protectedPaths = protectedDirectories .Where(static path => !string.IsNullOrWhiteSpace(path)) .Select(static path => Path.GetFullPath(path!)) @@ -31,9 +33,9 @@ internal static int Collect( int removed = 0; foreach (Entry entry in entries) { - if (protectedPaths.Contains(entry.path) || - entry.lastWriteUtc > cutoff && totalSize <= C_MAXIMUM_SIZE) - { + if (protectedPaths.Contains(entry.path) + || entry.lastWriteUtc > cutoff && totalSize <= C_MAXIMUM_SIZE + ) { continue; } try diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs index 362af54a2..735c7aee3 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Reflection; using System.Runtime.Loader; - using Inno.Scripting.Api; namespace Inno.Scripting.Compiler; @@ -53,10 +52,11 @@ internal static ScriptApiProfile Build(bool includeEditor) { LoadReferencedInnoAssemblies(); Assembly[] loaded = AppDomain.CurrentDomain.GetAssemblies() - .Where(static assembly => - !assembly.IsDynamic && - !string.IsNullOrWhiteSpace(assembly.Location) && - AssemblyLoadContext.GetLoadContext(assembly) == AssemblyLoadContext.Default) + .Where(static assembly => ( + !assembly.IsDynamic + && !string.IsNullOrWhiteSpace(assembly.Location) + && AssemblyLoadContext.GetLoadContext(assembly) == AssemblyLoadContext.Default + )) .ToArray(); var byName = loaded .Where(static assembly => assembly.GetName().Name is not null) @@ -67,18 +67,13 @@ internal static ScriptApiProfile Build(bool includeEditor) .SelectMany(assembly => assembly .GetCustomAttributes() .Where(attribute => Includes(attribute.scope, includeEditor)) - .Select(attribute => new NamespaceMapping( - attribute.name, - attribute.implementationNamespace, - assembly))) + .Select(attribute => new NamespaceMapping(attribute.name, attribute.implementationNamespace, assembly))) .OrderBy(static mapping => mapping.apiNamespace, StringComparer.Ordinal) .ThenBy(static mapping => mapping.implementationNamespace, StringComparer.Ordinal) .ToArray(); ValidateNamespaceMappings(declaredNamespaceMappings); NamespaceMapping[] namespaceMappings = declaredNamespaceMappings - .GroupBy(static mapping => ( - mapping.apiNamespace, - mapping.implementationNamespace)) + .GroupBy(static mapping => (mapping.apiNamespace, mapping.implementationNamespace)) .Select(static group => group.First()) .ToArray(); @@ -86,10 +81,7 @@ internal static ScriptApiProfile Build(bool includeEditor) .SelectMany(declarationAssembly => declarationAssembly .GetCustomAttributes() .Where(attribute => Includes(attribute.scope, includeEditor)) - .Select(attribute => new DeclaredTypeExport( - declarationAssembly, - attribute.type, - attribute.name))) + .Select(attribute => new DeclaredTypeExport(declarationAssembly, attribute.type, attribute.name))) .OrderBy(static export => export.type.Assembly.GetName().Name, StringComparer.Ordinal) .ThenBy(static export => export.type.FullName, StringComparer.Ordinal) .ThenBy(static export => export.name, StringComparer.Ordinal) @@ -99,9 +91,9 @@ internal static ScriptApiProfile Build(bool includeEditor) var exports = new List(); var implementationAssemblies = new HashSet(); foreach (IGrouping implementationGroup in declaredExports - .GroupBy(static export => export.type.Assembly) - .OrderBy(static group => group.Key.GetName().Name, StringComparer.Ordinal)) - { + .GroupBy(static export => export.type.Assembly) + .OrderBy(static group => group.Key.GetName().Name, StringComparer.Ordinal) + ) { ScriptApiTypeExport[] assemblyExports = implementationGroup .Select(static export => new ScriptApiTypeExport(export.type, export.name)) .Distinct() @@ -120,7 +112,8 @@ internal static ScriptApiProfile Build(bool includeEditor) ScriptApiNamespaceMapping[] publicMappings = namespaceMappings .Select(static mapping => new ScriptApiNamespaceMapping( mapping.apiNamespace, - mapping.implementationNamespace)) + mapping.implementationNamespace + )) .Distinct() .ToArray(); ScriptApiTypeMapping[] allTypeMappings = CreateTypeMappings(exports, namespaceMappings); @@ -134,8 +127,9 @@ internal static ScriptApiProfile Build(bool includeEditor) .Where(static value => value.metadata is not null) .Select(static value => new ScriptApiAttachableType( value.type.FullName - ?? throw new InvalidOperationException("An attachable scripting API type has no full name."), - value.metadata!.kind)) + ?? throw new InvalidOperationException("An attachable scripting API type has no full name."), + value.metadata!.kind + )) .Distinct() .OrderBy(static value => value.implementationName, StringComparer.Ordinal) .ToArray(); @@ -149,14 +143,14 @@ internal static ScriptApiProfile Build(bool includeEditor) apiNamespaces, publicMappings, typeMappings, - attachableTypes); + attachableTypes + ); } private static bool Includes( ScriptingApiScope scope, bool includeEditor - ) - => scope is ScriptingApiScope.Runtime or ScriptingApiScope.Authoring || includeEditor && scope == ScriptingApiScope.Editor; + ) => scope is ScriptingApiScope.Runtime or ScriptingApiScope.Authoring || includeEditor && scope == ScriptingApiScope.Editor; private static void ValidateExports( IReadOnlyList exports, @@ -167,34 +161,40 @@ IReadOnlyList mappings if (group.Select(static export => export.name).Distinct(StringComparer.Ordinal).Skip(1).Any()) { throw new InvalidOperationException( - $"Script API type '{group.Key.FullName}' cannot be exported with multiple names."); + $"Script API type '{group.Key.FullName}' cannot be exported with multiple names." + ); } } foreach (DeclaredTypeExport export in exports) { Type type = export.type; if (!type.IsPublic && !type.IsNestedPublic) + { throw new InvalidOperationException($"Script API type '{type.FullName}' must be public."); + } if (!Microsoft.CodeAnalysis.CSharp.SyntaxFacts.IsValidIdentifier(export.name)) { throw new InvalidOperationException( - $"Script API name '{export.name}' for type '{type.FullName}' is not a valid C# identifier."); + $"Script API name '{export.name}' for type '{type.FullName}' is not a valid C# identifier." + ); } if (type.IsGenericTypeDefinition && !string.Equals( - export.name, - GetTypeName(type), - StringComparison.Ordinal)) - { + export.name, + GetTypeName(type), + StringComparison.Ordinal + )) { throw new InvalidOperationException( - $"Generic script API type '{type.FullName}' cannot use a script-facing alias."); + $"Generic script API type '{type.FullName}' cannot use a script-facing alias." + ); } string implementationNamespace = type.Namespace ?? string.Empty; if (!mappings.Any(mapping => - string.Equals(mapping.implementationNamespace, implementationNamespace, StringComparison.Ordinal))) - { + string.Equals(mapping.implementationNamespace, implementationNamespace, StringComparison.Ordinal)) + ) { throw new InvalidOperationException( - $"Script API type '{type.FullName}' exported by " + - $"'{export.declarationAssembly.GetName().Name}' is not assigned to a declared script API namespace."); + $"Script API type '{type.FullName}' exported by " + + $"'{export.declarationAssembly.GetName().Name}' is not assigned to a declared script API namespace." + ); } } } @@ -202,41 +202,42 @@ IReadOnlyList mappings private static ScriptApiTypeMapping[] CreateTypeMappings( IReadOnlyList exports, IReadOnlyList namespaceMappings - ) - => exports - .SelectMany(assemblyExport => assemblyExport.exports.Select(typeExport => - { - NamespaceMapping mapping = namespaceMappings.Single(value => - string.Equals( - value.implementationNamespace, - typeExport.type.Namespace ?? string.Empty, - StringComparison.Ordinal)); - return new ScriptApiTypeMapping( - mapping.apiNamespace, - typeExport.name, + ) => exports + .SelectMany(assemblyExport => assemblyExport.exports.Select(typeExport => + { + NamespaceMapping mapping = namespaceMappings.Single(value => + string.Equals( + value.implementationNamespace, typeExport.type.Namespace ?? string.Empty, - GetTypeName(typeExport.type), - typeExport.type.IsGenericTypeDefinition - ? typeExport.type.GetGenericArguments().Length - : 0); - })) - .OrderBy(static mapping => mapping.apiNamespace, StringComparer.Ordinal) - .ThenBy(static mapping => mapping.apiName, StringComparer.Ordinal) - .ToArray(); + StringComparison.Ordinal + )); + return new ScriptApiTypeMapping( + mapping.apiNamespace, + typeExport.name, + typeExport.type.Namespace ?? string.Empty, + GetTypeName(typeExport.type), + typeExport.type.IsGenericTypeDefinition + ? typeExport.type.GetGenericArguments().Length + : 0 + ); + })) + .OrderBy(static mapping => mapping.apiNamespace, StringComparer.Ordinal) + .ThenBy(static mapping => mapping.apiName, StringComparer.Ordinal) + .ToArray(); private static void ValidateTypeMappings(IReadOnlyList mappings) { foreach (IGrouping<(string apiNamespace, string apiName, int arity), ScriptApiTypeMapping> group in mappings - .GroupBy(static mapping => (mapping.apiNamespace, mapping.apiName, mapping.arity))) - { - if (group.Select(static mapping => - (mapping.implementationNamespace, mapping.implementationName)) + .GroupBy(static mapping => (mapping.apiNamespace, mapping.apiName, mapping.arity)) + ) { + if (group.Select(static mapping => (mapping.implementationNamespace, mapping.implementationName)) .Distinct() .Skip(1) - .Any()) - { + .Any() + ) { throw new InvalidOperationException( - $"Script API type name '{group.Key.apiNamespace}.{group.Key.apiName}' maps to multiple runtime types."); + $"Script API type name '{group.Key.apiNamespace}.{group.Key.apiName}' maps to multiple runtime types." + ); } } } @@ -250,8 +251,8 @@ private static string GetTypeName(Type type) private static void ValidateNamespaceMappings(IReadOnlyList mappings) { foreach (IGrouping group in mappings - .GroupBy(static mapping => mapping.implementationNamespace, StringComparer.Ordinal)) - { + .GroupBy(static mapping => mapping.implementationNamespace, StringComparer.Ordinal) + ) { string[] apiNamespaces = group .Select(static mapping => mapping.apiNamespace) .Distinct(StringComparer.Ordinal) @@ -262,10 +263,12 @@ private static void ValidateNamespaceMappings(IReadOnlyList ma ", ", group.Select(static mapping => mapping.declarationAssembly.GetName().Name) .Distinct(StringComparer.Ordinal) - .OrderBy(static name => name, StringComparer.Ordinal)); + .OrderBy(static name => name, StringComparer.Ordinal) + ); throw new InvalidOperationException( - $"Implementation namespace '{group.Key}' maps to multiple script API namespaces " + - $"across declarations in: {declarations}."); + $"Implementation namespace '{group.Key}' maps to multiple script API namespaces " + + $"across declarations in: {declarations}." + ); } } } @@ -276,20 +279,25 @@ private static void AddWithDependencies( ISet selected ) { if (!selected.Add(assembly)) + { return; + } foreach (AssemblyName reference in assembly.GetReferencedAssemblies()) { if (reference.Name is not null && byName.TryGetValue(reference.Name, out Assembly? dependency)) + { AddWithDependencies(dependency, byName, selected); + } } } private static void LoadReferencedInnoAssemblies() { Assembly[] loaded = AppDomain.CurrentDomain.GetAssemblies() - .Where(static assembly => - !assembly.IsDynamic && - AssemblyLoadContext.GetLoadContext(assembly) == AssemblyLoadContext.Default) + .Where(static assembly => ( + !assembly.IsDynamic + && AssemblyLoadContext.GetLoadContext(assembly) == AssemblyLoadContext.Default + )) .ToArray(); var byName = loaded .Where(static assembly => assembly.GetName().Name is not null) @@ -303,7 +311,9 @@ private static void LoadReferencedInnoAssemblies() { string name = reference.Name ?? string.Empty; if (!name.StartsWith("Inno.", StringComparison.Ordinal) || byName.ContainsKey(name)) + { continue; + } try { Assembly dependency = Assembly.Load(reference); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs index 9347bfc35..33645247e 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs @@ -22,13 +22,16 @@ internal static Inputs Capture(IReadOnlyList exports) { var documents = new Dictionary(StringComparer.Ordinal); var identity = new StringBuilder(C_SCHEMA); - foreach (Assembly assembly in exports.Select(static export => export.type.Assembly).Distinct() - .OrderBy(static assembly => assembly.GetName().Name, StringComparer.Ordinal)) - { + foreach (Assembly assembly in exports.Select(static export => export.type.Assembly) + .Distinct() + .OrderBy(static assembly => assembly.GetName().Name, StringComparer.Ordinal) + ) { string path = Path.ChangeExtension(assembly.Location, ".xml"); byte[]? bytes = File.Exists(path) ? File.ReadAllBytes(path) : null; documents.Add(path, bytes); - identity.Append('\n').Append(assembly.GetName().Name).Append(':') + identity.Append('\n') + .Append(assembly.GetName().Name) + .Append(':') .Append(bytes is null ? "missing" : Convert.ToHexStringLower(SHA256.HashData(bytes))); } return new(Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(identity.ToString()))), documents); @@ -40,7 +43,9 @@ internal static void Verify(Inputs inputs) { bool exists = File.Exists(input.Key); if (exists != (input.Value is not null) || exists && !File.ReadAllBytes(input.Key).AsSpan().SequenceEqual(input.Value)) + { throw new IOException("Script API source documentation changed during reference preparation: " + input.Key); + } } } @@ -56,12 +61,14 @@ Inputs inputs var emittedNames = new HashSet(StringComparer.Ordinal); (string source, string target)[] replacements = CreateIdentityReplacements(namespaceMappings, typeMappings); foreach (IGrouping group in exports.GroupBy( - static export => export.type.Assembly)) - { + static export => export.type.Assembly + )) { string documentationPath = Path.ChangeExtension(group.Key.Location, ".xml"); byte[]? bytes = inputs.documents[documentationPath]; if (bytes is null) + { continue; + } using var stream = new MemoryStream(bytes, writable: false); XDocument source = XDocument.Load(stream, LoadOptions.PreserveWhitespace); XElement[] members = source.Root? @@ -78,36 +85,42 @@ Inputs inputs RewriteDocumentationIdentities(copy, replacements); string? name = copy.Attribute("name")?.Value; if (name is not null && emittedNames.Add(name)) + { outputMembers.Add(copy); + } } } } foreach (ScriptApiTypeExport export in exports.Where(export => !string.Equals( - export.name, - GetRuntimeTypeName(export.type), - StringComparison.Ordinal))) - { - ScriptApiTypeMapping mapping = typeMappings.Single(value => + export.name, + GetRuntimeTypeName(export.type), + StringComparison.Ordinal + ))) { + ScriptApiTypeMapping mapping = typeMappings.Single(value => ( string.Equals( value.implementationNamespace, export.type.Namespace ?? string.Empty, - StringComparison.Ordinal) && - string.Equals(value.implementationName, GetRuntimeTypeName(export.type), StringComparison.Ordinal) && - string.Equals(value.apiName, export.name, StringComparison.Ordinal)); + StringComparison.Ordinal + ) + && string.Equals(value.implementationName, GetRuntimeTypeName(export.type), StringComparison.Ordinal) + && string.Equals(value.apiName, export.name, StringComparison.Ordinal) + )); string facadeTypeName = mapping.apiNamespace + "." + mapping.apiName; AddFallbackDocumentation( outputMembers, emittedNames, "T:" + facadeTypeName, - $"Provides the {mapping.apiName} values exposed by the script API."); + $"Provides the {mapping.apiName} values exposed by the script API." + ); foreach (FieldInfo field in export.type.GetFields( - BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)) - { + BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly + )) { AddFallbackDocumentation( outputMembers, emittedNames, "F:" + facadeTypeName + "." + field.Name, - $"Provides the {field.Name} value from {mapping.apiName}."); + $"Provides the {field.Name} value from {mapping.apiName}." + ); } } @@ -118,20 +131,32 @@ Inputs inputs string sourceId = "T:" + GetDocumentationTypeName(export.type); string logicalId = sourceId; foreach ((string sourceName, string targetName) in replacements) + { logicalId = logicalId.Replace(sourceName, targetName, StringComparison.Ordinal); - return new XElement("type", new XAttribute("id", logicalId), + } + return new XElement( + "type", + new XAttribute("id", logicalId), new XAttribute("source", sourceId), - new XAttribute("assembly", export.type.Assembly.GetName().Name - ?? throw new InvalidOperationException("An exported type has no assembly identity."))); + new XAttribute( + "assembly", + export.type.Assembly.GetName().Name + ?? throw new InvalidOperationException("An exported type has no assembly identity.") + ) + ); }).OrderBy(static origin => (string?)origin.Attribute("id"), StringComparer.Ordinal); var document = new XDocument( new XDeclaration("1.0", "utf-8", null), - new XElement("doc", + new XElement( + "doc", new XElement("assembly", new XElement("name", assemblyName)), new XElement("provenance", new XAttribute("format", C_SCHEMA), origins), - new XElement("members", outputMembers.OrderBy( - static member => member.Attribute("name")?.Value, - StringComparer.Ordinal)))); + new XElement( + "members", + outputMembers.OrderBy(static member => member.Attribute("name")?.Value, StringComparer.Ordinal) + ) + ) + ); string temporaryPath = outputPath + ".tmp"; document.Save(temporaryPath); File.Move(temporaryPath, outputPath, overwrite: true); @@ -143,13 +168,15 @@ string typeName ) { string? name = member.Attribute("name")?.Value; if (string.IsNullOrEmpty(name) || name.Length < 3 || name[1] != ':') + { return false; + } ReadOnlySpan declarationName = name.AsSpan(2); return name[0] == 'T' - ? declarationName.Equals(typeName, StringComparison.Ordinal) - : declarationName.Length > typeName.Length && - declarationName[typeName.Length] == '.' && - declarationName.StartsWith(typeName, StringComparison.Ordinal); + ? declarationName.Equals(typeName, StringComparison.Ordinal) + : declarationName.Length > typeName.Length + && declarationName[typeName.Length] == '.' + && declarationName.StartsWith(typeName, StringComparison.Ordinal); } private static string GetDocumentationTypeName(Type type) => (type.FullName ?? type.Name).Replace('+', '.'); @@ -167,11 +194,10 @@ private static void AddFallbackDocumentation( string summary ) { if (!emittedNames.Add(memberName)) + { return; - outputMembers.Add(new XElement( - "member", - new XAttribute("name", memberName), - new XElement("summary", summary))); + } + outputMembers.Add(new XElement("member", new XAttribute("name", memberName), new XElement("summary", summary))); } private static void RewriteDocumentationIdentities( @@ -181,10 +207,14 @@ private static void RewriteDocumentationIdentities( foreach (XAttribute attribute in member.DescendantsAndSelf().Attributes()) { if (attribute.Name.LocalName is not ("name" or "cref")) + { continue; + } string value = attribute.Value; foreach ((string source, string target) in replacements) + { value = value.Replace(source, target, StringComparison.Ordinal); + } attribute.Value = value; } } @@ -197,11 +227,13 @@ IReadOnlyList typeMappings return namespaceMappings .OrderByDescending(static pair => pair.Key.Length) .Select(static pair => (source: pair.Key, target: pair.Value)) - .Concat(typeMappings - .OrderByDescending(static mapping => mapping.apiNamespace.Length + mapping.implementationName.Length) - .Select(static mapping => ( - source: mapping.apiNamespace + "." + mapping.implementationName, - target: mapping.apiNamespace + "." + mapping.apiName))) + .Concat( + typeMappings + .OrderByDescending(static mapping => mapping.apiNamespace.Length + mapping.implementationName.Length) + .Select(static mapping => ( + source: mapping.apiNamespace + "." + mapping.implementationName, + target: mapping.apiNamespace + "." + mapping.apiName)) + ) .Where(static replacement => !string.Equals(replacement.source, replacement.target, StringComparison.Ordinal)) .ToArray(); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs index 5fef33a11..cead48cb3 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs @@ -4,7 +4,6 @@ using System.IO; using System.Linq; using System.Threading; - using Microsoft.CodeAnalysis; namespace Inno.Scripting.Compiler; @@ -28,16 +27,22 @@ CancellationToken cancellationToken foreach (AdditionalText file in additionalFiles) { if (!file.Path.EndsWith(C_FILE_EXTENSION, StringComparison.OrdinalIgnoreCase)) + { continue; + } string text = file.GetText(cancellationToken)?.ToString() ?? string.Empty; using var reader = new StringReader(text); while (reader.ReadLine() is { } line) { if (string.IsNullOrWhiteSpace(line) || line[0] == '#') + { continue; + } string[] parts = line.Split('\t'); if (parts.Length != 2 || string.IsNullOrWhiteSpace(parts[0]) || string.IsNullOrWhiteSpace(parts[1])) + { continue; + } if (!mappings.TryGetValue(parts[0], out HashSet? implementations)) { implementations = new HashSet(StringComparer.Ordinal); @@ -51,7 +56,8 @@ CancellationToken cancellationToken .OrderBy(static pair => pair.Key, StringComparer.Ordinal) .Select(static pair => new ScriptApiNamespaceMap( pair.Key, - pair.Value.OrderBy(static value => value, StringComparer.Ordinal).ToImmutableArray())) + pair.Value.OrderBy(static value => value, StringComparer.Ordinal).ToImmutableArray() + )) .ToImmutableArray(); return new ScriptApiMap(namespaces); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMapBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMapBuilder.cs index 657fa12cd..ae5e78366 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMapBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMapBuilder.cs @@ -12,10 +12,10 @@ internal static string Build(ScriptApiProfile profile) { var source = new StringBuilder("# Script namespace\tImplementation namespace\n"); foreach (ScriptApiNamespaceMapping mapping in profile.namespaceMappings - .Distinct() - .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) - .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal)) - { + .Distinct() + .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) + .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal) + ) { source.Append(mapping.apiNamespace) .Append('\t') .Append(mapping.implementationNamespace) diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs index 31bcfbeca..2d876a588 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs @@ -6,7 +6,6 @@ using System.Security.Cryptography; using System.Text; using System.Threading; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; @@ -60,9 +59,19 @@ CancellationToken cancellationToken .ToArray(); ScriptApiDocumentationBuilder.Inputs documentationInputs = ScriptApiDocumentationBuilder.Capture(allExports); string contractFingerprint = CreateFingerprint(profile); - string fingerprint = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes( - string.Join('|', contractFingerprint, environment.fingerprint, baseReferences?.artifactFingerprint ?? string.Empty, - documentationInputs.identity)))); + string fingerprint = Convert.ToHexStringLower( + SHA256.HashData( + Encoding.UTF8.GetBytes( + string.Join( + '|', + contractFingerprint, + environment.fingerprint, + baseReferences?.artifactFingerprint ?? string.Empty, + documentationInputs.identity + ) + ) + ) + ); string directory = Path.Combine(options.scriptApiDirectory, profile.name, fingerprint); Directory.CreateDirectory(directory); string[] implementationPaths = GetImplementationPaths(profile, environment); @@ -76,11 +85,19 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); string assemblyName = export.assembly.GetName().Name - ?? throw new InvalidOperationException("A script API assembly has no simple name."); + ?? throw new InvalidOperationException("A script API assembly has no simple name."); string referencePath = Path.Combine(runtimeDirectory, assemblyName + ".dll"); if (!File.Exists(referencePath)) + { EmitImplementationReferenceAssembly( - export, referencePath, implementationPaths, exportedTypes, environment, cancellationToken); + export, + referencePath, + implementationPaths, + exportedTypes, + environment, + cancellationToken + ); + } runtimeReferencePaths.Add(referencePath); } @@ -94,7 +111,9 @@ CancellationToken cancellationToken .ToArray(); var ideReferencePaths = new List(); if (baseReferences is not null) + { ideReferencePaths.AddRange(baseReferences.ideReferencePaths); + } if (logicalExports.Length > 0) { string logicalDirectory = Path.Combine(directory, "IDE"); @@ -111,7 +130,8 @@ CancellationToken cancellationToken profile.namespaceMappings, baseReferences?.ideReferencePaths ?? [], environment, - cancellationToken); + cancellationToken + ); } string documentationPath = Path.ChangeExtension(referencePath, ".xml"); if (!File.Exists(documentationPath)) @@ -122,21 +142,21 @@ CancellationToken cancellationToken logicalExports, profile.namespaceMappings, profile.typeMappings, - documentationInputs); + documentationInputs + ); } ideReferencePaths.Add(referencePath); } ScriptApiDocumentationBuilder.Verify(documentationInputs); - ScriptApiArtifactCache.Collect( - options.scriptApiDirectory, - new[] { directory, baseReferences?.cacheDirectory }); + ScriptApiArtifactCache.Collect(options.scriptApiDirectory, new[] { directory, baseReferences?.cacheDirectory }); return new ScriptApiReferenceSet( runtimeReferencePaths, ideReferencePaths, contractFingerprint, fingerprint, environment, - directory); + directory + ); } private static void EmitImplementationReferenceAssembly( @@ -153,20 +173,23 @@ CancellationToken cancellationToken SourceText.From(source, Encoding.UTF8), new CSharpParseOptions(LanguageVersion.CSharp14), $"<{assemblyName}.ScriptApi.g.cs>", - cancellationToken: cancellationToken); + cancellationToken: cancellationToken + ); var references = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (MetadataReference reference in environment.frameworkReferences) { if (!string.IsNullOrWhiteSpace(reference.Display)) + { references[reference.Display!] = reference; + } } foreach (string implementationPath in implementationPaths) { if (string.Equals( - Path.GetFileNameWithoutExtension(implementationPath), - assemblyName, - StringComparison.OrdinalIgnoreCase)) - { + Path.GetFileNameWithoutExtension(implementationPath), + assemblyName, + StringComparison.OrdinalIgnoreCase + )) { continue; } references[implementationPath] = MetadataReference.CreateFromFile(implementationPath); @@ -183,10 +206,16 @@ CancellationToken cancellationToken deterministic: true, concurrentBuild: false, nullableContextOptions: NullableContextOptions.Enable, - metadataImportOptions: MetadataImportOptions.Public)); + metadataImportOptions: MetadataImportOptions.Public + ) + ); EmitReferenceAssembly( - compilation, referencePath, source, - $"Failed to build script API reference assembly '{assemblyName}'.", cancellationToken); + compilation, + referencePath, + source, + $"Failed to build script API reference assembly '{assemblyName}'.", + cancellationToken + ); } private static void EmitLogicalReferenceAssembly( @@ -204,21 +233,27 @@ CancellationToken cancellationToken .ToDictionary( static group => group.Key, static group => group.First().apiNamespace, - StringComparer.Ordinal); + StringComparer.Ordinal + ); string source = ScriptApiStubSourceBuilder.BuildLogical(exports, exportedTypes, mappings); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText( SourceText.From(source, Encoding.UTF8), new CSharpParseOptions(LanguageVersion.CSharp14), $"<{assemblyName}.g.cs>", - cancellationToken: cancellationToken); + cancellationToken: cancellationToken + ); var references = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (MetadataReference reference in environment.frameworkReferences) { if (!string.IsNullOrWhiteSpace(reference.Display)) + { references[reference.Display!] = reference; + } } foreach (string baseReferencePath in baseReferencePaths) + { references[baseReferencePath] = MetadataReference.CreateFromFile(baseReferencePath); + } CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, @@ -231,10 +266,16 @@ CancellationToken cancellationToken deterministic: true, concurrentBuild: false, nullableContextOptions: NullableContextOptions.Enable, - metadataImportOptions: MetadataImportOptions.Public)); + metadataImportOptions: MetadataImportOptions.Public + ) + ); EmitReferenceAssembly( - compilation, referencePath, source, - $"Failed to build logical script API assembly '{assemblyName}'.", cancellationToken); + compilation, + referencePath, + source, + $"Failed to build logical script API assembly '{assemblyName}'.", + cancellationToken + ); } private static void EmitReferenceAssembly( @@ -252,16 +293,19 @@ CancellationToken cancellationToken EmitResult result = compilation.Emit( peStream: stream, options: new EmitOptions(metadataOnly: true, includePrivateMembers: false), - cancellationToken: cancellationToken); + cancellationToken: cancellationToken + ); if (!result.Success) { string errors = string.Join( Environment.NewLine, result.Diagnostics .Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) - .Select(static diagnostic => diagnostic.ToString())); + .Select(static diagnostic => diagnostic.ToString()) + ); throw new InvalidOperationException( - failureMessage + $"{Environment.NewLine}{errors}{Environment.NewLine}{source}"); + failureMessage + $"{Environment.NewLine}{errors}{Environment.NewLine}{source}" + ); } } cancellationToken.ThrowIfCancellationRequested(); @@ -270,7 +314,9 @@ CancellationToken cancellationToken finally { if (File.Exists(temporaryPath)) + { File.Delete(temporaryPath); + } } } @@ -289,7 +335,9 @@ string referencePath finally { if (File.Exists(temporaryPath)) + { File.Delete(temporaryPath); + } } } @@ -306,14 +354,16 @@ ScriptApiDocumentationBuilder.Inputs documentationInputs .ToDictionary( static group => group.Key, static group => group.First().apiNamespace, - StringComparer.Ordinal); + StringComparer.Ordinal + ); ScriptApiDocumentationBuilder.Write( Path.ChangeExtension(referencePath, ".xml"), assemblyName, exports, mappings, typeMappings, - documentationInputs); + documentationInputs + ); } private static string CreateFingerprint(ScriptApiProfile profile) @@ -328,30 +378,32 @@ private static string CreateFingerprint(ScriptApiProfile profile) .Append('|') .Append(profile.name); foreach (ScriptApiAssembly export in profile.exports - .OrderBy(static value => value.assembly.GetName().Name, StringComparer.Ordinal)) - { + .OrderBy(static value => value.assembly.GetName().Name, StringComparer.Ordinal) + ) { builder.Append("|implementation:") .Append(export.assembly.GetName().Name) .Append('|') .Append(ScriptApiStubSourceBuilder.BuildImplementation(export, exportedTypes)); } foreach (string apiNamespace in profile.apiNamespaces.OrderBy(static value => value, StringComparer.Ordinal)) + { builder.Append('|').Append(apiNamespace); + } foreach (ScriptApiNamespaceMapping mapping in profile.namespaceMappings - .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) - .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal)) - { + .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) + .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal) + ) { builder.Append('|') .Append(mapping.apiNamespace) .Append('>') .Append(mapping.implementationNamespace); } foreach (ScriptApiTypeMapping mapping in profile.typeMappings - .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) - .ThenBy(static value => value.apiName, StringComparer.Ordinal) - .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal) - .ThenBy(static value => value.implementationName, StringComparer.Ordinal)) - { + .OrderBy(static value => value.apiNamespace, StringComparer.Ordinal) + .ThenBy(static value => value.apiName, StringComparer.Ordinal) + .ThenBy(static value => value.implementationNamespace, StringComparer.Ordinal) + .ThenBy(static value => value.implementationName, StringComparer.Ordinal) + ) { builder.Append('|') .Append(mapping.apiNamespace) .Append('.') @@ -364,8 +416,8 @@ private static string CreateFingerprint(ScriptApiProfile profile) .Append(mapping.arity); } foreach (ScriptApiAttachableType attachableType in profile.attachableTypes - .OrderBy(static value => value.implementationName, StringComparer.Ordinal)) - { + .OrderBy(static value => value.implementationName, StringComparer.Ordinal) + ) { builder.Append('|') .Append(attachableType.implementationName) .Append('>') @@ -388,5 +440,4 @@ ScriptCompilationEnvironment environment .OrderBy(static path => path, StringComparer.Ordinal) .ToArray(); } - } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs index 2cee33a0e..6740ac176 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Reflection; using System.Text; - using Inno.Scripting.Api; namespace Inno.Scripting.Compiler; @@ -12,11 +11,11 @@ namespace Inno.Scripting.Compiler; internal static class ScriptApiStubSourceBuilder { private const BindingFlags C_DECLARED_MEMBERS = - BindingFlags.Public | - BindingFlags.NonPublic | - BindingFlags.Instance | - BindingFlags.Static | - BindingFlags.DeclaredOnly; + BindingFlags.Public + | BindingFlags.NonPublic + | BindingFlags.Instance + | BindingFlags.Static + | BindingFlags.DeclaredOnly; [ThreadStatic] private static IReadOnlySet? s_exportedTypes; @@ -33,25 +32,25 @@ internal static class ScriptApiStubSourceBuilder internal static string BuildImplementation( ScriptApiAssembly export, IReadOnlySet exportedTypes - ) - => Build( - export.exports.Select(static value => value.type).ToArray(), - exportedTypes, - export.assembly.GetName().Version ?? new Version(1, 0, 0, 0), - namespaceMappings: null, - typeNames: null); + ) => Build( + export.exports.Select(static value => value.type).ToArray(), + exportedTypes, + export.assembly.GetName().Version ?? new Version(1, 0, 0, 0), + namespaceMappings: null, + typeNames: null + ); internal static string BuildLogical( IReadOnlyList exports, IReadOnlySet exportedTypes, IReadOnlyDictionary namespaceMappings - ) - => Build( - exports.Select(static value => value.type).ToArray(), - exportedTypes, - new Version(1, 0, 0, 0), - namespaceMappings, - exports.ToDictionary(static value => value.type, static value => value.name)); + ) => Build( + exports.Select(static value => value.type).ToArray(), + exportedTypes, + new Version(1, 0, 0, 0), + namespaceMappings, + exports.ToDictionary(static value => value.type, static value => value.name) + ); private static string Build( IReadOnlyList types, @@ -112,13 +111,19 @@ Type type if (type.IsClass) { if (type.IsAbstract && type.IsSealed) + { builder.Append("static "); + } else { if (type.IsAbstract) + { builder.Append("abstract "); + } if (type.IsSealed) + { builder.Append("sealed "); + } } builder.Append("class "); } @@ -129,7 +134,9 @@ Type type else { if (type.IsDefined(typeof(System.Runtime.CompilerServices.IsReadOnlyAttribute), inherit: false)) + { builder.Append("readonly "); + } builder.Append("struct "); } AppendNamedType(builder, type); @@ -149,9 +156,11 @@ private static void AppendAttributeUsage( Type type ) { if (!typeof(Attribute).IsAssignableFrom(type)) + { return; + } AttributeUsageAttribute usage = type.GetCustomAttribute(inherit: true) - ?? new AttributeUsageAttribute(AttributeTargets.All); + ?? new AttributeUsageAttribute(AttributeTargets.All); builder.Append("[global::System.AttributeUsage((global::System.AttributeTargets)") .Append(((int)usage.ValidOn).ToString(CultureInfo.InvariantCulture)) .Append(", AllowMultiple = ") @@ -188,7 +197,7 @@ private static void AppendDelegate( Type type ) { MethodInfo invoke = type.GetMethod("Invoke") - ?? throw new InvalidOperationException($"Delegate '{type.FullName}' has no Invoke method."); + ?? throw new InvalidOperationException($"Delegate '{type.FullName}' has no Invoke method."); builder.Append("public delegate ") .Append(FormatParameterType(invoke.ReturnParameter)) .Append(' '); @@ -209,18 +218,26 @@ Type type .Where(static argument => argument.DeclaringMethod is null) .ToArray(); if (arguments.Length == 0) + { return; + } builder.Append('<'); for (int i = 0; i < arguments.Length; i++) { if (i > 0) + { builder.Append(", "); - GenericParameterAttributes variance = arguments[i].GenericParameterAttributes & - GenericParameterAttributes.VarianceMask; + } + GenericParameterAttributes variance = arguments[i].GenericParameterAttributes + & GenericParameterAttributes.VarianceMask; if (variance == GenericParameterAttributes.Covariant) + { builder.Append("out "); + } else if (variance == GenericParameterAttributes.Contravariant) + { builder.Append("in "); + } builder.Append(arguments[i].Name); } builder.Append('>'); @@ -231,25 +248,27 @@ private static void AppendBaseTypes( Type type ) { var baseTypes = new List(); - if (type.IsClass && - !type.IsStaticClass() && - type.BaseType is not null && - type.BaseType != typeof(object) && - IsApiType(type.BaseType)) - { + if (type.IsClass + && !type.IsStaticClass() + && type.BaseType is not null + && type.BaseType != typeof(object) + && IsApiType(type.BaseType) + ) { baseTypes.Add(type.BaseType); } foreach (Type interfaceType in type.GetInterfaces()) { - if ((interfaceType.IsPublic || interfaceType.IsNestedPublic) && - IsApiType(interfaceType) && - CanExposeInterface(type, interfaceType)) - { + if ((interfaceType.IsPublic || interfaceType.IsNestedPublic) + && IsApiType(interfaceType) + && CanExposeInterface(type, interfaceType) + ) { baseTypes.Add(interfaceType); } } if (baseTypes.Count == 0) + { return; + } builder.Append(" : ") .Append(string.Join(", ", baseTypes.Distinct().Select(FormatType))); } @@ -259,7 +278,9 @@ private static bool CanExposeInterface( Type interfaceType ) { if (type.IsInterface) + { return true; + } InterfaceMapping mapping = type.GetInterfaceMap(interfaceType); return mapping.TargetMethods.All(IsVisible); } @@ -273,16 +294,24 @@ IEnumerable genericParameters GenericParameterAttributes attributes = parameter.GenericParameterAttributes; var constraints = new List(); if ((attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0) + { constraints.Add("class"); + } bool isStruct = (attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; if (isStruct) + { constraints.Add("struct"); - constraints.AddRange(parameter - .GetGenericParameterConstraints() - .Where(constraint => constraint != typeof(ValueType)) - .Select(FormatType)); + } + constraints.AddRange( + parameter + .GetGenericParameterConstraints() + .Where(constraint => constraint != typeof(ValueType)) + .Select(FormatType) + ); if (!isStruct && (attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0) + { constraints.Add("new()"); + } if (constraints.Count > 0) { builder.Append(" where ") @@ -300,7 +329,9 @@ Type type foreach (FieldInfo field in type.GetFields(C_DECLARED_MEMBERS)) { if (!IsVisible(field) || field.IsSpecialName) + { continue; + } if (!IsApiType(field.FieldType)) { RejectUnclosedMember(field, field.FieldType); @@ -310,19 +341,27 @@ Type type .Append(GetAccessibility(field)) .Append(' '); if (field.IsLiteral) + { builder.Append("const "); + } else { if (field.IsStatic) + { builder.Append("static "); + } if (field.IsInitOnly) + { builder.Append("readonly "); + } } builder.Append(FormatType(field.FieldType, s_nullability!.Create(field), new(field.GetCustomAttributesData(), field))) .Append(' ') .Append(EscapeIdentifier(field.Name)); if (field.IsLiteral) + { builder.Append(" = ").Append(FormatConstant(field.GetRawConstantValue(), field.FieldType)); + } builder.AppendLine(";"); } } @@ -332,11 +371,15 @@ private static void AppendConstructors( Type type ) { if (type.IsStaticClass() || type.IsInterface) + { return; + } foreach (ConstructorInfo constructor in type.GetConstructors(C_DECLARED_MEMBERS)) { if (!IsVisible(constructor) || type.IsValueType && constructor.GetParameters().Length == 0) + { continue; + } if (!AreApiParameters(constructor.GetParameters())) { RejectUnclosedMember(constructor, constructor.GetParameters().Select(static value => value.ParameterType)); @@ -362,13 +405,17 @@ Type type MethodInfo? setter = IsVisible(property.SetMethod) ? property.SetMethod : null; MethodInfo? representative = MoreVisible(getter, setter); if (representative is null) + { continue; + } if (!IsApiType(property.PropertyType) || !AreApiParameters(property.GetIndexParameters())) { RejectUnclosedMember( property, new[] { property.PropertyType }.Concat( - property.GetIndexParameters().Select(static value => value.ParameterType))); + property.GetIndexParameters().Select(static value => value.ParameterType) + ) + ); continue; } string accessibility = GetAccessibility(representative); @@ -376,7 +423,11 @@ Type type .Append(accessibility) .Append(' '); AppendMethodModifiers(builder, representative, type.IsInterface); - builder.Append(FormatType(property.PropertyType, s_nullability!.Create(property), new(property.GetCustomAttributesData(), property))).Append(' '); + builder + .Append( + FormatType(property.PropertyType, s_nullability!.Create(property), new(property.GetCustomAttributesData(), property)) + ) + .Append(' '); ParameterInfo[] indexParameters = property.GetIndexParameters(); if (indexParameters.Length > 0) { @@ -402,16 +453,24 @@ private static void AppendAccessor( string propertyAccessibility ) { if (method is null) + { return; + } builder.Append(" "); string accessibility = GetAccessibility(method); if (!string.Equals(accessibility, propertyAccessibility, StringComparison.Ordinal)) + { builder.Append(accessibility).Append(' '); + } builder.Append(keyword); if (method.IsAbstract) + { builder.AppendLine(";"); + } else + { builder.AppendLine(" => throw new global::System.NotImplementedException();"); + } } private static void AppendEvents( @@ -422,7 +481,9 @@ Type type { MethodInfo? accessor = MoreVisible(eventInfo.AddMethod, eventInfo.RemoveMethod); if (!IsVisible(accessor)) + { continue; + } if (!IsApiType(eventInfo.EventHandlerType!)) { RejectUnclosedMember(eventInfo, eventInfo.EventHandlerType!); @@ -432,9 +493,17 @@ Type type .Append(GetAccessibility(accessor!)) .Append(' '); if (accessor!.IsStatic) + { builder.Append("static "); + } builder.Append("event ") - .Append(FormatType(eventInfo.EventHandlerType!, s_nullability!.Create(eventInfo), new(eventInfo.GetCustomAttributesData(), eventInfo))) + .Append( + FormatType( + eventInfo.EventHandlerType!, + s_nullability!.Create(eventInfo), + new(eventInfo.GetCustomAttributesData(), eventInfo) + ) + ) .Append(' ') .Append(EscapeIdentifier(eventInfo.Name)) .AppendLine(";"); @@ -447,14 +516,16 @@ Type type ) { foreach (MethodInfo method in type.GetMethods(C_DECLARED_MEMBERS)) { - if (!IsVisible(method) || - method.Name == "Finalize" && method.GetParameters().Length == 0 || - method.Name.Contains('<', StringComparison.Ordinal)) + if (!IsVisible(method) + || method.Name == "Finalize" && method.GetParameters().Length == 0 + || method.Name.Contains('<', StringComparison.Ordinal) + ) { continue; - if (method.IsSpecialName && - method.Name is not "op_Implicit" and not "op_Explicit" && - !TryGetOperator(method.Name, out _)) - { + } + if (method.IsSpecialName + && method.Name is not "op_Implicit" and not "op_Explicit" + && !TryGetOperator(method.Name, out _) + ) { continue; } if (!IsApiMethod(method)) @@ -463,16 +534,23 @@ method.Name is not "op_Implicit" and not "op_Explicit" && method, new[] { method.ReturnType } .Concat(method.GetParameters().Select(static value => value.ParameterType)) - .Concat(method.GetGenericArguments() - .SelectMany(static argument => argument.GetGenericParameterConstraints()))); + .Concat( + method.GetGenericArguments() + .SelectMany(static argument => argument.GetGenericParameterConstraints()) + ) + ); continue; } if (method.IsSpecialName) { if (method.Name is "op_Implicit" or "op_Explicit") + { AppendConversionOperator(builder, method); + } else if (TryGetOperator(method.Name, out string? symbol)) + { AppendOperator(builder, method, symbol!); + } continue; } builder.Append(" ") @@ -484,7 +562,9 @@ method.Name is not "op_Implicit" and not "op_Explicit" && .Append(EscapeIdentifier(method.Name)); Type[] genericArguments = method.GetGenericArguments(); if (genericArguments.Length > 0) + { builder.Append('<').Append(string.Join(", ", genericArguments.Select(static value => value.Name))).Append('>'); + } builder.Append('('); AppendParameters(builder, method.GetParameters()); builder.Append(')'); @@ -531,17 +611,25 @@ bool declaringTypeIsInterface return; } if (declaringTypeIsInterface) + { return; + } if (method.IsAbstract) + { builder.Append("abstract "); + } else if (method.GetBaseDefinition() != method) { if (method.IsFinal) + { builder.Append("sealed "); + } builder.Append("override "); } else if (method.IsVirtual && !method.IsFinal) + { builder.Append("virtual "); + } } private static void AppendMethodBody( @@ -549,9 +637,13 @@ private static void AppendMethodBody( MethodInfo method ) { if (method.IsAbstract) + { builder.AppendLine(";"); + } else + { builder.AppendLine(" => throw new global::System.NotImplementedException();"); + } } private static void AppendParameters( @@ -561,51 +653,71 @@ IReadOnlyList parameters for (int i = 0; i < parameters.Count; i++) { if (i > 0) + { builder.Append(", "); + } ParameterInfo parameter = parameters[i]; AppendFlowAttributes(builder, parameter.GetCustomAttributesData()); if (parameter.IsDefined(typeof(ParamArrayAttribute), inherit: false)) + { builder.Append("params "); + } Type parameterType = parameter.ParameterType; if (parameterType.IsByRef) { if (parameter.IsOut) + { builder.Append("out "); + } else if (parameter.IsIn) + { builder.Append("in "); + } else + { builder.Append("ref "); + } parameterType = parameterType.GetElementType()!; } builder.Append(FormatParameterType(parameter)) .Append(' ') .Append(EscapeIdentifier(parameter.Name ?? "value")); if (parameter.IsOptional) + { builder.Append(" = ").Append(FormatConstant(parameter.DefaultValue, parameterType)); + } } } private static bool IsVisible(MethodBase? method) - => method is not null && - (method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly); + => method is not null + && (method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly); private static bool IsVisible(FieldInfo field) => field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly; private static string GetAccessibility(MethodBase method) { if (method.IsPublic) + { return "public"; + } if (method.IsFamilyOrAssembly) + { return "protected internal"; + } return "protected"; } private static string GetAccessibility(FieldInfo field) { if (field.IsPublic) + { return "public"; + } if (field.IsFamilyOrAssembly) + { return "protected internal"; + } return "protected"; } @@ -614,9 +726,13 @@ private static string GetAccessibility(FieldInfo field) MethodInfo? second ) { if (!IsVisible(first)) + { return IsVisible(second) ? second : null; + } if (!IsVisible(second)) + { return first; + } return VisibilityRank(first!) >= VisibilityRank(second!) ? first : second; } @@ -625,7 +741,11 @@ private static string GetAccessibility(FieldInfo field) private static string FormatType(Type type) => FormatType(type, null); private static string FormatParameterType(ParameterInfo parameter) - => FormatType(parameter.ParameterType, s_nullability!.Create(parameter), new(parameter.GetCustomAttributesData(), parameter.Member)); + => FormatType( + parameter.ParameterType, + s_nullability!.Create(parameter), + new(parameter.GetCustomAttributesData(), parameter.Member) + ); private static void AppendFlowAttributes( StringBuilder builder, @@ -635,21 +755,37 @@ IEnumerable attributes { if (attribute.AttributeType.Namespace == "System.Runtime.CompilerServices" && attribute.AttributeType.Name is "CallerFilePathAttribute" or "CallerLineNumberAttribute" - or "CallerMemberNameAttribute" or "CallerArgumentExpressionAttribute") - { - builder.Append("[global::").Append(attribute.AttributeType.FullName).Append('(') - .Append(string.Join(", ", attribute.ConstructorArguments.Select(static argument => - FormatConstant(argument.Value, argument.ArgumentType)))) + or "CallerMemberNameAttribute" or "CallerArgumentExpressionAttribute" + ) { + builder.Append("[global::") + .Append(attribute.AttributeType.FullName) + .Append('(') + .Append( + string.Join( + ", ", + attribute.ConstructorArguments.Select(static argument => + FormatConstant(argument.Value, argument.ArgumentType)) + ) + ) .Append(")] "); continue; } if (attribute.AttributeType.Namespace != "System.Diagnostics.CodeAnalysis" || attribute.AttributeType.Name is not ("AllowNullAttribute" or "DisallowNullAttribute" - or "MaybeNullAttribute" or "NotNullAttribute" or "NotNullWhenAttribute" - or "MaybeNullWhenAttribute" or "NotNullIfNotNullAttribute" or "DoesNotReturnIfAttribute")) + or "MaybeNullAttribute" or "NotNullAttribute" or "NotNullWhenAttribute" + or "MaybeNullWhenAttribute" or "NotNullIfNotNullAttribute" or "DoesNotReturnIfAttribute") + ) { continue; - builder.Append("[global::").Append(attribute.AttributeType.FullName).Append('(') - .Append(string.Join(", ", attribute.ConstructorArguments.Select(static argument => FormatConstant(argument.Value, argument.ArgumentType)))) + } + builder.Append("[global::") + .Append(attribute.AttributeType.FullName) + .Append('(') + .Append( + string.Join( + ", ", + attribute.ConstructorArguments.Select(static argument => FormatConstant(argument.Value, argument.ArgumentType)) + ) + ) .Append(")] "); } } @@ -670,21 +806,36 @@ private static string FormatType( bool nullable = type.IsGenericParameter ? flag == 2 : nullability?.ReadState == NullabilityState.Nullable; string annotation = !type.IsValueType && nullable ? "?" : string.Empty; if (type.IsArray) - return FormatType(type.GetElementType()!, nullability?.ElementType, annotations) + "[" + new string(',', type.GetArrayRank() - 1) + "]" + annotation; + { + return FormatType(type.GetElementType()!, nullability?.ElementType, annotations) + + "[" + + new string(',', type.GetArrayRank() - 1) + + "]" + + annotation; + } if (type.IsGenericParameter) + { return type.Name + annotation; + } if (C_TYPE_ALIASES.TryGetValue(type, out string? alias)) + { return alias + annotation; + } if (!type.IsGenericType) + { return "global::" + FormatNamedTypeName(type, removeGenericArities: false) + annotation; + } Type definition = type.GetGenericTypeDefinition(); string name = FormatNamedTypeName(definition, removeGenericArities: true); - return "global::" + name + "<" + - string.Join(", ", type.GetGenericArguments().Select(( - argument, - index - ) => - FormatType(argument, nullability?.GenericTypeArguments.ElementAtOrDefault(index), annotations))) + ">" + annotation; + return "global::" + name + "<" + + string.Join( + ", ", + type.GetGenericArguments().Select(( + argument, + index + ) => + FormatType(argument, nullability?.GenericTypeArguments.ElementAtOrDefault(index), annotations)) + ) + ">" + annotation; } private sealed class NullableAnnotations @@ -697,8 +848,9 @@ internal NullableAnnotations( IEnumerable attributes, MemberInfo owner ) { - CustomAttributeData? transform = attributes.FirstOrDefault(static attribute => - attribute.AttributeType.FullName == "System.Runtime.CompilerServices.NullableAttribute"); + CustomAttributeData? transform = attributes.FirstOrDefault(static attribute => ( + attribute.AttributeType.FullName == "System.Runtime.CompilerServices.NullableAttribute" + )); m_flags = transform?.ConstructorArguments[0].Value switch { byte flag => [flag], @@ -707,10 +859,13 @@ MemberInfo owner }; for (MemberInfo? current = owner; current is not null; current = current.DeclaringType) { - CustomAttributeData? context = current.GetCustomAttributesData().FirstOrDefault(static attribute => - attribute.AttributeType.FullName == "System.Runtime.CompilerServices.NullableContextAttribute"); + CustomAttributeData? context = current.GetCustomAttributesData().FirstOrDefault(static attribute => ( + attribute.AttributeType.FullName == "System.Runtime.CompilerServices.NullableContextAttribute" + )); if (context is null) + { continue; + } m_context = (byte)context.ConstructorArguments[0].Value!; break; } @@ -719,7 +874,9 @@ MemberInfo owner internal byte Next(Type type) { if (type.IsValueType && !type.IsGenericType) + { return 0; + } int index = m_index++; return index < m_flags.Length ? m_flags[index] : m_context; } @@ -734,37 +891,41 @@ bool removeGenericArities { string aliasNamespace = ResolveNamespace(implementationNamespace); return string.IsNullOrEmpty(aliasNamespace) - ? typeName - : aliasNamespace + "." + typeName; + ? typeName + : aliasNamespace + "." + typeName; } string fullName = type.FullName ?? type.Name; string relativeName = string.IsNullOrEmpty(implementationNamespace) - ? fullName - : fullName[(implementationNamespace.Length + 1)..]; + ? fullName + : fullName[(implementationNamespace.Length + 1)..]; if (removeGenericArities) + { relativeName = RemoveGenericArities(relativeName); + } relativeName = relativeName.Replace('+', '.'); string targetNamespace = ResolveNamespace(implementationNamespace); return string.IsNullOrEmpty(targetNamespace) - ? relativeName - : targetNamespace + "." + relativeName; + ? relativeName + : targetNamespace + "." + relativeName; } private static string ResolveNamespace(string implementationNamespace) - => s_namespaceMappings is not null && - s_namespaceMappings.TryGetValue(implementationNamespace, out string? apiNamespace) - ? apiNamespace - : implementationNamespace; + => s_namespaceMappings is not null + && s_namespaceMappings.TryGetValue(implementationNamespace, out string? apiNamespace) + ? apiNamespace + : implementationNamespace; private static string GetTypeName(Type type) => s_typeNames is not null && s_typeNames.TryGetValue(type, out string? name) - ? name - : RemoveArity(type.Name); + ? name + : RemoveArity(type.Name); private static bool IsApiMethod(MethodInfo method) { if (!IsApiType(method.ReturnType) || !AreApiParameters(method.GetParameters())) + { return false; + } return method.GetGenericArguments() .SelectMany(static argument => argument.GetGenericParameterConstraints()) .All(IsApiType); @@ -776,15 +937,21 @@ private static bool AreApiParameters(IEnumerable parameters) private static bool IsApiType(Type type) { if (type.IsByRef || type.IsPointer || type.IsArray) + { return IsApiType(type.GetElementType()!); + } if (type.IsGenericParameter) + { return type.GetGenericParameterConstraints().All(IsApiType); + } if (C_TYPE_ALIASES.ContainsKey(type) || type == typeof(void)) + { return true; + } if (type.IsGenericType) { - return IsApiNamedType(type.GetGenericTypeDefinition()) && - type.GetGenericArguments().All(IsApiType); + return IsApiNamedType(type.GetGenericTypeDefinition()) + && type.GetGenericArguments().All(IsApiType); } return IsApiNamedType(type); } @@ -799,18 +966,22 @@ private static void RejectUnclosedMember( IEnumerable dependencies ) { if (member.IsDefined(typeof(ScriptingApiIgnoreAttribute), inherit: false)) + { return; + } string missing = string.Join( ", ", dependencies .SelectMany(GetUnexportedTypes) .Select(static type => type.FullName ?? type.Name) .Distinct(StringComparer.Ordinal) - .OrderBy(static name => name, StringComparer.Ordinal)); + .OrderBy(static name => name, StringComparer.Ordinal) + ); throw new InvalidOperationException( - $"Scripting API member '{member.DeclaringType?.FullName}.{member.Name}' depends on " + - $"unexported type(s): {missing}. Export the dependency or mark the member with " + - $"{nameof(ScriptingApiIgnoreAttribute)}."); + $"Scripting API member '{member.DeclaringType?.FullName}.{member.Name}' depends on " + + $"unexported type(s): {missing}. Export the dependency or mark the member with " + + $"{nameof(ScriptingApiIgnoreAttribute)}." + ); } private static IEnumerable GetUnexportedTypes(Type type) @@ -818,39 +989,55 @@ private static IEnumerable GetUnexportedTypes(Type type) if (type.IsByRef || type.IsPointer || type.IsArray) { foreach (Type missing in GetUnexportedTypes(type.GetElementType()!)) + { yield return missing; + } yield break; } if (type.IsGenericParameter) { foreach (Type constraint in type.GetGenericParameterConstraints()) + { foreach (Type missing in GetUnexportedTypes(constraint)) + { yield return missing; + } + } yield break; } if (C_TYPE_ALIASES.ContainsKey(type) || type == typeof(void)) + { yield break; + } if (type.IsGenericType) { if (!IsApiNamedType(type.GetGenericTypeDefinition())) + { yield return type.GetGenericTypeDefinition(); + } foreach (Type argument in type.GetGenericArguments()) + { foreach (Type missing in GetUnexportedTypes(argument)) + { yield return missing; + } + } yield break; } if (!IsApiNamedType(type)) + { yield return type; + } } private static bool IsApiNamedType(Type type) { Assembly assembly = type.Assembly; string name = assembly.GetName().Name ?? string.Empty; - if (assembly == typeof(object).Assembly || - name.StartsWith("System.", StringComparison.Ordinal) || - name.StartsWith("Microsoft.", StringComparison.Ordinal)) - { + if (assembly == typeof(object).Assembly + || name.StartsWith("System.", StringComparison.Ordinal) + || name.StartsWith("Microsoft.", StringComparison.Ordinal) + ) { return true; } return s_exportedTypes?.Contains(type) == true; @@ -861,13 +1048,12 @@ private static string FormatConstant( Type type ) { if (value is null || value == DBNull.Value || value == Missing.Value) + { return "default"; + } if (type.IsEnum) { - object numeric = Convert.ChangeType( - value, - Enum.GetUnderlyingType(type), - CultureInfo.InvariantCulture); + object numeric = Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture); return "(" + FormatType(type) + ")" + FormatNumericConstant(numeric); } return value switch @@ -937,7 +1123,9 @@ private static string RemoveGenericArities(string value) continue; } while (i + 1 < value.Length && char.IsDigit(value[i + 1])) + { i++; + } } return builder.ToString(); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs index 6df053951..37fd36422 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -13,6 +12,7 @@ internal sealed class ScriptApiUsingRewriter : CSharpSyntaxRewriter private readonly IReadOnlyDictionary m_mappings; private readonly IReadOnlyDictionary m_typeMappings; private readonly IReadOnlyDictionary m_qualifiedTypeMappings; + private IReadOnlyDictionary m_activeSimpleTypeMappings = new Dictionary(StringComparer.Ordinal); @@ -29,7 +29,8 @@ IReadOnlyList typeMappings .Distinct(StringComparer.Ordinal) .OrderBy(static value => value, StringComparer.Ordinal) .ToArray(), - StringComparer.Ordinal); + StringComparer.Ordinal + ); m_typeMappings = typeMappings .Where(static mapping => mapping.arity == 0) .GroupBy(static mapping => mapping.apiNamespace, StringComparer.Ordinal) @@ -40,22 +41,23 @@ IReadOnlyList typeMappings static mapping => ( mapping.apiName, mapping.implementationNamespace, - mapping.implementationName)) + mapping.implementationName) + ) .Select(static mappings => mappings.First()) .OrderBy(static mapping => mapping.apiName, StringComparer.Ordinal) .ToArray(), - StringComparer.Ordinal); + StringComparer.Ordinal + ); m_qualifiedTypeMappings = typeMappings - .GroupBy( - static mapping => mapping.apiNamespace + "." + mapping.apiName, - StringComparer.Ordinal) + .GroupBy(static mapping => mapping.apiNamespace + "." + mapping.apiName, StringComparer.Ordinal) .ToDictionary( static group => group.Key, static group => group .Select(static mapping => mapping.implementationNamespace + "." + mapping.implementationName) .Distinct(StringComparer.Ordinal) .Single(), - StringComparer.Ordinal); + StringComparer.Ordinal + ); } /// @@ -68,9 +70,7 @@ IReadOnlyList typeMappings /// The rewritten compilation unit, or when the base visitor removes it. /// public override SyntaxNode? VisitCompilationUnit(CompilationUnitSyntax node) - => VisitWithUsings( - node.Usings, - () => base.VisitCompilationUnit(node.WithUsings(RewriteUsings(node.Usings)))); + => VisitWithUsings(node.Usings, () => base.VisitCompilationUnit(node.WithUsings(RewriteUsings(node.Usings)))); /// /// Rewrites logical API imports and type expressions declared inside a file-scoped namespace. @@ -84,7 +84,8 @@ IReadOnlyList typeMappings public override SyntaxNode? VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => VisitWithUsings( node.Usings, - () => base.VisitFileScopedNamespaceDeclaration(node.WithUsings(RewriteUsings(node.Usings)))); + () => base.VisitFileScopedNamespaceDeclaration(node.WithUsings(RewriteUsings(node.Usings))) + ); /// /// Rewrites logical API imports and type expressions declared inside a block-scoped namespace. @@ -98,7 +99,8 @@ IReadOnlyList typeMappings public override SyntaxNode? VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => VisitWithUsings( node.Usings, - () => base.VisitNamespaceDeclaration(node.WithUsings(RewriteUsings(node.Usings)))); + () => base.VisitNamespaceDeclaration(node.WithUsings(RewriteUsings(node.Usings))) + ); /// /// Replaces a fully qualified logical API type with its implementation type identity. @@ -112,7 +114,9 @@ IReadOnlyList typeMappings public override SyntaxNode? VisitQualifiedName(QualifiedNameSyntax node) { if (m_qualifiedTypeMappings.TryGetValue(node.ToString(), out string? implementationName)) + { return SyntaxFactory.ParseName(implementationName).WithTriviaFrom(node); + } return base.VisitQualifiedName(node); } @@ -127,16 +131,20 @@ IReadOnlyList typeMappings /// public override SyntaxNode? VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { - if (node.Expression is IdentifierNameSyntax identifier && - m_activeSimpleTypeMappings.TryGetValue(identifier.Identifier.ValueText, out string? simpleType)) - { - return base.VisitMemberAccessExpression(node.WithExpression( - SyntaxFactory.ParseExpression("global::" + simpleType).WithTriviaFrom(node.Expression))); + if (node.Expression is IdentifierNameSyntax identifier + && m_activeSimpleTypeMappings.TryGetValue(identifier.Identifier.ValueText, out string? simpleType) + ) { + return base.VisitMemberAccessExpression( + node.WithExpression( + SyntaxFactory.ParseExpression("global::" + simpleType).WithTriviaFrom(node.Expression) + ) + ); } if (m_qualifiedTypeMappings.TryGetValue(node.Expression.ToString(), out string? implementationName)) { - return base.VisitMemberAccessExpression(node.WithExpression( - SyntaxFactory.ParseExpression(implementationName).WithTriviaFrom(node.Expression))); + return base.VisitMemberAccessExpression( + node.WithExpression(SyntaxFactory.ParseExpression(implementationName).WithTriviaFrom(node.Expression)) + ); } return base.VisitMemberAccessExpression(node); } @@ -166,19 +174,19 @@ IReadOnlyDictionary inherited var ambiguous = new HashSet(StringComparer.Ordinal); foreach (UsingDirectiveSyntax usingDirective in usings) { - if (usingDirective.Alias is not null || - usingDirective.StaticKeyword != default || - usingDirective.Name is null || - !m_typeMappings.TryGetValue(usingDirective.Name.ToString(), out ScriptApiTypeMapping[]? mappings)) - { + if (usingDirective.Alias is not null + || usingDirective.StaticKeyword != default + || usingDirective.Name is null + || !m_typeMappings.TryGetValue(usingDirective.Name.ToString(), out ScriptApiTypeMapping[]? mappings) + ) { continue; } foreach (ScriptApiTypeMapping mapping in mappings) { string implementation = mapping.implementationNamespace + "." + mapping.implementationName; - if (candidates.TryGetValue(mapping.apiName, out string? existing) && - !string.Equals(existing, implementation, StringComparison.Ordinal)) - { + if (candidates.TryGetValue(mapping.apiName, out string? existing) + && !string.Equals(existing, implementation, StringComparison.Ordinal) + ) { ambiguous.Add(mapping.apiName); continue; } @@ -186,7 +194,9 @@ usingDirective.Name is null || } } foreach (string name in ambiguous) + { candidates.Remove(name); + } return candidates; } @@ -195,12 +205,12 @@ private SyntaxList RewriteUsings(SyntaxList(usings.Count); foreach (UsingDirectiveSyntax usingDirective in usings) { - if (usingDirective.Alias is not null || - usingDirective.StaticKeyword != default || - usingDirective.Name is null || - !m_mappings.TryGetValue(usingDirective.Name.ToString(), out string[]? implementations) || - implementations.Length == 0) - { + if (usingDirective.Alias is not null + || usingDirective.StaticKeyword != default + || usingDirective.Name is null + || !m_mappings.TryGetValue(usingDirective.Name.ToString(), out string[]? implementations) + || implementations.Length == 0 + ) { result.Add(usingDirective); continue; } @@ -209,18 +219,26 @@ usingDirective.Name is null || { foreach (ScriptApiTypeMapping alias in aliases) { - result.Add(SyntaxFactory.UsingDirective( - SyntaxFactory.ParseName( - "global::" + alias.implementationNamespace + "." + alias.implementationName)) - .WithAlias(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(alias.apiName)))); + result.Add( + SyntaxFactory + .UsingDirective( + SyntaxFactory.ParseName( + "global::" + alias.implementationNamespace + "." + alias.implementationName + ) + ) + .WithAlias(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(alias.apiName))) + ); } } for (int i = 0; i < implementations.Length; i++) { UsingDirectiveSyntax rewritten = usingDirective.WithName( - SyntaxFactory.ParseName(implementations[i]).WithTriviaFrom(usingDirective.Name)); + SyntaxFactory.ParseName(implementations[i]).WithTriviaFrom(usingDirective.Name) + ); if (i > 0) + { rewritten = rewritten.WithLeadingTrivia(default(SyntaxTriviaList)); + } result.Add(rewritten); } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs index 72b71c6f5..bc371de7b 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs @@ -29,12 +29,16 @@ internal int Collect(IEnumerable protectedDirectories) string assemblyRoot = Path.Combine(m_root, ".assemblies"); IEnumerable candidates = Directory.EnumerateDirectories(m_root); if (Directory.Exists(assemblyRoot)) + { candidates = candidates.Concat(Directory.EnumerateDirectories(assemblyRoot)); + } var discoveredEntries = new List(); foreach (string path in candidates.Where(IsArtifactDirectory)) { if (TryCreateEntry(path, out Entry entry)) + { discoveredEntries.Add(entry); + } } Entry[] entries = discoveredEntries .OrderBy(static entry => entry.lastWriteUtc) @@ -44,9 +48,13 @@ internal int Collect(IEnumerable protectedDirectories) foreach (Entry entry in entries) { if (protectedPaths.Contains(entry.path)) + { continue; + } if (entry.lastWriteUtc > cutoff && totalSize <= C_DEFAULT_MAXIMUM_SIZE) + { continue; + } try { Directory.Delete(entry.path, recursive: true); @@ -72,7 +80,9 @@ private static int CollectStaleStaging( DateTime cutoff ) { if (!Directory.Exists(root)) + { return 0; + } int removed = 0; foreach (string path in Directory.EnumerateDirectories(root)) @@ -80,7 +90,9 @@ DateTime cutoff try { if (Directory.GetLastWriteTimeUtc(path) > cutoff) + { continue; + } Directory.Delete(path, recursive: true); removed++; } @@ -99,8 +111,8 @@ DateTime cutoff private static bool IsArtifactDirectory(string path) { string name = Path.GetFileName(path); - return name.Length == C_BUILD_KEY_LENGTH && - name.All(static character => char.IsAsciiHexDigit(character)); + return name.Length == C_BUILD_KEY_LENGTH + && name.All(static character => char.IsAsciiHexDigit(character)); } private static bool TryCreateEntry( @@ -112,10 +124,7 @@ out Entry entry long size = new DirectoryInfo(path) .EnumerateFiles("*", SearchOption.AllDirectories) .Sum(static file => file.Length); - entry = new Entry( - Path.GetFullPath(path), - Directory.GetLastWriteTimeUtc(path), - size); + entry = new Entry(Path.GetFullPath(path), Directory.GetLastWriteTimeUtc(path), size); return true; } catch (IOException) diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs index c13fe2e59..c9c6fb29a 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Linq; using System.Threading; -using Inno.Scripting.Api; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Inno.Scripting.Api; namespace Inno.Scripting.Compiler; @@ -32,11 +32,14 @@ internal static SyntaxTree[] Erase( ScriptApiProfile api, CancellationToken cancellationToken ) { - Type[] types = api.exports.SelectMany(export => export.assembly + Type[] types = api.exports + .SelectMany(export => export.assembly .GetCustomAttributes(typeof(ScriptingApiExportAttribute), false) .Cast()) .Where(export => export.scope == ScriptingApiScope.Authoring) - .Select(export => export.type).Distinct().ToArray(); + .Select(export => export.type) + .Distinct() + .ToArray(); var names = types.Select(type => type.FullName!).ToHashSet(StringComparer.Ordinal); var namespaces = types.Select(type => type.Namespace!).ToHashSet(StringComparer.Ordinal); return compilation.SyntaxTrees.Select(tree => @@ -88,14 +91,19 @@ CancellationToken cancellationToken ISymbol? symbol = node.Name is null ? null : semanticModel.GetSymbolInfo(node.Name).Symbol; return symbol is INamedTypeSymbol type && IsAnnotation(type) || symbol is INamespaceSymbol ns && annotationNamespaces.Contains(ns.ToDisplayString()) - ? null : base.VisitUsingDirective(node); + ? null + : base.VisitUsingDirective(node); } private bool IsAnnotation(INamedTypeSymbol? type) { for (INamedTypeSymbol? current = type; current is not null; current = current.BaseType) + { if (annotationTypes.Contains(current.ToDisplayString())) + { return true; + } + } return false; } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs index 071093458..18f3e40d5 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using Inno.Extensibility.Modules; namespace Inno.Scripting.Compiler; @@ -28,11 +27,14 @@ internal ScriptCompilationResult( runtimeAssemblyPaths = this.moduleDeployments .SelectMany(static request => new[] { request.mainAssemblyPath }.Concat(request.preloadAssemblyPaths) - .Where(path => request.assemblyScopes.TryGetValue( + .Where(path => ( + request.assemblyScopes.TryGetValue( Path.GetFileNameWithoutExtension(path), - out AssemblyScope scope) + out AssemblyScope scope + ) ? scope == AssemblyScope.Runtime - : request.scope == AssemblyScope.Runtime)) + : request.scope == AssemblyScope.Runtime + ))) .Distinct(StringComparer.OrdinalIgnoreCase) .Order(StringComparer.OrdinalIgnoreCase) .ToArray(); @@ -97,7 +99,8 @@ public static ScriptCompilationResult Failure(ScriptDiagnostic diagnostic) success: false, [diagnostic], outputDirectory: null, - moduleDeployments: null); + moduleDeployments: null + ); } internal IReadOnlyList compiledAssemblies { get; } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationStageTiming.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationStageTiming.cs index a1ddbd1d0..a42f90165 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationStageTiming.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationStageTiming.cs @@ -27,9 +27,13 @@ public ScriptCompilationStageTiming( TimeSpan elapsed ) { if (string.IsNullOrWhiteSpace(stage)) + { throw new ArgumentException("A compilation stage name is required.", nameof(stage)); + } if (elapsed < TimeSpan.Zero) + { throw new ArgumentOutOfRangeException(nameof(elapsed), "Stage duration cannot be negative."); + } this.stage = stage; this.elapsed = elapsed; } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs index dcea597a1..875e17d07 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs @@ -1,8 +1,8 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; using System.IO; using System.Text; +using Inno.Core.Diagnostics; namespace Inno.Scripting.Compiler; @@ -106,7 +106,8 @@ internal static ScriptTypeManifest DecodeTypeManifest(ReadOnlySpan bytes) reader.ReadInt32(), reader.ReadInt32(), reader.ReadBoolean(), - reader.ReadBoolean()); + reader.ReadBoolean() + ); } ValidateEndOfArtifact(stream, "script type manifest cache"); @@ -132,7 +133,9 @@ string fieldName ) { byte[] bytes = reader.ReadBytes(16); if (bytes.Length != 16) + { throw new InvalidDataException($"The script compiler cache truncated its {fieldName}."); + } return new Guid(bytes); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs index 02ef21cff..0ede839c4 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs @@ -9,19 +9,18 @@ using System.Text; using System.Threading; using System.Threading.Tasks; - -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; -using Inno.Extensibility.Modules; -using Inno.Runtime.Generators; -using Inno.Core.IO; -using Inno.Core.Serialization.Generators; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.IO; +using Inno.Core.Serialization.Generators; +using Inno.Extensibility.Modules; +using Inno.Plugins.Authoring; +using Inno.Runtime.Generators; namespace Inno.Scripting.Compiler; @@ -48,16 +47,25 @@ internal static async ValueTask CompileAsync( { throw new ArgumentException( includeEditor - ? "Authoring compilation cannot bind to a Player runtime." - : "Runtime deployment compilation requires a target Player runtime directory.", - nameof(targetRuntimeDirectory)); + ? "Authoring compilation cannot bind to a Player runtime." + : "Runtime deployment compilation requires a target Player runtime directory.", + nameof(targetRuntimeDirectory) + ); } cancellationToken.ThrowIfCancellationRequested(); reportProgress?.Invoke(0f, "Discovering project scripts..."); ScriptSourceSet sources = ScriptSourceSet.Discover(assets, plugins, includeEditor, sourceSnapshot); - return await Task.Run(() => CompileCapturedAsync( - options, sources, includeEditor, targetRuntimeDirectory, reportProgress, cancellationToken).AsTask(), - cancellationToken).ConfigureAwait(false); + return await Task.Run( + () => CompileCapturedAsync( + options, + sources, + includeEditor, + targetRuntimeDirectory, + reportProgress, + cancellationToken + ).AsTask(), + cancellationToken + ).ConfigureAwait(false); } private static async ValueTask CompileCapturedAsync( @@ -70,32 +78,38 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); var progress = new CompilationProgress( - sources.assemblies.Sum(static assembly => assembly.sources.Count) + - sources.assemblies.Count * 6 + - 8, + sources.assemblies.Sum(static assembly => assembly.sources.Count) + + sources.assemblies.Count * 6 + + 8, reportProgress, - initialCompleted: 1); + initialCompleted: 1 + ); progress.Complete("Project scripts discovered."); progress.Begin("Building the script API profile..."); ScriptApiProfile runtimeApi = ScriptApiCatalog.Build(includeEditor: false); ScriptApiProfile? editorApi = includeEditor - ? ScriptApiCatalog.Build(includeEditor: true) - : null; + ? ScriptApiCatalog.Build(includeEditor: true) + : null; progress.Complete("Script API profile built."); progress.Begin("Resolving script references..."); ScriptCompilationEnvironment environment = FrameworkReferenceResolver.Resolve(options.compilationEnvironment, cancellationToken); ScriptApiReferenceSet runtimeApiReferences = ScriptApiReferenceBuilder.Build( - options, runtimeApi, environment, cancellationToken: cancellationToken); + options, + runtimeApi, + environment, + cancellationToken: cancellationToken + ); ScriptApiReferenceSet? editorApiReferences = editorApi is null - ? null - : ScriptApiReferenceBuilder.Build( - options, - editorApi, - environment, - runtimeApi, - runtimeApiReferences, - cancellationToken); + ? null + : ScriptApiReferenceBuilder.Build( + options, + editorApi, + environment, + runtimeApi, + runtimeApiReferences, + cancellationToken + ); progress.Complete("Script references resolved."); ScriptDeploymentReferenceSet? deploymentReferences = null; if (!includeEditor) @@ -108,25 +122,19 @@ CancellationToken cancellationToken foreach (ScriptAssemblyInput assembly in sources.assemblies) { ScriptApiReferenceSet api = assembly.scope == ScriptAssemblyScope.Editor - ? editorApiReferences ?? throw new InvalidOperationException( - "A runtime deployment cannot contain an editor script assembly.") - : runtimeApiReferences; + ? editorApiReferences ?? throw new InvalidOperationException( + "A runtime deployment cannot contain an editor script assembly." + ) + : runtimeApiReferences; IReadOnlyList defines = GetCompilationDefines(assembly, includeEditor, environment.inputs.predefinedSymbols); assemblyKeys.Add( assembly.name, - ComputeAssemblyBuildKey( - assembly, - api, - deploymentReferences?.fingerprint, - assemblyKeys, - defines)); + ComputeAssemblyBuildKey(assembly, api, deploymentReferences?.fingerprint, assemblyKeys, defines) + ); } string buildKey = ComputeGenerationBuildKey(sources, assemblyKeys); string outputDirectory = Path.Combine(options.outputDirectory, buildKey); - if (TryCreateCachedResult( - outputDirectory, - sources, - out ScriptCompilationResult? cachedResult)) + if (TryCreateCachedResult(outputDirectory, sources, out ScriptCompilationResult? cachedResult)) { progress.Complete("Reused cached script assembly artifact."); return new ScriptCompilationResult( @@ -136,7 +144,8 @@ CancellationToken cancellationToken cachedResult.moduleDeployments, compiledAssemblies: [], reusedAssemblies: sources.assemblies.Select(static assembly => assembly.name).ToArray(), - stageTimings: progress.Snapshot()); + stageTimings: progress.Snapshot() + ); } IReadOnlyList platformReferences = environment.frameworkReferences; @@ -155,24 +164,27 @@ CancellationToken cancellationToken { bool editor = assembly.scope == ScriptAssemblyScope.Editor; ScriptApiProfile api = editor - ? editorApi ?? throw new InvalidOperationException( - "A runtime deployment cannot contain an editor script assembly.") - : runtimeApi; + ? editorApi ?? throw new InvalidOperationException( + "A runtime deployment cannot contain an editor script assembly." + ) + : runtimeApi; ScriptApiReferenceSet apiReferences = editor - ? editorApiReferences ?? throw new InvalidOperationException( - "A runtime deployment cannot contain editor API references.") - : runtimeApiReferences; + ? editorApiReferences ?? throw new InvalidOperationException( + "A runtime deployment cannot contain editor API references." + ) + : runtimeApiReferences; string assemblyPath = Path.Combine(stagingDirectory, assembly.name + ".dll"); string assemblyCacheDirectory = Path.Combine( options.outputDirectory, ".assemblies", - assemblyKeys[assembly.name]); + assemblyKeys[assembly.name] + ); if (TryCopyCachedAssembly( - assemblyCacheDirectory, - assembly.name, - stagingDirectory, - out ScriptDiagnostic[] cachedDiagnostics)) - { + assemblyCacheDirectory, + assembly.name, + stagingDirectory, + out ScriptDiagnostic[] cachedDiagnostics + )) { diagnostics.AddRange(cachedDiagnostics); compiledPaths.Add(assembly.name, assemblyPath); reusedAssemblies.Add(assembly.name); @@ -198,13 +210,14 @@ CancellationToken cancellationToken assembly.scope, assembly.domain, string.IsNullOrEmpty(assembly.ownerPluginId) - ? AssetSourceId.project.value - : assembly.ownerPluginId, + ? AssetSourceId.project.value + : assembly.ownerPluginId, GetCompilationDefines(assembly, includeEditor, environment.inputs.predefinedSymbols), assembly.nullable, assembly.allowUnsafe, progress, - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); diagnostics.AddRange(result.diagnostics); if (!result.success) { @@ -215,21 +228,15 @@ CancellationToken cancellationToken diagnostics, outputDirectory: null, moduleDeployments: null, - stageTimings: progress.Snapshot()); + stageTimings: progress.Snapshot() + ); } File.WriteAllBytes( GetDiagnosticsPath(assemblyStagingDirectory), - ScriptCompilerCacheSerialization.EncodeDiagnostics(result.diagnostics)); - CommitAssemblyCache( - assemblyStagingDirectory, - assemblyCacheDirectory, - assembly.name, - cancellationToken); - if (!TryCopyCachedAssembly( - assemblyCacheDirectory, - assembly.name, - stagingDirectory, - out _)) + ScriptCompilerCacheSerialization.EncodeDiagnostics(result.diagnostics) + ); + CommitAssemblyCache(assemblyStagingDirectory, assemblyCacheDirectory, assembly.name, cancellationToken); + if (!TryCopyCachedAssembly(assemblyCacheDirectory, assembly.name, stagingDirectory, out _)) { DeleteStagingDirectory(stagingDirectory); throw new IOException($"Committed script assembly cache '{assembly.name}' is incomplete."); @@ -240,13 +247,12 @@ CancellationToken cancellationToken File.WriteAllBytes( GetDiagnosticsPath(stagingDirectory), - ScriptCompilerCacheSerialization.EncodeDiagnostics(diagnostics)); + ScriptCompilerCacheSerialization.EncodeDiagnostics(diagnostics) + ); CommitGenerationCache(stagingDirectory, outputDirectory, sources, cancellationToken); progress.Begin("Preparing the script reload..."); - IReadOnlyList requests = CreateModuleDeployments( - outputDirectory, - sources); + IReadOnlyList requests = CreateModuleDeployments(outputDirectory, sources); progress.Complete("Script reload prepared."); return new ScriptCompilationResult( true, @@ -255,7 +261,8 @@ CancellationToken cancellationToken requests, compiledAssemblies, reusedAssemblies, - progress.Snapshot()); + progress.Snapshot() + ); } private static async ValueTask CompileAssemblyAsync( @@ -282,7 +289,8 @@ CancellationToken cancellationToken preprocessorSymbols: defines .Concat(["DEBUG", "TRACE"]) .Distinct(StringComparer.Ordinal) - .OrderBy(static value => value, StringComparer.Ordinal)); + .OrderBy(static value => value, StringComparer.Ordinal) + ); var syntaxTrees = new List(sources.Count + 1); for (int sourceIndex = 0; sourceIndex < sources.Count; sourceIndex++) { @@ -290,35 +298,42 @@ CancellationToken cancellationToken progress.Begin($"Parsing {assemblyName} sources ({sourceIndex + 1}/{sources.Count})..."); cancellationToken.ThrowIfCancellationRequested(); string source = sourceInput.snapshotSource; - syntaxTrees.Add(CSharpSyntaxTree.ParseText( - SourceText.From(source, Encoding.UTF8), - parseOptions, - sourceInput.sourcePath, - cancellationToken)); + syntaxTrees.Add( + CSharpSyntaxTree.ParseText( + SourceText.From(source, Encoding.UTF8), + parseOptions, + sourceInput.sourcePath, + cancellationToken + ) + ); progress.Complete($"Parsed {assemblyName} source {sourceIndex + 1}/{sources.Count}."); } progress.Begin($"Preparing generated {assemblyName} sources..."); - syntaxTrees.Add(CSharpSyntaxTree.ParseText( - SourceText.From( - CreateGeneratedSource( - assemblyName, - scope == ScriptAssemblyScope.Editor, - domain, - assetSourceId), - Encoding.UTF8), - parseOptions, - $"<{assemblyName}.Generated.g.cs>", - cancellationToken)); + syntaxTrees.Add( + CSharpSyntaxTree.ParseText( + SourceText.From( + CreateGeneratedSource(assemblyName, scope == ScriptAssemblyScope.Editor, domain, assetSourceId), + Encoding.UTF8 + ), + parseOptions, + $"<{assemblyName}.Generated.g.cs>", + cancellationToken + ) + ); progress.Complete($"Prepared generated {assemblyName} sources."); var validationReferences = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (MetadataReference reference in platformReferences) { if (!string.IsNullOrWhiteSpace(reference.Display)) + { validationReferences[reference.Display!] = reference; + } } foreach (string referencePath in apiReferences.runtimeReferencePaths) + { validationReferences[referencePath] = MetadataReference.CreateFromFile(referencePath); + } var validationCompilation = CSharpCompilation.Create( assemblyName, @@ -332,13 +347,19 @@ CancellationToken cancellationToken deterministic: true, concurrentBuild: false, sourceReferenceResolver: new SourceFileResolver( - [], Environment.CurrentDirectory, ScriptSourceLocations.CreatePathMap(sources)), + [], + Environment.CurrentDirectory, + ScriptSourceLocations.CreatePathMap(sources) + ), nullableContextOptions: nullable - ? NullableContextOptions.Enable - : NullableContextOptions.Disable)); + ? NullableContextOptions.Enable + : NullableContextOptions.Disable + ) + ); var apiMapFile = new InMemoryAdditionalText( assemblyName + ScriptApiMapBuilder.C_FILE_EXTENSION, - ScriptApiMapBuilder.Build(api)); + ScriptApiMapBuilder.Build(api) + ); var analyzerOptions = new AnalyzerOptions(ImmutableArray.Create(apiMapFile)); var analyzers = ImmutableArray.Create(new LogicalScriptingApiAnalyzer()); progress.Begin($"Validating the {assemblyName} API surface..."); @@ -354,33 +375,51 @@ CancellationToken cancellationToken analyzerDiagnostics .Where(static diagnostic => diagnostic.Severity != DiagnosticSeverity.Hidden) .Select(ToDiagnostic) - .ToArray()); + .ToArray() + ); } var usingRewriter = new ScriptApiUsingRewriter(api.namespaceMappings, api.typeMappings); var propertyOrderRewriter = new SerializablePropertyOrderRewriter(); var logicalReferences = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (MetadataReference reference in platformReferences) + { if (!string.IsNullOrWhiteSpace(reference.Display)) + { logicalReferences[reference.Display!] = reference; + } + } foreach (string referencePath in apiReferences.ideReferencePaths) + { logicalReferences[referencePath] = MetadataReference.CreateFromFile(referencePath); + } var logicalBindings = CSharpCompilation.Create(assemblyName, syntaxTrees, logicalReferences.Values, validationCompilation.Options); SyntaxTree[] runtimeTrees = syntaxTrees .Select(tree => CSharpSyntaxTree.Create( (CSharpSyntaxNode)usingRewriter.Visit( - propertyOrderRewriter.Visit(new ScriptStaticMemberRewriter(logicalBindings.GetSemanticModel(tree)) - .Visit(tree.GetRoot(cancellationToken))))!, + propertyOrderRewriter.Visit( + new ScriptStaticMemberRewriter(logicalBindings.GetSemanticModel(tree)) + .Visit(tree.GetRoot(cancellationToken)) + ) + )!, parseOptions, tree.FilePath, - Encoding.UTF8)) + Encoding.UTF8 + )) .ToArray(); var contractCompilation = CSharpCompilation.Create( - assemblyName, runtimeTrees, validationReferences.Values, validationCompilation.Options); + assemblyName, + runtimeTrees, + validationReferences.Values, + validationCompilation.Options + ); Diagnostic[] contractErrors = contractCompilation.GetDiagnostics(cancellationToken) - .Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error).ToArray(); + .Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .ToArray(); if (contractErrors.Length > 0) + { return new CompilationResult(false, contractErrors.Select(ToDiagnostic).ToArray()); + } IReadOnlyCollection runtimeReferences; if (deploymentReferences is null) @@ -388,9 +427,13 @@ CancellationToken cancellationToken // User code has passed the same trimmed contract used by IDE projects. // Generated registration alone needs the owning assemblies' implementation metadata. var implementationReferences = platformReferences.ToDictionary( - static reference => reference.Display!, StringComparer.OrdinalIgnoreCase); + static reference => reference.Display!, + StringComparer.OrdinalIgnoreCase + ); foreach (string path in ScriptApiReferenceBuilder.GetImplementationPaths(api, apiReferences.environment)) + { implementationReferences[path] = MetadataReference.CreateFromFile(path); + } runtimeReferences = implementationReferences.Values; } else @@ -400,17 +443,22 @@ CancellationToken cancellationToken foreach (MetadataReference reference in platformReferences) { if (!string.IsNullOrWhiteSpace(reference.Display)) + { targetReferences[reference.Display!] = reference; + } } foreach (string referencePath in deploymentReferences.paths) + { targetReferences[referencePath] = MetadataReference.CreateFromFile(referencePath); + } runtimeReferences = targetReferences.Values; } var runtimeCompilation = CSharpCompilation.Create( assemblyName, runtimeTrees, runtimeReferences, - validationCompilation.Options); + validationCompilation.Options + ); progress.Begin($"Resolving {assemblyName} script type identities..."); ScriptTypeAnalysisResult typeAnalysis = ScriptTypeAnalyzer.Analyze( runtimeCompilation, @@ -418,31 +466,41 @@ CancellationToken cancellationToken api.attachableTypes.ToDictionary( static value => value.implementationName, static value => value.kind, - StringComparer.Ordinal), - cancellationToken); + StringComparer.Ordinal + ), + cancellationToken + ); if (typeAnalysis.mappings.Count > 0) { SyntaxTree mappingTree = CSharpSyntaxTree.ParseText( - SourceText.From( - ScriptTypeAnalyzer.CreateMappingSource(typeAnalysis.mappings), - Encoding.UTF8), + SourceText.From(ScriptTypeAnalyzer.CreateMappingSource(typeAnalysis.mappings), Encoding.UTF8), parseOptions, $"<{assemblyName}.ScriptTypeIds.g.cs>", - cancellationToken); + cancellationToken + ); runtimeCompilation = runtimeCompilation.AddSyntaxTrees(mappingTree); } progress.Complete($"Resolved {assemblyName} script type identities."); - if (typeAnalysis.diagnostics.Any(static diagnostic => - diagnostic.severity == Inno.Core.Diagnostics.DiagnosticSeverity.Error)) - { + if (typeAnalysis.diagnostics.Any(static diagnostic => ( + diagnostic.severity == Inno.Core.Diagnostics.DiagnosticSeverity.Error + )) + ) { return new CompilationResult(false, typeAnalysis.diagnostics); } GeneratorDriver registration = CSharpGeneratorDriver.Create( - [new RuntimeModuleCatalogGenerator().AsSourceGenerator(), - new SerializationConverterGenerator().AsSourceGenerator(), new SerializationMetadataGenerator().AsSourceGenerator()], - parseOptions: parseOptions); - registration.RunGeneratorsAndUpdateCompilation(runtimeCompilation, out Compilation registeredCompilation, - out ImmutableArray registrationDiagnostics, cancellationToken); + [ + new RuntimeModuleCatalogGenerator().AsSourceGenerator(), + new SerializationConverterGenerator().AsSourceGenerator(), + new SerializationMetadataGenerator().AsSourceGenerator() + ], + parseOptions: parseOptions + ); + registration.RunGeneratorsAndUpdateCompilation( + runtimeCompilation, + out Compilation registeredCompilation, + out ImmutableArray registrationDiagnostics, + cancellationToken + ); runtimeCompilation = (CSharpCompilation)registeredCompilation; progress.Begin($"Checking {assemblyName} compilation diagnostics..."); Diagnostic[] preEmitDiagnostics = runtimeCompilation @@ -459,7 +517,8 @@ [new RuntimeModuleCatalogGenerator().AsSourceGenerator(), false, typeAnalysis.diagnostics .Concat(preEmitDiagnostics.Select(ToDiagnostic)) - .ToArray()); + .ToArray() + ); } string pdbPath = Path.ChangeExtension(outputPath, ".pdb"); @@ -473,21 +532,25 @@ [new RuntimeModuleCatalogGenerator().AsSourceGenerator(), pdbStream, xmlDocumentationStream: documentationStream, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), - cancellationToken: cancellationToken); + cancellationToken: cancellationToken + ); if (emit.Success) { await File.WriteAllBytesAsync( GetTypeManifestPath(outputPath), ScriptCompilerCacheSerialization.EncodeTypeManifest(typeAnalysis.manifest), - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); } progress.Complete($"Emitted {assemblyName}."); ScriptDiagnostic[] diagnostics = typeAnalysis.diagnostics - .Concat(preEmitDiagnostics - .Concat(emit.Diagnostics) - .Where(static diagnostic => diagnostic.Severity != DiagnosticSeverity.Hidden) - .Distinct(DiagnosticComparer.Instance) - .Select(ToDiagnostic)) + .Concat( + preEmitDiagnostics + .Concat(emit.Diagnostics) + .Where(static diagnostic => diagnostic.Severity != DiagnosticSeverity.Hidden) + .Distinct(DiagnosticComparer.Instance) + .Select(ToDiagnostic) + ) .ToArray(); return new CompilationResult(emit.Success, diagnostics); } @@ -535,7 +598,9 @@ internal IReadOnlyList Snapshot() private void FinishCurrentStage() { if (m_stage is null) + { return; + } m_stageStopwatch.Stop(); m_timings.Add(new ScriptCompilationStageTiming(m_stage, m_stageStopwatch.Elapsed)); m_stage = null; @@ -564,7 +629,9 @@ IReadOnlyList defines AppendHash(hash, assembly.nullable.ToString()); AppendHash(hash, assembly.allowUnsafe.ToString()); foreach (string define in defines.OrderBy(static value => value, StringComparer.Ordinal)) + { AppendHash(hash, define); + } foreach (ScriptSourceInput source in assembly.sources.OrderBy(static value => value.relativePath, StringComparer.Ordinal)) { AppendHash(hash, source.relativePath); @@ -588,12 +655,12 @@ IReadOnlyList predefinedSymbols ) { ArgumentNullException.ThrowIfNull(assembly); return includeEditor - ? assembly.defines.Concat(predefinedSymbols) - .Append(C_EDITOR_COMPILATION_SYMBOL) - .Distinct(StringComparer.Ordinal) - .OrderBy(static value => value, StringComparer.Ordinal) - .ToArray() - : assembly.defines.Concat(predefinedSymbols).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + ? assembly.defines.Concat(predefinedSymbols) + .Append(C_EDITOR_COMPILATION_SYMBOL) + .Distinct(StringComparer.Ordinal) + .OrderBy(static value => value, StringComparer.Ordinal) + .ToArray() + : assembly.defines.Concat(predefinedSymbols).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); } private static string ComputeGenerationBuildKey( @@ -627,18 +694,20 @@ out ScriptDiagnostic[] diagnostics ]; string diagnosticsPath = GetDiagnosticsPath(cacheDirectory); if (!IsCachedAssemblyComplete(cacheDirectory, assemblyName)) + { return false; + } try { - diagnostics = ScriptCompilerCacheSerialization.DecodeDiagnostics( - File.ReadAllBytes(diagnosticsPath)); + diagnostics = ScriptCompilerCacheSerialization.DecodeDiagnostics(File.ReadAllBytes(diagnosticsPath)); Directory.CreateDirectory(destinationDirectory); for (int i = 0; i < sourcePaths.Length; i++) { File.Copy( sourcePaths[i], Path.Combine(destinationDirectory, Path.GetFileName(sourcePaths[i])), - overwrite: true); + overwrite: true + ); } TryTouchCacheDirectory(cacheDirectory); return true; @@ -686,35 +755,36 @@ private static bool IsCachedAssemblyComplete( string assemblyName ) { string assemblyPath = Path.Combine(cacheDirectory, assemblyName + ".dll"); - if (!File.Exists(assemblyPath) || - !File.Exists(Path.ChangeExtension(assemblyPath, ".pdb")) || - !File.Exists(Path.ChangeExtension(assemblyPath, ".xml")) || - !File.Exists(GetTypeManifestPath(assemblyPath)) || - !File.Exists(GetDiagnosticsPath(cacheDirectory))) - { + if (!File.Exists(assemblyPath) + || !File.Exists(Path.ChangeExtension(assemblyPath, ".pdb")) + || !File.Exists(Path.ChangeExtension(assemblyPath, ".xml")) + || !File.Exists(GetTypeManifestPath(assemblyPath)) + || !File.Exists(GetDiagnosticsPath(cacheDirectory)) + ) { return false; } try { if (!HasExpectedAssemblyIdentity(assemblyPath, assemblyName)) + { return false; + } _ = ScriptCompilerCacheSerialization.DecodeDiagnostics( - File.ReadAllBytes(GetDiagnosticsPath(cacheDirectory))); + File.ReadAllBytes(GetDiagnosticsPath(cacheDirectory)) + ); ScriptTypeManifest manifest = ScriptCompilerCacheSerialization.DecodeTypeManifest( - File.ReadAllBytes(GetTypeManifestPath(assemblyPath))); - if (!string.Equals( - manifest.assemblyName, - assemblyName, - StringComparison.Ordinal)) + File.ReadAllBytes(GetTypeManifestPath(assemblyPath)) + ); + if (!string.Equals(manifest.assemblyName, assemblyName, StringComparison.Ordinal)) { return false; } return true; } catch (Exception exception) when (exception is - InvalidOperationException or - IOException or - BadImageFormatException) + InvalidOperationException + or IOException + or BadImageFormatException) { return false; } @@ -752,12 +822,13 @@ out ScriptCompilationResult? result result = null; string diagnosticsPath = GetDiagnosticsPath(outputDirectory); if (!File.Exists(diagnosticsPath)) + { return false; + } ScriptDiagnostic[] diagnostics; try { - diagnostics = ScriptCompilerCacheSerialization.DecodeDiagnostics( - File.ReadAllBytes(diagnosticsPath)); + diagnostics = ScriptCompilerCacheSerialization.DecodeDiagnostics(File.ReadAllBytes(diagnosticsPath)); } catch (InvalidOperationException) { @@ -770,15 +841,16 @@ out ScriptCompilationResult? result foreach (ScriptAssemblyInput assembly in sources.assemblies) { if (!IsCachedAssemblyComplete(outputDirectory, assembly.name)) + { return false; + } } result = new ScriptCompilationResult( success: true, diagnostics: diagnostics, outputDirectory: outputDirectory, - moduleDeployments: CreateModuleDeployments( - outputDirectory, - sources)); + moduleDeployments: CreateModuleDeployments(outputDirectory, sources) + ); TryTouchCacheDirectory(outputDirectory); return true; } @@ -788,7 +860,9 @@ private static void DeleteStagingDirectory(string path) try { if (Directory.Exists(path)) + { Directory.Delete(path, recursive: true); + } } catch (IOException) { @@ -888,18 +962,16 @@ ScriptSourceSet sources Dictionary pluginModules = pluginAssemblies .Select(static assembly => assembly.ownerPluginId) .Distinct(StringComparer.Ordinal) - .ToDictionary( - static pluginId => pluginId, - static pluginId => "Plugin." + pluginId, - StringComparer.Ordinal); + .ToDictionary(static pluginId => pluginId, static pluginId => "Plugin." + pluginId, StringComparer.Ordinal); Dictionary assembliesByName = sources.assemblies.ToDictionary( static assembly => assembly.name, - StringComparer.OrdinalIgnoreCase); + StringComparer.OrdinalIgnoreCase + ); var requests = new List(); foreach (IGrouping group in pluginAssemblies - .GroupBy(static assembly => assembly.ownerPluginId, StringComparer.Ordinal) - .OrderBy(static group => group.Key, StringComparer.Ordinal)) - { + .GroupBy(static assembly => assembly.ownerPluginId, StringComparer.Ordinal) + .OrderBy(static group => group.Key, StringComparer.Ordinal) + ) { ScriptAssemblyInput[] owned = group .OrderBy(static assembly => assembly.scope) .ThenBy(static assembly => assembly.name, StringComparer.Ordinal) @@ -908,36 +980,48 @@ ScriptSourceSet sources string[] dependencies = owned .SelectMany(static assembly => assembly.references) .Select(reference => assembliesByName[reference].ownerPluginId) - .Where(owner => !string.IsNullOrEmpty(owner) && - !string.Equals(owner, group.Key, StringComparison.Ordinal)) + .Where(owner => ( + !string.IsNullOrEmpty(owner) + && !string.Equals(owner, group.Key, StringComparison.Ordinal) + )) .Distinct(StringComparer.Ordinal) .OrderBy(static value => value, StringComparer.Ordinal) .Select(owner => pluginModules[owner]) .ToArray(); - requests.Add(new ScriptModuleDeployment( - pluginModules[group.Key], - AssemblyPath(main.name), - AssemblyDomain.InnoPlugin, - main.scope == ScriptAssemblyScope.Editor ? AssemblyScope.Editor : AssemblyScope.Runtime, - owned - .Where(assembly => !ReferenceEquals(assembly, main)) - .Select(assembly => AssemblyPath(assembly.name)) - .ToArray(), - dependencies, - owned.ToDictionary( - static assembly => assembly.name, - static assembly => assembly.scope == ScriptAssemblyScope.Editor - ? AssemblyScope.Editor - : AssemblyScope.Runtime, - StringComparer.OrdinalIgnoreCase))); + requests.Add( + new ScriptModuleDeployment( + pluginModules[group.Key], + AssemblyPath(main.name), + AssemblyDomain.InnoPlugin, + main.scope == ScriptAssemblyScope.Editor ? AssemblyScope.Editor : AssemblyScope.Runtime, + owned + .Where(assembly => !ReferenceEquals(assembly, main)) + .Select(assembly => AssemblyPath(assembly.name)) + .ToArray(), + dependencies, + owned.ToDictionary( + static assembly => assembly.name, + static assembly => ( + assembly.scope == ScriptAssemblyScope.Editor + ? AssemblyScope.Editor + : AssemblyScope.Runtime + ), + StringComparer.OrdinalIgnoreCase + ) + ) + ); } ScriptAssemblyInput[] runtimeAssemblies = sources.assemblies - .Where(static assembly => assembly.domain == AssemblyDomain.InnoScripting - && assembly.scope == ScriptAssemblyScope.Runtime) + .Where(static assembly => ( + assembly.domain == AssemblyDomain.InnoScripting + && assembly.scope == ScriptAssemblyScope.Runtime + )) .ToArray(); ScriptAssemblyInput[] editorAssemblies = sources.assemblies - .Where(static assembly => assembly.domain == AssemblyDomain.InnoScripting - && assembly.scope == ScriptAssemblyScope.Editor) + .Where(static assembly => ( + assembly.domain == AssemblyDomain.InnoScripting + && assembly.scope == ScriptAssemblyScope.Editor + )) .ToArray(); string[] pluginModuleNames = pluginModules.Values .OrderBy(static value => value, StringComparer.Ordinal) @@ -952,7 +1036,9 @@ ScriptSourceSet sources .Where(static assembly => assembly.name != C_GAME_ASSEMBLY_NAME) .Select(assembly => AssemblyPath(assembly.name)) .ToArray(), - pluginModuleNames)); + pluginModuleNames + ) + ); if (sources.includesEditor) { requests.Add( @@ -969,7 +1055,10 @@ ScriptSourceSet sources editorAssemblies.ToDictionary( static assembly => assembly.name, static _ => AssemblyScope.Editor, - StringComparer.OrdinalIgnoreCase))); + StringComparer.OrdinalIgnoreCase + ) + ) + ); } return requests; } @@ -988,7 +1077,8 @@ private static ScriptDiagnostic ToDiagnostic(Diagnostic diagnostic) diagnostic.GetMessage(), string.IsNullOrWhiteSpace(location.Path) ? null : location.Path, location.IsValid ? location.StartLinePosition.Line + 1 : 0, - location.IsValid ? location.StartLinePosition.Character + 1 : 0); + location.IsValid ? location.StartLinePosition.Character + 1 : 0 + ); } private sealed record CompilationResult( @@ -1046,15 +1136,19 @@ public bool Equals( Diagnostic? right ) { if (ReferenceEquals(left, right)) + { return true; + } if (left is null || right is null) + { return false; + } FileLinePositionSpan leftLocation = left.Location.GetLineSpan(); FileLinePositionSpan rightLocation = right.Location.GetLineSpan(); - return string.Equals(left.Id, right.Id, StringComparison.Ordinal) && - string.Equals(left.GetMessage(), right.GetMessage(), StringComparison.Ordinal) && - string.Equals(leftLocation.Path, rightLocation.Path, StringComparison.Ordinal) && - leftLocation.StartLinePosition.Equals(rightLocation.StartLinePosition); + return string.Equals(left.Id, right.Id, StringComparison.Ordinal) + && string.Equals(left.GetMessage(), right.GetMessage(), StringComparison.Ordinal) + && string.Equals(leftLocation.Path, rightLocation.Path, StringComparison.Ordinal) + && leftLocation.StartLinePosition.Equals(rightLocation.StartLinePosition); } /// @@ -1069,11 +1163,7 @@ public bool Equals( public int GetHashCode(Diagnostic diagnostic) { FileLinePositionSpan location = diagnostic.Location.GetLineSpan(); - return HashCode.Combine( - diagnostic.Id, - diagnostic.GetMessage(), - location.Path, - location.StartLinePosition); + return HashCode.Combine(diagnostic.Id, diagnostic.GetMessage(), location.Path, location.StartLinePosition); } } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs index 7dd0a495e..d1dc0854b 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs @@ -22,7 +22,8 @@ internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) if (!Directory.Exists(normalizedDirectory)) { throw new DirectoryNotFoundException( - $"The target Player runtime directory '{normalizedDirectory}' does not exist."); + $"The target Player runtime directory '{normalizedDirectory}' does not exist." + ); } string[] paths = Directory @@ -32,7 +33,8 @@ internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) if (paths.Length == 0) { throw new InvalidDataException( - $"The target Player runtime directory '{normalizedDirectory}' contains no Inno runtime assemblies."); + $"The target Player runtime directory '{normalizedDirectory}' contains no Inno runtime assemblies." + ); } var identities = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -49,16 +51,19 @@ internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) { throw new InvalidDataException( $"Target Player runtime assembly '{Path.GetFileName(path)}' is not valid managed metadata.", - exception); + exception + ); } string simpleName = identity.Name - ?? throw new InvalidDataException( - $"Target Player runtime assembly '{Path.GetFileName(path)}' has no assembly identity."); + ?? throw new InvalidDataException( + $"Target Player runtime assembly '{Path.GetFileName(path)}' has no assembly identity." + ); if (!identities.Add(simpleName)) { throw new InvalidDataException( - $"The target Player runtime contains more than one '{simpleName}' assembly identity."); + $"The target Player runtime contains more than one '{simpleName}' assembly identity." + ); } Append(fingerprint, Path.GetFileName(path)); @@ -66,9 +71,7 @@ internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) fingerprint.AppendData(SHA256.HashData(stream)); } - return new ScriptDeploymentReferenceSet( - paths, - Convert.ToHexString(fingerprint.GetHashAndReset())); + return new ScriptDeploymentReferenceSet(paths, Convert.ToHexString(fingerprint.GetHashAndReset())); } private static void Append( diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDiagnostic.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDiagnostic.cs index 74200ca70..abb55b93d 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDiagnostic.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDiagnostic.cs @@ -1,4 +1,5 @@ using Inno.Core.Diagnostics; + namespace Inno.Scripting.Compiler; /// diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptIdePluginReferenceBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptIdePluginReferenceBuilder.cs index 3a267ce3b..2227b14b7 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptIdePluginReferenceBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptIdePluginReferenceBuilder.cs @@ -4,12 +4,11 @@ using System.Linq; using System.Security.Cryptography; using System.Text; - -using Inno.Extensibility.Modules; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; +using Inno.Extensibility.Modules; namespace Inno.Scripting.Compiler; @@ -26,16 +25,21 @@ ScriptApiReferenceSet editorApi foreach (ScriptAssemblyInput assembly in sources.assemblies) { if (assembly.domain != AssemblyDomain.InnoPlugin) + { continue; + } ScriptApiReferenceSet api = assembly.scope == ScriptAssemblyScope.Editor - ? editorApi - : runtimeApi; + ? editorApi + : runtimeApi; string[] dependencies = assembly.references - .Select(name => results.TryGetValue(name, out string? path) + .Select(name => ( + results.TryGetValue(name, out string? path) ? path : throw new InvalidDataException( - $"IDE Plugin dependency '{name}' for '{assembly.name}' is unavailable.")) + $"IDE Plugin dependency '{name}' for '{assembly.name}' is unavailable." + ) + )) .ToArray(); string fingerprint = CreateFingerprint(assembly, api, dependencies); string directory = Path.Combine(root, fingerprint); @@ -55,17 +59,20 @@ private static string CreateFingerprint( ScriptApiReferenceSet api, IReadOnlyList dependencies ) { - string input = string.Join('\n', new[] - { - assembly.name, - assembly.definitionHash, - api.artifactFingerprint, - assembly.scope.ToString(), - assembly.nullable.ToString(), - assembly.allowUnsafe.ToString() - }.Concat(assembly.defines) - .Concat(assembly.sources.Select(static source => source.contentHash)) - .Concat(dependencies)); + string input = string.Join( + '\n', + new[] + { + assembly.name, + assembly.definitionHash, + api.artifactFingerprint, + assembly.scope.ToString(), + assembly.nullable.ToString(), + assembly.allowUnsafe.ToString() + }.Concat(assembly.defines) + .Concat(assembly.sources.Select(static source => source.contentHash)) + .Concat(dependencies) + ); return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(input))); } @@ -84,12 +91,14 @@ string outputPath LanguageVersion.CSharp14, DocumentationMode.Parse, SourceCodeKind.Regular, - preprocessorSymbols: symbols); + preprocessorSymbols: symbols + ); SyntaxTree[] trees = assembly.sources.Select(source => CSharpSyntaxTree.ParseText( SourceText.From(source.snapshotSource, Encoding.UTF8), parseOptions, - source.sourcePath)).ToArray(); + source.sourcePath + )).ToArray(); IEnumerable references = api.environment.frameworkReferences .Concat(api.ideReferencePaths.Select(static path => MetadataReference.CreateFromFile(path))) .Concat(dependencies.Select(static path => MetadataReference.CreateFromFile(path))); @@ -103,8 +112,10 @@ string outputPath allowUnsafe: assembly.allowUnsafe, deterministic: true, nullableContextOptions: assembly.nullable - ? NullableContextOptions.Enable - : NullableContextOptions.Disable)); + ? NullableContextOptions.Enable + : NullableContextOptions.Disable + ) + ); string temporaryPath = outputPath + ".tmp-" + Guid.NewGuid().ToString("N"); try { @@ -112,15 +123,19 @@ string outputPath { EmitResult result = compilation.Emit( stream, - options: new EmitOptions(metadataOnly: true, includePrivateMembers: false)); + options: new EmitOptions(metadataOnly: true, includePrivateMembers: false) + ); if (!result.Success) { - string errors = string.Join(Environment.NewLine, + string errors = string.Join( + Environment.NewLine, result.Diagnostics .Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) - .Select(static diagnostic => diagnostic.ToString())); + .Select(static diagnostic => diagnostic.ToString()) + ); throw new InvalidDataException( - $"Failed to generate IDE Plugin reference '{assembly.name}':{Environment.NewLine}{errors}"); + $"Failed to generate IDE Plugin reference '{assembly.name}':{Environment.NewLine}{errors}" + ); } } try @@ -135,7 +150,9 @@ string outputPath finally { if (File.Exists(temporaryPath)) + { File.Delete(temporaryPath); + } } } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptModuleDeployment.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptModuleDeployment.cs index fe1e5ab5a..64680b9e6 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptModuleDeployment.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptModuleDeployment.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; - using Inno.Extensibility.Modules; namespace Inno.Scripting.Compiler; @@ -30,8 +29,9 @@ internal ScriptModuleDeployment( this.upstreamModuleNames = Array.AsReadOnly(upstreamModuleNames.ToArray()); this.assemblyScopes = new ReadOnlyDictionary( assemblyScopes is null - ? new Dictionary(StringComparer.OrdinalIgnoreCase) - : new Dictionary(assemblyScopes, StringComparer.OrdinalIgnoreCase)); + ? new Dictionary(StringComparer.OrdinalIgnoreCase) + : new Dictionary(assemblyScopes, StringComparer.OrdinalIgnoreCase) + ); } /// diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptProjectGenerator.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptProjectGenerator.cs index d81f4b087..3259219c3 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptProjectGenerator.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptProjectGenerator.cs @@ -7,14 +7,15 @@ using System.Xml.Linq; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; using Inno.Extensibility.Modules; +using Inno.Plugins.Authoring; namespace Inno.Scripting.Compiler; internal static class ScriptProjectGenerator { private const string C_EDITOR_COMPILATION_SYMBOL = "INNO_EDITOR"; + private static readonly IReadOnlyList C_IDE_CONTENT_FILE_EXTENSIONS = [ ".ishadersource" @@ -40,9 +41,14 @@ PluginEnvironment plugins editorApi, environment, runtimeApi, - runtimeApiReferences); + runtimeApiReferences + ); IReadOnlyDictionary pluginReferences = ScriptIdePluginReferenceBuilder.Build( - options, sources, runtimeApiReferences, editorApiReferences); + options, + sources, + runtimeApiReferences, + editorApiReferences + ); string apiMapDirectory = Path.Combine(options.ideDirectory, "ScriptApiMaps"); Directory.CreateDirectory(apiMapDirectory); string codeAnalysisPath = CopyCodeAnalysisAssembly(options.ideDirectory); @@ -51,40 +57,39 @@ PluginEnvironment plugins bool editor = assembly.scope == ScriptAssemblyScope.Editor; ScriptApiProfile api = editor ? editorApi : runtimeApi; ScriptApiReferenceSet references = editor ? editorApiReferences : runtimeApiReferences; - string apiMapPath = Path.Combine( - apiMapDirectory, - assembly.name + ScriptApiMapBuilder.C_FILE_EXTENSION); + string apiMapPath = Path.Combine(apiMapDirectory, assembly.name + ScriptApiMapBuilder.C_FILE_EXTENSION); File.WriteAllText(apiMapPath, ScriptApiMapBuilder.Build(api)); CreateProject( - assembly.name, - ToProjectRelativePaths( - options, - assembly.sources.Select(static source => source.sourcePath).ToArray()), - api, - references, - ResolvePluginReferences(sources, assembly, pluginReferences), - apiMapPath, - codeAnalysisPath, - assembly.references - .Where(reference => userAssemblies.Any(candidate => string.Equals( - candidate.name, - reference, - StringComparison.OrdinalIgnoreCase))) - .Select(static reference => reference + ".csproj") - .ToArray(), - assembly.defines - .Concat(editor ? [C_EDITOR_COMPILATION_SYMBOL] : []) - .Distinct(StringComparer.Ordinal) - .OrderBy(static value => value, StringComparer.Ordinal) - .ToArray(), - assembly.nullable, - assembly.allowUnsafe, - ScriptSourceLocations.CreateProjectPathMap(assembly.sources)) + assembly.name, + ToProjectRelativePaths(options, assembly.sources.Select(static source => source.sourcePath).ToArray()), + api, + references, + ResolvePluginReferences(sources, assembly, pluginReferences), + apiMapPath, + codeAnalysisPath, + assembly.references + .Where(reference => userAssemblies.Any(candidate => string.Equals( + candidate.name, + reference, + StringComparison.OrdinalIgnoreCase + ))) + .Select(static reference => reference + ".csproj") + .ToArray(), + assembly.defines + .Concat(editor ? [C_EDITOR_COMPILATION_SYMBOL] : []) + .Distinct(StringComparer.Ordinal) + .OrderBy(static value => value, StringComparer.Ordinal) + .ToArray(), + assembly.nullable, + assembly.allowUnsafe, + ScriptSourceLocations.CreateProjectPathMap(assembly.sources) + ) .Save(Path.Combine(options.projectRootDirectory, assembly.name + ".csproj")); } File.WriteAllText( Path.Combine(options.projectRootDirectory, "InnoProject.sln"), - CreateSolution(userAssemblies)); + CreateSolution(userAssemblies) + ); } private static string[] ResolvePluginReferences( @@ -94,7 +99,8 @@ IReadOnlyDictionary pluginReferences ) { IReadOnlyDictionary assemblies = sources.assemblies.ToDictionary( static assembly => assembly.name, - StringComparer.OrdinalIgnoreCase); + StringComparer.OrdinalIgnoreCase + ); var pending = new Queue(userAssembly.references); var visited = new HashSet(StringComparer.OrdinalIgnoreCase); var references = new List(); @@ -102,13 +108,21 @@ IReadOnlyDictionary pluginReferences { string name = pending.Dequeue(); if (!visited.Add(name) || !assemblies.TryGetValue(name, out ScriptAssemblyInput? dependency)) + { continue; + } foreach (string transitiveReference in dependency.references) + { pending.Enqueue(transitiveReference); + } if (dependency.domain != AssemblyDomain.InnoPlugin) + { continue; + } if (!pluginReferences.TryGetValue(dependency.name, out string? path)) + { throw new InvalidDataException($"IDE Plugin reference '{dependency.name}' was not generated."); + } references.Add(path); } return references @@ -120,20 +134,22 @@ IReadOnlyDictionary pluginReferences private static void RemoveStalePluginProjectionFiles(ScriptCompilerOptions options) { foreach (string path in Directory.EnumerateFiles( - options.projectRootDirectory, - "Inno.Plugin.*.csproj", - SearchOption.TopDirectoryOnly)) - { + options.projectRootDirectory, + "Inno.Plugin.*.csproj", + SearchOption.TopDirectoryOnly + )) { File.Delete(path); } string apiMapDirectory = Path.Combine(options.ideDirectory, "ScriptApiMaps"); if (!Directory.Exists(apiMapDirectory)) + { return; + } foreach (string path in Directory.EnumerateFiles( - apiMapDirectory, - "Inno.Plugin.*" + ScriptApiMapBuilder.C_FILE_EXTENSION, - SearchOption.TopDirectoryOnly)) - { + apiMapDirectory, + "Inno.Plugin.*" + ScriptApiMapBuilder.C_FILE_EXTENSION, + SearchOption.TopDirectoryOnly + )) { File.Delete(path); } } @@ -162,15 +178,21 @@ private static XDocument CreateProject( bool allowUnsafe, string sourcePathMap ) { - string frozenDefines = string.Join(";", defines.Concat(apiReferences.environment.inputs.predefinedSymbols).Distinct(StringComparer.Ordinal)); - var earlyPropertyGroup = new XElement("PropertyGroup", + string frozenDefines = string.Join( + ";", + defines.Concat(apiReferences.environment.inputs.predefinedSymbols).Distinct(StringComparer.Ordinal) + ); + var earlyPropertyGroup = new XElement( + "PropertyGroup", new XElement("ImportDirectoryBuildProps", "false"), new XElement("ImportDirectoryBuildTargets", "false"), new XElement("BaseOutputPath", "Library/IDE/bin/" + assemblyName + "/"), new XElement("BaseIntermediateOutputPath", "Library/IDE/obj/" + assemblyName + "/"), new XElement("MSBuildProjectExtensionsPath", "Library/IDE/obj/" + assemblyName + "/"), - new XElement("RestoreOutputPath", "Library/IDE/obj/" + assemblyName + "/")); - var propertyGroup = new XElement("PropertyGroup", + new XElement("RestoreOutputPath", "Library/IDE/obj/" + assemblyName + "/") + ); + var propertyGroup = new XElement( + "PropertyGroup", new XElement("TargetFramework", ScriptCompilationEnvironment.C_TARGET_FRAMEWORK), new XElement("AssemblyName", assemblyName), new XElement("DefaultItemExcludes", "$(DefaultItemExcludes);Library/**"), @@ -185,100 +207,138 @@ string sourcePathMap new XElement("NoStdLib", "true"), new XElement("DefineConstants", frozenDefines), new XElement("PathMap", sourcePathMap), - new XElement("LangVersion", ScriptCompilationEnvironment.C_LANGUAGE_VERSION)); + new XElement("LangVersion", ScriptCompilationEnvironment.C_LANGUAGE_VERSION) + ); var compileGroup = new XElement( "ItemGroup", - sourcePaths.Select(static path => - new XElement("Compile", new XAttribute("Include", path)))); + sourcePaths.Select(static path => new XElement("Compile", new XAttribute("Include", path))) + ); var contentGroup = new XElement( "ItemGroup", C_IDE_CONTENT_FILE_EXTENSIONS.Select(static extension => - new XElement("None", new XAttribute("Include", $"Assets/**/*{extension}")))); + new XElement("None", new XAttribute("Include", $"Assets/**/*{extension}"))) + ); var referenceGroup = new XElement("ItemGroup"); foreach (string path in apiReferences.ideReferencePaths.Concat(apiReferences.environment.inputs.frameworkReferences)) + { AddReference(referenceGroup, path); + } foreach (string path in plugins - .Distinct(StringComparer.OrdinalIgnoreCase) - .OrderBy(static value => value, StringComparer.Ordinal)) - { + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(static value => value, StringComparer.Ordinal) + ) { AddReference(referenceGroup, path); } - var folderGroup = new XElement("ItemGroup", - new XElement("Folder", new XAttribute("Include", "Assets/"))); - var codeAnalysisGroup = new XElement("ItemGroup", - new XElement("Analyzer", - new XAttribute("Include", codeAnalysisPath), - new XElement("Visible", "false")), - new XElement("AdditionalFiles", - new XAttribute("Include", apiMapPath), - new XElement("Visible", "false"))); - var project = new XElement("Project", + var folderGroup = new XElement("ItemGroup", new XElement("Folder", new XAttribute("Include", "Assets/"))); + var codeAnalysisGroup = new XElement( + "ItemGroup", + new XElement("Analyzer", new XAttribute("Include", codeAnalysisPath), new XElement("Visible", "false")), + new XElement("AdditionalFiles", new XAttribute("Include", apiMapPath), new XElement("Visible", "false")) + ); + var project = new XElement( + "Project", earlyPropertyGroup, - new XElement("Import", - new XAttribute("Project", "Sdk.props"), - new XAttribute("Sdk", "Microsoft.NET.Sdk")), + new XElement("Import", new XAttribute("Project", "Sdk.props"), new XAttribute("Sdk", "Microsoft.NET.Sdk")), propertyGroup, compileGroup, contentGroup, referenceGroup, - codeAnalysisGroup); - project.Add(new XElement("Target", new XAttribute("Name", "ValidateInnoScriptSdk"), - new XAttribute("BeforeTargets", "ResolveReferences"), - new XElement("Error", new XAttribute("Condition", "'$(NETCoreSdkVersion)' != '" + apiReferences.environment.inputs.sdkIdentity + "'"), - new XAttribute("Text", "The IDE selected a different SDK from the active script compilation. Regenerate project files with the intended SDK selection.")))); + codeAnalysisGroup + ); + project.Add( + new XElement( + "Target", + new XAttribute("Name", "ValidateInnoScriptSdk"), + new XAttribute("BeforeTargets", "ResolveReferences"), + new XElement( + "Error", + new XAttribute( + "Condition", + "'$(NETCoreSdkVersion)' != '" + apiReferences.environment.inputs.sdkIdentity + "'" + ), + new XAttribute( + "Text", + "The IDE selected a different SDK from the active script compilation. Regenerate project files with the intended SDK selection." + ) + ) + ) + ); XElement validation = project.Elements("Target").Single(); foreach ((string property, string expected) in new[] { ("TargetFramework", ScriptCompilationEnvironment.C_TARGET_FRAMEWORK), ("LangVersion", ScriptCompilationEnvironment.C_LANGUAGE_VERSION), - ("ImplicitUsings", "disable"), ("DisableImplicitFrameworkReferences", "true"), - ("DisableImplicitFrameworkDefines", "true"), ("NoStdLib", "true"), + ("ImplicitUsings", "disable"), + ("DisableImplicitFrameworkReferences", "true"), + ("DisableImplicitFrameworkDefines", "true"), + ("NoStdLib", "true"), ("DisableImplicitConfigurationDefines", "true"), - ("Nullable", nullable ? "enable" : "disable"), ("AllowUnsafeBlocks", allowUnsafe ? "true" : "false"), + ("Nullable", nullable ? "enable" : "disable"), + ("AllowUnsafeBlocks", allowUnsafe ? "true" : "false"), ("DefineConstants", frozenDefines) - }) - { + }) { string condition = property == "DefineConstants" - ? "$([System.String]::CompareOrdinal('$(DefineConstants)', '" + expected + "')) != 0" - : "'$(" + property + ")' != '" + expected + "'"; - validation.Add(new XElement("Error", new XAttribute("Condition", condition), - new XAttribute("Text", "The IDE compiler input '" + property + "' differs from the active script contract. Actual: '$(" + property + ")'. Expected: '" + expected + "'. Regenerate project files instead of overriding derived compiler inputs."))); + ? "$([System.String]::CompareOrdinal('$(DefineConstants)', '" + expected + "')) != 0" + : "'$(" + property + ")' != '" + expected + "'"; + validation.Add( + new XElement( + "Error", + new XAttribute("Condition", condition), + new XAttribute( + "Text", + "The IDE compiler input '" + + property + + "' differs from the active script contract. Actual: '$(" + + property + + ")'. Expected: '" + + expected + + "'. Regenerate project files instead of overriding derived compiler inputs." + ) + ) + ); } project.Add(folderGroup); if (projectReferences.Count > 0) { - project.Add(new XElement("ItemGroup", - projectReferences.Select(static reference => - new XElement("ProjectReference", new XAttribute("Include", reference))))); + project.Add( + new XElement( + "ItemGroup", + projectReferences.Select(static reference => + new XElement("ProjectReference", new XAttribute("Include", reference))) + ) + ); } - project.Add(new XElement("Import", - new XAttribute("Project", "Sdk.targets"), - new XAttribute("Sdk", "Microsoft.NET.Sdk"))); + project.Add( + new XElement("Import", new XAttribute("Project", "Sdk.targets"), new XAttribute("Sdk", "Microsoft.NET.Sdk")) + ); return new XDocument(project); } private static string[] ToProjectRelativePaths( ScriptCompilerOptions options, IReadOnlyList absolutePaths - ) - => absolutePaths - .Select(path => Path.GetRelativePath(options.projectRootDirectory, path).Replace('\\', '/')) - .OrderBy(static path => path, StringComparer.Ordinal) - .ToArray(); + ) => absolutePaths + .Select(path => Path.GetRelativePath(options.projectRootDirectory, path).Replace('\\', '/')) + .OrderBy(static path => path, StringComparer.Ordinal) + .ToArray(); private static void AddReference( XElement group, string path ) { - var reference = new XElement("Reference", + var reference = new XElement( + "Reference", new XAttribute("Include", Path.GetFileNameWithoutExtension(path)), new XElement("HintPath", path), - new XElement("Private", "false")); + new XElement("Private", "false") + ); string documentationPath = Path.ChangeExtension(path, ".xml"); if (File.Exists(documentationPath)) + { reference.Add(new XElement("DocumentationFile", documentationPath)); + } group.Add(reference); } @@ -293,8 +353,9 @@ private static string CreateSolution(IReadOnlyList assembli { string id = FormatProjectId(assembly.name); builder.AppendLine( - $"Project(\"{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}\") = " + - $"\"{assembly.name}\", \"{assembly.name}.csproj\", \"{id}\""); + $"Project(\"{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}\") = " + + $"\"{assembly.name}\", \"{assembly.name}.csproj\", \"{id}\"" + ); builder.AppendLine("EndProject"); } builder.AppendLine("Global"); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceLocations.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceLocations.cs index b368aa366..82bc70db7 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceLocations.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceLocations.cs @@ -9,10 +9,12 @@ namespace Inno.Scripting.Compiler; internal static class ScriptSourceLocations { internal static ImmutableArray> CreatePathMap(IReadOnlyList sources) - => sources.Select(static source => new KeyValuePair( + => sources + .Select(static source => new KeyValuePair( Path.GetDirectoryName(source.sourcePath)!, source.assetPath.source.value + "::./" - + (Path.GetDirectoryName(source.assetPath.localPath) ?? string.Empty).Replace('\\', '/'))) + + (Path.GetDirectoryName(source.assetPath.localPath) ?? string.Empty).Replace('\\', '/') + )) .Distinct() .OrderByDescending(static mapping => mapping.Key.Length) .ThenBy(static mapping => mapping.Key, StringComparer.Ordinal) @@ -20,8 +22,12 @@ internal static ImmutableArray> CreatePathMap(IRead internal static string CreateProjectPathMap(IReadOnlyList sources) { - string value = string.Join(",", CreatePathMap(sources).Select(static mapping => - EscapeSeparators(mapping.Key) + "=" + EscapeSeparators(mapping.Value))); + string value = string.Join( + ",", + CreatePathMap(sources).Select(static mapping => ( + EscapeSeparators(mapping.Key) + "=" + EscapeSeparators(mapping.Value) + )) + ); return value.Replace("%", "%25", StringComparison.Ordinal) .Replace("$", "%24", StringComparison.Ordinal) .Replace("@", "%40", StringComparison.Ordinal) diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs index 7472867e8..059b4deee 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs @@ -3,12 +3,11 @@ using System.IO; using System.Linq; using System.Text; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; -using Inno.Extensibility.Modules; using Inno.Core.Collections; +using Inno.Extensibility.Modules; +using Inno.Plugins.Authoring; namespace Inno.Scripting.Compiler; @@ -31,19 +30,23 @@ internal static ScriptSourceSet Discover( ArgumentNullException.ThrowIfNull(assets); ArgumentNullException.ThrowIfNull(plugins); if (!assets.isInitialized) + { throw new InvalidOperationException("Script discovery requires the Asset Database."); + } IAssetSourceSnapshot? candidateAssets = sourceSnapshot ?? plugins.compilationAssets; AssetFileEntry[] entries = (candidateAssets?.GetFileSystemEntries(includeDirectories: false) - ?? assets.GetFileSystemEntries(includeDirectories: false)) + ?? assets.GetFileSystemEntries(includeDirectories: false)) .Where(entry => includeEditor || !entry.isSampleContent) .Where(entry => includeEditor || !AssetSample.IsRuntimeExcluded(entry.assetPath, isDirectory: false)) .OrderBy(static entry => entry.assetPath.source.value, StringComparer.Ordinal) .ThenBy(static entry => entry.assetPath.localPath, StringComparer.Ordinal) .ToArray(); ScriptAssemblyDefinition[] explicitDefinitions = entries - .Where(static entry => !entry.isSampleContent && - string.Equals(entry.extension, ".iasmdef", StringComparison.OrdinalIgnoreCase)) + .Where(static entry => ( + !entry.isSampleContent + && string.Equals(entry.extension, ".iasmdef", StringComparison.OrdinalIgnoreCase) + )) .Select(entry => ParseDefinition(entry, candidateAssets, assets)) .OrderBy(static definition => definition.source.value, StringComparer.Ordinal) .ThenBy(static definition => definition.directory, StringComparer.Ordinal) @@ -51,17 +54,21 @@ internal static ScriptSourceSet Discover( var builders = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (ScriptAssemblyDefinition definition in explicitDefinitions) + { AddBuilder(builders, definition); + } if (builders.ContainsKey(C_GAME_ASSEMBLY_NAME) || builders.ContainsKey(C_EDITOR_ASSEMBLY_NAME)) { throw new InvalidDataException( - $"Assembly definitions cannot use the reserved {C_GAME_ASSEMBLY_NAME} or {C_EDITOR_ASSEMBLY_NAME} names."); + $"Assembly definitions cannot use the reserved {C_GAME_ASSEMBLY_NAME} or {C_EDITOR_ASSEMBLY_NAME} names." + ); } PluginCandidate[] codePlugins = plugins.compilationPlugins - .Where(candidate => entries.Any(entry => + .Where(candidate => entries.Any(entry => ( entry.assetPath.source == candidate.sourceMount.id - && string.Equals(entry.extension, ".cs", StringComparison.OrdinalIgnoreCase))) + && string.Equals(entry.extension, ".cs", StringComparison.OrdinalIgnoreCase) + ))) .ToArray(); ValidateManifestDefinitions(entries, explicitDefinitions, codePlugins); @@ -71,68 +78,98 @@ internal static ScriptSourceSet Discover( string runtimeName = CreatePluginAssemblyName(plugin.manifest.pluginId); string editorName = runtimeName + ".Editor"; string samplesName = runtimeName + ".Samples"; - pluginDefaultNames.Add(plugin.manifest.pluginId, - new PluginDefaultNames(runtimeName, editorName, samplesName)); - AddBuilder(builders, CreateDefaultDefinition( - runtimeName, - plugin.sourceMount.id, - ScriptAssemblyScope.Runtime, - AssemblyDomain.InnoPlugin, + pluginDefaultNames.Add( plugin.manifest.pluginId, - "plugin-default-runtime")); - AddBuilder(builders, CreateDefaultDefinition( - editorName, - plugin.sourceMount.id, - ScriptAssemblyScope.Editor, - AssemblyDomain.InnoPlugin, - plugin.manifest.pluginId, - "plugin-default-editor")); - if (includeEditor) - AddBuilder(builders, CreateDefaultDefinition( - samplesName, + new PluginDefaultNames(runtimeName, editorName, samplesName) + ); + AddBuilder( + builders, + CreateDefaultDefinition( + runtimeName, + plugin.sourceMount.id, + ScriptAssemblyScope.Runtime, + AssemblyDomain.InnoPlugin, + plugin.manifest.pluginId, + "plugin-default-runtime" + ) + ); + AddBuilder( + builders, + CreateDefaultDefinition( + editorName, plugin.sourceMount.id, ScriptAssemblyScope.Editor, AssemblyDomain.InnoPlugin, plugin.manifest.pluginId, - "plugin-authoring-samples")); + "plugin-default-editor" + ) + ); + if (includeEditor) + { + AddBuilder( + builders, + CreateDefaultDefinition( + samplesName, + plugin.sourceMount.id, + ScriptAssemblyScope.Editor, + AssemblyDomain.InnoPlugin, + plugin.manifest.pluginId, + "plugin-authoring-samples" + ) + ); + } } - AddBuilder(builders, CreateDefaultDefinition( - C_GAME_ASSEMBLY_NAME, - AssetSourceId.project, - ScriptAssemblyScope.Runtime, - AssemblyDomain.InnoScripting, - string.Empty, - "project-default-runtime")); - AddBuilder(builders, CreateDefaultDefinition( - C_EDITOR_ASSEMBLY_NAME, - AssetSourceId.project, - ScriptAssemblyScope.Editor, - AssemblyDomain.InnoScripting, - string.Empty, - "project-default-editor")); + AddBuilder( + builders, + CreateDefaultDefinition( + C_GAME_ASSEMBLY_NAME, + AssetSourceId.project, + ScriptAssemblyScope.Runtime, + AssemblyDomain.InnoScripting, + string.Empty, + "project-default-runtime" + ) + ); + AddBuilder( + builders, + CreateDefaultDefinition( + C_EDITOR_ASSEMBLY_NAME, + AssetSourceId.project, + ScriptAssemblyScope.Editor, + AssemblyDomain.InnoScripting, + string.Empty, + "project-default-editor" + ) + ); ConfigureDefaultReferences(builders, explicitDefinitions, codePlugins, pluginDefaultNames); foreach (AssetFileEntry entry in entries.Where(static entry => - string.Equals(entry.extension, ".cs", StringComparison.OrdinalIgnoreCase))) - { + string.Equals(entry.extension, ".cs", StringComparison.OrdinalIgnoreCase)) + ) { if (entry.isSampleContent) { if (entry.assetPath.source == AssetSourceId.project) + { continue; + } if (!plugins.TryGetCompilationPlugin(entry.assetPath.source, out PluginCandidate? samplePlugin) || samplePlugin is null - || !pluginDefaultNames.TryGetValue(samplePlugin.manifest.pluginId, - out PluginDefaultNames sampleNames)) + || !pluginDefaultNames.TryGetValue( + samplePlugin.manifest.pluginId, + out PluginDefaultNames sampleNames + ) + ) { throw new InvalidDataException($"Sample script '{entry.assetPath}' has no active Plugin."); + } builders[sampleNames.samples].sources.Add(CreateSourceInput(entry, candidateAssets, assets)); continue; } ScriptAssemblyDefinition? definition = FindNearestDefinition(entry.assetPath, explicitDefinitions); ScriptAssemblyScope scope = definition?.scope - ?? (entry.assetPath.localPath.EndsWith(".editor.cs", StringComparison.OrdinalIgnoreCase) - ? ScriptAssemblyScope.Editor - : ScriptAssemblyScope.Runtime); + ?? (entry.assetPath.localPath.EndsWith(".editor.cs", StringComparison.OrdinalIgnoreCase) + ? ScriptAssemblyScope.Editor + : ScriptAssemblyScope.Runtime); AssemblyBuilder builder; if (definition is not null) { @@ -141,19 +178,18 @@ internal static ScriptSourceSet Discover( else if (entry.assetPath.source == AssetSourceId.project) { builder = builders[scope == ScriptAssemblyScope.Editor - ? C_EDITOR_ASSEMBLY_NAME - : C_GAME_ASSEMBLY_NAME]; + ? C_EDITOR_ASSEMBLY_NAME + : C_GAME_ASSEMBLY_NAME]; } else { - if (!plugins.TryGetCompilationPlugin( - entry.assetPath.source, - out PluginCandidate? plugin) + if (!plugins.TryGetCompilationPlugin(entry.assetPath.source, out PluginCandidate? plugin) || plugin is null - || !pluginDefaultNames.TryGetValue(plugin.manifest.pluginId, out PluginDefaultNames names)) - { + || !pluginDefaultNames.TryGetValue(plugin.manifest.pluginId, out PluginDefaultNames names) + ) { throw new InvalidDataException( - $"Script '{entry.assetPath}' does not belong to an active Plugin source."); + $"Script '{entry.assetPath}' does not belong to an active Plugin source." + ); } builder = builders[scope == ScriptAssemblyScope.Editor ? names.editor : names.runtime]; } @@ -164,22 +200,21 @@ internal static ScriptSourceSet Discover( ? builders : builders .Where(static pair => pair.Value.definition.scope == ScriptAssemblyScope.Runtime) - .ToDictionary( - static pair => pair.Key, - static pair => pair.Value, - StringComparer.OrdinalIgnoreCase); + .ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase); ScriptAssemblyInput[] assemblies = ValidateAndOrderAssemblies(compilationBuilders, plugins); return new ScriptSourceSet( builders[C_GAME_ASSEMBLY_NAME].sources.Select(static source => source.sourcePath).ToArray(), includeEditor - ? builders[C_EDITOR_ASSEMBLY_NAME].sources.Select(static source => source.sourcePath).ToArray() - : [], + ? builders[C_EDITOR_ASSEMBLY_NAME].sources.Select(static source => source.sourcePath).ToArray() + : [], includeEditor - ? explicitDefinitions - : explicitDefinitions.Where(static definition => - definition.scope == ScriptAssemblyScope.Runtime).ToArray(), + ? explicitDefinitions + : explicitDefinitions.Where(static definition => ( + definition.scope == ScriptAssemblyScope.Runtime + )).ToArray(), assemblies, - includeEditor); + includeEditor + ); } private static ScriptAssemblyDefinition ParseDefinition( @@ -188,13 +223,15 @@ private static ScriptAssemblyDefinition ParseDefinition( AssetPipeline assets ) { ScriptAssemblyDefinitionAsset asset = candidateAssets is null - ? assets.Load(entry.assetPath) - : candidateAssets.Load(entry.assetPath); + ? assets.Load(entry.assetPath) + : candidateAssets.Load(entry.assetPath); bool hasInfo = candidateAssets is null - ? assets.TryGetInfo(entry.assetPath, out AssetInfo? info) - : candidateAssets.TryGetInfo(entry.assetPath, out info); + ? assets.TryGetInfo(entry.assetPath, out AssetInfo? info) + : candidateAssets.TryGetInfo(entry.assetPath, out info); if (!hasInfo || info is null) + { throw new InvalidDataException($"Script assembly definition '{entry.assetPath}' has no metadata."); + } bool isPlugin = entry.assetPath.source != AssetSourceId.project; return new ScriptAssemblyDefinition( asset.assemblyName, @@ -207,7 +244,8 @@ AssetPipeline assets asset.defines, asset.nullable, asset.allowUnsafe, - ComputeDefinitionHash(asset)); + ComputeDefinitionHash(asset) + ); } private static ScriptSourceInput CreateSourceInput( @@ -216,30 +254,31 @@ private static ScriptSourceInput CreateSourceInput( AssetPipeline assets ) { bool hasInfo = candidateAssets is null - ? assets.TryGetInfo(entry.assetPath, out AssetInfo? info) - : candidateAssets.TryGetInfo(entry.assetPath, out info); + ? assets.TryGetInfo(entry.assetPath, out AssetInfo? info) + : candidateAssets.TryGetInfo(entry.assetPath, out info); if (!hasInfo || info is null || info.persistentId == Guid.Empty || !(candidateAssets is null - ? assets.TryGetArtifact(info.persistentId, "source", out AssetArtifactInfo? source) - : candidateAssets.TryGetArtifact(info.persistentId, "source", out source)) - || source is null) - { + ? assets.TryGetArtifact(info.persistentId, "source", out AssetArtifactInfo? source) + : candidateAssets.TryGetArtifact(info.persistentId, "source", out source)) + || source is null + ) { throw new InvalidDataException($"Script source '{entry.assetPath}' has no committed source artifact."); } IReadOnlyList mounts = candidateAssets?.sourceMounts ?? assets.sourceMounts; AssetSourceMount mount = mounts.Single(candidate => candidate.id == entry.assetPath.source); using ArtifactLease lease = candidateAssets is null - ? assets.AcquireArtifact(info.persistentId, "source") - : candidateAssets.AcquireArtifact(info.persistentId, "source"); + ? assets.AcquireArtifact(info.persistentId, "source") + : candidateAssets.AcquireArtifact(info.persistentId, "source"); using StreamReader reader = new(lease.OpenRead(), Encoding.UTF8, detectEncodingFromByteOrderMarks: true); return new ScriptSourceInput( entry.assetPath, mount.Resolve(entry.assetPath.localPath), reader.ReadToEnd(), info.persistentId, - source.contentHash); + source.contentHash + ); } private static string ComputeDefinitionHash(ScriptAssemblyDefinitionAsset asset) @@ -253,10 +292,10 @@ private static string ComputeDefinitionHash(ScriptAssemblyDefinitionAsset asset) asset.nullable.ToString(), asset.allowUnsafe.ToString() } - .Concat(asset.references.OrderBy(static value => value, StringComparer.Ordinal)) - .Concat(asset.defines.OrderBy(static value => value, StringComparer.Ordinal))); - return Convert.ToHexString( - System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(normalized))); + .Concat(asset.references.OrderBy(static value => value, StringComparer.Ordinal)) + .Concat(asset.defines.OrderBy(static value => value, StringComparer.Ordinal)) + ); + return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(normalized))); } private static void ValidateManifestDefinitions( @@ -268,22 +307,27 @@ IReadOnlyList plugins foreach (PluginCandidate plugin in plugins) { string[] declared = plugin.manifest.assemblyDefinitions - .Select(static path => path.StartsWith("Assets/", StringComparison.Ordinal) + .Select(static path => ( + path.StartsWith("Assets/", StringComparison.Ordinal) ? path["Assets/".Length..] - : path) + : path + )) .OrderBy(static path => path, StringComparer.Ordinal) .ToArray(); string[] discovered = entries - .Where(entry => entry.assetPath.source == plugin.sourceMount.id + .Where(entry => ( + entry.assetPath.source == plugin.sourceMount.id && !entry.isSampleContent - && string.Equals(entry.extension, ".iasmdef", StringComparison.OrdinalIgnoreCase)) + && string.Equals(entry.extension, ".iasmdef", StringComparison.OrdinalIgnoreCase) + )) .Select(static entry => entry.assetPath.localPath) .OrderBy(static path => path, StringComparer.Ordinal) .ToArray(); if (!declared.SequenceEqual(discovered, StringComparer.Ordinal)) { throw new InvalidDataException( - $"Plugin '{plugin.manifest.pluginId}' assemblyDefinitions do not match its imported .iasmdef sources."); + $"Plugin '{plugin.manifest.pluginId}' assemblyDefinitions do not match its imported .iasmdef sources." + ); } } } @@ -310,11 +354,14 @@ IReadOnlyDictionary defaultNames } foreach (string dependencyId in plugin.manifest.dependencies) { - foreach (ScriptAssemblyDefinition dependency in explicitDefinitions.Where(definition => - definition.ownerPluginId == dependencyId)) - { + foreach (ScriptAssemblyDefinition dependency in explicitDefinitions.Where(definition => ( + definition.ownerPluginId == dependencyId + )) + ) { if (dependency.scope == ScriptAssemblyScope.Runtime) + { runtime.references.Add(dependency.name); + } pluginEditor.references.Add(dependency.name); samples?.references.Add(dependency.name); } @@ -330,11 +377,14 @@ IReadOnlyDictionary defaultNames game.references.Add(names.runtime); editor.references.Add(names.runtime); editor.references.Add(names.editor); - foreach (ScriptAssemblyDefinition definition in explicitDefinitions.Where(candidate => - candidate.ownerPluginId == plugin.manifest.pluginId)) - { + foreach (ScriptAssemblyDefinition definition in explicitDefinitions.Where(candidate => ( + candidate.ownerPluginId == plugin.manifest.pluginId + )) + ) { if (definition.scope == ScriptAssemblyScope.Runtime) + { game.references.Add(definition.name); + } editor.references.Add(definition.name); } } @@ -369,27 +419,31 @@ PluginEnvironment plugins if (!builders.TryGetValue(reference, out AssemblyBuilder? dependency)) { throw new InvalidDataException( - $"Script assembly '{builder.definition.name}' references unknown assembly '{reference}'."); + $"Script assembly '{builder.definition.name}' references unknown assembly '{reference}'." + ); } if (builder.definition.scope == ScriptAssemblyScope.Runtime - && dependency.definition.scope == ScriptAssemblyScope.Editor) - { + && dependency.definition.scope == ScriptAssemblyScope.Editor + ) { throw new InvalidDataException( - $"Runtime script assembly '{builder.definition.name}' cannot reference editor assembly '{reference}'."); + $"Runtime script assembly '{builder.definition.name}' cannot reference editor assembly '{reference}'." + ); } ValidateDomainDependency(builder.definition, dependency.definition, plugins); } } - var graph = new DependencyGraph( - StringComparer.OrdinalIgnoreCase, - StringComparer.Ordinal); + var graph = new DependencyGraph(StringComparer.OrdinalIgnoreCase, StringComparer.Ordinal); foreach (string name in builders.Keys) + { graph.AddNode(name); + } foreach ((string name, string[] references) in referencesByAssembly) { foreach (string reference in references) + { graph.AddDependency(name, reference); + } } IReadOnlyList order; try @@ -413,7 +467,8 @@ PluginEnvironment plugins builder.definition.defines, builder.definition.nullable, builder.definition.allowUnsafe, - builder.definition.configurationHash); + builder.definition.configurationHash + ); }).ToArray(); } @@ -423,23 +478,27 @@ private static void ValidateDomainDependency( PluginEnvironment plugins ) { if (assembly.domain != AssemblyDomain.InnoPlugin) + { return; + } if (dependency.domain != AssemblyDomain.InnoPlugin) { throw new InvalidDataException( - $"Plugin assembly '{assembly.name}' cannot reference project assembly '{dependency.name}'."); + $"Plugin assembly '{assembly.name}' cannot reference project assembly '{dependency.name}'." + ); } if (string.Equals(assembly.ownerPluginId, dependency.ownerPluginId, StringComparison.Ordinal)) + { return; - if (!plugins.TryGetCompilationPlugin( - new AssetSourceId(assembly.ownerPluginId), - out PluginCandidate? owner) + } + if (!plugins.TryGetCompilationPlugin(new AssetSourceId(assembly.ownerPluginId), out PluginCandidate? owner) || owner is null - || !owner.manifest.dependencies.Contains(dependency.ownerPluginId, StringComparer.Ordinal)) - { + || !owner.manifest.dependencies.Contains(dependency.ownerPluginId, StringComparer.Ordinal) + ) { throw new InvalidDataException( - $"Plugin '{assembly.ownerPluginId}' must declare dependency '{dependency.ownerPluginId}' " + - $"before assembly '{assembly.name}' can reference '{dependency.name}'."); + $"Plugin '{assembly.ownerPluginId}' must declare dependency '{dependency.ownerPluginId}' " + + $"before assembly '{assembly.name}' can reference '{dependency.name}'." + ); } } @@ -450,26 +509,28 @@ private static ScriptAssemblyDefinition CreateDefaultDefinition( AssemblyDomain domain, string ownerPluginId, string configurationHash - ) - => new( - name, - source, - string.Empty, - scope, - domain, - ownerPluginId, - [], - ["DEBUG", "TRACE"], - nullable: true, - allowUnsafe: false, - configurationHash); + ) => new( + name, + source, + string.Empty, + scope, + domain, + ownerPluginId, + [], + ["DEBUG", "TRACE"], + nullable: true, + allowUnsafe: false, + configurationHash + ); private static void AddBuilder( IDictionary builders, ScriptAssemblyDefinition definition ) { if (!builders.TryAdd(definition.name, new AssemblyBuilder(definition))) + { throw new InvalidDataException($"Script assembly name '{definition.name}' is declared more than once."); + } } private static string CreatePluginAssemblyName(string pluginId) @@ -479,7 +540,9 @@ private static string CreatePluginAssemblyName(string pluginId) { builder.Append(char.ToUpperInvariant(segment[0])); for (int i = 1; i < segment.Length; i++) + { builder.Append(char.IsLetterOrDigit(segment[i]) ? segment[i] : '_'); + } } return builder.ToString(); } @@ -487,10 +550,9 @@ private static string CreatePluginAssemblyName(string pluginId) private static bool IsWithin( string directory, string ancestor - ) - => string.IsNullOrEmpty(ancestor) - || string.Equals(directory, ancestor, StringComparison.OrdinalIgnoreCase) - || directory.StartsWith(ancestor + "/", StringComparison.OrdinalIgnoreCase); + ) => string.IsNullOrEmpty(ancestor) + || string.Equals(directory, ancestor, StringComparison.OrdinalIgnoreCase) + || directory.StartsWith(ancestor + "/", StringComparison.OrdinalIgnoreCase); private sealed class AssemblyBuilder { diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptStaticMemberRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptStaticMemberRewriter.cs index 519354792..ced354238 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptStaticMemberRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptStaticMemberRewriter.cs @@ -33,13 +33,19 @@ internal sealed class ScriptStaticMemberRewriter(SemanticModel model) : CSharpSy private SyntaxNode? Qualify(SimpleNameSyntax node) { if (node.Parent is MemberAccessExpressionSyntax member && member.Name == node - || node.Parent is QualifiedNameSyntax or AliasQualifiedNameSyntax) + || node.Parent is QualifiedNameSyntax or AliasQualifiedNameSyntax + ) { return null; + } if (model.GetSymbolInfo(node).Symbol is not IMethodSymbol { IsStatic: true, MethodKind: MethodKind.Ordinary } method - || !SymbolEqualityComparer.Default.Equals(method.ContainingAssembly, model.Compilation.Assembly)) + || !SymbolEqualityComparer.Default.Equals(method.ContainingAssembly, model.Compilation.Assembly) + ) { return null; - return SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, + } + return SyntaxFactory.MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseExpression(method.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)), - node.WithoutTrivia()).WithTriviaFrom(node); + node.WithoutTrivia() + ).WithTriviaFrom(node); } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs index 4d7901e31..57b198103 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Text; using System.Threading; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -21,26 +20,25 @@ internal static ScriptTypeAnalysisResult Analyze( IReadOnlyDictionary attachableTypes, CancellationToken cancellationToken ) { - var sourcesByPath = sources.ToDictionary( - static source => source.sourcePath, - StringComparer.OrdinalIgnoreCase); - var discovered = new Dictionary( - SymbolEqualityComparer.Default); + var sourcesByPath = sources.ToDictionary(static source => source.sourcePath, StringComparer.OrdinalIgnoreCase); + var discovered = new Dictionary(SymbolEqualityComparer.Default); foreach (SyntaxTree tree in compilation.SyntaxTrees) { if (!sourcesByPath.TryGetValue(tree.FilePath, out ScriptSourceInput? source)) + { continue; + } SemanticModel semanticModel = compilation.GetSemanticModel(tree); foreach (TypeDeclarationSyntax declaration in tree.GetRoot(cancellationToken) - .DescendantNodes() - .OfType()) - { - if (semanticModel.GetDeclaredSymbol(declaration, cancellationToken) is not INamedTypeSymbol symbol || - symbol.TypeKind != TypeKind.Class || - symbol.IsAbstract || - symbol.IsGenericType || - !TryGetAttachableKind(symbol, attachableTypes, out string kind)) - { + .DescendantNodes() + .OfType() + ) { + if (semanticModel.GetDeclaredSymbol(declaration, cancellationToken) is not INamedTypeSymbol symbol + || symbol.TypeKind != TypeKind.Class + || symbol.IsAbstract + || symbol.IsGenericType + || !TryGetAttachableKind(symbol, attachableTypes, out string kind) + ) { continue; } @@ -58,18 +56,18 @@ CancellationToken cancellationToken var mappings = new List(); var implicitTypesBySource = discovered.Values .Where(static type => GetExplicitStableTypeId(type.symbol) is null) - .SelectMany(static type => type.declarations - .Select(declaration => (declaration.source.persistentId, type))) + .SelectMany(static type => type.declarations.Select(declaration => (declaration.source.persistentId, type))) .GroupBy(static value => value.persistentId) .ToDictionary( static group => group.Key, static group => group.Select(static value => value.type) .Distinct() - .Count()); + .Count() + ); foreach (MutableScriptType type in discovered.Values - .OrderBy(static value => GetMetadataTypeName(value.symbol), StringComparer.Ordinal)) - { + .OrderBy(static value => GetMetadataTypeName(value.symbol), StringComparer.Ordinal) + ) { string typeName = GetMetadataTypeName(type.symbol); string? explicitIdValue = GetExplicitStableTypeId(type.symbol); if (explicitIdValue is not null) @@ -77,19 +75,19 @@ CancellationToken cancellationToken ScriptDeclaration declaration = SelectManifestDeclaration(type); if (!Guid.TryParse(explicitIdValue, out Guid explicitId)) { - diagnostics.Add(CreateDiagnostic( - "INNO2000", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, - $"Type '{typeName}' has invalid StableTypeId '{explicitIdValue}'.", - declaration)); + diagnostics.Add( + CreateDiagnostic( + "INNO2000", + Inno.Core.Diagnostics.DiagnosticSeverity.Error, + $"Type '{typeName}' has invalid StableTypeId '{explicitIdValue}'.", + declaration + ) + ); continue; } - manifestEntries.Add(CreateManifestEntry( - type, - declaration, - explicitId, - explicitIdentity: true, - canonicalSource: true)); + manifestEntries.Add( + CreateManifestEntry(type, declaration, explicitId, explicitIdentity: true, canonicalSource: true) + ); continue; } @@ -97,7 +95,8 @@ CancellationToken cancellationToken .Where(declaration => string.Equals( GetCanonicalFileName(declaration.source.sourcePath), type.symbol.Name, - StringComparison.Ordinal)) + StringComparison.Ordinal + )) .GroupBy(static declaration => declaration.source.persistentId) .Select(static group => group.First()) .ToArray(); @@ -108,12 +107,15 @@ CancellationToken cancellationToken } else if (matchingDeclarations.Length > 1) { - diagnostics.Add(CreateDiagnostic( - "INNO2003", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, - $"Partial type '{typeName}' has more than one source file matching its type name. " + - "Keep one canonical source or add an explicit StableTypeId.", - matchingDeclarations[0])); + diagnostics.Add( + CreateDiagnostic( + "INNO2003", + Inno.Core.Diagnostics.DiagnosticSeverity.Error, + $"Partial type '{typeName}' has more than one source file matching its type name. " + + "Keep one canonical source or add an explicit StableTypeId.", + matchingDeclarations[0] + ) + ); } else { @@ -121,63 +123,72 @@ CancellationToken cancellationToken .GroupBy(static declaration => declaration.source.persistentId) .Select(static group => group.First()) .ToArray(); - if (distinctSources.Length == 1 && - implicitTypesBySource.GetValueOrDefault(distinctSources[0].source.persistentId) == 1) - { + if (distinctSources.Length == 1 + && implicitTypesBySource.GetValueOrDefault(distinctSources[0].source.persistentId) == 1 + ) { canonical = distinctSources[0]; - diagnostics.Add(CreateDiagnostic( - "INNO2002", - Inno.Core.Diagnostics.DiagnosticSeverity.Warning, - $"Attachable type '{typeName}' does not match its canonical script file name. " + - "Its source identity is preserved, but matching names are recommended.", - canonical)); + diagnostics.Add( + CreateDiagnostic( + "INNO2002", + Inno.Core.Diagnostics.DiagnosticSeverity.Warning, + $"Attachable type '{typeName}' does not match its canonical script file name. " + + "Its source identity is preserved, but matching names are recommended.", + canonical + ) + ); } else { ScriptDeclaration declaration = distinctSources[0]; - diagnostics.Add(CreateDiagnostic( - "INNO2001", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, - $"Attachable type '{typeName}' has no unambiguous canonical script source. " + - "Move it to a matching file or add an explicit StableTypeId.", - declaration)); + diagnostics.Add( + CreateDiagnostic( + "INNO2001", + Inno.Core.Diagnostics.DiagnosticSeverity.Error, + $"Attachable type '{typeName}' has no unambiguous canonical script source. " + + "Move it to a matching file or add an explicit StableTypeId.", + declaration + ) + ); } } if (canonical is null) + { continue; + } Guid stableTypeId = ScriptTypeIdentity.CreateCanonical(canonical.source.persistentId); mappings.Add(new ScriptTypeMapping(typeName, stableTypeId)); - manifestEntries.Add(CreateManifestEntry( - type, - canonical, - stableTypeId, - explicitIdentity: false, - canonicalSource: true)); + manifestEntries.Add( + CreateManifestEntry(type, canonical, stableTypeId, explicitIdentity: false, canonicalSource: true) + ); } foreach (IGrouping collision in mappings - .GroupBy(static mapping => mapping.stableTypeId) - .Where(static group => group.Count() > 1)) - { + .GroupBy(static mapping => mapping.stableTypeId) + .Where(static group => group.Count() > 1) + ) { ScriptTypeMapping[] conflicting = collision.ToArray(); ScriptTypeManifestEntry entry = manifestEntries.First(value => string.Equals(value.typeName, conflicting[0].typeName, StringComparison.Ordinal)); - diagnostics.Add(new ScriptDiagnostic( - "INNO2004", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, - $"Script source '{entry.sourcePath}' owns more than one attachable type identity: " + - string.Join(", ", conflicting.Select(static value => value.typeName)) + - ". Keep one canonical type or add explicit StableTypeId attributes.", - entry.sourcePath, - entry.line, - entry.column)); + diagnostics.Add( + new ScriptDiagnostic( + "INNO2004", + Inno.Core.Diagnostics.DiagnosticSeverity.Error, + $"Script source '{entry.sourcePath}' owns more than one attachable type identity: " + + string.Join(", ", conflicting.Select(static value => value.typeName)) + + ". Keep one canonical type or add explicit StableTypeId attributes.", + entry.sourcePath, + entry.line, + entry.column + ) + ); } return new ScriptTypeAnalysisResult( new ScriptTypeManifest(compilation.AssemblyName ?? string.Empty, manifestEntries), mappings, - diagnostics); + diagnostics + ); } internal static string CreateMappingSource(IReadOnlyList mappings) @@ -217,29 +228,32 @@ out string kind AttributeData? attribute = symbol.GetAttributes().FirstOrDefault(value => string.Equals( value.AttributeClass?.ToDisplayString(), C_STABLE_TYPE_ID_ATTRIBUTE, - StringComparison.Ordinal)); + StringComparison.Ordinal + )); return attribute?.ConstructorArguments.Length > 0 - ? attribute.ConstructorArguments[0].Value as string - : null; + ? attribute.ConstructorArguments[0].Value as string + : null; } private static string GetMetadataTypeName(INamedTypeSymbol symbol) { var typeNames = new Stack(); for (INamedTypeSymbol? current = symbol; current is not null; current = current.ContainingType) + { typeNames.Push(current.MetadataName); + } string nestedName = string.Join("+", typeNames); return symbol.ContainingNamespace.IsGlobalNamespace - ? nestedName - : symbol.ContainingNamespace.ToDisplayString() + "." + nestedName; + ? nestedName + : symbol.ContainingNamespace.ToDisplayString() + "." + nestedName; } private static string GetCanonicalFileName(string sourcePath) { string name = System.IO.Path.GetFileNameWithoutExtension(sourcePath); return name.EndsWith(".editor", StringComparison.OrdinalIgnoreCase) - ? name[..^".editor".Length] - : name; + ? name[..^".editor".Length] + : name; } private static ScriptDeclaration SelectManifestDeclaration(MutableScriptType type) @@ -247,7 +261,8 @@ private static ScriptDeclaration SelectManifestDeclaration(MutableScriptType typ .OrderByDescending(declaration => string.Equals( GetCanonicalFileName(declaration.source.sourcePath), type.symbol.Name, - StringComparison.Ordinal)) + StringComparison.Ordinal + )) .ThenBy(static declaration => declaration.source.relativePath, StringComparer.Ordinal) .First(); @@ -268,7 +283,8 @@ bool canonicalSource span.StartLinePosition.Line + 1, span.StartLinePosition.Character + 1, explicitIdentity, - canonicalSource); + canonicalSource + ); } private static ScriptDiagnostic CreateDiagnostic( @@ -284,7 +300,8 @@ ScriptDeclaration declaration message, declaration.source.sourcePath, span.StartLinePosition.Line + 1, - span.StartLinePosition.Character + 1); + span.StartLinePosition.Character + 1 + ); } private sealed class MutableScriptType( diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs index 69ec571ca..e3a05e6b3 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs @@ -12,7 +12,9 @@ internal static class ScriptTypeIdentity internal static Guid CreateCanonical(Guid sourcePersistentId) { if (sourcePersistentId == Guid.Empty) + { throw new ArgumentException("A script source identity is required.", nameof(sourcePersistentId)); + } return CreateGuidV5(C_SCRIPT_SOURCE_NAMESPACE, sourcePersistentId.ToString("D")); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs index 6225592fd..c66e12d20 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Linq; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -27,7 +26,9 @@ internal sealed class SerializablePropertyOrderRewriter : CSharpSyntaxRewriter public override SyntaxNode? Visit(SyntaxNode? node) { if (node is not TypeDeclarationSyntax) + { return base.Visit(node); + } m_nextOrders.Push(0); try @@ -71,23 +72,25 @@ internal sealed class SerializablePropertyOrderRewriter : CSharpSyntaxRewriter private TMember RewriteMember( TMember member, SyntaxList attributeLists - ) - where TMember : MemberDeclarationSyntax + ) where TMember : MemberDeclarationSyntax { if (m_nextOrders.Count == 0 || !TryFindSerializableAttribute(attributeLists, out AttributeSyntax attribute)) + { return member; + } int order = m_nextOrders.Pop(); m_nextOrders.Push(order + 1); if (HasExplicitOrder(attribute)) + { return member; + } AttributeArgumentSyntax orderArgument = SyntaxFactory.AttributeArgument( SyntaxFactory.NameEquals(C_ORDER_PROPERTY_NAME), nameColon: null, - SyntaxFactory.LiteralExpression( - SyntaxKind.NumericLiteralExpression, - SyntaxFactory.Literal(order))); + SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(order)) + ); AttributeArgumentListSyntax argumentList = attribute.ArgumentList ?? SyntaxFactory.AttributeArgumentList(); AttributeSyntax rewrittenAttribute = attribute.WithArgumentList(argumentList.AddArguments(orderArgument)); return member.ReplaceNode(attribute, rewrittenAttribute); @@ -114,8 +117,11 @@ out AttributeSyntax result private static bool HasExplicitOrder(AttributeSyntax attribute) { return attribute.ArgumentList?.Arguments.Any(static argument => - string.Equals(argument.NameEquals?.Name.Identifier.ValueText, C_ORDER_PROPERTY_NAME, - System.StringComparison.Ordinal)) == true; + string.Equals( + argument.NameEquals?.Name.Identifier.ValueText, + C_ORDER_PROPERTY_NAME, + System.StringComparison.Ordinal + )) == true; } private static string GetRightmostName(NameSyntax name) diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs index dff34b19d..2cf0c6126 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs @@ -4,12 +4,11 @@ using System.Text; using System.Threading; using System.Threading.Tasks; - -using Inno.Assets.Pipeline; -using Inno.Core.Serialization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Inno.Assets.Pipeline; +using Inno.Core.Serialization; namespace Inno.Scripting.Compiler; @@ -20,6 +19,7 @@ internal sealed class CSharpScriptImporter : AssetImporter /// Gets whether imported output is deployed to runtime, editor, or both domains. /// public override AssetDeploymentScope deploymentScope => AssetDeploymentScope.AuthoringOnly; + /// /// Gets the normalized source extensions accepted by this importer. /// @@ -51,7 +51,8 @@ CancellationToken cancellationToken new CSharpParseOptions(LanguageVersion.CSharp14, DocumentationMode.Parse), context.assetPath.ToString(), Encoding.UTF8, - cancellationToken); + cancellationToken + ); BaseTypeDeclarationSyntax[] declarations = tree.GetRoot(cancellationToken) .DescendantNodes() .OfType() @@ -67,26 +68,31 @@ CancellationToken cancellationToken .ToArray(); ScriptAssemblyScope scope = context.assetPath.localPath.EndsWith( ".editor.cs", - StringComparison.OrdinalIgnoreCase) - ? ScriptAssemblyScope.Editor - : ScriptAssemblyScope.Runtime; + StringComparison.OrdinalIgnoreCase + ) + ? ScriptAssemblyScope.Editor + : ScriptAssemblyScope.Runtime; output.SetAsset(new ScriptSourceAsset(scope, declaredTypes, diagnostics)); await output.WriteArtifactAsync( "source", Encoding.UTF8.GetBytes(source), - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); await output.WriteArtifactAsync( "diagnostics", Encoding.UTF8.GetBytes(string.Join(Environment.NewLine, diagnostics)), - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); var typeManifest = new ScriptSourceTypeManifest( context.persistentId, context.assetPath.ToString(), - declarations.Select(CreateTypeDeclaration).ToArray()); + declarations.Select(CreateTypeDeclaration).ToArray() + ); await output.WriteArtifactAsync( "type-manifest", context.serialization.Serialize(typeManifest), - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); } private static ScriptSourceTypeDeclaration CreateTypeDeclaration(BaseTypeDeclarationSyntax declaration) @@ -97,7 +103,8 @@ private static ScriptSourceTypeDeclaration CreateTypeDeclaration(BaseTypeDeclara declaration.Kind().ToString(), declaration.Modifiers.Any(static modifier => modifier.IsKind(SyntaxKind.PartialKeyword)), span.StartLinePosition.Line + 1, - span.StartLinePosition.Character + 1); + span.StartLinePosition.Character + 1 + ); } private static string GetDeclaredTypeName(BaseTypeDeclarationSyntax declaration) @@ -115,7 +122,7 @@ private static string GetDeclaredTypeName(BaseTypeDeclarationSyntax declaration) .Select(static value => value.Name.ToString()) .ToArray(); return namespaces.Length == 0 - ? nestedTypeName - : string.Join(".", namespaces) + "." + nestedTypeName; + ? nestedTypeName + : string.Join(".", namespaces) + "." + nestedTypeName; } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs index fc80a46ca..baf602b60 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; @@ -15,6 +14,7 @@ internal sealed class ScriptAssemblyDefinitionImporter : AssetImporter public override AssetDeploymentScope deploymentScope => AssetDeploymentScope.AuthoringOnly; + /// /// Gets the normalized source extensions accepted by this importer. /// @@ -43,13 +43,20 @@ CancellationToken cancellationToken ScriptAssemblyDefinitionAsset asset = NativeAssetSourceSerialization.Import( context.sourceBytes.Span, context.services, - out IReadOnlyList dependencies); + out IReadOnlyList dependencies + ); foreach (AssetDependency dependency in dependencies) + { output.DependsOnAsset(dependency); + } if (string.IsNullOrWhiteSpace(asset.assemblyName)) + { throw new InvalidOperationException("Assembly definition name is required."); + } if (!Enum.IsDefined(asset.scope)) + { throw new InvalidOperationException("Assembly definition scope must be Runtime or Editor."); + } output.SetAsset(asset); await output.WriteArtifactAsync("source", context.sourceBytes, cancellationToken) .ConfigureAwait(false); @@ -77,9 +84,11 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(asset.assemblyName)) + { throw new InvalidOperationException("Assembly definition name is required."); - return ValueTask.FromResult?>(NativeAssetSourceSerialization.Export( - asset, - context.services)); + } + return ValueTask.FromResult?>( + NativeAssetSourceSerialization.Export(asset, context.services) + ); } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompilationInputs.cs b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompilationInputs.cs index d3cbdc0ed..5354f6ffd 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompilationInputs.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompilationInputs.cs @@ -38,10 +38,14 @@ IEnumerable predefinedSymbols ArgumentNullException.ThrowIfNull(predefinedSymbols); string[] references = frameworkReferences.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); if (references.Length == 0 || references.Any(static path => !Path.IsPathFullyQualified(path))) + { throw new ArgumentException("SDK framework references must be a nonempty set of absolute paths.", nameof(frameworkReferences)); + } this.sdkIdentity = sdkIdentity; this.frameworkReferences = Array.AsReadOnly(references); - this.predefinedSymbols = Array.AsReadOnly(predefinedSymbols.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray()); + this.predefinedSymbols = Array.AsReadOnly( + predefinedSymbols.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray() + ); } /// diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs index 71fb666cf..c3cacff11 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs @@ -3,7 +3,6 @@ using System.IO; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Plugins.Authoring; @@ -19,6 +18,7 @@ public sealed class ScriptCompiler private readonly ScriptArtifactCache m_artifacts; private readonly ScriptCompilerOptions m_options; private readonly PluginEnvironment m_plugins; + /// /// Creates a compiler over explicit authoring services owned by one host. /// @@ -65,10 +65,7 @@ PluginEnvironment plugins /// public void GenerateProjectFiles() { - ScriptProjectGenerator.Generate( - m_options, - m_assets, - m_plugins); + ScriptProjectGenerator.Generate(m_options, m_assets, m_plugins); } /// @@ -110,21 +107,21 @@ public ValueTask CompileAuthoringGenerationAsync( IProgress? progress = null, CancellationToken cancellationToken = default, IAssetSourceSnapshot? sourceSnapshot = null - ) - => ScriptCompilerEngine.CompileAsync( - m_options, - m_assets, - m_plugins, - includeEditor: true, - targetRuntimeDirectory: null, - progress is null - ? null - : ( - fraction, - stage - ) => progress.Report(new ScriptCompilationProgress(fraction, stage)), - cancellationToken, - sourceSnapshot); + ) => ScriptCompilerEngine.CompileAsync( + m_options, + m_assets, + m_plugins, + includeEditor: true, + targetRuntimeDirectory: null, + progress is null + ? null + : ( + fraction, + stage + ) => progress.Report(new ScriptCompilationProgress(fraction, stage)), + cancellationToken, + sourceSnapshot + ); /// /// Compiles only the runtime assembly closure required by a deployed Player and binds it to that Player runtime. @@ -180,12 +177,13 @@ public ValueTask CompileRuntimeDeploymentAsync( includeEditor: false, targetRuntimeDirectory: targetRuntimeDirectory, progress is null - ? null - : ( - fraction, - stage - ) => progress.Report(new ScriptCompilationProgress(fraction, stage)), - cancellationToken); + ? null + : ( + fraction, + stage + ) => progress.Report(new ScriptCompilationProgress(fraction, stage)), + cancellationToken + ); } /// diff --git a/src/runtime/scripting/Inno.Scripting.Reload/IScriptReloadCoordinator.cs b/src/runtime/scripting/Inno.Scripting.Reload/IScriptReloadCoordinator.cs index c0364f739..1977b490e 100644 --- a/src/runtime/scripting/Inno.Scripting.Reload/IScriptReloadCoordinator.cs +++ b/src/runtime/scripting/Inno.Scripting.Reload/IScriptReloadCoordinator.cs @@ -1,6 +1,5 @@ -using Inno.Extensibility.Reload; - using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; namespace Inno.Scripting.Reload; diff --git a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs index 98300a910..6dce6ef24 100644 --- a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs +++ b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs @@ -1,4 +1,3 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; using System.Linq; @@ -6,14 +5,14 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; +using Inno.Core.Diagnostics; +using Inno.Core.Settings; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; -using Inno.Core.Settings; +using Inno.Plugins.Authoring; using Inno.Scripting.Compiler; namespace Inno.Scripting.Reload; @@ -39,8 +38,11 @@ public sealed class ScriptReloadHost : IDisposable private readonly Func m_moduleSourceFactory; private readonly SemaphoreSlim m_compileGate = new(1, 1); private readonly CancellationTokenSource m_lifetimeCancellation = new(); + private readonly TaskCompletionSource m_disposalCompleted = new( - TaskCreationOptions.RunContinuationsAsynchronously); + TaskCreationOptions.RunContinuationsAsynchronously + ); + private readonly CancellationToken m_lifetimeToken; private CancellationTokenSource? m_activeCompilationCancellation; @@ -120,22 +122,28 @@ Func moduleSourceFactory ArgumentNullException.ThrowIfNull(reloads); ArgumentNullException.ThrowIfNull(moduleSourceFactory); if (options.debounceMilliseconds < 0) - throw new ArgumentOutOfRangeException(nameof(options), "Debounce duration cannot be negative."); - if (options.compilationWarningTimeout <= TimeSpan.Zero && - options.compilationWarningTimeout != Timeout.InfiniteTimeSpan) { + throw new ArgumentOutOfRangeException(nameof(options), "Debounce duration cannot be negative."); + } + if (options.compilationWarningTimeout <= TimeSpan.Zero + && options.compilationWarningTimeout != Timeout.InfiniteTimeSpan + ) { throw new ArgumentOutOfRangeException( nameof(options), - "Compilation warning timeout must be positive or infinite."); + "Compilation warning timeout must be positive or infinite." + ); } if (options.unloadCollectionInterval < TimeSpan.Zero) - throw new ArgumentOutOfRangeException(nameof(options), "Unload collection interval cannot be negative."); - if (options.unloadRetentionTimeout <= TimeSpan.Zero && - options.unloadRetentionTimeout != Timeout.InfiniteTimeSpan) { + throw new ArgumentOutOfRangeException(nameof(options), "Unload collection interval cannot be negative."); + } + if (options.unloadRetentionTimeout <= TimeSpan.Zero + && options.unloadRetentionTimeout != Timeout.InfiniteTimeSpan + ) { throw new ArgumentOutOfRangeException( nameof(options), - "Unload retention timeout must be positive or infinite."); + "Unload retention timeout must be positive or infinite." + ); } m_assets = assets; m_compiler = compiler; @@ -173,7 +181,9 @@ public bool isCompilationPending get { lock (m_sync) + { return m_requestedReload != ScriptReloadRequest.None; + } } } @@ -191,8 +201,8 @@ public TimeSpan compilationElapsed { long started = Volatile.Read(ref m_compilationStartedTimestamp); return isCompiling && started != 0 - ? TimeSpan.FromMilliseconds(Math.Max(0, Environment.TickCount64 - started)) - : m_lastCompilationElapsed; + ? TimeSpan.FromMilliseconds(Math.Max(0, Environment.TickCount64 - started)) + : m_lastCompilationElapsed; } } @@ -200,9 +210,9 @@ public TimeSpan compilationElapsed /// Gets whether the active compilation exceeded the configured warning duration. /// public bool isCompilationTakingLong - => isCompiling && - m_options.compilationWarningTimeout != Timeout.InfiniteTimeSpan && - compilationElapsed >= m_options.compilationWarningTimeout; + => isCompiling + && m_options.compilationWarningTimeout != Timeout.InfiniteTimeSpan + && compilationElapsed >= m_options.compilationWarningTimeout; /// /// Gets the most recently completed compilation. @@ -212,7 +222,9 @@ public ScriptCompilationResult? lastCompilation get { lock (m_sync) + { return m_lastCompilation; + } } } @@ -224,7 +236,9 @@ public bool isUnloadVerificationPending get { lock (m_sync) + { return m_modules.generations.state == GenerationState.AwaitingCollection; + } } } @@ -236,7 +250,9 @@ public bool isFaulted get { lock (m_sync) + { return m_modules.generations.state == GenerationState.Faulted; + } } } @@ -247,7 +263,9 @@ public void Start() { ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_assets.isInitialized) + { throw new InvalidOperationException("ScriptReloadHost requires AssetPipeline to be initialized first."); + } m_assets.Update(); m_assets.Changed -= OnAssetDatabaseChanged; m_assets.Changed += OnAssetDatabaseChanged; @@ -259,17 +277,19 @@ public void Start() { lock (m_sync) { - bool hasActiveScripting = m_modules.isInitialized && - m_modules.modules.Any(static module => module.domain == AssemblyDomain.InnoScripting); + bool hasActiveScripting = m_modules.isInitialized + && m_modules.modules.Any(static module => module.domain == AssemblyDomain.InnoScripting); m_requestedReload = m_plugins.hasPendingActivation - ? ScriptReloadRequest.ReloadPlugins - : hasActiveScripting - ? ScriptReloadRequest.Recompile - : ScriptReloadRequest.ReloadScripting; + ? ScriptReloadRequest.ReloadPlugins + : hasActiveScripting + ? ScriptReloadRequest.Recompile + : ScriptReloadRequest.ReloadScripting; m_initialCompileRequested = true; m_lastCompileRequestTimestamp = Environment.TickCount64; - Volatile.Write(ref m_progress, new ScriptReloadProgress(++m_progressOperation, 0f, - "Initial scripting cache probe queued.", false)); + Volatile.Write( + ref m_progress, + new ScriptReloadProgress(++m_progressOperation, 0f, "Initial scripting cache probe queued.", false) + ); } } } @@ -293,13 +313,19 @@ public bool CancelCompilation(long operationId) lock (m_sync) { if (operationId != m_progress.operationId || operationId != m_activeProgressOperation) + { return false; + } cancellation = m_activeCompilationCancellation; if (cancellation is not null) + { SetCompilationProgress(m_progress.fraction, "Canceling script compilation...", operationId, cancellationRequested: true); + } } if (cancellation is null) + { return false; + } try { cancellation.Cancel(); @@ -372,10 +398,10 @@ public bool TryCompilePending(out Task? compilation) return false; } long elapsed = Environment.TickCount64 - m_lastCompileRequestTimestamp; - if (m_requestedReload == ScriptReloadRequest.None || - isCompiling || - !m_initialCompileRequested && elapsed < m_options.debounceMilliseconds) - { + if (m_requestedReload == ScriptReloadRequest.None + || isCompiling + || !m_initialCompileRequested && elapsed < m_options.debounceMilliseconds + ) { compilation = null; return false; } @@ -385,10 +411,12 @@ public bool TryCompilePending(out Task? compilation) m_initialCompileRequested = false; } if (m_assets.isInitialized) + { m_assets.Update(); + } PluginUnavailabilityPlan? unavailability = request == ScriptReloadRequest.ReloadPlugins - ? CapturePluginUnavailabilityPlan() - : null; + ? CapturePluginUnavailabilityPlan() + : null; compilation = CompileAsync(request, unavailability, operation).AsTask(); return true; } @@ -402,7 +430,8 @@ private async ValueTask CompileAsync( ObjectDisposedException.ThrowIf(m_disposed, this); using CancellationTokenSource linkedCancellation = CancellationTokenSource.CreateLinkedTokenSource( cancellationToken, - m_lifetimeToken); + m_lifetimeToken + ); CancellationToken effectiveCancellation = linkedCancellation.Token; await m_compileGate.WaitAsync(effectiveCancellation).ConfigureAwait(false); try @@ -429,8 +458,11 @@ private async ValueTask CompileAsync( ) => SetCompilationProgress( progress * C_COMPILATION_PROGRESS_SHARE, progress >= 1f ? "Compilation finished; waiting for generation activation and state recovery." : status, - operation, isCompilerUpdate: true)), - effectiveCancellation) + operation, + isCompilerUpdate: true + )), + effectiveCancellation + ) .ConfigureAwait(false); } catch (OperationCanceledException) when (effectiveCancellation.IsCancellationRequested) @@ -446,7 +478,9 @@ private async ValueTask CompileAsync( exception.ToString(), filePath: null, line: 0, - column: 0)); + column: 0 + ) + ); } lock (m_sync) { @@ -457,7 +491,9 @@ private async ValueTask CompileAsync( if (m_requestedReload != ScriptReloadRequest.None) { if (request > m_requestedReload) + { m_requestedReload = request; + } m_pendingCompilation = null; } else if (result.success || unavailability is not null) @@ -466,18 +502,21 @@ private async ValueTask CompileAsync( result, request, operation, - result.success ? null : unavailability); + result.success ? null : unavailability + ); } SetCompilationProgress( result.success || unavailability is not null ? C_COMPILATION_PROGRESS_SHARE : progress.fraction, m_requestedReload != ScriptReloadRequest.None - ? "Compilation superseded by a queued reload request." - : result.success - ? "Script compilation completed; waiting for generation activation and state recovery." - : unavailability is not null - ? "Compilation failed after a Plugin availability change; the unavailable " + - "generation is ready to activate." - : "Script compilation failed.", operation); + ? "Compilation superseded by a queued reload request." + : result.success + ? "Script compilation completed; waiting for generation activation and state recovery." + : unavailability is not null + ? "Compilation failed after a Plugin availability change; the unavailable " + + "generation is ready to activate." + : "Script compilation failed.", + operation + ); } } return result; @@ -487,8 +526,7 @@ private async ValueTask CompileAsync( long started = Interlocked.Exchange(ref m_compilationStartedTimestamp, 0); if (started != 0) { - m_lastCompilationElapsed = TimeSpan.FromMilliseconds( - Math.Max(0, Environment.TickCount64 - started)); + m_lastCompilationElapsed = TimeSpan.FromMilliseconds(Math.Max(0, Environment.TickCount64 - started)); } lock (m_sync) { @@ -521,18 +559,26 @@ public bool ApplyPendingReload() { ThrowIfFaultedLocked(); if (m_modules.generations.state == GenerationState.AwaitingCollection) - throw new InvalidOperationException("A new script generation cannot activate before the previous unload barrier completes."); + { + throw new InvalidOperationException( + "A new script generation cannot activate before the previous unload barrier completes." + ); + } pending = m_pendingCompilation; if (pending is not null && m_requestedReload != ScriptReloadRequest.None) { if (pending.request > m_requestedReload) + { m_requestedReload = pending.request; + } m_pendingCompilation = null; pending = null; } } if (pending is null) + { return false; + } ReloadPlan plan = SelectReloadPlan(pending); if (plan.requests.Count == 0 && plan.removedModuleNames.Count == 0) @@ -547,28 +593,33 @@ public bool ApplyPendingReload() SetCompilationProgress(C_STAGING_PROGRESS, "Staging script reload candidates...", pending.operationId); using AssemblyReloadSession reload = m_modules.BeginReload( plan.requests.Select(m_moduleSourceFactory).ToArray(), - plan.removedModuleNames); + plan.removedModuleNames + ); SetCompilationProgress(C_MIGRATION_PROGRESS, "Restoring active editor state...", pending.operationId); IAssemblyUnloadProbe unload = PublishGeneration(reload); m_modules.generations.TrackRetirement(unload); m_retiringProgressOperation = pending.operationId; m_activeCompilationDirectory = pending.unavailability is null - ? pending.compilation.outputDirectory - : null; - _ = m_compiler.CollectArtifacts(m_activeCompilationDirectory is null + ? pending.compilation.outputDirectory + : null; + _ = m_compiler.CollectArtifacts( + m_activeCompilationDirectory is null ? Array.Empty() - : [m_activeCompilationDirectory]); + : [m_activeCompilationDirectory] + ); RefreshModuleHandles(); UpdateActiveFingerprints(plan); string completedStatus = pending.unavailability is null - ? "Script reload completed." - : "Plugin availability change committed. Unavailable scene types are preserved as Missing until their " + - "Stable IDs return."; + ? "Script reload completed." + : "Plugin availability change committed. Unavailable scene types are preserved as Missing until their " + + "Stable IDs return."; SetCompilationProgress( !isUnloadVerificationPending ? 1f : C_UNLOAD_VERIFICATION_PROGRESS, !isUnloadVerificationPending - ? completedStatus - : completedStatus + " Verifying retired assembly unload...", pending.operationId); + ? completedStatus + : completedStatus + " Verifying retired assembly unload...", + pending.operationId + ); m_reloads.RefreshDiagnostics(); CompletePendingReload(pending); return true; @@ -601,7 +652,9 @@ public void Dispose() { Exception? previousFailure = m_disposalCompleted.Task.GetAwaiter().GetResult(); if (previousFailure is not null) + { ExceptionDispatchInfo.Capture(previousFailure).Throw(); + } return; } Exception? disposalFailure = null; @@ -635,12 +688,16 @@ public void Dispose() .. m_pluginModules.Values ]; if (modules.Length > 0) + { _ = m_modules.Unload(modules); + } m_pluginModules.Clear(); m_runtimeScriptModule = null; m_editorScriptModule = null; if (modules.Length > 0 && m_assets.isInitialized) + { m_assets.Rescan(); + } } m_activeCompilationDirectory = null; m_activeCompilation = null; @@ -677,14 +734,21 @@ public bool AdvanceUnloadVerification(out Exception? failure) failure = m_modules.generations.failure; if (failure is not null) { - SetCompilationProgress(progress.fraction, "Generation retirement failed. Restart the host before Play, Build, Export or reload."); + SetCompilationProgress( + progress.fraction, + "Generation retirement failed. Restart the host before Play, Build, Export or reload." + ); return true; } try { if (!m_modules.generations.Advance()) { - SetCompilationProgress(C_UNLOAD_VERIFICATION_PROGRESS, "Verifying retired generation unload...", m_retiringProgressOperation); + SetCompilationProgress( + C_UNLOAD_VERIFICATION_PROGRESS, + "Verifying retired generation unload...", + m_retiringProgressOperation + ); return false; } SetCompilationProgress(1f, "Generation publication and retired assembly unload completed.", m_retiringProgressOperation); @@ -693,7 +757,10 @@ public bool AdvanceUnloadVerification(out Exception? failure) catch (Exception exception) { failure = exception; - SetCompilationProgress(progress.fraction, "Generation retirement failed. Restart the host before Play, Build, Export or reload."); + SetCompilationProgress( + progress.fraction, + "Generation retirement failed. Restart the host before Play, Build, Export or reload." + ); return true; } } @@ -701,17 +768,23 @@ public bool AdvanceUnloadVerification(out Exception? failure) private void OnAssetDatabaseChanged(AssetChangeSet changeSet) { if (m_disposed || !m_options.autoCompile) + { return; + } for (int i = 0; i < changeSet.changes.Count; i++) { AssetChange change = changeSet.changes[i]; string path = change.assetPath.ToString(); string previousPath = change.previousAssetPath?.ToString() ?? string.Empty; if (!IsScriptInput(path) && !IsScriptInput(previousPath)) + { continue; - QueueReload(IsPluginInput(path) || IsPluginInput(previousPath) + } + QueueReload( + IsPluginInput(path) || IsPluginInput(previousPath) ? ScriptReloadRequest.ReloadPlugins - : ScriptReloadRequest.Recompile); + : ScriptReloadRequest.Recompile + ); return; } } @@ -719,9 +792,13 @@ private void OnAssetDatabaseChanged(AssetChangeSet changeSet) private void OnSourceMountsChanged() { if (m_disposed || !m_options.autoCompile || m_publishingGeneration) + { return; + } if (m_plugins.hasPendingActivation) + { return; + } QueueReload(ScriptReloadRequest.ReloadPlugins); } @@ -743,7 +820,9 @@ private IAssemblyUnloadProbe PublishGeneration(AssemblyReloadSession reload) private void OnPluginActivationCandidateChanged() { if (m_disposed || !m_options.autoCompile) + { return; + } QueueReload(ScriptReloadRequest.ReloadPlugins); } @@ -759,13 +838,24 @@ private void SetCompilationProgress( { ScriptReloadProgress current = m_progress; if (m_disposed || (operationId is long expected && expected != current.operationId)) + { return; + } if (isCompilerUpdate && (!m_acceptCompilerProgress || current.cancellationRequested)) + { return; - Volatile.Write(ref m_progress, new ScriptReloadProgress(current.operationId, - Math.Clamp(fraction, 0f, 1f), stage, current.cancellationRequested || cancellationRequested, - m_activeCompilationCancellation is not null && m_activeProgressOperation == current.operationId && - (canCancel || isCompilerUpdate) && !current.cancellationRequested && !cancellationRequested)); + } + Volatile.Write( + ref m_progress, + new ScriptReloadProgress( + current.operationId, + Math.Clamp(fraction, 0f, 1f), + stage, + current.cancellationRequested || cancellationRequested, + m_activeCompilationCancellation is not null && m_activeProgressOperation == current.operationId + && (canCancel || isCompilerUpdate) && !current.cancellationRequested && !cancellationRequested + ) + ); } } @@ -776,14 +866,24 @@ private void QueueReload(ScriptReloadRequest request) { ThrowIfFaultedLocked(); if (request > m_requestedReload) + { m_requestedReload = request; + } m_lastCompileRequestTimestamp = Environment.TickCount64; - Volatile.Write(ref m_progress, new ScriptReloadProgress(++m_progressOperation, 0f, m_requestedReload switch - { - ScriptReloadRequest.ReloadPlugins => "Plugin and scripting reload queued.", - ScriptReloadRequest.ReloadScripting => "Full scripting reload queued.", - _ => "Scripting recompile queued." - }, false)); + Volatile.Write( + ref m_progress, + new ScriptReloadProgress( + ++m_progressOperation, + 0f, + m_requestedReload switch + { + ScriptReloadRequest.ReloadPlugins => "Plugin and scripting reload queued.", + ScriptReloadRequest.ReloadScripting => "Full scripting reload queued.", + _ => "Scripting recompile queued." + }, + false + ) + ); } } @@ -791,9 +891,7 @@ private ReloadPlan SelectReloadPlan(PendingReload pending) { if (pending.unavailability is not null) { - return new ReloadPlan( - Array.Empty(), - pending.unavailability.removedModuleNames); + return new ReloadPlan(Array.Empty(), pending.unavailability.removedModuleNames); } IReadOnlyList requests = pending.compilation.moduleDeployments; @@ -802,99 +900,110 @@ private ReloadPlan SelectReloadPlan(PendingReload pending) .Select(static request => request.moduleName) .ToArray(); string[] removedPlugins = pending.request == ScriptReloadRequest.ReloadPlugins - ? m_pluginModules.Keys.Except(candidatePlugins, StringComparer.Ordinal).ToArray() - : []; - if (m_runtimeScriptModule is null || m_editorScriptModule is null || - candidatePlugins.Any(plugin => !m_pluginModules.ContainsKey(plugin))) - { + ? m_pluginModules.Keys.Except(candidatePlugins, StringComparer.Ordinal).ToArray() + : []; + if (m_runtimeScriptModule is null || m_editorScriptModule is null + || candidatePlugins.Any(plugin => !m_pluginModules.ContainsKey(plugin)) + ) { return new ReloadPlan(requests, removedPlugins); } if (pending.request == ScriptReloadRequest.ReloadPlugins) + { return new ReloadPlan(requests, removedPlugins); + } if (pending.request == ScriptReloadRequest.ReloadScripting) { return new ReloadPlan( requests.Where(static request => request.domain == AssemblyDomain.InnoScripting).ToArray(), - []); + [] + ); } if (string.Equals( - pending.compilation.outputDirectory, - m_activeCompilationDirectory, - StringComparison.OrdinalIgnoreCase)) - { + pending.compilation.outputDirectory, + m_activeCompilationDirectory, + StringComparison.OrdinalIgnoreCase + )) { return new ReloadPlan([], []); } var compiled = pending.compilation.compiledAssemblyNames.ToHashSet(StringComparer.OrdinalIgnoreCase); var selected = requests - .Where(request => GetOwnedAssemblyNames(request).Any(compiled.Contains) || - !m_activeModuleFingerprints.TryGetValue( - request.moduleName, - out string? activeFingerprint) || - !string.Equals( - ComputeRequestFingerprint(request), - activeFingerprint, - StringComparison.Ordinal)) + .Where(request => ( + GetOwnedAssemblyNames(request).Any(compiled.Contains) + || !m_activeModuleFingerprints.TryGetValue(request.moduleName, out string? activeFingerprint) + || !string.Equals(ComputeRequestFingerprint(request), activeFingerprint, StringComparison.Ordinal) + )) .Select(static request => request.moduleName) .ToHashSet(StringComparer.Ordinal); - if (selected.Any(name => requests.Any(request => - request.domain == AssemblyDomain.InnoPlugin && - string.Equals(request.moduleName, name, StringComparison.Ordinal)))) - { + if (selected.Any(name => requests.Any(request => ( + request.domain == AssemblyDomain.InnoPlugin + && string.Equals(request.moduleName, name, StringComparison.Ordinal) + ))) + ) { bool changed; do { changed = false; - foreach (ScriptModuleDeployment request in requests.Where(static request => - request.domain == AssemblyDomain.InnoPlugin)) - { + foreach (ScriptModuleDeployment request in requests.Where(static request => ( + request.domain == AssemblyDomain.InnoPlugin + )) + ) { if (!selected.Contains(request.moduleName) && request.upstreamModuleNames.Any(selected.Contains)) + { changed |= selected.Add(request.moduleName); + } } } while (changed); - selected.UnionWith(requests - .Where(static request => request.domain == AssemblyDomain.InnoScripting) - .Select(static request => request.moduleName)); + selected.UnionWith( + requests + .Where(static request => request.domain == AssemblyDomain.InnoScripting) + .Select(static request => request.moduleName) + ); } // Closed generic editor extensions over project runtime types can create CLR loader // allocator dependencies in both directions even though assembly references are one-way. // Project scripts therefore retire as one authoring generation, preserving scene state // through the same candidate transaction used for runtime-source changes. - if (requests.Any(request => request.domain == AssemblyDomain.InnoScripting && - selected.Contains(request.moduleName))) - { - selected.UnionWith(requests - .Where(static request => request.domain == AssemblyDomain.InnoScripting) - .Select(static request => request.moduleName)); + if (requests.Any(request => ( + request.domain == AssemblyDomain.InnoScripting + && selected.Contains(request.moduleName) + )) + ) { + selected.UnionWith( + requests + .Where(static request => request.domain == AssemblyDomain.InnoScripting) + .Select(static request => request.moduleName) + ); } - return new ReloadPlan( - requests.Where(request => selected.Contains(request.moduleName)).ToArray(), - []); + return new ReloadPlan(requests.Where(request => selected.Contains(request.moduleName)).ToArray(), []); } private void RefreshModuleHandles() { IReadOnlyList modules = m_modules.modules; m_pluginModules.Clear(); - foreach (AssemblyModuleInfo module in modules.Where(static module => - module.domain == AssemblyDomain.InnoPlugin && - module.moduleName.StartsWith("Plugin.", StringComparison.Ordinal))) - { + foreach (AssemblyModuleInfo module in modules.Where(static module => ( + module.domain == AssemblyDomain.InnoPlugin + && module.moduleName.StartsWith("Plugin.", StringComparison.Ordinal) + )) + ) { m_pluginModules.Add(module.moduleName, module.handle); } - m_runtimeScriptModule = modules.SingleOrDefault(static module => - module.moduleName == "RuntimeScripts")?.handle; - m_editorScriptModule = modules.SingleOrDefault(static module => - module.moduleName == "EditorScripts")?.handle; + m_runtimeScriptModule = modules.SingleOrDefault(static module => module.moduleName == "RuntimeScripts")?.handle; + m_editorScriptModule = modules.SingleOrDefault(static module => module.moduleName == "EditorScripts")?.handle; } private void UpdateActiveFingerprints(ReloadPlan plan) { foreach (string removed in plan.removedModuleNames) + { m_activeModuleFingerprints.Remove(removed); + } foreach (ScriptModuleDeployment request in plan.requests) + { m_activeModuleFingerprints[request.moduleName] = ComputeRequestFingerprint(request); + } } private static IEnumerable GetOwnedAssemblyNames(ScriptModuleDeployment request) @@ -906,9 +1015,9 @@ private static string ComputeRequestFingerprint(ScriptModuleDeployment request) { using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (string path in new[] { request.mainAssemblyPath } - .Concat(request.preloadAssemblyPaths) - .OrderBy(static value => value, StringComparer.OrdinalIgnoreCase)) - { + .Concat(request.preloadAssemblyPaths) + .OrderBy(static value => value, StringComparer.OrdinalIgnoreCase) + ) { byte[] name = System.Text.Encoding.UTF8.GetBytes(System.IO.Path.GetFileName(path)); hash.AppendData(name); hash.AppendData(System.IO.File.ReadAllBytes(path)); @@ -921,38 +1030,42 @@ private void CompletePendingReload(PendingReload applied) lock (m_sync) { m_activeCompilation = applied.unavailability is null - ? applied.compilation - : null; + ? applied.compilation + : null; if (ReferenceEquals(m_pendingCompilation, applied)) + { m_pendingCompilation = null; + } } } private PluginUnavailabilityPlan? CapturePluginUnavailabilityPlan() { if (!m_plugins.hasPendingActivation || m_pluginModules.Count == 0) + { return null; + } Dictionary candidatePluginHashes = m_plugins.compilationPlugins .Where(static plugin => plugin.containsCode) .ToDictionary( static plugin => plugin.manifest.pluginId, static plugin => plugin.contentHash, - StringComparer.Ordinal); + StringComparer.Ordinal + ); var removedModuleNames = m_plugins.activePlugins .Where(static plugin => plugin.containsCode) - .Where(plugin => !candidatePluginHashes.TryGetValue( - plugin.manifest.pluginId, - out string? candidateHash) || - !string.Equals( - plugin.contentHash, - candidateHash, - StringComparison.Ordinal)) + .Where(plugin => ( + !candidatePluginHashes.TryGetValue(plugin.manifest.pluginId, out string? candidateHash) + || !string.Equals(plugin.contentHash, candidateHash, StringComparison.Ordinal) + )) .Select(static plugin => "Plugin." + plugin.manifest.pluginId) .Where(m_pluginModules.ContainsKey) .ToHashSet(StringComparer.Ordinal); if (removedModuleNames.Count == 0) + { return null; + } AssemblyModuleInfo[] activeModules = m_modules.modules.ToArray(); bool changed; @@ -961,9 +1074,9 @@ private void CompletePendingReload(PendingReload applied) changed = false; foreach (AssemblyModuleInfo module in activeModules) { - if (removedModuleNames.Contains(module.moduleName) || - !module.upstreamModuleNames.Any(removedModuleNames.Contains)) - { + if (removedModuleNames.Contains(module.moduleName) + || !module.upstreamModuleNames.Any(removedModuleNames.Contains) + ) { continue; } changed |= removedModuleNames.Add(module.moduleName); @@ -974,17 +1087,20 @@ private void CompletePendingReload(PendingReload applied) return new PluginUnavailabilityPlan( removedModuleNames .OrderBy(static moduleName => moduleName, StringComparer.Ordinal) - .ToArray()); + .ToArray() + ); } private static bool IsScriptInput(string path) - => path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) || - path.EndsWith(".iasmdef", StringComparison.OrdinalIgnoreCase); + => path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) + || path.EndsWith(".iasmdef", StringComparison.OrdinalIgnoreCase); private static bool IsPluginInput(string path) { if (string.IsNullOrWhiteSpace(path) || !IsScriptInput(path)) + { return false; + } try { return AssetPath.Parse(path).source != AssetSourceId.project; @@ -998,7 +1114,9 @@ private static bool IsPluginInput(string path) private void ThrowIfFaultedLocked() { if (m_modules.generations.state == GenerationState.Faulted) + { throw new InvalidOperationException("The generation owner is Faulted; restart the host.", m_modules.generations.failure); + } } private sealed record PendingReload( @@ -1015,8 +1133,7 @@ private sealed record ReloadPlan( IReadOnlyList removedModuleNames ); - private sealed class ScriptProgressObserver(Action report) - : IProgress + private sealed class ScriptProgressObserver(Action report) : IProgress { /// /// Publishes one progress update to the receiving workflow. diff --git a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadOptions.cs b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadOptions.cs index 8cccdbcef..de6204898 100644 --- a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadOptions.cs +++ b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadOptions.cs @@ -1,4 +1,5 @@ using System; + namespace Inno.Scripting.Reload; /// diff --git a/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs b/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs index 31c9592c7..778111b93 100644 --- a/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs +++ b/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs @@ -50,14 +50,17 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", AudioClipMetadataCodec.Encode(metadata), - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); await output.WriteArtifactAsync("audio-data", context.sourceBytes, cancellationToken).ConfigureAwait(false); } private static AudioClipMetadata ReadWav(ReadOnlySpan bytes) { if (bytes.Length < 12 || !bytes[..4].SequenceEqual("RIFF"u8) || !bytes[8..12].SequenceEqual("WAVE"u8)) + { throw new InvalidDataException("The WAV source has an invalid RIFF header."); + } int channels = 0; int sampleRate = 0; @@ -69,20 +72,28 @@ private static AudioClipMetadata ReadWav(ReadOnlySpan bytes) ReadOnlySpan chunkId = bytes.Slice(offset, 4); uint chunkLengthValue = BinaryPrimitives.ReadUInt32LittleEndian(bytes.Slice(offset + 4, 4)); if (chunkLengthValue > int.MaxValue) + { throw new InvalidDataException("The WAV source contains an oversized chunk."); + } int chunkLength = (int)chunkLengthValue; int chunkStart = checked(offset + 8); int chunkEnd = checked(chunkStart + chunkLength); if (chunkEnd > bytes.Length) + { throw new InvalidDataException("The WAV source contains a truncated chunk."); + } if (chunkId.SequenceEqual("fmt "u8)) { if (chunkLength < 16) + { throw new InvalidDataException("The WAV format chunk is truncated."); + } ushort format = BinaryPrimitives.ReadUInt16LittleEndian(bytes.Slice(chunkStart, 2)); if (format is not 1 and not 3 and not 0xfffe) + { throw new InvalidDataException($"The WAV format code '{format}' is not supported."); + } channels = BinaryPrimitives.ReadUInt16LittleEndian(bytes.Slice(chunkStart + 2, 2)); sampleRate = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(bytes.Slice(chunkStart + 4, 4))); blockAlignment = BinaryPrimitives.ReadUInt16LittleEndian(bytes.Slice(chunkStart + 12, 2)); @@ -96,19 +107,18 @@ private static AudioClipMetadata ReadWav(ReadOnlySpan bytes) } if (channels <= 0 || sampleRate <= 0 || blockAlignment <= 0 || dataLength < 0) + { throw new InvalidDataException("The WAV source is missing valid format or data chunks."); - return new AudioClipMetadata( - AudioCodecId.wav, - channels, - sampleRate, - dataLength / blockAlignment, - bytes.Length); + } + return new AudioClipMetadata(AudioCodecId.wav, channels, sampleRate, dataLength / blockAlignment, bytes.Length); } private static AudioClipMetadata ReadFlac(ReadOnlySpan bytes) { if (bytes.Length < 42 || !bytes[..4].SequenceEqual("fLaC"u8)) + { throw new InvalidDataException("The FLAC source has an invalid stream marker."); + } int offset = 4; bool foundStreamInfo = false; int channels = 0; @@ -122,11 +132,15 @@ private static AudioClipMetadata ReadFlac(ReadOnlySpan bytes) int dataStart = checked(offset + 4); int dataEnd = checked(dataStart + length); if (dataEnd > bytes.Length) + { throw new InvalidDataException("The FLAC source contains a truncated metadata block."); + } if (blockType == 0) { if (foundStreamInfo || length != 34) + { throw new InvalidDataException("The FLAC STREAMINFO block is invalid."); + } ReadOnlySpan packed = bytes.Slice(dataStart + 10, 8); ulong value = BinaryPrimitives.ReadUInt64BigEndian(packed); sampleRate = (int)((value >> 44) & 0xfffff); @@ -136,10 +150,14 @@ private static AudioClipMetadata ReadFlac(ReadOnlySpan bytes) } offset = dataEnd; if ((header & 0x80) != 0) + { break; + } } if (!foundStreamInfo || channels <= 0 || sampleRate <= 0 || frameCount <= 0) + { throw new InvalidDataException("The FLAC source is missing valid STREAMINFO metadata."); + } return new AudioClipMetadata(AudioCodecId.flac, channels, sampleRate, frameCount, bytes.Length); } @@ -163,7 +181,9 @@ private static AudioClipMetadata ReadMp3(ReadOnlySpan bytes) break; } if (offset + frameLength > bytes.Length) + { throw new InvalidDataException("The MP3 source contains a truncated audio frame."); + } sampleRate = frameSampleRate; channels = frameChannels; frameCount += samples; @@ -171,23 +191,31 @@ private static AudioClipMetadata ReadMp3(ReadOnlySpan bytes) offset += frameLength; } if (encodedFrameCount == 0) + { throw new InvalidDataException("The MP3 source contains no valid Layer III frame."); + } return new AudioClipMetadata(AudioCodecId.mp3, channels, sampleRate, frameCount, bytes.Length); } private static int SkipId3(ReadOnlySpan bytes) { if (bytes.Length < 10 || !bytes[..3].SequenceEqual("ID3"u8)) + { return 0; + } for (int index = 6; index < 10; index++) { if ((bytes[index] & 0x80) != 0) + { throw new InvalidDataException("The MP3 ID3 size is invalid."); + } } int size = (bytes[6] << 21) | (bytes[7] << 14) | (bytes[8] << 7) | bytes[9]; int offset = checked(10 + size); if (offset > bytes.Length) + { throw new InvalidDataException("The MP3 ID3 tag is truncated."); + } return offset; } @@ -203,21 +231,29 @@ out int channels samples = 0; channels = 0; if ((header & 0xffe00000) != 0xffe00000) + { return false; + } int mpegBits = (int)((header >> 19) & 0x3); int layerBits = (int)((header >> 17) & 0x3); int bitrateIndex = (int)((header >> 12) & 0xf); int sampleRateIndex = (int)((header >> 10) & 0x3); if (mpegBits == 1 || layerBits != 1 || bitrateIndex is 0 or 15 || sampleRateIndex == 3) + { return false; + } int[] sampleRates = [44100, 48000, 32000]; sampleRate = sampleRates[sampleRateIndex]; bool mpegOne = mpegBits == 3; if (mpegBits == 2) + { sampleRate /= 2; + } else if (mpegBits == 0) + { sampleRate /= 4; + } int[] mpegOneBitrates = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]; int[] lowerBitrates = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; int bitrate = (mpegOne ? mpegOneBitrates : lowerBitrates)[bitrateIndex]; diff --git a/src/services/audio/Inno.Audio.Runtime/AudioClipCache.cs b/src/services/audio/Inno.Audio.Runtime/AudioClipCache.cs index 8db5397f3..d7d2e4743 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioClipCache.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioClipCache.cs @@ -41,9 +41,13 @@ internal ValueTask PreloadAsync( ArgumentNullException.ThrowIfNull(clip); cancellationToken.ThrowIfCancellationRequested(); if (!Enum.IsDefined(loadMode)) + { throw new ArgumentOutOfRangeException(nameof(loadMode)); + } if (m_preloads.Count >= m_options.maxPendingPreloads) + { throw new InvalidOperationException("Audio preload waiters are at capacity; retry after an update safety point."); + } var request = new AudioClipRequest(clip, m_artifacts); Exception? preparationFailure = null; try @@ -67,80 +71,105 @@ internal ValueTask PreloadAsync( } catch (Exception cleanup) when (preparationFailure is not null) { - throw new AggregateException("Audio preload preparation and request retirement failed.", - preparationFailure, cleanup); + throw new AggregateException( + "Audio preload preparation and request retirement failed.", + preparationFailure, + cleanup + ); } } } + internal void ReleasePreload(AudioClipAsset clip) { ArgumentNullException.ThrowIfNull(clip); - ClipCacheEntry? retiring = m_clips.Values.FirstOrDefault(entry => - entry.key.persistentId == clip.identity.persistentId && entry.isRetiring); + ClipCacheEntry? retiring = m_clips.Values.FirstOrDefault(entry => ( + entry.key.persistentId == clip.identity.persistentId && entry.isRetiring + )); if (retiring is not null) { TryReleaseClip(retiring); return; } ClipCacheEntry? entry = m_clips - .Where(pair => pair.Key.persistentId == clip.identity.persistentId && - pair.Value.preloadReferences > pair.Value.pendingPreloadReferences) + .Where(pair => ( + pair.Key.persistentId == clip.identity.persistentId + && pair.Value.preloadReferences > pair.Value.pendingPreloadReferences + )) .Select(static pair => pair.Value) .FirstOrDefault(); if (entry is null) + { return; + } entry.preloadReferences--; TryReleaseClip(entry); } + internal ClipCacheEntry GetOrCreateClip( AudioClipRequest clip, AudioClipLoadMode requestedMode ) { AudioClipMetadata metadata = clip.metadata - ?? throw new InvalidOperationException("The audio clip has no imported runtime metadata."); + ?? throw new InvalidOperationException("The audio clip has no imported runtime metadata."); AssetArtifactInfo artifact = clip.artifact; AudioClipLoadMode resolvedMode = requestedMode == AudioClipLoadMode.Automatic - ? (artifact.length >= m_options.automaticStreamingThresholdBytes || - WouldExceedDecodedBudget(EstimateDecodedByteLength(metadata, artifact.length)) - ? AudioClipLoadMode.Stream - : AudioClipLoadMode.Decode) - : requestedMode; + ? (artifact.length >= m_options.automaticStreamingThresholdBytes + || WouldExceedDecodedBudget(EstimateDecodedByteLength(metadata, artifact.length)) + ? AudioClipLoadMode.Stream + : AudioClipLoadMode.Decode) + : requestedMode; var key = new ClipCacheKey(clip.persistentId, clip.contentVersion, artifact.key, resolvedMode); if (m_clips.TryGetValue(key, out ClipCacheEntry? cached)) { if (!cached.isRetiring) + { return cached; + } TryReleaseClip(cached); } long decodedByteLength = resolvedMode == AudioClipLoadMode.Decode - ? EstimateDecodedByteLength(metadata, artifact.length) - : 0; + ? EstimateDecodedByteLength(metadata, artifact.length) + : 0; if (resolvedMode == AudioClipLoadMode.Decode && WouldExceedDecodedBudget(decodedByteLength)) { throw new InvalidOperationException( - $"Decoded audio clip '{clip.assetPath}' exceeds the configured cache budget."); + $"Decoded audio clip '{clip.assetPath}' exceeds the configured cache budget." + ); } - AudioClipHandle handle = m_device.CreateClip(new AudioClipDescriptor( - metadata.codec, - resolvedMode, - metadata.channels, - metadata.sampleRate, - metadata.frameCount, - artifact.length), clip.source); + AudioClipHandle handle = m_device.CreateClip( + new AudioClipDescriptor( + metadata.codec, + resolvedMode, + metadata.channels, + metadata.sampleRate, + metadata.frameCount, + artifact.length + ), + clip.source + ); if (!handle.isValid) + { throw new InvalidOperationException("The audio backend rejected clip creation."); + } var entry = new ClipCacheEntry(key, handle, decodedByteLength, clip.TakeArtifact(), m_device); m_clips.Add(key, entry); return entry; } + internal void TryReleaseClip(ClipCacheEntry entry) { if (entry.preloadReferences > 0 || entry.voiceReferences > 0) + { return; + } entry.Dispose(); if (m_clips.TryGetValue(entry.key, out ClipCacheEntry? current) && ReferenceEquals(current, entry)) + { m_clips.Remove(entry.key); + } } + internal void CompletePreloads() { for (int index = m_preloads.Count - 1; index >= 0; index--) @@ -151,12 +180,16 @@ internal void CompletePreloads() AudioClipState state = m_device.GetClipState(pending.clip.handle); pending.canceled = pending.cancellationToken.IsCancellationRequested; if (!pending.canceled && state == AudioClipState.Preparing) + { continue; + } pending.failed = state == AudioClipState.Failed; pending.completing = true; pending.clip.pendingPreloadReferences--; if (pending.canceled || pending.failed) + { pending.clip.preloadReferences--; + } } if (pending.canceled || pending.failed) { @@ -164,9 +197,13 @@ internal void CompletePreloads() { TryReleaseClip(pending.clip); if (pending.canceled) + { pending.completion.TrySetCanceled(pending.cancellationToken); + } else + { pending.completion.TrySetException(new InvalidOperationException("Native audio preparation failed.")); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -180,18 +217,23 @@ internal void CompletePreloads() } } else + { pending.completion.TrySetResult(); + } m_preloads.RemoveAt(index); } DrainRetiringClips(); } + /// /// Cancels waiters and releases every native clip and immutable artifact owned by this device cache. /// public void Dispose() { foreach (PendingPreload preload in m_preloads) + { preload.completion.TrySetCanceled(); + } m_preloads.Clear(); foreach (ClipCacheEntry clip in m_clips.Values.ToArray()) { @@ -217,6 +259,7 @@ public void Dispose() throw new AggregateException("Audio cache retirement failed after every clip and artifact was attempted.", failures); } } + private ValueTask PreparePreload( AudioClipRequest request, AudioClipLoadMode loadMode, @@ -228,7 +271,9 @@ CancellationToken cancellationToken { state = m_device.GetClipState(entry.handle); if (state == AudioClipState.Failed) + { throw new InvalidOperationException("Native audio clip preparation failed."); + } } catch (Exception failure) { @@ -248,24 +293,33 @@ CancellationToken cancellationToken } entry.preloadReferences++; if (state == AudioClipState.Ready) + { return ValueTask.CompletedTask; + } var pending = new PendingPreload(entry, cancellationToken); entry.pendingPreloadReferences++; m_preloads.Add(pending); return new ValueTask(pending.completion.Task); } + private void DrainRetiringClips() { foreach (ClipCacheEntry clip in m_clips.Values.Where(static clip => clip.isRetiring).ToArray()) + { TryReleaseClip(clip); + } } + private bool WouldExceedDecodedBudget(long additionalBytes) { if (additionalBytes > m_options.decodedCacheBudgetBytes) + { return true; + } long currentBytes = m_clips.Values.Sum(static clip => clip.decodedByteLength); return currentBytes > m_options.decodedCacheBudgetBytes - additionalBytes; } + private static long EstimateDecodedByteLength( AudioClipMetadata metadata, long encodedByteLength @@ -280,12 +334,14 @@ long encodedByteLength return long.MaxValue; } } + internal readonly record struct ClipCacheKey( Guid persistentId, long contentVersion, AssetArtifactKey artifactKey, AudioClipLoadMode loadMode ); + internal sealed class ClipCacheEntry : IDisposable { private readonly LifetimeScope m_lifetime = new(); @@ -321,6 +377,7 @@ public void Dispose() internal int pendingPreloadReferences { get; set; } internal int voiceReferences { get; set; } } + private sealed class NativeClipRetirement( IAudioDevice device, AudioClipHandle handle @@ -332,9 +389,12 @@ AudioClipHandle handle public void Dispose() { if (!device.DestroyClip(handle)) + { throw new InvalidOperationException("The audio backend refused clip retirement."); + } } } + private sealed class PendingPreload( ClipCacheEntry clip, CancellationToken cancellationToken diff --git a/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs b/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs index 967a4474d..5cad8fd2b 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs @@ -20,7 +20,9 @@ IAssetArtifactLookup artifacts try { if (clip.isMissing || metadata is null) + { throw new InvalidOperationException("The audio clip or its imported metadata is missing."); + } m_artifact = artifacts.AcquireArtifact(persistentId, "audio-data"); } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) @@ -37,11 +39,16 @@ IAssetArtifactLookup artifacts internal long contentVersion { get; } internal AssetPath assetPath { get; } internal AudioClipMetadata? metadata { get; } - internal AssetArtifactInfo artifact => m_artifact?.info - ?? throw new InvalidOperationException(m_failure ?? "The clip artifact was transferred or released."); - internal IAudioClipSource source => new ArtifactAudioClipSource(m_artifact - ?? throw new InvalidOperationException(m_failure ?? "The clip artifact was transferred or released.")); + internal AssetArtifactInfo artifact + => m_artifact?.info + ?? throw new InvalidOperationException(m_failure ?? "The clip artifact was transferred or released."); + + internal IAudioClipSource source + => new ArtifactAudioClipSource( + m_artifact + ?? throw new InvalidOperationException(m_failure ?? "The clip artifact was transferred or released.") + ); internal ArtifactLease TakeArtifact() { diff --git a/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs b/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs index 1b7719328..632481d7f 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs @@ -45,15 +45,21 @@ int capacity public void Dispose() { if (m_listener.isValid) + { _ = m_device.DestroyListener(m_listener); + } m_listener = default; m_listenerId = Guid.Empty; m_emitters.Clear(); foreach (string id in m_providerDiagnosticIds) + { m_diagnostics.Resolve("AUDIO_CONTENT_PROVIDER_FAILED", id); + } m_providerDiagnosticIds.Clear(); if (m_listenerDiagnosticId != Guid.Empty) + { m_diagnostics.Resolve("AUDIO_LISTENER_PRIORITY_TIE", m_listenerDiagnosticId.ToString("D")); + } m_listenerDiagnosticId = Guid.Empty; } @@ -77,7 +83,8 @@ float deltaTime "AUDIO_CONTENT_SCOPE_FAILED", $"The host audio content scope failed; an empty scope is used for this update: {exception.Message}", DiagnosticSeverity.Error, - "AudioRuntime"); + "AudioRuntime" + ); content = ContentReadScope.empty; } using ContentReadScope contentScope = content; @@ -86,8 +93,9 @@ float deltaTime var ids = new HashSet(); int rejectedProviders = 0; foreach (string retiredId in m_providerDiagnosticIds - .Where(id => !providers.providers.Any(entry => entry.id == id)).ToArray()) - { + .Where(id => !providers.providers.Any(entry => entry.id == id)) + .ToArray() + ) { m_diagnostics.Resolve("AUDIO_CONTENT_PROVIDER_FAILED", retiredId); m_providerDiagnosticIds.Remove(retiredId); } @@ -99,9 +107,11 @@ float deltaTime entry.provider.Submit(context); IReadOnlyList contributionEmitters = context.emitters; IReadOnlyList contributionListeners = context.listeners; - if (contributionEmitters.Any(emitter => ids.Contains(emitter.id)) || - contributionListeners.Any(listener => ids.Contains(listener.id))) + if (contributionEmitters.Any(emitter => ids.Contains(emitter.id)) + || contributionListeners.Any(listener => ids.Contains(listener.id)) + ) { throw new ArgumentException("The contribution repeats an identity already accepted from another provider."); + } foreach (AudioEmitterSnapshot emitter in contributionEmitters) { ids.Add(emitter.id); @@ -127,7 +137,8 @@ float deltaTime "AUDIO_CONTENT_PROVIDER_FAILED", $"Audio content provider '{entry.id}' was isolated for this update: {exception.Message}", DiagnosticSeverity.Error, - entry.id); + entry.id + ); } } statistics = new AudioContentStatistics(m_capacity, ids.Count, rejectedProviders); @@ -144,20 +155,23 @@ private void SynchronizeEmitters(IReadOnlyList snapshots) if (!snapshot.shouldPlay) { if (m_emitters.Remove(snapshot.id, out EmitterRecord? inactive)) + { _ = m_voices.Stop(inactive.voice); + } continue; } if (m_emitters.TryGetValue(snapshot.id, out EmitterRecord? current)) { - if (current.clipId != snapshot.clip.identity.persistentId || - current.contentVersion != snapshot.clip.contentVersion || - current.playbackRevision != snapshot.playbackRevision) - { + if (current.clipId != snapshot.clip.identity.persistentId + || current.contentVersion != snapshot.clip.contentVersion + || current.playbackRevision != snapshot.playbackRevision + ) { _ = m_voices.Stop(current.voice); current = new EmitterRecord( snapshot.clip, snapshot.playbackRevision, - m_voices.Play(snapshot.clip, snapshot.options)); + m_voices.Play(snapshot.clip, snapshot.options) + ); m_emitters[snapshot.id] = current; } else @@ -168,13 +182,16 @@ private void SynchronizeEmitters(IReadOnlyList snapshots) snapshot.options.volume, snapshot.options.pitch, snapshot.options.pan, - snapshot.options.spatial)); + snapshot.options.spatial + ) + ); } continue; } m_emitters.Add( snapshot.id, - new EmitterRecord(snapshot.clip, snapshot.playbackRevision, m_voices.Play(snapshot.clip, snapshot.options))); + new EmitterRecord(snapshot.clip, snapshot.playbackRevision, m_voices.Play(snapshot.clip, snapshot.options)) + ); } foreach (Guid id in m_emitters.Keys.Where(id => !seen.Contains(id)).ToArray()) { @@ -198,7 +215,9 @@ private void SynchronizeListener(IReadOnlyList snapshots) if (active.Length == 0) { if (m_listener.isValid) + { _ = m_device.DestroyListener(m_listener); + } m_listener = default; m_listenerId = Guid.Empty; return; @@ -211,12 +230,15 @@ private void SynchronizeListener(IReadOnlyList snapshots) "AUDIO_LISTENER_PRIORITY_TIE", "Multiple active listeners share the highest priority; stable identity selected the winner.", DiagnosticSeverity.Warning, - selected.id.ToString("D")); + selected.id.ToString("D") + ); } if (!m_listener.isValid || m_listenerId != selected.id) { if (m_listener.isValid) + { _ = m_device.DestroyListener(m_listener); + } m_listener = m_device.CreateListener(selected.state); m_listenerId = selected.id; return; @@ -240,6 +262,5 @@ private void Publish( string message, DiagnosticSeverity severity, string? source - ) - => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); + ) => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs b/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs index b2179e401..4fc0a42d2 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs @@ -52,7 +52,9 @@ public void Dispose() } m_device = null; if (m_failures.Count == 0) + { return; + } Exception[] failures = m_failures.ToArray(); m_failures.Clear(); throw new AggregateException("Audio candidate retirement failed after every owner was attempted.", failures); diff --git a/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs b/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs index f779b92da..09b7d4f83 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs @@ -12,9 +12,7 @@ internal sealed class AudioExtensionRegistry : TypeRegistry current; @@ -40,7 +38,9 @@ internal void Fault(Exception exception) internal void EnsureHealthy() { if (m_retirementFailure is not null) + { throw new InvalidOperationException("The audio generation owner is Faulted and requires a host restart.", m_retirementFailure); + } } /// @@ -76,15 +76,15 @@ protected override Snapshot Build(TypeCacheSnapshot types) Discover(types, static value => value.id, "mixer"), Discover(types, static value => value.id, "mixer feature"), Discover(types, static value => value.id, "content provider"), - CreateExtension); + CreateExtension + ); } private static Dictionary Discover( TypeCacheSnapshot types, Func getId, string kind - ) - where TAttribute : Attribute + ) where TAttribute : Attribute { var result = new Dictionary(StringComparer.Ordinal); foreach (TypeRef typeRef in types.GetTypesWithAttribute()) @@ -93,7 +93,8 @@ string kind if (type.IsAbstract || !typeof(TContract).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Audio {kind} '{type.FullName}' must be a non-abstract {typeof(TContract).FullName}."); + $"Audio {kind} '{type.FullName}' must be a non-abstract {typeof(TContract).FullName}." + ); } if (!types.CanCreateInstance(typeRef)) { @@ -104,7 +105,8 @@ string kind if (!result.TryAdd(id, type)) { throw new InvalidOperationException( - $"Audio {kind} ID '{id}' is declared by both '{result[id].FullName}' and '{type.FullName}'."); + $"Audio {kind} ID '{id}' is declared by both '{result[id].FullName}' and '{type.FullName}'." + ); } } return result; @@ -185,9 +187,13 @@ out AudioMixer? mixer foreach (AudioMixerFeatureConfiguration configuration in asset.features) { if (!configuration.enabled) + { continue; + } if (string.IsNullOrWhiteSpace(configuration.featureTypeId) || !configured.Add(configuration.featureTypeId)) + { throw new InvalidOperationException("Enabled audio mixer features require unique stable identifiers."); + } if (!m_features.TryGetValue(configuration.featureTypeId, out Type? featureType)) { mixer = null; @@ -199,7 +205,8 @@ out AudioMixer? mixer return true; } - private TContract Create(Type type) where TContract : class + private TContract Create(Type type) + where TContract : class { try { @@ -224,7 +231,9 @@ IReadOnlyList providers this.typeCacheVersion = typeCacheVersion; this.providers = Array.AsReadOnly(providers.ToArray()); foreach (ProviderEntry entry in providers) + { m_lifetime.Own(entry.provider); + } } internal long typeCacheVersion { get; } @@ -237,7 +246,9 @@ IReadOnlyList providers public void Dispose() { if (m_disposed) + { return; + } try { m_lifetime.Dispose(); diff --git a/src/services/audio/Inno.Audio.Runtime/AudioMixerOwner.cs b/src/services/audio/Inno.Audio.Runtime/AudioMixerOwner.cs index 1f911d93c..34da8d4c3 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioMixerOwner.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioMixerOwner.cs @@ -1,7 +1,7 @@ using System; -using Inno.Core.Execution; using System.Collections.Generic; using System.Linq; +using Inno.Core.Execution; namespace Inno.Audio.Runtime; @@ -22,8 +22,7 @@ internal AudioMixerOwner( IAudioDevice device, Action retirementFailed, Action retire - ) - : this(device, new AudioMixerBuilder().Build(), null, false, retirementFailed, retire) { } + ) : this(device, new AudioMixerBuilder().Build(), null, false, retirementFailed, retire) {} private AudioMixerOwner( IAudioDevice device, @@ -39,11 +38,14 @@ Action retire m_activeMixer = mixer; m_suspended = suspended; foreach ((AudioBusId id, AudioBusHandle handle) in CreateBusSet(device, mixer, controls)) + { m_buses.Add(id, handle); + } foreach (AudioBusDefinition bus in mixer.buses) { BusControlState state = controls is not null && controls.TryGetValue(bus.id, out BusControlState? current) - ? current : new BusControlState(bus.volume, bus.muted, paused: false); + ? current + : new BusControlState(bus.volume, bus.muted, paused: false); m_busControls.Add(bus.id, new BusControlState(state.volume, state.muted, state.paused)); } } @@ -60,10 +62,10 @@ internal bool SetBusVolume( AudioBusId bus, float volume ) { - if (volume < 0f || !float.IsFinite(volume) || - !m_buses.TryGetValue(bus, out AudioBusHandle handle) || - !m_device.SetBusVolume(handle, volume)) - { + if (volume < 0f || !float.IsFinite(volume) + || !m_buses.TryGetValue(bus, out AudioBusHandle handle) + || !m_device.SetBusVolume(handle, volume) + ) { return false; } m_busControls[bus].volume = volume; @@ -75,7 +77,9 @@ internal bool SetBusMuted( bool muted ) { if (!m_buses.TryGetValue(bus, out AudioBusHandle handle) || !m_device.SetBusMuted(handle, muted)) + { return false; + } m_busControls[bus].muted = muted; return true; } @@ -84,9 +88,11 @@ internal bool SetBusPaused( AudioBusId bus, bool paused ) { - if (!m_buses.TryGetValue(bus, out AudioBusHandle handle) || - !m_device.SetBusPaused(handle, paused || bus == AudioBusId.master && m_suspended)) + if (!m_buses.TryGetValue(bus, out AudioBusHandle handle) + || !m_device.SetBusPaused(handle, paused || bus == AudioBusId.master && m_suspended) + ) { return false; + } m_busControls[bus].paused = paused; return true; } @@ -94,7 +100,9 @@ bool paused internal void SetSuspended(bool suspended) { if (suspended == m_suspended) + { return; + } var masters = new List>(m_retiredMasterPauses) { new(m_buses[AudioBusId.master], m_busControls[AudioBusId.master].paused) @@ -105,7 +113,9 @@ internal void SetSuspended(bool suspended) foreach ((AudioBusHandle handle, bool paused) in masters) { if (!m_device.SetBusPaused(handle, paused || suspended)) + { throw new InvalidOperationException("The audio backend rejected application suspension."); + } applied++; } } @@ -118,7 +128,9 @@ internal void SetSuspended(bool suspended) { KeyValuePair master = masters[index]; if (!m_device.SetBusPaused(master.Key, master.Value || m_suspended)) + { throw new InvalidOperationException("The audio backend rejected suspension rollback."); + } } catch (Exception rollback) { @@ -149,10 +161,14 @@ IEnumerable usedBuses } m_buses.Clear(); foreach ((AudioBusId id, AudioBusHandle handle) in candidate) + { m_buses.Add(id, handle); + } m_busControls.Clear(); foreach (AudioBusDefinition bus in mixer.buses) + { m_busControls.Add(bus.id, new BusControlState(bus.volume, bus.muted, paused: false)); + } m_activeMixer = mixer; } @@ -163,7 +179,9 @@ internal void CollectRetiredBuses(IEnumerable usedBuses) { Dictionary retired = m_retiredBuses[index]; if (retired.Values.Any(retained.Contains)) + { continue; + } try { AudioBusHandle master = retired[AudioBusId.master]; @@ -215,7 +233,9 @@ public void Dispose() m_busControls.Clear(); m_retiredMasterPauses.Clear(); if (m_retirementFailures.Count == 0) + { return; + } Exception[] failures = m_retirementFailures.ToArray(); m_retirementFailures.Clear(); throw new AggregateException("Audio mixer retirement failed after every graph was attempted.", failures); @@ -232,26 +252,30 @@ private IReadOnlyDictionary CreateBusSet( foreach (AudioBusDefinition bus in mixer.buses) { AudioBusHandle parent = bus.parent is AudioBusId parentId - ? candidate[parentId] - : default; + ? candidate[parentId] + : default; AudioBusHandle handle = device.CreateBus(bus.id, parent); if (!handle.isValid) + { throw new InvalidOperationException($"The backend rejected audio bus '{bus.id}'."); + } candidate.Add(bus.id, handle); BusControlState state = controls is not null && controls.TryGetValue(bus.id, out BusControlState? current) - ? current - : new BusControlState(bus.volume, bus.muted, paused: false); - if (!device.SetBusVolume(handle, state.volume) || - !device.SetBusMuted(handle, state.muted) || - (state.paused || bus.id == AudioBusId.master && m_suspended) && - !device.SetBusPaused(handle, paused: true)) - { + ? current + : new BusControlState(bus.volume, bus.muted, paused: false); + if (!device.SetBusVolume(handle, state.volume) + || !device.SetBusMuted(handle, state.muted) + || (state.paused || bus.id == AudioBusId.master && m_suspended) + && !device.SetBusPaused(handle, paused: true) + ) { throw new InvalidOperationException($"The backend rejected parameters for audio bus '{bus.id}'."); } foreach (AudioProcessorConfiguration processor in bus.processors) { if (!device.AddBusProcessor(handle, processor)) + { throw new InvalidOperationException($"The backend rejected processor '{processor.id}'."); + } } } return candidate; @@ -285,7 +309,9 @@ Dictionary buses try { if (!device.DestroyBus(bus)) + { throw new InvalidOperationException("The backend refused audio bus retirement."); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -298,7 +324,9 @@ Dictionary buses buses.Remove(id); } if (failures.Count > 0) + { throw new AggregateException("Audio bus retirement failed after every bus was attempted.", failures); + } } private sealed class BusControlState( diff --git a/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs b/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs index 0ca7665c4..eda109bdb 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs @@ -1,15 +1,15 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Inno.Assets; +using Inno.Core.Diagnostics; using Inno.Core.Events; +using Inno.Core.Execution; using Inno.Extensibility.Types; +using Inno.References; +using Inno.Runtime.Contracts; namespace Inno.Audio.Runtime; @@ -108,7 +108,16 @@ public AudioRuntime( m_extensions.Dispose(); throw; } - m_voices = new AudioVoiceOwner(m_device, m_artifacts, m_clipCache, m_mixer, m_events, m_diagnostics, m_options, m_extensions.RetireBackend); + m_voices = new AudioVoiceOwner( + m_device, + m_artifacts, + m_clipCache, + m_mixer, + m_events, + m_diagnostics, + m_options, + m_extensions.RetireBackend + ); m_content = new AudioContentOwner(m_device, m_voices, m_diagnostics, m_contentScopeProvider, m_options.maxContentSnapshots); if (m_device.state == AudioDeviceState.Muted) { @@ -116,7 +125,8 @@ public AudioRuntime( "AUDIO_NO_DEVICE", "Audio is running in explicit muted mode because no output device is active.", DiagnosticSeverity.Warning, - m_device.GetType().FullName); + m_device.GetType().FullName + ); } } @@ -140,6 +150,7 @@ protected override void OnStart() { m_events.dispatched += OnEventDispatched; } + /// /// Captures snapshots and binds service façades. /// @@ -147,6 +158,7 @@ protected override void OnStart() /// The variable frame timing. /// protected override void OnBeginFrame(RuntimeFrame frame) => OwnFrameScope(EnterExecutionScope()); + /// /// Advances domain state on the variable clock. /// @@ -159,11 +171,7 @@ protected override void OnStart() /// Gets current runtime resource statistics. /// public AudioStatistics statistics - => new( - m_voices.count, - m_clipCache.count, - m_clipCache.decodedBytes, - m_stolenVoiceCount + m_voices.stolenCount); + => new(m_voices.count, m_clipCache.count, m_clipCache.decodedBytes, m_stolenVoiceCount + m_voices.stolenCount); /// /// Gets bounded provider admission counts from the most recent content collection on this device generation. @@ -240,7 +248,9 @@ public AudioVoiceHandle PlayScheduled( AudioPlayOptions options ) { if (double.IsNaN(scheduledDspTime) || double.IsInfinity(scheduledDspTime) || scheduledDspTime < 0d) + { throw new ArgumentOutOfRangeException(nameof(scheduledDspTime)); + } EnsureActive(); return m_voices.Play(clip, options, scheduledDspTime); } @@ -473,7 +483,8 @@ public bool ApplyMixer(AudioMixerAsset asset) "AUDIO_MIXER_EXTENSION_MISSING", "The candidate audio mixer references an unavailable extension; the last-good mixer remains active.", DiagnosticSeverity.Error, - asset.mixerTypeId); + asset.mixerTypeId + ); return false; } m_mixer.Install(mixer, m_voices.usedBuses); @@ -486,7 +497,8 @@ public bool ApplyMixer(AudioMixerAsset asset) "AUDIO_MIXER_CANDIDATE_FAILED", $"The candidate audio mixer failed validation; the last-good mixer remains active: {exception.Message}", DiagnosticSeverity.Error, - asset.mixerTypeId); + asset.mixerTypeId + ); return false; } } @@ -508,7 +520,9 @@ public void ReplaceDevice(IAudioDevice replacement) EnsureActive(); ArgumentNullException.ThrowIfNull(replacement); if (ReferenceEquals(replacement, m_device)) + { throw new ArgumentException("The replacement must be a different device instance.", nameof(replacement)); + } AudioMixerOwner replacementMixer; m_candidateRetirement = new AudioDeviceCandidate(replacement); try @@ -566,7 +580,17 @@ public void ReplaceDevice(IAudioDevice replacement) m_device = replacement; m_clipCache = new AudioClipCache(m_device, m_artifacts, m_options, m_extensions.RetireBackend); m_mixer = replacementMixer; - m_voices = new AudioVoiceOwner(m_device, m_artifacts, m_clipCache, m_mixer, m_events, m_diagnostics, m_options, m_extensions.RetireBackend, m_voices); + m_voices = new AudioVoiceOwner( + m_device, + m_artifacts, + m_clipCache, + m_mixer, + m_events, + m_diagnostics, + m_options, + m_extensions.RetireBackend, + m_voices + ); m_content = new AudioContentOwner(m_device, m_voices, m_diagnostics, m_contentScopeProvider, m_options.maxContentSnapshots); m_deviceRecoveryElapsed = 0f; m_deviceLossReported = false; @@ -590,13 +614,15 @@ public bool TryRecoverDevice(Func deviceFactory) EnsureActive(); ArgumentNullException.ThrowIfNull(deviceFactory); if (m_device.state == AudioDeviceState.Ready) + { return true; + } IAudioDevice? candidate = null; try { candidate = deviceFactory() - ?? throw new InvalidOperationException("The audio recovery factory returned null."); + ?? throw new InvalidOperationException("The audio recovery factory returned null."); if (candidate.state != AudioDeviceState.Ready) { IAudioDevice rejected = candidate; @@ -614,7 +640,8 @@ public bool TryRecoverDevice(Func deviceFactory) "AUDIO_DEVICE_RECOVERY_FAILED", "The replacement audio device did not reach the ready state; muted playback remains active.", DiagnosticSeverity.Warning, - "AudioRuntime"); + "AudioRuntime" + ); return false; } string? recoveredSource = candidate.GetType().FullName; @@ -625,7 +652,8 @@ public bool TryRecoverDevice(Func deviceFactory) "AUDIO_DEVICE_RECOVERED", "The audio output device recovered with a new generation.", DiagnosticSeverity.Info, - recoveredSource); + recoveredSource + ); return true; } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) @@ -637,7 +665,9 @@ public bool TryRecoverDevice(Func deviceFactory) try { if (candidate is not null) + { m_extensions.RetireBackend(candidate.Dispose); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -653,7 +683,8 @@ public bool TryRecoverDevice(Func deviceFactory) "AUDIO_DEVICE_RECOVERY_FAILED", $"The audio output recovery candidate failed; muted playback remains active: {exception.Message}", DiagnosticSeverity.Warning, - "AudioRuntime"); + "AudioRuntime" + ); return false; } } @@ -671,7 +702,9 @@ public void Update(float deltaTime) { EnsureActive(); if (!float.IsFinite(deltaTime) || deltaTime < 0f) + { throw new ArgumentOutOfRangeException(nameof(deltaTime)); + } m_content.Update(m_extensions.extensions.providers, deltaTime); m_voices.PrepareVoices(); m_device.Update(deltaTime); @@ -689,7 +722,8 @@ public void Update(float deltaTime) "AUDIO_DEVICE_LOST", "The audio output device was lost; active voices are completing and recovery will retry at safe points.", DiagnosticSeverity.Warning, - m_device.GetType().FullName); + m_device.GetType().FullName + ); } m_voices.CompleteAll(AudioCompletionReason.DeviceLost); m_content.ClearEmitters(); @@ -703,7 +737,9 @@ public void Update(float deltaTime) protected override void OnStop() { if (m_disposed) + { return; + } m_stopping = true; m_events.dispatched -= OnEventDispatched; if (!m_extensionsRetired) @@ -738,13 +774,17 @@ protected override void OnStop() m_candidateRetirement = null; m_disposed = true; if (failures.Count > 0) + { throw new AggregateException("Audio retirement failed after all resource owners were attempted.", failures); + } } private void OnEventDispatched(Event e) { if (e is ApplicationSuspensionChangedEvent suspension) + { m_mixer.SetSuspended(suspension.isSuspended); + } } private List RetireBackend(AudioCompletionReason reason) @@ -786,10 +826,14 @@ private void AdvanceDeviceRecovery(float deltaTime) return; } if (m_deviceRecoveryFactory is null) + { return; + } m_deviceRecoveryElapsed += deltaTime; if (m_deviceRecoveryElapsed < m_options.deviceRecoveryIntervalSeconds) + { return; + } m_deviceRecoveryElapsed = 0f; _ = TryRecoverDevice(m_deviceRecoveryFactory); } @@ -799,14 +843,15 @@ private void Publish( string message, DiagnosticSeverity severity, string? source - ) - => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); + ) => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); private void EnsureActive() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_stopping || m_retirementStage != 0) + { throw new InvalidOperationException("Audio retirement has started; no new work can be accepted."); + } m_extensions.EnsureHealthy(); } } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioRuntimeFactory.cs b/src/services/audio/Inno.Audio.Runtime/AudioRuntimeFactory.cs index 34a7746e2..7112fb79d 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioRuntimeFactory.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioRuntimeFactory.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Audio.Runtime; @@ -29,7 +28,8 @@ public AudioRuntimeFactory(Func runtimeFa public RuntimeSubsystemDescriptor descriptor { get; } = new( new RuntimeSubsystemId("inno.runtime.audio"), order: 500, - dependencies: [new RuntimeSubsystemId("inno.runtime.scene")]); + dependencies: [new RuntimeSubsystemId("inno.runtime.scene")] + ); /// /// Creates an audio feature over a newly allocated runtime layer. @@ -44,7 +44,7 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); AudioRuntime runtime = m_runtimeFactory(context) - ?? throw new InvalidOperationException("The audio runtime factory returned null."); + ?? throw new InvalidOperationException("The audio runtime factory returned null."); return runtime; } } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioRuntimeOptions.cs b/src/services/audio/Inno.Audio.Runtime/AudioRuntimeOptions.cs index c561e0aab..a7ae1925f 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioRuntimeOptions.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioRuntimeOptions.cs @@ -45,7 +45,9 @@ internal AudioRuntimeOptions Validate() ArgumentOutOfRangeException.ThrowIfNegative(decodedCacheBudgetBytes); ArgumentOutOfRangeException.ThrowIfNegative(automaticStreamingThresholdBytes); if (!float.IsFinite(deviceRecoveryIntervalSeconds) || deviceRecoveryIntervalSeconds <= 0f) + { throw new ArgumentOutOfRangeException(nameof(deviceRecoveryIntervalSeconds)); + } return new AudioRuntimeOptions { maxVoices = maxVoices, diff --git a/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs b/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs index 27d70ae4b..0a9619b7d 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs @@ -59,13 +59,17 @@ internal AudioVoiceOwner( internal void RefreshStates() { foreach (VoiceRecord voice in m_voices.Values) + { UpdateVoiceState(voice); + } } internal bool Stop(AudioVoiceHandle voice) { if (!m_voices.TryGetValue(voice, out VoiceRecord? record)) + { return false; + } if (!record.backendVoice.isValid) { FinishVoice(record, AudioCompletionReason.Stopped); @@ -73,7 +77,9 @@ internal bool Stop(AudioVoiceHandle voice) } record.completionOverride = AudioCompletionReason.Stopped; if (m_device.Stop(record.backendVoice)) + { return true; + } FinishVoice(record, AudioCompletionReason.Stopped); return true; } @@ -81,7 +87,9 @@ internal bool Stop(AudioVoiceHandle voice) internal bool Pause(AudioVoiceHandle voice) { if (!m_voices.TryGetValue(voice, out VoiceRecord? record)) + { return false; + } record.pauseRequested = true; if (!record.backendVoice.isValid) { @@ -90,14 +98,18 @@ internal bool Pause(AudioVoiceHandle voice) } bool result = m_device.Pause(record.backendVoice); if (result) + { record.state = AudioPlaybackState.Paused; + } return result; } internal bool Resume(AudioVoiceHandle voice) { if (!m_voices.TryGetValue(voice, out VoiceRecord? record) || !record.pauseRequested) + { return false; + } record.pauseRequested = false; if (!record.backendVoice.isValid) { @@ -106,7 +118,9 @@ internal bool Resume(AudioVoiceHandle voice) } bool result = m_device.Resume(record.backendVoice); if (result) + { UpdateVoiceState(record); + } return result; } @@ -115,7 +129,9 @@ internal bool Seek( TimeSpan position ) { if (position < TimeSpan.Zero || !m_voices.TryGetValue(voice, out VoiceRecord? record)) + { return false; + } record.seekPosition = position; return !record.backendVoice.isValid || m_device.Seek(record.backendVoice, position); } @@ -125,9 +141,13 @@ internal bool SetVoiceParameters( AudioVoiceParameters parameters ) { if (parameters.pitch <= 0f) + { return false; + } if (!m_voices.TryGetValue(voice, out VoiceRecord? record)) + { return false; + } record.parameters = parameters; return !record.backendVoice.isValid || m_device.SetVoiceParameters(record.backendVoice, parameters); } @@ -158,7 +178,9 @@ internal AudioVoiceHandle Play( ) { ArgumentNullException.ThrowIfNull(clip); if (!options.bus.isValid) + { throw new ArgumentException("Playback options must be initialized.", nameof(options)); + } var request = new AudioClipRequest(clip, m_artifacts); AudioVoiceHandle handle; try @@ -166,7 +188,9 @@ internal AudioVoiceHandle Play( handle = m_voiceAllocator.Allocate(); var record = new VoiceRecord(handle, request, options, scheduledDspTime, m_nextVoiceSequence++); while (m_voices.Count >= m_options.maxVoices) + { StealVoice(); + } m_voices.Add(handle, record); } catch (Exception failure) @@ -200,16 +224,19 @@ private void StealVoice() return; } if (victim.backendVoice.isValid) + { _ = m_device.Stop(victim.backendVoice); + } m_stolenVoiceCount++; FinishVoice(victim, AudioCompletionReason.Stolen); } internal void PrepareVoices() { - foreach (VoiceRecord voice in m_voices.Values.Where(static voice => - !voice.backendVoice.isValid && voice.finishingReason is null).ToArray()) - { + foreach (VoiceRecord voice in m_voices.Values.Where(static voice => ( + !voice.backendVoice.isValid && voice.finishingReason is null + )).ToArray() + ) { try { AudioClipCache.ClipCacheEntry clip; @@ -221,23 +248,37 @@ internal void PrepareVoices() voice.clip.Dispose(); } else + { clip = voice.clipCache; + } AudioClipState preparation = m_device.GetClipState(clip.handle); if (preparation == AudioClipState.Preparing) + { continue; + } if (preparation == AudioClipState.Failed) + { throw new InvalidOperationException("Native audio preparation failed."); + } if (!m_mixer.TryGetBus(voice.options.bus, out AudioBusHandle bus)) + { throw new InvalidOperationException($"Audio bus '{voice.options.bus}' is not present in the active mixer."); + } voice.backendVoice = m_device.Play(clip.handle, bus, voice.options, voice.scheduledDspTime); voice.backendBus = bus; if (!voice.backendVoice.isValid) + { throw new InvalidOperationException("The audio backend rejected voice creation."); + } if (voice.seekPosition is TimeSpan seek) + { _ = m_device.Seek(voice.backendVoice, seek); + } _ = m_device.SetVoiceParameters(voice.backendVoice, voice.parameters); if (voice.pauseRequested) + { _ = m_device.Pause(voice.backendVoice); + } UpdateVoiceState(voice); m_diagnostics.Resolve("AUDIO_CLIP_PREPARATION_FAILED", voice.clip.persistentId.ToString("D")); } @@ -251,7 +292,8 @@ internal void PrepareVoices() "AUDIO_CLIP_PREPARATION_FAILED", $"Audio clip '{voice.clip.assetPath}' could not be prepared: {exception.Message}", DiagnosticSeverity.Error, - voice.clip.persistentId.ToString("D")); + voice.clip.persistentId.ToString("D") + ); FinishVoice(voice, AudioCompletionReason.DecodeFailed); } } @@ -262,7 +304,9 @@ private void FinishVoice( AudioCompletionReason reason ) { if (!m_voices.ContainsKey(voice.handle)) + { return; + } voice.finishingReason ??= reason; voice.clip.Dispose(); if (voice.clipCache is not null) @@ -278,24 +322,32 @@ AudioCompletionReason reason m_events.Enqueue(new AudioVoiceCompletedEvent(voice.handle, voice.finishingReason.Value)); m_voices.Remove(voice.handle); if (m_terminalVoices.Add(voice.handle)) + { m_terminalVoiceOrder.Enqueue(voice.handle); + } int terminalCapacity = m_options.maxVoices > int.MaxValue / 2 - ? int.MaxValue - : Math.Max(64, m_options.maxVoices * 2); + ? int.MaxValue + : Math.Max(64, m_options.maxVoices * 2); while (m_terminalVoiceOrder.Count > terminalCapacity) + { m_terminalVoices.Remove(m_terminalVoiceOrder.Dequeue()); + } } internal void DrainCompletions() { foreach (VoiceRecord pending in m_voices.Values.Where(static voice => voice.finishingReason is not null).ToArray()) + { FinishVoice(pending, pending.finishingReason!.Value); + } long budget = Math.Max(64L, 2L * m_options.maxVoices); while (budget-- > 0 && m_device.TryDequeueCompletion(out AudioDeviceCompletion completion)) { VoiceRecord? voice = m_voices.Values.FirstOrDefault(candidate => candidate.backendVoice == completion.voice); if (voice is null) + { continue; + } FinishVoice(voice, voice.completionOverride ?? completion.reason); } } @@ -303,9 +355,13 @@ internal void DrainCompletions() private void UpdateVoiceState(VoiceRecord voice) { if (!voice.backendVoice.isValid) + { return; + } if (m_device.TryGetVoiceState(voice.backendVoice, out AudioPlaybackState state)) + { voice.state = state; + } } internal void CompleteAll(AudioCompletionReason reason) @@ -315,7 +371,9 @@ internal void CompleteAll(AudioCompletionReason reason) try { if (voice.backendVoice.isValid && voice.finishingReason is null) + { _ = m_device.Stop(voice.backendVoice); + } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -339,7 +397,9 @@ internal void CompleteAll(AudioCompletionReason reason) } } if (m_retirementFailures.Count == 0) + { return; + } Exception[] failures = m_retirementFailures.ToArray(); m_retirementFailures.Clear(); throw new AggregateException("Audio voice retirement failed after every voice was attempted.", failures); @@ -384,6 +444,5 @@ private void Publish( string message, DiagnosticSeverity severity, string? source - ) - => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); + ) => m_diagnostics.Publish(new Diagnostic(code, message, severity, source)); } diff --git a/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs b/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs index d6cde8305..16b682da4 100644 --- a/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs +++ b/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs @@ -40,7 +40,9 @@ public MutedAudioDevice( m_limits = limits ?? new AudioDeviceLimits(); generation = unchecked(++S_NEXT_GENERATION); if (generation == 0) + { generation = unchecked(++S_NEXT_GENERATION); + } capabilities = new AudioCapabilities(true, true, true, 4, sampleRate); } @@ -67,12 +69,7 @@ public MutedAudioDevice( /// /// Gets current logical resource statistics. /// - public AudioStatistics statistics - => new( - ActiveVoiceCount(), - m_clips.Count, - 0, - 0); + public AudioStatistics statistics => new(ActiveVoiceCount(), m_clips.Count, 0, 0); AudioClipHandle IAudioDevice.CreateClip( AudioClipDescriptor descriptor, @@ -81,7 +78,9 @@ IAudioClipSource source EnsureActive(); ArgumentNullException.ThrowIfNull(source); if (m_clips.Count >= m_limits.clips) + { return default; + } ulong id = m_nextIdentity++; m_clips.Add(id, descriptor); return CreateClipHandle(id, generation); @@ -91,7 +90,8 @@ AudioClipState IAudioDevice.GetClipState(AudioClipHandle clip) { DeviceHandleIdentity identity = GetHandleIdentity(clip); return identity.generation == generation && m_clips.ContainsKey(identity.value) - ? AudioClipState.Ready : AudioClipState.Failed; + ? AudioClipState.Ready + : AudioClipState.Failed; } bool IAudioDevice.DestroyClip(AudioClipHandle clip) @@ -99,7 +99,9 @@ bool IAudioDevice.DestroyClip(AudioClipHandle clip) EnsureActive(); DeviceHandleIdentity identity = GetHandleIdentity(clip); if (identity.generation != generation || HasActiveVoiceForClip(identity.value)) + { return false; + } return m_clips.Remove(identity.value); } @@ -111,36 +113,47 @@ AudioDeviceVoiceHandle IAudioDevice.Play( ) { EnsureActive(); if (m_voices.Count >= m_limits.voices) + { return default; + } if (!options.bus.isValid || scheduledDspTime is double startTime && (!double.IsFinite(startTime) || startTime < 0)) + { return default; + } DeviceHandleIdentity clipIdentity = GetHandleIdentity(clip); DeviceHandleIdentity busIdentity = GetHandleIdentity(bus); if (clipIdentity.generation != generation || !m_clips.TryGetValue(clipIdentity.value, out AudioClipDescriptor descriptor)) + { return default; + } if (busIdentity.generation != generation || !m_buses.ContainsKey(busIdentity.value)) + { return default; + } ulong id = m_nextIdentity++; AudioPlaybackState playbackState = scheduledDspTime is double start && start > m_dspTime - ? AudioPlaybackState.Scheduled - : AudioPlaybackState.Playing; - m_voices.Add(id, new VoiceRecord( - clipIdentity.value, - descriptor.frameCount / (double)descriptor.sampleRate, - options, - playbackState, - scheduledDspTime ?? m_dspTime)); + ? AudioPlaybackState.Scheduled + : AudioPlaybackState.Playing; + m_voices.Add( + id, + new VoiceRecord( + clipIdentity.value, + descriptor.frameCount / (double)descriptor.sampleRate, + options, + playbackState, + scheduledDspTime ?? m_dspTime + ) + ); return CreateVoiceHandle(id, generation); } - bool IAudioDevice.Stop(AudioDeviceVoiceHandle voice) - => CompleteVoice(voice, AudioCompletionReason.Stopped); + bool IAudioDevice.Stop(AudioDeviceVoiceHandle voice) => CompleteVoice(voice, AudioCompletionReason.Stopped); bool IAudioDevice.Pause(AudioDeviceVoiceHandle voice) { - if (!TryGetVoice(voice, out VoiceRecord record) || - record.state is AudioPlaybackState.Completed or AudioPlaybackState.Paused) - { + if (!TryGetVoice(voice, out VoiceRecord record) + || record.state is AudioPlaybackState.Completed or AudioPlaybackState.Paused + ) { return false; } record.state = AudioPlaybackState.Paused; @@ -150,10 +163,12 @@ bool IAudioDevice.Pause(AudioDeviceVoiceHandle voice) bool IAudioDevice.Resume(AudioDeviceVoiceHandle voice) { if (!TryGetVoice(voice, out VoiceRecord record) || record.state != AudioPlaybackState.Paused) + { return false; + } record.state = record.scheduledDspTime > m_dspTime - ? AudioPlaybackState.Scheduled - : AudioPlaybackState.Playing; + ? AudioPlaybackState.Scheduled + : AudioPlaybackState.Playing; return true; } @@ -161,9 +176,9 @@ bool IAudioDevice.Seek( AudioDeviceVoiceHandle voice, TimeSpan position ) { - if (position < TimeSpan.Zero || !TryGetVoice(voice, out VoiceRecord record) || - record.state == AudioPlaybackState.Completed) - { + if (position < TimeSpan.Zero || !TryGetVoice(voice, out VoiceRecord record) + || record.state == AudioPlaybackState.Completed + ) { return false; } record.position = position.TotalSeconds; @@ -175,9 +190,13 @@ bool IAudioDevice.SetVoiceParameters( AudioVoiceParameters parameters ) { if (parameters.pitch <= 0f) + { return false; + } if (!TryGetVoice(voice, out VoiceRecord record) || record.state == AudioPlaybackState.Completed) + { return false; + } record.parameters = parameters; return true; } @@ -201,10 +220,14 @@ AudioBusHandle parent ) { EnsureActive(); if (!id.isValid || m_buses.Count >= m_limits.buses) + { return default; + } DeviceHandleIdentity parentIdentity = GetHandleIdentity(parent); if (parent.isValid && (parentIdentity.generation != generation || !m_buses.ContainsKey(parentIdentity.value))) + { return default; + } ulong identity = m_nextIdentity++; m_buses.Add(identity, new BusRecord(id, parentIdentity.value)); return CreateBusHandle(identity, generation); @@ -215,7 +238,9 @@ bool IAudioDevice.DestroyBus(AudioBusHandle bus) EnsureActive(); DeviceHandleIdentity identity = GetHandleIdentity(bus); if (identity.generation != generation) + { return false; + } return m_buses.Remove(identity.value); } @@ -224,7 +249,9 @@ bool IAudioDevice.SetBusVolume( float volume ) { if (!float.IsFinite(volume) || volume < 0f || !TryGetBus(bus, out BusRecord record)) + { return false; + } record.volume = volume; return true; } @@ -234,7 +261,9 @@ bool IAudioDevice.SetBusMuted( bool muted ) { if (!TryGetBus(bus, out BusRecord record)) + { return false; + } record.muted = muted; return true; } @@ -244,7 +273,9 @@ bool IAudioDevice.SetBusPaused( bool paused ) { if (!TryGetBus(bus, out BusRecord record)) + { return false; + } record.paused = paused; return true; } @@ -261,7 +292,9 @@ AudioListenerHandle IAudioDevice.CreateListener(AudioListenerState state) { EnsureActive(); if (m_listeners.Count >= capabilities.maxListeners) + { return default; + } ulong id = m_nextIdentity++; m_listeners.Add(id, new ListenerRecord(state)); return CreateListenerHandle(id, generation); @@ -273,7 +306,9 @@ AudioListenerState state ) { DeviceHandleIdentity identity = GetHandleIdentity(listener); if (identity.generation != generation || !m_listeners.TryGetValue(identity.value, out ListenerRecord? record)) + { return false; + } record.state = state; return true; } @@ -288,21 +323,27 @@ void IAudioDevice.Update(float deltaTime) { EnsureActive(); if (deltaTime < 0f) + { deltaTime = 0f; + } m_dspTime += deltaTime; foreach ((ulong id, VoiceRecord voice) in m_voices) { if (voice.state == AudioPlaybackState.Scheduled && voice.scheduledDspTime <= m_dspTime) + { voice.state = AudioPlaybackState.Playing; + } if (voice.state != AudioPlaybackState.Playing) + { continue; + } voice.position += deltaTime * voice.parameters.pitch; if (!voice.loop && voice.duration > 0d && voice.position >= voice.duration) { voice.state = AudioPlaybackState.Completed; - m_completions.Enqueue(new AudioDeviceCompletion( - CreateVoiceHandle(id, generation), - AudioCompletionReason.NaturalEnd)); + m_completions.Enqueue( + new AudioDeviceCompletion(CreateVoiceHandle(id, generation), AudioCompletionReason.NaturalEnd) + ); } else if (voice.loop && voice.duration > 0d && voice.position >= voice.duration) { @@ -314,10 +355,14 @@ void IAudioDevice.Update(float deltaTime) bool IAudioDevice.TryDequeueCompletion(out AudioDeviceCompletion completion) { if (!m_completions.TryDequeue(out completion)) + { return false; + } DeviceHandleIdentity identity = GetHandleIdentity(completion.voice); if (identity.generation == generation) + { m_voices.Remove(identity.value); + } return true; } @@ -327,7 +372,9 @@ bool IAudioDevice.TryDequeueCompletion(out AudioDeviceCompletion completion) public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_clips.Clear(); m_voices.Clear(); @@ -341,7 +388,9 @@ private bool CompleteVoice( AudioCompletionReason reason ) { if (!TryGetVoice(voice, out VoiceRecord record) || record.state == AudioPlaybackState.Completed) + { return false; + } record.state = AudioPlaybackState.Completed; m_completions.Enqueue(new AudioDeviceCompletion(voice, reason)); return true; @@ -383,7 +432,9 @@ private int ActiveVoiceCount() foreach (VoiceRecord voice in m_voices.Values) { if (voice.state != AudioPlaybackState.Completed) + { count++; + } } return count; } @@ -393,7 +444,9 @@ private bool HasActiveVoiceForClip(ulong clip) foreach (VoiceRecord voice in m_voices.Values) { if (voice.clip == clip && voice.state != AudioPlaybackState.Completed) + { return true; + } } return false; } diff --git a/src/services/audio/Inno.Audio/Audio.cs b/src/services/audio/Inno.Audio/Audio.cs index 38086f727..894240a69 100644 --- a/src/services/audio/Inno.Audio/Audio.cs +++ b/src/services/audio/Inno.Audio/Audio.cs @@ -1,7 +1,7 @@ -using Inno.Core.Execution; using System; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Execution; namespace Inno.Audio; @@ -37,7 +37,6 @@ public static IDisposable EnterScope(IAudioService audio) ArgumentNullException.ThrowIfNull(audio); return S_CURRENT_SCOPE.Enter(audio); } - } /// @@ -112,8 +111,7 @@ public static AudioVoiceHandle PlayScheduled( AudioClipAsset clip, double scheduledDspTime, AudioPlayOptions options - ) - => AudioExecutionContext.current.PlayScheduled(clip, scheduledDspTime, options); + ) => AudioExecutionContext.current.PlayScheduled(clip, scheduledDspTime, options); /// /// Stops a live voice. @@ -180,8 +178,7 @@ TimeSpan position public static bool SetVoiceParameters( AudioVoiceHandle voice, AudioVoiceParameters parameters - ) - => AudioExecutionContext.current.SetVoiceParameters(voice, parameters); + ) => AudioExecutionContext.current.SetVoiceParameters(voice, parameters); /// /// Queries the current state of a voice. @@ -198,8 +195,7 @@ AudioVoiceParameters parameters public static bool TryGetVoiceState( AudioVoiceHandle voice, out AudioPlaybackState playbackState - ) - => AudioExecutionContext.current.TryGetVoiceState(voice, out playbackState); + ) => AudioExecutionContext.current.TryGetVoiceState(voice, out playbackState); /// /// Updates linear gain for a semantic mixer bus. @@ -271,8 +267,7 @@ public static ValueTask PreloadAsync( AudioClipAsset clip, AudioClipLoadMode loadMode = AudioClipLoadMode.Automatic, CancellationToken cancellationToken = default - ) - => AudioExecutionContext.current.PreloadAsync(clip, loadMode, cancellationToken); + ) => AudioExecutionContext.current.PreloadAsync(clip, loadMode, cancellationToken); /// /// Releases one explicit preload retention without interrupting active voices. diff --git a/src/services/audio/Inno.Audio/AudioClipAsset.cs b/src/services/audio/Inno.Audio/AudioClipAsset.cs index 646708505..74bc327a6 100644 --- a/src/services/audio/Inno.Audio/AudioClipAsset.cs +++ b/src/services/audio/Inno.Audio/AudioClipAsset.cs @@ -37,7 +37,9 @@ public AudioClipMetadata( long encodedByteLength ) { if (!codec.isValid) + { throw new ArgumentException("A valid codec identifier is required.", nameof(codec)); + } ArgumentOutOfRangeException.ThrowIfNegativeOrZero(channels); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); ArgumentOutOfRangeException.ThrowIfNegative(frameCount); @@ -101,7 +103,9 @@ public static byte[] Encode(AudioClipMetadata metadata) { byte[] codec = Encoding.UTF8.GetBytes(metadata.codec.value); if (codec.Length > byte.MaxValue) + { throw new ArgumentException("The codec identifier is too long.", nameof(metadata)); + } byte[] output = new byte[C_FIXED_SIZE + codec.Length]; BinaryPrimitives.WriteUInt32LittleEndian(output.AsSpan(0, 4), C_MAGIC); output[4] = (byte)codec.Length; @@ -128,10 +132,14 @@ public static byte[] Encode(AudioClipMetadata metadata) public static AudioClipMetadata Decode(ReadOnlySpan payload) { if (payload.Length < C_FIXED_SIZE || BinaryPrimitives.ReadUInt32LittleEndian(payload) != C_MAGIC) + { throw new InvalidOperationException("The audio runtime header is invalid."); + } int codecLength = payload[4]; if (payload.Length != C_FIXED_SIZE + codecLength || codecLength == 0) + { throw new InvalidOperationException("The audio runtime header length is invalid."); + } try { return new AudioClipMetadata( @@ -139,7 +147,8 @@ public static AudioClipMetadata Decode(ReadOnlySpan payload) BinaryPrimitives.ReadInt32LittleEndian(payload[8..12]), BinaryPrimitives.ReadInt32LittleEndian(payload[12..16]), BinaryPrimitives.ReadInt64LittleEndian(payload[16..24]), - BinaryPrimitives.ReadInt64LittleEndian(payload[24..32])); + BinaryPrimitives.ReadInt64LittleEndian(payload[24..32]) + ); } catch (ArgumentException exception) { @@ -180,7 +189,7 @@ protected override void OnRuntimePayloadChanged( ReadOnlyMemory currentPayload ) { m_metadata = currentPayload.IsEmpty - ? null - : AudioClipMetadataCodec.Decode(currentPayload.Span); + ? null + : AudioClipMetadataCodec.Decode(currentPayload.Span); } } diff --git a/src/services/audio/Inno.Audio/AudioClipDescriptor.cs b/src/services/audio/Inno.Audio/AudioClipDescriptor.cs index 134980051..3fd38e3d4 100644 --- a/src/services/audio/Inno.Audio/AudioClipDescriptor.cs +++ b/src/services/audio/Inno.Audio/AudioClipDescriptor.cs @@ -40,9 +40,13 @@ public AudioClipDescriptor( long encodedByteLength ) { if (!codec.isValid) + { throw new ArgumentException("A valid codec identifier is required.", nameof(codec)); + } if (!Enum.IsDefined(loadMode)) + { throw new ArgumentOutOfRangeException(nameof(loadMode)); + } ArgumentOutOfRangeException.ThrowIfNegativeOrZero(channels); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); ArgumentOutOfRangeException.ThrowIfNegative(frameCount); @@ -84,5 +88,4 @@ long encodedByteLength /// Gets the encoded artifact length in bytes. /// public long encodedByteLength { get; } - } diff --git a/src/services/audio/Inno.Audio/AudioContent.cs b/src/services/audio/Inno.Audio/AudioContent.cs index 3f78606a7..3deffbffa 100644 --- a/src/services/audio/Inno.Audio/AudioContent.cs +++ b/src/services/audio/Inno.Audio/AudioContent.cs @@ -33,7 +33,9 @@ public AudioEmitterSnapshot( ulong playbackRevision = 0 ) { if (id == Guid.Empty) + { throw new ArgumentException("An emitter identity cannot be empty.", nameof(id)); + } this.id = id; this.clip = clip ?? throw new ArgumentNullException(nameof(clip)); this.options = options; @@ -94,7 +96,9 @@ public AudioListenerSnapshot( bool active ) { if (id == Guid.Empty) + { throw new ArgumentException("A listener identity cannot be empty.", nameof(id)); + } this.id = id; this.priority = priority; this.state = state; diff --git a/src/services/audio/Inno.Audio/AudioContentProvider.cs b/src/services/audio/Inno.Audio/AudioContentProvider.cs index 09cd4ec3c..f9b77a311 100644 --- a/src/services/audio/Inno.Audio/AudioContentProvider.cs +++ b/src/services/audio/Inno.Audio/AudioContentProvider.cs @@ -1,7 +1,7 @@ -using Inno.References; using System; using System.Collections.Generic; using Inno.Core.Execution; +using Inno.References; namespace Inno.Audio; @@ -81,7 +81,9 @@ public AudioContentProviderContext( ) { ArgumentNullException.ThrowIfNull(content); if (!float.IsFinite(deltaTime) || deltaTime < 0f) + { throw new ArgumentOutOfRangeException(nameof(deltaTime)); + } ArgumentOutOfRangeException.ThrowIfNegative(capacity); m_content = content; this.deltaTime = deltaTime; @@ -236,13 +238,17 @@ private void EnsureActive() EnsureOwnerThread(); ObjectDisposedException.ThrowIf(m_content is null, this); if (m_rejected) + { throw new InvalidOperationException("The audio content contribution contains a rejected submission."); + } } private void EnsureOwnerThread() { if (Environment.CurrentManagedThreadId != m_ownerThread) + { throw new InvalidOperationException("Audio content collection requires its owning control thread."); + } } } @@ -270,7 +276,9 @@ public abstract class AudioContentProvider : IDisposable public void Dispose() { if (m_disposed) + { return; + } try { Dispose(true); @@ -294,7 +302,5 @@ public void Dispose() /// /// Always for explicit disposal. /// - protected virtual void Dispose(bool disposing) - { - } + protected virtual void Dispose(bool disposing) {} } diff --git a/src/services/audio/Inno.Audio/AudioDeviceLimits.cs b/src/services/audio/Inno.Audio/AudioDeviceLimits.cs index 48cc6d838..bf8710895 100644 --- a/src/services/audio/Inno.Audio/AudioDeviceLimits.cs +++ b/src/services/audio/Inno.Audio/AudioDeviceLimits.cs @@ -39,10 +39,12 @@ public AudioDeviceLimits( /// Gets the maximum retained clip count. /// public int clips { get; } + /// /// Gets the combined voice and undelivered completion capacity. /// public int voices { get; } + /// /// Gets the maximum retained bus count. /// diff --git a/src/services/audio/Inno.Audio/AudioDeviceVoiceHandle.cs b/src/services/audio/Inno.Audio/AudioDeviceVoiceHandle.cs index 5423cf792..2dde924d1 100644 --- a/src/services/audio/Inno.Audio/AudioDeviceVoiceHandle.cs +++ b/src/services/audio/Inno.Audio/AudioDeviceVoiceHandle.cs @@ -14,10 +14,12 @@ uint deviceGeneration } internal ulong value { get; } + /// /// Gets the backend device generation that owns this voice. /// public uint deviceGeneration { get; } + /// /// Gets whether this value identifies a backend allocation. /// diff --git a/src/services/audio/Inno.Audio/AudioMixer.cs b/src/services/audio/Inno.Audio/AudioMixer.cs index f61b43145..5635992f3 100644 --- a/src/services/audio/Inno.Audio/AudioMixer.cs +++ b/src/services/audio/Inno.Audio/AudioMixer.cs @@ -26,7 +26,9 @@ public AudioProcessorParameter( float value ) { if (!id.isValid) + { throw new ArgumentException("A valid parameter identifier is required.", nameof(id)); + } this.id = id; this.value = value; } @@ -63,11 +65,15 @@ public AudioProcessorConfiguration( IEnumerable? parameters = null ) { if (!id.isValid) + { throw new ArgumentException("A valid processor identifier is required.", nameof(id)); + } this.id = id; m_parameters = parameters?.ToArray() ?? []; if (m_parameters.Select(static parameter => parameter.id).Distinct().Count() != m_parameters.Length) + { throw new ArgumentException("Processor parameter identifiers must be unique.", nameof(parameters)); + } } /// @@ -114,13 +120,21 @@ public AudioBusDefinition( IEnumerable? processors = null ) { if (!id.isValid) + { throw new ArgumentException("A valid bus identifier is required.", nameof(id)); + } if (volume < 0f) + { throw new ArgumentOutOfRangeException(nameof(volume)); + } if (id == AudioBusId.master && parent is not null) + { throw new ArgumentException("The master bus cannot have a parent.", nameof(parent)); + } if (id != AudioBusId.master && (parent is null || !parent.Value.isValid)) + { throw new ArgumentException("A non-master bus requires a valid parent.", nameof(parent)); + } this.id = id; this.parent = parent; this.volume = volume; @@ -207,9 +221,13 @@ public void AddBus( bool muted = false ) { if (!id.isValid || id == AudioBusId.master) + { throw new ArgumentException("A valid non-master bus identifier is required.", nameof(id)); + } if (m_buses.ContainsKey(id)) + { throw new ArgumentException($"Audio bus '{id}' is already defined.", nameof(id)); + } m_buses.Add(id, new AudioBusDefinition(id, parent, volume, muted)); } @@ -231,13 +249,16 @@ AudioProcessorConfiguration processor ) { ArgumentNullException.ThrowIfNull(processor); if (!m_buses.TryGetValue(bus, out AudioBusDefinition? definition)) + { throw new KeyNotFoundException($"Audio bus '{bus}' is not defined."); + } m_buses[bus] = new AudioBusDefinition( definition.id, definition.parent, definition.volume, definition.muted, - definition.processors.Append(processor)); + definition.processors.Append(processor) + ); } /// @@ -256,7 +277,9 @@ public AudioMixer Build() var visited = new HashSet(); Visit(AudioBusId.master, order, visiting, visited); foreach (AudioBusId id in m_buses.Keys.OrderBy(static id => id.value, StringComparer.Ordinal)) + { Visit(id, order, visiting, visited); + } return new AudioMixer(order); } @@ -267,13 +290,21 @@ private void Visit( ISet visited ) { if (visited.Contains(id)) + { return; + } if (!m_buses.TryGetValue(id, out AudioBusDefinition? definition)) + { throw new InvalidOperationException($"Audio mixer references missing bus '{id}'."); + } if (!visiting.Add(id)) + { throw new InvalidOperationException($"Audio mixer bus routing contains a cycle at '{id}'."); + } if (definition.parent is AudioBusId parent) + { Visit(parent, order, visiting, visited); + } visiting.Remove(id); visited.Add(id); order.Add(definition); @@ -331,9 +362,7 @@ public struct AudioMixerFeatureConfiguration /// /// Creates an empty feature configuration for deserialization. /// - public AudioMixerFeatureConfiguration() - { - } + public AudioMixerFeatureConfiguration() {} /// /// Creates a mixer feature configuration. @@ -383,7 +412,6 @@ public AudioMixerFeatureConfiguration( [StableTypeId("6e167326-d078-45e9-ad33-993300ee5fed")] public sealed class AudioMixerAsset : AssetObject { - /// /// Gets or sets the globally stable mixer extension identifier. /// diff --git a/src/services/audio/Inno.Audio/AudioTypes.cs b/src/services/audio/Inno.Audio/AudioTypes.cs index 31012d045..502ed77ca 100644 --- a/src/services/audio/Inno.Audio/AudioTypes.cs +++ b/src/services/audio/Inno.Audio/AudioTypes.cs @@ -12,12 +12,10 @@ public enum AudioClipLoadMode /// Lets the runtime choose between decoded and streamed storage. /// Automatic, - /// /// Decodes the complete clip before playback. /// Decode, - /// /// Decodes encoded data incrementally while playback advances. /// @@ -33,22 +31,18 @@ public enum AudioDeviceState /// The device has not completed initialization. /// Initializing, - /// /// The device is available for audible playback. /// Ready, - /// /// Playback is advancing without an output device. /// Muted, - /// /// The active output device was lost and recovery is pending. /// Lost, - /// /// The device has been released and cannot accept work. /// @@ -64,27 +58,22 @@ public enum AudioPlaybackState /// The voice is waiting for clip preparation. /// Preparing, - /// /// The voice is scheduled against the audio clock. /// Scheduled, - /// /// The voice is actively advancing. /// Playing, - /// /// The voice is paused at its current cursor. /// Paused, - /// /// The voice has completed and no longer accepts control commands. /// Completed, - /// /// The handle is invalid, stale, or unknown to the active runtime. /// @@ -100,22 +89,18 @@ public enum AudioCompletionReason /// The clip reached its natural end. /// NaturalEnd, - /// /// A caller explicitly stopped the voice. /// Stopped, - /// /// The runtime reclaimed the voice to satisfy its voice budget. /// Stolen, - /// /// Encoded data could not be prepared or decoded. /// DecodeFailed, - /// /// Playback ended because the owning device generation was lost. /// @@ -131,17 +116,14 @@ public enum AudioDistanceModel /// Disables distance attenuation while retaining spatial direction. /// None, - /// /// Uses inverse-distance attenuation. /// Inverse, - /// /// Uses linear-distance attenuation. /// Linear, - /// /// Uses exponential-distance attenuation. /// @@ -331,18 +313,30 @@ public AudioSpatialOptions( AudioValueValidation.RequireFinite(direction, nameof(direction)); AudioValueValidation.RequireFinite(velocity, nameof(velocity)); if (!Enum.IsDefined(distanceModel)) + { throw new ArgumentOutOfRangeException(nameof(distanceModel)); + } if (!float.IsFinite(minDistance) || !float.IsFinite(maxDistance) || minDistance < 0f || maxDistance < minDistance) + { throw new ArgumentOutOfRangeException(nameof(minDistance), "Spatial distance bounds are invalid."); + } if (!float.IsFinite(rolloff) || rolloff < 0f) + { throw new ArgumentOutOfRangeException(nameof(rolloff)); - if (!float.IsFinite(coneInnerAngle) || !float.IsFinite(coneOuterAngle) || - coneInnerAngle is < 0f or > 360f || coneOuterAngle < coneInnerAngle || coneOuterAngle > 360f) + } + if (!float.IsFinite(coneInnerAngle) || !float.IsFinite(coneOuterAngle) + || coneInnerAngle is < 0f or > 360f || coneOuterAngle < coneInnerAngle || coneOuterAngle > 360f + ) { throw new ArgumentOutOfRangeException(nameof(coneOuterAngle), "Spatial cone angles are invalid."); + } if (!float.IsFinite(coneOuterGain) || coneOuterGain is < 0f or > 1f) + { throw new ArgumentOutOfRangeException(nameof(coneOuterGain)); + } if (!float.IsFinite(dopplerFactor) || dopplerFactor < 0f) + { throw new ArgumentOutOfRangeException(nameof(dopplerFactor)); + } this.position = position; this.direction = direction; this.velocity = velocity; @@ -421,9 +415,7 @@ public readonly record struct AudioPlayOptions /// Creates default playback parameters. /// public AudioPlayOptions() - : this(1f, 1f, 0f, false, 0, AudioBusId.master, AudioClipLoadMode.Automatic, null) - { - } + : this(1f, 1f, 0f, false, 0, AudioBusId.master, AudioClipLoadMode.Automatic, null) {} /// /// Creates playback parameters. @@ -469,16 +461,26 @@ public AudioPlayOptions( AudioSpatialOptions? spatial = null ) { if (!float.IsFinite(volume) || volume < 0f) + { throw new ArgumentOutOfRangeException(nameof(volume)); + } if (!float.IsFinite(pitch) || pitch <= 0f) + { throw new ArgumentOutOfRangeException(nameof(pitch)); + } if (!float.IsFinite(pan) || pan is < -1f or > 1f) + { throw new ArgumentOutOfRangeException(nameof(pan)); + } if (!Enum.IsDefined(loadMode)) + { throw new ArgumentOutOfRangeException(nameof(loadMode)); + } AudioBusId resolvedBus = bus ?? AudioBusId.master; if (!resolvedBus.isValid) + { throw new ArgumentException("A valid destination bus is required.", nameof(bus)); + } this.volume = volume; this.pitch = pitch; this.pan = pan; @@ -565,11 +567,17 @@ public AudioVoiceParameters( AudioSpatialOptions? spatial = null ) { if (!float.IsFinite(volume) || volume < 0f) + { throw new ArgumentOutOfRangeException(nameof(volume)); + } if (!float.IsFinite(pitch) || pitch <= 0f) + { throw new ArgumentOutOfRangeException(nameof(pitch)); + } if (!float.IsFinite(pan) || pan is < -1f or > 1f) + { throw new ArgumentOutOfRangeException(nameof(pan)); + } this.volume = volume; this.pitch = pitch; this.pan = pan; diff --git a/src/services/audio/Inno.Audio/AudioValueValidation.cs b/src/services/audio/Inno.Audio/AudioValueValidation.cs index ba8507dd8..b86d15bb8 100644 --- a/src/services/audio/Inno.Audio/AudioValueValidation.cs +++ b/src/services/audio/Inno.Audio/AudioValueValidation.cs @@ -10,6 +10,8 @@ internal static void RequireFinite( string parameterName ) { if (!float.IsFinite(value.x) || !float.IsFinite(value.y) || !float.IsFinite(value.z)) + { throw new ArgumentOutOfRangeException(parameterName, "Audio vectors must contain finite components."); + } } } diff --git a/src/services/audio/Inno.Audio/AudioVoiceAllocator.cs b/src/services/audio/Inno.Audio/AudioVoiceAllocator.cs index fccbb00b6..3559e0a12 100644 --- a/src/services/audio/Inno.Audio/AudioVoiceAllocator.cs +++ b/src/services/audio/Inno.Audio/AudioVoiceAllocator.cs @@ -22,7 +22,9 @@ public AudioVoiceAllocator() { int generation = Interlocked.Increment(ref S_NEXT_GENERATION); if (generation <= 0) + { throw new InvalidOperationException("Audio playback owner generations are exhausted."); + } m_generation = (uint)generation; } diff --git a/src/services/audio/Inno.Audio/AudioVoiceCompletedEvent.cs b/src/services/audio/Inno.Audio/AudioVoiceCompletedEvent.cs index bce06314b..424527f06 100644 --- a/src/services/audio/Inno.Audio/AudioVoiceCompletedEvent.cs +++ b/src/services/audio/Inno.Audio/AudioVoiceCompletedEvent.cs @@ -22,7 +22,9 @@ public AudioVoiceCompletedEvent( AudioCompletionReason reason ) { if (!voice.isValid) + { throw new ArgumentException("A valid voice handle is required.", nameof(voice)); + } this.voice = voice; this.reason = reason; } diff --git a/src/services/audio/Inno.Audio/IAudioDevice.cs b/src/services/audio/Inno.Audio/IAudioDevice.cs index 95b258a09..249edb073 100644 --- a/src/services/audio/Inno.Audio/IAudioDevice.cs +++ b/src/services/audio/Inno.Audio/IAudioDevice.cs @@ -21,7 +21,9 @@ public AudioDeviceCompletion( AudioCompletionReason reason ) { if (!voice.isValid) + { throw new ArgumentException("A valid voice handle is required.", nameof(voice)); + } this.voice = voice; this.reason = reason; } diff --git a/src/services/audio/Inno.Audio/Properties/ScriptingApi.cs b/src/services/audio/Inno.Audio/Properties/ScriptingApi.cs index fe945bdcc..06fe1919f 100644 --- a/src/services/audio/Inno.Audio/Properties/ScriptingApi.cs +++ b/src/services/audio/Inno.Audio/Properties/ScriptingApi.cs @@ -1,10 +1,7 @@ using Inno.Audio; using Inno.Scripting.Api; -[assembly: ScriptingApiNamespace( - "InnoEngine.Audio", - "Inno.Audio", - ScriptingApiScope.Runtime)] +[assembly: ScriptingApiNamespace("InnoEngine.Audio", "Inno.Audio", ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(Audio), ScriptingApiScope.Runtime)] [assembly: ScriptingApiExport(typeof(AudioClipAsset), ScriptingApiScope.Runtime)] diff --git a/src/services/input/Inno.Input.Runtime/InputRuntime.cs b/src/services/input/Inno.Input.Runtime/InputRuntime.cs index ac4ebe768..141e75452 100644 --- a/src/services/input/Inno.Input.Runtime/InputRuntime.cs +++ b/src/services/input/Inno.Input.Runtime/InputRuntime.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Input.Runtime; @@ -39,6 +38,7 @@ protected override void OnBeginFrame(RuntimeFrame frame) snapshot = m_backend.Capture(frame.frameIndex); OwnFrameScope(InputExecutionContext.EnterScope(this)); } + /// /// Releases the input backend after its frame scope and owned work have quiesced. /// diff --git a/src/services/input/Inno.Input.Runtime/InputRuntimeFactory.cs b/src/services/input/Inno.Input.Runtime/InputRuntimeFactory.cs index e9074130f..de8225fb5 100644 --- a/src/services/input/Inno.Input.Runtime/InputRuntimeFactory.cs +++ b/src/services/input/Inno.Input.Runtime/InputRuntimeFactory.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Input.Runtime; @@ -28,7 +27,8 @@ public InputRuntimeFactory(Func backendF /// public RuntimeSubsystemDescriptor descriptor { get; } = new( new RuntimeSubsystemId("inno.runtime.input"), - order: -1000); + order: -1000 + ); /// /// Creates an input feature over a newly allocated session backend. @@ -43,7 +43,7 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); IInputBackend backend = m_backendFactory(context) - ?? throw new InvalidOperationException("The input backend factory returned null."); + ?? throw new InvalidOperationException("The input backend factory returned null."); return new InputRuntime(backend); } } diff --git a/src/services/input/Inno.Input/Input.cs b/src/services/input/Inno.Input/Input.cs index b4499ca69..32a7ea6d8 100644 --- a/src/services/input/Inno.Input/Input.cs +++ b/src/services/input/Inno.Input/Input.cs @@ -1,7 +1,6 @@ -using Inno.Core.Execution; using System; using System.Threading; - +using Inno.Core.Execution; using Inno.Core.Input; using Inno.Core.Mathematics; @@ -47,7 +46,6 @@ public static IDisposable EnterScope(IInputService input) ArgumentNullException.ThrowIfNull(input); return S_CURRENT_SCOPE.Enter(input); } - } /// diff --git a/src/services/input/Inno.Input/InputSnapshot.cs b/src/services/input/Inno.Input/InputSnapshot.cs index fcb2c4373..49a5398e9 100644 --- a/src/services/input/Inno.Input/InputSnapshot.cs +++ b/src/services/input/Inno.Input/InputSnapshot.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Core.Input; using Inno.Core.Mathematics; @@ -74,7 +73,9 @@ public InputSnapshot( IEnumerable? textInput = null ) { if (frameIndex < 0) + { throw new ArgumentOutOfRangeException(nameof(frameIndex)); + } this.frameIndex = frameIndex; m_keysDown = Copy(keysDown); m_keysPressed = Copy(keysPressed); @@ -212,5 +213,5 @@ public InputSnapshot( private static HashSet Copy(IEnumerable? values) where TValue : struct, Enum - => values is null ? [] : values.ToHashSet(); + => values is null ? [] : values.ToHashSet(); } diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs index 54e64f0e0..490903fb6 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs @@ -1,11 +1,11 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; @@ -128,6 +128,7 @@ ShaderSourceLocation sourceLocation public sealed class CompiledShaderPass { private readonly ShaderPassDefinition m_definition; + /// /// Creates a compiled pass artifact. /// @@ -184,6 +185,7 @@ public ShaderPassDefinition definition public sealed class CompiledShaderArtifact { private readonly byte[] m_definitionData; + /// /// Creates a compiled shader artifact. /// @@ -223,7 +225,9 @@ ReadOnlySpan definitionData this.shaderInterface = shaderInterface; this.passes = Array.AsReadOnly(passes.ToArray()); if (definitionData.IsEmpty) + { throw new ArgumentException("Compiled programs require a captured runtime contract.", nameof(definitionData)); + } m_definitionData = definitionData.ToArray(); } @@ -271,38 +275,41 @@ public RenderShaderArtifact CreateRuntimeArtifact() pass.shaderInterface, pass.stages.Select(static stage => new RenderShaderStageArtifact( stage.stage, - stage.bytes.Span)).ToArray())).ToArray(), - m_definitionData); + stage.bytes.Span + )).ToArray() + )).ToArray(), + m_definitionData + ); private static RenderRasterState ConvertRasterState(ShaderRenderState source) => new() + { + topology = source.topology, + cull = source.cull switch + { + ShaderCullMode.None => RenderCullMode.None, + ShaderCullMode.Front => RenderCullMode.Front, + ShaderCullMode.Back => RenderCullMode.Back, + _ => throw new ArgumentOutOfRangeException(nameof(source)) + }, + frontFace = source.frontFace, + depthCompare = source.depthCompare switch { - topology = source.topology, - cull = source.cull switch - { - ShaderCullMode.None => RenderCullMode.None, - ShaderCullMode.Front => RenderCullMode.Front, - ShaderCullMode.Back => RenderCullMode.Back, - _ => throw new ArgumentOutOfRangeException(nameof(source)) - }, - frontFace = source.frontFace, - depthCompare = source.depthCompare switch - { - ShaderCompareFunction.Never => RenderDepthCompare.Never, - ShaderCompareFunction.Less => RenderDepthCompare.Less, - ShaderCompareFunction.Equal => RenderDepthCompare.Equal, - ShaderCompareFunction.LessEqual => RenderDepthCompare.LessEqual, - ShaderCompareFunction.Greater => RenderDepthCompare.Greater, - ShaderCompareFunction.NotEqual => RenderDepthCompare.NotEqual, - ShaderCompareFunction.GreaterEqual => RenderDepthCompare.GreaterEqual, - ShaderCompareFunction.Always => RenderDepthCompare.Always, - _ => throw new ArgumentOutOfRangeException(nameof(source)) - }, - depthWrite = source.depthWrite, - blend = source.blend, - colorWriteMask = source.colorWriteMask, - multisampling = source.multisampling - }; + ShaderCompareFunction.Never => RenderDepthCompare.Never, + ShaderCompareFunction.Less => RenderDepthCompare.Less, + ShaderCompareFunction.Equal => RenderDepthCompare.Equal, + ShaderCompareFunction.LessEqual => RenderDepthCompare.LessEqual, + ShaderCompareFunction.Greater => RenderDepthCompare.Greater, + ShaderCompareFunction.NotEqual => RenderDepthCompare.NotEqual, + ShaderCompareFunction.GreaterEqual => RenderDepthCompare.GreaterEqual, + ShaderCompareFunction.Always => RenderDepthCompare.Always, + _ => throw new ArgumentOutOfRangeException(nameof(source)) + }, + depthWrite = source.depthWrite, + blend = source.blend, + colorWriteMask = source.colorWriteMask, + multisampling = source.multisampling + }; } /// @@ -342,8 +349,9 @@ IReadOnlyList diagnostics /// /// Gets whether a complete candidate artifact was produced. /// - public bool succeeded => artifact is not null - && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); + public bool succeeded + => artifact is not null + && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); } /// @@ -399,7 +407,6 @@ ShaderCompileTarget CreateTarget( bool optimize = true, bool debugInformation = false ); - } /// @@ -440,8 +447,5 @@ public ShaderCompileTarget CreateTarget( GraphicsCapabilities capabilities, bool optimize = true, bool debugInformation = false - ) - => m_toolchain.CreateTarget(capabilities, optimize, debugInformation); - + ) => m_toolchain.CreateTarget(capabilities, optimize, debugInformation); } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs index 30a2c6b03..f31b3c317 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs @@ -1,14 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Threading; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Shaders; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; -using System.Threading; namespace Inno.Rendering.Assets.Authoring; @@ -69,10 +69,14 @@ public static byte[] Capture( { cancellationToken.ThrowIfCancellationRequested(); if (node.definitionId != "inno.shader.source") + { continue; + } Guid id = ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, serialization, context); if (id == Guid.Empty) + { continue; + } string path = ShaderGraphDocument.Read(node, "sourcePath", "", serialization, context); sources.Add(node.id, readSource(id, path)); } @@ -82,9 +86,9 @@ public static byte[] Capture( private static GraphDocument MissingGraphResolver( Guid id, string path - ) - => throw new InvalidOperationException( - $"Shader graph node '{id}' at '{path}' requires a graph resolver during artifact capture."); + ) => throw new InvalidOperationException( + $"Shader graph node '{id}' at '{path}' requires a graph resolver during artifact capture." + ); /// /// Reads the target-expanded runtime interface from the same frozen candidate as its computations. @@ -105,8 +109,11 @@ public static ShaderDefinition ReadDefinition( ReadOnlySpan bytes, SerializationRegistry serialization, SerializationContext context - ) - => ShaderGraphDocument.ReadDefinition(GraphDocumentCodec.Decode(serialization.Deserialize(bytes).program, serialization), serialization, context); + ) => ShaderGraphDocument.ReadDefinition( + GraphDocumentCodec.Decode(serialization.Deserialize(bytes).program, serialization), + serialization, + context + ); /// /// Reads a retained immutable authoring snapshot through its explicit artifact owner. @@ -152,10 +159,14 @@ SerializationRegistry serialization { node.position = default; foreach (string key in node.values.Keys.Where(static key => key.StartsWith("inno.editor.", StringComparison.Ordinal)).ToArray()) + { node.RemoveValue(key); + } } foreach (string key in graph.metadata.Keys.Where(static key => key.StartsWith("inno.editor.", StringComparison.Ordinal)).ToArray()) + { graph.RemoveMetadata(key); + } data.document = []; data.program = GraphDocumentCodec.Encode(graph, serialization); return Convert.ToHexString(SHA256.HashData(serialization.Serialize(data))); @@ -184,14 +195,14 @@ public static byte[] Encode( IReadOnlyDictionary sources, SerializationRegistry serialization, GraphDocument? program = null - ) - => serialization.Serialize(new ArtifactData - { - document = GraphDocumentCodec.Encode(graph, serialization), - program = GraphDocumentCodec.Encode(program ?? graph, serialization), - sources = sources.OrderBy(static pair => pair.Key.value, StringComparer.Ordinal) - .Select(static pair => new SourceData { node = pair.Key.value, bundle = pair.Value.ToArray() }).ToArray() - }); + ) => serialization.Serialize(new ArtifactData + { + document = GraphDocumentCodec.Encode(graph, serialization), + program = GraphDocumentCodec.Encode(program ?? graph, serialization), + sources = sources.OrderBy(static pair => pair.Key.value, StringComparer.Ordinal) + .Select(static pair => new SourceData { node = pair.Key.value, bundle = pair.Value.ToArray() }) + .ToArray() + }); /// /// Restores the imported graph for authoring or source export. @@ -208,8 +219,7 @@ public static byte[] Encode( public static GraphDocument ReadDocument( ReadOnlySpan bytes, SerializationRegistry serialization - ) - => GraphDocumentCodec.Decode(serialization.Deserialize(bytes).document, serialization); + ) => GraphDocumentCodec.Decode(serialization.Deserialize(bytes).document, serialization); /// /// Analyzes frozen functions and lowers the graph in the owner's active generation. @@ -252,10 +262,12 @@ public static ShaderGraphProgramResult Lower( var sources = data.sources.ToDictionary(static source => new GraphNodeId(source.node), source => { GraphNodeRecord node = graph.FindNode(new(source.node)) - ?? throw new InvalidOperationException($"Captured source node '{source.node}' is unavailable."); + ?? throw new InvalidOperationException($"Captured source node '{source.node}' is unavailable."); string function = ShaderGraphDocument.Read(node, "function", "", serialization, context); if (string.IsNullOrWhiteSpace(function)) + { throw new InvalidOperationException($"Source node '{source.node}' has no exported function selection."); + } return frontends.AnalyzeModule(ShaderSourceBundle.Decode(source.bundle, function, serialization, defines)); }); return new ShaderGraphProgramCompiler(nodes).Lower(graph, implementationId, sources, serialization, context); @@ -268,15 +280,18 @@ private sealed class ArtifactData : ISerializable /// Gets or sets native graph bytes. /// [SerializableProperty] public byte[] document { get; set; } = []; + /// /// Gets or sets explicit target-expanded stage graph bytes. /// [SerializableProperty] public byte[] program { get; set; } = []; + /// /// Gets or sets frozen functions by node identity. /// [SerializableProperty] public SourceData[] sources { get; set; } = []; } + [Inno.Extensibility.Types.StableTypeId("91d54277-1257-5bf0-904d-165e8092fe4a")] private struct SourceData { @@ -284,10 +299,10 @@ private struct SourceData /// Gets or sets the stable source node identity. /// public string node { get; set; } + /// /// Gets or sets native frozen function bytes. /// public byte[] bundle { get; set; } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs index 15b68fec4..23e8889d6 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs @@ -1,14 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Inno.Core.Diagnostics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Shaders; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; namespace Inno.Rendering.Assets.Authoring; @@ -58,7 +58,15 @@ public ValueTask CompileGraphAsync( CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(shader); - return CompileGraphAsync(ShaderGraphArtifact.Read(shader, artifacts), target, variant, types, serialization, context, cancellationToken); + return CompileGraphAsync( + ShaderGraphArtifact.Read(shader, artifacts), + target, + variant, + types, + serialization, + context, + cancellationToken + ); } /// @@ -103,15 +111,32 @@ public ValueTask CompileGraphAsync( ShaderDefinition definition = ShaderGraphArtifact.ReadDefinition(artifact.Span, serialization, context); var diagnostics = ShaderDefinitionValidator.Validate(definition, target.capabilities).ToList(); if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); + } var keywords = definition.keywords.ToDictionary(static value => value.id, StringComparer.Ordinal); foreach ((string id, string value) in variant.options) + { if (!keywords.TryGetValue(id, out ShaderKeywordDefinition keyword) || !keyword.options.Contains(value, StringComparer.Ordinal)) - diagnostics.Add(new("SHADER_VARIANT_INVALID", DiagnosticSeverity.Error, $"Shader variant selects undeclared option '{id}={value}'.")); + { + diagnostics.Add( + new("SHADER_VARIANT_INVALID", DiagnosticSeverity.Error, $"Shader variant selects undeclared option '{id}={value}'.") + ); + } + } if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); - ShaderGraphProgramResult program = ShaderGraphArtifact.Lower(artifact.Span, m_toolchain.implementationId, - nodes, frontends, serialization, context, variant.options); + } + ShaderGraphProgramResult program = ShaderGraphArtifact.Lower( + artifact.Span, + m_toolchain.implementationId, + nodes, + frontends, + serialization, + context, + variant.options + ); return CompileAsync(definition, program, target, variant, serialization, context, cancellationToken); } @@ -158,21 +183,50 @@ public ValueTask CompileAsync( ArgumentNullException.ThrowIfNull(target); var diagnostics = ShaderDefinitionValidator.Validate(definition, target.capabilities).ToList(); if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); + } foreach ((string id, string value) in variant.options) + { if (!definition.keywords.Any(keyword => keyword.id == id && keyword.options.Contains(value, StringComparer.Ordinal))) - diagnostics.Add(new("SHADER_VARIANT_INVALID", DiagnosticSeverity.Error, $"Shader variant selects undeclared option '{id}={value}'.")); + { + diagnostics.Add( + new("SHADER_VARIANT_INVALID", DiagnosticSeverity.Error, $"Shader variant selects undeclared option '{id}={value}'.") + ); + } + } if (diagnostics.Count != 0 && diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); + } byte[] definitionData = serialization.Serialize(definition, context); - var captured = new ShaderDefinition(definition.name, - definition.properties.Select(static value => new ShaderPropertyDefinition(value.id, value.displayName, - value.type, value.stages, default, value.bindingKind, value.storageAccess, value.bindingOwner)), + var captured = new ShaderDefinition( + definition.name, + definition.properties.Select(static value => new ShaderPropertyDefinition( + value.id, + value.displayName, + value.type, + value.stages, + default, + value.bindingKind, + value.storageAccess, + value.bindingOwner + )), definition.keywords.Select(static value => new ShaderKeywordDefinition(value.id, value.options.ToArray())), - definition.passes.Select(static value => new ShaderPassDefinition(value.name, value.programKind, - value.requiredFeatures, value.renderState, value.metadata)), - definition.techniques.Select(static value => new ShaderTechniqueDefinition(value.id, value.contract, - value.passes.ToArray(), value.requiredFeatures))); + definition.passes.Select(static value => new ShaderPassDefinition( + value.name, + value.programKind, + value.requiredFeatures, + value.renderState, + value.metadata + )), + definition.techniques.Select(static value => new ShaderTechniqueDefinition( + value.id, + value.contract, + value.passes.ToArray(), + value.requiredFeatures + )) + ); return CompileCapturedAsync(captured, definitionData, program, target, variant, cancellationToken); } @@ -187,58 +241,111 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(program); ArgumentNullException.ThrowIfNull(target); - var diagnostics = program.diagnostics.Select(static value => new ShaderDiagnostic(value.code, value.severity, value.message)).ToList(); + var diagnostics = program.diagnostics + .Select(static value => new ShaderDiagnostic(value.code, value.severity, value.message)) + .ToList(); diagnostics.AddRange(ShaderDefinitionValidator.Validate(definition, target.capabilities)); if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return new(null, diagnostics); + } if (!program.succeeded) + { return new(null, diagnostics); + } string shaderName = definition.name; // Only value contracts cross the asynchronous native compiler boundary. Texture defaults remain owned by the imported asset. - ShaderPropertyDefinition[] properties = definition.properties.Select(static value => new ShaderPropertyDefinition(value.id, - value.displayName, value.type, value.stages, default, value.bindingKind, value.storageAccess, value.bindingOwner)).ToArray(); - var passes = definition.passes.Select(static value => new ShaderPassDefinition(value.name, value.programKind, - requiredFeatures: value.requiredFeatures, renderState: value.renderState, metadata: value.metadata)).ToDictionary(static value => value.name, StringComparer.Ordinal); + ShaderPropertyDefinition[] properties = definition.properties.Select(static value => new ShaderPropertyDefinition( + value.id, + value.displayName, + value.type, + value.stages, + default, + value.bindingKind, + value.storageAccess, + value.bindingOwner + )).ToArray(); + var passes = definition.passes.Select(static value => new ShaderPassDefinition( + value.name, + value.programKind, + requiredFeatures: value.requiredFeatures, + renderState: value.renderState, + metadata: value.metadata + )).ToDictionary(static value => value.name, StringComparer.Ordinal); var compiledPasses = new List(); var allBindings = new Dictionary(StringComparer.Ordinal); foreach (ShaderGraphPass pass in program.passes) { cancellationToken.ThrowIfCancellationRequested(); if (!passes.TryGetValue(pass.name, out ShaderPassDefinition passDefinition)) + { throw new InvalidOperationException($"The graph produced undeclared pass '{pass.name}'."); + } if ((passDefinition.requiredFeatures & ~target.capabilities.features) != 0) + { continue; + } var binaries = new List(); var bindings = new Dictionary(StringComparer.Ordinal); foreach (ShaderIrStage stage in pass.stages) { ShaderStageToolResult result = await CompileAsync(stage, target, cancellationToken).ConfigureAwait(false); - diagnostics.AddRange(result.diagnostics.Select(value => new ShaderDiagnostic(value.code, value.severity, value.message, - new ShaderSourceLocation(value.location.assetPath, pass.name, stage.stage, value.location.line, value.location.column)))); + diagnostics.AddRange( + result.diagnostics.Select(value => new ShaderDiagnostic( + value.code, + value.severity, + value.message, + new ShaderSourceLocation( + value.location.assetPath, + pass.name, + stage.stage, + value.location.line, + value.location.column + ) + )) + ); if (!result.succeeded) + { return new(null, diagnostics); + } binaries.Add(new(stage.stage, result.bytes.Span, new ShaderSourceLocation(shaderName, pass.name, stage.stage))); foreach (ShaderStageBinding generated in result.bindings) { ShaderPropertyDefinition[] matches = properties.Where(value => value.id.value == generated.id).ToArray(); if (matches.Length != 1) { - diagnostics.Add(new("SHADER_GRAPH_BINDING", DiagnosticSeverity.Error, - $"Generated binding '{generated.id}' requires exactly one declared shader property.")); + diagnostics.Add( + new( + "SHADER_GRAPH_BINDING", + DiagnosticSeverity.Error, + $"Generated binding '{generated.id}' requires exactly one declared shader property." + ) + ); continue; } ShaderPropertyDefinition property = matches[0]; ShaderIrStageInput input = stage.inputs.Single(value => value.id == generated.id); if ((property.stages & stage.stage) == 0 || !Matches(property, input)) { - diagnostics.Add(new("SHADER_GRAPH_BINDING_TYPE", DiagnosticSeverity.Error, - $"Property '{generated.id}' does not match the {stage.stage} graph binding's type, access or visibility.")); + diagnostics.Add( + new( + "SHADER_GRAPH_BINDING_TYPE", + DiagnosticSeverity.Error, + $"Property '{generated.id}' does not match the {stage.stage} graph binding's type, access or visibility." + ) + ); continue; } - var binding = new ShaderInterfaceBinding(property.id, property.type, stage.stage, + var binding = new ShaderInterfaceBinding( + property.id, + property.type, + stage.stage, input.type.elementType is null ? 1 : input.type.elementCount, - property.bindingKind, property.storageAccess, generated.nativeName, - property.bindingKind == ShaderPropertyBindingKind.Uniform ? null : generated.location); + property.bindingKind, + property.storageAccess, + generated.nativeName, + property.bindingKind == ShaderPropertyBindingKind.Uniform ? null : generated.location + ); Merge(bindings, binding); Merge(allBindings, binding); } @@ -246,10 +353,19 @@ CancellationToken cancellationToken compiledPasses.Add(new(passDefinition, binaries, new(bindings.Values.ToArray()))); } if (compiledPasses.Count == 0) - diagnostics.Add(new("SHADER_NO_SUPPORTED_PASS", DiagnosticSeverity.Error, - $"Shader '{shaderName}' has no pass supported by '{target.key}'.")); + { + diagnostics.Add( + new( + "SHADER_NO_SUPPORTED_PASS", + DiagnosticSeverity.Error, + $"Shader '{shaderName}' has no pass supported by '{target.key}'." + ) + ); + } if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return new(null, diagnostics); + } return new(new(shaderName, target.key, variant, new(allBindings.Values.ToArray()), compiledPasses, definitionData), diagnostics); } @@ -258,11 +374,21 @@ private static bool Matches( ShaderIrStageInput input ) { if (property.bindingKind == ShaderPropertyBindingKind.StorageBuffer) - return input.kind == ShaderIrInputKind.Storage && input.type.storage is { isImage: false } buffer && buffer.access == property.storageAccess; + { + return input.kind == ShaderIrInputKind.Storage + && input.type.storage is { isImage: false } buffer + && buffer.access == property.storageAccess; + } if (property.bindingKind == ShaderPropertyBindingKind.StorageTexture) - return input.kind == ShaderIrInputKind.Storage && input.type.storage is { isImage: true } image && image.access == property.storageAccess; + { + return input.kind == ShaderIrInputKind.Storage + && input.type.storage is { isImage: true } image + && image.access == property.storageAccess; + } if ((property.bindingKind == ShaderPropertyBindingKind.SampledTexture) != (input.kind == ShaderIrInputKind.SampledTexture)) + { return false; + } string type = (input.type.elementType ?? input.type).id; return property.type switch { @@ -286,12 +412,25 @@ ShaderInterfaceBinding binding if (target.TryGetValue(binding.id.value, out ShaderInterfaceBinding? previous)) { if (previous.type != binding.type || previous.arrayCount != binding.arrayCount || previous.bindingKind != binding.bindingKind - || previous.storageAccess != binding.storageAccess || previous.nativeName != binding.nativeName || previous.location != binding.location) - throw new InvalidOperationException($"Shader binding '{binding.id}' has inconsistent native layouts between stages or passes."); - binding = new(binding.id, binding.type, previous.stages | binding.stages, binding.arrayCount, binding.bindingKind, - binding.storageAccess, binding.nativeName, binding.location); + || previous.storageAccess != binding.storageAccess + || previous.nativeName != binding.nativeName + || previous.location != binding.location + ) { + throw new InvalidOperationException( + $"Shader binding '{binding.id}' has inconsistent native layouts between stages or passes." + ); + } + binding = new( + binding.id, + binding.type, + previous.stages | binding.stages, + binding.arrayCount, + binding.bindingKind, + binding.storageAccess, + binding.nativeName, + binding.location + ); } target[binding.id.value] = binding; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs index 1113bba20..e2dcdde89 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs @@ -1,8 +1,8 @@ -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; @@ -111,7 +111,8 @@ ShaderCompilationResult candidate candidate.artifact, candidateSucceeded: true, usingLastGood: false, - candidate.diagnostics); + candidate.diagnostics + ); } m_artifacts.TryGetValue(key, out CompiledShaderArtifact? lastGood); @@ -119,7 +120,8 @@ ShaderCompilationResult candidate lastGood, candidateSucceeded: false, usingLastGood: lastGood is not null, - candidate.diagnostics); + candidate.diagnostics + ); } } @@ -160,4 +162,3 @@ private readonly record struct ArtifactKey( string variantKey ); } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs index 93009db73..c4ca92825 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs @@ -1,9 +1,9 @@ -using Inno.Core.Serialization; -using Inno.Rendering; -using Inno.Rendering.Shaders; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Serialization; +using Inno.Rendering; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring; @@ -59,7 +59,9 @@ SerializationRegistry serialization ArgumentNullException.ThrowIfNull(functions); ArgumentNullException.ThrowIfNull(serialization); if (functions.Count == 0 || functions.Any(static pair => string.IsNullOrWhiteSpace(pair.Key) || pair.Value is null)) + { throw new ArgumentException("A shader source library requires named function analyses.", nameof(functions)); + } return serialization.Serialize(new BundleData { functions = functions.OrderBy(static pair => pair.Key, StringComparer.Ordinal).Select(static pair => new FunctionData @@ -67,13 +69,17 @@ SerializationRegistry serialization name = pair.Key, implementations = pair.Value.implementations.Select(static value => new ImplementationData { - id = value.implementationId, language = value.languageId, root = value.sourcePath, entry = value.entryPoint, + id = value.implementationId, + language = value.languageId, + root = value.sourcePath, + entry = value.entryPoint, paths = value.sources.Select(static file => file.assetPath).ToArray(), texts = value.sources.Select(static file => file.text).ToArray(), includeOwners = value.includes.Select(static edge => edge.includingFile).ToArray(), includeNames = value.includes.Select(static edge => edge.include).ToArray(), includePaths = value.includes.Select(static edge => edge.resolvedPath).ToArray(), - defineNames = value.defines.Keys.ToArray(), defineValues = value.defines.Values.ToArray() + defineNames = value.defines.Keys.ToArray(), + defineValues = value.defines.Values.ToArray() }).ToArray() }).ToArray() }); @@ -108,37 +114,51 @@ public static IReadOnlyList Decode( BundleData data = serialization.Deserialize(bytes); FunctionData selected = (data.functions ?? []).SingleOrDefault(value => value.name == function); if (selected.implementations is null) - throw new InvalidOperationException($"Shader source library does not export function '{function}'."); - return Array.AsReadOnly(selected.implementations.Select(value => { - if (value.paths is null || value.texts is null || value.includeOwners is null || value.includeNames is null - || value.includePaths is null || value.defineNames is null || value.defineValues is null) - throw new InvalidOperationException("The frozen shader source bundle is missing required collections."); - if (value.paths.Length != value.texts.Length || value.includeOwners.Length != value.includeNames.Length - || value.includeOwners.Length != value.includePaths.Length || value.defineNames.Length != value.defineValues.Length) - throw new InvalidOperationException("The frozen shader source bundle has inconsistent collection lengths."); - var files = value.paths.Select(( - path, - index - ) => new ShaderSourceFile(path, value.texts[index])).ToDictionary(static file => file.assetPath, StringComparer.Ordinal); - var edges = value.includeOwners.Select(( - owner, - index - ) => new ShaderSourceInclude(owner, value.includeNames[index], value.includePaths[index])) - .ToDictionary(static edge => (edge.includingFile, edge.include)); - var macros = value.defineNames.Select(( - name, - index - ) => new KeyValuePair(name, value.defineValues[index])).ToDictionary(StringComparer.Ordinal); - foreach ((string name, string text) in defines ?? new Dictionary()) + throw new InvalidOperationException($"Shader source library does not export function '{function}'."); + } + return Array.AsReadOnly( + selected.implementations.Select(value => { - if (macros.TryGetValue(name, out string? previous) && previous != text) - throw new InvalidOperationException($"The target changes recorded source definition '{name}'."); - macros[name] = text; - } - return new ShaderSourceImplementationRequest(value.id, value.language, - new(files[value.root], value.entry, new FrozenResolver(files, edges), macros)); - }).ToArray()); + if (value.paths is null || value.texts is null || value.includeOwners is null || value.includeNames is null + || value.includePaths is null || value.defineNames is null || value.defineValues is null + ) { + throw new InvalidOperationException("The frozen shader source bundle is missing required collections."); + } + if (value.paths.Length != value.texts.Length || value.includeOwners.Length != value.includeNames.Length + || value.includeOwners.Length != value.includePaths.Length || value.defineNames.Length != value.defineValues.Length + ) { + throw new InvalidOperationException("The frozen shader source bundle has inconsistent collection lengths."); + } + var files = value.paths.Select(( + path, + index + ) => new ShaderSourceFile(path, value.texts[index])).ToDictionary(static file => file.assetPath, StringComparer.Ordinal); + var edges = value.includeOwners + .Select(( + owner, + index + ) => new ShaderSourceInclude(owner, value.includeNames[index], value.includePaths[index])) + .ToDictionary(static edge => (edge.includingFile, edge.include)); + var macros = value.defineNames.Select(( + name, + index + ) => new KeyValuePair(name, value.defineValues[index])).ToDictionary(StringComparer.Ordinal); + foreach ((string name, string text) in defines ?? new Dictionary()) + { + if (macros.TryGetValue(name, out string? previous) && previous != text) + { + throw new InvalidOperationException($"The target changes recorded source definition '{name}'."); + } + macros[name] = text; + } + return new ShaderSourceImplementationRequest( + value.id, + value.language, + new(files[value.root], value.entry, new FrozenResolver(files, edges), macros) + ); + }).ToArray() + ); } private sealed class FrozenResolver( @@ -161,9 +181,10 @@ private sealed class FrozenResolver( public ShaderSourceFile ReadInclude( string includingFile, string include - ) - => edges.TryGetValue((includingFile, include), out ShaderSourceInclude? edge) && files.TryGetValue(edge.resolvedPath, out ShaderSourceFile? file) - ? file : throw new InvalidOperationException($"Source dependency '{include}' from '{includingFile}' was not captured by import."); + ) => edges.TryGetValue((includingFile, include), out ShaderSourceInclude? edge) + && files.TryGetValue(edge.resolvedPath, out ShaderSourceFile? file) + ? file + : throw new InvalidOperationException($"Source dependency '{include}' from '{includingFile}' was not captured by import."); } [Inno.Extensibility.Types.StableTypeId("0e035881-9850-5f9c-8037-283168890d0d")] @@ -174,6 +195,7 @@ private sealed class BundleData : ISerializable /// [SerializableProperty] public FunctionData[] functions { get; set; } = []; } + [Inno.Extensibility.Types.StableTypeId("3c78ad4e-deb3-547b-984e-18de97667641")] private struct FunctionData { @@ -181,11 +203,13 @@ private struct FunctionData /// Gets the human-readable name used for presentation and diagnostics. /// public string name { get; set; } + /// /// Gets the shader implementations associated with these functions. /// public ImplementationData[] implementations { get; set; } } + [Inno.Extensibility.Types.StableTypeId("4f51d0e8-599b-5fd7-b4cc-4694fe18e922")] private struct ImplementationData { @@ -193,46 +217,55 @@ private struct ImplementationData /// Gets the stable identity used to reference this value across subsystem boundaries. /// public string id { get; set; } + /// /// Gets the language text used by the current instance. /// public string language { get; set; } + /// /// Gets the root text used by the current instance. /// public string root { get; set; } + /// /// Gets the entry text used by the current instance. /// public string entry { get; set; } + /// /// Gets the source paths in this shader bundle. /// public string[] paths { get; set; } + /// /// Gets the source text corresponding to each path. /// public string[] texts { get; set; } + /// /// Gets the source that owns each included file. /// public string[] includeOwners { get; set; } + /// /// Gets the names used to reference included files. /// public string[] includeNames { get; set; } + /// /// Gets the resolved paths of included files. /// public string[] includePaths { get; set; } + /// /// Gets the names of compilation defines. /// public string[] defineNames { get; set; } + /// /// Gets the values corresponding to compilation defines. /// public string[] defineValues { get; set; } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs index bc4e2d4b1..61c25f9bd 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs @@ -1,11 +1,11 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Shaders; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Rendering; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring; @@ -73,7 +73,9 @@ IEnumerable diagnostics this.bindings = Array.AsReadOnly(bindings.ToArray()); this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); if (!bytes.IsEmpty && this.diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { throw new ArgumentException("A failed candidate cannot publish compiled bytes.", nameof(bytes)); + } m_bytes = bytes.ToArray(); } @@ -81,14 +83,17 @@ IEnumerable diagnostics /// Gets immutable target binary data, empty on failure. /// public ReadOnlyMemory bytes => m_bytes; + /// /// Gets the exact generated logical-to-native resource layout. /// public IReadOnlyList bindings { get; } + /// /// Gets generation and native compiler diagnostics. /// public IReadOnlyList diagnostics { get; } + /// /// Gets whether a nonempty binary was compiled without error diagnostics. /// @@ -103,6 +108,7 @@ public sealed partial class ShaderCompiler private readonly object m_stageCacheLock = new(); private readonly Dictionary<(string stage, string target, GraphicsCapabilities capabilities), ShaderStageToolResult> m_stageCache = []; private long m_stageCacheBytes; + /// /// Compiles a typed stage through the configured adapter without an intermediate complete-source authoring asset. /// @@ -128,13 +134,21 @@ public async ValueTask CompileAsync( cancellationToken.ThrowIfCancellationRequested(); var key = (stage.contentHash, target.key, target.capabilities); lock (m_stageCacheLock) + { if (m_stageCache.TryGetValue(key, out ShaderStageToolResult? previous)) + { return previous; - ShaderStageToolResult result = await m_toolchain.CompileAsync(new ShaderStageToolRequest(stage, target), cancellationToken).ConfigureAwait(false); + } + } + ShaderStageToolResult result = await m_toolchain.CompileAsync( + new ShaderStageToolRequest(stage, target), + cancellationToken + ).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // The bounded cache contains immutable backend results only, never IR, providers or source assets. // Failed and cancelled requests are not cached, and layout-only graph edits reuse the semantic key. if (result.succeeded && result.bytes.Length <= 32 * 1024 * 1024) + { lock (m_stageCacheLock) { if (m_stageCache.Count >= 256 || m_stageCacheBytes + result.bytes.Length > 32 * 1024 * 1024) @@ -143,9 +157,11 @@ public async ValueTask CompileAsync( m_stageCacheBytes = 0; } if (m_stageCache.TryAdd(key, result)) + { m_stageCacheBytes += result.bytes.Length; + } } + } return result; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs index 0cd66d6ed..2e4937d26 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs @@ -1,9 +1,9 @@ -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.IO; using System.Threading; using System.Threading.Tasks; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; @@ -37,4 +37,3 @@ ValueTask CompileKtxAsync( CancellationToken cancellationToken = default ); } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs index 31081563d..aee98f7a6 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs @@ -1,10 +1,10 @@ +using System; +using System.IO; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Rendering; -using System; -using System.IO; namespace Inno.Rendering.Assets.Authoring; @@ -85,9 +85,10 @@ public string Save( private static void Validate(AssetPath path) { if (!path.isValid || !path.localPath.EndsWith(".ishader", StringComparison.OrdinalIgnoreCase)) + { throw new ArgumentException("A shader graph source must use the .ishader extension.", nameof(path)); + } } - } /// @@ -97,6 +98,7 @@ private static void Validate(AssetPath path) public sealed class ShaderGraphSourceSnapshot { private readonly GraphDocument m_document; + internal ShaderGraphSourceSnapshot( GraphDocument document, string hash, @@ -106,17 +108,19 @@ bool readOnly contentHash = hash; isReadOnly = readOnly; } + /// /// Gets a detached copy of authored graph records. /// public GraphDocument document => m_document.Clone(); + /// /// Gets the source fingerprint used to reject external-edit conflicts. /// public string contentHash { get; } + /// /// Gets whether the source belongs to an immutable installation mount. /// public bool isReadOnly { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs index 22f519678..99e5f2196 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs @@ -1,13 +1,13 @@ -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Core.Mathematics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Mathematics; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; @@ -54,13 +54,15 @@ byte[] ReadDependency(string relativePath) context.sourceBytes.Span, isBinary: false, ReadDependency, - path => output.DependsOnSource(AssetPath.Parse(path))), + path => output.DependsOnSource(AssetPath.Parse(path)) + ), ".glb" => MeshSourceParser.ParseGltf( context.assetPath.ToString(), context.sourceBytes.Span, isBinary: true, ReadDependency, - path => output.DependsOnSource(AssetPath.Parse(path))), + path => output.DependsOnSource(AssetPath.Parse(path)) + ), _ => throw new RenderingAssetFormatException(context.assetPath.ToString(), "Unsupported geometry container.") }; (Vector3 boundsCenter, Vector3 boundsExtents) = CalculateBounds(data); @@ -69,7 +71,8 @@ byte[] ReadDependency(string relativePath) data.indices.Count, data.sections.Count, boundsCenter, - boundsExtents); + boundsExtents + ); output.SetAsset(asset); byte[] artifact = GeometryArtifact.Encode(data); await output.WriteArtifactAsync("runtime", artifact, cancellationToken).ConfigureAwait(false); @@ -91,15 +94,15 @@ private static (Vector3 center, Vector3 extents) CalculateBounds(GeometryData da minimum = new Vector3( MathF.Min(minimum.x, position.x), MathF.Min(minimum.y, position.y), - MathF.Min(minimum.z, position.z)); + MathF.Min(minimum.z, position.z) + ); maximum = new Vector3( MathF.Max(maximum.x, position.x), MathF.Max(maximum.y, position.y), - MathF.Max(maximum.z, position.z)); + MathF.Max(maximum.z, position.z) + ); } return ((minimum + maximum) * 0.5f, (maximum - minimum) * 0.5f); } - } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs index 1ea4b8f68..bf6627d30 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs @@ -1,6 +1,6 @@ -using Inno.Rendering; using System; using System.Text.Json; +using Inno.Rendering; namespace Inno.Rendering.Assets.Authoring; @@ -20,7 +20,9 @@ internal static string RequireString( string path ) { if (element.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(element.GetString())) + { throw new RenderingAssetFormatException(path, "A non-empty string is required."); + } return element.GetString()!; } @@ -30,26 +32,25 @@ internal static void RequireKind( string path ) { if (element.ValueKind != kind) + { throw new RenderingAssetFormatException(path, $"Expected {kind}, found {element.ValueKind}."); + } } internal static bool RequireBoolean( JsonElement element, string path - ) - => element.ValueKind switch - { - JsonValueKind.True => true, - JsonValueKind.False => false, - _ => throw new RenderingAssetFormatException(path, "A boolean is required.") - }; + ) => element.ValueKind switch + { + JsonValueKind.True => true, + JsonValueKind.False => false, + _ => throw new RenderingAssetFormatException(path, "A boolean is required.") + }; internal static int RequireInt32( JsonElement element, string path - ) - => element.TryGetInt32(out int result) - ? result - : throw new RenderingAssetFormatException(path, "A 32-bit integer is required."); + ) => element.TryGetInt32(out int result) + ? result + : throw new RenderingAssetFormatException(path, "A 32-bit integer is required."); } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs index 95edcbd98..ffbadcba8 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs @@ -1,6 +1,3 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Buffers.Binary; using System.Collections.Generic; @@ -8,6 +5,9 @@ using System.Linq; using System.Text; using System.Text.Json; +using Inno.Core.Mathematics; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; @@ -40,12 +40,7 @@ Action dependencySink using JsonDocument document = JsonDocument.Parse(jsonBytes); JsonElement root = GltfJson.RequireObject(document.RootElement, "$gltf"); - byte[][] buffers = ReadBuffers( - sourcePath, - root, - binaryChunk, - dependencyReader, - dependencySink); + byte[][] buffers = ReadBuffers(sourcePath, root, binaryChunk, dependencyReader, dependencySink); BufferView[] bufferViews = ReadBufferViews(root, buffers); Accessor[] accessors = ReadAccessors(root, bufferViews); return ReadMeshes(sourcePath, root, accessors); @@ -116,7 +111,8 @@ Action dependencySink GltfJson.RequireObject(buffer, $"$gltf.buffers[{index}]"); int byteLength = GltfJson.RequireInt32( buffer.GetProperty("byteLength"), - $"$gltf.buffers[{index}].byteLength"); + $"$gltf.buffers[{index}].byteLength" + ); byte[] bytes; if (buffer.TryGetProperty("uri", out JsonElement uriElement)) { @@ -128,7 +124,8 @@ Action dependencySink { throw new RenderingAssetFormatException( $"$gltf.buffers[{index}].uri", - "Only base64 data URIs are supported."); + "Only base64 data URIs are supported." + ); } bytes = Convert.FromBase64String(uri[(separator + 1)..]); @@ -137,7 +134,8 @@ Action dependencySink { string dependency = NormalizeProjectPath( CombineProjectPath(directory, Uri.UnescapeDataString(uri)), - $"$gltf.buffers[{index}].uri"); + $"$gltf.buffers[{index}].uri" + ); dependencySink(dependency); bytes = dependencyReader(dependency); } @@ -150,14 +148,16 @@ Action dependencySink { throw new RenderingAssetFormatException( $"$gltf.buffers[{index}]", - "A URI or matching GLB binary chunk is required."); + "A URI or matching GLB binary chunk is required." + ); } if (byteLength < 0 || bytes.Length < byteLength) { throw new RenderingAssetFormatException( $"$gltf.buffers[{index}].byteLength", - "Buffer content is shorter than its declared byte length."); + "Buffer content is shorter than its declared byte length." + ); } buffers.Add(bytes); @@ -181,25 +181,25 @@ IReadOnlyList buffers int index = 0; foreach (JsonElement view in viewArray.EnumerateArray()) { - int bufferIndex = GltfJson.RequireInt32( - view.GetProperty("buffer"), - $"$gltf.bufferViews[{index}].buffer"); + int bufferIndex = GltfJson.RequireInt32(view.GetProperty("buffer"), $"$gltf.bufferViews[{index}].buffer"); int offset = view.TryGetProperty("byteOffset", out JsonElement offsetElement) - ? GltfJson.RequireInt32(offsetElement, $"$gltf.bufferViews[{index}].byteOffset") - : 0; + ? GltfJson.RequireInt32(offsetElement, $"$gltf.bufferViews[{index}].byteOffset") + : 0; int length = GltfJson.RequireInt32( view.GetProperty("byteLength"), - $"$gltf.bufferViews[{index}].byteLength"); + $"$gltf.bufferViews[{index}].byteLength" + ); int stride = view.TryGetProperty("byteStride", out JsonElement strideElement) - ? GltfJson.RequireInt32(strideElement, $"$gltf.bufferViews[{index}].byteStride") - : 0; + ? GltfJson.RequireInt32(strideElement, $"$gltf.bufferViews[{index}].byteStride") + : 0; if (bufferIndex < 0 || bufferIndex >= buffers.Count || offset < 0 || length < 0 || offset + length > buffers[bufferIndex].Length - || stride < 0) - { + || stride < 0 + ) { throw new RenderingAssetFormatException( $"$gltf.bufferViews[{index}]", - "Buffer view bounds are invalid."); + "Buffer view bounds are invalid." + ); } result.Add(new BufferView(buffers[bufferIndex], offset, length, stride)); @@ -227,31 +227,28 @@ IReadOnlyList views { throw new RenderingAssetFormatException( $"$gltf.accessors[{index}].sparse", - "Sparse accessors are not supported by the first mesh importer."); + "Sparse accessors are not supported by the first mesh importer." + ); } int viewIndex = GltfJson.RequireInt32( accessor.GetProperty("bufferView"), - $"$gltf.accessors[{index}].bufferView"); + $"$gltf.accessors[{index}].bufferView" + ); int offset = accessor.TryGetProperty("byteOffset", out JsonElement offsetElement) - ? GltfJson.RequireInt32(offsetElement, $"$gltf.accessors[{index}].byteOffset") - : 0; + ? GltfJson.RequireInt32(offsetElement, $"$gltf.accessors[{index}].byteOffset") + : 0; int componentType = GltfJson.RequireInt32( accessor.GetProperty("componentType"), - $"$gltf.accessors[{index}].componentType"); - int count = GltfJson.RequireInt32( - accessor.GetProperty("count"), - $"$gltf.accessors[{index}].count"); - string type = GltfJson.RequireString( - accessor.GetProperty("type"), - $"$gltf.accessors[{index}].type"); + $"$gltf.accessors[{index}].componentType" + ); + int count = GltfJson.RequireInt32(accessor.GetProperty("count"), $"$gltf.accessors[{index}].count"); + string type = GltfJson.RequireString(accessor.GetProperty("type"), $"$gltf.accessors[{index}].type"); bool normalized = accessor.TryGetProperty("normalized", out JsonElement normalizedElement) - && GltfJson.RequireBoolean(normalizedElement, $"$gltf.accessors[{index}].normalized"); + && GltfJson.RequireBoolean(normalizedElement, $"$gltf.accessors[{index}].normalized"); if (viewIndex < 0 || viewIndex >= views.Count || offset < 0 || count <= 0) { - throw new RenderingAssetFormatException( - $"$gltf.accessors[{index}]", - "Accessor bounds are invalid."); + throw new RenderingAssetFormatException($"$gltf.accessors[{index}]", "Accessor bounds are invalid."); } result.Add(new Accessor(views[viewIndex], offset, componentType, count, type, normalized)); @@ -282,19 +279,21 @@ IReadOnlyList accessors foreach (JsonElement primitive in primitives.EnumerateArray()) { int mode = primitive.TryGetProperty("mode", out JsonElement modeElement) - ? GltfJson.RequireInt32(modeElement, "$gltf.meshes[].primitives[].mode") - : 4; + ? GltfJson.RequireInt32(modeElement, "$gltf.meshes[].primitives[].mode") + : 4; if (mode != 4) { throw new RenderingAssetFormatException( "$gltf.meshes[].primitives[].mode", - "Only triangle-list primitives are supported."); + "Only triangle-list primitives are supported." + ); } JsonElement attributes = primitive.GetProperty("attributes"); int positionAccessor = GltfJson.RequireInt32( attributes.GetProperty("POSITION"), - "$gltf.meshes[].primitives[].attributes.POSITION"); + "$gltf.meshes[].primitives[].attributes.POSITION" + ); float[][] positions = ReadFloatAccessor(accessors, positionAccessor, 3, "POSITION"); float[][]? normals = TryReadAttribute(attributes, "NORMAL", accessors, 3); float[][]? textureCoordinates = TryReadAttribute(attributes, "TEXCOORD_0", accessors, 2); @@ -314,28 +313,30 @@ IReadOnlyList accessors { position = new Vector3(position[0], position[1], -position[2]), normal = normal is null - ? default - : new Vector3(normal[0], normal[1], -normal[2]), + ? default + : new Vector3(normal[0], normal[1], -normal[2]), hasNormal = normal is not null, textureCoordinate = uv is null ? default : new Vector2(uv[0], uv[1]), tangent = tangent is null - ? default - : new Vector3(tangent[0], tangent[1], -tangent[2]), + ? default + : new Vector3(tangent[0], tangent[1], -tangent[2]), tangentW = tangent is null ? 1f : -tangent[3], hasTangent = tangent is not null }); } uint[] localIndices = primitive.TryGetProperty("indices", out JsonElement indexElement) - ? ReadIndexAccessor( - accessors, - GltfJson.RequireInt32(indexElement, "$gltf.meshes[].primitives[].indices")) - : Enumerable.Range(0, positions.Length).Select(static value => checked((uint)value)).ToArray(); + ? ReadIndexAccessor( + accessors, + GltfJson.RequireInt32(indexElement, "$gltf.meshes[].primitives[].indices") + ) + : Enumerable.Range(0, positions.Length).Select(static value => checked((uint)value)).ToArray(); if (localIndices.Length % 3 != 0) { throw new RenderingAssetFormatException( "$gltf.meshes[].primitives[].indices", - "Triangle index count must be divisible by three."); + "Triangle index count must be divisible by three." + ); } int firstIndex = indices.Count; @@ -363,7 +364,8 @@ IReadOnlyList accessors value.position, Vector3.NormalizeSafe(value.normal), ToTangent(value.tangent, value.tangentW), - value.textureCoordinate)).ToArray(); + value.textureCoordinate + )).ToArray(); return new GeometryData(normalizedVertices, [.. indices], [.. sections]); } @@ -372,14 +374,9 @@ IReadOnlyList accessors string name, IReadOnlyList accessors, int components - ) - => attributes.TryGetProperty(name, out JsonElement accessor) - ? ReadFloatAccessor( - accessors, - GltfJson.RequireInt32(accessor, $"$gltf.attributes.{name}"), - components, - name) - : null; + ) => attributes.TryGetProperty(name, out JsonElement accessor) + ? ReadFloatAccessor(accessors, GltfJson.RequireInt32(accessor, $"$gltf.attributes.{name}"), components, name) + : null; private static float[][] ReadFloatAccessor( IReadOnlyList accessors, @@ -392,7 +389,8 @@ string semantic { throw new RenderingAssetFormatException( $"$gltf.accessors[{index}]", - $"Attribute '{semantic}' must contain {expectedComponents} components."); + $"Attribute '{semantic}' must contain {expectedComponents} components." + ); } int componentSize = ComponentSize(accessor.componentType); @@ -410,7 +408,8 @@ string semantic accessor.view.buffer, offset + component * componentSize, accessor.componentType, - accessor.normalized); + accessor.normalized + ); } } @@ -423,11 +422,12 @@ int index ) { Accessor accessor = GetAccessor(accessors, index, "indices"); if (!string.Equals(accessor.type, "SCALAR", StringComparison.Ordinal) - || accessor.componentType is not (5121 or 5123 or 5125)) - { + || accessor.componentType is not (5121 or 5123 or 5125) + ) { throw new RenderingAssetFormatException( $"$gltf.accessors[{index}]", - "Indices require an unsigned SCALAR accessor."); + "Indices require an unsigned SCALAR accessor." + ); } int elementSize = ComponentSize(accessor.componentType); @@ -454,24 +454,22 @@ private static float ReadComponent( int offset, int componentType, bool normalized - ) - => componentType switch - { - 5120 => normalized ? Math.Max((sbyte)buffer[offset] / 127f, -1f) : (sbyte)buffer[offset], - 5121 => normalized ? buffer[offset] / 255f : buffer[offset], - 5122 => normalized + ) => componentType switch + { + 5120 => normalized ? Math.Max((sbyte)buffer[offset] / 127f, -1f) : (sbyte)buffer[offset], + 5121 => normalized ? buffer[offset] / 255f : buffer[offset], + 5122 => normalized ? Math.Max(BinaryPrimitives.ReadInt16LittleEndian(buffer.AsSpan(offset, 2)) / 32767f, -1f) : BinaryPrimitives.ReadInt16LittleEndian(buffer.AsSpan(offset, 2)), - 5123 => normalized + 5123 => normalized ? BinaryPrimitives.ReadUInt16LittleEndian(buffer.AsSpan(offset, 2)) / 65535f : BinaryPrimitives.ReadUInt16LittleEndian(buffer.AsSpan(offset, 2)), - 5125 => normalized + 5125 => normalized ? BinaryPrimitives.ReadUInt32LittleEndian(buffer.AsSpan(offset, 4)) / (float)uint.MaxValue : BinaryPrimitives.ReadUInt32LittleEndian(buffer.AsSpan(offset, 4)), - 5126 => BitConverter.Int32BitsToSingle( - BinaryPrimitives.ReadInt32LittleEndian(buffer.AsSpan(offset, 4))), - _ => throw new RenderingAssetFormatException("$gltf.accessor", $"Unsupported component type '{componentType}'.") - }; + 5126 => BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(buffer.AsSpan(offset, 4))), + _ => throw new RenderingAssetFormatException("$gltf.accessor", $"Unsupported component type '{componentType}'.") + }; private static void ValidateAccessorBounds( Accessor accessor, @@ -484,7 +482,8 @@ int index { throw new RenderingAssetFormatException( $"$gltf.accessors[{index}]", - "Accessor exceeds its buffer view or uses an invalid stride."); + "Accessor exceeds its buffer view or uses an invalid stride." + ); } } @@ -492,31 +491,28 @@ private static Accessor GetAccessor( IReadOnlyList accessors, int index, string semantic - ) - => index >= 0 && index < accessors.Count - ? accessors[index] - : throw new RenderingAssetFormatException( - $"$gltf.{semantic}", - $"Accessor index '{index}' is out of range."); + ) => index >= 0 && index < accessors.Count + ? accessors[index] + : throw new RenderingAssetFormatException($"$gltf.{semantic}", $"Accessor index '{index}' is out of range."); private static int ComponentCount(string type) => type switch - { - "SCALAR" => 1, - "VEC2" => 2, - "VEC3" => 3, - "VEC4" => 4, - _ => throw new RenderingAssetFormatException("$gltf.accessor.type", $"Unsupported accessor type '{type}'.") - }; + { + "SCALAR" => 1, + "VEC2" => 2, + "VEC3" => 3, + "VEC4" => 4, + _ => throw new RenderingAssetFormatException("$gltf.accessor.type", $"Unsupported accessor type '{type}'.") + }; private static int ComponentSize(int type) => type switch - { - 5120 or 5121 => 1, - 5122 or 5123 => 2, - 5125 or 5126 => 4, - _ => throw new RenderingAssetFormatException("$gltf.accessor.componentType", $"Unsupported component type '{type}'.") - }; + { + 5120 or 5121 => 1, + 5122 or 5123 => 2, + 5125 or 5126 => 4, + _ => throw new RenderingAssetFormatException("$gltf.accessor.componentType", $"Unsupported component type '{type}'.") + }; private static void ValidateAttributeCount( int expected, @@ -527,7 +523,8 @@ string semantic { throw new RenderingAssetFormatException( $"$gltf.attributes.{semantic}", - "Attribute count does not match POSITION."); + "Attribute count does not match POSITION." + ); } } @@ -547,8 +544,8 @@ string path ) { string normalized = value.Replace('\\', '/').TrimStart('/'); if (string.IsNullOrWhiteSpace(normalized) - || normalized.Split('/', StringSplitOptions.RemoveEmptyEntries).Contains("..", StringComparer.Ordinal)) - { + || normalized.Split('/', StringSplitOptions.RemoveEmptyEntries).Contains("..", StringComparer.Ordinal) + ) { throw new RenderingAssetFormatException(path, "A project-relative URI without '..' is required."); } @@ -564,8 +561,7 @@ private static string GetProjectDirectory(string sourcePath) private static string CombineProjectPath( string directory, string relative - ) - => string.IsNullOrEmpty(directory) ? relative : $"{directory}/{relative}"; + ) => string.IsNullOrEmpty(directory) ? relative : $"{directory}/{relative}"; private readonly record struct BufferView( byte[] buffer, @@ -573,6 +569,7 @@ private readonly record struct BufferView( int length, int stride ); + private readonly record struct Accessor( BufferView view, int offset, @@ -582,4 +579,3 @@ private readonly record struct Accessor( bool normalized ); } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs index 1e1c28438..1426db37d 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs @@ -1,12 +1,12 @@ -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; @@ -42,9 +42,12 @@ CancellationToken cancellationToken MaterialAsset asset = NativeAssetSourceSerialization.Import( context.sourceBytes.Span, context.services, - out IReadOnlyList dependencies); + out IReadOnlyList dependencies + ); foreach (AssetDependency dependency in dependencies) + { output.DependsOnAsset(dependency); + } Validate(asset); output.SetAsset(asset); await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken) @@ -73,32 +76,36 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); Validate(asset); - return ValueTask.FromResult?>(NativeAssetSourceSerialization.Export( - asset, - context.services)); + return ValueTask.FromResult?>( + NativeAssetSourceSerialization.Export(asset, context.services) + ); } private static void Validate(MaterialAsset asset) { ShaderDefinition definition = asset.shader?.definition - ?? throw new InvalidOperationException("A material requires a shader with a committed definition."); + ?? throw new InvalidOperationException("A material requires a shader with a committed definition."); Dictionary properties = definition.properties .ToDictionary(static property => property.id); foreach (MaterialPropertyEntry property in asset.properties) { if (!properties.TryGetValue(property.id, out ShaderPropertyDefinition shaderProperty)) + { throw new InvalidOperationException($"Material property '{property.id}' is not declared by its shader."); + } if (shaderProperty.bindingKind is ShaderPropertyBindingKind.StorageTexture - or ShaderPropertyBindingKind.StorageBuffer) - { + or ShaderPropertyBindingKind.StorageBuffer + ) { throw new InvalidOperationException( - $"Material property '{property.id}' is Pipeline-owned storage state and cannot be persisted by a material."); + $"Material property '{property.id}' is Pipeline-owned storage state and cannot be persisted by a material." + ); } if (!IsCompatible(shaderProperty.type, property.value.kind)) { throw new InvalidOperationException( - $"Material property '{property.id}' value '{property.value.kind}' is incompatible with " + - $"shader type '{shaderProperty.type}'."); + $"Material property '{property.id}' value '{property.value.kind}' is incompatible with " + + $"shader type '{shaderProperty.type}'." + ); } } HashSet options = definition.keywords @@ -106,26 +113,26 @@ private static void Validate(MaterialAsset asset) .ToHashSet(StringComparer.Ordinal); string? unknownKeyword = asset.keywords.FirstOrDefault(keyword => !options.Contains(keyword)); if (unknownKeyword is not null) + { throw new InvalidOperationException($"Material keyword '{unknownKeyword}' is not declared by its shader."); + } } private static bool IsCompatible( ShaderPropertyType propertyType, MaterialValueKind valueKind - ) - => propertyType switch - { - ShaderPropertyType.Float => valueKind == MaterialValueKind.Float, - ShaderPropertyType.Vector2 or ShaderPropertyType.Vector3 or ShaderPropertyType.Vector4 => - valueKind == MaterialValueKind.Vector, - ShaderPropertyType.Color => valueKind == MaterialValueKind.Color, - ShaderPropertyType.Matrix4x4 => valueKind == MaterialValueKind.Matrix, - ShaderPropertyType.Texture2D - or ShaderPropertyType.Texture2DArray - or ShaderPropertyType.Texture3D - or ShaderPropertyType.TextureCube => - valueKind == MaterialValueKind.Texture, - _ => false - }; + ) => propertyType switch + { + ShaderPropertyType.Float => valueKind == MaterialValueKind.Float, + ShaderPropertyType.Vector2 or ShaderPropertyType.Vector3 or ShaderPropertyType.Vector4 => + valueKind == MaterialValueKind.Vector, + ShaderPropertyType.Color => valueKind == MaterialValueKind.Color, + ShaderPropertyType.Matrix4x4 => valueKind == MaterialValueKind.Matrix, + ShaderPropertyType.Texture2D + or ShaderPropertyType.Texture2DArray + or ShaderPropertyType.Texture3D + or ShaderPropertyType.TextureCube => + valueKind == MaterialValueKind.Texture, + _ => false + }; } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ObjMeshParser.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ObjMeshParser.cs index f3707bc90..db6e38114 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ObjMeshParser.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ObjMeshParser.cs @@ -1,10 +1,10 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using Inno.Core.Mathematics; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; @@ -37,23 +37,34 @@ string text { case "v": RequirePartCount(parts, 4, sourcePath, lineIndex); - positions.Add(new Vector3( - ParseFloat(parts[1], sourcePath, lineIndex), - ParseFloat(parts[2], sourcePath, lineIndex), - ParseFloat(parts[3], sourcePath, lineIndex))); + positions.Add( + new Vector3( + ParseFloat(parts[1], sourcePath, lineIndex), + ParseFloat(parts[2], sourcePath, lineIndex), + ParseFloat(parts[3], sourcePath, lineIndex) + ) + ); break; case "vn": RequirePartCount(parts, 4, sourcePath, lineIndex); - normals.Add(Vector3.NormalizeSafe(new Vector3( - ParseFloat(parts[1], sourcePath, lineIndex), - ParseFloat(parts[2], sourcePath, lineIndex), - ParseFloat(parts[3], sourcePath, lineIndex)))); + normals.Add( + Vector3.NormalizeSafe( + new Vector3( + ParseFloat(parts[1], sourcePath, lineIndex), + ParseFloat(parts[2], sourcePath, lineIndex), + ParseFloat(parts[3], sourcePath, lineIndex) + ) + ) + ); break; case "vt": RequirePartCount(parts, 3, sourcePath, lineIndex); - textureCoordinates.Add(new Vector2( - ParseFloat(parts[1], sourcePath, lineIndex), - ParseFloat(parts[2], sourcePath, lineIndex))); + textureCoordinates.Add( + new Vector2( + ParseFloat(parts[1], sourcePath, lineIndex), + ParseFloat(parts[2], sourcePath, lineIndex) + ) + ); break; case "f": if (parts.Length < 4) @@ -70,7 +81,8 @@ string text normals, textureCoordinates, vertices, - vertexMap)) + vertexMap + )) .ToArray(); for (int corner = 1; corner < polygon.Length - 1; corner++) { @@ -98,7 +110,8 @@ string text value.position, Vector3.NormalizeSafe(value.normal), ToTangent(value.tangent, value.tangentW), - value.textureCoordinate)).ToArray(); + value.textureCoordinate + )).ToArray(); return new GeometryData(resultVertices, [.. indices], [.. sections]); } @@ -118,11 +131,17 @@ IReadOnlyList indices Vector3 edge2 = v2.position - v0.position; Vector3 faceNormal = Vector3.Cross(edge1, edge2); if (!v0.hasNormal) + { v0.normal += faceNormal; + } if (!v1.hasNormal) + { v1.normal += faceNormal; + } if (!v2.hasNormal) + { v2.normal += faceNormal; + } Vector2 uv1 = v1.textureCoordinate - v0.textureCoordinate; Vector2 uv2 = v2.textureCoordinate - v0.textureCoordinate; @@ -132,11 +151,17 @@ IReadOnlyList indices float inverse = 1f / determinant; Vector3 tangent = (edge1 * uv2.y - edge2 * uv1.y) * inverse; if (!v0.hasTangent) + { v0.tangent += tangent; + } if (!v1.hasTangent) + { v1.tangent += tangent; + } if (!v2.hasTangent) + { v2.tangent += tangent; + } } } } @@ -154,11 +179,11 @@ Dictionary vertexMap string[] values = token.Split('/'); int position = ResolveIndex(values[0], positions.Count, sourcePath, lineIndex, "position"); int texture = values.Length > 1 && values[1].Length != 0 - ? ResolveIndex(values[1], textureCoordinates.Count, sourcePath, lineIndex, "texture coordinate") - : -1; + ? ResolveIndex(values[1], textureCoordinates.Count, sourcePath, lineIndex, "texture coordinate") + : -1; int normal = values.Length > 2 && values[2].Length != 0 - ? ResolveIndex(values[2], normals.Count, sourcePath, lineIndex, "normal") - : -1; + ? ResolveIndex(values[2], normals.Count, sourcePath, lineIndex, "normal") + : -1; var key = new ObjVertexKey(position, texture, normal); if (vertexMap.TryGetValue(key, out uint existing)) { @@ -185,8 +210,8 @@ private static int ResolveIndex( string kind ) { if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) - || parsed == 0) - { + || parsed == 0 + ) { throw Error(sourcePath, lineIndex, $"Invalid OBJ {kind} index '{value}'."); } @@ -203,11 +228,10 @@ private static float ParseFloat( string value, string sourcePath, int lineIndex - ) - => float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float result) - && float.IsFinite(result) - ? result - : throw Error(sourcePath, lineIndex, $"Invalid finite float '{value}'."); + ) => float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float result) + && float.IsFinite(result) + ? result + : throw Error(sourcePath, lineIndex, $"Invalid finite float '{value}'."); private static void RequirePartCount( IReadOnlyList values, @@ -250,8 +274,7 @@ private static RenderingAssetFormatException Error( string path, int lineIndex, string message - ) - => new($"{path}:{lineIndex + 1}", message); + ) => new($"{path}:{lineIndex + 1}", message); private readonly record struct ObjVertexKey( int position, @@ -270,4 +293,3 @@ internal sealed class MutableVertex internal float tangentW = 1f; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs index e3672b000..3a5d9ac7d 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs @@ -1,12 +1,12 @@ -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; @@ -42,9 +42,12 @@ CancellationToken cancellationToken RenderPipelineAsset asset = NativeAssetSourceSerialization.Import( context.sourceBytes.Span, context.services, - out IReadOnlyList dependencies); + out IReadOnlyList dependencies + ); foreach (AssetDependency dependency in dependencies) + { output.DependsOnAsset(dependency); + } Validate(asset); output.SetAsset(asset); await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken) @@ -73,9 +76,9 @@ CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); Validate(asset); - return ValueTask.FromResult?>(NativeAssetSourceSerialization.Export( - asset, - context.services)); + return ValueTask.FromResult?>( + NativeAssetSourceSerialization.Export(asset, context.services) + ); } private static void Validate(RenderPipelineAsset asset) @@ -85,9 +88,12 @@ private static void Validate(RenderPipelineAsset asset) .GroupBy(static feature => feature.featureTypeId, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicate is not null) + { throw new InvalidOperationException($"Pipeline feature '{duplicate}' is configured more than once."); + } if (asset.features.Any(static feature => feature.enabled && string.IsNullOrWhiteSpace(feature.featureTypeId))) + { throw new InvalidOperationException("Every enabled pipeline feature requires a stable extension ID."); + } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs index ce6398ee7..75951dfd9 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs @@ -1,5 +1,5 @@ -using Inno.Rendering; using System; +using Inno.Rendering; namespace Inno.Rendering.Assets.Authoring; @@ -9,9 +9,5 @@ internal sealed class RenderingAssetFormatException : FormatException internal RenderingAssetFormatException( string path, string message - ) - : base($"{path}: {message}") - { - } + ) : base($"{path}: {message}") {} } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs index 2a29ac805..3c2f87c80 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs @@ -1,3 +1,8 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Graphs; @@ -5,11 +10,6 @@ using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Shaders; -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; namespace Inno.Rendering.Assets.Authoring; @@ -48,33 +48,53 @@ CancellationToken cancellationToken byte[] captured; try { - captured = ShaderGraphArtifact.Capture(graph, context.types, context.serialization, owner, + captured = ShaderGraphArtifact.Capture( + graph, + context.types, + context.serialization, + owner, ( id, path ) => { context.DependsOnArtifact(id); - AssetObject resolved = context.references.Resolve(id, context.services.GetStableTypeId(), - path, typeof(ShaderFunctionAsset), $"shader.sources[{id}]"); + AssetObject resolved = context.references.Resolve( + id, + context.services.GetStableTypeId(), + path, + typeof(ShaderFunctionAsset), + $"shader.sources[{id}]" + ); if (resolved is not ShaderFunctionAsset { isMissing: false } source) + { throw new InvalidDataException($"Shader function '{id}' is unavailable. Its graph reference is preserved."); + } using ArtifactLease sourceLease = context.AcquireArtifact(source.identity.persistentId, ShaderSourceBundle.outputName); return sourceLease.ReadAllBytes(); - }, cancellationToken, + }, + cancellationToken, ( id, path ) => { context.DependsOnArtifact(id); - AssetObject resolved = context.references.Resolve(id, context.services.GetStableTypeId(), - path, typeof(ShaderAsset), $"shader.graphNodes[{id}]"); + AssetObject resolved = context.references.Resolve( + id, + context.services.GetStableTypeId(), + path, + typeof(ShaderAsset), + $"shader.graphNodes[{id}]" + ); if (resolved is not ShaderAsset { isMissing: false } node) + { throw new InvalidDataException($"Shader graph node '{id}' is unavailable. Its graph reference is preserved."); + } using ArtifactLease graphLease = context.AcquireArtifact(node.identity.persistentId, ShaderGraphArtifact.outputName); return ShaderGraphArtifact.ReadDocument(graphLease.ReadAllBytes(), context.serialization); - }); + } + ); } catch (ShaderTargetUnavailableException exception) { @@ -84,16 +104,26 @@ CancellationToken cancellationToken // Function dependencies are authoring-only; texture defaults remain ordinary runtime references. _ = context.serialization.Serialize(definition, owner); foreach (AssetDependency dependency in dependencies.dependencies) + { output.DependsOnAsset(dependency); + } var asset = new ShaderAsset(); asset.SetDefinition(definition, context.serialization, owner); output.SetAsset(asset); if (definition.passes.Length == 0) + { output.SetDeploymentScope(AssetDeploymentScope.AuthoringOnly); + } else + { await output.WriteArtifactAsync("runtime", ReadOnlyMemory.Empty, cancellationToken).ConfigureAwait(false); - await output.WriteArtifactAsync(ShaderGraphArtifact.outputName, captured, - cancellationToken, AssetDeploymentScope.AuthoringOnly).ConfigureAwait(false); + } + await output.WriteArtifactAsync( + ShaderGraphArtifact.outputName, + captured, + cancellationToken, + AssetDeploymentScope.AuthoringOnly + ).ConfigureAwait(false); } /// @@ -117,8 +147,14 @@ await output.WriteArtifactAsync(ShaderGraphArtifact.outputName, captured, CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); - return ValueTask.FromResult?>(GraphDocumentCodec.Encode( - ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(asset, context.artifacts), context.serialization), context.serialization)); + return ValueTask.FromResult?>( + GraphDocumentCodec.Encode( + ShaderGraphArtifact.ReadDocument( + ShaderGraphArtifact.Read(asset, context.artifacts), + context.serialization + ), + context.serialization + ) + ); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs index 185a0224f..1402c26e2 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs @@ -15,21 +15,24 @@ public sealed class ShaderFunctionAsset : AssetObject /// Gets the configured source language identity. /// [SerializableProperty] public string languageId { get; internal set; } = string.Empty; + /// /// Gets the explicitly exported functions available to graph source-function nodes. /// [SerializableProperty] public string[] exports { get; internal set; } = []; + /// /// Gets the adapter implementation identity. /// [SerializableProperty] public string implementationId { get; internal set; } = string.Empty; + /// /// Gets the author-declared catalog path used by Shader creation tools. /// [SerializableProperty] public string catalogPath { get; internal set; } = string.Empty; + /// /// Gets the stable ordering value inside the authoring catalog. /// [SerializableProperty] public int catalogOrder { get; internal set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs index 158ce9547..8fb351965 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs @@ -1,14 +1,14 @@ -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Core.Serialization; -using Inno.Rendering; -using Inno.Rendering.Shaders; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Serialization; +using Inno.Rendering; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring; @@ -20,10 +20,12 @@ internal sealed class ShaderFunctionImporter : AssetImporter public override IReadOnlyList supportedExtensions { get; } = [".ishadersource"]; + /// /// Gets whether imported output is deployed to runtime, editor, or both domains. /// public override AssetDeploymentScope deploymentScope => AssetDeploymentScope.AuthoringOnly; + /// /// Creates an import settings using this implementation's validated inputs. /// @@ -53,32 +55,49 @@ protected override async ValueTask ImportAsync( CancellationToken cancellationToken ) { var settings = context.importSettings as ShaderSourceImportSettings - ?? throw new InvalidOperationException("Shader source requires its standard import settings."); + ?? throw new InvalidOperationException("Shader source requires its standard import settings."); ArgumentException.ThrowIfNullOrWhiteSpace(settings.languageId); ArgumentException.ThrowIfNullOrWhiteSpace(settings.implementationId); string[] exports = (settings.exports ?? []).Where(static value => !string.IsNullOrWhiteSpace(value)) - .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); if (exports.Length == 0) + { throw new InvalidDataException("Shader source libraries must export at least one named function."); + } var source = new ShaderSourceFile(context.assetPath.ToString(), context.ReadUtf8Text()); using var frontends = new ShaderSourceFrontendRegistry(context.types); var modules = new Dictionary(StringComparer.Ordinal); foreach (string export in exports) { var requests = new List - { new(settings.implementationId, settings.languageId, new(source, export, new SourceResolver(context))) }; + { + new(settings.implementationId, settings.languageId, new(source, export, new SourceResolver(context))) + }; foreach (ShaderFunctionAsset implementation in settings.implementations ?? []) { if (implementation is null || implementation.isMissing) - throw new InvalidDataException("An alternate shader implementation is missing; its reference must be repaired before compilation."); + { + throw new InvalidDataException( + "An alternate shader implementation is missing; its reference must be repaired before compilation." + ); + } context.DependsOnArtifact(implementation.identity.persistentId); using ArtifactLease lease = context.AcquireArtifact(implementation.identity.persistentId, ShaderSourceBundle.outputName); requests.AddRange(ShaderSourceBundle.Decode(lease.ReadAllBytes(), export, context.serialization)); } ShaderSourceModuleAnalysis module = frontends.AnalyzeModule(requests); if (!module.succeeded) - throw new InvalidDataException(string.Join("\n", module.diagnostics.Select(static diagnostic => - $"{diagnostic.location.assetPath}:{diagnostic.location.line}:{diagnostic.location.column}: {diagnostic.message}"))); + { + throw new InvalidDataException( + string.Join( + "\n", + module.diagnostics.Select(static diagnostic => + $"{diagnostic.location.assetPath}:{diagnostic.location.line}:{diagnostic.location.column}: {diagnostic.message}") + ) + ); + } modules.Add(export, module); } output.SetAsset(new ShaderFunctionAsset @@ -89,13 +108,19 @@ CancellationToken cancellationToken catalogPath = NormalizeCatalogPath(settings.catalogPath), catalogOrder = settings.catalogOrder }); - await output.WriteArtifactAsync(ShaderSourceBundle.outputName, ShaderSourceBundle.Encode(modules, context.serialization), - cancellationToken, AssetDeploymentScope.AuthoringOnly).ConfigureAwait(false); + await output.WriteArtifactAsync( + ShaderSourceBundle.outputName, + ShaderSourceBundle.Encode(modules, context.serialization), + cancellationToken, + AssetDeploymentScope.AuthoringOnly + ).ConfigureAwait(false); } private static string NormalizeCatalogPath(string? value) - => string.Join('/', (value ?? string.Empty).Split('/', - StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + => string.Join( + '/', + (value ?? string.Empty).Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + ); private sealed class SourceResolver(AssetImportContext context) : IShaderSourceResolver { @@ -117,11 +142,15 @@ string include ) { AssetPath owner = AssetPath.Parse(includingFile); string normalized = include.Replace('\\', '/'); - AssetPath path = normalized.Contains("::", StringComparison.Ordinal) ? AssetPath.Parse(normalized) - : new AssetPath(owner.source, (Path.GetDirectoryName(owner.localPath)?.Replace('\\', '/') is { Length: > 0 } directory - ? directory + "/" : "") + normalized); + AssetPath path = normalized.Contains("::", StringComparison.Ordinal) + ? AssetPath.Parse(normalized) + : new AssetPath( + owner.source, + (Path.GetDirectoryName(owner.localPath)?.Replace('\\', '/') is { Length: > 0 } directory + ? directory + "/" + : "") + normalized + ); return new(path.ToString(), context.ReadSourceUtf8Text(path)); } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs index a15ca46e4..b4814b2ae 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs @@ -14,25 +14,29 @@ public sealed class ShaderSourceImportSettings : ISerializable /// Gets or sets the registered language identity; an empty selection is an import error. /// [SerializableProperty] public string languageId { get; set; } = string.Empty; + /// /// Gets or sets the explicitly exported function names. Unlisted helpers remain private to the source library. /// [SerializableProperty] public string[] exports { get; set; } = ["Evaluate"]; + /// /// Gets or sets the exact implementation key used by the selected rendering backend. /// [SerializableProperty] public string implementationId { get; set; } = string.Empty; + /// /// Gets or sets alternate source implementations; all must expose the same public interface with unique backend IDs. /// [SerializableProperty] public ShaderFunctionAsset[] implementations { get; set; } = []; + /// /// Gets or sets the slash-delimited authoring catalog path used to group this library in creation UIs. /// [SerializableProperty] public string catalogPath { get; set; } = string.Empty; + /// /// Gets or sets the stable ordering value of this library inside its authoring catalog group. /// [SerializableProperty] public int catalogOrder { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs index e6fe073d2..95dd0dd15 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs @@ -1,6 +1,3 @@ -using Inno.Assets.Pipeline; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Buffers.Binary; using System.Collections.Generic; @@ -8,6 +5,9 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; +using Inno.Assets.Pipeline; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; @@ -53,7 +53,8 @@ CancellationToken cancellationToken width, height, context.extension == ".hdr" ? TextureColorSpace.Linear : TextureColorSpace.Srgb, - context.extension.TrimStart('.').ToLowerInvariant()); + context.extension.TrimStart('.').ToLowerInvariant() + ); output.SetAsset(asset); await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken).ConfigureAwait(false); await output.WriteArtifactAsync("source", context.sourceBytes, cancellationToken).ConfigureAwait(false); @@ -139,8 +140,8 @@ internal static (int width, int height) ReadHdrSize(string text) Match match = HdrResolutionPattern().Match(text); if (!match.Success || !int.TryParse(match.Groups[1].Value, out int height) - || !int.TryParse(match.Groups[2].Value, out int width)) - { + || !int.TryParse(match.Groups[2].Value, out int width) + ) { throw new RenderingAssetFormatException("texture.hdr", "Radiance HDR resolution line is missing."); } @@ -153,12 +154,10 @@ private static (int width, int height) RequirePositiveSize( int width, int height, string path - ) - => width > 0 && height > 0 - ? (width, height) - : throw new RenderingAssetFormatException(path, "Texture dimensions must be positive."); + ) => width > 0 && height > 0 + ? (width, height) + : throw new RenderingAssetFormatException(path, "Texture dimensions must be positive."); [GeneratedRegex(@"(?m)^[+-]Y\s+(\d+)\s+[+-]X\s+(\d+)\s*$")] private static partial Regex HdrResolutionPattern(); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs index 616829806..39aea9394 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs @@ -1,8 +1,8 @@ -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -53,16 +53,22 @@ ReadOnlySpan definitionData ArgumentNullException.ThrowIfNull(passes); RenderShaderPassArtifact[] passSnapshot = passes.ToArray(); if (passSnapshot.Length == 0) + { throw new ArgumentException("A deployed shader artifact must contain at least one pass.", nameof(passes)); + } if (passSnapshot.Select(static pass => pass.name).Distinct(StringComparer.Ordinal).Count() != passSnapshot.Length) + { throw new ArgumentException("A deployed shader artifact cannot repeat a pass name.", nameof(passes)); + } this.shaderName = shaderName; this.targetKey = targetKey; this.variant = variant; this.shaderInterface = RenderShaderPassArtifact.CloneInterface(shaderInterface); m_passes = Array.AsReadOnly(passSnapshot); if (definitionData.IsEmpty) + { throw new ArgumentException("A shader publication requires its captured runtime contract.", nameof(definitionData)); + } m_definitionData = definitionData.ToArray(); contentHash = Convert.ToHexString(SHA256.HashData(RenderShaderArtifactCodec.Encode(this))); } @@ -102,4 +108,3 @@ ReadOnlySpan definitionData /// public IReadOnlyList passes => m_passes; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs index e9609edd9..efa81f951 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs @@ -1,9 +1,9 @@ -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -88,28 +88,36 @@ RenderShaderVariant expectedVariant using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); if (!reader.ReadBytes(S_MAGIC.Length).AsSpan().SequenceEqual(S_MAGIC)) + { throw new InvalidDataException("Shader artifact magic is invalid."); + } string shaderName = ReadString(reader); if (!string.Equals(shaderName, expectedShaderName, StringComparison.Ordinal)) { throw new InvalidDataException( - $"Shader artifact '{shaderName}' does not match requested shader '{expectedShaderName}'."); + $"Shader artifact '{shaderName}' does not match requested shader '{expectedShaderName}'." + ); } string targetKey = ReadString(reader); RenderShaderVariant variant = RenderShaderVariant.Parse(ReadString(reader)); if (variant != expectedVariant) { throw new InvalidDataException( - $"Shader artifact variant '{variant}' does not match requested variant '{expectedVariant}'."); + $"Shader artifact variant '{variant}' does not match requested variant '{expectedVariant}'." + ); } int definitionLength = ReadCount(reader, C_MAX_STAGE_BYTES, "shader definition byte"); if (definitionLength == 0) + { throw new InvalidDataException("A shader publication has no runtime contract."); + } byte[] definitionData = ReadBytes(reader, definitionLength); ShaderInterface shaderInterface = ReadInterface(reader); int passCount = ReadCount(reader, C_MAX_PASSES, "shader pass"); if (passCount == 0) + { throw new InvalidDataException("Shader artifact contains no pass."); + } var passes = new RenderShaderPassArtifact[passCount]; for (int index = 0; index < passes.Length; index++) { @@ -124,18 +132,17 @@ RenderShaderVariant expectedVariant ShaderStage stage = ReadEnum(reader); int byteCount = ReadCount(reader, C_MAX_STAGE_BYTES, "shader stage byte"); if (byteCount == 0) + { throw new InvalidDataException($"Shader pass '{passName}' contains an empty stage."); + } stages[stageIndex] = new RenderShaderStageArtifact(stage, ReadBytes(reader, byteCount)); } - passes[index] = new RenderShaderPassArtifact( - passName, - programKind, - rasterState, - passInterface, - stages); + passes[index] = new RenderShaderPassArtifact(passName, programKind, rasterState, passInterface, stages); } if (stream.Position != stream.Length) + { throw new InvalidDataException("Shader artifact contains trailing data."); + } return new RenderShaderArtifact(shaderName, targetKey, variant, shaderInterface, passes, definitionData); } catch (InvalidDataException) @@ -143,10 +150,10 @@ RenderShaderVariant expectedVariant throw; } catch (Exception exception) when (exception is EndOfStreamException - or IOException - or ArgumentException - or FormatException - or OverflowException) + or IOException + or ArgumentException + or FormatException + or OverflowException) { throw new InvalidDataException("Shader artifact payload is corrupt.", exception); } @@ -168,7 +175,9 @@ ShaderInterface shaderInterface WriteString(writer, binding.nativeName); writer.Write(binding.location.HasValue); if (binding.location.HasValue) + { writer.Write(binding.location.Value); + } } } @@ -181,15 +190,21 @@ private static ShaderInterface ReadInterface(BinaryReader reader) { string id = ReadString(reader); if (!identities.Add(id)) + { throw new InvalidDataException($"Shader interface repeats binding '{id}'."); + } ShaderPropertyType type = ReadEnum(reader); ShaderStage stages = (ShaderStage)reader.ReadInt32(); const ShaderStage validStages = ShaderStage.Vertex | ShaderStage.Fragment | ShaderStage.Compute; if (stages == ShaderStage.None || (stages & ~validStages) != 0) + { throw new InvalidDataException($"Shader binding '{id}' has an invalid stage mask."); + } int arrayCount = reader.ReadInt32(); if (arrayCount <= 0) + { throw new InvalidDataException($"Shader binding '{id}' has an invalid array count."); + } bindings[index] = new ShaderInterfaceBinding( new ShaderPropertyId(id), type, @@ -198,7 +213,8 @@ private static ShaderInterface ReadInterface(BinaryReader reader) ReadEnum(reader), ReadEnum(reader), ReadString(reader), - reader.ReadBoolean() ? reader.ReadInt32() : null); + reader.ReadBoolean() ? reader.ReadInt32() : null + ); } return new ShaderInterface(bindings); } @@ -227,27 +243,27 @@ RenderRasterState state private static RenderRasterState ReadRasterState(BinaryReader reader) => new() + { + topology = ReadEnum(reader), + cull = ReadEnum(reader), + frontFace = ReadEnum(reader), + depthCompare = ReadEnum(reader), + depthWrite = reader.ReadBoolean(), + colorWriteMask = reader.ReadByte(), + multisampling = reader.ReadBoolean(), + blend = new RenderBlendState { - topology = ReadEnum(reader), - cull = ReadEnum(reader), - frontFace = ReadEnum(reader), - depthCompare = ReadEnum(reader), - depthWrite = reader.ReadBoolean(), - colorWriteMask = reader.ReadByte(), - multisampling = reader.ReadBoolean(), - blend = new RenderBlendState - { - enabled = reader.ReadBoolean(), - colorSource = ReadEnum(reader), - colorDestination = ReadEnum(reader), - colorEquation = ReadEnum(reader), - alphaSource = ReadEnum(reader), - alphaDestination = ReadEnum(reader), - alphaEquation = ReadEnum(reader), - constantRgba = reader.ReadUInt32(), - alphaToCoverage = reader.ReadBoolean() - } - }; + enabled = reader.ReadBoolean(), + colorSource = ReadEnum(reader), + colorDestination = ReadEnum(reader), + colorEquation = ReadEnum(reader), + alphaSource = ReadEnum(reader), + alphaDestination = ReadEnum(reader), + alphaEquation = ReadEnum(reader), + constantRgba = reader.ReadUInt32(), + alphaToCoverage = reader.ReadBoolean() + } + }; private static void WriteString( BinaryWriter writer, @@ -256,7 +272,9 @@ string value ArgumentNullException.ThrowIfNull(value); byte[] bytes = Encoding.UTF8.GetBytes(value); if (bytes.Length > C_MAX_STRING_BYTES) + { throw new ArgumentException("Shader artifact string exceeds the deployment safety limit.", nameof(value)); + } writer.Write(bytes.Length); writer.Write(bytes); } @@ -274,7 +292,9 @@ string subject ) { int value = reader.ReadInt32(); if (value < 0 || value > maximum) + { throw new InvalidDataException($"Shader artifact {subject} count '{value}' is outside the valid range."); + } return value; } @@ -284,7 +304,9 @@ int count ) { byte[] bytes = reader.ReadBytes(count); if (bytes.Length != count) + { throw new EndOfStreamException("Shader artifact ended before the declared payload length."); + } return bytes; } @@ -293,8 +315,9 @@ private static TEnum ReadEnum(BinaryReader reader) { int value = reader.ReadInt32(); if (!Enum.IsDefined(typeof(TEnum), value)) + { throw new InvalidDataException($"Shader artifact contains invalid {typeof(TEnum).Name} value '{value}'."); + } return (TEnum)Enum.ToObject(typeof(TEnum), value); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs index 80747c1ee..dcaa5504b 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs @@ -1,8 +1,8 @@ -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -44,7 +44,9 @@ IReadOnlyList stages ) { ArgumentException.ThrowIfNullOrWhiteSpace(name); if (!Enum.IsDefined(programKind)) + { throw new ArgumentOutOfRangeException(nameof(programKind)); + } ArgumentNullException.ThrowIfNull(rasterState); ArgumentNullException.ThrowIfNull(shaderInterface); ArgumentNullException.ThrowIfNull(stages); @@ -83,28 +85,31 @@ IReadOnlyList stages public IReadOnlyList stages => m_stages; internal static ShaderInterface CloneInterface(ShaderInterface source) - => new(source.bindings.Select(static binding => new ShaderInterfaceBinding( - binding.id, - binding.type, - binding.stages, - binding.arrayCount, - binding.bindingKind, - binding.storageAccess, - binding.nativeName, - binding.location)).ToArray()); + => new( + source.bindings.Select(static binding => new ShaderInterfaceBinding( + binding.id, + binding.type, + binding.stages, + binding.arrayCount, + binding.bindingKind, + binding.storageAccess, + binding.nativeName, + binding.location + )).ToArray() + ); internal static RenderRasterState CloneRasterState(RenderRasterState source) => new() - { - topology = source.topology, - cull = source.cull, - frontFace = source.frontFace, - depthCompare = source.depthCompare, - depthWrite = source.depthWrite, - blend = source.blend, - colorWriteMask = source.colorWriteMask, - multisampling = source.multisampling - }; + { + topology = source.topology, + cull = source.cull, + frontFace = source.frontFace, + depthCompare = source.depthCompare, + depthWrite = source.depthWrite, + blend = source.blend, + colorWriteMask = source.colorWriteMask, + multisampling = source.multisampling + }; private static void ValidateStages( ShaderProgramKind programKind, @@ -112,14 +117,14 @@ IReadOnlyCollection stages ) { ShaderStage[] actual = stages.Select(static value => value.stage).Order().ToArray(); ShaderStage[] expected = programKind == ShaderProgramKind.Raster - ? [ShaderStage.Vertex, ShaderStage.Fragment] - : [ShaderStage.Compute]; + ? [ShaderStage.Vertex, ShaderStage.Fragment] + : [ShaderStage.Compute]; if (!actual.SequenceEqual(expected)) { throw new ArgumentException( $"Program kind '{programKind}' requires stages '{string.Join(", ", expected)}'.", - nameof(stages)); + nameof(stages) + ); } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs index 9cda30256..8095cc426 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs @@ -1,8 +1,8 @@ -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -31,9 +31,13 @@ public RenderShaderStageArtifact( ReadOnlySpan bytes ) { if (stage is not ShaderStage.Vertex and not ShaderStage.Fragment and not ShaderStage.Compute) + { throw new ArgumentException("A deployed shader stage must identify one programmable stage.", nameof(stage)); + } if (bytes.IsEmpty) + { throw new ArgumentException("A deployed shader stage cannot be empty.", nameof(bytes)); + } this.stage = stage; m_bytes = bytes.ToArray(); } @@ -48,4 +52,3 @@ ReadOnlySpan bytes /// public ReadOnlyMemory bytes => m_bytes; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs index d1c78deb3..49d6cbd60 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs @@ -1,8 +1,8 @@ -using Inno.Rendering; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -36,9 +36,11 @@ public RenderShaderVariant(IReadOnlyDictionary options) ValidatePart(option, nameof(options)); } - m_options = new ReadOnlyDictionary(options - .OrderBy(static value => value.Key, StringComparer.Ordinal) - .ToDictionary(static value => value.Key, static value => value.Value, StringComparer.Ordinal)); + m_options = new ReadOnlyDictionary( + options + .OrderBy(static value => value.Key, StringComparer.Ordinal) + .ToDictionary(static value => value.Key, static value => value.Value, StringComparer.Ordinal) + ); m_value = string.Join(";", m_options.Select(static pair => $"{pair.Key}={pair.Value}")); } @@ -73,23 +75,31 @@ public static RenderShaderVariant Parse(string value) { ArgumentNullException.ThrowIfNull(value); if (value.Length == 0) + { return empty; + } var options = new Dictionary(StringComparer.Ordinal); foreach (string selection in value.Split(';', StringSplitOptions.None)) { int separator = selection.IndexOf('=', StringComparison.Ordinal); if (separator <= 0 || separator == selection.Length - 1 || selection.IndexOf('=', separator + 1) >= 0) + { throw new FormatException($"Shader variant selection '{selection}' is malformed."); + } string keyword = selection[..separator]; string option = selection[(separator + 1)..]; if (!options.TryAdd(keyword, option)) + { throw new FormatException($"Shader variant repeats keyword '{keyword}'."); + } } var result = new RenderShaderVariant(options); if (!string.Equals(result.value, value, StringComparison.Ordinal)) + { throw new FormatException("Shader variant selections are not in canonical order."); + } return result; } @@ -109,9 +119,9 @@ public static RenderShaderVariant FromMaterial(MaterialAsset material) { ArgumentNullException.ThrowIfNull(material); ShaderAsset shader = material.shader - ?? throw new InvalidOperationException($"Material '{material.assetPath}' has no shader reference."); + ?? throw new InvalidOperationException($"Material '{material.assetPath}' has no shader reference."); ShaderDefinition definition = shader.definition - ?? throw new InvalidOperationException($"Shader '{shader.assetPath}' has no committed definition."); + ?? throw new InvalidOperationException($"Shader '{shader.assetPath}' has no committed definition."); return FromMaterial(material, definition); } @@ -137,7 +147,9 @@ ShaderDefinition definition ArgumentNullException.ThrowIfNull(material); ArgumentNullException.ThrowIfNull(definition); if (material.keywords.Count == 0) + { return empty; + } HashSet enabled = material.keywords.ToHashSet(StringComparer.Ordinal); var selections = new Dictionary(StringComparer.Ordinal); foreach (ShaderKeywordDefinition keyword in definition.keywords) @@ -146,18 +158,20 @@ ShaderDefinition definition if (selected.Length > 1) { throw new InvalidOperationException( - $"Material '{material.assetPath}' selects multiple options for keyword '{keyword.id}'."); + $"Material '{material.assetPath}' selects multiple options for keyword '{keyword.id}'." + ); } if (selected.Length == 1) + { selections.Add(keyword.id, selected[0]); + } } string? unknown = enabled.FirstOrDefault(option => !definition.keywords.Any(keyword => keyword.options.Contains(option, StringComparer.Ordinal))); if (unknown is not null) { - throw new InvalidOperationException( - $"Material '{material.assetPath}' enables unknown option '{unknown}'."); + throw new InvalidOperationException($"Material '{material.assetPath}' enables unknown option '{unknown}'."); } return new RenderShaderVariant(selections); } @@ -242,8 +256,8 @@ string parameterName { throw new ArgumentException( "Shader variant identifiers and options must be non-empty and cannot contain ';' or '='.", - parameterName); + parameterName + ); } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs index d81280f92..86c4973f0 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs @@ -1,8 +1,8 @@ -using Inno.Rendering; using System; using System.Globalization; using System.Security.Cryptography; using System.Text; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -36,13 +36,17 @@ public static string GetShaderPath( RenderShaderVariant variant ) { if (shaderId == Guid.Empty) + { throw new ArgumentException("A target shader path requires a persistent asset identity.", nameof(shaderId)); - return string.Join('/', + } + return string.Join( + '/', "TargetArtifacts", "Shaders", backend.ToString(), shaderId.ToString("D", CultureInfo.InvariantCulture), - HashVariant(variant.value) + ".shader"); + HashVariant(variant.value) + ".shader" + ); } /// @@ -60,12 +64,16 @@ RenderShaderVariant variant public static string GetTexturePath(RenderTextureArtifactReference texture) { if (texture.assetId == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + { throw new ArgumentException("A target texture path requires a valid artifact reference.", nameof(texture)); - return string.Join('/', + } + return string.Join( + '/', "TargetArtifacts", "Textures", texture.assetId.ToString("D", CultureInfo.InvariantCulture), - HashSlot(texture.slot.id) + ".ktx"); + HashSlot(texture.slot.id) + ".ktx" + ); } private static string HashVariant(string value) @@ -73,4 +81,3 @@ private static string HashVariant(string value) private static string HashSlot(string value) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(value))); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs index 724de99d0..8808e47b1 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs @@ -1,8 +1,8 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Mathematics; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -105,7 +105,8 @@ public static GeometryData Decode(ReadOnlySpan bytes) new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), - new Vector2(reader.ReadSingle(), reader.ReadSingle())); + new Vector2(reader.ReadSingle(), reader.ReadSingle()) + ); } for (int index = 0; index < indices.Length; index++) @@ -142,9 +143,7 @@ public static GeometryData Decode(ReadOnlySpan bytes) private static int RequireCount( int value, string kind - ) - => value >= 0 && value <= 100_000_000 - ? value - : throw new InvalidDataException($"Mesh artifact {kind} count is invalid."); + ) => value >= 0 && value <= 100_000_000 + ? value + : throw new InvalidDataException($"Mesh artifact {kind} count is invalid."); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAsset.cs index 388d4f0cf..a2541c27c 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAsset.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -16,9 +16,7 @@ namespace Inno.Rendering.Assets; [StableTypeId("f214637e-0a54-438d-8a72-9d892bd29a56")] public sealed class GeometryAsset : AssetObject { - internal GeometryAsset() - { - } + internal GeometryAsset() {} /// /// Creates an immutable imported geometry description. @@ -52,7 +50,9 @@ Vector3 boundsExtents ArgumentOutOfRangeException.ThrowIfNegative(indexCount); ArgumentOutOfRangeException.ThrowIfNegative(sectionCount); if (boundsExtents.x < 0f || boundsExtents.y < 0f || boundsExtents.z < 0f) + { throw new ArgumentOutOfRangeException(nameof(boundsExtents), "Geometry bounds extents cannot be negative."); + } this.vertexCount = vertexCount; this.indexCount = indexCount; this.sectionCount = sectionCount; @@ -90,4 +90,3 @@ Vector3 boundsExtents [SerializableProperty] public Vector3 boundsExtents { get; internal set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs index 5f465d837..7968ed998 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs @@ -1,8 +1,8 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Mathematics; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -30,4 +30,3 @@ public static GeometryData GetGeometryData(GeometryAsset geometry) return GeometryArtifact.Decode(geometry.runtimePayload.Span); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs index 6432e686f..459995228 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs @@ -1,8 +1,8 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Mathematics; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -52,4 +52,3 @@ GeometrySection[] sections /// public IReadOnlyList sections { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs index 237992b59..79980d255 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs @@ -1,8 +1,8 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Mathematics; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -41,4 +41,3 @@ int indexCount /// public int indexCount { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs index db07d0a29..d60c82852 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs @@ -1,8 +1,8 @@ -using Inno.Core.Mathematics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.IO; +using Inno.Core.Mathematics; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -59,4 +59,3 @@ Vector2 textureCoordinate /// public Vector2 textureCoordinate { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs index ec478ed18..65fdc6c04 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -65,7 +65,9 @@ public void Set( MaterialValue value ) { if (!id.isValid) + { throw new ArgumentException("A material property ID must be valid.", nameof(id)); + } int index = Array.FindIndex(m_properties, candidate => candidate.id == id); if (index < 0) { @@ -91,12 +93,12 @@ public void ReplaceProperties(IEnumerable properties) foreach (MaterialPropertyEntry property in candidate) { if (!property.id.isValid) + { throw new ArgumentException("A material property ID must be valid.", nameof(properties)); + } if (!ids.Add(property.id)) { - throw new ArgumentException( - $"Material property '{property.id}' is duplicated.", - nameof(properties)); + throw new ArgumentException($"Material property '{property.id}' is duplicated.", nameof(properties)); } } m_properties = candidate @@ -141,9 +143,13 @@ bool enabled ArgumentException.ThrowIfNullOrWhiteSpace(keyword); var values = m_keywords.ToHashSet(StringComparer.Ordinal); if (enabled) + { values.Add(keyword); + } else + { values.Remove(keyword); + } m_keywords = values.OrderBy(static value => value, StringComparer.Ordinal).ToArray(); } @@ -205,24 +211,21 @@ out string? value public bool RemoveMetadata(string key) { ArgumentException.ThrowIfNullOrWhiteSpace(key); - int index = Array.FindIndex(m_metadata, entry => - string.Equals(entry.key, key, StringComparison.Ordinal)); + int index = Array.FindIndex(m_metadata, entry => string.Equals(entry.key, key, StringComparison.Ordinal)); if (index < 0) + { return false; + } var replacement = new MaterialMetadataEntry[m_metadata.Length - 1]; if (index > 0) + { Array.Copy(m_metadata, 0, replacement, 0, index); + } if (index < m_metadata.Length - 1) { - Array.Copy( - m_metadata, - index + 1, - replacement, - index, - m_metadata.Length - index - 1); + Array.Copy(m_metadata, index + 1, replacement, index, m_metadata.Length - index - 1); } m_metadata = replacement; return true; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs index 84ab29bb4..18de130ac 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -43,4 +43,3 @@ string value /// public string value { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs index 8ed87bb8c..a614c5d2a 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -45,4 +45,3 @@ ShaderPassDefinition pass /// public ShaderPassDefinition pass => ShaderDefinitionSnapshot.Copy(m_pass); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs index 5cec7791e..55d973a26 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -78,26 +78,38 @@ GraphicsCapabilities capabilities ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(capabilities); if (!contractId.isValid) + { throw new ArgumentException("A shader contract ID must be valid.", nameof(contractId)); + } if (!passRoleId.isValid) + { throw new ArgumentException("A shader pass role ID must be valid.", nameof(passRoleId)); + } foreach (ShaderTechniqueDefinition technique in definition.techniques) { if (technique.contract != contractId || !capabilities.Supports(technique.requiredFeatures) - || techniqueId.isValid && technique.id != techniqueId) + || techniqueId.isValid && technique.id != techniqueId + ) { continue; + } foreach (ShaderTechniquePass mapping in technique.passes) { if (mapping.role != passRoleId) + { continue; + } foreach (ShaderPassDefinition pass in definition.passes) - if (string.Equals(pass.name, mapping.passName, StringComparison.Ordinal) && capabilities.Supports(pass.requiredFeatures)) + { + if (string.Equals(pass.name, mapping.passName, StringComparison.Ordinal) + && capabilities.Supports(pass.requiredFeatures) + ) { return new MaterialPassResolution(technique, pass); + } + } } } return null; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs index 35c985e74..c63169ad3 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -36,7 +36,9 @@ public void Set( MaterialValue value ) { if (!id.isValid) + { throw new ArgumentException("A material property ID must be valid.", nameof(id)); + } m_values[id] = value; } @@ -66,8 +68,9 @@ internal MaterialPropertyBlock Snapshot() { var snapshot = new MaterialPropertyBlock(); foreach ((ShaderPropertyId id, MaterialValue value) in m_values) + { snapshot.m_values.Add(id, value); + } return snapshot; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs index 99682d8b2..7f6c8ee2b 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -29,7 +29,9 @@ public MaterialPropertyEntry( MaterialValue value ) { if (!id.isValid) + { throw new ArgumentException("A material property ID must be valid.", nameof(id)); + } this.id = id; this.value = value; } @@ -44,4 +46,3 @@ MaterialValue value /// public MaterialValue value { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs index 4c3433a4a..cd6b81651 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -150,7 +150,7 @@ public static MaterialValue FromTexture( default, default, value, - sampler ?? RenderSamplerState.linearClamp); + sampler ?? RenderSamplerState.linearClamp + ); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs index d9a4f405f..a7e2ebe44 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -18,9 +18,7 @@ public struct RenderFeatureConfiguration /// /// Creates an empty feature configuration for deserialization. /// - public RenderFeatureConfiguration() - { - } + public RenderFeatureConfiguration() {} /// /// Creates a feature configuration. @@ -63,4 +61,3 @@ public RenderFeatureConfiguration( [SerializableProperty] public bool enabled { get; set; } = true; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderPipelineAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderPipelineAsset.cs index 0daa6c44d..3e8a456c9 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderPipelineAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderPipelineAsset.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -15,7 +15,6 @@ namespace Inno.Rendering.Assets; [StableTypeId("b17d289e-62de-4299-9e85-497143911798")] public sealed class RenderPipelineAsset : AssetObject { - /// /// Gets or sets the globally stable pipeline extension identifier. /// @@ -54,4 +53,3 @@ public void SetFeatures(IEnumerable features) this.features = features.ToArray(); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs index caff618cc..f5348d8f4 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs @@ -1,11 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -74,4 +74,3 @@ public SerializedRenderExtensionState(AssetPropertySnapshot properties) [SerializableProperty] public AssetDependency[] dependencies { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs index 799a5c9ce..36d7551e1 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs @@ -25,8 +25,12 @@ SerializedRenderExtensionState value writer.Write("propertyData", value.propertyData ?? []); writer.Write("dependencies", value.dependencies ?? []); if (writer.context.TryGet(out AssetDependencyCollection? dependencies) && dependencies is not null) + { foreach (AssetDependency dependency in value.dependencies ?? []) + { dependencies.Add(dependency); + } + } } /// @@ -38,11 +42,11 @@ SerializedRenderExtensionState value /// /// The validated serialized render extension state that represents the completed operation. /// - public override SerializedRenderExtensionState Read(SerializationReader reader) => new() + public override SerializedRenderExtensionState Read(SerializationReader reader) + => new() { stableTypeId = reader.Read("stableTypeId"), propertyData = reader.Read("propertyData"), dependencies = reader.Read("dependencies") }; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs index 5783a8f4b..1c6fc999a 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -65,10 +65,12 @@ SerializationContext context private void OnSerializableRestored(SerializationContext context) { m_definition = m_definitionData.Length == 0 - ? null - : new ShaderDefinitionSnapshot(context.GetRequired().Deserialize( - m_definitionData, - context)); + ? null + : new ShaderDefinitionSnapshot( + context.GetRequired().Deserialize( + m_definitionData, + context + ) + ); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs index e28ecfa20..1226cc70d 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -46,4 +46,3 @@ public ShaderContractId(string value) /// public readonly override string ToString() => value ?? string.Empty; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs index a2a237fd8..42b7f09c4 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -19,9 +19,7 @@ public sealed class ShaderDefinition : ISerializable /// /// Creates an empty shader definition for native deserialization. /// - public ShaderDefinition() - { - } + public ShaderDefinition() {} /// /// Creates a shader definition. @@ -89,4 +87,3 @@ public ShaderDefinition( [SerializableProperty] public ShaderTechniqueDefinition[] techniques { get; set; } = []; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs index 50297bf81..421ccc9dd 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs @@ -1,6 +1,6 @@ -using Inno.Rendering; using System; using System.Linq; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -12,9 +12,9 @@ internal sealed class ShaderDefinitionSnapshot internal ShaderDefinitionSnapshot(ShaderDefinition definition) { ArgumentNullException.ThrowIfNull(definition); - if (definition.properties is null || definition.keywords is null || - definition.passes is null || definition.techniques is null) - { + if (definition.properties is null || definition.keywords is null + || definition.passes is null || definition.techniques is null + ) { throw new ArgumentException("Shader declaration collections cannot be null.", nameof(definition)); } m_definition = Copy(definition); @@ -36,16 +36,15 @@ internal static ShaderTechniqueDefinition Copy(ShaderTechniqueDefinition definit private static ShaderDefinition Copy(ShaderDefinition definition) => new() + { + name = definition.name, + properties = definition.properties.ToArray(), + keywords = definition.keywords.Select(static keyword => new ShaderKeywordDefinition { - name = definition.name, - properties = definition.properties.ToArray(), - keywords = definition.keywords.Select(static keyword => new ShaderKeywordDefinition - { - id = keyword.id, - options = keyword.options?.ToArray() ?? [] - }).ToArray(), - passes = definition.passes.Select(Copy).ToArray(), - techniques = definition.techniques.Select(Copy).ToArray() - }; + id = keyword.id, + options = keyword.options?.ToArray() ?? [] + }).ToArray(), + passes = definition.passes.Select(Copy).ToArray(), + techniques = definition.techniques.Select(Copy).ToArray() + }; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs index e525a9cb7..6c302a9ca 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs @@ -1,8 +1,8 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -34,7 +34,9 @@ public static IReadOnlyList Validate( ArgumentNullException.ThrowIfNull(definition); var diagnostics = new List(); if (string.IsNullOrWhiteSpace(definition.name)) + { Error("SHADER_NAME_MISSING", "A shader requires a nonempty name."); + } if (definition.properties is null || definition.passes is null || definition.keywords is null || definition.techniques is null) { Error("SHADER_DECLARATIONS_MISSING", "Shader declaration collections cannot be null."); @@ -45,30 +47,50 @@ public static IReadOnlyList Validate( Identifiers(definition.keywords.Select(static value => value.id), "KEYWORD"); Identifiers(definition.techniques.Select(static value => value.id.value), "TECHNIQUE"); if (definition.passes.Length == 0) + { Error("SHADER_PASSES_MISSING", "A shader requires at least one pass."); + } foreach (ShaderPropertyDefinition property in definition.properties) { if (!Enum.IsDefined(property.type) || !ShaderPropertyDefinition.IsBindingKindCompatible(property.type, property.bindingKind)) - Error("SHADER_PROPERTY_BINDING_INCOMPATIBLE", $"Property '{property.id}' has incompatible type '{property.type}' and binding '{property.bindingKind}'."); + { + Error( + "SHADER_PROPERTY_BINDING_INCOMPATIBLE", + $"Property '{property.id}' has incompatible type '{property.type}' and binding '{property.bindingKind}'." + ); + } if (!Enum.IsDefined(property.storageAccess)) + { Error("SHADER_STORAGE_ACCESS_INVALID", $"Property '{property.id}' has invalid storage access."); + } if (!Enum.IsDefined(property.bindingOwner)) + { Error("SHADER_BINDING_OWNER_INVALID", $"Property '{property.id}' has invalid binding ownership."); - if (property.stages == ShaderStage.None || (property.stages & ~(ShaderStage.Vertex | ShaderStage.Fragment | ShaderStage.Compute)) != 0) + } + if (property.stages == ShaderStage.None + || (property.stages & ~(ShaderStage.Vertex | ShaderStage.Fragment | ShaderStage.Compute)) != 0 + ) { Error("SHADER_PROPERTY_STAGES_INVALID", $"Property '{property.id}' requires valid stage visibility."); + } } foreach (ShaderKeywordDefinition keyword in definition.keywords) { if (keyword.options is null || keyword.options.Length == 0) + { Error("SHADER_KEYWORD_OPTIONS_MISSING", $"Keyword '{keyword.id}' requires selectable options."); + } else + { Identifiers(keyword.options, "KEYWORD_OPTION"); + } } HashSet passes = definition.passes.Select(static value => value.name).ToHashSet(StringComparer.Ordinal); foreach (ShaderTechniqueDefinition technique in definition.techniques) { if (string.IsNullOrWhiteSpace(technique.contract.value)) + { Error("SHADER_TECHNIQUE_CONTRACT_MISSING", $"Technique '{technique.id}' requires a contract ID."); + } if (technique.passes is null) { Error("SHADER_TECHNIQUE_ROLES_MISSING", $"Technique '{technique.id}' requires a role collection."); @@ -76,17 +98,35 @@ public static IReadOnlyList Validate( } Identifiers(technique.passes.Select(static value => value.role.value), "TECHNIQUE_ROLE"); foreach (ShaderTechniquePass binding in technique.passes) + { if (!passes.Contains(binding.passName)) + { Error("SHADER_UNKNOWN_TECHNIQUE_PASS", $"Technique '{technique.id}' refers to absent pass '{binding.passName}'."); + } + } } foreach (ShaderPassDefinition pass in definition.passes) { if (!Enum.IsDefined(pass.programKind)) + { Error("SHADER_PASS_KIND_INVALID", $"Pass '{pass.name}' has invalid program kind."); - if (!Enum.IsDefined(pass.renderState.cull) || !Enum.IsDefined(pass.renderState.depthCompare) || (pass.renderState.colorWriteMask & ~15) != 0) + } + if (!Enum.IsDefined(pass.renderState.cull) + || !Enum.IsDefined(pass.renderState.depthCompare) + || (pass.renderState.colorWriteMask & ~15) != 0 + ) { Error("SHADER_RASTER_STATE_INVALID", $"Pass '{pass.name}' has invalid raster state."); + } if (capabilities is not null && (pass.requiredFeatures & ~capabilities.features) != 0) - diagnostics.Add(new("SHADER_CAPABILITY_UNAVAILABLE", DiagnosticSeverity.Warning, $"Pass '{pass.name}' requires unavailable features '{pass.requiredFeatures & ~capabilities.features}'.")); + { + diagnostics.Add( + new( + "SHADER_CAPABILITY_UNAVAILABLE", + DiagnosticSeverity.Warning, + $"Pass '{pass.name}' requires unavailable features '{pass.requiredFeatures & ~capabilities.features}'." + ) + ); + } } return diagnostics.AsReadOnly(); @@ -100,11 +140,16 @@ string kind ) { var seen = new HashSet(StringComparer.Ordinal); foreach (string id in values) + { if (string.IsNullOrWhiteSpace(id)) + { Error("SHADER_" + kind + "_ID_MISSING", $"A {kind.ToLowerInvariant()} identity is empty."); + } else if (!seen.Add(id)) + { Error("SHADER_DUPLICATE_" + kind, $"The {kind.ToLowerInvariant()} identity '{id}' is repeated."); + } + } } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs index 6e888d2f9..ebc7d7816 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs @@ -1,8 +1,8 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -61,4 +61,3 @@ public ShaderDiagnostic( /// public ShaderSourceLocation? location { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs index d59e4aa6e..ae4ce540b 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -45,4 +45,3 @@ IEnumerable options /// public string[] options { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs index a7ca542c1..6bb892cf1 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -44,4 +44,3 @@ string value /// public string value { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs index 3fe3f6f05..ffb53def2 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -83,4 +83,3 @@ public ShaderPassDefinition( /// public ShaderPassDefinition Copy() => ShaderDefinitionSnapshot.Copy(this); } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs index 5db2d462e..6bec0c349 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -46,4 +46,3 @@ public ShaderPassRoleId(string value) /// public readonly override string ToString() => value ?? string.Empty; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs index 60f96a172..d93add639 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -25,4 +25,3 @@ public enum ShaderPropertyBindingOwner /// RenderPass } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs index af4793b3f..9e36a421d 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -55,7 +55,9 @@ public ShaderPropertyDefinition( ShaderPropertyBindingOwner bindingOwner = ShaderPropertyBindingOwner.Material ) { if (!id.isValid) + { throw new ArgumentException("A shader property ID must be valid.", nameof(id)); + } ArgumentException.ThrowIfNullOrWhiteSpace(displayName); this.id = id; this.displayName = displayName; @@ -66,9 +68,13 @@ public ShaderPropertyDefinition( this.storageAccess = storageAccess; this.bindingOwner = bindingOwner; if (!Enum.IsDefined(storageAccess)) + { throw new ArgumentOutOfRangeException(nameof(storageAccess)); + } if (!Enum.IsDefined(bindingOwner)) + { throw new ArgumentOutOfRangeException(nameof(bindingOwner)); + } ValidateBindingKind(type, this.bindingKind); } @@ -115,28 +121,27 @@ public ShaderPropertyDefinition( internal static bool IsBindingKindCompatible( ShaderPropertyType type, ShaderPropertyBindingKind bindingKind - ) - => bindingKind switch - { - ShaderPropertyBindingKind.Uniform => !IsTexture(type) && type != ShaderPropertyType.Buffer, - ShaderPropertyBindingKind.SampledTexture => IsTexture(type), - ShaderPropertyBindingKind.StorageTexture => IsTexture(type), - ShaderPropertyBindingKind.StorageBuffer => type == ShaderPropertyType.Buffer, - _ => false - }; + ) => bindingKind switch + { + ShaderPropertyBindingKind.Uniform => !IsTexture(type) && type != ShaderPropertyType.Buffer, + ShaderPropertyBindingKind.SampledTexture => IsTexture(type), + ShaderPropertyBindingKind.StorageTexture => IsTexture(type), + ShaderPropertyBindingKind.StorageBuffer => type == ShaderPropertyType.Buffer, + _ => false + }; private static ShaderPropertyBindingKind InferBindingKind(ShaderPropertyType type) => IsTexture(type) - ? ShaderPropertyBindingKind.SampledTexture - : type == ShaderPropertyType.Buffer - ? ShaderPropertyBindingKind.StorageBuffer - : ShaderPropertyBindingKind.Uniform; + ? ShaderPropertyBindingKind.SampledTexture + : type == ShaderPropertyType.Buffer + ? ShaderPropertyBindingKind.StorageBuffer + : ShaderPropertyBindingKind.Uniform; private static bool IsTexture(ShaderPropertyType type) => type is ShaderPropertyType.Texture2D - or ShaderPropertyType.Texture2DArray - or ShaderPropertyType.Texture3D - or ShaderPropertyType.TextureCube; + or ShaderPropertyType.Texture2DArray + or ShaderPropertyType.Texture3D + or ShaderPropertyType.TextureCube; private static void ValidateBindingKind( ShaderPropertyType type, @@ -146,8 +151,8 @@ ShaderPropertyBindingKind bindingKind { throw new ArgumentException( $"Shader property type '{type}' is incompatible with binding kind '{bindingKind}'.", - nameof(bindingKind)); + nameof(bindingKind) + ); } } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs index a4e541863..22e8147a7 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -79,7 +79,8 @@ public struct ShaderRenderState /// /// Gets the default opaque raster state. /// - public static ShaderRenderState opaque => new() + public static ShaderRenderState opaque + => new() { topology = RenderPrimitiveTopology.TriangleList, cull = ShaderCullMode.Back, @@ -131,4 +132,3 @@ public struct ShaderRenderState /// public bool multisampling { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs index 46c767aa1..12514d832 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs @@ -1,8 +1,8 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -72,6 +72,4 @@ public ShaderSourceLocation( /// Gets the one-based column, or zero when unavailable. /// public int column { get; } - } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs index 5f443c58f..c8f7c9b74 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -38,9 +38,13 @@ public ShaderTechniqueDefinition( GraphicsCapability requiredFeatures = GraphicsCapability.None ) { if (!id.isValid) + { throw new ArgumentException("A technique ID must be valid.", nameof(id)); + } if (!contract.isValid) + { throw new ArgumentException("A shader contract ID must be valid.", nameof(contract)); + } ArgumentNullException.ThrowIfNull(passes); this.id = id; this.contract = contract; @@ -68,4 +72,3 @@ public ShaderTechniqueDefinition( /// public GraphicsCapability requiredFeatures { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs index d335fad99..d8c2f212b 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -46,4 +46,3 @@ public ShaderTechniqueId(string value) /// public readonly override string ToString() => value ?? string.Empty; } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs index dca5e870c..71cae724a 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -30,7 +30,9 @@ public ShaderTechniquePass( string passName ) { if (!role.isValid) + { throw new ArgumentException("A pass role must be valid.", nameof(role)); + } ArgumentException.ThrowIfNullOrWhiteSpace(passName); this.role = role; this.passName = passName; @@ -46,4 +48,3 @@ string passName /// public string passName { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs index 741a67a87..8059326ac 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs @@ -1,6 +1,6 @@ -using Inno.Rendering; using System; using System.Collections.Generic; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -15,4 +15,3 @@ public interface IRenderTextureArtifactSource /// IReadOnlyList textureArtifacts { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs index 51847fa8e..8c367384d 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs @@ -1,6 +1,6 @@ -using Inno.Rendering; using System; using System.Collections.Generic; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -31,10 +31,14 @@ public RenderTextureArtifactReference( RenderTextureArtifactSlot slot ) { if (assetId == Guid.Empty) + { throw new ArgumentException("A texture artifact reference requires a persistent asset identity.", nameof(assetId)); + } ArgumentOutOfRangeException.ThrowIfNegative(contentRevision); if (string.IsNullOrWhiteSpace(slot.id) || string.IsNullOrWhiteSpace(slot.sourceOutputName)) + { throw new ArgumentException("A texture artifact reference requires a valid slot.", nameof(slot)); + } this.assetId = assetId; this.contentRevision = contentRevision; this.slot = slot; @@ -54,6 +58,4 @@ RenderTextureArtifactSlot slot /// Gets the referenced stable texture slot. /// public RenderTextureArtifactSlot slot { get; } - } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs index 930579a9c..ce6a832f5 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs @@ -1,6 +1,6 @@ -using Inno.Rendering; using System; using System.Collections.Generic; +using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -52,4 +52,3 @@ TextureColorSpace colorSpace /// public TextureColorSpace colorSpace { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/TextureAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/TextureAsset.cs index b5772da33..650c4e43e 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/TextureAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/TextureAsset.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -18,12 +18,11 @@ public sealed class TextureAsset : AssetObject, IRenderTextureArtifactSource { private static readonly RenderTextureArtifactSlot[] S_linearTextureArtifacts = [new RenderTextureArtifactSlot("main", "source", TextureColorSpace.Linear)]; + private static readonly RenderTextureArtifactSlot[] S_sRgbTextureArtifacts = [new RenderTextureArtifactSlot("main", "source", TextureColorSpace.Srgb)]; - internal TextureAsset() - { - } + internal TextureAsset() {} /// /// Creates an immutable imported texture description. @@ -90,8 +89,8 @@ string sourceFormat /// public IReadOnlyList textureArtifacts => colorSpace == TextureColorSpace.Srgb - ? S_sRgbTextureArtifacts - : S_linearTextureArtifacts; + ? S_sRgbTextureArtifacts + : S_linearTextureArtifacts; /// /// Creates a stable reference to this texture's current imported content. @@ -106,8 +105,9 @@ public RenderTextureArtifactReference GetTextureArtifactReference() { Guid id = identity.persistentId; if (id == Guid.Empty) + { throw new InvalidOperationException("Texture must have a persistent asset identity."); + } return new RenderTextureArtifactReference(id, contentVersion, textureArtifacts[0]); } } - diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs index 98fc0e7e2..7bd6a3303 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs @@ -1,12 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering.Assets; @@ -25,4 +25,3 @@ public enum TextureColorSpace /// Srgb } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs index ee7151b5c..5b141337a 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs @@ -1,9 +1,8 @@ using System; -using System.IO; using System.Collections.Generic; -using Inno.Core.Serialization; +using System.IO; using Inno.Content; - +using Inno.Core.Serialization; using Inno.Rendering; using Inno.Rendering.Assets; @@ -95,9 +94,12 @@ out RenderShaderArtifact? artifact string path = RenderTargetArtifactPath.GetShaderPath( shader.identity.persistentId, capabilities.backend, - variant); + variant + ); if (m_shaders.TryGetValue(path, out artifact)) + { return RenderTargetArtifactStatus.Ready; + } if (!m_content.index.TryGetEntry(new ContentKey(path), out _)) { artifact = null; @@ -106,12 +108,8 @@ out RenderShaderArtifact? artifact try { ShaderDefinition definition = shader.definition - ?? throw new InvalidDataException( - $"Runtime shader '{shader.assetPath}' has no committed definition."); - artifact = RenderShaderArtifactCodec.Decode( - ReadContent(new ContentKey(path)), - definition.name, - variant); + ?? throw new InvalidDataException($"Runtime shader '{shader.assetPath}' has no committed definition."); + artifact = RenderShaderArtifactCodec.Decode(ReadContent(new ContentKey(path)), definition.name, variant); m_shaders.Add(path, artifact); return RenderTargetArtifactStatus.Ready; } @@ -119,7 +117,8 @@ out RenderShaderArtifact? artifact { throw new InvalidDataException( $"Deployed shader artifact '{path}' failed integrity validation.", - exception); + exception + ); } } @@ -147,7 +146,9 @@ public RenderTargetArtifactStatus GetTextureArtifact( out ReadOnlyMemory artifact ) { if (texture.assetId == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + { throw new ArgumentException("A valid texture artifact reference is required.", nameof(texture)); + } string path = RenderTargetArtifactPath.GetTexturePath(texture); if (!m_content.index.TryGetEntry(new ContentKey(path), out _)) { @@ -156,7 +157,9 @@ out ReadOnlyMemory artifact } byte[] bytes = ReadContent(new ContentKey(path)); if (bytes.Length == 0) + { throw new InvalidDataException($"Deployed texture artifact '{path}' is empty."); + } artifact = bytes; return RenderTargetArtifactStatus.Ready; } @@ -165,12 +168,16 @@ private byte[] ReadContent(ContentKey key) { using ContentReadLease lease = m_content.Acquire(key); if (lease.entry.length > Array.MaxLength) + { throw new InvalidDataException($"Target artifact '{key}' exceeds the managed payload limit."); + } using Stream stream = lease.OpenRead(); byte[] bytes = new byte[checked((int)lease.entry.length)]; stream.ReadExactly(bytes); if (stream.ReadByte() != -1) + { throw new InvalidDataException($"Target artifact '{key}' exceeds its indexed length."); + } return bytes; } } diff --git a/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs index 3a9c7ca83..8251668d4 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs @@ -1,6 +1,6 @@ +using System; using Inno.Rendering; using Inno.Rendering.Assets; -using System; namespace Inno.Rendering.Runtime; @@ -74,4 +74,3 @@ RenderTargetArtifactStatus GetTextureArtifact( out ReadOnlyMemory artifact ); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs b/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs index d069ba478..7a1f4b15a 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs @@ -12,20 +12,16 @@ public enum RenderTargetArtifactStatus /// A validated artifact is available for immediate use. /// Ready, - /// /// Artifact production is still running and no usable artifact is available yet. /// Pending, - /// /// The active deployment does not contain the requested artifact. /// Unavailable, - /// /// Artifact production completed unsuccessfully and published a specific diagnostic. /// Failed } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs index 90b145fad..a9292363b 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs @@ -1,8 +1,8 @@ +using System; +using System.Threading; using Inno.Core.Execution; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Threading; namespace Inno.Rendering.Runtime; @@ -51,12 +51,16 @@ internal RenderPipelineAsset? defaultPipeline get { lock (m_sync) + { return m_defaultPipeline; + } } set { lock (m_sync) + { m_defaultPipeline = value; + } } } @@ -65,12 +69,16 @@ internal RenderFrameStatistics? frameStatistics get { lock (m_sync) + { return m_frameStatistics; + } } set { lock (m_sync) + { m_frameStatistics = value; + } } } @@ -91,8 +99,7 @@ internal static class GraphicsSettingsExecutionContext internal static GraphicsSettingsState current => currentOrNull - ?? throw new InvalidOperationException( - "No rendering runtime is bound to the current execution context."); + ?? throw new InvalidOperationException("No rendering runtime is bound to the current execution context."); internal static GraphicsSettingsState? currentOrNull => S_CURRENT.TryGet(out GraphicsSettingsState? state) ? state : null; @@ -101,5 +108,4 @@ internal static IDisposable Enter(GraphicsSettingsState state) ArgumentNullException.ThrowIfNull(state); return S_CURRENT.Enter(state); } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs index e9f72c8be..14d2e0fb1 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs @@ -1,10 +1,10 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -36,4 +36,3 @@ public interface IRenderModel : IDisposable /// RenderModelOutput Build(RenderOutputSession session); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs index b265e62b5..51ed88f00 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs @@ -1,10 +1,10 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -32,4 +32,3 @@ public RenderModelExtensionAttribute(string id) /// public string id { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs index bdcaad772..a3db0a3ec 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs @@ -1,10 +1,10 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -46,17 +46,19 @@ public RenderModelOutput( /// Gets the diagnostic name. /// public string name { get; } + /// /// Gets the model's pipeline. /// public RenderPipelineAsset pipeline { get; } + /// /// Gets model frame data. /// public RenderFrameData data { get; } + /// /// Gets required target format. /// public RenderTextureFormat targetFormat { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs index 1132829ee..615c7859c 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs @@ -1,8 +1,8 @@ +using System; +using System.Collections.Generic; using Inno.Core.Input; using Inno.Core.Mathematics; using Inno.Rendering; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -72,47 +72,64 @@ public RenderOutputInput( /// /// Gets a snapshot with no active input. /// - public static RenderOutputInput empty { get; } = new(default, false, default, - KeyModifier.None, [], [], [], [], []); + public static RenderOutputInput empty { get; } = new(default, false, default, KeyModifier.None, [], [], [], [], []); /// /// Gets a snapshot that clears gameplay interaction while retaining the rendered output. /// - public static RenderOutputInput suspended { get; } = new(default, false, default, - KeyModifier.None, [], [], [], [], [], interactionEnabled: false); + public static RenderOutputInput suspended { get; } = new( + default, + false, + default, + KeyModifier.None, + [], + [], + [], + [], + [], + interactionEnabled: false + ); /// /// Gets viewport-local pointer coordinates. /// public Vector2 pointerPosition { get; } + /// /// Gets whether the pointer is inside this output. /// public bool pointerInside { get; } + /// /// Gets wheel movement. /// public Vector2 scrollDelta { get; } + /// /// Gets active keyboard modifiers. /// public KeyModifier modifiers { get; } + /// /// Gets keys pressed this frame. /// public IReadOnlyCollection keysPressed { get; } + /// /// Gets keys released this frame. /// public IReadOnlyCollection keysReleased { get; } + /// /// Gets buttons pressed this frame. /// public IReadOnlyCollection buttonsPressed { get; } + /// /// Gets buttons released this frame. /// public IReadOnlyCollection buttonsReleased { get; } + /// /// Gets ordered text commits. /// @@ -123,4 +140,3 @@ public RenderOutputInput( /// public bool interactionEnabled { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs index 9949caf95..ee02a6da9 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs @@ -1,10 +1,10 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -31,8 +31,10 @@ IEnumerable sourceIds ArgumentNullException.ThrowIfNull(sourceIds); string[] ids = sourceIds.ToArray(); if (ids.Any(string.IsNullOrWhiteSpace) - || ids.Distinct(StringComparer.Ordinal).Count() != ids.Length) + || ids.Distinct(StringComparer.Ordinal).Count() != ids.Length + ) { throw new ArgumentException("A layer requires distinct non-empty source IDs.", nameof(sourceIds)); + } this.modelId = modelId; this.sourceIds = new ReadOnlyCollection(ids); } @@ -41,9 +43,9 @@ IEnumerable sourceIds /// Gets the exact rendering model ID. /// public string modelId { get; } + /// /// Gets the assigned world-content source IDs. /// public IReadOnlyList sourceIds { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs index f8b9e5f0a..ceefcea55 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs @@ -1,10 +1,10 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -25,11 +25,15 @@ public RenderOutputRoute(IEnumerable layers) ArgumentNullException.ThrowIfNull(layers); RenderOutputLayer[] values = layers.ToArray(); if (values.Length == 0 || values.Any(static layer => layer is null) - || values.Select(static layer => layer.modelId).Distinct(StringComparer.Ordinal).Count() != values.Length) + || values.Select(static layer => layer.modelId).Distinct(StringComparer.Ordinal).Count() != values.Length + ) { throw new ArgumentException("A route requires distinct model layers.", nameof(layers)); + } string[] sourceIds = values.SelectMany(static layer => layer.sourceIds).ToArray(); if (sourceIds.Distinct(StringComparer.Ordinal).Count() != sourceIds.Length) + { throw new ArgumentException("Each world-content source may be assigned to only one model layer.", nameof(layers)); + } this.layers = new ReadOnlyCollection(values); } @@ -38,4 +42,3 @@ public RenderOutputRoute(IEnumerable layers) /// public IReadOnlyList layers { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs index a34d6ed5d..82d9cfd34 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs @@ -1,10 +1,10 @@ -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.References; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -66,30 +66,37 @@ public RenderOutputSession( /// Gets the stable host output identity. /// public string id { get; } + /// /// Gets selected content roots. /// public ContentReadScope content { get; } + /// /// Gets the output pixel viewport. /// public RenderViewport viewport { get; } + /// /// Gets the shared output frame index. /// public ulong frameIndex { get; } + /// /// Gets elapsed frame time. /// public float deltaTime { get; } + /// /// Gets the world content collector. /// public IViewContentCollector viewContent { get; } + /// /// Gets viewport-local input. /// public RenderOutputInput input { get; } + /// /// Gets the explicit model route, if configured. /// @@ -107,8 +114,14 @@ public RenderOutputSession( public RenderOutputSession ForLayer(RenderOutputLayer layer) { ArgumentNullException.ThrowIfNull(layer); - return new RenderOutputSession(id, content, viewport, frameIndex, deltaTime, - new SelectedViewContentCollector(viewContent, layer.sourceIds), input); + return new RenderOutputSession( + id, + content, + viewport, + frameIndex, + deltaTime, + new SelectedViewContentCollector(viewContent, layer.sourceIds), + input + ); } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs index b35796395..8d8ec6f7b 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs @@ -1,9 +1,9 @@ +using System; +using System.Collections.Generic; using Inno.Core.Identity; using Inno.Core.Mathematics; using Inno.References; using Inno.Rendering; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -150,14 +150,17 @@ public ViewContentContext( /// Gets elapsed time in seconds. /// public float deltaTime { get; } + /// /// Gets frame-local input for this output. /// public RenderOutputInput input { get; } + /// /// Gets every view in the same model output. /// public IReadOnlyList views { get; } + /// /// Gets the exclusive source allowlist; null collects every active source. /// @@ -339,6 +342,7 @@ public ViewContentItem( /// Gets the drawable encoded by the selected rendering model. /// public IViewDrawable drawable { get; } + /// /// Gets the optional pointer target associated with this draw item. /// @@ -477,9 +481,17 @@ IReadOnlyList sourceIds public IReadOnlyList Collect(ViewContentContext context) { ArgumentNullException.ThrowIfNull(context); - return m_inner.Collect(new ViewContentContext(context.content, context.sessionId, - context.view, context.frameIndex, context.deltaTime, context.input, - context.views, m_sourceIds)); + return m_inner.Collect( + new ViewContentContext( + context.content, + context.sessionId, + context.view, + context.frameIndex, + context.deltaTime, + context.input, + context.views, + m_sourceIds + ) + ); } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs index e8767bd30..3e2782d6d 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs @@ -1,8 +1,8 @@ +using System; using Inno.Assets; using Inno.Core.Serialization; using Inno.Rendering; using Inno.Rendering.Assets; -using System; namespace Inno.Rendering.Runtime; @@ -46,4 +46,3 @@ TSettings target m_owner.RestoreProperties(state.stableTypeId, state.propertyData, target); } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs index 670388089..77a4dd6d5 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -66,4 +66,3 @@ RenderFeatureConfiguration configuration /// public IRenderFrameUploadService uploads => pipeline.uploads; } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs index 70466bddc..d7ee8227f 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -32,4 +32,3 @@ public RenderFeatureExtensionAttribute(string id) /// public string id { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs index 647284a4a..5da784f06 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -50,7 +50,9 @@ RenderExtensionStateContext settings public void Dispose() { if (m_disposed) + { return; + } try { Dispose(true); @@ -80,7 +82,7 @@ public void Dispose() protected virtual void OnConfigure( SerializedRenderExtensionState state, RenderExtensionStateContext settings - ) { } + ) {} /// /// Releases managed generation-scoped state. @@ -91,6 +93,5 @@ RenderExtensionStateContext settings /// /// Retirement cannot complete yet; subsequent calls resume this hook with its remaining owned resources. /// - protected virtual void Dispose(bool disposing) { } + protected virtual void Dispose(bool disposing) {} } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs index 3649800eb..d33e80860 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -142,4 +142,3 @@ public RenderPipelineContext( /// public RenderTextureHandle outputTexture { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs index df2def25a..730b1734c 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -32,4 +32,3 @@ public RenderPipelineExtensionAttribute(string id) /// public string id { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs index 4e0e2a66e..0d6cae0a2 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -51,6 +51,5 @@ RenderExtensionStateContext settings protected virtual void OnConfigure( SerializedRenderExtensionState state, RenderExtensionStateContext settings - ) { } + ) {} } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs index f1542b420..c41cba01b 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Rendering; using Inno.Rendering.Assets; -using System; -using System.Collections.Generic; namespace Inno.Rendering.Runtime; @@ -31,9 +31,13 @@ public void PublishTexture( RenderTextureHandle texture ) { if (!id.isValid) + { throw new ArgumentException("A render resource identifier must be valid.", nameof(id)); + } if (!texture.isValid) + { throw new ArgumentException("A published texture must be valid.", nameof(texture)); + } m_textures[id] = texture; } @@ -51,9 +55,13 @@ public void PublishBuffer( RenderBufferHandle buffer ) { if (!id.isValid) + { throw new ArgumentException("A render resource identifier must be valid.", nameof(id)); + } if (!buffer.isValid) + { throw new ArgumentException("A published buffer must be valid.", nameof(buffer)); + } m_buffers[id] = buffer; } @@ -91,4 +99,3 @@ public bool TryGetBuffer( out RenderBufferHandle buffer ) => m_buffers.TryGetValue(id, out buffer); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs index d4b0bf5af..feb774166 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs @@ -15,9 +15,7 @@ internal sealed class RenderExtensionRegistry : TypeRegistry current; @@ -26,7 +24,9 @@ internal void Retire(IDisposable? resource) try { if (resource is not null) + { RetireResource("render generation", resource.Dispose); + } } catch (Exception exception) { @@ -39,7 +39,12 @@ internal void Retire(IDisposable? resource) internal void EnsureHealthy() { if (m_retirementFailure is not null) - throw new InvalidOperationException("The rendering generation owner is Faulted and requires a host restart.", m_retirementFailure); + { + throw new InvalidOperationException( + "The rendering generation owner is Faulted and requires a host restart.", + m_retirementFailure + ); + } } /// @@ -73,29 +78,33 @@ protected override Snapshot Build(TypeCacheSnapshot types) Dictionary pipelines = Discover( types, static attribute => attribute.id, - "render pipeline"); + "render pipeline" + ); Dictionary features = Discover( types, static attribute => attribute.id, - "render feature"); + "render feature" + ); Dictionary requestProviders = Discover< RenderRequestProviderExtensionAttribute, - RenderRequestProvider>( - types, - static attribute => attribute.id, - "render request provider"); + RenderRequestProvider>(types, static attribute => attribute.id, "render request provider"); Dictionary contentSources = Discover< ViewContentSourceExtensionAttribute, - IViewContentSource>( - types, - static attribute => attribute.id, - "view content source"); + IViewContentSource>(types, static attribute => attribute.id, "view content source"); Dictionary renderModels = Discover< - RenderModelExtensionAttribute, IRenderModel>(types, - static attribute => attribute.id, "render model"); - return new Snapshot(types, pipelines, features, requestProviders, contentSources, renderModels, - CreateExtension, CreateExtension, - CreateExtension, Retire); + RenderModelExtensionAttribute, IRenderModel>(types, static attribute => attribute.id, "render model"); + return new Snapshot( + types, + pipelines, + features, + requestProviders, + contentSources, + renderModels, + CreateExtension, + CreateExtension, + CreateExtension, + Retire + ); } internal static string GetConfigurationFingerprint(RenderPipelineAsset asset) @@ -129,8 +138,7 @@ private static Dictionary Discover( TypeCacheSnapshot types, Func getId, string kind - ) - where TAttribute : Attribute + ) where TAttribute : Attribute { var result = new Dictionary(StringComparer.Ordinal); foreach (TypeRef typeRef in types.GetTypesWithAttribute()) @@ -139,13 +147,15 @@ string kind if (type.IsAbstract || !typeof(TContract).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Reloadable {kind} '{type.FullName}' must be a non-abstract {typeof(TContract).FullName}."); + $"Reloadable {kind} '{type.FullName}' must be a non-abstract {typeof(TContract).FullName}." + ); } if (!types.CanCreateInstance(typeRef)) { throw new InvalidOperationException( - $"Reloadable {kind} '{type.FullName}' requires a parameterless constructor."); + $"Reloadable {kind} '{type.FullName}' requires a parameterless constructor." + ); } TAttribute attribute = types.GetAttribute(typeRef, inherit: false)!; @@ -153,8 +163,9 @@ string kind if (!result.TryAdd(id, type)) { throw new InvalidOperationException( - $"Reloadable {kind} ID '{id}' is declared by both " + - $"'{result[id].FullName}' and '{type.FullName}'."); + $"Reloadable {kind} ID '{id}' is declared by both " + + $"'{result[id].FullName}' and '{type.FullName}'." + ); } } @@ -218,7 +229,9 @@ private ContentSourceGeneration CreateContentSources(Func(m_contentSources.Count); foreach ((string id, Type type) in m_contentSources.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) + { sources.Add(new ContentSourceEntry(id, createSource(type))); + } return new ContentSourceGeneration(typeCacheVersion, sources); } @@ -226,7 +239,9 @@ private RenderModelGeneration CreateRenderModels(Func create { var models = new List(m_renderModels.Count); foreach ((string id, Type type) in m_renderModels.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) + { models.Add(new RenderModelEntry(id, createModel(type))); + } return new RenderModelGeneration(typeCacheVersion, models); } @@ -256,7 +271,9 @@ out RenderPipelineGeneration? generation ) { ArgumentNullException.ThrowIfNull(asset); if (string.IsNullOrWhiteSpace(asset.pipelineTypeId)) + { throw new InvalidOperationException("A render pipeline asset requires a stable pipeline extension ID."); + } if (!m_pipelines.TryGetValue(asset.pipelineTypeId, out Type? pipelineType)) { generation = null; @@ -267,13 +284,18 @@ out RenderPipelineGeneration? generation foreach (RenderFeatureConfiguration configuration in asset.features) { if (!configuration.enabled) + { continue; + } if (string.IsNullOrWhiteSpace(configuration.featureTypeId)) + { throw new InvalidOperationException("An enabled render feature requires a stable extension ID."); + } if (featureTypes.ContainsKey(configuration.featureTypeId)) { throw new InvalidOperationException( - $"Render feature '{configuration.featureTypeId}' is configured more than once."); + $"Render feature '{configuration.featureTypeId}' is configured more than once." + ); } if (!m_features.TryGetValue(configuration.featureTypeId, out Type? featureType)) { @@ -289,10 +311,11 @@ out RenderPipelineGeneration? generation var settings = new RenderExtensionStateContext(asset); candidate.pipeline.Configure(asset.pipelineState, settings); foreach (RenderFeatureConfiguration configuration in asset.features.Where( - static value => value.enabled)) - { + static value => value.enabled + )) { RenderPipelineFeature feature = Create( - featureTypes[configuration.featureTypeId]); + featureTypes[configuration.featureTypeId] + ); candidate.AddFeature(configuration.featureTypeId, feature); feature.Configure(configuration, settings); } @@ -318,7 +341,8 @@ out RenderPipelineGeneration? generation } } - private TContract Create(Type type) where TContract : class + private TContract Create(Type type) + where TContract : class { try { @@ -328,7 +352,8 @@ private TContract Create(Type type) where TContract : class { throw new InvalidOperationException( $"Rendering extension '{type.FullName}' could not be activated.", - exception); + exception + ); } } } @@ -345,7 +370,9 @@ IReadOnlyList providers this.typeCacheVersion = typeCacheVersion; m_providers = Array.AsReadOnly(providers.ToArray()); foreach (RequestProviderEntry entry in m_providers) + { m_lifetime.Own(entry.provider); + } } internal long typeCacheVersion { get; } @@ -392,7 +419,9 @@ IReadOnlyList sources this.typeCacheVersion = typeCacheVersion; m_sources = Array.AsReadOnly(sources.ToArray()); foreach (ContentSourceEntry entry in m_sources) + { m_lifetime.Own(entry.source); + } } internal long typeCacheVersion { get; } @@ -426,7 +455,9 @@ IReadOnlyList models this.typeCacheVersion = typeCacheVersion; m_models = Array.AsReadOnly(models.ToArray()); foreach (RenderModelEntry entry in m_models) + { m_lifetime.Own(entry.model); + } } internal long typeCacheVersion { get; } @@ -446,5 +477,4 @@ internal sealed record RenderModelEntry( string id, IRenderModel model ); - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs index abd484cb3..1f4abf9bf 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs @@ -1,6 +1,6 @@ -using Inno.Rendering.Assets; using System; using System.Collections.Generic; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs index 91db02b8a..df5e0c4af 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs @@ -1,8 +1,7 @@ using System; -using Inno.Core.Execution; using System.Collections.Generic; using System.Linq; - +using Inno.Core.Execution; using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -56,14 +55,14 @@ string name ) { ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); if (!m_frameOpen) + { throw new InvalidOperationException("Frame uploads are only accepted during an open render frame."); + } ArgumentNullException.ThrowIfNull(descriptor); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (data.IsEmpty || data.Length % descriptor.elementStride != 0) { - throw new ArgumentException( - "Upload data must contain one or more complete elements.", - nameof(data)); + throw new ArgumentException("Upload data must contain one or more complete elements.", nameof(data)); } DrainSweep(); @@ -77,7 +76,8 @@ string name descriptor.elementStride, descriptor.usage, descriptor.vertexLayout, - descriptor.indexFormat); + descriptor.indexFormat + ); if (!m_pools.TryGetValue(key, out UploadPool? pool)) { pool = new UploadPool(); @@ -85,10 +85,8 @@ string name bool requiresDedicatedPage = (descriptor.usage & RenderBufferUsage.Storage) != 0; UploadPage? page = requiresDedicatedPage - ? pool.pages.FirstOrDefault(candidate => - !candidate.usedThisFrame && candidate.capacity >= elementCount) - : pool.pages.FirstOrDefault(candidate => - candidate.capacity - candidate.writeOffset >= elementCount); + ? pool.pages.FirstOrDefault(candidate => !candidate.usedThisFrame && candidate.capacity >= elementCount) + : pool.pages.FirstOrDefault(candidate => candidate.capacity - candidate.writeOffset >= elementCount); if (page is null) { int capacity = NextPowerOfTwo(Math.Max(C_MINIMUM_PAGE_ELEMENTS, elementCount)); @@ -102,11 +100,13 @@ string name var bufferDescriptor = new PersistentBufferDescriptor( new RenderBufferDescriptor(capacity, descriptor.elementStride, usage), descriptor.vertexLayout, - descriptor.indexFormat); + descriptor.indexFormat + ); PersistentBufferHandle handle = m_device.CreateBuffer( bufferDescriptor, ReadOnlySpan.Empty, - $"{name}/FrameUpload[{pool.pages.Count}]"); + $"{name}/FrameUpload[{pool.pages.Count}]" + ); page = new UploadPage(handle, capacity, bytes); pool.pages.Add(page); m_pools[key] = pool; @@ -121,12 +121,7 @@ string name page.writeOffset = checked(firstElement + elementCount); page.usedThisFrame = true; page.lastUsedFrame = m_frameIndex; - return CreateBufferSlice( - page.handle, - firstElement, - elementCount, - descriptor.usage, - m_frameIndex); + return CreateBufferSlice(page.handle, firstElement, elementCount, descriptor.usage, m_frameIndex); } internal void BeginFrame(ulong frameIndex) @@ -146,23 +141,27 @@ internal void BeginFrame(ulong frameIndex) internal void EndFrame() { if (!m_disposed) + { m_frameOpen = false; + } } internal void SweepUnused() { ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); if (m_frameIndex < C_UNUSED_FRAME_LIMIT) + { return; + } DrainSweep(); ulong oldest = m_frameIndex - C_UNUSED_FRAME_LIMIT; foreach (UploadPageKey key in m_pools.Keys.ToArray()) { UploadPool pool = m_pools[key]; foreach (UploadPage page in pool.pages - .Where(candidate => candidate.lastUsedFrame < oldest) - .ToArray()) - { + .Where(candidate => candidate.lastUsedFrame < oldest) + .ToArray() + ) { m_sweep ??= new RenderRetirementQueue(); m_sweep.Add(() => m_device.DestroyBuffer(page.handle)); m_sweep.Add(() => @@ -173,7 +172,9 @@ internal void SweepUnused() pool.pages.Remove(page); } if (pool.pages.Count == 0) + { m_pools.Remove(key); + } } DrainSweep(); } @@ -184,15 +185,21 @@ internal void SweepUnused() public void Dispose() { if (m_disposed) + { return; + } m_frameOpen = false; if (m_retirement is null) { m_retirement = new RenderRetirementQueue(); if (m_sweep is not null) + { m_retirement.Add(m_sweep.Dispose); + } foreach (UploadPage page in m_pools.Values.SelectMany(static pool => pool.pages)) + { m_retirement.Add(() => m_device.DestroyBuffer(page.handle)); + } } try { @@ -225,7 +232,9 @@ public void Dispose() private void DrainSweep() { if (m_sweep is null) + { return; + } try { m_sweep.Dispose(); @@ -246,7 +255,9 @@ private static int NextPowerOfTwo(int value) { int result = 1; while (result < value) + { result = checked(result * 2); + } return result; } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderGeometryOwner.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderGeometryOwner.cs index b4b9f17c3..69a40cbb0 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderGeometryOwner.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderGeometryOwner.cs @@ -62,8 +62,14 @@ out RenderGeometry? geometry string source = asset.assetPath.ToString(); if (id == Guid.Empty) { - m_diagnostics.Publish(new Diagnostic("RENDER_GEOMETRY_ID_MISSING", - "Geometry must have a persistent asset identity.", DiagnosticSeverity.Error, source)); + m_diagnostics.Publish( + new Diagnostic( + "RENDER_GEOMETRY_ID_MISSING", + "Geometry must have a persistent asset identity.", + DiagnosticSeverity.Error, + source + ) + ); return false; } m_diagnostics.Resolve("RENDER_GEOMETRY_ID_MISSING", source); @@ -82,11 +88,18 @@ out RenderGeometry? geometry } catch (Exception failure) { - m_diagnostics.Publish(new Diagnostic("RENDER_GEOMETRY_RESOLVE_FAILED", - $"Geometry '{source}' kept its complete last-good buffer pair: {failure.Message}", - DiagnosticSeverity.Error, source)); + m_diagnostics.Publish( + new Diagnostic( + "RENDER_GEOMETRY_RESOLVE_FAILED", + $"Geometry '{source}' kept its complete last-good buffer pair: {failure.Message}", + DiagnosticSeverity.Error, + source + ) + ); if (entry is null) + { return false; + } entry.lastUsedFrame = m_frameIndex; geometry = entry.geometry; return true; @@ -110,7 +123,9 @@ public void Dispose() { m_retirement = new RenderRetirementQueue(); if (m_allocation is not null) + { m_retirement.Add(m_allocation.Dispose); + } m_retirement.Add(m_entries.Dispose); } m_retirement.Dispose(); @@ -123,21 +138,37 @@ private Entry Create(GeometryAsset asset) RenderVertexLayout layout = CanonicalGeometryLayout(); byte[] vertices = PackVertices(data.vertices); byte[] indices = MemoryMarshal.AsBytes(data.indices.ToArray().AsSpan()).ToArray(); - IReadOnlyList sections = Array.AsReadOnly(data.sections.Select(static section => - new RenderGeometrySection(section.firstIndex, section.indexCount)).ToArray()); + IReadOnlyList sections = Array.AsReadOnly( + data.sections.Select(static section => + new RenderGeometrySection(section.firstIndex, section.indexCount)).ToArray() + ); m_allocation = new RenderRetirementQueue(); try { - PersistentBufferHandle vertex = m_device.CreateBuffer(new PersistentBufferDescriptor( - new RenderBufferDescriptor(data.vertices.Count, layout.stride, RenderBufferUsage.Vertex), layout), - vertices, $"{asset.name}/Vertices"); + PersistentBufferHandle vertex = m_device.CreateBuffer( + new PersistentBufferDescriptor( + new RenderBufferDescriptor(data.vertices.Count, layout.stride, RenderBufferUsage.Vertex), + layout + ), + vertices, + $"{asset.name}/Vertices" + ); m_allocation.Add(() => m_device.DestroyBuffer(vertex)); - PersistentBufferHandle index = m_device.CreateBuffer(new PersistentBufferDescriptor( - new RenderBufferDescriptor(data.indices.Count, sizeof(uint), RenderBufferUsage.Index), - indexFormat: RenderIndexFormat.UInt32), indices, $"{asset.name}/Indices"); + PersistentBufferHandle index = m_device.CreateBuffer( + new PersistentBufferDescriptor( + new RenderBufferDescriptor(data.indices.Count, sizeof(uint), RenderBufferUsage.Index), + indexFormat: RenderIndexFormat.UInt32 + ), + indices, + $"{asset.name}/Indices" + ); m_allocation.Add(() => m_device.DestroyBuffer(index)); - var entry = new Entry(CreateGeometry(vertex, index, layout, data.vertices.Count, - data.indices.Count, sections), asset.contentVersion, m_frameIndex, m_allocation); + var entry = new Entry( + CreateGeometry(vertex, index, layout, data.vertices.Count, data.indices.Count, sections), + asset.contentVersion, + m_frameIndex, + m_allocation + ); m_allocation = null; return entry; } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs index a6eeeb5f7..964b062d1 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs @@ -12,6 +12,7 @@ internal sealed class RenderLayerCompositor : IDisposable { private static readonly RenderPhaseId S_PHASE = new("inno.runtime.model-composition"); private static readonly RenderBindingId S_TEXTURE = new("s_tex"); + private static readonly float[] S_IDENTITY = [ 1f, 0f, 0f, 0f, @@ -19,12 +20,14 @@ internal sealed class RenderLayerCompositor : IDisposable 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f ]; + private static readonly RenderVertexLayout S_VERTEX_LAYOUT = new( - [ - new(RenderVertexSemantic.Position, RenderVertexFormat.Float2), - new(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), - new(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) - ]); + [ + new(RenderVertexSemantic.Position, RenderVertexFormat.Float2), + new(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), + new(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) + ] + ); private readonly IRenderDevice m_device; private readonly IRenderLayerCompositionProgramProvider? m_programProvider; @@ -55,11 +58,15 @@ RenderTextureFormat layerFormat ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(layers); if (layers.Count == 0) + { throw new ArgumentException("Composition requires at least one layer.", nameof(layers)); + } EnsureResources(); bool needsOutputTransfer = !output.isValid && !m_device.primaryPresentationEncodesSrgb; if (needsOutputTransfer) + { EnsureOutputTransferPipeline(); + } if (needsOutputTransfer && layers.Count == 1) { AddOutputTransfer(graph, name, layers[0], viewport); @@ -75,37 +82,52 @@ RenderTextureFormat layerFormat viewport.width, viewport.height, layerFormat, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); compositionViewport = new RenderViewport(0, 0, viewport.width, viewport.height); } for (int index = 0; index < layers.Count; index++) { if (!layers[index].isValid) + { throw new ArgumentException("Composition contains an invalid layer.", nameof(layers)); + } var data = new PassData(m_pipeline, m_vertices, m_indices, layers[index], compositionViewport); RasterPassBuilder pass = graph.AddRasterPass( - $"{name}/Layer {index + 1}", S_PHASE, data, + $"{name}/Layer {index + 1}", + S_PHASE, + data, static ( value, context - ) => DrawFullscreen(value, context)); + ) => DrawFullscreen(value, context) + ); pass.SetViewTransform(S_IDENTITY, S_IDENTITY); pass.ReadTexture(layers[index]); if (compositionTarget.isValid) { - pass.UseColorAttachment(compositionTarget, 0, + pass.UseColorAttachment( + compositionTarget, + 0, index == 0 ? RenderLoadAction.Clear : RenderLoadAction.Load, - RenderStoreAction.Store, default); + RenderStoreAction.Store, + default + ); } else { if (index == 0) + { pass.ClearPresentationTarget(default); + } pass.HasSideEffect(); } } if (needsOutputTransfer) + { AddOutputTransfer(graph, name, compositionTarget, viewport); + } } /// @@ -114,15 +136,25 @@ RenderTextureFormat layerFormat public void Dispose() { if (m_disposed) + { return; + } if (m_indices.isValid) + { m_device.DestroyBuffer(m_indices); + } if (m_vertices.isValid) + { m_device.DestroyBuffer(m_vertices); + } if (m_pipeline.isValid) + { m_device.DestroyGraphicsPipeline(m_pipeline); + } if (m_outputTransferPipeline.isValid) + { m_device.DestroyGraphicsPipeline(m_outputTransferPipeline); + } m_indices = default; m_vertices = default; m_pipeline = default; @@ -133,12 +165,13 @@ public void Dispose() private void EnsureResources() { if (m_pipeline.isValid) + { return; + } IRenderLayerCompositionProgramProvider provider = m_programProvider ?? throw new InvalidOperationException("The rendering host has no layer composition program provider."); GraphicsPipelineDescriptor descriptor = provider.CreateDescriptor(m_device.capabilities, S_VERTEX_LAYOUT); - GraphicsPipelineHandle pipeline = m_device.CreateGraphicsPipeline( - descriptor, "Render Model Composition"); + GraphicsPipelineHandle pipeline = m_device.CreateGraphicsPipeline(descriptor, "Render Model Composition"); PersistentBufferHandle vertices = default; PersistentBufferHandle indices = default; try @@ -146,20 +179,27 @@ private void EnsureResources() vertices = m_device.CreateBuffer( new PersistentBufferDescriptor(new RenderBufferDescriptor(4, 20, RenderBufferUsage.Vertex), S_VERTEX_LAYOUT), CreateVertices(m_device.capabilities.originBottomLeft), - "Render Model Composition Vertices"); + "Render Model Composition Vertices" + ); indices = m_device.CreateBuffer( new PersistentBufferDescriptor( new RenderBufferDescriptor(6, sizeof(ushort), RenderBufferUsage.Index), - indexFormat: RenderIndexFormat.UInt16), + indexFormat: RenderIndexFormat.UInt16 + ), [0, 0, 1, 0, 2, 0, 0, 0, 2, 0, 3, 0], - "Render Model Composition Indices"); + "Render Model Composition Indices" + ); } catch { if (indices.isValid) + { m_device.DestroyBuffer(indices); + } if (vertices.isValid) + { m_device.DestroyBuffer(vertices); + } m_device.DestroyGraphicsPipeline(pipeline); throw; } @@ -171,15 +211,16 @@ private void EnsureResources() private void EnsureOutputTransferPipeline() { if (m_outputTransferPipeline.isValid) + { return; + } IRenderLayerCompositionProgramProvider provider = m_programProvider ?? throw new InvalidOperationException("The rendering host has no layer composition program provider."); GraphicsPipelineDescriptor descriptor = provider.CreateOutputTransferDescriptor( m_device.capabilities, - S_VERTEX_LAYOUT); - m_outputTransferPipeline = m_device.CreateGraphicsPipeline( - descriptor, - "Render Model Output Transfer"); + S_VERTEX_LAYOUT + ); + m_outputTransferPipeline = m_device.CreateGraphicsPipeline(descriptor, "Render Model Output Transfer"); } private void AddOutputTransfer( @@ -196,7 +237,8 @@ RenderViewport viewport static ( value, context - ) => DrawFullscreen(value, context)); + ) => DrawFullscreen(value, context) + ); transfer.SetViewTransform(S_IDENTITY, S_IDENTITY); transfer.ReadTexture(source); transfer.ClearPresentationTarget(default); @@ -207,16 +249,8 @@ private static void DrawFullscreen( PassData value, RenderPassContext context ) { - context.commands.SetViewport( - value.viewport.x, - value.viewport.y, - value.viewport.width, - value.viewport.height); - context.commands.SetScissor( - value.viewport.x, - value.viewport.y, - value.viewport.width, - value.viewport.height); + context.commands.SetViewport(value.viewport.x, value.viewport.y, value.viewport.width, value.viewport.height); + context.commands.SetScissor(value.viewport.x, value.viewport.y, value.viewport.width, value.viewport.height); context.commands.BindGraphicsPipeline(value.pipeline); context.commands.BindVertexBuffer(value.vertices); context.commands.BindIndexBuffer(value.indices); diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs index da9f63b61..339f54375 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs @@ -51,10 +51,13 @@ internal int count { int result = 0; foreach (var pair in m_programs) + { result += pair.Value.programs.Count; + } return result; } } + internal int retiringCount => m_programs.pendingCount + m_failedCandidates.Count; internal long rejectedCount => m_programs.rejectedCount; @@ -67,6 +70,7 @@ internal void BeginFrame(ulong frameIndex) } internal void Sweep(ulong oldest) => m_programs.Sweep(entry => entry.lastUsedFrame < oldest); + internal void Drain() { ObjectDisposedException.ThrowIf(m_stopping, this); @@ -108,7 +112,12 @@ internal bool TryResolveMaterial( ShaderAsset? shader = material.shader; if (shader is null || shader.identity.persistentId == Guid.Empty) { - Publish("RENDER_SHADER_ID_MISSING", "Material requires a shader with a persistent asset identity.", material.assetPath.ToString(), diagnostics); + Publish( + "RENDER_SHADER_ID_MISSING", + "Material requires a shader with a persistent asset identity.", + material.assetPath.ToString(), + diagnostics + ); return false; } @@ -116,8 +125,9 @@ internal bool TryResolveMaterial( RenderShaderVariant variant; try { - variant = suppliedArtifact is null ? RenderShaderVariant.FromMaterial(material) - : RenderShaderVariant.FromMaterial(material, m_targetArtifacts!.ReadShaderDefinition(suppliedArtifact)); + variant = suppliedArtifact is null + ? RenderShaderVariant.FromMaterial(material) + : RenderShaderVariant.FromMaterial(material, m_targetArtifacts!.ReadShaderDefinition(suppliedArtifact)); } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { @@ -126,13 +136,26 @@ internal bool TryResolveMaterial( catch (Exception failure) { Publish("RENDER_MATERIAL_VARIANT_INVALID", failure.Message, material.assetPath.ToString(), diagnostics); - return TryUseLastGood(material, shaderId, contractId, passRoleId, expectedKind, vertexLayout, overrides, out materialPass, scope, diagnostics); + return TryUseLastGood( + material, + shaderId, + contractId, + passRoleId, + expectedKind, + vertexLayout, + overrides, + out materialPass, + scope, + diagnostics + ); } ProgramPublication? publication = FindPublication(shaderId, variant, scope); ArtifactResult result; if (suppliedArtifact is null) + { result = QueryArtifact(shader, variant); + } else { var lookup = new LookupKey(shaderId, variant.value, scope); @@ -144,33 +167,52 @@ internal bool TryResolveMaterial( } if (result.artifact is { } artifact && result.status == RenderTargetArtifactStatus.Ready && publication?.artifact.contentHash != artifact.contentHash - && !m_failedFrameCandidates.Contains(scope + artifact.contentHash)) - { + && !m_failedFrameCandidates.Contains(scope + artifact.contentHash) + ) { ProgramPublication? candidate = null; bool published = false; try { ShaderDefinition definition = m_targetArtifacts!.ReadShaderDefinition(artifact); ValidatePublication(artifact, definition, variant); - MaterialPassResolution? selected = MaterialPassResolver.Resolve(definition, material.techniqueId, - contractId, passRoleId, m_device.capabilities); + MaterialPassResolution? selected = MaterialPassResolver.Resolve( + definition, + material.techniqueId, + contractId, + passRoleId, + m_device.capabilities + ); if (selected is null) + { return Unavailable(material, contractId, passRoleId, diagnostics); + } if (selected.pass.programKind != expectedKind) + { return WrongKind(material, selected.pass, expectedKind, diagnostics); + } candidate = new(artifact, definition); var required = new HashSet(); if (publication is not null) + { foreach (ProgramLayout layout in publication.programs.Keys) + { if (artifact.passes.Any(pass => pass.name == layout.passName && pass.programKind == layout.kind)) + { required.Add(layout); + } + } + } required.Add(new(selected.pass.name, expectedKind, vertexLayout)); if (count - (publication?.programs.Count ?? 0) + required.Count > m_capacity) + { throw new InvalidOperationException("Shader program publication exceeds the configured program capacity."); + } var key = new PublicationKey(shaderId, artifact.targetKey, variant.value, scope); m_programs.RequireCapacity(key); foreach (ProgramLayout layout in required) + { candidate.programs.Add(layout, CreateProgram(artifact, layout)); + } candidate.lastUsedFrame = m_frameIndex; m_programs.Replace(key, candidate); publication = candidate; @@ -183,7 +225,9 @@ internal bool TryResolveMaterial( { // Publication has already committed; a retirement failure must never be reported as a rollback. if (published) + { throw; + } if (candidate is not null) { m_failedCandidates.Add(candidate); @@ -197,27 +241,52 @@ internal bool TryResolveMaterial( } } if (RetirementPendingException.Find(failure) is not null) + { throw; + } m_failedFrameCandidates.Add(scope + artifact.contentHash); - Publish("RENDER_PROGRAM_CREATE_FAILED", $"Shader kept its complete last-good publication: {failure.Message}", shader.assetPath.ToString(), diagnostics); + Publish( + "RENDER_PROGRAM_CREATE_FAILED", + $"Shader kept its complete last-good publication: {failure.Message}", + shader.assetPath.ToString(), + diagnostics + ); } } if (publication is null) + { return false; - return TryUsePublication(material, publication, contractId, passRoleId, expectedKind, vertexLayout, overrides, out materialPass, diagnostics); + } + return TryUsePublication( + material, + publication, + contractId, + passRoleId, + expectedKind, + vertexLayout, + overrides, + out materialPass, + diagnostics + ); } internal void ReleaseScope(string scope) { foreach (PublicationKey key in m_programs.Where(pair => pair.Key.scope == scope).Select(pair => pair.Key).ToArray()) + { m_programs.Release(key); + } } internal bool HasScope(string scope) { foreach (var pair in m_programs) + { if (pair.Key.scope == scope) + { return true; + } + } return false; } @@ -227,20 +296,28 @@ RenderShaderVariant variant ) { var key = new LookupKey(shader.identity.persistentId, variant.value, ""); if (m_frameArtifacts.TryGetValue(key, out ArtifactResult result)) + { return result; + } string source = shader.assetPath.ToString(); try { RenderShaderArtifact? artifact = null; RenderTargetArtifactStatus status = m_targetArtifacts?.GetShaderArtifact(shader, variant, m_device.capabilities, out artifact) - ?? RenderTargetArtifactStatus.Unavailable; + ?? RenderTargetArtifactStatus.Unavailable; if (status == RenderTargetArtifactStatus.Ready && artifact is null) + { throw new InvalidOperationException("The artifact provider returned Ready without a shader publication."); + } result = new(status, artifact); if (status == RenderTargetArtifactStatus.Unavailable) + { Publish("RENDER_SHADER_TARGET_UNAVAILABLE", "No target shader artifact is available for this device and variant.", source); + } else + { m_diagnostics.Resolve("RENDER_SHADER_TARGET_UNAVAILABLE", source); + } m_diagnostics.Resolve("RENDER_SHADER_TARGET_INVALID", source); } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) @@ -262,8 +339,12 @@ RenderShaderVariant variant string scope ) { foreach ((PublicationKey key, ProgramPublication publication) in m_programs) + { if (key.shaderId == shaderId && key.variantKey == variant.value && key.scope == scope) + { return publication; + } + } return null; } @@ -282,7 +363,9 @@ IDiagnosticReporter diagnostics foreach ((PublicationKey key, ProgramPublication publication) in m_programs) { if (key.shaderId != shaderId || key.scope != scope) + { continue; + } RenderShaderVariant variant; try { @@ -293,7 +376,9 @@ IDiagnosticReporter diagnostics continue; } if (variant.value == key.variantKey) + { return TryUsePublication(material, publication, contract, role, kind, layout, overrides, out result, diagnostics); + } } result = null; return false; @@ -311,19 +396,30 @@ private bool TryUsePublication( IDiagnosticReporter diagnostics ) { result = null; - MaterialPassResolution? resolution = MaterialPassResolver.Resolve(publication.definition, material.techniqueId, - contract, role, m_device.capabilities); + MaterialPassResolution? resolution = MaterialPassResolver.Resolve( + publication.definition, + material.techniqueId, + contract, + role, + m_device.capabilities + ); if (resolution is null) + { return Unavailable(material, contract, role, diagnostics); + } if (resolution.pass.programKind != kind) + { return WrongKind(material, resolution.pass, kind, diagnostics); + } var key = new ProgramLayout(resolution.pass.name, kind, layout); if (!publication.programs.TryGetValue(key, out ProgramEntry? program)) { try { if (count >= m_capacity) + { throw new InvalidOperationException("Shader program capacity is exhausted."); + } program = CreateProgram(publication.artifact, key); publication.programs.Add(key, program); } @@ -339,9 +435,17 @@ IDiagnosticReporter diagnostics } publication.lastUsedFrame = m_frameIndex; if (!TryBuildBindings(material, overrides, publication, program.shaderInterface, out MaterialBinding[] bindings, diagnostics)) + { return false; - result = CreateMaterialPass(resolution.pass, program.graphicsPipeline, program.computePipeline, - publication.definition.properties, program.shaderInterface, bindings); + } + result = CreateMaterialPass( + resolution.pass, + program.graphicsPipeline, + program.computePipeline, + publication.definition.properties, + program.shaderInterface, + bindings + ); diagnostics.Resolve("RENDER_MATERIAL_PASS_UNAVAILABLE", material.assetPath.ToString()); diagnostics.Resolve("RENDER_MATERIAL_PASS_KIND_MISMATCH", material.assetPath.ToString()); diagnostics.Resolve("RENDER_MATERIAL_PROPERTY_TYPE_MISMATCH", material.assetPath.ToString()); @@ -354,7 +458,12 @@ private bool Unavailable( ShaderPassRoleId role, IDiagnosticReporter diagnostics ) { - Publish("RENDER_MATERIAL_PASS_UNAVAILABLE", $"Material does not implement contract '{contract}' role '{role}' in its published shader.", material.assetPath.ToString(), diagnostics); + Publish( + "RENDER_MATERIAL_PASS_UNAVAILABLE", + $"Material does not implement contract '{contract}' role '{role}' in its published shader.", + material.assetPath.ToString(), + diagnostics + ); return false; } @@ -364,7 +473,12 @@ private bool WrongKind( ShaderProgramKind kind, IDiagnosticReporter diagnostics ) { - Publish("RENDER_MATERIAL_PASS_KIND_MISMATCH", $"Published pass '{pass.name}' is {pass.programKind}, not {kind}.", material.assetPath.ToString(), diagnostics); + Publish( + "RENDER_MATERIAL_PASS_KIND_MISMATCH", + $"Published pass '{pass.name}' is {pass.programKind}, not {kind}.", + material.assetPath.ToString(), + diagnostics + ); return false; } @@ -376,18 +490,33 @@ ProgramLayout layout IReadOnlyList bindings = BuildBindingDescriptors(pass.shaderInterface); if (pass.programKind == ShaderProgramKind.Raster) { - GraphicsPipelineHandle handle = m_device.CreateGraphicsPipeline(new GraphicsPipelineDescriptor( - pass.stages.Single(value => value.stage == ShaderStage.Vertex).bytes.Span, - pass.stages.Single(value => value.stage == ShaderStage.Fragment).bytes.Span, - bindings, layout.vertexLayout, pass.rasterState), artifact.shaderName + "/" + pass.name); + GraphicsPipelineHandle handle = m_device.CreateGraphicsPipeline( + new GraphicsPipelineDescriptor( + pass.stages.Single(value => value.stage == ShaderStage.Vertex).bytes.Span, + pass.stages.Single(value => value.stage == ShaderStage.Fragment).bytes.Span, + bindings, + layout.vertexLayout, + pass.rasterState + ), + artifact.shaderName + "/" + pass.name + ); if (!handle.isValid) + { throw new InvalidOperationException("The rendering device returned an invalid graphics pipeline."); + } return new(handle, default, pass.shaderInterface); } - ComputePipelineHandle compute = m_device.CreateComputePipeline(new ComputePipelineDescriptor( - pass.stages.Single(value => value.stage == ShaderStage.Compute).bytes.Span, bindings), artifact.shaderName + "/" + pass.name); + ComputePipelineHandle compute = m_device.CreateComputePipeline( + new ComputePipelineDescriptor( + pass.stages.Single(value => value.stage == ShaderStage.Compute).bytes.Span, + bindings + ), + artifact.shaderName + "/" + pass.name + ); if (!compute.isValid) + { throw new InvalidOperationException("The rendering device returned an invalid compute pipeline."); + } return new(default, compute, pass.shaderInterface); } @@ -404,9 +533,13 @@ internal void ValidateArtifact(RenderShaderArtifact artifact) finally { if (program?.graphicsPipeline.isValid == true) + { m_device.DestroyGraphicsPipeline(program.graphicsPipeline); + } if (program?.computePipeline.isValid == true) + { m_device.DestroyComputePipeline(program.computePipeline); + } } } } @@ -417,21 +550,35 @@ private void ValidatePublication( RenderShaderVariant variant ) { if (artifact.variant != variant || definition.name != artifact.shaderName) - throw new InvalidOperationException("The shader program publication does not match its requested variant and captured definition."); + { + throw new InvalidOperationException( + "The shader program publication does not match its requested variant and captured definition." + ); + } foreach (ShaderDiagnostic diagnostic in ShaderDefinitionValidator.Validate(definition, m_device.capabilities)) + { if (diagnostic.severity == DiagnosticSeverity.Error) + { throw new InvalidOperationException(diagnostic.message); + } + } var properties = definition.properties.ToDictionary(static property => property.id); foreach (RenderShaderPassArtifact pass in artifact.passes) { ShaderPassDefinition declared = definition.passes.SingleOrDefault(value => value.name == pass.name); if (declared.name != pass.name || declared.programKind != pass.programKind) + { throw new InvalidOperationException($"Program '{pass.name}' has no matching captured pass contract."); + } foreach (ShaderInterfaceBinding binding in pass.shaderInterface.bindings) + { if (!properties.TryGetValue(binding.id, out ShaderPropertyDefinition property) || property.type != binding.type || property.bindingKind != binding.bindingKind || property.storageAccess != binding.storageAccess - || (binding.stages & ~property.stages) != 0) + || (binding.stages & ~property.stages) != 0 + ) { throw new InvalidOperationException($"Program binding '{binding.id}' does not match its captured material contract."); + } + } } } @@ -474,9 +621,13 @@ IDiagnosticReporter diagnostics foreach (ShaderInterfaceBinding binding in shaderInterface.bindings) { if (!definitions.TryGetValue(binding.id, out ShaderPropertyDefinition property)) + { continue; + } if (property.bindingOwner == ShaderPropertyBindingOwner.RenderPass) + { continue; + } bool supplied = overrides is not null && overrides.TryGet(binding.id, out _); MaterialValue value; if (supplied) @@ -484,42 +635,49 @@ IDiagnosticReporter diagnostics overrides!.TryGet(binding.id, out value); } else if (material.TryGet(binding.id, out value)) + { supplied = true; + } else + { value = property.defaultValue; + } if (binding.bindingKind == ShaderPropertyBindingKind.SampledTexture) { RenderTextureArtifactReference reference; if (supplied && value.kind == MaterialValueKind.Texture && value.texture is not null) + { reference = value.texture.GetTextureArtifactReference(); + } else if (supplied || !publication.textureDefaults.TryGetValue(binding.id, out reference)) + { continue; + } if (!m_textureResolver(reference, out PersistentTextureHandle texture)) { bindings = []; return false; } - result.Add(CreateTextureBinding( - new RenderBindingId(binding.id.value), - texture, - value.sampler)); + result.Add(CreateTextureBinding(new RenderBindingId(binding.id.value), texture, value.sampler)); continue; } if (binding.bindingKind is ShaderPropertyBindingKind.StorageBuffer - or ShaderPropertyBindingKind.StorageTexture) + or ShaderPropertyBindingKind.StorageTexture + ) { continue; + } if (!TryEncodeUniform(binding.type, value, out byte[]? bytes)) { Publish( "RENDER_MATERIAL_PROPERTY_TYPE_MISMATCH", $"Material '{material.assetPath.ToString()}' property '{binding.id}' does not match {binding.type}.", - material.assetPath.ToString(), diagnostics); + material.assetPath.ToString(), + diagnostics + ); bindings = []; return false; } - result.Add(CreateUniformBinding( - new RenderBindingId(binding.id.value), - bytes)); + result.Add(CreateUniformBinding(new RenderBindingId(binding.id.value), bytes)); } bindings = result.ToArray(); return true; @@ -559,16 +717,24 @@ private static IReadOnlyList BuildBindingDescript foreach (ShaderInterfaceBinding binding in shaderInterface.bindings) { if (!binding.location.HasValue || binding.bindingKind == ShaderPropertyBindingKind.Uniform) + { continue; + } HashSet used = binding.bindingKind == ShaderPropertyBindingKind.SampledTexture ? textureSlots : storageSlots; if (!used.Add(binding.location.Value)) - throw new InvalidOperationException($"Shader resource slot '{binding.location}' is assigned more than once in its binding domain."); + { + throw new InvalidOperationException( + $"Shader resource slot '{binding.location}' is assigned more than once in its binding domain." + ); + } } static int Next(HashSet used) { int slot = 0; while (!used.Add(slot)) + { slot++; + } return slot; } foreach (ShaderInterfaceBinding binding in shaderInterface.bindings) @@ -577,37 +743,49 @@ static int Next(HashSet used) switch (binding.bindingKind) { case ShaderPropertyBindingKind.Uniform: - result.Add(new RenderShaderBindingDescriptor( - id, - RenderShaderBindingKind.Uniform, - uniformType: binding.type == ShaderPropertyType.Matrix4x4 - ? RenderUniformType.Matrix4x4 - : RenderUniformType.Vector4, - count: binding.arrayCount, - nativeName: binding.nativeName)); + result.Add( + new RenderShaderBindingDescriptor( + id, + RenderShaderBindingKind.Uniform, + uniformType: binding.type == ShaderPropertyType.Matrix4x4 + ? RenderUniformType.Matrix4x4 + : RenderUniformType.Vector4, + count: binding.arrayCount, + nativeName: binding.nativeName + ) + ); break; case ShaderPropertyBindingKind.SampledTexture: - result.Add(new RenderShaderBindingDescriptor( - id, - RenderShaderBindingKind.Texture, - slot: binding.location ?? Next(textureSlots), - nativeName: binding.nativeName)); + result.Add( + new RenderShaderBindingDescriptor( + id, + RenderShaderBindingKind.Texture, + slot: binding.location ?? Next(textureSlots), + nativeName: binding.nativeName + ) + ); break; case ShaderPropertyBindingKind.StorageTexture: - result.Add(new RenderShaderBindingDescriptor( - id, - RenderShaderBindingKind.StorageTexture, - slot: binding.location ?? Next(storageSlots), - storageAccess: binding.storageAccess, - nativeName: binding.nativeName)); + result.Add( + new RenderShaderBindingDescriptor( + id, + RenderShaderBindingKind.StorageTexture, + slot: binding.location ?? Next(storageSlots), + storageAccess: binding.storageAccess, + nativeName: binding.nativeName + ) + ); break; case ShaderPropertyBindingKind.StorageBuffer: - result.Add(new RenderShaderBindingDescriptor( - id, - RenderShaderBindingKind.StorageBuffer, - slot: binding.location ?? Next(storageSlots), - storageAccess: binding.storageAccess, - nativeName: binding.nativeName)); + result.Add( + new RenderShaderBindingDescriptor( + id, + RenderShaderBindingKind.StorageBuffer, + slot: binding.location ?? Next(storageSlots), + storageAccess: binding.storageAccess, + nativeName: binding.nativeName + ) + ); break; default: throw new ArgumentOutOfRangeException(nameof(binding)); @@ -621,12 +799,7 @@ private void Publish( string message, string? source, IDiagnosticReporter? diagnostics = null - ) - => (diagnostics ?? m_diagnostics).Publish(new Diagnostic( - code, - message, - DiagnosticSeverity.Error, - source)); + ) => (diagnostics ?? m_diagnostics).Publish(new Diagnostic(code, message, DiagnosticSeverity.Error, source)); private void DestroyPublication(ProgramPublication publication) { @@ -636,9 +809,13 @@ private void DestroyPublication(ProgramPublication publication) foreach (ProgramEntry program in publication.programs.Values) { if (program.graphicsPipeline.isValid) + { publication.retirement.Add(() => m_device.DestroyGraphicsPipeline(program.graphicsPipeline)); + } if (program.computePipeline.isValid) + { publication.retirement.Add(() => m_device.DestroyComputePipeline(program.computePipeline)); + } } publication.retirement.Add(publication.programs.Clear); } @@ -658,13 +835,16 @@ ShaderDefinition definition ShaderPropertyDefinition property = definition.properties[index]; MaterialValue value = property.defaultValue; if (value.texture is not null) + { textureDefaults.Add(property.id, value.texture.GetTextureArtifactReference()); + } value.texture = null; property.defaultValue = value; definition.properties[index] = property; properties.Add(property.id, property); } } + internal RenderShaderArtifact artifact { get; } internal ShaderDefinition definition { get; } internal Dictionary properties { get; } = []; @@ -679,22 +859,26 @@ private sealed record ProgramEntry( ComputePipelineHandle computePipeline, ShaderInterface shaderInterface ); + private readonly record struct ProgramLayout( string passName, ShaderProgramKind kind, RenderVertexLayout? vertexLayout ); + private readonly record struct PublicationKey( Guid shaderId, string targetKey, string variantKey, string scope ); + private readonly record struct LookupKey( Guid shaderId, string variantKey, string scope ); + private readonly record struct ArtifactResult( RenderTargetArtifactStatus status, RenderShaderArtifact? artifact diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs index f41acbccd..7dced018f 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs @@ -28,7 +28,9 @@ internal void AddFeature( RenderPipelineFeature feature ) { if (feature is IDisposable resource) + { m_lifetime.Own(resource); + } m_features.Add(id, feature); } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderPresentationComposer.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderPresentationComposer.cs index 2cebbda7d..72b663073 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderPresentationComposer.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderPresentationComposer.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -15,9 +14,10 @@ internal sealed class RenderPresentationComposer internal bool MustPreserve(RenderRequest request) { ArgumentNullException.ThrowIfNull(request); - return m_initializedRegions.Exists(region => + return m_initializedRegions.Exists(region => ( region.target == request.target - && Overlaps(region.viewport, request.viewport)); + && Overlaps(region.viewport, request.viewport) + )); } internal void Commit(RenderRequest request) @@ -31,11 +31,10 @@ internal void Commit(RenderRequest request) private static bool Overlaps( RenderViewport left, RenderViewport right - ) - => (long)left.x < (long)right.x + right.width - && (long)right.x < (long)left.x + left.width - && (long)left.y < (long)right.y + right.height - && (long)right.y < (long)left.y + left.height; + ) => (long)left.x < (long)right.x + right.width + && (long)right.x < (long)left.x + left.width + && (long)left.y < (long)right.y + right.height + && (long)right.y < (long)left.y + left.height; private readonly record struct PresentationRegion( RenderTarget target, diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderReadbackOwner.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderReadbackOwner.cs index 046910144..a185bb051 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderReadbackOwner.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderReadbackOwner.cs @@ -31,7 +31,9 @@ CancellationToken cancellation ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); cancellation.ThrowIfCancellationRequested(); if (!device.capabilities.Supports(GraphicsCapability.TextureReadback)) + { throw new NotSupportedException("The active backend does not support texture readback."); + } if (m_pending.Count >= capacity) { m_rejected++; @@ -54,7 +56,9 @@ internal void Update() try { if (!device.TryGetTextureReadback(handle, out RenderTextureReadbackResult? result)) + { continue; + } m_pending.Remove(handle); pending.completion.TrySetResult(result!); continue; @@ -72,7 +76,9 @@ internal void Update() try { if (!pending.retirement.TryComplete(() => device.CancelTextureReadback(handle))) + { throw new RetirementPendingException("Texture readback cancellation is still pending."); + } } catch (Exception unfinished) when (RetirementPendingException.Find(unfinished) is not null) { @@ -84,9 +90,13 @@ internal void Update() } m_pending.Remove(handle); if (pending.failure is not null) + { pending.completion.TrySetException(pending.failure); + } else + { pending.completion.TrySetCanceled(pending.cancellation); + } } } @@ -96,7 +106,9 @@ internal void Update() public void Dispose() { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new RenderRetirementQueue(); @@ -129,6 +141,9 @@ private sealed class PendingReadback(CancellationToken cancellation) internal Exception? failure { get; set; } internal RetirementBarrier? retirement { get; set; } internal CancellationToken cancellation { get; } = cancellation; - internal TaskCompletionSource completion { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + internal TaskCompletionSource completion { get; } = new( + TaskCreationOptions.RunContinuationsAsynchronously + ); } } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceCache.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceCache.cs index bcf2c6a5c..4139256e2 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceCache.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceCache.cs @@ -1,7 +1,7 @@ using System; using System.Collections; -using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Inno.Core.Execution; @@ -10,8 +10,9 @@ namespace Inno.Rendering.Runtime; internal sealed class RenderResourceCache( Action release, int capacity -) - : IEnumerable>, IDisposable where TKey : notnull where TEntry : class +) : IEnumerable>, IDisposable + where TKey : notnull + where TEntry : class { private readonly Dictionary m_entries = []; private readonly Queue m_retiring = []; @@ -48,7 +49,9 @@ internal void Replace( TEntry candidate ) { if (m_entries.TryGetValue(key, out TEntry? previous)) + { m_retiring.Enqueue(previous); + } m_entries[key] = candidate; m_peak = Math.Max(m_peak, m_entries.Count); } @@ -56,7 +59,9 @@ TEntry candidate internal void Release(TKey key) { if (m_entries.Remove(key, out TEntry? entry)) + { m_retiring.Enqueue(entry); + } Drain(); } @@ -64,7 +69,9 @@ internal void Sweep(Func unused) { Drain(); foreach (TKey key in m_entries.Where(pair => unused(pair.Value)).Select(pair => pair.Key).ToArray()) + { Release(key); + } } internal void Drain() @@ -76,12 +83,16 @@ internal void Drain() try { if (!m_barrier.TryComplete(() => release(entry))) + { throw new RetirementPendingException("A retired GPU resource still owns unfinished work."); + } } catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { if (failures.Count != 0) + { throw new AggregateException("GPU retirement is pending after completed failures.", [.. failures, pending]); + } throw; } catch (Exception failure) @@ -108,7 +119,9 @@ public void Dispose() { m_stopping = true; foreach (TEntry entry in m_entries.Values) + { m_retiring.Enqueue(entry); + } m_entries.Clear(); } Drain(); diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs index c0c9375a8..72066929f 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs @@ -21,14 +21,17 @@ public sealed class RenderResourceLimits /// Gets the maximum resident frame-upload pages. /// public int uploadPages { get; init; } = 1024; + /// /// Gets the maximum resident frame-upload bytes, including retired pages. /// public long uploadResidentBytes { get; init; } = 256L * 1024 * 1024; + /// /// Gets the maximum bytes uploaded during one frame. /// public long uploadBytesPerFrame { get; init; } = 64L * 1024 * 1024; + /// /// Gets the offscreen target count and per-frame target allocation capacity. /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs index 8fff3a6b5..18a5d3ff4 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs @@ -1,11 +1,11 @@ -using Inno.Core.Diagnostics; using System; -using Inno.Core.Execution; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; using Inno.Rendering; using Inno.Rendering.Assets; @@ -66,7 +66,9 @@ public void ValidateShaderArtifact(RenderShaderArtifact artifact) ThrowIfDisposed(); ArgumentNullException.ThrowIfNull(artifact); if (!m_mutationAllowed) + { throw new InvalidOperationException("Shader artifact validation requires an open frame before graph execution."); + } m_materials.ValidateArtifact(artifact); } @@ -84,10 +86,12 @@ public RenderTargetArtifactStatus PrewarmMaterial(MaterialAsset material) ThrowIfDisposed(); ArgumentNullException.ThrowIfNull(material); ShaderAsset shader = material.shader - ?? throw new ArgumentException("A material must reference a shader before prewarming.", nameof(material)); + ?? throw new ArgumentException("A material must reference a shader before prewarming.", nameof(material)); RenderShaderVariant variant = RenderShaderVariant.FromMaterial(material); if (m_targetArtifacts is null) + { throw new InvalidOperationException("No render target artifact provider is configured for this runtime."); + } return m_targetArtifacts.GetShaderArtifact(shader, variant, m_device.capabilities, out _); } @@ -114,9 +118,13 @@ public void PrewarmTextureArtifact(RenderTextureArtifactReference texture) { ThrowIfDisposed(); if (texture.assetId == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + { throw new ArgumentException("A valid texture artifact reference is required.", nameof(texture)); + } if (m_targetArtifacts is null) + { throw new InvalidOperationException("No render target artifact provider is configured for this runtime."); + } _ = m_targetArtifacts.GetTextureArtifact(texture, out _); } @@ -154,8 +162,8 @@ string name ArgumentException.ThrowIfNullOrWhiteSpace(name); if (m_buffers.TryGetValue(id, out BufferEntry? current) && current.revision == revision - && BufferDescriptorsEqual(current.descriptor, descriptor)) - { + && BufferDescriptorsEqual(current.descriptor, descriptor) + ) { current.lastUsedFrame = m_frameIndex; return current.handle; } @@ -202,12 +210,14 @@ string name ArgumentNullException.ThrowIfNull(subresources); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (subresources.Count == 0) + { throw new ArgumentException("A raw texture requires at least one subresource upload.", nameof(subresources)); + } if (m_textures.TryGetValue(id, out TextureEntry? current) && current.kind == TextureEntryKind.Raw && current.revision == revision - && descriptor.Equals(current.descriptor)) - { + && descriptor.Equals(current.descriptor) + ) { current.lastUsedFrame = m_frameIndex; return current.handle; } @@ -221,17 +231,14 @@ string name if (subresource.mipLevel >= descriptor.mipCount || (subresource.mipLevel < descriptor.mipCount && subresource.arrayLayer - >= descriptor.GetSubresourceLayerCount(subresource.mipLevel))) - { + >= descriptor.GetSubresourceLayerCount(subresource.mipLevel)) + ) { throw new ArgumentException( "A texture upload addresses a mip or layer outside its descriptor.", - nameof(subresources)); + nameof(subresources) + ); } - m_device.UpdateTexture( - candidate, - subresource.data.Span, - subresource.mipLevel, - subresource.arrayLayer); + m_device.UpdateTexture(candidate, subresource.data.Span, subresource.mipLevel, subresource.arrayLayer); } } catch (Exception failure) @@ -240,12 +247,7 @@ string name throw; } - var replacement = new TextureEntry( - candidate, - TextureEntryKind.Raw, - descriptor, - revision, - m_frameIndex); + var replacement = new TextureEntry(candidate, TextureEntryKind.Raw, descriptor, revision, m_frameIndex); m_textures.Replace(id, replacement); m_textures.Drain(); return candidate; @@ -283,12 +285,14 @@ string name RequireId(id); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (containerData.IsEmpty) + { throw new ArgumentException("A KTX resource cannot be empty.", nameof(containerData)); + } if (m_textures.TryGetValue(id, out TextureEntry? current) && current.kind == TextureEntryKind.Ktx && current.revision == revision - && current.sRgb == sRgb) - { + && current.sRgb == sRgb + ) { current.lastUsedFrame = m_frameIndex; return current.handle; } @@ -298,14 +302,16 @@ string name RenderTextureContainer.Ktx, containerData.Span, sRgb, - name); + name + ); var replacement = new TextureEntry( candidate, TextureEntryKind.Ktx, descriptor: null, revision, m_frameIndex, - sRgb); + sRgb + ); m_textures.Replace(id, replacement); m_textures.Drain(); return candidate; @@ -330,9 +336,13 @@ ReadOnlyMemory data ) { ThrowIfDisposed(); if (!texture.isValid) + { throw new ArgumentException("A valid persistent texture is required.", nameof(texture)); + } if (data.IsEmpty) + { throw new ArgumentException("Texture update data cannot be empty.", nameof(data)); + } m_device.UpdateTextureRegion(texture, region, data.Span); } @@ -400,7 +410,8 @@ out RenderMaterialPass? materialPass ShaderProgramKind.Raster, vertexLayout, overrides, - out materialPass); + out materialPass + ); } /// @@ -456,13 +467,29 @@ out RenderMaterialPass? materialPass ArgumentNullException.ThrowIfNull(artifact); ArgumentNullException.ThrowIfNull(diagnostics); if (m_targetArtifacts is null) + { throw new InvalidOperationException("No render target artifact decoder is configured."); + } if (!Enum.IsDefined(programKind)) + { throw new ArgumentOutOfRangeException(nameof(programKind)); + } if (programKind == ShaderProgramKind.Compute && vertexLayout is not null) + { throw new ArgumentException("A compute program cannot consume a vertex layout.", nameof(vertexLayout)); - return m_materials.TryResolveMaterial(material, contractId, passRoleId, programKind, vertexLayout, overrides, - out materialPass, artifact, scope.value, diagnostics); + } + return m_materials.TryResolveMaterial( + material, + contractId, + passRoleId, + programKind, + vertexLayout, + overrides, + out materialPass, + artifact, + scope.value, + diagnostics + ); } /// @@ -501,7 +528,8 @@ out RenderMaterialPass? materialPass ShaderProgramKind.Compute, vertexLayout: null, overrides, - out materialPass); + out materialPass + ); } /// @@ -571,15 +599,17 @@ out PersistentTextureHandle resolvedTexture ThrowIfDisposed(); resolvedTexture = default; if (texture.assetId == Guid.Empty || string.IsNullOrWhiteSpace(texture.slot.id)) + { return false; + } RenderPersistentResourceId resourceId = new($"asset:{texture.assetId:D}:texture:{texture.slot.id}"); bool sRgb = texture.slot.colorSpace == TextureColorSpace.Srgb; if (m_textures.TryGetValue(resourceId, out TextureEntry? current) && current.kind == TextureEntryKind.Ktx && current.revision == texture.contentRevision - && current.sRgb == sRgb) - { + && current.sRgb == sRgb + ) { current.lastUsedFrame = m_frameIndex; resolvedTexture = current.handle; return true; @@ -588,11 +618,13 @@ out PersistentTextureHandle resolvedTexture { ReadOnlyMemory artifact = ReadOnlyMemory.Empty; RenderTargetArtifactStatus status = m_targetArtifacts is null - ? RenderTargetArtifactStatus.Unavailable - : m_targetArtifacts.GetTextureArtifact(texture, out artifact); + ? RenderTargetArtifactStatus.Unavailable + : m_targetArtifacts.GetTextureArtifact(texture, out artifact); string sourceId = $"{texture.assetId:D}:{texture.slot.id}"; if (status != RenderTargetArtifactStatus.Unavailable) + { m_diagnostics.Resolve("RENDER_TEXTURE_TARGET_UNAVAILABLE", sourceId); + } if (status != RenderTargetArtifactStatus.Ready) { if (status == RenderTargetArtifactStatus.Unavailable) @@ -600,9 +632,10 @@ out PersistentTextureHandle resolvedTexture Publish( "RENDER_TEXTURE_TARGET_UNAVAILABLE", m_targetArtifacts is null - ? "No render target artifact provider is configured for this runtime." - : $"No deployed target texture artifact exists for '{sourceId}'.", - sourceId); + ? "No render target artifact provider is configured for this runtime." + : $"No deployed target texture artifact exists for '{sourceId}'.", + sourceId + ); } if (m_textures.TryGetValue(resourceId, out TextureEntry? lastGood)) { @@ -615,14 +648,10 @@ m_targetArtifacts is null if (artifact.IsEmpty) { throw new InvalidOperationException( - $"Target artifact provider returned an empty ready texture for '{sourceId}'."); + $"Target artifact provider returned an empty ready texture for '{sourceId}'." + ); } - resolvedTexture = AcquireKtxTexture( - resourceId, - texture.contentRevision, - artifact, - sRgb, - sourceId); + resolvedTexture = AcquireKtxTexture(resourceId, texture.contentRevision, artifact, sRgb, sourceId); m_diagnostics.Resolve("RENDER_TEXTURE_RESOLVE_FAILED", sourceId); return true; } @@ -635,7 +664,8 @@ m_targetArtifacts is null Publish( "RENDER_TEXTURE_RESOLVE_FAILED", $"Texture artifact '{texture.assetId:D}:{texture.slot.id}' kept its last-good GPU resource: {exception.Message}", - $"{texture.assetId:D}:{texture.slot.id}"); + $"{texture.assetId:D}:{texture.slot.id}" + ); if (m_textures.TryGetValue(resourceId, out TextureEntry? lastGood)) { lastGood.lastUsedFrame = m_frameIndex; @@ -675,8 +705,8 @@ string name ArgumentNullException.ThrowIfNull(descriptor); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (m_graphicsPipelines.TryGetValue(id, out GraphicsPipelineEntry? current) - && current.revision == revision) - { + && current.revision == revision + ) { current.lastUsedFrame = m_frameIndex; return current.handle; } @@ -718,8 +748,8 @@ string name ArgumentNullException.ThrowIfNull(descriptor); ArgumentException.ThrowIfNullOrWhiteSpace(name); if (m_computePipelines.TryGetValue(id, out ComputePipelineEntry? current) - && current.revision == revision) - { + && current.revision == revision + ) { current.lastUsedFrame = m_frameIndex; return current.handle; } @@ -745,8 +775,10 @@ public void Release(RenderPersistentResourceId id) if (!m_mutationAllowed) { if (m_materials.HasScope(id.value) || m_graphicsPipelines.TryGetValue(id, out _) - || m_computePipelines.TryGetValue(id, out _) || m_buffers.TryGetValue(id, out _) || m_textures.TryGetValue(id, out _)) + || m_computePipelines.TryGetValue(id, out _) || m_buffers.TryGetValue(id, out _) || m_textures.TryGetValue(id, out _) + ) { m_pendingReleases.Add(id); + } return; } ThrowIfDisposed(); @@ -768,13 +800,17 @@ private void ReleaseNow(RenderPersistentResourceId id) public void Dispose() { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new RenderRetirementQueue(); m_retirement.Add(m_readbacks.Dispose); if (m_failedAllocation is not null) + { m_retirement.Add(m_failedAllocation.Dispose); + } m_retirement.Add(m_materials.Dispose); m_retirement.Add(m_geometry.Dispose); m_retirement.Add(m_graphicsPipelines.Dispose); @@ -803,12 +839,30 @@ private void CompleteRetirement() m_disposed = true; } - internal RenderResourceStatistics statistics => new() + internal RenderResourceStatistics statistics + => new() { - activeResources = m_buffers.Count + m_textures.Count + m_graphicsPipelines.Count + m_computePipelines.Count + m_materials.count + m_geometry.count, - retiringResources = m_buffers.pendingCount + m_textures.pendingCount + m_graphicsPipelines.pendingCount + m_computePipelines.pendingCount + m_materials.retiringCount + m_geometry.retiringCount, - rejectedResources = m_buffers.rejectedCount + m_textures.rejectedCount + m_graphicsPipelines.rejectedCount + m_computePipelines.rejectedCount + m_materials.rejectedCount + m_geometry.rejectedCount, - pendingReadbacks = m_readbacks.count, peakReadbacks = m_readbacks.peakCount, rejectedReadbacks = m_readbacks.rejectedCount + activeResources = m_buffers.Count + + m_textures.Count + + m_graphicsPipelines.Count + + m_computePipelines.Count + + m_materials.count + + m_geometry.count, + retiringResources = m_buffers.pendingCount + + m_textures.pendingCount + + m_graphicsPipelines.pendingCount + + m_computePipelines.pendingCount + + m_materials.retiringCount + + m_geometry.retiringCount, + rejectedResources = m_buffers.rejectedCount + + m_textures.rejectedCount + + m_graphicsPipelines.rejectedCount + + m_computePipelines.rejectedCount + + m_materials.rejectedCount + + m_geometry.rejectedCount, + pendingReadbacks = m_readbacks.count, + peakReadbacks = m_readbacks.peakCount, + rejectedReadbacks = m_readbacks.rejectedCount }; internal void BeginFrame(ulong frameIndex) @@ -820,18 +874,23 @@ internal void BeginFrame(ulong frameIndex) m_materials.BeginFrame(frameIndex); m_readbacks.Update(); foreach (RenderPersistentResourceId id in m_pendingReleases) + { ReleaseNow(id); + } m_pendingReleases.Clear(); } internal void EndMutation() => m_mutationAllowed = false; + internal void BeginMutation() => m_mutationAllowed = true; internal void SweepUnused() { ThrowIfDisposed(); if (m_frameIndex < C_UNUSED_FRAME_LIMIT) + { return; + } ulong oldest = m_frameIndex - C_UNUSED_FRAME_LIMIT; m_materials.Sweep(oldest); m_geometry.Sweep(oldest); @@ -844,27 +903,23 @@ internal void SweepUnused() private static bool BufferDescriptorsEqual( PersistentBufferDescriptor left, PersistentBufferDescriptor right - ) - => left.buffer.Equals(right.buffer) - && Equals(left.vertexLayout, right.vertexLayout) - && left.indexFormat == right.indexFormat; + ) => left.buffer.Equals(right.buffer) + && Equals(left.vertexLayout, right.vertexLayout) + && left.indexFormat == right.indexFormat; private static void RequireId(RenderPersistentResourceId id) { if (!id.isValid) + { throw new ArgumentException("A persistent render resource ID must be valid.", nameof(id)); + } } private void Publish( string code, string message, string? source - ) - => m_diagnostics.Publish(new Diagnostic( - code, - message, - DiagnosticSeverity.Error, - source)); + ) => m_diagnostics.Publish(new Diagnostic(code, message, DiagnosticSeverity.Error, source)); private void ThrowIfDisposed() { @@ -984,5 +1039,4 @@ ulong lastUsedFrame internal long revision { get; } internal ulong lastUsedFrame { get; set; } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceStatistics.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceStatistics.cs index a7074ec67..316bacaef 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceStatistics.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceStatistics.cs @@ -9,50 +9,62 @@ public readonly record struct RenderResourceStatistics /// Gets active persistent buffers, textures, pipelines, material programs and geometry pairs. /// public int activeResources { get; init; } + /// /// Gets resource entries whose native retirement is still pending. /// public int retiringResources { get; init; } + /// /// Gets cache admissions rejected by per-kind capacity. /// public long rejectedResources { get; init; } + /// /// Gets readbacks that still own native operations. /// public int pendingReadbacks { get; init; } + /// /// Gets the largest simultaneous readback occupancy. /// public int peakReadbacks { get; init; } + /// /// Gets readbacks rejected before native allocation. /// public long rejectedReadbacks { get; init; } + /// /// Gets retained upload pages, including pages awaiting retirement. /// public int uploadPages { get; init; } + /// /// Gets resident upload bytes, including pages awaiting retirement. /// public long uploadResidentBytes { get; init; } + /// /// Gets the high-water mark of resident upload bytes. /// public long uploadPeakBytes { get; init; } + /// /// Gets successfully uploaded bytes during the current frame. /// public long uploadedFrameBytes { get; init; } + /// /// Gets upload requests rejected by resident or per-frame limits. /// public long rejectedUploads { get; init; } + /// /// Gets active offscreen targets. /// public int targets { get; init; } + /// /// Gets offscreen target requests rejected by finite capacity. /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs index c01e50a82..fc2d4a1b5 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs @@ -13,7 +13,9 @@ internal sealed class RenderRetirementQueue : IDisposable internal void Add(Action retire) { if (m_stopping) + { throw new InvalidOperationException("Rendering retirement no longer accepts allocations."); + } m_steps.Enqueue(retire); } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs index a25c85cce..4bbc7081b 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs @@ -1,16 +1,16 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -35,7 +35,9 @@ public void RegisterContributor(IRenderFrameGraphContributor contributor) lock (m_contributorLock) { if (m_contributors.Contains(contributor)) + { throw new ArgumentException("Frame graph contributor is already registered.", nameof(contributor)); + } m_contributors.Add(contributor); m_contributorSnapshot = new RenderContributorSnapshot(m_contributors); } @@ -56,7 +58,9 @@ public bool UnregisterContributor(IRenderFrameGraphContributor contributor) lock (m_contributorLock) { if (!m_contributors.Remove(contributor)) + { return false; + } m_contributorSnapshot = new RenderContributorSnapshot(m_contributors); return true; } @@ -114,5 +118,4 @@ private void AddContributors( } } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs index b9ae28368..2cd87afaa 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs @@ -1,16 +1,16 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -18,8 +18,7 @@ sealed partial class RenderRuntime { private void PublishModelDiagnostic(string message) { - PublishFrameIssue(new Diagnostic("RENDER_OUTPUT_MODEL_UNAVAILABLE", message, - DiagnosticSeverity.Warning)); + PublishFrameIssue(new Diagnostic("RENDER_OUTPUT_MODEL_UNAVAILABLE", message, DiagnosticSeverity.Warning)); } private void PublishFrameIssue(Diagnostic diagnostic) @@ -34,11 +33,15 @@ private void ReconcileFrameIssues() foreach (FrameIssueKey key in m_previousFrameIssues.Keys) { if (!m_currentFrameIssues.ContainsKey(key)) + { m_diagnostics.Resolve(key.code, key.semanticId, key.objectId); + } } m_previousFrameIssues.Clear(); foreach ((FrameIssueKey key, Diagnostic diagnostic) in m_currentFrameIssues) + { m_previousFrameIssues.Add(key, diagnostic); + } m_currentFrameIssues.Clear(); } @@ -48,15 +51,18 @@ string source ) { foreach (RenderGraphDiagnostic diagnostic in diagnostics) { - PublishFrameIssue(new Diagnostic( - diagnostic.code, - diagnostic.message, - diagnostic.severity == DiagnosticSeverity.Error + PublishFrameIssue( + new Diagnostic( + diagnostic.code, + diagnostic.message, + diagnostic.severity == DiagnosticSeverity.Error ? DiagnosticSeverity.Error : diagnostic.severity == DiagnosticSeverity.Warning - ? DiagnosticSeverity.Warning - : DiagnosticSeverity.Info, - diagnostic.passName ?? diagnostic.resourceName ?? source)); + ? DiagnosticSeverity.Warning + : DiagnosticSeverity.Info, + diagnostic.passName ?? diagnostic.resourceName ?? source + ) + ); } } @@ -64,17 +70,18 @@ private void PublishContributorFailure( IRenderFrameGraphContributor contributor, string stage, Exception exception - ) - => PublishFrameIssue(new Diagnostic( + ) => PublishFrameIssue( + new Diagnostic( "RENDER_FRAME_CONTRIBUTOR_FAILED", $"Frame contributor '{contributor.GetType().Name}' failed during {stage}: {exception.Message}", DiagnosticSeverity.Error, - contributor.GetType().FullName)); + contributor.GetType().FullName + ) + ); private readonly record struct FrameIssueKey( string code, string? semanticId, Guid? objectId ); - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs index 6dcf9a33e..142076a5b 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs @@ -1,16 +1,16 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -25,9 +25,11 @@ sealed partial class RenderRuntime protected override void OnBeginFrame(RuntimeFrame frame) { m_frameInput = InputExecutionContext.TryGet(out IInputService? input) - ? input!.snapshot : InputSnapshot.empty; + ? input!.snapshot + : InputSnapshot.empty; OwnFrameScope(EnterExecutionScope()); } + /// /// Opens resources required for this frame's output. /// @@ -35,6 +37,7 @@ protected override void OnBeginFrame(RuntimeFrame frame) /// The variable frame timing. /// protected override void OnPrepareOutput(RuntimeFrame frame) => BeginRendering(frame.unscaledDeltaTime); + /// /// Collects output commands without executing managed code on a native realtime callback. /// @@ -42,6 +45,7 @@ protected override void OnBeginFrame(RuntimeFrame frame) /// The variable frame timing. /// protected override void OnProduceOutput(RuntimeFrame frame) => CollectRendering(frame.unscaledDeltaTime); + /// /// Submits output and closes output-specific temporary resources. /// @@ -65,7 +69,9 @@ private void BeginRendering(float deltaTime) m_device.BeginFrame(); m_frameOpen = true; lock (m_contributorLock) + { m_frameContributors = m_contributorSnapshot; + } try { m_resourceService.BeginFrame(m_frameIndex); @@ -73,9 +79,12 @@ private void BeginRendering(float deltaTime) targets.PrepareFrame(); m_primaryPresentationSize = m_device.primaryPresentationSize; if (m_primaryPresentationSize is RenderPresentationSize size && !size.isValid) + { throw new InvalidOperationException("The render device reported an invalid primary presentation extent."); + } m_primaryPresentationViewport = m_primaryPresentationSize is RenderPresentationSize available - ? ResolvePrimaryPresentationViewport(available) : null; + ? ResolvePrimaryPresentationViewport(available) + : null; lock (m_requestLock) { m_currentRequests.Clear(); @@ -119,7 +128,9 @@ private void BeginRendering(float deltaTime) private void CollectRendering(float deltaTime) { if (!m_frameOpen || m_requestProviders is null) + { return; + } using IDisposable executionScope = EnterExecutionScope(); using ContentReadScope content = GetFrameContentScope(); @@ -134,10 +145,23 @@ private void CollectRendering(float deltaTime) m_frameIndex, deltaTime, this, - outputInput); + outputInput + ); if (m_primaryModelOutputEnabled && m_primaryPresentationViewport is RenderViewport viewport) - CollectModels(new RenderOutputSession("primary", content, viewport, - m_frameIndex, deltaTime, this, outputInput, m_primaryRoute)); + { + CollectModels( + new RenderOutputSession( + "primary", + content, + viewport, + m_frameIndex, + deltaTime, + this, + outputInput, + m_primaryRoute + ) + ); + } foreach (RenderExtensionRegistry.RequestProviderEntry entry in m_requestProviders.providers) { try @@ -150,11 +174,14 @@ private void CollectRendering(float deltaTime) } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_REQUEST_PROVIDER_FAILED", - $"Render request provider '{entry.id}' was isolated after failure: {exception}", - DiagnosticSeverity.Error, - entry.id)); + PublishFrameIssue( + new Diagnostic( + "RENDER_REQUEST_PROVIDER_FAILED", + $"Render request provider '{entry.id}' was isolated after failure: {exception}", + DiagnosticSeverity.Error, + entry.id + ) + ); } } } @@ -162,11 +189,13 @@ private void CollectRendering(float deltaTime) private ContentReadScope GetFrameContentScope() { if (m_contentScopeProvider is null) + { return ContentReadScope.empty; + } try { return m_contentScopeProvider() - ?? throw new InvalidOperationException("The host content-scope provider returned null."); + ?? throw new InvalidOperationException("The host content-scope provider returned null."); } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) { @@ -174,11 +203,14 @@ private ContentReadScope GetFrameContentScope() } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_CONTENT_SCOPE_FAILED", - $"The host content scope failed and an empty scope was used for this frame: {exception}", - DiagnosticSeverity.Error, - "RenderRuntime")); + PublishFrameIssue( + new Diagnostic( + "RENDER_CONTENT_SCOPE_FAILED", + $"The host content scope failed and an empty scope was used for this frame: {exception}", + DiagnosticSeverity.Error, + "RenderRuntime" + ) + ); return ContentReadScope.empty; } } @@ -193,7 +225,9 @@ private void CompleteRendering(float deltaTime) { _ = deltaTime; if (!m_frameOpen) + { return; + } int executedViewCount = 0; int culledPassCount = 0; @@ -202,7 +236,9 @@ private void CompleteRendering(float deltaTime) try { lock (m_requestLock) + { m_acceptingCurrentFrame = false; + } RenderGraphBuilder graph = CreateGraph(); AddPrimaryPresentationBackground(graph); @@ -211,9 +247,15 @@ private void CompleteRendering(float deltaTime) int requestIndex = 0; RenderPresentationComposer presentation = m_scratch.presentation; foreach (RenderRequest request in m_currentRequests) + { m_scratch.scheduled.Add(new ScheduledWork(m_scratch.scheduled.Count, request.priority, request.name, request, null)); + } foreach (CompositionRequest composition in m_currentCompositions) - m_scratch.scheduled.Add(new ScheduledWork(m_scratch.scheduled.Count, composition.priority, composition.name, null, composition)); + { + m_scratch.scheduled.Add( + new ScheduledWork(m_scratch.scheduled.Count, composition.priority, composition.name, null, composition) + ); + } m_scratch.scheduled.Sort(static ( left, right @@ -221,7 +263,9 @@ private void CompleteRendering(float deltaTime) { int priority = left.priority.CompareTo(right.priority); if (priority != 0) + { return priority; + } int name = StringComparer.Ordinal.Compare(left.name, right.name); return name != 0 ? name : left.order.CompareTo(right.order); }); @@ -235,7 +279,9 @@ private void CompleteRendering(float deltaTime) RenderRequest request = work.request!; bool preservePresentationTarget = presentation.MustPreserve(request); if (TryBuildRequest(graph, request, requestIndex++, preservePresentationTarget)) + { presentation.Commit(request); + } } AddContributors(graph, m_scratch.contributors); @@ -267,7 +313,9 @@ private void CompleteRendering(float deltaTime) m_scratch.Clear(); m_frameContributors = RenderContributorSnapshot.empty; if (!retirementPending) + { EndRenderingFrame(executedViewCount, culledPassCount, graphCompileCount); + } } } @@ -303,8 +351,14 @@ void CompleteFrameState() m_currentCompositions.Clear(); m_frameIndex++; m_graphicsSettings.frameStatistics = new RenderFrameStatistics( - m_frameIndex, executedViewCount, counters.drawCount, counters.dispatchCount, culledPassCount, - allocations, graphCompileCount); + m_frameIndex, + executedViewCount, + counters.drawCount, + counters.dispatchCount, + culledPassCount, + allocations, + graphCompileCount + ); } } @@ -313,7 +367,9 @@ private void CompleteViewContentFrame() foreach (RenderExtensionRegistry.ContentSourceEntry entry in m_extensions.extensions.sources.sources) { if (entry.source is not IViewContentFrameSource source) + { continue; + } try { source.CompleteFrame(m_frameIndex); @@ -324,9 +380,14 @@ private void CompleteViewContentFrame() } catch (Exception exception) { - PublishFrameIssue(new Diagnostic("RENDER_VIEW_CONTENT_FRAME_FAILED", - $"View content source '{entry.id}' failed to complete its frame: {exception}", - DiagnosticSeverity.Error, entry.id)); + PublishFrameIssue( + new Diagnostic( + "RENDER_VIEW_CONTENT_FRAME_FAILED", + $"View content source '{entry.id}' failed to complete its frame: {exception}", + DiagnosticSeverity.Error, + entry.id + ) + ); } } } @@ -335,7 +396,9 @@ private RenderGraphBuilder CreateGraph() { m_graphGeneration++; if (m_graphGeneration == 0) + { m_graphGeneration++; + } return new RenderGraphBuilder(m_graphGeneration, m_device.capabilities); } @@ -357,5 +420,4 @@ public void Submit(ViewContentItem item) m_items.Add(item); } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs index 1a469aa17..e2fe64885 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs @@ -1,16 +1,16 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -26,7 +26,9 @@ public void SetPrimaryRoute(RenderOutputRoute? route) { EnsureActive(); if (m_frameOpen) + { throw new InvalidOperationException("Output routes can only change at a frame boundary."); + } m_primaryRoute = route; } @@ -41,9 +43,10 @@ public void SetPrimaryModelOutputEnabled(bool enabled) { EnsureActive(); if (m_frameOpen) + { throw new InvalidOperationException("Primary output ownership can only change at a frame boundary."); + } m_primaryModelOutputEnabled = enabled; - } private void CollectModels(RenderOutputSession session) @@ -56,13 +59,20 @@ private void CollectModels(RenderOutputSession session) try { if (entry.model.CanRender(session)) + { applicable.Add(entry); + } } catch (Exception exception) { - PublishFrameIssue(new Diagnostic("RENDER_MODEL_ACCEPT_FAILED", - $"Render model '{entry.id}' failed to inspect output content: {exception}", - DiagnosticSeverity.Error, entry.id)); + PublishFrameIssue( + new Diagnostic( + "RENDER_MODEL_ACCEPT_FAILED", + $"Render model '{entry.id}' failed to inspect output content: {exception}", + DiagnosticSeverity.Error, + entry.id + ) + ); } } if (applicable.Count == 0) @@ -100,12 +110,16 @@ private void CollectModels(RenderOutputSession session) } else if (applicable.Count > 1) { - PublishModelDiagnostic("Multiple rendering models accept the primary output; configure a RenderOutputRoute: " - + string.Join(", ", applicable.Select(static entry => entry.id))); + PublishModelDiagnostic( + "Multiple rendering models accept the primary output; configure a RenderOutputRoute: " + + string.Join(", ", applicable.Select(static entry => entry.id)) + ); return; } if (route is null) + { ordered.AddRange(applicable); + } List requests = m_scratch.modelRequests; RenderTextureFormat? format = null; @@ -115,8 +129,8 @@ private void CollectModels(RenderOutputSession session) try { RenderOutputSession modelSession = route is null - ? session - : session.ForLayer(route.layers[index]); + ? session + : session.ForLayer(route.layers[index]); RenderModelOutput model = entry.model.Build(modelSession); if (format is RenderTextureFormat selected && selected != model.targetFormat) { @@ -124,22 +138,45 @@ private void CollectModels(RenderOutputSession session) return; } format ??= model.targetFormat; - requests.Add(new RenderRequest(model.name, RenderTarget.backbuffer, session.viewport, - model.pipeline, model.data, 1000 + index)); + requests.Add( + new RenderRequest( + model.name, + RenderTarget.backbuffer, + session.viewport, + model.pipeline, + model.data, + 1000 + index + ) + ); } catch (Exception exception) { - PublishFrameIssue(new Diagnostic("RENDER_MODEL_BUILD_FAILED", - $"Render model '{entry.id}' failed to build output: {exception}", - DiagnosticSeverity.Error, entry.id)); + PublishFrameIssue( + new Diagnostic( + "RENDER_MODEL_BUILD_FAILED", + $"Render model '{entry.id}' failed to build output: {exception}", + DiagnosticSeverity.Error, + entry.id + ) + ); return; } } if (requests.Count == 1 && m_device.primaryPresentationEncodesSrgb) + { Submit(requests[0]); + } else - SubmitComposition($"Output:{session.id}", RenderTarget.backbuffer, - session.viewport, format!.Value, requests, priority: 1000); + { + SubmitComposition( + $"Output:{session.id}", + RenderTarget.backbuffer, + session.viewport, + format!.Value, + requests, + priority: 1000 + ); + } } finally { @@ -148,5 +185,4 @@ private void CollectModels(RenderOutputSession session) m_scratch.modelRequests.Clear(); } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs index b6a294e82..3030ee434 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs @@ -1,16 +1,16 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -33,7 +33,9 @@ public bool TryActivateDefaultPipeline(RenderPipelineAsset pipelineAsset) EnsureActive(); ArgumentNullException.ThrowIfNull(pipelineAsset); if (m_frameOpen) + { throw new InvalidOperationException("A default pipeline can only change at a frame boundary."); + } if (TryGetGeneration(pipelineAsset, out _)) { m_graphicsSettings.defaultPipeline = pipelineAsset; @@ -56,9 +58,13 @@ public IRenderRuntimeReloadTransaction BeginExtensionReload() { EnsureActive(); if (m_frameOpen) + { throw new InvalidOperationException("Rendering extensions can only reload at a frame boundary."); + } if (m_reloadSession is not null) + { throw new InvalidOperationException("A rendering extension reload is already active."); + } m_reloadSession = RenderRuntimeReloadSession.Create(this); return m_reloadSession; @@ -82,13 +88,16 @@ out RenderPipelineGeneration? generation catch (Exception exception) { m_extensions.EnsureHealthy(); - m_diagnostics.Publish(new Diagnostic( - "RENDER_EXTENSION_REGISTRY_FAILED", - $"Rendering extension discovery kept every last-good generation: {exception.Message}", - DiagnosticSeverity.Error, - asset.pipelineTypeId)); + m_diagnostics.Publish( + new Diagnostic( + "RENDER_EXTENSION_REGISTRY_FAILED", + $"Rendering extension discovery kept every last-good generation: {exception.Message}", + DiagnosticSeverity.Error, + asset.pipelineTypeId + ) + ); return m_generations.TryGetValue(asset, out GenerationCacheEntry? failedEntry) - && (generation = failedEntry.lastGood) is not null; + && (generation = failedEntry.lastGood) is not null; } m_diagnostics.Resolve("RENDER_EXTENSION_REGISTRY_FAILED", asset.pipelineTypeId); @@ -99,15 +108,15 @@ out RenderPipelineGeneration? generation } if (entry.lastGood is not null - && entry.lastGood.typeCacheVersion != snapshot.typeCacheVersion) - { + && entry.lastGood.typeCacheVersion != snapshot.typeCacheVersion + ) { m_extensions.Retire(entry.lastGood); entry.lastGood = null; } if (entry.attemptedTypeCacheVersion == snapshot.typeCacheVersion - && string.Equals(entry.attemptedFingerprint, fingerprint, StringComparison.Ordinal)) - { + && string.Equals(entry.attemptedFingerprint, fingerprint, StringComparison.Ordinal) + ) { generation = entry.lastGood; return generation is not null; } @@ -130,11 +139,14 @@ out RenderPipelineGeneration? generation catch (Exception exception) { m_extensions.EnsureHealthy(); - m_diagnostics.Publish(new Diagnostic( - "RENDER_EXTENSION_GENERATION_FAILED", - $"Pipeline '{asset.pipelineTypeId}' kept its last-good generation: {exception.Message}", - DiagnosticSeverity.Error, - asset.pipelineTypeId)); + m_diagnostics.Publish( + new Diagnostic( + "RENDER_EXTENSION_GENERATION_FAILED", + $"Pipeline '{asset.pipelineTypeId}' kept its last-good generation: {exception.Message}", + DiagnosticSeverity.Error, + asset.pipelineTypeId + ) + ); generation = entry.lastGood; return generation is not null; } @@ -150,13 +162,14 @@ private static bool TryCreateGeneration( RenderExtensionRegistry.Snapshot snapshot, RenderPipelineAsset asset, out RenderPipelineGeneration? generation - ) - => snapshot.TryCreateGeneration(asset, out generation); + ) => snapshot.TryCreateGeneration(asset, out generation); private void EndReloadSession(RenderRuntimeReloadSession session) { if (ReferenceEquals(m_reloadSession, session)) + { m_reloadSession = null; + } } private void PruneRetiredGenerations() @@ -174,32 +187,38 @@ private void PruneRetiredGenerations() catch (Exception exception) { m_extensions.EnsureHealthy(); - m_diagnostics.Publish(new Diagnostic( - "RENDER_EXTENSION_REGISTRY_FAILED", - $"Rendering extension discovery kept the current frame available: {exception.Message}", - DiagnosticSeverity.Error)); + m_diagnostics.Publish( + new Diagnostic( + "RENDER_EXTENSION_REGISTRY_FAILED", + $"Rendering extension discovery kept the current frame available: {exception.Message}", + DiagnosticSeverity.Error + ) + ); return; } m_diagnostics.Resolve("RENDER_EXTENSION_REGISTRY_FAILED"); if (m_prunedTypeCacheVersion == snapshot.typeCacheVersion) + { return; + } m_scratch.generations.AddRange(m_generations); try { foreach ((RenderPipelineAsset asset, GenerationCacheEntry entry) in m_scratch.generations) { if (entry.lastGood is not null - && entry.lastGood.typeCacheVersion != snapshot.typeCacheVersion) - { + && entry.lastGood.typeCacheVersion != snapshot.typeCacheVersion + ) { m_extensions.Retire(entry.lastGood); entry.lastGood = null; } if (entry.attemptedTypeCacheVersion != snapshot.typeCacheVersion) + { m_generations.Remove(asset); + } } - } finally { @@ -207,8 +226,8 @@ private void PruneRetiredGenerations() } if (m_requestProviders is not null - && m_requestProviders.typeCacheVersion != snapshot.typeCacheVersion) - { + && m_requestProviders.typeCacheVersion != snapshot.typeCacheVersion + ) { m_requestProviders = null; } m_prunedTypeCacheVersion = snapshot.typeCacheVersion; @@ -222,8 +241,8 @@ RenderPipelineContext context foreach (RenderFeatureConfiguration configuration in asset.features) { if (!configuration.enabled - || !features.TryGetValue(configuration.featureTypeId, out RenderPipelineFeature? feature)) - { + || !features.TryGetValue(configuration.featureTypeId, out RenderPipelineFeature? feature) + ) { continue; } @@ -239,11 +258,14 @@ RenderPipelineContext context } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_FEATURE_FAILED", - $"Feature '{configuration.featureTypeId}' was rolled back: {exception.Message}", - DiagnosticSeverity.Error, - configuration.featureTypeId)); + PublishFrameIssue( + new Diagnostic( + "RENDER_FEATURE_FAILED", + $"Feature '{configuration.featureTypeId}' was rolled back: {exception.Message}", + DiagnosticSeverity.Error, + configuration.featureTypeId + ) + ); } } } @@ -303,10 +325,10 @@ internal static RenderRuntimeReloadSession Create(RenderRuntime owner) var previous = new Dictionary(); foreach ((RenderPipelineAsset asset, GenerationCacheEntry entry) in owner.m_generations) { - previous.Add(asset, new GenerationState( - entry.attemptedTypeCacheVersion, - entry.attemptedFingerprint, - entry.lastGood)); + previous.Add( + asset, + new GenerationState(entry.attemptedTypeCacheVersion, entry.attemptedFingerprint, entry.lastGood) + ); } lock (owner.m_requestLock) { @@ -317,7 +339,8 @@ internal static RenderRuntimeReloadSession Create(RenderRuntime owner) [.. owner.m_pendingRequests], [.. owner.m_currentRequests], [.. owner.m_pendingCompositions], - [.. owner.m_currentCompositions]); + [.. owner.m_currentCompositions] + ); } } @@ -325,7 +348,9 @@ internal void PrepareCandidate() { EnsureNotFinished(); if (m_prepared) + { return; + } RenderExtensionRegistry.Snapshot snapshot = m_owner.m_extensions.extensions; try @@ -335,10 +360,7 @@ internal void PrepareCandidate() { string fingerprint = RenderExtensionRegistry.GetConfigurationFingerprint(asset); _ = TryCreateGeneration(snapshot, asset, out RenderPipelineGeneration? candidate); - m_candidates.Add(asset, new GenerationState( - snapshot.typeCacheVersion, - fingerprint, - candidate)); + m_candidates.Add(asset, new GenerationState(snapshot.typeCacheVersion, fingerprint, candidate)); } m_prepared = true; } @@ -349,14 +371,15 @@ internal void PrepareCandidate() catch (Exception exception) { DisposeCandidates(); - m_owner.m_diagnostics.Publish(new Diagnostic( - "RENDER_EXTENSION_RELOAD_REJECTED", - "Rendering extension candidate was rejected and every last-good generation was retained: " + - exception.Message, - DiagnosticSeverity.Error)); - throw new InvalidOperationException( - "Rendering extension candidate activation failed.", - exception); + m_owner.m_diagnostics.Publish( + new Diagnostic( + "RENDER_EXTENSION_RELOAD_REJECTED", + "Rendering extension candidate was rejected and every last-good generation was retained: " + + exception.Message, + DiagnosticSeverity.Error + ) + ); + throw new InvalidOperationException("Rendering extension candidate activation failed.", exception); } } @@ -364,14 +387,20 @@ internal void Activate() { EnsureNotFinished(); if (!m_prepared) + { throw new InvalidOperationException("Rendering extension candidates have not been prepared."); + } if (m_activated) + { return; + } foreach (RenderPipelineAsset asset in m_candidates.Keys) { if (!m_owner.m_generations.ContainsKey(asset)) + { throw new InvalidOperationException("A tracked rendering generation changed during reload."); + } } foreach ((RenderPipelineAsset asset, GenerationState candidate) in m_candidates) { @@ -396,14 +425,18 @@ internal void Complete() { EnsureNotFinished(); if (!m_activated) + { throw new InvalidOperationException("Rendering extension candidates have not been activated."); + } try { var resources = new LifetimeScope(); foreach (GenerationState previous in m_previous!.Values) { if (previous.lastGood is not null) + { resources.Own(previous.lastGood); + } } m_owner.m_extensions.Retire(resources); } @@ -423,14 +456,18 @@ internal void Complete() internal void Rollback() { if (m_finished) + { return; + } if (m_activated) { foreach ((RenderPipelineAsset asset, GenerationState previous) in m_previous!) { if (!m_owner.m_generations.TryGetValue(asset, out GenerationCacheEntry? entry)) + { continue; + } entry.attemptedTypeCacheVersion = previous.attemptedTypeCacheVersion; entry.attemptedFingerprint = previous.attemptedFingerprint; entry.lastGood = previous.lastGood; @@ -478,7 +515,9 @@ private void DisposeCandidates() foreach (GenerationState candidate in m_candidates.Values) { if (candidate.lastGood is not null) + { resources.Own(candidate.lastGood); + } } m_owner.m_extensions.Retire(resources); m_candidates.Clear(); @@ -502,8 +541,9 @@ private void Finish() private void EnsureNotFinished() { if (m_finished) + { throw new InvalidOperationException("Rendering extension reload session is already finished."); + } } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs index 02a118e18..8c08175e4 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs @@ -1,16 +1,16 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -20,15 +20,18 @@ private RenderViewport ResolvePrimaryPresentationViewport(RenderPresentationSize { var fullViewport = new RenderViewport(0, 0, size.width, size.height); if (m_primaryPresentationViewportProvider is null) + { return fullViewport; + } try { RenderViewport viewport = m_primaryPresentationViewportProvider(size); if ((long)viewport.x + viewport.width > size.width - || (long)viewport.y + viewport.height > size.height) - { + || (long)viewport.y + viewport.height > size.height + ) { throw new InvalidOperationException( - "The configured viewport extends beyond the primary presentation surface."); + "The configured viewport extends beyond the primary presentation surface." + ); } return viewport; } @@ -38,11 +41,14 @@ private RenderViewport ResolvePrimaryPresentationViewport(RenderPresentationSize } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_PRESENTATION_VIEWPORT_FAILED", - $"The primary presentation viewport was invalid and the complete surface was used: {exception.Message}", - DiagnosticSeverity.Error, - "RenderRuntime")); + PublishFrameIssue( + new Diagnostic( + "RENDER_PRESENTATION_VIEWPORT_FAILED", + $"The primary presentation viewport was invalid and the complete surface was used: {exception.Message}", + DiagnosticSeverity.Error, + "RenderRuntime" + ) + ); return fullViewport; } } @@ -50,45 +56,63 @@ private RenderViewport ResolvePrimaryPresentationViewport(RenderPresentationSize private RenderOutputInput CreatePrimaryOutputInput(InputSnapshot input) { if (m_primaryPresentationSize is not RenderPresentationSize physicalSize - || m_primaryPresentationViewport is not RenderViewport viewport) + || m_primaryPresentationViewport is not RenderViewport viewport + ) { return RenderOutputInput.suspended; + } Vector2 pointerPosition = input.mousePosition; if (m_primaryInputSurfaceSizeProvider is not null) { RenderPresentationSize? inputSize = m_primaryInputSurfaceSizeProvider(); if (inputSize is not RenderPresentationSize logicalSize) + { return RenderOutputInput.suspended; + } if (!logicalSize.isValid) + { throw new InvalidOperationException("The primary input surface has an invalid logical size."); + } pointerPosition = new Vector2( pointerPosition.x * physicalSize.width / logicalSize.width, - pointerPosition.y * physicalSize.height / logicalSize.height); + pointerPosition.y * physicalSize.height / logicalSize.height + ); } Vector2 pointer = pointerPosition - new Vector2(viewport.x, viewport.y); return new RenderOutputInput( - pointer, pointer.x >= 0f && pointer.y >= 0f && pointer.x < viewport.width && pointer.y < viewport.height, - input.scrollDelta, input.modifiers, input.keysPressed, input.keysReleased, - input.mouseButtonsPressed, input.mouseButtonsReleased, input.textInput); + pointer, + pointer.x >= 0f && pointer.y >= 0f && pointer.x < viewport.width && pointer.y < viewport.height, + input.scrollDelta, + input.modifiers, + input.keysPressed, + input.keysReleased, + input.mouseButtonsPressed, + input.mouseButtonsReleased, + input.textInput + ); } private void AddPrimaryPresentationBackground(RenderGraphBuilder graph) { if (m_primaryPresentationSize is not RenderPresentationSize size - || m_primaryPresentationViewport is not RenderViewport viewport) + || m_primaryPresentationViewport is not RenderViewport viewport + ) { return; + } if (viewport.x == 0 && viewport.y == 0 && viewport.width == size.width && viewport.height == size.height) { return; } - graph.AddRasterPass( + graph + .AddRasterPass( "Primary Presentation Background", S_PRESENTATION_BACKGROUND_PHASE, 0, static ( _, _ - ) => { }) + ) => {} + ) .ClearPresentationTarget(S_PRESENTATION_BACKGROUND_COLOR) .HasSideEffect(); } @@ -99,38 +123,57 @@ private void BuildComposition( ref int requestIndex ) { if (composition.target.kind == RenderTargetKind.Backbuffer && !m_primaryPresentationSize.HasValue) + { return; + } try { using RenderGraphMutationScope mutation = graph.BeginMutationScope(); - using RenderGraphNameScope names = graph.BeginNameScope( - $"Composition {composition.name}"); + using RenderGraphNameScope names = graph.BeginNameScope($"Composition {composition.name}"); var layers = new List(composition.layers.Length); for (int index = 0; index < composition.layers.Length; index++) { RenderTextureHandle color = graph.CreateTexture( $"Model Layer {index + 1}", new RenderTextureDescriptor( - composition.viewport.width, composition.viewport.height, + composition.viewport.width, + composition.viewport.height, composition.format, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); RenderRequest layer = composition.layers[index]; - var localLayer = new RenderRequest(layer.name, layer.target, + var localLayer = new RenderRequest( + layer.name, + layer.target, new RenderViewport(0, 0, composition.viewport.width, composition.viewport.height), - layer.pipeline, layer.data, layer.priority); - if (!TryBuildRequest(graph, localLayer, requestIndex++, - preservePresentationTarget: false, outputOverride: color)) + layer.pipeline, + layer.data, + layer.priority + ); + if (!TryBuildRequest( + graph, + localLayer, + requestIndex++, + preservePresentationTarget: false, + outputOverride: color + )) { return; + } layers.Add(color); } RenderTextureHandle output = composition.target.kind == RenderTargetKind.Texture - ? targets.Import(graph, composition.target.texture - ?? throw new InvalidOperationException("A texture output requires a RenderTexture.")) - : default; - m_compositor.AddPasses(graph, composition.name, layers, output, - composition.viewport, composition.format); + ? targets.Import( + graph, + composition.target.texture + ?? throw new InvalidOperationException("A texture output requires a RenderTexture.") + ) + : default; + m_compositor.AddPasses(graph, composition.name, layers, output, composition.viewport, composition.format); if (output.isValid) + { graph.MarkOutput(output); + } RenderGraphValidationResult validation = graph.Validate(); if (!validation.isValid) { @@ -145,12 +188,14 @@ ref int requestIndex } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_OUTPUT_COMPOSITION_FAILED", - $"Output composition '{composition.name}' was isolated after failure: {exception}", - DiagnosticSeverity.Error, - composition.name)); + PublishFrameIssue( + new Diagnostic( + "RENDER_OUTPUT_COMPOSITION_FAILED", + $"Output composition '{composition.name}' was isolated after failure: {exception}", + DiagnosticSeverity.Error, + composition.name + ) + ); } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs index 361832668..6862eb191 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs @@ -1,16 +1,16 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -36,8 +36,10 @@ public void Submit(RenderRequest request) { EnsureActive(); if (m_currentRequests.Count + m_pendingRequests.Count - + m_currentCompositions.Count + m_pendingCompositions.Count >= C_MAX_QUEUED_REQUESTS) + + m_currentCompositions.Count + m_pendingCompositions.Count >= C_MAX_QUEUED_REQUESTS + ) { throw new InvalidOperationException("The rendering request queue is at capacity."); + } (m_acceptingCurrentFrame ? m_currentRequests : m_pendingRequests).Add(request); } } @@ -80,20 +82,27 @@ public void SubmitComposition( ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(layers); if (layers.Count == 0 || layers.Any(static layer => layer is null)) + { throw new ArgumentException("A composition requires at least one non-null model layer.", nameof(layers)); + } if (layers.Any(layer => layer.viewport != viewport || layer.target != target)) + { throw new ArgumentException("All composition layers must name the same final target and viewport.", nameof(layers)); + } if (!m_device.capabilities.SupportsRenderTarget(format) - || !m_device.capabilities.SupportsSampled(format)) + || !m_device.capabilities.SupportsSampled(format) + ) { throw new ArgumentException($"The device cannot sample and render model layers in '{format}'.", nameof(format)); - var composition = new CompositionRequest(name, target, viewport, format, - layers.ToArray(), priority); + } + var composition = new CompositionRequest(name, target, viewport, format, layers.ToArray(), priority); lock (m_requestLock) { EnsureActive(); if (m_currentRequests.Count + m_pendingRequests.Count - + m_currentCompositions.Count + m_pendingCompositions.Count >= C_MAX_QUEUED_REQUESTS) + + m_currentCompositions.Count + m_pendingCompositions.Count >= C_MAX_QUEUED_REQUESTS + ) { throw new InvalidOperationException("The rendering request queue is at capacity."); + } (m_acceptingCurrentFrame ? m_currentCompositions : m_pendingCompositions).Add(composition); } } @@ -106,36 +115,45 @@ private bool TryBuildRequest( RenderTextureHandle outputOverride = default ) { if (request.target.kind == RenderTargetKind.Backbuffer && !outputOverride.isValid && !m_primaryPresentationSize.HasValue) + { return false; + } RenderPipelineAsset? asset = request.pipeline ?? m_graphicsSettings.defaultPipeline; if (asset is null) { - PublishFrameIssue(new Diagnostic( - "RENDER_PIPELINE_UNAVAILABLE", - $"Render request '{request.name}' has no pipeline. The frame and UI remain active.", - DiagnosticSeverity.Warning, - request.name)); + PublishFrameIssue( + new Diagnostic( + "RENDER_PIPELINE_UNAVAILABLE", + $"Render request '{request.name}' has no pipeline. The frame and UI remain active.", + DiagnosticSeverity.Warning, + request.name + ) + ); return false; } if (!TryGetGeneration(asset, out RenderPipelineGeneration? generation)) + { return false; + } try { using RenderGraphMutationScope mutation = graph.BeginMutationScope(); - using RenderGraphNameScope names = graph.BeginNameScope( - $"Request[{requestIndex}] {request.name}"); + using RenderGraphNameScope names = graph.BeginNameScope($"Request[{requestIndex}] {request.name}"); RenderTextureHandle outputTexture = outputOverride.isValid - ? outputOverride - : request.target.kind == RenderTargetKind.Texture - ? targets.Import( - graph, - request.target.texture - ?? throw new InvalidOperationException("A texture target requires a RenderTexture.")) - : default; + ? outputOverride + : request.target.kind == RenderTargetKind.Texture + ? targets.Import( + graph, + request.target.texture + ?? throw new InvalidOperationException("A texture target requires a RenderTexture.") + ) + : default; if (outputTexture.isValid && !outputOverride.isValid) + { graph.MarkOutput(outputTexture); + } var context = new RenderPipelineContext( request, @@ -148,7 +166,8 @@ private bool TryBuildRequest( m_uploads, m_frameIndex, preservePresentationTarget, - outputTexture); + outputTexture + ); generation!.pipeline.Build(context); AddFeatures(asset, generation.features, context); RenderGraphValidationResult validation = graph.Validate(); @@ -166,11 +185,14 @@ private bool TryBuildRequest( } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_REQUEST_FAILED", - $"Render request '{request.name}' was isolated after failure: {exception}", - DiagnosticSeverity.Error, - request.name)); + PublishFrameIssue( + new Diagnostic( + "RENDER_REQUEST_FAILED", + $"Render request '{request.name}' was isolated after failure: {exception}", + DiagnosticSeverity.Error, + request.name + ) + ); return false; } } @@ -196,5 +218,4 @@ private readonly record struct ScheduledWork( RenderRequest? request, CompositionRequest? composition ); - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs index 7b47d446d..2b9e3dfcb 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs @@ -1,16 +1,16 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -22,7 +22,9 @@ sealed partial class RenderRuntime private void ReleaseRendering() { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new RenderRetirementQueue(); @@ -64,7 +66,9 @@ private void ReleaseRendering() m_retirement.Add(() => { if (m_frameOpen) + { _ = m_device.EndFrame(); + } m_frameOpen = false; }); m_retirement.Add(m_uploads.EndFrame); @@ -91,7 +95,9 @@ private void RetireGenerations() foreach (GenerationCacheEntry entry in m_generations.Values) { if (entry.lastGood is not null) + { resources.Add(entry.lastGood.Dispose); + } } try { @@ -116,7 +122,9 @@ private void PruneRetiredAssets() foreach ((RenderPipelineAsset asset, GenerationCacheEntry entry) in m_generations) { if (entry.hasAssetOwner && !ReferenceEquals(entry.assetIdentity.Resolve(), asset)) + { m_retiredAssets.Add(asset); + } } foreach (RenderPipelineAsset asset in m_retiredAssets) { @@ -129,5 +137,4 @@ private void PruneRetiredAssets() m_retiredAssets.Clear(); } } - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs index 83993eeaf..198bb809b 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs @@ -1,16 +1,16 @@ -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Input; -using Inno.Core.Mathematics; +using Inno.References; +using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -20,8 +20,9 @@ namespace Inno.Rendering.Runtime; public sealed partial class RenderRuntime : RuntimeSubsystem, IRenderRequestSink, IViewContentCollector { private const int C_MAX_QUEUED_REQUESTS = 4096; - private static readonly RenderPhaseId S_PRESENTATION_BACKGROUND_PHASE = new( - "inno.runtime.presentation-background"); + + private static readonly RenderPhaseId S_PRESENTATION_BACKGROUND_PHASE = new("inno.runtime.presentation-background"); + private static readonly RenderClearColor S_PRESENTATION_BACKGROUND_COLOR = new(0f, 0f, 0f, 1f); private readonly object m_requestLock = new(); @@ -129,7 +130,9 @@ public RenderRuntime( foreach (IRenderFrameGraphContributor contributor in contributors) { if (contributor is null || m_contributors.Contains(contributor)) + { throw new ArgumentException("Initial contributors must contain unique non-null instances.", nameof(contributors)); + } m_contributors.Add(contributor); } } @@ -140,11 +143,7 @@ public RenderRuntime( m_primaryPresentationViewportProvider = primaryPresentationViewportProvider; m_extensions = new RenderExtensionRegistry(types); m_graphicsSettings = new GraphicsSettingsState(m_device.capabilities); - m_resourceService = new RenderResourceService( - m_device, - m_diagnostics, - targetArtifacts, - resourceLimits); + m_resourceService = new RenderResourceService(m_device, m_diagnostics, targetArtifacts, resourceLimits); m_uploads = new RenderFrameUploadService(m_device, resourceLimits); m_compositor = new RenderLayerCompositor(m_device, compositionProgramProvider); targets = new RenderTargetStore(device, resourceLimits.targets); @@ -187,8 +186,10 @@ public IReadOnlyList Collect(ViewContentContext context) foreach (RenderExtensionRegistry.ContentSourceEntry entry in m_extensions.extensions.sources.sources) { if (context.sourceIds is { } sourceIds - && !sourceIds.Contains(entry.id, StringComparer.Ordinal)) + && !sourceIds.Contains(entry.id, StringComparer.Ordinal) + ) { continue; + } try { entry.source.Collect(context, sink); @@ -199,11 +200,14 @@ public IReadOnlyList Collect(ViewContentContext context) } catch (Exception exception) { - PublishFrameIssue(new Diagnostic( - "RENDER_VIEW_CONTENT_SOURCE_FAILED", - $"View content source '{entry.id}' was isolated after failure: {exception}", - DiagnosticSeverity.Error, - entry.id)); + PublishFrameIssue( + new Diagnostic( + "RENDER_VIEW_CONTENT_SOURCE_FAILED", + $"View content source '{entry.id}' was isolated after failure: {exception}", + DiagnosticSeverity.Error, + entry.id + ) + ); } } return sink.items; @@ -217,11 +221,16 @@ public IReadOnlyList Collect(ViewContentContext context) /// /// Gets a detached control-thread snapshot of resource occupancy, high-water marks and rejected admissions. /// - public RenderResourceStatistics resourceStatistics => m_resourceService.statistics with + public RenderResourceStatistics resourceStatistics + => m_resourceService.statistics with { - uploadPages = m_uploads.pageCount, uploadResidentBytes = m_uploads.residentBytes, - uploadPeakBytes = m_uploads.peakResidentBytes, uploadedFrameBytes = m_uploads.frameBytes, - rejectedUploads = m_uploads.rejectedCount, targets = targets.count, rejectedTargets = targets.rejectedCount + uploadPages = m_uploads.pageCount, + uploadResidentBytes = m_uploads.residentBytes, + uploadPeakBytes = m_uploads.peakResidentBytes, + uploadedFrameBytes = m_uploads.frameBytes, + rejectedUploads = m_uploads.rejectedCount, + targets = targets.count, + rejectedTargets = targets.rejectedCount }; /// @@ -254,7 +263,9 @@ private void EnsureActive() { ObjectDisposedException.ThrowIf(m_disposed, this); if (m_retirement is not null) + { throw new InvalidOperationException("Rendering retirement has started and cannot accept new work."); + } m_extensions.EnsureHealthy(); } @@ -263,5 +274,4 @@ private void EnsureActive() /// owned by this instance. /// protected override void OnStop() => ReleaseRendering(); - } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntimeFactory.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntimeFactory.cs index 2950b6817..e63a5fe60 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntimeFactory.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntimeFactory.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime; @@ -29,7 +28,8 @@ public RenderRuntimeFactory(Func runtime public RuntimeSubsystemDescriptor descriptor { get; } = new( new RuntimeSubsystemId("inno.runtime.rendering"), order: 1000, - lifetime: RuntimeSubsystemLifetime.Host); + lifetime: RuntimeSubsystemLifetime.Host + ); /// /// Creates a rendering feature over a newly allocated runtime layer. @@ -44,7 +44,7 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); RenderRuntime runtime = m_runtimeFactory(context) - ?? throw new InvalidOperationException("The rendering runtime factory returned null."); + ?? throw new InvalidOperationException("The rendering runtime factory returned null."); return runtime; } } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderTargetStore.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderTargetStore.cs index ee3a38e4b..1f9348120 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderTargetStore.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderTargetStore.cs @@ -73,8 +73,8 @@ RenderTexture target if (!m_targets.TryGetValue(target, out TargetEntry? entry) || entry.revision != target.contentRevision - || !entry.descriptor.Equals(target.descriptor)) - { + || !entry.descriptor.Equals(target.descriptor) + ) { if ((entry is null && m_targets.Count >= m_capacity) || m_frameAllocations >= m_capacity) { m_rejected++; @@ -83,7 +83,9 @@ RenderTexture target PersistentTextureHandle next = m_device.CreateTexture(target.descriptor, target.name); m_frameAllocations++; if (entry is not null) + { Retire(entry.handle); + } entry = new TargetEntry(target.contentRevision, target.descriptor, next); m_targets[target] = entry; } @@ -130,8 +132,12 @@ internal void MarkWrittenOutputs(CompiledRenderGraph graph) ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); ArgumentNullException.ThrowIfNull(graph); foreach (TargetEntry entry in m_targets.Values) + { if (!entry.hasWritten && WritesTarget(graph, entry.handle)) + { entry.hasWritten = true; + } + } } /// @@ -145,7 +151,9 @@ public void Release(RenderTexture target) ObjectDisposedException.ThrowIf(m_disposed || m_retirement is not null, this); ArgumentNullException.ThrowIfNull(target); if (m_targets.ContainsKey(target)) + { m_pendingReleases.Add(target); + } } /// @@ -162,7 +170,9 @@ public void PrepareFrame() { m_frameRetirement = new RenderRetirementQueue(); foreach (PersistentTextureHandle texture in m_retireFollowingFrame) + { m_frameRetirement.Add(() => m_device.DestroyTexture(texture)); + } m_retireFollowingFrame.Clear(); } try @@ -186,7 +196,9 @@ public void PrepareFrame() foreach (RenderTexture target in m_pendingReleases) { if (m_targets.Remove(target, out TargetEntry? entry)) + { Retire(entry.handle); + } } m_pendingReleases.Clear(); } @@ -203,18 +215,28 @@ public void PrepareFrame() public void Dispose() { if (m_disposed) + { return; + } if (m_retirement is null) { m_retirement = new RenderRetirementQueue(); if (m_frameRetirement is not null) + { m_retirement.Add(m_frameRetirement.Dispose); + } foreach (TargetEntry entry in m_targets.Values) + { m_retirement.Add(() => m_device.DestroyTexture(entry.handle)); + } foreach (PersistentTextureHandle texture in m_retireNextFrame) + { m_retirement.Add(() => m_device.DestroyTexture(texture)); + } foreach (PersistentTextureHandle texture in m_retireFollowingFrame) + { m_retirement.Add(() => m_device.DestroyTexture(texture)); + } } try { @@ -239,11 +261,19 @@ PersistentTextureHandle handle foreach (CompiledRenderTexture texture in graph.textures) { if (!texture.imported || texture.persistentHandle != handle) + { continue; + } foreach (CompiledRenderPass pass in graph.passes) + { foreach (CompiledRenderAttachment attachment in pass.attachments) + { if (attachment.texture == texture.handle) + { return true; + } + } + } } return false; } @@ -260,7 +290,9 @@ private void CompleteRetirement() private void Retire(PersistentTextureHandle texture) { if (texture.isValid) + { m_retireNextFrame.Add(texture); + } } private sealed record TargetEntry( diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs index 1191dd614..abaf25f73 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs @@ -1,5 +1,5 @@ -using Inno.Rendering; using System; +using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -17,4 +17,3 @@ public interface IRenderRequestSink /// void Submit(RenderRequest request); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs index 2e7b7c50e..30b41ac65 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs @@ -1,7 +1,7 @@ -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -41,13 +41,16 @@ public sealed class RenderFrameData public void Set( Inno.Rendering.RenderDataChannelId channel, TValue value - ) - where TValue : notnull + ) where TValue : notnull { if (!channel.isValid) + { throw new ArgumentException("A render data channel must be valid.", nameof(channel)); + } if (m_isReadOnly) + { throw new InvalidOperationException("Submitted render frame data is immutable."); + } ArgumentNullException.ThrowIfNull(value); m_values[new FrameDataKey(channel, typeof(TValue))] = value; } @@ -73,8 +76,8 @@ out TValue? value ) { if (channel.isValid && m_values.TryGetValue(new FrameDataKey(channel, typeof(TValue)), out object? stored) - && stored is TValue typed) - { + && stored is TValue typed + ) { value = typed; return true; } @@ -92,7 +95,9 @@ out TValue? value public void Clear() { if (m_isReadOnly) + { throw new InvalidOperationException("Submitted render frame data is immutable."); + } m_values.Clear(); } @@ -100,7 +105,9 @@ internal RenderFrameData Snapshot() { var snapshot = new RenderFrameData(); foreach ((FrameDataKey key, object value) in m_values) + { snapshot.m_values.Add(key, value); + } snapshot.m_isReadOnly = true; return snapshot; } @@ -110,4 +117,3 @@ private readonly record struct FrameDataKey( Type type ); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs index 3fb6bb3fa..5f5cdec4b 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs @@ -1,7 +1,7 @@ -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -79,4 +79,3 @@ public RenderRequest( /// public int priority { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs index 3dcf3aeef..8470fff18 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs @@ -1,7 +1,7 @@ +using System; using Inno.Core.Execution; using Inno.References; using Inno.Rendering; -using System; namespace Inno.Rendering.Runtime; @@ -93,15 +93,18 @@ public RenderRequestProviderContext( this.capabilities = capabilities ?? throw new ArgumentNullException(nameof(capabilities)); this.primaryPresentationSize = primaryPresentationSize; if (primaryPresentationSize.HasValue != primaryPresentationViewport.HasValue) + { throw new ArgumentException("Primary presentation size and viewport must have the same availability."); + } if (primaryPresentationSize is RenderPresentationSize size && primaryPresentationViewport is RenderViewport viewport && (!size.isValid || viewport.width <= 0 || viewport.height <= 0 || (long)viewport.x + viewport.width > size.width - || (long)viewport.y + viewport.height > size.height)) - { + || (long)viewport.y + viewport.height > size.height) + ) { throw new ArgumentException( "The primary presentation viewport must fit inside the primary presentation surface.", - nameof(primaryPresentationViewport)); + nameof(primaryPresentationViewport) + ); } this.primaryPresentationViewport = primaryPresentationViewport; this.frameIndex = frameIndex; @@ -149,6 +152,7 @@ public RenderRequestProviderContext( /// Gets the active generation's world-content collector. /// public IViewContentCollector viewContent { get; } + /// /// Gets viewport-local input for the primary output. /// @@ -180,7 +184,9 @@ public abstract class RenderRequestProvider : IDisposable public void Dispose() { if (m_disposed) + { return; + } try { Dispose(true); @@ -207,6 +213,5 @@ public void Dispose() /// /// Retirement cannot complete yet; subsequent calls resume this hook with its remaining owned resources. /// - protected virtual void Dispose(bool disposing) { } + protected virtual void Dispose(bool disposing) {} } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs index ad0cf5e1f..4f76fca8a 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs @@ -1,11 +1,11 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -416,4 +416,3 @@ out PersistentTextureHandle resolvedTexture /// void Release(RenderPersistentResourceId id); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs index 2c8183e08..b56b987b0 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs @@ -1,11 +1,11 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -96,11 +96,12 @@ public void DrawSection( ArgumentNullException.ThrowIfNull(commands); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(instanceCount); if ((uint)sectionIndex >= (uint)m_sections.Count) + { throw new ArgumentOutOfRangeException(nameof(sectionIndex)); + } RenderGeometrySection section = m_sections[sectionIndex]; commands.BindVertexBuffer(vertexBuffer); commands.BindIndexBuffer(indexBuffer, section.firstIndex); commands.DrawIndexed(section.indexCount, instanceCount); } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs index 57016556f..104b3ccfd 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs @@ -1,11 +1,11 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -44,4 +44,3 @@ int indexCount /// public int indexCount { get; } } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs index 4d16493b9..d14549937 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs @@ -1,11 +1,11 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -55,14 +55,17 @@ IReadOnlyList bindings this.computePipeline = computePipeline; m_declaredBindings = declaredBindings.ToDictionary( static property => new RenderBindingId(property.id.value), - static property => ToRenderBindingKind(property.bindingKind)); + static property => ToRenderBindingKind(property.bindingKind) + ); m_activeBindings = activeInterface.bindings .Select(static binding => new RenderBindingId(binding.id.value)) .ToHashSet(); - m_bindings = Array.AsReadOnly(bindings.Select(static binding => binding with - { - uniformData = binding.uniformData?.ToArray() - }).ToArray()); + m_bindings = Array.AsReadOnly( + bindings.Select(static binding => binding with + { + uniformData = binding.uniformData?.ToArray() + }).ToArray() + ); } /// @@ -111,15 +114,24 @@ public bool UsesBinding( RenderShaderBindingKind kind ) { if (!binding.isValid) + { throw new ArgumentException("A stable shader binding identifier is required.", nameof(binding)); + } if (!Enum.IsDefined(kind)) + { throw new ArgumentOutOfRangeException(nameof(kind)); + } if (!m_declaredBindings.TryGetValue(binding, out RenderShaderBindingKind declaredKind)) + { throw new ArgumentException($"Shader does not declare binding '{binding.value}'.", nameof(binding)); + } if (declaredKind != kind) + { throw new ArgumentException( $"Shader binding '{binding.value}' is declared as {declaredKind}, not {kind}.", - nameof(kind)); + nameof(kind) + ); + } return m_activeBindings.Contains(binding); } @@ -133,29 +145,38 @@ public void Bind(RenderCommandEncoder commands) { ArgumentNullException.ThrowIfNull(commands); if (graphicsPipeline.isValid) + { commands.BindGraphicsPipeline(graphicsPipeline); + } else if (computePipeline.isValid) + { commands.BindComputePipeline(computePipeline); + } else + { throw new InvalidOperationException("A resolved material pass has no active program."); + } foreach (RenderMaterialBinding binding in m_bindings) { if (binding.kind == RenderMaterialBindingKind.Uniform) + { commands.SetUniform(binding.id, binding.uniformData ?? []); + } else + { commands.BindTexture(binding.id, binding.texture, binding.sampler); + } } } private static RenderShaderBindingKind ToRenderBindingKind(ShaderPropertyBindingKind kind) => kind switch - { - ShaderPropertyBindingKind.Uniform => RenderShaderBindingKind.Uniform, - ShaderPropertyBindingKind.SampledTexture => RenderShaderBindingKind.Texture, - ShaderPropertyBindingKind.StorageTexture => RenderShaderBindingKind.StorageTexture, - ShaderPropertyBindingKind.StorageBuffer => RenderShaderBindingKind.StorageBuffer, - _ => throw new ArgumentOutOfRangeException(nameof(kind)) - }; + { + ShaderPropertyBindingKind.Uniform => RenderShaderBindingKind.Uniform, + ShaderPropertyBindingKind.SampledTexture => RenderShaderBindingKind.Texture, + ShaderPropertyBindingKind.StorageTexture => RenderShaderBindingKind.StorageTexture, + ShaderPropertyBindingKind.StorageBuffer => RenderShaderBindingKind.StorageBuffer, + _ => throw new ArgumentOutOfRangeException(nameof(kind)) + }; } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs index 713a9680c..946c274f2 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs @@ -1,11 +1,11 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -45,4 +45,3 @@ public RenderPersistentResourceId(string value) /// public override string ToString() => value ?? string.Empty; } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs index 8d2739413..37d671d45 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs @@ -1,8 +1,8 @@ -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -44,8 +44,7 @@ internal MaterialBinding(RenderMaterialBinding value) protected static MaterialBinding CreateUniformBinding( RenderBindingId id, ReadOnlySpan data - ) - => new(new RenderMaterialBinding(RenderMaterialBindingKind.Uniform, id, data.ToArray(), default, default)); + ) => new(new RenderMaterialBinding(RenderMaterialBindingKind.Uniform, id, data.ToArray(), default, default)); /// /// Creates a protected sampled-texture binding value. @@ -66,8 +65,7 @@ protected static MaterialBinding CreateTextureBinding( RenderBindingId id, PersistentTextureHandle texture, RenderSamplerState sampler - ) - => new(new RenderMaterialBinding(RenderMaterialBindingKind.Texture, id, null, texture, sampler)); + ) => new(new RenderMaterialBinding(RenderMaterialBindingKind.Texture, id, null, texture, sampler)); /// /// Creates a generation-scoped resolved material pass when no compiled-interface query is required. @@ -93,8 +91,7 @@ protected static RenderMaterialPass CreateMaterialPass( GraphicsPipelineHandle graphicsPipeline, ComputePipelineHandle computePipeline, IReadOnlyList bindings - ) - => CreateMaterialPass(definition, graphicsPipeline, computePipeline, [], new ShaderInterface([]), bindings); + ) => CreateMaterialPass(definition, graphicsPipeline, computePipeline, [], new ShaderInterface([]), bindings); /// /// Creates a generation-scoped resolved material pass. @@ -127,14 +124,14 @@ protected static RenderMaterialPass CreateMaterialPass( IReadOnlyList declaredBindings, ShaderInterface activeInterface, IReadOnlyList bindings - ) - => new( - definition, - graphicsPipeline, - computePipeline, - declaredBindings, - activeInterface, - bindings.Select(static binding => binding.value).ToArray()); + ) => new( + definition, + graphicsPipeline, + computePipeline, + declaredBindings, + activeInterface, + bindings.Select(static binding => binding.value).ToArray() + ); /// /// Creates generation-scoped resolved geometry from persistent buffers and immutable sections. @@ -167,7 +164,5 @@ protected static RenderGeometry CreateGeometry( int vertexCount, int indexCount, IReadOnlyList sections - ) - => new(vertexBuffer, indexBuffer, vertexLayout, vertexCount, indexCount, sections); + ) => new(vertexBuffer, indexBuffer, vertexLayout, vertexCount, indexCount, sections); } - diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs index 865328c42..d2feab991 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs @@ -1,11 +1,11 @@ -using Inno.Core.Diagnostics; -using Inno.Rendering; -using Inno.Rendering.Assets; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Diagnostics; +using Inno.Rendering; +using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -37,7 +37,9 @@ ReadOnlySpan data ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); ArgumentOutOfRangeException.ThrowIfNegative(arrayLayer); if (data.IsEmpty) + { throw new ArgumentException("A texture subresource upload cannot be empty.", nameof(data)); + } this.mipLevel = mipLevel; this.arrayLayer = arrayLayer; m_data = data.ToArray(); @@ -58,4 +60,3 @@ ReadOnlySpan data /// public ReadOnlyMemory data => m_data; } - diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs index 9f1f8148a..b65013745 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs @@ -14,6 +14,7 @@ public sealed class ShaderConstantNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.constant"; + /// /// Gets a ports required by the implemented contract. /// @@ -25,6 +26,7 @@ public sealed class ShaderConstantNodeCompiler : IShaderNodeCompiler /// public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => [new("value", ShaderSourceType.Atomic(context.Read("type", "float")), GraphPortDirection.Output)]; + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -58,6 +60,7 @@ public sealed class ShaderBinaryNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.binary"; + /// /// Gets a ports required by the implemented contract. /// @@ -71,9 +74,17 @@ public IReadOnlyList GetPorts(ShaderNodeDescriptionContext conte { ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float")); ShaderIrOperation operation = Operation(context); - return [new("left", type, GraphPortDirection.Input), new("right", type, GraphPortDirection.Input), - new("value", operation is ShaderIrOperation.Equal or ShaderIrOperation.LessThan ? ShaderSourceType.Atomic("bool") : type, GraphPortDirection.Output)]; + return [ + new("left", type, GraphPortDirection.Input), + new("right", type, GraphPortDirection.Input), + new( + "value", + operation is ShaderIrOperation.Equal or ShaderIrOperation.LessThan ? ShaderSourceType.Atomic("bool") : type, + GraphPortDirection.Output + ) + ]; } + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -84,17 +95,24 @@ public IReadOnlyList GetPorts(ShaderNodeDescriptionContext conte /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary { ["value"] = context.builder.Binary(Operation(context.description), context.Input("left"), context.Input("right")) }; + => new Dictionary + { + ["value"] = context.builder.Binary(Operation(context.description), context.Input("left"), context.Input("right")) + }; private static ShaderIrOperation Operation(ShaderNodeDescriptionContext context) => context.Read("operation", "add") switch - { - "add" => ShaderIrOperation.Add, "subtract" => ShaderIrOperation.Subtract, - "multiply" => ShaderIrOperation.Multiply, "divide" => ShaderIrOperation.Divide, - "minimum" => ShaderIrOperation.Minimum, "maximum" => ShaderIrOperation.Maximum, - "equal" => ShaderIrOperation.Equal, "less-than" => ShaderIrOperation.LessThan, - _ => throw new InvalidOperationException("Unknown binary shader operation.") - }; + { + "add" => ShaderIrOperation.Add, + "subtract" => ShaderIrOperation.Subtract, + "multiply" => ShaderIrOperation.Multiply, + "divide" => ShaderIrOperation.Divide, + "minimum" => ShaderIrOperation.Minimum, + "maximum" => ShaderIrOperation.Maximum, + "equal" => ShaderIrOperation.Equal, + "less-than" => ShaderIrOperation.LessThan, + _ => throw new InvalidOperationException("Unknown binary shader operation.") + }; } /// @@ -106,6 +124,7 @@ public sealed class ShaderConstructNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.construct"; + /// /// Gets a ports required by the implemented contract. /// @@ -118,9 +137,12 @@ public sealed class ShaderConstructNodeCompiler : IShaderNodeCompiler public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) { (ShaderSourceType type, ShaderSourceType scalar, int count) = Shape(context); - return Enumerable.Range(0, count).Select(index => new ShaderNodePort("component." + index, scalar, GraphPortDirection.Input)) - .Append(new("value", type, GraphPortDirection.Output)).ToArray(); + return Enumerable.Range(0, count) + .Select(index => new ShaderNodePort("component." + index, scalar, GraphPortDirection.Input)) + .Append(new("value", type, GraphPortDirection.Output)) + .ToArray(); } + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -134,7 +156,12 @@ public IReadOnlyDictionary Lower(ShaderNodeLoweringContex { (ShaderSourceType type, _, int count) = Shape(context.description); return new Dictionary - { ["value"] = context.builder.Construct(type, Enumerable.Range(0, count).Select(index => context.Input("component." + index)).ToArray()) }; + { + ["value"] = context.builder.Construct( + type, + Enumerable.Range(0, count).Select(index => context.Input("component." + index)).ToArray() + ) + }; } private static (ShaderSourceType type, ShaderSourceType scalar, int count) Shape(ShaderNodeDescriptionContext context) @@ -143,10 +170,18 @@ private static (ShaderSourceType type, ShaderSourceType scalar, int count) Shape foreach (string scalar in new[] { "float", "int", "uint", "bool" }) { if (id.Length == scalar.Length + 1 && id.StartsWith(scalar, StringComparison.Ordinal) && id[^1] is >= '2' and <= '4') + { return (ShaderSourceType.Atomic(id), ShaderSourceType.Atomic(scalar), id[^1] - '0'); + } } - if (id.Length == 8 && id.StartsWith("float", StringComparison.Ordinal) && id[5] is >= '2' and <= '4' && id[6] == 'x' && id[7] is >= '2' and <= '4') + if (id.Length == 8 + && id.StartsWith("float", StringComparison.Ordinal) + && id[5] is >= '2' and <= '4' + && id[6] == 'x' + && id[7] is >= '2' and <= '4' + ) { return (ShaderSourceType.Atomic(id), ShaderSourceType.Atomic("float"), (id[5] - '0') * (id[7] - '0')); + } throw new InvalidOperationException("Construction requires a numeric vector or floating-point matrix."); } } @@ -160,6 +195,7 @@ public sealed class ShaderStageInputNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.stage-input"; + /// /// Gets a ports required by the implemented contract. /// @@ -171,6 +207,7 @@ public sealed class ShaderStageInputNodeCompiler : IShaderNodeCompiler /// public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => [new("value", RequireBinding(context).type, GraphPortDirection.Output)]; + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -185,6 +222,7 @@ public IReadOnlyDictionary Lower(ShaderNodeLoweringContex ShaderIrStageInput input = RequireBinding(context.description); return new Dictionary { ["value"] = context.builder.Input(input.id, input.type) }; } + private static ShaderIrStageInput RequireBinding(ShaderNodeDescriptionContext context) => context.stageInput ?? throw new InvalidOperationException("The target has not resolved this stage input binding."); } @@ -198,6 +236,7 @@ public sealed class ShaderSelectNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.select"; + /// /// Gets a ports required by the implemented contract. /// @@ -210,9 +249,14 @@ public sealed class ShaderSelectNodeCompiler : IShaderNodeCompiler public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) { ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float")); - return [new("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), new("true", type, GraphPortDirection.Input), - new("false", type, GraphPortDirection.Input), new("value", type, GraphPortDirection.Output)]; + return [ + new("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), + new("true", type, GraphPortDirection.Input), + new("false", type, GraphPortDirection.Input), + new("value", type, GraphPortDirection.Output) + ]; } + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -223,7 +267,10 @@ public IReadOnlyList GetPorts(ShaderNodeDescriptionContext conte /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary { ["value"] = context.builder.Select(context.Input("condition"), context.Input("true"), context.Input("false")) }; + => new Dictionary + { + ["value"] = context.builder.Select(context.Input("condition"), context.Input("true"), context.Input("false")) + }; } /// @@ -235,6 +282,7 @@ public sealed class ShaderSourceNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.source"; + /// /// Gets a ports required by the implemented contract. /// @@ -251,12 +299,18 @@ public IReadOnlyList GetPorts(ShaderNodeDescriptionContext conte foreach (ShaderSourceParameter parameter in function.parameters) { if (parameter.direction != ShaderSourceParameterDirection.Output) + { Add("input." + parameter.name, parameter.type, GraphPortDirection.Input); + } if (parameter.direction != ShaderSourceParameterDirection.Input) + { Add("output." + parameter.name, parameter.type, GraphPortDirection.Output); + } } if (function.returnType.id != "void") + { Add("return", function.returnType, GraphPortDirection.Output); + } return ports.AsReadOnly(); void Add( string name, @@ -265,9 +319,12 @@ GraphPortDirection direction ) { ports.Add(new(name, type, direction, required: false)); foreach (ShaderSourceField field in type.fields) + { Add(name + "." + field.name, field.type, direction); + } } } + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -282,12 +339,18 @@ public IReadOnlyDictionary Lower(ShaderNodeLoweringContex ShaderSourceModuleAnalysis module = RequireModule(context.description); var arguments = new Dictionary(StringComparer.Ordinal); foreach (ShaderSourceParameter parameter in module.function!.parameters) + { if (parameter.direction != ShaderSourceParameterDirection.Output) + { arguments.Add(parameter.name, Resolve("input." + parameter.name, parameter.type)); + } + } IReadOnlyDictionary values = context.builder.Call(module, context.description.implementationId, arguments); var outputs = new Dictionary(StringComparer.Ordinal); foreach ((string name, ShaderIrValue value) in values) + { Add(name, value); + } return outputs; ShaderIrValue Resolve( @@ -297,11 +360,17 @@ ShaderSourceType type if (context.inputs.TryGetValue(name, out ShaderIrValue? aggregate)) { if (context.inputs.Keys.Any(key => key.StartsWith(name + ".", StringComparison.Ordinal))) - throw new InvalidOperationException($"'{name}' connects both its aggregate and a member; choose one representation explicitly."); + { + throw new InvalidOperationException( + $"'{name}' connects both its aggregate and a member; choose one representation explicitly." + ); + } return aggregate; } if (type.fields.Count == 0) + { return context.Input(name); + } return context.builder.Construct(type, type.fields.Select(field => Resolve(name + "." + field.name, field.type)).ToArray()); } @@ -311,7 +380,9 @@ ShaderIrValue value ) { outputs.Add(name, value); for (int index = 0; index < value.type.fields.Count; index++) + { Add(name + "." + value.type.fields[index].name, context.builder.Extract(value, index)); + } } } @@ -319,9 +390,18 @@ private static ShaderSourceModuleAnalysis RequireModule(ShaderNodeDescriptionCon { ShaderSourceModuleAnalysis? module = context.sourceModule; if (module is null) - throw new InvalidOperationException("The source module is unassigned or unavailable; its stored reference and connections must remain intact."); + { + throw new InvalidOperationException( + "The source module is unassigned or unavailable; its stored reference and connections must remain intact." + ); + } if (!module.succeeded) - throw new InvalidOperationException("The source module has no valid common interface: " + string.Join("; ", module.diagnostics.Select(static value => value.message))); + { + throw new InvalidOperationException( + "The source module has no valid common interface: " + + string.Join("; ", module.diagnostics.Select(static value => value.message)) + ); + } return module; } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs index f09cac39f..61c7d7b16 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs @@ -43,26 +43,39 @@ public ShaderGraphLoweringRequest( ArgumentNullException.ThrowIfNull(outputs); ArgumentException.ThrowIfNullOrWhiteSpace(implementationId); foreach (string name in outputs.Keys) + { ArgumentException.ThrowIfNullOrWhiteSpace(name); + } this.graph = graph.Clone(); - this.outputs = new ReadOnlyDictionary(new Dictionary(outputs, StringComparer.Ordinal)); + this.outputs = new ReadOnlyDictionary( + new Dictionary(outputs, StringComparer.Ordinal) + ); this.implementationId = implementationId; - this.sourceModules = new ReadOnlyDictionary(new Dictionary(sourceModules ?? new Dictionary())); - this.stageInputs = new ReadOnlyDictionary(new Dictionary(stageInputs ?? new Dictionary())); + this.sourceModules = new ReadOnlyDictionary( + new Dictionary( + sourceModules ?? new Dictionary() + ) + ); + this.stageInputs = new ReadOnlyDictionary( + new Dictionary(stageInputs ?? new Dictionary()) + ); } /// /// Gets named region outputs by stable graph endpoint. /// public IReadOnlyDictionary outputs { get; } + /// /// Gets the exact implementation key selected by the target. /// public string implementationId { get; } + /// /// Gets frozen source modules, including unavailable/failed modules for accurate diagnostics. /// public IReadOnlyDictionary sourceModules { get; } + /// /// Gets target-assigned input descriptors; they contain no native expressions. /// @@ -107,14 +120,17 @@ IEnumerable diagnostics this.block = block; this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); } + /// /// Gets the immutable typed region, or null on failure. /// public ShaderIrBlock? block { get; } + /// /// Gets located graph diagnostics, including missing definitions and stale source ports. /// public IReadOnlyList diagnostics { get; } + /// /// Gets whether lowering produced a complete region without errors; native compilation is a separate gate. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs index b00259c1a..d28dd60d3 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs @@ -38,6 +38,7 @@ public interface IShaderNodeCompiler /// Gets the exact graph node definition identity implemented by this compiler. /// string definitionId { get; } + /// /// Describes ports for the current neutral properties and resolved source/target inputs. /// @@ -48,6 +49,7 @@ public interface IShaderNodeCompiler /// Complete typed ports; duplicate identities are invalid. /// IReadOnlyList GetPorts(ShaderNodeDescriptionContext context); + /// /// Lowers the node into the supplied typed builder without generating source strings. /// @@ -89,18 +91,22 @@ internal ShaderNodeDescriptionContext( /// Gets the node's stable identity, never its editor runtime handle. /// public GraphNodeId nodeId => m_node.id; + /// /// Gets the node definition's stable identity. /// public string definitionId => m_node.definitionId; + /// /// Gets a frozen module resolved by the asset owner; null means unassigned or unavailable. /// public ShaderSourceModuleAnalysis? sourceModule { get; } + /// /// Gets the exact implementation key chosen by the target. /// public string implementationId { get; } + /// /// Gets the target-assigned stage input for this node, when applicable. /// @@ -127,8 +133,8 @@ T defaultValue ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); return m_node.TryGetValue(id, out GraphSerializedValue? value) - ? m_serialization.Decode(value!.data.Span, reader => reader.Read("value"), m_context) - : defaultValue; + ? m_serialization.Decode(value!.data.Span, reader => reader.Read("value"), m_context) + : defaultValue; } } @@ -151,14 +157,17 @@ IReadOnlyDictionary inputs /// Gets the invocation-scoped node description. /// public ShaderNodeDescriptionContext description { get; } + /// /// Gets the builder shared by nodes in this typed region. /// public ShaderIrBuilder builder { get; } + /// /// Gets connected values keyed by semantic input port identity, never connection order. /// public IReadOnlyDictionary inputs { get; } + /// /// Requires one connected input without implicit defaults or positional rebinding. /// @@ -169,5 +178,7 @@ IReadOnlyDictionary inputs /// The connected typed value. /// public ShaderIrValue Input(string id) - => inputs.TryGetValue(id, out ShaderIrValue? value) ? value : throw new InvalidOperationException($"Input '{id}' is not connected."); + => inputs.TryGetValue(id, out ShaderIrValue? value) + ? value + : throw new InvalidOperationException($"Input '{id}' is not connected."); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs index 42dea3300..5bd7f80d3 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs @@ -32,7 +32,9 @@ public ShaderNodeCompilerCatalog(IEnumerable compilers) ArgumentNullException.ThrowIfNull(compiler); ArgumentException.ThrowIfNullOrWhiteSpace(compiler.definitionId); if (!m_compilers.TryAdd(compiler.definitionId, compiler)) + { throw new ArgumentException($"Duplicate shader node compiler '{compiler.definitionId}'.", nameof(compilers)); + } } providers = Array.AsReadOnly(m_compilers.Values.ToArray()); definitionIds = Array.AsReadOnly(m_compilers.Keys.Order(StringComparer.Ordinal).ToArray()); @@ -77,7 +79,9 @@ public IReadOnlyList DescribePorts( ) { ArgumentNullException.ThrowIfNull(node); if (!m_compilers.TryGetValue(node.definitionId, out IShaderNodeCompiler? compiler)) + { throw new InvalidOperationException($"Node compiler '{node.definitionId}' is unavailable."); + } return Array.AsReadOnly(compiler.GetPorts(new(node, serialization, context, source, implementationId, input)).ToArray()); } @@ -138,15 +142,25 @@ public ShaderGraphLoweringResult Lower( nodePorts.Add(node.id, describedPorts); foreach (ShaderNodePort port in describedPorts) { - if (port is null || string.IsNullOrWhiteSpace(port.id) || port.type is null || port.type.id == "void" || !Enum.IsDefined(port.direction)) + if (port is null + || string.IsNullOrWhiteSpace(port.id) + || port.type is null + || port.type.id == "void" + || !Enum.IsDefined(port.direction) + ) { throw new InvalidOperationException($"Compiler '{node.definitionId}' returned an invalid port."); + } if (!ports.TryAdd(new(node.id, new(port.id)), port)) + { throw new InvalidOperationException($"Compiler '{node.definitionId}' returned duplicate port '{port.id}'."); + } } } activeNode = null; if (diagnostics.Count != 0) + { return new(null, diagnostics); + } var connections = new Dictionary(); var inputDefaults = new Dictionary(); @@ -157,22 +171,42 @@ public ShaderGraphLoweringResult Lower( { if (!ports.TryGetValue(edge.input, out ShaderNodePort? input) || input.direction != GraphPortDirection.Input) { - Error("SHADER_GRAPH_PORT_MISSING", $"Connection '{edge.id}' has an unavailable input; it remains stored for explicit repair.", edge.input.nodeId, edge.input.portId.value); + Error( + "SHADER_GRAPH_PORT_MISSING", + $"Connection '{edge.id}' has an unavailable input; it remains stored for explicit repair.", + edge.input.nodeId, + edge.input.portId.value + ); continue; } if (!ports.TryGetValue(edge.output, out ShaderNodePort? output) || output.direction != GraphPortDirection.Output) { - Error("SHADER_GRAPH_PORT_MISSING", $"Connection '{edge.id}' has an unavailable output; it remains stored for explicit repair.", edge.output.nodeId, edge.output.portId.value); + Error( + "SHADER_GRAPH_PORT_MISSING", + $"Connection '{edge.id}' has an unavailable output; it remains stored for explicit repair.", + edge.output.nodeId, + edge.output.portId.value + ); continue; } if (!input.type.IsEquivalentTo(output.type)) { - Error("SHADER_GRAPH_TYPE", $"Connection '{edge.id}' changed type or aggregate layout; implicit conversion and positional rebinding are forbidden.", edge.input.nodeId, edge.input.portId.value); + Error( + "SHADER_GRAPH_TYPE", + $"Connection '{edge.id}' changed type or aggregate layout; implicit conversion and positional rebinding are forbidden.", + edge.input.nodeId, + edge.input.portId.value + ); continue; } if (!connections.TryAdd(edge.input, edge.output)) { - Error("SHADER_GRAPH_INPUT_CAPACITY", "A value input has more than one connection.", edge.input.nodeId, edge.input.portId.value); + Error( + "SHADER_GRAPH_INPUT_CAPACITY", + "A value input has more than one connection.", + edge.input.nodeId, + edge.input.portId.value + ); continue; } int target = nodeIndexes[edge.input.nodeId]; @@ -183,14 +217,17 @@ public ShaderGraphLoweringResult Lower( foreach ((GraphEndpoint endpoint, ShaderNodePort port) in ports) { if (port.direction != GraphPortDirection.Input || connections.ContainsKey(endpoint)) + { continue; + } if (port.required) { Error( "SHADER_GRAPH_INPUT_REQUIRED", $"Required input '{endpoint.portId.value}' on node '{endpoint.nodeId.value}' is not connected. Connect a Constant or another compatible graph output.", endpoint.nodeId, - endpoint.portId.value); + endpoint.portId.value + ); continue; } try @@ -203,15 +240,27 @@ public ShaderGraphLoweringResult Lower( "SHADER_GRAPH_OPTIONAL_TYPE", $"Optional input '{endpoint.portId.value}' cannot represent an automatic zero value and must be required instead.", endpoint.nodeId, - endpoint.portId.value); + endpoint.portId.value + ); } } activeNode = null; foreach ((string name, GraphEndpoint endpoint) in request.outputs) + { if (!ports.TryGetValue(endpoint, out ShaderNodePort? port) || port.direction != GraphPortDirection.Output) - Error("SHADER_GRAPH_OUTPUT_MISSING", $"Region output '{name}' points to an unavailable output port.", endpoint.nodeId, endpoint.portId.value); + { + Error( + "SHADER_GRAPH_OUTPUT_MISSING", + $"Region output '{name}' points to an unavailable output port.", + endpoint.nodeId, + endpoint.portId.value + ); + } + } if (diagnostics.Count != 0) + { return new(null, diagnostics); + } var ready = new SortedSet(Enumerable.Range(0, nodes.Count).Where(index => incoming[index] == 0)); var ordered = new List(); @@ -221,12 +270,19 @@ public ShaderGraphLoweringResult Lower( ready.Remove(index); ordered.Add(index); foreach (int next in following[index]) + { if (--incoming[next] == 0) + { ready.Add(next); + } + } } if (ordered.Count != nodes.Count) { - Error("SHADER_GRAPH_CYCLE", "Value connections contain a cycle; structured control flow must be represented by a control-flow operation."); + Error( + "SHADER_GRAPH_CYCLE", + "Value connections contain a cycle; structured control flow must be represented by a control-flow operation." + ); return new(null, diagnostics); } var builder = new ShaderIrBuilder(); @@ -238,27 +294,45 @@ public ShaderGraphLoweringResult Lower( activeNode = node.id; var inputs = new Dictionary(StringComparer.Ordinal); foreach ((string port, GraphEndpoint source) in nodeConnections[node.id]) + { inputs.Add(port, values[source]); + } foreach (ShaderNodePort port in nodePorts[node.id]) + { if (inputDefaults.TryGetValue(new(node.id, new(port.id)), out ShaderGraphLiteral? literal)) + { inputs.Add(port.id, literal.Emit(builder, port.type)); - IReadOnlyDictionary outputs = m_compilers[node.definitionId].Lower(new(descriptions[node.id], builder, inputs)); + } + } + IReadOnlyDictionary outputs = m_compilers[node.definitionId].Lower( + new(descriptions[node.id], builder, inputs) + ); ShaderNodePort[] expected = nodePorts[node.id].Where(static port => port.direction == GraphPortDirection.Output).ToArray(); if (outputs.Count != expected.Length) + { throw new InvalidOperationException("A node compiler did not return exactly its declared outputs."); + } foreach (ShaderNodePort port in expected) { if (!outputs.TryGetValue(port.id, out ShaderIrValue? value) || !port.type.IsEquivalentTo(value.type)) + { throw new InvalidOperationException($"Node output '{port.id}' is missing or has an incompatible type."); + } builder.RequireOwned(value); values.Add(new(node.id, new(port.id)), value); } } cancellationToken.ThrowIfCancellationRequested(); - return new(builder.Build(request.outputs.ToDictionary(static pair => pair.Key, pair => values[pair.Value], StringComparer.Ordinal)), diagnostics); + return new( + builder.Build(request.outputs.ToDictionary(static pair => pair.Key, pair => values[pair.Value], StringComparer.Ordinal)), + diagnostics + ); } - catch (Exception failure) when (failure is ArgumentException or InvalidOperationException or InvalidDataException or KeyNotFoundException - or FormatException or NotSupportedException && RetirementPendingException.Find(failure) is null) + catch (Exception failure) when (failure is ArgumentException + or InvalidOperationException + or InvalidDataException + or KeyNotFoundException + or FormatException or NotSupportedException && RetirementPendingException.Find(failure) is null) { Error("SHADER_NODE_LOWERING", failure.Message, activeNode); return new(null, diagnostics); @@ -269,7 +343,6 @@ void Error( string message, GraphNodeId? nodeId = null, string? portId = null - ) - => diagnostics.Add(new(code, DiagnosticSeverity.Error, message, nodeId, portId)); + ) => diagnostics.Add(new(code, DiagnosticSeverity.Error, message, nodeId, portId)); } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs index be3f246a2..0e0930d5e 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Linq; using System.Threading; -using Inno.Core.Serialization; using Inno.Core.Graphs; +using Inno.Core.Serialization; using Inno.Extensibility.Types; namespace Inno.Rendering.Shaders; @@ -21,7 +21,8 @@ public sealed class ShaderNodeCompilerRegistry : TypeRegistry /// Owner catalog, which must outlive this registry. /// - public ShaderNodeCompilerRegistry(TypeCatalog types) : base(types) => m_types = types; + public ShaderNodeCompilerRegistry(TypeCatalog types) + : base(types) => m_types = types; /// /// Gets stable compiler identities without exposing provider instances. @@ -112,8 +113,11 @@ protected override ShaderNodeCompilerCatalog Build(TypeCacheSnapshot types) { var providers = new List(); foreach (Type type in types.GetTypesImplementing() - .Select(reference => reference.Resolve(types)).OrderBy(static type => type.FullName, StringComparer.Ordinal)) + .Select(reference => reference.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { providers.Add(CreateExtension(type)); + } return new(providers); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderRerouteNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderRerouteNodeCompiler.cs index 4175bf9d4..9250d0a20 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderRerouteNodeCompiler.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderRerouteNodeCompiler.cs @@ -12,6 +12,7 @@ public sealed class ShaderRerouteNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.reroute"; + /// /// Gets a ports required by the implemented contract. /// @@ -26,6 +27,7 @@ public IReadOnlyList GetPorts(ShaderNodeDescriptionContext conte ShaderSourceType type = context.Read("valueType", new ShaderGraphType { id = "float" }).CreateType(); return [new("input", type, GraphPortDirection.Input, required: false), new("value", type, GraphPortDirection.Output)]; } + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs index cc47c4ec5..4f58f7741 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs @@ -7,9 +7,18 @@ namespace Inno.Rendering.Shaders; internal static class StorageNodePorts { internal static ShaderSourceType Resource(ShaderNodeDescriptionContext context) - => context.Read("resource", new ShaderGraphType { isStorage = true, storageElement = new() { id = "float4" }, access = RenderStorageAccess.ReadWrite }).CreateType(); + => context + .Read( + "resource", + new ShaderGraphType { isStorage = true, storageElement = new() { id = "float4" }, access = RenderStorageAccess.ReadWrite } + ) + .CreateType(); + internal static ShaderSourceType Coordinate(ShaderStorageType storage) - => ShaderSourceType.Atomic(!storage.isImage ? "uint" : storage.array || storage.dimension == RenderTextureDimension.Texture3D ? "int3" : "int2"); + => ShaderSourceType.Atomic( + !storage.isImage ? "uint" : storage.array || storage.dimension == RenderTextureDimension.Texture3D ? "int3" : "int2" + ); + internal static IReadOnlyList Describe( ShaderNodeDescriptionContext context, bool write, @@ -25,9 +34,13 @@ bool atomic new("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output) }; if (write) + { ports.Add(new("value", storage.valueType, GraphPortDirection.Input)); + } if (!write || atomic) + { ports.Add(new(atomic ? "previous" : "value", storage.valueType, GraphPortDirection.Output)); + } return ports; } } @@ -38,6 +51,7 @@ internal sealed class ShaderStorageLoadNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.storage-load"; + /// /// Retrieves the current ports from authoritative state. /// @@ -48,6 +62,7 @@ internal sealed class ShaderStorageLoadNodeCompiler : IShaderNodeCompiler /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, false, false); + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -58,11 +73,11 @@ internal sealed class ShaderStorageLoadNodeCompiler : IShaderNodeCompiler /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary - { - ["value"] = context.builder.LoadStorage(context.Input("resource"), context.Input("coordinate")), - ["then"] = context.builder.Constant(true) - }; + => new Dictionary +{ + ["value"] = context.builder.LoadStorage(context.Input("resource"), context.Input("coordinate")), + ["then"] = context.builder.Constant(true) +}; } internal sealed class ShaderStorageStoreNodeCompiler : IShaderNodeCompiler @@ -71,6 +86,7 @@ internal sealed class ShaderStorageStoreNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.storage-store"; + /// /// Retrieves the current ports from authoritative state. /// @@ -81,6 +97,7 @@ internal sealed class ShaderStorageStoreNodeCompiler : IShaderNodeCompiler /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, true, false); + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -103,6 +120,7 @@ internal sealed class ShaderStorageAtomicAddNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.storage-atomic-add"; + /// /// Retrieves the current ports from authoritative state. /// @@ -113,6 +131,7 @@ internal sealed class ShaderStorageAtomicAddNodeCompiler : IShaderNodeCompiler /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, true, true); + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -123,11 +142,11 @@ internal sealed class ShaderStorageAtomicAddNodeCompiler : IShaderNodeCompiler /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary - { - ["previous"] = context.builder.AtomicAddStorage(context.Input("resource"), context.Input("coordinate"), context.Input("value")), - ["then"] = context.builder.Constant(true) - }; + => new Dictionary +{ + ["previous"] = context.builder.AtomicAddStorage(context.Input("resource"), context.Input("coordinate"), context.Input("value")), + ["then"] = context.builder.Constant(true) +}; } internal sealed class ShaderDiscardNodeCompiler : IShaderNodeCompiler @@ -136,6 +155,7 @@ internal sealed class ShaderDiscardNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.discard"; + /// /// Retrieves the current ports from authoritative state. /// @@ -146,9 +166,12 @@ internal sealed class ShaderDiscardNodeCompiler : IShaderNodeCompiler /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => [new("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), - new("after", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input, false), - new("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output)]; + => [ + new("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), + new("after", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input, false), + new("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output) + ]; + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderValueNodeCompilers.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderValueNodeCompilers.cs index 691299c71..21501f1d4 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderValueNodeCompilers.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderValueNodeCompilers.cs @@ -13,6 +13,7 @@ public sealed class ShaderExtractNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.extract"; + /// /// Gets a ports required by the implemented contract. /// @@ -29,6 +30,7 @@ public IReadOnlyList GetPorts(ShaderNodeDescriptionContext conte ShaderIrValue member = builder.Extract(builder.Input("input", type), context.Read("index", 0)); return [new("input", type, GraphPortDirection.Input), new("value", member.type, GraphPortDirection.Output)]; } + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -39,7 +41,10 @@ public IReadOnlyList GetPorts(ShaderNodeDescriptionContext conte /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary { ["value"] = context.builder.Extract(context.Input("input"), context.description.Read("index", 0)) }; + => new Dictionary + { + ["value"] = context.builder.Extract(context.Input("input"), context.description.Read("index", 0)) + }; } /// @@ -51,6 +56,7 @@ public sealed class ShaderSampleNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => "inno.shader.sample"; + /// /// Gets a ports required by the implemented contract. /// @@ -63,13 +69,25 @@ public sealed class ShaderSampleNodeCompiler : IShaderNodeCompiler public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) { string type = context.Read("type", "sampled-texture2d"); - string coordinate = type switch { "sampled-texture2d" => "float2", "sampled-texture2d-array" or "sampled-texture3d" or "sampled-texture-cube" => "float3", _ => throw new InvalidOperationException("Unknown sampled texture type.") }; - var ports = new List { new("texture", ShaderSourceType.Atomic(type), GraphPortDirection.Input), new("coordinate", ShaderSourceType.Atomic(coordinate), GraphPortDirection.Input) }; + string coordinate = type switch + { + "sampled-texture2d" => "float2", + "sampled-texture2d-array" or "sampled-texture3d" or "sampled-texture-cube" => "float3", + _ => throw new InvalidOperationException("Unknown sampled texture type.") + }; + var ports = new List + { + new("texture", ShaderSourceType.Atomic(type), GraphPortDirection.Input), + new("coordinate", ShaderSourceType.Atomic(coordinate), GraphPortDirection.Input) + }; if (context.Read("explicitLevel", false)) + { ports.Add(new("level", ShaderSourceType.Atomic("float"), GraphPortDirection.Input)); + } ports.Add(new("value", ShaderSourceType.Atomic("float4"), GraphPortDirection.Output)); return ports; } + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -80,7 +98,10 @@ public IReadOnlyList GetPorts(ShaderNodeDescriptionContext conte /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary { ["value"] = context.description.Read("explicitLevel", false) - ? context.builder.SampleLevel(context.Input("texture"), context.Input("coordinate"), context.Input("level")) - : context.builder.Sample(context.Input("texture"), context.Input("coordinate")) }; + => new Dictionary + { + ["value"] = context.description.Read("explicitLevel", false) + ? context.builder.SampleLevel(context.Input("texture"), context.Input("coordinate"), context.Input("level")) + : context.builder.Sample(context.Input("texture"), context.Input("coordinate")) + }; } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs index abe887b38..b0be3f145 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs @@ -43,39 +43,74 @@ SerializationContext context ArgumentNullException.ThrowIfNull(nodeIds); HashSet removed = [.. nodeIds]; foreach (GraphNodeId id in removed) + { if (graph.FindNode(id) is null) + { throw new ArgumentException("A selected shader node is missing.", nameof(nodeIds)); + } + } GraphDocument candidate = graph.Clone(); - HashSet stages = graph.nodes.Where(node => removed.Contains(node.id) && node.definitionId == ShaderGraphDocument.outputDefinitionId) - .Select(static node => node.id.value).ToHashSet(StringComparer.Ordinal); + HashSet stages = graph.nodes + .Where(node => removed.Contains(node.id) && node.definitionId == ShaderGraphDocument.outputDefinitionId) + .Select(static node => node.id.value) + .ToHashSet(StringComparer.Ordinal); foreach (GraphNodeRecord node in graph.nodes) + { if (stages.Contains(ShaderGraphDocument.Read(node, "stage", "", serialization, context))) + { removed.Add(node.id); + } + } ShaderGraphPassProgram[] programs = graph.metadata.ContainsKey(ShaderGraphPrograms.bindingsKey) - ? ShaderGraphPrograms.Read(graph, serialization, context) : []; + ? ShaderGraphPrograms.Read(graph, serialization, context) + : []; HashSet affectedPasses = programs.Where(program => program.stages.Any(stages.Contains)) - .Select(static program => program.pass).ToHashSet(StringComparer.Ordinal); + .Select(static program => program.pass) + .ToHashSet(StringComparer.Ordinal); ShaderGraphPassProgram[] retainedPrograms = programs.Where(program => !affectedPasses.Contains(program.pass)).ToArray(); HashSet retainedStages = retainedPrograms.SelectMany(static program => program.stages).ToHashSet(StringComparer.Ordinal); - foreach (string stage in programs.Where(program => affectedPasses.Contains(program.pass)).SelectMany(static program => program.stages)) + foreach (string stage in programs + .Where(program => affectedPasses.Contains(program.pass)) + .SelectMany(static program => program.stages) + ) { if (!retainedStages.Contains(stage)) + { stages.Add(stage); + } + } foreach (GraphNodeRecord node in graph.nodes) + { if (stages.Contains(node.id.value) || stages.Contains(ShaderGraphDocument.Read(node, "stage", "", serialization, context))) + { removed.Add(node.id); + } + } HashSet affectedBindings = []; - foreach (GraphNodeRecord node in graph.nodes.Where(node => removed.Contains(node.id) && node.definitionId == "inno.shader.stage-input")) - { - ShaderGraphInputSettings input = ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context); + foreach (GraphNodeRecord node in graph.nodes.Where( + node => removed.Contains(node.id) && node.definitionId == "inno.shader.stage-input" + )) { + ShaderGraphInputSettings input = ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphInputSettings(), + serialization, + context + ); if (IsBinding(input)) + { affectedBindings.Add(input.id); + } affectedBindings.Add(ShaderGraphDocument.Read(node, "bindingIdentity", "", serialization, context)); } foreach (GraphNodeId id in removed) + { candidate.RemoveNode(id); + } if (!candidate.metadata.ContainsKey(ShaderGraphDocument.definitionKey)) + { return candidate; + } ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(candidate, serialization, context); ShaderGraphPrograms.Write(candidate, retainedPrograms, serialization, context); definition.passes = definition.passes.Where(pass => !affectedPasses.Contains(pass.name)).ToArray(); @@ -88,23 +123,42 @@ SerializationContext context var remainingBindings = new Dictionary(StringComparer.Ordinal); foreach (GraphNodeRecord node in candidate.nodes.Where(static node => node.definitionId == "inno.shader.stage-input")) { - ShaderGraphInputSettings input = ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context); - string id = string.IsNullOrWhiteSpace(input.id) ? ShaderGraphDocument.Read(node, "bindingIdentity", "", serialization, context) : input.id; + ShaderGraphInputSettings input = ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphInputSettings(), + serialization, + context + ); + string id = string.IsNullOrWhiteSpace(input.id) + ? ShaderGraphDocument.Read(node, "bindingIdentity", "", serialization, context) + : input.id; if (!IsBinding(input) || !affectedBindings.Contains(id)) + { continue; + } string stageId = ShaderGraphDocument.Read(node, "stage", "", serialization, context); GraphNodeRecord? output = string.IsNullOrWhiteSpace(stageId) ? null : candidate.FindNode(new(stageId)); - ShaderStage stage = output is null ? ShaderStage.None : ShaderGraphDocument.Read(output, "settings", new ShaderGraphStageSettings(), serialization, context).stage; + ShaderStage stage = output is null + ? ShaderStage.None + : ShaderGraphDocument.Read(output, "settings", new ShaderGraphStageSettings(), serialization, context).stage; remainingBindings[id] = remainingBindings.GetValueOrDefault(id) | stage; } - definition.properties = definition.properties.Where(property => !affectedBindings.Contains(property.id.value) || remainingBindings.ContainsKey(property.id.value)) + definition.properties = definition.properties + .Where(property => !affectedBindings.Contains(property.id.value) || remainingBindings.ContainsKey(property.id.value)) .Select(property => { if (remainingBindings.TryGetValue(property.id.value, out ShaderStage stagesUsed)) + { property.stages = stagesUsed; + } return property; - }).ToArray(); - candidate.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context)); + }) + .ToArray(); + candidate.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context) + ); return candidate; } @@ -142,60 +196,111 @@ SerializationContext context ArgumentNullException.ThrowIfNull(graph); ArgumentNullException.ThrowIfNull(settings); GraphDocument candidate = graph.Clone(); - GraphNodeRecord node = candidate.FindNode(nodeId) ?? throw new ArgumentException("The stage input node is missing.", nameof(nodeId)); + GraphNodeRecord node = candidate.FindNode(nodeId) + ?? throw new ArgumentException("The stage input node is missing.", nameof(nodeId)); if (node.definitionId != "inno.shader.stage-input") + { throw new ArgumentException("The node is not a stage input.", nameof(nodeId)); - ShaderGraphInputSettings previous = ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context); + } + ShaderGraphInputSettings previous = ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphInputSettings(), + serialization, + context + ); // Keep the last declared identity through incomplete text input; clearing a name must not erase its default value. if (string.IsNullOrWhiteSpace(previous.id)) + { previous.id = ShaderGraphDocument.Read(node, "bindingIdentity", "", serialization, context); + } node.SetValue("settings", ShaderGraphDocument.Encode(settings, serialization, context)); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(candidate, serialization, context); var properties = definition.properties.ToList(); - ShaderPropertyDefinition? previousProperty = properties.Where(value => value.id.value == previous.id).Cast().FirstOrDefault(); + ShaderPropertyDefinition? previousProperty = properties + .Where(value => value.id.value == previous.id) + .Cast() + .FirstOrDefault(); if (IsBinding(previous) && !string.IsNullOrWhiteSpace(previous.id)) + { node.SetValue("bindingIdentity", ShaderGraphDocument.Encode(previous.id, serialization, context)); + } if (IsBinding(previous) && (!IsBinding(settings) || !string.IsNullOrWhiteSpace(settings.id) && previous.id != settings.id) && !candidate.nodes.Where(value => value.id != nodeId && value.definitionId == "inno.shader.stage-input") .Select(value => ShaderGraphDocument.Read(value, "settings", new ShaderGraphInputSettings(), serialization, context)) - .Any(value => IsBinding(value) && value.id == previous.id)) + .Any(value => IsBinding(value) && value.id == previous.id) + ) { properties.RemoveAll(value => value.id.value == previous.id); + } if (IsBinding(settings) && !string.IsNullOrWhiteSpace(settings.id) && TryPropertyType(settings.type, out ShaderPropertyType type)) { - ShaderPropertyDefinition? existing = properties.Where(value => value.id.value == settings.id).Cast().FirstOrDefault(); + ShaderPropertyDefinition? existing = properties + .Where(value => value.id.value == settings.id) + .Cast() + .FirstOrDefault(); ShaderPropertyDefinition? source = existing ?? previousProperty; if (type == ShaderPropertyType.Vector4 && source?.type == ShaderPropertyType.Color) + { type = ShaderPropertyType.Color; + } ShaderPropertyBindingKind kind = settings.kind switch { ShaderIrInputKind.SampledTexture => ShaderPropertyBindingKind.SampledTexture, - ShaderIrInputKind.Storage => settings.type.isImage ? ShaderPropertyBindingKind.StorageTexture : ShaderPropertyBindingKind.StorageBuffer, + ShaderIrInputKind.Storage => settings.type.isImage + ? ShaderPropertyBindingKind.StorageTexture + : ShaderPropertyBindingKind.StorageBuffer, _ => ShaderPropertyBindingKind.Uniform }; ShaderStage stages = ShaderStage.None; foreach (GraphNodeRecord input in candidate.nodes.Where(static value => value.definitionId == "inno.shader.stage-input")) { - ShaderGraphInputSettings value = ShaderGraphDocument.Read(input, "settings", new ShaderGraphInputSettings(), serialization, context); + ShaderGraphInputSettings value = ShaderGraphDocument.Read( + input, + "settings", + new ShaderGraphInputSettings(), + serialization, + context + ); if (value.id != settings.id || !IsBinding(value)) + { continue; + } string stageId = ShaderGraphDocument.Read(input, "stage", "", serialization, context); GraphNodeRecord? output = string.IsNullOrWhiteSpace(stageId) ? null : candidate.FindNode(new(stageId)); if (output is not null) + { stages |= ShaderGraphDocument.Read(output, "settings", new ShaderGraphStageSettings(), serialization, context).stage; + } } MaterialValue defaultValue = source?.type == type ? source.Value.defaultValue : default; - var declaration = new ShaderPropertyDefinition(new(settings.id), source?.displayName ?? settings.id, type, stages, - defaultValue, kind, settings.type.access, source?.bindingOwner ?? (kind is ShaderPropertyBindingKind.StorageBuffer or ShaderPropertyBindingKind.StorageTexture - ? ShaderPropertyBindingOwner.RenderPass : ShaderPropertyBindingOwner.Material)); + var declaration = new ShaderPropertyDefinition( + new(settings.id), + source?.displayName ?? settings.id, + type, + stages, + defaultValue, + kind, + settings.type.access, + source?.bindingOwner ?? (kind is ShaderPropertyBindingKind.StorageBuffer or ShaderPropertyBindingKind.StorageTexture + ? ShaderPropertyBindingOwner.RenderPass + : ShaderPropertyBindingOwner.Material) + ); int index = properties.FindIndex(value => value.id.value == settings.id); if (index < 0) + { properties.Add(declaration); + } else + { properties[index] = declaration; + } node.SetValue("bindingIdentity", ShaderGraphDocument.Encode(settings.id, serialization, context)); } definition.properties = properties.ToArray(); - candidate.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context)); + candidate.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context) + ); return candidate; } @@ -206,17 +311,27 @@ private static bool TryPropertyType( ShaderGraphType value, out ShaderPropertyType type ) { - type = value.isStorage ? value.isImage ? value.dimension switch - { - RenderTextureDimension.Texture3D => ShaderPropertyType.Texture3D, - RenderTextureDimension.Cube => ShaderPropertyType.TextureCube, - _ => value.isArray ? ShaderPropertyType.Texture2DArray : ShaderPropertyType.Texture2D - } : ShaderPropertyType.Buffer : (value.element ?? value).id switch + type = value.isStorage + ? value.isImage + ? value.dimension switch +{ + RenderTextureDimension.Texture3D => ShaderPropertyType.Texture3D, + RenderTextureDimension.Cube => ShaderPropertyType.TextureCube, + _ => value.isArray ? ShaderPropertyType.Texture2DArray : ShaderPropertyType.Texture2D +} + : ShaderPropertyType.Buffer + : (value.element ?? value).id switch { - "float" => ShaderPropertyType.Float, "float2" => ShaderPropertyType.Vector2, "float3" => ShaderPropertyType.Vector3, - "float4" => ShaderPropertyType.Vector4, "float4x4" => ShaderPropertyType.Matrix4x4, - "sampled-texture2d" => ShaderPropertyType.Texture2D, "sampled-texture2d-array" => ShaderPropertyType.Texture2DArray, - "sampled-texture3d" => ShaderPropertyType.Texture3D, "sampled-texture-cube" => ShaderPropertyType.TextureCube, _ => (ShaderPropertyType)(-1) + "float" => ShaderPropertyType.Float, + "float2" => ShaderPropertyType.Vector2, + "float3" => ShaderPropertyType.Vector3, + "float4" => ShaderPropertyType.Vector4, + "float4x4" => ShaderPropertyType.Matrix4x4, + "sampled-texture2d" => ShaderPropertyType.Texture2D, + "sampled-texture2d-array" => ShaderPropertyType.Texture2DArray, + "sampled-texture3d" => ShaderPropertyType.Texture3D, + "sampled-texture-cube" => ShaderPropertyType.TextureCube, + _ => (ShaderPropertyType)(-1) }; return Enum.IsDefined(type); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs index 76d5f1f5c..b7af36caf 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs @@ -38,11 +38,17 @@ SerializationContext context ) { GraphDocument fragment = graph.Clone(); HashSet selected = [.. nodes]; - HashSet stages = fragment.nodes.Where(node => selected.Contains(node.id) && node.definitionId == ShaderGraphDocument.outputDefinitionId) - .Select(static node => node.id.value).ToHashSet(StringComparer.Ordinal); + HashSet stages = fragment.nodes + .Where(node => selected.Contains(node.id) && node.definitionId == ShaderGraphDocument.outputDefinitionId) + .Select(static node => node.id.value) + .ToHashSet(StringComparer.Ordinal); foreach (GraphNodeRecord node in fragment.nodes.ToArray()) + { if (!selected.Contains(node.id) && !stages.Contains(ShaderGraphDocument.Read(node, "stage", "", serialization, context))) + { fragment.RemoveNode(node.id); + } + } return fragment; } @@ -79,25 +85,39 @@ public static ShaderGraphPasteResult Paste( SerializationContext context ) { GraphDocument candidate = graph.Clone(); - ShaderDefinition? definition = candidate.metadata.ContainsKey(ShaderGraphDocument.definitionKey) ? ShaderGraphDocument.ReadDefinition(candidate, serialization, context) : null; - ShaderDefinition? source = fragment.metadata.ContainsKey(ShaderGraphDocument.definitionKey) ? ShaderGraphDocument.ReadDefinition(fragment, serialization, context) : null; - Dictionary remap = fragment.nodes.ToDictionary(static node => node.id, static _ => new GraphNodeId(Guid.NewGuid().ToString("N"))); + ShaderDefinition? definition = candidate.metadata.ContainsKey(ShaderGraphDocument.definitionKey) + ? ShaderGraphDocument.ReadDefinition(candidate, serialization, context) + : null; + ShaderDefinition? source = fragment.metadata.ContainsKey(ShaderGraphDocument.definitionKey) + ? ShaderGraphDocument.ReadDefinition(fragment, serialization, context) + : null; + Dictionary remap = fragment.nodes.ToDictionary( + static node => node.id, + static _ => new GraphNodeId(Guid.NewGuid().ToString("N")) + ); var passes = new Dictionary(StringComparer.Ordinal); var programs = candidate.metadata.ContainsKey(ShaderGraphPrograms.bindingsKey) - ? ShaderGraphPrograms.Read(candidate, serialization, context).ToList() : []; + ? ShaderGraphPrograms.Read(candidate, serialization, context).ToList() + : []; if (definition is not null && source is not null) { foreach (ShaderGraphPassProgram program in ShaderGraphPrograms.Read(fragment, serialization, context)) { GraphNodeId[] copiedStages = program.stages.Select(static id => new GraphNodeId(id)).Where(remap.ContainsKey).ToArray(); if (copiedStages.Length == 0) + { continue; + } int index = Array.FindIndex(source.passes, pass => pass.name == program.pass); if (index < 0) + { continue; + } string destination = program.pass; for (int suffix = 2; definition.passes.Any(pass => pass.name == destination); suffix++) + { destination = program.pass + " " + suffix; + } passes.Add(program.pass, destination); ShaderPassDefinition pass = source.passes[index]; pass.name = destination; @@ -110,34 +130,61 @@ SerializationContext context foreach (ShaderTechniqueDefinition technique in source.techniques) { ShaderTechniquePass[] mappings = technique.passes.Where(mapping => passes.ContainsKey(mapping.passName)) - .Select(mapping => new ShaderTechniquePass(mapping.role, passes[mapping.passName])).ToArray(); + .Select(mapping => new ShaderTechniquePass(mapping.role, passes[mapping.passName])) + .ToArray(); if (mappings.Length == 0) + { continue; + } string id = technique.id.value; for (int suffix = 2; definition.techniques.Any(value => value.id.value == id); suffix++) + { id = technique.id.value + "-" + suffix; - definition.techniques = [.. definition.techniques, new ShaderTechniqueDefinition(new(id), technique.contract, mappings, technique.requiredFeatures)]; + } + definition.techniques = + [ + .. definition.techniques, + new ShaderTechniqueDefinition(new(id), technique.contract, mappings, technique.requiredFeatures) + ]; } } - GraphNodeId? targetStage = activeStage ?? candidate.nodes.FirstOrDefault(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId)?.id; + GraphNodeId? targetStage = activeStage + ?? candidate.nodes.FirstOrDefault(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId)?.id; foreach (GraphNodeRecord node in fragment.nodes) { - var clone = new GraphNodeRecord(remap[node.id], node.definitionId) { position = new(node.position.x + 32, node.position.y + 32) }; + var clone = new GraphNodeRecord(remap[node.id], node.definitionId) + { + position = new(node.position.x + 32, node.position.y + 32) + }; foreach (var value in node.values) + { clone.SetValue(value.Key, value.Value.Clone()); + } string stage = ShaderGraphDocument.Read(node, "stage", "", serialization, context); if (stage.Length != 0) { if (remap.TryGetValue(new(stage), out GraphNodeId mapped)) + { stage = mapped.value; + } else if ((!preserveExternalStageReferences || candidate.FindNode(new(stage)) is null) && targetStage is GraphNodeId target) + { stage = target.value; + } clone.SetValue("stage", ShaderGraphDocument.Encode(stage, serialization, context)); } candidate.AddNode(clone); } foreach (GraphEdgeRecord edge in fragment.edges) - candidate.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(remap[edge.output.nodeId], edge.output.portId), new(remap[edge.input.nodeId], edge.input.portId))); + { + candidate.AddEdge( + new( + new(Guid.NewGuid().ToString("N")), + new(remap[edge.output.nodeId], edge.output.portId), + new(remap[edge.input.nodeId], edge.input.portId) + ) + ); + } if (definition is not null) { candidate.SetMetadata(ShaderGraphPrograms.bindingsKey, ShaderGraphDocument.Encode(programs.ToArray(), serialization, context)); @@ -145,19 +192,46 @@ SerializationContext context if (source is not null) { HashSet bindings = fragment.nodes.Where(static node => node.definitionId == "inno.shader.stage-input") - .Select(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context).id).ToHashSet(StringComparer.Ordinal); - definition.properties = [.. definition.properties, .. source.properties.Where(property => bindings.Contains(property.id.value) - && !definition.properties.Any(existing => existing.id == property.id))]; + .Select(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context).id) + .ToHashSet(StringComparer.Ordinal); + definition.properties = + [ + .. definition.properties, + .. source.properties.Where(property => ( + bindings.Contains(property.id.value) + && !definition.properties.Any(existing => existing.id == property.id) + )) + ]; + } + candidate.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context) + ); + foreach (GraphNodeRecord node in candidate.nodes + .Where(node => remap.Values.Contains(node.id) && node.definitionId == "inno.shader.stage-input") + .ToArray() + ) { + candidate = ShaderGraphBindings.ChangeInput( + candidate, + node.id, + ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context), + serialization, + context + ); } - candidate.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context)); - foreach (GraphNodeRecord node in candidate.nodes.Where(node => remap.Values.Contains(node.id) && node.definitionId == "inno.shader.stage-input").ToArray()) - candidate = ShaderGraphBindings.ChangeInput(candidate, node.id, ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context), serialization, context); ShaderDefinition updated = ShaderGraphDocument.ReadDefinition(candidate, serialization, context); foreach (ShaderPropertyDefinition property in definition.properties) { ShaderPropertyDefinition next = updated.properties.Single(value => value.id == property.id); - if (next.type != property.type || next.bindingKind != property.bindingKind || next.storageAccess != property.storageAccess || next.bindingOwner != property.bindingOwner) - throw new InvalidOperationException($"Cannot paste incompatible shader parameter '{property.id.value}'. Rename the copied parameter first."); + if (next.type != property.type + || next.bindingKind != property.bindingKind + || next.storageAccess != property.storageAccess + || next.bindingOwner != property.bindingOwner + ) { + throw new InvalidOperationException( + $"Cannot paste incompatible shader parameter '{property.id.value}'. Rename the copied parameter first." + ); + } } } return new(candidate, remap.Values.ToArray()); @@ -176,10 +250,12 @@ GraphNodeId[] nodes document = graph; insertedNodes = Array.AsReadOnly(nodes); } + /// /// Gets the complete detached candidate; the caller owns its subsequent edits. /// public GraphDocument document { get; } + /// /// Gets new identities suitable for selecting the pasted nodes. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs index e40ed9cf2..e84201a8f 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs @@ -14,6 +14,7 @@ public static class ShaderGraphDocument /// Identifies the graph metadata containing the source-free material and pass contract. /// public const string definitionKey = "inno.shader.definition"; + /// /// Identifies the optional domain target; absent means explicitly authored generic stages. /// @@ -38,8 +39,7 @@ public static string ReadTarget( GraphDocument graph, SerializationRegistry serialization, SerializationContext context - ) - => graph.metadata.TryGetValue(targetKey, out GraphSerializedValue? value) ? Decode(value, serialization, context) : ""; + ) => graph.metadata.TryGetValue(targetKey, out GraphSerializedValue? value) ? Decode(value, serialization, context) : ""; /// /// Assigns a domain target by stable identity without retaining its current provider. @@ -64,22 +64,30 @@ SerializationContext context ) { ArgumentNullException.ThrowIfNull(targetId); if (targetId.Length == 0) + { graph.RemoveMetadata(targetKey); + } else + { graph.SetMetadata(targetKey, Encode(targetId, serialization, context)); + } } + /// /// Identifies a stage output node; its incoming edges name the stage's GPU outputs. /// public const string outputDefinitionId = "inno.shader.stage-output"; + /// /// Identifies a node property containing its owning stage output node identity. /// public const string stageKey = "stage"; + /// /// Identifies the structured settings stored on a stage output node. /// public const string settingsKey = "settings"; + /// /// Prefixes stable port IDs storing explicit typed defaults for unconnected inputs. /// @@ -134,7 +142,9 @@ SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); if (!graph.metadata.TryGetValue(definitionKey, out GraphSerializedValue? value)) + { throw new InvalidOperationException("The shader graph has no program definition."); + } return serialization.Deserialize(Decode(value, serialization, context), context); } @@ -225,8 +235,7 @@ public static T Read( T defaultValue, SerializationRegistry serialization, SerializationContext context - ) - => node.TryGetValue(key, out GraphSerializedValue? value) ? Decode(value!, serialization, context) : defaultValue; + ) => node.TryGetValue(key, out GraphSerializedValue? value) ? Decode(value!, serialization, context) : defaultValue; } /// @@ -238,18 +247,22 @@ public sealed class ShaderGraphStageSettings : ISerializable /// Gets or sets the programmable stage. /// [SerializableProperty] public ShaderStage stage { get; set; } = ShaderStage.Fragment; + /// /// Gets or sets output ports and their GPU destinations. /// [SerializableProperty] public ShaderGraphOutput[] outputs { get; set; } = []; + /// /// Gets or sets compute workgroup width. /// [SerializableProperty] public int threadsX { get; set; } = 1; + /// /// Gets or sets compute workgroup height. /// [SerializableProperty] public int threadsY { get; set; } = 1; + /// /// Gets or sets compute workgroup depth. /// @@ -265,14 +278,17 @@ public struct ShaderGraphOutput /// Gets or sets the stable input port identity on the stage output node. /// public string id { get; set; } + /// /// Gets or sets the GPU destination category. /// public ShaderIrOutputKind kind { get; set; } + /// /// Gets or sets the varying semantic; empty for fixed position, color or depth outputs. /// public string semantic { get; set; } + /// /// Gets or sets the varying or attachment index. /// @@ -288,18 +304,22 @@ public sealed class ShaderGraphInputSettings : ISerializable /// Gets or sets the stable logical binding identity. /// [SerializableProperty] public string id { get; set; } = "input"; + /// /// Gets or sets the complete neutral type descriptor. /// [SerializableProperty] public ShaderGraphType type { get; set; } = new(); + /// /// Gets or sets the stage input category. /// [SerializableProperty] public ShaderIrInputKind kind { get; set; } + /// /// Gets or sets the target semantic, not a native expression. /// [SerializableProperty] public string semantic { get; set; } = "position"; + /// /// Gets or sets the interface index. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs index 917616fa9..26689fde8 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs @@ -13,6 +13,7 @@ public sealed class ShaderGraphLiteral : ISerializable /// Gets or sets the complete value type, including named aggregates and fixed arrays. /// [SerializableProperty] public ShaderGraphType type { get; set; } = new() { id = "float" }; + /// /// Gets or sets scalar bit patterns in declaration order; matrices use column-major order. /// @@ -47,14 +48,22 @@ public static ShaderGraphLiteral Zero(ShaderSourceType type) public IReadOnlyList GetScalarTypes() { if (type is null || scalarBits is null) + { throw new InvalidOperationException("The input default must retain a type and scalar bits."); + } var scalars = new List(); Flatten(type.CreateType(), scalars, 0); if (scalarBits.Length != scalars.Count) + { throw new InvalidOperationException("The input default's component count does not match its type."); + } for (int i = 0; i < scalars.Count; i++) + { if (scalars[i] == "bool" && scalarBits[i] > 1) + { throw new InvalidOperationException("A boolean input default must contain zero or one."); + } + } return scalars; } @@ -82,7 +91,9 @@ ShaderSourceType expectedType _ = GetScalarTypes(); ShaderSourceType declared = type.CreateType(); if (!declared.IsEquivalentTo(expectedType)) + { throw new InvalidOperationException("The input default type changed; reset or repair it explicitly."); + } int offset = 0; return Build(declared); @@ -103,7 +114,9 @@ ShaderIrValue Build(ShaderSourceType current) ShaderSourceType[] members = Members(current); var values = new ShaderIrValue[members.Length]; for (int i = 0; i < values.Length; i++) + { values[i] = Build(members[i]); + } return builder.Construct(current, values); } } @@ -116,22 +129,34 @@ private static void Flatten( int depth ) { if (depth > 32 || scalars.Count >= 4096) + { throw new NotSupportedException("An input literal exceeds the bounded aggregate size."); + } if (IsScalar(type.id) && type.fields.Count == 0 && type.elementType is null && type.storage is null) + { scalars.Add(type.id); + } else + { foreach (ShaderSourceType member in Members(type)) + { Flatten(member, scalars, depth + 1); + } + } } private static ShaderSourceType[] Members(ShaderSourceType type) { if (type.storage is not null) + { throw new NotSupportedException("Resource inputs require explicit bindings, not literal defaults."); + } if (type.elementType is not null) { if (type.elementCount > 4096) + { throw new NotSupportedException("An input literal array is too large."); + } var elements = new ShaderSourceType[type.elementCount]; Array.Fill(elements, type.elementType); return elements; } @@ -139,17 +164,27 @@ private static ShaderSourceType[] Members(ShaderSourceType type) { var fields = new ShaderSourceType[type.fields.Count]; for (int i = 0; i < fields.Length; i++) + { fields[i] = type.fields[i].type; + } return fields; } foreach (string scalar in new[] { "float", "int", "uint", "bool" }) { string shape = type.id.StartsWith(scalar, StringComparison.Ordinal) ? type.id[scalar.Length..] : ""; - int count = shape.Length == 1 && shape[0] is >= '2' and <= '4' ? shape[0] - '0' - : scalar == "float" && shape.Length == 3 && shape[0] is >= '2' and <= '4' && shape[1] == 'x' && shape[2] is >= '2' and <= '4' - ? (shape[0] - '0') * (shape[2] - '0') : 0; + int count = shape.Length == 1 && shape[0] is >= '2' and <= '4' + ? shape[0] - '0' + : scalar == "float" + && shape.Length == 3 + && shape[0] is >= '2' and <= '4' + && shape[1] == 'x' + && shape[2] is >= '2' and <= '4' + ? (shape[0] - '0') * (shape[2] - '0') + : 0; if (count == 0) + { continue; + } var result = new ShaderSourceType[count]; Array.Fill(result, ShaderSourceType.Atomic(scalar)); return result; } throw new NotSupportedException($"Input type '{type.id}' has no literal representation."); diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs index eb49744e0..0761148c6 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs @@ -46,22 +46,27 @@ public sealed class ShaderGraphNodeSettings : ISerializable /// Gets or sets the node title displayed to authors. /// [SerializableProperty] public string displayName { get; set; } = "Graph Node"; + /// /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. /// [SerializableProperty] public string createPath { get; set; } = "General"; + /// /// Gets or sets the deterministic order within the creation catalog. /// [SerializableProperty] public int createOrder { get; set; } + /// /// Gets or sets how a reference to this graph participates in compilation. /// [SerializableProperty] public ShaderGraphNodeKind kind { get; set; } + /// /// Gets or sets the observable computation behavior of an inline function. /// [SerializableProperty] public ShaderGraphNodeEffect effect { get; set; } + /// /// Gets or sets the domain role consumed by a Target; empty for ordinary inline functions. /// @@ -77,10 +82,12 @@ public sealed class ShaderGraphNodePortDefinition : ISerializable /// Gets or sets the stable node-local port identity. /// [SerializableProperty] public string id { get; set; } = "value"; + /// /// Gets or sets the complete backend-neutral value type. /// [SerializableProperty] public ShaderGraphType type { get; set; } = new() { id = "float" }; + /// /// Gets or sets whether callers must connect the input instead of using an explicit/default zero. /// @@ -121,30 +128,37 @@ public sealed class ShaderGraphNodeInterface : ISerializable /// Gets or sets the node title displayed to authors. /// [SerializableProperty] public string displayName { get; set; } = "Graph Node"; + /// /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. /// [SerializableProperty] public string createPath { get; set; } = "General"; + /// /// Gets or sets the deterministic order within the creation catalog. /// [SerializableProperty] public int createOrder { get; set; } + /// /// Gets or sets whether the graph is inline computation or a Target-owned output boundary. /// [SerializableProperty] public ShaderGraphNodeKind kind { get; set; } + /// /// Gets or sets whether an inline function is pure or intentionally emits ordered effects. /// [SerializableProperty] public ShaderGraphNodeEffect effect { get; set; } + /// /// Gets or sets the Target-owned role for a domain output. /// [SerializableProperty] public string role { get; set; } = ""; + /// /// Gets or sets externally supplied inputs. /// [SerializableProperty] public ShaderGraphNodePortDefinition[] inputs { get; set; } = []; + /// /// Gets or sets externally visible results. /// @@ -171,18 +185,22 @@ public static class ShaderGraphNodes /// Identifies the single multi-port node-input interface record. /// public const string inputDefinitionId = "inno.shader.node-inputs"; + /// /// Identifies the optional multi-port node-output interface record. /// public const string outputDefinitionId = "inno.shader.node-outputs"; + /// /// Identifies a reference to another Shader graph used as a node. /// public const string callDefinitionId = "inno.shader.graph-node"; + /// /// Identifies the serialized interface snapshot retained by a graph-node reference. /// public const string interfaceKey = "interface"; + /// /// Identifies graph-level reusable-node metadata, independent of either interface direction. /// @@ -251,7 +269,9 @@ SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); if (!graph.metadata.TryGetValue(settingsKey, out GraphSerializedValue? value)) + { throw new InvalidOperationException("The Shader graph does not declare reusable-node settings."); + } return ShaderGraphDocument.Decode(value, serialization, context); } @@ -277,26 +297,46 @@ SerializationContext context ) { ArgumentNullException.ThrowIfNull(graph); if (ShaderGraphDocument.ReadTarget(graph, serialization, context).Length != 0) + { throw new InvalidOperationException("A graph-authored node cannot select a Shader Target."); + } if (graph.nodes.Any(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId)) + { throw new InvalidOperationException("A graph-authored node cannot contain explicit GPU stage outputs."); + } GraphNodeRecord[] inputs = graph.nodes.Where(static node => node.definitionId == inputDefinitionId).ToArray(); GraphNodeRecord[] outputs = graph.nodes.Where(static node => node.definitionId == outputDefinitionId).ToArray(); if (inputs.Length > 1) + { throw new InvalidOperationException("A graph-authored node can contain at most one Function Inputs record."); + } if (outputs.Length > 1) + { throw new InvalidOperationException("A graph-authored node can contain at most one Function Outputs record."); + } if (inputs.Length == 0 && outputs.Length == 0) + { throw new InvalidOperationException("A graph-authored node requires Function Inputs, Function Outputs, or both."); + } ShaderGraphNodeSettings settings = ReadSettings(graph, serialization, context); ShaderGraphNodeInputSettings input = inputs.Length == 0 - ? new() - : ShaderGraphDocument.Read(inputs[0], ShaderGraphDocument.settingsKey, - new ShaderGraphNodeInputSettings(), serialization, context); + ? new() + : ShaderGraphDocument.Read( + inputs[0], + ShaderGraphDocument.settingsKey, + new ShaderGraphNodeInputSettings(), + serialization, + context + ); ShaderGraphNodeOutputSettings output = outputs.Length == 0 - ? new() - : ShaderGraphDocument.Read(outputs[0], ShaderGraphDocument.settingsKey, - new ShaderGraphNodeOutputSettings(), serialization, context); + ? new() + : ShaderGraphDocument.Read( + outputs[0], + ShaderGraphDocument.settingsKey, + new ShaderGraphNodeOutputSettings(), + serialization, + context + ); var result = new ShaderGraphNodeInterface { displayName = settings.displayName, @@ -333,7 +373,12 @@ public static ShaderGraphNodeInterface ReadCallInterface( SerializationContext context ) { ShaderGraphNodeInterface result = ShaderGraphDocument.Read( - node, interfaceKey, new ShaderGraphNodeInterface(), serialization, context); + node, + interfaceKey, + new ShaderGraphNodeInterface(), + serialization, + context + ); Validate(result, result.inputs.Length == 0 ? 0 : 1, result.outputs.Length == 0 ? 0 : 1); return result; } @@ -377,15 +422,21 @@ private static void Expand( HashSet stack ) { var retainedDomainOutputs = new HashSet(); - while (graph.nodes.FirstOrDefault(node => node.definitionId == callDefinitionId - && !retainedDomainOutputs.Contains(node.id)) is { } call) - { + while (graph.nodes.FirstOrDefault(node => ( + node.definitionId == callDefinitionId + && !retainedDomainOutputs.Contains(node.id) + )) is { } call + ) { Guid sourceId = ShaderGraphDocument.Read(call, "sourceId", Guid.Empty, serialization, context); string sourcePath = ShaderGraphDocument.Read(call, "sourcePath", "", serialization, context); if (sourceId == Guid.Empty) + { throw new InvalidOperationException("A graph-node reference has no Shader asset identity."); + } if (!stack.Add(sourceId)) + { throw new InvalidOperationException($"Graph-node references contain a cycle at '{sourcePath}'."); + } GraphDocument child = resolve(sourceId, sourcePath).Clone(); ShaderGraphNodeInterface nodeInterface = ReadInterface(child, serialization, context); if (nodeInterface.kind == ShaderGraphNodeKind.DomainOutput) @@ -418,12 +469,23 @@ SerializationContext context { var mapped = new GraphNodeId(call.id.value + "/" + node.id.value); if (parent.FindNode(mapped) is not null) - throw new InvalidOperationException($"Inlining '{nodeInterface.displayName}' produced duplicate node identity '{mapped.value}'."); - var copy = new GraphNodeRecord(mapped, node.definitionId) { position = new(call.position.x + node.position.x, call.position.y + node.position.y) }; + { + throw new InvalidOperationException( + $"Inlining '{nodeInterface.displayName}' produced duplicate node identity '{mapped.value}'." + ); + } + var copy = new GraphNodeRecord(mapped, node.definitionId) + { + position = new(call.position.x + node.position.x, call.position.y + node.position.y) + }; foreach ((string key, GraphSerializedValue value) in node.values) + { copy.SetValue(key, value); + } if (stage.Length != 0) + { copy.SetValue(ShaderGraphDocument.stageKey, ShaderGraphDocument.Encode(stage, serialization, context)); + } parent.AddNode(copy); map.Add(node.id, mapped); } @@ -438,26 +500,43 @@ SerializationContext context HashSet outputIds = nodeInterface.outputs.Select(static port => port.id).ToHashSet(StringComparer.Ordinal); string? missingInput = incoming.Keys.FirstOrDefault(id => !inputIds.Contains(id)); if (missingInput is not null) + { throw new InvalidOperationException( - $"Graph-node call '{nodeInterface.displayName}' retains unavailable input port '{missingInput}'."); + $"Graph-node call '{nodeInterface.displayName}' retains unavailable input port '{missingInput}'." + ); + } string? missingOutput = outgoing.Keys.FirstOrDefault(id => !outputIds.Contains(id)); if (missingOutput is not null) + { throw new InvalidOperationException( - $"Graph-node call '{nodeInterface.displayName}' retains unavailable output port '{missingOutput}'."); + $"Graph-node call '{nodeInterface.displayName}' retains unavailable output port '{missingOutput}'." + ); + } foreach (GraphEdgeRecord[] values in incoming.Values) + { if (values.Length != 1) + { throw new InvalidOperationException("A graph-node input has multiple incoming connections."); + } + } var resolvedInputs = new Dictionary(StringComparer.Ordinal); foreach (ShaderGraphNodePortDefinition port in nodeInterface.inputs) { if (incoming.TryGetValue(port.id, out GraphEdgeRecord[]? edges)) + { resolvedInputs.Add(port.id, edges[0].output); + } else if (!port.required) + { resolvedInputs.Add(port.id, AddOptionalZero(parent, call, port, stage, serialization, context)); + } else + { throw new InvalidOperationException( - $"Required graph-node input '{port.id}' is not connected on '{nodeInterface.displayName}'."); + $"Required graph-node input '{port.id}' is not connected on '{nodeInterface.displayName}'." + ); + } } var resolvedOutputs = new Dictionary(StringComparer.Ordinal); @@ -469,31 +548,45 @@ SerializationContext context if (fromInput) { if (!resolvedInputs.TryGetValue(edge.output.portId.value, out GraphEndpoint source)) + { continue; + } mappedSource = source; } else { if (!map.TryGetValue(edge.output.nodeId, out GraphNodeId sourceNode)) + { continue; + } mappedSource = new(sourceNode, edge.output.portId); } if (toOutput) { if (!resolvedOutputs.TryAdd(edge.input.portId.value, mappedSource)) + { throw new InvalidOperationException($"Graph-node output '{edge.input.portId.value}' is connected more than once."); + } } else if (map.TryGetValue(edge.input.nodeId, out GraphNodeId targetNode)) + { parent.AddEdge(new(new(call.id.value + "/" + edge.id.value), mappedSource, new(targetNode, edge.input.portId))); + } } foreach (ShaderGraphNodePortDefinition port in nodeInterface.outputs) { if (!resolvedOutputs.TryGetValue(port.id, out GraphEndpoint source)) + { throw new InvalidOperationException($"Graph-node output '{port.id}' has no value inside '{nodeInterface.displayName}'."); + } if (!outgoing.TryGetValue(port.id, out GraphEdgeRecord[]? edges)) + { continue; + } foreach (GraphEdgeRecord edge in edges) + { parent.AddEdge(new(new(call.id.value + "/return/" + edge.id.value), source, edge.input)); + } } parent.RemoveNode(call.id); } @@ -509,14 +602,23 @@ SerializationContext context ShaderDefinition childDefinition = ShaderGraphDocument.ReadDefinition(child, serialization, context); ShaderStage callerStage = ShaderStage.None; if (stageId.Length != 0 && parent.FindNode(new(stageId)) is { definitionId: ShaderGraphDocument.outputDefinitionId } stageNode) - callerStage = ShaderGraphDocument.Read(stageNode, ShaderGraphDocument.settingsKey, - new ShaderGraphStageSettings(), serialization, context).stage; + { + callerStage = ShaderGraphDocument.Read( + stageNode, + ShaderGraphDocument.settingsKey, + new ShaderGraphStageSettings(), + serialization, + context + ).stage; + } var properties = parentDefinition.properties.ToList(); foreach (ShaderPropertyDefinition childPropertyValue in childDefinition.properties) { ShaderPropertyDefinition childProperty = childPropertyValue; if (callerStage != ShaderStage.None) + { childProperty.stages |= callerStage; + } int index = properties.FindIndex(value => value.id.value == childProperty.id.value); if (index < 0) { @@ -525,14 +627,18 @@ SerializationContext context } ShaderPropertyDefinition existing = properties[index]; if (existing.type != childProperty.type || existing.bindingKind != childProperty.bindingKind - || existing.storageAccess != childProperty.storageAccess || existing.bindingOwner != childProperty.bindingOwner) + || existing.storageAccess != childProperty.storageAccess || existing.bindingOwner != childProperty.bindingOwner + ) { throw new InvalidOperationException($"Graph node property '{childProperty.id.value}' conflicts with its caller."); + } existing.stages |= childProperty.stages; properties[index] = existing; } parentDefinition.properties = properties.ToArray(); - parent.SetMetadata(ShaderGraphDocument.definitionKey, - ShaderGraphDocument.Encode(serialization.Serialize(parentDefinition, context), serialization, context)); + parent.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(serialization.Serialize(parentDefinition, context), serialization, context) + ); } private static GraphEndpoint AddOptionalZero( @@ -548,7 +654,9 @@ SerializationContext context var node = new GraphNodeRecord(id, "inno.shader.reroute") { position = call.position }; node.SetValue("valueType", ShaderGraphDocument.Encode(port.type, serialization, context)); if (stage.Length != 0) + { node.SetValue(ShaderGraphDocument.stageKey, ShaderGraphDocument.Encode(stage, serialization, context)); + } graph.AddNode(node); return new(id, new("value")); } @@ -559,21 +667,39 @@ private static void Validate( int outputRecords ) { if (string.IsNullOrWhiteSpace(value.displayName)) + { throw new InvalidOperationException("A graph-authored node requires a display name."); + } if (!Enum.IsDefined(value.kind)) + { throw new InvalidOperationException("The graph-authored node kind is invalid."); + } if (!Enum.IsDefined(value.effect)) + { throw new InvalidOperationException("The graph-authored node effect is invalid."); + } if (inputRecords is < 0 or > 1 || outputRecords is < 0 or > 1 || inputRecords + outputRecords == 0) - throw new InvalidOperationException("A graph-authored node requires at most one interface record per direction and at least one direction."); + { + throw new InvalidOperationException( + "A graph-authored node requires at most one interface record per direction and at least one direction." + ); + } if (value.inputs.Length + value.outputs.Length == 0) + { throw new InvalidOperationException("A graph-authored node requires at least one public input or output port."); + } if (value.kind == ShaderGraphNodeKind.Function && value.effect == ShaderGraphNodeEffect.Pure && outputRecords == 0) + { throw new InvalidOperationException("A pure graph-authored function requires at least one Function Output."); + } if (value.kind == ShaderGraphNodeKind.DomainOutput && outputRecords != 0) + { throw new InvalidOperationException("A domain output graph node cannot declare returned values."); + } if (value.kind == ShaderGraphNodeKind.DomainOutput && string.IsNullOrWhiteSpace(value.role)) + { throw new InvalidOperationException("A domain output graph node requires a stable Target role."); + } ValidatePorts(value.inputs, "input"); ValidatePorts(value.outputs, "output"); } @@ -583,14 +709,20 @@ private static void ValidatePorts( string direction ) { if (ports is null) + { throw new InvalidOperationException($"The graph-node {direction} port list is missing."); + } var ids = new HashSet(StringComparer.Ordinal); foreach (ShaderGraphNodePortDefinition port in ports) { if (port is null || string.IsNullOrWhiteSpace(port.id) || port.type is null || port.type.CreateType().id == "void") + { throw new InvalidOperationException($"A graph-node {direction} port is invalid."); + } if (!ids.Add(port.id)) + { throw new InvalidOperationException($"A graph-node {direction} port repeats '{port.id}'."); + } } } } @@ -604,6 +736,7 @@ public sealed class ShaderGraphCallNodeCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => ShaderGraphNodes.callDefinitionId; + /// /// Gets a ports required by the implemented contract. /// @@ -615,6 +748,7 @@ public sealed class ShaderGraphCallNodeCompiler : IShaderNodeCompiler /// public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => context.Read(ShaderGraphNodes.interfaceKey, new ShaderGraphNodeInterface()).GetPorts(); + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -637,6 +771,7 @@ public sealed class ShaderGraphNodeInputsCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => ShaderGraphNodes.inputDefinitionId; + /// /// Gets a ports required by the implemented contract. /// @@ -648,7 +783,9 @@ public sealed class ShaderGraphNodeInputsCompiler : IShaderNodeCompiler /// public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => context.Read(ShaderGraphDocument.settingsKey, new ShaderGraphNodeInputSettings()).ports - .Select(static value => value.ToPort(GraphPortDirection.Output)).ToArray(); + .Select(static value => value.ToPort(GraphPortDirection.Output)) + .ToArray(); + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// @@ -671,6 +808,7 @@ public sealed class ShaderGraphNodeOutputsCompiler : IShaderNodeCompiler /// Gets the definition id text used by the current instance. /// public string definitionId => ShaderGraphNodes.outputDefinitionId; + /// /// Gets a ports required by the implemented contract. /// @@ -682,7 +820,9 @@ public sealed class ShaderGraphNodeOutputsCompiler : IShaderNodeCompiler /// public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => context.Read(ShaderGraphDocument.settingsKey, new ShaderGraphNodeOutputSettings()).ports - .Select(static value => value.ToPort(GraphPortDirection.Input)).ToArray(); + .Select(static value => value.ToPort(GraphPortDirection.Input)) + .ToArray(); + /// /// Lowers this graph node to typed shader IR after validating its inputs. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgram.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgram.cs index 4083f0fd7..345befc46 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgram.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgram.cs @@ -28,10 +28,12 @@ IEnumerable stages this.name = name; this.stages = Array.AsReadOnly(stages.ToArray()); } + /// /// Gets the stable pass identity. /// public string name { get; } + /// /// Gets immutable graph-lowered stages. /// @@ -50,14 +52,17 @@ IEnumerable diagnostics this.passes = Array.AsReadOnly(passes.ToArray()); this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); } + /// /// Gets the complete stage set; empty if any stage failed. /// public IReadOnlyList passes { get; } + /// /// Gets stable graph/node diagnostics without provider references. /// public IReadOnlyList diagnostics { get; } + /// /// Gets whether every declared pass was lowered without errors. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs index a4f4c9999..8372880df 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs @@ -69,39 +69,65 @@ public ShaderGraphProgramResult Lower( { GraphDocument graph = document.Clone(); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, serialization, context); - diagnostics.AddRange(ShaderDefinitionValidator.Validate(definition).Select(static value => - new ShaderGraphDiagnostic(value.code, value.severity, value.message))); + diagnostics.AddRange( + ShaderDefinitionValidator.Validate(definition).Select(static value => + new ShaderGraphDiagnostic(value.code, value.severity, value.message)) + ); if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { return new([], diagnostics); + } ConnectRasterStages(graph, implementationId, sources, serialization, context); var definitions = definition.passes.ToDictionary(static pass => pass.name, StringComparer.Ordinal); if (definitions.Count == 0) + { throw new InvalidOperationException("A shader graph requires at least one pass."); + } ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(graph, serialization, context); if (programs.Select(static value => value.pass).Distinct(StringComparer.Ordinal).Count() != programs.Length - || programs.Any(value => !definitions.ContainsKey(value.pass))) + || programs.Any(value => !definitions.ContainsKey(value.pass)) + ) { throw new InvalidOperationException("Program references must name unique declared passes."); + } var stages = new Dictionary(StringComparer.Ordinal); var outputs = graph.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId).ToArray(); var owners = graph.nodes.Where(static node => node.definitionId != ShaderGraphDocument.outputDefinitionId) - .ToDictionary(static node => node.id, node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", serialization, context)); + .ToDictionary( + static node => node.id, + node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", serialization, context) + ); var outputIds = outputs.Select(static node => node.id.value).ToHashSet(StringComparer.Ordinal); foreach ((GraphNodeId node, string owner) in owners) + { if (!outputIds.Contains(owner)) + { Error("SHADER_STAGE_MISSING", "The node's stage is missing; its data remains available for repair.", node); + } + } if (diagnostics.Count != 0) + { return new([], diagnostics); + } foreach (GraphNodeRecord output in outputs) { cancellationToken.ThrowIfCancellationRequested(); activeNode = output.id; - ShaderGraphStageSettings settings = ShaderGraphDocument.Read(output, - ShaderGraphDocument.settingsKey, null, serialization, context) + ShaderGraphStageSettings settings = ShaderGraphDocument.Read( + output, + ShaderGraphDocument.settingsKey, + null, + serialization, + context + ) ?? throw new InvalidOperationException("A stage output node requires its stage settings."); var region = graph.Clone(); foreach (GraphNodeRecord node in graph.nodes) + { if (!owners.TryGetValue(node.id, out string? owner) || owner != output.id.value) + { region.RemoveNode(node.id); + } + } HashSet members = region.nodes.Select(static node => node.id).ToHashSet(); var endpoints = new Dictionary(StringComparer.Ordinal); foreach (GraphEdgeRecord edge in graph.edges) @@ -109,22 +135,43 @@ public ShaderGraphProgramResult Lower( if (edge.input.nodeId == output.id) { if (!members.Contains(edge.output.nodeId)) - throw new InvalidOperationException("A stage output is connected to another stage; use an explicit varying interface."); + { + throw new InvalidOperationException( + "A stage output is connected to another stage; use an explicit varying interface." + ); + } if (!endpoints.TryAdd(edge.input.portId.value, edge.output)) + { throw new InvalidOperationException("A stage output port has multiple incoming connections."); + } } else if (members.Contains(edge.input.nodeId) != members.Contains(edge.output.nodeId) - && edge.output.nodeId != output.id && edge.input.nodeId != output.id) + && edge.output.nodeId != output.id && edge.input.nodeId != output.id + ) { throw new InvalidOperationException("A connection crosses incompatible stage boundaries."); + } if (edge.output.nodeId == output.id) + { throw new InvalidOperationException("A GPU stage output node cannot produce graph values."); + } } string[] expected = settings.outputs.Select(static value => value.id).ToArray(); - if (expected.Distinct(StringComparer.Ordinal).Count() != expected.Length || !expected.ToHashSet(StringComparer.Ordinal).SetEquals(endpoints.Keys)) - throw new InvalidOperationException("Every stage output must have exactly one connection with its original port identity."); + if (expected.Distinct(StringComparer.Ordinal).Count() != expected.Length + || !expected.ToHashSet(StringComparer.Ordinal).SetEquals(endpoints.Keys) + ) { + throw new InvalidOperationException( + "Every stage output must have exactly one connection with its original port identity." + ); + } var inputs = region.nodes.Where(static node => node.definitionId == "inno.shader.stage-input") .ToDictionary(static node => node.id, node => - (ShaderGraphDocument.Read(node, ShaderGraphDocument.settingsKey, null, serialization, context) + (ShaderGraphDocument.Read( + node, + ShaderGraphDocument.settingsKey, + null, + serialization, + context + ) ?? throw new InvalidOperationException("A stage input requires its interface settings.")).CreateBinding()); IGrouping>? duplicateInput = inputs .GroupBy(static pair => pair.Value.id, StringComparer.Ordinal) @@ -133,16 +180,37 @@ public ShaderGraphProgramResult Lower( { string nodes = string.Join(", ", duplicateInput.Select(static pair => $"'{pair.Key.value}'")); throw new InvalidOperationException( - $"Stage '{output.id.value}' contains duplicate input '{duplicateInput.Key}' from graph nodes {nodes}."); + $"Stage '{output.id.value}' contains duplicate input '{duplicateInput.Key}' from graph nodes {nodes}." + ); } - ShaderGraphLoweringResult lowered = m_nodes.Lower(new(region, endpoints, implementationId, - sources.Where(pair => members.Contains(pair.Key)).ToDictionary(), inputs), serialization, context, cancellationToken); + ShaderGraphLoweringResult lowered = m_nodes.Lower( + new( + region, + endpoints, + implementationId, + sources.Where(pair => members.Contains(pair.Key)).ToDictionary(), + inputs + ), + serialization, + context, + cancellationToken + ); diagnostics.AddRange(lowered.diagnostics); if (!lowered.succeeded) + { continue; - var stage = new ShaderIrStage(settings.stage, lowered.block!, inputs.Values, - settings.outputs.Select(static value => new ShaderIrStageOutput(value.id, value.kind, value.semantic ?? "", value.location)), - settings.threadsX, settings.threadsY, settings.threadsZ); + } + var stage = new ShaderIrStage( + settings.stage, + lowered.block!, + inputs.Values, + settings.outputs.Select( + static value => new ShaderIrStageOutput(value.id, value.kind, value.semantic ?? "", value.location) + ), + settings.threadsX, + settings.threadsY, + settings.threadsZ + ); stages.Add(output.id.value, stage); } activeNode = null; @@ -169,7 +237,9 @@ public ShaderGraphProgramResult Lower( continue; } if (!selected.TryAdd(shared.stage, shared)) + { Error("SHADER_PROGRAM_STAGE_DUPLICATE", $"Pass '{pass.name}' repeats stage {shared.stage}."); + } } if (!expected.ToHashSet().SetEquals(selected.Keys)) { @@ -177,12 +247,17 @@ public ShaderGraphProgramResult Lower( continue; } if (pass.programKind == ShaderProgramKind.Raster) + { ValidateVaryings(selected[ShaderStage.Vertex], selected[ShaderStage.Fragment]); + } passes.Add(new(pass.name, expected.Select(stage => selected[stage]))); } } - catch (Exception failure) when (failure is ArgumentException or InvalidOperationException or FormatException or NotSupportedException - && RetirementPendingException.Find(failure) is null) + catch (Exception failure) when (failure is ArgumentException + or InvalidOperationException + or FormatException + or NotSupportedException + && RetirementPendingException.Find(failure) is null) { Error("SHADER_GRAPH_PROGRAM", failure.Message, activeNode); } @@ -192,8 +267,7 @@ void Error( string code, string message, GraphNodeId? node = null - ) - => diagnostics.Add(new(code, DiagnosticSeverity.Error, message, node)); + ) => diagnostics.Add(new(code, DiagnosticSeverity.Error, message, node)); } private void ConnectRasterStages( @@ -209,25 +283,34 @@ SerializationContext context var outputById = outputs.ToDictionary(static node => node.id.value, StringComparer.Ordinal); var stageById = outputs.ToDictionary( static node => node.id.value, - node => ShaderGraphDocument.Read(node, ShaderGraphDocument.settingsKey, - new ShaderGraphStageSettings(), serialization, context).stage, - StringComparer.Ordinal); + node => ShaderGraphDocument.Read( + node, + ShaderGraphDocument.settingsKey, + new ShaderGraphStageSettings(), + serialization, + context + ).stage, + StringComparer.Ordinal + ); string Owner(GraphNodeRecord node) => node.definitionId == ShaderGraphDocument.outputDefinitionId - ? node.id.value - : ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", serialization, context); + ? node.id.value + : ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", serialization, context); - var crossings = graph.edges.Select(edge => - { - GraphNodeRecord source = graph.FindNode(edge.output.nodeId) - ?? throw new InvalidOperationException($"Connection '{edge.id.value}' has no source node."); - GraphNodeRecord destination = graph.FindNode(edge.input.nodeId) - ?? throw new InvalidOperationException($"Connection '{edge.id.value}' has no destination node."); - return (edge, source, destination, sourceOwner: Owner(source), destinationOwner: Owner(destination)); - }) - .Where(static value => value.sourceOwner.Length != 0 && value.destinationOwner.Length != 0 - && value.sourceOwner != value.destinationOwner) + var crossings = graph.edges + .Select(edge => + { + GraphNodeRecord source = graph.FindNode(edge.output.nodeId) + ?? throw new InvalidOperationException($"Connection '{edge.id.value}' has no source node."); + GraphNodeRecord destination = graph.FindNode(edge.input.nodeId) + ?? throw new InvalidOperationException($"Connection '{edge.id.value}' has no destination node."); + return (edge, source, destination, sourceOwner: Owner(source), destinationOwner: Owner(destination)); + }) + .Where(static value => ( + value.sourceOwner.Length != 0 && value.destinationOwner.Length != 0 + && value.sourceOwner != value.destinationOwner + )) .OrderBy(static value => value.sourceOwner, StringComparer.Ordinal) .ThenBy(static value => value.edge.output.nodeId.value, StringComparer.Ordinal) .ThenBy(static value => value.edge.output.portId.value, StringComparer.Ordinal) @@ -236,69 +319,117 @@ string Owner(GraphNodeRecord node) .ThenBy(static value => value.edge.input.portId.value, StringComparer.Ordinal) .ToArray(); if (crossings.Length == 0) + { return; + } var ports = new Dictionary(); foreach (GraphNodeRecord node in graph.nodes.Where(static node => node.definitionId != ShaderGraphDocument.outputDefinitionId)) { sources.TryGetValue(node.id, out ShaderSourceModuleAnalysis? source); ShaderIrStageInput? input = node.definitionId == "inno.shader.stage-input" - ? ShaderGraphDocument.Read(node, ShaderGraphDocument.settingsKey, - new ShaderGraphInputSettings(), serialization, context).CreateBinding() - : null; + ? ShaderGraphDocument.Read( + node, + ShaderGraphDocument.settingsKey, + new ShaderGraphInputSettings(), + serialization, + context + ).CreateBinding() + : null; foreach (ShaderNodePort port in m_nodes.DescribePorts(node, serialization, context, source, implementationId, input)) + { ports.Add(new(node.id, new(port.id)), port); + } } var occupiedLocations = outputs.ToDictionary( static node => node.id.value, - node => ShaderGraphDocument.Read(node, ShaderGraphDocument.settingsKey, - new ShaderGraphStageSettings(), serialization, context).outputs - .Where(static output => output.kind == ShaderIrOutputKind.Varying - && string.Equals(output.semantic, "texcoord", StringComparison.Ordinal)) + node => ShaderGraphDocument.Read( + node, + ShaderGraphDocument.settingsKey, + new ShaderGraphStageSettings(), + serialization, + context + ).outputs + .Where(static output => ( + output.kind == ShaderIrOutputKind.Varying + && string.Equals(output.semantic, "texcoord", StringComparison.Ordinal) + )) .Select(static output => output.location) .ToHashSet(), - StringComparer.Ordinal); + StringComparer.Ordinal + ); var sourceBridges = new Dictionary(); var destinationBridges = new Dictionary<(GraphEndpoint source, string destination), GraphNodeRecord>(); foreach ((GraphEdgeRecord edge, _, _, string sourceOwner, string destinationOwner) in crossings) { if (!stageById.TryGetValue(sourceOwner, out ShaderStage sourceStage)) + { throw new InvalidOperationException( - $"Connection '{edge.id.value}' refers to unavailable source stage '{sourceOwner}'."); + $"Connection '{edge.id.value}' refers to unavailable source stage '{sourceOwner}'." + ); + } if (!stageById.TryGetValue(destinationOwner, out ShaderStage destinationStage)) + { throw new InvalidOperationException( - $"Connection '{edge.id.value}' refers to unavailable destination stage '{destinationOwner}'."); + $"Connection '{edge.id.value}' refers to unavailable destination stage '{destinationOwner}'." + ); + } if (sourceStage != ShaderStage.Vertex || destinationStage != ShaderStage.Fragment) + { throw new InvalidOperationException( - $"Automatic stage transfer supports Vertex-to-Fragment values only; '{edge.id.value}' connects {sourceStage} to {destinationStage}."); + $"Automatic stage transfer supports Vertex-to-Fragment values only; '{edge.id.value}' connects {sourceStage} to {destinationStage}." + ); + } if (!ports.TryGetValue(edge.output, out ShaderNodePort? sourcePort) - || sourcePort.direction != GraphPortDirection.Output) + || sourcePort.direction != GraphPortDirection.Output + ) { throw new InvalidOperationException($"Connection '{edge.id.value}' has no typed source output."); + } if (sourcePort.type.storage is not null - || sourcePort.type.id.StartsWith("sampled-texture", StringComparison.Ordinal)) + || sourcePort.type.id.StartsWith("sampled-texture", StringComparison.Ordinal) + ) { throw new InvalidOperationException( - $"Connection '{edge.id.value}' tries to transfer GPU resource type '{sourcePort.type.id}' between stages."); + $"Connection '{edge.id.value}' tries to transfer GPU resource type '{sourcePort.type.id}' between stages." + ); + } if (!sourceBridges.TryGetValue(edge.output, out (string portId, int location) sourceBridge)) { - string token = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes( - sourceOwner + "\n" + edge.output.nodeId.value + "\n" + edge.output.portId.value)))[..16]; + string token = Convert.ToHexString( + SHA256.HashData( + Encoding.UTF8.GetBytes( + sourceOwner + "\n" + edge.output.nodeId.value + "\n" + edge.output.portId.value + ) + ) + )[..16]; string edgeId = "__stage-bridge-" + token + "/write"; if (graph.edges.Any(value => value.id.value == edgeId)) - throw new InvalidOperationException($"Generated stage bridge identity '{edgeId}' collides with an authored connection."); + { + throw new InvalidOperationException( + $"Generated stage bridge identity '{edgeId}' collides with an authored connection." + ); + } string portId = "bridge_" + token; const string semantic = "texcoord"; HashSet occupied = occupiedLocations[sourceOwner]; int location = Enumerable.Range(0, 16).FirstOrDefault(value => !occupied.Contains(value), -1); if (location < 0) + { throw new InvalidOperationException( - "Automatic Vertex-to-Fragment transfer exhausted the portable texcoord varying locations 0 through 15."); + "Automatic Vertex-to-Fragment transfer exhausted the portable texcoord varying locations 0 through 15." + ); + } occupied.Add(location); GraphNodeRecord sourceOutput = outputById[sourceOwner]; - ShaderGraphStageSettings outputSettings = ShaderGraphDocument.Read(sourceOutput, - ShaderGraphDocument.settingsKey, new ShaderGraphStageSettings(), serialization, context); + ShaderGraphStageSettings outputSettings = ShaderGraphDocument.Read( + sourceOutput, + ShaderGraphDocument.settingsKey, + new ShaderGraphStageSettings(), + serialization, + context + ); outputSettings.outputs = [ .. outputSettings.outputs, @@ -310,12 +441,11 @@ string Owner(GraphNodeRecord node) location = location } ]; - sourceOutput.SetValue(ShaderGraphDocument.settingsKey, - ShaderGraphDocument.Encode(outputSettings, serialization, context)); - graph.AddEdge(new( - new(edgeId), - edge.output, - new(sourceOutput.id, new(portId)))); + sourceOutput.SetValue( + ShaderGraphDocument.settingsKey, + ShaderGraphDocument.Encode(outputSettings, serialization, context) + ); + graph.AddEdge(new(new(edgeId), edge.output, new(sourceOutput.id, new(portId)))); sourceBridge = (portId, location); sourceBridges.Add(edge.output, sourceBridge); } @@ -323,15 +453,25 @@ string Owner(GraphNodeRecord node) var key = (edge.output, destinationOwner); if (!destinationBridges.TryGetValue(key, out GraphNodeRecord? inputNode)) { - string token = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes( - sourceOwner + "\n" + edge.output.nodeId.value + "\n" + edge.output.portId.value + "\n" + destinationOwner)))[..16]; + string token = Convert.ToHexString( + SHA256.HashData( + Encoding.UTF8.GetBytes( + sourceOwner + "\n" + edge.output.nodeId.value + "\n" + edge.output.portId.value + "\n" + destinationOwner + ) + ) + )[..16]; string id = "__stage-bridge-" + token; if (graph.FindNode(new(id)) is not null) + { throw new InvalidOperationException($"Generated stage bridge identity '{id}' collides with an authored node."); + } inputNode = new(new(id), "inno.shader.stage-input"); - inputNode.SetValue(ShaderGraphDocument.stageKey, - ShaderGraphDocument.Encode(destinationOwner, serialization, context)); - inputNode.SetValue(ShaderGraphDocument.settingsKey, + inputNode.SetValue( + ShaderGraphDocument.stageKey, + ShaderGraphDocument.Encode(destinationOwner, serialization, context) + ); + inputNode.SetValue( + ShaderGraphDocument.settingsKey, ShaderGraphDocument.Encode(new ShaderGraphInputSettings { id = sourceBridge.portId, @@ -339,16 +479,16 @@ string Owner(GraphNodeRecord node) kind = ShaderIrInputKind.Varying, semantic = "texcoord", location = sourceBridge.location - }, serialization, context)); + }, serialization, context) + ); graph.AddNode(inputNode); destinationBridges.Add(key, inputNode); } graph.RemoveEdge(edge.id); - graph.AddEdge(new( - new(inputNode.id.value + "/read/" + edge.id.value), - new(inputNode.id, new("value")), - edge.input)); + graph.AddEdge( + new(new(inputNode.id.value + "/read/" + edge.id.value), new(inputNode.id, new("value")), edge.input) + ); } } @@ -358,10 +498,16 @@ ShaderIrStage fragment ) { foreach (ShaderIrStageInput input in fragment.inputs.Where(static input => input.kind == ShaderIrInputKind.Varying)) { - ShaderIrStageOutput? output = vertex.outputs.SingleOrDefault(output => output.kind == ShaderIrOutputKind.Varying - && output.semantic == input.semantic && output.location == input.location); + ShaderIrStageOutput? output = vertex.outputs.SingleOrDefault(output => ( + output.kind == ShaderIrOutputKind.Varying + && output.semantic == input.semantic && output.location == input.location + )); if (output is null || !vertex.body.outputs[output.id].type.IsEquivalentTo(input.type)) - throw new InvalidOperationException($"Fragment varying '{input.semantic}' at {input.location} has no matching vertex output type."); + { + throw new InvalidOperationException( + $"Fragment varying '{input.semantic}' at {input.location} has no matching vertex output type." + ); + } } } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs index 5119c6c9d..520a55d76 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs @@ -16,6 +16,7 @@ public struct ShaderGraphPassProgram /// Gets or sets the exact pass identity in the runtime shader definition. /// public string pass { get; set; } + /// /// Gets or sets stable stage output node identities; computation remains owned by those nodes. /// @@ -51,10 +52,9 @@ public static ShaderGraphPassProgram[] Read( GraphDocument graph, SerializationRegistry serialization, SerializationContext context - ) - => graph.metadata.TryGetValue(bindingsKey, out GraphSerializedValue? data) - ? ShaderGraphDocument.Decode(data, serialization, context) - : throw new InvalidOperationException("The shader document has no pass-to-program references."); + ) => graph.metadata.TryGetValue(bindingsKey, out GraphSerializedValue? data) + ? ShaderGraphDocument.Decode(data, serialization, context) + : throw new InvalidOperationException("The shader document has no pass-to-program references."); /// /// Assigns existing shared stages to one pass in an atomic detached candidate. @@ -87,21 +87,33 @@ SerializationContext context ArgumentNullException.ThrowIfNull(stages); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, serialization, context); if (!definition.passes.Any(value => value.name == pass)) + { throw new ArgumentException($"Unknown pass '{pass}'.", nameof(pass)); + } string[] references = stages.Select(static value => value.value).ToArray(); if (references.Distinct(StringComparer.Ordinal).Count() != references.Length) + { throw new ArgumentException("A pass cannot reference the same stage twice.", nameof(stages)); + } foreach (string id in references) + { if (graph.FindNode(new(id))?.definitionId != ShaderGraphDocument.outputDefinitionId) + { throw new ArgumentException($"Stage program '{id}' is unavailable.", nameof(stages)); + } + } GraphDocument candidate = graph.Clone(); ShaderGraphPassProgram[] bindings = Read(graph, serialization, context); int index = Array.FindIndex(bindings, value => value.pass == pass); var binding = new ShaderGraphPassProgram { pass = pass, stages = references }; if (index < 0) + { bindings = [.. bindings, binding]; + } else + { bindings[index] = binding; + } Write(candidate, bindings, serialization, context); return candidate; } @@ -132,7 +144,9 @@ SerializationContext context ) { ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, serialization, context); if (!definition.passes.Any(value => value.name == pass)) + { throw new ArgumentException($"Unknown pass '{pass}'.", nameof(pass)); + } ShaderGraphPassProgram[] bindings = Read(graph, serialization, context); string[] removedStages = bindings.Where(value => value.pass == pass).SelectMany(static value => value.stages).ToArray(); ShaderGraphPassProgram[] remaining = bindings.Where(value => value.pass != pass).ToArray(); @@ -145,11 +159,20 @@ SerializationContext context technique.passes = technique.passes.Where(value => value.passName != pass).ToArray(); definition.techniques[index] = technique; } - candidate.SetMetadata(ShaderGraphDocument.definitionKey, - ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context)); + candidate.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(serialization.Serialize(definition, context), serialization, context) + ); Write(candidate, remaining, serialization, context); - return ShaderGraphBindings.RemoveNodes(candidate, removedStages.Where(id => !retained.Contains(id)) - .Distinct(StringComparer.Ordinal).Select(static id => new GraphNodeId(id)).Where(id => candidate.FindNode(id) is not null), serialization, context); + return ShaderGraphBindings.RemoveNodes( + candidate, + removedStages.Where(id => !retained.Contains(id)) + .Distinct(StringComparer.Ordinal) + .Select(static id => new GraphNodeId(id)) + .Where(id => candidate.FindNode(id) is not null), + serialization, + context + ); } internal static void Write( @@ -157,6 +180,5 @@ internal static void Write( ShaderGraphPassProgram[] programs, SerializationRegistry serialization, SerializationContext context - ) - => graph.SetMetadata(bindingsKey, ShaderGraphDocument.Encode(programs, serialization, context)); + ) => graph.SetMetadata(bindingsKey, ShaderGraphDocument.Encode(programs, serialization, context)); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs index 40bba1490..c1a8c1b18 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs @@ -28,16 +28,53 @@ public static GraphDocument CreateRaster( SerializationContext context ) { var pass = new ShaderPassDefinition("Main", ShaderProgramKind.Raster, renderState: new() - { cull = ShaderCullMode.None, depthCompare = ShaderCompareFunction.Always, depthWrite = false, blend = RenderBlendState.alpha, colorWriteMask = 15 }); - var definition = new ShaderDefinition("New Shader", [new(new("color"), "Color", ShaderPropertyType.Color, ShaderStage.Fragment, - MaterialValue.FromVector(new Vector4(1f, 1f, 1f, 1f)))], [], [pass]); + { + cull = ShaderCullMode.None, + depthCompare = ShaderCompareFunction.Always, + depthWrite = false, + blend = RenderBlendState.alpha, + colorWriteMask = 15 + }); + var definition = new ShaderDefinition("New Shader", [new( + new("color"), + "Color", + ShaderPropertyType.Color, + ShaderStage.Fragment, + MaterialValue.FromVector(new Vector4(1f, 1f, 1f, 1f)) + )], [], [pass]); GraphDocument graph = ShaderGraphDocument.Create(definition, serialization, context); GraphNodeRecord vertex = Node("vertex", ShaderGraphDocument.outputDefinitionId, 770, 50); - Set(vertex, "settings", new ShaderGraphStageSettings { stage = ShaderStage.Vertex, outputs = [new() { id = "position", kind = ShaderIrOutputKind.ClipPosition }] }); + Set( + vertex, + "settings", + new ShaderGraphStageSettings + { + stage = ShaderStage.Vertex, + outputs = [new() { id = "position", kind = ShaderIrOutputKind.ClipPosition }] + } + ); GraphNodeRecord fragment = Node("fragment", ShaderGraphDocument.outputDefinitionId, 770, 640); - Set(fragment, "settings", new ShaderGraphStageSettings { stage = ShaderStage.Fragment, outputs = [new() { id = "color", kind = ShaderIrOutputKind.Color }] }); + Set( + fragment, + "settings", + new ShaderGraphStageSettings + { + stage = ShaderStage.Fragment, + outputs = [new() { id = "color", kind = ShaderIrOutputKind.Color }] + } + ); GraphNodeRecord position = Node("position", "inno.shader.stage-input", 40, 50, vertex); - Set(position, "settings", new ShaderGraphInputSettings { id = "position", type = new() { id = "float2" }, kind = ShaderIrInputKind.VertexAttribute, semantic = "position" }); + Set( + position, + "settings", + new ShaderGraphInputSettings + { + id = "position", + type = new() { id = "float2" }, + kind = ShaderIrInputKind.VertexAttribute, + semantic = "position" + } + ); GraphNodeRecord construct = Node("clip-position", "inno.shader.construct", 480, 50, vertex); Set(construct, "type", "float4"); for (int index = 0; index < 2; index++) @@ -50,7 +87,11 @@ SerializationContext context } Connect(construct, "value", vertex, "position"); GraphNodeRecord color = Node("color", "inno.shader.stage-input", 480, 920, fragment); - Set(color, "settings", new ShaderGraphInputSettings { id = "color", type = new() { id = "float4" }, kind = ShaderIrInputKind.Uniform, semantic = "" }); + Set( + color, + "settings", + new ShaderGraphInputSettings { id = "color", type = new() { id = "float4" }, kind = ShaderIrInputKind.Uniform, semantic = "" } + ); Connect(color, "value", fragment, "color"); return ShaderGraphPrograms.Bind(graph, "Main", [vertex.id, fragment.id], serialization, context); @@ -63,7 +104,9 @@ GraphNodeRecord Node( ) { var node = new GraphNodeRecord(new(id), type) { position = new(x, y) }; if (stage is not null) + { Set(node, "stage", stage.id.value); + } graph.AddNode(node); return node; } void Set( @@ -76,7 +119,6 @@ void Connect( string output, GraphNodeRecord b, string input - ) - => graph.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(a.id, new(output)), new(b.id, new(input)))); + ) => graph.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(a.id, new(output)), new(b.id, new(input)))); } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs index a1890d072..529b9069c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs @@ -13,46 +13,57 @@ public sealed class ShaderGraphType : ISerializable /// Gets or sets the atomic or nominal structure type identity. /// [SerializableProperty] public string id { get; set; } = "float4"; + /// /// Gets or sets the fixed array element type, or null for a non-array. /// [SerializableProperty] public ShaderGraphType? element { get; set; } + /// /// Gets or sets the fixed array length. /// [SerializableProperty] public int length { get; set; } + /// /// Gets or sets ordered structure member names. /// [SerializableProperty] public string[] fieldNames { get; set; } = []; + /// /// Gets or sets ordered structure member types. /// [SerializableProperty] public ShaderGraphType[] fieldTypes { get; set; } = []; + /// /// Gets or sets whether the descriptor represents a storage binding. /// [SerializableProperty] public bool isStorage { get; set; } + /// /// Gets or sets whether storage is an image instead of a buffer. /// [SerializableProperty] public bool isImage { get; set; } + /// /// Gets or sets the complete buffer element type. /// [SerializableProperty] public ShaderGraphType? storageElement { get; set; } + /// /// Gets or sets storage access. /// [SerializableProperty] public RenderStorageAccess access { get; set; } + /// /// Gets or sets the image texel format. /// [SerializableProperty] public RenderTextureFormat format { get; set; } + /// /// Gets or sets the image spatial dimension. /// [SerializableProperty] public RenderTextureDimension dimension { get; set; } = RenderTextureDimension.Texture2D; + /// /// Gets or sets whether an image has array layers. /// @@ -70,9 +81,14 @@ public sealed class ShaderGraphType : ISerializable public static ShaderGraphType Capture(ShaderSourceType type) { ArgumentNullException.ThrowIfNull(type); - var result = new ShaderGraphType { id = type.id, element = type.elementType is null ? null : Capture(type.elementType), - length = type.elementCount, fieldNames = type.fields.Select(static field => field.name).ToArray(), - fieldTypes = type.fields.Select(static field => Capture(field.type)).ToArray() }; + var result = new ShaderGraphType + { + id = type.id, + element = type.elementType is null ? null : Capture(type.elementType), + length = type.elementCount, + fieldNames = type.fields.Select(static field => field.name).ToArray(), + fieldTypes = type.fields.Select(static field => Capture(field.type)).ToArray() + }; if (type.storage is ShaderStorageType storage) { result.isStorage = true; @@ -81,9 +97,13 @@ public static ShaderGraphType Capture(ShaderSourceType type) result.dimension = storage.dimension; result.isArray = storage.array; if (storage.isImage) + { result.format = storage.format!.Value; + } else + { result.storageElement = Capture(storage.valueType); + } } return result; } @@ -97,27 +117,44 @@ public static ShaderGraphType Capture(ShaderSourceType type) public ShaderSourceType CreateType() { if (fieldNames.Length != fieldTypes.Length) + { throw new InvalidOperationException("Shader structure field names and types differ in length."); + } if (isStorage) { if (element is not null || fieldNames.Length != 0 || length != 0) + { throw new InvalidOperationException("A storage type cannot also be an array or structure."); - return ShaderSourceType.Storage(isImage + } + return ShaderSourceType.Storage( + isImage ? ShaderStorageType.Image(format, access, dimension, isArray) - : ShaderStorageType.Buffer((storageElement ?? throw new InvalidOperationException("A storage buffer requires its element type.")).CreateType(), access)); + : ShaderStorageType.Buffer( + (storageElement ?? throw new InvalidOperationException("A storage buffer requires its element type.")).CreateType(), + access + ) + ); } if (element is not null) { if (fieldNames.Length != 0) + { throw new InvalidOperationException("An array cannot also declare structure fields."); + } return ShaderSourceType.ArrayOf(element.CreateType(), length); } if (length != 0 || storageElement is not null) + { throw new InvalidOperationException("A non-array value contains an unexpected element descriptor."); - return fieldNames.Length == 0 ? ShaderSourceType.Atomic(id) - : ShaderSourceType.Structure(id, fieldNames.Select(( - name, - index - ) => new ShaderSourceField(name, fieldTypes[index].CreateType())).ToArray()); + } + return fieldNames.Length == 0 + ? ShaderSourceType.Atomic(id) + : ShaderSourceType.Structure( + id, + fieldNames.Select(( + name, + index + ) => new ShaderSourceField(name, fieldTypes[index].CreateType())).ToArray() + ); } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs index 57148b37e..ecfaae9ca 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs @@ -21,6 +21,7 @@ ShaderGraphLiteral value writer.Write("type", value.type); writer.Write("scalarBits", value.scalarBits); } + /// /// Reconstructs a complete value through the configured serialization contract. /// @@ -55,6 +56,7 @@ ShaderGraphStageSettings value writer.Write("threadsY", value.threadsY); writer.Write("threadsZ", value.threadsZ); } + /// /// Reconstructs a complete value through the configured serialization contract. /// @@ -64,13 +66,14 @@ ShaderGraphStageSettings value /// /// The validated shader graph stage settings that represents the completed operation. /// - public override ShaderGraphStageSettings Read(SerializationReader reader) => new() + public override ShaderGraphStageSettings Read(SerializationReader reader) + => new() { stage = reader.Read("stage"), outputs = reader.Read("outputs"), threadsX = reader.Read("threadsX"), threadsY = reader.Read("threadsY"), - threadsZ = reader.Read("threadsZ"), + threadsZ = reader.Read("threadsZ") }; } @@ -95,6 +98,7 @@ ShaderGraphInputSettings value writer.Write("semantic", value.semantic); writer.Write("location", value.location); } + /// /// Reconstructs a complete value through the configured serialization contract. /// @@ -104,13 +108,14 @@ ShaderGraphInputSettings value /// /// The validated shader graph input settings that represents the completed operation. /// - public override ShaderGraphInputSettings Read(SerializationReader reader) => new() + public override ShaderGraphInputSettings Read(SerializationReader reader) + => new() { id = reader.Read("id"), type = reader.Read("type"), kind = reader.Read("kind"), semantic = reader.Read("semantic"), - location = reader.Read("location"), + location = reader.Read("location") }; } @@ -143,7 +148,8 @@ ShaderGraphNodePortDefinition value /// /// The validated shader graph node port definition that represents the completed operation. /// - public override ShaderGraphNodePortDefinition Read(SerializationReader reader) => new() + public override ShaderGraphNodePortDefinition Read(SerializationReader reader) + => new() { id = reader.Read("id"), type = reader.Read("type"), @@ -183,7 +189,8 @@ ShaderGraphNodeSettings value /// /// The validated shader graph node settings that represents the completed operation. /// - public override ShaderGraphNodeSettings Read(SerializationReader reader) => new() + public override ShaderGraphNodeSettings Read(SerializationReader reader) + => new() { displayName = reader.Read("displayName"), createPath = reader.Read("createPath"), @@ -219,7 +226,8 @@ ShaderGraphNodeInputSettings value /// /// The validated shader graph node input settings that represents the completed operation. /// - public override ShaderGraphNodeInputSettings Read(SerializationReader reader) => new() + public override ShaderGraphNodeInputSettings Read(SerializationReader reader) + => new() { ports = reader.Read("ports") }; @@ -288,7 +296,8 @@ ShaderGraphNodeInterface value /// /// The validated shader graph node interface that represents the completed operation. /// - public override ShaderGraphNodeInterface Read(SerializationReader reader) => new() + public override ShaderGraphNodeInterface Read(SerializationReader reader) + => new() { displayName = reader.Read("displayName"), createPath = reader.Read("createPath"), @@ -329,6 +338,7 @@ ShaderGraphType value writer.Write("dimension", value.dimension); writer.Write("isArray", value.isArray); } + /// /// Reconstructs a complete value through the configured serialization contract. /// @@ -338,7 +348,8 @@ ShaderGraphType value /// /// The validated shader graph type that represents the completed operation. /// - public override ShaderGraphType Read(SerializationReader reader) => new() + public override ShaderGraphType Read(SerializationReader reader) + => new() { id = reader.Read("id"), element = reader.Read("element"), @@ -351,6 +362,6 @@ ShaderGraphType value access = reader.Read("access"), format = reader.Read("format"), dimension = reader.Read("dimension"), - isArray = reader.Read("isArray"), + isArray = reader.Read("isArray") }; } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs index bd7aa9f7d..c96580d80 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs @@ -24,10 +24,12 @@ ShaderSourceType type /// Gets the deterministic block-local value index, not a GPU register or resource slot. /// public int index { get; } + /// /// Gets the complete language-independent value type. /// public ShaderSourceType type { get; } + internal object owner { get; } } @@ -159,40 +161,49 @@ internal ShaderIrInstruction( /// Gets the semantic operation independent of any source language. /// public ShaderIrOperation operation { get; } + /// /// Gets immutable operands in operation or function-declaration order. /// public IReadOnlyList inputs { get; } + /// /// Gets produced values; a call orders its return value first, then out/inout parameters. /// public IReadOnlyList outputs { get; } + /// /// Gets the stable interface or region-parameter identity, only for Input or RegionInput. /// public string? inputName { get; } + /// /// Gets exact scalar bits for a Constant instruction; the result type determines interpretation. /// public ulong constantBits { get; } + /// /// Gets the zero-based component/member/element ordinal for an Extract instruction. /// public int memberIndex { get; } + /// /// Gets a frozen, analyzed function implementation only for a SourceCall instruction. /// public ShaderSourceImplementationAnalysis? source { get; } + /// /// Gets immutable nested regions: true/false for Branch, or one body for Loop. /// public IReadOnlyList regions { get; } + /// /// Gets whether removing or reordering this instruction may change observable behavior. /// - public bool hasSideEffects => operation is ShaderIrOperation.SourceCall or ShaderIrOperation.StorageLoad - or ShaderIrOperation.StorageStore or ShaderIrOperation.StorageAtomicAdd or ShaderIrOperation.Discard - or ShaderIrOperation.Branch or ShaderIrOperation.Loop; + public bool hasSideEffects + => operation is ShaderIrOperation.SourceCall or ShaderIrOperation.StorageLoad + or ShaderIrOperation.StorageStore or ShaderIrOperation.StorageAtomicAdd or ShaderIrOperation.Discard + or ShaderIrOperation.Branch or ShaderIrOperation.Loop; } /// @@ -205,13 +216,16 @@ internal ShaderIrBlock( IReadOnlyDictionary outputs ) { this.instructions = Array.AsReadOnly(instructions.ToArray()); - this.outputs = new ReadOnlyDictionary(new Dictionary(outputs, StringComparer.Ordinal)); + this.outputs = new ReadOnlyDictionary( + new Dictionary(outputs, StringComparer.Ordinal) + ); } /// /// Gets instructions in evaluation order, including source calls whose outputs are unused. /// public IReadOnlyList instructions { get; } + /// /// Gets named values returned to the enclosing stage or region. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.ControlFlow.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.ControlFlow.cs index 358468e81..bb5ff152c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.ControlFlow.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.ControlFlow.cs @@ -40,7 +40,9 @@ Func> whenFalse ArgumentNullException.ThrowIfNull(whenTrue); ArgumentNullException.ThrowIfNull(whenFalse); if (!condition.type.IsEquivalentTo(ShaderSourceType.Atomic("bool"))) + { throw new ArgumentException("A branch condition must be bool.", nameof(condition)); + } int nextValue = m_root.m_nextValue; try { @@ -88,13 +90,18 @@ Func, ArgumentNullException.ThrowIfNull(initialState); ArgumentNullException.ThrowIfNull(body); if (!iterations.type.IsEquivalentTo(ShaderSourceType.Atomic("uint"))) + { throw new ArgumentException("A loop count must be uint.", nameof(iterations)); + } foreach ((string name, ShaderIrValue value) in initialState) { ArgumentException.ThrowIfNullOrWhiteSpace(name); RequireOwned(value); } - var initial = new SortedDictionary(initialState.ToDictionary(static pair => pair.Key, static pair => pair.Value), StringComparer.Ordinal); + var initial = new SortedDictionary( + initialState.ToDictionary(static pair => pair.Key, static pair => pair.Value), + StringComparer.Ordinal + ); int nextValue = m_root.m_nextValue; try { @@ -103,7 +110,9 @@ Func, ShaderIrValue index = builder.RegionInput("iteration", ShaderSourceType.Atomic("uint")); var carried = new Dictionary(StringComparer.Ordinal); foreach ((string name, ShaderIrValue value) in initial) + { carried.Add(name, builder.RegionInput("state." + name, value.type)); + } return body(builder, index, new ReadOnlyDictionary(carried)); }); ValidateOutputs(initial, region.outputs); @@ -148,7 +157,9 @@ private IReadOnlyDictionary MergeValues(IReadOnlyDictiona foreach ((string name, ShaderIrValue value) in contract.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) { if (value.type.storage is not null || value.type.id.StartsWith("sampled-texture", StringComparison.Ordinal)) + { throw new ArgumentException("Resource bindings cannot be merged or loop-carried as ordinary values."); + } values.Add(name, NewValue(value.type)); } return new ReadOnlyDictionary(values); @@ -158,7 +169,10 @@ private static void ValidateOutputs( IReadOnlyDictionary expected, IReadOnlyDictionary actual ) { - if (expected.Count != actual.Count || expected.Any(pair => !actual.TryGetValue(pair.Key, out ShaderIrValue? value) || !pair.Value.type.IsEquivalentTo(value.type))) + if (expected.Count != actual.Count + || expected.Any(pair => !actual.TryGetValue(pair.Key, out ShaderIrValue? value) || !pair.Value.type.IsEquivalentTo(value.type)) + ) { throw new ArgumentException("Control-flow regions require identical named output types."); + } } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.Resources.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.Resources.cs index c98de6941..223fadb57 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.Resources.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.Resources.cs @@ -59,7 +59,9 @@ ShaderIrValue level ValidateSample(texture, coordinate); RequireOwned(level); if (!level.type.IsEquivalentTo(ShaderSourceType.Atomic("float"))) + { throw new ArgumentException("A mip level must be float.", nameof(level)); + } ShaderIrValue output = NewValue(ShaderSourceType.Atomic("float4")); m_instructions.Add(new(ShaderIrOperation.TextureSampleLevel, [texture, coordinate, level], [output])); return output; @@ -86,7 +88,9 @@ ShaderIrValue coordinate ) { ShaderStorageType storage = ValidateStorage(resource, coordinate); if (storage.access == RenderStorageAccess.Write) + { throw new ArgumentException("A write-only resource cannot be loaded.", nameof(resource)); + } ShaderIrValue output = NewValue(storage.valueType); m_instructions.Add(new(ShaderIrOperation.StorageLoad, [resource, coordinate], [output])); return output; @@ -115,7 +119,9 @@ ShaderIrValue value ShaderStorageType storage = ValidateStorage(resource, coordinate); RequireOwned(value); if (storage.access == RenderStorageAccess.Read || !storage.valueType.IsEquivalentTo(value.type)) + { throw new ArgumentException("A store requires a writable resource and its exact element type.", nameof(resource)); + } m_instructions.Add(new(ShaderIrOperation.StorageStore, [resource, coordinate, value], [])); } @@ -145,9 +151,12 @@ ShaderIrValue value ShaderStorageType storage = ValidateStorage(resource, index); RequireOwned(value); if (storage.isImage || storage.access != RenderStorageAccess.ReadWrite - || !(storage.valueType.IsEquivalentTo(ShaderSourceType.Atomic("int")) || storage.valueType.IsEquivalentTo(ShaderSourceType.Atomic("uint"))) - || !storage.valueType.IsEquivalentTo(value.type)) + || !(storage.valueType.IsEquivalentTo(ShaderSourceType.Atomic("int")) + || storage.valueType.IsEquivalentTo(ShaderSourceType.Atomic("uint"))) + || !storage.valueType.IsEquivalentTo(value.type) + ) { throw new ArgumentException("Atomic add requires a read-write scalar integer buffer.", nameof(resource)); + } ShaderIrValue output = NewValue(storage.valueType); m_instructions.Add(new(ShaderIrOperation.StorageAtomicAdd, [resource, index, value], [output])); return output; @@ -166,7 +175,9 @@ public void Discard(ShaderIrValue condition) { RequireOwned(condition); if (!condition.type.IsEquivalentTo(ShaderSourceType.Atomic("bool"))) + { throw new ArgumentException("Discard requires bool.", nameof(condition)); + } m_instructions.Add(new(ShaderIrOperation.Discard, [condition], [])); } @@ -177,7 +188,9 @@ ShaderIrValue coordinate RequireOwned(texture); RequireOwned(coordinate); if (!texture.type.IsEquivalentTo(ShaderSourceType.Atomic(texture.type.id))) + { throw new ArgumentException("A sampled binding cannot be disguised as an aggregate.", nameof(texture)); + } string type = texture.type.id switch { "sampled-texture2d" => "float2", @@ -185,7 +198,9 @@ ShaderIrValue coordinate _ => throw new ArgumentException("Sampling requires a supported sampled texture type.", nameof(texture)) }; if (!coordinate.type.IsEquivalentTo(ShaderSourceType.Atomic(type))) + { throw new ArgumentException($"Sampling requires a {type} coordinate.", nameof(coordinate)); + } } private ShaderStorageType ValidateStorage( @@ -194,10 +209,15 @@ ShaderIrValue coordinate ) { RequireOwned(resource); RequireOwned(coordinate); - ShaderStorageType storage = resource.type.storage ?? throw new ArgumentException("A typed storage binding is required.", nameof(resource)); - string coordinateType = !storage.isImage ? "uint" : storage.array || storage.dimension == RenderTextureDimension.Texture3D ? "int3" : "int2"; + ShaderStorageType storage = resource.type.storage + ?? throw new ArgumentException("A typed storage binding is required.", nameof(resource)); + string coordinateType = !storage.isImage + ? "uint" + : storage.array || storage.dimension == RenderTextureDimension.Texture3D ? "int3" : "int2"; if (!coordinate.type.IsEquivalentTo(ShaderSourceType.Atomic(coordinateType))) + { throw new ArgumentException($"This resource requires a {coordinateType} coordinate.", nameof(coordinate)); + } return storage; } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs index 157000345..9db82bff5 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs @@ -52,13 +52,17 @@ ShaderSourceType type ) { EnsureWritable(); if (m_parent is not null) + { throw new InvalidOperationException("Stage inputs must be declared in the root region and captured by nested regions."); + } ArgumentException.ThrowIfNullOrWhiteSpace(name); RequireValueType(type); if (m_inputs.TryGetValue(name, out ShaderIrValue? previous)) { if (!type.IsEquivalentTo(previous.type)) + { throw new ArgumentException($"Input '{name}' changed type.", nameof(type)); + } return previous; } ShaderIrValue output = NewValue(type); @@ -82,7 +86,9 @@ ShaderSourceType type public ShaderIrValue Constant(float value) { if (!float.IsFinite(value)) + { throw new ArgumentOutOfRangeException(nameof(value), "Shader constants must be finite."); + } return ConstantBits("float", BitConverter.SingleToUInt32Bits(value)); } @@ -145,20 +151,24 @@ ShaderIrValue right RequireOwned(left); RequireOwned(right); if (!left.type.IsEquivalentTo(right.type)) + { throw new ArgumentException("Binary operands require identical types; conversions must be explicit.", nameof(right)); + } bool numeric = TryNumeric(left.type, out string scalar, out int columns, out int rows); bool scalarValue = columns == 1 && rows == 1; bool comparison = operation is ShaderIrOperation.Equal or ShaderIrOperation.LessThan; bool permitted = operation switch { ShaderIrOperation.Add or ShaderIrOperation.Subtract or ShaderIrOperation.Multiply or ShaderIrOperation.Divide - or ShaderIrOperation.Minimum or ShaderIrOperation.Maximum => numeric && scalar != "bool", + or ShaderIrOperation.Minimum or ShaderIrOperation.Maximum => numeric && scalar != "bool", ShaderIrOperation.Equal => numeric && scalarValue, ShaderIrOperation.LessThan => numeric && scalarValue && scalar != "bool", _ => false }; if (!permitted) + { throw new ArgumentException($"Operation '{operation}' is not defined for '{left.type.id}'.", nameof(operation)); + } ShaderIrValue output = NewValue(comparison ? ShaderSourceType.Atomic("bool") : left.type); m_instructions.Add(new(operation, [left, right], [output])); return output; @@ -191,9 +201,13 @@ ShaderIrValue whenFalse RequireOwned(whenTrue); RequireOwned(whenFalse); if (whenTrue.type.storage is not null || whenTrue.type.id.StartsWith("sampled-texture", StringComparison.Ordinal)) + { throw new ArgumentException("Resource bindings cannot be selected as ordinary values.", nameof(whenTrue)); + } if (!condition.type.IsEquivalentTo(ShaderSourceType.Atomic("bool")) || !whenTrue.type.IsEquivalentTo(whenFalse.type)) + { throw new ArgumentException("Selection requires a scalar bool and two values of identical type."); + } ShaderIrValue output = NewValue(whenTrue.type); m_instructions.Add(new(ShaderIrOperation.Select, [condition, whenTrue, whenFalse], [output])); return output; @@ -221,21 +235,33 @@ params ShaderIrValue[] members RequireValueType(type); ArgumentNullException.ThrowIfNull(members); foreach (ShaderIrValue member in members) + { RequireOwned(member); + } ShaderSourceType[] expected; if (type.elementType is not null) + { expected = Enumerable.Repeat(type.elementType, type.elementCount).ToArray(); + } else if (type.fields.Count != 0) + { expected = type.fields.Select(static field => field.type).ToArray(); + } else if (TryNumeric(type, out string scalar, out int columns, out int rows) && columns * rows > 1) + { expected = Enumerable.Repeat(ShaderSourceType.Atomic(scalar), columns * rows).ToArray(); + } else + { throw new ArgumentException("Construction requires a vector, matrix, structure or array type.", nameof(type)); + } if (expected.Length != members.Length || expected.Where(( value, index - ) => !value.IsEquivalentTo(members[index].type)).Any()) + ) => !value.IsEquivalentTo(members[index].type)).Any() + ) { throw new ArgumentException("Aggregate members do not match the complete type layout.", nameof(members)); + } ShaderIrValue output = NewValue(type); m_instructions.Add(new(ShaderIrOperation.Construct, members, [output])); return output; @@ -277,7 +303,9 @@ int memberIndex { count = type.fields.Count; if (memberIndex >= count) + { throw new ArgumentOutOfRangeException(nameof(memberIndex)); + } memberType = type.fields[memberIndex].type; } else if (TryNumeric(type, out string scalar, out int columns, out int rows) && columns * rows > 1) @@ -286,9 +314,13 @@ int memberIndex memberType = ShaderSourceType.Atomic(rows == 1 ? scalar : scalar + rows); } else + { throw new ArgumentException("Extraction requires a vector, matrix, structure or array.", nameof(value)); + } if (memberIndex >= count) + { throw new ArgumentOutOfRangeException(nameof(memberIndex)); + } ShaderIrValue output = NewValue(memberType); m_instructions.Add(new(ShaderIrOperation.Extract, [value], [output], memberIndex: memberIndex)); return output; @@ -322,29 +354,47 @@ IReadOnlyDictionary inputs ArgumentException.ThrowIfNullOrWhiteSpace(implementationId); ArgumentNullException.ThrowIfNull(inputs); if (!module.succeeded) + { throw new ArgumentException("A source call requires a fully validated module interface.", nameof(module)); - ShaderSourceImplementationAnalysis source = module.implementations.FirstOrDefault(value => value.implementationId == implementationId) + } + ShaderSourceImplementationAnalysis source = module.implementations.FirstOrDefault( + value => value.implementationId == implementationId + ) ?? throw new ArgumentException($"Implementation '{implementationId}' is not part of this module.", nameof(implementationId)); ShaderSourceFunction function = source.analysis.function!; - ShaderSourceParameter[] parameters = function.parameters.Where(static value => value.direction != ShaderSourceParameterDirection.Output).ToArray(); + ShaderSourceParameter[] parameters = function.parameters + .Where(static value => value.direction != ShaderSourceParameterDirection.Output) + .ToArray(); if (parameters.Length != inputs.Count) + { throw new ArgumentException("Source inputs must match every input/inout parameter exactly.", nameof(inputs)); + } var operands = new List(); foreach (ShaderSourceParameter parameter in parameters) { if (!inputs.TryGetValue(parameter.name, out ShaderIrValue? value)) + { throw new ArgumentException($"Missing source input '{parameter.name}'.", nameof(inputs)); + } RequireOwned(value); if (!value.type.IsEquivalentTo(parameter.type)) + { throw new ArgumentException($"Source input '{parameter.name}' does not match its declared type.", nameof(inputs)); + } operands.Add(value); } var outputs = new Dictionary(StringComparer.Ordinal); if (function.returnType.id != "void") + { outputs.Add("return", NewValue(function.returnType)); + } foreach (ShaderSourceParameter parameter in function.parameters) + { if (parameter.direction != ShaderSourceParameterDirection.Input) + { outputs.Add("output." + parameter.name, NewValue(parameter.type)); + } + } m_instructions.Add(new(ShaderIrOperation.SourceCall, operands, outputs.Values, source: source)); return new ReadOnlyDictionary(outputs); } @@ -392,24 +442,34 @@ internal void RequireOwned(ShaderIrValue value) EnsureWritable(); ArgumentNullException.ThrowIfNull(value); for (ShaderIrBuilder? scope = this; scope is not null; scope = scope.m_parent) + { if (ReferenceEquals(value.owner, scope.m_owner)) + { return; + } + } throw new ArgumentException("The value is outside this region's visible scope.", nameof(value)); } private void EnsureWritable() { if (m_closed) + { throw new InvalidOperationException("A completed nested region cannot be edited after its callback returns."); + } if (m_buildingChild) + { throw new InvalidOperationException("An enclosing builder cannot be mutated while its nested region is being constructed."); + } } private static void RequireValueType(ShaderSourceType type) { ArgumentNullException.ThrowIfNull(type); if (type.id == "void") + { throw new ArgumentException("Void is not a value type.", nameof(type)); + } } private static bool TryNumeric( @@ -421,11 +481,15 @@ out int rows scalar = string.Empty; columns = rows = 1; if (type.elementType is not null || type.fields.Count != 0) + { return false; + } foreach (string name in new[] { "float", "int", "uint", "bool" }) { if (!type.id.StartsWith(name, StringComparison.Ordinal)) + { continue; + } ReadOnlySpan shape = type.id.AsSpan(name.Length); if (shape.Length == 0) { diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs index e3116b7e4..8f6a6c6f2 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs @@ -46,7 +46,9 @@ void WriteBlock(ShaderIrBlock block) writer.Write((int)instruction.operation); writer.Write(instruction.inputs.Count); foreach (ShaderIrValue input in instruction.inputs) + { writer.Write(input.index); + } writer.Write(instruction.outputs.Count); foreach (ShaderIrValue output in instruction.outputs) { @@ -59,7 +61,9 @@ void WriteBlock(ShaderIrBlock block) writer.Write(instruction.source?.contentHash ?? string.Empty); writer.Write(instruction.regions.Count); foreach (ShaderIrBlock region in instruction.regions) + { WriteBlock(region); + } } writer.Write(block.outputs.Count); foreach (var output in block.outputs.OrderBy(static value => value.Key, StringComparer.Ordinal)) @@ -75,7 +79,9 @@ void WriteType(ShaderSourceType type) writer.Write(type.elementCount); writer.Write(type.elementType is not null); if (type.elementType is not null) + { WriteType(type.elementType); + } writer.Write(type.fields.Count); foreach (ShaderSourceField field in type.fields) { diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs index c9912c7b7..4fcddea1c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs @@ -93,11 +93,18 @@ public ShaderIrStageInput( ArgumentNullException.ThrowIfNull(type); ArgumentOutOfRangeException.ThrowIfNegative(location); if (type.id == "void" || !Enum.IsDefined(kind)) + { throw new ArgumentException("A stage input requires a value type and defined interface kind."); - if (kind == ShaderIrInputKind.SampledTexture && (type.fields.Count != 0 || type.elementType is not null || type.storage is not null)) + } + if (kind == ShaderIrInputKind.SampledTexture + && (type.fields.Count != 0 || type.elementType is not null || type.storage is not null) + ) { throw new ArgumentException("A sampled texture binding requires an opaque atomic resource type.", nameof(type)); + } if (kind is ShaderIrInputKind.VertexAttribute or ShaderIrInputKind.Varying or ShaderIrInputKind.Builtin) + { ArgumentException.ThrowIfNullOrWhiteSpace(semantic); + } this.id = id; this.type = type; this.kind = kind; @@ -109,18 +116,22 @@ public ShaderIrStageInput( /// Gets the logical binding identity. /// public string id { get; } + /// /// Gets the complete typed value received by the stage. /// public ShaderSourceType type { get; } + /// /// Gets the GPU input category. /// public ShaderIrInputKind kind { get; } + /// /// Gets the target semantic; an adapter must reject unsupported semantics. /// public string semantic { get; } + /// /// Gets the target-assigned interface location or sampled-texture slot. /// @@ -156,9 +167,13 @@ public ShaderIrStageOutput( ArgumentException.ThrowIfNullOrWhiteSpace(id); ArgumentOutOfRangeException.ThrowIfNegative(location); if (!Enum.IsDefined(kind)) + { throw new ArgumentException("A stage output requires a defined destination kind.", nameof(kind)); + } if (kind == ShaderIrOutputKind.Varying) + { ArgumentException.ThrowIfNullOrWhiteSpace(semantic); + } this.id = id; this.kind = kind; this.semantic = semantic; @@ -169,14 +184,17 @@ public ShaderIrStageOutput( /// Gets the exact block output identity. /// public string id { get; } + /// /// Gets the GPU output category. /// public ShaderIrOutputKind kind { get; } + /// /// Gets the varying semantic, not native assignment syntax. /// public string semantic { get; } + /// /// Gets the target-assigned varying or attachment index. /// @@ -226,9 +244,16 @@ public ShaderIrStage( ArgumentNullException.ThrowIfNull(inputs); ArgumentNullException.ThrowIfNull(outputs); if (stage is not (ShaderStage.Vertex or ShaderStage.Fragment or ShaderStage.Compute)) + { throw new ArgumentException("A single programmable stage is required.", nameof(stage)); - if (threadsX <= 0 || threadsY <= 0 || threadsZ <= 0 || (stage != ShaderStage.Compute && (threadsX != 1 || threadsY != 1 || threadsZ != 1))) + } + if (threadsX <= 0 + || threadsY <= 0 + || threadsZ <= 0 + || (stage != ShaderStage.Compute && (threadsX != 1 || threadsY != 1 || threadsZ != 1)) + ) { throw new ArgumentException("Workgroup dimensions must be positive and apply only to compute stages."); + } this.inputs = Array.AsReadOnly(inputs.ToArray()); this.outputs = Array.AsReadOnly(outputs.ToArray()); this.stage = stage; @@ -244,30 +269,37 @@ public ShaderIrStage( /// Gets the programmable stage. /// public ShaderStage stage { get; } + /// /// Gets its immutable ordered instructions. /// public ShaderIrBlock body { get; } + /// /// Gets all input bindings. /// public IReadOnlyList inputs { get; } + /// /// Gets all output destinations. /// public IReadOnlyList outputs { get; } + /// /// Gets the compute workgroup X size. /// public int threadsX { get; } + /// /// Gets the compute workgroup Y size. /// public int threadsY { get; } + /// /// Gets the compute workgroup Z size. /// public int threadsZ { get; } + /// /// Gets a deterministic hash of stage semantics, ordered effects, nested regions, complete types, resource layout and frozen sources. /// A compiled artifact cache must additionally include toolchain identity, target capabilities, optimization and variant configuration. @@ -282,25 +314,41 @@ private void Validate() { ArgumentNullException.ThrowIfNull(input); if (!bindings.TryAdd(input.id, input)) + { throw new ArgumentException($"Duplicate stage input '{input.id}'."); + } if ((input.type.storage is not null) != (input.kind == ShaderIrInputKind.Storage)) + { throw new ArgumentException("Storage types require storage bindings, and storage bindings require complete storage types."); + } string semantic = input.kind is ShaderIrInputKind.SampledTexture or ShaderIrInputKind.Storage ? string.Empty : input.semantic; if (input.kind != ShaderIrInputKind.Uniform && !occupied.Add((input.kind, semantic, input.location))) + { throw new ArgumentException($"Two stage inputs alias the same {input.kind} location."); + } if ((input.kind == ShaderIrInputKind.VertexAttribute && stage != ShaderStage.Vertex) - || (input.kind == ShaderIrInputKind.Varying && stage != ShaderStage.Fragment)) + || (input.kind == ShaderIrInputKind.Varying && stage != ShaderStage.Fragment) + ) { throw new ArgumentException($"{input.kind} is not an input of the {stage} stage."); + } } ShaderIrInstruction[] reads = body.instructions.Where(static value => value.operation == ShaderIrOperation.Input).ToArray(); if (reads.Length != bindings.Count) + { throw new ArgumentException("The stage interface must describe exactly every body input."); + } foreach (ShaderIrInstruction read in reads) + { if (!bindings.TryGetValue(read.inputName!, out ShaderIrStageInput? input) || !input.type.IsEquivalentTo(read.outputs[0].type)) + { throw new ArgumentException($"Stage input '{read.inputName}' has a missing or incompatible binding."); + } + } if (stage != ShaderStage.Fragment && RequiresFragment(body)) + { throw new ArgumentException("Implicit-derivative texture sampling and discard are fragment-only operations."); + } var names = new HashSet(StringComparer.Ordinal); var destinations = new HashSet<(ShaderIrOutputKind, string, int)>(); @@ -308,28 +356,51 @@ private void Validate() { ArgumentNullException.ThrowIfNull(output); if (!names.Add(output.id) || !destinations.Add((output.kind, output.semantic, output.location))) + { throw new ArgumentException("Stage output identities and destinations must be unique."); + } if (!body.outputs.TryGetValue(output.id, out ShaderIrValue? value)) + { throw new ArgumentException($"Missing body output '{output.id}'."); + } bool vertexOutput = output.kind is ShaderIrOutputKind.ClipPosition or ShaderIrOutputKind.Varying; if (stage == ShaderStage.Compute || vertexOutput != (stage == ShaderStage.Vertex)) + { throw new ArgumentException($"{output.kind} is not an output of the {stage} stage."); - if (output.kind is ShaderIrOutputKind.ClipPosition or ShaderIrOutputKind.Color && !value.type.IsEquivalentTo(ShaderSourceType.Atomic("float4"))) + } + if (output.kind is ShaderIrOutputKind.ClipPosition or ShaderIrOutputKind.Color + && !value.type.IsEquivalentTo(ShaderSourceType.Atomic("float4")) + ) { throw new ArgumentException($"{output.kind} requires float4."); + } if (output.kind == ShaderIrOutputKind.Depth && !value.type.IsEquivalentTo(ShaderSourceType.Atomic("float"))) + { throw new ArgumentException("Depth requires float."); - if (output.kind is ShaderIrOutputKind.Depth or ShaderIrOutputKind.ClipPosition && (output.location != 0 || output.semantic.Length != 0)) + } + if (output.kind is ShaderIrOutputKind.Depth or ShaderIrOutputKind.ClipPosition + && (output.location != 0 || output.semantic.Length != 0) + ) { throw new ArgumentException("Position and depth have exactly one fixed destination."); + } if (output.kind == ShaderIrOutputKind.Color && output.semantic.Length != 0) + { throw new ArgumentException("Color attachments are addressed only by location."); + } } if (names.Count != body.outputs.Count) + { throw new ArgumentException("Every body output requires a GPU destination."); + } if (stage == ShaderStage.Vertex && !outputs.Any(static value => value.kind == ShaderIrOutputKind.ClipPosition)) + { throw new ArgumentException("A vertex stage must write clip position."); + } } private static bool RequiresFragment(ShaderIrBlock block) - => block.instructions.Any(static instruction => instruction.operation is ShaderIrOperation.TextureSample or ShaderIrOperation.Discard - || instruction.regions.Any(RequiresFragment)); + => block.instructions.Any(static instruction => ( + instruction.operation is ShaderIrOperation.TextureSample + or ShaderIrOperation.Discard + || instruction.regions.Any(RequiresFragment) + )); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderStorageType.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderStorageType.cs index 672891cd0..889968412 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderStorageType.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderStorageType.cs @@ -16,7 +16,9 @@ private ShaderStorageType( bool array ) { if (!Enum.IsDefined(access)) + { throw new ArgumentOutOfRangeException(nameof(access)); + } this.valueType = valueType; this.access = access; this.format = format; @@ -28,22 +30,27 @@ bool array /// Gets the buffer element or image load/store value type; image operations use float4. /// public ShaderSourceType valueType { get; } + /// /// Gets the permitted memory access, independent of Render Graph scheduling. /// public RenderStorageAccess access { get; } + /// /// Gets the exact storage image format, or null for a structured buffer. /// public RenderTextureFormat? format { get; } + /// /// Gets the image dimension; ignored for buffers. /// public RenderTextureDimension dimension { get; } + /// /// Gets whether a two-dimensional storage image has array layers. /// public bool array { get; } + /// /// Gets whether this descriptor denotes an image rather than a structured buffer. /// @@ -100,10 +107,16 @@ public static ShaderStorageType Image( RenderTextureDimension dimension = RenderTextureDimension.Texture2D, bool array = false ) { - if (!Enum.IsDefined(format) || format is RenderTextureFormat.RGBA8Srgb or RenderTextureFormat.Depth24Stencil8 or RenderTextureFormat.Depth32Float) + if (!Enum.IsDefined(format) + || format is RenderTextureFormat.RGBA8Srgb or RenderTextureFormat.Depth24Stencil8 or RenderTextureFormat.Depth32Float + ) { throw new ArgumentException("A storage image requires a linear color format.", nameof(format)); - if (dimension is not (RenderTextureDimension.Texture2D or RenderTextureDimension.Texture3D) || (array && dimension != RenderTextureDimension.Texture2D)) + } + if (dimension is not (RenderTextureDimension.Texture2D or RenderTextureDimension.Texture3D) + || (array && dimension != RenderTextureDimension.Texture2D) + ) { throw new ArgumentException("Storage images support 2D, 2D array or 3D shapes.", nameof(dimension)); + } return new(ShaderSourceType.Atomic("float4"), access, format, dimension, array); } @@ -118,15 +131,21 @@ public static ShaderStorageType Image( /// public bool IsEquivalentTo(ShaderStorageType? other) => other is not null && access == other.access && format == other.format && dimension == other.dimension - && array == other.array && valueType.IsEquivalentTo(other.valueType); + && array == other.array && valueType.IsEquivalentTo(other.valueType); private static void ValidateElement(ShaderSourceType type) { if (type.id == "void" || type.storage is not null || type.id.StartsWith("sampled-texture", StringComparison.Ordinal)) + { throw new ArgumentException("Storage elements cannot contain void or resource handles."); + } if (type.elementType is not null) + { ValidateElement(type.elementType); + } foreach (ShaderSourceField field in type.fields) + { ValidateElement(field.type); + } } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs index 34b064e35..2d235992c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs @@ -115,20 +115,27 @@ public ShaderSourceRequest( this.entryPoint = entryPoint; this.resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); this.defines = new System.Collections.ObjectModel.ReadOnlyDictionary( - defines is null ? new Dictionary(StringComparer.Ordinal) : new Dictionary(defines, StringComparer.Ordinal)); + defines is null + ? new Dictionary(StringComparer.Ordinal) + : new Dictionary(defines, StringComparer.Ordinal) + ); } + /// /// Gets the root source snapshot. /// public ShaderSourceFile source { get; } + /// /// Gets the explicitly selected export function name. /// public string entryPoint { get; } + /// /// Gets the candidate-scoped dependency resolver. /// public IShaderSourceResolver resolver { get; } + /// /// Gets immutable preprocessing inputs included in analysis cache identity. /// @@ -163,18 +170,22 @@ IEnumerable diagnostics this.dependencies = Array.AsReadOnly(dependencies.Distinct(StringComparer.Ordinal).ToArray()); this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); } + /// /// Gets the parsed interface, or null after an analysis failure. /// public ShaderSourceFunction? function { get; } + /// /// Gets original source dependencies for invalidation. /// public IReadOnlyList dependencies { get; } + /// /// Gets immutable, provider-neutral diagnostics. /// public IReadOnlyList diagnostics { get; } + /// /// Gets whether a usable interface was found without errors. /// @@ -190,6 +201,7 @@ public interface IShaderSourceFrontend /// Gets the open source language identity, distinct from a rendering backend or GPU API. /// string languageId { get; } + /// /// Analyzes an immutable source candidate with explicit preprocessing inputs. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs index 55139e46f..3b5a5181a 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs @@ -26,11 +26,16 @@ public ShaderSourceFrontendCatalog(IEnumerable frontends) { ArgumentNullException.ThrowIfNull(frontends); foreach (IShaderSourceFrontend frontend in frontends) - if (frontend is null || string.IsNullOrWhiteSpace(frontend.languageId) || - !m_frontends.TryAdd(frontend.languageId, frontend)) + { + if (frontend is null || string.IsNullOrWhiteSpace(frontend.languageId) + || !m_frontends.TryAdd(frontend.languageId, frontend) + ) { throw new ArgumentException("Source frontends require unique, assigned language IDs.", nameof(frontends)); + } + } languageIds = new ReadOnlyCollection(new List(m_frontends.Keys)); } + /// /// Gets registered language identities for source import settings. /// @@ -60,8 +65,8 @@ ShaderSourceRequest request ArgumentException.ThrowIfNullOrWhiteSpace(languageId); ArgumentNullException.ThrowIfNull(request); return m_frontends.TryGetValue(languageId, out IShaderSourceFrontend? frontend) - ? frontend.Analyze(request) - : throw new NotSupportedException($"Shader source language '{languageId}' is unavailable."); + ? frontend.Analyze(request) + : throw new NotSupportedException($"Shader source language '{languageId}' is unavailable."); } /// @@ -80,49 +85,80 @@ public ShaderSourceModuleAnalysis AnalyzeModule(IEnumerable value is null) || - requests.Select(static value => value.implementationId).Distinct(StringComparer.Ordinal).Count() != requests.Length) + if (requests.Length == 0 || requests.Any(static value => value is null) + || requests.Select(static value => value.implementationId).Distinct(StringComparer.Ordinal).Count() != requests.Length + ) { throw new ArgumentException("A module requires unique, assigned implementation/configuration IDs.", nameof(implementations)); + } var results = new List(); var diagnostics = new List(); ShaderSourceFunction? common = null; string? commonId = null; - foreach (ShaderSourceImplementationRequest request in requests.OrderBy(static value => value.implementationId, StringComparer.Ordinal)) - { + foreach (ShaderSourceImplementationRequest request in requests.OrderBy( + static value => value.implementationId, + StringComparer.Ordinal + )) { var resolver = new ShaderSourceSnapshotResolver(request.source); ShaderSourceAnalysis analysis; if (!m_frontends.TryGetValue(request.languageId, out IShaderSourceFrontend? frontend)) - analysis = new(null, [], [new("SHADER_SOURCE_LANGUAGE_MISSING", DiagnosticSeverity.Error, + { + analysis = new(null, [], [new( + "SHADER_SOURCE_LANGUAGE_MISSING", + DiagnosticSeverity.Error, $"Implementation '{request.implementationId}' requires unavailable language '{request.languageId}'.", - new(request.source.source.assetPath, 1, 1))]); + new(request.source.source.assetPath, 1, 1) + )]); + } else { analysis = frontend.Analyze(new(request.source.source, request.source.entryPoint, resolver, request.source.defines)) - ?? throw new InvalidOperationException($"Language '{request.languageId}' returned no source analysis."); + ?? throw new InvalidOperationException($"Language '{request.languageId}' returned no source analysis."); var paths = new HashSet(resolver.files.Select(static file => file.assetPath), StringComparer.Ordinal); string[] uncaptured = analysis.dependencies.Where(path => !paths.Contains(path)).ToArray(); if (analysis.succeeded && uncaptured.Length != 0) - analysis = new(analysis.function, analysis.dependencies, analysis.diagnostics.Concat( - uncaptured.Select(path => new ShaderSourceDiagnostic("SHADER_SOURCE_DEPENDENCY_UNCAPTURED", DiagnosticSeverity.Error, - $"Language '{request.languageId}' reported dependency '{path}' without reading it through the source resolver.", - new(request.source.source.assetPath, 1, 1))))); - analysis = new(analysis.function, - analysis.dependencies.Concat(paths.Where(path => path != request.source.source.assetPath)), analysis.diagnostics); + { + analysis = new( + analysis.function, + analysis.dependencies, + analysis.diagnostics.Concat( + uncaptured.Select(path => new ShaderSourceDiagnostic( + "SHADER_SOURCE_DEPENDENCY_UNCAPTURED", + DiagnosticSeverity.Error, + $"Language '{request.languageId}' reported dependency '{path}' without reading it through the source resolver.", + new(request.source.source.assetPath, 1, 1) + )) + ) + ); + } + analysis = new( + analysis.function, + analysis.dependencies.Concat(paths.Where(path => path != request.source.source.assetPath)), + analysis.diagnostics + ); } results.Add(new(request, analysis, resolver.files, resolver.includes)); diagnostics.AddRange(analysis.diagnostics); if (!analysis.succeeded) + { continue; + } if (common is null) { common = analysis.function; commonId = request.implementationId; } else if (!common.HasSameInterface(analysis.function)) - diagnostics.Add(new("SHADER_SOURCE_IMPLEMENTATION_INTERFACE", DiagnosticSeverity.Error, - $"Implementation '{request.implementationId}' does not match '{commonId}': public parameter names, directions, order and complete value types must agree.", - analysis.function!.location)); + { + diagnostics.Add( + new( + "SHADER_SOURCE_IMPLEMENTATION_INTERFACE", + DiagnosticSeverity.Error, + $"Implementation '{request.implementationId}' does not match '{commonId}': public parameter names, directions, order and complete value types must agree.", + analysis.function!.location + ) + ); + } } return new(results, diagnostics); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs index d4280afd7..130948424 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; - using Inno.Extensibility.Types; namespace Inno.Rendering.Shaders; @@ -19,7 +18,8 @@ public sealed class ShaderSourceFrontendRegistry : TypeRegistry /// The owner type catalog; it must outlive this registry. /// - public ShaderSourceFrontendRegistry(TypeCatalog types) : base(types) => m_types = types; + public ShaderSourceFrontendRegistry(TypeCatalog types) + : base(types) => m_types = types; /// /// Gets immutable language identities available in the current generation. @@ -87,9 +87,11 @@ protected override ShaderSourceFrontendCatalog Build(TypeCacheSnapshot types) { var providers = new List(); foreach (Type type in types.GetTypesImplementing() - .Select(reference => reference.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal)) + .Select(reference => reference.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { providers.Add(CreateExtension(type)); + } return new ShaderSourceFrontendCatalog(providers); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs index 5645b1fce..48c00d344 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs @@ -50,21 +50,28 @@ ShaderSourceParameterDirection direction ) { ArgumentException.ThrowIfNullOrWhiteSpace(name); if (!Enum.IsDefined(direction)) + { throw new ArgumentOutOfRangeException(nameof(direction)); + } if (type?.id == "void") + { throw new ArgumentException("A parameter cannot have void type.", nameof(type)); + } this.name = name; this.type = type ?? throw new ArgumentNullException(nameof(type)); this.direction = direction; } + /// /// Gets the public parameter name. /// public string name { get; } + /// /// Gets the complete canonical value type. /// public ShaderSourceType type { get; } + /// /// Gets the declared value flow. /// @@ -103,28 +110,36 @@ ShaderSourcePosition location ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(parameters); if (name == "main") + { throw new ArgumentException("A source module exports a function, not a shader main entry point.", nameof(name)); + } ShaderSourceParameter[] snapshot = parameters.ToArray(); - if (snapshot.Any(static parameter => parameter is null) || - snapshot.Select(static parameter => parameter.name).Distinct(StringComparer.Ordinal).Count() != snapshot.Length) + if (snapshot.Any(static parameter => parameter is null) + || snapshot.Select(static parameter => parameter.name).Distinct(StringComparer.Ordinal).Count() != snapshot.Length + ) { throw new ArgumentException("A function requires unique parameter names.", nameof(parameters)); + } this.name = name; this.returnType = returnType ?? throw new ArgumentNullException(nameof(returnType)); this.parameters = Array.AsReadOnly(snapshot); this.location = location; } + /// /// Gets the implementation function name. /// public string name { get; } + /// /// Gets the canonical result type. /// public ShaderSourceType returnType { get; } + /// /// Gets the immutable function parameters. /// public IReadOnlyList parameters { get; } + /// /// Gets the original declaration position. /// @@ -142,11 +157,17 @@ ShaderSourcePosition location public bool HasSameInterface(ShaderSourceFunction? other) { if (other is null || !returnType.IsEquivalentTo(other.returnType) || parameters.Count != other.parameters.Count) + { return false; + } for (int i = 0; i < parameters.Count; i++) - if (parameters[i].name != other.parameters[i].name || parameters[i].direction != other.parameters[i].direction || - !parameters[i].type.IsEquivalentTo(other.parameters[i].type)) + { + if (parameters[i].name != other.parameters[i].name || parameters[i].direction != other.parameters[i].direction + || !parameters[i].type.IsEquivalentTo(other.parameters[i].type) + ) { return false; + } + } return true; } } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs index a65b17a76..7a6aec711 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs @@ -59,10 +59,12 @@ ShaderSourceRequest source /// Gets the stable owner-defined implementation/configuration key. /// public string implementationId { get; } + /// /// Gets the explicitly selected language identity. /// public string languageId { get; } + /// /// Gets the transient candidate request, which must not be persisted or retained after analysis. /// @@ -87,8 +89,11 @@ IEnumerable includes defines = request.source.defines; this.analysis = analysis; sources = Array.AsReadOnly(files.OrderBy(static file => file.assetPath, StringComparer.Ordinal).ToArray()); - this.includes = Array.AsReadOnly(includes.OrderBy(static edge => edge.includingFile, StringComparer.Ordinal) - .ThenBy(static edge => edge.include, StringComparer.Ordinal).ToArray()); + this.includes = Array.AsReadOnly( + includes.OrderBy(static edge => edge.includingFile, StringComparer.Ordinal) + .ThenBy(static edge => edge.include, StringComparer.Ordinal) + .ToArray() + ); contentHash = ComputeContentHash(); } @@ -96,34 +101,42 @@ IEnumerable includes /// Gets the stable implementation/configuration key. /// public string implementationId { get; } + /// /// Gets the selected source language. /// public string languageId { get; } + /// /// Gets the root source path in the frozen source set. /// public string sourcePath { get; } + /// /// Gets the implementation's selected callable function name. /// public string entryPoint { get; } + /// /// Gets the immutable preprocessing inputs used for this implementation. /// public IReadOnlyDictionary defines { get; } + /// /// Gets every successfully read source, including the root, ordered by path. /// public IReadOnlyList sources { get; } + /// /// Gets the original resolver's frozen include edges, including aliases and mounted source paths. /// public IReadOnlyList includes { get; } + /// /// Gets the parsed interface and implementation-local diagnostics. /// public ShaderSourceAnalysis analysis { get; } + /// /// Gets a deterministic source-input hash. A compiler cache must additionally include its toolchain, /// target, graph semantics and binding layout; this hash alone is not a compiled artifact key. @@ -191,7 +204,9 @@ public ShaderSourceFile ReadInclude( string include ) { ShaderSourceInclude edge = includes.FirstOrDefault(value => value.includingFile == includingFile && value.include == include) - ?? throw new InvalidOperationException($"Include '{include}' from '{includingFile}' was not captured during source analysis."); + ?? throw new InvalidOperationException( + $"Include '{include}' from '{includingFile}' was not captured during source analysis." + ); return sources.Single(file => file.assetPath == edge.resolvedPath); } } @@ -209,7 +224,7 @@ IEnumerable diagnostics this.implementations = Array.AsReadOnly(implementations.ToArray()); this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); succeeded = this.implementations.Count != 0 && this.implementations.All(static item => item.analysis.succeeded) - && this.diagnostics.All(static item => item.severity != DiagnosticSeverity.Error); + && this.diagnostics.All(static item => item.severity != DiagnosticSeverity.Error); function = succeeded ? this.implementations[0].analysis.function : null; } @@ -217,14 +232,17 @@ IEnumerable diagnostics /// Gets all implementation snapshots, including failed or unavailable implementations. /// public IReadOnlyList implementations { get; } + /// /// Gets implementation and cross-implementation diagnostics with original source positions. /// public IReadOnlyList diagnostics { get; } + /// /// Gets the common interface only when all supplied implementations agree and are valid. /// public ShaderSourceFunction? function { get; } + /// /// Gets whether interface analysis succeeded; native compilation is a separate gate. /// @@ -263,15 +281,21 @@ public ShaderSourceFile ReadInclude( string include ) { if (!m_files.ContainsKey(includingFile)) + { throw new InvalidOperationException("An include must originate from an already captured source."); + } ShaderSourceFile file = m_resolver.ReadInclude(includingFile, include) - ?? throw new InvalidOperationException("The source resolver returned no source snapshot."); + ?? throw new InvalidOperationException("The source resolver returned no source snapshot."); ArgumentException.ThrowIfNullOrWhiteSpace(file.assetPath); ArgumentNullException.ThrowIfNull(file.text); if (m_files.TryGetValue(file.assetPath, out ShaderSourceFile? previous) && previous.text != file.text) + { throw new InvalidOperationException($"Source '{file.assetPath}' changed during module analysis."); + } if (m_includes.TryGetValue((includingFile, include), out ShaderSourceInclude? edge) && edge.resolvedPath != file.assetPath) + { throw new InvalidOperationException($"Include '{include}' changed resolution during module analysis."); + } m_includes[(includingFile, include)] = new(includingFile, include, file.assetPath); m_files[file.assetPath] = file; return file; diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceNodeDefinition.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceNodeDefinition.cs index ddb164750..e5c8cb01b 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceNodeDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceNodeDefinition.cs @@ -27,12 +27,18 @@ public ShaderSourceNodeDefinition(ShaderSourceFunction function) foreach (ShaderSourceParameter parameter in function.parameters) { if (parameter.direction != ShaderSourceParameterDirection.Output) + { Add("input." + parameter.name, parameter.name, parameter.type, GraphPortDirection.Input); + } if (parameter.direction != ShaderSourceParameterDirection.Input) + { Add("output." + parameter.name, parameter.name, parameter.type, GraphPortDirection.Output); + } } if (function.returnType.id != "void") + { Add("return", "Result", function.returnType, GraphPortDirection.Output); + } m_ports = ports.AsReadOnly(); void Add( @@ -41,11 +47,20 @@ void Add( ShaderSourceType type, GraphPortDirection direction ) { - ports.Add(new(new GraphPortId(id), label, TypeIdentity(type), direction, - direction == GraphPortDirection.Input ? GraphPortCapacity.Single : GraphPortCapacity.Multiple)); + ports.Add( + new( + new GraphPortId(id), + label, + TypeIdentity(type), + direction, + direction == GraphPortDirection.Input ? GraphPortCapacity.Single : GraphPortCapacity.Multiple + ) + ); // Aggregate and member ports coexist so collapsing presentation never changes edge identity. foreach (ShaderSourceField field in type.fields) + { Add(id + "." + field.name, label + "." + field.name, field.type, direction); + } } } @@ -72,7 +87,9 @@ public override IReadOnlyList GetPorts(GraphNodeRecord node private static string TypeIdentity(ShaderSourceType type) { if (type.elementType is null && type.fields.Count == 0 && type.storage is null) + { return type.id; + } var canonical = new StringBuilder(); Write(type); return "inno.shader.aggregate." + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(canonical.ToString()))); @@ -81,11 +98,21 @@ void Write(ShaderSourceType value) { canonical.Append(value.id.Length).Append(':').Append(value.id).Append('[').Append(value.elementCount).Append(']'); if (value.elementType is not null) + { Write(value.elementType); + } if (value.storage is ShaderStorageType storage) { - canonical.Append('(').Append((int)storage.access).Append(',').Append(storage.format.HasValue ? (int)storage.format.Value : -1) - .Append(',').Append((int)storage.dimension).Append(',').Append(storage.array ? 1 : 0).Append(')'); + canonical + .Append('(') + .Append((int)storage.access) + .Append(',') + .Append(storage.format.HasValue ? (int)storage.format.Value : -1) + .Append(',') + .Append((int)storage.dimension) + .Append(',') + .Append(storage.array ? 1 : 0) + .Append(')'); Write(storage.valueType); } canonical.Append('{'); diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs index 79d5378c0..216f911dd 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs @@ -28,14 +28,17 @@ private ShaderSourceType( /// Gets the open semantic type identifier, independent of source-language spelling. /// public string id { get; } + /// /// Gets the array element type, or null for a non-array value. /// public ShaderSourceType? elementType { get; } + /// /// Gets the fixed array length, or zero for a non-array value. /// public int elementCount { get; } + /// /// Gets immutable structure fields in declaration order. /// @@ -91,7 +94,9 @@ int count ArgumentNullException.ThrowIfNull(element); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(count); if (element.id == "void" || element.storage is not null) + { throw new ArgumentException("An array cannot contain void values or opaque storage bindings.", nameof(element)); + } return new("array", element, count, []); } @@ -116,11 +121,15 @@ IEnumerable fields ) { ArgumentNullException.ThrowIfNull(fields); if (id == "void") + { throw new ArgumentException("Void is reserved for the absence of a return value.", nameof(id)); + } ShaderSourceField[] snapshot = fields.ToArray(); - if (snapshot.Length == 0 || snapshot.Any(static field => field is null) || - snapshot.Select(static field => field.name).Distinct(StringComparer.Ordinal).Count() != snapshot.Length) + if (snapshot.Length == 0 || snapshot.Any(static field => field is null) + || snapshot.Select(static field => field.name).Distinct(StringComparer.Ordinal).Count() != snapshot.Length + ) { throw new ArgumentException("A structure requires unique named fields.", nameof(fields)); + } return new(id, null, 0, snapshot); } @@ -136,15 +145,25 @@ IEnumerable fields public bool IsEquivalentTo(ShaderSourceType? other) { if (other is null || id != other.id || elementCount != other.elementCount || fields.Count != other.fields.Count) + { return false; + } if ((storage is null) != (other.storage is null) || storage is not null && !storage.IsEquivalentTo(other.storage)) + { return false; - if ((elementType is null) != (other.elementType is null) || - elementType is not null && !elementType.IsEquivalentTo(other.elementType)) + } + if ((elementType is null) != (other.elementType is null) + || elementType is not null && !elementType.IsEquivalentTo(other.elementType) + ) { return false; + } for (int i = 0; i < fields.Count; i++) + { if (fields[i].name != other.fields[i].name || !fields[i].type.IsEquivalentTo(other.fields[i].type)) + { return false; + } + } return true; } } @@ -172,14 +191,18 @@ ShaderSourceType type ) { ArgumentException.ThrowIfNullOrWhiteSpace(name); if (type?.id == "void" || type?.storage is not null) + { throw new ArgumentException("A structure field cannot have void type or contain an opaque storage binding.", nameof(type)); + } this.name = name; this.type = type ?? throw new ArgumentNullException(nameof(type)); } + /// /// Gets the public field name. /// public string name { get; } + /// /// Gets the complete field type. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs index f9f1977c9..241c1cd09 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs @@ -19,8 +19,8 @@ public sealed class ShaderTargetAttribute : Attribute /// public ShaderTargetAttribute(string id) => this.id = string.IsNullOrWhiteSpace(id) - ? throw new ArgumentException("Shader target identity cannot be empty.", nameof(id)) - : id; + ? throw new ArgumentException("Shader target identity cannot be empty.", nameof(id)) + : id; /// /// Gets the stable target identity persisted by Shader assets. @@ -70,10 +70,12 @@ SerializationContext references /// Gets a private document copy; expansion cannot modify the authored source. /// public GraphDocument document { get; } + /// /// Gets the current owner converter registry, valid only during expansion. /// public SerializationRegistry serialization { get; } + /// /// Gets the complete owner reference context used for generated resource defaults. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetRegistry.cs index 43ed67d90..09252b61c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetRegistry.cs @@ -78,11 +78,15 @@ public GraphDocument Expand( cancellationToken.ThrowIfCancellationRequested(); string id = ShaderGraphDocument.ReadTarget(document, serialization, context); if (id.Length == 0) + { return document.Clone(); + } if (!m_registry.snapshot.TryGetValue(id, out ShaderTarget? target)) + { throw new ShaderTargetUnavailableException(id); + } GraphDocument expanded = target.Expand(new(document.Clone(), serialization, context), cancellationToken) - ?? throw new InvalidOperationException($"Shader target '{id}' returned no program."); + ?? throw new InvalidOperationException($"Shader target '{id}' returned no program."); cancellationToken.ThrowIfCancellationRequested(); return expanded.Clone(); } @@ -115,7 +119,8 @@ protected override IReadOnlyDictionary Build(TypeCacheSnap if (type.IsAbstract || !typeof(ShaderTarget).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Shader target '{type.FullName}' must be a concrete {nameof(ShaderTarget)}."); + $"Shader target '{type.FullName}' must be a concrete {nameof(ShaderTarget)}." + ); } return (type, type.GetCustomAttribute(inherit: false)!.id); }) @@ -124,7 +129,9 @@ protected override IReadOnlyDictionary Build(TypeCacheSnap .GroupBy(static registration => registration.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicateId is not null) + { throw new InvalidOperationException($"Duplicate shader target '{duplicateId}'."); + } var targets = new Dictionary(StringComparer.Ordinal); foreach ((Type type, string id) in registrations) diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs index 4ec32c7c2..52ec54447 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs @@ -24,11 +24,11 @@ public ShaderGraphTemplateAttribute( string displayName ) { this.id = string.IsNullOrWhiteSpace(id) - ? throw new ArgumentException("Shader graph template identity cannot be empty.", nameof(id)) - : id; + ? throw new ArgumentException("Shader graph template identity cannot be empty.", nameof(id)) + : id; this.displayName = string.IsNullOrWhiteSpace(displayName) - ? throw new ArgumentException("Shader graph template display name cannot be empty.", nameof(displayName)) - : displayName; + ? throw new ArgumentException("Shader graph template display name cannot be empty.", nameof(displayName)) + : displayName; } /// @@ -83,8 +83,7 @@ internal sealed class RasterShaderGraphTemplate : ShaderGraphTemplate public override GraphDocument Create( SerializationRegistry serialization, SerializationContext context -) - => ShaderGraphTemplates.CreateRaster(serialization, context); +) => ShaderGraphTemplates.CreateRaster(serialization, context); } [ShaderGraphTemplate(ShaderBuiltInIds.nodeTemplate, "Reusable Node")] @@ -112,18 +111,24 @@ SerializationContext context { position = new(40, 120) }; - input.SetValue(ShaderGraphDocument.settingsKey, ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings - { - ports = [new() { id = "value", type = new() { id = "float" } }] - }, serialization, context)); + input.SetValue( + ShaderGraphDocument.settingsKey, + ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings + { + ports = [new() { id = "value", type = new() { id = "float" } }] + }, serialization, context) + ); var output = new GraphNodeRecord(new("node-outputs"), ShaderGraphNodes.outputDefinitionId) { position = new(620, 120) }; - output.SetValue(ShaderGraphDocument.settingsKey, ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings - { - ports = [new() { id = "value", type = new() { id = "float" } }] - }, serialization, context)); + output.SetValue( + ShaderGraphDocument.settingsKey, + ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings + { + ports = [new() { id = "value", type = new() { id = "float" } }] + }, serialization, context) + ); graph.AddNode(input); graph.AddNode(output); graph.AddEdge(new(new("node-value"), new(input.id, new("value")), new(output.id, new("value")))); diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs index 2e927ce8e..4cab2f3a8 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs @@ -50,8 +50,12 @@ public IReadOnlyList templates get { using IDisposable operation = m_types.AcquireOperation("Describe shader templates"); - return Array.AsReadOnly(m_registry.snapshot.Values.Select(static value => value.info) - .OrderBy(static value => value.displayName, StringComparer.Ordinal).ThenBy(static value => value.id, StringComparer.Ordinal).ToArray()); + return Array.AsReadOnly( + m_registry.snapshot.Values.Select(static value => value.info) + .OrderBy(static value => value.displayName, StringComparer.Ordinal) + .ThenBy(static value => value.id, StringComparer.Ordinal) + .ToArray() + ); } } @@ -81,7 +85,9 @@ SerializationContext context ArgumentException.ThrowIfNullOrWhiteSpace(id); using IDisposable operation = m_types.AcquireOperation("Create shader from template"); if (!m_registry.snapshot.TryGetValue(id, out Entry? entry)) + { throw new InvalidOperationException($"Shader template '{id}' is unavailable."); + } return entry.template.Create(serialization, context).Clone(); } @@ -98,6 +104,7 @@ ShaderGraphTemplate template private sealed class Registry(TypeCatalog types) : TypeRegistry>(types) { internal IReadOnlyDictionary snapshot => current; + /// /// Builds a validated result from the current immutable input snapshot. /// @@ -118,7 +125,8 @@ protected override IReadOnlyDictionary Build(TypeCacheSnapshot ty if (type.IsAbstract || !typeof(ShaderGraphTemplate).IsAssignableFrom(type)) { throw new InvalidOperationException( - $"Shader graph template '{type.FullName}' must be a concrete {nameof(ShaderGraphTemplate)}."); + $"Shader graph template '{type.FullName}' must be a concrete {nameof(ShaderGraphTemplate)}." + ); } return (type, type.GetCustomAttribute(inherit: false)!); }) @@ -127,7 +135,9 @@ protected override IReadOnlyDictionary Build(TypeCacheSnapshot ty .GroupBy(static registration => registration.metadata.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1)?.Key; if (duplicateId is not null) + { throw new InvalidOperationException($"Duplicate shader template '{duplicateId}'."); + } var templates = new Dictionary(StringComparer.Ordinal); foreach ((Type type, ShaderGraphTemplateAttribute metadata) in registrations) @@ -138,6 +148,7 @@ protected override IReadOnlyDictionary Build(TypeCacheSnapshot ty } return templates; } + /// /// Releases the generation lease retained by an immutable registry snapshot. /// @@ -145,6 +156,6 @@ protected override IReadOnlyDictionary Build(TypeCacheSnapshot ty /// The immutable state snapshot consumed by this operation. /// protected override void DisposeSnapshot(IReadOnlyDictionary snapshot) - => DisposeExtensions(snapshot.Values.Select(static value => value.template)); + => DisposeExtensions(snapshot.Values.Select(static value => value.template)); } } diff --git a/src/services/rendering/Inno.Rendering/Device/ComputePipelineDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/ComputePipelineDescriptor.cs index 4990cfaf0..7bb05661d 100644 --- a/src/services/rendering/Inno.Rendering/Device/ComputePipelineDescriptor.cs +++ b/src/services/rendering/Inno.Rendering/Device/ComputePipelineDescriptor.cs @@ -50,4 +50,3 @@ IReadOnlyList bindings /// public IReadOnlyList bindings => m_bindings; } - diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs index 3c9c32955..66c3ddc11 100644 --- a/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs @@ -14,30 +14,37 @@ namespace Inno.Rendering; /// Headless validation backend. /// public static GraphicsApi Noop { get; } = new("Noop"); + /// /// Direct3D 11 renderer. /// public static GraphicsApi Direct3D11 { get; } = new("Direct3D11"); + /// /// Direct3D 12 renderer. /// public static GraphicsApi Direct3D12 { get; } = new("Direct3D12"); + /// /// Apple Metal renderer. /// public static GraphicsApi Metal { get; } = new("Metal"); + /// /// Khronos Vulkan renderer. /// public static GraphicsApi Vulkan { get; } = new("Vulkan"); + /// /// Desktop OpenGL renderer. /// public static GraphicsApi OpenGL { get; } = new("OpenGL"); + /// /// OpenGL ES renderer. /// public static GraphicsApi OpenGLES { get; } = new("OpenGLES"); + /// /// WebGPU renderer. /// @@ -55,9 +62,12 @@ namespace Inno.Rendering; public GraphicsApi(string value) { if (!IsPortableIdentifier(value)) + { throw new ArgumentException( "Graphics API IDs must begin with a letter or digit and use only portable letters, numbers, dots, underscores or hyphens.", - nameof(value)); + nameof(value) + ); + } this.value = value; } @@ -89,7 +99,9 @@ out GraphicsApi api ) { api = default; if (!IsPortableIdentifier(value)) + { return false; + } api = new GraphicsApi(value!); return true; } @@ -116,10 +128,16 @@ out GraphicsApi api private static bool IsPortableIdentifier(string? candidate) { if (string.IsNullOrEmpty(candidate) || !char.IsAsciiLetterOrDigit(candidate[0])) + { return false; + } foreach (char character in candidate) + { if (!(char.IsAsciiLetterOrDigit(character) || character is '-' or '_' or '.')) + { return false; + } + } return true; } } @@ -345,7 +363,9 @@ public GraphicsCapabilities( ArgumentNullException.ThrowIfNull(storageReadFormats); ArgumentNullException.ThrowIfNull(storageWriteFormats); if (!backend.isValid) + { throw new ArgumentException("Graphics capabilities require a backend identity.", nameof(backend)); + } this.backend = backend; this.features = features; this.limits = limits; @@ -355,8 +375,7 @@ public GraphicsCapabilities( m_sampled3DFormats = new HashSet(sampled3DFormats ?? []); m_sampledCubeFormats = new HashSet(sampledCubeFormats ?? []); m_renderTargetFormats = new HashSet(renderTargetFormats); - m_multisampleRenderTargetFormats = new HashSet( - multisampleRenderTargetFormats ?? []); + m_multisampleRenderTargetFormats = new HashSet(multisampleRenderTargetFormats ?? []); m_storageReadFormats = new HashSet(storageReadFormats); m_storageWriteFormats = new HashSet(storageWriteFormats); } @@ -423,14 +442,13 @@ public GraphicsCapabilities( public bool SupportsSampled( RenderTextureFormat format, RenderTextureDimension dimension - ) - => dimension switch - { - RenderTextureDimension.Texture2D => m_sampledFormats.Contains(format), - RenderTextureDimension.Texture3D => m_sampled3DFormats.Contains(format), - RenderTextureDimension.Cube => m_sampledCubeFormats.Contains(format), - _ => false - }; + ) => dimension switch + { + RenderTextureDimension.Texture2D => m_sampledFormats.Contains(format), + RenderTextureDimension.Texture3D => m_sampled3DFormats.Contains(format), + RenderTextureDimension.Cube => m_sampledCubeFormats.Contains(format), + _ => false + }; /// /// Tests whether a format is valid as a raster attachment. @@ -469,13 +487,12 @@ RenderTextureDimension dimension public bool SupportsStorage( RenderTextureFormat format, RenderStorageAccess access - ) - => access switch - { - RenderStorageAccess.Read => m_storageReadFormats.Contains(format), - RenderStorageAccess.Write => m_storageWriteFormats.Contains(format), - RenderStorageAccess.ReadWrite => m_storageReadFormats.Contains(format) - && m_storageWriteFormats.Contains(format), - _ => false - }; + ) => access switch + { + RenderStorageAccess.Read => m_storageReadFormats.Contains(format), + RenderStorageAccess.Write => m_storageWriteFormats.Contains(format), + RenderStorageAccess.ReadWrite => m_storageReadFormats.Contains(format) + && m_storageWriteFormats.Contains(format), + _ => false + }; } diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineDescriptor.cs index de39c6464..c3f1ff5a0 100644 --- a/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineDescriptor.cs +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineDescriptor.cs @@ -90,4 +90,3 @@ private static void EnsureUniqueBindings(IReadOnlyList data, bool sRgb, string name - ) - => throw new NotSupportedException("This render device does not support encoded texture containers."); + ) => throw new NotSupportedException("This render device does not support encoded texture containers."); /// /// Replaces one complete mip and addressable layer, slice, or cubemap face. diff --git a/src/services/rendering/Inno.Rendering/Device/PersistentBufferDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/PersistentBufferDescriptor.cs index 8cf9269d0..87cfbfb39 100644 --- a/src/services/rendering/Inno.Rendering/Device/PersistentBufferDescriptor.cs +++ b/src/services/rendering/Inno.Rendering/Device/PersistentBufferDescriptor.cs @@ -33,8 +33,8 @@ public PersistentBufferDescriptor( } if ((buffer.usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) - == (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) - { + == (RenderBufferUsage.Vertex | RenderBufferUsage.Index) + ) { throw new ArgumentException("A buffer cannot be both vertex and index input.", nameof(buffer)); } @@ -50,8 +50,8 @@ public PersistentBufferDescriptor( int expectedIndexStride = indexFormat == RenderIndexFormat.UInt16 ? 2 : 4; if ((buffer.usage & RenderBufferUsage.Index) != 0 - && buffer.elementStride != expectedIndexStride) - { + && buffer.elementStride != expectedIndexStride + ) { throw new ArgumentException("Index format must match buffer element stride.", nameof(indexFormat)); } @@ -75,4 +75,3 @@ public PersistentBufferDescriptor( /// public RenderIndexFormat indexFormat { get; } } - diff --git a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandBuffer.cs b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandBuffer.cs index 736252934..df2443599 100644 --- a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandBuffer.cs +++ b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandBuffer.cs @@ -22,7 +22,9 @@ internal sealed class RecordedRenderCommandBuffer : IDisposable public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; byte[] bytes = m_bytes; object?[] references = m_references; @@ -31,9 +33,13 @@ public void Dispose() m_length = 0; m_referenceCount = 0; if (bytes.Length != 0) + { ArrayPool.Shared.Return(bytes); + } if (references.Length != 0) + { ArrayPool.Shared.Return(references, clearArray: true); + } } internal Reader GetReader() @@ -43,7 +49,8 @@ internal Reader GetReader() } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void Write(T value) where T : unmanaged + internal void Write(T value) + where T : unmanaged { int size = Unsafe.SizeOf(); EnsureCapacity(size); @@ -55,7 +62,8 @@ internal void Write(T value) where T : unmanaged internal void WriteInstruction( byte operation, T value - ) where T : unmanaged { + ) where T : unmanaged + { int size = Unsafe.SizeOf(); EnsureCapacity(checked(size + 1)); m_bytes[m_length] = operation; @@ -68,10 +76,13 @@ internal void WriteReference(object? value) if (m_referenceCount == m_references.Length) { object?[] next = ArrayPool.Shared.Rent( - m_references.Length == 0 ? C_INITIAL_REFERENCE_CAPACITY : checked(m_references.Length * 2)); + m_references.Length == 0 ? C_INITIAL_REFERENCE_CAPACITY : checked(m_references.Length * 2) + ); m_references.AsSpan(0, m_referenceCount).CopyTo(next); if (m_references.Length != 0) + { ArrayPool.Shared.Return(m_references, clearArray: true); + } m_references = next; } Write(m_referenceCount); @@ -94,7 +105,9 @@ private void EnsureCapacity(int additionalBytes) ObjectDisposedException.ThrowIf(m_disposed, this); int required = checked(m_length + additionalBytes); if (required > m_bytes.Length) + { Grow(required); + } } private void Grow(int required) @@ -103,7 +116,9 @@ private void Grow(int required) byte[] next = ArrayPool.Shared.Rent(Math.Max(required, capacity)); m_bytes.AsSpan(0, m_length).CopyTo(next); if (m_bytes.Length != 0) + { ArrayPool.Shared.Return(m_bytes); + } m_bytes = next; } @@ -124,7 +139,8 @@ internal Reader( internal readonly bool hasCommands => m_position < m_bytes.Length; [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal T Read() where T : unmanaged + internal T Read() + where T : unmanaged { int size = Unsafe.SizeOf(); T value = MemoryMarshal.Read(m_bytes.Slice(m_position, size)); @@ -132,7 +148,8 @@ internal T Read() where T : unmanaged return value; } - internal T? ReadReference() where T : class => (T?)m_references[Read()]; + internal T? ReadReference() + where T : class => (T?)m_references[Read()]; internal RenderBindingId ReadBinding() { diff --git a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.Replay.cs b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.Replay.cs index 705f54531..5c03114d6 100644 --- a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.Replay.cs +++ b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.Replay.cs @@ -11,7 +11,9 @@ internal void Replay(RenderCommandEncoder destination) { ArgumentNullException.ThrowIfNull(destination); if (!m_sealed) + { throw new InvalidOperationException("A render command list must be sealed before replay."); + } RecordedRenderCommandBuffer.Reader reader = m_buffer.GetReader(); while (reader.hasCommands) { @@ -27,40 +29,38 @@ internal void Replay(RenderCommandEncoder destination) destination.BindTexture( reader.ReadBinding(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindTexturePersistent: destination.BindTexture( reader.ReadBinding(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindStorageTextureGraph: destination.BindStorageTexture( reader.ReadBinding(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindStorageTexturePersistent: destination.BindStorageTexture( reader.ReadBinding(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindBufferGraph: - destination.BindBuffer( - reader.ReadBinding(), - reader.Read()); + destination.BindBuffer(reader.ReadBinding(), reader.Read()); break; case Operation.BindBufferPersistent: - destination.BindBuffer( - reader.ReadBinding(), - reader.Read()); + destination.BindBuffer(reader.ReadBinding(), reader.Read()); break; case Operation.SetUniform: - destination.SetUniform( - reader.ReadBinding(), - reader.ReadSnapshot()); + destination.SetUniform(reader.ReadBinding(), reader.ReadSnapshot()); break; case Operation.SetTransform: destination.SetTransform(MemoryMarshal.Cast(reader.ReadSnapshot())); @@ -76,111 +76,95 @@ internal void Replay(RenderCommandEncoder destination) reader.Read(), reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.SetScissor: destination.SetScissor( reader.Read(), reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindVertexBufferGraph: - destination.BindVertexBuffer( - reader.Read(), - reader.Read()); + destination.BindVertexBuffer(reader.Read(), reader.Read()); break; case Operation.BindVertexBufferPersistent: - destination.BindVertexBuffer( - reader.Read(), - reader.Read()); + destination.BindVertexBuffer(reader.Read(), reader.Read()); break; case Operation.BindIndexBufferGraph: - destination.BindIndexBuffer( - reader.Read(), - reader.Read()); + destination.BindIndexBuffer(reader.Read(), reader.Read()); break; case Operation.BindIndexBufferPersistent: - destination.BindIndexBuffer( - reader.Read(), - reader.Read()); + destination.BindIndexBuffer(reader.Read(), reader.Read()); break; case Operation.BindInstanceBufferGraph: destination.BindInstanceBuffer( reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.BindInstanceBufferPersistent: destination.BindInstanceBuffer( reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.Draw: DrawArguments draw = reader.Read(); - destination.Draw( - draw.count, - draw.instanceCount); + destination.Draw(draw.count, draw.instanceCount); break; case Operation.DrawProcedural: DrawArguments procedural = reader.Read(); - destination.DrawProcedural( - procedural.count, - procedural.instanceCount); + destination.DrawProcedural(procedural.count, procedural.instanceCount); break; case Operation.DrawIndexed: DrawArguments indexed = reader.Read(); - destination.DrawIndexed( - indexed.count, - indexed.instanceCount); + destination.DrawIndexed(indexed.count, indexed.instanceCount); break; case Operation.DrawIndirectGraph: - destination.DrawIndirect( - reader.Read(), - reader.Read(), - reader.Read()); + destination.DrawIndirect(reader.Read(), reader.Read(), reader.Read()); break; case Operation.DrawIndirectPersistent: destination.DrawIndirect( reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.Dispatch: - destination.Dispatch( - reader.Read(), - reader.Read(), - reader.Read()); + destination.Dispatch(reader.Read(), reader.Read(), reader.Read()); break; case Operation.DispatchIndirectGraph: destination.DispatchIndirect( reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.DispatchIndirectPersistent: destination.DispatchIndirect( reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.CopyTextureGraph: - destination.CopyTexture( - reader.Read(), - reader.Read()); + destination.CopyTexture(reader.Read(), reader.Read()); break; case Operation.BlitTextureGraph: destination.BlitTexture( reader.Read(), reader.Read(), reader.Read(), - reader.Read()); + reader.Read() + ); break; case Operation.CopyBufferGraph: - destination.CopyBuffer( - reader.Read(), - reader.Read()); + destination.CopyBuffer(reader.Read(), reader.Read()); break; default: throw new InvalidOperationException("A recorded render command has an invalid operation."); diff --git a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs index c204ff1fd..75e95ad14 100644 --- a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs +++ b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs @@ -375,7 +375,8 @@ int instanceCount private void EnsureWritable() { if (m_sealed) + { throw new InvalidOperationException("A recorded render command list is already sealed."); + } } - } diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs b/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs index b2a4e20ab..c74446c8c 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs @@ -98,7 +98,8 @@ public struct RenderBlendState /// /// Gets the disabled opaque blend state. /// - public static RenderBlendState opaque => new() + public static RenderBlendState opaque + => new() { enabled = false, colorSource = RenderBlendFactor.One, @@ -110,7 +111,8 @@ public struct RenderBlendState /// /// Gets conventional straight-alpha blending. /// - public static RenderBlendState alpha => new() + public static RenderBlendState alpha + => new() { enabled = true, colorSource = RenderBlendFactor.SourceAlpha, @@ -122,7 +124,8 @@ public struct RenderBlendState /// /// Gets additive source-alpha blending. /// - public static RenderBlendState additive => new() + public static RenderBlendState additive + => new() { enabled = true, colorSource = RenderBlendFactor.SourceAlpha, @@ -134,7 +137,8 @@ public struct RenderBlendState /// /// Gets conventional premultiplied-alpha blending. /// - public static RenderBlendState premultiplied => new() + public static RenderBlendState premultiplied + => new() { enabled = true, colorSource = RenderBlendFactor.One, @@ -188,4 +192,3 @@ public struct RenderBlendState /// public bool alphaToCoverage { get; set; } } - diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferUploads.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferUploads.cs index 663aa0459..dcf9b9934 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderBufferUploads.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferUploads.cs @@ -30,26 +30,30 @@ public RenderBufferUploadDescriptor( ) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(elementStride); RenderBufferUsage allowed = RenderBufferUsage.Vertex - | RenderBufferUsage.Index - | RenderBufferUsage.Storage; + | RenderBufferUsage.Index + | RenderBufferUsage.Storage; if (usage == 0 || (usage & ~allowed) != 0) { - throw new ArgumentException( - "Frame uploads support vertex, index, and storage usage only.", - nameof(usage)); + throw new ArgumentException("Frame uploads support vertex, index, and storage usage only.", nameof(usage)); } if ((usage & (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) - == (RenderBufferUsage.Vertex | RenderBufferUsage.Index)) - { + == (RenderBufferUsage.Vertex | RenderBufferUsage.Index) + ) { throw new ArgumentException("An upload cannot be both vertex and index input.", nameof(usage)); } if ((usage & RenderBufferUsage.Vertex) != 0 && vertexLayout is null) + { throw new ArgumentException("Vertex uploads require an interleaved layout.", nameof(vertexLayout)); + } if (vertexLayout is not null && vertexLayout.stride != elementStride) + { throw new ArgumentException("Vertex layout stride must match element stride.", nameof(vertexLayout)); + } int indexStride = indexFormat == RenderIndexFormat.UInt16 ? 2 : 4; if ((usage & RenderBufferUsage.Index) != 0 && indexStride != elementStride) + { throw new ArgumentException("Index format must match element stride.", nameof(indexFormat)); + } this.elementStride = elementStride; this.usage = usage; @@ -153,6 +157,5 @@ protected static RenderBufferSlice CreateBufferSlice( int elementCount, RenderBufferUsage usage, ulong frameIndex - ) - => new(buffer, firstElement, elementCount, usage, frameIndex); + ) => new(buffer, firstElement, elementCount, usage, frameIndex); } diff --git a/src/services/rendering/Inno.Rendering/Device/RenderCommands.cs b/src/services/rendering/Inno.Rendering/Device/RenderCommands.cs index 2f00b5dd2..de61b7f76 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderCommands.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderCommands.cs @@ -200,8 +200,7 @@ public abstract class RenderCommandEncoder public void BindTexture( RenderBindingId binding, RenderTextureHandle texture - ) - => BindTexture(binding, texture, RenderSamplerState.linearClamp); + ) => BindTexture(binding, texture, RenderSamplerState.linearClamp); /// /// Binds a sampled texture and its sampler to a shader binding. @@ -233,8 +232,7 @@ RenderSamplerState sampler public void BindTexture( RenderBindingId binding, PersistentTextureHandle texture - ) - => BindTexture(binding, texture, RenderSamplerState.linearClamp); + ) => BindTexture(binding, texture, RenderSamplerState.linearClamp); /// /// Binds a sampled texture and its sampler to a shader binding. @@ -336,7 +334,8 @@ RenderBufferSlice buffer { throw new ArgumentException( "Storage upload slices must begin at the first backing element.", - nameof(buffer)); + nameof(buffer) + ); } BindBuffer(binding, buffer.buffer); } @@ -744,18 +743,22 @@ private void ValidateSlice( RenderBufferUsage requiredUsage ) { if (!buffer.isValid) + { throw new ArgumentException("A frame buffer slice must be valid.", nameof(buffer)); + } if (!m_hasFrameIndex || buffer.frameIndex != m_frameIndex) { throw new ArgumentException( "A frame buffer slice cannot be used outside the frame that uploaded it.", - nameof(buffer)); + nameof(buffer) + ); } if ((buffer.usage & requiredUsage) == 0) { throw new ArgumentException( $"The frame buffer slice does not declare {requiredUsage} usage.", - nameof(buffer)); + nameof(buffer) + ); } } } diff --git a/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs b/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs index b1fa9608a..1c9f77228 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs @@ -85,9 +85,7 @@ public sealed class RenderRasterState /// /// Creates the default opaque raster state. /// - public RenderRasterState() - { - } + public RenderRasterState() {} /// /// Creates a complete immutable raster configuration without relying on init-only setters. @@ -181,4 +179,3 @@ RenderPrimitiveTopology topology /// public RenderPrimitiveTopology topology { get; init; } = RenderPrimitiveTopology.TriangleList; } - diff --git a/src/services/rendering/Inno.Rendering/Device/RenderResources.cs b/src/services/rendering/Inno.Rendering/Device/RenderResources.cs index 0956f4428..d4522991d 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderResources.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderResources.cs @@ -207,11 +207,10 @@ public RenderTextureDescriptor( case RenderTextureDimension.Texture3D when arrayLayers != 1: throw new ArgumentException( "A three-dimensional texture cannot also declare array layers.", - nameof(arrayLayers)); + nameof(arrayLayers) + ); case RenderTextureDimension.Texture3D when sampleCount != 1: - throw new ArgumentException( - "A three-dimensional texture cannot be multisampled.", - nameof(sampleCount)); + throw new ArgumentException("A three-dimensional texture cannot be multisampled.", nameof(sampleCount)); case RenderTextureDimension.Cube when width != height: throw new ArgumentException("Cubemap width and height must be equal.", nameof(height)); case RenderTextureDimension.Cube when depth != 1: @@ -294,7 +293,9 @@ public RenderTextureDescriptor( public int GetSubresourceLayerCount(int mipLevel) { if ((uint)mipLevel >= (uint)mipCount) + { throw new ArgumentOutOfRangeException(nameof(mipLevel)); + } return dimension switch { RenderTextureDimension.Texture2D => arrayLayers, @@ -315,15 +316,15 @@ public int GetSubresourceLayerCount(int mipLevel) /// public bool Equals(RenderTextureDescriptor? other) => other is not null - && width == other.width - && height == other.height - && format == other.format - && usage == other.usage - && mipCount == other.mipCount - && arrayLayers == other.arrayLayers - && sampleCount == other.sampleCount - && dimension == other.dimension - && depth == other.depth; + && width == other.width + && height == other.height + && format == other.format + && usage == other.usage + && mipCount == other.mipCount + && arrayLayers == other.arrayLayers + && sampleCount == other.sampleCount + && dimension == other.dimension + && depth == other.depth; /// /// Determines whether this instance and the supplied value represent the same logical state. @@ -413,9 +414,9 @@ RenderBufferUsage usage /// public bool Equals(RenderBufferDescriptor? other) => other is not null - && elementCount == other.elementCount - && elementStride == other.elementStride - && usage == other.usage; + && elementCount == other.elementCount + && elementStride == other.elementStride + && usage == other.usage; /// /// Determines whether this instance and the supplied value represent the same logical state. diff --git a/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs b/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs index 44f8e4968..042cf2093 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs @@ -54,11 +54,13 @@ public struct RenderSamplerState : IEquatable /// /// Gets linear filtering with clamped addressing. /// - public static RenderSamplerState linearClamp => new( - RenderSamplerFilter.Linear, - RenderSamplerAddressMode.Clamp, - RenderSamplerAddressMode.Clamp, - RenderSamplerAddressMode.Clamp); + public static RenderSamplerState linearClamp + => new( + RenderSamplerFilter.Linear, + RenderSamplerAddressMode.Clamp, + RenderSamplerAddressMode.Clamp, + RenderSamplerAddressMode.Clamp + ); /// /// Creates a sampler state. @@ -175,4 +177,3 @@ RenderSamplerState right RenderSamplerState right ) => !left.Equals(right); } - diff --git a/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs index 227b08fb2..7eeef1395 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs @@ -111,11 +111,17 @@ public RenderShaderBindingDescriptor( ArgumentOutOfRangeException.ThrowIfNegative(slot); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(count); if (!Enum.IsDefined(kind)) + { throw new ArgumentOutOfRangeException(nameof(kind)); + } if (!Enum.IsDefined(uniformType)) + { throw new ArgumentOutOfRangeException(nameof(uniformType)); + } if (!Enum.IsDefined(storageAccess)) + { throw new ArgumentOutOfRangeException(nameof(storageAccess)); + } this.id = id; this.kind = kind; this.slot = slot; @@ -161,4 +167,3 @@ public RenderShaderBindingDescriptor( /// public string nativeName { get; } } - diff --git a/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs b/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs index bbd378c92..d2b8a59e8 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs @@ -143,9 +143,7 @@ public sealed class RenderStencilState /// /// Creates the default disabled stencil state. /// - public RenderStencilState() - { - } + public RenderStencilState() {} /// /// Creates a complete immutable stencil configuration without relying on init-only setters. @@ -216,7 +214,8 @@ RenderStencilFaceState back RenderStencilCompare.Always, RenderStencilOperation.Keep, RenderStencilOperation.Keep, - RenderStencilOperation.Keep); + RenderStencilOperation.Keep + ); /// /// Gets back-face stencil behavior. @@ -225,6 +224,6 @@ RenderStencilFaceState back RenderStencilCompare.Always, RenderStencilOperation.Keep, RenderStencilOperation.Keep, - RenderStencilOperation.Keep); + RenderStencilOperation.Keep + ); } - diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureReadback.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureReadback.cs index 9c1c3fef3..91315571e 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderTextureReadback.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureReadback.cs @@ -56,9 +56,13 @@ ReadOnlySpan data ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(rowPitch); if (mipLevel >= descriptor.mipCount) + { throw new ArgumentOutOfRangeException(nameof(mipLevel)); + } if (data.IsEmpty) + { throw new ArgumentException("Texture readback data cannot be empty.", nameof(data)); + } this.descriptor = descriptor; this.mipLevel = mipLevel; this.rowPitch = rowPitch; diff --git a/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs b/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs index 4f8d9ba9f..0de817a85 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs @@ -173,7 +173,9 @@ public RenderVertexAttribute( int byteOffset = -1 ) { if (byteOffset < -1) + { throw new ArgumentOutOfRangeException(nameof(byteOffset)); + } this.semantic = semantic; this.format = format; this.byteOffset = byteOffset; @@ -197,7 +199,8 @@ public RenderVertexAttribute( /// /// Gets the packed byte size. /// - public int byteSize => format switch + public int byteSize + => format switch { RenderVertexFormat.Float1 => 4, RenderVertexFormat.Float2 => 8, @@ -261,7 +264,8 @@ public RenderVertexLayout( { throw new ArgumentException( $"Vertex attribute '{attribute.semantic}' overlaps a preceding attribute.", - nameof(attributes)); + nameof(attributes) + ); } resolved[index] = new RenderVertexAttribute(attribute.semantic, attribute.format, offset); @@ -270,9 +274,7 @@ public RenderVertexLayout( if (stride != 0 && stride < occupiedEnd) { - throw new ArgumentException( - "Vertex stride cannot end before the final attribute.", - nameof(stride)); + throw new ArgumentException("Vertex stride cannot end before the final attribute.", nameof(stride)); } m_attributes = Array.AsReadOnly(resolved); @@ -300,8 +302,8 @@ public RenderVertexLayout( /// public bool Equals(RenderVertexLayout? other) => other is not null - && stride == other.stride - && m_attributes.SequenceEqual(other.m_attributes); + && stride == other.stride + && m_attributes.SequenceEqual(other.m_attributes); /// /// Determines whether this instance and the supplied value represent the same logical state. @@ -375,4 +377,3 @@ public enum RenderPrimitiveTopology /// PointList } - diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs index 18938eb97..b85953cc3 100644 --- a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs @@ -36,7 +36,8 @@ ReadOnlySpan projectionMatrix { throw new ArgumentException( "A projection matrix requires exactly sixteen values.", - nameof(projectionMatrix)); + nameof(projectionMatrix) + ); } m_viewMatrix = viewMatrix.ToArray(); @@ -425,7 +426,9 @@ ulong frameIndex backend.BeginGraph(this); graphStarted = true; if (m_parallelPasses.Length != 0) + { recorded = RecordParallelPasses(frameIndex); + } foreach (CompiledRenderPass pass in m_passes) { bool passStarted = false; @@ -437,9 +440,13 @@ ulong frameIndex commands.SetFrameIndex(frameIndex); passStarted = true; if (recorded is not null && recorded.TryGetValue(pass, out RecordedRenderCommandEncoder? commandList)) + { commandList.Replay(commands); + } else + { pass.Execute(new RenderPassContext(commands, frameIndex)); + } } catch (Exception exception) { @@ -455,13 +462,16 @@ ulong frameIndex } catch (Exception exception) { - passFailure = passFailure is null ? exception + passFailure = passFailure is null + ? exception : new AggregateException("Render pass execution and cleanup both failed.", passFailure, exception); } } } if (passFailure is not null) + { ExceptionDispatchInfo.Capture(passFailure).Throw(); + } } } catch (Exception exception) @@ -483,8 +493,12 @@ ulong frameIndex } } if (recorded is not null) + { foreach (RecordedRenderCommandEncoder commands in recorded.Values) + { commands.Dispose(); + } + } } if (errors is null) @@ -511,9 +525,7 @@ private Dictionary RecordParal m_parallelPasses, new ParallelOptions { - MaxDegreeOfParallelism = Math.Max( - 1, - Math.Min(Environment.ProcessorCount, m_parallelPasses.Length)) + MaxDegreeOfParallelism = Math.Max(1, Math.Min(Environment.ProcessorCount, m_parallelPasses.Length)) }, pass => { @@ -524,20 +536,25 @@ private Dictionary RecordParal pass.Execute(new RenderPassContext(commands, frameIndex)); commands.Seal(); if (!recorded.TryAdd(pass, commands)) + { throw new InvalidOperationException("A parallel render pass was recorded more than once."); + } } catch { commands.Dispose(); throw; } - }); + } + ); return recorded.ToDictionary(static pair => pair.Key, static pair => pair.Value); } catch { foreach (RecordedRenderCommandEncoder commands in recorded.Values) + { commands.Dispose(); + } throw; } } diff --git a/src/services/rendering/Inno.Rendering/Graph/ComputePassBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/ComputePassBuilder.cs index 71191a2fa..d04156904 100644 --- a/src/services/rendering/Inno.Rendering/Graph/ComputePassBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/ComputePassBuilder.cs @@ -11,8 +11,7 @@ public sealed class ComputePassBuilder : RenderPassBuilder internal ComputePassBuilder( RenderGraphBuilder graph, RenderPassRecord pass - ) - : base(graph, pass) { } + ) : base(graph, pass) {} /// /// Sets backend-ready column-major transform matrices exposed to this compute view. @@ -46,11 +45,7 @@ ReadOnlySpan projectionMatrix /// public ComputePassBuilder ReadStorageTexture(RenderTextureHandle texture) { - graph.AddUse( - pass, - texture, - RenderResourceAccess.Read, - RenderResourceUseKind.StorageRead); + graph.AddUse(pass, texture, RenderResourceAccess.Read, RenderResourceUseKind.StorageRead); return this; } @@ -65,11 +60,7 @@ public ComputePassBuilder ReadStorageTexture(RenderTextureHandle texture) /// public ComputePassBuilder WriteStorageTexture(RenderTextureHandle texture) { - graph.AddUse( - pass, - texture, - RenderResourceAccess.Write, - RenderResourceUseKind.StorageWrite); + graph.AddUse(pass, texture, RenderResourceAccess.Write, RenderResourceUseKind.StorageWrite); return this; } @@ -84,11 +75,7 @@ public ComputePassBuilder WriteStorageTexture(RenderTextureHandle texture) /// public ComputePassBuilder ReadWriteStorageTexture(RenderTextureHandle texture) { - graph.AddUse( - pass, - texture, - RenderResourceAccess.ReadWrite, - RenderResourceUseKind.StorageReadWrite); + graph.AddUse(pass, texture, RenderResourceAccess.ReadWrite, RenderResourceUseKind.StorageReadWrite); return this; } @@ -103,11 +90,7 @@ public ComputePassBuilder ReadWriteStorageTexture(RenderTextureHandle texture) /// public ComputePassBuilder ReadStorageBuffer(RenderBufferHandle buffer) { - graph.AddUse( - pass, - buffer, - RenderResourceAccess.Read, - RenderResourceUseKind.StorageRead); + graph.AddUse(pass, buffer, RenderResourceAccess.Read, RenderResourceUseKind.StorageRead); return this; } @@ -122,11 +105,7 @@ public ComputePassBuilder ReadStorageBuffer(RenderBufferHandle buffer) /// public ComputePassBuilder WriteStorageBuffer(RenderBufferHandle buffer) { - graph.AddUse( - pass, - buffer, - RenderResourceAccess.Write, - RenderResourceUseKind.StorageWrite); + graph.AddUse(pass, buffer, RenderResourceAccess.Write, RenderResourceUseKind.StorageWrite); return this; } @@ -141,12 +120,7 @@ public ComputePassBuilder WriteStorageBuffer(RenderBufferHandle buffer) /// public ComputePassBuilder ReadWriteStorageBuffer(RenderBufferHandle buffer) { - graph.AddUse( - pass, - buffer, - RenderResourceAccess.ReadWrite, - RenderResourceUseKind.StorageReadWrite); + graph.AddUse(pass, buffer, RenderResourceAccess.ReadWrite, RenderResourceUseKind.StorageReadWrite); return this; } } - diff --git a/src/services/rendering/Inno.Rendering/Graph/CopyPassBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/CopyPassBuilder.cs index cbc2f14be..e7e2b5e37 100644 --- a/src/services/rendering/Inno.Rendering/Graph/CopyPassBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/CopyPassBuilder.cs @@ -11,8 +11,7 @@ public sealed class CopyPassBuilder : RenderPassBuilder internal CopyPassBuilder( RenderGraphBuilder graph, RenderPassRecord pass - ) - : base(graph, pass) { } + ) : base(graph, pass) {} /// /// Declares one texture copy operation. @@ -30,16 +29,8 @@ public CopyPassBuilder CopyTexture( RenderTextureHandle source, RenderTextureHandle destination ) { - graph.AddUse( - pass, - source, - RenderResourceAccess.Read, - RenderResourceUseKind.CopySource); - graph.AddUse( - pass, - destination, - RenderResourceAccess.Write, - RenderResourceUseKind.CopyDestination); + graph.AddUse(pass, source, RenderResourceAccess.Read, RenderResourceUseKind.CopySource); + graph.AddUse(pass, destination, RenderResourceAccess.Write, RenderResourceUseKind.CopyDestination); return this; } @@ -59,16 +50,8 @@ public CopyPassBuilder CopyBuffer( RenderBufferHandle source, RenderBufferHandle destination ) { - graph.AddUse( - pass, - source, - RenderResourceAccess.Read, - RenderResourceUseKind.CopySource); - graph.AddUse( - pass, - destination, - RenderResourceAccess.Write, - RenderResourceUseKind.CopyDestination); + graph.AddUse(pass, source, RenderResourceAccess.Read, RenderResourceUseKind.CopySource); + graph.AddUse(pass, destination, RenderResourceAccess.Write, RenderResourceUseKind.CopyDestination); return this; } } diff --git a/src/services/rendering/Inno.Rendering/Graph/RasterPassBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/RasterPassBuilder.cs index 3c58c532c..51ea72949 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RasterPassBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RasterPassBuilder.cs @@ -11,8 +11,7 @@ public sealed class RasterPassBuilder : RenderPassBuilder internal RasterPassBuilder( RenderGraphBuilder graph, RenderPassRecord pass - ) - : base(graph, pass) { } + ) : base(graph, pass) {} /// /// Sets backend-ready column-major transform matrices for this raster view. @@ -115,17 +114,10 @@ public RasterPassBuilder UseColorAttachment( ArgumentOutOfRangeException.ThrowIfNegative(slot); ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); ArgumentOutOfRangeException.ThrowIfNegative(arrayLayer); - graph.AddAttachment(pass, new RenderAttachment( - texture, - slot, - false, - mipLevel, - arrayLayer, - loadAction, - storeAction, - clearColor, - 1f, - 0)); + graph.AddAttachment( + pass, + new RenderAttachment(texture, slot, false, mipLevel, arrayLayer, loadAction, storeAction, clearColor, 1f, 0) + ); return this; } @@ -167,18 +159,21 @@ public RasterPassBuilder UseDepthAttachment( ) { ArgumentOutOfRangeException.ThrowIfNegative(mipLevel); ArgumentOutOfRangeException.ThrowIfNegative(arrayLayer); - graph.AddAttachment(pass, new RenderAttachment( - texture, - 0, - true, - mipLevel, - arrayLayer, - loadAction, - storeAction, - default, - clearDepth, - clearStencil)); + graph.AddAttachment( + pass, + new RenderAttachment( + texture, + 0, + true, + mipLevel, + arrayLayer, + loadAction, + storeAction, + default, + clearDepth, + clearStencil + ) + ); return this; } } - diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs index 39e5d3eb3..5db2441f6 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs @@ -8,10 +8,14 @@ internal void EnsurePassMutable(RenderPassRecord pass) { EnsureMutating(); if (pass.index < m_frozenPassCount || pass.index >= m_passes.Count - || !ReferenceEquals(m_passes[pass.index], pass)) + || !ReferenceEquals(m_passes[pass.index], pass) + ) { throw new InvalidOperationException("The pass declaration was committed or removed by rollback."); + } if (pass.index < m_analysis.passCount) + { m_analysis.Reset(); + } InvalidateValidation(); } @@ -19,9 +23,13 @@ internal void CommitMutation(RenderGraphMutationScope scope) { EnsureCurrentMutation(scope); if (scope.isCommitted) + { throw new InvalidOperationException("The graph mutation has already been committed."); + } if (!GetValidation().result.isValid) + { throw new InvalidOperationException("Invalid graph additions cannot be committed."); + } m_frozenPassCount = m_passes.Count; scope.isCommitted = true; } @@ -35,10 +43,14 @@ internal void EndMutation(RenderGraphMutationScope scope) m_buffers.RemoveRange(scope.bufferCount, m_buffers.Count - scope.bufferCount); m_passes.RemoveRange(scope.passCount, m_passes.Count - scope.passCount); for (int index = m_addedOutputs.Count - 1; index >= scope.outputCount; index--) + { m_outputs.Remove(m_addedOutputs[index]); + } m_addedOutputs.RemoveRange(scope.outputCount, m_addedOutputs.Count - scope.outputCount); if (m_nameScopes.Count > scope.nameScopeCount) + { m_nameScopes.RemoveRange(scope.nameScopeCount, m_nameScopes.Count - scope.nameScopeCount); + } m_frozenPassCount = Math.Min(m_frozenPassCount, m_passes.Count); InvalidateValidation(); m_analysis.Reset(); @@ -47,29 +59,39 @@ internal void EndMutation(RenderGraphMutationScope scope) } m_mutations.RemoveAt(m_mutations.Count - 1); if (m_mutations.Count == 0) + { m_addedOutputs.Clear(); + } } private void EnsureCurrentMutation(RenderGraphMutationScope scope) { EnsureBuilding(); if (m_mutations.Count == 0 || !ReferenceEquals(m_mutations[^1], scope)) + { throw new InvalidOperationException("Render graph mutations must end in nesting order."); + } } private void EnsureMutating() { EnsureBuilding(); if (m_mutations.Count != 0 && m_mutations[^1].isCommitted) + { throw new InvalidOperationException("End the committed mutation scope before adding graph declarations."); + } } private void MarkOutput(RenderResourceKey key) { if (!m_outputs.Add(key)) + { return; + } if (m_mutations.Count != 0) + { m_addedOutputs.Add(key); + } InvalidateValidation(); } @@ -82,7 +104,9 @@ private void InvalidateValidation() private RenderGraphValidationState GetValidation() { if (m_validation is not null && m_validatedRevision == m_revision) + { return m_validation; + } m_validation = RenderGraphValidator.Validate(m_capabilities, m_textures, m_buffers, m_passes, m_outputs, m_analysis); m_validatedRevision = m_revision; return m_validation; diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs index f53c68287..34b6a2e41 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Scripting.Api; namespace Inno.Rendering; @@ -200,8 +199,14 @@ public RenderGraphMutationScope BeginMutationScope() EnsureMutating(); m_frozenPassCount = m_passes.Count; var scope = new RenderGraphMutationScope( - this, m_textures.Count, m_buffers.Count, m_passes.Count, m_addedOutputs.Count, m_nameScopes.Count, - m_validatedRevision == m_revision ? m_validation : null); + this, + m_textures.Count, + m_buffers.Count, + m_passes.Count, + m_addedOutputs.Count, + m_nameScopes.Count, + m_validatedRevision == m_revision ? m_validation : null + ); m_mutations.Add(scope); return scope; } @@ -250,8 +255,7 @@ public RasterPassBuilder AddRasterPass( RenderPhaseId phase, TPassData passData, RenderPassExecute execute - ) - where TPassData : notnull + ) where TPassData : notnull => new(this, AddPass(name, phase, RenderPassKind.Raster, passData, execute)); /// @@ -280,8 +284,7 @@ public ComputePassBuilder AddComputePass( RenderPhaseId phase, TPassData passData, RenderPassExecute execute - ) - where TPassData : notnull + ) where TPassData : notnull => new(this, AddPass(name, phase, RenderPassKind.Compute, passData, execute)); /// @@ -310,8 +313,7 @@ public CopyPassBuilder AddCopyPass( RenderPhaseId phase, TPassData passData, RenderPassExecute execute - ) - where TPassData : notnull + ) where TPassData : notnull => new(this, AddPass(name, phase, RenderPassKind.Copy, passData, execute)); /// @@ -325,7 +327,9 @@ public RenderGraphCompileResult Compile() { EnsureBuilding(); if (m_mutations.Count != 0) + { throw new InvalidOperationException("End all graph mutation scopes before final compilation."); + } RenderGraphValidationState validation = GetValidation(); m_compiled = true; return RenderGraphCompiler.Compile(m_generation, m_textures, m_buffers, m_passes, validation); @@ -348,11 +352,17 @@ internal void EndNameScope(long id) { int index = m_nameScopes.FindIndex(scope => scope.id == id); if (index < 0) + { return; + } if (index != m_nameScopes.Count - 1) + { throw new InvalidOperationException("Render graph name scopes must be disposed in nesting order."); + } if (m_mutations.Count != 0 && index < m_mutations[^1].nameScopeCount) + { throw new InvalidOperationException("A mutation cannot close a name scope owned by an earlier declaration."); + } m_nameScopes.RemoveAt(index); } @@ -389,11 +399,12 @@ RenderAttachment attachment pass, attachment.texture, attachment.loadAction == RenderLoadAction.Load - ? RenderResourceAccess.ReadWrite - : RenderResourceAccess.Write, + ? RenderResourceAccess.ReadWrite + : RenderResourceAccess.Write, attachment.isDepth - ? RenderResourceUseKind.DepthStencilAttachment - : RenderResourceUseKind.ColorAttachment); + ? RenderResourceUseKind.DepthStencilAttachment + : RenderResourceUseKind.ColorAttachment + ); } private RenderPassRecord AddPass( @@ -402,8 +413,7 @@ private RenderPassRecord AddPass( RenderPassKind kind, TPassData passData, RenderPassExecute execute - ) - where TPassData : notnull + ) where TPassData : notnull { EnsureMutating(); ArgumentException.ThrowIfNullOrWhiteSpace(name); @@ -431,8 +441,8 @@ private void EnsureTexture(RenderTextureHandle handle) { EnsureMutating(); if (handle.generation != m_generation || handle.index < 0 || handle.index >= m_textures.Count - || handle.allocationId != m_textures[handle.index].allocationId) - { + || handle.allocationId != m_textures[handle.index].allocationId + ) { throw new ArgumentException("Texture handle does not belong to this render graph generation.", nameof(handle)); } } @@ -441,8 +451,8 @@ private void EnsureBuffer(RenderBufferHandle handle) { EnsureMutating(); if (handle.generation != m_generation || handle.index < 0 || handle.index >= m_buffers.Count - || handle.allocationId != m_buffers[handle.index].allocationId) - { + || handle.allocationId != m_buffers[handle.index].allocationId + ) { throw new ArgumentException("Buffer handle does not belong to this render graph generation.", nameof(handle)); } } @@ -457,14 +467,13 @@ private void EnsureBuilding() private string QualifyName(string name) => m_nameScopes.Count == 0 - ? name - : $"{string.Join('/', m_nameScopes.ConvertAll(static scope => scope.name))}/{name}"; + ? name + : $"{string.Join('/', m_nameScopes.ConvertAll(static scope => scope.name))}/{name}"; private static void ValidateNameAndValue( string name, T value - ) - where T : class + ) where T : class { ArgumentException.ThrowIfNullOrWhiteSpace(name); ArgumentNullException.ThrowIfNull(value); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.cs index 731ef1a9f..c296e9a1a 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.cs @@ -1,6 +1,6 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; +using Inno.Core.Diagnostics; namespace Inno.Rendering; @@ -14,17 +14,22 @@ internal static RenderGraphCompileResult Compile( RenderGraphValidationState validation ) { if (!validation.result.isValid) + { return new RenderGraphCompileResult(null, validation.result.diagnostics); + } Dictionary schedulePositions = []; for (int index = 0; index < validation.schedule.Length; index++) + { schedulePositions.Add(validation.schedule[index], index); + } int[] textureSlots = AllocateTextureSlots(textures, passes, schedulePositions); int[] bufferSlots = AllocateBufferSlots(buffers, passes, schedulePositions); return new RenderGraphCompileResult( BuildCompiledGraph(generation, textures, buffers, passes, validation.schedule, textureSlots, bufferSlots), validation.result.diagnostics, - validation.result.culledPassCount); + validation.result.culledPassCount + ); } private static CompiledRenderGraph BuildCompiledGraph( @@ -46,44 +51,53 @@ IReadOnlyList bufferSlots attachments.Add(new CompiledRenderAttachment(attachment)); } - compiledPasses.Add(new CompiledRenderPass( - pass.name, - pass.phase, - pass.kind, - viewIndex, - attachments, - pass.surface, - pass.clearsPresentationTarget, - pass.presentationClearColor, - pass.viewTransform, - pass.recordingMode, - pass.execute)); + compiledPasses.Add( + new CompiledRenderPass( + pass.name, + pass.phase, + pass.kind, + viewIndex, + attachments, + pass.surface, + pass.clearsPresentationTarget, + pass.presentationClearColor, + pass.viewTransform, + pass.recordingMode, + pass.execute + ) + ); } List compiledTextures = []; for (int index = 0; index < textures.Count; index++) { RenderTextureRecord texture = textures[index]; - compiledTextures.Add(new CompiledRenderTexture( - new RenderTextureHandle(index, generation, texture.allocationId), - texture.name, - texture.descriptor, - texture.imported, - texture.persistentHandle, - textureSlots[index])); + compiledTextures.Add( + new CompiledRenderTexture( + new RenderTextureHandle(index, generation, texture.allocationId), + texture.name, + texture.descriptor, + texture.imported, + texture.persistentHandle, + textureSlots[index] + ) + ); } List compiledBuffers = []; for (int index = 0; index < buffers.Count; index++) { RenderBufferRecord buffer = buffers[index]; - compiledBuffers.Add(new CompiledRenderBuffer( - new RenderBufferHandle(index, generation, buffer.allocationId), - buffer.name, - buffer.descriptor, - buffer.imported, - buffer.persistentHandle, - bufferSlots[index])); + compiledBuffers.Add( + new CompiledRenderBuffer( + new RenderBufferHandle(index, generation, buffer.allocationId), + buffer.name, + buffer.descriptor, + buffer.imported, + buffer.persistentHandle, + bufferSlots[index] + ) + ); } return new CompiledRenderGraph(generation, compiledPasses, compiledTextures, compiledBuffers); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphDependencyAnalysis.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphDependencyAnalysis.cs index 196e30c4b..66894a8a7 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphDependencyAnalysis.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphDependencyAnalysis.cs @@ -1,6 +1,6 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; +using Inno.Core.Diagnostics; namespace Inno.Rendering; @@ -39,18 +39,23 @@ List diagnostics foreach (RenderResourceUse use in pass.resources) { if (!analysis.uniqueUses.Add(use.key)) + { continue; + } bool reads = use.access is RenderResourceAccess.Read or RenderResourceAccess.ReadWrite; bool writes = use.access is RenderResourceAccess.Write or RenderResourceAccess.ReadWrite; if (reads && !initialized.Contains(use.key)) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_UNINITIALIZED_READ", - $"Pass '{passes[passIndex].name}' reads '{GetResourceName(use.key, textures, buffers)}' before it is initialized.", - DiagnosticSeverity.Error, - passes[passIndex].name, - GetResourceName(use.key, textures, buffers))); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_UNINITIALIZED_READ", + $"Pass '{passes[passIndex].name}' reads '{GetResourceName(use.key, textures, buffers)}' before it is initialized.", + DiagnosticSeverity.Error, + passes[passIndex].name, + GetResourceName(use.key, textures, buffers) + ) + ); } if (lastWriters.TryGetValue(use.key, out int writer)) @@ -102,7 +107,6 @@ List diagnostics } } } - } private static bool StoresResult( @@ -113,8 +117,8 @@ RenderResourceKey key { if (key.isTexture && attachment.texture.index == key.index - && attachment.storeAction == RenderStoreAction.Discard) - { + && attachment.storeAction == RenderStoreAction.Discard + ) { return false; } } @@ -155,15 +159,13 @@ private static bool IsImported( RenderResourceKey key, IReadOnlyList textures, IReadOnlyList buffers - ) - => key.isTexture ? textures[key.index].imported : buffers[key.index].imported; + ) => key.isTexture ? textures[key.index].imported : buffers[key.index].imported; private static string GetResourceName( RenderResourceKey key, IReadOnlyList textures, IReadOnlyList buffers - ) - => key.isTexture ? textures[key.index].name : buffers[key.index].name; + ) => key.isTexture ? textures[key.index].name : buffers[key.index].name; private static void AddDependency( int dependency, diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphMutationScope.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphMutationScope.cs index 7119a79cb..d35438b09 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphMutationScope.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphMutationScope.cs @@ -53,7 +53,9 @@ public void Dispose() { RenderGraphBuilder? graph = m_graph; if (graph is null) + { return; + } graph.EndMutation(this); m_graph = null; } diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphNameScope.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphNameScope.cs index 531394fe9..f507f0ddb 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphNameScope.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphNameScope.cs @@ -26,9 +26,10 @@ public void Dispose() { RenderGraphBuilder? graph = m_graph; if (graph is null) + { return; + } graph.EndNameScope(m_id); m_graph = null; } } - diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs index 5bdcbda66..75f8f99b4 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs @@ -1,6 +1,6 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; +using Inno.Core.Diagnostics; namespace Inno.Rendering; @@ -10,33 +10,33 @@ private static int[] AllocateTextureSlots( IReadOnlyList textures, IReadOnlyList passes, IReadOnlyDictionary schedulePositions - ) - => AllocateSlots( - textures.Count, - index => textures[index].imported, - ( - left, - right - ) => textures[left].descriptor.Equals(textures[right].descriptor), - new RenderResourceKey(true, 0), - passes, - schedulePositions); + ) => AllocateSlots( + textures.Count, + index => textures[index].imported, + ( + left, + right + ) => textures[left].descriptor.Equals(textures[right].descriptor), + new RenderResourceKey(true, 0), + passes, + schedulePositions + ); private static int[] AllocateBufferSlots( IReadOnlyList buffers, IReadOnlyList passes, IReadOnlyDictionary schedulePositions - ) - => AllocateSlots( - buffers.Count, - index => buffers[index].imported, - ( - left, - right - ) => buffers[left].descriptor.Equals(buffers[right].descriptor), - new RenderResourceKey(false, 0), - passes, - schedulePositions); + ) => AllocateSlots( + buffers.Count, + index => buffers[index].imported, + ( + left, + right + ) => buffers[left].descriptor.Equals(buffers[right].descriptor), + new RenderResourceKey(false, 0), + passes, + schedulePositions + ); private static int[] AllocateSlots( int resourceCount, @@ -88,8 +88,8 @@ IReadOnlyDictionary schedulePositions { (int representative, int lastUse) allocation = allocations[slot]; if (allocation.lastUse < firstUses[resource] - && descriptorsEqual(allocation.representative, resource)) - { + && descriptorsEqual(allocation.representative, resource) + ) { selected = slot; allocations[slot] = (allocation.representative, lastUses[resource]); break; diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphScheduling.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphScheduling.cs index 29dad5006..378170028 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphScheduling.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphScheduling.cs @@ -1,6 +1,6 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; +using Inno.Core.Diagnostics; namespace Inno.Rendering; diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs index 7f2812ced..fbc54897e 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs @@ -1,6 +1,6 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; +using Inno.Core.Diagnostics; namespace Inno.Rendering; @@ -267,58 +267,72 @@ byte clearStencil internal sealed class RenderPassRecord { internal required int index { get; init; } + /// /// Gets the human-readable name used for presentation and diagnostics. /// public required string name { get; init; } + /// /// Gets the render phase that owns this pass declaration. /// public required RenderPhaseId phase { get; init; } + /// /// Gets the operation kind that determines how this value is interpreted. /// public required RenderPassKind kind { get; init; } + /// /// Gets the callback that records commands for this render pass. /// public required Action execute { get; init; } + /// /// Gets the render phases that must execute after this pass. /// public List before { get; } = []; + /// /// Gets the render phases that must execute before this pass. /// public List after { get; } = []; + /// /// Gets the complete resource access declarations used for graph dependency analysis. /// public List resources { get; } = []; + /// /// Gets the color and depth attachments written by this render pass. /// public List attachments { get; } = []; + /// /// Gets the presentation surface targeted by this render pass. /// public RenderSurfaceHandle surface { get; set; } + /// /// Gets the color used when the presentation surface is cleared. /// public RenderClearColor presentationClearColor { get; set; } + /// /// Gets the optional view and projection transform applied by this pass. /// public RenderViewTransform? viewTransform { get; set; } + /// /// Gets whether the caller-visible condition represented by this property is satisfied. /// public bool clearsPresentationTarget { get; set; } + /// /// Gets whether this value has side effect. /// public bool hasSideEffect { get; set; } + /// /// Gets whether the pass records graphics, compute, or transfer commands. /// diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs index 03f0ad95a..8a43dbc72 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs @@ -1,6 +1,6 @@ -using Inno.Core.Diagnostics; using System; using System.Collections.Generic; +using Inno.Core.Diagnostics; namespace Inno.Rendering; @@ -30,41 +30,62 @@ RenderGraphValidationWorkspace analysis // End-of-graph output and scheduling diagnostics are revision-local, not prefix state. diagnostics = new List(diagnostics); foreach (RenderResourceKey output in outputs) + { if (!analysis.initialized.Contains(output)) - diagnostics.Add(new RenderGraphDiagnostic("RENDER_GRAPH_OUTPUT_UNINITIALIZED", - $"Graph output '{GetResourceName(output, textures, buffers)}' has no stored contents at the end of the graph.", - DiagnosticSeverity.Error, resourceName: GetResourceName(output, textures, buffers))); + { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_OUTPUT_UNINITIALIZED", + $"Graph output '{GetResourceName(output, textures, buffers)}' has no stored contents at the end of the graph.", + DiagnosticSeverity.Error, + resourceName: GetResourceName(output, textures, buffers) + ) + ); + } + } if (ContainsErrors(diagnostics)) + { return CreateState(null); + } HashSet livePasses = FindLivePasses(textures, buffers, passes, outputs, analysis); List? schedule = TopologicalSort(passes.Count, livePasses, analysis); if (schedule is null) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_CYCLE", - "Pass ordering and resource dependencies contain a cycle.", - DiagnosticSeverity.Error)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_CYCLE", + "Pass ordering and resource dependencies contain a cycle.", + DiagnosticSeverity.Error + ) + ); return CreateState(null); } if (schedule.Count > capabilities.limits.maxViews) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_VIEW_LIMIT", - $"Graph requires {schedule.Count} views but the device supports {capabilities.limits.maxViews}.", - DiagnosticSeverity.Error)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_VIEW_LIMIT", + $"Graph requires {schedule.Count} views but the device supports {capabilities.limits.maxViews}.", + DiagnosticSeverity.Error + ) + ); return CreateState(null); } return CreateState(schedule.ToArray()); RenderGraphValidationState CreateState(int[]? orderedPasses) - => new(new RenderGraphValidationResult( - orderedPasses is not null, - diagnostics, - passes.Count, - orderedPasses?.Length ?? 0, - textures.Count, - buffers.Count), orderedPasses ?? []); + => new( + new RenderGraphValidationResult( + orderedPasses is not null, + diagnostics, + passes.Count, + orderedPasses?.Length ?? 0, + textures.Count, + buffers.Count + ), + orderedPasses ?? [] + ); } private static void ValidateResources( @@ -81,90 +102,114 @@ int bufferStart RenderTextureDescriptor descriptor = texture.descriptor; if (descriptor.width > capabilities.limits.maxTextureSize || descriptor.height > capabilities.limits.maxTextureSize - || descriptor.depth > capabilities.limits.maxTextureSize) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_TEXTURE_LIMIT", - $"Texture '{texture.name}' exceeds the device texture extent limit.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + || descriptor.depth > capabilities.limits.maxTextureSize + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_TEXTURE_LIMIT", + $"Texture '{texture.name}' exceeds the device texture extent limit.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if (descriptor.dimension == RenderTextureDimension.Texture2D && descriptor.arrayLayers > 1 - && !capabilities.Supports(GraphicsCapability.Texture2DArray)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_TEXTURE_ARRAY_UNSUPPORTED", - $"Texture '{texture.name}' requires two-dimensional texture-array capability.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.Supports(GraphicsCapability.Texture2DArray) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_TEXTURE_ARRAY_UNSUPPORTED", + $"Texture '{texture.name}' requires two-dimensional texture-array capability.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if (descriptor.dimension == RenderTextureDimension.Texture3D - && !capabilities.Supports(GraphicsCapability.Texture3D)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_TEXTURE_3D_UNSUPPORTED", - $"Texture '{texture.name}' requires three-dimensional texture capability.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.Supports(GraphicsCapability.Texture3D) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_TEXTURE_3D_UNSUPPORTED", + $"Texture '{texture.name}' requires three-dimensional texture capability.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if (descriptor.dimension == RenderTextureDimension.Cube && descriptor.arrayLayers > 1 - && !capabilities.Supports(GraphicsCapability.TextureCubeArray)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_TEXTURE_CUBE_ARRAY_UNSUPPORTED", - $"Texture '{texture.name}' requires cubemap-array capability.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.Supports(GraphicsCapability.TextureCubeArray) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_TEXTURE_CUBE_ARRAY_UNSUPPORTED", + $"Texture '{texture.name}' requires cubemap-array capability.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } bool attachmentUsage = (descriptor.usage - & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0; + & (RenderTextureUsage.ColorAttachment | RenderTextureUsage.DepthStencilAttachment)) != 0; if ((descriptor.usage & RenderTextureUsage.Sampled) != 0 - && !capabilities.SupportsSampled(descriptor.format, descriptor.dimension)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_FORMAT_SAMPLED_UNSUPPORTED", - $"Texture format '{descriptor.format}' is not supported for sampling.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.SupportsSampled(descriptor.format, descriptor.dimension) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_FORMAT_SAMPLED_UNSUPPORTED", + $"Texture format '{descriptor.format}' is not supported for sampling.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if (attachmentUsage && !capabilities.SupportsRenderTarget(descriptor.format)) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_FORMAT_ATTACHMENT_UNSUPPORTED", - $"Texture format '{descriptor.format}' is not supported as an attachment.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_FORMAT_ATTACHMENT_UNSUPPORTED", + $"Texture format '{descriptor.format}' is not supported as an attachment.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if (attachmentUsage && descriptor.sampleCount > 1 - && !capabilities.SupportsMultisampleRenderTarget(descriptor.format)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_FORMAT_MSAA_UNSUPPORTED", - $"Texture format '{descriptor.format}' is not supported as a multisampled attachment.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.SupportsMultisampleRenderTarget(descriptor.format) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_FORMAT_MSAA_UNSUPPORTED", + $"Texture format '{descriptor.format}' is not supported as a multisampled attachment.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } if ((descriptor.usage & RenderTextureUsage.Storage) != 0 && (!capabilities.Supports(GraphicsCapability.Compute) || !capabilities.Supports(GraphicsCapability.StorageTexture) || (!capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Read) - && !capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Write)))) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_FORMAT_STORAGE_UNSUPPORTED", - $"Texture '{texture.name}' cannot be used for unordered shader access on this device.", - DiagnosticSeverity.Error, - resourceName: texture.name)); + && !capabilities.SupportsStorage(descriptor.format, RenderStorageAccess.Write))) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_FORMAT_STORAGE_UNSUPPORTED", + $"Texture '{texture.name}' cannot be used for unordered shader access on this device.", + DiagnosticSeverity.Error, + resourceName: texture.name + ) + ); } } @@ -172,25 +217,30 @@ int bufferStart { RenderBufferRecord buffer = buffers[bufferIndex]; if ((buffer.descriptor.usage & RenderBufferUsage.Storage) != 0 - && !capabilities.Supports(GraphicsCapability.StorageBuffer)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_STORAGE_BUFFER_UNSUPPORTED", - $"Buffer '{buffer.name}' requires storage-buffer capability.", - DiagnosticSeverity.Error, - resourceName: buffer.name)); + && !capabilities.Supports(GraphicsCapability.StorageBuffer) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_STORAGE_BUFFER_UNSUPPORTED", + $"Buffer '{buffer.name}' requires storage-buffer capability.", + DiagnosticSeverity.Error, + resourceName: buffer.name + ) + ); } - if ((buffer.descriptor.usage & RenderBufferUsage.Index) != 0 && buffer.descriptor.elementStride == sizeof(uint) - && !capabilities.Supports(GraphicsCapability.Index32)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_INDEX32_UNSUPPORTED", - $"Buffer '{buffer.name}' requires unsigned 32-bit index capability.", - DiagnosticSeverity.Error, - resourceName: buffer.name)); + && !capabilities.Supports(GraphicsCapability.Index32) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_INDEX32_UNSUPPORTED", + $"Buffer '{buffer.name}' requires unsigned 32-bit index capability.", + DiagnosticSeverity.Error, + resourceName: buffer.name + ) + ); } } } @@ -208,49 +258,64 @@ int passStart RenderPassRecord pass = passes[passIndex]; if (pass.kind == RenderPassKind.Compute && !capabilities.Supports(GraphicsCapability.Compute)) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_COMPUTE_UNSUPPORTED", - $"Compute pass '{pass.name}' requires compute capability.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_COMPUTE_UNSUPPORTED", + $"Compute pass '{pass.name}' requires compute capability.", + DiagnosticSeverity.Error, + pass.name + ) + ); } ValidatePassResourceConflicts(pass, diagnostics); ValidatePassResourceUsage(capabilities, textures, buffers, pass, diagnostics); if (pass.kind != RenderPassKind.Raster && pass.attachments.Count != 0) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_ATTACHMENT_DOMAIN", - $"Pass '{pass.name}' is not a raster pass and cannot own attachments.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_ATTACHMENT_DOMAIN", + $"Pass '{pass.name}' is not a raster pass and cannot own attachments.", + DiagnosticSeverity.Error, + pass.name + ) + ); } if (pass.surface.isValid && pass.kind != RenderPassKind.Raster) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_SURFACE_DOMAIN", - $"Pass '{pass.name}' is not a raster pass and cannot target a presentation surface.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_SURFACE_DOMAIN", + $"Pass '{pass.name}' is not a raster pass and cannot target a presentation surface.", + DiagnosticSeverity.Error, + pass.name + ) + ); } if (pass.surface.isValid && pass.attachments.Count != 0) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_SURFACE_ATTACHMENTS", - $"Raster pass '{pass.name}' cannot target a presentation surface and texture attachments together.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_SURFACE_ATTACHMENTS", + $"Raster pass '{pass.name}' cannot target a presentation surface and texture attachments together.", + DiagnosticSeverity.Error, + pass.name + ) + ); } if (pass.clearsPresentationTarget && pass.attachments.Count != 0) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_PRESENTATION_CLEAR_ATTACHMENTS", - $"Raster pass '{pass.name}' cannot combine a presentation clear with texture attachments.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_PRESENTATION_CLEAR_ATTACHMENTS", + $"Raster pass '{pass.name}' cannot combine a presentation clear with texture attachments.", + DiagnosticSeverity.Error, + pass.name + ) + ); } if (pass.attachments.Count == 0) @@ -269,32 +334,38 @@ int passStart RenderTextureDescriptor descriptor = texture.descriptor; if (!attachedTextures.Add(attachment.texture.index)) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_DUPLICATE_ATTACHMENT_RESOURCE", - $"Raster pass '{pass.name}' attaches texture '{texture.name}' more than once.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_DUPLICATE_ATTACHMENT_RESOURCE", + $"Raster pass '{pass.name}' attaches texture '{texture.name}' more than once.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } if (attachment.mipLevel >= descriptor.mipCount || (attachment.mipLevel < descriptor.mipCount - && attachment.arrayLayer >= descriptor.GetSubresourceLayerCount(attachment.mipLevel))) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_ATTACHMENT_SUBRESOURCE", - $"Raster pass '{pass.name}' attachment subresource is outside texture '{texture.name}'.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + && attachment.arrayLayer >= descriptor.GetSubresourceLayerCount(attachment.mipLevel)) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_ATTACHMENT_SUBRESOURCE", + $"Raster pass '{pass.name}' attachment subresource is outside texture '{texture.name}'.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } if (attachment.isDepth) { depthCount++; if ((descriptor.usage & RenderTextureUsage.DepthStencilAttachment) == 0 - || !IsDepthFormat(descriptor.format)) - { + || !IsDepthFormat(descriptor.format) + ) { AddAttachmentUsageError(pass, texture, "depth-stencil", diagnostics); } } @@ -303,17 +374,20 @@ int passStart colorCount++; if (!colorSlots.Add(attachment.slot)) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_DUPLICATE_ATTACHMENT", - $"Raster pass '{pass.name}' uses color attachment slot {attachment.slot} more than once.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_DUPLICATE_ATTACHMENT", + $"Raster pass '{pass.name}' uses color attachment slot {attachment.slot} more than once.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } if ((descriptor.usage & RenderTextureUsage.ColorAttachment) == 0 - || IsDepthFormat(descriptor.format)) - { + || IsDepthFormat(descriptor.format) + ) { AddAttachmentUsageError(pass, texture, "color", diagnostics); } } @@ -325,24 +399,30 @@ int passStart int firstHeight = MipExtent(firstDescriptor.height, pass.attachments[0].mipLevel); if (firstWidth != attachmentWidth || firstHeight != attachmentHeight - || firstDescriptor.sampleCount != descriptor.sampleCount) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_ATTACHMENT_MISMATCH", - $"Raster pass '{pass.name}' attachments must have equal width, height and sample count.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + || firstDescriptor.sampleCount != descriptor.sampleCount + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_ATTACHMENT_MISMATCH", + $"Raster pass '{pass.name}' attachments must have equal width, height and sample count.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } } if (colorCount > capabilities.limits.maxColorAttachments || depthCount > 1) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_ATTACHMENT_LIMIT", - $"Raster pass '{pass.name}' exceeds the device attachment limit.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_ATTACHMENT_LIMIT", + $"Raster pass '{pass.name}' exceeds the device attachment limit.", + DiagnosticSeverity.Error, + pass.name + ) + ); } } } @@ -370,11 +450,14 @@ List diagnostics continue; } - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_PASS_HAZARD", - $"Pass '{pass.name}' declares conflicting access for one resource. Use an explicit ReadWrite declaration.", - DiagnosticSeverity.Error, - pass.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_PASS_HAZARD", + $"Pass '{pass.name}' declares conflicting access for one resource. Use an explicit ReadWrite declaration.", + DiagnosticSeverity.Error, + pass.name + ) + ); } } @@ -394,8 +477,8 @@ List diagnostics { RenderResourceUseKind.GenericRead => RenderTextureUsage.Sampled, RenderResourceUseKind.StorageRead - or RenderResourceUseKind.StorageWrite - or RenderResourceUseKind.StorageReadWrite + or RenderResourceUseKind.StorageWrite + or RenderResourceUseKind.StorageReadWrite => RenderTextureUsage.Storage, RenderResourceUseKind.CopySource => RenderTextureUsage.CopySource, RenderResourceUseKind.CopyDestination => RenderTextureUsage.CopyDestination, @@ -411,20 +494,15 @@ or RenderResourceUseKind.StorageReadWrite if (use.kind is RenderResourceUseKind.CopySource or RenderResourceUseKind.CopyDestination - && !capabilities.Supports(GraphicsCapability.TextureBlit)) - { - AddCapabilityError( - pass, - texture.name, - "texture-copy", - GraphicsCapability.TextureBlit, - diagnostics); + && !capabilities.Supports(GraphicsCapability.TextureBlit) + ) { + AddCapabilityError(pass, texture.name, "texture-copy", GraphicsCapability.TextureBlit, diagnostics); } if (use.kind is RenderResourceUseKind.StorageRead or RenderResourceUseKind.StorageWrite - or RenderResourceUseKind.StorageReadWrite) - { + or RenderResourceUseKind.StorageReadWrite + ) { RenderStorageAccess access = use.kind switch { RenderResourceUseKind.StorageRead => RenderStorageAccess.Read, @@ -433,14 +511,17 @@ or RenderResourceUseKind.StorageWrite _ => throw new InvalidOperationException("Unexpected storage texture access.") }; if (!capabilities.Supports(GraphicsCapability.StorageTexture) - || !capabilities.SupportsStorage(texture.descriptor.format, access)) - { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_STORAGE_TEXTURE_ACCESS_UNSUPPORTED", - $"Texture '{texture.name}' does not support {access} storage access required by pass '{pass.name}'.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + || !capabilities.SupportsStorage(texture.descriptor.format, access) + ) { + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_STORAGE_TEXTURE_ACCESS_UNSUPPORTED", + $"Texture '{texture.name}' does not support {access} storage access required by pass '{pass.name}'.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } } @@ -450,8 +531,8 @@ or RenderResourceUseKind.StorageWrite RenderBufferUsage requiredBufferUsage = use.kind switch { RenderResourceUseKind.StorageRead - or RenderResourceUseKind.StorageWrite - or RenderResourceUseKind.StorageReadWrite + or RenderResourceUseKind.StorageWrite + or RenderResourceUseKind.StorageReadWrite => RenderBufferUsage.Storage, RenderResourceUseKind.CopySource => RenderBufferUsage.CopySource, RenderResourceUseKind.CopyDestination => RenderBufferUsage.CopyDestination, @@ -460,13 +541,7 @@ or RenderResourceUseKind.StorageReadWrite if (requiredBufferUsage != 0) { // Buffer names and descriptors are validated by the overload below. - ValidateBufferUse( - capabilities, - buffers, - pass, - use, - requiredBufferUsage, - diagnostics); + ValidateBufferUse(capabilities, buffers, pass, use, requiredBufferUsage, diagnostics); } } } @@ -486,14 +561,9 @@ List diagnostics } if (use.kind is RenderResourceUseKind.CopySource or RenderResourceUseKind.CopyDestination - && !capabilities.Supports(GraphicsCapability.BufferCopy)) - { - AddCapabilityError( - pass, - buffer.name, - "buffer-copy", - GraphicsCapability.BufferCopy, - diagnostics); + && !capabilities.Supports(GraphicsCapability.BufferCopy) + ) { + AddCapabilityError(pass, buffer.name, "buffer-copy", GraphicsCapability.BufferCopy, diagnostics); } } @@ -519,12 +589,15 @@ private static void AddAttachmentUsageError( string role, List diagnostics ) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_ATTACHMENT_USAGE", - $"Texture '{texture.name}' is not declared for {role} attachment usage.", - DiagnosticSeverity.Error, - pass.name, - texture.name)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_ATTACHMENT_USAGE", + $"Texture '{texture.name}' is not declared for {role} attachment usage.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); } private static void AddResourceUsageError( @@ -533,12 +606,15 @@ private static void AddResourceUsageError( string requiredUsage, List diagnostics ) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_RESOURCE_USAGE", - $"Resource '{resourceName}' used by pass '{pass.name}' requires '{requiredUsage}' usage.", - DiagnosticSeverity.Error, - pass.name, - resourceName)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_RESOURCE_USAGE", + $"Resource '{resourceName}' used by pass '{pass.name}' requires '{requiredUsage}' usage.", + DiagnosticSeverity.Error, + pass.name, + resourceName + ) + ); } private static void AddCapabilityError( @@ -548,11 +624,14 @@ private static void AddCapabilityError( GraphicsCapability requiredFeature, List diagnostics ) { - diagnostics.Add(new RenderGraphDiagnostic( - "RENDER_GRAPH_CAPABILITY_UNSUPPORTED", - $"Pass '{pass.name}' requires '{requiredFeature}' for {operation} operations.", - DiagnosticSeverity.Error, - pass.name, - resourceName)); + diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_CAPABILITY_UNSUPPORTED", + $"Pass '{pass.name}' requires '{requiredFeature}' for {operation} operations.", + DiagnosticSeverity.Error, + pass.name, + resourceName + ) + ); } } diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs index 842c672c2..59ce7d6ca 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs @@ -95,11 +95,7 @@ public RenderPassBuilder AllowParallelRecording() /// public RenderPassBuilder ReadTexture(RenderTextureHandle texture) { - m_graph.AddUse( - m_pass, - texture, - RenderResourceAccess.Read, - RenderResourceUseKind.GenericRead); + m_graph.AddUse(m_pass, texture, RenderResourceAccess.Read, RenderResourceUseKind.GenericRead); return this; } @@ -114,12 +110,7 @@ public RenderPassBuilder ReadTexture(RenderTextureHandle texture) /// public RenderPassBuilder ReadBuffer(RenderBufferHandle buffer) { - m_graph.AddUse( - m_pass, - buffer, - RenderResourceAccess.Read, - RenderResourceUseKind.GenericRead); + m_graph.AddUse(m_pass, buffer, RenderResourceAccess.Read, RenderResourceUseKind.GenericRead); return this; } } - diff --git a/src/services/rendering/Inno.Rendering/IRenderFrameUploadService.cs b/src/services/rendering/Inno.Rendering/IRenderFrameUploadService.cs index efb733e2d..9eaa6d1d9 100644 --- a/src/services/rendering/Inno.Rendering/IRenderFrameUploadService.cs +++ b/src/services/rendering/Inno.Rendering/IRenderFrameUploadService.cs @@ -1,5 +1,4 @@ using System; - using Inno.Rendering; namespace Inno.Rendering; diff --git a/src/services/rendering/Inno.Rendering/Shaders/GraphicsProgramArtifactCodec.cs b/src/services/rendering/Inno.Rendering/Shaders/GraphicsProgramArtifactCodec.cs index a9abf0a55..a4c0e781a 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/GraphicsProgramArtifactCodec.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/GraphicsProgramArtifactCodec.cs @@ -40,7 +40,9 @@ public static byte[] Encode(GraphicsPipelineDescriptor descriptor) WriteStage(writer, descriptor.vertexShader.Span); WriteStage(writer, descriptor.fragmentShader.Span); if (descriptor.bindings.Count > C_MAX_BINDINGS) + { throw new InvalidDataException("The graphics program contains too many bindings."); + } writer.Write(descriptor.bindings.Count); foreach (RenderShaderBindingDescriptor binding in descriptor.bindings) { @@ -77,13 +79,17 @@ public static GraphicsPipelineDescriptor Decode( RenderVertexLayout? vertexLayout = null ) { if (bytes.Length > 2L * C_MAX_STAGE_BYTES + 2L * C_MAX_BINDINGS * C_MAX_NAME_BYTES + 1024 * 1024) + { throw new InvalidDataException("The graphics program exceeds its input budget."); + } try { using var input = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(input, Utf8, leaveOpen: true); if (!ReadBytes(reader, Magic.Length).AsSpan().SequenceEqual(Magic)) + { throw new InvalidDataException("The graphics program magic is invalid."); + } byte[] vertex = ReadBytes(reader, ReadCount(reader, C_MAX_STAGE_BYTES)); byte[] fragment = ReadBytes(reader, ReadCount(reader, C_MAX_STAGE_BYTES)); int count = ReadCount(reader, C_MAX_BINDINGS); @@ -97,14 +103,20 @@ public static GraphicsPipelineDescriptor Decode( ReadEnum(reader), reader.ReadInt32(), ReadEnum(reader), - ReadName(reader)); + ReadName(reader) + ); } RenderRasterState raster = ReadRaster(reader); if (input.Position != input.Length) + { throw new InvalidDataException("The graphics program contains trailing data."); + } return new GraphicsPipelineDescriptor(vertex, fragment, bindings, vertexLayout, raster); } - catch (InvalidDataException) { throw; } + catch (InvalidDataException) + { + throw; + } catch (Exception failure) when (failure is IOException or ArgumentException or OverflowException) { throw new InvalidDataException("The graphics program is malformed.", failure); @@ -116,7 +128,9 @@ private static void WriteStage( ReadOnlySpan bytes ) { if (bytes.IsEmpty || bytes.Length > C_MAX_STAGE_BYTES) + { throw new InvalidDataException("A graphics program stage has an invalid length."); + } writer.Write(bytes.Length); writer.Write(bytes); } @@ -127,7 +141,9 @@ string value ) { byte[] bytes = Utf8.GetBytes(value); if (bytes.Length == 0 || bytes.Length > C_MAX_NAME_BYTES) + { throw new InvalidDataException("A graphics program binding name has an invalid length."); + } writer.Write(bytes.Length); writer.Write(bytes); } @@ -141,7 +157,9 @@ int maximum ) { int count = reader.ReadInt32(); if (count < 0 || count > maximum) + { throw new InvalidDataException("A graphics program field exceeds its length budget."); + } return count; } @@ -150,14 +168,19 @@ private static byte[] ReadBytes( int count ) { if (count > reader.BaseStream.Length - reader.BaseStream.Position) + { throw new InvalidDataException("The graphics program is truncated."); + } byte[] bytes = reader.ReadBytes(count); if (bytes.Length != count) + { throw new InvalidDataException("The graphics program is truncated."); + } return bytes; } - private static T ReadEnum(BinaryReader reader) where T : struct, Enum + private static T ReadEnum(BinaryReader reader) + where T : struct, Enum { T value = (T)Enum.ToObject(typeof(T), reader.ReadInt32()); return Enum.IsDefined(value) ? value : throw new InvalidDataException("A graphics program enum is invalid."); @@ -165,11 +188,11 @@ private static T ReadEnum(BinaryReader reader) where T : struct, Enum private static bool ReadBoolean(BinaryReader reader) => reader.ReadByte() switch - { - 0 => false, - 1 => true, - _ => throw new InvalidDataException("A graphics program boolean is invalid.") - }; + { + 0 => false, + 1 => true, + _ => throw new InvalidDataException("A graphics program boolean is invalid.") + }; private static void WriteRaster( BinaryWriter writer, @@ -180,8 +203,10 @@ RenderRasterState state || (state.colorWriteMask & ~0xF) != 0 || !Enum.IsDefined(state.blend.colorSource) || !Enum.IsDefined(state.blend.colorDestination) || !Enum.IsDefined(state.blend.colorEquation) || !Enum.IsDefined(state.blend.alphaSource) - || !Enum.IsDefined(state.blend.alphaDestination) || !Enum.IsDefined(state.blend.alphaEquation)) + || !Enum.IsDefined(state.blend.alphaDestination) || !Enum.IsDefined(state.blend.alphaEquation) + ) { throw new InvalidDataException("The graphics program raster state is invalid."); + } writer.Write((int)state.topology); writer.Write((int)state.cull); writer.Write((int)state.frontFace); @@ -209,7 +234,9 @@ private static RenderRasterState ReadRaster(BinaryReader reader) bool depthWrite = ReadBoolean(reader); byte mask = reader.ReadByte(); if ((mask & ~0xF) != 0) + { throw new InvalidDataException("A graphics program color mask is invalid."); + } bool multisampling = ReadBoolean(reader); var blend = new RenderBlendState { diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderInterface.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderInterface.cs index 568aa36ce..8e4a01c68 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderInterface.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderInterface.cs @@ -25,6 +25,4 @@ public ShaderInterface(IReadOnlyList bindings) /// Gets stable expected bindings. /// public IReadOnlyList bindings { get; } - } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderInterfaceBinding.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderInterfaceBinding.cs index 9cd80f1af..6dc0b829f 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderInterfaceBinding.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderInterfaceBinding.cs @@ -48,9 +48,13 @@ public ShaderInterfaceBinding( ) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(arrayCount); if (!Enum.IsDefined(bindingKind)) + { throw new ArgumentOutOfRangeException(nameof(bindingKind)); + } if (!Enum.IsDefined(storageAccess)) + { throw new ArgumentOutOfRangeException(nameof(storageAccess)); + } this.id = id; this.type = type; this.stages = stages; @@ -60,7 +64,9 @@ public ShaderInterfaceBinding( this.nativeName = nativeName ?? id.value; ArgumentException.ThrowIfNullOrWhiteSpace(this.nativeName); if (location < 0) + { throw new ArgumentOutOfRangeException(nameof(location)); + } this.location = location; } @@ -98,9 +104,9 @@ public ShaderInterfaceBinding( /// Gets the exact reflected symbol emitted by the adapter, distinct from the logical property ID. /// public string nativeName { get; } + /// /// Gets an explicitly compiled resource slot, or null for a caller-assigned layout. /// public int? location { get; } } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderProgramKind.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderProgramKind.cs index 8a6d26a96..db256211f 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderProgramKind.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderProgramKind.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; @@ -22,4 +22,3 @@ public enum ShaderProgramKind /// Compute } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyBindingKind.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyBindingKind.cs index f5de8cdbd..2c80276eb 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyBindingKind.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyBindingKind.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; @@ -30,4 +30,3 @@ public enum ShaderPropertyBindingKind /// StorageBuffer } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs index 29a9bce4f..8976b2766 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; @@ -43,4 +43,3 @@ public ShaderPropertyId(string value) /// public readonly override string ToString() => value ?? string.Empty; } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyType.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyType.cs index 8d8c3a10e..805c0d343 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyType.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyType.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; @@ -58,4 +58,3 @@ public enum ShaderPropertyType /// Buffer } - diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderStage.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderStage.cs index 42c27626d..ad3f6de0f 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderStage.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderStage.cs @@ -1,10 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; @@ -31,4 +31,3 @@ public enum ShaderStage /// Compute = 1 << 2 } - diff --git a/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs b/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs index 80ad08c28..b922ec6e1 100644 --- a/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs +++ b/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs @@ -60,4 +60,3 @@ public static RenderTarget FromTexture(RenderTexture texture) return new RenderTarget(RenderTargetKind.Texture, texture); } } - diff --git a/src/services/rendering/Inno.Rendering/Targets/RenderTexture.cs b/src/services/rendering/Inno.Rendering/Targets/RenderTexture.cs index 34cc9fade..6de52bd2b 100644 --- a/src/services/rendering/Inno.Rendering/Targets/RenderTexture.cs +++ b/src/services/rendering/Inno.Rendering/Targets/RenderTexture.cs @@ -61,4 +61,3 @@ public void Resize(RenderTextureDescriptor descriptor) contentRevision++; } } - diff --git a/src/services/rendering/Inno.Rendering/Views/RenderViewport.cs b/src/services/rendering/Inno.Rendering/Views/RenderViewport.cs index 9ba72b94d..ef6118227 100644 --- a/src/services/rendering/Inno.Rendering/Views/RenderViewport.cs +++ b/src/services/rendering/Inno.Rendering/Views/RenderViewport.cs @@ -59,4 +59,3 @@ int height /// public int height { get; } } - diff --git a/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs b/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs index 5a929d783..531be4cf8 100644 --- a/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs +++ b/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs @@ -1,11 +1,10 @@ -using Inno.Runtime.Contracts; using System; -using Inno.Core.Execution; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - +using Inno.Core.Execution; using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Storage.Runtime; @@ -40,21 +39,26 @@ public StorageRuntime( m_maxWriteBytes = maxWriteBytes; m_operations = lifetime.Own(new LifetimeScope(maxPendingOperations)); if (storage is IDisposable disposable) + { m_operations.Own(disposable); + } } /// /// Gets the storage service owned by this runtime feature. /// public IApplicationStorage storage => this; + /// /// Gets asynchronous operations retained until completion or retirement reporting. /// public int pendingOperations => m_operations.trackedWorkCount; + /// /// Gets operations rejected by finite asynchronous admission capacity. /// public long rejectedOperations => m_operations.rejectedWorkCount; + /// /// Determines whether a value exists. /// @@ -70,8 +74,8 @@ public StorageRuntime( public ValueTask ExistsAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => new(m_operations.RunAsync(token => m_storage.ExistsAsync(key, token), cancellationToken)); + ) => new(m_operations.RunAsync(token => m_storage.ExistsAsync(key, token), cancellationToken)); + /// /// Reads a complete immutable value. /// @@ -87,8 +91,8 @@ public ValueTask ExistsAsync( public ValueTask ReadAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => new(m_operations.RunAsync(token => m_storage.ReadAsync(key, token), cancellationToken)); + ) => new(m_operations.RunAsync(token => m_storage.ReadAsync(key, token), cancellationToken)); + /// /// Atomically replaces a complete value. /// @@ -108,15 +112,19 @@ public ValueTask WriteAsync( StorageKey key, ReadOnlyMemory value, CancellationToken cancellationToken = default - ) - => new(m_operations.RunAsync(async token => + ) => new( + m_operations.RunAsync(async token => { if (value.Length > m_maxWriteBytes) + { throw new ArgumentException("The storage value exceeds its write byte budget.", nameof(value)); + } byte[] snapshot = value.ToArray(); await m_storage.WriteAsync(key, snapshot, token).ConfigureAwait(false); return true; - }, cancellationToken)); + }, cancellationToken) + ); + /// /// Deletes one value without failing when it is already absent. /// @@ -132,8 +140,8 @@ public ValueTask WriteAsync( public ValueTask DeleteAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => new(m_operations.RunAsync(token => m_storage.DeleteAsync(key, token), cancellationToken)); + ) => new(m_operations.RunAsync(token => m_storage.DeleteAsync(key, token), cancellationToken)); + /// /// Lists immutable keys below an optional logical prefix. /// @@ -149,8 +157,7 @@ public ValueTask DeleteAsync( public ValueTask> ListAsync( StorageKey? prefix = null, CancellationToken cancellationToken = default - ) - => new(m_operations.RunAsync(token => m_storage.ListAsync(prefix, token), cancellationToken)); + ) => new(m_operations.RunAsync(token => m_storage.ListAsync(prefix, token), cancellationToken)); /// /// Begins a frame-scoped operation and makes queued work visible. @@ -162,6 +169,7 @@ protected override void OnBeginFrame(RuntimeFrame frame) { OwnFrameScope(StorageExecutionContext.EnterScope(this)); } + /// /// Releases the storage backend after owned work has quiesced. /// diff --git a/src/services/storage/Inno.Storage.Runtime/StorageRuntimeFactory.cs b/src/services/storage/Inno.Storage.Runtime/StorageRuntimeFactory.cs index e0d468303..2cf2415d8 100644 --- a/src/services/storage/Inno.Storage.Runtime/StorageRuntimeFactory.cs +++ b/src/services/storage/Inno.Storage.Runtime/StorageRuntimeFactory.cs @@ -1,7 +1,6 @@ -using Inno.Runtime.Contracts; using System; - using Inno.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Storage.Runtime; @@ -28,7 +27,8 @@ public StorageRuntimeFactory(Func /// public RuntimeSubsystemDescriptor descriptor { get; } = new( new RuntimeSubsystemId("inno.runtime.storage"), - order: -900); + order: -900 + ); /// /// Creates a storage feature over a newly allocated application sandbox. @@ -43,7 +43,7 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); IApplicationStorage storage = m_storageFactory(context) - ?? throw new InvalidOperationException("The application storage factory returned null."); + ?? throw new InvalidOperationException("The application storage factory returned null."); return new StorageRuntime(storage); } } diff --git a/src/services/storage/Inno.Storage/Storage.cs b/src/services/storage/Inno.Storage/Storage.cs index 76aac3262..206a816f8 100644 --- a/src/services/storage/Inno.Storage/Storage.cs +++ b/src/services/storage/Inno.Storage/Storage.cs @@ -1,8 +1,8 @@ -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Inno.Core.Execution; namespace Inno.Storage; @@ -35,7 +35,6 @@ public static IDisposable EnterScope(IApplicationStorage storage) ArgumentNullException.ThrowIfNull(storage); return S_CURRENT_SCOPE.Enter(storage); } - } /// @@ -58,8 +57,7 @@ public static class Storage public static ValueTask ExistsAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => StorageExecutionContext.current.ExistsAsync(key, cancellationToken); + ) => StorageExecutionContext.current.ExistsAsync(key, cancellationToken); /// /// Reads a complete value. @@ -76,8 +74,7 @@ public static ValueTask ExistsAsync( public static ValueTask ReadAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => StorageExecutionContext.current.ReadAsync(key, cancellationToken); + ) => StorageExecutionContext.current.ReadAsync(key, cancellationToken); /// /// Atomically replaces a complete value. @@ -98,8 +95,7 @@ public static ValueTask WriteAsync( StorageKey key, ReadOnlyMemory value, CancellationToken cancellationToken = default - ) - => StorageExecutionContext.current.WriteAsync(key, value, cancellationToken); + ) => StorageExecutionContext.current.WriteAsync(key, value, cancellationToken); /// /// Deletes one value. @@ -116,8 +112,7 @@ public static ValueTask WriteAsync( public static ValueTask DeleteAsync( StorageKey key, CancellationToken cancellationToken = default - ) - => StorageExecutionContext.current.DeleteAsync(key, cancellationToken); + ) => StorageExecutionContext.current.DeleteAsync(key, cancellationToken); /// /// Lists keys below an optional prefix. @@ -134,6 +129,5 @@ public static ValueTask DeleteAsync( public static ValueTask> ListAsync( StorageKey? prefix = null, CancellationToken cancellationToken = default - ) - => StorageExecutionContext.current.ListAsync(prefix, cancellationToken); + ) => StorageExecutionContext.current.ListAsync(prefix, cancellationToken); } diff --git a/src/services/storage/Inno.Storage/StorageKey.cs b/src/services/storage/Inno.Storage/StorageKey.cs index 9f2844a00..68b9f079b 100644 --- a/src/services/storage/Inno.Storage/StorageKey.cs +++ b/src/services/storage/Inno.Storage/StorageKey.cs @@ -21,13 +21,14 @@ public StorageKey(string value) ArgumentException.ThrowIfNullOrWhiteSpace(value); string normalized = value.Replace('\\', '/').Trim('/'); string[] segments = normalized.Split('/'); - if (normalized.Length == 0 || - value.StartsWith('/') || - value.StartsWith('\\') || - segments.Length == 0 || - Array.Exists(segments, static segment => - string.IsNullOrWhiteSpace(segment) || segment is "." or ".." || segment.Contains(':'))) - { + if (normalized.Length == 0 + || value.StartsWith('/') + || value.StartsWith('\\') + || segments.Length == 0 + || Array.Exists(segments, static segment => ( + string.IsNullOrWhiteSpace(segment) || segment is "." or ".." || segment.Contains(':') + )) + ) { throw new ArgumentException("A storage key must be a non-rooted unambiguous sandbox path.", nameof(value)); } this.value = normalized; diff --git a/src/services/storage/Inno.Storage/StorageScope.cs b/src/services/storage/Inno.Storage/StorageScope.cs index a235db24f..8e8da21db 100644 --- a/src/services/storage/Inno.Storage/StorageScope.cs +++ b/src/services/storage/Inno.Storage/StorageScope.cs @@ -21,24 +21,30 @@ public StorageScope(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); if (value[0] == '.' || value[^1] == '.') + { throw new ArgumentException("A storage namespace cannot begin or end with a dot.", nameof(value)); + } foreach (char character in value) { if (!char.IsAsciiLetterOrDigit(character) && character is not '.' and not '_' and not '-') + { throw new ArgumentException("A storage namespace requires portable identifier characters.", nameof(value)); + } } ReadOnlySpan name = value.AsSpan(); int extension = name.IndexOf('.'); if (extension >= 0) + { name = name[..extension]; + } if (name.Equals("CON", StringComparison.OrdinalIgnoreCase) || name.Equals("PRN", StringComparison.OrdinalIgnoreCase) || name.Equals("AUX", StringComparison.OrdinalIgnoreCase) || name.Equals("NUL", StringComparison.OrdinalIgnoreCase) || (name.Length == 4 && name[3] is >= '1' and <= '9' && (name[..3].Equals("COM", StringComparison.OrdinalIgnoreCase) - || name[..3].Equals("LPT", StringComparison.OrdinalIgnoreCase)))) - { + || name[..3].Equals("LPT", StringComparison.OrdinalIgnoreCase))) + ) { throw new ArgumentException("A storage namespace cannot use a reserved portable device name.", nameof(value)); } this.value = value; diff --git a/src/services/text/Inno.Text.Assets/FontImporter.cs b/src/services/text/Inno.Text.Assets/FontImporter.cs index afa272f65..89b38e0f7 100644 --- a/src/services/text/Inno.Text.Assets/FontImporter.cs +++ b/src/services/text/Inno.Text.Assets/FontImporter.cs @@ -4,7 +4,6 @@ using System.IO; using System.Threading; using System.Threading.Tasks; - using Inno.Assets.Pipeline; namespace Inno.Text.Assets; @@ -45,21 +44,26 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", FontMetadataCodec.Encode(metadata), - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); await output.WriteArtifactAsync("font-data", context.sourceBytes, cancellationToken).ConfigureAwait(false); } private static FontMetadata ReadMetadata(ReadOnlySpan source) { if (source.Length < 12) + { throw new InvalidDataException("The font source is truncated."); + } uint signature = BinaryPrimitives.ReadUInt32BigEndian(source); int faceCount; if (signature == 0x74746366) { uint count = BinaryPrimitives.ReadUInt32BigEndian(source[8..]); if (count is 0 or > 65535 || source.Length < checked(12 + ((int)count * 4))) + { throw new InvalidDataException("The OpenType collection header is invalid."); + } faceCount = (int)count; } else if (signature is 0x00010000 or 0x4f54544f or 0x74727565 or 0x74797031) diff --git a/src/services/text/Inno.Text.Runtime/TextRuntime.cs b/src/services/text/Inno.Text.Runtime/TextRuntime.cs index ea6d75330..4d3c1599f 100644 --- a/src/services/text/Inno.Text.Runtime/TextRuntime.cs +++ b/src/services/text/Inno.Text.Runtime/TextRuntime.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; - using Inno.Assets; using Inno.Runtime; using Inno.Runtime.Contracts; @@ -112,7 +111,9 @@ float fontSize ) { ArgumentNullException.ThrowIfNull(font); if (!float.IsFinite(fontSize) || fontSize <= 0f) + { throw new ArgumentOutOfRangeException(nameof(fontSize)); + } ObjectDisposedException.ThrowIf(m_disposed, this); return m_backend.Rasterize(GetOrLoad(font, faceIndex).handle, glyphId, fontSize); } @@ -123,7 +124,9 @@ float fontSize protected override void OnStop() { if (m_disposed) + { return; + } m_disposed = true; List failures = []; foreach (LoadedFont font in m_fonts.Values) @@ -155,7 +158,9 @@ protected override void OnStop() failures.Add(exception); } if (failures.Count > 0) + { throw new AggregateException("Text runtime retirement failed.", failures); + } } private LoadedFont GetOrLoad( @@ -163,14 +168,20 @@ private LoadedFont GetOrLoad( int faceIndex ) { FontMetadata metadata = font.metadata - ?? throw new InvalidOperationException("The font has no imported runtime metadata."); + ?? throw new InvalidOperationException("The font has no imported runtime metadata."); if (font.isMissing) + { throw new InvalidOperationException("The font asset is missing."); + } if ((uint)faceIndex >= (uint)metadata.faceCount) + { throw new ArgumentOutOfRangeException(nameof(faceIndex)); + } var key = new FontKey(font.identity.persistentId, font.contentVersion, faceIndex); if (m_fonts.TryGetValue(key, out LoadedFont? loaded)) + { return loaded; + } ArtifactLease artifact = m_artifacts.AcquireArtifact(font.identity.persistentId, "font-data"); try @@ -178,7 +189,9 @@ int faceIndex byte[] bytes = artifact.ReadAllBytes(); TextFontHandle handle = m_backend.LoadFont(bytes, faceIndex); if (!handle.isValid) + { throw new InvalidOperationException("The text backend rejected the imported font face."); + } loaded = new LoadedFont(handle, artifact); m_fonts.Add(key, loaded); return loaded; diff --git a/src/services/text/Inno.Text.Runtime/TextRuntimeFactory.cs b/src/services/text/Inno.Text.Runtime/TextRuntimeFactory.cs index 29067c741..e4a8173be 100644 --- a/src/services/text/Inno.Text.Runtime/TextRuntimeFactory.cs +++ b/src/services/text/Inno.Text.Runtime/TextRuntimeFactory.cs @@ -1,5 +1,4 @@ using System; - using Inno.Runtime; using Inno.Runtime.Contracts; @@ -28,7 +27,8 @@ public TextRuntimeFactory(Func runtimeFact /// public RuntimeSubsystemDescriptor descriptor { get; } = new( new RuntimeSubsystemId("inno.runtime.text"), - order: -800); + order: -800 + ); /// /// Creates one session-owned text runtime. @@ -43,6 +43,6 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); return m_runtimeFactory(context) - ?? throw new InvalidOperationException("The text runtime factory returned null."); + ?? throw new InvalidOperationException("The text runtime factory returned null."); } } diff --git a/src/services/text/Inno.Text/FontAsset.cs b/src/services/text/Inno.Text/FontAsset.cs index 1c8e12c88..aa694618b 100644 --- a/src/services/text/Inno.Text/FontAsset.cs +++ b/src/services/text/Inno.Text/FontAsset.cs @@ -1,6 +1,5 @@ using System; using System.Buffers.Binary; - using Inno.Assets; using Inno.Extensibility.Types; @@ -79,12 +78,15 @@ public static byte[] Encode(FontMetadata metadata) public static FontMetadata Decode(ReadOnlySpan payload) { if (payload.Length != C_SIZE || BinaryPrimitives.ReadUInt32LittleEndian(payload) != C_MAGIC) + { throw new InvalidOperationException("The font runtime payload is invalid."); + } try { return new FontMetadata( BinaryPrimitives.ReadInt32LittleEndian(payload[4..]), - BinaryPrimitives.ReadInt64LittleEndian(payload[8..])); + BinaryPrimitives.ReadInt64LittleEndian(payload[8..]) + ); } catch (ArgumentOutOfRangeException exception) { diff --git a/src/services/text/Inno.Text/Text.cs b/src/services/text/Inno.Text/Text.cs index 3d002d9ec..c25b30a61 100644 --- a/src/services/text/Inno.Text/Text.cs +++ b/src/services/text/Inno.Text/Text.cs @@ -1,5 +1,4 @@ using System; - using Inno.Core.Execution; namespace Inno.Text; @@ -56,8 +55,7 @@ public static TextLayout Shape( FontAsset font, string text, TextStyle style - ) - => TextExecutionContext.current.Shape(font, text, style, TextShapingOptions.automatic); + ) => TextExecutionContext.current.Shape(font, text, style, TextShapingOptions.automatic); /// /// Shapes text with explicit language, script, and direction hints. @@ -82,8 +80,7 @@ public static TextLayout Shape( string text, TextStyle style, TextShapingOptions options - ) - => TextExecutionContext.current.Shape(font, text, style, options); + ) => TextExecutionContext.current.Shape(font, text, style, options); /// /// Rasterizes one shaped glyph into immutable 8-bit coverage. @@ -108,6 +105,5 @@ public static GlyphBitmap Rasterize( int faceIndex, uint glyphId, float fontSize - ) - => TextExecutionContext.current.Rasterize(font, faceIndex, glyphId, fontSize); + ) => TextExecutionContext.current.Rasterize(font, faceIndex, glyphId, fontSize); } diff --git a/src/services/text/Inno.Text/TextTypes.cs b/src/services/text/Inno.Text/TextTypes.cs index 3b0ab61f1..0e9433ef4 100644 --- a/src/services/text/Inno.Text/TextTypes.cs +++ b/src/services/text/Inno.Text/TextTypes.cs @@ -94,14 +94,22 @@ public TextStyle( float letterSpacing = 0f ) { if (!float.IsFinite(fontSize) || fontSize <= 0f) + { throw new ArgumentOutOfRangeException(nameof(fontSize)); + } ArgumentOutOfRangeException.ThrowIfNegative(faceIndex); if (weight is < 1 or > 1000) + { throw new ArgumentOutOfRangeException(nameof(weight)); + } if (!Enum.IsDefined(style)) + { throw new ArgumentOutOfRangeException(nameof(style)); + } if (!float.IsFinite(letterSpacing)) + { throw new ArgumentOutOfRangeException(nameof(letterSpacing)); + } this.fontSize = fontSize; this.faceIndex = faceIndex; this.weight = weight; @@ -113,22 +121,27 @@ public TextStyle( /// Gets a 16-pixel regular default style. /// public static TextStyle defaultValue { get; } = new(16f); + /// /// Gets the logical font size. /// public float fontSize { get; } + /// /// Gets the collection face index. /// public int faceIndex { get; } + /// /// Gets the CSS-compatible font weight. /// public int weight { get; } + /// /// Gets the requested face slant. /// public TextFontStyle style { get; } + /// /// Gets additional spacing appended to each glyph advance. /// @@ -158,7 +171,9 @@ public TextShapingOptions( string? script = null ) { if (!Enum.IsDefined(direction)) + { throw new ArgumentOutOfRangeException(nameof(direction)); + } this.direction = direction; this.language = string.IsNullOrWhiteSpace(language) ? null : language.Trim(); this.script = string.IsNullOrWhiteSpace(script) ? null : script.Trim(); @@ -168,14 +183,17 @@ public TextShapingOptions( /// Gets automatic shaping hints. /// public static TextShapingOptions automatic { get; } = new(); + /// /// Gets the requested logical direction. /// public TextDirection direction { get; } + /// /// Gets the optional BCP 47 language code. /// public string? language { get; } + /// /// Gets the optional ISO 15924 script code. /// @@ -269,9 +287,13 @@ float height ) { ArgumentNullException.ThrowIfNull(glyphs); if (!float.IsFinite(width) || width < 0f) + { throw new ArgumentOutOfRangeException(nameof(width)); + } if (!float.IsFinite(height) || height < 0f) + { throw new ArgumentOutOfRangeException(nameof(height)); + } m_glyphs = [..glyphs]; this.metrics = metrics; this.width = width; @@ -282,14 +304,17 @@ float height /// Gets the immutable positioned glyph sequence. /// public IReadOnlyList glyphs => m_glyphs; + /// /// Gets the font metrics used to build this layout. /// public TextMetrics metrics { get; } + /// /// Gets the aggregate horizontal advance. /// public float width { get; } + /// /// Gets the aggregate line height. /// @@ -335,9 +360,13 @@ ReadOnlySpan pixels ArgumentOutOfRangeException.ThrowIfNegative(width); ArgumentOutOfRangeException.ThrowIfNegative(height); if (pixels.Length != checked(width * height)) + { throw new ArgumentException("Glyph coverage length must match its dimensions.", nameof(pixels)); + } if (!float.IsFinite(advanceX)) + { throw new ArgumentOutOfRangeException(nameof(advanceX)); + } this.width = width; this.height = height; this.bearingX = bearingX; @@ -350,22 +379,27 @@ ReadOnlySpan pixels /// Gets the bitmap width in pixels. /// public int width { get; } + /// /// Gets the bitmap height in pixels. /// public int height { get; } + /// /// Gets the horizontal bearing in pixels. /// public int bearingX { get; } + /// /// Gets the vertical bearing in pixels. /// public int bearingY { get; } + /// /// Gets the horizontal glyph advance. /// public float advanceX { get; } + /// /// Gets tightly packed row-major 8-bit coverage. /// diff --git a/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs b/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs index ec2ca543d..21c58cabc 100644 --- a/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs +++ b/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; - using Inno.Extensibility.Types; namespace Inno.UI.Assets; @@ -92,22 +91,28 @@ public UiDocumentAnalysis( IEnumerable? fonts = null ) { this.text = text; - this.diagnostics = new ReadOnlyCollection(diagnostics?.ToArray() - ?? throw new ArgumentNullException(nameof(diagnostics))); + this.diagnostics = new ReadOnlyCollection( + diagnostics?.ToArray() + ?? throw new ArgumentNullException(nameof(diagnostics)) + ); this.fonts = new ReadOnlyCollection(fonts?.ToArray() ?? []); } + /// /// Gets canonical source text, or null after failure. /// public string? text { get; } + /// /// Gets frozen diagnostics. /// public IReadOnlyList diagnostics { get; } + /// /// Gets font assets declared by the canonical document. /// public IReadOnlyList fonts { get; } + /// /// Gets whether the frontend accepted the source. /// @@ -123,6 +128,7 @@ public interface IUiDocumentFrontend /// Gets the open source-language identity. /// UiDocumentLanguageId languageId { get; } + /// /// Analyzes one immutable source snapshot. /// @@ -141,6 +147,7 @@ public interface IUiDocumentFrontend public sealed class UiDocumentFrontendCatalog { private readonly Dictionary m_frontends = []; + /// /// Captures a validated provider set. /// @@ -151,15 +158,22 @@ public UiDocumentFrontendCatalog(IEnumerable frontends) { ArgumentNullException.ThrowIfNull(frontends); foreach (IUiDocumentFrontend frontend in frontends) + { if (frontend is null || !frontend.languageId.isValid || !m_frontends.TryAdd(frontend.languageId, frontend)) + { throw new ArgumentException("UI document frontends require unique, assigned language IDs.", nameof(frontends)); + } + } languageIds = new ReadOnlyCollection([.. m_frontends.Keys]); } + /// /// Gets registered language identities. /// public IReadOnlyList languageIds { get; } + internal IEnumerable providers => m_frontends.Values; + /// /// Analyzes source using an explicit language. /// @@ -175,10 +189,9 @@ public UiDocumentFrontendCatalog(IEnumerable frontends) public UiDocumentAnalysis Analyze( UiDocumentLanguageId language, UiDocumentSourceFile source - ) - => m_frontends.TryGetValue(language, out IUiDocumentFrontend? frontend) - ? frontend.Analyze(source) ?? throw new InvalidOperationException($"UI language '{language}' returned no analysis.") - : throw new NotSupportedException($"UI document language '{language}' is unavailable."); + ) => m_frontends.TryGetValue(language, out IUiDocumentFrontend? frontend) + ? frontend.Analyze(source) ?? throw new InvalidOperationException($"UI language '{language}' returned no analysis.") + : throw new NotSupportedException($"UI document language '{language}' is unavailable."); } /// @@ -187,13 +200,16 @@ UiDocumentSourceFile source public sealed class UiDocumentFrontendRegistry : TypeRegistry { private readonly TypeCatalog m_types; + /// /// Registers with the owner type catalog. /// /// /// Catalog that outlives this registry. /// - public UiDocumentFrontendRegistry(TypeCatalog types) : base(types) => m_types = types; + public UiDocumentFrontendRegistry(TypeCatalog types) + : base(types) => m_types = types; + /// /// Analyzes source while preventing provider retirement. /// @@ -213,6 +229,7 @@ UiDocumentSourceFile source using IDisposable operation = m_types.AcquireOperation("Analyze UI document source"); return current.Analyze(language, source); } + /// /// Builds a validated result from the current immutable input snapshot. /// @@ -226,11 +243,14 @@ protected override UiDocumentFrontendCatalog Build(TypeCacheSnapshot types) { var providers = new List(); foreach (Type type in types.GetTypesImplementing() - .Select(reference => reference.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal)) + .Select(reference => reference.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { providers.Add(CreateExtension(type)); + } return new UiDocumentFrontendCatalog(providers); } + /// /// Releases the generation lease retained by an immutable registry snapshot. /// diff --git a/src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs b/src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs index 2320f665a..fe4e7aa11 100644 --- a/src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs +++ b/src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs @@ -13,6 +13,7 @@ public sealed class UiDocumentImportSettings : ISerializable /// Gets or sets the registered source-language identity. /// [SerializableProperty] public string languageId { get; set; } = string.Empty; + /// /// Gets or sets the exact runtime implementation identity. /// diff --git a/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs b/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs index 6d622bda5..cefd7f3be 100644 --- a/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs +++ b/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs @@ -4,9 +4,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; - -using Inno.Assets.Pipeline; using Inno.Assets; +using Inno.Assets.Pipeline; using Inno.Core.Serialization; using Inno.Text; @@ -52,7 +51,7 @@ protected override async ValueTask ImportAsync( CancellationToken cancellationToken ) { var settings = context.importSettings as UiDocumentImportSettings - ?? throw new InvalidOperationException("UI source requires its standard import settings."); + ?? throw new InvalidOperationException("UI source requires its standard import settings."); ArgumentException.ThrowIfNullOrWhiteSpace(settings.languageId); ArgumentException.ThrowIfNullOrWhiteSpace(settings.implementationId); await UiDocumentImportPipeline.ImportAsync( @@ -60,7 +59,8 @@ await UiDocumentImportPipeline.ImportAsync( output, new UiDocumentLanguageId(settings.languageId), settings.implementationId, - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); } } @@ -100,20 +100,37 @@ CancellationToken cancellationToken ArgumentException.ThrowIfNullOrWhiteSpace(implementationId); string text = context.ReadUtf8Text(); using var frontends = new UiDocumentFrontendRegistry(context.types); - UiDocumentAnalysis analysis = frontends.Analyze(language, - new(context.assetPath.ToString(), text, context.ReadSourceUtf8Text)); + UiDocumentAnalysis analysis = frontends.Analyze( + language, + new(context.assetPath.ToString(), text, context.ReadSourceUtf8Text) + ); if (!analysis.succeeded) - throw new InvalidDataException(string.Join("\n", analysis.diagnostics.Select(static diagnostic => - $"{diagnostic.line}:{diagnostic.column}: {diagnostic.code}: {diagnostic.message}"))); + { + throw new InvalidDataException( + string.Join( + "\n", + analysis.diagnostics.Select(static diagnostic => + $"{diagnostic.line}:{diagnostic.column}: {diagnostic.code}: {diagnostic.message}") + ) + ); + } var fonts = new List(analysis.fonts.Count); foreach (UiDocumentFontDeclaration declaration in analysis.fonts) { FontAsset font = context.ResolveDependency(AssetPath.Parse(declaration.assetPath)); if (font.isMissing || font.metadata is not { faceCount: > 0 }) + { throw new InvalidDataException($"UI font asset '{declaration.assetPath}' has no usable face."); + } context.DependsOnArtifact(font.identity.persistentId); - fonts.Add(new UiDocumentFontFace(font.identity.persistentId, - declaration.family, declaration.style, declaration.weight)); + fonts.Add( + new UiDocumentFontFace( + font.identity.persistentId, + declaration.family, + declaration.style, + declaration.weight + ) + ); } string sourceUri = $"innoasset://{context.assetPath.source.value}/{context.assetPath.localPath}"; var source = new UiDocumentSource(language, analysis.text!, sourceUri); @@ -121,6 +138,7 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", UiDocumentAsset.CreateRuntimePayload(implementationId, source, fonts), - cancellationToken).ConfigureAwait(false); + cancellationToken + ).ConfigureAwait(false); } } diff --git a/src/services/ui/Inno.UI.Runtime/UiRuntime.cs b/src/services/ui/Inno.UI.Runtime/UiRuntime.cs index 3057b230e..3a6f36516 100644 --- a/src/services/ui/Inno.UI.Runtime/UiRuntime.cs +++ b/src/services/ui/Inno.UI.Runtime/UiRuntime.cs @@ -3,7 +3,6 @@ using System.Globalization; using System.IO; using System.Linq; - using Inno.Assets; using Inno.Core.Mathematics; using Inno.Input; @@ -165,12 +164,17 @@ UiDocumentAsset document ArgumentNullException.ThrowIfNull(document); EnsureActive(); if (document.isMissing) + { throw new InvalidOperationException("The UI document asset is missing."); + } UiDocumentSource source = document.source - ?? throw new InvalidOperationException("The UI document has no imported runtime payload."); + ?? throw new InvalidOperationException("The UI document has no imported runtime payload."); if (!string.Equals(document.implementationId, m_backend.implementationId, StringComparison.Ordinal)) + { throw new InvalidOperationException( - $"UI document implementation '{document.implementationId}' cannot be loaded by selected backend '{m_backend.implementationId}'."); + $"UI document implementation '{document.implementationId}' cannot be loaded by selected backend '{m_backend.implementationId}'." + ); + } EnsureLanguageSupported(source.language); string text = source.text; var families = new Dictionary(StringComparer.Ordinal); @@ -182,14 +186,16 @@ UiDocumentAsset document if (!families.TryGetValue(face.family, out string? versionedFamily)) { versionedFamily = face.family + "__v" - + document.contentVersion.ToString("x", CultureInfo.InvariantCulture); + + document.contentVersion.ToString("x", CultureInfo.InvariantCulture); families.Add(face.family, versionedFamily); text = text.Replace(face.family, versionedFamily, StringComparison.Ordinal); } registrations.Add(RegisterDocumentFont(face, document.contentVersion, versionedFamily)); } - UiDocumentHandle handle = m_backend.LoadDocument(context, - new UiDocumentSource(source.language, text, source.sourceUri)); + UiDocumentHandle handle = m_backend.LoadDocument( + context, + new UiDocumentSource(source.language, text, source.sourceUri) + ); if (registrations.Count > 0) { var key = new DocumentKey(context, handle); @@ -259,7 +265,9 @@ UiDocumentHandle document m_backend.CloseDocument(context, document); var key = new DocumentKey(context, document); if (m_documentFonts.Remove(key, out FontRegistration[]? registrations)) + { ReleaseFonts(registrations); + } } /// @@ -433,15 +441,19 @@ Vector2 position public void Update(UiContextHandle context) { EnsureActive(); - m_backend.Update(context, new UiInputSnapshot( - m_input.mousePosition, - m_input.scrollDelta, - m_input.modifiers, - m_input.keysPressed, - m_input.keysReleased, - m_input.mouseButtonsPressed, - m_input.mouseButtonsReleased, - m_input.textInput)); + m_backend.Update( + context, + new UiInputSnapshot( + m_input.mousePosition, + m_input.scrollDelta, + m_input.modifiers, + m_input.keysPressed, + m_input.keysReleased, + m_input.mouseButtonsPressed, + m_input.mouseButtonsReleased, + m_input.textInput + ) + ); } /// @@ -497,7 +509,9 @@ public IReadOnlyList DrainEvents(UiContextHandle context) protected override void OnStop() { if (m_disposed) + { return; + } List failures = []; try { @@ -521,7 +535,9 @@ protected override void OnStop() } m_documentFonts.Clear(); if (failures.Count > 0) + { throw new AggregateException("UI runtime retirement failed.", failures); + } m_disposed = true; } @@ -530,21 +546,22 @@ protected override void OnStop() private void RegisterBackendFont( ArtifactLease artifact, FontRegistration registration - ) - => m_backend.RegisterFont(new UiFontRegistration( + ) => m_backend.RegisterFont( + new UiFontRegistration( artifact.ReadAllBytes(), registration.faceIndex, registration.family, registration.style, - registration.weight)); + registration.weight + ) + ); private FontRegistration RegisterDocumentFont( UiDocumentFontFace face, long documentVersion, string family ) { - var registration = new FontRegistration(face.assetId, documentVersion, 0, - family, face.style, face.weight); + var registration = new FontRegistration(face.assetId, documentVersion, 0, family, face.style, face.weight); if (m_fonts.TryGetValue(registration, out FontResidency? existing)) { RegisterBackendFont(existing.lease, registration); @@ -572,7 +589,9 @@ private void ReleaseFonts(IEnumerable registrations) { FontResidency residency = m_fonts[registration]; if (--residency.references > 0) + { continue; + } try { residency.lease.Dispose(); @@ -584,7 +603,9 @@ private void ReleaseFonts(IEnumerable registrations) } } if (failures is not null) + { throw new AggregateException("UI font artifact retirement is incomplete.", failures); + } } private sealed class FontResidency(ArtifactLease lease) @@ -601,8 +622,11 @@ UiDocumentHandle document private void EnsureLanguageSupported(UiDocumentLanguageId language) { if (!m_backend.capabilities.Supports(language)) + { throw new NotSupportedException( - $"UI document language '{language}' is not supported by selected backend '{m_backend.implementationId}'."); + $"UI document language '{language}' is not supported by selected backend '{m_backend.implementationId}'." + ); + } } private readonly record struct FontRegistration( diff --git a/src/services/ui/Inno.UI.Runtime/UiRuntimeFactory.cs b/src/services/ui/Inno.UI.Runtime/UiRuntimeFactory.cs index dfeda8cdf..d364565bf 100644 --- a/src/services/ui/Inno.UI.Runtime/UiRuntimeFactory.cs +++ b/src/services/ui/Inno.UI.Runtime/UiRuntimeFactory.cs @@ -1,5 +1,4 @@ using System; - using Inno.Runtime; using Inno.Runtime.Contracts; @@ -32,7 +31,8 @@ public UiRuntimeFactory(Func runtimeFactory) dependencies: [ new RuntimeSubsystemId("inno.runtime.input") - ]); + ] + ); /// /// Creates one session-owned UI runtime. @@ -47,6 +47,6 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { ArgumentNullException.ThrowIfNull(context); return m_runtimeFactory(context) - ?? throw new InvalidOperationException("The UI runtime factory returned null."); + ?? throw new InvalidOperationException("The UI runtime factory returned null."); } } diff --git a/src/services/ui/Inno.UI/IUiBackend.cs b/src/services/ui/Inno.UI/IUiBackend.cs index 0e452366d..526060d7e 100644 --- a/src/services/ui/Inno.UI/IUiBackend.cs +++ b/src/services/ui/Inno.UI/IUiBackend.cs @@ -13,10 +13,12 @@ public interface IUiBackend : IDisposable /// Gets the stable implementation identity used by imported document artifacts. /// string implementationId { get; } + /// /// Gets optional behavior and accepted document languages for this generation. /// UiBackendCapabilities capabilities { get; } + /// /// Creates one independent UI context. /// @@ -27,6 +29,7 @@ public interface IUiBackend : IDisposable /// A handle owned by the caller until destruction. /// UiContextHandle CreateContext(UiContextOptions options); + /// /// Destroys one UI context and all of its documents. /// @@ -34,6 +37,7 @@ public interface IUiBackend : IDisposable /// The context that owns the requested document or state. /// void DestroyContext(UiContextHandle context); + /// /// Changes one UI context's pixel dimensions and density. /// @@ -55,6 +59,7 @@ void SetViewport( int height, float density ); + /// /// Loads one explicitly tagged in-memory document. /// @@ -71,6 +76,7 @@ UiDocumentHandle LoadDocument( UiContextHandle context, UiDocumentSource source ); + /// /// Shows one document. /// @@ -84,6 +90,7 @@ void ShowDocument( UiContextHandle context, UiDocumentHandle document ); + /// /// Hides one document. /// @@ -97,6 +104,7 @@ void HideDocument( UiContextHandle context, UiDocumentHandle document ); + /// /// Closes one document. /// @@ -110,6 +118,7 @@ void CloseDocument( UiContextHandle context, UiDocumentHandle document ); + /// /// Replaces an element's children with plain Unicode text. /// @@ -135,6 +144,7 @@ bool SetText( string elementId, string text ); + /// /// Replaces an element's children with an explicitly tagged source-language fragment. /// @@ -160,6 +170,7 @@ bool SetContent( string elementId, UiDocumentFragment fragment ); + /// /// Sets one element attribute. /// @@ -189,6 +200,7 @@ bool SetAttribute( string name, string value ); + /// /// Activates or deactivates one element class. /// @@ -218,6 +230,7 @@ bool SetClass( string className, bool active ); + /// /// Registers an encoded font face in the document engine. /// @@ -225,6 +238,7 @@ bool active /// Font bytes and family metadata to register. /// void RegisterFont(UiFontRegistration registration); + /// /// Registers a named RGBA8 texture source. /// @@ -242,6 +256,7 @@ void RegisterTexture( string source, UiTextureData texture ); + /// /// Tests whether a visible document element receives pointer events at a pixel location. /// @@ -258,6 +273,7 @@ bool HasElementAtPoint( UiContextHandle context, Vector2 position ); + /// /// Processes input and advances document state. /// @@ -271,6 +287,7 @@ void Update( UiContextHandle context, UiInputSnapshot input ); + /// /// Builds an immutable frame of incremental resources and ordered draws. /// @@ -281,6 +298,7 @@ UiInputSnapshot input /// An immutable frame of ordered UI draws and resources. /// UiRenderFrame Render(UiContextHandle context); + /// /// Drains document events queued by the preceding updates. /// diff --git a/src/services/ui/Inno.UI/IUiService.cs b/src/services/ui/Inno.UI/IUiService.cs index f4b28decb..e9867096f 100644 --- a/src/services/ui/Inno.UI/IUiService.cs +++ b/src/services/ui/Inno.UI/IUiService.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using Inno.Core.Mathematics; - namespace Inno.UI; /// @@ -19,6 +18,7 @@ public interface IUiService /// A handle owned by the caller until destruction. /// UiContextHandle CreateContext(UiContextOptions options); + /// /// Destroys one UI context and all owned documents. /// @@ -26,6 +26,7 @@ public interface IUiService /// The context that owns the requested document or state. /// void DestroyContext(UiContextHandle context); + /// /// Changes one context's pixel dimensions and density. /// @@ -47,6 +48,7 @@ void SetViewport( int height, float density = 1f ); + /// /// Loads one explicitly tagged in-memory document. /// @@ -63,6 +65,7 @@ UiDocumentHandle LoadDocument( UiContextHandle context, UiDocumentSource source ); + /// /// Loads one imported document compatible with the selected backend. /// @@ -79,6 +82,7 @@ UiDocumentHandle LoadDocument( UiContextHandle context, UiDocumentAsset document ); + /// /// Shows one document. /// @@ -92,6 +96,7 @@ void ShowDocument( UiContextHandle context, UiDocumentHandle document ); + /// /// Hides one document. /// @@ -105,6 +110,7 @@ void HideDocument( UiContextHandle context, UiDocumentHandle document ); + /// /// Closes one document. /// @@ -118,6 +124,7 @@ void CloseDocument( UiContextHandle context, UiDocumentHandle document ); + /// /// Replaces an element's children with plain Unicode text. /// @@ -143,6 +150,7 @@ bool SetText( string elementId, string text ); + /// /// Replaces an element's children with an explicitly tagged source-language fragment. /// @@ -168,6 +176,7 @@ bool SetContent( string elementId, UiDocumentFragment fragment ); + /// /// Sets one element attribute. /// @@ -197,6 +206,7 @@ bool SetAttribute( string name, string value ); + /// /// Activates or deactivates one element class. /// @@ -226,6 +236,7 @@ bool SetClass( string className, bool active ); + /// /// Registers one named RGBA8 texture source. /// @@ -243,6 +254,7 @@ void RegisterTexture( string source, UiTextureData texture ); + /// /// Tests whether a visible document element receives pointer events at a pixel location. /// @@ -259,6 +271,7 @@ bool HasElementAtPoint( UiContextHandle context, Vector2 position ); + /// /// Processes current-frame input and advances one context. /// @@ -266,6 +279,7 @@ Vector2 position /// The context that owns the requested document or state. /// void Update(UiContextHandle context); + /// /// Advances one context with explicitly routed viewport-local input. /// @@ -279,6 +293,7 @@ void Update( UiContextHandle context, UiInputSnapshot input ); + /// /// Builds an immutable frame of incremental resources and ordered draws. /// @@ -289,6 +304,7 @@ UiInputSnapshot input /// An immutable frame of ordered UI draws and resources. /// UiRenderFrame Render(UiContextHandle context); + /// /// Drains document events queued by preceding updates. /// diff --git a/src/services/ui/Inno.UI/UI.cs b/src/services/ui/Inno.UI/UI.cs index 26b522ddc..a2f3dd8f4 100644 --- a/src/services/ui/Inno.UI/UI.cs +++ b/src/services/ui/Inno.UI/UI.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Execution; namespace Inno.UI; @@ -48,6 +47,7 @@ public static class UI /// The validated ui context handle that represents the completed operation. /// public static UiContextHandle CreateContext(UiContextOptions options) => UiExecutionContext.current.CreateContext(options); + /// /// Destroys one UI context and all owned documents. /// @@ -55,6 +55,7 @@ public static class UI /// The context that supplies state and services for this operation. /// public static void DestroyContext(UiContextHandle context) => UiExecutionContext.current.DestroyContext(context); + /// /// Changes one context's pixel dimensions and density. /// @@ -75,8 +76,8 @@ public static void SetViewport( int width, int height, float density = 1f - ) - => UiExecutionContext.current.SetViewport(context, width, height, density); + ) => UiExecutionContext.current.SetViewport(context, width, height, density); + /// /// Loads one explicitly tagged in-memory document. /// @@ -92,8 +93,8 @@ public static void SetViewport( public static UiDocumentHandle LoadDocument( UiContextHandle context, UiDocumentSource source - ) - => UiExecutionContext.current.LoadDocument(context, source); + ) => UiExecutionContext.current.LoadDocument(context, source); + /// /// Loads one imported document compatible with the selected backend. /// @@ -109,8 +110,8 @@ UiDocumentSource source public static UiDocumentHandle LoadDocument( UiContextHandle context, UiDocumentAsset document - ) - => UiExecutionContext.current.LoadDocument(context, document); + ) => UiExecutionContext.current.LoadDocument(context, document); + /// /// Shows one document. /// @@ -123,8 +124,8 @@ UiDocumentAsset document public static void ShowDocument( UiContextHandle context, UiDocumentHandle document - ) - => UiExecutionContext.current.ShowDocument(context, document); + ) => UiExecutionContext.current.ShowDocument(context, document); + /// /// Hides one document. /// @@ -137,8 +138,8 @@ UiDocumentHandle document public static void HideDocument( UiContextHandle context, UiDocumentHandle document - ) - => UiExecutionContext.current.HideDocument(context, document); + ) => UiExecutionContext.current.HideDocument(context, document); + /// /// Closes one document. /// @@ -151,8 +152,8 @@ UiDocumentHandle document public static void CloseDocument( UiContextHandle context, UiDocumentHandle document - ) - => UiExecutionContext.current.CloseDocument(context, document); + ) => UiExecutionContext.current.CloseDocument(context, document); + /// /// Replaces an element's children with plain Unicode text. /// @@ -176,8 +177,8 @@ public static bool SetText( UiDocumentHandle document, string elementId, string text - ) - => UiExecutionContext.current.SetText(context, document, elementId, text); + ) => UiExecutionContext.current.SetText(context, document, elementId, text); + /// /// Replaces an element's children with an explicitly tagged source-language fragment. /// @@ -201,8 +202,8 @@ public static bool SetContent( UiDocumentHandle document, string elementId, UiDocumentFragment fragment - ) - => UiExecutionContext.current.SetContent(context, document, elementId, fragment); + ) => UiExecutionContext.current.SetContent(context, document, elementId, fragment); + /// /// Sets one element attribute. /// @@ -230,8 +231,8 @@ public static bool SetAttribute( string elementId, string name, string value - ) - => UiExecutionContext.current.SetAttribute(context, document, elementId, name, value); + ) => UiExecutionContext.current.SetAttribute(context, document, elementId, name, value); + /// /// Activates or deactivates one element class. /// @@ -259,8 +260,8 @@ public static bool SetClass( string elementId, string className, bool active - ) - => UiExecutionContext.current.SetClass(context, document, elementId, className, active); + ) => UiExecutionContext.current.SetClass(context, document, elementId, className, active); + /// /// Registers one named RGBA8 texture source. /// @@ -277,8 +278,8 @@ public static void RegisterTexture( UiContextHandle context, string source, UiTextureData texture - ) - => UiExecutionContext.current.RegisterTexture(context, source, texture); + ) => UiExecutionContext.current.RegisterTexture(context, source, texture); + /// /// Processes current-frame input and advances one context. /// @@ -286,6 +287,7 @@ UiTextureData texture /// The context that supplies state and services for this operation. /// public static void Update(UiContextHandle context) => UiExecutionContext.current.Update(context); + /// /// Advances one context with explicitly routed viewport-local input. /// @@ -299,6 +301,7 @@ public static void Update( UiContextHandle context, UiInputSnapshot input ) => UiExecutionContext.current.Update(context, input); + /// /// Builds an immutable frame of incremental resources and ordered draws. /// @@ -309,6 +312,7 @@ UiInputSnapshot input /// The validated ui render frame that represents the completed operation. /// public static UiRenderFrame Render(UiContextHandle context) => UiExecutionContext.current.Render(context); + /// /// Drains document events queued by preceding updates. /// diff --git a/src/services/ui/Inno.UI/UiBackendCapabilities.cs b/src/services/ui/Inno.UI/UiBackendCapabilities.cs index 6205c01ae..7d8e4a425 100644 --- a/src/services/ui/Inno.UI/UiBackendCapabilities.cs +++ b/src/services/ui/Inno.UI/UiBackendCapabilities.cs @@ -28,7 +28,9 @@ bool supportsFontCollectionFaces ArgumentNullException.ThrowIfNull(documentLanguages); UiDocumentLanguageId[] languages = documentLanguages.Distinct().ToArray(); if (languages.Length == 0 || languages.Any(static language => !language.isValid)) + { throw new ArgumentException("A UI backend must declare at least one assigned document language.", nameof(documentLanguages)); + } m_documentLanguages = new ReadOnlyCollection(languages); this.supportsFontCollectionFaces = supportsFontCollectionFaces; } @@ -79,7 +81,7 @@ public sealed class UiCapabilityUnavailableException : NotSupportedException /// public UiCapabilityUnavailableException(UiBackendCapability capability) : base($"The selected UI backend does not support capability '{capability}'.") - => this.capability = capability; + => this.capability = capability; /// /// Gets the unavailable capability. diff --git a/src/services/ui/Inno.UI/UiDocumentAsset.cs b/src/services/ui/Inno.UI/UiDocumentAsset.cs index 1a1419449..c61e67b62 100644 --- a/src/services/ui/Inno.UI/UiDocumentAsset.cs +++ b/src/services/ui/Inno.UI/UiDocumentAsset.cs @@ -1,12 +1,11 @@ using System; -using System.IO; -using System.Text; using System.Collections.Generic; using System.Collections.ObjectModel; -using Inno.Text; - +using System.IO; +using System.Text; using Inno.Assets; using Inno.Extensibility.Types; +using Inno.Text; namespace Inno.UI; @@ -25,6 +24,7 @@ public sealed class UiDocumentAsset : AssetObject /// Gets the frozen source, or null before runtime content is loaded. /// public UiDocumentSource? source => m_source; + /// /// Gets font dependencies declared by this document. /// @@ -67,6 +67,7 @@ public static byte[] CreateRuntimePayload( writer.Write(source.text); writer.Write(fonts?.Count ?? 0); if (fonts is not null) + { foreach (UiDocumentFontFace face in fonts) { writer.Write(face.assetId.ToByteArray()); @@ -74,6 +75,7 @@ public static byte[] CreateRuntimePayload( writer.Write((int)face.style); writer.Write(face.weight); } + } } return stream.ToArray(); } @@ -101,20 +103,34 @@ ReadOnlyMemory currentPayload using var stream = new MemoryStream(currentPayload.ToArray(), writable: false); using var reader = new BinaryReader(stream, new UTF8Encoding(false, true), leaveOpen: false); if (reader.ReadUInt32() != C_PAYLOAD_MAGIC) + { throw new InvalidDataException("The UI document runtime payload has an invalid header."); + } string implementation = reader.ReadString(); string language = reader.ReadString(); string sourceUri = reader.ReadString(); string text = reader.ReadString(); int count = reader.ReadInt32(); if (count is < 0 or > 256) + { throw new InvalidDataException("The UI document declares an invalid number of font faces."); + } var fonts = new List(count); for (int index = 0; index < count; index++) - fonts.Add(new UiDocumentFontFace(new Guid(reader.ReadBytes(16)), reader.ReadString(), - (TextFontStyle)reader.ReadInt32(), reader.ReadInt32())); + { + fonts.Add( + new UiDocumentFontFace( + new Guid(reader.ReadBytes(16)), + reader.ReadString(), + (TextFontStyle)reader.ReadInt32(), + reader.ReadInt32() + ) + ); + } if (stream.Position != stream.Length) + { throw new InvalidDataException("The UI document runtime payload contains trailing data."); + } ArgumentException.ThrowIfNullOrWhiteSpace(implementation); m_implementationId = implementation; m_source = new UiDocumentSource(new UiDocumentLanguageId(language), text, sourceUri); diff --git a/src/services/ui/Inno.UI/UiDocumentFontFace.cs b/src/services/ui/Inno.UI/UiDocumentFontFace.cs index 10a0462d2..facaefb92 100644 --- a/src/services/ui/Inno.UI/UiDocumentFontFace.cs +++ b/src/services/ui/Inno.UI/UiDocumentFontFace.cs @@ -30,10 +30,14 @@ public UiDocumentFontFace( int weight ) { if (assetId == Guid.Empty) + { throw new ArgumentException("A font asset ID is required.", nameof(assetId)); + } ArgumentException.ThrowIfNullOrWhiteSpace(family); if (weight is < 100 or > 1000) + { throw new ArgumentOutOfRangeException(nameof(weight)); + } this.assetId = assetId; this.family = family; this.style = style; @@ -44,14 +48,17 @@ int weight /// Gets the imported font asset identity. /// public Guid assetId { get; } + /// /// Gets the family referenced by the document. /// public string family { get; } + /// /// Gets the declared style. /// public TextFontStyle style { get; } + /// /// Gets the declared weight. /// diff --git a/src/services/ui/Inno.UI/UiFontRegistration.cs b/src/services/ui/Inno.UI/UiFontRegistration.cs index 9aea57c91..0b9eed38d 100644 --- a/src/services/ui/Inno.UI/UiFontRegistration.cs +++ b/src/services/ui/Inno.UI/UiFontRegistration.cs @@ -1,5 +1,4 @@ using System; - using Inno.Text; namespace Inno.UI; @@ -35,11 +34,15 @@ public UiFontRegistration( int weight ) { if (data.IsEmpty) + { throw new ArgumentException("Font data cannot be empty.", nameof(data)); + } ArgumentOutOfRangeException.ThrowIfNegative(faceIndex); ArgumentException.ThrowIfNullOrWhiteSpace(family); if (weight is < 100 or > 1000) + { throw new ArgumentOutOfRangeException(nameof(weight)); + } this.data = data; this.faceIndex = faceIndex; this.family = family.Trim(); @@ -51,18 +54,22 @@ int weight /// Gets encoded font bytes valid for the synchronous backend call. /// public ReadOnlyMemory data { get; } + /// /// Gets the zero-based collection face index. /// public int faceIndex { get; } + /// /// Gets the logical family. /// public string family { get; } + /// /// Gets the logical style. /// public TextFontStyle style { get; } + /// /// Gets the logical weight. /// diff --git a/src/services/ui/Inno.UI/UiIdentifiers.cs b/src/services/ui/Inno.UI/UiIdentifiers.cs index 1ce02c63a..2e3931fa7 100644 --- a/src/services/ui/Inno.UI/UiIdentifiers.cs +++ b/src/services/ui/Inno.UI/UiIdentifiers.cs @@ -17,8 +17,12 @@ public UiDocumentLanguageId(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); foreach (char character in value) + { if (char.IsWhiteSpace(character)) + { throw new ArgumentException("A UI document language identifier cannot contain whitespace.", nameof(value)); + } + } this.value = value; } diff --git a/src/services/ui/Inno.UI/UiRendering.cs b/src/services/ui/Inno.UI/UiRendering.cs index ab68ec1f6..a4d4b0c8f 100644 --- a/src/services/ui/Inno.UI/UiRendering.cs +++ b/src/services/ui/Inno.UI/UiRendering.cs @@ -76,14 +76,17 @@ uint[] indices /// Gets the generation-scoped mesh handle. /// public UiMeshHandle mesh { get; } + /// /// Gets the monotonically increasing mesh content revision. /// public ulong revision { get; } + /// /// Gets immutable local-space vertices. /// public IReadOnlyList vertices => m_vertices; + /// /// Gets immutable triangle indices. /// @@ -115,18 +118,22 @@ byte[] pixels /// Gets the generation-scoped texture handle. /// public UiTextureHandle texture { get; } + /// /// Gets the monotonically increasing content revision. /// public ulong revision { get; } + /// /// Gets the texture width. /// public int width { get; } + /// /// Gets the texture height. /// public int height { get; } + /// /// Gets immutable tightly packed premultiplied RGBA8 pixels. /// @@ -204,27 +211,36 @@ UiTextureHandle[] textures ArgumentNullException.ThrowIfNull(meshes); ArgumentNullException.ThrowIfNull(textures); if (Array.Exists(meshes, static value => !value.isValid)) + { throw new ArgumentException("Retirement meshes must be assigned.", nameof(meshes)); + } if (Array.Exists(textures, static value => !value.isValid)) + { throw new ArgumentException("Retirement textures must be assigned.", nameof(textures)); + } return new([], (UiMeshHandle[])meshes.Clone(), [], (UiTextureHandle[])textures.Clone(), []); } + /// /// Gets created or replaced mesh generations. /// public IReadOnlyList meshUpdates => m_meshUpdates; + /// /// Gets mesh generations that must be retired. /// public IReadOnlyList releasedMeshes => m_releasedMeshes; + /// /// Gets created or replaced texture generations. /// public IReadOnlyList textureUpdates => m_textureUpdates; + /// /// Gets texture generations that must be retired. /// public IReadOnlyList releasedTextures => m_releasedTextures; + /// /// Gets ordered draws referencing published resources. /// @@ -269,16 +285,26 @@ uint[] indices ) { EnsureMutable(); if (!mesh.isValid) + { throw new ArgumentException("A mesh update requires an assigned handle.", nameof(mesh)); + } if (revision == 0) + { throw new ArgumentOutOfRangeException(nameof(revision)); + } ArgumentNullException.ThrowIfNull(vertices); ArgumentNullException.ThrowIfNull(indices); if (vertices.Length == 0 || indices.Length == 0) + { throw new ArgumentException("A mesh update requires nonempty geometry."); + } foreach (uint index in indices) + { if (index >= vertices.Length) + { throw new ArgumentException("A mesh index references a vertex outside the update.", nameof(indices)); + } + } m_meshUpdates.Add(new(mesh, revision, vertices, indices)); } @@ -292,7 +318,9 @@ public void AddReleasedMesh(UiMeshHandle mesh) { EnsureMutable(); if (!mesh.isValid) + { throw new ArgumentException("A released mesh requires an assigned handle.", nameof(mesh)); + } m_releasedMeshes.Add(mesh); } @@ -323,14 +351,20 @@ byte[] pixels ) { EnsureMutable(); if (!texture.isValid) + { throw new ArgumentException("A texture update requires an assigned handle.", nameof(texture)); + } if (revision == 0) + { throw new ArgumentOutOfRangeException(nameof(revision)); + } ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); ArgumentNullException.ThrowIfNull(pixels); if (pixels.Length != checked(width * height * 4)) + { throw new ArgumentException("Texture pixels must be tightly packed RGBA8.", nameof(pixels)); + } m_textureUpdates.Add(new(texture, revision, width, height, pixels)); } @@ -344,7 +378,9 @@ public void AddReleasedTexture(UiTextureHandle texture) { EnsureMutable(); if (!texture.isValid) + { throw new ArgumentException("A released texture requires an assigned handle.", nameof(texture)); + } m_releasedTextures.Add(texture); } @@ -358,7 +394,9 @@ public void AddCommand(UiDrawCommand command) { EnsureMutable(); if (!command.mesh.isValid) + { throw new ArgumentException("A draw command requires an assigned mesh.", nameof(command)); + } m_commands.Add(command); } @@ -377,12 +415,15 @@ public UiRenderFrame Build() m_releasedMeshes.ToArray(), m_textureUpdates.ToArray(), m_releasedTextures.ToArray(), - m_commands.ToArray()); + m_commands.ToArray() + ); } private void EnsureMutable() { if (m_built) + { throw new InvalidOperationException("A UI render-frame builder can only build one frame."); + } } } diff --git a/src/services/ui/Inno.UI/UiTypes.cs b/src/services/ui/Inno.UI/UiTypes.cs index fa66e9ac4..f2f852607 100644 --- a/src/services/ui/Inno.UI/UiTypes.cs +++ b/src/services/ui/Inno.UI/UiTypes.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Inno.Core.Input; using Inno.Core.Mathematics; @@ -36,7 +35,9 @@ public UiContextOptions( ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); if (!float.IsFinite(density) || density <= 0f) + { throw new ArgumentOutOfRangeException(nameof(density)); + } this.name = name.Trim(); this.width = width; this.height = height; @@ -47,14 +48,17 @@ public UiContextOptions( /// Gets the diagnostic context name. /// public string name { get; } + /// /// Gets the initial width in pixels. /// public int width { get; } + /// /// Gets the initial height in pixels. /// public int height { get; } + /// /// Gets the density-independent pixel ratio. /// @@ -84,7 +88,9 @@ public UiDocumentSource( string sourceUri = "memory://ui-document" ) { if (!language.isValid) + { throw new ArgumentException("A document source requires an assigned language.", nameof(language)); + } ArgumentException.ThrowIfNullOrWhiteSpace(text); ArgumentException.ThrowIfNullOrWhiteSpace(sourceUri); this.language = language; @@ -96,10 +102,12 @@ public UiDocumentSource( /// Gets the explicitly selected source language. /// public UiDocumentLanguageId language { get; } + /// /// Gets the complete immutable source text. /// public string text { get; } + /// /// Gets the virtual source address. /// @@ -125,7 +133,9 @@ public UiDocumentFragment( string text ) { if (!language.isValid) + { throw new ArgumentException("A document fragment requires an assigned language.", nameof(language)); + } ArgumentNullException.ThrowIfNull(text); this.language = language; this.text = text; @@ -135,6 +145,7 @@ string text /// Gets the explicitly selected fragment language. /// public UiDocumentLanguageId language { get; } + /// /// Gets the complete fragment text. /// @@ -168,7 +179,9 @@ ReadOnlySpan pixels ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); if (pixels.Length != checked(width * height * 4)) + { throw new ArgumentException("UI texture pixels must be tightly packed RGBA8.", nameof(pixels)); + } this.width = width; this.height = height; m_pixels = pixels.ToArray(); @@ -178,10 +191,12 @@ ReadOnlySpan pixels /// Gets the texture width. /// public int width { get; } + /// /// Gets the texture height. /// public int height { get; } + /// /// Gets the immutable RGBA8 pixels. /// @@ -322,30 +337,37 @@ IReadOnlyList textInput /// Gets the pointer position. /// public Vector2 mousePosition { get; } + /// /// Gets pointer wheel movement. /// public Vector2 scrollDelta { get; } + /// /// Gets active keyboard modifiers. /// public KeyModifier modifiers { get; } + /// /// Gets physical keys pressed this frame. /// public IReadOnlyCollection keysPressed { get; } + /// /// Gets physical keys released this frame. /// public IReadOnlyCollection keysReleased { get; } + /// /// Gets pointer buttons pressed this frame. /// public IReadOnlyCollection buttonsPressed { get; } + /// /// Gets pointer buttons released this frame. /// public IReadOnlyCollection buttonsReleased { get; } + /// /// Gets ordered Unicode text commits. /// diff --git a/tests/animation/Inno.Animation.Tests/AnimationBindingTests.cs b/tests/animation/Inno.Animation.Tests/AnimationBindingTests.cs index 7b025a08f..e680847d5 100644 --- a/tests/animation/Inno.Animation.Tests/AnimationBindingTests.cs +++ b/tests/animation/Inno.Animation.Tests/AnimationBindingTests.cs @@ -1,14 +1,14 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Animation.Runtime; using Inno.Core.Diagnostics; using Inno.Core.Identity; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Animation.Tests; @@ -20,7 +20,9 @@ public void ProviderIsDiscoveredAndMissingIssuesRecoverOnTheNextBatch() string cache = Path.Combine(Path.GetTempPath(), "InnoAnimationBindings", Guid.NewGuid().ToString("N")); try { - using var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(AnimationBindingTests).Assembly)}); + using var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(AnimationBindingTests).Assembly)} + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); var reporter = new Reporter(); using var bindings = new AnimationBindingRuntime(types, reporter); @@ -28,18 +30,28 @@ public void ProviderIsDiscoveredAndMissingIssuesRecoverOnTheNextBatch() var destination = new Destination(); owner.Register(destination); var target = new AnimationTarget(destination.identity); - bindings.Apply([new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 3f))]); + bindings.Apply( + [new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 3f))] + ); Assert.Equal(3f, destination.value); Assert.Empty(reporter.issues); - bindings.Apply([new AnimationSample(target, new AnimationBindingId("test.missing"), new AnimationValue(AnimationValueKind.Scalar, 3f))]); + bindings.Apply( + [new AnimationSample(target, new AnimationBindingId("test.missing"), new AnimationValue(AnimationValueKind.Scalar, 3f))] + ); Assert.Equal("animation.binding.unavailable", Assert.Single(reporter.issues).code); - bindings.Apply([new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 4f))]); + bindings.Apply( + [new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 4f))] + ); Assert.Empty(reporter.issues); types.Rebuild(); - bindings.Apply([new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 5f))]); + bindings.Apply( + [new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 5f))] + ); Assert.Equal(5f, destination.value); owner.Unregister(destination); - bindings.Apply([new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 6f))]); + bindings.Apply( + [new AnimationSample(target, new AnimationBindingId("test.scalar"), new AnimationValue(AnimationValueKind.Scalar, 6f))] + ); Assert.Single(reporter.issues); bindings.Apply([new AnimationSample(AnimationTarget.samplingOnly, new AnimationBindingId("test.missing"), default)]); Assert.Empty(reporter.issues); @@ -47,7 +59,9 @@ public void ProviderIsDiscoveredAndMissingIssuesRecoverOnTheNextBatch() finally { if (Directory.Exists(cache)) + { Directory.Delete(cache, true); + } } } @@ -59,11 +73,15 @@ public sealed class Destination : IdentityObject [AnimationBindingProvider("test.animation.scalar", "test.scalar", AnimationValueKind.Scalar)] public sealed class ScalarProvider : AnimationBindingProvider { - public override bool TryApply(AnimationTarget target, AnimationValue value) - { + public override bool TryApply( + AnimationTarget target, + AnimationValue value + ) { Destination? destination = target.Resolve(); if (destination is null) + { return false; + } destination.value = value.x; return true; } @@ -72,8 +90,15 @@ public override bool TryApply(AnimationTarget target, AnimationValue value) private sealed class Reporter : IDiagnosticReporter { internal Diagnostic[] issues = []; + public void Publish(Diagnostic diagnostic) => issues = [diagnostic]; - public void Resolve(string code, string? semanticId = null, Guid? objectId = null) => issues = []; + + public void Resolve( + string code, + string? semanticId = null, + Guid? objectId = null + ) => issues = []; + public void Replace(IEnumerable diagnostics) => issues = diagnostics.ToArray(); } } diff --git a/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs b/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs index c4e3431ff..e570e9ff2 100644 --- a/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs +++ b/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs @@ -1,11 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; - +using Xunit; using Inno.Animation.Runtime; using Inno.Core.Events; using Inno.Core.Identity; -using Xunit; namespace Inno.Animation.Tests; @@ -114,9 +113,7 @@ public void ClipValidationRejectsDuplicateBindingsAndInvalidTimes() Assert.Throws(clip.Validate); clip = CreateClip(); - clip.tracks[0].keyframes[1] = new AnimationKeyframe(2f, new AnimationValue( - AnimationValueKind.Scalar, - 1f)); + clip.tracks[0].keyframes[1] = new AnimationKeyframe(2f, new AnimationValue(AnimationValueKind.Scalar, 1f)); Assert.Throws(clip.Validate); } @@ -150,41 +147,43 @@ private sealed class Destination : IdentityObject; private static AnimationClipAsset CreateClip() => new() - { - duration = 1f, - tracks = - [ - new AnimationTrack( - "visual.opacity", - AnimationInterpolation.Linear, - [ - new AnimationKeyframe(0f, new AnimationValue(AnimationValueKind.Scalar, 0f)), - new AnimationKeyframe(1f, new AnimationValue(AnimationValueKind.Scalar, 1f)) - ]) - ], - events = - [ - new AnimationEventMarker - { - time = 0.5f, - eventId = "midpoint", - payload = [1, 2, 3] - } - ] - }; + { + duration = 1f, + tracks = + [ + new AnimationTrack( + "visual.opacity", + AnimationInterpolation.Linear, + [ + new AnimationKeyframe(0f, new AnimationValue(AnimationValueKind.Scalar, 0f)), + new AnimationKeyframe(1f, new AnimationValue(AnimationValueKind.Scalar, 1f)) + ] + ) + ], + events = + [ + new AnimationEventMarker + { + time = 0.5f, + eventId = "midpoint", + payload = [1, 2, 3] + } + ] + }; private static AnimationClipAsset CreateConstantClip(float value) => new() - { - duration = 1f, - tracks = - [ - new AnimationTrack( - "visual.opacity", - AnimationInterpolation.Step, - [new AnimationKeyframe(0f, new AnimationValue(AnimationValueKind.Scalar, value))]) - ] - }; + { + duration = 1f, + tracks = + [ + new AnimationTrack( + "visual.opacity", + AnimationInterpolation.Step, + [new AnimationKeyframe(0f, new AnimationValue(AnimationValueKind.Scalar, value))] + ) + ] + }; private sealed class RecordingSink : IAnimationBindingSink { diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs index 9564b74e0..5e4a01b5e 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs @@ -3,12 +3,10 @@ using System.IO; using System.Linq; using System.Threading; - +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; -using Xunit; - namespace Inno.Assets.Pipeline.Tests; public sealed class AssetFileSystemChangeTests @@ -33,9 +31,10 @@ public void Watcher_CoalescesCreateChangeAndDeleteThroughPublicCoordinator() observed = observed.Concat(fileSystem.WaitForIdle()).ToArray(); Assert.False(fileSystem.TryGetEntry(AssetPath.Project("Flow/item.txt"), out _)); - Assert.Contains(observed, static change => - change.relativePath == "Flow/item.txt" && - change.changeType.HasFlag(WatcherChangeTypes.Deleted)); + Assert.Contains(observed, static change => ( + change.relativePath == "Flow/item.txt" + && change.changeType.HasFlag(WatcherChangeTypes.Deleted) + )); } finally { @@ -56,8 +55,9 @@ public void Watcher_RenamePreservesOldAndNewRelativePaths() System.IO.File.Move(oldPath, newPath); IReadOnlyList observed = fileSystem.WaitForIdle(); - AssetChangedEvent renamed = Assert.Single(observed.Where(static change => - change.changeType.HasFlag(WatcherChangeTypes.Renamed))); + AssetChangedEvent renamed = Assert.Single( + observed.Where(static change => change.changeType.HasFlag(WatcherChangeTypes.Renamed)) + ); Assert.Equal("old.txt", renamed.oldRelativePath); Assert.Equal("new.txt", renamed.relativePath); Assert.False(fileSystem.Exists(AssetPath.Project("old.txt"))); @@ -102,6 +102,8 @@ private static string CreateRoot() private static void DeleteRoot(string root) { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs index a33cf931f..775aa37d6 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs @@ -3,12 +3,10 @@ using System.IO; using System.Linq; using System.Threading; - +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; -using Xunit; - namespace Inno.Assets.Pipeline.Tests; public sealed class AssetFileSystemTests @@ -181,8 +179,7 @@ public void Entries_ExposeLastExtensionDisplayNameAndFilterDatabaseNoise() System.IO.File.WriteAllText(Path.Combine(root, ".DS_Store"), "noise"); using var fileSystem = new AssetFileSystem(root, autoStart: false); - AssetFileEntry entry = Assert.Single( - fileSystem.GetEntries(includeDirectories: false)); + AssetFileEntry entry = Assert.Single(fileSystem.GetEntries(includeDirectories: false)); Assert.Equal("Tool.editor.cs", entry.name); Assert.Equal("Tool.editor", entry.nameWithoutExtension); @@ -203,7 +200,8 @@ public void Refresh_TreatsProjectTildeDirectoriesAsOrdinaryWritableContent() Directory.CreateDirectory(Path.Combine(root, "~Starter", "Scenes")); System.IO.File.WriteAllText( Path.Combine(root, "~Starter", "Scenes", "Game.cs"), - "public sealed class Game { }"); + "public sealed class Game { }" + ); System.IO.File.WriteAllText(Path.Combine(root, "~Standalone.cs"), "sample-like file"); using var fileSystem = new AssetFileSystem(root, autoStart: false); @@ -211,14 +209,12 @@ public void Refresh_TreatsProjectTildeDirectoriesAsOrdinaryWritableContent() Assert.True(fileSystem.TryGetEntry(AssetPath.Project("~Starter"), out AssetFileEntry tildeRoot)); Assert.False(tildeRoot.isSample); Assert.False(tildeRoot.isSampleContent); - Assert.True(fileSystem.TryGetEntry( - AssetPath.Project("~Starter/Scenes/Game.cs"), - out AssetFileEntry tildeContent)); + Assert.True( + fileSystem.TryGetEntry(AssetPath.Project("~Starter/Scenes/Game.cs"), out AssetFileEntry tildeContent) + ); Assert.False(tildeContent.isSample); Assert.False(tildeContent.isSampleContent); - Assert.True(fileSystem.TryGetEntry( - AssetPath.Project("~Standalone.cs"), - out AssetFileEntry ordinaryFile)); + Assert.True(fileSystem.TryGetEntry(AssetPath.Project("~Standalone.cs"), out AssetFileEntry ordinaryFile)); Assert.False(ordinaryFile.isSample); Assert.False(ordinaryFile.isSampleContent); } @@ -246,7 +242,8 @@ public void MultipleSourcesKeepCanonicalPathsNamesAndReadOnlyStateIsolated() new AssetSourceMount(AssetSourceId.project, project, isReadOnly: false), new AssetSourceMount(pluginId, plugin, isReadOnly: true) ], - autoStart: false); + autoStart: false + ); Assert.True(fileSystem.TryGetEntry(AssetPath.Project("same.txt"), out AssetFileEntry projectEntry)); Assert.True(fileSystem.TryGetEntry(new AssetPath(pluginId, "same.txt"), out AssetFileEntry pluginEntry)); @@ -262,13 +259,16 @@ public void MultipleSourcesKeepCanonicalPathsNamesAndReadOnlyStateIsolated() Assert.Equal(pluginId, pluginEntry.source); Assert.Contains( fileSystem.GetChildren(AssetPath.Project(string.Empty)), - entry => entry.source == AssetSourceId.project); + entry => entry.source == AssetSourceId.project + ); Assert.Contains( fileSystem.GetChildren(AssetPath.Project(string.Empty)), - entry => entry.assetPath == new AssetPath(pluginId, string.Empty)); + entry => entry.assetPath == new AssetPath(pluginId, string.Empty) + ); Assert.Contains( fileSystem.GetChildren(new AssetPath(pluginId, string.Empty)), - entry => entry.assetPath == new AssetPath(pluginId, "same.txt")); + entry => entry.assetPath == new AssetPath(pluginId, "same.txt") + ); } finally { @@ -313,6 +313,8 @@ private static string CreateRoot() private static void DeleteRoot(string root) { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs index 8c39415f8..ceb83ffb8 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs @@ -1,7 +1,3 @@ -using Inno.Content.Testing; -using Inno.Content; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; @@ -10,26 +6,31 @@ using System.Text; using System.Threading; using System.Threading.Tasks; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; +using Inno.Content; +using Inno.Content.Testing; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; using Inno.References; -using Xunit; - namespace Inno.Assets.Pipeline.Tests; public sealed class AssetLoaderTests : IDisposable { - private readonly string m_moduleArtifacts = Path.Combine(Path.GetTempPath(), - "AssetImporterModules-" + Guid.NewGuid().ToString("N")); + private readonly string m_moduleArtifacts = Path.Combine( + Path.GetTempPath(), + "AssetImporterModules-" + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; @@ -50,7 +51,9 @@ public AssetLoaderTests() m_identityScope = m_identities.EnterScope(); m_diagnosticScope = m_diagnostics.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetLoaderTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetLoaderTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); SlowAssetImporter.Reset(); @@ -68,7 +71,9 @@ public void Dispose() m_identityScope.Dispose(); m_modules.generations.Wait(); if (Directory.Exists(m_moduleArtifacts)) + { Directory.Delete(m_moduleArtifacts, recursive: true); + } } [Fact] @@ -85,9 +90,18 @@ public void ReadOnlyImportFailureDoesNotRewriteMetadataOrThrowAgainWhileRecordin }); System.IO.File.WriteAllBytes(package.SourcePath("README.md.imeta"), metadata); var source = new AssetSourceId("tests.readonly"); - using var loader = new AssetLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs, - [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false), - new AssetSourceMount(source, package.assetRoot, true)], workspace.libraryRoot); + using var loader = new AssetLoader( + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + [ + new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false), + new AssetSourceMount(source, package.assetRoot, true) + ], + workspace.libraryRoot + ); Assert.False(loader.Import(new AssetPath(source, "README.md"))); Assert.Equal(metadata, System.IO.File.ReadAllBytes(package.SourcePath("README.md.imeta"))); @@ -109,8 +123,15 @@ public void FailedRuntimeDependencyRecoversAfterPublicationOrLoaderRestart(bool AssetLoader? loader = null; try { - loader = new AssetLoader(m_types, m_serialization, m_identities, m_diagnostics, - m_logs, workspace.assetRoot, workspace.libraryRoot); + loader = new AssetLoader( + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + workspace.assetRoot, + workspace.libraryRoot + ); loader.Rescan(); AssetPath parent = AssetPath.Project("parent.depgraph"); Assert.True(loader.TryGetInfo(parent, out AssetInfo? failed)); @@ -127,8 +148,15 @@ public void FailedRuntimeDependencyRecoversAfterPublicationOrLoaderRestart(bool } DeferredAssetImporter.isAvailable = true; m_types.Rebuild(); - loader ??= new AssetLoader(m_types, m_serialization, m_identities, m_diagnostics, - m_logs, workspace.assetRoot, workspace.libraryRoot); + loader ??= new AssetLoader( + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + workspace.assetRoot, + workspace.libraryRoot + ); loader.Rescan(); Assert.True(loader.TryGetInfo(parent, out AssetInfo? recovered)); Assert.Equal(AssetImportStatus.Imported, recovered!.status); @@ -152,36 +180,61 @@ public void ExtensionDiscoveryDefersOnlyMissingExtensionsAndRetriesOnceWhenCompl workspace.WriteText("surface.extensionasset", "authored"); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, deferUnavailableExtensions = true }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions + { + assetRoot = workspace.assetRoot, + libraryRoot = workspace.libraryRoot, + deferUnavailableExtensions = true + } + ); AssetPath path = AssetPath.Project("surface.extensionasset"); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? pending)); Assert.Equal(AssetImportStatus.Pending, pending!.status); Assert.Equal(DiagnosticSeverity.Info, Assert.Single(Assert.Single(sink.reports.Values).diagnostics).severity); byte[] sidecar = System.IO.File.ReadAllBytes(workspace.SourcePath("surface.extensionasset.imeta")); int attempts = ExtensionDependentImporter.attempts; - for (int i = 0; i < 5; i++) pipeline.Rescan(); + for (int i = 0; i < 5; i++) + { + pipeline.Rescan(); + } Assert.Equal(attempts, ExtensionDependentImporter.attempts); - Assert.Throws(() => pipeline.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "PendingExport"))); + Assert.Throws( + () => pipeline.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "PendingExport")) + ); ExtensionDependentImporter.available = available; pipeline.CompleteExtensionDiscovery(); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? completed)); Assert.Equal(available ? AssetImportStatus.Imported : AssetImportStatus.Failed, completed!.status); if (available) + { Assert.Empty(sink.reports); + } else + { Assert.Equal(DiagnosticSeverity.Error, Assert.Single(Assert.Single(sink.reports.Values).diagnostics).severity); + } Assert.Equal(pending.persistentId, completed.persistentId); Assert.Equal(sidecar, System.IO.File.ReadAllBytes(workspace.SourcePath("surface.extensionasset.imeta"))); Assert.Equal("authored", System.IO.File.ReadAllText(workspace.SourcePath("surface.extensionasset"))); attempts = ExtensionDependentImporter.attempts; - for (int i = 0; i < 5; i++) pipeline.Rescan(); + for (int i = 0; i < 5; i++) + { + pipeline.Rescan(); + } Assert.Equal(attempts, ExtensionDependentImporter.attempts); if (!available) { - Assert.Throws(() => pipeline.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "MissingExport"))); + Assert.Throws( + () => pipeline.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "MissingExport")) + ); ExtensionDependentImporter.available = true; Assert.True(pipeline.Import(path)); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? restored)); @@ -199,18 +252,27 @@ public void ReadOnlyExtensionWaitPreservesSidecarAndBecomesStrictAfterDiscovery( package.WriteText("surface.extensionasset", "authored"); byte[] metadata = m_serialization.Serialize(new MountedSourceMetadata { - persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.File, + persistentId = Guid.NewGuid(), + sourceKind = (int)AssetSourceKind.File, importerId = "tests.extension-dependent" }); System.IO.File.WriteAllBytes(package.SourcePath("surface.extensionasset.imeta"), metadata); var source = new AssetSourceId("tests.readonly-extension"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { - assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, + assetRoot = workspace.assetRoot, + libraryRoot = workspace.libraryRoot, deferUnavailableExtensions = true, sourceMounts = [new(AssetSourceId.project, workspace.assetRoot, false), new(source, package.assetRoot, true)] - }); + } + ); var path = new AssetPath(source, "surface.extensionasset"); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? pending)); Assert.Equal(AssetImportStatus.Pending, pending!.status); @@ -230,9 +292,20 @@ public void DiscoveryDoesNotDeferMalformedContentAndCandidateActivationDoesNotHi { using TestWorkspace workspace = new(); workspace.WriteText("bad.mutableasset", "!invalid!"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, deferUnavailableExtensions = true }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions + { + assetRoot = workspace.assetRoot, + libraryRoot = workspace.libraryRoot, + deferUnavailableExtensions = true + } + ); Assert.True(pipeline.TryGetInfo(AssetPath.Project("bad.mutableasset"), out AssetInfo? bad)); Assert.Equal(AssetImportStatus.Failed, bad!.status); workspace.WriteText("surface.extensionasset", "authored"); @@ -259,9 +332,20 @@ public void MissingExtensionPropagatesToImportDependentsWithoutHydratingEmptyArt { using TestWorkspace workspace = new(); workspace.WriteText("surface.extensionasset", "authored"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, deferUnavailableExtensions = true }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions + { + assetRoot = workspace.assetRoot, + libraryRoot = workspace.libraryRoot, + deferUnavailableExtensions = true + } + ); Assert.True(pipeline.TryGetInfo(AssetPath.Project("surface.extensionasset"), out AssetInfo? root)); workspace.WriteText("material.extensiondependent", reference ? root!.persistentId.ToString() : "surface.extensionasset"); pipeline.Rescan(); @@ -286,9 +370,15 @@ public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingL { using TestWorkspace workspace = new(); workspace.WriteText("value.hookasset", "previous"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); HookAsset previous = pipeline.Load(AssetPath.Project("value.hookasset")); byte[] previousMeta = System.IO.File.ReadAllBytes(workspace.SourcePath("value.hookasset.imeta")); var observer = new CatalogObserver(); @@ -310,7 +400,9 @@ public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingL Assert.Equal("previous", Encoding.UTF8.GetString(previous.runtimePayload.Span)); Assert.False(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); if (reject) + { throw new InvalidOperationException("Expected later participant rejection."); + } }; if (reject) { @@ -347,9 +439,15 @@ public void AssemblyCatalogJoinsAnExistingSourceCandidateWithoutTakingItsPublica { using TestWorkspace workspace = new(); workspace.WriteText("value.txt", "previous"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); TextAsset previous = pipeline.Load(AssetPath.Project("value.txt")); var observer = new CatalogObserver(); using IDisposable registration = m_modules.RegisterCatalogParticipant(observer); @@ -362,20 +460,28 @@ public void AssemblyCatalogJoinsAnExistingSourceCandidateWithoutTakingItsPublica if (reject) throw new InvalidOperationException("Expected joined candidate rejection."); }; if (reject) + { Assert.Throws(m_modules.Rebuild); + } else + { m_modules.Rebuild(); + } Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); Assert.True(candidate.TryGetInfo(AssetPath.Project("value.txt"), out _)); observer.activate = null; if (reject) + { candidate.Rollback(); + } else { candidate.Activate(); candidate.Complete(); - Assert.Equal("candidate", Encoding.UTF8.GetString( - pipeline.Load(replacement.identity.persistentId).runtimePayload.Span)); + Assert.Equal( + "candidate", + Encoding.UTF8.GetString(pipeline.Load(replacement.identity.persistentId).runtimePayload.Span) + ); } } @@ -384,9 +490,15 @@ public void IntroducedImportFailureLeavesTheLiveAssetAndCatalogUntouched() { using TestWorkspace workspace = new(); workspace.WriteText("value.mutableasset", "previous"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); MutableAsset previous = pipeline.Load(AssetPath.Project("value.mutableasset")); byte[] sidecar = System.IO.File.ReadAllBytes(workspace.SourcePath("value.mutableasset.imeta")); workspace.WriteText("value.mutableasset", "!invalid!"); @@ -410,14 +522,16 @@ public void CandidateMetadataRejectsExternalChangesWithoutOverwritingThem() using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); workspace.WriteText("new.txt", "candidate"); using AssetCatalogCandidate candidate = loader.PrepareCatalogCandidate( - [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)]); + [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)] + ); using AssetLoader candidateLoader = candidate.loader; candidateLoader.Rescan(); string sidecarPath = workspace.SourcePath("new.txt.imeta"); Assert.False(System.IO.File.Exists(sidecarPath)); byte[] external = m_serialization.Serialize(new MountedSourceMetadata { - persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.File, + persistentId = Guid.NewGuid(), + sourceKind = (int)AssetSourceKind.File, importerId = "external.importer" }); System.IO.File.WriteAllBytes(sidecarPath, external); @@ -433,7 +547,8 @@ public void CandidateMetadataCompensatesEarlierSidecarsWhenALaterWriteFails() workspace.WriteText("a.txt", "first"); workspace.WriteText("z.txt", "last"); using AssetCatalogCandidate candidate = loader.PrepareCatalogCandidate( - [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)]); + [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)] + ); using AssetLoader candidateLoader = candidate.loader; candidateLoader.Rescan(); Directory.CreateDirectory(workspace.SourcePath("z.txt.imeta")); @@ -452,9 +567,15 @@ public void CandidateDiagnosticsPublishOnlyWithTheirSourceGenerationAndRetireWit workspace.WriteText("previous.mutableasset", "!invalid!"); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); Assert.Single(sink.reports.Values); string previousSource = Assert.Single(sink.reports.Keys); workspace.WriteText("new.mutableasset", "!invalid!"); @@ -490,7 +611,8 @@ public void CandidateCommitRestoresCatalogAndSidecarsWhenJournalRetirementFails( byte[] previous = System.IO.File.ReadAllBytes(snapshotPath); workspace.WriteText("new.txt", "candidate"); using AssetCatalogCandidate candidate = loader.PrepareCatalogCandidate( - [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)]); + [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)] + ); using AssetLoader candidateLoader = candidate.loader; candidateLoader.Rescan(); Directory.CreateDirectory(journalPath); @@ -510,9 +632,15 @@ public void CandidateDiagnosticRecoveryCanRollBackToThePreviousUnresolvedReport( workspace.WriteText("value.mutableasset", "!invalid!"); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); DiagnosticReport previous = Assert.Single(sink.reports.Values); workspace.WriteText("value.mutableasset", "fixed"); using AssetSourceMountTransaction candidate = pipeline.PrepareSourceMounts(pipeline.sourceMounts); @@ -522,8 +650,10 @@ public void CandidateDiagnosticRecoveryCanRollBackToThePreviousUnresolvedReport( candidate.Rollback(); DiagnosticReport restored = Assert.Single(sink.reports.Values); Assert.Equal(previous.source.id, restored.source.id); - Assert.Equal(previous.diagnostics.Select(static issue => issue.message), - restored.diagnostics.Select(static issue => issue.message)); + Assert.Equal( + previous.diagnostics.Select(static issue => issue.message), + restored.diagnostics.Select(static issue => issue.message) + ); m_diagnostics.UnregisterSink(sink); } @@ -541,9 +671,12 @@ public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) private sealed class Observation(Action? activate) : IAssemblyCatalogTransaction { public object? context => null; + public void Activate() => activate?.Invoke(); - public void Complete() { } - public void Rollback() { } + + public void Complete() {} + + public void Rollback() {} } } @@ -554,13 +687,20 @@ public void SourceCandidatePublishesCanonicalIdentitiesOnlyDuringSharedRecovery( { using TestWorkspace workspace = new(); workspace.WriteText("value.txt", "old"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, enableFileSystemWatcher = false - }); + } + ); TextAsset previous = pipeline.Load(AssetPath.Project("value.txt")); RuntimeIdentity previousIdentity = previous.identity.runtimeIdentity!.Value; workspace.WriteText("value.txt", "candidate"); @@ -600,9 +740,15 @@ public void SourceCandidateIdentityConflictRestoresThePreviousDomain() { using TestWorkspace workspace = new(); workspace.WriteText("previous.txt", "old"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); TextAsset previous = pipeline.Load(AssetPath.Project("previous.txt")); workspace.WriteText("candidate.txt", "new"); using AssetSourceMountTransaction transaction = pipeline.PrepareSourceMounts(pipeline.sourceMounts); @@ -617,7 +763,10 @@ public void SourceCandidateIdentityConflictRestoresThePreviousDomain() transaction.Rollback(); Assert.Same(previous, pipeline.Load(previous.identity.persistentId)); } - finally { m_identities.Unregister(unrelated); } + finally + { + m_identities.Unregister(unrelated); + } } [Fact] @@ -625,9 +774,15 @@ public void SourceRemovalAndReturnKeepTheSameRecoverySlotAndNeutralState() { using TestWorkspace workspace = new(); workspace.WriteText("value.txt", "preserved"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); TextAsset previous = pipeline.Load(AssetPath.Project("value.txt")); Guid id = previous.identity.persistentId; byte[] metadata = System.IO.File.ReadAllBytes(workspace.SourcePath("value.txt.imeta")); @@ -664,9 +819,15 @@ public void SourceRetirementDrainsPendingHooksBeforeCompletingTheTransaction(boo { using TestWorkspace workspace = new(); workspace.WriteText("value.hookasset", "previous"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); HookAsset previous = pipeline.Load(AssetPath.Project("value.hookasset")); workspace.WriteText("value.hookasset", "candidate"); using AssetSourceMountTransaction transaction = pipeline.PrepareSourceMounts(pipeline.sourceMounts); @@ -676,8 +837,14 @@ public void SourceRetirementDrainsPendingHooksBeforeCompletingTheTransaction(boo retiring.pendingUnloads = 2; transaction.Activate(); - if (commit) transaction.Complete(); - else transaction.Rollback(); + if (commit) + { + transaction.Complete(); + } + else + { + transaction.Rollback(); + } Assert.Equal(3, retiring.unloadingCount); Assert.True(retiring.runtimePayload.IsEmpty); @@ -715,9 +882,15 @@ public void PipelineShutdownDrainsCanonicalAssetsBeforeReleasingTheirOwners() { using TestWorkspace workspace = new(); workspace.WriteText("value.hookasset", "payload"); - var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); HookAsset asset = pipeline.Load(AssetPath.Project("value.hookasset")); asset.pendingUnloads = 1; pipeline.Dispose(); @@ -777,7 +950,10 @@ public async Task LoaderDisposalDoesNotBlockAnInFlightLoadOrAdmitNewWork() Assert.Throws(loader.Dispose); Assert.Throws(() => loader.LoadAsync(AssetPath.Project("value.slowasset"), typeof(SlowAsset))); } - finally { SlowAssetImporter.allowImport.Set(); } + finally + { + SlowAssetImporter.allowImport.Set(); + } AssetObject asset = Assert.IsType(await loading); Assert.NotNull(asset.identity.runtimeId); loader.Dispose(); @@ -792,12 +968,20 @@ public void SourceRetirementTimeoutFaultsAdmissionAndKeepsBothGenerationsOwned(b using TestWorkspace workspace = new(); workspace.WriteText("value.hookasset", "previous"); var modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetLoaderTests).Assembly)}); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetLoaderTests).Assembly) + }); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); var serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - var pipeline = new AssetPipeline(modules, types, serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot }); + var pipeline = new AssetPipeline( + modules, + types, + serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } + ); HookAsset previous = pipeline.Load(AssetPath.Project("value.hookasset")); workspace.WriteText("value.hookasset", "candidate"); AssetSourceMountTransaction transaction = pipeline.PrepareSourceMounts(pipeline.sourceMounts); @@ -807,8 +991,14 @@ public void SourceRetirementTimeoutFaultsAdmissionAndKeepsBothGenerationsOwned(b retiring.retirementExpired = true; transaction.Activate(); - if (commit) Assert.Throws(transaction.Complete); - else Assert.Throws(transaction.Rollback); + if (commit) + { + Assert.Throws(transaction.Complete); + } + else + { + Assert.Throws(transaction.Rollback); + } Assert.False(retiring.runtimePayload.IsEmpty); Assert.False(retained.runtimePayload.IsEmpty); @@ -884,15 +1074,23 @@ public async Task RuntimeLeaseRetriesPendingBudgetEvictionWithoutReleasingAnothe using SerializationGeneration serialization = m_serialization.CaptureGeneration(); var identities = new IdentityAllocator(); using ContentTestStore contentStore = ContentTestStore.FromDirectory(contentRoot); - using var database = new AssetDatabase(contentStore, serialization, m_types.current, identities, - residencyBudgetBytes: 0); + using var database = new AssetDatabase( + contentStore, + serialization, + m_types.current, + identities, + residencyBudgetBytes: 0 + ); Task> pending = database.AcquireAsync( - AssetPath.Project("value.hookasset")).AsTask(); - Assert.True(SpinWait.SpinUntil(() => - { - database.CompletePendingLoads(); - return pending.IsCompleted; - }, TimeSpan.FromSeconds(5))); + AssetPath.Project("value.hookasset") + ).AsTask(); + Assert.True( + SpinWait.SpinUntil(() => + { + database.CompletePendingLoads(); + return pending.IsCompleted; + }, TimeSpan.FromSeconds(5)) + ); using AssetLease first = await pending; HookAsset asset = first.asset; RuntimeIdentity identity = asset.identity.runtimeIdentity!.Value; @@ -978,7 +1176,8 @@ public void AutomaticallyDiscoveredPrivateImporter_LoadsWithoutRegistrationApi() using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); PrivateConstructorAsset asset = Assert.IsType( - loader.Load(AssetPath.Project("Private/item.privateasset"), typeof(PrivateConstructorAsset))); + loader.Load(AssetPath.Project("Private/item.privateasset"), typeof(PrivateConstructorAsset)) + ); Assert.Equal("private", asset.value); m_types.Rebuild(); @@ -1013,10 +1212,12 @@ public void DuplicateImporterId_IsRejectedDuringAutomaticDiscovery() AppContext.BaseDirectory, "Modules", "DuplicateAssetImporters", - "Inno.Assets.Pipeline.DuplicateImporterFixture.dll"), + "Inno.Assets.Pipeline.DuplicateImporterFixture.dll" + ), domain = AssemblyDomain.InnoPlugin, scope = AssemblyScope.Editor - })); + }) + ); Assert.Contains("importer id", exception.Message, StringComparison.OrdinalIgnoreCase); } @@ -1030,7 +1231,8 @@ public void DuplicateImporterExtension_IsRejectedDuringAutomaticDiscovery() ImporterConflictProbe.duplicateExtension = true; InvalidOperationException exception = Assert.Throws( - () => loader.Import(AssetPath.Project("Conflict/value.conflict"))); + () => loader.Import(AssetPath.Project("Conflict/value.conflict")) + ); Assert.Contains("extension", exception.Message, StringComparison.OrdinalIgnoreCase); } @@ -1055,17 +1257,21 @@ public void BlockedSourceVerificationRetainsLastGoodArtifactAndReportsImportFail using TestWorkspace workspace = new(); workspace.WriteText("Text/cached.txt", "cached"); using (AssetLoader first = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs)) + { first.Rescan(); + } using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); using var sourceLock = new FileStream( workspace.SourcePath("Text/cached.txt"), FileMode.Open, FileAccess.ReadWrite, - FileShare.None); + FileShare.None + ); TextAsset asset = Assert.IsType( - loader.Load(AssetPath.Project("Text/cached.txt"), typeof(TextAsset))); + loader.Load(AssetPath.Project("Text/cached.txt"), typeof(TextAsset)) + ); Assert.Equal("cached", asset.content); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/cached.txt"), out AssetInfo? info)); @@ -1080,15 +1286,15 @@ public void ChangedStampWithEqualContent_DoesNotReimportCanonicalAsset() workspace.WriteText("Text/touched.txt", "value"); using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset before = Assert.IsType( - loader.Load(AssetPath.Project("Text/touched.txt"), typeof(TextAsset))); + loader.Load(AssetPath.Project("Text/touched.txt"), typeof(TextAsset)) + ); long version = before.contentVersion; string sourcePath = workspace.SourcePath("Text/touched.txt"); - System.IO.File.SetLastWriteTimeUtc( - sourcePath, - System.IO.File.GetLastWriteTimeUtc(sourcePath).AddSeconds(1)); + System.IO.File.SetLastWriteTimeUtc(sourcePath, System.IO.File.GetLastWriteTimeUtc(sourcePath).AddSeconds(1)); TextAsset after = Assert.IsType( - loader.Load(AssetPath.Project("Text/touched.txt"), typeof(TextAsset))); + loader.Load(AssetPath.Project("Text/touched.txt"), typeof(TextAsset)) + ); Assert.Same(before, after); Assert.Equal(version, after.contentVersion); @@ -1106,10 +1312,12 @@ public void BlockedDependencyVerificationRetainsLastGoodArtifactAndReportsImport workspace.SourcePath("Import/schema.inc"), FileMode.Open, FileAccess.ReadWrite, - FileShare.None); + FileShare.None + ); ImportGraphAsset asset = Assert.IsType( - loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset))); + loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset)) + ); Assert.False(asset.isMissing); Assert.True(loader.TryGetInfo(AssetPath.Project("Import/root.importgraph"), out AssetInfo? info)); @@ -1129,7 +1337,8 @@ public async Task ConcurrentAsyncLoads_ShareImportAndCancellationOnlyCancelsOneW ValueTask second = loader.LoadAsync( AssetPath.Project("Slow/item.slowasset"), typeof(SlowAsset), - cancellation.Token); + cancellation.Token + ); cancellation.Cancel(); await Assert.ThrowsAnyAsync(async () => await second); @@ -1148,7 +1357,8 @@ public void ChangedDependencyWithPreservedTimestampReimportsTheCanonicalAsset() workspace.WriteText("Import/root.importgraph", "Import/schema.inc"); using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); ImportGraphAsset before = Assert.IsType( - loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset))); + loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset)) + ); long version = before.contentVersion; string dependency = workspace.SourcePath("Import/schema.inc"); DateTime timestamp = System.IO.File.GetLastWriteTimeUtc(dependency); @@ -1156,7 +1366,8 @@ public void ChangedDependencyWithPreservedTimestampReimportsTheCanonicalAsset() System.IO.File.SetLastWriteTimeUtc(dependency, timestamp); ImportGraphAsset after = Assert.IsType( - loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset))); + loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset)) + ); Assert.Same(before, after); Assert.Equal(version + 1, after.contentVersion); @@ -1179,7 +1390,9 @@ public void StaleSource_ReimportsAndUpdatesCanonicalInstanceInPlace(bool preserv workspace.WriteText("Text/reload.txt", "two"); if (preserveTimestamp) + { System.IO.File.SetLastWriteTimeUtc(sourcePath, sourceTime); + } TextAsset after = Assert.IsType(loader.Load(AssetPath.Project("Text/reload.txt"), typeof(TextAsset))); Assert.Same(before, after); @@ -1197,7 +1410,8 @@ public void RuntimeDependencyCycle_IsAllowedAndLoadsAsOneCanonicalSubgraph() using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); DependencyAsset root = Assert.IsType( - loader.Load(AssetPath.Project("Graphs/a.depgraph"), typeof(DependencyAsset))); + loader.Load(AssetPath.Project("Graphs/a.depgraph"), typeof(DependencyAsset)) + ); IReadOnlyList direct = loader.GetDependencies(root); IReadOnlyList recursive = loader.GetDependencies(root, recursive: true); @@ -1215,9 +1429,20 @@ public async Task AsyncRuntimeExportReleasesItsGenerationLeaseAfterEveryOutcome( { using TestWorkspace workspace = new(); workspace.WriteText("leaf.buildinput", "original"); - using var pipeline = new AssetPipeline(m_modules, m_types, m_serialization, m_identities, - m_diagnostics, m_logs, new AssetPipelineOptions - { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, enableFileSystemWatcher = false }); + using var pipeline = new AssetPipeline( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions + { + assetRoot = workspace.assetRoot, + libraryRoot = workspace.libraryRoot, + enableFileSystemWatcher = false + } + ); DependencyAsset leaf = pipeline.Load(AssetPath.Project("leaf.buildinput")); workspace.WriteText("root.buildconsumer", leaf.identity.persistentId.ToString()); _ = pipeline.Load(AssetPath.Project("root.buildconsumer")); @@ -1225,13 +1450,21 @@ public async Task AsyncRuntimeExportReleasesItsGenerationLeaseAfterEveryOutcome( using var cancellation = new CancellationTokenSource(); if (outcome == "cancel") cancellation.Cancel(); Task export = pipeline.ExportRuntimeArtifactsAsync( - Path.Combine(workspace.libraryRoot, "AsyncRuntime"), cancellation.Token); + Path.Combine(workspace.libraryRoot, "AsyncRuntime"), + cancellation.Token + ); if (outcome == "cancel") + { await Assert.ThrowsAnyAsync(() => export); + } else if (outcome == "invalid") + { await Assert.ThrowsAsync(() => export); + } else + { _ = await export; + } m_modules.generations.EnsureReady("replace the generation after export"); } @@ -1256,9 +1489,13 @@ bool importChange workspace.WriteText("leaf.buildinput", change); if (importChange) + { Assert.False(loader.Import(AssetPath.Project("leaf.buildinput"))); + } using (ArtifactLease lastGood = loader.AcquireArtifact(leaf.identity.persistentId, "authoring")) + { Assert.Equal("original", Encoding.UTF8.GetString(lastGood.ReadAllBytes())); + } string invalidDestination = Path.Combine(workspace.libraryRoot, "InvalidRuntime"); InvalidOperationException error = Assert.Throws(() => loader.ExportRuntimeArtifacts(invalidDestination)); Assert.Contains("root.buildconsumer -> middle.buildinput -> leaf.buildinput", error.Message); @@ -1291,29 +1528,46 @@ public async Task ColdRootsShareDependencyIoAndRetireReservationsAcrossRepeatedC loader.ExportRuntimeArtifacts(contentRoot); using SerializationGeneration serialization = m_serialization.CaptureGeneration(); using ContentTestStore contentStore = ContentTestStore.FromDirectory(contentRoot); - using var database = new AssetDatabase(contentStore, serialization, m_types.current, - new IdentityAllocator(), residencyBudgetBytes: 0, preparationBudgetBytes: 100000); + using var database = new AssetDatabase( + contentStore, + serialization, + m_types.current, + new IdentityAllocator(), + residencyBudgetBytes: 0, + preparationBudgetBytes: 100000 + ); for (int cycle = 0; cycle < 32; cycle++) { using var cancellation = new CancellationTokenSource(); Task> first = database.AcquireAsync( - AssetPath.Project("A.depgraph"), cancellation.Token).AsTask(); + AssetPath.Project("A.depgraph"), + cancellation.Token + ).AsTask(); long firstBytes = database.preparingBytes; Task> second = database.AcquireAsync( - AssetPath.Project("B.depgraph")).AsTask(); + AssetPath.Project("B.depgraph") + ).AsTask(); Assert.Equal(3, database.preparationStatistics.pendingPayloads); Assert.True(database.preparingBytes < firstBytes * 2); if (cancelFirst) - cancellation.Cancel(); - Assert.True(SpinWait.SpinUntil(() => { - database.CompletePendingLoads(); - return first.IsCompleted && second.IsCompleted; - }, TimeSpan.FromSeconds(5))); + cancellation.Cancel(); + } + Assert.True( + SpinWait.SpinUntil(() => + { + database.CompletePendingLoads(); + return first.IsCompleted && second.IsCompleted; + }, TimeSpan.FromSeconds(5)) + ); if (cancelFirst) + { Assert.True(first.IsCanceled); + } else + { (await first).Dispose(); + } (await second).Dispose(); Assert.Equal(0, database.preparationStatistics.pendingPayloads); Assert.Equal(0, database.preparingBytes); @@ -1372,21 +1626,26 @@ public void CorruptSharedPayloadFailsBothRootsWithoutLeakingReservationsOrPublis using var database = new AssetDatabase(contentStore, serialization, m_types.current, new IdentityAllocator()); using (ArtifactLease artifact = database.AcquireArtifact(shared.identity.persistentId, "runtime")) { - ContentKey key = Assert.Single(contentStore.index.entries.Where(entry => - entry.key.value!.StartsWith("Artifacts/", StringComparison.Ordinal) - && entry.key.value.Contains("/outputs/", StringComparison.Ordinal) - && entry.contentHash == artifact.info.contentHash)).key; + ContentKey key = Assert.Single( + contentStore.index.entries.Where(entry => ( + entry.key.value!.StartsWith("Artifacts/", StringComparison.Ordinal) + && entry.key.value.Contains("/outputs/", StringComparison.Ordinal) + && entry.contentHash == artifact.info.contentHash + )) + ).key; byte[] bytes = artifact.ReadAllBytes(); bytes[0] ^= 0xff; contentStore.CorruptPayload(key, bytes); } Task> first = database.AcquireAsync(AssetPath.Project("A.depgraph")).AsTask(); Task> second = database.AcquireAsync(AssetPath.Project("B.depgraph")).AsTask(); - Assert.True(SpinWait.SpinUntil(() => - { - database.CompletePendingLoads(); - return first.IsCompleted && second.IsCompleted; - }, TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => + { + database.CompletePendingLoads(); + return first.IsCompleted && second.IsCompleted; + }, TimeSpan.FromSeconds(5)) + ); Assert.True(first.IsFaulted); Assert.True(second.IsFaulted); Assert.Contains("integrity", first.Exception!.ToString()); @@ -1468,7 +1727,8 @@ public void RecreatedSourceWithoutMetadata_ReceivesNewIdentity() ]); TextAsset replacement = Assert.IsType( - loader.Load(AssetPath.Project("Text/recover.txt"), typeof(TextAsset))); + loader.Load(AssetPath.Project("Text/recover.txt"), typeof(TextAsset)) + ); Assert.True(asset.isMissing); Assert.False(replacement.isMissing); Assert.Equal("two", replacement.content); @@ -1510,22 +1770,31 @@ public void CatalogRestart_PrefersCurrentSourceIdentityOverHistoricalPathRecord( workspace.WriteText(path, "value"); Guid historicalId; using (AssetLoader first = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { first.Rescan(); Assert.True(first.TryGetPersistentId(AssetPath.Project(path), out historicalId)); } string sidecarPath = workspace.SourcePath(path + ".imeta"); MountedSourceMetadata metadata = m_serialization.Deserialize( - System.IO.File.ReadAllBytes(sidecarPath)); + System.IO.File.ReadAllBytes(sidecarPath) + ); Guid currentId = Guid.NewGuid(); metadata.persistentId = currentId; System.IO.File.WriteAllBytes(sidecarPath, m_serialization.Serialize(metadata)); using (AssetLoader recovered = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { recovered.Rescan(); Assert.True(recovered.TryGetPersistentId(AssetPath.Project(path), out Guid indexedId)); Assert.Equal(currentId, indexedId); @@ -1534,12 +1803,18 @@ public void CatalogRestart_PrefersCurrentSourceIdentityOverHistoricalPathRecord( } using AssetLoader restarted = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs); + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + ); restarted.Rescan(); Assert.True(restarted.TryGetPersistentId(AssetPath.Project(path), out Guid stableId)); Assert.Equal(currentId, stableId); MountedSourceMetadata stableMetadata = m_serialization.Deserialize( - System.IO.File.ReadAllBytes(sidecarPath)); + System.IO.File.ReadAllBytes(sidecarPath) + ); Assert.Equal(currentId, stableMetadata.persistentId); } @@ -1550,14 +1825,17 @@ public void CatalogRestart_DoesNotPromoteHistoricalTombstonesToMissingReferences workspace.WriteText("Text/removed.txt", "one"); Guid removedId; using (AssetLoader loader = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { loader.Rescan(); Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/removed.txt"), out removedId)); workspace.DeleteSource("Text/removed.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent( - "Text/removed.txt", WatcherChangeTypes.Deleted) + new Inno.Assets.Pipeline.AssetChangedEvent("Text/removed.txt", WatcherChangeTypes.Deleted) ]); } @@ -1577,7 +1855,8 @@ public void CatalogRestart_DoesNotPromoteHistoricalTombstonesToMissingReferences assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot, enableFileSystemWatcher = false - }); + } + ); Assert.True(restarted.TryGetInfo(removedId, out AssetInfo? tombstone)); Assert.Equal(AssetImportStatus.Missing, tombstone!.status); @@ -1589,7 +1868,8 @@ public void CatalogRestart_DoesNotPromoteHistoricalTombstonesToMissingReferences Assert.Empty(generation.recoveryChanges); Assert.DoesNotContain( sink.reports.Values.SelectMany(static report => report.diagnostics), - static diagnostic => diagnostic.code == "ASSET-REFERENCE"); + static diagnostic => diagnostic.code == "ASSET-REFERENCE" + ); generation.Complete(); @@ -1598,11 +1878,13 @@ public void CatalogRestart_DoesNotPromoteHistoricalTombstonesToMissingReferences tombstone.stableAssetTypeId, "Text/removed.txt", typeof(TextAsset), - "$test.reference"); + "$test.reference" + ); Assert.True(explicitlyResolved.isMissing); Assert.Contains( sink.reports.Values.SelectMany(static report => report.diagnostics), - static diagnostic => diagnostic.code == "ASSET-REFERENCE"); + static diagnostic => diagnostic.code == "ASSET-REFERENCE" + ); } finally { @@ -1717,7 +1999,8 @@ public void FailedReimport_KeepsPreviousCanonicalStateAndVersion() workspace.WriteText("Data/stable.mutableasset", "one"); using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); MutableAsset asset = Assert.IsType( - loader.Load(AssetPath.Project("Data/stable.mutableasset"), typeof(MutableAsset))); + loader.Load(AssetPath.Project("Data/stable.mutableasset"), typeof(MutableAsset)) + ); long version = asset.contentVersion; workspace.WriteText("Data/stable.mutableasset", "!invalid!"); @@ -1742,12 +2025,14 @@ public void FailedReimport_PublishesCurrentDiagnosticUntilSuccessfulRetry() try { MutableAsset asset = Assert.IsType( - loader.Load(AssetPath.Project("Data/diagnostic.mutableasset"), typeof(MutableAsset))); + loader.Load(AssetPath.Project("Data/diagnostic.mutableasset"), typeof(MutableAsset)) + ); workspace.WriteText("Data/diagnostic.mutableasset", "!invalid!"); Assert.False(loader.Import(AssetPath.Project("Data/diagnostic.mutableasset"))); - DiagnosticReport report = Assert.Single(sink.reports.Values.Where(value => - value.source.displayName == "Data/diagnostic.mutableasset")); + DiagnosticReport report = Assert.Single( + sink.reports.Values.Where(value => (value.source.displayName == "Data/diagnostic.mutableasset")) + ); Diagnostic diagnostic = Assert.Single(report.diagnostics); Assert.Equal("ASSET-IMPORT", diagnostic.code); Assert.Equal(DiagnosticSeverity.Error, diagnostic.severity); @@ -1756,7 +2041,8 @@ public void FailedReimport_PublishesCurrentDiagnosticUntilSuccessfulRetry() Assert.True(loader.Import(AssetPath.Project("Data/diagnostic.mutableasset"))); Assert.DoesNotContain( sink.reports.Values, - value => value.source.displayName == "Data/diagnostic.mutableasset"); + value => value.source.displayName == "Data/diagnostic.mutableasset" + ); Assert.Equal("recovered", asset.value); } finally @@ -1775,7 +2061,9 @@ public void UnchangedFailedSourceIsNotRetriedUntilItsInputChanges() Assert.False(loader.Import(path)); int failedAttempts = MutableAssetImporter.attempts; for (int index = 0; index < 5; index++) + { loader.Rescan(); + } Assert.Equal(failedAttempts, MutableAssetImporter.attempts); workspace.WriteText("Data/retry.mutableasset", "repaired"); @@ -1797,7 +2085,9 @@ public void FailedSave_PreservesCommittedSourceMetaArtifactAndVersion() Assert.NotNull(artifact); byte[] artifactBefore; using (ArtifactLease before = loader.AcquireArtifact(asset.identity.persistentId, "runtime")) + { artifactBefore = before.ReadAllBytes(); + } long versionBefore = asset.contentVersion; asset.value = "!invalid!"; @@ -1806,7 +2096,9 @@ public void FailedSave_PreservesCommittedSourceMetaArtifactAndVersion() Assert.Equal(sourceBefore, System.IO.File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset"))); Assert.Equal(metaBefore, System.IO.File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset.imeta"))); using (ArtifactLease after = loader.AcquireArtifact(asset.identity.persistentId, "runtime")) + { Assert.Equal(artifactBefore, after.ReadAllBytes()); + } Assert.Equal(versionBefore, asset.contentVersion); } @@ -1818,7 +2110,8 @@ public void RuntimeDependencyRetention_KeepsDependencyAliveWhileRootIsReferenced workspace.WriteText("Graphs/root.depgraph", "Text/dependency.txt"); using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); DependencyAsset root = Assert.IsType( - loader.Load(AssetPath.Project("Graphs/root.depgraph"), typeof(DependencyAsset))); + loader.Load(AssetPath.Project("Graphs/root.depgraph"), typeof(DependencyAsset)) + ); Assert.Equal(0, loader.UnloadUnusedAssets()); Assert.Equal(2, loader.GetLoadedPaths().Count); @@ -1900,8 +2193,12 @@ public void Rescan_RecoversAnonymousCatalogEntryFromSourceIdentityWithoutFalseMi const string path = "Deferred/value.unavailable"; workspace.WriteText(path, "source awaiting its module generation"); using (AssetLoader first = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { first.Rescan(); Assert.True(first.TryGetInfo(AssetPath.Project(path), out AssetInfo? unsupported)); Assert.Equal(Guid.Empty, unsupported!.persistentId); @@ -1916,14 +2213,19 @@ public void Rescan_RecoversAnonymousCatalogEntryFromSourceIdentityWithoutFalseMi persistentId = persistentId, sourceKind = (int)AssetSourceKind.File, importerId = "tests.unavailable-generation" - })); + }) + ); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); try { using (AssetLoader recovered = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { recovered.Rescan(); Assert.True(recovered.TryGetInfo(persistentId, out AssetInfo? pending)); Assert.Equal(path, pending!.assetPath.ToString()); @@ -1934,15 +2236,22 @@ public void Rescan_RecoversAnonymousCatalogEntryFromSourceIdentityWithoutFalseMi persistentId, expectedStableTypeId, path, - typeof(AssetObject)); + typeof(AssetObject) + ); Assert.True(placeholder.isMissing); Assert.DoesNotContain( sink.reports.Values.SelectMany(static report => report.diagnostics), - static diagnostic => diagnostic.code == "ASSET-REFERENCE"); + static diagnostic => diagnostic.code == "ASSET-REFERENCE" + ); } using AssetLoader restarted = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs); + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + ); restarted.Rescan(); Assert.True(restarted.TryGetInfo(persistentId, out AssetInfo? retained)); Assert.Equal("tests.unavailable-generation", retained!.importerId); @@ -1963,8 +2272,12 @@ public void Rescan_PreservesLastGoodCatalogWhileItsPathImporterIsUnavailable() Guid stableTypeId; AssetArtifactKey artifactKey; using (AssetLoader first = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { first.Rescan(); Assert.True(first.TryGetInfo(AssetPath.Project(path), out AssetInfo? imported)); persistentId = imported!.persistentId; @@ -1980,8 +2293,12 @@ public void Rescan_PreservesLastGoodCatalogWhileItsPathImporterIsUnavailable() try { using (AssetLoader restarted = workspace.CreateLoader( - m_types, m_serialization, m_identities, m_diagnostics, m_logs)) - { + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs + )) { restarted.Rescan(); Assert.True(restarted.TryGetInfo(AssetPath.Project(path), out AssetInfo? preserved)); @@ -1993,11 +2310,13 @@ public void Rescan_PreservesLastGoodCatalogWhileItsPathImporterIsUnavailable() persistentId, stableTypeId, path, - typeof(AssetObject)); + typeof(AssetObject) + ); Assert.False(resolved.isMissing); Assert.DoesNotContain( sink.reports.Values.SelectMany(static report => report.diagnostics), - static diagnostic => diagnostic.code == "ASSET-REFERENCE"); + static diagnostic => diagnostic.code == "ASSET-REFERENCE" + ); } } finally @@ -2129,7 +2448,8 @@ private sealed class TestWorkspace : IDisposable private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoAssetLoaderTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); internal TestWorkspace() { @@ -2139,25 +2459,34 @@ internal TestWorkspace() internal string assetRoot => Path.Combine(m_root, "Assets"); internal string libraryRoot => Path.Combine(m_root, "Library"); + internal AssetLoader CreateLoader( TypeCatalog types, SerializationRegistry serialization, IdentityAllocator identities, DiagnosticHub diagnostics, LogRouter logs - ) - => new(types, serialization, identities, diagnostics, logs, assetRoot, libraryRoot); + ) => new(types, serialization, identities, diagnostics, logs, assetRoot, libraryRoot); + internal string SourcePath(string relativePath) => Path.Combine(assetRoot, relativePath); internal string FindArtifactFile(AssetArtifactInfo artifact) { string key = artifact.key.value; - string directory = Path.Combine(libraryRoot, "Artifacts", key[..2].ToLowerInvariant(), - key[2..4].ToLowerInvariant(), key, "outputs"); - return Directory.EnumerateFiles(directory).Single(path => + string directory = Path.Combine( + libraryRoot, + "Artifacts", + key[..2].ToLowerInvariant(), + key[2..4].ToLowerInvariant(), + key, + "outputs" + ); + return Directory.EnumerateFiles(directory).Single(path => ( new FileInfo(path).Length == artifact.length - && Convert.ToHexString(System.Security.Cryptography.SHA256.HashData( - System.IO.File.ReadAllBytes(path))) == artifact.contentHash); + && Convert.ToHexString( + System.Security.Cryptography.SHA256.HashData(System.IO.File.ReadAllBytes(path)) + ) == artifact.contentHash + )); } internal void WriteText( @@ -2184,14 +2513,18 @@ internal void DeleteSource(string relativePath) { string path = SourcePath(relativePath); if (System.IO.File.Exists(path)) + { System.IO.File.Delete(path); + } } public void Dispose() { SlowAssetImporter.allowImport.Set(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } @@ -2199,11 +2532,9 @@ private sealed class TestDiagnosticSink : IDiagnosticSink { internal Dictionary reports { get; } = new(StringComparer.Ordinal); - public void Replace(DiagnosticReport report) - => reports[report.source.id] = report; + public void Replace(DiagnosticReport report) => reports[report.source.id] = report; - public void Clear(DiagnosticSource source) - => reports.Remove(source.id); + public void Clear(DiagnosticSource source) => reports.Remove(source.id); } } @@ -2219,9 +2550,7 @@ internal sealed class PrivateConstructorAssetImporter : AssetImporter s_extensions = [".privateasset"]; - private PrivateConstructorAssetImporter() - { - } + private PrivateConstructorAssetImporter() {} public override IReadOnlyList supportedExtensions => s_extensions; @@ -2255,7 +2584,9 @@ CancellationToken cancellationToken ) { attempts++; if (!available) + { throw new AssetImportExtensionUnavailableException("tests.target", "tests.surface"); + } output.SetAsset(new ExtensionDependentAsset()); return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); } @@ -2273,10 +2604,19 @@ CancellationToken cancellationToken ) { string source = context.ReadUtf8Text(); if (Guid.TryParse(source, out Guid id)) - _ = context.references.Resolve(id, context.services.GetStableTypeId(), - "surface.extensionasset", typeof(ExtensionDependentAsset), "$.shader"); + { + _ = context.references.Resolve( + id, + context.services.GetStableTypeId(), + "surface.extensionasset", + typeof(ExtensionDependentAsset), + "$.shader" + ); + } else + { _ = context.ResolveDependency(AssetPath.Project(source)); + } output.SetAsset(new ExtensionDependentAsset()); return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); } @@ -2289,8 +2629,7 @@ internal sealed class DeferredAssetImporter : AssetImporter internal static bool isAvailable { get; set; } = true; - public override IReadOnlyList supportedExtensions - => isAvailable ? s_extensions : Array.Empty(); + public override IReadOnlyList supportedExtensions => isAvailable ? s_extensions : Array.Empty(); protected override ValueTask ImportAsync( AssetImportContext context, @@ -2317,7 +2656,9 @@ CancellationToken cancellationToken ) { string dependency = context.ReadUtf8Text().Trim(); if (!string.IsNullOrWhiteSpace(dependency)) + { output.DependsOnAsset(AssetPath.Parse(dependency)); + } output.SetAsset(new DependencyAsset()); return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); } @@ -2351,9 +2692,13 @@ CancellationToken cancellationToken ) { string text = context.ReadUtf8Text(); if (text == "failed") + { throw new InvalidDataException("Required authoring input failed."); + } if (Guid.TryParse(text, out Guid dependency)) + { context.DependsOnArtifact(dependency); + } output.SetAsset(new DependencyAsset()); return output.WriteArtifactAsync("authoring", context.sourceBytes, cancellationToken, AssetDeploymentScope.AuthoringOnly); } @@ -2373,8 +2718,12 @@ CancellationToken cancellationToken if (context.ReadUtf8Text() == "authoring") { output.SetDeploymentScope(AssetDeploymentScope.AuthoringOnly); - return output.WriteArtifactAsync("graph", context.sourceBytes, cancellationToken, - AssetDeploymentScope.AuthoringOnly); + return output.WriteArtifactAsync( + "graph", + context.sourceBytes, + cancellationToken, + AssetDeploymentScope.AuthoringOnly + ); } return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); } @@ -2411,7 +2760,9 @@ CancellationToken cancellationToken ) { string dependency = context.ReadUtf8Text().Trim(); if (!string.IsNullOrWhiteSpace(dependency)) + { output.DependsOnSource(AssetPath.Parse(dependency)); + } output.SetAsset(new ImportGraphAsset()); return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); } @@ -2448,7 +2799,9 @@ CancellationToken cancellationToken Interlocked.Increment(ref importCount); importStarted.Set(); if (!allowImport.Wait(TimeSpan.FromSeconds(5))) + { throw new TimeoutException("The slow importer test gate was not released."); + } output.SetAsset(new SlowAsset { value = context.ReadUtf8Text() }); return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); } @@ -2475,7 +2828,9 @@ CancellationToken cancellationToken attempts++; string value = context.ReadUtf8Text(); if (value == "!invalid!") + { throw new InvalidDataException("The mutable asset source is invalid."); + } output.SetAsset(new MutableAsset { value = value }); return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); } @@ -2484,8 +2839,7 @@ CancellationToken cancellationToken AssetExportContext context, MutableAsset asset, CancellationToken cancellationToken - ) - => ValueTask.FromResult?>(Encoding.UTF8.GetBytes(asset.value)); + ) => ValueTask.FromResult?>(Encoding.UTF8.GetBytes(asset.value)); } [StableTypeId("9f9f5f9f-4d86-414f-9ff9-78ad8ec60606")] @@ -2500,21 +2854,24 @@ internal sealed class HookAsset : AssetObject protected override void OnRuntimePayloadChanged( ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload - ) - => Interlocked.Increment(ref payloadChangeCount); + ) => Interlocked.Increment(ref payloadChangeCount); protected override void OnUnloading() { Interlocked.Increment(ref unloadingCount); if (retirementExpired) + { throw new RetirementTimeoutException("The test asset work exceeded its retirement deadline."); + } if (pendingUnloads > 0) { pendingUnloads--; throw new RetirementPendingException("The test asset still owns unfinished work."); } if (failUnloading) + { throw new InvalidOperationException("The test asset release failed."); + } } } @@ -2544,10 +2901,10 @@ internal sealed class ImporterConflictAsset : AssetObject; [AssetImporter("inno.tests.conflict-a")] internal sealed class ImporterConflictAssetImporterA : AssetImporter { - public override IReadOnlyList supportedExtensions => - ImporterConflictProbe.duplicateExtension - ? [".conflict"] - : [".probea"]; + public override IReadOnlyList supportedExtensions + => ImporterConflictProbe.duplicateExtension + ? [".conflict"] + : [".probea"]; protected override ValueTask ImportAsync( AssetImportContext context, @@ -2562,10 +2919,10 @@ CancellationToken cancellationToken [AssetImporter("inno.tests.conflict-b")] internal sealed class ImporterConflictAssetImporterB : AssetImporter { - public override IReadOnlyList supportedExtensions => - ImporterConflictProbe.duplicateExtension - ? [".conflict"] - : [".probeb"]; + public override IReadOnlyList supportedExtensions + => ImporterConflictProbe.duplicateExtension + ? [".conflict"] + : [".probeb"]; protected override ValueTask ImportAsync( AssetImportContext context, diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs index 094818c95..ad123c194 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs @@ -1,12 +1,12 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Core.Diagnostics; using Inno.Core.Identity; @@ -15,8 +15,6 @@ using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Assets.Pipeline.Tests; public sealed class ImportSettingsTests @@ -70,8 +68,11 @@ public void StaleSettingsSnapshotCannotOverwriteNewerSidecar() AssetImportSettingsSnapshot original = loader.GetImportSettings(Fixture.path); Assert.True(loader.SaveImportSettings(Fixture.path, new ConfiguredSettings { multiplier = 2 }, original.fingerprint)); byte[] current = File.ReadAllBytes(fixture.sourcePath + ".imeta"); - Assert.Throws(() => loader.SaveImportSettings(Fixture.path, - new ConfiguredSettings { multiplier = 3 }, original.fingerprint)); + Assert.Throws(() => loader.SaveImportSettings( + Fixture.path, + new ConfiguredSettings { multiplier = 3 }, + original.fingerprint + )); Assert.Equal(current, File.ReadAllBytes(fixture.sourcePath + ".imeta")); } @@ -133,7 +134,10 @@ public void SettingsReferencesAreImportDependenciesNotRuntimeDependencies() public void ReadOnlySourcesAllowViewingButRejectSettingsWrites() { using var fixture = new Fixture(); - using (AssetLoader writer = fixture.CreateLoader()) Assert.True(writer.Import(Fixture.path)); + using (AssetLoader writer = fixture.CreateLoader()) + { + Assert.True(writer.Import(Fixture.path)); + } byte[] metadata = File.ReadAllBytes(fixture.sourcePath + ".imeta"); var source = new AssetSourceId("tests.readonly.settings"); using AssetLoader reader = fixture.CreateReadOnlyLoader(source); @@ -174,18 +178,33 @@ internal Fixture() Directory.CreateDirectory(Path.Combine(m_root, "EmptyProject")); File.WriteAllText(sourcePath, "source"); m_scope = m_identities.EnterScope(); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ImportSettingsTests).Assembly)}); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ImportSettingsTests).Assembly)} + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } + internal string assetRoot => Path.Combine(m_root, "Assets"); internal string sourcePath => Path.Combine(assetRoot, "value.configured"); + internal AssetLoader CreateLoader(string library = "Library") => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, assetRoot, Path.Combine(m_root, library)); + internal AssetLoader CreateReadOnlyLoader(AssetSourceId id) - => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, - [new AssetSourceMount(AssetSourceId.project, Path.Combine(m_root, "EmptyProject"), false), - new AssetSourceMount(id, assetRoot, true)], Path.Combine(m_root, "ReadOnlyLibrary")); + => new( + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + [ + new AssetSourceMount(AssetSourceId.project, Path.Combine(m_root, "EmptyProject"), false), + new AssetSourceMount(id, assetRoot, true) + ], + Path.Combine(m_root, "ReadOnlyLibrary") + ); + public void Dispose() { m_serialization.Dispose(); @@ -215,9 +234,14 @@ internal sealed class ConfiguredAsset : AssetObject internal sealed class ConfiguredImporter : AssetImporter { public override IReadOnlyList supportedExtensions { get; } = [".configured"]; + public override ISerializable CreateImportSettings() => new ConfiguredSettings(); - protected override ValueTask ImportAsync(AssetImportContext context, AssetImportWriter output, CancellationToken cancellationToken) - { + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { var settings = (ConfiguredSettings)context.importSettings!; if (settings.multiplier < 0) throw new InvalidOperationException("A negative multiplier is invalid."); string value = $"{settings.multiplier}:{context.ReadUtf8Text()}"; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs index be8e1b2be..5bb7c7c3d 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs @@ -1,19 +1,17 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; using System.Text; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; - -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Assets.Pipeline.Tests; @@ -31,7 +29,9 @@ public ImporterIntegrationTests() { m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(ImporterIntegrationTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(ImporterIntegrationTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -52,8 +52,10 @@ public void Dispose() [InlineData("Text/a.yml", "yaml")] [InlineData("Text/a.md", "markdown")] [InlineData("Text/a.xml", "xml")] - public void TextExtensions_AreAutomaticallyDiscovered(string relativePath, string languageHint) - { + public void TextExtensions_AreAutomaticallyDiscovered( + string relativePath, + string languageHint + ) { using TestWorkspace workspace = new(); workspace.Write(relativePath, Encoding.UTF8.GetBytes("content")); using var loader = new AssetLoader( @@ -63,7 +65,8 @@ public void TextExtensions_AreAutomaticallyDiscovered(string relativePath, strin m_diagnostics, m_logs, workspace.assetRoot, - workspace.libraryRoot); + workspace.libraryRoot + ); AssetPath path = AssetPath.Project(relativePath); Assert.True(loader.Import(path)); @@ -84,7 +87,8 @@ public void BinaryImporter_CreatesRuntimeDescriptor() m_diagnostics, m_logs, workspace.assetRoot, - workspace.libraryRoot); + workspace.libraryRoot + ); BinaryAsset binary = Assert.IsType(loader.Load(AssetPath.Project("Data/blob.bytes"), typeof(BinaryAsset))); @@ -102,7 +106,8 @@ public void ExportableBuiltInAsset_RoundTripsThroughPublicLoaderContract() m_diagnostics, m_logs, workspace.assetRoot, - workspace.libraryRoot); + workspace.libraryRoot + ); var source = new TextAsset("saved", "plain"); Assert.True(loader.Save(AssetPath.Project("Text/saved.txt"), source)); @@ -117,7 +122,8 @@ private sealed class TestWorkspace : IDisposable private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoAssetsImporterTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); internal TestWorkspace() { @@ -128,8 +134,10 @@ internal TestWorkspace() internal string assetRoot => Path.Combine(m_root, "Assets"); internal string libraryRoot => Path.Combine(m_root, "Library"); - internal void Write(string relativePath, byte[] bytes) - { + internal void Write( + string relativePath, + byte[] bytes + ) { string path = Path.Combine(assetRoot, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(path)!); System.IO.File.WriteAllBytes(path, bytes); @@ -138,7 +146,9 @@ internal void Write(string relativePath, byte[] bytes) public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs index 74ef674d1..c646cad08 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs @@ -1,23 +1,23 @@ -using Inno.Content.Testing; -using Inno.Content; -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Content; +using Inno.Content.Testing; using Inno.Core.Diagnostics; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; using Inno.Extensibility.Reload; -using Xunit; +using Inno.Extensibility.Types; namespace Inno.Assets.Pipeline.Tests; @@ -86,8 +86,13 @@ public void RuntimeSettingsLoadTheirColdReferencesThroughTheSessionAssetOwner(bo using Stream settingsInput = settingsLease.OpenRead(); byte[] settingsBytes = new byte[checked((int)settingsLease.entry.length)]; settingsInput.ReadExactly(settingsBytes); - using var settings = new ProjectSettingsStore(new ReadOnlyByteDocumentStore("Settings.Project.inno", settingsBytes), fixture.types, fixture.serialization, - new ProjectId("tests.deployed.settings"), AssetSerializationContext.Create(database)); + using var settings = new ProjectSettingsStore( + new ReadOnlyByteDocumentStore("Settings.Project.inno", settingsBytes), + fixture.types, + fixture.serialization, + new ProjectId("tests.deployed.settings"), + AssetSerializationContext.Create(database) + ); TextAsset runtime = Assert.IsType(settings.Get(id).clip); Assert.Equal("deployed", runtime.content); @@ -106,12 +111,16 @@ public void FivePhaseSettingsRollbackRestoresExactEffectiveStateWithoutWritingDo using var fixture = new Fixture(); byte[] first = fixture.serialization.CapturePropertiesData(new ClipSettings { labels = ["previous"] }, fixture.context); byte[] next = fixture.serialization.CapturePropertiesData(new ClipSettings { labels = ["candidate"] }, fixture.context); - fixture.settings.Rebuild([new ProjectSettingsContributor("source", [], [], [new ProjectSettingRecord(ClipSettings.id, ClipSettings.typeId, first)])]); + fixture.settings.Rebuild( + [new ProjectSettingsContributor("source", [], [], [new ProjectSettingRecord(ClipSettings.id, ClipSettings.typeId, first)])] + ); byte[] document = fixture.settings.CaptureDocument(); long revision = fixture.settings.revision; IGenerationChange change = fixture.settings.CreateReloadChange(); change.PrepareForActivation(); - fixture.settings.SetContributors([new ProjectSettingsContributor("source", [], [], [new ProjectSettingRecord(ClipSettings.id, ClipSettings.typeId, next)])]); + fixture.settings.SetContributors( + [new ProjectSettingsContributor("source", [], [], [new ProjectSettingRecord(ClipSettings.id, ClipSettings.typeId, next)])] + ); change.Apply(); Assert.Equal("candidate", Assert.Single(fixture.settings.Get(ClipSettings.id).labels)); change.RollbackStructure(); @@ -143,8 +152,12 @@ public void ContributorPublicationFreezesNestedPayloadsAndKeepsLastGoodOnFailure long revision = fixture.settings.revision; Assert.ThrowsAny(() => fixture.settings.Rebuild([ - new ProjectSettingsContributor("broken", [], [], - [new ProjectSettingRecord(ClipSettings.id, ClipSettings.typeId, [1, 2, 3])])])); + new ProjectSettingsContributor( + "broken", + [], + [], + [new ProjectSettingRecord(ClipSettings.id, ClipSettings.typeId, [1, 2, 3])] + )])); Assert.Equal(revision, fixture.settings.revision); Assert.Equal("stable", Assert.Single(fixture.settings.Get(ClipSettings.id).labels)); } @@ -167,8 +180,12 @@ public void SettingsRequireAnExplicitOwnerSerializationContext() { using var fixture = new Fixture(); Assert.Throws(() => new ProjectSettingsStore( - new FileByteDocumentStore(Path.GetFullPath(Path.Combine(fixture.root, "Rejected.inno"))), fixture.types, fixture.serialization, - new ProjectId("tests.rejected"), null!)); + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(fixture.root, "Rejected.inno"))), + fixture.types, + fixture.serialization, + new ProjectId("tests.rejected"), + null! + )); } private sealed class Fixture : IDisposable @@ -185,14 +202,28 @@ internal Fixture() assetRoot = Path.Combine(root, "Assets"); Directory.CreateDirectory(assetRoot); m_identityScope = m_identities.EnterScope(); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(SettingsReferenceTests).Assembly)}); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(SettingsReferenceTests).Assembly)} + ); types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - assets = new AssetPipeline(m_modules, types, serialization, m_identities, m_diagnostics, m_logs, - AssetPipelineOptions.Create(assetRoot, Path.Combine(root, "Library")) with { enableFileSystemWatcher = false }); + assets = new AssetPipeline( + m_modules, + types, + serialization, + m_identities, + m_diagnostics, + m_logs, + AssetPipelineOptions.Create(assetRoot, Path.Combine(root, "Library")) with { enableFileSystemWatcher = false } + ); context = AssetSerializationContext.Create(assets); - settings = new ProjectSettingsStore(new FileByteDocumentStore(Path.GetFullPath(Path.Combine(root, "Settings.Project.inno"))), types, - serialization, new ProjectId("tests.settings.references"), context); + settings = new ProjectSettingsStore( + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(root, "Settings.Project.inno"))), + types, + serialization, + new ProjectId("tests.settings.references"), + context + ); } internal string root { get; } @@ -246,14 +277,20 @@ internal sealed class ClipContribution : ISerializable [ProjectSettingComposer("tests.settings.composed-clip")] internal sealed class ClipSettingsComposer : ProjectSettingComposer { - protected override ClipContribution CaptureContribution(ComposedClipSettings baseline, ComposedClipSettings value) - => new() { clip = value.clip }; + protected override ClipContribution CaptureContribution( + ComposedClipSettings baseline, + ComposedClipSettings value + ) => new() { clip = value.clip }; protected override bool IsEmpty(ClipContribution contribution) => contribution.clip is null; - protected override void Compose(ComposedClipSettings target, IReadOnlyList> contributions) - { + protected override void Compose( + ComposedClipSettings target, + IReadOnlyList> contributions + ) { foreach (ProjectSettingContribution contribution in contributions) + { target.clip = contribution.value.clip; + } } } diff --git a/tests/assets/Inno.Assets.Tests/AssetCoreTests.cs b/tests/assets/Inno.Assets.Tests/AssetCoreTests.cs index be8cdee55..bcf11f876 100644 --- a/tests/assets/Inno.Assets.Tests/AssetCoreTests.cs +++ b/tests/assets/Inno.Assets.Tests/AssetCoreTests.cs @@ -1,15 +1,13 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Collections.Generic; - +using Xunit; using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Execution; +using Inno.Extensibility.Types; using Inno.References; -using Xunit; - namespace Inno.Assets.Tests; public sealed class AssetCoreTests @@ -19,7 +17,8 @@ public void ReferenceBridgeDoesNotConvertAnUnfinishedRetirementIntoMissing() { IReferenceResolver resolver = new PendingResolver(); Assert.Throws(() => resolver.Resolve( - new ReferenceDescriptor(AssetReferenceProtocol.id, Guid.NewGuid(), Guid.Empty))); + new ReferenceDescriptor(AssetReferenceProtocol.id, Guid.NewGuid(), Guid.Empty) + )); } [Fact] @@ -131,21 +130,27 @@ public void AssetInfo_ExposesAnImmutableCatalogSnapshot() Guid.NewGuid(), new AssetArtifactKey(new string('A', 64)), new AssetArtifactKey(new string('B', 64)), - new[] { "diagnostic" }); + new[] { "diagnostic" } + ); Assert.Equal(id, info.persistentId); Assert.Equal(AssetSourceKind.File, info.sourceKind); Assert.Equal(AssetImportStatus.Imported, info.status); Assert.All( typeof(AssetInfo).GetProperties(BindingFlags.Instance | BindingFlags.Public), - static property => Assert.Null(property.SetMethod)); + static property => Assert.Null(property.SetMethod) + ); } private sealed class PendingResolver : IAssetReferenceResolver { - public AssetObject Resolve(Guid persistentId, Guid stableTypeId, string lastKnownPath, - Type expectedType, string propertyPath) - => throw new RetirementPendingException("The asset generation is still retiring."); + public AssetObject Resolve( + Guid persistentId, + Guid stableTypeId, + string lastKnownPath, + Type expectedType, + string propertyPath + ) => throw new RetirementPendingException("The asset generation is still retiring."); } [Fact] @@ -156,7 +161,8 @@ public void ChangeSet_PreservesMoveIdentityAndRevision() AssetChangeKind.Moved, id, AssetPath.Project("B/value.txt"), - AssetPath.Project("A/value.txt")); + AssetPath.Project("A/value.txt") + ); var set = new AssetChangeSet(42, new List { change }); Assert.Equal(42, set.revision); diff --git a/tests/assets/Inno.Assets.Tests/AssetExecutionContextTests.cs b/tests/assets/Inno.Assets.Tests/AssetExecutionContextTests.cs index eacf93d8b..d4f8d9276 100644 --- a/tests/assets/Inno.Assets.Tests/AssetExecutionContextTests.cs +++ b/tests/assets/Inno.Assets.Tests/AssetExecutionContextTests.cs @@ -1,9 +1,7 @@ using System; using System.Threading.Tasks; - -using Inno.Assets; - using Xunit; +using Inno.Assets; namespace Inno.Assets.Tests; @@ -30,7 +28,9 @@ public void NestedScopes_RestoreThePreviousLookup() { Assert.Same(outerAsset, Assets.Load(AssetPath.Project("value.txt"))); using (AssetExecutionContext.EnterScope(inner)) + { Assert.Same(innerAsset, Assets.Load(AssetPath.Project("value.txt"))); + } Assert.Same(outerAsset, Assets.Load(AssetPath.Project("value.txt"))); } } @@ -79,21 +79,25 @@ private sealed class FixedAssetLookup(AssetObject asset) : IAssetLookup { public TAsset Load(AssetPath path) where TAsset : AssetObject - => Cast(); + => Cast(); public TAsset Load(Guid persistentId) where TAsset : AssetObject - => Cast(); + => Cast(); - public bool TryLoad(AssetPath path, out TAsset? loadedAsset) - where TAsset : AssetObject + public bool TryLoad( + AssetPath path, + out TAsset? loadedAsset + ) where TAsset : AssetObject { loadedAsset = Cast(); return true; } - public bool TryLoad(Guid persistentId, out TAsset? loadedAsset) - where TAsset : AssetObject + public bool TryLoad( + Guid persistentId, + out TAsset? loadedAsset + ) where TAsset : AssetObject { loadedAsset = Cast(); return true; @@ -101,6 +105,6 @@ public bool TryLoad(Guid persistentId, out TAsset? loadedAsset) private TAsset Cast() where TAsset : AssetObject - => Assert.IsType(asset); + => Assert.IsType(asset); } } diff --git a/tests/assets/Inno.Assets.Tests/AssetResidencyTests.cs b/tests/assets/Inno.Assets.Tests/AssetResidencyTests.cs index c578cb95d..89b117031 100644 --- a/tests/assets/Inno.Assets.Tests/AssetResidencyTests.cs +++ b/tests/assets/Inno.Assets.Tests/AssetResidencyTests.cs @@ -3,9 +3,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; - -using Inno.Assets; using Xunit; +using Inno.Assets; namespace Inno.Assets.Tests; @@ -15,8 +14,7 @@ public sealed class AssetResidencyTests public async Task AssetLeaseRetainsCanonicalAssetAndReleasesExactlyOnce() { var provider = new FakeResidencyProvider(); - AssetLease lease = await provider.AcquireAsync( - AssetPath.Project("Text/readme.txt")); + AssetLease lease = await provider.AcquireAsync(AssetPath.Project("Text/readme.txt")); Assert.Same(provider.asset, lease.asset); lease.Dispose(); @@ -49,7 +47,9 @@ public void ArtifactLeaseReadsProviderBytesAndInvalidatesAfterRelease() var provider = new FakeResidencyProvider(path); ArtifactLease lease = provider.AcquireArtifact(Guid.NewGuid(), "runtime"); using (Stream stream = lease.OpenRead()) + { Assert.Equal(3, stream.Length); + } lease.Dispose(); @@ -79,30 +79,27 @@ internal FakeResidencyProvider(string artifactPath = "unused") public ValueTask> AcquireAsync( AssetPath path, - CancellationToken cancellationToken = default) - where TAsset : AssetObject + CancellationToken cancellationToken = default + ) where TAsset : AssetObject { cancellationToken.ThrowIfCancellationRequested(); - return ValueTask.FromResult(CreateAssetLease( - (TAsset)(AssetObject)asset, - () => assetReleaseCount++)); + return ValueTask.FromResult(CreateAssetLease((TAsset)(AssetObject)asset, () => assetReleaseCount++)); } public ValueTask> AcquireAsync( Guid persistentId, - CancellationToken cancellationToken = default) - where TAsset : AssetObject + CancellationToken cancellationToken = default + ) where TAsset : AssetObject => AcquireAsync(AssetPath.Project("Text/readme.txt"), cancellationToken); - public ArtifactLease AcquireArtifact(Guid persistentId, string outputName) - => CreateArtifactLease( - new AssetArtifactInfo( - new AssetArtifactKey(new string('A', 64)), - outputName, - "HASH", - 3), - () => File.OpenRead(m_artifactPath), - () => artifactReleaseCount++); + public ArtifactLease AcquireArtifact( + Guid persistentId, + string outputName + ) => CreateArtifactLease( + new AssetArtifactInfo(new AssetArtifactKey(new string('A', 64)), outputName, "HASH", 3), + () => File.OpenRead(m_artifactPath), + () => artifactReleaseCount++ + ); } private sealed class CallbackLease(Action callback) : IDisposable diff --git a/tests/assets/Inno.Assets.Tests/AssetRuntimeOwnerTests.cs b/tests/assets/Inno.Assets.Tests/AssetRuntimeOwnerTests.cs index 0526c672b..d26d2b794 100644 --- a/tests/assets/Inno.Assets.Tests/AssetRuntimeOwnerTests.cs +++ b/tests/assets/Inno.Assets.Tests/AssetRuntimeOwnerTests.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.IO; -using Inno.Assets; using Xunit; +using Inno.Assets; namespace Inno.Assets.Tests; @@ -30,7 +30,9 @@ public void FailedPayloadHookDoesNotPublishCandidateState() var asset = new TestAsset(); owner.Initialize(asset, AssetPath.Project("one.bin"), "one", new byte[] { 1 }, false, 1); asset.fail = true; - Assert.Throws(() => owner.Initialize(asset, AssetPath.Project("two.bin"), "two", new byte[] { 2 }, true, 2)); + Assert.Throws( + () => owner.Initialize(asset, AssetPath.Project("two.bin"), "two", new byte[] { 2 }, true, 2) + ); Assert.Equal(1, asset.contentVersion); Assert.False(asset.isMissing); Assert.Equal("one", owner.GetSourceHash(asset)); @@ -58,10 +60,14 @@ private sealed class TestAsset : AssetObject { internal bool fail; internal int unloadCount; - protected override void OnRuntimePayloadChanged(ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload) - { + + protected override void OnRuntimePayloadChanged( + ReadOnlyMemory previousPayload, + ReadOnlyMemory currentPayload + ) { if (fail) throw new InvalidOperationException("Rejected payload."); } + protected override void OnUnloading() => unloadCount++; } } diff --git a/tests/assets/Inno.Assets.Tests/AssetTypesTests.cs b/tests/assets/Inno.Assets.Tests/AssetTypesTests.cs index d9d7e44d0..a40f7b2be 100644 --- a/tests/assets/Inno.Assets.Tests/AssetTypesTests.cs +++ b/tests/assets/Inno.Assets.Tests/AssetTypesTests.cs @@ -1,6 +1,5 @@ -using Inno.Assets; - using Xunit; +using Inno.Assets; namespace Inno.Assets.Tests; diff --git a/tests/assets/Inno.Assets.Tests/ResidencyRetirementTests.cs b/tests/assets/Inno.Assets.Tests/ResidencyRetirementTests.cs index 2f4166584..abe6745a4 100644 --- a/tests/assets/Inno.Assets.Tests/ResidencyRetirementTests.cs +++ b/tests/assets/Inno.Assets.Tests/ResidencyRetirementTests.cs @@ -4,8 +4,8 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; -using Inno.Core.Execution; using Xunit; +using Inno.Core.Execution; namespace Inno.Assets.Tests; @@ -23,20 +23,34 @@ public void PendingLeaseRetainsItsValueAndCallbackUntilReleaseCompletes(bool art Action release = () => { if (++attempts == 1) + { throw new RetirementPendingException("Expected residency drain."); + } }; using IDisposable lease = artifact ? provider.Artifact(info, release) : provider.Asset(asset, release); Assert.Throws(lease.Dispose); - if (lease is ArtifactLease artifactLease) Assert.Same(info, artifactLease.info); - else Assert.Same(asset, ((AssetLease)lease).asset); + if (lease is ArtifactLease artifactLease) + { + Assert.Same(info, artifactLease.info); + } + else + { + Assert.Same(asset, ((AssetLease)lease).asset); + } lease.Dispose(); Assert.Equal(2, attempts); lease.Dispose(); Assert.Equal(2, attempts); Assert.Throws(() => { - if (lease is ArtifactLease releasedArtifact) _ = releasedArtifact.info; - else _ = ((AssetLease)lease).asset; + if (lease is ArtifactLease releasedArtifact) + { + _ = releasedArtifact.info; + } + else + { + _ = ((AssetLease)lease).asset; + } }); } @@ -47,7 +61,11 @@ public void OrdinaryReleaseFailureIsTerminalAndNeverInvokesTheCallbackTwice(bool { int attempts = 0; var provider = new TestProvider(); - Action release = () => { attempts++; throw new InvalidOperationException("Expected terminal release failure."); }; + Action release = () => + { + attempts++; + throw new InvalidOperationException("Expected terminal release failure."); + }; IDisposable lease = artifact ? provider.Artifact(Artifact(), release) : provider.Asset(new TextAsset(), release); Assert.Throws(lease.Dispose); lease.Dispose(); @@ -64,12 +82,21 @@ public void WrappedPendingRetainsTheLeaseAndReportsOrdinarySiblingsAfterCompleti var asset = new TextAsset(); var ordinary = new InvalidOperationException("completed sibling"); var pending = new AggregateException(ordinary, new RetirementPendingException("unfinished callback")); - Action release = () => { if (++attempts < 3) throw pending; }; + Action release = () => + { + if (++attempts < 3) throw pending; + }; IDisposable lease = artifact ? provider.Artifact(Artifact(), release) : provider.Asset(asset, release); Assert.Same(pending, Assert.Throws(lease.Dispose)); Assert.Same(pending, Assert.Throws(lease.Dispose)); - if (lease is ArtifactLease artifactLease) Assert.NotNull(artifactLease.info); - else Assert.Same(asset, ((AssetLease)lease).asset); + if (lease is ArtifactLease artifactLease) + { + Assert.NotNull(artifactLease.info); + } + else + { + Assert.Same(asset, ((AssetLease)lease).asset); + } AggregateException completed = Assert.Throws(lease.Dispose); Assert.Same(ordinary, Assert.Single(completed.InnerExceptions)); lease.Dispose(); @@ -92,7 +119,8 @@ public async Task ConcurrentReleaseCannotReportCompletionWhileTheProviderIsStill lease.Dispose, CancellationToken.None, TaskCreationOptions.LongRunning, - TaskScheduler.Default); + TaskScheduler.Default + ); try { Assert.True(started.Wait(TimeSpan.FromSeconds(30))); @@ -100,7 +128,11 @@ public async Task ConcurrentReleaseCannotReportCompletionWhileTheProviderIsStill Assert.NotNull(lease.info); Assert.Equal(1, attempts); } - finally { finish.Set(); await worker; } + finally + { + finish.Set(); + await worker; + } lease.Dispose(); Assert.Equal(1, attempts); Assert.Throws(() => _ = lease.info); @@ -113,16 +145,24 @@ public void RetentionScopePreservesLifoDependenciesAndEarlierFailuresAcrossPendi int pendingAttempts = 0; var scope = new RetentionScope(); scope.Retain(new ReleaseStep(() => order.Add("dependency"))); - scope.Retain(new ReleaseStep(() => - { - order.Add("pending"); - if (++pendingAttempts == 1) throw new RetirementPendingException("Expected owner drain."); - })); - scope.Retain(new ReleaseStep(() => { order.Add("failure"); throw new InvalidOperationException("Expected release failure."); })); + scope.Retain( + new ReleaseStep(() => + { + order.Add("pending"); + if (++pendingAttempts == 1) throw new RetirementPendingException("Expected owner drain."); + }) + ); + scope.Retain( + new ReleaseStep(() => + { + order.Add("failure"); + throw new InvalidOperationException("Expected release failure."); + }) + ); Assert.Throws(scope.Dispose); Assert.Equal(new[] { "failure", "pending" }, order); - Assert.Throws(() => scope.Retain(new ReleaseStep(() => { }))); + Assert.Throws(() => scope.Retain(new ReleaseStep(() => {}))); AggregateException failure = Assert.Throws(scope.Dispose); Assert.Contains(failure.InnerExceptions, exception => exception.Message == "Expected release failure."); Assert.Equal(new[] { "failure", "pending", "pending", "dependency" }, order); @@ -166,7 +206,11 @@ private static void Collect() private sealed class TestProvider : AssetResidencyProvider { - internal AssetLease Asset(TextAsset asset, Action release) => CreateAssetLease(asset, release); + internal AssetLease Asset( + TextAsset asset, + Action release + ) => CreateAssetLease(asset, release); + internal ArtifactLease Artifact( AssetArtifactInfo info, Action release diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs index 9130f3554..06a112380 100644 --- a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs +++ b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Extensibility.Types; @@ -35,8 +34,8 @@ public sealed class DuplicateImporterA : AssetImporter protected override ValueTask ImportAsync( AssetImportContext context, AssetImportWriter output, - CancellationToken cancellationToken) - { + CancellationToken cancellationToken + ) { output.SetAsset(new DuplicateImporterAsset()); return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); } @@ -63,8 +62,8 @@ public sealed class DuplicateImporterB : AssetImporter protected override ValueTask ImportAsync( AssetImportContext context, AssetImportWriter output, - CancellationToken cancellationToken) - { + CancellationToken cancellationToken + ) { output.SetAsset(new DuplicateImporterAsset()); return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); } diff --git a/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs b/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs index 3f28ba053..c35a6d8d8 100644 --- a/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs +++ b/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs @@ -1,9 +1,10 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Buffers.Binary; using System.IO; using System.Reflection; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Diagnostics; @@ -12,7 +13,6 @@ using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Audio.Assets.Tests; @@ -37,7 +37,9 @@ public AudioClipImporterTests() Directory.CreateDirectory(m_assets); m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(AudioClipImporterTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(AudioClipImporterTests).Assembly) + }); _ = Assembly.Load("Inno.Audio.Assets"); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); @@ -52,7 +54,9 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -92,11 +96,16 @@ public void CorruptEncodedSourceFailsWithoutCommittingAnAsset() private AssetLoader CreateLoader() => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, m_assets, m_library); - private static AudioClipAsset Load(AssetLoader loader, string path) - => Assert.IsType(loader.Load(AssetPath.Project(path), typeof(AudioClipAsset))); + private static AudioClipAsset Load( + AssetLoader loader, + string path + ) => Assert.IsType(loader.Load(AssetPath.Project(path), typeof(AudioClipAsset))); - private static void AssertSeparateArtifact(AssetLoader loader, AudioClipAsset asset, byte[] expected) - { + private static void AssertSeparateArtifact( + AssetLoader loader, + AudioClipAsset asset, + byte[] expected + ) { Assert.True(loader.TryGetArtifact(asset.identity.persistentId, "runtime", out AssetArtifactInfo? runtime)); Assert.True(loader.TryGetArtifact(asset.identity.persistentId, "audio-data", out AssetArtifactInfo? data)); Assert.NotNull(runtime); @@ -107,7 +116,10 @@ private static void AssertSeparateArtifact(AssetLoader loader, AudioClipAsset as Assert.Equal(expected, encoded.ReadAllBytes()); } - private void Write(string path, byte[] bytes) => File.WriteAllBytes(Path.Combine(m_assets, path), bytes); + private void Write( + string path, + byte[] bytes + ) => File.WriteAllBytes(Path.Combine(m_assets, path), bytes); private static byte[] CreateWav() { diff --git a/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs b/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs index b38927514..96e3da04a 100644 --- a/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs +++ b/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs @@ -1,21 +1,21 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; -using Inno.Core.Diagnostics; -using System.Threading.Tasks; using System.Threading; +using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Assets; using Inno.Audio.Runtime; +using Inno.Core.Diagnostics; using Inno.Core.Events; using Inno.Core.Execution; using Inno.Core.Identity; -using Inno.References; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; +using Inno.References; namespace Inno.Audio.Runtime.Tests; @@ -131,8 +131,14 @@ public void AdmissionRetryAfterCompletionBackpressureReleasesCandidateLeaseAndSt var events = new EventDispatcher(queueCapacity: 1); var device = new ReadyAudioDevice(); using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.admission", "Admission")); - using var runtime = new AudioRuntime(m_types, device, m_artifacts, events, reporter, - new AudioRuntimeOptions { maxVoices = 1 }); + using var runtime = new AudioRuntime( + m_types, + device, + m_artifacts, + events, + reporter, + new AudioRuntimeOptions { maxVoices = 1 } + ); using EventHub hub = events.CreateHub(); var completions = new List(); hub.Listen(completions.Add); @@ -196,12 +202,19 @@ public void MutedBackendRejectsInvalidValuesWithTheSameAdmissionPolicy() AudioClipAsset asset = CreateClip(48000); using ArtifactLease artifact = m_artifacts.AcquireArtifact(asset.identity.persistentId, "audio-data"); AudioBusHandle master = backend.CreateBus(AudioBusId.master); - AudioClipHandle clip = backend.CreateClip(new AudioClipDescriptor( AudioCodecId.wav, AudioClipLoadMode.Decode, 2, 48000, 48000, artifact.info.length),new LeaseAudioTestSource(artifact)); + AudioClipHandle clip = backend.CreateClip( + new AudioClipDescriptor( AudioCodecId.wav, AudioClipLoadMode.Decode, 2, 48000, 48000, artifact.info.length), + new LeaseAudioTestSource(artifact) + ); Assert.False(backend.Play(clip, master, default).isValid); foreach (double invalid in new[] { double.NaN, double.PositiveInfinity, double.NegativeInfinity, -1d }) + { Assert.False(backend.Play(clip, master, AudioPlayOptions.defaultValue, invalid).isValid); + } foreach (float invalid in new[] { float.NaN, float.PositiveInfinity, float.NegativeInfinity }) + { Assert.False(backend.SetBusVolume(master, invalid)); + } Assert.Equal(0, backend.statistics.activeVoices); AudioDeviceVoiceHandle voice = backend.Play(clip, master, AudioPlayOptions.defaultValue); Assert.False(backend.SetVoiceParameters(voice, default)); @@ -226,14 +239,24 @@ public void ProviderFailureDiscardsItsEntireContributionAndReleasesItsIdentities context.Submit(listener); throw new InvalidOperationException("Expected partial provider failure."); }; - content.second = context => { context.Submit(emitter); context.Submit(listener); }; + content.second = context => + { + context.Submit(emitter); + context.Submit(listener); + }; var diagnostics = new DiagnosticHub(); var sink = new RecordingSink(); diagnostics.RegisterSink(sink); using var reporter = diagnostics.CreateReporter(new DiagnosticSource("test.content", "Content")); var device = new ReadyAudioDevice(); - using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter, - contentScopeProvider: () => new ContentReadScope([content.identity])); + using var runtime = new AudioRuntime( + m_types, + device, + m_artifacts, + m_events, + reporter, + contentScopeProvider: () => new ContentReadScope([content.identity]) + ); runtime.Update(0); Assert.Equal(new AudioContentStatistics(1024, 2, 1), runtime.contentStatistics); @@ -256,11 +279,21 @@ public void CrossProviderDuplicateRejectsTheWholeBatchWithoutClaimingOtherIdenti var first = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); var second = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); content.first = context => context.Submit(first); - content.second = context => { context.Submit(second); context.Submit(first); }; + content.second = context => + { + context.Submit(second); + context.Submit(first); + }; content.third = context => context.Submit(second); using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.duplicate", "Duplicate")); - using var runtime = new AudioRuntime(m_types, new ReadyAudioDevice(), m_artifacts, m_events, reporter, - contentScopeProvider: () => new ContentReadScope([content.identity])); + using var runtime = new AudioRuntime( + m_types, + new ReadyAudioDevice(), + m_artifacts, + m_events, + reporter, + contentScopeProvider: () => new ContentReadScope([content.identity]) + ); runtime.Update(0); Assert.Equal(new AudioContentStatistics(1024, 2, 1), runtime.contentStatistics); @@ -281,14 +314,24 @@ public void RepeatedOverflowIsBoundedAndCannotBeHiddenByAProviderCatch() content.second = context => { context.Submit(overflow); - try { context.Submit(last); } + try + { + context.Submit(last); + } catch (InvalidOperationException) { } }; content.third = context => context.Submit(last); using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.capacity", "Capacity")); var options = new AudioRuntimeOptions { maxContentSnapshots = 2 }; - using var runtime = new AudioRuntime(m_types, new ReadyAudioDevice(), m_artifacts, m_events, reporter, - options, () => new ContentReadScope([content.identity])); + using var runtime = new AudioRuntime( + m_types, + new ReadyAudioDevice(), + m_artifacts, + m_events, + reporter, + options, + () => new ContentReadScope([content.identity]) + ); options.maxContentSnapshots = 100; for (int frame = 0; frame < 256; frame++) @@ -312,10 +355,20 @@ public void ProviderContextAndContentLookupAreRevokedAfterTheUpdate() identities.Register(content); AudioContentProviderContext? captured = null; ContentReadScope? capturedScope = null; - content.first = context => { captured = context; capturedScope = context.content; }; + content.first = context => + { + captured = context; + capturedScope = context.content; + }; using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.scope", "Scope")); - using var runtime = new AudioRuntime(m_types, new ReadyAudioDevice(), m_artifacts, m_events, reporter, - contentScopeProvider: () => new ContentReadScope([content.identity])); + using var runtime = new AudioRuntime( + m_types, + new ReadyAudioDevice(), + m_artifacts, + m_events, + reporter, + contentScopeProvider: () => new ContentReadScope([content.identity]) + ); runtime.Update(0); Assert.NotNull(captured); Assert.Throws(() => captured!.Submit(default(AudioListenerSnapshot))); @@ -338,8 +391,14 @@ public void ProviderRetirementPendingIsNotConvertedToARejectedContribution() }; content.second = _ => nextInvoked = true; using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.pending-content", "Pending")); - using var runtime = new AudioRuntime(m_types, new ReadyAudioDevice(), m_artifacts, m_events, reporter, - contentScopeProvider: () => new ContentReadScope([content.identity])); + using var runtime = new AudioRuntime( + m_types, + new ReadyAudioDevice(), + m_artifacts, + m_events, + reporter, + contentScopeProvider: () => new ContentReadScope([content.identity]) + ); Assert.Throws(() => runtime.Update(0)); Assert.False(nextInvoked); Assert.Equal(0, runtime.contentStatistics.rejectedProviders); @@ -369,7 +428,9 @@ private sealed class FirstContentProvider : AudioContentProvider public override void Submit(AudioContentProviderContext context) { foreach (TestAudioContent content in context.content.GetValues()) + { content.first?.Invoke(context); + } } } @@ -379,7 +440,9 @@ private sealed class SecondContentProvider : AudioContentProvider public override void Submit(AudioContentProviderContext context) { foreach (TestAudioContent content in context.content.GetValues()) + { content.second?.Invoke(context); + } } } @@ -389,7 +452,9 @@ private sealed class ThirdContentProvider : AudioContentProvider public override void Submit(AudioContentProviderContext context) { foreach (TestAudioContent content in context.content.GetValues()) + { content.third?.Invoke(context); + } } } @@ -408,7 +473,9 @@ public async Task PendingClipRetirementPreservesDeviceAndRetriesExactlyOnce(bool runtime.Update(0); } else + { await runtime.PreloadAsync(clip); + } device.pendingClipRetirements = 1; Assert.Throws(runtime.Dispose); @@ -468,7 +535,10 @@ public void PendingProviderIsRetriedBeforeItsGenerationIsReleased() Assert.Equal(2, RetirementProviderFirst.disposals); Assert.NotEqual("Faulted", m_modules.generations.state.ToString()); } - finally { RetirementProviderFirst.pendingRetirements = 0; } + finally + { + RetirementProviderFirst.pendingRetirements = 0; + } } [Fact] @@ -577,7 +647,10 @@ public void ProviderRetirementAttemptsEveryInstanceAndFaultsSharedGeneration() Assert.Equal(1, RetirementProviderSecond.disposals); Assert.Equal("Faulted", m_modules.generations.state.ToString()); } - finally { RetirementProviderFirst.fail = false; } + finally + { + RetirementProviderFirst.fail = false; + } } [AudioContentProviderExtension("tests.retirement.first", -100)] @@ -586,14 +659,20 @@ private sealed class RetirementProviderFirst : AudioContentProvider internal static bool fail; internal static int disposals; internal static int pendingRetirements; - public override void Submit(AudioContentProviderContext context) { } + + public override void Submit(AudioContentProviderContext context) {} + protected override void Dispose(bool disposing) { disposals++; if (pendingRetirements-- > 0) + { throw new RetirementPendingException("Expected provider drain."); + } if (fail) + { throw new InvalidOperationException("Expected provider retirement failure."); + } } } @@ -602,12 +681,17 @@ private sealed class RetirementProviderSecond : AudioContentProvider { internal static bool failConstruction; internal static int disposals; + public RetirementProviderSecond() { if (failConstruction) + { throw new InvalidOperationException("Expected provider candidate failure."); + } } - public override void Submit(AudioContentProviderContext context) { } + + public override void Submit(AudioContentProviderContext context) {} + protected override void Dispose(bool disposing) => disposals++; } @@ -630,7 +714,9 @@ public void RecoveredMixerResolvesItsPreviousMissingDiagnostic() private sealed class RecordingSink : IDiagnosticSink { internal IReadOnlyList issues { get; private set; } = []; + public void Replace(DiagnosticReport report) => issues = report.diagnostics; + public void Clear(DiagnosticSource source) => issues = []; } @@ -645,7 +731,9 @@ public AudioRuntimeTests() m_root = Path.Combine(Path.GetTempPath(), "InnoAudioRuntimeTests", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(m_root); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(AudioRuntimeTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(AudioRuntimeTests).Assembly) + }); _ = typeof(TestMixerExtension); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_types.Rebuild(); @@ -656,7 +744,9 @@ public void Dispose() m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -689,10 +779,7 @@ public void ScheduledLoopingVoiceSupportsPauseResumeAndSeek() { AudioClipAsset clip = CreateClip(frameCount: 4800); using var runtime = CreateRuntime(); - AudioVoiceHandle voice = runtime.PlayScheduled( - clip, - 1d, - new AudioPlayOptions(loop: true)); + AudioVoiceHandle voice = runtime.PlayScheduled(clip, 1d, new AudioPlayOptions(loop: true)); runtime.Update(0.1f); Assert.True(runtime.TryGetVoiceState(voice, out AudioPlaybackState scheduled)); @@ -753,7 +840,8 @@ public async Task AutomaticPreparationStreamsWhenDecodedFootprintExceedsBudget() AudioClipAsset clip = CreateClip(frameCount: 4800); using var runtime = CreateRuntime( decodedCacheBudgetBytes: 1024, - automaticStreamingThresholdBytes: long.MaxValue); + automaticStreamingThresholdBytes: long.MaxValue + ); await runtime.PreloadAsync(clip); @@ -815,8 +903,13 @@ public void RecoveryCandidatePreservesTheLastGoodMixerGraph() public async Task PreloadCompletesOnlyAfterPreparationAndCancellationReleasesReservation() { var device = new ReadyAudioDevice { clipState = AudioClipState.Preparing }; - using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, - new Inno.Core.Diagnostics.DiagnosticHub().CreateReporter(new Inno.Core.Diagnostics.DiagnosticSource("test.preload", "Preload"))); + using var runtime = new AudioRuntime( + m_types, + device, + m_artifacts, + m_events, + new Inno.Core.Diagnostics.DiagnosticHub().CreateReporter(new Inno.Core.Diagnostics.DiagnosticSource("test.preload", "Preload")) + ); AudioClipAsset clip = CreateClip(4800); ValueTask ready = runtime.PreloadAsync(clip); Assert.False(ready.IsCompleted); @@ -852,13 +945,19 @@ public async Task PreloadedArtifactRetirementResumesWithoutDestroyingTheNativeCl Assert.Single(m_artifacts.retainedKeys); Assert.Equal(0, device.disposals); if (shutdown) + { runtime.Dispose(); + } else + { runtime.Update(0); + } Assert.Equal(1, device.clipRetirements); Assert.Empty(m_artifacts.retainedKeys); if (!shutdown) + { Assert.Equal(0, runtime.statistics.loadedClips); + } } [Fact] @@ -946,18 +1045,26 @@ public async Task RetryingPreloadReleaseDoesNotConsumeAnotherLoadModeReservation [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] - public async Task FailedPreloadAdmissionRetiresOnlyItsOwnReservation(bool cached, bool queryThrows) - { + public async Task FailedPreloadAdmissionRetiresOnlyItsOwnReservation( + bool cached, + bool queryThrows + ) { var device = new ReadyAudioDevice(); using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.query", "Query")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); if (cached) + { await runtime.PreloadAsync(clip); + } if (queryThrows) + { device.clipQueryFailure = new InvalidOperationException("Expected clip query failure."); + } else + { device.clipState = AudioClipState.Failed; + } m_artifacts.pendingReleaseId = clip.identity.persistentId; m_artifacts.pendingReleases = 1; InvalidOperationException failure = Assert.Throws(() => runtime.PreloadAsync(clip)); @@ -1004,36 +1111,35 @@ public void PreloadQueryAndRollbackFailureRetainBothDiagnosticsAndFaultTheGenera private AudioRuntime CreateRuntime( int maxVoices = 128, long decodedCacheBudgetBytes = 128L * 1024 * 1024, - long automaticStreamingThresholdBytes = 1024) - => new( - m_types, - new MutedAudioDevice(), - m_artifacts, - m_events, - new Inno.Core.Diagnostics.DiagnosticHub().CreateReporter(new Inno.Core.Diagnostics.DiagnosticSource("tests.audio", "Audio")), - options: new AudioRuntimeOptions - { - maxVoices = maxVoices, - decodedCacheBudgetBytes = decodedCacheBudgetBytes, - automaticStreamingThresholdBytes = automaticStreamingThresholdBytes - }); + long automaticStreamingThresholdBytes = 1024 + ) => new( + m_types, + new MutedAudioDevice(), + m_artifacts, + m_events, + new Inno.Core.Diagnostics.DiagnosticHub().CreateReporter(new Inno.Core.Diagnostics.DiagnosticSource("tests.audio", "Audio")), + options: new AudioRuntimeOptions + { + maxVoices = maxVoices, + decodedCacheBudgetBytes = decodedCacheBudgetBytes, + automaticStreamingThresholdBytes = automaticStreamingThresholdBytes + } + ); private AudioClipAsset CreateClip(long frameCount) { var clip = new AudioClipAsset(); - byte[] payload = AudioClipMetadataCodec.Encode(new AudioClipMetadata( - AudioCodecId.wav, - 2, - 48000, - frameCount, - 256)); + byte[] payload = AudioClipMetadataCodec.Encode( + new AudioClipMetadata(AudioCodecId.wav, 2, 48000, frameCount, 256) + ); new AssetRuntimeOwner().Initialize( clip, AssetPath.Project($"Audio/{clip.identity.persistentId:N}.wav"), "TEST", payload, isMissing: false, - version: 1); + version: 1 + ); m_artifacts.Add(clip.identity.persistentId, Path.Combine(m_root, $"{clip.identity.persistentId:N}.wav")); return clip; } @@ -1041,12 +1147,15 @@ private AudioClipAsset CreateClip(long frameCount) [AudioMixerExtension("tests.audio.mixer")] private sealed class TestMixerExtension : AudioMixerExtension { - public override void Build(AudioMixerBuilder builder, SerializedAudioExtensionState state) - { + public override void Build( + AudioMixerBuilder builder, + SerializedAudioExtensionState state + ) { builder.AddBus(new AudioBusId("tests.audio.bus.music"), AudioBusId.master); builder.AddProcessor( new AudioBusId("tests.audio.bus.music"), - new AudioProcessorConfiguration(AudioProcessorId.lowPass)); + new AudioProcessorConfiguration(AudioProcessorId.lowPass) + ); } } @@ -1061,24 +1170,35 @@ private sealed class FakeArtifactLookup : AssetResidencyProvider, IAssetArtifact internal int pendingReleases; internal int releaseAttempts; internal IReadOnlyList retainedKeys => m_retention.GetRetainedKeys(); - public ArtifactLease AcquireArtifact(Guid persistentId, string outputName) - { + + public ArtifactLease AcquireArtifact( + Guid persistentId, + string outputName + ) { acquisitions++; if (acquisitionFailure is not null) + { throw acquisitionFailure; - ArtifactLease retained = m_retention.Retain(m_artifacts[persistentId], - () => File.OpenRead(m_paths[persistentId])); + } + ArtifactLease retained = m_retention.Retain( + m_artifacts[persistentId], + () => File.OpenRead(m_paths[persistentId]) + ); return CreateArtifactLease(retained.info, retained.OpenRead, () => { releaseAttempts++; if (persistentId == pendingReleaseId && pendingReleases-- > 0) + { throw new RetirementPendingException("Expected admitted artifact drain."); + } retained.Dispose(); }); } - internal void Add(Guid id, string path) - { + internal void Add( + Guid id, + string path + ) { byte[] bytes = new byte[256]; File.WriteAllBytes(path, bytes); m_paths[id] = path; @@ -1086,11 +1206,15 @@ internal void Add(Guid id, string path) new AssetArtifactKey(new string('A', 64)), "audio-data", Convert.ToHexString(SHA256.HashData(bytes)), - 256); + 256 + ); } - public bool TryGetArtifact(Guid persistentId, string outputName, out AssetArtifactInfo? artifact) - { + public bool TryGetArtifact( + Guid persistentId, + string outputName, + out AssetArtifactInfo? artifact + ) { if (outputName == "audio-data" && m_artifacts.TryGetValue(persistentId, out AssetArtifactInfo? found)) { artifact = found; @@ -1135,11 +1259,15 @@ public AudioClipHandle CreateClip( AudioClipDescriptor descriptor, IAudioClipSource source ) => m_inner.CreateClip(descriptor, source); + internal AudioClipState clipState = AudioClipState.Ready; + public AudioClipState GetClipState(AudioClipHandle clip) { if (clipQueryFailure is not null) + { throw clipQueryFailure; + } return clipState; } @@ -1147,9 +1275,13 @@ public bool DestroyClip(AudioClipHandle clip) { clipRetirements++; if (pendingClipRetirements-- > 0) + { throw new RetirementPendingException("Expected clip drain."); + } if (failClipRetirement) + { throw new InvalidOperationException("Expected clip retirement failure."); + } return m_inner.DestroyClip(clip); } @@ -1157,8 +1289,8 @@ public AudioDeviceVoiceHandle Play( AudioClipHandle clip, AudioBusHandle bus, AudioPlayOptions options, - double? scheduledDspTime = null) - => m_inner.Play(clip, bus, options, scheduledDspTime); + double? scheduledDspTime = null + ) => m_inner.Play(clip, bus, options, scheduledDspTime); public bool Stop(AudioDeviceVoiceHandle voice) { @@ -1170,16 +1302,25 @@ public bool Stop(AudioDeviceVoiceHandle voice) public bool Resume(AudioDeviceVoiceHandle voice) => m_inner.Resume(voice); - public bool Seek(AudioDeviceVoiceHandle voice, TimeSpan position) => m_inner.Seek(voice, position); - - public bool SetVoiceParameters(AudioDeviceVoiceHandle voice, AudioVoiceParameters parameters) - => m_inner.SetVoiceParameters(voice, parameters); - - public bool TryGetVoiceState(AudioDeviceVoiceHandle voice, out AudioPlaybackState playbackState) - => m_inner.TryGetVoiceState(voice, out playbackState); - - public AudioBusHandle CreateBus(AudioBusId id, AudioBusHandle parent = default) - { + public bool Seek( + AudioDeviceVoiceHandle voice, + TimeSpan position + ) => m_inner.Seek(voice, position); + + public bool SetVoiceParameters( + AudioDeviceVoiceHandle voice, + AudioVoiceParameters parameters + ) => m_inner.SetVoiceParameters(voice, parameters); + + public bool TryGetVoiceState( + AudioDeviceVoiceHandle voice, + out AudioPlaybackState playbackState + ) => m_inner.TryGetVoiceState(voice, out playbackState); + + public AudioBusHandle CreateBus( + AudioBusId id, + AudioBusHandle parent = default + ) { AudioBusHandle handle = m_inner.CreateBus(id, parent); if (handle.isValid) { @@ -1193,36 +1334,55 @@ public bool DestroyBus(AudioBusHandle bus) { busRetirements++; if (pendingBusRetirements-- > 0) + { throw new RetirementPendingException("Expected bus drain."); + } bool destroyed = m_inner.DestroyBus(bus); if (destroyed) + { m_pausedHandles.Remove(bus); + } return destroyed; } - public bool SetBusVolume(AudioBusHandle bus, float volume) - { + public bool SetBusVolume( + AudioBusHandle bus, + float volume + ) { if (!m_inner.SetBusVolume(bus, volume)) + { return false; + } m_busVolumes[m_busIds[bus]] = volume; return true; } - public bool SetBusMuted(AudioBusHandle bus, bool muted) => m_inner.SetBusMuted(bus, muted); + public bool SetBusMuted( + AudioBusHandle bus, + bool muted + ) => m_inner.SetBusMuted(bus, muted); - public bool SetBusPaused(AudioBusHandle bus, bool paused) - { + public bool SetBusPaused( + AudioBusHandle bus, + bool paused + ) { if (++busPauseCalls == failBusPauseAt) + { return false; + } if (!m_inner.SetBusPaused(bus, paused)) + { return false; + } m_busPaused[m_busIds[bus]] = paused; m_pausedHandles[bus] = paused; return true; } - public bool AddBusProcessor(AudioBusHandle bus, AudioProcessorConfiguration processor) - => m_inner.AddBusProcessor(bus, processor); + public bool AddBusProcessor( + AudioBusHandle bus, + AudioProcessorConfiguration processor + ) => m_inner.AddBusProcessor(bus, processor); public AudioListenerHandle CreateListener(AudioListenerState state) { @@ -1230,8 +1390,10 @@ public AudioListenerHandle CreateListener(AudioListenerState state) return m_inner.CreateListener(state); } - public bool SetListener(AudioListenerHandle listener, AudioListenerState state) - => m_inner.SetListener(listener, state); + public bool SetListener( + AudioListenerHandle listener, + AudioListenerState state + ) => m_inner.SetListener(listener, state); public bool DestroyListener(AudioListenerHandle listener) => m_inner.DestroyListener(listener); @@ -1245,14 +1407,18 @@ public void Dispose() disposals++; m_inner.Dispose(); if (failDisposal) + { throw new InvalidOperationException("Expected device retirement failure."); + } } internal float GetBusVolume(AudioBusId id) => m_busVolumes[id]; internal bool GetBusPaused(AudioBusId id) => m_busPaused[id]; + internal IReadOnlyList GetMasterPauses() => m_pausedHandles.Where(pair => m_busIds[pair.Key] == AudioBusId.master) - .Select(pair => pair.Value).ToArray(); + .Select(pair => pair.Value) + .ToArray(); } } diff --git a/tests/audio/Inno.Audio.Runtime.Tests/LeaseAudioTestSource.cs b/tests/audio/Inno.Audio.Runtime.Tests/LeaseAudioTestSource.cs index 2def5d2e6..3912ac7d3 100644 --- a/tests/audio/Inno.Audio.Runtime.Tests/LeaseAudioTestSource.cs +++ b/tests/audio/Inno.Audio.Runtime.Tests/LeaseAudioTestSource.cs @@ -7,5 +7,6 @@ internal sealed class LeaseAudioTestSource(ArtifactLease artifact) : IAudioClipS { public string contentHash => artifact.info.contentHash; public long length => artifact.info.length; + public Stream OpenRead() => artifact.OpenRead(); } diff --git a/tests/audio/Inno.Audio.Tests/AudioContentContractTests.cs b/tests/audio/Inno.Audio.Tests/AudioContentContractTests.cs index bdd63e501..afa63be37 100644 --- a/tests/audio/Inno.Audio.Tests/AudioContentContractTests.cs +++ b/tests/audio/Inno.Audio.Tests/AudioContentContractTests.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; -using Inno.References; using Xunit; +using Inno.References; namespace Inno.Audio.Tests; @@ -39,9 +39,13 @@ public void DefaultSnapshotsPoisonTheContribution(bool emitter) using ContentReadScope content = ContentReadScope.empty; using var context = new AudioContentProviderContext(content, 0); if (emitter) + { Assert.Throws(() => context.Submit(default(AudioEmitterSnapshot))); + } else + { Assert.Throws(() => context.Submit(default(AudioListenerSnapshot))); + } Assert.Throws(() => _ = context.listeners); } diff --git a/tests/audio/Inno.Audio.Tests/AudioContractTests.cs b/tests/audio/Inno.Audio.Tests/AudioContractTests.cs index 02a07f319..4a3cfdcc3 100644 --- a/tests/audio/Inno.Audio.Tests/AudioContractTests.cs +++ b/tests/audio/Inno.Audio.Tests/AudioContractTests.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Inno.Audio; using Xunit; +using Inno.Audio; namespace Inno.Audio.Tests; @@ -37,12 +37,16 @@ public void MixerBuilder_ProducesParentBeforeChildGraphWithMasterBus() music, new AudioProcessorConfiguration( AudioProcessorId.lowPass, - [new AudioProcessorParameter(new AudioParameterId("frequency"), 12000f)])); + [new AudioProcessorParameter(new AudioParameterId("frequency"), 12000f)] + ) + ); AudioMixer mixer = builder.Build(); - Assert.Equal([AudioBusId.master, music, ambience], - System.Linq.Enumerable.Select(mixer.buses, static bus => bus.id)); + Assert.Equal( + [AudioBusId.master, music, ambience], + System.Linq.Enumerable.Select(mixer.buses, static bus => bus.id) + ); Assert.Single(mixer.buses[1].processors); } @@ -110,14 +114,16 @@ public AudioVoiceHandle Play(AudioClipAsset clip) return CreateTestVoice(); } - public AudioVoiceHandle Play(AudioClipAsset clip, AudioPlayOptions options) - => Play(clip); + public AudioVoiceHandle Play( + AudioClipAsset clip, + AudioPlayOptions options + ) => Play(clip); public AudioVoiceHandle PlayScheduled( AudioClipAsset clip, double scheduledDspTime, - AudioPlayOptions options) - => Play(clip); + AudioPlayOptions options + ) => Play(clip); public bool Stop(AudioVoiceHandle voice) => Owns(voice); @@ -125,27 +131,44 @@ public AudioVoiceHandle PlayScheduled( public bool Resume(AudioVoiceHandle voice) => Owns(voice); - public bool Seek(AudioVoiceHandle voice, TimeSpan position) => Owns(voice) && position >= TimeSpan.Zero; + public bool Seek( + AudioVoiceHandle voice, + TimeSpan position + ) => Owns(voice) && position >= TimeSpan.Zero; - public bool SetVoiceParameters(AudioVoiceHandle voice, AudioVoiceParameters parameters) => Owns(voice); + public bool SetVoiceParameters( + AudioVoiceHandle voice, + AudioVoiceParameters parameters + ) => Owns(voice); - public bool TryGetVoiceState(AudioVoiceHandle voice, out AudioPlaybackState playbackState) - { + public bool TryGetVoiceState( + AudioVoiceHandle voice, + out AudioPlaybackState playbackState + ) { playbackState = Owns(voice) ? AudioPlaybackState.Playing : AudioPlaybackState.Invalid; return playbackState != AudioPlaybackState.Invalid; } - public bool SetBusVolume(AudioBusId bus, float volume) => bus.isValid && volume >= 0f; + public bool SetBusVolume( + AudioBusId bus, + float volume + ) => bus.isValid && volume >= 0f; - public bool SetBusMuted(AudioBusId bus, bool muted) => bus.isValid; + public bool SetBusMuted( + AudioBusId bus, + bool muted + ) => bus.isValid; - public bool SetBusPaused(AudioBusId bus, bool paused) => bus.isValid; + public bool SetBusPaused( + AudioBusId bus, + bool paused + ) => bus.isValid; public ValueTask PreloadAsync( AudioClipAsset clip, AudioClipLoadMode loadMode = AudioClipLoadMode.Automatic, - CancellationToken cancellationToken = default) - { + CancellationToken cancellationToken = default + ) { ArgumentNullException.ThrowIfNull(clip); cancellationToken.ThrowIfCancellationRequested(); return ValueTask.CompletedTask; diff --git a/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs b/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs index f4c64dedc..ccd2312c4 100644 --- a/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs +++ b/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs @@ -1,20 +1,20 @@ -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using Inno.Assets; using System.IO; using System.Linq; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Audio.Runtime; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Settings; using Inno.Plugins; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scripting.Compiler; -using Xunit; namespace Inno.Audio.Tests; @@ -23,10 +23,7 @@ public sealed class AudioScriptingApiTests [Fact] public async Task FacadeMixerProviderAndSceneComponentsCompileThroughLogicalNamespace() { - string projectRoot = Path.Combine( - Path.GetTempPath(), - "InnoAudioScriptingTests", - Guid.NewGuid().ToString("N")); + string projectRoot = Path.Combine(Path.GetTempPath(), "InnoAudioScriptingTests", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(Path.Combine(projectRoot, "Assets")); Directory.CreateDirectory(Path.Combine(projectRoot, "Plugins")); Directory.CreateDirectory(Path.Combine(projectRoot, "Library")); @@ -37,13 +34,17 @@ public async Task FacadeMixerProviderAndSceneComponentsCompileThroughLogicalName var identities = new IdentityAllocator(); using IDisposable identityScope = identities.EnterScope(); using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(AudioScriptingApiTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(AudioScriptingApiTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); var pluginSources = new PluginSourceService( host.serialization, Path.Combine(projectRoot, "Plugins"), - Path.Combine(projectRoot, "Library")); + Path.Combine(projectRoot, "Library") + ); PluginScanResult scan = pluginSources.Scan(); using var assets = new AssetPipeline( host.modules, @@ -54,16 +55,19 @@ public async Task FacadeMixerProviderAndSceneComponentsCompileThroughLogicalName host.logs, AssetPipelineOptions.Create( Path.Combine(projectRoot, "Assets"), - Path.Combine(projectRoot, "Library")) with + Path.Combine(projectRoot, "Library") + ) with { enableFileSystemWatcher = false - }); + } + ); using var settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, "Settings.Project.inno"))), host.types, host.serialization, new ProjectId("tests.audio.scripting"), - AssetSerializationContext.Create(assets)); + AssetSerializationContext.Create(assets) + ); using var plugins = new PluginEnvironment( assets, settings, @@ -71,10 +75,12 @@ public async Task FacadeMixerProviderAndSceneComponentsCompileThroughLogicalName Path.Combine(projectRoot, "Plugins"), Path.Combine(projectRoot, "Library"), scan, - host.modules.generations); + host.modules.generations + ); string dotnetHost = Path.Combine( Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var compiler = new ScriptCompiler( new ScriptCompilerOptions { @@ -82,7 +88,8 @@ public async Task FacadeMixerProviderAndSceneComponentsCompileThroughLogicalName compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, projectRoot) }, assets, - plugins); + plugins + ); File.WriteAllText(Path.Combine(projectRoot, "Assets", "AudioProbe.cs"), """ using InnoEngine.Audio; @@ -115,14 +122,20 @@ public override void Submit(AudioContentProviderContext context) ScriptCompilationResult result = await compiler.CompileAuthoringGenerationAsync(); - Assert.True(result.success, string.Join( - Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.id}: {diagnostic.message}"))); + Assert.True( + result.success, + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.id}: {diagnostic.message}") + ) + ); } finally { if (Directory.Exists(projectRoot)) + { Directory.Delete(projectRoot, recursive: true); + } } } } diff --git a/tests/audio/Inno.Audio.Tests/AudioValueValidationTests.cs b/tests/audio/Inno.Audio.Tests/AudioValueValidationTests.cs index db516f65e..79470a1fb 100644 --- a/tests/audio/Inno.Audio.Tests/AudioValueValidationTests.cs +++ b/tests/audio/Inno.Audio.Tests/AudioValueValidationTests.cs @@ -1,7 +1,7 @@ using System; +using Xunit; using Inno.Core.Mathematics; using Inno.References; -using Xunit; namespace Inno.Audio.Tests; @@ -63,8 +63,18 @@ public void UndefinedModesAreRejectedAndFiniteBoundaryValuesRemainUsable() Assert.Equal(0, options.volume); Assert.Equal(float.Epsilon, options.pitch); Assert.Equal(-1, options.pan); - var spatial = new AudioSpatialOptions(default, default, default, minDistance: 0, maxDistance: 0, - rolloff: 0, coneInnerAngle: 0, coneOuterAngle: 360, coneOuterGain: 0, dopplerFactor: 0); + var spatial = new AudioSpatialOptions( + default, + default, + default, + minDistance: 0, + maxDistance: 0, + rolloff: 0, + coneInnerAngle: 0, + coneOuterAngle: 360, + coneOuterGain: 0, + dopplerFactor: 0 + ); Assert.Equal(360, spatial.coneOuterAngle); } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxCompositionProgramProviderTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxCompositionProgramProviderTests.cs index d539f185e..a1b1bd9e5 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxCompositionProgramProviderTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxCompositionProgramProviderTests.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.Versioning; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -15,33 +15,46 @@ public sealed class BgfxCompositionProgramProviderTests public void EmbeddedTargetProgramMatchesTheDeviceBackendAndFullscreenLayout(bool outputTransfer) { if (!OperatingSystem.IsMacOS() && !OperatingSystem.IsWindows()) + { return; + } GraphicsApi[] apis = OperatingSystem.IsMacOS() - ? [GraphicsApi.Metal, GraphicsApi.Vulkan, GraphicsApi.OpenGL] - : [GraphicsApi.Direct3D11, GraphicsApi.Direct3D12, GraphicsApi.Vulkan, GraphicsApi.OpenGL]; + ? [GraphicsApi.Metal, GraphicsApi.Vulkan, GraphicsApi.OpenGL] + : [GraphicsApi.Direct3D11, GraphicsApi.Direct3D12, GraphicsApi.Vulkan, GraphicsApi.OpenGL]; var layout = new RenderVertexLayout( - [ - new(RenderVertexSemantic.Position, RenderVertexFormat.Float2), - new(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), - new(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) - ]); + [ + new(RenderVertexSemantic.Position, RenderVertexFormat.Float2), + new(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Float2), + new(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4) + ] + ); var provider = new BgfxCompositionProgramProvider(); foreach (GraphicsApi api in apis) { var capabilities = new GraphicsCapabilities( - api, GraphicsCapability.None, new GraphicsLimits(16, 1, 256, 0), - [], [], [], [], originBottomLeft: false, homogeneousDepth: false); + api, + GraphicsCapability.None, + new GraphicsLimits(16, 1, 256, 0), + [], + [], + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); GraphicsPipelineDescriptor descriptor = outputTransfer - ? provider.CreateOutputTransferDescriptor(capabilities, layout) - : provider.CreateDescriptor(capabilities, layout); + ? provider.CreateOutputTransferDescriptor(capabilities, layout) + : provider.CreateDescriptor(capabilities, layout); Assert.Same(layout, descriptor.vertexLayout); Assert.Equal("s_tex", Assert.Single(descriptor.bindings).id.value); Assert.False(descriptor.vertexShader.IsEmpty); Assert.False(descriptor.fragmentShader.IsEmpty); - Assert.Equal(outputTransfer ? RenderBlendState.opaque : RenderBlendState.premultiplied, - descriptor.rasterState.blend); + Assert.Equal( + outputTransfer ? RenderBlendState.opaque : RenderBlendState.premultiplied, + descriptor.rasterState.blend + ); } } } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs index 77fef33a4..5987559d5 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs @@ -1,8 +1,8 @@ -using Inno.Adapter.Platform; using System; -using Inno.Rendering; -using Inno.Platform; using Xunit; +using Inno.Adapter.Platform; +using Inno.Platform; +using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -25,10 +25,11 @@ public BgfxDeviceTests(BgfxDeviceFixture fixture) public void NoopDevice_ExecutesOneGraphAndSubmitsOneFrame() { RenderGraphBuilder builder = new(1, m_device.capabilities); - builder.AddRasterPass("Noop Clear", C_FIRST, 0, static ( - _, - _ - ) => { }) + builder + .AddRasterPass("Noop Clear", C_FIRST, 0, static ( + _, + _ + ) => {}) .HasSideEffect(); CompiledRenderGraph graph = builder.Compile().graph!; @@ -61,7 +62,8 @@ public void CreateWindowSurface_RejectsUnsupportedPlatformHandlesBeforeNativeCre new PlatformNativeHandles(new IntPtr(1), handleKind: default(PlatformNativeHandleId)), 32, 32, - "Unsupported")); + "Unsupported" + )); m_device.EndFrame(); } @@ -69,11 +71,7 @@ public void CreateWindowSurface_RejectsUnsupportedPlatformHandlesBeforeNativeCre [Fact] public void NoopDevice_CreatesAndDefersPersistentTextureDestruction() { - RenderTextureDescriptor descriptor = new( - 16, - 16, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled); + RenderTextureDescriptor descriptor = new(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled); m_device.BeginFrame(); PersistentTextureHandle texture = m_device.CreateTexture(descriptor, "Persistent Test"); @@ -92,11 +90,7 @@ public void NoopDevice_CreatesAndDefersPersistentTextureDestruction() [Fact] public void NoopDevice_UploadsCompletePersistentTextureSubresource() { - RenderTextureDescriptor descriptor = new( - 4, - 4, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled); + RenderTextureDescriptor descriptor = new(4, 4, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled); m_device.BeginFrame(); PersistentTextureHandle texture = m_device.CreateTexture(descriptor, "Upload Test"); @@ -109,25 +103,23 @@ public void NoopDevice_UploadsCompletePersistentTextureSubresource() public void NoopDevice_CreatesAndUpdatesVolumeAndCubemapSubresources() { Assert.True(m_device.capabilities.Supports(GraphicsCapability.Texture3D)); - Assert.True(m_device.capabilities.SupportsSampled( - RenderTextureFormat.RGBA8, - RenderTextureDimension.Texture3D)); - Assert.True(m_device.capabilities.SupportsSampled( - RenderTextureFormat.RGBA8, - RenderTextureDimension.Cube)); + Assert.True(m_device.capabilities.SupportsSampled(RenderTextureFormat.RGBA8, RenderTextureDimension.Texture3D)); + Assert.True(m_device.capabilities.SupportsSampled(RenderTextureFormat.RGBA8, RenderTextureDimension.Cube)); RenderTextureDescriptor volumeDescriptor = new( 4, 4, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, dimension: RenderTextureDimension.Texture3D, - depth: 2); + depth: 2 + ); RenderTextureDescriptor cubeDescriptor = new( 4, 4, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, - dimension: RenderTextureDimension.Cube); + dimension: RenderTextureDimension.Cube + ); m_device.BeginFrame(); PersistentTextureHandle volume = m_device.CreateTexture(volumeDescriptor, "Volume"); @@ -143,12 +135,14 @@ public void NoopDevice_CreatesAndUpdatesVolumeAndCubemapSubresources() public void NoopDevice_UpdatesDynamicVertexBuffer() { RenderVertexLayout layout = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ]); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ] + ); PersistentBufferDescriptor descriptor = new( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex | RenderBufferUsage.Dynamic), - layout); + layout + ); m_device.BeginFrame(); PersistentBufferHandle buffer = m_device.CreateBuffer(descriptor, ReadOnlySpan.Empty, "Dynamic"); @@ -161,19 +155,23 @@ public void NoopDevice_UpdatesDynamicVertexBuffer() public void NoopDevice_CreatesVertexBufferWithExplicitPadding() { RenderVertexLayout layout = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), - new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 16) - ], stride: 32); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), + new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 16) + ], + stride: 32 + ); PersistentBufferDescriptor descriptor = new( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex), - layout); + layout + ); m_device.BeginFrame(); PersistentBufferHandle buffer = m_device.CreateBuffer( descriptor, new byte[layout.stride * 3], - "Padded Vertices"); + "Padded Vertices" + ); m_device.DestroyBuffer(buffer); m_device.EndFrame(); @@ -184,15 +182,18 @@ public void NoopDevice_CreatesVertexBufferWithExplicitPadding() public void NoopDevice_CreatesVertexAndIndexBuffersAtFrameSafetyPoint() { RenderVertexLayout layout = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ]); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ] + ); PersistentBufferDescriptor vertices = new( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex), - layout); + layout + ); PersistentBufferDescriptor indices = new( new RenderBufferDescriptor(3, sizeof(ushort), RenderBufferUsage.Index), - indexFormat: RenderIndexFormat.UInt16); + indexFormat: RenderIndexFormat.UInt16 + ); m_device.BeginFrame(); PersistentBufferHandle vertexBuffer = m_device.CreateBuffer(vertices, new byte[36], "Test Vertices"); @@ -211,11 +212,13 @@ public void NoopDevice_AllocatesTransientStorageBufferForCompiledGraph() RenderGraphBuilder builder = new(8, m_device.capabilities); RenderBufferHandle buffer = builder.CreateBuffer( "Cluster Light List", - new RenderBufferDescriptor(64, 16, RenderBufferUsage.Storage)); - builder.AddComputePass("Build Data", C_COMPUTE, 0, static ( - _, - _ - ) => { }) + new RenderBufferDescriptor(64, 16, RenderBufferUsage.Storage) + ); + builder + .AddComputePass("Build Data", C_COMPUTE, 0, static ( + _, + _ + ) => {}) .WriteStorageBuffer(buffer) .HasSideEffect(); CompiledRenderGraph graph = builder.Compile().graph!; @@ -231,21 +234,17 @@ public void NoopDevice_AllocatesTransientStorageBufferForCompiledGraph() public void NoopDevice_AllocatesTransientStorageTextureForCompiledGraph() { Assert.True(m_device.capabilities.Supports(GraphicsCapability.StorageTexture)); - Assert.True(m_device.capabilities.SupportsStorage( - RenderTextureFormat.RGBA8, - RenderStorageAccess.Write)); + Assert.True(m_device.capabilities.SupportsStorage(RenderTextureFormat.RGBA8, RenderStorageAccess.Write)); RenderGraphBuilder builder = new(9, m_device.capabilities); RenderTextureHandle texture = builder.CreateTexture( "Compute Output", - new RenderTextureDescriptor( - 8, - 8, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Storage)); - builder.AddComputePass("Write Image", C_COMPUTE, 0, static ( - _, - _ - ) => { }) + new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Storage) + ); + builder + .AddComputePass("Write Image", C_COMPUTE, 0, static ( + _, + _ + ) => {}) .WriteStorageTexture(texture) .HasSideEffect(); CompiledRenderGraph graph = builder.Compile().graph!; @@ -309,15 +308,19 @@ public void NoopDevice_RetiresSupersededNamedFramebuffersDuringResizeChurn() extent, extent, RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); - builder.AddRasterPass( + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); + builder + .AddRasterPass( $"Resize Pass {passIndex}", C_FIRST, passIndex, static ( _, _ - ) => { }) + ) => {} + ) .UseColorAttachment(texture, 0, RenderLoadAction.Clear) .HasSideEffect(); } @@ -333,12 +336,14 @@ public void NoopDevice_RetiresSupersededNamedFramebuffersDuringResizeChurn() public void CreateBuffer_WithPartialInitialData_FailsWithoutClosingFrame() { RenderVertexLayout layout = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ]); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ] + ); PersistentBufferDescriptor descriptor = new( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex), - layout); + layout + ); m_device.BeginFrame(); Assert.Throws(() => m_device.CreateBuffer(descriptor, new byte[12], "Partial")); @@ -356,16 +361,15 @@ public void NoopDevice_BindsRequestedTextureArrayLayer() 8, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment, - arrayLayers: 2)); - builder.AddRasterPass("Layer One", C_LAYERED, 0, static ( - _, - _ - ) => { }) - .UseColorAttachment( - texture, - 0, - RenderLoadAction.Clear, - arrayLayer: 1); + arrayLayers: 2 + ) + ); + builder + .AddRasterPass("Layer One", C_LAYERED, 0, static ( + _, + _ + ) => {}) + .UseColorAttachment(texture, 0, RenderLoadAction.Clear, arrayLayer: 1); builder.MarkOutput(texture); CompiledRenderGraph graph = builder.Compile().graph!; @@ -406,8 +410,7 @@ public void SecondDeviceIsRejectedWhileTheProcessRuntimeIsOwned() forceSingleThreaded = false }; - InvalidOperationException exception = Assert.Throws( - () => new BgfxDevice(options)); + InvalidOperationException exception = Assert.Throws(() => new BgfxDevice(options)); Assert.Contains("Only one BGFX device", exception.Message, StringComparison.Ordinal); } @@ -423,11 +426,14 @@ private CompiledRenderGraph BuildColorTargetGraph( 32, 32, RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); - builder.AddRasterPass(passName, C_FIRST, 0, static ( - _, - _ - ) => { }) + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); + builder + .AddRasterPass(passName, C_FIRST, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(texture, 0, RenderLoadAction.Clear); builder.MarkOutput(texture); return builder.Compile().graph!; @@ -449,8 +455,7 @@ public BgfxDeviceFixture() public BgfxDevice device { get; } - public void Dispose() - => device.Dispose(); + public void Dispose() => device.Dispose(); private static BgfxDevice CreateDevice() => new(new BgfxDeviceOptions diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxImGuiColorContractTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxImGuiColorContractTests.cs index a187c0320..75e055589 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxImGuiColorContractTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxImGuiColorContractTests.cs @@ -1,10 +1,10 @@ using System; using System.IO; using System.Linq; -using Inno.Adapter.Rendering.Bgfx; +using Xunit; using Inno.Adapter.Presentation.ImGui; +using Inno.Adapter.Rendering.Bgfx; using Inno.Rendering; -using Xunit; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -34,13 +34,15 @@ public void DistributedImGuiGraphLoadsTextureAndOutputTransferBindings() Assert.False(pipeline.vertexShader.IsEmpty); Assert.False(pipeline.fragmentShader.IsEmpty); Assert.Equal(2, pipeline.bindings.Count); - RenderShaderBindingDescriptor texture = Assert.Single(pipeline.bindings.Where( - binding => binding.id.value == "s_tex")); + RenderShaderBindingDescriptor texture = Assert.Single( + pipeline.bindings.Where(binding => binding.id.value == "s_tex") + ); Assert.Equal(RenderShaderBindingKind.Texture, texture.kind); Assert.Equal(0, texture.slot); Assert.InRange(texture.nativeName.Length, 1, 63); - RenderShaderBindingDescriptor output = Assert.Single(pipeline.bindings.Where( - binding => binding.id.value == "outputEncoding")); + RenderShaderBindingDescriptor output = Assert.Single( + pipeline.bindings.Where(binding => binding.id.value == "outputEncoding") + ); Assert.Equal(RenderShaderBindingKind.Uniform, output.kind); Assert.InRange(output.nativeName.Length, 1, 63); } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxProcessLifetimeTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxProcessLifetimeTests.cs index 759255972..7c91411ac 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxProcessLifetimeTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxProcessLifetimeTests.cs @@ -1,6 +1,6 @@ using System; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -12,17 +12,20 @@ public void SingleThreadedRuntimeCannotRestartWithEitherThreadingPolicy() { using (var device = new BgfxDevice(new BgfxDeviceOptions { - preferredBackend = GraphicsApi.Noop, forceSingleThreaded = true - })) - { + preferredBackend = GraphicsApi.Noop, + forceSingleThreaded = true + })) { device.BeginFrame(); device.EndFrame(); } foreach (bool inline in new[] { false, true }) + { Assert.Throws(() => new BgfxDevice(new BgfxDeviceOptions { - preferredBackend = GraphicsApi.Noop, forceSingleThreaded = inline + preferredBackend = GraphicsApi.Noop, + forceSingleThreaded = inline })); + } } [Fact] @@ -30,11 +33,11 @@ public void UnsupportedRendererIsRejectedBeforeTheNativeThreadingModeChanges() { Assert.Throws(() => new BgfxDevice(new BgfxDeviceOptions { - preferredBackend = new GraphicsApi("fixture.unsupported"), forceSingleThreaded = true + preferredBackend = new GraphicsApi("fixture.unsupported"), + forceSingleThreaded = true })); using var device = new BgfxDevice(new BgfxDeviceOptions { preferredBackend = GraphicsApi.Noop }); device.BeginFrame(); device.EndFrame(); } - } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs index 7fd6e25dc..3ae6e6202 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs @@ -1,9 +1,9 @@ using System; +using Xunit; using Inno.Adapter.Platform; using Inno.Adapter.Platform.Sdl3; using Inno.Platform; using Inno.Rendering; -using Xunit; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -14,17 +14,23 @@ public sealed class BgfxShutdownTests [Fact] public void ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner() { - if (NativeWindowTestHost.RunIfRequired(nameof(BgfxShutdownTests) + "." + nameof(ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner))) + if (NativeWindowTestHost.RunIfRequired( + nameof(BgfxShutdownTests) + "." + nameof(ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner) + )) { return; + } string? requestedBackend = Environment.GetEnvironmentVariable("INNO_TEST_GRAPHICS_API"); GraphicsApi backend = requestedBackend is null - ? OperatingSystem.IsWindows() ? GraphicsApi.Direct3D11 : GraphicsApi.Metal - : new GraphicsApi(requestedBackend); + ? OperatingSystem.IsWindows() ? GraphicsApi.Direct3D11 : GraphicsApi.Metal + : new GraphicsApi(requestedBackend); using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = application.CreateWindow(new PlatformWindowOptions { - title = "Resource retirement", width = 100, height = 90, visible = false + title = "Resource retirement", + width = 100, + height = 90, + visible = false }); var options = new BgfxDeviceOptions { @@ -41,12 +47,14 @@ public void ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner() 32, 32, RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ); RenderTextureHandle target = builder.CreateTexture("Retired target", descriptor); - builder.AddRasterPass("Offscreen clear", new RenderPhaseId("tests.shutdown"), 0, static ( - _, - _ - ) => { }) + builder + .AddRasterPass("Offscreen clear", new RenderPhaseId("tests.shutdown"), 0, static ( + _, + _ + ) => {}) .UseColorAttachment(target, 0, RenderLoadAction.Clear) .HasSideEffect(); RenderGraphCompileResult result = builder.Compile(); diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceIntegrationTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceIntegrationTests.cs index ea1215241..783446bec 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceIntegrationTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceIntegrationTests.cs @@ -1,9 +1,9 @@ using System; +using Xunit; using Inno.Adapter.Platform; using Inno.Integration.BrowserWasm32.Bgfx.Runtime; using Inno.Integration.MacOSArm64.Bgfx.Runtime; using Inno.Integration.WindowsX64.Bgfx.Runtime; -using Xunit; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -15,22 +15,43 @@ public void EachIntegrationValidatesItsOwnAbiAndRole() var windows = new WindowsX64BgfxSurfaceIntegration(); var macOS = new MacOSArm64BgfxSurfaceIntegration(); var browser = new BrowserWasm32BgfxSurfaceIntegration(); - Assert.Equal((nint)42, windows.Resolve(new((nint)42, handleKind: PlatformNativeHandleId.win32), - BgfxSurfaceRole.Primary).windowHandle); + Assert.Equal( + (nint)42, + windows.Resolve( + new((nint)42, handleKind: PlatformNativeHandleId.win32), + BgfxSurfaceRole.Primary + ).windowHandle + ); Assert.True(windows.supportsAdditionalSurfaces); - Assert.True(macOS.Resolve(new((nint)42, handleKind: PlatformNativeHandleId.cocoa), - BgfxSurfaceRole.Additional).supportsSrgbReset); - Assert.False(browser.Resolve(new((nint)42, handleKind: PlatformNativeHandleId.browserCanvas), - BgfxSurfaceRole.Primary).supportsSrgbReset); + Assert.True( + macOS.Resolve( + new((nint)42, handleKind: PlatformNativeHandleId.cocoa), + BgfxSurfaceRole.Additional + ).supportsSrgbReset + ); + Assert.False( + browser.Resolve( + new((nint)42, handleKind: PlatformNativeHandleId.browserCanvas), + BgfxSurfaceRole.Primary + ).supportsSrgbReset + ); Assert.False(browser.supportsAdditionalSurfaces); Assert.Throws(() => windows.Resolve( - new((nint)42, handleKind: PlatformNativeHandleId.cocoa), BgfxSurfaceRole.Primary)); + new((nint)42, handleKind: PlatformNativeHandleId.cocoa), + BgfxSurfaceRole.Primary + )); Assert.Throws(() => browser.Resolve( - new((nint)42, handleKind: PlatformNativeHandleId.browserCanvas), BgfxSurfaceRole.Additional)); + new((nint)42, handleKind: PlatformNativeHandleId.browserCanvas), + BgfxSurfaceRole.Additional + )); Assert.Throws(() => windows.Resolve( - new((nint)42, handleKind: PlatformNativeHandleId.win32), (BgfxSurfaceRole)99)); + new((nint)42, handleKind: PlatformNativeHandleId.win32), + (BgfxSurfaceRole)99 + )); Assert.Throws(() => windows.Resolve( - new(0, handleKind: PlatformNativeHandleId.win32), BgfxSurfaceRole.Primary)); + new(0, handleKind: PlatformNativeHandleId.win32), + BgfxSurfaceRole.Primary + )); } [Fact] diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs index 88a460c76..4d61790bf 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs @@ -1,9 +1,9 @@ using System; +using Xunit; using Inno.Adapter.Platform; using Inno.Adapter.Platform.Sdl3; using Inno.Platform; using Inno.Rendering; -using Xunit; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -14,29 +14,41 @@ public sealed class BgfxSurfaceRetirementTests [Fact] public void MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission() { - if (NativeWindowTestHost.RunIfRequired(nameof(BgfxSurfaceRetirementTests) + "." + nameof(MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission))) + if (NativeWindowTestHost.RunIfRequired( + nameof(BgfxSurfaceRetirementTests) + "." + nameof(MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission) + )) { return; + } VerifyRetirement(false); } [Fact] public void InlineSurfaceUsesTheSameConservativeAcknowledgment() { - if (NativeWindowTestHost.RunIfRequired(nameof(BgfxSurfaceRetirementTests) + "." + nameof(InlineSurfaceUsesTheSameConservativeAcknowledgment))) + if (NativeWindowTestHost.RunIfRequired( + nameof(BgfxSurfaceRetirementTests) + "." + nameof(InlineSurfaceUsesTheSameConservativeAcknowledgment) + )) { return; + } VerifyRetirement(true); } [Fact] public void InvalidIntegrationFailsBeforeTakingTheProcessOwner() { - if (NativeWindowTestHost.RunIfRequired(nameof(BgfxSurfaceRetirementTests) + "." + nameof(InvalidIntegrationFailsBeforeTakingTheProcessOwner))) + if (NativeWindowTestHost.RunIfRequired( + nameof(BgfxSurfaceRetirementTests) + "." + nameof(InvalidIntegrationFailsBeforeTakingTheProcessOwner) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = application.CreateWindow(new PlatformWindowOptions { - title = "Invalid integration", width = 100, height = 90, visible = false + title = "Invalid integration", + width = 100, + height = 90, + visible = false }); Assert.Throws(() => new BgfxDevice(new BgfxDeviceOptions { @@ -59,11 +71,17 @@ private static void VerifyRetirement(bool inline) using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var primary = application.CreateWindow(new PlatformWindowOptions { - title = "Primary surface", width = 100, height = 90, visible = false + title = "Primary surface", + width = 100, + height = 90, + visible = false }); using var additional = application.CreateWindow(new PlatformWindowOptions { - title = "Additional surface", width = 100, height = 90, visible = false + title = "Additional surface", + width = 100, + height = 90, + visible = false }); var integration = new FixtureIntegration(); using var device = new BgfxDevice(new BgfxDeviceOptions @@ -76,7 +94,10 @@ private static void VerifyRetirement(bool inline) }); PlatformNativeHandles native = additional.nativeHandles; var handles = new PlatformNativeHandles( - native.windowHandle, native.displayHandle, new PlatformNativeHandleId("fixture.custom-surface")); + native.windowHandle, + native.displayHandle, + new PlatformNativeHandleId("fixture.custom-surface") + ); RenderSurfaceHandle surface = device.CreateWindowSurface(handles, 100, 90, "Custom surface"); device.ResizeWindowSurface(surface, 110, 95); device.ResizeWindowSurface(surface, 120, 100); @@ -113,6 +134,7 @@ private sealed class FixtureIntegration : IBgfxSurfaceIntegration { internal int resolveCount; public bool supportsAdditionalSurfaces => true; + public BgfxSurfaceDescriptor Resolve( PlatformNativeHandles handles, BgfxSurfaceRole role @@ -125,6 +147,7 @@ BgfxSurfaceRole role private sealed class InvalidIntegration : IBgfxSurfaceIntegration { public bool supportsAdditionalSurfaces => true; + public BgfxSurfaceDescriptor Resolve( PlatformNativeHandles handles, BgfxSurfaceRole role diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeHostFixture.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeHostFixture.cs index 58521217d..d8a488054 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeHostFixture.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeHostFixture.cs @@ -1,15 +1,16 @@ using System; using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.WindowsX64.Sdl3; using Inno.Integration.MacOSArm64.Sdl3; +using Inno.Integration.WindowsX64.Sdl3; namespace Inno.Adapter.Rendering.Bgfx.Tests; internal static class NativeHostFixture { - internal static ISdl3HostIntegration Create() => OperatingSystem.IsWindows() - ? new WindowsX64Sdl3HostIntegration() - : OperatingSystem.IsMacOS() - ? new MacOSArm64Sdl3HostIntegration() - : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); + internal static ISdl3HostIntegration Create() + => OperatingSystem.IsWindows() + ? new WindowsX64Sdl3HostIntegration() + : OperatingSystem.IsMacOS() + ? new MacOSArm64Sdl3HostIntegration() + : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeWindowTestHost.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeWindowTestHost.cs index eea6397f0..f439713cc 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeWindowTestHost.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/NativeWindowTestHost.cs @@ -8,18 +8,25 @@ internal static class NativeWindowTestHost { private static readonly IReadOnlyDictionary S_CONTRACTS = new Dictionary { - ["BgfxShutdownTests.ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner"] = () => new BgfxShutdownTests().ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner(), - ["BgfxSurfaceRetirementTests.MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission"] = () => new BgfxSurfaceRetirementTests().MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission(), - ["BgfxSurfaceRetirementTests.InlineSurfaceUsesTheSameConservativeAcknowledgment"] = () => new BgfxSurfaceRetirementTests().InlineSurfaceUsesTheSameConservativeAcknowledgment(), - ["BgfxSurfaceRetirementTests.InvalidIntegrationFailsBeforeTakingTheProcessOwner"] = () => new BgfxSurfaceRetirementTests().InvalidIntegrationFailsBeforeTakingTheProcessOwner(), + ["BgfxShutdownTests.ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner"] = () => new BgfxShutdownTests() + .ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner(), + ["BgfxSurfaceRetirementTests.MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission"] = () => new BgfxSurfaceRetirementTests() + .MultiThreadedSurfaceAcknowledgesDestructionAfterTheFollowingSubmission(), + ["BgfxSurfaceRetirementTests.InlineSurfaceUsesTheSameConservativeAcknowledgment"] = () => new BgfxSurfaceRetirementTests() + .InlineSurfaceUsesTheSameConservativeAcknowledgment(), + ["BgfxSurfaceRetirementTests.InvalidIntegrationFailsBeforeTakingTheProcessOwner"] = () => new BgfxSurfaceRetirementTests() + .InvalidIntegrationFailsBeforeTakingTheProcessOwner() }; + private static bool m_executingContract; internal static bool RunIfRequired(string contract) { if (m_executingContract || !OperatingSystem.IsMacOS() - && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1") + && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1" + ) { return false; + } NativeProcessTestHost.Run(typeof(NativeWindowTestHost).Assembly.Location, contract); return true; } @@ -29,7 +36,9 @@ private static int Main(string[] arguments) try { if (arguments.Length != 1 || !S_CONTRACTS.TryGetValue(arguments[0], out Action? contract)) + { throw new ArgumentException("The native test host requires one declared contract."); + } // Cocoa must create real windows on the process main thread, including isolated renderer tests. m_executingContract = true; Console.Error.WriteLine($"Native contract started: {arguments[0]}; thread={Environment.CurrentManagedThreadId}."); diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs index 3ec8e81bd..115270c52 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs @@ -1,24 +1,25 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Buffers.Binary; +using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.Linq; -using System.Collections.Generic; +using System.Runtime.Versioning; using System.Text; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Inno.Rendering.Shaders; -using Inno.Build.Toolchains.Bgfx.Tools; -using Inno.Rendering.Assets; using Inno.Rendering; -using Xunit; +using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; using Inno.Testing.Bgfx; + using static Inno.Testing.Bgfx.ShaderProfileFixture; namespace Inno.Build.Toolchains.Bgfx.Integration.Tests; @@ -34,7 +35,8 @@ public sealed class BgfxToolchainTests : IDisposable private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoBgfxToolchainTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); public BgfxToolchainTests() => Directory.CreateDirectory(m_root); @@ -43,7 +45,9 @@ public sealed class BgfxToolchainTests : IDisposable public async Task BrowserProfileCompilesTheCommonGraphOnWindows() { if (!OperatingSystem.IsWindows()) + { return; + } using var modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderNodeCompilerRegistry).Assembly) @@ -52,8 +56,13 @@ public async Task BrowserProfileCompilesTheCommonGraphOnWindows() using var serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); using var nodes = new ShaderNodeCompilerRegistry(types); GraphDocument graph = ShaderGraphTemplates.CreateRaster(serialization, SerializationContext.empty); - ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(nodes).Lower(graph, "bgfx", - new Dictionary(), serialization, SerializationContext.empty); + ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(nodes).Lower( + graph, + "bgfx", + new Dictionary(), + serialization, + SerializationContext.empty + ); var compiler = new ShaderCompiler(new BgfxShadercToolchain(ShaderProfileFixture.browser)); ShaderCompilationResult result = await compiler.CompileAsync( @@ -61,11 +70,17 @@ public async Task BrowserProfileCompilesTheCommonGraphOnWindows() program, compiler.CreateTarget(CreateCapabilities(GraphicsApi.OpenGLES, GraphicsCapability.None)), RenderShaderVariant.empty, - serialization, SerializationContext.empty); + serialization, + SerializationContext.empty + ); - Assert.True(result.succeeded, string.Join( - Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}"))); + Assert.True( + result.succeeded, + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}") + ) + ); Assert.Single(result.artifact!.passes); } @@ -74,7 +89,9 @@ public async Task BrowserProfileCompilesTheCommonGraphOnWindows() public async Task Direct3DProfileCompilesTheCommonGraphOnWindows() { if (!OperatingSystem.IsWindows()) + { return; + } using var modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderNodeCompilerRegistry).Assembly) @@ -83,8 +100,13 @@ public async Task Direct3DProfileCompilesTheCommonGraphOnWindows() using var serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); using var nodes = new ShaderNodeCompilerRegistry(types); GraphDocument graph = ShaderGraphTemplates.CreateRaster(serialization, SerializationContext.empty); - ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(nodes).Lower(graph, "bgfx", - new Dictionary(), serialization, SerializationContext.empty); + ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(nodes).Lower( + graph, + "bgfx", + new Dictionary(), + serialization, + SerializationContext.empty + ); var compiler = new ShaderCompiler(new BgfxShadercToolchain(ShaderProfileFixture.windows)); ShaderCompilationResult result = await compiler.CompileAsync( @@ -92,11 +114,17 @@ public async Task Direct3DProfileCompilesTheCommonGraphOnWindows() program, compiler.CreateTarget(CreateCapabilities(GraphicsApi.Direct3D11, GraphicsCapability.None)), RenderShaderVariant.empty, - serialization, SerializationContext.empty); + serialization, + SerializationContext.empty + ); - Assert.True(result.succeeded, string.Join( - Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}"))); + Assert.True( + result.succeeded, + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}") + ) + ); Assert.Single(result.artifact!.passes); } @@ -108,7 +136,9 @@ public async Task Direct3DProfileCompilesTheCommonGraphOnWindows() public async Task GlslReflectionPreservesUsedBindingsAndRemovesOptimizedBindings(bool browser) { if (!OperatingSystem.IsWindows() && !OperatingSystem.IsMacOS()) + { return; + } GraphicsApi backend = browser ? GraphicsApi.OpenGLES : GraphicsApi.OpenGL; var builder = new ShaderIrBuilder(); ShaderSourceType colorType = ShaderSourceType.Atomic("float4"); @@ -116,8 +146,10 @@ public async Task GlslReflectionPreservesUsedBindingsAndRemovesOptimizedBindings _ = builder.Input("unused-tint", colorType); ShaderSourceType textureType = ShaderSourceType.Atomic("sampled-texture2d"); ShaderIrValue texture = builder.Input("sampled", textureType); - ShaderIrValue coordinate = builder.Construct(ShaderSourceType.Atomic("float2"), - [builder.Constant(0.5f), builder.Constant(0.5f)]); + ShaderIrValue coordinate = builder.Construct( + ShaderSourceType.Atomic("float2"), + [builder.Constant(0.5f), builder.Constant(0.5f)] + ); ShaderIrValue output = builder.Binary(ShaderIrOperation.Multiply, color, builder.Sample(texture, coordinate)); var stage = new ShaderIrStage( ShaderStage.Fragment, @@ -127,21 +159,27 @@ public async Task GlslReflectionPreservesUsedBindingsAndRemovesOptimizedBindings new("unused-tint", colorType, ShaderIrInputKind.Uniform), new("sampled", textureType, ShaderIrInputKind.SampledTexture) ], - [new("color", ShaderIrOutputKind.Color)]); + [new("color", ShaderIrOutputKind.Color)] + ); BgfxShaderTargetProfile platform = backend == GraphicsApi.OpenGLES - ? ShaderProfileFixture.browser - : OperatingSystem.IsWindows() - ? ShaderProfileFixture.windows - : ShaderProfileFixture.mac; + ? ShaderProfileFixture.browser + : OperatingSystem.IsWindows() + ? ShaderProfileFixture.windows + : ShaderProfileFixture.mac; var compiler = new ShaderCompiler(new BgfxShadercToolchain(platform)); ShaderStageToolResult result = await compiler.CompileAsync( stage, - compiler.CreateTarget(CreateCapabilities(backend, GraphicsCapability.None))); + compiler.CreateTarget(CreateCapabilities(backend, GraphicsCapability.None)) + ); - Assert.True(result.succeeded, string.Join( - Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}"))); + Assert.True( + result.succeeded, + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}") + ) + ); Assert.Equal(new[] { "sampled", "used-tint" }, result.bindings.Select(static binding => binding.id).Order().ToArray()); Dictionary uniforms = ReadBinaryUniformTypes(result.bytes.Span); Assert.Equal(2, uniforms.Count); @@ -156,9 +194,7 @@ public async System.Threading.Tasks.Task TextureCompilerProducesValidatedPortabl File.WriteAllBytes(sourcePath, CreateTga()); using FileStream source = File.OpenRead(sourcePath); - byte[] artifact = await new BgfxTextureTargetCompiler().CompileKtxAsync( - source, - TextureColorSpace.Srgb); + byte[] artifact = await new BgfxTextureTargetCompiler().CompileKtxAsync(source, TextureColorSpace.Srgb); Assert.True(artifact.Length > C_KTX_IDENTIFIER.Length); Assert.Equal(C_KTX_IDENTIFIER, artifact[..C_KTX_IDENTIFIER.Length]); @@ -181,25 +217,38 @@ public async System.Threading.Tasks.Task TextureCompilerProducesValidatedPortabl public async Task GlslFragmentOutputsPreserveSparseAttachmentLocations(bool browser) { if (!OperatingSystem.IsWindows() && !OperatingSystem.IsMacOS()) + { return; + } GraphicsApi backend = browser ? GraphicsApi.OpenGLES : GraphicsApi.OpenGL; - BgfxShaderTargetProfile platform = browser ? ShaderProfileFixture.browser - : OperatingSystem.IsWindows() ? ShaderProfileFixture.windows : ShaderProfileFixture.mac; + BgfxShaderTargetProfile platform = browser + ? ShaderProfileFixture.browser + : OperatingSystem.IsWindows() ? ShaderProfileFixture.windows : ShaderProfileFixture.mac; var builder = new ShaderIrBuilder(); - ShaderIrValue color = builder.Construct(ShaderSourceType.Atomic("float4"), - [builder.Constant(0.25f), builder.Constant(0.5f), builder.Constant(0.75f), builder.Constant(1f)]); + ShaderIrValue color = builder.Construct( + ShaderSourceType.Atomic("float4"), + [builder.Constant(0.25f), builder.Constant(0.5f), builder.Constant(0.75f), builder.Constant(1f)] + ); var stage = new ShaderIrStage( ShaderStage.Fragment, builder.Build(new Dictionary { ["first"] = color, ["third"] = color }), [], - [new("first", ShaderIrOutputKind.Color, location: 0), new("third", ShaderIrOutputKind.Color, location: 2)]); + [new("first", ShaderIrOutputKind.Color, location: 0), new("third", ShaderIrOutputKind.Color, location: 2)] + ); var compiler = new ShaderCompiler(new BgfxShadercToolchain(platform)); - ShaderStageToolResult result = await compiler.CompileAsync(stage, - compiler.CreateTarget(CreateCapabilities(backend, GraphicsCapability.None))); + ShaderStageToolResult result = await compiler.CompileAsync( + stage, + compiler.CreateTarget(CreateCapabilities(backend, GraphicsCapability.None)) + ); - Assert.True(result.succeeded, string.Join(Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}"))); + Assert.True( + result.succeeded, + string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.code}: {diagnostic.message}") + ) + ); string glsl = Encoding.UTF8.GetString(result.bytes.Span); if (browser) { @@ -217,7 +266,9 @@ public async Task GlslFragmentOutputsPreserveSparseAttachmentLocations(bool brow public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private static Dictionary ReadBinaryUniformTypes(ReadOnlySpan binary) diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/ToolRunnerTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/ToolRunnerTests.cs index c1315eba9..62dc58f73 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/ToolRunnerTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/ToolRunnerTests.cs @@ -1,15 +1,14 @@ using System; using System.IO; -using Inno.Native.LibraryLoading; - using Xunit; - using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Native.LibraryLoading; namespace Inno.Build.Toolchains.Bgfx.Integration.Tests; public sealed class ToolRunnerTests -{ [Fact] +{ + [Fact] public void Run_UsesExplicitlyDeployedTools() { foreach (var tool in Enum.GetValues()) diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxNativeProfileTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxNativeProfileTests.cs index faf2c8c61..d468c649a 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxNativeProfileTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxNativeProfileTests.cs @@ -65,12 +65,15 @@ public void SourceDeclarationFreezesRuntimeAndToolOptionsBeforeBindingExists(boo var profile = new FixtureProfile("fixture-new-target"); NativeBuildContext context = CreateContext(profile.targetId); foreach (string source in new[] { "bgfx", "bx", "bimg" }) + { Directory.CreateDirectory(Path.Combine(m_root, "extern", source)); + } string project = Path.Combine(m_root, BgfxNativeBuild.componentDescriptor.toolchainProject); Directory.CreateDirectory(Path.GetDirectoryName(project)!); File.WriteAllText(project, ""); - NativeBuildRecipe recipe = tools ? BgfxToolsBuild.CreateRecipe(context, profile) - : BgfxNativeBuild.CreateRecipe(context, profile); + NativeBuildRecipe recipe = tools + ? BgfxToolsBuild.CreateRecipe(context, profile) + : BgfxNativeBuild.CreateRecipe(context, profile); Assert.Equal(tools ? "bgfx-tools" : "bgfx", recipe.component); Assert.Equal(tools ? null : BgfxNativeBuild.componentDescriptor.bindingDefinition, recipe.owner.bindingDefinition); Assert.Equal(1, profile.invocationCount); @@ -89,7 +92,10 @@ public async Task OfflineToolsDoNotRequestRuntimeBindings() Assert.Equal(BgfxNativeBuild.componentDescriptor.toolchainProject, tools.toolchainProject); Assert.Null(tools.bindingDefinition); using NativeBindingGenerationResult generations = await NativeBindingPreparation.PrepareAsync( - CreateContext("fixture-new-target"), [tools], CancellationToken.None); + CreateContext("fixture-new-target"), + [tools], + CancellationToken.None + ); Assert.Empty(generations); } @@ -97,9 +103,19 @@ private NativeBuildContext CreateContext(string target) { string compiler = Path.Combine(m_root, "fixture-compiler"); File.WriteAllText(compiler, "Not executable: this fixture stops before source preparation."); - var selection = new NativeToolchainSelection(target, new BuildHostDescriptor("FixtureHost", "fixture-cpu"), - new Dictionary { ["compiler"] = compiler, ["genie"] = compiler }, new Dictionary(), [], [], new NativeLinkPlan(".fixture"), false); - return new NativeBuildContext(m_root, "debug").WithToolchain(selection).WithComponentOptions(BgfxNativeBuild.componentDescriptor, new(NativeLibraryKind.Shared)); + var selection = new NativeToolchainSelection( + target, + new BuildHostDescriptor("FixtureHost", "fixture-cpu"), + new Dictionary { ["compiler"] = compiler, ["genie"] = compiler }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".fixture"), + false + ); + return new NativeBuildContext(m_root, "debug") + .WithToolchain(selection) + .WithComponentOptions(BgfxNativeBuild.componentDescriptor, new(NativeLibraryKind.Shared)); } private sealed class FixtureProfile(string target) : BgfxNativeBuildProfile @@ -114,7 +130,9 @@ bool includeTools public override IReadOnlyList generatorArguments => ["fixture-generator"]; public override string artifactPathToken => "/fixture-cpu/bin/"; public override IReadOnlyList bindingCmakeArguments => []; - public override (string reference, IReadOnlyList arguments) CreateBindingLinkSettings(string archivePath) => (archivePath, []); + + public override (string reference, IReadOnlyList arguments) CreateBindingLinkSettings(string archivePath) + => (archivePath, []); public override BgfxBuildInvocation CreateBuildInvocation( NativeBuildContext context, diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs index de43c3d04..1450639e5 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs @@ -1,7 +1,7 @@ using System; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering; -using Xunit; namespace Inno.Build.Toolchains.Bgfx.Tests; @@ -31,28 +31,62 @@ public void DialectDefinesAndCapabilitiesAllParticipateInIdentity() defines[0] = "TEST=2"; Assert.Equal("TEST=1", original.defines[0]); - Assert.NotEqual(original.key, new BgfxShaderCompilerProfile(capabilities, - "fixture-sdk", "spirv", "spirv", "spirv", defines).key); - Assert.NotEqual(original.key, new BgfxShaderCompilerProfile(capabilities, - "other-sdk", "spirv", "spirv", "spirv", ["TEST=1"]).key); - Assert.NotEqual(original.key, new BgfxShaderCompilerProfile(capabilities, - "fixture-sdk", "other-dialect", "spirv", "spirv", ["TEST=1"]).key); - var reduced = new GraphicsCapabilities(GraphicsApi.Vulkan, capabilities.features, - new GraphicsLimits(16, 4, 1024, 8), [], [], [], [], false, false); - Assert.NotEqual(original.key, new BgfxShaderCompilerProfile(reduced, - "fixture-sdk", "spirv", "spirv", "spirv", ["TEST=1"]).key); + Assert.NotEqual( + original.key, + new BgfxShaderCompilerProfile(capabilities, "fixture-sdk", "spirv", "spirv", "spirv", defines).key + ); + Assert.NotEqual( + original.key, + new BgfxShaderCompilerProfile(capabilities, "other-sdk", "spirv", "spirv", "spirv", ["TEST=1"]).key + ); + Assert.NotEqual( + original.key, + new BgfxShaderCompilerProfile( + capabilities, + "fixture-sdk", + "other-dialect", + "spirv", + "spirv", + ["TEST=1"] + ).key + ); + var reduced = new GraphicsCapabilities( + GraphicsApi.Vulkan, + capabilities.features, + new GraphicsLimits(16, 4, 1024, 8), + [], + [], + [], + [], + false, + false + ); + Assert.NotEqual( + original.key, + new BgfxShaderCompilerProfile(reduced, "fixture-sdk", "spirv", "spirv", "spirv", ["TEST=1"]).key + ); } [Fact] public void InvalidAndDuplicateProfilesFailBeforeCreatingACompiler() { - var profile = new BgfxShaderCompilerProfile(BgfxTargetCapabilities.Create(GraphicsApi.Metal), - "osx", "metal", "metal", "metal"); + var profile = new BgfxShaderCompilerProfile( + BgfxTargetCapabilities.Create(GraphicsApi.Metal), + "osx", + "metal", + "metal", + "metal" + ); Assert.Throws(() => new BgfxShaderTargetProfile("fixture", [])); Assert.Throws(() => new BgfxShaderTargetProfile("fixture", [profile, profile])); - Assert.Throws(() => new BgfxShaderCompilerProfile(profile.capabilities, - "osx", "metal", "metal", "")); + Assert.Throws(() => new BgfxShaderCompilerProfile( + profile.capabilities, + "osx", + "metal", + "metal", + "" + )); Assert.Throws(() => new BgfxShadercToolchain(null!)); } } diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderTargetTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderTargetTests.cs index 46c41dc90..49b145b13 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderTargetTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderTargetTests.cs @@ -1,10 +1,11 @@ using System; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering; using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Shaders; -using Xunit; using Inno.Testing.Bgfx; + using static Inno.Testing.Bgfx.ShaderProfileFixture; namespace Inno.Build.Toolchains.Bgfx.Tests; @@ -14,9 +15,7 @@ public sealed class BgfxShaderTargetTests [Fact] public void MetalProfileIsOwnedByMacBgfxToolchain() { - GraphicsCapabilities capabilities = CreateCapabilities( - GraphicsApi.Metal, - GraphicsCapability.Compute); + GraphicsCapabilities capabilities = CreateCapabilities(GraphicsApi.Metal, GraphicsCapability.Compute); var toolchain = new BgfxShadercToolchain(ShaderProfileFixture.mac); ShaderCompileTarget target = toolchain.CreateTarget(capabilities); @@ -45,12 +44,15 @@ public void BrowserProfileRequiresWebGlWithoutCompute() var toolchain = new BgfxShadercToolchain(ShaderProfileFixture.browser); ShaderCompileTarget target = toolchain.CreateTarget( - CreateCapabilities(GraphicsApi.OpenGLES, GraphicsCapability.None)); + CreateCapabilities(GraphicsApi.OpenGLES, GraphicsCapability.None) + ); Assert.Contains("bgfx-shaderc:fixture-browser:", target.profileKey, StringComparison.Ordinal); Assert.Throws(() => toolchain.CreateTarget( - CreateCapabilities(GraphicsApi.OpenGLES, GraphicsCapability.Compute))); + CreateCapabilities(GraphicsApi.OpenGLES, GraphicsCapability.Compute) + )); Assert.Throws(() => toolchain.CreateTarget( - CreateCapabilities(GraphicsApi.OpenGL, GraphicsCapability.None))); + CreateCapabilities(GraphicsApi.OpenGL, GraphicsCapability.None) + )); } } diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs index e39933d00..25a9fd2d7 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs @@ -1,8 +1,6 @@ using System; using System.IO; - using Xunit; - using Inno.Build.Toolchains.Bgfx.Tools; namespace Inno.Build.Toolchains.Bgfx.Tests; diff --git a/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs b/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs index 6458e83b7..49b1fea64 100644 --- a/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs +++ b/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs @@ -8,20 +8,46 @@ namespace Inno.Testing.Bgfx; public static class ShaderProfileFixture { /// Gets the explicit windows shader profile used by the tests. - public static BgfxShaderTargetProfile windows { get; } = new("fixture-windows", - [new(BgfxTargetCapabilities.Create(GraphicsApi.Direct3D11), "windows", "s_5_0", "s_5_0", "s_5_0"), + public static BgfxShaderTargetProfile windows { get; } = new( + "fixture-windows", + [ + new(BgfxTargetCapabilities.Create(GraphicsApi.Direct3D11), "windows", "s_5_0", "s_5_0", "s_5_0"), new(BgfxTargetCapabilities.Create(GraphicsApi.OpenGL), "windows", "430", "430", "430"), - new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "windows", "spirv", "spirv", "spirv")]); + new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "windows", "spirv", "spirv", "spirv") + ] + ); + /// Gets the explicit mac shader profile used by the tests. - public static BgfxShaderTargetProfile mac { get; } = new("fixture-mac", - [new(BgfxTargetCapabilities.Create(GraphicsApi.Metal), "osx", "metal", "metal", "metal"), + public static BgfxShaderTargetProfile mac { get; } = new( + "fixture-mac", + [ + new(BgfxTargetCapabilities.Create(GraphicsApi.Metal), "osx", "metal", "metal", "metal"), new(BgfxTargetCapabilities.Create(GraphicsApi.OpenGL), "osx", "430", "430", "430"), - new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "osx", "spirv", "spirv", "spirv", ["BGFX_SHADER_LANGUAGE_SPIRV=1"])]); + new(BgfxTargetCapabilities.Create(GraphicsApi.Vulkan), "osx", "spirv", "spirv", "spirv", ["BGFX_SHADER_LANGUAGE_SPIRV=1"]) + ] + ); + /// Gets the explicit browser shader profile used by the tests. - public static BgfxShaderTargetProfile browser { get; } = new("fixture-browser", - [new(new GraphicsCapabilities(GraphicsApi.OpenGLES, GraphicsCapability.None, - new GraphicsLimits(256, 4, 2048, 0), [RenderTextureFormat.RGBA8], [RenderTextureFormat.RGBA8], - [], [], true, true), "asm.js", "300_es", "300_es", "")]); + public static BgfxShaderTargetProfile browser { get; } = new( + "fixture-browser", + [new( + new GraphicsCapabilities( + GraphicsApi.OpenGLES, + GraphicsCapability.None, + new GraphicsLimits(256, 4, 2048, 0), + [RenderTextureFormat.RGBA8], + [RenderTextureFormat.RGBA8], + [], + [], + true, + true + ), + "asm.js", + "300_es", + "300_es", + "" + )] + ); /// Creates the declared rendering capabilities without loading a native runtime. /// The explicit graphics API. @@ -32,13 +58,14 @@ public static GraphicsCapabilities CreateCapabilities( GraphicsApi backend, GraphicsCapability features ) => new( - backend, - features, - new GraphicsLimits(256, 8, 8192, 16), - Enum.GetValues(), - Enum.GetValues(), - Enum.GetValues(), - Enum.GetValues(), - originBottomLeft: false, - homogeneousDepth: false); + backend, + features, + new GraphicsLimits(256, 8, 8192, 16), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + originBottomLeft: false, + homogeneousDepth: false + ); } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs index 1d9d4b9ec..ad7eb8b9d 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs @@ -20,7 +20,10 @@ public async Task CancellationDuringCopyDiscardsCandidateAndPreservesThePrevious using CancellationTokenSource cancellation = new(); fixture.source.onRead = cancellation.Cancel; await Assert.ThrowsAnyAsync(() => FileContentPreparation.PrepareAsync( - fixture.source, fixture.options, cancellation.Token).AsTask()); + fixture.source, + fixture.options, + cancellation.Token + ).AsTask()); Assert.Equal(previous, fixture.current); Assert.Empty(Directory.GetDirectories(Path.Combine(fixture.cache, "staging"))); fixture.source.onRead = null; @@ -33,7 +36,10 @@ public async Task PriorCancellationCreatesNoCacheDirectory() { using ContentCacheFixture fixture = new(); await Assert.ThrowsAnyAsync(() => FileContentPreparation.PrepareAsync( - fixture.source, fixture.options, new CancellationToken(true)).AsTask()); + fixture.source, + fixture.options, + new CancellationToken(true) + ).AsTask()); Assert.False(Directory.Exists(fixture.root)); } } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs index c10298354..26ba49e69 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs @@ -11,8 +11,10 @@ public sealed class ContentCacheConcurrencyTests public async Task ConcurrentPreparationPublishesOneCompleteGeneration() { using ContentCacheFixture fixture = new(); - FileContentStore[] readers = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => - FileContentPreparation.PrepareAsync(fixture.source, fixture.options).AsTask())); + FileContentStore[] readers = await Task.WhenAll( + Enumerable.Range(0, 8).Select(_ => + FileContentPreparation.PrepareAsync(fixture.source, fixture.options).AsTask()) + ); try { Assert.Single(Directory.GetDirectories(Path.Combine(fixture.cache, "generations"))); @@ -22,7 +24,9 @@ public async Task ConcurrentPreparationPublishesOneCompleteGeneration() finally { foreach (FileContentStore reader in readers) + { reader.Dispose(); + } } } } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs index 40e4e0b28..b82340340 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs @@ -11,6 +11,7 @@ namespace Inno.Adapter.Content.FileSystem.Tests; internal sealed class ContentCacheFixture : IDisposable { internal readonly string root = Path.Combine(Path.GetTempPath(), "inno-content-cache-" + Guid.NewGuid().ToString("N")); + internal readonly MemoryContentStore source = new(new Dictionary { ["AssetDatabase/Catalog.snapshot"] = [1, 2, 3], @@ -25,7 +26,9 @@ public void Dispose() { source.Dispose(); if (Directory.Exists(root)) + { Directory.Delete(root, true); + } } internal sealed class MemoryContentStore : IRuntimeContentStore @@ -37,27 +40,41 @@ internal sealed class MemoryContentStore : IRuntimeContentStore internal MemoryContentStore(Dictionary content) { m_content = content.ToDictionary(static pair => new ContentKey(pair.Key), static pair => (byte[])pair.Value.Clone()); - index = new ContentPackIndex(m_content.Select(static pair => new ContentEntry(pair.Key, pair.Value.Length, - Convert.ToHexString(SHA256.HashData(pair.Value))))); - string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join(";", - index.entries.Select(static entry => entry.key.value + entry.contentHash))))); + index = new ContentPackIndex( + m_content.Select(static pair => new ContentEntry( + pair.Key, + pair.Value.Length, + Convert.ToHexString(SHA256.HashData(pair.Value)) + )) + ); + string hash = Convert.ToHexString( + SHA256.HashData( + Encoding.UTF8.GetBytes( + string.Join(";", index.entries.Select(static entry => entry.key.value + entry.contentHash)) + ) + ) + ); descriptor = new ContentPackDescriptor(hash, $"content-{hash}.pack"); } public ContentPackDescriptor descriptor { get; } public ContentPackIndex index { get; } + public ContentReadLease Acquire(ContentKey key) { ObjectDisposedException.ThrowIf(m_closed, this); if (!index.TryGetEntry(key, out ContentEntry? entry)) + { throw new FileNotFoundException(); + } byte[] bytes = m_content[key]; return new ContentReadLease(entry!, () => { onRead?.Invoke(); return new MemoryStream(bytes, false); - }, static () => { }); + }, static () => {}); } + public void Dispose() => m_closed = true; } } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs index d61bd24a0..f4a28ddbb 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs @@ -1,7 +1,7 @@ using System.IO; using System.Threading.Tasks; -using Inno.Content; using Xunit; +using Inno.Content; namespace Inno.Adapter.Content.FileSystem.Tests; @@ -76,7 +76,9 @@ public async Task ContentChangedAfterPreparationFailsReadingAndReleasesTheFailed File.WriteAllBytes(file, [3, 2, 1]); File.SetLastWriteTimeUtc(file, time); using (ContentReadLease lease = store.Acquire(new ContentKey("AssetDatabase/Catalog.snapshot"))) + { Assert.Throws(() => lease.OpenRead()); + } store.Dispose(); using FileContentStore repaired = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); Assert.False(Directory.Exists(original)); diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheProcessTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheProcessTests.cs index 0d5281383..706528414 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheProcessTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheProcessTests.cs @@ -2,8 +2,8 @@ using System.Diagnostics; using System.IO; using System.Threading.Tasks; -using Inno.Content.Testing; using Xunit; +using Inno.Content.Testing; namespace Inno.Adapter.Content.FileSystem.Tests; @@ -34,21 +34,25 @@ public async Task IndependentProcessesPublishOneGenerationAndPinItUntilBothReade Assert.Single(Directory.GetDirectories(Path.Combine(cache, "generations"))); File.WriteAllBytes(Path.Combine(oldDirectory, "repair.bin"), [6, 5, 4]); - using (FileContentStore repaired = await FileContentPreparation.PrepareAsync(source, - new FileContentCacheOptions(cacheRoot))) - { + using (FileContentStore repaired = await FileContentPreparation.PrepareAsync( + source, + new FileContentCacheOptions(cacheRoot) + )) { Assert.NotEqual(generation, File.ReadAllText(Path.Combine(cache, "current"))); Assert.True(Directory.Exists(oldDirectory)); } await first.ReleaseAsync(); - using (FileContentStore next = await FileContentPreparation.PrepareAsync(source, - new FileContentCacheOptions(cacheRoot))) - { + using (FileContentStore next = await FileContentPreparation.PrepareAsync( + source, + new FileContentCacheOptions(cacheRoot) + )) { Assert.True(Directory.Exists(oldDirectory)); } await second.ReleaseAsync(); - using FileContentStore final = await FileContentPreparation.PrepareAsync(source, - new FileContentCacheOptions(cacheRoot)); + using FileContentStore final = await FileContentPreparation.PrepareAsync( + source, + new FileContentCacheOptions(cacheRoot) + ); Assert.False(Directory.Exists(oldDirectory)); Assert.Single(Directory.GetDirectories(Path.Combine(cache, "generations"))); } @@ -84,7 +88,7 @@ private sealed class Probe(Process process) : IAsyncDisposable internal async Task ReadLineAsync() => await process.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(30)) - ?? throw new InvalidOperationException("The cache probe exited before reporting its state."); + ?? throw new InvalidOperationException("The cache probe exited before reporting its state."); internal async Task ReleaseAsync() { diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCachePublicationTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCachePublicationTests.cs index 5d1059da7..c604a049f 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCachePublicationTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCachePublicationTests.cs @@ -2,9 +2,9 @@ using System.IO; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Content; using Inno.Core.IO; -using Xunit; namespace Inno.Adapter.Content.FileSystem.Tests; @@ -33,10 +33,14 @@ await Assert.ThrowsAsync(() => public async Task AWriterLeaseEnforcesBoundedWaitingAndCancellationWithoutChangingContent() { using var fixture = new ContentCacheFixture(); - using FileLease writer = await FileLease.AcquireAsync(Path.Combine(fixture.cache, "install.lock"), - TimeSpan.Zero); - await Assert.ThrowsAsync(() => FileContentPreparation.PrepareAsync(fixture.source, - new FileContentCacheOptions(fixture.root, TimeSpan.FromMilliseconds(40))).AsTask()); + using FileLease writer = await FileLease.AcquireAsync( + Path.Combine(fixture.cache, "install.lock"), + TimeSpan.Zero + ); + await Assert.ThrowsAsync(() => FileContentPreparation.PrepareAsync( + fixture.source, + new FileContentCacheOptions(fixture.root, TimeSpan.FromMilliseconds(40)) + ).AsTask()); using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(40)); await Assert.ThrowsAnyAsync(() => FileContentPreparation.PrepareAsync(fixture.source, fixture.options, cancellation.Token).AsTask()); diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs index 800789d02..6bb53c8ac 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs @@ -1,7 +1,7 @@ using System.IO; using System.Threading.Tasks; -using Inno.Content; using Xunit; +using Inno.Content; namespace Inno.Adapter.Content.FileSystem.Tests; diff --git a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs index d7affd1ff..bf6f10186 100644 --- a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs @@ -1,5 +1,5 @@ -using System.Numerics; using System; +using System.Numerics; using System.Runtime.InteropServices; using Xunit; using Xunit.Abstractions; @@ -47,7 +47,9 @@ public void TextDisabled_UsesTheLoadedCimguiSymbol() _ = ImGui.Begin("Native Text Test", ref open); ReadOnlySpan text = "Plugin status\0"u8; fixed (byte* bytes = text) + { ImGui.Raw.TextDisabled((sbyte*)bytes); + } ImGui.End(); ImGui.Render(); } @@ -56,5 +58,4 @@ public void TextDisabled_UsesTheLoadedCimguiSymbol() ImGui.Raw.DestroyContext(context); } } - } diff --git a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs index 6cd2cbb01..0d4266a14 100644 --- a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs @@ -88,7 +88,7 @@ public void NativeViewportDispatchPreservesScalarsAndRejectsRetirementInsideCall io->ConfigFlags |= (int)ImGuiConfigFlags.ViewportsEnable; io->ConfigViewportsNoAutoMerge = 1; io->BackendFlags |= (int)(ImGuiBackendFlags.PlatformHasViewports - | ImGuiBackendFlags.RendererHasViewports | ImGuiBackendFlags.RendererHasTextures); + | ImGuiBackendFlags.RendererHasViewports | ImGuiBackendFlags.RendererHasTextures); io->Fonts->RendererHasTextures = 1; io->BackendRendererUserData = &state; ImGui.Raw.GetMainViewport()->PlatformHandle = (void*)1; @@ -147,7 +147,7 @@ float y var state = (CallbackState*)viewport->PlatformUserData; state->positions++; state->invalid |= x != viewport->Pos.X || y != viewport->Pos.Y - || ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(state->registration) != 0; + || ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(state->registration) != 0; } [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] @@ -159,7 +159,7 @@ float height var state = (CallbackState*)viewport->PlatformUserData; state->sizes++; state->invalid |= width != viewport->Size.X || height != viewport->Size.Y - || ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(state->registration) != 0; + || ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(state->registration) != 0; } [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] @@ -177,13 +177,13 @@ private static void DestroyWindow(ImGuiViewport* viewport) } [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] - private static void NoOp(ImGuiViewport* viewport) { } + private static void NoOp(ImGuiViewport* viewport) {} [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] private static void SetTitle( ImGuiViewport* viewport, sbyte* title - ) { } + ) {} [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] private static void GetPosition( diff --git a/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs b/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs index 856414a37..f84d2c884 100644 --- a/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs @@ -1,5 +1,5 @@ -using Xunit; using System; +using Xunit; using Xunit.Abstractions; namespace Inno.Native.ImGuizmo.Tests; diff --git a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs index cb843ab99..9b4117f15 100644 --- a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs +++ b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs @@ -17,5 +17,6 @@ internal EncodedAudioTestSource(byte[] bytes) public string contentHash { get; } public long length => m_bytes.LongLength; + public Stream OpenRead() => new MemoryStream(m_bytes, writable: false); } diff --git a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs index 68155baba..b260e4341 100644 --- a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs +++ b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs @@ -3,9 +3,9 @@ using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Audio; using Inno.Core.Execution; -using Xunit; namespace Inno.Adapter.Audio.MiniAudio.Tests; @@ -76,8 +76,9 @@ public void InvalidEncodingIdentityFailsPreparationWithoutLeakingTheSource() using var source = new GatedSource(CreateWave()) { contentHash = new string('A', 64) }; source.Release(); AudioClipHandle clip = backend.CreateClip(Describe(source, AudioClipLoadMode.Decode), source); - Assert.True(SpinWait.SpinUntil(() => backend.GetClipState(clip) != AudioClipState.Preparing, - TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => backend.GetClipState(clip) != AudioClipState.Preparing, TimeSpan.FromSeconds(5)) + ); Assert.Equal(AudioClipState.Failed, backend.GetClipState(clip)); Assert.Equal(1, source.closures); Assert.True(backend.DestroyClip(clip)); @@ -93,25 +94,28 @@ private static void WaitForReady( IAudioDevice backend, AudioClipHandle clip ) { - Assert.True(SpinWait.SpinUntil(() => backend.GetClipState(clip) != AudioClipState.Preparing, - TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => backend.GetClipState(clip) != AudioClipState.Preparing, TimeSpan.FromSeconds(5)) + ); Assert.Equal(AudioClipState.Ready, backend.GetClipState(clip)); } private static void Retire(Func cleanup) { - Assert.True(SpinWait.SpinUntil(() => - { - try - { - _ = cleanup(); - return true; - } - catch (RetirementPendingException) + Assert.True( + SpinWait.SpinUntil(() => { - return false; - } - }, TimeSpan.FromSeconds(5))); + try + { + _ = cleanup(); + return true; + } + catch (RetirementPendingException) + { + return false; + } + }, TimeSpan.FromSeconds(5)) + ); } private static byte[] CreateWave() @@ -173,7 +177,8 @@ private sealed class GatedStream : MemoryStream private readonly GatedSource m_owner; private bool m_closed; - internal GatedStream(GatedSource owner) : base(owner.m_bytes, writable: false) => m_owner = owner; + internal GatedStream(GatedSource owner) + : base(owner.m_bytes, writable: false) => m_owner = owner; public override async ValueTask ReadAsync( Memory buffer, diff --git a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs index d83d82807..ad1bda274 100644 --- a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs +++ b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.IO; using System.Threading; -using Inno.Audio; +using Xunit; using Inno.Adapter.Audio.MiniAudio; +using Inno.Audio; using Inno.Core.Mathematics; -using Xunit; namespace Inno.Adapter.Audio.MiniAudio.Tests; @@ -19,11 +19,18 @@ public void NativeAdmissionIncludesUndeliveredCompletionsAndReopensAfterDrain() { using var device = new MiniAudioDevice(new MiniAudioDeviceOptions { - noDevice = true, limits = new AudioDeviceLimits(clips: 1, voices: 1, buses: 1) + noDevice = true, + limits = new AudioDeviceLimits(clips: 1, voices: 1, buses: 1) }); IAudioDevice backend = device; - var descriptor = new AudioClipDescriptor(AudioCodecId.wav, AudioClipLoadMode.Decode, - 1, 48000, 4800, new FileInfo(path).Length); + var descriptor = new AudioClipDescriptor( + AudioCodecId.wav, + AudioClipLoadMode.Decode, + 1, + 48000, + 4800, + new FileInfo(path).Length + ); var source = new EncodedAudioTestSource(File.ReadAllBytes(path)); AudioClipHandle clip = backend.CreateClip(descriptor, source); WaitForClip(backend, clip); @@ -41,7 +48,10 @@ public void NativeAdmissionIncludesUndeliveredCompletionsAndReopensAfterDrain() Assert.Equal(voice, completion.voice); } } - finally { File.Delete(path); } + finally + { + File.Delete(path); + } } [Fact] @@ -53,14 +63,27 @@ public void InvalidInputsDoNotAllocateNativeVoicesOrPoisonExistingPlayback() using var device = new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = true }); IAudioDevice backend = device; AudioBusHandle master = backend.CreateBus(AudioBusId.master); - AudioClipHandle clip = backend.CreateClip(new AudioClipDescriptor(AudioCodecId.wav, - AudioClipLoadMode.Decode, 1, 48000, 4800, new FileInfo(clipPath).Length),new EncodedAudioTestSource(File.ReadAllBytes(clipPath))); + AudioClipHandle clip = backend.CreateClip( + new AudioClipDescriptor( + AudioCodecId.wav, + AudioClipLoadMode.Decode, + 1, + 48000, + 4800, + new FileInfo(clipPath).Length + ), + new EncodedAudioTestSource(File.ReadAllBytes(clipPath)) + ); WaitForClip(backend, clip); Assert.False(backend.Play(clip, master, default).isValid); foreach (double invalid in new[] { double.NaN, double.PositiveInfinity, double.NegativeInfinity, -1d }) + { Assert.False(backend.Play(clip, master, AudioPlayOptions.defaultValue, invalid).isValid); + } foreach (float invalid in new[] { float.NaN, float.PositiveInfinity, float.NegativeInfinity }) + { Assert.False(backend.SetBusVolume(master, invalid)); + } Assert.Equal(0, backend.statistics.activeVoices); AudioDeviceVoiceHandle voice = backend.Play(clip, master, new AudioPlayOptions(loop: true)); WaitForVoice(backend, voice); @@ -74,7 +97,10 @@ public void InvalidInputsDoNotAllocateNativeVoicesOrPoisonExistingPlayback() Assert.True(backend.DestroyClip(clip)); Assert.True(backend.DestroyBus(master)); } - finally { File.Delete(clipPath); } + finally + { + File.Delete(clipPath); + } } [Fact] @@ -92,37 +118,40 @@ public void HeadlessDeviceAdvancesNativeGraphAndCompletesVoice() }); IAudioDevice backend = device; AudioBusHandle master = backend.CreateBus(AudioBusId.master); - AudioClipHandle clip = backend.CreateClip(new AudioClipDescriptor( - AudioCodecId.wav, - AudioClipLoadMode.Decode, - 1, - 48000, - 2400, - new FileInfo(clipPath).Length),new EncodedAudioTestSource(File.ReadAllBytes(clipPath))); + AudioClipHandle clip = backend.CreateClip( + new AudioClipDescriptor( + AudioCodecId.wav, + AudioClipLoadMode.Decode, + 1, + 48000, + 2400, + new FileInfo(clipPath).Length + ), + new EncodedAudioTestSource(File.ReadAllBytes(clipPath)) + ); WaitForClip(backend, clip); - AudioListenerHandle listener = backend.CreateListener(new AudioListenerState( - Vector3.ZERO, - Vector3.FORWARD, - Vector3.UP, - Vector3.ZERO)); + AudioListenerHandle listener = backend.CreateListener( + new AudioListenerState(Vector3.ZERO, Vector3.FORWARD, Vector3.UP, Vector3.ZERO) + ); AudioDeviceVoiceHandle voice = backend.Play( clip, master, - new AudioPlayOptions(spatial: new AudioSpatialOptions( - new Vector3(2f, 0f, 0f), - Vector3.FORWARD, - Vector3.ZERO)), - null); + new AudioPlayOptions( + spatial: new AudioSpatialOptions(new Vector3(2f, 0f, 0f), Vector3.FORWARD, Vector3.ZERO) + ), + null + ); WaitForVoice(backend, voice); Assert.Equal(AudioDeviceState.Muted, backend.state); Assert.Equal(2, backend.capabilities.maxListeners); Assert.True(voice.isValid); - Assert.True(backend.SetListener(listener, new AudioListenerState( - new Vector3(1f, 0f, 0f), - Vector3.FORWARD, - Vector3.UP, - Vector3.ZERO))); + Assert.True( + backend.SetListener( + listener, + new AudioListenerState(new Vector3(1f, 0f, 0f), Vector3.FORWARD, Vector3.UP, Vector3.ZERO) + ) + ); backend.Update(0.1f); @@ -153,21 +182,28 @@ public void StandardProcessorsAndScheduledControlsUseNativeNodes() AudioBusHandle master = backend.CreateBus(AudioBusId.master); AudioBusHandle effects = backend.CreateBus(new AudioBusId("test.effects"), master); foreach (AudioProcessorId processorId in StandardProcessors()) + { Assert.True(backend.AddBusProcessor(effects, CreateProcessor(processorId))); + } - AudioClipHandle clip = backend.CreateClip(new AudioClipDescriptor( - AudioCodecId.wav, - AudioClipLoadMode.Stream, - 1, - 48000, - 4800, - new FileInfo(clipPath).Length),new EncodedAudioTestSource(File.ReadAllBytes(clipPath))); + AudioClipHandle clip = backend.CreateClip( + new AudioClipDescriptor( + AudioCodecId.wav, + AudioClipLoadMode.Stream, + 1, + 48000, + 4800, + new FileInfo(clipPath).Length + ), + new EncodedAudioTestSource(File.ReadAllBytes(clipPath)) + ); WaitForClip(backend, clip); AudioDeviceVoiceHandle voice = backend.Play( clip, effects, new AudioPlayOptions(loop: true), - backend.dspTime + 0.05d); + backend.dspTime + 0.05d + ); WaitForVoice(backend, voice); Assert.True(backend.TryGetVoiceState(voice, out AudioPlaybackState scheduled)); @@ -202,19 +238,19 @@ public void MixerGenerationsCanOverlapUntilOldVoicesReleaseTheirGraph() IAudioDevice backend = device; AudioBusHandle oldMaster = backend.CreateBus(AudioBusId.master); AudioBusHandle oldMusic = backend.CreateBus(new AudioBusId("test.music"), oldMaster); - AudioClipHandle clip = backend.CreateClip(new AudioClipDescriptor( - AudioCodecId.wav, - AudioClipLoadMode.Decode, - 1, - 48000, - 48000, - new FileInfo(clipPath).Length),new EncodedAudioTestSource(File.ReadAllBytes(clipPath))); + AudioClipHandle clip = backend.CreateClip( + new AudioClipDescriptor( + AudioCodecId.wav, + AudioClipLoadMode.Decode, + 1, + 48000, + 48000, + new FileInfo(clipPath).Length + ), + new EncodedAudioTestSource(File.ReadAllBytes(clipPath)) + ); WaitForClip(backend, clip); - AudioDeviceVoiceHandle voice = backend.Play( - clip, - oldMusic, - new AudioPlayOptions(loop: true), - null); + AudioDeviceVoiceHandle voice = backend.Play(clip, oldMusic, new AudioPlayOptions(loop: true), null); AudioBusHandle newMaster = backend.CreateBus(AudioBusId.master); AudioBusHandle newMusic = backend.CreateBus(new AudioBusId("test.music"), newMaster); @@ -247,8 +283,12 @@ private static void WaitForVoice( IAudioDevice device, AudioDeviceVoiceHandle voice ) { - Assert.True(SpinWait.SpinUntil(() => device.TryGetVoiceState(voice, out AudioPlaybackState state) - && state != AudioPlaybackState.Preparing, TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => ( + device.TryGetVoiceState(voice, out AudioPlaybackState state) + && state != AudioPlaybackState.Preparing + ), TimeSpan.FromSeconds(5)) + ); } private static IEnumerable StandardProcessors() @@ -267,19 +307,23 @@ private static AudioProcessorConfiguration CreateProcessor(AudioProcessorId id) { if (id == AudioProcessorId.delay) { - return new AudioProcessorConfiguration(id, - [ - new AudioProcessorParameter(AudioParameterId.delayMilliseconds, 5f), - new AudioProcessorParameter(AudioParameterId.decay, 0.2f) - ]); + return new AudioProcessorConfiguration( + id, + [ + new AudioProcessorParameter(AudioParameterId.delayMilliseconds, 5f), + new AudioProcessorParameter(AudioParameterId.decay, 0.2f) + ] + ); } - return new AudioProcessorConfiguration(id, - [ - new AudioProcessorParameter(AudioParameterId.frequency, 1000f), - new AudioProcessorParameter(AudioParameterId.quality, 0.707f), - new AudioProcessorParameter(AudioParameterId.gainDecibels, 2f), - new AudioProcessorParameter(AudioParameterId.shelfSlope, 1f) - ]); + return new AudioProcessorConfiguration( + id, + [ + new AudioProcessorParameter(AudioParameterId.frequency, 1000f), + new AudioProcessorParameter(AudioParameterId.quality, 0.707f), + new AudioProcessorParameter(AudioParameterId.gainDecibels, 2f), + new AudioProcessorParameter(AudioParameterId.shelfSlope, 1f) + ] + ); } private static string CreateWaveFile(int frameCount) diff --git a/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs b/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs index a7b97d871..b1ebdfba8 100644 --- a/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs +++ b/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs @@ -1,11 +1,11 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Adapter.UI.RmlUi; using Inno.Adapter.UI.RmlUi.Authoring; using Inno.Assets; @@ -22,7 +22,6 @@ using Inno.UI; using Inno.UI.Assets; using Inno.UI.Runtime; -using Xunit; namespace Inno.Adapter.UI.RmlUi.Tests; @@ -47,7 +46,9 @@ public UiServiceTests() Directory.CreateDirectory(m_assets); m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(UiServiceTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(UiServiceTests).Assembly) + }); _ = Assembly.Load("Inno.UI.Assets"); _ = Assembly.Load("Inno.Text.Assets"); _ = Assembly.Load("Inno.Adapter.UI.RmlUi.Authoring"); @@ -64,7 +65,8 @@ public void ImporterPublishesValidatedUtf8Document() using AssetLoader loader = CreateLoader(); UiDocumentAsset document = Assert.IsType( - loader.Load(AssetPath.Project("Hud.rml"), typeof(UiDocumentAsset))); + loader.Load(AssetPath.Project("Hud.rml"), typeof(UiDocumentAsset)) + ); Assert.Equal(markup, Assert.IsType(document.source).text); Assert.Equal(RmlUiIdentifiers.documentLanguage, document.source.language); @@ -75,19 +77,23 @@ public void ImporterPublishesValidatedUtf8Document() public void RmlFrontendScopesFontFamiliesAndHonorsNone() { var frontend = new RmlUiDocumentFrontend(); - UiDocumentAnalysis first = frontend.Analyze(new("Hud.rml", """ + UiDocumentAnalysis first = frontend.Analyze( + new("Hud.rml", """ - """)); - UiDocumentAnalysis second = frontend.Analyze(new("Other.rml", """ + """) + ); + UiDocumentAnalysis second = frontend.Analyze( + new("Other.rml", """ - """)); + """) + ); Assert.True(first.succeeded); Assert.True(second.succeeded); UiDocumentFontDeclaration face = Assert.Single(first.fonts); @@ -104,10 +110,13 @@ public void UndeclaredFontFamilyProducesNoGlyphDraw() using var backend = new RmlUiBackend(); backend.RegisterFont(new(File.ReadAllBytes(FontPath()), 0, "Declared", TextFontStyle.Normal, 400)); UiContextHandle context = backend.CreateContext(new UiContextOptions("missing-font", 320, 180)); - UiDocumentHandle document = backend.LoadDocument(context, Rml(""" + UiDocumentHandle document = backend.LoadDocument( + context, + Rml(""" Invisible text - """)); + """) + ); backend.ShowDocument(context, document); backend.Update(context, EmptyInput()); Assert.Empty(backend.Render(context).commands); @@ -118,13 +127,16 @@ public void ElementHitTestIgnoresBlankCanvasAndPointerEventsNone() { using var backend = new RmlUiBackend(); UiContextHandle context = backend.CreateContext(new UiContextOptions("hit-test", 320, 180)); - UiDocumentHandle document = backend.LoadDocument(context, Rml(""" + UiDocumentHandle document = backend.LoadDocument( + context, + Rml("""
- """)); + """) + ); backend.ShowDocument(context, document); backend.Update(context, EmptyInput()); Assert.True(backend.HasElementAtPoint(context, new Inno.Core.Mathematics.Vector2(30f, 30f))); @@ -141,16 +153,26 @@ public void SwitchingDocumentFamiliesThroughNoneDoesNotReuseOldGlyphs() UiContextHandle context = backend.CreateContext(new UiContextOptions("font-switch", 320, 180)); foreach ((string family, bool visible) in new[] { - ("A", true), ("B", true), ("none", false), ("A", true) - }) - { - string face = family == "none" ? string.Empty : - $"@font-face {{ font-family: {family}; src: url(Lato.ttf); font-weight: 400; }}"; - UiDocumentAnalysis analysis = frontend.Analyze(new("FontSwitch.rml", - $"Visible text")); + ("A", true), + ("B", true), + ("none", false), + ("A", true) + } + ) { + string face = family == "none" + ? string.Empty + : $"@font-face {{ font-family: {family}; src: url(Lato.ttf); font-weight: 400; }}"; + UiDocumentAnalysis analysis = frontend.Analyze( + new( + "FontSwitch.rml", + $"Visible text" + ) + ); Assert.True(analysis.succeeded); foreach (UiDocumentFontDeclaration declaration in analysis.fonts) + { backend.RegisterFont(new(font, 0, declaration.family, declaration.style, declaration.weight)); + } UiDocumentHandle document = backend.LoadDocument(context, Rml(analysis.text!)); backend.ShowDocument(context, document); backend.Update(context, EmptyInput()); @@ -163,13 +185,20 @@ public void SwitchingDocumentFamiliesThroughNoneDoesNotReuseOldGlyphs() public void CssWeightSelectsDifferentFacesOfOneDeclaredFamily() { using var backend = new RmlUiBackend(); - backend.RegisterFont(new(File.ReadAllBytes(FontPath()), 0, - "WeightFamily", TextFontStyle.Normal, 400)); - backend.RegisterFont(new(File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, - "TestData", "LatoLatin-Bold.ttf")), 0, - "WeightFamily", TextFontStyle.Normal, 700)); + backend.RegisterFont(new(File.ReadAllBytes(FontPath()), 0, "WeightFamily", TextFontStyle.Normal, 400)); + backend.RegisterFont( + new( + File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "TestData", "LatoLatin-Bold.ttf")), + 0, + "WeightFamily", + TextFontStyle.Normal, + 700 + ) + ); UiContextHandle context = backend.CreateContext(new UiContextOptions("weight-selection", 640, 240)); - UiDocumentHandle document = backend.LoadDocument(context, Rml(""" + UiDocumentHandle document = backend.LoadDocument( + context, + Rml("""
Panel
- """)); + """) + ); backend.ShowDocument(context, document); backend.Update(context, EmptyInput()); Assert.NotEmpty(backend.Render(context).commands); @@ -313,14 +354,15 @@ public void NativeHandlesCannotAliasAfterContextOrBackendRetirement() using (var first = new RmlUiBackend()) { retired = first.CreateContext(new UiContextOptions("first", 128, 128)); - retiredDocument = first.LoadDocument(retired, Rml( - "
First
")); + retiredDocument = first.LoadDocument(retired, Rml("
First
")); } using var second = new RmlUiBackend(); UiContextHandle current = second.CreateContext(new UiContextOptions("second", 128, 128)); - UiDocumentHandle currentDocument = second.LoadDocument(current, Rml( - "
Second
")); + UiDocumentHandle currentDocument = second.LoadDocument( + current, + Rml("
Second
") + ); Assert.NotEqual(retired, current); Assert.NotEqual(retiredDocument, currentDocument); @@ -336,20 +378,19 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private AssetLoader CreateLoader() => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, m_assets, m_library); - private static UiInputSnapshot EmptyInput() - => new(default, default, KeyModifier.None, [], [], [], [], []); + private static UiInputSnapshot EmptyInput() => new(default, default, KeyModifier.None, [], [], [], [], []); - private static UiDocumentSource Rml(string text) - => new(RmlUiIdentifiers.documentLanguage, text); + private static UiDocumentSource Rml(string text) => new(RmlUiIdentifiers.documentLanguage, text); - private static string FontPath() - => Path.Combine(AppContext.BaseDirectory, "TestData", "LatoLatin-Regular.ttf"); + private static string FontPath() => Path.Combine(AppContext.BaseDirectory, "TestData", "LatoLatin-Regular.ttf"); private sealed class RetainingArtifactLookup(AssetLoader loader) : AssetResidencyProvider, IAssetArtifactLookup { @@ -382,7 +423,6 @@ public bool TryGetArtifact( Guid persistentId, string outputName, out AssetArtifactInfo? artifact - ) - => loader.TryGetArtifact(persistentId, outputName, out artifact); + ) => loader.TryGetArtifact(persistentId, outputName, out artifact); } } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs index 818f0df57..a4cc13c52 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs @@ -1,9 +1,9 @@ using System; -using Inno.Integration.WindowsX64.Sdl3; +using Xunit; using Inno.Adapter.Platform; +using Inno.Integration.WindowsX64.Sdl3; using Inno.Native.Sdl3; using Inno.Platform; -using Xunit; [assembly: CollectionBehavior(DisableTestParallelization = true)] @@ -22,12 +22,19 @@ public void MissingHostIsRejectedBeforeSdkInitialization() public void WrappingFailureDestroysOnlyTheNewlyOwnedWindow() { if (NativeWindowTestHost.RunIfRequired(nameof(HostIntegrationTests) + "." + nameof(WrappingFailureDestroysOnlyTheNewlyOwnedWindow))) + { return; + } var host = new FailingHost(); using var app = new Sdl3PlatformApplication(host); Assert.Throws(() => app.CreateWindow(new PlatformWindowOptions - { title = "Failed surface", width = 40, height = 40, visible = false })); + { + title = "Failed surface", + width = 40, + height = 40, + visible = false + })); Assert.Empty(app.GetWindows()); Assert.True(SDL.Raw.GetWindowFromId(host.lastId) == null); } @@ -35,13 +42,21 @@ public void WrappingFailureDestroysOnlyTheNewlyOwnedWindow() [Fact] public void SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain() { - if (NativeWindowTestHost.RunIfRequired(nameof(HostIntegrationTests) + "." + nameof(SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain))) + if (NativeWindowTestHost.RunIfRequired( + nameof(HostIntegrationTests) + "." + nameof(SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain) + )) { return; + } var host = new FailingHost { failSurface = false }; using var app = new Sdl3PlatformApplication(host); using var window = app.CreateWindow(new PlatformWindowOptions - { title = "Single surface", width = 40, height = 40, visible = false }); + { + title = "Single surface", + width = 40, + height = 40, + visible = false + }); Assert.Throws(() => app.CreateWindow(new PlatformWindowOptions())); Assert.Equal(1, host.calls); } @@ -53,7 +68,9 @@ private sealed class FailingHost : ISdl3HostIntegration internal uint lastId; internal int calls; public Sdl3HostCapabilities capabilities { get; } = new(multipleWindows: false, liveResize: false); + public void ConfigureInitialization() => m_inner.ConfigureInitialization(); + public nint CreateWindow(PlatformWindowOptions options) { calls++; @@ -61,8 +78,12 @@ public nint CreateWindow(PlatformWindowOptions options) lastId = SDL.Raw.GetWindowId((SDLWindow*)handle); return handle; } - public PlatformNativeHandles ResolveNativeSurface(nint windowHandle) => failSurface - ? throw new InvalidOperationException("Injected surface inspection failure.") : m_inner.ResolveNativeSurface(windowHandle); + + public PlatformNativeHandles ResolveNativeSurface(nint windowHandle) + => failSurface + ? throw new InvalidOperationException("Injected surface inspection failure.") + : m_inner.ResolveNativeSurface(windowHandle); + public bool GetInitialFocus(nint windowHandle) => false; } } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeHostFixture.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeHostFixture.cs index 47e73b481..605ac5f5c 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeHostFixture.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeHostFixture.cs @@ -1,15 +1,16 @@ using System; using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.WindowsX64.Sdl3; using Inno.Integration.MacOSArm64.Sdl3; +using Inno.Integration.WindowsX64.Sdl3; namespace Inno.Adapter.Platform.Sdl3.Tests; internal static class NativeHostFixture { - internal static ISdl3HostIntegration Create() => OperatingSystem.IsWindows() - ? new WindowsX64Sdl3HostIntegration() - : OperatingSystem.IsMacOS() - ? new MacOSArm64Sdl3HostIntegration() - : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); + internal static ISdl3HostIntegration Create() + => OperatingSystem.IsWindows() + ? new WindowsX64Sdl3HostIntegration() + : OperatingSystem.IsMacOS() + ? new MacOSArm64Sdl3HostIntegration() + : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeSurfaceLifetimeTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeSurfaceLifetimeTests.cs index 000e3fcd8..6145cf09a 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeSurfaceLifetimeTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeSurfaceLifetimeTests.cs @@ -1,7 +1,7 @@ using System; +using Xunit; using Inno.Adapter.Platform; using Inno.Platform; -using Xunit; namespace Inno.Adapter.Platform.Sdl3.Tests; @@ -10,8 +10,11 @@ public sealed class NativeSurfaceLifetimeTests [Fact] public void DisposedWindowRejectsBorrowingItsNativeSurface() { - if (NativeWindowTestHost.RunIfRequired(nameof(NativeSurfaceLifetimeTests) + "." + nameof(DisposedWindowRejectsBorrowingItsNativeSurface))) + if (NativeWindowTestHost.RunIfRequired( + nameof(NativeSurfaceLifetimeTests) + "." + nameof(DisposedWindowRejectsBorrowingItsNativeSurface) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { @@ -21,7 +24,10 @@ public void DisposedWindowRejectsBorrowingItsNativeSurface() visible = false }); INativeWindowSurface surface = window; - Assert.Equal(OperatingSystem.IsWindows() ? PlatformNativeHandleId.win32 : PlatformNativeHandleId.cocoa, surface.nativeHandles.handleKind); + Assert.Equal( + OperatingSystem.IsWindows() ? PlatformNativeHandleId.win32 : PlatformNativeHandleId.cocoa, + surface.nativeHandles.handleKind + ); Assert.NotEqual(IntPtr.Zero, surface.nativeHandles.windowHandle); window.Dispose(); Assert.Throws(() => surface.nativeHandles); diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeWindowTestHost.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeWindowTestHost.cs index adcd65adb..d79e4be30 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeWindowTestHost.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/NativeWindowTestHost.cs @@ -8,23 +8,39 @@ internal static class NativeWindowTestHost { private static readonly IReadOnlyDictionary S_CONTRACTS = new Dictionary { - ["NativeSurfaceLifetimeTests.DisposedWindowRejectsBorrowingItsNativeSurface"] = () => new NativeSurfaceLifetimeTests().DisposedWindowRejectsBorrowingItsNativeSurface(), - ["HostIntegrationTests.WrappingFailureDestroysOnlyTheNewlyOwnedWindow"] = () => new HostIntegrationTests().WrappingFailureDestroysOnlyTheNewlyOwnedWindow(), - ["HostIntegrationTests.SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain"] = () => new HostIntegrationTests().SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain(), - ["WindowOwnershipTests.ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows"] = () => new WindowOwnershipTests().ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows(), - ["WindowOwnershipTests.AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt"] = () => new WindowOwnershipTests().AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt(), - ["WindowOwnershipTests.CrossApplicationReleaseAndCrossThreadCreationAreRejected"] = () => new WindowOwnershipTests().CrossApplicationReleaseAndCrossThreadCreationAreRejected(), - ["WindowSurfaceTests.OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution"] = () => new WindowSurfaceTests().OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution(), - ["Sdl3WindowOperationsTests.CreationPreservesOptionsAndLeavesRegistrationToTheOwner.False.False"] = () => new Sdl3WindowOperationsTests().CreationPreservesOptionsAndLeavesRegistrationToTheOwner(false, false), - ["Sdl3WindowOperationsTests.CreationPreservesOptionsAndLeavesRegistrationToTheOwner.True.True"] = () => new Sdl3WindowOperationsTests().CreationPreservesOptionsAndLeavesRegistrationToTheOwner(true, true), + ["NativeSurfaceLifetimeTests.DisposedWindowRejectsBorrowingItsNativeSurface"] = () => new NativeSurfaceLifetimeTests() + .DisposedWindowRejectsBorrowingItsNativeSurface(), + ["HostIntegrationTests.WrappingFailureDestroysOnlyTheNewlyOwnedWindow"] = () => new HostIntegrationTests() + .WrappingFailureDestroysOnlyTheNewlyOwnedWindow(), + ["HostIntegrationTests.SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain"] = () => new HostIntegrationTests() + .SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain(), + ["WindowOwnershipTests.ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows"] = () => new WindowOwnershipTests() + .ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows(), + ["WindowOwnershipTests.AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt"] = () => new WindowOwnershipTests() + .AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt(), + ["WindowOwnershipTests.CrossApplicationReleaseAndCrossThreadCreationAreRejected"] = () => new WindowOwnershipTests() + .CrossApplicationReleaseAndCrossThreadCreationAreRejected(), + ["WindowSurfaceTests.OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution"] = () => new WindowSurfaceTests() + .OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution(), + ["Sdl3WindowOperationsTests.CreationPreservesOptionsAndLeavesRegistrationToTheOwner.False.False"] = () => new Sdl3WindowOperationsTests().CreationPreservesOptionsAndLeavesRegistrationToTheOwner( + false, + false + ), + ["Sdl3WindowOperationsTests.CreationPreservesOptionsAndLeavesRegistrationToTheOwner.True.True"] = () => new Sdl3WindowOperationsTests().CreationPreservesOptionsAndLeavesRegistrationToTheOwner( + true, + true + ) }; + private static bool m_executingContract; internal static bool RunIfRequired(string contract) { if (m_executingContract || !OperatingSystem.IsMacOS() - && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1") + && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1" + ) { return false; + } NativeProcessTestHost.Run(typeof(NativeWindowTestHost).Assembly.Location, contract); return true; } @@ -34,7 +50,9 @@ private static int Main(string[] arguments) try { if (arguments.Length != 1 || !S_CONTRACTS.TryGetValue(arguments[0], out Action? contract)) + { throw new ArgumentException("The native test host requires one declared contract."); + } // Cocoa requires the process main thread, rather than an xUnit worker or a new managed thread. m_executingContract = true; Console.Error.WriteLine($"Native contract started: {arguments[0]}; thread={Environment.CurrentManagedThreadId}."); diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs index fe64cfb7e..6d44cb1f1 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs @@ -1,9 +1,9 @@ using System; using System.Runtime.InteropServices; +using Xunit; using Inno.Integration.WindowsX64.Sdl3; using Inno.Native.Sdl3; using Inno.Platform; -using Xunit; namespace Inno.Adapter.Platform.Sdl3.Tests; @@ -16,8 +16,17 @@ public void CreationPreservesOptionsAndLeavesRegistrationToTheOwner( bool resizable, bool highPixelDensity ) { - if (NativeWindowTestHost.RunIfRequired(nameof(Sdl3WindowOperationsTests) + "." + nameof(CreationPreservesOptionsAndLeavesRegistrationToTheOwner) + "." + resizable + "." + highPixelDensity)) + if (NativeWindowTestHost.RunIfRequired( + nameof(Sdl3WindowOperationsTests) + + "." + + nameof(CreationPreservesOptionsAndLeavesRegistrationToTheOwner) + + "." + + resizable + + "." + + highPixelDensity + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); var options = new PlatformWindowOptions @@ -44,8 +53,7 @@ bool highPixelDensity Assert.True((flags & SDLWindowFlags.Hidden) != 0); Assert.Equal(resizable, (flags & SDLWindowFlags.Resizable) != 0); Assert.Equal(highPixelDensity, (flags & SDLWindowFlags.HighPixelDensity) != 0); - Assert.Equal((flags & SDLWindowFlags.InputFocus) != 0, - Sdl3WindowOperations.ReadFocus((nint)native)); + Assert.Equal((flags & SDLWindowFlags.InputFocus) != 0, Sdl3WindowOperations.ReadFocus((nint)native)); } finally { @@ -58,7 +66,9 @@ bool highPixelDensity public void InvalidInputFailsBeforeCreatingAWindow() { Assert.Throws(() => Sdl3WindowOperations.CreateWindow( - new PlatformWindowOptions { width = 0 }, requireOpenGl: false)); + new PlatformWindowOptions { width = 0 }, + requireOpenGl: false + )); Assert.Throws(() => Sdl3WindowOperations.ReadFocus(0)); } } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs index 1765ec9b2..28644b15d 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs @@ -1,9 +1,9 @@ using System; using System.Threading.Tasks; +using Xunit; using Inno.Integration.WindowsX64.Sdl3; using Inno.Native.Sdl3; using Inno.Platform; -using Xunit; namespace Inno.Adapter.Platform.Sdl3.Tests; @@ -12,13 +12,21 @@ public sealed unsafe class WindowOwnershipTests [Fact] public void ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows() { - if (NativeWindowTestHost.RunIfRequired(nameof(WindowOwnershipTests) + "." + nameof(ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows))) + if (NativeWindowTestHost.RunIfRequired( + nameof(WindowOwnershipTests) + "." + nameof(ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows) + )) { return; + } using var first = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var second = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = first.CreateWindow(new PlatformWindowOptions - { title = "Owned surface", width = 40, height = 40, visible = false }); + { + title = "Owned surface", + width = 40, + height = 40, + visible = false + }); Assert.Single(first.GetWindows()); Assert.Empty(second.GetWindows()); window.Dispose(); @@ -29,14 +37,19 @@ public void ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows() [Fact] public void AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt() { - if (NativeWindowTestHost.RunIfRequired(nameof(WindowOwnershipTests) + "." + nameof(AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt))) + if (NativeWindowTestHost.RunIfRequired( + nameof(WindowOwnershipTests) + "." + nameof(AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt) + )) { return; + } using var app = new Sdl3PlatformApplication(NativeHostFixture.Create()); ReadOnlySpan title = "Borrowed surface\0"u8; SDLWindow* native; fixed (byte* bytes = title) + { native = SDL.Raw.CreateWindow((sbyte*)bytes, 40, 40, (ulong)SDLWindowFlags.Hidden); + } Assert.True(native != null); uint id = SDL.Raw.GetWindowId(native); try @@ -63,15 +76,25 @@ public void AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt() [Fact] public void CrossApplicationReleaseAndCrossThreadCreationAreRejected() { - if (NativeWindowTestHost.RunIfRequired(nameof(WindowOwnershipTests) + "." + nameof(CrossApplicationReleaseAndCrossThreadCreationAreRejected))) + if (NativeWindowTestHost.RunIfRequired( + nameof(WindowOwnershipTests) + "." + nameof(CrossApplicationReleaseAndCrossThreadCreationAreRejected) + )) { return; + } using var first = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var second = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = first.CreateWindow(new PlatformWindowOptions - { title = "Thread owner", width = 40, height = 40, visible = false }); + { + title = "Thread owner", + width = 40, + height = 40, + visible = false + }); Assert.Throws(() => second.ReleaseWindow(window)); - Assert.Throws(() => Task.Run(() => first.CreateWindow(new PlatformWindowOptions())).GetAwaiter().GetResult()); + Assert.Throws( + () => Task.Run(() => first.CreateWindow(new PlatformWindowOptions())).GetAwaiter().GetResult() + ); Assert.Single(first.GetWindows()); } } diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs index 2d11f45b0..a5260a350 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs @@ -1,8 +1,8 @@ using System; -using Inno.Integration.WindowsX64.Sdl3; +using Xunit; using Inno.Adapter.Platform; +using Inno.Integration.WindowsX64.Sdl3; using Inno.Platform; -using Xunit; namespace Inno.Adapter.Platform.Sdl3.Tests; @@ -11,15 +11,26 @@ public sealed class WindowSurfaceTests [Fact] public void OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution() { - if (NativeWindowTestHost.RunIfRequired(nameof(WindowSurfaceTests) + "." + nameof(OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution))) + if (NativeWindowTestHost.RunIfRequired( + nameof(WindowSurfaceTests) + "." + nameof(OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution) + )) { return; + } var host = NativeHostFixture.Create(); using var app = new Sdl3PlatformApplication(host); using var window = app.CreateWindow(new PlatformWindowOptions - { title = "Surface contract", width = 40, height = 40, visible = false }); + { + title = "Surface contract", + width = 40, + height = 40, + visible = false + }); Assert.Equal(host.ResolveNativeSurface(window.sdlWindowHandle), window.nativeHandles); - Assert.Equal(OperatingSystem.IsWindows() ? PlatformNativeHandleId.win32 : PlatformNativeHandleId.cocoa, window.nativeHandles.handleKind); + Assert.Equal( + OperatingSystem.IsWindows() ? PlatformNativeHandleId.win32 : PlatformNativeHandleId.cocoa, + window.nativeHandles.handleKind + ); Assert.True(window.pixelWidth > 0); Assert.True(window.pixelHeight > 0); } diff --git a/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/NativeDllLoaderTests.cs b/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/NativeDllLoaderTests.cs index 38d8a52b7..368d4e41e 100644 --- a/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/NativeDllLoaderTests.cs +++ b/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/NativeDllLoaderTests.cs @@ -3,8 +3,8 @@ using System.IO; using System.Runtime.InteropServices; using System.Runtime.Versioning; -using Inno.Native.LibraryLoading; using Xunit; +using Inno.Native.LibraryLoading; namespace Inno.Native.Sdl3.Tests; @@ -46,7 +46,9 @@ public void ExplicitDeploymentSupportsIndependentLibraryOwners() public void ExplicitDeploymentLoadsSdlNearTheWindowsPathLimit() { if (OperatingSystem.IsWindows()) + { LoadSdlFromDeepOutputDirectory(252, extendedRoot: false); + } } [Fact] @@ -55,7 +57,9 @@ public void ExplicitDeploymentLoadsSdlNearTheWindowsPathLimit() public void ExplicitDeploymentLoadsSdlBeyondTheWindowsPathLimit() { if (OperatingSystem.IsWindows()) + { LoadSdlFromDeepOutputDirectory(300, extendedRoot: false); + } } [Fact] @@ -64,7 +68,9 @@ public void ExplicitDeploymentLoadsSdlBeyondTheWindowsPathLimit() public void ExplicitDeploymentLoadsSdlWithAnExtendedWindowsRoot() { if (OperatingSystem.IsWindows()) + { LoadSdlFromDeepOutputDirectory(300, extendedRoot: true); + } } [Theory] @@ -104,8 +110,11 @@ bool extendedRoot string payload = Path.Combine(directory, fileName); File.Copy(source, payload); Assert.Equal(pathLength, payload.Length); - var deployment = new NativeDeploymentIndex("windows-x64", - new Dictionary { [C_LIBRARY_NAME] = fileName }, new Dictionary()); + var deployment = new NativeDeploymentIndex( + "windows-x64", + new Dictionary { [C_LIBRARY_NAME] = fileName }, + new Dictionary() + ); string selectedRoot = extendedRoot ? @"\\?\" + directory : directory; string library = NativeDeploymentIndex.Decode(deployment.Encode()).ResolveLibrary(selectedRoot, C_LIBRARY_NAME); nint module = NativeLibrary.Load(library, typeof(SDL).Assembly, null); diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs index cb3c10c64..c3d992dd4 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs @@ -27,7 +27,10 @@ public BindingDefinitionTests() [InlineData("")] public async Task ExecutableOrNonLiteralDefinitionsFailBeforeOutputCreation(string body) { - File.WriteAllText(Path.Combine(m_root, "bindings.props"), "fixture" + body + ""); + File.WriteAllText( + Path.Combine(m_root, "bindings.props"), + "fixture" + body + "" + ); var descriptor = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); var request = new NativeBindingGenerationRequest([descriptor], "fixture", NativeBindingOutputMode.HostSource); await Assert.ThrowsAsync(async () => await BindingTestProfiles.Generator() diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs index a9741bb75..ea8de06c1 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs @@ -30,7 +30,10 @@ public async Task SourceInputIdentityDetectsSelectedInputsWithoutGeneratingOrRea string config = Path.Combine(directory, "bindgen.json"); File.WriteAllText(Path.Combine(directory, "common.json"), "{\"schemaVersion\":2,\"api\":{\"name\":\"UnusedDefault\"}}"); string text = File.ReadAllText(config); - File.WriteAllText(config, text.Replace("\"schemaVersion\":2", "\"schemaVersion\":2,\"extends\":[\"common.json\"]", StringComparison.Ordinal)); + File.WriteAllText( + config, + text.Replace("\"schemaVersion\":2", "\"schemaVersion\":2,\"extends\":[\"common.json\"]", StringComparison.Ordinal) + ); string unselected = Path.Combine(directory, "bindgen.unselected.json"); File.WriteAllText(unselected, "{}"); var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); @@ -38,12 +41,18 @@ public async Task SourceInputIdentityDetectsSelectedInputsWithoutGeneratingOrRea NativeBuildContext initial = new(m_root, "release"); string identity = await generator.ComputeInputFingerprintAsync(initial, request, CancellationToken.None); File.WriteAllText(unselected, "{\"changed\":true}"); - Assert.Equal(identity, await generator.ComputeInputFingerprintAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); + Assert.Equal( + identity, + await generator.ComputeInputFingerprintAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None) + ); string shared = Path.Combine(m_root, "Source", "shared.h"); DateTime timestamp = File.GetLastWriteTimeUtc(shared); File.WriteAllText(shared, File.ReadAllText(shared).Replace("sample", "change", StringComparison.Ordinal)); File.SetLastWriteTimeUtc(shared, timestamp); - Assert.NotEqual(identity, await generator.ComputeInputFingerprintAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); + Assert.NotEqual( + identity, + await generator.ComputeInputFingerprintAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None) + ); Assert.Equal(0, initial.statistics.bindingGenerations); Assert.Equal(0, initial.statistics.bindingBatches); Assert.False(Directory.Exists(Path.Combine(directory, "obj"))); @@ -92,20 +101,32 @@ public async Task ActiveConsumersBlockReplacementAndReleaseAllowsRepair() await Assert.ThrowsAnyAsync(async () => { using BuildArtifactWriteLease mutation = await BuildArtifactWriteLease.AcquireAsync( - descriptor.artifactDirectory, descriptor.artifactOwnerDirectory, waiting.Token); + descriptor.artifactDirectory, + descriptor.artifactOwnerDirectory, + waiting.Token + ); }); using NativeBindingGenerationResult concurrent = await generator.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); Assert.Equal(descriptor.fingerprint, concurrent[component.nativeProject].fingerprint); first.Dispose(); concurrent.Dispose(); Assert.Throws(() => first[component.nativeProject]); using (BuildArtifactWriteLease mutation = await BuildArtifactWriteLease.AcquireAsync( - descriptor.artifactDirectory, descriptor.artifactOwnerDirectory)) + descriptor.artifactDirectory, + descriptor.artifactOwnerDirectory + )) { File.WriteAllText(descriptor.bindingsPath, "damaged"); + } using NativeBindingGenerationResult repaired = await generator.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); Assert.Equal(original, File.ReadAllText(repaired[component.nativeProject].bindingsPath)); } @@ -123,13 +144,19 @@ public async Task AFailedBatchPublishesNoPartialClosureAndPreservesEarlierOutput string config = Path.Combine(m_root, "second", "bindgen.json"); File.WriteAllText(config, File.ReadAllText(config).Replace("../Source/shared.h", "broken.h", StringComparison.Ordinal)); await Assert.ThrowsAnyAsync(async () => await generator.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + )); Assert.Equal(original, File.ReadAllText(completed[first.nativeProject].bindingsPath)); Assert.Single(Directory.GetDirectories(Path.Combine(m_root, "artifacts", "bindings", "first", "fixture"))); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(async () => await generator.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, cancellation.Token)); + new NativeBuildContext(m_root, "release"), + request, + cancellation.Token + )); } [Fact] @@ -164,7 +191,10 @@ public async Task MissingSelectedSdkFailsBeforeCreatingCandidatesAndPreservesPub string source = File.ReadAllText(result[component.nativeProject].bindingsPath); var failure = await Assert.ThrowsAsync(async () => await generator.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + )); Assert.Contains("owned.h", failure.Message); Assert.Equal(source, File.ReadAllText(result[component.nativeProject].bindingsPath)); @@ -197,9 +227,17 @@ string sdk ) { string executable = Path.Combine(m_root, "sdk-tool.exe"); File.WriteAllText(executable, "Selected SDK tool identity; not executed by this C parser fixture."); - var selection = new NativeToolchainSelection("fixture", new BuildHostDescriptor("Windows", "x64"), + var selection = new NativeToolchainSelection( + "fixture", + new BuildHostDescriptor("Windows", "x64"), new Dictionary { ["fixture"] = executable }, - new Dictionary { [variable] = sdk, ["INCLUDE"] = Path.Combine(sdk, "include") }, [sdk], [], new NativeLinkPlan(".dll"), false, new NativeCompilerInputs(systemIncludeDirectories: [Path.Combine(sdk, "include")])); + new Dictionary { [variable] = sdk, ["INCLUDE"] = Path.Combine(sdk, "include") }, + [sdk], + [], + new NativeLinkPlan(".dll"), + false, + new NativeCompilerInputs(systemIncludeDirectories: [Path.Combine(sdk, "include")]) + ); return new NativeBuildContext(m_root, "release").WithToolchain(selection); } @@ -217,7 +255,11 @@ private NativeComponentDescriptor CreateComponent(string name) "api":{"namespace":"Fixture.Native","name":"Api","naming":{"functions":{"casing":"pascal"}}}, "output":{"root":"Generated","layout":"singleFile"}} """); - return new NativeComponentDescriptor(name, name + "/" + name + ".csproj", name + "/" + name + ".csproj", - bindingDefinition: name + "/bindings.props"); + return new NativeComponentDescriptor( + name, + name + "/" + name + ".csproj", + name + "/" + name + ".csproj", + bindingDefinition: name + "/bindings.props" + ); } } diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs index 51c928f29..aba6a695b 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs @@ -5,8 +5,8 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Bindings.Tests; @@ -29,10 +29,18 @@ public async Task DictionaryMappingsRemainStableAcrossIndependentProcesses() string? inherited = Environment.GetEnvironmentVariable(C_ROOT); if (inherited is not null) { - var component = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); + var component = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); string identity = await BindingTestProfiles.Generator().ComputeInputFingerprintAsync( - new NativeBuildContext(inherited, "release"), request, CancellationToken.None); + new NativeBuildContext(inherited, "release"), + request, + CancellationToken.None + ); File.WriteAllText(Environment.GetEnvironmentVariable(C_OUTPUT)!, identity); return; } @@ -43,10 +51,17 @@ public async Task DictionaryMappingsRemainStableAcrossIndependentProcesses() { File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), string.Empty); File.WriteAllText(Path.Combine(root, "Fixture.csproj"), ""); - File.WriteAllText(Path.Combine(root, "bindings.props"), "fixturebindgen.json"); + File.WriteAllText( + Path.Combine(root, "bindings.props"), + "fixturebindgen.json" + ); Directory.CreateDirectory(Path.Combine(root, "Native")); - File.WriteAllLines(Path.Combine(root, "Native", "fixture.h"), Enumerable.Range(0, 64).Select(static index => $"int sample_{index}(int value);")); - var names = Enumerable.Range(0, 64).ToDictionary(static index => $"sample_{index}", static index => $"Sample{index}", StringComparer.Ordinal); + File.WriteAllLines( + Path.Combine(root, "Native", "fixture.h"), + Enumerable.Range(0, 64).Select(static index => $"int sample_{index}(int value);") + ); + var names = Enumerable.Range(0, 64) + .ToDictionary(static index => $"sample_{index}", static index => $"Sample{index}", StringComparer.Ordinal); WriteConfiguration(root, names); string first = await RunHost(root, "first"); string second = await RunHost(root, "second"); @@ -64,14 +79,17 @@ public async Task DictionaryMappingsRemainStableAcrossIndependentProcesses() private static void WriteConfiguration( string root, Dictionary names - ) => File.WriteAllText(Path.Combine(root, "bindgen.json"), JsonSerializer.Serialize(new - { - schemaVersion = 2, - library = new { id = "fixture", nativeName = "fixture" }, - source = new { language = "c", headers = new[] { "Native/fixture.h" }, includeDirectories = new[] { "Native" } }, - api = new { @namespace = "Fixture.Native", name = "Api", names }, - output = new { layout = "singleFile", singleFileName = "Bindings.cs", root = "Generated" } - })); + ) => File.WriteAllText( + Path.Combine(root, "bindgen.json"), + JsonSerializer.Serialize(new + { + schemaVersion = 2, + library = new { id = "fixture", nativeName = "fixture" }, + source = new { language = "c", headers = new[] { "Native/fixture.h" }, includeDirectories = new[] { "Native" } }, + api = new { @namespace = "Fixture.Native", name = "Api", names }, + output = new { layout = "singleFile", singleFileName = "Bindings.cs", root = "Generated" } + }) + ); private static async Task RunHost( string root, @@ -80,13 +98,29 @@ string name string dotnet = ToolchainEnvironment.ResolveExecutable(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet"); string output = Path.Combine(root, name + ".identity"); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - await ToolchainEnvironment.RunAsync(dotnet, - ["test", typeof(BindingGenerationProcessTests).Assembly.Location, - "--filter", "FullyQualifiedName=" + typeof(BindingGenerationProcessTests).FullName + "." + nameof(DictionaryMappingsRemainStableAcrossIndependentProcesses), - "--results-directory", Path.Combine(root, "results"), - "--logger", "trx;LogFileName=" + name + ".trx", - "--environment", C_ROOT + "=" + root, "--environment", C_OUTPUT + "=" + output], - root, timeout.Token, DotNetSdkEnvironment.Create(dotnet)); + await ToolchainEnvironment.RunAsync( + dotnet, + [ + "test", + typeof(BindingGenerationProcessTests).Assembly.Location, + "--filter", + "FullyQualifiedName=" + + typeof(BindingGenerationProcessTests).FullName + + "." + + nameof(DictionaryMappingsRemainStableAcrossIndependentProcesses), + "--results-directory", + Path.Combine(root, "results"), + "--logger", + "trx;LogFileName=" + name + ".trx", + "--environment", + C_ROOT + "=" + root, + "--environment", + C_OUTPUT + "=" + output + ], + root, + timeout.Token, + DotNetSdkEnvironment.Create(dotnet) + ); return File.ReadAllText(output); } } diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingMaterializationTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingMaterializationTests.cs index 272c36b99..d1d213f3c 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingMaterializationTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingMaterializationTests.cs @@ -39,7 +39,9 @@ public async Task ConsumerCopySurvivesSourceRetirementAndUnchangedCopyKeepsTimes Assert.True(second.Execute()); Assert.Equal(timestamp, File.GetLastWriteTimeUtc(second.MaterializedSource)); using (BuildArtifactWriteLease retirement = await BuildArtifactWriteLease.AcquireAsync(first.ArtifactDirectory, m_root)) + { Directory.Delete(first.ArtifactDirectory, recursive: true); + } Assert.Equal(contents, File.ReadAllText(first.MaterializedSource)); } @@ -148,7 +150,8 @@ private MaterializeBindingsTask CreateHostTask() return task; } - private MaterializeBindingsTask CreateTask() => new() + private MaterializeBindingsTask CreateTask() + => new() { Source = Path.Combine(m_root, "artifact", "Generated", "Bindings.cs"), ArtifactDirectory = Path.Combine(m_root, "artifact"), @@ -170,23 +173,33 @@ private sealed class RecordingBuildEngine : IBuildEngine3 public int ColumnNumberOfTaskNode => 0; public string ProjectFileOfTaskNode => string.Empty; public bool IsRunningMultipleNodes => true; + public void Yield() => yielded.TrySetResult(); + public void Reacquire() { if (failReacquire) + { throw new InvalidOperationException("The build node is unavailable."); + } reacquired = true; } + public void LogErrorEvent(BuildErrorEventArgs error) => errors.Add(error); - public void LogWarningEvent(BuildWarningEventArgs warning) { } - public void LogMessageEvent(BuildMessageEventArgs message) { } - public void LogCustomEvent(CustomBuildEventArgs custom) { } + + public void LogWarningEvent(BuildWarningEventArgs warning) {} + + public void LogMessageEvent(BuildMessageEventArgs message) {} + + public void LogCustomEvent(CustomBuildEventArgs custom) {} + public bool BuildProjectFile( string project, string[] targets, IDictionary properties, IDictionary outputs ) => throw new NotSupportedException(); + public bool BuildProjectFile( string project, string[] targets, diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs index 1d3a0ca12..b700d6e1e 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Bindings.Tests; @@ -22,20 +22,35 @@ public async Task PublicationWithoutItsCompiledSelectionFailsBeforePreparingTheT { File.Copy(Path.Combine(engine, "global.json"), Path.Combine(root, "global.json")); string project = Path.Combine(root, "Fixture.proj"); - new XDocument(new XElement("Project", - new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), - new XElement("PropertyGroup", new XElement("InnoProductId", "player")), - new XElement("Target", new XAttribute("Name", "PrepareInnoBuildTaskHost"), - new XElement("Error", new XAttribute("Text", "An invalid publication prepared the task runtime."))))) + new XDocument( + new XElement( + "Project", + new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), + new XElement("PropertyGroup", new XElement("InnoProductId", "player")), + new XElement( + "Target", + new XAttribute("Name", "PrepareInnoBuildTaskHost"), + new XElement("Error", new XAttribute("Text", "An invalid publication prepared the task runtime.")) + ) + ) + ) .Save(project); - string sdk = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string sdk = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); using CancellationTokenSource timeout = new(TimeSpan.FromMinutes(3)); using StringWriter output = new(); using StringWriter error = new(); - Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync(sdk, + Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( + sdk, ["msbuild", project, "-t:PublishProductNativeDeployment", "-nodeReuse:false", "-v:minimal"], - root, timeout.Token, null, output, error)); + root, + timeout.Token, + null, + output, + error + )); Assert.NotNull(failure); string messages = output.ToString() + error; Assert.Contains("Native publication requires the exact binding selection", messages); @@ -58,24 +73,52 @@ public async Task SelectionRemainsProductOwnedThroughBuildAndPublish() File.Copy(Path.Combine(engine, "global.json"), Path.Combine(root, "global.json")); File.WriteAllText(Path.Combine(root, "Directory.Build.props"), ""); string selection = Path.Combine(root, "NativeBindingSelection.props"); - new XDocument(new XElement("Project", - new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), - new XElement("PropertyGroup", - new XElement("_InnoOwnedProductBindingSelection", selection), - new XElement("InnoNativeBindingSelection", selection)), - new XElement("Target", new XAttribute("Name", "CreateFixtureSelection"), - new XAttribute("BeforeTargets", "PrepareForBuild"), - new XElement("WriteLinesToFile", new XAttribute("File", selection), - new XAttribute("Lines", ""), new XAttribute("Overwrite", "true"))), - new XElement("Target", new XAttribute("Name", "RequireCompiledSelectionForPublication"), - new XAttribute("BeforeTargets", "Publish"), - new XElement("Error", new XAttribute("Condition", $"!Exists('{selection}')"), - new XAttribute("Text", "Build retired the selection before its publication consumer."))))) + new XDocument( + new XElement( + "Project", + new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), + new XElement( + "PropertyGroup", + new XElement("_InnoOwnedProductBindingSelection", selection), + new XElement("InnoNativeBindingSelection", selection) + ), + new XElement( + "Target", + new XAttribute("Name", "CreateFixtureSelection"), + new XAttribute("BeforeTargets", "PrepareForBuild"), + new XElement( + "WriteLinesToFile", + new XAttribute("File", selection), + new XAttribute("Lines", ""), + new XAttribute("Overwrite", "true") + ) + ), + new XElement( + "Target", + new XAttribute("Name", "RequireCompiledSelectionForPublication"), + new XAttribute("BeforeTargets", "Publish"), + new XElement( + "Error", + new XAttribute("Condition", $"!Exists('{selection}')"), + new XAttribute("Text", "Build retired the selection before its publication consumer.") + ) + ) + ) + ) .Save(Path.Combine(root, "Directory.Build.targets")); string project = Path.Combine(root, "Fixture.csproj"); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), - new XElement("ImplicitUsings", "disable"), new XElement("Nullable", "enable")))) + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("ImplicitUsings", "disable"), + new XElement("Nullable", "enable") + ) + ) + ) .Save(project); File.WriteAllText(Path.Combine(root, "Api.cs"), "public static class Api { public static int value => 42; }"); @@ -86,14 +129,22 @@ public async Task SelectionRemainsProductOwnedThroughBuildAndPublish() async Task Execute(string command) { - string sdk = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string sdk = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); using CancellationTokenSource timeout = new(TimeSpan.FromMinutes(3)); using StringWriter output = new(); using StringWriter error = new(); - Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync(sdk, + Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( + sdk, [command, project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "-v:minimal"], - root, timeout.Token, null, output, error)); + root, + timeout.Token, + null, + output, + error + )); Assert.True(failure is null, output.ToString() + error + failure); } } diff --git a/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs b/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs index 57840ef10..1a305592e 100644 --- a/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs @@ -15,8 +15,11 @@ namespace Inno.Build.Bindings.Tests; public sealed class NativeBindingGenerationTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), - "InnoNativeBindingTests", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoNativeBindingTests", + Guid.NewGuid().ToString("N") + ); [Fact] [Trait("ExternalDependency", "BGCS")] @@ -31,49 +34,85 @@ public async Task DependencyPackageRetainsBindingsWithoutConsumerGeneration() await Git(m_root, "clone", "--no-hardlinks", m_root, consumer); var component = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); string sdk = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - var tools = new NativeToolchainSelection("fixture-target", new BuildHostDescriptor("fixture-host", "fixture-arch"), - new Dictionary { ["sdk"] = sdk }, new Dictionary(), [], [], - new NativeLinkPlan(sharedLibraryExtension: ".data"), false); + var tools = new NativeToolchainSelection( + "fixture-target", + new BuildHostDescriptor("fixture-host", "fixture-arch"), + new Dictionary { ["sdk"] = sdk }, + new Dictionary(), + [], + [], + new NativeLinkPlan(sharedLibraryExtension: ".data"), + false + ); var context = new NativeBuildContext(m_root, "release").WithToolchain(tools) .WithBindingGenerator(BindingTestProfiles.Generator("fixture-target")); int productions = 0; - NativeBuildRecipe Recipe(NativeBuildContext current) => new(component, "fixture", "fixture-target", - [NativeBuildInput.FromPath(current.engineRoot, Path.Combine(current.engineRoot, "Source"))], ["fixture"]); - var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep("fixture", component, new(NativeLibraryKind.Shared), [], + NativeBuildRecipe Recipe(NativeBuildContext current) + => new( + component, + "fixture", + "fixture-target", + [NativeBuildInput.FromPath(current.engineRoot, Path.Combine(current.engineRoot, "Source"))], + ["fixture"] + ); + var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep( + "fixture", + component, + new(NativeLibraryKind.Shared), + [], ( current, _, cancellation - ) => NativeArtifactPublisher.PublishAsync(current, Recipe(current), ( - _, - output, - token - ) => - { - productions++; - return File.WriteAllTextAsync(Path.Combine(output, "fixture.data"), "native payload", token); - }, cancellation, describeOutputs: static ( - _, - output - ) => - [new NativeArtifact("fixture", Path.Combine(output, "fixture.data"), NativeArtifactRole.SharedLibrary)]), - Recipe, static ( + ) => NativeArtifactPublisher.PublishAsync( + current, + Recipe(current), + ( + _, + output, + token + ) => + { + productions++; + return File.WriteAllTextAsync(Path.Combine(output, "fixture.data"), "native payload", token); + }, + cancellation, + describeOutputs: static ( + _, + output + ) => + [new NativeArtifact("fixture", Path.Combine(output, "fixture.data"), NativeArtifactRole.SharedLibrary)] + ), + Recipe, + static ( relative, _ - ) => relative)]); - using ProductNativeBuildResult produced = await new ComponentNativeProductExecutor().BuildAsync(context, plan, CancellationToken.None); + ) => relative + )]); + using ProductNativeBuildResult produced = await new ComponentNativeProductExecutor().BuildAsync( + context, + plan, + CancellationToken.None + ); string selection = await NativeDependencyManifest.ExportAsync(context, plan, produced, Path.Combine(m_root, "artifacts", "export")); using JsonDocument manifest = JsonDocument.Parse(File.ReadAllText(selection)); JsonElement asset = manifest.RootElement.GetProperty("assets")[0]; string downloads = Path.Combine(consumer, "artifacts", "fixture-target", "native"); Directory.CreateDirectory(downloads); - File.Copy(Path.Combine(m_root, "artifacts", "export", asset.GetProperty("asset").GetString()!), - Path.Combine(downloads, asset.GetProperty("sha256").GetString() + ".zip")); + File.Copy( + Path.Combine(m_root, "artifacts", "export", asset.GetProperty("asset").GetString()!), + Path.Combine(downloads, asset.GetProperty("sha256").GetString() + ".zip") + ); string selected = Path.Combine(consumer, "artifacts", "selection.json"); File.Copy(selection, selected); string managed = File.ReadAllText(produced[0].bindingGeneration!.bindingsPath); - using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync(consumer, selected, "fixture-target", "release", plan)) - { + using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( + consumer, + selected, + "fixture-target", + "release", + plan + )) { NativeBindingGenerationDescriptor binding = imported.bindingGenerations[component.nativeProject]; Assert.Equal(produced[0].bindingGeneration!.fingerprint, binding.fingerprint); Assert.Equal(managed, File.ReadAllText(binding.bindingsPath)); @@ -82,40 +121,52 @@ [new NativeArtifact("fixture", Path.Combine(output, "fixture.data"), NativeArtif Assert.NotEmpty(NativeBindingCompilation.Load(binding.nativeDirectory).roots); Assert.Equal(1, productions); } - using ProductNativeBuildResult warm = await NativeDependencyManifest.AcquireAsync(consumer, selected, "fixture-target", "release", plan); + using ProductNativeBuildResult warm = await NativeDependencyManifest.AcquireAsync( + consumer, + selected, + "fixture-target", + "release", + plan + ); Assert.Equal(managed, File.ReadAllText(warm[0].bindingGeneration!.bindingsPath)); Assert.Equal(1, productions); static Task Git( string root, params string[] arguments - ) - => ToolchainEnvironment.CaptureOutputAsync("git", arguments, root, CancellationToken.None); + ) => ToolchainEnvironment.CaptureOutputAsync("git", arguments, root, CancellationToken.None); } [Fact] public void ManagedSelectionPreservesExactNativeIdentitiesInStableProjectOrder() { string output = Path.Combine(m_root, "BindingSelection.props"); - NativeBindingGenerationDescriptor.WriteSelection(output, + NativeBindingGenerationDescriptor.WriteSelection( + output, new Dictionary { ["backends/Text/native/Inno.Native.Text/Inno.Native.Text.csproj"] = SelectedGeneration("text-fingerprint"), ["backends/Bgfx/native/Inno.Native.Bgfx/Inno.Native.Bgfx.csproj"] = SelectedGeneration("bgfx-fingerprint") - }, new Dictionary + }, + new Dictionary { ["backends/Text/native/Inno.Native.Text/Inno.Native.Text.csproj"] = NativeLibraryKind.Static, ["backends/Bgfx/native/Inno.Native.Bgfx/Inno.Native.Bgfx.csproj"] = NativeLibraryKind.Shared - }); + } + ); XElement[] groups = XDocument.Load(output).Root!.Elements("PropertyGroup").ToArray(); Assert.Equal(2, groups.Length); Assert.Equal("'$(MSBuildProjectName)' == 'Inno.Native.Bgfx'", groups[0].Attribute("Condition")!.Value); Assert.Equal("bgfx-fingerprint", groups[0].Element("BindGenExpectedFingerprint")!.Value); - Assert.Equal(SelectedGeneration("bgfx-fingerprint").artifactOwnerDirectory, - groups[0].Element("BindGenArtifactOwnerDirectory")!.Value); - Assert.Equal(Path.GetDirectoryName(SelectedGeneration("bgfx-fingerprint").bindingsPath), - groups[0].Element("BindGenOutputDirectory")!.Value); + Assert.Equal( + SelectedGeneration("bgfx-fingerprint").artifactOwnerDirectory, + groups[0].Element("BindGenArtifactOwnerDirectory")!.Value + ); + Assert.Equal( + Path.GetDirectoryName(SelectedGeneration("bgfx-fingerprint").bindingsPath), + groups[0].Element("BindGenOutputDirectory")!.Value + ); Assert.Equal("text-fingerprint", groups[1].Element("BindGenExpectedFingerprint")!.Value); Assert.Equal("Shared", groups[0].Element("InnoNativeLibraryKind")!.Value); Assert.Equal("Static", groups[1].Element("InnoNativeLibraryKind")!.Value); @@ -141,11 +192,14 @@ bool runtimeImports Assert.Equal(runtimeImports ? "true" : "false", group.Element("InnoNativeRuntimeImports")!.Value); Assert.Equal(linkage.ToString(), group.Element("InnoNativeLibraryKind")!.Value); NativeBindingGenerationDescriptor.ValidateSelection(output, generations, links); - Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection(output, + Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection( + output, new Dictionary { ["Inno.Native.Text.csproj"] = SelectedGeneration("selected", !runtimeImports) - }, links)); + }, + links + )); } [Fact] @@ -182,19 +236,34 @@ public void PublicationRejectsChangedOrIncompleteManagedSelection() var linkage = new Dictionary { ["Inno.Native.Text.csproj"] = NativeLibraryKind.Shared }; NativeBindingGenerationDescriptor.WriteSelection(output, original, linkage); NativeBindingGenerationDescriptor.ValidateSelection(output, original, linkage); - Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection(output, + Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection( + output, new Dictionary { ["Inno.Native.Text.csproj"] = SelectedGeneration("changed") - }, linkage)); - Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection(output, - new Dictionary(), new Dictionary())); - Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection(output, original, - new Dictionary { ["Inno.Native.Text.csproj"] = NativeLibraryKind.Static })); - Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection(output, original, - new Dictionary())); - Assert.Equal("original", XDocument.Load(output).Root!.Element("PropertyGroup")! - .Element("BindGenExpectedFingerprint")!.Value); + }, + linkage + )); + Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection( + output, + new Dictionary(), + new Dictionary() + )); + Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection( + output, + original, + new Dictionary { ["Inno.Native.Text.csproj"] = NativeLibraryKind.Static } + )); + Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection( + output, + original, + new Dictionary() + )); + Assert.Equal( + "original", + XDocument.Load(output).Root!.Element("PropertyGroup")! + .Element("BindGenExpectedFingerprint")!.Value + ); } [Fact] @@ -204,16 +273,19 @@ public void CollidingManagedSelectionDoesNotReplaceAnExistingCompleteSelection() Directory.CreateDirectory(Path.Combine(m_root, "Source")); File.WriteAllText(output, "previous complete selection"); - Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection(output, + Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection( + output, new Dictionary { ["first/Inno.Native.Text.csproj"] = SelectedGeneration("first"), ["second/inno.native.text.csproj"] = SelectedGeneration("second") - }, new Dictionary + }, + new Dictionary { ["first/Inno.Native.Text.csproj"] = NativeLibraryKind.Shared, ["second/inno.native.text.csproj"] = NativeLibraryKind.Shared - })); + } + )); Assert.Equal("previous complete selection", File.ReadAllText(output)); } @@ -221,11 +293,14 @@ public void CollidingManagedSelectionDoesNotReplaceAnExistingCompleteSelection() public void UnsafeManagedProjectNameIsRejectedBeforeCreatingSelectionOutput() { string output = Path.Combine(m_root, "BindingSelection.props"); - Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection(output, + Assert.Throws(() => NativeBindingGenerationDescriptor.WriteSelection( + output, new Dictionary { ["Inno'Injected.csproj"] = SelectedGeneration("selected") - }, new Dictionary { ["Inno'Injected.csproj"] = NativeLibraryKind.Shared })); + }, + new Dictionary { ["Inno'Injected.csproj"] = NativeLibraryKind.Shared } + )); Assert.False(Directory.Exists(m_root)); } @@ -239,10 +314,16 @@ public async Task PlatformImportChoiceChangesOfficialGenerationAndFrozenSelectio NativeBindingGenerationDescriptor provider = await GenerateAsync(); var component = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); var request = new NativeBindingGenerationRequest([component], "fixture-target", NativeBindingOutputMode.TargetArtifacts); - var profile = new NativeBindingProfile("fixture-target", - new BGCS.Configuration.TargetConfiguration { id = "windows-x64-msvc" }, importMode: importMode); + var profile = new NativeBindingProfile( + "fixture-target", + new BGCS.Configuration.TargetConfiguration { id = "windows-x64-msvc" }, + importMode: importMode + ); using NativeBindingGenerationResult result = await new NativeBindingGenerator(profile).GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); NativeBindingGenerationDescriptor imports = result[component.nativeProject]; Assert.False(provider.usesRuntimeImports); Assert.True(imports.usesRuntimeImports); @@ -263,8 +344,13 @@ public async Task SourceChangesSelectIndependentGenerationsAndTamperingIsRepaire string descriptorPath = Path.Combine(m_root, "requests", "descriptor.json"); first.Write(descriptorPath); Assert.Equal(first.bindingsPath, NativeBindingGenerationDescriptor.Load(descriptorPath).bindingsPath); - Assert.True(BuildArtifactManifest.IsComplete(Path.GetDirectoryName(Path.GetDirectoryName(first.bindingsPath))!, - first.fingerprint, ["Native", "Generated"])); + Assert.True( + BuildArtifactManifest.IsComplete( + Path.GetDirectoryName(Path.GetDirectoryName(first.bindingsPath))!, + first.fingerprint, + ["Native", "Generated"] + ) + ); File.WriteAllText(first.bindingsPath, "tampered"); NativeBindingGenerationDescriptor repaired = await GenerateAsync(); @@ -293,14 +379,16 @@ public async Task UnselectedPlatformDoesNotInvalidateTheSelectedGeneration() var unchangedContext = new NativeBuildContext(m_root, "release"); using (NativeBindingGenerationResult unchanged = await BindingTestProfiles.Generator("fixture-target") - .GenerateAsync(unchangedContext, request, CancellationToken.None)) - { + .GenerateAsync(unchangedContext, request, CancellationToken.None) + ) { Assert.Equal(first.fingerprint, unchanged[owner.nativeProject].fingerprint); Assert.Equal(0, unchangedContext.statistics.bindingGenerations); } - File.WriteAllText(Path.Combine(m_root, "selected.json"), - File.ReadAllText(config).Replace("Fixture.Native", "Fixture.Selected", StringComparison.Ordinal)); + File.WriteAllText( + Path.Combine(m_root, "selected.json"), + File.ReadAllText(config).Replace("Fixture.Native", "Fixture.Selected", StringComparison.Ordinal) + ); definition.Root!.Element("PropertyGroup")!.Element("InnoBindingConfig")!.Value = "selected.json"; definition.Save(definitionPath); NativeBindingGenerationDescriptor changed = await GenerateAsync(); @@ -315,14 +403,22 @@ public async Task CppBridgeAndManagedBindingsShareOneCompletedGeneration() { string config = CreateConfig("int sample(int value);"); string facade = Path.Combine(m_root, "Source", "facade.hpp"); - File.WriteAllText(facade, "class Counter { public: explicit Counter(int value) : value_(value) {} int Add(int value) { return value_ + value; } private: int value_; };"); + File.WriteAllText( + facade, + "class Counter { public: explicit Counter(int value) : value_(value) {} int Add(int value) { return value_ + value; } private: int value_; };" + ); WriteCppConfig(config); NativeBindingGenerationDescriptor first = await GenerateAsync(); NativeBindingCompilation compilation = NativeBindingCompilation.Load(first.nativeDirectory); Assert.Contains(compilation.files, file => file.compile && file.rootId == "generated"); - Assert.Contains(compilation.files, file => !file.compile && file.rootId == "generated" && file.relativePath.EndsWith(".h", StringComparison.Ordinal)); - Assert.Equal(Path.GetDirectoryName(first.nativeDirectory), - Path.GetDirectoryName(Path.GetDirectoryName(first.bindingsPath))); + Assert.Contains( + compilation.files, + file => !file.compile && file.rootId == "generated" && file.relativePath.EndsWith(".h", StringComparison.Ordinal) + ); + Assert.Equal( + Path.GetDirectoryName(first.nativeDirectory), + Path.GetDirectoryName(Path.GetDirectoryName(first.bindingsPath)) + ); Assert.False(Directory.Exists(Path.Combine(m_root, "declared"))); string original = File.ReadAllText(first.bindingsPath); File.WriteAllText(facade, "class Counter { invalid C++; };"); @@ -342,11 +438,17 @@ public async Task HostBindingFailurePreservesBothPublishedOutputTrees() NativeBindingGenerationDescriptor initial = await GenerateAsync(mode: NativeBindingOutputMode.HostSource); string source = File.ReadAllText(initial.bindingsPath); NativeBindingCompilation compilation = NativeBindingCompilation.Load(initial.nativeDirectory); - string nativeHeader = Path.Combine(initial.nativeDirectory, compilation.files.First(file => - file.rootId == "generated" && file.relativePath.EndsWith(".h", StringComparison.Ordinal)).relativePath); + string nativeHeader = Path.Combine( + initial.nativeDirectory, + compilation.files.First(file => ( + file.rootId == "generated" && file.relativePath.EndsWith(".h", StringComparison.Ordinal) + )).relativePath + ); string header = File.ReadAllText(nativeHeader); - string nativeSource = Path.Combine(initial.nativeDirectory, compilation.files.First(file => - file.rootId == "generated" && file.compile).relativePath); + string nativeSource = Path.Combine( + initial.nativeDirectory, + compilation.files.First(file => (file.rootId == "generated" && file.compile)).relativePath + ); string implementation = File.ReadAllText(nativeSource); File.WriteAllText(facade, "class Counter { public: int Changed() { return 9; } };"); File.WriteAllText(config, File.ReadAllText(config).Replace("facade.hpp", "missing.hpp", StringComparison.Ordinal)); @@ -393,7 +495,9 @@ public void Dispose() if (Directory.Exists(m_root)) { foreach (string file in Directory.EnumerateFiles(m_root, "*", SearchOption.AllDirectories)) + { File.SetAttributes(file, FileAttributes.Normal); + } Directory.Delete(m_root, recursive: true); } } @@ -401,16 +505,15 @@ public void Dispose() private static NativeBindingGenerationDescriptor SelectedGeneration( string fingerprint, bool usesRuntimeImports = false - ) - => new() - { - fingerprint = fingerprint, - artifactDirectory = Path.Combine(Path.GetTempPath(), "SelectedGeneration", fingerprint), - artifactOwnerDirectory = Path.Combine(Path.GetTempPath(), "SelectedGeneration"), - bindingsPath = Path.Combine(Path.GetTempPath(), "SelectedGeneration", fingerprint, "Generated", "Bindings.cs"), - usesRuntimeImports = usesRuntimeImports, - nativeDirectory = string.Empty - }; + ) => new() + { + fingerprint = fingerprint, + artifactDirectory = Path.Combine(Path.GetTempPath(), "SelectedGeneration", fingerprint), + artifactOwnerDirectory = Path.Combine(Path.GetTempPath(), "SelectedGeneration"), + bindingsPath = Path.Combine(Path.GetTempPath(), "SelectedGeneration", fingerprint, "Generated", "Bindings.cs"), + usesRuntimeImports = usesRuntimeImports, + nativeDirectory = string.Empty + }; private string CreateConfig(string header) { @@ -420,13 +523,17 @@ private string CreateConfig(string header) File.WriteAllText(Path.Combine(m_root, "Fixture.csproj"), ""); WriteDefinition(); string config = Path.Combine(m_root, "bindgen.json"); - File.WriteAllText(config, JsonSerializer.Serialize(new { - schemaVersion = 2, - library = new { id = "fixture", nativeName = "fixture" }, - source = new { language = "c", headers = new[] { "Source/api.h" } }, - api = new { @namespace = "Fixture.Native", name = "Api" }, - output = new { root = "Generated", layout = "singleFile" } - })); + File.WriteAllText( + config, + JsonSerializer.Serialize(new + { + schemaVersion = 2, + library = new { id = "fixture", nativeName = "fixture" }, + source = new { language = "c", headers = new[] { "Source/api.h" } }, + api = new { @namespace = "Fixture.Native", name = "Api" }, + output = new { root = "Generated", layout = "singleFile" } + }) + ); return config; } @@ -440,27 +547,40 @@ private async Task GenerateAsync( var fingerprints = expected is null ? null : new Dictionary { [owner.nativeProject] = expected }; var request = new NativeBindingGenerationRequest([owner], "fixture-target", mode, checkOnly, fingerprints); using var result = await BindingTestProfiles.Generator("fixture-target").GenerateAsync( - new NativeBuildContext(m_root, "release"), request, cancellation); + new NativeBuildContext(m_root, "release"), + request, + cancellation + ); return result[owner.nativeProject]; } private void WriteDefinition() { - new XDocument(new XElement("Project", - new XElement("PropertyGroup", new XElement("InnoNativeComponentId", "fixture"), new XElement("InnoBindingConfig", "bindgen.json")))) + new XDocument( + new XElement( + "Project", + new XElement( + "PropertyGroup", + new XElement("InnoNativeComponentId", "fixture"), + new XElement("InnoBindingConfig", "bindgen.json") + ) + ) + ) .Save(Path.Combine(m_root, "bindings.props")); } private static void WriteCppConfig(string path) { - File.WriteAllText(path, JsonSerializer.Serialize(new - { - schemaVersion = 2, - library = new { id = "fixture", nativeName = "fixture" }, - source = new { language = "cpp", languageStandard = "c++20", headers = new[] { "Source/facade.hpp" } }, - api = new { @namespace = "Fixture.Native", name = "Api" }, - output = new { root = "Generated", layout = "singleFile" } - })); + File.WriteAllText( + path, + JsonSerializer.Serialize(new + { + schemaVersion = 2, + library = new { id = "fixture", nativeName = "fixture" }, + source = new { language = "cpp", languageStandard = "c++20", headers = new[] { "Source/facade.hpp" } }, + api = new { @namespace = "Fixture.Native", name = "Api" }, + output = new { root = "Generated", layout = "singleFile" } + }) + ); } - } diff --git a/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs b/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs index bffe5a1f0..1c82162d7 100644 --- a/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs @@ -7,9 +7,9 @@ using BGCS.Core; using BGCS.Core.Targets; using BGCS.Extension.BrowserWasm; +using Xunit; using Inno.Build.Bindings; using Inno.Build.Toolchains; -using Xunit; namespace Inno.Build.Bindings.Tests; @@ -31,11 +31,15 @@ public async Task BrowserAggregateBridgeRequiresExplicitExtensionAndReusesVerifi Directory.CreateDirectory(Path.Combine(m_root, "Source")); File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), string.Empty); File.WriteAllText(Path.Combine(m_root, "Fixture.csproj"), ""); - File.WriteAllText(Path.Combine(m_root, "Source", "api.h"), - "typedef struct Pair { int first; int second; } Pair; Pair swap_pair(Pair value);"); - File.WriteAllText(Path.Combine(m_root, "bindings.props"), - "fixture" + - "bindgen.json"); + File.WriteAllText( + Path.Combine(m_root, "Source", "api.h"), + "typedef struct Pair { int first; int second; } Pair; Pair swap_pair(Pair value);" + ); + File.WriteAllText( + Path.Combine(m_root, "bindings.props"), + "fixture" + + "bindgen.json" + ); File.WriteAllText(Path.Combine(m_root, "bindgen.json"), """ {"schemaVersion":2,"library":{"id":"fixture","nativeName":"fixture"}, "source":{"language":"c","headers":["Source/api.h"]}, @@ -46,18 +50,28 @@ public async Task BrowserAggregateBridgeRequiresExplicitExtensionAndReusesVerifi var request = new NativeBindingGenerationRequest([component], "fixture-target", NativeBindingOutputMode.TargetArtifacts); var target = new TargetConfiguration { id = "emscripten-wasm32-emscripten" }; var runtime = new ManagedRuntimeId("dotnet.mono-wasm"); - var missing = new NativeBindingGenerator(new NativeBindingProfile("fixture-target", target, runtime, - importMode: BindingImportMode.LibraryImport)); + var missing = new NativeBindingGenerator( + new NativeBindingProfile("fixture-target", target, runtime, importMode: BindingImportMode.LibraryImport) + ); await Assert.ThrowsAsync(async () => { using NativeBindingGenerationResult rejected = await missing.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); }); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts", "bindings"))); - var generator = new NativeBindingGenerator(new NativeBindingProfile("fixture-target", target, runtime, - configureGenerator: static builder => builder.AddPlugin(), - importMode: BindingImportMode.LibraryImport)); + var generator = new NativeBindingGenerator( + new NativeBindingProfile( + "fixture-target", + target, + runtime, + configureGenerator: static builder => builder.AddPlugin(), + importMode: BindingImportMode.LibraryImport + ) + ); NativeBuildContext cold = new(m_root, "release"); using NativeBindingGenerationResult first = await generator.GenerateAsync(cold, request, CancellationToken.None); NativeBindingGenerationDescriptor generation = first[component.nativeProject]; @@ -66,17 +80,29 @@ await Assert.ThrowsAsync(async () => Assert.True(generation.usesRuntimeImports); Assert.NotEmpty(compilation.requiredExports); Assert.Empty(compilation.staticExportSymbols); - Assert.All(compilation.roots.Where(static root => root.frozen), static root => Assert.False(Path.IsPathFullyQualified(root.directory))); + Assert.All( + compilation.roots.Where(static root => root.frozen), + static root => Assert.False(Path.IsPathFullyQualified(root.directory)) + ); Assert.Equal(1, cold.statistics.bindingGenerations); byte[] published = File.ReadAllBytes(generation.bindingsPath); - var unsupported = new NativeBindingGenerator(new NativeBindingProfile("fixture-target", target, runtime, - configureGenerator: static builder => builder.AddPlugin(), - importMode: BindingImportMode.FunctionTable)); + var unsupported = new NativeBindingGenerator( + new NativeBindingProfile( + "fixture-target", + target, + runtime, + configureGenerator: static builder => builder.AddPlugin(), + importMode: BindingImportMode.FunctionTable + ) + ); InvalidDataException importFailure = await Assert.ThrowsAsync(async () => { using NativeBindingGenerationResult rejected = await unsupported.GenerateAsync( - new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); }); Assert.Contains("FunctionTable", importFailure.Message, StringComparison.Ordinal); Assert.Equal(published, File.ReadAllBytes(generation.bindingsPath)); @@ -93,6 +119,8 @@ await Assert.ThrowsAsync(async () => public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, true); + } } } diff --git a/tests/build/Inno.Build.Cli.Tests/ArchitectureVerificationCommandTests.cs b/tests/build/Inno.Build.Cli.Tests/ArchitectureVerificationCommandTests.cs index d244de35e..1b50a247a 100644 --- a/tests/build/Inno.Build.Cli.Tests/ArchitectureVerificationCommandTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/ArchitectureVerificationCommandTests.cs @@ -23,7 +23,10 @@ public async Task NativeVerificationRejectsTargetsWithoutAnEditorRunnerBeforeCre File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); Console.SetOut(output); Console.SetError(output); - int result = await BuildApplication.Run(["verify-native", "--engine-root", root, "--target", "browser-wasm"], CancellationToken.None); + int result = await BuildApplication.Run( + ["verify-native", "--engine-root", root, "--target", "browser-wasm"], + CancellationToken.None + ); Assert.Equal(1, result); Assert.Contains("requires a registered Editor test host", output.ToString(), StringComparison.Ordinal); Assert.DoesNotContain("BGCS-CSHARP-ABI-PLAN", output.ToString(), StringComparison.Ordinal); @@ -47,8 +50,10 @@ public async Task VerifyRoutesToTheArchitectureCommandWithoutPreparingAProduct() try { Directory.CreateDirectory(Path.Combine(root, "src", "services", "audio")); - File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), - "Microsoft Visual Studio Solution File, Format Version 12.00"); + File.WriteAllText( + Path.Combine(root, "InnoEngine.sln"), + "Microsoft Visual Studio Solution File, Format Version 12.00" + ); File.WriteAllText(Path.Combine(root, "src", "services", "audio", "Probe.cs"), "global using System;"); Console.SetOut(output); Console.SetError(output); @@ -63,7 +68,9 @@ public async Task VerifyRoutesToTheArchitectureCommandWithoutPreparingAProduct() Console.SetOut(previousOutput); Console.SetError(previousError); if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } } diff --git a/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs b/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs index dcbb7d676..e268adabd 100644 --- a/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs @@ -1,7 +1,7 @@ using System.Threading; using System.Threading.Tasks; -using Inno.Build.Cli; using Xunit; +using Inno.Build.Cli; namespace Inno.Build.Cli.Tests; diff --git a/tests/build/Inno.Build.Cli.Tests/DevelopmentEntrySdkSelectionTests.cs b/tests/build/Inno.Build.Cli.Tests/DevelopmentEntrySdkSelectionTests.cs index 6fb642317..e414c3d0f 100644 --- a/tests/build/Inno.Build.Cli.Tests/DevelopmentEntrySdkSelectionTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/DevelopmentEntrySdkSelectionTests.cs @@ -1,10 +1,10 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Cli; using Xunit; +using Inno.Build.Cli; +using Inno.Testing.Source; namespace Inno.Build.Cli.Tests; diff --git a/tests/build/Inno.Build.Cli.Tests/NativeDependencyDescriptionTests.cs b/tests/build/Inno.Build.Cli.Tests/NativeDependencyDescriptionTests.cs index 7ff9cc10c..1d11f9ca7 100644 --- a/tests/build/Inno.Build.Cli.Tests/NativeDependencyDescriptionTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/NativeDependencyDescriptionTests.cs @@ -4,8 +4,8 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Testing.Source; using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Cli.Tests; @@ -24,12 +24,27 @@ string products Directory.CreateDirectory(Path.GetDirectoryName(output)!); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT")!, OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); - int result = await BuildApplication.Run(["native-dependencies", "--operation", "describe", "--engine-root", root, - "--tools-target", OperatingSystem.IsWindows() ? "windows-x64" : "macos-arm64", "--target", target, - "--dotnet", dotnet, "--output", output], CancellationToken.None); + int result = await BuildApplication.Run([ + "native-dependencies", + "--operation", + "describe", + "--engine-root", + root, + "--tools-target", + OperatingSystem.IsWindows() ? "windows-x64" : "macos-arm64", + "--target", + target, + "--dotnet", + dotnet, + "--output", + output + ], CancellationToken.None); Assert.Equal(0, result); using JsonDocument description = JsonDocument.Parse(File.ReadAllText(output)); Assert.Equal(target, description.RootElement.GetProperty("target").GetString()); - Assert.Equal(products.Split(','), description.RootElement.GetProperty("products").EnumerateArray().Select(static value => value.GetString())); + Assert.Equal( + products.Split(','), + description.RootElement.GetProperty("products").EnumerateArray().Select(static value => value.GetString()) + ); } } diff --git a/tests/build/Inno.Build.Cli.Tests/ProjectCommandSourceTests.cs b/tests/build/Inno.Build.Cli.Tests/ProjectCommandSourceTests.cs index b5d8d24bf..398a2d5ae 100644 --- a/tests/build/Inno.Build.Cli.Tests/ProjectCommandSourceTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/ProjectCommandSourceTests.cs @@ -2,8 +2,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Cli; using Xunit; +using Inno.Build.Cli; namespace Inno.Build.Cli.Tests; @@ -22,9 +22,17 @@ public async Task InvalidExplicitSourceIsRejectedBeforeToolsAndProjectStateAreCr { Console.SetError(errors); int result = await BuildApplication.Run( - ["scripts", "--engine-root", owner, - "--project", project, "--output", output], - CancellationToken.None); + [ + "scripts", + "--engine-root", + owner, + "--project", + project, + "--output", + output + ], + CancellationToken.None + ); Assert.Equal(1, result); Assert.Contains("Engine checkout is unavailable", errors.ToString()); diff --git a/tests/build/Inno.Build.Cli.Tests/ScriptCommandTests.cs b/tests/build/Inno.Build.Cli.Tests/ScriptCommandTests.cs index a9745b686..5275a0640 100644 --- a/tests/build/Inno.Build.Cli.Tests/ScriptCommandTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/ScriptCommandTests.cs @@ -17,27 +17,50 @@ public async Task ScriptExportAndIdeProjectionRequireNoNativeSourceOrToolsTarget { Directory.CreateDirectory(Path.Combine(m_root, "Project", "Assets")); File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); - File.WriteAllText(Path.Combine(m_root, "Project", "Assets", "Probe.cs"), - "using InnoEngine.Scene; public sealed class Probe : GameBehavior { }"); + File.WriteAllText( + Path.Combine(m_root, "Project", "Assets", "Probe.cs"), + "using InnoEngine.Scene; public sealed class Probe : GameBehavior { }" + ); string unrelatedCatalog = Path.Combine(m_root, "artifacts", "cache-owners"); Directory.CreateDirectory(unrelatedCatalog); File.WriteAllText(Path.Combine(unrelatedCatalog, "unrelated.json"), "unavailable product-cache metadata"); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); TextWriter previousError = Console.Error; using var errors = new StringWriter(CultureInfo.InvariantCulture); try { Console.SetError(errors); - int result = await BuildApplication.Run(["scripts", "--engine-root", m_root, - "--project", Path.Combine(m_root, "Project"), "--output", Path.Combine(m_root, "Scripts"), - "--dotnet", host, "--ide"], CancellationToken.None); + int result = await BuildApplication.Run([ + "scripts", + "--engine-root", + m_root, + "--project", + Path.Combine(m_root, "Project"), + "--output", + Path.Combine(m_root, "Scripts"), + "--dotnet", + host, + "--ide" + ], CancellationToken.None); Assert.True(result == 0, errors.ToString()); Assert.DoesNotContain("automatic cache maintenance", errors.ToString(), StringComparison.Ordinal); Assert.True(File.Exists(Path.Combine(m_root, "Scripts", "Inno.GameScripts.dll"))); Assert.True(File.Exists(Path.Combine(m_root, "Project", "Inno.GameScripts.csproj"))); - Assert.NotEmpty(Directory.GetFiles(Path.Combine(m_root, "Project", "Library"), - "Inno.ScriptApi.Runtime.dll", SearchOption.AllDirectories)); + Assert.NotEmpty( + Directory.GetFiles( + Path.Combine(m_root, "Project", "Library"), + "Inno.ScriptApi.Runtime.dll", + SearchOption.AllDirectories + ) + ); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts", "native"))); Assert.False(Directory.Exists(Path.Combine(m_root, "extern"))); } @@ -52,14 +75,26 @@ public async Task PrecancelledScriptExportCreatesNoWorkspace() { using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - Assert.Equal(2, await BuildApplication.Run(["scripts", "--engine-root", m_root, - "--project", Path.Combine(m_root, "Project"), "--output", Path.Combine(m_root, "Scripts")], cancellation.Token)); + Assert.Equal( + 2, + await BuildApplication.Run([ + "scripts", + "--engine-root", + m_root, + "--project", + Path.Combine(m_root, "Project"), + "--output", + Path.Combine(m_root, "Scripts") + ], cancellation.Token) + ); Assert.False(Directory.Exists(m_root)); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Integration.Tests/BindingToolchainTaskTests.cs b/tests/build/Inno.Build.Integration.Tests/BindingToolchainTaskTests.cs index b0f1ac4e2..64c661501 100644 --- a/tests/build/Inno.Build.Integration.Tests/BindingToolchainTaskTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/BindingToolchainTaskTests.cs @@ -2,10 +2,10 @@ using System.Collections; using System.Collections.Generic; using System.IO; -using Inno.Build.Tasks; -using Inno.Build.Toolchains; using Microsoft.Build.Framework; using Xunit; +using Inno.Build.Tasks; +using Inno.Build.Toolchains; namespace Inno.Build.Integration.Tests; @@ -33,7 +33,9 @@ public void MissingOrCanceledDefinitionCannotCreateGenerationCandidates(bool can DescriptorOutputPath = Path.Combine(m_root, "request.json") }; if (canceled) + { task.Cancel(); + } Assert.False(task.Execute()); Assert.NotEmpty(engine.errors); @@ -52,9 +54,12 @@ private sealed class RecordingBuildEngine : IBuildEngine public string ProjectFileOfTaskNode => "fixture.proj"; public void LogErrorEvent(BuildErrorEventArgs e) => errors.Add(e.Message ?? string.Empty); - public void LogWarningEvent(BuildWarningEventArgs e) { } - public void LogMessageEvent(BuildMessageEventArgs e) { } - public void LogCustomEvent(CustomBuildEventArgs e) { } + + public void LogWarningEvent(BuildWarningEventArgs e) {} + + public void LogMessageEvent(BuildMessageEventArgs e) {} + + public void LogCustomEvent(CustomBuildEventArgs e) {} public bool BuildProjectFile( string projectFileName, diff --git a/tests/build/Inno.Build.Integration.Tests/CompilerToolBuildScopeTests.cs b/tests/build/Inno.Build.Integration.Tests/CompilerToolBuildScopeTests.cs index 364c5720a..02f2f18f4 100644 --- a/tests/build/Inno.Build.Integration.Tests/CompilerToolBuildScopeTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/CompilerToolBuildScopeTests.cs @@ -5,10 +5,10 @@ using System.Security; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; -using Inno.Testing.Source; using Microsoft.Build.Logging; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -26,8 +26,14 @@ public async Task AnalyzerRuntimeAndTransitiveEdgesShareOneCompilerToolBuild(str { File.Copy(Path.Combine(repository, "global.json"), Path.Combine(root, "global.json")); foreach (string suffix in new[] { "props", "targets" }) - File.WriteAllText(Path.Combine(root, "Directory.Build." + suffix), - ""); + { + File.WriteAllText( + Path.Combine(root, "Directory.Build." + suffix), + "" + ); + } WriteProject(root, "Tool", """ true @@ -62,35 +68,62 @@ public async Task AnalyzerRuntimeAndTransitiveEdgesShareOneCompilerToolBuild(str for (int run = 0; run < 3; run++) { if (run == 2) + { File.AppendAllText(Path.Combine(root, "Tool", "Tool.cs"), "\npublic sealed class ChangedToolMarker { }\n"); + } string binlog = Path.Combine(root, run + ".binlog"); - await ToolchainEnvironment.RunAsync(dotnet, - ["build", "Root/Root.csproj", "--nologo", "-m:4", "-nodeReuse:false", "-c", configuration, - "-p:ArtifactsPath=" + Path.Combine(root, "managed"), "-p:InnoNativeTarget=fixture-target", "-bl:" + binlog], - root, timeout.Token, DotNetSdkEnvironment.Create(dotnet)); + await ToolchainEnvironment.RunAsync( + dotnet, + [ + "build", + "Root/Root.csproj", + "--nologo", + "-m:4", + "-nodeReuse:false", + "-c", + configuration, + "-p:ArtifactsPath=" + Path.Combine(root, "managed"), + "-p:InnoNativeTarget=fixture-target", + "-bl:" + binlog + ], + root, + timeout.Token, + DotNetSdkEnvironment.Create(dotnet) + ); int compilations = 0; var identities = new HashSet(StringComparer.Ordinal); var events = new BinaryLogReplayEventSource(); events.ProjectStarted += ( _, project - ) => { + ) => + { if (Path.GetFileName(project.ProjectFile) != "Tool.csproj" || !string.IsNullOrEmpty(project.TargetNames)) + { return; + } Assert.NotNull(project.GlobalProperties); Assert.DoesNotContain("InnoNativeTarget", project.GlobalProperties!.Keys); Assert.DoesNotContain("BuildProjectReferences", project.GlobalProperties.Keys); Assert.DoesNotContain("InnoTaskBootstrapOwner", project.GlobalProperties.Keys); Assert.DoesNotContain("BuildingInsideVisualStudio", project.GlobalProperties.Keys); - identities.Add(string.Join(";", project.GlobalProperties.OrderBy(static pair => pair.Key) - .Select(static pair => pair.Key + "=" + pair.Value))); + identities.Add( + string.Join( + ";", + project.GlobalProperties.OrderBy(static pair => pair.Key) + .Select(static pair => pair.Key + "=" + pair.Value) + ) + ); }; events.TaskStarted += ( _, task - ) => { + ) => + { if (task.TaskName == "Csc" && Path.GetFileName(task.ProjectFile) == "Tool.csproj") + { compilations++; + } }; events.Replay(binlog); Assert.Single(identities); diff --git a/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs b/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs index 80b278f25..a2af2b437 100644 --- a/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs @@ -5,11 +5,11 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; +using Xunit; using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -22,16 +22,36 @@ public async Task DirectAppHostUsesItsLoadedRuntimeBeforeAnUnrelatedPath() string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", executable)); Assert.True(File.Exists(host)); // Process claims belong to the temporary owner, not the verified assembly deployment. - using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync(Path.Combine(Path.GetTempPath(), "InnoSdkHostFixtures")); + using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync( + Path.Combine(Path.GetTempPath(), "InnoSdkHostFixtures") + ); string project = Path.Combine(owner.directory, "SdkHostProbe.csproj"); Type[] references = [typeof(StandardBuildEnvironment), typeof(BuildCompositionContext), typeof(BuildTargetId)]; var items = new XElement("ItemGroup"); foreach (Type reference in references) - items.Add(new XElement("Reference", new XAttribute("Include", reference.Assembly.GetName().Name!), - new XElement("HintPath", reference.Assembly.Location))); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), new XElement("OutputType", "Exe"), - new XElement("ImplicitUsings", "disable"), new XElement("UseAppHost", "true")), items)).Save(project); + { + items.Add( + new XElement( + "Reference", + new XAttribute("Include", reference.Assembly.GetName().Name!), + new XElement("HintPath", reference.Assembly.Location) + ) + ); + } + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("OutputType", "Exe"), + new XElement("ImplicitUsings", "disable"), + new XElement("UseAppHost", "true") + ), + items + ) + ).Save(project); await File.WriteAllTextAsync(Path.Combine(owner.directory, "Program.cs"), """ using System; using Inno.Build; @@ -42,8 +62,15 @@ await File.WriteAllTextAsync(Path.Combine(owner.directory, "Program.cs"), """ using var buildErrors = new StringWriter(); try { - await ToolchainEnvironment.RunAsync(host, ["build", project, "-nologo", "-nodeReuse:false"], - owner.directory, CancellationToken.None, DotNetSdkEnvironment.Create(host), buildOutput, buildErrors); + await ToolchainEnvironment.RunAsync( + host, + ["build", project, "-nologo", "-nodeReuse:false"], + owner.directory, + CancellationToken.None, + DotNetSdkEnvironment.Create(host), + buildOutput, + buildErrors + ); } catch (InvalidOperationException failure) { @@ -51,7 +78,9 @@ await ToolchainEnvironment.RunAsync(host, ["build", project, "-nologo", "-nodeRe } string output = Path.Combine(owner.directory, "bin", "Debug", "net10.0"); foreach (string dependency in Directory.EnumerateFiles(AppContext.BaseDirectory, "*.dll")) + { File.Copy(dependency, Path.Combine(output, Path.GetFileName(dependency)), overwrite: true); + } var environment = new Dictionary { ["DOTNET_HOST_PATH"] = null, @@ -59,8 +88,13 @@ await ToolchainEnvironment.RunAsync(host, ["build", project, "-nologo", "-nodeRe ["PATH"] = owner.directory }; string appHost = Path.Combine(output, OperatingSystem.IsWindows() ? "SdkHostProbe.exe" : "SdkHostProbe"); - string selected = await ToolchainEnvironment.CaptureOutputAsync(appHost, [], owner.directory, - CancellationToken.None, environment); + string selected = await ToolchainEnvironment.CaptureOutputAsync( + appHost, + [], + owner.directory, + CancellationToken.None, + environment + ); Assert.Equal(host, selected.Trim()); } } diff --git a/tests/build/Inno.Build.Integration.Tests/DevelopmentEntryBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/DevelopmentEntryBuildTests.cs index bc5f11af1..36aeb127b 100644 --- a/tests/build/Inno.Build.Integration.Tests/DevelopmentEntryBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/DevelopmentEntryBuildTests.cs @@ -3,9 +3,9 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Testing.Source; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -23,32 +23,47 @@ bool designTime string root = TestRepository.GetRoot(typeof(DevelopmentEntryBuildTests).Assembly); string dotnet = ToolchainEnvironment.ResolveExecutable("dotnet"); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(1)); - string output = await ToolchainEnvironment.CaptureOutputAsync(dotnet, + string output = await ToolchainEnvironment.CaptureOutputAsync( + dotnet, [ - "msbuild", "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", "-nologo", - "-p:BuildProjectReferences=false", "-p:OnlyReferenceAndBuildProjectsEnabledInSolutionConfiguration=true", + "msbuild", + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + "-nologo", + "-p:BuildProjectReferences=false", + "-p:OnlyReferenceAndBuildProjectsEnabledInSolutionConfiguration=true", "-p:BuildingInsideVisualStudio=true", "-p:NETCoreSdkRuntimeIdentifier=" + sdkHost, "-p:DesignTimeBuild=" + designTime.ToString().ToLowerInvariant(), "-getProperty:BuildProjectReferences,BuildingInsideVisualStudio,OnlyReferenceAndBuildProjectsEnabledInSolutionConfiguration", "-getItem:ProjectReference" ], - root, timeout.Token, DotNetSdkEnvironment.Create(dotnet)); + root, + timeout.Token, + DotNetSdkEnvironment.Create(dotnet) + ); using JsonDocument document = JsonDocument.Parse(output); JsonElement properties = document.RootElement.GetProperty("Properties"); Assert.Equal(designTime ? "false" : "true", properties.GetProperty("BuildProjectReferences").GetString()); Assert.Equal(designTime ? "true" : "false", properties.GetProperty("BuildingInsideVisualStudio").GetString()); Assert.Equal("false", properties.GetProperty("OnlyReferenceAndBuildProjectsEnabledInSolutionConfiguration").GetString()); - JsonElement[] references = document.RootElement.GetProperty("Items").GetProperty("ProjectReference") - .EnumerateArray().ToArray(); - JsonElement product = Assert.Single(references.Where(reference => reference.GetProperty("Filename").GetString()! - .StartsWith("Inno.Editor.", StringComparison.Ordinal))); - Assert.Equal(sdkHost == "win-x64" ? "Inno.Editor.WindowsX64" : "Inno.Editor.MacOSArm64", - product.GetProperty("Filename").GetString()); + JsonElement[] references = document.RootElement.GetProperty("Items") + .GetProperty("ProjectReference") + .EnumerateArray() + .ToArray(); + JsonElement product = Assert.Single( + references.Where(reference => reference.GetProperty("Filename") + .GetString()! + .StartsWith("Inno.Editor.", StringComparison.Ordinal)) + ); + Assert.Equal( + sdkHost == "win-x64" ? "Inno.Editor.WindowsX64" : "Inno.Editor.MacOSArm64", + product.GetProperty("Filename").GetString() + ); foreach (JsonElement reference in references) { string declarations = reference.TryGetProperty("AdditionalProperties", out JsonElement value) - ? value.GetString() ?? string.Empty : string.Empty; + ? value.GetString() ?? string.Empty + : string.Empty; Assert.Equal(!designTime, declarations.Split(';').Contains("BuildProjectReferences=true", StringComparer.Ordinal)); Assert.Equal(!designTime, declarations.Split(';').Contains("BuildingInsideVisualStudio=false", StringComparer.Ordinal)); } diff --git a/tests/build/Inno.Build.Integration.Tests/DotNetSdkEnvironmentTests.cs b/tests/build/Inno.Build.Integration.Tests/DotNetSdkEnvironmentTests.cs index 3a6271115..b9754e94b 100644 --- a/tests/build/Inno.Build.Integration.Tests/DotNetSdkEnvironmentTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/DotNetSdkEnvironmentTests.cs @@ -3,8 +3,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Integration.Tests; @@ -32,19 +32,29 @@ public async Task SelectedSdkIgnoresAnInvokingBuildsSdkIdentityAndPreservesItsNa try { string project = Path.Combine(root, "Sdk.csproj"); - await File.WriteAllTextAsync(project, - "net10.0"); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, + await File.WriteAllTextAsync( + project, + "net10.0" + ); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, ["msbuild", project, "-nologo", "-nodeReuse:false", "-getProperty:TargetFramework"], - root, CancellationToken.None, selected); + root, + CancellationToken.None, + selected + ); Assert.Equal("net10.0", output.Trim()); string resolvedHost = ToolchainEnvironment.ResolveExecutable(host); string relativeHost = Path.GetRelativePath(Environment.CurrentDirectory, resolvedHost); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(relativeHost, project); Assert.Equal(resolvedHost, sdk.hostPath); - string sdkVersion = await ToolchainEnvironment.CaptureOutputAsync(sdk.hostPath, - [sdk.cliPath, "--version"], root, CancellationToken.None, - DotNetSdkEnvironment.Create(sdk.hostPath)); + string sdkVersion = await ToolchainEnvironment.CaptureOutputAsync( + sdk.hostPath, + [sdk.cliPath, "--version"], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); Assert.Equal(sdk.sdkIdentity, sdkVersion.Trim()); Assert.Equal(parent, Environment.GetEnvironmentVariable("MSBuildSDKsPath")); } diff --git a/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs b/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs index c7290a9f1..4af7e2102 100644 --- a/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs @@ -29,8 +29,18 @@ string nativeFileName string projectRoot = Path.Combine(m_root, new string('p', 70), new string('p', 70), "PlayerLink"); Directory.CreateDirectory(projectRoot); string project = Path.Combine(projectRoot, "Player.csproj"); - File.Copy(Path.Combine(engine, "platforms", platform, "build", "Inno.Build." + platform, - "Templates", platform + "Player.project.xml"), project); + File.Copy( + Path.Combine( + engine, + "platforms", + platform, + "build", + "Inno.Build." + platform, + "Templates", + platform + "Player.project.xml" + ), + project + ); File.Copy(Path.Combine(engine, "global.json"), Path.Combine(m_root, "global.json")); File.WriteAllText(Path.Combine(projectRoot, "Program.cs"), "using System; Console.WriteLine(\"Published\");"); File.WriteAllText(Path.Combine(projectRoot, "PlayerDeploymentDefinition.g.cs"), "// The fixture has no game registrations."); @@ -45,21 +55,32 @@ string nativeFileName string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); IToolchainWorkspaceProvider workspaces = OperatingSystem.IsWindows() - ? new WindowsToolchainWorkspaceProvider() : new PhysicalToolchainWorkspaceProvider(); + ? new WindowsToolchainWorkspaceProvider() + : new PhysicalToolchainWorkspaceProvider(); CoreClrDeploymentCompiler compiler = new(host, [RuntimeInformation.RuntimeIdentifier], workspaces); using CancellationTokenSource timeout = new(TimeSpan.FromMinutes(3)); DotNetSdkDescriptor selectedSdk = await DotNetSdkResolver.ResolveAsync(host, project, timeout.Token); XDocument definition = XDocument.Load(project); - definition.Root!.Add(new XElement("Target", - new XAttribute("Name", "VerifySelectedSdk"), - new XAttribute("BeforeTargets", "PrepareForBuild"), - new XElement("Error", - new XAttribute("Condition", $"'$(NETCoreSdkVersion)' != '{selectedSdk.sdkIdentity}'"), - new XAttribute("Text", "Publication changed the project-selected SDK.")))); + definition.Root!.Add( + new XElement( + "Target", + new XAttribute("Name", "VerifySelectedSdk"), + new XAttribute("BeforeTargets", "PrepareForBuild"), + new XElement( + "Error", + new XAttribute("Condition", $"'$(NETCoreSdkVersion)' != '{selectedSdk.sdkIdentity}'"), + new XAttribute("Text", "Publication changed the project-selected SDK.") + ) + ) + ); definition.Save(project); - string evaluated = await ToolchainEnvironment.CaptureOutputAsync(selectedSdk.hostPath, + string evaluated = await ToolchainEnvironment.CaptureOutputAsync( + selectedSdk.hostPath, [selectedSdk.cliPath, "msbuild", project, "-getItem:Content", "-nologo"], - projectRoot, timeout.Token, DotNetSdkEnvironment.Create(selectedSdk.hostPath)); + projectRoot, + timeout.Token, + DotNetSdkEnvironment.Create(selectedSdk.hostPath) + ); using (JsonDocument items = JsonDocument.Parse(evaluated)) { JsonElement content = Assert.Single(items.RootElement.GetProperty("Items").GetProperty("Content").EnumerateArray()); @@ -69,14 +90,22 @@ string nativeFileName ManagedDeploymentResult result; try { - result = await compiler.CompileAsync(new ManagedDeploymentRequest( - project, RuntimeInformation.RuntimeIdentifier, code, output, Path.Combine(m_root, "Logs")), timeout.Token); + result = await compiler.CompileAsync( + new ManagedDeploymentRequest( + project, + RuntimeInformation.RuntimeIdentifier, + code, + output, + Path.Combine(m_root, "Logs") + ), + timeout.Token + ); } catch (InvalidOperationException exception) { string[] observed = Directory.Exists(output) - ? Directory.GetFiles(output, "*", SearchOption.AllDirectories) - : []; + ? Directory.GetFiles(output, "*", SearchOption.AllDirectories) + : []; string layout = string.Join(", ", Array.ConvertAll(observed, file => Path.GetRelativePath(output, file))); throw new InvalidOperationException($"Publication output '{output}' contained [{layout}].", exception); } @@ -84,10 +113,22 @@ string nativeFileName Assert.Contains(nativeRelative, result.files); Assert.Equal(File.ReadAllBytes(nativeInput), File.ReadAllBytes(deployed)); // PublishDir is also supplied by external SDK callers without a trailing separator. - await ToolchainEnvironment.RunAsync(selectedSdk.hostPath, - [selectedSdk.cliPath, "msbuild", project, "-target:ValidateNativePublicationOutput", - "-p:PublishDir=" + output, "-nologo", "-m:1", "-nodeReuse:false"], - projectRoot, timeout.Token, DotNetSdkEnvironment.Create(selectedSdk.hostPath)); + await ToolchainEnvironment.RunAsync( + selectedSdk.hostPath, + [ + selectedSdk.cliPath, + "msbuild", + project, + "-target:ValidateNativePublicationOutput", + "-p:PublishDir=" + output, + "-nologo", + "-m:1", + "-nodeReuse:false" + ], + projectRoot, + timeout.Token, + DotNetSdkEnvironment.Create(selectedSdk.hostPath) + ); string[] executionPaths = File.ReadAllLines(Path.Combine(m_root, "Logs", "managed-working-directory.txt")); Assert.Equal(projectRoot, executionPaths[0]); if (OperatingSystem.IsWindows()) @@ -98,8 +139,16 @@ await ToolchainEnvironment.RunAsync(selectedSdk.hostPath, File.Delete(nativeInput); InvalidOperationException failure = await Assert.ThrowsAsync(async () => - await compiler.CompileAsync(new ManagedDeploymentRequest(project, RuntimeInformation.RuntimeIdentifier, - code, Path.Combine(m_root, "Rejected"), Path.Combine(m_root, "RejectedLogs")), timeout.Token)); + await compiler.CompileAsync( + new ManagedDeploymentRequest( + project, + RuntimeInformation.RuntimeIdentifier, + code, + Path.Combine(m_root, "Rejected"), + Path.Combine(m_root, "RejectedLogs") + ), + timeout.Token + )); Assert.Contains("explicitly deployed native runtime closure", failure.Message); Assert.True(File.Exists(deployed)); } @@ -107,6 +156,8 @@ await compiler.CompileAsync(new ManagedDeploymentRequest(project, RuntimeInforma public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs b/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs index df077039e..2e42ffc48 100644 --- a/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Source; using System; using System.Diagnostics; using System.IO; using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -28,16 +28,27 @@ public async Task CompilerToolsKeepTheirSdkOutputOwnerWhenGivenAnExplicitRuntime { string root = TestRepository.GetRoot(typeof(GeneratorRestoreScopeTests).Assembly); string project = Path.Combine(root, relative); - using Process process = new() { StartInfo = new ProcessStartInfo("dotnet") + using Process process = new() { - UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true - } }; + StartInfo = new ProcessStartInfo("dotnet") + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + } + }; foreach (string argument in new[] { - "msbuild", project, "-getProperty:BaseIntermediateOutputPath,IsRoslynComponent,RuntimeIdentifier", - "-p:InnoNativeTarget=windows-x64", "-p:RuntimeIdentifier=win-x64", "-nodeReuse:false" - }) + "msbuild", + project, + "-getProperty:BaseIntermediateOutputPath,IsRoslynComponent,RuntimeIdentifier", + "-p:InnoNativeTarget=windows-x64", + "-p:RuntimeIdentifier=win-x64", + "-nodeReuse:false" + }) { process.StartInfo.ArgumentList.Add(argument); + } Assert.True(process.Start()); Task output = process.StandardOutput.ReadToEndAsync(); Task error = process.StandardError.ReadToEndAsync(); diff --git a/tests/build/Inno.Build.Integration.Tests/HostRuntimeClosureBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/HostRuntimeClosureBuildTests.cs index d5abe385a..64503d34e 100644 --- a/tests/build/Inno.Build.Integration.Tests/HostRuntimeClosureBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/HostRuntimeClosureBuildTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Security; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -25,15 +25,30 @@ public async Task RuntimeDiscoveryReceivesPrivateDependenciesWithoutExposingThei string artifacts = Path.Combine(root, "managed"); try { - string extension = WriteProject(root, "Inno.Fixture.Extension", string.Empty, - "namespace Inno.Fixture.Extension; public sealed class Marker { }"); - string library = WriteProject(root, "Inno.Fixture.Host", + string extension = WriteProject( + root, + "Inno.Fixture.Extension", + string.Empty, + "namespace Inno.Fixture.Extension; public sealed class Marker { }" + ); + string library = WriteProject( + root, + "Inno.Fixture.Host", $"{exposeClosure.ToString().ToLowerInvariant()}" + $"", - "namespace Inno.Fixture.Host; public sealed class Marker { }"); - string adapter = Path.Combine(engine, "backends", "DotNet", "runtime", "Inno.Adapter.Modules.DotNet", - "Inno.Adapter.Modules.DotNet.csproj"); - string application = WriteProject(root, "Host", + "namespace Inno.Fixture.Host; public sealed class Marker { }" + ); + string adapter = Path.Combine( + engine, + "backends", + "DotNet", + "runtime", + "Inno.Adapter.Modules.DotNet", + "Inno.Adapter.Modules.DotNet.csproj" + ); + string application = WriteProject( + root, + "Host", "Exe" + $"" + $"", @@ -48,43 +63,90 @@ private static int Main() return source.GetAssemblies().Any(assembly => assembly.GetName().Name == "Inno.Fixture.Extension") ? 0 : 13; } } - """); + """ + ); string[] properties = ["-p:ArtifactsPath=" + artifacts, "-p:UseSharedCompilation=false"]; - await ToolchainEnvironment.RunAsync(dotnet, + await ToolchainEnvironment.RunAsync( + dotnet, ["build", application, "-c", "Release", "--disable-build-servers", "-m:1", "-nr:false", ..properties], - root, CancellationToken.None, DotNetSdkEnvironment.Create(dotnet)); - string executable = (await ToolchainEnvironment.CaptureOutputAsync(dotnet, - ["msbuild", application, "-nologo", "-m:1", "-nr:false", "-p:Configuration=Release", - "-getProperty:TargetPath", ..properties], root, CancellationToken.None, - DotNetSdkEnvironment.Create(dotnet))).Trim(); + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(dotnet) + ); + string executable = (await ToolchainEnvironment.CaptureOutputAsync( + dotnet, + [ + "msbuild", + application, + "-nologo", + "-m:1", + "-nr:false", + "-p:Configuration=Release", + "-getProperty:TargetPath", + ..properties + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(dotnet) + )).Trim(); string output = Path.GetDirectoryName(executable)!; Assert.Equal(exposeClosure, File.Exists(Path.Combine(output, "Inno.Fixture.Extension.dll"))); Assert.Equal(exposeClosure, File.Exists(Path.Combine(output, "Inno.Fixture.Host.deps.json"))); if (exposeClosure) - await ToolchainEnvironment.RunAsync(dotnet, [executable], root, CancellationToken.None, - DotNetSdkEnvironment.Create(dotnet)); + { + await ToolchainEnvironment.RunAsync( + dotnet, + [executable], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(dotnet) + ); + } else { InvalidOperationException unavailable = await Assert.ThrowsAsync(() => - ToolchainEnvironment.RunAsync(dotnet, [executable], root, CancellationToken.None, - DotNetSdkEnvironment.Create(dotnet))); + ToolchainEnvironment.RunAsync( + dotnet, + [executable], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(dotnet) + )); Assert.EndsWith("exit code 13.", unavailable.Message); } - File.WriteAllText(Path.Combine(Path.GetDirectoryName(application)!, "ForbiddenCompile.cs"), - "internal sealed class ForbiddenCompile { private readonly Inno.Fixture.Extension.Marker m_value = new(); }"); + File.WriteAllText( + Path.Combine(Path.GetDirectoryName(application)!, "ForbiddenCompile.cs"), + "internal sealed class ForbiddenCompile { private readonly Inno.Fixture.Extension.Marker m_value = new(); }" + ); string compilerLog = Path.Combine(root, "negative-compile.log"); await Assert.ThrowsAsync(() => - ToolchainEnvironment.RunAsync(dotnet, - ["build", application, "-c", "Release", "--no-restore", "--disable-build-servers", "-m:1", "-nr:false", - "-flp:logfile=" + compilerLog + ";verbosity=normal", ..properties], - root, CancellationToken.None, DotNetSdkEnvironment.Create(dotnet))); + ToolchainEnvironment.RunAsync( + dotnet, + [ + "build", + application, + "-c", + "Release", + "--no-restore", + "--disable-build-servers", + "-m:1", + "-nr:false", + "-flp:logfile=" + compilerLog + ";verbosity=normal", + ..properties + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(dotnet) + )); Assert.Contains("CS0234", File.ReadAllText(compilerLog)); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs b/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs index b09c63312..88590924c 100644 --- a/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs @@ -4,9 +4,9 @@ using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -18,17 +18,26 @@ public ManagedBuildInputSnapshotTests() { Directory.CreateDirectory(m_root); File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), "fixture"); - Write("Shared/Shared.csproj", "net10.0"); + Write( + "Shared/Shared.csproj", + "net10.0" + ); Write("Shared/Shared.cs", "public sealed class Shared { }"); - Write("App/App.csproj", "net10.0" + Write( + "App/App.csproj", + "net10.0" + "disable" + "" - + ""); + + "" + ); Write("App/Options.props", "FIXTURE"); Write("App/App.cs", "public sealed class App { }"); Write("App/data.txt", "first"); Write("App/input.txt", "first"); - Write("Tool/Tool.csproj", "net10.0"); + Write( + "Tool/Tool.csproj", + "net10.0" + ); Write("Tool/Tool.cs", "public sealed class Tool { }"); } @@ -38,19 +47,39 @@ public ManagedBuildInputSnapshotTests() public async Task FrameworkSelectionUsesTheSdkAndRestoredTargetSemantics(string framework) { string project = Path.Combine(m_root, "App", "App.csproj"); - File.WriteAllText(project, File.ReadAllText(project).Replace("net10.0", - "" + framework + "", StringComparison.Ordinal)); + File.WriteAllText( + project, + File.ReadAllText(project).Replace( + "net10.0", + "" + framework + "", + StringComparison.Ordinal + ) + ); string shared = Path.Combine(m_root, "Shared", "Shared.csproj"); - File.WriteAllText(shared, File.ReadAllText(shared).Replace("net10.0", - "" + framework + "", StringComparison.Ordinal)); + File.WriteAllText( + shared, + File.ReadAllText(shared).Replace( + "net10.0", + "" + framework + "", + StringComparison.Ordinal + ) + ); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( - new NativeBuildContext(m_root, "release"), sdk, project, - new Dictionary { ["Configuration"] = "Release" }); + new NativeBuildContext(m_root, "release"), + sdk, + project, + new Dictionary { ["Configuration"] = "Release" } + ); Assert.NotEmpty(snapshot.fingerprint); await snapshot.VerifyAsync(); @@ -75,12 +104,20 @@ public async Task PackageDeclarationsBelongToFrozenCompilationInputs() string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project, cancellation.Token); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "restore", project, "--disable-build-servers", "-v:quiet"], - m_root, cancellation.Token, DotNetSdkEnvironment.Create(sdk.hostPath)); + m_root, + cancellation.Token, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( - new NativeBuildContext(m_root, "release"), sdk, project, - new Dictionary { ["Configuration"] = "Release" }, cancellation.Token); + new NativeBuildContext(m_root, "release"), + sdk, + project, + new Dictionary { ["Configuration"] = "Release" }, + cancellation.Token + ); using ManagedBuildExecution execution = await snapshot.CreateExecutionAsync(cancellation.Token); string source = Path.Combine(m_root, "App", "Options.props"); string frozen = Path.Combine(execution.engineRoot, "App", "Options.props"); @@ -94,31 +131,48 @@ await ToolchainEnvironment.RunAsync(sdk.hostPath, public async Task RuntimeInputEvaluationDoesNotShareOrdinaryRestoreOutputs() { string project = Path.Combine(m_root, "App", "App.csproj"); - File.WriteAllText(project, File.ReadAllText(project).Replace("", - "", StringComparison.Ordinal)); - Write("Tool/Tool.csproj", "net10.0" + File.WriteAllText( + project, + File.ReadAllText(project).Replace( + "", + "", + StringComparison.Ordinal + ) + ); + Write( + "Tool/Tool.csproj", + "net10.0" + "disable" - + ""); + + "" + ); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); await RestoreOrdinary(); string assets = Path.Combine(m_root, "App", "obj", "project.assets.json"); byte[] ordinary = File.ReadAllBytes(assets); ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( - new NativeBuildContext(m_root, "release"), sdk, project, + new NativeBuildContext(m_root, "release"), + sdk, + project, new Dictionary { ["Configuration"] = "Release", ["RuntimeIdentifier"] = RuntimeInformation.RuntimeIdentifier - }); + } + ); Assert.Equal(ordinary, File.ReadAllBytes(assets)); await Task.WhenAll(RestoreOrdinary(), snapshot.VerifyAsync().AsTask()); Assert.Equal(ordinary, File.ReadAllBytes(assets)); Assert.False(Directory.Exists(Path.Combine(m_root, "App", "bin"))); - Task RestoreOrdinary() => ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "restore", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + Task RestoreOrdinary() + => ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); } [Fact] @@ -128,30 +182,56 @@ public async Task CheckoutAliasPreservesOwnedSourcesWhileSharingPhysicalInputRea try { if (OperatingSystem.IsWindows()) - await ToolchainEnvironment.RunAsync("powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", - "New-Item -ItemType Junction -Path '" + alias + "' -Target '" + m_root + "' | Out-Null"], - m_root, CancellationToken.None); + { + await ToolchainEnvironment.RunAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + "New-Item -ItemType Junction -Path '" + alias + "' -Target '" + m_root + "' | Out-Null" + ], + m_root, + CancellationToken.None + ); + } else + { Directory.CreateSymbolicLink(alias, m_root); + } string project = Path.Combine(alias, "App", "App.csproj"); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], - alias, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], + alias, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); var context = new NativeBuildContext(alias, "release"); - ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync(context, sdk, project, - new Dictionary { ["Configuration"] = "Release" }); + ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( + context, + sdk, + project, + new Dictionary { ["Configuration"] = "Release" } + ); using ManagedBuildExecution execution = await snapshot.CreateExecutionAsync(); Assert.Contains("class App", File.ReadAllText(Path.Combine(execution.engineRoot, "App", "App.cs")), StringComparison.Ordinal); - Assert.Contains("class Shared", File.ReadAllText(Path.Combine(execution.engineRoot, "Shared", "Shared.cs")), StringComparison.Ordinal); + Assert.Contains( + "class Shared", + File.ReadAllText(Path.Combine(execution.engineRoot, "Shared", "Shared.cs")), + StringComparison.Ordinal + ); await snapshot.VerifyAsync(); await execution.VerifyAsync(); } finally { if (Directory.Exists(alias)) + { Directory.Delete(alias, recursive: false); + } } } @@ -160,25 +240,58 @@ public async Task FixedExecutionCompilesPlannedBytesWhenTheOriginalSourceChanges { Write("Vendor/bin/tool.dat", "owned vendor tool"); string fixture = Path.Combine(m_root, "App", "App.csproj"); - File.WriteAllText(fixture, File.ReadAllText(fixture).Replace("", - "", StringComparison.Ordinal)); + File.WriteAllText( + fixture, + File.ReadAllText(fixture).Replace( + "", + "
", + StringComparison.Ordinal + ) + ); string project = Path.Combine(m_root, "App", "App.csproj"); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); var context = new NativeBuildContext(m_root, "release"); - ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync(context, sdk, project, - new System.Collections.Generic.Dictionary { ["Configuration"] = "Release" }); + ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( + context, + sdk, + project, + new System.Collections.Generic.Dictionary { ["Configuration"] = "Release" } + ); using ManagedBuildExecution execution = await snapshot.CreateExecutionAsync(); Assert.Equal("owned vendor tool", File.ReadAllText(Path.Combine(execution.engineRoot, "Vendor", "bin", "tool.dat"))); string original = Path.Combine(m_root, "App", "App.cs"); File.WriteAllText(original, "public sealed class Changed { }"); - Assert.Contains("class App", File.ReadAllText(Path.Combine(Path.GetDirectoryName(execution.project)!, "App.cs")), StringComparison.Ordinal); - await ToolchainEnvironment.RunAsync(sdk.hostPath, - [sdk.cliPath, "build", execution.project, "--configuration", "Release", "--disable-build-servers", - "-m:1", "-nodeReuse:false", "--nologo", "-v:quiet"], execution.engineRoot, CancellationToken.None, - DotNetSdkEnvironment.Create(sdk.hostPath)); + Assert.Contains( + "class App", + File.ReadAllText(Path.Combine(Path.GetDirectoryName(execution.project)!, "App.cs")), + StringComparison.Ordinal + ); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [ + sdk.cliPath, + "build", + execution.project, + "--configuration", + "Release", + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "--nologo", + "-v:quiet" + ], + execution.engineRoot, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); File.WriteAllText(original, "public sealed class App { }"); await snapshot.VerifyAsync(); await execution.VerifyAsync(); @@ -186,8 +299,12 @@ await ToolchainEnvironment.RunAsync(sdk.hostPath, using FileStream stream = File.OpenRead(output); using var image = new System.Reflection.PortableExecutable.PEReader(stream); System.Reflection.Metadata.MetadataReader metadata = System.Reflection.Metadata.PEReaderExtensions.GetMetadataReader(image); - string[] names = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Select(metadata.TypeDefinitions, - handle => metadata.GetString(metadata.GetTypeDefinition(handle).Name))); + string[] names = System.Linq.Enumerable.ToArray( + System.Linq.Enumerable.Select( + metadata.TypeDefinitions, + handle => metadata.GetString(metadata.GetTypeDefinition(handle).Name) + ) + ); Assert.Contains("App", names); Assert.DoesNotContain("Changed", names); } @@ -198,12 +315,28 @@ public async Task SelectedSdkGraphDetectsSameLengthSourceResourceImportAndNewFil string project = Path.Combine(m_root, "App", "App.csproj"); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", Path.Combine(m_root, "Tool", "Tool.csproj"), "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); - File.WriteAllText(project, File.ReadAllText(project).Replace("", - "", StringComparison.Ordinal)); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", Path.Combine(m_root, "Tool", "Tool.csproj"), "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); + File.WriteAllText( + project, + File.ReadAllText(project).Replace( + "", + "", + StringComparison.Ordinal + ) + ); var properties = new Dictionary { ["Configuration"] = "Release" }; ManagedBuildInputSnapshot original = await Capture(sdk, project, properties); await original.VerifyAsync(); @@ -214,10 +347,16 @@ await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", Path. string file = Path.Combine(m_root, path); string previous = File.ReadAllText(file); DateTime timestamp = File.GetLastWriteTimeUtc(file); - File.WriteAllText(file, previous.Replace("first", "other", StringComparison.Ordinal) - .Replace("Shared", "Change", StringComparison.Ordinal).Replace("FIXTURE", "CHANGED", StringComparison.Ordinal)); + File.WriteAllText( + file, + previous.Replace("first", "other", StringComparison.Ordinal) + .Replace("Shared", "Change", StringComparison.Ordinal) + .Replace("FIXTURE", "CHANGED", StringComparison.Ordinal) + ); if (path == "Tool/Tool.cs") + { File.WriteAllText(file, previous.Replace("Tool", "Next", StringComparison.Ordinal)); + } File.SetLastWriteTimeUtc(file, timestamp); await Assert.ThrowsAsync(() => original.VerifyAsync().AsTask()); File.WriteAllText(file, previous); @@ -226,8 +365,10 @@ await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", Path. Write("App/Added.cs", "public sealed class Added { }"); await Assert.ThrowsAsync(() => original.VerifyAsync().AsTask()); Assert.False(Directory.Exists(Path.Combine(m_root, "App", "bin"))); - Assert.All(Directory.EnumerateDirectories(Path.Combine(m_root, "artifacts", "build-tools", "managed-inputs")), - static directory => Assert.Contains(Path.GetFileName(directory), new[] { "evaluators", "requests" })); + Assert.All( + Directory.EnumerateDirectories(Path.Combine(m_root, "artifacts", "build-tools", "managed-inputs")), + static directory => Assert.Contains(Path.GetFileName(directory), new[] { "evaluators", "requests" }) + ); string requests = Path.Combine(m_root, "artifacts", "build-tools", "managed-inputs", "requests"); Assert.Empty(ProcessOwnedDirectory.ReadClaims(requests)); Assert.Empty(Directory.EnumerateDirectories(requests)); @@ -251,7 +392,10 @@ IReadOnlyDictionary globals public async Task SdkPreparedSymbolsParticipateInTheFrozenInputIdentity() { string project = Path.Combine(m_root, "App", "App.csproj"); - File.WriteAllText(project, File.ReadAllText(project).Replace("", "", StringComparison.Ordinal)); + File.WriteAllText( + project, + File.ReadAllText(project).Replace("", "", StringComparison.Ordinal) + ); Write("App/Symbols.targets", """ @@ -269,11 +413,19 @@ public async Task SdkPreparedSymbolsParticipateInTheFrozenInputIdentity() Environment.SetEnvironmentVariable("INNO_TEST_COMPILER_SYMBOL", "FIRST_SYMBOL"); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(dotnet, project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], - m_root, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, + [sdk.cliPath, "restore", project, "--nologo", "-v:quiet"], + m_root, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); ManagedBuildInputSnapshot snapshot = await ManagedBuildInputSnapshot.CaptureAsync( - new NativeBuildContext(m_root, "release"), sdk, project, - new Dictionary { ["Configuration"] = "Release" }); + new NativeBuildContext(m_root, "release"), + sdk, + project, + new Dictionary { ["Configuration"] = "Release" } + ); await snapshot.VerifyAsync(); Environment.SetEnvironmentVariable("INNO_TEST_COMPILER_SYMBOL", "SECOND_SYMBOL"); InvalidOperationException failure = await Assert.ThrowsAsync(() => snapshot.VerifyAsync().AsTask()); diff --git a/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs b/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs index cb56e13b2..c18851fa3 100644 --- a/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs @@ -1,6 +1,3 @@ -using Inno.Build.Toolchains; -using Inno.Core.IO; -using Inno.Testing.Source; using System; using System.Collections.Generic; using System.IO; @@ -9,6 +6,9 @@ using System.Threading; using System.Threading.Tasks; using Xunit; +using Inno.Build.Toolchains; +using Inno.Core.IO; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -21,7 +21,7 @@ public async Task ProductOutputOwnersRemainStableAcrossCheckoutBindings() string owner = Path.Combine(Path.GetTempPath(), "InnoManagedOutputTests"); string fixture = PathBoundary.Resolve(owner, Guid.NewGuid().ToString("N")); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? ToolchainEnvironment.ResolveExecutable("dotnet"); + ?? ToolchainEnvironment.ResolveExecutable("dotnet"); var outputs = new List>(); Directory.CreateDirectory(fixture); try @@ -31,7 +31,9 @@ public async Task ProductOutputOwnersRemainStableAcrossCheckoutBindings() string checkoutRoot = Path.Combine(fixture, checkout); Directory.CreateDirectory(Path.Combine(checkoutRoot, "build", "msbuild")); foreach (string source in new[] { "global.json", "Directory.Build.props", "build/msbuild/Inno.Packages.props" }) + { File.Copy(Path.Combine(root, source), Path.Combine(checkoutRoot, source)); + } await File.WriteAllTextAsync(Path.Combine(checkoutRoot, "Directory.Build.targets"), ""); string productProperties = Path.Combine(checkoutRoot, "Product.props"); await File.WriteAllTextAsync(productProperties, ""); @@ -44,7 +46,9 @@ await File.WriteAllTextAsync(project, """ await File.WriteAllTextAsync(Path.Combine(checkoutRoot, "Shared.cs"), "public sealed class Shared { }"); var properties = new List { - "-p:Configuration=Debug", "-p:InnoNativeTarget=test-target", "-p:InnoToolTarget=test-host", + "-p:Configuration=Debug", + "-p:InnoNativeTarget=test-target", + "-p:InnoToolTarget=test-host", "-p:ArtifactsPath=" + Path.Combine(checkoutRoot, "outputs"), "-p:InnoProductBuildProperties=" + productProperties }; @@ -95,15 +99,19 @@ await File.WriteAllTextAsync(project, """ """); await File.WriteAllTextAsync(Path.Combine(fixture, "Shared.cs"), "public sealed class Shared { }"); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? ToolchainEnvironment.ResolveExecutable("dotnet"); + ?? ToolchainEnvironment.ResolveExecutable("dotnet"); var common = new List { $"-p:Configuration={configuration}" }; if (artifacts) + { common.Add($"-p:ArtifactsPath={Path.Combine(fixture, "outputs")}"); + } Dictionary neutral = await EvaluateAsync(host, project, common); var productArguments = new List(common) { "-p:InnoNativeTarget=test-target" }; Dictionary product = await EvaluateAsync(host, project, productArguments); foreach (string property in new[] { "ProjectAssetsFile", "IntermediateOutputPath", "TargetPath" }) + { Assert.NotEqual(neutral[property], product[property]); + } var compileArguments = new List(productArguments) { @@ -151,7 +159,9 @@ await File.WriteAllTextAsync(project, """ Assert.NotEqual(product["TargetPath"], rid["TargetPath"]); foreach (List request in new[] { common, productArguments }) + { await RunAsync(host, fixture, ["restore", project, .. request, "-v:quiet"]); + } string driver = Path.Combine(fixture, "Build.proj"); await File.WriteAllTextAsync(driver, $""" @@ -183,13 +193,18 @@ List properties ) { using var output = new StringWriter(); await RunAsync(host, Path.GetDirectoryName(project)!, [ - "msbuild", project, "-nologo", .. properties, + "msbuild", + project, + "-nologo", + .. properties, "-getProperty:ProjectAssetsFile,IntermediateOutputPath,TargetPath,RuntimeIdentifier" ], output); using JsonDocument document = JsonDocument.Parse(output.ToString()); var values = new Dictionary(StringComparer.Ordinal); foreach (JsonProperty property in document.RootElement.GetProperty("Properties").EnumerateObject()) + { values.Add(property.Name, property.Value.GetString()!); + } return values; } @@ -203,7 +218,14 @@ private static async Task RunAsync( using var error = new StringWriter(); using var captured = new StringWriter(); Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( - host, arguments, directory, cancellation.Token, DotNetSdkEnvironment.Create(host), output ?? captured, error)); + host, + arguments, + directory, + cancellation.Token, + DotNetSdkEnvironment.Create(host), + output ?? captured, + error + )); Assert.True(failure is null, $"{failure}{Environment.NewLine}{output ?? captured}{Environment.NewLine}{error}"); } } diff --git a/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs b/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs index 236b263d7..c6b09d75c 100644 --- a/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs @@ -6,8 +6,7 @@ using System.Text.Json; using System.Threading.Tasks; using System.Xml.Linq; -using Inno.Testing.Source; - +using Xunit; using Inno.Build; using Inno.Build.Distribution.Standard; using Inno.Build.MacOSArm64; @@ -15,7 +14,7 @@ using Inno.Build.Toolchains; using Inno.Build.WindowsX64; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -34,65 +33,102 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection File.WriteAllText(Path.Combine(root, "Generated", "Bindings.cs"), "#error Host bindings must not be compiled for this target."); File.WriteAllText(Path.Combine(root, "Source", "api.h"), "int sample(int value);"); string config = Path.Combine(root, "bindgen.json"); - File.WriteAllText(config, JsonSerializer.Serialize(new - { - schemaVersion = 2, - library = new { id = "fixture", nativeName = "fixture" }, - source = new { language = "c", headers = new[] { "Source/api.h" } }, - api = new { @namespace = "Fixture.Native", name = "Api" }, - output = new { root = "Generated", layout = "singleFile" } - })); + File.WriteAllText( + config, + JsonSerializer.Serialize(new + { + schemaVersion = 2, + library = new { id = "fixture", nativeName = "fixture" }, + source = new { language = "c", headers = new[] { "Source/api.h" } }, + api = new { @namespace = "Fixture.Native", name = "Api" }, + output = new { root = "Generated", layout = "singleFile" } + }) + ); string engine = TestRepository.GetRoot(typeof(NativeBindingCompilationTests).Assembly); BuildHostDescriptor host = StandardBuildHosts.Capture(); PlatformTargetDescriptor[] targets = [WindowsX64BuildModule.target, MacOSArm64BuildModule.target]; - string targetId = Assert.Single(targets.Where(target => target.platform == host.system - && target.architecture == host.architecture)).id.value; + string targetId = Assert.Single( + targets.Where(target => (target.platform == host.system && target.architecture == host.architecture)) + ).id.value; IEnumerable profileDirectories = Directory.EnumerateDirectories(Path.Combine(engine, "platforms")) - .Select(platform => Path.Combine(platform, "integrations")).Where(Directory.Exists) + .Select(platform => Path.Combine(platform, "integrations")) + .Where(Directory.Exists) .SelectMany(Directory.EnumerateDirectories) - .Select(integration => Path.Combine(integration, "Bindings")).Where(Directory.Exists); - foreach (string profile in profileDirectories.SelectMany(directory => Directory.EnumerateFiles(directory, "*BindingProfile.cs"))) - { + .Select(integration => Path.Combine(integration, "Bindings")) + .Where(Directory.Exists); + foreach (string profile in profileDirectories.SelectMany( + directory => Directory.EnumerateFiles(directory, "*BindingProfile.cs") + )) { string profileInput = Path.Combine(root, Path.GetRelativePath(engine, profile)); Directory.CreateDirectory(Path.GetDirectoryName(profileInput)!); File.Copy(profile, profileInput); } File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), string.Empty); string definition = Path.Combine(root, "bindings.props"); - new XDocument(new XElement("Project", - new XElement("PropertyGroup", new XElement("InnoNativeComponentId", "fixture"), new XElement("InnoBindingConfig", "bindgen.json")))) + new XDocument( + new XElement( + "Project", + new XElement( + "PropertyGroup", + new XElement("InnoNativeComponentId", "fixture"), + new XElement("InnoBindingConfig", "bindgen.json") + ) + ) + ) .Save(definition); string sources = Path.Combine(root, "compile-sources.txt"); string project = Path.Combine(root, "Fixture.csproj"); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", - new XElement("TargetFramework", "net10.0"), - new XElement("LangVersion", "14.0"), - new XElement("AllowUnsafeBlocks", "true"), - new XElement("ImplicitUsings", "disable"), - new XElement("EnableDefaultCompileItems", "false"), - new XElement("Nullable", "enable"), - new XElement("IsTestProject", "true"), - new XElement("BindGenGeneratedBindings", "true"), - new XElement("InnoBindingTargetId", targetId), - new XElement("InnoBindingEngineRoot", root), - new XElement("InnoBindingDefinition", definition), - new XElement("InnoBindingOutputMode", "TargetArtifacts")), - new XElement("Import", new XAttribute("Project", definition)), - new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), - new XElement("ItemGroup", new XElement("Reference", new XAttribute("Include", "BGCS.Runtime"), - new XElement("HintPath", typeof(BGCS.Runtime.NativeModuleSession).Assembly.Location))), - new XElement("Target", new XAttribute("Name", "CaptureCompileSources"), - new XAttribute("AfterTargets", "ValidateBindGenBindings"), - new XElement("WriteLinesToFile", new XAttribute("File", sources), - new XAttribute("Lines", "@(Compile->'%(FullPath)')"), new XAttribute("Overwrite", "true"))))) + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("LangVersion", "14.0"), + new XElement("AllowUnsafeBlocks", "true"), + new XElement("ImplicitUsings", "disable"), + new XElement("EnableDefaultCompileItems", "false"), + new XElement("Nullable", "enable"), + new XElement("IsTestProject", "true"), + new XElement("BindGenGeneratedBindings", "true"), + new XElement("InnoBindingTargetId", targetId), + new XElement("InnoBindingEngineRoot", root), + new XElement("InnoBindingDefinition", definition), + new XElement("InnoBindingOutputMode", "TargetArtifacts") + ), + new XElement("Import", new XAttribute("Project", definition)), + new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), + new XElement( + "ItemGroup", + new XElement( + "Reference", + new XAttribute("Include", "BGCS.Runtime"), + new XElement("HintPath", typeof(BGCS.Runtime.NativeModuleSession).Assembly.Location) + ) + ), + new XElement( + "Target", + new XAttribute("Name", "CaptureCompileSources"), + new XAttribute("AfterTargets", "ValidateBindGenBindings"), + new XElement( + "WriteLinesToFile", + new XAttribute("File", sources), + new XAttribute("Lines", "@(Compile->'%(FullPath)')"), + new XAttribute("Overwrite", "true") + ) + ) + ) + ) .Save(project); (int success, string output) = await Build(project, []); Assert.True(success == 0, output); Assert.Equal(1, output.Split("INNO-TASK-HOST verified", StringSplitOptions.None).Length - 1); - string selected = Assert.Single(File.ReadAllLines(sources) - .Where(static path => Path.GetFileName(path) == "Bindings.cs")); + string selected = Assert.Single( + File.ReadAllLines(sources) + .Where(static path => Path.GetFileName(path) == "Bindings.cs") + ); Assert.Equal(Path.Combine(root, "obj", "Release", "net10.0", "bindings", "Bindings.cs"), selected); Assert.True(File.Exists(selected), output); string artifact = Assert.Single(Directory.GetDirectories(Path.Combine(root, "artifacts", "bindings", "fixture", targetId))); @@ -101,7 +137,8 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection Assert.True(File.Exists(Path.Combine(root, "bin", "Release", "net10.0", "Fixture.dll")), output); string selection = Path.Combine(root, "SelectedBindings.props"); - NativeBindingGenerationDescriptor.WriteSelection(selection, + NativeBindingGenerationDescriptor.WriteSelection( + selection, new Dictionary { [project] = new() @@ -113,11 +150,15 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection usesRuntimeImports = false, nativeDirectory = string.Empty } - }, new Dictionary { [project] = NativeLibraryKind.Shared }); + }, + new Dictionary { [project] = NativeLibraryKind.Shared } + ); (int reused, string reuseOutput) = await Build(project, ["-p:InnoNativeBindingSelection=" + selection]); Assert.True(reused == 0, reuseOutput); - Assert.Equal(selected, Assert.Single(File.ReadAllLines(sources) - .Where(static path => Path.GetFileName(path) == "Bindings.cs"))); + Assert.Equal( + selected, + Assert.Single(File.ReadAllLines(sources).Where(static path => Path.GetFileName(path) == "Bindings.cs")) + ); Assert.DoesNotContain("INNO-BINDINGS-PREPARE", reuseOutput); Assert.DoesNotContain("INNO-TASK-RUNTIME", reuseOutput); @@ -133,7 +174,8 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection Assert.True(File.Exists(Path.Combine(frozen, "obj", "Release", "net10.0", "bindings", "Bindings.cs"))); string staticSelection = Path.Combine(root, "StaticBindings.props"); - NativeBindingGenerationDescriptor.WriteSelection(staticSelection, + NativeBindingGenerationDescriptor.WriteSelection( + staticSelection, new Dictionary { [project] = new() @@ -145,9 +187,14 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection usesRuntimeImports = false, nativeDirectory = string.Empty } - }, new Dictionary { [project] = NativeLibraryKind.Static }); + }, + new Dictionary { [project] = NativeLibraryKind.Static } + ); string bootstrap = Path.Combine(root, "Bootstrap.cs"); - File.WriteAllText(bootstrap, "#if !INNO_STATIC_NATIVE\n#error The selected static component must omit dynamic initialization.\n#endif"); + File.WriteAllText( + bootstrap, + "#if !INNO_STATIC_NATIVE\n#error The selected static component must omit dynamic initialization.\n#endif" + ); XDocument staticProject = XDocument.Load(project); staticProject.Root!.Add(new XElement("ItemGroup", new XElement("Compile", new XAttribute("Include", bootstrap)))); staticProject.Save(project); @@ -158,15 +205,19 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection await VerifyTransitiveSelection(root, engine, project, selection, sources, selected); - (int rejected, string failure) = await Build(project, - ["-p:InnoNativeBindingSelection=" + Path.Combine(root, "absent-selection.props")]); + (int rejected, string failure) = await Build( + project, + ["-p:InnoNativeBindingSelection=" + Path.Combine(root, "absent-selection.props")] + ); Assert.NotEqual(0, rejected); Assert.Contains("The selected native binding manifest is missing", failure); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -183,44 +234,82 @@ string selected foreach (var entry in new[] { (path: middle, reference: nativeProject), (path: host, reference: middle) }) { Directory.CreateDirectory(Path.GetDirectoryName(entry.path)!); - var document = new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), - new XElement("IsTestProject", "true"), new XElement("EnableDefaultCompileItems", "false"), - new XElement("InnoProductReferenceProperties", "FixtureDeclared=true")), + var document = new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("IsTestProject", "true"), + new XElement("EnableDefaultCompileItems", "false"), + new XElement("InnoProductReferenceProperties", "FixtureDeclared=true") + ), new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.targets"))), - new XElement("ItemGroup", new XElement("ProjectReference", new XAttribute("Include", entry.reference)))); + new XElement("ItemGroup", new XElement("ProjectReference", new XAttribute("Include", entry.reference))) + ); if (entry.path == host) - document.Add(new XElement("Target", new XAttribute("Name", "SelectOperationBindings"), - new XAttribute("BeforeTargets", "AssignProjectConfiguration"), - new XElement("PropertyGroup", new XElement("InnoNativeBindingSelection", selection)), - new XElement("ItemGroup", new XElement("ProjectReference", - new XElement("AdditionalProperties", "InnoNativeBindingSelection=$(InnoNativeBindingSelection)"))))); + { + document.Add( + new XElement( + "Target", + new XAttribute("Name", "SelectOperationBindings"), + new XAttribute("BeforeTargets", "AssignProjectConfiguration"), + new XElement("PropertyGroup", new XElement("InnoNativeBindingSelection", selection)), + new XElement( + "ItemGroup", + new XElement( + "ProjectReference", + new XElement("AdditionalProperties", "InnoNativeBindingSelection=$(InnoNativeBindingSelection)") + ) + ) + ) + ); + } new XDocument(document).Save(entry.path); } (int exit, string output) = await Build(host, []); Assert.True(exit == 0, output); Assert.DoesNotContain("INNO-BINDINGS-PREPARE", output); Assert.DoesNotContain("INNO-TASK-RUNTIME", output); - Assert.Equal(selected, Assert.Single(File.ReadAllLines(sources) - .Where(static path => Path.GetFileName(path) == "Bindings.cs"))); + Assert.Equal( + selected, + Assert.Single(File.ReadAllLines(sources).Where(static path => Path.GetFileName(path) == "Bindings.cs")) + ); } private static async Task<(int exitCode, string output)> Build( string project, string[] arguments ) { - string host = Path.Combine(Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string host = Path.Combine( + Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(host) { - WorkingDirectory = TestRepository.GetRoot(typeof(NativeBindingCompilationTests).Assembly), UseShellExecute = false, CreateNoWindow = true, - RedirectStandardOutput = true, RedirectStandardError = true + WorkingDirectory = TestRepository.GetRoot(typeof(NativeBindingCompilationTests).Assembly), + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true }; // This temporary project owns its fixture component and exercises both generation and explicit selections. start.Environment.Remove("InnoNativeDependencyManifest"); - foreach (string argument in new[] { "build", project, "-c", "Release", "--disable-build-servers", "-m:1", "-nodeReuse:false", "-v:normal" } - .Concat(arguments)) + foreach (string argument in new[] + { + "build", + project, + "-c", + "Release", + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "-v:normal" + } + .Concat(arguments) + ) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start) ?? throw new InvalidOperationException("MSBuild did not start."); Task output = process.StandardOutput.ReadToEndAsync(); Task error = process.StandardError.ReadToEndAsync(); diff --git a/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs b/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs index 2347c6050..820c6a02c 100644 --- a/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs @@ -32,16 +32,19 @@ public async Task EveryDeclaredComponentConfigurationCanBeReadByTheInstalledSdk( { string root = TestRepository.GetRoot(typeof(NativeBindingConfigurationTests).Assembly); BuildCompositionContext environment = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId("windows-x64")); - ProductNativeBuildPlan product = StandardBuildDistribution.Create(environment).build.ResolveNativeProduct("windows-x64", "editor").plan; + ProductNativeBuildPlan product = StandardBuildDistribution.Create(environment).build + .ResolveNativeProduct("windows-x64", "editor").plan; using HostServices services = new HostServicesProvider().Create(new(root, JsonSerializer.SerializeToElement(new { }))); foreach (NativeComponentDescriptor owner in product.steps.Select(step => step.component) - .Where(owner => owner.bindingDefinition is not null).DistinctBy(owner => owner.nativeProject)) - { + .Where(owner => owner.bindingDefinition is not null) + .DistinctBy(owner => owner.nativeProject) + ) { string definition = Path.GetFullPath(owner.bindingDefinition!, root); XDocument document = XDocument.Load(definition); string[] configurations = document.Descendants("InnoBindingConfig") .Select(element => Path.GetFullPath(element.Value, Path.GetDirectoryName(definition)!)) - .Distinct(StringComparer.Ordinal).ToArray(); + .Distinct(StringComparer.Ordinal) + .ToArray(); Assert.NotEmpty(configurations); foreach (string configuration in configurations) { diff --git a/tests/build/Inno.Build.Integration.Tests/NativeBindingSelectionBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/NativeBindingSelectionBuildTests.cs index ab3fe086b..89f61f0bb 100644 --- a/tests/build/Inno.Build.Integration.Tests/NativeBindingSelectionBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NativeBindingSelectionBuildTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.Diagnostics; using System.IO; @@ -7,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -21,8 +21,13 @@ public async Task ANewSelectionDocumentDoesNotRecompileANeutralProject() try { foreach (string name in new[] { "Directory.Build.props", "Directory.Build.targets" }) - File.WriteAllText(Path.Combine(root, name), ""); + { + File.WriteAllText( + Path.Combine(root, name), + "" + ); + } File.WriteAllText(Path.Combine(root, "Probe.csproj"), """ net10.0disable @@ -49,8 +54,10 @@ private static async Task Build( string root, string selection ) { - string dotnet = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string dotnet = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(dotnet) { WorkingDirectory = root, @@ -59,9 +66,18 @@ string selection RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "build", "Probe.csproj", "--disable-build-servers", "--nologo", "-m:1", - "-nodeReuse:false", "-p:InnoNativeBindingSelection=" + selection }) + foreach (string argument in new[] + { + "build", + "Probe.csproj", + "--disable-build-servers", + "--nologo", + "-m:1", + "-nodeReuse:false", + "-p:InnoNativeBindingSelection=" + selection + }) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start) ?? throw new InvalidOperationException("MSBuild did not start."); Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); @@ -73,7 +89,9 @@ string selection catch { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } await process.WaitForExitAsync(); await output; await errors; diff --git a/tests/build/Inno.Build.Integration.Tests/NuGetBindingDependencyTests.cs b/tests/build/Inno.Build.Integration.Tests/NuGetBindingDependencyTests.cs index 836cd853f..af78c538e 100644 --- a/tests/build/Inno.Build.Integration.Tests/NuGetBindingDependencyTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NuGetBindingDependencyTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Linq; @@ -6,8 +5,9 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -21,13 +21,25 @@ public async Task RuntimeConsumptionUsesAnExactPackageWithoutARepositorySourceRe { string root = TestRepository.GetRoot(typeof(NuGetBindingDependencyTests).Assembly); string host = ToolchainEnvironment.ResolveExecutable("dotnet"); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", Path.Combine(root, project), "-nologo", "-nodeReuse:false", "-p:DesignTimeBuild=true", - "-getItem:PackageReference,ProjectReference", "-getProperty:InnoBgcsPackageVersion"], - root, CancellationToken.None, DotNetSdkEnvironment.Create(host)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + Path.Combine(root, project), + "-nologo", + "-nodeReuse:false", + "-p:DesignTimeBuild=true", + "-getItem:PackageReference,ProjectReference", + "-getProperty:InnoBgcsPackageVersion" + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument document = JsonDocument.Parse(output); JsonElement items = document.RootElement.GetProperty("Items"); - JsonElement runtime = items.GetProperty("PackageReference").EnumerateArray() + JsonElement runtime = items.GetProperty("PackageReference") + .EnumerateArray() .Single(static item => item.GetProperty("Identity").GetString() == "BGCS.Runtime"); string version = document.RootElement.GetProperty("Properties").GetProperty("InnoBgcsPackageVersion").GetString()!; Assert.Equal("[" + version + "]", runtime.GetProperty("Version").GetString()); @@ -51,36 +63,53 @@ public async Task RestoredRuntimePackageMatchesItsDeclaredVersionAndNuGetContent try { using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", Path.Combine(root, "backends", "ImGui", "native", "Inno.Native.ImGui", "Inno.Native.ImGui.csproj"), - "-t:Restore", "-p:ArtifactsPath=" + workspace, - "-getProperty:ProjectAssetsFile,InnoBgcsPackageVersion", "-nologo", "-nr:false", "-v:quiet"], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + Path.Combine(root, "backends", "ImGui", "native", "Inno.Native.ImGui", "Inno.Native.ImGui.csproj"), + "-t:Restore", + "-p:ArtifactsPath=" + workspace, + "-getProperty:ProjectAssetsFile,InnoBgcsPackageVersion", + "-nologo", + "-nr:false", + "-v:quiet" + ], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument evaluation = JsonDocument.Parse(output); JsonElement properties = evaluation.RootElement.GetProperty("Properties"); using JsonDocument assets = JsonDocument.Parse(File.ReadAllBytes(properties.GetProperty("ProjectAssetsFile").GetString()!)); - JsonProperty runtime = assets.RootElement.GetProperty("libraries").EnumerateObject() + JsonProperty runtime = assets.RootElement.GetProperty("libraries") + .EnumerateObject() .Single(static library => library.Name.StartsWith("BGCS.Runtime/", StringComparison.Ordinal)); string version = properties.GetProperty("InnoBgcsPackageVersion").GetString()!; Assert.Equal("BGCS.Runtime/" + version, runtime.Name); string packagePath = runtime.Value.GetProperty("path").GetString()!; - string archive = assets.RootElement.GetProperty("packageFolders").EnumerateObject() + string archive = assets.RootElement.GetProperty("packageFolders") + .EnumerateObject() .Select(folder => Path.Combine(folder.Name, packagePath, "bgcs.runtime." + version + ".nupkg")) .Single(File.Exists); await using FileStream package = File.OpenRead(archive); string archiveHash = Convert.ToBase64String(await SHA512.HashDataAsync(package)); Assert.Equal(File.ReadAllText(archive + ".sha512").Trim(), archiveHash); // NuGet's content identity excludes signature metadata from the signed archive. - using JsonDocument metadata = JsonDocument.Parse(File.ReadAllBytes( - Path.Combine(Path.GetDirectoryName(archive)!, ".nupkg.metadata"))); - Assert.Equal(runtime.Value.GetProperty("sha512").GetString(), - metadata.RootElement.GetProperty("contentHash").GetString()); + using JsonDocument metadata = JsonDocument.Parse( + File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(archive)!, ".nupkg.metadata")) + ); + Assert.Equal( + runtime.Value.GetProperty("sha512").GetString(), + metadata.RootElement.GetProperty("contentHash").GetString() + ); } finally { if (Directory.Exists(workspace)) + { Directory.Delete(workspace, recursive: true); + } } } - } diff --git a/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs b/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs index 761707ad2..3267f3916 100644 --- a/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs @@ -10,9 +10,9 @@ using System.Threading.Tasks; using System.Xml.Linq; using BGCS.Runtime; +using Xunit; using Inno.Build.Toolchains; using Inno.Testing.Source; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -38,11 +38,13 @@ public Task IsolatedHostRejectsARealLoadedPayloadMismatch() { string? expected = Environment.GetEnvironmentVariable(C_EXPECTED_RUNTIME); if (expected is null) + { return VerifyScope(true, true); + } string mismatch = Environment.GetEnvironmentVariable(C_MISMATCH_RUNTIME) - ?? throw new InvalidOperationException("The loaded-package probe has no owned mismatch input."); + ?? throw new InvalidOperationException("The loaded-package probe has no owned mismatch input."); string result = Environment.GetEnvironmentVariable(C_PROBE_RESULT) - ?? throw new InvalidOperationException("The loaded-package probe has no result owner."); + ?? throw new InvalidOperationException("The loaded-package probe has no result owner."); (WeakReference retired, WeakReference retiredAssembly) = LoadMismatchedContent(expected, mismatch, typeof(Utf8Codec).Assembly); GC.Collect(); GC.WaitForPendingFinalizers(); @@ -64,16 +66,40 @@ bool staleDefault string repository = TestRepository.GetRoot(typeof(NuGetLoadedIdentityTests).Assembly); string sdk = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - string version = (await ToolchainEnvironment.CaptureOutputAsync(sdk, - ["msbuild", Path.Combine(repository, "backends/ImGui/native/Inno.Native.ImGui/Inno.Native.ImGui.csproj"), - "-nologo", "-nr:false", "-getProperty:InnoBgcsPackageVersion"], - repository, cancellation.Token, DotNetSdkEnvironment.Create(sdk))).Trim(); + string version = (await ToolchainEnvironment.CaptureOutputAsync( + sdk, + [ + "msbuild", + Path.Combine(repository, "backends/ImGui/native/Inno.Native.ImGui/Inno.Native.ImGui.csproj"), + "-nologo", + "-nr:false", + "-getProperty:InnoBgcsPackageVersion" + ], + repository, + cancellation.Token, + DotNetSdkEnvironment.Create(sdk) + )).Trim(); string project = Path.Combine(root, "Consumer.csproj"); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), - new XElement("LangVersion", "14.0"), new XElement("ImplicitUsings", "disable")), - new XElement("ItemGroup", new XElement("PackageReference", new XAttribute("Include", "BGCS.Runtime"), - new XAttribute("Version", "[" + version + "]"))))).Save(project); + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("LangVersion", "14.0"), + new XElement("ImplicitUsings", "disable") + ), + new XElement( + "ItemGroup", + new XElement( + "PackageReference", + new XAttribute("Include", "BGCS.Runtime"), + new XAttribute("Version", "[" + version + "]") + ) + ) + ) + ).Save(project); string defaultAssets = Path.Combine(root, "obj", "project.assets.json"); const string stale = "unrelated stale default assets must never be consumed"; if (staleDefault) @@ -82,28 +108,43 @@ bool staleDefault File.WriteAllText(defaultAssets, stale); } string[] owner = isolated ? ["-p:ArtifactsPath=" + Path.Combine(root, "owned-output")] : []; - string evaluated = await ToolchainEnvironment.CaptureOutputAsync(sdk, + string evaluated = await ToolchainEnvironment.CaptureOutputAsync( + sdk, ["msbuild", project, "-t:Restore", "-nologo", "-nr:false", "-v:quiet", "-getProperty:ProjectAssetsFile", .. owner], - root, cancellation.Token, DotNetSdkEnvironment.Create(sdk)); + root, + cancellation.Token, + DotNetSdkEnvironment.Create(sdk) + ); string assetsPath = evaluated.Trim(); Assert.True(File.Exists(assetsPath), evaluated); if (isolated) { Assert.StartsWith(Path.Combine(root, "owned-output"), assetsPath, StringComparison.OrdinalIgnoreCase); if (staleDefault) + { Assert.Equal(stale, File.ReadAllText(defaultAssets)); + } else + { Assert.False(File.Exists(defaultAssets)); + } } else + { Assert.Equal(defaultAssets, assetsPath); + } using JsonDocument assets = JsonDocument.Parse(File.ReadAllBytes(assetsPath)); string library = "BGCS.Runtime/" + version; JsonElement package = assets.RootElement.GetProperty("libraries").GetProperty(library); - string packageRoot = assets.RootElement.GetProperty("packageFolders").EnumerateObject() - .Select(folder => Path.Combine(folder.Name, package.GetProperty("path").GetString()!)).Single(Directory.Exists); + string packageRoot = assets.RootElement.GetProperty("packageFolders") + .EnumerateObject() + .Select(folder => Path.Combine(folder.Name, package.GetProperty("path").GetString()!)) + .Single(Directory.Exists); JsonElement target = assets.RootElement.GetProperty("targets").EnumerateObject().Single().Value.GetProperty(library); - string relative = target.GetProperty("runtime").EnumerateObject().Single(item => item.Name.EndsWith(".dll", StringComparison.Ordinal)).Name; + string relative = target + .GetProperty("runtime") + .EnumerateObject() + .Single(item => item.Name.EndsWith(".dll", StringComparison.Ordinal)).Name; string runtime = Path.Combine(packageRoot, relative); Assembly loaded = typeof(Utf8Codec).Assembly; AssertLoadedContent(runtime, loaded); @@ -112,7 +153,9 @@ bool staleDefault Directory.CreateDirectory(Path.GetDirectoryName(mismatch)!); File.WriteAllBytes(mismatch, File.ReadAllBytes(runtime)); await using (FileStream altered = new(mismatch, FileMode.Append, FileAccess.Write)) + { await altered.WriteAsync(new byte[] { 0x49, 0x4E, 0x4E, 0x4F }, cancellation.Token); + } await RunLoadedMismatchProbeAsync(sdk, runtime, mismatch, root, cancellation.Token); } finally @@ -129,15 +172,31 @@ private static async Task RunLoadedMismatchProbeAsync( CancellationToken cancellationToken ) { string result = Path.Combine(root, "loaded-package-probe.txt"); - string output = await ToolchainEnvironment.CaptureOutputAsync(sdk, - ["test", typeof(NuGetLoadedIdentityTests).Assembly.Location, - "--filter", "FullyQualifiedName=" + typeof(NuGetLoadedIdentityTests).FullName + "." + nameof(IsolatedHostRejectsARealLoadedPayloadMismatch), - "--results-directory", Path.Combine(root, "probe-results"), - "--logger", "trx;LogFileName=loaded-package.trx", - "--environment", C_EXPECTED_RUNTIME + "=" + expected, - "--environment", C_MISMATCH_RUNTIME + "=" + mismatch, - "--environment", C_PROBE_RESULT + "=" + result], - root, cancellationToken, DotNetSdkEnvironment.Create(sdk)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + sdk, + [ + "test", + typeof(NuGetLoadedIdentityTests).Assembly.Location, + "--filter", + "FullyQualifiedName=" + + typeof(NuGetLoadedIdentityTests).FullName + + "." + + nameof(IsolatedHostRejectsARealLoadedPayloadMismatch), + "--results-directory", + Path.Combine(root, "probe-results"), + "--logger", + "trx;LogFileName=loaded-package.trx", + "--environment", + C_EXPECTED_RUNTIME + "=" + expected, + "--environment", + C_MISMATCH_RUNTIME + "=" + mismatch, + "--environment", + C_PROBE_RESULT + "=" + result + ], + root, + cancellationToken, + DotNetSdkEnvironment.Create(sdk) + ); Assert.True(File.Exists(result), output); Assert.Equal(C_VERIFIED_PROBE, File.ReadAllText(result)); // The physical image belongs to the probe process; normal cleanup follows its complete exit. @@ -167,6 +226,8 @@ Assembly loaded private static void AssertLoadedContent( string expected, Assembly loaded - ) => Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(expected))), - Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(loaded.Location)))); + ) => Assert.Equal( + Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(expected))), + Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(loaded.Location))) + ); } diff --git a/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs b/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs index 6110a6c82..1ff6d9d64 100644 --- a/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs @@ -5,11 +5,11 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Build.TaskHosting; -using Inno.Core.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Xunit; +using Inno.Build.TaskHosting; +using Inno.Core.IO; namespace Inno.Build.Integration.Tests; @@ -134,12 +134,18 @@ private sealed class RecordingEngine(Func restore) : IBuildEngine3 public int ColumnNumberOfTaskNode => 0; public string ProjectFileOfTaskNode => string.Empty; public bool IsRunningMultipleNodes => true; + public void Yield() => m_yielded = true; + public void Reacquire() => reacquired = true; - public void LogErrorEvent(BuildErrorEventArgs error) { } - public void LogWarningEvent(BuildWarningEventArgs warning) { } - public void LogMessageEvent(BuildMessageEventArgs message) { } - public void LogCustomEvent(CustomBuildEventArgs custom) { } + + public void LogErrorEvent(BuildErrorEventArgs error) {} + + public void LogWarningEvent(BuildWarningEventArgs warning) {} + + public void LogMessageEvent(BuildMessageEventArgs message) {} + + public void LogCustomEvent(CustomBuildEventArgs custom) {} public BuildEngineResult BuildProjectFilesInParallel( string[] projects, diff --git a/tests/build/Inno.Build.Integration.Tests/SdkRestoreTests.cs b/tests/build/Inno.Build.Integration.Tests/SdkRestoreTests.cs index 541c80bee..57fb3248c 100644 --- a/tests/build/Inno.Build.Integration.Tests/SdkRestoreTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/SdkRestoreTests.cs @@ -4,10 +4,10 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; using Inno.Testing.Source; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -56,33 +56,62 @@ bool trimmed try { using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", project, "-t:Restore", "-p:ArtifactsPath=" + workspace, - "-p:InnoNativeTarget=" + target, "-p:RuntimeIdentifier=" + runtime, - "-p:PublishAot=" + aheadOfTime, "-p:PublishTrimmed=" + trimmed, - "-getProperty:ProjectAssetsFile", "-nologo", "-nr:false", "-v:quiet"], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + project, + "-t:Restore", + "-p:ArtifactsPath=" + workspace, + "-p:InnoNativeTarget=" + target, + "-p:RuntimeIdentifier=" + runtime, + "-p:PublishAot=" + aheadOfTime, + "-p:PublishTrimmed=" + trimmed, + "-getProperty:ProjectAssetsFile", + "-nologo", + "-nr:false", + "-v:quiet" + ], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); string assetsPath = output.Trim(); - Assert.StartsWith(Path.GetFullPath(workspace) + Path.DirectorySeparatorChar, - Path.GetFullPath(assetsPath), StringComparison.Ordinal); + Assert.StartsWith( + Path.GetFullPath(workspace) + Path.DirectorySeparatorChar, + Path.GetFullPath(assetsPath), + StringComparison.Ordinal + ); using JsonDocument assets = JsonDocument.Parse(File.ReadAllBytes(assetsPath)); JsonProperty[] resolved = assets.RootElement.GetProperty("targets").EnumerateObject().ToArray(); Assert.NotEmpty(resolved); if (runtime.Length != 0) + { Assert.Contains(resolved, entry => entry.Name.EndsWith("/" + runtime, StringComparison.Ordinal)); + } if (aheadOfTime) - Assert.Contains(assets.RootElement.GetProperty("libraries").EnumerateObject(), - static entry => entry.Name.StartsWith("Microsoft.DotNet.ILCompiler/", StringComparison.Ordinal)); + { + Assert.Contains( + assets.RootElement.GetProperty("libraries").EnumerateObject(), + static entry => entry.Name.StartsWith("Microsoft.DotNet.ILCompiler/", StringComparison.Ordinal) + ); + } if (trimmed) - Assert.Contains(assets.RootElement.GetProperty("libraries").EnumerateObject(), - static entry => entry.Name.StartsWith("Microsoft.NET.ILLink.Tasks/", StringComparison.Ordinal)); + { + Assert.Contains( + assets.RootElement.GetProperty("libraries").EnumerateObject(), + static entry => entry.Name.StartsWith("Microsoft.NET.ILLink.Tasks/", StringComparison.Ordinal) + ); + } Assert.Empty(Directory.EnumerateFiles(Path.GetDirectoryName(project)!, "packages*.lock.json")); Assert.Empty(Directory.EnumerateFiles(workspace, "packages*.lock.json", SearchOption.AllDirectories)); } finally { if (Directory.Exists(workspace)) + { Directory.Delete(workspace, recursive: true); + } } } } diff --git a/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs b/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs index 72be287b9..11bedf681 100644 --- a/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Security; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -21,7 +21,11 @@ public async Task OwnedProductCleanDoesNotPrepareNativeArtifacts( bool explicitlyDisablePreparation ) { string repository = TestRepository.GetRoot(typeof(SolutionBootstrapOwnershipTests).Assembly); - string root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoProductCleanTests", Guid.NewGuid().ToString("N")); + string root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoProductCleanTests", + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(root); try { @@ -31,12 +35,25 @@ bool explicitlyDisablePreparation using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(1)); using var output = new StringWriter(); using var error = new StringWriter(); - Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync(host, - ["clean", Path.Combine(repository, project), - "--artifacts-path", artifacts, "-p:InnoTaskArtifacts=" + tasks, + Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( + host, + [ + "clean", + Path.Combine(repository, project), + "--artifacts-path", + artifacts, + "-p:InnoTaskArtifacts=" + tasks, .. (explicitlyDisablePreparation ? new[] { "-p:InnoPrepareProductNative=false" } : Array.Empty()), - "--disable-build-servers", "-m:1", "-nr:false"], - repository, cancellation.Token, DotNetSdkEnvironment.Create(host), output, error)); + "--disable-build-servers", + "-m:1", + "-nr:false" + ], + repository, + cancellation.Token, + DotNetSdkEnvironment.Create(host), + output, + error + )); Assert.True(failure is null, $"{failure}\n{output}\n{error}"); Assert.False(Directory.Exists(tasks), output.ToString()); Assert.Empty(Directory.GetFiles(artifacts, "*.dll", SearchOption.AllDirectories)); @@ -52,7 +69,11 @@ bool explicitlyDisablePreparation public async Task BootstrapClaimsAreSharedWithinOneProcessButCannotCrossExitedProcesses() { string repository = TestRepository.GetRoot(typeof(SolutionBootstrapOwnershipTests).Assembly); - string root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoBootstrapLifetimeTests", Guid.NewGuid().ToString("N")); + string root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoBootstrapLifetimeTests", + Guid.NewGuid().ToString("N") + ); Directory.CreateDirectory(root); try { @@ -85,11 +106,19 @@ async Task InvokeAsync(string owner) using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(1)); using var output = new StringWriter(); using var error = new StringWriter(); - Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync(host, + Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( + host, ["msbuild", project, "-t:Build", "-nr:false", "-p:InnoTaskBootstrapOwner=" + owner], - root, cancellation.Token, DotNetSdkEnvironment.Create(host), output, error)); + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host), + output, + error + )); if (failure is not null) + { throw new InvalidOperationException(output.ToString() + error, failure); + } } } finally @@ -108,6 +137,7 @@ public async Task SolutionSharesOneBootstrapOwnerAndRenewsItForTheNextBuild() { File.Copy(Path.Combine(root, "Directory.Solution.targets"), Path.Combine(fixture, "Directory.Solution.targets")); foreach (string name in new[] { "First", "Second" }) + { await File.WriteAllTextAsync(Path.Combine(fixture, name + ".csproj"), """ @@ -117,6 +147,7 @@ await File.WriteAllTextAsync(Path.Combine(fixture, name + ".csproj"), """ """); + } string solution = Path.Combine(fixture, "InnoEngine.sln"); await File.WriteAllTextAsync(solution, """ Microsoft Visual Studio Solution File, Format Version 12.00 @@ -144,8 +175,14 @@ await File.WriteAllTextAsync(solution, """ using var output = new StringWriter(); using var error = new StringWriter(); Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( - host, ["msbuild", solution, "-m:2", "-nodeReuse:false", "-v:quiet"], - fixture, cancellation.Token, DotNetSdkEnvironment.Create(host), output, error)); + host, + ["msbuild", solution, "-m:2", "-nodeReuse:false", "-v:quiet"], + fixture, + cancellation.Token, + DotNetSdkEnvironment.Create(host), + output, + error + )); Assert.True(failure is null, $"{failure}{Environment.NewLine}{output}{Environment.NewLine}{error}"); string first = File.ReadAllText(Path.Combine(fixture, "First.owner")).Trim(); Assert.True(Guid.TryParseExact(first, "N", out _)); diff --git a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs index ee076e193..c0e770a45 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs @@ -48,15 +48,27 @@ internal static async Task StartAsync(string root) string ready = Path.Combine(worker, "ready"); string release = Path.Combine(worker, "release"); string source = Path.Combine(root, "input", "Inno.Build.Tasks.dll"); - var project = new XDocument(new XElement("Project", - new XElement("UsingTask", new XAttribute("TaskName", "Inno.Build.TaskHosting.PublishTaskHostTask"), - new XAttribute("AssemblyFile", typeof(PublishTaskHostTask).Assembly.Location)), - new XElement("UsingTask", new XAttribute("TaskName", "HoldPublication"), - new XAttribute("TaskFactory", "RoslynCodeTaskFactory"), - new XAttribute("AssemblyFile", "$(MSBuildToolsPath)/Microsoft.Build.Tasks.Core.dll"), - new XElement("ParameterGroup", new XElement("ReleaseFile", new XAttribute("Required", "true"))), - new XElement("Task", new XElement("Code", new XAttribute("Type", "Fragment"), - new XAttribute("Language", "cs"), new XCData(""" + var project = new XDocument( + new XElement( + "Project", + new XElement( + "UsingTask", + new XAttribute("TaskName", "Inno.Build.TaskHosting.PublishTaskHostTask"), + new XAttribute("AssemblyFile", typeof(PublishTaskHostTask).Assembly.Location) + ), + new XElement( + "UsingTask", + new XAttribute("TaskName", "HoldPublication"), + new XAttribute("TaskFactory", "RoslynCodeTaskFactory"), + new XAttribute("AssemblyFile", "$(MSBuildToolsPath)/Microsoft.Build.Tasks.Core.dll"), + new XElement("ParameterGroup", new XElement("ReleaseFile", new XAttribute("Required", "true"))), + new XElement( + "Task", + new XElement( + "Code", + new XAttribute("Type", "Fragment"), + new XAttribute("Language", "cs"), + new XCData(""" var elapsed = System.Diagnostics.Stopwatch.StartNew(); while (!System.IO.File.Exists(ReleaseFile)) { @@ -64,26 +76,55 @@ internal static async Task StartAsync(string root) throw new System.TimeoutException("The publication fixture was not released."); System.Threading.Thread.Sleep(10); } - """)))), - new XElement("Target", new XAttribute("Name", "Publish"), - new XElement("ItemGroup", new XElement("RuntimeFile", new XAttribute("Include", source), - new XElement("RelativePath", "Inno.Build.Tasks.dll"), - new XElement("FileHash", Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(source)))))), - new XElement("Inno.Build.TaskHosting.PublishTaskHostTask", - new XAttribute("InputFiles", "@(RuntimeFile)"), - new XAttribute("CacheDirectory", Path.Combine(root, "hosts")), - new XAttribute("LoadDirectory", load), new XAttribute("PublisherDirectory", publisher), - new XElement("Output", new XAttribute("TaskParameter", "PublishedAssembly"), - new XAttribute("PropertyName", "PublishedRuntime"))), - new XElement("WriteLinesToFile", new XAttribute("File", ready), - new XAttribute("Lines", "$(PublishedRuntime)"), new XAttribute("Overwrite", "true")), - new XElement("HoldPublication", new XAttribute("ReleaseFile", release))))); + """) + ) + ) + ), + new XElement( + "Target", + new XAttribute("Name", "Publish"), + new XElement( + "ItemGroup", + new XElement( + "RuntimeFile", + new XAttribute("Include", source), + new XElement("RelativePath", "Inno.Build.Tasks.dll"), + new XElement("FileHash", Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(source)))) + ) + ), + new XElement( + "Inno.Build.TaskHosting.PublishTaskHostTask", + new XAttribute("InputFiles", "@(RuntimeFile)"), + new XAttribute("CacheDirectory", Path.Combine(root, "hosts")), + new XAttribute("LoadDirectory", load), + new XAttribute("PublisherDirectory", publisher), + new XElement( + "Output", + new XAttribute("TaskParameter", "PublishedAssembly"), + new XAttribute("PropertyName", "PublishedRuntime") + ) + ), + new XElement( + "WriteLinesToFile", + new XAttribute("File", ready), + new XAttribute("Lines", "$(PublishedRuntime)"), + new XAttribute("Overwrite", "true") + ), + new XElement("HoldPublication", new XAttribute("ReleaseFile", release)) + ) + ) + ); string path = Path.Combine(worker, "Publication.proj"); project.Save(path); string dotnet = ToolchainEnvironment.ResolveExecutable(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet"); var budget = new CancellationTokenSource(TimeSpan.FromMinutes(2)); - Task running = ToolchainEnvironment.RunAsync(dotnet, ["msbuild", path, "-t:Publish", "-nologo", "-m:1", "-nr:false"], - worker, budget.Token, DotNetSdkEnvironment.Create(dotnet)); + Task running = ToolchainEnvironment.RunAsync( + dotnet, + ["msbuild", path, "-t:Publish", "-nologo", "-m:1", "-nr:false"], + worker, + budget.Token, + DotNetSdkEnvironment.Create(dotnet) + ); var result = new TaskHostPublicationProcess(load, publisher, ready, release, running, budget); try { @@ -101,7 +142,10 @@ internal static async Task StartAsync(string root) catch { budget.Cancel(); - try { await running; } + try + { + await running; + } catch (Exception) { } budget.Dispose(); throw; @@ -112,9 +156,17 @@ internal static async Task StartAsync(string root) public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref m_disposed, 1) != 0) + { return; + } File.WriteAllText(m_release, "release"); - try { await m_running; } - finally { m_budget.Dispose(); } + try + { + await m_running; + } + finally + { + m_budget.Dispose(); + } } } diff --git a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs index 25408bf79..f3fd60358 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs @@ -5,11 +5,11 @@ using System.Linq; using System.Security.Cryptography; using System.Threading.Tasks; -using Inno.Build.TaskHosting; -using Inno.Build.Toolchains; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Xunit; +using Inno.Build.TaskHosting; +using Inno.Build.Toolchains; namespace Inno.Build.Integration.Tests; @@ -46,7 +46,9 @@ public async System.Threading.Tasks.Task ConcurrentReadersShareTheCompleteConten PublishTaskHostTask first = CreateTask(); PublishTaskHostTask second = CreateTask(); bool[] results = await System.Threading.Tasks.Task.WhenAll( - System.Threading.Tasks.Task.Run(first.Execute), System.Threading.Tasks.Task.Run(second.Execute)); + System.Threading.Tasks.Task.Run(first.Execute), + System.Threading.Tasks.Task.Run(second.Execute) + ); Assert.All(results, result => Assert.True(result)); Assert.Equal(first.PublishedAssembly, second.PublishedAssembly); Assert.Single(Directory.GetDirectories(Path.Combine(m_root, "hosts"))); @@ -151,7 +153,8 @@ private PublishTaskHostTask CreateTask() file.SetMetadata("FileHash", Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(source)))); return new PublishTaskHostTask { - InputFiles = [file], CacheDirectory = Path.Combine(m_root, "hosts"), + InputFiles = [file], + CacheDirectory = Path.Combine(m_root, "hosts"), LoadDirectory = Path.Combine(m_root, "loads", Guid.NewGuid().ToString("N"), "Debug"), BuildEngine = m_engine }; @@ -163,10 +166,17 @@ private async System.Threading.Tasks.Task MaintainAsync() [ new BuildCachePublisher(Path.Combine(m_root, "hosts"), BuildCacheArtifactRole.ImmutableArtifact).Describe("hosts"), new BuildCachePublisher(Path.Combine(m_root, "loads"), BuildCacheArtifactRole.ProcessWorkingDirectory).Describe("loads"), - new BuildCachePublisher(Path.Combine(m_root, "publishers"), BuildCacheArtifactRole.ProcessWorkingDirectory).Describe("publishers") + new BuildCachePublisher( + Path.Combine(m_root, "publishers"), + BuildCacheArtifactRole.ProcessWorkingDirectory + ).Describe("publishers") ]; - BuildCacheCleanupResult result = await BuildCacheCleanupPlan.Create(m_root, owners, - new BuildCachePolicy(0, 0, TimeSpan.FromSeconds(20)), retireAll: true).ExecuteAsync(); + BuildCacheCleanupResult result = await BuildCacheCleanupPlan.Create( + m_root, + owners, + new BuildCachePolicy(0, 0, TimeSpan.FromSeconds(20)), + retireAll: true + ).ExecuteAsync(); Assert.Empty(result.failures); } @@ -177,10 +187,15 @@ private sealed class RecordingBuildEngine : IBuildEngine public int LineNumberOfTaskNode => 0; public int ColumnNumberOfTaskNode => 0; public string ProjectFileOfTaskNode => string.Empty; + public void LogErrorEvent(BuildErrorEventArgs error) => errors.Add(error); - public void LogWarningEvent(BuildWarningEventArgs warning) { } - public void LogMessageEvent(BuildMessageEventArgs message) { } - public void LogCustomEvent(CustomBuildEventArgs custom) { } + + public void LogWarningEvent(BuildWarningEventArgs warning) {} + + public void LogMessageEvent(BuildMessageEventArgs message) {} + + public void LogCustomEvent(CustomBuildEventArgs custom) {} + public bool BuildProjectFile( string project, string[] targets, diff --git a/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs index 6fd60bde6..75fd2393f 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.Diagnostics; using System.IO; @@ -8,8 +7,9 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Build.Logging; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -25,9 +25,11 @@ public async Task ProjectGraphSharesCompilationButKeepsPrivateLoadsAndFreshBuild Directory.CreateDirectory(root); try { - File.WriteAllText(Path.Combine(root, "Directory.Build.props"), + File.WriteAllText( + Path.Combine(root, "Directory.Build.props"), ""); + + "\" />" + ); File.WriteAllText(Path.Combine(root, "Directory.Build.targets"), $$""" @@ -46,16 +48,23 @@ public async Task ProjectGraphSharesCompilationButKeepsPrivateLoadsAndFreshBuild "Left" or "Right" => ["Shared"], _ => [] }; - string references = string.Join(string.Empty, dependencies.Select(static name => - $"")); + string references = string.Join( + string.Empty, + dependencies.Select(static name => $"") + ); if (name == "Root") - references += ""; - File.WriteAllText(Path.Combine(directory, name + ".csproj"), + { + references += ""; + } + File.WriteAllText( + Path.Combine(directory, name + ".csproj"), "net10.0" + "disablefalse" + "BuildProjectReferences=true;BuildingInsideVisualStudio=false" - + "" + references + ""); + + "" + references + "" + ); } var first = await Build(root, configuration); string firstOwner = Validate(first.output, first.binlog); @@ -95,28 +104,59 @@ string runtimeIdentifier using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); using var output = new StringWriter(); using var errors = new StringWriter(); - Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync(dotnet, - ["msbuild", project, "-nologo", "-t:Probe", "-nr:false", "-bl:" + binlog, - "-p:InnoTaskArtifacts=" + Path.Combine(root, "tasks"), "-p:ArtifactsPath=" + Path.Combine(root, "caller"), - "-p:TargetFramework=" + framework, "-p:RuntimeIdentifier=" + runtimeIdentifier, - "-p:PublishAot=true", "-p:PublishSingleFile=true", "-p:SelfContained=true", "-p:WasmBuildNative=true"], - repository, timeout.Token, DotNetSdkEnvironment.Create(dotnet), output, errors)); + Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( + dotnet, + [ + "msbuild", + project, + "-nologo", + "-t:Probe", + "-nr:false", + "-bl:" + binlog, + "-p:InnoTaskArtifacts=" + Path.Combine(root, "tasks"), + "-p:ArtifactsPath=" + Path.Combine(root, "caller"), + "-p:TargetFramework=" + framework, + "-p:RuntimeIdentifier=" + runtimeIdentifier, + "-p:PublishAot=true", + "-p:PublishSingleFile=true", + "-p:SelfContained=true", + "-p:WasmBuildNative=true" + ], + repository, + timeout.Token, + DotNetSdkEnvironment.Create(dotnet), + output, + errors + )); Assert.True(failure is null, $"{failure}\n{output}\n{errors}"); int requests = 0; var events = new BinaryLogReplayEventSource(); events.ProjectStarted += ( _, item - ) => { + ) => + { if (Path.GetFileNameWithoutExtension(item.ProjectFile) != "Inno.Core.IO" - || item.TargetNames != "Restore;Build") + || item.TargetNames != "Restore;Build" + ) { return; + } requests++; Assert.NotNull(item.GlobalProperties); - foreach (string property in new[] { "RuntimeIdentifier", "TargetFramework", "PublishAot", "PublishSingleFile", "SelfContained", "WasmBuildNative" }) + foreach (string property in new[] { + "RuntimeIdentifier", + "TargetFramework", + "PublishAot", + "PublishSingleFile", + "SelfContained", + "WasmBuildNative" + }) { Assert.DoesNotContain(property, item.GlobalProperties!.Keys); - Assert.Equal(Path.Combine(root, "caller", ".inno-task-foundation").Replace('\\', '/'), - item.GlobalProperties!["ArtifactsPath"].Replace('\\', '/')); + } + Assert.Equal( + Path.Combine(root, "caller", ".inno-task-foundation").Replace('\\', '/'), + item.GlobalProperties!["ArtifactsPath"].Replace('\\', '/') + ); }; events.Replay(binlog); Assert.True(requests > 0, "No neutral Foundation bootstrap was inspected."); @@ -133,9 +173,11 @@ private static string Validate( string output, string binlog ) { - string[][] reports = output.Split('\n').Select(static line => line.Trim()) + string[][] reports = output.Split('\n') + .Select(static line => line.Trim()) .Where(static line => line.StartsWith("INNO-PUBLISHER-PROBE|", StringComparison.Ordinal)) - .Select(static line => line.Split('|')).ToArray(); + .Select(static line => line.Split('|')) + .ToArray(); Assert.True(reports.Length == 4, output); Assert.Equal(4, reports.Select(static report => report[1]).Distinct().Count()); Assert.Equal(4, reports.Select(static report => report[3]).Distinct().Count()); @@ -148,11 +190,14 @@ string binlog events.ProjectStarted += ( _, project - ) => { + ) => + { if (Path.GetFileNameWithoutExtension(project.ProjectFile) != "Inno.Core.IO" || project.GlobalProperties is not { } globals - || !globals.TryGetValue("ArtifactsPath", out string? artifacts)) + || !globals.TryGetValue("ArtifactsPath", out string? artifacts) + ) { return; + } if (string.Equals(Path.GetFileName(artifacts), ".inno-task-foundation", StringComparison.Ordinal)) { bootstrapFoundationRequests++; @@ -161,8 +206,10 @@ string binlog return; } if (!string.IsNullOrEmpty(project.TargetNames) - || !string.Equals(Path.GetFileName(artifacts), "managed", StringComparison.Ordinal)) + || !string.Equals(Path.GetFileName(artifacts), "managed", StringComparison.Ordinal) + ) { return; + } sharedFoundationRequests++; Assert.True(globals.TryGetValue("InnoNativeTarget", out string? target)); Assert.Equal("fixture-target", target); @@ -172,21 +219,28 @@ string binlog events.TaskStarted += ( _, task - ) => { + ) => + { if (task.TaskName == "Csc" && Path.GetFileNameWithoutExtension(task.ProjectFile) == "Inno.Build.TaskHosting") + { compilations++; + } }; events.Replay(binlog); Assert.True(sharedFoundationRequests > 0, "The real shared Foundation graph was not exercised."); Assert.True(bootstrapFoundationRequests > 0, "The neutral bootstrap output owner was not exercised."); Assert.True(compilations == 1, $"Expected one bootstrap Csc task, observed {compilations}.\n{output}"); - string[] runtimeReports = output.Split('\n').Select(static line => line.Trim()) - .Where(static line => line.StartsWith("INNO-TASK-RUNTIME ", StringComparison.Ordinal)).ToArray(); + string[] runtimeReports = output.Split('\n') + .Select(static line => line.Trim()) + .Where(static line => line.StartsWith("INNO-TASK-RUNTIME ", StringComparison.Ordinal)) + .ToArray(); Assert.Equal(4, runtimeReports.Length); Assert.Single(runtimeReports.Select(static line => line[(line.LastIndexOf(' ') + 1)..]).Distinct()); Assert.InRange(runtimeReports.Count(static line => line.StartsWith("INNO-TASK-RUNTIME prepared ", StringComparison.Ordinal)), 0, 1); foreach (string[] report in reports) + { Assert.True(File.Exists(report[3]), "The private publisher was not retained for its loading process: " + report[3]); + } return owner; } @@ -194,8 +248,10 @@ string binlog string root, string configuration ) { - string dotnet = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string dotnet = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(dotnet) { WorkingDirectory = root, @@ -207,13 +263,21 @@ string configuration string binlog = Path.Combine(root, Guid.NewGuid().ToString("N") + ".binlog"); foreach (string argument in new[] { - "build", "Root/Root.csproj", "--configuration", configuration, "--disable-build-servers", "--nologo", "-m:2", "-nodeReuse:false", + "build", + "Root/Root.csproj", + "--configuration", + configuration, + "--disable-build-servers", + "--nologo", + "-m:2", + "-nodeReuse:false", "-p:InnoNativeTarget=fixture-target", "-p:InnoTaskArtifacts=" + Path.Combine(root, "tasks"), "-p:ArtifactsPath=" + Path.Combine(root, "managed"), "-bl:" + binlog - }) + }) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start) ?? throw new InvalidOperationException("MSBuild did not start."); Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); @@ -225,7 +289,9 @@ string configuration catch { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } await process.WaitForExitAsync(); await output; await errors; diff --git a/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs index 0ded074d5..5c89598e4 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs @@ -4,9 +4,9 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Testing.Source; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -167,15 +167,27 @@ public void Shutdown() { } string dotnet = ToolchainEnvironment.ResolveExecutable("dotnet"); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(10)); var environment = DotNetSdkEnvironment.Create(dotnet); - await ToolchainEnvironment.RunAsync(dotnet, + await ToolchainEnvironment.RunAsync( + dotnet, ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-p:UseSharedCompilation=false"], - repository, timeout.Token, environment); - string sdk = (await ToolchainEnvironment.CaptureOutputAsync(dotnet, + repository, + timeout.Token, + environment + ); + string sdk = (await ToolchainEnvironment.CaptureOutputAsync( + dotnet, ["msbuild", project, "-nologo", "-getProperty:MSBuildBinPath"], - repository, timeout.Token, environment)).Trim(); - await ToolchainEnvironment.RunAsync(dotnet, + repository, + timeout.Token, + environment + )).Trim(); + await ToolchainEnvironment.RunAsync( + dotnet, [Path.Combine(root, "bin/Debug/net10.0/Runner.dll"), fixture, sdk, report, repository], - repository, timeout.Token, environment); + repository, + timeout.Token, + environment + ); using JsonDocument results = JsonDocument.Parse(await File.ReadAllTextAsync(report)); Assert.Equal(2, results.RootElement.GetArrayLength()); string? previous = null; diff --git a/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs index d3f00c794..9a112c1fc 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs @@ -3,12 +3,10 @@ using System.IO; using System.Threading.Tasks; using System.Xml.Linq; - +using Xunit; using Inno.Build.TaskHosting; using Inno.Build.Toolchains; -using Xunit; - namespace Inno.Build.Integration.Tests; public sealed class TaskRestoreEvaluationTests @@ -27,47 +25,102 @@ public async Task RestoreDoesNotReusePackageContentItemsDuringCompilation(bool o File.WriteAllText(oldPayload, "old-package-content"); File.WriteAllText(newPayload, "new-package-content"); string imports = Path.Combine(root, "restored.props"); - new XDocument(new XElement("Project", new XElement("PropertyGroup", - new XElement("PayloadPath", oldPayload)))).Save(imports); - string updatedImports = new XElement("Project", new XElement("PropertyGroup", - new XElement("PayloadPath", newPayload))).ToString(SaveOptions.DisableFormatting); + new XDocument( + new XElement("Project", new XElement("PropertyGroup", new XElement("PayloadPath", oldPayload))) + ).Save(imports); + string updatedImports = new XElement( + "Project", + new XElement("PropertyGroup", new XElement("PayloadPath", newPayload)) + ).ToString(SaveOptions.DisableFormatting); string project = Path.Combine(root, "Runtime.csproj"); - new XDocument(new XElement("Project", - new XElement("Import", new XAttribute("Project", imports), - new XAttribute("Condition", "'$(ExcludeRestorePackageImports)' != 'true'")), - new XElement("Target", new XAttribute("Name", "Restore"), - new XElement("WriteLinesToFile", new XAttribute("File", imports), - new XAttribute("Lines", updatedImports), new XAttribute("Overwrite", "true"))), - new XElement("Target", new XAttribute("Name", "PublishRuntime"), - new XAttribute("Returns", "@(HashedRuntime)"), - new XElement("MakeDir", new XAttribute("Directories", "$(ArtifactsPath)/bin")), - new XElement("Copy", new XAttribute("SourceFiles", "$(PayloadPath)"), - new XAttribute("DestinationFiles", "$(ArtifactsPath)/bin/Inno.Build.Tasks.dll")), - new XElement("ItemGroup", new XElement("RuntimeFile", - new XAttribute("Include", "$(ArtifactsPath)/bin/Inno.Build.Tasks.dll"), - new XElement("RelativePath", "Inno.Build.Tasks.dll"))), - new XElement("GetFileHash", new XAttribute("Files", "@(RuntimeFile)"), - new XElement("Output", new XAttribute("TaskParameter", "Items"), - new XAttribute("ItemName", "HashedRuntime")))))).Save(project); + new XDocument( + new XElement( + "Project", + new XElement( + "Import", + new XAttribute("Project", imports), + new XAttribute("Condition", "'$(ExcludeRestorePackageImports)' != 'true'") + ), + new XElement( + "Target", + new XAttribute("Name", "Restore"), + new XElement( + "WriteLinesToFile", + new XAttribute("File", imports), + new XAttribute("Lines", updatedImports), + new XAttribute("Overwrite", "true") + ) + ), + new XElement( + "Target", + new XAttribute("Name", "PublishRuntime"), + new XAttribute("Returns", "@(HashedRuntime)"), + new XElement("MakeDir", new XAttribute("Directories", "$(ArtifactsPath)/bin")), + new XElement( + "Copy", + new XAttribute("SourceFiles", "$(PayloadPath)"), + new XAttribute("DestinationFiles", "$(ArtifactsPath)/bin/Inno.Build.Tasks.dll") + ), + new XElement( + "ItemGroup", + new XElement( + "RuntimeFile", + new XAttribute("Include", "$(ArtifactsPath)/bin/Inno.Build.Tasks.dll"), + new XElement("RelativePath", "Inno.Build.Tasks.dll") + ) + ), + new XElement( + "GetFileHash", + new XAttribute("Files", "@(RuntimeFile)"), + new XElement( + "Output", + new XAttribute("TaskParameter", "Items"), + new XAttribute("ItemName", "HashedRuntime") + ) + ) + ) + ) + ).Save(project); string artifacts = Path.Combine(root, "workspaces", "shared"); XElement operation = ownedRestore - ? new XElement("Inno.Build.TaskHosting.RestoreOwnedProjectTask", - new XAttribute("Projects", project), new XAttribute("LockPath", artifacts + ".lock"), - new XAttribute("Properties", "ArtifactsPath=" + artifacts)) - : new XElement("Inno.Build.TaskHosting.BuildTaskRuntimeTask", - new XAttribute("ProjectFile", project), new XAttribute("ArtifactsDirectory", artifacts), - new XAttribute("LoadDirectory", Path.Combine(root, "loads", "reader", "Debug")), - new XAttribute("Targets", "Restore;PublishRuntime")); + ? new XElement( + "Inno.Build.TaskHosting.RestoreOwnedProjectTask", + new XAttribute("Projects", project), + new XAttribute("LockPath", artifacts + ".lock"), + new XAttribute("Properties", "ArtifactsPath=" + artifacts) + ) + : new XElement( + "Inno.Build.TaskHosting.BuildTaskRuntimeTask", + new XAttribute("ProjectFile", project), + new XAttribute("ArtifactsDirectory", artifacts), + new XAttribute("LoadDirectory", Path.Combine(root, "loads", "reader", "Debug")), + new XAttribute("Targets", "Restore;PublishRuntime") + ); XElement run = new("Target", new XAttribute("Name", "Run"), operation); if (ownedRestore) - run.Add(new XElement("MSBuild", new XAttribute("Projects", project), - new XAttribute("Targets", "PublishRuntime"), - new XAttribute("Properties", "ArtifactsPath=" + artifacts))); + { + run.Add( + new XElement( + "MSBuild", + new XAttribute("Projects", project), + new XAttribute("Targets", "PublishRuntime"), + new XAttribute("Properties", "ArtifactsPath=" + artifacts) + ) + ); + } string parent = Path.Combine(root, "Parent.proj"); - new XDocument(new XElement("Project", - new XElement("UsingTask", new XAttribute("TaskName", operation.Name), - new XAttribute("AssemblyFile", typeof(BuildTaskRuntimeTask).Assembly.Location)), run)).Save(parent); + new XDocument( + new XElement( + "Project", + new XElement( + "UsingTask", + new XAttribute("TaskName", operation.Name), + new XAttribute("AssemblyFile", typeof(BuildTaskRuntimeTask).Assembly.Location) + ), + run + ) + ).Save(parent); var start = new ProcessStartInfo(ToolchainEnvironment.ResolveExecutable("dotnet")) { @@ -77,7 +130,9 @@ public async Task RestoreDoesNotReusePackageContentItemsDuringCompilation(bool o WorkingDirectory = root }; foreach (string argument in new[] { "msbuild", parent, "-t:Run", "-m:1", "-nr:false", "-v:minimal" }) + { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); diff --git a/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs index 8cf2f75fd..24b7f0da5 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs @@ -1,19 +1,20 @@ -using System.Security.Cryptography; using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Security.Cryptography; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using System.Text.Json; +using Microsoft.Build.Framework; +using Xunit; using Inno.Build.TaskHosting; using Inno.Build.Toolchains; using Inno.Core.IO; -using Microsoft.Build.Framework; + using TaskItem = Microsoft.Build.Utilities.TaskItem; -using Xunit; namespace Inno.Build.Integration.Tests; @@ -48,8 +49,10 @@ public void MissingSelectedTargetRequiresRestoreBeforePublication() """); File.WriteAllText(assets, """{"targets":{},"libraries":{},"packageFolders":{}}"""); - var engine = new RecordingEngine(() => true, () => File.WriteAllText(assets, - """{"targets":{"net10.0":{}},"libraries":{},"packageFolders":{}}""")); + var engine = new RecordingEngine(() => true, () => File.WriteAllText( + assets, + """{"targets":{"net10.0":{}},"libraries":{},"packageFolders":{}}""" + )); BuildTaskRuntimeTask task = CreateTask(engine); task.Targets = ["PublishInnoBuildTaskHost"]; Assert.True(task.Execute(), string.Join("\n", engine.errors.Select(static error => error.Message))); @@ -73,7 +76,9 @@ public async Task CompletedPreparationProtectsWorkspaceDuringMaintenanceAndCache var engine = new RecordingEngine(static () => true, () => { if (restored) + { return; + } Directory.CreateDirectory(workspace); File.WriteAllText(assets, """{"targets":{"net10.0":{}},"libraries":{},"packageFolders":{}}"""); restored = true; @@ -103,7 +108,8 @@ public async Task SharedBuildsYieldWhileWaitingAndSerializeWrites() { using ManualResetEventSlim entered = new(); using ManualResetEventSlim release = new(); - RecordingEngine firstEngine = new(() => { + RecordingEngine firstEngine = new(() => + { entered.Set(); Assert.True(release.Wait(TimeSpan.FromSeconds(10))); return true; @@ -111,11 +117,19 @@ public async Task SharedBuildsYieldWhileWaitingAndSerializeWrites() RecordingEngine secondEngine = new(() => true); BuildTaskRuntimeTask first = CreateTask(firstEngine); BuildTaskRuntimeTask second = CreateTask(secondEngine); - Task firstRun = Task.Factory.StartNew(first.Execute, - CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + Task firstRun = Task.Factory.StartNew( + first.Execute, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default + ); Assert.True(entered.Wait(TimeSpan.FromSeconds(10))); - Task secondRun = Task.Factory.StartNew(second.Execute, - CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + Task secondRun = Task.Factory.StartNew( + second.Execute, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default + ); try { Assert.True(SpinWait.SpinUntil(() => secondEngine.yielded, TimeSpan.FromSeconds(10))); @@ -129,8 +143,10 @@ public async Task SharedBuildsYieldWhileWaitingAndSerializeWrites() Assert.True(await secondRun, string.Join("\n", secondEngine.errors.Select(static error => error.Message))); Assert.True(firstEngine.reacquired && secondEngine.reacquired); Assert.Single(first.TargetOutputs); - Assert.Equal(Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(Path.Combine(m_root, "Inno.Build.Tasks.dll")))), - first.TargetOutputs[0].GetMetadata("FileHash")); + Assert.Equal( + Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(Path.Combine(m_root, "Inno.Build.Tasks.dll")))), + first.TargetOutputs[0].GetMetadata("FileHash") + ); Assert.Equal("Debug", firstEngine.properties!["Configuration"]); Assert.Equal(Path.Combine(m_root, "bootstrap"), firstEngine.properties["ArtifactsPath"]); Assert.Contains("RuntimeIdentifier", firstEngine.removed!); @@ -142,14 +158,21 @@ public async Task CancellationReleasesWaitAndAllowsTheNextBuild() RecordingEngine engine = new(() => true); BuildTaskRuntimeTask canceled = CreateTask(engine); using (FileLease lease = await FileLease.AcquireAsync( - Path.Combine(m_root, "bootstrap") + ".lock", TimeSpan.FromSeconds(10))) - { - Task execution = Task.Factory.StartNew(canceled.Execute, - CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + Path.Combine(m_root, "bootstrap") + ".lock", + TimeSpan.FromSeconds(10) + )) { + Task execution = Task.Factory.StartNew( + canceled.Execute, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default + ); try { - Assert.True(SpinWait.SpinUntil(() => engine.yielded || execution.IsCompleted, TimeSpan.FromSeconds(10)), - string.Join("\n", engine.errors.Select(static error => error.Message))); + Assert.True( + SpinWait.SpinUntil(() => engine.yielded || execution.IsCompleted, TimeSpan.FromSeconds(10)), + string.Join("\n", engine.errors.Select(static error => error.Message)) + ); Assert.True(engine.yielded, string.Join("\n", engine.errors.Select(static error => error.Message))); canceled.Cancel(); Assert.False(await execution); @@ -225,8 +248,13 @@ public void BootstrapOwnershipIsForwardedWithoutHidingDerivedCompilerInputs( int expectedBuilds ) { if (affectsCompilation) - File.WriteAllText(m_project, "$(InnoTaskBootstrapOwner)" - + ""); + { + File.WriteAllText( + m_project, + "$(InnoTaskBootstrapOwner)" + + "" + ); + } var engine = new RecordingEngine(static () => true); foreach (string owner in new[] { new string('a', 32), new string('b', 32) }) { @@ -252,8 +280,10 @@ public void CompilerInputChangesCannotReuseThePreviousRuntime(string itemType) { string input = Path.Combine(m_root, "compiler-input.txt"); File.WriteAllText(input, "value=one"); - File.WriteAllText(m_project, - $"<{itemType} Include=\"compiler-input.txt\" />"); + File.WriteAllText( + m_project, + $"<{itemType} Include=\"compiler-input.txt\" />" + ); var engine = new RecordingEngine(static () => true); Assert.True(CreateTask(engine).Execute(), string.Join("\n", engine.errors)); Assert.True(CreateTask(engine).Execute(), string.Join("\n", engine.errors)); @@ -282,27 +312,39 @@ public void ResolvedPackageBytesCannotReuseThePreviousRuntime(string assetGroup) File.WriteAllText(unrelated, "unselected-one"); var package = new Dictionary { ["type"] = "package" }; if (assetGroup != "analyzers") + { package[assetGroup] = new Dictionary { [relative] = new { } }; + } string assets = Path.Combine(m_root, "project.assets.json"); - File.WriteAllText(assets, JsonSerializer.Serialize(new - { - targets = new Dictionary + File.WriteAllText( + assets, + JsonSerializer.Serialize(new { - ["net10.0"] = new Dictionary + targets = new Dictionary { - ["Fixture/1.0.0"] = package - } - }, - libraries = new Dictionary - { - ["Fixture/1.0.0"] = new { type = "package", path = "fixture/1.0.0", files = new[] { relative, "lib/net8.0/Fixture.dll" } } - }, - packageFolders = new Dictionary { [packageRoot] = new { } } - })); - File.WriteAllText(m_project, + ["net10.0"] = new Dictionary + { + ["Fixture/1.0.0"] = package + } + }, + libraries = new Dictionary + { + ["Fixture/1.0.0"] = new + { + type = "package", + path = "fixture/1.0.0", + files = new[] { relative, "lib/net8.0/Fixture.dll" } + } + }, + packageFolders = new Dictionary { [packageRoot] = new { } } + }) + ); + File.WriteAllText( + m_project, "net10.0" + "" + assets + "" - + ""); + + "" + ); var engine = new RecordingEngine(static () => true); Assert.True(CreateTask(engine).Execute(), string.Join("\n", engine.errors)); File.WriteAllText(unrelated, "unselected-two"); @@ -336,10 +378,13 @@ public void DeclaredIndependentRestoresFinishBeforeCompilationAndAreNotRepeatedO { string dependency = Path.Combine(m_root, "Dependency.csproj"); File.WriteAllText(dependency, ""); - File.WriteAllText(m_project, "" + File.WriteAllText( + m_project, + "" + "" + "OwnedRestore=true" - + ""); + + "" + ); var engine = new RecordingEngine(static () => true); Assert.True(CreateTask(engine).Execute(), string.Join("\n", engine.errors)); Assert.Equal(new[] { m_project + ":Restore", dependency + ":Restore", m_project + ":PublishInnoBuildTaskHost" }, engine.requests); @@ -354,13 +399,13 @@ private BuildTaskRuntimeTask CreateTask(RecordingEngine engine) engine.outputPath = Path.Combine(m_root, "Inno.Build.Tasks.dll"); return new() { - BuildEngine = engine, - ProjectFile = m_project, - ArtifactsDirectory = Path.Combine(m_root, "bootstrap"), - LoadDirectory = Path.Combine(m_root, "loads", Guid.NewGuid().ToString("N"), "Debug"), - Targets = ["Restore", "PublishInnoBuildTaskHost"], - Properties = ["Configuration=Debug", "BuildProjectReferences=true"], - RemoveProperties = ["RuntimeIdentifier", "PublishAot"] + BuildEngine = engine, + ProjectFile = m_project, + ArtifactsDirectory = Path.Combine(m_root, "bootstrap"), + LoadDirectory = Path.Combine(m_root, "loads", Guid.NewGuid().ToString("N"), "Debug"), + Targets = ["Restore", "PublishInnoBuildTaskHost"], + Properties = ["Configuration=Debug", "BuildProjectReferences=true"], + RemoveProperties = ["RuntimeIdentifier", "PublishAot"] }; } @@ -380,6 +425,7 @@ internal RecordingEngine( m_build = build; m_restore = restore; } + internal int builds => m_builds; internal bool yielded => m_yielded; internal bool reacquired { get; private set; } @@ -392,12 +438,19 @@ internal RecordingEngine( public int ColumnNumberOfTaskNode => 0; public string ProjectFileOfTaskNode => string.Empty; public bool IsRunningMultipleNodes => true; + public void Yield() => m_yielded = true; + public void Reacquire() => reacquired = true; + public void LogErrorEvent(BuildErrorEventArgs error) => errors.Add(error); - public void LogWarningEvent(BuildWarningEventArgs warning) { } - public void LogMessageEvent(BuildMessageEventArgs message) { } - public void LogCustomEvent(CustomBuildEventArgs custom) { } + + public void LogWarningEvent(BuildWarningEventArgs warning) {} + + public void LogMessageEvent(BuildMessageEventArgs message) {} + + public void LogCustomEvent(CustomBuildEventArgs custom) {} + public BuildEngineResult BuildProjectFilesInParallel( string[] projects, string[] targets, @@ -409,9 +462,13 @@ bool returnTargetOutputs Assert.True(reacquired); requests.Add(projects[0] + ":" + string.Join(";", targets)); if (returnTargetOutputs) + { Interlocked.Increment(ref m_builds); + } else if (targets.Contains("Restore", StringComparer.Ordinal)) + { m_restore?.Invoke(); + } properties = globalProperties[0]; removed = removeGlobalProperties[0]; TaskItem output = new(outputPath); @@ -424,12 +481,14 @@ public object GetRegisteredTaskObject( object key, RegisteredTaskObjectLifetime lifetime ) => m_registry.TryGetValue(key, out object? value) ? value : null!; + public void RegisterTaskObject( object key, object value, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection ) => m_registry[key] = value; + public object UnregisterTaskObject( object key, RegisteredTaskObjectLifetime lifetime diff --git a/tests/build/Inno.Build.Integration.Tests/ToolchainEnvironmentTests.cs b/tests/build/Inno.Build.Integration.Tests/ToolchainEnvironmentTests.cs index b6ff913eb..978c7750c 100644 --- a/tests/build/Inno.Build.Integration.Tests/ToolchainEnvironmentTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/ToolchainEnvironmentTests.cs @@ -1,8 +1,8 @@ -using Inno.Testing.Source; using System; using System.IO; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; namespace Inno.Build.Integration.Tests; @@ -12,12 +12,12 @@ public sealed class ToolchainEnvironmentTests public void NativeBuildRootBelongsToTheToolchainProject() { string engine = TestRepository.GetRoot(typeof(ToolchainEnvironmentTests).Assembly); - string expected = Path.Combine(engine, - "build", "toolchains", "Inno.Build.Toolchains", "obj", "native"); + string expected = Path.Combine(engine, "build", "toolchains", "Inno.Build.Toolchains", "obj", "native"); var component = new NativeComponentDescriptor( "fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"); + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ); var context = new NativeBuildContext(engine, "debug"); Assert.Equal(expected, context.GetNativeBuildRoot(component)); diff --git a/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs b/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs index 5b16cbe76..b525c2ee8 100644 --- a/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs +++ b/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs @@ -28,9 +28,10 @@ public ProductNativeCostTests(ITestOutputHelper output) { m_output = output; m_host = new WindowsBuildHostProvider().TryCapture() - ?? throw new PlatformNotSupportedException("Native cost acceptance requires its declared Windows host."); - m_distribution = StandardBuildDistribution.Create(new BuildCompositionContext( - "explicit-sdk", Path.GetTempPath(), m_host, new BuildTargetId("windows-x64"))).build; + ?? throw new PlatformNotSupportedException("Native cost acceptance requires its declared Windows host."); + m_distribution = StandardBuildDistribution.Create( + new BuildCompositionContext("explicit-sdk", Path.GetTempPath(), m_host, new BuildTargetId("windows-x64")) + ).build; } [Fact] @@ -38,12 +39,17 @@ public async Task RealPresentationBuildUsesDeclaredCMakeAndFrozenWindowSource() { string root = TestRepository.GetRoot(typeof(ProductNativeCostTests).Assembly); ProductNativeBuildStep[] steps = m_distribution.ResolveNativeProduct("windows-x64", "editor").plan.steps - .Where(static step => step.id is "cimgui" or "cimguizmo").ToArray(); + .Where(static step => step.id is "cimgui" or "cimguizmo") + .ToArray(); var plan = new ProductNativeBuildPlan("presentation-acceptance", steps); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(15)); var context = new NativeBuildContext(root, "debug").WithBindingGenerator(m_distribution.ResolveBindingGenerator("windows-x64")); - NativeToolchainSelection sdk = await new WindowsX64NativeToolchainProvider("dotnet").ResolveAsync(context, - m_host, "windows-x64", cancellation.Token); + NativeToolchainSelection sdk = await new WindowsX64NativeToolchainProvider("dotnet").ResolveAsync( + context, + m_host, + "windows-x64", + cancellation.Token + ); context = context.WithToolchain(sdk); using ProductNativeBuildResult result = await new ComponentNativeProductExecutor().BuildAsync(context, plan, cancellation.Token); Assert.Equal(2, result.Count); @@ -64,18 +70,24 @@ public async Task RealHotProductBatchReadsLessThanSequentialPublicProducers(int async Task Context() { var context = new NativeBuildContext(root, "debug").WithBindingGenerator(m_distribution.ResolveBindingGenerator("windows-x64")); - NativeToolchainSelection sdk = await new WindowsX64NativeToolchainProvider("dotnet").ResolveAsync(context, - m_host, "windows-x64", cancellation.Token); + NativeToolchainSelection sdk = await new WindowsX64NativeToolchainProvider("dotnet").ResolveAsync( + context, + m_host, + "windows-x64", + cancellation.Token + ); return context.WithToolchain(sdk); } NativeBuildContext serial = await Context(); Stopwatch elapsed = Stopwatch.StartNew(); - using (NativeBindingGenerationResult bindings = await NativeBindingPreparation.PrepareAsync(serial, - plan.steps.Select(static step => step.component).ToArray(), cancellation.Token, + using (NativeBindingGenerationResult bindings = await NativeBindingPreparation.PrepareAsync( + serial, + plan.steps.Select(static step => step.component).ToArray(), + cancellation.Token, plan.steps.Where(static step => step.component.bindingDefinition is not null) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal))) - { + .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal) + )) { serial = serial.WithBindings(bindings); var products = new Dictionary(StringComparer.Ordinal); try @@ -83,14 +95,17 @@ async Task Context() foreach (ProductNativeBuildStep step in plan.steps) { NativeBuildContext selected = (step.configuration is string configuration - ? serial.WithConfiguration(configuration) : serial).WithComponentOptions(step.component, step.options); + ? serial.WithConfiguration(configuration) + : serial).WithComponentOptions(step.component, step.options); products.Add(step.id, await step.build!(selected, products, cancellation.Token)); } } finally { foreach (NativeBuildProduct product in products.Values.Reverse()) + { product.Dispose(); + } } } double serialSeconds = elapsed.Elapsed.TotalSeconds; diff --git a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/EditorShaderProfileTests.cs b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/EditorShaderProfileTests.cs index 2fe833db1..82ba762b9 100644 --- a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/EditorShaderProfileTests.cs +++ b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/EditorShaderProfileTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Linq; @@ -6,9 +5,10 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Build.ProductProfiles.Integration.Tests; @@ -21,40 +21,81 @@ public async Task SdkAddedReferencesRetainTheProductTargetAndShaderProfile() string platform = OperatingSystem.IsWindows() ? "WindowsX64" : "MacOSArm64"; string target = OperatingSystem.IsWindows() ? "windows-x64" : "macos-arm64"; string profile = Path.Combine(root, "platforms", platform, "build", "Inno.Build." + platform, "EditorProduct.props"); - string backend = Path.Combine(root, "backends", "Sdl3", "runtime", - "Inno.Adapter.Platform.Sdl3", "Inno.Adapter.Platform.Sdl3.csproj"); + string backend = Path.Combine( + root, + "backends", + "Sdl3", + "runtime", + "Inno.Adapter.Platform.Sdl3", + "Inno.Adapter.Platform.Sdl3.csproj" + ); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - using ProcessOwnedDirectory outputs = await ProcessOwnedDirectory.CreateAsync(Path.Combine(Path.GetTempPath(), "InnoShaderReferenceTests")); - string configuration = typeof(EditorShaderProfileTests).Assembly.GetCustomAttribute()!.Configuration; - string[] buildProperties = ["-p:InnoProductBuildProperties=" + profile, "-p:InnoNativeTarget=" + target, - "-p:InnoToolTarget=" + target, "-p:Configuration=" + configuration, "-p:ArtifactsPath=" + outputs.directory]; + using ProcessOwnedDirectory outputs = await ProcessOwnedDirectory.CreateAsync( + Path.Combine(Path.GetTempPath(), "InnoShaderReferenceTests") + ); + string configuration = typeof(EditorShaderProfileTests) + .Assembly + .GetCustomAttribute()! + .Configuration; + string[] buildProperties = + [ + "-p:InnoProductBuildProperties=" + profile, + "-p:InnoNativeTarget=" + target, + "-p:InnoToolTarget=" + target, + "-p:Configuration=" + configuration, + "-p:ArtifactsPath=" + outputs.directory + ]; using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - await ToolchainEnvironment.RunAsync(host, ["restore", backend, "--disable-build-servers", "-m:1", "-nr:false", ..buildProperties], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", backend, "-nologo", "-nodeReuse:false", "-t:IncludeTransitiveProjectReferences", - "-getItem:ProjectReference", ..buildProperties], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + await ToolchainEnvironment.RunAsync( + host, + ["restore", backend, "--disable-build-servers", "-m:1", "-nr:false", ..buildProperties], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + backend, + "-nologo", + "-nodeReuse:false", + "-t:IncludeTransitiveProjectReferences", + "-getItem:ProjectReference", + ..buildProperties + ], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument document = JsonDocument.Parse(output); JsonElement references = document.RootElement.GetProperty("Items").GetProperty("ProjectReference"); Assert.Contains(references.EnumerateArray(), reference => reference.GetProperty("Filename").GetString() == "Inno.Native.Sdl3"); Assert.DoesNotContain(references.EnumerateArray(), reference => reference.GetProperty("Filename").GetString() == "BGCS.Runtime"); - Assert.All(references.EnumerateArray().Where(reference => - !reference.TryGetProperty("OutputItemType", out JsonElement kind) || kind.GetString() != "Analyzer"), reference => + Assert.All( + references.EnumerateArray().Where(reference => ( + !reference.TryGetProperty("OutputItemType", out JsonElement kind) || kind.GetString() != "Analyzer" + )), + reference => { string properties = reference.GetProperty("AdditionalProperties").GetString()!; Assert.Contains("InnoNativeTarget=" + target, properties); Assert.Contains("InnoProductBuildProperties=" + profile, properties); - }); - Assert.All(references.EnumerateArray().Where(reference => - reference.TryGetProperty("OutputItemType", out JsonElement kind) && kind.GetString() == "Analyzer"), reference => + } + ); + Assert.All( + references.EnumerateArray().Where(reference => ( + reference.TryGetProperty("OutputItemType", out JsonElement kind) && kind.GetString() == "Analyzer" + )), + reference => { Assert.Equal("all", reference.GetProperty("PrivateAssets").GetString()); string removed = reference.GetProperty("GlobalPropertiesToRemove").GetString()!; Assert.Contains("InnoNativeTarget", removed); Assert.Contains("InnoProductBuildProperties", removed); Assert.Contains("RuntimeIdentifier", removed); - }); + } + ); } [Theory] @@ -68,16 +109,38 @@ int apiCount ) { string root = TestRepository.GetRoot(typeof(EditorShaderProfileTests).Assembly); string profile = Path.Combine(root, "platforms", platform, "build", "Inno.Build." + platform, "ProductBuild.props"); - string backend = Path.Combine(root, "backends", "Bgfx", "runtime", - "Inno.Adapter.Rendering.Bgfx", "Inno.Adapter.Rendering.Bgfx.csproj"); + string backend = Path.Combine( + root, + "backends", + "Bgfx", + "runtime", + "Inno.Adapter.Rendering.Bgfx", + "Inno.Adapter.Rendering.Bgfx.csproj" + ); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", backend, "-nologo", "-nodeReuse:false", "-getProperty:InnoBgfxShaderTarget", - "-getItem:_CompositionShaderApi", "-p:InnoProductBuildProperties=" + profile, - "-p:InnoNativeTarget=fixture-new-cpu"], root, CancellationToken.None, DotNetSdkEnvironment.Create(host)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + backend, + "-nologo", + "-nodeReuse:false", + "-getProperty:InnoBgfxShaderTarget", + "-getItem:_CompositionShaderApi", + "-p:InnoProductBuildProperties=" + profile, + "-p:InnoNativeTarget=fixture-new-cpu" + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument document = JsonDocument.Parse(output); - Assert.Equal(shaderPlatform, document.RootElement.GetProperty("Properties") - .GetProperty("InnoBgfxShaderTarget").GetString()); + Assert.Equal( + shaderPlatform, + document.RootElement.GetProperty("Properties") + .GetProperty("InnoBgfxShaderTarget") + .GetString() + ); Assert.Equal(apiCount, document.RootElement.GetProperty("Items").GetProperty("_CompositionShaderApi").GetArrayLength()); } @@ -92,37 +155,84 @@ int apiCount ) { string root = TestRepository.GetRoot(typeof(EditorShaderProfileTests).Assembly); string profile = Path.Combine(root, "platforms", platform, "build", "Inno.Build." + platform, "EditorProduct.props"); - string backend = Path.Combine(root, "backends", "ImGui", "runtime", - "Inno.Adapter.Presentation.ImGui.Bgfx", "Inno.Adapter.Presentation.ImGui.Bgfx.csproj"); + string backend = Path.Combine( + root, + "backends", + "ImGui", + "runtime", + "Inno.Adapter.Presentation.ImGui.Bgfx", + "Inno.Adapter.Presentation.ImGui.Bgfx.csproj" + ); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", backend, "-nologo", "-nodeReuse:false", "-getProperty:InnoImGuiShaderTarget", - "-getItem:_ImGuiShaderApi,ProjectReference", "-p:InnoProductBuildProperties=" + profile, - "-p:InnoNativeTarget=" + nativeTarget], root, CancellationToken.None, DotNetSdkEnvironment.Create(host)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + backend, + "-nologo", + "-nodeReuse:false", + "-getProperty:InnoImGuiShaderTarget", + "-getItem:_ImGuiShaderApi,ProjectReference", + "-p:InnoProductBuildProperties=" + profile, + "-p:InnoNativeTarget=" + nativeTarget + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument document = JsonDocument.Parse(output); - Assert.Equal(shaderPlatform, document.RootElement.GetProperty("Properties") - .GetProperty("InnoImGuiShaderTarget").GetString()); + Assert.Equal( + shaderPlatform, + document.RootElement.GetProperty("Properties") + .GetProperty("InnoImGuiShaderTarget") + .GetString() + ); JsonElement items = document.RootElement.GetProperty("Items"); Assert.Equal(apiCount, items.GetProperty("_ImGuiShaderApi").GetArrayLength()); - Assert.All(items.GetProperty("ProjectReference").EnumerateArray() - .Where(reference => !reference.TryGetProperty("OutputItemType", out JsonElement kind) - || kind.GetString() != "Analyzer"), reference => - Assert.Contains("InnoProductBuildProperties=" + profile, - reference.GetProperty("AdditionalProperties").GetString())); + Assert.All( + items.GetProperty("ProjectReference") + .EnumerateArray() + .Where(reference => ( + !reference.TryGetProperty("OutputItemType", out JsonElement kind) + || kind.GetString() != "Analyzer" + )), + reference => + Assert.Contains( + "InnoProductBuildProperties=" + profile, + reference.GetProperty("AdditionalProperties").GetString() + ) + ); } [Fact] public async Task FrozenProductSourcesKeepTheExplicitOfflineToolOwner() { string root = TestRepository.GetRoot(typeof(EditorShaderProfileTests).Assembly); - string backend = Path.Combine(root, "backends", "Bgfx", "runtime", - "Inno.Adapter.Rendering.Bgfx", "Inno.Adapter.Rendering.Bgfx.csproj"); + string backend = Path.Combine( + root, + "backends", + "Bgfx", + "runtime", + "Inno.Adapter.Rendering.Bgfx", + "Inno.Adapter.Rendering.Bgfx.csproj" + ); string host = ToolchainEnvironment.ResolveExecutable("dotnet"); string selectedOwner = Path.Combine(root, "artifacts", "fixture-tool-source-owner"); - string selected = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", backend, "-nologo", "-nodeReuse:false", "-p:DesignTimeBuild=true", - "-p:InnoShaderToolSourceRoot=" + selectedOwner, "-getProperty:InnoShaderToolSourceRoot"], - root, CancellationToken.None, DotNetSdkEnvironment.Create(host)); + string selected = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + backend, + "-nologo", + "-nodeReuse:false", + "-p:DesignTimeBuild=true", + "-p:InnoShaderToolSourceRoot=" + selectedOwner, + "-getProperty:InnoShaderToolSourceRoot" + ], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(host) + ); Assert.Equal(selectedOwner, selected.Trim()); } } diff --git a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/ProductBindingSelectionTests.cs b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/ProductBindingSelectionTests.cs index 07b04153a..1d8483439 100644 --- a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/ProductBindingSelectionTests.cs +++ b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/ProductBindingSelectionTests.cs @@ -5,8 +5,8 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Testing.Source; using Xunit; +using Inno.Testing.Source; namespace Inno.Build.ProductProfiles.Integration.Tests; @@ -25,8 +25,10 @@ public async Task StandaloneBindingCompilationDeclaresItsDependencyWithoutProduc string product ) { string root = TestRepository.GetRoot(typeof(ProductBindingSelectionTests).Assembly); - string dotnet = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string dotnet = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(dotnet) { WorkingDirectory = root, @@ -37,12 +39,16 @@ string product }; foreach (string argument in new[] { - "msbuild", "backends/Bgfx/native/Inno.Native.Bgfx/Inno.Native.Bgfx.csproj", "-nologo", + "msbuild", + "backends/Bgfx/native/Inno.Native.Bgfx/Inno.Native.Bgfx.csproj", + "-nologo", "-getProperty:InnoBindingProductId,InnoProductId,InnoProductRestoreProject,BindGenGeneratedBindings", - "-p:Configuration=Debug", "-p:InnoNativeTarget=" + target, + "-p:Configuration=Debug", + "-p:InnoNativeTarget=" + target, "-p:InnoProductBuildProperties=" + Path.Combine(root, "platforms", platform, "build", "Inno.Build." + platform, properties) - }) + }) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start) ?? throw new InvalidOperationException("MSBuild did not start."); Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); @@ -54,7 +60,9 @@ string product catch { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } await process.WaitForExitAsync(); await output; await errors; diff --git a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs index 547d29b43..07d42877a 100644 --- a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs +++ b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.Collections.Generic; using System.IO; @@ -7,9 +6,10 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Build.ProductProfiles.Integration.Tests; @@ -37,11 +37,21 @@ string expectedTarget string root = TestRepository.GetRoot(typeof(StaticGraphRestoreTests).Assembly); string host = ToolchainEnvironment.ResolveExecutable("dotnet"); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(60)); - string output = await ToolchainEnvironment.CaptureOutputAsync(host, - ["msbuild", Path.Combine(root, "entry", "InnoEngine.Editor", "InnoEngine.Editor.csproj"), + string output = await ToolchainEnvironment.CaptureOutputAsync( + host, + [ + "msbuild", + Path.Combine(root, "entry", "InnoEngine.Editor", "InnoEngine.Editor.csproj"), "-p:NETCoreSdkRuntimeIdentifier=" + sdkHost, - "-getProperty:InnoNativeTarget,InnoProductBuildProperties", "-getItem:ProjectReference", "-nologo", "-nr:false"], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + "-getProperty:InnoNativeTarget,InnoProductBuildProperties", + "-getItem:ProjectReference", + "-nologo", + "-nr:false" + ], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); using JsonDocument evaluation = JsonDocument.Parse(output); JsonElement properties = evaluation.RootElement.GetProperty("Properties"); Assert.Equal(expectedTarget, properties.GetProperty("InnoNativeTarget").GetString()); @@ -50,7 +60,9 @@ string expectedTarget foreach (JsonElement reference in evaluation.RootElement.GetProperty("Items").GetProperty("ProjectReference").EnumerateArray()) { if (reference.TryGetProperty("OutputItemType", out JsonElement role) && role.GetString() == "Analyzer") + { continue; + } string context = reference.GetProperty("AdditionalProperties").GetString()!; Assert.Contains("InnoNativeTarget=" + expectedTarget, context); Assert.Contains("InnoProductBuildProperties=" + product, context); @@ -67,7 +79,7 @@ public async Task DevelopmentEntryRestoresItsDirectProductReferenceOwners() try { string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? ToolchainEnvironment.ResolveExecutable("dotnet"); + ?? ToolchainEnvironment.ResolveExecutable("dotnet"); string entry = Path.Combine(root, "entry", "InnoEngine.Editor", "InnoEngine.Editor.csproj"); string artifacts = Path.Combine(fixture, "managed"); string[] common = ["-p:Configuration=Debug", "-p:ArtifactsPath=" + artifacts, "-nodeReuse:false"]; @@ -75,23 +87,38 @@ public async Task DevelopmentEntryRestoresItsDirectProductReferenceOwners() JsonElement properties = route.RootElement.GetProperty("Properties"); string product = properties.GetProperty("InnoProductRestoreProject").GetString()!; Assert.True(File.Exists(product)); - string[] productProperties = [.. common, + string[] productProperties = + [ + .. common, "-p:InnoNativeTarget=" + properties.GetProperty("InnoNativeTarget").GetString(), "-p:InnoToolTarget=" + properties.GetProperty("InnoToolTarget").GetString(), - "-p:InnoProductBuildProperties=" + properties.GetProperty("InnoProductBuildProperties").GetString()]; + "-p:InnoProductBuildProperties=" + properties.GetProperty("InnoProductBuildProperties").GetString() + ]; using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - await ToolchainEnvironment.RunAsync(host, + await ToolchainEnvironment.RunAsync( + host, ["msbuild", entry, "-t:RestoreProductTargetGraph", "-v:quiet", .. common], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); var references = new HashSet(StringComparer.Ordinal); foreach (JsonElement reference in route.RootElement.GetProperty("Items").GetProperty("ProjectReference").EnumerateArray()) + { references.Add(reference.GetProperty("FullPath").GetString()!); + } using JsonDocument selectedProduct = await EvaluateAsync(host, product, productProperties); - foreach (JsonElement reference in selectedProduct.RootElement.GetProperty("Items").GetProperty("ProjectReference").EnumerateArray()) - { - if (!reference.TryGetProperty("PrivateAssets", out JsonElement privateAssets) || string.IsNullOrEmpty(privateAssets.GetString())) + foreach (JsonElement reference in selectedProduct.RootElement + .GetProperty("Items") + .GetProperty("ProjectReference") + .EnumerateArray() + ) { + if (!reference.TryGetProperty("PrivateAssets", out JsonElement privateAssets) + || string.IsNullOrEmpty(privateAssets.GetString()) + ) { references.Add(reference.GetProperty("FullPath").GetString()!); + } } Assert.NotEmpty(references); foreach (string reference in references) @@ -115,7 +142,7 @@ public async Task ProductRestoreAcceptsLargeInheritedProperties(bool inheritSolu { string root = TestRepository.GetRoot(typeof(StaticGraphRestoreTests).Assembly); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? ToolchainEnvironment.ResolveExecutable("dotnet"); + ?? ToolchainEnvironment.ResolveExecutable("dotnet"); IReadOnlyDictionary environment = DotNetSdkEnvironment.Create(host); string owner = Path.Combine(Path.GetTempPath(), "InnoStaticGraphRestoreTests"); string fixture = PathBoundary.Resolve(owner, Guid.NewGuid().ToString("N")); @@ -136,9 +163,13 @@ await File.WriteAllTextAsync(driver, $""" """); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(3)); - await ToolchainEnvironment.RunAsync(host, + await ToolchainEnvironment.RunAsync( + host, ["msbuild", driver, "-t:Verify", "-m:1", "-nodeReuse:false", "-nologo", "-v:minimal"], - root, cancellation.Token, environment); + root, + cancellation.Token, + environment + ); } finally { @@ -154,11 +185,22 @@ IReadOnlyList properties using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(1)); using var output = new StringWriter(); using var error = new StringWriter(); - await ToolchainEnvironment.RunAsync(host, - ["msbuild", project, "-nologo", .. properties, + await ToolchainEnvironment.RunAsync( + host, + [ + "msbuild", + project, + "-nologo", + .. properties, "-getProperty:ProjectAssetsFile,InnoProductRestoreProject,InnoNativeTarget,InnoToolTarget,InnoProductBuildProperties", - "-getItem:ProjectReference"], - Path.GetDirectoryName(project)!, cancellation.Token, DotNetSdkEnvironment.Create(host), output, error); + "-getItem:ProjectReference" + ], + Path.GetDirectoryName(project)!, + cancellation.Token, + DotNetSdkEnvironment.Create(host), + output, + error + ); return JsonDocument.Parse(output.ToString()); } } diff --git a/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs b/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs index ad2b3c01a..f6be6f963 100644 --- a/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs +++ b/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs @@ -24,8 +24,12 @@ public async Task StandardOwnersPreserveReadersAndIgnoreUnregisteredDirectories( publisher.Record(old, old + ".read.lock", [], "editor", null); publisher.Record(current, current + ".read.lock", [], "editor", null); } - using (BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(old, Path.Combine(m_root, "artifacts", "native"), "old", ["Outputs"])) - { + using (BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + old, + Path.Combine(m_root, "artifacts", "native"), + "old", + ["Outputs"] + )) { BuildCacheCleanupResult busy = await Plan().ExecuteAsync(); Assert.Empty(busy.retired); Assert.Contains(old, busy.skipped); @@ -52,10 +56,14 @@ public async Task NativeCurrentRetainsItsExactOlderBindingGeneration() bindings.Record(newBinding, newBinding + ".read.lock", [], "component", null); } using (await native.AcquireUseAsync()) + { native.Record(oldNative, oldNative + ".read.lock", [oldBinding], "component", null); + } Assert.Empty(Plan().candidates); using (await native.AcquireUseAsync()) + { native.Record(newNative, newNative + ".read.lock", [newBinding], "component", null); + } BuildCacheCleanupResult result = await Plan().ExecuteAsync(); Assert.Equal(2, result.retired.Count); Assert.Contains(oldNative, result.retired); @@ -87,11 +95,15 @@ public async Task ProcessOwnedLoadsProtectTheirExactHostDependency() File.WriteAllText(Path.Combine(load, "runtime.dll"), "private bytes"); var hosts = new BuildCachePublisher(Path.GetDirectoryName(host)!, BuildCacheArtifactRole.ImmutableArtifact); using (await hosts.AcquireUseAsync()) + { hosts.Record(host, host + ".lock", [], null, null); + } string secondHost = Path.Combine(Path.GetDirectoryName(host)!, "second"); Directory.CreateDirectory(secondHost); using (await hosts.AcquireUseAsync()) + { hosts.Record(secondHost, secondHost + ".lock", [], null, null); + } var loads = new BuildCachePublisher(Path.GetDirectoryName(load)!, BuildCacheArtifactRole.ProcessWorkingDirectory); loads.RecordProcessUse(load, load + ".lock", [host]); loads.RecordProcessUse(load, load + ".lock", [secondHost]); @@ -108,20 +120,26 @@ public async Task SizeAccountingIsRecordedByTheProducerWithoutServingAsIntegrity var publisher = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); string artifact = Create("native", "owned"); using (await publisher.AcquireUseAsync()) + { publisher.Record(artifact, artifact + ".read.lock", [], null, null); + } long recorded = Plan().totalBytes; File.WriteAllText(Path.Combine(artifact, "Outputs", "payload"), "corrupted and larger"); Assert.Equal(recorded, Plan().totalBytes); Assert.False(BuildArtifactManifest.IsComplete(artifact, "owned", ["Outputs"])); using (await publisher.AcquireUseAsync()) + { publisher.Record(artifact, artifact + ".read.lock", [], null, null); + } Assert.True(Plan().totalBytes > recorded); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private BuildCacheCleanupPlan Plan() diff --git a/tests/build/Inno.Build.Products.Tests/BuildCompositionTests.cs b/tests/build/Inno.Build.Products.Tests/BuildCompositionTests.cs index 1223fad7a..270832623 100644 --- a/tests/build/Inno.Build.Products.Tests/BuildCompositionTests.cs +++ b/tests/build/Inno.Build.Products.Tests/BuildCompositionTests.cs @@ -26,11 +26,17 @@ public sealed class BuildCompositionTests [InlineData("macos-arm64")] public void EditorAndStandaloneShaderToolsShareTheSameBindingFreeReleaseProducer(string target) { - var context = new BuildCompositionContext("explicit-sdk", Path.GetFullPath(Path.GetTempPath()), - new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64")); + var context = new BuildCompositionContext( + "explicit-sdk", + Path.GetFullPath(Path.GetTempPath()), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetId("windows-x64") + ); BuildDistribution distribution = StandardBuildDistribution.Create(context).build; - ProductNativeBuildStep editor = Assert.Single(distribution.ResolveNativeProduct(target, "editor").plan.steps, - static step => step.id == "bgfx-tools"); + ProductNativeBuildStep editor = Assert.Single( + distribution.ResolveNativeProduct(target, "editor").plan.steps, + static step => step.id == "bgfx-tools" + ); ProductNativeBuildStep standalone = Assert.Single(distribution.ResolveNativeProduct(target, "shader-tools").plan.steps); Assert.Equal("release", editor.configuration); Assert.Equal(editor.configuration, standalone.configuration); @@ -43,7 +49,12 @@ public void EditorAndStandaloneShaderToolsShareTheSameBindingFreeReleaseProducer [Fact] public void EveryHostObtainsTheSameFrozenBuiltInDistribution() { - var context = new BuildCompositionContext("explicit-sdk", Path.GetFullPath(Path.GetTempPath()), new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64")); + var context = new BuildCompositionContext( + "explicit-sdk", + Path.GetFullPath(Path.GetTempPath()), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetId("windows-x64") + ); BuildDistribution editor = StandardBuildDistribution.Create(context).build; BuildDistribution cli = StandardBuildDistribution.Create(context).build; BuildDistribution msbuild = StandardBuildDistribution.Create(context).build; @@ -52,10 +63,19 @@ public void EveryHostObtainsTheSameFrozenBuiltInDistribution() Assert.Equal(3, editor.availableTargets.Count); Assert.Equal(editor.managedDeployments.availableDeployments, msbuild.managedDeployments.availableDeployments); Assert.Equal(4, editor.managedDeployments.availableDeployments.Count); - Assert.Equal(editor.ResolveNativeProduct("windows-x64", "editor").plan.steps.Select(static step => step.id), - msbuild.ResolveNativeProduct("windows-x64", "editor").plan.steps.Select(static step => step.id)); + Assert.Equal( + editor.ResolveNativeProduct("windows-x64", "editor").plan.steps.Select(static step => step.id), + msbuild.ResolveNativeProduct("windows-x64", "editor").plan.steps.Select(static step => step.id) + ); Assert.Throws(() => editor.ResolveNativeProduct("browser-wasm", "editor")); - Assert.Throws(() => new BuildCompositionContext("sdk", "relative", new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64"))); + Assert.Throws( + () => new BuildCompositionContext( + "sdk", + "relative", + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetId("windows-x64") + ) + ); } [Fact] @@ -66,15 +86,38 @@ public void TargetsContributeDistinctImmutableProductClosuresWithoutChangingTheI ProductNativeBuildPlan complete = BuildTestProducts.Player(); var reduced = new ProductNativeBuildPlan("player", [complete.steps[0]]); NativeProductContribution[] products = [new(complete, new ComponentNativeProductExecutor())]; - var firstContribution = new BuildPlatformContribution(Descriptor(first), () => first, first, new FixtureToolchain(), nativeProducts: products); - var secondContribution = new BuildPlatformContribution(Descriptor(second), () => second, second, new FixtureToolchain(), nativeProducts: [new(reduced, new ComponentNativeProductExecutor())]); - var distribution = new BuildDistribution([Game(firstContribution, first), Game(secondContribution, second)], [new FixtureCompiler()]); + var firstContribution = new BuildPlatformContribution( + Descriptor(first), + () => first, + first, + new FixtureToolchain(), + nativeProducts: products + ); + var secondContribution = new BuildPlatformContribution( + Descriptor(second), + () => second, + second, + new FixtureToolchain(), + nativeProducts: [new(reduced, new ComponentNativeProductExecutor())] + ); + var distribution = new BuildDistribution( + [Game(firstContribution, first), Game(secondContribution, second)], + [new FixtureCompiler()] + ); products[0] = null!; Assert.Same(complete, distribution.ResolveNativeProduct("fixture-a", "player").plan); Assert.Same(reduced, distribution.ResolveNativeProduct("fixture-b", "player").plan); Assert.Throws(() => distribution.ResolveNativeProduct("fixture-a", "editor")); Assert.Throws(() => distribution.ResolveNativeProduct("absent-target", "player")); - Assert.Throws(() => new BuildPlatformContribution(Descriptor(first), () => first, first, new FixtureToolchain(), nativeProducts: [new(complete, new ComponentNativeProductExecutor()), new(reduced, new ComponentNativeProductExecutor())])); + Assert.Throws( + () => new BuildPlatformContribution( + Descriptor(first), + () => first, + first, + new FixtureToolchain(), + nativeProducts: [new(complete, new ComponentNativeProductExecutor()), new(reduced, new ComponentNativeProductExecutor())] + ) + ); } [Fact] @@ -87,12 +130,22 @@ public void CustomTargetComposesAndRejectsInconsistentDefaultsBeforePublication( using EngineHost engine = new EngineHostBuilder() .UseMetadataSources( new DotNetAssemblyCatalogSource(typeof(BuildCompositionTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); using var assets = new AssetPipeline( - engine.modules, engine.types, engine.serialization, new IdentityAllocator(), engine.diagnostics, engine.logs, + engine.modules, + engine.types, + engine.serialization, + new IdentityAllocator(), + engine.diagnostics, + engine.logs, AssetPipelineOptions.Create(Path.Combine(root, "Assets"), Path.Combine(root, "Library")) with - { enableFileSystemWatcher = false }); + { + enableFileSystemWatcher = false + } + ); var target = new FixtureTarget(); BuildTargetFactory factory = () => target; GameBuildContribution[] platforms = [Contribution(target, factory)]; @@ -102,7 +155,11 @@ public void CustomTargetComposesAndRejectsInconsistentDefaultsBeforePublication( distribution.ValidateDeployment(target, target.defaultManagedDeployment); Assert.Throws(() => distribution.ValidateDeployment(target, ManagedDeploymentId.coreClr)); Assert.Throws(() => new BuildPlatformContribution( - Descriptor(target), factory, new FixtureTarget(new BuildTargetId("different")), new FixtureToolchain())); + Descriptor(target), + factory, + new FixtureTarget(new BuildTargetId("different")), + new FixtureToolchain() + )); var invalid = new BuildDistribution([Contribution(target, () => new FixtureTarget(new BuildTargetId("different")))], [new FixtureCompiler()]); Assert.Throws(() => invalid.CreateBindings(assets, engine.serialization, engine.types)); @@ -121,12 +178,14 @@ public void DistributionRejectsAmbiguousOrIncompleteRegistrationSets() var target = new FixtureTarget(); BuildTargetFactory factory = () => target; Assert.Throws(() => new BuildDistribution([], [new FixtureCompiler()])); - Assert.Throws(() => new BuildDistribution([Contribution(target, factory), Contribution(target, factory)], [new FixtureCompiler()])); + Assert.Throws( + () => new BuildDistribution([Contribution(target, factory), Contribution(target, factory)], [new FixtureCompiler()]) + ); Assert.Throws(() => new BuildDistribution([Contribution(target, factory), null!], [new FixtureCompiler()])); } - private static PlatformTargetDescriptor Descriptor(FixtureTarget target) => - new(target.id, "Fixture", "fixture-cpu", "fixture-abi", target.runtimeIdentifier, supportsEditor: false); + private static PlatformTargetDescriptor Descriptor(FixtureTarget target) + => new(target.id, "Fixture", "fixture-cpu", "fixture-abi", target.runtimeIdentifier, supportsEditor: false); private static GameBuildContribution Contribution( FixtureTarget target, @@ -155,8 +214,13 @@ CancellationToken cancellationToken private sealed class FixtureCompiler(string runtimeIdentifier = "fixture-rid") : IManagedDeploymentCompiler { public ManagedDeploymentId id => new("fixture-managed"); + public ManagedDeploymentCapabilities capabilities { get; } = new( - [runtimeIdentifier], dynamicCode: false, aheadOfTime: true, nativeStaticLinking: true); + [runtimeIdentifier], + dynamicCode: false, + aheadOfTime: true, + nativeStaticLinking: true + ); public ValueTask CompileAsync( ManagedDeploymentRequest request, @@ -171,15 +235,19 @@ private sealed class FixtureTarget(BuildTargetId? identity = null) : IGameBuildT public ManagedDeploymentId defaultManagedDeployment => new("fixture-managed"); public string runtimeIdentifier => "fixture-rid"; public string displayName => "Fixture"; + public void Validate(string directory) => throw new InvalidOperationException("Composition must not read a pack."); + public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken ) => throw new InvalidOperationException("Composition must not prepare a pack."); + public ValueTask CompileAsync( GameBuildContentContext context, CancellationToken cancellationToken = default ) => throw new InvalidOperationException("Composition must not compile content."); + public ValueTask PackageAsync( GameBuildPackageContext context, CancellationToken cancellationToken = default diff --git a/tests/build/Inno.Build.Products.Tests/BuildTargetCatalogTests.cs b/tests/build/Inno.Build.Products.Tests/BuildTargetCatalogTests.cs index 2dc252359..ef17d2cd7 100644 --- a/tests/build/Inno.Build.Products.Tests/BuildTargetCatalogTests.cs +++ b/tests/build/Inno.Build.Products.Tests/BuildTargetCatalogTests.cs @@ -9,7 +9,6 @@ namespace Inno.Build.Products.Tests; public sealed class BuildTargetCatalogTests : BuildPipelineFixture { - [Fact] public void ProjectSettingsUseTheHostSuppliedInitialIdentity() { @@ -17,21 +16,20 @@ public void ProjectSettingsUseTheHostSuppliedInitialIdentity() Assert.False(m_settings.HasProjectOverride(ProjectIdentitySettings.settingId)); } - - [Fact] public void BuildTargetsAreOpenIdsOwnedByTheRegisteredAdapterCatalog() { Assert.Equal( [new BuildTargetId("macos-arm64"), new BuildTargetId("windows-x64")], - m_pipeline.availableGameTargets); - Assert.True(m_pipeline.TryGetGameTargetDisplayName( - new BuildTargetId("macos-arm64"), - out string macOSDisplayName)); + m_pipeline.availableGameTargets + ); + Assert.True( + m_pipeline.TryGetGameTargetDisplayName(new BuildTargetId("macos-arm64"), out string macOSDisplayName) + ); Assert.Equal("macOS (Apple silicon)", macOSDisplayName); - Assert.False(m_pipeline.TryGetGameTargetDisplayName( - new BuildTargetId("linux-x64"), - out string missingDisplayName)); + Assert.False( + m_pipeline.TryGetGameTargetDisplayName(new BuildTargetId("linux-x64"), out string missingDisplayName) + ); Assert.Empty(missingDisplayName); var profile = new BuildProfile @@ -44,8 +42,6 @@ public void BuildTargetsAreOpenIdsOwnedByTheRegisteredAdapterCatalog() profile.Validate(); } - - [Fact] public void BuildTargetInventoryCannotBeMutatedThroughItsCollectionView() { @@ -55,5 +51,4 @@ public void BuildTargetInventoryCannotBeMutatedThroughItsCollectionView() Assert.Throws(() => targets[0] = new BuildTargetId("unknown-target")); Assert.Equal([new BuildTargetId("macos-arm64"), new BuildTargetId("windows-x64")], m_pipeline.availableGameTargets); } - } diff --git a/tests/build/Inno.Build.Products.Tests/BuildTestProducts.cs b/tests/build/Inno.Build.Products.Tests/BuildTestProducts.cs index 3b80a91c8..44babb433 100644 --- a/tests/build/Inno.Build.Products.Tests/BuildTestProducts.cs +++ b/tests/build/Inno.Build.Products.Tests/BuildTestProducts.cs @@ -9,13 +9,23 @@ namespace Inno.Build.Products.Tests; internal static class BuildTestProducts { - internal static BuildHostDescriptor WindowsHost() => new WindowsBuildHostProvider().TryCapture() - ?? throw new PlatformNotSupportedException("This native fixture requires a Windows build host."); - internal static BuildDistribution Distribution() => StandardBuildDistribution.Create(new BuildCompositionContext( - "explicit-sdk", Path.GetTempPath(), new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64"))).build; + internal static BuildHostDescriptor WindowsHost() + => new WindowsBuildHostProvider().TryCapture() + ?? throw new PlatformNotSupportedException("This native fixture requires a Windows build host."); + + internal static BuildDistribution Distribution() + => StandardBuildDistribution.Create( + new BuildCompositionContext( + "explicit-sdk", + Path.GetTempPath(), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetId("windows-x64") + ) + ).build; internal static ProductNativeBuildPlan Player() => Distribution().ResolveNativeProduct("windows-x64", "player").plan; + internal static ProductNativeBuildPlan Editor() => Distribution().ResolveNativeProduct("windows-x64", "editor").plan; - internal static ProductNativeBuildPlan StaticPlayer() => Distribution().ResolveNativeProduct("browser-wasm", "player").plan; + internal static ProductNativeBuildPlan StaticPlayer() => Distribution().ResolveNativeProduct("browser-wasm", "player").plan; } diff --git a/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs b/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs index d18a3ce77..12d1004d4 100644 --- a/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs +++ b/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs @@ -1,48 +1,40 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.IO.Compression; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; - +using Xunit; using Inno.Adapter.Content.FileSystem; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Build.Managed; -using Inno.Content; -using Inno.Core.IO; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.MacOSArm64; +using Inno.Build.Managed; using Inno.Build.WindowsX64; -using Inno.Core.Identity; +using Inno.Content; using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Types; - - - - using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; - -using Xunit; -using Inno.Build; using Inno.Testing.Build; namespace Inno.Build.Products.Tests; public sealed class GameBuildWorkflowTests : BuildPipelineFixture { - [Theory] [InlineData("macos-arm64")] [InlineData("windows-x64")] @@ -65,30 +57,45 @@ public async Task GameBuildPublishesOnlyVerifiedContentPacksAndRuntimeAssemblies string outputPath = Assert.IsType(result.outputPath); string contentHash = Assert.IsType(result.contentHash); string packagedContent = target == new BuildTargetId("macos-arm64") - ? Path.Combine(outputPath, "Contents", "Resources", "Content") - : Path.Combine(outputPath, "Content"); + ? Path.Combine(outputPath, "Contents", "Resources", "Content") + : Path.Combine(outputPath, "Content"); string executable = target == new BuildTargetId("macos-arm64") - ? Path.Combine(outputPath, "Contents", "MacOS", "Test Game") - : Path.Combine(outputPath, "Test Game.exe"); + ? Path.Combine(outputPath, "Contents", "MacOS", "Test Game") + : Path.Combine(outputPath, "Test Game.exe"); Assert.True(File.Exists(executable)); string playerRoot = target == new BuildTargetId("macos-arm64") - ? Path.Combine(outputPath, "Contents", "MacOS") - : outputPath; + ? Path.Combine(outputPath, "Contents", "MacOS") + : outputPath; Assert.False(Directory.Exists(Path.Combine(playerRoot, "References"))); string deployedNative = target == new BuildTargetId("macos-arm64") - ? Path.Combine(outputPath, "Contents", "MacOS", "native") - : Path.Combine(outputPath, "native"); - Assert.True(File.Exists(Path.Combine(deployedNative, target == new BuildTargetId("macos-arm64") - ? "libinno-text-release.dylib" - : "inno-text-release.dll"))); - Assert.True(File.Exists(Path.Combine(deployedNative, target == new BuildTargetId("macos-arm64") - ? "libinno-ui-release.dylib" - : "inno-ui-release.dll"))); + ? Path.Combine(outputPath, "Contents", "MacOS", "native") + : Path.Combine(outputPath, "native"); + Assert.True( + File.Exists( + Path.Combine( + deployedNative, + target == new BuildTargetId("macos-arm64") + ? "libinno-text-release.dylib" + : "inno-text-release.dll" + ) + ) + ); + Assert.True( + File.Exists( + Path.Combine( + deployedNative, + target == new BuildTargetId("macos-arm64") + ? "libinno-ui-release.dylib" + : "inno-ui-release.dll" + ) + ) + ); Assert.Equal( ["catalog.inno", $"content-{contentHash}.pack", "runtime.manifest"], Directory.EnumerateFiles(packagedContent) .Select(Path.GetFileName) - .Order(StringComparer.Ordinal)); + .Order(StringComparer.Ordinal) + ); byte[] envelope = File.ReadAllBytes(Path.Combine(packagedContent, "runtime.manifest")); Assert.Equal("tests.game", RuntimeManifestEnvelope.ReadApplicationId(envelope)); @@ -103,63 +110,91 @@ public async Task GameBuildPublishesOnlyVerifiedContentPacksAndRuntimeAssemblies string persistentRoot = Path.Combine(m_root, "Persistent", manifest.applicationId); RuntimeContentCatalog contentCatalog = serialization.Deserialize( - File.ReadAllBytes(Path.Combine(packagedContent, "catalog.inno"))); + File.ReadAllBytes(Path.Combine(packagedContent, "catalog.inno")) + ); contentCatalog.Validate(); using PackContentStore packStore = ContentPackReader.Open( File.OpenRead(Path.Combine(packagedContent, contentCatalog.packFileName)), - new ContentPackDescriptor(contentCatalog.contentHash, contentCatalog.packFileName), serialization); - using FileContentStore contentStore = await FileContentPreparation.PrepareAsync(packStore, - new FileContentCacheOptions(persistentRoot)); + new ContentPackDescriptor(contentCatalog.contentHash, contentCatalog.packFileName), + serialization + ); + using FileContentStore contentStore = await FileContentPreparation.PrepareAsync( + packStore, + new FileContentCacheOptions(persistentRoot) + ); using var runtimeAssets = new AssetDatabase( contentStore, serialization, runtimeTypes, new IdentityAllocator(), - residencyBudgetBytes: 0); + residencyBudgetBytes: 0 + ); Task> coldLoad = runtimeAssets.AcquireAsync( - AssetPath.Project("Scenes/Startup.iscene")).AsTask(); + AssetPath.Project("Scenes/Startup.iscene") + ).AsTask(); long preparingBytes = runtimeAssets.preparingBytes; Assert.True(preparingBytes > 0); using var coalescedCancellation = new CancellationTokenSource(); Task> coalesced = runtimeAssets.AcquireAsync( - AssetPath.Project("Scenes/Startup.iscene"), coalescedCancellation.Token).AsTask(); + AssetPath.Project("Scenes/Startup.iscene"), + coalescedCancellation.Token + ).AsTask(); Assert.Equal(preparingBytes, runtimeAssets.preparingBytes); coalescedCancellation.Cancel(); Assert.False(coldLoad.IsCompleted); - Assert.True(SpinWait.SpinUntil(() => - { - runtimeAssets.CompletePendingLoads(); - return coldLoad.IsCompleted; - }, TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => + { + runtimeAssets.CompletePendingLoads(); + return coldLoad.IsCompleted; + }, TimeSpan.FromSeconds(5)) + ); using (AssetLease lease = await coldLoad) + { Assert.NotNull(lease.asset); + } Assert.True(coalesced.IsCanceled); Assert.Equal(0, runtimeAssets.preparingBytes); Assert.Equal(0, runtimeAssets.residencyStatistics.residentAssetCount); - using (var limited = new AssetDatabase(contentStore, serialization, runtimeTypes, - new IdentityAllocator(), preparationBudgetBytes: 1)) - { + using (var limited = new AssetDatabase( + contentStore, + serialization, + runtimeTypes, + new IdentityAllocator(), + preparationBudgetBytes: 1 + )) { Assert.Throws(() => limited.AcquireAsync( - AssetPath.Project("Scenes/Startup.iscene"))); + AssetPath.Project("Scenes/Startup.iscene") + )); Assert.Equal(0, limited.preparingBytes); } using var loadCancellation = new CancellationTokenSource(); Task> canceledLoad = runtimeAssets.AcquireAsync( - AssetPath.Project("Scenes/Startup.iscene"), loadCancellation.Token).AsTask(); + AssetPath.Project("Scenes/Startup.iscene"), + loadCancellation.Token + ).AsTask(); loadCancellation.Cancel(); - Assert.True(SpinWait.SpinUntil(() => - { - runtimeAssets.CompletePendingLoads(); - return canceledLoad.IsCompleted; - }, TimeSpan.FromSeconds(5))); + Assert.True( + SpinWait.SpinUntil(() => + { + runtimeAssets.CompletePendingLoads(); + return canceledLoad.IsCompleted; + }, TimeSpan.FromSeconds(5)) + ); Assert.True(canceledLoad.IsCanceled); Assert.True(contentStore.index.TryGetEntry(new ContentKey("AssetDatabase/Catalog.snapshot"), out _)); - Assert.DoesNotContain(contentStore.index.entries, static entry => entry.key.value!.StartsWith("Managed/", StringComparison.Ordinal)); Assert.DoesNotContain( contentStore.index.entries, - static entry => entry.key.value!.EndsWith(".iscene", StringComparison.OrdinalIgnoreCase) - || entry.key.value.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase) - || entry.key.value.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)); + static entry => entry.key.value!.StartsWith("Managed/", StringComparison.Ordinal) + ); + Assert.DoesNotContain( + contentStore.index.entries, + static entry => ( + entry.key.value!.EndsWith(".iscene", StringComparison.OrdinalIgnoreCase) + || entry.key.value.EndsWith(".imeta", StringComparison.OrdinalIgnoreCase) + || entry.key.value.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) + ) + ); Assert.Equal(1, result.assetCount); Assert.Equal(1, result.runtimeAssemblyCount); } @@ -170,9 +205,7 @@ public async Task GameBuildWaitsForPendingStartupSceneImportBeforeValidation() AssetPath stagedPath = AssetPath.Project("Staged/Startup.iscene"); var scene = new GameScene("Startup"); scene.CreateObject("Player"); - Assert.True(m_assets.Save( - stagedPath, - SceneAsset.Capture(scene, m_engine.serialization, m_assets))); + Assert.True(m_assets.Save(stagedPath, SceneAsset.Capture(scene, m_engine.serialization, m_assets))); string stagedSource = Path.Combine(m_projectRoot, "Assets", "Staged", "Startup.iscene"); string destinationDirectory = Path.Combine(m_projectRoot, "Assets", "Scenes"); string destinationSource = Path.Combine(destinationDirectory, "Startup.iscene"); @@ -207,10 +240,9 @@ public async Task BackgroundArtifactExportUsesAnOwnerThreadSerializationSnapshot public async Task BackgroundArtifactExportRejectsACorruptCurrentFormatManifest() { SaveStartupScene(); - string manifest = Assert.Single(Directory.EnumerateFiles( - m_assets.artifactRoot, - "manifest", - SearchOption.AllDirectories)); + string manifest = Assert.Single( + Directory.EnumerateFiles(m_assets.artifactRoot, "manifest", SearchOption.AllDirectories) + ); File.WriteAllBytes(manifest, [0x42, 0x41, 0x44]); InvalidDataException failure = await Assert.ThrowsAsync(() => @@ -233,7 +265,8 @@ public async Task ChangedAuthoringGenerationCannotCommitAMixedBuildSnapshot() m_compiler, m_supportPackRoot, [new GameBuildTargetBinding(target, target)], - CreateManagedDeployments()); + CreateManagedDeployments() + ); string outputRoot = Path.Combine(m_root, "Builds", "MixedGeneration"); Task build = pipeline.BuildGameAsync(new GameBuildRequest @@ -241,9 +274,7 @@ [new GameBuildTargetBinding(target, target)], profile = CreateProfile(new BuildTargetId("macos-arm64")), outputDirectory = outputRoot }).AsTask(); - Assert.True(SpinWait.SpinUntil( - () => target.started.Task.IsCompleted, - TimeSpan.FromSeconds(2))); + Assert.True(SpinWait.SpinUntil(() => target.started.Task.IsCompleted, TimeSpan.FromSeconds(2))); Assert.True(m_assets.Save(AssetPath.Project("Changed.txt"), new TextAsset("new generation"))); target.release.SetResult(); @@ -271,15 +302,11 @@ public async Task CompilationFailureLeavesNoProductOrStagingDirectory() Assert.False(result.succeeded); Assert.Null(result.outputPath); - Assert.Contains(result.diagnostics, static diagnostic => - diagnostic.severity == BuildDiagnosticSeverity.Error); + Assert.Contains(result.diagnostics, static diagnostic => diagnostic.severity == BuildDiagnosticSeverity.Error); Assert.False(Directory.Exists(Path.Combine(outputRoot, "Test Game.app"))); if (Directory.Exists(outputRoot)) { - Assert.Empty(Directory.EnumerateDirectories( - outputRoot, - ".inno-build-*", - SearchOption.TopDirectoryOnly)); + Assert.Empty(Directory.EnumerateDirectories(outputRoot, ".inno-build-*", SearchOption.TopDirectoryOnly)); } } @@ -288,7 +315,9 @@ public async Task CompilationFailureLeavesNoProductOrStagingDirectory() public async Task CommittedGameReportsBackupCleanupAsAWarningWithoutLosingSuccess() { if (!OperatingSystem.IsWindows()) + { return; + } SaveStartupScene(); var request = new GameBuildRequest { @@ -307,13 +336,20 @@ public async Task CommittedGameReportsBackupCleanupAsAWarningWithoutLosingSucces Assert.Equal(previous, current.outputPath); Assert.True(File.Exists(Path.Combine(current.outputPath!, "Test Game.exe"))); Assert.False(File.Exists(locked)); - Assert.Contains(current.diagnostics, static diagnostic => diagnostic.code == "INNO-BUILD-CLEANUP" - && diagnostic.severity == BuildDiagnosticSeverity.Warning); + Assert.Contains(current.diagnostics, static diagnostic => ( + diagnostic.code == "INNO-BUILD-CLEANUP" + && diagnostic.severity == BuildDiagnosticSeverity.Warning + )); } finally { - foreach (string retained in Directory.EnumerateFiles(request.outputDirectory, "retained-readonly.txt", SearchOption.AllDirectories)) + foreach (string retained in Directory.EnumerateFiles( + request.outputDirectory, + "retained-readonly.txt", + SearchOption.AllDirectories + )) { File.SetAttributes(retained, FileAttributes.Normal); + } } } @@ -328,8 +364,10 @@ public async Task CommittedGameRemainsSuccessfulWhenItsFinalProgressObserverThro }, new CommitFailingProgress()); Assert.True(result.succeeded); Assert.True(File.Exists(Path.Combine(result.outputPath!, "Test Game.exe"))); - Assert.Contains(result.diagnostics, static diagnostic => diagnostic.code == "INNO-BUILD-PROGRESS" - && diagnostic.severity == BuildDiagnosticSeverity.Warning); + Assert.Contains(result.diagnostics, static diagnostic => ( + diagnostic.code == "INNO-BUILD-PROGRESS" + && diagnostic.severity == BuildDiagnosticSeverity.Warning + )); } [Fact] @@ -347,15 +385,13 @@ await Assert.ThrowsAnyAsync(() => profile = CreateProfile(new BuildTargetId("macos-arm64")), outputDirectory = outputRoot }, - cancellationToken: cancellation.Token).AsTask()); + cancellationToken: cancellation.Token + ).AsTask()); Assert.False(Directory.Exists(Path.Combine(outputRoot, "Test Game.app"))); if (Directory.Exists(outputRoot)) { - Assert.Empty(Directory.EnumerateDirectories( - outputRoot, - ".inno-build-*", - SearchOption.TopDirectoryOnly)); + Assert.Empty(Directory.EnumerateDirectories(outputRoot, ".inno-build-*", SearchOption.TopDirectoryOnly)); } } @@ -380,9 +416,7 @@ public async Task GameBuildRejectsManagedProjectOutputWithoutLeavingAProduct() public async Task PluginBuildIsDeterministicSourceOnlyAndUsesTheInstallContract() { m_assets.CreateDirectory(AssetPath.Project("Content")); - Assert.True(m_assets.Save( - AssetPath.Project("Content/value.txt"), - new TextAsset("deterministic"))); + Assert.True(m_assets.Save(AssetPath.Project("Content/value.txt"), new TextAsset("deterministic"))); string firstPath = Path.Combine(m_root, "first.iplugin"); string secondPath = Path.Combine(m_root, "second.iplugin"); @@ -421,7 +455,8 @@ public async Task PluginBuildIsDeterministicSourceOnlyAndUsesTheInstallContract( PluginScanResult scan = new PluginSourceService( m_engine.serialization, installRoot, - Path.Combine(m_root, "InstallLibrary")).Scan(); + Path.Combine(m_root, "InstallLibrary") + ).Scan(); Assert.Empty(scan.diagnostics); PluginCandidate candidate = Assert.Single(scan.candidates); Assert.Equal("tests.export", candidate.manifest.pluginId); @@ -445,7 +480,8 @@ await Assert.ThrowsAnyAsync(() => displayName = "Canceled", outputPath = output }, - cancellationToken: cancellation.Token).AsTask()); + cancellationToken: cancellation.Token + ).AsTask()); Assert.False(File.Exists(output)); Assert.Empty(Directory.EnumerateFiles(m_root, "Canceled.iplugin.staging-*", SearchOption.TopDirectoryOnly)); diff --git a/tests/build/Inno.Build.Products.Tests/GameContentCompilerBindingTests.cs b/tests/build/Inno.Build.Products.Tests/GameContentCompilerBindingTests.cs index ae77d371e..c8706bc4e 100644 --- a/tests/build/Inno.Build.Products.Tests/GameContentCompilerBindingTests.cs +++ b/tests/build/Inno.Build.Products.Tests/GameContentCompilerBindingTests.cs @@ -1,8 +1,8 @@ using System; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Managed; using Xunit; +using Inno.Build.Managed; namespace Inno.Build.Products.Tests; @@ -63,6 +63,7 @@ private sealed class FixturePackager : IGameBuildTarget public string runtimeIdentifier => "fixture-rid"; public string displayName => "Fixture"; internal int calls { get; private set; } + public void Validate(string directory) => throw new InvalidOperationException("Binding must not inspect output."); public ValueTask PackageAsync( diff --git a/tests/build/Inno.Build.Products.Tests/ManagedDeploymentTests.cs b/tests/build/Inno.Build.Products.Tests/ManagedDeploymentTests.cs index 42f97ea40..e97a3ba12 100644 --- a/tests/build/Inno.Build.Products.Tests/ManagedDeploymentTests.cs +++ b/tests/build/Inno.Build.Products.Tests/ManagedDeploymentTests.cs @@ -2,10 +2,10 @@ using System.IO; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Managed; using Inno.Build.Managed.DotNet; using Inno.Build.Toolchains; -using Xunit; namespace Inno.Build.Products.Tests; @@ -28,7 +28,9 @@ public void DotNetProvidersConsumeAnOpenFrozenTargetSelection() Assert.Equal(4, catalog.GetSupportedDeployments("fixture-runtime").Count); Assert.Empty(catalog.GetSupportedDeployments("changed")); foreach (IManagedDeploymentCompiler compiler in compilers) + { Assert.Same(compiler, catalog.Resolve(compiler.id, "fixture-runtime")); + } } [Fact] @@ -46,24 +48,41 @@ public void OpenProviderCatalogDispatchesCustomIdentityWithoutPlatformBranches() public void CapabilityInputsAndPublicationArtifactsAreImmutable() { string[] targets = ["custom-target"]; - var capabilities = new ManagedDeploymentCapabilities(targets, - dynamicCode: false, aheadOfTime: true, nativeStaticLinking: true); + var capabilities = new ManagedDeploymentCapabilities( + targets, + dynamicCode: false, + aheadOfTime: true, + nativeStaticLinking: true + ); targets[0] = "replaced"; Assert.Equal("custom-target", Assert.Single(capabilities.runtimeIdentifiers)); string[] files = ["game.wasm"]; - var result = new ManagedDeploymentResult(new ManagedDeploymentId("custom-runtime"), - Path.GetTempPath(), "selected-sdk", files); + var result = new ManagedDeploymentResult( + new ManagedDeploymentId("custom-runtime"), + Path.GetTempPath(), + "selected-sdk", + files + ); files[0] = "replaced.wasm"; Assert.Equal("game.wasm", Assert.Single(result.files)); - Assert.Throws(() => new ManagedDeploymentResult(result.deployment, - result.outputDirectory, result.sdkIdentity, ["../outside"])); + Assert.Throws(() => new ManagedDeploymentResult( + result.deployment, + result.outputDirectory, + result.sdkIdentity, + ["../outside"] + )); } private sealed class CustomCompiler : IManagedDeploymentCompiler { public ManagedDeploymentId id => new("custom-runtime"); + public ManagedDeploymentCapabilities capabilities { get; } = new( - ["custom-target"], dynamicCode: false, aheadOfTime: true, nativeStaticLinking: true); + ["custom-target"], + dynamicCode: false, + aheadOfTime: true, + nativeStaticLinking: true + ); public ValueTask CompileAsync( ManagedDeploymentRequest request, diff --git a/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs b/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs index 563780a6f..ca08ec97b 100644 --- a/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs +++ b/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs @@ -22,8 +22,9 @@ public void EquivalentCheckoutSpellingsHaveOneRecipeIdentity() var owner = new NativeComponentDescriptor("fixture", "native/fixture.csproj", "build/fixture.csproj"); Directory.CreateDirectory(Path.Combine(m_root, "build")); File.WriteAllText(Path.Combine(m_root, "build", "fixture.csproj"), ""); - NativeBuildContext Context(string path) => new NativeBuildContext(path, "release") - .WithComponentOptions(owner, new(NativeLibraryKind.Shared)); + NativeBuildContext Context(string path) + => new NativeBuildContext(path, "release") + .WithComponentOptions(owner, new(NativeLibraryKind.Shared)); var plain = Context(m_root); var separated = Context(m_root + Path.DirectorySeparatorChar); Assert.Equal(plain.engineRoot, separated.engineRoot); @@ -37,7 +38,9 @@ public void EquivalentCheckoutSpellingsHaveOneRecipeIdentity() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -51,8 +54,16 @@ public void SelectedCheckoutOwnsIntermediatesEvenWhenTheToolRunsFromAnotherCheck Assert.Equal(new PhysicalPathResolver().Resolve(m_root), context.engineRoot); Assert.Equal("release", context.configuration); - Assert.Equal(Path.Combine(context.engineRoot, "build", "toolchains", "Inno.Build.Toolchains", "obj", "native"), - context.GetNativeBuildRoot(new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"))); + Assert.Equal( + Path.Combine(context.engineRoot, "build", "toolchains", "Inno.Build.Toolchains", "obj", "native"), + context.GetNativeBuildRoot( + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ) + ) + ); Assert.NotEqual(TestRepository.GetRoot(typeof(NativeBuildContextTests).Assembly), context.engineRoot); Assert.False(Directory.Exists(Path.Combine(owner, "obj"))); } @@ -77,9 +88,11 @@ public async Task CanceledBuildDoesNotStartAComponentOrCreateIntermediates(bool cancellation.Cancel(); var context = new NativeBuildContext(m_root, "debug"); - await Assert.ThrowsAnyAsync(() => editor + await Assert.ThrowsAnyAsync(() => ( + editor ? new ComponentNativeProductExecutor().BuildAsync(context, BuildTestProducts.Editor(), cancellation.Token) - : new ComponentNativeProductExecutor().BuildAsync(context, BuildTestProducts.Player(), cancellation.Token)); + : new ComponentNativeProductExecutor().BuildAsync(context, BuildTestProducts.Player(), cancellation.Token) + )); Assert.Single(Directory.EnumerateFileSystemEntries(m_root)); } @@ -90,7 +103,8 @@ public async Task UnresolvedToolchainsFailBeforeIntermediatesOrSourceDiscovery() CreateCheckout(); var context = new NativeBuildContext(m_root, "release"); InvalidOperationException failure = await Assert.ThrowsAsync( - () => new ComponentNativeProductExecutor().BuildAsync(context, BuildTestProducts.Player(), CancellationToken.None)); + () => new ComponentNativeProductExecutor().BuildAsync(context, BuildTestProducts.Player(), CancellationToken.None) + ); Assert.Contains("explicit target toolchain", failure.Message, StringComparison.Ordinal); Assert.Single(Directory.EnumerateFileSystemEntries(m_root)); } diff --git a/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs b/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs index 1191a7f0b..eb4a30455 100644 --- a/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs +++ b/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs @@ -24,11 +24,17 @@ public void OptionsFreezeOrderedDefinitionsAndRejectAmbiguousSdkOverrides() Assert.Equal("-DA=one", options.cmakeArguments[0]); Assert.Equal("config/profile.cs", Assert.Single(options.inputPaths)); Assert.Throws(() => new NativeComponentBuildOptions((NativeLibraryKind)99)); - foreach (string[] invalid in new[] { - new[] { "-DCMAKE_TOOLCHAIN_FILE=other" }, new[] { "-DINNO_COMPONENT_BRIDGE=other" }, new[] { "-DINNO_LIBRARY_KIND=SHARED" }, - new[] { "-DA=one", "-DA:STRING=two" }, new[] { "--build" }, new[] { "-DA=one\0two" } - }) + foreach (string[] invalid in new[] + { + new[] { "-DCMAKE_TOOLCHAIN_FILE=other" }, + new[] { "-DINNO_COMPONENT_BRIDGE=other" }, + new[] { "-DINNO_LIBRARY_KIND=SHARED" }, + new[] { "-DA=one", "-DA:STRING=two" }, + new[] { "--build" }, + new[] { "-DA=one\0two" } + }) { Assert.Throws(() => new NativeComponentBuildOptions(NativeLibraryKind.Shared, invalid)); + } Assert.Throws(() => new NativeComponentBuildOptions(NativeLibraryKind.Static, inputPaths: ["../escape"])); Assert.Throws(() => new NativeComponentBuildOptions(NativeLibraryKind.Static, inputPaths: ["C:/absolute"])); } @@ -44,12 +50,28 @@ public async Task RecipeOwnedDefinitionsCannotBeReplacedBeforeAnyToolStarts() string tool = Path.Combine(root, "unexecutable.fixture"); File.WriteAllText(tool, "This file must never execute."); var owner = new NativeComponentDescriptor("fixture", "Native.csproj", "Build.csproj"); - var selection = new NativeToolchainSelection("fixture-target", new BuildHostDescriptor("Windows", "x64"), - new Dictionary { ["cmake"] = tool }, new Dictionary(), [], [], new NativeLinkPlan(".dll"), false); + var selection = new NativeToolchainSelection( + "fixture-target", + new BuildHostDescriptor("Windows", "x64"), + new Dictionary { ["cmake"] = tool }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".dll"), + false + ); var context = new NativeBuildContext(root, "debug").WithToolchain(selection).WithComponentOptions( - owner, new NativeComponentBuildOptions(NativeLibraryKind.Shared, ["-DLINKAGE:BOOL=OFF"])); - await Assert.ThrowsAsync(() => NativeCMakeExecutor.BuildAsync(context, owner, root, - "fixture", ["-DLINKAGE=ON"], CancellationToken.None)); + owner, + new NativeComponentBuildOptions(NativeLibraryKind.Shared, ["-DLINKAGE:BOOL=OFF"]) + ); + await Assert.ThrowsAsync(() => NativeCMakeExecutor.BuildAsync( + context, + owner, + root, + "fixture", + ["-DLINKAGE=ON"], + CancellationToken.None + )); Assert.Equal(0, context.statistics.nativeProcesses); Assert.False(Directory.Exists(Path.Combine(root, "obj"))); } @@ -62,19 +84,28 @@ await Assert.ThrowsAsync(() => NativeCMakeExecutor.BuildAsync [Fact] public void StaticRecipesDeclareOnlyNativeSourceRootsThatTheyActuallyConsume() { - var source = new NativeStaticBuildDefinition("build/Static.cmake", ["native/include", "native/src"], - ["fixture"], "native"); + var source = new NativeStaticBuildDefinition( + "build/Static.cmake", + ["native/include", "native/src"], + ["fixture"], + "native" + ); Assert.Equal("native", source.nativeSourceDirectory); Assert.Null(new NativeStaticBuildDefinition("build/Static.cmake", ["vendor"], ["fixture"]).nativeSourceDirectory); - Assert.Throws(() => new NativeStaticBuildDefinition("build/Static.cmake", ["vendor"], - ["fixture"], "undeclared/native")); + Assert.Throws(() => new NativeStaticBuildDefinition( + "build/Static.cmake", + ["vendor"], + ["fixture"], + "undeclared/native" + )); } [Fact] public void ProductPlanDeclaresStaticArchivesAndDoesNotGuessLinkageFromTheHost() { ProductNativeBuildPlan plan = BuildTestProducts.StaticPlayer(); - Assert.All(plan.steps, static step => { + Assert.All(plan.steps, static step => + { Assert.Equal(NativeLibraryKind.Static, step.options.libraryKind); Assert.NotEmpty(step.component.staticBuild!.logicalOutputs); }); @@ -99,11 +130,21 @@ public void LinkageOrderedArgumentsAndConfigurationBytesAllChangeRecipeIdentity( string Identity(NativeComponentBuildOptions options) { var context = new NativeBuildContext(root, "debug").WithComponentOptions(owner, options); - NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent(context, owner, "fixture", "fixture-target", [], [], [config]); + NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent( + context, + owner, + "fixture", + "fixture-target", + [], + [], + [config] + ); foreach (NativeBuildInput input in recipe.inputs) { if (File.Exists(input.physicalPath) || Directory.Exists(input.physicalPath)) + { continue; + } Directory.CreateDirectory(Path.GetDirectoryName(input.physicalPath)!); File.WriteAllText(input.physicalPath, "executor"); } diff --git a/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs b/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs index 5e3e08ced..9da3cc33b 100644 --- a/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs +++ b/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs @@ -16,8 +16,13 @@ namespace Inno.Build.Products.Tests; public sealed class NativeRecipeClosureTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoRecipeClosureTests", Guid.NewGuid().ToString("N")); - private readonly NativeComponentDescriptor m_owner = new("fixture", "native/fixture.csproj", "build/fixture.csproj", - bindingDefinition: "native/Bindings/bindings.props"); + + private readonly NativeComponentDescriptor m_owner = new( + "fixture", + "native/fixture.csproj", + "build/fixture.csproj", + bindingDefinition: "native/Bindings/bindings.props" + ); public NativeRecipeClosureTests() { @@ -52,12 +57,17 @@ public void BackendDeclarationUsesItsProducerOptionsWithoutGeneratingBindings(bo Assert.Equal(owner.id, recipe.component); Assert.Equal("fixture-target", recipe.targetId); Assert.Contains(recipe.declarations, value => value == (audio ? "-DBUILD_SHARED_LIBS=ON" : "-DSDL_SHARED=ON")); - Assert.DoesNotContain(recipe.inputs, input => input.physicalPath.Contains("BuildUtils", StringComparison.Ordinal) - || input.physicalPath.Contains("BuildConstants", StringComparison.Ordinal)); + Assert.DoesNotContain(recipe.inputs, input => ( + input.physicalPath.Contains("BuildUtils", StringComparison.Ordinal) + || input.physicalPath.Contains("BuildConstants", StringComparison.Ordinal) + )); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts"))); NativeBuildContext staticContext = context.WithComponentOptions(owner, new(NativeLibraryKind.Static)); - Assert.Throws(() => audio - ? MiniAudioToolchain.CreateRecipe(staticContext) : Sdl3Toolchain.CreateRecipe(staticContext)); + Assert.Throws(() => ( + audio + ? MiniAudioToolchain.CreateRecipe(staticContext) + : Sdl3Toolchain.CreateRecipe(staticContext) + )); } [Theory] @@ -72,8 +82,10 @@ public void BridgeBackendDeclarationExcludesHostGeneratedOutput(bool ui) NativeBuildRecipe recipe = ui ? UiToolchain.CreateRecipe(context) : TextToolchain.CreateRecipe(context); Assert.Equal(owner.id, recipe.component); Assert.DoesNotContain(recipe.declarations, value => value.Contains("BRIDGE_ROOT", StringComparison.Ordinal)); - Assert.DoesNotContain(recipe.inputs, input => input.physicalPath.EndsWith("Native", StringComparison.Ordinal) - || input.physicalPath.Contains("Generated", StringComparison.Ordinal)); + Assert.DoesNotContain(recipe.inputs, input => ( + input.physicalPath.EndsWith("Native", StringComparison.Ordinal) + || input.physicalPath.Contains("Generated", StringComparison.Ordinal) + )); Assert.Contains(recipe.inputs, input => input.physicalPath.EndsWith("CMakeLists.txt", StringComparison.Ordinal)); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts"))); } @@ -86,22 +98,35 @@ public void ProductSourceDeclarationUsesEachSelectedOwnerWithoutExecutingProduce foreach (string id in new[] { "first", "second" }) { var owner = new NativeComponentDescriptor(id, m_owner.nativeProject, m_owner.toolchainProject); - steps.Add(new ProductNativeBuildStep(id, owner, new(NativeLibraryKind.Shared), id == "first" ? [] : ["first"], - static ( - context, - completed, - cancellation - ) => throw new Xunit.Sdk.XunitException("Input declaration must not compile."), - context => { - declarations++; - Assert.Equal(NativeLibraryKind.Shared, context.RequireComponentOptions(owner).libraryKind); - return new NativeBuildRecipe(owner, id, context.RequireToolchain().targetId, - [NativeBuildInput.FromPath(m_root, "input.cpp")], ["selected=" + id]); - }, - static ( - relative, - target - ) => relative)); + steps.Add( + new ProductNativeBuildStep( + id, + owner, + new(NativeLibraryKind.Shared), + id == "first" ? [] : ["first"], + static ( + context, + completed, + cancellation + ) => throw new Xunit.Sdk.XunitException("Input declaration must not compile."), + context => + { + declarations++; + Assert.Equal(NativeLibraryKind.Shared, context.RequireComponentOptions(owner).libraryKind); + return new NativeBuildRecipe( + owner, + id, + context.RequireToolchain().targetId, + [NativeBuildInput.FromPath(m_root, "input.cpp")], + ["selected=" + id] + ); + }, + static ( + relative, + target + ) => relative + ) + ); } var plan = new ProductNativeBuildPlan("fixture", steps); IReadOnlyList recipes = plan.CreateRecipes(Context()); @@ -113,17 +138,27 @@ public void ProductSourceDeclarationUsesEachSelectedOwnerWithoutExecutingProduce [Fact] public void StandaloneStepsRejectMissingDeclarationsAndForeignRecipes() { - Assert.Throws(() => new ProductNativeBuildStep("fixture", m_owner, new(NativeLibraryKind.Shared), [], + Assert.Throws(() => new ProductNativeBuildStep( + "fixture", + m_owner, + new(NativeLibraryKind.Shared), + [], static ( context, completed, cancellation - ) => throw new Xunit.Sdk.XunitException("Validation must not compile."), null, + ) => throw new Xunit.Sdk.XunitException("Validation must not compile."), + null, static ( relative, target - ) => relative)); - var step = new ProductNativeBuildStep("fixture", m_owner, new(NativeLibraryKind.Shared), [], + ) => relative + )); + var step = new ProductNativeBuildStep( + "fixture", + m_owner, + new(NativeLibraryKind.Shared), + [], static ( context, completed, @@ -133,7 +168,8 @@ public void StandaloneStepsRejectMissingDeclarationsAndForeignRecipes() static ( relative, target - ) => relative); + ) => relative + ); Assert.Throws(() => new ProductNativeBuildPlan("fixture", [step]).CreateRecipes(Context())); } @@ -142,15 +178,19 @@ public async Task MissingGenerationPreventsPublicationBeforeProducerOrStaging() { NativeBuildContext context = Context(); bool produced = false; - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, Recipe(context), + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + Recipe(context), ( @scoped, output, cancellation - ) => { + ) => + { produced = true; return Task.CompletedTask; - })); + } + )); Assert.False(produced); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts"))); } @@ -180,16 +220,22 @@ CancellationToken cancellation File.WriteAllText(generated, "other"); File.SetLastWriteTimeUtc(generated, timestamp); } - using NativeBindingGenerationResult nextGeneration = Generation(changeBytes ? "generation-a" : "generation-b", - generated, Path.GetDirectoryName(bridge)!); + using NativeBindingGenerationResult nextGeneration = Generation( + changeBytes ? "generation-a" : "generation-b", + generated, + Path.GetDirectoryName(bridge)! + ); NativeBuildContext nextContext = Context().WithBindings(nextGeneration); using NativeBuildProduct next = await NativeArtifactPublisher.PublishAsync(nextContext, Recipe(nextContext), Produce); Assert.NotEqual(first.fingerprint, next.fingerprint); Assert.Equal(2, productions); Assert.Equal("first", File.ReadAllText(first.files[0])); Assert.Equal(changeBytes ? "other" : "first", File.ReadAllText(next.files[0])); - using NativeBindingGenerationResult hotGeneration = Generation(changeBytes ? "generation-a" : "generation-b", - generated, Path.GetDirectoryName(bridge)!); + using NativeBindingGenerationResult hotGeneration = Generation( + changeBytes ? "generation-a" : "generation-b", + generated, + Path.GetDirectoryName(bridge)! + ); NativeBuildContext hotContext = Context().WithBindings(hotGeneration); using NativeBuildProduct hot = await NativeArtifactPublisher.PublishAsync(hotContext, Recipe(hotContext), Produce); Assert.Equal(next.fingerprint, hot.fingerprint); @@ -199,22 +245,45 @@ CancellationToken cancellation public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } - private NativeBuildContext Context() => new NativeBuildContext(m_root, "release") - .WithToolchain(new NativeToolchainSelection("fixture-target", new BuildHostDescriptor("Windows", "x64"), - new Dictionary { ["compiler"] = Path.Combine(m_root, "tools", "compiler") }, - new Dictionary(), [], [], new NativeLinkPlan(".dll"), false)) - .WithComponentOptions(m_owner, new(NativeLibraryKind.Shared)); + private NativeBuildContext Context() + => new NativeBuildContext(m_root, "release") + .WithToolchain( + new NativeToolchainSelection( + "fixture-target", + new BuildHostDescriptor("Windows", "x64"), + new Dictionary { ["compiler"] = Path.Combine(m_root, "tools", "compiler") }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".dll"), + false + ) + ) + .WithComponentOptions(m_owner, new(NativeLibraryKind.Shared)); private NativeBuildRecipe Recipe(NativeBuildContext context) { - NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent(context, m_owner, "fixture", "fixture-target", - [Path.Combine(m_root, "input.cpp")], ["compiler-options"], [Path.Combine(m_root, "build", "Producer.cs")]); + NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent( + context, + m_owner, + "fixture", + "fixture-target", + [Path.Combine(m_root, "input.cpp")], + ["compiler-options"], + [Path.Combine(m_root, "build", "Producer.cs")] + ); foreach (NativeBuildInput input in recipe.inputs) + { if (!File.Exists(input.physicalPath) && !Directory.Exists(input.physicalPath)) + { Write(Path.GetRelativePath(m_root, input.physicalPath), "common executor"); + } + } return recipe; } @@ -223,18 +292,33 @@ private NativeBindingGenerationResult Generation( string generated, string bridge ) { - File.WriteAllText(Path.Combine(bridge, "compilation.json"), JsonSerializer.Serialize(new NativeBindingCompilation - { - roots = [new("generated", "", true, true)], files = [], includeDirectories = [], defines = [], compilerDefines = [], - cxxStandard = 0, cStandard = 0, requiredExports = [], staticExportSymbols = [], staticExportAbi = "", staticExportNames = [] - })); + File.WriteAllText( + Path.Combine(bridge, "compilation.json"), + JsonSerializer.Serialize(new NativeBindingCompilation + { + roots = [new("generated", "", true, true)], + files = [], + includeDirectories = [], + defines = [], + compilerDefines = [], + cxxStandard = 0, + cStandard = 0, + requiredExports = [], + staticExportSymbols = [], + staticExportAbi = "", + staticExportNames = [] + }) + ); return new(new Dictionary { [m_owner.nativeProject] = new() { - fingerprint = fingerprint, bindingsPath = generated, nativeDirectory = bridge, + fingerprint = fingerprint, + bindingsPath = generated, + nativeDirectory = bridge, usesRuntimeImports = false, - artifactDirectory = string.Empty, artifactOwnerDirectory = string.Empty + artifactDirectory = string.Empty, + artifactOwnerDirectory = string.Empty } }, []); } diff --git a/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs b/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs index ea8f308bd..b691bffe2 100644 --- a/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs +++ b/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs @@ -17,8 +17,12 @@ public void IntegrationsPreserveExactShaderAndNativeTargetIdentities() { Assert.Equal("windows-x64", WindowsX64BgfxIntegration.nativeProfile.targetId); Assert.Equal("macos-arm64", MacOSArm64BgfxIntegration.nativeProfile.targetId); - var context = new BuildCompositionContext("explicit-sdk", System.IO.Path.GetTempPath(), - new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64")); + var context = new BuildCompositionContext( + "explicit-sdk", + System.IO.Path.GetTempPath(), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetId("windows-x64") + ); var standard = StandardBuildDistribution.Create(context); Assert.Same(WindowsX64BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetId("windows-x64"))); Assert.Same(MacOSArm64BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetId("macos-arm64"))); diff --git a/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs b/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs index 43249737d..373c612a9 100644 --- a/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs +++ b/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs @@ -29,13 +29,20 @@ public void HostedTargetsCoverTheDistributionAndDeclareOneProducerHost() JsonElement[] targets = packages.RootElement.EnumerateArray().ToArray(); var runners = hosts.RootElement.EnumerateArray().ToDictionary(host => host.GetProperty("runner").GetString()!); var distribution = BuildTestProducts.Distribution(); - Assert.Equal(distribution.availableTargets.Select(id => id.value), targets.Select(target => target.GetProperty("target").GetString()).Order(StringComparer.Ordinal)); + Assert.Equal( + distribution.availableTargets.Select(id => id.value), + targets.Select(target => target.GetProperty("target").GetString()).Order(StringComparer.Ordinal) + ); Assert.All(targets, target => { string runner = target.GetProperty("runner").GetString()!; string host = runners[runner].GetProperty("target").GetString()!; - Assert.Single(targets.Where(candidate => candidate.GetProperty("target").GetString() == host - && candidate.GetProperty("runner").GetString() == runner)); + Assert.Single( + targets.Where(candidate => ( + candidate.GetProperty("target").GetString() == host + && candidate.GetProperty("runner").GetString() == runner + )) + ); Assert.NotEmpty(target.GetProperty("configurations").EnumerateArray()); }); } @@ -52,8 +59,12 @@ public void SharedBackendSourcesKeepDistinctRuntimeBindingAndOfflineToolOwners(s Assert.NotEqual(runtime.id, tools.id); Assert.NotNull(runtime.bindingDefinition); Assert.Null(tools.bindingDefinition); - Assert.Single(editor.steps.Where(step => step.component.id == runtime.id - && step.component.nativeProject == runtime.nativeProject)); + Assert.Single( + editor.steps.Where(step => ( + step.component.id == runtime.id + && step.component.nativeProject == runtime.nativeProject + )) + ); } [Theory] @@ -63,19 +74,36 @@ public async Task RealPlatformPreflightRejectsUnavailableSdkOrHostWithoutCreatin { string output = Path.Combine(Path.GetTempPath(), "InnoPlatformPreflight", Guid.NewGuid().ToString("N")); string sdk = Path.Combine(output, "unavailable-dotnet.exe"); - var host = unsupportedHost ? new BuildHostDescriptor("MacOS", "arm64") - : new BuildHostDescriptor("Windows", "x64"); + var host = unsupportedHost + ? new BuildHostDescriptor("MacOS", "arm64") + : new BuildHostDescriptor("Windows", "x64"); var source = new WindowsX64PlayerSupportPackSource( BuildTestProducts.Distribution().ResolveNativeProduct("windows-x64", "player"), - host, sdk, BuildTestProducts.Distribution().ResolveBindingGenerator("windows-x64"), new WindowsX64SupportPackValidator()); + host, + sdk, + BuildTestProducts.Distribution().ResolveBindingGenerator("windows-x64"), + new WindowsX64SupportPackValidator() + ); var publisher = new PlayerSupportPackPublisher([source]); if (unsupportedHost) + { await Assert.ThrowsAsync(() => publisher.PublishAsync( - TestRepository.GetRoot(typeof(PlatformOwnershipContractTests).Assembly), output, new BuildTargetId("windows-x64"), sdk).AsTask()); + TestRepository.GetRoot(typeof(PlatformOwnershipContractTests).Assembly), + output, + new BuildTargetId("windows-x64"), + sdk + ).AsTask()); + } else + { await Assert.ThrowsAsync(() => publisher.PublishAsync( - TestRepository.GetRoot(typeof(PlatformOwnershipContractTests).Assembly), output, new BuildTargetId("windows-x64"), sdk).AsTask()); + TestRepository.GetRoot(typeof(PlatformOwnershipContractTests).Assembly), + output, + new BuildTargetId("windows-x64"), + sdk + ).AsTask()); + } Assert.False(Directory.Exists(output)); } @@ -85,26 +113,40 @@ public void StaticComponentsHaveOneAggregateOwnerAndNoUnusedStandaloneProducer() { ProductNativeBuildPlan plan = BuildTestProducts.StaticPlayer(); - Assert.All(plan.steps, static step => { + Assert.All(plan.steps, static step => + { Assert.Null(step.build); Assert.NotNull(step.component.staticBuild); }); - Assert.Throws(() => new ProductNativeBuildStep("fixture", Step("fixture", []).component, new(NativeLibraryKind.Static), - [], null, null, static ( + Assert.Throws(() => new ProductNativeBuildStep( + "fixture", + Step("fixture", []).component, + new(NativeLibraryKind.Static), + [], + null, + null, + static ( relative, target - ) => relative)); + ) => relative + )); } [Fact] public void StandardShaderTargetIsIndependentOfTheOfflineToolTarget() { - var context = new BuildCompositionContext("unresolved-sdk", Path.GetFullPath(Path.GetTempPath()), - new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64")); + var context = new BuildCompositionContext( + "unresolved-sdk", + Path.GetFullPath(Path.GetTempPath()), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetId("windows-x64") + ); StandardBuildDistribution distribution = StandardBuildDistribution.Create(context); - Assert.Same(BrowserWasm32BgfxShaderProfiles.target, - distribution.ResolveShaderTarget(new BuildTargetId("browser-wasm"))); + Assert.Same( + BrowserWasm32BgfxShaderProfiles.target, + distribution.ResolveShaderTarget(new BuildTargetId("browser-wasm")) + ); Assert.Throws(() => distribution.build.ResolveNativeProduct("linux-arm64", "shader-tools")); Assert.Throws(() => distribution.ResolveShaderTarget(new("unregistered-target"))); Assert.Throws(() => distribution.build.ResolveNativeProduct("browser-wasm", "shader-tools")); @@ -113,18 +155,28 @@ public void StandardShaderTargetIsIndependentOfTheOfflineToolTarget() [Fact] public void DistributionDoesNotDeriveProductTargetsFromTheToolHost() { - var windows = new BuildCompositionContext("unresolved-sdk", Path.GetFullPath(Path.GetTempPath()), - new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64")); - var apple = new BuildCompositionContext("unresolved-sdk", Path.GetFullPath(Path.GetTempPath()), - new BuildHostDescriptor("MacOS", "arm64"), new BuildTargetId("macos-arm64")); + var windows = new BuildCompositionContext( + "unresolved-sdk", + Path.GetFullPath(Path.GetTempPath()), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetId("windows-x64") + ); + var apple = new BuildCompositionContext( + "unresolved-sdk", + Path.GetFullPath(Path.GetTempPath()), + new BuildHostDescriptor("MacOS", "arm64"), + new BuildTargetId("macos-arm64") + ); BuildDistribution first = StandardBuildDistribution.Create(windows).build; BuildDistribution second = StandardBuildDistribution.Create(apple).build; Assert.Equal(first.availableTargets, second.availableTargets); Assert.Contains(new BuildTargetId("browser-wasm"), first.availableTargets); ProductNativeBuildPlan browser = first.ResolveNativeProduct("browser-wasm", "player").plan; - Assert.Equal(browser.steps.Select(static step => step.component.id), - second.ResolveNativeProduct("browser-wasm", "player").plan.steps.Select(static step => step.component.id)); + Assert.Equal( + browser.steps.Select(static step => step.component.id), + second.ResolveNativeProduct("browser-wasm", "player").plan.steps.Select(static step => step.component.id) + ); Assert.All(browser.steps, static step => { Assert.Equal(NativeLibraryKind.Static, step.options.libraryKind); @@ -157,8 +209,8 @@ string target var context = new NativeBuildContext(root, "debug"); var host = new BuildHostDescriptor(system, architecture); INativeToolchainProvider provider = target == "macos-arm64" - ? new MacOSArm64NativeToolchainProvider("deliberately-unavailable-sdk") - : new WindowsX64NativeToolchainProvider("deliberately-unavailable-sdk"); + ? new MacOSArm64NativeToolchainProvider("deliberately-unavailable-sdk") + : new WindowsX64NativeToolchainProvider("deliberately-unavailable-sdk"); await Assert.ThrowsAsync(() => provider.ResolveAsync(context, host, target, CancellationToken.None).AsTask()); @@ -196,10 +248,14 @@ public async Task UnselectedToolchainAndCancellationNeverRunAComponentProducer() { var context = new NativeBuildContext(root, "debug"); var plan = new ProductNativeBuildPlan("fixture-product", [Step("first", [])]); - await Assert.ThrowsAsync(() => new ComponentNativeProductExecutor().BuildAsync(context, plan, CancellationToken.None)); + await Assert.ThrowsAsync( + () => new ComponentNativeProductExecutor().BuildAsync(context, plan, CancellationToken.None) + ); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - await Assert.ThrowsAnyAsync(() => new ComponentNativeProductExecutor().BuildAsync(context, plan, cancellation.Token)); + await Assert.ThrowsAnyAsync( + () => new ComponentNativeProductExecutor().BuildAsync(context, plan, cancellation.Token) + ); Assert.False(Directory.Exists(Path.Combine(root, "artifacts"))); } finally @@ -211,9 +267,15 @@ public async Task UnselectedToolchainAndCancellationNeverRunAComponentProducer() private static ProductNativeBuildStep Step( string id, string[] dependencies - ) => new(id, new NativeComponentDescriptor(id, - "backends/Fixture/native/Inno.Native.Fixture/Inno.Native.Fixture.csproj", - "backends/Fixture/build/Inno.Build.Toolchains.Fixture/Inno.Build.Toolchains.Fixture.csproj"), new(NativeLibraryKind.Shared), dependencies, + ) => new( + id, + new NativeComponentDescriptor( + id, + "backends/Fixture/native/Inno.Native.Fixture/Inno.Native.Fixture.csproj", + "backends/Fixture/build/Inno.Build.Toolchains.Fixture/Inno.Build.Toolchains.Fixture.csproj" + ), + new(NativeLibraryKind.Shared), + dependencies, static ( context, completed, @@ -223,5 +285,6 @@ string[] dependencies static ( relative, target - ) => relative); + ) => relative + ); } diff --git a/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs b/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs index e25ce32e4..c2865d475 100644 --- a/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs +++ b/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs @@ -3,14 +3,14 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Assets.Pipeline; -using Inno.Build.Toolchains; using Inno.Build.Distribution.Standard; +using Inno.Build.Toolchains; using Inno.Build.Toolchains.Bgfx.Shaders; using Inno.Core.IO; using Inno.Integration.WindowsX64.Bgfx; using Inno.Rendering; -using Xunit; namespace Inno.Build.Products.Tests; @@ -109,7 +109,13 @@ public async Task FailedImportDoesNotWriteTheAuthoringTreeOrReplaceAnExistingArt ShaderBuildInputs inputs = ShaderBuildInputs.Capture(sources); using ProcessOwnedDirectory compilation = await ProcessOwnedDirectory.CreateAsync(Path.Combine(m_root, "requests")); Assert.Throws(() => ShaderArtifactBuilder.CompileGraphicsProgram( - inputs, compilation, "invalid.ishader", WindowsX64BgfxIntegration.shaderProfile, GraphicsApi.Direct3D12, output)); + inputs, + compilation, + "invalid.ishader", + WindowsX64BgfxIntegration.shaderProfile, + GraphicsApi.Direct3D12, + output + )); Assert.Equal(original, Directory.GetFiles(sources)); Assert.Equal(bytes, File.ReadAllBytes(original.Single())); Assert.Equal("last good artifact", File.ReadAllText(output)); @@ -127,8 +133,14 @@ public async Task CancellationCannotPublishAnArtifact() File.WriteAllText(output, "last good artifact"); using ProcessOwnedDirectory compilation = await ProcessOwnedDirectory.CreateAsync(Path.Combine(m_root, "requests")); Assert.Throws(() => ShaderArtifactBuilder.CompileGraphicsProgram( - inputs, compilation, "graph.ishader", WindowsX64BgfxIntegration.shaderProfile, GraphicsApi.Direct3D12, output, - cancellationToken: canceled.Token)); + inputs, + compilation, + "graph.ishader", + WindowsX64BgfxIntegration.shaderProfile, + GraphicsApi.Direct3D12, + output, + cancellationToken: canceled.Token + )); Assert.Equal("last good artifact", File.ReadAllText(output)); } diff --git a/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs b/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs index b8f6c5ec4..7d18c6015 100644 --- a/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs +++ b/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs @@ -20,21 +20,49 @@ public void OfflineToolsExcludeCmakeWhileRuntimeBindingsKeepTheSelectedSdk() string owner = Path.Combine(root, "platforms", "WindowsX64", "integrations", "Inno.Integration.WindowsX64.Bgfx"); Directory.CreateDirectory(owner); foreach (string file in new[] { "WindowsX64BgfxToolContribution.cs", "WindowsX64BgfxBuildProfile.cs" }) + { File.WriteAllText(Path.Combine(owner, file), "declared integration input"); + } var tools = new Dictionary(); foreach (string name in new[] { "cl", "msbuild", "genie", "cmake", "dotnet" }) { tools[name] = Path.Combine(root, name + ".exe"); File.WriteAllText(tools[name], "frozen executable input"); } - var sdk = new NativeToolchainSelection("windows-x64", new BuildHostDescriptor("Windows", "x64"), - tools, new Dictionary(), [], ["-G", "Fixture"], new NativeLinkPlan(".dll"), true); - NativeToolchainSelection first = WindowsX64BgfxIntegration.nativeProfile.SelectTools(new NativeBuildContext(root, "release").WithToolchain(sdk), true); - NativeToolchainSelection runtime = WindowsX64BgfxIntegration.nativeProfile.SelectTools(new NativeBuildContext(root, "release").WithToolchain(sdk), false); + var sdk = new NativeToolchainSelection( + "windows-x64", + new BuildHostDescriptor("Windows", "x64"), + tools, + new Dictionary(), + [], + ["-G", "Fixture"], + new NativeLinkPlan(".dll"), + true + ); + NativeToolchainSelection first = WindowsX64BgfxIntegration.nativeProfile.SelectTools( + new NativeBuildContext(root, "release").WithToolchain(sdk), + true + ); + NativeToolchainSelection runtime = WindowsX64BgfxIntegration.nativeProfile.SelectTools( + new NativeBuildContext(root, "release").WithToolchain(sdk), + false + ); tools["dotnet"] = Path.Combine(root, "another-dotnet.exe"); File.WriteAllText(tools["dotnet"], "another managed SDK"); - var otherSdk = new NativeToolchainSelection("windows-x64", sdk.host, tools, sdk.environment, [], sdk.cmakeArguments, new NativeLinkPlan(".dll"), true); - NativeToolchainSelection second = WindowsX64BgfxIntegration.nativeProfile.SelectTools(new NativeBuildContext(root, "release").WithToolchain(otherSdk), true); + var otherSdk = new NativeToolchainSelection( + "windows-x64", + sdk.host, + tools, + sdk.environment, + [], + sdk.cmakeArguments, + new NativeLinkPlan(".dll"), + true + ); + NativeToolchainSelection second = WindowsX64BgfxIntegration.nativeProfile.SelectTools( + new NativeBuildContext(root, "release").WithToolchain(otherSdk), + true + ); Assert.Equal(first.declarations, second.declarations); Assert.Equal(first.inputPaths, second.inputPaths); diff --git a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackClosureValidationTests.cs b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackClosureValidationTests.cs index 91ec81caf..40579a142 100644 --- a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackClosureValidationTests.cs +++ b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackClosureValidationTests.cs @@ -1,8 +1,8 @@ using System; using System.IO; using System.Text; -using Inno.Build.SupportPacks; using Xunit; +using Inno.Build.SupportPacks; namespace Inno.Build.SupportPacks.Tests; @@ -15,8 +15,13 @@ public void ACustomBackendUsesItsDeclaredGroupWithoutStandardLibraryNames() { Write("PlayerLink/References/Custom.Runtime.dll"); Write("native/custom/fixture-target/arbitrary-name.fixture"); - var requirements = new PlayerSupportPackRequirements(new("fixture-target"), - ["PlayerLink/References/Custom.Runtime.dll"], "native", ["custom/fixture-target"], ".fixture"); + var requirements = new PlayerSupportPackRequirements( + new("fixture-target"), + ["PlayerLink/References/Custom.Runtime.dll"], + "native", + ["custom/fixture-target"], + ".fixture" + ); var validator = new PlayerSupportPackClosureValidator(requirements, new LayoutValidator(), null); validator.Validate(m_root); Write("native/unselected/fixture-target/another.fixture"); @@ -27,8 +32,13 @@ public void ACustomBackendUsesItsDeclaredGroupWithoutStandardLibraryNames() public void MissingDeclaredArchiveFailsEvenWhenItsGroupContainsAnotherArchive() { Write("PlayerLink/Native/custom/fixture-target/other.a"); - var requirements = new PlayerSupportPackRequirements(new("fixture-target"), - ["PlayerLink/Native/custom/fixture-target/required.a"], "PlayerLink/Native", ["custom/fixture-target"], ".a"); + var requirements = new PlayerSupportPackRequirements( + new("fixture-target"), + ["PlayerLink/Native/custom/fixture-target/required.a"], + "PlayerLink/Native", + ["custom/fixture-target"], + ".a" + ); var validator = new PlayerSupportPackClosureValidator(requirements, new LayoutValidator(), null); InvalidDataException missing = Assert.Throws(() => validator.Validate(m_root)); Assert.Contains("required.a", missing.Message); @@ -40,9 +50,14 @@ public void MissingDeclaredArchiveFailsEvenWhenItsGroupContainsAnotherArchive() public void StaticClosureRejectsAnAdditionalArchive(string extra) { Write("PlayerLink/Native/custom/fixture-target/required.a"); - var requirements = new PlayerSupportPackRequirements(new("fixture-target"), - ["PlayerLink/Native/custom/fixture-target/required.a"], "PlayerLink/Native", - ["custom/fixture-target"], ".a", ["custom/fixture-target/required.a"]); + var requirements = new PlayerSupportPackRequirements( + new("fixture-target"), + ["PlayerLink/Native/custom/fixture-target/required.a"], + "PlayerLink/Native", + ["custom/fixture-target"], + ".a", + ["custom/fixture-target/required.a"] + ); var validator = new PlayerSupportPackClosureValidator(requirements, new LayoutValidator(), null); validator.Validate(m_root); Write("PlayerLink/Native/" + extra); @@ -54,13 +69,20 @@ public void StaticClosureRejectsAnAdditionalArchive(string extra) [InlineData("native/../outside")] [InlineData("C:/outside")] public void RequirementPathsCannotEscapeTheirOwner(string path) - => Assert.Throws(() => new PlayerSupportPackRequirements(new("fixture-target"), - [path], "native", ["custom"], ".fixture")); + => Assert.Throws(() => new PlayerSupportPackRequirements( + new("fixture-target"), + [path], + "native", + ["custom"], + ".fixture" + )); public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private void Write(string relative) diff --git a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPreparationCacheTests.cs b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPreparationCacheTests.cs index 1f2eec3bd..d7382a200 100644 --- a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPreparationCacheTests.cs +++ b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPreparationCacheTests.cs @@ -1,13 +1,13 @@ using System; using System.IO; -using System.Runtime.Versioning; using System.Linq; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.SupportPacks; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.SupportPacks.Tests; @@ -32,12 +32,16 @@ public async Task IdenticalPreparationSkipsProducerAndDamagedOutputsRequireRepai var publisher = new PlayerSupportPackPublisher([m_source]); string directory; using (PlayerSupportPackPublication first = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + { directory = first.directory; + } string current = Path.Combine(output, S_TARGET.value, "current"); File.SetLastWriteTimeUtc(current, DateTime.UtcNow.AddDays(-1)); DateTime selectedAt = File.GetLastWriteTimeUtc(current); using (PlayerSupportPackPublication repeated = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + { Assert.Equal(directory, repeated.directory); + } Assert.Equal(selectedAt, File.GetLastWriteTimeUtc(current)); Assert.Equal(1, m_source.preparations); string file = Path.Combine(directory, "References", "Inno.Fixture.dll"); @@ -45,11 +49,15 @@ public async Task IdenticalPreparationSkipsProducerAndDamagedOutputsRequireRepai File.WriteAllText(file, "other"); File.SetLastWriteTimeUtc(file, timestamp); using (PlayerSupportPackPublication repaired = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + { Assert.Equal("first", File.ReadAllText(Path.Combine(repaired.directory, "References", "Inno.Fixture.dll"))); + } Assert.Equal(2, m_source.preparations); File.WriteAllText(Path.Combine(directory, "References", "Extra.dll"), "extra"); using (PlayerSupportPackPublication repaired = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + { Assert.Single(Directory.EnumerateFiles(Path.Combine(repaired.directory, "References"))); + } Assert.Equal(3, m_source.preparations); Assert.Empty(Directory.EnumerateDirectories(output, ".support-pack-*")); } @@ -61,16 +69,24 @@ public async Task RetiringAnOldPackAlsoRetiresItsPreparationIndex() var publisher = new PlayerSupportPackPublisher([m_source]); string previous; using (PlayerSupportPackPublication first = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + { previous = first.directory; + } string indexes = Path.Combine(output, S_TARGET.value, ".preparations"); string oldIndex = Assert.Single(Directory.GetFiles(indexes)); File.WriteAllText(Path.Combine(m_root, "input.txt"), "changed"); string current; using (PlayerSupportPackPublication second = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + { current = second.directory; + } - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, - [new BuildCachePublisher(output, BuildCacheArtifactRole.ImmutableArtifact).Describe("packs")], new(), retireAll: true); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + m_root, + [new BuildCachePublisher(output, BuildCacheArtifactRole.ImmutableArtifact).Describe("packs")], + new(), + retireAll: true + ); Assert.Empty((await plan.ExecuteAsync()).failures); Assert.False(Directory.Exists(previous)); Assert.False(File.Exists(oldIndex)); @@ -83,8 +99,10 @@ public async Task ConcurrentIdenticalRequestsPrepareOnlyOneCandidate() { string output = Path.Combine(m_root, "Packs"); var publisher = new PlayerSupportPackPublisher([m_source]); - PlayerSupportPackPublication[] readers = await Task.WhenAll(Enumerable.Range(0, 4) - .Select(_ => publisher.PublishAsync(m_root, output, S_TARGET, "unused").AsTask())); + PlayerSupportPackPublication[] readers = await Task.WhenAll( + Enumerable.Range(0, 4) + .Select(_ => publisher.PublishAsync(m_root, output, S_TARGET, "unused").AsTask()) + ); try { Assert.All(readers, reader => Assert.Equal(readers[0].directory, reader.directory)); @@ -93,7 +111,9 @@ public async Task ConcurrentIdenticalRequestsPrepareOnlyOneCandidate() finally { foreach (PlayerSupportPackPublication reader in readers) + { reader.Dispose(); + } } } @@ -123,7 +143,9 @@ public async Task PreparationIndexFailureReportsCommittedPublicationWithoutThrow string output = Path.Combine(m_root, "Packs"); var publisher = new PlayerSupportPackPublisher([m_source]); using (PlayerSupportPackPublication first = await publisher.PublishAsync(m_root, output, S_TARGET, "unused")) + { Assert.Empty(first.diagnostics); + } string current = Path.Combine(output, S_TARGET.value, "current"); string previous = File.ReadAllText(current); File.WriteAllText(Path.Combine(m_root, "input.txt"), "other"); @@ -146,7 +168,9 @@ public async Task PreparationIndexFailureReportsCommittedPublicationWithoutThrow public async Task PostCommitStagingCleanupFailurePreservesReadingOwnership() { if (!OperatingSystem.IsWindows()) + { return; + } string output = Path.Combine(m_root, "Packs"); FileStream? blocker = null; m_source.onPrepared = staging => @@ -223,12 +247,15 @@ private sealed class Plan( Source owner, string identity, string content - ) : PlayerSupportPackPlan(S_TARGET, identity) { + ) : PlayerSupportPackPlan(S_TARGET, identity) + { public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (owner.Identity() != preparationIdentity) + { throw new InvalidOperationException("Fixture source input changed after planning."); + } return ValueTask.CompletedTask; } diff --git a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs index 455eb1a72..cf6318dc6 100644 --- a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs +++ b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs @@ -3,8 +3,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Build.SupportPacks; using Xunit; +using Inno.Build.SupportPacks; namespace Inno.Build.SupportPacks.Tests; @@ -24,7 +24,13 @@ public SupportPackPublisherTests() [Fact] public async Task SourceProvisioningRetainsConsumeOnlySelectionBeforePublication() { - string declaration = Path.Combine(m_root, "build", "distributions", "Inno.Build.Distribution.Standard", "Inno.Build.Distribution.Standard.csproj"); + string declaration = Path.Combine( + m_root, + "build", + "distributions", + "Inno.Build.Distribution.Standard", + "Inno.Build.Distribution.Standard.csproj" + ); Directory.CreateDirectory(Path.GetDirectoryName(declaration)!); File.WriteAllText(declaration, ""); string selection = Path.Combine(m_root, "selection.json"); @@ -33,13 +39,19 @@ public async Task SourceProvisioningRetainsConsumeOnlySelectionBeforePublication var source = new PlanningSource(( context, token - ) => { + ) => + { attempts++; Assert.Equal(selection, context.nativeDependencies); throw new FileNotFoundException("The selected dependency package is unavailable."); }); - var provisioner = new SourcePlayerSupportPackProvisioner(m_root, new PlayerSupportPackPublisher([source]), - "unused", static diagnostic => throw new InvalidOperationException(diagnostic), selection); + var provisioner = new SourcePlayerSupportPackProvisioner( + m_root, + new PlayerSupportPackPublisher([source]), + "unused", + static diagnostic => throw new InvalidOperationException(diagnostic), + selection + ); await Assert.ThrowsAsync(() => provisioner.ProvisionAsync(S_TARGET, output).AsTask()); @@ -57,19 +69,25 @@ public async Task PreflightFailuresLeaveNoPublicationDirectory(string failure) var source = new PlanningSource(( context, token - ) => { + ) => + { Assert.False(Directory.Exists(output)); if (failure == "missing-sdk") + { throw new FileNotFoundException("The selected SDK is absent."); - return ValueTask.FromResult(failure == "null-plan" - ? null! : new ForeignPlan()); + } + return ValueTask.FromResult(failure == "null-plan" ? null! : new ForeignPlan()); }); var publisher = new PlayerSupportPackPublisher([source]); if (failure == "missing-sdk") + { await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, S_TARGET, "unused").AsTask()); + } else + { await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, S_TARGET, "unused").AsTask()); + } Assert.False(Directory.Exists(output)); } @@ -81,13 +99,15 @@ public async Task CancellationDuringPlanningLeavesNoOutputAndExecutesNoPlan() var source = new PlanningSource(( context, token - ) => { + ) => + { cancellation.Cancel(); return ValueTask.FromResult(new ForeignPlan(S_TARGET)); }); await Assert.ThrowsAnyAsync(() => new PlayerSupportPackPublisher([source]) - .PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token).AsTask()); + .PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token) + .AsTask()); Assert.False(Directory.Exists(output)); } @@ -100,13 +120,19 @@ public async Task PreparedPlanIsExecutedOnceWithoutRepeatingDiscovery() var source = new PlanningSource(async ( context, token - ) => { + ) => + { Assert.False(Directory.Exists(output)); planningCount++; return await new TestSource(null, payload: "frozen").CreatePlanAsync(context, token); }); - using PlayerSupportPackPublication installedLease = await new PlayerSupportPackPublisher([source]).PublishAsync(m_root, output, S_TARGET, "unused"); + using PlayerSupportPackPublication installedLease = await new PlayerSupportPackPublisher([source]).PublishAsync( + m_root, + output, + S_TARGET, + "unused" + ); string installed = installedLease.directory; Assert.Equal(1, planningCount); @@ -117,7 +143,12 @@ public async Task PreparedPlanIsExecutedOnceWithoutRepeatingDiscovery() public async Task RegisteredCustomTargetInstallsWithoutCorePlatformBranches() { var publisher = new PlayerSupportPackPublisher([new TestSource(null)]); - using PlayerSupportPackPublication installedLease = await publisher.PublishAsync(m_root, Path.Combine(m_root, "Packs"), S_TARGET, "unused"); + using PlayerSupportPackPublication installedLease = await publisher.PublishAsync( + m_root, + Path.Combine(m_root, "Packs"), + S_TARGET, + "unused" + ); string installed = installedLease.directory; Assert.True(File.Exists(Path.Combine(installed, "References", "Inno.Test.dll"))); Assert.Single(Directory.EnumerateDirectories(Path.Combine(m_root, "Packs"))); @@ -128,7 +159,11 @@ public async Task FailedPreparationPreservesInstalledPackAndRemovesStaging() { string output = Path.Combine(m_root, "Packs"); using PlayerSupportPackPublication installedLease = await new PlayerSupportPackPublisher([new TestSource(null)]).PublishAsync( - m_root, output, S_TARGET, "unused"); + m_root, + output, + S_TARGET, + "unused" + ); string installed = installedLease.directory; var publisher = new PlayerSupportPackPublisher([new TestSource(new InvalidDataException("invalid candidate"))]); await Assert.ThrowsAsync(() => publisher.PublishAsync(m_root, output, S_TARGET, "unused").AsTask()); @@ -144,7 +179,8 @@ public async Task CancellationRejectsCandidateBeforeInstallation() var publisher = new PlayerSupportPackPublisher([new TestSource(null)]); string output = Path.Combine(m_root, "Packs"); await Assert.ThrowsAnyAsync( - () => publisher.PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token).AsTask()); + () => publisher.PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token).AsTask() + ); Assert.False(Directory.Exists(output)); } @@ -158,12 +194,17 @@ public async Task CancellationDuringValidationPreservesTheInstalledPack() using var cancellation = new CancellationTokenSource(); string output = Path.Combine(m_root, "Packs"); using PlayerSupportPackPublication installedLease = await new PlayerSupportPackPublisher([new TestSource(null)]).PublishAsync( - m_root, output, S_TARGET, "unused"); + m_root, + output, + S_TARGET, + "unused" + ); string installed = installedLease.directory; var publisher = new PlayerSupportPackPublisher([new TestSource(null, cancellation.Cancel)]); await Assert.ThrowsAnyAsync( - () => publisher.PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token).AsTask()); + () => publisher.PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token).AsTask() + ); Assert.Equal("candidate", File.ReadAllText(Path.Combine(installed, "References", "Inno.Test.dll"))); Assert.Single(Directory.EnumerateDirectories(output)); @@ -174,12 +215,17 @@ public async Task NewPublicationRetainsTheImmutableInputsHeldByEarlierReaders() { string output = Path.Combine(m_root, "Packs"); using PlayerSupportPackPublication previousLease = await new PlayerSupportPackPublisher([new TestSource(null)]).PublishAsync( - m_root, output, S_TARGET, "unused"); + m_root, + output, + S_TARGET, + "unused" + ); string previous = previousLease.directory; using FileStream reader = File.OpenRead(Path.Combine(previous, "References", "Inno.Test.dll")); - using PlayerSupportPackPublication currentLease = await new PlayerSupportPackPublisher([new TestSource(null, payload: "updated")]).PublishAsync( - m_root, output, S_TARGET, "unused"); + using PlayerSupportPackPublication currentLease = await new PlayerSupportPackPublisher( + [new TestSource(null, payload: "updated")] + ).PublishAsync(m_root, output, S_TARGET, "unused"); string current = currentLease.directory; Assert.NotEqual(previous, current); @@ -200,8 +246,10 @@ public async Task IdenticalPublicationReusesTheExistingImmutableDirectory() using PlayerSupportPackPublication second = await publisher.PublishAsync(m_root, output, S_TARGET, "unused"); Assert.Equal(first, second.directory); - Assert.Single(Directory.EnumerateDirectories(Path.Combine(output, S_TARGET.value)) - .Where(static directory => Path.GetFileName(directory) != ".preparations")); + Assert.Single( + Directory.EnumerateDirectories(Path.Combine(output, S_TARGET.value)) + .Where(static directory => Path.GetFileName(directory) != ".preparations") + ); Assert.Empty(Directory.EnumerateDirectories(output, ".support-pack-*")); } @@ -217,7 +265,12 @@ public async Task DamagedInstalledArtifactCannotBeSilentlyReplacedWhileReadersHo using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(150)); await Assert.ThrowsAnyAsync(() => publisher.PublishAsync( - m_root, output, S_TARGET, "unused", cancellation.Token).AsTask()); + m_root, + output, + S_TARGET, + "unused", + cancellation.Token + ).AsTask()); Assert.Equal("changed externally", File.ReadAllText(file)); Assert.Throws(() => new PlayerSupportPackCatalog(output).Acquire(S_TARGET, new TestSource(null))); @@ -257,12 +310,14 @@ public async Task WaitingWriterCanCancelWithoutEnteringPreparationOrDisturbingTh Assert.Empty(Directory.EnumerateDirectories(output, ".support-pack-*")); } - private static string InputIdentity(string input) => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(input))); + private static string InputIdentity(string input) + => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(input))); private sealed class PendingSource( TaskCompletionSource entered, TaskCompletionSource release - ) : IPlayerSupportPackSource { + ) : IPlayerSupportPackSource + { public BuildTargetId target => S_TARGET; public ValueTask CreatePlanAsync( @@ -275,7 +330,8 @@ CancellationToken cancellationToken private sealed class PendingPlan( TaskCompletionSource entered, TaskCompletionSource release - ) : PlayerSupportPackPlan(S_TARGET, InputIdentity("pending")) { + ) : PlayerSupportPackPlan(S_TARGET, InputIdentity("pending")) + { public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => ValueTask.CompletedTask; public override async ValueTask PrepareAsync( @@ -285,7 +341,9 @@ CancellationToken cancellationToken entered.SetResult(); await release.Task.WaitAsync(cancellationToken); PlayerSupportPackPlan plan = await new TestSource(null).CreatePlanAsync( - new PlayerSupportPackPlanningContext("unused", "unused"), cancellationToken); + new PlayerSupportPackPlanningContext("unused", "unused"), + cancellationToken + ); await plan.PrepareAsync(stagingDirectory, cancellationToken); } } @@ -295,7 +353,8 @@ CancellationToken cancellationToken private sealed class PlanningSource( Func> createPlan - ) : IPlayerSupportPackSource { + ) : IPlayerSupportPackSource + { public BuildTargetId target => S_TARGET; public ValueTask CreatePlanAsync( @@ -306,7 +365,10 @@ CancellationToken cancellationToken public void Validate(string directory) => new TestSource(null).Validate(directory); } - private sealed class ForeignPlan(BuildTargetId? target = null) : PlayerSupportPackPlan(target ?? new("foreign-target"), InputIdentity("foreign")) + private sealed class ForeignPlan(BuildTargetId? target = null) : PlayerSupportPackPlan( + target ?? new("foreign-target"), + InputIdentity("foreign") + ) { public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => ValueTask.CompletedTask; @@ -320,7 +382,8 @@ private sealed class TestSource( Exception? failure, Action? afterValidation = null, string payload = "candidate" - ) : IPlayerSupportPackSource { + ) : IPlayerSupportPackSource + { public BuildTargetId target => S_TARGET; public ValueTask CreatePlanAsync( @@ -331,7 +394,8 @@ CancellationToken cancellationToken private sealed class TestPlan( Exception? failure, string payload - ) : PlayerSupportPackPlan(S_TARGET, InputIdentity(payload + failure?.GetType().FullName)) { + ) : PlayerSupportPackPlan(S_TARGET, InputIdentity(payload + failure?.GetType().FullName)) + { public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => ValueTask.CompletedTask; public override ValueTask PrepareAsync( @@ -343,16 +407,19 @@ CancellationToken cancellationToken Directory.CreateDirectory(references); File.WriteAllText(Path.Combine(references, "Inno.Test.dll"), payload); if (failure is not null) + { throw failure; + } return ValueTask.CompletedTask; } - } public void Validate(string directory) { if (!File.Exists(Path.Combine(directory, "References", "Inno.Test.dll"))) + { throw new InvalidDataException("Candidate is incomplete."); + } afterValidation?.Invoke(); } } diff --git a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackWorkflowTests.cs b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackWorkflowTests.cs index 216bd040d..172937301 100644 --- a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackWorkflowTests.cs +++ b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackWorkflowTests.cs @@ -1,48 +1,40 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.IO.Compression; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; - +using Xunit; using Inno.Adapter.Content.FileSystem; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Build.Managed; -using Inno.Content; -using Inno.Core.IO; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.MacOSArm64; +using Inno.Build.Managed; using Inno.Build.WindowsX64; -using Inno.Core.Identity; +using Inno.Content; using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Types; - - - - using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; - -using Xunit; -using Inno.Build; using Inno.Testing.Build; namespace Inno.Build.SupportPacks.Tests; public sealed class SupportPackWorkflowTests : BuildPipelineFixture { - [Fact] public async Task UnknownManagedDeploymentNeverStartsSupportPackPreparation() { @@ -52,7 +44,9 @@ public async Task UnknownManagedDeploymentNeverStartsSupportPackPreparation() InvalidOperationException failure = await Assert.ThrowsAsync(() => pipeline.EnsurePlayerSupportPackAsync( - new BuildTargetId("windows-x64"), new ManagedDeploymentId("unregistered")).AsTask()); + new BuildTargetId("windows-x64"), + new ManagedDeploymentId("unregistered") + ).AsTask()); Assert.Contains("unregistered", failure.Message, StringComparison.Ordinal); Assert.Equal(0, provisioner.callCount); @@ -63,13 +57,14 @@ public async Task UnsupportedPlatformDeploymentPairNeverStartsSupportPackPrepara { var provisioner = new TestSupportPackProvisioner(_ => throw new InvalidOperationException("Unsupported platforms must not prepare a Pack.")); - var deployments = new ManagedDeploymentCatalog( - [new FixtureManagedDeploymentCompiler(["browser-wasm"])]); + var deployments = new ManagedDeploymentCatalog([new FixtureManagedDeploymentCompiler(["browser-wasm"])]); BuildPipeline pipeline = CreatePipeline(provisioner, deployments); InvalidOperationException failure = await Assert.ThrowsAsync(() => pipeline.EnsurePlayerSupportPackAsync( - new BuildTargetId("windows-x64"), ManagedDeploymentId.coreClr).AsTask()); + new BuildTargetId("windows-x64"), + ManagedDeploymentId.coreClr + ).AsTask()); Assert.Contains("win-x64", failure.Message, StringComparison.Ordinal); Assert.Equal(0, provisioner.callCount); @@ -80,11 +75,13 @@ public async Task MissingSupportPackIsPreparedBeforeTheOwnerThreadExport() { SaveStartupScene(); Directory.Delete(Path.Combine(m_supportPackRoot, new BuildTargetId("macos-arm64").value), recursive: true); - var provisioner = new TestSupportPackProvisioner(target => - CreateSupportPack(target, "Inno.Player.MacOSArm64")); + var provisioner = new TestSupportPackProvisioner(target => CreateSupportPack(target, "Inno.Player.MacOSArm64")); BuildPipeline pipeline = CreatePipeline(provisioner); - using PlayerSupportPackLease prepared = await pipeline.EnsurePlayerSupportPackAsync(new BuildTargetId("macos-arm64"), deployment: null); + using PlayerSupportPackLease prepared = await pipeline.EnsurePlayerSupportPackAsync( + new BuildTargetId("macos-arm64"), + deployment: null + ); BuildResult result = await pipeline.BuildGameAsync(new GameBuildRequest { profile = CreateProfile(new BuildTargetId("macos-arm64")), @@ -105,7 +102,10 @@ public async Task MissingPackFailsPromptlyWhileAsynchronousPreparationIsPending( var provisioner = new PendingSupportPackProvisioner(); BuildPipeline pipeline = CreatePipeline(provisioner); Task preparation = pipeline.EnsurePlayerSupportPackAsync( - new BuildTargetId("macos-arm64"), deployment: null, cancellation.Token).AsTask(); + new BuildTargetId("macos-arm64"), + deployment: null, + cancellation.Token + ).AsTask(); try { Assert.False(preparation.IsCompleted); @@ -131,10 +131,14 @@ public async Task MissingPackFailsPromptlyWhileAsynchronousPreparationIsPending( public async Task InvalidInstalledSupportPackDoesNotTriggerProvisioning() { SaveStartupScene(); - File.Delete(Path.Combine(GetSupportPackDirectory(new BuildTargetId("macos-arm64")), - "native", "libminiaudio-release.dylib")); - var provisioner = new TestSupportPackProvisioner(target => - CreateSupportPack(target, "Inno.Player.MacOSArm64")); + File.Delete( + Path.Combine( + GetSupportPackDirectory(new BuildTargetId("macos-arm64")), + "native", + "libminiaudio-release.dylib" + ) + ); + var provisioner = new TestSupportPackProvisioner(target => CreateSupportPack(target, "Inno.Player.MacOSArm64")); await Assert.ThrowsAsync(() => CreatePipeline(provisioner).BuildGameAsync(new GameBuildRequest diff --git a/tests/build/Inno.Build.Tests/BuildProfileTests.cs b/tests/build/Inno.Build.Tests/BuildProfileTests.cs index c400c98e2..e10ff6b7d 100644 --- a/tests/build/Inno.Build.Tests/BuildProfileTests.cs +++ b/tests/build/Inno.Build.Tests/BuildProfileTests.cs @@ -16,8 +16,11 @@ public sealed class BuildProfileTests : IDisposable public BuildProfileTests() { Directory.CreateDirectory(m_projectRoot); - m_engine = new EngineHostBuilder().UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(BuildProfile).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + m_engine = new EngineHostBuilder().UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(BuildProfile).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ).Build(); } public void Dispose() @@ -31,10 +34,12 @@ private static BuildProfile CreateProfile( string productName = "Test Game" ) => new() { - applicationId = "tests.game", productName = productName, startupScene = "Scenes/Startup.iscene", target = target + applicationId = "tests.game", + productName = productName, + startupScene = "Scenes/Startup.iscene", + target = target }; - [Theory] [InlineData("../other-game")] [InlineData("C:/absolute")] @@ -46,8 +51,6 @@ public void ProfileRejectsPersistentDataPathsOutsidePortableApplicationFolders(s Assert.Throws(profile.Validate); } - - [Theory] [InlineData("CON")] [InlineData("nul.txt")] @@ -61,8 +64,6 @@ public void BuildProfileRejectsNamesThatAreInvalidOnEitherTarget(string productN Assert.Throws(profile.Validate); } - - [Fact] public void BuildProfileStoreRoundTripsGeneratedCurrentFormat() { @@ -84,8 +85,6 @@ public void BuildProfileStoreRoundTripsGeneratedCurrentFormat() Assert.Equal(1080, restored.windowHeight); } - - [Fact] public void BuildProfileStorePreservesCommittedDocumentWhenCandidateIsInvalid() { @@ -102,8 +101,6 @@ public void BuildProfileStorePreservesCommittedDocumentWhenCandidateIsInvalid() Assert.Empty(Directory.EnumerateFiles(m_projectRoot, "BuildProfile.inno.staging-*")); } - - [Fact] public void BuildProfileStoreRejectsCorruptCurrentFormatWithoutFallback() { @@ -115,5 +112,4 @@ public void BuildProfileStoreRejectsCorruptCurrentFormatWithoutFallback() Assert.Contains("current-format", failure.Message, StringComparison.Ordinal); } - } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs index efd19a9d4..3aea40115 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs @@ -5,14 +5,19 @@ using System.Security.Cryptography; using System.Text.Json; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Build.Toolchains.Tests; public sealed class BackendPrebuiltArchiveTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoBackendPackages", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoBackendPackages", + Guid.NewGuid().ToString("N") + ); + private string Inventory => Path.Combine(m_root, "inventory.json"); private string Archive => Path.Combine(m_root, "platform.zip"); @@ -56,16 +61,27 @@ public async Task ChangedInputsAndExtraArchiveEntriesCannotReplaceCertifiedOutpu string output = Path.Combine(m_root, "consumer"); await Assert.ThrowsAsync(() => BackendPrebuiltArchive.ExtractAsync(Archive, digest, "other-target", output)); using (ZipArchive zip = ZipFile.Open(Archive, ZipArchiveMode.Update)) + { zip.CreateEntry("undeclared"); - await Assert.ThrowsAsync(() => BackendPrebuiltArchive.ExtractAsync(Archive, digest, "fixture-target", output)); - await Assert.ThrowsAsync(() => BackendPrebuiltArchive.ExtractAsync(Archive, Digest(Archive), "fixture-target", output)); + } + await Assert.ThrowsAsync( + () => BackendPrebuiltArchive.ExtractAsync(Archive, digest, "fixture-target", output) + ); + await Assert.ThrowsAsync( + () => BackendPrebuiltArchive.ExtractAsync(Archive, Digest(Archive), "fixture-target", output) + ); Assert.False(Directory.Exists(output)); } private void Select(string path) { string digest = Digest(Path.Combine(m_root, path)); - var inventory = new { version = 1, target = "fixture-target", files = new[] { new { owner = "Fixture", configuration = "Debug", input = digest, path, sha256 = digest } } }; + var inventory = new + { + version = 1, + target = "fixture-target", + files = new[] { new { owner = "Fixture", configuration = "Debug", input = digest, path, sha256 = digest } } + }; File.WriteAllBytes(Inventory, JsonSerializer.SerializeToUtf8Bytes(inventory)); } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs index 553fd5af0..84e353327 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs @@ -4,9 +4,9 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -76,7 +76,9 @@ public async Task ActiveReadersKeepTheirInventoryUntilRetirementActuallyComplete await PrepareAsync("first", "first payload"); await MaintainAsync(); string directory = Path.Combine(m_root, "cache", "first"); - string checkpoint = Assert.Single(Directory.GetFiles(Path.Combine(m_root, "artifacts", "cache-owners", "inventory"), "*.inventory")); + string checkpoint = Assert.Single( + Directory.GetFiles(Path.Combine(m_root, "artifacts", "cache-owners", "inventory"), "*.inventory") + ); using (FileLease reader = await FileLease.AcquireSharedAsync(directory + ".lock", TimeSpan.FromSeconds(5))) { await MaintainAsync(retireAll: true); @@ -93,7 +95,9 @@ public async Task InterruptedInventoryResumesCompletedShardsBeforeRetiringAnyArt { const int C_COUNT = 64; for (int index = 0; index < C_COUNT; index++) + { await PrepareAsync("shard-" + index.ToString("D3"), new string('x', 4096)); + } string directory = Path.Combine(m_root, "artifacts", "cache-owners", "inventory"); Directory.CreateDirectory(directory); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); @@ -118,8 +122,14 @@ public async Task InterruptedInventoryResumesCompletedShardsBeforeRetiringAnyArt { Assert.True(observing.Wait(TimeSpan.FromSeconds(30)), "The checkpoint observer did not start."); await Assert.ThrowsAnyAsync(() => Task.Run(() => - BuildMaintenanceApplication.CleanAsync(m_root, new(long.MaxValue, 0, TimeSpan.FromMinutes(2)), - true, false, null, cancellation.Token))); + BuildMaintenanceApplication.CleanAsync( + m_root, + new(long.MaxValue, 0, TimeSpan.FromMinutes(2)), + true, + false, + null, + cancellation.Token + ))); } finally { @@ -128,8 +138,14 @@ await Assert.ThrowsAnyAsync(() => Task.Run(() => } string[] completed = Directory.GetFiles(directory, "*.inventory"); Assert.NotEmpty(completed); - Assert.True(completed.Length < C_COUNT, "The first checkpoint must interrupt discovery before the complete protection graph exists."); - var snapshots = completed.ToDictionary(static path => path, static path => (File.ReadAllText(path), File.GetLastWriteTimeUtc(path))); + Assert.True( + completed.Length < C_COUNT, + "The first checkpoint must interrupt discovery before the complete protection graph exists." + ); + var snapshots = completed.ToDictionary( + static path => path, + static path => (File.ReadAllText(path), File.GetLastWriteTimeUtc(path)) + ); Assert.Equal(C_COUNT, Directory.GetDirectories(Path.Combine(m_root, "cache")).Length); await MaintainAsync(); Assert.Equal(C_COUNT, Directory.GetFiles(directory, "*.inventory").Length); @@ -143,8 +159,10 @@ await Assert.ThrowsAnyAsync(() => Task.Run(() => Assert.Empty(Directory.GetFiles(directory, "*.inventory")); } - private async Task PrepareAsync(string name, string content) - { + private async Task PrepareAsync( + string name, + string content + ) { string root = Path.Combine(m_root, "cache"); var publisher = new BuildCachePublisher(root, BuildCacheArtifactRole.ReusableWorkspace); BuildCacheOwnerCatalog.Register(m_root, root, "fixture", publisher.role); @@ -160,16 +178,26 @@ private Task MaintainAsync( bool retireAll = false ) { // Full inventory and retirement assertions are foreground work, not a five-second automatic maintenance slice. - return BuildMaintenanceApplication.CleanAsync(m_root, new(long.MaxValue, 0, TimeSpan.FromMinutes(2)), - retireAll, dryRun, null, CancellationToken.None); + return BuildMaintenanceApplication.CleanAsync( + m_root, + new(long.MaxValue, 0, TimeSpan.FromMinutes(2)), + retireAll, + dryRun, + null, + CancellationToken.None + ); } public void Dispose() { string parent = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "InnoInventoryProgress")) + Path.DirectorySeparatorChar; if (!Path.GetFullPath(m_root).StartsWith(parent, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidOperationException("The inventory fixture escaped its owner."); + } if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheMetadataRetirementTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheMetadataRetirementTests.cs index cd5f5b90e..2b726bbde 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheMetadataRetirementTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheMetadataRetirementTests.cs @@ -20,8 +20,14 @@ public async Task OwnerCatalogWaitParticipatesInTheCompleteMaintenanceBudget() string coordination = Path.Combine(m_root, "artifacts", "cache-owners", "owner.lock"); using FileLease writer = await FileLease.AcquireAsync(coordination, TimeSpan.FromSeconds(5)); Stopwatch elapsed = Stopwatch.StartNew(); - await Assert.ThrowsAsync(() => BuildMaintenanceApplication.CleanAsync(m_root, - new(timeBudget: TimeSpan.FromMilliseconds(100)), false, false, null, default)); + await Assert.ThrowsAsync(() => BuildMaintenanceApplication.CleanAsync( + m_root, + new(timeBudget: TimeSpan.FromMilliseconds(100)), + false, + false, + null, + default + )); Assert.True(elapsed.Elapsed < TimeSpan.FromSeconds(5)); } @@ -34,7 +40,9 @@ public async Task RetiredPublicationsReleaseTheirMetadataAndLeafWhilePreservingO Directory.CreateDirectory(Path.Combine(output, "Outputs")); File.WriteAllText(Path.Combine(output, "Outputs", "file"), "payload"); using (await publisher.AcquireUseAsync()) + { publisher.Record(output, output + ".read.lock", [], null, null); + } File.WriteAllText(Path.Combine(cache, "unknown.lock"), "user-owned"); BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [publisher.Describe("fixture")], new(0, 0), retireAll: true); Assert.Empty((await plan.ExecuteAsync()).failures); @@ -89,6 +97,8 @@ public async Task StableCurrentPointersAreNotRewrittenAndCorruptionIsReported() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheOwnerCatalogTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheOwnerCatalogTests.cs index 6fe60b130..a5cc29429 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheOwnerCatalogTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheOwnerCatalogTests.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -26,7 +26,9 @@ public async Task MaintenanceUsesPublisherInventoryWithoutAdoptingUnrecordedDire File.WriteAllText(Path.Combine(owned, "value"), "owned"); File.WriteAllText(Path.Combine(unknown, "value"), "user"); using (await publisher.AcquireUseAsync()) + { publisher.Record(owned, owned + ".read.lock", [], null, "windows-x64"); + } Assert.Single(BuildCacheOwnerCatalog.ReadOwners(m_root)); await BuildMaintenanceApplication.CleanAsync(m_root, new(0, 0), true, true, "windows-x64", CancellationToken.None); Assert.True(Directory.Exists(owned)); @@ -39,9 +41,21 @@ public async Task MaintenanceUsesPublisherInventoryWithoutAdoptingUnrecordedDire public async Task EmptyCheckoutAndInvalidRequestsDoNotPrepareGeneratorsOrClaimArtifacts() { Assert.Empty(BuildCacheOwnerCatalog.ReadOwners(m_root)); - Assert.Equal(0, await BuildMaintenanceApplication.Run(["clean", "--scope", "cache", "--engine-root", m_root, "--dry-run"], CancellationToken.None)); + Assert.Equal( + 0, + await BuildMaintenanceApplication.Run( + ["clean", "--scope", "cache", "--engine-root", m_root, "--dry-run"], + CancellationToken.None + ) + ); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts", "native"))); - Assert.Equal(1, await BuildMaintenanceApplication.Run(["clean", "--scope", "cache", "--scope", "cache", "--engine-root", m_root], CancellationToken.None)); + Assert.Equal( + 1, + await BuildMaintenanceApplication.Run( + ["clean", "--scope", "cache", "--scope", "cache", "--engine-root", m_root], + CancellationToken.None + ) + ); using var canceled = new CancellationTokenSource(); canceled.Cancel(); Assert.Equal(2, await BuildMaintenanceApplication.Run(["clean"], canceled.Token)); @@ -52,7 +66,9 @@ public void CorruptRegistrationOrChangedRoleIsRejectedBeforeRetirement() { string ownerRoot = Path.Combine(m_root, "artifacts", "fixture"); BuildCacheOwnerCatalog.Register(m_root, ownerRoot, "fixture", BuildCacheArtifactRole.ImmutableArtifact); - Assert.Throws(() => BuildCacheOwnerCatalog.Register(m_root, ownerRoot, "fixture", BuildCacheArtifactRole.ReusableWorkspace)); + Assert.Throws( + () => BuildCacheOwnerCatalog.Register(m_root, ownerRoot, "fixture", BuildCacheArtifactRole.ReusableWorkspace) + ); string registration = Directory.EnumerateFiles(Path.Combine(m_root, "artifacts", "cache-owners"), "*.json").Single(); File.WriteAllText(registration, "{}"); Assert.Throws(() => BuildCacheOwnerCatalog.ReadOwners(m_root)); @@ -61,6 +77,8 @@ public void CorruptRegistrationOrChangedRoleIsRejectedBeforeRetirement() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementFailureTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementFailureTests.cs index 8a58cb643..ebaef878d 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementFailureTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementFailureTests.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Text.Json.Nodes; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -32,10 +32,16 @@ public async Task UnverifiableMetadataPreservesClaimsAndReportsCompletedRetireme Directory.CreateDirectory(output); File.WriteAllBytes(Path.Combine(output, "payload"), [1, 2, 3]); using (await healthy.AcquireUseAsync()) + { healthy.Record(output, output + ".read.lock", [], null, null); + } - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, - [invalid.Describe("invalid"), healthy.Describe("healthy")], new(0, 0), retireAll: true); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + m_root, + [invalid.Describe("invalid"), healthy.Describe("healthy")], + new(0, 0), + retireAll: true + ); BuildCacheCleanupResult result = await plan.ExecuteAsync(); Assert.Equal(3, result.retiredBytes); @@ -61,14 +67,22 @@ public async Task ExplicitMaintenanceStillFailsWhenMetadataCannotBeCertified() File.WriteAllText(claim + ".invalid.process", "unverifiable"); await Assert.ThrowsAsync(() => BuildMaintenanceApplication.CleanAsync( - m_root, new(timeBudget: TimeSpan.FromSeconds(30)), true, false, null, default)); + m_root, + new(timeBudget: TimeSpan.FromSeconds(30)), + true, + false, + null, + default + )); Assert.True(File.Exists(claim)); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private static void MarkOwnerExited(string claim) diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs index f2f16d3e7..1a9b0ee3a 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs @@ -20,8 +20,15 @@ public async Task UnprotectedProcessWorkIsRetiredWithoutEvictingReusablePayloads { OwnedCache owner = AddOwner("process-work"); BuildCacheArtifactDescriptor process = owner.Add("exited-process", 2); - owner.artifacts[0] = new(process.directory, process.leasePath, process.targetId, - process.bytes, process.lastUseUtc, [], BuildCacheArtifactRole.ProcessWorkingDirectory); + owner.artifacts[0] = new( + process.directory, + process.leasePath, + process.targetId, + process.bytes, + process.lastUseUtc, + [], + BuildCacheArtifactRole.ProcessWorkingDirectory + ); BuildCacheArtifactDescriptor reusable = owner.Add("reusable", 3); BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new(long.MaxValue, 0)); Assert.Equal(process.directory, Assert.Single(plan.candidates).directory); @@ -37,8 +44,13 @@ public async Task TargetCleanupPreservesOtherTargetsSharedArtifactsAndTheirDepen BuildCacheArtifactDescriptor requiredByMac = owner.Add("windows-dependency", 3, targetId: "windows-x64"); BuildCacheArtifactDescriptor mac = owner.Add("mac", 4, [requiredByMac.directory], "macos-arm64"); BuildCacheArtifactDescriptor obsoleteWindows = owner.Add("windows-obsolete", 5, targetId: "windows-x64"); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new(0, 0), - retireAll: true, targetId: "windows-x64"); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + m_root, + [owner.descriptor], + new(0, 0), + retireAll: true, + targetId: "windows-x64" + ); Assert.Equal(obsoleteWindows.directory, Assert.Single(plan.candidates).directory); BuildCacheCleanupResult result = await plan.ExecuteAsync(); Assert.Equal(obsoleteWindows.directory, Assert.Single(result.retired)); @@ -52,10 +64,22 @@ public async Task FreshTargetChangePreventsRetiringAnOriginalCandidate() { OwnedCache owner = AddOwner("retargeted"); BuildCacheArtifactDescriptor original = owner.Add("candidate", 2, targetId: "windows-x64"); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new(0, 0), - retireAll: true, targetId: "windows-x64"); - owner.artifacts[0] = new(original.directory, original.leasePath, "macos-arm64", - original.bytes, original.lastUseUtc, original.dependencies, BuildCacheArtifactRole.ImmutableArtifact); + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + m_root, + [owner.descriptor], + new(0, 0), + retireAll: true, + targetId: "windows-x64" + ); + owner.artifacts[0] = new( + original.directory, + original.leasePath, + "macos-arm64", + original.bytes, + original.lastUseUtc, + original.dependencies, + BuildCacheArtifactRole.ImmutableArtifact + ); BuildCacheCleanupResult result = await plan.ExecuteAsync(); Assert.Empty(result.retired); Assert.True(Directory.Exists(original.directory)); @@ -95,8 +119,12 @@ public async Task ActiveReaderPreventsRetirementUntilItReleasesOwnership() BuildCacheArtifactDescriptor artifact = owner.Add("generation", 6); BuildArtifactManifest.Write(artifact.directory, "fixture", ["Outputs"]); BuildCacheCleanupPlan plan = CreatePlan(); - using (BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(artifact.directory, Path.GetDirectoryName(artifact.directory)!, "fixture", ["Outputs"])) - { + using (BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + artifact.directory, + Path.GetDirectoryName(artifact.directory)!, + "fixture", + ["Outputs"] + )) { BuildCacheCleanupResult blocked = await plan.ExecuteAsync(); Assert.Empty(blocked.retired); Assert.Contains(artifact.directory, blocked.skipped); @@ -114,7 +142,15 @@ public async Task WorkspaceRetirementUsesTheActualProducerLease() OwnedCache owner = AddOwner("workspaces"); BuildCacheArtifactDescriptor artifact = owner.Add("workspace", 6); string producerLease = Path.Combine(owner.descriptor.directory, "producer.lock"); - owner.artifacts[0] = new(artifact.directory, producerLease, artifact.targetId, artifact.bytes, artifact.lastUseUtc, [], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[0] = new( + artifact.directory, + producerLease, + artifact.targetId, + artifact.bytes, + artifact.lastUseUtc, + [], + BuildCacheArtifactRole.ImmutableArtifact + ); BuildCacheCleanupPlan plan = CreatePlan(); using (FileLease producer = await FileLease.AcquireAsync(producerLease, TimeSpan.Zero)) { @@ -134,11 +170,26 @@ public void PersistentLeasesCannotBeInsideRetiredDirectoriesOrSharedByEntries() OwnedCache owner = AddOwner("native"); BuildCacheArtifactDescriptor first = owner.Add("first", 2); BuildCacheArtifactDescriptor second = owner.Add("second", 2); - owner.artifacts[0] = new(first.directory, Path.Combine(first.directory, "inside.lock"), - first.targetId, first.bytes, first.lastUseUtc, [], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[0] = new( + first.directory, + Path.Combine(first.directory, "inside.lock"), + first.targetId, + first.bytes, + first.lastUseUtc, + [], + BuildCacheArtifactRole.ImmutableArtifact + ); Assert.Throws(() => CreatePlan()); owner.artifacts[0] = first; - owner.artifacts[1] = new(second.directory, first.leasePath, second.targetId, second.bytes, second.lastUseUtc, [], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[1] = new( + second.directory, + first.leasePath, + second.targetId, + second.bytes, + second.lastUseUtc, + [], + BuildCacheArtifactRole.ImmutableArtifact + ); Assert.Throws(() => CreatePlan()); Assert.True(Directory.Exists(first.directory)); Assert.True(Directory.Exists(second.directory)); @@ -153,7 +204,12 @@ public async Task ActiveParentOutsideTheProposalProtectsItsDependency() BuildArtifactManifest.Write(parent.directory, "parent", ["Outputs"]); BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], new(13, 0)); Assert.Equal(dependency.directory, Assert.Single(plan.candidates).directory); - using BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync(parent.directory, Path.GetDirectoryName(parent.directory)!, "parent", ["Outputs"]); + using BuildArtifactReadLease reading = await BuildArtifactReadLease.AcquireAsync( + parent.directory, + Path.GetDirectoryName(parent.directory)!, + "parent", + ["Outputs"] + ); BuildCacheCleanupResult result = await plan.ExecuteAsync(); @@ -174,7 +230,9 @@ public async Task PreviewAndExecutionUseTheSameProposalAndFreshRoots() Assert.Contains(artifact.directory, preview.skipped); Assert.True(Directory.Exists(artifact.directory)); using (FileLease update = await FileLease.AcquireAsync(owner.descriptor.coordinationPath, TimeSpan.Zero)) + { owner.roots.Add(artifact.directory); + } BuildCacheCleanupResult actual = await plan.ExecuteAsync(); @@ -207,7 +265,15 @@ public async Task ChangedInventoryDoesNotDeleteTheEarlierGeneration() OwnedCache owner = AddOwner("native"); BuildCacheArtifactDescriptor artifact = owner.Add("generation", 3); BuildCacheCleanupPlan plan = CreatePlan(); - owner.artifacts[0] = new(artifact.directory, artifact.leasePath, artifact.targetId, 4, artifact.lastUseUtc, [], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[0] = new( + artifact.directory, + artifact.leasePath, + artifact.targetId, + 4, + artifact.lastUseUtc, + [], + BuildCacheArtifactRole.ImmutableArtifact + ); BuildCacheCleanupResult result = await plan.ExecuteAsync(); @@ -234,12 +300,17 @@ public async Task CancellationAndDurationLimitPreserveUnprocessedArtifacts() { OwnedCache owner = AddOwner("native"); BuildCacheArtifactDescriptor artifact = owner.Add("generation", 3); - Assert.Throws(() => BuildCacheCleanupPlan.Create(m_root, [owner.descriptor], - new(0, 0, TimeSpan.FromTicks(1)), retireAll: true)); + Assert.Throws(() => BuildCacheCleanupPlan.Create( + m_root, + [owner.descriptor], + new(0, 0, TimeSpan.FromTicks(1)), + retireAll: true + )); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync( - () => CreatePlan().ExecuteAsync(cancellationToken: cancellation.Token).AsTask()); + () => CreatePlan().ExecuteAsync(cancellationToken: cancellation.Token).AsTask() + ); Assert.True(Directory.Exists(artifact.directory)); } @@ -249,9 +320,25 @@ public void InvalidOwnershipAndDependencyCyclesFailBeforeRemoval() OwnedCache owner = AddOwner("native"); BuildCacheArtifactDescriptor first = owner.Add("first", 2); BuildCacheArtifactDescriptor second = owner.Add("second", 2, [first.directory]); - owner.artifacts[0] = new(first.directory, first.leasePath, first.targetId, first.bytes, first.lastUseUtc, [second.directory], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[0] = new( + first.directory, + first.leasePath, + first.targetId, + first.bytes, + first.lastUseUtc, + [second.directory], + BuildCacheArtifactRole.ImmutableArtifact + ); Assert.Throws(() => CreatePlan()); - owner.artifacts[0] = new(first.directory, first.leasePath, first.targetId, first.bytes, first.lastUseUtc, [Path.Combine(m_root, "unregistered")], BuildCacheArtifactRole.ImmutableArtifact); + owner.artifacts[0] = new( + first.directory, + first.leasePath, + first.targetId, + first.bytes, + first.lastUseUtc, + [Path.Combine(m_root, "unregistered")], + BuildCacheArtifactRole.ImmutableArtifact + ); Assert.Throws(() => CreatePlan()); owner.artifacts[0] = new(m_root, first.leasePath, null, 2, DateTime.UtcNow, [], BuildCacheArtifactRole.ImmutableArtifact); Assert.Throws(() => CreatePlan()); @@ -289,7 +376,9 @@ public void ProtectedArtifactsCanExceedTheBudgetWithoutBecomingCandidates() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private OwnedCache AddOwner(string name) @@ -299,8 +388,13 @@ private OwnedCache AddOwner(string name) return owner; } - private BuildCacheCleanupPlan CreatePlan() => BuildCacheCleanupPlan.Create(m_root, - m_owners.Select(static owner => owner.descriptor).ToArray(), new(0, 0), retireAll: true); + private BuildCacheCleanupPlan CreatePlan() + => BuildCacheCleanupPlan.Create( + m_root, + m_owners.Select(static owner => owner.descriptor).ToArray(), + new(0, 0), + retireAll: true + ); private sealed class OwnedCache { @@ -309,7 +403,10 @@ internal OwnedCache( string id ) { Directory.CreateDirectory(directory); - descriptor = new(id, directory, Path.Combine(directory, "owner.lock"), + descriptor = new( + id, + directory, + Path.Combine(directory, "owner.lock"), token => { token.ThrowIfCancellationRequested(); @@ -319,7 +416,8 @@ string id { token.ThrowIfCancellationRequested(); return roots.ToArray(); - }); + } + ); } internal List artifacts { get; } = []; @@ -336,7 +434,15 @@ internal BuildCacheArtifactDescriptor Add( Directory.CreateDirectory(Path.Combine(directory, "Outputs")); File.WriteAllBytes(Path.Combine(directory, "Outputs", "payload.bin"), new byte[bytes]); var used = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(artifacts.Count); - var artifact = new BuildCacheArtifactDescriptor(directory, directory + ".read.lock", targetId, bytes, used, dependencies ?? [], BuildCacheArtifactRole.ImmutableArtifact); + var artifact = new BuildCacheArtifactDescriptor( + directory, + directory + ".read.lock", + targetId, + bytes, + used, + dependencies ?? [], + BuildCacheArtifactRole.ImmutableArtifact + ); artifacts.Add(artifact); return artifact; } diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheWorkspaceLinkTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheWorkspaceLinkTests.cs index b1ddcbcb9..634b15827 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheWorkspaceLinkTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheWorkspaceLinkTests.cs @@ -4,9 +4,9 @@ using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -31,9 +31,15 @@ public async Task WorkspaceLibraryAliasesAreCountedOnceAndRetiredWithoutFollowin File.CreateSymbolicLink(Path.Combine(workspace, "libsample.1.dylib"), "libsample.1.0.dylib"); File.CreateSymbolicLink(Path.Combine(workspace, "libsample.dylib"), "libsample.1.dylib"); long bytes = Directory.EnumerateFiles(workspace, "*", SearchOption.AllDirectories) - .Where(path => new FileInfo(path).LinkTarget is null).Sum(path => new FileInfo(path).Length); + .Where(path => new FileInfo(path).LinkTarget is null) + .Sum(path => new FileInfo(path).Length); publisher.Record(workspace, producer, [], null, "macos-arm64"); - BuildCacheCleanupPlan measured = BuildCacheCleanupPlan.Create(root, [publisher.Describe("fixture")], new(0, 0), retireAll: true); + BuildCacheCleanupPlan measured = BuildCacheCleanupPlan.Create( + root, + [publisher.Describe("fixture")], + new(0, 0), + retireAll: true + ); Assert.Equal(bytes, measured.totalBytes); } BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(root, [publisher.Describe("fixture")], new(0, 0), retireAll: true); @@ -50,7 +56,9 @@ public async Task WorkspaceLibraryAliasesAreCountedOnceAndRetiredWithoutFollowin [SupportedOSPlatform("linux")] public async Task FileAliasesCannotEscapeCycleDangleOrEnterImmutableArtifacts() { - using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync(Path.Combine(Path.GetTempPath(), "InnoCacheLinkBoundary")); + using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync( + Path.Combine(Path.GetTempPath(), "InnoCacheLinkBoundary") + ); string root = owner.directory; string cache = Path.Combine(root, "cache"); string workspace = Path.Combine(cache, "workspace"); @@ -75,7 +83,9 @@ public async Task FileAliasesCannotEscapeCycleDangleOrEnterImmutableArtifacts() [Fact] public async Task WorkspacesRejectDirectoryLinksEvenWhenTheTargetIsOwned() { - using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync(Path.Combine(Path.GetTempPath(), "InnoCacheDirectoryLinks")); + using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync( + Path.Combine(Path.GetTempPath(), "InnoCacheDirectoryLinks") + ); string root = owner.directory; string cache = Path.Combine(root, "cache"); string workspace = Path.Combine(cache, "workspace"); @@ -86,12 +96,22 @@ public async Task WorkspacesRejectDirectoryLinksEvenWhenTheTargetIsOwned() { string escapedLink = link.Replace("'", "''", StringComparison.Ordinal); string escapedTarget = target.Replace("'", "''", StringComparison.Ordinal); - await ToolchainEnvironment.RunAsync("powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", "New-Item -ItemType Junction -Path '" + escapedLink + "' -Target '" + escapedTarget + "' | Out-Null"], - root, CancellationToken.None); + await ToolchainEnvironment.RunAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + "New-Item -ItemType Junction -Path '" + escapedLink + "' -Target '" + escapedTarget + "' | Out-Null" + ], + root, + CancellationToken.None + ); } else + { Directory.CreateSymbolicLink(link, target); + } try { var publisher = new BuildCachePublisher(cache, BuildCacheArtifactRole.ReusableWorkspace); diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildOutputOwnershipTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildOutputOwnershipTests.cs index 8da45cfe0..ec5da41d5 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildOutputOwnershipTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildOutputOwnershipTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.Diagnostics; using System.IO; @@ -6,8 +5,8 @@ using System.Text.Json; using System.Threading.Tasks; using System.Xml.Linq; - using Xunit; +using Inno.Testing.Source; namespace Inno.Build.Toolchains.Tests; @@ -21,17 +20,30 @@ public async Task ConcurrentSdkRequestsKeepExplicitOutputOwnersForTheSameTarget( Directory.CreateDirectory(root); try { - new XDocument(new XElement("Project", new XElement("Import", - new XAttribute("Project", Path.Combine(engine, "Directory.Build.props"))))) + new XDocument( + new XElement( + "Project", + new XElement("Import", new XAttribute("Project", Path.Combine(engine, "Directory.Build.props"))) + ) + ) .Save(Path.Combine(root, "Directory.Build.props")); File.WriteAllText(Path.Combine(root, "Directory.Build.targets"), ""); File.WriteAllText(Path.Combine(root, "Api.cs"), "public static class Api { public static int value => 42; }"); string project = Path.Combine(root, "Fixture.csproj"); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), - new XElement("ImplicitUsings", "disable"), new XElement("Nullable", "enable"), - new XElement("EnableDefaultCompileItems", "false")), - new XElement("ItemGroup", new XElement("Compile", new XAttribute("Include", "Api.cs"))))) + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("ImplicitUsings", "disable"), + new XElement("Nullable", "enable"), + new XElement("EnableDefaultCompileItems", "false") + ), + new XElement("ItemGroup", new XElement("Compile", new XAttribute("Include", "Api.cs"))) + ) + ) .Save(project); string first = Path.Combine(root, "requests", "first"); string second = Path.Combine(root, "requests", "second"); @@ -60,20 +72,39 @@ private static async Task Build( string project, string outputOwner ) { - string sdk = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string sdk = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(sdk) { - WorkingDirectory = Path.GetDirectoryName(project)!, UseShellExecute = false, CreateNoWindow = true, - RedirectStandardOutput = true, RedirectStandardError = true + WorkingDirectory = Path.GetDirectoryName(project)!, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true }; string evaluated = Path.Combine(Path.GetDirectoryName(outputOwner)!, Path.GetFileName(outputOwner) + ".json"); Directory.CreateDirectory(Path.GetDirectoryName(evaluated)!); - foreach (string argument in new[] { "build", project, "--artifacts-path", outputOwner, - "-p:InnoNativeTarget=fixture-target", "-p:InnoNativeBuildFingerprint=fixture-fingerprint", - "-target:Build", "-getProperty:TargetPath,ProjectAssetsFile", "-getItem:IntermediateAssembly", "-getResultOutputFile:" + evaluated, - "--disable-build-servers", "-m:1", "-nodeReuse:false", "-v:minimal" }) + foreach (string argument in new[] + { + "build", + project, + "--artifacts-path", + outputOwner, + "-p:InnoNativeTarget=fixture-target", + "-p:InnoNativeBuildFingerprint=fixture-fingerprint", + "-target:Build", + "-getProperty:TargetPath,ProjectAssetsFile", + "-getItem:IntermediateAssembly", + "-getResultOutputFile:" + evaluated, + "--disable-build-servers", + "-m:1", + "-nodeReuse:false", + "-v:minimal" + }) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start) ?? throw new InvalidOperationException("The SDK did not start."); Task output = process.StandardOutput.ReadToEndAsync(); Task error = process.StandardError.ReadToEndAsync(); @@ -92,7 +123,9 @@ string outputOwner Assert.True(process.ExitCode == 0, await output + await error); using JsonDocument result = JsonDocument.Parse(File.ReadAllText(evaluated)); JsonElement properties = result.RootElement.GetProperty("Properties"); - JsonElement intermediate = Assert.Single(result.RootElement.GetProperty("Items").GetProperty("IntermediateAssembly").EnumerateArray()); + JsonElement intermediate = Assert.Single( + result.RootElement.GetProperty("Items").GetProperty("IntermediateAssembly").EnumerateArray() + ); return [ Path.GetFullPath(properties.GetProperty("TargetPath").GetString()!), diff --git a/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs b/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs index 6505ea21a..d051d0443 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs @@ -28,19 +28,30 @@ bool continuousIntegration string parent = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "InnoDevelopmentBuildTests")); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("An explicit SDK host is required."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("An explicit SDK host is required."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); DirectoryInfo? repository = new(Directory.GetCurrentDirectory()); while (repository is not null && !File.Exists(Path.Combine(repository.FullName, "InnoEngine.sln"))) + { repository = repository.Parent; + } Assert.NotNull(repository); try { Directory.CreateDirectory(Path.Combine(root, "build", "msbuild")); File.Copy(Path.Combine(repository.FullName, "Directory.Build.props"), Path.Combine(root, "Directory.Build.props")); File.Copy(Path.Combine(repository.FullName, "Directory.Build.targets"), Path.Combine(root, "Directory.Build.targets")); - File.Copy(Path.Combine(repository.FullName, "build", "msbuild", "Inno.Packages.props"), Path.Combine(root, "build", "msbuild", "Inno.Packages.props")); - File.Copy(Path.Combine(repository.FullName, "build", "msbuild", "Inno.Build.Tasks.targets"), Path.Combine(root, "build", "msbuild", "Inno.Build.Tasks.targets")); + File.Copy( + Path.Combine(repository.FullName, "build", "msbuild", "Inno.Packages.props"), + Path.Combine(root, "build", "msbuild", "Inno.Packages.props") + ); + File.Copy( + Path.Combine(repository.FullName, "build", "msbuild", "Inno.Build.Tasks.targets"), + Path.Combine(root, "build", "msbuild", "Inno.Build.Tasks.targets") + ); File.Copy(Path.Combine(repository.FullName, "global.json"), Path.Combine(root, "global.json")); await File.WriteAllTextAsync(Path.Combine(root, ".gitignore"), "bin/\nobj/\n"); await File.WriteAllTextAsync(Path.Combine(root, "Fixture.csproj"), """ @@ -72,13 +83,21 @@ await File.WriteAllTextAsync(Path.Combine(root, "Fixture.csproj"), """ Assert.Equal(beforeSymbols, afterSymbols); Assert.Equal(beforeTimestamp, File.GetLastWriteTimeUtc(assembly)); Assert.Equal(C_SOURCE, ReadEmbeddedSource(symbols, "Contract.cs")); - Assert.DoesNotContain(commit, await File.ReadAllTextAsync(Path.Combine(root, "obj", effectiveConfiguration, "net10.0", "Fixture.AssemblyInfo.cs")), StringComparison.Ordinal); + Assert.DoesNotContain( + commit, + await File.ReadAllTextAsync(Path.Combine(root, "obj", effectiveConfiguration, "net10.0", "Fixture.AssemblyInfo.cs")), + StringComparison.Ordinal + ); } else { Assert.False(beforeAssembly.SequenceEqual(afterAssembly)); Assert.False(beforeSymbols.SequenceEqual(afterSymbols)); - Assert.Contains(commit, await File.ReadAllTextAsync(Path.Combine(root, "obj", effectiveConfiguration, "net10.0", "Fixture.AssemblyInfo.cs")), StringComparison.Ordinal); + Assert.Contains( + commit, + await File.ReadAllTextAsync(Path.Combine(root, "obj", effectiveConfiguration, "net10.0", "Fixture.AssemblyInfo.cs")), + StringComparison.Ordinal + ); Assert.Contains(commit, ReadSourceLink(symbols), StringComparison.Ordinal); } @@ -88,9 +107,16 @@ async Task CommitAsync(string message) await RunAsync("git", "-c", "user.name=Aaron Liao", "-c", "user.email=hsuankailiao@gmail.com", "commit", "-m", message); } - Task BuildAsync() => RunAsync(dotnet, ["build", "Fixture.csproj", - ..configuration.Length == 0 ? Array.Empty() : ["-c", configuration], - "-p:ContinuousIntegrationBuild=" + continuousIntegration, "-m:1", "-nr:false", "--disable-build-servers"]); + Task BuildAsync() + => RunAsync(dotnet, [ + "build", + "Fixture.csproj", + ..configuration.Length == 0 ? Array.Empty() : ["-c", configuration], + "-p:ContinuousIntegrationBuild=" + continuousIntegration, + "-m:1", + "-nr:false", + "--disable-build-servers" + ]); async Task RunAsync( string executable, @@ -98,11 +124,16 @@ params string[] arguments ) { var start = new ProcessStartInfo(executable) { - WorkingDirectory = root, UseShellExecute = false, CreateNoWindow = true, - RedirectStandardOutput = true, RedirectStandardError = true + WorkingDirectory = root, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true }; foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); @@ -115,11 +146,15 @@ params string[] arguments finally { if (!Path.GetFullPath(root).StartsWith(parent + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidOperationException("The development-build fixture escaped its temporary owner."); + } if (Directory.Exists(root)) { foreach (string file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)) + { File.SetAttributes(file, FileAttributes.Normal); + } Directory.Delete(root, recursive: true); } } @@ -132,12 +167,19 @@ string fileName using var stream = File.OpenRead(symbols); using MetadataReaderProvider provider = MetadataReaderProvider.FromPortablePdbStream(stream); MetadataReader reader = provider.GetMetadataReader(); - DocumentHandle document = Assert.Single(reader.Documents.Where(handle => reader.GetString(reader.GetDocument(handle).Name).EndsWith(fileName, StringComparison.Ordinal))); - CustomDebugInformation source = Assert.Single(reader.GetCustomDebugInformation(document).Select(reader.GetCustomDebugInformation) - .Where(info => reader.GetGuid(info.Kind) == new Guid("0E8A571B-6926-466E-B4AD-8AB04611F5FE"))); + DocumentHandle document = Assert.Single( + reader.Documents.Where(handle => reader.GetString(reader.GetDocument(handle).Name).EndsWith(fileName, StringComparison.Ordinal)) + ); + CustomDebugInformation source = Assert.Single( + reader.GetCustomDebugInformation(document) + .Select(reader.GetCustomDebugInformation) + .Where(info => reader.GetGuid(info.Kind) == new Guid("0E8A571B-6926-466E-B4AD-8AB04611F5FE")) + ); byte[] data = reader.GetBlobBytes(source.Value); if (BitConverter.ToInt32(data, 0) == 0) + { return Encoding.UTF8.GetString(data, 4, data.Length - 4); + } using var compressed = new MemoryStream(data, 4, data.Length - 4, writable: false); using var decoder = new DeflateStream(compressed, CompressionMode.Decompress); using var decoded = new MemoryStream(); @@ -151,8 +193,10 @@ private static string ReadSourceLink(string symbols) using var stream = File.OpenRead(symbols); using MetadataReaderProvider provider = MetadataReaderProvider.FromPortablePdbStream(stream); MetadataReader reader = provider.GetMetadataReader(); - CustomDebugInformation source = Assert.Single(reader.CustomDebugInformation.Select(reader.GetCustomDebugInformation) - .Where(info => reader.GetGuid(info.Kind) == new Guid("CC110556-A091-4D38-9FEC-25AB9A351A6A"))); + CustomDebugInformation source = Assert.Single( + reader.CustomDebugInformation.Select(reader.GetCustomDebugInformation) + .Where(info => reader.GetGuid(info.Kind) == new Guid("CC110556-A091-4D38-9FEC-25AB9A351A6A")) + ); return Encoding.UTF8.GetString(reader.GetBlobBytes(source.Value)); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ImmutableRegistrationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ImmutableRegistrationTests.cs index b2be55240..e9d77a5d7 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ImmutableRegistrationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ImmutableRegistrationTests.cs @@ -2,9 +2,9 @@ using System.IO; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -31,8 +31,12 @@ public async Task ConfirmationRetainsPublicationMetadataAndCurrentDependencyProt Assert.Equal(time, File.GetLastWriteTimeUtc(record)); publisher.Record(generation, generation + ".lock", [page], "selected", null); } - BuildCacheCleanupPlan protectedPlan = BuildCacheCleanupPlan.Create(Path.GetDirectoryName(m_root)!, - [publisher.Describe("documentation")], new(0, 0), retireAll: true); + BuildCacheCleanupPlan protectedPlan = BuildCacheCleanupPlan.Create( + Path.GetDirectoryName(m_root)!, + [publisher.Describe("documentation")], + new(0, 0), + retireAll: true + ); Assert.Empty((await protectedPlan.ExecuteAsync()).retired); Assert.True(Directory.Exists(page)); } @@ -53,11 +57,15 @@ public async Task ConfirmationRejectsChangedOwnershipWithoutRepairingItsRecord(s string record = Assert.Single(Directory.GetFiles(m_root, "*.cache.json")); byte[] bytes = File.ReadAllBytes(record); if (change == "payload") + { File.WriteAllText(Path.Combine(page, "extra"), "unaccounted bytes"); - Assert.Throws(() => publisher.EnsureImmutableRegistration(page, + } + Assert.Throws(() => publisher.EnsureImmutableRegistration( + page, change == "lease" ? page + ".other.lock" : page + ".lock", change == "dependency" ? [Path.Combine(m_root, "dependency")] : [], - change == "target" ? "another-target" : null)); + change == "target" ? "another-target" : null + )); Assert.Equal(bytes, File.ReadAllBytes(record)); } } @@ -73,19 +81,30 @@ public async Task CanceledRegistrationDoesNotCreateOwnershipAndWorkspacesCannotO using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); Assert.Throws(() => publisher.EnsureImmutableRegistration( - page, page + ".lock", [], null, cancellation.Token)); + page, + page + ".lock", + [], + null, + cancellation.Token + )); Assert.Empty(Directory.GetFiles(m_root, "*.cache.json")); var workspace = new BuildCachePublisher(m_root, BuildCacheArtifactRole.ReusableWorkspace); Assert.Throws(() => workspace.EnsureImmutableRegistration(page, page + ".lock", [], null)); Assert.Throws(() => publisher.EnsureImmutableRegistration( - Path.Combine(m_root, "..", "foreign"), page + ".lock", [], null)); + Path.Combine(m_root, "..", "foreign"), + page + ".lock", + [], + null + )); } } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private string Create(string name) diff --git a/tests/build/Inno.Build.Toolchains.Tests/ManagedProjectGraphCaptureTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ManagedProjectGraphCaptureTests.cs index 03e056ede..e10721fbd 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ManagedProjectGraphCaptureTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ManagedProjectGraphCaptureTests.cs @@ -5,8 +5,8 @@ using System.Linq; using System.Text.Json; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -18,8 +18,11 @@ public async Task RootOutputsBelongToTheEvaluatedInstanceEvenWithNonrepeatablePr string parent = Path.Combine(Path.GetTempPath(), "InnoGraphTests"); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("An explicit test SDK is required."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("An explicit test SDK is required."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); try { Directory.CreateDirectory(root); @@ -33,19 +36,33 @@ public async Task RootOutputsBelongToTheEvaluatedInstanceEvenWithNonrepeatablePr """); - using JsonDocument graph = JsonDocument.Parse(await ManagedProjectGraphCapture.CaptureAsync(root, dotnet, [project], - new Dictionary { ["Configuration"] = "Debug", ["DesignTimeBuild"] = "true" })); + using JsonDocument graph = JsonDocument.Parse( + await ManagedProjectGraphCapture.CaptureAsync( + root, + dotnet, + [project], + new Dictionary { ["Configuration"] = "Debug", ["DesignTimeBuild"] = "true" } + ) + ); JsonElement owner = Assert.Single(graph.RootElement.EnumerateArray()); JsonElement instance = Assert.Single(owner.GetProperty("Instances").EnumerateArray()); - Assert.Equal(instance.GetProperty("TargetPath").GetString(), owner.GetProperty("Properties").GetProperty("TargetPath").GetString()); + Assert.Equal( + instance.GetProperty("TargetPath").GetString(), + owner.GetProperty("Properties").GetProperty("TargetPath").GetString() + ); Assert.Empty(owner.GetProperty("Variants").EnumerateArray()); } finally { - if (!Path.GetFullPath(root).StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetFullPath(root) + .StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException("The test output escaped its declared owner."); + } if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -60,33 +77,57 @@ bool explicitVersion string parent = Path.Combine(Path.GetTempPath(), "InnoGraphTests"); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("An explicit test SDK is required."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("An explicit test SDK is required."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); try { Directory.CreateDirectory(root); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00\n"); string project = Path.Combine(root, "Example.csproj"); - File.WriteAllText(project, "" + framework + "" + File.WriteAllText( + project, + "" + framework + "" + (explicitVersion ? "" : string.Empty) - + ""); - string captured = await ManagedProjectGraphCapture.CaptureAsync(root, dotnet, [project], - new Dictionary { ["Configuration"] = "Debug", ["DesignTimeBuild"] = "true", ["BuildProjectReferences"] = "false" }); + + "" + ); + string captured = await ManagedProjectGraphCapture.CaptureAsync( + root, + dotnet, + [project], + new Dictionary + { + ["Configuration"] = "Debug", + ["DesignTimeBuild"] = "true", + ["BuildProjectReferences"] = "false" + } + ); using JsonDocument graph = JsonDocument.Parse(captured); JsonElement owner = Assert.Single(graph.RootElement.EnumerateArray()); string pack = Assert.Single(owner.GetProperty("FrameworkPacks").EnumerateArray()).GetString()!; Assert.Equal("Microsoft.NETCore.App.Ref", Path.GetFileName(Path.GetDirectoryName(pack))); if (explicitVersion) + { Assert.Equal("99.0.1", Path.GetFileName(pack)); + } else + { Assert.True(Directory.Exists(pack)); + } } finally { - if (!Path.GetFullPath(root).StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetFullPath(root) + .StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException("The test output escaped its declared owner."); + } if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -96,12 +137,17 @@ public async Task EquivalentVariantInputsSharePayloadWhileConditionalInputsAndPr string parent = Path.Combine(Path.GetTempPath(), "InnoGraphTests"); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("An explicit test SDK is required."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("An explicit test SDK is required."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); try { foreach (string name in new[] { "A", "B", "C" }) + { Directory.CreateDirectory(Path.Combine(root, name)); + } File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00\n"); File.WriteAllText(Path.Combine(root, "Extra.cs"), "namespace Example; public class Extra { }"); string first = Path.Combine(root, "A", "A.csproj"); @@ -110,36 +156,64 @@ public async Task EquivalentVariantInputsSharePayloadWhileConditionalInputsAndPr """); foreach ((string name, string flavor) in new[] { ("B", "one"), ("C", "two") }) - File.WriteAllText(Path.Combine(root, name, name + ".csproj"), + { + File.WriteAllText( + Path.Combine(root, name, name + ".csproj"), "net10.0" - + ""); - string captured = await ManagedProjectGraphCapture.CaptureAsync(root, dotnet, + + "" + ); + } + string captured = await ManagedProjectGraphCapture.CaptureAsync( + root, + dotnet, [first, Path.Combine(root, "B", "B.csproj"), Path.Combine(root, "C", "C.csproj")], - new Dictionary { ["Configuration"] = "Debug", ["DesignTimeBuild"] = "true", ["BuildProjectReferences"] = "false" }); + new Dictionary + { + ["Configuration"] = "Debug", + ["DesignTimeBuild"] = "true", + ["BuildProjectReferences"] = "false" + } + ); using JsonDocument graph = JsonDocument.Parse(captured); JsonElement owner = graph.RootElement.EnumerateArray().Single(node => node.GetProperty("Path").GetString() == first); - Assert.Contains(owner.GetProperty("EquivalentGlobalProperties").EnumerateArray(), - properties => properties.TryGetProperty("Flavor", out JsonElement flavor) && flavor.GetString() == "one"); + Assert.Contains( + owner.GetProperty("EquivalentGlobalProperties").EnumerateArray(), + properties => properties.TryGetProperty("Flavor", out JsonElement flavor) && flavor.GetString() == "one" + ); JsonElement variant = Assert.Single(owner.GetProperty("Variants").EnumerateArray()); - Assert.Contains(variant.GetProperty("EquivalentGlobalProperties").EnumerateArray(), - properties => properties.TryGetProperty("Flavor", out JsonElement flavor) && flavor.GetString() == "two"); - Assert.Contains(variant.GetProperty("Items").GetProperty("Compile").EnumerateArray(), - item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Extra.cs")); - Assert.DoesNotContain(owner.GetProperty("Items").GetProperty("Compile").EnumerateArray(), - item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Extra.cs")); + Assert.Contains( + variant.GetProperty("EquivalentGlobalProperties").EnumerateArray(), + properties => properties.TryGetProperty("Flavor", out JsonElement flavor) && flavor.GetString() == "two" + ); + Assert.Contains( + variant.GetProperty("Items").GetProperty("Compile").EnumerateArray(), + item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Extra.cs") + ); + Assert.DoesNotContain( + owner.GetProperty("Items").GetProperty("Compile").EnumerateArray(), + item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Extra.cs") + ); foreach ((string name, string flavor) in new[] { ("B", "one"), ("C", "two") }) { - JsonElement consumer = graph.RootElement.EnumerateArray().Single(node => node.GetProperty("Path").GetString() == Path.Combine(root, name, name + ".csproj")); + JsonElement consumer = graph.RootElement + .EnumerateArray() + .Single(node => node.GetProperty("Path").GetString() == Path.Combine(root, name, name + ".csproj")); JsonElement instance = Assert.Single(consumer.GetProperty("Instances").EnumerateArray()); string reference = Assert.Single(instance.GetProperty("References").EnumerateArray()).GetString()!; - JsonElement selected = owner.GetProperty("Instances").EnumerateArray().Single(node => node.GetProperty("Identity").GetString() == reference); + JsonElement selected = owner + .GetProperty("Instances") + .EnumerateArray() + .Single(node => node.GetProperty("Identity").GetString() == reference); Assert.Equal(flavor, selected.GetProperty("GlobalProperties").GetProperty("Flavor").GetString()); } } finally { - if (!Path.GetFullPath(root).StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetFullPath(root) + .StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException("The test output escaped its declared owner."); + } Directory.Delete(root, recursive: true); } } @@ -152,8 +226,11 @@ public async Task BatchResolutionPreservesActualReferencesCompilerSymbolsAndImpo string parent = Path.Combine(Path.GetTempPath(), "InnoGraphTests"); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("An explicit test SDK is required."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("An explicit test SDK is required."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); Directory.CreateDirectory(Path.Combine(root, "A")); Directory.CreateDirectory(Path.Combine(root, "B")); try @@ -161,14 +238,31 @@ public async Task BatchResolutionPreservesActualReferencesCompilerSymbolsAndImpo File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00\n"); string first = Path.Combine(root, "A", "A.csproj"); string second = Path.Combine(root, "B", "B.csproj"); - File.WriteAllText(first, "net10.0"); + File.WriteAllText( + first, + "net10.0" + ); File.WriteAllText(Path.Combine(root, "A", "Contract.cs"), "namespace Contracts; public class Contract { }"); File.WriteAllText(Path.Combine(root, "Imported.cs"), "namespace Consumers; public class Consumer : Contracts.Contract { }"); - File.WriteAllText(Path.Combine(root, "Imported.props"), "$(DefineConstants);IMPORTED"); - File.WriteAllText(second, "net10.0true"); - var start = new ProcessStartInfo(dotnet) { WorkingDirectory = root, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false }; + File.WriteAllText( + Path.Combine(root, "Imported.props"), + "$(DefineConstants);IMPORTED" + ); + File.WriteAllText( + second, + "net10.0true" + ); + var start = new ProcessStartInfo(dotnet) + { + WorkingDirectory = root, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }; foreach (string argument in new[] { "build", second, "-m:1", "-nr:false", "--disable-build-servers" }) + { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task output = process.StandardOutput.ReadToEndAsync(); Task errors = process.StandardError.ReadToEndAsync(); @@ -181,28 +275,45 @@ public async Task BatchResolutionPreservesActualReferencesCompilerSymbolsAndImpo """); - string captured = await ManagedProjectGraphCapture.CaptureAsync(root, dotnet, [first, second], + string captured = await ManagedProjectGraphCapture.CaptureAsync( + root, + dotnet, + [first, second], new Dictionary { - ["Configuration"] = "Debug", ["DesignTimeBuild"] = "true", ["BuildProjectReferences"] = buildReferences.ToString(), ["InnoProductRestore"] = "false" - }, resolveReferences: true); + ["Configuration"] = "Debug", + ["DesignTimeBuild"] = "true", + ["BuildProjectReferences"] = buildReferences.ToString(), + ["InnoProductRestore"] = "false" + }, + resolveReferences: true + ); using JsonDocument graph = JsonDocument.Parse(captured); Assert.Equal(2, graph.RootElement.GetArrayLength()); JsonElement consumer = graph.RootElement.EnumerateArray().Single(node => node.GetProperty("Path").GetString() == second); string[] defines = consumer.GetProperty("Properties").GetProperty("DefineConstants").GetString()!.Split(';'); Assert.Contains("IMPORTED", defines); Assert.Contains("NET10_0", defines); - Assert.Contains(consumer.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray(), - item => Path.GetFileName(item.GetProperty("FullPath").GetString()) == "A.dll"); - Assert.Contains(consumer.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray(), - item => item.TryGetProperty("FrameworkReferenceName", out JsonElement value) && value.GetString() == "Microsoft.NETCore.App"); - Assert.Contains(consumer.GetProperty("Items").GetProperty("Compile").EnumerateArray(), - item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Imported.cs")); + Assert.Contains( + consumer.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray(), + item => Path.GetFileName(item.GetProperty("FullPath").GetString()) == "A.dll" + ); + Assert.Contains( + consumer.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray(), + item => item.TryGetProperty("FrameworkReferenceName", out JsonElement value) && value.GetString() == "Microsoft.NETCore.App" + ); + Assert.Contains( + consumer.GetProperty("Items").GetProperty("Compile").EnumerateArray(), + item => item.GetProperty("FullPath").GetString() == Path.Combine(root, "Imported.cs") + ); } finally { - if (!Path.GetFullPath(root).StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetFullPath(root) + .StartsWith(Path.GetFullPath(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + ) { throw new InvalidOperationException("The test output escaped its declared owner."); + } Directory.Delete(root, recursive: true); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs index 0c0c03643..135f563af 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs @@ -1,7 +1,7 @@ using System; using System.IO; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -36,14 +36,28 @@ public void MultipurposeRecipeOwnerIncludesOnlyItsDeclaredImplementationClosure( string project = Write("platforms/Fixture/Inno.Build.Fixture.csproj", ""); string builder = Write("platforms/Fixture/NativeBuilder.cs", "builder"); string packaging = Write("platforms/Fixture/Packaging.cs", "packaging"); - var owner = new NativeComponentDescriptor("fixture", - Path.GetRelativePath(m_root, project), Path.GetRelativePath(m_root, project)); + var owner = new NativeComponentDescriptor( + "fixture", + Path.GetRelativePath(m_root, project), + Path.GetRelativePath(m_root, project) + ); var context = new NativeBuildContext(m_root, "release").WithComponentOptions(owner, new(NativeLibraryKind.Shared)); NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent( - context, owner, "fixture", "fixture-target", [], [], [builder]); + context, + owner, + "fixture", + "fixture-target", + [], + [], + [builder] + ); foreach (NativeBuildInput input in recipe.inputs) + { if (!File.Exists(input.physicalPath) && !Directory.Exists(input.physicalPath)) + { Write(Path.GetRelativePath(m_root, input.physicalPath), "common executor"); + } + } string identity = NativeBuildFingerprint.Create(recipe.declarations, recipe.inputs); File.WriteAllText(packaging, "unrelated packaging changed"); Assert.Equal(identity, NativeBuildFingerprint.Create(recipe.declarations, recipe.inputs)); @@ -56,12 +70,43 @@ public void FingerprintPreservesDeclarationOrderAndChangesForSourceOrSdkIdentity { string header = Write("include/api.h", "int sample(void);"); string compiler = Write("tools/clang", "compiler"); - string first = NativeBuildFingerprint.Create(["sdk-a", "wasm32"], [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)]); - Assert.Equal(first, NativeBuildFingerprint.Create(["sdk-a", "wasm32"], [new NativeBuildInput("tools/clang", compiler), new NativeBuildInput("include/api.h", header), new NativeBuildInput("include/api.h", header)])); - Assert.NotEqual(first, NativeBuildFingerprint.Create(["sdk-b", "wasm32"], [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)])); - Assert.NotEqual(first, NativeBuildFingerprint.Create(["wasm32", "sdk-a"], [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)])); + string first = NativeBuildFingerprint.Create( + ["sdk-a", "wasm32"], + [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)] + ); + Assert.Equal( + first, + NativeBuildFingerprint.Create( + ["sdk-a", "wasm32"], + [ + new NativeBuildInput("tools/clang", compiler), + new NativeBuildInput("include/api.h", header), + new NativeBuildInput("include/api.h", header) + ] + ) + ); + Assert.NotEqual( + first, + NativeBuildFingerprint.Create( + ["sdk-b", "wasm32"], + [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)] + ) + ); + Assert.NotEqual( + first, + NativeBuildFingerprint.Create( + ["wasm32", "sdk-a"], + [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)] + ) + ); File.WriteAllText(header, "long sample(void);"); - Assert.NotEqual(first, NativeBuildFingerprint.Create(["sdk-a", "wasm32"], [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)])); + Assert.NotEqual( + first, + NativeBuildFingerprint.Create( + ["sdk-a", "wasm32"], + [new NativeBuildInput("include/api.h", header), new NativeBuildInput("tools/clang", compiler)] + ) + ); Assert.Throws(() => new NativeBuildInput("include/api.h", "relative.h")); } @@ -71,15 +116,19 @@ public void LogicalInputsCanMoveWithoutChangingIdentityAndSameTimestampTampering string first = Write("checkout-a/include/api.h", "int one(void);"); string relocated = Write("checkout-b/include/api.h", "int one(void);"); string fingerprint = NativeBuildFingerprint.Create(["target"], [new NativeBuildInput("include/api.h", first)]); - Assert.Equal(fingerprint, - NativeBuildFingerprint.Create(["target"], [new NativeBuildInput("include/api.h", relocated)])); + Assert.Equal( + fingerprint, + NativeBuildFingerprint.Create(["target"], [new NativeBuildInput("include/api.h", relocated)]) + ); DateTime timestamp = File.GetLastWriteTimeUtc(relocated); long length = new FileInfo(relocated).Length; File.WriteAllText(relocated, "int two(void);"); File.SetLastWriteTimeUtc(relocated, timestamp); Assert.Equal(length, new FileInfo(relocated).Length); - Assert.NotEqual(fingerprint, - NativeBuildFingerprint.Create(["target"], [new NativeBuildInput("include/api.h", relocated)])); + Assert.NotEqual( + fingerprint, + NativeBuildFingerprint.Create(["target"], [new NativeBuildInput("include/api.h", relocated)]) + ); } [Fact] @@ -115,10 +164,14 @@ public void RequestDescriptorRejectsUnavailableOutputs() { string bindings = Write("Generated/Bindings.cs", "generated"); string descriptor = Path.Combine(m_root, "request.json"); - new NativeBindingGenerationDescriptor { - fingerprint = "identity", bindingsPath = bindings, nativeDirectory = string.Empty, + new NativeBindingGenerationDescriptor + { + fingerprint = "identity", + bindingsPath = bindings, + nativeDirectory = string.Empty, usesRuntimeImports = false, - artifactDirectory = string.Empty, artifactOwnerDirectory = string.Empty + artifactDirectory = string.Empty, + artifactOwnerDirectory = string.Empty }.Write(descriptor); Assert.Equal(bindings, NativeBindingGenerationDescriptor.Load(descriptor).bindingsPath); File.Delete(bindings); @@ -128,7 +181,9 @@ public void RequestDescriptorRejectsUnavailableOutputs() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private string Write( diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs index 436e023b9..25f8ccc96 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs @@ -4,15 +4,20 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; public sealed class NativeArtifactImportTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoNativeImport", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoNativeImport", + Guid.NewGuid().ToString("N") + ); + private readonly NativeComponentDescriptor m_owner = new("fixture", "component/Fixture.csproj", "component/Fixture.csproj"); [Fact] @@ -24,7 +29,14 @@ public async Task ImportedImmutableContentIsVerifiedAndRegisteredWithoutCopyingS string imported = Import(source, producer, consumer); Assert.False(File.Exists(imported + ".read.lock")); Assert.Empty(BuildCacheOwnerCatalog.ReadOwners(consumer)); - using NativeBuildProduct selected = await PublishAsync(consumer, static (_, _, _) => throw new InvalidOperationException("A valid import must not compile again.")); + using NativeBuildProduct selected = await PublishAsync( + consumer, + static ( + _, + _, + _ + ) => throw new InvalidOperationException("A valid import must not compile again.") + ); Assert.Equal(source.fingerprint, selected.fingerprint); Assert.Equal("result", File.ReadAllText(selected.files.Single())); Assert.Contains(BuildCacheOwnerCatalog.ReadOwners(consumer), owner => owner.id == "native"); @@ -52,17 +64,32 @@ public async Task DamagedImportedContentsCannotBypassTheRealProducer(string dama File.SetLastWriteTimeUtc(output, timestamp); } else if (damage == "missing") + { File.Delete(output); + } else if (damage == "additional") + { File.WriteAllText(Path.Combine(imported, "Outputs", "unexpected"), "extra"); + } else - File.WriteAllText(Path.Combine(imported, "generation-manifest.json"), System.Text.Json.JsonSerializer.Serialize(new - { - fingerprint = damage == "wrong-identity" ? new string('0', 64) : source.fingerprint, - files = new System.Collections.Generic.Dictionary { ["../escape"] = new string('0', 64) } - })); - await Assert.ThrowsAsync(() => PublishAsync(consumer, - static (_, _, _) => throw new InvalidOperationException("Retain the first real producer failure."))); + { + File.WriteAllText( + Path.Combine(imported, "generation-manifest.json"), + System.Text.Json.JsonSerializer.Serialize(new + { + fingerprint = damage == "wrong-identity" ? new string('0', 64) : source.fingerprint, + files = new System.Collections.Generic.Dictionary { ["../escape"] = new string('0', 64) } + }) + ); + } + await Assert.ThrowsAsync(() => PublishAsync( + consumer, + static ( + _, + _, + _ + ) => throw new InvalidOperationException("Retain the first real producer failure.") + )); Assert.Empty(Directory.GetFiles(Path.Combine(consumer, "artifacts", "native"), "*.current")); using NativeBuildProduct repaired = await PublishAsync(consumer, ProduceAsync); Assert.True(BuildArtifactManifest.IsComplete(repaired.directory, source.fingerprint, ["Outputs", "Metadata"])); @@ -83,11 +110,20 @@ public async Task TransportExcludesUnadoptedCandidatesAndReimportsWithoutProduce string archive = Path.Combine(producer, "artifacts", "transfer.zip"); Assert.Equal(1, await NativeArtifactTransfer.ExportAsync(producer, archive)); using (ZipArchive zip = ZipFile.OpenRead(archive)) + { Assert.All(zip.Entries, entry => Assert.DoesNotContain(other.fingerprint, entry.FullName)); + } Assert.Equal(1, await NativeArtifactTransfer.ImportAsync(consumer, archive)); Assert.DoesNotContain(BuildCacheOwnerCatalog.ReadOwners(consumer), owner => owner.id == "native"); Assert.Empty(Directory.GetFiles(Path.Combine(consumer, "artifacts", "native"), "*.cache.json")); - using NativeBuildProduct selected = await PublishAsync(consumer, static (_, _, _) => throw new InvalidOperationException("The imported candidate must be reusable.")); + using NativeBuildProduct selected = await PublishAsync( + consumer, + static ( + _, + _, + _ + ) => throw new InvalidOperationException("The imported candidate must be reusable.") + ); Assert.Equal(source.fingerprint, selected.fingerprint); Assert.Equal(0, await NativeArtifactTransfer.ImportAsync(consumer, archive)); } @@ -105,13 +141,29 @@ public async Task ExportAllowsRegisteredPublishersThatHaveNotProducedAnyGenerati using NativeBuildProduct source = await PublishAsync(producer, ProduceAsync); string archive = Path.Combine(producer, "artifacts", "transfer.zip"); string relative = Path.GetRelativePath(Path.Combine(producer, "artifacts"), source.directory).Replace('\\', '/'); - Assert.Equal(1, await NativeArtifactTransfer.ExportAsync(producer, archive, - selectedArtifacts: exactSelection ? new System.Collections.Generic.HashSet(StringComparer.Ordinal) { relative } : null)); + Assert.Equal( + 1, + await NativeArtifactTransfer.ExportAsync( + producer, + archive, + selectedArtifacts: exactSelection + ? new System.Collections.Generic.HashSet(StringComparer.Ordinal) { relative } + : null + ) + ); using (ZipArchive zip = ZipFile.OpenRead(archive)) + { Assert.All(zip.Entries, entry => Assert.StartsWith(relative + "/", entry.FullName)); + } Assert.Equal(1, await NativeArtifactTransfer.ImportAsync(consumer, archive)); - using NativeBuildProduct imported = await PublishAsync(consumer, - static (_, _, _) => throw new InvalidOperationException("The transferred generation must not compile again.")); + using NativeBuildProduct imported = await PublishAsync( + consumer, + static ( + _, + _, + _ + ) => throw new InvalidOperationException("The transferred generation must not compile again.") + ); Assert.Equal(source.fingerprint, imported.fingerprint); Assert.Equal("result", File.ReadAllText(imported.files.Single())); } @@ -132,14 +184,18 @@ public async Task TransportRejectsIncompleteOrUnsafeArchivesBeforeInstallingAnyC { ZipArchiveEntry output = zip.Entries.Single(entry => entry.FullName.EndsWith("result.fixture", StringComparison.Ordinal)); if (damage == "missing") + { output.Delete(); + } else if (damage == "tamper") { using var writer = new StreamWriter(output.Open()); writer.Write("broken"); } else if (damage == "link") + { output.ExternalAttributes = 0xa000 << 16; + } else { using var writer = new StreamWriter(zip.CreateEntry("../escape").Open()); @@ -161,7 +217,9 @@ public async Task CanceledExportPreservesThePreviousTransport() byte[] before = File.ReadAllBytes(archive); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - await Assert.ThrowsAnyAsync(() => NativeArtifactTransfer.ExportAsync(producer, archive, cancellation.Token)); + await Assert.ThrowsAnyAsync( + () => NativeArtifactTransfer.ExportAsync(producer, archive, cancellation.Token) + ); Assert.Equal(before, File.ReadAllBytes(archive)); Assert.Empty(Directory.GetFiles(Path.GetDirectoryName(archive)!, "*.staging-*")); } @@ -177,15 +235,32 @@ private string Prepare(string name) return root; } - private Task PublishAsync(string root, Func produce) - => NativeArtifactPublisher.PublishAsync(new(root, "debug"), new(m_owner, "fixture", "fixture-target", - [NativeBuildInput.FromPath(root, "Source")], ["debug", "fixture-recipe"]), produce); + private Task PublishAsync( + string root, + Func produce + ) => NativeArtifactPublisher.PublishAsync( + new(root, "debug"), + new( + m_owner, + "fixture", + "fixture-target", + [NativeBuildInput.FromPath(root, "Source")], + ["debug", "fixture-recipe"] + ), + produce + ); - private static Task ProduceAsync(NativeBuildContext context, string directory, CancellationToken cancellation) - => File.WriteAllTextAsync(Path.Combine(directory, "result.fixture"), "result", cancellation); + private static Task ProduceAsync( + NativeBuildContext context, + string directory, + CancellationToken cancellation + ) => File.WriteAllTextAsync(Path.Combine(directory, "result.fixture"), "result", cancellation); - private static string Import(NativeBuildProduct source, string producer, string consumer) - { + private static string Import( + NativeBuildProduct source, + string producer, + string consumer + ) { string sourceDirectory = PathBoundary.RequireUnlinkedPath(producer, source.directory); string destination = PathBoundary.Resolve(consumer, Path.GetRelativePath(producer, sourceDirectory)); foreach (string file in Directory.GetFiles(source.directory, "*", SearchOption.AllDirectories)) @@ -199,10 +274,15 @@ private static string Import(NativeBuildProduct source, string producer, string public void Dispose() { - string parent = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoNativeImport") + Path.DirectorySeparatorChar; + string parent = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoNativeImport") + + Path.DirectorySeparatorChar; if (!Path.GetFullPath(m_root).StartsWith(parent, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidOperationException("The import fixture escaped its owner."); + } if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs index b5e29592f..8a03ab851 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs @@ -1,21 +1,19 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.Linq; using System.Runtime.InteropServices; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using Xunit; using Inno.Build.Toolchains; - using Inno.Core.IO; namespace Inno.Build.Toolchains.Tests; public sealed class NativeArtifactPublicationTests : IDisposable { - private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoNativePublication", Guid.NewGuid().ToString("N")); [Fact] @@ -24,9 +22,11 @@ public async Task RepairWaitsForReadersAndCancellationPreservesThePinnedDirector NativeBuildContext context = CreateContext(); string source = Path.Combine(m_root, "repair.h"); File.WriteAllText(source, "input"); - var owner = new NativeComponentDescriptor("fixture", + var owner = new NativeComponentDescriptor( + "fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"); + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ); NativeBuildRecipe recipe = CreateRecipe(context, owner, "fixture", "fixture-x64", [source], []); var prepared = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); int calls = 0; @@ -37,7 +37,9 @@ CancellationToken cancellation ) { await File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", cancellation); if (Interlocked.Increment(ref calls) > 1) + { prepared.TrySetResult(); + } } using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(context, recipe, Produce); File.WriteAllText(first.files[0], "damaged"); @@ -61,30 +63,60 @@ public async Task MaterializationPreservesIdenticalTimestampsAndRejectsChangesAf string source = Path.Combine(m_root, "source.h"); File.WriteAllText(source, "int first;"); string intermediate = Path.Combine(m_root, "Intermediate", "input.h"); - using NativeBuildProduct result1 = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + using NativeBuildProduct result1 = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { + ) => + { Assert.True(await NativeInputMaterializer.CopyAsync(scoped, source, intermediate, cancellation)); DateTime original = File.GetLastWriteTimeUtc(intermediate); Assert.False(await NativeInputMaterializer.CopyAsync(scoped, source, intermediate, cancellation)); Assert.Equal(original, File.GetLastWriteTimeUtc(intermediate)); File.WriteAllText(Path.Combine(output, "result.native"), "complete"); - }); + } + ); context = CreateContext(); File.WriteAllText(source, "int newer;"); - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { + ) => + { File.WriteAllText(source, "int wrong;"); await NativeInputMaterializer.CopyAsync(scoped, source, intermediate, cancellation); - })); + } + )); Assert.Equal("int first;", File.ReadAllText(intermediate)); Assert.Empty(Directory.EnumerateFiles(m_root, "*.staging-*", SearchOption.AllDirectories)); } @@ -97,18 +129,33 @@ public async Task CanceledMaterializationPreservesTheOwnedIntermediate() string intermediate = Path.Combine(m_root, "input.h"); File.WriteAllText(source, "source"); File.WriteAllText(intermediate, "previous"); - using NativeBuildProduct result2 = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + using NativeBuildProduct result2 = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { + ) => + { using var canceled = new CancellationTokenSource(); canceled.Cancel(); await Assert.ThrowsAnyAsync(() => NativeInputMaterializer.CopyAsync(scoped, source, intermediate, canceled.Token).AsTask()); File.WriteAllText(Path.Combine(output, "result.native"), "complete"); - }); + } + ); Assert.Equal("previous", File.ReadAllText(intermediate)); } @@ -135,8 +182,22 @@ CancellationToken cancellation Task Publish() { NativeBuildContext operation = CreateContext(); - return NativeArtifactPublisher.PublishAsync(operation, - CreateRecipe(operation, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), Produce); + return NativeArtifactPublisher.PublishAsync( + operation, + CreateRecipe( + operation, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + Produce + ); } using NativeBuildProduct first = await Publish(); File.WriteAllText(header, "changed declaration"); @@ -154,7 +215,9 @@ Task Publish() finally { if (Directory.Exists(cycle)) + { Directory.Delete(cycle, recursive: false); + } Directory.Delete(alias, recursive: false); } } @@ -174,15 +237,36 @@ async Task Produce( CancellationToken cancellation ) { Interlocked.Increment(ref builds); - string intermediate = scoped.GetNativeBuildRoot(new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj")); + string intermediate = scoped.GetNativeBuildRoot( + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ) + ); string physical = new DirectoryInfo(intermediate).LinkTarget ?? intermediate; Assert.Contains(Path.Combine("obj", "native", "fixture-x64"), physical); toolDirectory = intermediate; Assert.True(Directory.Exists(intermediate)); await File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellation); } - Task Publish() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], ["sdk"]), Produce); + Task Publish() + => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + ["sdk"] + ), + Produce + ); NativeBuildProduct[] products = await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => Publish())); Assert.Equal(1, builds); @@ -192,7 +276,9 @@ Task Publish() => NativeArtifactPublisher.PublishAsync(conte File.WriteAllText(products[0].files[0], "tampered"); foreach (NativeBuildProduct product in products) + { product.Dispose(); + } using NativeBuildProduct repaired = await Publish(); Assert.Equal(2, builds); Assert.Equal(products[0].fingerprint, repaired.fingerprint); @@ -211,18 +297,60 @@ Task Produce( string output, CancellationToken cancellation ) => File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellation); - using NativeBuildProduct result3 = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "first", "fixture-x64", [source], []), Produce); - using NativeBuildProduct result4 = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "second", "fixture-x64", [source], []), Produce); + using NativeBuildProduct result3 = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "first", + "fixture-x64", + [source], + [] + ), + Produce + ); + using NativeBuildProduct result4 = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "second", + "fixture-x64", + [source], + [] + ), + Produce + ); Assert.Equal(5, context.statistics.hashedFiles); Assert.Equal(30, context.statistics.hashedBytes); DateTime timestamp = File.GetLastWriteTimeUtc(source); File.WriteAllText(source, "unsafe"); File.SetLastWriteTimeUtc(source, timestamp); - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "third", "fixture-x64", [source], []), Produce)); + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "third", + "fixture-x64", + [source], + [] + ), + Produce + )); } [Fact] @@ -237,30 +365,72 @@ Task Produce( string output, CancellationToken cancellation ) => File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellation); - using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), Produce); + using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + Produce + ); File.WriteAllText(Path.Combine(source, "added.h"), "new closure"); context = CreateContext(); - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), ( @scoped, output, cancellation - ) => throw new IOException("Compiler failed."))); + ) => throw new IOException("Compiler failed.") + )); Assert.Equal("complete", File.ReadAllText(first.files[0])); context = CreateContext(); - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { + ) => + { await Produce(scoped, output, cancellation); File.WriteAllText(Path.Combine(source, "changed-during-build.h"), "changed"); - })); + } + )); Assert.Equal("complete", File.ReadAllText(first.files[0])); Assert.Empty(Directory.GetDirectories(m_root, "*.staging-*", SearchOption.AllDirectories)); } @@ -271,19 +441,41 @@ public async Task DeploymentUsesExactProductsAndPreservesThePriorTreeOnCancellat NativeBuildContext context = CreateContext(); string source = Path.Combine(m_root, "source.h"); File.WriteAllText(source, "source"); - using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { + ) => + { await File.WriteAllTextAsync(Path.Combine(output, "api.native"), "complete", cancellation); string link = Path.Combine(output, "Link"); Directory.CreateDirectory(link); await File.WriteAllTextAsync(Path.Combine(link, "api.lib"), "build-only", cancellation); - }); + } + ); var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep( - "fixture", new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), new(NativeLibraryKind.Shared), [], + "fixture", + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + new(NativeLibraryKind.Shared), + [], ( context, dependencies, @@ -293,11 +485,17 @@ public async Task DeploymentUsesExactProductsAndPreservesThePriorTreeOnCancellat ( relative, target - ) => relative.Split(Path.DirectorySeparatorChar)[0] == "Link" - ? null : Path.Combine("fixture", target, relative))]); + ) => ( + relative.Split(Path.DirectorySeparatorChar)[0] == "Link" + ? null + : Path.Combine("fixture", target, relative) + ) + )]); string application = Path.Combine(m_root, "Application"); - await Task.WhenAll(Enumerable.Range(0, 3) - .Select(_ => ProductNativeDeployment.InstallAsync([product], plan, application).AsTask())); + await Task.WhenAll( + Enumerable.Range(0, 3) + .Select(_ => ProductNativeDeployment.InstallAsync([product], plan, application).AsTask()) + ); string deployed = Path.Combine(application, "native", "fixture", "fixture-x64", "api.native"); Assert.Equal("complete", File.ReadAllText(deployed)); Assert.Single(Directory.EnumerateFiles(Path.Combine(application, "native"), "*", SearchOption.AllDirectories)); @@ -334,9 +532,12 @@ await Assert.ThrowsAsync(() => Assert.Empty(Directory.EnumerateFileSystemEntries(canceledCandidate)); Assert.Empty(Directory.EnumerateDirectories(application, "*.staging-*")); - static NativeComponentDescriptor productOwner() => new("fixture", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"); + static NativeComponentDescriptor productOwner() + => new( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ); } [Fact] @@ -346,15 +547,31 @@ public async Task CanceledProducerCannotPublishItsCandidate() string source = Path.Combine(m_root, "source.h"); File.WriteAllText(source, "source"); using var cancellation = new CancellationTokenSource(); - await Assert.ThrowsAnyAsync(() => NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "fixture-x64", [source], []), async ( + await Assert.ThrowsAnyAsync(() => NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "fixture-x64", + [source], + [] + ), + async ( @scoped, output, token - ) => { + ) => + { await File.WriteAllTextAsync(Path.Combine(output, "api.native"), "candidate", token); cancellation.Cancel(); - }, cancellation.Token)); + }, + cancellation.Token + )); Assert.Empty(Directory.EnumerateFiles(Path.Combine(m_root, "artifacts"), "api.native", SearchOption.AllDirectories)); Assert.Empty(Directory.GetDirectories(m_root, "*.staging-*", SearchOption.AllDirectories)); } @@ -362,7 +579,9 @@ await Assert.ThrowsAnyAsync(() => NativeArtifactPubl public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private static NativeBuildRecipe CreateRecipe( @@ -372,10 +591,14 @@ private static NativeBuildRecipe CreateRecipe( string targetId, IReadOnlyList inputPaths, IReadOnlyList declarations - ) => new(owner, component, targetId, + ) => new( + owner, + component, + targetId, inputPaths.Concat(context.toolchain?.inputPaths ?? []) .Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), - declarations.Concat(context.toolchain?.declarations ?? [])); + declarations.Concat(context.toolchain?.declarations ?? []) + ); private static async Task CreateDirectoryAlias( string path, @@ -388,10 +611,17 @@ string target } string escapedPath = path.Replace("'", "''", StringComparison.Ordinal); string escapedTarget = target.Replace("'", "''", StringComparison.Ordinal); - await ToolchainEnvironment.RunAsync("powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", - $"$ErrorActionPreference='Stop'; New-Item -ItemType Junction -Path '{escapedPath}' -Target '{escapedTarget}' | Out-Null"], - Path.GetDirectoryName(path)!, CancellationToken.None); + await ToolchainEnvironment.RunAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + $"$ErrorActionPreference='Stop'; New-Item -ItemType Junction -Path '{escapedPath}' -Target '{escapedTarget}' | Out-Null" + ], + Path.GetDirectoryName(path)!, + CancellationToken.None + ); } private NativeBuildContext CreateContext() diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs index 9f987c92b..2ae83739b 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs @@ -4,8 +4,8 @@ using System.Text; using System.Text.Json; using System.Threading; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -77,8 +77,11 @@ public void MissingRootSemanticsAndUnknownFieldsAreRejected() Directory.CreateDirectory(m_root); string json = JsonSerializer.Serialize(Create()); string path = Path.Combine(m_root, "compilation.json"); - File.WriteAllText(path, json.Replace("\"frozen\":true,", string.Empty, StringComparison.Ordinal) - .Replace(",\"frozen\":true", string.Empty, StringComparison.Ordinal)); + File.WriteAllText( + path, + json.Replace("\"frozen\":true,", string.Empty, StringComparison.Ordinal) + .Replace(",\"frozen\":true", string.Empty, StringComparison.Ordinal) + ); Assert.Throws(() => NativeBindingCompilation.Load(m_root)); File.WriteAllText(path, json.Insert(1, "\"unrecognized\":true,")); Assert.Throws(() => NativeBindingCompilation.Load(m_root)); @@ -87,7 +90,9 @@ public void MissingRootSemanticsAndUnknownFieldsAreRejected() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, true); + } } private static NativeBindingCompilation Create() @@ -98,8 +103,14 @@ private static NativeBindingCompilation Create() roots = [new("user", "source", false, true), new("nested", "source/nested", false, true), new("generated", "", true, true)], files = [new("user", "nested/api.hpp", 8, hash, false), new("nested", "api.hpp", 8, hash, true)], includeDirectories = [new("user", "", false, false), new("nested", "", false, false)], - defines = ["first", "second"], compilerDefines = ["__COMPILER_FACT=1"], cxxStandard = 20, cStandard = 0, - requiredExports = ["exported"], staticExportSymbols = [], staticExportAbi = "", staticExportNames = [] + defines = ["first", "second"], + compilerDefines = ["__COMPILER_FACT=1"], + cxxStandard = 20, + cStandard = 0, + requiredExports = ["exported"], + staticExportSymbols = [], + staticExportAbi = "", + staticExportNames = [] }; } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs index ae1ef12dc..d8b9fd93c 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs @@ -5,24 +5,43 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Build.Toolchains.Tests; + public sealed class NativeDependencyManifestTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoDependencyTests", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoDependencyTests", + Guid.NewGuid().ToString("N") + ); + private readonly NativeComponentDescriptor m_component = new("fixture", "component/Native.csproj", "component/Toolchain.csproj"); private int m_productions; + [Fact] public async Task ExactPublishedPayloadImportsWithoutAConsumerCompilerAndIsAdoptedByItsOwner() { var fixture = await PrepareAsync(); - using ProductNativeBuildResult result = await NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan); + using ProductNativeBuildResult result = await NativeDependencyManifest.AcquireAsync( + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + ); Assert.Equal("payload", File.ReadAllText(Assert.Single(result).files.Single())); Assert.Equal(1, m_productions); Assert.Single(Directory.GetFiles(Path.Combine(fixture.consumer, "artifacts", "native"), "*.cache.json")); - using ProductNativeBuildResult warm = await NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan); + using ProductNativeBuildResult warm = await NativeDependencyManifest.AcquireAsync( + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + ); Assert.Equal(result[0].fingerprint, warm[0].fingerprint); Assert.Equal(1, m_productions); } @@ -31,7 +50,13 @@ public async Task ExactPublishedPayloadImportsWithoutAConsumerCompilerAndIsAdopt public async Task AggregateProductsRetainTheirExplicitLayoutWithoutPlatformBranches() { var fixture = await PrepareAsync(aggregate: true); - using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan); + using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + ); Assert.Equal(Path.Combine(imported[0].directory, "Outputs"), imported.aggregateDirectory); Assert.Equal("payload", File.ReadAllText(Assert.Single(imported).files.Single())); Assert.Empty(imported.bindingGenerations); @@ -46,8 +71,16 @@ public async Task SelectionIsReadOnlyAndRequiresNoArchive(bool aggregate) var fixture = await PrepareAsync(aggregate); string downloads = Path.Combine(fixture.consumer, "artifacts", "fixture-target", "native"); foreach (string archive in Directory.GetFiles(downloads)) + { File.Delete(archive); - IReadOnlyList selected = await NativeDependencyManifest.SelectAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan); + } + IReadOnlyList selected = await NativeDependencyManifest.SelectAsync( + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + ); Assert.Single(selected); Assert.False(Directory.Exists(Path.Combine(fixture.consumer, "artifacts", "native"))); Assert.Equal(1, m_productions); @@ -61,7 +94,9 @@ public async Task MalformedSelectionFailsBeforeTouchingArtifacts(string json) { var fixture = await PrepareAsync(); File.WriteAllText(fixture.selection, json); - await Assert.ThrowsAsync(() => NativeDependencyManifest.SelectAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + await Assert.ThrowsAsync( + () => NativeDependencyManifest.SelectAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan) + ); Assert.False(Directory.Exists(Path.Combine(fixture.consumer, "artifacts", "native"))); } @@ -78,7 +113,13 @@ public async Task MissingOrChangedDependencyCannotInvokeTheProducer(string damag var fixture = await PrepareAsync(); JsonObject selection = JsonNode.Parse(File.ReadAllText(fixture.selection))!.AsObject(); JsonObject asset = selection["assets"]![0]!.AsObject(); - string archive = Path.Combine(fixture.consumer, "artifacts", "fixture-target", "native", asset["sha256"]!.GetValue() + ".zip"); + string archive = Path.Combine( + fixture.consumer, + "artifacts", + "fixture-target", + "native", + asset["sha256"]!.GetValue() + ".zip" + ); switch (damage) { case "missing": @@ -105,11 +146,17 @@ public async Task MissingOrChangedDependencyCannotInvokeTheProducer(string damag } File.WriteAllText(fixture.selection, selection.ToJsonString()); - Exception? failure = await Record.ExceptionAsync(() => NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + Exception? failure = await Record.ExceptionAsync( + () => NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan) + ); if (damage == "missing") + { Assert.IsType(failure); + } else + { Assert.IsType(failure); + } Assert.Equal(1, m_productions); } @@ -118,10 +165,19 @@ public async Task ModifiedInstalledArtifactFailsWithoutRepairOrProduction() { var fixture = await PrepareAsync(); string output; - using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)) + using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )) { output = imported[0].files.Single(); + } File.WriteAllText(output, "changed"); - await Assert.ThrowsAsync(() => NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + await Assert.ThrowsAsync( + () => NativeDependencyManifest.AcquireAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan) + ); Assert.Equal("changed", File.ReadAllText(output)); Assert.Equal(1, m_productions); } @@ -134,9 +190,19 @@ public async Task ForeignDependencyClosureIsRejectedBeforeDownloadOrInstallation selection["assets"]![0]!["dependencies"] = new JsonObject { ["foreign"] = new string('a', 64) }; File.WriteAllText(fixture.selection, selection.ToJsonString()); await Assert.ThrowsAsync(() => NativeDependencyManifest.SelectAsync( - fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )); await Assert.ThrowsAsync(() => NativeDependencyManifest.AcquireAsync( - fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )); Assert.False(Directory.Exists(Path.Combine(fixture.consumer, "artifacts", "native"))); Assert.Equal(1, m_productions); } @@ -153,7 +219,12 @@ public async Task IndexFlagsCannotHideChangedConsumerSourceBytes() File.SetLastWriteTimeUtc(source, timestamp); Assert.Equal(string.Empty, (await Git(fixture.consumer, "status", "--porcelain")).Trim()); await Assert.ThrowsAsync(() => NativeDependencyManifest.SelectAsync( - fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )); Assert.False(Directory.Exists(Path.Combine(fixture.consumer, "artifacts", "native"))); Assert.Equal(1, m_productions); } @@ -163,15 +234,26 @@ public async Task PinnedSubmoduleNeedsNoConsumerCheckoutButMutableCheckoutCannot { var fixture = await PrepareAsync(submodule: true); using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( - fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)) + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )) { Assert.Equal("payload", File.ReadAllText(imported[0].files.Single())); + } Assert.False(File.Exists(Path.Combine(fixture.consumer, "component", "Source", "source.h"))); await Git(fixture.consumer, "-c", "protocol.file.allow=always", "submodule", "update", "--init"); string sourceRoot = Path.Combine(fixture.consumer, "component", "Source"); await Git(sourceRoot, "update-index", "--assume-unchanged", "source.h"); File.WriteAllText(Path.Combine(sourceRoot, "source.h"), "hidden changed input"); await Assert.ThrowsAsync(() => NativeDependencyManifest.AcquireAsync( - fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan)); + fixture.consumer, + fixture.selection, + "fixture-target", + "release", + fixture.plan + )); Assert.Equal(1, m_productions); } @@ -200,51 +282,105 @@ await Assert.ThrowsAsync(() => NativeDependencyManifest.Ac await Git(producer, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-m", "Native source"); await Git(m_root, "clone", "--no-hardlinks", producer, consumer); string sdk = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - var tools = new NativeToolchainSelection("fixture-target", new BuildHostDescriptor("fixture-host", "fixture-arch"), new Dictionary { ["sdk"] = sdk }, new Dictionary(), [], [], new NativeLinkPlan(staticLibraryExtension: ".data"), false); + var tools = new NativeToolchainSelection( + "fixture-target", + new BuildHostDescriptor("fixture-host", "fixture-arch"), + new Dictionary { ["sdk"] = sdk }, + new Dictionary(), + [], + [], + new NativeLinkPlan(staticLibraryExtension: ".data"), + false + ); var context = new NativeBuildContext(producer, "release").WithToolchain(tools); - var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep("fixture", m_component, new(NativeLibraryKind.Static), [], Produce, Recipe, static ( - relative, - _ - ) => relative)]); - NativeBuildProduct? aggregateProduct = aggregate ? await Produce(context, new Dictionary(), CancellationToken.None) : null; - using ProductNativeBuildResult products = aggregateProduct is not null ? new ProductNativeBuildResult([aggregateProduct], new NativeBindingGenerationResult(new Dictionary(), []), Path.Combine(aggregateProduct.directory, "Outputs"), Recipe(context)) : await new ComponentNativeProductExecutor().BuildAsync(context, plan, CancellationToken.None); - string selection = await NativeDependencyManifest.ExportAsync(context, plan, products, Path.Combine(producer, "artifacts", "export")); + var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep( + "fixture", + m_component, + new(NativeLibraryKind.Static), + [], + Produce, + Recipe, + static ( + relative, + _ + ) => relative + )]); + NativeBuildProduct? aggregateProduct = aggregate + ? await Produce(context, new Dictionary(), CancellationToken.None) + : null; + using ProductNativeBuildResult products = aggregateProduct is not null + ? new ProductNativeBuildResult( + [aggregateProduct], + new NativeBindingGenerationResult(new Dictionary(), []), + Path.Combine(aggregateProduct.directory, "Outputs"), + Recipe(context) + ) + : await new ComponentNativeProductExecutor().BuildAsync(context, plan, CancellationToken.None); + string selection = await NativeDependencyManifest.ExportAsync( + context, + plan, + products, + Path.Combine(producer, "artifacts", "export") + ); var asset = JsonNode.Parse(File.ReadAllText(selection))![aggregate ? "aggregates" : "assets"]![0]!; string downloads = Path.Combine(consumer, "artifacts", "fixture-target", "native"); Directory.CreateDirectory(downloads); - File.Copy(Path.Combine(producer, "artifacts", "export", asset["asset"]!.GetValue()), Path.Combine(downloads, asset["sha256"]!.GetValue() + ".zip")); + File.Copy( + Path.Combine(producer, "artifacts", "export", asset["asset"]!.GetValue()), + Path.Combine(downloads, asset["sha256"]!.GetValue() + ".zip") + ); string consumerSelection = Path.Combine(consumer, "artifacts", "selection.json"); File.Copy(selection, consumerSelection); return (consumer, consumerSelection, plan); } - private NativeBuildRecipe Recipe(NativeBuildContext context) => new(m_component, "fixture", "fixture-target", [NativeBuildInput.FromPath(context.engineRoot, Path.Combine(context.engineRoot, "component", "Source"))], ["fixture"]); + private NativeBuildRecipe Recipe(NativeBuildContext context) + => new( + m_component, + "fixture", + "fixture-target", + [NativeBuildInput.FromPath(context.engineRoot, Path.Combine(context.engineRoot, "component", "Source"))], + ["fixture"] + ); + private Task Produce( NativeBuildContext context, IReadOnlyDictionary dependencies, CancellationToken cancellation - ) => NativeArtifactPublisher.PublishAsync(context, Recipe(context), ( - _, - output, - token - ) => - { - m_productions++; - return File.WriteAllTextAsync(Path.Combine(output, "output.data"), "payload", token); - }, cancellation, describeOutputs: static ( - _, - output - ) => [new NativeArtifact("fixture", Path.Combine(output, "output.data"), NativeArtifactRole.StaticArchive)]); + ) => NativeArtifactPublisher.PublishAsync( + context, + Recipe(context), + ( + _, + output, + token + ) => + { + m_productions++; + return File.WriteAllTextAsync(Path.Combine(output, "output.data"), "payload", token); + }, + cancellation, + describeOutputs: static ( + _, + output + ) => [new NativeArtifact("fixture", Path.Combine(output, "output.data"), NativeArtifactRole.StaticArchive)] + ); + private static Task Git( string root, params string[] arguments ) => ToolchainEnvironment.CaptureOutputAsync("git", arguments, root, CancellationToken.None); + public void Dispose() { if (!Directory.Exists(m_root)) + { return; + } foreach (string file in Directory.EnumerateFiles(m_root, "*", SearchOption.AllDirectories)) + { File.SetAttributes(file, FileAttributes.Normal); + } Directory.Delete(m_root, recursive: true); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs index 9bb5bcdbf..412659456 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.IO; -using Inno.Native.LibraryLoading; using Xunit; +using Inno.Native.LibraryLoading; namespace Inno.Build.Toolchains.Tests; @@ -38,15 +38,19 @@ public void UnknownSystemAndSuffixResolveThroughExplicitMappings() [InlineData("C:/outside.bin")] [InlineData("part\\wrong.bin")] public void InvalidDeploymentPathsFailBeforeResolution(string path) - => Assert.Throws(() => new NativeDeploymentIndex("fixture", - new Dictionary { ["library"] = path }, new Dictionary())); + => Assert.Throws(() => new NativeDeploymentIndex( + "fixture", + new Dictionary { ["library"] = path }, + new Dictionary() + )); [Fact] public void MissingAndUnknownIndexFieldsAreRejected() { Assert.Throws(() => NativeDeploymentIndex.Decode("{}"u8)); Assert.Throws(() => NativeDeploymentIndex.Decode( - "{\"targetId\":\"fixture\",\"libraries\":{},\"files\":{},\"oldLayout\":true}"u8)); + "{\"targetId\":\"fixture\",\"libraries\":{},\"files\":{},\"oldLayout\":true}"u8 + )); } public void Dispose() => Directory.Delete(m_root, recursive: true); diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeInputBatchTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeInputBatchTests.cs index dfd646acd..4120f94e2 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeInputBatchTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeInputBatchTests.cs @@ -4,9 +4,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; @@ -23,7 +23,9 @@ public NativeInputBatchTests() Directory.CreateDirectory(m_source); File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), string.Empty); for (int index = 0; index < 64; index++) + { File.WriteAllText(Path.Combine(m_source, index.ToString("D2") + ".h"), new string((char)('A' + index % 26), 16 * 1024)); + } } [Fact] @@ -57,7 +59,9 @@ public async Task FailedBatchDrainsReadersAndDoesNotFreezePartialContent() var context = new NativeBuildContext(m_root, "debug"); NativeBuildInput[] inputs = [new("source", m_source)]; using (var locked = new FileStream(Path.Combine(m_source, "63.h"), FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + { await Assert.ThrowsAnyAsync(() => Task.Run(() => NativeBuildFingerprint.Create(context, [], inputs))); + } foreach (string path in Directory.EnumerateFiles(m_source)) { using var exclusive = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None); @@ -91,7 +95,9 @@ IEnumerable CancelAfterInventory() public void Dispose() { if (!Path.GetFullPath(m_root).StartsWith(m_parent + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { throw new InvalidOperationException("The native input fixture escaped its owner."); + } Directory.Delete(m_root, recursive: true); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs index 53491054c..a4b39cdaa 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs @@ -19,11 +19,18 @@ public sealed class NativeProductExecutorTests : IDisposable public async Task NewTargetAndBackendUseTheSameExecutorAndStaticLinkageCanUseAStandaloneProducer() { NativeBuildContext context = Context(); - var plan = new ProductNativeBuildPlan("probe-product", [new ProductNativeBuildStep("probe", m_owner, - new(NativeLibraryKind.Static), [], Produce, Recipe, static ( + var plan = new ProductNativeBuildPlan("probe-product", [new ProductNativeBuildStep( + "probe", + m_owner, + new(NativeLibraryKind.Static), + [], + Produce, + Recipe, + static ( relative, target - ) => relative)]); + ) => relative + )]); var executor = new SelectedExecutor(); var contribution = new NativeProductContribution(plan, executor); using (ProductNativeBuildResult first = await contribution.BuildAsync(context, CancellationToken.None)) @@ -43,14 +50,28 @@ public async Task UnsupportedLinkageIsRejectedBeforeBindingOrStaging() { NativeBuildContext context = Context(); string sdk = ToolchainEnvironment.ResolveExecutable("dotnet"); - var selection = new NativeToolchainSelection("probe-target", new BuildHostDescriptor("ProbeHost", "processor"), - new Dictionary { ["sdk"] = sdk }, new Dictionary(), [], [], - new NativeLinkPlan(staticLibraryExtension: ".archive"), false); - var plan = new ProductNativeBuildPlan("probe-product", [new ProductNativeBuildStep("probe", m_owner, - new(NativeLibraryKind.Shared), [], Produce, Recipe, static ( + var selection = new NativeToolchainSelection( + "probe-target", + new BuildHostDescriptor("ProbeHost", "processor"), + new Dictionary { ["sdk"] = sdk }, + new Dictionary(), + [], + [], + new NativeLinkPlan(staticLibraryExtension: ".archive"), + false + ); + var plan = new ProductNativeBuildPlan("probe-product", [new ProductNativeBuildStep( + "probe", + m_owner, + new(NativeLibraryKind.Shared), + [], + Produce, + Recipe, + static ( relative, target - ) => relative)]); + ) => relative + )]); await Assert.ThrowsAsync(() => new ComponentNativeProductExecutor() .BuildAsync(context.WithToolchain(selection), plan, CancellationToken.None)); Assert.Equal(0, m_productions); @@ -62,7 +83,9 @@ public async Task UnsupportedLinkageIsRejectedBeforeBindingOrStaging() public async Task IncompleteRoleInventoryIsRejectedBeforePublication() { NativeBuildContext context = Context(); - await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync(context, Recipe(context), + await Assert.ThrowsAsync(() => NativeArtifactPublisher.PublishAsync( + context, + Recipe(context), static ( operation, output, @@ -71,14 +94,19 @@ await Assert.ThrowsAsync(() => NativeArtifactPublisher.Pub describeOutputs: static ( operation, output - ) => [])); - Assert.Empty(Directory.GetFiles(Path.Combine(m_root, "artifacts", "native"), "generation-manifest.json", SearchOption.AllDirectories)); + ) => [] + )); + Assert.Empty( + Directory.GetFiles(Path.Combine(m_root, "artifacts", "native"), "generation-manifest.json", SearchOption.AllDirectories) + ); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private NativeBuildContext Context() @@ -88,29 +116,50 @@ private NativeBuildContext Context() File.WriteAllText(Path.Combine(m_root, "component", "Native.csproj"), ""); File.WriteAllText(Path.Combine(m_root, "component", "Toolchain.csproj"), ""); string sdk = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); - var tools = new NativeToolchainSelection("probe-target", new BuildHostDescriptor("ProbeHost", "processor"), - new Dictionary { ["sdk"] = sdk }, new Dictionary(), [], [], new NativeLinkPlan(".shared", staticLibraryExtension: ".data"), false); + var tools = new NativeToolchainSelection( + "probe-target", + new BuildHostDescriptor("ProbeHost", "processor"), + new Dictionary { ["sdk"] = sdk }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".shared", staticLibraryExtension: ".data"), + false + ); return new NativeBuildContext(m_root, "release").WithToolchain(tools); } - private NativeBuildRecipe Recipe(NativeBuildContext context) => new(m_owner, "probe", "probe-target", - [NativeBuildInput.FromPath(m_root, Path.Combine(m_root, "component", "Native.csproj"))], ["probe-recipe"]); + private NativeBuildRecipe Recipe(NativeBuildContext context) + => new( + m_owner, + "probe", + "probe-target", + [NativeBuildInput.FromPath(m_root, Path.Combine(m_root, "component", "Native.csproj"))], + ["probe-recipe"] + ); private Task Produce( NativeBuildContext context, IReadOnlyDictionary dependencies, CancellationToken cancellation - ) => NativeArtifactPublisher.PublishAsync(context, Recipe(context), ( - operation, - output, - token - ) => { - m_productions++; - return File.WriteAllTextAsync(Path.Combine(output, "probe-output.data"), "archive", token); - }, cancellation, describeOutputs: static ( - operation, - output - ) => [new NativeArtifact("probe-archive", Path.Combine(output, "probe-output.data"), NativeArtifactRole.StaticArchive)]); + ) => NativeArtifactPublisher.PublishAsync( + context, + Recipe(context), + ( + operation, + output, + token + ) => + { + m_productions++; + return File.WriteAllTextAsync(Path.Combine(output, "probe-output.data"), "archive", token); + }, + cancellation, + describeOutputs: static ( + operation, + output + ) => [new NativeArtifact("probe-archive", Path.Combine(output, "probe-output.data"), NativeArtifactRole.StaticArchive)] + ); private sealed class SelectedExecutor : INativeProductExecutor { diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeToolchainPreparationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeToolchainPreparationTests.cs index dfa0115d6..7d889d52b 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeToolchainPreparationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeToolchainPreparationTests.cs @@ -5,8 +5,8 @@ using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Build.Toolchains.Tests; @@ -22,8 +22,11 @@ public sealed class NativeToolchainPreparationTests private static async Task VerifyInstallationInputsAsync(bool executableAlias) { - string root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), - "InnoCMakeInputs", Guid.NewGuid().ToString("N")); + string root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoCMakeInputs", + Guid.NewGuid().ToString("N") + ); string prefix = Path.Combine(root, "prefix"); string installation = Path.Combine(root, "installation"); string physicalBin = Path.Combine(installation, "bin"); @@ -51,18 +54,33 @@ private static async Task VerifyInstallationInputsAsync(bool executableAlias) { string escapedAlias = aliasBin.Replace("'", "''", StringComparison.Ordinal); string escapedTarget = physicalBin.Replace("'", "''", StringComparison.Ordinal); - await ToolchainEnvironment.RunAsync("powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", - $"$ErrorActionPreference='Stop'; New-Item -ItemType Junction -Path '{escapedAlias}' -Target '{escapedTarget}' | Out-Null"], - root, CancellationToken.None); + await ToolchainEnvironment.RunAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + $"$ErrorActionPreference='Stop'; New-Item -ItemType Junction -Path '{escapedAlias}' -Target '{escapedTarget}' | Out-Null" + ], + root, + CancellationToken.None + ); } else + { Directory.CreateSymbolicLink(aliasBin, physicalBin); + } - NativeToolchainSelection selection = NativeToolchainPreparation.Freeze("fixture-x64", + NativeToolchainSelection selection = NativeToolchainPreparation.Freeze( + "fixture-x64", new BuildHostDescriptor("Fixture", "x64"), new Dictionary { ["cmake"] = selected }, - new Dictionary(), [], [], new NativeLinkPlan(staticLibraryExtension: ".a"), false); + new Dictionary(), + [], + [], + new NativeLinkPlan(staticLibraryExtension: ".a"), + false + ); Assert.Contains(modules, selection.inputPaths); Assert.DoesNotContain(Path.GetDirectoryName(unrelated)!, selection.inputPaths); string initial = Capture(); @@ -76,16 +94,24 @@ await ToolchainEnvironment.RunAsync("powershell.exe", File.WriteAllText(executable, "tool-two"); Assert.NotEqual(changedModule, Capture()); - string Capture() => NativeBuildFingerprint.Create(new NativeBuildContext(root, "release"), - selection.declarations, selection.inputPaths.Select(path => NativeBuildInput.FromPath(root, path)), - CancellationToken.None); + string Capture() + => NativeBuildFingerprint.Create( + new NativeBuildContext(root, "release"), + selection.declarations, + selection.inputPaths.Select(path => NativeBuildInput.FromPath(root, path)), + CancellationToken.None + ); } finally { if (executableAlias && File.Exists(selected)) + { File.Delete(selected); + } else if (!executableAlias && Directory.Exists(aliasBin)) + { Directory.Delete(aliasBin, recursive: false); + } Directory.Delete(root, recursive: true); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs index daf25b0c4..b94b122f5 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs @@ -3,8 +3,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -23,12 +23,30 @@ public async Task DifferentDirectoryAliasesKeepLogicalMappingsButShareOnePhysica Directory.CreateDirectory(physical); File.WriteAllText(Path.Combine(physical, "input.h"), "bytes"); if (OperatingSystem.IsWindows()) - await ToolchainEnvironment.RunAsync("powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", "New-Item -ItemType Junction -Path '" + alias + "' -Target '" + physical + "' | Out-Null"], root, CancellationToken.None); + { + await ToolchainEnvironment.RunAsync( + "powershell.exe", + [ + "-NoProfile", + "-NonInteractive", + "-Command", + "New-Item -ItemType Junction -Path '" + alias + "' -Target '" + physical + "' | Out-Null" + ], + root, + CancellationToken.None + ); + } else + { Directory.CreateSymbolicLink(alias, physical); + } var context = new NativeBuildContext(root, "release"); - _ = NativeBuildFingerprint.Create(context, [], [new NativeBuildInput("physical", physical), new NativeBuildInput("alias", alias)], CancellationToken.None); + _ = NativeBuildFingerprint.Create( + context, + [], + [new NativeBuildInput("physical", physical), new NativeBuildInput("alias", alias)], + CancellationToken.None + ); Assert.Equal(1, context.statistics.hashedFiles); Assert.Equal(5, context.statistics.hashedBytes); Assert.True(context.statistics.phases.Single().reusedReads > 0); @@ -36,10 +54,13 @@ await ToolchainEnvironment.RunAsync("powershell.exe", finally { if (Directory.Exists(alias)) + { Directory.Delete(alias, recursive: false); + } Directory.Delete(root, recursive: true); } } + [Fact] public void FreshPhasesDetectSameLengthSameTimestampChangesAndReuseSharedReads() { diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs index fdcf92da7..291b8a2cc 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.Linq; using System.Runtime.InteropServices; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -13,7 +13,6 @@ namespace Inno.Build.Toolchains.Tests; public sealed class NativeWorkspaceReuseTests : IDisposable { - private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoWorkspaceTests", Guid.NewGuid().ToString("N")); private readonly string m_bindingRoot = Path.Combine(Path.GetTempPath(), "InnoWorkspaceBindings", Guid.NewGuid().ToString("N")); private readonly NativeComponentDescriptor m_owner = new("fixture", "native/fixture.csproj", "build/fixture.csproj"); @@ -50,8 +49,14 @@ CancellationToken cancellation Interlocked.Increment(ref compilations); return File.WriteAllTextAsync(Path.Combine(output, "result.native"), File.ReadAllText(source), cancellation); } - NativeBuildRecipe Recipe() => new(m_owner, "fixture", "fixture-x64", - [new NativeBuildInput("input.cpp", source)], ["shared", "compiler-flag"]); + NativeBuildRecipe Recipe() + => new( + m_owner, + "fixture", + "fixture-x64", + [new NativeBuildInput("input.cpp", source)], + ["shared", "compiler-flag"] + ); using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(new(m_root, "release"), Recipe(), Produce); DateTime timestamp = File.GetLastWriteTimeUtc(source); await File.WriteAllTextAsync(source, "other"); @@ -80,15 +85,22 @@ CancellationToken cancellation ) { string current = scoped.GetNativeBuildRoot(m_owner); if (calls++ == 0) + { first = current; + } else + { Assert.NotEqual(first, current); + } return File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", cancellation); } foreach (string argument in new[] { "-O0", "-O2" }) { - using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(new(m_root, "release"), - new(m_owner, "fixture", "fixture-x64", [new NativeBuildInput("input.cpp", source)], [argument]), Produce); + using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + new(m_root, "release"), + new(m_owner, "fixture", "fixture-x64", [new NativeBuildInput("input.cpp", source)], [argument]), + Produce + ); } Assert.Equal(2, calls); } @@ -102,14 +114,25 @@ public async Task BindingGenerationChangesReuseTheWorkspaceAndCopiedInputLocatio bool aggregate, bool externalBindings ) { - var owner = new NativeComponentDescriptor("fixture", "native/fixture.csproj", "build/fixture.csproj", - bindingDefinition: "native/Bindings/bindings.props"); + var owner = new NativeComponentDescriptor( + "fixture", + "native/fixture.csproj", + "build/fixture.csproj", + bindingDefinition: "native/Bindings/bindings.props" + ); string? workspace = null; string? copiedBridge = null; string? previousProduct = null; - var tools = new NativeToolchainSelection("fixture-x64", new BuildHostDescriptor("Fixture", "x64"), + var tools = new NativeToolchainSelection( + "fixture-x64", + new BuildHostDescriptor("Fixture", "x64"), new Dictionary { ["fixture"] = ToolchainEnvironment.ResolveExecutable("dotnet") }, - new Dictionary(), [], [], new NativeLinkPlan(".native"), false); + new Dictionary(), + [], + [], + new NativeLinkPlan(".native"), + false + ); foreach (string generation in new[] { new string('a', 64), new string('b', 64) }) { string artifact = Path.Combine(externalBindings ? m_bindingRoot : m_root, "native", "obj", "fixture-x64", generation); @@ -120,11 +143,23 @@ bool externalBindings string header = Path.Combine(bridge, "fixture.h"); File.WriteAllText(header, generation); File.WriteAllText(managed, generation); - File.WriteAllText(Path.Combine(bridge, "compilation.json"), System.Text.Json.JsonSerializer.Serialize(new NativeBindingCompilation - { - roots = [new("generated", "", true, true)], files = [], includeDirectories = [], defines = [], compilerDefines = [], - cxxStandard = 0, cStandard = 0, requiredExports = [], staticExportSymbols = [], staticExportAbi = "", staticExportNames = [] - })); + File.WriteAllText( + Path.Combine(bridge, "compilation.json"), + System.Text.Json.JsonSerializer.Serialize(new NativeBindingCompilation + { + roots = [new("generated", "", true, true)], + files = [], + includeDirectories = [], + defines = [], + compilerDefines = [], + cxxStandard = 0, + cStandard = 0, + requiredExports = [], + staticExportSymbols = [], + staticExportAbi = "", + staticExportNames = [] + }) + ); var descriptor = new NativeBindingGenerationDescriptor { fingerprint = generation, @@ -135,18 +170,29 @@ bool externalBindings artifactOwnerDirectory = externalBindings ? m_bindingRoot : m_root }; using var bindings = new NativeBindingGenerationResult( - new Dictionary { [owner.nativeProject] = descriptor }, []); + new Dictionary { [owner.nativeProject] = descriptor }, + [] + ); NativeBuildContext context = new NativeBuildContext(m_root, "release").WithToolchain(tools).WithBindings(bindings); - var recipe = new NativeBuildRecipe(owner, "fixture", "fixture-x64", + var recipe = new NativeBuildRecipe( + owner, + "fixture", + "fixture-x64", [NativeBuildInput.FromPath(m_root, bridge), NativeBuildInput.FromPath(m_root, managed)], - [(aggregate ? owner.nativeProject + "=" : "bindings=") + generation, - (aggregate ? "componentArgument=" : string.Empty) + "-DINNO_FIXTURE_BRIDGE_ROOT=" + bridge]); - using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(context, recipe, + [ + (aggregate ? owner.nativeProject + "=" : "bindings=") + generation, + (aggregate ? "componentArgument=" : string.Empty) + "-DINNO_FIXTURE_BRIDGE_ROOT=" + bridge + ] + ); + using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( @scoped, output, cancellation - ) => { + ) => + { string current = scoped.GetNativeBuildRoot(owner); string physical = new DirectoryInfo(current).LinkTarget ?? current; NativeCMakeSource sources = await NativeCMakeExecutor.PrepareSourceAsync(scoped, owner, cancellation); @@ -159,12 +205,17 @@ bool externalBindings workspace = physical; copiedBridge = input; Assert.Equal(generation, File.ReadAllText(input)); - Assert.Equal("-DINNO_FIXTURE_BRIDGE_ROOT=" + Path.GetDirectoryName(input), - sources.ResolveDefinition("-DINNO_FIXTURE_BRIDGE_ROOT=" + bridge)); + Assert.Equal( + "-DINNO_FIXTURE_BRIDGE_ROOT=" + Path.GetDirectoryName(input), + sources.ResolveDefinition("-DINNO_FIXTURE_BRIDGE_ROOT=" + bridge) + ); await File.WriteAllTextAsync(Path.Combine(output, "result.native"), generation, cancellation); - }); + } + ); if (previousProduct is not null) + { Assert.NotEqual(previousProduct, product.fingerprint); + } previousProduct = product.fingerprint; } } @@ -172,9 +223,12 @@ bool externalBindings public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } if (Directory.Exists(m_bindingRoot)) + { Directory.Delete(m_bindingRoot, recursive: true); + } } - } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ProcessOwnershipTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ProcessOwnershipTests.cs index aa3bbdcf1..03e1fa54f 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ProcessOwnershipTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ProcessOwnershipTests.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Toolchains.Tests; @@ -29,7 +29,9 @@ public async Task MalformedSubprocessClaimsPreventRetirement(string malformed) finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -56,7 +58,9 @@ public async Task RegistrationAndRetirementCoordinateThroughTheSamePersistentLea finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -79,9 +83,12 @@ public async Task ProcessParticipantsReuseOnlyTheSameActiveDeclaredOperation() finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } + [Fact] public void ProcessIdentityIncludesItsStartTimeAndInvalidIdentityIsConservative() { @@ -115,7 +122,9 @@ public async Task WorkingClaimPrecedesPayloadAndNeverAdoptsUnrecordedDirectories finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -131,9 +140,15 @@ public async Task WorkspacePreferenceDoesNotPermanentlyPinAnIdleWorkspace() File.WriteAllText(Path.Combine(workspace, "payload"), "owned"); var publisher = new BuildCachePublisher(cache, BuildCacheArtifactRole.ReusableWorkspace); using (await publisher.AcquireUseAsync()) + { publisher.Record(workspace, workspace + ".lock", [], "preferred", "fixture"); - BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create(root, [publisher.Describe("workspace")], - new BuildCachePolicy(0, 0, TimeSpan.FromSeconds(10)), retireAll: true); + } + BuildCacheCleanupPlan plan = BuildCacheCleanupPlan.Create( + root, + [publisher.Describe("workspace")], + new BuildCachePolicy(0, 0, TimeSpan.FromSeconds(10)), + retireAll: true + ); Assert.Single(plan.candidates); BuildCacheCleanupResult result = await plan.ExecuteAsync(); Assert.Single(result.retired); @@ -142,7 +157,9 @@ public async Task WorkspacePreferenceDoesNotPermanentlyPinAnIdleWorkspace() finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -167,7 +184,9 @@ public async Task WorkingRegistrationRefusesToAdoptUnknownExistingPayload() finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs index a6587a8d1..776bc8ba1 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs @@ -42,9 +42,18 @@ public async Task CompleteHitUsesOneFreshUnionAndDoesNotInvokeProducers() public async Task DamagedMemberFallsBackWithoutReturningPartialProducts() { ProductNativeBuildPlan plan = Plan(); - using (ProductNativeBuildResult initial = await new ComponentNativeProductExecutor().BuildAsync(Context(), plan, CancellationToken.None)) + using (ProductNativeBuildResult initial = await new ComponentNativeProductExecutor().BuildAsync( + Context(), + plan, + CancellationToken.None + )) { File.WriteAllText(initial[1].files[0], "damaged"); - using ProductNativeBuildResult repaired = await new ComponentNativeProductExecutor().BuildAsync(Context(), plan, CancellationToken.None); + } + using ProductNativeBuildResult repaired = await new ComponentNativeProductExecutor().BuildAsync( + Context(), + plan, + CancellationToken.None + ); Assert.Equal(3, m_builds); Assert.All(repaired, static product => Assert.Equal("complete", File.ReadAllText(product.files[0]))); } @@ -55,39 +64,67 @@ public async Task ConcurrentHotRequestsShareReadOwnershipWithoutWorkspaceDeadloc ProductNativeBuildPlan plan = Plan(); using (await new ComponentNativeProductExecutor().BuildAsync(Context(), plan, CancellationToken.None)) { } using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); - ProductNativeBuildResult[] results = await Task.WhenAll(new ComponentNativeProductExecutor().BuildAsync(Context(), plan, cancellation.Token), new ComponentNativeProductExecutor().BuildAsync(Context(), plan, cancellation.Token)); + ProductNativeBuildResult[] results = await Task.WhenAll( + new ComponentNativeProductExecutor().BuildAsync(Context(), plan, cancellation.Token), + new ComponentNativeProductExecutor().BuildAsync(Context(), plan, cancellation.Token) + ); foreach (ProductNativeBuildResult result in results) + { result.Dispose(); + } Assert.Equal(2, m_builds); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } - private NativeBuildContext Context() => new NativeBuildContext(m_root, "release").WithToolchain(new("fixture-x64", - new BuildHostDescriptor("Fixture", "x64"), new Dictionary { ["compiler"] = Environment.ProcessPath! }, - new Dictionary(), [], [], new NativeLinkPlan(".dll"), false)); + private NativeBuildContext Context() + => new NativeBuildContext(m_root, "release").WithToolchain( + new( + "fixture-x64", + new BuildHostDescriptor("Fixture", "x64"), + new Dictionary { ["compiler"] = Environment.ProcessPath! }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".dll"), + false + ) + ); - private ProductNativeBuildPlan Plan() => new("fixture", new[] { "first", "second" }.Select(id => new ProductNativeBuildStep( - id, m_owner, new(NativeLibraryKind.Shared), [], - ( - context, - dependencies, - cancellation - ) => NativeArtifactPublisher.PublishAsync(context, Recipe(context, id), async ( - @scoped, - output, - token - ) => { - Interlocked.Increment(ref m_builds); - await File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", token); - }, cancellation), context => Recipe(context, id), static ( - relative, - target - ) => relative)).ToArray()); + private ProductNativeBuildPlan Plan() + => new( + "fixture", + new[] { "first", "second" }.Select(id => new ProductNativeBuildStep( + id, + m_owner, + new(NativeLibraryKind.Shared), + [], + ( + context, + dependencies, + cancellation + ) => NativeArtifactPublisher.PublishAsync(context, Recipe(context, id), async ( + @scoped, + output, + token + ) => + { + Interlocked.Increment(ref m_builds); + await File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", token); + }, cancellation), + context => Recipe(context, id), + static ( + relative, + target + ) => relative + )).ToArray() + ); private NativeBuildRecipe Recipe( NativeBuildContext context, diff --git a/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs index 5349315bd..fc3ba56b7 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs @@ -4,15 +4,20 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; namespace Inno.Build.Toolchains.Tests; public sealed class ProductNativePreparationTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoPreparedNative", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoPreparedNative", + Guid.NewGuid().ToString("N") + ); + private readonly NativeComponentDescriptor m_owner = new("fixture", "component/Fixture.csproj", "component/Fixture.csproj"); private int m_productions; @@ -32,10 +37,16 @@ public async Task EqualRequestsAcquireIndependentReadersWithoutProducingAgain() NativeBuildContext producer = Context(); ProductNativeBuildPlan plan = Plan(); string identity = await ProductNativePreparation.FreezeAsync(producer, plan); - using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync(producer, plan, CancellationToken.None); + using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync( + producer, + plan, + CancellationToken.None + ); string[][] rows = Assert.IsType(ProductNativePreparation.Capture(producer, plan, built, identity)); NativeBuildContext consumer = Context(); - using ProductNativeBuildResult reading = Assert.IsType(await ProductNativePreparation.TryAcquireAsync(consumer, plan, rows, identity)); + using ProductNativeBuildResult reading = Assert.IsType( + await ProductNativePreparation.TryAcquireAsync(consumer, plan, rows, identity) + ); NativeBuildPhaseStatistics phase = Assert.Single(consumer.statistics.phases); Assert.Equal("prepared-consumer", phase.phase); Assert.Equal(2, phase.files); @@ -45,8 +56,11 @@ public async Task EqualRequestsAcquireIndependentReadersWithoutProducingAgain() Assert.Equal("result", File.ReadAllText(reading[0].files.Single())); Assert.Equal(1, m_productions); using var cancellation = new CancellationTokenSource(); - Task waiting = BuildArtifactWriteLease.AcquireAsync(reading[0].directory, - Path.Combine(m_root, "artifacts", "native"), cancellation.Token).AsTask(); + Task waiting = BuildArtifactWriteLease.AcquireAsync( + reading[0].directory, + Path.Combine(m_root, "artifacts", "native"), + cancellation.Token + ).AsTask(); Assert.False(waiting.IsCompleted); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => waiting); @@ -70,10 +84,17 @@ public async Task FrozenIdentityChangesWithEveryDeclaredInput(string changed) File.SetLastWriteTimeUtc(path, timestamp); } else if (changed == "membership") + { File.WriteAllText(Path.Combine(m_root, "Source", "added.h"), "new"); + } else if (changed == "sdk") + { File.WriteAllText(Path.Combine(m_root, "sdk-tool"), "tool-b"); - NativeBuildContext after = Context(changed == "configuration" ? "release" : "debug", changed == "target" ? "other-target" : "fixture-target"); + } + NativeBuildContext after = Context( + changed == "configuration" ? "release" : "debug", + changed == "target" ? "other-target" : "fixture-target" + ); Assert.NotEqual(original, await ProductNativePreparation.FreezeAsync(after, Plan())); } @@ -90,7 +111,11 @@ public async Task ConsumerRejectsChangedInputsWithoutASeparatePreliminaryFreeze( NativeBuildContext producer = Context(); ProductNativeBuildPlan plan = Plan(); string identity = await ProductNativePreparation.FreezeAsync(producer, plan); - using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync(producer, plan, CancellationToken.None); + using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync( + producer, + plan, + CancellationToken.None + ); string[][] rows = ProductNativePreparation.Capture(producer, plan, built, identity)!; built.Dispose(); if (changed is "source" or "sdk") @@ -101,10 +126,16 @@ public async Task ConsumerRejectsChangedInputsWithoutASeparatePreliminaryFreeze( File.SetLastWriteTimeUtc(path, timestamp); } else if (changed == "membership") + { File.WriteAllText(Path.Combine(m_root, "Source", "added.h"), "new"); - NativeBuildContext consumer = Context(changed == "configuration" ? "release" : "debug", changed == "target" ? "other-target" : "fixture-target"); - ProductNativeBuildPlan current = changed == "product" ? new("different-product", plan.steps) - : changed == "recipe" ? Plan(NativeLibraryKind.Static) : plan; + } + NativeBuildContext consumer = Context( + changed == "configuration" ? "release" : "debug", + changed == "target" ? "other-target" : "fixture-target" + ); + ProductNativeBuildPlan current = changed == "product" + ? new("different-product", plan.steps) + : changed == "recipe" ? Plan(NativeLibraryKind.Static) : plan; Assert.Null(await ProductNativePreparation.TryAcquireAsync(consumer, current, rows, identity)); Assert.Equal(1, m_productions); } @@ -115,18 +146,33 @@ public async Task CancellationWhileWaitingReleasesPartialConsumerProtection() NativeBuildContext producer = Context(); ProductNativeBuildPlan plan = Plan(); string identity = await ProductNativePreparation.FreezeAsync(producer, plan); - using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync(producer, plan, CancellationToken.None); + using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync( + producer, + plan, + CancellationToken.None + ); string[][] rows = ProductNativePreparation.Capture(producer, plan, built, identity)!; string directory = built[0].directory; built.Dispose(); - using BuildArtifactWriteLease writer = await BuildArtifactWriteLease.AcquireAsync(directory, Path.Combine(m_root, "artifacts", "native")); + using BuildArtifactWriteLease writer = await BuildArtifactWriteLease.AcquireAsync( + directory, + Path.Combine(m_root, "artifacts", "native") + ); using var cancellation = new CancellationTokenSource(); - Task pending = ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity, cancellation.Token); + Task pending = ProductNativePreparation.TryAcquireAsync( + Context(), + plan, + rows, + identity, + cancellation.Token + ); Assert.False(pending.IsCompleted); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => pending); writer.Dispose(); - using ProductNativeBuildResult reading = Assert.IsType(await ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity)); + using ProductNativeBuildResult reading = Assert.IsType( + await ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity) + ); Assert.Equal("result", File.ReadAllText(reading[0].files.Single())); } @@ -136,13 +182,20 @@ public async Task SourceChangesWhileWaitingForProtectionRejectReuse() NativeBuildContext producer = Context(); ProductNativeBuildPlan plan = Plan(); string identity = await ProductNativePreparation.FreezeAsync(producer, plan); - using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync(producer, plan, CancellationToken.None); + using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync( + producer, + plan, + CancellationToken.None + ); string[][] rows = ProductNativePreparation.Capture(producer, plan, built, identity)!; string directory = built[0].directory; built.Dispose(); NativeBuildContext consumer = Context(); Assert.Equal(identity, await ProductNativePreparation.FreezeAsync(consumer, plan)); - using BuildArtifactWriteLease writer = await BuildArtifactWriteLease.AcquireAsync(directory, Path.Combine(m_root, "artifacts", "native")); + using BuildArtifactWriteLease writer = await BuildArtifactWriteLease.AcquireAsync( + directory, + Path.Combine(m_root, "artifacts", "native") + ); Task pending = ProductNativePreparation.TryAcquireAsync(consumer, plan, rows, identity); Assert.False(pending.IsCompleted); File.WriteAllText(Path.Combine(m_root, "Source", "source.h"), "other"); @@ -156,7 +209,11 @@ public async Task CorruptedPublicationAndPreCancellationCannotReturnSuccessfulRe NativeBuildContext producer = Context(); ProductNativeBuildPlan plan = Plan(); string identity = await ProductNativePreparation.FreezeAsync(producer, plan); - using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync(producer, plan, CancellationToken.None); + using ProductNativeBuildResult built = await new ComponentNativeProductExecutor().BuildAsync( + producer, + plan, + CancellationToken.None + ); string[][] rows = ProductNativePreparation.Capture(producer, plan, built, identity)!; string output = built[0].files.Single(); built.Dispose(); @@ -164,26 +221,47 @@ public async Task CorruptedPublicationAndPreCancellationCannotReturnSuccessfulRe Assert.Null(await ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity)); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - await Assert.ThrowsAnyAsync(() => ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity, cancellation.Token)); + await Assert.ThrowsAnyAsync( + () => ProductNativePreparation.TryAcquireAsync(Context(), plan, rows, identity, cancellation.Token) + ); } public void Dispose() { - string parent = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoPreparedNative") + Path.DirectorySeparatorChar; + string parent = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoPreparedNative") + + Path.DirectorySeparatorChar; if (!Path.GetFullPath(m_root).StartsWith(parent, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidOperationException("The native fixture escaped its temporary owner."); + } Directory.Delete(m_root, recursive: true); } private NativeBuildContext Context( string configuration = "debug", string target = "fixture-target" - ) => new NativeBuildContext(m_root, configuration).WithToolchain(new NativeToolchainSelection(target, - new BuildHostDescriptor("Fixture", "fixture-cpu"), new Dictionary { ["compiler"] = Path.Combine(m_root, "sdk-tool") }, - new Dictionary(), [], [], new NativeLinkPlan(".fixture", staticLibraryExtension: ".fixture-static"), false)); + ) => new NativeBuildContext(m_root, configuration).WithToolchain( + new NativeToolchainSelection( + target, + new BuildHostDescriptor("Fixture", "fixture-cpu"), + new Dictionary + { + ["compiler"] = Path.Combine(m_root, "sdk-tool") + }, + new Dictionary(), + [], + [], + new NativeLinkPlan(".fixture", staticLibraryExtension: ".fixture-static"), + false + ) + ); private ProductNativeBuildPlan Plan(NativeLibraryKind kind = NativeLibraryKind.Shared) - => new("fixture-product", [new ProductNativeBuildStep("fixture", m_owner, new NativeComponentBuildOptions(kind), [], + => new("fixture-product", [new ProductNativeBuildStep( + "fixture", + m_owner, + new NativeComponentBuildOptions(kind), + [], ( context, dependencies, @@ -192,16 +270,26 @@ private ProductNativeBuildPlan Plan(NativeLibraryKind kind = NativeLibraryKind.S owned, output, token - ) => { + ) => + { Interlocked.Increment(ref m_productions); await File.WriteAllTextAsync(Path.Combine(output, "result.fixture"), "result", token); - }, cancellation), Recipe, ( + }, cancellation), + Recipe, + ( path, target - ) => path)]); + ) => path + )]); private NativeBuildRecipe Recipe(NativeBuildContext context) - => new(m_owner, "fixture", context.toolchain!.targetId, - new[] { Path.Combine(m_root, "Source") }.Concat(context.toolchain.inputPaths).Select(path => NativeBuildInput.FromPath(m_root, path)), - new[] { context.configuration }.Concat(context.toolchain.declarations)); + => new( + m_owner, + "fixture", + context.toolchain!.targetId, + new[] { Path.Combine(m_root, "Source") } + .Concat(context.toolchain.inputPaths) + .Select(path => NativeBuildInput.FromPath(m_root, path)), + new[] { context.configuration }.Concat(context.toolchain.declarations) + ); } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ToolchainDiagnosticTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ToolchainDiagnosticTests.cs index b5c48e5ba..5802998b0 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ToolchainDiagnosticTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ToolchainDiagnosticTests.cs @@ -2,8 +2,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -15,8 +15,11 @@ public async Task CapturedSdkFailuresRetainTheirOriginalDiagnostic() string parent = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "InnoToolDiagnostics")); string root = Path.Combine(parent, Guid.NewGuid().ToString("N")); string host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("The test requires its selected SDK."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("The test requires its selected SDK."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); Directory.CreateDirectory(root); try { @@ -30,8 +33,13 @@ public async Task CapturedSdkFailuresRetainTheirOriginalDiagnostic() """); InvalidOperationException failure = await Assert.ThrowsAsync(() => - ToolchainEnvironment.CaptureOutputAsync(host, ["msbuild", project, "-t:Diagnose", "-nologo", "-nr:false"], - root, CancellationToken.None, DotNetSdkEnvironment.Create(host))); + ToolchainEnvironment.CaptureOutputAsync( + host, + ["msbuild", project, "-t:Diagnose", "-nologo", "-nr:false"], + root, + CancellationToken.None, + DotNetSdkEnvironment.Create(host) + )); Assert.Contains("failed with exit code", failure.Message); Assert.Contains("Original SDK diagnostic before failure.", failure.Message); Assert.Contains("The declared fixture input is unavailable.", failure.Message); @@ -40,7 +48,9 @@ public async Task CapturedSdkFailuresRetainTheirOriginalDiagnostic() finally { if (!Path.GetFullPath(root).StartsWith(parent + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidOperationException("The diagnostic fixture escaped its owner."); + } Directory.Delete(root, recursive: true); } } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs index fe4e0e171..3da827a55 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs @@ -5,8 +5,8 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Build.Toolchains.Tests; @@ -21,9 +21,11 @@ public void Dispose() { string root = Path.GetFullPath(m_root); string owner = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "InnoToolchainProcessTests")) - + Path.DirectorySeparatorChar; + + Path.DirectorySeparatorChar; if (!root.StartsWith(owner, StringComparison.Ordinal)) + { throw new InvalidOperationException("The process fixture directory escaped its temporary owner."); + } long started = Stopwatch.GetTimestamp(); while (Directory.Exists(root)) { @@ -33,8 +35,8 @@ public void Dispose() return; } catch (IOException exception) when ((exception.HResult is unchecked((int)0x80070020) - or unchecked((int)0x80070021)) - && Stopwatch.GetElapsedTime(started).TotalMilliseconds < C_RETIREMENT_WINDOW_MILLISECONDS) + or unchecked((int)0x80070021)) + && Stopwatch.GetElapsedTime(started).TotalMilliseconds < C_RETIREMENT_WINDOW_MILLISECONDS) { // Process termination does not promise that filesystem observers have released the directory. // Retry only sharing/lock violations; persistent failures and all other errors remain visible. @@ -79,14 +81,16 @@ sleep 120 & using var cancellation = new CancellationTokenSource(); Task running = rawArguments - ? ToolchainEnvironment.RunAsync(executable, string.Join(' ', arguments.Select(Quote)), m_root, cancellation.Token) - : ToolchainEnvironment.RunAsync(executable, arguments, m_root, cancellation.Token); + ? ToolchainEnvironment.RunAsync(executable, string.Join(' ', arguments.Select(Quote)), m_root, cancellation.Token) + : ToolchainEnvironment.RunAsync(executable, arguments, m_root, cancellation.Token); int[] processes = []; try { DateTime deadline = DateTime.UtcNow.AddSeconds(15); while (!File.Exists(marker) && !running.IsCompleted && DateTime.UtcNow < deadline) + { await Task.Delay(25); + } Assert.True(File.Exists(marker), "The process tree did not reach its waiting stage."); processes = File.ReadAllText(marker).Trim().Split(',').Select(int.Parse).ToArray(); Assert.Equal(2, processes.Length); @@ -103,7 +107,9 @@ sleep 120 & foreach (int processId in processes) { if (!IsRunning(processId)) + { continue; + } using Process process = Process.GetProcessById(processId); process.Kill(entireProcessTree: true); } @@ -115,11 +121,19 @@ public async Task RawRunnerRejectsFailedAndAlreadyCanceledTools() { Directory.CreateDirectory(m_root); await Assert.ThrowsAsync(() => ToolchainEnvironment.RunAsync( - "dotnet", "--inno-invalid-option", m_root, CancellationToken.None)); + "dotnet", + "--inno-invalid-option", + m_root, + CancellationToken.None + )); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => ToolchainEnvironment.RunAsync( - "inno-missing-tool", string.Empty, m_root, cancellation.Token)); + "inno-missing-tool", + string.Empty, + m_root, + cancellation.Token + )); } [Theory] @@ -167,9 +181,13 @@ sleep 120 & try { if (standardError) + { Console.SetError(failing); + } else + { Console.SetOut(failing); + } running = ToolchainEnvironment.RunAsync(executable, arguments, m_root, cancellation.Token); IOException failure = await Assert.ThrowsAsync(() => running.WaitAsync(TimeSpan.FromSeconds(10))); @@ -183,9 +201,13 @@ sleep 120 & finally { if (standardError) + { Console.SetError(original); + } else + { Console.SetOut(original); + } cancellation.Cancel(); if (running is not null) { diff --git a/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs b/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs index d24d41d9d..9b67f85a2 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs @@ -8,6 +8,8 @@ public sealed class UnixFileLinksFactAttribute : FactAttribute public UnixFileLinksFactAttribute() { if (OperatingSystem.IsWindows()) + { Skip = "Unix compiler file-link semantics require a Unix filesystem; Windows directory-link rejection is tested separately."; + } } } diff --git a/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs b/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs index bef2465c6..058dd8440 100644 --- a/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs +++ b/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs @@ -1,44 +1,36 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.IO.Compression; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; - +using Xunit; using Inno.Adapter.Content.FileSystem; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Build.Managed; -using Inno.Content; -using Inno.Core.IO; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.MacOSArm64; +using Inno.Build.Managed; using Inno.Build.WindowsX64; -using Inno.Core.Identity; +using Inno.Content; using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Types; - - - - using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; - -using Xunit; -using Inno.Build; using Inno.Testing.SupportPacks; - namespace Inno.Testing.Build; public abstract class BuildPipelineFixture : PlayerSupportPackFixture @@ -54,8 +46,12 @@ public abstract class BuildPipelineFixture : PlayerSupportPackFixture protected readonly SceneWorld m_sceneWorld; protected readonly IDisposable m_sceneWorldScope; - protected BuildPipelineFixture() : base(Directory.EnumerateFiles(AppContext.BaseDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly) - .Where(static path => !IsAuthoringAssembly(Path.GetFileName(path))).ToArray()) + protected BuildPipelineFixture() + : base( + Directory.EnumerateFiles(AppContext.BaseDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly) + .Where(static path => !IsAuthoringAssembly(Path.GetFileName(path))) + .ToArray() + ) { m_projectRoot = Path.Combine(m_root, "Project"); string assetRoot = Path.Combine(m_projectRoot, "Assets"); @@ -65,8 +61,11 @@ protected BuildPipelineFixture() : base(Directory.EnumerateFiles(AppContext.Base Directory.CreateDirectory(pluginRoot); m_engine = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(BuildPipelineFixture).Assembly, GetType().Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(BuildPipelineFixture).Assembly, GetType().Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); m_sceneWorld = new SceneWorld(m_identities, m_engine.types); m_sceneWorldScope = m_sceneWorld.EnterScope(); @@ -82,13 +81,15 @@ protected BuildPipelineFixture() : base(Directory.EnumerateFiles(AppContext.Base AssetPipelineOptions.Create(assetRoot, libraryRoot) with { enableFileSystemWatcher = false - }); + } + ); m_settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.GetFullPath(Path.Combine(m_projectRoot, "Settings.Project.inno"))), m_engine.types, m_engine.serialization, new ProjectId("tests.build"), - AssetSerializationContext.Create(m_assets)); + AssetSerializationContext.Create(m_assets) + ); m_plugins = new PluginEnvironment( m_assets, m_settings, @@ -96,15 +97,23 @@ protected BuildPipelineFixture() : base(Directory.EnumerateFiles(AppContext.Base pluginRoot, libraryRoot, scan, - m_engine.modules.generations); + m_engine.modules.generations + ); m_compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = m_projectRoot, - compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(Path.Combine(Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"), m_projectRoot) + compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment( + Path.Combine( + Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ), + m_projectRoot + ) }, m_assets, - m_plugins); + m_plugins + ); m_pipeline = CreatePipeline(); } @@ -122,46 +131,69 @@ public override void Dispose() protected static BuildProfile CreateProfile( BuildTargetId target, string productName = "Test Game" - ) - => new() - { - applicationId = "tests.game", - productName = productName, - startupScene = "Scenes/Startup.iscene", - target = target - }; + ) => new() + { + applicationId = "tests.game", + productName = productName, + startupScene = "Scenes/Startup.iscene", + target = target + }; protected void SaveStartupScene() { var scene = new GameScene("Startup"); scene.CreateObject("Player"); - Assert.True(m_assets.Save( - AssetPath.Project("Scenes/Startup.iscene"), - SceneAsset.Capture(scene, m_engine.serialization, m_assets))); + Assert.True( + m_assets.Save( + AssetPath.Project("Scenes/Startup.iscene"), + SceneAsset.Capture(scene, m_engine.serialization, m_assets) + ) + ); } protected BuildPipeline CreatePipeline( IPlayerSupportPackProvisioner? provisioner = null, ManagedDeploymentCatalog? managedDeployments = null - ) - => new( - m_assets, - m_plugins, - m_settings, - m_engine.serialization, - m_engine.generations, - m_compiler, - m_supportPackRoot, - [ - new GameBuildTargetBinding(new MacOSArm64GameBuildTarget(new MacOSArm64SupportPackValidator()), - new Inno.Build.Toolchains.Bgfx.Tools.BgfxGameContentCompiler(m_assets, m_engine.serialization, m_engine.types, - Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxIntegration.shaderProfile, [Inno.Rendering.GraphicsApi.Metal], new Inno.Build.Toolchains.Bgfx.Tools.ToolRunner())), - new GameBuildTargetBinding(new WindowsX64GameBuildTarget(new WindowsX64SupportPackValidator()), - new Inno.Build.Toolchains.Bgfx.Tools.BgfxGameContentCompiler(m_assets, m_engine.serialization, m_engine.types, - Inno.Integration.WindowsX64.Bgfx.WindowsX64BgfxIntegration.shaderProfile, [Inno.Rendering.GraphicsApi.Direct3D11, Inno.Rendering.GraphicsApi.Direct3D12, Inno.Rendering.GraphicsApi.Vulkan, Inno.Rendering.GraphicsApi.OpenGL], new Inno.Build.Toolchains.Bgfx.Tools.ToolRunner())) - ], - managedDeployments ?? CreateManagedDeployments(), - provisioner); + ) => new( + m_assets, + m_plugins, + m_settings, + m_engine.serialization, + m_engine.generations, + m_compiler, + m_supportPackRoot, + [ + new GameBuildTargetBinding( + new MacOSArm64GameBuildTarget(new MacOSArm64SupportPackValidator()), + new Inno.Build.Toolchains.Bgfx.Tools.BgfxGameContentCompiler( + m_assets, + m_engine.serialization, + m_engine.types, + Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxIntegration.shaderProfile, + [Inno.Rendering.GraphicsApi.Metal], + new Inno.Build.Toolchains.Bgfx.Tools.ToolRunner() + ) + ), + new GameBuildTargetBinding( + new WindowsX64GameBuildTarget(new WindowsX64SupportPackValidator()), + new Inno.Build.Toolchains.Bgfx.Tools.BgfxGameContentCompiler( + m_assets, + m_engine.serialization, + m_engine.types, + Inno.Integration.WindowsX64.Bgfx.WindowsX64BgfxIntegration.shaderProfile, + [ + Inno.Rendering.GraphicsApi.Direct3D11, + Inno.Rendering.GraphicsApi.Direct3D12, + Inno.Rendering.GraphicsApi.Vulkan, + Inno.Rendering.GraphicsApi.OpenGL + ], + new Inno.Build.Toolchains.Bgfx.Tools.ToolRunner() + ) + ) + ], + managedDeployments ?? CreateManagedDeployments(), + provisioner + ); protected static ManagedDeploymentCatalog CreateManagedDeployments() => new([new FixtureManagedDeploymentCompiler()]); @@ -171,7 +203,9 @@ protected sealed class CommitFailingProgress : IProgress public void Report(BuildProgress value) { if (value.stage == "commit") + { throw new InvalidOperationException("Fixture commit observer failed after publication."); + } } } @@ -181,7 +215,10 @@ public FixtureManagedDeploymentCompiler(IReadOnlyList? runtimeIdentifier { capabilities = new ManagedDeploymentCapabilities( runtimeIdentifiers ?? ["win-x64", "osx-arm64"], - dynamicCode: true, aheadOfTime: false, nativeStaticLinking: false); + dynamicCode: true, + aheadOfTime: false, + nativeStaticLinking: false + ); } public ManagedDeploymentId id => ManagedDeploymentId.coreClr; @@ -205,9 +242,16 @@ public ValueTask CompileAsync( Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(native, destination); } - return ValueTask.FromResult(new ManagedDeploymentResult(id, request.outputDirectory, "fixture-sdk", - Directory.EnumerateFiles(request.outputDirectory, "*", SearchOption.AllDirectories) - .Select(file => Path.GetRelativePath(request.outputDirectory, file)).ToArray())); + return ValueTask.FromResult( + new ManagedDeploymentResult( + id, + request.outputDirectory, + "fixture-sdk", + Directory.EnumerateFiles(request.outputDirectory, "*", SearchOption.AllDirectories) + .Select(file => Path.GetRelativePath(request.outputDirectory, file)) + .ToArray() + ) + ); } } @@ -242,8 +286,7 @@ public async ValueTask ProvisionAsync( } } - protected sealed class TestSupportPackProvisioner(Action provision) - : IPlayerSupportPackProvisioner + protected sealed class TestSupportPackProvisioner(Action provision) : IPlayerSupportPackProvisioner { public int callCount { get; private set; } @@ -262,10 +305,9 @@ public ValueTask ProvisionAsync( protected sealed class BlockingBuildTarget : IGameBuildTarget, IGameContentCompiler { - public TaskCompletionSource started { get; } = new( - TaskCreationOptions.RunContinuationsAsynchronously); - public TaskCompletionSource release { get; } = new( - TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public void Validate(string directory) => new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator().Validate(directory); @@ -278,7 +320,6 @@ protected sealed class BlockingBuildTarget : IGameBuildTarget, IGameContentCompi public string displayName => "Blocking test target"; - public async ValueTask CompileAsync( GameBuildContentContext context, CancellationToken cancellationToken = default diff --git a/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs b/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs index 7487b08f4..14368b0ae 100644 --- a/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs +++ b/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs @@ -11,9 +11,8 @@ public abstract class PlayerSupportPackFixture : IDisposable protected readonly string m_supportPackRoot; private readonly string[] m_referenceAssemblies; - protected PlayerSupportPackFixture() : this([typeof(Inno.Core.Identity.IdentityAllocator).Assembly.Location]) - { - } + protected PlayerSupportPackFixture() + : this([typeof(Inno.Core.Identity.IdentityAllocator).Assembly.Location]) {} protected PlayerSupportPackFixture(string[] referenceAssemblies) { @@ -26,10 +25,18 @@ protected PlayerSupportPackFixture(string[] referenceAssemblies) public virtual void Dispose() { - if (!Path.GetFullPath(m_root).StartsWith(Path.Combine(Path.GetTempPath(), "InnoBuildTests") + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + if (!Path.GetFullPath(m_root) + .StartsWith( + Path.Combine(Path.GetTempPath(), "InnoBuildTests") + Path.DirectorySeparatorChar, + StringComparison.OrdinalIgnoreCase + ) + ) { throw new InvalidOperationException("The support pack fixture escaped its owned directory."); + } if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } protected void CreateSupportPack( @@ -48,10 +55,19 @@ string executable string link = Path.Combine(directory, "PlayerLink"); Directory.CreateDirectory(link); string platform = target == new BuildTargetId("macos-arm64") ? "MacOSArm64" : "WindowsX64"; - File.WriteAllText(Path.Combine(link, "Player.csproj"), - "Inno.Player." + platform + ""); - foreach (string source in new[] { "Program.cs", platform + "PlayerComposition.cs", platform + "PlayerContentSource.cs", "global.json" }) + File.WriteAllText( + Path.Combine(link, "Player.csproj"), + "Inno.Player." + platform + "" + ); + foreach (string source in new[] + { + "Program.cs", + platform + "PlayerComposition.cs", + platform + "PlayerContentSource.cs", + "global.json" + }) { File.WriteAllText(Path.Combine(link, source), "fixture input"); + } string analyzers = Path.Combine(link, "Analyzers"); Directory.CreateDirectory(analyzers); File.WriteAllText(Path.Combine(analyzers, "Inno.Runtime.Generators.dll"), "fixture analyzer"); @@ -59,17 +75,19 @@ string executable string linkReferences = Path.Combine(link, "References"); Directory.CreateDirectory(linkReferences); foreach (string source in Directory.EnumerateFiles(references, "*.dll")) + { File.Copy(source, Path.Combine(linkReferences, Path.GetFileName(source))); + } File.WriteAllText(Path.Combine(linkReferences, "Inno.Player.Runtime.dll"), "fixture runtime"); File.WriteAllText(Path.Combine(linkReferences, "BGCS.Runtime.dll"), "fixture interop"); File.WriteAllBytes(Path.Combine(link, executable), [0x49, 0x4E, 0x4E, 0x4F]); string native = Path.Combine(directory, "native"); Directory.CreateDirectory(native); string[] required = target == new BuildTargetId("macos-arm64") - ? ["libbgfx-shared-lib-release.dylib", "SDL3-release.dylib", "libminiaudio-release.dylib", - "libinno-text-release.dylib", "libinno-ui-release.dylib"] - : ["bgfx-shared-lib-release.dll", "SDL3-release.dll", "miniaudio-release.dll", - "inno-text-release.dll", "inno-ui-release.dll"]; + ? ["libbgfx-shared-lib-release.dylib", "SDL3-release.dylib", "libminiaudio-release.dylib", + "libinno-text-release.dylib", "libinno-ui-release.dylib"] + : ["bgfx-shared-lib-release.dll", "SDL3-release.dll", "miniaudio-release.dll", + "inno-text-release.dll", "inno-ui-release.dll"]; string linkNative = Path.Combine(link, "native"); Directory.CreateDirectory(linkNative); foreach (string file in required) @@ -78,10 +96,13 @@ string executable File.WriteAllBytes(Path.Combine(linkNative, file), CreateNativeImage(target)); } IPlayerSupportPackValidator validator = target == new BuildTargetId("macos-arm64") - ? new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator() - : new Inno.Build.WindowsX64.WindowsX64SupportPackValidator(); + ? new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator() + : new Inno.Build.WindowsX64.WindowsX64SupportPackValidator(); using PlayerSupportPackLease published = new PlayerSupportPackCatalog(m_supportPackRoot).PublishAsync( - target, directory, validator).AsTask().GetAwaiter().GetResult(); + target, + directory, + validator + ).AsTask().GetAwaiter().GetResult(); } protected string GetSupportPackDirectory(BuildTargetId target) @@ -122,5 +143,4 @@ protected static bool IsAuthoringAssembly(string name) || name.Contains("Inno.Scripting.Compiler", StringComparison.OrdinalIgnoreCase) || name.Contains("Inno.Assets.Pipeline", StringComparison.OrdinalIgnoreCase) || name.Contains("Inno.Plugins.Authoring", StringComparison.OrdinalIgnoreCase); - } diff --git a/tests/content/Inno.Content.Tests/PackContentStoreTests.cs b/tests/content/Inno.Content.Tests/PackContentStoreTests.cs index 1cd2fd605..53150fff0 100644 --- a/tests/content/Inno.Content.Tests/PackContentStoreTests.cs +++ b/tests/content/Inno.Content.Tests/PackContentStoreTests.cs @@ -5,9 +5,9 @@ using System.Linq; using System.Security.Cryptography; using System.Threading.Tasks; +using Xunit; using Inno.Core.Serialization; using Inno.Runtime; -using Xunit; namespace Inno.Content.Tests; @@ -20,8 +20,10 @@ public async Task IndependentReadersRetainPackAfterStoreAndLeaseClose() using SerializationGeneration generation = host.serialization.CaptureGeneration(); byte[] firstBytes = Enumerable.Range(0, 100_000).Select(static value => (byte)value).ToArray(); byte[] secondBytes = Enumerable.Range(0, 90_000).Select(static value => (byte)(value * 7)).ToArray(); - (MemoryStream pack, ContentPackDescriptor descriptor) = CreatePack(generation, - new Dictionary { ["a"] = firstBytes, ["b"] = secondBytes }); + (MemoryStream pack, ContentPackDescriptor descriptor) = CreatePack( + generation, + new Dictionary { ["a"] = firstBytes, ["b"] = secondBytes } + ); PackContentStore store = ContentPackReader.Open(pack, descriptor, generation); ContentReadLease first = store.Acquire(new ContentKey("a")); ContentReadLease second = store.Acquire(new ContentKey("b")); @@ -31,8 +33,10 @@ public async Task IndependentReadersRetainPackAfterStoreAndLeaseClose() store.Dispose(); Assert.Throws(() => store.Acquire(new ContentKey("a"))); Assert.Throws(() => first.OpenRead()); - await Task.WhenAll(Task.Run(() => Assert.Equal(firstBytes, Read(inputA))), - Task.Run(() => Assert.Equal(secondBytes, Read(inputB)))); + await Task.WhenAll( + Task.Run(() => Assert.Equal(firstBytes, Read(inputA))), + Task.Run(() => Assert.Equal(secondBytes, Read(inputB))) + ); using Stream anotherB = second.OpenRead(); Assert.Equal(secondBytes, Read(anotherB)); second.Dispose(); @@ -55,8 +59,11 @@ public void MalformedPacksAreRejectedAndTheirInputIsDisposed(string fault) { using EngineHost host = CreateHost(); using SerializationGeneration generation = host.serialization.CaptureGeneration(); - (MemoryStream pack, ContentPackDescriptor descriptor) = CreatePack(generation, - new Dictionary { ["a"] = [1, 2, 3] }, fault); + (MemoryStream pack, ContentPackDescriptor descriptor) = CreatePack( + generation, + new Dictionary { ["a"] = [1, 2, 3] }, + fault + ); Assert.Throws(() => ContentPackReader.Open(pack, descriptor, generation)); Assert.False(pack.CanRead); } @@ -67,17 +74,28 @@ public void BudgetsAndCancellationPrecedeStorePublication() using EngineHost host = CreateHost(); using SerializationGeneration generation = host.serialization.CaptureGeneration(); var (pack, descriptor) = CreatePack(generation, new Dictionary { ["a"] = [1, 2, 3] }); - Assert.Throws(() => ContentPackReader.Open(pack, descriptor, generation, - new ContentReadLimits(entryBytes: 2))); + Assert.Throws(() => ContentPackReader.Open( + pack, + descriptor, + generation, + new ContentReadLimits(entryBytes: 2) + )); var (canceled, canceledDescriptor) = CreatePack(generation, new Dictionary { ["a"] = [] }); - Assert.Throws(() => ContentPackReader.Open(canceled, canceledDescriptor, generation, - cancellationToken: new System.Threading.CancellationToken(true))); + Assert.Throws(() => ContentPackReader.Open( + canceled, + canceledDescriptor, + generation, + cancellationToken: new System.Threading.CancellationToken(true) + )); Assert.False(canceled.CanRead); } - internal static EngineHost CreateHost() => new EngineHostBuilder().UseMetadataSources( - new StaticAssemblyCatalogSource([], [typeof(object).Assembly]), new StaticTypeCatalogSource([]), - new StaticSerializationMetadataSource([])).Build(); + internal static EngineHost CreateHost() + => new EngineHostBuilder().UseMetadataSources( + new StaticAssemblyCatalogSource([], [typeof(object).Assembly]), + new StaticTypeCatalogSource([]), + new StaticSerializationMetadataSource([]) + ).Build(); internal static ( MemoryStream pack, @@ -87,20 +105,26 @@ ContentPackDescriptor descriptor Dictionary payloads, string fault = "" ) { - List entries = payloads.Select(pair => new ContentEntry(new ContentKey(pair.Key), + List entries = payloads.Select(pair => new ContentEntry( + new ContentKey(pair.Key), pair.Value.Length + (fault == "length" ? 1 : 0), - fault == "payload" ? new string('A', 64) : Convert.ToHexString(SHA256.HashData(pair.Value)))).ToList(); + fault == "payload" ? new string('A', 64) : Convert.ToHexString(SHA256.HashData(pair.Value)) + )).ToList(); MemoryStream output = new(); using (ZipArchive archive = new(output, ZipArchiveMode.Create, true)) { foreach (var pair in payloads) { if (fault == "missing") + { continue; + } string name = fault == "traversal" ? "../a" : pair.Key; ZipArchiveEntry entry = archive.CreateEntry(name); if (fault == "link") + { entry.ExternalAttributes = 0xA000 << 16; + } using Stream destination = entry.Open(); destination.Write(pair.Value); } diff --git a/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs b/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs index 218e38ac3..aaa1519a4 100644 --- a/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs +++ b/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs @@ -14,15 +14,21 @@ private static async Task Main(string[] arguments) using ContentTestStore source = ContentTestStore.FromDirectory(arguments[0]); Console.WriteLine("ready"); if (await Console.In.ReadLineAsync() != "prepare") + { return 2; - using FileContentStore store = await FileContentPreparation.PrepareAsync(source, - new FileContentCacheOptions(arguments[1])); + } + using FileContentStore store = await FileContentPreparation.PrepareAsync( + source, + new FileContentCacheOptions(arguments[1]) + ); using ContentReadLease lease = store.Acquire(new ContentKey("pinned.bin")); using Stream reader = lease.OpenRead(); string cache = Path.Combine(arguments[1], "Content", source.descriptor.contentHash); Console.WriteLine(File.ReadAllText(Path.Combine(cache, "current"))); if (await Console.In.ReadLineAsync() != "release") + { return 3; + } byte[] bytes = new byte[checked((int)lease.entry.length)]; reader.ReadExactly(bytes); Console.WriteLine(Convert.ToHexString(bytes)); diff --git a/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs b/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs index 61053e1c7..461cf83c4 100644 --- a/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs +++ b/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs @@ -24,10 +24,17 @@ public sealed class ContentTestStore : IRuntimeContentStore public ContentTestStore(IEnumerable> payloads) { m_payloads = payloads.ToDictionary(static pair => pair.Key, static pair => (byte[])pair.Value.Clone()); - index = new ContentPackIndex(m_payloads.Select(static pair => new ContentEntry( - pair.Key, pair.Value.LongLength, Convert.ToHexString(SHA256.HashData(pair.Value))))); - string identity = string.Join('\n', index.entries.Select(static entry => - entry.key + ":" + entry.length + ":" + entry.contentHash)); + index = new ContentPackIndex( + m_payloads.Select(static pair => new ContentEntry( + pair.Key, + pair.Value.LongLength, + Convert.ToHexString(SHA256.HashData(pair.Value)) + )) + ); + string identity = string.Join( + '\n', + index.entries.Select(static entry => (entry.key + ":" + entry.length + ":" + entry.contentHash)) + ); string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity))); descriptor = new ContentPackDescriptor(hash, $"content-{hash}.pack"); } @@ -48,9 +55,13 @@ public ContentTestStore(IEnumerable> payloads) /// A caller-owned memory provider usable after the directory has been removed. /// public static ContentTestStore FromDirectory(string directory) - => new(Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).Select(path => - new KeyValuePair(new ContentKey(Path.GetRelativePath(directory, path) - .Replace('\\', '/')), File.ReadAllBytes(path)))); + => new( + Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).Select(path => + new KeyValuePair( + new ContentKey(Path.GetRelativePath(directory, path).Replace('\\', '/')), + File.ReadAllBytes(path) + )) + ); /// /// Injects a provider corruption while preserving its previously declared inventory. @@ -67,7 +78,9 @@ ReadOnlySpan bytes ) { ObjectDisposedException.ThrowIf(m_disposed, this); if (!m_payloads.ContainsKey(key)) + { throw new KeyNotFoundException(key.ToString()); + } m_payloads[key] = bytes.ToArray(); } @@ -76,9 +89,11 @@ public ContentReadLease Acquire(ContentKey key) { ObjectDisposedException.ThrowIf(m_disposed, this); if (!index.TryGetEntry(key, out ContentEntry? entry)) + { throw new KeyNotFoundException(key.ToString()); + } byte[] bytes = m_payloads[key]; - return new ContentReadLease(entry!, () => new MemoryStream(bytes, writable: false), static () => { }); + return new ContentReadLease(entry!, () => new MemoryStream(bytes, writable: false), static () => {}); } /// diff --git a/tests/core/Inno.Core.Collections.Tests/DependencyGraphTests.cs b/tests/core/Inno.Core.Collections.Tests/DependencyGraphTests.cs index 0ab73a7c5..d9e794013 100644 --- a/tests/core/Inno.Core.Collections.Tests/DependencyGraphTests.cs +++ b/tests/core/Inno.Core.Collections.Tests/DependencyGraphTests.cs @@ -2,10 +2,8 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; - -using Inno.Core.Collections; - using Xunit; +using Inno.Core.Collections; namespace Inno.Core.Collections.Tests; @@ -159,22 +157,29 @@ public async Task ConcurrentReaders_ObserveOnlyCompleteSnapshots() { IReadOnlyList dependencies = graph.GetDependencies(10); Assert.True( - dependencies.SequenceEqual(new[] { 1, 2, 3 }) || - dependencies.SequenceEqual(new[] { 4, 5, 6 })); + dependencies.SequenceEqual(new[] { 1, 2, 3 }) + || dependencies.SequenceEqual(new[] { 4, 5, 6 }) + ); } })) .ToArray(); for (int i = 0; i < 100; i++) + { graph.ReplaceDependencies(10, i % 2 == 0 ? [4, 5, 6] : [1, 2, 3]); + } await Task.WhenAll(readers); } - private static int IndexOf(IReadOnlyList values, string value) - { + private static int IndexOf( + IReadOnlyList values, + string value + ) { for (int i = 0; i < values.Count; i++) { if (values[i] == value) + { return i; + } } return -1; } diff --git a/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs b/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs index a943014d1..5afa8aa3a 100644 --- a/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs +++ b/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs @@ -1,10 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; - -using Inno.Core.Collections; - using Xunit; +using Inno.Core.Collections; namespace Inno.Core.Collections.Tests; @@ -15,8 +13,10 @@ private sealed class Item public string name { get; } public int Category { get; } - public Item(string name, int category) - { + public Item( + string name, + int category + ) { this.name = name; Category = category; } @@ -72,8 +72,7 @@ public void DefineKey_Unique_ThrowsOnDuplicateValueFromDifferentItems() store.Add(a).Set(key, 10); - InvalidOperationException ex = Assert.Throws(() => - store.Add(b).Set(key, 10)); + InvalidOperationException ex = Assert.Throws(() => store.Add(b).Set(key, 10)); Assert.Contains("Duplicate key", ex.Message); } @@ -85,7 +84,7 @@ public void DefineKey_Unique_AllowsResettingSameValueOnSameItem() var key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); var a = new Item("A", 1); - + store.Add(a).Set(key, 10); store.Add(a).Set(key, 20); @@ -125,7 +124,8 @@ public void OrderedQueryUsesSmallestIndexedCandidateSetAndReturnsAnIsolatedSnaps IndexedObjectKey orderKey = store.DefineKey( "order", IndexedObjectKeyFlags.Ordered | IndexedObjectKeyFlags.Unique, - Comparer.Default); + Comparer.Default + ); var unrelated = new Item("Unrelated", 2); var last = new Item("Last", 1); var excluded = new Item("Excluded", 1); @@ -340,5 +340,4 @@ public void AllFast_IsFailFast_WhenStoreMutates() Assert.Throws(() => enumerator.MoveNext()); } - } diff --git a/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs b/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs index ffd77f6a0..db3a4f3f9 100644 --- a/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs +++ b/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs @@ -1,10 +1,8 @@ using System; using System.Collections; using System.Collections.Generic; - -using Inno.Core.Coroutines; - using Xunit; +using Inno.Core.Coroutines; namespace Inno.Core.Coroutines.Tests; @@ -82,12 +80,22 @@ public void PendingEnumeratorIsDisposedWithoutBeingAdvanced(bool ownerStop) var owner = new object(); int moves = 0; int disposed = 0; - CoroutineHandle handle = scheduler.StartCoroutine(owner, - new Probe(() => { moves++; return true; }, () => null, () => disposed++)); + CoroutineHandle handle = scheduler.StartCoroutine( + owner, + new Probe(() => + { + moves++; + return true; + }, () => null, () => disposed++) + ); if (ownerStop) + { scheduler.StopAllCoroutines(owner); + } else + { scheduler.Dispose(); + } Assert.False(handle.isValid); Assert.Equal(0, moves); Assert.Equal(1, disposed); @@ -103,13 +111,18 @@ public void CallbackFaultRetiresItsStackAndDoesNotSkipOtherCoroutines(string sta var failure = new InvalidOperationException(stage); int disposed = 0; int survivorTicks = 0; - CoroutineHandle failed = scheduler.StartCoroutine(new Probe( - () => stage == "move" ? throw failure : true, - () => stage == "current" ? throw failure : new WaitUntil(() => throw failure), - () => disposed++)); + CoroutineHandle failed = scheduler.StartCoroutine( + new Probe( + () => stage == "move" ? throw failure : true, + () => stage == "current" ? throw failure : new WaitUntil(() => throw failure), + () => disposed++ + ) + ); scheduler.StartCoroutine(Loop(() => survivorTicks++)); if (stage == "wait") + { scheduler.Tick(0); + } AggregateException error = Assert.Throws(() => scheduler.Tick(0)); Assert.Contains(failure, error.InnerExceptions); Assert.False(failed.isValid); @@ -133,7 +146,9 @@ public void CleanupFailuresDoNotPreventParentOrOtherCoroutineCleanup(bool dispos scheduler.Tick(0); AggregateException error; if (dispose) + { error = Assert.Throws(scheduler.Dispose); + } else { scheduler.StopAllCoroutines(); @@ -161,17 +176,25 @@ public void SelfOwnerStopDefersDisposeUntilMoveNextReturnsAndPreservesOtherCorou bool moving = false; int disposed = 0; int ticks = 0; - CoroutineHandle self = scheduler.StartCoroutine(owner, new Probe( - () => - { - moving = true; - scheduler.StopAllCoroutines(owner); - Assert.Equal(0, disposed); - moving = false; - return true; - }, - () => throw new Exception("A retired coroutine must not read Current."), - () => { Assert.False(moving); disposed++; })); + CoroutineHandle self = scheduler.StartCoroutine( + owner, + new Probe( + () => + { + moving = true; + scheduler.StopAllCoroutines(owner); + Assert.Equal(0, disposed); + moving = false; + return true; + }, + () => throw new Exception("A retired coroutine must not read Current."), + () => + { + Assert.False(moving); + disposed++; + } + ) + ); CoroutineHandle other = survivor ? scheduler.StartCoroutine(Loop(() => ticks++)) : default; scheduler.Tick(0); scheduler.Tick(0); @@ -187,7 +210,7 @@ public void StopEarlierOwnerDuringCallbackDoesNotSkipFollowingCoroutine() using var scheduler = new CoroutineScheduler(); var owner = new object(); int following = 0; - scheduler.StartCoroutine(owner, Loop(() => { })); + scheduler.StartCoroutine(owner, Loop(() => {})); scheduler.StartCoroutine(Loop(() => scheduler.StopAllCoroutines(owner))); scheduler.StartCoroutine(Loop(() => following++)); scheduler.Tick(0); @@ -201,10 +224,24 @@ public void ReentrantDisposeRetiresExecutingEnumeratorAfterItsCallback() using var scheduler = new CoroutineScheduler(); bool moving = false; int disposed = 0; - scheduler.StartCoroutine(new Probe( - () => { moving = true; scheduler.Dispose(); Assert.Equal(0, disposed); moving = false; return true; }, - () => null, - () => { Assert.False(moving); disposed++; })); + scheduler.StartCoroutine( + new Probe( + () => + { + moving = true; + scheduler.Dispose(); + Assert.Equal(0, disposed); + moving = false; + return true; + }, + () => null, + () => + { + Assert.False(moving); + disposed++; + } + ) + ); scheduler.Tick(0); Assert.Equal(1, disposed); Assert.Throws(() => scheduler.Tick(0)); @@ -216,12 +253,15 @@ public void ReentrantCleanupCommandsAreDrainedWithoutDoubleDisposal() using var scheduler = new CoroutineScheduler(); var owner = new object(); int disposed = 0; - scheduler.StartCoroutine(owner, new Probe(() => true, () => null, () => - { - disposed++; - scheduler.StartCoroutine(owner, new Probe(() => true, () => null, () => disposed++)); - scheduler.StopAllCoroutines(owner); - })); + scheduler.StartCoroutine( + owner, + new Probe(() => true, () => null, () => + { + disposed++; + scheduler.StartCoroutine(owner, new Probe(() => true, () => null, () => disposed++)); + scheduler.StopAllCoroutines(owner); + }) + ); scheduler.StopAllCoroutines(owner); Assert.Equal(2, disposed); scheduler.Tick(0); @@ -233,7 +273,13 @@ public void RecursiveTickIsRejectedBeforeAdvancingAnotherFrame() { using var scheduler = new CoroutineScheduler(); int disposed = 0; - scheduler.StartCoroutine(new Probe(() => { scheduler.Tick(0); return true; }, () => null, () => disposed++)); + scheduler.StartCoroutine( + new Probe(() => + { + scheduler.Tick(0); + return true; + }, () => null, () => disposed++) + ); AggregateException error = Assert.Throws(() => scheduler.Tick(0)); Assert.IsType(Assert.Single(error.InnerExceptions)); Assert.Equal(1, disposed); @@ -261,16 +307,30 @@ public void OwnerStopFromCurrentOrWaitPredicateCannotResumeRetiredState(bool wai var owner = new object(); int disposed = 0; int moves = 0; - CoroutineHandle handle = scheduler.StartCoroutine(owner, new Probe( - () => { moves++; return true; }, - () => - { - if (wait) - return new WaitUntil(() => { scheduler.StopAllCoroutines(owner); return true; }); - scheduler.StopAllCoroutines(owner); - return null; - }, - () => disposed++)); + CoroutineHandle handle = scheduler.StartCoroutine( + owner, + new Probe( + () => + { + moves++; + return true; + }, + () => + { + if (wait) + { + return new WaitUntil(() => + { + scheduler.StopAllCoroutines(owner); + return true; + }); + } + scheduler.StopAllCoroutines(owner); + return null; + }, + () => disposed++ + ) + ); scheduler.Tick(0); scheduler.Tick(0); Assert.False(handle.isValid); @@ -331,17 +391,24 @@ public void QueuedStopFromCoroutineDoesNotCorruptActiveDispatch(string stop) int disposed = 0; int following = 0; CoroutineHandle self = default; - self = scheduler.StartCoroutine(new Probe( - () => - { - if (stop == "handle") - Assert.True(scheduler.StopCoroutine(self)); - else - scheduler.StopAllCoroutines(); - return true; - }, - () => null, - () => disposed++)); + self = scheduler.StartCoroutine( + new Probe( + () => + { + if (stop == "handle") + { + Assert.True(scheduler.StopCoroutine(self)); + } + else + { + scheduler.StopAllCoroutines(); + } + return true; + }, + () => null, + () => disposed++ + ) + ); scheduler.StartCoroutine(Loop(() => following++)); scheduler.Tick(0); Assert.Equal(1, following); @@ -367,8 +434,11 @@ Action dispose ) : IEnumerator, IDisposable { public object? Current => current(); + public bool MoveNext() => move(); + public void Reset() => throw new NotSupportedException(); + public void Dispose() => dispose(); } } diff --git a/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs b/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs index b4884164b..dec5af81f 100644 --- a/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs +++ b/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs @@ -3,10 +3,8 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; - -using Inno.Core.Coroutines; - using Xunit; +using Inno.Core.Coroutines; namespace Inno.Core.Coroutines.Tests; @@ -261,7 +259,10 @@ public void ConcurrentStopByHandle_IsStable() handles[i] = scheduler.StartCoroutine(Routine()); } - Parallel.For(0, count, i => { scheduler.StopCoroutine(handles[i]); }); + Parallel.For(0, count, i => + { + scheduler.StopCoroutine(handles[i]); + }); scheduler.Tick(0.016f); scheduler.Tick(0.016f); @@ -298,7 +299,7 @@ IEnumerator Routine() public void HandleIsValid_BecomesFalseAfterStop() { using var scheduler = new CoroutineScheduler(); - CoroutineHandle handle = scheduler.StartCoroutine(Loop(() => { })); + CoroutineHandle handle = scheduler.StartCoroutine(Loop(() => {})); Assert.True(handle.isValid); Assert.True(scheduler.StopCoroutine(handle)); @@ -328,7 +329,7 @@ public void StartCoroutine_AfterDispose_ThrowsAndHandleCannotBeCreated() using var scheduler = new CoroutineScheduler(); scheduler.Dispose(); - Assert.Throws(() => scheduler.StartCoroutine(Loop(() => { }))); + Assert.Throws(() => scheduler.StartCoroutine(Loop(() => {}))); } private static IEnumerator Loop(Action onTick) @@ -341,11 +342,10 @@ private static IEnumerator Loop(Action onTick) } [MethodImpl(MethodImplOptions.NoInlining)] - private static (WeakReference owner, WeakReference routine) StopOwnedCoroutine( - CoroutineScheduler scheduler) + private static (WeakReference owner, WeakReference routine) StopOwnedCoroutine(CoroutineScheduler scheduler) { var owner = new object(); - IEnumerator routine = Loop(static () => { }); + IEnumerator routine = Loop(static () => {}); CoroutineHandle handle = scheduler.StartCoroutine(owner, routine); scheduler.Tick(0.016f); diff --git a/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs b/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs index 01a4496e4..3061252cb 100644 --- a/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs +++ b/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs @@ -1,10 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; - -using Inno.Core.Diagnostics; - using Xunit; +using Inno.Core.Diagnostics; namespace Inno.Core.Diagnostics.Tests; @@ -50,10 +48,8 @@ public void Set_ReplacesTheCompleteReportOwnedByOneCallerGroup() Diagnostics.Set( C_COMPILATION_DIAGNOSTICS, - Diagnostic.Error( - "CS1001", - "Expected identifier.", - new DiagnosticLocation("Assets/Test.cs", 4, 2))); + Diagnostic.Error("CS1001", "Expected identifier.", new DiagnosticLocation("Assets/Test.cs", 4, 2)) + ); DiagnosticReport firstReport = Assert.Single(sink.reports); Diagnostic first = Assert.Single(firstReport.diagnostics); Assert.Equal("CS1001", first.code); @@ -61,7 +57,8 @@ public void Set_ReplacesTheCompleteReportOwnedByOneCallerGroup() Diagnostics.Set( C_COMPILATION_DIAGNOSTICS, - Diagnostic.Warning("CS0168", "Variable is declared but never used.")); + Diagnostic.Warning("CS0168", "Variable is declared but never used.") + ); DiagnosticReport replacementReport = Assert.Single(sink.reports); Diagnostic replacement = Assert.Single(replacementReport.diagnostics); @@ -95,12 +92,14 @@ public void Set_TargetedReportsRemainIndependent() m_assetId, C_IMPORT_DIAGNOSTICS, Diagnostic.Error("A", "First asset"), - displayName: "Assets/First.asset"); + displayName: "Assets/First.asset" + ); Diagnostics.Set( otherAssetId, C_IMPORT_DIAGNOSTICS, Diagnostic.Warning("B", "Second asset"), - displayName: "Assets/Second.asset"); + displayName: "Assets/Second.asset" + ); Diagnostics.Clear(m_assetId, C_IMPORT_DIAGNOSTICS); @@ -229,20 +228,16 @@ private sealed class ProbeSink : IDiagnosticSink internal IReadOnlyList reports => m_reports.Values.ToArray(); - public void Replace(DiagnosticReport report) - => m_reports[report.source.id] = report; + public void Replace(DiagnosticReport report) => m_reports[report.source.id] = report; - public void Clear(DiagnosticSource source) - => m_reports.Remove(source.id); + public void Clear(DiagnosticSource source) => m_reports.Remove(source.id); } private sealed class FailingSink : IDiagnosticSink { - public void Replace(DiagnosticReport report) - => throw new InvalidOperationException("Expected test failure."); + public void Replace(DiagnosticReport report) => throw new InvalidOperationException("Expected test failure."); - public void Clear(DiagnosticSource source) - => throw new InvalidOperationException("Expected test failure."); + public void Clear(DiagnosticSource source) => throw new InvalidOperationException("Expected test failure."); } private sealed class CountingSink : IDiagnosticSink @@ -251,17 +246,14 @@ private sealed class CountingSink : IDiagnosticSink public void Replace(DiagnosticReport report) => replaceCount++; - public void Clear(DiagnosticSource source) { } + public void Clear(DiagnosticSource source) {} } private static class OtherProducer { internal static void SetCompilation() - => Diagnostics.Set( - C_COMPILATION_DIAGNOSTICS, - Diagnostic.Error("B", "Other caller")); + => Diagnostics.Set(C_COMPILATION_DIAGNOSTICS, Diagnostic.Error("B", "Other caller")); - internal static void ClearCompilation() - => Diagnostics.Clear(C_COMPILATION_DIAGNOSTICS); + internal static void ClearCompilation() => Diagnostics.Clear(C_COMPILATION_DIAGNOSTICS); } } diff --git a/tests/core/Inno.Core.Events.Tests/EventDispatchObservationTests.cs b/tests/core/Inno.Core.Events.Tests/EventDispatchObservationTests.cs index b5f0a16a3..10d943067 100644 --- a/tests/core/Inno.Core.Events.Tests/EventDispatchObservationTests.cs +++ b/tests/core/Inno.Core.Events.Tests/EventDispatchObservationTests.cs @@ -1,8 +1,7 @@ using System; using System.Collections.Generic; - -using Inno.Core.Events; using Xunit; +using Inno.Core.Events; namespace Inno.Core.Events.Tests; @@ -64,7 +63,9 @@ public void RecursivelyQueuedObservationWaitsForTheNextFlush() { observed.Add(evnt); if (ReferenceEquals(evnt, first)) + { dispatcher.Enqueue(second); + } }; dispatcher.Enqueue(first); diff --git a/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs b/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs index 63af6e5cf..7e51db18d 100644 --- a/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs +++ b/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs @@ -1,11 +1,9 @@ using System; using System.Collections.Generic; -using System.Threading.Tasks; using System.Threading; - -using Inno.Core.Events; - +using System.Threading.Tasks; using Xunit; +using Inno.Core.Events; namespace Inno.Core.Events.Tests; @@ -81,7 +79,7 @@ public void DisposeHub_MakesHubInvalidAndPreventsFurtherListen() hub.Dispose(); Assert.False(hub.isValid); - Assert.Throws(() => hub.Listen(_ => { })); + Assert.Throws(() => hub.Listen(_ => {})); } [Fact] @@ -137,7 +135,10 @@ public void ListenOnce_ConcurrentEmit_StillInvokesOnlyOneTime() var count = 0; hub.ListenOnce(_ => Interlocked.Increment(ref count)); - Parallel.For(0, iterations, i => { dispatcher.Emit(new ProbeEvent(i)); }); + Parallel.For(0, iterations, i => + { + dispatcher.Emit(new ProbeEvent(i)); + }); Assert.Equal(1, count); } @@ -284,7 +285,10 @@ public void ConcurrentEmit_AcrossThreads_IsStable() hubA.Listen(_ => Interlocked.Increment(ref countA)); hubB.Listen(_ => Interlocked.Increment(ref countB)); - Parallel.For(0, iterations, i => { dispatcher.Emit(new ProbeEvent(i)); }); + Parallel.For(0, iterations, i => + { + dispatcher.Emit(new ProbeEvent(i)); + }); Assert.Equal(iterations, countA); Assert.Equal(iterations, countB); @@ -312,7 +316,10 @@ public void ConcurrentEmit_WithHandleInHub_StopsOnlyCurrentHub() hubA.Listen(_ => Interlocked.Increment(ref hubASecond)); hubB.Listen(_ => Interlocked.Increment(ref hubBCount)); - Parallel.For(0, iterations, i => { dispatcher.Emit(new ProbeEvent(i)); }); + Parallel.For(0, iterations, i => + { + dispatcher.Emit(new ProbeEvent(i)); + }); Assert.Equal(iterations, hubAFirst); Assert.Equal(iterations / 2, hubASecond); @@ -341,7 +348,10 @@ public void ConcurrentEmit_WithHandleInGlobal_StopsFollowingHubs() hubA.Listen(_ => Interlocked.Increment(ref hubASecond)); hubB.Listen(_ => Interlocked.Increment(ref hubBCount)); - Parallel.For(0, iterations, i => { dispatcher.Emit(new ProbeEvent(i)); }); + Parallel.For(0, iterations, i => + { + dispatcher.Emit(new ProbeEvent(i)); + }); Assert.Equal(iterations, hubAFirst); Assert.Equal(iterations / 2, hubASecond); diff --git a/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs b/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs index d4d9cbf86..ea4833b95 100644 --- a/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs @@ -1,7 +1,6 @@ using System; using System.Threading; using System.Threading.Tasks; - using Xunit; namespace Inno.Core.Execution.Tests; @@ -48,7 +47,9 @@ public void SuspensionMasksAndRestoresParent() object value = new(); using IDisposable outer = slot.Enter(value); using (slot.Suspend()) + { Assert.False(slot.TryGet(out _)); + } Assert.Same(value, slot.current); } diff --git a/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs b/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs index 339cd21a1..af45f3ea5 100644 --- a/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs @@ -16,7 +16,16 @@ public async Task CapacityRejectsBeforeUserCodeAndCompletedWorkReleasesAdmission var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); Task operation = owner.RunAsync(_ => new ValueTask(ready.Task)); bool invoked = false; - Assert.Throws(() => { _ = owner.RunAsync(_ => { invoked = true; return ValueTask.FromResult(0); }); }); + Assert.Throws( + () => + { + _ = owner.RunAsync(_ => + { + invoked = true; + return ValueTask.FromResult(0); + }); + } + ); Assert.False(invoked); ready.SetResult(iteration); Assert.Equal(iteration, await operation); diff --git a/tests/core/Inno.Core.Execution.Tests/LifetimeScopeTests.cs b/tests/core/Inno.Core.Execution.Tests/LifetimeScopeTests.cs index 4def07892..8ca2d048c 100644 --- a/tests/core/Inno.Core.Execution.Tests/LifetimeScopeTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/LifetimeScopeTests.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; - using Xunit; namespace Inno.Core.Execution.Tests; @@ -14,12 +13,22 @@ public void FailureBeforePendingRemainsObservableAfterRetry() bool ready = false; int failingReleaseCount = 0; var lifetime = new LifetimeScope(); - lifetime.Own(new Resource(() => - { - if (!ready) - throw new RetirementPendingException("pending"); - })); - lifetime.Own(new Resource(() => { failingReleaseCount++; throw new InvalidOperationException("release failed"); })); + lifetime.Own( + new Resource(() => + { + if (!ready) + { + throw new RetirementPendingException("pending"); + } + }) + ); + lifetime.Own( + new Resource(() => + { + failingReleaseCount++; + throw new InvalidOperationException("release failed"); + }) + ); Assert.Throws(lifetime.Dispose); ready = true; AggregateException error = Assert.Throws(lifetime.Dispose); @@ -33,10 +42,12 @@ public void RetirementDeadlineRemainsFaultedAndDoesNotReleasePendingDependencies { var barrier = new RetirementBarrier("test owner", TimeSpan.FromTicks(1)); Assert.Throws(() => barrier.TryComplete( - () => throw new RetirementPendingException("worker still running"))); + () => throw new RetirementPendingException("worker still running") + )); bool released = false; RetirementTimeoutException error = Assert.Throws( - () => barrier.TryComplete(() => released = true)); + () => barrier.TryComplete(() => released = true) + ); Assert.Contains("test owner", error.Message); Assert.False(released); } @@ -46,7 +57,7 @@ public void RetirementBarrierRetriesOnOwnerThreadAndDoesNotRetainCompletedCallba { var barrier = new RetirementBarrier("test owner"); Assert.False(barrier.TryComplete(() => throw new RetirementPendingException("pending"))); - Assert.True(barrier.TryComplete(() => { })); + Assert.True(barrier.TryComplete(() => {})); Assert.True(barrier.TryComplete(() => throw new InvalidOperationException("must not run"))); } @@ -56,7 +67,13 @@ public void RetirementAttemptsEveryResourceInReverseOrder() List released = []; var lifetime = new LifetimeScope(); lifetime.Own(new Resource(() => released.Add(1))); - lifetime.Own(new Resource(() => { released.Add(2); throw new InvalidOperationException("expected"); })); + lifetime.Own( + new Resource(() => + { + released.Add(2); + throw new InvalidOperationException("expected"); + }) + ); lifetime.Own(new Resource(() => released.Add(3))); Assert.Throws(lifetime.Dispose); Assert.Equal(new[] { 3, 2, 1 }, released); diff --git a/tests/core/Inno.Core.Execution.Tests/OwnerThreadExecutionTests.cs b/tests/core/Inno.Core.Execution.Tests/OwnerThreadExecutionTests.cs index b099472b5..65c743cab 100644 --- a/tests/core/Inno.Core.Execution.Tests/OwnerThreadExecutionTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/OwnerThreadExecutionTests.cs @@ -37,15 +37,18 @@ public void AsynchronousContinuationsAndSendReturnToTheCallingThread() { int owner = Environment.CurrentManagedThreadId; SynchronizationContext? original = SynchronizationContext.Current; - Assert.Equal(42, OwnerThreadExecution.Run(async () => - { - SynchronizationContext context = SynchronizationContext.Current!; - await Task.Run(() => context.Send(_ => Assert.Equal(owner, Environment.CurrentManagedThreadId), null)); - Assert.Equal(owner, Environment.CurrentManagedThreadId); - await Task.Delay(10); - Assert.Equal(owner, Environment.CurrentManagedThreadId); - return 42; - })); + Assert.Equal( + 42, + OwnerThreadExecution.Run(async () => + { + SynchronizationContext context = SynchronizationContext.Current!; + await Task.Run(() => context.Send(_ => Assert.Equal(owner, Environment.CurrentManagedThreadId), null)); + Assert.Equal(owner, Environment.CurrentManagedThreadId); + await Task.Delay(10); + Assert.Equal(owner, Environment.CurrentManagedThreadId); + return 42; + }) + ); Assert.Same(original, SynchronizationContext.Current); } @@ -55,8 +58,11 @@ public void CompletedOperationsFailuresAndCancellationRestoreThePreviousContext( SynchronizationContext? original = SynchronizationContext.Current; Assert.Equal(1, OwnerThreadExecution.Run(() => Task.FromResult(1))); var failure = new InvalidOperationException("Expected owner failure."); - Assert.Same(failure, Assert.Throws(() => - OwnerThreadExecution.Run(() => Task.FromException(failure)))); + Assert.Same( + failure, + Assert.Throws(() => + OwnerThreadExecution.Run(() => Task.FromException(failure))) + ); Assert.Throws(() => OwnerThreadExecution.Run(() => Task.FromCanceled(new CancellationToken(canceled: true)))); Assert.Throws(() => OwnerThreadExecution.Run(null!)); @@ -67,16 +73,19 @@ public void CompletedOperationsFailuresAndCancellationRestoreThePreviousContext( public void CompletedOperationsDrainCallbacksPostedByAlreadyQueuedWork() { int callbacks = 0; - Assert.Equal(7, OwnerThreadExecution.Run(() => - { - SynchronizationContext context = SynchronizationContext.Current!; - context.Post(_ => + Assert.Equal( + 7, + OwnerThreadExecution.Run(() => { - callbacks++; - context.Post(_ => callbacks++, null); - }, null); - return Task.FromResult(7); - })); + SynchronizationContext context = SynchronizationContext.Current!; + context.Post(_ => + { + callbacks++; + context.Post(_ => callbacks++, null); + }, null); + return Task.FromResult(7); + }) + ); Assert.Equal(2, callbacks); } } diff --git a/tests/core/Inno.Core.Execution.Tests/RetirementFailureTests.cs b/tests/core/Inno.Core.Execution.Tests/RetirementFailureTests.cs index cf7d46c6b..4107cdff5 100644 --- a/tests/core/Inno.Core.Execution.Tests/RetirementFailureTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/RetirementFailureTests.cs @@ -32,10 +32,20 @@ public void LifetimeRetainsPendingResourceAndEarlierErrorsAcrossWrappedRetries() bool ready = false; bool dependencyReleased = false; var ordinary = new InvalidOperationException("completed sibling"); - var failure = new InvalidOperationException("resource context", new AggregateException( - ordinary, new AggregateException(new RetirementPendingException("callback remains active")))); + var failure = new InvalidOperationException( + "resource context", + new AggregateException( + ordinary, + new AggregateException(new RetirementPendingException("callback remains active")) + ) + ); lifetime.Own(new Resource(() => dependencyReleased = true)); - lifetime.Own(new Resource(() => { if (!ready) throw failure; })); + lifetime.Own( + new Resource(() => + { + if (!ready) throw failure; + }) + ); Assert.Same(failure, Assert.Throws(lifetime.Dispose)); Assert.Same(failure, Assert.Throws(lifetime.Dispose)); Assert.False(dependencyReleased); @@ -54,7 +64,7 @@ public void BarrierRetainsOrdinarySiblingsUntilThePendingWorkCompletes() var failure = new AggregateException(ordinary, new RetirementPendingException("pending")); Assert.False(barrier.TryComplete(() => throw failure)); Assert.False(barrier.TryComplete(() => throw failure)); - AggregateException completed = Assert.Throws(() => barrier.TryComplete(() => { })); + AggregateException completed = Assert.Throws(() => barrier.TryComplete(() => {})); Assert.Same(ordinary, Assert.Single(completed.InnerExceptions)); Assert.True(barrier.TryComplete(() => throw new InvalidOperationException("must not run twice"))); } @@ -66,7 +76,7 @@ public void NestedTimeoutRemainsTerminalAndPreservesEveryFailure() var timeout = new RetirementTimeoutException("inner deadline"); var failure = new AggregateException(new InvalidOperationException("first"), timeout); Assert.Same(failure, Assert.Throws(() => barrier.TryComplete(() => throw failure))); - Assert.Same(failure, Assert.Throws(() => barrier.TryComplete(() => { }))); + Assert.Same(failure, Assert.Throws(() => barrier.TryComplete(() => {}))); } [Fact] @@ -75,9 +85,10 @@ public void NewTimeoutKeepsTheCompleteWrappedCause() var barrier = new RetirementBarrier("deadline", TimeSpan.FromTicks(1)); var failure = new InvalidOperationException("context", new RetirementPendingException("pending callback")); RetirementTimeoutException timeout = Assert.Throws( - () => barrier.TryComplete(() => throw failure)); + () => barrier.TryComplete(() => throw failure) + ); Assert.Same(failure, timeout.InnerException); - Assert.Same(timeout, Assert.Throws(() => barrier.TryComplete(() => { }))); + Assert.Same(timeout, Assert.Throws(() => barrier.TryComplete(() => {}))); } [Theory] @@ -90,9 +101,13 @@ public async Task CompletedTaskOrCancellationPendingDoesNotAuthorizeDependencyRe lifetime.Own(new Resource(() => dependencyReleased = true)); var failure = new AggregateException(new RetirementPendingException("unfinished owner outside completed task")); if (cancellation) + { lifetime.cancellationToken.Register(() => throw failure); + } else + { lifetime.Track(Task.FromException(failure)); + } Exception first = Assert.ThrowsAny(lifetime.Dispose); Assert.NotNull(RetirementPendingException.Find(first)); Assert.Same(first, Assert.ThrowsAny(lifetime.Dispose)); @@ -168,12 +183,14 @@ public async Task ConcurrentDisposalCannotReleaseTheSameResourceTwice() using var finish = new ManualResetEventSlim(); var lifetime = new LifetimeScope(); int released = 0; - lifetime.Own(new Resource(() => - { - Interlocked.Increment(ref released); - started.Set(); - Assert.True(finish.Wait(TimeSpan.FromSeconds(5))); - })); + lifetime.Own( + new Resource(() => + { + Interlocked.Increment(ref released); + started.Set(); + Assert.True(finish.Wait(TimeSpan.FromSeconds(5))); + }) + ); Task disposal = Task.Run(lifetime.Dispose); try { @@ -197,11 +214,13 @@ public void ReentrantDisposalKeepsTheCurrentOwnerUntilItsCallbackReturns() { var lifetime = new LifetimeScope(); int released = 0; - lifetime.Own(new Resource(() => - { - Assert.Throws(lifetime.Dispose); - released++; - })); + lifetime.Own( + new Resource(() => + { + Assert.Throws(lifetime.Dispose); + released++; + }) + ); lifetime.Dispose(); Assert.Equal(1, released); } @@ -218,8 +237,13 @@ public async Task AsyncOperationIsOwnedBeforeItsSynchronousPrefixCanReenter(bool { Assert.False(lifetime.isQuiescent); if (dispose) + { Assert.Throws(lifetime.Dispose); - else lifetime.Cancel(); + } + else + { + lifetime.Cancel(); + } Assert.False(released); return ValueTask.FromResult(42); }); diff --git a/tests/core/Inno.Core.Graphs.Tests/GraphDocumentTests.cs b/tests/core/Inno.Core.Graphs.Tests/GraphDocumentTests.cs index da198f5d9..70165c7d4 100644 --- a/tests/core/Inno.Core.Graphs.Tests/GraphDocumentTests.cs +++ b/tests/core/Inno.Core.Graphs.Tests/GraphDocumentTests.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using Inno.Core.Graphs; using Xunit; +using Inno.Core.Graphs; namespace Inno.Core.Graphs.Tests; @@ -42,11 +42,15 @@ public void RepeatedLookupAndCollectionAccessDoNotAllocate() { var document = new GraphDocument(); for (int index = 0; index < 2_000; index++) + { document.AddNode(new(new("node-" + index), "test.node")); + } GraphNodeRecord node = document.nodes[^1]; GraphNodeId id = node.id; for (int index = 0; index < 1_000; index++) + { _ = document.FindNode(id); + } long before = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < 10_000; index++) diff --git a/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs b/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs index a34d3e934..fb9dbe8f4 100644 --- a/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs +++ b/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs @@ -1,13 +1,13 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; -using Inno.Extensibility.Modules; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Core.Graphs.Tests; @@ -16,7 +16,9 @@ public sealed class GraphValidatorTests : IDisposable private readonly string m_testRoot = Path.Combine( Path.GetTempPath(), "InnoCoreGraphsTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; @@ -24,7 +26,9 @@ public sealed class GraphValidatorTests : IDisposable public GraphValidatorTests() { m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(GraphValidatorTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(GraphValidatorTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -35,7 +39,9 @@ public void Dispose() m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_testRoot)) + { Directory.Delete(m_testRoot, recursive: true); + } } [Fact] @@ -57,7 +63,8 @@ public void Validate_WithDirectedConversion_IsValid() GraphValidationResult result = GraphValidator.Validate( document, new Resolver(m_serialization), - new Conversion()); + new Conversion() + ); Assert.True(result.isValid); } @@ -115,8 +122,10 @@ public void RemoveNode_RemovesConnectedEdges() Assert.Empty(document.edges); } - private GraphDocument CreateConnectedDocument(string outputType, string inputType) - { + private GraphDocument CreateConnectedDocument( + string outputType, + string inputType + ) { GraphDocument document = new(); GraphNodeRecord source = CreateNode("source", outputType, outputType); GraphNodeRecord destination = CreateNode("destination", inputType, inputType); @@ -126,24 +135,33 @@ private GraphDocument CreateConnectedDocument(string outputType, string inputTyp return document; } - private GraphNodeRecord CreateNode(string id, string inputType, string outputType) - { + private GraphNodeRecord CreateNode( + string id, + string inputType, + string outputType + ) { GraphNodeRecord node = new(new GraphNodeId(id), $"node.{id}"); node.SetValue("inputType", GraphSerializedValue.From(inputType, m_serialization)); node.SetValue("outputType", GraphSerializedValue.From(outputType, m_serialization)); return node; } - private static GraphEdgeRecord CreateEdge(string id, GraphNodeId source, GraphNodeId destination) - => new( - new GraphEdgeId(id), - new GraphEndpoint(source, new GraphPortId("out")), - new GraphEndpoint(destination, new GraphPortId("in"))); + private static GraphEdgeRecord CreateEdge( + string id, + GraphNodeId source, + GraphNodeId destination + ) => new( + new GraphEdgeId(id), + new GraphEndpoint(source, new GraphPortId("out")), + new GraphEndpoint(destination, new GraphPortId("in")) + ); private sealed class Resolver(SerializationRegistry serialization) : IGraphNodeDefinitionResolver { - public bool TryResolve(string definitionId, out GraphNodeDefinition? definition) - { + public bool TryResolve( + string definitionId, + out GraphNodeDefinition? definition + ) { if (!definitionId.StartsWith("node.", System.StringComparison.Ordinal)) { definition = null; @@ -157,16 +175,17 @@ public bool TryResolve(string definitionId, out GraphNodeDefinition? definition) private sealed class Definition( string id, - SerializationRegistry serialization) : GraphNodeDefinition(id, id, "Tests") + SerializationRegistry serialization + ) : GraphNodeDefinition(id, id, "Tests") { public override IReadOnlyList GetPorts(GraphNodeRecord node) { string inputType = node.TryGetValue("inputType", out GraphSerializedValue? input) - ? input!.Deserialize(serialization)! - : "float"; + ? input!.Deserialize(serialization)! + : "float"; string outputType = node.TryGetValue("outputType", out GraphSerializedValue? output) - ? output!.Deserialize(serialization)! - : "float"; + ? output!.Deserialize(serialization)! + : "float"; return [ @@ -178,7 +197,9 @@ public override IReadOnlyList GetPorts(GraphNodeRecord node private sealed class Conversion : IGraphTypeConversion { - public bool CanConvert(string sourceTypeId, string destinationTypeId) - => sourceTypeId == "float" && destinationTypeId == "vector3"; + public bool CanConvert( + string sourceTypeId, + string destinationTypeId + ) => sourceTypeId == "float" && destinationTypeId == "vector3"; } } diff --git a/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs b/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs index e9c69367c..337d74409 100644 --- a/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs +++ b/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs @@ -6,7 +6,6 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; - using Xunit; namespace Inno.Core.IO.Tests; @@ -73,7 +72,9 @@ public async Task ConcurrentCandidatesPublishExactlyOneCompleteFile() string destination = Path.Combine(m_root, "document-" + round); string[] candidates = Enumerable.Range(0, count).Select(index => destination + ".candidate-" + index).ToArray(); foreach (string candidate in candidates) + { File.WriteAllBytes(candidate, Enumerable.Repeat((byte)Array.IndexOf(candidates, candidate), 64 * 1024).ToArray()); + } int winner = -1; int successes = 0; using var ready = new CountdownEvent(count); @@ -101,7 +102,9 @@ public async Task ConcurrentCandidatesPublishExactlyOneCompleteFile() Assert.Equal(64 * 1024, bytes.Length); Assert.All(bytes, value => Assert.Equal((byte)winner, value)); for (int index = 0; index < count; index++) + { Assert.Equal(index != winner, File.Exists(candidates[index])); + } } } @@ -109,11 +112,26 @@ public async Task ConcurrentCandidatesPublishExactlyOneCompleteFile() public async Task IndependentCreatorsAndAReaderObserveOnlyTheCompleteWinningPayload() { string project = Path.Combine(m_root, "Publisher.csproj"); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), new XElement("OutputType", "Exe"), - new XElement("ImplicitUsings", "disable")), - new XElement("ItemGroup", new XElement("Reference", new XAttribute("Include", "Inno.Core.IO"), - new XElement("HintPath", typeof(AtomicFile).Assembly.Location))))).Save(project); + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement( + "PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("OutputType", "Exe"), + new XElement("ImplicitUsings", "disable") + ), + new XElement( + "ItemGroup", + new XElement( + "Reference", + new XAttribute("Include", "Inno.Core.IO"), + new XElement("HintPath", typeof(AtomicFile).Assembly.Location) + ) + ) + ) + ).Save(project); File.WriteAllText(Path.Combine(m_root, "Program.cs"), """ using System; using System.IO; @@ -164,7 +182,9 @@ public async Task IndependentCreatorsAndAReaderObserveOnlyTheCompleteWinningPayl Assert.InRange(winner[0], (byte)1, (byte)8); Assert.All(winner, value => Assert.Equal(winner[0], value)); for (int read = 0; read < 16; read++) + { Assert.Equal(winner, document.Read()); + } await Task.WhenAll(creators.Select(process => process.WaitForExitAsync())).WaitAsync(TimeSpan.FromSeconds(30)); Assert.Single(creators.Where(process => process.ExitCode == 0)); Assert.All(creators, process => Assert.True(process.ExitCode is 0 or 17)); @@ -175,7 +195,9 @@ public async Task IndependentCreatorsAndAReaderObserveOnlyTheCompleteWinningPayl foreach (Process process in creators) { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } await process.WaitForExitAsync(); process.Dispose(); } @@ -186,8 +208,10 @@ public async Task IndependentCreatorsAndAReaderObserveOnlyTheCompleteWinningPayl private Process Start(params string[] arguments) { - string sdk = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string sdk = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var start = new ProcessStartInfo(sdk) { WorkingDirectory = m_root, @@ -197,7 +221,9 @@ private Process Start(params string[] arguments) RedirectStandardError = true }; foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } return Process.Start(start) ?? throw new InvalidOperationException("The SDK fixture did not start."); } diff --git a/tests/core/Inno.Core.IO.Tests/ByteDocumentStoreTests.cs b/tests/core/Inno.Core.IO.Tests/ByteDocumentStoreTests.cs index 7b64575b9..a70e1a23e 100644 --- a/tests/core/Inno.Core.IO.Tests/ByteDocumentStoreTests.cs +++ b/tests/core/Inno.Core.IO.Tests/ByteDocumentStoreTests.cs @@ -37,7 +37,9 @@ public void FilesDistinguishAbsentAndEmptyAndReplaceCompleteDocuments() finally { if (Directory.Exists(root)) + { Directory.Delete(root, true); + } } } @@ -52,18 +54,22 @@ public void FilesReadTheCompleteDocumentWhileADeleteAccessHandleRemainsOpen() { File.WriteAllBytes(path, expected); using (var renameHandle = new FileStream( - path, - FileMode.Open, - FileAccess.Read, - FileShare.Read | FileShare.Delete, - 4096, - FileOptions.DeleteOnClose)) - { + path, + FileMode.Open, + FileAccess.Read, + FileShare.Read | FileShare.Delete, + 4096, + FileOptions.DeleteOnClose + )) { if (OperatingSystem.IsWindows()) + { Assert.ThrowsAny(() => File.ReadAllBytes(path)); + } var store = new FileByteDocumentStore(path); for (int read = 0; read < 16; read++) + { Assert.Equal(expected, store.Read()); + } Assert.True(File.Exists(path)); } Assert.False(File.Exists(path)); diff --git a/tests/core/Inno.Core.IO.Tests/CoordinatedFileLeaseTests.cs b/tests/core/Inno.Core.IO.Tests/CoordinatedFileLeaseTests.cs index 21f3f704f..7f109622f 100644 --- a/tests/core/Inno.Core.IO.Tests/CoordinatedFileLeaseTests.cs +++ b/tests/core/Inno.Core.IO.Tests/CoordinatedFileLeaseTests.cs @@ -18,8 +18,12 @@ public async Task WaitingAndHoldingParticipantsKeepTheOwnerGateUntilTheLeafIsRel string leaf = Path.Combine(m_root, "generation.lock"); using FileLease producer = await FileLease.AcquireAsync(leaf, TimeSpan.Zero); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5)); - Task waiting = CoordinatedFileLease.AcquireAsync(owner, leaf, - Timeout.InfiniteTimeSpan, cancellationToken: cancellation.Token).AsTask(); + Task waiting = CoordinatedFileLease.AcquireAsync( + owner, + leaf, + Timeout.InfiniteTimeSpan, + cancellationToken: cancellation.Token + ).AsTask(); Assert.False(waiting.IsCompleted); await Assert.ThrowsAsync(async () => { @@ -33,7 +37,9 @@ await Assert.ThrowsAsync(async () => }); acquired.Dispose(); using (FileLease retirement = await FileLease.AcquireAsync(owner, TimeSpan.Zero)) + { File.Delete(leaf); + } Assert.True(File.Exists(owner)); using CoordinatedFileLease next = await CoordinatedFileLease.AcquireAsync(owner, leaf, TimeSpan.Zero); } @@ -60,8 +66,7 @@ public async Task SharedReadersPreventOwnerRetirementAndExclusiveLeafAccess() using CoordinatedFileLease second = await CoordinatedFileLease.AcquireAsync(owner, leaf, TimeSpan.Zero, shared: true); await Assert.ThrowsAsync(async () => await CoordinatedFileLease.AcquireAsync(owner, leaf, TimeSpan.Zero)); - await Assert.ThrowsAsync(async () => - await FileLease.AcquireAsync(owner, TimeSpan.Zero)); + await Assert.ThrowsAsync(async () => await FileLease.AcquireAsync(owner, TimeSpan.Zero)); } [Fact] @@ -78,6 +83,8 @@ await Assert.ThrowsAnyAsync(async () => public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs b/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs index b0b98ae2d..9bc63c8c5 100644 --- a/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs +++ b/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs @@ -2,8 +2,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Core.IO.Tests; @@ -60,13 +60,17 @@ public async Task InvalidRequestsAndPriorCancellationHaveNoFilesystemEffects() await Assert.ThrowsAsync(() => FileLease.AcquireAsync(path, TimeSpan.FromSeconds(-2)).AsTask()); using CancellationTokenSource cancellation = new(); cancellation.Cancel(); - await Assert.ThrowsAnyAsync(() => FileLease.AcquireAsync(path, TimeSpan.Zero, cancellation.Token).AsTask()); + await Assert.ThrowsAnyAsync( + () => FileLease.AcquireAsync(path, TimeSpan.Zero, cancellation.Token).AsTask() + ); Assert.False(Directory.Exists(m_root)); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs b/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs index 84c25c5ef..8aae21770 100644 --- a/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs +++ b/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs @@ -1,12 +1,11 @@ using System; using System.Diagnostics; using System.IO; -using System.Runtime.ExceptionServices; using System.Linq; +using System.Runtime.ExceptionServices; using System.Runtime.Versioning; using System.Text; using System.Threading; - using Xunit; using Xunit.Abstractions; @@ -14,10 +13,7 @@ namespace Inno.Core.IO.Tests; public sealed class FileSystemSafetyTests : IDisposable { - private readonly string m_root = Path.Combine( - Path.GetTempPath(), - "InnoCoreIoTests", - Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoCoreIoTests", Guid.NewGuid().ToString("N")); private readonly ITestOutputHelper m_output; @@ -74,9 +70,7 @@ public void PathBoundaryRejectsAbsoluteAndParentTraversalPaths() { Assert.Throws(() => PathBoundary.Resolve(m_root, Path.Combine(m_root, "absolute"))); Assert.Throws(() => PathBoundary.Resolve(m_root, "../escape")); - Assert.Equal( - Path.Combine(m_root, "Assets", "item.inno"), - PathBoundary.Resolve(m_root, "Assets/item.inno")); + Assert.Equal(Path.Combine(m_root, "Assets", "item.inno"), PathBoundary.Resolve(m_root, "Assets/item.inno")); } [Fact] @@ -156,9 +150,13 @@ public void DirectoryInstallPriorCancellationPreservesBothOwners(bool existing) Assert.Equal("current", File.ReadAllText(Path.Combine(candidate, "current.txt"))); if (existing) + { Assert.Equal("previous", File.ReadAllText(Path.Combine(destination, "previous.txt"))); + } else + { Assert.False(Directory.Exists(Path.GetDirectoryName(destination))); + } Assert.Empty(Directory.EnumerateDirectories(m_root, "*.backup-*", SearchOption.AllDirectories)); } @@ -168,7 +166,9 @@ public void DirectoryInstallPriorCancellationPreservesBothOwners(bool existing) public void DirectoryInstallCancellationRestoresThePreviousTreeDuringABlockedRename() { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Directory.CreateDirectory(Path.Combine(m_root, "candidate")).FullName; string destination = Directory.CreateDirectory(Path.Combine(m_root, "destination")).FullName; string file = Path.Combine(candidate, "value.txt"); @@ -177,13 +177,20 @@ public void DirectoryInstallCancellationRestoresThePreviousTreeDuringABlockedRen using var reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); using var cancellation = new CancellationTokenSource(); bool evacuated = false; - ObserveBlockedRename(() => { - evacuated = !Directory.Exists(destination); - cancellation.Cancel(); - }, () => { - var failure = Assert.ThrowsAny(() => AtomicDirectory.Install(candidate, destination, cancellation.Token)); - Assert.Equal(cancellation.Token, failure.CancellationToken); - }); + ObserveBlockedRename( + () => + { + evacuated = !Directory.Exists(destination); + cancellation.Cancel(); + }, + () => + { + var failure = Assert.ThrowsAny( + () => AtomicDirectory.Install(candidate, destination, cancellation.Token) + ); + Assert.Equal(cancellation.Token, failure.CancellationToken); + } + ); Assert.True(evacuated); Assert.Equal("previous", File.ReadAllText(Path.Combine(destination, "previous.txt"))); Assert.Equal("current", File.ReadAllText(file)); @@ -204,21 +211,32 @@ public void DirectoryInstallCancellationRestoresThePreviousTreeDuringABlockedRen private void VerifyBlockedCancellation(bool expireWindow) { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Directory.CreateDirectory(Path.Combine(m_root, "candidate")).FullName; string destination = Path.Combine(m_root, "published"); string file = Path.Combine(candidate, "value.txt"); File.WriteAllText(file, "complete"); using var reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); using var cancellation = new CancellationTokenSource(); - ObserveBlockedRename(() => { - cancellation.Cancel(); - if (expireWindow) - Thread.Sleep(TimeSpan.FromMilliseconds(2100)); - }, () => { - var failure = Assert.ThrowsAny(() => AtomicDirectory.Publish(candidate, destination, cancellation.Token)); - Assert.Equal(cancellation.Token, failure.CancellationToken); - }); + ObserveBlockedRename( + () => + { + cancellation.Cancel(); + if (expireWindow) + { + Thread.Sleep(TimeSpan.FromMilliseconds(2100)); + } + }, + () => + { + var failure = Assert.ThrowsAny( + () => AtomicDirectory.Publish(candidate, destination, cancellation.Token) + ); + Assert.Equal(cancellation.Token, failure.CancellationToken); + } + ); Assert.Equal("complete", File.ReadAllText(file)); Assert.False(Directory.Exists(destination)); } @@ -229,7 +247,9 @@ private void VerifyBlockedCancellation(bool expireWindow) public void DirectoryPublicationToleratesATemporaryWindowsReaderWithoutDeleteSharing() { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Directory.CreateDirectory(Path.Combine(m_root, "candidate")).FullName; string destination = Path.Combine(m_root, "published"); string file = Path.Combine(candidate, "value.txt"); @@ -247,7 +267,9 @@ public void DirectoryPublicationToleratesATemporaryWindowsReaderWithoutDeleteSha public void PersistentReaderPreservesCandidateAndReturnsWindowsError() { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Directory.CreateDirectory(Path.Combine(m_root, "candidate")).FullName; string destination = Path.Combine(m_root, "published"); string file = Path.Combine(candidate, "value.txt"); @@ -289,7 +311,9 @@ void Observe( FirstChanceExceptionEventArgs args ) { if (Environment.CurrentManagedThreadId != thread || blocked >= 0 || !IsSharingError(args.Exception)) + { return; + } blocked = clock.ElapsedMilliseconds; hresult = args.Exception.HResult; onBlocked(); @@ -303,7 +327,9 @@ FirstChanceExceptionEventArgs args finally { AppDomain.CurrentDomain.FirstChanceException -= Observe; - m_output.WriteLine($"Rename worker started at 0 ms, denied at {blocked} ms, intervention completed at {resumed} ms, exited at {clock.ElapsedMilliseconds} ms, HRESULT 0x{hresult:X8}."); + m_output.WriteLine( + $"Rename worker started at 0 ms, denied at {blocked} ms, intervention completed at {resumed} ms, exited at {clock.ElapsedMilliseconds} ms, HRESULT 0x{hresult:X8}." + ); } Assert.True(blocked >= 0, "Expected an actual Windows sharing failure on the publishing thread."); } @@ -313,7 +339,9 @@ FirstChanceExceptionEventArgs args public void DirectoryCleanupFailurePreservesTheCompleteCommittedCandidate() { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Path.Combine(m_root, "candidate"); string destination = Path.Combine(m_root, "destination"); @@ -325,7 +353,9 @@ public void DirectoryCleanupFailurePreservesTheCompleteCommittedCandidate() File.SetAttributes(lockedFile, FileAttributes.ReadOnly); try { - DirectoryCleanupException failure = Assert.Throws(() => AtomicDirectory.Install(candidate, destination)); + DirectoryCleanupException failure = Assert.Throws( + () => AtomicDirectory.Install(candidate, destination) + ); Assert.Contains("installed", failure.Message, StringComparison.OrdinalIgnoreCase); Assert.Equal("current", File.ReadAllText(Path.Combine(destination, "current.txt"))); @@ -338,7 +368,9 @@ public void DirectoryCleanupFailurePreservesTheCompleteCommittedCandidate() finally { foreach (string retained in Directory.EnumerateFiles(m_root, "locked.txt", SearchOption.AllDirectories)) + { File.SetAttributes(retained, FileAttributes.Normal); + } } } @@ -365,7 +397,9 @@ public void DirectoryInstallRejectsOverlappingTreesBeforeChangingEitherOwner() public void DirectoryInstallRestoresThePreviousTreeWhenTheCandidateCannotMove() { if (!OperatingSystem.IsWindows()) + { return; + } string candidate = Path.Combine(m_root, "candidate"); string destination = Path.Combine(m_root, "destination"); @@ -398,6 +432,8 @@ public void PathBoundaryAcceptsChildrenOfAVolumeRoot() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs b/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs index cf9e94fe2..f2a95f618 100644 --- a/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs +++ b/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs @@ -31,7 +31,9 @@ public void Dispose() { Assert.False(input.CanRead); if (++releases == 1) + { throw new IOException("Expected retryable release."); + } } } } diff --git a/tests/core/Inno.Core.IO.Tests/PhysicalPathResolverTests.cs b/tests/core/Inno.Core.IO.Tests/PhysicalPathResolverTests.cs index d164496a2..41ed17369 100644 --- a/tests/core/Inno.Core.IO.Tests/PhysicalPathResolverTests.cs +++ b/tests/core/Inno.Core.IO.Tests/PhysicalPathResolverTests.cs @@ -21,7 +21,9 @@ public void ReadingResolutionDoesNotCreateMissingEntriesOrGrantOwnership() Assert.Equal(resolved, resolver.Resolve(file)); Assert.Equal(resolved, new PhysicalPathResolver().Resolve(resolved)); for (string? entry = resolved; entry is not null; entry = Path.GetDirectoryName(entry)) + { Assert.False(File.GetAttributes(entry).HasFlag(FileAttributes.ReparsePoint), entry); + } string owner = Path.Combine(Path.GetDirectoryName(resolved)!, "Owned"); Assert.Throws(() => PathBoundary.RequireContained(owner, resolved)); Assert.False(Directory.Exists(owner)); @@ -34,6 +36,8 @@ public void ReadingResolutionDoesNotCreateMissingEntriesOrGrantOwnership() public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs b/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs index d927a4932..21850dc2e 100644 --- a/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs +++ b/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs @@ -1,6 +1,6 @@ using System; -using Inno.Core.Identity; using Xunit; +using Inno.Core.Identity; namespace Inno.Core.Identity.Tests; @@ -8,20 +8,15 @@ public sealed class IdentityAllocatorTests { private readonly IdentityAllocator m_allocator = new(); - private static void AssertRuntimeIdNotNull(IdentityObject target) - => Assert.NotNull(target.identity.runtimeId); + private static void AssertRuntimeIdNotNull(IdentityObject target) => Assert.NotNull(target.identity.runtimeId); - private static void AssertRuntimeIdIsNull(IdentityObject target) - => Assert.Null(target.identity.runtimeId); + private static void AssertRuntimeIdIsNull(IdentityObject target) => Assert.Null(target.identity.runtimeId); - private static int UnpackSlot(int runtimeId) - => runtimeId & 0x000F_FFFF; + private static int UnpackSlot(int runtimeId) => runtimeId & 0x000F_FFFF; - private static int UnpackGeneration(int runtimeId) - => (runtimeId >> 20) & 0x0000_0FFF; + private static int UnpackGeneration(int runtimeId) => (runtimeId >> 20) & 0x0000_0FFF; - private static Identity GetIdentity(IdentityObject target) - => target.identity; + private static Identity GetIdentity(IdentityObject target) => target.identity; private WeakReference CreateRegisteredEntity(out int runtimeId) { @@ -31,13 +26,9 @@ private WeakReference CreateRegisteredEntity(out int runtimeId) return new WeakReference(entity); } - private sealed class Entity : IdentityObject - { - } + private sealed class Entity : IdentityObject; - private sealed class UnrelatedEntity : IdentityObject - { - } + private sealed class UnrelatedEntity : IdentityObject; [Fact] public void GetIdentity_DoesNotAutoRegisterObject() @@ -156,8 +147,7 @@ void SuccessfulHandler(IdentityObject removed) m_allocator.ObjectUnregistered += SuccessfulHandler; try { - AggregateException exception = Assert.Throws( - () => m_allocator.Unregister(entity)); + AggregateException exception = Assert.Throws(() => m_allocator.Unregister(entity)); Assert.Single(exception.InnerExceptions); Assert.Equal(1, successfulHandlers); @@ -210,7 +200,6 @@ public void Get_ReturnsNull_ForInvalidLookupKeys() [Fact] public void RegisteredIdentity_DoesNotPreventGarbageCollection() { - int runtimeId; WeakReference weakEntity; diff --git a/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs b/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs index c4607c1ca..56a78082d 100644 --- a/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs +++ b/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs @@ -2,10 +2,8 @@ using System.Diagnostics; using System.Threading; using Xunit; - using Inno.Core.Jobs; - namespace Inno.Core.JobsSystem.Tests; public sealed class JobSystemPerformanceTests @@ -30,7 +28,8 @@ public void SameScheduleFlow_MoreWorkersIsFasterThanSingleWorker() Assert.True( multiWorkerBest < oneWorkerBest, - $"Expected same schedule flow to be faster with more workers. oneWorker={oneWorkerBest.TotalMilliseconds:F2}ms, multiWorker={multiWorkerBest.TotalMilliseconds:F2}ms, workers={multiWorkerCount}"); + $"Expected same schedule flow to be faster with more workers. oneWorker={oneWorkerBest.TotalMilliseconds:F2}ms, multiWorker={multiWorkerBest.TotalMilliseconds:F2}ms, workers={multiWorkerCount}" + ); } [Fact] @@ -53,7 +52,8 @@ public void WorkStealingScheduleCompleteAll_IsFasterThanSingleThread() Assert.True( multiBest < singleBest, - $"Expected work-stealing to be faster. single={singleBest.TotalMilliseconds:F2}ms, multi={multiBest.TotalMilliseconds:F2}ms, workers={workerCount}"); + $"Expected work-stealing to be faster. single={singleBest.TotalMilliseconds:F2}ms, multi={multiBest.TotalMilliseconds:F2}ms, workers={workerCount}" + ); } [Fact] @@ -77,7 +77,8 @@ public void WorkStealingParallelFor_IsFasterThanSingleThread() Assert.True( multiBest < singleBest, - $"Expected work-stealing parallel-for to be faster. single={singleBest.TotalMilliseconds:F2}ms, multi={multiBest.TotalMilliseconds:F2}ms, workers={workerCount}"); + $"Expected work-stealing parallel-for to be faster. single={singleBest.TotalMilliseconds:F2}ms, multi={multiBest.TotalMilliseconds:F2}ms, workers={workerCount}" + ); } private static JobScheduler CreateWorkStealing(int workerCount) diff --git a/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs b/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs index 584fad7da..113330a6b 100644 --- a/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs +++ b/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs @@ -4,10 +4,8 @@ using System.Threading; using System.Threading.Tasks; using Xunit; - using Inno.Core.Jobs; - namespace Inno.Core.JobsSystem.Tests; public sealed class JobSystemBehaviorTests @@ -22,11 +20,17 @@ public void FrameAdmissionRemainsAtomicUnderRepeatedInvalidAndOversizedRequests( for (int frame = 0; frame < 256; frame++) { jobs.BeginFrame(); - Assert.Throws(() => jobs.Schedule(_ => { }, null, new JobHandle[] { default })); + Assert.Throws(() => jobs.Schedule(_ => {}, null, new JobHandle[] { default })); Assert.Equal(0, jobs.statistics.frameJobs); - Assert.Throws(() => jobs.ParallelFor(8, 1, (_, _) => Interlocked.Increment(ref completed))); + Assert.Throws(() => jobs.ParallelFor(8, 1, ( + _, + _ + ) => Interlocked.Increment(ref completed))); Assert.Equal(0, jobs.statistics.frameJobs); - for (int index = 0; index < 4; index++) jobs.Schedule(() => Interlocked.Increment(ref completed)); + for (int index = 0; index < 4; index++) + { + jobs.Schedule(() => Interlocked.Increment(ref completed)); + } jobs.EndFrame(); Assert.Equal(0, jobs.statistics.frameJobs); } @@ -42,7 +46,10 @@ public void PendingMainThreadCallbackRemainsOwnedUntilRetry(JobExecutionMode mod { using var jobs = new JobScheduler(mode, new JobSchedulerOptions { workerCount = 1, mainThreadDrainBudget = 1 }); int attempts = 0; - jobs.EnqueueMainThread(() => { if (++attempts == 1) throw new Inno.Core.Execution.RetirementPendingException("pending"); }); + jobs.EnqueueMainThread(() => + { + if (++attempts == 1) throw new Inno.Core.Execution.RetirementPendingException("pending"); + }); Assert.Throws(jobs.DrainMainThreadQueue); Assert.Equal(1, jobs.statistics.mainThreadPending); jobs.DrainMainThreadQueue(); @@ -64,18 +71,22 @@ public void CallbackDrainIsBoundedAndDefersRecursivelyEnqueuedWork(JobExecutionM }); int executions = 0; Action? repeat = null; - repeat = () => { executions++; jobs.EnqueueMainThread(repeat!); }; + repeat = () => + { + executions++; + jobs.EnqueueMainThread(repeat!); + }; jobs.EnqueueMainThread(repeat); jobs.EnqueueMainThread(() => executions++); - Assert.Throws(() => jobs.EnqueueMainThread(() => { })); + Assert.Throws(() => jobs.EnqueueMainThread(() => {})); jobs.DrainMainThreadQueue(); Assert.Equal(1, executions); jobs.DrainMainThreadQueue(); Assert.Equal(2, executions); jobs.BeginFrame(); - jobs.Schedule(() => { }); - jobs.Schedule(() => { }); - Assert.Throws(() => jobs.Schedule(() => { })); + jobs.Schedule(() => {}); + jobs.Schedule(() => {}); + Assert.Throws(() => jobs.Schedule(() => {})); jobs.EndFrame(); } @@ -109,7 +120,7 @@ public void SingleThread_RejectsCrossThreadUsage() { try { - _ = jobs.Schedule(() => { }); + _ = jobs.Schedule(() => {}); } catch (Exception ex) { @@ -178,7 +189,10 @@ public void WorkStealing_ParallelFor_CoversEveryIndexExactlyOnce() const int length = 1024; var values = new int[length]; - var handle = jobs.ParallelFor(length, 32, (start, end) => + var handle = jobs.ParallelFor(length, 32, ( + start, + end + ) => { for (var i = start; i < end; i++) { @@ -257,7 +271,7 @@ public void WorkStealing_EndFrameRecyclesHandle_AndStaleHandleThrows() using var jobs = CreateWorkStealing(); jobs.BeginFrame(); - var handle = jobs.Schedule(() => { }); + var handle = jobs.Schedule(() => {}); jobs.EndFrame(); jobs.BeginFrame(); @@ -331,9 +345,7 @@ public void WorkStealing_NestedScheduleFromWorker_IsSupported() [Fact] public void WorkStealing_AutoWorkerCount_IsInValidRange() { - using var jobs = new JobScheduler( - JobExecutionMode.WorkerPool, - new JobSchedulerOptions { workerCount = 0 }); + using var jobs = new JobScheduler(JobExecutionMode.WorkerPool, new JobSchedulerOptions { workerCount = 0 }); Assert.InRange(jobs.workerCount, 1, 64); } @@ -380,8 +392,14 @@ public void CommonApi_ParallelForInvalidArguments_Throws() using var jobs = CreateWorkStealing(); jobs.BeginFrame(); - Assert.Throws(() => jobs.ParallelFor(-1, 8, (_, _) => { })); - Assert.Throws(() => jobs.ParallelFor(1, 0, (_, _) => { })); + Assert.Throws(() => jobs.ParallelFor(-1, 8, ( + _, + _ + ) => {})); + Assert.Throws(() => jobs.ParallelFor(1, 0, ( + _, + _ + ) => {})); jobs.EndFrame(); } @@ -393,7 +411,7 @@ public void CommonApi_DisposePreventsFurtherUse() jobs.Dispose(); Assert.Throws(() => jobs.BeginFrame()); - Assert.Throws(() => jobs.EnqueueMainThread(() => { })); + Assert.Throws(() => jobs.EnqueueMainThread(() => {})); } private static JobScheduler CreateWorkStealing(int workerCount = 2) diff --git a/tests/core/Inno.Core.Layers.Tests/LayerStackTests.cs b/tests/core/Inno.Core.Layers.Tests/LayerStackTests.cs index 1a7c049d6..dcf3a56ed 100644 --- a/tests/core/Inno.Core.Layers.Tests/LayerStackTests.cs +++ b/tests/core/Inno.Core.Layers.Tests/LayerStackTests.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; - +using Xunit; using Inno.Core.Events; using Inno.Core.Execution; using Inno.Core.Layers; -using Xunit; - namespace Inno.Core.Layers.Tests; public sealed class LayerStackTests @@ -71,7 +69,8 @@ public void RenderFrame_UnwindsPreparedLayersInReverseOrderAfterFailure() Assert.Equal( ["first.before", "second.before", "first.render", "second.render", "second.after", "first.after"], - calls); + calls + ); } [Fact] @@ -177,16 +176,16 @@ public void CrossStackAttachmentDoesNotDetachTheOriginalOwner() Assert.Equal(0, layer.detachCount); } - private sealed class ProbeEvent : Event - { - } + private sealed class ProbeEvent : Event; private sealed class ProbeLayer : Layer { private readonly List? m_calls; - internal ProbeLayer(string name, List? calls = null) - : base(name) + internal ProbeLayer( + string name, + List? calls = null + ) : base(name) { m_calls = calls; } @@ -211,29 +210,35 @@ public override void OnAttach() m_calls?.Add(name); }); if (throwOnAttach) + { throw new InvalidOperationException("Attach failed."); + } } public override void OnDetach() { detachCount++; if (pendingDetaches-- > 0) + { throw new RetirementPendingException("Expected unfinished layer work."); + } if (throwOnDetach) + { throw new InvalidOperationException("Detach failed."); + } } - public override void OnBeforeRender(float deltaTime) - => m_calls?.Add($"{name}.before"); + public override void OnBeforeRender(float deltaTime) => m_calls?.Add($"{name}.before"); public override void OnRender(float deltaTime) { m_calls?.Add($"{name}.render"); if (throwOnRender) + { throw new InvalidOperationException("Render failed."); + } } - public override void OnAfterRender(float deltaTime) - => m_calls?.Add($"{name}.after"); + public override void OnAfterRender(float deltaTime) => m_calls?.Add($"{name}.after"); } } diff --git a/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs b/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs index 8c84feef6..1c0c9edd3 100644 --- a/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs +++ b/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs @@ -2,10 +2,9 @@ using System.IO; using System.Linq; using System.Threading.Tasks; - +using Xunit; using Inno.Core.Logging; using Inno.Extensibility.Modules; -using Xunit; namespace Inno.Core.Logging.Tests; @@ -16,7 +15,9 @@ public sealed class FileLogSinkTests : IDisposable public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Theory] @@ -28,7 +29,9 @@ public void RouterFlushMakesCompletedFileWritesObservable(LogDeliveryMode mode) using var sink = new FileLogSink(m_root); router.RegisterSink(sink); for (int index = 0; index < 100; index++) + { router.Dispatch(CreateEntry("visible-" + index)); + } router.Flush(); @@ -43,7 +46,9 @@ public void RapidRotationRetainsTheCurrentEntryAndHonorsTheByteLimit() { using var sink = new FileLogSink(m_root, maxFileSizeBytes: 512, maxFiles: 3); for (int index = 0; index < 120; index++) + { sink.Receive(CreateEntry($"entry-{index:D3}-" + new string('★', 80))); + } string[] files = Directory.GetFiles(m_root, "*.log"); Assert.InRange(files.Length, 1, 3); @@ -75,7 +80,9 @@ public void MultipleSinksOwnDistinctFilesInTheSameDirectory() try { for (int index = 0; index < sinks.Length; index++) + { sinks[index].Receive(CreateEntry("sink-" + index)); + } string[] files = Directory.GetFiles(m_root, "*.log"); Assert.Equal(sinks.Length, files.Length); @@ -84,7 +91,9 @@ public void MultipleSinksOwnDistinctFilesInTheSameDirectory() finally { foreach (FileLogSink sink in sinks) + { sink.Dispose(); + } } } @@ -173,7 +182,16 @@ private static string ReadContent(string file) return reader.ReadToEnd(); } - private static LogEntry CreateEntry(string message) => new( - LogLevel.Info, AssemblyDomain.InnoInternal, AssemblyScope.Runtime, - "file-test", message, string.Empty, 0, string.Empty, LogSessionId.none); + private static LogEntry CreateEntry(string message) + => new( + LogLevel.Info, + AssemblyDomain.InnoInternal, + AssemblyScope.Runtime, + "file-test", + message, + string.Empty, + 0, + string.Empty, + LogSessionId.none + ); } diff --git a/tests/core/Inno.Core.Logging.Tests/InlineLogDeliveryTests.cs b/tests/core/Inno.Core.Logging.Tests/InlineLogDeliveryTests.cs index b18a9af85..65e7d5743 100644 --- a/tests/core/Inno.Core.Logging.Tests/InlineLogDeliveryTests.cs +++ b/tests/core/Inno.Core.Logging.Tests/InlineLogDeliveryTests.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Core.Logging; using Inno.Extensibility.Modules; -using Xunit; namespace Inno.Core.Logging.Tests; @@ -16,11 +16,15 @@ public void NestedEntriesReachEverySinkInQueueOrder() { using var router = new LogRouter(deliveryMode: LogDeliveryMode.Inline); var received = new ConcurrentQueue(); - router.RegisterSink(new CallbackSink(entry => - { - if (entry.message == "first") - router.Dispatch(CreateEntry("nested")); - })); + router.RegisterSink( + new CallbackSink(entry => + { + if (entry.message == "first") + { + router.Dispatch(CreateEntry("nested")); + } + }) + ); router.RegisterSink(new CallbackSink(entry => received.Enqueue(entry.message))); router.Dispatch(CreateEntry("first")); @@ -36,13 +40,17 @@ public void LongNestedChainsDoNotReenterDelivery() int received = 0; int depth = 0; int maximumDepth = 0; - router.RegisterSink(new CallbackSink(_ => - { - maximumDepth = Math.Max(maximumDepth, ++depth); - if (++received < 10_000) - router.Dispatch(CreateEntry("next")); - depth--; - })); + router.RegisterSink( + new CallbackSink(_ => + { + maximumDepth = Math.Max(maximumDepth, ++depth); + if (++received < 10_000) + { + router.Dispatch(CreateEntry("next")); + } + depth--; + }) + ); router.Dispatch(CreateEntry("first")); @@ -57,11 +65,13 @@ public async Task FlushWaitsForAnEntryAlreadyInsideReceive() using var entered = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); using var flushing = new ManualResetEventSlim(); - router.RegisterSink(new CallbackSink(_ => - { - entered.Set(); - Assert.True(release.Wait(TimeSpan.FromSeconds(10))); - })); + router.RegisterSink( + new CallbackSink(_ => + { + entered.Set(); + Assert.True(release.Wait(TimeSpan.FromSeconds(10))); + }) + ); Task producer = Task.Run(() => router.Dispatch(CreateEntry("blocked"))); Assert.True(entered.Wait(TimeSpan.FromSeconds(5))); Task flush = Task.Run(() => @@ -89,20 +99,28 @@ public async Task ConcurrentProducersNeverInvokeASinkConcurrently() int active = 0; int overlap = 0; int received = 0; - router.RegisterSink(new CallbackSink(_ => - { - if (Interlocked.Increment(ref active) != 1) - Interlocked.Increment(ref overlap); - Thread.SpinWait(2_000); - Interlocked.Increment(ref received); - Interlocked.Decrement(ref active); - })); - - await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(() => - { - for (int entry = 0; entry < 64; entry++) - router.Dispatch(CreateEntry("parallel")); - }))); + router.RegisterSink( + new CallbackSink(_ => + { + if (Interlocked.Increment(ref active) != 1) + { + Interlocked.Increment(ref overlap); + } + Thread.SpinWait(2_000); + Interlocked.Increment(ref received); + Interlocked.Decrement(ref active); + }) + ); + + await Task.WhenAll( + Enumerable.Range(0, 8).Select(_ => Task.Run(() => + { + for (int entry = 0; entry < 64; entry++) + { + router.Dispatch(CreateEntry("parallel")); + } + })) + ); router.Flush(); Assert.Equal(512, received); @@ -122,12 +140,14 @@ public async Task DisposalWaitsForActiveDeliveryBeforeReleasingTheSink() _, exception ) => deliveryFailure = exception; - router.RegisterSink(new DisposableCallbackSink(_ => - { - entered.Set(); - Assert.True(release.Wait(TimeSpan.FromSeconds(10))); - Assert.False(released); - }, () => released = true)); + router.RegisterSink( + new DisposableCallbackSink(_ => + { + entered.Set(); + Assert.True(release.Wait(TimeSpan.FromSeconds(10))); + Assert.False(released); + }, () => released = true) + ); Task producer = Task.Run(() => router.Dispatch(CreateEntry("blocked"))); Assert.True(entered.Wait(TimeSpan.FromSeconds(5))); Task disposal = Task.Run(() => @@ -157,11 +177,13 @@ public async Task DisposalWaitsForActiveDeliveryBeforeReleasingTheSink() public void DeliveryCallbacksCannotFlushOrDisposeTheirOwnRouter(LogDeliveryMode mode) { using var router = new LogRouter(deliveryMode: mode); - router.RegisterSink(new CallbackSink(_ => - { - Assert.Throws(router.Flush); - Assert.Throws(router.Dispose); - })); + router.RegisterSink( + new CallbackSink(_ => + { + Assert.Throws(router.Flush); + Assert.Throws(router.Dispose); + }) + ); Exception? failure = null; router.sinkFailed += ( _, @@ -174,9 +196,18 @@ public void DeliveryCallbacksCannotFlushOrDisposeTheirOwnRouter(LogDeliveryMode Assert.Null(failure); } - private static LogEntry CreateEntry(string message) => new( - LogLevel.Info, AssemblyDomain.InnoInternal, AssemblyScope.Runtime, - "inline-test", message, string.Empty, 0, string.Empty, LogSessionId.none); + private static LogEntry CreateEntry(string message) + => new( + LogLevel.Info, + AssemblyDomain.InnoInternal, + AssemblyScope.Runtime, + "inline-test", + message, + string.Empty, + 0, + string.Empty, + LogSessionId.none + ); private sealed class CallbackSink(Action callback) : ILogSink { diff --git a/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs b/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs index 121979d15..c74c1319b 100644 --- a/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs +++ b/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs @@ -5,10 +5,8 @@ using System.Text; using System.Threading; using System.Threading.Tasks; - -using Inno.Core.Logging; - using Xunit; +using Inno.Core.Logging; namespace Inno.Core.Logging.Tests; @@ -63,7 +61,6 @@ public void ExplicitOwnershipAcceptsStaticSourcesAndRejectsMissingTypes() m_router.UnregisterSink(sink); } - [Fact] public void UnknownDeliveryPoliciesFailAtConstruction() { @@ -104,8 +101,14 @@ bool failingObserver int reported = 0; if (failingObserver) { - router.sinkFailed += (_, _) => throw new InvalidOperationException("Expected observer failure."); - router.sinkFailed += (_, _) => reported++; + router.sinkFailed += ( + _, + _ + ) => throw new InvalidOperationException("Expected observer failure."); + router.sinkFailed += ( + _, + _ + ) => reported++; } router.RegisterSink(failing); router.RegisterSink(healthy); @@ -243,7 +246,10 @@ public void FailingSinkIsReportedQuarantinedAndDoesNotBlockHealthySinks() using var healthy = new ProbeSink(); ILogSink? reportedSink = null; Exception? reportedFailure = null; - m_router.sinkFailed += (sink, failure) => + m_router.sinkFailed += ( + sink, + failure + ) => { reportedSink = sink; reportedFailure = failure; @@ -272,7 +278,9 @@ public void FileLogSink_WritesEntriesAndRotates() m_router.RegisterSink(sink); for (var i = 0; i < 80; i++) + { Log.Warn(typeof(LoggingBehaviorTests), "line-{0}", [i]); + } m_router.Flush(); m_router.UnregisterSink(sink); @@ -304,13 +312,17 @@ public void Receive(LogEntry entry) m_signal.Set(); } - public bool WaitForCount(int count, TimeSpan timeout) - { + public bool WaitForCount( + int count, + TimeSpan timeout + ) { var deadline = DateTime.UtcNow + timeout; while (DateTime.UtcNow < deadline) { if (m_entries.Count >= count) + { return true; + } m_signal.Wait(TimeSpan.FromMilliseconds(20)); m_signal.Reset(); diff --git a/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs b/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs index 027d4c371..299b71821 100644 --- a/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs +++ b/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs @@ -1,8 +1,6 @@ using System; - -using Inno.Core.Mathematics; - using Xunit; +using Inno.Core.Mathematics; namespace Inno.Core.Mathematics.Tests; @@ -32,7 +30,8 @@ public void EulerAnglesXYZ_RoundTripsCompoundRotation() original.x * roundTrip.x + original.y * roundTrip.y + original.z * roundTrip.z - + original.w * roundTrip.w); + + original.w * roundTrip.w + ); Assert.InRange(alignment, 0.99999f, 1.00001f); } @@ -138,14 +137,20 @@ public void Matrix_Decompose_PreservesReflectedTransform() var rotation = Quaternion.FromEulerAnglesXYZ(new Vector3(0.2f, 0.3f, 0.4f)); var translation = new Vector3(5f, 6f, 7f); Matrix matrix = Matrix.CreateTranslation(translation) - * Matrix.CreateFromQuaternion(rotation) - * Matrix.CreateScale(scale); - - Assert.True(Matrix.Decompose(matrix, out Vector3 resultScale, - out Quaternion resultRotation, out Vector3 resultTranslation)); + * Matrix.CreateFromQuaternion(rotation) + * Matrix.CreateScale(scale); + + Assert.True( + Matrix.Decompose( + matrix, + out Vector3 resultScale, + out Quaternion resultRotation, + out Vector3 resultTranslation + ) + ); Matrix reconstructed = Matrix.CreateTranslation(resultTranslation) - * Matrix.CreateFromQuaternion(resultRotation) - * Matrix.CreateScale(resultScale); + * Matrix.CreateFromQuaternion(resultRotation) + * Matrix.CreateScale(resultScale); Assert.True(matrix == reconstructed); } @@ -218,11 +223,7 @@ public void Matrix_OrthographicOffCenter_MapsEdges() [Fact] public void Matrix_ToColumnMajorArray_Layout() { - var m = new Matrix( - 1f, 2f, 3f, 4f, - 5f, 6f, 7f, 8f, - 9f, 10f, 11f, 12f, - 13f, 14f, 15f, 16f); + var m = new Matrix(1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f); var data = m.ToColumnMajorArray(); @@ -264,8 +265,10 @@ public void Quaternion_FromRotationMatrix_Roundtrip() Assert.True(MathF.Abs(q.w - q2.w) < epsilon); } - private static float Dot(Quaternion a, Quaternion b) - { + private static float Dot( + Quaternion a, + Quaternion b + ) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs index 295cf2fd7..e6c51ca8e 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; +using Xunit; using Inno.Core.Identity; using Inno.Core.Serialization.Converters; -using Xunit; namespace Inno.Core.Serialization.Tests; @@ -179,31 +179,44 @@ public override void Write( CaptureArrayRoot value ) { writer.Write("scope", value.scope); - writer.WriteObjectArray("rows", value.rows, ( - child, - row - ) => { - row.writes++; - value.onWrite?.Invoke(); - child.Write("number", row.number); - child.Write("mode", value.mode); - if (value.stateful) - child.WritePropertiesData("state", row.state); - }, captureKey: ( - row, - key - ) => { - value.keys++; - value.savedBuilder = key; - if (value.failKey) - throw new InvalidOperationException("Array key failure."); - if (!value.allowKeys || !key.TryAddOwner(row, row.revision)) - return false; - key.AddValue(value.scope); - key.AddValue(unchecked((ulong)value.mode)); - key.AddValue(value.stateful ? 1UL : 0UL); - return true; - }); + writer.WriteObjectArray( + "rows", + value.rows, + ( + child, + row + ) => + { + row.writes++; + value.onWrite?.Invoke(); + child.Write("number", row.number); + child.Write("mode", value.mode); + if (value.stateful) + { + child.WritePropertiesData("state", row.state); + } + }, + captureKey: ( + row, + key + ) => + { + value.keys++; + value.savedBuilder = key; + if (value.failKey) + { + throw new InvalidOperationException("Array key failure."); + } + if (!value.allowKeys || !key.TryAddOwner(row, row.revision)) + { + return false; + } + key.AddValue(value.scope); + key.AddValue(unchecked((ulong)value.mode)); + key.AddValue(value.stateful ? 1UL : 0UL); + return true; + } + ); } public override CaptureArrayRoot Read(SerializationReader reader) => throw new NotSupportedException(); diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs index 103574b17..9e148df0c 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs @@ -5,10 +5,10 @@ using System.Runtime.CompilerServices; using System.Runtime.Loader; using System.Threading.Tasks; +using Xunit; using Inno.Adapter.Serialization.DotNet; using Inno.Core.Identity; using Inno.Core.Serialization.Converters; -using Xunit; namespace Inno.Core.Serialization.Tests; @@ -383,14 +383,20 @@ CaptureKeyRoot value value.writeCalls++; value.onWrite?.Invoke(); if (value.failWrite) + { throw new InvalidOperationException("Capture writer failure."); + } writer.Write("number", value.number); writer.Write("text", value.text); writer.Write("context", writer.context.TryGet(out CaptureKeyContext? context) ? context!.value : 0UL); if (value.properties is not null) + { writer.WritePropertiesData("properties", value.properties); + } if (value.converted.HasValue) + { writer.Write("converted", value.converted.Value); + } } public override CaptureKeyRoot Read(SerializationReader reader) => throw new NotSupportedException(); @@ -402,14 +408,20 @@ SerializationCaptureKeyBuilder key value.keyCalls++; value.savedBuilder = key; if (value.failKey) + { throw new InvalidOperationException("Capture key failure."); + } if (!value.allowKey) + { return false; + } key.EnsureCapacity(5); bool complete = key.TryAddOwner(value, value.revision); key.AddValue(key.context.TryGet(out CaptureKeyContext? context) ? context!.value : 0UL); if (value.properties is not null) + { complete &= key.TryAddProperties(value.properties); + } value.onKey?.Invoke(key); return complete || value.ignoreDecline; } @@ -427,7 +439,7 @@ public sealed class CaptureRevisionProperties : IdentityObject, ISerializable /// /// Creates an initially empty tracked property source. /// - public CaptureRevisionProperties() { } + public CaptureRevisionProperties() {} /// /// Gets or sets the serialized number, advancing its complete source-owned revision before mutation. @@ -439,7 +451,9 @@ public int number set { if (m_revision is { } revision) + { m_revision = revision == ulong.MaxValue ? null : revision + 1; + } m_number = value; } } @@ -498,7 +512,7 @@ public int value calls++; return 1; } - set { } + set {} } } diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs index 520497b77..212b11bfa 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs @@ -1,8 +1,8 @@ using System; using System.Threading; using System.Threading.Tasks; -using Inno.Core.Serialization.Converters; using Xunit; +using Inno.Core.Serialization.Converters; namespace Inno.Core.Serialization.Tests; diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Efficiency.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Efficiency.cs index 1b58c184c..bfc993320 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Efficiency.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Efficiency.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using Xunit; using Inno.Adapter.Serialization.DotNet; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Core.Serialization.Tests; @@ -38,17 +38,23 @@ public void PreparedSerializationContextsAvoidRepeatedOwnerCopies() long fresh = Measure(null); long inherited = Measure(prepared); - Assert.True(inherited < fresh && inherited <= 1024, - $"Prepared context allocated {inherited} bytes; fresh context allocated {fresh} bytes."); + Assert.True( + inherited < fresh && inherited <= 1024, + $"Prepared context allocated {inherited} bytes; fresh context allocated {fresh} bytes." + ); long Measure(SerializationContext? context) { for (int index = 0; index < 16; index++) + { _ = m_serialization.CapturePropertyData(source, nameof(DefaultSample.count), context); + } byte[]? actual = null; long before = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < 128; index++) + { actual = m_serialization.CapturePropertyData(source, nameof(DefaultSample.count), context); + } long allocated = (GC.GetAllocatedBytesForCurrentThread() - before) / 128; Assert.Equal(expected, actual); return allocated; @@ -85,12 +91,16 @@ public void BinaryObjectKeysRemainOrdinalAndIndependentOfInsertionOrder() byte[] forward = m_serialization.Encode(writer => { foreach (string key in keys) + { writer.Write(key, key); + } }); byte[] reverse = m_serialization.Encode(writer => { for (int index = keys.Length - 1; index >= 0; index--) + { writer.Write(keys[index], keys[index]); + } }); Assert.Equal(forward, reverse); @@ -101,13 +111,17 @@ public void SmallBinaryDocumentsStayWithinABoundedAllocationBudget() { byte[] expected = m_serialization.Encode(static writer => writer.Write("value", 73)); for (int index = 0; index < 16; index++) + { _ = m_serialization.Encode(static writer => writer.Write("value", 73)); + } const int C_ITERATIONS = 128; byte[]? actual = null; long before = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < C_ITERATIONS; index++) + { actual = m_serialization.Encode(static writer => writer.Write("value", 73)); + } long allocated = GC.GetAllocatedBytesForCurrentThread() - before; Assert.Equal(expected, actual); @@ -152,7 +166,9 @@ public void BinaryDocumentsRoundTripAcrossBufferGrowthBoundaries(int length) { var payload = new byte[length]; for (int index = 0; index < payload.Length; index++) + { payload[index] = unchecked((byte)index); + } byte[] data = m_serialization.Serialize(new DefaultSample { bytes = payload }); DefaultSample restored = m_serialization.Deserialize(data); @@ -175,7 +191,7 @@ public int unrelated m_unrelatedReads++; throw new InvalidOperationException("An unrelated getter must not be evaluated."); } - set { } + set {} } public int ignored { get; set; } @@ -188,8 +204,9 @@ private static (SerializationContext, WeakReference) ReplaceContextService(bool var replaced = new object(); SerializationContext context = SerializationContext.empty.With(replaced); if (nested) + { context = context.With("marker").With>(new[] { 1, 2 }); + } return (context.With(new object()), new WeakReference(replaced)); } - } diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs index b3c267f72..c56b62cbf 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs @@ -12,15 +12,42 @@ public void EncodedScalarBytesMatchTheBinaryWriterContract() { object?[] values = [ - null, false, true, byte.MaxValue, sbyte.MinValue, short.MinValue, ushort.MaxValue, - int.MinValue, uint.MaxValue, long.MinValue, ulong.MaxValue, - float.NegativeInfinity, float.PositiveInfinity, float.NaN, -0f, float.Epsilon, - double.NegativeInfinity, double.PositiveInfinity, double.NaN, -0d, double.Epsilon, - decimal.MinValue, decimal.MaxValue, new decimal(0, 0, 0, true, 28), - string.Empty, "English / 中文 / 🧪", Guid.Empty, Guid.Parse("62ce926a-e339-493d-bb74-743ed44ef37a") + null, + false, + true, + byte.MaxValue, + sbyte.MinValue, + short.MinValue, + ushort.MaxValue, + int.MinValue, + uint.MaxValue, + long.MinValue, + ulong.MaxValue, + float.NegativeInfinity, + float.PositiveInfinity, + float.NaN, + -0f, + float.Epsilon, + double.NegativeInfinity, + double.PositiveInfinity, + double.NaN, + -0d, + double.Epsilon, + decimal.MinValue, + decimal.MaxValue, + new decimal(0, 0, 0, true, 28), + string.Empty, + "English / 中文 / 🧪", + Guid.Empty, + Guid.Parse("62ce926a-e339-493d-bb74-743ed44ef37a") ]; foreach (object? value in values) - Assert.Equal(EncodeWithBinaryWriter(value), m_serialization.Encode(writer => writer.Write("value", value, value?.GetType() ?? typeof(string)))); + { + Assert.Equal( + EncodeWithBinaryWriter(value), + m_serialization.Encode(writer => writer.Write("value", value, value?.GetType() ?? typeof(string))) + ); + } } [Theory] @@ -35,11 +62,15 @@ public void EncodedStringsKeepUtf8AndSevenBitLengthSemantics(int length) { string[] values = [ - new string('a', length), new string('中', length), - new string((char)0xD800, length), "🧪" + new string('a', length) + new string('a', length), + new string('中', length), + new string((char)0xD800, length), + "🧪" + new string('a', length) ]; foreach (string value in values) + { Assert.Equal(EncodeWithBinaryWriter(value), m_serialization.Encode(writer => writer.Write("value", value))); + } } [Fact] @@ -49,12 +80,16 @@ public void LargeBinaryEncodingAllocatesOnlyTheOwnedCaptureAndResult() source[0] = 73; source[^1] = 19; for (int index = 0; index < 4; index++) + { _ = m_serialization.Encode(writer => writer.Write("value", source)); + } long before = GC.GetAllocatedBytesForCurrentThread(); byte[] data = []; const int repetitions = 16; for (int index = 0; index < repetitions; index++) + { data = m_serialization.Encode(writer => writer.Write("value", source)); + } long allocated = (GC.GetAllocatedBytesForCurrentThread() - before) / repetitions; // Retain the per-call bound while amortizing one-time runtime/catalog admission during the suite. Assert.InRange(allocated, source.Length * 2, source.Length * 2 + 8192); diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs index f333958a3..e7b9d84cb 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs @@ -1,6 +1,6 @@ using System; -using Inno.Core.Serialization.Converters; using Xunit; +using Inno.Core.Serialization.Converters; namespace Inno.Core.Serialization.Tests; @@ -36,7 +36,9 @@ public override void Write( OrdinalCapture value ) { foreach (string name in value.names) + { writer.Write(name, 7); + } } public override OrdinalCapture Read(SerializationReader reader) => throw new NotSupportedException(); diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs index 5aaf3fe51..194b6f191 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs @@ -3,8 +3,8 @@ using System.IO; using System.Runtime.CompilerServices; using System.Threading.Tasks; -using Inno.Core.Serialization.Converters; using Xunit; +using Inno.Core.Serialization.Converters; namespace Inno.Core.Serialization.Tests; @@ -117,7 +117,9 @@ public void SnapshotObjectCaptureHandlesReplacementRemovalAndEmptyObjects(int co { var value = new SnapshotEnvelope { omitState = true }; for (int index = 0; index < count; index++) + { value.fields.Add("item-" + index, index); + } SerializationSnapshot snapshot = m_serialization.CaptureSnapshot(value); value.fields.Remove("item-0"); value.fields.Add("replacement", 91); @@ -139,8 +141,10 @@ public void SnapshotStateBlobsUseTheExistingPropertyWireFormatAndDetectArrayShri value.state.count = 42; SerializationSnapshot before = m_serialization.CaptureSnapshot(value); byte[] bytes = before.ToArray(); - Assert.Equal(m_serialization.CapturePropertiesData(value.state), - m_serialization.Decode(bytes, reader => reader.Read("state"))); + Assert.Equal( + m_serialization.CapturePropertiesData(value.state), + m_serialization.Decode(bytes, reader => reader.Read("state")) + ); value.items.RemoveAt(1); value.state.name = "changed"; SerializationSnapshot after = m_serialization.CaptureSnapshot(value, previous: before); @@ -208,10 +212,14 @@ public void UnchangedLargeBinaryCaptureDoesNotCopyItsPayload() source.state.bytes = new byte[1024 * 1024]; SerializationSnapshot snapshot = m_serialization.CaptureSnapshot(source); for (int index = 0; index < 8; index++) + { Assert.Same(snapshot, m_serialization.CaptureSnapshot(source, previous: snapshot)); + } long started = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < 16; index++) + { Assert.Same(snapshot, m_serialization.CaptureSnapshot(source, previous: snapshot)); + } long allocated = (GC.GetAllocatedBytesForCurrentThread() - started) / 16; Assert.True(allocated < 16_384, $"An unchanged 1 MiB payload allocated {allocated} bytes per capture."); source.state.bytes[500] = 12; @@ -277,7 +285,9 @@ SnapshotEnvelope value value.writeCalls++; value.observedTypeGeneration = writer.typeSnapshot.version; foreach (var pair in value.fields) + { writer.Write(pair.Key, pair.Value); + } if (value.duplicate) { writer.Write("duplicate", 1); @@ -292,7 +302,9 @@ SnapshotEnvelope value ) => child.Write("value", number)); } if (value.fail) + { throw new InvalidOperationException("Capture rejected by its source converter."); + } } public override SnapshotEnvelope Read(SerializationReader reader) => throw new NotSupportedException(); diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs index c1727e205..72f46ac65 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs @@ -1,16 +1,14 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Core.Serialization.Converters; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Inno.Core.Serialization.Converters; - -using Xunit; namespace Inno.Core.Serialization.Tests; @@ -19,7 +17,9 @@ public sealed partial class SerializationBehaviorTests : IDisposable private readonly string m_testRoot = Path.Combine( Path.GetTempPath(), "InnoSerializationTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private ModuleHost m_modules; private TypeCatalog m_types; private SerializationRegistry m_serialization; @@ -27,7 +27,9 @@ public sealed partial class SerializationBehaviorTests : IDisposable public SerializationBehaviorTests() { m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(SerializationBehaviorTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(SerializationBehaviorTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -38,7 +40,9 @@ public void Dispose() m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_testRoot)) + { Directory.Delete(m_testRoot, recursive: true); + } } [Fact] @@ -58,9 +62,11 @@ public void IdentityRemapperRewritesNestedSerializedValuesWithoutChangingRawBina bytes = nested }); - byte[] rewritten = SerializedIdentityRemapper.Rewrite(source, + byte[] rewritten = SerializedIdentityRemapper.Rewrite( + source, new Dictionary { [oldId] = newId }, - new Dictionary { ["plugin::~Samples/Document.rml"] = "plugin-Samples/Document.rml" }); + new Dictionary { ["plugin::~Samples/Document.rml"] = "plugin-Samples/Document.rml" } + ); DefaultSample outer = m_serialization.Deserialize(rewritten); DefaultSample inner = m_serialization.Deserialize(outer.bytes); @@ -82,8 +88,7 @@ public void PublicOperations_RejectDisposedRegistry() { m_serialization.Dispose(); - Assert.Throws( - () => m_serialization.Serialize(new DefaultSample())); + Assert.Throws(() => m_serialization.Serialize(new DefaultSample())); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); Assert.NotEmpty(m_serialization.Serialize(new DefaultSample())); @@ -115,7 +120,9 @@ public void TypeCatalogConstructor_RequiresActiveModuleHost() Assert.Throws(() => new TypeCatalog(m_modules, new ReflectionTypeCatalogSource())); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(SerializationBehaviorTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(SerializationBehaviorTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -211,7 +218,8 @@ public void CollectingPropertyRestore_CollectsInvalidMembersAndPreservesDefaults SerializationPropertyRestoreResult result = m_serialization.RestoreProperties( current, snapshots, - SerializationPropertyRestoreMode.CollectFailures); + SerializationPropertyRestoreMode.CollectFailures + ); Assert.False(result.success); Assert.Equal(1, result.restoredCount); @@ -236,7 +244,8 @@ public void StrictPropertyRestore_ThrowsForAnIncompatibleMember() Assert.Throws(() => m_serialization.RestoreProperties( current, snapshots, - SerializationPropertyRestoreMode.Strict)); + SerializationPropertyRestoreMode.Strict + )); Assert.Equal("default", current.changed); Assert.Equal(0, current.restoreCount); @@ -291,16 +300,16 @@ public void PropertyData_RejectsMalformedOrTrailingBytes() { byte[] data = m_serialization.CapturePropertyData( new DefaultSample { count = 12 }, - nameof(DefaultSample.count)); + nameof(DefaultSample.count) + ); byte[] trailing = new byte[data.Length + 1]; data.CopyTo(trailing, 0); - Assert.Throws(() => m_serialization.RestorePropertiesData( - new DefaultSample(), - trailing)); + Assert.Throws(() => m_serialization.RestorePropertiesData(new DefaultSample(), trailing)); Assert.ThrowsAny(() => m_serialization.RestorePropertiesData( new DefaultSample(), - new byte[] { 1, 2, 3 })); + new byte[] { 1, 2, 3 } + )); } [Fact] @@ -320,7 +329,8 @@ public void Deserialize_WithoutParameterlessConstructor_RequiresConverter() byte[] bytes = m_serialization.Encode(static writer => writer.Write("value", 5)); InvalidOperationException exception = Assert.Throws( - () => m_serialization.Deserialize(bytes)); + () => m_serialization.Deserialize(bytes) + ); Assert.Contains(typeof(MissingConstructorSample).FullName!, exception.Message); Assert.Contains("parameterless constructor", exception.Message); @@ -332,7 +342,8 @@ public void Deserialize_UsesConverterWhenNoParameterlessConstructorExists() var source = new ConvertedConstructorSample(31); ConvertedConstructorSample restored = m_serialization.Deserialize( - m_serialization.Serialize(source)); + m_serialization.Serialize(source) + ); Assert.Equal(31, restored.value); } @@ -340,10 +351,11 @@ public void Deserialize_UsesConverterWhenNoParameterlessConstructorExists() [Fact] public void Deserialize_PreservesConstructorFailureAsInnerException() { - byte[] bytes = m_serialization.Encode(static _ => { }); + byte[] bytes = m_serialization.Encode(static _ => {}); InvalidOperationException exception = Assert.Throws( - () => m_serialization.Deserialize(bytes)); + () => m_serialization.Deserialize(bytes) + ); Assert.IsType(exception.InnerException); Assert.Equal("constructor failure", exception.InnerException!.Message); @@ -353,7 +365,8 @@ public void Deserialize_PreservesConstructorFailureAsInnerException() public void RequiredConverter_Missing_ThrowsClearError() { InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(new MissingRequiredConverterSample())); + () => m_serialization.Serialize(new MissingRequiredConverterSample()) + ); Assert.Contains(typeof(MissingRequiredConverterSample).FullName!, exception.Message); Assert.Contains("requires an explicit serialization converter", exception.Message); @@ -410,10 +423,8 @@ public void Visibility_ControlsPersistenceAndRuntimeMetadataStrictly() [Fact] public void MetadataValidation_RejectsInvalidMembersAndDuplicateKeys() { - Assert.Throws( - () => m_serialization.GetProperties(new MissingSetterSample())); - Assert.Throws( - () => m_serialization.GetProperties(new DuplicateKeyDerivedSample())); + Assert.Throws(() => m_serialization.GetProperties(new MissingSetterSample())); + Assert.Throws(() => m_serialization.GetProperties(new DuplicateKeyDerivedSample())); } [Fact] @@ -422,7 +433,8 @@ public void ClassMemberWithoutConverter_FailsWithCompletePath() var source = new MissingClassHost { child = new MissingChild { value = 1 } }; InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(source)); + () => m_serialization.Serialize(source) + ); Assert.Contains("$.child", exception.Message); Assert.Contains("SerializationConverter", exception.Message); @@ -437,7 +449,8 @@ public void ClassCollectionElementWithoutConverter_FailsWithIndexedPath() }; InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(source)); + () => m_serialization.Serialize(source) + ); Assert.Contains("$.children[0]", exception.Message); } @@ -451,7 +464,8 @@ public void ExplicitConverter_RoundTripsNestedClass() }; ConvertedChildHost restored = m_serialization.Deserialize( - m_serialization.Serialize(source)); + m_serialization.Serialize(source) + ); Assert.NotNull(restored.child); Assert.Equal(14, restored.child!.value); @@ -465,7 +479,8 @@ public void ExplicitConverter_CycleFailsWithBothPaths() var source = new CycleHost { value = cycle }; InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(source)); + () => m_serialization.Serialize(source) + ); Assert.Contains("Serialization cycle detected", exception.Message); Assert.Contains("$.value", exception.Message); @@ -497,8 +512,7 @@ public void DeclaredTypeValueOperationsMatchGenericBytesAndPreserveNullableValue Assert.Throws(() => reader.Read("number", null!)); return true; }); - Assert.Throws(() => - m_serialization.Encode(writer => writer.Write("value", 1, null!))); + Assert.Throws(() => m_serialization.Encode(writer => writer.Write("value", 1, null!))); } [Fact] @@ -532,7 +546,8 @@ public void ConverterSelection_RejectsEqualDistanceAmbiguity() var source = new AmbiguousHost { item = new AmbiguousValue() }; InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(source)); + () => m_serialization.Serialize(source) + ); Assert.Contains("ambiguous converters", exception.Message); Assert.Contains(typeof(AmbiguousValue).FullName!, exception.Message); @@ -585,7 +600,10 @@ public void ReaderWriter_ReportDuplicateMissingAndTypePaths() Assert.Contains("value", duplicate.Message); byte[] arrayBytes = m_serialization.Encode(writer => - writer.WriteObjectArray("items", new[] { 1 }, static (_, _) => { })); + writer.WriteObjectArray("items", new[] { 1 }, static ( + _, + _ + ) => {})); InvalidOperationException missing = Assert.Throws(() => m_serialization.Decode(arrayBytes, static reader => reader.ReadObjectArray("items")[0].Read("missing"))); @@ -634,7 +652,8 @@ public void RestoreHooks_RunOnceBaseToDerivedForDefaultAndConverterPaths() var converted = new ConvertedHookSample { value = 8 }; ConvertedHookSample restored = m_serialization.Deserialize( - m_serialization.Serialize(converted)); + m_serialization.Serialize(converted) + ); Assert.Equal(1, restored.hookCount); var existing = new ConvertedHookSample(); @@ -680,10 +699,13 @@ public void ForeignFormatHeader_IsRejected() { using var stream = new MemoryStream(); using (var writer = new BinaryWriter(stream, System.Text.Encoding.UTF8, leaveOpen: true)) + { writer.Write("FOREIGN"); + } InvalidDataException exception = Assert.Throws( - () => m_serialization.Decode(stream.ToArray(), static _ => true)); + () => m_serialization.Decode(stream.ToArray(), static _ => true) + ); Assert.Contains("Invalid serialization magic", exception.Message); } } @@ -738,15 +760,22 @@ internal struct StructSample public readonly int computed => x + m_hidden; public readonly int hidden => m_hidden; - private StructSample(int x, int y, int hidden) - { + private StructSample( + int x, + int y, + int hidden + ) { this.x = x; this.y = y; readOnly = 99; m_hidden = hidden; } - internal static StructSample Create(int x, int y, int hidden) => new(x, y, hidden); + internal static StructSample Create( + int x, + int y, + int hidden + ) => new(x, y, hidden); } internal sealed class PrivateConstructorSample : ISerializable @@ -782,14 +811,17 @@ public ConvertedConstructorSample(int value) internal sealed class ConvertedConstructorSampleConverter : SerializationConverter { - public override void Write(SerializationWriter writer, ConvertedConstructorSample value) - => writer.Write("value", value.value); + public override void Write( + SerializationWriter writer, + ConvertedConstructorSample value + ) => writer.Write("value", value.value); - public override ConvertedConstructorSample Read(SerializationReader reader) - => new(reader.Read("value")); + public override ConvertedConstructorSample Read(SerializationReader reader) => new(reader.Read("value")); - public override void Restore(SerializationReader reader, ConvertedConstructorSample target) - => target.value = reader.Read("value"); + public override void Restore( + SerializationReader reader, + ConvertedConstructorSample target + ) => target.value = reader.Read("value"); } internal sealed class ThrowingConstructorSample : ISerializable @@ -868,20 +900,22 @@ internal sealed class CycleHost : ISerializable internal sealed class CycleValueConverter : SerializationConverter { - public override void Write(SerializationWriter writer, CycleValue value) - => writer.Write("next", value.next); + public override void Write( + SerializationWriter writer, + CycleValue value + ) => writer.Write("next", value.next); - public override CycleValue Read(SerializationReader reader) - => new() { next = reader.Read("next") }; + public override CycleValue Read(SerializationReader reader) => new() { next = reader.Read("next") }; } internal sealed class ConvertedChildConverter : SerializationConverter { - public override void Write(SerializationWriter writer, ConvertedChild value) - => writer.Write("value", value.value); + public override void Write( + SerializationWriter writer, + ConvertedChild value + ) => writer.Write("value", value.value); - public override ConvertedChild Read(SerializationReader reader) - => new() { value = reader.Read("value") }; + public override ConvertedChild Read(SerializationReader reader) => new() { value = reader.Read("value") }; } internal class NearestBase @@ -901,8 +935,10 @@ internal sealed class NearestHost : ISerializable internal sealed class NearestBaseConverter : SerializationConverter { - public override void Write(SerializationWriter writer, NearestBase value) - => writer.Write("value", value.value); + public override void Write( + SerializationWriter writer, + NearestBase value + ) => writer.Write("value", value.value); public override NearestBase Read(SerializationReader reader) => new NearestLeaf { value = reader.Read("value"), selectedBy = "base" }; @@ -910,8 +946,10 @@ public override NearestBase Read(SerializationReader reader) internal sealed class NearestMidConverter : SerializationConverter { - public override void Write(SerializationWriter writer, NearestMid value) - => writer.Write("value", value.value); + public override void Write( + SerializationWriter writer, + NearestMid value + ) => writer.Write("value", value.value); public override NearestMid Read(SerializationReader reader) => new NearestLeaf { value = reader.Read("value"), selectedBy = "mid" }; @@ -932,8 +970,10 @@ internal sealed class ExactHost : ISerializable internal sealed class ExactBaseConverter : SerializationConverter { - public override void Write(SerializationWriter writer, ExactBase value) - => writer.Write("value", value.value); + public override void Write( + SerializationWriter writer, + ExactBase value + ) => writer.Write("value", value.value); public override ExactBase Read(SerializationReader reader) => new ExactLeaf { value = reader.Read("value"), selectedBy = "base" }; @@ -941,8 +981,10 @@ public override ExactBase Read(SerializationReader reader) internal sealed class ExactLeafConverter : SerializationConverter { - public override void Write(SerializationWriter writer, ExactLeaf value) - => writer.Write("value", value.value); + public override void Write( + SerializationWriter writer, + ExactLeaf value + ) => writer.Write("value", value.value); public override ExactLeaf Read(SerializationReader reader) => new() { value = reader.Read("value"), selectedBy = "exact" }; @@ -961,13 +1003,21 @@ internal sealed class AmbiguousHost : ISerializable internal sealed class AmbiguousLeftConverter : SerializationConverter { - public override void Write(SerializationWriter writer, IAmbiguousLeft value) { } + public override void Write( + SerializationWriter writer, + IAmbiguousLeft value + ) {} + public override IAmbiguousLeft Read(SerializationReader reader) => new AmbiguousValue(); } internal sealed class AmbiguousRightConverter : SerializationConverter { - public override void Write(SerializationWriter writer, IAmbiguousRight value) { } + public override void Write( + SerializationWriter writer, + IAmbiguousRight value + ) {} + public override IAmbiguousRight Read(SerializationReader reader) => new AmbiguousValue(); } @@ -988,11 +1038,12 @@ internal sealed class GenericBoxHost : ISerializable internal sealed class GenericBoxConverter : SerializationConverter> { - public override void Write(SerializationWriter writer, GenericBox value) - => writer.Write("value", value.value); + public override void Write( + SerializationWriter writer, + GenericBox value + ) => writer.Write("value", value.value); - public override GenericBox Read(SerializationReader reader) - => new(reader.Read("value")); + public override GenericBox Read(SerializationReader reader) => new(reader.Read("value")); } internal interface IVariantValue @@ -1046,14 +1097,17 @@ internal sealed class ConvertedHookSample : ISerializable internal sealed class ConvertedHookSampleConverter : SerializationConverter { - public override void Write(SerializationWriter writer, ConvertedHookSample value) - => writer.Write("value", value.value); + public override void Write( + SerializationWriter writer, + ConvertedHookSample value + ) => writer.Write("value", value.value); - public override ConvertedHookSample Read(SerializationReader reader) - => new() { value = reader.Read("value") }; + public override ConvertedHookSample Read(SerializationReader reader) => new() { value = reader.Read("value") }; - public override void Restore(SerializationReader reader, ConvertedHookSample target) - => target.value = reader.Read("value"); + public override void Restore( + SerializationReader reader, + ConvertedHookSample target + ) => target.value = reader.Read("value"); } internal sealed class MapHost : ISerializable diff --git a/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs b/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs index f90984c9a..94783a98e 100644 --- a/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs +++ b/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs @@ -1,15 +1,15 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Audio; using Inno.Audio.Runtime; +using Inno.Core.Logging; using Inno.Runtime; -using Xunit; +using Inno.Runtime.Contracts; namespace Inno.Editor.Audio.Tests; @@ -24,8 +24,11 @@ public EditorAudioHostTests() m_root = Path.Combine(Path.GetTempPath(), "InnoEditorAudioTests", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(m_root); m_engine = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(EditorAudioHostTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(EditorAudioHostTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); } @@ -33,7 +36,9 @@ public void Dispose() { m_engine.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -43,20 +48,27 @@ public void EditAndPlaySessionsOwnIndependentExecutionScopesAndLifetimes() m_engine.types, m_artifacts, m_engine.diagnostics, - deviceFactory: static () => new MutedAudioDevice()); + deviceFactory: static () => new MutedAudioDevice() + ); using RuntimeSession edit = m_engine.CreateSession(CreateOptions(host, RuntimeSessionKind.Edit, "edit")); using (host.EnterExecutionScope(edit)) + { Assert.Equal(AudioDeviceState.Muted, Inno.Audio.Audio.deviceState); + } using (RuntimeSession play = m_engine.CreateSession(CreateOptions(host, RuntimeSessionKind.Play, "play"))) { using (host.EnterExecutionScope(play)) + { Assert.Equal(AudioDeviceState.Muted, Inno.Audio.Audio.deviceState); + } play.Tick(0.016f); } using (host.EnterExecutionScope(edit)) + { Assert.Equal(AudioDeviceState.Muted, Inno.Audio.Audio.deviceState); + } edit.Tick(0.016f); } @@ -67,11 +79,14 @@ public void PreviewUsesTheRealAudioServiceAndRejectsPlaySessionPreview() m_engine.types, m_artifacts, m_engine.diagnostics, - deviceFactory: static () => new MutedAudioDevice()); + deviceFactory: static () => new MutedAudioDevice() + ); using RuntimeSession edit = m_engine.CreateSession( - CreateOptions(host, RuntimeSessionKind.Edit, "preview-edit")); + CreateOptions(host, RuntimeSessionKind.Edit, "preview-edit") + ); using RuntimeSession play = m_engine.CreateSession( - CreateOptions(host, RuntimeSessionKind.Play, "preview-play")); + CreateOptions(host, RuntimeSessionKind.Play, "preview-play") + ); AudioClipAsset clip = CreateClip(); AudioVoiceHandle voice = host.PlayPreview(edit, clip); @@ -84,32 +99,28 @@ public void PreviewUsesTheRealAudioServiceAndRejectsPlaySessionPreview() private RuntimeSessionOptions CreateOptions( IEditorAudioHost host, RuntimeSessionKind kind, - string name) - => new() - { - kind = kind, - applicationId = name, - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_root, "Persistent", name), "Logs")), - jobExecutionMode = RuntimeJobExecutionMode.SingleThread, - createSubsystems = owner => [host.CreateRuntimeSubsystemFactory(owner)] - }; + string name + ) => new() + { + kind = kind, + applicationId = name, + createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_root, "Persistent", name), "Logs")), + jobExecutionMode = RuntimeJobExecutionMode.SingleThread, + createSubsystems = owner => [host.CreateRuntimeSubsystemFactory(owner)] + }; private AudioClipAsset CreateClip() { var clip = new AudioClipAsset(); - byte[] payload = AudioClipMetadataCodec.Encode(new AudioClipMetadata( - AudioCodecId.wav, - 1, - 48000, - 480000, - 128)); + byte[] payload = AudioClipMetadataCodec.Encode(new AudioClipMetadata(AudioCodecId.wav, 1, 48000, 480000, 128)); new AssetRuntimeOwner().Initialize( clip, AssetPath.Project("Audio/Preview.wav"), "TEST", payload, isMissing: false, - version: 1); + version: 1 + ); string path = Path.Combine(m_root, "preview.wav"); File.WriteAllBytes(path, new byte[128]); m_artifacts.Add(clip.identity.persistentId, path); @@ -119,18 +130,21 @@ private AudioClipAsset CreateClip() private sealed class FakeArtifactLookup : IAssetArtifactLookup { private readonly ArtifactRetention m_retention = new(); - public ArtifactLease AcquireArtifact(Guid persistentId, string outputName) - => m_retention.Retain(m_artifacts[persistentId].info, - () => File.OpenRead(m_artifacts[persistentId].path)); + + public ArtifactLease AcquireArtifact( + Guid persistentId, + string outputName + ) => m_retention.Retain(m_artifacts[persistentId].info, () => File.OpenRead(m_artifacts[persistentId].path)); + private readonly Dictionary m_artifacts = []; internal void Add( Guid id, string path - ) - => m_artifacts.Add( - id, - (new AssetArtifactInfo(new AssetArtifactKey(new string('A', 64)), "audio-data", "TEST", 128), path)); + ) => m_artifacts.Add( + id, + (new AssetArtifactInfo(new AssetArtifactKey(new string('A', 64)), "audio-data", "TEST", 128), path) + ); public bool TryGetArtifact( Guid persistentId, diff --git a/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs b/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs index c1af81397..3058274a1 100644 --- a/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs +++ b/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs @@ -1,53 +1,52 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.IO.Compression; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using BGCS.Runtime; +using Xunit; using Inno.Adapter.Content.FileSystem; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Build.Managed; -using Inno.Content; -using Inno.Core.IO; - using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.MacOSArm64; +using Inno.Build.Managed; using Inno.Build.WindowsX64; -using Inno.Core.Identity; +using Inno.Content; using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Identity; +using Inno.Core.Input; +using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Extensibility.Types; using Inno.Editor.Core; using Inno.Editor.Exporting; using Inno.Editor.Interactions; +using Inno.Extensibility.Types; using Inno.Native.ImGui; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; -using Xunit; -using NativeImGui = Inno.Native.ImGui.ImGui; +using Inno.Testing.Build; + +using EditorUiSession = Inno.Editor.ImGui.EditorUiSession; using ImGuiEditorRuntime = Inno.Editor.ImGui.ImGuiEditorRuntime; -using Inno.Core.Input; -using Inno.Core.Logging; using NativeGui = Inno.Native.ImGui.ImGui; -using EditorUiSession = Inno.Editor.ImGui.EditorUiSession; -using Inno.Build; -using Inno.Testing.Build; +using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.Exporting.Native.Tests; public sealed class ExportPresentationTests : BuildPipelineFixture { - [Fact] [Trait("ExternalDependency", "NativeProduct")] public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportServices() @@ -58,14 +57,21 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe BuildPipeline pipeline = CreatePipeline(provisioner); var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); var buildSettings = new BuildSettingsStore( - Path.Combine(m_projectRoot, "Settings.Build.inno"), m_engine.serialization, defaults); + Path.Combine(m_projectRoot, "Settings.Build.inno"), + m_engine.serialization, + defaults + ); m_engine.modules.Register("Tests.Exporting", [ typeof(EditorExportService).Assembly, Assembly.Load(new AssemblyName("Inno.Editor.Workbench")) ]); var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); using var runtime = new EditorInteractionRuntime( - context, m_engine.types, m_engine.logs, [pipeline, buildSettings, m_settings]); + context, + m_engine.types, + m_engine.logs, + [pipeline, buildSettings, m_settings] + ); runtime.Start(); Assert.True(runtime.interactions.For("editor/main-menu").Execute("export/game")); EditorModalExtension modal = Assert.Single(runtime.modals.Where(static item => item.id == "export.game")); @@ -91,7 +97,9 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe NativeImGui.Raw.AddMouseButtonEvent(io, 0, 1); } if (frame == 3) + { NativeImGui.Raw.AddMouseButtonEvent(io, 0, 0); + } NativeImGui.NewFrame(); NativeImGui.SetNextWindowPos(new Vector2(20f), (int)ImGuiCond.Always); NativeImGui.SetNextWindowSize(new Vector2(1000f, 800f), (int)ImGuiCond.Always); @@ -127,7 +135,9 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe catch (Exception pending) when (RetirementPendingException.Find(pending) is not null) { if (retirement.Elapsed >= TimeSpan.FromSeconds(5)) + { throw; + } Thread.Sleep(1); } } @@ -140,19 +150,33 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe NativeImGui.Raw.DestroyContext(imgui); } } + [Fact] [Trait("ExternalDependency", "NativeProduct")] public unsafe void ExportFormBalancesItsTablesWhenARegisteredTargetLabelFails() { var target = new ExportLabelTarget(); - var pipeline = new BuildPipeline(m_assets, m_plugins, m_settings, m_engine.serialization, - m_engine.generations, m_compiler, m_supportPackRoot, - [new GameBuildTargetBinding(target, target)], CreateManagedDeployments()); + var pipeline = new BuildPipeline( + m_assets, + m_plugins, + m_settings, + m_engine.serialization, + m_engine.generations, + m_compiler, + m_supportPackRoot, + [new GameBuildTargetBinding(target, target)], + CreateManagedDeployments() + ); var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", target.id); - var settings = new BuildSettingsStore(System.IO.Path.Combine(m_projectRoot, "Settings.Build.inno"), - m_engine.serialization, defaults); - m_engine.modules.Register("Tests.Exporting", [typeof(EditorExportService).Assembly, - Assembly.Load(new AssemblyName("Inno.Editor.Workbench"))]); + var settings = new BuildSettingsStore( + System.IO.Path.Combine(m_projectRoot, "Settings.Build.inno"), + m_engine.serialization, + defaults + ); + m_engine.modules.Register("Tests.Exporting", [ + typeof(EditorExportService).Assembly, + Assembly.Load(new AssemblyName("Inno.Editor.Workbench")) + ]); var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")); var logs = new ExportLogSink(); ImGuiNativeContext* native = NativeGui.Raw.CreateContext(null); @@ -162,8 +186,12 @@ public unsafe void ExportFormBalancesItsTablesWhenARegisteredTargetLabelFails() m_engine.logs.RegisterSink(logs); using var session = new EditorUiSession(); using IDisposable scope = session.Enter(); - using var runtime = new EditorInteractionRuntime(context, m_engine.types, m_engine.logs, - [pipeline, settings, m_settings, session]); + using var runtime = new EditorInteractionRuntime( + context, + m_engine.types, + m_engine.logs, + [pipeline, settings, m_settings, session] + ); runtime.Start(); Assert.True(runtime.interactions.For("editor/main-menu").Execute("export/game")); EditorModalExtension modal = Assert.Single(runtime.modals, item => item.id == "export.game"); @@ -204,8 +232,10 @@ float dpi ) { var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); var settings = new BuildSettingsStore(Path.Combine(m_projectRoot, "Settings.Build.inno"), m_engine.serialization, defaults); - m_engine.modules.Register("Tests.ExportPresentation", [typeof(EditorExportService).Assembly, - Assembly.Load(new AssemblyName("Inno.Editor.Workbench"))]); + m_engine.modules.Register("Tests.ExportPresentation", [ + typeof(EditorExportService).Assembly, + Assembly.Load(new AssemblyName("Inno.Editor.Workbench")) + ]); var native = NativeGui.Raw.CreateContext(null); try { @@ -215,8 +245,12 @@ float dpi io->DeltaTime = 0.2f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; - using var runtime = new ImGuiEditorRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), - m_engine.types, m_engine.logs, [m_pipeline, settings, m_settings]); + using var runtime = new ImGuiEditorRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), + m_engine.types, + m_engine.logs, + [m_pipeline, settings, m_settings] + ); runtime.Start(); Assert.True(runtime.interactions.For("editor/main-menu").Execute("export/plugin")); NativeGui.Raw.GetStyle()->FontScaleDpi = dpi; @@ -238,7 +272,9 @@ float dpi Assert.InRange(window->ScrollMax.Y, 0f, 0.01f); } else + { Assert.True(window->ScrollMax.Y > 0f); + } Assert.True(runtime.interactions.TryGetModule(out var exports)); Assert.False(exports!.progress.isBusy); } @@ -263,7 +299,9 @@ EditorModalExtension modal bool leaked = NativeGui.Raw.GetCurrentTable() != null; // Retire only a table opened by this fixture's modal before reporting a failed regression. if (leaked) + { NativeGui.EndTable(); + } Assert.False(leaked, "A modal failure left its own native Table active."); return drawn; } @@ -277,6 +315,7 @@ EditorModalExtension modal private sealed class ExportLogSink : ILogSink { internal List messages { get; } = []; + public void Receive(LogEntry entry) => messages.Add(entry.message); } @@ -288,7 +327,9 @@ private sealed class ExportLabelTarget : IGameBuildTarget, IGameContentCompiler public ManagedDeploymentId defaultManagedDeployment => ManagedDeploymentId.coreClr; public string runtimeIdentifier => "fixture"; public string displayName => reject ? throw new InvalidOperationException("Export target label failed.") : "Fixture target"; - public void Validate(string directory) => throw new InvalidOperationException("This presentation fixture cannot validate products."); + + public void Validate(string directory) + => throw new InvalidOperationException("This presentation fixture cannot validate products."); public ValueTask PackageAsync( GameBuildPackageContext context, diff --git a/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs b/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs index b7419ec19..30a948dc0 100644 --- a/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs +++ b/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs @@ -1,16 +1,15 @@ using System.IO; +using Xunit; using Inno.Build; using Inno.Core.Input; using Inno.Editor.Core; using Inno.Editor.Exporting; using Inno.Testing.Build; -using Xunit; namespace Inno.Editor.Exporting.Tests; public sealed class ExportWorkflowTests : BuildPipelineFixture { - [Fact] public void ExportPresentationKeepsUnknownProgressAndRejectsStaleCancellation() { @@ -18,12 +17,19 @@ public void ExportPresentationKeepsUnknownProgressAndRejectsStaleCancellation() var settings = new BuildSettingsStore(Path.Combine(m_projectRoot, "Settings.Build.inno"), m_engine.serialization, defaults); m_engine.modules.Register("Tests.ExportProgress", [typeof(EditorExportService).Assembly]); var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")); - using var runtime = new Inno.Editor.Interactions.EditorInteractionRuntime(context, m_engine.types, m_engine.logs, - [m_pipeline, settings, m_settings]); + using var runtime = new Inno.Editor.Interactions.EditorInteractionRuntime( + context, + m_engine.types, + m_engine.logs, + [m_pipeline, settings, m_settings] + ); runtime.Start(); Assert.True(runtime.interactions.TryGetModule(out var exports)); - exports!.StartGame(new GameBuildRequest { profile = CreateProfile(new BuildTargetId("macos-arm64")), - outputDirectory = Path.Combine(m_root, "ProgressOutput") }); + exports!.StartGame(new GameBuildRequest + { + profile = CreateProfile(new BuildTargetId("macos-arm64")), + outputDirectory = Path.Combine(m_root, "ProgressOutput") + }); var observed = exports.progress; Assert.Null(observed.fraction); Assert.True(observed.isBusy); diff --git a/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs b/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs index b6c9d4bfb..e1c2ea4ac 100644 --- a/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs +++ b/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs @@ -1,19 +1,19 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Reload; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Graph; using Inno.Editor.Interactions; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; namespace Inno.Editor.Graph.Tests; @@ -22,7 +22,9 @@ public sealed class GraphDocumentControllerTests : IDisposable private readonly string m_testRoot = Path.Combine( Path.GetTempPath(), "InnoEditorGraphTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; @@ -35,14 +37,17 @@ public GraphDocumentControllerTests() { _ = typeof(GraphEditorModule); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(GraphDocumentControllerTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(GraphDocumentControllerTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); m_runtime = new EditorInteractionRuntime( new EditorContext(m_testRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), m_types, m_logs, - [m_serialization, m_sink, m_reloads]); + [m_serialization, m_sink, m_reloads] + ); m_runtime.Start(); } @@ -57,7 +62,9 @@ public void Dispose() GC.WaitForPendingFinalizers(); GC.Collect(); if (Directory.Exists(m_testRoot)) + { Directory.Delete(m_testRoot, recursive: true); + } } [Theory] @@ -80,13 +87,20 @@ public void AssemblyPublicationPreservesNeutralGraphAndRollsBackLaterParticipant using (AssemblyReloadSession reload = m_modules.BeginReload([new DotNetModuleSource { artifactRootDirectory = Path.Combine(m_testRoot, "Assemblies"), - moduleName = "GraphRecovery", domain = AssemblyDomain.InnoPlugin, scope = AssemblyScope.Runtime, + moduleName = "GraphRecovery", + domain = AssemblyDomain.InnoPlugin, + scope = AssemblyScope.Runtime, mainAssemblyPath = Path.Combine(directory, "Inno.Extensibility.Modules.TestModule.dll"), preloadAssemblyPaths = [Path.Combine(directory, "Reloadable.PrivateDependency.dll")] - }])) - { - if (reject) Assert.Throws(() => m_reloads.Execute(reload)); - else _ = m_reloads.Execute(reload); + }])) { + if (reject) + { + Assert.Throws(() => m_reloads.Execute(reload)); + } + else + { + _ = m_reloads.Execute(reload); + } } m_modules.generations.Wait(); Assert.Equal(GenerationState.Ready, m_modules.generations.state); @@ -111,7 +125,9 @@ public void OneHundredDocumentCyclesReleasePayloadsAndRejectRetiredControllers() Guid identity = Guid.NewGuid(); var retired = new List<(GraphDocumentController controller, WeakReference document)>(); for (int iteration = 0; iteration < 100; iteration++) + { retired.Add(OpenAndClose()); + } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); @@ -137,12 +153,21 @@ public void OneHundredDocumentCyclesReleasePayloadsAndRejectRetiredControllers() private sealed class RejectionParticipant(bool reject) : IEditorReloadParticipant, IGenerationChange { public IGenerationChange Capture(AssemblyReloadContext context) => this; - public void RefreshDiagnostics() { } - public void PrepareForActivation() { } - public void Apply() { if (reject) throw new InvalidOperationException("Later recovery participant rejected the candidate."); } - public void Complete() { } - public void RollbackStructure() { } - public void RestorePreviousState() { } + + public void RefreshDiagnostics() {} + + public void PrepareForActivation() {} + + public void Apply() + { + if (reject) throw new InvalidOperationException("Later recovery participant rejected the candidate."); + } + + public void Complete() {} + + public void RollbackStructure() {} + + public void RestorePreviousState() {} } [Fact] @@ -227,7 +252,8 @@ public void CopyPaste_RemapsNodesAndPreservesInternalConnections() GraphNodeId second = controller.AddNode("test.second", new GraphPosition(3f, 4f)); controller.Connect( new GraphEndpoint(first, new GraphPortId("out")), - new GraphEndpoint(second, new GraphPortId("in"))); + new GraphEndpoint(second, new GraphPortId("in")) + ); GraphClipboardData clipboard = controller.Copy([first, second]); IReadOnlyList pasted = controller.Paste(clipboard, new GraphPosition(10f, 20f)); @@ -290,7 +316,10 @@ public void PasteRemapRunsInsideTheSameAtomicHistoryOperation() remap ) => node.SetValue("owner", new(System.Text.Encoding.UTF8.GetBytes(remap[owner].value)))); - Assert.Equal(created[0].value, System.Text.Encoding.UTF8.GetString(controller.document.FindNode(created[1])!.values["owner"].data.Span)); + Assert.Equal( + created[0].value, + System.Text.Encoding.UTF8.GetString(controller.document.FindNode(created[1])!.values["owner"].data.Span) + ); Assert.True(history.Undo().succeeded); Assert.Equal(2, controller.document.nodes.Count); byte[] before = GraphDocumentCodec.Encode(controller.document, m_serialization); @@ -314,11 +343,14 @@ private sealed class RecordingHistory : IEditorHistory public string? faultReason => null; public long residentBytes => 0; public long diskBytes => 0; + public EditorHistoryTransaction BeginTransaction(string name) => throw new NotSupportedException(); + public EditorHistoryResult Execute( string name, EditorHistoryChange change ) => throw new NotSupportedException(); + public void RecordApplied( string name, EditorHistoryChange change @@ -326,8 +358,11 @@ EditorHistoryChange change _ = name; changes.Add(change); } + public EditorHistoryResult Undo() => throw new NotSupportedException(); + public EditorHistoryResult Redo() => throw new NotSupportedException(); + public void DisposeChanges() { foreach (EditorHistoryChange change in changes) diff --git a/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs b/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs index 29592c88e..cd56ecee3 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs @@ -83,15 +83,29 @@ private static EditorLaunchOptions CreateOptions( "dotnet", AppContext.BaseDirectory, new BuildHostDescriptor("Windows", "x64"), - new BuildTargetId("windows-x64")); + new BuildTargetId("windows-x64") + ); StandardBuildDistribution standard = StandardBuildDistribution.Create(build); - var adapters = new DefaultAuthoringAdapterCatalog(new DefaultAdapterCatalogOptions - { - platform = new Inno.Adapter.Platform.PlatformBackendCatalog([new Inno.Adapter.Platform.Sdl3.Sdl3PlatformBackendProvider(new Inno.Integration.WindowsX64.Sdl3.WindowsX64Sdl3HostIntegration())]), - rendering = new Inno.Adapter.Rendering.RenderingBackendCatalog([new Inno.Adapter.Rendering.Bgfx.BgfxRenderingBackendProvider(new Inno.Integration.WindowsX64.Bgfx.Runtime.WindowsX64BgfxSurfaceIntegration())]), - storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(Path.Combine(project, "Data"))]) - }, [new BgfxAuthoringProvider(standard.ResolveShaderTarget(new BuildTargetId("windows-x64")))], - [new Inno.Adapter.Presentation.ImGui.ImGuiPresentationProvider(new Inno.Adapter.Presentation.ImGui.ImGuiInteractionOptions(false, 1))]); + var adapters = new DefaultAuthoringAdapterCatalog( + new DefaultAdapterCatalogOptions + { + platform = new Inno.Adapter.Platform.PlatformBackendCatalog( + [new Inno.Adapter.Platform.Sdl3.Sdl3PlatformBackendProvider( + new Inno.Integration.WindowsX64.Sdl3.WindowsX64Sdl3HostIntegration() + )] + ), + rendering = new Inno.Adapter.Rendering.RenderingBackendCatalog( + [new Inno.Adapter.Rendering.Bgfx.BgfxRenderingBackendProvider( + new Inno.Integration.WindowsX64.Bgfx.Runtime.WindowsX64BgfxSurfaceIntegration() + )] + ), + storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(Path.Combine(project, "Data"))]) + }, + [new BgfxAuthoringProvider(standard.ResolveShaderTarget(new BuildTargetId("windows-x64")))], + [new Inno.Adapter.Presentation.ImGui.ImGuiPresentationProvider( + new Inno.Adapter.Presentation.ImGui.ImGuiInteractionOptions(false, 1) + )] + ); return new EditorLaunchOptions { projectDirectory = project, diff --git a/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs b/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs index 00f17913f..74dfe43df 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs @@ -1,7 +1,7 @@ using System; using System.IO; -using Inno.Editor.Hosting; using Xunit; +using Inno.Editor.Hosting; namespace Inno.Editor.Hosting.Tests; @@ -15,7 +15,9 @@ public void DependencySelectionRemainsExplicitAndCannotFallBackToSourcePreparati Assert.Null(EditorCommandLineOptions.Parse(["project"]).nativeDependencies); Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--native-dependencies", "relative.json"])); Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--native-dependencies", ""])); - Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--native-dependencies", selection, "--native-dependencies", selection])); + Assert.Throws( + () => EditorCommandLineOptions.Parse(["project", "--native-dependencies", selection, "--native-dependencies", selection]) + ); } [Fact] @@ -35,5 +37,7 @@ public void InvalidVisibilityIsRejectedBeforeComposition(string value) [Fact] public void RepeatedVisibilityIsRejectedBeforeComposition() - => Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--window-visible", "false", "--window-visible", "true"])); + => Assert.Throws( + () => EditorCommandLineOptions.Parse(["project", "--window-visible", "false", "--window-visible", "true"]) + ); } diff --git a/tests/editor/Inno.Editor.Hosting.Tests/EditorScriptProjectionCollection.cs b/tests/editor/Inno.Editor.Hosting.Tests/EditorScriptProjectionCollection.cs index 35c415d5d..c316ef91e 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/EditorScriptProjectionCollection.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/EditorScriptProjectionCollection.cs @@ -3,6 +3,4 @@ namespace Inno.Editor.Hosting.Tests; [CollectionDefinition("Editor script projection", DisableParallelization = true)] -public sealed class EditorScriptProjectionCollection -{ -} +public sealed class EditorScriptProjectionCollection; diff --git a/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs b/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs index 38e3da9dd..90c4af562 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs @@ -4,20 +4,20 @@ using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Build.Cli; using Inno.Build.Toolchains; -using Inno.Core.Identity; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Settings; using Inno.Editor.Hosting; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scripting.Compiler; -using Xunit; namespace Inno.Editor.Hosting.Tests; @@ -32,8 +32,11 @@ public void CliLogicalRuntimeReferencesIncludeAnimation() try { GenerateReferences(project, typeof(BuildApplication).Assembly); - string assembly = Directory.EnumerateFiles(Path.Combine(project, "Library", "ScriptApi"), - "Inno.ScriptApi.Runtime.dll", SearchOption.AllDirectories).Single(); + string assembly = Directory.EnumerateFiles( + Path.Combine(project, "Library", "ScriptApi"), + "Inno.ScriptApi.Runtime.dll", + SearchOption.AllDirectories + ).Single(); using FileStream stream = File.OpenRead(assembly); using var image = new PEReader(stream); MetadataReader metadata = image.GetMetadataReader(); @@ -60,10 +63,17 @@ public void LogicalEditorReferencesIncludeTheSharedProductFeatures() Directory.CreateDirectory(project); try { - GenerateReferences(project, typeof(RepositoryWikiTests).Assembly, - typeof(EditorApplication).Assembly, typeof(BuildApplication).Assembly); - string assembly = Directory.EnumerateFiles(Path.Combine(project, "Library", "ScriptApi"), - "Inno.ScriptApi.Editor.dll", SearchOption.AllDirectories).Single(); + GenerateReferences( + project, + typeof(RepositoryWikiTests).Assembly, + typeof(EditorApplication).Assembly, + typeof(BuildApplication).Assembly + ); + string assembly = Directory.EnumerateFiles( + Path.Combine(project, "Library", "ScriptApi"), + "Inno.ScriptApi.Editor.dll", + SearchOption.AllDirectories + ).Single(); using FileStream stream = File.OpenRead(assembly); using var image = new PEReader(stream); MetadataReader metadata = image.GetMetadataReader(); @@ -97,29 +107,51 @@ params System.Reflection.Assembly[] roots using IDisposable identityScope = identities.EnterScope(); using EngineHost host = new EngineHostBuilder().UseMetadataSources( new DotNetAssemblyCatalogSource(roots), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ).Build(); using IDisposable diagnostics = host.diagnostics.EnterScope(); var sources = new PluginSourceService(host.serialization, pluginsRoot, libraryRoot); PluginScanResult scan = sources.Scan(); - using var assets = new AssetPipeline(host.modules, host.types, host.serialization, identities, - host.diagnostics, host.logs, AssetPipelineOptions.Create(assetsRoot, libraryRoot) - with { enableFileSystemWatcher = false }); + using var assets = new AssetPipeline( + host.modules, + host.types, + host.serialization, + identities, + host.diagnostics, + host.logs, + AssetPipelineOptions.Create(assetsRoot, libraryRoot) + with { enableFileSystemWatcher = false } + ); using var settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.Combine(project, "Settings.Project.inno")), - host.types, host.serialization, new ProjectId("wiki.contract.validation"), - AssetSerializationContext.Create(assets)); - using var plugins = new PluginEnvironment(assets, settings, host.serialization, pluginsRoot, - libraryRoot, scan, host.modules.generations); + host.types, + host.serialization, + new ProjectId("wiki.contract.validation"), + AssetSerializationContext.Create(assets) + ); + using var plugins = new PluginEnvironment( + assets, + settings, + host.serialization, + pluginsRoot, + libraryRoot, + scan, + host.modules.generations + ); string dotnetHost = Path.Combine( Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = project, compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, project) - }, assets, plugins); + }, + assets, + plugins + ); compiler.GenerateProjectFiles(); } - } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs index 5cdff697f..31547a590 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs @@ -1,7 +1,10 @@ using System; using System.IO; using System.Numerics; +using System.Text.Json; using System.Threading; +using Xunit; +using Xunit.Abstractions; using Inno.Adapter.Modules.DotNet; using Inno.Core.Input; using Inno.Core.Logging; @@ -10,9 +13,7 @@ using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Native.ImGui; -using Xunit; -using Xunit.Abstractions; -using System.Text.Json; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.Tests; @@ -20,7 +21,9 @@ namespace Inno.Editor.ImGui.Tests; public sealed unsafe class DynamicModalTests { private readonly ITestOutputHelper m_output; + public DynamicModalTests(ITestOutputHelper output) => m_output = output; + [Fact] [Trait("Acceptance", "Visual")] public void ChangedContentFitsOnTheTransitionFrameThroughTheActualRenderer() @@ -49,6 +52,7 @@ public void ScaleMatrixBoundsCurrentTextAndActions( int height ) { foreach (float zoom in new[] { 0.75f, 0.85f, 0.9f, 1f, 1.1f, 1.25f, 1.5f }) + { foreach (float dpi in new[] { 1f, 1.25f, 1.5f, 2f }) { using var host = new ModalHost(width, height); @@ -56,30 +60,51 @@ int height NativeGui.Raw.GetStyle()->FontScaleDpi = dpi; host.Frame(); host.Frame(); - string[] messages = ["Short", "First\nSecond", new string('W', 600), "中文状态 / café / Ελληνικά\n" + new string('x', 4000), "", "Short"]; + string[] messages = + [ + "Short", + "First\nSecond", + new string('W', 600), + "中文状态 / café / Ελληνικά\n" + new string('x', 4000), + "", + "Short" + ]; foreach (string text in messages) { host.state.message = text; host.Frame(); - m_output.WriteLine(JsonSerializer.Serialize(new - { - width, height, zoom, dpi, messageLength = text.Length, - wrapWidth = host.state.wrapWidth, bodyHeight = host.state.bodyHeight, - bodyContentHeight = host.state.bodyContentHeight, - windowWidth = host.state.windowSize.X, windowHeight = host.state.windowSize.Y, - actionMinimumX = host.state.actionMin.X, actionMinimumY = host.state.actionMin.Y, - actionMaximumX = host.state.actionMax.X, actionMaximumY = host.state.actionMax.Y, - scrollMaxX = host.state.scrollMaxX - })); + m_output.WriteLine( + JsonSerializer.Serialize(new + { + width, + height, + zoom, + dpi, + messageLength = text.Length, + wrapWidth = host.state.wrapWidth, + bodyHeight = host.state.bodyHeight, + bodyContentHeight = host.state.bodyContentHeight, + windowWidth = host.state.windowSize.X, + windowHeight = host.state.windowSize.Y, + actionMinimumX = host.state.actionMin.X, + actionMinimumY = host.state.actionMin.Y, + actionMaximumX = host.state.actionMax.X, + actionMaximumY = host.state.actionMax.Y, + scrollMaxX = host.state.scrollMaxX + }) + ); Assert.True(host.state.windowSize.X <= width && host.state.windowSize.Y <= height); - Assert.True(host.state.actionMax.Y <= host.state.windowMax.Y + 1f, - $"Action exceeded the window: zoom={zoom}, dpi={dpi}, message length={text.Length}."); + Assert.True( + host.state.actionMax.Y <= host.state.windowMax.Y + 1f, + $"Action exceeded the window: zoom={zoom}, dpi={dpi}, message length={text.Length}." + ); Assert.InRange(host.state.scrollMaxX, 0f, 0.01f); Vector2 first = host.state.windowSize; host.Frame(); Assert.Equal(first, host.state.windowSize); } } + } } [Fact] @@ -315,10 +340,16 @@ internal ModalHost( io->IniFilename = null; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(DynamicModalTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(DynamicModalTests).Assembly) } + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - m_runtime = new ImGuiEditorRuntime(new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), - m_types, m_logs, [state]); + m_runtime = new ImGuiEditorRuntime( + new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), + m_types, + m_logs, + [state] + ); m_runtime.Start(); } @@ -384,6 +415,7 @@ public sealed unsafe class DynamicTestModal(DynamicModalState state) : EditorMod public override bool allowScrolling => false; public override Vector2 initialSize => state.initialSize; public override bool canResize => state.resizable; + protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize @@ -391,8 +423,15 @@ Vector2 availableContentSize state.preparations++; if (state.rejectPreparation) throw new InvalidOperationException("Rejected modal measurement."); EditorUiSession.current.widgets.style.SetZoom(state.zoom); - state.content = new(state.message, state.showProgress ? 0.5f : null, state.indeterminate, - actionLabel: state.showAction ? "Cancel" : null, actionEnabled: !state.canceled, details: state.details, cancelOnEscape: true); + state.content = new( + state.message, + state.showProgress ? 0.5f : null, + state.indeterminate, + actionLabel: state.showAction ? "Cancel" : null, + actionEnabled: !state.canceled, + details: state.details, + cancelOnEscape: true + ); state.layout = EditorUiSession.current.widgets.MeasureDialog(state.content, availableContentSize); return state.layout.size; } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/EditorUiSessionTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/EditorUiSessionTests.cs index 1e30dca5e..134b0d9f9 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/EditorUiSessionTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/EditorUiSessionTests.cs @@ -1,9 +1,10 @@ using System; using System.Threading; -using Inno.Editor.ImGui; using Xunit; +using Inno.Editor.ImGui; namespace Inno.Editor.ImGui.Tests; + public sealed class EditorUiSessionTests { [Fact] diff --git a/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs index 3e9a56636..6d0181776 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs @@ -1,18 +1,19 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading.Tasks; +using Xunit; using Inno.Adapter.Platform.Sdl3; using Inno.Adapter.Presentation.ImGui; using Inno.Native.ImGui; using Inno.Platform; -using Xunit; -using NativeImGui = Inno.Native.ImGui.ImGui; + using BackendFont = Inno.Adapter.Presentation.ImGui.ImGuiFont; using BackendFontScope = Inno.Adapter.Presentation.ImGui.ImGuiFontScope; using BackendFontStyle = Inno.Adapter.Presentation.ImGui.ImGuiFontStyle; +using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.Tests; @@ -26,12 +27,25 @@ public sealed unsafe class FontCoverageTests [Trait("Acceptance", "Visual")] public void EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(float zoom) { - string contract = nameof(FontCoverageTests) + "." + nameof(EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback) + "." + zoom.ToString(CultureInfo.InvariantCulture); + string contract = nameof(FontCoverageTests) + + "." + + nameof(EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback) + + "." + + zoom.ToString(CultureInfo.InvariantCulture); if (NativeWindowTestHost.RunIfRequired(contract)) + { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Glyph coverage", width = 640, height = 480, visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using var window = application.CreateWindow( + new PlatformWindowOptions { title = "Glyph coverage", width = 640, height = 480, visible = false } + ); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); context.SetIniFile(null); context.RenderFrame(() => { @@ -40,8 +54,13 @@ public void EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(float _ = NativeImGui.Begin("Glyph coverage", ref open, 0); try { - foreach (BackendFontStyle style in new[] { BackendFontStyle.Regular, BackendFontStyle.Bold, BackendFontStyle.Italic, BackendFontStyle.Bold | BackendFontStyle.Italic }) + foreach (BackendFontStyle style in new[] { + BackendFontStyle.Regular, + BackendFontStyle.Bold, + BackendFontStyle.Italic, + BackendFontStyle.Bold | BackendFontStyle.Italic + }) { Assert.True(BackendFont.IsAvailable(style)); using BackendFontScope scope = BackendFont.PushStyle(style); ImFont* font = NativeImGui.Raw.GetFont(); @@ -77,18 +96,33 @@ public void EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(float [Trait("Acceptance", "Lifecycle")] public void SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow() { - if (NativeWindowTestHost.RunIfRequired(nameof(FontCoverageTests) + "." + nameof(SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow))) + if (NativeWindowTestHost.RunIfRequired( + nameof(FontCoverageTests) + "." + nameof(SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Replacement context", width = 320, height = 240, visible = false }); - var original = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using var window = application.CreateWindow( + new PlatformWindowOptions { title = "Replacement context", width = 320, height = 240, visible = false } + ); + var original = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); original.SetIniFile(null); _ = CaptureSource(original); original.Dispose(); - using var replacement = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using var replacement = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); replacement.SetIniFile(null); _ = CaptureSource(replacement); - Assert.Throws(() => original.RenderFrame(static () => { })); + Assert.Throws(() => original.RenderFrame(static () => {})); } [Fact] @@ -96,30 +130,56 @@ public void SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow() public void ApplicationShutdownRetiresBothRegisteredContexts() { if (NativeWindowTestHost.RunIfRequired(nameof(FontCoverageTests) + "." + nameof(ApplicationShutdownRetiresBothRegisteredContexts))) + { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var firstWindow = application.CreateWindow(new PlatformWindowOptions { title = "First context", width = 320, height = 240, visible = false }); - using var secondWindow = application.CreateWindow(new PlatformWindowOptions { title = "Second context", width = 320, height = 240, visible = false }); - var first = application.CreateImGuiContext(firstWindow, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using var firstWindow = application.CreateWindow( + new PlatformWindowOptions { title = "First context", width = 320, height = 240, visible = false } + ); + using var secondWindow = application.CreateWindow( + new PlatformWindowOptions { title = "Second context", width = 320, height = 240, visible = false } + ); + var first = application.CreateImGuiContext( + firstWindow, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); first.SetIniFile(null); - var second = application.CreateImGuiContext(secondWindow, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + var second = application.CreateImGuiContext( + secondWindow, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); second.SetIniFile(null); _ = CaptureSource(first); _ = CaptureSource(second); application.Dispose(); - Assert.Throws(() => first.RenderFrame(static () => { })); - Assert.Throws(() => second.RenderFrame(static () => { })); + Assert.Throws(() => first.RenderFrame(static () => {})); + Assert.Throws(() => second.RenderFrame(static () => {})); } [Fact] [Trait("Acceptance", "Lifecycle")] public void RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext() { - if (NativeWindowTestHost.RunIfRequired(nameof(FontCoverageTests) + "." + nameof(RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext))) + if (NativeWindowTestHost.RunIfRequired( + nameof(FontCoverageTests) + "." + nameof(RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Retained font context", width = 320, height = 240, visible = false }); - using var retained = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using var window = application.CreateWindow( + new PlatformWindowOptions { title = "Retained font context", width = 320, height = 240, visible = false } + ); + using var retained = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); retained.SetIniFile(null); nint source = CaptureSource(retained); long baseline = CollectLiveManagedBytes(); @@ -139,10 +199,19 @@ public void RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext() public void CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons() { if (NativeWindowTestHost.RunIfRequired(nameof(FontCoverageTests) + "." + nameof(CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons))) + { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Custom font", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using var window = application.CreateWindow( + new PlatformWindowOptions { title = "Custom font", width = 320, height = 240, visible = false } + ); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); context.SetIniFile(null); string fontPath = Path.Combine(AppContext.BaseDirectory, "BuiltIn", "Fonts", "JetBrainsMono-Bold.ttf"); Assert.Throws(() => context.RegisterFontStyle(BackendFontStyle.Regular, fontPath + ".missing")); @@ -183,8 +252,15 @@ private static WeakReference CreateAndRetire( Sdl3PlatformApplication application, nint retainedSource ) { - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Retired font context", width = 320, height = 240, visible = false }); - var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer()); + using var window = application.CreateWindow( + new PlatformWindowOptions { title = "Retired font context", width = 320, height = 240, visible = false } + ); + var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new NoOutputRenderer() + ); context.SetIniFile(null); Assert.NotEqual(retainedSource, CaptureSource(context)); context.Dispose(); @@ -208,20 +284,29 @@ private sealed class NoOutputRenderer : IPlatformImGuiRenderer { public bool supportsViewports => false; public bool supportsVertexOffsets => false; - public void RenderMain(IntPtr drawData) { } + + public void RenderMain(IntPtr drawData) {} + public void SynchronizeMainOutput( int pixelWidth, int pixelHeight - ) { } + ) {} + public void CreateViewport(PlatformImGuiViewportTarget target) => throw new NotSupportedException(); + public void ResizeViewport(PlatformImGuiViewportTarget target) => throw new NotSupportedException(); + public void RenderViewport( PlatformImGuiViewportTarget target, IntPtr drawData ) => throw new NotSupportedException(); + public void PresentViewport(PlatformImGuiViewportTarget target) => throw new NotSupportedException(); + public Task RetireViewport(PlatformImGuiViewportTarget target) => Task.CompletedTask; - public void DrainViewportRetirements() { } - public void Dispose() { } + + public void DrainViewportRetirements() {} + + public void Dispose() {} } } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs index 5d99b3183..09e0f8b16 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs @@ -1,6 +1,6 @@ using System; -using Inno.Adapter.Presentation.ImGui; using Xunit; +using Inno.Adapter.Presentation.ImGui; namespace Inno.Editor.ImGui.Tests; diff --git a/tests/editor/Inno.Editor.ImGui.Tests/NativeHostFixture.cs b/tests/editor/Inno.Editor.ImGui.Tests/NativeHostFixture.cs index 77f5f7122..b8c77c349 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/NativeHostFixture.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/NativeHostFixture.cs @@ -1,15 +1,16 @@ using System; using Inno.Adapter.Platform.Sdl3; -using Inno.Integration.WindowsX64.Sdl3; using Inno.Integration.MacOSArm64.Sdl3; +using Inno.Integration.WindowsX64.Sdl3; namespace Inno.Editor.ImGui.Tests; internal static class NativeHostFixture { - internal static ISdl3HostIntegration Create() => OperatingSystem.IsWindows() - ? new WindowsX64Sdl3HostIntegration() - : OperatingSystem.IsMacOS() - ? new MacOSArm64Sdl3HostIntegration() - : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); + internal static ISdl3HostIntegration Create() + => OperatingSystem.IsWindows() + ? new WindowsX64Sdl3HostIntegration() + : OperatingSystem.IsMacOS() + ? new MacOSArm64Sdl3HostIntegration() + : throw new PlatformNotSupportedException("Native window contracts require an implemented desktop host."); } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/NativeWindowTestHost.cs b/tests/editor/Inno.Editor.ImGui.Tests/NativeWindowTestHost.cs index 10a23aed0..a4f4bef30 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/NativeWindowTestHost.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/NativeWindowTestHost.cs @@ -8,37 +8,71 @@ internal static class NativeWindowTestHost { private static readonly IReadOnlyDictionary S_CONTRACTS = new Dictionary { - ["ViewportMetricsTests.FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations"] = () => new ViewportMetricsTests().FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations(), - ["ViewportMetricsTests.FailedPreparationDoesNotBeginOrPublishANativeFrame"] = () => new ViewportMetricsTests().FailedPreparationDoesNotBeginOrPublishANativeFrame(), - ["ViewportMetricsTests.AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest"] = () => new ViewportMetricsTests().AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest(), - ["ViewportMetricsTests.ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability.False"] = () => new ViewportMetricsTests().ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability(false), - ["ViewportMetricsTests.ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability.True"] = () => new ViewportMetricsTests().ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability(true), - ["ViewportMetricsTests.FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback.False"] = () => new ViewportMetricsTests().FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback(false), - ["ViewportMetricsTests.FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback.True"] = () => new ViewportMetricsTests().FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback(true), - ["ViewportMetricsTests.MetricRefreshPreservesRequestedViewportGeometry"] = () => new ViewportMetricsTests().MetricRefreshPreservesRequestedViewportGeometry(), - ["ViewportMetricsTests.DetachedWindowAppliesRequestsAfterPlatformEventReconciliation"] = () => new ViewportMetricsTests().DetachedWindowAppliesRequestsAfterPlatformEventReconciliation(), - ["ViewportMetricsTests.LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame"] = () => new ViewportMetricsTests().LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame(), - ["ViewportMetricsTests.ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction"] = () => new ViewportMetricsTests().ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction(), - ["ViewportRetirementTests.FaultedRetirementRetainsWindowRendererAndApplicationOwners"] = () => new ViewportRetirementTests().FaultedRetirementRetainsWindowRendererAndApplicationOwners(), - ["ViewportRetirementTests.DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement"] = () => new ViewportRetirementTests().DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement(), - ["ViewportRetirementTests.IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint"] = () => new ViewportRetirementTests().IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint(), - ["ViewportRetirementTests.CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup"] = () => new ViewportRetirementTests().CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup(), - ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.0.75"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(0.75f), - ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.1"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(1f), - ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.1.5"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(1.5f), - ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.2"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(2f), - ["FontCoverageTests.CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons"] = () => new FontCoverageTests().CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons(), - ["FontCoverageTests.RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext"] = () => new FontCoverageTests().RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext(), - ["FontCoverageTests.SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow"] = () => new FontCoverageTests().SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow(), - ["FontCoverageTests.ApplicationShutdownRetiresBothRegisteredContexts"] = () => new FontCoverageTests().ApplicationShutdownRetiresBothRegisteredContexts(), + ["ViewportMetricsTests.FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations"] = () => new ViewportMetricsTests() + .FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations(), + ["ViewportMetricsTests.FailedPreparationDoesNotBeginOrPublishANativeFrame"] = () => new ViewportMetricsTests() + .FailedPreparationDoesNotBeginOrPublishANativeFrame(), + ["ViewportMetricsTests.AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest"] = () => new ViewportMetricsTests() + .AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest(), + ["ViewportMetricsTests.ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability.False"] = () => new ViewportMetricsTests().ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability( + false + ), + ["ViewportMetricsTests.ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability.True"] = () => new ViewportMetricsTests().ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability( + true + ), + ["ViewportMetricsTests.FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback.False"] = () => new ViewportMetricsTests().FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback( + false + ), + ["ViewportMetricsTests.FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback.True"] = () => new ViewportMetricsTests().FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback( + true + ), + ["ViewportMetricsTests.MetricRefreshPreservesRequestedViewportGeometry"] = () => new ViewportMetricsTests() + .MetricRefreshPreservesRequestedViewportGeometry(), + ["ViewportMetricsTests.DetachedWindowAppliesRequestsAfterPlatformEventReconciliation"] = () => new ViewportMetricsTests() + .DetachedWindowAppliesRequestsAfterPlatformEventReconciliation(), + ["ViewportMetricsTests.LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame"] = () => new ViewportMetricsTests() + .LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame(), + ["ViewportMetricsTests.ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction"] = () => new ViewportMetricsTests() + .ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction(), + ["ViewportRetirementTests.FaultedRetirementRetainsWindowRendererAndApplicationOwners"] = () => new ViewportRetirementTests() + .FaultedRetirementRetainsWindowRendererAndApplicationOwners(), + ["ViewportRetirementTests.DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement"] = () => new ViewportRetirementTests() + .DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement(), + ["ViewportRetirementTests.IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint"] = () => new ViewportRetirementTests() + .IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint(), + ["ViewportRetirementTests.CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup"] = () => new ViewportRetirementTests() + .CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup(), + ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.0.75"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback( + 0.75f + ), + ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.1"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback( + 1f + ), + ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.1.5"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback( + 1.5f + ), + ["FontCoverageTests.EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback.2"] = () => new FontCoverageTests().EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback( + 2f + ), + ["FontCoverageTests.CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons"] = () => new FontCoverageTests() + .CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons(), + ["FontCoverageTests.RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext"] = () => new FontCoverageTests() + .RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext(), + ["FontCoverageTests.SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow"] = () => new FontCoverageTests() + .SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow(), + ["FontCoverageTests.ApplicationShutdownRetiresBothRegisteredContexts"] = () => new FontCoverageTests() + .ApplicationShutdownRetiresBothRegisteredContexts() }; + private static bool m_executingContract; internal static bool RunIfRequired(string contract) { if (m_executingContract || !OperatingSystem.IsMacOS() - && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1") + && Environment.GetEnvironmentVariable("INNO_TEST_MAIN_THREAD_HOST") != "1" + ) { return false; + } NativeProcessTestHost.Run(typeof(NativeWindowTestHost).Assembly.Location, contract); return true; } @@ -48,7 +82,9 @@ private static int Main(string[] arguments) try { if (arguments.Length != 1 || !S_CONTRACTS.TryGetValue(arguments[0], out Action? contract)) + { throw new ArgumentException("The native test host requires one declared contract."); + } // Cocoa requires the process main thread, rather than an xUnit worker or a new managed thread. m_executingContract = true; Console.Error.WriteLine($"Native contract started: {arguments[0]}; thread={Environment.CurrentManagedThreadId}."); diff --git a/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs index 9e4ca602d..a03830707 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs @@ -1,10 +1,9 @@ -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; -using System.Threading.Tasks; using System; using System.Numerics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using BGCS.Runtime; +using Xunit; using Inno.Adapter.Platform; using Inno.Adapter.Platform.Sdl3; using Inno.Adapter.Presentation.ImGui; @@ -12,46 +11,63 @@ using Inno.Native.ImGui; using Inno.Native.Sdl3; using Inno.Platform; -using Xunit; + +using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; [assembly: CollectionBehavior(DisableTestParallelization = true)] + namespace Inno.Editor.ImGui.Tests; + public sealed unsafe class ViewportMetricsTests { [Fact] public void FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperations) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = application.CreateWindow(new PlatformWindowOptions { - title = "Prepared presentation frame", width = 320, height = 240, visible = false + title = "Prepared presentation frame", + width = 320, + height = 240, + visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, - new ImGuiInteractionOptions(false, 1), new FixtureRenderer()); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer() + ); context.SetIniFile(null); using var ui = new EditorUiSession(); context.SetIniFile(null); int phase = 0; - context.RenderFrame(() => - { - Assert.Equal(1, phase); - Assert.Equal(1, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); - Assert.Equal(ui.widgets.style.fontScale, NativeImGui.Raw.GetStyle()->FontScaleMain); - phase = 2; - }, () => - { - using IDisposable scope = ui.Enter(); - Assert.Equal(0, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); - Assert.Equal(new Vector2(320f, 240f), Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize)); - Assert.True(ui.widgets.style.SetZoom(1.25f)); - ui.widgets.SetupStyle(); - Assert.Throws(() => context.RenderFrame(static () => { })); - Assert.Throws(() => context.Dispose()); - phase = 1; - }); + context.RenderFrame( + () => + { + Assert.Equal(1, phase); + Assert.Equal(1, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); + Assert.Equal(ui.widgets.style.fontScale, NativeImGui.Raw.GetStyle()->FontScaleMain); + phase = 2; + }, + () => + { + using IDisposable scope = ui.Enter(); + Assert.Equal(0, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); + Assert.Equal(new Vector2(320f, 240f), Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize)); + Assert.True(ui.widgets.style.SetZoom(1.25f)); + ui.widgets.SetupStyle(); + Assert.Throws(() => context.RenderFrame(static () => {})); + Assert.Throws(() => context.Dispose()); + phase = 1; + } + ); Assert.Equal(2, phase); Assert.Equal(0, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); } @@ -59,16 +75,26 @@ public void FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperation [Fact] public void FailedPreparationDoesNotBeginOrPublishANativeFrame() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(FailedPreparationDoesNotBeginOrPublishANativeFrame))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(FailedPreparationDoesNotBeginOrPublishANativeFrame) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = application.CreateWindow(new PlatformWindowOptions { - title = "Failed frame preparation", width = 320, height = 240, visible = false + title = "Failed frame preparation", + width = 320, + height = 240, + visible = false }); var renderer = new FixtureRenderer(); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, - new ImGuiInteractionOptions(false, 1), renderer); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); bool drawn = false; var failure = new InvalidOperationException("Frame preparation failed."); @@ -82,27 +108,39 @@ public void FailedPreparationDoesNotBeginOrPublishANativeFrame() [Fact] public void AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = application.CreateWindow(new PlatformWindowOptions { - title = "Failed presentation frame", width = 320, height = 240, visible = false + title = "Failed presentation frame", + width = 320, + height = 240, + visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, - new ImGuiInteractionOptions(false, 1), new FixtureRenderer()); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer() + ); context.SetIniFile(null); var failure = new InvalidOperationException("The frame extension failed."); try { Assert.Same(failure, Assert.Throws(() => context.RenderFrame(() => throw failure))); Assert.Equal(0, NativeImGui.Raw.GetCurrentContext()->WithinFrameScope); - context.RenderFrame(static () => { }); + context.RenderFrame(static () => {}); } finally { if (NativeImGui.Raw.GetCurrentContext()->WithinFrameScope != 0) + { NativeImGui.Raw.EndFrame(); + } } } @@ -111,18 +149,30 @@ public void AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest() [InlineData(true)] public void ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability(bool supported) { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability) + "." + supported)) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability) + "." + supported + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = application.CreateWindow(new PlatformWindowOptions { - title = "Renderer capability", width = 320, height = 240, visible = false + title = "Renderer capability", + width = 320, + height = 240, + visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.None, - new ImGuiInteractionOptions(false, 1), new FixtureRenderer { supportsVertexOffsets = supported }); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.None, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer { supportsVertexOffsets = supported } + ); context.SetIniFile(null); - context.RenderFrame(() => Assert.Equal(supported, - (NativeImGui.Raw.GetIO()->BackendFlags & (int)Inno.Native.ImGui.ImGuiBackendFlags.RendererHasVtxOffset) != 0)); + context.RenderFrame(() => Assert.Equal( + supported, + (NativeImGui.Raw.GetIO()->BackendFlags & (int)Inno.Native.ImGui.ImGuiBackendFlags.RendererHasVtxOffset) != 0 + )); } [Theory] @@ -130,11 +180,21 @@ public void ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability(bool [InlineData(true)] public void FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback(bool commandKeys) { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback) + "." + commandKeys)) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback) + "." + commandKeys + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Viewport metrics", width = 320, height = 240, visible = false, highPixelDensity = true }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(commandKeys, 1), new FixtureRenderer()); + using var window = application.CreateWindow( + new PlatformWindowOptions { title = "Viewport metrics", width = 320, height = 240, visible = false, highPixelDensity = true } + ); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(commandKeys, 1), + new FixtureRenderer() + ); context.SetIniFile(null); context.RenderFrame(() => { @@ -149,23 +209,39 @@ public void FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback(bool comm Vector2 expected = new(pixelWidth / (float)logicalWidth, pixelHeight / (float)logicalHeight); Assert.Equal(expected, Unsafe.BitCast(NativeImGui.Raw.GetMainViewport()->FramebufferScale)); Assert.Equal( - SDL.Raw.GetWindowDisplayScale((SDLWindow*)window.sdlWindowHandle) / SDL.Raw.GetWindowPixelDensity((SDLWindow*)window.sdlWindowHandle), + SDL.Raw.GetWindowDisplayScale((SDLWindow*)window.sdlWindowHandle) + / SDL.Raw.GetWindowPixelDensity((SDLWindow*)window.sdlWindowHandle), NativeImGui.Raw.GetMainViewport()->DpiScale ); - Assert.Equal(new Vector2(logicalWidth, logicalHeight), Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize)); + Assert.Equal( + new Vector2(logicalWidth, logicalHeight), + Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize) + ); }); SDL.Raw.SetWindowSize((SDLWindow*)window.sdlWindowHandle, 450, 300); - context.RenderFrame(() => Assert.Equal(new Vector2(450, 300), Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize))); + context.RenderFrame( + () => Assert.Equal(new Vector2(450, 300), Unsafe.BitCast(NativeImGui.Raw.GetIO()->DisplaySize)) + ); } [Fact] public void MetricRefreshPreservesRequestedViewportGeometry() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(MetricRefreshPreservesRequestedViewportGeometry))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(MetricRefreshPreservesRequestedViewportGeometry) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Viewport geometry owner", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), new FixtureRenderer()); + using var window = application.CreateWindow( + new PlatformWindowOptions { title = "Viewport geometry owner", width = 320, height = 240, visible = false } + ); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer() + ); context.SetIniFile(null); var viewport = new ImGuiViewport { @@ -182,9 +258,7 @@ public void MetricRefreshPreservesRequestedViewportGeometry() Vector2 requestedSize = new(140, 110); viewport.Pos = viewport.WorkPos = Unsafe.BitCast(requestedPosition); viewport.Size = viewport.WorkSize = Unsafe.BitCast(requestedSize); - context.RenderFrame(() => - { - }); + context.RenderFrame(() => {}); Assert.Equal(requestedPosition, Unsafe.BitCast(viewport.Pos)); Assert.Equal(requestedPosition, Unsafe.BitCast(viewport.WorkPos)); Assert.Equal(requestedSize, Unsafe.BitCast(viewport.Size)); @@ -202,11 +276,21 @@ public void MetricRefreshPreservesRequestedViewportGeometry() [Fact] public void DetachedWindowAppliesRequestsAfterPlatformEventReconciliation() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(DetachedWindowAppliesRequestsAfterPlatformEventReconciliation))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(DetachedWindowAppliesRequestsAfterPlatformEventReconciliation) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Viewport movement", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), new FixtureRenderer()); + using var window = application.CreateWindow( + new PlatformWindowOptions { title = "Viewport movement", width = 320, height = 240, visible = false } + ); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer() + ); context.SetIniFile(null); var io = NativeImGui.Raw.GetIO(); io->ConfigViewportsNoAutoMerge = (true ? (byte)1 : (byte)0); @@ -249,18 +333,30 @@ public void DetachedWindowAppliesRequestsAfterPlatformEventReconciliation() [Fact] public void LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Logical DPI transition", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), new FixtureRenderer()); + using var window = application.CreateWindow( + new PlatformWindowOptions { title = "Logical DPI transition", width = 320, height = 240, visible = false } + ); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + new FixtureRenderer() + ); context.SetIniFile(null); float previous = 0f; context.RenderFrame(() => previous = NativeImGui.Raw.GetMainViewport()->DpiScale); var io = NativeImGui.Raw.GetPlatformIO(); Assert.True(io->Monitors.Size > 0); for (int index = 0; index < io->Monitors.Size; index++) + { io->Monitors.Data[index].DpiScale = previous * 2f; + } Assert.Equal(previous, NativeImGui.Raw.GetMainViewport()->DpiScale); context.RenderFrame(() => Assert.Equal(previous * 2f, NativeImGui.Raw.GetMainViewport()->DpiScale)); } @@ -268,12 +364,22 @@ public void LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame( [Fact] public void ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportMetricsTests) + "." + nameof(ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportMetricsTests) + "." + nameof(ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestruction) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions { title = "Viewport ownership", width = 320, height = 240, visible = false }); + using var window = application.CreateWindow( + new PlatformWindowOptions { title = "Viewport ownership", width = 320, height = 240, visible = false } + ); var renderer = new FixtureRenderer(); - using var context = application.CreateImGuiContext(window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), renderer); + using var context = application.CreateImGuiContext( + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); var viewport = new ImGuiViewport { @@ -308,30 +414,23 @@ private sealed class FixtureRenderer : IPlatformImGuiRenderer public bool supportsViewports => true; public bool supportsVertexOffsets { get; init; } - public void RenderMain(IntPtr drawData) - { - } + public void RenderMain(IntPtr drawData) {} public void SynchronizeMainOutput( int pixelWidth, int pixelHeight - ) { - } + ) {} public void CreateViewport(PlatformImGuiViewportTarget target) => this.target = target; - public void ResizeViewport(PlatformImGuiViewportTarget target) - { - } + + public void ResizeViewport(PlatformImGuiViewportTarget target) {} public void RenderViewport( PlatformImGuiViewportTarget target, IntPtr drawData - ) { - } + ) {} - public void PresentViewport(PlatformImGuiViewportTarget target) - { - } + public void PresentViewport(PlatformImGuiViewportTarget target) {} public Task RetireViewport(PlatformImGuiViewportTarget target) { @@ -339,12 +438,8 @@ public Task RetireViewport(PlatformImGuiViewportTarget target) return Task.CompletedTask; } - public void DrainViewportRetirements() - { - } + public void DrainViewportRetirements() {} - public void Dispose() - { - } + public void Dispose() {} } } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs index 636fed6f8..582b75bcc 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs @@ -1,8 +1,8 @@ -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; using System; using System.Numerics; +using System.Runtime.CompilerServices; using System.Threading.Tasks; +using Xunit; using Inno.Adapter.Platform.Sdl3; using Inno.Adapter.Presentation.ImGui; using Inno.Core.Execution; @@ -10,8 +10,9 @@ using Inno.Native.ImGui; using Inno.Native.Sdl3; using Inno.Platform; -using Xunit; + using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.ImGui.Tests; @@ -21,19 +22,29 @@ public sealed unsafe class ViewportRetirementTests [Trait("ProcessIsolation", "Required")] public void FaultedRetirementRetainsWindowRendererAndApplicationOwners() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportRetirementTests) + "." + nameof(FaultedRetirementRetainsWindowRendererAndApplicationOwners))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportRetirementTests) + "." + nameof(FaultedRetirementRetainsWindowRendererAndApplicationOwners) + )) { return; + } // A failed retirement intentionally retains dependencies until the host process restarts. // Run this contract in its own test process, rather than forcing unsafe cleanup. var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); var window = application.CreateWindow(new PlatformWindowOptions { - title = "Faulted retirement", width = 320, height = 240, visible = false + title = "Faulted retirement", + width = 320, + height = 240, + visible = false }); var renderer = new PendingRenderer(); var context = application.CreateImGuiContext( - window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), renderer); + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); var viewport = new ImGuiViewport { ID = 4221, Size = Unsafe.BitCast(new Vector2(100, 90)) }; var io = NativeImGui.Raw.GetPlatformIO(); @@ -42,7 +53,7 @@ public void FaultedRetirementRetainsWindowRendererAndApplicationOwners() io->PlatformDestroyWindow(&viewport); renderer.Fail(); - Assert.Throws(() => context.RenderFrame(static () => { })); + Assert.Throws(() => context.RenderFrame(static () => {})); Assert.Throws(() => application.DestroyImGuiContext(window)); Assert.Throws(() => application.Dispose()); Assert.False((SDL.Raw.GetWindowFromId(id) == null)); @@ -54,19 +65,34 @@ public void FaultedRetirementRetainsWindowRendererAndApplicationOwners() [Fact] public void DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportRetirementTests) + "." + nameof(DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportRetirementTests) + "." + nameof(DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = application.CreateWindow(new PlatformWindowOptions { - title = "Retirement owner", width = 320, height = 240, visible = false + title = "Retirement owner", + width = 320, + height = 240, + visible = false }); var renderer = new PendingRenderer(); using var context = application.CreateImGuiContext( - window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), renderer); + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); - var viewport = new ImGuiViewport { ID = 4218, Size = Unsafe.BitCast(new Vector2(100, 90)), Pos = Unsafe.BitCast(new Vector2(30, 30)) }; + var viewport = new ImGuiViewport + { + ID = 4218, + Size = Unsafe.BitCast(new Vector2(100, 90)), + Pos = Unsafe.BitCast(new Vector2(30, 30)) + }; var io = NativeImGui.Raw.GetPlatformIO(); io->PlatformCreateWindow(&viewport); uint id = renderer.target!.windowId; @@ -77,33 +103,48 @@ public void DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement() Assert.False(context.TryGetWindowId(viewport.ID, out _)); Assert.True(viewport.PlatformUserData == null); Assert.False((SDL.Raw.GetWindowFromId(id) == null)); - context.RenderFrame(static () => { }); + context.RenderFrame(static () => {}); Assert.False((SDL.Raw.GetWindowFromId(id) == null)); Assert.Equal(1, renderer.retireCount); renderer.Complete(); - context.RenderFrame(static () => { }); + context.RenderFrame(static () => {}); Assert.True((SDL.Raw.GetWindowFromId(id) == null)); - context.RenderFrame(static () => { }); + context.RenderFrame(static () => {}); Assert.Equal(1, renderer.retireCount); } [Fact] public void IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportRetirementTests) + "." + nameof(IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportRetirementTests) + "." + nameof(IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoint) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = application.CreateWindow(new PlatformWindowOptions { - title = "Pending drain", width = 320, height = 240, visible = false + title = "Pending drain", + width = 320, + height = 240, + visible = false }); var renderer = new PendingRenderer(); var context = application.CreateImGuiContext( - window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), renderer); + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); - var viewport = new ImGuiViewport { ID = 4219, Size = Unsafe.BitCast(new Vector2(100, 90)), Pos = Unsafe.BitCast(new Vector2(30, 30)) }; + var viewport = new ImGuiViewport + { + ID = 4219, + Size = Unsafe.BitCast(new Vector2(100, 90)), + Pos = Unsafe.BitCast(new Vector2(30, 30)) + }; NativeImGui.Raw.GetPlatformIO()->PlatformCreateWindow(&viewport); uint id = renderer.target!.windowId; @@ -112,7 +153,11 @@ public void IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoi Assert.Equal(0, renderer.disposeCount); var replacement = new PendingRenderer(); Assert.Throws(() => application.CreateImGuiContext( - window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), replacement)); + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + replacement + )); Assert.Equal(0, replacement.disposeCount); renderer.Complete(); @@ -128,17 +173,27 @@ public void IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoi [Fact] public void CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup() { - if (NativeWindowTestHost.RunIfRequired(nameof(ViewportRetirementTests) + "." + nameof(CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup))) + if (NativeWindowTestHost.RunIfRequired( + nameof(ViewportRetirementTests) + "." + nameof(CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup) + )) { return; + } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var window = application.CreateWindow(new PlatformWindowOptions { - title = "Failed creation", width = 320, height = 240, visible = false + title = "Failed creation", + width = 320, + height = 240, + visible = false }); var renderer = new PendingRenderer { failCreation = true }; using var context = application.CreateImGuiContext( - window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), renderer); + window, + ImGuiContextFlags.EnableViewports, + new ImGuiInteractionOptions(false, 1), + renderer + ); context.SetIniFile(null); var viewport = new ImGuiViewport { ID = 4220, Size = Unsafe.BitCast(new Vector2(100, 90)) }; NativeImGui.Raw.GetPlatformIO()->PlatformCreateWindow(&viewport); @@ -147,9 +202,9 @@ public void CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup() Assert.False((SDL.Raw.GetWindowFromId(id) == null)); renderer.Complete(); - Assert.Throws(() => context.RenderFrame(static () => { })); + Assert.Throws(() => context.RenderFrame(static () => {})); Assert.True((SDL.Raw.GetWindowFromId(id) == null)); - context.RenderFrame(static () => { }); + context.RenderFrame(static () => {}); } private sealed class PendingRenderer : IPlatformImGuiRenderer @@ -162,35 +217,50 @@ private sealed class PendingRenderer : IPlatformImGuiRenderer public bool supportsViewports => true; public bool supportsVertexOffsets => false; - public void RenderMain(IntPtr drawData) { } + + public void RenderMain(IntPtr drawData) {} + public void SynchronizeMainOutput( int pixelWidth, int pixelHeight - ) { } + ) {} + public void CreateViewport(PlatformImGuiViewportTarget target) { this.target = target; if (failCreation) + { throw new InvalidOperationException("The fixture rejected viewport creation."); + } } - public void ResizeViewport(PlatformImGuiViewportTarget target) { } + + public void ResizeViewport(PlatformImGuiViewportTarget target) {} + public void RenderViewport( PlatformImGuiViewportTarget target, IntPtr drawData - ) { } - public void PresentViewport(PlatformImGuiViewportTarget target) { } + ) {} + + public void PresentViewport(PlatformImGuiViewportTarget target) {} + public Task RetireViewport(PlatformImGuiViewportTarget target) { retireCount++; return m_retirement.Task; } + public void DrainViewportRetirements() { if (retireCount != 0 && !m_retirement.Task.IsCompletedSuccessfully) + { throw new RetirementPendingException("The fixture still borrows the SDL window."); + } } + public void Dispose() => disposeCount++; + internal void Complete() => m_retirement.TrySetResult(); + internal void Fail() => m_retirement.TrySetException(new InvalidOperationException("The renderer failed to retire its window.")); } } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs index 4a087a20f..a9b4e3288 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs @@ -1,19 +1,21 @@ -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; -using ImGuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; -using ImGuiCond = Inno.Editor.ImGui.ImGuiCond; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; using System; using System.Numerics; -using Inno.Native.ImGui; +using System.Runtime.CompilerServices; +using BGCS.Runtime; using Xunit; +using Inno.Native.ImGui; + +using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using ImGuiCond = Inno.Editor.ImGui.ImGuiCond; +using ImGuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; +using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; using Widget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; -using EditorImGui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.ImGui.Tests; + public sealed unsafe class WidgetLayoutTests { [Fact] @@ -41,8 +43,16 @@ public void PackedColorConversionMatchesNativeSaturationRoundingAndChannelOrder( } var random = new Random(0x2DCA); for (int index = 0; index < 4096; index++) - Verify(new(random.NextSingle() * 3f - 1f, random.NextSingle() * 3f - 1f, - random.NextSingle() * 3f - 1f, random.NextSingle() * 3f - 1f)); + { + Verify( + new( + random.NextSingle() * 3f - 1f, + random.NextSingle() * 3f - 1f, + random.NextSingle() * 3f - 1f, + random.NextSingle() * 3f - 1f + ) + ); + } } finally { @@ -196,10 +206,17 @@ public void FlattenedRowsRetainExpansionWithoutOwningNativeTreeScopes() Assert.True(root.isOpen); Assert.True(widgets.IsTreeNodeOpen("root")); Assert.Equal(nativeDepth, NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth); - var child = widgets.TreeNode("child", _ => NativeImGui.TextUnformatted("Deep child"), new() { depth = 7, isLeaf = true }); + var child = widgets.TreeNode( + "child", + _ => NativeImGui.TextUnformatted("Deep child"), + new() { depth = 7, isLeaf = true } + ); Assert.True(child.contentMin.X > root.contentMin.X); var failure = new InvalidOperationException("Rejected flat content"); - Assert.Same(failure, Assert.Throws(() => widgets.TreeNode("failed", _ => throw failure, new() { depth = 2 }))); + Assert.Same( + failure, + Assert.Throws(() => widgets.TreeNode("failed", _ => throw failure, new() { depth = 2 })) + ); Assert.Equal(nativeDepth, NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth); widgets.SetTreeNodeOpen("root", false); Assert.True(widgets.treeExpansionRevision > revision); @@ -229,10 +246,14 @@ public void TenThousandTreeRowsSubmitCustomContentOnlyWithinTheViewport() NativeImGui.TextUnformatted("Visible content"); }; for (int row = 0; row < 10_000; row++) + { _ = EditorUI.current.widgets.TreeNode("row-" + row, draw, new() { isLeaf = true }); + } Assert.InRange(drawn, 1, 64); if (frame == 1) + { NativeImGui.SetScrollY(100_000f); + } NativeImGui.End(); }); } @@ -257,7 +278,9 @@ public void FixedRowsRetainExplicitRowsAndBalanceTheirNativeOwner() submitted += end - start; preserved |= start <= 9999 && end > 9999; for (int row = start; row < end; row++) + { NativeImGui.Dummy(new(100f, NativeImGui.GetTextLineHeight())); + } }, [9999]); Assert.InRange(submitted, 1, 64); Assert.True(preserved); @@ -276,12 +299,19 @@ public void FixedRowFailureReleasesTheClipperBeforeTheNextFrame() BeginWindow("Clipper failure", new(400f, 300f)); int before = NativeImGui.Raw.GetCurrentContext()->ClipperTempDataStacked; var failure = new InvalidOperationException("Row extension rejected drawing."); - Assert.Same(failure, Assert.Throws(() => EditorUI.current.widgets.ClippedRows( - 10_000, NativeImGui.GetTextLineHeightWithSpacing(), 0, ( - state, - start, - end - ) => throw failure))); + Assert.Same( + failure, + Assert.Throws(() => EditorUI.current.widgets.ClippedRows( + 10_000, + NativeImGui.GetTextLineHeightWithSpacing(), + 0, + ( + state, + start, + end + ) => throw failure + )) + ); Assert.Equal(before, NativeImGui.Raw.GetCurrentContext()->ClipperTempDataStacked); NativeImGui.End(); }); @@ -328,13 +358,17 @@ public void ListNavigationUsesVisibleIndicesAndRespectsTextAndPopupOwnership() { catalogSource = new Inno.Adapter.Modules.DotNet.DotNetAssemblyCatalogSource(typeof(WidgetLayoutTests).Assembly) }); - using var types = new Inno.Extensibility.Types.TypeCatalog(modules, new Inno.Adapter.Modules.DotNet.ReflectionTypeCatalogSource()); + using var types = new Inno.Extensibility.Types.TypeCatalog( + modules, + new Inno.Adapter.Modules.DotNet.ReflectionTypeCatalogSource() + ); using var logs = new Inno.Core.Logging.LogRouter(); using var runtime = new Inno.Editor.Interactions.EditorInteractionRuntime( root, types, logs, - new Inno.Editor.Core.EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); + new Inno.Editor.Core.EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super") + ); runtime.Start(); using NativeContext context = new(1f); NativeImGui.Raw.GetIO()->ConfigFlags |= (int)Inno.Native.ImGui.ImGuiConfigFlags.NavEnableKeyboard; @@ -432,7 +466,8 @@ public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) drawLeadingControl: failure == "card-leading" ? rejected : null, drawTrailingControl: failure == "card-trailing" ? rejected : null, dimmed: true, - drawContextMenu: failure == "card-menu" ? rejected : null); + drawContextMenu: failure == "card-menu" ? rejected : null + ); } else { @@ -440,7 +475,9 @@ public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) _ = widgets.TreeNode("failed-tree", _ => { if (failure == "tree-content") + { rejected(); + } EditorImGui.Text("Extension"); }, new() { drawViewportOverlay = failure == "tree-overlay" ? rejected : null }); } @@ -529,7 +566,9 @@ public void TimelineWorkspace_UsesOneBoundedChildScrollOwner() if (EditorUI.current.widgets.SectionHeader("Frames")) { for (int index = 0; index < 40; index++) + { EditorImGui.Text("Frame " + index); + } } }); } @@ -606,17 +645,21 @@ public void PropertyRows_WrapWithinTwoToThreeColumnsWithoutScrollbars(float zoom { BeginWindow("Property layout", new Vector2(320f, 270f)); fontHeight = NativeImGui.GetTextLineHeight(); - EditorUI.current.widgets.PropertyRow("persistence", () => - { - labelWidth = NativeImGui.GetContentRegionAvail().X; - EditorUI.current.widgets.PropertyLabel("Persistent data directory for this exported application"); - labelSize = NativeImGui.GetItemRectSize(); - }, () => - { - valueWidth = NativeImGui.GetContentRegionAvail().X; - string value = "Application data"; - EditorUI.current.widgets.SearchInput("directory", "Directory", ref value); - }); + EditorUI.current.widgets.PropertyRow( + "persistence", + () => + { + labelWidth = NativeImGui.GetContentRegionAvail().X; + EditorUI.current.widgets.PropertyLabel("Persistent data directory for this exported application"); + labelSize = NativeImGui.GetItemRectSize(); + }, + () => + { + valueWidth = NativeImGui.GetContentRegionAvail().X; + string value = "Application data"; + EditorUI.current.widgets.SearchInput("directory", "Directory", ref value); + } + ); scroll = new Vector2(NativeImGui.GetScrollMaxX(), NativeImGui.GetScrollMaxY()); NativeImGui.End(); }); @@ -658,7 +701,9 @@ float zoom { opened = true; for (int index = 0; index < itemCount; index++) + { NativeImGui.Selectable($"Tag {index}"); + } popupPosition = NativeImGui.GetWindowPos(); popupSize = NativeImGui.GetWindowSize(); scroll = new Vector2(NativeImGui.GetScrollMaxX(), NativeImGui.GetScrollMaxY()); @@ -675,7 +720,9 @@ float zoom context.Frame(draw); context.Click((controlMinimum + controlMaximum) * 0.5f, 0, draw); for (int frame = 0; frame < 6; frame++) + { context.Frame(draw); + } Assert.True(opened); Assert.InRange(popupPosition.Y, controlMaximum.Y - 1f, controlMaximum.Y + 1f); Assert.True(popupPosition.X >= 20f); @@ -706,7 +753,9 @@ public void SelectorsNearWindowBottom_UseOnlyRemainingDownwardSpace(float vertic { opened = true; for (int index = 0; index < 100; index++) + { NativeImGui.Selectable($"Object {index}"); + } popupPosition = NativeImGui.GetWindowPos(); popupSize = NativeImGui.GetWindowSize(); EditorUI.current.widgets.EndBoundedCombo(); @@ -722,7 +771,9 @@ public void SelectorsNearWindowBottom_UseOnlyRemainingDownwardSpace(float vertic context.Frame(draw); context.Click((controlMinimum + controlMaximum) * 0.5f, 0, draw); for (int frame = 0; frame < 6; frame++) + { context.Frame(draw); + } Assert.True(opened); Assert.InRange(popupPosition.Y, controlMaximum.Y - 1f, controlMaximum.Y + 1f); Assert.True(popupPosition.Y + popupSize.Y <= 381f); @@ -768,7 +819,9 @@ public void ContextMenu_SearchFillsItsActualContentWidthWithoutScrollbars(float context.Frame(draw); context.Click((controlMinimum + controlMaximum) * 0.5f, 1, draw); for (int frame = 0; frame < 6; frame++) + { context.Frame(draw); + } Assert.True(opened); Assert.InRange(availableWidth - searchWidth, 0f, 1.1f); Assert.Equal(Vector2.Zero, scroll); @@ -786,12 +839,16 @@ public void OverlappingWindows_OnlyForegroundClickableTextReceivesPress() BeginWindow("Background panel", new Vector2(400f, 300f)); NativeImGui.SetCursorScreenPos(new Vector2(100f, 100f)); if (EditorUI.current.widgets.ClickableText("close", "X", new Vector2(40f, 40f))) + { backgroundPresses++; + } NativeImGui.End(); BeginWindow("Foreground shader", new Vector2(400f, 300f)); NativeImGui.SetCursorScreenPos(new Vector2(100f, 100f)); if (EditorUI.current.widgets.ClickableText("action", "Edit", new Vector2(40f, 40f))) + { foregroundPresses++; + } hit = (NativeImGui.GetItemRectMin() + NativeImGui.GetItemRectMax()) * 0.5f; NativeImGui.End(); }; @@ -817,21 +874,29 @@ float zoom Action draw = () => { BeginWindow("Tree content", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode($"content-{isLeaf}-{zoom}", _ => EditorUI.current.widgets.IconText( - "O", - "Selected object", - false - ), new() { isLeaf = isLeaf, drawViewportOverlay = () => - { - float rowY = NativeImGui.GetItemRectMin().Y; - NativeImGui.SetCursorScreenPos(new Vector2(360f, rowY)); - _ = EditorUI.current.widgets.ClickableIcon("visibility", "V", "Visibility"); - } }); + var result = EditorUI.current.widgets.TreeNode( + $"content-{isLeaf}-{zoom}", + _ => EditorUI.current.widgets.IconText("O", "Selected object", false), + new() + { + isLeaf = isLeaf, + drawViewportOverlay = () => + { + float rowY = NativeImGui.GetItemRectMin().Y; + NativeImGui.SetCursorScreenPos(new Vector2(360f, rowY)); + _ = EditorUI.current.widgets.ClickableIcon("visibility", "V", "Visibility"); + } + } + ); hit = new Vector2(result.contentMin.X + 80f, (result.min.Y + result.max.Y) * 0.5f); if (result.isClicked) + { presses++; + } if (result.isOpen) + { NativeImGui.TreePop(); + } NativeImGui.End(); }; context.Frame(draw); @@ -850,13 +915,21 @@ public void TreeRows_DisclosureClickExpandsWithoutSelectingContent() Action draw = () => { BeginWindow("Tree disclosure", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode("disclosure", _ => NativeImGui.TextUnformatted("Parent"), new() { isLeaf = false }); + var result = EditorUI.current.widgets.TreeNode( + "disclosure", + _ => NativeImGui.TextUnformatted("Parent"), + new() { isLeaf = false } + ); hit = new Vector2(result.contentMin.X - NativeImGui.GetTreeNodeToLabelSpacing() * 0.5f, (result.min.Y + result.max.Y) * 0.5f); opened = result.isOpen; if (result.isClicked) + { presses++; + } if (result.isOpen) + { NativeImGui.TreePop(); + } NativeImGui.End(); }; context.Frame(draw); @@ -879,16 +952,28 @@ public void TreeRows_OverlayConsumesItsOwnClick(bool settleHover) Action draw = () => { BeginWindow("Tree overlay", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode($"overlay-{settleHover}", _ => NativeImGui.TextUnformatted("Object"), new() { isLeaf = true, drawViewportOverlay = () => - { - float rowY = NativeImGui.GetItemRectMin().Y; - NativeImGui.SetCursorScreenPos(new Vector2(360f, rowY)); - if (NativeImGui.SmallButton("Eye")) - overlayPresses++; - overlayHit = (NativeImGui.GetItemRectMin() + NativeImGui.GetItemRectMax()) * 0.5f; - } }); + var result = EditorUI.current.widgets.TreeNode( + $"overlay-{settleHover}", + _ => NativeImGui.TextUnformatted("Object"), + new() + { + isLeaf = true, + drawViewportOverlay = () => + { + float rowY = NativeImGui.GetItemRectMin().Y; + NativeImGui.SetCursorScreenPos(new Vector2(360f, rowY)); + if (NativeImGui.SmallButton("Eye")) + { + overlayPresses++; + } + overlayHit = (NativeImGui.GetItemRectMin() + NativeImGui.GetItemRectMax()) * 0.5f; + } + } + ); if (result.isClicked) + { rowPresses++; + } NativeImGui.End(); }; context.Frame(draw); @@ -909,15 +994,25 @@ public void TreeRows_ContentDoubleClickExpandsOnce() Action draw = () => { BeginWindow("Tree double click", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode("double-click", _ => NativeImGui.TextUnformatted("Parent"), new() { isLeaf = false }); + var result = EditorUI.current.widgets.TreeNode( + "double-click", + _ => NativeImGui.TextUnformatted("Parent"), + new() { isLeaf = false } + ); hit = new Vector2(result.contentMin.X + 80f, (result.min.Y + result.max.Y) * 0.5f); opened = result.isOpen; if (result.isClicked) + { presses++; + } if (result.isDoubleClicked) + { doublePresses++; + } if (result.isOpen) + { NativeImGui.TreePop(); + } NativeImGui.End(); }; context.Frame(draw); @@ -946,7 +1041,9 @@ public void MixedValueRestoresOuterStateAfterNestedGroupsAndFailures() Assert.True(widgets.isMixedValue); }); Assert.False(widgets.isMixedValue); - Assert.Throws(() => widgets.MixedValue(true, () => throw new InvalidOperationException("rejected draw"))); + Assert.Throws( + () => widgets.MixedValue(true, () => throw new InvalidOperationException("rejected draw")) + ); Assert.False(widgets.isMixedValue); NativeImGui.End(); }); @@ -979,6 +1076,7 @@ private sealed class NativeContext : IDisposable private readonly ImGuiNativeContext* m_context; private readonly Inno.Editor.ImGui.EditorUiSession m_ui = new(); private readonly IDisposable m_uiScope; + public NativeContext(float zoom) { m_context = NativeImGui.Raw.CreateContext(null); @@ -1009,7 +1107,9 @@ public void Click( ImGuiIO* io = NativeImGui.Raw.GetIO(); NativeImGui.Raw.AddMousePosEvent(io, position.X, position.Y); if (settleHover) + { Frame(draw); + } NativeImGui.Raw.AddMouseButtonEvent(io, button, (true ? (byte)1 : (byte)0)); Frame(draw); NativeImGui.Raw.AddMouseButtonEvent(io, button, (false ? (byte)1 : (byte)0)); diff --git a/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs b/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs index 85d9cbbab..38f878294 100644 --- a/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs +++ b/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs @@ -1,18 +1,19 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; using System.Linq; -using Inno.Editor.Annotations; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Logging; using Inno.Core.Serialization; +using Inno.Editor.Annotations; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Editor.Inspection.Tests; + public sealed class ConditionalInspectionTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "inno-inspection-" + Guid.NewGuid().ToString("N")); @@ -21,13 +22,19 @@ public sealed class ConditionalInspectionTests : IDisposable private readonly SerializationRegistry m_serialization; private readonly LogRouter m_logs = new(); private readonly EditorInteractionRuntime m_runtime; + public ConditionalInspectionTests() { Directory.CreateDirectory(m_root); m_modules = new(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConditionalInspectionTests).Assembly) }); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); - m_runtime = new(new EditorContext(m_root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), m_types, m_logs, [m_types, m_serialization]); + m_runtime = new( + new EditorContext(m_root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + m_types, + m_logs, + [m_types, m_serialization] + ); m_runtime.Start(); } @@ -42,9 +49,13 @@ public void ConditionalInspectorPeersResolveByPredicateAndRejectActualAmbiguity( Assert.IsType(first); Assert.True(inspectors.TryResolveExact(m_runtime.context, new ConditionalTarget(2, false), renderer, out var second, out _)); Assert.IsType(second); - InvalidOperationException error = Assert.Throws(() => inspectors.TryResolve(m_runtime.context, new ConditionalTarget(2, true), renderer, out _, out _)); + InvalidOperationException error = Assert.Throws( + () => inspectors.TryResolve(m_runtime.context, new ConditionalTarget(2, true), renderer, out _, out _) + ); Assert.Contains("both accept", error.Message); - Assert.Throws(() => inspectors.TryResolveExact(m_runtime.context, new ConditionalTarget(2, true), renderer, out _, out _)); + Assert.Throws( + () => inspectors.TryResolveExact(m_runtime.context, new ConditionalTarget(2, true), renderer, out _, out _) + ); IInspectionDrawer CreateDrawer(Type type) => (IInspectionDrawer)Activator.CreateInstance(type, nonPublic: true)!; } @@ -60,7 +71,12 @@ public void PropertyAvailabilityUsesCurrentOwnerConditionsWithoutRequiringNative Assert.False(renderer.GetPropertyAvailability(target, conditional).isVisible); target.visible = true; Assert.True(renderer.GetPropertyAvailability(target, conditional).isVisible); - Assert.True(renderer.GetPropertyAvailability(target, values.Single(value => value.name == nameof(AvailabilityTarget.readOnlyValue))).isReadOnly); + Assert.True( + renderer.GetPropertyAvailability( + target, + values.Single(value => value.name == nameof(AvailabilityTarget.readOnlyValue)) + ).isReadOnly + ); } [StableTypeId("eeeb7c59-2af3-4cc3-81d2-c853feef3874")] @@ -79,21 +95,23 @@ public sealed record ConditionalTarget( int kind, bool ambiguous ); + [InspectionDrawer(typeof(ConditionalTarget), conditional: true)] public sealed class ConditionalFirst : InspectionDrawer { public override string icon => ""; protected override bool CanInspect(ConditionalTarget target) => target.kind == 1; + protected override (string name, Action? setter) BindName( InspectionDrawContext context, ConditionalTarget target ) => ("First", null); + protected override void Draw( InspectionDrawContext context, ConditionalTarget target - ) { - } + ) {} } [InspectionDrawer(typeof(ConditionalTarget), conditional: true)] @@ -102,15 +120,16 @@ public sealed class ConditionalSecond : InspectionDrawer public override string icon => ""; protected override bool CanInspect(ConditionalTarget target) => target.kind == 2; + protected override (string name, Action? setter) BindName( InspectionDrawContext context, ConditionalTarget target ) => ("Second", null); + protected override void Draw( InspectionDrawContext context, ConditionalTarget target - ) { - } + ) {} } [InspectionDrawer(typeof(ConditionalTarget), conditional: true)] @@ -119,15 +138,16 @@ public sealed class ConditionalOverlap : InspectionDrawer public override string icon => ""; protected override bool CanInspect(ConditionalTarget target) => target.ambiguous; + protected override (string name, Action? setter) BindName( InspectionDrawContext context, ConditionalTarget target ) => ("Overlap", null); + protected override void Draw( InspectionDrawContext context, ConditionalTarget target - ) { - } + ) {} } private sealed class ProbePropertyEdits : IInspectionPropertyEditService diff --git a/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs b/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs index 73c4c5b5e..71c885c76 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs @@ -1,15 +1,16 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Editor.Interactions; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Editor.Interactions.Tests; + public sealed class EditorHistoryTests { [Fact] @@ -19,7 +20,9 @@ public void SeparateGesturesNeverMergeTheSamePropertyAcrossCommitBoundaries() for (int step = 0; step < 2; step++) { using var gesture = new EditorEditGesture(fixture.history, "Drag Value"); - Assert.True(fixture.history.Execute("Update", NeutralValueHistoryHandler.CreateChange(1, step, step + 1, gesture.mergeKey)).succeeded); + Assert.True( + fixture.history.Execute("Update", NeutralValueHistoryHandler.CreateChange(1, step, step + 1, gesture.mergeKey)).succeeded + ); gesture.Commit(); } @@ -87,7 +90,10 @@ public void RejectedOutOfOrderCompletionPreservesBothTransactions(string complet public void ExecuteUndoAndRedoMoveNeutralChangeBetweenStacks() { using var fixture = new HistoryFixture(); - EditorHistoryResult applied = fixture.history.Execute("Change Value", NeutralValueHistoryHandler.CreateChange(slot: 1, before: 0, after: 10)); + EditorHistoryResult applied = fixture.history.Execute( + "Change Value", + NeutralValueHistoryHandler.CreateChange(slot: 1, before: 0, after: 10) + ); Assert.True(applied.succeeded); Assert.Equal(10, NeutralValueHistoryHandler.GetValue(1)); Assert.Equal("Change Value", fixture.history.undoName); @@ -102,7 +108,9 @@ public void ExecuteUndoAndRedoMoveNeutralChangeBetweenStacks() public void FailedTransitionRemainsAvailableForRetry() { using var fixture = new HistoryFixture(); - Assert.True(fixture.history.Execute("Conditional", NeutralValueHistoryHandler.CreateChange(slot: 1, before: 0, after: 1)).succeeded); + Assert.True( + fixture.history.Execute("Conditional", NeutralValueHistoryHandler.CreateChange(slot: 1, before: 0, after: 1)).succeeded + ); NeutralValueHistoryHandler.Block(slot: 1, EditorHistoryDirection.Undo); Assert.False(fixture.history.Undo().succeeded); Assert.True(fixture.history.canUndo); @@ -230,7 +238,10 @@ public void CompensationFailureFaultsHistoryAndRejectsFurtherTransactions() public void MissingHandlerCreatesAnExplicitAvailabilityBarrier() { using var fixture = new HistoryFixture(); - fixture.history.RecordApplied("Unavailable Change", new EditorHistoryChange("tests/missing-history-handler", EditorHistoryPayload.FromBytes([1, 2, 3]))); + fixture.history.RecordApplied( + "Unavailable Change", + new EditorHistoryChange("tests/missing-history-handler", EditorHistoryPayload.FromBytes([1, 2, 3])) + ); Assert.False(fixture.history.canUndo); Assert.Contains("tests/missing-history-handler", fixture.history.undoUnavailableReason); Assert.False(fixture.history.Undo().succeeded); @@ -246,7 +257,10 @@ public void LargePayloadUsesTheBoundedSessionDiskStore() BitConverter.GetBytes(9).CopyTo(payload, sizeof(int)); BitConverter.GetBytes(32).CopyTo(payload, sizeof(int) * 2); NeutralValueHistoryHandler.SetValue(slot: 1, value: 32); - fixture.history.RecordApplied("Large Neutral Change", new EditorHistoryChange(NeutralValueHistoryHandler.KIND, EditorHistoryPayload.FromBytes(payload))); + fixture.history.RecordApplied( + "Large Neutral Change", + new EditorHistoryChange(NeutralValueHistoryHandler.KIND, EditorHistoryPayload.FromBytes(payload)) + ); Assert.Equal(0, fixture.history.residentBytes); Assert.Equal(payload.LongLength, fixture.history.diskBytes); Assert.True(fixture.history.Undo().succeeded); @@ -272,11 +286,14 @@ private sealed class HistoryFixture : IDisposable private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoEditorHistoryTests", Guid.NewGuid().ToString("N")); private readonly ModuleHost m_modules; private readonly LogRouter m_logs = new(); + internal HistoryFixture() { Directory.CreateDirectory(Path.Combine(m_projectRoot, "Assets")); NeutralValueHistoryHandler.Reset(); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorHistoryTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorHistoryTests).Assembly) } + ); types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); runtime = new EditorInteractionRuntime( new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), @@ -298,7 +315,9 @@ public void Dispose() m_modules.Dispose(); m_logs.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } } } @@ -309,6 +328,7 @@ public sealed class NeutralValueHistoryHandler : EditorHistoryHandler public const string KIND = "tests/neutral-values"; private static readonly HashSet<(int Slot, EditorHistoryDirection Direction)> S_BLOCKED = []; private static readonly Dictionary S_VALUES = []; + public static EditorHistoryChange CreateChange( int slot, int before, @@ -323,18 +343,22 @@ public static EditorHistoryChange CreateChange( } public static int GetValue(int slot) => S_VALUES.TryGetValue(slot, out int value) ? value : 0; + public static void SetValue( int slot, int value ) => S_VALUES[slot] = value; + public static void Block( int slot, EditorHistoryDirection direction ) => S_BLOCKED.Add((slot, direction)); + public static void Unblock( int slot, EditorHistoryDirection direction ) => S_BLOCKED.Remove((slot, direction)); + public static void Reset() { S_BLOCKED.Clear(); @@ -345,7 +369,10 @@ protected override EditorHistoryAvailability Query( EditorHistoryContext context, EditorHistoryChange change, EditorHistoryDirection direction - ) => change.payload.length >= sizeof(int) * 3 ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); + ) => change.payload.length >= sizeof(int) * 3 + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); + protected override EditorHistoryResult Apply( EditorHistoryContext context, EditorHistoryChange change, @@ -354,7 +381,9 @@ EditorHistoryDirection direction byte[] bytes = change.payload.ReadBytes(); int slot = BitConverter.ToInt32(bytes, 0); if (S_BLOCKED.Contains((slot, direction))) + { return EditorHistoryResult.Failure($"Slot {slot} is blocked for {direction}."); + } int offset = direction == EditorHistoryDirection.Undo ? sizeof(int) : sizeof(int) * 2; S_VALUES[slot] = BitConverter.ToInt32(bytes, offset); return EditorHistoryResult.Success(); @@ -374,7 +403,12 @@ out EditorHistoryChange? merged return false; } - merged = CreateChange(slot, BitConverter.ToInt32(olderBytes, sizeof(int)), BitConverter.ToInt32(newerBytes, sizeof(int) * 2), older.mergeKey); + merged = CreateChange( + slot, + BitConverter.ToInt32(olderBytes, sizeof(int)), + BitConverter.ToInt32(newerBytes, sizeof(int) * 2), + older.mergeKey + ); return true; } } diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs index f544b02d9..6f1315fcb 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs @@ -1,12 +1,13 @@ using System; +using Xunit; using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; -using Xunit; namespace Inno.Editor.Interactions.Tests; + public sealed partial class SceneHistoryTests { [Fact] @@ -38,13 +39,29 @@ public void BatchAxisEditPreservesUneditedComponentsIncludingEqualPrimarySamples var second = scene.CreateObject("Second").transform; first.localPosition = new(1, 2, 3); second.localPosition = new(4, 5, 6); - Assert.True(m_edits.ChangeProperties([first, second], "localPosition", () => first.localPosition = new(9, 2, 3), "Edit X", componentName: "x")); + Assert.True( + m_edits.ChangeProperties( + [first, second], + "localPosition", + () => first.localPosition = new(9, 2, 3), + "Edit X", + componentName: "x" + ) + ); Assert.Equal(new Inno.Core.Mathematics.Vector3(9, 5, 6), second.localPosition); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal(new Inno.Core.Mathematics.Vector3(4, 5, 6), second.localPosition); - Assert.True(m_edits.ChangeProperties([first, second], "localPosition", () => { }, "Use Primary X", componentName: "x")); + Assert.True(m_edits.ChangeProperties([first, second], "localPosition", () => {}, "Use Primary X", componentName: "x")); Assert.Equal(new Inno.Core.Mathematics.Vector3(1, 5, 6), second.localPosition); - Assert.Throws(() => m_edits.ChangeProperties([first, second], "localPosition", () => first.localPosition = default, "Rejected Component", componentName: "notAComponent")); + Assert.Throws( + () => m_edits.ChangeProperties( + [first, second], + "localPosition", + () => first.localPosition = default, + "Rejected Component", + componentName: "notAComponent" + ) + ); Assert.Equal(new Inno.Core.Mathematics.Vector3(1, 2, 3), first.localPosition); } @@ -126,6 +143,8 @@ internal sealed class BatchValidationComponent : GameComponent private void Validate() { if (rejectAnswer && value == 42) + { throw new InvalidOperationException("The current owner rejected this batch value."); + } } } diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs index fa569eba9..4c4696e42 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs @@ -1,26 +1,27 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; using System.Linq; using System.Runtime.CompilerServices; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Reload; using Inno.Core.Identity; -using Inno.Extensibility.Types; +using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Scene; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; -using Xunit; namespace Inno.Editor.Interactions.Tests; + public sealed partial class SceneHistoryTests : IDisposable { private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoSceneHistoryTests", Guid.NewGuid().ToString("N")); @@ -31,6 +32,7 @@ public sealed partial class SceneHistoryTests : IDisposable private readonly EditorInteractionRuntime m_runtime; private readonly SceneEdits m_edits; private readonly EditorReloadCoordinator m_reloads = new(); + public SceneHistoryTests() { Directory.CreateDirectory(Path.Combine(m_projectRoot, "Assets")); @@ -40,7 +42,17 @@ public SceneHistoryTests() new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource() ).Build(); - m_session = m_host.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Edit, applicationId = "inno.tests.scene-history", createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_projectRoot, "Library", "PersistentData", "inno.tests.scene-history"), "Logs")), jobExecutionMode = RuntimeJobExecutionMode.SingleThread }); + m_session = m_host.CreateSession( + new RuntimeSessionOptions + { + kind = RuntimeSessionKind.Edit, + applicationId = "inno.tests.scene-history", + createLogSink = _ => new FileLogSink( + Path.Combine(Path.Combine(m_projectRoot, "Library", "PersistentData", "inno.tests.scene-history"), "Logs") + ), + jobExecutionMode = RuntimeJobExecutionMode.SingleThread + } + ); m_executionScope = m_session.EnterExecutionScope(); m_assets = new AssetPipeline( m_host.modules, @@ -49,7 +61,10 @@ public SceneHistoryTests() new IdentityAllocator(), m_host.diagnostics, m_host.logs, - AssetPipelineOptions.Create(Path.Combine(m_projectRoot, "Assets"), Path.Combine(m_projectRoot, "Library"))with { enableFileSystemWatcher = false } + AssetPipelineOptions.Create( + Path.Combine(m_projectRoot, "Assets"), + Path.Combine(m_projectRoot, "Library") + )with { enableFileSystemWatcher = false } ); m_runtime = new EditorInteractionRuntime( new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), @@ -70,7 +85,9 @@ public void Dispose() m_session.Dispose(); m_host.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } [Fact] @@ -83,7 +100,15 @@ public void PropertyUndoRestoresOnlyThePropertyOnTheExistingSceneGraph() Guid sceneId = scene.identity.persistentId; Guid objectId = gameObject.identity.persistentId; Guid componentId = component.identity.persistentId; - Assert.True(m_edits.ChangeProperty(component, nameof(HistoryComponent.value), () => component.value = 25, "Change Value", "tests:component-value")); + Assert.True( + m_edits.ChangeProperty( + component, + nameof(HistoryComponent.value), + () => component.value = 25, + "Change Value", + "tests:component-value" + ) + ); Assert.Equal(25, component.value); EditorHistoryResult undo = m_runtime.interactions.history.Undo(); Assert.True(undo.succeeded, undo.message); @@ -101,7 +126,14 @@ public void PropertyUndoRestoresEverySiblingChangedByThePrimarySetter() var component = CreateScene().CreateObject("Coupled").AddComponent(); Assert.True(component.primary); Assert.Equal(CoupledHistoryMode.Base, component.mode); - Assert.True(m_edits.ChangeProperty(component, nameof(CoupledHistoryComponent.mode), () => component.mode = CoupledHistoryMode.Overlay, "Change Coupled Mode")); + Assert.True( + m_edits.ChangeProperty( + component, + nameof(CoupledHistoryComponent.mode), + () => component.mode = CoupledHistoryMode.Overlay, + "Change Coupled Mode" + ) + ); Assert.Equal(CoupledHistoryMode.Overlay, component.mode); Assert.False(component.primary); EditorHistoryResult undo = m_runtime.interactions.history.Undo(); @@ -124,9 +156,25 @@ public void TransformManipulationTransactionUndoesAllLocalValuesAtomically() var scale = new Inno.Core.Mathematics.Vector3(2f, 3f, 4f); using (EditorHistoryTransaction transaction = m_runtime.interactions.history.BeginTransaction("Move GameObject")) { - Assert.True(m_edits.ChangeProperty(transform, nameof(Transform.localPosition), () => transform.localPosition = position, "Move GameObject")); - Assert.True(m_edits.ChangeProperty(transform, nameof(Transform.localRotation), () => transform.localRotation = rotation, "Move GameObject")); - Assert.True(m_edits.ChangeProperty(transform, nameof(Transform.localScale), () => transform.localScale = scale, "Move GameObject")); + Assert.True( + m_edits.ChangeProperty( + transform, + nameof(Transform.localPosition), + () => transform.localPosition = position, + "Move GameObject" + ) + ); + Assert.True( + m_edits.ChangeProperty( + transform, + nameof(Transform.localRotation), + () => transform.localRotation = rotation, + "Move GameObject" + ) + ); + Assert.True( + m_edits.ChangeProperty(transform, nameof(Transform.localScale), () => transform.localScale = scale, "Move GameObject") + ); transaction.Commit(); } @@ -153,7 +201,14 @@ public void WorldPositionEditRestoresLocalStorageAndWorldResultThroughHistory() var beforeLocal = child.localPosition; var beforeWorld = child.worldPosition; var requestedWorld = new Inno.Core.Mathematics.Vector3(11f, 7f, 20f); - Assert.True(m_edits.ChangeProperty(child, nameof(Transform.localPosition), () => child.worldPosition = requestedWorld, "Edit World Position")); + Assert.True( + m_edits.ChangeProperty( + child, + nameof(Transform.localPosition), + () => child.worldPosition = requestedWorld, + "Edit World Position" + ) + ); var afterLocal = child.localPosition; Assert.Equal(requestedWorld, child.worldPosition); Assert.NotEqual(beforeLocal, afterLocal); @@ -292,6 +347,7 @@ bool rejectRestore [MethodImpl(MethodImplOptions.NoInlining)] private void AssertRejectedHistoryModule() => Assert.ThrowsAny(() => ReloadHistoryModule(install: true)); + [Fact] public void MissingComponentEditsPreserveOriginalStateAndRecoveryDoesNotDirtySavedScene() { @@ -389,11 +445,14 @@ int missingRuntimeId private void ReloadHistoryModule(bool install) { DotNetModuleSource request = CreateHistoryRequest(); - using AssemblyReloadSession reload = install ? m_host.modules.BeginReload([request]) : m_host.modules.BeginReload([], [request.moduleName]); + using AssemblyReloadSession reload = install + ? m_host.modules.BeginReload([request]) + : m_host.modules.BeginReload([], [request.moduleName]); _ = m_reloads.Execute(reload); } - private DotNetModuleSource CreateHistoryRequest() => new() + private DotNetModuleSource CreateHistoryRequest() + => new() { moduleName = "SceneHistoryRecovery", artifactRootDirectory = Path.Combine(m_projectRoot, "Library", "Modules"), @@ -401,6 +460,7 @@ private void ReloadHistoryModule(bool install) domain = AssemblyDomain.InnoPlugin, scope = AssemblyScope.Runtime }; + [Fact] public void ExternalResolversAreRestoredBeforeDomainPropertyCompensation() { @@ -408,7 +468,12 @@ public void ExternalResolversAreRestoredBeforeDomainPropertyCompensation() var participant = new ExternalRecoveryOrder(() => externalCandidateActive); using IDisposable registration = m_reloads.Register(participant); using AssemblyReloadSession reload = m_host.modules.BeginReload([CreateHistoryRequest()]); - Assert.Throws(() => m_reloads.Execute(reload, new ExternalContentChange(() => externalCandidateActive = true, () => externalCandidateActive = false))); + Assert.Throws( + () => m_reloads.Execute( + reload, + new ExternalContentChange(() => externalCandidateActive = true, () => externalCandidateActive = false) + ) + ); Assert.True(participant.restored); Assert.False(externalCandidateActive); reload.Dispose(); @@ -421,18 +486,13 @@ private sealed class ExternalContentChange( Action restore ) : IGenerationChange { - public void PrepareForActivation() - { - } + public void PrepareForActivation() {} public void Apply() => activate(); - public void Complete() - { - } - public void RollbackStructure() - { - } + public void Complete() {} + + public void RollbackStructure() {} public void RestorePreviousState() => restore(); } @@ -442,11 +502,11 @@ private sealed class ExternalRecoveryOrder(Func externalCandidateActive) : internal bool restored { get; private set; } public IGenerationChange Capture(AssemblyReloadContext context) => this; - public void RefreshDiagnostics() - { - } + + public void RefreshDiagnostics() {} public void PrepareForActivation() => Assert.False(externalCandidateActive()); + public void Apply() { Assert.True(externalCandidateActive()); @@ -454,6 +514,7 @@ public void Apply() } public void RollbackStructure() => Assert.True(externalCandidateActive()); + public void RestorePreviousState() { Assert.False(externalCandidateActive()); @@ -508,8 +569,28 @@ public void ElementRestoreRejectsAnotherLogicalTypesPayloadBeforeAttachingElemen TypeRef systemType = m_host.types.GetTypeRef(typeof(HistorySystem)); Guid componentId = Guid.NewGuid(); Guid systemId = Guid.NewGuid(); - InvalidDataException componentFailure = Assert.Throws(() => SceneElementSerialization.RestoreComponent(owner, componentType, componentId, componentIndex: owner.GetComponents().Count, incompatibleState, m_host.serialization, m_assets)); - InvalidDataException systemFailure = Assert.Throws(() => SceneElementSerialization.RestoreSystem(scene, systemType, systemId, systemIndex: scene.GetSystems().Count, incompatibleState, m_host.serialization, m_assets)); + InvalidDataException componentFailure = Assert.Throws( + () => SceneElementSerialization.RestoreComponent( + owner, + componentType, + componentId, + componentIndex: owner.GetComponents().Count, + incompatibleState, + m_host.serialization, + m_assets + ) + ); + InvalidDataException systemFailure = Assert.Throws( + () => SceneElementSerialization.RestoreSystem( + scene, + systemType, + systemId, + systemIndex: scene.GetSystems().Count, + incompatibleState, + m_host.serialization, + m_assets + ) + ); Assert.Contains("type", componentFailure.Message, StringComparison.OrdinalIgnoreCase); Assert.Contains("type", systemFailure.Message, StringComparison.OrdinalIgnoreCase); Assert.Null(IdentityAllocator.current.Get(componentId)); @@ -526,7 +607,17 @@ public void ElementRestoreRemovesPartialElementWhenRestoreCallbackFails() GameObject targetOwner = scene.CreateObject("Target"); TypeRef typeRef = m_host.types.GetTypeRef(typeof(RestoreCleanupFailureComponent)); Guid persistentId = Guid.NewGuid(); - _ = Assert.ThrowsAny(() => SceneElementSerialization.RestoreComponent(targetOwner, typeRef, persistentId, componentIndex: targetOwner.GetComponents().Count, state, m_host.serialization, m_assets)); + _ = Assert.ThrowsAny( + () => SceneElementSerialization.RestoreComponent( + targetOwner, + typeRef, + persistentId, + componentIndex: targetOwner.GetComponents().Count, + state, + m_host.serialization, + m_assets + ) + ); Assert.Null(IdentityAllocator.current.Get(persistentId)); } @@ -546,7 +637,9 @@ public void FailedSubtreeRestoreRemovesEveryCreatedObjectDespiteDestructionCallb SubtreeRestoreFailureComponent.throwOnDestroy = true; try { - _ = Assert.ThrowsAny(() => SceneSubtreeSerialization.Restore(scene, state, m_host.serialization, m_assets, parent: null, siblingIndex: 0)); + _ = Assert.ThrowsAny( + () => SceneSubtreeSerialization.Restore(scene, state, m_host.serialization, m_assets, parent: null, siblingIndex: 0) + ); } finally { @@ -761,8 +854,13 @@ internal sealed class CoupledHistoryComponent : GameBehavior { private bool m_primary = true; private CoupledHistoryMode m_mode; + [SerializableProperty] - public bool primary { get => m_primary; set => m_primary = value && mode == CoupledHistoryMode.Base; } + public bool primary + { + get => m_primary; + set => m_primary = value && mode == CoupledHistoryMode.Base; + } [SerializableProperty] public CoupledHistoryMode mode @@ -772,7 +870,9 @@ public CoupledHistoryMode mode { m_mode = value; if (value == CoupledHistoryMode.Overlay) + { m_primary = false; + } } } } @@ -824,14 +924,18 @@ internal sealed class RestoreCleanupFailureComponent : GameBehavior internal sealed class SubtreeRestoreFailureComponent : GameBehavior { internal static bool throwOnDestroy; + [SerializableProperty] public int value { get; set; } = 5; [OnSerializableRestored] private void OnRestored() => throw new InvalidOperationException("Injected subtree restore callback failure."); + protected override void OnDestroy() { if (throwOnDestroy) + { throw new InvalidOperationException("Injected subtree destruction callback failure."); + } } } diff --git a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs index 1fe85307f..e32f32b4e 100644 --- a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs +++ b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs @@ -9,12 +9,13 @@ using System.Runtime.InteropServices; using System.Text.Json; using BGCS.Runtime; +using Xunit; using Inno.Editor.Interactions; using Inno.Native.ImGui; using Inno.Scene; using Inno.Scene.Components; using Inno.Testing.Editor.Native; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; using NativeVector = Inno.Native.ImGui.ImVec2C; using SceneVector = Inno.Core.Mathematics.Vector3; @@ -38,10 +39,16 @@ public unsafe void LargeViewsMeasureActualInputAndContinuousEditWork(string scen { string? input = InputDirectory("assets"); if (input is not null && Directory.Exists(input)) + { CopyDirectory(input, Path.Combine(host.projectRoot, "Assets")); + } else + { for (int index = 0; index < 10_000; index++) + { Directory.CreateDirectory(Path.Combine(host.projectRoot, "Assets", "Folder " + index.ToString("D5"))); + } + } host.assets.Rescan(); Assert.Equal(10_000, Directory.EnumerateDirectories(Path.Combine(host.projectRoot, "Assets"), "Folder *").Count()); } @@ -54,10 +61,12 @@ public unsafe void LargeViewsMeasureActualInputAndContinuousEditWork(string scen SceneVector initial = scene?.GetObjects()[0].transform.localPosition ?? default; Transform? transform = scene?.GetObjects()[0].transform; using EditorEditGesture? gesture = scenario == "hierarchy-edit" - ? new EditorEditGesture(host.runtime.interactions.history, "Measured continuous edit") - : null; + ? new EditorEditGesture(host.runtime.interactions.history, "Measured continuous edit") + : null; if (scenario == "assets-search") + { FocusAssetSearch(host, panel); + } Action operation = scenario switch { "assets-search" => Search, @@ -75,7 +84,9 @@ public unsafe void LargeViewsMeasureActualInputAndContinuousEditWork(string scen Assert.Equal((float)edits, transform.localPosition.x); } else if (scenario.EndsWith("scroll", StringComparison.Ordinal)) + { Assert.True(maximumScroll > 0f, "Actual wheel input never moved the visible list."); + } void Scroll() { @@ -109,8 +120,15 @@ void Search() void Edit() { int value = ++edits; - Assert.True(host.edits.ChangeProperty(transform!, nameof(Transform.localPosition), - () => transform!.localPosition = new(value, 0f, 0f), "Measured continuous edit", gesture!.mergeKey)); + Assert.True( + host.edits.ChangeProperty( + transform!, + nameof(Transform.localPosition), + () => transform!.localPosition = new(value, 0f, 0f), + "Measured continuous edit", + gesture!.mergeKey + ) + ); host.native.DrawPanel(panel); } } @@ -126,7 +144,9 @@ private static GameScene LoadInteractionHierarchy(NativeProjectPanelHost host) } GameScene scene = host.CreateScene(); for (int index = 0; index < 10_000; index++) + { _ = scene.CreateObject("Object " + index.ToString("D5")); + } _ = host.workspace.Save(scene, string.Empty); return scene; } @@ -148,7 +168,9 @@ EditorPanelExtension panel host.native.DrawPanel(panel); ImGuiNativeContext* context = NativeGui.Raw.GetCurrentContext(); if (context->InputTextState.ID != 0 && context->ActiveId == context->InputTextState.ID) + { return; + } } throw new InvalidOperationException("Ordinary pointer input did not focus the existing asset search field."); } @@ -161,7 +183,9 @@ EditorPanelExtension panel ImGuiWindow* window = context->Windows.Data[index]; string? name = Marshal.PtrToStringUTF8((nint)window->Name); if (window->Active != 0 && name?.Contains(fragment, StringComparison.Ordinal) == true) + { return window; + } } throw new InvalidOperationException("The drawn native input owner is absent: " + fragment); } @@ -171,9 +195,13 @@ private void MeasureInteraction( Action operation ) { for (int warmup = 0; warmup < 5; warmup++) + { operation(); - int repetitions = int.Parse(Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_REPETITIONS") ?? "5", - System.Globalization.CultureInfo.InvariantCulture); + } + int repetitions = int.Parse( + Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_REPETITIONS") ?? "5", + System.Globalization.CultureInfo.InvariantCulture + ); Assert.InRange(repetitions, 1, 5); using Process process = Process.GetCurrentProcess(); var samples = new List(); @@ -196,7 +224,11 @@ Action operation double[] sorted = milliseconds.Order().ToArray(); samples.Add(new { - repetition, milliseconds, median = (sorted[4] + sorted[5]) / 2, p95 = sorted[9], allocatedBytes = allocated, + repetition, + milliseconds, + median = (sorted[4] + sorted[5]) / 2, + p95 = sorted[9], + allocatedBytes = allocated, totalAllocatedBytes = GC.GetTotalAllocatedBytes(precise: true) - totalBefore, cpuMilliseconds = (process.TotalProcessorTime - cpuBefore).TotalMilliseconds, gen0Collections = GC.CollectionCount(0) - gen0, @@ -204,14 +236,22 @@ Action operation gen2Collections = GC.CollectionCount(2) - gen2 }); } - output.WriteLine(JsonSerializer.Serialize(new - { - workload = scenario, samples, - configuration = typeof(LargePanelPerformanceTests).Assembly.GetCustomAttribute()?.Configuration, - viewport = "1000x800", warmupOperations = 5, measuredOperationsPerRepetition = 10, - nativeFramesPerOperation = scenario == "assets-search" ? 4 : 1, - consumer = scenario == "hierarchy-edit" ? "continuous-domain-gesture-and-actual-hierarchy-draw" : "actual-native-input-and-panel-draw", - sharedInput = InputDirectory(scenario.StartsWith("hierarchy", StringComparison.Ordinal) ? "hierarchy" : "assets") - })); + output.WriteLine( + JsonSerializer.Serialize(new + { + workload = scenario, + samples, + configuration = typeof(LargePanelPerformanceTests) + .Assembly + .GetCustomAttribute() + ?.Configuration, + viewport = "1000x800", + warmupOperations = 5, + measuredOperationsPerRepetition = 10, + nativeFramesPerOperation = scenario == "assets-search" ? 4 : 1, + consumer = scenario == "hierarchy-edit" ? "continuous-domain-gesture-and-actual-hierarchy-draw" : "actual-native-input-and-panel-draw", + sharedInput = InputDirectory(scenario.StartsWith("hierarchy", StringComparison.Ordinal) ? "hierarchy" : "assets") + }) + ); } } diff --git a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs index 23fdf7cde..fc9d36278 100644 --- a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs +++ b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs @@ -1,6 +1,7 @@ using System; using System.IO; using BGCS.Runtime; +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Identity; @@ -9,7 +10,7 @@ using Inno.Native.ImGui; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.Performance.Tests; @@ -31,17 +32,25 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str { string? input = InputDirectory("assets"); if (input is not null && Directory.Exists(input)) + { CopyDirectory(input, Path.Combine(host.projectRoot, "Assets")); + } else + { for (int index = 0; index < 10_000; index++) + { Directory.CreateDirectory(Path.Combine(host.projectRoot, "Assets", "Folder " + index.ToString("D5"))); + } + } host.assets.Rescan(); } EditorPanelExtension panel = host.native.GetPanel(hierarchy ? "scene.hierarchy" : "asset.file-browser"); host.native.DrawPanel(panel); host.native.DrawPanel(panel); if (view == "grid") + { SelectGrid(host, panel); + } IdentityObject first = hierarchy ? scene!.GetObjects()[0] : Entry("Folder 00000"); IdentityObject last = hierarchy ? scene!.GetObjects()[^1] : Entry("Folder 09999"); string area = hierarchy ? "panel/scene.hierarchy" : "panel/asset.file-browser"; @@ -51,8 +60,11 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str { SetLargeQuery(host, panel, "Folder 00042"); ImGuiWindow* filtered = FindInteractionWindow(windowName); - NativeGui.Raw.AddMousePosEvent(NativeGui.Raw.GetIO(), filtered->Pos.X + filtered->Size.X - 60f, - filtered->Pos.Y + filtered->Size.Y * 0.7f); + NativeGui.Raw.AddMousePosEvent( + NativeGui.Raw.GetIO(), + filtered->Pos.X + filtered->Size.X - 60f, + filtered->Pos.Y + filtered->Size.Y * 0.7f + ); NativeGui.Raw.AddMouseButtonEvent(NativeGui.Raw.GetIO(), 0, 1); host.native.DrawPanel(panel); NativeGui.Raw.AddMouseButtonEvent(NativeGui.Raw.GetIO(), 0, 0); @@ -62,8 +74,11 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str NativePanelInput.Key(host.native, panel, ImGuiKey.End); Assert.Same(Entry("Folder 00042"), interactions.selection.selectedTarget); SetLargeQuery(host, panel, string.Empty); - NativeGui.Raw.AddMousePosEvent(NativeGui.Raw.GetIO(), filtered->Pos.X + filtered->Size.X * 0.4f, - filtered->Pos.Y + filtered->Size.Y * 0.7f); + NativeGui.Raw.AddMousePosEvent( + NativeGui.Raw.GetIO(), + filtered->Pos.X + filtered->Size.X * 0.4f, + filtered->Pos.Y + filtered->Size.Y * 0.7f + ); NativeGui.Raw.AddMouseButtonEvent(NativeGui.Raw.GetIO(), 0, 1); host.native.DrawPanel(panel); NativeGui.Raw.AddMouseButtonEvent(NativeGui.Raw.GetIO(), 0, 0); @@ -103,15 +118,23 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str Assert.Equal(objectId, ((GameObject)last).identity.persistentId); } else + { last = Entry("Renamed last"); + } Assert.True(interactions.history.Undo().succeeded); if (hierarchy) + { Assert.Equal(original, ((GameObject)last).name); + } else + { Assert.True(Directory.Exists(Path.Combine(host.projectRoot, "Assets", original))); + } Assert.True(interactions.history.Redo().succeeded); if (!hierarchy) + { last = Entry("Renamed last"); + } interactions.SetSelection(last); RuntimeIdentity drag = interactions.For(area, last).BeginDrag(new EditorDragData(last, "Clipped source")); Assert.Equal(hierarchy ? ((GameObject)last).identity.runtimeIdentity : ((AssetFileEntry)last).identity.runtimeIdentity, drag); @@ -125,8 +148,8 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str Assert.True(interactions.For(area).TryGetActiveDragIdentity(out RuntimeIdentity retained)); Assert.Equal(drag, retained); EditorInteraction drop = hierarchy - ? interactions.For(area, new HierarchyObjectDropTarget((GameObject)first)) - : interactions.For(area, ((AssetFileEntry)first).assetPath.ToString()); + ? interactions.For(area, new HierarchyObjectDropTarget((GameObject)first)) + : interactions.For(area, ((AssetFileEntry)first).assetPath.ToString()); Assert.True(drop.QueryDrop(drag, EditorDropPlacement.Into).canDrop); Assert.True(drop.Drop(drag, EditorDropPlacement.Into).accepted); if (hierarchy) @@ -135,12 +158,18 @@ public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(str Assert.Equal(10_000, scene!.GetObjects().Count); } else + { Assert.True(Directory.Exists(Path.Combine(host.projectRoot, "Assets", "Folder 00000", "Renamed last"))); + } Assert.True(interactions.history.Undo().succeeded); if (hierarchy) + { Assert.Null(((GameObject)last).transform.parent); + } else + { Assert.True(Directory.Exists(Path.Combine(host.projectRoot, "Assets", "Renamed last"))); + } Assert.True(interactions.history.Redo().succeeded); host.native.DrawPanel(panel); @@ -180,7 +209,9 @@ EditorPanelExtension panel host.native.DrawPanel(panel); host.runtime.SaveState(); if (File.ReadAllText(Path.Combine(host.projectRoot, "editor.ini")).Contains("viewMode=\"Grid\"", StringComparison.Ordinal)) + { return; + } } throw new InvalidOperationException("Ordinary pointer input did not select the actual Browser grid."); } diff --git a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs index e54283ebd..b15fe21fc 100644 --- a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs +++ b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs @@ -6,13 +6,13 @@ using System.Reflection; using System.Text.Json; using System.Threading; +using Xunit; +using Xunit.Abstractions; using Inno.Assets; using Inno.Core.Serialization; using Inno.Editor.Interactions; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; -using Xunit.Abstractions; namespace Inno.Editor.Performance.Tests; @@ -24,8 +24,13 @@ public void DueDirtyInspectionsMeasureTheCompleteSavedSceneTraversal() { using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); Inno.Scene.GameScene scene = LoadSavedHierarchy(host); - Measure(host, null, "10000-hierarchy-dirty-inspections", - () => Assert.False(host.workspace.IsDirty(scene)), static () => Thread.Sleep(110)); + Measure( + host, + null, + "10000-hierarchy-dirty-inspections", + () => Assert.False(host.workspace.IsDirty(scene)), + static () => Thread.Sleep(110) + ); } [Fact] @@ -49,11 +54,18 @@ public void NeutralCaptureSeparatesSerializationFromSourceFreshness() { using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); Inno.Scene.GameScene scene = LoadSavedHierarchy(host); - SerializationContext context = AssetSerializationContext.Create(host.assets, new AssetDependencyCollection(includeLastKnownPaths: false)); + SerializationContext context = AssetSerializationContext.Create( + host.assets, + new AssetDependencyCollection(includeLastKnownPaths: false) + ); SerializationSnapshot? previous = null; - Measure(host, null, "10000-hierarchy-neutral-capture", + Measure( + host, + null, + "10000-hierarchy-neutral-capture", () => previous = host.serialization.CaptureSnapshot(scene, context, previous), - consumer: "complete-authoritative-serialization-capture"); + consumer: "complete-authoritative-serialization-capture" + ); Assert.NotNull(previous); } @@ -65,9 +77,13 @@ public void SourceFreshnessMeasuresTheActualSavedSceneLoadBoundary() Inno.Scene.GameScene scene = LoadSavedHierarchy(host); Assert.True(host.workspace.TryGetSourcePath(scene, out string path)); SceneAsset asset = host.assets.Load(AssetPath.Project(path)); - Measure(host, null, "10000-hierarchy-source-freshness", + Measure( + host, + null, + "10000-hierarchy-source-freshness", () => Assert.Same(asset, host.assets.Load(asset.identity.persistentId)), - consumer: "canonical-source-load-with-freshness-verification"); + consumer: "canonical-source-load-with-freshness-verification" + ); } [Fact] @@ -107,7 +123,9 @@ public void TenThousandHierarchyRowsProduceRepeatableFrameMeasurements() { var scene = host.CreateScene(); for (int index = 0; index < 10_000; index++) + { _ = scene.CreateObject("Object " + index.ToString("D5")); + } if (input is not null) { Assert.Equal("Untitled Scene.iscene", host.workspace.Save(scene, string.Empty)); @@ -125,14 +143,22 @@ public void TenThousandAssetRowsProduceRepeatableFrameMeasurements() using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); string? input = InputDirectory("assets"); if (input is not null && Directory.Exists(input)) + { CopyDirectory(input, Path.Combine(host.projectRoot, "Assets")); + } else + { for (int index = 0; index < 10_000; index++) + { Directory.CreateDirectory(Path.Combine(host.projectRoot, "Assets", "Folder " + index.ToString("D5"))); + } + } host.assets.Rescan(); Assert.Equal(10_000, Directory.EnumerateDirectories(Path.Combine(host.projectRoot, "Assets"), "Folder *").Count()); if (input is not null && !Directory.Exists(input)) + { CopyDirectory(Path.Combine(host.projectRoot, "Assets"), input); + } EditorPanelExtension panel = host.native.GetPanel("asset.file-browser"); Measure(host, panel, "10000-asset-directory-rows"); } @@ -151,7 +177,9 @@ private static Inno.Scene.GameScene LoadSavedHierarchy(NativeProjectPanelHost ho { scene = host.CreateScene(); for (int index = 0; index < 10_000; index++) + { _ = scene.CreateObject("Object " + index.ToString("D5")); + } _ = host.workspace.Save(scene, string.Empty); } Assert.Equal(10_000, scene.GetObjects().Count); @@ -170,9 +198,13 @@ string destination ) { Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) + { Directory.CreateDirectory(Path.Combine(destination, Path.GetRelativePath(source, directory))); + } foreach (string file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) + { File.Copy(file, Path.Combine(destination, Path.GetRelativePath(source, file)), overwrite: false); + } } private void Measure( @@ -214,8 +246,11 @@ private void Measure( double[] sorted = milliseconds.Order().ToArray(); samples.Add(new { - repetition, milliseconds, median = (sorted[4] + sorted[5]) / 2, - p95 = sorted[9], allocatedBytes = allocated, + repetition, + milliseconds, + median = (sorted[4] + sorted[5]) / 2, + p95 = sorted[9], + allocatedBytes = allocated, totalAllocatedBytes = GC.GetTotalAllocatedBytes(precise: true) - totalBytesBefore, cpuMilliseconds = (process.TotalProcessorTime - cpuBefore).TotalMilliseconds, gen0Collections = GC.CollectionCount(0) - collectionsBefore, @@ -223,20 +258,29 @@ private void Measure( gen2Collections = GC.CollectionCount(2) - gen2Before }); } - output.WriteLine(JsonSerializer.Serialize(new - { - workload, - configuration = typeof(LargePanelPerformanceTests).Assembly.GetCustomAttribute()?.Configuration - ?? throw new InvalidOperationException("The benchmark assembly has no SDK configuration metadata."), - samples, - framework = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, - viewport = "1000x800", warmupFrames = 5, measuredFramesPerRepetition = 10, - sharedInput = InputDirectory(workload.Contains("hierarchy", StringComparison.Ordinal) ? "hierarchy" : "assets"), - consumer = consumer ?? (prepare is null ? "native-command-offset-validation" : "complete-authoritative-dirty-inspection"), - preparationExcludedFromFrameTiming = prepare is not null, - supportsVertexOffsets = true - })); + output.WriteLine( + JsonSerializer.Serialize(new + { + workload, + configuration = typeof(LargePanelPerformanceTests) + .Assembly + .GetCustomAttribute() + ?.Configuration + ?? throw new InvalidOperationException("The benchmark assembly has no SDK configuration metadata."), + samples, + framework = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, + viewport = "1000x800", + warmupFrames = 5, + measuredFramesPerRepetition = 10, + sharedInput = InputDirectory(workload.Contains("hierarchy", StringComparison.Ordinal) ? "hierarchy" : "assets"), + consumer = consumer ?? (prepare is null ? "native-command-offset-validation" : "complete-authoritative-dirty-inspection"), + preparationExcludedFromFrameTiming = prepare is not null, + supportsVertexOffsets = true + }) + ); if (panel is not null) + { Assert.True(panel.isOpen); + } } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleEntryLayoutTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleEntryLayoutTests.cs index 42013e6f4..6cabf1482 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleEntryLayoutTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleEntryLayoutTests.cs @@ -1,14 +1,12 @@ -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; using System.Collections.Generic; using System.Numerics; - +using System.Runtime.CompilerServices; +using BGCS.Runtime; +using Xunit; using Inno.Native.ImGui; using NativeImGui = Inno.Native.ImGui.ImGui; - -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.PlayMode.Tests; @@ -82,13 +80,13 @@ private static void DrawCardFrame(bool assertSpacing) { NativeImGui.PushID(identities[i]); if (NativeImGui.BeginChild( - "##ConsoleEntryCard", - Vector2.Zero, - (int)(ImGuiChildFlags.FrameStyle | ImGuiChildFlags.AutoResizeY), - (int)(ImGuiWindowFlags.NoScrollbar | - ImGuiWindowFlags.NoScrollWithMouse | - ImGuiWindowFlags.NoSavedSettings))) - { + "##ConsoleEntryCard", + Vector2.Zero, + (int)(ImGuiChildFlags.FrameStyle | ImGuiChildFlags.AutoResizeY), + (int)(ImGuiWindowFlags.NoScrollbar + | ImGuiWindowFlags.NoScrollWithMouse + | ImGuiWindowFlags.NoSavedSettings) + )) { NativeImGui.TextUnformatted($"Entry {i}"); } NativeImGui.EndChild(); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs index 399c94683..d58756851 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs @@ -1,24 +1,25 @@ -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using BGCS.Runtime; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Logging; using Inno.Editor.Core; -using Inno.Editor.ImGui; using Inno.Editor.Diagnostics; +using Inno.Editor.ImGui; using Inno.Editor.Interactions; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Native.ImGui; + using ImGuiApi = Inno.Native.ImGui.ImGui; -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.PlayMode.Tests; @@ -40,7 +41,9 @@ public void SnapshotFailureQuarantinesTheConsoleWithoutLeakingChildWindows() io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; io->IniFilename = null; - using var modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConsolePanelNativeLayoutTests).Assembly) }); + using var modules = new ModuleHost( + new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConsolePanelNativeLayoutTests).Assembly) } + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var logs = new LogRouter(); var diagnostics = new DiagnosticHub(); @@ -50,7 +53,8 @@ public void SnapshotFailureQuarantinesTheConsoleWithoutLeakingChildWindows() new EditorContext(root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), types, logs, - [new RejectedConsole()]); + [new RejectedConsole()] + ); runtime.Start(); EditorPanelExtension panel = Assert.Single(runtime.panels, value => value.id == "diagnostics.console"); panel.isOpen = true; @@ -101,7 +105,9 @@ float scale ImGuiApi.Raw.GetIO()->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; ImGuiApi.Raw.GetIO()->Fonts->RendererHasTextures = 1; ImGuiApi.Raw.ScaleAllSizes(ImGuiApi.Raw.GetStyle(), scale); - using var modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConsolePanelNativeLayoutTests).Assembly)}); + using var modules = new ModuleHost( + new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ConsolePanelNativeLayoutTests).Assembly)} + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var logs = new LogRouter(); var hub = new DiagnosticHub(); @@ -118,8 +124,14 @@ float scale runtime.Start(); logs.Flush(); console.Clear(); - if (diagnostic) reporter.Publish(new("BGFX_IR_GENERATION", "BGFX has no position builtin for stage Compute.", DiagnosticSeverity.Error)); - else logs.CreateLogger().Write(LogLevel.Error, "BGFX has no position builtin for stage Compute."); + if (diagnostic) + { + reporter.Publish(new("BGFX_IR_GENERATION", "BGFX has no position builtin for stage Compute.", DiagnosticSeverity.Error)); + } + else + { + logs.CreateLogger().Write(LogLevel.Error, "BGFX has no position builtin for stage Compute."); + } logs.Flush(); EditorPanelExtension panel = Assert.Single(runtime.panels, value => value.id == "diagnostics.console"); panel.isOpen = true; @@ -141,7 +153,10 @@ void Draw(float width) for (int i = 0; i < context->Windows.Size; i++) { ImGuiWindow* window = context->Windows.Data[i]; - if (Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true) card = window; + if (Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true) + { + card = window; + } } Assert.True(card != null); ImGuiTable* header = FindActiveTable(card, 3); @@ -149,7 +164,10 @@ void Draw(float width) Vector2 toggle = new(header->Columns.Data[0].WorkMinX + 6, header->RowPosY1 + ImGuiApi.GetFontSize() / 2); ImGuiApi.Raw.AddMousePosEvent(ImGuiApi.Raw.GetIO(), toggle.X, toggle.Y); Draw(960); - Assert.True(context->HoveredId != 0, $"No toggle hovered: {toggle}; window {Marshal.PtrToStringUTF8((nint)context->HoveredWindow->Name)}"); + Assert.True( + context->HoveredId != 0, + $"No toggle hovered: {toggle}; window {Marshal.PtrToStringUTF8((nint)context->HoveredWindow->Name)}" + ); ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (true ? (byte)1 : (byte)0)); Draw(960); Assert.True(context->ActiveId != 0, "Toggle did not activate."); ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (false ? (byte)1 : (byte)0)); Draw(960); @@ -167,11 +185,18 @@ void Draw(float width) Assert.True(value.MinX > label.MinX + ImGuiApi.CalcTextSize("Source:").X); Assert.True(label.ClipRect.Max.X >= label.WorkMinX + ImGuiApi.CalcTextSize("Source:").X); } - if (width >= 500) Assert.True(details, $"Width {width}, details {details}, toggle {toggle}, card {card->Pos} / {card->Size}"); + if (width >= 500) + { + Assert.True(details, $"Width {width}, details {details}, toggle {toggle}, card {card->Pos} / {card->Size}"); + } if (width == 140) Assert.False(details); } } - finally { ImGuiApi.Raw.DestroyContext(context); Directory.Delete(root, true); } + finally + { + ImGuiApi.Raw.DestroyContext(context); + Directory.Delete(root, true); + } } private static ImGuiTable* FindActiveTable( @@ -183,7 +208,9 @@ int columns { ImGuiTable* table = &context->Tables.Buf.Data[index]; if (table->OuterWindow == window && table->ColumnsCount == columns && table->LastFrameActive == ImGuiApi.GetFrameCount()) + { return table; + } } return null; } @@ -192,8 +219,10 @@ private sealed class RejectedConsole : IEditorConsole { public int capacity { get; set; } public bool clearOnPlay { get; set; } + public EditorConsoleSnapshot Capture() => throw new InvalidOperationException("Snapshot source failed."); - public void Clear() { } + + public void Clear() {} } private sealed class InactivePlayMode : IEditorPlayMode @@ -203,9 +232,11 @@ private sealed class InactivePlayMode : IEditorPlayMode public string? lastFailure => null; public LogSessionId activeSessionId => LogSessionId.none; private readonly Inno.Core.Events.EventDispatcher m_stateDispatcher = new(); + public IDisposable ListenStateChanges(Action listener) => m_stateDispatcher.CreateHub(); public bool EnterPlayMode() => false; + public bool ExitPlayMode() => false; } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs index 3bb4a5b56..c4d931850 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs @@ -3,12 +3,13 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using BGCS.Runtime; +using Xunit; using Inno.Core.Diagnostics; using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + using NativeImGui = Inno.Native.ImGui.ImGui; using NativeVector2 = Inno.Native.ImGui.ImVec2C; @@ -30,13 +31,17 @@ float height EditorPanelExtension panel = host.GetPanel("diagnostics.console"); var logger = host.logs.CreateLogger(); for (int occurrence = 0; occurrence < 2; occurrence++) + { logger.Write(LogLevel.Info, "Needle message"); + } logger.Write(LogLevel.Warn, "Unrelated message"); string longMessage = new('x', 300); logger.Write(LogLevel.Info, longMessage); host.logs.Flush(); using var reporter = host.diagnostics.CreateReporter(new("search-source", "SOURCE-NAME")); - reporter.Publish(new("SEARCH_CODE", "A diagnostic", DiagnosticSeverity.Error, location: new DiagnosticLocation("Assets/漢字.shader", 42, 3))); + reporter.Publish( + new("SEARCH_CODE", "A diagnostic", DiagnosticSeverity.Error, location: new DiagnosticLocation("Assets/漢字.shader", 42, 3)) + ); host.DrawPanel(panel); host.DrawPanel(panel); Assert.Equal(5, host.console.Capture().occurrences.Count); @@ -67,7 +72,9 @@ float height EditorPanelExtension panel = host.GetPanel("diagnostics.console"); var logger = host.logs.CreateLogger(); for (int occurrence = 0; occurrence < 2; occurrence++) + { logger.Write(LogLevel.Info, "Needle message"); + } logger.Write(LogLevel.Warn, "Other entry"); host.logs.Flush(); host.DrawPanel(panel); @@ -145,8 +152,11 @@ private static int CountCards() for (int index = 0; index < context->Windows.Size; index++) { ImGuiWindow* window = context->Windows.Data[index]; - if (window->Active != 0 && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true) + if (window->Active != 0 + && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true + ) { count++; + } } return count; } @@ -161,8 +171,10 @@ private static int CountCards() ImGuiWindow* window = context->Windows.Data[index]; string name = Marshal.PtrToStringUTF8((nint)window->Name) ?? string.Empty; if (window->Active != 0 && name.Contains(containing, StringComparison.Ordinal) - && (excluding is null || !name.Contains(excluding, StringComparison.Ordinal))) + && (excluding is null || !name.Contains(excluding, StringComparison.Ordinal)) + ) { return window; + } } throw new InvalidOperationException("The actual control window was not submitted: " + containing); } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs index 7e6b44e38..a1801ad19 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs @@ -1,11 +1,12 @@ using System; using System.Runtime.InteropServices; +using Xunit; +using Xunit.Abstractions; using Inno.Core.Logging; using Inno.Editor.Interactions; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; -using Xunit.Abstractions; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.PlayMode.Tests; @@ -30,8 +31,11 @@ public void RetiringTheContextRecordClosesItsPopup(bool clear) for (int index = 0; index < context->Windows.Size; index++) { ImGuiWindow* window = context->Windows.Data[index]; - if (window->Active != 0 && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true) + if (window->Active != 0 + && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true + ) { card = window; + } } Assert.True(card is not null); ImGuiIO* io = NativeGui.Raw.GetIO(); @@ -43,16 +47,22 @@ public void RetiringTheContextRecordClosesItsPopup(bool clear) host.DrawPanel(panel); Assert.True(context->OpenPopupStack.Size > 0); if (clear) + { host.console.Clear(); + } else { for (int index = 0; index < host.console.capacity; index++) + { logger.Write(LogLevel.Info, "Replacement context record " + index); + } host.logs.Flush(); } Assert.DoesNotContain(host.console.Capture().occurrences, static entry => entry.message == "Original context record"); for (int frame = 0; frame < 3; frame++) + { host.DrawPanel(panel); + } Assert.Equal(0, context->OpenPopupStack.Size); } @@ -75,8 +85,11 @@ public void RepeatedContextMenusDoNotAccumulateRetiredOccurrenceWindows() for (int index = 0; index < context->Windows.Size; index++) { ImGuiWindow* window = context->Windows.Data[index]; - if (window->Active != 0 && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true) + if (window->Active != 0 + && Marshal.PtrToStringUTF8((nint)window->Name)?.Contains("##ConsoleEntryCard", StringComparison.Ordinal) == true + ) { card = window; + } } Assert.True(card is not null); NativeGui.Raw.AddMousePosEvent(io, card->Pos.X + 230f, card->Pos.Y + 12f); @@ -88,8 +101,10 @@ public void RepeatedContextMenusDoNotAccumulateRetiredOccurrenceWindows() Assert.True(context->OpenPopupStack.Size > 0); NativePanelInput.Key(host, panel, ImGuiKey.Escape); } - output.WriteLine("Context menus: 100; retained records: " + host.console.Capture().occurrences.Count - + "; native windows: " + NativeGui.Raw.GetCurrentContext()->Windows.Size); + output.WriteLine( + "Context menus: 100; retained records: " + host.console.Capture().occurrences.Count + + "; native windows: " + NativeGui.Raw.GetCurrentContext()->Windows.Size + ); Assert.InRange(NativeGui.Raw.GetCurrentContext()->Windows.Size, 1, 32); } @@ -103,19 +118,25 @@ public void TenThousandOccurrencesSubmitOnlyViewportCardsAndKeepKeyboardNavigati { logger.Write(LogLevel.Info, "Entry " + index.ToString("D5") + "\nDetails / 资源信息"); if (index % 128 == 0) + { host.logs.Flush(); + } } host.logs.Flush(); Assert.Equal(10_000, host.console.Capture().occurrences.Count); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); for (int frame = 0; frame < 4; frame++) + { host.DrawPanel(panel); + } Assert.InRange(NativeGui.Raw.GetCurrentContext()->Windows.Size, 1, 128); NativePanelInput.Focus(host, panel, "ConsoleRegion"); NativePanelInput.Key(host, panel, ImGuiKey.Home); NativePanelInput.Key(host, panel, ImGuiKey.Enter); for (int frame = 0; frame < 3; frame++) + { host.DrawPanel(panel); + } Assert.InRange(NativeGui.Raw.GetCurrentContext()->Windows.Size, 1, 128); } @@ -134,7 +155,9 @@ public void RetiredOccurrencesDoNotAccumulateNativeChildWindows() host.DrawPanel(panel); } Assert.Equal(16, host.console.Capture().occurrences.Count); - output.WriteLine("Retained records: 16; completed updates: 150; native windows: " + NativeGui.Raw.GetCurrentContext()->Windows.Size); + output.WriteLine( + "Retained records: 16; completed updates: 150; native windows: " + NativeGui.Raw.GetCurrentContext()->Windows.Size + ); Assert.InRange(NativeGui.Raw.GetCurrentContext()->Windows.Size, 1, 64); } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs index 63c001948..dc94422a5 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs @@ -5,6 +5,7 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Text; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Core.Input; using Inno.Core.Logging; @@ -15,7 +16,7 @@ using Inno.Extensibility.Types; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.PlayMode.Tests; @@ -31,7 +32,9 @@ public void StandardDockTreeLoadsAndResizesThroughThePresentationRuntime( float height ) { using var host = new NativePanelHost(typeof(DefaultLayoutNativeTests).Assembly); - using var modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(DefaultLayoutNativeTests).Assembly) }); + using var modules = new ModuleHost( + new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(DefaultLayoutNativeTests).Assembly) } + ); using var types = new TypeCatalog(modules, new EmptyTypeSource()); using var logs = new LogRouter(); var context = new EditorContext(host.runtime.context.projectDirectory, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")); @@ -39,16 +42,22 @@ float height ImGuiIO* io = NativeGui.Raw.GetIO(); io->ConfigFlags |= (int)ImGuiConfigFlags.DockingEnable; io->DisplaySize = Unsafe.BitCast(new(1600f, 900f)); - byte[] layout = Encoding.UTF8.GetBytes(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "DefaultEditorLayout.ini")) + '\0'); + byte[] layout = Encoding.UTF8.GetBytes( + File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "DefaultEditorLayout.ini")) + '\0' + ); fixed (byte* pointer = layout) + { NativeGui.Raw.LoadIniSettingsFromMemory((sbyte*)pointer, (ulong)(layout.Length - 1)); + } runtime.Start(); string[] titles = ["Scene", "Game", "File", "Hierarchy", "Inspector", "Shader Editor", "Console", "Stats"]; var rectangles = new Dictionary(); for (int frame = 0; frame < 12; frame++) { if (frame == 6) + { io->DisplaySize = Unsafe.BitCast(new(width, height)); + } host.Frame(() => { runtime.Draw(); @@ -91,12 +100,16 @@ float height private sealed class EmptyTypeSource : ITypeCatalogSource { public IReadOnlyList GetTypes(Assembly assembly) => []; + public TypeCatalogMetadata GetMetadata(Type type) => throw new NotSupportedException(); + public Type? ConstructGenericType( Type definition, IReadOnlyList arguments ) => throw new NotSupportedException(); + public bool CanCreateInstance(Type type) => false; + public object CreateInstance(Type type) => throw new NotSupportedException(); } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs index 49da286f5..1de80275c 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs @@ -1,11 +1,10 @@ using System.Numerics; - +using Xunit; using Inno.Adapter.Input; using Inno.Core.Events; using Inno.Core.Input; using Inno.Editor.ImGui; using Inno.Input; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -23,8 +22,8 @@ public void ConsumedMouseMovementStillUpdatesPointerBounds(bool pressed) Assert.Null(capture.Route(moved)); Event pointer = pressed - ? new MouseButtonPressedEvent(42, MouseButton.Left) - : new MouseScrolledEvent(42, 0f, 1f); + ? new MouseButtonPressedEvent(42, MouseButton.Left) + : new MouseScrolledEvent(42, 0f, 1f); Assert.Null(capture.Route(pointer)); Assert.NotNull(capture.Route(new KeyPressedEvent(42, KeyCode.A))); } @@ -60,7 +59,9 @@ bool consumed capture.Report(9, Vector2.Zero, new Vector2(100f), focused: true, hovered: true); Event exit = close ? new WindowCloseEvent(42) : new WindowFocusChangedEvent(42, false); if (consumed) + { exit.HandleInGlobal(); + } Assert.Null(capture.Route(exit)); Assert.Null(capture.Route(new KeyPressedEvent(42, KeyCode.A))); @@ -78,9 +79,13 @@ public void DispatcherRoutesInputOnlyAfterEditorConsumption(bool globalConsumpti using System.IDisposable subscription = ui.Listen(evnt => { if (globalConsumption) + { evnt.HandleInGlobal(); + } else + { evnt.HandleInHub(); + } }); var capture = new EditorGameInputCapture(_ => 42u); capture.BeginFrame(); @@ -94,9 +99,13 @@ public void DispatcherRoutesInputOnlyAfterEditorConsumption(bool globalConsumpti dispatcher.Flush(); if (globalConsumption) + { Assert.Null(routed); + } else + { Assert.Same(pressed, routed); + } } [Fact] @@ -114,7 +123,9 @@ public void ConsumedReleaseResetsInputDuringDispatchBeforeSimulation() { Event? routed = capture.Route(evnt); if (routed is not null) + { source.ProcessEvent(routed); + } }; dispatcher.Enqueue(new KeyPressedEvent(42, KeyCode.A)); dispatcher.Flush(); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs index 6ba5a874a..3f2f77be9 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; +using Xunit; using Inno.Core.IO; using Inno.Core.Input; using Inno.Editor.Core; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -108,8 +108,8 @@ public void AContextWithoutACompositionDefaultRemainsPassive() public void Dispose() => Directory.Delete(PathBoundary.RequireUnlinkedPath(m_owner, m_root), recursive: true); - private EditorContext CreateContext(string? initialDocument) => new( - m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl"), initialDocument); + private EditorContext CreateContext(string? initialDocument) + => new(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl"), initialDocument); private static string ReadTemplate() => File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "DefaultEditorLayout.ini")); } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs index c673db7ed..8a0d0c8d8 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs @@ -1,20 +1,21 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Core.Identity; using Inno.Core.Events; -using Inno.Core.Input; using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Input; +using Inno.Core.Logging; using Inno.Core.Mathematics; using Inno.Core.Serialization; -using Inno.Editor.Interactions; using Inno.Editor.Core; +using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Scripting; using Inno.Extensibility.Types; @@ -23,9 +24,9 @@ using Inno.Runtime.Contracts; using Inno.Scene; using Inno.Scripting.Compiler; -using Xunit; namespace Inno.Editor.PlayMode.Tests; + public sealed class EditorPlayModeTests : IDisposable { private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoEditorPlayModeTests", Guid.NewGuid().ToString("N")); @@ -33,6 +34,7 @@ public sealed class EditorPlayModeTests : IDisposable private readonly RuntimeSession m_editSession; private readonly AssetPipeline m_authoringAssets; private readonly IDisposable m_editScope; + public EditorPlayModeTests() { Directory.CreateDirectory(Path.Combine(m_projectRoot, "Assets")); @@ -50,7 +52,10 @@ public EditorPlayModeTests() new IdentityAllocator(), m_engineHost.diagnostics, m_engineHost.logs, - AssetPipelineOptions.Create(Path.Combine(m_projectRoot, "Assets"), Path.Combine(m_projectRoot, "Library"))with { enableFileSystemWatcher = false } + AssetPipelineOptions.Create( + Path.Combine(m_projectRoot, "Assets"), + Path.Combine(m_projectRoot, "Library") + )with { enableFileSystemWatcher = false } ); } @@ -61,13 +66,20 @@ public void Dispose() m_editSession.Dispose(); m_engineHost.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } [Fact] public void StateSubscriptionsNotifyAllObserversAndReleaseIndependently() { - using var harness = new PlayModeHarness(m_projectRoot, m_engineHost, new FakeScriptCompilation(EditorScriptCompilationState.Ready), new FakeScenePlayMode()); + using var harness = new PlayModeHarness( + m_projectRoot, + m_engineHost, + new FakeScriptCompilation(EditorScriptCompilationState.Ready), + new FakeScenePlayMode() + ); int observed = 0; using IDisposable failing = harness.playMode.ListenStateChanges(_ => throw new InvalidOperationException("Rejected observer.")); using IDisposable healthy = harness.playMode.ListenStateChanges(_ => observed++); @@ -87,8 +99,18 @@ public void StateSubscriptionsNotifyAllObserversAndReleaseIndependently() [Fact] public void PlayShortcutStopsTheSessionFromAFocusedGameView() { - using var harness = new PlayModeHarness(m_projectRoot, m_engineHost, new FakeScriptCompilation(EditorScriptCompilationState.Ready), new FakeScenePlayMode()); - using var modules = new Inno.Extensibility.Modules.ModuleHost(new Inno.Extensibility.Modules.ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorPlayModeController).Assembly) }); + using var harness = new PlayModeHarness( + m_projectRoot, + m_engineHost, + new FakeScriptCompilation(EditorScriptCompilationState.Ready), + new FakeScenePlayMode() + ); + using var modules = new Inno.Extensibility.Modules.ModuleHost( + new Inno.Extensibility.Modules.ModuleHostOptions + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorPlayModeController).Assembly) + } + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var interactions = new EditorInteractionRuntime( new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), @@ -138,7 +160,12 @@ public void ReloadGuardPreservesStartupCompilationAndPinsThePlayingGeneration() [Fact] public void ReleasingGuardRegistrationDoesNotRetainItsBlockingState() { - using var harness = new PlayModeHarness(m_projectRoot, m_engineHost, new FakeScriptCompilation(EditorScriptCompilationState.Compiling), new FakeScenePlayMode()); + using var harness = new PlayModeHarness( + m_projectRoot, + m_engineHost, + new FakeScriptCompilation(EditorScriptCompilationState.Compiling), + new FakeScenePlayMode() + ); var reloads = new EditorReloadCoordinator(); IDisposable registration = reloads.RegisterGuard((IEditorReloadGuard)harness.playMode); Assert.True(harness.playMode.EnterPlayMode()); @@ -183,7 +210,9 @@ public void PendingStopRetainsHistoryAndBlocksNewGenerationUntilWorkDrains(bool var scenes = new FakeScenePlayMode(_ => { if (failSceneEntry) + { throw new InvalidOperationException("Scene materialization failed"); + } }); using var harness = new PlayModeHarness(m_projectRoot, m_engineHost, scripting, scenes, new PendingPlayFactory(subsystem)); try @@ -431,7 +460,11 @@ public void GamePresentationSwitchesFromEditToPlayAndBackWithoutSharingObjects() runtimeObject.name = "Runtime Object"; runtimeObject.transform.localRotation = Quaternion.FromEulerAnglesXYZDegrees(new Vector3(0f, 0f, 90f)); Assert.Equal("Runtime Object", Assert.Single(Assert.Single(playing.GetValues()).GetObjects()).name); - Assert.Equal(90f, Assert.Single(Assert.Single(playing.GetValues()).GetObjects()).transform.localRotation.ToEulerAnglesXYZDegrees().z, precision: 3); + Assert.Equal( + 90f, + Assert.Single(Assert.Single(playing.GetValues()).GetObjects()).transform.localRotation.ToEulerAnglesXYZDegrees().z, + precision: 3 + ); Assert.Equal("Edit Object", editObject.name); Assert.Equal(Quaternion.identity, editObject.transform.localRotation); playLease.Dispose(); @@ -456,7 +489,9 @@ public void RejectedPlayWorldDoesNotReplaceTheEditPresentation() SceneManager.LoadScene(editScene); using RuntimeSession runtimeSession = m_engineHost.CreateSession(CreateSessionOptions(RuntimeSessionKind.Play)); using (runtimeSession.EnterExecutionScope()) + { runtimeSession.scenes.LoadScene(new GameScene("Unexpected Existing Runtime Scene")); + } Assert.Throws(() => workspaceHost.playMode.BeginPlayMode(runtimeSession)); using ContentReadScope snapshot = presentation.Capture(); Assert.Same(editScene, Assert.Single(snapshot.GetValues())); @@ -499,7 +534,9 @@ public sealed class CountingSystem : GameSystem public int lateCount { get; private set; } protected override void OnFixedUpdate() => fixedCount++; + protected override void OnUpdate() => updateCount++; + protected override void OnLateUpdate() => lateCount++; } @@ -512,6 +549,7 @@ private sealed class PlayModeHarness : IDisposable { private readonly EditorPlayModeController m_controller; private readonly FakeHistoryIsolation m_history = new(); + internal PlayModeHarness( string projectRoot, EngineHost engineHost, @@ -521,10 +559,13 @@ internal PlayModeHarness( ) { m_controller = new EditorPlayModeController( engineHost, - new RuntimeSessionOptions { + new RuntimeSessionOptions + { kind = RuntimeSessionKind.Play, applicationId = "inno.tests.play", - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(projectRoot, "PersistentData", "inno.tests.play"), "Logs")), + createLogSink = _ => new FileLogSink( + Path.Combine(Path.Combine(projectRoot, "PersistentData", "inno.tests.play"), "Logs") + ), jobExecutionMode = RuntimeJobExecutionMode.SingleThread, createSubsystems = _ => factory is null ? [] : [factory] }, @@ -539,7 +580,9 @@ internal PlayModeHarness( internal FakeHistoryIsolation history => m_history; internal void Update() => m_controller.AdvanceTransition(); + internal void Simulate(float deltaTime) => m_controller.Tick(deltaTime); + public void Dispose() { m_controller.Dispose(); @@ -551,12 +594,11 @@ private sealed class FakeScriptCompilation(EditorScriptCompilationState initialS public bool requiresExclusiveProgress => false; public EditorScriptCompilationProgress progress => new(0, 0f, "Test script status.", false); - public void CancelCompilation(long operationId) - { - } + public void CancelCompilation(long operationId) {} private EditorScriptCompilationState m_state = initialState; private FakeCompilationTicket? m_ticket; + public IScriptCompilationTicket RequestCompilation() { m_ticket = new FakeCompilationTicket(); @@ -591,7 +633,9 @@ private sealed class PendingPlaySubsystem : RuntimeSubsystem internal TaskCompletionSource work { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); internal bool stopped; + protected override void OnStart() => lifetime.Track(work.Task); + protected override void OnStop() => stopped = true; } @@ -601,7 +645,12 @@ private sealed class FakeCompilationTicket : IScriptCompilationTicket public ScriptCompilationTicketState state { get; private set; } public string status => "Test compilation ticket."; public ScriptCompilationResult? result => null; - public bool isCompleted => state is ScriptCompilationTicketState.Succeeded or ScriptCompilationTicketState.Failed or ScriptCompilationTicketState.Canceled or ScriptCompilationTicketState.Superseded; + + public bool isCompleted + => state is ScriptCompilationTicketState.Succeeded + or ScriptCompilationTicketState.Failed + or ScriptCompilationTicketState.Canceled + or ScriptCompilationTicketState.Superseded; internal void SetState(EditorScriptCompilationState value) { @@ -629,10 +678,13 @@ public IDisposable BeginPlayMode(RuntimeSession runtimeSession) private sealed class Session(FakeScenePlayMode owner) : IDisposable { private bool m_restored; + public void Dispose() { if (m_restored) + { return; + } m_restored = true; owner.restoreCount++; } @@ -641,7 +693,9 @@ public void Dispose() private sealed class FakeSelectionCoordinator : IEditorSelectionCoordinator { - public IDisposable RegisterIdentityDomain(Inno.Core.Identity.IdentityAllocator allocator) => new Inno.Core.Execution.LifetimeScope(); + public IDisposable RegisterIdentityDomain(Inno.Core.Identity.IdentityAllocator allocator) + => new Inno.Core.Execution.LifetimeScope(); + public object? selectedTarget { get; private set; } public void SetSelection(object? target) => selectedTarget = target; @@ -661,10 +715,13 @@ public IDisposable BeginHistoryIsolation() private sealed class Lease(FakeHistoryIsolation owner) : IDisposable { private bool m_disposed; + public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; owner.disposeCount++; } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs index e4e83c400..6495bb7c2 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs @@ -1,15 +1,17 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; using System; using System.Numerics; +using System.Runtime.CompilerServices; +using BGCS.Runtime; +using Xunit; using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; using NativeImGui = Inno.Native.ImGui.ImGui; -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.PlayMode.Tests; + public sealed unsafe class EditorPopupLayoutTests { [Fact] @@ -123,7 +125,9 @@ public void LongSelectorNearWindowBottomScrollsWithoutOpeningUpward() Vector2 popupPosition = NativeImGui.GetWindowPos(); Vector2 popupSize = NativeImGui.GetWindowSize(); for (int index = 0; index < 40; index++) + { _ = NativeImGui.Selectable($"Item {index}"); + } if (frame == 2) { Assert.InRange(popupPosition.Y, triggerBottom - 1f, triggerBottom + 1f); @@ -166,7 +170,9 @@ public void SelectorInsideLayoutChildUsesContainingPanelBounds() Vector2 popupPosition = NativeImGui.GetWindowPos(); Vector2 popupSize = NativeImGui.GetWindowSize(); for (int index = 0; index < 40; index++) + { _ = NativeImGui.Selectable($"Item {index}"); + } if (frame == 2) { Assert.True(popupSize.Y > 55f); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs index 2ad0095d1..4b1b3dcf2 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs @@ -1,12 +1,13 @@ using System; using System.Linq; using System.Numerics; +using Xunit; using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; using Ui = Inno.Editor.ImGui.ImGui; @@ -68,11 +69,19 @@ bool down Vector2 size = Ui.GetContentRegionAvailable(); _ = Ui.InvisibleButton("workflow-canvas", size); var view = new GraphCanvasView(state, origin, size); - _ = layout.SetNodes(controller.document.nodes.Select(node => new GraphCanvasNode(node.id, node.position, - new(200f, 100f), 24f, "Workflow step", [ - new(new(node.id, new("previous")), GraphPortDirection.Input, new(0f, 40f), "Previous"), - new(new(node.id, new("next")), GraphPortDirection.Output, new(200f, 40f), "Next") - ]))); + _ = layout.SetNodes( + controller.document.nodes.Select(node => new GraphCanvasNode( + node.id, + node.position, + new(200f, 100f), + 24f, + "Workflow step", + [ + new(new(node.id, new("previous")), GraphPortDirection.Input, new(0f, 40f), "Previous"), + new(new(node.id, new("next")), GraphPortDirection.Output, new(200f, 40f), "Next") + ] + )) + ); GraphCanvasPointerResult result = pointer.Step(view, layout, new() { position = Ui.GetMousePos(), @@ -82,13 +91,24 @@ bool down isReleased = Ui.IsMouseReleased(Inno.Editor.ImGui.ImGuiMouseButton.Left) }); if (result.movedNodes is { } positions) + { controller.MoveNodes(positions); + } if (result.output is GraphEndpoint output && result.input is GraphEndpoint input) + { _ = controller.Connect(output, input); + } var draw = Ui.GetDrawList(); foreach (GraphCanvasNode node in layout.nodes) - _ = view.DrawNode(draw, node, 0xFF504030, state.selectedNodes.Contains(node.id), - previewPosition: pointer.previewPositions.TryGetValue(node.id, out GraphPosition position) ? position : null); + { + _ = view.DrawNode( + draw, + node, + 0xFF504030, + state.selectedNodes.Contains(node.id), + previewPosition: pointer.previewPositions.TryGetValue(node.id, out GraphPosition position) ? position : null + ); + } } finally { @@ -104,8 +124,14 @@ public void NonShaderNodeDrawingRestoresItsClipAfterAnExtensionThrows() using var host = new NativePanelHost(typeof(GraphCanvasNativeTests).Assembly); var state = new GraphCanvasState(); GraphNodeId id = new("workflow.begin"); - var node = new GraphCanvasNode(id, new(10f, 10f), new(200f, 100f), 24f, "Workflow step", - [new(new(id, new("next")), GraphPortDirection.Output, new(200f, 40f), "Continue", labelBounds: (new(0f, 28f), new(200f, 52f)))]); + var node = new GraphCanvasNode( + id, + new(10f, 10f), + new(200f, 100f), + 24f, + "Workflow step", + [new(new(id, new("next")), GraphPortDirection.Output, new(200f, 40f), "Continue", labelBounds: (new(0f, 28f), new(200f, 52f)))] + ); for (int frame = 0; frame < 3; frame++) { host.Frame(() => @@ -121,15 +147,46 @@ public void NonShaderNodeDrawingRestoresItsClipAfterAnExtensionThrows() var draw = Ui.GetDrawList(); var view = new GraphCanvasView(state, new(40f, 60f), new(540f, 300f)); var failure = new InvalidOperationException("Workflow node extension failed."); - Assert.Same(failure, Assert.Throws(() => view.DrawNode(draw, node, 0xFF504030, true, - () => throw failure))); + Assert.Same( + failure, + Assert.Throws(() => view.DrawNode( + draw, + node, + 0xFF504030, + true, + () => throw failure + )) + ); Assert.Equal(clipDepth, window->DrawList->ClipRectStack.Size); Assert.True(view.DrawNode(draw, node, 0xFF504030, false)); var offscreen = new GraphCanvasNode(new("workflow.hidden"), new(5000f, 5000f), new(200f, 100f), 24f, "Hidden", []); - Assert.False(view.DrawNode(draw, offscreen, 0xFF504030, false, () => throw new InvalidOperationException("Culled content must not run."))); - var outsideWindow = new GraphCanvasNode(new("workflow.clipped-parent"), new(900f, 900f), new(200f, 100f), 24f, "Clipped by parent", []); + Assert.False( + view.DrawNode( + draw, + offscreen, + 0xFF504030, + false, + () => throw new InvalidOperationException("Culled content must not run.") + ) + ); + var outsideWindow = new GraphCanvasNode( + new("workflow.clipped-parent"), + new(900f, 900f), + new(200f, 100f), + 24f, + "Clipped by parent", + [] + ); var oversized = new GraphCanvasView(state, new(40f, 60f), new(1800f, 1800f)); - Assert.False(oversized.DrawNode(draw, outsideWindow, 0xFF504030, false, () => throw new InvalidOperationException("Parent-clipped content must not run."))); + Assert.False( + oversized.DrawNode( + draw, + outsideWindow, + 0xFF504030, + false, + () => throw new InvalidOperationException("Parent-clipped content must not run.") + ) + ); Assert.Equal(clipDepth, window->DrawList->ClipRectStack.Size); } finally diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs index 4b9d12299..517ed060d 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Numerics; +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Assets.ImGui; @@ -9,7 +10,6 @@ using Inno.Native.ImGui; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -138,7 +138,11 @@ float height public static IEnumerable BrowserMetrics() { foreach (bool tree in new[] { false, true }) + { foreach (object[] metric in VisualScaleMatrixTests.Metrics()) + { yield return [tree, .. metric]; + } + } } } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/MissingSceneSourceTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/MissingSceneSourceTests.cs index b216aa125..a081b3d74 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/MissingSceneSourceTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/MissingSceneSourceTests.cs @@ -1,10 +1,10 @@ using System; using System.IO; using System.Threading; +using Xunit; using Inno.Assets; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -25,7 +25,9 @@ public void UnavailableSourceKeepsAssignmentEditsAndIdentityUntilRecovery(bool e byte[] metadata = File.ReadAllBytes(physical + ".imeta"); Guid id = host.assets.Load(AssetPath.Project(path)).identity.persistentId; if (edited) + { value.name = "Unsaved edit"; + } File.Delete(physical); Assert.True(host.workspace.TryGetSourcePath(scene, out string pendingPath)); Assert.Equal(path, pendingPath); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs index 5cb91fabc..7f13f06ac 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs @@ -1,12 +1,10 @@ using System; using System.Linq; - -using Inno.Extensibility.Modules; +using Xunit; using Inno.Core.Diagnostics; using Inno.Core.Logging; using Inno.Editor.Diagnostics; - -using Xunit; +using Inno.Extensibility.Modules; namespace Inno.Editor.PlayMode.Tests; @@ -43,7 +41,8 @@ public void ClearOnPlayRemovesOldLogsButRetainsCurrentDiagnostics() Dispatch(LogLevel.Info, LogSessionId.none, "before-play"); m_diagnosticHub.Set( new DiagnosticSource("test.compiler", "Test Compiler"), - [Diagnostic.Error("TEST001", "compiler-diagnostic")]); + [Diagnostic.Error("TEST001", "compiler-diagnostic")] + ); m_logRouter.Flush(); _ = m_playMode.Begin(); @@ -59,7 +58,8 @@ public void ManualClearRemovesHistoryButKeepsCurrentIssuesUntilResolved() { Dispatch(LogLevel.Error, LogSessionId.none, "old failure"); using DiagnosticReporter reporter = m_diagnosticHub.CreateReporter( - new DiagnosticSource("tests.current", "Current issue")); + new DiagnosticSource("tests.current", "Current issue") + ); reporter.Publish(Diagnostic.Error("CURRENT", "still failing")); m_logRouter.Flush(); @@ -101,9 +101,7 @@ public void FailedEntryRetainsPreparationDiagnosticsBecauseSimulationNeverStarte m_playMode.SetState(EditorPlayModeState.Failed); m_logRouter.Flush(); - Assert.Contains( - m_console.Capture().occurrences, - static entry => entry.message == "entry-diagnostic"); + Assert.Contains(m_console.Capture().occurrences, static entry => entry.message == "entry-diagnostic"); } [Fact] @@ -115,9 +113,7 @@ public void DisabledClearOnPlayRetainsExistingLogs() _ = m_playMode.Begin(); - Assert.Contains( - m_console.Capture().occurrences, - static entry => entry.message == "before-play"); + Assert.Contains(m_console.Capture().occurrences, static entry => entry.message == "before-play"); } [Fact] @@ -130,8 +126,9 @@ public void CollapseGroupsEquivalentNonConsecutiveOccurrencesGlobally() m_logRouter.Flush(); EditorConsoleSnapshot snapshot = m_console.Capture(); - EditorConsoleGroup repeated = Assert.Single(snapshot.groups.Where( - static group => group.latest.message == "repeated" && group.latest.file == "A.cs")); + EditorConsoleGroup repeated = Assert.Single( + snapshot.groups.Where(static group => group.latest.message == "repeated" && group.latest.file == "A.cs") + ); Assert.Equal(2, repeated.count); Assert.Equal(3, snapshot.groups.Count); @@ -149,9 +146,7 @@ public void CollapseDoesNotMergeEquivalentEntriesAcrossRuntimeSessions() EditorConsoleSnapshot snapshot = m_console.Capture(); - Assert.Equal( - 2, - snapshot.groups.Count(static group => group.latest.message == "session-entry")); + Assert.Equal(2, snapshot.groups.Count(static group => group.latest.message == "session-entry")); } [Fact] @@ -174,8 +169,9 @@ private void Dispatch( LogSessionId sessionId, string message, string file = nameof(PlayModeLogRetentionTests), - int line = 0) - => m_logRouter.Dispatch(new LogEntry( + int line = 0 + ) => m_logRouter.Dispatch( + new LogEntry( level, AssemblyDomain.InnoScripting, AssemblyScope.Runtime, @@ -184,7 +180,9 @@ private void Dispatch( file, line, $"at {file}:{line}", - sessionId)); + sessionId + ) + ); private sealed class FakePlayMode : IEditorPlayMode { @@ -200,8 +198,10 @@ private sealed class FakePlayMode : IEditorPlayMode private readonly Inno.Core.Events.EventHub m_stateEvents; internal FakePlayMode() => m_stateEvents = m_stateDispatcher.CreateHub(); + public IDisposable ListenStateChanges(Action listener) => m_stateEvents.Listen(notification => listener(notification.state)); + private sealed class StateNotification(EditorPlayModeState state) : Inno.Core.Events.Event { internal EditorPlayModeState state { get; } = state; diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs index a3455ede1..4e2110d21 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs @@ -1,14 +1,14 @@ using System; using System.Security.Cryptography; using System.Threading; +using Xunit; using Inno.Assets; +using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; -using Inno.Core.Mathematics; using Inno.Extensibility.Types; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -31,8 +31,14 @@ public void OwnedRevisionCaptureKeepsDirtyStateExactAcrossHistoryRestoreAndDirec Check(true); Assert.True(host.runtime.interactions.history.Undo().succeeded); Check(false); - Assert.True(host.edits.ChangeProperty(value.transform, "localPosition", - () => value.transform.localPosition = new Vector3(3, 4, 5), "Move")); + Assert.True( + host.edits.ChangeProperty( + value.transform, + "localPosition", + () => value.transform.localPosition = new Vector3(3, 4, 5), + "Move" + ) + ); Check(true); Assert.True(host.runtime.interactions.history.Undo().succeeded); Check(false); @@ -58,7 +64,10 @@ public void CompleteSceneCapturesReuseOnlyUnchangedNeutralState() GameObject target = scene.CreateObject("Target"); DirtyCaptureComponent component = owner.AddComponent(); component.target = target; - SerializationContext context = AssetSerializationContext.Create(host.assets, new AssetDependencyCollection(includeLastKnownPaths: false)); + SerializationContext context = AssetSerializationContext.Create( + host.assets, + new AssetDependencyCollection(includeLastKnownPaths: false) + ); SerializationSnapshot before = host.serialization.CaptureSnapshot(scene, context); Assert.Equal(host.serialization.Serialize(scene, context), before.ToArray()); Assert.Same(before, host.serialization.CaptureSnapshot(scene, context, before)); @@ -168,8 +177,12 @@ public void FailedCapturePreservesTheSavedBaselineAndRecoversWithoutPublishingCl private static byte[] Hash( NativeProjectPanelHost host, GameScene scene - ) => SHA256.HashData(host.serialization.Serialize(scene, - AssetSerializationContext.Create(host.assets, new AssetDependencyCollection(includeLastKnownPaths: false)))); + ) => SHA256.HashData( + host.serialization.Serialize( + scene, + AssetSerializationContext.Create(host.assets, new AssetDependencyCollection(includeLastKnownPaths: false)) + ) + ); } [StableTypeId("942e794b-1c53-45a6-80e6-a641d76fdd09")] @@ -197,7 +210,9 @@ DirtyCaptureValue value value.reads++; writer.Write("value", value.value); if (value.reject) + { throw new InvalidOperationException("The test-owned converter rejected capture."); + } } public override DirtyCaptureValue Read(SerializationReader reader) => new() { value = reader.Read("value") }; diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDocumentLifecycleNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDocumentLifecycleNativeTests.cs index 73aee6ff6..ca55dc941 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDocumentLifecycleNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDocumentLifecycleNativeTests.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; +using Xunit; using Inno.Editor.Interactions; using Inno.Scene; using Inno.Testing.Editor.Native; -using Xunit; namespace Inno.Editor.PlayMode.Tests; @@ -24,7 +24,9 @@ public void OneHundredSavedSceneCyclesRetireLiveScenesAndPreserveSourceAndHistor EditorPanelExtension panel = host.native.GetPanel("scene.hierarchy"); var retired = new List>(); for (int iteration = 0; iteration < 100; iteration++) + { retired.Add(OpenDrawAndClose(host, panel, path)); + } Assert.Empty(host.workspace.scenes); Assert.True(host.runtime.interactions.history.canUndo); Assert.Equal(source, File.ReadAllBytes(Path.Combine(host.projectRoot, "Assets", path))); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs index eb804f06f..a320842e5 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs @@ -1,9 +1,10 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; -using System.Collections.Generic; using System.Runtime.CompilerServices; +using Xunit; using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -11,7 +12,7 @@ using Inno.Editor.Settings; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.PlayMode.Tests; @@ -60,7 +61,9 @@ public void OneHundredSettingsCyclesReleaseDrawnValuesAndReloadAdmission() { using var host = new NativeProjectPanelHost(typeof(SettingsApplyNativeTests).Assembly, includeSettings: true); for (int cycle = 0; cycle < 100; cycle++) + { OpenAndClose(host); + } Assert.True(AtomicEditorSetting.snapshots.Count >= 100); GC.Collect(); GC.WaitForPendingFinalizers(); @@ -99,7 +102,11 @@ public void FailedRollbackKeepsHistoryFaultedAndPreventsFurtherApply() try { var document = new FailingSettingsDocument(new FileByteDocumentStore(Path.Combine(directory, "Project.inno"))); - using var host = new NativeProjectPanelHost(typeof(SettingsApplyNativeTests).Assembly, includeSettings: true, settingsDocument: document); + using var host = new NativeProjectPanelHost( + typeof(SettingsApplyNativeTests).Assembly, + includeSettings: true, + settingsDocument: document + ); Assert.True(host.runtime.interactions.TryGetModule(out var editor)); var driver = new SettingsInput(host); Assert.True(host.runtime.interactions.For("editor/main-menu").Execute("editor.settings.open")); @@ -116,7 +123,9 @@ public void FailedRollbackKeepsHistoryFaultedAndPreventsFurtherApply() using IDisposable listener = editor!.ListenChanges(_ => { if (obstructed) + { return; + } File.Move(editorFile, savedFile); Directory.CreateDirectory(editorFile); obstructed = true; @@ -147,7 +156,12 @@ public void FailedRollbackKeepsHistoryFaultedAndPreventsFurtherApply() Assert.Equal(0, host.projectSettings.Get(new("tests.ui.atomic-settings")).value); driver.Cancel(); host.native.logs.Flush(); - Assert.False(driver.isVisible, driver.diagnostic + Environment.NewLine + string.Join(Environment.NewLine, host.native.console.Capture().occurrences.Select(entry => entry.message))); + Assert.False( + driver.isVisible, + driver.diagnostic + + Environment.NewLine + + string.Join(Environment.NewLine, host.native.console.Capture().occurrences.Select(entry => entry.message)) + ); } finally { @@ -166,7 +180,11 @@ public void FailedSettingsBatchPreservesAllOwnersAndDraftsForRetry() try { var document = new FailingSettingsDocument(new FileByteDocumentStore(Path.Combine(directory, "Project.inno"))); - using var host = new NativeProjectPanelHost(typeof(SettingsApplyNativeTests).Assembly, includeSettings: true, settingsDocument: document); + using var host = new NativeProjectPanelHost( + typeof(SettingsApplyNativeTests).Assembly, + includeSettings: true, + settingsDocument: document + ); Assert.True(host.runtime.interactions.TryGetModule(out var editor)); var driver = new SettingsInput(host); Assert.True(host.runtime.interactions.For("editor/main-menu").Execute("editor.settings.open")); @@ -209,11 +227,15 @@ private sealed class FailingSettingsDocument(IByteDocumentStore owner) : IByteDo public string documentName => owner.documentName; public bool canWrite => owner.canWrite; public bool exists => owner.exists; + public byte[]? Read() => owner.Read(); + public void Write(ReadOnlySpan data) { if (failWrites) + { throw new IOException("Controlled project settings publication failure."); + } owner.Write(data); } } @@ -242,12 +264,17 @@ internal void Draw() Assert.True(modal.TryGetPresentation(out var presentation)); isVisible = presentation.isVisible; if (!isVisible) + { return; + } Assert.True(modal.Draw(host.runtime.context), "The operational Settings failure must not quarantine the modal."); m_apply = (NativeGui.GetItemRectMin() + NativeGui.GetItemRectMax()) * 0.5f; var style = NativeGui.Raw.GetStyle(); - m_cancel = new Vector2(NativeGui.GetItemRectMin().X - style->ItemSpacing.X - - NativeGui.CalcTextSize("Cancel").X * 0.5f - style->FramePadding.X, m_apply.Y); + m_cancel = new Vector2( + NativeGui.GetItemRectMin().X - style->ItemSpacing.X + - NativeGui.CalcTextSize("Cancel").X * 0.5f - style->FramePadding.X, + m_apply.Y + ); } finally { @@ -267,13 +294,17 @@ internal void Search(string text) NativeGui.Raw.AddKeyEvent(io, ImGuiKey.ImGuiModCtrl, 0); Draw(); foreach (char character in text) + { NativeGui.Raw.AddInputCharacter(io, character); + } Draw(); Draw(); } internal void Apply() => Click(m_apply); + internal void Cancel() => Click(m_cancel); + internal void CloseClean() => Click(m_apply); private void Click(Vector2 point) @@ -297,6 +328,7 @@ public sealed class AtomicEditorSetting : EditorSetting public static bool throwOnDraw; public static bool observe; public static readonly List> snapshots = []; + public override EditorSettingObject defaultValue { get @@ -306,14 +338,21 @@ public override EditorSettingObject defaultValue return value; } } + protected override void OnDraw(EditorSettingObject setting) { if (throwOnDraw) + { throw new InvalidOperationException("Controlled Settings drawer failure."); + } if (observe && (snapshots.Count == 0 || !snapshots[^1].TryGetTarget(out var last) || !ReferenceEquals(last, setting))) + { snapshots.Add(new WeakReference(setting)); + } if (!stage) + { return; + } setting.SetAsInt32("value", 42); stage = false; } @@ -331,10 +370,13 @@ public sealed class AtomicProjectSetting : ISerializable public sealed class AtomicProjectEditor : ProjectSettingEditor { public static bool stage; + protected override void OnDraw(AtomicProjectSetting setting) { if (!stage) + { return; + } setting.value = 84; stage = false; } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs index 748873b82..7fe93907d 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs @@ -1,9 +1,10 @@ using System; using System.Numerics; +using Xunit; using Inno.Editor.Interactions; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + using NativeImGui = Inno.Native.ImGui.ImGui; using Ui = Inno.Editor.ImGui.ImGui; @@ -18,7 +19,9 @@ public void ActualPanelSamplesAtHalfSecondIntervalsAndResetsAfterHiddenFrames() EditorPanelExtension panel = host.GetPanel("diagnostics.stats"); Assert.Equal(0, DrawAndCountTrendVertices(host, panel, 0.1f)); for (int frame = 0; frame < 4; frame++) + { Assert.Equal(0, DrawAndCountTrendVertices(host, panel, 0.1f)); + } int twoSampleVertices = DrawAndCountTrendVertices(host, panel, 0.1f); Assert.True(twoSampleVertices > 0); panel.isOpen = false; @@ -73,7 +76,9 @@ float deltaTime { uint vertex = draw->VtxBuffer.Data[index].Col; if ((vertex & 0x00ffffff) == (packed & 0x00ffffff) && (vertex >> 24) != 0) + { count++; + } } } finally diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs index ca080b306..4cc7fa69e 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs @@ -1,11 +1,12 @@ using System; using System.Numerics; +using Xunit; using Inno.Core.Input; using Inno.Editor.Core; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + using NativeImGui = Inno.Native.ImGui.ImGui; using Ui = Inno.Editor.ImGui.ImGui; @@ -22,7 +23,11 @@ public void ListActivationDoesNotToggleDisclosureOrStealAnOverlayButton( bool commandKeyBehavior, KeyModifier primaryModifier ) { - using var host = new NativePanelHost(typeof(TreeKeyboardOwnershipNativeTests).Assembly, false, new EditorKeyboardPolicy(primaryModifier, "Super")); + using var host = new NativePanelHost( + typeof(TreeKeyboardOwnershipNativeTests).Assembly, + false, + new EditorKeyboardPolicy(primaryModifier, "Super") + ); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->ConfigMacOsxBehaviors = commandKeyBehavior ? (byte)1 : (byte)0; ImGuiKey primaryKey = primaryModifier == KeyModifier.Super ? ImGuiKey.ImGuiModSuper : ImGuiKey.ImGuiModCtrl; @@ -54,9 +59,13 @@ KeyModifier primaryModifier { NativeImGui.SameLine(0f, -1f); if (overlayFocus) + { Ui.FocusNextItem(); + } if (NativeImGui.SmallButton("Overlay")) + { overlayPresses++; + } overlayId = NativeImGui.Raw.GetCurrentContext()->LastItemData.ID; ImGuiNativeContext* state = NativeImGui.Raw.GetCurrentContext(); overlayState = $"id={overlayId:X}, nav={state->NavId:X}, active={state->ActiveId:X}, activate={state->NavActivateId:X}, pressed={state->NavActivatePressedId:X}, keyOwner={NativeImGui.GetKeyOwner(ImGuiKey.Space):X}"; @@ -64,10 +73,14 @@ KeyModifier primaryModifier }); open = row.isOpen; if (open) + { NativeImGui.TreePop(); + } navigation = host.ui.widgets.NavigateList(host.runtime.interactions, 1, 0); if (navigation.toggle) + { toggles++; + } } finally { diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs index c0d6888c3..56132ee54 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs @@ -2,10 +2,11 @@ using System.Collections.Generic; using System.Numerics; using System.Runtime.CompilerServices; +using Xunit; using Inno.Editor.ImGui; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; using NativeVector = Inno.Native.ImGui.ImVec2C; @@ -16,9 +17,15 @@ public sealed unsafe class VisualScaleMatrixTests public static IEnumerable Metrics() { foreach (float zoom in new[] { 0.75f, 0.85f, 0.90f, 1f, 1.10f, 1.25f, 1.50f }) + { foreach (float density in new[] { 1f, 1.25f, 1.50f, 2f }) + { foreach (Vector2 size in new[] { new Vector2(1280f, 720f), new Vector2(1920f, 1080f) }) + { yield return [zoom, density, size.X, size.Y]; + } + } + } } [Theory] @@ -48,16 +55,20 @@ float height try { var widgets = host.ui.widgets; - widgets.PropertyRow("reference", () => - { - labelWidth = NativeGui.GetContentRegionAvail().X; - widgets.PropertyLabel("Resource reference / 资源引用 / Missing"); - }, () => - { - valueWidth = NativeGui.GetContentRegionAvail().X; - string value = "Unassigned / 未指定"; - widgets.Disabled(true, () => NativeGui.TextUnformatted(value)); - }); + widgets.PropertyRow( + "reference", + () => + { + labelWidth = NativeGui.GetContentRegionAvail().X; + widgets.PropertyLabel("Resource reference / 资源引用 / Missing"); + }, + () => + { + valueWidth = NativeGui.GetContentRegionAvail().X; + string value = "Unassigned / 未指定"; + widgets.Disabled(true, () => NativeGui.TextUnformatted(value)); + } + ); widgets.MixedValue(true, () => Assert.True(widgets.isMixedValue)); Assert.False(widgets.isMixedValue); Assert.Equal(zoom, widgets.style.zoom); diff --git a/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs index 3518d7454..8bce5c1e5 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs @@ -1,25 +1,26 @@ -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Diagnostics; -using Inno.Extensibility.Modules; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; +using Inno.Editor.Core; +using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; using Inno.Plugins.Authoring; -using Xunit; namespace Inno.Editor.Presentation.Tests; + public sealed class AssetHistoryTests : IDisposable { private readonly Inno.Editor.ImGui.EditorUiSession m_ui = new(); @@ -35,6 +36,7 @@ public sealed class AssetHistoryTests : IDisposable private readonly PluginEnvironment m_plugins; private readonly ProjectSettingsStore m_settings; private readonly EditorInteractionRuntime m_runtime; + public AssetHistoryTests() { string assetRoot = Path.Combine(m_projectRoot, "Assets"); @@ -42,7 +44,9 @@ public AssetHistoryTests() m_identityScope = m_identities.EnterScope(); _ = typeof(AssetEditingModule); _ = typeof(TextAsset); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetHistoryTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(AssetHistoryTests).Assembly) } + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); string libraryRoot = Path.Combine(m_projectRoot, "Library"); @@ -62,7 +66,15 @@ public AssetHistoryTests() new ProjectId("tests.editor"), AssetSerializationContext.Create(m_assets) ); - m_plugins = new PluginEnvironment(m_assets, m_settings, m_serialization, pluginRoot, libraryRoot, pluginScan, m_modules.generations); + m_plugins = new PluginEnvironment( + m_assets, + m_settings, + m_serialization, + pluginRoot, + libraryRoot, + pluginScan, + m_modules.generations + ); m_runtime = new EditorInteractionRuntime( new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), m_types, @@ -85,7 +97,9 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } [Fact] @@ -157,7 +171,9 @@ public void FileBrowserDropMovesFilesAndFoldersWithUndoRedo() m_assets.CreateDirectory(AssetPath.Project("To")); Assert.True(m_assets.Save(AssetPath.Project("From/Value.txt"), new TextAsset("value"))); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("From/Value.txt"), out AssetFileEntry file)); - RuntimeIdentity fileToken = m_runtime.interactions.For("panel/asset.file-browser", file).BeginDrag(new EditorDragData(file, "Value.txt")); + RuntimeIdentity fileToken = m_runtime.interactions + .For("panel/asset.file-browser", file) + .BeginDrag(new EditorDragData(file, "Value.txt")); EditorInteraction destination = m_runtime.interactions.For("panel/asset.file-browser", "To"); Assert.True(destination.QueryDrop(fileToken, EditorDropPlacement.Into).canDrop); Assert.True(destination.Drop(fileToken, EditorDropPlacement.Into).accepted); @@ -168,7 +184,9 @@ public void FileBrowserDropMovesFilesAndFoldersWithUndoRedo() Assert.True(m_runtime.interactions.history.Redo().succeeded); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("To/Value.txt"), out _)); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("From/Folder"), out AssetFileEntry folder)); - RuntimeIdentity folderToken = m_runtime.interactions.For("panel/asset.file-browser", folder).BeginDrag(new EditorDragData(folder, "Folder")); + RuntimeIdentity folderToken = m_runtime.interactions + .For("panel/asset.file-browser", folder) + .BeginDrag(new EditorDragData(folder, "Folder")); Assert.True(destination.QueryDrop(folderToken, EditorDropPlacement.Into).canDrop); Assert.True(destination.Drop(folderToken, EditorDropPlacement.Into).accepted); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("To/Folder/Child"), out _)); @@ -184,9 +202,19 @@ public void FileBrowserDropRejectsAFolderOwnDescendantAndNameCollisions() m_assets.CreateDirectory(AssetPath.Project("Target")); m_assets.CreateDirectory(AssetPath.Project("Target/Source")); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project("Source"), out AssetFileEntry source)); - RuntimeIdentity descendantToken = m_runtime.interactions.For("panel/asset.file-browser", source).BeginDrag(new EditorDragData(source, "Source")); - Assert.False(m_runtime.interactions.For("panel/asset.file-browser", "Source/Child").QueryDrop(descendantToken, EditorDropPlacement.Into).canDrop); - RuntimeIdentity collisionToken = m_runtime.interactions.For("panel/asset.file-browser", source).BeginDrag(new EditorDragData(source, "Source")); - Assert.False(m_runtime.interactions.For("panel/asset.file-browser", "Target").QueryDrop(collisionToken, EditorDropPlacement.Into).canDrop); + RuntimeIdentity descendantToken = m_runtime.interactions + .For("panel/asset.file-browser", source) + .BeginDrag(new EditorDragData(source, "Source")); + Assert.False( + m_runtime.interactions + .For("panel/asset.file-browser", "Source/Child") + .QueryDrop(descendantToken, EditorDropPlacement.Into).canDrop + ); + RuntimeIdentity collisionToken = m_runtime.interactions + .For("panel/asset.file-browser", source) + .BeginDrag(new EditorDragData(source, "Source")); + Assert.False( + m_runtime.interactions.For("panel/asset.file-browser", "Target").QueryDrop(collisionToken, EditorDropPlacement.Into).canDrop + ); } } diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs index 5d682f6c9..3e395cda6 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs @@ -1,8 +1,8 @@ using System; using System.Linq; +using Xunit; using Inno.Core.Input; using Inno.Editor.Interactions; -using Xunit; namespace Inno.Editor.Presentation.Tests; @@ -81,17 +81,17 @@ public sealed class MenuStateAction : EditorAction { protected override EditorActionState Query(EditorActionContext context) => context.target is MenuStateTarget target - ? new(target.visible, target.enabled, target.isChecked, target.label, "Current owner is read-only.") - : EditorActionState.hidden; + ? new(target.visible, target.enabled, target.isChecked, target.label, "Current owner is read-only.") + : EditorActionState.hidden; - protected override void Execute(EditorActionContext context) { } + protected override void Execute(EditorActionContext context) {} } [EditorAction("tests.menu-fallback", "tests/shared-menu")] [EditorMenu("tests/shared-menu", "Shared", order: 100)] public sealed class MenuFallbackAction : EditorAction { - protected override void Execute(EditorActionContext context) { } + protected override void Execute(EditorActionContext context) {} } [EditorAction("tests.menu-conditional", "tests/shared-menu")] @@ -101,7 +101,7 @@ public sealed class MenuConditionalAction : EditorAction protected override EditorActionState Query(EditorActionContext context) => context.target is MenuStateTarget { visible: true } ? EditorActionState.enabled : EditorActionState.hidden; - protected override void Execute(EditorActionContext context) { } + protected override void Execute(EditorActionContext context) {} } [EditorMenuSource("tests/failed-menu")] diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs index e45ff0d3d..af23945b2 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs @@ -1,10 +1,10 @@ using System; using System.Diagnostics; using System.Text.Json; +using Xunit; using Inno.Core.Events; using Inno.Core.Input; using Inno.Editor.Core; -using Xunit; namespace Inno.Editor.Presentation.Tests; @@ -25,13 +25,16 @@ public void PublicCommandAndStatisticsPathsProduceRepeatableSamples() var statistics = new EditorStatistics(); for (int index = 0; index < 100; index++) { - statistics.Publish(new EditorStatistic( - new("metric/" + index), - new("group/" + index / 10), - "Group " + index / 10, - "Metric " + index, - index.ToString(), - order: index)); + statistics.Publish( + new EditorStatistic( + new("metric/" + index), + new("group/" + index / 10), + "Group " + index / 10, + "Metric " + index, + index.ToString(), + order: index + ) + ); } Measure("statistics-unchanged", () => Assert.Equal(100, statistics.GetSnapshot().Count)); } @@ -43,7 +46,9 @@ Action operation const int iterations = 2_000; using Process process = Process.GetCurrentProcess(); for (int warmup = 0; warmup < 200; warmup++) + { operation(); + } for (int sample = 0; sample < 5; sample++) { TimeSpan cpu = process.TotalProcessorTime; @@ -53,17 +58,25 @@ Action operation long before = GC.GetAllocatedBytesForCurrentThread(); long start = Stopwatch.GetTimestamp(); for (int iteration = 0; iteration < iterations; iteration++) + { operation(); + } double milliseconds = Stopwatch.GetElapsedTime(start).TotalMilliseconds; long bytes = GC.GetAllocatedBytesForCurrentThread() - before; - Console.WriteLine(JsonSerializer.Serialize(new - { - workload = name, sample, iterations, milliseconds, bytes, - cpuMilliseconds = (process.TotalProcessorTime - cpu).TotalMilliseconds, - gen0 = GC.CollectionCount(0) - gen0, - gen1 = GC.CollectionCount(1) - gen1, - gen2 = GC.CollectionCount(2) - gen2 - })); + Console.WriteLine( + JsonSerializer.Serialize(new + { + workload = name, + sample, + iterations, + milliseconds, + bytes, + cpuMilliseconds = (process.TotalProcessorTime - cpu).TotalMilliseconds, + gen0 = GC.CollectionCount(0) - gen0, + gen1 = GC.CollectionCount(1) - gen1, + gen2 = GC.CollectionCount(2) - gen2 + }) + ); } } } diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs index c7dd30f93..089bec356 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs @@ -1,12 +1,13 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using Xunit; using Inno.Core.Identity; using Inno.Editor.Core; using Inno.Editor.Interactions; -using Xunit; namespace Inno.Editor.Presentation.Tests; + public sealed partial class EditorRuntimeTests { [Fact] @@ -21,7 +22,9 @@ public void MissingIdentityRejectsTheEntireVisibleRangeWithoutChangingSelection( RuntimeIdentity firstId = first.identity.runtimeIdentity!.Value; RuntimeIdentity missing = new(firstId.domainId, int.MaxValue); Assert.Throws(() => m_runtime.interactions.SelectRange( - [firstId, missing, last.identity.runtimeIdentity!.Value], last)); + [firstId, missing, last.identity.runtimeIdentity!.Value], + last + )); Assert.Same(original, m_runtime.interactions.selection.Capture()); Assert.Same(first, m_runtime.interactions.selection.selectedTarget); } @@ -42,7 +45,9 @@ public void LargeIdentityRangesKeepOrderedPrimaryAndIndexedMembership() Assert.Equal(targets.Length, m_runtime.interactions.selection.count); Assert.Same(targets[^1], m_runtime.interactions.selection.selectedTarget); foreach (SelectionQueueTarget target in targets) + { Assert.True(m_runtime.interactions.selection.Contains(target)); + } m_runtime.interactions.SetSelection(targets[0]); Assert.False(m_runtime.interactions.selection.Contains(targets[^1])); } @@ -145,13 +150,14 @@ public void SelectionFinishesPendingEditsBeforeChangingAndPreservesStateWhenPrep { Assert.Same(first, m_runtime.interactions.selection.selectedTarget); gesture.Commit(); - })) - { + })) { m_runtime.interactions.SetSelection(second); } Assert.False(gesture.isActive); ulong revision = m_runtime.interactions.selection.version; - using var rejecting = hub.Listen(_ => throw new InvalidOperationException("Pending edit cannot finish.")); + using var rejecting = hub.Listen( + _ => throw new InvalidOperationException("Pending edit cannot finish.") + ); Assert.Throws(() => m_runtime.interactions.SetSelection(first)); Assert.Throws(() => m_runtime.interactions.SetSelection([first], first)); Assert.Same(second, m_runtime.interactions.selection.selectedTarget); @@ -188,13 +194,19 @@ public void RangeSelectionUsesVisibleOrderAndTogglePreservesTheAnchor() Assert.True(m_identities.Register(second)); Assert.True(m_identities.Register(third)); m_runtime.interactions.SetSelection(first); - m_runtime.interactions.SelectRange([first.identity.runtimeIdentity!.Value, second.identity.runtimeIdentity!.Value, third.identity.runtimeIdentity!.Value], third); + m_runtime.interactions.SelectRange( + [first.identity.runtimeIdentity!.Value, second.identity.runtimeIdentity!.Value, third.identity.runtimeIdentity!.Value], + third + ); Assert.Equal(3, m_runtime.interactions.selection.count); m_runtime.interactions.ToggleSelection(second); Assert.False(m_runtime.interactions.selection.Contains(second)); Assert.Same(first, m_runtime.interactions.selection.anchor); Assert.Same(third, m_runtime.interactions.selection.selectedTarget); - m_runtime.interactions.SelectRange([third.identity.runtimeIdentity!.Value, second.identity.runtimeIdentity!.Value, first.identity.runtimeIdentity!.Value], second); + m_runtime.interactions.SelectRange( + [third.identity.runtimeIdentity!.Value, second.identity.runtimeIdentity!.Value, first.identity.runtimeIdentity!.Value], + second + ); var targets = new List(); Assert.Equal(2, m_runtime.interactions.selection.CopyTargets(targets)); Assert.Equal([first, second], targets); diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs index d90070537..654a4136e 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs @@ -1,6 +1,6 @@ using System.Linq; -using Inno.Editor.Core; using Xunit; +using Inno.Editor.Core; namespace Inno.Editor.Presentation.Tests; @@ -34,7 +34,10 @@ public void StatisticFrameHandoffRetainsLateProvidersAndRemovesExpiredContributi var combined = statistics.GetSnapshot(); Assert.Equal(2, combined.Count(value => value.groupId == new EditorStatisticGroupId("sampling"))); m_runtime.Update(new EditorFrame(0.016f, 2f, isFocused: true)); - Assert.Equal("second", Assert.Single(statistics.GetSnapshot().Where(value => value.groupId == new EditorStatisticGroupId("sampling"))).id.value); + Assert.Equal( + "second", + Assert.Single(statistics.GetSnapshot().Where(value => value.groupId == new EditorStatisticGroupId("sampling"))).id.value + ); Assert.Equal(2, combined.Count); m_runtime.Update(new EditorFrame(0.016f, 3f, isFocused: true)); Assert.DoesNotContain(statistics.GetSnapshot(), value => value.groupId == new EditorStatisticGroupId("sampling")); diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs index e527ee352..e20918da0 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs @@ -1,11 +1,10 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Reload; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Events; using Inno.Core.Execution; @@ -14,14 +13,16 @@ using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; -using Inno.Extensibility.Types; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.Interactions; using Inno.Editor.Settings; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; namespace Inno.Editor.Presentation.Tests; + public sealed partial class EditorRuntimeTests : IDisposable { private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoEditorRuntimeTests", Guid.NewGuid().ToString("N")); @@ -33,11 +34,14 @@ public sealed partial class EditorRuntimeTests : IDisposable private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; private readonly EditorInteractionRuntime m_runtime; + public EditorRuntimeTests() { Directory.CreateDirectory(Path.Combine(m_projectRoot, "Assets")); m_diagnosticScope = m_diagnostics.EnterScope(); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorRuntimeTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorRuntimeTests).Assembly) } + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); TestModule.startCount = 0; TestModule.stopCount = 0; @@ -85,13 +89,16 @@ public void Dispose() m_diagnosticScope.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } private EditorInteractionRuntime CreateRuntime( EditorContext context, params object[] hostServices ) => new(context, m_types, m_logs, [m_types, m_identities, m_secondaryIdentities, ..hostServices]); + [Fact] public void FeatureLookupReturnsOnlyStartedNonQuarantinedModules() { @@ -137,7 +144,10 @@ public void InteractionRuntimeInjectsOneStableAssignableHostService() { var service = new TestHostService(); HostServicePanel.current = null; - using EditorInteractionRuntime runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), service); + using EditorInteractionRuntime runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + service + ); runtime.Start(); Assert.Contains(runtime.panels, static panel => panel.id == "tests.host-service"); Assert.Same(service, HostServicePanel.current); @@ -147,7 +157,9 @@ public void InteractionRuntimeInjectsOneStableAssignableHostService() public void InteractionRuntimeRejectsExtensionWhenHostServiceIsUnavailable() { HostServicePanel.current = null; - using EditorInteractionRuntime runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + using EditorInteractionRuntime runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")) + ); runtime.Start(); Assert.DoesNotContain(runtime.panels, static panel => panel.id == "tests.host-service"); Assert.Null(HostServicePanel.current); @@ -269,8 +281,21 @@ public void ViewportToolCapturesOnePointerAndCommitsOneGestureTransaction() KeyModifier.None ); Assert.True(session.HandlePointer(down)); - Assert.False(session.HandlePointer(new EditorViewportPointerEvent(8, EditorViewportPointerPhase.Move, default, default, 0, KeyModifier.None))); - Assert.True(session.HandlePointer(new EditorViewportPointerEvent(7, EditorViewportPointerPhase.Up, down.screenPosition, down.worldPosition, 0, KeyModifier.None))); + Assert.False( + session.HandlePointer(new EditorViewportPointerEvent(8, EditorViewportPointerPhase.Move, default, default, 0, KeyModifier.None)) + ); + Assert.True( + session.HandlePointer( + new EditorViewportPointerEvent( + 7, + EditorViewportPointerPhase.Up, + down.screenPosition, + down.worldPosition, + 0, + KeyModifier.None + ) + ) + ); Assert.Equal(1, tool.downCount); Assert.Equal(1, tool.upCount); Assert.True(history.canUndo); @@ -398,7 +423,10 @@ public void NeutralHistorySurvivesATypeCatalogGenerationChange() [Fact] public void MissingHistoryHandlerCreatesAnExplicitBarrier() { - m_runtime.interactions.history.RecordApplied("Unavailable Change", new EditorHistoryChange("tests/missing-history-handler", EditorHistoryPayload.FromBytes([1, 2, 3]))); + m_runtime.interactions.history.RecordApplied( + "Unavailable Change", + new EditorHistoryChange("tests/missing-history-handler", EditorHistoryPayload.FromBytes([1, 2, 3])) + ); Assert.False(m_runtime.interactions.history.canUndo); Assert.Contains("tests/missing-history-handler", m_runtime.interactions.history.undoUnavailableReason); Assert.False(m_runtime.interactions.history.Undo().succeeded); @@ -412,7 +440,10 @@ public void LargeNeutralPayloadSpillsToTheBoundedSessionDiskStore() byte[] bytes = new byte[128 * 1024]; BitConverter.GetBytes(9).CopyTo(bytes, 0); BitConverter.GetBytes(32).CopyTo(bytes, sizeof(int)); - m_runtime.interactions.history.RecordApplied("Large Neutral Change", new EditorHistoryChange(NeutralHistoryHandler.KIND, EditorHistoryPayload.FromBytes(bytes))); + m_runtime.interactions.history.RecordApplied( + "Large Neutral Change", + new EditorHistoryChange(NeutralHistoryHandler.KIND, EditorHistoryPayload.FromBytes(bytes)) + ); Assert.Equal(0, m_runtime.interactions.history.residentBytes); Assert.Equal(bytes.LongLength, m_runtime.interactions.history.diskBytes); Assert.True(m_runtime.interactions.history.Undo().succeeded); @@ -567,7 +598,13 @@ public void IdentityResolutionUsesTheOwningDomain() Assert.Same(primary, primaryResult); Assert.True(m_runtime.interactions.TryResolveIdentity(secondaryIdentity, out IdentityObject? secondaryResult)); Assert.Same(secondary, secondaryResult); - Assert.True(m_runtime.interactions.TryResolveIdentity(secondaryIdentity.domainId, secondary.identity.persistentId, out IdentityObject? persistentResult)); + Assert.True( + m_runtime.interactions.TryResolveIdentity( + secondaryIdentity.domainId, + secondary.identity.persistentId, + out IdentityObject? persistentResult + ) + ); Assert.Same(secondary, persistentResult); var crossDomainAlias = new RuntimeIdentity(secondaryIdentity.domainId, primaryIdentity.runtimeId); Assert.NotSame(primary, m_runtime.interactions.TryResolveIdentity(crossDomainAlias, out IdentityObject? alias) ? alias : null); @@ -575,7 +612,9 @@ public void IdentityResolutionUsesTheOwningDomain() Assert.True(m_secondaryIdentities.Unregister(secondary)); var replacement = new DragSource(); Assert.True(m_secondaryIdentities.Register(replacement, persistentId)); - Assert.True(m_runtime.interactions.TryResolveIdentity(secondaryIdentity.domainId, persistentId, out IdentityObject? replacementResult)); + Assert.True( + m_runtime.interactions.TryResolveIdentity(secondaryIdentity.domainId, persistentId, out IdentityObject? replacementResult) + ); Assert.Same(replacement, replacementResult); } @@ -586,7 +625,9 @@ public void TypedDropRoutesAndCancelsItsManagedSession() DragSource source = Register(new DragSource()); var target = new DropTarget(); var data = new EditorDragData(source, "source"); - RuntimeIdentity supersededIdentity = m_runtime.interactions.For("tests/other", supersededSource).BeginDrag(new EditorDragData(supersededSource, "superseded")); + RuntimeIdentity supersededIdentity = m_runtime.interactions + .For("tests/other", supersededSource) + .BeginDrag(new EditorDragData(supersededSource, "superseded")); RuntimeIdentity identity = m_runtime.interactions.For("tests/other", source).BeginDrag(data); EditorInteraction dropTarget = m_runtime.interactions.For("tests/drop", target); Assert.NotEqual(supersededIdentity, identity); @@ -646,7 +687,9 @@ public void FailedModuleStartIsStoppedBeforeCandidateDisposal() m_runtime.Dispose(); int stops = TestModule.stopCount; TestModule.throwOnStart = true; - using var runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + using var runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")) + ); try { Assert.Throws(runtime.Start); @@ -665,7 +708,9 @@ public void FailedPanelAttachmentIsCompensatedBeforeItIsQuarantined() m_runtime.Dispose(); int detaches = TestPanel.detachCount; TestPanel.throwOnAttach = true; - using var runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + using var runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")) + ); try { runtime.Start(); @@ -748,7 +793,9 @@ public void ModuleStateAndPanelVisibilityRestoreForTheSameProject() string document = File.ReadAllText(settingsPath); Assert.Contains("[InnoEditor][Module.tests.state]", document); Assert.DoesNotContain("[InnoEditor][Module.tests.update-barrier]", document); - using EditorInteractionRuntime restored = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + using EditorInteractionRuntime restored = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")) + ); restored.Start(); Assert.Equal(42, TestModule.restoredStateValue); Assert.True(Assert.Single(restored.panels.Where(static value => value.id == "tests.panel")).isOpen); @@ -776,7 +823,9 @@ public void ExtensionStateCaptureFailure_PublishesCurrentDiagnosticUntilRetrySuc { TestModule.captureFailure = true; m_runtime.Update(new EditorFrame(0.016f, 3f, isFocused: true)); - DiagnosticReport report = Assert.Single(sink.reports.Values.Where(static value => value.source.displayName == "Editor State Capture")); + DiagnosticReport report = Assert.Single( + sink.reports.Values.Where(static value => value.source.displayName == "Editor State Capture") + ); Assert.Equal("EDITOR-STATE-CAPTURE", Assert.Single(report.diagnostics).code); TestModule.captureFailure = false; m_runtime.Update(new EditorFrame(0.016f, 6f, isFocused: true)); @@ -818,7 +867,9 @@ public void StartupRegistryRefreshCannotOverwriteModuleStateBeforeRestore() TestModule.startCount = 0; TestModule.restoredStateValue = 0; TestModule.rebuildDuringRestore = true; - using EditorInteractionRuntime restored = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + using EditorInteractionRuntime restored = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")) + ); restored.Start(); Assert.Equal(91, TestModule.restoredStateValue); TestModule.stateValue = TestModule.restoredStateValue; @@ -835,13 +886,17 @@ private sealed class TestDiagnosticSink : IDiagnosticSink internal Dictionary reports { get; } = new(StringComparer.Ordinal); public void Replace(DiagnosticReport report) => reports[report.source.id] = report; + public void Clear(DiagnosticSource source) => reports.Remove(source.id); } } public class BaseTarget; + public sealed class DerivedTarget : BaseTarget; + public sealed class DragSource : IdentityObject; + public sealed class DropTarget { public bool wasDropped { get; set; } @@ -858,11 +913,13 @@ public sealed record InteractionPresentation( bool submit, bool cancel = false ); + [EditorHistoryHandler(NeutralHistoryHandler.KIND)] public sealed class NeutralHistoryHandler : EditorHistoryHandler { public const string KIND = "tests/neutral-value"; public static int value; + public static EditorHistoryChange CreateChange( int before, int after @@ -877,7 +934,10 @@ protected override EditorHistoryAvailability Query( EditorHistoryContext context, EditorHistoryChange change, EditorHistoryDirection direction - ) => change.payload.length >= sizeof(int) * 2 ? EditorHistoryAvailability.Available() : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); + ) => change.payload.length >= sizeof(int) * 2 + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); + protected override EditorHistoryResult Apply( EditorHistoryContext context, EditorHistoryChange change, @@ -890,11 +950,14 @@ EditorHistoryDirection direction } public interface ITestHostService; + public sealed class TestHostService : ITestHostService; + [EditorPanel("tests.host-service", "Host Service")] public sealed class HostServicePanel : EditorPanel { public static ITestHostService? current; + public HostServicePanel(ITestHostService service) { current = service; @@ -916,6 +979,7 @@ public sealed class TestModule : EditorModule public static bool throwOnStart; public static bool throwOnStop; public static int pendingStops; + public TestModule(TypeCatalog types) { m_types = types; @@ -924,7 +988,9 @@ public TestModule(TypeCatalog types) protected override void Capture(EditorState state) { if (captureFailure) + { throw new InvalidOperationException("The test module state cannot be captured."); + } state.Set("value", stateValue); } @@ -932,7 +998,9 @@ protected override void Restore(EditorState state) { restoredStateValue = state.Get("value", 0); if (!rebuildDuringRestore) + { return; + } rebuildDuringRestore = false; m_types.Rebuild(); } @@ -941,9 +1009,13 @@ protected override void OnStart(EditorContext context) { startCount++; if (throwOnStart) + { throw new InvalidOperationException("Injected module startup failure."); + } if (startCount == 1) + { m_types.Rebuild(); + } } protected override void OnStop(EditorContext context) @@ -951,9 +1023,13 @@ protected override void OnStop(EditorContext context) stopCount++; ShutdownOrder.events.Add("module.stop"); if (pendingStops-- > 0) + { throw new RetirementPendingException("Module-owned work has not drained."); + } if (throwOnStop) + { throw new InvalidOperationException("Injected module stop failure."); + } } } @@ -963,6 +1039,7 @@ public sealed class UpdateBarrierModule : EditorModule public static bool block; public static bool throwWhenRead; public static int barrierReadCount; + public override bool blocksFollowingUpdates { get @@ -977,6 +1054,7 @@ public override bool blocksFollowingUpdates public sealed class FollowingUpdateModule : EditorModule { public static int updateCount; + protected override void OnUpdate(EditorContext context) => updateCount++; } @@ -990,16 +1068,22 @@ public sealed class TestPanel(TestModule module) : EditorPanel public static bool throwOnAttach; public static bool throwOnDetach; public static int pendingDetaches; - public override bool useWindowPadding => throwFromWindowPadding ? throw new InvalidOperationException("Injected panel presentation failure.") : true; + + public override bool useWindowPadding + => throwFromWindowPadding ? throw new InvalidOperationException("Injected panel presentation failure.") : true; protected override void OnAttach(EditorContext context) { _ = module; if (attachCount == 0) + { firstAttachPrecededModuleStart = TestModule.startCount == 0; + } attachCount++; if (throwOnAttach) + { throw new InvalidOperationException("Injected panel attachment failure."); + } } protected override void OnDetach(EditorContext context) @@ -1007,14 +1091,16 @@ protected override void OnDetach(EditorContext context) detachCount++; ShutdownOrder.events.Add("panel.detach"); if (pendingDetaches-- > 0) + { throw new RetirementPendingException("Panel-owned work has not drained."); + } if (throwOnDetach) + { throw new InvalidOperationException("Injected panel detach failure."); + } } - protected override void OnDraw(EditorContext context) - { - } + protected override void OnDraw(EditorContext context) {} } [StableTypeId("0fbd66e2-303e-4b35-83a1-fc2b90d58360")] @@ -1043,24 +1129,23 @@ public sealed class SecondaryMultiPresentationEditor : ProjectSettingEditor { protected override EditorActionState Query(EditorActionContext context) => new(true, true, displayName: "base"); - protected override void Execute(EditorActionContext context) - { - } + + protected override void Execute(EditorActionContext context) {} } [EditorAction("tests.resolve", "tests/special", priority: 100)] public sealed class AreaResolveAction : EditorAction { protected override EditorActionState Query(EditorActionContext context) => new(true, true, displayName: "area"); - protected override void Execute(EditorActionContext context) - { - } + + protected override void Execute(EditorActionContext context) {} } [EditorAction("tests.deferred")] public sealed class DeferredAction : EditorAction { public static int executeCount; + protected override void Execute(EditorActionContext context) => executeCount++; } @@ -1069,6 +1154,7 @@ public sealed class MetadataAction : EditorAction { public static int targetTypeReadCount; public static bool throwWhenRead; + public override Type? targetType { get @@ -1078,9 +1164,7 @@ public override Type? targetType } } - protected override void Execute(EditorActionContext context) - { - } + protected override void Execute(EditorActionContext context) {} } [EditorAction("tests.multiple-shortcuts", "tests/multiple-shortcuts")] @@ -1089,6 +1173,7 @@ protected override void Execute(EditorActionContext context) public sealed class MultiShortcutAction : EditorAction { public static int executeCount; + protected override void Execute(EditorActionContext context) => executeCount++; } @@ -1098,7 +1183,10 @@ public sealed class ToolbarAction : EditorAction { public static bool isChecked; public static int executeCount; - protected override EditorActionState Query(EditorActionContext context) => new(true, true, isChecked, isChecked ? "Stop Runtime" : "Start Runtime"); + + protected override EditorActionState Query(EditorActionContext context) + => new(true, true, isChecked, isChecked ? "Stop Runtime" : "Start Runtime"); + protected override void Execute(EditorActionContext context) => executeCount++; } @@ -1106,6 +1194,7 @@ public sealed class ToolbarAction : EditorAction public sealed class ThrowAfterActivateAction : EditorAction { public static int cancelCount; + protected override void Execute(EditorActionContext context) { Activate(context); @@ -1121,10 +1210,13 @@ public sealed class ADisposeObserverModule(EditorInteractions interactions) : Ed public static bool historyAvailableDuringStop; public static bool historyDisposedDuringDispose; public static int disposeCount; + protected override void OnStop(EditorContext context) { if (interactions.history.isFaulted) + { return; + } using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Shutdown probe"); historyAvailableDuringStop = transaction.Rollback().succeeded; } @@ -1148,11 +1240,14 @@ public sealed class ZThrowingDisposeModule : EditorModule { public static bool throwOnDispose; public static int disposeCount; + protected override void OnDispose() { disposeCount++; if (throwOnDispose) + { throw new InvalidOperationException("Injected extension disposal failure."); + } } } @@ -1165,6 +1260,7 @@ internal static class ShutdownOrder public sealed class InteractionAction : EditorPresentationAction { private string m_value = string.Empty; + protected override void Execute(EditorActionContext context) { m_value = "Initial"; @@ -1183,7 +1279,9 @@ protected override bool Present(EditorActionContext { private InteractionTarget? m_target; + protected override void Execute(EditorActionContext context) { m_target = context.target; @@ -1212,7 +1311,9 @@ protected override void Execute(EditorActionContext context) protected override void OnPresentationLost() { if (m_target is not null) + { m_target.committedValue = "Committed on focus loss"; + } m_target = null; Complete(); } @@ -1224,9 +1325,7 @@ protected override void OnPresentationLost() [EditorMenu("tests/menu", "Tools/Create/Asset", order: 100)] public sealed class MenuAction : EditorAction { - protected override void Execute(EditorActionContext context) - { - } + protected override void Execute(EditorActionContext context) {} } [EditorMenuSource("tests/menu")] @@ -1246,6 +1345,7 @@ EditorMenuBuilder builder public sealed class TestDrop : EditorDrop { protected override EditorDropStatus Query(EditorDropContext context) => EditorDropStatus.Accept(); + protected override EditorDropResult Drop(EditorDropContext context) { context.target.wasDropped = true; @@ -1260,15 +1360,12 @@ public sealed class TestDocumentProvider : EditorDocumentProvider public int closeCount { get; private set; } public override string id => "tests.documents"; - public override bool CanOpen(string assetPath) => assetPath.EndsWith( - ".ispriteatlas2d", - StringComparison.Ordinal - ) - || assetPath.EndsWith( - ".itilemap2d", - StringComparison.Ordinal - ); + public override bool CanOpen(string assetPath) + => assetPath.EndsWith(".ispriteatlas2d", StringComparison.Ordinal) + || assetPath.EndsWith(".itilemap2d", StringComparison.Ordinal); + public override void Open(EditorDocumentContext context) => openCount++; + public override bool Save(EditorDocumentContext context) { saveCount++; @@ -1281,6 +1378,7 @@ public override bool Save(EditorDocumentContext context) public sealed class TestViewportCoordinates : IEditorViewportCoordinateConverter { public Inno.Core.Mathematics.Vector2 ScreenToWorld(Inno.Core.Mathematics.Vector2 screenPosition) => screenPosition * 2f; + public Inno.Core.Mathematics.Vector2 WorldToScreen(Inno.Core.Mathematics.Vector2 worldPosition) => worldPosition / 2f; } diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs index 9585221a0..f8d5ed8de 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs @@ -1,11 +1,10 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Logging; using Inno.Core.Serialization; @@ -14,9 +13,11 @@ using Inno.Editor.Interactions; using Inno.Editor.PlayMode; using Inno.Editor.Settings; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Editor.Presentation.Tests; + public sealed class EditorSettingsTests : IDisposable { private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoEditorSettingsTests", Guid.NewGuid().ToString("N")); @@ -29,10 +30,13 @@ public sealed class EditorSettingsTests : IDisposable private readonly DiagnosticHub m_diagnostics = new(); private readonly FakePlayMode m_playMode = new(); private readonly LogRouter m_logs = new(); + public EditorSettingsTests() { Directory.CreateDirectory(m_projectRoot); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorSettingsTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorSettingsTests).Assembly) } + ); _ = typeof(EditorSettings); _ = System.Reflection.Assembly.Load("Inno.Editor.Panel.Logging"); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); @@ -60,7 +64,9 @@ public void Dispose() m_modules.Dispose(); m_logs.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } [Fact] @@ -75,7 +81,11 @@ public void ApplyPersistsObjectsAtTheProjectRootAndPublishesOnlyTheService() }); var value = new EditorSettingObject(); value.SetAsInt32("value", 10); - Assert.True(m_settings.Apply(new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Values/Project Count"] = value })); + Assert.True( + m_settings.Apply( + new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Values/Project Count"] = value } + ) + ); string path = Path.Combine(m_projectRoot, "Settings.Editor.inno"); Assert.True(File.Exists(path)); Assert.False(Directory.Exists(Path.Combine(m_projectRoot, "Settings"))); @@ -92,7 +102,11 @@ public void ChangedSubscriberFailureDoesNotChangeHistoryResultOrSkipLaterSubscri using IDisposable deliveredSubscription = m_settings.ListenChanges(_ => delivered++); var value = new EditorSettingObject(); value.SetAsInt32("value", 11); - Assert.True(m_settings.Apply(new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Values/Project Count"] = value })); + Assert.True( + m_settings.Apply( + new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Values/Project Count"] = value } + ) + ); Assert.Equal(1, delivered); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal(2, delivered); @@ -115,12 +129,20 @@ public void GetReturnsIsolatedObjectsAndRejectsPagesOrMissingPaths() [Fact] public void ResetRemovesThePathOverrideAndRestoresTheDefinitionObject() { - EditorSetting definition = Assert.Single(m_settings.definitions, static setting => setting.path == "Editor/Tests/Values/Project Count"); + EditorSetting definition = Assert.Single( + m_settings.definitions, + static setting => setting.path == "Editor/Tests/Values/Project Count" + ); var value = new EditorSettingObject(); value.SetAsInt32("value", 8); Assert.True(m_settings.Apply(new Dictionary { ["Editor/Tests/Values/Project Count"] = value })); Assert.False(definition.IsDefault(m_settings.Get("Editor/Tests/Values/Project Count"))); - Assert.True(m_settings.Apply(new Dictionary(), new HashSet(StringComparer.Ordinal) { "Editor/Tests/Values/Project Count" })); + Assert.True( + m_settings.Apply( + new Dictionary(), + new HashSet(StringComparer.Ordinal) { "Editor/Tests/Values/Project Count" } + ) + ); Assert.Equal(3, m_settings.Get("Editor/Tests/Values/Project Count").GetAsInt32("value")); Assert.True(definition.IsDefault(m_settings.Get("Editor/Tests/Values/Project Count"))); Assert.NotSame(definition.defaultValue, definition.defaultValue); @@ -134,7 +156,15 @@ public void OneApplyCreatesOneSharedHistoryEntryForAllSettings() count.SetAsInt32("value", 7); var toggle = new EditorSettingObject(); toggle.SetAsBoolean("value", false); - Assert.True(m_settings.Apply(new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Values/Project Count"] = count, ["Editor/Tests/Values/Project Toggle"] = toggle })); + Assert.True( + m_settings.Apply( + new Dictionary(StringComparer.Ordinal) + { + ["Editor/Tests/Values/Project Count"] = count, + ["Editor/Tests/Values/Project Toggle"] = toggle + } + ) + ); Assert.Equal("Apply Settings", m_runtime.interactions.history.undoName); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal(3, m_settings.Get("Editor/Tests/Values/Project Count").GetAsInt32("value")); @@ -191,7 +221,11 @@ public void SettingObjectRoundTripsSupportedPrimitivesAndArrays() value.SetAsSingleArray("singles", [1.5f, 2.5f]); value.SetAsDoubleArray("doubles", [3.5d, 4.5d]); value.SetAsStringArray("strings", ["first", null, "third"]); - Assert.True(m_settings.Apply(new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Objects/Primitives"] = value })); + Assert.True( + m_settings.Apply( + new Dictionary(StringComparer.Ordinal) { ["Editor/Tests/Objects/Primitives"] = value } + ) + ); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.True(m_runtime.interactions.history.Redo().succeeded); EditorSettingObject restored = m_settings.Get("Editor/Tests/Objects/Primitives"); @@ -219,7 +253,10 @@ public void SettingObjectRoundTripsSupportedPrimitivesAndArrays() [Fact] public void DrawTracksDifferenceFromEachStagedObjectsFirstDraw() { - EditorSetting definition = Assert.Single(m_settings.definitions, static setting => setting.path == "Editor/Tests/Objects/Draw Mutation"); + EditorSetting definition = Assert.Single( + m_settings.definitions, + static setting => setting.path == "Editor/Tests/Objects/Draw Mutation" + ); var value = new EditorSettingObject(); Assert.True(definition.Draw(value)); Assert.Equal(42, value.GetAsInt32("value")); @@ -237,6 +274,7 @@ IEditorConsole editorConsole { internal static EditorSettings? current; internal static IEditorConsole? console; + protected override void OnStart(EditorContext context) { current = settings; @@ -252,9 +290,11 @@ private sealed class FakePlayMode : IEditorPlayMode public LogSessionId activeSessionId => LogSessionId.none; private readonly Inno.Core.Events.EventDispatcher m_stateDispatcher = new(); + public IDisposable ListenStateChanges(Action listener) => m_stateDispatcher.CreateHub(); public bool EnterPlayMode() => false; + public bool ExitPlayMode() => false; } @@ -271,9 +311,7 @@ private sealed class TestCountSetting : EditorSetting public override string section => "Numbers"; public override string description => "Exercises path-addressed project persistence."; - protected override void OnDraw(EditorSettingObject setting) - { - } + protected override void OnDraw(EditorSettingObject setting) {} private static EditorSettingObject CreateDefault() { @@ -289,9 +327,7 @@ private sealed class TestToggleSetting : EditorSetting public override EditorSettingObject defaultValue => CreateDefault(); public override string section => "Alpha"; - protected override void OnDraw(EditorSettingObject setting) - { - } + protected override void OnDraw(EditorSettingObject setting) {} private static EditorSettingObject CreateDefault() { @@ -306,9 +342,7 @@ private sealed class TestPrimitiveObjectSetting : EditorSetting { public override EditorSettingObject defaultValue => new(); - protected override void OnDraw(EditorSettingObject setting) - { - } + protected override void OnDraw(EditorSettingObject setting) {} } [EditorSettingPath("Editor/Tests/Objects/Draw Mutation")] diff --git a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs index a01743b1a..c27827bc9 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs @@ -1,9 +1,9 @@ using System; using System.Numerics; +using Xunit; using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; -using Xunit; namespace Inno.Editor.Presentation.Tests; @@ -41,11 +41,22 @@ public void ConnectionReleaseBehindAnotherInputOwnerDoesNotConnect() var output = new GraphEndpoint(new("source"), new("out")); var input = new GraphEndpoint(new("target"), new("in")); _ = layout.SetNodes([ - new(new("source"), new(0f, 0f), new(100f, 100f), 24f, "Source", [new(output, GraphPortDirection.Output, new(100f, 50f), "Output")]), + new( + new("source"), + new(0f, 0f), + new(100f, 100f), + 24f, + "Source", + [new(output, GraphPortDirection.Output, new(100f, 50f), "Output")] + ), new(new("target"), new(200f, 0f), new(100f, 100f), 24f, "Target", [new(input, GraphPortDirection.Input, new(0f, 50f), "Input")]) ]); _ = pointer.Step(view, layout, new() { position = new(100f, 50f), isHovered = true, isPressed = true, isDown = true }); - GraphCanvasPointerResult result = pointer.Step(view, layout, new() { position = new(200f, 50f), isReleased = true, isHovered = false }); + GraphCanvasPointerResult result = pointer.Step( + view, + layout, + new() { position = new(200f, 50f), isReleased = true, isHovered = false } + ); Assert.Null(result.output); Assert.Null(result.input); Assert.Null(state.pendingConnection); @@ -60,7 +71,10 @@ public void DragReturnsOneNeutralEditAndCancelLeavesTheDocumentUntouched() var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); var node = new GraphCanvasNode(new("flow.step"), new(10f, 10f), new(200f, 100f), 24f, "Workflow", []); _ = layout.SetNodes([node]); - Assert.Equal(node.id, pointer.Step(view, layout, new() { position = new(20f, 15f), isHovered = true, isPressed = true, isDown = true }).nodePressed); + Assert.Equal( + node.id, + pointer.Step(view, layout, new() { position = new(20f, 15f), isHovered = true, isPressed = true, isDown = true }).nodePressed + ); _ = pointer.Step(view, layout, new() { position = new(70f, 45f), isDown = true }); Assert.Equal(new GraphPosition(60f, 40f), pointer.previewPositions[node.id]); GraphCanvasPointerResult completed = pointer.Step(view, layout, new() { position = new(70f, 45f), isReleased = true }); @@ -88,11 +102,22 @@ public void ConnectionsAreNeutralIntentsAndMissingEndpointsCannotBeConnected(boo GraphEndpoint input = new(new("flow.target"), new("previous")); _ = layout.SetNodes([ new(output.nodeId, default, new(200f, 100f), 24f, "Source", [new(output, GraphPortDirection.Output, new(200f, 40f), "Next")]), - new(input.nodeId, new(300f, 0f), new(200f, 100f), 24f, "Target", [new(input, GraphPortDirection.Input, new(0f, 40f), "Previous", isMissing: missing)]) + new( + input.nodeId, + new(300f, 0f), + new(200f, 100f), + 24f, + "Target", + [new(input, GraphPortDirection.Input, new(0f, 40f), "Previous", isMissing: missing)] + ) ]); _ = pointer.Step(view, layout, new() { position = new(200f, 40f), isHovered = true, isPressed = true, isDown = true }); Assert.Equal(output, state.pendingConnection); - GraphCanvasPointerResult result = pointer.Step(view, layout, new() { position = new(300f, 40f), isHovered = true, isReleased = true }); + GraphCanvasPointerResult result = pointer.Step( + view, + layout, + new() { position = new(300f, 40f), isHovered = true, isReleased = true } + ); Assert.Equal(missing ? null : output, result.output); Assert.Equal(missing ? null : input, result.input); Assert.Null(state.pendingConnection); @@ -111,7 +136,11 @@ public void ReadOnlyChangesCancelEditsButStillAllowBoxSelection() _ = pointer.Step(view, layout, new() { position = new(100f, 100f), isDown = true }); Assert.Null(pointer.Step(view, layout, new() { position = new(100f, 100f), isReleased = true, readOnly = true }).movedNodes); Assert.False(pointer.isMoving); - _ = pointer.Step(view, layout, new() { position = new(5f, 150f), isHovered = true, isPressed = true, isDown = true, readOnly = true }); + _ = pointer.Step( + view, + layout, + new() { position = new(5f, 150f), isHovered = true, isPressed = true, isDown = true, readOnly = true } + ); Assert.True(pointer.isBoxSelecting); _ = pointer.Step(view, layout, new() { position = new(240f, 10f), isReleased = true, readOnly = true }); Assert.Equal(id, Assert.Single(state.selectedNodes)); diff --git a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs index 667329c39..9ffcc5984 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs @@ -1,10 +1,10 @@ using System; using System.Linq; using System.Numerics; +using Xunit; using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; -using Xunit; namespace Inno.Editor.Presentation.Tests; @@ -32,8 +32,14 @@ public void PortHitGeometryPreservesMissingAndExplicitLabelBounds() var state = new GraphCanvasState(); var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); GraphNodeId id = new("workflow.output"); - var port = new GraphCanvasPort(new(id, new("next")), GraphPortDirection.Output, new(200f, 40f), "Continue", - isMissing: true, labelBounds: (new(100f, 28f), new(200f, 52f))); + var port = new GraphCanvasPort( + new(id, new("next")), + GraphPortDirection.Output, + new(200f, 40f), + "Continue", + isMissing: true, + labelBounds: (new(100f, 28f), new(200f, 52f)) + ); var node = new GraphCanvasNode(id, new(10f, 10f), new(200f, 100f), 24f, "Flow step", [port]); var layout = new GraphCanvasLayout(); _ = layout.SetNodes([node]); @@ -47,7 +53,8 @@ public void PortHitGeometryPreservesMissingAndExplicitLabelBounds() public void ChangingOneOfTwoThousandNodesPreservesOtherGeometry() { GraphCanvasNode[] nodes = Enumerable.Range(0, 2000) - .Select(index => Node("workflow." + index, new(index * 220f, 0f))).ToArray(); + .Select(index => Node("workflow." + index, new(index * 220f, 0f))) + .ToArray(); var layout = new GraphCanvasLayout(); Assert.Equal(2000, layout.SetNodes(nodes)); GraphCanvasNode retained = nodes[999]; @@ -67,8 +74,14 @@ public void InvalidCandidatesDoNotReplaceTheCurrentSnapshot() Assert.Throws(() => layout.SetNodes([node, node])); Assert.Same(node, Assert.Single(layout.nodes)); Assert.Throws(() => new GraphCanvasNode(node.id, default, new(float.NaN, 10f), 2f, "Invalid", [])); - Assert.Throws(() => new GraphCanvasNode(node.id, default, new(200f, 100f), 24f, "Invalid", - [new GraphCanvasPort(new(new("foreign"), new("port")), GraphPortDirection.Input, Vector2.Zero, "Foreign")])); + Assert.Throws(() => new GraphCanvasNode( + node.id, + default, + new(200f, 100f), + 24f, + "Invalid", + [new GraphCanvasPort(new(new("foreign"), new("port")), GraphPortDirection.Input, Vector2.Zero, "Foreign")] + )); } private static GraphCanvasNode Node( diff --git a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs index f2f939da2..fa8754951 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs @@ -1,11 +1,12 @@ using System; using System.Numerics; +using Xunit; using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; -using Xunit; namespace Inno.Editor.Presentation.Tests; + public sealed class GraphCanvasViewTests { [Fact] diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeClipboard.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeClipboard.cs index 9f76c3b1c..8caaea53c 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeClipboard.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeClipboard.cs @@ -3,6 +3,7 @@ using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Testing.Editor.Native; @@ -28,7 +29,9 @@ internal NativeClipboard(ImGuiNativeContext* context) public void Dispose() { if (!m_handle.IsAllocated) + { return; + } Marshal.FreeCoTaskMem(m_text); m_text = 0; m_handle.Free(); diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs index 7a9ce7765..7f93eb858 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs @@ -16,10 +16,11 @@ using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Native.ImGui; -using NativeImGui = Inno.Native.ImGui.ImGui; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; + using ImGuiCond = Inno.Native.ImGui.ImGuiCond; using ImGuiWindowFlags = Inno.Native.ImGui.ImGuiWindowFlags; +using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Testing.Editor.Native; @@ -47,7 +48,10 @@ public sealed unsafe class NativePanelHost : IDisposable /// /// The calling test assembly owning the complete discovery closure. /// Additional declared panel assemblies to load before discovery. - public NativePanelHost(Assembly composition, params string[] assemblies) : this(composition, false, assemblies) { } + public NativePanelHost( + Assembly composition, + params string[] assemblies + ) : this(composition, false, assemblies) {} /// /// Creates a panel host with an explicit vertex-offset capability. @@ -59,7 +63,7 @@ public NativePanelHost( Assembly composition, bool supportsVertexOffsets, params string[] assemblies - ) : this(composition, supportsVertexOffsets, new EditorKeyboardPolicy(KeyModifier.Control, "Super"), assemblies) { } + ) : this(composition, supportsVertexOffsets, new EditorKeyboardPolicy(KeyModifier.Control, "Super"), assemblies) {} /// /// Creates the owned diagnostics, discovery, interactions and native frame context. @@ -78,7 +82,9 @@ params string[] assemblies m_ownsServices = true; Directory.CreateDirectory(m_root); foreach (string assembly in assemblies) + { _ = Assembly.Load(assembly); + } diagnostics = new DiagnosticHub(); m_diagnosticScope = diagnostics.EnterScope(); logs = new LogRouter(); @@ -118,18 +124,22 @@ internal NativePanelHost( /// Gets the borrowed diagnostic hub for this host's lifetime. /// public DiagnosticHub diagnostics { get; } + /// /// Gets the borrowed log router for this host's lifetime. /// public LogRouter logs { get; } + /// /// Gets the borrowed console consuming the host's logs. /// public EditorConsole console { get; } + /// /// Gets the borrowed interaction runtime and discovered panels. /// public EditorInteractionRuntime runtime { get; } + /// /// Gets the borrowed UI session owning the host's frame state. /// @@ -170,7 +180,9 @@ public void Frame( { NativeImGui.Render(); if (m_validateVertexOffsets) + { ValidateDrawData(); + } m_clipboard.ThrowIfFaulted(); } } @@ -218,9 +230,12 @@ public void DrawPanel( if (panel.isOpen && !panel.Draw(runtime.context)) { logs.Flush(); - string failures = string.Join(Environment.NewLine, console.Capture().occurrences - .Where(static entry => entry.level >= LogLevel.Error) - .Select(static entry => entry.message + Environment.NewLine + entry.stackTrace)); + string failures = string.Join( + Environment.NewLine, + console.Capture().occurrences + .Where(static entry => entry.level >= LogLevel.Error) + .Select(static entry => entry.message + Environment.NewLine + entry.stackTrace) + ); throw new InvalidOperationException("The actual panel was quarantined: " + panel.id + Environment.NewLine + failures); } afterDraw?.Invoke(); @@ -253,7 +268,9 @@ public void Dispose() NativeImGui.Raw.DestroyContext(m_nativeContext); m_clipboard.Dispose(); if (m_ownsServices) + { Directory.Delete(m_root, recursive: true); + } } private static ImGuiNativeContext* CreateNativeContext( @@ -266,14 +283,18 @@ bool supportsVertexOffsets io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; if (supportsVertexOffsets) + { io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasVtxOffset; + } io->ConfigFlags |= (int)ImGuiConfigFlags.NavEnableKeyboard; // Fixture input uses an explicit Control convention on every runner. io->ConfigMacOsxBehaviors = 0; io->Fonts->RendererHasTextures = 1; io->IniFilename = null; using (ui.Enter()) + { ui.widgets.SetupStyle(); + } return context; } @@ -288,10 +309,18 @@ private static void ValidateDrawData() ImDrawCmd command = list->CmdBuffer.Data[commandIndex]; ulong lastIndex = (ulong)command.IdxOffset + command.ElemCount; if (lastIndex > (ulong)list->IdxBuffer.Size) + { throw new InvalidOperationException("Native draw data exceeded its index buffer."); + } for (ulong index = command.IdxOffset; index < lastIndex; index++) + { if ((ulong)command.VtxOffset + list->IdxBuffer.Data[index] >= (ulong)list->VtxBuffer.Size) - throw new InvalidOperationException("Native draw data exceeded its vertex buffer after applying the command offset."); + { + throw new InvalidOperationException( + "Native draw data exceeded its vertex buffer after applying the command offset." + ); + } + } } } } @@ -303,8 +332,11 @@ internal sealed class InactivePlayMode : IEditorPlayMode public bool isPlaying => false; public string? lastFailure => null; public LogSessionId activeSessionId => LogSessionId.none; + public IDisposable ListenStateChanges(Action listener) => m_events.CreateHub(); + public bool EnterPlayMode() => false; + public bool ExitPlayMode() => false; } } diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs index db46f1b8f..c25303827 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs @@ -2,6 +2,7 @@ using System.Runtime.InteropServices; using Inno.Editor.Interactions; using Inno.Native.ImGui; + using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Testing.Editor.Native; @@ -57,16 +58,24 @@ public static void Key( ) { ImGuiIO* io = NativeImGui.Raw.GetIO(); if (shift) + { NativeImGui.Raw.AddKeyEvent(io, ImGuiKey.ImGuiModShift, 1); + } if (primary) + { NativeImGui.Raw.AddKeyEvent(io, ImGuiKey.ImGuiModCtrl, 1); + } NativeImGui.Raw.AddKeyEvent(io, key, 1); host.DrawPanel(panel); NativeImGui.Raw.AddKeyEvent(io, key, 0); if (shift) + { NativeImGui.Raw.AddKeyEvent(io, ImGuiKey.ImGuiModShift, 0); + } if (primary) + { NativeImGui.Raw.AddKeyEvent(io, ImGuiKey.ImGuiModCtrl, 0); + } host.DrawPanel(panel); } } diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs index ba4ecd953..c1aab50c1 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs @@ -1,26 +1,26 @@ using System; using System.IO; using System.Reflection; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Input; -using Inno.Core.IO; using Inno.Core.Logging; -using Inno.Core.Settings; using Inno.Core.Serialization; +using Inno.Core.Settings; using Inno.Editor.Core; using Inno.Editor.Diagnostics; -using Inno.Editor.ImGui; using Inno.Editor.Graph; +using Inno.Editor.ImGui; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; -using Xunit; namespace Inno.Testing.Editor.Native; @@ -64,7 +64,8 @@ public NativeProjectPanelHost( m_engine = new EngineHostBuilder().UseMetadataSources( new DotNetAssemblyCatalogSource(composition), new ReflectionTypeCatalogSource(), - new ReflectionSerializationMetadataSource()).Build(); + new ReflectionSerializationMetadataSource() + ).Build(); m_session = m_engine.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Edit, @@ -74,30 +75,62 @@ public NativeProjectPanelHost( }); m_execution = m_session.EnterExecutionScope(); var identities = new IdentityAllocator(); - assets = new AssetPipeline(m_engine.modules, m_engine.types, m_engine.serialization, identities, - m_engine.diagnostics, m_engine.logs, AssetPipelineOptions.Create(source, library) with { enableFileSystemWatcher = false }); - m_settings = new ProjectSettingsStore(settingsDocument ?? new FileByteDocumentStore(Path.Combine(m_root, "Settings.Project.inno")), - m_engine.types, m_engine.serialization, new ProjectId("tests.native-panels"), AssetSerializationContext.Create(assets)); + assets = new AssetPipeline( + m_engine.modules, + m_engine.types, + m_engine.serialization, + identities, + m_engine.diagnostics, + m_engine.logs, + AssetPipelineOptions.Create(source, library) with { enableFileSystemWatcher = false } + ); + m_settings = new ProjectSettingsStore( + settingsDocument ?? new FileByteDocumentStore(Path.Combine(m_root, "Settings.Project.inno")), + m_engine.types, + m_engine.serialization, + new ProjectId("tests.native-panels"), + AssetSerializationContext.Create(assets) + ); var pluginSources = new PluginSourceService(m_engine.serialization, pluginRoot, library); - m_plugins = new PluginEnvironment(assets, m_settings, m_engine.serialization, pluginRoot, library, pluginSources.Scan(), m_engine.modules.generations); + m_plugins = new PluginEnvironment( + assets, + m_settings, + m_engine.serialization, + pluginRoot, + library, + pluginSources.Scan(), + m_engine.modules.generations + ); m_console = new EditorConsole(m_engine.logs, m_engine.diagnostics, new NativePanelHost.InactivePlayMode()); m_console.Start(); var ui = new EditorUiSession(); reloads = new EditorReloadCoordinator(); SettingsPanelServices? settingsServices = includeSettings - ? new SettingsPanelServices(m_root, assets, m_plugins, m_settings, m_engine) - : null; + ? new SettingsPanelServices(m_root, assets, m_plugins, m_settings, m_engine) + : null; if (includeSettings) + { _ = Assembly.Load("Inno.Editor.Panel.Settings"); + } runtime = new EditorInteractionRuntime( new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), m_engine.types, m_engine.logs, [ - m_engine.types, m_engine.serialization, m_session, identities, m_session.identities, - assets, m_plugins, m_settings, reloads, ui, m_console, + m_engine.types, + m_engine.serialization, + m_session, + identities, + m_session.identities, + assets, + m_plugins, + m_settings, + reloads, + ui, + m_console, .. (settingsServices?.services ?? []) - ]); + ] + ); runtime.Start(); _ = runtime.panelCount; Assert.True(runtime.interactions.TryGetModule(out var probe)); @@ -111,38 +144,47 @@ public NativeProjectPanelHost( /// Gets the borrowed reload coordinator. /// public EditorReloadCoordinator reloads { get; } + /// /// Gets the borrowed project settings store. /// public ProjectSettingsStore projectSettings => m_settings; + /// /// Gets the borrowed authoring asset pipeline. /// public AssetPipeline assets { get; } + /// /// Gets the borrowed engine serialization registry. /// public SerializationRegistry serialization => m_engine.serialization; + /// /// Gets the absolute temporary project directory removed during disposal. /// public string projectRoot => m_root; + /// /// Gets the borrowed interaction runtime. /// public EditorInteractionRuntime runtime { get; } + /// /// Gets the borrowed scene workspace resolved through normal module composition. /// public IEditorSceneWorkspace workspace { get; } + /// /// Gets the borrowed graph editor module. /// public GraphEditorModule graphs { get; } + /// /// Gets the borrowed scene editing service. /// public SceneEdits edits { get; } + /// /// Gets the borrowed native panel host. /// @@ -153,6 +195,7 @@ public NativeProjectPanelHost( /// /// The scene owned by this fixture's session. public GameScene CreateScene() => m_session.scenes.LoadNewSceneAdditive(); + /// /// Rebuilds the actual type catalog after a declared discovery change. /// diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs index d502b116b..dd0d0e66e 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs @@ -1,7 +1,7 @@ using Inno.Editor.Core; +using Inno.Editor.Graph; using Inno.Editor.Interactions; using Inno.Editor.Scene; -using Inno.Editor.Graph; namespace Inno.Testing.Editor.Native; @@ -16,15 +16,18 @@ public sealed class NativeProjectPanelProbe( IEditorSceneWorkspace workspace, GraphEditorModule graphs, SceneEdits edits -) : EditorModule { +) : EditorModule +{ /// /// Gets the borrowed scene workspace. /// public IEditorSceneWorkspace workspace { get; } = workspace; + /// /// Gets the borrowed graph editor module. /// public GraphEditorModule graphs { get; } = graphs; + /// /// Gets the borrowed scene editing service. /// diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs index c7d1a8448..6cf1b3155 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs @@ -23,19 +23,32 @@ internal SettingsPanelServices( ProjectSettingsStore settings, EngineHost engine ) { - string host = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string host = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var compiler = new ScriptCompiler(new ScriptCompilerOptions { projectRootDirectory = root, compilationEnvironment = new SdkScriptCompilationEnvironment(host, root) }, assets, plugins); var target = new FixtureTarget(); - var pipeline = new BuildPipeline(assets, plugins, settings, engine.serialization, engine.modules.generations, - compiler, Path.Combine(root, "SupportPacks"), [new GameBuildTargetBinding(target, target)], - new ManagedDeploymentCatalog([new FixtureDeployment()])); - var build = new BuildSettingsStore(Path.Combine(root, "Settings.Build.inno"), engine.serialization, - BuildSettings.CreateDefault("Settings acceptance", string.Empty, target.id)); + var pipeline = new BuildPipeline( + assets, + plugins, + settings, + engine.serialization, + engine.modules.generations, + compiler, + Path.Combine(root, "SupportPacks"), + [new GameBuildTargetBinding(target, target)], + new ManagedDeploymentCatalog([new FixtureDeployment()]) + ); + var build = new BuildSettingsStore( + Path.Combine(root, "Settings.Build.inno"), + engine.serialization, + BuildSettings.CreateDefault("Settings acceptance", string.Empty, target.id) + ); services = [pipeline, build]; } @@ -48,11 +61,14 @@ private sealed class FixtureTarget : IGameBuildTarget, IGameContentCompiler public ManagedDeploymentId defaultManagedDeployment => new("tests-ui-managed"); public string runtimeIdentifier => "tests-ui-rid"; public string displayName => "Settings fixture"; + public void Validate(string directory) => throw new NotSupportedException("Settings acceptance does not package players."); + public ValueTask PackageAsync( GameBuildPackageContext context, CancellationToken cancellationToken = default ) => throw new NotSupportedException("Settings acceptance does not package players."); + public ValueTask CompileAsync( GameBuildContentContext context, CancellationToken cancellationToken = default @@ -63,6 +79,7 @@ private sealed class FixtureDeployment : IManagedDeploymentCompiler { public ManagedDeploymentId id => new("tests-ui-managed"); public ManagedDeploymentCapabilities capabilities => new(["tests-ui-rid"], true, false, false); + public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default diff --git a/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs b/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs index a7f77dc10..3517587b2 100644 --- a/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs +++ b/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs @@ -1,4 +1,3 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; @@ -6,17 +5,16 @@ using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; -using System.Runtime.Loader; using System.Runtime.InteropServices; +using System.Runtime.Loader; using System.Threading; using System.Threading.Tasks; -using Inno.Extensibility.Reload; - +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Extensibility.Modules.Tests; public sealed class ModuleHostTests : IDisposable @@ -91,10 +89,21 @@ private IDisposable CreateRetention(string kind) case "thread": var stop = new ManualResetEventSlim(); var started = new ManualResetEventSlim(); - var thread = new Thread(() => { started.Set(); stop.Wait(); GC.KeepAlive(type); }); + var thread = new Thread(() => + { + started.Set(); + stop.Wait(); + GC.KeepAlive(type); + }); thread.Start(); started.Wait(); - return new Retention(() => { stop.Set(); thread.Join(); stop.Dispose(); started.Dispose(); }); + return new Retention(() => + { + stop.Set(); + thread.Join(); + stop.Dispose(); + started.Dispose(); + }); case "handle": GCHandle handle = GCHandle.Alloc(type); return new Retention(handle.Free); @@ -109,8 +118,7 @@ private IDisposable CreateRetention(string kind) } } - private static unsafe void InvokeNativeCallback(IntPtr pointer) - => ((delegate* unmanaged[Cdecl])pointer)(); + private static unsafe void InvokeNativeCallback(IntPtr pointer) => ((delegate* unmanaged[Cdecl])pointer)(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void NativeCallback(); @@ -118,6 +126,7 @@ private static unsafe void InvokeNativeCallback(IntPtr pointer) private sealed class Retention(Action release) : IDisposable { private Action? m_release = release; + public void Dispose() => Interlocked.Exchange(ref m_release, null)?.Invoke(); } @@ -127,13 +136,17 @@ private sealed class Retention(Action release) : IDisposable private readonly string m_cacheDirectory = Path.Combine( Path.GetTempPath(), "InnoModuleHostTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; public ModuleHostTests() { - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleHostTests).Assembly)}); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleHostTests).Assembly)} + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); } @@ -143,7 +156,9 @@ public void Dispose() m_modules.Dispose(); ForceCollection(); if (Directory.Exists(m_cacheDirectory)) + { Directory.Delete(m_cacheDirectory, recursive: true); + } } [Fact] @@ -199,8 +214,7 @@ public void InvalidCandidateLeavesTheActiveGenerationUntouched() AssemblyModuleHandle handle = LoadVersion("V1"); Type previous = new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(m_types); - Assert.Throws( - () => m_modules.BeginReload(handle, CreateRequest("Invalid"))); + Assert.Throws(() => m_modules.BeginReload(handle, CreateRequest("Invalid"))); Assert.Same(previous, new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(m_types)); Assert.Equal(1, m_modules.modules.Single().generation); @@ -269,27 +283,21 @@ public void ExplicitPluginDependenciesUseSeparateContextsAndRemoveAtomically() _ = addition.Complete(); } - AssemblyModuleInfo consumerInfo = m_modules.modules.Single(module => - module.moduleName == consumer.moduleName); + AssemblyModuleInfo consumerInfo = m_modules.modules.Single(module => module.moduleName == consumer.moduleName); Assert.Equal([dependency.moduleName], consumerInfo.upstreamModuleNames); Type consumerType = new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(m_types); Assert.Equal(1, ReadVersion(consumerType)); - Assembly dependencyAssembly = AppDomain.CurrentDomain.GetAssemblies().Single(assembly => - string.Equals( - assembly.GetName().Name, - "Reloadable.PrivateDependency", - StringComparison.Ordinal) && - AssemblyLoadContext.GetLoadContext(assembly)?.IsCollectible == true); + Assembly dependencyAssembly = AppDomain.CurrentDomain.GetAssemblies().Single(assembly => ( + string.Equals(assembly.GetName().Name, "Reloadable.PrivateDependency", StringComparison.Ordinal) + && AssemblyLoadContext.GetLoadContext(assembly)?.IsCollectible == true + )); Assert.NotSame( AssemblyLoadContext.GetLoadContext(consumerType.Assembly), - AssemblyLoadContext.GetLoadContext(dependencyAssembly)); - - Assert.Throws(() => m_modules.BeginReload( - [], - [dependency.moduleName])); - using (AssemblyReloadSession removal = m_modules.BeginReload( - [], - [consumer.moduleName, dependency.moduleName])) + AssemblyLoadContext.GetLoadContext(dependencyAssembly) + ); + + Assert.Throws(() => m_modules.BeginReload([], [dependency.moduleName])); + using (AssemblyReloadSession removal = m_modules.BeginReload([], [consumer.moduleName, dependency.moduleName])) { removal.Activate(); _ = removal.Complete(); @@ -350,14 +358,17 @@ public void RolledBackCandidateRuntimeIdsAreNeverReused() int previousRuntimeId = m_types.GetTypeRef(previous).runtimeId; using (AssemblyReloadSession failed = m_modules.BeginReload(handle, CreateRequest("V2"))) + { Assert.Throws(failed.Activate); + } int rejectedRuntimeId = registry.lastBuiltRef.runtimeId; registry.failActivation = false; using AssemblyReloadSession accepted = m_modules.BeginReload(handle, CreateRequest("V2")); TypeCacheReloadContext context = accepted.context.GetContext(); TypeRef acceptedRef = context.candidate.GetTypeRef( - new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(context.candidate)); + new TypeRef(S_RELOADABLE_TYPE_ID).Resolve(context.candidate) + ); Assert.NotEqual(previousRuntimeId, rejectedRuntimeId); Assert.NotEqual(rejectedRuntimeId, acceptedRef.runtimeId); accepted.Activate(); @@ -397,7 +408,9 @@ public void RejectedCatalogRemainsReadableAndIgnoresNonParticipatingAssemblyLoad Assert.Throws(m_modules.Rebuild); Assert.Same(previous, m_types.current); _ = AssemblyBuilder.DefineDynamicAssembly( - new AssemblyName("Ignored.Dynamic." + Guid.NewGuid().ToString("N")), AssemblyBuilderAccess.RunAndCollect); + new AssemblyName("Ignored.Dynamic." + Guid.NewGuid().ToString("N")), + AssemblyBuilderAccess.RunAndCollect + ); m_modules.Refresh(); Assert.Same(previous, m_types.current); rejecting.throwOnActivate = false; @@ -423,7 +436,8 @@ public void RollbackCleanupFailureDoesNotSkipRemainingParticipants() using AssemblyReloadSession reload = m_modules.BeginReload( m_modules.modules.Single().handle, - CreateRequest("V2")); + CreateRequest("V2") + ); Assert.Throws(reload.Activate); activationFailure.throwOnActivate = false; throwing.throwOnRollback = false; @@ -437,9 +451,7 @@ public void RollbackCleanupFailureDoesNotSkipRemainingParticipants() [Fact] public void ExternalRegistrationIsNonOwningAndImmediatelyUnloadable() { - AssemblyModuleHandle handle = m_modules.Register( - "ExternalTests", - [typeof(ModuleHostTests).Assembly]); + AssemblyModuleHandle handle = m_modules.Register("ExternalTests", [typeof(ModuleHostTests).Assembly]); AssemblyModuleInfo info = Assert.Single(m_modules.modules); Assert.True(info.externallyOwned); @@ -466,34 +478,36 @@ private StrongTypeHolder CreateStrongTypeHolder() private static void ClearStrongTypeHolder(StrongTypeHolder holder) => holder.type = null; - private AssemblyModuleHandle LoadVersion(string version) - => m_modules.Load(CreateRequest(version)); + private AssemblyModuleHandle LoadVersion(string version) => m_modules.Load(CreateRequest(version)); [MethodImpl(MethodImplOptions.NoInlining)] private WeakReference CaptureRejectedCandidateContext(AssemblyModuleHandle handle) { WeakReference? candidateContext = null; - AssemblyLoadEventHandler capture = (_, args) => + AssemblyLoadEventHandler capture = ( + _, + args + ) => { AssemblyLoadContext? context = AssemblyLoadContext.GetLoadContext(args.LoadedAssembly); - if (context is { IsCollectible: true } && - context.Name?.StartsWith("ReloadableTests#2", StringComparison.Ordinal) == true) - { + if (context is { IsCollectible: true } + && context.Name?.StartsWith("ReloadableTests#2", StringComparison.Ordinal) == true + ) { candidateContext = new WeakReference(context); } }; AppDomain.CurrentDomain.AssemblyLoad += capture; try { - Assert.Throws( - () => m_modules.BeginReload(handle, CreateRequest("Invalid"))); + Assert.Throws(() => m_modules.BeginReload(handle, CreateRequest("Invalid"))); } finally { AppDomain.CurrentDomain.AssemblyLoad -= capture; } return candidateContext ?? throw new InvalidOperationException( - "The rejected candidate load context was not observed."); + "The rejected candidate load context was not observed." + ); } private DotNetModuleSource CreateRequest(string version) @@ -534,21 +548,29 @@ private sealed class ReloadableTypeRegistry(TypeCatalog types) : TypeRegistry - string.Equals( - type.Resolve(types).FullName, - "Inno.Extensibility.Modules.TestModule.ReloadableExtension", - StringComparison.Ordinal)) + TypeRef[] matches = types.types + .Where(type => + string.Equals( + type.Resolve(types).FullName, + "Inno.Extensibility.Modules.TestModule.ReloadableExtension", + StringComparison.Ordinal + )) .ToArray(); if (matches.Length == 1) + { lastBuiltRef = matches[0]; + } return matches.Select(type => type.Resolve(types)).ToArray(); } - protected override void OnActivating(Type[]? previous, Type[] candidate) - { + protected override void OnActivating( + Type[]? previous, + Type[] candidate + ) { if (failActivation) + { throw new InvalidOperationException("Injected assembly registry activation failure."); + } } } @@ -565,8 +587,7 @@ private sealed class CatalogParticipantProbe : IAssemblyCatalogParticipant internal int completeCount; internal int rollbackCount; - public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) - => new Transaction(this); + public IAssemblyCatalogTransaction Prepare(AssemblyCatalogSnapshot catalog) => new Transaction(this); internal void Reset() { @@ -581,21 +602,27 @@ private sealed class Transaction(CatalogParticipantProbe owner) : IAssemblyCatal public void Activate() { if (owner.throwOnActivate) + { throw new InvalidOperationException("Injected participant activation failure."); + } } public void Complete() { owner.completeCount++; if (owner.throwOnComplete) + { throw new InvalidOperationException("Injected participant completion failure."); + } } public void Rollback() { owner.rollbackCount++; if (owner.throwOnRollback) + { throw new InvalidOperationException("Injected participant rollback failure."); + } } } } diff --git a/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs b/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs index 5a973a546..9ecdff78f 100644 --- a/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs +++ b/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs @@ -3,10 +3,10 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Loader; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Inno.Adapter.Modules.DotNet; -using Xunit; namespace Inno.Extensibility.Modules.Tests; @@ -31,7 +31,9 @@ public void IsolatedHostDiscoversItsOwnTypesAndReleasesItsContext() finally { if (Directory.Exists(cache)) + { Directory.Delete(cache, recursive: true); + } } } @@ -73,7 +75,9 @@ private sealed class IsolatedHostContext() : AssemblyLoadContext("Inno isolated protected override Assembly? Load(AssemblyName assemblyName) { if (!(assemblyName.Name ?? string.Empty).StartsWith("Inno.", StringComparison.Ordinal)) + { return null; + } string path = Path.Combine(AppContext.BaseDirectory, assemblyName.Name + ".dll"); return File.Exists(path) ? LoadFromAssemblyPath(path) : null; } diff --git a/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs b/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs index bd16f8c69..cb294facf 100644 --- a/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs +++ b/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs @@ -1,16 +1,14 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.IO; using System.Linq; using System.Runtime.Loader; - +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Core.Execution; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Extensibility.Modules.Tests; public sealed class ModuleRetirementTests @@ -22,7 +20,9 @@ public sealed class ModuleRetirementTests public void PendingParticipantDoesNotBeginUnloadingEitherLiveGeneration(string phase) { string cache = Path.Combine(Path.GetTempPath(), "InnoModuleRetirement", Guid.NewGuid().ToString("N")); - var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)}); + var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)} + ); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); AssemblyModuleHandle handle = modules.Load(Request("V1", cache)); var participant = new Participant(); @@ -36,14 +36,20 @@ public void PendingParticipantDoesNotBeginUnloadingEitherLiveGeneration(string p candidate.Unloading += _ => unloads++; if (phase == "activate") + { Assert.Throws(reload.Activate); + } else { reload.Activate(); if (phase == "complete") + { Assert.Throws(() => reload.Complete()); + } else + { Assert.Throws(reload.Rollback); + } } Assert.Equal(GenerationState.Faulted, modules.generations.state); @@ -65,28 +71,43 @@ public void PendingParticipantDoesNotBeginUnloadingEitherLiveGeneration(string p public void WrappedPendingKeepsBothCollectibleContextsAndPreservesTheOriginalFailure(string phase) { string cache = Path.Combine(Path.GetTempPath(), "InnoWrappedRetirement", Guid.NewGuid().ToString("N")); - var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)}); + var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)} + ); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); AssemblyModuleHandle handle = modules.Load(Request("V1", cache)); var participant = new Participant(); using IDisposable registration = modules.RegisterCatalogParticipant(participant); participant.phase = phase; - participant.failure = new AggregateException(new InvalidOperationException("completed sibling"), - new InvalidOperationException("native owner", new RetirementTimeoutException("callback still active"))); + participant.failure = new AggregateException( + new InvalidOperationException("completed sibling"), + new InvalidOperationException("native owner", new RetirementTimeoutException("callback still active")) + ); var reload = modules.BeginReload(handle, Request("V2", cache)); int unloads = 0; Context(reload.context.previousCatalog).Unloading += _ => unloads++; Context(reload.context.candidateCatalog).Unloading += _ => unloads++; if (phase == "activate") + { Assert.Same(participant.failure, Assert.Throws(reload.Activate)); + } else { reload.Activate(); - Assert.Same(participant.failure, Assert.Throws(() => - { - if (phase == "complete") _ = reload.Complete(); - else reload.Rollback(); - })); + Assert.Same( + participant.failure, + Assert.Throws(() => + { + if (phase == "complete") + { + _ = reload.Complete(); + } + else + { + reload.Rollback(); + } + }) + ); } Assert.Equal(GenerationState.Faulted, modules.generations.state); Assert.Same(participant.failure, Assert.Throws(reload.Dispose)); @@ -103,7 +124,9 @@ public void WrappedPendingKeepsBothCollectibleContextsAndPreservesTheOriginalFai public void CatalogParticipantErrorsBeforePendingDoNotDisappearOrUnloadEitherContext(string phase) { string cache = Path.Combine(Path.GetTempPath(), "InnoCatalogRetirement", Guid.NewGuid().ToString("N")); - var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)}); + var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)} + ); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); AssemblyModuleHandle handle = modules.Load(Request("V1", cache)); var ordinary = new Participant { failure = new InvalidOperationException("earlier catalog cleanup") }; @@ -119,8 +142,14 @@ public void CatalogParticipantErrorsBeforePendingDoNotDisappearOrUnloadEitherCon reload.Activate(); AggregateException failure = Assert.Throws(() => { - if (phase == "complete") _ = reload.Complete(); - else reload.Rollback(); + if (phase == "complete") + { + _ = reload.Complete(); + } + else + { + reload.Rollback(); + } }); Assert.Contains(ordinary.failure, failure.Flatten().InnerExceptions); Assert.Same(pending.failure, RetirementPendingException.Find(failure)); @@ -135,7 +164,9 @@ public void CatalogParticipantErrorsBeforePendingDoNotDisappearOrUnloadEitherCon public void RejectedCatalogActivationRemainsVisibleWhenItsRollbackIsPending() { string cache = Path.Combine(Path.GetTempPath(), "InnoRejectedRetirement", Guid.NewGuid().ToString("N")); - var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)}); + var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ModuleRetirementTests).Assembly)} + ); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); AssemblyModuleHandle handle = modules.Load(Request("V1", cache)); var participant = new Participant(); @@ -158,8 +189,7 @@ public void RejectedCatalogActivationRemainsVisibleWhenItsRollbackIsPending() private static DotNetModuleSource Request( string variant, string artifactRootDirectory - ) - { + ) { string directory = Path.Combine(AppContext.BaseDirectory, "Modules", variant); return new DotNetModuleSource { @@ -173,8 +203,9 @@ string artifactRootDirectory } private static AssemblyLoadContext Context(AssemblyCatalogSnapshot catalog) - => AssemblyLoadContext.GetLoadContext(catalog.assemblies.Single(assembly => - assembly.GetName().Name == "Inno.Extensibility.Modules.TestModule"))!; + => AssemblyLoadContext.GetLoadContext( + catalog.assemblies.Single(assembly => (assembly.GetName().Name == "Inno.Extensibility.Modules.TestModule")) + )!; private sealed class Participant : IAssemblyCatalogParticipant { @@ -197,9 +228,13 @@ private sealed class Transaction(Participant owner) : IAssemblyCatalogTransactio private void ThrowIfPending(string phase) { if (phase == "activate" && owner.activationFailure is not null) + { throw owner.activationFailure; + } if (owner.phase == phase) + { throw owner.failure; + } } } } diff --git a/tests/extensibility/Inno.Extensibility.Reload.Tests/AssemblyUnloadBarrierTests.cs b/tests/extensibility/Inno.Extensibility.Reload.Tests/AssemblyUnloadBarrierTests.cs index aeebd93f3..7058f413b 100644 --- a/tests/extensibility/Inno.Extensibility.Reload.Tests/AssemblyUnloadBarrierTests.cs +++ b/tests/extensibility/Inno.Extensibility.Reload.Tests/AssemblyUnloadBarrierTests.cs @@ -1,7 +1,7 @@ using System; using System.Threading; -using Inno.Extensibility.Reload; using Xunit; +using Inno.Extensibility.Reload; namespace Inno.Extensibility.Reload.Tests; @@ -18,7 +18,8 @@ public void Advance_CompletesOnlyAfterEveryProbeCompletes() { collectionInterval = TimeSpan.Zero, retentionTimeout = TimeSpan.FromSeconds(2) - }); + } + ); first.isCompleted = true; Assert.False(barrier.Advance()); @@ -39,7 +40,8 @@ public void Advance_RetainsFaultAndRejectsEveryLaterSuccessAttempt() { collectionInterval = TimeSpan.Zero, retentionTimeout = TimeSpan.FromMilliseconds(20) - }); + } + ); Thread.Sleep(30); AssemblyUnloadException first = Assert.Throws(() => barrier.Advance()); diff --git a/tests/extensibility/Inno.Extensibility.Reload.Tests/GenerationCoordinatorTests.cs b/tests/extensibility/Inno.Extensibility.Reload.Tests/GenerationCoordinatorTests.cs index 4da0d2efa..dcd8bb9c7 100644 --- a/tests/extensibility/Inno.Extensibility.Reload.Tests/GenerationCoordinatorTests.cs +++ b/tests/extensibility/Inno.Extensibility.Reload.Tests/GenerationCoordinatorTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Threading; +using Xunit; using Inno.Core.Execution; using Inno.Extensibility.Reload; -using Xunit; namespace Inno.Extensibility.Reload.Tests; @@ -30,9 +30,11 @@ public void FailedApplyRollsBackStructureBeforePublicationAndThenRestoresValues( { var owner = new GenerationCoordinator(); var events = new List(); - Assert.Throws(() => owner.Execute("reload", + Assert.Throws(() => owner.Execute( + "reload", new Publication(new Probe { isCompleted = true }, events), - [new Change("first", events), new Change("second", events, failApply: true)])); + [new Change("first", events), new Change("second", events, failApply: true)] + )); Assert.Equal(["prepare:first", "prepare:second", "activate", "apply:first", "apply:second", "structure:second", "structure:first", "rollback", "restore:second", "restore:first"], events); Assert.Equal(GenerationState.Ready, owner.state); @@ -43,9 +45,11 @@ public void IrreversibleCleanupFailureFaultsOwnerAndStillAttemptsAllCleanup() { var owner = new GenerationCoordinator(); var events = new List(); - Assert.Throws(() => owner.Execute("reload", + Assert.Throws(() => owner.Execute( + "reload", new Publication(new Probe { isCompleted = true }, events), - [new Change("first", events, failComplete: true), new Change("second", events)])); + [new Change("first", events, failComplete: true), new Change("second", events)] + )); Assert.Contains("complete:second", events); Assert.DoesNotContain("rollback", events); Assert.Equal(GenerationState.Faulted, owner.state); @@ -68,9 +72,11 @@ public void RollbackFailureIsTerminalEvenWhenNoCollectibleMonitorExists() { var owner = new GenerationCoordinator(); var events = new List(); - Assert.Throws(() => owner.Execute("reload", + Assert.Throws(() => owner.Execute( + "reload", new Publication(new Probe { isCompleted = true }, events), - [new Change("scene", events, failApply: true, failRestore: true)])); + [new Change("scene", events, failApply: true, failRestore: true)] + )); Assert.Equal(GenerationState.Faulted, owner.state); Assert.Throws(() => owner.Advance()); } @@ -104,13 +110,23 @@ public void PendingRetirementNeverFallsThroughToLowerCleanupOrReopensAdmission(s var events = new List(); var failure = new RetirementTimeoutException("Pending generation-owned work exceeded its deadline."); var change = new PendingChange(phase, events, failure); - Exception reported = Assert.ThrowsAny(() => owner.Execute("reload", - new Publication(new Probe { isCompleted = true }, events), [change])); + Exception reported = Assert.ThrowsAny(() => owner.Execute( + "reload", + new Publication(new Probe { isCompleted = true }, events), + [change] + )); Assert.Same(failure, RetirementPendingException.Find(reported)); if (phase == "rollback") - Assert.Contains(Assert.IsType(reported).InnerExceptions, - item => item.Message == "Candidate publication failed."); - else Assert.Same(failure, reported); + { + Assert.Contains( + Assert.IsType(reported).InnerExceptions, + item => item.Message == "Candidate publication failed." + ); + } + else + { + Assert.Same(failure, reported); + } Assert.DoesNotContain("rollback", events); Assert.DoesNotContain("restore", events); Assert.Equal(GenerationState.Faulted, owner.state); @@ -140,7 +156,9 @@ public void PublicationMayBorrowAnOperationOnlyOnItsOwnControlThread() var owner = new GenerationCoordinator(); Assert.True(owner.TryAcquireChange("refresh", out IDisposable? publication)); using (owner.AcquireOperation("validate candidate")) + { Assert.Throws(() => owner.AcquireRead("Build")); + } Assert.Equal(GenerationState.Transitioning, owner.state); Exception? failure = null; var thread = new Thread(() => @@ -185,8 +203,11 @@ public void ExecuteBorrowsOperationAdmissionWithoutReopeningItBetweenDomainPhase { var owner = new GenerationCoordinator(); var events = new List(); - owner.Execute("reload", new Publication(new Probe { isCompleted = true }, events), - [new OperationChange(owner, events)]); + owner.Execute( + "reload", + new Publication(new Probe { isCompleted = true }, events), + [new OperationChange(owner, events)] + ); Assert.Equal(["prepare", "activate", "apply", "commit", "complete"], events); owner.EnsureReady("Play"); owner.Fault(new InvalidOperationException("Terminal cleanup failure.")); @@ -217,17 +238,25 @@ public void WrappedPendingRetainsTheTransactionWithoutContinuingDependentPhases( var owner = new GenerationCoordinator(); var events = new List(); var pending = new RetirementTimeoutException("unfinished native callback"); - var failure = new AggregateException(new InvalidOperationException("completed sibling"), - new InvalidOperationException("scope context", pending)); + var failure = new AggregateException( + new InvalidOperationException("completed sibling"), + new InvalidOperationException("scope context", pending) + ); var change = new WrappedChange(phase, failure, events); - AggregateException reported = Assert.Throws(() => owner.Execute("reload", - new Publication(new Probe { isCompleted = true }, events), [change])); + AggregateException reported = Assert.Throws(() => owner.Execute( + "reload", + new Publication(new Probe { isCompleted = true }, events), + [change] + )); if (phase is "rollback" or "restore") { Assert.Contains(failure, reported.InnerExceptions); Assert.Contains(reported.InnerExceptions, item => item.Message == "activation rejected"); } - else Assert.Same(failure, reported); + else + { + Assert.Same(failure, reported); + } Assert.Equal(GenerationState.Faulted, owner.state); Assert.Same(reported, owner.failure); Assert.Same(pending, Assert.Throws(owner.EnsureRetirementSafe)); @@ -241,10 +270,15 @@ public void CleanupFailureBeforeAPendingParticipantRemainsInTheTerminalReport() var owner = new GenerationCoordinator(); var events = new List(); var pending = new RetirementPendingException("unfinished callback"); - AggregateException failure = Assert.Throws(() => owner.Execute("reload", + AggregateException failure = Assert.Throws(() => owner.Execute( + "reload", new Publication(new Probe { isCompleted = true }, events), - [new Change("ordinary", events, failComplete: true), new WrappedChange("complete", pending, events), - new Change("dependency", events)])); + [ + new Change("ordinary", events, failComplete: true), + new WrappedChange("complete", pending, events), + new Change("dependency", events) + ] + )); Assert.Same(failure, owner.failure); Assert.Contains(failure.InnerExceptions, item => item.Message == "complete"); Assert.Contains(pending, failure.InnerExceptions); @@ -252,20 +286,27 @@ public void CleanupFailureBeforeAPendingParticipantRemainsInTheTerminalReport() Assert.Same(pending, Assert.Throws(owner.EnsureRetirementSafe)); } - private sealed class PendingChange(string phase, List events, RetirementTimeoutException failure) - : IGenerationChange + private sealed class PendingChange( + string phase, + List events, + RetirementTimeoutException failure + ) : IGenerationChange { public void PrepareForActivation() { events.Add("prepare"); if (phase == "prepare") + { throw failure; + } } public void Apply() { if (phase == "rollback") + { throw new InvalidOperationException("Candidate publication failed."); + } } public void Complete() => throw failure; @@ -275,17 +316,26 @@ public void Apply() public void RestorePreviousState() => events.Add("restore"); } - private sealed class WrappedChange(string phase, Exception failure, List events) : IGenerationChange + private sealed class WrappedChange( + string phase, + Exception failure, + List events + ) : IGenerationChange { public void PrepareForActivation() => Visit("prepare"); + public void Apply() { Visit("apply"); if (phase is "rollback" or "restore") throw new InvalidOperationException("activation rejected"); } + public void Complete() => Visit("complete"); + public void RollbackStructure() => Visit("rollback"); + public void RestorePreviousState() => Visit("restore"); + private void Visit(string current) { events.Add(current); @@ -299,12 +349,19 @@ private sealed class Probe : IAssemblyUnloadProbe public bool isCompleted { get; set; } } - private sealed class OperationChange(GenerationCoordinator owner, List events) : IGenerationChange + private sealed class OperationChange( + GenerationCoordinator owner, + List events + ) : IGenerationChange { public void PrepareForActivation() => Visit("prepare"); + public void Apply() => Visit("apply"); + public void Complete() => Visit("complete"); + public void RollbackStructure() => Visit("rollback"); + public void RestorePreviousState() => Visit("restore"); private void Visit(string phase) @@ -316,20 +373,50 @@ private void Visit(string phase) } } - private sealed class Publication(Probe probe, List events) : IGenerationPublication + private sealed class Publication( + Probe probe, + List events + ) : IGenerationPublication { public void Activate() => events.Add("activate"); + public void Rollback() => events.Add("rollback"); - public Probe Complete() { events.Add("commit"); return probe; } + + public Probe Complete() + { + events.Add("commit"); + return probe; + } } - private sealed class Change(string name, List events, - bool failApply = false, bool failComplete = false, bool failRestore = false) : IGenerationChange + private sealed class Change( + string name, + List events, + bool failApply = false, + bool failComplete = false, + bool failRestore = false + ) : IGenerationChange { public void PrepareForActivation() => events.Add($"prepare:{name}"); - public void Apply() { events.Add($"apply:{name}"); if (failApply) throw new InvalidOperationException("apply"); } - public void Complete() { events.Add($"complete:{name}"); if (failComplete) throw new InvalidOperationException("complete"); } + + public void Apply() + { + events.Add($"apply:{name}"); + if (failApply) throw new InvalidOperationException("apply"); + } + + public void Complete() + { + events.Add($"complete:{name}"); + if (failComplete) throw new InvalidOperationException("complete"); + } + public void RollbackStructure() => events.Add($"structure:{name}"); - public void RestorePreviousState() { events.Add($"restore:{name}"); if (failRestore) throw new InvalidOperationException("restore"); } + + public void RestorePreviousState() + { + events.Add($"restore:{name}"); + if (failRestore) throw new InvalidOperationException("restore"); + } } } diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs index ea262d678..7f0a554a6 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs @@ -1,12 +1,10 @@ using System; using System.Reflection; using System.Reflection.Emit; - +using Xunit; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Extensibility.Types.Tests; public sealed class AssemblyExtensionsTests @@ -27,20 +25,22 @@ public void MissingClassificationIsRejected() Assert.Throws(() => asm.GetInnoAssemblyScope()); } - private static Assembly BuildDynamicAssembly(string? domainName, string? scopeName) - { + private static Assembly BuildDynamicAssembly( + string? domainName, + string? scopeName + ) { var asmName = new AssemblyName("Inno.Dynamic." + Guid.NewGuid().ToString("N")); var asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); if (domainName is not null && scopeName is not null) { var ctor = typeof(AssemblyMetadataAttribute).GetConstructor(new[] { typeof(string), typeof(string) })!; - asmBuilder.SetCustomAttribute(new CustomAttributeBuilder( - ctor, - new object[] { "Inno.AssemblyDomain", domainName })); - asmBuilder.SetCustomAttribute(new CustomAttributeBuilder( - ctor, - new object[] { "Inno.AssemblyScope", scopeName })); + asmBuilder.SetCustomAttribute( + new CustomAttributeBuilder(ctor, new object[] { "Inno.AssemblyDomain", domainName }) + ); + asmBuilder.SetCustomAttribute( + new CustomAttributeBuilder(ctor, new object[] { "Inno.AssemblyScope", scopeName }) + ); } var module = asmBuilder.DefineDynamicModule("main"); diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyInfo.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyInfo.cs index 90530011e..b40fa5b7b 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyInfo.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyInfo.cs @@ -2,8 +2,10 @@ [assembly: AssemblyMetadata( "Inno.StableTypeId", - "44444444-4444-4444-4444-444444444444|Inno.Extensibility.Types.Tests.GeneratedMappedType")] + "44444444-4444-4444-4444-444444444444|Inno.Extensibility.Types.Tests.GeneratedMappedType" +)] [assembly: AssemblyMetadata( "Inno.StableTypeId", - "66666666-6666-6666-6666-666666666666|Inno.Extensibility.Types.Tests.StableAnnotatedTypeA")] + "66666666-6666-6666-6666-666666666666|Inno.Extensibility.Types.Tests.StableAnnotatedTypeA" +)] diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/RegistryRetirementTests.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/RegistryRetirementTests.cs index 4cf4a7427..bdda221fe 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/RegistryRetirementTests.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/RegistryRetirementTests.cs @@ -1,15 +1,13 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; - +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Core.Execution; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Extensibility.Types.Tests; [Collection(TypeCacheCollection.NAME)] @@ -19,7 +17,9 @@ public sealed class RegistryRetirementTests public void PendingBatchDoesNotRepeatCompletedResourcesOrReleaseLowerDependenciesEarly() { string cache = Path.Combine(Path.GetTempPath(), "InnoRegistryRetirement", Guid.NewGuid().ToString("N")); - using var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(RegistryRetirementTests).Assembly)}); + using var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(RegistryRetirementTests).Assembly)} + ); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); var calls = new List(); int pendingAttempts = 0; @@ -28,7 +28,9 @@ public void PendingBatchDoesNotRepeatCompletedResourcesOrReleaseLowerDependencie { calls.Add("second"); if (++pendingAttempts < 3) + { throw new RetirementPendingException("Pending registry resource."); + } }); var third = new Resource(() => { @@ -52,7 +54,9 @@ public void PendingBatchDoesNotRepeatCompletedResourcesOrReleaseLowerDependencie public void DeadlineFailureRetainsDependenciesAndPermanentlyRejectsFurtherRetirement(bool clear) { string cache = Path.Combine(Path.GetTempPath(), "InnoRegistryRetirement", Guid.NewGuid().ToString("N")); - var modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(RegistryRetirementTests).Assembly)}); + var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(RegistryRetirementTests).Assembly)} + ); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); int released = 0; int attempts = 0; @@ -81,8 +85,11 @@ public void DeadlineFailureRetainsDependenciesAndPermanentlyRejectsFurtherRetire Assert.Throws(modules.Dispose); } - private sealed class Registry(TypeCatalog types, Func factory, TimeSpan? timeout = null) - : TypeRegistry(types, timeout) + private sealed class Registry( + TypeCatalog types, + Func factory, + TimeSpan? timeout = null + ) : TypeRegistry(types, timeout) { protected override object[] Build(TypeCacheSnapshot types) => factory(); diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs index 0f7e4abb1..55e020382 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs @@ -1,16 +1,14 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Reflection; - using ExternalNamespace; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; -using Xunit; - namespace Inno.Extensibility.Types.Tests; [Collection(TypeCacheCollection.NAME)] @@ -19,13 +17,17 @@ public sealed class TypeCacheTests : IDisposable private readonly string m_cacheDirectory = Path.Combine( Path.GetTempPath(), "InnoTypeCacheTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; public TypeCacheTests() { - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(TypeCacheTests).Assembly)}); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(TypeCacheTests).Assembly)} + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); } @@ -34,7 +36,9 @@ public void Dispose() m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_cacheDirectory)) + { Directory.Delete(m_cacheDirectory, recursive: true); + } } [Fact] @@ -61,7 +65,10 @@ public void CandidateRollbackCleanupFailureFaultsGateAfterEveryResourceIsAttempt Assert.Equal(new[] { 4, 3 }, registry.released); Assert.Equal(GenerationState.Faulted, m_modules.generations.state); } - finally { registry.failCleanup = false; } + finally + { + registry.failCleanup = false; + } } private sealed class CandidateOwnershipRegistry(TypeCatalog types) : TypeRegistry(types) @@ -76,19 +83,26 @@ protected override object[] Build(TypeCacheSnapshot types) var first = OwnCandidateExtension(new Resource(this, ++m_nextId)); var second = OwnCandidateExtension(new Resource(this, ++m_nextId)); if (failBuild) + { throw new InvalidOperationException("Expected candidate validation failure."); + } return [first, second, first]; } protected override void DisposeSnapshot(object[] snapshot) => DisposeExtensions(snapshot); - private sealed class Resource(CandidateOwnershipRegistry owner, int id) : IDisposable + private sealed class Resource( + CandidateOwnershipRegistry owner, + int id + ) : IDisposable { public void Dispose() { owner.released.Add(id); if (owner.failCleanup) + { throw new InvalidOperationException("Expected extension cleanup failure."); + } } } } @@ -97,21 +111,20 @@ public void Dispose() public void QueriesReturnOnlyConcreteMatchingTypes() { Assert.Contains(m_types.GetTypeRef(typeof(TestDerived)), m_types.GetSubTypesOf()); - Assert.DoesNotContain( - m_types.GetTypeRef(typeof(TestAbstractDerived)), - m_types.GetSubTypesOf()); - Assert.Contains( - m_types.GetTypeRef(typeof(TestContractImpl)), - m_types.GetTypesImplementing()); + Assert.DoesNotContain(m_types.GetTypeRef(typeof(TestAbstractDerived)), m_types.GetSubTypesOf()); + Assert.Contains(m_types.GetTypeRef(typeof(TestContractImpl)), m_types.GetTypesImplementing()); Assert.DoesNotContain( m_types.GetTypeRef(typeof(TestAbstractContractImpl)), - m_types.GetTypesImplementing()); + m_types.GetTypesImplementing() + ); Assert.Contains( m_types.GetTypeRef(typeof(AttributedType)), - m_types.GetTypesWithAttribute()); + m_types.GetTypesWithAttribute() + ); Assert.DoesNotContain( m_types.GetTypeRef(typeof(AbstractAttributedType)), - m_types.GetTypesWithAttribute()); + m_types.GetTypesWithAttribute() + ); } [Fact] @@ -134,10 +147,12 @@ public void ExplicitAndGeneratedStableIdentitiesAreCanonical() { Assert.Equal( Guid.Parse("11111111-1111-1111-1111-111111111111"), - m_types.GetTypeRef(typeof(StableAnnotatedTypeA)).stableId); + m_types.GetTypeRef(typeof(StableAnnotatedTypeA)).stableId + ); Assert.Equal( Guid.Parse("44444444-4444-4444-4444-444444444444"), - m_types.GetTypeRef(typeof(GeneratedMappedType)).stableId); + m_types.GetTypeRef(typeof(GeneratedMappedType)).stableId + ); Guid first = m_types.GetTypeRef(typeof(DeterministicStableType)).stableId; m_types.Rebuild(); @@ -150,7 +165,8 @@ public void DiscoveryIncludesTypesOutsideInnoNamespace() Assert.True(m_types.GetTypeRef(typeof(OutsideNamespaceType)).runtimeId > 0); Assert.Equal( Guid.Parse("33333333-3333-3333-3333-333333333333"), - m_types.GetTypeRef(typeof(OutsideStableAnnotatedType)).stableId); + m_types.GetTypeRef(typeof(OutsideStableAnnotatedType)).stableId + ); } [Fact] @@ -159,7 +175,8 @@ public void NewlyLoadedHostAssemblyAppearsAfterCatalogRefresh() Assembly assembly = Assembly.Load("Inno.Extensibility.Types.TestAssemblyA"); Type marked = assembly.GetType( "Inno.Extensibility.Types.TestAssets.A.AssemblyAMarkedType", - throwOnError: true)!; + throwOnError: true + )!; m_types.Rebuild(); @@ -246,8 +263,7 @@ public void DisposedCatalogRejectsQueriesWithoutAStaticFallback() Assert.Throws(() => m_types.GetSubTypesOf()); } - private sealed class TransactionalTestRegistry(TypeCatalog types) - : TypeRegistry(types) + private sealed class TransactionalTestRegistry(TypeCatalog types) : TypeRegistry(types) { private int m_nextSnapshotId; @@ -261,17 +277,23 @@ private sealed class TransactionalTestRegistry(TypeCatalog types) protected override Snapshot Build(TypeCacheSnapshot types) => new(++m_nextSnapshotId); - protected override void OnActivating(Snapshot? previous, Snapshot candidate) - { + protected override void OnActivating( + Snapshot? previous, + Snapshot candidate + ) { snapshotId = candidate.id; disposeOnActivation?.Dispose(); disposeOnActivation = null; if (failActivation) + { throw new InvalidOperationException("Injected registry activation failure."); + } } - protected override void OnActivationRolledBack(Snapshot? previous, Snapshot candidate) - { + protected override void OnActivationRolledBack( + Snapshot? previous, + Snapshot candidate + ) { snapshotId = previous?.id ?? 0; rollbackCount++; } @@ -280,22 +302,30 @@ protected override void DisposeSnapshot(Snapshot snapshot) { disposedSnapshotIds.Add(snapshot.id); if (failSnapshotCleanup) + { throw new InvalidOperationException("Injected snapshot cleanup failure."); + } } - protected override void OnCleanupFailed(string phase, Exception exception) - => cleanupFailureCount++; + protected override void OnCleanupFailed( + string phase, + Exception exception + ) => cleanupFailureCount++; internal sealed record Snapshot(int id); } } public class TestBase; + public sealed class TestDerived : TestBase; + public abstract class TestAbstractDerived : TestBase; public interface ITestContract; + public sealed class TestContractImpl : ITestContract; + public abstract class TestAbstractContractImpl : ITestContract; [AttributeUsage(AttributeTargets.Class)] @@ -314,4 +344,5 @@ public sealed class StableAnnotatedTypeA; public struct StableAnnotatedTypeB; public sealed class DeterministicStableType; + public sealed class GeneratedMappedType; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V1/ReloadableExtension.cs b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V1/ReloadableExtension.cs index 991d65ac4..9fb1723ac 100644 --- a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V1/ReloadableExtension.cs +++ b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V1/ReloadableExtension.cs @@ -1,5 +1,5 @@ -using Inno.Extensibility.Types; using Reloadable.PrivateDependency; +using Inno.Extensibility.Types; namespace Inno.Extensibility.Modules.TestModule; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V2/ReloadableExtension.cs b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V2/ReloadableExtension.cs index f10bc8123..ad7db46f7 100644 --- a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V2/ReloadableExtension.cs +++ b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.V2/ReloadableExtension.cs @@ -1,5 +1,5 @@ -using Inno.Extensibility.Types; using Reloadable.PrivateDependency; +using Inno.Extensibility.Types; namespace Inno.Extensibility.Modules.TestModule; diff --git a/tests/fixtures/editor-ui/ManagedMemorySample.editor.cs b/tests/fixtures/editor-ui/ManagedMemorySample.editor.cs index 3d9536665..1bd69b58e 100644 --- a/tests/fixtures/editor-ui/ManagedMemorySample.editor.cs +++ b/tests/fixtures/editor-ui/ManagedMemorySample.editor.cs @@ -19,13 +19,22 @@ internal static ManagedMemorySample Capture() GC.WaitForPendingFinalizers(); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); GCMemoryInfo memory = GC.GetGCMemoryInfo(GCKind.FullBlocking); - if (memory.Index <= previousIndex || memory.Generation != GC.MaxGeneration || memory.Concurrent || !memory.Compacted || - memory.FragmentedBytes < 0 || memory.HeapSizeBytes < memory.FragmentedBytes) + if (memory.Index <= previousIndex || memory.Generation != GC.MaxGeneration || memory.Concurrent || !memory.Compacted + || memory.FragmentedBytes < 0 || memory.HeapSizeBytes < memory.FragmentedBytes + ) { throw new InvalidOperationException("The lifecycle sample requires a fresh compacting full-GC snapshot."); + } // Keep the approximate API as diagnostic data; pinned fragmentation can make it negative. return new ManagedMemorySample( - checked(memory.HeapSizeBytes - memory.FragmentedBytes), GC.GetTotalMemory(forceFullCollection: false), - memory.HeapSizeBytes, memory.FragmentedBytes, memory.Index, memory.Generation, memory.Compacted, memory.Concurrent); + checked(memory.HeapSizeBytes - memory.FragmentedBytes), + GC.GetTotalMemory(forceFullCollection: false), + memory.HeapSizeBytes, + memory.FragmentedBytes, + memory.Index, + memory.Generation, + memory.Compacted, + memory.Concurrent + ); } } diff --git a/tests/fixtures/editor-ui/PanelLifecycle.editor.cs b/tests/fixtures/editor-ui/PanelLifecycle.editor.cs index 432a8e41d..688a4abd3 100644 --- a/tests/fixtures/editor-ui/PanelLifecycle.editor.cs +++ b/tests/fixtures/editor-ui/PanelLifecycle.editor.cs @@ -25,8 +25,9 @@ IEditorSceneWorkspace workspace ) : EditorModule { private const string C_RESOURCE_COLUMNS = - "managed-bytes-after-full-gc\tprivate-bytes\tselection-count\tscene-count\thistory-resident-bytes\thistory-disk-bytes\tpending-events" + - "\tgc-index\tgc-generation\tgc-compacted\tgc-concurrent\tgc-heap-bytes\tgc-fragmented-bytes\testimated-managed-bytes"; + "managed-bytes-after-full-gc\tprivate-bytes\tselection-count\tscene-count\thistory-resident-bytes\thistory-disk-bytes\tpending-events" + + "\tgc-index\tgc-generation\tgc-compacted\tgc-concurrent\tgc-heap-bytes\tgc-fragmented-bytes\testimated-managed-bytes"; + private readonly List m_resources = ["completed-cycles\t" + C_RESOURCE_COLUMNS]; private readonly List m_preparationResources = ["phase\t" + C_RESOURCE_COLUMNS]; private string[] m_panels = []; @@ -49,7 +50,9 @@ IEditorSceneWorkspace workspace protected override void OnUpdate(EditorContext context) { if (m_completed) + { return; + } if (m_panels.Length == 0 && m_warmup++ < 20) { return; @@ -57,17 +60,23 @@ protected override void OnUpdate(EditorContext context) if (m_panels.Length == 0) { if (workspace.scenes.Count == 0) + { workspace.Open("FlappyBird/FlappyBird.iscene"); + } m_panels = interactions.GetPanelDeclarations().Select(static panel => panel.id).Order(StringComparer.Ordinal).ToArray(); if (m_panels.Length < 8) + { throw new InvalidOperationException("The complete Editor product must expose its eight standard panels."); + } m_originalOpenStates = new bool[m_panels.Length]; m_preparationResources.Add(CaptureResourceRow("before-first-panel-draw")); for (int index = 0; index < m_panels.Length; index++) { string panel = m_panels[index]; if (!interactions.TryGetPanelState(panel, out m_originalOpenStates[index]) || !interactions.OpenPanel(panel)) + { throw new InvalidOperationException("The product could not open panel '" + panel + "' for preparation."); + } } m_preparationFrames = 120; return; @@ -75,10 +84,16 @@ protected override void OnUpdate(EditorContext context) if (m_preparationFrames > 0) { if (--m_preparationFrames > 0) + { return; + } foreach (string panel in m_panels) + { if (!interactions.ClosePanel(panel)) + { throw new InvalidOperationException("The product could not close panel '" + panel + "' after preparation."); + } + } m_preparationResources.Add(CaptureResourceRow("after-120-drawn-frames")); return; } @@ -86,29 +101,45 @@ protected override void OnUpdate(EditorContext context) foreach (string panel in m_panels) { if (!interactions.TryGetPanelState(panel, out bool isOpen) || isOpen != expectedOpen) + { throw new InvalidOperationException("Panel state or native drawing failed for '" + panel + "' at cycle " + m_cycles + "."); + } } if (expectedOpen) + { m_cycles++; + } else { VerifyDocumentState(); if (m_cycles % 10 == 0) + { CaptureResources(); + } } if (m_cycles == m_requiredCycles && !expectedOpen) { for (int index = 0; index < m_panels.Length; index++) { - bool restored = m_originalOpenStates[index] ? interactions.OpenPanel(m_panels[index]) : interactions.ClosePanel(m_panels[index]); + bool restored = m_originalOpenStates[index] + ? interactions.OpenPanel(m_panels[index]) + : interactions.ClosePanel(m_panels[index]); if (!restored) + { throw new InvalidOperationException("The product could not restore panel '" + m_panels[index] + "'."); + } } string directory = Path.Combine(context.projectDirectory, "Library", "Acceptance"); Directory.CreateDirectory(directory); - File.WriteAllLines(Path.Combine(directory, "panel-lifecycle.tsv"), + File.WriteAllLines( + Path.Combine(directory, "panel-lifecycle.tsv"), new[] { "panel\tcompleted-open-close-cycles", "protocol\tpublic EditorInteractions / actual product drawing" } - .Concat(m_panels.Select(panel => panel + "\t" + m_requiredCycles.ToString(System.Globalization.CultureInfo.InvariantCulture)))); + .Concat( + m_panels.Select( + panel => panel + "\t" + m_requiredCycles.ToString(System.Globalization.CultureInfo.InvariantCulture) + ) + ) + ); File.WriteAllLines(Path.Combine(directory, "panel-lifecycle-resources.tsv"), m_resources); File.WriteAllLines(Path.Combine(directory, "panel-lifecycle-preparation.tsv"), m_preparationResources); string completion = Path.Combine(directory, "journey-completed.txt"); @@ -121,7 +152,9 @@ protected override void OnUpdate(EditorContext context) { bool changed = expectedOpen ? interactions.ClosePanel(panel) : interactions.OpenPanel(panel); if (!changed) + { throw new InvalidOperationException("The panel protocol rejected '" + panel + "'."); + } } } @@ -138,10 +171,14 @@ private void VerifyDocumentState() m_sceneCount = workspace.scenes.Count; m_baselineCaptured = true; } - if (history.isFaulted || history.undoName != m_undoName || history.redoName != m_redoName || - history.residentBytes != m_historyResidentBytes || history.diskBytes != m_historyDiskBytes || - interactions.selection.count != m_selectionCount || workspace.scenes.Count != m_sceneCount) - throw new InvalidOperationException("Window-only lifecycle operations changed Edit selection, scenes or committed History state."); + if (history.isFaulted || history.undoName != m_undoName || history.redoName != m_redoName + || history.residentBytes != m_historyResidentBytes || history.diskBytes != m_historyDiskBytes + || interactions.selection.count != m_selectionCount || workspace.scenes.Count != m_sceneCount + ) { + throw new InvalidOperationException( + "Window-only lifecycle operations changed Edit selection, scenes or committed History state." + ); + } } private void CaptureResources() @@ -151,8 +188,10 @@ private static int ReadRequiredCycles() { string value = Environment.GetEnvironmentVariable("INNO_ACCEPTANCE_PANEL_CYCLES") ?? "100"; if (!int.TryParse(value, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int cycles) - || cycles < 100 || cycles > 10000 || cycles % 10 != 0) + || cycles < 100 || cycles > 10000 || cycles % 10 != 0 + ) { throw new InvalidOperationException("The lifecycle acceptance requires 100–10000 cycles in ten-cycle intervals."); + } return cycles; } @@ -160,7 +199,12 @@ private string CaptureResourceRow(string observation) { ManagedMemorySample memory = ManagedMemorySample.Capture(); using Process process = Process.GetCurrentProcess(); - string state = FormattableString.Invariant($"{observation}\t{memory.liveBytes}\t{process.PrivateMemorySize64}\t{interactions.selection.count}\t{workspace.scenes.Count}\t{interactions.history.residentBytes}\t{interactions.history.diskBytes}\t{interactions.events.pendingCount}"); - return state + FormattableString.Invariant($"\t{memory.collectionIndex}\t{memory.generation}\t{memory.compacted}\t{memory.concurrent}\t{memory.heapBytes}\t{memory.fragmentedBytes}\t{memory.estimatedBytes}"); + string state = FormattableString.Invariant( + $"{observation}\t{memory.liveBytes}\t{process.PrivateMemorySize64}\t{interactions.selection.count}\t{workspace.scenes.Count}\t{interactions.history.residentBytes}\t{interactions.history.diskBytes}\t{interactions.events.pendingCount}" + ); + return state + + FormattableString.Invariant( + $"\t{memory.collectionIndex}\t{memory.generation}\t{memory.compacted}\t{memory.concurrent}\t{memory.heapBytes}\t{memory.fragmentedBytes}\t{memory.estimatedBytes}" + ); } } diff --git a/tests/input/Inno.Input.Tests/InputRuntimeTests.cs b/tests/input/Inno.Input.Tests/InputRuntimeTests.cs index 3bbf8ebf9..7c2f89c19 100644 --- a/tests/input/Inno.Input.Tests/InputRuntimeTests.cs +++ b/tests/input/Inno.Input.Tests/InputRuntimeTests.cs @@ -1,17 +1,16 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using Inno.Runtime.Contracts; using System; using System.Collections.Generic; using System.IO; - +using Xunit; +using Inno.Adapter.Input; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Events; using Inno.Core.Input; +using Inno.Core.Logging; using Inno.Input.Runtime; -using Inno.Adapter.Input; using Inno.Runtime; -using Xunit; +using Inno.Runtime.Contracts; namespace Inno.Input.Tests; @@ -34,7 +33,8 @@ public void WindowSourcesRemainIsolatedAcrossTextWheelAndRelease() using var second = new EventInputSource(8); using var firstBackend = first.CreateBackend(); using var secondBackend = second.CreateBackend(); - Event[] events = [ + Event[] events = + [ new KeyPressedEvent(7, KeyCode.Space), new TextInputEvent(7, "typed"), new MouseScrolledEvent(7, 2f, 3f) @@ -152,8 +152,11 @@ public void RuntimeSubsystemBindsSnapshotAcrossSimulationPhases() using var source = new EventInputSource(windowId: 1); var observations = new List(); using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(InputRuntimeTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(InputRuntimeTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); var options = new RuntimeSessionOptions { @@ -177,22 +180,24 @@ public void RuntimeSubsystemBindsSnapshotAcrossSimulationPhases() Assert.Equal([true, true], observations); Assert.Throws(() => _ = Input.snapshot); if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } private sealed class InputProbeFactory(List observations) : IRuntimeSubsystemFactory { public RuntimeSubsystemDescriptor descriptor { get; } = new( new RuntimeSubsystemId("tests.input.probe"), - dependencies: [new RuntimeSubsystemId("inno.runtime.input")]); + dependencies: [new RuntimeSubsystemId("inno.runtime.input")] + ); public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => new InputProbe(observations); } private sealed class InputProbe(List observations) : RuntimeSubsystem { - protected override void OnUpdate(RuntimeFrame frame) - => observations.Add(Input.IsKeyDown(KeyCode.Enter)); + protected override void OnUpdate(RuntimeFrame frame) => observations.Add(Input.IsKeyDown(KeyCode.Enter)); protected override void OnLateUpdate(RuntimeFrame frame) => observations.Add(Input.WasKeyPressed(KeyCode.Enter)); diff --git a/tests/input/Inno.Input.Tests/NativeWindowSurfaceTests.cs b/tests/input/Inno.Input.Tests/NativeWindowSurfaceTests.cs index bfb256796..cc26005da 100644 --- a/tests/input/Inno.Input.Tests/NativeWindowSurfaceTests.cs +++ b/tests/input/Inno.Input.Tests/NativeWindowSurfaceTests.cs @@ -1,7 +1,7 @@ using System; +using Xunit; using Inno.Adapter.Platform; using Inno.Platform; -using Xunit; namespace Inno.Input.Tests; @@ -18,5 +18,4 @@ public void NativeSurfaceIdentifiersAreOpenAndRejectWhitespace() Assert.Throws(() => new PlatformNativeHandleId(" ")); Assert.Throws(() => new PlatformNativeHandleId("tests. surface")); } - } diff --git a/tests/input/Inno.Input.Tests/ShellFrameDriverTests.cs b/tests/input/Inno.Input.Tests/ShellFrameDriverTests.cs index 38539ef9d..7eb995a08 100644 --- a/tests/input/Inno.Input.Tests/ShellFrameDriverTests.cs +++ b/tests/input/Inno.Input.Tests/ShellFrameDriverTests.cs @@ -1,8 +1,8 @@ using System; using System.Threading; using System.Threading.Tasks; -using Inno.Shell; using Xunit; +using Inno.Shell; namespace Inno.Input.Tests; @@ -71,9 +71,11 @@ public async Task SchedulingAndFrameFailuresPropagateToTheShellOwner() var expected = new InvalidOperationException("frame failed"); var driver = new ScheduledShellFrameDriver(_ => ValueTask.CompletedTask); Exception actual = await Assert.ThrowsAsync( - () => driver.RunAsync(() => throw expected, CancellationToken.None).AsTask()); + () => driver.RunAsync(() => throw expected, CancellationToken.None).AsTask() + ); Assert.Same(expected, actual); Assert.Throws( - () => new PollingShellFrameDriver().RunAsync(() => throw expected, CancellationToken.None)); + () => new PollingShellFrameDriver().RunAsync(() => throw expected, CancellationToken.None) + ); } } diff --git a/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs b/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs index c0be8999f..917532965 100644 --- a/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs +++ b/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Adapter; using Inno.Adapter.Audio; using Inno.Adapter.Input; @@ -20,7 +21,6 @@ using Inno.Storage; using Inno.Text; using Inno.UI; -using Xunit; namespace Inno.Input.Tests; @@ -94,7 +94,8 @@ public async Task ExecutionAndStoppingFailuresAreBothRetainedAndCallbacksDetach( stoppingFailure = new InvalidOperationException("stopping failure") }; AggregateException failure = await Assert.ThrowsAsync( - () => shell.RunAsync(new PollingShellFrameDriver(), smokeFrameLimit: 1)); + () => shell.RunAsync(new PollingShellFrameDriver(), smokeFrameLimit: 1) + ); Assert.Contains(shell.frameFailure, failure.InnerExceptions); Assert.Contains(shell.stoppingFailure, failure.InnerExceptions); Assert.Equal(ShellState.Faulted, shell.state); @@ -112,7 +113,10 @@ public async Task CancellationStopsWithoutClaimingSmokeCompletion() using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => shell.RunAsync( - new PollingShellFrameDriver(), smokeFrameLimit: 1, cancellationToken: cancellation.Token)); + new PollingShellFrameDriver(), + smokeFrameLimit: 1, + cancellationToken: cancellation.Token + )); Assert.Equal(ShellState.Stopped, shell.state); Assert.Equal(0, shell.smokeFrames); Assert.Empty(shell.frames); @@ -124,7 +128,10 @@ private sealed class TestShell : Inno.Shell.Shell public TestShell( TestCatalog catalog, bool suspendWhenHidden - ) : base(catalog, new ShellOptions { adapters = new Inno.Adapter.AdapterSelection { + ) : base(catalog, new ShellOptions + { + adapters = new Inno.Adapter.AdapterSelection + { platform = Inno.Adapter.Platform.PlatformBackendId.sdl3, input = Inno.Adapter.Input.InputBackendId.events, rendering = Inno.Adapter.Rendering.RenderingBackendId.bgfx, @@ -132,7 +139,10 @@ bool suspendWhenHidden audio = Inno.Adapter.Audio.AudioBackendId.miniAudio, text = Inno.Adapter.Text.TextBackendId.freeTypeHarfBuzz, ui = Inno.Adapter.UI.UiBackendId.rmlUi - }, suspendWhenHidden = suspendWhenHidden }) { + }, + suspendWhenHidden = suspendWhenHidden + }) + { InitializeAdapterResources(); } @@ -145,16 +155,22 @@ bool suspendWhenHidden protected override void OnFrame(ShellFrame frame) { if (frameFailure is not null) + { throw frameFailure; + } frames.Add(frame); } protected override void OnSuspensionChanged(bool isSuspended) => suspensions.Add(isSuspended); + protected override void OnSmokeCompleted(int frameCount) => smokeFrames = frameCount; + protected override void OnStopping() { if (stoppingFailure is not null) + { throw stoppingFailure; + } } } @@ -162,6 +178,7 @@ private sealed class TestCatalog : IAdapterCatalog, IPlatformBackendFactory, IIn IRenderingBackendFactory, IStorageBackendFactory, IAudioBackendFactory, ITextBackendFactory, IUiBackendFactory { public TestCatalog() => application = new TestApplication(retired); + public TestApplication application { get; } public List retired { get; } = []; public IPlatformBackendFactory platform => this; @@ -178,26 +195,34 @@ private sealed class TestCatalog : IAdapterCatalog, IPlatformBackendFactory, IIn IReadOnlyList IAudioBackendFactory.supportedBackends => [AudioBackendId.miniAudio]; IReadOnlyList ITextBackendFactory.supportedBackends => [TextBackendId.freeTypeHarfBuzz]; IReadOnlyList IUiBackendFactory.supportedBackends => [UiBackendId.rmlUi]; + public IPlatformApplication CreateApplication(PlatformBackendId backend) => application; + public IInputEventSource CreateEventSource( InputBackendId backend, IPlatformWindow window, bool acceptAllWindows ) => new TestInputSource(retired); + public IRenderDevice CreateDevice( RenderingBackendId backend, RenderingBackendOptions options ) => new TestRenderDevice(retired); + public IApplicationStorage CreateStorage( StorageBackendId backend, StorageScope scope ) => throw new NotSupportedException(); + public IAudioDevice CreateDevice( AudioBackendId backend, AudioBackendOptions options = default ) => throw new NotSupportedException(); + public ITextBackend CreateBackend(TextBackendId backend) => throw new NotSupportedException(); + public IUiBackend CreateBackend(UiBackendId backend) => throw new NotSupportedException(); + public IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendId backend) => throw new NotSupportedException(); } @@ -207,15 +232,29 @@ private sealed class TestApplication(List retired) : IPlatformApplicatio private Action? m_redraw; public Queue events { get; } = new(); public int redrawSubscribers { get; private set; } + public event Action? redrawRequested { - add { m_redraw += value; redrawSubscribers++; } - remove { m_redraw -= value; redrawSubscribers--; } + add + { + m_redraw += value; + redrawSubscribers++; + } + remove + { + m_redraw -= value; + redrawSubscribers--; + } } + public IPlatformWindow CreateWindow(PlatformWindowOptions options) => new TestWindow(retired); + public bool PollEvent(out Event? evnt) => events.TryDequeue(out evnt); + public IReadOnlyList GetWindows() => []; + public void RequestRedraw() => m_redraw?.Invoke(1); + public void Dispose() => retired.Add("platform"); } @@ -229,15 +268,20 @@ private sealed class TestWindow(List retired) : IPlatformWindow public int pixelHeight => 32; public bool isClosed { get; private set; } public bool isFocused => true; + public void RequestClose() => isClosed = true; + public void Dispose() => retired.Add("window"); } private sealed class TestInputSource(List retired) : IInputEventSource { private readonly EventInputSource m_source = new(1); + public IInputBackend CreateBackend() => m_source.CreateBackend(); + public void ProcessEvent(Event evnt) => m_source.ProcessEvent(evnt); + public void Dispose() { m_source.Dispose(); @@ -251,60 +295,80 @@ private sealed class TestRenderDevice(List retired) : IRenderDevice public uint generation => 1; public RenderPresentationSize? primaryPresentationSize { get; private set; } public bool primaryPresentationEncodesSrgb => true; - public void SetVerticalSync(bool enabled) { } + + public void SetVerticalSync(bool enabled) {} + public void BeginFrame() => throw new NotSupportedException(); + public uint EndFrame() => throw new NotSupportedException(); + public void Execute( CompiledRenderGraph graph, ulong frameIndex ) => throw new NotSupportedException(); + public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; + public PersistentTextureHandle CreateTexture( RenderTextureDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void UpdateTexture( PersistentTextureHandle texture, ReadOnlySpan data, int mipLevel = 0, int arrayLayer = 0 ) => throw new NotSupportedException(); + public void UpdateTextureRegion( PersistentTextureHandle texture, RenderTextureRegion region, ReadOnlySpan data ) => throw new NotSupportedException(); + public RenderTextureReadbackHandle BeginTextureReadback( PersistentTextureHandle texture, int mipLevel = 0 ) => throw new NotSupportedException(); + public bool TryGetTextureReadback( RenderTextureReadbackHandle readback, out RenderTextureReadbackResult? result ) => throw new NotSupportedException(); + public void CancelTextureReadback(RenderTextureReadbackHandle readback) => throw new NotSupportedException(); + public void DestroyTexture(PersistentTextureHandle texture) => throw new NotSupportedException(); + public PersistentBufferHandle CreateBuffer( PersistentBufferDescriptor descriptor, ReadOnlySpan initialData, string name ) => throw new NotSupportedException(); + public void UpdateBuffer( PersistentBufferHandle buffer, ReadOnlySpan data, int startElement = 0 ) => throw new NotSupportedException(); + public void DestroyBuffer(PersistentBufferHandle buffer) => throw new NotSupportedException(); + public GraphicsPipelineHandle CreateGraphicsPipeline( GraphicsPipelineDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) => throw new NotSupportedException(); + public ComputePipelineHandle CreateComputePipeline( ComputePipelineDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void DestroyComputePipeline(ComputePipelineHandle pipeline) => throw new NotSupportedException(); + public void Dispose() => retired.Add("render"); } } diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs index f12d9aa45..e77fe3205 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs @@ -4,10 +4,10 @@ using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Distribution.Standard; using Inno.Build.SupportPacks; using Inno.Testing.Source; -using Xunit; namespace Inno.Build.BrowserWasm32.Integration.Tests; @@ -27,7 +27,14 @@ public async Task MatchingStaticDependenciesProduceARealManagedPlayerSupportPack var target = new BuildTargetId("browser-wasm"); string output = Path.Combine(root, "artifacts", "validation", "browser-support-pack"); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(20)); - using PlayerSupportPackPublication pack = await distribution.supportPacks.PublishAsync(root, output, target, dotnet, cancellation.Token, manifest); + using PlayerSupportPackPublication pack = await distribution.supportPacks.PublishAsync( + root, + output, + target, + dotnet, + cancellation.Token, + manifest + ); distribution.platforms.Single(platform => platform.descriptor.id == target).supportPackSource.Validate(pack.directory); Assert.True(File.Exists(Path.Combine(pack.directory, "References", "Inno.Player.Runtime.dll"))); Assert.False(File.Exists(Path.Combine(pack.directory, "References", "Inno.Player.BrowserWasm32.dll"))); diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs index f3a952c75..405b06896 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs @@ -18,11 +18,12 @@ public void BrowserPlatformChecksObjectAbiWithoutKnowingTheSelectedBackend() "BrowserWasm32Bridge.cs", "global.json", "Analyzers/Inno.Runtime.Generators.dll", "Analyzers/Inno.Core.Serialization.Generators.dll", "wwwroot/index.html", "wwwroot/main.js", "Native/wasm_sjlj_shim.c", "References/Inno.Player.Runtime.dll" - }) + }) { Write("PlayerLink/" + input); + } string archive = Path.Combine(m_root, "PlayerLink", "Native", "custom.a"); string header = "object.o/".PadRight(16) + "0".PadRight(12) + "0".PadRight(6) - + "0".PadRight(6) + "644".PadRight(8) + "8".PadRight(10) + "`\n"; + + "0".PadRight(6) + "644".PadRight(8) + "8".PadRight(10) + "`\n"; byte[] bytes = [.. Encoding.ASCII.GetBytes("!\n" + header), 0, 97, 115, 109, 1, 0, 0, 0]; File.WriteAllBytes(archive, bytes); var validator = new Inno.Build.BrowserWasm32.BrowserWasm32SupportPackValidator(); diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs index 233e83b4e..857580108 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs @@ -1,4 +1,3 @@ -using Inno.Build.Composition; using System; using System.IO; using System.Linq; @@ -6,6 +5,7 @@ using System.Threading.Tasks; using Xunit; using Inno.Build; +using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Products.Standard; using Inno.Build.Toolchains; @@ -15,20 +15,34 @@ namespace Inno.Build.BrowserWasm32.Tests; public sealed class BrowserSupportPackTests : IDisposable { private readonly string m_root = Path.Combine( - Path.GetTempPath(), "InnoBrowserPackTests", Guid.NewGuid().ToString("N")); + Path.GetTempPath(), + "InnoBrowserPackTests", + Guid.NewGuid().ToString("N") + ); public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] public async Task BrowserPackRequiresItsStaticGameLinkerClosure() { - ProductNativeBuildPlan plan = StandardBuildDistribution.Create(new BuildCompositionContext("explicit-sdk", Path.GetTempPath(), new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("browser-wasm"))).build.ResolveNativeProduct("browser-wasm", "player").plan; + ProductNativeBuildPlan plan = StandardBuildDistribution.Create( + new BuildCompositionContext( + "explicit-sdk", + Path.GetTempPath(), + new BuildHostDescriptor("Windows", "x64"), + new BuildTargetId("browser-wasm") + ) + ).build + .ResolveNativeProduct("browser-wasm", "player").plan; IPlayerSupportPackValidator validator = StandardBuildDistribution.Create( - StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId("windows-x64"))).build.platforms + StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId("windows-x64")) + ).build.platforms .Single(static platform => platform.descriptor.id == new BuildTargetId("browser-wasm")).supportPackSource; string pack = Path.Combine(m_root, "candidate"); Write(pack, "References/Inno.Runtime.dll"); @@ -48,25 +62,27 @@ public async Task BrowserPackRequiresItsStaticGameLinkerClosure() { "Inno.Native.Bgfx.dll", "Inno.Native.MiniAudio.dll", "Inno.Native.Sdl3.dll", "Inno.Native.Text.dll", "Inno.Native.UI.dll" - }) - { + }) { Write(pack, "PlayerLink/References/" + binding); Write(pack, "References/" + binding); } Write(pack, "PlayerLink/References/BGCS.Runtime.dll"); foreach (ProductNativeBuildStep step in plan.steps) - foreach (string archive in step.component.staticBuild!.logicalOutputs.Select(Inno.Build.BrowserWasm32.BrowserWasm32LinkerSettings.Create().GetStaticFileName)) + { + foreach (string archive in step.component.staticBuild!.logicalOutputs.Select( + Inno.Build.BrowserWasm32.BrowserWasm32LinkerSettings.Create().GetStaticFileName + )) { Write(pack, $"PlayerLink/Native/{step.id}/browser-wasm/{archive}"); + } + } var catalog = new PlayerSupportPackCatalog(m_root); Write(pack, "PlayerLink/Native/foreign.dll"); - InvalidDataException foreignBinary = Assert.Throws( - () => validator.Validate(pack)); + InvalidDataException foreignBinary = Assert.Throws(() => validator.Validate(pack)); Assert.Contains("foreign.dll", foreignBinary.Message, StringComparison.Ordinal); File.Delete(Path.Combine(pack, "PlayerLink", "Native", "foreign.dll")); File.Delete(Path.Combine(pack, "PlayerLink", "HttpPlayerContentSource.cs")); - InvalidDataException missingSource = Assert.Throws( - () => validator.Validate(pack)); + InvalidDataException missingSource = Assert.Throws(() => validator.Validate(pack)); Assert.Contains("HttpPlayerContentSource.cs", missingSource.Message, StringComparison.Ordinal); Write(pack, "PlayerLink/HttpPlayerContentSource.cs"); Write(pack, "PlayerLink/Native/extra.a"); @@ -80,7 +96,8 @@ public async Task BrowserPackRequiresItsStaticGameLinkerClosure() File.Delete(Path.Combine(pack, "PlayerLink", "Native", "sdl3", "browser-wasm", "libSDL3.a")); InvalidDataException missingArchive = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("browser-wasm"), validator)); + () => catalog.Acquire(new BuildTargetId("browser-wasm"), validator) + ); Assert.Contains("libSDL3.a", missingArchive.Message, StringComparison.Ordinal); } @@ -93,10 +110,12 @@ string relativePath if (relativePath.EndsWith(".a", StringComparison.Ordinal)) { string header = "fixture.o/".PadRight(16) + "0".PadRight(12) + "0".PadRight(6) - + "0".PadRight(6) + "100644".PadRight(8) + "8".PadRight(10) + "`\n"; + + "0".PadRight(6) + "100644".PadRight(8) + "8".PadRight(10) + "`\n"; File.WriteAllBytes(path, [.. Encoding.ASCII.GetBytes("!\n" + header), .. "\0asm\u0001\0\0\0"u8]); } else + { File.WriteAllText(path, "fixture"); + } } } diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserToolchainTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserToolchainTests.cs index 65b2ab785..6fac28594 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserToolchainTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserToolchainTests.cs @@ -4,9 +4,9 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; -using Inno.Build.Toolchains; -using Inno.Build.BrowserWasm32; using Xunit; +using Inno.Build.BrowserWasm32; +using Inno.Build.Toolchains; namespace Inno.Build.BrowserWasm32.Tests; @@ -17,7 +17,9 @@ public sealed class BrowserToolchainTests : IDisposable public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -31,8 +33,12 @@ public async Task EnvironmentUsesTheProjectSelectedToolsWithoutChangingTheParent IReadOnlyDictionary environment = await EmscriptenToolchainResolver.ResolveAsync("dotnet", project); Assert.Equal(Path.Combine(m_root, "selected-sdk", "bin"), environment["DOTNET_EMSCRIPTEN_LLVM_ROOT"]); - Assert.True(File.Exists(Path.Combine(environment["DOTNET_EMSCRIPTEN_LLVM_ROOT"], OperatingSystem.IsWindows() ? "clang.exe" : "clang"))); - Assert.True(File.Exists(Path.Combine(environment["DOTNET_EMSCRIPTEN_LLVM_ROOT"], OperatingSystem.IsWindows() ? "clang++.exe" : "clang++"))); + Assert.True( + File.Exists(Path.Combine(environment["DOTNET_EMSCRIPTEN_LLVM_ROOT"], OperatingSystem.IsWindows() ? "clang.exe" : "clang")) + ); + Assert.True( + File.Exists(Path.Combine(environment["DOTNET_EMSCRIPTEN_LLVM_ROOT"], OperatingSystem.IsWindows() ? "clang++.exe" : "clang++")) + ); Assert.Equal(Path.Combine(m_root, "selected-cache"), environment["EM_CACHE"]); Assert.Equal(Path.Combine(m_root, "selected-node", "bin", NodeFileName()), environment["EMSDK_NODE"]); Assert.False(environment.ContainsKey("EMCC_CORES")); @@ -49,7 +55,8 @@ public async Task EnvironmentRejectsAnIncompleteSelectedToolchain() File.Delete(Path.Combine(m_root, "selected-node", "bin", NodeFileName())); FileNotFoundException failure = await Assert.ThrowsAsync( - () => EmscriptenToolchainResolver.ResolveAsync("dotnet", project)); + () => EmscriptenToolchainResolver.ResolveAsync("dotnet", project) + ); Assert.EndsWith(NodeFileName(), failure.FileName); } @@ -62,7 +69,8 @@ public async Task EnvironmentRejectsAProjectWithoutWorkloadSelection() new XDocument(new XElement("Project")).Save(project); InvalidOperationException failure = await Assert.ThrowsAsync( - () => EmscriptenToolchainResolver.ResolveAsync("dotnet", project)); + () => EmscriptenToolchainResolver.ResolveAsync("dotnet", project) + ); Assert.Contains("EmscriptenSdkToolsPath", failure.Message, StringComparison.Ordinal); } @@ -75,12 +83,17 @@ public async Task CapturePreservesStructuredArgumentsAndChildOnlyEnvironment() string? parent = Environment.GetEnvironmentVariable(variable); Directory.CreateDirectory(m_root); string project = Path.Combine(m_root, "Environment.proj"); - new XDocument(new XElement("Project", - new XElement("PropertyGroup", new XElement("Result", "$(" + variable + ")")))).Save(project); + new XDocument( + new XElement("Project", new XElement("PropertyGroup", new XElement("Result", "$(" + variable + ")"))) + ).Save(project); - string output = await ToolchainEnvironment.CaptureOutputAsync("dotnet", + string output = await ToolchainEnvironment.CaptureOutputAsync( + "dotnet", ["msbuild", project, "-nologo", "-nodeReuse:false", "-getProperty:Result"], - m_root, CancellationToken.None, new Dictionary { [variable] = value }); + m_root, + CancellationToken.None, + new Dictionary { [variable] = value } + ); Assert.Equal(value, output.Trim()); Assert.Equal(parent, Environment.GetEnvironmentVariable(variable)); @@ -92,7 +105,11 @@ public async Task CaptureRejectsFailedTools() Directory.CreateDirectory(m_root); await Assert.ThrowsAsync(() => ToolchainEnvironment.CaptureOutputAsync( - "dotnet", ["--inno-invalid-option"], m_root, CancellationToken.None)); + "dotnet", + ["--inno-invalid-option"], + m_root, + CancellationToken.None + )); } [Fact] @@ -102,7 +119,11 @@ public async Task CaptureDoesNotStartAnAlreadyCanceledOperation() cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => ToolchainEnvironment.CaptureOutputAsync( - "inno-tool-that-does-not-exist", [], m_root, cancellation.Token)); + "inno-tool-that-does-not-exist", + [], + m_root, + cancellation.Token + )); } private string CreateProject() @@ -120,11 +141,18 @@ private string CreateProject() File.WriteAllText(Path.Combine(node, "bin", NodeFileName()), string.Empty); File.WriteAllText(Path.Combine(python, "python.exe"), string.Empty); string project = Path.Combine(m_root, "SelectedWorkload.proj"); - new XDocument(new XElement("Project", new XElement("PropertyGroup", - new XElement("EmscriptenSdkToolsPath", sdk), - new XElement("EmscriptenNodeToolsPath", node), - new XElement("EmscriptenPythonToolsPath", python), - new XElement("EmscriptenCacheSdkCacheDir", cache)))).Save(project); + new XDocument( + new XElement( + "Project", + new XElement( + "PropertyGroup", + new XElement("EmscriptenSdkToolsPath", sdk), + new XElement("EmscriptenNodeToolsPath", node), + new XElement("EmscriptenPythonToolsPath", python), + new XElement("EmscriptenCacheSdkCacheDir", cache) + ) + ) + ).Save(project); return project; } diff --git a/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs b/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs index 4a9d507c8..520d91f50 100644 --- a/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs +++ b/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs @@ -1,14 +1,13 @@ using System; using System.IO; +using Xunit; using Inno.Build; using Inno.Testing.SupportPacks; -using Xunit; namespace Inno.Build.MacOSArm64.Tests; public sealed class SupportPackValidationTests : PlayerSupportPackFixture { - [Fact] public void PlatformPackRejectsAMissingContentSource() { @@ -31,7 +30,8 @@ public void SupportPackRejectsAuthoringAssetPipelineAssemblies() var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator())); + () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator()) + ); Assert.Contains("forbidden build-time file", exception.Message, StringComparison.OrdinalIgnoreCase); } @@ -44,7 +44,8 @@ public void SupportPackRejectsMissingMiniAudioRuntime() var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator())); + () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator()) + ); Assert.Contains("no longer matches", exception.Message, StringComparison.Ordinal); } @@ -55,8 +56,10 @@ public void PlatformValidatorRejectsForeignAbiDespiteTheExpectedFilename() BuildTargetId target = new BuildTargetId("macos-arm64"); string directory = GetSupportPackDirectory(target); string library = "libminiaudio-release.dylib"; - File.WriteAllBytes(Path.Combine(directory, "native", library), - CreateNativeImage(new BuildTargetId("windows-x64"))); + File.WriteAllBytes( + Path.Combine(directory, "native", library), + CreateNativeImage(new BuildTargetId("windows-x64")) + ); IPlayerSupportPackValidator validator = new MacOSArm64SupportPackValidator(); InvalidDataException failure = Assert.Throws(() => validator.Validate(directory)); Assert.Contains("ARM64 ABI", failure.Message); @@ -70,7 +73,8 @@ public void SupportPackRejectsForeignNativeRuntime() var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator())); + () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator()) + ); Assert.Contains("foreign native runtime", exception.Message, StringComparison.Ordinal); } @@ -85,9 +89,9 @@ public void SupportPackRejectsMissingTextOrUiRuntime(string nativeRuntime) var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator())); + () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator()) + ); Assert.Contains("no longer matches", exception.Message, StringComparison.Ordinal); } - } diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs index c313d01e2..ddbbff035 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs @@ -8,9 +8,9 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Build.WindowsX64; -using Xunit; namespace Inno.Build.WindowsX64.Integration.Tests; @@ -83,32 +83,62 @@ public async Task WindowsCompilationUsesFrozenHeadersAndKeepsBindingDefinesOutOf roots = [new("generated", "", true, true), new("user", headerRoot, false, true)], files = [Input("generated", "binding.c", unit, true), Input("user", "api.h", header, false)], includeDirectories = [new("user", "", false, false)], - defines = ["INNO_BINDING_ONLY=1"], compilerDefines = [], cxxStandard = 0, cStandard = 17, - requiredExports = ["value", "upstream"], staticExportSymbols = [], staticExportAbi = "", staticExportNames = [] + defines = ["INNO_BINDING_ONLY=1"], + compilerDefines = [], + cxxStandard = 0, + cStandard = 17, + requiredExports = ["value", "upstream"], + staticExportSymbols = [], + staticExportAbi = "", + staticExportNames = [] }; File.WriteAllBytes(Path.Combine(native, "compilation.json"), JsonSerializer.SerializeToUtf8Bytes(compilation)); - var owner = new NativeComponentDescriptor("fixture", "native/fixture.csproj", "build/fixture.csproj", - bindingDefinition: "native/Bindings/bindings.props"); + var owner = new NativeComponentDescriptor( + "fixture", + "native/fixture.csproj", + "build/fixture.csproj", + bindingDefinition: "native/Bindings/bindings.props" + ); var descriptor = new NativeBindingGenerationDescriptor { - fingerprint = new string('a', 64), artifactDirectory = artifact, artifactOwnerDirectory = root, - bindingsPath = managed, nativeDirectory = native, - usesRuntimeImports = false, + fingerprint = new string('a', 64), + artifactDirectory = artifact, + artifactOwnerDirectory = root, + bindingsPath = managed, + nativeDirectory = native, + usesRuntimeImports = false }; using var bindings = new NativeBindingGenerationResult( - new Dictionary { [owner.nativeProject] = descriptor }, []); + new Dictionary { [owner.nativeProject] = descriptor }, + [] + ); var tools = await new WindowsX64NativeToolchainProvider(ToolchainEnvironment.ResolveExecutable("dotnet")) - .ResolveAsync(new(root, "release"), (new WindowsBuildHostProvider().TryCapture() ?? throw new PlatformNotSupportedException("A Windows build host is required.")), "windows-x64", CancellationToken.None); - NativeBuildContext context = new NativeBuildContext(sourceAlias.toolPath, "release").WithToolchain(tools).WithBindings(bindings) + .ResolveAsync( + new(root, "release"), + (new WindowsBuildHostProvider().TryCapture() + ?? throw new PlatformNotSupportedException("A Windows build host is required.")), + "windows-x64", + CancellationToken.None + ); + NativeBuildContext context = new NativeBuildContext(sourceAlias.toolPath, "release").WithToolchain(tools) + .WithBindings(bindings) .WithComponentOptions(owner, new(NativeLibraryKind.Shared)); - var recipe = new NativeBuildRecipe(owner, "fixture", "windows-x64", - new[] { source }.Concat(tools.inputPaths).Select(path => NativeBuildInput.FromPath(root, path)), tools.declarations); - using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(context, recipe, + var recipe = new NativeBuildRecipe( + owner, + "fixture", + "windows-x64", + new[] { source }.Concat(tools.inputPaths).Select(path => NativeBuildInput.FromPath(root, path)), + tools.declarations + ); + using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + context, + recipe, async ( operation, output, cancellation - ) => { + ) => + { NativeCMakeSource inputs = await NativeCMakeExecutor.PrepareSourceAsync(operation, owner, cancellation); string frozenHeader = inputs.ResolvePath(header); Assert.NotEqual(header, frozenHeader); @@ -124,7 +154,8 @@ public async Task WindowsCompilationUsesFrozenHeadersAndKeepsBindingDefinesOutOf throw new Xunit.Sdk.XunitException(exception + Environment.NewLine + File.ReadAllText(requirements)); } File.Copy(NativeCMakeExecutor.FindOutput(operation, build, "fixture.dll"), Path.Combine(output, "fixture.dll")); - }); + } + ); Assert.True(File.Exists(header)); Assert.False(File.Exists(hidden)); nint library = NativeLibrary.Load(Assert.Single(product.files)); @@ -141,7 +172,9 @@ public async Task WindowsCompilationUsesFrozenHeadersAndKeepsBindingDefinesOutOf finally { if (File.Exists(hidden)) + { File.Move(hidden, header, overwrite: true); + } Directory.Delete(root, recursive: true); Directory.Delete(headerRoot, recursive: true); } @@ -162,7 +195,9 @@ private sealed class WindowsCompilerFactAttribute : FactAttribute public WindowsCompilerFactAttribute() { if (!OperatingSystem.IsWindows()) + { Skip = "Requires the Windows MSVC toolchain and its path-length contract."; + } } } } diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs index 4d56554fa..62297a568 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs @@ -25,9 +25,14 @@ public async Task ProcessTempDirectoriesSelectCompatibleCMakeWorkspaces() string dotnet = ToolchainEnvironment.ResolveExecutable("dotnet"); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); string cmake = OperatingSystem.IsWindows() - ? (await new WindowsX64NativeToolchainProvider(dotnet).ResolveAsync(new(repository, "debug"), - (new WindowsBuildHostProvider().TryCapture() ?? throw new PlatformNotSupportedException("A Windows build host is required.")), "windows-x64", timeout.Token)).ResolveExecutable("cmake") - : ToolchainEnvironment.ResolveExecutable("cmake"); + ? (await new WindowsX64NativeToolchainProvider(dotnet).ResolveAsync( + new(repository, "debug"), + (new WindowsBuildHostProvider().TryCapture() + ?? throw new PlatformNotSupportedException("A Windows build host is required.")), + "windows-x64", + timeout.Token + )).ResolveExecutable("cmake") + : ToolchainEnvironment.ResolveExecutable("cmake"); string project = Path.Combine(root, "Runner.csproj"); await File.WriteAllTextAsync(project, $$""" @@ -92,9 +97,13 @@ await File.WriteAllTextAsync(Path.Combine(root, "Program.cs"), """ return 0; """); var environment = DotNetSdkEnvironment.Create(dotnet); - await ToolchainEnvironment.RunAsync(dotnet, + await ToolchainEnvironment.RunAsync( + dotnet, ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-p:UseSharedCompilation=false"], - repository, timeout.Token, environment); + repository, + timeout.Token, + environment + ); string physical = Path.Combine(root, "Workspace with spaces", new string('x', 70), new string('y', 70), new string('z', 70)); string? firstExecution = null; (string value, string temporary, bool hit)[] calls = @@ -115,18 +124,30 @@ await ToolchainEnvironment.RunAsync(dotnet, ["TMPDIR"] = temporary }; string report = Path.Combine(root, call.value + (call.hit ? "-hit" : string.Empty) + ".txt"); - await ToolchainEnvironment.RunAsync(dotnet, + await ToolchainEnvironment.RunAsync( + dotnet, [Path.Combine(root, "bin/Debug/net10.0/Runner.dll"), physical, cmake, report, call.value, call.hit ? "hit" : "build"], - repository, timeout.Token, processEnvironment); + repository, + timeout.Token, + processEnvironment + ); string current = await File.ReadAllTextAsync(report); if (call.hit) + { Assert.Equal("cache", current); + } else if (call.value == "first") + { firstExecution = current; + } else if (call.value == "second" && OperatingSystem.IsWindows()) + { Assert.NotEqual(firstExecution, current); + } else + { Assert.Equal(firstExecution, current); + } } } finally diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsColdPublicationTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsColdPublicationTests.cs index fe581ff74..89c74e092 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsColdPublicationTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsColdPublicationTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.Linq; using System.Runtime.InteropServices; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -25,35 +25,68 @@ public sealed class WindowsColdPublicationTests : IDisposable public async Task WindowsColdCMakeBuildCompilesCopiedInputsEvenWhenOriginalBytesAreTemporarilyChanged() { if (!OperatingSystem.IsWindows()) + { return; + } NativeBuildContext unresolved = CreateContext(); - NativeToolchainSelection tools = await new WindowsX64NativeToolchainProvider(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet")).ResolveAsync( - unresolved, (new WindowsBuildHostProvider().TryCapture() ?? throw new PlatformNotSupportedException("A Windows build host is required.")), "windows-x64", CancellationToken.None); + NativeToolchainSelection tools = await new WindowsX64NativeToolchainProvider( + Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet") + ).ResolveAsync( + unresolved, + (new WindowsBuildHostProvider().TryCapture() ?? throw new PlatformNotSupportedException("A Windows build host is required.")), + "windows-x64", + CancellationToken.None + ); NativeBuildContext context = unresolved.WithToolchain(tools).WithComponentOptions( - new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), - new NativeComponentBuildOptions(NativeLibraryKind.Shared)); + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + new NativeComponentBuildOptions(NativeLibraryKind.Shared) + ); string source = Path.Combine(m_root, "Source"); Directory.CreateDirectory(source); - File.WriteAllText(Path.Combine(source, "CMakeLists.txt"), + File.WriteAllText( + Path.Combine(source, "CMakeLists.txt"), "cmake_minimum_required(VERSION 3.20)\nproject(ColdFixture C)\n" + "configure_file(\"${INNO_FIXTURE_INPUT}\" \"${CMAKE_CURRENT_BINARY_DIR}/answer.h\" COPYONLY)\n" + "add_library(fixture SHARED api.c)\n" - + "target_include_directories(fixture PRIVATE \"${CMAKE_CURRENT_BINARY_DIR}\")\n"); - File.WriteAllText(Path.Combine(source, "api.c"), "#include \"answer.h\"\n__declspec(dllexport) int value(void) { return ANSWER; }\n"); + + "target_include_directories(fixture PRIVATE \"${CMAKE_CURRENT_BINARY_DIR}\")\n" + ); + File.WriteAllText( + Path.Combine(source, "api.c"), + "#include \"answer.h\"\n__declspec(dllexport) int value(void) { return ANSWER; }\n" + ); string header = Path.Combine(source, "answer.h"); File.WriteAllText(header, "#define ANSWER 42\n"); DateTime timestamp = File.GetLastWriteTimeUtc(header); - using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync(context, - CreateRecipe(context, new NativeComponentDescriptor("fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"), "fixture", "windows-x64", [source], []), async ( + using NativeBuildProduct product = await NativeArtifactPublisher.PublishAsync( + context, + CreateRecipe( + context, + new NativeComponentDescriptor( + "fixture", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ), + "fixture", + "windows-x64", + [source], + [] + ), + async ( @scoped, output, cancellation - ) => { - var owner = new NativeComponentDescriptor("fixture", + ) => + { + var owner = new NativeComponentDescriptor( + "fixture", "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj", - "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj"); + "build/toolchains/Inno.Build.Toolchains/Inno.Build.Toolchains.csproj" + ); NativeCMakeSource copied = await NativeCMakeExecutor.PrepareSourceAsync(scoped, owner, cancellation); Assert.Same(copied, await NativeCMakeExecutor.PrepareSourceAsync(scoped.WithToolchain(tools), owner, cancellation)); Assert.NotEqual(source, copied.ResolvePath(source)); @@ -64,8 +97,14 @@ public async Task WindowsColdCMakeBuildCompilesCopiedInputsEvenWhenOriginalBytes try { Assert.Equal("#define ANSWER 42\n", File.ReadAllText(copied.ResolvePath(header))); - string directory = await NativeCMakeExecutor.BuildAsync(scoped, owner, source, - "fixture", ["-DINNO_FIXTURE_INPUT=" + header], cancellation); + string directory = await NativeCMakeExecutor.BuildAsync( + scoped, + owner, + source, + "fixture", + ["-DINNO_FIXTURE_INPUT=" + header], + cancellation + ); File.Copy(NativeCMakeExecutor.FindOutput(scoped, directory, "fixture.dll"), Path.Combine(output, "fixture.dll")); } finally @@ -73,7 +112,8 @@ public async Task WindowsColdCMakeBuildCompilesCopiedInputsEvenWhenOriginalBytes File.WriteAllText(header, "#define ANSWER 42\n"); File.SetLastWriteTimeUtc(header, timestamp); } - }); + } + ); Assert.Single(product.files); Assert.True(new FileInfo(product.files[0]).Length > 0); @@ -94,7 +134,9 @@ public async Task WindowsColdCMakeBuildCompilesCopiedInputsEvenWhenOriginalBytes public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private static NativeBuildRecipe CreateRecipe( @@ -104,10 +146,14 @@ private static NativeBuildRecipe CreateRecipe( string targetId, IReadOnlyList inputPaths, IReadOnlyList declarations - ) => new(owner, component, targetId, + ) => new( + owner, + component, + targetId, inputPaths.Concat(context.toolchain?.inputPaths ?? []) .Select(path => NativeBuildInput.FromPath(context.engineRoot, path)), - declarations.Concat(context.toolchain?.declarations ?? [])); + declarations.Concat(context.toolchain?.declarations ?? []) + ); private NativeBuildContext CreateContext() { diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsNativeWorkspaceTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsNativeWorkspaceTests.cs index 40755bb14..85ba4eb42 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsNativeWorkspaceTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/WindowsNativeWorkspaceTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.IO; -using System.Runtime.Versioning; using System.Linq; using System.Runtime.InteropServices; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -33,14 +33,24 @@ public WindowsNativeWorkspaceTests() public async Task WindowsCMakeReusesUnchangedObjectsAndPublishesChangedSourceBytes() { if (!OperatingSystem.IsWindows()) + { return; + } NativeToolchainSelection tools = await new WindowsX64NativeToolchainProvider( - ToolchainEnvironment.ResolveExecutable("dotnet")).ResolveAsync(new(m_root, "release"), - (new WindowsBuildHostProvider().TryCapture() ?? throw new PlatformNotSupportedException("A Windows build host is required.")), "windows-x64", CancellationToken.None); + ToolchainEnvironment.ResolveExecutable("dotnet") + ).ResolveAsync( + new(m_root, "release"), + (new WindowsBuildHostProvider().TryCapture() + ?? throw new PlatformNotSupportedException("A Windows build host is required.")), + "windows-x64", + CancellationToken.None + ); string source = Path.Combine(m_root, "Source"); Directory.CreateDirectory(source); - File.WriteAllText(Path.Combine(source, "CMakeLists.txt"), - "cmake_minimum_required(VERSION 3.20)\nproject(WorkspaceFixture C)\nadd_library(fixture SHARED api.c stable.c)\n"); + File.WriteAllText( + Path.Combine(source, "CMakeLists.txt"), + "cmake_minimum_required(VERSION 3.20)\nproject(WorkspaceFixture C)\nadd_library(fixture SHARED api.c stable.c)\n" + ); string changed = Path.Combine(source, "api.c"); File.WriteAllText(changed, "__declspec(dllexport) int value(void) { return 41; }\n"); File.WriteAllText(Path.Combine(source, "stable.c"), "int stable(void) { return 7; }\n"); @@ -57,7 +67,9 @@ CancellationToken cancellation string current = scoped.GetNativeBuildRoot(m_owner); string physical = new DirectoryInfo(current).LinkTarget ?? current; if (workspace is not null) + { Assert.Equal(workspace, physical); + } workspace = physical; string build = await NativeCMakeExecutor.BuildAsync(scoped, m_owner, source, "fixture", [], cancellation); File.Copy(NativeCMakeExecutor.FindOutput(scoped, build, "fixture.dll"), Path.Combine(output, "fixture.dll")); @@ -74,11 +86,17 @@ CancellationToken cancellation Assert.Equal(stableTime, File.GetLastWriteTimeUtc(objectPath)); } } - NativeBuildContext Context() => new NativeBuildContext(m_root, "release").WithToolchain(tools) - .WithComponentOptions(m_owner, new(NativeLibraryKind.Shared)); - NativeBuildRecipe Recipe() => new(m_owner, "fixture", "windows-x64", - new[] { source }.Concat(tools.inputPaths).Select(path => NativeBuildInput.FromPath(m_root, path)), - tools.declarations.Concat(new[] { "shared", "fixture" })); + NativeBuildContext Context() + => new NativeBuildContext(m_root, "release").WithToolchain(tools) + .WithComponentOptions(m_owner, new(NativeLibraryKind.Shared)); + NativeBuildRecipe Recipe() + => new( + m_owner, + "fixture", + "windows-x64", + new[] { source }.Concat(tools.inputPaths).Select(path => NativeBuildInput.FromPath(m_root, path)), + tools.declarations.Concat(new[] { "shared", "fixture" }) + ); using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(Context(), Recipe(), Produce); Assert.Equal(41, Read(first)); File.WriteAllText(changed, "__declspec(dllexport) int value(void) { return 42; }\n"); @@ -97,9 +115,13 @@ CancellationToken cancellation public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } if (Directory.Exists(m_bindingRoot)) + { Directory.Delete(m_bindingRoot, recursive: true); + } } private static int Read(NativeBuildProduct product) @@ -114,5 +136,4 @@ private static int Read(NativeBuildProduct product) NativeLibrary.Free(library); } } - } diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs index df99bfa4b..c840a0062 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs @@ -1,14 +1,13 @@ using System; using System.IO; +using Xunit; using Inno.Build; using Inno.Testing.SupportPacks; -using Xunit; namespace Inno.Build.WindowsX64.Tests; public sealed class SupportPackValidationTests : PlayerSupportPackFixture { - [Fact] public void PlatformPackRejectsAMissingContentSource() { @@ -29,11 +28,12 @@ public void PlatformValidatorRejectsForeignAbiDespiteTheExpectedFilename() BuildTargetId target = new BuildTargetId("windows-x64"); string directory = GetSupportPackDirectory(target); string library = "miniaudio-release.dll"; - File.WriteAllBytes(Path.Combine(directory, "native", library), - CreateNativeImage(new BuildTargetId("macos-arm64"))); + File.WriteAllBytes( + Path.Combine(directory, "native", library), + CreateNativeImage(new BuildTargetId("macos-arm64")) + ); IPlayerSupportPackValidator validator = new WindowsX64SupportPackValidator(); InvalidDataException failure = Assert.Throws(() => validator.Validate(directory)); Assert.Contains("PE header", failure.Message); } - } diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolRunnerPathTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolRunnerPathTests.cs index ef90a6371..9ff0d38e1 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolRunnerPathTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolRunnerPathTests.cs @@ -3,9 +3,9 @@ using System.IO; using System.Runtime.Versioning; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Build.WindowsX64; -using Xunit; namespace Inno.Build.WindowsX64.Tests; @@ -16,7 +16,9 @@ public sealed class ToolRunnerPathTests public async Task DeepOwnedExecutableStartsAndRemainsAfterItsAliasIsReleased() { if (!OperatingSystem.IsWindows()) + { return; + } string root = Path.Combine(Path.GetTempPath(), "InnoToolRunner", Guid.NewGuid().ToString("N")); string directory = Path.Combine(root, new string('a', 90), new string('b', 90), new string('c', 50)); Directory.CreateDirectory(directory); @@ -25,8 +27,11 @@ public async Task DeepOwnedExecutableStartsAndRemainsAfterItsAliasIsReleased() { File.Copy(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe"), executable); Assert.True(executable.Length > 260); - var runner = new ToolRunner(new Dictionary { [BgfxTool.Shaderc] = executable }, - directory, new WindowsToolchainWorkspaceProvider()); + var runner = new ToolRunner( + new Dictionary { [BgfxTool.Shaderc] = executable }, + directory, + new WindowsToolchainWorkspaceProvider() + ); ToolRunResult result = await runner.RunAsync(BgfxTool.Shaderc, ["/c", "exit", "0"], root); Assert.True(result.exitCode == 0, $"exit={result.exitCode}; stdout={result.standardOutput}; stderr={result.standardError}"); Assert.True(File.Exists(executable)); diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs index d11284cb6..7fdf65153 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs @@ -40,7 +40,9 @@ public async Task BoundedExecutionRetainsFilesAndStableIdentityAcrossOwners() next.Dispose(); next.Dispose(); if (OperatingSystem.IsWindows()) + { Assert.False(Directory.Exists(execution)); + } } [Fact] @@ -85,16 +87,19 @@ await Assert.ThrowsAnyAsync(async () => public async Task OccupiedAliasFailsWithoutRemovingTheOccupantAndReleasesOwnership() { if (!OperatingSystem.IsWindows()) + { return; + } string physical = Path.Combine(m_root, "Occupied"); string alias; using (ToolchainWorkingDirectory owner = await CreateProvider().OpenAsync(physical)) + { alias = owner.toolPath; + } Directory.CreateDirectory(alias); try { - await Assert.ThrowsAsync(async () => - await CreateProvider().OpenAsync(physical)); + await Assert.ThrowsAsync(async () => await CreateProvider().OpenAsync(physical)); Assert.Null(new DirectoryInfo(alias).LinkTarget); } finally @@ -120,12 +125,16 @@ public async Task PhysicalProviderPreservesTheExactOwnerPath() Assert.Equal("retained", File.ReadAllText(Path.Combine(physical, "output.txt"))); } - private static IToolchainWorkspaceProvider CreateProvider() => OperatingSystem.IsWindows() - ? new WindowsToolchainWorkspaceProvider() : new PhysicalToolchainWorkspaceProvider(); + private static IToolchainWorkspaceProvider CreateProvider() + => OperatingSystem.IsWindows() + ? new WindowsToolchainWorkspaceProvider() + : new PhysicalToolchainWorkspaceProvider(); public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs b/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs index e65a36668..626c32d58 100644 --- a/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs +++ b/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs @@ -1,6 +1,3 @@ -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; @@ -8,19 +5,22 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Plugins.Authoring; -using Inno.Plugins; -using Inno.Extensibility.Modules; -using Inno.Core.Identity; using Inno.Core.Diagnostics; using Inno.Core.Execution; +using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Settings; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; +using Inno.Plugins; +using Inno.Plugins.Authoring; namespace Inno.Plugins.Authoring.Tests; @@ -52,7 +52,9 @@ public PluginSourceServiceTests() _ = typeof(TextAsset); _ = typeof(PluginSourceService); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(PluginSourceServiceTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(PluginSourceServiceTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); m_settings = new ProjectSettingsStore( @@ -60,7 +62,8 @@ public PluginSourceServiceTests() m_types, m_serialization, new ProjectId("tests.plugins"), - SerializationContext.empty); + SerializationContext.empty + ); } public void Dispose() @@ -74,7 +77,9 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -157,20 +162,14 @@ public void CodePluginActivatesImmediatelyAfterValidation() [Fact] public void FolderPluginIsRejectedAsANonPackageInstallation() { - WriteDirectoryPlugin( - "InstalledPlugin", - Manifest("tests.directory"), - TextContent("content")); + WriteDirectoryPlugin("InstalledPlugin", Manifest("tests.directory"), TextContent("content")); var service = new PluginSourceService(m_serialization, m_plugins, m_library); PluginScanResult scan = service.Scan(); Assert.Empty(scan.candidates); PluginDiagnostic diagnostic = Assert.Single(scan.diagnostics); - Assert.Contains( - ".iplugin package", - diagnostic.message, - StringComparison.OrdinalIgnoreCase); + Assert.Contains(".iplugin package", diagnostic.message, StringComparison.OrdinalIgnoreCase); } [Fact] @@ -185,7 +184,8 @@ public void RemovingAnActiveCodePackageKeepsTheLastGoodSnapshotUntilAtomicRemova { ["Assets/Plugin.cs"] = "public sealed class RemovedPackageEntry { }"u8.ToArray(), ["Assets/Plugin.cs.imeta"] = CreateTextSourceMeta() - }); + } + ); var service = new PluginSourceService(m_serialization, m_plugins, m_library); PluginScanResult initial = service.Scan(); InitializeProjectAssets(); @@ -214,9 +214,7 @@ public void RemovingAnActiveCodePackageKeepsTheLastGoodSnapshotUntilAtomicRemova m_environment.CommitPending(); Assert.Empty(m_environment.activePlugins); - Assert.Collection( - m_assets.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Collection(m_assets.sourceMounts, mount => Assert.Equal(AssetSourceId.project, mount.id)); } [Fact] @@ -231,7 +229,8 @@ public void StructurallyInvalidActivePluginStagesAnUnavailableGeneration() { ["Assets/Plugin.cs"] = "public sealed class InvalidatedPackageEntry { }"u8.ToArray(), ["Assets/Plugin.cs.imeta"] = CreateTextSourceMeta() - }); + } + ); var service = new PluginSourceService(m_serialization, m_plugins, m_library); InitializeProjectAssets(); StartEnvironment(service.Scan()); @@ -252,9 +251,7 @@ public void StructurallyInvalidActivePluginStagesAnUnavailableGeneration() m_environment.CommitPending(); Assert.Empty(m_environment.activePlugins); - Assert.Collection( - m_assets.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Collection(m_assets.sourceMounts, mount => Assert.Equal(AssetSourceId.project, mount.id)); } [Fact] @@ -268,7 +265,8 @@ public void InvalidAssetMetadataUpdateStagesAnUnavailableGenerationWithoutThrowi { ["Assets/Plugin.cs"] = "public sealed class InvalidAssetMetadataEntry { }"u8.ToArray(), ["Assets/Plugin.cs.imeta"] = CreateTextSourceMeta() - }); + } + ); var service = new PluginSourceService(m_serialization, m_plugins, m_library); InitializeProjectAssets(); StartEnvironment(service.Scan()); @@ -281,7 +279,8 @@ public void InvalidAssetMetadataUpdateStagesAnUnavailableGenerationWithoutThrowi { ["Assets/Plugin.cs"] = "public sealed class InvalidAssetMetadataEntry { }"u8.ToArray(), ["Assets/Plugin.cs.imeta"] = [1] - }); + } + ); Assert.True(m_environment.Refresh()); Assert.True(m_environment.hasPendingActivation); @@ -296,9 +295,7 @@ public void InvalidAssetMetadataUpdateStagesAnUnavailableGenerationWithoutThrowi m_environment.CommitPending(); Assert.Empty(m_environment.activePlugins); - Assert.Collection( - m_assets.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Collection(m_assets.sourceMounts, mount => Assert.Equal(AssetSourceId.project, mount.id)); } [Fact] @@ -352,10 +349,7 @@ public void FolderManifestCannotConflictWithAValidPackageIdentity() Assert.Equal("tests.same-source-id", Assert.Single(result.candidates).manifest.pluginId); PluginDiagnostic diagnostic = Assert.Single(result.diagnostics); - Assert.Contains( - ".iplugin package", - diagnostic.message, - StringComparison.OrdinalIgnoreCase); + Assert.Contains(".iplugin package", diagnostic.message, StringComparison.OrdinalIgnoreCase); } [Fact] @@ -381,8 +375,10 @@ public void DependencyGraphUsesDeterministicTopologicalOrderAndRejectsCycles() [InlineData("../escape.txt", "non-portable segment")] [InlineData("Assets/missing.txt", "missing its required .imeta sidecar")] [InlineData("Assets/native.dll", "forbidden prebuilt binary")] - public void UnsafeOrIncompleteArchivesAreIsolatedAsDiagnostics(string entryPath, string expectedMessage) - { + public void UnsafeOrIncompleteArchivesAreIsolatedAsDiagnostics( + string entryPath, + string expectedMessage + ) { Dictionary entries = TextContent("safe"); entries.Remove("Assets/content.txt"); entries.Remove("Assets/content.txt.imeta"); @@ -421,8 +417,8 @@ public void PortableCaseCollisionsAreRejectedBeforeExtraction() [InlineData("Assets/e\u0301.txt", "Unicode-normalized")] public void PlatformSpecificAndNonNormalizedPathsAreRejected( string entryPath, - string expectedMessage) - { + string expectedMessage + ) { WritePlugin("portable.iplugin", Manifest("tests.portable"), new Dictionary { [entryPath] = [1], @@ -461,7 +457,8 @@ public void SymbolicLinksAndExcessiveEntryCountsAreRejectedBeforeExtraction() m_serialization, m_plugins, m_library, - new PluginSourceLimits { maximumEntryCount = 2 }); + new PluginSourceLimits { maximumEntryCount = 2 } + ); PluginScanResult entryCount = entryCountService.Scan(); @@ -473,8 +470,10 @@ public void SymbolicLinksAndExcessiveEntryCountsAreRejectedBeforeExtraction() [InlineData("file", "file-size limit")] [InlineData("total", "total uncompressed-size limit")] [InlineData("ratio", "compression-ratio limit")] - public void ArchiveLimitsRejectOversizedOrSuspiciousContent(string scenario, string expectedMessage) - { + public void ArchiveLimitsRejectOversizedOrSuspiciousContent( + string scenario, + string expectedMessage + ) { byte[] first = scenario == "ratio" ? new byte[4096] : CreateNoise(1024, seed: 17); Dictionary entries = new() { @@ -520,10 +519,7 @@ public void ArchiveLimitsRejectOversizedOrSuspiciousContent(string scenario, str [Fact] public void CorruptManifestAndDuplicateEntriesAreIsolated() { - WritePluginWithManifestBytes( - "corrupt.iplugin", - [0x49, 0x4E, 0x4E, 0x4F], - TextContent("corrupt")); + WritePluginWithManifestBytes("corrupt.iplugin", [0x49, 0x4E, 0x4E, 0x4F], TextContent("corrupt")); WriteArchiveWithDuplicateEntry("duplicate.iplugin"); var service = new PluginSourceService(m_serialization, m_plugins, m_library); @@ -563,16 +559,18 @@ public void SettingsCompositionRejectsPeersAllowsExplicitDependencyOverrideAndKe ProjectSettingRecord first = SettingRecord(10); ProjectSettingRecord second = SettingRecord(20); m_settings.Rebuild( - [ - new ProjectSettingsContributor("tests.first", [], [], [first]) - ]); + [ + new ProjectSettingsContributor("tests.first", [], [], [first]) + ] + ); Assert.Equal(10, m_settings.Get(PluginDefaultTestSetting.id).value); Assert.Throws(() => m_settings.Rebuild( - [ - new ProjectSettingsContributor("tests.first", [], [], [first]), - new ProjectSettingsContributor("tests.peer", [], [], [second]) - ])); + [ + new ProjectSettingsContributor("tests.first", [], [], [first]), + new ProjectSettingsContributor("tests.peer", [], [], [second]) + ] + )); Assert.Equal(10, m_settings.Get(PluginDefaultTestSetting.id).value); ProjectSettingsContributor[] overridden = @@ -586,11 +584,13 @@ public void SettingsCompositionRejectsPeersAllowsExplicitDependencyOverrideAndKe m_settings.SetProjectOverride( PluginDefaultTestSetting.id, new PluginDefaultTestSetting { value = 30 }, - overridden); + overridden + ); m_settings.Rebuild( - [ - new ProjectSettingsContributor("tests.first", [], [], [SettingRecord(40)]) - ]); + [ + new ProjectSettingsContributor("tests.first", [], [], [SettingRecord(40)]) + ] + ); Assert.Equal(30, m_settings.Get(PluginDefaultTestSetting.id).value); } @@ -612,9 +612,7 @@ public void InitialActivationFailureKeepsTheHostOnlyMountAndPublishesDiscoveryDi Assert.Single(m_environment!.discovery.candidates); Assert.Contains(m_environment!.discovery.diagnostics, diagnostic => diagnostic.message.Contains("candidate activation failed", StringComparison.OrdinalIgnoreCase)); - Assert.Collection( - m_assets!.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Collection(m_assets!.sourceMounts, mount => Assert.Equal(AssetSourceId.project, mount.id)); } [Fact] @@ -627,7 +625,8 @@ public void InitialActivationPublishesPluginSettingDefaultsWithoutAnEditorFronte new ProjectSettingRecord( PluginDefaultTestSetting.id, m_types.GetTypeRef(typeof(PluginDefaultTestSetting)).stableId, - m_serialization.CapturePropertiesData(contributed)) + m_serialization.CapturePropertiesData(contributed) + ) ]; WritePlugin("settings.iplugin", manifest, new Dictionary { @@ -643,7 +642,8 @@ public void InitialActivationPublishesPluginSettingDefaultsWithoutAnEditorFronte Assert.Equal("tests.settings", Assert.Single(m_environment!.activePlugins).manifest.pluginId); Assert.Equal( [AssetSourceId.project, new AssetSourceId("tests.settings")], - m_assets!.sourceMounts.Select(static mount => mount.id)); + m_assets!.sourceMounts.Select(static mount => mount.id) + ); Assert.Equal(42, m_settings.Get(PluginDefaultTestSetting.id).value); } @@ -663,23 +663,18 @@ public void CodePluginUpdate_RemainsInvisibleWhileItsCompilationCandidateIsPendi Assert.True(m_environment!.hasPendingActivation); Assert.Empty(m_environment!.activePlugins); - Assert.Collection( - m_assets!.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); - Assert.Equal( - "tests.staged-code", - Assert.Single(m_environment!.compilationPlugins).manifest.pluginId); + Assert.Collection(m_assets!.sourceMounts, mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Equal("tests.staged-code", Assert.Single(m_environment!.compilationPlugins).manifest.pluginId); Assert.Contains( m_environment!.compilationAssets!.GetFileSystemEntries(includeDirectories: false), - entry => entry.assetPath == new AssetPath(new AssetSourceId("tests.staged-code"), "Plugin.cs")); + entry => entry.assetPath == new AssetPath(new AssetSourceId("tests.staged-code"), "Plugin.cs") + ); m_environment!.RollbackPending(); Assert.False(m_environment!.hasPendingActivation); Assert.Empty(m_environment!.activePlugins); - Assert.Collection( - m_assets!.sourceMounts, - mount => Assert.Equal(AssetSourceId.project, mount.id)); + Assert.Collection(m_assets!.sourceMounts, mount => Assert.Equal(AssetSourceId.project, mount.id)); } [Theory] @@ -712,7 +707,10 @@ public void CandidateObserverPendingKeepsTheCandidateAndStopsLaterObservers(bool Assert.Contains(ordinary, failure.InnerExceptions); Assert.Contains(pending, failure.InnerExceptions); } - else Assert.Same(pending, failure); + else + { + Assert.Same(pending, failure); + } Assert.False(laterCalled); Assert.True(m_environment.hasPendingActivation); Assert.NotNull(m_environment.compilationAssets); @@ -780,9 +778,7 @@ public void SourceMountCandidate_TransfersLiveIdentitiesOnlyDuringActivation() InitializeProjectAssets(); var service = new PluginSourceService(m_serialization, m_plugins, m_library); StartEnvironment(service.Scan()); - Assert.True(m_assets!.TryGetFileSystemEntry( - AssetPath.Project(string.Empty), - out AssetFileEntry activeEntry)); + Assert.True(m_assets!.TryGetFileSystemEntry(AssetPath.Project(string.Empty), out AssetFileEntry activeEntry)); Assert.NotNull(activeEntry.identity.runtimeIdentity); WritePlugin(c_fileName, Manifest("tests.identity-handoff"), new Dictionary @@ -793,10 +789,12 @@ public void SourceMountCandidate_TransfersLiveIdentitiesOnlyDuringActivation() Assert.True(m_environment!.Refresh()); AssetSourceMountTransaction candidate = Assert.IsType( - m_environment.compilationAssets); + m_environment.compilationAssets + ); AssetFileEntry candidateEntry = Assert.Single( candidate.GetFileSystemEntries(), - static entry => entry.assetPath == AssetPath.Project(string.Empty)); + static entry => entry.assetPath == AssetPath.Project(string.Empty) + ); Assert.Equal(activeEntry.identity.persistentId, candidateEntry.identity.persistentId); Assert.NotNull(activeEntry.identity.runtimeIdentity); Assert.Null(candidateEntry.identity.runtimeIdentity); @@ -804,9 +802,7 @@ public void SourceMountCandidate_TransfersLiveIdentitiesOnlyDuringActivation() m_environment.ActivatePending(); Assert.Null(activeEntry.identity.runtimeIdentity); - Assert.True(m_assets.TryGetFileSystemEntry( - AssetPath.Project(string.Empty), - out AssetFileEntry activatedEntry)); + Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project(string.Empty), out AssetFileEntry activatedEntry)); Assert.Equal(activeEntry.identity.persistentId, activatedEntry.identity.persistentId); Assert.NotNull(activatedEntry.identity.runtimeIdentity); @@ -814,9 +810,7 @@ public void SourceMountCandidate_TransfersLiveIdentitiesOnlyDuringActivation() Assert.NotNull(activeEntry.identity.runtimeIdentity); Assert.Null(activatedEntry.identity.runtimeIdentity); - Assert.True(m_assets.TryGetFileSystemEntry( - AssetPath.Project(string.Empty), - out AssetFileEntry restoredEntry)); + Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project(string.Empty), out AssetFileEntry restoredEntry)); Assert.Same(activeEntry, restoredEntry); } @@ -842,29 +836,33 @@ public void SourceWatcherDebouncesChangesAndActivatesOnTheOwnerThread() Assert.Equal("tests.watched", Assert.Single(m_environment.activePlugins).manifest.pluginId); Assert.Equal( [AssetSourceId.project, new AssetSourceId("tests.watched")], - m_assets!.sourceMounts.Select(static mount => mount.id)); + m_assets!.sourceMounts.Select(static mount => mount.id) + ); } - private static PluginManifest Manifest(string id, params string[] dependencies) - => new() - { - pluginId = id, - displayName = id, - dependencies = dependencies - }; + private static PluginManifest Manifest( + string id, + params string[] dependencies + ) => new() + { + pluginId = id, + displayName = id, + dependencies = dependencies + }; private static Dictionary TextContent(string value) => new() - { - ["Assets/content.txt"] = System.Text.Encoding.UTF8.GetBytes(value), - ["Assets/content.txt.imeta"] = [1] - }; + { + ["Assets/content.txt"] = System.Text.Encoding.UTF8.GetBytes(value), + ["Assets/content.txt.imeta"] = [1] + }; private ProjectSettingRecord SettingRecord(int value) => new( PluginDefaultTestSetting.id, m_types.GetTypeRef(typeof(PluginDefaultTestSetting)).stableId, - m_serialization.CapturePropertiesData(new PluginDefaultTestSetting { value = value })); + m_serialization.CapturePropertiesData(new PluginDefaultTestSetting { value = value }) + ); private PluginManifest ReadManifest(ZipArchive archive) { @@ -877,37 +875,35 @@ private PluginManifest ReadManifest(ZipArchive archive) private void WritePlugin( string fileName, PluginManifest manifest, - IReadOnlyDictionary entries) - => WritePluginWithManifestBytes(fileName, m_serialization.Serialize(manifest), entries); + IReadOnlyDictionary entries + ) => WritePluginWithManifestBytes(fileName, m_serialization.Serialize(manifest), entries); private void WritePluginWithManifestBytes( string fileName, byte[] manifestBytes, - IReadOnlyDictionary entries) - { + IReadOnlyDictionary entries + ) { string path = Path.Combine(m_plugins, fileName); using FileStream stream = System.IO.File.Create(path); using var archive = new ZipArchive(stream, ZipArchiveMode.Create); WriteEntry(archive, "Plugin.inno", manifestBytes); foreach ((string entryPath, byte[] bytes) in entries) + { WriteEntry(archive, entryPath, bytes); + } } private void WriteDirectoryPlugin( string directoryName, PluginManifest manifest, - IReadOnlyDictionary entries) - { + IReadOnlyDictionary entries + ) { string root = Path.Combine(m_plugins, directoryName); Directory.CreateDirectory(root); - System.IO.File.WriteAllBytes( - Path.Combine(root, "Plugin.inno"), - m_serialization.Serialize(manifest)); + System.IO.File.WriteAllBytes(Path.Combine(root, "Plugin.inno"), m_serialization.Serialize(manifest)); foreach ((string entryPath, byte[] bytes) in entries) { - string physicalPath = Path.Combine( - root, - entryPath.Replace('/', Path.DirectorySeparatorChar)); + string physicalPath = Path.Combine(root, entryPath.Replace('/', Path.DirectorySeparatorChar)); Directory.CreateDirectory(Path.GetDirectoryName(physicalPath)!); System.IO.File.WriteAllBytes(physicalPath, bytes); } @@ -924,8 +920,10 @@ private void WriteArchiveWithDuplicateEntry(string fileName) WriteEntry(archive, "Assets/value.txt.imeta", [1]); } - private static byte[] CreateNoise(int length, int seed) - { + private static byte[] CreateNoise( + int length, + int seed + ) { var result = new byte[length]; new Random(seed).NextBytes(result); return result; @@ -947,7 +945,8 @@ private void InitializeProjectAssets() defaults with { enableFileSystemWatcher = false - }); + } + ); } private void StartEnvironment(PluginScanResult scan) @@ -959,7 +958,8 @@ private void StartEnvironment(PluginScanResult scan) m_plugins, m_library, scan, - m_modules.generations); + m_modules.generations + ); } private byte[] CreateTextSourceMeta() @@ -970,8 +970,11 @@ private byte[] CreateTextSourceMeta() importerId = "inno.assets.text" }); - private static void WriteEntry(ZipArchive archive, string path, byte[] bytes) - { + private static void WriteEntry( + ZipArchive archive, + string path, + byte[] bytes + ) { ZipArchiveEntry entry = archive.CreateEntry(path, CompressionLevel.Optimal); using Stream output = entry.Open(); output.Write(bytes); @@ -979,9 +982,7 @@ private static void WriteEntry(ZipArchive archive, string path, byte[] bytes) } [CollectionDefinition("Plugin source serialization", DisableParallelization = true)] -public sealed class PluginSourceSerializationCollection -{ -} +public sealed class PluginSourceSerializationCollection; [StableTypeId("706c1248-478b-43f1-a44d-98a1a8f7b919")] [ProjectSettingDefinition("tests.plugins.default")] diff --git a/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs b/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs index ac58d0f93..ace074165 100644 --- a/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs +++ b/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs @@ -23,8 +23,7 @@ public sealed class DiscoveryLogger : ITestLoggerWithParameters public void Initialize( TestLoggerEvents events, string testRunDirectory - ) => - throw new ArgumentException("Discovery requires an explicit receipt path."); + ) => throw new ArgumentException("Discovery requires an explicit receipt path."); /// /// @@ -35,7 +34,9 @@ public void Initialize( Dictionary parameters ) { if (!parameters.TryGetValue("Receipt", out string? receipt) || !Path.IsPathFullyQualified(receipt ?? string.Empty)) + { throw new ArgumentException("Discovery requires an absolute receipt path."); + } var owners = new Dictionary(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); var errors = new List(); @@ -45,7 +46,9 @@ public void Initialize( ) => { if (message.Level == TestMessageLevel.Error) + { errors.Add(message.Message ?? "Discovery emitted an unspecified error."); + } }; events.DiscoveredTests += ( _, @@ -56,10 +59,14 @@ public void Initialize( { string source = Path.GetFullPath(test.Source); if (!owners.TryGetValue(source, out Owner? owner)) + { owners.Add(source, owner = new Owner()); + } owner.Count++; if (test.Traits.Any(trait => trait.Name == "ProcessIsolation" && trait.Value == "Required")) + { owner.Contracts.Add(test.FullyQualifiedName); + } } }; events.DiscoveryComplete += ( @@ -71,9 +78,9 @@ public void Initialize( JsonSerializer.Serialize(output, new { completed = !completion.IsAborted && errors.Count == 0 - && completion.PartiallyDiscoveredSources?.Count is null or 0 - && completion.NotDiscoveredSources?.Count is null or 0 - && completion.SkippedDiscoveredSources?.Count is null or 0, + && completion.PartiallyDiscoveredSources?.Count is null or 0 + && completion.NotDiscoveredSources?.Count is null or 0 + && completion.SkippedDiscoveredSources?.Count is null or 0, errors, discovered = completion.TotalCount, owners = owners.Select(pair => new { source = pair.Key, count = pair.Value.Count, contracts = pair.Value.Contracts }) diff --git a/tests/process/Inno.Testing.Processes.Tests/NativeProcessHostFixture.cs b/tests/process/Inno.Testing.Processes.Tests/NativeProcessHostFixture.cs index f4f622b02..66d87deea 100644 --- a/tests/process/Inno.Testing.Processes.Tests/NativeProcessHostFixture.cs +++ b/tests/process/Inno.Testing.Processes.Tests/NativeProcessHostFixture.cs @@ -9,13 +9,19 @@ internal static class NativeProcessHostFixture private static int Main(string[] arguments) { if (arguments.Length != 1) + { return 2; + } Console.WriteLine("Fixture stdout: " + arguments[0]); Console.Error.WriteLine("Fixture stderr: " + arguments[0]); if (arguments[0] == "success") + { return 0; + } if (arguments[0] == "failure") + { return 3; + } if (arguments[0] == "timeout") { var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") diff --git a/tests/process/Inno.Testing.Processes.Tests/NativeProcessTestHostTests.cs b/tests/process/Inno.Testing.Processes.Tests/NativeProcessTestHostTests.cs index a60d9d092..a6915ae6e 100644 --- a/tests/process/Inno.Testing.Processes.Tests/NativeProcessTestHostTests.cs +++ b/tests/process/Inno.Testing.Processes.Tests/NativeProcessTestHostTests.cs @@ -9,7 +9,10 @@ namespace Inno.Testing.Processes.Tests; public sealed class NativeProcessTestHostTests { [Fact] - public void SuccessfulContractDrainsItsOutput() => NativeProcessTestHost.Run(typeof(NativeProcessHostFixture).Assembly.Location, "success"); + public void SuccessfulContractDrainsItsOutput() => NativeProcessTestHost.Run( + typeof(NativeProcessHostFixture).Assembly.Location, + "success" + ); [Fact] public void FailedContractRetainsBothStreamsAndIdentity() @@ -42,7 +45,9 @@ public void TimeoutRetainsPartialOutputAndTerminatesDescendants() public void RelativeAssemblyAndInvalidBudgetFailBeforeStarting() { Assert.Throws(() => NativeProcessTestHost.Run("relative.dll", "success")); - Assert.Throws(() => NativeProcessTestHost.Run(typeof(NativeProcessHostFixture).Assembly.Location, "success", 0)); + Assert.Throws( + () => NativeProcessTestHost.Run(typeof(NativeProcessHostFixture).Assembly.Location, "success", 0) + ); } private static bool HasExited(int processId) diff --git a/tests/process/Inno.Testing.Processes/NativeProcessTestHost.cs b/tests/process/Inno.Testing.Processes/NativeProcessTestHost.cs index 9de53e682..4c797d627 100644 --- a/tests/process/Inno.Testing.Processes/NativeProcessTestHost.cs +++ b/tests/process/Inno.Testing.Processes/NativeProcessTestHost.cs @@ -44,7 +44,9 @@ public static void Run( ArgumentException.ThrowIfNullOrWhiteSpace(contract); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(timeoutMilliseconds); if (!Path.IsPathFullyQualified(assembly)) + { throw new ArgumentException("A contract assembly requires an absolute path.", nameof(assembly)); + } var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") { UseShellExecute = false, @@ -69,7 +71,9 @@ public static void Run( ) => Capture(data, error, errorClosed); Stopwatch elapsed = Stopwatch.StartNew(); if (!process.Start()) + { throw new InvalidOperationException("The native contract host did not start."); + } process.BeginOutputReadLine(); process.BeginErrorReadLine(); bool timedOut = !process.WaitForExit(timeoutMilliseconds); @@ -80,7 +84,9 @@ public static void Run( { process.Kill(entireProcessTree: true); if (!process.WaitForExit(10_000)) + { cleanup = "The process tree did not exit within the cleanup budget."; + } } catch (Exception failure) { @@ -91,12 +97,14 @@ public static void Run( if (timedOut || !drained || process.ExitCode != 0) { string diagnostic = $"Native contract '{contract}', PID {process.Id}, elapsed {elapsed.Elapsed}.\n" - + $"Command: {start.FileName} {assembly} {contract}\n" - + $"TimedOut={timedOut}; OutputDrained={drained}. {cleanup}\n" - + "stdout:\n" + string.Join(Environment.NewLine, output) - + "\nstderr:\n" + string.Join(Environment.NewLine, error); + + $"Command: {start.FileName} {assembly} {contract}\n" + + $"TimedOut={timedOut}; OutputDrained={drained}. {cleanup}\n" + + "stdout:\n" + string.Join(Environment.NewLine, output) + + "\nstderr:\n" + string.Join(Environment.NewLine, error); if (timedOut) + { throw new TimeoutException(diagnostic); + } throw new InvalidOperationException(diagnostic); } } @@ -107,8 +115,12 @@ private static void Capture( TaskCompletionSource closed ) { if (data.Data is string line) + { destination.Enqueue(line); + } else + { closed.TrySetResult(); + } } } diff --git a/tests/references/Inno.References.Tests/ContentReadScopeTests.cs b/tests/references/Inno.References.Tests/ContentReadScopeTests.cs index cbb6310e0..610ab0e24 100644 --- a/tests/references/Inno.References.Tests/ContentReadScopeTests.cs +++ b/tests/references/Inno.References.Tests/ContentReadScopeTests.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; -using Inno.Core.Identity; using Xunit; +using Inno.Core.Identity; namespace Inno.References.Tests; diff --git a/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs b/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs index 90595fe16..dae289364 100644 --- a/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs +++ b/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; +using Xunit; using Inno.Core.Identity; using Inno.Extensibility.Reload; using Inno.References; -using Xunit; namespace Inno.References.Tests; @@ -42,16 +42,11 @@ public void RecoveryTransaction_RollsBackAppliedParticipantsInReverseOrder() var target = new Target(); Assert.True(allocator.Register(target)); var descriptor = new ReferenceDescriptor(S_KIND, target.identity.persistentId); - var catalog = ReferenceCatalog.Create( - 1, - [new FixedResolver(S_KIND, target.identity.runtimeIdentity)]); + var catalog = ReferenceCatalog.Create(1, [new FixedResolver(S_KIND, target.identity.runtimeIdentity)]); var events = new List(); var first = new RecordingParticipant("first", events); var second = new RecordingParticipant("second", events, failApply: true); - var state = new SerializedMissingState( - new ReferenceKey(Guid.NewGuid(), "portrait"), - descriptor, - [1, 2, 3]); + var state = new SerializedMissingState(new ReferenceKey(Guid.NewGuid(), "portrait"), descriptor, [1, 2, 3]); var transaction = new ReferenceRecoveryTransaction(catalog, [state], [first, second]); transaction.PrepareForActivation(); @@ -91,8 +86,11 @@ public void RecoveryResolvesOnlyAfterObjectsExistAndRetainsNeutralResultsAfterCo [Fact] public void RecoveryRejectsDuplicateSlotsAndOutOfOrderPhases() { - var state = new SerializedMissingState(new ReferenceKey(Guid.NewGuid(), "asset"), - new ReferenceDescriptor(S_KIND, Guid.NewGuid()), []); + var state = new SerializedMissingState( + new ReferenceKey(Guid.NewGuid(), "asset"), + new ReferenceDescriptor(S_KIND, Guid.NewGuid()), + [] + ); Assert.Throws(() => new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [state, state], [])); var transaction = new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [state], []); Assert.Throws(transaction.Apply); @@ -102,27 +100,28 @@ public void RecoveryRejectsDuplicateSlotsAndOutOfOrderPhases() transaction.RestorePreviousState(); } - private sealed class Target : IdentityObject - { - } + private sealed class Target : IdentityObject; - private sealed class FixedResolver(ReferenceKindId kindId, RuntimeIdentity? runtimeIdentity) : IReferenceResolver + private sealed class FixedResolver( + ReferenceKindId kindId, + RuntimeIdentity? runtimeIdentity + ) : IReferenceResolver { public ReferenceKindId kindId { get; } = kindId; public ReferenceResolution Resolve(ReferenceDescriptor descriptor) => runtimeIdentity.HasValue - ? new ReferenceResolution(descriptor, ReferenceResolutionState.Resolved, runtimeIdentity) - : new ReferenceResolution(descriptor, ReferenceResolutionState.Missing); + ? new ReferenceResolution(descriptor, ReferenceResolutionState.Resolved, runtimeIdentity) + : new ReferenceResolution(descriptor, ReferenceResolutionState.Missing); } private sealed class RecordingParticipant( string name, ICollection events, - bool failApply = false) : IReferenceRecoveryParticipant + bool failApply = false + ) : IReferenceRecoveryParticipant { - public void Validate(IReadOnlyList changes) - => events.Add($"validate:{name}"); + public void Validate(IReadOnlyList changes) => events.Add($"validate:{name}"); public void PrepareForActivation() => events.Add($"prepare:{name}"); @@ -130,13 +129,15 @@ public void Apply() { events.Add($"apply:{name}"); if (failApply) + { throw new InvalidOperationException("expected apply failure"); + } } - public void RollbackStructure() - => events.Add($"rollback:{name}"); + public void RollbackStructure() => events.Add($"rollback:{name}"); public void RestorePreviousState() => events.Add($"restore:{name}"); + public void Complete() => events.Add($"complete:{name}"); } } diff --git a/tests/references/Inno.References.Tests/ReferenceRecoveryTests.cs b/tests/references/Inno.References.Tests/ReferenceRecoveryTests.cs index f08ab5dfa..1ec44794c 100644 --- a/tests/references/Inno.References.Tests/ReferenceRecoveryTests.cs +++ b/tests/references/Inno.References.Tests/ReferenceRecoveryTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Threading; +using Xunit; using Inno.Core.Execution; using Inno.Extensibility.Reload; -using Xunit; namespace Inno.References.Tests; @@ -43,27 +43,45 @@ public void CandidateFailureCompensatesAttemptedOwnersAroundPublication(string p [InlineData("complete", true)] [InlineData("structure", true)] [InlineData("restore", true)] - public void PendingRetirementKeepsOwnersAndFaultsTheSharedGate(string phase, bool wrapped) - { + public void PendingRetirementKeepsOwnersAndFaultsTheSharedGate( + string phase, + bool wrapped + ) { var events = new List(); var first = new Participant("first", events); var pending = new Participant("pending", events, phase, pending: true, wrapped: wrapped); var gate = new GenerationCoordinator(); - var recovery = new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], - phase == "complete" ? [pending, first] : [first, pending]); - Exception failure = Assert.ThrowsAny(() => gate.Execute("recovery", new Publication(events, phase != "complete"), [recovery])); - if (wrapped || phase != "complete") Assert.IsType(failure); - else Assert.IsType(failure); + var recovery = new ReferenceRecoveryTransaction( + ReferenceCatalog.empty, + [], + phase == "complete" ? [pending, first] : [first, pending] + ); + Exception failure = Assert.ThrowsAny( + () => gate.Execute("recovery", new Publication(events, phase != "complete"), [recovery]) + ); + if (wrapped || phase != "complete") + { + Assert.IsType(failure); + } + else + { + Assert.IsType(failure); + } Assert.Same(failure, gate.failure); Assert.Equal(GenerationState.Faulted, gate.state); Assert.DoesNotContain($"{phase}:first", events); Exception retained = Assert.ThrowsAny(recovery.Complete); - if (phase == "complete") Assert.Same(failure, retained); + if (phase == "complete") + { + Assert.Same(failure, retained); + } else { Assert.Contains(retained, Assert.IsType(failure).InnerExceptions); - Assert.Contains(Assert.IsType(failure).InnerExceptions, - item => item.Message == "Rejected publication."); + Assert.Contains( + Assert.IsType(failure).InnerExceptions, + item => item.Message == "Rejected publication." + ); } Assert.Same(retained, Assert.ThrowsAny(recovery.RollbackStructure)); Assert.Same(retained, Assert.ThrowsAny(recovery.RestorePreviousState)); @@ -75,8 +93,11 @@ public void PendingRetirementKeepsOwnersAndFaultsTheSharedGate(string phase, boo public void OrdinaryCleanupFailureStillRetiresOtherOwnersAndCannotPretendToRollback() { var events = new List(); - var recovery = new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], - [new Participant("first", events, "complete"), new Participant("second", events)]); + var recovery = new ReferenceRecoveryTransaction( + ReferenceCatalog.empty, + [], + [new Participant("first", events, "complete"), new Participant("second", events)] + ); var gate = new GenerationCoordinator(); Assert.Throws(() => gate.Execute("recovery", new Publication(events), [recovery])); Assert.Contains("complete:second", events); @@ -95,8 +116,11 @@ public void EarlierParticipantFailureIsRetainedAlongsidePendingOwnership(string var ordinary = new Participant("ordinary", events, phase); var pending = new Participant("pending", events, phase, pending: true); var dependency = new Participant("dependency", events); - var recovery = new ReferenceRecoveryTransaction(ReferenceCatalog.empty, [], - phase == "complete" ? [ordinary, pending, dependency] : [dependency, pending, ordinary]); + var recovery = new ReferenceRecoveryTransaction( + ReferenceCatalog.empty, + [], + phase == "complete" ? [ordinary, pending, dependency] : [dependency, pending, ordinary] + ); recovery.PrepareForActivation(); Action finish; if (phase == "complete") @@ -104,7 +128,10 @@ public void EarlierParticipantFailureIsRetainedAlongsidePendingOwnership(string recovery.Apply(); finish = recovery.Complete; } - else if (phase == "structure") finish = recovery.RollbackStructure; + else if (phase == "structure") + { + finish = recovery.RollbackStructure; + } else { recovery.RollbackStructure(); @@ -125,8 +152,14 @@ public void RecoveryRejectsAnotherThreadBeforeInvokingDomainCode() Exception? failure = null; var thread = new Thread(() => { - try { recovery.PrepareForActivation(); } - catch (Exception exception) { failure = exception; } + try + { + recovery.PrepareForActivation(); + } + catch (Exception exception) + { + failure = exception; + } }); thread.Start(); thread.Join(); @@ -136,41 +169,64 @@ public void RecoveryRejectsAnotherThreadBeforeInvokingDomainCode() recovery.RestorePreviousState(); } - private sealed class Participant(string name, ICollection events, string? failurePhase = null, - bool pending = false, bool wrapped = false) : IReferenceRecoveryParticipant + private sealed class Participant( + string name, + ICollection events, + string? failurePhase = null, + bool pending = false, + bool wrapped = false + ) : IReferenceRecoveryParticipant { public void PrepareForActivation() => Run("prepare"); + public void Apply() => Run("apply"); + public void Validate(IReadOnlyList changes) => Run("validate"); + public void Complete() => Run("complete"); + public void RollbackStructure() => Run("structure"); + public void RestorePreviousState() => Run("restore"); private void Run(string phase) { events.Add($"{phase}:{name}"); if (phase != failurePhase) + { return; + } if (pending) { if (wrapped) - throw new AggregateException(new InvalidOperationException("completed sibling"), - new InvalidOperationException("owner context", new RetirementPendingException("Pending reference owner."))); + { + throw new AggregateException( + new InvalidOperationException("completed sibling"), + new InvalidOperationException("owner context", new RetirementPendingException("Pending reference owner.")) + ); + } throw new RetirementPendingException("Pending reference owner."); } throw new InvalidOperationException("Rejected reference owner."); } } - private sealed class Publication(ICollection events, bool failApply = false) : IGenerationPublication + private sealed class Publication( + ICollection events, + bool failApply = false + ) : IGenerationPublication { public void Activate() { events.Add("publication:activate"); if (failApply) + { throw new InvalidOperationException("Rejected publication."); + } } + public void Rollback() => events.Add("publication:rollback"); + public Probe Complete() { events.Add("commit"); diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs index 816031b16..f7e9f62d2 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs @@ -1,17 +1,17 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Buffers.Binary; using System.Collections.Generic; using System.IO; using System.Text; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; -using Inno.Extensibility.Modules; using Inno.Core.Mathematics; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring.Tests; @@ -26,7 +26,9 @@ public sealed class MeshAndStateTests : IDisposable public MeshAndStateTests() { m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(MeshAndStateTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(MeshAndStateTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -53,8 +55,10 @@ public void MaterialAndPipelineState_RoundTripsThroughAssetSerialization() RenderSamplerFilter.Point, RenderSamplerAddressMode.Repeat, RenderSamplerAddressMode.Mirror, - RenderSamplerAddressMode.Clamp) - }); + RenderSamplerAddressMode.Clamp + ) + } + ); material.SetKeyword("Cutout", enabled: true); material.SetMetadata("tests.sort", "2450"); byte[] materialState = m_serialization.Encode(writer => writer.WriteProperties(material)); @@ -84,7 +88,8 @@ public void MaterialAndPipelineState_RoundTripsThroughAssetSerialization() new RenderFeatureConfiguration( "tests.feature", new SerializedRenderExtensionState(Guid.Empty, [4, 5]), - enabled: true) + enabled: true + ) ]); byte[] pipelineState = m_serialization.Encode(writer => writer.WriteProperties(pipeline)); var restoredPipeline = new RenderPipelineAsset(); @@ -107,49 +112,66 @@ public void MaterialResolver_UsesProviderOwnedContractsRolesAndCapabilities() var advancedPass = new ShaderPassDefinition( "advanced-draw", ShaderProgramKind.Raster, - requiredFeatures: GraphicsCapability.Compute); + requiredFeatures: GraphicsCapability.Compute + ); var basicPass = new ShaderPassDefinition("basic-draw", ShaderProgramKind.Raster); var shader = new ShaderAsset(); - shader.SetDefinition(new ShaderDefinition( - "Provider-owned shader", - [], - [], - [advancedPass, basicPass], - [ - new ShaderTechniqueDefinition( - new ShaderTechniqueId("advanced"), - new ShaderContractId("example.2d.sprite"), - [new ShaderTechniquePass(new ShaderPassRoleId("draw"), advancedPass.name)], - GraphicsCapability.Compute), - new ShaderTechniqueDefinition( - new ShaderTechniqueId("basic"), - new ShaderContractId("example.2d.sprite"), - [new ShaderTechniquePass(new ShaderPassRoleId("draw"), basicPass.name)]) - ]), m_serialization, SerializationContext.empty); + shader.SetDefinition( + new ShaderDefinition( + "Provider-owned shader", + [], + [], + [advancedPass, basicPass], + [ + new ShaderTechniqueDefinition( + new ShaderTechniqueId("advanced"), + new ShaderContractId("example.2d.sprite"), + [new ShaderTechniquePass(new ShaderPassRoleId("draw"), advancedPass.name)], + GraphicsCapability.Compute + ), + new ShaderTechniqueDefinition( + new ShaderTechniqueId("basic"), + new ShaderContractId("example.2d.sprite"), + [new ShaderTechniquePass(new ShaderPassRoleId("draw"), basicPass.name)] + ) + ] + ), + m_serialization, + SerializationContext.empty + ); var material = new MaterialAsset { shader = shader }; GraphicsCapabilities basicCapabilities = CreateCapabilities(GraphicsCapability.None); GraphicsCapabilities computeCapabilities = CreateCapabilities(GraphicsCapability.Compute); - MaterialPassResolution basic = Assert.IsType(MaterialPassResolver.Resolve( - material, - new ShaderContractId("example.2d.sprite"), - new ShaderPassRoleId("draw"), - basicCapabilities)); - MaterialPassResolution advanced = Assert.IsType(MaterialPassResolver.Resolve( - material, - new ShaderContractId("example.2d.sprite"), - new ShaderPassRoleId("draw"), - computeCapabilities)); + MaterialPassResolution basic = Assert.IsType( + MaterialPassResolver.Resolve( + material, + new ShaderContractId("example.2d.sprite"), + new ShaderPassRoleId("draw"), + basicCapabilities + ) + ); + MaterialPassResolution advanced = Assert.IsType( + MaterialPassResolver.Resolve( + material, + new ShaderContractId("example.2d.sprite"), + new ShaderPassRoleId("draw"), + computeCapabilities + ) + ); Assert.Equal("basic", basic.technique.id.value); Assert.Equal("basic-draw", basic.pass.name); Assert.Equal("advanced", advanced.technique.id.value); Assert.Equal("advanced-draw", advanced.pass.name); - Assert.Null(MaterialPassResolver.Resolve( - material, - new ShaderContractId("unrelated.contract"), - new ShaderPassRoleId("draw"), - computeCapabilities)); + Assert.Null( + MaterialPassResolver.Resolve( + material, + new ShaderContractId("unrelated.contract"), + new ShaderPassRoleId("draw"), + computeCapabilities + ) + ); } [Fact] @@ -161,16 +183,18 @@ public void ShaderRasterState_RoundTripsWithoutLosingProviderChoices() sourceState.frontFace = RenderFrontFace.Clockwise; sourceState.multisampling = false; var source = new ShaderAsset(); - source.SetDefinition(new ShaderDefinition( - "Tests/RasterState", - [], - [], - [ - new ShaderPassDefinition( - "wire", - ShaderProgramKind.Raster, - renderState: sourceState) - ]), m_serialization, SerializationContext.empty); + source.SetDefinition( + new ShaderDefinition( + "Tests/RasterState", + [], + [], + [ + new ShaderPassDefinition("wire", ShaderProgramKind.Raster, renderState: sourceState) + ] + ), + m_serialization, + SerializationContext.empty + ); byte[] state = m_serialization.Encode(writer => writer.WriteProperties(source)); var restored = new ShaderAsset(); @@ -217,10 +241,9 @@ private static GraphicsCapabilities CreateCapabilities(GraphicsCapability featur [], [], originBottomLeft: false, - homogeneousDepth: false); + homogeneousDepth: false + ); } [CollectionDefinition("Rendering assets serialization", DisableParallelization = true)] -public sealed class RenderingAssetsSerializationCollection -{ -} +public sealed class RenderingAssetsSerializationCollection; diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs index 2ac378e28..9fbd65468 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs @@ -1,28 +1,28 @@ -using Inno.Integration.MacOSArm64.Bgfx; -using Inno.Content.Testing; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Buffers.Binary; using System.Collections.Generic; using System.IO; -using System.Text; using System.Linq; -using Inno.Build.Toolchains.Bgfx.Tools; -using Inno.Core.Graphs; -using Inno.Rendering.Shaders; +using System.Text; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Content.Testing; using Inno.Core.Diagnostics; -using Inno.Extensibility.Modules; +using Inno.Core.Graphs; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Runtime; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring.Tests; @@ -48,7 +48,9 @@ public RenderingImporterIntegrationTests() Directory.CreateDirectory(m_assets); m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(RenderingImporterIntegrationTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(RenderingImporterIntegrationTests).Assembly) + }); _ = typeof(AssetSerializationServices); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); @@ -64,7 +66,9 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -73,10 +77,22 @@ public void LoaderUsesGraphShaderMaterialAndPipelineAssetsWithOneCompilationMode GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); definition.name = "Tests/Basic"; - definition.properties = [.. definition.properties, new(new("roughness"), "Roughness", ShaderPropertyType.Float, - ShaderStage.Fragment, MaterialValue.FromFloat(0.5f))]; + definition.properties = + [ + .. definition.properties, + new( + new("roughness"), + "Roughness", + ShaderPropertyType.Float, + ShaderStage.Fragment, + MaterialValue.FromFloat(0.5f) + ) + ]; definition.techniques = [new(new("default"), new("tests.surface"), [new(new("draw"), "Main")])]; - graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); + graph.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); WriteBytes("Shaders/basic.ishader", GraphDocumentCodec.Encode(graph, m_serialization)); WriteText("Meshes/triangle.obj", "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"); byte[] png = new byte[24]; @@ -104,25 +120,28 @@ public void LoaderUsesGraphShaderMaterialAndPipelineAssetsWithOneCompilationMode } using var loader = CreateLoader(m_assets, m_library); - ShaderAsset loadedShader = Assert.IsType(loader.Load( - AssetPath.Project("Shaders/basic.ishader"), - typeof(ShaderAsset))); - MaterialAsset loadedMaterial = Assert.IsType(loader.Load( - AssetPath.Project("Materials/basic.imaterial"), - typeof(MaterialAsset))); - RenderPipelineAsset loadedPipeline = Assert.IsType(loader.Load( - AssetPath.Project("Pipelines/default.irenderpipeline"), - typeof(RenderPipelineAsset))); - GeometryAsset geometry = Assert.IsType(loader.Load( - AssetPath.Project("Meshes/triangle.obj"), - typeof(GeometryAsset))); - TextureAsset texture = Assert.IsType(loader.Load( - AssetPath.Project("Textures/color.png"), - typeof(TextureAsset))); + ShaderAsset loadedShader = Assert.IsType( + loader.Load(AssetPath.Project("Shaders/basic.ishader"), typeof(ShaderAsset)) + ); + MaterialAsset loadedMaterial = Assert.IsType( + loader.Load(AssetPath.Project("Materials/basic.imaterial"), typeof(MaterialAsset)) + ); + RenderPipelineAsset loadedPipeline = Assert.IsType( + loader.Load(AssetPath.Project("Pipelines/default.irenderpipeline"), typeof(RenderPipelineAsset)) + ); + GeometryAsset geometry = Assert.IsType( + loader.Load(AssetPath.Project("Meshes/triangle.obj"), typeof(GeometryAsset)) + ); + TextureAsset texture = Assert.IsType( + loader.Load(AssetPath.Project("Textures/color.png"), typeof(TextureAsset)) + ); Assert.Equal("Tests/Basic", loadedShader.definition!.name); Assert.True(loadedShader.runtimePayload.IsEmpty); - Assert.Equal(graph.nodes.Count, ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(loadedShader, loader), m_serialization).nodes.Count); + Assert.Equal( + graph.nodes.Count, + ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(loadedShader, loader), m_serialization).nodes.Count + ); Assert.Same(loadedShader, loadedMaterial.shader); Assert.True(loadedMaterial.TryGet(new ShaderPropertyId("roughness"), out MaterialValue roughness)); Assert.Equal(0.25f, roughness.vector.x); @@ -148,11 +167,15 @@ public void ShaderIncludesUseTheCandidateMountSnapshotAndDeclaredPluginDependenc WriteReadOnlyShaderSource( providerRoot, "common.ishadersource", - "vec4 ProviderColor() { return vec4(0.2, 0.4, 0.6, 1.0); }", "ProviderColor"); + "vec4 ProviderColor() { return vec4(0.2, 0.4, 0.6, 1.0); }", + "ProviderColor" + ); WriteReadOnlyShaderSource( consumerRoot, "local.ishadersource", - "float LocalValue() { return 0.5; }", "LocalValue"); + "float LocalValue() { return 0.5; }", + "LocalValue" + ); WriteReadOnlyShaderSource( consumerRoot, "main.ishadersource", @@ -160,51 +183,56 @@ public void ShaderIncludesUseTheCandidateMountSnapshotAndDeclaredPluginDependenc #include "local.ishadersource" #include "tests.provider::common.ishadersource" vec4 Evaluate() { return ProviderColor() * LocalValue(); } - """); + """ + ); AssetSourceMount project = new(AssetSourceId.project, m_assets, isReadOnly: false); AssetSourceMount provider = new(providerId, providerRoot, isReadOnly: true); AssetSourceMount undeclaredConsumer = new(consumerId, consumerRoot, isReadOnly: true); using (var undeclared = CreateLoader( - [project, provider, undeclaredConsumer], - Path.Combine(m_root, "UndeclaredLibrary"))) - { + [project, provider, undeclaredConsumer], + Path.Combine(m_root, "UndeclaredLibrary") + )) { InvalidDataException error = Assert.Throws(() => undeclared.Rescan()); Assert.Contains("did not declare dependency", error.Message, StringComparison.OrdinalIgnoreCase); } - AssetSourceMount declaredConsumer = new( - consumerId, - consumerRoot, - isReadOnly: true, - dependencies: [providerId]); - using var loader = CreateLoader( - [project, provider, declaredConsumer], - Path.Combine(m_root, "DeclaredLibrary")); + AssetSourceMount declaredConsumer = new(consumerId, consumerRoot, isReadOnly: true, dependencies: [providerId]); + using var loader = CreateLoader([project, provider, declaredConsumer], Path.Combine(m_root, "DeclaredLibrary")); loader.Rescan(); - ShaderFunctionAsset shader = Assert.IsType(loader.Load( - new AssetPath(consumerId, "main.ishadersource"), typeof(ShaderFunctionAsset))); - ShaderSourceImplementationRequest request = Assert.Single(ShaderSourceBundle.Decode(ShaderSourceBundle.Read(shader, loader), "Evaluate", m_serialization)); + ShaderFunctionAsset shader = Assert.IsType( + loader.Load(new AssetPath(consumerId, "main.ishadersource"), typeof(ShaderFunctionAsset)) + ); + ShaderSourceImplementationRequest request = Assert.Single( + ShaderSourceBundle.Decode(ShaderSourceBundle.Read(shader, loader), "Evaluate", m_serialization) + ); using var frontends = new ShaderSourceFrontendRegistry(m_types); ShaderSourceModuleAnalysis analysis = frontends.AnalyzeModule([request]); Assert.True(analysis.succeeded, string.Join("\n", analysis.diagnostics.Select(static value => value.message))); Assert.Equal("Evaluate", Assert.Single(shader.exports)); Assert.Equal(3, Assert.Single(analysis.implementations).sources.Count); Assert.Equal( - [ - new AssetPath(consumerId, "local.ishadersource"), - new AssetPath(providerId, "common.ishadersource") - ], loader.GetImportDependencies(shader)); + [ + new AssetPath(consumerId, "local.ishadersource"), + new AssetPath(providerId, "common.ishadersource") + ], + loader.GetImportDependencies(shader) + ); } [Fact] public void RuntimeExportStripsGraphAndFunctionArtifactsAndPreservesShaderIdentityAndDefinition() { - WriteBytes("Surface.ishader", GraphDocumentCodec.Encode(ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty), m_serialization)); + WriteBytes( + "Surface.ishader", + GraphDocumentCodec.Encode(ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty), m_serialization) + ); WriteReadOnlyShaderSource(m_assets, "Function.ishadersource", "vec4 Evaluate(vec4 color) { return color; }"); using var loader = CreateLoader(m_assets, m_library); ShaderAsset shader = Assert.IsType(loader.Load(AssetPath.Project("Surface.ishader"), typeof(ShaderAsset))); - ShaderFunctionAsset function = Assert.IsType(loader.Load(AssetPath.Project("Function.ishadersource"), typeof(ShaderFunctionAsset))); + ShaderFunctionAsset function = Assert.IsType( + loader.Load(AssetPath.Project("Function.ishadersource"), typeof(ShaderFunctionAsset)) + ); Assert.NotEmpty(ShaderGraphArtifact.Read(shader, loader)); Assert.NotEmpty(ShaderSourceBundle.Read(function, loader)); string destination = Path.Combine(m_root, "PlayerContent"); @@ -230,31 +258,39 @@ public void RuntimeExportStripsGraphAndFunctionArtifactsAndPreservesShaderIdenti [Fact] public void OneShaderSourceLibraryExportsMultipleExplicitGraphFunctions() { - WriteReadOnlyShaderSource(m_assets, "Library.ishadersource", + WriteReadOnlyShaderSource( + m_assets, + "Library.ishadersource", "float Exposure(float value) { return value; }\nvec4 Tint(vec4 color) { return color; }", - "Exposure", "Tint"); + "Exposure", + "Tint" + ); using var loader = CreateLoader(m_assets, m_library); - ShaderFunctionAsset library = Assert.IsType(loader.Load( - AssetPath.Project("Library.ishadersource"), typeof(ShaderFunctionAsset))); + ShaderFunctionAsset library = Assert.IsType( + loader.Load(AssetPath.Project("Library.ishadersource"), typeof(ShaderFunctionAsset)) + ); Assert.Equal(new[] { "Exposure", "Tint" }, library.exports); byte[] bundle = ShaderSourceBundle.Read(library, loader); using var frontends = new ShaderSourceFrontendRegistry(m_types); - Assert.Equal("Exposure", Assert.Single(frontends.AnalyzeModule( - ShaderSourceBundle.Decode(bundle, "Exposure", m_serialization)).implementations).entryPoint); - Assert.Equal("Tint", Assert.Single(frontends.AnalyzeModule( - ShaderSourceBundle.Decode(bundle, "Tint", m_serialization)).implementations).entryPoint); + Assert.Equal( + "Exposure", + Assert.Single( + frontends.AnalyzeModule(ShaderSourceBundle.Decode(bundle, "Exposure", m_serialization)).implementations + ).entryPoint + ); + Assert.Equal( + "Tint", + Assert.Single( + frontends.AnalyzeModule(ShaderSourceBundle.Decode(bundle, "Tint", m_serialization)).implementations + ).entryPoint + ); Assert.Throws(() => ShaderSourceBundle.Decode(bundle, "PrivateHelper", m_serialization)); } - private AssetLoader CreateLoader(string assetRoot, string libraryRoot) - => new( - m_types, - m_serialization, - m_identities, - m_diagnostics, - m_logs, - assetRoot, - libraryRoot); + private AssetLoader CreateLoader( + string assetRoot, + string libraryRoot + ) => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, assetRoot, libraryRoot); [Fact] public void InvalidGraphAutosaveSurvivesImportFailureAndRestartWithoutLosingMissingRecords() @@ -302,8 +338,15 @@ public void ReadOnlyInstalledGraphCanBeReadButNeverAutosaved() GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); byte[] bytes = GraphDocumentCodec.Encode(graph, m_serialization); File.WriteAllBytes(Path.Combine(installed, "shader.ishader"), bytes); - File.WriteAllBytes(Path.Combine(installed, "shader.ishader.imeta"), m_serialization.Serialize(new RenderingAssetSourceMeta - { persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.File, importerId = "inno.rendering.shader" })); + File.WriteAllBytes( + Path.Combine(installed, "shader.ishader.imeta"), + m_serialization.Serialize(new RenderingAssetSourceMeta + { + persistentId = Guid.NewGuid(), + sourceKind = (int)AssetSourceKind.File, + importerId = "inno.rendering.shader" + }) + ); var id = new AssetSourceId("test.installed"); using var pipeline = CreatePipeline([new(AssetSourceId.project, m_assets, false), new(id, installed, true)]); var store = new ShaderGraphSourceStore(pipeline, m_serialization); @@ -315,8 +358,21 @@ public void ReadOnlyInstalledGraphCanBeReadButNeverAutosaved() } private AssetPipeline CreatePipeline(IReadOnlyList? mounts = null) - => new(m_modules, m_types, m_serialization, m_identities, m_diagnostics, m_logs, - new AssetPipelineOptions { assetRoot = m_assets, libraryRoot = m_library, enableFileSystemWatcher = false, sourceMounts = mounts }); + => new( + m_modules, + m_types, + m_serialization, + m_identities, + m_diagnostics, + m_logs, + new AssetPipelineOptions + { + assetRoot = m_assets, + libraryRoot = m_library, + enableFileSystemWatcher = false, + sourceMounts = mounts + } + ); [Fact] public void NativePipelineSettingsCaptureNestedReferencesAndRestoreAgainstTheirOwner() @@ -325,8 +381,12 @@ public void NativePipelineSettingsCaptureNestedReferencesAndRestoreAgainstTheirO WriteBytes("surface.ishader", GraphDocumentCodec.Encode(graph, m_serialization)); using AssetPipeline assets = CreatePipeline(); ShaderAsset shader = assets.Load(AssetPath.Project("surface.ishader")); - SerializedRenderExtensionState state = new(assets.CaptureProperties(new NestedPipelineSettings - { nested = new NestedPipelineReferences { shader = shader } })); + SerializedRenderExtensionState state = new( + assets.CaptureProperties(new NestedPipelineSettings + { + nested = new NestedPipelineReferences { shader = shader } + }) + ); Assert.Equal(shader.identity.persistentId, Assert.Single(state.dependencies).persistentId); var pipeline = new RenderPipelineAsset { pipelineTypeId = "tests.pipeline", pipelineState = state }; AssetPath path = AssetPath.Project("configured.irenderpipeline"); @@ -341,11 +401,19 @@ public void NativePipelineSettingsCaptureNestedReferencesAndRestoreAgainstTheirO var restoredThroughOwner = new NestedPipelineSettings(); ownedContext.Restore(loaded.pipelineState, restoredThroughOwner); Assert.Same(shader, restoredThroughOwner.nested.shader); - Assert.Throws(() => new RenderPipelineAsset().RestoreProperties(state.stableTypeId, state.propertyData, new NestedPipelineSettings())); + Assert.Throws( + () => new RenderPipelineAsset().RestoreProperties(state.stableTypeId, state.propertyData, new NestedPipelineSettings()) + ); Assert.Throws(() => context.Restore(loaded.pipelineState, new OtherPipelineSettings())); - using (AssetLoader other = new(m_types, m_serialization, new IdentityAllocator(), m_diagnostics, m_logs, - m_assets, Path.Combine(m_root, "IsolatedLibrary"))) - { + using (AssetLoader other = new( + m_types, + m_serialization, + new IdentityAllocator(), + m_diagnostics, + m_logs, + m_assets, + Path.Combine(m_root, "IsolatedLibrary") + )) { var otherPipeline = Assert.IsType(other.Load(path, typeof(RenderPipelineAsset))); var otherShader = Assert.IsType(other.Load(AssetPath.Project("surface.ishader"), typeof(ShaderAsset))); Assert.Equal(shader.identity.persistentId, otherShader.identity.persistentId); @@ -371,49 +439,58 @@ private struct NestedPipelineReferences } [StableTypeId("830a7851-bc19-44d4-a6e6-a6c38f6bb972")] - private sealed class OtherPipelineSettings : ISerializable { } + private sealed class OtherPipelineSettings : ISerializable; private AssetLoader CreateLoader( IReadOnlyList mounts, - string libraryRoot) - => new( - m_types, - m_serialization, - m_identities, - m_diagnostics, - m_logs, - mounts, - libraryRoot); - - private void WriteText(string relativePath, string value) - => WriteBytes(relativePath, Encoding.UTF8.GetBytes(value)); - - private void WriteBytes(string relativePath, byte[] bytes) - { + string libraryRoot + ) => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, mounts, libraryRoot); + + private void WriteText( + string relativePath, + string value + ) => WriteBytes(relativePath, Encoding.UTF8.GetBytes(value)); + + private void WriteBytes( + string relativePath, + byte[] bytes + ) { string path = Path.Combine(m_assets, relativePath.Replace('/', Path.DirectorySeparatorChar)); Directory.CreateDirectory(Path.GetDirectoryName(path)!); System.IO.File.WriteAllBytes(path, bytes); } - private void WriteReadOnlyShaderSource(string root, string localPath, string content, params string[] exports) - { + private void WriteReadOnlyShaderSource( + string root, + string localPath, + string content, + params string[] exports + ) { if (exports.Length == 0) exports = ["Evaluate"]; string path = Path.Combine(root, localPath.Replace('/', Path.DirectorySeparatorChar)); Directory.CreateDirectory(Path.GetDirectoryName(path)!); System.IO.File.WriteAllText(path, content, Encoding.UTF8); - System.IO.File.WriteAllBytes(path + ".imeta", m_serialization.Serialize( - new RenderingAssetSourceMeta - { - persistentId = Guid.NewGuid(), - sourceKind = (int)AssetSourceKind.File, - importerId = "inno.rendering.shader-function", - importerSettingsBytes = m_serialization.Serialize(new RenderingImportSettingsEnvelope + System.IO.File.WriteAllBytes( + path + ".imeta", + m_serialization.Serialize( + new RenderingAssetSourceMeta { - stableTypeId = Guid.Parse("59c92a59-ef51-4587-b917-df5d187d2717"), - properties = m_serialization.Encode(writer => writer.WriteProperties(new ShaderSourceImportSettings - { languageId = "inno.shader-language.bgfx-sc", implementationId = "bgfx", exports = exports })) - }) - })); + persistentId = Guid.NewGuid(), + sourceKind = (int)AssetSourceKind.File, + importerId = "inno.rendering.shader-function", + importerSettingsBytes = m_serialization.Serialize(new RenderingImportSettingsEnvelope + { + stableTypeId = Guid.Parse("59c92a59-ef51-4587-b917-df5d187d2717"), + properties = m_serialization.Encode(writer => writer.WriteProperties(new ShaderSourceImportSettings + { + languageId = "inno.shader-language.bgfx-sc", + implementationId = "bgfx", + exports = exports + })) + }) + } + ) + ); } } diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs index 2f641c31b..a7e48e613 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs @@ -1,28 +1,31 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Rendering; -using Inno.Rendering.Shaders; -using Xunit; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring.Tests; [Collection("Rendering assets serialization")] public sealed class ShaderCompilerTests : IDisposable { - private readonly ModuleHost m_modules = new(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderCompilerTests).Assembly)}); + private readonly ModuleHost m_modules = new( + new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderCompilerTests).Assembly)} + ); + private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; private readonly ShaderNodeCompilerRegistry m_nodes; @@ -36,8 +39,11 @@ public ShaderCompilerTests() [Fact] public void FailedToolResultsCannotCarrySuccessfulBinaryBytes() - => Assert.Throws(() => new ShaderStageToolResult([1], [], - [new("TEST_ERROR", DiagnosticSeverity.Error, "The adapter rejected its binary.", new("test", 1, 1))])); + => Assert.Throws(() => new ShaderStageToolResult( + [1], + [], + [new("TEST_ERROR", DiagnosticSeverity.Error, "The adapter rejected its binary.", new("test", 1, 1))] + )); [Fact] public void ToolResultsCopyAdapterOwnedBytesBindingsAndDiagnostics() @@ -85,26 +91,69 @@ public async Task UnsupportedAlternativePassKeepsSupportedPassAndExactBindingLay foreach (GraphNodeRecord original in alternate.nodes) { var node = new GraphNodeRecord(new("alternate." + original.id.value), original.definitionId); - foreach ((string key, GraphSerializedValue value) in original.values) node.SetValue(key, value.Clone()); + foreach ((string key, GraphSerializedValue value) in original.values) + { + node.SetValue(key, value.Clone()); + } if (node.definitionId == ShaderGraphDocument.outputDefinitionId) { - ShaderGraphStageSettings settings = ShaderGraphDocument.Read(node, "settings", null!, m_serialization, SerializationContext.empty); + ShaderGraphStageSettings settings = ShaderGraphDocument.Read( + node, + "settings", + null!, + m_serialization, + SerializationContext.empty + ); node.SetValue("settings", ShaderGraphDocument.Encode(settings, m_serialization, SerializationContext.empty)); } - else node.SetValue("stage", ShaderGraphDocument.Encode("alternate." + ShaderGraphDocument.Read(node, "stage", "", m_serialization, SerializationContext.empty), m_serialization, SerializationContext.empty)); + else + { + node.SetValue( + "stage", + ShaderGraphDocument.Encode( + "alternate." + ShaderGraphDocument.Read(node, "stage", "", m_serialization, SerializationContext.empty), + m_serialization, + SerializationContext.empty + ) + ); + } graph.AddNode(node); } foreach (GraphEdgeRecord edge in alternate.edges) - graph.AddEdge(new(new("alternate." + edge.id.value), new(new("alternate." + edge.output.nodeId.value), edge.output.portId), new(new("alternate." + edge.input.nodeId.value), edge.input.portId))); - definition.passes = [new("Clustered", ShaderProgramKind.Raster, requiredFeatures: GraphicsCapability.Compute | GraphicsCapability.StorageBuffer), definition.passes[0]]; - graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); - graph = ShaderGraphPrograms.Bind(graph, "Clustered", [new("alternate.vertex"), new("alternate.fragment")], m_serialization, SerializationContext.empty); + { + graph.AddEdge( + new( + new("alternate." + edge.id.value), + new(new("alternate." + edge.output.nodeId.value), edge.output.portId), + new(new("alternate." + edge.input.nodeId.value), edge.input.portId) + ) + ); + } + definition.passes = + [ + new("Clustered", ShaderProgramKind.Raster, requiredFeatures: GraphicsCapability.Compute | GraphicsCapability.StorageBuffer), + definition.passes[0] + ]; + graph.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); + graph = ShaderGraphPrograms.Bind( + graph, + "Clustered", + [new("alternate.vertex"), new("alternate.fragment")], + m_serialization, + SerializationContext.empty + ); var toolchain = new FakeToolchain(); ShaderCompilationResult result = await Compile(new(toolchain), graph); Assert.True(result.succeeded, Diagnostics(result)); Assert.Equal("Main", Assert.Single(result.artifact!.passes).definition.name); Assert.Equal(2, toolchain.requests.Count); - Assert.Contains(result.diagnostics, static value => value.code == "SHADER_CAPABILITY_UNAVAILABLE" && value.severity == DiagnosticSeverity.Warning); + Assert.Contains( + result.diagnostics, + static value => value.code == "SHADER_CAPABILITY_UNAVAILABLE" && value.severity == DiagnosticSeverity.Warning + ); } [Fact] @@ -123,18 +172,53 @@ public async Task LastGoodStorePreservesArtifactAfterFailedCandidate() } private GraphDocument Template() => ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); - private ShaderDefinition Definition(GraphDocument graph) => ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); - private ValueTask Compile(ShaderCompiler compiler, GraphDocument graph) - { - ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(m_nodes).Lower(graph, "tests.fake", new Dictionary(), m_serialization, SerializationContext.empty); + + private ShaderDefinition Definition(GraphDocument graph) + => ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); + + private ValueTask Compile( + ShaderCompiler compiler, + GraphDocument graph + ) { + ShaderGraphProgramResult program = new ShaderGraphProgramCompiler(m_nodes).Lower( + graph, + "tests.fake", + new Dictionary(), + m_serialization, + SerializationContext.empty + ); RenderTextureFormat[] formats = Enum.GetValues(); - var capabilities = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.None, new(256, 8, 8192, 16), formats, formats, formats, formats, false, false); - return compiler.CompileAsync(Definition(graph), program, compiler.CreateTarget(capabilities), RenderShaderVariant.empty, - m_serialization, SerializationContext.empty); + var capabilities = new GraphicsCapabilities( + GraphicsApi.Metal, + GraphicsCapability.None, + new(256, 8, 8192, 16), + formats, + formats, + formats, + formats, + false, + false + ); + return compiler.CompileAsync( + Definition(graph), + program, + compiler.CreateTarget(capabilities), + RenderShaderVariant.empty, + m_serialization, + SerializationContext.empty + ); } - private static string Diagnostics(ShaderCompilationResult result) => string.Join("\n", result.diagnostics.Select(static value => value.message)); - public void Dispose() { m_nodes.Dispose(); m_serialization.Dispose(); m_types.Dispose(); m_modules.Dispose(); } + private static string Diagnostics(ShaderCompilationResult result) + => string.Join("\n", result.diagnostics.Select(static value => value.message)); + + public void Dispose() + { + m_nodes.Dispose(); + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + } private sealed class FakeToolchain : IShaderCompilerToolchain { @@ -142,17 +226,34 @@ private sealed class FakeToolchain : IShaderCompilerToolchain internal bool reportError { get; init; } public IReadOnlyList supportedSourceLanguages => []; internal List requests { get; } = []; - public ShaderCompileTarget CreateTarget(GraphicsCapabilities capabilities, bool optimize = true, bool debugInformation = false) - => new("tests:fake", capabilities, optimize, debugInformation); - public ValueTask CompileAsync(ShaderStageToolRequest request, CancellationToken cancellationToken) - { + + public ShaderCompileTarget CreateTarget( + GraphicsCapabilities capabilities, + bool optimize = true, + bool debugInformation = false + ) => new("tests:fake", capabilities, optimize, debugInformation); + + public ValueTask CompileAsync( + ShaderStageToolRequest request, + CancellationToken cancellationToken + ) { cancellationToken.ThrowIfCancellationRequested(); requests.Add(request); - return ValueTask.FromResult(reportError - ? new ShaderStageToolResult([], [], [new("TEST_ERROR", DiagnosticSeverity.Error, "Opaque compiler failure", new("Shaders/function.ishadersource", 2, 3))]) - : new ShaderStageToolResult([1, 2, 3], request.stage.inputs.Where(static input => input.kind == ShaderIrInputKind.Uniform) - .Select(static input => new ShaderStageBinding(input.id, "native_" + input.id, 0)), [])); + return ValueTask.FromResult( + reportError + ? new ShaderStageToolResult( + [], + [], + [new("TEST_ERROR", DiagnosticSeverity.Error, "Opaque compiler failure", new("Shaders/function.ishadersource", 2, 3))] + ) + : new ShaderStageToolResult( + [1, 2, 3], + request.stage.inputs + .Where(static input => input.kind == ShaderIrInputKind.Uniform) + .Select(static input => new ShaderStageBinding(input.id, "native_" + input.id, 0)), + [] + ) + ); } - } } diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs index 1ebb2b898..0fa80df3a 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs @@ -1,29 +1,39 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Rendering; -using Inno.Rendering.Shaders; -using Xunit; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring.Tests; [Collection("Rendering assets serialization")] public sealed class ShaderGraphArtifactTests : IDisposable { - private readonly ModuleHost m_modules = new(new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphArtifactTests).Assembly)}); + private readonly ModuleHost m_modules = new( + new() { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphArtifactTests).Assembly)} + ); + private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; - public ShaderGraphArtifactTests() { m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); } + + public ShaderGraphArtifactTests() + { + m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new( + m_types, + new ReflectionSerializationMetadataSource() + ); + } [Theory] [InlineData("16182a41-f19b-5a28-a66f-5310360f8a32", "ArtifactData")] @@ -35,8 +45,7 @@ public void FrozenArtifactRecordsKeepTheirPersistentIdentitiesAfterOwnershipMove string stableId, string typeName ) { - TypeRef record = Assert.Single(m_types.current.types, - reference => reference.stableId == Guid.Parse(stableId)); + TypeRef record = Assert.Single(m_types.current.types, reference => reference.stableId == Guid.Parse(stableId)); Assert.Equal(typeName, record.Resolve(m_types).Name); } @@ -44,7 +53,8 @@ string typeName public void SemanticFingerprintIgnoresLayoutButIncludesPropertiesAndFrozenDependencies() { GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); - string Hash(Dictionary sources) => ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(graph, sources, m_serialization), m_serialization); + string Hash(Dictionary sources) + => ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(graph, sources, m_serialization), m_serialization); string initial = Hash([]); graph.nodes[0].position = new(1000, -500); graph.SetMetadata("inno.editor.groups", ShaderGraphDocument.Encode("view-only", m_serialization, SerializationContext.empty)); @@ -63,13 +73,30 @@ public void ExpandedProgramCompilesWhileAuthoringExportRetainsTheSmallSourceGrap byte[] bytes = ShaderGraphArtifact.Encode(authored, new Dictionary(), m_serialization, expanded); using var nodes = new ShaderNodeCompilerRegistry(m_types); using var sources = new ShaderSourceFrontendRegistry(m_types); - ShaderGraphProgramResult result = ShaderGraphArtifact.Lower(bytes, "bgfx", nodes, sources, m_serialization, SerializationContext.empty); + ShaderGraphProgramResult result = ShaderGraphArtifact.Lower( + bytes, + "bgfx", + nodes, + sources, + m_serialization, + SerializationContext.empty + ); Assert.True(result.succeeded); - Assert.Equal(GraphDocumentCodec.Encode(authored, m_serialization), GraphDocumentCodec.Encode(ShaderGraphArtifact.ReadDocument(bytes, m_serialization), m_serialization)); + Assert.Equal( + GraphDocumentCodec.Encode(authored, m_serialization), + GraphDocumentCodec.Encode(ShaderGraphArtifact.ReadDocument(bytes, m_serialization), m_serialization) + ); string hash = ShaderGraphArtifact.GetSemanticHash(bytes, m_serialization); - expanded.FindNode(new("color"))!.SetValue("semantic-value", ShaderGraphDocument.Encode(3f, m_serialization, SerializationContext.empty)); - Assert.NotEqual(hash, ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(authored, - new Dictionary(), m_serialization, expanded), m_serialization)); + expanded + .FindNode(new("color"))! + .SetValue("semantic-value", ShaderGraphDocument.Encode(3f, m_serialization, SerializationContext.empty)); + Assert.NotEqual( + hash, + ShaderGraphArtifact.GetSemanticHash( + ShaderGraphArtifact.Encode(authored, new Dictionary(), m_serialization, expanded), + m_serialization + ) + ); } [Fact] @@ -77,7 +104,13 @@ public void TemporarilyEmptyInputNameRetainsItsMaterialDefaultWhileTyping() { GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); GraphNodeRecord input = graph.FindNode(new("color"))!; - var settings = ShaderGraphDocument.Read(input, "settings", new ShaderGraphInputSettings(), m_serialization, SerializationContext.empty); + var settings = ShaderGraphDocument.Read( + input, + "settings", + new ShaderGraphInputSettings(), + m_serialization, + SerializationContext.empty + ); settings.id = ""; graph = ShaderGraphBindings.ChangeInput(graph, input.id, settings, m_serialization, SerializationContext.empty); settings.id = "renamed-color"; @@ -120,14 +153,28 @@ public void GraphArtifactDetachesAuthoredDefinitionNodesAndConnections() [Fact] public void GraphDefinitionPreservesPipelineOwnedStorageTextureContract() { - var property = new ShaderPropertyDefinition(new("outputImage"), "Output Image", ShaderPropertyType.Texture2D, - ShaderStage.Compute, default, ShaderPropertyBindingKind.StorageTexture, RenderStorageAccess.ReadWrite, ShaderPropertyBindingOwner.RenderPass); - var pass = new ShaderPassDefinition("Compute", ShaderProgramKind.Compute, - requiredFeatures: GraphicsCapability.Compute | GraphicsCapability.StorageTexture); + var property = new ShaderPropertyDefinition( + new("outputImage"), + "Output Image", + ShaderPropertyType.Texture2D, + ShaderStage.Compute, + default, + ShaderPropertyBindingKind.StorageTexture, + RenderStorageAccess.ReadWrite, + ShaderPropertyBindingOwner.RenderPass + ); + var pass = new ShaderPassDefinition( + "Compute", + ShaderProgramKind.Compute, + requiredFeatures: GraphicsCapability.Compute | GraphicsCapability.StorageTexture + ); var definition = new ShaderDefinition("Tests/Storage", [property], [], [pass]); GraphDocument graph = ShaderGraphDocument.Create(definition, m_serialization, SerializationContext.empty); - ShaderDefinition restored = ShaderGraphDocument.ReadDefinition(GraphDocumentCodec.Decode(GraphDocumentCodec.Encode(graph, m_serialization), m_serialization), - m_serialization, SerializationContext.empty); + ShaderDefinition restored = ShaderGraphDocument.ReadDefinition( + GraphDocumentCodec.Decode(GraphDocumentCodec.Encode(graph, m_serialization), m_serialization), + m_serialization, + SerializationContext.empty + ); Assert.DoesNotContain(ShaderDefinitionValidator.Validate(restored), static value => value.severity == DiagnosticSeverity.Error); ShaderPropertyDefinition binding = Assert.Single(restored.properties); Assert.Equal(ShaderPropertyBindingKind.StorageTexture, binding.bindingKind); @@ -136,7 +183,18 @@ public void GraphDefinitionPreservesPipelineOwnedStorageTextureContract() Assert.Equal(ShaderProgramKind.Compute, Assert.Single(restored.passes).programKind); } - private void SetDefinition(GraphDocument graph, ShaderDefinition definition) - => graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); - public void Dispose() { m_serialization.Dispose(); m_types.Dispose(); m_modules.Dispose(); } + private void SetDefinition( + GraphDocument graph, + ShaderDefinition definition + ) => graph.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); + + public void Dispose() + { + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + } } diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderPublicationTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderPublicationTests.cs index 8a89f456c..98bdecfd3 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderPublicationTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderPublicationTests.cs @@ -1,18 +1,18 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.IO; using System.Collections.Generic; +using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; -using Inno.Rendering.Shaders; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Runtime; +using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring.Tests; @@ -26,7 +26,9 @@ public sealed class ShaderPublicationTests : IDisposable public ShaderPublicationTests() { m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderPublicationTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderPublicationTests).Assembly) + }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); } @@ -112,14 +114,27 @@ public void MaterialSelectionAndResolvedPassDoNotPublishTheirMetadataArrays() } private static ShaderDefinition CreateDefinition() - => new("Original", - [new ShaderPropertyDefinition(new ShaderPropertyId("value"), "Value", ShaderPropertyType.Float, - ShaderStage.Fragment, MaterialValue.FromFloat(1))], + => new( + "Original", + [new ShaderPropertyDefinition( + new ShaderPropertyId("value"), + "Value", + ShaderPropertyType.Float, + ShaderStage.Fragment, + MaterialValue.FromFloat(1) + )], [new ShaderKeywordDefinition("quality", ["high"])], - [new ShaderPassDefinition("main", ShaderProgramKind.Raster, - metadata: [new ShaderMetadataEntry("sort", "opaque")])], - [new ShaderTechniqueDefinition(new ShaderTechniqueId("default"), new ShaderContractId("test.draw"), - [new ShaderTechniquePass(new ShaderPassRoleId("draw"), "main")])]); + [new ShaderPassDefinition( + "main", + ShaderProgramKind.Raster, + metadata: [new ShaderMetadataEntry("sort", "opaque")] + )], + [new ShaderTechniqueDefinition( + new ShaderTechniqueId("default"), + new ShaderContractId("test.draw"), + [new ShaderTechniquePass(new ShaderPassRoleId("draw"), "main")] + )] + ); private static void Mutate(ShaderDefinition definition) { diff --git a/tests/rendering/Inno.Rendering.Assets.Tests/GeometryArtifactTests.cs b/tests/rendering/Inno.Rendering.Assets.Tests/GeometryArtifactTests.cs index 04da441bf..62a8e18c0 100644 --- a/tests/rendering/Inno.Rendering.Assets.Tests/GeometryArtifactTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Tests/GeometryArtifactTests.cs @@ -1,5 +1,5 @@ -using Inno.Core.Mathematics; using Xunit; +using Inno.Core.Mathematics; namespace Inno.Rendering.Assets.Tests; @@ -8,8 +8,12 @@ public sealed class GeometryArtifactTests [Fact] public void RuntimeGeometryDecodesWithoutAnImporterOrRenderDevice() { - var vertex = new GeometryVertex(new Vector3(1, 2, 3), new Vector3(0, 1, 0), - new Vector4(1, 0, 0, 1), new Vector2(0.5f, 0.25f)); + var vertex = new GeometryVertex( + new Vector3(1, 2, 3), + new Vector3(0, 1, 0), + new Vector4(1, 0, 0, 1), + new Vector2(0.5f, 0.25f) + ); var data = new GeometryData([vertex, vertex, vertex], [0, 1, 2], [new GeometrySection(0, 3)]); GeometryData decoded = GeometryArtifact.Decode(GeometryArtifact.Encode(data)); Assert.Equal(data.vertices, decoded.vertices); diff --git a/tests/rendering/Inno.Rendering.Assets.Tests/RuntimeAssetSerializationTests.cs b/tests/rendering/Inno.Rendering.Assets.Tests/RuntimeAssetSerializationTests.cs index a5368ba3e..599c42b43 100644 --- a/tests/rendering/Inno.Rendering.Assets.Tests/RuntimeAssetSerializationTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Tests/RuntimeAssetSerializationTests.cs @@ -1,10 +1,10 @@ using System; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Rendering.Assets.Tests; @@ -33,9 +33,16 @@ public void ShaderDeclarationsRoundTripThroughTheCommonSerializationContract() }); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - var definition = new ShaderDefinition("Fixture", [], [], - [new ShaderPassDefinition("color", ShaderProgramKind.Raster, - metadata: [new ShaderMetadataEntry("fixture", "value")])]); + var definition = new ShaderDefinition( + "Fixture", + [], + [], + [new ShaderPassDefinition( + "color", + ShaderProgramKind.Raster, + metadata: [new ShaderMetadataEntry("fixture", "value")] + )] + ); byte[] bytes = serialization.Serialize(definition); ShaderDefinition decoded = serialization.Deserialize(bytes); Assert.Equal(definition.name, decoded.name); diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/ContentRenderTargetArtifactProviderTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/ContentRenderTargetArtifactProviderTests.cs index 4d9f58159..4d872f276 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/ContentRenderTargetArtifactProviderTests.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/ContentRenderTargetArtifactProviderTests.cs @@ -1,15 +1,14 @@ -using Inno.Content.Testing; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Content.Testing; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; - -using Inno.Core.Identity; using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; using Inno.Rendering.Runtime; @@ -20,7 +19,9 @@ public sealed class ContentRenderTargetArtifactProviderTests : IDisposable private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoRenderTargetArtifactProviderTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly ModuleHost m_modules; private readonly TypeCatalog m_types; private readonly SerializationRegistry m_serialization; @@ -29,7 +30,8 @@ public ContentRenderTargetArtifactProviderTests() { m_modules = new(new() { - catalogSource = new DotNetAssemblyCatalogSource(typeof(ContentRenderTargetArtifactProviderTests).Assembly) }); + catalogSource = new DotNetAssemblyCatalogSource(typeof(ContentRenderTargetArtifactProviderTests).Assembly) + }); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); } @@ -43,18 +45,14 @@ public void TextureTargetArtifactLoadsWithoutAnyAuthoringSourceMount() Guid persistentId = Guid.NewGuid(); identities.InitializePersistentIdentity(texture, persistentId); RenderTextureArtifactReference reference = texture.GetTextureArtifactReference(); - string artifactPath = Path.Combine( - m_root, - RenderTargetArtifactPath.GetTexturePath(reference)); + string artifactPath = Path.Combine(m_root, RenderTargetArtifactPath.GetTexturePath(reference)); Directory.CreateDirectory(Path.GetDirectoryName(artifactPath)!); byte[] expected = [0xAB, 0x4B, 0x54, 0x58]; File.WriteAllBytes(artifactPath, expected); using ContentTestStore content = ContentTestStore.FromDirectory(m_root); var provider = new ContentRenderTargetArtifactProvider(content, m_serialization, SerializationContext.empty); - RenderTargetArtifactStatus status = provider.GetTextureArtifact( - reference, - out ReadOnlyMemory artifact); + RenderTargetArtifactStatus status = provider.GetTextureArtifact(reference, out ReadOnlyMemory artifact); Assert.Equal(RenderTargetArtifactStatus.Ready, status); Assert.Equal(expected, artifact.ToArray()); @@ -72,9 +70,7 @@ public void MissingDeployedTextureArtifactIsReportedAsUnavailable() using ContentTestStore content = ContentTestStore.FromDirectory(m_root); var provider = new ContentRenderTargetArtifactProvider(content, m_serialization, SerializationContext.empty); - RenderTargetArtifactStatus status = provider.GetTextureArtifact( - reference, - out ReadOnlyMemory artifact); + RenderTargetArtifactStatus status = provider.GetTextureArtifact(reference, out ReadOnlyMemory artifact); Assert.Equal(RenderTargetArtifactStatus.Unavailable, status); Assert.True(artifact.IsEmpty); @@ -94,10 +90,7 @@ public void IndependentTextureSlotsUseStableDistinctDeploymentPaths() Assert.NotEqual(firstRelativePath, secondRelativePath); Assert.Equal(firstRelativePath, RenderTargetArtifactPath.GetTexturePath(first)); - Assert.StartsWith( - "TargetArtifacts/Textures/" + $"{assetId:D}/", - firstRelativePath, - StringComparison.Ordinal); + Assert.StartsWith("TargetArtifacts/Textures/" + $"{assetId:D}/", firstRelativePath, StringComparison.Ordinal); string firstPath = Path.Combine(m_root, firstRelativePath); string secondPath = Path.Combine(m_root, secondRelativePath); @@ -119,6 +112,8 @@ public void Dispose() m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs index f410dee7f..8e41172a3 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs @@ -1,10 +1,3 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Extensibility.Reload; -using Inno.Adapter.Modules.DotNet; -using Inno.References; -using Inno.Runtime.Contracts; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; using System; using System.Collections.Generic; using System.IO; @@ -12,15 +5,22 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; -using Inno.Extensibility.Modules; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Serialization; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; using Inno.Extensibility.Types; +using Inno.References; using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; using Inno.Rendering.Runtime; +using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime.Tests; @@ -30,11 +30,17 @@ public sealed class EmptyRenderingKernelTests public void OutputRouteAssignsEachWorldContentSourceOnlyOnce() { Assert.Throws(() => new RenderOutputRoute( - [new RenderOutputLayer("model-a", ["canvas"]), - new RenderOutputLayer("model-b", ["canvas"])])); + [ + new RenderOutputLayer("model-a", ["canvas"]), + new RenderOutputLayer("model-b", ["canvas"]) + ] + )); var route = new RenderOutputRoute( - [new RenderOutputLayer("model-a", ["canvas"]), - new RenderOutputLayer("model-b", [])]); + [ + new RenderOutputLayer("model-a", ["canvas"]), + new RenderOutputLayer("model-b", []) + ] + ); Assert.Equal("canvas", Assert.Single(route.layers[0].sourceIds)); Assert.Empty(route.layers[1].sourceIds); } @@ -55,8 +61,9 @@ public void ProductionRenderingAssemblyDoesNotDeclareConcreteRenderingWorldviews public void OpenShaderProtocolsRemainBackendNeutral() { Type[] publicTypes = typeof(ShaderContractId).Assembly.GetExportedTypes(); - Assert.DoesNotContain(publicTypes, static type => - type.FullName?.Contains("Bgfx", StringComparison.OrdinalIgnoreCase) == true); + Assert.DoesNotContain(publicTypes, static type => ( + type.FullName?.Contains("Bgfx", StringComparison.OrdinalIgnoreCase) == true + )); Assert.Contains(publicTypes, static type => type == typeof(ShaderContractId)); Assert.Contains(publicTypes, static type => type == typeof(ShaderPassRoleId)); } @@ -67,7 +74,9 @@ public sealed partial class RenderRuntimeGenerationTests : IDisposable private readonly string m_cacheDirectory = Path.Combine( Path.GetTempPath(), "InnoRenderRuntimeTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly IdentityAllocator m_identities; private readonly IDisposable m_identityScope; private readonly ModuleHost m_modules; @@ -79,7 +88,9 @@ public RenderRuntimeGenerationTests() _ = typeof(TextureAsset); m_identities = new IdentityAllocator(); m_identityScope = m_identities.EnterScope(); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly)}); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly)} + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); ResourceProbePipeline.action = null; @@ -104,7 +115,9 @@ public void Dispose() m_modules.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_cacheDirectory)) + { Directory.Delete(m_cacheDirectory, recursive: true); + } } [Fact] @@ -115,9 +128,13 @@ public void GeometryCandidatePublishesACompletePairAndPreservesOldPairAfterParti var owner = new AssetRuntimeOwner(); var geometry = new GeometryAsset(3, 3, 1, default, default); m_identities.Register(geometry); - byte[] bytes = GeometryArtifact.Encode(new GeometryData( - [new(default, default, default, default), new(default, default, default, default), new(default, default, default, default)], - [0, 1, 2], [new GeometrySection(0, 3)])); + byte[] bytes = GeometryArtifact.Encode( + new GeometryData( + [new(default, default, default, default), new(default, default, default, default), new(default, default, default, default)], + [0, 1, 2], + [new GeometrySection(0, 3)] + ) + ); owner.Initialize(geometry, AssetPath.Project("triangle.obj"), "first", bytes, false, 1); RenderGeometry? first = null; ResourceProbePipeline.action = resources => resources.TryResolveGeometry(geometry, out first); @@ -149,8 +166,12 @@ public void GeometryCandidatePublishesACompletePairAndPreservesOldPairAfterParti public void PersistentResourceAdmissionAndReplacementStayBoundedAcrossFrames() { IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); - using var runtime = new RenderRuntime(m_types, backend, new TestDiagnosticSink(), - resourceLimits: new RenderResourceLimits { resourcesPerKind = 1 }); + using var runtime = new RenderRuntime( + m_types, + backend, + new TestDiagnosticSink(), + resourceLimits: new RenderResourceLimits { resourcesPerKind = 1 } + ); var descriptor = new PersistentBufferDescriptor(new RenderBufferDescriptor(4, 4, RenderBufferUsage.Storage)); int rejected = 0; for (int frame = 0; frame < 256; frame++) @@ -159,8 +180,14 @@ public void PersistentResourceAdmissionAndReplacementStayBoundedAcrossFrames() ResourceProbePipeline.action = resources => { _ = resources.AcquireBuffer(new RenderPersistentResourceId("owned"), revision, descriptor, new byte[16], "owned"); - try { resources.AcquireBuffer(new RenderPersistentResourceId("overflow"), revision, descriptor, new byte[16], "overflow"); } - catch (InvalidOperationException) { rejected++; } + try + { + resources.AcquireBuffer(new RenderPersistentResourceId("overflow"), revision, descriptor, new byte[16], "overflow"); + } + catch (InvalidOperationException) + { + rejected++; + } }; RunResourceFrame(runtime); Assert.Equal(1, runtime.resourceStatistics.activeResources); @@ -177,15 +204,25 @@ public void PersistentResourceAdmissionAndReplacementStayBoundedAcrossFrames() public async Task ReadbackAdmissionIsRejectedBeforeAllocatingASecondNativeOperation() { var device = new RecordingRenderDevice(supportsReadback: true); - using var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), - resourceLimits: new RenderResourceLimits { pendingReadbacks = 1 }); + using var runtime = new RenderRuntime( + m_types, + device, + new TestDiagnosticSink(), + resourceLimits: new RenderResourceLimits { pendingReadbacks = 1 } + ); Task? readback = null; bool rejected = false; ResourceProbePipeline.action = resources => { readback = resources.ReadTextureAsync(device.textureHandle).AsTask(); - try { _ = resources.ReadTextureAsync(device.textureHandle); } - catch (InvalidOperationException) { rejected = true; } + try + { + _ = resources.ReadTextureAsync(device.textureHandle); + } + catch (InvalidOperationException) + { + rejected = true; + } }; RunResourceFrame(runtime); ResourceProbePipeline.action = null; @@ -210,10 +247,14 @@ private sealed class ResourceProbePipeline : RenderPipeline { internal const string extensionId = "tests.runtime.resource-owner"; internal static Action? action; + public override void Build(RenderPipelineContext context) { action?.Invoke(context.resourceService); - context.graph.AddRasterPass("Resources", new RenderPhaseId("tests.resources"), 0, static (_, _) => { }).HasSideEffect(); + context.graph.AddRasterPass("Resources", new RenderPhaseId("tests.resources"), 0, static ( + _, + _ + ) => {}).HasSideEffect(); } } @@ -259,7 +300,11 @@ public void InvalidInitialContributorsFailBeforeRegisteringAnExtensionOwner(bool var contributor = new SideEffectContributor(); IRenderFrameGraphContributor[] contributors = duplicate ? [contributor, contributor] : [null!]; Assert.Throws(() => new RenderRuntime( - m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink(), contributors)); + m_types, + TestDeviceProxy.Create(out _), + new TestDiagnosticSink(), + contributors + )); m_types.Rebuild(); Assert.Equal(0, TestRequestProvider.retirementAttempts); } @@ -268,11 +313,13 @@ public void InvalidInitialContributorsFailBeforeRegisteringAnExtensionOwner(bool public void PendingFeatureRetirementKeepsItsPipelineAliveUntilQuiescent() { var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy device), new TestDiagnosticSink()); - Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset - { - pipelineTypeId = DisposablePipeline.extensionId, - features = [new RenderFeatureConfiguration(PendingFeature.extensionId)] - })); + Assert.True( + runtime.TryActivateDefaultPipeline(new RenderPipelineAsset + { + pipelineTypeId = DisposablePipeline.extensionId, + features = [new RenderFeatureConfiguration(PendingFeature.extensionId)] + }) + ); PendingFeature.pendingRetirements = 2; DisposablePipeline.pendingRetirements = 1; @@ -316,9 +363,13 @@ public void ReloadRetirementDrainsPendingBeforeFinishingTheTransaction(bool comm DisposablePipeline.pendingRetirements = 2; if (commit) + { transaction.Complete(); + } else + { transaction.Rollback(); + } Assert.Equal(3, DisposablePipeline.retirementAttempts); Assert.Equal(1, DisposablePipeline.disposedCount); @@ -401,7 +452,9 @@ public void TargetRetirementRetainsProgressAndOrdinaryErrorsAcrossPendingRetries public void TerminalPipelineRetirementBlocksAdmissionAndPreservesLowerOwners(bool duringFrame) { var modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly) + }); var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); var runtime = new RenderRuntime(types, TestDeviceProxy.Create(out TestDeviceProxy device), new TestDiagnosticSink()); var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.extensionId }; @@ -419,7 +472,9 @@ public void TerminalPipelineRetirementBlocksAdmissionAndPreservesLowerOwners(boo Assert.True(device.frameOpen); } else + { Assert.Throws(runtime.Dispose); + } Assert.Throws(() => runtime.Submit(CreateRequest("Late", new RenderPipelineAsset()))); Assert.Throws(() => runtime.RegisterContributor(new SideEffectContributor())); Assert.Throws(() => runtime.BeginExtensionReload()); @@ -447,10 +502,18 @@ public void RuntimeKeepsItsMaintenanceFrameOpenUntilTargetsFinishRetiring() { IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - var target = new RenderTexture("Pending Target", new RenderTextureDescriptor( - 16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment)); - runtime.Submit(new RenderRequest("Target", RenderTarget.FromTexture(target), - new RenderViewport(0, 0, 16, 16), new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.extensionId })); + var target = new RenderTexture( + "Pending Target", + new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment) + ); + runtime.Submit( + new RenderRequest( + "Target", + RenderTarget.FromTexture(target), + new RenderViewport(0, 0, 16, 16), + new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.extensionId } + ) + ); BeginRenderFrame(runtime, 0f); runtime.AfterRender(default); runtime.EndFrame(default); @@ -504,7 +567,8 @@ public void RemovingAndRestoringPluginRenderingCommitsTheSameUnavailableStateAsC Assert.Equal(1, proxy.executeCount); Assert.DoesNotContain( diagnostics.items, - static diagnostic => diagnostic.code == "RENDER_EXTENSION_RELOAD_REJECTED"); + static diagnostic => diagnostic.code == "RENDER_EXTENSION_RELOAD_REJECTED" + ); IRenderRuntimeReloadTransaction renderingRecovery = runtime.BeginExtensionReload(); using (AssemblyReloadSession recovery = m_modules.BeginReload([plugin])) @@ -551,18 +615,16 @@ public void FrameStatisticsReportBackendCommandsAndGraphCulling(bool reportsAllo IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); proxy.frameCounters = new RenderDeviceFrameCounters(3, 2); proxy.allocationCounters = reportsAllocations - ? new RenderDeviceAllocationCounters(device.generation, 17, 23, 11) - : null; + ? new RenderDeviceAllocationCounters(device.generation, 17, 23, 11) + : null; var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); using IDisposable executionScope = runtime.EnterExecutionScope(); var asset = new RenderPipelineAsset { pipelineTypeId = StatisticsPipeline.extensionId }; runtime.Attach(); Assert.True(runtime.TryActivateDefaultPipeline(asset)); - runtime.Submit(new RenderRequest( - "Statistics", - RenderTarget.backbuffer, - new RenderViewport(0, 0, 64, 64), - asset)); + runtime.Submit( + new RenderRequest("Statistics", RenderTarget.backbuffer, new RenderViewport(0, 0, 64, 64), asset) + ); BeginRenderFrame(runtime, 0f); runtime.AfterRender(default); @@ -668,11 +730,7 @@ public void RequestProviderReceivesExplicitHostContentScope() Assert.True(scope.TryGetValue(contentId, out TestContent? resolved)); Assert.Same(content, resolved); TestRequestProvider.enabled = true; - var runtime = new RenderRuntime( - m_types, - device, - new TestDiagnosticSink(), - contentScopeProvider: () => scope); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), contentScopeProvider: () => scope); runtime.Attach(); BeginRenderFrame(runtime, 0f); @@ -699,7 +757,9 @@ public void PrimaryPresentationViewportIsSharedAndLetterboxSurfaceIsCleared() 0, (size.height - 562) / 2, size.width, - 562)); + 562 + ) + ); runtime.Attach(); BeginRenderFrame(runtime, 0f); @@ -721,20 +781,25 @@ public void PrimaryOutputScalesLogicalWindowPointerToPhysicalPixels() IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); proxy.presentationSize = new RenderPresentationSize(2560, 1440); TestRequestProvider.enabled = true; - var snapshot = new Inno.Input.InputSnapshot(1, + var snapshot = new Inno.Input.InputSnapshot( + 1, mousePosition: new Inno.Core.Mathematics.Vector2(400f, 274f), - mouseButtonsPressed: [Inno.Core.Input.MouseButton.Left]); - using var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), + mouseButtonsPressed: [Inno.Core.Input.MouseButton.Left] + ); + using var runtime = new RenderRuntime( + m_types, + device, + new TestDiagnosticSink(), inputSnapshotProvider: () => snapshot, - primaryInputSurfaceSizeProvider: static () => new RenderPresentationSize(1280, 720)); + primaryInputSurfaceSizeProvider: static () => new RenderPresentationSize(1280, 720) + ); BeginRenderFrame(runtime, 0f); runtime.Render(default); runtime.AfterRender(default); runtime.EndFrame(default); - Assert.Equal(new Inno.Core.Mathematics.Vector2(800f, 548f), - TestRequestProvider.lastInput.pointerPosition); + Assert.Equal(new Inno.Core.Mathematics.Vector2(800f, 548f), TestRequestProvider.lastInput.pointerPosition); Assert.Single(TestRequestProvider.lastInput.buttonsPressed); } @@ -743,16 +808,27 @@ public void CompetingModelsDoNotShareATargetWhenAnExactRouteExists() { IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); var diagnostics = new TestDiagnosticSink(); - proxy.capabilities = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.None, - new GraphicsLimits(64, 4, 4096, 8), Enum.GetValues(), - Enum.GetValues(), [], [], originBottomLeft: false, - homogeneousDepth: false); + proxy.capabilities = new GraphicsCapabilities( + GraphicsApi.Metal, + GraphicsCapability.None, + new GraphicsLimits(64, 4, 4096, 8), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); proxy.presentationSize = new RenderPresentationSize(1000, 1000); FirstTestRenderModel.enabled = true; SecondTestRenderModel.enabled = true; - using var runtime = new RenderRuntime(m_types, device, diagnostics, + using var runtime = new RenderRuntime( + m_types, + device, + diagnostics, primaryPresentationViewportProvider: static _ => new RenderViewport(100, 200, 800, 600), - compositionProgramProvider: new TestCompositionProgramProvider()); + compositionProgramProvider: new TestCompositionProgramProvider() + ); BeginRenderFrame(runtime, 0f); runtime.Render(default); @@ -760,29 +836,40 @@ public void CompetingModelsDoNotShareATargetWhenAnExactRouteExists() runtime.EndFrame(default); Assert.Equal(0, FirstTestRenderModel.buildCount); Assert.Equal(0, SecondTestRenderModel.buildCount); - Assert.Contains(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" - && item.message.Contains("Multiple rendering models", StringComparison.Ordinal)); - - runtime.SetPrimaryRoute(new RenderOutputRoute( - [new RenderOutputLayer(SecondTestRenderModel.extensionId, []), - new RenderOutputLayer(FirstTestRenderModel.extensionId, [])])); + Assert.Contains(diagnostics.items, item => ( + item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" + && item.message.Contains("Multiple rendering models", StringComparison.Ordinal) + )); + + runtime.SetPrimaryRoute( + new RenderOutputRoute( + [ + new RenderOutputLayer(SecondTestRenderModel.extensionId, []), + new RenderOutputLayer(FirstTestRenderModel.extensionId, []) + ] + ) + ); BeginRenderFrame(runtime, 0f); runtime.Render(default); runtime.AfterRender(default); runtime.EndFrame(default); Assert.Equal(1, FirstTestRenderModel.buildCount); Assert.Equal(1, SecondTestRenderModel.buildCount); - Assert.Equal([new RenderViewport(0, 0, 800, 600), new RenderViewport(0, 0, 800, 600)], - CompositionLayerPipeline.viewports); + Assert.Equal( + [new RenderViewport(0, 0, 800, 600), new RenderViewport(0, 0, 800, 600)], + CompositionLayerPipeline.viewports + ); Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE"); - Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" - && item.message.Contains("independent model targets", StringComparison.Ordinal)); - Assert.True(diagnostics.items.All(item => item.code != "RENDER_OUTPUT_COMPOSITION_FAILED"), - string.Join("\n", diagnostics.items.Select(item => item.message))); - Assert.True(proxy.lastGraph is not null, - string.Join("\n", diagnostics.items.Select(item => item.message))); - Assert.Contains(proxy.lastGraph.passes, - pass => pass.name.Contains("Layer 2", StringComparison.Ordinal)); + Assert.DoesNotContain(diagnostics.items, item => ( + item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" + && item.message.Contains("independent model targets", StringComparison.Ordinal) + )); + Assert.True( + diagnostics.items.All(item => item.code != "RENDER_OUTPUT_COMPOSITION_FAILED"), + string.Join("\n", diagnostics.items.Select(item => item.message)) + ); + Assert.True(proxy.lastGraph is not null, string.Join("\n", diagnostics.items.Select(item => item.message))); + Assert.Contains(proxy.lastGraph.passes, pass => pass.name.Contains("Layer 2", StringComparison.Ordinal)); runtime.Detach(); } @@ -795,8 +882,10 @@ public void OutputWithoutAnApplicableModelReportsItsMissingRenderer() runtime.Render(default); runtime.AfterRender(default); runtime.EndFrame(default); - Assert.Contains(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" - && item.message.Contains("No rendering model", StringComparison.Ordinal)); + Assert.Contains(diagnostics.items, item => ( + item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" + && item.message.Contains("No rendering model", StringComparison.Ordinal) + )); runtime.Detach(); } @@ -813,12 +902,16 @@ public void LinearPresentationReceivesOneTransferAfterAllModelLayers() m_types, device, diagnostics, - compositionProgramProvider: new TestCompositionProgramProvider()); - runtime.SetPrimaryRoute(new RenderOutputRoute( - [ - new RenderOutputLayer(FirstTestRenderModel.extensionId, []), - new RenderOutputLayer(SecondTestRenderModel.extensionId, []) - ])); + compositionProgramProvider: new TestCompositionProgramProvider() + ); + runtime.SetPrimaryRoute( + new RenderOutputRoute( + [ + new RenderOutputLayer(FirstTestRenderModel.extensionId, []), + new RenderOutputLayer(SecondTestRenderModel.extensionId, []) + ] + ) + ); BeginRenderFrame(runtime, 0f); runtime.Render(default); @@ -829,11 +922,12 @@ public void LinearPresentationReceivesOneTransferAfterAllModelLayers() Assert.NotNull(proxy.lastGraph); Assert.Single(proxy.lastGraph.passes.Where(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal))); Assert.Contains("Output Transfer", proxy.lastGraph.passes[^1].name, StringComparison.Ordinal); - Assert.Contains(proxy.lastGraph.textures, texture => + Assert.Contains(proxy.lastGraph.textures, texture => ( texture.name.EndsWith("/Composition", StringComparison.Ordinal) && texture.descriptor.width == 800 && texture.descriptor.height == 600 - && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb); + && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb + )); runtime.Detach(); } @@ -851,7 +945,8 @@ public void SingleModelPresentationEncodesColorExactlyOnce(bool presentationEnco m_types, device, diagnostics, - compositionProgramProvider: new TestCompositionProgramProvider()); + compositionProgramProvider: new TestCompositionProgramProvider() + ); BeginRenderFrame(runtime, 0f); runtime.Render(default); @@ -861,16 +956,21 @@ public void SingleModelPresentationEncodesColorExactlyOnce(bool presentationEnco Assert.Equal(1, FirstTestRenderModel.buildCount); Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_COMPOSITION_FAILED"); Assert.NotNull(proxy.lastGraph); - Assert.Equal(presentationEncodesSrgb ? 0 : 1, - proxy.lastGraph.passes.Count(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal))); - Assert.DoesNotContain(proxy.lastGraph.textures, - texture => texture.name.EndsWith("/Composition", StringComparison.Ordinal)); + Assert.Equal( + presentationEncodesSrgb ? 0 : 1, + proxy.lastGraph.passes.Count(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal)) + ); + Assert.DoesNotContain( + proxy.lastGraph.textures, + texture => texture.name.EndsWith("/Composition", StringComparison.Ordinal) + ); if (!presentationEncodesSrgb) { Assert.Contains("Output Transfer", proxy.lastGraph.passes[^1].name, StringComparison.Ordinal); - Assert.Contains(proxy.lastGraph.textures, texture => + Assert.Contains(proxy.lastGraph.textures, texture => ( texture.name.Contains("Model Layer 1", StringComparison.Ordinal) - && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb); + && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb + )); } runtime.Detach(); } @@ -936,7 +1036,8 @@ public void OverlappingRequestsPreserveEarlierPresentationLayersInSchedulingOrde new PresentationObservation("Base", false), new PresentationObservation("Overlay", true) }, - PresentationPipeline.observations); + PresentationPipeline.observations + ); Assert.Equal(1, proxy.executeCount); runtime.Detach(); } @@ -947,16 +1048,8 @@ public void DisjointViewportsCanInitializeTheSamePresentationTargetIndependently IRenderDevice device = TestDeviceProxy.Create(out _); var asset = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.extensionId }; var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(new RenderRequest( - "Left", - RenderTarget.backbuffer, - new RenderViewport(0, 0, 32, 64), - asset)); - runtime.Submit(new RenderRequest( - "Right", - RenderTarget.backbuffer, - new RenderViewport(32, 0, 32, 64), - asset)); + runtime.Submit(new RenderRequest("Left", RenderTarget.backbuffer, new RenderViewport(0, 0, 32, 64), asset)); + runtime.Submit(new RenderRequest("Right", RenderTarget.backbuffer, new RenderViewport(32, 0, 32, 64), asset)); BeginRenderFrame(runtime, 0f); runtime.AfterRender(default); @@ -968,7 +1061,8 @@ public void DisjointViewportsCanInitializeTheSamePresentationTargetIndependently new PresentationObservation("Left", false), new PresentationObservation("Right", false) }, - PresentationPipeline.observations); + PresentationPipeline.observations + ); runtime.Detach(); } @@ -986,9 +1080,7 @@ public void FailedRequestDoesNotClaimThePresentationTarget() runtime.AfterRender(default); runtime.EndFrame(default); - Assert.Equal( - new[] { new PresentationObservation("Recovery", false) }, - PresentationPipeline.observations); + Assert.Equal(new[] { new PresentationObservation("Recovery", false) }, PresentationPipeline.observations); runtime.Detach(); } @@ -1003,7 +1095,9 @@ public void ReplacedAndReleasedTargetsRemainValidAcrossPreparedPresentationFrame 32, 32, RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); device.BeginFrame(); registry.PrepareFrame(); @@ -1011,11 +1105,14 @@ public void ReplacedAndReleasedTargetsRemainValidAcrossPreparedPresentationFrame _ = device.EndFrame(); PersistentTextureHandle first = Assert.Single(proxy.createdTextures); - target.Resize(new RenderTextureDescriptor( - 64, - 64, - RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); + target.Resize( + new RenderTextureDescriptor( + 64, + 64, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); device.BeginFrame(); registry.PrepareFrame(); _ = registry.Import(new RenderGraphBuilder(2, device.capabilities), target); @@ -1057,16 +1154,11 @@ public void DetachUsesADeviceSafetyFrameToReleaseResidentTargets() var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.extensionId }; var target = new RenderTexture( "Detach Target", - new RenderTextureDescriptor( - 16, - 16, - RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment)); - runtime.Submit(new RenderRequest( - "Detach", - RenderTarget.FromTexture(target), - new RenderViewport(0, 0, 16, 16), - asset)); + new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment) + ); + runtime.Submit( + new RenderRequest("Detach", RenderTarget.FromTexture(target), new RenderViewport(0, 0, 16, 16), asset) + ); BeginRenderFrame(runtime, 0f); runtime.AfterRender(default); @@ -1148,11 +1240,7 @@ public void TexturePrewarmRunsOutsideTheRenderFrameAndDoesNotDelaySubmission() var device = new RecordingRenderDevice(); var asset = new RenderPipelineAsset { pipelineTypeId = TexturePrewarmPipeline.extensionId }; var artifacts = new DelayedArtifactProvider(compiler); - var runtime = new RenderRuntime( - m_types, - device, - new TestDiagnosticSink(), - targetArtifacts: artifacts); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), targetArtifacts: artifacts); runtime.Submit(CreateRequest("Prewarm", asset)); BeginRenderFrame(runtime, 0f); @@ -1183,9 +1271,12 @@ public void PendingShaderCompilationDoesNotPublishAnUnavailableArtifactError() [new ShaderTechniqueDefinition( new ShaderTechniqueId("default"), contract, - [new ShaderTechniquePass(role, pass.name)])]), + [new ShaderTechniquePass(role, pass.name)] + )] + ), m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); PendingShaderPipeline.material = new MaterialAsset { shader = shader }; PendingShaderPipeline.contract = contract; PendingShaderPipeline.role = role; @@ -1196,7 +1287,8 @@ [new ShaderTechniquePass(role, pass.name)])]), m_types, new RecordingRenderDevice(), diagnostics, - targetArtifacts: new DelayedArtifactProvider(compiler)); + targetArtifacts: new DelayedArtifactProvider(compiler) + ); var asset = new RenderPipelineAsset { pipelineTypeId = PendingShaderPipeline.extensionId }; runtime.Submit(CreateRequest("Pending Shader", asset)); @@ -1207,7 +1299,8 @@ [new ShaderTechniquePass(role, pass.name)])]), Assert.False(PendingShaderPipeline.resolved); Assert.DoesNotContain( diagnostics.items, - static diagnostic => diagnostic.code == "RENDER_SHADER_TARGET_UNAVAILABLE"); + static diagnostic => diagnostic.code == "RENDER_SHADER_TARGET_UNAVAILABLE" + ); runtime.Detach(); } @@ -1227,7 +1320,8 @@ public async Task PersistentTextureRegionUpdateAndReadbackCompleteAcrossFrameBou Assert.Equal(new RenderTextureRegion(0, 1, 1, 0, 2, 2), device.updatedRegion); Assert.Equal(Enumerable.Range(0, 16).Select(static value => (byte)value), device.updatedBytes); Task readback = Assert.IsType>( - ReadbackPipeline.readback); + ReadbackPipeline.readback + ); Assert.False(readback.IsCompleted); device.readbackReady = true; @@ -1285,7 +1379,8 @@ public async Task CancelingReadbackReleasesTheDeviceOperationAtTheNextFrameBound runtime.EndFrame(default); cancellation.Cancel(); Task readback = Assert.IsType>( - ReadbackPipeline.readback); + ReadbackPipeline.readback + ); Assert.False(readback.IsCompleted); BeginRenderFrame(runtime, 0f); await Assert.ThrowsAnyAsync(async () => await readback); @@ -1299,40 +1394,37 @@ public async Task CancelingReadbackReleasesTheDeviceOperationAtTheNextFrameBound private static RenderRequest CreateRequest( string name, RenderPipelineAsset pipeline, - int priority = 0) - => new( - name, - RenderTarget.backbuffer, - new RenderViewport(0, 0, 64, 64), - pipeline, - priority: priority); + int priority = 0 + ) => new(name, RenderTarget.backbuffer, new RenderViewport(0, 0, 64, 64), pipeline, priority: priority); private DotNetModuleSource CreateRenderingPluginRequest() => new() - { - moduleName = "RenderingRuntimeReloadTests", - artifactRootDirectory = Path.Combine(m_cacheDirectory, "Modules"), - mainAssemblyPath = Path.Combine( - AppContext.BaseDirectory, - "Modules", - "RenderingReload", - "Inno.Rendering.Runtime.Reload.TestModule.dll"), - domain = AssemblyDomain.InnoPlugin, - scope = AssemblyScope.Runtime - }; + { + moduleName = "RenderingRuntimeReloadTests", + artifactRootDirectory = Path.Combine(m_cacheDirectory, "Modules"), + mainAssemblyPath = Path.Combine( + AppContext.BaseDirectory, + "Modules", + "RenderingReload", + "Inno.Rendering.Runtime.Reload.TestModule.dll" + ), + domain = AssemblyDomain.InnoPlugin, + scope = AssemblyScope.Runtime + }; [MethodImpl(MethodImplOptions.NoInlining)] private static ( IAssemblyUnloadProbe monitor, IRenderRuntimeReloadTransaction transaction) RemoveRenderingPlugin( - RenderRuntime runtime, - ModuleHost modules, - DotNetModuleSource plugin) - { + RenderRuntime runtime, + ModuleHost modules, + DotNetModuleSource plugin + ) { IRenderRuntimeReloadTransaction rendering = runtime.BeginExtensionReload(); using AssemblyReloadSession removal = modules.BeginReload( Array.Empty(), - [plugin.moduleName]); + [plugin.moduleName] + ); removal.Activate(); rendering.Prepare(); rendering.Activate(); @@ -1344,11 +1436,12 @@ private static ( [MethodImpl(MethodImplOptions.NoInlining)] private static IAssemblyUnloadProbe RemoveUnusedPlugin( ModuleHost modules, - DotNetModuleSource plugin) - { + DotNetModuleSource plugin + ) { using AssemblyReloadSession removal = modules.BeginReload( Array.Empty(), - [plugin.moduleName]); + [plugin.moduleName] + ); removal.Activate(); return removal.Complete(); } @@ -1357,24 +1450,28 @@ private static IAssemblyUnloadProbe RemoveUnusedPlugin( private static void QueueCollectiblePayload( RenderRuntime runtime, TypeCatalog types, - RenderPipelineAsset pipeline) - { + RenderPipelineAsset pipeline + ) { Type payloadType = types.current.types .Select(type => type.Resolve(types)) .Single(type => string.Equals( type.FullName, "Inno.Rendering.Runtime.Reload.TestModule.ReloadableFramePayload", - StringComparison.Ordinal)); + StringComparison.Ordinal + )); object payload = Activator.CreateInstance(payloadType) - ?? throw new InvalidOperationException("The collectible frame payload could not be created."); + ?? throw new InvalidOperationException("The collectible frame payload could not be created."); var data = new RenderFrameData(); data.Set(new RenderDataChannelId("tests.runtime.collectible-payload"), payload); - runtime.Submit(new RenderRequest( - "Collectible Pending Request", - RenderTarget.backbuffer, - new RenderViewport(0, 0, 64, 64), - pipeline, - data)); + runtime.Submit( + new RenderRequest( + "Collectible Pending Request", + RenderTarget.backbuffer, + new RenderViewport(0, 0, 64, 64), + pipeline, + data + ) + ); } [MethodImpl(MethodImplOptions.NoInlining)] @@ -1387,10 +1484,14 @@ private static void ForceCollection() } } - private static void BeginRenderFrame(RenderRuntime runtime, float deltaTime) - { + private static void BeginRenderFrame( + RenderRuntime runtime, + float deltaTime + ) { if (!runtime.isStarted) + { runtime.Attach(); + } var frame = new RuntimeFrame(0, deltaTime, deltaTime, 0, 0, 1, false); runtime.BeginFrame(frame); runtime.BeforeRender(frame); @@ -1404,15 +1505,26 @@ private sealed class FirstTestRenderModel : IRenderModel internal const string extensionId = "tests.runtime.model.first"; internal static bool enabled; internal static int buildCount; + public bool CanRender(RenderOutputSession session) => enabled; + public RenderModelOutput Build(RenderOutputSession session) { buildCount++; - return new RenderModelOutput("First Model", - new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.extensionId }, new RenderFrameData()); + return new RenderModelOutput( + "First Model", + new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.extensionId }, + new RenderFrameData() + ); + } + + public void Dispose() {} + + internal static void Reset() + { + enabled = false; + buildCount = 0; } - public void Dispose() { } - internal static void Reset() { enabled = false; buildCount = 0; } } [RenderModelExtension(extensionId)] @@ -1421,15 +1533,26 @@ private sealed class SecondTestRenderModel : IRenderModel internal const string extensionId = "tests.runtime.model.second"; internal static bool enabled; internal static int buildCount; + public bool CanRender(RenderOutputSession session) => enabled; + public RenderModelOutput Build(RenderOutputSession session) { buildCount++; - return new RenderModelOutput("Second Model", - new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.extensionId }, new RenderFrameData()); + return new RenderModelOutput( + "Second Model", + new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.extensionId }, + new RenderFrameData() + ); + } + + public void Dispose() {} + + internal static void Reset() + { + enabled = false; + buildCount = 0; } - public void Dispose() { } - internal static void Reset() { enabled = false; buildCount = 0; } } [RenderPipelineExtension(extensionId)] @@ -1448,11 +1571,15 @@ private sealed class DisposablePipeline : RenderPipeline public override void Build(RenderPipelineContext context) => _ = context; - protected override void OnConfigure(SerializedRenderExtensionState state, RenderExtensionStateContext settings) - { + protected override void OnConfigure( + SerializedRenderExtensionState state, + RenderExtensionStateContext settings + ) { _ = state; if (rejectConfiguration) + { throw new InvalidOperationException("Rejected pipeline configuration candidate."); + } } internal static void Reset() @@ -1470,7 +1597,9 @@ protected override void Dispose(bool disposing) _ = disposing; retirementAttempts++; if (retirementExpired) + { throw new RetirementTimeoutException("The pipeline-owned device work exceeded its deadline."); + } if (pendingRetirements > 0) { pendingRetirements--; @@ -1487,7 +1616,7 @@ private sealed class PendingFeature : RenderPipelineFeature, IDisposable internal static int pendingRetirements { get; set; } internal static int retirementAttempts { get; private set; } - public override void AddRenderPasses(RenderFeatureContext context) { } + public override void AddRenderPasses(RenderFeatureContext context) {} public void Dispose() { @@ -1519,13 +1648,21 @@ public override void Build(RenderPipelineContext context) "Visible", new RenderPhaseId("tests.statistics.visible"), 0, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); context.graph.AddRasterPass( "Culled", new RenderPhaseId("tests.statistics.culled"), 0, - static (_, _) => { }); + static ( + _, + _ + ) => {} + ); } } @@ -1538,15 +1675,29 @@ private sealed class CompositionLayerPipeline : RenderPipeline public override void Build(RenderPipelineContext context) { viewports.Add(context.request.viewport); - RasterPassBuilder pass = context.graph.AddRasterPass("Scene Color", - new RenderPhaseId("tests.runtime.composition-layer"), 0, - static (_, _) => { }); + RasterPassBuilder pass = context.graph.AddRasterPass( + "Scene Color", + new RenderPhaseId("tests.runtime.composition-layer"), + 0, + static ( + _, + _ + ) => {} + ); if (context.outputTexture.isValid) - pass.UseColorAttachment(context.outputTexture, 0, - RenderLoadAction.Clear, RenderStoreAction.Store, - new RenderClearColor(0f, 0f, 0f, 0f)); + { + pass.UseColorAttachment( + context.outputTexture, + 0, + RenderLoadAction.Clear, + RenderStoreAction.Store, + new RenderClearColor(0f, 0f, 0f, 0f) + ); + } else + { pass.ClearPresentationTarget(default).HasSideEffect(); + } } } @@ -1562,7 +1713,11 @@ public override void Build(RenderPipelineContext context) "Visible", new RenderPhaseId("tests.runtime.visible"), 0, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); } } @@ -1576,15 +1731,17 @@ private sealed class PresentationPipeline : RenderPipeline public override void Build(RenderPipelineContext context) { - observations.Add(new PresentationObservation( - context.request.name, - context.preservePresentationTarget)); + observations.Add(new PresentationObservation(context.request.name, context.preservePresentationTarget)); context.graph .AddRasterPass( "Presentation", new RenderPhaseId("tests.runtime.presentation"), 0, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); } @@ -1603,7 +1760,11 @@ public override void Build(RenderPipelineContext context) "Rolled Back", new RenderPhaseId("tests.runtime.rolled-back"), 0, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); throw new InvalidOperationException("Expected request failure."); } @@ -1611,7 +1772,8 @@ public override void Build(RenderPipelineContext context) private readonly record struct PresentationObservation( string requestName, - bool preserveTarget); + bool preserveTarget + ); [RenderPipelineExtension(extensionId)] private sealed class UploadPipeline : RenderPipeline @@ -1625,20 +1787,15 @@ private sealed class UploadPipeline : RenderPipeline public override void Build(RenderPipelineContext context) { var layout = new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ]); - var descriptor = new RenderBufferUploadDescriptor( - layout.stride, - RenderBufferUsage.Vertex, - layout); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ] + ); + var descriptor = new RenderBufferUploadDescriptor(layout.stride, RenderBufferUsage.Vertex, layout); firstSlice = context.uploads.UploadBuffer(descriptor, new byte[layout.stride * 3], "Vertices"); if (!singleUpload) { - secondSlice = context.uploads.UploadBuffer( - descriptor, - new byte[layout.stride * 3], - "Vertices"); + secondSlice = context.uploads.UploadBuffer(descriptor, new byte[layout.stride * 3], "Vertices"); } } @@ -1660,13 +1817,18 @@ private sealed class TexturePrewarmPipeline : RenderPipeline public override void Build(RenderPipelineContext context) { context.resourceService.PrewarmTexture( - texture ?? throw new InvalidOperationException("A test texture is required.")); + texture ?? throw new InvalidOperationException("A test texture is required.") + ); context.graph .AddRasterPass( "Submit While Prewarming", new RenderPhaseId("tests.runtime.prewarm"), 0, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); } } @@ -1689,13 +1851,18 @@ public override void Build(RenderPipelineContext context) role, null, null, - out _); + out _ + ); context.graph .AddRasterPass( "Submit While Compiling", new RenderPhaseId("tests.runtime.pending-shader"), 0, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); } @@ -1720,10 +1887,7 @@ private sealed class ReadbackPipeline : RenderPipeline public override void Build(RenderPipelineContext context) { byte[] update = Enumerable.Range(0, 16).Select(static value => (byte)value).ToArray(); - context.resourceService.UpdateTexture( - texture, - new RenderTextureRegion(0, 1, 1, 0, 2, 2), - update); + context.resourceService.UpdateTexture(texture, new RenderTextureRegion(0, 1, 1, 0, 2, 2), update); readback ??= context.resourceService .ReadTextureAsync(texture, cancellationToken: cancellationToken) .AsTask(); @@ -1732,7 +1896,11 @@ public override void Build(RenderPipelineContext context) "Readback Submission", new RenderPhaseId("tests.runtime.readback"), 0, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); } @@ -1761,16 +1929,18 @@ private sealed class TestRequestProvider : RenderRequestProvider public override void Submit(RenderRequestProviderContext context) { if (!enabled) + { return; + } submitCount++; lastContent = context.content; lastPresentationViewport = context.primaryPresentationViewport; lastInput = context.input; if (pipeline is null) + { return; - context.requests.Submit(CreateRequest( - "Provider Request", - pipeline)); + } + context.requests.Submit(CreateRequest("Provider Request", pipeline)); } internal static void Reset() @@ -1800,14 +1970,21 @@ private sealed class SideEffectContributor : IRenderFrameGraphContributor { public void PrepareFrame(ulong frameIndex) => _ = frameIndex; - public void AddRenderPasses(RenderGraphBuilder graph, ulong frameIndex) - { + public void AddRenderPasses( + RenderGraphBuilder graph, + ulong frameIndex + ) { _ = frameIndex; - graph.AddRasterPass( + graph + .AddRasterPass( "Overlay", new RenderPhaseId("tests.runtime.overlay"), 0, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); } } @@ -1818,10 +1995,14 @@ private sealed class TestDiagnosticSink : IDiagnosticReporter public void Publish(Diagnostic diagnostic) => items.Add(diagnostic); - public void Resolve(string code, string? semanticId = null, Guid? objectId = null) - => items.RemoveAll(diagnostic => - string.Equals(diagnostic.code, code, StringComparison.Ordinal) && - string.Equals(diagnostic.semanticId, semanticId, StringComparison.Ordinal) && diagnostic.objectId == objectId); + public void Resolve( + string code, + string? semanticId = null, + Guid? objectId = null + ) => items.RemoveAll(diagnostic => ( + string.Equals(diagnostic.code, code, StringComparison.Ordinal) + && string.Equals(diagnostic.semanticId, semanticId, StringComparison.Ordinal) && diagnostic.objectId == objectId + )); public void Replace(IEnumerable diagnostics) { @@ -1841,12 +2022,15 @@ private sealed class TestDeviceProxy : RenderDevice, IRenderDevice [], [], originBottomLeft: false, - homogeneousDepth: false); + homogeneousDepth: false + ); public RenderDeviceFrameCounters frameCounters { get; internal set; } public RenderDeviceAllocationCounters? allocationCounters { get; internal set; } internal bool verticalSync { get; private set; } + public void SetVerticalSync(bool enabled) => verticalSync = enabled; + internal List createdBuffers { get; } = []; internal List destroyedBuffers { get; } = []; internal int failBufferCreationAt { get; set; } @@ -1872,11 +2056,13 @@ internal static IRenderDevice Create(out TestDeviceProxy proxy) public GraphicsCapabilities capabilities { get; internal set; } = S_CAPABILITIES; public uint generation => 1; public RenderPresentationSize? presentationSize { get; set; } = new(1, 1); + public RenderPresentationSize? primaryPresentationSize { get => presentationSize; private set => presentationSize = value; } + public bool primaryPresentationEncodesSrgb { get; set; } = true; public void BeginFrame() @@ -1885,8 +2071,10 @@ public void BeginFrame() frameOpen = true; } - public void Execute(CompiledRenderGraph graph, ulong frameIndex) - { + public void Execute( + CompiledRenderGraph graph, + ulong frameIndex + ) { Assert.True(frameOpen); _ = frameIndex; executeCount++; @@ -1906,14 +2094,17 @@ public void SetPrimaryPresentationSize(RenderPresentationSize? size) primaryPresentationSize = size; } - public PersistentTextureHandle CreateTexture(RenderTextureDescriptor descriptor, string name) - { + public PersistentTextureHandle CreateTexture( + RenderTextureDescriptor descriptor, + string name + ) { Assert.True(frameOpen); _ = descriptor; _ = name; PersistentTextureHandle texture = CreatePersistentTextureHandle( checked((ulong)createdTextures.Count + 1), - generation); + generation + ); createdTextures.Add(texture); return texture; } @@ -1922,8 +2113,8 @@ public void UpdateTexture( PersistentTextureHandle texture, ReadOnlySpan data, int mipLevel = 0, - int arrayLayer = 0) - { + int arrayLayer = 0 + ) { _ = texture; _ = data; _ = mipLevel; @@ -1933,8 +2124,8 @@ public void UpdateTexture( public void UpdateTextureRegion( PersistentTextureHandle texture, RenderTextureRegion region, - ReadOnlySpan data) - { + ReadOnlySpan data + ) { _ = texture; _ = region; _ = data; @@ -1942,8 +2133,8 @@ public void UpdateTextureRegion( public RenderTextureReadbackHandle BeginTextureReadback( PersistentTextureHandle texture, - int mipLevel = 0) - { + int mipLevel = 0 + ) { _ = texture; _ = mipLevel; return default; @@ -1951,8 +2142,8 @@ public RenderTextureReadbackHandle BeginTextureReadback( public bool TryGetTextureReadback( RenderTextureReadbackHandle readback, - out RenderTextureReadbackResult? result) - { + out RenderTextureReadbackResult? result + ) { _ = readback; result = null; return false; @@ -1977,10 +2168,16 @@ public void DestroyTexture(PersistentTextureHandle texture) destroyedTextures.Add(texture); } - public PersistentBufferHandle CreateBuffer(PersistentBufferDescriptor descriptor, ReadOnlySpan initialData, string name) - { + public PersistentBufferHandle CreateBuffer( + PersistentBufferDescriptor descriptor, + ReadOnlySpan initialData, + string name + ) { m_bufferCreationCount++; - if (m_bufferCreationCount == failBufferCreationAt) throw new InvalidOperationException("Native allocation rejected."); + if (m_bufferCreationCount == failBufferCreationAt) + { + throw new InvalidOperationException("Native allocation rejected."); + } PersistentBufferHandle handle = CreatePersistentBufferHandle((ulong)m_bufferCreationCount, generation); createdBuffers.Add(handle); return handle; @@ -1989,8 +2186,8 @@ public PersistentBufferHandle CreateBuffer(PersistentBufferDescriptor descriptor public void UpdateBuffer( PersistentBufferHandle buffer, ReadOnlySpan data, - int startElement = 0) - { + int startElement = 0 + ) { _ = buffer; _ = data; _ = startElement; @@ -2004,8 +2201,8 @@ public void DestroyBuffer(PersistentBufferHandle buffer) public GraphicsPipelineHandle CreateGraphicsPipeline( GraphicsPipelineDescriptor descriptor, - string name) - { + string name + ) { _ = descriptor; _ = name; return default; @@ -2015,8 +2212,8 @@ public GraphicsPipelineHandle CreateGraphicsPipeline( public ComputePipelineHandle CreateComputePipeline( ComputePipelineDescriptor descriptor, - string name) - { + string name + ) { _ = descriptor; _ = name; return default; @@ -2024,7 +2221,7 @@ public ComputePipelineHandle CreateComputePipeline( public void DestroyComputePipeline(ComputePipelineHandle pipeline) => _ = pipeline; - public void Dispose() { } + public void Dispose() {} } private sealed class RecordingRenderDevice : RenderDevice, IRenderDevice @@ -2037,13 +2234,16 @@ private sealed class RecordingRenderDevice : RenderDevice, IRenderDevice internal int failedProgramRetirements { get; set; } internal int programRetirementAttempts { get; private set; } internal bool verticalSync { get; private set; } + public void SetVerticalSync(bool enabled) => verticalSync = enabled; private readonly RenderTextureDescriptor m_readbackDescriptor = new( 4, 4, RenderTextureFormat.RGBA8, - RenderTextureUsage.Readback); + RenderTextureUsage.Readback + ); + private readonly RenderTextureReadbackHandle m_readbackHandle; internal List bufferUpdateOffsets { get; } = []; @@ -2070,7 +2270,8 @@ internal RecordingRenderDevice(bool supportsReadback = false) [], [], originBottomLeft: false, - homogeneousDepth: false); + homogeneousDepth: false + ); textureHandle = CreatePersistentTextureHandle(1UL, generation); m_readbackHandle = CreateRenderTextureReadbackHandle(1UL, generation); } @@ -2081,10 +2282,12 @@ internal RecordingRenderDevice(bool supportsReadback = false) public RenderPresentationSize? primaryPresentationSize { get; private set; } = new(1, 1); public bool primaryPresentationEncodesSrgb => true; - public void BeginFrame() { } + public void BeginFrame() {} - public void Execute(CompiledRenderGraph graph, ulong frameIndex) - { + public void Execute( + CompiledRenderGraph graph, + ulong frameIndex + ) { _ = graph; _ = frameIndex; executeCount++; @@ -2098,8 +2301,10 @@ public uint EndFrame() public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; - public PersistentTextureHandle CreateTexture(RenderTextureDescriptor descriptor, string name) - { + public PersistentTextureHandle CreateTexture( + RenderTextureDescriptor descriptor, + string name + ) { _ = descriptor; _ = name; return default; @@ -2109,8 +2314,8 @@ public void UpdateTexture( PersistentTextureHandle texture, ReadOnlySpan data, int mipLevel = 0, - int arrayLayer = 0) - { + int arrayLayer = 0 + ) { _ = texture; _ = data; _ = mipLevel; @@ -2120,8 +2325,8 @@ public void UpdateTexture( public void UpdateTextureRegion( PersistentTextureHandle texture, RenderTextureRegion region, - ReadOnlySpan data) - { + ReadOnlySpan data + ) { Assert.Equal(textureHandle, texture); updatedRegion = region; updatedBytes = data.ToArray(); @@ -2129,8 +2334,8 @@ public void UpdateTextureRegion( public RenderTextureReadbackHandle BeginTextureReadback( PersistentTextureHandle texture, - int mipLevel = 0) - { + int mipLevel = 0 + ) { Assert.Equal(textureHandle, texture); _ = mipLevel; return m_readbackHandle; @@ -2138,16 +2343,17 @@ public RenderTextureReadbackHandle BeginTextureReadback( public bool TryGetTextureReadback( RenderTextureReadbackHandle readback, - out RenderTextureReadbackResult? result) - { + out RenderTextureReadbackResult? result + ) { Assert.Equal(m_readbackHandle, readback); result = readbackReady - ? new RenderTextureReadbackResult( - m_readbackDescriptor, - 0, - 16, - Enumerable.Repeat((byte)37, 64).ToArray()) - : null; + ? new RenderTextureReadbackResult( + m_readbackDescriptor, + 0, + 16, + Enumerable.Repeat((byte)37, 64).ToArray() + ) + : null; return result is not null; } @@ -2169,8 +2375,8 @@ public void CancelTextureReadback(RenderTextureReadbackHandle readback) public PersistentBufferHandle CreateBuffer( PersistentBufferDescriptor descriptor, ReadOnlySpan initialData, - string name) - { + string name + ) { _ = descriptor; _ = initialData; _ = name; @@ -2181,8 +2387,8 @@ public PersistentBufferHandle CreateBuffer( public void UpdateBuffer( PersistentBufferHandle buffer, ReadOnlySpan data, - int startElement = 0) - { + int startElement = 0 + ) { _ = buffer; _ = data; bufferUpdateOffsets.Add(startElement); @@ -2203,8 +2409,8 @@ public void DestroyBuffer(PersistentBufferHandle buffer) public GraphicsPipelineHandle CreateGraphicsPipeline( GraphicsPipelineDescriptor descriptor, - string name) - { + string name + ) { if (name == failProgramName) throw new InvalidOperationException("Injected program allocation failure."); GraphicsPipelineHandle handle = CreateGraphicsPipelineHandle(checked((ulong)createdPrograms.Count + 1), generation); createdPrograms.Add(handle); @@ -2231,8 +2437,8 @@ public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) public ComputePipelineHandle CreateComputePipeline( ComputePipelineDescriptor descriptor, - string name) - { + string name + ) { _ = descriptor; _ = name; return default; @@ -2240,14 +2446,14 @@ public ComputePipelineHandle CreateComputePipeline( public void DestroyComputePipeline(ComputePipelineHandle pipeline) => _ = pipeline; - public void Dispose() { } - + public void Dispose() {} } private sealed class DelayedTextureArtifactSource { private readonly TaskCompletionSource m_completion = new( - TaskCreationOptions.RunContinuationsAsynchronously); + TaskCreationOptions.RunContinuationsAsynchronously + ); internal ManualResetEventSlim started { get; } = new(initialState: false); internal bool isCompleted => m_completion.Task.IsCompleted; @@ -2261,8 +2467,7 @@ internal Task LoadAsync(CancellationToken cancellationToken = default) internal void Complete(byte[] data) => m_completion.TrySetResult(data); } - private sealed class DelayedArtifactProvider(DelayedTextureArtifactSource compiler) - : IRenderTargetArtifactProvider + private sealed class DelayedArtifactProvider(DelayedTextureArtifactSource compiler) : IRenderTargetArtifactProvider { private Task? m_texture; @@ -2273,8 +2478,8 @@ public RenderTargetArtifactStatus GetShaderArtifact( ShaderAsset shader, RenderShaderVariant variant, GraphicsCapabilities capabilities, - out RenderShaderArtifact? artifact) - { + out RenderShaderArtifact? artifact + ) { _ = shader; _ = variant; _ = capabilities; @@ -2284,8 +2489,8 @@ public RenderTargetArtifactStatus GetShaderArtifact( public RenderTargetArtifactStatus GetTextureArtifact( RenderTextureArtifactReference texture, - out ReadOnlyMemory artifact) - { + out ReadOnlyMemory artifact + ) { _ = texture; m_texture ??= compiler.LoadAsync(); if (m_texture.IsCompletedSuccessfully) @@ -2301,18 +2506,26 @@ public RenderTargetArtifactStatus GetTextureArtifact( private sealed class TestCompositionProgramProvider : IRenderLayerCompositionProgramProvider { public GraphicsPipelineDescriptor CreateDescriptor( - GraphicsCapabilities capabilities, RenderVertexLayout vertexLayout) - { + GraphicsCapabilities capabilities, + RenderVertexLayout vertexLayout + ) { _ = capabilities; return new GraphicsPipelineDescriptor( - [1], [1], + [1], + [1], [new RenderShaderBindingDescriptor( - new RenderBindingId("s_tex"), RenderShaderBindingKind.Texture, 0, nativeName: "s_tex")], - vertexLayout); + new RenderBindingId("s_tex"), + RenderShaderBindingKind.Texture, + 0, + nativeName: "s_tex" + )], + vertexLayout + ); } public GraphicsPipelineDescriptor CreateOutputTransferDescriptor( - GraphicsCapabilities capabilities, RenderVertexLayout vertexLayout) - => CreateDescriptor(capabilities, vertexLayout); + GraphicsCapabilities capabilities, + RenderVertexLayout vertexLayout + ) => CreateDescriptor(capabilities, vertexLayout); } } diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs index 0f5fb659f..d1ff87e19 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Source; using System; using System.Collections.Generic; using System.Diagnostics; @@ -6,10 +5,11 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Text.Json; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Extensibility.Reload; using Inno.Rendering; -using Xunit; +using Inno.Testing.Source; namespace Inno.Rendering.Runtime.Tests; @@ -120,27 +120,41 @@ bool fail runtime.RegisterContributor(contributor); } for (int frame = 0; frame < 16; frame++) + { CompleteContributorFrame(runtime, proxy); + } const int frames = 64; long before = GC.GetAllocatedBytesForCurrentThread(); long start = Stopwatch.GetTimestamp(); for (int frame = 0; frame < frames; frame++) + { CompleteContributorFrame(runtime, proxy); + } double elapsedMs = Stopwatch.GetElapsedTime(start).TotalMilliseconds; long allocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before; Assert.All(contributors, contributor => Assert.Equal(frames + 16, contributor.builds)); Assert.Equal(frames + 16, proxy.endFrameCount); Assert.Equal(contributorCount != 0 && !fail ? frames + 16 : 0, proxy.executeCount); - string directory = Path.Combine(TestRepository.GetRoot(typeof(RenderRuntimeGenerationTests).Assembly), "artifacts/acceptance/architecture-cleanup/results"); + string directory = Path.Combine( + TestRepository.GetRoot(typeof(RenderRuntimeGenerationTests).Assembly), + "artifacts/acceptance/architecture-cleanup/results" + ); Directory.CreateDirectory(directory); - File.WriteAllText(Path.Combine(directory, $"frames-{contributorCount}-{fail}.json"), JsonSerializer.Serialize(new - { - contributorCount, fail, frames, elapsedMs, allocatedBytes, - bytesPerFrame = allocatedBytes / (double)frames, - millisecondsPerFrame = elapsedMs / frames, - graphCompileCount = ReadGraphCompileCount(runtime), - runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription - }, new JsonSerializerOptions { WriteIndented = true })); + File.WriteAllText( + Path.Combine(directory, $"frames-{contributorCount}-{fail}.json"), + JsonSerializer.Serialize(new + { + contributorCount, + fail, + frames, + elapsedMs, + allocatedBytes, + bytesPerFrame = allocatedBytes / (double)frames, + millisecondsPerFrame = elapsedMs / frames, + graphCompileCount = ReadGraphCompileCount(runtime), + runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription + }, new JsonSerializerOptions { WriteIndented = true }) + ); } [Theory] @@ -153,33 +167,50 @@ public void ContributorRetirementMeasurementsIncludeRegistrationAndTheFollowingE using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy proxy), new TestDiagnosticSink()); runtime.SetPrimaryModelOutputEnabled(false); CountingContributor[] contributors = Enumerable.Range(0, contributorCount) - .Select(static _ => new CountingContributor()).ToArray(); + .Select(static _ => new CountingContributor()) + .ToArray(); foreach (CountingContributor contributor in contributors) + { runtime.RegisterContributor(contributor); + } for (int cycle = 0; cycle < 16; cycle++) + { CompleteContributorRetirementCycle(runtime, proxy, contributors); + } const int cycles = 64; long before = GC.GetAllocatedBytesForCurrentThread(); long start = Stopwatch.GetTimestamp(); for (int cycle = 0; cycle < cycles; cycle++) + { CompleteContributorRetirementCycle(runtime, proxy, contributors); + } double elapsedMs = Stopwatch.GetElapsedTime(start).TotalMilliseconds; long allocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before; Assert.All(contributors, contributor => Assert.Equal(cycles + 16, contributor.builds)); Assert.Equal(2 * (cycles + 16), proxy.endFrameCount); Assert.Equal(contributorCount == 0 ? 0 : cycles + 16, proxy.executeCount); - string directory = Path.Combine(TestRepository.GetRoot(typeof(RenderRuntimeGenerationTests).Assembly), "artifacts/acceptance/architecture-cleanup/results"); + string directory = Path.Combine( + TestRepository.GetRoot(typeof(RenderRuntimeGenerationTests).Assembly), + "artifacts/acceptance/architecture-cleanup/results" + ); Directory.CreateDirectory(directory); - File.WriteAllText(Path.Combine(directory, $"retirement-{contributorCount}.json"), JsonSerializer.Serialize(new - { - contributorCount, cycles, frames = 2 * cycles, elapsedMs, allocatedBytes, - bytesPerCycle = allocatedBytes / (double)cycles, - millisecondsPerCycle = elapsedMs / cycles, - graphCompileCount = ReadGraphCompileCount(runtime), - runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription - }, new JsonSerializerOptions { WriteIndented = true })); + File.WriteAllText( + Path.Combine(directory, $"retirement-{contributorCount}.json"), + JsonSerializer.Serialize(new + { + contributorCount, + cycles, + frames = 2 * cycles, + elapsedMs, + allocatedBytes, + bytesPerCycle = allocatedBytes / (double)cycles, + millisecondsPerCycle = elapsedMs / cycles, + graphCompileCount = ReadGraphCompileCount(runtime), + runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription + }, new JsonSerializerOptions { WriteIndented = true }) + ); } private static void CompleteContributorRetirementCycle( @@ -189,10 +220,14 @@ IReadOnlyList contributors ) { CompleteContributorFrame(runtime, proxy); foreach (CountingContributor contributor in contributors) + { Assert.True(runtime.UnregisterContributor(contributor)); + } CompleteContributorFrame(runtime, proxy); foreach (CountingContributor contributor in contributors) + { runtime.RegisterContributor(contributor); + } } private static void CompleteContributorFrame( @@ -221,9 +256,11 @@ bool rejectGraph Type type = m_types.current.GetTypesImplementing() .Select(reference => reference.Resolve(m_types)) .Single(type => type.Name == "ReloadableContributor"); - var contributor = (IRenderFrameGraphContributor)Activator.CreateInstance(type, + var contributor = (IRenderFrameGraphContributor)Activator.CreateInstance( + type, new Action(value => Assert.True(runtime.UnregisterContributor(value))), - rejectGraph)!; + rejectGraph + )!; var weak = new WeakReference(contributor); runtime.RegisterContributor(contributor); CompleteContributorFrame(runtime, proxy); @@ -243,13 +280,19 @@ public void AddRenderPasses( ulong frameIndex ) { builds++; - graph.AddRasterPass(fail ? "Discarded" : "Accepted", new("tests.contributor"), 0, + graph.AddRasterPass( + fail ? "Discarded" : "Accepted", + new("tests.contributor"), + 0, static ( payload, context - ) => { }).HasSideEffect(); + ) => {} + ).HasSideEffect(); if (fail) + { throw new InvalidOperationException("Discard this contributor's complete mutation."); + } } } } diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Presentation.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Presentation.cs index f3231b6f0..ae43e5353 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Presentation.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Presentation.cs @@ -1,7 +1,7 @@ using System; +using Xunit; using Inno.Rendering; using Inno.Rendering.Assets; -using Xunit; namespace Inno.Rendering.Runtime.Tests; @@ -15,11 +15,21 @@ public void UnavailablePrimaryOutputSkipsInputScalingAndKeepsOffscreenWork() TestRequestProvider.enabled = true; FirstTestRenderModel.enabled = true; using var runtime = new RenderRuntime( - m_types, device, new TestDiagnosticSink(), - primaryInputSurfaceSizeProvider: static () => throw new InvalidOperationException("There is no primary input surface.")); + m_types, + device, + new TestDiagnosticSink(), + primaryInputSurfaceSizeProvider: static () => throw new InvalidOperationException("There is no primary input surface.") + ); var asset = new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.extensionId }; - var target = new RenderTexture("Offscreen", new RenderTextureDescriptor( - 32, 24, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled)); + var target = new RenderTexture( + "Offscreen", + new RenderTextureDescriptor( + 32, + 24, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); runtime.Submit(new RenderRequest("Offscreen", RenderTarget.FromTexture(target), new RenderViewport(0, 0, 32, 24), asset)); runtime.Submit(new RenderRequest("Unavailable", RenderTarget.backbuffer, new RenderViewport(0, 0, 32, 24), asset)); BeginRenderFrame(runtime, 0f); @@ -78,7 +88,11 @@ public void UnavailableLogicalInputSurfaceDoesNotDispatchPrimaryInteraction() proxy.presentationSize = new RenderPresentationSize(1280, 720); TestRequestProvider.enabled = true; using var runtime = new RenderRuntime( - m_types, device, new TestDiagnosticSink(), primaryInputSurfaceSizeProvider: static () => null); + m_types, + device, + new TestDiagnosticSink(), + primaryInputSurfaceSizeProvider: static () => null + ); BeginRenderFrame(runtime, 0f); runtime.Render(default); runtime.AfterRender(default); diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs index 62b0b9d57..c70a498aa 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using Xunit; using Inno.Core.Serialization; using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; using Inno.Rendering.Runtime; @@ -25,14 +25,38 @@ public void ExplicitArtifactScopesDoNotPublishIntoCanonicalMaterialCachesAndRele ResourceProbePipeline.action = resources => { Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out var saved)); - Assert.True(resources.TryResolveMaterialArtifact(new("preview/document"), draft, material, new("test.publication"), - new("draw"), ShaderProgramKind.Raster, null, null, previewDiagnostics, out var edited)); + Assert.True( + resources.TryResolveMaterialArtifact( + new("preview/document"), + draft, + material, + new("test.publication"), + new("draw"), + ShaderProgramKind.Raster, + null, + null, + previewDiagnostics, + out var edited + ) + ); Assert.Equal("saved", saved!.definition.name); Assert.Equal("draft", edited!.definition.name); canonical = saved.graphicsPipeline; preview = edited.graphicsPipeline; Assert.NotEqual(canonical, preview); - Assert.True(resources.TryResolveMaterialArtifact(new("preview/document"), Publication("next-frame"), material, new("test.publication"), - new("draw"), ShaderProgramKind.Raster, null, null, previewDiagnostics, out var sameFrame)); + Assert.True( + resources.TryResolveMaterialArtifact( + new("preview/document"), + Publication("next-frame"), + material, + new("test.publication"), + new("draw"), + ShaderProgramKind.Raster, + null, + null, + previewDiagnostics, + out var sameFrame + ) + ); Assert.Equal(preview, sameFrame!.graphicsPipeline); }; RunResourceFrame(runtime); @@ -63,8 +87,20 @@ public void InvalidDraftProgramKeepsOnlyItsOwnLastGoodAndReportsOnlyToItsConsume GraphicsPipelineHandle lastGood = default; ResourceProbePipeline.action = resources => { - Assert.True(resources.TryResolveMaterialArtifact(new("preview/a"), draft, material, new("test.publication"), - new("draw"), ShaderProgramKind.Raster, null, null, preview, out var pass)); + Assert.True( + resources.TryResolveMaterialArtifact( + new("preview/a"), + draft, + material, + new("test.publication"), + new("draw"), + ShaderProgramKind.Raster, + null, + null, + preview, + out var pass + ) + ); if (lastGood.isValid) Assert.Equal(lastGood, pass!.graphicsPipeline); lastGood = pass!.graphicsPipeline; }; @@ -97,8 +133,16 @@ public void ShaderProgramsFollowPublishedContentNotTheLatestAssetDefinitionOrIts RenderMaterialPass Read() { RenderMaterialPass? pass = null; - ResourceProbePipeline.action = resources => Assert.True(resources.TryResolveGraphicsMaterial(material, - new("test.publication"), new("draw"), null, null, out pass)); + ResourceProbePipeline.action = resources => Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new("test.publication"), + new("draw"), + null, + null, + out pass + ) + ); RunResourceFrame(runtime); return Assert.IsType(pass); } @@ -129,7 +173,16 @@ public void AllPreviouslyUsedPassesMustBeCreatedBeforeAnyReplacementIsPublished( resolved.Clear(); foreach (string role in new[] { "draw", "shadow" }) { - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new(role), null, null, out RenderMaterialPass? pass)); + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new("test.publication"), + new(role), + null, + null, + out RenderMaterialPass? pass + ) + ); resolved.Add(pass!.graphicsPipeline); } }; @@ -157,9 +210,13 @@ public void ShaderArtifactChangesCannotSplitTheCurrentExtractionFrame() using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), new TestDiagnosticSink(), targetArtifacts: provider); ResourceProbePipeline.action = resources => { - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out RenderMaterialPass? a)); + Assert.True( + resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out RenderMaterialPass? a) + ); provider.artifact = second; - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out RenderMaterialPass? b)); + Assert.True( + resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out RenderMaterialPass? b) + ); Assert.Equal(a!.graphicsPipeline, b!.graphicsPipeline); }; RunResourceFrame(runtime); @@ -176,7 +233,9 @@ public void CompletedRetirementFailureStillAttemptsEveryProgramExactlyOnce() ResourceProbePipeline.action = resources => { foreach (string role in new[] { "draw", "shadow" }) + { Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new(role), null, null, out _)); + } }; RunResourceFrame(runtime); device.failedProgramRetirements = 1; @@ -196,7 +255,9 @@ public void UnfinishedRetirementKeepsProgramOwnershipUntilOwnerDrainCompletes() ResourceProbePipeline.action = resources => { foreach (string role in new[] { "draw", "shadow" }) + { Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new(role), null, null, out _)); + } }; RunResourceFrame(runtime); device.pendingProgramRetirements = 1; @@ -214,7 +275,11 @@ public void UnfinishedRetirementKeepsProgramOwnershipUntilOwnerDrainCompletes() public void ShaderArtifactCodecRetainsTheExactDetachedRuntimeContract() { RenderShaderArtifact artifact = Publication("main"); - RenderShaderArtifact decoded = RenderShaderArtifactCodec.Decode(RenderShaderArtifactCodec.Encode(artifact), artifact.shaderName, artifact.variant); + RenderShaderArtifact decoded = RenderShaderArtifactCodec.Decode( + RenderShaderArtifactCodec.Encode(artifact), + artifact.shaderName, + artifact.variant + ); Assert.Equal(artifact.contentHash, decoded.contentHash); Assert.Equal(artifact.definitionData.ToArray(), decoded.definitionData.ToArray()); var provider = new PublicationProvider(m_serialization); @@ -233,32 +298,64 @@ private ShaderAsset PublicationShader(params string[] passes) } private static ShaderDefinition PublicationDefinition(params string[] passes) - => new("Publication", [], [], passes.Select(name => new ShaderPassDefinition(name, ShaderProgramKind.Raster)), - [new(new("default"), new("test.publication"), passes.Select((name, index) => new ShaderTechniquePass(new(index == 0 ? "draw" : name), name)))]); + => new( + "Publication", + [], + [], + passes.Select(name => new ShaderPassDefinition(name, ShaderProgramKind.Raster)), + [new( + new("default"), + new("test.publication"), + passes.Select(( + name, + index + ) => new ShaderTechniquePass(new(index == 0 ? "draw" : name), name)) + )] + ); private RenderShaderArtifact Publication(params string[] passes) => Publication(passes, 1); - private RenderShaderArtifact Publication(string[] passes, byte marker) - => new("Publication", "test.noop", RenderShaderVariant.empty, new([]), - passes.Select(name => new RenderShaderPassArtifact(name, ShaderProgramKind.Raster, new(), new([]), - [new(ShaderStage.Vertex, [marker]), new(ShaderStage.Fragment, [marker])])).ToArray(), - m_serialization.Serialize(PublicationDefinition(passes), SerializationContext.empty)); + private RenderShaderArtifact Publication( + string[] passes, + byte marker + ) => new( + "Publication", + "test.noop", + RenderShaderVariant.empty, + new([]), + passes.Select(name => new RenderShaderPassArtifact( + name, + ShaderProgramKind.Raster, + new(), + new([]), + [new(ShaderStage.Vertex, [marker]), new(ShaderStage.Fragment, [marker])] + )).ToArray(), + m_serialization.Serialize(PublicationDefinition(passes), SerializationContext.empty) + ); private sealed class PublicationProvider(SerializationRegistry serialization) : IRenderTargetArtifactProvider { internal RenderShaderArtifact? artifact; internal int requests; + public ShaderDefinition ReadShaderDefinition(RenderShaderArtifact value) => serialization.Deserialize(value.definitionData.Span, SerializationContext.empty); - public RenderTargetArtifactStatus GetShaderArtifact(ShaderAsset shader, RenderShaderVariant variant, - GraphicsCapabilities capabilities, out RenderShaderArtifact? value) - { + + public RenderTargetArtifactStatus GetShaderArtifact( + ShaderAsset shader, + RenderShaderVariant variant, + GraphicsCapabilities capabilities, + out RenderShaderArtifact? value + ) { requests++; value = artifact; return value is null ? RenderTargetArtifactStatus.Pending : RenderTargetArtifactStatus.Ready; } - public RenderTargetArtifactStatus GetTextureArtifact(RenderTextureArtifactReference texture, out ReadOnlyMemory value) - { + + public RenderTargetArtifactStatus GetTextureArtifact( + RenderTextureArtifactReference texture, + out ReadOnlyMemory value + ) { value = default; return RenderTargetArtifactStatus.Unavailable; } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryLifetimeCollection.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryLifetimeCollection.cs index 81aa2ee98..bde39212b 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryLifetimeCollection.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryLifetimeCollection.cs @@ -5,4 +5,4 @@ namespace Inno.Rendering.Shaders.Tests; // These fixtures deliberately change process-visible extension declarations. Other tests discover // the same declarations, so fault injection must not overlap another registry's construction. [CollectionDefinition("Shader registry fault injection", DisableParallelization = true)] -public sealed class RegistryLifetimeCollection { } +public sealed class RegistryLifetimeCollection; diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs index 9e96a10ad..d2b650d4d 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs @@ -1,9 +1,9 @@ -using Inno.Integration.WindowsX64.Bgfx; using System; +using Xunit; using Inno.Adapter.Rendering; using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Integration.WindowsX64.Bgfx; using Inno.Rendering.Assets; -using Xunit; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; @@ -32,7 +32,9 @@ public void DuplicateUnassignedAndUnpairedRegistrationsFail() Assert.Throws(() => new RenderingBackendCatalog([new RuntimeProvider(default)])); var runtime = new RenderingBackendCatalog([new RuntimeProvider(id)]); Assert.Throws(() => new RenderingAuthoringBackendCatalog(runtime, [])); - Assert.Throws(() => new RenderingAuthoringBackendCatalog(runtime, [new AuthoringProvider(RenderingBackendId.bgfx)])); + Assert.Throws( + () => new RenderingAuthoringBackendCatalog(runtime, [new AuthoringProvider(RenderingBackendId.bgfx)]) + ); Assert.Throws(() => new RenderingBackendId("invalid id")); Assert.False(default(RenderingBackendId).isValid); } @@ -40,15 +42,22 @@ public void DuplicateUnassignedAndUnpairedRegistrationsFail() private sealed class RuntimeProvider(RenderingBackendId id) : RenderingBackendProvider(id) { public bool wasCreated { get; private set; } + public override IRenderDevice CreateDevice(RenderingBackendOptions options) - { wasCreated = true; throw new InvalidOperationException("These registration tests must not create a GPU device."); } + { + wasCreated = true; + throw new InvalidOperationException("These registration tests must not create a GPU device."); + } + public override IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider() => throw new InvalidOperationException("These registration tests do not create composition programs."); } private sealed class AuthoringProvider(RenderingBackendId id) : RenderingAuthoringBackendProvider(id) { - public override IShaderCompilerToolchain CreateShaderCompilerToolchain() => new BgfxShadercToolchain(Inno.Integration.WindowsX64.Bgfx.WindowsX64BgfxShaderProfiles.target); + public override IShaderCompilerToolchain CreateShaderCompilerToolchain() + => new BgfxShadercToolchain(Inno.Integration.WindowsX64.Bgfx.WindowsX64BgfxShaderProfiles.target); + public override ITextureTargetCompiler CreateTextureTargetCompiler() => new BgfxTextureTargetCompiler(); } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs index 3093b03e9..ff0372d84 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs @@ -1,13 +1,13 @@ -using Inno.Integration.MacOSArm64.Bgfx; using System; -using System.Runtime.Versioning; using System.Collections.Generic; using System.Linq; +using System.Runtime.Versioning; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering; using Inno.Rendering.Assets; -using Xunit; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; @@ -21,9 +21,18 @@ public void BranchCapturesOuterValuesButOnlyExposesMergedValues() ShaderIrValue input = builder.Constant(2f); ShaderIrValue? leaked = null; ShaderIrBuilder? retained = null; - IReadOnlyDictionary outputs = builder.Branch(builder.Constant(true), - region => { retained = region; leaked = region.Binary(ShaderIrOperation.Add, input, input); return Values(("result", leaked)); }, - region => Values(("result", region.Constant(3f)))); + IReadOnlyDictionary outputs = builder.Branch( + builder.Constant(true), + region => + { + retained = region; leaked = region.Binary( + ShaderIrOperation.Add, + input, + input + ); return Values(("result", leaked)); + }, + region => Values(("result", region.Constant(3f))) + ); ShaderIrBlock block = builder.Build(outputs); ShaderIrInstruction branch = block.instructions[^1]; Assert.Equal(ShaderIrOperation.Branch, branch.operation); @@ -41,13 +50,22 @@ public void FailedRegionConstructionRollsBackWithoutLeavingInstructionsOrIdentit var builder = new ShaderIrBuilder(); ShaderIrValue condition = builder.Constant(true); ShaderIrValue input = builder.Constant(2f); - Assert.Throws(() => builder.Branch(condition, - region => Values(("first", region.Constant(1f))), region => Values(("renamed", region.Constant(1f))))); + Assert.Throws(() => builder.Branch( + condition, + region => Values(("first", region.Constant(1f))), + region => Values(("renamed", region.Constant(1f))) + )); Assert.Equal(2, builder.Build(Values()).instructions.Count); - Assert.Throws(() => builder.Branch(condition, - region => Values(("result", builder.Constant(1f))), region => Values(("result", input)))); - Assert.Throws(() => builder.Branch(condition, - region => Values(("result", region.Input("hidden-stage-input", input.type))), region => Values(("result", input)))); + Assert.Throws(() => builder.Branch( + condition, + region => Values(("result", builder.Constant(1f))), + region => Values(("result", input)) + )); + Assert.Throws(() => builder.Branch( + condition, + region => Values(("result", region.Input("hidden-stage-input", input.type))), + region => Values(("result", input)) + )); Assert.Equal(2, builder.Constant(4f).index); } @@ -56,9 +74,15 @@ public void SiblingScopesCannotShareUnmergedValues() { var builder = new ShaderIrBuilder(); ShaderIrValue? first = null; - Assert.Throws(() => builder.Branch(builder.Constant(true), - region => { first = region.Constant(1f); return Values(("value", first)); }, - region => Values(("value", first!)))); + Assert.Throws(() => builder.Branch( + builder.Constant(true), + region => + { + first = region.Constant(1f); + return Values(("value", first)); + }, + region => Values(("value", first!)) + )); } [Fact] @@ -67,20 +91,37 @@ public void LoopsHaveExplicitIndicesStateAndSimultaneousNamedOutputs() var builder = new ShaderIrBuilder(); ShaderIrValue first = builder.Constant(1f); ShaderIrValue second = builder.Constant(2f); - IReadOnlyDictionary outputs = builder.Loop(builder.Constant(3u), Values(("b", second), ("a", first)), - (region, index, state) => + IReadOnlyDictionary outputs = builder.Loop( + builder.Constant(3u), + Values(("b", second), ("a", first)), + ( + region, + index, + state + ) => { Assert.Equal("uint", index.type.id); Assert.Equal(["a", "b"], state.Keys); return Values(("a", state["b"]), ("b", state["a"])); - }); + } + ); ShaderIrInstruction loop = builder.Build(outputs).instructions[^1]; Assert.Equal(["iteration", "state.a", "state.b"], loop.regions[0].instructions.Select(static instruction => instruction.inputName)); Assert.Same(first, loop.inputs[1]); Assert.Same(second, loop.inputs[2]); Assert.Equal(["a", "b"], outputs.Keys); - Assert.Throws(() => builder.Loop(builder.Constant(1u), Values(("a", first)), (region, index, state) => Values(("a", index)))); - Assert.Throws(() => builder.Loop(builder.Constant(1), Values(), (region, index, state) => Values())); + Assert.Throws( + () => builder.Loop(builder.Constant(1u), Values(("a", first)), ( + region, + index, + state + ) => Values(("a", index))) + ); + Assert.Throws(() => builder.Loop(builder.Constant(1), Values(), ( + region, + index, + state + ) => Values())); } [Fact] @@ -88,8 +129,19 @@ public void NestedFragmentOnlyEffectsAreStillRejectedByComputeStageValidation() { var builder = new ShaderIrBuilder(); ShaderIrValue condition = builder.Constant(true); - _ = builder.Loop(builder.Constant(1u), Values(), (region, index, state) => region.Branch(condition, - yes => { yes.Discard(condition); return Values(); }, no => Values())); + _ = builder.Loop(builder.Constant(1u), Values(), ( + region, + index, + state + ) => region.Branch( + condition, + yes => + { + yes.Discard(condition); + return Values(); + }, + no => Values() + )); Assert.Throws(() => new ShaderIrStage(ShaderStage.Compute, builder.Build(Values()), [], [])); } @@ -98,15 +150,24 @@ public void NestedFragmentOnlyEffectsAreStillRejectedByComputeStageValidation() public async Task NestedBranchLoopAndStorageEffectsCompileThroughTheSameMetalChain() { var builder = new ShaderIrBuilder(); - ShaderSourceType bufferType = ShaderSourceType.Storage(ShaderStorageType.Buffer(ShaderSourceType.Atomic("uint"), RenderStorageAccess.ReadWrite)); + ShaderSourceType bufferType = ShaderSourceType.Storage( + ShaderStorageType.Buffer(ShaderSourceType.Atomic("uint"), RenderStorageAccess.ReadWrite) + ); ShaderIrValue buffer = builder.Input("output", bufferType); ShaderIrValue gid = builder.Input("gid", ShaderSourceType.Atomic("uint3")); ShaderIrValue count = builder.Binary(ShaderIrOperation.Add, builder.Extract(gid, 0), builder.Constant(3u)); - IReadOnlyDictionary result = builder.Loop(count, Values(("a", builder.Constant(1u)), ("b", builder.Constant(2u))), - (region, index, state) => + IReadOnlyDictionary result = builder.Loop( + count, + Values(("a", builder.Constant(1u)), ("b", builder.Constant(2u))), + ( + region, + index, + state + ) => { ShaderIrValue condition = region.Binary(ShaderIrOperation.LessThan, index, region.Constant(2u)); - return region.Branch(condition, + return region.Branch( + condition, yes => { _ = yes.AtomicAddStorage(buffer, index, state["a"]); @@ -116,12 +177,24 @@ public async Task NestedBranchLoopAndStorageEffectsCompileThroughTheSameMetalCha { ShaderIrValue loaded = no.LoadStorage(buffer, index); return Values(("a", loaded), ("b", no.Binary(ShaderIrOperation.Add, state["b"], loaded))); - }); - }); + } + ); + } + ); builder.StoreStorage(buffer, builder.Constant(0u), result["a"]); builder.StoreStorage(buffer, builder.Constant(1u), result["b"]); - await Compile(new(ShaderStage.Compute, builder.Build(Values()), - [new("output", bufferType, ShaderIrInputKind.Storage), new("gid", gid.type, ShaderIrInputKind.Builtin, "global-invocation-id")], [], 8)); + await Compile( + new( + ShaderStage.Compute, + builder.Build(Values()), + [ + new("output", bufferType, ShaderIrInputKind.Storage), + new("gid", gid.type, ShaderIrInputKind.Builtin, "global-invocation-id") + ], + [], + 8 + ) + ); } [MetalShaderFact] @@ -129,10 +202,22 @@ await Compile(new(ShaderStage.Compute, builder.Build(Values()), public async Task AggregateCarriedStateAndZeroIterationLoopsCompileWithoutFlatteningTheirTypes() { var builder = new ShaderIrBuilder(); - ShaderSourceType pair = ShaderSourceType.Structure("Pair", [new("a", ShaderSourceType.Atomic("float")), new("b", ShaderSourceType.Atomic("float"))]); + ShaderSourceType pair = ShaderSourceType.Structure( + "Pair", + [new("a", ShaderSourceType.Atomic("float")), new("b", ShaderSourceType.Atomic("float"))] + ); ShaderIrValue initial = builder.Construct(pair, builder.Constant(1f), builder.Constant(2f)); - IReadOnlyDictionary result = builder.Loop(builder.Constant(0u), Values(("pair", initial)), - (region, index, state) => Values(("pair", region.Construct(pair, region.Extract(state["pair"], 1), region.Extract(state["pair"], 0))))); + IReadOnlyDictionary result = builder.Loop( + builder.Constant(0u), + Values(("pair", initial)), + ( + region, + index, + state + ) => Values( + ("pair", region.Construct(pair, region.Extract(state["pair"], 1), region.Extract(state["pair"], 0))) + ) + ); ShaderIrValue a = builder.Extract(result["pair"], 0); ShaderIrValue b = builder.Extract(result["pair"], 1); ShaderIrValue color = builder.Construct(ShaderSourceType.Atomic("float4"), a, b, a, builder.Constant(1f)); @@ -145,9 +230,17 @@ private static Dictionary Values(params (string name, Sha private static async Task Compile(ShaderIrStage stage) { var toolchain = new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target); - var capabilities = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.Compute | GraphicsCapability.StorageBuffer, - new GraphicsLimits(256, 8, 8192, 16), Enum.GetValues(), Enum.GetValues(), - Enum.GetValues(), Enum.GetValues(), false, false); + var capabilities = new GraphicsCapabilities( + GraphicsApi.Metal, + GraphicsCapability.Compute | GraphicsCapability.StorageBuffer, + new GraphicsLimits(256, 8, 8192, 16), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + false, + false + ); ShaderStageToolResult result = await new ShaderCompiler(toolchain).CompileAsync(stage, toolchain.CreateTarget(capabilities)); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static value => value.message))); } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs index 0b1525f05..44122f73d 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs @@ -1,14 +1,14 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; using Inno.Rendering.Assets; namespace Inno.Rendering.Shaders.Tests; @@ -25,7 +25,8 @@ public ShaderGraphInputDefaultTests() { m_modules = new(new() { - catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphInputDefaultTests).Assembly) }); + catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphInputDefaultTests).Assembly) + }); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); } @@ -81,13 +82,18 @@ public void ConnectedInputsIgnoreButRetainObsoleteStoredDefaults() public void AggregateDefaultsPreserveExactIntegerBitsAndRejectResourcesOrMalformedValues() { ShaderSourceType type = ShaderSourceType.Structure("Settings", [ - new("index", ShaderSourceType.Atomic("uint")), new("values", ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float3"), 2))]); + new("index", ShaderSourceType.Atomic("uint")), + new("values", ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float3"), 2)) + ]); ShaderGraphLiteral value = ShaderGraphLiteral.Zero(type); Assert.Equal(7, value.scalarBits.Length); value.scalarBits[0] = uint.MaxValue; var builder = new ShaderIrBuilder(); ShaderIrValue output = value.Emit(builder, type); - Assert.Equal(uint.MaxValue, builder.Build(new Dictionary { ["value"] = output }).instructions[0].constantBits); + Assert.Equal( + uint.MaxValue, + builder.Build(new Dictionary { ["value"] = output }).instructions[0].constantBits + ); Assert.Throws(() => ShaderGraphLiteral.Zero(ShaderSourceType.Atomic("sampled-texture2d"))); var boolean = new ShaderGraphLiteral { type = new() { id = "bool" }, scalarBits = [2] }; Assert.Throws(() => boolean.Emit(new(), ShaderSourceType.Atomic("bool"))); @@ -102,7 +108,8 @@ public void OptionalGraphNodeInputExpandsToTheRerouteInputDefault() GraphDocument child = ShaderGraphDocument.Create( new ShaderDefinition("Optional Node", [], [], []), m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); ShaderGraphNodes.WriteSettings( child, new ShaderGraphNodeSettings @@ -111,7 +118,8 @@ public void OptionalGraphNodeInputExpandsToTheRerouteInputDefault() kind = ShaderGraphNodeKind.Function }, m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); var boundaryInput = new GraphNodeRecord(new("node-inputs"), ShaderGraphNodes.inputDefinitionId); var boundaryOutput = new GraphNodeRecord(new("node-outputs"), ShaderGraphNodes.outputDefinitionId); child.AddNode(boundaryInput); @@ -130,29 +138,32 @@ public void OptionalGraphNodeInputExpandsToTheRerouteInputDefault() { ports = [new() { id = "value", type = new() { id = "float3" } }] }); - child.AddEdge(new( - new("return"), - new(boundaryInput.id, new("offset")), - new(boundaryOutput.id, new("value")))); + child.AddEdge(new(new("return"), new(boundaryInput.id, new("offset")), new(boundaryOutput.id, new("value")))); GraphDocument parent = ShaderGraphDocument.Create( new ShaderDefinition("Parent", [], [], []), m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); var call = new GraphNodeRecord(new("call"), ShaderGraphNodes.callDefinitionId); parent.AddNode(call); Set(call, "sourceId", sourceId); Set(call, "sourcePath", "Optional.ishader"); - Set(call, ShaderGraphNodes.interfaceKey, ShaderGraphNodes.ReadInterface( - child, - m_serialization, - SerializationContext.empty)); + Set( + call, + ShaderGraphNodes.interfaceKey, + ShaderGraphNodes.ReadInterface(child, m_serialization, SerializationContext.empty) + ); GraphDocument expanded = ShaderGraphNodes.Expand( parent, - (id, _) => id == sourceId ? child : throw new InvalidOperationException(), + ( + id, + _ + ) => id == sourceId ? child : throw new InvalidOperationException(), m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); GraphNodeRecord value = Assert.Single(expanded.nodes); Assert.Equal("inno.shader.reroute", value.definitionId); Assert.False(value.TryGetValue(ShaderGraphDocument.inputDefaultPrefix + "input", out _)); @@ -175,9 +186,11 @@ public void OptionalInputsCompileFromTypedZeroWithoutPersistedOverrides() { ["value"] = new(reroute.id, new("value")) }, - "test.optional-zero"), + "test.optional-zero" + ), m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(value => value.message))); Assert.Empty(result.diagnostics); @@ -200,20 +213,36 @@ public void OptionalInputsRejectTypesThatCannotHaveAZeroValue() { ["value"] = new(reroute.id, new("value")) }, - "test.optional-resource"), + "test.optional-resource" + ), m_serialization, - SerializationContext.empty); + SerializationContext.empty + ); ShaderGraphDiagnostic diagnostic = Assert.Single(result.diagnostics); Assert.Equal("SHADER_GRAPH_OPTIONAL_TYPE", diagnostic.code); } - private ShaderGraphLoweringResult Lower(GraphDocument graph, ShaderNodeCompilerCatalog catalog) - => catalog.Lower(new(graph, new Dictionary { ["value"] = new(new("multiply"), new("value")) }, "test.defaults"), m_serialization, SerializationContext.empty); - - private void Set(GraphNodeRecord node, string key, T value) - => node.SetValue(key, ShaderGraphDocument.Encode(value, m_serialization, SerializationContext.empty)); + private ShaderGraphLoweringResult Lower( + GraphDocument graph, + ShaderNodeCompilerCatalog catalog + ) => catalog.Lower( + new(graph, new Dictionary { ["value"] = new(new("multiply"), new("value")) }, "test.defaults"), + m_serialization, + SerializationContext.empty + ); + + private void Set( + GraphNodeRecord node, + string key, + T value + ) => node.SetValue(key, ShaderGraphDocument.Encode(value, m_serialization, SerializationContext.empty)); public void Dispose() - { m_serialization.Dispose(); m_types.Dispose(); m_modules.Dispose(); if (Directory.Exists(m_root)) Directory.Delete(m_root, true); } + { + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + if (Directory.Exists(m_root)) Directory.Delete(m_root, true); + } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs index f51f27ca5..035d4892f 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading; +using Xunit; using Inno.Core.Graphs; using Inno.Core.Serialization; -using Xunit; namespace Inno.Rendering.Shaders.Tests; @@ -21,7 +21,8 @@ public void TypedEdgesRejectMismatchesAndCyclesBeforeInvokingAnyCompiler() Connect(graph, b, "value", a, "left"); Connect(graph, value, "value", a, "right"); Connect(graph, value, "value", b, "right"); - ShaderGraphLoweringRequest Request() => new(graph, new Dictionary { ["result"] = Endpoint(a, "value") }, "metal"); + ShaderGraphLoweringRequest Request() + => new(graph, new Dictionary { ["result"] = Endpoint(a, "value") }, "metal"); ShaderGraphLoweringResult cycle = Catalog().Lower(Request(), m_serialization, SerializationContext.empty); Assert.Contains(cycle.diagnostics, diagnostic => diagnostic.code == "SHADER_GRAPH_CYCLE"); Set(value, "type", "int"); @@ -41,9 +42,16 @@ public void IndependentUnusedSourceEffectsKeepStableDocumentOrder() [first.id] = Source("void Shade() {}", "first.ishadersource"), [second.id] = Source("void Shade() {}", "second.ishadersource") }; - ShaderGraphLoweringResult result = Catalog().Lower(new(graph, new Dictionary(), "metal", modules), m_serialization, SerializationContext.empty); + ShaderGraphLoweringResult result = Catalog().Lower( + new(graph, new Dictionary(), "metal", modules), + m_serialization, + SerializationContext.empty + ); Assert.True(result.succeeded, Errors(result)); - Assert.Equal(["first.ishadersource", "second.ishadersource"], result.block!.instructions.Select(static instruction => instruction.source!.sourcePath)); + Assert.Equal( + ["first.ishadersource", "second.ishadersource"], + result.block!.instructions.Select(static instruction => instruction.source!.sourcePath) + ); } [Fact] @@ -53,15 +61,27 @@ public void ExpandedMembersAndAggregateConnectionsCannotSilentlyOverrideEachOthe GraphNodeRecord input = Add(graph, "input", "inno.shader.stage-input"); GraphNodeRecord scalar = Add(graph, "scalar", "inno.shader.constant"); GraphNodeRecord source = Add(graph, "source", "inno.shader.source"); - ShaderSourceModuleAnalysis module = Source("struct Data { float x; float y; }; float Shade(Data value) { return value.x + value.y; }"); + ShaderSourceModuleAnalysis module = Source( + "struct Data { float x; float y; }; float Shade(Data value) { return value.x + value.y; }" + ); Connect(graph, input, "value", source, "input.value"); Connect(graph, scalar, "value", source, "input.value.x"); - var request = new ShaderGraphLoweringRequest(graph, new Dictionary { ["value"] = Endpoint(source, "return") }, "metal", + var request = new ShaderGraphLoweringRequest( + graph, + new Dictionary { ["value"] = Endpoint(source, "return") }, + "metal", new Dictionary { [source.id] = module }, - new Dictionary { [input.id] = new("data", module.function!.parameters[0].type, ShaderIrInputKind.Uniform) }); + new Dictionary + { + [input.id] = new("data", module.function!.parameters[0].type, ShaderIrInputKind.Uniform) + } + ); ShaderGraphLoweringResult result = Catalog().Lower(request, m_serialization, SerializationContext.empty); Assert.False(result.succeeded); - Assert.Contains(result.diagnostics, diagnostic => diagnostic.message.Contains("both its aggregate and a member", StringComparison.Ordinal)); + Assert.Contains( + result.diagnostics, + diagnostic => diagnostic.message.Contains("both its aggregate and a member", StringComparison.Ordinal) + ); } [Fact] @@ -69,7 +89,9 @@ public void DuplicateProvidersAndCanceledRequestsAreRejectedWithoutPartialResult { Assert.Throws(() => Catalog(new DoubleCompiler(), new DoubleCompiler())); var request = new ShaderGraphLoweringRequest(new(), new Dictionary(), "metal"); - Assert.ThrowsAny(() => Catalog().Lower(request, m_serialization, SerializationContext.empty, new CancellationToken(true))); + Assert.ThrowsAny( + () => Catalog().Lower(request, m_serialization, SerializationContext.empty, new CancellationToken(true)) + ); } [Fact] @@ -84,8 +106,14 @@ public void RegistryDiscoversExtensionsAndRollsBackDuplicateCandidatesWithoutLea m_modules.Rebuild(); Assert.Equal(1, NodeRegistryProbe.created - NodeRegistryProbe.disposed); NodeRegistryProbe.conflict = true; - try { Assert.ThrowsAny(m_modules.Rebuild); } - finally { NodeRegistryProbe.conflict = false; } + try + { + Assert.ThrowsAny(m_modules.Rebuild); + } + finally + { + NodeRegistryProbe.conflict = false; + } Assert.Contains("tests.registry.node", registry.definitionIds); Assert.Equal(1, NodeRegistryProbe.created - NodeRegistryProbe.disposed); } @@ -99,9 +127,18 @@ internal sealed class NodeRegistryProbe : IShaderNodeCompiler, IDisposable internal static int disposed; internal static bool conflict; private readonly string m_id; - public NodeRegistryProbe() { created++; m_id = conflict ? "inno.shader.constant" : "tests.registry.node"; } + + public NodeRegistryProbe() + { + created++; + m_id = conflict ? "inno.shader.constant" : "tests.registry.node"; + } + public string definitionId => m_id; + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => []; + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) => new Dictionary(); + public void Dispose() => disposed++; } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs index 62b69397b..c674d66a4 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs @@ -1,22 +1,22 @@ -using Inno.Integration.MacOSArm64.Bgfx; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.Runtime.Versioning; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Execution; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering; using Inno.Rendering.Assets; -using Xunit; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; @@ -31,7 +31,9 @@ public sealed partial class ShaderGraphLoweringTests : IDisposable public ShaderGraphLoweringTests() { - m_modules = new(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphLoweringTests).Assembly)}); + m_modules = new( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderGraphLoweringTests).Assembly)} + ); m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); } @@ -40,11 +42,20 @@ public ShaderGraphLoweringTests() [SupportedOSPlatform("macos")] public async Task RealGraphMixesAnIndependentNodeExtensionAndSourceFunctionInOneNativeCompilation() { - GraphDocument graph = Graph(out GraphNodeRecord constant, out GraphNodeRecord extension, out GraphNodeRecord source, out GraphNodeRecord color); + GraphDocument graph = Graph( + out GraphNodeRecord constant, + out GraphNodeRecord extension, + out GraphNodeRecord source, + out GraphNodeRecord color + ); Set(constant, "value", 0.25f); ShaderSourceModuleAnalysis module = Source("float Shade(float value) { return value * 0.75; }"); - var request = new ShaderGraphLoweringRequest(graph, new Dictionary { ["color"] = Endpoint(color, "value") }, "metal", - new Dictionary { [source.id] = module }); + var request = new ShaderGraphLoweringRequest( + graph, + new Dictionary { ["color"] = Endpoint(color, "value") }, + "metal", + new Dictionary { [source.id] = module } + ); Set(constant, "value", 99f); extension.position = new(900, 1200); ShaderGraphLoweringResult lowered = Catalog(new DoubleCompiler()).Lower(request, m_serialization, SerializationContext.empty); @@ -54,9 +65,17 @@ public async Task RealGraphMixesAnIndependentNodeExtensionAndSourceFunctionInOne Assert.Equal(BitConverter.SingleToUInt32Bits(0.25f), lowered.block.instructions[0].constantBits); var stage = new ShaderIrStage(ShaderStage.Fragment, lowered.block, [], [new("color", ShaderIrOutputKind.Color)]); var compiler = new ShaderCompiler(new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target)); - var caps = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.None, new(256, 8, 8192, 16), - Enum.GetValues(), Enum.GetValues(), Enum.GetValues(), - Enum.GetValues(), false, false); + var caps = new GraphicsCapabilities( + GraphicsApi.Metal, + GraphicsCapability.None, + new(256, 8, 8192, 16), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + false, + false + ); ShaderStageToolResult compiled = await compiler.CompileAsync(stage, compiler.CreateTarget(caps)); Assert.True(compiled.succeeded, string.Join("\n", compiled.diagnostics.Select(static diagnostic => diagnostic.message))); } @@ -64,12 +83,21 @@ public async Task RealGraphMixesAnIndependentNodeExtensionAndSourceFunctionInOne [Fact] public void LayoutOnlyEditsKeepTheSameTypedStageSemanticHash() { - GraphDocument graph = Graph(out GraphNodeRecord constant, out GraphNodeRecord extension, out GraphNodeRecord source, out GraphNodeRecord color); + GraphDocument graph = Graph( + out GraphNodeRecord constant, + out GraphNodeRecord extension, + out GraphNodeRecord source, + out GraphNodeRecord color + ); ShaderSourceModuleAnalysis module = Source("float Shade(float value) { return value; }"); string Hash() { - var request = new ShaderGraphLoweringRequest(graph, new Dictionary { ["color"] = Endpoint(color, "value") }, "metal", - new Dictionary { [source.id] = module }); + var request = new ShaderGraphLoweringRequest( + graph, + new Dictionary { ["color"] = Endpoint(color, "value") }, + "metal", + new Dictionary { [source.id] = module } + ); ShaderGraphLoweringResult result = Catalog(new DoubleCompiler()).Lower(request, m_serialization, SerializationContext.empty); Assert.True(result.succeeded, Errors(result)); return new ShaderIrStage(ShaderStage.Fragment, result.block!, [], [new("color", ShaderIrOutputKind.Color)]).contentHash; @@ -91,22 +119,45 @@ public void MissingCompilerAndRenamedSourcePortPreserveEveryOriginalConnection() { GraphDocument graph = Graph(out _, out _, out GraphNodeRecord source, out GraphNodeRecord color); int edgeCount = graph.edges.Count; - ShaderGraphLoweringRequest Request(ShaderSourceModuleAnalysis module) => new(graph, - new Dictionary { ["color"] = Endpoint(color, "value") }, "metal", - new Dictionary { [source.id] = module }); - ShaderGraphLoweringResult missing = Catalog().Lower(Request(Source("float Shade(float value) { return value; }")), m_serialization, SerializationContext.empty); + ShaderGraphLoweringRequest Request(ShaderSourceModuleAnalysis module) + => new( + graph, + new Dictionary { ["color"] = Endpoint(color, "value") }, + "metal", + new Dictionary { [source.id] = module } + ); + ShaderGraphLoweringResult missing = Catalog().Lower( + Request(Source("float Shade(float value) { return value; }")), + m_serialization, + SerializationContext.empty + ); Assert.False(missing.succeeded); Assert.Contains(missing.diagnostics, diagnostic => diagnostic.code == "SHADER_NODE_COMPILER_MISSING"); - ShaderGraphLoweringResult renamed = Catalog(new DoubleCompiler()).Lower(Request(Source("float Shade(float renamed) { return renamed; }")), m_serialization, SerializationContext.empty); + ShaderGraphLoweringResult renamed = Catalog(new DoubleCompiler()).Lower( + Request(Source("float Shade(float renamed) { return renamed; }")), + m_serialization, + SerializationContext.empty + ); Assert.False(renamed.succeeded); - Assert.Contains(renamed.diagnostics, diagnostic => diagnostic.code == "SHADER_GRAPH_PORT_MISSING" && diagnostic.portId == "input.value"); + Assert.Contains( + renamed.diagnostics, + diagnostic => diagnostic.code == "SHADER_GRAPH_PORT_MISSING" && diagnostic.portId == "input.value" + ); Assert.Equal(edgeCount, graph.edges.Count); - ShaderGraphLoweringResult restored = Catalog(new DoubleCompiler()).Lower(Request(Source("float Shade(float value) { return value; }")), m_serialization, SerializationContext.empty); + ShaderGraphLoweringResult restored = Catalog(new DoubleCompiler()).Lower( + Request(Source("float Shade(float value) { return value; }")), + m_serialization, + SerializationContext.empty + ); Assert.True(restored.succeeded, Errors(restored)); } - private GraphDocument Graph(out GraphNodeRecord constant, out GraphNodeRecord extension, out GraphNodeRecord source, out GraphNodeRecord color) - { + private GraphDocument Graph( + out GraphNodeRecord constant, + out GraphNodeRecord extension, + out GraphNodeRecord source, + out GraphNodeRecord color + ) { var graph = new GraphDocument(); constant = Add(graph, "constant", "inno.shader.constant"); extension = Add(graph, "extension", "tests.double"); @@ -114,33 +165,64 @@ private GraphDocument Graph(out GraphNodeRecord constant, out GraphNodeRecord ex color = Add(graph, "color", "inno.shader.construct"); Connect(graph, constant, "value", extension, "input"); Connect(graph, extension, "value", source, "input.value"); - for (int index = 0; index < 4; index++) Connect(graph, source, "return", color, "component." + index); + for (int index = 0; index < 4; index++) + { + Connect(graph, source, "return", color, "component." + index); + } return graph; } private static ShaderNodeCompilerCatalog Catalog(params IShaderNodeCompiler[] extra) - => new(new IShaderNodeCompiler[] { new ShaderConstantNodeCompiler(), new ShaderBinaryNodeCompiler(), new ShaderConstructNodeCompiler(), - new ShaderStageInputNodeCompiler(), new ShaderSelectNodeCompiler(), new ShaderSourceNodeCompiler() }.Concat(extra)); + => new( + new IShaderNodeCompiler[] + { + new ShaderConstantNodeCompiler(), + new ShaderBinaryNodeCompiler(), + new ShaderConstructNodeCompiler(), + new ShaderStageInputNodeCompiler(), + new ShaderSelectNodeCompiler(), + new ShaderSourceNodeCompiler() + }.Concat(extra) + ); - private void Set(GraphNodeRecord node, string property, T value) - => node.SetValue(property, new(m_serialization.Encode(writer => writer.Write("value", value), SerializationContext.empty))); + private void Set( + GraphNodeRecord node, + string property, + T value + ) => node.SetValue(property, new(m_serialization.Encode(writer => writer.Write("value", value), SerializationContext.empty))); - private static GraphNodeRecord Add(GraphDocument graph, string id, string definition) - { + private static GraphNodeRecord Add( + GraphDocument graph, + string id, + string definition + ) { var node = new GraphNodeRecord(new(id), definition); graph.AddNode(node); return node; } - private static GraphEndpoint Endpoint(GraphNodeRecord node, string port) => new(node.id, new(port)); - private static void Connect(GraphDocument graph, GraphNodeRecord source, string output, GraphNodeRecord target, string input) - => graph.AddEdge(new(new("edge." + graph.edges.Count), Endpoint(source, output), Endpoint(target, input))); + private static GraphEndpoint Endpoint( + GraphNodeRecord node, + string port + ) => new(node.id, new(port)); - private static ShaderSourceModuleAnalysis Source(string text, string path = "module.ishadersource") - => new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule( - [new("metal", "inno.shader-language.bgfx-sc", new(new(path, text), "Shade", new NoIncludes()))]); + private static void Connect( + GraphDocument graph, + GraphNodeRecord source, + string output, + GraphNodeRecord target, + string input + ) => graph.AddEdge(new(new("edge." + graph.edges.Count), Endpoint(source, output), Endpoint(target, input))); - private static string Errors(ShaderGraphLoweringResult result) => string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message)); + private static ShaderSourceModuleAnalysis Source( + string text, + string path = "module.ishadersource" + ) => new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule( + [new("metal", "inno.shader-language.bgfx-sc", new(new(path, text), "Shade", new NoIncludes()))] + ); + + private static string Errors(ShaderGraphLoweringResult result) + => string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message)); public void Dispose() { @@ -152,15 +234,26 @@ public void Dispose() private sealed class NoIncludes : IShaderSourceResolver { - public ShaderSourceFile ReadInclude(string includingFile, string include) => throw new FileNotFoundException(include); + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => throw new FileNotFoundException(include); } private sealed class DoubleCompiler : IShaderNodeCompiler { public string definitionId => "tests.double"; + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => [new("input", ShaderSourceType.Atomic("float"), GraphPortDirection.Input), new("value", ShaderSourceType.Atomic("float"), GraphPortDirection.Output)]; + => [ + new("input", ShaderSourceType.Atomic("float"), GraphPortDirection.Input), + new("value", ShaderSourceType.Atomic("float"), GraphPortDirection.Output) + ]; + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary { ["value"] = context.builder.Binary(ShaderIrOperation.Multiply, context.Input("input"), context.builder.Constant(2f)) }; + => new Dictionary + { + ["value"] = context.builder.Binary(ShaderIrOperation.Multiply, context.Input("input"), context.builder.Constant(2f)) + }; } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs index a5c0ff38b..51abe5b1a 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs @@ -1,16 +1,16 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; namespace Inno.Rendering.Shaders.Tests; @@ -40,7 +40,10 @@ public void NativeGraphRoundTripPreservesTheOnlyRasterCreationTemplate() Assert.Equal(bytes, GraphDocumentCodec.Encode(restored, m_serialization)); ShaderGraphProgramResult result = Lower(restored); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static value => value.message))); - Assert.Equal(new[] { ShaderStage.Vertex, ShaderStage.Fragment }, Assert.Single(result.passes).stages.Select(static value => value.stage)); + Assert.Equal( + new[] { ShaderStage.Vertex, ShaderStage.Fragment }, + Assert.Single(result.passes).stages.Select(static value => value.stage) + ); } [Fact] @@ -68,14 +71,19 @@ public void NewCompilerRetainsPropertyPassKeywordTechniqueAndStageValidation() definition.passes = [definition.passes[0], definition.passes[0]]; definition.keywords = [new("quality", ["low", "low"])]; definition.techniques = [new(new("surface"), new("arbitrary.render-model"), [new(new("forward"), "absent")])]; - string[] codes = ShaderDefinitionValidator.Validate(definition).Where(static value => value.severity == DiagnosticSeverity.Error) - .Select(static value => value.code).ToArray(); + string[] codes = ShaderDefinitionValidator.Validate(definition) + .Where(static value => value.severity == DiagnosticSeverity.Error) + .Select(static value => value.code) + .ToArray(); Assert.Contains("SHADER_DUPLICATE_PROPERTY", codes); Assert.Contains("SHADER_DUPLICATE_PASS", codes); Assert.Contains("SHADER_PROPERTY_STAGES_INVALID", codes); Assert.Contains("SHADER_DUPLICATE_KEYWORD_OPTION", codes); Assert.Contains("SHADER_UNKNOWN_TECHNIQUE_PASS", codes); - graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); + graph.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); Assert.False(Lower(graph).succeeded); } @@ -87,10 +95,20 @@ public void CapabilityValidationReportsUnsupportedPassWithoutMutatingTheDefiniti pass.requiredFeatures = GraphicsCapability.Compute; definition.passes = [pass]; RenderTextureFormat[] formats = Enum.GetValues(); - var capabilities = new GraphicsCapabilities(GraphicsApi.Noop, GraphicsCapability.None, new(64, 1, 4096, 0), - formats, formats, formats, formats, false, false); - Assert.Contains(ShaderDefinitionValidator.Validate(definition, capabilities), static value => - value.code == "SHADER_CAPABILITY_UNAVAILABLE" && value.severity == DiagnosticSeverity.Warning); + var capabilities = new GraphicsCapabilities( + GraphicsApi.Noop, + GraphicsCapability.None, + new(64, 1, 4096, 0), + formats, + formats, + formats, + formats, + false, + false + ); + Assert.Contains(ShaderDefinitionValidator.Validate(definition, capabilities), static value => ( + value.code == "SHADER_CAPABILITY_UNAVAILABLE" && value.severity == DiagnosticSeverity.Warning + )); Assert.Equal(GraphicsCapability.Compute, definition.passes[0].requiredFeatures); } @@ -101,7 +119,13 @@ public void RenamingAnExposedInputAtomicallyChangesItsParameterAndPreservesTheDe { GraphDocument graph = Template(); GraphNodeRecord color = graph.FindNode(new("color"))!; - ShaderGraphInputSettings input = ShaderGraphDocument.Read(color, "settings", new ShaderGraphInputSettings(), m_serialization, SerializationContext.empty); + ShaderGraphInputSettings input = ShaderGraphDocument.Read( + color, + "settings", + new ShaderGraphInputSettings(), + m_serialization, + SerializationContext.empty + ); input.id = "tint"; GraphDocument changed = ShaderGraphBindings.ChangeInput(graph, color.id, input, m_serialization, SerializationContext.empty); ShaderDefinition original = ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); @@ -116,7 +140,13 @@ public void RenamingAnExposedInputAtomicallyChangesItsParameterAndPreservesTheDe public void PartiallyTypedInputRemainsSerializableInsteadOfDiscardingItsNodeOrEdges() { GraphDocument graph = Template(); - ShaderGraphInputSettings input = ShaderGraphDocument.Read(graph.FindNode(new("color"))!, "settings", new ShaderGraphInputSettings(), m_serialization, SerializationContext.empty); + ShaderGraphInputSettings input = ShaderGraphDocument.Read( + graph.FindNode(new("color"))!, + "settings", + new ShaderGraphInputSettings(), + m_serialization, + SerializationContext.empty + ); input.id = ""; GraphDocument changed = ShaderGraphBindings.ChangeInput(graph, new("color"), input, m_serialization, SerializationContext.empty); Assert.Equal(graph.nodes.Count, changed.nodes.Count); @@ -124,8 +154,15 @@ public void PartiallyTypedInputRemainsSerializableInsteadOfDiscardingItsNodeOrEd Assert.False(Lower(changed).succeeded); Assert.NotEmpty(GraphDocumentCodec.Encode(changed, m_serialization)); } - private ShaderGraphProgramResult Lower(GraphDocument graph) => new ShaderGraphProgramCompiler(m_nodes).Lower(graph, "bgfx", - new Dictionary(), m_serialization, SerializationContext.empty); + + private ShaderGraphProgramResult Lower(GraphDocument graph) + => new ShaderGraphProgramCompiler(m_nodes).Lower( + graph, + "bgfx", + new Dictionary(), + m_serialization, + SerializationContext.empty + ); [Fact] public void RemovingLastParameterInputRemovesItsDeclarationWithoutMutatingTheOriginal() @@ -148,10 +185,14 @@ public void RemovingOneSharedBindingPreservesItsDefaultAndRemainingStageVisibili graph.AddNode(node); var settings = new ShaderGraphInputSettings { id = "color", kind = ShaderIrInputKind.Uniform, type = new() { id = "float4" } }; graph = ShaderGraphBindings.ChangeInput(graph, node.id, settings, m_serialization, SerializationContext.empty); - ShaderPropertyDefinition original = Assert.Single(ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty).properties); + ShaderPropertyDefinition original = Assert.Single( + ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty).properties + ); Assert.Equal(ShaderStage.Vertex | ShaderStage.Fragment, original.stages); GraphDocument edited = ShaderGraphBindings.RemoveNodes(graph, [node.id], m_serialization, SerializationContext.empty); - ShaderPropertyDefinition remaining = Assert.Single(ShaderGraphDocument.ReadDefinition(edited, m_serialization, SerializationContext.empty).properties); + ShaderPropertyDefinition remaining = Assert.Single( + ShaderGraphDocument.ReadDefinition(edited, m_serialization, SerializationContext.empty).properties + ); Assert.Equal(ShaderStage.Fragment, remaining.stages); Assert.Equal(original.defaultValue, remaining.defaultValue); Assert.True(Lower(edited).succeeded); diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphSharedProgramTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphSharedProgramTests.cs index 0df3dcbdd..3624edea9 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphSharedProgramTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphSharedProgramTests.cs @@ -1,9 +1,9 @@ using System; using System.Linq; +using Xunit; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Rendering; -using Xunit; using Inno.Rendering.Assets; namespace Inno.Rendering.Shaders.Tests; @@ -34,7 +34,9 @@ public void RemovingOnePassKeepsSharedNodesAndRemovingLastPassReleasesItsParamet Assert.True(Lower(changed).succeeded); Assert.Equal(5, ShaderGraphPrograms.Read(original, m_serialization, SerializationContext.empty).Length); foreach (string pass in new[] { "Premultiplied", "Additive", "Multiply", "Opaque" }) + { changed = ShaderGraphPrograms.RemovePass(changed, pass, m_serialization, SerializationContext.empty); + } Assert.Empty(changed.nodes); Assert.Empty(changed.edges); Assert.Empty(ShaderGraphDocument.ReadDefinition(changed, m_serialization, SerializationContext.empty).properties); @@ -58,19 +60,44 @@ public void PastePreservesSharedProgramsAndTechniqueRolesWithNewIdentities() { GraphDocument graph = SharedGraph(); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty); - definition.techniques = [new(new("surface"), new("tests.surface"), definition.passes.Select(pass => new ShaderTechniquePass(new(pass.name.ToLowerInvariant()), pass.name)))]; - graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); + definition.techniques = [new( + new("surface"), + new("tests.surface"), + definition.passes.Select(pass => new ShaderTechniquePass(new(pass.name.ToLowerInvariant()), pass.name)) + )]; + graph.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); byte[] original = GraphDocumentCodec.Encode(graph, m_serialization); - GraphDocument fragment = ShaderGraphClipboard.Copy(graph, [new("vertex"), new("fragment")], m_serialization, SerializationContext.empty); - ShaderGraphPasteResult pasted = ShaderGraphClipboard.Paste(graph, fragment, true, null, m_serialization, SerializationContext.empty); + GraphDocument fragment = ShaderGraphClipboard.Copy( + graph, + [new("vertex"), new("fragment")], + m_serialization, + SerializationContext.empty + ); + ShaderGraphPasteResult pasted = ShaderGraphClipboard.Paste( + graph, + fragment, + true, + null, + m_serialization, + SerializationContext.empty + ); Assert.Equal(original, GraphDocumentCodec.Encode(graph, m_serialization)); Assert.Equal(graph.nodes.Count * 2, pasted.document.nodes.Count); ShaderDefinition result = ShaderGraphDocument.ReadDefinition(pasted.document, m_serialization, SerializationContext.empty); Assert.Equal(2, result.techniques.Length); Assert.NotEqual(result.techniques[0].id, result.techniques[1].id); Assert.All(result.techniques[1].passes, pass => Assert.EndsWith(" 2", pass.passName)); - Assert.Equal(2, ShaderGraphPrograms.Read(pasted.document, m_serialization, SerializationContext.empty) - .Where(program => program.pass.EndsWith(" 2", StringComparison.Ordinal)).SelectMany(program => program.stages).Distinct().Count()); + Assert.Equal( + 2, + ShaderGraphPrograms.Read(pasted.document, m_serialization, SerializationContext.empty) + .Where(program => program.pass.EndsWith(" 2", StringComparison.Ordinal)) + .SelectMany(program => program.stages) + .Distinct() + .Count() + ); Assert.True(Lower(pasted.document).succeeded); } @@ -82,7 +109,14 @@ public void CopyAndPasteUnknownNodesPreserveTheirUnresolvedData() node.SetValue("payload", new([1, 3, 5])); graph.AddNode(node); GraphDocument fragment = ShaderGraphClipboard.Copy(graph, [node.id], m_serialization, SerializationContext.empty); - ShaderGraphPasteResult pasted = ShaderGraphClipboard.Paste(graph, fragment, true, null, m_serialization, SerializationContext.empty); + ShaderGraphPasteResult pasted = ShaderGraphClipboard.Paste( + graph, + fragment, + true, + null, + m_serialization, + SerializationContext.empty + ); Assert.Equal(2, pasted.document.nodes.Count); Assert.NotEqual(node.id, Assert.Single(pasted.insertedNodes)); Assert.Equal(GraphDocumentCodec.Encode(fragment, m_serialization), GraphDocumentCodec.Encode(graph, m_serialization)); @@ -98,9 +132,20 @@ private GraphDocument SharedGraph() pass.name = name; return pass; }).ToArray(); - graph.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty)); + graph.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition), m_serialization, SerializationContext.empty) + ); foreach (ShaderPassDefinition pass in definition.passes) - graph = ShaderGraphPrograms.Bind(graph, pass.name, [new("vertex"), new("fragment")], m_serialization, SerializationContext.empty); + { + graph = ShaderGraphPrograms.Bind( + graph, + pass.name, + [new("vertex"), new("fragment")], + m_serialization, + SerializationContext.empty + ); + } return graph; } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs index 9a00108c9..d6750f362 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs @@ -1,14 +1,14 @@ -using Inno.Integration.MacOSArm64.Bgfx; using System; -using System.Runtime.Versioning; using System.Linq; +using System.Runtime.Versioning; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Graphs; using Inno.Core.Serialization; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering; using Inno.Rendering.Assets; -using Xunit; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; @@ -21,8 +21,10 @@ public void StorageGraphKeepsExplicitEffectsEvenWithoutAValueOutput() ShaderGraphProgramResult lowered = Lower(StorageGraph()); Assert.True(lowered.succeeded, string.Join("\n", lowered.diagnostics.Select(value => value.message))); ShaderIrStage stage = Assert.Single(Assert.Single(lowered.passes).stages); - Assert.Equal(new[] { ShaderIrOperation.StorageStore, ShaderIrOperation.StorageLoad, ShaderIrOperation.StorageAtomicAdd }, - stage.body.instructions.Where(value => value.hasSideEffects).Select(value => value.operation)); + Assert.Equal( + new[] { ShaderIrOperation.StorageStore, ShaderIrOperation.StorageLoad, ShaderIrOperation.StorageAtomicAdd }, + stage.body.instructions.Where(value => value.hasSideEffects).Select(value => value.operation) + ); } [MetalShaderFact] @@ -33,8 +35,20 @@ public async Task StorageGraphCompilesThroughTheSameMetalToolchainAsSourceNodes( Assert.True(lowered.succeeded, string.Join("\n", lowered.diagnostics.Select(value => value.message))); var compiler = new ShaderCompiler(new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target)); RenderTextureFormat[] formats = Enum.GetValues(); - var caps = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.Compute | GraphicsCapability.StorageBuffer, new(256, 8, 8192, 16), - formats, formats, formats, formats, false, false, formats, formats, formats); + var caps = new GraphicsCapabilities( + GraphicsApi.Metal, + GraphicsCapability.Compute | GraphicsCapability.StorageBuffer, + new(256, 8, 8192, 16), + formats, + formats, + formats, + formats, + false, + false, + formats, + formats, + formats + ); ShaderStageToolResult result = await compiler.CompileAsync(lowered.passes[0].stages[0], compiler.CreateTarget(caps)); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(value => value.message))); } @@ -42,11 +56,20 @@ public async Task StorageGraphCompilesThroughTheSameMetalToolchainAsSourceNodes( [Fact] public void RerouteRetainsAggregateAndStoragePortContracts() { - ShaderSourceType aggregate = ShaderSourceType.Structure("Payload", [new("points", ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float2"), 3))]); - foreach (ShaderSourceType type in new[] { aggregate, ShaderSourceType.Storage(ShaderStorageType.Buffer(aggregate, RenderStorageAccess.ReadWrite)) }) + ShaderSourceType aggregate = ShaderSourceType.Structure( + "Payload", + [new("points", ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float2"), 3))] + ); + foreach (ShaderSourceType type in new[] { + aggregate, + ShaderSourceType.Storage(ShaderStorageType.Buffer(aggregate, RenderStorageAccess.ReadWrite)) + }) { var node = new GraphNodeRecord(new("route"), "inno.shader.reroute"); - node.SetValue("valueType", ShaderGraphDocument.Encode(ShaderGraphType.Capture(type), m_serialization, SerializationContext.empty)); + node.SetValue( + "valueType", + ShaderGraphDocument.Encode(ShaderGraphType.Capture(type), m_serialization, SerializationContext.empty) + ); var ports = m_nodes.DescribePorts(node, m_serialization, SerializationContext.empty); Assert.Equal(2, ports.Count); Assert.All(ports, port => Assert.True(type.IsEquivalentTo(port.type))); @@ -55,31 +78,66 @@ public void RerouteRetainsAggregateAndStoragePortContracts() private GraphDocument StorageGraph() { - GraphDocument graph = ShaderGraphDocument.Create(new("Compute", [], [], [new("Main", ShaderProgramKind.Compute)]), m_serialization, SerializationContext.empty); + GraphDocument graph = ShaderGraphDocument.Create( + new("Compute", [], [], [new("Main", ShaderProgramKind.Compute)]), + m_serialization, + SerializationContext.empty + ); GraphNodeRecord stage = Node("compute", ShaderGraphDocument.outputDefinitionId); Set(stage, "settings", new ShaderGraphStageSettings { stage = ShaderStage.Compute }); - var resourceType = new ShaderGraphType { isStorage = true, access = RenderStorageAccess.ReadWrite, storageElement = new() { id = "uint" } }; + var resourceType = new ShaderGraphType + { + isStorage = true, + access = RenderStorageAccess.ReadWrite, + storageElement = new() { id = "uint" } + }; GraphNodeRecord resource = Node("resource", "inno.shader.stage-input"); var settings = new ShaderGraphInputSettings { id = "buffer", kind = ShaderIrInputKind.Storage, type = resourceType }; Set(resource, "settings", settings); - GraphNodeRecord coordinate = Node("coordinate", "inno.shader.constant"); Set(coordinate, "type", "uint"); Set(coordinate, "value", 0u); + GraphNodeRecord coordinate = Node( + "coordinate", + "inno.shader.constant" + ); Set(coordinate, "type", "uint"); Set(coordinate, "value", 0u); GraphNodeRecord value = Node("constant", "inno.shader.constant"); Set(value, "type", "uint"); Set(value, "value", 7u); - GraphNodeRecord store = Node("z-store", "inno.shader.storage-store"), load = Node("m-load", "inno.shader.storage-load"), atomic = Node("a-atomic", "inno.shader.storage-atomic-add"); + GraphNodeRecord store = Node( + "z-store", + "inno.shader.storage-store" + ), load = Node("m-load", "inno.shader.storage-load"), atomic = Node( + "a-atomic", + "inno.shader.storage-atomic-add" + ); foreach (GraphNodeRecord effect in new[] { store, load, atomic }) - { Set(effect, "resource", resourceType); Connect(resource, "value", effect, "resource"); Connect(coordinate, "value", effect, "coordinate"); } + { + Set(effect, "resource", resourceType); Connect(resource, "value", effect, "resource"); Connect( + coordinate, + "value", + effect, + "coordinate" + ); + } Connect(value, "value", store, "value"); Connect(value, "value", atomic, "value"); Connect(store, "then", load, "after"); Connect(load, "then", atomic, "after"); graph = ShaderGraphPrograms.Bind(graph, "Main", [stage.id], m_serialization, SerializationContext.empty); return ShaderGraphBindings.ChangeInput(graph, resource.id, settings, m_serialization, SerializationContext.empty); - GraphNodeRecord Node(string id, string type) - { + GraphNodeRecord Node( + string id, + string type + ) { var node = new GraphNodeRecord(new(id), type); if (id != "compute") Set(node, "stage", "compute"); graph.AddNode(node); return node; } - void Set(GraphNodeRecord node, string key, T data) => node.SetValue(key, ShaderGraphDocument.Encode(data, m_serialization, SerializationContext.empty)); - void Connect(GraphNodeRecord output, string outputPort, GraphNodeRecord input, string inputPort) - => graph.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(output.id, new(outputPort)), new(input.id, new(inputPort)))); + void Set( + GraphNodeRecord node, + string key, + T data + ) => node.SetValue(key, ShaderGraphDocument.Encode(data, m_serialization, SerializationContext.empty)); + void Connect( + GraphNodeRecord output, + string outputPort, + GraphNodeRecord input, + string inputPort + ) => graph.AddEdge(new(new(Guid.NewGuid().ToString("N")), new(output.id, new(outputPort)), new(input.id, new(inputPort)))); } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs index 742a7f54a..280bdc4b4 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using Inno.Build.Toolchains.Bgfx.Tools; using Xunit; +using Inno.Build.Toolchains.Bgfx.Tools; namespace Inno.Rendering.Shaders.Tests; @@ -17,8 +17,13 @@ public void NumericGraphLowersToTypedOrderedValuesInsteadOfSourceFragments() ShaderIrValue scaled = builder.Binary(ShaderIrOperation.Multiply, input, builder.Constant(2f)); ShaderIrValue clamped = builder.Binary(ShaderIrOperation.Minimum, scaled, builder.Constant(1f)); ShaderIrBlock block = builder.Build(new Dictionary { ["color"] = clamped }); - Assert.Equal([ShaderIrOperation.Input, ShaderIrOperation.Constant, ShaderIrOperation.Multiply, - ShaderIrOperation.Constant, ShaderIrOperation.Minimum], block.instructions.Select(static value => value.operation)); + Assert.Equal([ + ShaderIrOperation.Input, + ShaderIrOperation.Constant, + ShaderIrOperation.Multiply, + ShaderIrOperation.Constant, + ShaderIrOperation.Minimum + ], block.instructions.Select(static value => value.operation)); Assert.Equal("float", block.outputs["color"].type.id); Assert.Equal(0x40000000UL, block.instructions[1].constantBits); Assert.Same(input, builder.Input("brightness", ShaderSourceType.Atomic("float"))); @@ -76,8 +81,10 @@ public void AggregateConstructionAndExtractionKeepFullMemberTypes() public void MatrixConstructionSpecifiesColumnMajorOrderAndExtractionReturnsAColumn() { var builder = new ShaderIrBuilder(); - ShaderIrValue matrix = builder.Construct(ShaderSourceType.Atomic("float2x3"), - Enumerable.Range(1, 6).Select(value => builder.Constant((float)value)).ToArray()); + ShaderIrValue matrix = builder.Construct( + ShaderSourceType.Atomic("float2x3"), + Enumerable.Range(1, 6).Select(value => builder.Constant((float)value)).ToArray() + ); Assert.Equal("float3", builder.Extract(matrix, 1).type.id); Assert.Throws(() => builder.Extract(matrix, 2)); } @@ -101,14 +108,19 @@ public void ComparisonAndSelectionCannotHideTypeOrControlFlowChanges() [Fact] public void MixedArithmeticAndSourceCallDeriveOutAndInOutByName() { - ShaderSourceModuleAnalysis module = Module("float Shade(float gain, out float alpha, inout vec2 uv) { alpha = gain; uv *= gain; return alpha; }"); + ShaderSourceModuleAnalysis module = Module( + "float Shade(float gain, out float alpha, inout vec2 uv) { alpha = gain; uv *= gain; return alpha; }" + ); Assert.True(module.succeeded); var builder = new ShaderIrBuilder(); ShaderIrValue gain = builder.Binary(ShaderIrOperation.Multiply, builder.Constant(0.5f), builder.Constant(2f)); ShaderIrValue uv = builder.Construct(ShaderSourceType.Atomic("float2"), builder.Constant(0f), builder.Constant(1f)); // Dictionary insertion order must not become native function argument order. IReadOnlyDictionary outputs = builder.Call(module, "test", new Dictionary - { ["uv"] = uv, ["gain"] = gain }); + { + ["uv"] = uv, + ["gain"] = gain + }); Assert.Equal(["return", "output.alpha", "output.uv"], outputs.Keys); ShaderIrBlock block = builder.Build(outputs); ShaderIrInstruction call = block.instructions[^1]; @@ -125,7 +137,11 @@ public void CallsWithUnusedOutputsAndVoidCallsRemainInEvaluationOrder() ShaderSourceModuleAnalysis module = Module("void Shade(inout float value) { value *= value; }"); var builder = new ShaderIrBuilder(); ShaderIrValue input = builder.Constant(2f); - IReadOnlyDictionary first = builder.Call(module, "test", new Dictionary { ["value"] = input }); + IReadOnlyDictionary first = builder.Call( + module, + "test", + new Dictionary { ["value"] = input } + ); _ = builder.Call(module, "test", new Dictionary { ["value"] = first["output.value"] }); ShaderSourceModuleAnalysis voidModule = Module("void Shade() { }"); Assert.Empty(builder.Call(voidModule, "test", new Dictionary())); @@ -142,9 +158,16 @@ public void InvalidOrMismatchedSourceModulesNeverEnterAnIntermediateBlock() ShaderSourceModuleAnalysis invalid = Module("float Other(float gain) { return gain; }"); Assert.Throws(() => builder.Call(invalid, "test", new Dictionary())); Assert.Throws(() => builder.Call(module, "not-registered", new Dictionary())); - Assert.Throws(() => builder.Call(module, "test", new Dictionary { ["renamed"] = builder.Constant(1f) })); - Assert.Throws(() => builder.Call(module, "test", new Dictionary { ["gain"] = builder.Constant(1) })); - Assert.DoesNotContain(builder.Build(new Dictionary()).instructions, value => value.operation == ShaderIrOperation.SourceCall); + Assert.Throws( + () => builder.Call(module, "test", new Dictionary { ["renamed"] = builder.Constant(1f) }) + ); + Assert.Throws( + () => builder.Call(module, "test", new Dictionary { ["gain"] = builder.Constant(1) }) + ); + Assert.DoesNotContain( + builder.Build(new Dictionary()).instructions, + value => value.operation == ShaderIrOperation.SourceCall + ); } [Fact] @@ -166,6 +189,9 @@ private static ShaderSourceModuleAnalysis Module(string text) private sealed class NoIncludes : IShaderSourceResolver { - public ShaderSourceFile ReadInclude(string includingFile, string include) => throw new FileNotFoundException(include); + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => throw new FileNotFoundException(include); } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs index d42b86de8..92fccdffd 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Shaders.Tests; @@ -10,8 +10,12 @@ public sealed class ShaderIrStageTests [Fact] public void SemanticHashCoversNestedCodeStorageAccessBindingsAndWorkgroups() { - string Hash(float value, int slot, int threads, RenderStorageAccess access) - { + string Hash( + float value, + int slot, + int threads, + RenderStorageAccess access + ) { var builder = new ShaderIrBuilder(); ShaderSourceType resourceType = ShaderSourceType.Storage(ShaderStorageType.Buffer(ShaderSourceType.Atomic("float"), access)); ShaderIrValue resource = builder.Input("resource", resourceType); @@ -21,8 +25,13 @@ string Hash(float value, int slot, int threads, RenderStorageAccess access) region.StoreStorage(resource, region.Constant(0u), region.Constant(value)); return new Dictionary(); }, region => new Dictionary()); - return new ShaderIrStage(ShaderStage.Compute, builder.Build(new Dictionary()), - [new("resource", resourceType, ShaderIrInputKind.Storage, location: slot)], [], threads).contentHash; + return new ShaderIrStage( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [new("resource", resourceType, ShaderIrInputKind.Storage, location: slot)], + [], + threads + ).contentHash; } string first = Hash(1f, 0, 8, RenderStorageAccess.ReadWrite); Assert.Equal(first, Hash(1f, 0, 8, RenderStorageAccess.ReadWrite)); @@ -44,8 +53,12 @@ public void VertexStageRequiresClipPositionAndExactBodyInterface() Assert.Same(body, stage.body); Assert.Throws(() => new ShaderIrStage(ShaderStage.Vertex, body, [], [output])); Assert.Throws(() => new ShaderIrStage(ShaderStage.Vertex, body, [input], [])); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Vertex, body, [input], [new("clip", ShaderIrOutputKind.Varying, "texcoord")])); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Fragment, body, [input], [new("clip", ShaderIrOutputKind.Color)])); + Assert.Throws( + () => new ShaderIrStage(ShaderStage.Vertex, body, [input], [new("clip", ShaderIrOutputKind.Varying, "texcoord")]) + ); + Assert.Throws( + () => new ShaderIrStage(ShaderStage.Fragment, body, [input], [new("clip", ShaderIrOutputKind.Color)]) + ); Assert.Throws(() => new ShaderIrStage(ShaderStage.Vertex, body, [input], [output], threadsX: 2)); } @@ -56,9 +69,15 @@ public void AliasedResourceSlotsAndUnmappedOutputsAreRejected() _ = builder.Input("first", ShaderSourceType.Atomic("sampled-texture2d")); _ = builder.Input("second", ShaderSourceType.Atomic("sampled-texture2d")); ShaderIrBlock body = builder.Build(new Dictionary()); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Fragment, body, - [new("first", ShaderSourceType.Atomic("sampled-texture2d"), ShaderIrInputKind.SampledTexture, "ignored-1", 2), - new("second", ShaderSourceType.Atomic("sampled-texture2d"), ShaderIrInputKind.SampledTexture, "ignored-2", 2)], [])); + Assert.Throws(() => new ShaderIrStage( + ShaderStage.Fragment, + body, + [ + new("first", ShaderSourceType.Atomic("sampled-texture2d"), ShaderIrInputKind.SampledTexture, "ignored-1", 2), + new("second", ShaderSourceType.Atomic("sampled-texture2d"), ShaderIrInputKind.SampledTexture, "ignored-2", 2) + ], + [] + )); } [Fact] diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs index 7aa37e0f1..5cd061f86 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs @@ -1,13 +1,13 @@ -using Inno.Integration.MacOSArm64.Bgfx; using System; -using System.Runtime.Versioning; using System.Collections.Generic; using System.Linq; +using System.Runtime.Versioning; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering; using Inno.Rendering.Assets; -using Xunit; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; @@ -20,16 +20,26 @@ public void AggregateNamesCannotImpersonateGpuScalarVectorOrResourceTypes() var builder = new ShaderIrBuilder(); ShaderSourceType impostor = ShaderSourceType.Structure("uint", [new("field", ShaderSourceType.Atomic("uint"))]); ShaderIrValue value = builder.Construct(impostor, builder.Constant(0u)); - ShaderIrValue storage = builder.Input("storage", ShaderSourceType.Storage(ShaderStorageType.Buffer(impostor, RenderStorageAccess.ReadWrite))); + ShaderIrValue storage = builder.Input( + "storage", + ShaderSourceType.Storage(ShaderStorageType.Buffer(impostor, RenderStorageAccess.ReadWrite)) + ); Assert.Throws(() => builder.AtomicAddStorage(storage, builder.Constant(0u), value)); ShaderSourceType textureType = ShaderSourceType.Structure("sampled-texture2d", [new("field", ShaderSourceType.Atomic("float"))]); ShaderIrValue texture = builder.Input("texture", textureType); ShaderIrValue uv = builder.Construct(ShaderSourceType.Atomic("float2"), builder.Constant(0f), builder.Constant(0f)); Assert.Throws(() => builder.Sample(texture, uv)); var color = new ShaderIrBuilder(); - ShaderIrValue fakeColor = color.Construct(ShaderSourceType.Structure("float4", [new("field", ShaderSourceType.Atomic("float"))]), color.Constant(1f)); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Fragment, - color.Build(new Dictionary { ["color"] = fakeColor }), [], [new("color", ShaderIrOutputKind.Color)])); + ShaderIrValue fakeColor = color.Construct( + ShaderSourceType.Structure("float4", [new("field", ShaderSourceType.Atomic("float"))]), + color.Constant(1f) + ); + Assert.Throws(() => new ShaderIrStage( + ShaderStage.Fragment, + color.Build(new Dictionary { ["color"] = fakeColor }), + [], + [new("color", ShaderIrOutputKind.Color)] + )); } [Fact] @@ -40,10 +50,16 @@ public void StorageTypesKeepAccessShapeFormatAndCompleteElementLayout() Assert.False(read.IsEquivalentTo(Buffer("uint", RenderStorageAccess.ReadWrite))); Assert.False(read.IsEquivalentTo(Buffer("int", RenderStorageAccess.Read))); Assert.False(read.IsEquivalentTo(ShaderSourceType.Atomic("storage"))); - Assert.False(Image().IsEquivalentTo(ShaderSourceType.Storage(ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.ReadWrite, array: true)))); + Assert.False( + Image().IsEquivalentTo( + ShaderSourceType.Storage(ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.ReadWrite, array: true)) + ) + ); Assert.Throws(() => ShaderStorageType.Buffer(read, RenderStorageAccess.Read)); Assert.Throws(() => ShaderStorageType.Image(RenderTextureFormat.RGBA8Srgb, RenderStorageAccess.Read)); - Assert.Throws(() => ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.Read, RenderTextureDimension.Cube)); + Assert.Throws( + () => ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.Read, RenderTextureDimension.Cube) + ); } [Fact] @@ -57,8 +73,15 @@ public void StorageReadsWritesAndAtomicsKeepTheirExactEvaluationOrder() ShaderIrValue second = builder.LoadStorage(resource, index); ShaderIrValue previous = builder.AtomicAddStorage(resource, index, builder.Constant(1u)); ShaderIrBlock block = builder.Build(new Dictionary()); - Assert.Equal([ShaderIrOperation.StorageLoad, ShaderIrOperation.StorageStore, ShaderIrOperation.StorageLoad, ShaderIrOperation.StorageAtomicAdd], - block.instructions.Where(static value => value.hasSideEffects).Select(static value => value.operation)); + Assert.Equal( + [ + ShaderIrOperation.StorageLoad, + ShaderIrOperation.StorageStore, + ShaderIrOperation.StorageLoad, + ShaderIrOperation.StorageAtomicAdd + ], + block.instructions.Where(static value => value.hasSideEffects).Select(static value => value.operation) + ); Assert.NotEqual(first.index, second.index); Assert.Equal("uint", previous.type.id); Assert.Single(block.instructions.Where(static value => value.operation == ShaderIrOperation.StorageStore)); @@ -79,8 +102,16 @@ public void ResourceAccessAndCoordinateErrorsFailBeforeNativeCodeGeneration() Assert.Throws(() => builder.Select(builder.Constant(true), read, read)); ShaderIrValue image = builder.Input("image", Image()); Assert.Throws(() => builder.LoadStorage(image, index)); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Compute, builder.Build(new Dictionary()), - [new("read", read.type, ShaderIrInputKind.Uniform), new("write", write.type, ShaderIrInputKind.Storage), new("image", image.type, ShaderIrInputKind.Storage, location: 1)], [])); + Assert.Throws(() => new ShaderIrStage( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [ + new("read", read.type, ShaderIrInputKind.Uniform), + new("write", write.type, ShaderIrInputKind.Storage), + new("image", image.type, ShaderIrInputKind.Storage, location: 1) + ], + [] + )); } [Fact] @@ -90,13 +121,19 @@ public void ImplicitDerivativesAndDiscardCannotLeakIntoVertexOrComputeStages() ShaderIrValue texture = builder.Input("texture", ShaderSourceType.Atomic("sampled-texture2d")); ShaderIrValue uv = builder.Construct(ShaderSourceType.Atomic("float2"), builder.Constant(0f), builder.Constant(0f)); _ = builder.Sample(texture, uv); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Compute, builder.Build(new Dictionary()), - [new("texture", texture.type, ShaderIrInputKind.SampledTexture)], [])); + Assert.Throws(() => new ShaderIrStage( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [new("texture", texture.type, ShaderIrInputKind.SampledTexture)], + [] + )); Assert.Throws(() => builder.Sample(texture, builder.Constant(0f))); Assert.Throws(() => builder.SampleLevel(texture, uv, builder.Constant(0))); var discard = new ShaderIrBuilder(); discard.Discard(discard.Constant(false)); - Assert.Throws(() => new ShaderIrStage(ShaderStage.Compute, discard.Build(new Dictionary()), [], [])); + Assert.Throws( + () => new ShaderIrStage(ShaderStage.Compute, discard.Build(new Dictionary()), [], []) + ); } [MetalShaderFact] @@ -110,8 +147,13 @@ public async Task TypedStorageBuffersCompileRealLoadsStoresAndAtomics() ShaderIrValue value = builder.LoadStorage(source, index); ShaderIrValue previous = builder.AtomicAddStorage(target, index, value); builder.StoreStorage(target, builder.Constant(1u), previous); - ShaderIrStage stage = new(ShaderStage.Compute, builder.Build(new Dictionary()), - [new("source", source.type, ShaderIrInputKind.Storage), new("target", target.type, ShaderIrInputKind.Storage, location: 1)], [], 8); + ShaderIrStage stage = new( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [new("source", source.type, ShaderIrInputKind.Storage), new("target", target.type, ShaderIrInputKind.Storage, location: 1)], + [], + 8 + ); ShaderStageToolResult result = await Compile(stage); Success(result); Assert.Equal(2, result.bindings.Count); @@ -123,18 +165,29 @@ public async Task TypedStorageBuffersCompileRealLoadsStoresAndAtomics() public async Task TypedStorageImagesCompileForTwoDimensionalArraysAndVolumes() { foreach ((RenderTextureDimension dimension, bool array) in new[] - { (RenderTextureDimension.Texture2D, false), (RenderTextureDimension.Texture2D, true), (RenderTextureDimension.Texture3D, false) }) - { + { + (RenderTextureDimension.Texture2D, false), + (RenderTextureDimension.Texture2D, true), + (RenderTextureDimension.Texture3D, false) + } + ) { var builder = new ShaderIrBuilder(); - ShaderSourceType type = ShaderSourceType.Storage(ShaderStorageType.Image(RenderTextureFormat.RGBA16Float, RenderStorageAccess.ReadWrite, dimension, array)); + ShaderSourceType type = ShaderSourceType.Storage( + ShaderStorageType.Image(RenderTextureFormat.RGBA16Float, RenderStorageAccess.ReadWrite, dimension, array) + ); ShaderIrValue image = builder.Input("image", type); ShaderIrValue zero = builder.Constant(0); ShaderIrValue coordinate = array || dimension == RenderTextureDimension.Texture3D - ? builder.Construct(ShaderSourceType.Atomic("int3"), zero, zero, zero) - : builder.Construct(ShaderSourceType.Atomic("int2"), zero, zero); + ? builder.Construct(ShaderSourceType.Atomic("int3"), zero, zero, zero) + : builder.Construct(ShaderSourceType.Atomic("int2"), zero, zero); ShaderIrValue loaded = builder.LoadStorage(image, coordinate); builder.StoreStorage(image, coordinate, builder.Binary(ShaderIrOperation.Add, loaded, loaded)); - ShaderIrStage stage = new(ShaderStage.Compute, builder.Build(new Dictionary()), [new("image", type, ShaderIrInputKind.Storage)], []); + ShaderIrStage stage = new( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [new("image", type, ShaderIrInputKind.Storage)], + [] + ); Success(await Compile(stage)); Assert.False((await Compile(stage, GraphicsCapability.Compute | GraphicsCapability.StorageBuffer)).succeeded); } @@ -149,29 +202,57 @@ public async Task SamplingAndFragmentDiscardCompileWithoutAHandwrittenModule() var builder = new ShaderIrBuilder(); ShaderIrValue texture = builder.Input("texture", ShaderSourceType.Atomic(kind)); ShaderIrValue zero = builder.Constant(0f); - ShaderIrValue uv = kind == "sampled-texture2d" ? builder.Construct(ShaderSourceType.Atomic("float2"), zero, zero) - : builder.Construct(ShaderSourceType.Atomic("float3"), zero, zero, zero); + ShaderIrValue uv = kind == "sampled-texture2d" + ? builder.Construct(ShaderSourceType.Atomic("float2"), zero, zero) + : builder.Construct(ShaderSourceType.Atomic("float3"), zero, zero, zero); ShaderIrValue sampled = builder.Sample(texture, uv); ShaderIrValue level = builder.SampleLevel(texture, uv, zero); ShaderIrValue color = builder.Binary(ShaderIrOperation.Add, sampled, level); builder.Discard(builder.Binary(ShaderIrOperation.LessThan, builder.Extract(sampled, 3), builder.Constant(0.01f))); - Success(await Compile(new(ShaderStage.Fragment, builder.Build(new Dictionary { ["color"] = color }), - [new("texture", texture.type, ShaderIrInputKind.SampledTexture)], [new("color", ShaderIrOutputKind.Color)]))); + Success( + await Compile( + new( + ShaderStage.Fragment, + builder.Build(new Dictionary { ["color"] = color }), + [new("texture", texture.type, ShaderIrInputKind.SampledTexture)], + [new("color", ShaderIrOutputKind.Color)] + ) + ) + ); } } - private static ShaderSourceType Buffer(string element, RenderStorageAccess access) - => ShaderSourceType.Storage(ShaderStorageType.Buffer(ShaderSourceType.Atomic(element), access)); - private static ShaderSourceType Image() => ShaderSourceType.Storage(ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.ReadWrite)); - private static async Task Compile(ShaderIrStage stage, GraphicsCapability features = GraphicsCapability.Compute - | GraphicsCapability.StorageBuffer | GraphicsCapability.StorageTexture | GraphicsCapability.Texture2DArray | GraphicsCapability.Texture3D) - { + private static ShaderSourceType Buffer( + string element, + RenderStorageAccess access + ) => ShaderSourceType.Storage(ShaderStorageType.Buffer(ShaderSourceType.Atomic(element), access)); + + private static ShaderSourceType Image() + => ShaderSourceType.Storage(ShaderStorageType.Image(RenderTextureFormat.RGBA8, RenderStorageAccess.ReadWrite)); + + private static async Task Compile( + ShaderIrStage stage, + GraphicsCapability features = GraphicsCapability.Compute + | GraphicsCapability.StorageBuffer + | GraphicsCapability.StorageTexture + | GraphicsCapability.Texture2DArray + | GraphicsCapability.Texture3D + ) { var toolchain = new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target); - var capabilities = new GraphicsCapabilities(GraphicsApi.Metal, features, new GraphicsLimits(256, 8, 8192, 16), - Enum.GetValues(), Enum.GetValues(), Enum.GetValues(), - Enum.GetValues(), false, false); + var capabilities = new GraphicsCapabilities( + GraphicsApi.Metal, + features, + new GraphicsLimits(256, 8, 8192, 16), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + false, + false + ); return await new ShaderCompiler(toolchain).CompileAsync(stage, toolchain.CreateTarget(capabilities)); } + private static void Success(ShaderStageToolResult result) => Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static value => value.message))); } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs index 87ec326e1..898804da5 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs @@ -1,10 +1,10 @@ -using Inno.Adapter.Modules.DotNet; using System; using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Rendering.Shaders.Tests; @@ -38,15 +38,24 @@ public void DuplicateCandidateReleasesNewProvidersAndKeepsPreviousSnapshotUsable using var registry = new ShaderSourceFrontendRegistry(fixture.types); Assert.Contains("tests.registry.language", registry.languageIds); RegistryFrontendProbe.conflict = true; - try { Assert.ThrowsAny(fixture.modules.Rebuild); } - finally { RegistryFrontendProbe.conflict = false; } + try + { + Assert.ThrowsAny(fixture.modules.Rebuild); + } + finally + { + RegistryFrontendProbe.conflict = false; + } Assert.Contains("tests.registry.language", registry.languageIds); Assert.Equal(1, RegistryFrontendProbe.created - RegistryFrontendProbe.disposed); } private sealed class NoIncludes : IShaderSourceResolver { - public ShaderSourceFile ReadInclude(string includingFile, string include) => throw new FileNotFoundException(include); + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => throw new FileNotFoundException(include); } private sealed class Fixture : IDisposable @@ -54,14 +63,18 @@ private sealed class Fixture : IDisposable private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoShaderRegistry", Guid.NewGuid().ToString("N")); internal ModuleHost modules { get; } internal TypeCatalog types { get; } + internal Fixture() { RegistryFrontendProbe.created = 0; RegistryFrontendProbe.disposed = 0; RegistryFrontendProbe.conflict = false; - modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderSourceFrontendRegistryTests).Assembly)}); + modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderSourceFrontendRegistryTests).Assembly)} + ); types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); } + public void Dispose() { types.Dispose(); @@ -77,13 +90,17 @@ internal sealed class RegistryFrontendProbe : IShaderSourceFrontend, IDisposable internal static int disposed; internal static bool conflict; private readonly string m_languageId; + public RegistryFrontendProbe() { created++; m_languageId = conflict ? "inno.shader-language.bgfx-sc" : "tests.registry.language"; } + public string languageId => m_languageId; + public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) => new(new(request.entryPoint, ShaderSourceType.Atomic("float"), [], new(request.source.assetPath, 1, 1)), [], []); + public void Dispose() => disposed++; } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendTests.cs index 61e730489..7444d1015 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendTests.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering.Shaders; -using Xunit; namespace Inno.Rendering.Shaders.Tests; @@ -25,7 +25,9 @@ public void SourceModulesCannotReadGeneratedStageBindingsImplicitly(string sourc [Fact] public void ExplicitParametersAndStructureMembersDoNotBecomeImplicitBindings() { - ShaderSourceAnalysis result = Analyze("struct Data { vec4 a_position; }; vec4 Shade(Data value, mat4 u_viewProj) { return mul(u_viewProj, value.a_position); }"); + ShaderSourceAnalysis result = Analyze( + "struct Data { vec4 a_position; }; vec4 Shade(Data value, mat4 u_viewProj) { return mul(u_viewProj, value.a_position); }" + ); Assert.True(result.succeeded, Errors(result)); } @@ -36,8 +38,10 @@ public void SourceFunctionDerivesInputOutputAndInOutFromOneDeclaration() Assert.True(result.succeeded, Errors(result)); Assert.Equal("float3", result.function!.returnType.id); Assert.Equal(["uv", "alpha", "color"], result.function.parameters.Select(static parameter => parameter.name)); - Assert.Equal([ShaderSourceParameterDirection.Input, ShaderSourceParameterDirection.Output, ShaderSourceParameterDirection.InputOutput], - result.function.parameters.Select(static parameter => parameter.direction)); + Assert.Equal( + [ShaderSourceParameterDirection.Input, ShaderSourceParameterDirection.Output, ShaderSourceParameterDirection.InputOutput], + result.function.parameters.Select(static parameter => parameter.direction) + ); } [Fact] @@ -163,10 +167,13 @@ public void PreprocessorHandlesElseIfAndShortCircuitWithoutReadingInactiveInclud [InlineData("#else\nfloat Shade(float v) {}", "Shade")] [InlineData("uniform vec4 global;\nfloat Shade(float v) {}", "Shade")] [InlineData("#define F(a,) a\nfloat Shade(float value) {}", "Shade")] - public void InvalidSourceReturnsLocatedDiagnosticInsteadOfGuessingPorts(string source, string entry) - { + public void InvalidSourceReturnsLocatedDiagnosticInsteadOfGuessingPorts( + string source, + string entry + ) { ShaderSourceAnalysis result = new BgfxShaderSourceFrontend().Analyze( - new(new("bad.ishadersource", source), entry, new Includes([]))); + new(new("bad.ishadersource", source), entry, new Includes([])) + ); Assert.False(result.succeeded); Assert.NotEmpty(result.diagnostics); Assert.Equal("bad.ishadersource", result.diagnostics[0].location.assetPath); @@ -176,8 +183,10 @@ public void InvalidSourceReturnsLocatedDiagnosticInsteadOfGuessingPorts(string s [Fact] public void IncludedFailureReportsOriginalFileAndKeepsDependency() { - ShaderSourceAnalysis result = Analyze("#include \"bad.inc\"\nfloat Shade(float v) {}", - new Dictionary { ["bad.inc"] = "struct Broken { Undefined x; };" }); + ShaderSourceAnalysis result = Analyze( + "#include \"bad.inc\"\nfloat Shade(float v) {}", + new Dictionary { ["bad.inc"] = "struct Broken { Undefined x; };" } + ); Assert.False(result.succeeded); Assert.Equal("bad.inc", result.diagnostics[0].location.assetPath); Assert.Equal("bad.inc", Assert.Single(result.dependencies)); @@ -186,8 +195,10 @@ public void IncludedFailureReportsOriginalFileAndKeepsDependency() [Fact] public void PragmaOnceBreaksGuardedIncludeCycles() { - ShaderSourceAnalysis result = Analyze("#include \"a.inc\"\nfloat Shade(Data value) { return value.x; }", - new Dictionary { ["a.inc"] = "#pragma once\n#include \"a.inc\"\nstruct Data { float x; };" }); + ShaderSourceAnalysis result = Analyze( + "#include \"a.inc\"\nfloat Shade(Data value) { return value.x; }", + new Dictionary { ["a.inc"] = "#pragma once\n#include \"a.inc\"\nstruct Data { float x; };" } + ); Assert.True(result.succeeded, Errors(result)); } @@ -214,21 +225,26 @@ public void LanguageCatalogAcceptsAnIndependentFrontendAndRejectsConflicts() Assert.Throws(() => new ShaderSourceFrontendCatalog([new IndependentFrontend(), new IndependentFrontend()])); } - private static ShaderSourceAnalysis Analyze(string source, Dictionary? includes = null, - IReadOnlyDictionary? defines = null) - => new BgfxShaderSourceFrontend().Analyze(new(new("module.ishadersource", source), "Shade", new Includes(includes ?? []), defines)); + private static ShaderSourceAnalysis Analyze( + string source, + Dictionary? includes = null, + IReadOnlyDictionary? defines = null + ) => new BgfxShaderSourceFrontend().Analyze(new(new("module.ishadersource", source), "Shade", new Includes(includes ?? []), defines)); private static string Errors(ShaderSourceAnalysis result) => string.Join("; ", result.diagnostics.Select(static item => item.message)); private sealed class Includes(Dictionary sources) : IShaderSourceResolver { - public ShaderSourceFile ReadInclude(string includingFile, string include) - => sources.TryGetValue(include, out string? source) ? new(include, source) : throw new FileNotFoundException(include); + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => sources.TryGetValue(include, out string? source) ? new(include, source) : throw new FileNotFoundException(include); } private sealed class IndependentFrontend : IShaderSourceFrontend { public string languageId => "tests.language"; + public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) => new(new(request.entryPoint, ShaderSourceType.Atomic("float"), [], new(request.source.assetPath, 1, 1)), [], []); } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs index 3a915c584..ef5f97a93 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Execution; -using Xunit; namespace Inno.Rendering.Shaders.Tests; @@ -19,7 +19,11 @@ public void IndependentLanguagesShareOneInterfaceWithoutTranslatingSource() var catalog = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend(), alternate]); ShaderSourceModuleAnalysis result = catalog.AnalyzeModule([ Request("adapter.first", "float Shade(float value) { return value; }"), - new("adapter.second", alternate.languageId, new(new("Other.ishadersource", "native function implementation"), "ShadeOther", new Includes())) + new( + "adapter.second", + alternate.languageId, + new(new("Other.ishadersource", "native function implementation"), "ShadeOther", new Includes()) + ) ]); Assert.True(result.succeeded, Errors(result)); Assert.Equal("value", Assert.Single(result.function!.parameters).name); @@ -37,7 +41,8 @@ public void InterfaceChangesInvalidateWholeModuleWithoutSelectingAnArbitraryImpl { var catalog = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]); ShaderSourceModuleAnalysis result = catalog.AnalyzeModule([ - Request("first", "float Shade(float value) { return value; }"), Request("second", source) + Request("first", "float Shade(float value) { return value; }"), + Request("second", source) ]); Assert.False(result.succeeded); Assert.Null(result.function); @@ -81,8 +86,14 @@ public void SourcesAndDefinesAreFrozenAndIncludedInTheContentHash() Assert.Equal(2, first.sources.Count); Assert.Equal("data.inc", Assert.Single(first.analysis.dependencies)); - ShaderSourceImplementationAnalysis reordered = Assert.Single(catalog.AnalyzeModule([Request("different-owner-key", source, includes, - new Dictionary { ["SECOND"] = "2", ["FIRST"] = "1" })]).implementations); + ShaderSourceImplementationAnalysis reordered = Assert.Single( + catalog.AnalyzeModule([Request( + "different-owner-key", + source, + includes, + new Dictionary { ["SECOND"] = "2", ["FIRST"] = "1" } + )]).implementations + ); Assert.Equal(first.contentHash, reordered.contentHash); includes.values["data.inc"] = "#pragma once\nconst float Scale = 2.0;"; ShaderSourceImplementationAnalysis changed = Assert.Single(catalog.AnalyzeModule([request]).implementations); @@ -93,7 +104,11 @@ public void SourcesAndDefinesAreFrozenAndIncludedInTheContentHash() [Fact] public void MissingLanguageRetainsSourceAndRecoversWhenItsProviderReturns() { - var implementation = new ShaderSourceImplementationRequest("alternate", "tests.alternate", new(new("Other.ishadersource", "native source"), "Other", new Includes())); + var implementation = new ShaderSourceImplementationRequest( + "alternate", + "tests.alternate", + new(new("Other.ishadersource", "native source"), "Other", new Includes()) + ); ShaderSourceModuleAnalysis missing = new ShaderSourceFrontendCatalog([]).AnalyzeModule([implementation]); Assert.False(missing.succeeded); Assert.Null(missing.function); @@ -106,8 +121,11 @@ public void MissingLanguageRetainsSourceAndRecoversWhenItsProviderReturns() public void SuccessfulFrontendsCannotClaimDependenciesOutsideTheirFrozenSourceSet() { var alternate = new AlternateFrontend { inventedDependency = true }; - var request = new ShaderSourceImplementationRequest("alternate", alternate.languageId, - new(new("Other.ishadersource", "native source"), "Other", new Includes())); + var request = new ShaderSourceImplementationRequest( + "alternate", + alternate.languageId, + new(new("Other.ishadersource", "native source"), "Other", new Includes()) + ); ShaderSourceModuleAnalysis result = new ShaderSourceFrontendCatalog([alternate]).AnalyzeModule([request]); Assert.False(result.succeeded); Assert.Contains(result.diagnostics, value => value.code == "SHADER_SOURCE_DEPENDENCY_UNCAPTURED"); @@ -125,8 +143,11 @@ public void DuplicateOrEmptyImplementationSetsAreRejectedBeforeProvidersRun() [Fact] public void IncludeReadsCannotMixDifferentContentsForTheSameSourcePath() { - var request = Request("first", "#include \"data.inc\"\n#include \"data.inc\"\nfloat Shade(float value) { return value; }", - new ChangingIncludes()); + var request = Request( + "first", + "#include \"data.inc\"\n#include \"data.inc\"\nfloat Shade(float value) { return value; }", + new ChangingIncludes() + ); ShaderSourceModuleAnalysis result = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule([request]); Assert.False(result.succeeded); Assert.Contains(result.diagnostics, value => value.message.Contains("changed during module analysis", StringComparison.Ordinal)); @@ -137,7 +158,9 @@ public void SourceErrorsCannotSwallowTheSharedRetirementBarrier() { var failure = new IOException("Source candidate is retiring.", new RetirementPendingException("Pending source owner.")); var request = Request("first", "#include \"data.inc\"\nfloat Shade(float value) { return value; }", new FailingIncludes(failure)); - IOException actual = Assert.Throws(() => new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule([request])); + IOException actual = Assert.Throws( + () => new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule([request]) + ); Assert.Same(failure, actual); } @@ -157,37 +180,57 @@ public void AStageMainPrototypeIsNotAnAllowedFunctionModule() [InlineData("struct Data { void values[2]; }; float Shade(float value) { return value; }")] public void VoidCannotBeSmuggledIntoTheValueInterfaceViaAnArrayOrAlias(string source) { - ShaderSourceModuleAnalysis result = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule([Request("test", source)]); + ShaderSourceModuleAnalysis result = new ShaderSourceFrontendCatalog( + [new BgfxShaderSourceFrontend()] + ).AnalyzeModule([Request("test", source)]); Assert.False(result.succeeded); - Assert.Contains(result.diagnostics, value => value.code == "SHADER_SOURCE_INTERFACE" && value.message.Contains("void", StringComparison.Ordinal)); + Assert.Contains( + result.diagnostics, + value => value.code == "SHADER_SOURCE_INTERFACE" && value.message.Contains("void", StringComparison.Ordinal) + ); Assert.Throws(() => ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("void"), 2)); Assert.Throws(() => new ShaderSourceField("value", ShaderSourceType.Atomic("void"))); - Assert.Throws(() => new ShaderSourceParameter("value", ShaderSourceType.Atomic("void"), ShaderSourceParameterDirection.Output)); + Assert.Throws( + () => new ShaderSourceParameter("value", ShaderSourceType.Atomic("void"), ShaderSourceParameterDirection.Output) + ); } - private static ShaderSourceImplementationRequest Request(string id, string source, IShaderSourceResolver? includes = null, - IReadOnlyDictionary? defines = null) - => new(id, C_SC, new(new("Module.ishadersource", source), "Shade", includes ?? new Includes(), defines)); + private static ShaderSourceImplementationRequest Request( + string id, + string source, + IShaderSourceResolver? includes = null, + IReadOnlyDictionary? defines = null + ) => new(id, C_SC, new(new("Module.ishadersource", source), "Shade", includes ?? new Includes(), defines)); - private static string Errors(ShaderSourceModuleAnalysis result) => string.Join("\n", result.diagnostics.Select(static value => value.message)); + private static string Errors(ShaderSourceModuleAnalysis result) + => string.Join("\n", result.diagnostics.Select(static value => value.message)); private sealed class Includes : IShaderSourceResolver { internal Dictionary values { get; } = new(StringComparer.Ordinal); - public ShaderSourceFile ReadInclude(string includingFile, string include) - => new(include, values.TryGetValue(include, out string? value) ? value : throw new FileNotFoundException(include)); + + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => new(include, values.TryGetValue(include, out string? value) ? value : throw new FileNotFoundException(include)); } private sealed class ChangingIncludes : IShaderSourceResolver { private int m_count; - public ShaderSourceFile ReadInclude(string includingFile, string include) - => new(include, ++m_count == 1 ? "#pragma once\nconst float Scale = 1.0;" : "#pragma once\nconst float Scale = 2.0;"); + + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => new(include, ++m_count == 1 ? "#pragma once\nconst float Scale = 1.0;" : "#pragma once\nconst float Scale = 2.0;"); } private sealed class FailingIncludes(Exception failure) : IShaderSourceResolver { - public ShaderSourceFile ReadInclude(string includingFile, string include) => throw failure; + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => throw failure; } private sealed class AlternateFrontend : IShaderSourceFrontend @@ -195,12 +238,20 @@ private sealed class AlternateFrontend : IShaderSourceFrontend internal int calls; internal bool inventedDependency; public string languageId => "tests.alternate"; + public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) { calls++; - return new(new(request.entryPoint, ShaderSourceType.Atomic("float"), - [new("value", ShaderSourceType.Atomic("float"), ShaderSourceParameterDirection.Input)], new(request.source.assetPath, 1, 1)), - inventedDependency ? ["unread.inc"] : [], []); + return new( + new( + request.entryPoint, + ShaderSourceType.Atomic("float"), + [new("value", ShaderSourceType.Atomic("float"), ShaderSourceParameterDirection.Input)], + new(request.source.assetPath, 1, 1) + ), + inventedDependency ? ["unread.inc"] : [], + [] + ); } } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceNodeDefinitionTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceNodeDefinitionTests.cs index 88caba897..a48230809 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceNodeDefinitionTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceNodeDefinitionTests.cs @@ -1,6 +1,6 @@ using System.Linq; -using Inno.Core.Graphs; using Xunit; +using Inno.Core.Graphs; namespace Inno.Rendering.Shaders.Tests; @@ -11,10 +11,21 @@ public sealed class ShaderSourceNodeDefinitionTests [Fact] public void FunctionPortsUseSemanticNamesAndInOutCreatesBothDirections() { - var definition = new ShaderSourceNodeDefinition(new("Shade", ShaderSourceType.Atomic("float4"), - [new("uv", ShaderSourceType.Atomic("float2"), ShaderSourceParameterDirection.Input), - new("color", ShaderSourceType.Atomic("float4"), ShaderSourceParameterDirection.InputOutput)], new("source", 1, 1))); - Assert.Equal(["input.uv", "input.color", "output.color", "return"], definition.GetPorts(S_node).Select(static port => port.id.value)); + var definition = new ShaderSourceNodeDefinition( + new( + "Shade", + ShaderSourceType.Atomic("float4"), + [ + new("uv", ShaderSourceType.Atomic("float2"), ShaderSourceParameterDirection.Input), + new("color", ShaderSourceType.Atomic("float4"), ShaderSourceParameterDirection.InputOutput) + ], + new("source", 1, 1) + ) + ); + Assert.Equal( + ["input.uv", "input.color", "output.color", "return"], + definition.GetPorts(S_node).Select(static port => port.id.value) + ); Assert.Equal(GraphPortCapacity.Multiple, definition.GetPorts(S_node)[2].capacity); Assert.Same(definition.GetPorts(S_node), definition.GetPorts(S_node)); } @@ -23,21 +34,34 @@ public void FunctionPortsUseSemanticNamesAndInOutCreatesBothDirections() public void AggregatesExposeMembersWithoutDiscardingTheirWholeValuePorts() { ShaderSourceType aggregate = ShaderSourceType.Structure("Surface", [new("normal", ShaderSourceType.Atomic("float3"))]); - var definition = new ShaderSourceNodeDefinition(new("Shade", aggregate, - [new("surface", aggregate, ShaderSourceParameterDirection.Input)], new("source", 1, 1))); - Assert.Equal(["input.surface", "input.surface.normal", "return", "return.normal"], - definition.GetPorts(S_node).Select(static port => port.id.value)); + var definition = new ShaderSourceNodeDefinition( + new( + "Shade", + aggregate, + [new("surface", aggregate, ShaderSourceParameterDirection.Input)], + new("source", 1, 1) + ) + ); + Assert.Equal( + ["input.surface", "input.surface.normal", "return", "return.normal"], + definition.GetPorts(S_node).Select(static port => port.id.value) + ); Assert.Equal(definition.GetPorts(S_node)[0].valueTypeId, definition.GetPorts(S_node)[2].valueTypeId); } [Fact] public void ArrayLengthsAndStructureLayoutsCannotAliasGraphValueTypes() { - string FirstPortType(ShaderSourceType type) => new ShaderSourceNodeDefinition(new("Shade", type, [], new("source", 1, 1))) - .GetPorts(S_node)[0].valueTypeId; - Assert.NotEqual(FirstPortType(ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 2)), - FirstPortType(ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 3))); - Assert.NotEqual(FirstPortType(ShaderSourceType.Structure("Surface", [new("a", ShaderSourceType.Atomic("float3"))])), - FirstPortType(ShaderSourceType.Structure("Surface", [new("a", ShaderSourceType.Atomic("float4"))]))); + string FirstPortType(ShaderSourceType type) + => new ShaderSourceNodeDefinition(new("Shade", type, [], new("source", 1, 1))) + .GetPorts(S_node)[0].valueTypeId; + Assert.NotEqual( + FirstPortType(ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 2)), + FirstPortType(ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 3)) + ); + Assert.NotEqual( + FirstPortType(ShaderSourceType.Structure("Surface", [new("a", ShaderSourceType.Atomic("float3"))])), + FirstPortType(ShaderSourceType.Structure("Surface", [new("a", ShaderSourceType.Atomic("float4"))])) + ); } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTargetTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTargetTests.cs index 2b1e315e5..51402e17b 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTargetTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTargetTests.cs @@ -1,15 +1,15 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Rendering.Shaders.Tests; @@ -36,8 +36,13 @@ public void IndependentTargetExpandsIntoTheCommonCompilerWithoutMutatingItsSourc byte[] before = GraphDocumentCodec.Encode(authored, m_serialization); GraphDocument expanded = m_targets.Expand(authored, m_serialization, SerializationContext.empty); using var nodes = new ShaderNodeCompilerRegistry(m_types); - ShaderGraphProgramResult result = new ShaderGraphProgramCompiler(nodes).Lower(expanded, "bgfx", - new Dictionary(), m_serialization, SerializationContext.empty); + ShaderGraphProgramResult result = new ShaderGraphProgramCompiler(nodes).Lower( + expanded, + "bgfx", + new Dictionary(), + m_serialization, + SerializationContext.empty + ); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static value => value.message))); Assert.Equal(before, GraphDocumentCodec.Encode(authored, m_serialization)); Assert.Contains("tests.surface-target", m_targets.ids); @@ -50,8 +55,12 @@ public void UnavailableTargetPreservesTheAssignedIdentityAndAllAuthoredData() GraphDocument authored = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); ShaderGraphDocument.SetTarget(authored, "tests.unavailable-target", m_serialization, SerializationContext.empty); byte[] before = GraphDocumentCodec.Encode(authored, m_serialization); - Assert.Contains("tests.unavailable-target", Assert.Throws( - () => m_targets.Expand(authored, m_serialization, SerializationContext.empty)).Message); + Assert.Contains( + "tests.unavailable-target", + Assert.Throws( + () => m_targets.Expand(authored, m_serialization, SerializationContext.empty) + ).Message + ); Assert.Equal(before, GraphDocumentCodec.Encode(authored, m_serialization)); } @@ -60,8 +69,12 @@ public void CancellationCannotPublishAnExpansionOrModifyTheSource() { GraphDocument authored = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); byte[] before = GraphDocumentCodec.Encode(authored, m_serialization); - Assert.Throws(() => m_targets.Expand(authored, m_serialization, - SerializationContext.empty, new CancellationToken(true))); + Assert.Throws(() => m_targets.Expand( + authored, + m_serialization, + SerializationContext.empty, + new CancellationToken(true) + )); Assert.Equal(before, GraphDocumentCodec.Encode(authored, m_serialization)); } @@ -79,20 +92,29 @@ public void TemplatesAreDiscoveredByStableIdentityAndCreateIndependentDocuments( } public void Dispose() - { m_targets.Dispose(); m_serialization.Dispose(); m_types.Dispose(); m_modules.Dispose(); } + { + m_targets.Dispose(); + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + } [ShaderTarget("tests.surface-target")] public sealed class SurfaceTarget : ShaderTarget { - public override GraphDocument Expand(ShaderTargetContext context, CancellationToken cancellationToken) - => ShaderGraphTemplates.CreateRaster(context.serialization, context.references); + public override GraphDocument Expand( + ShaderTargetContext context, + CancellationToken cancellationToken + ) => ShaderGraphTemplates.CreateRaster(context.serialization, context.references); } [ShaderGraphTemplate("tests.surface-template", "Test Surface")] public sealed class SurfaceTemplate : ShaderGraphTemplate { - public override GraphDocument Create(SerializationRegistry serialization, SerializationContext context) - { + public override GraphDocument Create( + SerializationRegistry serialization, + SerializationContext context + ) { GraphDocument graph = ShaderGraphDocument.Create(new("Surface", [], [], []), serialization, context); ShaderGraphDocument.SetTarget(graph, "tests.surface-target", serialization, context); return graph; diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs index 574062cdf..a50c1dea7 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs @@ -1,4 +1,3 @@ -using Inno.Integration.MacOSArm64.Bgfx; using System; using System.Collections.Generic; using System.IO; @@ -6,11 +5,12 @@ using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Diagnostics; +using Inno.Integration.MacOSArm64.Bgfx; using Inno.Rendering; using Inno.Rendering.Assets; -using Xunit; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; @@ -19,7 +19,10 @@ public sealed class MetalShaderFactAttribute : FactAttribute { public MetalShaderFactAttribute() { - if (!OperatingSystem.IsMacOS()) Skip = "Requires the macOS BGFX Metal compiler; Windows validation is explicitly deferred."; + if (!OperatingSystem.IsMacOS()) + { + Skip = "Requires the macOS BGFX Metal compiler; Windows validation is explicitly deferred."; + } } } @@ -30,16 +33,24 @@ public sealed class ShaderTypedNativeCompilationTests public async Task EveryRectangularMatrixShapeSupportsColumnConstructionAndExtraction() { for (int columns = 2; columns <= 4; columns++) + { for (int rows = 2; rows <= 4; rows++) { var builder = new ShaderIrBuilder(); - ShaderIrValue matrix = builder.Construct(ShaderSourceType.Atomic($"float{columns}x{rows}"), - Enumerable.Range(1, columns * rows).Select(value => builder.Constant((float)value)).ToArray()); + ShaderIrValue matrix = builder.Construct( + ShaderSourceType.Atomic($"float{columns}x{rows}"), + Enumerable.Range(1, columns * rows).Select(value => builder.Constant((float)value)).ToArray() + ); ShaderIrValue product = builder.Binary(ShaderIrOperation.Multiply, matrix, matrix); ShaderIrValue column = builder.Extract(product, columns - 1); ShaderIrValue first = builder.Extract(column, 0); ShaderIrValue last = builder.Extract(column, rows - 1); - AssertSuccess(await Compile(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), first, last, first, builder.Constant(1f))))); + AssertSuccess( + await Compile( + Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), first, last, first, builder.Constant(1f))) + ) + ); + } } } @@ -56,12 +67,24 @@ public async Task OrdinaryArithmeticAndSelectionCompileWithoutSourceModules() [MetalShaderFact] public async Task SameNamedPrivateHelpersAndPublicFunctionsAreIsolatedPerModule() { - ShaderSourceModuleAnalysis first = Module("First.ishadersource", "float Adjust(float value) { return value * 1e-3; } float Shade(float value) { return Adjust(value) + .25; }"); - ShaderSourceModuleAnalysis second = Module("Second.ishadersource", "float Adjust(float value) { return value * 2.0; } float Shade(float value) { uint bits = 0xFE+1u; bits <<= 1u; return Adjust(value) + float(bits) * 0.0; }"); + ShaderSourceModuleAnalysis first = Module( + "First.ishadersource", + "float Adjust(float value) { return value * 1e-3; } float Shade(float value) { return Adjust(value) + .25; }" + ); + ShaderSourceModuleAnalysis second = Module( + "Second.ishadersource", + "float Adjust(float value) { return value * 2.0; } float Shade(float value) { uint bits = 0xFE+1u; bits <<= 1u; return Adjust(value) + float(bits) * 0.0; }" + ); var builder = new ShaderIrBuilder(); - ShaderIrValue a = builder.Call(first, "metal", new Dictionary { ["value"] = builder.Constant(0.5f) })["return"]; + ShaderIrValue a = builder.Call( + first, + "metal", + new Dictionary { ["value"] = builder.Constant(0.5f) } + )["return"]; ShaderIrValue b = builder.Call(second, "metal", new Dictionary { ["value"] = a })["return"]; - AssertSuccess(await Compile(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), a, b, a, builder.Constant(1f))))); + AssertSuccess( + await Compile(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), a, b, a, builder.Constant(1f)))) + ); } [MetalShaderFact] @@ -78,26 +101,53 @@ Surface Shade(Surface value, float weights[2], out float alpha, inout vec2 uv) { ShaderSourceType surfaceType = module.function!.returnType; ShaderIrValue uv = builder.Construct(ShaderSourceType.Atomic("float2"), builder.Constant(0.2f), builder.Constant(0.4f)); ShaderIrValue surface = builder.Construct(surfaceType, uv, builder.Constant(0.5f)); - ShaderIrValue weights = builder.Construct(ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 2), builder.Constant(0.5f), builder.Constant(1f)); + ShaderIrValue weights = builder.Construct( + ShaderSourceType.ArrayOf(ShaderSourceType.Atomic("float"), 2), + builder.Constant(0.5f), + builder.Constant(1f) + ); IReadOnlyDictionary values = builder.Call(module, "metal", new Dictionary - { ["value"] = surface, ["weights"] = weights, ["uv"] = uv }); + { + ["value"] = surface, + ["weights"] = weights, + ["uv"] = uv + }); ShaderIrValue result = builder.Extract(values["return"], 1); - ShaderIrValue color = builder.Construct(ShaderSourceType.Atomic("float4"), result, builder.Extract(values["output.uv"], 0), result, values["output.alpha"]); + ShaderIrValue color = builder.Construct( + ShaderSourceType.Atomic("float4"), + result, + builder.Extract(values["output.uv"], 0), + result, + values["output.alpha"] + ); AssertSuccess(await Compile(Fragment(builder, color))); } [MetalShaderFact] public async Task SampledTextureAndUniformBindingsAreReturnedWithTheBinary() { - ShaderSourceModuleAnalysis module = Module("Sample.ishadersource", "vec4 Shade(sampler2D image, vec2 uv, vec4 tint) { return texture2D(image, uv) * tint; }"); + ShaderSourceModuleAnalysis module = Module( + "Sample.ishadersource", + "vec4 Shade(sampler2D image, vec2 uv, vec4 tint) { return texture2D(image, uv) * tint; }" + ); var builder = new ShaderIrBuilder(); ShaderIrValue image = builder.Input("texture-id", ShaderSourceType.Atomic("sampled-texture2d")); ShaderIrValue tint = builder.Input("tint-id", ShaderSourceType.Atomic("float4")); ShaderIrValue uv = builder.Input("uv-id", ShaderSourceType.Atomic("float2")); - ShaderIrValue color = builder.Call(module, "metal", new Dictionary { ["image"] = image, ["uv"] = uv, ["tint"] = tint })["return"]; - ShaderIrStage stage = Fragment(builder, color, - [new("texture-id", image.type, ShaderIrInputKind.SampledTexture, location: 3), - new("tint-id", tint.type, ShaderIrInputKind.Uniform), new("uv-id", uv.type, ShaderIrInputKind.Varying, "texcoord")]); + ShaderIrValue color = builder.Call( + module, + "metal", + new Dictionary { ["image"] = image, ["uv"] = uv, ["tint"] = tint } + )["return"]; + ShaderIrStage stage = Fragment( + builder, + color, + [ + new("texture-id", image.type, ShaderIrInputKind.SampledTexture, location: 3), + new("tint-id", tint.type, ShaderIrInputKind.Uniform), + new("uv-id", uv.type, ShaderIrInputKind.Varying, "texcoord") + ] + ); ShaderStageToolResult result = await Compile(stage); AssertSuccess(result); Assert.Equal(2, result.bindings.Count); @@ -116,16 +166,32 @@ public async Task VertexInstanceInputAndMrtFragmentCompileAsTypedStages() ShaderIrValue instance = vertex.Input("instance", ShaderSourceType.Atomic("float4")); ShaderIrValue clip = vertex.Binary(ShaderIrOperation.Add, position, instance); ShaderIrBlock vertexBody = vertex.Build(new Dictionary { ["clip"] = clip, ["color"] = instance }); - AssertSuccess(await Compile(new(ShaderStage.Vertex, vertexBody, - [new("position", position.type, ShaderIrInputKind.VertexAttribute, "position"), - new("instance", instance.type, ShaderIrInputKind.VertexAttribute, "instance-data")], - [new("clip", ShaderIrOutputKind.ClipPosition), new("color", ShaderIrOutputKind.Varying, "color")]))); + AssertSuccess( + await Compile( + new( + ShaderStage.Vertex, + vertexBody, + [ + new("position", position.type, ShaderIrInputKind.VertexAttribute, "position"), + new("instance", instance.type, ShaderIrInputKind.VertexAttribute, "instance-data") + ], + [new("clip", ShaderIrOutputKind.ClipPosition), new("color", ShaderIrOutputKind.Varying, "color")] + ) + ) + ); var fragment = new ShaderIrBuilder(); ShaderIrValue color = fragment.Input("color", ShaderSourceType.Atomic("float4")); ShaderIrBlock fragmentBody = fragment.Build(new Dictionary { ["base"] = color, ["emission"] = color }); - AssertSuccess(await Compile(new(ShaderStage.Fragment, fragmentBody, - [new("color", color.type, ShaderIrInputKind.Varying, "color")], - [new("base", ShaderIrOutputKind.Color), new("emission", ShaderIrOutputKind.Color, location: 1)]))); + AssertSuccess( + await Compile( + new( + ShaderStage.Fragment, + fragmentBody, + [new("color", color.type, ShaderIrInputKind.Varying, "color")], + [new("base", ShaderIrOutputKind.Color), new("emission", ShaderIrOutputKind.Color, location: 1)] + ) + ) + ); } [MetalShaderFact] @@ -135,36 +201,65 @@ public async Task ComputeEntryAndWorkgroupAreGeneratedNotSuppliedByTheSourceModu ShaderIrValue id = builder.Input("invocation", ShaderSourceType.Atomic("uint3")); ShaderSourceModuleAnalysis module = Module("Compute.ishadersource", "void Shade(uvec3 gid) { if (gid.x > 0u) return; }"); _ = builder.Call(module, "metal", new Dictionary { ["gid"] = id }); - ShaderIrStage stage = new(ShaderStage.Compute, builder.Build(new Dictionary()), - [new("invocation", id.type, ShaderIrInputKind.Builtin, "global-invocation-id")], [], 8, 4, 1); + ShaderIrStage stage = new( + ShaderStage.Compute, + builder.Build(new Dictionary()), + [new("invocation", id.type, ShaderIrInputKind.Builtin, "global-invocation-id")], + [], + 8, + 4, + 1 + ); AssertSuccess(await Compile(stage)); ShaderStageToolResult unsupported = await Compile(stage, GraphicsCapability.None); Assert.False(unsupported.succeeded); - Assert.Contains(unsupported.diagnostics, diagnostic => diagnostic.code == "BGFX_IR_GENERATION" && diagnostic.message.Contains("Compute", StringComparison.Ordinal)); + Assert.Contains( + unsupported.diagnostics, + diagnostic => diagnostic.code == "BGFX_IR_GENERATION" && diagnostic.message.Contains("Compute", StringComparison.Ordinal) + ); } [MetalShaderFact] public async Task InvalidNativeFunctionBodyCannotPublishAStageBinary() { - ShaderSourceModuleAnalysis module = Module("Broken.ishadersource", "float Shade(float value) { return ThisFunctionDoesNotExist(value); }"); + ShaderSourceModuleAnalysis module = Module( + "Broken.ishadersource", + "float Shade(float value) { return ThisFunctionDoesNotExist(value); }" + ); var builder = new ShaderIrBuilder(); - ShaderIrValue value = builder.Call(module, "metal", new Dictionary { ["value"] = builder.Constant(1f) })["return"]; - ShaderStageToolResult result = await Compile(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), value, value, value, value))); + ShaderIrValue value = builder.Call( + module, + "metal", + new Dictionary { ["value"] = builder.Constant(1f) } + )["return"]; + ShaderStageToolResult result = await Compile( + Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), value, value, value, value)) + ); Assert.False(result.succeeded); Assert.Empty(result.bytes.ToArray()); Assert.Contains(result.diagnostics, diagnostic => diagnostic.severity == DiagnosticSeverity.Error); - Assert.True(result.diagnostics.Any(diagnostic => diagnostic.location.assetPath.Contains("Broken.ishadersource", StringComparison.Ordinal)), - string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message))); + Assert.True( + result.diagnostics.Any(diagnostic => diagnostic.location.assetPath.Contains("Broken.ishadersource", StringComparison.Ordinal)), + string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message)) + ); } [MetalShaderFact] public async Task IncludeAliasesCompileFromFrozenSnapshotsAfterTheOwnerResolverIsGone() { var resolver = new AliasedInclude(); - ShaderSourceModuleAnalysis module = Module("Include.ishadersource", "#include \"@library/math\"\nfloat Shade(float value) { return Scale(value); }", resolver); + ShaderSourceModuleAnalysis module = Module( + "Include.ishadersource", + "#include \"@library/math\"\nfloat Shade(float value) { return Scale(value); }", + resolver + ); resolver.available = false; var builder = new ShaderIrBuilder(); - ShaderIrValue value = builder.Call(module, "metal", new Dictionary { ["value"] = builder.Constant(1f) })["return"]; + ShaderIrValue value = builder.Call( + module, + "metal", + new Dictionary { ["value"] = builder.Constant(1f) } + )["return"]; AssertSuccess(await Compile(Fragment(builder, builder.Construct(ShaderSourceType.Atomic("float4"), value, value, value, value)))); Assert.Single(module.implementations[0].includes); Assert.Equal("plugin:library/scale.ishadersource", module.implementations[0].includes[0].resolvedPath); @@ -181,34 +276,60 @@ await Assert.ThrowsAnyAsync(async () => await toolchain.CompileAsync(new ShaderStageToolRequest(stage, target), new CancellationToken(true))); } - private static ShaderIrValue Color(ShaderIrBuilder builder, float value) - { + private static ShaderIrValue Color( + ShaderIrBuilder builder, + float value + ) { ShaderIrValue scalar = builder.Constant(value); return builder.Construct(ShaderSourceType.Atomic("float4"), scalar, scalar, scalar, scalar); } - private static ShaderIrStage Fragment(ShaderIrBuilder builder, ShaderIrValue color, ShaderIrStageInput[]? inputs = null) - => new(ShaderStage.Fragment, builder.Build(new Dictionary { ["color"] = color }), inputs ?? [], [new("color", ShaderIrOutputKind.Color)]); + private static ShaderIrStage Fragment( + ShaderIrBuilder builder, + ShaderIrValue color, + ShaderIrStageInput[]? inputs = null + ) => new( + ShaderStage.Fragment, + builder.Build(new Dictionary { ["color"] = color }), + inputs ?? [], + [new("color", ShaderIrOutputKind.Color)] + ); - private static ShaderSourceModuleAnalysis Module(string path, string source, IShaderSourceResolver? resolver = null) - { + private static ShaderSourceModuleAnalysis Module( + string path, + string source, + IShaderSourceResolver? resolver = null + ) { ShaderSourceModuleAnalysis result = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule( - [new("metal", "inno.shader-language.bgfx-sc", new(new(path, source), "Shade", resolver ?? new AliasedInclude()))]); + [new("metal", "inno.shader-language.bgfx-sc", new(new(path, source), "Shade", resolver ?? new AliasedInclude()))] + ); Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message))); return result; } - private static async Task Compile(ShaderIrStage stage, - GraphicsCapability capabilities = GraphicsCapability.Compute | GraphicsCapability.Instancing | GraphicsCapability.Texture2DArray | GraphicsCapability.Texture3D) - { + private static async Task Compile( + ShaderIrStage stage, + GraphicsCapability capabilities = GraphicsCapability.Compute + | GraphicsCapability.Instancing + | GraphicsCapability.Texture2DArray + | GraphicsCapability.Texture3D + ) { var compiler = new ShaderCompiler(new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target)); return await compiler.CompileAsync(stage, compiler.CreateTarget(Capabilities(capabilities))); } private static GraphicsCapabilities Capabilities(GraphicsCapability features) - => new(GraphicsApi.Metal, features, new GraphicsLimits(256, 8, 8192, 16), - Enum.GetValues(), Enum.GetValues(), Enum.GetValues(), - Enum.GetValues(), originBottomLeft: false, homogeneousDepth: false); + => new( + GraphicsApi.Metal, + features, + new GraphicsLimits(256, 8, 8192, 16), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + Enum.GetValues(), + originBottomLeft: false, + homogeneousDepth: false + ); private static void AssertSuccess(ShaderStageToolResult result) => Assert.True(result.succeeded, string.Join("\n", result.diagnostics.Select(static diagnostic => diagnostic.message))); @@ -216,8 +337,12 @@ private static void AssertSuccess(ShaderStageToolResult result) private sealed class AliasedInclude : IShaderSourceResolver { internal bool available = true; - public ShaderSourceFile ReadInclude(string includingFile, string include) - => available && include == "@library/math" ? new("plugin:library/scale.ishadersource", "float Scale(float value) { return value * 2.0; }") - : throw new FileNotFoundException(include); + + public ShaderSourceFile ReadInclude( + string includingFile, + string include + ) => available && include == "@library/math" + ? new("plugin:library/scale.ishadersource", "float Scale(float value) { return value * 2.0; }") + : throw new FileNotFoundException(include); } } diff --git a/tests/rendering/Inno.Rendering.Tests/GraphicsApiTests.cs b/tests/rendering/Inno.Rendering.Tests/GraphicsApiTests.cs index 9e5d14dbf..28fb88a45 100644 --- a/tests/rendering/Inno.Rendering.Tests/GraphicsApiTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/GraphicsApiTests.cs @@ -1,6 +1,6 @@ using System; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -17,11 +17,27 @@ public void CustomBackendIdentityCanFlowThroughDeviceCapabilities() Assert.Throws(() => new GraphicsApi("..")); Assert.False(GraphicsApi.TryParse("../other", out _)); Assert.Throws(() => new GraphicsCapabilities( - default, GraphicsCapability.None, new GraphicsLimits(16, 1, 256, 0), - [], [], [], [], originBottomLeft: false, homogeneousDepth: false)); + default, + GraphicsCapability.None, + new GraphicsLimits(16, 1, 256, 0), + [], + [], + [], + [], + originBottomLeft: false, + homogeneousDepth: false + )); var capabilities = new GraphicsCapabilities( - api, GraphicsCapability.None, new GraphicsLimits(16, 1, 256, 0), - [], [], [], [], originBottomLeft: false, homogeneousDepth: false); + api, + GraphicsCapability.None, + new GraphicsLimits(16, 1, 256, 0), + [], + [], + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); Assert.Equal(api, capabilities.backend); } } diff --git a/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs b/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs index 47bf3bab6..fc01e4b92 100644 --- a/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs @@ -12,11 +12,28 @@ public void DeviceProgramRoundTripPreservesBinariesBindingsAndRasterWithoutAutho { byte[] vertex = [1, 2, 3]; byte[] fragment = [4, 5]; - var raster = new RenderRasterState(RenderCullMode.None, RenderFrontFace.CounterClockwise, - RenderDepthCompare.Always, false, RenderBlendState.premultiplied, 0xF, true, RenderPrimitiveTopology.TriangleList); - var descriptor = new GraphicsPipelineDescriptor(vertex, fragment, - [new RenderShaderBindingDescriptor(new RenderBindingId("s_tex"), RenderShaderBindingKind.Texture, - slot: 3, nativeName: "native_sampler")], null, raster); + var raster = new RenderRasterState( + RenderCullMode.None, + RenderFrontFace.CounterClockwise, + RenderDepthCompare.Always, + false, + RenderBlendState.premultiplied, + 0xF, + true, + RenderPrimitiveTopology.TriangleList + ); + var descriptor = new GraphicsPipelineDescriptor( + vertex, + fragment, + [new RenderShaderBindingDescriptor( + new RenderBindingId("s_tex"), + RenderShaderBindingKind.Texture, + slot: 3, + nativeName: "native_sampler" + )], + null, + raster + ); byte[] bytes = GraphicsProgramArtifactCodec.Encode(descriptor); Assert.Equal(bytes, GraphicsProgramArtifactCodec.Encode(descriptor)); GraphicsPipelineDescriptor decoded = GraphicsProgramArtifactCodec.Decode(bytes); @@ -39,13 +56,17 @@ [new RenderShaderBindingDescriptor(new RenderBindingId("s_tex"), RenderShaderBin public void InvalidBindingAndRasterValuesCannotBeEncodedAsValidArtifacts() { Assert.Throws(() => new RenderShaderBindingDescriptor( - new("invalid"), RenderShaderBindingKind.Uniform, uniformType: (RenderUniformType)99)); + new("invalid"), + RenderShaderBindingKind.Uniform, + uniformType: (RenderUniformType)99 + )); var invalidRaster = new RenderRasterState { colorWriteMask = 0xFF }; var descriptor = new GraphicsPipelineDescriptor([1], [2], [], null, invalidRaster); Assert.Throws(() => GraphicsProgramArtifactCodec.Encode(descriptor)); var invalidBlend = new RenderRasterState { blend = new RenderBlendState { colorSource = (RenderBlendFactor)99 } }; Assert.Throws(() => GraphicsProgramArtifactCodec.Encode( - new GraphicsPipelineDescriptor([1], [2], [], null, invalidBlend))); + new GraphicsPipelineDescriptor([1], [2], [], null, invalidBlend) + )); } [Fact] @@ -53,7 +74,9 @@ public void TruncationOversizedFieldsBadHeadersAndTrailingBytesFailBeforePublica { byte[] bytes = GraphicsProgramArtifactCodec.Encode(new GraphicsPipelineDescriptor([1], [2], [], null)); for (int length = 0; length < bytes.Length; length++) + { Assert.Throws(() => GraphicsProgramArtifactCodec.Decode(bytes.AsSpan(0, length))); + } byte[] excessive = (byte[])bytes.Clone(); BinaryPrimitives.WriteInt32LittleEndian(excessive.AsSpan("INNOGPU"u8.Length), int.MaxValue); Assert.Throws(() => GraphicsProgramArtifactCodec.Decode(excessive)); diff --git a/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs b/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs index 4b9eb9daf..67f48009d 100644 --- a/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -12,8 +12,12 @@ public sealed class ParallelCommandRecordingTests public void EveryCommandReplaysTheSameArgumentsAfterBufferGrowthAndSourceReuse() { RenderGraphBuilder builder = CreateGraph(); - var texture = new RenderTextureDescriptor(32, 32, RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled | RenderTextureUsage.ColorAttachment); + var texture = new RenderTextureDescriptor( + 32, + 32, + RenderTextureFormat.RGBA8, + RenderTextureUsage.Sampled | RenderTextureUsage.ColorAttachment + ); var buffer = new RenderBufferDescriptor(32, 16, RenderBufferUsage.Vertex | RenderBufferUsage.Storage); var data = new CommandInputs { @@ -22,11 +26,16 @@ public void EveryCommandReplaysTheSameArgumentsAfterBufferGrowthAndSourceReuse() buffer = builder.ImportBuffer("buffer", DeviceHandles.buffer, buffer), otherBuffer = builder.ImportBuffer("other-buffer", DeviceHandles.otherBuffer, buffer) }; - builder.AddRasterPass("Commands", new RenderPhaseId("tests.commands"), data, - static ( - inputs, - context - ) => IssueCommands(inputs, context.commands)) + builder + .AddRasterPass( + "Commands", + new RenderPhaseId("tests.commands"), + data, + static ( + inputs, + context + ) => IssueCommands(inputs, context.commands) + ) .AllowParallelRecording() .ReadTexture(data.source) .ReadTexture(data.destination) @@ -53,7 +62,9 @@ public void EveryCommandReplaysTheSameArgumentsAfterBufferGrowthAndSourceReuse() graph.Execute(backend, 43); Assert.Equal(expected.calls.Count, backend.encoder.calls.Count); for (int index = 0; index < expected.calls.Count; index++) + { Assert.Equal(expected.calls[index].arguments, backend.encoder.calls[index].arguments); + } } [Theory] @@ -75,14 +86,20 @@ public void RecordedReferencesAreReleasedOnEveryExecutionExit(string phase) CompiledRenderGraph graph = builder.Compile().graph!; var backend = new ProbeBackend(phase, capture: false); if (phase == "success") + { graph.Execute(backend, 1); + } else { Exception failure = Assert.ThrowsAny(() => graph.Execute(backend, 1)); foreach (string expected in phase.Split(',')) + { Assert.Contains(expected, failure.ToString(), StringComparison.Ordinal); + } if (phase.Contains(',', StringComparison.Ordinal)) + { Assert.Equal(phase.Split(',').Length, Assert.IsType(failure).Flatten().InnerExceptions.Count); + } } Assert.True(backend.ended); @@ -96,13 +113,21 @@ public void RecordedReferencesAreReleasedOnEveryExecutionExit(string phase) GC.KeepAlive(data.borrowedCommands); } - private static RenderGraphBuilder CreateGraph() => new(1, new GraphicsCapabilities( - GraphicsApi.Noop, - GraphicsCapability.Compute | GraphicsCapability.StorageBuffer | GraphicsCapability.StorageTexture, - new GraphicsLimits(16, 8, 16384, 16), - [RenderTextureFormat.RGBA8], [RenderTextureFormat.RGBA8], - [RenderTextureFormat.RGBA8], [RenderTextureFormat.RGBA8], - originBottomLeft: false, homogeneousDepth: false)); + private static RenderGraphBuilder CreateGraph() + => new( + 1, + new GraphicsCapabilities( + GraphicsApi.Noop, + GraphicsCapability.Compute | GraphicsCapability.StorageBuffer | GraphicsCapability.StorageTexture, + new GraphicsLimits(16, 8, 16384, 16), + [RenderTextureFormat.RGBA8], + [RenderTextureFormat.RGBA8], + [RenderTextureFormat.RGBA8], + [RenderTextureFormat.RGBA8], + originBottomLeft: false, + homogeneousDepth: false + ) + ); private static void IssueCommands( CommandInputs data, @@ -113,10 +138,14 @@ RenderCommandEncoder commands { byte[] uniform = new byte[4097]; for (int offset = 0; offset < uniform.Length; offset++) + { uniform[offset] = unchecked((byte)(offset + index)); + } float[] transform = new float[16]; for (int element = 0; element < transform.Length; element++) + { transform[element] = index + element * 0.25f; + } var sampler = RenderSamplerState.linearClamp; var sourceRegion = new RenderTextureRegion(0, 1, 2, 0, 3, 4); var destinationRegion = new RenderTextureRegion(0, 5, 6, 0, 3, 4); @@ -167,9 +196,13 @@ RenderPassContext context data.borrowedCommands = context.commands; context.commands.SetRasterState(state); for (int index = 0; index < 32; index++) + { context.commands.SetUniform(new RenderBindingId("lifetime"), new byte[257]); + } if (data.phase.Contains("record", StringComparison.Ordinal)) + { throw new InvalidOperationException("record"); + } } private sealed class CommandInputs @@ -213,26 +246,32 @@ internal ProbeBackend( encoder = new ProbeEncoder(phase, capture); } - public void BeginGraph(CompiledRenderGraph graph) { } + public void BeginGraph(CompiledRenderGraph graph) {} public RenderCommandEncoder BeginPass(CompiledRenderPass pass) { if (m_phase == "begin-pass") + { throw new InvalidOperationException(m_phase); + } return encoder; } public void EndPass(CompiledRenderPass pass) { if (m_phase.Contains("end-pass", StringComparison.Ordinal)) + { throw new InvalidOperationException("end-pass"); + } } public void EndGraph(CompiledRenderGraph graph) { ended = true; if (m_phase.Contains("end-graph", StringComparison.Ordinal)) + { throw new InvalidOperationException("end-graph"); + } } } @@ -294,7 +333,8 @@ public override void SetUniform( ReadOnlySpan value ) => Record("SetUniform", binding, Convert.ToHexString(value)); - public override void SetTransform(ReadOnlySpan columnMajorMatrix) => Record("SetTransform", Convert.ToHexString(MemoryMarshal.AsBytes(columnMajorMatrix))); + public override void SetTransform(ReadOnlySpan columnMajorMatrix) + => Record("SetTransform", Convert.ToHexString(MemoryMarshal.AsBytes(columnMajorMatrix))); public override void SetRasterState(RenderRasterState state) => Record("SetRasterState", state); @@ -413,9 +453,13 @@ private void Record( params object?[] arguments ) { if (m_phase.Contains("replay", StringComparison.Ordinal)) + { throw new InvalidOperationException("replay"); + } if (m_capture) + { calls.Add(new ObservedCommand(operation, arguments)); + } } } diff --git a/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs b/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs index 7faee8848..d9bcbddb0 100644 --- a/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs @@ -1,7 +1,7 @@ using System; using System.Linq; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -18,8 +18,12 @@ public void PipelineBindingSnapshotsRejectMutationOfPublishedStorage() input[0] = changed; Assert.Same(binding, graphics.bindings[0]); Assert.Same(binding, compute.bindings[0]); - Assert.Throws(() => ((System.Collections.Generic.IList)graphics.bindings)[0] = changed); - Assert.Throws(() => ((System.Collections.Generic.IList)compute.bindings)[0] = changed); + Assert.Throws( + () => ((System.Collections.Generic.IList)graphics.bindings)[0] = changed + ); + Assert.Throws( + () => ((System.Collections.Generic.IList)compute.bindings)[0] = changed + ); } [Fact] @@ -28,7 +32,8 @@ public void VertexLayoutAcceptsAllPortableSemanticChannels() RenderVertexSemantic[] semantics = Enum.GetValues(); var layout = new RenderVertexLayout( semantics.Select(static semantic => - new RenderVertexAttribute(semantic, RenderVertexFormat.Float4)).ToArray()); + new RenderVertexAttribute(semantic, RenderVertexFormat.Float4)).ToArray() + ); Assert.Equal(semantics.Length, layout.attributes.Count); Assert.Equal(semantics.Length * 16, layout.stride); @@ -40,21 +45,24 @@ public void VertexLayoutAcceptsAllPortableSemanticChannels() public void VertexLayout_RejectsDuplicateSemantic() { Assert.Throws(() => new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3), - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2) - ])); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3), + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2) + ] + )); } [Fact] public void VertexLayout_PreservesExplicitOffsetsAndTrailingPadding() { var layout = new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), - new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 16), - new RenderVertexAttribute(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Half2) - ], stride: 32); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), + new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 16), + new RenderVertexAttribute(RenderVertexSemantic.TextureCoordinate0, RenderVertexFormat.Half2) + ], + stride: 32 + ); Assert.Equal([0, 16, 20], layout.attributes.Select(static attribute => attribute.byteOffset)); Assert.Equal(32, layout.stride); @@ -78,14 +86,17 @@ public void VertexLayoutEquality_IncludesTrailingStride() public void VertexLayout_RejectsOverlappingAttributesAndShortStride() { Assert.Throws(() => new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), - new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 8) - ])); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), + new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 8) + ] + )); Assert.Throws(() => new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ], stride: 8)); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ], + stride: 8 + )); } [Fact] @@ -93,9 +104,10 @@ public void PersistentVertexBuffer_RequiresMatchingLayout() { RenderBufferDescriptor buffer = new(3, 12, RenderBufferUsage.Vertex); RenderVertexLayout mismatched = new( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float4) - ]); + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float4) + ] + ); Assert.Throws(() => new PersistentBufferDescriptor(buffer, mismatched)); } @@ -110,26 +122,24 @@ public void TextureDescriptor_ModelsVolumeAndCubemapSubresourcesWithoutBackendTy RenderTextureUsage.Sampled, mipCount: 3, dimension: RenderTextureDimension.Texture3D, - depth: 8); + depth: 8 + ); var cubemapArray = new RenderTextureDescriptor( 32, 32, RenderTextureFormat.RGBA16Float, RenderTextureUsage.Sampled, arrayLayers: 2, - dimension: RenderTextureDimension.Cube); + dimension: RenderTextureDimension.Cube + ); Assert.Equal(8, volume.GetSubresourceLayerCount(0)); Assert.Equal(2, volume.GetSubresourceLayerCount(2)); Assert.Equal(12, cubemapArray.GetSubresourceLayerCount(0)); Assert.NotEqual( volume, - new RenderTextureDescriptor( - 16, - 8, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled, - mipCount: 3)); + new RenderTextureDescriptor(16, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, mipCount: 3) + ); } [Fact] @@ -140,7 +150,8 @@ public void TextureDescriptor_RejectsContradictoryDimensions() 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, - dimension: RenderTextureDimension.Cube)); + dimension: RenderTextureDimension.Cube + )); Assert.Throws(() => new RenderTextureDescriptor( 16, 16, @@ -148,7 +159,8 @@ public void TextureDescriptor_RejectsContradictoryDimensions() RenderTextureUsage.Sampled, arrayLayers: 2, dimension: RenderTextureDimension.Texture3D, - depth: 4)); + depth: 4 + )); Assert.Throws(() => new RenderTextureDescriptor( 16, 16, @@ -156,7 +168,8 @@ public void TextureDescriptor_RejectsContradictoryDimensions() RenderTextureUsage.Sampled, sampleCount: 4, dimension: RenderTextureDimension.Texture3D, - depth: 4)); + depth: 4 + )); } [Fact] @@ -189,14 +202,9 @@ public void FixedFunctionStateConstructorsPreserveCompleteImmutableConfiguration RenderStencilCompare.NotEqual, RenderStencilOperation.Zero, RenderStencilOperation.IncrementWrap, - RenderStencilOperation.Replace); - var stencil = new RenderStencilState( - true, - 7, - 0x7f, - 0x3f, - face, - face); + RenderStencilOperation.Replace + ); + var stencil = new RenderStencilState(true, 7, 0x7f, 0x3f, face, face); var raster = new RenderRasterState( RenderCullMode.Front, RenderFrontFace.Clockwise, @@ -205,7 +213,8 @@ public void FixedFunctionStateConstructorsPreserveCompleteImmutableConfiguration RenderBlendState.premultiplied, 0x07, false, - RenderPrimitiveTopology.LineList); + RenderPrimitiveTopology.LineList + ); Assert.True(stencil.enabled); Assert.Equal((byte)7, stencil.reference); @@ -228,7 +237,8 @@ public void ShaderBinding_RejectsDefaultIdentifier() { Assert.Throws(() => new RenderShaderBindingDescriptor( default, - RenderShaderBindingKind.Uniform)); + RenderShaderBindingKind.Uniform + )); } [Fact] @@ -238,7 +248,8 @@ public void ShaderBinding_ModelsStorageTextureAccessWithoutBackendTypes() new RenderBindingId("u_output"), RenderShaderBindingKind.StorageTexture, slot: 3, - storageAccess: RenderStorageAccess.ReadWrite); + storageAccess: RenderStorageAccess.ReadWrite + ); Assert.Equal(RenderShaderBindingKind.StorageTexture, binding.kind); Assert.Equal(RenderStorageAccess.ReadWrite, binding.storageAccess); diff --git a/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs b/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs index 5bb8a386c..0128af2b4 100644 --- a/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs @@ -2,8 +2,8 @@ using System.Collections.Generic; using System.Linq; using System.Threading; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -21,21 +21,27 @@ public void NameScopesIsolateRepeatedProducerNamesInsideOneFrameGraph() RenderGraphBuilder graph = CreateGraph(); using (graph.BeginNameScope("Request[0] First")) { - graph.AddRasterPass("Visible", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Visible", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) .HasSideEffect(); } using (graph.BeginNameScope("Request[1] Second")) { - graph.AddRasterPass("Visible", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Visible", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) .HasSideEffect(); } RenderGraphCompileResult result = graph.Compile(); Assert.True(result.succeeded); - Assert.Equal( - ["Request[0] First/Visible", "Request[1] Second/Visible"], - PassNames(result.graph!)); + Assert.Equal(["Request[0] First/Visible", "Request[1] Second/Visible"], PassNames(result.graph!)); } [Fact] @@ -45,12 +51,20 @@ public void MutationScope_Uncommitted_RollsBackPassesResourcesAndOutputs() using (graph.BeginMutationScope()) { RenderTextureHandle temporary = graph.CreateTexture("Temporary", ColorDescriptor()); - graph.AddRasterPass("Failed Feature", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Failed Feature", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(temporary, 0, RenderLoadAction.Clear); graph.MarkOutput(temporary); } - graph.AddRasterPass("Survivor", C_FINAL, 0, static (_, _) => { }) + graph + .AddRasterPass("Survivor", C_FINAL, 0, static ( + _, + _ + ) => {}) .HasSideEffect(); RenderGraphCompileResult result = graph.Compile(); @@ -59,15 +73,24 @@ public void MutationScope_Uncommitted_RollsBackPassesResourcesAndOutputs() Assert.Equal(["Survivor"], PassNames(result.graph!)); Assert.Empty(result.graph!.textures); } + [Fact] public void Compile_SchedulesProducerBeforeConsumer() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle intermediate = graph.CreateTexture("Intermediate", ColorDescriptor()); RenderTextureHandle output = graph.CreateTexture("Output", ColorDescriptor()); - graph.AddRasterPass("Producer", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Producer", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(intermediate, 0, RenderLoadAction.Clear); - graph.AddRasterPass("Consumer", C_POST, 0, static (_, _) => { }) + graph + .AddRasterPass("Consumer", C_POST, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(output, 0, RenderLoadAction.Clear) .ReadTexture(intermediate); graph.MarkOutput(output); @@ -84,9 +107,17 @@ public void Compile_CullsUnconsumedPass() RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle unused = graph.CreateTexture("Unused", ColorDescriptor()); RenderTextureHandle output = graph.CreateTexture("Output", ColorDescriptor()); - graph.AddRasterPass("Unused Pass", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Unused Pass", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(unused, 0, RenderLoadAction.Clear); - graph.AddRasterPass("Output Pass", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Output Pass", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(output, 0, RenderLoadAction.Clear); graph.MarkOutput(output); @@ -102,7 +133,11 @@ public void Compile_WithUninitializedRead_FailsClearly() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle input = graph.CreateTexture("Input", SampledDescriptor()); - graph.AddRasterPass("Reader", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("Reader", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) .ReadTexture(input) .HasSideEffect(); @@ -122,14 +157,24 @@ public void Compile_WithReadWriteDeclaredAsSeparateAccess_FailsHazardValidation( 64, 64, RenderTextureFormat.RGBA16Float, - RenderTextureUsage.Storage | RenderTextureUsage.Sampled)); - graph.AddComputePass("Hazard", C_PROCESS, 0, static (_, _) => { }) + RenderTextureUsage.Storage | RenderTextureUsage.Sampled + ) + ); + graph + .AddComputePass("Hazard", C_PROCESS, 0, static ( + _, + _ + ) => {}) .ReadTexture(texture); ComputePassBuilder writer = graph.AddComputePass( "Writer", C_PROCESS, 0, - static (_, _) => { }); + static ( + _, + _ + ) => {} + ); writer.WriteStorageTexture(texture); writer.ReadTexture(texture); writer.HasSideEffect(); @@ -149,15 +194,31 @@ public void Compile_ReusesCompatibleNonOverlappingTextures() RenderTextureHandle second = graph.CreateTexture("Second", ColorDescriptor()); RenderTextureHandle output = graph.CreateTexture("Output", ColorDescriptor()); - graph.AddRasterPass("A", C_GEOMETRY, 0, static (_, _) => { }) + graph + .AddRasterPass("A", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(first, 0, RenderLoadAction.Clear); - graph.AddRasterPass("B", C_PROCESS, 0, static (_, _) => { }) + graph + .AddRasterPass("B", C_PROCESS, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(middle, 0, RenderLoadAction.Clear) .ReadTexture(first); - graph.AddRasterPass("C", C_TRANSPARENT, 0, static (_, _) => { }) + graph + .AddRasterPass("C", C_TRANSPARENT, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(second, 0, RenderLoadAction.Clear) .ReadTexture(middle); - graph.AddRasterPass("D", C_POST, 0, static (_, _) => { }) + graph + .AddRasterPass("D", C_POST, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(output, 0, RenderLoadAction.Clear) .ReadTexture(second); graph.MarkOutput(output); @@ -171,8 +232,14 @@ public void Compile_ReusesCompatibleNonOverlappingTextures() public void Compile_WhenViewLimitExceeded_FailsClearly() { RenderGraphBuilder graph = new(1, CreateCapabilities(maxViews: 1)); - graph.AddRasterPass("A", C_GEOMETRY, 0, static (_, _) => { }).HasSideEffect(); - graph.AddRasterPass("B", C_TRANSPARENT, 0, static (_, _) => { }).HasSideEffect(); + graph.AddRasterPass("A", C_GEOMETRY, 0, static ( + _, + _ + ) => {}).HasSideEffect(); + graph.AddRasterPass("B", C_TRANSPARENT, 0, static ( + _, + _ + ) => {}).HasSideEffect(); RenderGraphCompileResult result = graph.Compile(); @@ -186,9 +253,15 @@ public void Compile_WithPhaseCycle_FailsClearly() RenderPhaseId left = new("tests.left"); RenderPhaseId right = new("tests.right"); RenderGraphBuilder graph = CreateGraph(); - RenderPassBuilder leftPass = graph.AddRasterPass("Left", left, 0, static (_, _) => { }); + RenderPassBuilder leftPass = graph.AddRasterPass("Left", left, 0, static ( + _, + _ + ) => {}); leftPass.Before(right).HasSideEffect(); - RenderPassBuilder rightPass = graph.AddRasterPass("Right", right, 0, static (_, _) => { }); + RenderPassBuilder rightPass = graph.AddRasterPass("Right", right, 0, static ( + _, + _ + ) => {}); rightPass.Before(left).HasSideEffect(); RenderGraphCompileResult result = graph.Compile(); @@ -209,14 +282,15 @@ public void Compile_WithInvalidAttachmentSubresource_FailsClearly() RenderTextureFormat.RGBA16Float, RenderTextureUsage.ColorAttachment, mipCount: 2, - arrayLayers: 2)); - graph.AddRasterPass("Invalid Layer", C_GEOMETRY, 0, static (_, _) => { }) - .UseColorAttachment( - texture, - 0, - RenderLoadAction.Clear, - mipLevel: 1, - arrayLayer: 2); + arrayLayers: 2 + ) + ); + graph + .AddRasterPass("Invalid Layer", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) + .UseColorAttachment(texture, 0, RenderLoadAction.Clear, mipLevel: 1, arrayLayer: 2); graph.MarkOutput(texture); RenderGraphCompileResult result = graph.Compile(); @@ -231,12 +305,13 @@ public void Compile_WhenTextureUsageDoesNotMatchPassOperation_FailsClearly() RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle texture = graph.CreateTexture( "Not Storage", - new RenderTextureDescriptor( - 64, - 64, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled)); - graph.AddComputePass("Storage Writer", C_PROCESS, 0, static (_, _) => { }) + new RenderTextureDescriptor(64, 64, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled) + ); + graph + .AddComputePass("Storage Writer", C_PROCESS, 0, static ( + _, + _ + ) => {}) .WriteStorageTexture(texture) .HasSideEffect(); @@ -251,12 +326,12 @@ public void Compile_WhenStoredOutputIsDiscarded_FailsClearly() { RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle output = graph.CreateTexture("Discarded", ColorDescriptor()); - graph.AddRasterPass("Discard", C_FINAL, 0, static (_, _) => { }) - .UseColorAttachment( - output, - 0, - RenderLoadAction.Clear, - RenderStoreAction.Discard); + graph + .AddRasterPass("Discard", C_FINAL, 0, static ( + _, + _ + ) => {}) + .UseColorAttachment(output, 0, RenderLoadAction.Clear, RenderStoreAction.Discard); graph.MarkOutput(output); RenderGraphCompileResult result = graph.Compile(); @@ -271,20 +346,24 @@ public void Compile_WhenBufferCopyCapabilityIsMissing_FailsClearly() RenderGraphBuilder graph = CreateGraph(); RenderBufferHandle source = graph.CreateBuffer( "Source", - new RenderBufferDescriptor(16, 4, RenderBufferUsage.CopySource)); + new RenderBufferDescriptor(16, 4, RenderBufferUsage.CopySource) + ); RenderBufferHandle destination = graph.CreateBuffer( "Destination", - new RenderBufferDescriptor(16, 4, RenderBufferUsage.CopyDestination)); - graph.AddCopyPass("Copy", C_PROCESS, 0, static (_, _) => { }) + new RenderBufferDescriptor(16, 4, RenderBufferUsage.CopyDestination) + ); + graph + .AddCopyPass("Copy", C_PROCESS, 0, static ( + _, + _ + ) => {}) .CopyBuffer(source, destination) .HasSideEffect(); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_CAPABILITY_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_CAPABILITY_UNSUPPORTED"); } [Fact] @@ -292,23 +371,17 @@ public void Compile_WhenSampledFormatIsMissing_FailsClearly() { RenderGraphBuilder graph = new( 1, - CreateCapabilities( - maxViews: 64, - sampledFormats: [RenderTextureFormat.RGBA8])); + CreateCapabilities(maxViews: 64, sampledFormats: [RenderTextureFormat.RGBA8]) + ); _ = graph.CreateTexture( "Unsupported Sampled Format", - new RenderTextureDescriptor( - 8, - 8, - RenderTextureFormat.RGBA16Float, - RenderTextureUsage.Sampled)); + new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA16Float, RenderTextureUsage.Sampled) + ); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_FORMAT_SAMPLED_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_FORMAT_SAMPLED_UNSUPPORTED"); } [Fact] @@ -319,24 +392,20 @@ public void Compile_WhenTextureArrayCapabilityIsMissing_FailsClearly() CreateCapabilities( maxViews: 64, features: GraphicsCapability.Compute - | GraphicsCapability.StorageBuffer - | GraphicsCapability.StorageTexture - | GraphicsCapability.TextureBlit)); + | GraphicsCapability.StorageBuffer + | GraphicsCapability.StorageTexture + | GraphicsCapability.TextureBlit + ) + ); _ = graph.CreateTexture( "Unsupported Array", - new RenderTextureDescriptor( - 8, - 8, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Sampled, - arrayLayers: 2)); + new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, arrayLayers: 2) + ); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_TEXTURE_ARRAY_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_TEXTURE_ARRAY_UNSUPPORTED"); } [Fact] @@ -347,18 +416,19 @@ public void Compile_WhenUnsigned32BitIndexCapabilityIsMissing_FailsClearly() CreateCapabilities( maxViews: 64, features: GraphicsCapability.Compute - | GraphicsCapability.StorageBuffer - | GraphicsCapability.TextureBlit)); + | GraphicsCapability.StorageBuffer + | GraphicsCapability.TextureBlit + ) + ); _ = graph.CreateBuffer( "Unsupported Indices", - new RenderBufferDescriptor(3, sizeof(uint), RenderBufferUsage.Index)); + new RenderBufferDescriptor(3, sizeof(uint), RenderBufferUsage.Index) + ); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_INDEX32_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_INDEX32_UNSUPPORTED"); } [Fact] @@ -373,14 +443,14 @@ public void Compile_WhenVolumeTextureCapabilityIsMissing_FailsClearly() RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, dimension: RenderTextureDimension.Texture3D, - depth: 8)); + depth: 8 + ) + ); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_TEXTURE_3D_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_TEXTURE_3D_UNSUPPORTED"); } [Fact] @@ -392,7 +462,9 @@ public void Compile_WithSupportedVolumeAndCubemapTextures_Succeeds() maxViews: 64, features: GraphicsCapability.Texture3D | GraphicsCapability.TextureCubeArray, sampled3DFormats: [RenderTextureFormat.RGBA8], - sampledCubeFormats: [RenderTextureFormat.RGBA8])); + sampledCubeFormats: [RenderTextureFormat.RGBA8] + ) + ); _ = graph.CreateTexture( "Volume", new RenderTextureDescriptor( @@ -401,7 +473,9 @@ public void Compile_WithSupportedVolumeAndCubemapTextures_Succeeds() RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, dimension: RenderTextureDimension.Texture3D, - depth: 8)); + depth: 8 + ) + ); _ = graph.CreateTexture( "Cubemap Array", new RenderTextureDescriptor( @@ -410,7 +484,9 @@ public void Compile_WithSupportedVolumeAndCubemapTextures_Succeeds() RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled, arrayLayers: 2, - dimension: RenderTextureDimension.Cube)); + dimension: RenderTextureDimension.Cube + ) + ); Assert.True(graph.Compile().succeeded); } @@ -426,17 +502,21 @@ public void Compile_WhenMultisampleFormatCapabilityIsMissing_FailsClearly() 8, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment, - sampleCount: 4)); - graph.AddRasterPass("MSAA", C_GEOMETRY, 0, static (_, _) => { }) + sampleCount: 4 + ) + ); + graph + .AddRasterPass("MSAA", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(target, 0, RenderLoadAction.Clear); graph.MarkOutput(target); RenderGraphCompileResult result = graph.Compile(); Assert.False(result.succeeded); - Assert.Contains( - result.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_FORMAT_MSAA_UNSUPPORTED"); + Assert.Contains(result.diagnostics, diagnostic => diagnostic.code == "RENDER_GRAPH_FORMAT_MSAA_UNSUPPORTED"); } [Fact] @@ -444,20 +524,28 @@ public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() { RenderGraphBuilder readGraph = new( 1, - CreateCapabilities( - maxViews: 64, - storageReadFormats: [RenderTextureFormat.RGBA8], - storageWriteFormats: [])); + CreateCapabilities(maxViews: 64, storageReadFormats: [RenderTextureFormat.RGBA8], storageWriteFormats: []) + ); RenderTextureHandle readTexture = readGraph.CreateTexture( "Read Only", new RenderTextureDescriptor( 8, 8, RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Storage)); - readGraph.AddRasterPass("Initialize", C_GEOMETRY, 0, static (_, _) => { }) + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Storage + ) + ); + readGraph + .AddRasterPass("Initialize", C_GEOMETRY, 0, static ( + _, + _ + ) => {}) .UseColorAttachment(readTexture, 0, RenderLoadAction.Clear); - readGraph.AddComputePass("Read", C_PROCESS, 0, static (_, _) => { }) + readGraph + .AddComputePass("Read", C_PROCESS, 0, static ( + _, + _ + ) => {}) .ReadStorageTexture(readTexture) .HasSideEffect(); @@ -467,18 +555,17 @@ public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() RenderGraphBuilder writeGraph = new( 2, - CreateCapabilities( - maxViews: 64, - storageReadFormats: [], - storageWriteFormats: [RenderTextureFormat.RGBA8])); + CreateCapabilities(maxViews: 64, storageReadFormats: [], storageWriteFormats: [RenderTextureFormat.RGBA8]) + ); RenderTextureHandle writeTexture = writeGraph.CreateTexture( "Write Only", - new RenderTextureDescriptor( - 8, - 8, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Storage)); - writeGraph.AddComputePass("Write", C_PROCESS, 0, static (_, _) => { }) + new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Storage) + ); + writeGraph + .AddComputePass("Write", C_PROCESS, 0, static ( + _, + _ + ) => {}) .WriteStorageTexture(writeTexture) .HasSideEffect(); @@ -488,18 +575,17 @@ public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() RenderGraphBuilder readWriteGraph = new( 3, - CreateCapabilities( - maxViews: 64, - storageReadFormats: [], - storageWriteFormats: [RenderTextureFormat.RGBA8])); + CreateCapabilities(maxViews: 64, storageReadFormats: [], storageWriteFormats: [RenderTextureFormat.RGBA8]) + ); RenderTextureHandle readWriteTexture = readWriteGraph.CreateTexture( "Read Write", - new RenderTextureDescriptor( - 8, - 8, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Storage)); - readWriteGraph.AddComputePass("Read Write", C_PROCESS, 0, static (_, _) => { }) + new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Storage) + ); + readWriteGraph + .AddComputePass("Read Write", C_PROCESS, 0, static ( + _, + _ + ) => {}) .ReadWriteStorageTexture(readWriteTexture) .HasSideEffect(); @@ -508,18 +594,24 @@ public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() Assert.False(readWriteResult.succeeded); Assert.Contains( readWriteResult.diagnostics, - diagnostic => diagnostic.code == "RENDER_GRAPH_STORAGE_TEXTURE_ACCESS_UNSUPPORTED"); + diagnostic => diagnostic.code == "RENDER_GRAPH_STORAGE_TEXTURE_ACCESS_UNSUPPORTED" + ); } [Fact] public void Execute_WhenPassFails_StillEndsPassAndGraph() { RenderGraphBuilder graph = CreateGraph(); - graph.AddRasterPass( + graph + .AddRasterPass( "Failure", C_GEOMETRY, 0, - static (_, _) => throw new InvalidOperationException("failure")) + static ( + _, + _ + ) => throw new InvalidOperationException("failure") + ) .HasSideEffect(); CompiledRenderGraph compiled = graph.Compile().graph!; RecordingBackend backend = new(); @@ -543,12 +635,16 @@ RenderPassContext context int active = Interlocked.Increment(ref activeRecorders); int observed; while (active > (observed = Volatile.Read(ref maximumRecorders))) + { _ = Interlocked.CompareExchange(ref maximumRecorders, active, observed); + } if (drawCount <= 2 && Environment.ProcessorCount > 1) { parallelEntered.Signal(); - Assert.True(parallelEntered.Wait(TimeSpan.FromSeconds(30)), - "Both eligible callbacks must enter before either completes recording."); + Assert.True( + parallelEntered.Wait(TimeSpan.FromSeconds(30)), + "Both eligible callbacks must enter before either completes recording." + ); } context.commands.Draw(drawCount); _ = Interlocked.Decrement(ref activeRecorders); @@ -575,12 +671,16 @@ RenderPassContext context "Begin:Serial", "Draw:Serial:3", "End:Serial", "EndGraph" ], - backend.calls); + backend.calls + ); Assert.Equal( [RenderPassRecordingMode.Parallel, RenderPassRecordingMode.Parallel, RenderPassRecordingMode.Serial], - compiled.passes.Select(static pass => pass.recordingMode)); + compiled.passes.Select(static pass => pass.recordingMode) + ); if (Environment.ProcessorCount > 1) + { Assert.True(maximumRecorders > 1, "Parallel pass callbacks did not overlap."); + } } private static RenderGraphBuilder CreateGraph() => new(1, CreateCapabilities(64)); @@ -592,34 +692,36 @@ private static GraphicsCapabilities CreateCapabilities( IReadOnlyList? sampled3DFormats = null, IReadOnlyList? sampledCubeFormats = null, IReadOnlyList? storageReadFormats = null, - IReadOnlyList? storageWriteFormats = null) - => new( - GraphicsApi.Noop, - features - ?? (GraphicsCapability.Compute - | GraphicsCapability.StorageBuffer - | GraphicsCapability.StorageTexture - | GraphicsCapability.TextureBlit - | GraphicsCapability.Texture2DArray - | GraphicsCapability.Index32), - new GraphicsLimits(maxViews, 8, 16384, 16), - sampledFormats ?? Enum.GetValues(), - Enum.GetValues(), - storageReadFormats ?? - [RenderTextureFormat.RGBA8, RenderTextureFormat.RGBA16Float, RenderTextureFormat.R32Float], - storageWriteFormats ?? - [RenderTextureFormat.RGBA8, RenderTextureFormat.RGBA16Float, RenderTextureFormat.R32Float], - false, - false, - sampled3DFormats, - sampledCubeFormats); + IReadOnlyList? storageWriteFormats = null + ) => new( + GraphicsApi.Noop, + features + ?? (GraphicsCapability.Compute + | GraphicsCapability.StorageBuffer + | GraphicsCapability.StorageTexture + | GraphicsCapability.TextureBlit + | GraphicsCapability.Texture2DArray + | GraphicsCapability.Index32), + new GraphicsLimits(maxViews, 8, 16384, 16), + sampledFormats ?? Enum.GetValues(), + Enum.GetValues(), + storageReadFormats + ?? [RenderTextureFormat.RGBA8, RenderTextureFormat.RGBA16Float, RenderTextureFormat.R32Float], + storageWriteFormats + ?? [RenderTextureFormat.RGBA8, RenderTextureFormat.RGBA16Float, RenderTextureFormat.R32Float], + false, + false, + sampled3DFormats, + sampledCubeFormats + ); private static RenderTextureDescriptor ColorDescriptor() => new( 128, 128, RenderTextureFormat.RGBA16Float, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled); + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ); private static RenderTextureDescriptor SampledDescriptor() => new(128, 128, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled); @@ -661,70 +763,161 @@ internal EmptyEncoder(Action? onDraw = null) m_onDraw = onDraw; } - public override void BindGraphicsPipeline(GraphicsPipelineHandle pipeline) { } - public override void BindComputePipeline(ComputePipelineHandle pipeline) { } + public override void BindGraphicsPipeline(GraphicsPipelineHandle pipeline) {} + + public override void BindComputePipeline(ComputePipelineHandle pipeline) {} + public override void BindTexture( RenderBindingId binding, RenderTextureHandle texture, - RenderSamplerState sampler) { } + RenderSamplerState sampler + ) {} + public override void BindTexture( RenderBindingId binding, PersistentTextureHandle texture, - RenderSamplerState sampler) { } + RenderSamplerState sampler + ) {} + public override void BindStorageTexture( RenderBindingId binding, RenderTextureHandle texture, - int mipLevel = 0) { } + int mipLevel = 0 + ) {} + public override void BindStorageTexture( RenderBindingId binding, PersistentTextureHandle texture, - int mipLevel = 0) { } - public override void BindBuffer(RenderBindingId binding, RenderBufferHandle buffer) { } - public override void BindBuffer(RenderBindingId binding, PersistentBufferHandle buffer) { } - public override void SetUniform(RenderBindingId binding, ReadOnlySpan value) { } - public override void SetTransform(ReadOnlySpan columnMajorMatrix) { } - public override void SetRasterState(RenderRasterState state) { } - public override void SetStencil(RenderStencilState state) { } - public override void SetViewport(int x, int y, int width, int height) { } - public override void SetScissor(int x, int y, int width, int height) { } - public override void BindVertexBuffer(RenderBufferHandle buffer, int firstVertex = 0) { } - public override void BindVertexBuffer(PersistentBufferHandle buffer, int firstVertex = 0) { } - public override void BindIndexBuffer(RenderBufferHandle buffer, int firstIndex = 0) { } - public override void BindIndexBuffer(PersistentBufferHandle buffer, int firstIndex = 0) { } + int mipLevel = 0 + ) {} + + public override void BindBuffer( + RenderBindingId binding, + RenderBufferHandle buffer + ) {} + + public override void BindBuffer( + RenderBindingId binding, + PersistentBufferHandle buffer + ) {} + + public override void SetUniform( + RenderBindingId binding, + ReadOnlySpan value + ) {} + + public override void SetTransform(ReadOnlySpan columnMajorMatrix) {} + + public override void SetRasterState(RenderRasterState state) {} + + public override void SetStencil(RenderStencilState state) {} + + public override void SetViewport( + int x, + int y, + int width, + int height + ) {} + + public override void SetScissor( + int x, + int y, + int width, + int height + ) {} + + public override void BindVertexBuffer( + RenderBufferHandle buffer, + int firstVertex = 0 + ) {} + + public override void BindVertexBuffer( + PersistentBufferHandle buffer, + int firstVertex = 0 + ) {} + + public override void BindIndexBuffer( + RenderBufferHandle buffer, + int firstIndex = 0 + ) {} + + public override void BindIndexBuffer( + PersistentBufferHandle buffer, + int firstIndex = 0 + ) {} + public override void BindInstanceBuffer( RenderBufferHandle buffer, int firstInstance, - int instanceCount) { } + int instanceCount + ) {} + public override void BindInstanceBuffer( PersistentBufferHandle buffer, int firstInstance, - int instanceCount) { } - public override void Draw(int vertexCount, int instanceCount = 1) => m_onDraw?.Invoke(vertexCount); - public override void DrawProcedural(int vertexCount, int instanceCount = 1) { } - public override void DrawIndexed(int indexCount, int instanceCount = 1) { } + int instanceCount + ) {} + + public override void Draw( + int vertexCount, + int instanceCount = 1 + ) => m_onDraw?.Invoke(vertexCount); + + public override void DrawProcedural( + int vertexCount, + int instanceCount = 1 + ) {} + + public override void DrawIndexed( + int indexCount, + int instanceCount = 1 + ) {} + public override void DrawIndirect( RenderBufferHandle buffer, int firstCommand = 0, - int commandCount = 1) { } + int commandCount = 1 + ) {} + public override void DrawIndirect( PersistentBufferHandle buffer, int firstCommand = 0, - int commandCount = 1) { } - public override void Dispatch(int groupCountX, int groupCountY = 1, int groupCountZ = 1) { } + int commandCount = 1 + ) {} + + public override void Dispatch( + int groupCountX, + int groupCountY = 1, + int groupCountZ = 1 + ) {} + public override void DispatchIndirect( RenderBufferHandle buffer, int firstCommand = 0, - int commandCount = 1) { } + int commandCount = 1 + ) {} + public override void DispatchIndirect( PersistentBufferHandle buffer, int firstCommand = 0, - int commandCount = 1) { } - public override void CopyTexture(RenderTextureHandle source, RenderTextureHandle destination) { } + int commandCount = 1 + ) {} + + public override void CopyTexture( + RenderTextureHandle source, + RenderTextureHandle destination + ) {} + public override void BlitTexture( RenderTextureHandle source, RenderTextureRegion sourceRegion, RenderTextureHandle destination, - RenderTextureRegion destinationRegion) { } - public override void CopyBuffer(RenderBufferHandle source, RenderBufferHandle destination) { } + RenderTextureRegion destinationRegion + ) {} + + public override void CopyBuffer( + RenderBufferHandle source, + RenderBufferHandle destination + ) {} } } diff --git a/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs b/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs index 452bc6b05..5ad9b2bf4 100644 --- a/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs @@ -1,7 +1,7 @@ using System; using System.Linq; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -94,7 +94,9 @@ public void RollbackRemovesNameScopeWithoutLateDisposalRemovingAnotherScope() var graph = CreateGraph(); RenderGraphNameScope retired; using (graph.BeginMutationScope()) + { retired = graph.BeginNameScope("Retired"); + } using (graph.BeginNameScope("Current")) { retired.Dispose(); @@ -109,17 +111,28 @@ public void MutationCannotCloseAnEarlierNameScopeOrChangeItsPrefix() var graph = CreateGraph(); using RenderGraphNameScope name = graph.BeginNameScope("Accepted"); using (graph.BeginMutationScope()) + { Assert.Throws(() => name.Dispose()); + } graph.AddRasterPass("Visible", new("visible"), 0, Execute).HasSideEffect(); Assert.Equal("Accepted/Visible", Assert.Single(graph.Compile().graph!.passes).name); } private static RenderGraphBuilder CreateGraph() - => new(1, new GraphicsCapabilities( - GraphicsApi.Noop, GraphicsCapability.None, - new GraphicsLimits(64, 8, 16384, 16), - Enum.GetValues(), Enum.GetValues(), - [], [], false, false)); + => new( + 1, + new GraphicsCapabilities( + GraphicsApi.Noop, + GraphicsCapability.None, + new GraphicsLimits(64, 8, 16384, 16), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + false, + false + ) + ); [Fact] public void AcceptedFuturePhaseOrderingStillDetectsALaterCycleAndRollsBack() @@ -127,7 +140,9 @@ public void AcceptedFuturePhaseOrderingStillDetectsALaterCycleAndRollsBack() var graph = CreateGraph(); graph.AddRasterPass("First", new("first"), 0, Execute).HasSideEffect().Before(new("future")); using (RenderGraphMutationScope accepted = graph.BeginMutationScope()) + { accepted.Commit(); + } using (graph.BeginMutationScope()) { graph.AddRasterPass("Future", new("future"), 0, Execute).HasSideEffect().Before(new("first")); @@ -180,5 +195,5 @@ private static RenderTextureDescriptor Descriptor() private static void Execute( int payload, RenderPassContext context - ) { } + ) {} } diff --git a/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs b/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs index b53004218..177966bfd 100644 --- a/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs @@ -1,7 +1,7 @@ using System; using System.Linq; -using Inno.Rendering; using Xunit; +using Inno.Rendering; namespace Inno.Rendering.Tests; @@ -70,22 +70,31 @@ public void ValidationDoesNotInvokeCommandCallbacks() context ) => calls++).HasSideEffect(); for (int index = 0; index < 32; index++) + { Assert.True(graph.Validate().isValid); + } Assert.True(graph.Compile().succeeded); Assert.Equal(0, calls); } private static RenderGraphBuilder CreateGraph(int maxViews = 64) - => new(1, new GraphicsCapabilities( - GraphicsApi.Noop, - GraphicsCapability.None, - new GraphicsLimits(maxViews, 8, 16384, 16), - Enum.GetValues(), - Enum.GetValues(), - [], [], false, false)); + => new( + 1, + new GraphicsCapabilities( + GraphicsApi.Noop, + GraphicsCapability.None, + new GraphicsLimits(maxViews, 8, 16384, 16), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + false, + false + ) + ); private static void Execute( int payload, RenderPassContext context - ) { } + ) {} } diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs index 703082097..361bca9ae 100644 --- a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs @@ -36,10 +36,16 @@ public void AddRenderPasses( RenderGraphBuilder graph, ulong frameIndex ) { - graph.AddRasterPass("Collectible Callback", new RenderPhaseId("tests.collectible.contributor"), - 0, Encode).HasSideEffect(); + graph.AddRasterPass( + "Collectible Callback", + new RenderPhaseId("tests.collectible.contributor"), + 0, + Encode + ).HasSideEffect(); if (m_rejectGraph) + { throw new InvalidOperationException("Reject the collectible frame mutation."); + } } private void Encode( diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs index 026895e23..5097bd4d3 100644 --- a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs @@ -32,7 +32,11 @@ public override void Build(RenderPipelineContext context) "Reloadable Plugin Pass", new RenderPhaseId("tests.runtime.reloadable-plugin.visible"), 0, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); } } @@ -55,7 +59,11 @@ public override void AddRenderPasses(RenderFeatureContext context) "Reloadable Plugin Feature Pass", new RenderPhaseId("tests.runtime.reloadable-plugin-feature.visible"), 1, - static (_, _) => { }) + static ( + _, + _ + ) => {} + ) .HasSideEffect(); } } diff --git a/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs b/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs index 912415bac..5417a2abe 100644 --- a/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs +++ b/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs @@ -4,12 +4,12 @@ using System.Linq; using System.Reflection; using System.Runtime.Loader; -using Inno.Extensibility.Catalogs; -using Inno.Runtime; -using Inno.Runtime.Generators; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Xunit; +using Inno.Extensibility.Catalogs; +using Inno.Runtime; +using Inno.Runtime.Generators; namespace Inno.Runtime.Generators.Tests; @@ -34,9 +34,12 @@ public override void Write(Inno.Core.Serialization.SerializationWriter writer, B } """; string[] paths = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator); - CSharpCompilation input = CSharpCompilation.Create("Inno.InvalidStaticCatalogFixture", - [CSharpSyntaxTree.ParseText(source)], paths.Select(static path => MetadataReference.CreateFromFile(path)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + CSharpCompilation input = CSharpCompilation.Create( + "Inno.InvalidStaticCatalogFixture", + [CSharpSyntaxTree.ParseText(source)], + paths.Select(static path => MetadataReference.CreateFromFile(path)), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) + ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new RuntimeModuleCatalogGenerator().AsSourceGenerator()); driver.RunGeneratorsAndUpdateCompilation(input, out _, out var diagnostics); Diagnostic failure = Assert.Single(diagnostics, static diagnostic => diagnostic.Id == "INNORUN002"); @@ -95,10 +98,13 @@ public class RequiredBase { public required string name { get; init; } } public sealed class RequiredChild : RequiredBase { } """; string[] paths = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") - ?? throw new InvalidOperationException("The test host provides no platform closure.")).Split(Path.PathSeparator); - CSharpCompilation input = CSharpCompilation.Create("Inno.StaticCatalogFixture", - [CSharpSyntaxTree.ParseText(source)], paths.Select(static path => MetadataReference.CreateFromFile(path)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + ?? throw new InvalidOperationException("The test host provides no platform closure.")).Split(Path.PathSeparator); + CSharpCompilation input = CSharpCompilation.Create( + "Inno.StaticCatalogFixture", + [CSharpSyntaxTree.ParseText(source)], + paths.Select(static path => MetadataReference.CreateFromFile(path)), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) + ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new RuntimeModuleCatalogGenerator().AsSourceGenerator()); driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out var diagnostics); Assert.Empty(diagnostics.Where(static value => value.Severity == DiagnosticSeverity.Error)); @@ -119,9 +125,15 @@ public sealed class RequiredChild : RequiredBase { } Assert.Equal(derived.type, catalog.CreateInstance(derived.type).GetType()); Assert.Equal("Fixture.Base", Assert.Single(derived.baseTypes).FullName); Assert.Equal(typeof(int), Assert.Single(derived.interfaces).GenericTypeArguments[0]); - Attribute marker = Assert.Single(derived.inheritedAttributes, static attribute => attribute.GetType().Name == "MarkerAttribute"); + Attribute marker = Assert.Single( + derived.inheritedAttributes, + static attribute => attribute.GetType().Name == "MarkerAttribute" + ); Assert.Equal("derived", marker.GetType().GetProperty("name")!.GetValue(marker)); - Assert.Contains(derived.parameterlessOverrides, static slot => slot.name == "Tick" && slot.declaringBase.FullName == "Fixture.Base"); + Assert.Contains( + derived.parameterlessOverrides, + static slot => slot.name == "Tick" && slot.declaringBase.FullName == "Fixture.Base" + ); Assert.False(catalog.CanCreateInstance(assembly.GetType("Fixture.RequiredChild", throwOnError: true)!)); Assert.False(catalog.CanCreateInstance(assembly.GetType("Fixture.Generic`1+Nested", throwOnError: true)!)); Type generic = assembly.GetType("Fixture.Generic`1", throwOnError: true)!; diff --git a/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeSubsystemGeneratorTests.cs b/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeSubsystemGeneratorTests.cs index 6f87a5d61..5039c857b 100644 --- a/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeSubsystemGeneratorTests.cs +++ b/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeSubsystemGeneratorTests.cs @@ -1,11 +1,11 @@ using System; using System.IO; using System.Linq; -using Inno.Runtime.Contracts; -using Inno.Runtime.Generators; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Xunit; +using Inno.Runtime.Contracts; +using Inno.Runtime.Generators; namespace Inno.Runtime.Generators.Tests; @@ -52,7 +52,8 @@ public static class AddedEngineModule [Fact] public void DuplicateStableIdsFailDuringCompilation() { - (_, GeneratorDriverRunResult result) = Generate(C_CATALOG + """ + (_, GeneratorDriverRunResult result) = Generate( + C_CATALOG + """ public static class DuplicateModule { @@ -61,22 +62,27 @@ public static class DuplicateModule [RuntimeSubsystemRegistration("same")] public static IRuntimeSubsystemFactory Second(HostInputs context) => throw new InvalidOperationException(); } - """); - Assert.Contains(result.Diagnostics, static diagnostic => diagnostic.Id == "INNORUN001" && - diagnostic.GetMessage().Contains("duplicated", StringComparison.Ordinal)); + """ + ); + Assert.Contains(result.Diagnostics, static diagnostic => ( + diagnostic.Id == "INNORUN001" + && diagnostic.GetMessage().Contains("duplicated", StringComparison.Ordinal) + )); } [Fact] public void InvalidFactoryBoundaryFailsInsteadOfBeingSilentlyDiscovered() { - (_, GeneratorDriverRunResult result) = Generate(C_CATALOG + """ + (_, GeneratorDriverRunResult result) = Generate( + C_CATALOG + """ public static class InvalidModule { [RuntimeSubsystemRegistration("invalid")] public static object Create(HostInputs context) => new object(); } - """); + """ + ); Assert.Contains(result.Diagnostics, static diagnostic => diagnostic.Id == "INNORUN001"); } @@ -92,11 +98,17 @@ public static class AudioModule } """; (Compilation compilation, GeneratorDriverRunResult result) = Generate(source); - Assert.Empty(compilation.GetDiagnostics().Where(static diagnostic => - diagnostic.Severity is DiagnosticSeverity.Error or DiagnosticSeverity.Warning)); + Assert.Empty( + compilation.GetDiagnostics().Where(static diagnostic => ( + diagnostic.Severity is DiagnosticSeverity.Error or DiagnosticSeverity.Warning + )) + ); Assert.Empty(result.Diagnostics); - Assert.Contains("Create(inputs)", Assert.Single(Assert.Single(result.Results).GeneratedSources).SourceText.ToString(), - StringComparison.Ordinal); + Assert.Contains( + "Create(inputs)", + Assert.Single(Assert.Single(result.Results).GeneratedSources).SourceText.ToString(), + StringComparison.Ordinal + ); } [Theory] @@ -104,8 +116,10 @@ public static class AudioModule [InlineData("public static partial class Catalog", "public static partial class Catalog")] [InlineData("Build(HostInputs context)", "Build(HostInputs context)")] [InlineData("Build(HostInputs context)", "Build(ref HostInputs context)")] - public void UnsupportedCatalogShapeProducesAnExplicitDiagnostic(string original, string replacement) - { + public void UnsupportedCatalogShapeProducesAnExplicitDiagnostic( + string original, + string replacement + ) { (_, GeneratorDriverRunResult result) = Generate(C_CATALOG.Replace(original, replacement, StringComparison.Ordinal)); Assert.Contains(result.Diagnostics, static diagnostic => diagnostic.Id == "INNORUN001"); Assert.Empty(Assert.Single(result.Results).GeneratedSources); @@ -116,10 +130,15 @@ private static (Compilation, GeneratorDriverRunResult) Generate(string source) string[] platformAssemblies = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? throw new InvalidOperationException("The test host has no platform assembly list.")).Split(Path.PathSeparator); MetadataReference[] references = platformAssemblies.Append(typeof(IRuntimeSubsystem).Assembly.Location) - .Distinct(StringComparer.Ordinal).Select(static path => MetadataReference.CreateFromFile(path)).ToArray(); - CSharpCompilation input = CSharpCompilation.Create("GeneratedCompositionTests", - [CSharpSyntaxTree.ParseText(source)], references, - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + .Distinct(StringComparer.Ordinal) + .Select(static path => MetadataReference.CreateFromFile(path)) + .ToArray(); + CSharpCompilation input = CSharpCompilation.Create( + "GeneratedCompositionTests", + [CSharpSyntaxTree.ParseText(source)], + references, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new RuntimeSubsystemGenerator().AsSourceGenerator()); driver = driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out _); return (output, driver.GetRunResult()); diff --git a/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs b/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs index 41647eb6b..ea69ab618 100644 --- a/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs +++ b/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs @@ -3,14 +3,14 @@ using System.Linq; using System.Reflection; using System.Runtime.Loader; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Core.Serialization; using Inno.Core.Serialization.Generators; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Xunit; namespace Inno.Runtime.Generators.Tests; @@ -55,7 +55,10 @@ public sealed class Child : Parent { private Child() {} } { lifetime.LoadFromStream(new MemoryStream(parent)); Assembly assembly = lifetime.LoadFromStream(new MemoryStream(child)); - Type catalog = assembly.GetType("Inno.SerializationChildFixture.Generated.RuntimeSerializationMetadataCatalog", throwOnError: true)!; + Type catalog = assembly.GetType( + "Inno.SerializationChildFixture.Generated.RuntimeSerializationMetadataCatalog", + throwOnError: true + )!; var register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! .CreateDelegate>>(); var source = new StaticSerializationMetadataSource([register]); @@ -160,9 +163,12 @@ public static bool Run(SerializationRegistry serialization) """; string[] references = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? throw new InvalidOperationException("The test host supplies no platform references.")).Split(Path.PathSeparator); - CSharpCompilation input = CSharpCompilation.Create("Inno.SerializationMetadataFixture", - [CSharpSyntaxTree.ParseText(source)], references.Select(static path => MetadataReference.CreateFromFile(path)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + CSharpCompilation input = CSharpCompilation.Create( + "Inno.SerializationMetadataFixture", + [CSharpSyntaxTree.ParseText(source)], + references.Select(static path => MetadataReference.CreateFromFile(path)), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) + ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new SerializationMetadataGenerator().AsSourceGenerator()); driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out var diagnostics); Assert.Empty(diagnostics.Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)); @@ -174,16 +180,21 @@ public static bool Run(SerializationRegistry serialization) try { Assembly assembly = lifetime.LoadFromStream(stream); - Type catalog = assembly.GetType("Inno.SerializationMetadataFixture.Generated.RuntimeSerializationMetadataCatalog", throwOnError: true)!; + Type catalog = assembly.GetType( + "Inno.SerializationMetadataFixture.Generated.RuntimeSerializationMetadataCatalog", + throwOnError: true + )!; var register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! .CreateDelegate>>(); var metadata = new StaticSerializationMetadataSource([register]); using var modules = new ModuleHost(new ModuleHostOptions { - catalogSource = new DotNetAssemblyCatalogSource(assembly) }); + catalogSource = new DotNetAssemblyCatalogSource(assembly) + }); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var serialization = new SerializationRegistry(types, metadata); - var run = assembly.GetType("Fixture.Scenario", throwOnError: true)!.GetMethod("Run")! + var run = assembly.GetType("Fixture.Scenario", throwOnError: true)! + .GetMethod("Run")! .CreateDelegate>(); Assert.True(run(serialization)); Assert.Throws(() => metadata.GetMetadata(typeof(DateTime))); @@ -267,8 +278,10 @@ public static class Owner { private sealed class State : ISerializable {} } """, []); GeneratorDriver driver = CSharpGeneratorDriver.Create(new SerializationMetadataGenerator().AsSourceGenerator()); driver.RunGeneratorsAndUpdateCompilation(input, out _, out var diagnostics); - Assert.Contains(diagnostics, static diagnostic => diagnostic.Id == "INNOSER012" - && diagnostic.Severity == DiagnosticSeverity.Error); + Assert.Contains(diagnostics, static diagnostic => ( + diagnostic.Id == "INNOSER012" + && diagnostic.Severity == DiagnosticSeverity.Error + )); } [Fact] @@ -287,16 +300,21 @@ private static void AssertScenario(string source) try { Assembly assembly = lifetime.LoadFromStream(new MemoryStream(bytes)); - Type catalog = assembly.GetType("Inno.PrivateSerializationFixture.Generated.RuntimeSerializationMetadataCatalog", throwOnError: true)!; + Type catalog = assembly.GetType( + "Inno.PrivateSerializationFixture.Generated.RuntimeSerializationMetadataCatalog", + throwOnError: true + )!; var register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! .CreateDelegate>>(); var metadata = new StaticSerializationMetadataSource([register]); using var modules = new ModuleHost(new ModuleHostOptions { - catalogSource = new DotNetAssemblyCatalogSource(assembly) }); + catalogSource = new DotNetAssemblyCatalogSource(assembly) + }); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var serialization = new SerializationRegistry(types, metadata); - var run = assembly.GetType("Fixture.Scenario", throwOnError: true)!.GetMethod("Run")! + var run = assembly.GetType("Fixture.Scenario", throwOnError: true)! + .GetMethod("Run")! .CreateDelegate>(); Assert.True(run(serialization)); } @@ -313,9 +331,12 @@ MetadataReference[] additionalReferences ) { string[] references = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? throw new InvalidOperationException("The test host supplies no platform references.")).Split(Path.PathSeparator); - return CSharpCompilation.Create(assemblyName, [CSharpSyntaxTree.ParseText(source)], + return CSharpCompilation.Create( + assemblyName, + [CSharpSyntaxTree.ParseText(source)], references.Select(static path => MetadataReference.CreateFromFile(path)).Concat(additionalReferences), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) + ); } private static byte[] Compile( @@ -324,8 +345,11 @@ private static byte[] Compile( MetadataReference[] additionalReferences ) { GeneratorDriver driver = CSharpGeneratorDriver.Create(new SerializationMetadataGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(CreateCompilation(assemblyName, source, additionalReferences), - out Compilation output, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation( + CreateCompilation(assemblyName, source, additionalReferences), + out Compilation output, + out var diagnostics + ); Assert.Empty(diagnostics.Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)); using var stream = new MemoryStream(); var emitted = output.Emit(stream); diff --git a/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs b/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs index 92862f83e..66cc5ae0b 100644 --- a/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs @@ -1,21 +1,21 @@ using System; using System.Collections.Generic; +using Xunit; using Inno.Adapter; -using Inno.Adapter.Platform; +using Inno.Adapter.Audio; using Inno.Adapter.Input; +using Inno.Adapter.Platform; +using Inno.Adapter.Presentation; +using Inno.Adapter.Rendering; using Inno.Adapter.Storage; -using Inno.Adapter.Audio; using Inno.Adapter.Text; -using Inno.Adapter.Rendering; using Inno.Adapter.UI; -using Inno.Adapter.Presentation; +using Inno.Audio; using Inno.Platform; +using Inno.Rendering; using Inno.Storage; -using Inno.Audio; using Inno.Text; -using Inno.Rendering; using Inno.UI; -using Xunit; namespace Inno.Runtime.Tests; @@ -105,8 +105,7 @@ public void CapturedRegistrationsCannotBeChangedByTheirSourceCollection() Assert.Throws(() => catalog.CreateStorage(first.id, new StorageScope("application"))); Assert.Equal(1, first.creationCount); Assert.Equal(0, second.creationCount); - Assert.Throws(() => - ((IList)catalog.supportedBackends).Add(second.id)); + Assert.Throws(() => ((IList)catalog.supportedBackends).Add(second.id)); } [Fact] @@ -150,7 +149,8 @@ public TestCatalog() ui = new UiBackendCatalog([m_ui]); } - public AdapterSelection selection => new() + public AdapterSelection selection + => new() { platform = m_platform.id, input = m_input.id, @@ -161,7 +161,14 @@ public TestCatalog() ui = m_ui.id }; - public int creationCount => m_platform.creationCount + m_input.creationCount + m_storage.creationCount + m_audio.creationCount + m_text.creationCount + m_rendering.creationCount + m_ui.creationCount; + public int creationCount + => m_platform.creationCount + + m_input.creationCount + + m_storage.creationCount + + m_audio.creationCount + + m_text.creationCount + + m_rendering.creationCount + + m_ui.creationCount; public IPlatformBackendFactory platform { get; } public IInputBackendFactory input { get; } @@ -174,7 +181,8 @@ public TestCatalog() private sealed class TestPlatformProvider : PlatformBackendProvider { - public TestPlatformProvider(PlatformBackendId id) : base(id) { } + public TestPlatformProvider(PlatformBackendId id) + : base(id) {} public int creationCount { get; private set; } @@ -187,7 +195,8 @@ public override IPlatformApplication CreateApplication() private sealed class TestInputProvider : InputBackendProvider { - public TestInputProvider(InputBackendId id) : base(id) { } + public TestInputProvider(InputBackendId id) + : base(id) {} public int creationCount { get; private set; } @@ -202,7 +211,8 @@ bool acceptAllWindows private sealed class TestStorageProvider : StorageBackendProvider { - public TestStorageProvider(StorageBackendId id) : base(id) { } + public TestStorageProvider(StorageBackendId id) + : base(id) {} public int creationCount { get; private set; } @@ -215,7 +225,8 @@ public override IApplicationStorage CreateStorage(StorageScope scope) private sealed class TestAudioProvider : AudioBackendProvider { - public TestAudioProvider(AudioBackendId id) : base(id) { } + public TestAudioProvider(AudioBackendId id) + : base(id) {} public int creationCount { get; private set; } @@ -228,7 +239,8 @@ public override IAudioDevice CreateDevice(AudioBackendOptions options) private sealed class TestTextProvider : TextBackendProvider { - public TestTextProvider(TextBackendId id) : base(id) { } + public TestTextProvider(TextBackendId id) + : base(id) {} public int creationCount { get; private set; } @@ -241,7 +253,8 @@ public override ITextBackend CreateBackend() private sealed class TestRenderingProvider : RenderingBackendProvider { - public TestRenderingProvider(RenderingBackendId id) : base(id) { } + public TestRenderingProvider(RenderingBackendId id) + : base(id) {} public int creationCount { get; private set; } @@ -257,7 +270,8 @@ public override IRenderLayerCompositionProgramProvider CreateCompositionProgramP private sealed class TestUiProvider : UiBackendProvider { - public TestUiProvider(UiBackendId id) : base(id) { } + public TestUiProvider(UiBackendId id) + : base(id) {} public int creationCount { get; private set; } @@ -270,7 +284,8 @@ public override IUiBackend CreateBackend() private sealed class TestPresentationProvider : PresentationBackendProvider { - public TestPresentationProvider(PresentationBackendId id) : base(id) { } + public TestPresentationProvider(PresentationBackendId id) + : base(id) {} public int creationCount { get; private set; } @@ -281,4 +296,3 @@ public override IPresentationContext CreateContext(PresentationBackendOptions op } } } - diff --git a/tests/runtime/Inno.Runtime.Tests/AssemblyClassificationTests.cs b/tests/runtime/Inno.Runtime.Tests/AssemblyClassificationTests.cs index 400122481..54060da25 100644 --- a/tests/runtime/Inno.Runtime.Tests/AssemblyClassificationTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/AssemblyClassificationTests.cs @@ -4,8 +4,8 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; -using Inno.Extensibility.Modules; using Xunit; +using Inno.Extensibility.Modules; namespace Inno.Runtime.Tests; @@ -16,8 +16,13 @@ public async Task IndependentModuleHostsCanPublishTheSameStaticAssemblyConcurren { // A separate linked instance keeps the test host's own classification unchanged. Assembly assembly = Assembly.Load(File.ReadAllBytes(typeof(AssemblyClassificationTests).Assembly.Location)); - var source = new StaticModuleSource("Shared", AssemblyDomain.InnoScripting, - AssemblyScope.Runtime, [assembly], []); + var source = new StaticModuleSource( + "Shared", + AssemblyDomain.InnoScripting, + AssemblyScope.Runtime, + [assembly], + [] + ); const int workerCount = 8; using var ready = new Barrier(workerCount); Task[] workers = Enumerable.Range(0, workerCount).Select(workerIndex => Task.Factory.StartNew( @@ -40,7 +45,8 @@ public async Task IndependentModuleHostsCanPublishTheSameStaticAssemblyConcurren }, CancellationToken.None, TaskCreationOptions.LongRunning, - TaskScheduler.Default)).ToArray(); + TaskScheduler.Default + )).ToArray(); await Task.WhenAll(workers).WaitAsync(TimeSpan.FromSeconds(30)); } } diff --git a/tests/runtime/Inno.Runtime.Tests/GamePresentationSettingsTests.cs b/tests/runtime/Inno.Runtime.Tests/GamePresentationSettingsTests.cs index bd12dfe6f..ea49267d9 100644 --- a/tests/runtime/Inno.Runtime.Tests/GamePresentationSettingsTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/GamePresentationSettingsTests.cs @@ -1,13 +1,12 @@ -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; - -using Inno.Core.Settings; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Core.IO; using Inno.Core.Serialization; +using Inno.Core.Settings; using Inno.Runtime; -using Xunit; namespace Inno.Runtime.Tests; @@ -49,27 +48,29 @@ public void PresentationRejectsInvalidReferenceResolution() [Fact] public void RuntimeHostRegistersDefaultPresentationProjectSetting() { - string directory = Path.Combine( - Path.GetTempPath(), - "InnoGamePresentationTests", - Guid.NewGuid().ToString("N")); + string directory = Path.Combine(Path.GetTempPath(), "InnoGamePresentationTests", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory); try { using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(GamePresentationSettingsTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(GamePresentationSettingsTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); using var settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.GetFullPath(Path.Combine(directory, "Settings.Project.inno"))), host.types, host.serialization, new ProjectId("tests.runtime"), - SerializationContext.empty); + SerializationContext.empty + ); settings.RebuildCurrent(); GamePresentationSettings presentation = settings.Get( - GamePresentationSettings.settingId); + GamePresentationSettings.settingId + ); Assert.True(presentation.preserveAspectRatio); Assert.Equal(1280, presentation.referenceWidth); diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs b/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs index 54396f6c3..68642f713 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs @@ -1,9 +1,10 @@ using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Adapter; using Inno.Adapter.Audio; using Inno.Adapter.Input; @@ -23,7 +24,6 @@ using Inno.Player.Runtime; using Inno.Shell; using Inno.Storage; -using Xunit; namespace Inno.Runtime.Tests; @@ -53,33 +53,49 @@ public async Task PreparedContentIsCheckedAndRetiredBeforeAnyPlatformAdapterStar }; PlayerContentMetadata metadata; using (EngineHost metadataOwner = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(PlayerContentSourceTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(PlayerContentSourceTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .Build()) using (SerializationGeneration serialization = metadataOwner.serialization.CaptureGeneration()) { string hash = new string('A', 64); - metadata = new PlayerContentMetadata(RuntimeManifestEnvelope.Encode(manifest, serialization), + metadata = new PlayerContentMetadata( + RuntimeManifestEnvelope.Encode(manifest, serialization), serialization.Serialize(new RuntimeContentCatalog { - contentHash = hash, packFileName = $"content-{hash}.pack", - snapshotFingerprint = hash, runtimeAssemblyCount = 1 - })); + contentHash = hash, + packFileName = $"content-{hash}.pack", + snapshotFingerprint = hash, + runtimeAssemblyCount = 1 + }) + ); } using var cancellation = new CancellationTokenSource(); var source = new PreparedSource(metadata, failure, cancellation); var modules = new DotNetAssemblyCatalogSource(typeof(PlayerContentSourceTests).Assembly); - var activator = new StaticPlayerModuleActivator(GameCodeDeployment.FromManifest(manifest.modules), + var activator = new StaticPlayerModuleActivator( + GameCodeDeployment.FromManifest(manifest.modules), new Dictionary> { ["Game"] = [typeof(PlayerContentSourceTests).Assembly] - }); + } + ); PlayerLaunchOptions options = CreateOptions(modules, source, activator); if (failure == "missing") + { await Assert.ThrowsAsync(() => PlayerApplication.RunAsync(options, cancellation.Token)); + } else if (failure == "mismatch") + { await Assert.ThrowsAsync(() => PlayerApplication.RunAsync(options, cancellation.Token)); + } else + { await Assert.ThrowsAnyAsync(() => PlayerApplication.RunAsync(options, cancellation.Token)); + } Assert.Equal(1, source.preparations); Assert.Equal(failure == "missing" ? 0 : 1, source.store?.disposals ?? 0); Assert.Throws(() => modules.GetAssemblies()); @@ -102,16 +118,19 @@ public void MetadataCopiesBothDocumentsBeforeTheBorrowedSourceCanReuseItsBuffers [Theory] [InlineData(false)] [InlineData(true)] - public async Task MetadataFailureRetiresTheTransferredModuleOwnerBeforeAnyAdapterOrContentPreparation( - bool malformed - ) { + public async Task MetadataFailureRetiresTheTransferredModuleOwnerBeforeAnyAdapterOrContentPreparation(bool malformed) + { var source = new MemorySource { malformed = malformed }; var modules = new DotNetAssemblyCatalogSource(typeof(PlayerContentSourceTests).Assembly); PlayerLaunchOptions options = CreateOptions(modules, source); if (malformed) + { await Assert.ThrowsAsync(() => PlayerApplication.RunAsync(options)); + } else + { await Assert.ThrowsAsync(() => PlayerApplication.RunAsync(options)); + } Assert.Equal(1, source.metadataReads); Assert.Equal(0, source.preparations); Assert.Throws(() => modules.GetAssemblies()); @@ -144,8 +163,10 @@ private static PlayerLaunchOptions CreateOptions( adapters = new RejectedAdapterCatalog(), contentSource = source, createStorage = _ => throw new InvalidOperationException("Storage must not start before content validation."), - moduleActivator = activator ?? new StaticPlayerModuleActivator(new GameCodeDeployment([]), - new Dictionary>()), + moduleActivator = activator ?? new StaticPlayerModuleActivator( + new GameCodeDeployment([]), + new Dictionary>() + ), frameDriver = new PollingShellFrameDriver(), logDeliveryMode = LogDeliveryMode.Inline }; @@ -171,10 +192,14 @@ public ValueTask PrepareAsync( preparations++; Assert.Equal("tests.memory", scope.value); if (failure == "missing") + { return ValueTask.FromResult(null!); + } store = new PreparedStore(failure == "mismatch" ? null : pack); if (failure == "canceled") + { cancellation.Cancel(); + } return ValueTask.FromResult(store); } } @@ -186,7 +211,9 @@ private sealed class PreparedStore(ContentPackDescriptor? expected) : IRuntimeCo public ContentPackDescriptor descriptor => expected ?? m_content.descriptor; public ContentPackIndex index => m_content.index; + public ContentReadLease Acquire(ContentKey key) => m_content.Acquire(key); + public void Dispose() { disposals++; @@ -204,8 +231,8 @@ public ValueTask ReadMetadataAsync(CancellationToken canc { metadataReads++; return malformed - ? ValueTask.FromResult(new PlayerContentMetadata([1], [2])) - : ValueTask.FromException(new IOException("Metadata unavailable.")); + ? ValueTask.FromResult(new PlayerContentMetadata([1], [2])) + : ValueTask.FromException(new IOException("Metadata unavailable.")); } public ValueTask PrepareAsync( diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs index 39ad3f760..ea5ae0cfb 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Adapter; using Inno.Adapter.Audio; using Inno.Adapter.Input; @@ -19,7 +20,6 @@ using Inno.Storage; using Inno.Text; using Inno.UI; -using Xunit; namespace Inno.Runtime.Tests; @@ -29,11 +29,13 @@ private sealed class MemoryAdapters : IAdapterCatalog, IPlatformBackendFactory, IRenderingBackendFactory, IStorageBackendFactory, IAudioBackendFactory, ITextBackendFactory, IUiBackendFactory { private readonly MemoryRenderDevice m_render; + public MemoryAdapters(bool failFrame) { application = new MemoryApplication(retired); m_render = new MemoryRenderDevice(retired, failFrame); } + internal int completedFrames => m_render.completedFrames; public MemoryApplication application { get; } public List retired { get; } = []; @@ -51,26 +53,34 @@ public MemoryAdapters(bool failFrame) IReadOnlyList IAudioBackendFactory.supportedBackends => [AudioBackendId.miniAudio]; IReadOnlyList ITextBackendFactory.supportedBackends => [TextBackendId.freeTypeHarfBuzz]; IReadOnlyList IUiBackendFactory.supportedBackends => [UiBackendId.rmlUi]; + public IPlatformApplication CreateApplication(PlatformBackendId backend) => application; + public IInputEventSource CreateEventSource( InputBackendId backend, IPlatformWindow window, bool acceptAllWindows ) => new MemoryInputSource(retired); + public IRenderDevice CreateDevice( RenderingBackendId backend, RenderingBackendOptions options ) => m_render; + public IApplicationStorage CreateStorage( StorageBackendId backend, StorageScope scope ) => new MemoryStorage(); + public IAudioDevice CreateDevice( AudioBackendId backend, AudioBackendOptions options = default ) => new MutedAudioDevice(); + public ITextBackend CreateBackend(TextBackendId backend) => new MemoryText(retired); + public IUiBackend CreateBackend(UiBackendId backend) => new MemoryUi(retired); + public IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider(RenderingBackendId backend) => new UnusedCompositionPrograms(); } @@ -80,15 +90,29 @@ private sealed class MemoryApplication(List retired) : IPlatformApplicat private Action? m_redraw; public Queue events { get; } = new(); public int redrawSubscribers { get; private set; } + public event Action? redrawRequested { - add { m_redraw += value; redrawSubscribers++; } - remove { m_redraw -= value; redrawSubscribers--; } + add + { + m_redraw += value; + redrawSubscribers++; + } + remove + { + m_redraw -= value; + redrawSubscribers--; + } } + public IPlatformWindow CreateWindow(PlatformWindowOptions options) => new MemoryWindow(retired); + public bool PollEvent(out Event? evnt) => events.TryDequeue(out evnt); + public IReadOnlyList GetWindows() => []; + public void RequestRedraw() => m_redraw?.Invoke(1); + public void Dispose() => retired.Add("platform"); } @@ -102,15 +126,20 @@ private sealed class MemoryWindow(List retired) : IPlatformWindow public int pixelHeight => 32; public bool isClosed { get; private set; } public bool isFocused => true; + public void RequestClose() => isClosed = true; + public void Dispose() => retired.Add("window"); } private sealed class MemoryInputSource(List retired) : IInputEventSource { private readonly EventInputSource m_source = new(1); + public IInputBackend CreateBackend() => m_source.CreateBackend(); + public void ProcessEvent(Event evnt) => m_source.ProcessEvent(evnt); + public void Dispose() { m_source.Dispose(); @@ -125,12 +154,25 @@ bool failFrame { private bool m_rejectedFrame; internal int completedFrames; - public GraphicsCapabilities capabilities { get; } = new(GraphicsApi.Noop, GraphicsCapability.None, - new GraphicsLimits(64, 4, 4096, 0), [RenderTextureFormat.RGBA8], [RenderTextureFormat.RGBA8], [], [], false, false); + + public GraphicsCapabilities capabilities { get; } = new( + GraphicsApi.Noop, + GraphicsCapability.None, + new GraphicsLimits(64, 4, 4096, 0), + [RenderTextureFormat.RGBA8], + [RenderTextureFormat.RGBA8], + [], + [], + false, + false + ); + public uint generation => 1; public RenderPresentationSize? primaryPresentationSize { get; private set; } public bool primaryPresentationEncodesSrgb => true; - public void SetVerticalSync(bool enabled) { } + + public void SetVerticalSync(bool enabled) {} + public void BeginFrame() { if (failFrame && !m_rejectedFrame) @@ -139,7 +181,9 @@ public void BeginFrame() throw new InvalidOperationException("Expected frame failure."); } } + public uint EndFrame() => 1; + public void Execute( CompiledRenderGraph graph, ulong frameIndex @@ -147,55 +191,72 @@ ulong frameIndex Assert.NotNull(graph); completedFrames++; } + public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; + public PersistentTextureHandle CreateTexture( RenderTextureDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void UpdateTexture( PersistentTextureHandle texture, ReadOnlySpan data, int mipLevel = 0, int arrayLayer = 0 ) => throw new NotSupportedException(); + public void UpdateTextureRegion( PersistentTextureHandle texture, RenderTextureRegion region, ReadOnlySpan data ) => throw new NotSupportedException(); + public RenderTextureReadbackHandle BeginTextureReadback( PersistentTextureHandle texture, int mipLevel = 0 ) => throw new NotSupportedException(); + public bool TryGetTextureReadback( RenderTextureReadbackHandle readback, out RenderTextureReadbackResult? result ) => throw new NotSupportedException(); + public void CancelTextureReadback(RenderTextureReadbackHandle readback) => throw new NotSupportedException(); + public void DestroyTexture(PersistentTextureHandle texture) => throw new NotSupportedException(); + public PersistentBufferHandle CreateBuffer( PersistentBufferDescriptor descriptor, ReadOnlySpan initialData, string name ) => throw new NotSupportedException(); + public void UpdateBuffer( PersistentBufferHandle buffer, ReadOnlySpan data, int startElement = 0 ) => throw new NotSupportedException(); + public void DestroyBuffer(PersistentBufferHandle buffer) => throw new NotSupportedException(); + public GraphicsPipelineHandle CreateGraphicsPipeline( GraphicsPipelineDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) => throw new NotSupportedException(); + public ComputePipelineHandle CreateComputePipeline( ComputePipelineDescriptor descriptor, string name ) => throw new NotSupportedException(); + public void DestroyComputePipeline(ComputePipelineHandle pipeline) => throw new NotSupportedException(); + public void Dispose() => retired.Add("render"); } + private sealed class MemoryUi(List retired) : IUiBackend { internal UiInputSnapshot? lastInput { get; private set; } @@ -204,41 +265,50 @@ private sealed class MemoryUi(List retired) : IUiBackend public UiBackendCapabilities capabilities { get; } = new([new("tests.ui-language")], true); public UiContextHandle CreateContext(UiContextOptions options) => new(1); - public void DestroyContext(UiContextHandle context) { } + + public void DestroyContext(UiContextHandle context) {} + public void SetViewport( UiContextHandle context, int width, int height, float density - ) { } + ) {} + public UiDocumentHandle LoadDocument( UiContextHandle context, UiDocumentSource source ) => new(1); + public void ShowDocument( UiContextHandle context, UiDocumentHandle document - ) { } + ) {} + public void HideDocument( UiContextHandle context, UiDocumentHandle document - ) { } + ) {} + public void CloseDocument( UiContextHandle context, UiDocumentHandle document - ) { } + ) {} + public bool SetText( UiContextHandle context, UiDocumentHandle document, string elementId, string text ) => true; + public bool SetContent( UiContextHandle context, UiDocumentHandle document, string elementId, UiDocumentFragment content ) => true; + public bool SetAttribute( UiContextHandle context, UiDocumentHandle document, @@ -246,6 +316,7 @@ public bool SetAttribute( string name, string value ) => true; + public bool SetClass( UiContextHandle context, UiDocumentHandle document, @@ -253,22 +324,29 @@ public bool SetClass( string className, bool active ) => true; - public void RegisterFont(UiFontRegistration registration) { } + + public void RegisterFont(UiFontRegistration registration) {} + public void RegisterTexture( UiContextHandle context, string source, UiTextureData texture - ) { } + ) {} + public bool HasElementAtPoint( UiContextHandle context, Inno.Core.Mathematics.Vector2 position ) => false; + public void Update( UiContextHandle context, UiInputSnapshot input ) => lastInput = input; + public UiRenderFrame Render(UiContextHandle context) => UiRenderFrame.empty; + public IReadOnlyList DrainEvents(UiContextHandle context) => []; + public void Dispose() => retired.Add("ui"); } @@ -291,18 +369,22 @@ public TextFontHandle LoadFont( ReadOnlySpan data, int faceIndex ) => throw new NotSupportedException(); + public void ReleaseFont(TextFontHandle font) => throw new NotSupportedException(); + public TextLayout Shape( TextFontHandle font, string text, TextStyle style, TextShapingOptions options ) => throw new NotSupportedException(); + public GlyphBitmap Rasterize( TextFontHandle font, uint glyphId, float fontSize ) => throw new NotSupportedException(); + public void Dispose() => retired.Add("text"); } @@ -312,19 +394,23 @@ public ValueTask ExistsAsync( StorageKey key, CancellationToken cancellationToken = default ) => ValueTask.FromResult(false); + public ValueTask ReadAsync( StorageKey key, CancellationToken cancellationToken = default ) => ValueTask.FromResult(null); + public ValueTask WriteAsync( StorageKey key, ReadOnlyMemory value, CancellationToken cancellationToken = default ) => throw new NotSupportedException(); + public ValueTask DeleteAsync( StorageKey key, CancellationToken cancellationToken = default ) => ValueTask.FromResult(false); + public ValueTask> ListAsync( StorageKey? prefix = null, CancellationToken cancellationToken = default diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs index 767fcc616..587fc882a 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs @@ -4,6 +4,7 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Assets; @@ -11,8 +12,8 @@ using Inno.Content; using Inno.Content.Testing; using Inno.Core.Execution; -using Inno.Core.Identity; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -21,7 +22,6 @@ using Inno.Scene; using Inno.Shell; using Inno.Storage; -using Xunit; namespace Inno.Runtime.Tests; @@ -40,7 +40,8 @@ public void CompletePlayerStartsFromOwnedMemoryAndRetiresAfterSuccessfulOrFailin var deployment = GameCodeDeployment.FromManifest(source.manifest.modules); var options = new PlayerLaunchOptions { - adapterSelection = new Inno.Adapter.AdapterSelection { + adapterSelection = new Inno.Adapter.AdapterSelection + { platform = Inno.Adapter.Platform.PlatformBackendId.sdl3, input = Inno.Adapter.Input.InputBackendId.events, rendering = Inno.Adapter.Rendering.RenderingBackendId.bgfx, @@ -55,11 +56,13 @@ public void CompletePlayerStartsFromOwnedMemoryAndRetiresAfterSuccessfulOrFailin contentSource = source, adapters = adapters, createStorage = _ => new MemoryStorage(), - moduleActivator = new StaticPlayerModuleActivator(deployment, + moduleActivator = new StaticPlayerModuleActivator( + deployment, new Dictionary> { ["Game"] = [typeof(PlayerWithoutFileSystemTests).Assembly] - }), + } + ), frameDriver = new PollingShellFrameDriver(), smokeFrameLimit = 3, windowVisible = false, @@ -67,10 +70,14 @@ public void CompletePlayerStartsFromOwnedMemoryAndRetiresAfterSuccessfulOrFailin logDeliveryMode = LogDeliveryMode.Inline }; if (failFrame) + { Assert.Throws(() => OwnerThreadExecution.Run(() => PlayerApplication.RunAsync(options))); + } else + { Assert.Equal(0, OwnerThreadExecution.Run(() => PlayerApplication.RunAsync(options))); + } Assert.Equal(1, source.metadataReads); Assert.Equal(1, source.preparations); Assert.Equal(1, source.disposals); @@ -90,18 +97,31 @@ private static MemoryPlayerSource CreateDeployment(string root) var identities = new IdentityAllocator(); var world = new SceneWorld(identities, engine.types); using IDisposable sceneScope = world.EnterScope(); - using var assets = new AssetPipeline(engine.modules, engine.types, engine.serialization, - identities, engine.diagnostics, engine.logs, + using var assets = new AssetPipeline( + engine.modules, + engine.types, + engine.serialization, + identities, + engine.diagnostics, + engine.logs, AssetPipelineOptions.Create(assetsDirectory, Path.Combine(root, "Library")) with { enableFileSystemWatcher = false - }); - Assert.True(assets.Save(AssetPath.Project("Startup.iscene"), - SceneAsset.Capture(new GameScene("Memory scene"), engine.serialization, assets))); + } + ); + Assert.True( + assets.Save( + AssetPath.Project("Startup.iscene"), + SceneAsset.Capture(new GameScene("Memory scene"), engine.serialization, assets) + ) + ); using var settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.Combine(root, SettingsFileNames.project)), - engine.types, engine.serialization, new ProjectId("tests.memory.player"), - AssetSerializationContext.Create(assets)); + engine.types, + engine.serialization, + new ProjectId("tests.memory.player"), + AssetSerializationContext.Create(assets) + ); string exported = Path.Combine(root, "Exported"); assets.ExportRuntimeArtifacts(exported); File.WriteAllBytes(Path.Combine(exported, SettingsFileNames.project), settings.CaptureDocument()); @@ -123,15 +143,20 @@ private static MemoryPlayerSource CreateDeployment(string root) }] }; using SerializationGeneration serialization = engine.serialization.CaptureGeneration(); - return new MemoryPlayerSource(manifest, content, - new PlayerContentMetadata(RuntimeManifestEnvelope.Encode(manifest, serialization), + return new MemoryPlayerSource( + manifest, + content, + new PlayerContentMetadata( + RuntimeManifestEnvelope.Encode(manifest, serialization), serialization.Serialize(new RuntimeContentCatalog { contentHash = content.descriptor.contentHash, packFileName = content.descriptor.fileName, snapshotFingerprint = new string('A', 64), runtimeAssemblyCount = 1 - }))); + }) + ) + ); } finally { diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.cs b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.cs index 096b9c74f..63ebbf1d3 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; +using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Content; using Inno.Content.Testing; using Inno.Core.Logging; using Inno.Core.Serialization; -using Xunit; namespace Inno.Runtime.Tests; @@ -45,9 +45,13 @@ [new ContentKey("AssetDatabase/Catalog.snapshot")] = catalog createLogSink = _ => secondLog }); using (first.EnterExecutionScope()) + { Log.Info(typeof(PlayerWithoutFileSystemTests), "first"); + } using (second.EnterExecutionScope()) + { Log.Info(typeof(PlayerWithoutFileSystemTests), "second"); + } first.Tick(0.01f); second.Tick(0.02f); Assert.Equal("first", Assert.Single(firstLog.messages)); @@ -82,11 +86,15 @@ public void AFailingHostLogFactoryCompensatesStartupAndKeepsTheHostUsable() valid.Tick(0.01f); } - private static EngineHost CreateHost() => new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(PlayerWithoutFileSystemTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) - .UseLogDelivery(LogDeliveryMode.Inline) - .Build(); + private static EngineHost CreateHost() + => new EngineHostBuilder() + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(PlayerWithoutFileSystemTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .UseLogDelivery(LogDeliveryMode.Inline) + .Build(); private sealed class MemoryLog : ILogSink, IDisposable { @@ -94,6 +102,7 @@ private sealed class MemoryLog : ILogSink, IDisposable internal int disposals; public void Receive(LogEntry entry) => messages.Add(entry.message); + public void Dispose() => disposals++; } } diff --git a/tests/runtime/Inno.Runtime.Tests/RuntimeRetirementTests.cs b/tests/runtime/Inno.Runtime.Tests/RuntimeRetirementTests.cs index fd845881a..9f627ab78 100644 --- a/tests/runtime/Inno.Runtime.Tests/RuntimeRetirementTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/RuntimeRetirementTests.cs @@ -1,14 +1,14 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Threading; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Execution; +using Inno.Core.Logging; using Inno.Runtime.Contracts; -using Xunit; namespace Inno.Runtime.Tests; @@ -19,26 +19,32 @@ public sealed class RuntimeRetirementTests [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] - public void FailedStartupDrainsBeforeReleasingFactoryResources(bool hostLifetime, bool failAttach) - { + public void FailedStartupDrainsBeforeReleasingFactoryResources( + bool hostLifetime, + bool failAttach + ) { string root = Path.Combine(Path.GetTempPath(), "InnoStartupTests", Guid.NewGuid().ToString("N")); using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .Build(); var resource = new Resource(); var factory = new FailingFactory(resource, hostLifetime, failAttach); try { Exception error = hostLifetime - ? Assert.Throws(() => host.CreateHostPipeline([factory])) - : Assert.Throws(() => host.CreateSession(new RuntimeSessionOptions - { - applicationId = "startup.test", - kind = RuntimeSessionKind.Play, - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(root, "startup.test"), "Logs")), - jobExecutionMode = RuntimeJobExecutionMode.SingleThread, - createSubsystems = _ => [factory] - })); + ? Assert.Throws(() => host.CreateHostPipeline([factory])) + : Assert.Throws(() => host.CreateSession(new RuntimeSessionOptions + { + applicationId = "startup.test", + kind = RuntimeSessionKind.Play, + createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(root, "startup.test"), "Logs")), + jobExecutionMode = RuntimeJobExecutionMode.SingleThread, + createSubsystems = _ => [factory] + })); Assert.Equal("startup failure", error.Message); Assert.True(factory.observedRetainedResource); Assert.True(resource.disposed); @@ -51,7 +57,9 @@ public void FailedStartupDrainsBeforeReleasingFactoryResources(bool hostLifetime { host.Dispose(); if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -60,8 +68,12 @@ public void StopHookPendingRetainsDependenciesWithoutRepeatingCompletedOwners() { string root = Path.Combine(Path.GetTempPath(), "InnoStopTests", Guid.NewGuid().ToString("N")); using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .Build(); var pending = new StopPendingSubsystem(); var resource = new Resource(); RuntimeSession session = host.CreateSession(new RuntimeSessionOptions @@ -89,8 +101,12 @@ public void PendingSessionRetainsDependenciesAndCanBeRetriedThroughHost() var pending = new PendingSubsystem(); var resource = new Resource(); using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeRetirementTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .Build(); try { RuntimeSession session = host.CreateSession(new RuntimeSessionOptions @@ -118,13 +134,19 @@ public void PendingSessionRetainsDependenciesAndCanBeRetriedThroughHost() pending.work.TrySetResult(); host.Dispose(); if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } - private sealed class Factory(PendingSubsystem subsystem, Resource resource) : IRuntimeSubsystemFactory + private sealed class Factory( + PendingSubsystem subsystem, + Resource resource + ) : IRuntimeSubsystemFactory { public RuntimeSubsystemDescriptor descriptor { get; } = new(new RuntimeSubsystemId("tests.pending")); + public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { context.resources.Own(resource); @@ -136,7 +158,9 @@ private sealed class PendingSubsystem : RuntimeSubsystem { internal TaskCompletionSource work { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); internal bool stopped { get; private set; } + protected override void OnStart() => lifetime.Track(work.Task); + protected override void OnStop() => stopped = true; } @@ -144,45 +168,70 @@ private sealed class Resource : IDisposable { internal bool disposed { get; private set; } internal int disposeCount { get; private set; } - public void Dispose() { disposed = true; disposeCount++; } + + public void Dispose() + { + disposed = true; + disposeCount++; + } } - private sealed class FailingFactory(Resource resource, bool hostLifetime, bool failAttach) : IRuntimeSubsystemFactory + private sealed class FailingFactory( + Resource resource, + bool hostLifetime, + bool failAttach + ) : IRuntimeSubsystemFactory { - public RuntimeSubsystemDescriptor descriptor { get; } = new(new RuntimeSubsystemId("tests.failure"), - lifetime: hostLifetime ? RuntimeSubsystemLifetime.Host : RuntimeSubsystemLifetime.Session); + public RuntimeSubsystemDescriptor descriptor { get; } = new( + new RuntimeSubsystemId("tests.failure"), + lifetime: hostLifetime ? RuntimeSubsystemLifetime.Host : RuntimeSubsystemLifetime.Session + ); + internal bool observedRetainedResource; public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { context.resources.Own(resource); if (failAttach) + { return new FailingSubsystem(this, resource); + } context.resources.Track(Drain(context.resources.cancellationToken)); throw new InvalidOperationException("startup failure"); } internal async Task Drain(CancellationToken cancellationToken) { - try { await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); } + try + { + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + } catch (OperationCanceledException) { } observedRetainedResource = !resource.disposed; } - private sealed class FailingSubsystem(FailingFactory factory, Resource resource) : RuntimeSubsystem + private sealed class FailingSubsystem( + FailingFactory factory, + Resource resource + ) : RuntimeSubsystem { protected override void OnStart() { lifetime.Track(factory.Drain(lifetime.cancellationToken)); throw new InvalidOperationException("startup failure"); } + protected override void OnStop() => Assert.False(resource.disposed); } } - private sealed class SimpleFactory(IRuntimeSubsystem subsystem, Resource resource) : IRuntimeSubsystemFactory + private sealed class SimpleFactory( + IRuntimeSubsystem subsystem, + Resource resource + ) : IRuntimeSubsystemFactory { public RuntimeSubsystemDescriptor descriptor { get; } = new(new RuntimeSubsystemId("tests.stop")); + public IRuntimeSubsystem Create(RuntimeSubsystemContext context) { context.resources.Own(resource); @@ -194,11 +243,14 @@ private sealed class StopPendingSubsystem : RuntimeSubsystem { internal bool ready; internal int stopAttempts; + protected override void OnStop() { stopAttempts++; if (!ready) + { throw new RetirementPendingException("native drain pending"); + } } } } diff --git a/tests/runtime/Inno.Runtime.Tests/RuntimeSessionTests.cs b/tests/runtime/Inno.Runtime.Tests/RuntimeSessionTests.cs index 53597711a..dce3b39f7 100644 --- a/tests/runtime/Inno.Runtime.Tests/RuntimeSessionTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/RuntimeSessionTests.cs @@ -1,17 +1,15 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using Inno.Runtime.Contracts; using System; -using System.IO; using System.Collections.Generic; - -using Inno.References; +using System.IO; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Logging; +using Inno.References; using Inno.Runtime; +using Inno.Runtime.Contracts; using Inno.Scene; -using Xunit; - namespace Inno.Runtime.Tests; public sealed class RuntimeSessionTests : IDisposable @@ -19,21 +17,27 @@ public sealed class RuntimeSessionTests : IDisposable private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoRuntimeSessionTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); [Fact] public void InlineHostDeliveryPersistsSessionLogsBeforeTheProducerReturns() { using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeSessionTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeSessionTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .UseLogDelivery(LogDeliveryMode.Inline) .Build(); RuntimeSessionOptions options = CreateOptions("inline", RuntimeSessionKind.Play); using RuntimeSession session = host.CreateSession(options); using (session.EnterExecutionScope()) + { Log.Info(typeof(RuntimeSessionTests), "session-inline-delivery"); + } string file = Assert.Single(Directory.GetFiles(Path.Combine(m_root, "Persistent", "inline", "Logs"))); using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); @@ -50,9 +54,13 @@ public void MultipleHostsAndSessionsKeepSceneAndTimeStateIsolated() using RuntimeSession second = secondHost.CreateSession(CreateOptions("second", RuntimeSessionKind.Play)); using (first.EnterExecutionScope()) + { _ = SceneManager.LoadNewScene("First Scene"); + } using (second.EnterExecutionScope()) + { _ = SceneManager.LoadNewScene("Second Scene"); + } first.Tick(0.02f); second.Tick(0.04f); @@ -106,10 +114,7 @@ public void RuntimeSubsystemsFollowDependenciesAndReleaseInReverseOrder() using EngineHost host = CreateHost("Features"); var events = new List(); var first = new ProbeFeatureFactory("tests.first", [], events); - var second = new ProbeFeatureFactory( - "tests.second", - [new RuntimeSubsystemId("tests.first")], - events); + var second = new ProbeFeatureFactory("tests.second", [new RuntimeSubsystemId("tests.first")], events); RuntimeSessionOptions baseline = CreateOptions("features", RuntimeSessionKind.Play); var options = new RuntimeSessionOptions { @@ -126,28 +131,30 @@ [new RuntimeSubsystemId("tests.first")], session.Dispose(); Assert.Equal( - [ - "attach:tests.first", - "attach:tests.second", - "begin:tests.first", - "begin:tests.second", - "update:tests.first", - "update:tests.second", - "late:tests.first", - "late:tests.second", - "before-render:tests.first", - "before-render:tests.second", - "render:tests.first", - "render:tests.second", - "after-render:tests.second", - "after-render:tests.first", - "end:tests.second", - "end:tests.first", - "detach:tests.second", - "dispose:tests.second", - "detach:tests.first", - "dispose:tests.first" - ], events); + [ + "attach:tests.first", + "attach:tests.second", + "begin:tests.first", + "begin:tests.second", + "update:tests.first", + "update:tests.second", + "late:tests.first", + "late:tests.second", + "before-render:tests.first", + "before-render:tests.second", + "render:tests.first", + "render:tests.second", + "after-render:tests.second", + "after-render:tests.first", + "end:tests.second", + "end:tests.first", + "detach:tests.second", + "dispose:tests.second", + "detach:tests.first", + "dispose:tests.first" + ], + events + ); } [Fact] @@ -185,45 +192,58 @@ public void DisposedHostRejectsNewSessions() host.Dispose(); Assert.Throws( - () => host.CreateSession(CreateOptions("disposed", RuntimeSessionKind.Edit))); + () => host.CreateSession(CreateOptions("disposed", RuntimeSessionKind.Edit)) + ); } public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private EngineHost CreateHost(string name) => new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeSessionTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeSessionTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); - private RuntimeSessionOptions CreateOptions(string applicationId, RuntimeSessionKind kind) - => new() - { - kind = kind, - applicationId = applicationId, - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_root, "Persistent", applicationId), "Logs")), - fixedDeltaTime = 0.02f, - jobExecutionMode = RuntimeJobExecutionMode.SingleThread - }; + private RuntimeSessionOptions CreateOptions( + string applicationId, + RuntimeSessionKind kind + ) => new() + { + kind = kind, + applicationId = applicationId, + createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(m_root, "Persistent", applicationId), "Logs")), + fixedDeltaTime = 0.02f, + jobExecutionMode = RuntimeJobExecutionMode.SingleThread + }; private sealed class ProbeFeatureFactory( string id, IReadOnlyList dependencies, - List events) : IRuntimeSubsystemFactory + List events + ) : IRuntimeSubsystemFactory { public RuntimeSubsystemDescriptor descriptor { get; } = new( new RuntimeSubsystemId(id), - dependencies: dependencies); + dependencies: dependencies + ); public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => new ProbeFeature(descriptor.id.value, events); } - private sealed class ProbeFeature(string id, List events) : RuntimeSubsystem + private sealed class ProbeFeature( + string id, + List events + ) : RuntimeSubsystem { protected override void OnStart() => events.Add($"attach:{id}"); diff --git a/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs b/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs index 11290dd25..4b50eee0a 100644 --- a/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs @@ -1,14 +1,14 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Execution; using Inno.Extensibility.Reload; using Inno.Runtime.Contracts; -using Xunit; namespace Inno.Runtime.Tests; @@ -19,14 +19,20 @@ public sealed class RuntimeSubsystemPolicyTests : IDisposable public RuntimeSubsystemPolicyTests() => m_host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeSubsystemPolicyTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeSubsystemPolicyTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .Build(); public void Dispose() { m_host.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -59,11 +65,17 @@ public void SuppliedCapabilitiesAndDescriptorCollectionsAreImmutableSnapshots() [InlineData(true)] public void OptionalUnavailabilityPropagatesToOptionalConsumers(bool missingCapability) { - var unavailable = Create("test.optional", RuntimeSubsystemRequirement.Optional, - capabilities: missingCapability ? [new RuntimeCapabilityId("test.absent")] : []); + var unavailable = Create( + "test.optional", + RuntimeSubsystemRequirement.Optional, + capabilities: missingCapability ? [new RuntimeCapabilityId("test.absent")] : [] + ); unavailable.failCreate = !missingCapability; - var consumer = Create("test.consumer", RuntimeSubsystemRequirement.Optional, - dependencies: [unavailable.descriptor.id]); + var consumer = Create( + "test.consumer", + RuntimeSubsystemRequirement.Optional, + dependencies: [unavailable.descriptor.id] + ); var available = Create("test.available"); RuntimeSubsystemPipeline pipeline = m_host.CreateHostPipeline([consumer, available, unavailable]); Assert.Equal("test.available", Assert.Single(pipeline.descriptors).id.value); @@ -116,8 +128,11 @@ public void OptionalRetirementFailureFaultsInsteadOfDegrading() [Fact] public void OptionalMissingDependencyIsDiagnosedButCyclesStillReject() { - var missing = Create("test.missing", RuntimeSubsystemRequirement.Optional, - dependencies: [new RuntimeSubsystemId("test.absent")]); + var missing = Create( + "test.missing", + RuntimeSubsystemRequirement.Optional, + dependencies: [new RuntimeSubsystemId("test.absent")] + ); Assert.Single(m_host.CreateHostPipeline([missing]).startupDiagnostics); var a = Create("test.a", RuntimeSubsystemRequirement.Optional, dependencies: [new RuntimeSubsystemId("test.b")]); var b = Create("test.b", RuntimeSubsystemRequirement.Optional, dependencies: [a.descriptor.id]); @@ -131,9 +146,13 @@ public void StartupTimeoutKeepsPendingHostPipelineAndPermanentlyFaultsAdmission( { string root = Path.Combine(m_root, "Timeout"); EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(RuntimeSubsystemPolicyTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) - .UseRetirementTimeout(TimeSpan.FromTicks(1)).Build(); + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(RuntimeSubsystemPolicyTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) + .UseRetirementTimeout(TimeSpan.FromTicks(1)) + .Build(); var pending = new TaskCompletionSource(); var factory = Create("test.timeout"); factory.pending = pending.Task; @@ -151,10 +170,20 @@ public void StartupTimeoutKeepsPendingHostPipelineAndPermanentlyFaultsAdmission( host.logs.Dispose(); } - private static Factory Create(string id, RuntimeSubsystemRequirement requirement = RuntimeSubsystemRequirement.Required, - IReadOnlyList? dependencies = null, IReadOnlyList? capabilities = null) - => new(new RuntimeSubsystemDescriptor(new RuntimeSubsystemId(id), dependencies: dependencies, - lifetime: RuntimeSubsystemLifetime.Host, requirement: requirement, requiredCapabilities: capabilities)); + private static Factory Create( + string id, + RuntimeSubsystemRequirement requirement = RuntimeSubsystemRequirement.Required, + IReadOnlyList? dependencies = null, + IReadOnlyList? capabilities = null + ) => new( + new RuntimeSubsystemDescriptor( + new RuntimeSubsystemId(id), + dependencies: dependencies, + lifetime: RuntimeSubsystemLifetime.Host, + requirement: requirement, + requiredCapabilities: capabilities + ) + ); private sealed class Factory(RuntimeSubsystemDescriptor descriptor) : IRuntimeSubsystemFactory { @@ -173,9 +202,13 @@ public IRuntimeSubsystem Create(RuntimeSubsystemContext context) createCount++; context.resources.Own(new Resource(this)); if (pending is not null) + { context.resources.Track(pending); + } if (failCreate) + { throw new InvalidOperationException("factory failed"); + } return new Subsystem(this); } @@ -185,7 +218,9 @@ public void Dispose() { factory.releaseCount++; if (factory.failRelease) + { throw new InvalidOperationException("resource retirement failed"); + } } } @@ -194,7 +229,9 @@ private sealed class Subsystem(Factory factory) : RuntimeSubsystem protected override void OnStart() { if (factory.failAttach) + { throw new InvalidOperationException("attach failed"); + } } } } diff --git a/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs b/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs index 135932cf2..af9ffaf87 100644 --- a/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs @@ -1,8 +1,8 @@ using System; using System.IO; +using Xunit; using Inno.Extensibility.Modules; using Inno.Runtime; -using Xunit; namespace Inno.Runtime.Tests; @@ -15,8 +15,10 @@ public void ManifestMutationCannotChangeFrozenDeployment() string[] dependencies = []; var module = new GameRuntimeModule { - name = "Game", domain = AssemblyDomain.InnoScripting, - assemblies = [assembly], dependencies = dependencies + name = "Game", + domain = AssemblyDomain.InnoScripting, + assemblies = [assembly], + dependencies = dependencies }; GameCodeDeployment frozen = GameCodeDeployment.FromManifest([module]); assembly.name = "Different.Code"; @@ -41,10 +43,15 @@ public void LinkedIdentityRejectsDifferentCodeBeforeModuleActivation() public void ClosureRejectsSharedAssemblyOwnersAndMissingUpstreamModules() { Assert.Throws(() => new GameCodeDeployment([ - CreateModule("One", "Shared.Code", 'a'), CreateModule("Two", "Shared.Code", 'a') + CreateModule("One", "Shared.Code", 'a'), + CreateModule("Two", "Shared.Code", 'a') ])); - var missing = new GameCodeModule("Game", AssemblyDomain.InnoScripting, - [new GameCodeAssembly("Game.Code", new string('a', 64))], ["Absent"]); + var missing = new GameCodeModule( + "Game", + AssemblyDomain.InnoScripting, + [new GameCodeAssembly("Game.Code", new string('a', 64))], + ["Absent"] + ); Assert.Throws(() => new GameCodeDeployment([missing])); } @@ -61,6 +68,5 @@ private static GameCodeModule CreateModule( string name, string assembly, char fingerprint - ) => new(name, AssemblyDomain.InnoScripting, - [new GameCodeAssembly(assembly, new string(fingerprint, 64))], []); + ) => new(name, AssemblyDomain.InnoScripting, [new GameCodeAssembly(assembly, new string(fingerprint, 64))], []); } diff --git a/tests/runtime/Inno.Runtime.Tests/StaticGenericFactoryTests.cs b/tests/runtime/Inno.Runtime.Tests/StaticGenericFactoryTests.cs index 87900d906..b138e0c1f 100644 --- a/tests/runtime/Inno.Runtime.Tests/StaticGenericFactoryTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/StaticGenericFactoryTests.cs @@ -1,8 +1,8 @@ using System; using System.Threading.Tasks; +using Xunit; using Inno.Extensibility.Catalogs; using Inno.Runtime; -using Xunit; namespace Inno.Runtime.Tests; @@ -15,7 +15,10 @@ public void FactoriesDoNotIntroduceClosedConstructionsIntoDiscovery() { register.Register(Metadata(typeof(Box<>)), null); register.RegisterFactory(typeof(Box), static () => new Box()); - register.RegisterFactory(typeof(Box), static () => throw new InvalidOperationException("Duplicate factory must not execute.")); + register.RegisterFactory( + typeof(Box), + static () => throw new InvalidOperationException("Duplicate factory must not execute.") + ); }]); Assert.Equal(typeof(Box), source.ConstructGenericType(typeof(Box<>), [typeof(int)])); @@ -57,9 +60,10 @@ public void FailedContributorAlsoRetiresItsRegistrar() [Fact] public void ContributorCannotTransferRegistrationToAnotherThread() - => new StaticTypeCatalogSource([register => Task.Run(() => - Assert.Throws(() => register.Register(Metadata(typeof(Box<>)), null))) - .GetAwaiter().GetResult()]); + => new StaticTypeCatalogSource([register => Task + .Run(() => Assert.Throws(() => register.Register(Metadata(typeof(Box<>)), null))) + .GetAwaiter() + .GetResult()]); [Fact] public void GenericArgumentValidationIsIndependentOfAvailableFactories() diff --git a/tests/runtime/Inno.Runtime.Tests/StaticProjectSettingsTests.cs b/tests/runtime/Inno.Runtime.Tests/StaticProjectSettingsTests.cs index a636752d0..64718237b 100644 --- a/tests/runtime/Inno.Runtime.Tests/StaticProjectSettingsTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/StaticProjectSettingsTests.cs @@ -1,13 +1,12 @@ -using Inno.Core.IO; using System; using System.IO; +using Xunit; +using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Catalogs; using Inno.Extensibility.Types; using Inno.Runtime; -using Xunit; - -using Inno.Extensibility.Catalogs; namespace Inno.Runtime.Tests; @@ -22,8 +21,13 @@ public void SettingsUseContributedMetadataAndFactoryWithoutReflectiveDeclaration try { using EngineHost host = CreateHost(directory, static () => new Setting(17)); - using var settings = new ProjectSettings(new FileByteDocumentStore(Path.GetFullPath(Path.Combine(directory, "Settings.Project.inno"))), - host.types, host.serialization, new ProjectId("tests.static"), SerializationContext.empty); + using var settings = new ProjectSettings( + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(directory, "Settings.Project.inno"))), + host.types, + host.serialization, + new ProjectId("tests.static"), + SerializationContext.empty + ); Setting first = settings.Get(SettingId); Assert.Equal(17, first.value); @@ -46,8 +50,13 @@ public void SettingsRejectMissingFactoriesDuringCandidatePreparation() { using EngineHost host = CreateHost(directory, factory: null); InvalidOperationException exception = Assert.Throws(() => - new ProjectSettings(new FileByteDocumentStore(Path.GetFullPath(Path.Combine(directory, "Settings.Project.inno"))), host.types, - host.serialization, new ProjectId("tests.static"), SerializationContext.empty)); + new ProjectSettings( + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(directory, "Settings.Project.inno"))), + host.types, + host.serialization, + new ProjectId("tests.static"), + SerializationContext.empty + )); Assert.Contains("factory in the current type catalog", exception.Message); } finally @@ -60,24 +69,39 @@ private static EngineHost CreateHost( string directory, Func? factory ) { - Attribute[] attributes = [new StableTypeIdAttribute("f506944b-bcfa-48e4-b839-a66b4d8f5887"), - new ProjectSettingDefinitionAttribute(SettingId.value)]; - var types = new StaticTypeCatalogSource([register => register.Register(new TypeCatalogMetadata(typeof(Setting), - [], [typeof(ISerializable)], attributes, attributes, []), factory)]); + Attribute[] attributes = + [ + new StableTypeIdAttribute("f506944b-bcfa-48e4-b839-a66b4d8f5887"), + new ProjectSettingDefinitionAttribute(SettingId.value) + ]; + var types = new StaticTypeCatalogSource([register => register.Register( + new TypeCatalogMetadata(typeof(Setting), [], [typeof(ISerializable)], attributes, attributes, []), + factory + )]); var serialization = new StaticSerializationMetadataSource([ - register => register(new SerializationTypeMetadata(typeof(Setting), [ - new SerializationMemberMetadata("value", typeof(int), PropertyVisibility.Show, - static value => ((Setting)value).value, - static ( - target, - value - ) => ((Setting)target).value = (int)value!) - ], static () => new Setting(17))), + register => register( + new SerializationTypeMetadata(typeof(Setting), [ + new SerializationMemberMetadata( + "value", + typeof(int), + PropertyVisibility.Show, + static value => ((Setting)value).value, + static ( + target, + value + ) => ((Setting)target).value = (int)value! + ) + ], static () => new Setting(17)) + ), Inno.Core.Settings.Generated.RuntimeSerializationMetadataCatalog.Register ]); return new EngineHostBuilder() - .UseMetadataSources(new StaticAssemblyCatalogSource([typeof(Setting).Assembly], [typeof(object).Assembly]), - types, serialization).Build(); + .UseMetadataSources( + new StaticAssemblyCatalogSource([typeof(Setting).Assembly], [typeof(object).Assembly]), + types, + serialization + ) + .Build(); } private static string CreateDirectory() diff --git a/tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs b/tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs index beec5cb8c..baa35080a 100644 --- a/tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs +++ b/tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs @@ -1,8 +1,7 @@ using System.Collections.Generic; - using Inno.Assets; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene; namespace Inno.Scene.Tests; @@ -33,6 +32,8 @@ internal sealed class PrefabInstantiationBehavior : GameBehavior protected override void Update() { if (prefab is not null && instances.Count < 2) + { instances.Add(gameObject.scene.InstantiatePrefab(prefab, gameObject.transform)); + } } } diff --git a/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.PropertyReferences.cs b/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.PropertyReferences.cs index a5e0f5300..bbaef8765 100644 --- a/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.PropertyReferences.cs +++ b/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.PropertyReferences.cs @@ -1,5 +1,5 @@ -using Inno.Assets; using Xunit; +using Inno.Assets; namespace Inno.Scene.Tests; diff --git a/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs b/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs index d7226ca48..f3293f64d 100644 --- a/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs +++ b/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs @@ -3,16 +3,14 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Text; - +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Types; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Layers; -using Xunit; - namespace Inno.Scene.Tests; [Collection(SceneTestsCollection.NAME)] @@ -21,7 +19,9 @@ public sealed partial class EngineAssetIntegrationTests : IDisposable private readonly string m_root = Path.Combine( Path.GetTempPath(), "InnoEngineAssetTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); + private readonly SceneTestsFixture m_fixture; private readonly AssetPipeline m_assets; private readonly SerializationContext m_assetSerializationContext; @@ -44,7 +44,8 @@ public EngineAssetIntegrationTests(SceneTestsFixture fixture) fixture.identities, fixture.diagnostics, fixture.logs, - options); + options + ); m_assetSerializationContext = AssetSerializationContext.Create(m_assets); } @@ -54,7 +55,9 @@ public void Dispose() m_assets.Dispose(); m_sceneScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -77,7 +80,8 @@ public void SceneAsset_CaptureSaveLoadInstantiate_PreservesCanonicalIdentity() Assert.NotEqual(first.identity.persistentId, second.identity.persistentId); Assert.NotEqual( Assert.Single(first.GetObjects()).identity.persistentId, - Assert.Single(second.GetObjects()).identity.persistentId); + Assert.Single(second.GetObjects()).identity.persistentId + ); DestroyScene(source); DestroyScene(first); @@ -108,10 +112,12 @@ public void PrefabAsset_IsSceneIndependentAndRemapsInternalReferences() Assert.NotEqual(first.identity.persistentId, second.identity.persistentId); Assert.Same( Assert.Single(first.transform.children).gameObject, - first.GetComponent().targetObject); + first.GetComponent().targetObject + ); Assert.Same( Assert.Single(second.transform.children).gameObject, - second.GetComponent().targetObject); + second.GetComponent().targetObject + ); DestroyScene(sourceScene); DestroyScene(targetScene); @@ -147,7 +153,8 @@ public void LoadedScene_InstantiatesConnectedPrefabsDuringUpdate() Assert.Same(spawner.gameObject.transform, instance.transform.parent); Assert.Same( Assert.Single(instance.transform.children).gameObject, - instance.GetComponent().targetObject); + instance.GetComponent().targetObject + ); } DestroyScene(sourceScene); @@ -389,13 +396,12 @@ private static void DestroyScene(GameScene scene) SceneManager.UnloadScene(scene); } - private void WriteAsset(string relativePath, string content) - { + private void WriteAsset( + string relativePath, + string content + ) { string path = Path.Combine(m_root, "Assets", relativePath); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - File.WriteAllText( - path, - content, - new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + File.WriteAllText(path, content, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } } diff --git a/tests/scene/Inno.Scene.Tests/GameLayerTests.cs b/tests/scene/Inno.Scene.Tests/GameLayerTests.cs index 4a36b3962..cc160801b 100644 --- a/tests/scene/Inno.Scene.Tests/GameLayerTests.cs +++ b/tests/scene/Inno.Scene.Tests/GameLayerTests.cs @@ -1,12 +1,10 @@ using System; using System.Linq; - +using Xunit; using Inno.Core.Settings; using Inno.Scene; using Inno.Scene.Layers; -using Xunit; - namespace Inno.Scene.Tests; /// @@ -132,9 +130,7 @@ public void GameScene_LayerQueriesTrackLiveObjectChanges() Assert.Same(first, scene.FindObjectWithLayer(player)); Assert.Equal([first], scene.FindObjectsWithLayer(player)); - Assert.Equal( - [first, second], - scene.FindObjectsWithLayers(GameLayerMask.FromLayers([player, enemy]))); + Assert.Equal([first, second], scene.FindObjectsWithLayers(GameLayerMask.FromLayers([player, enemy]))); first.layer = enemy; diff --git a/tests/scene/Inno.Scene.Tests/GameSystemTests.cs b/tests/scene/Inno.Scene.Tests/GameSystemTests.cs index 578662682..bd16eb1f9 100644 --- a/tests/scene/Inno.Scene.Tests/GameSystemTests.cs +++ b/tests/scene/Inno.Scene.Tests/GameSystemTests.cs @@ -1,13 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; - -using Inno.Extensibility.Types; +using Xunit; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Scene; -using Xunit; - namespace Inno.Scene.Tests; [Collection(SceneTestsCollection.NAME)] @@ -148,12 +146,19 @@ private sealed class LifecycleSystem : GameSystem internal int lateCount; protected override void Awake() => awakeCount++; + protected override void Start() => startCount++; + protected override void OnEnable() => enableCount++; + protected override void OnDisable() => disableCount++; + protected override void OnDestroy() => destroyCount++; + protected override void OnFixedUpdate() => fixedCount++; + protected override void OnUpdate() => updateCount++; + protected override void OnLateUpdate() => lateCount++; } @@ -161,7 +166,8 @@ private sealed class LifecycleSystem : GameSystem private sealed class OrderedSystem( string label, int executionOrder, - ICollection execution) : GameSystem + ICollection execution + ) : GameSystem { public override int order => executionOrder; diff --git a/tests/scene/Inno.Scene.Tests/PluginSceneReloadTests.cs b/tests/scene/Inno.Scene.Tests/PluginSceneReloadTests.cs index 7a8b196ff..96ced67b1 100644 --- a/tests/scene/Inno.Scene.Tests/PluginSceneReloadTests.cs +++ b/tests/scene/Inno.Scene.Tests/PluginSceneReloadTests.cs @@ -1,19 +1,17 @@ -using Inno.Adapter.Modules.DotNet; using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; -using System.Collections.Generic; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Core.Identity; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; +using Inno.References; using Inno.Scene; using Inno.Scene.Components; -using Inno.Core.Identity; -using Inno.References; - -using Xunit; namespace Inno.Scene.Tests; @@ -46,11 +44,15 @@ public void Dispose() { m_world.UnloadAllScenes(); if (m_activeModule is AssemblyModuleHandle activeModule) + { _ = m_modules.Unload(activeModule); + } m_sceneScope.Dispose(); m_modules.generations.Wait(); if (Directory.Exists(m_artifactRoot)) + { Directory.Delete(m_artifactRoot, recursive: true); + } } [Fact] @@ -65,13 +67,15 @@ public void RemovingAndRestoringAPluginGenerationPreservesItsComponentAsMissingS m_activeModule = null; MissingGameComponent missing = Assert.IsType( - owner.GetComponents().Single(component => component is not Transform)); + owner.GetComponents().Single(component => component is not Transform) + ); Assert.Equal(componentPersistentId, missing.identity.persistentId); Assert.Equal(S_COMPONENT_TYPE_ID, missing.missingType.stableId); Assert.Equal(typeName, missing.missingTypeName); Assert.False(missing.missingType.IsValid(m_types)); - ReferenceRecoveryChange missingChange = Assert.Single(m_changes.Where(change => - change.missingState.descriptor.targetPersistentId == componentPersistentId)); + ReferenceRecoveryChange missingChange = Assert.Single( + m_changes.Where(change => (change.missingState.descriptor.targetPersistentId == componentPersistentId)) + ); Assert.Equal(ReferenceResolutionState.Missing, missingChange.resolution.state); Assert.Equal(S_COMPONENT_TYPE_ID, missingChange.missingState.descriptor.expectedStableTypeId); Assert.False(missingChange.missingState.payload.IsEmpty); @@ -80,7 +84,8 @@ public void RemovingAndRestoringAPluginGenerationPreservesItsComponentAsMissingS { m_activeModule = recovery.context.module; ISceneReloadStateTransfer transfer = m_reload.Capture( - recovery.context.GetContext()); + recovery.context.GetContext() + ); transfer.PrepareForActivation(); recovery.Activate(); transfer.Apply(); @@ -95,25 +100,27 @@ public void RemovingAndRestoringAPluginGenerationPreservesItsComponentAsMissingS Assert.Equal(S_COMPONENT_TYPE_ID, m_types.GetTypeRef(recovered.GetType()).stableId); Assert.Equal(componentPersistentId, recovered.identity.persistentId); Assert.Equal(47, GetValue(recovered)); - ReferenceRecoveryChange recoveredChange = Assert.Single(m_changes.Where(change => - change.missingState.descriptor.targetPersistentId == componentPersistentId)); + ReferenceRecoveryChange recoveredChange = Assert.Single( + m_changes.Where(change => (change.missingState.descriptor.targetPersistentId == componentPersistentId)) + ); Assert.Equal(ReferenceResolutionState.Resolved, recoveredChange.resolution.state); Assert.Equal(recovered.identity.runtimeIdentity, recoveredChange.resolution.runtimeIdentity); } private DotNetModuleSource CreateRequest() => new() - { - moduleName = "SceneReloadPluginTests", - artifactRootDirectory = m_artifactRoot, - mainAssemblyPath = Path.Combine( - AppContext.BaseDirectory, - "Modules", - "SceneReload", - "Inno.Scene.Reload.TestModule.dll"), - domain = AssemblyDomain.InnoPlugin, - scope = AssemblyScope.Runtime - }; + { + moduleName = "SceneReloadPluginTests", + artifactRootDirectory = m_artifactRoot, + mainAssemblyPath = Path.Combine( + AppContext.BaseDirectory, + "Modules", + "SceneReload", + "Inno.Scene.Reload.TestModule.dll" + ), + domain = AssemblyDomain.InnoPlugin, + scope = AssemblyScope.Runtime + }; [MethodImpl(MethodImplOptions.NoInlining)] private (Guid, string) AttachPluginComponent(GameObject owner) @@ -165,14 +172,16 @@ private void RemovePlugin() m_changes = transfer.recoveryChanges; } - private static int GetValue(GameComponent component) - => (int)GetValueProperty(component).GetValue(component)!; + private static int GetValue(GameComponent component) => (int)GetValueProperty(component).GetValue(component)!; - private static void SetValue(GameComponent component, int value) - => GetValueProperty(component).SetValue(component, value); + private static void SetValue( + GameComponent component, + int value + ) => GetValueProperty(component).SetValue(component, value); private static PropertyInfo GetValueProperty(GameComponent component) => component.GetType().GetProperty("value", BindingFlags.Instance | BindingFlags.Public) ?? throw new InvalidOperationException( - $"Reload test component '{component.GetType().FullName}' does not expose its public state contract."); + $"Reload test component '{component.GetType().FullName}' does not expose its public state contract." + ); } diff --git a/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs b/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs index 99b515c6c..6d991d96e 100644 --- a/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs +++ b/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs @@ -1,13 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; - -using Inno.Scene; +using Xunit; using Inno.Runtime; +using Inno.Scene; using Inno.Scene.Components; -using Xunit; - namespace Inno.Scene.Tests; [Collection(SceneTestsCollection.NAME)] @@ -23,7 +21,9 @@ public void RootSiblingPositionsStayAuthoritativeAcrossHierarchyMutations() Transform destinationRoot = destination.CreateObject("Existing").transform; var roots = new List(); for (int index = 0; index < 64; index++) + { roots.Add(scene.CreateObject("Root " + index).transform); + } var random = new Random(27102026); for (int iteration = 0; iteration < 200; iteration++) { @@ -73,7 +73,9 @@ public void RootSiblingPositionsStayAuthoritativeAcrossHierarchyMutations() void Verify() { for (int index = 0; index < roots.Count; index++) + { Assert.Equal(index, roots[index].siblingIndex); + } } } @@ -223,14 +225,16 @@ public void ComponentsCanBeReorderedIncludingTransform() Assert.Equal( [typeof(Transform), typeof(OrderComponentB), typeof(OrderComponentA)], - gameObject.GetComponents().Select(static component => component.GetType())); + gameObject.GetComponents().Select(static component => component.GetType()) + ); Assert.Equal(1, gameObject.GetComponentIndex(second)); gameObject.SetComponentIndex(gameObject.transform, 2); Assert.Equal( [typeof(OrderComponentB), typeof(OrderComponentA), typeof(Transform)], - gameObject.GetComponents().Select(static component => component.GetType())); + gameObject.GetComponents().Select(static component => component.GetType()) + ); Assert.Equal(2, gameObject.GetComponentIndex(gameObject.transform)); } @@ -367,11 +371,17 @@ private sealed class TestBehaviour : GameBehavior public int disableCount; protected override void Awake() => awakeCount++; + protected override void Start() => startCount++; + protected override void Update() => updateCount++; + protected override void FixedUpdate() => fixedUpdateCount++; + protected override void LateUpdate() => lateUpdateCount++; + protected override void OnEnable() => enableCount++; + protected override void OnDisable() => disableCount++; protected override void Reset() diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs index fdaafdaa9..2e0e3f73d 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs @@ -1,10 +1,10 @@ using System; using System.Linq; using System.Runtime.CompilerServices; +using Xunit; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Scene.Layers; -using Xunit; namespace Inno.Scene.Tests; @@ -121,6 +121,7 @@ public void UntrackedPluginPropertiesAndObjectReferencesRemainAuthoritativelyCap SerializationSnapshot restored = m_serialization.CaptureSnapshot(scene, m_serializationContext, changed); Assert.Equal(before.ToArray(), restored.ToArray()); } + [MethodImpl(MethodImplOptions.NoInlining)] private WeakReference CaptureAndRemoveSystem(GameScene scene) { diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs index 7cf0551e6..f4ecf575c 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs @@ -1,8 +1,8 @@ using System; using System.Linq; +using Xunit; using Inno.Assets; using Inno.Core.Serialization; -using Xunit; namespace Inno.Scene.Tests; @@ -43,7 +43,9 @@ public void ElementPropertyAliasesRejectCollisionsMissingTargetsAndMalformedMeta probe.targetObject = original; IAssetReferenceResolver assets = m_serializationContext.GetRequired(); PropertyElementEnvelope envelope = m_serialization.Deserialize( - SceneElementSerialization.CaptureState(probe, m_serialization, assets), m_serializationContext); + SceneElementSerialization.CaptureState(probe, m_serialization, assets), + m_serializationContext + ); envelope.aliasIds = [original.identity.persistentId]; envelope.aliasTargets = [replacement.identity.persistentId]; probe.targetObject = null; @@ -62,7 +64,12 @@ public void ElementPropertyAliasesRejectCollisionsMissingTargetsAndMalformedMeta Assert.Null(probe.targetObject); void Restore() - => SceneElementSerialization.RestoreState(probe, m_serialization.Serialize(envelope, m_serializationContext), m_serialization, assets); + => SceneElementSerialization.RestoreState( + probe, + m_serialization.Serialize(envelope, m_serializationContext), + m_serialization, + assets + ); } [Fact] @@ -75,10 +82,21 @@ public void ElementPropertyRestoreRejectsReferencesOfTheWrongCurrentComponentTyp probe.targetComponent = probe; IAssetReferenceResolver assets = m_serializationContext.GetRequired(); PropertyElementEnvelope envelope = m_serialization.Deserialize( - SceneElementSerialization.CaptureState(target, m_serialization, assets), m_serializationContext); - envelope.properties = ScenePropertySerialization.CaptureProperty(probe, nameof(PropertyReferenceProbe.targetComponent), m_serialization, assets); + SceneElementSerialization.CaptureState(target, m_serialization, assets), + m_serializationContext + ); + envelope.properties = ScenePropertySerialization.CaptureProperty( + probe, + nameof(PropertyReferenceProbe.targetComponent), + m_serialization, + assets + ); Exception failure = Assert.ThrowsAny(() => SceneElementSerialization.RestoreState( - target, m_serialization.Serialize(envelope, m_serializationContext), m_serialization, assets)); + target, + m_serialization.Serialize(envelope, m_serializationContext), + m_serialization, + assets + )); Assert.Contains("targetComponent", failure.ToString()); Assert.Null(target.targetComponent); } @@ -99,12 +117,19 @@ public void PropertyRestoreRejectsAnInvalidReferenceKindBeforeAssigningTheTarget token.kind = int.MaxValue; byte[] invalid = m_serialization.Serialize(token, m_serializationContext); Assert.Equal(original.Length, invalid.Length); - byte[] payload = ScenePropertySerialization.CaptureProperty(probe, nameof(PropertyReferenceProbe.targetComponent), m_serialization, assets); + byte[] payload = ScenePropertySerialization.CaptureProperty( + probe, + nameof(PropertyReferenceProbe.targetComponent), + m_serialization, + assets + ); int offset = payload.AsSpan().IndexOf(original); Assert.True(offset >= 0, "The public property document did not contain its independently encoded value."); invalid.CopyTo(payload.AsSpan(offset, invalid.Length)); probe.targetComponent = null; - Exception failure = Assert.ThrowsAny(() => ScenePropertySerialization.RestoreProperties(probe, payload, m_serialization, assets)); + Exception failure = Assert.ThrowsAny( + () => ScenePropertySerialization.RestoreProperties(probe, payload, m_serialization, assets) + ); Assert.Contains("not a GameComponent reference", failure.ToString()); Assert.Null(probe.targetComponent); } diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs index bf0f24e98..0338113b1 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs @@ -1,10 +1,10 @@ using System; using System.Linq; +using Xunit; using Inno.Assets; using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Extensibility.Types; -using Xunit; namespace Inno.Scene.Tests; @@ -18,18 +18,26 @@ public void ScalarPropertyPreparationDoesNotAllocateAnIndexOfUnrelatedSceneObjec IAssetReferenceResolver assets = m_serializationContext.GetRequired(); long small = Measure(); for (int index = 0; index < 5_000; index++) + { _ = scene.CreateObject("Unrelated " + index); + } long large = Measure(); - Assert.True(large <= small + 64 * 1024, - $"Ten scalar property captures allocated {small} bytes in a small Scene and {large} with 5,000 unrelated objects."); + Assert.True( + large <= small + 64 * 1024, + $"Ten scalar property captures allocated {small} bytes in a small Scene and {large} with 5,000 unrelated objects." + ); long Measure() { for (int index = 0; index < 10; index++) + { _ = ScenePropertySerialization.CapturePropertySnapshots(owner.transform, m_serialization, assets); + } long before = GC.GetAllocatedBytesForCurrentThread(); for (int index = 0; index < 10; index++) + { Assert.Equal(3, ScenePropertySerialization.CapturePropertySnapshots(owner.transform, m_serialization, assets).Count); + } return GC.GetAllocatedBytesForCurrentThread() - before; } } @@ -53,8 +61,11 @@ public void PropertyReferencesRestoreCurrentObjectComponentAndSystemInstancesAft Assert.True(SceneManager.UnloadScene(scene)); GameScene replacement = m_serialization.Deserialize(graph, m_serializationContext); SceneManager.LoadScene(replacement); - PropertyReferenceProbe restored = replacement.GetObjects().Single(value => value.name == "Owner").GetComponents() - .OfType().Single(); + PropertyReferenceProbe restored = replacement.GetObjects() + .Single(value => value.name == "Owner") + .GetComponents() + .OfType() + .Single(); GameObject current = replacement.GetObjects().Single(value => value.name == "Target"); restored.targetObject = null; restored.targetComponent = null; @@ -97,7 +108,12 @@ public void MissingPropertyTargetRejectsRestoreWithoutAssigningTheDestroyedObjec GameObject target = scene.CreateObject("Target"); probe.targetObject = target; IAssetReferenceResolver assets = m_serializationContext.GetRequired(); - byte[] property = ScenePropertySerialization.CaptureProperty(probe, nameof(PropertyReferenceProbe.targetObject), m_serialization, assets); + byte[] property = ScenePropertySerialization.CaptureProperty( + probe, + nameof(PropertyReferenceProbe.targetObject), + m_serialization, + assets + ); scene.DestroyObject(target); probe.targetObject = null; Assert.ThrowsAny(() => ScenePropertySerialization.RestoreProperties(probe, property, m_serialization, assets)); @@ -119,7 +135,12 @@ public void NestedPropertyReadsAndGetterFailuresRestoreTheOuterReferenceScope() IAssetReferenceResolver assets = m_serializationContext.GetRequired(); probe.beforeRead = () => { - byte[] value = ScenePropertySerialization.CaptureProperty(nested, nameof(ReferenceComponent.targetObject), m_serialization, assets); + byte[] value = ScenePropertySerialization.CaptureProperty( + nested, + nameof(ReferenceComponent.targetObject), + m_serialization, + assets + ); nested.targetObject = null; _ = ScenePropertySerialization.RestoreProperties(nested, value, m_serialization, assets); Assert.NotNull(nested.targetObject); @@ -150,7 +171,7 @@ public int trigger beforeRead?.Invoke(); return 0; } - set { } + set {} } [SerializableProperty] diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs index 180d8b25a..ad98c6ac1 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs @@ -1,17 +1,15 @@ using System; using System.Linq; using System.Runtime.CompilerServices; - +using Xunit; using Inno.Core.Mathematics; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; -using Xunit; - namespace Inno.Scene.Tests; [Collection(SceneTestsCollection.NAME)] @@ -76,7 +74,8 @@ public void SceneRoundtrip_PreservesHierarchyOrderStateAndDirectReferences() byte[] bytes = m_serialization.Serialize(source, m_serializationContext); Assert.Contains( m_types.GetSubTypesOf(), - type => type.Resolve(m_types).Name == "GameSceneConverter"); + type => type.Resolve(m_types).Name == "GameSceneConverter" + ); SceneManager.LoadScene(source); Assert.True(SceneManager.UnloadScene(source)); @@ -94,8 +93,10 @@ public void SceneRoundtrip_PreservesHierarchyOrderStateAndDirectReferences() Assert.Equal(new GameLayer(7), restoredChild.layer); Assert.Same(restoredRoot, restored.FindObjectWithLayer(new GameLayer(3))); Assert.Same(restoredRoot, restored.FindObjectWithTag("Player")); - Assert.Equal(new[] { typeof(Transform), typeof(ReferenceComponent) }, - restoredRoot.GetComponents().Select(static component => component.GetType())); + Assert.Equal( + new[] { typeof(Transform), typeof(ReferenceComponent) }, + restoredRoot.GetComponents().Select(static component => component.GetType()) + ); Assert.Same(restoredRoot.transform, restoredChild.transform.parent); Assert.Equal(new Vector3(1, 2, 3), restoredChild.transform.localPosition); Assert.False(restoredChild.activeSelf); @@ -158,7 +159,8 @@ public void PrefabInstantiation_RemapsIdentitiesAndIsolatesInternalReferences() Assert.NotSame(firstReference.targetObject, secondReference.targetObject); Assert.NotEqual( firstReference.targetComponent!.identity.persistentId, - secondReference.targetComponent!.identity.persistentId); + secondReference.targetComponent!.identity.persistentId + ); } [Fact] @@ -181,10 +183,12 @@ public void SceneRoundtripPreservesManualComponentAndSystemOrder() Assert.Equal( [typeof(OrderComponentB), typeof(OrderComponentA), typeof(Transform)], - Assert.Single(restored.GetObjects()).GetComponents().Select(static component => component.GetType())); + Assert.Single(restored.GetObjects()).GetComponents().Select(static component => component.GetType()) + ); Assert.Equal( [typeof(OrderSerializationSystemB), typeof(OrderSerializationSystemA)], - restored.GetSystems().Select(static system => system.GetType())); + restored.GetSystems().Select(static system => system.GetType()) + ); } [Fact] @@ -239,7 +243,8 @@ public void PrefabCapture_RejectsReferenceOutsideCapturedSubtreeWithDiagnosticCo root.AddComponent().targetObject = external; InvalidOperationException exception = Assert.Throws( - () => m_serialization.Serialize(root, m_serializationContext)); + () => m_serialization.Serialize(root, m_serializationContext) + ); Assert.Contains(typeof(ReferenceComponent).FullName!, exception.Message); Assert.Contains("targetObject", exception.Message); diff --git a/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs b/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs index aa302dda4..029f41978 100644 --- a/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs +++ b/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs @@ -1,17 +1,15 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; -using Inno.Extensibility.Modules; using Inno.Core.Diagnostics; using Inno.Core.Identity; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; - -using Xunit; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; namespace Inno.Scene.Tests; @@ -26,7 +24,8 @@ public sealed class SceneTestsFixture : IDisposable private readonly string m_cacheDirectory = Path.Combine( Path.GetTempPath(), "InnoSceneTests", - Guid.NewGuid().ToString("N")); + Guid.NewGuid().ToString("N") + ); public ModuleHost modules { get; } public TypeCatalog types { get; } @@ -42,7 +41,9 @@ public SceneTestsFixture() { _ = typeof(Inno.Scene.SceneAsset); modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(SceneTestsCollection).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(SceneTestsCollection).Assembly) + }); types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); world = new Inno.Scene.SceneWorld(identities, types); @@ -58,7 +59,9 @@ public void Dispose() modules.Dispose(); logs.Dispose(); if (Directory.Exists(m_cacheDirectory)) + { Directory.Delete(m_cacheDirectory, recursive: true); + } } private sealed class RejectingAssetReferenceResolver : IAssetReferenceResolver @@ -68,8 +71,7 @@ public AssetObject Resolve( Guid stableTypeId, string lastKnownPath, Type expectedType, - string propertyPath) - => throw new InvalidOperationException( - $"Unexpected asset reference '{persistentId:D}' at '{propertyPath}'."); + string propertyPath + ) => throw new InvalidOperationException($"Unexpected asset reference '{persistentId:D}' at '{propertyPath}'."); } } diff --git a/tests/scene/Inno.Scene.Tests/TransformTests.cs b/tests/scene/Inno.Scene.Tests/TransformTests.cs index 94bb15c27..a86c80317 100644 --- a/tests/scene/Inno.Scene.Tests/TransformTests.cs +++ b/tests/scene/Inno.Scene.Tests/TransformTests.cs @@ -1,11 +1,9 @@ using System; - +using Xunit; using Inno.Core.Mathematics; using Inno.Scene; using Inno.Scene.Components; -using Xunit; - namespace Inno.Scene.Tests; [Collection(SceneTestsCollection.NAME)] @@ -156,10 +154,13 @@ public void TransformPoint_UsesExactRotatedNonUniformParentHierarchy() child.localScale = new Vector3(2f, 1.5f, 1f); var localPoint = new Vector3(0.3f, -0.6f, 0f); - Vector3 expected = Vector3.Transform(localPoint, parent.localToWorldMatrix + Vector3 expected = Vector3.Transform( + localPoint, + parent.localToWorldMatrix * Matrix.CreateTranslation(child.localPosition) * Matrix.CreateFromQuaternion(child.localRotation) - * Matrix.CreateScale(child.localScale)); + * Matrix.CreateScale(child.localScale) + ); Vector3 actual = child.TransformPoint(localPoint); AssertEqualWithTolerance(expected, actual, 1e-5f); @@ -197,8 +198,11 @@ public void WorldToLocal_RejectsNonInvertibleZeroScaleHierarchy() Assert.Throws(() => transform.InverseTransformPoint(Vector3.ONE)); } - private static void AssertEqualWithTolerance(Vector3 expected, Vector3 actual, float tolerance) - { + private static void AssertEqualWithTolerance( + Vector3 expected, + Vector3 actual, + float tolerance + ) { float deltaX = expected.x - actual.x; float deltaY = expected.y - actual.y; float deltaZ = expected.z - actual.z; @@ -207,8 +211,11 @@ private static void AssertEqualWithTolerance(Vector3 expected, Vector3 actual, f Assert.True(distance <= tolerance); } - private static void AssertEqualWithTolerance(Quaternion expected, Quaternion actual, float tolerance) - { + private static void AssertEqualWithTolerance( + Quaternion expected, + Quaternion actual, + float tolerance + ) { float deltaX = expected.x - actual.x; float deltaY = expected.y - actual.y; float deltaZ = expected.z - actual.z; diff --git a/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneComponent.cs b/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneComponent.cs index d3c78ca2e..2f2250b2a 100644 --- a/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneComponent.cs +++ b/tests/scene/fixtures/Inno.Scene.Reload.TestModule/ReloadableSceneComponent.cs @@ -34,6 +34,8 @@ public sealed class ReloadableSceneComponent : GameComponent private void ValidateRestoredState() { if (rejectRestore) + { throw new InvalidOperationException("Component state rejected restoration."); + } } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs index d25ae3b23..1d66d60f2 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Inno.Assets; using Inno.Assets.Pipeline; @@ -16,12 +15,14 @@ internal sealed class ControlledSampleAssetImporter : AssetImporter /// /// Creates a discoverable importer that uses only test-owned synchronization state. /// - public ControlledSampleAssetImporter() + public ControlledSampleAssetImporter() {} + + internal static Control? current { + get => m_current.Value; + set => m_current.Value = value; } - internal static Control? current { get => m_current.Value; set => m_current.Value = value; } - /// /// Gets the unique source extension used by the real importer cancellation test. /// diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs index 32129455d..09cf10acd 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs @@ -1,6 +1,5 @@ using System; using System.Threading; - using Inno.Assets.Pipeline; namespace Inno.Editor.Scripting.Tests; @@ -14,22 +13,28 @@ internal sealed class ControlledSampleSourceRewriter : IAssetSampleSourceRewrite /// /// Captures the current test-owned control through the real source rewriter discovery contract. /// - public ControlledSampleSourceRewriter() + public ControlledSampleSourceRewriter() {} + + internal static Control? current { + get => m_current.Value; + set => m_current.Value = value; } - internal static Control? current { get => m_current.Value; set => m_current.Value = value; } - /// public void Transform(AssetSampleTransformContext context) { if (m_control is null) + { return; + } m_control.workerThread = Environment.CurrentManagedThreadId; m_control.started.Set(); using CancellationTokenRegistration cancellation = context.cancellationToken.Register(m_control.canceled.Set); if (!m_control.release.Wait(TimeSpan.FromSeconds(15))) + { throw new TimeoutException("The test-owned source rewriter was not released."); + } context.cancellationToken.ThrowIfCancellationRequested(); } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs index 7515204d2..53458af30 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs @@ -1,29 +1,31 @@ -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; -using ImGuiTableRowFlags = Inno.Editor.ImGui.ImGuiTableRowFlags; -using ImGuiStyleVar = Inno.Editor.ImGui.ImGuiStyleVar; -using ImGuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; -using ImGuiCond = Inno.Editor.ImGui.ImGuiCond; -using ImGuiCol = Inno.Editor.ImGui.ImGuiCol; -using ImGuiChildFlags = Inno.Editor.ImGui.ImGuiChildFlags; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; +using System.Runtime.CompilerServices; +using BGCS.Runtime; +using Xunit; using Inno.Editor.ImGui; using Inno.Native.ImGui; + using EditorImGui = Inno.Editor.ImGui.ImGui; +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; +using ImGuiChildFlags = Inno.Editor.ImGui.ImGuiChildFlags; +using ImGuiCol = Inno.Editor.ImGui.ImGuiCol; +using ImGuiCond = Inno.Editor.ImGui.ImGuiCond; +using ImGuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; +using ImGuiStyleVar = Inno.Editor.ImGui.ImGuiStyleVar; +using ImGuiTableRowFlags = Inno.Editor.ImGui.ImGuiTableRowFlags; +using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using InlineRenameResult = Inno.Editor.ImGui.ImGuiWidget.InlineRenameResult; +using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; using TreeNodeOptions = Inno.Editor.ImGui.ImGuiWidget.TreeNodeOptions; using TreeNodeResult = Inno.Editor.ImGui.ImGuiWidget.TreeNodeResult; -using NativeImGui = Inno.Native.ImGui.ImGui; -using Xunit; namespace Inno.Editor.Scripting.Tests; + public sealed unsafe class EditorStyleMetricsTests { [Fact] @@ -93,7 +95,9 @@ public void WrappedTextRendersThroughTheSafeLiteralTextPath() using NativeStringLease nativeTestText0 = Utf8Codec.EncodeNullTerminated("Wrapped Text Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText0.pointer, null, 0); float lineHeight = NativeImGui.GetTextLineHeight(); - EditorUI.current.widgets.WrappedText("Literal %s text remains safe and wraps. This deliberately long compilation status " + "must stay inside the modal content width instead of extending beyond its right edge."); + EditorUI.current.widgets.WrappedText( + "Literal %s text remains safe and wraps. This deliberately long compilation status " + "must stay inside the modal content width instead of extending beyond its right edge." + ); Assert.True(NativeImGui.GetItemRectSize().Y > lineHeight); Inno.Native.ImGui.ImDrawList* windowDrawList = NativeImGui.Raw.GetWindowDrawList(); Inno.Native.ImGui.ImDrawList* foregroundDrawList = NativeImGui.Raw.GetForegroundDrawList(NativeImGui.Raw.GetMainViewport()); @@ -147,7 +151,9 @@ public void CenteredWrappedTextStaysInsidePaddingAndUsesMultipleLines() { ImDrawVert vertex = drawList->VtxBuffer.Data[i]; if (vertex.Col != textColor) + { continue; + } minimum = Vector2.Min(minimum, Unsafe.BitCast(vertex.Pos)); maximum = Vector2.Max(maximum, Unsafe.BitCast(vertex.Pos)); } @@ -212,7 +218,11 @@ public void InlineRenameIsCenteredAndSelectsTheCompleteValueWhenFocused() Assert.Equal(0, NativeImGui.Raw.GetSelectionStart(inputState)); Assert.Equal(value.Length, NativeImGui.Raw.GetSelectionEnd(inputState)); uint navCursorColor = NativeImGui.GetColorU32((int)(ImGuiCol.NavCursor)); - AssertDrawListDoesNotContainColor(NativeImGui.Raw.GetWindowDrawList(), navCursorColor, "The inline rename focus outline was submitted to the window draw list."); + AssertDrawListDoesNotContainColor( + NativeImGui.Raw.GetWindowDrawList(), + navCursorColor, + "The inline rename focus outline was submitted to the window draw list." + ); AssertColorBoundsStayCloseToItem( NativeImGui.Raw.GetForegroundDrawList(NativeImGui.Raw.GetMainViewport()), navCursorColor, @@ -254,7 +264,13 @@ void Frame() NativeImGui.SetNextWindowSize(new Vector2(320f, 180f), (int)(ImGuiCond.Always)); using NativeStringLease nativeTestText4 = Utf8Codec.EncodeNullTerminated("Inline Rename Context Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText4.pointer, null, 0); - result = EditorUI.current.widgets.InlineRename("created_asset", ref value, ref requestFocus, NativeImGui.GetFrameHeight(), width: 220f); + result = EditorUI.current.widgets.InlineRename( + "created_asset", + ref value, + ref requestFocus, + NativeImGui.GetFrameHeight(), + width: 220f + ); center = (NativeImGui.GetItemRectMin() + NativeImGui.GetItemRectMax()) * 0.5f; NativeImGui.End(); NativeImGui.Render(); @@ -305,7 +321,13 @@ public void InlineRenameCentersWithinTheNativeTableRowBounds() ImGuiTable* table = NativeImGui.Raw.GetCurrentTable(); Vector2 cursor = NativeImGui.GetCursorScreenPos(); NativeImGui.SetCursorScreenPos(new Vector2(cursor.X, table->RowPosY1)); - _ = EditorUI.current.widgets.InlineRename("table_scene", ref value, ref requestFocus, table->RowPosY2 - table->RowPosY1, width: 180f); + _ = EditorUI.current.widgets.InlineRename( + "table_scene", + ref value, + ref requestFocus, + table->RowPosY2 - table->RowPosY1, + width: 180f + ); Vector2 fieldMin = NativeImGui.GetItemRectMin(); Vector2 fieldMax = NativeImGui.GetItemRectMax(); Assert.True(fieldMin.Y >= table->RowPosY1); @@ -344,8 +366,7 @@ public void TreeGuideDepthRemainsBalancedAcrossSupportedZoomLevels() 1.5f } - ) - { + ) { _ = EditorUI.current.widgets.style.SetZoom(zoom); EditorUI.current.widgets.SetupStyle(); DrawTreeFrame(); @@ -379,7 +400,9 @@ public void MenuSelectorPopupIsBoundedAndScrollsLongContent() using NativeStringLease nativeTestText6 = Utf8Codec.EncodeNullTerminated("Menu Selector Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText6.pointer, null, 0); if (frame == 0) + { NativeImGui.OpenPopup("##menu_selector_popup_test"); + } Assert.True(EditorUI.current.widgets.BeginMenuSelector("test", "Untagged", 180f, 240f)); ImGuiWindowFlags flags = (ImGuiWindowFlags)NativeImGui.Raw.GetCurrentWindow()->Flags; Assert.True(flags.HasFlag(ImGuiWindowFlags.AlwaysAutoResize)); @@ -392,11 +415,17 @@ public void MenuSelectorPopupIsBoundedAndScrollsLongContent() _ = EditorImGui.InputTextWithHint("##new_tag", "Add tag...", ref newTag, 128); float inputCenterY = (NativeImGui.GetItemRectMin().Y + NativeImGui.GetItemRectMax().Y) * 0.5f; NativeImGui.SameLine(0f, -1f); - _ = EditorUI.current.widgets.ClickableText("add_tag", "+", new Vector2(EditorUI.current.widgets.GetCompactIconSize().X, NativeImGui.GetFrameHeight())); + _ = EditorUI.current.widgets.ClickableText( + "add_tag", + "+", + new Vector2(EditorUI.current.widgets.GetCompactIconSize().X, NativeImGui.GetFrameHeight()) + ); float actionCenterY = (NativeImGui.GetItemRectMin().Y + NativeImGui.GetItemRectMax().Y) * 0.5f; Assert.Equal(inputCenterY, actionCenterY, 3); for (int index = 0; index < 64; index++) + { NativeImGui.Selectable($"Entry {index:D2}"); + } if (frame == 1) { Assert.True(NativeImGui.GetWindowSize().Y <= io->DisplaySize.Y + 1f); @@ -436,10 +465,14 @@ public void SmallMenuSelectorDoesNotReserveAScrollbar() using NativeStringLease nativeTestText7 = Utf8Codec.EncodeNullTerminated("Small Menu Selector Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText7.pointer, null, 0); if (frame == 0) + { NativeImGui.OpenPopup("##menu_selector_popup_small"); + } Assert.True(EditorUI.current.widgets.BeginMenuSelector("small", "Current", 180f, 240f)); for (int index = 0; index < 3; index++) + { NativeImGui.Selectable($"Entry {index}"); + } if (frame == 2) { Assert.False((NativeImGui.Raw.GetCurrentWindow()->ScrollbarY != 0)); @@ -478,7 +511,9 @@ public void SmallContextMenuDoesNotReserveScrollbars() _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText8.pointer, null, 0); NativeImGui.Selectable("Target"); if (frame == 0) + { NativeImGui.OpenPopup("context"); + } Assert.True(EditorUI.current.widgets.BeginContextMenu("context")); NativeImGui.MenuItem("Rename", string.Empty, false, true); NativeImGui.MenuItem("Delete", string.Empty, false, true); @@ -537,7 +572,9 @@ public void BoundedComboPopupUsesTheSharedScrollingContract() string search = string.Empty; _ = EditorUI.current.widgets.SearchInput("assets", "Search assets...", ref search); for (int index = 0; index < 64; index++) + { NativeImGui.Selectable($"project:Material{index:D2}"); + } popupWidths.Add(NativeImGui.GetWindowSize().X); if (openFrames >= 2) { @@ -664,9 +701,17 @@ public void ChildGuideRetainsAVisualGapBelowTheParentWithoutChangingCompactRowHe _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText10.pointer, null, 0); float expectedHeight = NativeImGui.GetTextLineHeight(); EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult parent = EditorUI.current.widgets.TreeNode("connected_parent", static _ => NativeImGui.TextUnformatted("Parent"), new TreeNodeOptions()); + TreeNodeResult parent = EditorUI.current.widgets.TreeNode( + "connected_parent", + static _ => NativeImGui.TextUnformatted("Parent"), + new TreeNodeOptions() + ); Assert.True(parent.isOpen); - TreeNodeResult child = EditorUI.current.widgets.TreeNode("connected_child", static _ => NativeImGui.TextUnformatted("Child"), new TreeNodeOptions { isLeaf = true }); + TreeNodeResult child = EditorUI.current.widgets.TreeNode( + "connected_child", + static _ => NativeImGui.TextUnformatted("Child"), + new TreeNodeOptions { isLeaf = true } + ); NativeImGui.TreePop(); Assert.Equal(expectedHeight, parent.max.Y - parent.min.Y, 3); Assert.Equal(expectedHeight, child.max.Y - child.min.Y, 3); @@ -702,10 +747,18 @@ public void TreeGuidesAreDrawnFromTheCurrentFrameWhileDragging() ImGuiNativeContext* currentContext = NativeImGui.Raw.GetCurrentContext(); currentContext->DragDropActive = 1; EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult root = EditorUI.current.widgets.TreeNode("drag_root", static _ => NativeImGui.TextUnformatted("Assets"), new TreeNodeOptions()); + TreeNodeResult root = EditorUI.current.widgets.TreeNode( + "drag_root", + static _ => NativeImGui.TextUnformatted("Assets"), + new TreeNodeOptions() + ); if (root.isOpen) { - _ = EditorUI.current.widgets.TreeNode("drag_child", static _ => NativeImGui.TextUnformatted("Scene"), new TreeNodeOptions { isLeaf = true }); + _ = EditorUI.current.widgets.TreeNode( + "drag_child", + static _ => NativeImGui.TextUnformatted("Scene"), + new TreeNodeOptions { isLeaf = true } + ); NativeImGui.TreePop(); } @@ -764,7 +817,11 @@ public void TreeRowsRetainTheirCompactContentHeight() using NativeStringLease nativeTestText12 = Utf8Codec.EncodeNullTerminated("Compact Tree Row Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText12.pointer, null, 0); float expectedHeight = NativeImGui.GetTextLineHeight(); - TreeNodeResult row = EditorUI.current.widgets.TreeNode("compact_row", static _ => NativeImGui.TextUnformatted("GameObject"), new TreeNodeOptions { isLeaf = true }); + TreeNodeResult row = EditorUI.current.widgets.TreeNode( + "compact_row", + static _ => NativeImGui.TextUnformatted("GameObject"), + new TreeNodeOptions { isLeaf = true } + ); Assert.Equal(expectedHeight, row.max.Y - row.min.Y, 3); NativeImGui.End(); NativeImGui.Render(); @@ -841,23 +898,41 @@ private static void DrawTreeFrame(bool assertContinuousGuides = false) using NativeStringLease nativeTestText13 = Utf8Codec.EncodeNullTerminated("Tree Zoom Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText13.pointer, null, 0); EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult root = EditorUI.current.widgets.TreeNode("root", static _ => NativeImGui.TextUnformatted("Assets"), new TreeNodeOptions()); + TreeNodeResult root = EditorUI.current.widgets.TreeNode( + "root", + static _ => NativeImGui.TextUnformatted("Assets"), + new TreeNodeOptions() + ); if (root.isOpen) { EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult folder = EditorUI.current.widgets.TreeNode("folder", static _ => NativeImGui.TextUnformatted("Scene"), new TreeNodeOptions()); + TreeNodeResult folder = EditorUI.current.widgets.TreeNode( + "folder", + static _ => NativeImGui.TextUnformatted("Scene"), + new TreeNodeOptions() + ); if (folder.isOpen) { - _ = EditorUI.current.widgets.TreeNode("nested-file", static _ => NativeImGui.TextUnformatted("TestScene1.iscene"), new TreeNodeOptions { isLeaf = true }); + _ = EditorUI.current.widgets.TreeNode( + "nested-file", + static _ => NativeImGui.TextUnformatted("TestScene1.iscene"), + new TreeNodeOptions { isLeaf = true } + ); NativeImGui.TreePop(); } - _ = EditorUI.current.widgets.TreeNode("sibling-folder", static _ => NativeImGui.TextUnformatted("Settings"), new TreeNodeOptions { isLeaf = true }); + _ = EditorUI.current.widgets.TreeNode( + "sibling-folder", + static _ => NativeImGui.TextUnformatted("Settings"), + new TreeNodeOptions { isLeaf = true } + ); NativeImGui.TreePop(); } if (assertContinuousGuides) + { AssertCurrentDrawListContainsTreeGuideColor(); + } NativeImGui.End(); NativeImGui.Render(); } @@ -869,10 +944,18 @@ private static TreeNodeResult DrawDoubleClickTreeFrame() NativeImGui.SetNextWindowSize(new Vector2(320f, 240f), (int)(ImGuiCond.Always)); using NativeStringLease nativeTestText14 = Utf8Codec.EncodeNullTerminated("Double Click Tree Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText14.pointer, null, 0); - TreeNodeResult result = EditorUI.current.widgets.TreeNode("double_click_parent", static _ => NativeImGui.TextUnformatted("Parent"), new TreeNodeOptions()); + TreeNodeResult result = EditorUI.current.widgets.TreeNode( + "double_click_parent", + static _ => NativeImGui.TextUnformatted("Parent"), + new TreeNodeOptions() + ); if (result.isOpen) { - _ = EditorUI.current.widgets.TreeNode("double_click_child", static _ => NativeImGui.TextUnformatted("Child"), new TreeNodeOptions { isLeaf = true }); + _ = EditorUI.current.widgets.TreeNode( + "double_click_child", + static _ => NativeImGui.TextUnformatted("Child"), + new TreeNodeOptions { isLeaf = true } + ); NativeImGui.TreePop(); } @@ -887,9 +970,17 @@ private static void DrawTreeOverflowFrame(bool assertRanges) NativeImGui.SetNextWindowSize(new Vector2(560f, 320f), (int)(ImGuiCond.Always)); using NativeStringLease nativeTestText15 = Utf8Codec.EncodeNullTerminated("Tree Overflow Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText15.pointer, null, 0); - if (NativeImGui.BeginChild("##short_tree", new Vector2(220f, 100f), (int)(ImGuiChildFlags.None), (int)(ImGuiWindowFlags.HorizontalScrollbar))) - { - _ = EditorUI.current.widgets.TreeNode("short", static _ => NativeImGui.TextUnformatted("Object"), new TreeNodeOptions { isLeaf = true }); + if (NativeImGui.BeginChild( + "##short_tree", + new Vector2(220f, 100f), + (int)(ImGuiChildFlags.None), + (int)(ImGuiWindowFlags.HorizontalScrollbar) + )) { + _ = EditorUI.current.widgets.TreeNode( + "short", + static _ => NativeImGui.TextUnformatted("Object"), + new TreeNodeOptions { isLeaf = true } + ); if (assertRanges) { Assert.Equal(0f, NativeImGui.GetScrollMaxX(), 3); @@ -899,8 +990,12 @@ private static void DrawTreeOverflowFrame(bool assertRanges) } NativeImGui.EndChild(); - if (NativeImGui.BeginChild("##long_tree", new Vector2(220f, 100f), (int)(ImGuiChildFlags.None), (int)(ImGuiWindowFlags.HorizontalScrollbar))) - { + if (NativeImGui.BeginChild( + "##long_tree", + new Vector2(220f, 100f), + (int)(ImGuiChildFlags.None), + (int)(ImGuiWindowFlags.HorizontalScrollbar) + )) { _ = EditorUI.current.widgets.TreeNode( "long", static _ => NativeImGui.TextUnformatted("Object_With_A_Name_That_Is_Intentionally_Wider_Than_The_Tree_Viewport"), @@ -928,8 +1023,12 @@ bool assertGeometry using NativeStringLease nativeTestText16 = Utf8Codec.EncodeNullTerminated("Scrolled Tree Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText16.pointer, null, 0); NativeImGui.SetNextWindowScroll(new Vector2(requestedScroll, 0f)); - if (NativeImGui.BeginChild("##scrolled_tree", new Vector2(220f, 120f), (int)(ImGuiChildFlags.None), (int)(ImGuiWindowFlags.HorizontalScrollbar))) - { + if (NativeImGui.BeginChild( + "##scrolled_tree", + new Vector2(220f, 120f), + (int)(ImGuiChildFlags.None), + (int)(ImGuiWindowFlags.HorizontalScrollbar) + )) { Vector2 contentCursor = default; TreeNodeResult row = EditorUI.current.widgets.TreeNode("scrolled", _ => { @@ -961,17 +1060,29 @@ bool assertNoOverflow using NativeStringLease nativeTestText17 = Utf8Codec.EncodeNullTerminated("Resizable Tree Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText17.pointer, null, 0); NativeImGui.SetNextWindowScroll(new Vector2(requestedScroll, 0f)); - if (NativeImGui.BeginChild("##resizable_tree", new Vector2(width, 120f), (int)(ImGuiChildFlags.None), (int)(ImGuiWindowFlags.HorizontalScrollbar))) - { - _ = EditorUI.current.widgets.TreeNode("resizable_row", static _ => NativeImGui.TextUnformatted("GameObject"), new TreeNodeOptions { isLeaf = true, drawViewportOverlay = static () => - { - ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); - Vector2 overlaySize = new(NativeImGui.GetFontSize(), NativeImGui.GetTextLineHeight()); - NativeImGui.SameLine(0f, -1f); - Vector2 cursor = NativeImGui.GetCursorScreenPos(); - NativeImGui.SetCursorScreenPos(new Vector2(MathF.Max(cursor.X, window->WorkRect.Max.X - overlaySize.X), cursor.Y)); - NativeImGui.Dummy(overlaySize); - } }); + if (NativeImGui.BeginChild( + "##resizable_tree", + new Vector2(width, 120f), + (int)(ImGuiChildFlags.None), + (int)(ImGuiWindowFlags.HorizontalScrollbar) + )) { + _ = EditorUI.current.widgets.TreeNode( + "resizable_row", + static _ => NativeImGui.TextUnformatted("GameObject"), + new TreeNodeOptions + { + isLeaf = true, + drawViewportOverlay = static () => + { + ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); + Vector2 overlaySize = new(NativeImGui.GetFontSize(), NativeImGui.GetTextLineHeight()); + NativeImGui.SameLine(0f, -1f); + Vector2 cursor = NativeImGui.GetCursorScreenPos(); + NativeImGui.SetCursorScreenPos(new Vector2(MathF.Max(cursor.X, window->WorkRect.Max.X - overlaySize.X), cursor.Y)); + NativeImGui.Dummy(overlaySize); + } + } + ); if (assertNoOverflow) { Assert.Equal(0f, NativeImGui.GetScrollX(), 3); @@ -1030,8 +1141,14 @@ Vector2 size NativeImGui.TreePop(); } - AssertCurrentDrawListContainsColor(NativeImGui.ColorConvertFloat4ToU32(EditorPalette.title), "The current frame did not submit the Scene row background."); - AssertCurrentDrawListContainsColor(NativeImGui.GetColorU32((int)(ImGuiCol.Header)), "The current frame did not submit the selected row highlight."); + AssertCurrentDrawListContainsColor( + NativeImGui.ColorConvertFloat4ToU32(EditorPalette.title), + "The current frame did not submit the Scene row background." + ); + AssertCurrentDrawListContainsColor( + NativeImGui.GetColorU32((int)(ImGuiCol.Header)), + "The current frame did not submit the selected row highlight." + ); NativeImGui.End(); NativeImGui.Render(); } @@ -1044,7 +1161,9 @@ string failureMessage for (int i = 0; i < drawList->VtxBuffer.Size; i++) { if (drawList->VtxBuffer.Data[i].Col == color) + { return; + } } Assert.Fail(failureMessage); @@ -1058,7 +1177,9 @@ string failureMessage for (int i = 0; i < drawList->VtxBuffer.Size; i++) { if (drawList->VtxBuffer.Data[i].Col == color) + { Assert.Fail(failureMessage); + } } } @@ -1075,7 +1196,9 @@ float maximumExpansion { ImDrawVert vertex = drawList->VtxBuffer.Data[i]; if (vertex.Col != color) + { continue; + } colorMin = Vector2.Min(colorMin, Unsafe.BitCast(vertex.Pos)); colorMax = Vector2.Max(colorMax, Unsafe.BitCast(vertex.Pos)); } @@ -1102,7 +1225,9 @@ uint color { ImDrawVert vertex = drawList->VtxBuffer.Data[i]; if (vertex.Col != color) + { continue; + } minimumX = MathF.Min(minimumX, vertex.Pos.X); maximumX = MathF.Max(maximumX, vertex.Pos.X); } @@ -1150,8 +1275,14 @@ private static void DrawInspectorCardBody(bool assertHorizontalRange) { if (assertHorizontalRange) { - Assert.Equal(EditorUI.current.widgets.style.windowPadding, Unsafe.BitCast(NativeImGui.Raw.GetCurrentWindow()->WindowPadding)); - Assert.Equal(NativeImGui.GetWindowPos() + EditorUI.current.widgets.style.windowPadding, NativeImGui.GetCursorScreenPos()); + Assert.Equal( + EditorUI.current.widgets.style.windowPadding, + Unsafe.BitCast(NativeImGui.Raw.GetCurrentWindow()->WindowPadding) + ); + Assert.Equal( + NativeImGui.GetWindowPos() + EditorUI.current.widgets.style.windowPadding, + NativeImGui.GetCursorScreenPos() + ); } EditorUI.current.widgets.LabelChip("Tag", new Vector4(0.34f, 0.29f, 0.44f, 1f)); @@ -1159,14 +1290,18 @@ private static void DrawInspectorCardBody(bool assertHorizontalRange) NativeImGui.SameLine(0f, 0f); NativeImGui.Dummy(new Vector2(80f, NativeImGui.GetFrameHeight())); if (assertHorizontalRange) + { Assert.Equal(tagMaximumX, NativeImGui.GetItemRectMin().X, 3); + } NativeImGui.SameLine(0f, EditorUI.current.widgets.style.headerSectionSpacing); EditorUI.current.widgets.LabelChip("Layer", new Vector4(0.24f, 0.34f, 0.40f, 1f)); float layerMaximumX = NativeImGui.GetItemRectMax().X; NativeImGui.SameLine(0f, 0f); NativeImGui.Dummy(new Vector2(80f, NativeImGui.GetFrameHeight())); if (assertHorizontalRange) + { Assert.Equal(layerMaximumX, NativeImGui.GetItemRectMin().X, 3); + } bool open = EditorUI.current.widgets.CollapsingCard( "long_behavior", "BehaviorWithAnIntentionallyLongTypeNameThatMustBeClipped", @@ -1182,7 +1317,9 @@ private static void DrawInspectorCardBody(bool assertHorizontalRange) static () => EditorUI.current.widgets.PropertyRow( "long_property", "Property With A Very Long Display Name", - static () => NativeImGui.Dummy(new Vector2(MathF.Max(1f, NativeImGui.GetContentRegionAvail().X), NativeImGui.GetFrameHeight())) + static () => NativeImGui.Dummy( + new Vector2(MathF.Max(1f, NativeImGui.GetContentRegionAvail().X), NativeImGui.GetFrameHeight()) + ) ) ); NativeImGui.Indent(); @@ -1191,10 +1328,14 @@ private static void DrawInspectorCardBody(bool assertHorizontalRange) } if (assertHorizontalRange) + { Assert.Equal(0f, NativeImGui.GetScrollMaxX(), 3); + } }); if (assertHorizontalRange) + { Assert.Equal(0f, NativeImGui.GetScrollMaxX(), 3); + } } NativeImGui.EndChild(); diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportCompositionTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportCompositionTests.cs index d14cf281a..1e1ae555e 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportCompositionTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportCompositionTests.cs @@ -1,10 +1,8 @@ using System; using System.Collections.Generic; - +using Xunit; using Inno.Editor.Rendering; using Inno.Rendering; - -using Xunit; using Inno.Rendering.Runtime; namespace Inno.Editor.Scripting.Tests; @@ -23,13 +21,15 @@ public void CompositionCanonicalizesModelLayersByOrderAndStableIdentity() 1280, 720, RenderTextureFormat.RGBA8Srgb, - new[] { overlay, baseB, baseA }); + new[] { overlay, baseB, baseA } + ); Assert.Collection( composition.layers, layer => Assert.Same(baseA, layer), layer => Assert.Same(baseB, layer), - layer => Assert.Same(overlay, layer)); + layer => Assert.Same(overlay, layer) + ); } [Fact] @@ -42,7 +42,8 @@ public void CompositionSnapshotsTheCallerCollection() 640, 360, RenderTextureFormat.RGBA8Srgb, - source); + source + ); source.Clear(); @@ -59,13 +60,15 @@ public void CompositionRejectsEmptyNullAndDuplicateModelLayers() 64, 64, RenderTextureFormat.RGBA8Srgb, - Array.Empty())); + Array.Empty() + )); Assert.Throws(() => new EditorViewportComposition( "tests.null", 64, 64, RenderTextureFormat.RGBA8Srgb, - new EditorViewportLayer[] { null! })); + new EditorViewportLayer[] { null! } + )); var first = new EditorViewportLayer("tests.duplicate", null, new RenderFrameData(), 0); var second = new EditorViewportLayer("tests.duplicate", null, new RenderFrameData(), 1000); @@ -74,6 +77,7 @@ public void CompositionRejectsEmptyNullAndDuplicateModelLayers() 64, 64, RenderTextureFormat.RGBA8Srgb, - new[] { first, second })); + new[] { first, second } + )); } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportNavigationTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportNavigationTests.cs index af3b1c2a4..dfa51a3d9 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportNavigationTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/EditorViewportNavigationTests.cs @@ -1,10 +1,8 @@ using System; - +using Xunit; using Inno.Core.Mathematics; using Inno.Editor.Rendering; -using Xunit; - namespace Inno.Editor.Scripting.Tests; public sealed class EditorViewportNavigationTests @@ -15,12 +13,14 @@ public void Profile_RejectsDefaultModeMissingFromCapabilities() Assert.Throws(() => new EditorViewportNavigationProfile( new EditorViewportNavigationProfileId("tests.navigation.invalid-default"), EditorViewportNavigationCapabilities.Pan, - EditorViewportNavigationMode.Fly)); + EditorViewportNavigationMode.Fly + )); _ = new EditorViewportNavigationProfile( new EditorViewportNavigationProfileId("tests.navigation.pan-only"), EditorViewportNavigationCapabilities.Pan, - EditorViewportNavigationMode.Planar); + EditorViewportNavigationMode.Planar + ); } [Fact] @@ -34,7 +34,8 @@ public void ConfigurePerspective_IsAtomicWhenValidationFails() Quaternion.FromEulerAnglesXYZDegrees(new Vector3(10f, 20f, 30f)), 200f, 0.1f, - 1000f)); + 1000f + )); Assert.Equal(EditorViewportProjection.Orthographic, state.projection); Assert.Equal(new Vector3(2f, 3f, 4f), state.position); @@ -47,9 +48,7 @@ public void State_RejectsUndefinedProjectionAndMode() { var state = new EditorViewportNavigationState(); - Assert.Throws(() => - state.projection = (EditorViewportProjection)100); - Assert.Throws(() => - state.mode = (EditorViewportNavigationMode)100); + Assert.Throws(() => state.projection = (EditorViewportProjection)100); + Assert.Throws(() => state.mode = (EditorViewportNavigationMode)100); } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs index 4d75bece3..c5402bbb7 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs @@ -1,29 +1,31 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using Inno.Native.ImGui; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; -using Inno.Extensibility.Modules; +using System.Runtime.CompilerServices; +using BGCS.Runtime; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Core.Logging; -using Inno.Extensibility.Types; using Inno.Core.Serialization; using Inno.Editor.Annotations; using Inno.Editor.Core; using Inno.Editor.ImGui; -using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; using Inno.Editor.Inspection; using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; +using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; using NativeImGui = Inno.Native.ImGui.ImGui; -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.Scripting.Tests; + public sealed class InspectionPipelineTests : IDisposable { private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoInspectionPipelineTests", Guid.NewGuid().ToString("N")); @@ -32,10 +34,13 @@ public sealed class InspectionPipelineTests : IDisposable private readonly SerializationRegistry m_serialization; private readonly LogRouter m_logs = new(); private readonly EditorInteractionRuntime m_runtime; + public InspectionPipelineTests() { Directory.CreateDirectory(m_projectRoot); - m_modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(InspectionPipelineTests).Assembly) }); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(InspectionPipelineTests).Assembly) } + ); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); m_runtime = new EditorInteractionRuntime( @@ -55,7 +60,9 @@ public void Dispose() m_modules.Dispose(); m_logs.Dispose(); if (Directory.Exists(m_projectRoot)) + { Directory.Delete(m_projectRoot, recursive: true); + } } [Fact] @@ -115,7 +122,13 @@ public unsafe void PanelWindowFailureStillEndsTheWindowAndAllowsLaterContent() using IDisposable uiScope = uiSession.Enter(); PrepareNativeFrame(); bool isOpen = true; - Assert.Throws(() => EditorUI.current.widgets.PanelWindow("Throwing Panel", ref isOpen, static () => throw new InvalidOperationException("panel"))); + Assert.Throws( + () => EditorUI.current.widgets.PanelWindow( + "Throwing Panel", + ref isOpen, + static () => throw new InvalidOperationException("panel") + ) + ); using NativeStringLease nativeTestText1 = Utf8Codec.EncodeNullTerminated("Content After Panel Failure", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, 0); NativeImGui.TextUnformatted("Still drawing."); @@ -174,7 +187,10 @@ public unsafe void PresentationAttributesComposeAndCustomDrawersRemainExtensible using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); var renderer = new SerializedPropertyRenderer(drawers, attributes, m_runtime.interactions, new NoopEditService(), m_logs); var owner = new AttributeOwner(); - SerializedProperty property = Assert.Single(m_serialization.GetProperties(owner), static candidate => candidate.name == nameof(AttributeOwner.value)); + SerializedProperty property = Assert.Single( + m_serialization.GetProperties(owner), + static candidate => candidate.name == nameof(AttributeOwner.value) + ); AttributeValueDrawer.observations.Clear(); ProbeInspectorAttributeDrawer.observations.Clear(); var nativeContext = NativeImGui.Raw.CreateContext(null); @@ -194,7 +210,10 @@ public unsafe void PresentationAttributesComposeAndCustomDrawersRemainExtensible NativeImGui.Raw.DestroyContext(nativeContext); } - Assert.Equal(["update:Friendly Value:False:2:8", "update:Friendly Value:False:2:8", "before", "after"], ProbeInspectorAttributeDrawer.observations); + Assert.Equal( + ["update:Friendly Value:False:2:8", "update:Friendly Value:False:2:8", "before", "after"], + ProbeInspectorAttributeDrawer.observations + ); Assert.Equal(["Friendly Value:False:2:8"], AttributeValueDrawer.observations); } @@ -257,6 +276,7 @@ internal sealed class InlineParent } internal sealed class InlineFailure; + internal sealed class TextStateOwner : ISerializable { [SerializableProperty] @@ -264,6 +284,7 @@ internal sealed class TextStateOwner : ISerializable } internal sealed record TextStateValue(string id); + internal sealed class AttributeOwner : ISerializable { internal bool showValue { get; set; } @@ -280,14 +301,18 @@ internal sealed class AttributeOwner : ISerializable } internal sealed class AttributeValue; + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] internal sealed class ProbeInspectorAttribute : InspectorPresentationAttribute; + [InspectorAttributeDrawer(typeof(ProbeInspectorAttribute), priority: 10_000)] internal sealed class ProbeInspectorAttributeDrawer : IInspectorAttributeDrawer { internal static List observations { get; } = []; - public void Update(InspectorAttributeDrawContext context) => observations.Add($"update:{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); + public void Update(InspectorAttributeDrawContext context) + => observations.Add($"update:{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); + public void DrawBefore(InspectorAttributeDrawContext context) { _ = context; @@ -306,7 +331,8 @@ internal sealed class AttributeValueDrawer : IPropertyDrawer { internal static List observations { get; } = []; - public void Draw(PropertyDrawContext context) => observations.Add($"{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); + public void Draw(PropertyDrawContext context) + => observations.Add($"{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); } [PropertyDrawer(typeof(TextStateValue), priority: 10_000)] @@ -327,12 +353,11 @@ public void Draw(PropertyDrawContext context) internal sealed class InlineParentDrawer : IPropertyDrawer { internal static bool drewAfterFailure; + public void Draw(PropertyDrawContext context) { var parent = (InlineParent)context.GetValue()!; - context.DrawInlineChild("child", typeof(InlineFailure), () => parent.child, static _ => - { - }, readOnly: true); + context.DrawInlineChild("child", typeof(InlineFailure), () => parent.child, static _ => {}, readOnly: true); drewAfterFailure = true; } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs index e65425f99..902106db2 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs @@ -1,24 +1,27 @@ -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using NativeVector4 = Inno.Native.ImGui.ImVec4C; -using BGCS.Runtime; using System; using System.Numerics; +using System.Runtime.CompilerServices; +using BGCS.Runtime; +using Xunit; using Inno.Editor.ImGui; using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; +using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using NativeImGui = Inno.Native.ImGui.ImGui; -using Xunit; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; +using NativeVector4 = Inno.Native.ImGui.ImVec4C; namespace Inno.Editor.Scripting.Tests; + [Trait("Acceptance", "Visual")] public sealed unsafe class InspectorPresentationLayoutTests : IDisposable { private readonly ImGuiNativeContext* m_context = NativeImGui.Raw.CreateContext(null); private readonly Inno.Editor.ImGui.EditorUiSession m_ui = new(); private readonly IDisposable m_uiScope; + public InspectorPresentationLayoutTests() { m_uiScope = m_ui.Enter(); @@ -99,7 +102,9 @@ void Frame() Frame(); NativeImGui.Raw.AddMousePosEvent(io, hover.X, hover.Y); for (int index = 0; index < 4; index++) + { Frame(); + } using NativeStringLease nativeTestText2 = Utf8Codec.EncodeNullTerminated("##Tooltip_00", allowsNull: false); ImGuiWindow* tooltip = NativeImGui.Raw.FindWindowByName((sbyte*)nativeTestText2.pointer); Assert.False((tooltip == null)); @@ -122,7 +127,11 @@ public void HelpBoxUsesWrappedCardHeightWithoutHorizontalOverflow() using NativeStringLease nativeTestText3 = Utf8Codec.EncodeNullTerminated("HelpBox acceptance", allowsNull: false); NativeImGui.Raw.Begin((sbyte*)nativeTestText3.pointer, null, 0); float width = NativeImGui.GetContentRegionAvail().X; - EditorUI.current.widgets.HelpBox("Assign a Sprite to enable atlas geometry, borders, pixel density, and sampling controls.", "i", EditorPalette.warning); + EditorUI.current.widgets.HelpBox( + "Assign a Sprite to enable atlas geometry, borders, pixel density, and sampling controls.", + "i", + EditorPalette.warning + ); Vector2 size = NativeImGui.GetItemRectSize(); Assert.Equal(width, size.X, 2); Assert.True(size.Y > NativeImGui.GetTextLineHeight() * 2); @@ -167,14 +176,20 @@ float framebufferScale { Vector2 point = new(window->Pos.X + window->Size.X * 0.47f, seam + sample * 0.1f); float coverage = CoverageAt(window->DrawList, point); - Assert.True(coverage >= 0.999f, $"Transparent title/body join: zoom={zoom}, scale={framebufferScale}, y={point.Y}, alpha={coverage}"); + Assert.True( + coverage >= 0.999f, + $"Transparent title/body join: zoom={zoom}, scale={framebufferScale}, y={point.Y}, alpha={coverage}" + ); } for (int pixel = -2; pixel <= 2; pixel++) { float y = (MathF.Floor(seam * framebufferScale) + pixel + 0.5f) / framebufferScale; Vector2 point = new(window->Pos.X + window->Size.X * 0.47f, y); - Assert.True(CoverageAt(window->DrawList, point) >= 0.999f, $"Transparent device pixel: zoom={zoom}, scale={framebufferScale}, y={y}"); + Assert.True( + CoverageAt(window->DrawList, point) >= 0.999f, + $"Transparent device pixel: zoom={zoom}, scale={framebufferScale}, y={y}" + ); } Assert.True(NativeImGui.Raw.GetStyle()->AntiAliasedFill != 0); @@ -191,7 +206,9 @@ Vector2 point ImDrawCmd command = list->CmdBuffer.Data[commandIndex]; Vector4 clip = Unsafe.BitCast(command.ClipRect); if (point.X < clip.X || point.X >= clip.Z || point.Y < clip.Y || point.Y >= clip.W) + { continue; + } for (uint index = command.IdxOffset; index < command.IdxOffset + command.ElemCount; index += 3) { ImDrawVert a = list->VtxBuffer.Data[(int)command.VtxOffset + list->IdxBuffer.Data[(int)index]]; @@ -202,12 +219,16 @@ Vector2 point Vector2 cPosition = Unsafe.BitCast(c.Pos); float area = Cross(bPosition - aPosition, cPosition - aPosition); if (MathF.Abs(area) < 0.000001f) + { continue; + } float wa = Cross(bPosition - point, cPosition - point) / area; float wb = Cross(cPosition - point, aPosition - point) / area; float wc = 1 - wa - wb; if (wa < 0 || wb < 0 || wc < 0) + { continue; + } float alpha = (wa * (a.Col >> 24) + wb * (b.Col >> 24) + wc * (c.Col >> 24)) / 255f; result = alpha + result * (1 - alpha); } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ProjectSettingsExecutionContextTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ProjectSettingsExecutionContextTests.cs index 9b5f2da65..3df9846ca 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ProjectSettingsExecutionContextTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ProjectSettingsExecutionContextTests.cs @@ -1,11 +1,10 @@ using System; using System.Threading.Tasks; - +using Xunit; using Inno.Core.Serialization; using Inno.Core.Settings; -using RuntimeSettings = Inno.Core.Settings.Settings; -using Xunit; +using RuntimeSettings = Inno.Core.Settings.Settings; namespace Inno.Editor.Scripting.Tests; @@ -32,7 +31,9 @@ public void NestedScopes_RestoreThePreviousSettingsLookup() { Assert.Equal(11, RuntimeSettings.Get(S_SETTING_ID).value); using (ProjectSettingsExecutionContext.EnterScope(inner)) + { Assert.Equal(22, RuntimeSettings.Get(S_SETTING_ID).value); + } Assert.Equal(11, RuntimeSettings.Get(S_SETTING_ID).value); } } @@ -83,12 +84,16 @@ public TSetting Get(ProjectSettingId id) where TSetting : class, ISerializable { if (typeof(TSetting) != typeof(TestSetting)) + { throw new InvalidOperationException("The requested test setting type is unsupported."); + } return (TSetting)(object)new TestSetting { value = value }; } - public bool TryGet(ProjectSettingId id, out TSetting? setting) - where TSetting : class, ISerializable + public bool TryGet( + ProjectSettingId id, + out TSetting? setting + ) where TSetting : class, ISerializable { setting = Get(id); return true; diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.Progress.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.Progress.cs index 29180f7de..64350a02b 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.Progress.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.Progress.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; +using Xunit; using Inno.Scripting.Compiler; using Inno.Scripting.Reload; -using Xunit; namespace Inno.Editor.Scripting.Tests; @@ -51,5 +51,6 @@ public void CompilationFailureDoesNotPublishSuccessfulWorkflowCompletion() } // Reload and fixture retirement must remain on their creating owner thread. - private static ScriptCompilationResult CompleteCompilationOnOwner(Task compilation) => compilation.GetAwaiter().GetResult(); + private static ScriptCompilationResult CompleteCompilationOnOwner(Task compilation) + => compilation.GetAwaiter().GetResult(); } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs index ad47add50..7de2fd212 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs @@ -1,12 +1,12 @@ using System; using System.Runtime.CompilerServices; +using Xunit; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Scripting.Compiler; using Inno.Scripting.Reload; -using Xunit; namespace Inno.Editor.Scripting.Tests; diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs index becba9147..e74f762a2 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs @@ -1,48 +1,51 @@ -using Inno.Core.Logging; -using Inno.Core.IO; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using Inno.Core.Diagnostics; -using Inno.Extensibility.Reload; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; -using Inno.Editor.Annotations; using System.IO.Compression; using System.Linq; -using System.Runtime.CompilerServices; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; +using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; +using Inno.Core.Diagnostics; +using Inno.Core.IO; using Inno.Core.Identity; +using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Editor.Annotations; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.PlayMode; using Inno.Editor.Scene; using Inno.Editor.Scripting; -using Inno.Plugins.Authoring; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; using Inno.Plugins; +using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; using Inno.Scripting.Compiler; using Inno.Scripting.Reload; -using Xunit; namespace Inno.Editor.Scripting.Tests; + public sealed partial class ScriptingPipelineTests : IDisposable { private readonly ScriptingFixture m_fixture = new(); + public void Dispose() => m_fixture.Dispose(); + [Theory] [InlineData(false)] [InlineData(true)] @@ -70,19 +73,35 @@ public void SourceLocalAssetPathsFollowInstalledPluginOwnership(bool runtimeDepl using var fixture = new ScriptingFixture(( root, serialization - ) => WritePluginPackage(root, "local-path.iplugin", serialization, new PluginManifest { - pluginId = "tests.local-path", - displayName = "Source Ownership Fixture" - }, new Dictionary { ["Assets/Nested.imeta"] = serialization.Serialize(new ScriptingAssetSourceMeta { persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.Directory }), ["Assets/Nested/SourceLocalPathProbe.cs"] = System.Text.Encoding.UTF8.GetBytes(""" + ) => WritePluginPackage( + root, + "local-path.iplugin", + serialization, + new PluginManifest + { + pluginId = "tests.local-path", + displayName = "Source Ownership Fixture" + }, + new Dictionary + { + ["Assets/Nested.imeta"] = serialization.Serialize( + new ScriptingAssetSourceMeta { persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.Directory } + ), + ["Assets/Nested/SourceLocalPathProbe.cs"] = System.Text.Encoding.UTF8.GetBytes(""" using InnoEngine.Assets; public static class SourceLocalPathProbe { public static AssetPath Resolve() => Assets.LocalPath("Materials/Default.imaterial"); } - """), ["Assets/Nested/SourceLocalPathProbe.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.NewGuid()) })); + """), + ["Assets/Nested/SourceLocalPathProbe.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.NewGuid()) + } + )); ScriptCompilationResult result = runtimeDeployment ? fixture.CompileRuntimeDeployment() : fixture.Compile(); Assert.True(result.success, FormatDiagnostics(result)); - string assemblyPath = Assert.Single(result.runtimeAssemblyPaths.Where(static path => Path.GetFileName(path).StartsWith("Inno.Plugin.", StringComparison.Ordinal))); + string assemblyPath = Assert.Single( + result.runtimeAssemblyPaths.Where(static path => Path.GetFileName(path).StartsWith("Inno.Plugin.", StringComparison.Ordinal)) + ); AssetPath path = InvokePublicPathProbe(assemblyPath); Assert.Equal(new AssetSourceId("tests.local-path"), path.source); Assert.Equal("Materials/Default.imaterial", path.localPath); @@ -104,7 +123,10 @@ public static class SourceLocalPathProbe string map = Assert.Single(project.Descendants("PathMap")).Value; Assert.Contains("Nested,,==Folder", map, StringComparison.Ordinal); Assert.Contains("project::./Nested,,==Folder", map, StringComparison.Ordinal); - Assert.Contains(project.Descendants("HintPath"), reference => ContainsCustomAttribute(Path.GetFullPath(reference.Value, m_fixture.projectRoot), "CallerFilePathAttribute")); + Assert.Contains( + project.Descendants("HintPath"), + reference => ContainsCustomAttribute(Path.GetFullPath(reference.Value, m_fixture.projectRoot), "CallerFilePathAttribute") + ); } [MethodImpl(MethodImplOptions.NoInlining)] @@ -115,10 +137,7 @@ private static AssetPath InvokePublicPathProbe(string assemblyPath) { using var stream = new MemoryStream(File.ReadAllBytes(assemblyPath)); var assembly = lifetime.LoadFromStream(stream); - Func resolve = assembly.GetType( - "SourceLocalPathProbe", - throwOnError: true - )!.GetMethod( + Func resolve = assembly.GetType("SourceLocalPathProbe", throwOnError: true)!.GetMethod( "Resolve", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static )!.CreateDelegate>(); @@ -148,7 +167,10 @@ public sealed class FrameworkReferenceProbe : GameBehavior using FileStream stream = File.OpenRead(Path.Combine(result.outputDirectory!, "Inno.GameScripts.dll")); using var executable = new PEReader(stream); MetadataReader metadata = executable.GetMetadataReader(); - Assert.DoesNotContain(metadata.AssemblyReferences, handle => metadata.GetString(metadata.GetAssemblyReference(handle).Name) == "System.Private.CoreLib"); + Assert.DoesNotContain( + metadata.AssemblyReferences, + handle => metadata.GetString(metadata.GetAssemblyReference(handle).Name) == "System.Private.CoreLib" + ); } [Theory] @@ -165,7 +187,10 @@ public static class IgnoredApiProbe """); ScriptCompilationResult result = runtimeDeployment ? m_fixture.CompileRuntimeDeployment() : m_fixture.Compile(); Assert.False(result.success); - Assert.Contains(result.diagnostics, static diagnostic => diagnostic.id == "CS1061" && diagnostic.message.Contains("CaptureFrom", StringComparison.Ordinal)); + Assert.Contains( + result.diagnostics, + static diagnostic => diagnostic.id == "CS1061" && diagnostic.message.Contains("CaptureFrom", StringComparison.Ordinal) + ); } [Fact] @@ -199,8 +224,7 @@ Action observer "Inno.EditorScripts.csproj" } - ) - { + ) { XDocument document = XDocument.Load(Path.Combine(m_fixture.projectRoot, project)); bool found = false; foreach (XElement reference in document.Descendants("HintPath")) @@ -212,8 +236,12 @@ Action observer { TypeDefinition type = metadata.GetTypeDefinition(handle); if (metadata.GetString(type.Namespace) != "InnoEngine.Events" || metadata.GetString(type.Name) != "EventDispatcher") + { continue; - found = type.GetEvents().Any(eventHandle => metadata.GetString(metadata.GetEventDefinition(eventHandle).Name) == "dispatched"); + } + found = type + .GetEvents() + .Any(eventHandle => metadata.GetString(metadata.GetEventDefinition(eventHandle).Name) == "dispatched"); } } @@ -341,9 +369,11 @@ bool ContainsShaderApi(string project) if (metadata.TypeDefinitions.Any(handle => { TypeDefinition type = metadata.GetTypeDefinition(handle); - return metadata.GetString(type.Namespace) == "InnoEditor.Rendering.Shaders" && metadata.GetString(type.Name) == "IShaderNodeCompiler"; - })) + return metadata.GetString(type.Namespace) == "InnoEditor.Rendering.Shaders" + && metadata.GetString(type.Name) == "IShaderNodeCompiler"; + })) { return true; + } } return false; @@ -471,7 +501,10 @@ public void RuntimeDeploymentCompilationDoesNotCompileOrValidateEditorSources() Assert.True(File.Exists(Path.Combine(result.outputDirectory!, "Inno.GameScripts.dll"))); Assert.False(File.Exists(Path.Combine(result.outputDirectory!, "Inno.EditorScripts.dll"))); Assert.DoesNotContain(result.moduleDeployments, static request => request.scope == AssemblyScope.Editor); - Assert.DoesNotContain(result.compiledAssemblyNames.Concat(result.reusedAssemblyNames), static assemblyName => assemblyName.Contains("Editor", StringComparison.Ordinal)); + Assert.DoesNotContain( + result.compiledAssemblyNames.Concat(result.reusedAssemblyNames), + static assemblyName => assemblyName.Contains("Editor", StringComparison.Ordinal) + ); } [Fact] @@ -521,8 +554,14 @@ public sealed class AttributedBehavior : GameBehavior using FileStream stream = File.OpenRead(playerAssembly); using var executable = new PEReader(stream); MetadataReader metadata = executable.GetMetadataReader(); - Assert.DoesNotContain(metadata.AssemblyReferences, handle => metadata.GetString(metadata.GetAssemblyReference(handle).Name).Contains("Editor", StringComparison.Ordinal)); - Assert.DoesNotContain(metadata.TypeDefinitions, handle => metadata.GetString(metadata.GetTypeDefinition(handle).Name) == "CustomPresentationAttribute"); + Assert.DoesNotContain( + metadata.AssemblyReferences, + handle => metadata.GetString(metadata.GetAssemblyReference(handle).Name).Contains("Editor", StringComparison.Ordinal) + ); + Assert.DoesNotContain( + metadata.TypeDefinitions, + handle => metadata.GetString(metadata.GetTypeDefinition(handle).Name) == "CustomPresentationAttribute" + ); } [Fact] @@ -611,11 +650,10 @@ public sealed class SecondaryProbe : GameBehavior Assert.False(result.success); Assert.Contains( result.diagnostics, - static diagnostic => diagnostic.id == "INNO2001" + static diagnostic => ( + diagnostic.id == "INNO2001" && diagnostic.severity == DiagnosticSeverity.Error - && diagnostic.message.Contains( - "SecondaryProbe", - StringComparison.Ordinal + && diagnostic.message.Contains("SecondaryProbe", StringComparison.Ordinal) ) ); } @@ -628,7 +666,10 @@ public void CachedCompilationReplaysWarningsAndReusesTheGeneration() ScriptCompilationResult second = m_fixture.Compile(); Assert.True(first.success, FormatDiagnostics(first)); Assert.True(second.success, FormatDiagnostics(second)); - ScriptDiagnostic firstWarning = Assert.Single(first.diagnostics, static diagnostic => diagnostic.id == "CS0169" && diagnostic.severity == DiagnosticSeverity.Warning); + ScriptDiagnostic firstWarning = Assert.Single( + first.diagnostics, + static diagnostic => diagnostic.id == "CS0169" && diagnostic.severity == DiagnosticSeverity.Warning + ); Assert.Contains(second.diagnostics, diagnostic => diagnostic == firstWarning); Assert.Equal(first.outputDirectory, second.outputDirectory); Assert.NotEmpty(second.reusedAssemblyNames); @@ -643,10 +684,12 @@ public void CompilerProgressIsMonotonicAndIncludesStageTimings() Assert.True(result.success, FormatDiagnostics(result)); Assert.NotEmpty(progress.values); Assert.All(progress.values, static value => Assert.InRange(value.fraction, 0f, 1f)); - Assert.True(progress.values.Zip(progress.values.Skip(1), static ( - left, - right - ) => right.fraction >= left.fraction).All(static value => value)); + Assert.True( + progress.values.Zip(progress.values.Skip(1), static ( + left, + right + ) => right.fraction >= left.fraction).All(static value => value) + ); Assert.NotEmpty(result.stageTimings); Assert.All(result.stageTimings, static timing => Assert.True(timing.elapsed >= TimeSpan.Zero)); } @@ -667,19 +710,26 @@ public void LogicalDocumentationProjectsNamespacesWithoutLosingMemberDescription { m_fixture.compiler.GenerateProjectFiles(); XDocument project = XDocument.Load(Path.Combine(m_fixture.projectRoot, "Inno.GameScripts.csproj")); - XElement[] members = project.Descendants("HintPath").Select(reference => Path.ChangeExtension(Path.GetFullPath(reference.Value, m_fixture.projectRoot), ".xml")).Where(File.Exists).SelectMany(path => XDocument.Load(path).Descendants("member")).ToArray(); + XElement[] members = project + .Descendants("HintPath") + .Select(reference => Path.ChangeExtension(Path.GetFullPath(reference.Value, m_fixture.projectRoot), ".xml")) + .Where(File.Exists) + .SelectMany(path => XDocument.Load(path).Descendants("member")) + .ToArray(); XElement manager = Assert.Single(members.Where(member => member.Attribute("name")?.Value == "T:InnoEngine.Scene.SceneManager")); Assert.Contains("scene operations", manager.Element("summary")!.Value, StringComparison.Ordinal); Assert.Contains(manager.Descendants("see"), reference => reference.Attribute("cref")?.Value == "T:InnoEngine.Scene.SceneWorld"); Assert.Contains( members, - member => member.Attribute("name")?.Value == "P:InnoEngine.Scene.SceneManager.activeScene" - && member.Element("summary")?.Value.Contains( - "active scene", - StringComparison.Ordinal - ) == true + member => ( + member.Attribute("name")?.Value == "P:InnoEngine.Scene.SceneManager.activeScene" + && member.Element("summary")?.Value.Contains("active scene", StringComparison.Ordinal) == true + ) + ); + Assert.DoesNotContain( + members, + member => member.Attribute("name")?.Value.StartsWith("T:Inno.Scene.", StringComparison.Ordinal) == true ); - Assert.DoesNotContain(members, member => member.Attribute("name")?.Value.StartsWith("T:Inno.Scene.", StringComparison.Ordinal) == true); } [Fact] @@ -737,7 +787,10 @@ public void InstalledPluginSampleImportsAsAnImmediatelyCompilableWritableCopy() ScriptCompilationResult authoring = fixture.Compile(); Assert.True(authoring.success, FormatDiagnostics(authoring)); Assert.Contains(authoring.compiledAssemblyNames, name => name.EndsWith(".Samples", StringComparison.Ordinal)); - Assert.DoesNotContain(authoring.runtimeAssemblyPaths, path => Path.GetFileNameWithoutExtension(path).EndsWith(".Samples", StringComparison.Ordinal)); + Assert.DoesNotContain( + authoring.runtimeAssemblyPaths, + path => Path.GetFileNameWithoutExtension(path).EndsWith(".Samples", StringComparison.Ordinal) + ); ScriptCompilationResult player = fixture.CompileRuntimeDeployment(); Assert.True(player.success, FormatDiagnostics(player)); Assert.DoesNotContain(player.compiledAssemblyNames, name => name.EndsWith(".Samples", StringComparison.Ordinal)); @@ -747,7 +800,10 @@ public void InstalledPluginSampleImportsAsAnImmediatelyCompilableWritableCopy() cancellationToken ) => { - ScriptCompilationResult candidate = await fixture.compiler.CompileAuthoringGenerationAsync(cancellationToken: cancellationToken, sourceSnapshot: sources); + ScriptCompilationResult candidate = await fixture.compiler.CompileAuthoringGenerationAsync( + cancellationToken: cancellationToken, + sourceSnapshot: sources + ); Assert.True(candidate.success, FormatDiagnostics(candidate)); }); Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); @@ -787,9 +843,14 @@ public void InvalidSampleScriptPreflightLeavesNoProjectCopy() cancellationToken ) => { - ScriptCompilationResult candidate = await fixture.compiler.CompileAuthoringGenerationAsync(cancellationToken: cancellationToken, sourceSnapshot: sources); + ScriptCompilationResult candidate = await fixture.compiler.CompileAuthoringGenerationAsync( + cancellationToken: cancellationToken, + sourceSnapshot: sources + ); if (!candidate.success) + { throw new InvalidOperationException(FormatDiagnostics(candidate)); + } }); Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); Assert.Throws(() => import.Commit()); @@ -894,20 +955,24 @@ public void SampleHistoryFinalizationFailureRollsBackWithoutPublication() public void SampleCopyCancellationLeavesNoProjectOrTransactionDirectory() { using var fixture = new ScriptingFixture(WriteSamplePlugin); - using AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + using AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport( + new AssetPath(new AssetSourceId("tests.samples"), "~Starter") + ); import.Cancel(); - Assert.True(SpinWait.SpinUntil(() => - { - try + Assert.True( + SpinWait.SpinUntil(() => { - import.Rollback(); - return true; - } - catch (Inno.Core.Execution.RetirementPendingException) - { - return false; - } - }, 15000)); + try + { + import.Rollback(); + return true; + } + catch (Inno.Core.Execution.RetirementPendingException) + { + return false; + } + }, 15000) + ); Assert.False(Directory.Exists(Path.Combine(fixture.projectRoot, "Assets", "~Starter"))); string transactions = Path.Combine(fixture.assets.libraryRoot, "AssetDatabase", "Transactions"); Assert.True(!Directory.Exists(transactions) || !Directory.EnumerateFileSystemEntries(transactions).Any()); @@ -920,23 +985,27 @@ public void PendingAutomaticCompilationDefersUntilSampleRollback() using var fixture = new ScriptingFixture(WriteSamplePlugin); using ScriptReloadHost reload = fixture.CreateReloadHost(autoCompile: true); reload.Start(); - using AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + using AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport( + new AssetPath(new AssetSourceId("tests.samples"), "~Starter") + ); Assert.False(reload.TryCompilePending(out Task? pending)); Assert.Null(pending); Assert.True(reload.isCompilationPending); import.Cancel(); - Assert.True(SpinWait.SpinUntil(() => - { - try - { - import.Rollback(); - return true; - } - catch (Inno.Core.Execution.RetirementPendingException) + Assert.True( + SpinWait.SpinUntil(() => { - return false; - } - }, 15000)); + try + { + import.Rollback(); + return true; + } + catch (Inno.Core.Execution.RetirementPendingException) + { + return false; + } + }, 15000) + ); Assert.True(reload.TryCompilePending(out Task? compilation)); Assert.True(SpinWait.SpinUntil(() => compilation!.IsCompleted, 15000)); Assert.True(compilation!.IsCompletedSuccessfully); @@ -951,7 +1020,9 @@ public void EditorSampleImportUsesSharedModalAndUndoRedo() runtime.Start(); IEditorScriptCompilation scripting = Assert.IsAssignableFrom(ScriptingCompilationProbe.compilation); WaitForInitialScriptCompilation(fixture, runtime, scripting); - Assert.True(fixture.assets.TryGetFileSystemEntry(new AssetPath(new AssetSourceId("tests.samples"), "~Starter"), out AssetFileEntry sample)); + Assert.True( + fixture.assets.TryGetFileSystemEntry(new AssetPath(new AssetSourceId("tests.samples"), "~Starter"), out AssetFileEntry sample) + ); Assert.True(runtime.interactions.For("panel/asset.file-browser", sample).Execute("file-browser/import-sample")); EditorModalExtension modal = runtime.modals.Single(value => value.id == "asset-sample-import.progress"); Assert.True(modal.TryGetPresentation(out EditorModalExtension.Presentation presentation)); @@ -961,7 +1032,12 @@ public void EditorSampleImportUsesSharedModalAndUndoRedo() EditorModalExtension compilationModal = runtime.modals.Single(value => value.id == "scripting.compilation"); Assert.True(compilationModal.TryGetPresentation(out EditorModalExtension.Presentation compilationPolicy)); Assert.Equal(compilationPolicy.allowScrolling, presentation.allowScrolling); - PumpEditorUntil(fixture, runtime, () => modal.TryGetPresentation(out EditorModalExtension.Presentation state) && !state.isVisible, () => scripting.progress.status); + PumpEditorUntil( + fixture, + runtime, + () => modal.TryGetPresentation(out EditorModalExtension.Presentation state) && !state.isVisible, + () => scripting.progress.status + ); Assert.True(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("~Starter"), out _)); Assert.True(runtime.interactions.history.Undo().succeeded); Assert.False(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("~Starter"), out _)); @@ -981,12 +1057,19 @@ public void SampleTransformRunsOnWorkerAndEditorStopRetainsPendingImport() ControlledSampleSourceRewriter.current = control; try { - Assert.True(fixture.assets.TryGetFileSystemEntry(new AssetPath(new AssetSourceId("tests.samples"), "~Starter"), out AssetFileEntry sample)); + Assert.True( + fixture.assets.TryGetFileSystemEntry( + new AssetPath(new AssetSourceId("tests.samples"), "~Starter"), + out AssetFileEntry sample + ) + ); Assert.True(runtime.interactions.For("panel/asset.file-browser", sample).Execute("file-browser/import-sample")); Assert.True(control.started.Wait(TimeSpan.FromSeconds(5))); Assert.NotEqual(Environment.CurrentManagedThreadId, control.workerThread); for (int frame = 0; frame < 30; frame++) + { runtime.Update(new EditorFrame(1f / 60f, frame / 60f, true)); + } Assert.False(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("~Starter"), out _)); Task shutdownObserver = Task.Run(() => { @@ -994,7 +1077,9 @@ public void SampleTransformRunsOnWorkerAndEditorStopRetainsPendingImport() { Assert.True(control.canceled.Wait(TimeSpan.FromSeconds(5))); Assert.True(fixture.assets.isInitialized); - Assert.Throws(() => fixture.host.modules.generations.EnsureReady("retire scripting before sample work")); + Assert.Throws( + () => fixture.host.modules.generations.EnsureReady("retire scripting before sample work") + ); } finally { @@ -1009,18 +1094,20 @@ public void SampleTransformRunsOnWorkerAndEditorStopRetainsPendingImport() { control.release.Set(); ControlledSampleSourceRewriter.current = null; - Assert.True(SpinWait.SpinUntil(() => - { - try - { - runtime.Dispose(); - return true; - } - catch (Inno.Core.Execution.RetirementPendingException) + Assert.True( + SpinWait.SpinUntil(() => { - return false; - } - }, 15000)); + try + { + runtime.Dispose(); + return true; + } + catch (Inno.Core.Execution.RetirementPendingException) + { + return false; + } + }, 15000) + ); } Assert.False(Directory.Exists(Path.Combine(fixture.projectRoot, "Assets", "~Starter"))); @@ -1044,7 +1131,14 @@ public void SampleDirectoryMetadataRemapsNestedImportSettingsIdentities() WritePluginPackageEntry( archive, "Assets/~Starter.imeta", - serialization.Serialize(new ScriptingAssetSourceMeta { persistentId = Guid.Parse("7726b1d2-9aee-4d2c-a865-2fd53155095f"), sourceKind = (int)AssetSourceKind.Directory, importerSettingsBytes = serialization.Serialize(new SampleIdentitySettings { referenceId = sourceId }) }) + serialization.Serialize( + new ScriptingAssetSourceMeta + { + persistentId = Guid.Parse("7726b1d2-9aee-4d2c-a865-2fd53155095f"), + sourceKind = (int)AssetSourceKind.Directory, + importerSettingsBytes = serialization.Serialize(new SampleIdentitySettings { referenceId = sourceId }) + } + ) ); }); using AssetSampleImportTransaction import = PrepareSample(fixture, new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); @@ -1054,8 +1148,12 @@ public void SampleDirectoryMetadataRemapsNestedImportSettingsIdentities() ) => { Assert.True(sources.TryGetInfo(AssetPath.Project("~Starter/StarterBehavior.cs"), out AssetInfo? info)); - ScriptingAssetSourceMeta metadata = fixture.host.serialization.Deserialize(File.ReadAllBytes(Path.Combine(fixture.projectRoot, "Assets", "~Starter.imeta"))); - SampleIdentitySettings settings = fixture.host.serialization.Deserialize(metadata.importerSettingsBytes); + ScriptingAssetSourceMeta metadata = fixture.host.serialization.Deserialize( + File.ReadAllBytes(Path.Combine(fixture.projectRoot, "Assets", "~Starter.imeta")) + ); + SampleIdentitySettings settings = fixture.host.serialization.Deserialize( + metadata.importerSettingsBytes + ); Assert.Equal(info!.persistentId, settings.referenceId); Assert.NotEqual(sourceId, settings.referenceId); return ValueTask.CompletedTask; @@ -1078,19 +1176,30 @@ public void SampleAssetPreimportRunsOnWorkerAndReceivesCancellation() WritePluginPackageEntry( package, "Assets/~Starter/Slow.samplebusy.imeta", - serialization.Serialize(new ScriptingAssetSourceMeta { persistentId = Guid.Parse("587849fc-777c-4501-a1b2-ec042ca40314"), sourceKind = (int)AssetSourceKind.File, importerId = "tests.scripting.controlled-sample-asset" }) + serialization.Serialize( + new ScriptingAssetSourceMeta + { + persistentId = Guid.Parse("587849fc-777c-4501-a1b2-ec042ca40314"), + sourceKind = (int)AssetSourceKind.File, + importerId = "tests.scripting.controlled-sample-asset" + } + ) ); }); using var control = new ControlledSampleAssetImporter.Control(); ControlledSampleAssetImporter.current = control; - AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport( + new AssetPath(new AssetSourceId("tests.samples"), "~Starter") + ); try { - Assert.True(SpinWait.SpinUntil(() => - { - Assert.False(import.Advance()); - return control.started.IsSet; - }, 15000)); + Assert.True( + SpinWait.SpinUntil(() => + { + Assert.False(import.Advance()); + return control.started.IsSet; + }, 15000) + ); Assert.NotEqual(Environment.CurrentManagedThreadId, control.workerThread); long revision = fixture.assets.revision; for (int frame = 0; frame < 30; frame++) @@ -1128,7 +1237,11 @@ public void SampleCompilerReferencePreparationRunsOnWorker() cancellationToken ) => { - ScriptCompilationResult result = await fixture.compiler.CompileAuthoringGenerationAsync(progress, cancellationToken, sources).ConfigureAwait(false); + ScriptCompilationResult result = await fixture.compiler.CompileAuthoringGenerationAsync( + progress, + cancellationToken, + sources + ).ConfigureAwait(false); Assert.True(result.success, FormatDiagnostics(result)); }); Assert.True(progress.started.Wait(TimeSpan.FromSeconds(5))); @@ -1162,7 +1275,9 @@ public void SampleCompilerReferencePreparationRunsOnWorker() public void SampleIndexingDoesNotWaitForWatcherQuietPeriod(bool commit) { using var fixture = new ScriptingFixture(WriteSamplePlugin, enableFileSystemWatcher: true, fileWatcherFlushDelayMs: 3000); - AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(new AssetPath(new AssetSourceId("tests.samples"), "~Starter")); + AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport( + new AssetPath(new AssetSourceId("tests.samples"), "~Starter") + ); try { TimeSpan maximumAdvance = TimeSpan.Zero; @@ -1171,11 +1286,16 @@ public void SampleIndexingDoesNotWaitForWatcherQuietPeriod(bool commit) Stopwatch frame = Stopwatch.StartNew(); bool ready = import.Advance(); if (frame.Elapsed > maximumAdvance) + { maximumAdvance = frame.Elapsed; + } return ready; }, 15000); Assert.True(indexed); - Assert.True(maximumAdvance < TimeSpan.FromSeconds(2), $"Owner-thread Advance waited {maximumAdvance} with a three-second watcher quiet period."); + Assert.True( + maximumAdvance < TimeSpan.FromSeconds(2), + $"Owner-thread Advance waited {maximumAdvance} with a three-second watcher quiet period." + ); fixture.Write("External.txt", "Changed while watching was paused."); Assert.False(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("External.txt"), out _)); if (commit) @@ -1188,7 +1308,9 @@ public void SampleIndexingDoesNotWaitForWatcherQuietPeriod(bool commit) import.Commit(); } else + { new Inno.Core.Execution.RetirementBarrier("Test canceled watched sample").Wait(import.Rollback); + } fixture.assets.Update(); Assert.True(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("External.txt"), out _)); Assert.Equal(commit, fixture.assets.TryGetFileSystemEntry(AssetPath.Project("~Starter"), out _)); @@ -1248,9 +1370,14 @@ public void SourceArtifactsAreCatalogedButRuntimeExportContainsNoSourceFiles() Assert.True(m_fixture.assets.TryGetArtifact(info.persistentId, "source", out AssetArtifactInfo? source)); Assert.NotNull(source); using (ArtifactLease encoded = m_fixture.assets.AcquireArtifact(info.persistentId, "source")) + { Assert.NotEmpty(encoded.ReadAllBytes()); + } Assert.Equal(0, exported.assetCount); - Assert.DoesNotContain(Directory.EnumerateFiles(contentRoot, "*", SearchOption.AllDirectories), static path => path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)); + Assert.DoesNotContain( + Directory.EnumerateFiles(contentRoot, "*", SearchOption.AllDirectories), + static path => path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) + ); } [Fact] @@ -1354,7 +1481,11 @@ public sealed class ReloadableBehavior : GameBehavior Assert.True(secondResult.success, FormatDiagnostics(secondResult)); Assert.True(reload.ApplyPendingReload()); Type currentType = m_fixture.ResolveActiveType("ReloadableBehavior"); - GameComponent current = Assert.Single(gameObject.GetComponents().Where(component => string.Equals(component.GetType().Name, "ReloadableBehavior", StringComparison.Ordinal))); + GameComponent current = Assert.Single( + gameObject + .GetComponents() + .Where(component => string.Equals(component.GetType().Name, "ReloadableBehavior", StringComparison.Ordinal)) + ); Assert.Same(currentType, current.GetType()); Assert.Equal(41, currentType.GetProperty("retained")!.GetValue(current)); Assert.Equal(2, currentType.GetProperty("added")!.GetValue(current)); @@ -1404,7 +1535,11 @@ public sealed class DependentBehavior : GameBehavior { if (updateInPlace) { - WriteUnavailableGenerationPlugin(fixture.projectRoot, fixture.host.serialization, "this Plugin update is deliberately invalid C#"); + WriteUnavailableGenerationPlugin( + fixture.projectRoot, + fixture.host.serialization, + "this Plugin update is deliberately invalid C#" + ); } else { @@ -1416,19 +1551,30 @@ public sealed class DependentBehavior : GameBehavior Assert.False(unavailable.success); Assert.Contains(unavailable.diagnostics, static diagnostic => diagnostic.severity == DiagnosticSeverity.Error); Assert.True(reload.ApplyPendingReload()); - Assert.DoesNotContain(fixture.host.modules.modules, static module => module.domain is AssemblyDomain.InnoPlugin or AssemblyDomain.InnoScripting); + Assert.DoesNotContain( + fixture.host.modules.modules, + static module => module.domain is AssemblyDomain.InnoPlugin or AssemblyDomain.InnoScripting + ); Assert.Equal(updateInPlace ? 1 : 0, fixture.activePlugins.Count); - MissingGameComponent missingPlugin = Assert.IsType(state.pluginOwner.GetComponents().Single(component => component is not Transform)); - MissingGameComponent missingScript = Assert.IsType(state.scriptOwner.GetComponents().Single(component => component is not Transform)); + MissingGameComponent missingPlugin = Assert.IsType( + state.pluginOwner.GetComponents().Single(component => component is not Transform) + ); + MissingGameComponent missingScript = Assert.IsType( + state.scriptOwner.GetComponents().Single(component => component is not Transform) + ); Assert.Equal(state.pluginComponentId, missingPlugin.identity.persistentId); Assert.Equal(state.scriptComponentId, missingScript.identity.persistentId); Assert.Equal("UnavailabilityPlugin.PluginBehavior", missingPlugin.missingTypeName); Assert.Equal("DependentBehavior", missingScript.missingTypeName); CompleteUnloadVerification(reload); if (updateInPlace) + { File.WriteAllBytes(installedPlugin, validPluginPackage); + } else + { File.Move(detachedPlugin, installedPlugin); + } Assert.True(fixture.RefreshPlugins()); ScriptCompilationResult recoveredCompilation = fixture.CompilePendingPluginReload(reload); Assert.True(recoveredCompilation.success, FormatDiagnostics(recoveredCompilation)); @@ -1537,7 +1683,9 @@ public void PluginRemovalUnloadsTheCommittedMissingGenerationWithoutASecondReloa Assert.False(expectation.retiredComponent.IsAlive, "The retired Plugin component remained strongly reachable."); Assert.False(expectation.retiredType.IsAlive, "The retired Plugin runtime Type remained strongly reachable."); Assert.DoesNotContain(fixture.host.modules.modules, static module => module.domain == AssemblyDomain.InnoPlugin); - MissingGameComponent missing = Assert.IsType(expectation.owner.GetComponents().Single(component => component is not Transform)); + MissingGameComponent missing = Assert.IsType( + expectation.owner.GetComponents().Single(component => component is not Transform) + ); Assert.Equal(expectation.componentId, missing.identity.persistentId); Assert.Equal("UnavailabilityPlugin.PluginBehavior", missing.missingTypeName); } @@ -1557,10 +1705,13 @@ public void PluginReloadWaitsForPlaySessionRetirementBeforeActivatingItsAssembly var history = new CountingHistoryIsolation(); using var playMode = new EditorPlayModeController( fixture.host, - new RuntimeSessionOptions { + new RuntimeSessionOptions + { kind = RuntimeSessionKind.Play, applicationId = "tests.scripting.play-reload", - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(fixture.projectRoot, "Persistent", "tests.scripting.play-reload"), "Logs")), + createLogSink = _ => new FileLogSink( + Path.Combine(Path.Combine(fixture.projectRoot, "Persistent", "tests.scripting.play-reload"), "Logs") + ), jobExecutionMode = RuntimeJobExecutionMode.SingleThread, referenceResolvers = [fixture.assets] }, @@ -1654,7 +1805,13 @@ protected override async ValueTask ImportAsync( Assert.True(fixture.assets.TryGetInfo(persistentId, out AssetInfo? preserved)); Assert.Equal(AssetImportStatus.Imported, preserved!.status); Assert.Equal(stableTypeId, preserved.stableAssetTypeId); - AssetObject missing = ((IAssetReferenceResolver)fixture.assets).Resolve(persistentId, stableTypeId, "Content/value.shutdownasset", typeof(AssetObject), "$test"); + AssetObject missing = ((IAssetReferenceResolver)fixture.assets).Resolve( + persistentId, + stableTypeId, + "Content/value.shutdownasset", + typeof(AssetObject), + "$test" + ); Assert.True(missing.isMissing); Assert.Equal(persistentId, missing.identity.persistentId); } @@ -1692,10 +1849,13 @@ public void ContentPlayStopReloadPlaySoakRetiresEverySessionBeforeTheNextGenerat var history = new CountingHistoryIsolation(); using var play = new EditorPlayModeController( fixture.host, - new RuntimeSessionOptions { + new RuntimeSessionOptions + { kind = RuntimeSessionKind.Play, applicationId = "tests.content-soak", - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(fixture.projectRoot, "Persistent", "tests.content-soak"), "Logs")), + createLogSink = _ => new FileLogSink( + Path.Combine(Path.Combine(fixture.projectRoot, "Persistent", "tests.content-soak"), "Logs") + ), jobExecutionMode = RuntimeJobExecutionMode.SingleThread, referenceResolvers = [fixture.assets] }, @@ -1712,7 +1872,9 @@ public void ContentPlayStopReloadPlaySoakRetiresEverySessionBeforeTheNextGenerat play.AdvanceTransition(); Assert.True(play.state == EditorPlayModeState.Playing, play.lastFailure); for (int frame = 0; frame < 60; frame++) + { play.Tick(1f / 60f); + } Assert.True(play.ExitPlayMode()); play.AdvanceTransition(); play.AdvanceTransition(); @@ -1739,7 +1901,10 @@ public void AutomaticPublicationDoesNotQueueItselfButExternalMountChangesStillDo reload.Start(); Assert.True(m_fixture.CompilePending(reload).success); Assert.True(reload.ApplyPendingReload()); - Assert.False(reload.isCompilationPending, "Publishing this script generation must not queue another generation from its own catalog notification."); + Assert.False( + reload.isCompilationPending, + "Publishing this script generation must not queue another generation from its own catalog notification." + ); CompleteUnloadVerification(reload); m_fixture.assets.ReplaceSourceMounts(m_fixture.assets.sourceMounts); Assert.True(reload.isCompilationPending, "An external source-mount publication must still invalidate scripting inputs."); @@ -1770,13 +1935,24 @@ public void EditorAutomaticCompilationClosesModalAndTicketWaitsForRetirement() m_fixture.WriteVersionedBehavior(2); m_fixture.Rescan(); IScriptCompilationTicket ticket = scripting.RequestCompilation(); - PumpEditorUntil(m_fixture, runtime, () => m_fixture.host.modules.generations.state == GenerationState.AwaitingCollection, () => scripting.progress.status); + PumpEditorUntil( + m_fixture, + runtime, + () => m_fixture.host.modules.generations.state == GenerationState.AwaitingCollection, + () => scripting.progress.status + ); Assert.Equal(ScriptCompilationTicketState.Compiling, ticket.state); Assert.False(ticket.isCompleted); retained.Clear(); // Publication readiness may be advanced by another host boundary before the next editor update. m_fixture.host.modules.generations.Wait(); - PumpEditorUntil(m_fixture, runtime, () => scripting.state == EditorScriptCompilationState.Ready && ticket.isCompleted, () => scripting.progress.status, focused: false); + PumpEditorUntil( + m_fixture, + runtime, + () => scripting.state == EditorScriptCompilationState.Ready && ticket.isCompleted, + () => scripting.progress.status, + focused: false + ); Assert.Equal(ScriptCompilationTicketState.Succeeded, ticket.state); AssertCompilationModalHidden(runtime); Assert.Equal(2, ReadVersion(m_fixture.ResolveActiveType("VersionedBehavior"))); @@ -1820,7 +1996,9 @@ public void EditorQueuesLatestAutomaticChangeWithoutReplacingAcceptedTicketWhile { fixture.assets.Update(); using (fixture.editorSession.EnterExecutionScope()) + { runtime.Update(new EditorFrame(1f / 60f, frame / 60f, true)); + } Thread.Sleep(5); } @@ -1844,6 +2022,7 @@ public void EditorQueuesLatestAutomaticChangeWithoutReplacingAcceptedTicketWhile [MethodImpl(MethodImplOptions.NoInlining)] private static int ReadLatestVersion(ScriptingFixture fixture) => ReadVersion(fixture.ResolveActiveType("VersionedBehavior")); + private sealed class DeferredReloadGuard : IEditorReloadGuard { internal bool isBlocked { get; set; } = true; @@ -1854,6 +2033,7 @@ private sealed class DeferredReloadGuard : IEditorReloadGuard [MethodImpl(MethodImplOptions.NoInlining)] private static List RetainActiveScriptType(ScriptingFixture fixture) => [fixture.ResolveActiveType("VersionedBehavior")]; + private static void AssertCompilationModalHidden(EditorInteractionRuntime runtime) { EditorModalExtension modal = runtime.modals.Single(value => value.id == "scripting.compilation"); @@ -1898,7 +2078,9 @@ private static void PumpEditorUntil( Assert.True(Environment.TickCount64 - started < timeoutMilliseconds, status()); fixture.assets.Update(); using (fixture.editorSession.EnterExecutionScope()) + { runtime.Update(new EditorFrame(1f / 60f, frame++ / 60f, focused)); + } Thread.Sleep(5); } } @@ -1922,7 +2104,9 @@ public void NewCompilationTicketSupersedesTheExactPreviousRequest() [Fact] public void FailedResultHasNoActivationOrRuntimeArtifacts() { - ScriptCompilationResult result = ScriptCompilationResult.Failure(new ScriptDiagnostic("INNO-TEST", DiagnosticSeverity.Error, "Injected compilation failure.", filePath: null, line: 0, column: 0)); + ScriptCompilationResult result = ScriptCompilationResult.Failure( + new ScriptDiagnostic("INNO-TEST", DiagnosticSeverity.Error, "Injected compilation failure.", filePath: null, line: 0, column: 0) + ); Assert.False(result.success); Assert.Null(result.outputDirectory); Assert.Empty(result.moduleDeployments); @@ -1979,14 +2163,21 @@ GameScene scene GameComponent scriptComponent = scriptOwner.AddComponent(scriptType); pluginType.GetProperty("retained")!.SetValue(pluginComponent, 47); scriptType.GetProperty("retained")!.SetValue(scriptComponent, 73); - return new AvailabilitySceneState(pluginOwner, scriptOwner, pluginComponent.identity.persistentId, scriptComponent.identity.persistentId); + return new AvailabilitySceneState( + pluginOwner, + scriptOwner, + pluginComponent.identity.persistentId, + scriptComponent.identity.persistentId + ); } private static void CompleteUnloadVerification(ScriptReloadHost reload) { Exception? failure = null; while (!reload.AdvanceUnloadVerification(out failure)) + { Thread.Yield(); + } Assert.Null(failure); } @@ -2015,7 +2206,10 @@ RuntimeSession session Assert.True(reload.ApplyPendingReload()); Assert.DoesNotContain( fixture.host.modules.modules, - static module => module.domain == AssemblyDomain.InnoPlugin || module.upstreamModuleNames.Contains("Plugin.tests.unavailability", StringComparer.Ordinal) + static module => ( + module.domain == AssemblyDomain.InnoPlugin + || module.upstreamModuleNames.Contains("Plugin.tests.unavailability", StringComparer.Ordinal) + ) ); return new MissingGenerationExpectation(owner, componentId, new WeakReference(component), new WeakReference(pluginType)); } @@ -2033,16 +2227,19 @@ private readonly record struct MissingGenerationExpectation( WeakReference retiredComponent, WeakReference retiredType ); + private readonly record struct RetiredScriptObject( WeakReference type, WeakReference component ); + private readonly record struct AvailabilitySceneState( GameObject pluginOwner, GameObject scriptOwner, Guid pluginComponentId, Guid scriptComponentId ); + private static void WriteProjectionPlugin( string projectRoot, SerializationRegistry serialization @@ -2061,7 +2258,8 @@ public sealed class ProjectionRuntime : GameBehavior "projection.iplugin", serialization, new PluginManifest { pluginId = "tests.projection", displayName = "Projection Plugin" }, - new Dictionary { + new Dictionary + { ["Assets/ProjectionRuntime.cs"] = System.Text.Encoding.UTF8.GetBytes(c_source), ["Assets/ProjectionRuntime.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.NewGuid()) } @@ -2085,6 +2283,7 @@ public sealed class PluginBehavior : GameBehavior public int retained { get; set; } = 5; } """); + private static void WriteUnavailableGenerationPlugin( string projectRoot, SerializationRegistry serialization, @@ -2095,9 +2294,13 @@ string source "unavailability.iplugin", serialization, new PluginManifest { pluginId = "tests.unavailability", displayName = "Unavailability Test Plugin" }, - new Dictionary { + new Dictionary + { ["Assets/PluginBehavior.cs"] = System.Text.Encoding.UTF8.GetBytes(source), - ["Assets/PluginBehavior.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.Parse("37f9751f-a7de-43c7-94ac-c8e854762d49")) + ["Assets/PluginBehavior.cs.imeta"] = CreateScriptSourceMeta( + serialization, + Guid.Parse("37f9751f-a7de-43c7-94ac-c8e854762d49") + ) } ); } @@ -2106,7 +2309,9 @@ private static void WriteSamplePlugin( string projectRoot, SerializationRegistry serialization ) { - const string c_source = "using InnoEngine.Reflection; using InnoEngine.Scene; " + "[StableTypeId(\"ce3b52c6-2a07-42ea-b632-a307a0ef7407\")] " + "public sealed class StarterBehavior : GameBehavior { }"; + const string c_source = "using InnoEngine.Reflection; using InnoEngine.Scene; " + + "[StableTypeId(\"ce3b52c6-2a07-42ea-b632-a307a0ef7407\")] " + + "public sealed class StarterBehavior : GameBehavior { }"; WriteSamplePlugin(projectRoot, serialization, c_source); } @@ -2120,12 +2325,22 @@ string source "samples.iplugin", serialization, new PluginManifest { pluginId = "tests.samples", displayName = "Sample Test Plugin" }, - new Dictionary { + new Dictionary + { ["Assets/"] = [], ["Assets/~Starter/"] = [], - ["Assets/~Starter.imeta"] = serialization.Serialize(new ScriptingAssetSourceMeta { persistentId = Guid.Parse("7726b1d2-9aee-4d2c-a865-2fd53155095f"), sourceKind = (int)AssetSourceKind.Directory }), + ["Assets/~Starter.imeta"] = serialization.Serialize( + new ScriptingAssetSourceMeta + { + persistentId = Guid.Parse("7726b1d2-9aee-4d2c-a865-2fd53155095f"), + sourceKind = (int)AssetSourceKind.Directory + } + ), ["Assets/~Starter/StarterBehavior.cs"] = System.Text.Encoding.UTF8.GetBytes(source), - ["Assets/~Starter/StarterBehavior.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.Parse("75f6a70b-93b2-47f0-8747-cc359474b7a3")) + ["Assets/~Starter/StarterBehavior.cs.imeta"] = CreateScriptSourceMeta( + serialization, + Guid.Parse("75f6a70b-93b2-47f0-8747-cc359474b7a3") + ) } ); } @@ -2133,7 +2348,15 @@ string source private static byte[] CreateScriptSourceMeta( SerializationRegistry serialization, Guid persistentId - ) => serialization.Serialize(new ScriptingAssetSourceMeta { persistentId = persistentId, sourceKind = (int)AssetSourceKind.File, importerId = "inno.editor.csharp-script" }); + ) => serialization.Serialize( + new ScriptingAssetSourceMeta + { + persistentId = persistentId, + sourceKind = (int)AssetSourceKind.File, + importerId = "inno.editor.csharp-script" + } + ); + private static void WritePluginPackage( string projectRoot, string fileName, @@ -2146,7 +2369,9 @@ IReadOnlyDictionary entries using var archive = new ZipArchive(stream, ZipArchiveMode.Create); WritePluginPackageEntry(archive, "Plugin.inno", serialization.Serialize(manifest)); foreach ((string entryPath, byte[] bytes)in entries) + { WritePluginPackageEntry(archive, entryPath, bytes); + } } private static void WritePluginPackageEntry( @@ -2156,15 +2381,19 @@ byte[] bytes ) { ZipArchiveEntry entry = archive.CreateEntry(path, CompressionLevel.Optimal); if (path.EndsWith("/", StringComparison.Ordinal)) + { return; + } using Stream output = entry.Open(); output.Write(bytes); } - private static string FormatDiagnostics(ScriptCompilationResult result) => string.Join( - Environment.NewLine, - result.diagnostics.Select(static diagnostic => $"{diagnostic.id}: {diagnostic.message}") - ); + private static string FormatDiagnostics(ScriptCompilationResult result) + => string.Join( + Environment.NewLine, + result.diagnostics.Select(static diagnostic => $"{diagnostic.id}: {diagnostic.message}") + ); + private static bool ContainsCustomAttribute( string assemblyPath, string attributeTypeName @@ -2178,11 +2407,17 @@ string attributeTypeName string? typeName = attribute.Constructor.Kind switch { HandleKind.MemberReference => GetMemberReferenceDeclaringTypeName(metadata, (MemberReferenceHandle)attribute.Constructor), - HandleKind.MethodDefinition => metadata.GetString(metadata.GetTypeDefinition(metadata.GetMethodDefinition((MethodDefinitionHandle)attribute.Constructor).GetDeclaringType()).Name), + HandleKind.MethodDefinition => metadata.GetString( + metadata.GetTypeDefinition( + metadata.GetMethodDefinition((MethodDefinitionHandle)attribute.Constructor).GetDeclaringType() + ).Name + ), _ => null }; if (string.Equals(typeName, attributeTypeName, StringComparison.Ordinal)) + { return true; + } } return false; @@ -2216,11 +2451,15 @@ private sealed class CompilationGate : IProgress, IDi public void Report(ScriptCompilationProgress value) { if (value.stage != "Building the script API profile...") + { return; + } workerThread = Environment.CurrentManagedThreadId; started.Set(); if (!release.Wait(TimeSpan.FromSeconds(15))) + { throw new TimeoutException("The test-owned compilation gate was not released."); + } } /// @@ -2256,10 +2495,13 @@ public IDisposable BeginPlayMode(RuntimeSession runtimeSession) private sealed class RestoreLease(PluginPlayScene owner) : IDisposable { private bool m_disposed; + public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; owner.restoreCount++; } @@ -2271,13 +2513,17 @@ private sealed class CountingHistoryIsolation : IEditorHistoryIsolation internal int disposeCount { get; private set; } public IDisposable BeginHistoryIsolation() => new HistoryLease(this); + private sealed class HistoryLease(CountingHistoryIsolation owner) : IDisposable { private bool m_disposed; + public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; owner.disposeCount++; } @@ -2289,12 +2535,12 @@ private sealed class ReadyScriptCompilation : IEditorScriptCompilation public bool requiresExclusiveProgress => false; public EditorScriptCompilationProgress progress => new(0, 0f, "Test script status.", false); - public void CancelCompilation(long operationId) - { - } + public void CancelCompilation(long operationId) {} private readonly ReadyCompilationTicket m_ticket = new(); + public IScriptCompilationTicket RequestCompilation() => m_ticket; + public IScriptCompilationTicket? currentTicket => m_ticket; public EditorScriptCompilationState state => EditorScriptCompilationState.Ready; public ScriptCompilationResult? lastCompilation => null; @@ -2311,18 +2557,22 @@ private sealed class ReadyCompilationTicket : IScriptCompilationTicket private sealed class TestSceneReloadParticipant(SceneReloadService reload) : IEditorReloadParticipant { - public IGenerationChange Capture(AssemblyReloadContext context) => new TestSceneReloadTransaction(reload.Capture(context.GetContext())); - public void RefreshDiagnostics() - { - } + public IGenerationChange Capture(AssemblyReloadContext context) + => new TestSceneReloadTransaction(reload.Capture(context.GetContext())); + + public void RefreshDiagnostics() {} } private sealed class TestSceneReloadTransaction(ISceneReloadStateTransfer transfer) : IGenerationChange { public void PrepareForActivation() => transfer.PrepareForActivation(); + public void Apply() => transfer.Apply(); + public void Complete() => transfer.Complete(); + public void RollbackStructure() => transfer.RollbackStructure(); + public void RestorePreviousState() => transfer.RestorePreviousState(); } } @@ -2336,6 +2586,7 @@ internal sealed class ScriptingFixture : IDisposable private readonly PluginEnvironment m_plugins; private RuntimeSession? m_editorSession; private bool m_disposed; + internal ScriptingFixture( Action? configureProject = null, bool enableFileSystemWatcher = false, @@ -2366,7 +2617,8 @@ internal ScriptingFixture( m_identities, host.diagnostics, host.logs, - options with { + options with + { enableFileSystemWatcher = enableFileSystemWatcher, fileWatcherFlushDelayMs = fileWatcherFlushDelayMs, sourceMounts = [..options.sourceMounts!, ..PluginSourceService.GetActivatableMounts(scan)] @@ -2382,13 +2634,17 @@ options with { m_plugins = new PluginEnvironment(assets, m_settings, host.serialization, pluginRoot, libraryRoot, scan, host.modules.generations); string dotnetHost = Path.Combine( Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = projectRoot, compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, projectRoot) - }, assets, m_plugins); + }, + assets, + m_plugins + ); } internal string projectRoot { get; } @@ -2396,7 +2652,9 @@ options with { internal AssetPipeline assets { get; } internal ScriptCompiler compiler { get; } internal IReadOnlyList activePlugins => m_plugins.activePlugins; - internal RuntimeSession editorSession => m_editorSession ?? throw new InvalidOperationException("The Editor runtime session has not been created."); + + internal RuntimeSession editorSession + => m_editorSession ?? throw new InvalidOperationException("The Editor runtime session has not been created."); internal void Write( string relativePath, @@ -2417,10 +2675,13 @@ string destinationRelativePath File.Move(source, destination); string sourceMetadata = source + ".imeta"; if (File.Exists(sourceMetadata)) + { File.Move(sourceMetadata, destination + ".imeta"); + } } - internal void WriteVersionedBehavior(int version) => Write("VersionedBehavior.cs", $$""" + internal void WriteVersionedBehavior(int version) + => Write("VersionedBehavior.cs", $$""" using InnoEngine.Scene; public sealed class VersionedBehavior : GameBehavior @@ -2428,7 +2689,9 @@ public sealed class VersionedBehavior : GameBehavior public int version => {{version}}; } """); + internal void Rescan() => assets.Rescan(); + internal ScriptCompilationResult Compile( IProgress? progress = null, CancellationToken cancellationToken = default @@ -2443,7 +2706,10 @@ internal ScriptCompilationResult CompileRuntimeDeployment( CancellationToken cancellationToken = default ) { Rescan(); - return compiler.CompileRuntimeDeploymentAsync(targetRuntimeDirectory ?? AppContext.BaseDirectory, progress, cancellationToken).GetAwaiter().GetResult(); + return compiler + .CompileRuntimeDeploymentAsync(targetRuntimeDirectory ?? AppContext.BaseDirectory, progress, cancellationToken) + .GetAwaiter() + .GetResult(); } internal string CreateDeploymentRuntime() @@ -2458,7 +2724,8 @@ internal string CreateDeploymentRuntime() return directory; } - private IModuleSource CreateScriptModuleSource(ScriptModuleDeployment deployment) => new DotNetModuleSource + private IModuleSource CreateScriptModuleSource(ScriptModuleDeployment deployment) + => new DotNetModuleSource { artifactRootDirectory = Path.Combine(projectRoot, "Library", "Assemblies"), moduleName = deployment.moduleName, @@ -2470,11 +2737,17 @@ internal string CreateDeploymentRuntime() assemblyScopes = deployment.assemblyScopes, collectible = true }; + internal ScriptReloadHost CreateReloadHost( EditorReloadCoordinator? reloads = null, bool autoCompile = false ) => new( - new ScriptReloadOptions { autoCompile = autoCompile, debounceMilliseconds = 0, compilationWarningTimeout = Timeout.InfiniteTimeSpan }, + new ScriptReloadOptions + { + autoCompile = autoCompile, + debounceMilliseconds = 0, + compilationWarningTimeout = Timeout.InfiniteTimeSpan + }, compiler, assets, m_plugins, @@ -2483,6 +2756,7 @@ internal ScriptReloadHost CreateReloadHost( reloads ?? new EditorReloadCoordinator(), CreateScriptModuleSource ); + internal ScriptCompilationResult CompilePending(ScriptReloadHost reload) { Rescan(); @@ -2499,10 +2773,13 @@ internal ScriptCompilationResult CompilePendingPluginReload(ScriptReloadHost rel } internal bool RefreshPlugins() => m_plugins.Refresh(); + internal Type ResolveActiveType(string name) { TypeCacheSnapshot snapshot = host.types.current; - return snapshot.types.Select(typeRef => typeRef.Resolve(snapshot)).Single(type => string.Equals(type.Name, name, StringComparison.Ordinal)); + return snapshot.types + .Select(typeRef => typeRef.Resolve(snapshot)) + .Single(type => string.Equals(type.Name, name, StringComparison.Ordinal)); } internal EditorInteractionRuntime CreateEditorRuntime(EditorReloadCoordinator? reloads = null) @@ -2534,14 +2811,24 @@ internal EditorInteractionRuntime CreateEditorRuntime(EditorReloadCoordinator? r internal RuntimeSession CreateEditorSession() { - m_editorSession ??= host.CreateSession(new RuntimeSessionOptions { kind = RuntimeSessionKind.Edit, applicationId = "tests.editor", createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(projectRoot, "Persistent", "tests.editor"), "Logs")), referenceResolvers = [assets] }); + m_editorSession ??= host.CreateSession( + new RuntimeSessionOptions + { + kind = RuntimeSessionKind.Edit, + applicationId = "tests.editor", + createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(projectRoot, "Persistent", "tests.editor"), "Logs")), + referenceResolvers = [assets] + } + ); return m_editorSession; } public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_editorSession?.Dispose(); m_plugins.Dispose(); @@ -2551,7 +2838,9 @@ public void Dispose() host.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(projectRoot)) + { Directory.Delete(projectRoot, recursive: true); + } } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs index 75fb232ad..970442b9e 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs @@ -7,13 +7,14 @@ using System.Reflection; using System.Security.Cryptography; using System.Text.Json; +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Native.ImGui; using Inno.Rendering.Shaders; -using Xunit; + using NativeGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.Scripting.Tests; @@ -30,7 +31,9 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() string? input = inputRoot is null ? null : Path.Combine(Path.GetFullPath(inputRoot), "shader-graph"); const string name = "Performance.ishader"; if (input is not null && Directory.Exists(input)) + { CopyPerformanceInput(input, source); + } else { GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, AssetSerializationContext.Create(m_assets)); @@ -38,32 +41,46 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() for (int index = 0; index < remaining; index++) { bool constant = index % 2 == 0; - var node = new GraphNodeRecord(new("performance.node." + index.ToString("D4")), - constant ? "inno.shader.constant" : "inno.shader.construct") + var node = new GraphNodeRecord( + new("performance.node." + index.ToString("D4")), + constant ? "inno.shader.constant" : "inno.shader.construct" + ) { position = new(index % 20 * 310f, index / 20 * 180f) }; if (!constant) + { node.SetValue("type", ShaderGraphDocument.Encode("float3", m_serialization, SerializationContext.empty)); + } graph.AddNode(node); if (!constant) - graph.AddEdge(new(new("performance.edge." + index.ToString("D4")), - new(new("performance.node." + (index - 1).ToString("D4")), new("value")), - new(node.id, new("component.0")))); + { + graph.AddEdge( + new( + new("performance.edge." + index.ToString("D4")), + new(new("performance.node." + (index - 1).ToString("D4")), new("value")), + new(node.id, new("component.0")) + ) + ); + } } File.WriteAllBytes(Path.Combine(source, name), GraphDocumentCodec.Encode(graph, m_serialization)); } Assert.True(m_assets.Import(AssetPath.Project(name))); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project(name), out AssetFileEntry entry)); if (input is not null && !Directory.Exists(input)) + { CopyPerformanceInput(source, input); + } byte[] original = SHA256.HashData(File.ReadAllBytes(Path.Combine(source, name))); SelectAndDraw(entry); var controller = Controller(entry); Assert.Equal(2_000, controller.document.nodes.Count); Assert.True(controller.document.edges.Count >= 900); for (int warmup = 0; warmup < 5; warmup++) + { DrawPerformanceCanvas(); + } string? requested = Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_REPETITIONS"); int repetitions = requested is null ? 5 : int.Parse(requested, System.Globalization.CultureInfo.InvariantCulture); Assert.InRange(repetitions, 1, 5); @@ -92,8 +109,13 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() double[] sorted = milliseconds.Order().ToArray(); samples.Add(new { - repetition, milliseconds, vertices, indices, median = (sorted[4] + sorted[5]) / 2, - p95 = sorted[9], allocatedBytes = allocated, + repetition, + milliseconds, + vertices, + indices, + median = (sorted[4] + sorted[5]) / 2, + p95 = sorted[9], + allocatedBytes = allocated, totalAllocatedBytes = GC.GetTotalAllocatedBytes(precise: true) - totalBytesBefore, cpuMilliseconds = (process.TotalProcessorTime - cpuBefore).TotalMilliseconds, gen0Collections = GC.CollectionCount(0) - gen0, @@ -101,17 +123,27 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() gen2Collections = GC.CollectionCount(2) - gen2 }); } - m_performanceOutput.WriteLine(JsonSerializer.Serialize(new - { - workload = "2000-shader-nodes", nodeCount = controller.document.nodes.Count, - edgeCount = controller.document.edges.Count, - configuration = typeof(ShaderEditorWorkflowTests).Assembly.GetCustomAttribute()?.Configuration - ?? throw new InvalidOperationException("The benchmark assembly has no SDK configuration metadata."), - samples, - framework = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, - viewport = "1200x800", warmupFrames = 5, measuredFramesPerRepetition = 10, - sharedInput = input, consumer = "native-command-offset-validation", supportsVertexOffsets = true - })); + m_performanceOutput.WriteLine( + JsonSerializer.Serialize(new + { + workload = "2000-shader-nodes", + nodeCount = controller.document.nodes.Count, + edgeCount = controller.document.edges.Count, + configuration = typeof(ShaderEditorWorkflowTests) + .Assembly + .GetCustomAttribute() + ?.Configuration + ?? throw new InvalidOperationException("The benchmark assembly has no SDK configuration metadata."), + samples, + framework = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, + viewport = "1200x800", + warmupFrames = 5, + measuredFramesPerRepetition = 10, + sharedInput = input, + consumer = "native-command-offset-validation", + supportsVertexOffsets = true + }) + ); Assert.Equal(original, SHA256.HashData(File.ReadAllBytes(Path.Combine(source, name)))); } @@ -127,10 +159,16 @@ private unsafe void DrawPerformanceCanvas() ImDrawCmd command = list->CmdBuffer.Data[commandIndex]; ulong end = (ulong)command.IdxOffset + command.ElemCount; if (end > (ulong)list->IdxBuffer.Size) + { throw new InvalidOperationException("The shader canvas exceeded its native index buffer."); + } for (ulong index = command.IdxOffset; index < end; index++) + { if ((ulong)command.VtxOffset + list->IdxBuffer.Data[index] >= (ulong)list->VtxBuffer.Size) + { throw new InvalidOperationException("The shader canvas exceeded its native vertex buffer."); + } + } } } } @@ -141,8 +179,12 @@ string destination ) { Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) + { Directory.CreateDirectory(Path.Combine(destination, Path.GetRelativePath(source, directory))); + } foreach (string file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) + { File.Copy(file, Path.Combine(destination, Path.GetRelativePath(source, file)), overwrite: false); + } } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs index 80b006866..7835ba048 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs @@ -7,9 +7,17 @@ public sealed partial class ShaderEditorWorkflowTests public static IEnumerable CanvasMetrics() { foreach (float zoom in new[] { 0.75f, 0.85f, 0.90f, 1f, 1.10f, 1.25f, 1.50f }) + { foreach (float density in new[] { 1f, 1.25f, 1.50f, 2f }) + { foreach ((float width, float height) in new[] { (1280f, 720f), (1920f, 1080f) }) + { foreach (bool emptyGraph in new[] { false, true }) + { yield return [zoom, density, width, height, emptyGraph]; + } + } + } + } } } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs index a7ea3b1f2..097022cf7 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs @@ -1,48 +1,50 @@ -using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using System.Runtime.CompilerServices; -using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using BGCS.Runtime; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; -using System.Collections.Generic; using System.Collections.Concurrent; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; +using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; +using BGCS.Runtime; +using Xunit; +using Xunit.Abstractions; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Diagnostics; +using Inno.Core.Events; using Inno.Core.Graphs; using Inno.Core.Identity; -using Inno.Core.Logging; -using Inno.Core.Events; using Inno.Core.Input; +using Inno.Core.Logging; using Inno.Core.Serialization; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.Graph; using Inno.Editor.Interactions; -using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; +using Inno.Editor.Rendering; using Inno.Editor.Shaders; using Inno.Editor.Shaders.ImGui; -using Inno.Editor.Rendering; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; +using Inno.Native.ImGui; using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Shaders; -using Inno.Native.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUiSession; using ImGuiApi = Inno.Native.ImGui.ImGui; -using Xunit; -using Xunit.Abstractions; -using Inno.Rendering.Assets.Authoring; +using NativeVector2 = Inno.Native.ImGui.ImVec2C; namespace Inno.Editor.Scripting.Tests; + public sealed partial class ShaderEditorWorkflowTests : IDisposable { private readonly ITestOutputHelper m_performanceOutput; @@ -68,6 +70,7 @@ public sealed partial class ShaderEditorWorkflowTests : IDisposable private Vector2 m_canvasMinimum; private Vector2 m_canvasMaximum; private Vector2 m_probeOffset; + public unsafe ShaderEditorWorkflowTests(ITestOutputHelper output) { m_performanceOutput = output; @@ -90,10 +93,20 @@ public unsafe ShaderEditorWorkflowTests(ITestOutputHelper output) m_identities, m_diagnostics, m_logs, - AssetPipelineOptions.Create(Path.Combine(m_root, "Assets"), Path.Combine(m_root, "Library"))with { enableFileSystemWatcher = false } + AssetPipelineOptions.Create( + Path.Combine(m_root, "Assets"), + Path.Combine(m_root, "Library") + )with { enableFileSystemWatcher = false } ); m_source = new(m_assets, m_serialization); - m_artifacts = new(m_assets, m_serialization, m_types, new ShaderCompiler(new WorkflowCompiler()), new BgfxTextureTargetCompiler(), m_reporter); + m_artifacts = new( + m_assets, + m_serialization, + m_types, + new ShaderCompiler(new WorkflowCompiler()), + new BgfxTextureTargetCompiler(), + m_reporter + ); m_runtime = CreateRuntime(); m_imgui = ImGuiApi.Raw.CreateContext(null); ImGuiIO* io = ImGuiApi.Raw.GetIO(); @@ -111,7 +124,10 @@ public void ParameterPresentationRoundTripsWithoutChangingTheRuntimeDefinitionOr GraphDocument graph = m_source.Read(entry.assetPath).document; SerializationContext context = AssetSerializationContext.Create(m_assets); byte[] beforeDefinition = m_serialization.Serialize(ShaderGraphDocument.ReadDefinition(graph, m_serialization, context), context); - string beforeHash = ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization), m_serialization); + string beforeHash = ShaderGraphArtifact.GetSemanticHash( + ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization), + m_serialization + ); ShaderPropertyId id = new("stable.tint"); Assert.True(ShaderParameterPresentation.Read(graph, id, m_serialization, context).visible); ShaderParameterPresentation.Write( @@ -131,10 +147,16 @@ public void ParameterPresentationRoundTripsWithoutChangingTheRuntimeDefinitionOr Assert.Equal(8, presentation.maximum); presentation.group = "Detached"; Assert.Equal("Surface", ShaderParameterPresentation.Read(restored, id, m_serialization, context).group); - Assert.Equal(beforeDefinition, m_serialization.Serialize(ShaderGraphDocument.ReadDefinition(restored, m_serialization, context), context)); + Assert.Equal( + beforeDefinition, + m_serialization.Serialize(ShaderGraphDocument.ReadDefinition(restored, m_serialization, context), context) + ); Assert.Equal( beforeHash, - ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(restored, new Dictionary(), m_serialization), m_serialization) + ShaderGraphArtifact.GetSemanticHash( + ShaderGraphArtifact.Encode(restored, new Dictionary(), m_serialization), + m_serialization + ) ); } @@ -153,8 +175,17 @@ public void ParameterPresentationRejectsInvalidBoundsBeforeMutatingTheGraph() (0d, 1e100) } - ) - Assert.Throws(() => ShaderParameterPresentation.Write(graph, new("range"), new() { hasRange = true, minimum = range.Item1, maximum = range.Item2 }, m_serialization, context)); + ) { + Assert.Throws( + () => ShaderParameterPresentation.Write( + graph, + new("range"), + new() { hasRange = true, minimum = range.Item1, maximum = range.Item2 }, + m_serialization, + context + ) + ); + } Assert.Equal(before, GraphDocumentCodec.Encode(graph, m_serialization)); } @@ -208,13 +239,19 @@ public void SourceSettingsUndoRedoRestoresValidAndInvalidImportStates() var settings = Assert.IsType(before.value); settings.exports = ["MissingFunction"]; Assert.False(edits.Apply(path, settings, before.fingerprint)); - Assert.Equal("MissingFunction", Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports)); + Assert.Equal( + "MissingFunction", + Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports) + ); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal("Evaluate", Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports)); Assert.True(m_assets.TryGetInfo(path, out AssetInfo? info)); Assert.Equal(AssetImportStatus.Imported, info!.status); Assert.True(m_runtime.interactions.history.Redo().succeeded); - Assert.Equal("MissingFunction", Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports)); + Assert.Equal( + "MissingFunction", + Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports) + ); } [Fact] @@ -231,13 +268,18 @@ public void SourceSettingsUndoRefusesToOverwriteAnExternalSidecarEdit() external.exports = ["ExternalFunction"]; _ = m_assets.SaveImportSettings(path, external, current.fingerprint); Assert.False(m_runtime.interactions.history.Undo().succeeded); - Assert.Equal("ExternalFunction", Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports)); + Assert.Equal( + "ExternalFunction", + Assert.Single(Assert.IsType(m_assets.GetImportSettings(path).value).exports) + ); } private AssetPath CreateFunction(params string[] exports) { if (exports.Length == 0) + { exports = ["Evaluate"]; + } AssetPath path = AssetPath.Project("Function.ishadersource"); File.WriteAllText( Path.Combine(m_root, "Assets", path.localPath), @@ -284,22 +326,38 @@ bool emptyGraph SelectAndDraw(entry); GraphDocumentController controller = Controller(entry); if (emptyGraph) + { controller.ReplaceDocument(new GraphDocument(), "Prepare Empty Canvas"); + } ulong revision = controller.revision; byte[] disk = File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath)); ImGuiApi.Raw.GetIO()->DisplaySize = Unsafe.BitCast(new(width, height)); ImGuiApi.Raw.GetIO()->DisplayFramebufferScale = Unsafe.BitCast(new(density)); m_ui.widgets.style.SetZoom(zoom); using (m_ui.Enter()) + { m_ui.widgets.SetupStyle(); - Vector2[] sizes = [new(width, height), new(640, 400), new(280, 220), new(96, 64), new(32, 32), new(width, 32), new(32, height), new(width, height)]; + } + Vector2[] sizes = + [ + new(width, height), + new(640, 400), + new(280, 220), + new(96, 64), + new(32, 32), + new(width, 32), + new(32, height), + new(width, height) + ]; for (int cycle = 0; cycle < 3; cycle++) + { foreach (Vector2 size in sizes) { // Run both the resize frame and its settled layout with native assertions enabled. Draw(size); Draw(size); } + } Assert.Equal(revision, controller.revision); Assert.Equal(disk, File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath))); @@ -397,7 +455,11 @@ public void FormatPlacesOutputsOnTheRightWithoutChangingShaderSemanticsAndIsUndo GraphDocumentController controller = Controller(entry); GraphDocument reversed = controller.document.Clone(); foreach (GraphNodeRecord node in reversed.nodes) - node.position = node.definitionId == ShaderGraphDocument.outputDefinitionId ? new(0, node.position.y) : new(900, node.position.y); + { + node.position = node.definitionId == ShaderGraphDocument.outputDefinitionId + ? new(0, node.position.y) + : new(900, node.position.y); + } controller.ReplaceDocument(reversed, "Reverse Shader Layout"); byte[] before = GraphDocumentCodec.Encode(controller.document, m_serialization); string semantic = ShaderGraphArtifact.GetSemanticHash( @@ -405,14 +467,28 @@ public void FormatPlacesOutputsOnTheRightWithoutChangingShaderSemanticsAndIsUndo m_serialization ); Assert.True(m_runtime.interactions.For("panel/rendering.shader-editor", entry).Execute("shader/format")); - GraphNodeRecord[] outputs = controller.document.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId).ToArray(); + GraphNodeRecord[] outputs = controller.document.nodes + .Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) + .ToArray(); Assert.All( outputs, - output => Assert.True(output.position.x > controller.document.nodes.Where(node => node.id != output.id && ShaderGraphDocument.Read(node, "stage", "", m_serialization, AssetSerializationContext.Create(m_assets)) == output.id.value).Max(static node => node.position.x)) + output => Assert.True( + output.position.x > controller.document.nodes + .Where( + node => ( + node.id != output.id + && ShaderGraphDocument.Read(node, "stage", "", m_serialization, AssetSerializationContext.Create(m_assets)) == output.id.value + ) + ) + .Max(static node => node.position.x) + ) ); Assert.Equal( semantic, - ShaderGraphArtifact.GetSemanticHash(ShaderGraphArtifact.Encode(controller.document, new Dictionary(), m_serialization), m_serialization) + ShaderGraphArtifact.GetSemanticHash( + ShaderGraphArtifact.Encode(controller.document, new Dictionary(), m_serialization), + m_serialization + ) ); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal(before, GraphDocumentCodec.Encode(controller.document, m_serialization)); @@ -512,7 +588,10 @@ private AssetFileEntry Create(string name) { File.WriteAllBytes( Path.Combine(m_root, "Assets", name), - GraphDocumentCodec.Encode(ShaderGraphTemplates.CreateRaster(m_serialization, AssetSerializationContext.Create(m_assets)), m_serialization) + GraphDocumentCodec.Encode( + ShaderGraphTemplates.CreateRaster(m_serialization, AssetSerializationContext.Create(m_assets)), + m_serialization + ) ); Assert.True(m_assets.Import(AssetPath.Project(name))); Assert.True(m_assets.TryGetFileSystemEntry(AssetPath.Project(name), out AssetFileEntry entry)); @@ -555,17 +634,33 @@ public void DeleteKeysRemoveTheSelectedComputeStageAndItsDeclarationsAsOneUndo(K m_logs.Flush(); Assert.True( controller.document.FindNode(output.id)is null, - "Focus: " + m_runtime.interactions.focusedArea + "; cut: " + interaction.Query("shader/cut").isEnabled + "; undo: " + m_runtime.interactions.history.undoName + "; " + string.Join( - "\n", - m_messages.messages - ) + "Focus: " + + m_runtime.interactions.focusedArea + + "; cut: " + + interaction.Query("shader/cut").isEnabled + + "; undo: " + + m_runtime.interactions.history.undoName + + "; " + + string.Join("\n", m_messages.messages) ); Assert.Null(controller.document.FindNode(input.id)); - ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(controller.document, m_serialization, AssetSerializationContext.Create(m_assets)); + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + controller.document, + m_serialization, + AssetSerializationContext.Create(m_assets) + ); Assert.Single(definition.passes); Assert.DoesNotContain(definition.properties, property => property.id.value == "computeParameter"); using var nodes = new ShaderNodeCompilerRegistry(m_types); - Assert.True(new ShaderGraphProgramCompiler(nodes).Lower(controller.document, "bgfx", new Dictionary(), m_serialization, AssetSerializationContext.Create(m_assets)).succeeded); + Assert.True( + new ShaderGraphProgramCompiler(nodes).Lower( + controller.document, + "bgfx", + new Dictionary(), + m_serialization, + AssetSerializationContext.Create(m_assets) + ).succeeded + ); Tick(); Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Equal(before, GraphDocumentCodec.Encode(controller.document, m_serialization)); @@ -585,31 +680,56 @@ public void CutAndPasteStageKeepsItsContentsAndDoesNotCreateDuplicatePassDeclara GraphNodeId child = controller.AddNode( "inno.shader.constant", new(10, 20), - new Dictionary { ["stage"] = ShaderGraphDocument.Encode(stage.value, m_serialization, AssetSerializationContext.Create(m_assets)) } + new Dictionary + { + ["stage"] = ShaderGraphDocument.Encode(stage.value, m_serialization, AssetSerializationContext.Create(m_assets)) + } ); Assert.True(interaction.Execute("shader/cut")); Assert.Null(controller.document.FindNode(child)); Assert.True(interaction.Execute("shader/paste")); Assert.Null(controller.document.FindNode(child)); - Assert.Equal(2, controller.document.nodes.Count(node => node.definitionId == "inno.shader.stage-output" && ReadStage(node).stage != ShaderStage.Compute)); - GraphNodeRecord pasted = controller.document.nodes.Single(node => node.definitionId == "inno.shader.stage-output" && ReadStage(node).stage == ShaderStage.Compute); + Assert.Equal( + 2, + controller.document.nodes.Count( + node => node.definitionId == "inno.shader.stage-output" && ReadStage(node).stage != ShaderStage.Compute + ) + ); + GraphNodeRecord pasted = controller.document.nodes.Single( + node => node.definitionId == "inno.shader.stage-output" && ReadStage(node).stage == ShaderStage.Compute + ); Assert.Contains( controller.document.nodes, - node => ShaderGraphDocument.Read(node, "stage", "", m_serialization, AssetSerializationContext.Create(m_assets)) == pasted.id.value + node => ( + ShaderGraphDocument.Read( + node, + "stage", + "", + m_serialization, + AssetSerializationContext.Create(m_assets) + ) == pasted.id.value + ) ); Assert.False(interaction.Execute("shader/duplicate")); - ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(controller.document, m_serialization, AssetSerializationContext.Create(m_assets)); + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + controller.document, + m_serialization, + AssetSerializationContext.Create(m_assets) + ); Assert.Equal(2, definition.passes.Length); Assert.Equal(2, definition.passes.Select(pass => pass.name).Distinct().Count()); Assert.True(m_runtime.interactions.history.Undo().succeeded); - Assert.Single(ShaderGraphDocument.ReadDefinition(controller.document, m_serialization, AssetSerializationContext.Create(m_assets)).passes); - ShaderGraphStageSettings ReadStage(GraphNodeRecord node) => ShaderGraphDocument.Read( - node, - "settings", - new ShaderGraphStageSettings(), - m_serialization, - AssetSerializationContext.Create(m_assets) + Assert.Single( + ShaderGraphDocument.ReadDefinition(controller.document, m_serialization, AssetSerializationContext.Create(m_assets)).passes ); + ShaderGraphStageSettings ReadStage(GraphNodeRecord node) + => ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphStageSettings(), + m_serialization, + AssetSerializationContext.Create(m_assets) + ); } [Fact] @@ -630,19 +750,38 @@ public void SourceMenuUsesAssetIdentityAndDisconnectCommitsOneUndoWithoutSaving( GraphDocumentController controller = Controller(entry); GraphNodeRecord node = controller.document.nodes.Single(node => node.definitionId == "inno.shader.source"); Assert.True(m_assets.TryGetInfo(source, out AssetInfo? info)); - Assert.Equal(info!.persistentId, ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, m_serialization, AssetSerializationContext.Create(m_assets))); - Assert.Equal("Evaluate", ShaderGraphDocument.Read(node, "function", "", m_serialization, AssetSerializationContext.Create(m_assets))); + Assert.Equal( + info!.persistentId, + ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, m_serialization, AssetSerializationContext.Create(m_assets)) + ); + Assert.Equal( + "Evaluate", + ShaderGraphDocument.Read(node, "function", "", m_serialization, AssetSerializationContext.Create(m_assets)) + ); Tick(); using var nodes = new ShaderNodeCompilerRegistry(m_types); using var frontends = new ShaderSourceFrontendRegistry(m_types); ShaderFunctionAsset functionAsset = m_assets.Load(source); - ShaderSourceModuleAnalysis module = frontends.AnalyzeModule(ShaderSourceBundle.Decode(ShaderSourceBundle.Read(functionAsset, m_assets), "Evaluate", m_serialization)); - IReadOnlyList ports = nodes.DescribePorts(node, m_serialization, AssetSerializationContext.Create(m_assets), module, functionAsset.implementationId, null); + ShaderSourceModuleAnalysis module = frontends.AnalyzeModule( + ShaderSourceBundle.Decode(ShaderSourceBundle.Read(functionAsset, m_assets), "Evaluate", m_serialization) + ); + IReadOnlyList ports = nodes.DescribePorts( + node, + m_serialization, + AssetSerializationContext.Create(m_assets), + module, + functionAsset.implementationId, + null + ); Assert.Contains(ports, port => port.direction == GraphPortDirection.Input); Assert.Contains(ports, port => port.direction == GraphPortDirection.Output); GraphNodeId constant = controller.AddNode("inno.shader.constant", new(0, 0)); GraphDocument candidate = controller.document.Clone(); - var edge = new GraphEdgeRecord(new("source-link"), new(constant, new("value")), new(node.id, new(ports.First(port => port.direction == GraphPortDirection.Input).id))); + var edge = new GraphEdgeRecord( + new("source-link"), + new(constant, new("value")), + new(node.id, new(ports.First(port => port.direction == GraphPortDirection.Input).id)) + ); candidate.AddEdge(edge); controller.ReplaceDocument(candidate, "Connect Source"); Assert.True(interaction.Execute("shader/disconnect")); @@ -663,7 +802,10 @@ public void SourceLibrariesOwnTheirNestedCreationCatalogWithoutLeakingSeparators Assert.True(m_assets.SaveImportSettings(source, settings, snapshot.fingerprint)); AssetFileEntry entry = Create("Catalog.ishader"); SelectAndDraw(entry); - EditorMenuItem create = m_runtime.interactions.For("panel/rendering.shader-editor", entry).BuildMenu().items.Single(item => item.label == "Create"); + EditorMenuItem create = m_runtime.interactions + .For("panel/rendering.shader-editor", entry) + .BuildMenu().items + .Single(item => item.label == "Create"); EditorMenuItem functions = create.children.Single(item => item.label == "Functions"); EditorMenuItem rendering2D = functions.children.Single(item => item.label == "Rendering 2D"); Assert.True(rendering2D.separatorBefore); @@ -679,7 +821,10 @@ public void PluginNodePresentationOwnsItsCreationGroupAndSeparator() { AssetFileEntry entry = Create("NodeCatalog.ishader"); SelectAndDraw(entry); - EditorMenuItem create = m_runtime.interactions.For("panel/rendering.shader-editor", entry).BuildMenu().items.Single(item => item.label == "Create"); + EditorMenuItem create = m_runtime.interactions + .For("panel/rendering.shader-editor", entry) + .BuildMenu().items + .Single(item => item.label == "Create"); EditorMenuItem domain = create.children.Single(item => item.label == "Domain"); EditorMenuItem extension = domain.children.Single(item => item.label == "Test Extension"); Assert.True(extension.separatorBefore); @@ -725,8 +870,9 @@ public void FormatOrdersSourcesByDestinationPortsToAvoidInputWireCrossings() output } - ) + ) { graph.AddNode(node); + } graph.AddEdge(new(new("top-edge"), new(top.id, new("value")), new(evaluate.id, new("component.0")))); graph.AddEdge(new(new("middle-edge"), new(middle.id, new("value")), new(evaluate.id, new("component.1")))); graph.AddEdge(new(new("bottom-edge"), new(bottom.id, new("value")), new(evaluate.id, new("component.2")))); @@ -750,7 +896,11 @@ public void SavingAppliesTheGraphWithoutDependingOnFileWatcherAndUndoStaysDraftO long before = asset.contentVersion; GraphDocumentController controller = Controller(entry); GraphDocument graph = controller.document.Clone(); - ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(graph, m_serialization, AssetSerializationContext.Create(m_assets)); + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + graph, + m_serialization, + AssetSerializationContext.Create(m_assets) + ); definition.name = "Saved Change"; graph.SetMetadata( ShaderGraphDocument.definitionKey, @@ -809,7 +959,9 @@ public void RestartRecoversOnlyTheLatestDraftAndNeverAppliesIt(bool undo) GraphNodeId node = Controller(entry).AddNode("tests.unsaved", new(0, 0)); Tick(); if (undo) + { Assert.True(m_runtime.interactions.history.Undo().succeeded); + } // Shutdown must capture even the final undo that has not had an update frame yet. m_runtime.Dispose(); Assert.Equal(saved, File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath))); @@ -826,7 +978,17 @@ public void DraftCompilationNeverReplacesTheCanonicalArtifactAndLayoutChangesDoN ShaderAsset shader = m_assets.Load(entry.assetPath); byte[] disk = File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath)); RenderTextureFormat[] formats = Enum.GetValues(); - var capabilities = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.None, new(256, 8, 8192, 16), formats, formats, formats, formats, false, false); + var capabilities = new GraphicsCapabilities( + GraphicsApi.Metal, + GraphicsCapability.None, + new(256, 8, 8192, 16), + formats, + formats, + formats, + formats, + false, + false + ); var compilation = new EditorShaderCompilation(m_artifacts, capabilities); RenderShaderArtifact? canonical = null; for (int i = 0; i < 100 && canonical is null; i++) @@ -842,7 +1004,10 @@ public void DraftCompilationNeverReplacesTheCanonicalArtifactAndLayoutChangesDoN ShaderPropertyDefinition property = definition.properties[0]; property.defaultValue = MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.23f, 1, 1, 1)); definition.properties[0] = property; - draft.SetMetadata(ShaderGraphDocument.definitionKey, ShaderGraphDocument.Encode(m_serialization.Serialize(definition, context), m_serialization, context)); + draft.SetMetadata( + ShaderGraphDocument.definitionKey, + ShaderGraphDocument.Encode(m_serialization.Serialize(definition, context), m_serialization, context) + ); Guid previewId = Guid.NewGuid(); EditorShaderDraftCompilationSnapshot Poll(ulong revision) { @@ -877,12 +1042,32 @@ EditorShaderDraftCompilationSnapshot Poll(ulong revision) private EditorInteractionRuntime CreateRuntime() { RenderTextureFormat[] formats = Enum.GetValues(); - var capabilities = new GraphicsCapabilities(GraphicsApi.Metal, GraphicsCapability.None, new(256, 8, 8192, 16), formats, formats, formats, formats, false, false); + var capabilities = new GraphicsCapabilities( + GraphicsApi.Metal, + GraphicsCapability.None, + new(256, 8, 8192, 16), + formats, + formats, + formats, + formats, + false, + false + ); var runtime = new EditorInteractionRuntime( new EditorContext(m_root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), m_types, m_logs, - [m_types, m_serialization, m_identities, m_assets, m_sink, m_ui, new EditorReloadCoordinator(), new EditorShaderCompilation(m_artifacts, capabilities), new EmptyPreviews()] + [ + m_types, + m_serialization, + m_identities, + m_assets, + m_sink, + m_ui, + new EditorReloadCoordinator(), + new EditorShaderCompilation(m_artifacts, capabilities), + new EmptyPreviews() + ] ); runtime.Start(); return runtime; @@ -1038,8 +1223,7 @@ void Sample( second } - ) - { + ) { MaterialAsset candidate = documents.Read(id); candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(value, 1, 1, 1))); candidates.Add(id, candidate); @@ -1069,8 +1253,7 @@ void Sample( second } - ) - { + ) { Assert.True(documents.Read(id).TryGet(property, out MaterialValue value)); Assert.Equal(0.4f, value.vector.x); } @@ -1082,8 +1265,9 @@ void Sample( second } - ) + ) { Assert.False(documents.Read(id).TryGet(property, out _)); + } Assert.All(m_runtime.interactions.documents.documents, document => Assert.False(document.isDirty)); Assert.Equal(original, sources.Read(firstPath).bytes); Assert.Equal(original, sources.Read(secondPath).bytes); @@ -1094,8 +1278,9 @@ void Sample( second } - ) + ) { Assert.True(documents.Read(id).TryGet(property, out _)); + } } [Fact] @@ -1110,7 +1295,12 @@ public void CommonMaterialEditingPreservesUntouchedMixedComponentsAndTextureRefe var secondTexture = new TextureAsset(1, 1, TextureColorSpace.Linear, "second"); first = MaterialValue.FromTexture(firstTexture); edited = first; - edited.sampler = new(RenderSamplerFilter.Point, RenderSamplerAddressMode.Clamp, RenderSamplerAddressMode.Clamp, RenderSamplerAddressMode.Clamp); + edited.sampler = new( + RenderSamplerFilter.Point, + RenderSamplerAddressMode.Clamp, + RenderSamplerAddressMode.Clamp, + RenderSamplerAddressMode.Clamp + ); other = MaterialValue.FromTexture(secondTexture); result = ShaderPropertyInspector.ApplyEdit(ShaderPropertyType.Texture2D, first, edited, other); Assert.Same(secondTexture, result.texture); @@ -1233,6 +1423,7 @@ private GraphPosition ReadPosition( AssetFileEntry entry, GraphNodeId id ) => m_source.Read(entry.assetPath).document.FindNode(id)!.position; + private Guid AssetId(AssetFileEntry entry) { Assert.True(m_assets.TryGetInfo(entry.assetPath, out AssetInfo? info)); @@ -1302,6 +1493,7 @@ public sealed unsafe class WorkflowSink private sealed class WorkflowLogs : ILogSink { internal readonly ConcurrentQueue messages = new(); + public void Receive(LogEntry entry) => messages.Enqueue(entry.message); } @@ -1309,6 +1501,7 @@ private sealed class WorkflowLogs : ILogSink public sealed unsafe class CanvasProbeDrawer : ShaderNodeDrawer { public static Vector2 header; + public override void Draw(ShaderNodeDrawContext context) { float zoom = ImGuiApi.GetWindowSize().X / 246f; @@ -1322,7 +1515,9 @@ public sealed unsafe class CanvasProbeCompiler : IShaderNodeCompiler public string definitionId => "tests.shader-ui-probe"; public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => []; - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) => new Dictionary(); + + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary(); } [EditorModule("tests.shader-workflow", order: 160)] @@ -1350,10 +1545,19 @@ public ShaderCompileTarget CreateTarget( bool optimize = true, bool debugInformation = false ) => new("tests:workflow", capabilities, optimize, debugInformation); + public ValueTask CompileAsync( ShaderStageToolRequest request, CancellationToken cancellationToken - ) => ValueTask.FromResult(new ShaderStageToolResult([1, 2, 3], request.stage.inputs.Where(input => input.kind == ShaderIrInputKind.Uniform).Select(input => new ShaderStageBinding(input.id, "native_" + input.id, 0)), [])); + ) => ValueTask.FromResult( + new ShaderStageToolResult( + [1, 2, 3], + request.stage.inputs + .Where(input => input.kind == ShaderIrInputKind.Uniform) + .Select(input => new ShaderStageBinding(input.id, "native_" + input.id, 0)), + [] + ) + ); } private sealed class EmptyPreviews : IEditorPreviewService @@ -1366,9 +1570,7 @@ out EditorPreviewHandle handle return false; } - public void ReleaseRendered(string viewportId) - { - } + public void ReleaseRendered(string viewportId) {} public uint deviceGeneration => 1; @@ -1394,9 +1596,9 @@ public void Draw( EditorPreviewHandle handle, Vector2 logicalSize ) => throw new InvalidOperationException("No texture was requested by this workflow."); + public bool Release(EditorPreviewHandle handle) => false; - public void ReleaseAll() - { - } + + public void ReleaseAll() {} } } diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs index 079252a05..a0644572f 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs @@ -2,20 +2,20 @@ using System.IO; using System.IO.Compression; using System.Linq; -using System.Runtime.InteropServices; +using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using System.Runtime.Loader; -using System.Reflection; +using System.Text; using System.Threading; using System.Threading.Tasks; -using System.Text; using System.Xml.Linq; +using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Build.Toolchains; using Inno.Plugins; using Inno.Scripting.Compiler; -using Xunit; namespace Inno.Scripting.Compiler.Tests; @@ -38,14 +38,27 @@ string value fixture.Rescan(); fixture.compiler.GenerateProjectFiles(); string project = Path.Combine(fixture.projectRoot, "Inno.GameScripts.csproj"); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveAsync(host, project); using var output = new StringWriter(); using var errors = new StringWriter(); - await Assert.ThrowsAsync(() => ToolchainEnvironment.RunAsync(sdk.hostPath, + await Assert.ThrowsAsync(() => ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nr:false", "-p:" + property + "=" + value], - fixture.projectRoot, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath), output, errors)); + fixture.projectRoot, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath), + output, + errors + )); Assert.Contains("IDE compiler input '" + property + "' differs", output.ToString() + errors, StringComparison.Ordinal); } @@ -61,17 +74,24 @@ public async Task InstalledPluginExtensionMembersAreAvailableInIdeReferences() using var fixture = new CompilerFixture(( root, serialization - ) => { + ) => + { using FileStream stream = File.Create(Path.Combine(root, "Plugins", "language.iplugin")); using var archive = new ZipArchive(stream, ZipArchiveMode.Create); using (Stream manifest = archive.CreateEntry("Plugin.inno").Open()) - manifest.Write(serialization.Serialize(new PluginManifest - { - pluginId = "tests.csharp14", - displayName = "CSharp14 source plugin" - })); + { + manifest.Write( + serialization.Serialize(new PluginManifest + { + pluginId = "tests.csharp14", + displayName = "CSharp14 source plugin" + }) + ); + } using (Stream source = archive.CreateEntry("Assets/PluginLanguage.cs").Open()) - source.Write(Encoding.UTF8.GetBytes(""" + { + source.Write( + Encoding.UTF8.GetBytes(""" namespace LanguagePlugin; public sealed class Counter { @@ -84,14 +104,18 @@ public static class CounterExtensions public bool hasCount => counter.count > 0; } } - """)); + """) + ); + } using Stream metadata = archive.CreateEntry("Assets/PluginLanguage.cs.imeta").Open(); - metadata.Write(serialization.Serialize(new ScriptingAssetSourceMeta - { - persistentId = Guid.NewGuid(), - sourceKind = (int)AssetSourceKind.File, - importerId = "inno.editor.csharp-script" - })); + metadata.Write( + serialization.Serialize(new ScriptingAssetSourceMeta + { + persistentId = Guid.NewGuid(), + sourceKind = (int)AssetSourceKind.File, + importerId = "inno.editor.csharp-script" + }) + ); }); fixture.Write("Consumer.cs", """ using LanguagePlugin; @@ -242,9 +266,15 @@ string directory using var errors = new StringWriter(); try { - await ToolchainEnvironment.RunAsync(sdk.hostPath, + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet"], - directory, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath), output, errors); + directory, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath), + output, + errors + ); return output.ToString(); } catch (InvalidOperationException failure) @@ -263,7 +293,8 @@ private static WeakReference InvokePublicSemantics(string assemblyPath) using var stream = new MemoryStream(File.ReadAllBytes(assemblyPath)); Assembly assembly = lifetime.LoadFromStream(stream); Func evaluate = assembly.GetType("LanguageSemantics", throwOnError: true)! - .GetMethod("Evaluate", BindingFlags.Public | BindingFlags.Static)!.CreateDelegate>(); + .GetMethod("Evaluate", BindingFlags.Public | BindingFlags.Static)! + .CreateDelegate>(); Assert.True(evaluate()); } finally @@ -283,21 +314,30 @@ public void FrameworkContentChangesSelectNewArtifacts() using var fixture = new CompilerFixture(compilationEnvironment: environment); fixture.Write("Counter.cs", "public sealed class Counter { public int count { get; set; } }"); fixture.Rescan(); - string host = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string host = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); ScriptCompilationInputs selected = new Inno.Build.SdkScriptCompilationEnvironment(host, fixture.projectRoot).Capture(); string destination = Path.Combine(fixture.projectRoot, "Framework"); Directory.CreateDirectory(destination); foreach (string path in selected.frameworkReferences) + { File.Copy(path, Path.Combine(destination, Path.GetFileName(path))); - environment.inputs = new ScriptCompilationInputs(selected.sdkIdentity, - Directory.EnumerateFiles(destination, "*.dll"), selected.predefinedSymbols); + } + environment.inputs = new ScriptCompilationInputs( + selected.sdkIdentity, + Directory.EnumerateFiles(destination, "*.dll"), + selected.predefinedSymbols + ); ScriptCompilationResult first = fixture.Compile(); Assert.True(first.success, string.Join(Environment.NewLine, first.diagnostics)); string referenceRoot = Path.Combine(fixture.projectRoot, "Library", "ScriptApi", "Runtime"); string[] references = Directory.GetDirectories(referenceRoot); using (FileStream changed = new(Path.Combine(destination, "System.Runtime.dll"), FileMode.Append)) + { changed.WriteByte(0); + } ScriptCompilationResult second = fixture.Compile(); Assert.True(second.success, string.Join(Environment.NewLine, second.diagnostics)); Assert.NotEqual(first.outputDirectory, second.outputDirectory); @@ -321,7 +361,8 @@ public void SourceDocumentationContentSelectsANewReferenceGeneration() try { XDocument document = XDocument.Parse(Encoding.UTF8.GetString(original)); - XElement member = document.Root!.Element("members")!.Elements("member") + XElement member = document.Root!.Element("members")! + .Elements("member") .Single(value => (string?)value.Attribute("name") == "T:Inno.Scene.SceneManager"); member.SetElementValue("summary", "Documentation generation Alpha."); document.Save(source); @@ -338,7 +379,8 @@ public void SourceDocumentationContentSelectsANewReferenceGeneration() Assert.NotEqual(first, second); Assert.Contains("generation Bravo.", File.ReadAllText(second), StringComparison.Ordinal); Assert.Equal(frozen, File.ReadAllBytes(first)); - XElement origin = XDocument.Load(second).Root!.Element("provenance")!.Elements("type") + XElement origin = XDocument.Load(second).Root!.Element("provenance")! + .Elements("type") .Single(value => (string?)value.Attribute("source") == "T:Inno.Scene.SceneManager"); Assert.Equal("T:InnoEngine.Scene.SceneManager", (string?)origin.Attribute("id")); } @@ -351,7 +393,8 @@ public void SourceDocumentationContentSelectsANewReferenceGeneration() string ReferenceDocumentation() { string project = Path.Combine(fixture.projectRoot, "Inno.GameScripts.csproj"); - XElement reference = XDocument.Load(project).Descendants("Reference") + XElement reference = XDocument.Load(project) + .Descendants("Reference") .Single(value => (string?)value.Attribute("Include") == "Inno.ScriptApi.Runtime"); return Path.ChangeExtension(Path.GetFullPath(reference.Element("HintPath")!.Value, fixture.projectRoot), ".xml"); } diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs index 7eccaa4ca..18f789af8 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs @@ -4,8 +4,8 @@ using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Core.Identity; using Inno.Core.IO; +using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Plugins.Authoring; @@ -27,8 +27,7 @@ internal sealed class CompilerFixture : IDisposable internal CompilerFixture( Action? configure = null, IScriptCompilationEnvironmentProvider? compilationEnvironment = null - ) - { + ) { projectRoot = Path.Combine(Path.GetTempPath(), "InnoCompilerTests", Guid.NewGuid().ToString("N")); string assetsRoot = Path.Combine(projectRoot, "Assets"); string pluginsRoot = Path.Combine(projectRoot, "Plugins"); @@ -38,35 +37,61 @@ internal CompilerFixture( Directory.CreateDirectory(libraryRoot); m_identityScope = m_identities.EnterScope(); m_host = new EngineHostBuilder().UseMetadataSources( - new DotNetAssemblyCatalogSource(typeof(CompilerFixture).Assembly, - typeof(GameBehavior).Assembly, typeof(ScriptCompiler).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()).Build(); + new DotNetAssemblyCatalogSource( + typeof(CompilerFixture).Assembly, + typeof(GameBehavior).Assembly, + typeof(ScriptCompiler).Assembly + ), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ).Build(); m_diagnosticScope = m_host.diagnostics.EnterScope(); configure?.Invoke(projectRoot, m_host.serialization); var sources = new PluginSourceService(m_host.serialization, pluginsRoot, libraryRoot); PluginScanResult scan = sources.Scan(); AssetPipelineOptions options = AssetPipelineOptions.Create(assetsRoot, libraryRoot); - m_assets = new AssetPipeline(m_host.modules, m_host.types, m_host.serialization, - m_identities, m_host.diagnostics, m_host.logs, options with + m_assets = new AssetPipeline( + m_host.modules, + m_host.types, + m_host.serialization, + m_identities, + m_host.diagnostics, + m_host.logs, + options with { enableFileSystemWatcher = false, sourceMounts = [.. options.sourceMounts!, .. PluginSourceService.GetActivatableMounts(scan)] - }); + } + ); m_settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.Combine(projectRoot, "Settings.Project.inno")), - m_host.types, m_host.serialization, new ProjectId("tests.compiler"), - AssetSerializationContext.Create(m_assets)); - m_plugins = new PluginEnvironment(m_assets, m_settings, m_host.serialization, - pluginsRoot, libraryRoot, scan, m_host.modules.generations); + m_host.types, + m_host.serialization, + new ProjectId("tests.compiler"), + AssetSerializationContext.Create(m_assets) + ); + m_plugins = new PluginEnvironment( + m_assets, + m_settings, + m_host.serialization, + pluginsRoot, + libraryRoot, + scan, + m_host.modules.generations + ); string dotnetHost = Path.Combine( Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = projectRoot, compilationEnvironment = compilationEnvironment ?? new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, projectRoot) - }, m_assets, m_plugins); + }, + m_assets, + m_plugins + ); } internal string projectRoot { get; } diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/IdeProjectIsolationTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/IdeProjectIsolationTests.cs index 836f60248..c6ff53fbf 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/IdeProjectIsolationTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/IdeProjectIsolationTests.cs @@ -1,11 +1,11 @@ -using Inno.Testing.Source; using System; using System.IO; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; -using Xunit; +using Inno.Testing.Source; namespace Inno.Scripting.Compiler.Tests; @@ -38,9 +38,13 @@ public async Task GeneratedProjectsIgnoreAmbientBuildConfiguration() """); } DotNetSdkDescriptor sdk = await ResolveSdk(Path.Combine(fixture.projectRoot, "Inno.GameScripts.csproj")); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "build", "InnoProject.sln", "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet"], - fixture.projectRoot, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + fixture.projectRoot, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); } /// @@ -54,7 +58,8 @@ public async Task NestedSolutionRestoresOnlyItsOwnProjects() { string repository = TestRepository.GetRoot(typeof(IdeProjectIsolationTests).Assembly); using ProcessOwnedDirectory owner = await ProcessOwnedDirectory.CreateAsync( - Path.Combine(repository, "artifacts", "acceptance", "nested-solution-tests")); + Path.Combine(repository, "artifacts", "acceptance", "nested-solution-tests") + ); string project = Path.Combine(owner.directory, "Nested.csproj"); File.WriteAllText(project, """ @@ -72,15 +77,27 @@ public async Task NestedSolutionRestoresOnlyItsOwnProjects() """); DotNetSdkDescriptor sdk = await ResolveSdk(project); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "new", "sln", "--format", "sln", "--name", "Nested"], - owner.directory, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + owner.directory, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "sln", "Nested.sln", "add", "Nested.csproj"], - owner.directory, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); - await ToolchainEnvironment.RunAsync(sdk.hostPath, + owner.directory, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); + await ToolchainEnvironment.RunAsync( + sdk.hostPath, [sdk.cliPath, "restore", "Nested.sln", "--disable-build-servers", "-m:1", "-nr:false"], - owner.directory, CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath)); + owner.directory, + CancellationToken.None, + DotNetSdkEnvironment.Create(sdk.hostPath) + ); Assert.True(File.Exists(Path.Combine(owner.directory, "obj", "project.assets.json"))); } diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs index 46ed5432b..475665953 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs @@ -31,16 +31,23 @@ public async Task ReusedAssembliesPublishAfterATemporaryStagingReaderReleasesThe Dictionary expected = Directory.EnumerateFiles(previous, "*.dll") .ToDictionary(static path => Path.GetFileName(path)!, File.ReadAllBytes, StringComparer.Ordinal); string root = Path.GetDirectoryName(previous)!; - Assert.StartsWith(Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, - Path.GetFullPath(previous), StringComparison.OrdinalIgnoreCase); + Assert.StartsWith( + Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, + Path.GetFullPath(previous), + StringComparison.OrdinalIgnoreCase + ); Directory.Delete(previous, recursive: true); HashSet existing = Directory.EnumerateFiles(root, "*.dll", SearchOption.AllDirectories) .ToHashSet(StringComparer.OrdinalIgnoreCase); - using var observer = new StagingReader(root, existing, - $"Reused cached {baseline.compiledAssemblyNames[^1]} assembly artifact."); + using var observer = new StagingReader( + root, + existing, + $"Reused cached {baseline.compiledAssemblyNames[^1]} assembly artifact." + ); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); Task compilation = fixture.compiler - .CompileAuthoringGenerationAsync(observer, cancellation.Token).AsTask(); + .CompileAuthoringGenerationAsync(observer, cancellation.Token) + .AsTask(); Exception? compilationFailure = null; bool captured = false; try @@ -48,15 +55,22 @@ public async Task ReusedAssembliesPublishAfterATemporaryStagingReaderReleasesThe await observer.captured.WaitAsync(TimeSpan.FromSeconds(20)); captured = true; await Task.Delay(150); - Assert.False(compilation.IsCompleted, - compilation.Exception?.ToString() ?? "A staged assembly borrow must delay publication."); + Assert.False( + compilation.IsCompleted, + compilation.Exception?.ToString() ?? "A staged assembly borrow must delay publication." + ); } finally { if (!captured) + { cancellation.Cancel(); + } observer.Dispose(); - compilationFailure = await Record.ExceptionAsync(async () => { _ = await compilation; }); + compilationFailure = await Record.ExceptionAsync(async () => + { + _ = await compilation; + }); } Assert.Null(compilationFailure); ScriptCompilationResult result = await compilation; @@ -65,7 +79,9 @@ public async Task ReusedAssembliesPublishAfterATemporaryStagingReaderReleasesThe Assert.Empty(result.compiledAssemblyNames); Assert.Equal(baseline.compiledAssemblyNames, result.reusedAssemblyNames); foreach ((string name, byte[] bytes) in expected) + { Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(result.outputDirectory!, name))); + } } /// @@ -99,8 +115,11 @@ private static void VerifyRejectedReplacement() ScriptCompilationResult baseline = fixture.Compile(); Assert.True(baseline.success, string.Join(Environment.NewLine, baseline.diagnostics)); string publication = Assert.IsType(baseline.outputDirectory); - Assert.StartsWith(Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, - Path.GetFullPath(publication), StringComparison.OrdinalIgnoreCase); + Assert.StartsWith( + Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, + Path.GetFullPath(publication), + StringComparison.OrdinalIgnoreCase + ); Dictionary original = Directory.EnumerateFiles(publication, "*", SearchOption.AllDirectories) .ToDictionary(path => Path.GetRelativePath(publication, path), File.ReadAllBytes, StringComparer.Ordinal); string assembly = Directory.EnumerateFiles(publication, "*.dll").First(); @@ -111,22 +130,32 @@ private static void VerifyRejectedReplacement() { Exception? failure = Record.Exception(() => fixture.Compile()); Assert.True(failure is IOException or UnauthorizedAccessException, failure?.ToString()); - Assert.Equal(rejected.Keys.Order(StringComparer.Ordinal), + Assert.Equal( + rejected.Keys.Order(StringComparer.Ordinal), Directory.EnumerateFiles(publication, "*", SearchOption.AllDirectories) - .Select(path => Path.GetRelativePath(publication, path)).Order(StringComparer.Ordinal)); + .Select(path => Path.GetRelativePath(publication, path)) + .Order(StringComparer.Ordinal) + ); foreach ((string path, byte[] bytes) in rejected) + { Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(publication, path))); + } } ScriptCompilationResult repaired = fixture.Compile(); Assert.True(repaired.success, string.Join(Environment.NewLine, repaired.diagnostics)); Assert.Equal(publication, repaired.outputDirectory); Assert.Empty(repaired.compiledAssemblyNames); - Assert.Equal(original.Keys.Order(StringComparer.Ordinal), + Assert.Equal( + original.Keys.Order(StringComparer.Ordinal), Directory.EnumerateFiles(publication, "*", SearchOption.AllDirectories) - .Select(path => Path.GetRelativePath(publication, path)).Order(StringComparer.Ordinal)); + .Select(path => Path.GetRelativePath(publication, path)) + .Order(StringComparer.Ordinal) + ); foreach ((string path, byte[] bytes) in original) + { Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(publication, path))); + } } private static void VerifyRejectedPublication(bool cancel) @@ -144,27 +173,40 @@ private static void VerifyRejectedPublication(bool cancel) string publication = Assert.IsType(candidate.outputDirectory); Assert.NotEqual(lastGood, publication); Assert.NotEmpty(candidate.compiledAssemblyNames); - Assert.StartsWith(Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, - Path.GetFullPath(publication), StringComparison.OrdinalIgnoreCase); + Assert.StartsWith( + Path.GetFullPath(fixture.projectRoot) + Path.DirectorySeparatorChar, + Path.GetFullPath(publication), + StringComparison.OrdinalIgnoreCase + ); string root = Path.GetDirectoryName(publication)!; Directory.Delete(publication, recursive: true); HashSet existing = Directory.EnumerateFiles(root, "*.dll", SearchOption.AllDirectories) .ToHashSet(StringComparer.OrdinalIgnoreCase); - using var observer = new StagingReader(root, existing, - $"Reused cached {candidate.compiledAssemblyNames[^1]} assembly artifact."); + using var observer = new StagingReader( + root, + existing, + $"Reused cached {candidate.compiledAssemblyNames[^1]} assembly artifact." + ); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); Task compilation = fixture.compiler - .CompileAuthoringGenerationAsync(observer, cancellation.Token).AsTask(); + .CompileAuthoringGenerationAsync(observer, cancellation.Token) + .AsTask(); try { observer.captured.WaitAsync(TimeSpan.FromSeconds(20)).GetAwaiter().GetResult(); if (cancel) + { cancellation.Cancel(); + } Exception? failure = Record.Exception(() => compilation.WaitAsync(TimeSpan.FromSeconds(10)).GetAwaiter().GetResult()); if (cancel) + { Assert.IsAssignableFrom(failure); + } else + { Assert.True(failure is IOException or UnauthorizedAccessException, failure?.ToString()); + } } finally { @@ -175,13 +217,17 @@ private static void VerifyRejectedPublication(bool cancel) Assert.False(Directory.Exists(publication)); foreach ((string path, byte[] bytes) in saved) + { Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(lastGood, path))); + } ScriptCompilationResult recovered = fixture.Compile(); Assert.True(recovered.success, string.Join(Environment.NewLine, recovered.diagnostics)); Assert.Equal(publication, recovered.outputDirectory); Assert.Empty(recovered.compiledAssemblyNames); foreach ((string path, byte[] bytes) in saved) + { Assert.Equal(bytes, File.ReadAllBytes(Path.Combine(lastGood, path))); + } } private sealed class StagingReader : IProgress, IDisposable @@ -210,11 +256,14 @@ public void Report(ScriptCompilationProgress value) lock (m_sync) { if (m_retired || m_reader is not null || value.stage != m_stage) + { return; + } try { string[] candidates = Directory.EnumerateFiles(m_root, "*.dll", SearchOption.AllDirectories) - .Where(path => !m_existing.Contains(path)).ToArray(); + .Where(path => !m_existing.Contains(path)) + .ToArray(); Assert.NotEmpty(candidates); m_reader = new FileStream(candidates[0], FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); m_captured.TrySetResult(true); @@ -247,7 +296,9 @@ private sealed class WindowsDirectorySharingFactAttribute : FactAttribute public WindowsDirectorySharingFactAttribute() { if (!OperatingSystem.IsWindows()) + { Skip = "This fixture requires Windows directory rename sharing semantics."; + } } } } diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/SdkCompilationInputsTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/SdkCompilationInputsTests.cs index a3da3069f..d509d9456 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/SdkCompilationInputsTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/SdkCompilationInputsTests.cs @@ -3,8 +3,8 @@ using System.Linq; using System.Runtime.InteropServices; using System.Threading; -using Inno.Build; using Xunit; +using Inno.Build; namespace Inno.Scripting.Compiler.Tests; @@ -14,8 +14,10 @@ public sealed class SdkCompilationInputsTests public void SelectedSdkSuppliesFrameworkSymbolsAndIdeReferences() { using var fixture = new CompilerFixture(); - string host = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string host = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); ScriptCompilationInputs inputs = new SdkScriptCompilationEnvironment(host, fixture.projectRoot).Capture(); Assert.Contains("NET10_0", inputs.predefinedSymbols); Assert.Contains("NET10_0_OR_GREATER", inputs.predefinedSymbols); @@ -37,8 +39,12 @@ public sealed class FrameworkSymbols { } Assert.Contains("ValidateInnoScriptSdk", project, StringComparison.Ordinal); Assert.Contains("true", project, StringComparison.Ordinal); foreach (string path in inputs.frameworkReferences) + { Assert.Contains(path.Replace("&", "&", StringComparison.Ordinal), project, StringComparison.Ordinal); - Assert.Empty(Directory.EnumerateFiles(Path.Combine(fixture.projectRoot, "Library", "Scripting"), "*.csproj", SearchOption.AllDirectories)); + } + Assert.Empty( + Directory.EnumerateFiles(Path.Combine(fixture.projectRoot, "Library", "Scripting"), "*.csproj", SearchOption.AllDirectories) + ); } [Fact] @@ -61,8 +67,10 @@ public void CancelledSdkEvaluationCreatesNoPublishedInputs() using var fixture = new CompilerFixture(); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - string host = Path.Combine(Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + string host = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); var provider = new SdkScriptCompilationEnvironment(host, fixture.projectRoot); Assert.ThrowsAny(() => provider.Capture(cancellation.Token)); Assert.Empty(Directory.EnumerateFiles(Path.Combine(fixture.projectRoot, "Library"), "*.csproj", SearchOption.AllDirectories)); diff --git a/tests/source/Inno.Testing.Source/TestRepository.cs b/tests/source/Inno.Testing.Source/TestRepository.cs index 05545bc85..57345e4dc 100644 --- a/tests/source/Inno.Testing.Source/TestRepository.cs +++ b/tests/source/Inno.Testing.Source/TestRepository.cs @@ -35,13 +35,19 @@ public static class TestRepository AssemblyMetadataAttribute? declaration = testAssembly.GetCustomAttributes() .SingleOrDefault(static attribute => attribute.Key == C_ARTIFACTS_METADATA); if (declaration is null) + { return null; + } string? directory = declaration.Value; if (string.IsNullOrWhiteSpace(directory) || !Path.IsPathFullyQualified(directory)) + { throw new InvalidOperationException("Tests require the absolute SDK artifacts owner recorded by their project."); + } directory = GetProcessBinding(testAssembly, "INNO_TESTING_ARTIFACTS_PATH") ?? directory; if (string.IsNullOrWhiteSpace(directory) || !Path.IsPathFullyQualified(directory)) + { throw new InvalidOperationException("Tests require the absolute SDK artifacts owner recorded by their project."); + } return Path.GetFullPath(directory); } @@ -68,11 +74,13 @@ public static string GetRoot(Assembly testAssembly) string? directory = testAssembly.GetCustomAttributes() .SingleOrDefault(static attribute => attribute.Key == C_ROOT_METADATA)?.Value; if (string.IsNullOrWhiteSpace(directory) || !Path.IsPathFullyQualified(directory)) + { throw new InvalidOperationException("Tests require the source checkout declared by their SDK project."); + } directory = GetProcessBinding(testAssembly, "INNO_TESTING_REPOSITORY_ROOT") ?? directory; if (string.IsNullOrWhiteSpace(directory) || !Path.IsPathFullyQualified(directory) - || !File.Exists(Path.Combine(directory, "InnoEngine.sln"))) - { + || !File.Exists(Path.Combine(directory, "InnoEngine.sln")) + ) { throw new InvalidOperationException("Tests require the source checkout declared by their SDK project."); } @@ -85,12 +93,18 @@ string variable ) { string? owner = Environment.GetEnvironmentVariable("INNO_TESTING_ARTIFACTS_PATH"); if (owner is null || testAssembly.IsDynamic || string.IsNullOrWhiteSpace(testAssembly.Location)) + { return null; + } if (string.IsNullOrWhiteSpace(owner) || !Path.IsPathFullyQualified(owner)) + { throw new InvalidOperationException("The test process must declare an absolute output owner before rebinding inputs."); + } string prefix = Path.TrimEndingDirectorySeparator(Path.GetFullPath(owner)) + Path.DirectorySeparatorChar; if (!Path.GetFullPath(testAssembly.Location).StartsWith(prefix, StringComparison.Ordinal)) + { return null; + } return Environment.GetEnvironmentVariable(variable); } } diff --git a/tests/storage/Inno.Storage.Tests/StorageTests.cs b/tests/storage/Inno.Storage.Tests/StorageTests.cs index fdf72b13f..779e89b40 100644 --- a/tests/storage/Inno.Storage.Tests/StorageTests.cs +++ b/tests/storage/Inno.Storage.Tests/StorageTests.cs @@ -1,18 +1,17 @@ -using Inno.Core.Logging; -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; -using Inno.Runtime.Contracts; using System; -using System.IO; using System.Collections.Generic; +using System.IO; using System.Threading; using System.Threading.Tasks; -using Inno.Core.Execution; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Adapter.Storage.FileSystem; -using Inno.Storage.Runtime; +using Inno.Core.Execution; +using Inno.Core.Logging; using Inno.Runtime; -using Xunit; +using Inno.Runtime.Contracts; +using Inno.Storage.Runtime; namespace Inno.Storage.Tests; @@ -85,7 +84,9 @@ public async Task DirectAdapterDisposalDoesNotDestroyAnActiveWritesSemaphore() finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -110,7 +111,9 @@ public async Task FileSystemAdapterAtomicallyStoresAndListsValues() finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -143,9 +146,13 @@ public void ExecutionScopesRequireLastInFirstOutDisposal() finally { if (Directory.Exists(firstRoot)) + { Directory.Delete(firstRoot, recursive: true); + } if (Directory.Exists(secondRoot)) + { Directory.Delete(secondRoot, recursive: true); + } } } @@ -156,8 +163,11 @@ public void RuntimeSubsystemBindsStorageForTheCompleteFrame() try { using EngineHost host = new EngineHostBuilder() - .UseMetadataSources(new DotNetAssemblyCatalogSource(typeof(StorageTests).Assembly), - new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource()) + .UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(StorageTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ) .Build(); var options = new RuntimeSessionOptions { @@ -168,22 +178,24 @@ public void RuntimeSubsystemBindsStorageForTheCompleteFrame() createSubsystems = owner => [ new StorageRuntimeFactory(context => - new FileSystemApplicationStorage(Path.Combine( - root, "tests.storage", - "Storage"))), + new FileSystemApplicationStorage(Path.Combine(root, "tests.storage", "Storage"))), new StorageProbeFactory() ] }; using (RuntimeSession session = host.CreateSession(options)) + { session.Tick(0.01f); + } Assert.Throws(() => _ = StorageExecutionContext.current); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -194,15 +206,15 @@ private sealed class StorageProbeFactory : IRuntimeSubsystemFactory { public RuntimeSubsystemDescriptor descriptor { get; } = new( new RuntimeSubsystemId("tests.storage.probe"), - dependencies: [new RuntimeSubsystemId("inno.runtime.storage")]); + dependencies: [new RuntimeSubsystemId("inno.runtime.storage")] + ); public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => new StorageProbe(); } private sealed class StorageProbe : RuntimeSubsystem { - protected override void OnUpdate(RuntimeFrame frame) - => Assert.NotNull(StorageExecutionContext.current); + protected override void OnUpdate(RuntimeFrame frame) => Assert.NotNull(StorageExecutionContext.current); } private sealed class PendingStorage : IApplicationStorage, IDisposable @@ -211,17 +223,37 @@ private sealed class PendingStorage : IApplicationStorage, IDisposable internal CancellationToken token { get; private set; } internal bool disposed { get; private set; } internal ReadOnlyMemory value { get; private set; } - public ValueTask WriteAsync(StorageKey key, ReadOnlyMemory value, CancellationToken cancellationToken = default) - { + + public ValueTask WriteAsync( + StorageKey key, + ReadOnlyMemory value, + CancellationToken cancellationToken = default + ) { token = cancellationToken; this.value = value; return new ValueTask(completion.Task); } - public ValueTask ExistsAsync(StorageKey key, CancellationToken cancellationToken = default) => ValueTask.FromResult(false); - public ValueTask ReadAsync(StorageKey key, CancellationToken cancellationToken = default) => ValueTask.FromResult(null); - public ValueTask DeleteAsync(StorageKey key, CancellationToken cancellationToken = default) => ValueTask.FromResult(false); - public ValueTask> ListAsync(StorageKey? prefix = null, CancellationToken cancellationToken = default) - => ValueTask.FromResult>(Array.Empty()); + + public ValueTask ExistsAsync( + StorageKey key, + CancellationToken cancellationToken = default + ) => ValueTask.FromResult(false); + + public ValueTask ReadAsync( + StorageKey key, + CancellationToken cancellationToken = default + ) => ValueTask.FromResult(null); + + public ValueTask DeleteAsync( + StorageKey key, + CancellationToken cancellationToken = default + ) => ValueTask.FromResult(false); + + public ValueTask> ListAsync( + StorageKey? prefix = null, + CancellationToken cancellationToken = default + ) => ValueTask.FromResult>(Array.Empty()); + public void Dispose() => disposed = true; } } diff --git a/tests/text/Inno.Text.Tests/TextServiceTests.cs b/tests/text/Inno.Text.Tests/TextServiceTests.cs index 22ff57dac..e6eeae736 100644 --- a/tests/text/Inno.Text.Tests/TextServiceTests.cs +++ b/tests/text/Inno.Text.Tests/TextServiceTests.cs @@ -1,9 +1,9 @@ -using Inno.Adapter.Serialization.DotNet; -using Inno.Adapter.Modules.DotNet; using System; using System.IO; using System.Reflection; - +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; using Inno.Adapter.Text.FreeTypeHarfBuzz; using Inno.Assets; using Inno.Assets.Pipeline; @@ -14,7 +14,6 @@ using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Text.Assets; -using Xunit; namespace Inno.Text.Tests; @@ -39,7 +38,9 @@ public TextServiceTests() Directory.CreateDirectory(m_assets); m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost(new ModuleHostOptions - { catalogSource = new DotNetAssemblyCatalogSource(typeof(TextServiceTests).Assembly) }); + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(TextServiceTests).Assembly) + }); _ = Assembly.Load("Inno.Text.Assets"); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); @@ -62,8 +63,7 @@ public void ImporterPublishesMetadataAndSeparateEncodedFont() File.WriteAllBytes(Path.Combine(m_assets, "Interface.ttf"), source); using AssetLoader loader = CreateLoader(); - FontAsset font = Assert.IsType( - loader.Load(AssetPath.Project("Interface.ttf"), typeof(FontAsset))); + FontAsset font = Assert.IsType(loader.Load(AssetPath.Project("Interface.ttf"), typeof(FontAsset))); Assert.Equal(1, font.metadata!.Value.faceCount); Assert.Equal(source.Length, font.metadata.Value.encodedByteLength); @@ -79,11 +79,7 @@ public void NativeBackendShapesAndRasterizesUnicodeText() using var backend = new FreeTypeHarfBuzzTextBackend(); TextFontHandle font = backend.LoadFont(File.ReadAllBytes(FontPath()), 0); - TextLayout layout = backend.Shape( - font, - "Hello, UI!", - new TextStyle(28f), - TextShapingOptions.automatic); + TextLayout layout = backend.Shape(font, "Hello, UI!", new TextStyle(28f), TextShapingOptions.automatic); Assert.NotEmpty(layout.glyphs); Assert.True(layout.width > 0f); @@ -103,12 +99,13 @@ public void Dispose() m_logs.Dispose(); m_identityScope.Dispose(); if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } private AssetLoader CreateLoader() => new(m_types, m_serialization, m_identities, m_diagnostics, m_logs, m_assets, m_library); - private static string FontPath() - => Path.Combine(AppContext.BaseDirectory, "TestData", "LatoLatin-Regular.ttf"); + private static string FontPath() => Path.Combine(AppContext.BaseDirectory, "TestData", "LatoLatin-Regular.ttf"); } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs index aa3743ace..f66a9aab3 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs @@ -13,8 +13,14 @@ public AgentDocumentTests() { Directory.CreateDirectory(m_root); File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), string.Empty); - foreach (string category in new[] { "rulebook", "records", "records/plans", "records/decisions", "records/acceptance", "records/history" }) - { + foreach (string category in new[] { + "rulebook", + "records", + "records/plans", + "records/decisions", + "records/acceptance", + "records/history" + }) { string directory = Path.Combine(m_root, ".agents", category); Directory.CreateDirectory(directory); File.WriteAllText(Path.Combine(directory, "README.md"), "# Category\n"); @@ -24,7 +30,10 @@ public AgentDocumentTests() [Fact] public void AgentLinksUseParsedHeadingsReferencesAndExplicitAnchorsWithoutReadingCodeLinks() { - File.WriteAllText(Path.Combine(m_root, "AGENTS.md"), "# Entry\n\n[Guide][guide]\n\n[guide]: .agents/rulebook/README.md#hello-world\n\n[Explicit](.agents/rulebook/README.md#contract)\n\n~~~text\n[missing](missing.md)\n~~~\n"); + File.WriteAllText( + Path.Combine(m_root, "AGENTS.md"), + "# Entry\n\n[Guide][guide]\n\n[guide]: .agents/rulebook/README.md#hello-world\n\n[Explicit](.agents/rulebook/README.md#contract)\n\n~~~text\n[missing](missing.md)\n~~~\n" + ); File.WriteAllText(Path.Combine(m_root, ".agents/rulebook/README.md"), "# Hello *World*\n\n\n"); Assert.Equal(0, ArchitectureCommandFixture.Run(m_root, "--agent-documents-only").exitCode); File.AppendAllText(Path.Combine(m_root, "AGENTS.md"), "\n[Broken](.agents/rulebook/README.md#absent)\n"); diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs index 0c5e3084c..4ccdc2d1f 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs @@ -4,8 +4,8 @@ using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; using Xunit; +using Inno.Build.Toolchains; namespace Inno.Tooling.Architecture.Tests; @@ -16,8 +16,15 @@ public sealed class ArchitectureOutputOwnerTests public async Task PublicContractsUseTheEvaluatedOutputOwnerInsteadOfStaleDefaultAssemblies() { string root = Path.Combine(Path.GetTempPath(), "InnoArchitectureOutputTests", Guid.NewGuid().ToString("N")); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(2)); try { @@ -43,56 +50,140 @@ public async Task PublicContractsUseTheEvaluatedOutputOwnerInsteadOfStaleDefault string source = Path.Combine(editor, "Probe.cs"); File.WriteAllText(source, "namespace Inno.Editor.Probe; public sealed class Probe { }"); await Build([]); - File.WriteAllText(source, "namespace Inno.Editor.Probe; public sealed class Probe { public Inno.Core.Contract.Contract value { get; } = new(); }"); + File.WriteAllText( + source, + "namespace Inno.Editor.Probe; public sealed class Probe { public Inno.Core.Contract.Contract value { get; } = new(); }" + ); string artifacts = Path.Combine(root, "owned-output"); await Build(["-p:ArtifactsPath=" + artifacts]); string graph = Path.Combine(root, "graph.json"); - string correct = ArchitectureCommandFixture.Run(root, "--dotnet", host, - "--artifacts-path", artifacts, "--project-graph", graph).output; + string correct = ArchitectureCommandFixture.Run( + root, + "--dotnet", + host, + "--artifacts-path", + artifacts, + "--project-graph", + graph + ).output; Assert.DoesNotContain("Inno.Core.Contract is an implementation dependency", correct, StringComparison.Ordinal); - Assert.Contains(artifacts.Replace('\\', '/'), File.ReadAllText(graph).Replace('\\', '/').Replace("//", "/"), StringComparison.OrdinalIgnoreCase); + Assert.Contains( + artifacts.Replace('\\', '/'), + File.ReadAllText(graph).Replace('\\', '/').Replace("//", "/"), + StringComparison.OrdinalIgnoreCase + ); string selectedOwner = Path.GetRelativePath(root, project).Replace('\\', '/'); - string selected = ArchitectureCommandFixture.Run(root, "--metadata-only", "--dotnet", host, - "--artifacts-path", artifacts, "--api-project", selectedOwner).output; + string selected = ArchitectureCommandFixture.Run( + root, + "--metadata-only", + "--dotnet", + host, + "--artifacts-path", + artifacts, + "--api-project", + selectedOwner + ).output; Assert.DoesNotContain("unresolved public signature type", selected, StringComparison.Ordinal); Assert.DoesNotContain("output is missing", selected, StringComparison.Ordinal); string snapshot = Path.Combine(root, "sdk-graph.json"); - File.WriteAllText(snapshot, await ManagedProjectGraphCapture.CaptureAsync(root, host, - [project, Path.Combine(contract, "Inno.Core.Contract.csproj")], new Dictionary - { - ["Configuration"] = "Debug", ["ArtifactsPath"] = artifacts, - ["DesignTimeBuild"] = "true", ["BuildProjectReferences"] = "false", ["InnoProductRestore"] = "false" - }, cancellation.Token)); - string captured = ArchitectureCommandFixture.Run(root, "--metadata-only", "--dotnet", host, - "--artifacts-path", artifacts, "--api-project", selectedOwner, "--sdk-snapshot", snapshot).output; + File.WriteAllText( + snapshot, + await ManagedProjectGraphCapture.CaptureAsync( + root, + host, + [project, Path.Combine(contract, "Inno.Core.Contract.csproj")], + new Dictionary + { + ["Configuration"] = "Debug", + ["ArtifactsPath"] = artifacts, + ["DesignTimeBuild"] = "true", + ["BuildProjectReferences"] = "false", + ["InnoProductRestore"] = "false" + }, + cancellation.Token + ) + ); + string captured = ArchitectureCommandFixture.Run( + root, + "--metadata-only", + "--dotnet", + host, + "--artifacts-path", + artifacts, + "--api-project", + selectedOwner, + "--sdk-snapshot", + snapshot + ).output; Assert.DoesNotContain("unresolved public signature type", captured, StringComparison.Ordinal); Assert.DoesNotContain("output is missing", captured, StringComparison.Ordinal); string reference = Path.Combine(root, "api-reference.json"); - Assert.Equal(0, DocumentationReferences.ExportApi(["--engine-root", root, "--dotnet", host, - "--project", selectedOwner, "--output", reference])); - Assert.Equal(0, await DocumentationReferences.ValidateApiAsync(["--engine-root", root, - "--dotnet", host, "--artifacts-path", artifacts, "--reference", reference, - "--output", Path.Combine(root, "api-validation.json")], cancellation.Token)); + Assert.Equal( + 0, + DocumentationReferences.ExportApi([ + "--engine-root", + root, + "--dotnet", + host, + "--project", + selectedOwner, + "--output", + reference + ]) + ); + Assert.Equal( + 0, + await DocumentationReferences.ValidateApiAsync([ + "--engine-root", + root, + "--dotnet", + host, + "--artifacts-path", + artifacts, + "--reference", + reference, + "--output", + Path.Combine(root, "api-validation.json") + ], cancellation.Token) + ); - File.WriteAllText(project, File.ReadAllText(project).Replace("Include=", "PrivateAssets=\"compile\" Include=", StringComparison.Ordinal)); - string rejected = ArchitectureCommandFixture.Run(root, "--metadata-only", "--dotnet", host, - "--artifacts-path", artifacts, "--api-project", selectedOwner).output; + File.WriteAllText( + project, + File.ReadAllText(project).Replace("Include=", "PrivateAssets=\"compile\" Include=", StringComparison.Ordinal) + ); + string rejected = ArchitectureCommandFixture.Run( + root, + "--metadata-only", + "--dotnet", + host, + "--artifacts-path", + artifacts, + "--api-project", + selectedOwner + ).output; Assert.Contains("public/protected API exposes Inno.Core.Contract", rejected, StringComparison.Ordinal); async Task Build(string[] properties) { - await ToolchainEnvironment.RunAsync(host, ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet", .. properties], - root, cancellation.Token, DotNetSdkEnvironment.Create(host)); + await ToolchainEnvironment.RunAsync( + host, + ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet", .. properties], + root, + cancellation.Token, + DotNetSdkEnvironment.Create(host) + ); } } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs index b9b1962e5..b99605b63 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs @@ -27,10 +27,16 @@ public sealed class Probe """; fixture.Compile(project, "Inno.Core.Probe", source); fixture.WriteSource(project, source); - Assert.DoesNotContain("inheritdoc requires a documented overridden or implemented contract", - fixture.Run("--source-only"), StringComparison.Ordinal); - Assert.Contains("inheritdoc requires a documented overridden or implemented contract", - fixture.Run("--metadata-only", "--api-project", project + "/Inno.Core.Probe.csproj"), StringComparison.Ordinal); + Assert.DoesNotContain( + "inheritdoc requires a documented overridden or implemented contract", + fixture.Run("--source-only"), + StringComparison.Ordinal + ); + Assert.Contains( + "inheritdoc requires a documented overridden or implemented contract", + fixture.Run("--metadata-only", "--api-project", project + "/Inno.Core.Probe.csproj"), + StringComparison.Ordinal + ); } [Fact] @@ -66,8 +72,11 @@ public class Probe : Inno.Core.Contract.IContract File.Copy(contract, copied); File.WriteAllText(Path.ChangeExtension(copied, ".xml"), ""); - Assert.DoesNotContain("inheritdoc requires a documented overridden or implemented contract", - fixture.Run(), StringComparison.Ordinal); + Assert.DoesNotContain( + "inheritdoc requires a documented overridden or implemented contract", + fixture.Run(), + StringComparison.Ordinal + ); } [Theory] @@ -122,30 +131,35 @@ bool accepted if (scenario is "override" or "chain") { source = "namespace Inno.Editor.Probe; public class Base {\n" + contract - + "public virtual int Combine(int left, int right) => left + right; }\n"; + + "public virtual int Combine(int left, int right) => left + right; }\n"; if (scenario == "chain") { source += "public class Middle : Base {\n/// \n" - + "public override int Combine(int left, int right) => base.Combine(left, right); }\n"; + + "public override int Combine(int left, int right) => base.Combine(left, right); }\n"; } source += "public class Probe : " + (scenario == "chain" ? "Middle" : "Base") - + " {\n/// \npublic override int Combine(int left, int right) => left + right; }"; + + " {\n/// \npublic override int Combine(int left, int right) => left + right; }"; } else { source = "namespace Inno.Editor.Probe; public interface IContract {\n" + contract - + "int Combine(int left, int right); }\npublic class Probe" - + (scenario == "standalone" ? "" : " : IContract") + " {\n" - + (scenario == "wrong-cref" ? "/// \n" : "/// \n") - + "public int Combine(int left, int right) => left + right; }"; + + "int Combine(int left, int right); }\npublic class Probe" + + (scenario == "standalone" ? "" : " : IContract") + " {\n" + + (scenario == "wrong-cref" ? "/// \n" : "/// \n") + + "public int Combine(int left, int right) => left + right; }"; } string relative = "src/composition/editor/framework/Inno.Editor.Probe"; fixture.Compile(relative, "Inno.Editor.Probe", source); fixture.WriteSource(relative, source); string output = fixture.Run(); - Assert.Equal(!accepted, output.Contains( - "inheritdoc requires a documented overridden or implemented contract", StringComparison.Ordinal)); + Assert.Equal( + !accepted, + output.Contains( + "inheritdoc requires a documented overridden or implemented contract", + StringComparison.Ordinal + ) + ); } [Theory] @@ -156,8 +170,11 @@ public void ReplaceableBackendContractsUseOpenIdentifiers( bool rejected ) { using var fixture = new SymbolFixture(); - fixture.Compile("src/adapters/input/Inno.Adapter.Input", "Inno.Adapter.Input", - "namespace Inno.Adapter.Input; " + declaration); + fixture.Compile( + "src/adapters/input/Inno.Adapter.Input", + "Inno.Adapter.Input", + "namespace Inno.Adapter.Input; " + declaration + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("replaceable backend selections require open IDs", StringComparison.Ordinal)); } @@ -197,13 +214,18 @@ public struct MaEngine { public int value; } public class MaBase { } public interface IMaBackend { } """); - fixture.Compile("src/services/audio/Inno.Audio", "Inno.Audio", """ + fixture.Compile( + "src/services/audio/Inno.Audio", + "Inno.Audio", + """ using System; using System.Collections.Generic; using System.Threading.Tasks; using Raw = Inno.Native.MiniAudio.MaEngine; namespace Inno.Audio; - """ + declaration, native); + """ + declaration, + native + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("exposes native symbol", StringComparison.Ordinal)); @@ -217,10 +239,17 @@ namespace Inno.Audio; public void NativePolicyUsesAssemblyIdentityRatherThanSourceTypeNames(string assemblyName) { using var fixture = new SymbolFixture(); - string native = fixture.Compile("backends/" + assemblyName["Inno.Native.".Length..] + "/native/" + assemblyName, assemblyName, - "namespace Renamed; public struct NeutralLookingName { public int value; }"); - fixture.Compile("src/services/audio/Inno.Audio", "Inno.Audio", - "namespace Inno.Audio; public class Probe { public Renamed.NeutralLookingName value; }", native); + string native = fixture.Compile( + "backends/" + assemblyName["Inno.Native.".Length..] + "/native/" + assemblyName, + assemblyName, + "namespace Renamed; public struct NeutralLookingName { public int value; }" + ); + fixture.Compile( + "src/services/audio/Inno.Audio", + "Inno.Audio", + "namespace Inno.Audio; public class Probe { public Renamed.NeutralLookingName value; }", + native + ); Assert.Contains("exposes native symbol Renamed.NeutralLookingName", fixture.Run(), StringComparison.Ordinal); } @@ -235,10 +264,17 @@ public void CompositionOnlyExposesNeutralAdapterContracts( bool rejected ) { using var fixture = new SymbolFixture(); - string implementation = fixture.Compile("src/adapters/audio/" + adapter, adapter, - "namespace Backend; public class Device { }"); - fixture.Compile("src/composition/" + owner, owner, - "namespace Product; public class Probe { public Backend.Device device; }", implementation); + string implementation = fixture.Compile( + "src/adapters/audio/" + adapter, + adapter, + "namespace Backend; public class Device { }" + ); + fixture.Compile( + "src/composition/" + owner, + owner, + "namespace Product; public class Probe { public Backend.Device device; }", + implementation + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("exposes concrete adapter", StringComparison.Ordinal)); } @@ -254,12 +290,22 @@ public void EditorPublicReferencePolicyFollowsCompiledVisibility( bool rejected ) { using var fixture = new SymbolFixture(); - string dependency = fixture.Compile("src/foundation/core/Inno.Core.Values", "Inno.Core.Values", - "namespace Values; public class Value { }"); - fixture.Compile("src/composition/editor/framework/Inno.Editor.Probe", "Inno.Editor.Probe", - "using Values; namespace Inno.Editor.Probe; " + declaration, dependency); - fixture.AddReference("src/composition/editor/framework/Inno.Editor.Probe/Inno.Editor.Probe.csproj", - "src/foundation/core/Inno.Core.Values/Inno.Core.Values.csproj", privateReference); + string dependency = fixture.Compile( + "src/foundation/core/Inno.Core.Values", + "Inno.Core.Values", + "namespace Values; public class Value { }" + ); + fixture.Compile( + "src/composition/editor/framework/Inno.Editor.Probe", + "Inno.Editor.Probe", + "using Values; namespace Inno.Editor.Probe; " + declaration, + dependency + ); + fixture.AddReference( + "src/composition/editor/framework/Inno.Editor.Probe/Inno.Editor.Probe.csproj", + "src/foundation/core/Inno.Core.Values/Inno.Core.Values.csproj", + privateReference + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("declare a direct public ProjectReference", StringComparison.Ordinal)); } @@ -277,7 +323,11 @@ bool rejected string native = fixture.Compile("backends/Sdl3/native/Inno.Native.Sdl3", "Inno.Native.Sdl3", "public struct Raw { }"); string projectName = Path.GetFileName(relative); fixture.Compile(relative, projectName, "internal class Probe { private Raw value; }", native); - fixture.AddReference(relative + "/" + projectName + ".csproj", "backends/Sdl3/native/Inno.Native.Sdl3/Inno.Native.Sdl3.csproj", true); + fixture.AddReference( + relative + "/" + projectName + ".csproj", + "backends/Sdl3/native/Inno.Native.Sdl3/Inno.Native.Sdl3.csproj", + true + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("SDL3 native code is restricted", StringComparison.Ordinal)); } @@ -290,13 +340,23 @@ public void EditorImplementationReferencesRequireCompilePrivacy( bool rejected ) { using var fixture = new SymbolFixture(); - string dependency = fixture.Compile("src/foundation/core/Inno.Core.Values", "Inno.Core.Values", - "namespace Values; public class Value { }"); + string dependency = fixture.Compile( + "src/foundation/core/Inno.Core.Values", + "Inno.Core.Values", + "namespace Values; public class Value { }" + ); string relative = "src/composition/editor/framework/Inno.Editor.Probe"; - fixture.Compile(relative, "Inno.Editor.Probe", - "using Values; namespace Inno.Editor.Probe; public class Probe { private Value value; }", dependency); - fixture.AddReference(relative + "/Inno.Editor.Probe.csproj", - "src/foundation/core/Inno.Core.Values/Inno.Core.Values.csproj", privateReference); + fixture.Compile( + relative, + "Inno.Editor.Probe", + "using Values; namespace Inno.Editor.Probe; public class Probe { private Value value; }", + dependency + ); + fixture.AddReference( + relative + "/Inno.Editor.Probe.csproj", + "src/foundation/core/Inno.Core.Values/Inno.Core.Values.csproj", + privateReference + ); string output = fixture.Run(); Assert.Equal(rejected, output.Contains("is an implementation dependency", StringComparison.Ordinal)); } @@ -310,14 +370,24 @@ public void EditorReferenceGroupsKeepImplementationBeforePublicApi( bool rejected ) { using var fixture = new SymbolFixture(); - string hidden = fixture.Compile("src/foundation/core/Inno.Core.Hidden", "Inno.Core.Hidden", - "namespace Hidden; public class Value { }"); - string visible = fixture.Compile("src/foundation/core/Inno.Core.Visible", "Inno.Core.Visible", - "namespace Visible; public class Value { }"); + string hidden = fixture.Compile( + "src/foundation/core/Inno.Core.Hidden", + "Inno.Core.Hidden", + "namespace Hidden; public class Value { }" + ); + string visible = fixture.Compile( + "src/foundation/core/Inno.Core.Visible", + "Inno.Core.Visible", + "namespace Visible; public class Value { }" + ); string relative = "src/composition/editor/framework/Inno.Editor.Probe"; - fixture.Compile(relative, "Inno.Editor.Probe", + fixture.Compile( + relative, + "Inno.Editor.Probe", "namespace Inno.Editor.Probe; public class Probe { private Hidden.Value hidden; public Visible.Value visible; }", - hidden, visible); + hidden, + visible + ); string owner = relative + "/Inno.Editor.Probe.csproj"; if (layout == 1) { @@ -368,7 +438,9 @@ private sealed class SymbolFixture : IDisposable internal SymbolFixture() { foreach (string folder in new[] { "src", "native", "build", "tools", "tests" }) + { Directory.CreateDirectory(Path.Combine(m_root, folder)); + } File.WriteAllText(Path.Combine(m_root, "InnoEngine.sln"), """ Microsoft Visual Studio Solution File, Format Version 12.00 Global @@ -385,15 +457,25 @@ params string[] dependencies string directory = Path.Combine(m_root, relative); string output = Path.Combine(directory, "bin", "Debug", "net10.0", assemblyName + ".dll"); Directory.CreateDirectory(Path.GetDirectoryName(output)!); - new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), - new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0")))) + new XDocument( + new XElement( + "Project", + new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0")) + ) + ) .Save(Path.Combine(directory, assemblyName + ".csproj")); string[] platform = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator); - MetadataReference[] references = platform.Concat(dependencies).Distinct(StringComparer.OrdinalIgnoreCase) - .Select(path => MetadataReference.CreateFromFile(path)).ToArray(); - CSharpCompilation compilation = CSharpCompilation.Create(assemblyName, - [CSharpSyntaxTree.ParseText(source)], references, - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true)); + MetadataReference[] references = platform.Concat(dependencies) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(path => MetadataReference.CreateFromFile(path)) + .ToArray(); + CSharpCompilation compilation = CSharpCompilation.Create( + assemblyName, + [CSharpSyntaxTree.ParseText(source)], + references, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true) + ); var result = compilation.Emit(output, xmlDocumentationPath: Path.ChangeExtension(output, ".xml")); Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics)); return output; @@ -406,10 +488,17 @@ bool privateReference ) { string path = Path.Combine(m_root, owner); XDocument document = XDocument.Load(path); - var reference = new XElement("ProjectReference", new XAttribute("Include", - Path.GetRelativePath(Path.GetDirectoryName(path)!, Path.Combine(m_root, target)))); + var reference = new XElement( + "ProjectReference", + new XAttribute( + "Include", + Path.GetRelativePath(Path.GetDirectoryName(path)!, Path.Combine(m_root, target)) + ) + ); if (privateReference) + { reference.Add(new XAttribute("PrivateAssets", "compile")); + } document.Root!.Add(new XElement("ItemGroup", reference)); document.Save(path); } @@ -432,7 +521,9 @@ internal string Run(params string[] arguments) public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs index ab236becb..5ef15f34b 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs @@ -10,12 +10,12 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; -using Inno.Build.Toolchains; -using Inno.Testing.Source; -using Inno.Tooling.Documentation; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Xunit; +using Inno.Build.Toolchains; +using Inno.Testing.Source; +using Inno.Tooling.Documentation; namespace Inno.Tooling.Architecture.Tests; @@ -25,8 +25,17 @@ public sealed class DocumentationExampleTests : IDisposable private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoDocumentationExamples", Guid.NewGuid().ToString("N")); private string cache => Path.Combine(m_root, "cache"); private string source => Path.Combine(m_root, "documentation"); - private string host => Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + + private string host + => Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); public DocumentationExampleTests() { @@ -48,12 +57,18 @@ public DocumentationExampleTests() new { name = "Inno.Probe", path = "src/Inno.Probe/Inno.Probe.csproj", surfaces = Array.Empty() } }); Write("documentation/reference/projects.json", Encoding.UTF8.GetString(projects)); - Write("documentation/reference/engine.lock.json", JsonSerializer.Serialize(new - { - repository = "https://github.com/Wolfiora/InnoEngine", revision = new string('a', 40), sourceTree = new string('b', 40), - projectManifest = "reference/projects.json", projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(projects)), - toolingRevision = new string('a', 40) - })); + Write( + "documentation/reference/engine.lock.json", + JsonSerializer.Serialize(new + { + repository = "https://github.com/Wolfiora/InnoEngine", + revision = new string('a', 40), + sourceTree = new string('b', 40), + projectManifest = "reference/projects.json", + projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(projects)), + toolingRevision = new string('a', 40) + }) + ); } [Fact] @@ -61,10 +76,15 @@ public async Task ExplicitReferencesCompileIndependentGroupsAndMissingScriptCont { var start = new ProcessStartInfo(host) { - UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true }; foreach (string argument in new[] { "build", Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), "-v:quiet" }) + { start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -84,7 +104,8 @@ public async Task ExplicitReferencesCompileIndependentGroupsAndMissingScriptCont Assert.Equal("inno-documentation-examples/1", report.RootElement.GetProperty("schema").GetString()); Assert.Matches("^[a-f0-9]{64}$", report.RootElement.GetProperty("validatorIdentity").GetString()!); Assert.Matches("^[a-f0-9]{64}$", report.RootElement.GetProperty("compilerIdentity").GetString()!); - var results = report.RootElement.GetProperty("results").EnumerateArray() + var results = report.RootElement.GetProperty("results") + .EnumerateArray() .ToDictionary(static group => group.GetProperty("page").GetString()!); Assert.Equal("Passed", results["working"].GetProperty("status").GetString()); Assert.Equal("Inno.Probe", Assert.Single(results["working"].GetProperty("projects").EnumerateArray()).GetString()); @@ -95,11 +116,21 @@ public async Task ExplicitReferencesCompileIndependentGroupsAndMissingScriptCont Assert.Equal("Blocked", results["unspecified"].GetProperty("status").GetString()); Assert.Equal("Unverified", report.RootElement.GetProperty("sourceApiStatus").GetString()); string graphPath = Path.Combine(m_root, "resolved-graph.json"); - string graph = await ManagedProjectGraphCapture.CaptureAsync(m_root, host, [Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj")], - new Dictionary { ["Configuration"] = "Debug" }, resolveReferences: true); + string graph = await ManagedProjectGraphCapture.CaptureAsync( + m_root, + host, + [Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj")], + new Dictionary { ["Configuration"] = "Debug" }, + resolveReferences: true + ); await File.WriteAllTextAsync(graphPath, graph); Write("src/Inno.Probe/no-resolve", "References are frozen for this execution boundary."); - Assert.Equal(0, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "working", "--sdk-snapshot", graphPath])); + Assert.Equal( + 0, + await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "working", "--sdk-snapshot", graphPath] + ) + ); } [Fact] @@ -113,11 +144,14 @@ public async Task EmptyDiscoveryCancellationAndUnknownPagesCannotProduceGreenEvi Assert.Equal("Blocked", report.RootElement.GetProperty("status").GetString()); byte[] previous = File.ReadAllBytes(output); await Assert.ThrowsAsync(() => DocumentationExamples.ExecuteAsync( - [..Arguments(index.snapshot, output), "--page", "missing"])); + [..Arguments(index.snapshot, output), "--page", "missing"] + )); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => DocumentationExamples.ExecuteAsync( - Arguments(index.snapshot, output), cancellation.Token)); + Arguments(index.snapshot, output), + cancellation.Token + )); Assert.Equal(previous, File.ReadAllBytes(output)); } @@ -136,25 +170,35 @@ public async Task ExamplePlanningUsesActualOwnersWithoutStartingSdkAndPreservesP { Assert.Equal("inno-example-plan/1", plan.RootElement.GetProperty("schema").GetString()); Assert.True(plan.RootElement.GetProperty("needsScriptProjection").GetBoolean()); - Assert.Equal("src/Inno.Probe/Inno.Probe.csproj", Assert.Single(plan.RootElement.GetProperty("projects").EnumerateArray()).GetString()); + Assert.Equal( + "src/Inno.Probe/Inno.Probe.csproj", + Assert.Single(plan.RootElement.GetProperty("projects").EnumerateArray()).GetString() + ); Assert.Equal(2, plan.RootElement.GetProperty("pages").GetArrayLength()); } Assert.Equal(0, await DocumentationExamples.ExecuteAsync([..arguments, "--operation", "plan", "--page", "host"])); using (JsonDocument plan = JsonDocument.Parse(File.ReadAllBytes(output))) + { Assert.False(plan.RootElement.GetProperty("needsScriptProjection").GetBoolean()); + } byte[] previous = File.ReadAllBytes(output); await Assert.ThrowsAsync(() => DocumentationExamples.ExecuteAsync( - [..arguments, "--operation", "plan", "--page", "empty"])); + [..arguments, "--operation", "plan", "--page", "empty"] + )); await Assert.ThrowsAsync(() => DocumentationExamples.ExecuteAsync( - [..arguments, "--operation", "plan", "--page", "absent"])); + [..arguments, "--operation", "plan", "--page", "absent"] + )); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => DocumentationExamples.ExecuteAsync( - [..arguments, "--operation", "plan"], cancellation.Token)); + [..arguments, "--operation", "plan"], + cancellation.Token + )); Assert.Equal(previous, File.ReadAllBytes(output)); File.Delete(Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj")); await Assert.ThrowsAsync(() => DocumentationExamples.ExecuteAsync( - [..arguments, "--operation", "plan"])); + [..arguments, "--operation", "plan"] + )); Assert.Equal(previous, File.ReadAllBytes(output)); Assert.False(Directory.Exists(Path.Combine(m_root, "src/Inno.Probe/obj"))); } @@ -162,7 +206,9 @@ await Assert.ThrowsAsync(() => DocumentationExamples.Execu public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -170,11 +216,27 @@ public async Task HostExamplesRejectUnreferencedAssembliesAndRespectMarkdownFenc { string directory = Path.Combine(m_root, "src/Inno.Probe/bin/Debug/net10.0"); Directory.CreateDirectory(directory); - File.Copy(EmitReference("Inno.Probe", "namespace Inno.Probe; public static class Probe { public static int Read() => 42; }"), Path.Combine(directory, "Inno.Probe.dll")); + File.Copy( + EmitReference("Inno.Probe", "namespace Inno.Probe; public static class Probe { public static int Read() => 42; }"), + Path.Combine(directory, "Inno.Probe.dll") + ); File.WriteAllText(Path.Combine(directory, "Inno.Probe.xml"), "

"); - File.Copy(EmitReference("Foreign", "public static class Foreign { public static int Read() => 7; }"), Path.Combine(directory, "Foreign.dll")); + File.Copy( + EmitReference("Foreign", "public static class Foreign { public static int Read() => 7; }"), + Path.Combine(directory, "Foreign.dll") + ); var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "restore", Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), "--disable-parallel", "-m:1", "-nr:false", "--disable-build-servers" }) start.ArgumentList.Add(argument); + foreach (string argument in new[] + { + "restore", + Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), + "--disable-parallel", + "-m:1", + "-nr:false", + "--disable-build-servers" + }) { + start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -182,7 +244,11 @@ public async Task HostExamplesRejectUnreferencedAssembliesAndRespectMarkdownFenc await process.WaitForExitAsync(); Assert.True(process.ExitCode == 0, await stdout + await stderr); } - Page("valid", "host", "public static class Example { public static int Read() => Inno.Probe.Probe.Read(); public static int Count(params System.ReadOnlySpan values) => values.Length; }"); + Page( + "valid", + "host", + "public static class Example { public static int Read() => Inno.Probe.Probe.Read(); public static int Count(params System.ReadOnlySpan values) => values.Length; }" + ); Page("foreign", "host", "public static class Example { public static int Read() => Foreign.Read(); }"); Page("tilde", "host", "int value = missing;"); Page("long-fence", "host", "int value = missing;"); @@ -197,9 +263,18 @@ public async Task HostExamplesRejectUnreferencedAssembliesAndRespectMarkdownFenc string output = Path.Combine(m_root, "fences.json"); Assert.Equal(1, await DocumentationExamples.ExecuteAsync(Arguments(index.snapshot, output))); using JsonDocument report = JsonDocument.Parse(File.ReadAllBytes(output)); - var results = report.RootElement.GetProperty("results").EnumerateArray().ToDictionary(static item => item.GetProperty("page").GetString()!); - foreach (string id in new[] { "valid", "text" }) Assert.Equal("Passed", results[id].GetProperty("status").GetString()); - foreach (string id in new[] { "foreign", "tilde", "long-fence" }) Assert.Equal("Failed", results[id].GetProperty("status").GetString()); + var results = report.RootElement + .GetProperty("results") + .EnumerateArray() + .ToDictionary(static item => item.GetProperty("page").GetString()!); + foreach (string id in new[] { "valid", "text" }) + { + Assert.Equal("Passed", results[id].GetProperty("status").GetString()); + } + foreach (string id in new[] { "foreign", "tilde", "long-fence" }) + { + Assert.Equal("Failed", results[id].GetProperty("status").GetString()); + } Assert.Contains("CS0103", results["foreign"].GetProperty("errors")[0].GetString()); } @@ -207,7 +282,17 @@ public async Task HostExamplesRejectUnreferencedAssembliesAndRespectMarkdownFenc public async Task LogicalExamplesRetainBothScriptSurfacesAndNeverBorrowHostImplementation() { var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "restore", Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), "--disable-parallel", "-m:1", "-nr:false", "--disable-build-servers" }) start.ArgumentList.Add(argument); + foreach (string argument in new[] + { + "restore", + Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), + "--disable-parallel", + "-m:1", + "-nr:false", + "--disable-build-servers" + }) { + start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -215,34 +300,76 @@ public async Task LogicalExamplesRetainBothScriptSurfacesAndNeverBorrowHostImple await process.WaitForExitAsync(); Assert.True(process.ExitCode == 0, await stdout + await stderr); } - string runtime = EmitReference("Inno.ScriptApi.Runtime", "namespace InnoEngine.Probe; public static class Value { public static int Read() => 7; }"); - string editor = EmitReference("Inno.ScriptApi.Editor", "namespace InnoEditor.Probe; public static class Action { public static int Read() => 9; }"); + string runtime = EmitReference( + "Inno.ScriptApi.Runtime", + "namespace InnoEngine.Probe; public static class Value { public static int Read() => 7; }" + ); + string editor = EmitReference( + "Inno.ScriptApi.Editor", + "namespace InnoEditor.Probe; public static class Action { public static int Read() => 9; }" + ); string unrelated = EmitReference("Unrelated", "public class Unrelated { }"); Page("runtime", "runtime-script", "public class Example { public int Read() => InnoEngine.Probe.Value.Read(); }"); - Page("editor", "editor-script", "public class Example { public int Read() => InnoEngine.Probe.Value.Read() + InnoEditor.Probe.Action.Read(); }"); + Page( + "editor", + "editor-script", + "public class Example { public int Read() => InnoEngine.Probe.Value.Read() + InnoEditor.Probe.Action.Read(); }" + ); Page("host-leak", "runtime-script", "public class Example { public int Read() => Inno.Probe.Probe.Read(); }"); DocumentationResult index = await DocumentationStore.IndexAsync(m_root, source, cache); string output = Path.Combine(m_root, "scripts.json"); Assert.Equal(1, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "runtime"])); Assert.Contains("Blocked", File.ReadAllText(output)); - int runtimeResult = await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "runtime", "--runtime-reference", runtime]); + int runtimeResult = await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "runtime", "--runtime-reference", runtime] + ); Assert.True(runtimeResult == 0, File.ReadAllText(output)); await AssertReceiptAsync(index.snapshot, output, "runtime"); - Assert.Equal(1, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "editor", "--runtime-reference", runtime])); + Assert.Equal( + 1, + await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "editor", "--runtime-reference", runtime] + ) + ); Assert.Contains("Blocked", File.ReadAllText(output)); - Assert.Equal(0, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "editor", "--runtime-reference", runtime, "--editor-reference", editor])); + Assert.Equal( + 0, + await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "editor", "--runtime-reference", runtime, "--editor-reference", editor] + ) + ); using (JsonDocument evidence = JsonDocument.Parse(File.ReadAllBytes(output))) { JsonElement references = evidence.RootElement.GetProperty("results")[0].GetProperty("references"); - Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(runtime))), references.GetProperty("Inno.ScriptApi.Runtime").GetString()); - Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(editor))), references.GetProperty("Inno.ScriptApi.Editor").GetString()); + Assert.Equal( + Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(runtime))), + references.GetProperty("Inno.ScriptApi.Runtime").GetString() + ); + Assert.Equal( + Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(editor))), + references.GetProperty("Inno.ScriptApi.Editor").GetString() + ); } await AssertReceiptAsync(index.snapshot, output, "editor"); - Assert.Equal(1, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "host-leak", "--runtime-reference", runtime])); + Assert.Equal( + 1, + await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "host-leak", "--runtime-reference", runtime] + ) + ); Assert.Contains("CS0103", File.ReadAllText(output)); - Assert.Equal(1, await DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "runtime", "--runtime-reference", unrelated])); + Assert.Equal( + 1, + await DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "runtime", "--runtime-reference", unrelated] + ) + ); Assert.Contains("Expected the Inno.ScriptApi.Runtime", File.ReadAllText(output)); - await Assert.ThrowsAsync(() => DocumentationExamples.ExecuteAsync([..Arguments(index.snapshot, output), "--page", "editor", "--editor-reference", editor])); + await Assert.ThrowsAsync( + () => DocumentationExamples.ExecuteAsync( + [..Arguments(index.snapshot, output), "--page", "editor", "--editor-reference", editor] + ) + ); } [Fact] @@ -267,8 +394,16 @@ public sealed class Owned { private Owned() { } } } """); var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "restore", Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), "--disable-parallel", "-nr:false", "-v:quiet" }) + foreach (string argument in new[] + { + "restore", + Path.Combine(m_root, "src/Inno.Probe/Inno.Probe.csproj"), + "--disable-parallel", + "-nr:false", + "-v:quiet" + }) { start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -277,10 +412,27 @@ public sealed class Owned { private Owned() { } } Assert.True(process.ExitCode == 0, await stdout + await stderr); } string facts = Path.Combine(m_root, "host.json"); - Assert.Equal(0, DocumentationReferences.ExportApi(["--engine-root", m_root, "--dotnet", host, - "--project", "src/Inno.Probe/Inno.Probe.csproj", "--output", facts])); - string runtime = EmitReference("Inno.ScriptApi.Runtime", "namespace Logical; public static class Renamed { public static int Read(int value) => value; public static int Read(string value) => value.Length; private static int Hidden() => 0; } public sealed class Owned { }"); - string editor = EmitReference("Inno.ScriptApi.Editor", "namespace Logical; public static class Tools { public static int Inspect() => 1; }"); + Assert.Equal( + 0, + DocumentationReferences.ExportApi([ + "--engine-root", + m_root, + "--dotnet", + host, + "--project", + "src/Inno.Probe/Inno.Probe.csproj", + "--output", + facts + ]) + ); + string runtime = EmitReference( + "Inno.ScriptApi.Runtime", + "namespace Logical; public static class Renamed { public static int Read(int value) => value; public static int Read(string value) => value.Length; private static int Hidden() => 0; } public sealed class Owned { }" + ); + string editor = EmitReference( + "Inno.ScriptApi.Editor", + "namespace Logical; public static class Tools { public static int Inspect() => 1; }" + ); const string C_XML = """ ASSEMBLY @@ -288,14 +440,39 @@ public sealed class Owned { private Owned() { } }

Reads the supplied value.The value.The supplied value. Must not become a projected declaration. """; - File.WriteAllText(Path.ChangeExtension(runtime, ".xml"), C_XML.Replace("ASSEMBLY", "Inno.ScriptApi.Runtime", StringComparison.Ordinal) - .Replace("", "", StringComparison.Ordinal)); - File.WriteAllText(Path.ChangeExtension(editor, ".xml"), C_XML.Replace("ASSEMBLY", "Inno.ScriptApi.Editor", StringComparison.Ordinal) - .Replace("Logical.Renamed", "Logical.Tools", StringComparison.Ordinal).Replace("T:Inno.Probe.Probe", "T:Inno.Probe.EditorProbe", StringComparison.Ordinal)); + File.WriteAllText( + Path.ChangeExtension(runtime, ".xml"), + C_XML.Replace("ASSEMBLY", "Inno.ScriptApi.Runtime", StringComparison.Ordinal) + .Replace( + "", + "", + StringComparison.Ordinal + ) + ); + File.WriteAllText( + Path.ChangeExtension(editor, ".xml"), + C_XML.Replace("ASSEMBLY", "Inno.ScriptApi.Editor", StringComparison.Ordinal) + .Replace("Logical.Renamed", "Logical.Tools", StringComparison.Ordinal) + .Replace("T:Inno.Probe.Probe", "T:Inno.Probe.EditorProbe", StringComparison.Ordinal) + ); string output = Path.Combine(m_root, "projected.json"); - string[] arguments = ["--engine-root", m_root, "--dotnet", host, "--source-reference", facts, - "--runtime-reference", runtime, "--editor-reference", editor, "--output", output, - "--framework-project", "src/Inno.Probe/Inno.Probe.csproj"]; + string[] arguments = + [ + "--engine-root", + m_root, + "--dotnet", + host, + "--source-reference", + facts, + "--runtime-reference", + runtime, + "--editor-reference", + editor, + "--output", + output, + "--framework-project", + "src/Inno.Probe/Inno.Probe.csproj" + ]; Assert.Equal(0, DocumentationReferences.ExportApi([..arguments, "--surface", "runtime-script"])); byte[] runtimeFacts = File.ReadAllBytes(output); using (JsonDocument captured = JsonDocument.Parse(File.ReadAllBytes(output))) @@ -304,10 +481,16 @@ public sealed class Owned { private Owned() { } } Assert.Single(captured.RootElement.GetProperty("projectionIdentities").EnumerateObject()); JsonElement project = captured.RootElement.GetProperty("projects")[0]; Assert.Equal("Inno.Probe", project.GetProperty("name").GetString()); - var symbols = project.GetProperty("symbols").EnumerateArray().ToDictionary(static symbol => symbol.GetProperty("id").GetString()!); + var symbols = project + .GetProperty("symbols") + .EnumerateArray() + .ToDictionary(static symbol => symbol.GetProperty("id").GetString()!); Assert.Contains("M:Logical.Renamed.Read(System.Int32)", symbols.Keys); Assert.Contains("M:Logical.Renamed.Read(System.String)", symbols.Keys); - Assert.DoesNotContain(symbols.Keys, static id => id.Contains("Hidden", StringComparison.Ordinal) || id.Contains("HostOnly", StringComparison.Ordinal)); + Assert.DoesNotContain( + symbols.Keys, + static id => id.Contains("Hidden", StringComparison.Ordinal) || id.Contains("HostOnly", StringComparison.Ordinal) + ); Assert.Contains("supplied value", symbols["M:Logical.Renamed.Read(System.Int32)"].GetProperty("documentation").GetString()); Assert.Equal("Runtime", symbols["M:Logical.Renamed.Read(System.Int32)"].GetProperty("scriptingScope").GetString()); Assert.Equal("Authoring", symbols["T:Logical.Owned"].GetProperty("scriptingScope").GetString()); @@ -318,14 +501,23 @@ public sealed class Owned { private Owned() { } } using (JsonDocument captured = JsonDocument.Parse(File.ReadAllBytes(output))) { Assert.Equal(2, captured.RootElement.GetProperty("projectionIdentities").EnumerateObject().Count()); - Assert.Contains(captured.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray(), - static symbol => symbol.GetProperty("id").GetString() == "M:Logical.Tools.Inspect"); + Assert.Contains( + captured.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray(), + static symbol => symbol.GetProperty("id").GetString() == "M:Logical.Tools.Inspect" + ); } - Page("projected-contract", "runtime-script", "public static class Example { public static int Read() => Logical.Renamed.Read(7); }"); + Page( + "projected-contract", + "runtime-script", + "public static class Example { public static int Read() => Logical.Renamed.Read(7); }" + ); Bind(runtimeFacts); DocumentationResult prepared = await DocumentationStore.IndexAsync(m_root, source, cache); string comparison = Path.Combine(m_root, "comparison.json"); - Assert.Equal(0, await DocumentationExamples.ExecuteAsync([..Arguments(prepared.snapshot, comparison), "--runtime-reference", runtime])); + Assert.Equal( + 0, + await DocumentationExamples.ExecuteAsync([..Arguments(prepared.snapshot, comparison), "--runtime-reference", runtime]) + ); using (JsonDocument report = JsonDocument.Parse(File.ReadAllBytes(comparison))) { Assert.Equal("Passed", report.RootElement.GetProperty("scriptReferences")[0].GetProperty("status").GetString()); @@ -335,7 +527,10 @@ public sealed class Owned { private Owned() { } } changedFacts["projects"]![0]!["symbols"]![0]!["signature"] = "public int ChangedContract"; Bind(JsonSerializer.SerializeToUtf8Bytes(changedFacts)); DocumentationResult changed = await DocumentationStore.IndexAsync(m_root, source, cache); - Assert.Equal(1, await DocumentationExamples.ExecuteAsync([..Arguments(changed.snapshot, comparison), "--runtime-reference", runtime])); + Assert.Equal( + 1, + await DocumentationExamples.ExecuteAsync([..Arguments(changed.snapshot, comparison), "--runtime-reference", runtime]) + ); using (JsonDocument report = JsonDocument.Parse(File.ReadAllBytes(comparison))) { Assert.Equal("Passed", report.RootElement.GetProperty("results")[0].GetProperty("status").GetString()); @@ -349,14 +544,20 @@ public sealed class Owned { private Owned() { } } string conflictPath = Path.Combine(m_root, "conflicting-source.json"); File.WriteAllBytes(conflictPath, JsonSerializer.SerializeToUtf8Bytes(conflicting)); Assert.Throws(() => DocumentationReferences.ExportApi( - [..arguments, "--source-reference", conflictPath, "--surface", "runtime-script"])); + [..arguments, "--source-reference", conflictPath, "--surface", "runtime-script"] + )); Assert.Equal(previous, File.ReadAllBytes(output)); - File.WriteAllText(Path.ChangeExtension(runtime, ".xml"), C_XML.Replace("T:Inno.Probe.Probe", "T:Missing.Owner", StringComparison.Ordinal)); + File.WriteAllText( + Path.ChangeExtension(runtime, ".xml"), + C_XML.Replace("T:Inno.Probe.Probe", "T:Missing.Owner", StringComparison.Ordinal) + ); Assert.Throws(() => DocumentationReferences.ExportApi([..arguments, "--surface", "runtime-script"])); Assert.Equal(previous, File.ReadAllBytes(output)); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - Assert.ThrowsAny(() => DocumentationReferences.ExportApi([..arguments, "--surface", "runtime-script"], cancellation.Token)); + Assert.ThrowsAny( + () => DocumentationReferences.ExportApi([..arguments, "--surface", "runtime-script"], cancellation.Token) + ); Assert.Equal(previous, File.ReadAllBytes(output)); void Bind(byte[] projectedFacts) @@ -369,21 +570,47 @@ void Bind(byte[] projectedFacts) Write("documentation/reference/projects.json", Encoding.UTF8.GetString(inventory)); Write("documentation/reference/host.json", Encoding.UTF8.GetString(hostFacts)); Write("documentation/reference/runtime.json", Encoding.UTF8.GetString(projectedFacts)); - Write("documentation/reference/engine.lock.json", JsonSerializer.Serialize(new - { - repository = "https://github.com/Wolfiora/InnoEngine", revision = new string('a', 40), sourceTree = new string('b', 40), - projectManifest = "reference/projects.json", projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(inventory)), - toolingRevision = new string('a', 40), apiManifests = new[] + Write( + "documentation/reference/engine.lock.json", + JsonSerializer.Serialize(new { - new { path = "reference/host.json", sha256 = Convert.ToHexStringLower(SHA256.HashData(hostFacts)), model = "source-clr", configuration = "Debug", sourceRevision = new string('a', 40), sourceTree = new string('b', 40) }, - new { path = "reference/runtime.json", sha256 = Convert.ToHexStringLower(SHA256.HashData(projectedFacts)), model = "runtime-script", configuration = "Debug", sourceRevision = new string('a', 40), sourceTree = new string('b', 40) } - } - })); + repository = "https://github.com/Wolfiora/InnoEngine", + revision = new string('a', 40), + sourceTree = new string('b', 40), + projectManifest = "reference/projects.json", + projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(inventory)), + toolingRevision = new string('a', 40), + apiManifests = new[] + { + new + { + path = "reference/host.json", + sha256 = Convert.ToHexStringLower(SHA256.HashData(hostFacts)), + model = "source-clr", + configuration = "Debug", + sourceRevision = new string('a', 40), + sourceTree = new string('b', 40) + }, + new + { + path = "reference/runtime.json", + sha256 = Convert.ToHexStringLower(SHA256.HashData(projectedFacts)), + model = "runtime-script", + configuration = "Debug", + sourceRevision = new string('a', 40), + sourceTree = new string('b', 40) + } + } + }) + ); } } - private async Task AssertReceiptAsync(string snapshotId, string reportPath, string pageId) - { + private async Task AssertReceiptAsync( + string snapshotId, + string reportPath, + string pageId + ) { using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, snapshotId); DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(); Write("receipt/documentation-catalog.json", JsonSerializer.Serialize(catalog)); @@ -406,10 +633,23 @@ private async Task AssertReceiptAsync(string snapshotId, string reportPath, stri } "Reconciled $Page against the actual example compiler report." """); - var start = new ProcessStartInfo("pwsh") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "-NoProfile", "-File", Path.Combine(m_root, "receipt/check.ps1"), - TestRepository.GetRoot(typeof(DocumentationExampleTests).Assembly), pageId }) + var start = new ProcessStartInfo("pwsh") + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (string argument in new[] + { + "-NoProfile", + "-File", + Path.Combine(m_root, "receipt/check.ps1"), + TestRepository.GetRoot(typeof(DocumentationExampleTests).Assembly), + pageId + }) { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task stdout = process.StandardOutput.ReadToEndAsync(); Task stderr = process.StandardError.ReadToEndAsync(); @@ -417,14 +657,19 @@ private async Task AssertReceiptAsync(string snapshotId, string reportPath, stri Assert.True(process.ExitCode == 0, await stdout + await stderr); } - private string EmitReference(string name, string sourceText) - { + private string EmitReference( + string name, + string sourceText + ) { string output = Path.Combine(m_root, name + ".dll"); string[] references = File.ReadAllLines(Path.Combine(AppContext.BaseDirectory, "DocumentationFrameworkReferences.txt")); Assert.NotEmpty(references); - var compilation = CSharpCompilation.Create(name, [CSharpSyntaxTree.ParseText(sourceText)], + var compilation = CSharpCompilation.Create( + name, + [CSharpSyntaxTree.ParseText(sourceText)], references.Select(static path => MetadataReference.CreateFromFile(path)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); Assert.True(compilation.Emit(output).Success); return output; } @@ -438,9 +683,12 @@ private void Page( string id, string? mode, string? code - ) => Write("documentation/content/en/" + id + ".md", "---\nuid: " + id + "\nkind: tutorial\n" + ) => Write( + "documentation/content/en/" + id + ".md", + "---\nuid: " + id + "\nkind: tutorial\n" + (mode is null ? "" : "exampleMode: " + mode + "\nexampleProjects: [Inno.Probe]\n") - + "---\n# " + id + "\n\nExample contract.\n" + (code is null ? "" : "\n```csharp\n" + code + "\n```\n")); + + "---\n# " + id + "\n\nExample contract.\n" + (code is null ? "" : "\n```csharp\n" + code + "\n```\n") + ); private void Write( string path, diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs index de52aed41..bc6b72d70 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.IO; using System.Diagnostics; +using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; @@ -10,9 +10,9 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Tooling.Documentation; -using Xunit; namespace Inno.Tooling.Architecture.Tests; @@ -24,7 +24,9 @@ public sealed class DocumentationReferenceTests : IDisposable public void Dispose() { if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -35,61 +37,125 @@ public async Task ExportPlanningUsesActualTargetsAndExcludesNonProductOwnersWith net10.014.0 fixture-host """); - foreach (string owner in new[] { "src/Local", "build/Foreign", "build/Empty", "entry/Hidden", "platforms/Hidden", "backends/Hidden", "tests/Hidden", "tools/Hidden", "src/Fixture" }) - { - string product = owner.StartsWith("build/", StringComparison.Ordinal) ? "fixture-foreign" : ""; + foreach (string owner in new[] { + "src/Local", + "build/Foreign", + "build/Empty", + "entry/Hidden", + "platforms/Hidden", + "backends/Hidden", + "tests/Hidden", + "tools/Hidden", + "src/Fixture" + }) { + string product = owner.StartsWith("build/", StringComparison.Ordinal) + ? "fixture-foreign" + : ""; string test = owner == "src/Fixture" ? "true" : ""; - Write(owner + "/" + Path.GetFileName(owner) + ".csproj", "" + product + test - + ""); + Write( + owner + "/" + Path.GetFileName(owner) + ".csproj", + "" + product + test + + "" + ); Write(owner + "/Probe.cs", owner == "build/Empty" ? "internal sealed class Probe { }" : "public sealed class Probe { }"); } - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); string output = Path.Combine(m_root, "plan.json"); Assert.Equal(0, await DocumentationReferences.PlanExportAsync(["--engine-root", m_root, "--dotnet", host, "--output", output])); using JsonDocument plan = JsonDocument.Parse(File.ReadAllBytes(output)); Assert.Equal(3, plan.RootElement.GetProperty("projects").GetArrayLength()); Assert.Equal("src/Local/Local.csproj", plan.RootElement.GetProperty("buildProjects").EnumerateArray().Single().GetString()); - Assert.Equal("build/Foreign/Foreign.csproj", plan.RootElement.GetProperty("foreignOwners").EnumerateArray().Single().GetProperty("path").GetString()); + Assert.Equal( + "build/Foreign/Foreign.csproj", + plan.RootElement.GetProperty("foreignOwners").EnumerateArray().Single().GetProperty("path").GetString() + ); Assert.Equal(2, plan.RootElement.GetProperty("captures").GetArrayLength()); string localIdentity = plan.RootElement.GetProperty("inputIdentities").GetProperty("src/Local/Local.csproj").GetString()!; string foreignIdentity = plan.RootElement.GetProperty("inputIdentities").GetProperty("build/Foreign/Foreign.csproj").GetString()!; Assert.Equal(0, await DocumentationReferences.PlanExportAsync(["--engine-root", m_root, "--dotnet", host, "--output", output])); using (JsonDocument repeated = JsonDocument.Parse(File.ReadAllBytes(output))) - Assert.Equal(localIdentity, repeated.RootElement.GetProperty("inputIdentities").GetProperty("src/Local/Local.csproj").GetString()); + { + Assert.Equal( + localIdentity, + repeated.RootElement.GetProperty("inputIdentities").GetProperty("src/Local/Local.csproj").GetString() + ); + } // Register a completed immutable owner payload, then plan again without running // any Build/Restore/ResolveReferences target in this fixture. - string facts = JsonSerializer.Serialize(new { projects = new[] { new { project = "src/Local/Local.csproj", name = "Local", symbols = Array.Empty() } } }); + string facts = JsonSerializer.Serialize( + new { projects = new[] { new { project = "src/Local/Local.csproj", name = "Local", symbols = Array.Empty() } } } + ); Write("completed/source.json", facts); Write("completed/plan.json", File.ReadAllText(output)); - Write("completed/producer.json", JsonSerializer.Serialize(new - { - configuration = "Debug", revision = new string('a', 40), - captures = new[] { new { path = "source.json", model = "source-clr", target = "fixture-host", - sha256 = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(facts))) } } - })); - Assert.Equal(0, await DocumentationReferences.PlanExportAsync(["--engine-root", m_root, - "--record-completed", Path.Combine(m_root, "completed")])); + Write( + "completed/producer.json", + JsonSerializer.Serialize(new + { + configuration = "Debug", + revision = new string('a', 40), + captures = new[] + { + new + { + path = "source.json", + model = "source-clr", + target = "fixture-host", + sha256 = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(facts))) + } + } + }) + ); + Assert.Equal( + 0, + await DocumentationReferences.PlanExportAsync([ + "--engine-root", + m_root, + "--record-completed", + Path.Combine(m_root, "completed") + ]) + ); Assert.Equal(0, await DocumentationReferences.PlanExportAsync(["--engine-root", m_root, "--dotnet", host, "--output", output])); using (JsonDocument reused = JsonDocument.Parse(File.ReadAllBytes(output))) { Assert.Empty(reused.RootElement.GetProperty("buildProjects").EnumerateArray()); - Assert.Equal(new string('a', 40), reused.RootElement.GetProperty("reusedOwners").GetProperty("fixture-host") - .GetProperty("src/Local/Local.csproj").GetProperty("producerRevision").GetString()); + Assert.Equal( + new string('a', 40), + reused.RootElement.GetProperty("reusedOwners") + .GetProperty("fixture-host") + .GetProperty("src/Local/Local.csproj") + .GetProperty("producerRevision") + .GetString() + ); } Write("src/Local/Added.cs", "public sealed class Added { }"); Assert.Equal(0, await DocumentationReferences.PlanExportAsync(["--engine-root", m_root, "--dotnet", host, "--output", output])); using (JsonDocument changed = JsonDocument.Parse(File.ReadAllBytes(output))) { - Assert.NotEqual(localIdentity, changed.RootElement.GetProperty("inputIdentities").GetProperty("src/Local/Local.csproj").GetString()); - Assert.Equal(foreignIdentity, changed.RootElement.GetProperty("inputIdentities").GetProperty("build/Foreign/Foreign.csproj").GetString()); + Assert.NotEqual( + localIdentity, + changed.RootElement.GetProperty("inputIdentities").GetProperty("src/Local/Local.csproj").GetString() + ); + Assert.Equal( + foreignIdentity, + changed.RootElement.GetProperty("inputIdentities").GetProperty("build/Foreign/Foreign.csproj").GetString() + ); Assert.Equal("src/Local/Local.csproj", changed.RootElement.GetProperty("buildProjects").EnumerateArray().Single().GetString()); } byte[] original = File.ReadAllBytes(output); using var canceled = new CancellationTokenSource(); canceled.Cancel(); await Assert.ThrowsAnyAsync(() => DocumentationReferences.PlanExportAsync( - ["--engine-root", m_root, "--dotnet", host, "--output", output], canceled.Token)); + ["--engine-root", m_root, "--dotnet", host, "--output", output], + canceled.Token + )); Assert.Equal(original, File.ReadAllBytes(output)); } @@ -110,14 +176,37 @@ public async Task ResolvedUnionSupportsIndependentSelectedSourceOwners() """); - Write("src/" + name + "/Probe.cs", "namespace " + name + ";\n/// Supplies this source owner's public contract.\npublic sealed class Probe { }\n"); + Write( + "src/" + name + "/Probe.cs", + "namespace " + name + ";\n/// Supplies this source owner's public contract.\npublic sealed class Probe { }\n" + ); } - Write("projects.slnx", ""); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + Write( + "projects.slnx", + "" + ); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "restore", Path.Combine(m_root, "projects.slnx"), "--nologo", "-v:quiet", "-m:1", "-nr:false", "--disable-parallel" }) + foreach (string argument in new[] + { + "restore", + Path.Combine(m_root, "projects.slnx"), + "--nologo", + "-v:quiet", + "-m:1", + "-nr:false", + "--disable-parallel" + }) { start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -127,20 +216,56 @@ public async Task ResolvedUnionSupportsIndependentSelectedSourceOwners() } string[] projects = ["src/First/First.csproj", "src/Second/Second.csproj"]; string facts = Path.Combine(m_root, "facts.json"); - Assert.Equal(0, DocumentationReferences.ExportApi(["--engine-root", m_root, "--dotnet", host, "--output", facts, - ..projects.SelectMany(static project => new[] { "--project", project })])); - string graph = await ManagedProjectGraphCapture.CaptureAsync(m_root, host, projects.Select(project => Path.Combine(m_root, project)).ToArray(), - new Dictionary { ["Configuration"] = "Debug" }, resolveReferences: true); + Assert.Equal( + 0, + DocumentationReferences.ExportApi([ + "--engine-root", + m_root, + "--dotnet", + host, + "--output", + facts, + ..projects.SelectMany(static project => new[] { "--project", project }) + ]) + ); + string graph = await ManagedProjectGraphCapture.CaptureAsync( + m_root, + host, + projects.Select(project => Path.Combine(m_root, project)).ToArray(), + new Dictionary { ["Configuration"] = "Debug" }, + resolveReferences: true + ); string graphPath = Path.Combine(m_root, "resolved.json"); await File.WriteAllTextAsync(graphPath, graph); - foreach (string name in new[] { "First", "Second" }) Write("src/" + name + "/no-resolve", "frozen"); + foreach (string name in new[] { "First", "Second" }) + { + Write("src/" + name + "/no-resolve", "frozen"); + } foreach (string project in projects) { string output = Path.Combine(m_root, Path.GetFileNameWithoutExtension(project) + "-comparison.json"); - Assert.Equal(0, await DocumentationReferences.ValidateApiAsync(["--engine-root", m_root, "--dotnet", host, - "--reference", facts, "--project", project, "--sdk-snapshot", graphPath, "--output", output])); + Assert.Equal( + 0, + await DocumentationReferences.ValidateApiAsync([ + "--engine-root", + m_root, + "--dotnet", + host, + "--reference", + facts, + "--project", + project, + "--sdk-snapshot", + graphPath, + "--output", + output + ]) + ); using JsonDocument report = JsonDocument.Parse(File.ReadAllBytes(output)); - Assert.Equal(project, Assert.Single(report.RootElement.GetProperty("projects").EnumerateArray()).GetProperty("project").GetString()); + Assert.Equal( + project, + Assert.Single(report.RootElement.GetProperty("projects").EnumerateArray()).GetProperty("project").GetString() + ); } } @@ -175,14 +300,26 @@ public class Probe protected virtual void OnRead() { } } """); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); var start = new ProcessStartInfo(host) { - UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true }; foreach (string argument in new[] { "restore", Path.Combine(m_root, C_PROJECT), "--nologo", "-v:quiet" }) + { start.ArgumentList.Add(argument); + } using (Process process = Process.Start(start)!) { Task stdout = process.StandardOutput.ReadToEndAsync(); @@ -198,16 +335,22 @@ protected virtual void OnRead() { } Assert.Equal("source-clr", inventory.RootElement.GetProperty("model").GetString()); Assert.Equal("Unverified", inventory.RootElement.GetProperty("sourceApiStatus").GetString()); JsonElement[] symbols = inventory.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray().ToArray(); - Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.Read(System.String)" + Assert.Contains(symbols, symbol => ( + symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.Read(System.String)" && symbol.GetProperty("signature").GetString()!.Contains("string? text = null", StringComparison.Ordinal) - && symbol.GetProperty("documentation").GetString()!.Contains("Borrowed text", StringComparison.Ordinal)); + && symbol.GetProperty("documentation").GetString()!.Contains("Borrowed text", StringComparison.Ordinal) + )); Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.Read(System.Int32)"); Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.OnRead"); - Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "T:Inno.Probe.Probe" + Assert.Contains(symbols, symbol => ( + symbol.GetProperty("id").GetString() == "T:Inno.Probe.Probe" && symbol.GetProperty("baseType").GetString() == "object" - && symbol.GetProperty("kind").GetString() == "NamedType"); - Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.OnRead" - && symbol.GetProperty("containingType").GetString() == "T:Inno.Probe.Probe"); + && symbol.GetProperty("kind").GetString() == "NamedType" + )); + Assert.Contains(symbols, symbol => ( + symbol.GetProperty("id").GetString() == "M:Inno.Probe.Probe.OnRead" + && symbol.GetProperty("containingType").GetString() == "T:Inno.Probe.Probe" + )); string comparison = Path.Combine(m_root, "comparison.json"); string[] comparisonArguments = ["--engine-root", m_root, "--dotnet", host, "--reference", output, "--output", comparison]; Assert.Equal(0, await DocumentationReferences.ValidateApiAsync(comparisonArguments)); @@ -217,8 +360,13 @@ protected virtual void OnRead() { } Assert.Equal("Unverified", matched.RootElement.GetProperty("sourceApiStatus").GetString()); } string graphPath = Path.Combine(m_root, "resolved-graph.json"); - string graph = await ManagedProjectGraphCapture.CaptureAsync(m_root, host, [Path.Combine(m_root, C_PROJECT)], - new Dictionary { ["Configuration"] = "Debug" }, resolveReferences: true); + string graph = await ManagedProjectGraphCapture.CaptureAsync( + m_root, + host, + [Path.Combine(m_root, C_PROJECT)], + new Dictionary { ["Configuration"] = "Debug" }, + resolveReferences: true + ); await File.WriteAllTextAsync(graphPath, graph); Write("src/Inno.Probe/no-resolve", "Reference resolution has already completed for this execution boundary."); Assert.Equal(0, await DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath])); @@ -228,31 +376,55 @@ protected virtual void OnRead() { } JsonNode wrongContext = JsonNode.Parse(graph)!; wrongContext[0]!["GlobalProperties"]!["Configuration"] = "Release"; await File.WriteAllTextAsync(graphPath, wrongContext.ToJsonString()); - await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath])); + await Assert.ThrowsAsync( + () => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath]) + ); Assert.Throws(() => DocumentationReferences.ExportApi([..arguments, "--sdk-snapshot", graphPath])); Assert.Equal(originalCapture, File.ReadAllBytes(output)); JsonNode missingOwner = JsonNode.Parse(graph)!; missingOwner[0]!["Path"] = Path.Combine(m_root, "src/Inno.Other/Inno.Other.csproj"); await File.WriteAllTextAsync(graphPath, missingOwner.ToJsonString()); - await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath])); + await Assert.ThrowsAsync( + () => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath]) + ); await File.WriteAllTextAsync(graphPath, "[]"); - await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath])); + await Assert.ThrowsAsync( + () => DocumentationReferences.ValidateApiAsync([..comparisonArguments, "--sdk-snapshot", graphPath]) + ); File.Delete(Path.Combine(m_root, "src/Inno.Probe/no-resolve")); const string C_UNRELATED = "src/Inno.Unrelated/Inno.Unrelated.csproj"; Write(C_UNRELATED, ""); JsonNode combined = JsonNode.Parse(File.ReadAllBytes(output))!; - combined["projects"]!.AsArray().Add(JsonSerializer.SerializeToNode(new - { - project = C_UNRELATED, name = "Inno.Unrelated", symbols = Array.Empty() - })); + combined["projects"]!.AsArray().Add( + JsonSerializer.SerializeToNode(new + { + project = C_UNRELATED, + name = "Inno.Unrelated", + symbols = Array.Empty() + }) + ); byte[] frozen = JsonSerializer.SerializeToUtf8Bytes(combined); string cache = Path.Combine(m_root, "artifacts", "documentation"); string documentation = PrepareDocumentation(frozen, C_PROJECT, C_UNRELATED); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, documentation, cache); Directory.Move(documentation, documentation + "-unavailable"); - string[] preparedArguments = ["--engine-root", m_root, "--dotnet", host, "--cache-root", cache, - "--snapshot", indexed.snapshot!, "--reference", "reference/api/probe.json", "--project", C_PROJECT, - "--output", comparison]; + string[] preparedArguments = + [ + "--engine-root", + m_root, + "--dotnet", + host, + "--cache-root", + cache, + "--snapshot", + indexed.snapshot!, + "--reference", + "reference/api/probe.json", + "--project", + C_PROJECT, + "--output", + comparison + ]; Assert.Equal(0, await DocumentationReferences.ValidateApiAsync(preparedArguments)); using (JsonDocument matched = JsonDocument.Parse(File.ReadAllBytes(comparison))) { @@ -266,7 +438,9 @@ protected virtual void OnRead() { } string[] unknownOwner = preparedArguments.Select(argument => argument == C_PROJECT ? "src/Missing.csproj" : argument).ToArray(); await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync(unknownOwner)); Assert.Equal(protectedResult, File.ReadAllBytes(comparison)); - string[] overwriteCache = preparedArguments.Select(argument => argument == comparison ? Path.Combine(cache, "current.json") : argument).ToArray(); + string[] overwriteCache = preparedArguments + .Select(argument => argument == comparison ? Path.Combine(cache, "current.json") : argument) + .ToArray(); await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync(overwriteCache)); string source = File.ReadAllText(Path.Combine(m_root, "src/Inno.Probe/Probe.cs")); Write("src/Inno.Probe/Probe.cs", source.Replace("Borrowed text.", "Caller must release the text lease.", StringComparison.Ordinal)); @@ -283,7 +457,9 @@ protected virtual void OnRead() { } Assert.Contains("Missing current declaration", File.ReadAllText(comparison)); File.WriteAllBytes(output, fullReference); byte[] firstFailure = File.ReadAllBytes(comparison); - await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync(comparisonArguments, new CancellationToken(true))); + await Assert.ThrowsAsync( + () => DocumentationReferences.ValidateApiAsync(comparisonArguments, new CancellationToken(true)) + ); Assert.Equal(firstFailure, File.ReadAllBytes(comparison)); byte[] previous = File.ReadAllBytes(output); Write("src/Inno.Probe/Probe.cs", "namespace Inno.Probe; public class Probe { public MissingContract Read() => null; }"); @@ -295,15 +471,24 @@ protected virtual void OnRead() { } [InlineData("[]")] [InlineData("[{\"project\":\"../escape.csproj\",\"name\":\"Escape\",\"symbols\":[]}]")] [InlineData("[{\"project\":\"src/./Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]}]")] - [InlineData("[{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]},{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]}]")] + [InlineData( + "[{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]},{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]}]" + )] [InlineData("[{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[{\"id\":\"T:Probe\"},{\"id\":\"T:Probe\"}]}]")] public async Task InvalidReferenceDiscoveryCannotReplaceEvidence(string projects) { Write("reference.json", "{\"model\":\"source-clr\",\"configuration\":\"Debug\",\"projects\":" + projects + "}"); Write("report.json", "first failure"); Exception? failure = await Record.ExceptionAsync(() => DocumentationReferences.ValidateApiAsync([ - "--engine-root", m_root, "--dotnet", "not-invoked", "--reference", Path.Combine(m_root, "reference.json"), - "--output", Path.Combine(m_root, "report.json")])); + "--engine-root", + m_root, + "--dotnet", + "not-invoked", + "--reference", + Path.Combine(m_root, "reference.json"), + "--output", + Path.Combine(m_root, "report.json") + ])); Assert.NotNull(failure); Assert.True(failure is InvalidDataException or IOException, failure.ToString()); Assert.Equal("first failure", File.ReadAllText(Path.Combine(m_root, "report.json"))); @@ -318,12 +503,24 @@ public async Task DifferentEvaluatedContextsCannotShareOneBatch( ) { const string C_PROJECTS = "[{\"project\":\"src/Probe.csproj\",\"name\":\"Probe\",\"symbols\":[]}]"; Write("first.json", "{\"model\":\"source-clr\",\"configuration\":\"Debug\",\"projects\":" + C_PROJECTS + "}"); - Write("second.json", "{\"model\":\"source-clr\",\"configuration\":" + JsonSerializer.Serialize(configuration) - + ",\"target\":" + JsonSerializer.Serialize(target) + ",\"projects\":" + C_PROJECTS + "}"); + Write( + "second.json", + "{\"model\":\"source-clr\",\"configuration\":" + JsonSerializer.Serialize(configuration) + + ",\"target\":" + JsonSerializer.Serialize(target) + ",\"projects\":" + C_PROJECTS + "}" + ); Write("report.json", "original result"); InvalidDataException failure = await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([ - "--engine-root", m_root, "--dotnet", "not-invoked", "--reference", Path.Combine(m_root, "first.json"), - "--reference", Path.Combine(m_root, "second.json"), "--output", Path.Combine(m_root, "report.json")])); + "--engine-root", + m_root, + "--dotnet", + "not-invoked", + "--reference", + Path.Combine(m_root, "first.json"), + "--reference", + Path.Combine(m_root, "second.json"), + "--output", + Path.Combine(m_root, "report.json") + ])); Assert.Contains("separate evaluated batches", failure.Message); Assert.Equal("original result", File.ReadAllText(Path.Combine(m_root, "report.json"))); } @@ -334,8 +531,17 @@ public async Task DifferentEvaluatedContextsCannotShareOneBatch( public async Task IncompleteSnapshotSelectionDoesNotOpenLocalFiles(string option) { await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([ - "--engine-root", m_root, "--dotnet", "not-invoked", "--reference", "absent.json", "--output", "report.json", - option, "missing"])); + "--engine-root", + m_root, + "--dotnet", + "not-invoked", + "--reference", + "absent.json", + "--output", + "report.json", + option, + "missing" + ])); } [Fact] @@ -345,7 +551,9 @@ public async Task RetiringSnapshotsPreservesReferencePayloadsForActiveReaders() const string C_UNRELATED = "src/Inno.Unrelated/Inno.Unrelated.csproj"; byte[] facts = JsonSerializer.SerializeToUtf8Bytes(new { - model = "source-clr", configuration = "Debug", projects = new[] + model = "source-clr", + configuration = "Debug", + projects = new[] { new { project = C_SELECTED, name = "Inno.Probe", symbols = Array.Empty() } } @@ -361,15 +569,23 @@ public async Task RetiringSnapshotsPreservesReferencePayloadsForActiveReaders() PrepareDocumentation(JsonSerializer.SerializeToUtf8Bytes(changed), C_SELECTED, C_UNRELATED); DocumentationResult second = await DocumentationStore.IndexAsync(m_root, documentation, cache); Assert.NotEqual(first.snapshot, second.snapshot); - BuildCacheCleanupPlan retirement = BuildCacheCleanupPlan.Create(m_root, - BuildCacheOwnerCatalog.ReadOwners(m_root), new(0, 0), retireAll: true); + BuildCacheCleanupPlan retirement = BuildCacheCleanupPlan.Create( + m_root, + BuildCacheOwnerCatalog.ReadOwners(m_root), + new(0, 0), + retireAll: true + ); BuildCacheCleanupResult result = await retirement.ExecuteAsync(); Assert.Empty(result.failures); Assert.DoesNotContain(payload, result.retired); Assert.Equal(facts, await reader.ReadReferenceAsync("reference/api/probe.json")); } - BuildCacheCleanupResult released = await BuildCacheCleanupPlan.Create(m_root, - BuildCacheOwnerCatalog.ReadOwners(m_root), new(0, 0), retireAll: true).ExecuteAsync(); + BuildCacheCleanupResult released = await BuildCacheCleanupPlan.Create( + m_root, + BuildCacheOwnerCatalog.ReadOwners(m_root), + new(0, 0), + retireAll: true + ).ExecuteAsync(); Assert.Empty(released.failures); Assert.Contains(payload, released.retired); using DocumentationSnapshot current = await DocumentationStore.OpenAsync(cache); @@ -380,7 +596,10 @@ public async Task RetiringSnapshotsPreservesReferencePayloadsForActiveReaders() public void ExportUsesTheActualSourceInventoryWithoutInferringApiSurfaces() { Write("src/Inno.Probe/Inno.Probe.csproj", ""); - Write("tests/Inno.Probe.Tests/Inno.Probe.Tests.csproj", "true"); + Write( + "tests/Inno.Probe.Tests/Inno.Probe.Tests.csproj", + "true" + ); Write("src/Inno.Probe/obj/Ignored.csproj", ""); Write("extern/ThirdParty/ThirdParty.csproj", ""); string output = Path.Combine(m_root, "output", "projects.json"); @@ -430,17 +649,34 @@ string unrelated string tree = new('b', 40); Write("documentation/reference/projects/catalog.json", Encoding.UTF8.GetString(projects)); Write("documentation/reference/api/probe.json", Encoding.UTF8.GetString(facts)); - Write("documentation/reference/engine.lock.json", JsonSerializer.Serialize(new - { - repository = "https://github.com/Wolfiora/InnoEngine", revision, sourceTree = tree, toolingRevision = revision, - projectManifest = "reference/projects/catalog.json", projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(projects)), - apiManifests = new[] { new + Write( + "documentation/reference/engine.lock.json", + JsonSerializer.Serialize(new { - path = "reference/api/probe.json", sha256 = Convert.ToHexStringLower(SHA256.HashData(facts)), model = "source-clr", - configuration = "Debug", sourceRevision = revision, sourceTree = tree - } } - })); - Write("documentation/content/en/probe.md", "---\nuid: probe\nkind: project\nowners: [Inno.Probe]\n---\n# Probe\n\nUse the declared source contract.\n"); + repository = "https://github.com/Wolfiora/InnoEngine", + revision, + sourceTree = tree, + toolingRevision = revision, + projectManifest = "reference/projects/catalog.json", + projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(projects)), + apiManifests = new[] + { + new + { + path = "reference/api/probe.json", + sha256 = Convert.ToHexStringLower(SHA256.HashData(facts)), + model = "source-clr", + configuration = "Debug", + sourceRevision = revision, + sourceTree = tree + } + } + }) + ); + Write( + "documentation/content/en/probe.md", + "---\nuid: probe\nkind: project\nowners: [Inno.Probe]\n---\n# Probe\n\nUse the declared source contract.\n" + ); return Path.Combine(m_root, "documentation"); } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs index f8d062e4e..3d3d0b2da 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs @@ -17,13 +17,17 @@ public sealed class DocumentationSourceContractTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoDocumentationSourceContracts", Guid.NewGuid().ToString("N")); private const string C_PROJECT = "tests/support/Contract/Contract.csproj"; + private readonly string m_host = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? throw new InvalidOperationException("The source contract fixture requires its selected SDK host."); + ?? throw new InvalidOperationException("The source contract fixture requires its selected SDK host."); public DocumentationSourceContractTests() { Write("InnoEngine.sln", "Microsoft Visual Studio Solution File, Format Version 12.00\n"); - Write(C_PROJECT, "net10.0enable"); + Write( + C_PROJECT, + "net10.0enable" + ); } [Fact] @@ -51,7 +55,9 @@ public class NotExported { } string facts = Path.Combine(m_root, "scope.json"); Assert.Equal(0, DocumentationReferences.ExportApi(ExportArguments(facts))); using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(facts)); - var symbols = document.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray() + var symbols = document.RootElement.GetProperty("projects")[0] + .GetProperty("symbols") + .EnumerateArray() .ToDictionary(symbol => symbol.GetProperty("id").GetString()!); Assert.Equal("Runtime", symbols["M:Contract.Outer.Read"].GetProperty("scriptingScope").GetString()); Assert.Equal("Editor", symbols["T:Contract.Outer.Inner"].GetProperty("scriptingScope").GetString()); @@ -91,7 +97,8 @@ public sealed class Probe Assert.Equal(0, DocumentationReferences.ExportApi(ExportArguments(facts))); using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(facts)); JsonElement[] symbols = document.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray().ToArray(); - string Signature(string id) => symbols.Single(symbol => symbol.GetProperty("id").GetString() == id).GetProperty("signature").GetString()!; + string Signature(string id) + => symbols.Single(symbol => symbol.GetProperty("id").GetString() == id).GetProperty("signature").GetString()!; Assert.Contains("sealed", Signature("T:Contract.Probe")); Assert.Contains("readonly", Signature("T:Contract.Token")); Assert.Contains("delegate string", Signature("T:Contract.Transform")); @@ -103,14 +110,23 @@ public sealed class Probe Assert.Contains("IReader", Signature("T:Contract.Snapshot")); Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "M:Contract.Snapshot.#ctor(System.String)"); Assert.Contains(symbols, symbol => symbol.GetProperty("id").GetString() == "P:Contract.Snapshot.Value"); - Assert.Contains("borrowed value", symbols.Single(symbol => symbol.GetProperty("id").GetString() == "M:Contract.Snapshot.Read").GetProperty("documentation").GetString()); + Assert.Contains( + "borrowed value", + symbols + .Single(symbol => symbol.GetProperty("id").GetString() == "M:Contract.Snapshot.Read") + .GetProperty("documentation") + .GetString() + ); Assert.DoesNotContain(symbols, symbol => symbol.GetProperty("id").GetString()!.Contains("m_value", StringComparison.Ordinal)); string comparison = Path.Combine(m_root, "comparison.json"); string[] arguments = ["--engine-root", m_root, "--dotnet", m_host, "--reference", facts, "--output", comparison]; Assert.Equal(0, await DocumentationReferences.ValidateApiAsync(arguments)); - Write("tests/support/Contract/Contract.cs", C_SOURCE.Replace("sealed class Probe", "class Probe", StringComparison.Ordinal) - .Replace("ref readonly int Read()", "ref int Read()", StringComparison.Ordinal) - .Replace("string? name = null", "string name = \"default\"", StringComparison.Ordinal)); + Write( + "tests/support/Contract/Contract.cs", + C_SOURCE.Replace("sealed class Probe", "class Probe", StringComparison.Ordinal) + .Replace("ref readonly int Read()", "ref int Read()", StringComparison.Ordinal) + .Replace("string? name = null", "string name = \"default\"", StringComparison.Ordinal) + ); Assert.Equal(1, await DocumentationReferences.ValidateApiAsync(arguments)); string failures = File.ReadAllText(comparison); Assert.Contains("T:Contract.Probe", failures); @@ -122,22 +138,33 @@ public sealed class Probe public async Task CompileOnlyPackageContractsNeedNoRuntimeDeploymentAndCannotDisappear() { string reference = Path.Combine(m_root, "PackageContract.dll"); - var compilation = CSharpCompilation.Create("PackageContract", + var compilation = CSharpCompilation.Create( + "PackageContract", [CSharpSyntaxTree.ParseText("namespace PackageContract; public abstract class BaseContract { }")], - ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator).Select(static file => MetadataReference.CreateFromFile(file)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) + .Split(Path.PathSeparator) + .Select(static file => MetadataReference.CreateFromFile(file)), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); Assert.True(compilation.Emit(reference).Success); string feed = Path.Combine(m_root, "feed"); Directory.CreateDirectory(feed); using (ZipArchive package = ZipFile.Open(Path.Combine(feed, "ContractFixture.1.0.0.nupkg"), ZipArchiveMode.Create)) { using (var writer = new StreamWriter(package.CreateEntry("ContractFixture.nuspec").Open(), new UTF8Encoding(false))) - writer.Write("ContractFixture1.0.0InnoEngineCompile-only fixture."); + { + writer.Write( + "ContractFixture1.0.0InnoEngineCompile-only fixture." + ); + } package.CreateEntryFromFile(reference, "ref/net10.0/PackageContract.dll"); using Stream empty = package.CreateEntry("lib/net10.0/_._").Open(); } - Write(C_PROJECT, "net10.0" - + ""); + Write( + C_PROJECT, + "net10.0" + + "" + ); Write("tests/support/Contract/Contract.cs", "namespace Contract; public abstract class Probe : PackageContract.BaseContract;"); await RestoreAsync("--source", feed, "--packages", Path.Combine(m_root, "packages")); string output = Path.Combine(m_root, "facts.json"); @@ -155,14 +182,23 @@ public async Task CompileOnlyPackageContractsNeedNoRuntimeDeploymentAndCannotDis [Fact] public async Task EvaluatedImportsConstantsAndGeneratedInputsDefineTheSourceContract() { - Write("tests/support/Contract/Framework.props", "net10.0"); + Write( + "tests/support/Contract/Framework.props", + "net10.0" + ); const string C_PROJECT_TEXT = "" + "SELECTED_CONTRACT" + ""; Write(C_PROJECT, C_PROJECT_TEXT); - Write("tests/support/Contract/Contract.cs", "namespace Contract;\n#if SELECTED_CONTRACT\npublic sealed class Selected;\n#else\npublic sealed class WrongBranch;\n#endif\n"); + Write( + "tests/support/Contract/Contract.cs", + "namespace Contract;\n#if SELECTED_CONTRACT\npublic sealed class Selected;\n#else\npublic sealed class WrongBranch;\n#endif\n" + ); Write("tests/support/Contract/Excluded.cs", "public sealed class Excluded;"); - Write("tests/support/Contract/obj/Selected.cs", "namespace Contract; public sealed class Generated { public enum Kind { None, Present } }"); + Write( + "tests/support/Contract/obj/Selected.cs", + "namespace Contract; public sealed class Generated { public enum Kind { None, Present } }" + ); Write("tests/support/Contract/obj/Unselected.cs", "public sealed class Unselected;"); await RestoreAsync(); string output = Path.Combine(m_root, "facts.json"); @@ -170,13 +206,30 @@ public async Task EvaluatedImportsConstantsAndGeneratedInputsDefineTheSourceCont string facts = File.ReadAllText(output); Assert.Contains("T:Contract.Selected", facts); Assert.Contains("F:Contract.Generated.Kind.Present", facts); - foreach (string excluded in new[] { "WrongBranch", "Excluded", "Unselected" }) Assert.DoesNotContain(excluded, facts); - Write(C_PROJECT, C_PROJECT_TEXT.Replace("", "99.0", StringComparison.Ordinal)); - InvalidDataException language = Assert.Throws(() => DocumentationReferences.ExportApi(ExportArguments(output))); + foreach (string excluded in new[] { "WrongBranch", "Excluded", "Unselected" }) + { + Assert.DoesNotContain(excluded, facts); + } + Write( + C_PROJECT, + C_PROJECT_TEXT.Replace("", "99.0", StringComparison.Ordinal) + ); + InvalidDataException language = Assert.Throws( + () => DocumentationReferences.ExportApi(ExportArguments(output)) + ); Assert.Contains("unsupported C# language version", language.Message); Assert.Equal(facts, File.ReadAllText(output)); - Write(C_PROJECT, C_PROJECT_TEXT.Replace("", "", StringComparison.Ordinal)); - InvalidDataException missing = Assert.Throws(() => DocumentationReferences.ExportApi(ExportArguments(output))); + Write( + C_PROJECT, + C_PROJECT_TEXT.Replace( + "", + "", + StringComparison.Ordinal + ) + ); + InvalidDataException missing = Assert.Throws( + () => DocumentationReferences.ExportApi(ExportArguments(output)) + ); Assert.Contains("requires its evaluated compile reference", missing.Message); Assert.Equal(facts, File.ReadAllText(output)); } @@ -184,7 +237,9 @@ public async Task EvaluatedImportsConstantsAndGeneratedInputsDefineTheSourceCont [Fact] public async Task PrivateProductEntriesHaveAnExplicitEmptySurfaceWithoutCompiledDependencies() { - Write(C_PROJECT, File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace("", """ + Write( + C_PROJECT, + File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace("", """ @@ -192,7 +247,8 @@ public async Task PrivateProductEntriesHaveAnExplicitEmptySurfaceWithoutCompiled - """, StringComparison.Ordinal)); + """, StringComparison.Ordinal) + ); const string C_SOURCE = "namespace Contract; internal sealed class Entry : UnavailableBase { public void Run() { } }"; Write("tests/support/Contract/Entry.cs", C_SOURCE); await RestoreAsync(); @@ -208,7 +264,9 @@ public async Task PrivateProductEntriesHaveAnExplicitEmptySurfaceWithoutCompiled } Assert.False(File.Exists(Path.Combine(m_root, "tests/support/Contract/bin/Debug/net10.0/Contract.dll"))); Write("tests/support/Contract/Entry.cs", C_SOURCE.Replace("internal sealed", "public sealed", StringComparison.Ordinal)); - InvalidDataException failure = Assert.Throws(() => DocumentationReferences.ExportApi(ExportArguments(output))); + InvalidDataException failure = Assert.Throws( + () => DocumentationReferences.ExportApi(ExportArguments(output)) + ); Assert.Contains("requires its evaluated compile reference", failure.Message); Assert.Equal(original, File.ReadAllBytes(output)); } @@ -216,11 +274,14 @@ public async Task PrivateProductEntriesHaveAnExplicitEmptySurfaceWithoutCompiled [Fact] public async Task EmptySurfaceUsesSelectedConditionalAndGeneratedSourceInputs() { - Write(C_PROJECT, File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace("", """ + Write( + C_PROJECT, + File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace("", """ EXPOSE_CONTRACT - """, StringComparison.Ordinal)); + """, StringComparison.Ordinal) + ); Write("tests/support/Contract/Entry.cs", "namespace Contract; internal sealed class Entry;"); Write("tests/support/Contract/obj/Selected.cs", """ namespace Contract; @@ -236,11 +297,15 @@ namespace Contract; Assert.Contains("T:Contract.GeneratedContract", File.ReadAllText(output)); byte[] previous = File.ReadAllBytes(output); Write("tests/support/Contract/obj/Selected.cs", "internal class Broken {"); - InvalidDataException invalid = Assert.Throws(() => DocumentationReferences.ExportApi(ExportArguments(output))); + InvalidDataException invalid = Assert.Throws( + () => DocumentationReferences.ExportApi(ExportArguments(output)) + ); Assert.Contains("invalid C# syntax", invalid.Message); Assert.Equal(previous, File.ReadAllBytes(output)); File.Delete(Path.Combine(m_root, "tests/support/Contract/obj/Selected.cs")); - InvalidDataException missing = Assert.Throws(() => DocumentationReferences.ExportApi(ExportArguments(output))); + InvalidDataException missing = Assert.Throws( + () => DocumentationReferences.ExportApi(ExportArguments(output)) + ); Assert.Contains("source is missing", missing.Message); Assert.Equal(previous, File.ReadAllBytes(output)); } @@ -248,13 +313,21 @@ namespace Contract; [Fact] public async Task ForeignProductSelectionCannotBorrowHostReferences() { - Write(C_PROJECT, File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace("", - "foreign-fixture", StringComparison.Ordinal)); + Write( + C_PROJECT, + File.ReadAllText(Path.Combine(m_root, C_PROJECT)).Replace( + "", + "foreign-fixture", + StringComparison.Ordinal + ) + ); Write("tests/support/Contract/Contract.cs", "namespace Contract; public sealed class Probe;"); await RestoreAsync(); string output = Path.Combine(m_root, "facts.json"); File.WriteAllText(output, "retain prior evidence"); - Assert.Throws(() => DocumentationReferences.ExportApi([..ExportArguments(output), "--target", "host-fixture"])); + Assert.Throws( + () => DocumentationReferences.ExportApi([..ExportArguments(output), "--target", "host-fixture"]) + ); Assert.Equal("retain prior evidence", File.ReadAllText(output)); } @@ -264,7 +337,10 @@ public async Task ExtractionReusesOwnersAndInvalidatesSameLengthSourceWithPreser const string C_OTHER = "src/Other/Other.csproj"; const string C_SOURCE = "namespace Contract;\n/// Alpha contract.\npublic sealed class Probe;"; Write("tests/support/Contract/Contract.cs", C_SOURCE); - Write(C_OTHER, "net10.0"); + Write( + C_OTHER, + "net10.0" + ); Write("src/Other/Other.cs", "namespace Other; public sealed class Independent;"); await RestoreAsync(); await RestoreProjectAsync(C_OTHER, []); @@ -276,7 +352,9 @@ public async Task ExtractionReusesOwnersAndInvalidatesSameLengthSourceWithPreser Assert.Equal(2, originals.Length); DateTime retainedTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); foreach (string file in originals) + { File.SetLastWriteTimeUtc(file, retainedTime); + } byte[] previous = File.ReadAllBytes(output); Write("notes.md", "A report does not alter compiler inputs."); Assert.Equal(0, DocumentationReferences.ExportApi(arguments)); @@ -308,7 +386,9 @@ public async Task CorruptExtractionIsQuarantinedBeforeARealReplacementIsReturned File.SetLastWriteTimeUtc(payload, timestamp); Assert.Equal(0, DocumentationReferences.ExportApi(ExportArguments(output))); Assert.Equal(previous, File.ReadAllBytes(output)); - string quarantine = Assert.Single(Directory.GetFiles(Path.Combine(cache, "quarantine"), "project.json", SearchOption.AllDirectories)); + string quarantine = Assert.Single( + Directory.GetFiles(Path.Combine(cache, "quarantine"), "project.json", SearchOption.AllDirectories) + ); Assert.Equal(corrupt, File.ReadAllText(quarantine)); } @@ -328,13 +408,17 @@ public async Task ExtractionPayloadsCanMoveWithoutCopyingLocalOwnershipOrLeases( foreach (string file in Directory.GetFiles(entries, "*", SearchOption.AllDirectories)) { string relative = Path.GetRelativePath(entries, file); - Assert.True(relative.EndsWith("project.json", StringComparison.Ordinal) - || relative.EndsWith("generation-manifest.json", StringComparison.Ordinal)); + Assert.True( + relative.EndsWith("project.json", StringComparison.Ordinal) + || relative.EndsWith("generation-manifest.json", StringComparison.Ordinal) + ); string destination = Path.Combine(consumer.m_root, C_ENTRIES, relative); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(file, destination); } - string payload = Assert.Single(Directory.GetFiles(Path.Combine(consumer.m_root, C_ENTRIES), "project.json", SearchOption.AllDirectories)); + string payload = Assert.Single( + Directory.GetFiles(Path.Combine(consumer.m_root, C_ENTRIES), "project.json", SearchOption.AllDirectories) + ); DateTime retainedTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); File.SetLastWriteTimeUtc(payload, retainedTime); string result = Path.Combine(consumer.m_root, "facts.json"); @@ -350,18 +434,26 @@ public async Task ExtractionPayloadsCanMoveWithoutCopyingLocalOwnershipOrLeases( public async Task ExtractionInvalidatesInheritedXmlWithoutChangingTheReferenceAssembly() { string reference = Path.Combine(m_root, "BaseContract.dll"); - var compilation = CSharpCompilation.Create("BaseContract", + var compilation = CSharpCompilation.Create( + "BaseContract", [CSharpSyntaxTree.ParseText("namespace BaseContract; public abstract class Parent { public abstract void Read(); }")], ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator) .Select(static file => MetadataReference.CreateFromFile(file)), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); Assert.True(compilation.Emit(reference).Success); string xml = Path.ChangeExtension(reference, ".xml"); const string C_XML = "Alpha obligation."; File.WriteAllText(xml, C_XML); - Write(C_PROJECT, "net10.0" - + "../../../BaseContract.dll"); - Write("tests/support/Contract/Contract.cs", "namespace Contract; public sealed class Probe : BaseContract.Parent {\n/// \npublic override void Read() {} }"); + Write( + C_PROJECT, + "net10.0" + + "../../../BaseContract.dll" + ); + Write( + "tests/support/Contract/Contract.cs", + "namespace Contract; public sealed class Probe : BaseContract.Parent {\n/// \npublic override void Read() {} }" + ); await RestoreAsync(); string output = Path.Combine(m_root, "facts.json"); Assert.Equal(0, DocumentationReferences.ExportApi(ExportArguments(output))); @@ -376,11 +468,15 @@ public async Task ExtractionInvalidatesInheritedXmlWithoutChangingTheReferenceAs public void Dispose() { string boundary = Path.Combine(Path.GetTempPath(), "InnoDocumentationSourceContracts") + Path.DirectorySeparatorChar; - if (!Path.GetFullPath(m_root).StartsWith(boundary, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("Fixture ownership escaped."); + if (!Path.GetFullPath(m_root).StartsWith(boundary, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("Fixture ownership escaped."); + } Directory.Delete(m_root, recursive: true); } - private string[] ExportArguments(string output) => ["--engine-root", m_root, "--dotnet", m_host, "--project", C_PROJECT, "--output", output]; + private string[] ExportArguments(string output) + => ["--engine-root", m_root, "--dotnet", m_host, "--project", C_PROJECT, "--output", output]; private Task RestoreAsync(params string[] arguments) => RestoreProjectAsync(C_PROJECT, arguments); @@ -388,8 +484,25 @@ private async Task RestoreProjectAsync( string project, string[] arguments ) { - var start = new ProcessStartInfo(m_host) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; - foreach (string argument in new[] { "restore", Path.Combine(m_root, project), "--disable-parallel", "-m:1", "-nr:false", "--disable-build-servers" }.Concat(arguments)) start.ArgumentList.Add(argument); + var start = new ProcessStartInfo(m_host) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + foreach (string argument in new[] + { + "restore", + Path.Combine(m_root, project), + "--disable-parallel", + "-m:1", + "-nr:false", + "--disable-build-servers" + }.Concat(arguments) + ) { + start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task stdout = process.StandardOutput.ReadToEndAsync(); Task stderr = process.StandardError.ReadToEndAsync(); @@ -397,8 +510,10 @@ string[] arguments Assert.True(process.ExitCode == 0, await stdout + await stderr); } - private void Write(string relative, string text) - { + private void Write( + string relative, + string text + ) { string file = Path.Combine(m_root, relative); Directory.CreateDirectory(Path.GetDirectoryName(file)!); File.WriteAllText(file, text); diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/IntegrationBoundaryTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/IntegrationBoundaryTests.cs index 801b59ffe..3a38b82e7 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/IntegrationBoundaryTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/IntegrationBoundaryTests.cs @@ -4,6 +4,7 @@ using Xunit; namespace Inno.Tooling.Architecture.Tests; + [Collection("Architecture diagnostics")] public sealed class IntegrationBoundaryTests { @@ -19,19 +20,36 @@ public void ImportedTestDeclarationsCannotEscapeRootOwnership(string declaration Directory.CreateDirectory(owner); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); File.WriteAllText(Path.Combine(root, "TestSupport.props"), "" + declaration + ""); - File.WriteAllText(Path.Combine(owner, "Probe.csproj"), + File.WriteAllText( + Path.Combine(owner, "Probe.csproj"), "" - + "net10.0disable"); - string host = Path.GetFullPath(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); - (_, string report) = ArchitectureCommandFixture.Run(root, "--source-only", "--dotnet", host, - "--artifacts-path", Path.Combine(root, "artifacts")); + + "net10.0disable" + ); + string host = Path.GetFullPath( + Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), + "..", + "..", + "..", + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ) + ); + (_, string report) = ArchitectureCommandFixture.Run( + root, + "--source-only", + "--dotnet", + host, + "--artifacts-path", + Path.Combine(root, "artifacts") + ); Assert.Contains("effective test projects must belong to the root tests directory", report, StringComparison.Ordinal); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -54,15 +72,19 @@ bool rejected string directory = Path.Combine(root, owner); Directory.CreateDirectory(directory); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); - File.WriteAllText(Path.Combine(directory, "Probe.csproj"), - "" + properties + "" + items + ""); + File.WriteAllText( + Path.Combine(directory, "Probe.csproj"), + "" + properties + "" + items + "" + ); (_, string report) = ArchitectureCommandFixture.Run(root); Assert.Equal(rejected, report.Contains("engine-owned tests and test support must belong", StringComparison.Ordinal)); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -70,21 +92,76 @@ bool rejected [InlineData("src/services/Probe", "tests/core/Probe.Tests", "production code cannot reference test support", true)] [InlineData("tests/build/Probe.Tests", "tests/build/fixtures/Probe.Support", "production code cannot reference test support", false)] [InlineData("platforms/WindowsX64/build/Probe", "backends/Bgfx/build/ProbeBackend", "platform base modules cannot select", true)] - [InlineData("platforms/WindowsX64/integrations/Probe", "backends/Bgfx/build/ProbeBackend", "platform base modules cannot select", false)] + [InlineData( + "platforms/WindowsX64/integrations/Probe", + "backends/Bgfx/build/ProbeBackend", + "platform base modules cannot select", + false + )] [InlineData("backends/Bgfx/build/ProbeBackend", "platforms/WindowsX64/integrations/Probe", "reusable backends cannot depend", true)] - [InlineData("platforms/BrowserWasm32/integrations/Probe", "platforms/WindowsX64/integrations/ProbeWindows", "one concrete platform cannot depend", true)] - [InlineData("platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", "backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx", "runtime surface integrations cannot depend", false)] - [InlineData("platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx", "runtime surface integrations cannot depend", true)] - [InlineData("platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", "backends/Bgfx/native/Inno.Native.Bgfx", "runtime surface integrations cannot depend", true)] + [InlineData( + "platforms/BrowserWasm32/integrations/Probe", + "platforms/WindowsX64/integrations/ProbeWindows", + "one concrete platform cannot depend", + true + )] + [InlineData( + "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", + "backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx", + "runtime surface integrations cannot depend", + false + )] + [InlineData( + "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", + "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx", + "runtime surface integrations cannot depend", + true + )] + [InlineData( + "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx.Runtime", + "backends/Bgfx/native/Inno.Native.Bgfx", + "runtime surface integrations cannot depend", + true + )] [InlineData("build/toolchains/Probe", "build/bindings/Inno.Build.Bindings", "neutral toolchains cannot depend", true)] [InlineData("build/bindings/Inno.Build.Bindings", "build/tasks/Inno.Build.Tasks", "binding generation cannot depend", true)] [InlineData("platforms/WindowsX64/build/Probe", "build/bindings/Inno.Build.Bindings", "platform modules must borrow", true)] - [InlineData("src/composition/editor/features/Inno.Editor.TestFeature", "src/composition/editor/presentation/Inno.Editor.ImGui", "Editor feature editing must be presentation-independent", true)] - [InlineData("src/composition/editor/features/Inno.Editor.TestFeature", "src/composition/editor/framework/Inno.Editor.Interactions", "Editor feature editing must be presentation-independent", false)] - [InlineData("src/composition/editor/panels/Inno.Editor.Panel.A", "src/composition/editor/panels/Inno.Editor.Panel.B", "Panels cannot depend on other Panels", true)] - [InlineData("src/composition/editor/panels/Inno.Editor.Panel.A", "src/composition/editor/presentation/Inno.Editor.Assets.ImGui", "Panels cannot depend on other Panels", false)] - [InlineData("src/composition/editor/panels/Inno.Editor.Panel.A", "backends/ImGui/native/Inno.Native.ImGui", "native UI access belongs", true)] - [InlineData("src/composition/editor/presentation/Inno.Editor.Graph.ImGui", "src/composition/editor/features/Inno.Editor.Shaders", "reusable Graph mechanisms cannot depend", true)] + [InlineData( + "src/composition/editor/features/Inno.Editor.TestFeature", + "src/composition/editor/presentation/Inno.Editor.ImGui", + "Editor feature editing must be presentation-independent", + true + )] + [InlineData( + "src/composition/editor/features/Inno.Editor.TestFeature", + "src/composition/editor/framework/Inno.Editor.Interactions", + "Editor feature editing must be presentation-independent", + false + )] + [InlineData( + "src/composition/editor/panels/Inno.Editor.Panel.A", + "src/composition/editor/panels/Inno.Editor.Panel.B", + "Panels cannot depend on other Panels", + true + )] + [InlineData( + "src/composition/editor/panels/Inno.Editor.Panel.A", + "src/composition/editor/presentation/Inno.Editor.Assets.ImGui", + "Panels cannot depend on other Panels", + false + )] + [InlineData( + "src/composition/editor/panels/Inno.Editor.Panel.A", + "backends/ImGui/native/Inno.Native.ImGui", + "native UI access belongs", + true + )] + [InlineData( + "src/composition/editor/presentation/Inno.Editor.Graph.ImGui", + "src/composition/editor/features/Inno.Editor.Shaders", + "reusable Graph mechanisms cannot depend", + true + )] public void CliChecksActualPlatformIntegrationProjectReferences( string owner, string dependency, @@ -97,7 +174,12 @@ bool rejected Directory.CreateDirectory(root); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); string destination = CreateProject(dependency, string.Empty); - CreateProject(owner, ""); + CreateProject( + owner, + "" + ); (_, string report) = ArchitectureCommandFixture.Run(root); Assert.Equal(rejected, report.Contains(expected, StringComparison.Ordinal)); Assert.DoesNotContain("explicit project dependency is missing", report); @@ -108,14 +190,19 @@ string references string directory = Path.Combine(root, relative); Directory.CreateDirectory(directory); string path = Path.Combine(directory, Path.GetFileName(directory) + ".csproj"); - File.WriteAllText(path, "net10.0" + references + ""); + File.WriteAllText( + path, + "net10.0" + references + "" + ); return path; } } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } @@ -133,20 +220,30 @@ public void ScriptSdkReferencesPanelContractsOnlyWhenThePanelActuallyExportsThem Directory.CreateDirectory(Path.Combine(panel, "Properties")); File.WriteAllText(Path.Combine(root, "InnoEngine.sln"), "Microsoft Visual Studio Solution File, Format Version 12.00"); string panelProject = Path.Combine(panel, "Inno.Editor.Panel.Probe.csproj"); - File.WriteAllText(panelProject, "net10.0"); + File.WriteAllText( + panelProject, + "net10.0" + ); string include = Path.GetRelativePath(host, panelProject).Replace('\\', '/'); - File.WriteAllText(Path.Combine(host, "Inno.Build.Cli.csproj"), + File.WriteAllText( + Path.Combine(host, "Inno.Build.Cli.csproj"), "net10.0"); + + include + "\" />" + ); const string C_EXPORT_DECLARATION = "[assembly: Inno.Scripting.Api.ScriptingApiExport(typeof(System.String), Inno.Scripting.Api.ScriptingApiScope.Editor)]"; - File.WriteAllText(Path.Combine(panel, "Properties/ScriptingApi.cs"), exportsContract ? C_EXPORT_DECLARATION : "// " + C_EXPORT_DECLARATION); + File.WriteAllText( + Path.Combine(panel, "Properties/ScriptingApi.cs"), + exportsContract ? C_EXPORT_DECLARATION : "// " + C_EXPORT_DECLARATION + ); (_, string report) = ArchitectureCommandFixture.Run(root); Assert.Equal(!exportsContract, report.Contains("script SDK host must reference API owners", StringComparison.Ordinal)); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs index 04a3dba82..3aa6df152 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs @@ -39,17 +39,21 @@ bool rejected File.WriteAllText(Path.Combine(bindings, "bindings.props"), ""); File.WriteAllText(Path.Combine(bindings, "bindgen.json"), configuration); if (targetPreset) + { File.WriteAllText(Path.Combine(bindings, "bindgen.probe-target.json"), "{}"); + } (_, string output) = ArchitectureCommandFixture.Run(root); bool violation = output.Contains("belongs to a platform Profile", StringComparison.Ordinal) - || output.Contains("must be supplied by the platform provider", StringComparison.Ordinal) - || output.Contains("platform binding presets belong", StringComparison.Ordinal); + || output.Contains("must be supplied by the platform provider", StringComparison.Ordinal) + || output.Contains("platform binding presets belong", StringComparison.Ordinal); Assert.Equal(rejected, violation); } finally { if (Directory.Exists(root)) + { Directory.Delete(root, recursive: true); + } } } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs index b29d1425e..bd9916c10 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs @@ -2,8 +2,8 @@ using System.IO; using System.Reflection; using System.Reflection.Emit; -using Inno.Testing.Source; using Xunit; +using Inno.Testing.Source; namespace Inno.Tooling.Architecture.Tests; @@ -39,8 +39,7 @@ public void MissingRelativeAndUnavailableDeclarationsAreRejected() CreateAssembly("relative-checkout"), CreateAssembly(Path.Combine(m_root, "absent")), CreateAssembly(m_root) - }) - { + }) { Assert.Throws(() => TestRepository.GetRoot(assembly)); } } @@ -70,7 +69,9 @@ private static Assembly CreateAssembly(params string[] directories) AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndCollect); ConstructorInfo constructor = typeof(AssemblyMetadataAttribute).GetConstructor([typeof(string), typeof(string)])!; foreach (string directory in directories) + { assembly.SetCustomAttribute(new CustomAttributeBuilder(constructor, ["Inno.Testing.RepositoryRoot", directory])); + } return assembly; } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs index 490d976de..a4e709a11 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs @@ -1,16 +1,16 @@ using System; +using System.Collections.Generic; using System.IO; +using System.Linq; using System.Reflection; using System.Reflection.Emit; -using System.Linq; -using System.Collections.Generic; -using System.Text.Json; using System.Security; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Testing.Source; -using Xunit; namespace Inno.Tooling.Architecture.Tests; @@ -40,24 +40,43 @@ await File.WriteAllTextAsync(project, $""" string dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); var arguments = new List { - "msbuild", project, "-nologo", "-nr:false", "-t:GetAssemblyAttributes", - "-getProperty:ArtifactsPath", "-getItem:AssemblyAttribute", + "msbuild", + project, + "-nologo", + "-nr:false", + "-t:GetAssemblyAttributes", + "-getProperty:ArtifactsPath", + "-getItem:AssemblyAttribute", "-p:UseArtifactsOutput=" + useArtifacts.ToString().ToLowerInvariant() }; if (explicitOwner) + { arguments.Add("-p:ArtifactsPath=" + Path.Combine(root, "independent")); + } using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(1)); - string output = await ToolchainEnvironment.CaptureOutputAsync(dotnet, arguments, - root, timeout.Token, DotNetSdkEnvironment.Create(dotnet)); + string output = await ToolchainEnvironment.CaptureOutputAsync( + dotnet, + arguments, + root, + timeout.Token, + DotNetSdkEnvironment.Create(dotnet) + ); using JsonDocument result = JsonDocument.Parse(output); string? artifacts = result.RootElement.GetProperty("Properties").GetProperty("ArtifactsPath").GetString(); - JsonElement[] declarations = result.RootElement.GetProperty("Items").GetProperty("AssemblyAttribute").EnumerateArray() - .Where(item => item.TryGetProperty("_Parameter1", out var key) && key.GetString() == "Inno.Testing.ArtifactsPath").ToArray(); + JsonElement[] declarations = result.RootElement.GetProperty("Items") + .GetProperty("AssemblyAttribute") + .EnumerateArray() + .Where(item => item.TryGetProperty("_Parameter1", out var key) && key.GetString() == "Inno.Testing.ArtifactsPath") + .ToArray(); if (useArtifacts) { Assert.False(string.IsNullOrWhiteSpace(artifacts)); - Assert.Equal(Path.GetFullPath(artifacts!), Path.TrimEndingDirectorySeparator( - Assert.Single(declarations).GetProperty("_Parameter2").GetString()!)); + Assert.Equal( + Path.GetFullPath(artifacts!), + Path.TrimEndingDirectorySeparator( + Assert.Single(declarations).GetProperty("_Parameter2").GetString()! + ) + ); } else { @@ -94,10 +113,14 @@ public void RelativeEmptyOrDuplicateArtifactsDeclarationsAreRejected() private static Assembly CreateAssembly(params string[] owners) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly( - new AssemblyName("RepositoryInputs." + Guid.NewGuid().ToString("N")), AssemblyBuilderAccess.RunAndCollect); + new AssemblyName("RepositoryInputs." + Guid.NewGuid().ToString("N")), + AssemblyBuilderAccess.RunAndCollect + ); ConstructorInfo constructor = typeof(AssemblyMetadataAttribute).GetConstructor([typeof(string), typeof(string)])!; foreach (string owner in owners) + { assembly.SetCustomAttribute(new CustomAttributeBuilder(constructor, ["Inno.Testing.ArtifactsPath", owner])); + } return assembly; } } diff --git a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs index 090f53e6c..1ec55d331 100644 --- a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs +++ b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs @@ -7,8 +7,8 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Tooling.Documentation.Tests; @@ -26,9 +26,18 @@ public sealed class DocumentationApiSynchronizationTests : IDisposable public async Task ProjectGuideBecomesAuthoredOnEditAndTracksSubsequentSourceChanges() { const string C_PAGE = "content/en/architecture/projects/probe.md"; - Write("reference/projects/content.json", JsonSerializer.Serialize(new { schema = "inno-project-guides/1", - entries = new[] { new { path = C_PAGE, uid = "project.probe", project = "Inno.Probe" } } })); - Write(C_PAGE, "---\nuid: project.probe\nsymbol: project:Inno.Probe\ntitle: Inno.Probe\nkind: project\nowners: [Inno.Probe]\nsource: xml\n---\n"); + Write( + "reference/projects/content.json", + JsonSerializer.Serialize(new + { + schema = "inno-project-guides/1", + entries = new[] { new { path = C_PAGE, uid = "project.probe", project = "Inno.Probe" } } + }) + ); + Write( + C_PAGE, + "---\nuid: project.probe\nsymbol: project:Inno.Probe\ntitle: Inno.Probe\nkind: project\nowners: [Inno.Probe]\nsource: xml\n---\n" + ); Bind(description: "The value\ncontract."); await Sync(); string path = Path.Combine(m_root, C_PAGE); @@ -37,14 +46,19 @@ public async Task ProjectGuideBecomesAuthoredOnEditAndTracksSubsequentSourceChan await Sync(); Assert.Equal(first, File.ReadAllText(path)); string manual = first.Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nIndependent lifetime guidance.\n"; + + "\nIndependent lifetime guidance.\n"; File.WriteAllText(path, manual); await Sync(); Assert.Equal(manual, File.ReadAllText(path)); string cache = Path.Combine(m_root, "artifacts/project-query"); var initial = await DocumentationStore.IndexAsync(m_root, m_root, cache); using (var initialSnapshot = await DocumentationStore.OpenAsync(cache, initial.snapshot)) - Assert.Contains("[!AUTHORED]", (await initialSnapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.probe").markdown); + { + Assert.Contains( + "[!AUTHORED]", + (await initialSnapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.probe").markdown + ); + } string original = File.ReadAllText(path); Bind(description: "The value\r\ncontract."); await Sync(); @@ -68,8 +82,14 @@ public async Task ProjectGuideBecomesAuthoredOnEditAndTracksSubsequentSourceChan public async Task ProjectGuideRegistryCannotClaimUnrelatedManualPages() { Write("content/en/manual/keep.md", "Preserve this unrelated guide."); - Write("reference/projects/content.json", JsonSerializer.Serialize(new { schema = "inno-project-guides/1", - entries = new[] { new { path = "content/en/manual/keep.md", uid = "manual.keep", project = "Inno.Probe" } } })); + Write( + "reference/projects/content.json", + JsonSerializer.Serialize(new + { + schema = "inno-project-guides/1", + entries = new[] { new { path = "content/en/manual/keep.md", uid = "manual.keep", project = "Inno.Probe" } } + }) + ); await Assert.ThrowsAsync(() => Sync(CancellationToken.None)); Assert.Equal("Preserve this unrelated guide.", File.ReadAllText(Path.Combine(m_root, "content/en/manual/keep.md"))); } @@ -81,26 +101,42 @@ public async Task NewProjectsReceiveSynchronizedGuidesBesideTheirOwnerKind() const string C_AUTHORED_TEXT = "---\nuid: project.authored\ntitle: Authored\nkind: project\nowners:\n - Inno.Authored.Tests\n---\n# Authored\n"; WriteGuideRegistry(); Write(C_AUTHORED, C_AUTHORED_TEXT); - SetProjects(("Inno.Probe", "src/Inno.Probe.csproj"), ("Inno.Probe.Tests", "tests/Inno.Probe.Tests/Inno.Probe.Tests.csproj"), - ("Inno.Adapter.Probe", "backends/Probe/Inno.Adapter.Probe.csproj"), ("Inno.Platform.Probe", "platforms/Probe/Inno.Platform.Probe.csproj"), - ("Inno.Authored.Tests", "tests/Inno.Authored.Tests/Inno.Authored.Tests.csproj")); + SetProjects( + ("Inno.Probe", "src/Inno.Probe.csproj"), + ("Inno.Probe.Tests", "tests/Inno.Probe.Tests/Inno.Probe.Tests.csproj"), + ("Inno.Adapter.Probe", "backends/Probe/Inno.Adapter.Probe.csproj"), + ("Inno.Platform.Probe", "platforms/Probe/Inno.Platform.Probe.csproj"), + ("Inno.Authored.Tests", "tests/Inno.Authored.Tests/Inno.Authored.Tests.csproj") + ); await Sync(); string source = File.ReadAllText(Path.Combine(m_root, "content/en/architecture/projects/inno-probe.md")); - Assert.Contains("uid: project.inno-probe\nsymbol: project:Inno.Probe\ntitle: Inno.Probe\nkind: project\nowners:\n- Inno.Probe\n", source); + Assert.Contains( + "uid: project.inno-probe\nsymbol: project:Inno.Probe\ntitle: Inno.Probe\nkind: project\nowners:\n- Inno.Probe\n", + source + ); Assert.Contains("source: xml", source); Assert.Contains("The value contract.", source); - Assert.Contains("source: xml", File.ReadAllText(Path.Combine(m_root, "content/en/contributing/testing/projects/inno-probe-tests.md"))); + Assert.Contains( + "source: xml", + File.ReadAllText(Path.Combine(m_root, "content/en/contributing/testing/projects/inno-probe-tests.md")) + ); Assert.Contains("source: xml", File.ReadAllText(Path.Combine(m_root, "content/en/backends/projects/inno-adapter-probe.md"))); string[] expected = ["content/en/architecture/projects/inno-probe.md", "content/en/backends/projects/inno-adapter-probe.md", "content/en/contributing/testing/projects/inno-probe-tests.md"]; Assert.Equal(expected, GuideRegistry()); Assert.Equal(C_AUTHORED_TEXT, File.ReadAllText(Path.Combine(m_root, C_AUTHORED))); - Assert.Single(Directory.GetFiles(Path.Combine(m_root, "content/en/contributing/testing/projects")), path => path.EndsWith("inno-probe-tests.md", StringComparison.Ordinal)); + Assert.Single( + Directory.GetFiles(Path.Combine(m_root, "content/en/contributing/testing/projects")), + path => path.EndsWith("inno-probe-tests.md", StringComparison.Ordinal) + ); Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); string cache = Path.Combine(m_root, "artifacts/project-query"); var indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using var snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - Assert.Contains("[!SYNCED]", (await snapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.inno-probe-tests").markdown); + Assert.Contains( + "[!SYNCED]", + (await snapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.inno-probe-tests").markdown + ); } [Theory] @@ -113,7 +149,13 @@ public async Task RemovedProjectsDeleteSynchronizedGuidesAndPreserveAuthoredGuid SetProjects(("Inno.Probe", "src/Inno.Probe.csproj"), ("Inno.Retired", "tools/Inno.Retired/Inno.Retired.csproj")); await Sync(); string path = Path.Combine(m_root, C_PAGE); - if (manual) File.WriteAllText(path, File.ReadAllText(path).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) + "\nRetained guidance.\n"); + if (manual) + { + File.WriteAllText( + path, + File.ReadAllText(path).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) + "\nRetained guidance.\n" + ); + } SetProjects(("Inno.Probe", "src/Inno.Probe.csproj")); await Sync(); Assert.Equal(manual, File.Exists(path)); @@ -148,7 +190,11 @@ public async Task CheckoutsWithoutAGuideRegistryDoNotManageProjectGuides() [InlineData("T:Inno.Probe.Outer`1.Value`1", "public class Inno.Probe.Outer.Value", "Value")] [InlineData("T:Inno.Probe.Outer`1.Value", "public class Inno.Probe.Outer.Value", "Value")] [InlineData("T:Inno.Probe.class`1", "public class Inno.Probe.@class", "@class")] - [InlineData("T:Inno.Probe.Factory`2", "public delegate TResult Inno.Probe.Factory(TValue value)", "Factory")] + [InlineData( + "T:Inno.Probe.Factory`2", + "public delegate TResult Inno.Probe.Factory(TValue value)", + "Factory" + )] public async Task GenericTitlesUseDeclaredNamesAndRenderAsText( string id, string signature, @@ -171,20 +217,24 @@ public async Task GenericParameterRenamesPreserveAddressesAndManualProseWithRead const string C_ONE = "T:Inno.Probe.Value`1"; const string C_TWO = "T:Inno.Probe.Value`2"; const string C_OTHER = "T:Other.Value`1"; - SetTypes((C_TYPE, "public class Inno.Probe.Value"), + SetTypes( + (C_TYPE, "public class Inno.Probe.Value"), (C_ONE, "public class Inno.Probe.Value"), (C_TWO, "public class Inno.Probe.Value"), - (C_OTHER, "public class Other.Value")); + (C_OTHER, "public class Other.Value") + ); await Sync(); string[] paths = new[] { C_TYPE, C_ONE, C_TWO, C_OTHER }.Select(Fragment).ToArray(); Assert.Equal(4, paths.Distinct().Count()); string manual = File.ReadAllText(paths[2]).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nKeep the target alive while the operation runs.\n"; + + "\nKeep the target alive while the operation runs.\n"; File.WriteAllText(paths[2], manual); - SetTypes((C_TYPE, "public class Inno.Probe.Value"), + SetTypes( + (C_TYPE, "public class Inno.Probe.Value"), (C_ONE, "public class Inno.Probe.Value"), (C_TWO, "public class Inno.Probe.Value"), - (C_OTHER, "public class Other.Value")); + (C_OTHER, "public class Other.Value") + ); await Sync(); Assert.Equal(paths, new[] { C_TYPE, C_ONE, C_TWO, C_OTHER }.Select(Fragment)); Assert.Equal(Body(manual), Body(File.ReadAllText(paths[2]))); @@ -211,7 +261,8 @@ public async Task SynchronizationIsDeterministicAndNeverTouchesManualGuides() Write("content/en/manual/task.md", "A hand-written guide without source metadata."); await Sync(); string[] paths = Directory.GetFiles(Path.Combine(m_root, "content/en/api"), "*.md", SearchOption.AllDirectories) - .Where(path => File.ReadAllText(path).Contains("symbol:", StringComparison.Ordinal)).ToArray(); + .Where(path => File.ReadAllText(path).Contains("symbol:", StringComparison.Ordinal)) + .ToArray(); Assert.Equal(2, paths.Length); Assert.All(paths, path => Assert.Contains("source: xml", File.ReadAllText(path))); DateTime[] times = paths.Select(File.GetLastWriteTimeUtc).ToArray(); @@ -226,7 +277,7 @@ public async Task ManualMemberSurvivesXmlChangesWhileItsSiblingUpdates() await Sync(); string member = Fragment(C_MEMBER); string manual = File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nUse this count after the owner has published the snapshot.\n"; + + "\nUse this count after the owner has published the snapshot.\n"; File.WriteAllText(member, manual); Bind(description: "Updated source documentation."); await Sync(); @@ -239,8 +290,10 @@ public async Task ManualMemberSurvivesXmlChangesWhileItsSiblingUpdates() DocumentationPageInfo[] pages = (await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api").ToArray(); Assert.All(pages, page => Assert.Contains("Updated source documentation.", page.markdown)); DocumentationPageInfo memberPage = Assert.Single(pages.Where(page => page.symbols.ContainsKey(C_MEMBER))); - Assert.True(memberPage.markdown.IndexOf("> [!OUTDATED]", StringComparison.Ordinal) - < memberPage.markdown.IndexOf("Updated source documentation.", StringComparison.Ordinal)); + Assert.True( + memberPage.markdown.IndexOf("> [!OUTDATED]", StringComparison.Ordinal) + < memberPage.markdown.IndexOf("Updated source documentation.", StringComparison.Ordinal) + ); Assert.Contains("Use this count after the owner has published the snapshot.", memberPage.markdown); Assert.Contains("Updated source documentation.", File.ReadAllText(Path.Combine(m_root, "content/en/api/engine/probe/index.md"))); Assert.Contains("| Updated source documentation. |", Assert.Single(pages.Where(page => page.symbols.ContainsKey(C_TYPE))).markdown); @@ -262,7 +315,10 @@ async Task AssertStatus(string status) Assert.Contains("> [!" + status + "]", (await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe"))).hits.Single().text); } await AssertStatus("OUTDATED"); - File.WriteAllText(member, File.ReadAllText(member).Replace("description: null", "description:\n- An updated explanation.", StringComparison.Ordinal)); + File.WriteAllText( + member, + File.ReadAllText(member).Replace("description: null", "description:\n- An updated explanation.", StringComparison.Ordinal) + ); Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); await AssertStatus("AUTHORED"); Bind(description: "A changed\r\ncontract."); @@ -291,8 +347,10 @@ public async Task LegacyStaleApiRetainsOutdatedStatusDuringMigration() { await Sync(); string member = Fragment(C_MEMBER); - string legacy = File.ReadAllText(member).Replace("sourceFingerprint:", "reviewed:", StringComparison.Ordinal) - .Replace("source: xml", "source: Ada", StringComparison.Ordinal).Replace("outdated: false", "outdated: true", StringComparison.Ordinal); + string legacy = File.ReadAllText(member) + .Replace("sourceFingerprint:", "reviewed:", StringComparison.Ordinal) + .Replace("source: xml", "source: Ada", StringComparison.Ordinal) + .Replace("outdated: false", "outdated: true", StringComparison.Ordinal); File.WriteAllText(member, legacy); await Sync(); Assert.Contains("outdatedFor:", File.ReadAllText(member)); @@ -321,7 +379,10 @@ public async Task RemovalDeletesXmlAndPreservesManualProse(bool manual) { await Sync(); string member = Fragment(C_MEMBER); - if (manual) File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal)); + if (manual) + { + File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal)); + } string before = File.ReadAllText(member); Bind(member: false); await Sync(); @@ -425,7 +486,10 @@ public async Task DeclaredScopeIsSeparateFromCompilationSurfaceAndHasOneCanonica { JsonNode projected = host.DeepClone(); projected["model"] = surface; - foreach (JsonNode? symbol in projected["projects"]![0]!["symbols"]!.AsArray()) symbol!["scriptingScope"] = scope; + foreach (JsonNode? symbol in projected["projects"]![0]!["symbols"]!.AsArray()) + { + symbol!["scriptingScope"] = scope; + } string text = projected.ToJsonString(); string file = "reference/api/" + surface + ".json"; Write(file, text); @@ -445,7 +509,9 @@ public async Task DeclaredScopeIsSeparateFromCompilationSurfaceAndHasOneCanonica DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(); - DocumentationPageInfo script = Assert.Single(catalog.pages.Where(page => page.kind == "api" && page.scope == scope && page.symbols.ContainsKey(C_MEMBER))); + DocumentationPageInfo script = Assert.Single( + catalog.pages.Where(page => page.kind == "api" && page.scope == scope && page.symbols.ContainsKey(C_MEMBER)) + ); Assert.Contains("scripting/" + scope.ToLowerInvariant(), script.path); string scopeDirectory = "content/en/api/scripting/" + scope.ToLowerInvariant(); DocumentationPageInfo scopePage = catalog.pages.Single(page => page.path == scopeDirectory + "/index.md"); @@ -453,18 +519,24 @@ public async Task DeclaredScopeIsSeparateFromCompilationSurfaceAndHasOneCanonica DocumentationPageInfo projectPage = catalog.pages.Single(page => page.path == scopeDirectory + "/_projects/probe/index.md"); Assert.Contains("## Types", projectPage.markdown); Assert.Contains("| [Value]", projectPage.markdown); - DocumentationPageInfo typePage = Assert.Single(catalog.pages.Where(page => page.kind == "api" && page.scope == scope && page.symbols.ContainsKey(C_TYPE))); + DocumentationPageInfo typePage = Assert.Single( + catalog.pages.Where(page => page.kind == "api" && page.scope == scope && page.symbols.ContainsKey(C_TYPE)) + ); string typeLink = Path.GetRelativePath(Path.GetDirectoryName(projectPage.path)!, typePage.path).Replace('\\', '/'); Assert.Contains("](" + typeLink + ")", projectPage.markdown); Assert.DoesNotContain("/_projects/", script.path); foreach (string surface in new[] { "runtime-script", "editor-script" }) { - DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe", surface, scope: scope))).hits); + DocumentationHit hit = Assert.Single( + (await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe", surface, scope: scope))).hits + ); Assert.Equal(script.id, hit.pageId); Assert.Equal(scope, hit.scope); Assert.Equal(new[] { "editor-script", "runtime-script" }, hit.surfaces); } - Assert.Empty((await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe", scope: scope == "Editor" ? "Runtime" : "Editor"))).hits); + Assert.Empty( + (await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe", scope: scope == "Editor" ? "Runtime" : "Editor"))).hits + ); } [Fact] @@ -473,13 +545,24 @@ public async Task WebsiteCatalogAndSymbolReadsShareComposedDeclarationsAndManual await Sync(); string member = Fragment(C_MEMBER); string manual = File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nRead the count only after publication.\n"; + + "\nRead the count only after publication.\n"; File.WriteAllText(member, manual); Bind(description: "Updated XML.", countType: "long"); await Sync(); - Write("content/en/manual/ownership.md", "---\nuid: manual.ownership\ntitle: Ownership and retirement\nkind: explanation\n---\n\n# Ownership and retirement\n\n## Release\n\nKeep the owner alive until all borrows end.\n"); + Write( + "content/en/manual/ownership.md", + "---\nuid: manual.ownership\ntitle: Ownership and retirement\nkind: explanation\n---\n\n# Ownership and retirement\n\n## Release\n\nKeep the owner alive until all borrows end.\n" + ); string typePath = Fragment(C_TYPE); - File.WriteAllText(typePath, File.ReadAllText(typePath).Replace("contracts: []", "contracts: [manual.ownership#release]\nexampleMode: host\nexampleProjects: [Inno.Probe]", StringComparison.Ordinal)); + File.WriteAllText( + typePath, + File.ReadAllText(typePath) + .Replace( + "contracts: []", + "contracts: [manual.ownership#release]\nexampleMode: host\nexampleProjects: [Inno.Probe]", + StringComparison.Ordinal + ) + ); string cache = Path.Combine(m_root, "artifacts", "query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); @@ -526,12 +609,17 @@ public async Task AllTargetDeclarationsRemainFactsWhileAuthoredExamplesRemainExe Write("reference/engine.lock.json", binding.ToJsonString()); await Sync(); string member = Fragment(C_MEMBER); - File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\n```csharp\nvar count = value.count;\n```\n"); + File.WriteAllText( + member, + File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) + + "\n```csharp\nvar count = value.count;\n```\n" + ); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api" && page.symbols.ContainsKey(C_MEMBER))); + DocumentationPageInfo page = Assert.Single( + (await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api" && page.symbols.ContainsKey(C_MEMBER)) + ); Assert.Equal(2, page.codeBlocks.Count(block => block.declarationSymbols.Count != 0)); Assert.Equal("var count = value.count;", Assert.Single(page.codeBlocks.Where(block => block.declarationSymbols.Count == 0)).text); Assert.Contains(C_VARIANT, page.symbols[C_MEMBER].code); @@ -541,8 +629,10 @@ public async Task AllTargetDeclarationsRemainFactsWhileAuthoredExamplesRemainExe [InlineData("xml", true)] [InlineData("Ada Example", false)] [InlineData("", true)] - public async Task EditorialNoticeFollowsOwnershipAndSourceLinkEndsThePage(string source, bool notice) - { + public async Task EditorialNoticeFollowsOwnershipAndSourceLinkEndsThePage( + string source, + bool notice + ) { await Sync(); string member = Fragment(C_MEMBER); string original = File.ReadAllText(member); @@ -550,9 +640,19 @@ public async Task EditorialNoticeFollowsOwnershipAndSourceLinkEndsThePage(string string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_MEMBER))); + DocumentationPageInfo page = Assert.Single( + (await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_MEMBER)) + ); Assert.Equal(notice, page.markdown.Contains("> [!SYNCED]", StringComparison.Ordinal)); - if (notice) Assert.True(page.markdown.IndexOf("> [!SYNCED]", StringComparison.Ordinal) < page.markdown.IndexOf("## Required contracts", StringComparison.Ordinal)); + if (notice) + { + Assert.True( + page.markdown.IndexOf("> [!SYNCED]", StringComparison.Ordinal) < page.markdown.IndexOf( + "## Required contracts", + StringComparison.Ordinal + ) + ); + } Assert.DoesNotContain("Available in:", page.markdown); Assert.DoesNotContain("XML-synced", page.markdown); Assert.DoesNotContain("Edit this explanation", page.markdown); @@ -596,8 +696,12 @@ public async Task ElementsAreIndependentPagesWithNestedContainmentAndOverloadLin Assert.Contains(pages.Single(page => page.symbols.ContainsKey(C_DEEP)).id, field.contracts); Assert.DoesNotContain("_members", field.path); - void Add(string id, string kind, string signature, string parent) - { + void Add( + string id, + string kind, + string signature, + string parent + ) { JsonNode symbol = symbols[0]!.DeepClone(); symbol["id"] = id; symbol["kind"] = kind; symbol["signature"] = signature; symbol["signatureHash"] = Hash(signature); symbol["containingType"] = parent; @@ -613,16 +717,23 @@ public async Task MovingLegacyMembersRepairsIncomingAnchorsAndManualRelativeLink string legacy = Path.Combine(Path.GetDirectoryName(current)!, "_members/count.md"); Directory.CreateDirectory(Path.GetDirectoryName(legacy)!); string text = File.ReadAllText(current).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nKeep the original explanation. [Owner](../index.md).\n"; + + "\nKeep the original explanation. [Owner](../index.md).\n"; File.WriteAllText(legacy, text); File.Delete(current); string registryPath = Path.Combine(m_root, "reference/api/content.json"); JsonNode registry = JsonNode.Parse(File.ReadAllText(registryPath))!; - registry["entries"]!.AsArray().Single(entry => entry!["symbol"]!.GetValue().EndsWith(C_MEMBER, StringComparison.Ordinal))!["path"] + registry["entries"]! + .AsArray() + .Single(entry => entry!["symbol"]!.GetValue().EndsWith(C_MEMBER, StringComparison.Ordinal))!["path"] = Path.GetRelativePath(m_root, legacy).Replace('\\', '/'); File.WriteAllText(registryPath, registry.ToJsonString()); - Write("content/en/manual/count.md", "---\nuid: manual.count\ntitle: Count\nkind: how-to\n---\n\n# Count\n\n" - + "[Old member](../api/engine/probe/value/_members/count.md) and [exact member](../api/engine/probe/value/index.md#api-" + Hash(C_MEMBER)[..16] + ").\n"); + Write( + "content/en/manual/count.md", + "---\nuid: manual.count\ntitle: Count\nkind: how-to\n---\n\n# Count\n\n" + + "[Old member](../api/engine/probe/value/_members/count.md) and [exact member](../api/engine/probe/value/index.md#api-" + + Hash(C_MEMBER)[..16] + + ").\n" + ); await Sync(); Assert.False(File.Exists(legacy)); Assert.Contains("Keep the original explanation. [Owner](index.md).", File.ReadAllText(current)); @@ -651,7 +762,12 @@ public async Task XmlRefreshPreservesAuthoredContractAndExampleAssociations() { await Sync(); string type = Fragment(C_TYPE); - string text = File.ReadAllText(type).Replace("contracts: []", "contracts: [manual.ownership#release]\naliases: [persistent value]\nexampleMode: host\nexampleProjects: [Inno.Probe]", StringComparison.Ordinal); + string text = File.ReadAllText(type) + .Replace( + "contracts: []", + "contracts: [manual.ownership#release]\naliases: [persistent value]\nexampleMode: host\nexampleProjects: [Inno.Probe]", + StringComparison.Ordinal + ); File.WriteAllText(type, text); Bind(description: "Fresh XML still needs shared ownership guidance."); await Sync(); @@ -709,7 +825,10 @@ public async Task RuntimeAvailabilityInEditorRequiresTheSameActualProjection(boo ["Inno.ScriptApi.Runtime"] = new string(mismatch && surface == "editor-script" ? 'f' : 'e', 64), ["Inno.ScriptApi.Editor"] = new string('d', 64) }; - foreach (JsonNode? symbol in projected["projects"]![0]!["symbols"]!.AsArray()) symbol!["scriptingScope"] = "Runtime"; + foreach (JsonNode? symbol in projected["projects"]![0]!["symbols"]!.AsArray()) + { + symbol!["scriptingScope"] = "Runtime"; + } if (surface == "editor-script") projected["projects"]![0]!["symbols"] = new JsonArray(); string file = "reference/api/" + surface + ".json"; string text = projected.ToJsonString(); @@ -735,7 +854,9 @@ public async Task RuntimeAvailabilityInEditorRequiresTheSameActualProjection(boo string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe", "editor-script", scope: "Runtime"))).hits); + DocumentationHit hit = Assert.Single( + (await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe", "editor-script", scope: "Runtime"))).hits + ); Assert.Equal(new[] { "editor-script", "runtime-script" }, hit.surfaces); } @@ -745,7 +866,7 @@ public async Task PackageImportPreservesManualProseAndSkipsRevisionOnlyChanges() await Sync(); string member = Fragment(C_MEMBER); string manual = File.ReadAllText(member).Replace("source: xml", "source: Ada Example", StringComparison.Ordinal) - + "\nRead this value only after publication.\n"; + + "\nRead this value only after publication.\n"; File.WriteAllText(member, manual); Bind(description: "Updated package XML."); string package = Path.Combine(m_root, "artifacts/api-package.json"); @@ -759,7 +880,9 @@ public async Task PackageImportPreservesManualProseAndSkipsRevisionOnlyChanges() JsonNode next = JsonNode.Parse(File.ReadAllText(package))!; next["revision"] = new string('c', 40); JsonNode bindingFile = next["files"]!.AsArray().Single(file => file!["path"]!.GetValue() == "reference/engine.lock.json")!; - string revised = bindingFile["text"]!.GetValue().Replace(new string('a', 40), new string('c', 40), StringComparison.Ordinal); + string revised = bindingFile["text"]! + .GetValue() + .Replace(new string('a', 40), new string('c', 40), StringComparison.Ordinal); bindingFile["text"] = revised; bindingFile["sha256"] = Hash(revised); next["toolingRevision"] = new string('c', 40); @@ -783,13 +906,18 @@ public async Task InvalidPackagesCannotModifyTheCheckout(string corruption) JsonNode packet = JsonNode.Parse(File.ReadAllText(package))!; JsonArray files = packet["files"]!.AsArray(); if (corruption == "tampered") files[0]!["text"] = "{}"; - if (corruption == "extra-file") files.Add(new JsonObject { ["path"] = "content/en/manual/task.md", ["text"] = "replace", ["sha256"] = Hash("replace") }); + if (corruption == "extra-file") + { + files.Add(new JsonObject { ["path"] = "content/en/manual/task.md", ["text"] = "replace", ["sha256"] = Hash("replace") }); + } if (corruption == "escape") files[0]!["path"] = "reference/api/../../AGENTS.md"; if (corruption == "mixed-revisions") packet["revision"] = new string('d', 40); File.WriteAllText(package, packet.ToJsonString()); byte[] binding = File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json")); string before = File.ReadAllText(Fragment(C_TYPE)); - await Assert.ThrowsAsync(() => DocumentationCommand.ExecuteAsync(["api-import", "--docs-root", m_root, "--package", package])); + await Assert.ThrowsAsync( + () => DocumentationCommand.ExecuteAsync(["api-import", "--docs-root", m_root, "--package", package]) + ); Assert.Equal(binding, File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json"))); Assert.Equal(before, File.ReadAllText(Fragment(C_TYPE))); } @@ -804,10 +932,15 @@ public async Task ImportWaitsForTheSharedWriterBeforeChangingFactsAndCancellatio Bind(); byte[] binding = File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json")); byte[] facts = File.ReadAllBytes(Path.Combine(m_root, "reference/api/probe.json")); - using (FileLease writer = await FileLease.AcquireAsync(Path.Combine(m_root, "artifacts/api-sync/writer.lock"), Timeout.InfiniteTimeSpan)) - { + using (FileLease writer = await FileLease.AcquireAsync( + Path.Combine(m_root, "artifacts/api-sync/writer.lock"), + Timeout.InfiniteTimeSpan + )) { using var cancellation = new CancellationTokenSource(); - Task import = DocumentationCommand.ExecuteAsync(["api-import", "--docs-root", m_root, "--package", package], cancellation.Token); + Task import = DocumentationCommand.ExecuteAsync( + ["api-import", "--docs-root", m_root, "--package", package], + cancellation.Token + ); Assert.False(import.IsCompleted); Assert.Equal(binding, File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json"))); Assert.Equal(facts, File.ReadAllBytes(Path.Combine(m_root, "reference/api/probe.json"))); @@ -832,7 +965,9 @@ public async Task ImportRestoresFactsWhenAuthoredContentRejectsSynchronization() File.WriteAllText(member, invalid); byte[] binding = File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json")); byte[] facts = File.ReadAllBytes(Path.Combine(m_root, "reference/api/probe.json")); - await Assert.ThrowsAsync(() => DocumentationCommand.ExecuteAsync(["api-import", "--docs-root", m_root, "--package", package])); + await Assert.ThrowsAsync( + () => DocumentationCommand.ExecuteAsync(["api-import", "--docs-root", m_root, "--package", package]) + ); Assert.Equal(binding, File.ReadAllBytes(Path.Combine(m_root, "reference/engine.lock.json"))); Assert.Equal(facts, File.ReadAllBytes(Path.Combine(m_root, "reference/api/probe.json"))); Assert.Equal(invalid, File.ReadAllText(member)); @@ -861,12 +996,21 @@ public async Task XmlSummaryAndSectionsHaveTheSameReadingOrderInMarkdownAndQueri string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE))); + DocumentationPageInfo page = Assert.Single( + (await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE)) + ); Assert.Contains("# Value\n\n> - Owns a value.\n> \n> Release it when finished.", page.markdown); Assert.Contains("> - Owns", page.markdown); - Assert.True(page.markdown.IndexOf("> [!SYNCED]", StringComparison.Ordinal) < page.markdown.IndexOf("# Value", StringComparison.Ordinal)); + Assert.True( + page.markdown.IndexOf("> [!SYNCED]", StringComparison.Ordinal) < page.markdown.IndexOf("# Value", StringComparison.Ordinal) + ); Assert.Contains("**API:** engine \n**Inherits:** `System.Object` \n**Project:** `Inno.Probe`", page.markdown); - Assert.True(page.markdown.IndexOf("## Declaration", StringComparison.Ordinal) < page.markdown.IndexOf("## Remarks", StringComparison.Ordinal)); + Assert.True( + page.markdown.IndexOf( + "## Declaration", + StringComparison.Ordinal + ) < page.markdown.IndexOf("## Remarks", StringComparison.Ordinal) + ); Assert.DoesNotContain("#### Remarks", page.markdown); DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new("symbol", C_TYPE, "Inno.Probe"))).hits); Assert.Contains("Owns a value.", hit.text); @@ -880,8 +1024,13 @@ public async Task NamedAuthorAndDescriptionsSurviveSyncAndReachTablesAndQueries( await Sync(); string typePath = Fragment(C_TYPE); string memberPath = Fragment(C_MEMBER); - File.WriteAllText(typePath, File.ReadAllText(typePath).Replace("description: null", "description: [Custom type introduction, Second type paragraph]", StringComparison.Ordinal)); - string original = File.ReadAllText(memberPath).Replace("source: xml", "source: Ada Lovelace", StringComparison.Ordinal) + File.WriteAllText( + typePath, + File.ReadAllText(typePath) + .Replace("description: null", "description: [Custom type introduction, Second type paragraph]", StringComparison.Ordinal) + ); + string original = File.ReadAllText(memberPath) + .Replace("source: xml", "source: Ada Lovelace", StringComparison.Ordinal) .Replace("description: null", "description: [Custom member introduction, Second member paragraph]", StringComparison.Ordinal); string body = "\n\n## Remarks\n\nKeep this author explanation byte for byte.\n"; File.WriteAllText(memberPath, original[..(original.Length - Body(original).Length)] + body); @@ -891,7 +1040,9 @@ public async Task NamedAuthorAndDescriptionsSurviveSyncAndReachTablesAndQueries( Assert.Contains("source: Ada Lovelace", saved); Assert.Contains("outdatedFor:", saved); Assert.Equal(body, Body(saved)); - Assert.True(saved.IndexOf("contracts:", StringComparison.Ordinal) < saved.IndexOf("# Authoring metadata", StringComparison.Ordinal)); + Assert.True( + saved.IndexOf("contracts:", StringComparison.Ordinal) < saved.IndexOf("# Authoring metadata", StringComparison.Ordinal) + ); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); @@ -902,7 +1053,10 @@ public async Task NamedAuthorAndDescriptionsSurviveSyncAndReachTablesAndQueries( Assert.Contains("Custom member introduction

Second member paragraph", type.markdown); Assert.Contains("> - Second member paragraph", member.markdown); Assert.Contains("public long", member.markdown); - Assert.Contains(catalog.pages, page => page.markdown.Contains("Custom type introduction

Second type paragraph", StringComparison.Ordinal)); + Assert.Contains( + catalog.pages, + page => page.markdown.Contains("Custom type introduction

Second type paragraph", StringComparison.Ordinal) + ); DocumentationHit hit = Assert.Single((await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe"))).hits); Assert.Contains("Custom member introduction", hit.text); Assert.DoesNotContain("Changed XML.", member.markdown); @@ -933,8 +1087,13 @@ public async Task PartialSummariesRemainSeparateQuotedItemsWithoutSplittingTheir string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE))); - Assert.Contains("> - First declaration.\n> \n> Still the first summary.\n> \n> - Second declaration with `Value`.", page.markdown); + DocumentationPageInfo page = Assert.Single( + (await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE)) + ); + Assert.Contains( + "> - First declaration.\n> \n> Still the first summary.\n> \n> - Second declaration with `Value`.", + page.markdown + ); string html = Markdig.Markdown.ToHtml(page.markdown); string summaryHtml = html[html.IndexOf("
\n
    ", StringComparison.Ordinal)..]; summaryHtml = summaryHtml[..summaryHtml.IndexOf("
", StringComparison.Ordinal)]; @@ -962,9 +1121,13 @@ public async Task ManualBodySectionsRemainEditableWhileSummaryFollowsSource() string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE))); + DocumentationPageInfo page = Assert.Single( + (await snapshot.ExportCatalogAsync()).pages.Where(page => page.symbols.ContainsKey(C_TYPE)) + ); Assert.Contains("# Value\n\n> - Updated source summary.", page.markdown); - Assert.True(page.markdown.IndexOf("> [!OUTDATED]", StringComparison.Ordinal) < page.markdown.IndexOf("# Value", StringComparison.Ordinal)); + Assert.True( + page.markdown.IndexOf("> [!OUTDATED]", StringComparison.Ordinal) < page.markdown.IndexOf("# Value", StringComparison.Ordinal) + ); Assert.Contains("## Remarks\n\nMy independently maintained ownership explanation.", page.markdown); Assert.DoesNotContain("#### Remarks", page.markdown); Assert.DoesNotContain("Changed source remarks.", page.markdown); @@ -1084,20 +1247,32 @@ private void SetTypes(params (string id, string signature)[] types) } private void WriteGuideRegistry() - => Write("reference/projects/content.json", JsonSerializer.Serialize(new { schema = "inno-project-guides/1", entries = Array.Empty() })); + => Write( + "reference/projects/content.json", + JsonSerializer.Serialize(new { schema = "inno-project-guides/1", entries = Array.Empty() }) + ); private string[] GuideRegistry() { using JsonDocument registry = JsonDocument.Parse(File.ReadAllBytes(Path.Combine(m_root, "reference/projects/content.json"))); - return registry.RootElement.GetProperty("entries").EnumerateArray().Select(entry => entry.GetProperty("path").GetString()!).ToArray(); + return registry.RootElement + .GetProperty("entries") + .EnumerateArray() + .Select(entry => entry.GetProperty("path").GetString()!) + .ToArray(); } private void SetProjects(params (string name, string path)[] projects) { - string inventory = JsonSerializer.Serialize(projects.Select(project => new - { - project.name, project.path, surfaces = new[] { "source-clr" }, isTest = project.path.StartsWith("tests/", StringComparison.Ordinal) - })); + string inventory = JsonSerializer.Serialize( + projects.Select(project => new + { + project.name, + project.path, + surfaces = new[] { "source-clr" }, + isTest = project.path.StartsWith("tests/", StringComparison.Ordinal) + }) + ); Write("reference/projects/catalog.json", inventory); JsonNode binding = JsonNode.Parse(File.ReadAllText(Path.Combine(m_root, "reference/engine.lock.json")))!; binding["projectManifestIdentity"] = Hash(inventory); @@ -1115,43 +1290,93 @@ private void SetTypeDocumentation(string xml) Write("reference/engine.lock.json", binding.ToJsonString()); } - private Task Sync(CancellationToken cancellation) => DocumentationCommand.ExecuteAsync(["api-sync", "--docs-root", m_root], cancellation); + private Task Sync(CancellationToken cancellation) + => DocumentationCommand.ExecuteAsync(["api-sync", "--docs-root", m_root], cancellation); private string Fragment(string id) { using JsonDocument registry = JsonDocument.Parse(File.ReadAllBytes(Path.Combine(m_root, "reference/api/content.json"))); - string path = registry.RootElement.GetProperty("entries").EnumerateArray() - .Single(entry => entry.GetProperty("symbol").GetString() == "engine:Inno.Probe:" + id).GetProperty("path").GetString()!; + string path = registry.RootElement.GetProperty("entries") + .EnumerateArray() + .Single(entry => entry.GetProperty("symbol").GetString() == "engine:Inno.Probe:" + id) + .GetProperty("path") + .GetString()!; return Path.Combine(m_root, path); } - private void Bind(bool member = true, string description = "The value contract.", string countType = "int") - { - string inventory = JsonSerializer.Serialize(new[] { new { name = "Inno.Probe", path = "src/Inno.Probe.csproj", surfaces = new[] { "source-clr" }, isTest = false } }); + private void Bind( + bool member = true, + string description = "The value contract.", + string countType = "int" + ) { + string inventory = JsonSerializer.Serialize( + new[] { new { name = "Inno.Probe", path = "src/Inno.Probe.csproj", surfaces = new[] { "source-clr" }, isTest = false } } + ); Write("reference/projects/catalog.json", inventory); - object Symbol(string id, string kind, string signature, string? parent) => new + object Symbol( + string id, + string kind, + string signature, + string? parent + ) => new { - project = "Inno.Probe", id, kind, signature, signatureHash = Hash(signature), source = "src/Value.cs", line = 1, - documentation = "" + description + "", containingType = parent, - baseType = (string?)null, interfaces = Array.Empty() + project = "Inno.Probe", + id, + kind, + signature, + signatureHash = Hash(signature), + source = "src/Value.cs", + line = 1, + documentation = "" + description + "", + containingType = parent, + baseType = (string?)null, + interfaces = Array.Empty() }; object[] symbols = member - ? [Symbol(C_TYPE, "NamedType", "public class Inno.Probe.Value", null), Symbol(C_MEMBER, "Property", "public " + countType + " Inno.Probe.Value.count { get; }", C_TYPE)] - : [Symbol(C_TYPE, "NamedType", "public class Inno.Probe.Value", null)]; - string facts = JsonSerializer.Serialize(new { model = "source-clr", configuration = "Debug", target = (string?)null, - projects = new[] { new { name = "Inno.Probe", project = "src/Inno.Probe.csproj", symbols } } }); - Write("reference/api/probe.json", facts); - Write("reference/engine.lock.json", JsonSerializer.Serialize(new + ? [ + Symbol(C_TYPE, "NamedType", "public class Inno.Probe.Value", null), + Symbol(C_MEMBER, "Property", "public " + countType + " Inno.Probe.Value.count { get; }", C_TYPE) + ] + : [Symbol(C_TYPE, "NamedType", "public class Inno.Probe.Value", null)]; + string facts = JsonSerializer.Serialize(new { - repository = "https://github.com/Wolfiora/InnoEngine", revision = new string('a', 40), sourceTree = new string('b', 40), - toolingRevision = new string('a', 40), projectManifest = "reference/projects/catalog.json", projectManifestIdentity = Hash(inventory), - apiManifests = new[] { new { path = "reference/api/probe.json", sha256 = Hash(facts), model = "source-clr", configuration = "Debug", - sourceRevision = new string('a', 40), sourceTree = new string('b', 40), target = (string?)null } } - })); + model = "source-clr", + configuration = "Debug", + target = (string?)null, + projects = new[] { new { name = "Inno.Probe", project = "src/Inno.Probe.csproj", symbols } } + }); + Write("reference/api/probe.json", facts); + Write( + "reference/engine.lock.json", + JsonSerializer.Serialize(new + { + repository = "https://github.com/Wolfiora/InnoEngine", + revision = new string('a', 40), + sourceTree = new string('b', 40), + toolingRevision = new string('a', 40), + projectManifest = "reference/projects/catalog.json", + projectManifestIdentity = Hash(inventory), + apiManifests = new[] + { + new + { + path = "reference/api/probe.json", + sha256 = Hash(facts), + model = "source-clr", + configuration = "Debug", + sourceRevision = new string('a', 40), + sourceTree = new string('b', 40), + target = (string?)null + } + } + }) + ); } - private void Write(string relative, string text) - { + private void Write( + string relative, + string text + ) { string path = Path.Combine(m_root, relative); Directory.CreateDirectory(Path.GetDirectoryName(path)!); File.WriteAllText(path, text); diff --git a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationEvidenceTests.cs b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationEvidenceTests.cs index 3db468a71..81789437b 100644 --- a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationEvidenceTests.cs +++ b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationEvidenceTests.cs @@ -7,14 +7,19 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Tooling.Documentation.Tests; public sealed class DocumentationEvidenceTests : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoDocumentationEvidence", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoDocumentationEvidence", + Guid.NewGuid().ToString("N") + ); + private string cache => Path.Combine(m_root, "cache"); private string source => Path.Combine(m_root, "source"); @@ -38,7 +43,9 @@ public async Task TrustedSourceEvidenceIsIndependentFromContentFreshnessAndQuery byte[] original = File.ReadAllBytes(manifest); File.WriteAllText(Path.Combine(source, "content/en/probe.md"), "Mutable authoring changes are not read by a prepared session."); File.WriteAllText(Path.Combine(m_root, "certificate.json"), "The imported immutable value does not retain a file dependency."); - DocumentationResult[] results = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => verified.QueryAsync(new("search", "ownership")))); + DocumentationResult[] results = await Task.WhenAll( + Enumerable.Range(0, 8).Select(_ => verified.QueryAsync(new("search", "ownership"))) + ); Assert.All(results, result => { Assert.Equal("Verified", result.sourceApiStatus); @@ -51,7 +58,11 @@ public async Task TrustedSourceEvidenceIsIndependentFromContentFreshnessAndQuery using DocumentationSnapshot prose = await DocumentationStore.OpenAsync(cache, sourceEvidence: evidence); Assert.NotEqual(raw.identity, prose.identity); Assert.Equal("Verified", (await prose.ExportCatalogAsync()).sourceApiStatus); - using DocumentationSnapshot mismatch = await DocumentationStore.OpenAsync(cache, expectedSourceTree: new string('c', 40), sourceEvidence: evidence); + using DocumentationSnapshot mismatch = await DocumentationStore.OpenAsync( + cache, + expectedSourceTree: new string('c', 40), + sourceEvidence: evidence + ); Assert.Equal("Mismatched", (await mismatch.QueryAsync(new("status"))).status); Assert.Equal("Unverified", (await mismatch.QueryAsync(new("status"))).sourceApiStatus); } @@ -69,17 +80,32 @@ public async Task TrustedSourceEvidenceIsIndependentFromContentFreshnessAndQuery public async Task MatchingDigestCannotCertifyDifferentSourceOrReferenceCoverage(string change) { JsonNode certificate = await PrepareAsync(); - if (change == "repository") certificate[change] = "https://example.invalid/other"; - else if (change == "sourceTree") certificate[change] = new string('c', 40); - else if (change == "projectManifestIdentity") certificate[change] = new string('c', 64); + if (change == "repository") + { + certificate[change] = "https://example.invalid/other"; + } + else if (change == "sourceTree") + { + certificate[change] = new string('c', 40); + } + else if (change == "projectManifestIdentity") + { + certificate[change] = new string('c', 64); + } else if (change == "extra-reference") { JsonNode extra = certificate["references"]![0]!.DeepClone(); extra["path"] = "reference/api/extra.json"; certificate["references"]!.AsArray().Add(extra); } - else if (change == "projects") certificate["references"]![0]![change] = new JsonArray("Other"); - else certificate["references"]![0]![change] = change == "identity" ? new string('c', 64) : "different"; + else if (change == "projects") + { + certificate["references"]![0]![change] = new JsonArray("Other"); + } + else + { + certificate["references"]![0]![change] = change == "identity" ? new string('c', 64) : "different"; + } DocumentationEvidence evidence = await ReadAsync(certificate); await Assert.ThrowsAsync(() => DocumentationStore.OpenAsync(cache, sourceEvidence: evidence)); using DocumentationSnapshot retained = await DocumentationStore.OpenAsync(cache); @@ -120,9 +146,23 @@ public async Task IncompleteOrAmbiguousCertificatesAreRejected(string change) case "escaping-source-file": certificate["sourceFiles"]![0]!["path"] = "../secret"; break; case "missing-input-group": case "different-input-group": - certificate["examples"] = JsonSerializer.SerializeToNode(new[] { new { contexts = new[] { - new { platform = "foreign", configuration = "Debug", target = (string?)null, - reportIdentity = new string('d', 64), inputGroup = change == "missing-input-group" ? 9 : 0 } } } }); + certificate["examples"] = JsonSerializer.SerializeToNode(new[] + { + new + { + contexts = new[] + { + new + { + platform = "foreign", + configuration = "Debug", + target = (string?)null, + reportIdentity = new string('d', 64), + inputGroup = change == "missing-input-group" ? 9 : 0 + } + } + } + }); break; } await Assert.ThrowsAsync(() => ReadAsync(certificate)); @@ -138,10 +178,21 @@ public async Task ImportRejectsTamperingCancellationAndImplicitCliTrust() await Assert.ThrowsAsync(() => DocumentationEvidence.ReadAsync(file, evidence.identity)); using var canceled = new CancellationTokenSource(); canceled.Cancel(); - await Assert.ThrowsAnyAsync(() => DocumentationEvidence.ReadAsync(file, Hash(File.ReadAllBytes(file)), canceled.Token)); - await Assert.ThrowsAsync(() => DocumentationCommand.ExecuteAsync(["status", "--cache-root", cache, "--evidence-file", file])); - await Assert.ThrowsAsync(() => DocumentationCommand.ExecuteAsync(["index", "--docs-root", source, - "--evidence-file", file, "--evidence-sha256", evidence.identity])); + await Assert.ThrowsAnyAsync( + () => DocumentationEvidence.ReadAsync(file, Hash(File.ReadAllBytes(file)), canceled.Token) + ); + await Assert.ThrowsAsync( + () => DocumentationCommand.ExecuteAsync(["status", "--cache-root", cache, "--evidence-file", file]) + ); + await Assert.ThrowsAsync(() => DocumentationCommand.ExecuteAsync([ + "index", + "--docs-root", + source, + "--evidence-file", + file, + "--evidence-sha256", + evidence.identity + ])); } [Theory] @@ -164,31 +215,82 @@ public async Task ScriptSurfaceRequiresActualProjectionAndMatchingExecutionInput private async Task PrepareAsync() { - byte[] projects = JsonSerializer.SerializeToUtf8Bytes(new[] { new { name = "Probe", path = "src/Probe.csproj", surfaces = new[] { "source-clr" } } }); - byte[] api = JsonSerializer.SerializeToUtf8Bytes(new { model = "source-clr", configuration = "Debug", target = (string?)null, - projects = new[] { new { name = "Probe", project = "src/Probe.csproj", symbols = Array.Empty() } } }); + byte[] projects = JsonSerializer.SerializeToUtf8Bytes( + new[] { new { name = "Probe", path = "src/Probe.csproj", surfaces = new[] { "source-clr" } } } + ); + byte[] api = JsonSerializer.SerializeToUtf8Bytes(new + { + model = "source-clr", + configuration = "Debug", + target = (string?)null, + projects = new[] { new { name = "Probe", project = "src/Probe.csproj", symbols = Array.Empty() } } + }); Write("reference/projects/catalog.json", Encoding.UTF8.GetString(projects)); Write("reference/api/probe.json", Encoding.UTF8.GetString(api)); - Write("reference/engine.lock.json", JsonSerializer.Serialize(new - { - repository = "https://github.com/Wolfiora/InnoEngine", revision = new string('a', 40), sourceTree = new string('b', 40), - toolingRevision = new string('a', 40), projectManifest = "reference/projects/catalog.json", projectManifestIdentity = Hash(projects), - apiManifests = new[] { new { path = "reference/api/probe.json", sha256 = Hash(api), model = "source-clr", configuration = "Debug", - target = (string?)null, sourceRevision = new string('a', 40), sourceTree = new string('b', 40) } } - })); - Write("content/en/probe.md", "---\nuid: probe\nkind: project\nowners: [Probe]\n---\n# Ownership task\n\nThe caller owns the result.\n"); + Write( + "reference/engine.lock.json", + JsonSerializer.Serialize(new + { + repository = "https://github.com/Wolfiora/InnoEngine", + revision = new string('a', 40), + sourceTree = new string('b', 40), + toolingRevision = new string('a', 40), + projectManifest = "reference/projects/catalog.json", + projectManifestIdentity = Hash(projects), + apiManifests = new[] + { + new + { + path = "reference/api/probe.json", + sha256 = Hash(api), + model = "source-clr", + configuration = "Debug", + target = (string?)null, + sourceRevision = new string('a', 40), + sourceTree = new string('b', 40) + } + } + }) + ); + Write( + "content/en/probe.md", + "---\nuid: probe\nkind: project\nowners: [Probe]\n---\n# Ownership task\n\nThe caller owns the result.\n" + ); await DocumentationStore.IndexAsync(m_root, source, cache); return JsonSerializer.SerializeToNode(new { - format = "inno-documentation-source/2", repository = "https://github.com/Wolfiora/InnoEngine", sourceTree = new string('b', 40), + format = "inno-documentation-source/2", + repository = "https://github.com/Wolfiora/InnoEngine", + sourceTree = new string('b', 40), projectManifestIdentity = Hash(projects), sourceFiles = new[] { new { path = "src/Probe.cs", identity = new string('a', 64) } }, sourceSets = new[] { new[] { 0 } }, - inputGroups = new[] { new { platform = "fixture", configuration = "Debug", target = (string?)null, - reportIdentity = new string('d', 64), inputs = new[] { new { sourceSet = 0 } } } }, - inputs = new[] { new { sourceSet = 0 } }, examples = Array.Empty(), scriptReferences = Array.Empty(), - references = new[] { new { path = "reference/api/probe.json", identity = Hash(api), model = "source-clr", configuration = "Debug", - target = (string?)null, projects = new[] { "Probe" } } }, + inputGroups = new[] + { + new + { + platform = "fixture", + configuration = "Debug", + target = (string?)null, + reportIdentity = new string('d', 64), + inputs = new[] { new { sourceSet = 0 } } + } + }, + inputs = new[] { new { sourceSet = 0 } }, + examples = Array.Empty(), + scriptReferences = Array.Empty(), + references = new[] + { + new + { + path = "reference/api/probe.json", + identity = Hash(api), + model = "source-clr", + configuration = "Debug", + target = (string?)null, + projects = new[] { "Probe" } + } + }, producers = new[] { new { origin = "fixture://reconciled-local-producer", receiptIdentity = new string('d', 64) } } })!; } @@ -201,8 +303,10 @@ private Task ReadAsync(JsonNode certificate) return DocumentationEvidence.ReadAsync(file, Hash(bytes)); } - private void Write(string relative, string content) - { + private void Write( + string relative, + string content + ) { string file = Path.Combine(source, relative); Directory.CreateDirectory(Path.GetDirectoryName(file)!); File.WriteAllText(file, content); diff --git a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationSnapshotTests.cs b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationSnapshotTests.cs index 23323c869..77bf5a114 100644 --- a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationSnapshotTests.cs +++ b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationSnapshotTests.cs @@ -8,8 +8,8 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Xunit; +using Inno.Core.IO; namespace Inno.Tooling.Documentation.Tests; @@ -24,16 +24,36 @@ public DocumentationSnapshotTests() { byte[] projects = JsonSerializer.SerializeToUtf8Bytes(new[] { - new { name = "Inno.Probe", path = "src/Inno.Probe.csproj", entry = "probe", surfaces = new[] { "host-runtime", "runtime-script" } } + new + { + name = "Inno.Probe", + path = "src/Inno.Probe.csproj", + entry = "probe", + surfaces = new[] { "host-runtime", "runtime-script" } + } }); Write("reference/projects/catalog.json", Encoding.UTF8.GetString(projects)); - Write("reference/engine.lock.json", JsonSerializer.Serialize(new - { - repository = "https://github.com/Wolfiora/InnoEngine", revision = new string('a', 40), sourceTree = new string('b', 40), - projectManifest = "reference/projects/catalog.json", projectManifestIdentity = Hash(projects), toolingRevision = new string('a', 40) - })); - Write("content/en/probe.md", Page("probe", "Probe", "## Ownership\n\nBorrow the lease; the owner releases it after the final consumer.\n", - "kind: project\nowners: [Inno.Probe]\naliases: [ProbeStyle, 控制台颜色]\n")); + Write( + "reference/engine.lock.json", + JsonSerializer.Serialize(new + { + repository = "https://github.com/Wolfiora/InnoEngine", + revision = new string('a', 40), + sourceTree = new string('b', 40), + projectManifest = "reference/projects/catalog.json", + projectManifestIdentity = Hash(projects), + toolingRevision = new string('a', 40) + }) + ); + Write( + "content/en/probe.md", + Page( + "probe", + "Probe", + "## Ownership\n\nBorrow the lease; the owner releases it after the final consumer.\n", + "kind: project\nowners: [Inno.Probe]\naliases: [ProbeStyle, 控制台颜色]\n" + ) + ); Write("content/en/api.md", Api("probe-api", "host-runtime")); } @@ -41,7 +61,9 @@ public void Dispose() { // All test-owned sessions are disposed before removing this uniquely allocated fixture boundary. if (Directory.Exists(m_root)) + { Directory.Delete(m_root, recursive: true); + } } [Fact] @@ -51,8 +73,9 @@ public async Task RestoredImmutablePayloadsAcquireLocalOwnershipBeforeOpening() string imported = Path.Combine(m_root, "artifacts", "imported"); string manifest = Path.Combine("generations", first.snapshot!, "manifest.json"); foreach (string file in Directory.GetFiles(cache, "page.json", SearchOption.AllDirectories) - .Append(Path.Combine(cache, "current.json")).Append(Path.Combine(cache, manifest))) - { + .Append(Path.Combine(cache, "current.json")) + .Append(Path.Combine(cache, manifest)) + ) { string destination = Path.Combine(imported, Path.GetRelativePath(cache, file)); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(file, destination); @@ -88,8 +111,15 @@ public async Task PlatformInventoryDoesNotRequireOrExposeImplementationGuides() DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(); Assert.Contains("Inno.Probe", catalog.projects.Keys); Assert.DoesNotContain("Inno.Platform.Probe", catalog.projects.Keys); - Write("content/en/platform.md", Page("platform", "Platform implementation", "Platform-specific internals.", - "kind: project\nowners: [Inno.Platform.Probe]\n")); + Write( + "content/en/platform.md", + Page( + "platform", + "Platform implementation", + "Platform-specific internals.", + "kind: project\nowners: [Inno.Platform.Probe]\n" + ) + ); await Assert.ThrowsAsync(IndexAsync); } @@ -134,7 +164,9 @@ public async Task ReferencePayloadsRemainReadableAfterCheckoutChangesAndShareImm Assert.All(readers, bytes => Assert.Equal(firstBytes, bytes)); Assert.Equal(before.OrderBy(static pair => pair.Key), Files().OrderBy(static pair => pair.Key)); await Assert.ThrowsAsync(() => snapshot.ReadReferenceAsync("../escape.json")); - await Assert.ThrowsAnyAsync(() => snapshot.ReadReferenceAsync(C_REFERENCE, new CancellationToken(true))); + await Assert.ThrowsAnyAsync( + () => snapshot.ReadReferenceAsync(C_REFERENCE, new CancellationToken(true)) + ); } [Fact] @@ -146,7 +178,10 @@ public async Task CorruptOrMismatchedReferencesCannotBecomePublishedFacts() byte[] pointer = File.ReadAllBytes(Path.Combine(cache, "current.json")); string input = Path.Combine(source, C_REFERENCE); DateTime timestamp = File.GetLastWriteTimeUtc(input); - File.WriteAllBytes(input, Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(expected).Replace("initial", "changed", StringComparison.Ordinal))); + File.WriteAllBytes( + input, + Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(expected).Replace("initial", "changed", StringComparison.Ordinal)) + ); File.SetLastWriteTimeUtc(input, timestamp); await Assert.ThrowsAsync(IndexAsync); Assert.Equal(pointer, File.ReadAllBytes(Path.Combine(cache, "current.json"))); @@ -173,14 +208,27 @@ public async Task InvalidReferenceBindingsFailBeforePublication(string changed) BindReference("reference/api/probe.json", "initial"); JsonNode binding = JsonNode.Parse(File.ReadAllText(Path.Combine(source, "reference/engine.lock.json")))!; JsonArray references = binding["apiManifests"]!.AsArray(); - if (changed == "duplicate") references.Add(references[0]!.DeepClone()); - else if (changed == "escape") references[0]!["path"] = "../outside.json"; - else references[0]![changed] = "invalid"; + if (changed == "duplicate") + { + references.Add(references[0]!.DeepClone()); + } + else if (changed == "escape") + { + references[0]!["path"] = "../outside.json"; + } + else + { + references[0]![changed] = "invalid"; + } Write("reference/engine.lock.json", binding.ToJsonString()); if (changed == "escape") + { await Assert.ThrowsAnyAsync(IndexAsync); + } else + { await Assert.ThrowsAsync(IndexAsync); + } Assert.False(File.Exists(Path.Combine(cache, "current.json"))); } @@ -209,11 +257,17 @@ public async Task CatalogUsesThePreparedSnapshotAndReportsMissingProjectCoverage public async Task CatalogPreservesSectionDeclarationsWithoutTreatingExamplesAsCertification() { const string C_DECLARATION = "public string? Read(string key = \"default\");"; - Write("content/en/api.md", Page("probe-api", "Probe API", - "## Read\n\n\n\n```csharp\n" + C_DECLARATION + "\n```\n\nThe caller retains ownership.\n" - + "\n## Other task\n\n```csharp\nUnrelatedExample();\n```\n", - "kind: api\nowners: [Inno.Probe]\napiSurface: host-runtime\ncontracts: [probe#ownership]\n")); + Write( + "content/en/api.md", + Page( + "probe-api", + "Probe API", + "## Read\n\n\n\n```csharp\n" + C_DECLARATION + "\n```\n\nThe caller retains ownership.\n" + + "\n## Other task\n\n```csharp\nUnrelatedExample();\n```\n", + "kind: api\nowners: [Inno.Probe]\napiSurface: host-runtime\ncontracts: [probe#ownership]\n" + ) + ); await IndexAsync(); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache); DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(); @@ -253,12 +307,18 @@ public async Task ExecutableOrPresentationHtmlCannotReplaceThePublishedSnapshot( [Fact] public async Task AMemberNameDoesNotPolluteEveryOtherSectionOnItsTypePage() { - Write("content/en/api.md", Page("probe-api", "Probe API", - "## ReadOnly\n\n\n\n```csharp\npublic void ReadOnly();\n```\n\nRead the current value.\n" - + "\n## WriteOnly\n\n\n\n```csharp\npublic void WriteOnly();\n```\n\nWrite a replacement value.\n", - "kind: api\nowners: [Inno.Probe]\napiSurface: host-runtime\n")); + Write( + "content/en/api.md", + Page( + "probe-api", + "Probe API", + "## ReadOnly\n\n\n\n```csharp\npublic void ReadOnly();\n```\n\nRead the current value.\n" + + "\n## WriteOnly\n\n\n\n```csharp\npublic void WriteOnly();\n```\n\nWrite a replacement value.\n", + "kind: api\nowners: [Inno.Probe]\napiSurface: host-runtime\n" + ) + ); await IndexAsync(); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache); DocumentationResult result = await snapshot.QueryAsync(new("search", "WriteOnly")); @@ -275,8 +335,7 @@ public async Task AMemberNameDoesNotPolluteEveryOtherSectionOnItsTypePage() public async Task BrokenOrUnsafeLinksCannotPublishANewGeneration( string link, Type failureType - ) - { + ) { DocumentationResult original = await IndexAsync(); Write("content/en/broken.md", Page("broken", "Broken", link)); Exception? failure = await Record.ExceptionAsync(() => IndexAsync()); @@ -289,7 +348,16 @@ Type failureType [Fact] public async Task ReferenceLinksAndEncodedHeadingTargetsUseCanonicalParsing() { - Write("content/en/links.md", Page("links", "Links", "[Ownership][target]\n\n[target]: probe.md#ownership\n\n[Self](#links)\n\n[API](api.md#api-" + Hash(Encoding.UTF8.GetBytes(C_SYMBOL))[..16] + ")\n")); + Write( + "content/en/links.md", + Page( + "links", + "Links", + "[Ownership][target]\n\n[target]: probe.md#ownership\n\n[Self](#links)\n\n[API](api.md#api-" + + Hash(Encoding.UTF8.GetBytes(C_SYMBOL))[..16] + + ")\n" + ) + ); await IndexAsync(); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache); DocumentationPageInfo page = (await snapshot.ExportCatalogAsync()).pages.Single(page => page.id == "links"); @@ -355,7 +423,9 @@ string expectedWork JsonNode manifest = JsonNode.Parse(File.ReadAllText(manifestPath))!; manifest["schema"] = "prior-query-implementation"; if (changeParser) + { manifest["parserSchema"] = "prior-parser-implementation"; + } manifest["identity"] = ""; string previousIdentity = Hash(JsonSerializer.SerializeToUtf8Bytes(manifest)); manifest["identity"] = previousIdentity; @@ -372,7 +442,9 @@ string expectedWork Assert.Contains(expectedWork, refreshed.message); Assert.Equal(initial.snapshot, refreshed.snapshot); if (!changeParser) + { Assert.All(payloads, path => Assert.Equal(timestamps[path], File.GetLastWriteTimeUtc(path))); + } using DocumentationSnapshot current = await DocumentationStore.OpenAsync(cache); Assert.Equal("Found", (await current.QueryAsync(new("read", "probe"))).status); } @@ -422,9 +494,13 @@ public async Task CorruptionFailsReadsAndExplicitRefreshRepairsOnlyTheOwnedPaylo DocumentationResult initial = await IndexAsync(); string[] payloads = Directory.GetFiles(Path.Combine(cache, "pages"), "page.json", SearchOption.AllDirectories); foreach (string payload in payloads) + { File.WriteAllText(payload, "{corrupt"); + } using (DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache)) + { await Assert.ThrowsAsync(() => snapshot.QueryAsync(new("read", "probe"))); + } DocumentationResult repaired = await IndexAsync(); Assert.Equal(initial.snapshot, repaired.snapshot); using DocumentationSnapshot current = await DocumentationStore.OpenAsync(cache); @@ -456,7 +532,9 @@ public async Task MovesKeepPageIdentityAndDeletesInvalidateOnlyTheNewSnapshot() DocumentationResult moved = await IndexAsync(); Assert.NotEqual(initial.snapshot, moved.snapshot); using (DocumentationSnapshot current = await DocumentationStore.OpenAsync(cache)) + { Assert.Equal("content/en/new.md", (await current.QueryAsync(new("read", "movable"))).hits.Single().page); + } File.Delete(Path.Combine(source, "content/en/new.md")); await IndexAsync(); using DocumentationSnapshot deleted = await DocumentationStore.OpenAsync(cache); @@ -467,7 +545,8 @@ public async Task MovesKeepPageIdentityAndDeletesInvalidateOnlyTheNewSnapshot() [Fact] public async Task LargeSectionsRoundTripWithoutLosingTextOrSurrogatePairs() { - string body = "## Long contract\n\n" + string.Concat(Enumerable.Repeat("The caller retains ownership until every consumer exits. 🦊\n", 700)); + string body = "## Long contract\n\n" + + string.Concat(Enumerable.Repeat("The caller retains ownership until every consumer exits. 🦊\n", 700)); Write("content/en/long.md", Page("long", "Long page", body)); await IndexAsync(); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache); @@ -478,11 +557,14 @@ public async Task LargeSectionsRoundTripWithoutLosingTextOrSurrogatePairs() DocumentationResult read = await snapshot.QueryAsync(new("read", "long", section: "long-contract", offset: offset)); recovered.Append(read.hits.Single().text); if (read.continuations.Count == 0) + { break; + } int next = read.continuations.Single().offset; Assert.True(next > offset); offset = next; - } while (true); + } + while (true); Assert.Equal(body, recovered.ToString()); } @@ -501,12 +583,14 @@ await Assert.ThrowsAnyAsync(() => Task[] queries = Enumerable.Range(0, 12).Select(index => Task.Run(async () => { await start.Task; - return await snapshot.QueryAsync((index % 3) switch - { - 0 => new("search", "ownership"), - 1 => new("symbol", C_SYMBOL, "Inno.Probe", "host-runtime"), - _ => new("read", "probe", section: "ownership") - }); + return await snapshot.QueryAsync( + (index % 3) switch + { + 0 => new("search", "ownership"), + 1 => new("symbol", C_SYMBOL, "Inno.Probe", "host-runtime"), + _ => new("read", "probe", section: "ownership") + } + ); })).ToArray(); start.SetResult(); DocumentationResult[] results = await Task.WhenAll(queries); @@ -533,7 +617,9 @@ await Assert.ThrowsAnyAsync(() => public async Task ConcurrentWritersAndReadersPublishConsistentGenerations() { for (int index = 0; index < 24; index++) + { Write($"content/en/task-{index}.md", Page($"task-{index}", $"Task {index}", $"Original content {index}.\n")); + } DocumentationResult[] results = await Task.WhenAll(Enumerable.Range(0, 3).Select(_ => IndexAsync())); Assert.Single(results.Select(result => result.snapshot).Distinct()); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache); @@ -542,7 +628,9 @@ public async Task ConcurrentWritersAndReadersPublishConsistentGenerations() byte[] pointer = File.ReadAllBytes(Path.Combine(cache, "current.json")); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); - await Assert.ThrowsAnyAsync(() => DocumentationStore.IndexAsync(m_root, source, cache, cancellation.Token)); + await Assert.ThrowsAnyAsync( + () => DocumentationStore.IndexAsync(m_root, source, cache, cancellation.Token) + ); Assert.Equal(pointer, File.ReadAllBytes(Path.Combine(cache, "current.json"))); } @@ -553,12 +641,16 @@ public async Task CancelingPreparationWithAProtectedPageRetainsThePublishedGener string pointer = Path.Combine(cache, "current.json"); byte[] selected = File.ReadAllBytes(pointer); string[] payloads = Directory.GetFiles(Path.Combine(cache, "pages"), "page.json", SearchOption.AllDirectories); - string protectedPage = payloads.Single(path => JsonNode.Parse(File.ReadAllText(path))!["path"]!.GetValue() == "content/en/probe.md"); + string protectedPage = payloads.Single( + path => JsonNode.Parse(File.ReadAllText(path))!["path"]!.GetValue() == "content/en/probe.md" + ); string key = Path.GetFileName(Path.GetDirectoryName(protectedPage)!); using DocumentationSnapshot reader = await DocumentationStore.OpenAsync(cache); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); for (int index = 0; index < 24; index++) + { Write($"content/en/new-{index}.md", Page($"new-{index}", $"New {index}", "New generation content.\n")); + } using (await FileLease.AcquireAsync(Path.Combine(cache, "leases", key + ".lock"), Timeout.InfiniteTimeSpan, cancellation.Token)) { Task preparation = DocumentationStore.IndexAsync(m_root, source, cache, cancellation.Token); @@ -581,7 +673,10 @@ public async Task CancelingPreparationWithAProtectedPageRetainsThePublishedGener finally { cancellation.Cancel(); - try { await preparation; } + try + { + await preparation; + } catch (OperationCanceledException) { /* Drain every worker before releasing the protected page. */ } } } @@ -604,8 +699,10 @@ public async Task InvalidExampleContextsCannotReplaceThePublishedSnapshot(string { await IndexAsync(); byte[] pointer = File.ReadAllBytes(Path.Combine(cache, "current.json")); - Write("content/en/example.md", Page("example", "Example", "```csharp\npublic class Example { }\n```\n", - "kind: tutorial\n" + metadata)); + Write( + "content/en/example.md", + Page("example", "Example", "```csharp\npublic class Example { }\n```\n", "kind: tutorial\n" + metadata) + ); await Assert.ThrowsAsync(() => IndexAsync()); Assert.Equal(pointer, File.ReadAllBytes(Path.Combine(cache, "current.json"))); } @@ -613,8 +710,15 @@ public async Task InvalidExampleContextsCannotReplaceThePublishedSnapshot(string [Fact] public async Task CatalogRetainsExplicitScriptContextWithoutPreparingItsReferences() { - Write("content/en/example.md", Page("example", "Example", "```csharp\npublic class Example { }\n```\n", - "kind: tutorial\nexampleMode: editor-script\nexampleProjects: [Inno.Probe]\n")); + Write( + "content/en/example.md", + Page( + "example", + "Example", + "```csharp\npublic class Example { }\n```\n", + "kind: tutorial\nexampleMode: editor-script\nexampleProjects: [Inno.Probe]\n" + ) + ); await IndexAsync(); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache); DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages, page => page.id == "example"); @@ -638,11 +742,28 @@ public async Task TaskHeadingsRankAboveTutorialsThatMerelyDemonstrateTheQuery() [Fact] public async Task TaskHeadingTermsOutrankAssemblyIndexesWithoutAnExactPhrase() { - Write("content/en/probe.md", Page("probe", "Probe", "Read keyboard, pointer and text input in the task guide.\n\n## Ownership\n\nBorrow the lease.\n", - "kind: project\nowners: [Inno.Probe]\n")); - Write("content/en/task.md", Page("z-task", "Read keyboard, pointer and text input", "Observe one immutable frame.\n", - "kind: how-to\nowners: [Inno.Probe]\n")); - Write("content/en/index.md", Page("a-index", "All members", "Read data. Keyboard values. Pointer fields. Text formatting. Input functions.\n")); + Write( + "content/en/probe.md", + Page( + "probe", + "Probe", + "Read keyboard, pointer and text input in the task guide.\n\n## Ownership\n\nBorrow the lease.\n", + "kind: project\nowners: [Inno.Probe]\n" + ) + ); + Write( + "content/en/task.md", + Page( + "z-task", + "Read keyboard, pointer and text input", + "Observe one immutable frame.\n", + "kind: how-to\nowners: [Inno.Probe]\n" + ) + ); + Write( + "content/en/index.md", + Page("a-index", "All members", "Read data. Keyboard values. Pointer fields. Text formatting. Input functions.\n") + ); await IndexAsync(); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache); Dictionary before = Files(); @@ -659,14 +780,29 @@ public async Task TaskHeadingTermsOutrankAssemblyIndexesWithoutAnExactPhrase() public async Task NaturalTaskTiesPreferGuidesWhileIdentifiersKeepReferencePriority() { const string C_PREFAB_SYMBOL = "M:Inno.Probe.InstantiatePrefab"; - Write("content/en/prefab-api.md", Page("a-prefab-api", "Prefab API", - "## InstantiatePrefab\n\n\n\n```csharp\npublic void InstantiatePrefab();\n```\n\nCreate an owned instance.\n", - "kind: api\nowners: [Inno.Probe]\napiSurface: host-runtime\n")); - Write("content/en/prefab-task.md", Page("z-prefab-task", "Instantiate a prefab in its owning scene", - "Supply the current scene and asset.\n", "kind: how-to\nowners: [Inno.Probe]\n")); - Write("content/en/body-only.md", Page("a-body-only", "Other task", "Instantiate a prefab.\n", - "kind: tutorial\nowners: [Inno.Probe]\n")); + Write( + "content/en/prefab-api.md", + Page( + "a-prefab-api", + "Prefab API", + "## InstantiatePrefab\n\n\n\n```csharp\npublic void InstantiatePrefab();\n```\n\nCreate an owned instance.\n", + "kind: api\nowners: [Inno.Probe]\napiSurface: host-runtime\n" + ) + ); + Write( + "content/en/prefab-task.md", + Page( + "z-prefab-task", + "Instantiate a prefab in its owning scene", + "Supply the current scene and asset.\n", + "kind: how-to\nowners: [Inno.Probe]\n" + ) + ); + Write( + "content/en/body-only.md", + Page("a-body-only", "Other task", "Instantiate a prefab.\n", "kind: tutorial\nowners: [Inno.Probe]\n") + ); await IndexAsync(); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache); Dictionary before = Files(); @@ -702,12 +838,29 @@ public async Task StructuredPaginationAndExactSymbolSearchNeedNoConsoleParsing() public async Task CommandReadsRequireExplicitPreparationAndNeverRefreshAuthoringInputs() { await Assert.ThrowsAsync(() => DocumentationCommand.ExecuteAsync(["index", "--engine-root", m_root])); - await Assert.ThrowsAsync(() => DocumentationCommand.ExecuteAsync(["read", "--engine-root", m_root, "--docs-root", source, "--page", "probe"])); - Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["index", "--engine-root", m_root, "--docs-root", source, "--cache-root", cache, "--format", "json"])); + await Assert.ThrowsAsync( + () => DocumentationCommand.ExecuteAsync(["read", "--engine-root", m_root, "--docs-root", source, "--page", "probe"]) + ); + Assert.Equal( + 0, + await DocumentationCommand.ExecuteAsync( + ["index", "--engine-root", m_root, "--docs-root", source, "--cache-root", cache, "--format", "json"] + ) + ); Dictionary prepared = Files(); Write("content/en/probe.md", "Invalid mutable authoring content cannot silently replace the selected snapshot."); - Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["read", "--engine-root", m_root, "--cache-root", cache, "--page", "probe", "--format", "json"])); - Assert.Equal(2, await DocumentationCommand.ExecuteAsync(["read", "--engine-root", m_root, "--cache-root", cache, "--page", "missing", "--format", "json"])); + Assert.Equal( + 0, + await DocumentationCommand.ExecuteAsync( + ["read", "--engine-root", m_root, "--cache-root", cache, "--page", "probe", "--format", "json"] + ) + ); + Assert.Equal( + 2, + await DocumentationCommand.ExecuteAsync( + ["read", "--engine-root", m_root, "--cache-root", cache, "--page", "missing", "--format", "json"] + ) + ); Assert.Equal(prepared.OrderBy(static pair => pair.Key), Files().OrderBy(static pair => pair.Key)); } @@ -747,7 +900,7 @@ public async Task AProjectMoveChangesTheSnapshotThroughItsExplicitInventoryWitho public async Task LargePageReadsPreservePreambleAndNestedSectionsThroughExplicitContinuation() { string body = "---\nuid: long-contract\nkind: explanation\n---\nPreamble ownership contract.\n\n# First\nOwner contract.\n\n### Deep\n" - + new string('x', 18000) + "\n\n## Second\nRetirement contract.\n"; + + new string('x', 18000) + "\n\n## Second\nRetirement contract.\n"; Write("content/en/long.md", body); await IndexAsync(); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache); @@ -758,11 +911,15 @@ public async Task LargePageReadsPreservePreambleAndNestedSectionsThroughExplicit DocumentationResult result = await snapshot.QueryAsync(request); text.Append(Assert.Single(result.hits).text); request = result.nextRequest; - } while (request is not null); + } + while (request is not null); Assert.Equal(body, text.ToString()); DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(); Assert.Equal(new[] { "first", "deep", "second" }, catalog.pages.Single(page => page.id == "long-contract").sections.Keys); - Assert.Contains("Retirement contract.", (await snapshot.QueryAsync(new("read", "long-contract", section: "second"))).hits.Single().text); + Assert.Contains( + "Retirement contract.", + (await snapshot.QueryAsync(new("read", "long-contract", section: "second"))).hits.Single().text + ); } private void SetProjectInventory(JsonNode projects) @@ -780,15 +937,28 @@ string description ) { byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(new { - model = "host-runtime", configuration = "Debug", target = (string?)null, - projects = new[] { new { name = "Inno.Probe", project = "src/Inno.Probe.csproj", symbols = Array.Empty(), description } } + model = "host-runtime", + configuration = "Debug", + target = (string?)null, + projects = new[] + { + new { name = "Inno.Probe", project = "src/Inno.Probe.csproj", symbols = Array.Empty(), description } + } }); Write(path, Encoding.UTF8.GetString(bytes)); JsonNode binding = JsonNode.Parse(File.ReadAllText(Path.Combine(source, "reference/engine.lock.json")))!; binding["apiManifests"] = JsonSerializer.SerializeToNode(new[] { - new { path, sha256 = Hash(bytes), model = "host-runtime", configuration = "Debug", target = (string?)null, - sourceRevision = new string('a', 40), sourceTree = new string('b', 40) } + new + { + path, + sha256 = Hash(bytes), + model = "host-runtime", + configuration = "Debug", + target = (string?)null, + sourceRevision = new string('a', 40), + sourceTree = new string('b', 40) + } }); Write("reference/engine.lock.json", binding.ToJsonString()); return bytes; @@ -803,9 +973,10 @@ string text File.WriteAllText(target, text, new UTF8Encoding(false)); } - private Dictionary Files() => Directory.GetFiles(cache, "*", SearchOption.AllDirectories) - .Where(static path => !path.EndsWith(".lock", StringComparison.Ordinal)) - .ToDictionary(path => Path.GetRelativePath(cache, path), path => Hash(File.ReadAllBytes(path)), StringComparer.Ordinal); + private Dictionary Files() + => Directory.GetFiles(cache, "*", SearchOption.AllDirectories) + .Where(static path => !path.EndsWith(".lock", StringComparison.Ordinal)) + .ToDictionary(path => Path.GetRelativePath(cache, path), path => Hash(File.ReadAllBytes(path)), StringComparer.Ordinal); private static string Hash(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes)); @@ -819,8 +990,12 @@ private static string Page( private static string Api( string uid, string surface - ) => Page(uid, "Probe API", "## Read\n\n\n\n| Declaration | Contract |\n| --- | --- |\n| `Read(string key)` | Returns the value; caller owns the lease. |\n", - "kind: api\nowners: [Inno.Probe]\napiSurface: " + surface + "\ncontracts: [probe#ownership]\n"); + "kind: api\nowners: [Inno.Probe]\napiSurface: " + surface + "\ncontracts: [probe#ownership]\n" + ); } diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationConsumerInputTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationConsumerInputTests.cs index 750b651a0..c35dde6f6 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationConsumerInputTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationConsumerInputTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Linq; @@ -6,6 +5,7 @@ using System.Text.Json.Nodes; using System.Threading.Tasks; using Xunit; +using Inno.Testing.Validation; namespace Inno.Tooling.Validation.Tests; @@ -16,7 +16,9 @@ public async Task ProductInputsUseVerifiedCommitObjectsAcrossRunsAndRepairCorrup { using var repository = new ValidationRepository(); using var consumer = new ValidationRepository(); - string origin = "https://github.com/validation/" + Path.GetFileName(Path.TrimEndingDirectorySeparator(consumer.PathOf("."))) + ".git"; + string origin = "https://github.com/validation/" + + Path.GetFileName(Path.TrimEndingDirectorySeparator(consumer.PathOf("."))) + + ".git"; consumer.Git("remote", "add", "origin", origin); const string C_SCENE = "FlappyBird/Assets/FlappyBird/FlappyBird.iscene"; consumer.Write(C_SCENE, "pinned scene content"); @@ -24,7 +26,10 @@ public async Task ProductInputsUseVerifiedCommitObjectsAcrossRunsAndRepairCorrup consumer.Git("commit", "-m", "Pin the consumer scene"); string commit = consumer.Git("rev-parse", "HEAD"); consumer.Write(C_SCENE, "uncommitted consumer changes must remain private"); - repository.Write("tests/fixtures/editor-ui/consumer.json", JsonSerializer.Serialize(new { repository = origin, commit, project = "FlappyBird" })); + repository.Write( + "tests/fixtures/editor-ui/consumer.json", + JsonSerializer.Serialize(new { repository = origin, commit, project = "FlappyBird" }) + ); // Stop at the external product boundary: this regression certifies input preparation, not an Editor journey. repository.Write("tests/Invoke-EditorSmoke.ps1", "throw 'Consumer input reached the product boundary.'\n"); repository.Git("add", "."); @@ -32,18 +37,31 @@ public async Task ProductInputsUseVerifiedCommitObjectsAcrossRunsAndRepairCorrup repository.Write("src/Example/Changed.cs", "namespace Example; public class Changed { }\n"); using JsonDocument generated = await repository.PlanAsync(); JsonNode plan = JsonNode.Parse(generated.RootElement.GetRawText())!; - JsonNode build = plan["checks"]!.AsArray().Single(check => check!["kind"]!.GetValue() == "build" - && check["owner"]!.GetValue() == "src/Example/Example.csproj")!.DeepClone(); + JsonNode build = plan["checks"]!.AsArray().Single(check => ( + check!["kind"]!.GetValue() == "build" + && check["owner"]!.GetValue() == "src/Example/Example.csproj" + ))!.DeepClone(); build["prerequisites"] = new JsonArray(); - plan["checks"] = new JsonArray(build, JsonSerializer.SerializeToNode(new - { - id = "consumer-probe", kind = "products", owner = "src/Example/Example.csproj", - reason = "Exercise the declared external product-input boundary.", environment = "fixture", - prerequisites = new[] { build["id"]!.GetValue() }, inputs = new[] { "@src/Example/Example.csproj" }, - reusable = false, exclusion = (string?)null, context = "managed", layer = "product" - })); - JsonNode project = plan["contexts"]!["managed"]!["sdkGraph"]!.AsArray().Single(snapshot => - repository.BindWorkspace(snapshot!["Path"]!.GetValue()) == repository.PathOf("src/Example/Example.csproj"))!; + plan["checks"] = new JsonArray( + build, + JsonSerializer.SerializeToNode(new + { + id = "consumer-probe", + kind = "products", + owner = "src/Example/Example.csproj", + reason = "Exercise the declared external product-input boundary.", + environment = "fixture", + prerequisites = new[] { build["id"]!.GetValue() }, + inputs = new[] { "@src/Example/Example.csproj" }, + reusable = false, + exclusion = (string?)null, + context = "managed", + layer = "product" + }) + ); + JsonNode project = plan["contexts"]!["managed"]!["sdkGraph"]!.AsArray().Single(snapshot => ( + repository.BindWorkspace(snapshot!["Path"]!.GetValue()) == repository.PathOf("src/Example/Example.csproj") + ))!; project["Properties"]!["InnoValidationBackendPattern"] = "Declared fixture renderer"; repository.Write("artifacts/plan/plan.json", plan.ToJsonString()); string artifacts = repository.BindWorkspace(plan["artifacts"]!.GetValue()); @@ -54,11 +72,13 @@ public async Task ProductInputsUseVerifiedCommitObjectsAcrossRunsAndRepairCorrup await RunProbeAsync("reused"); Assert.False(File.Exists(repository.PathOf("artifacts/reused/consumer-probe/consumer-fetch.log"))); string stored = Directory.GetFiles(Path.Combine(cache, "objects", "pack"), "*.pack").SingleOrDefault() - ?? Path.Combine(cache, "objects", commit[..2], commit[2..]); + ?? Path.Combine(cache, "objects", commit[..2], commit[2..]); Assert.True(File.Exists(stored)); File.SetAttributes(stored, FileAttributes.Normal); using (FileStream corrupt = File.OpenWrite(stored)) + { corrupt.WriteByte(0); + } await RunProbeAsync("repaired"); Assert.Single(Directory.GetDirectories(Path.Combine(artifacts, "consumer-inputs"), "*.rejected-*")); Assert.True(File.Exists(repository.PathOf("artifacts/repaired/consumer-probe/consumer-fetch.log"))); @@ -66,18 +86,27 @@ public async Task ProductInputsUseVerifiedCommitObjectsAcrossRunsAndRepairCorrup consumer.Git("fsck", "--full", "--strict"); consumer.Git("-C", cache, "remote", "set-url", "origin", "https://github.com/validation/wrong.git"); await Assert.ThrowsAsync(() => repository.RunAsync(output: "artifacts/wrong-origin")); - Assert.Contains("different repository or storage owner", File.ReadAllText(repository.PathOf("artifacts/wrong-origin/results.json"))); + Assert.Contains( + "different repository or storage owner", + File.ReadAllText(repository.PathOf("artifacts/wrong-origin/results.json")) + ); async Task RunProbeAsync(string name) { await Assert.ThrowsAsync(() => repository.RunAsync(output: "artifacts/" + name)); string output = repository.PathOf("artifacts/" + name); using JsonDocument evidence = JsonDocument.Parse(File.ReadAllText(Path.Combine(output, "results.json"))); - JsonElement result = evidence.RootElement.GetProperty("results").EnumerateArray().Single(result => result.GetProperty("id").GetString() == "consumer-probe"); + JsonElement result = evidence.RootElement + .GetProperty("results") + .EnumerateArray() + .Single(result => result.GetProperty("id").GetString() == "consumer-probe"); Assert.Equal("Failed", result.GetProperty("status").GetString()); string detail = result.GetProperty("detail").GetString()!; Assert.True(detail.Contains("Consumer input reached the product boundary", StringComparison.Ordinal), detail); - Assert.Equal("pinned scene content", File.ReadAllText(Path.Combine(output, "consumer-probe", "Source", "Assets", "FlappyBird", "FlappyBird.iscene"))); + Assert.Equal( + "pinned scene content", + File.ReadAllText(Path.Combine(output, "consumer-probe", "Source", "Assets", "FlappyBird", "FlappyBird.iscene")) + ); } } } diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationDocumentationCompilationTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationDocumentationCompilationTests.cs index 711426cc9..d3e9c80d3 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationDocumentationCompilationTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationDocumentationCompilationTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.IO.Compression; @@ -7,14 +6,14 @@ using System.Text.Json.Nodes; using System.Threading.Tasks; using System.Xml.Linq; -using Inno.Tooling.Documentation; using Xunit; +using Inno.Testing.Validation; +using Inno.Tooling.Documentation; namespace Inno.Tooling.Validation.Integration.Tests; public sealed class ValidationDocumentationCompilationTests { - [Fact] public async Task SuccessfulSourceComparisonRetainsSeparateOwnerAndPackageInputs() { @@ -27,23 +26,41 @@ public async Task SuccessfulSourceComparisonRetainsSeparateOwnerAndPackageInputs using (ZipArchive package = ZipFile.Open(Path.Combine(feed, "Inno.ProofFixture.1.0.0.nupkg"), ZipArchiveMode.Create)) { using (var manifest = new StreamWriter(package.CreateEntry("Inno.ProofFixture.nuspec").Open())) - manifest.Write("Inno.ProofFixture1.0.0" - + "InnoEngineOwned dependency evidence fixture."); + { + manifest.Write( + "Inno.ProofFixture1.0.0" + + "InnoEngineOwned dependency evidence fixture." + ); + } using var content = new StreamWriter(package.CreateEntry("content/proof.txt").Open()); content.Write("first"); } - repository.Write(C_EXAMPLE, ValidationRepository.Project( - new XElement("PropertyGroup", new XElement("RestoreSources", feed), new XElement("RestorePackagesPath", packages), - new XElement("NuGetAudit", false)).ToString() - + "")); + repository.Write( + C_EXAMPLE, + ValidationRepository.Project( + new XElement( + "PropertyGroup", + new XElement("RestoreSources", feed), + new XElement("RestorePackagesPath", packages), + new XElement("NuGetAudit", false) + ).ToString() + + "" + ) + ); repository.Write("tests/ci/Test-AgentRules.ps1", "Write-Output 'Fixture instructions passed'\n"); repository.Write("tests/ci/Policy.Tests.ps1", "Write-Output 'Fixture compilation policy passed'\n"); repository.Git("add", "."); repository.Git("commit", "-m", "Declare actual package and finite compilation policy"); var docs = new ValidationDocumentationFixture(repository); docs.Initialize(); - docs.Write("content/en/example-task.md", ValidationDocumentationFixture.Page("Example", - "Keep an ordinary managed value alive.\n\n```csharp\nSystem.GC.KeepAlive(1);\n```\n", "host")); + docs.Write( + "content/en/example-task.md", + ValidationDocumentationFixture.Page( + "Example", + "Keep an ordinary managed value alive.\n\n```csharp\nSystem.GC.KeepAlive(1);\n```\n", + "host" + ) + ); DocumentationResult indexed = await docs.IndexAsync(); int run = 0; repository.Write("src/Example/Implementation.cs", "namespace Example; internal sealed class Implementation { }\n"); @@ -58,7 +75,8 @@ public async Task SuccessfulSourceComparisonRetainsSeparateOwnerAndPackageInputs Assert.Matches("^[a-f0-9]{64}$", example.GetProperty("packages").GetProperty("inno.prooffixture/1.0.0").GetString()!); Assert.Equal("Debug", example.GetProperty("configuration").GetString()); Assert.Equal(first.RootElement.GetProperty("environment").GetString(), example.GetProperty("environment").GetString()); - JsonElement exampleExecution = first.RootElement.GetProperty("results").EnumerateArray() + JsonElement exampleExecution = first.RootElement.GetProperty("results") + .EnumerateArray() .Single(result => result.GetProperty("id").GetString() == "documentation-examples:managed"); Assert.Equal("Passed", exampleExecution.GetProperty("status").GetString()); JsonElement exampleInputs = Assert.Single(exampleExecution.GetProperty("documentationInputs").EnumerateArray()); @@ -69,10 +87,14 @@ public async Task SuccessfulSourceComparisonRetainsSeparateOwnerAndPackageInputs repository.Write("src/Other/Implementation.cs", "namespace Other; internal sealed class Implementation { internal int value; }\n"); using JsonDocument next = await ExecuteAsync(); JsonElement[] changed = Proofs(next); - Assert.Equal(example.GetProperty("sourceIdentity").GetString(), - changed.Single(proof => proof.GetProperty("project").GetString() == C_EXAMPLE).GetProperty("sourceIdentity").GetString()); - Assert.NotEqual(initial.Single(proof => proof.GetProperty("project").GetString() == C_OTHER).GetProperty("sourceIdentity").GetString(), - changed.Single(proof => proof.GetProperty("project").GetString() == C_OTHER).GetProperty("sourceIdentity").GetString()); + Assert.Equal( + example.GetProperty("sourceIdentity").GetString(), + changed.Single(proof => proof.GetProperty("project").GetString() == C_EXAMPLE).GetProperty("sourceIdentity").GetString() + ); + Assert.NotEqual( + initial.Single(proof => proof.GetProperty("project").GetString() == C_OTHER).GetProperty("sourceIdentity").GetString(), + changed.Single(proof => proof.GetProperty("project").GetString() == C_OTHER).GetProperty("sourceIdentity").GetString() + ); string evidence = repository.PathOf("artifacts/source-input-run-2/results.json"); Assert.Equal(0, await repository.EvidenceAsync(evidence)); string restored = Path.Combine(packages, "inno.prooffixture", "1.0.0", "content", "proof.txt"); @@ -90,33 +112,46 @@ async Task ExecuteAsync() { string kind = check.GetProperty("kind").GetString()!; if (kind is not ("instructions" or "architecture" or "documentation" or "documentation-api" or "documentation-examples") - && !(kind == "build" && check.GetProperty("owner").GetString() is C_EXAMPLE or C_OTHER)) + && !(kind == "build" && check.GetProperty("owner").GetString() is C_EXAMPLE or C_OTHER) + ) { continue; + } JsonNode item = JsonNode.Parse(check.GetRawText())!; // The source-input protocol uses real compilation and comparison. Repository-wide // architecture policy is verified independently, not synthesized by this small fixture. if (kind == "architecture") + { item["kind"] = "ci-contracts"; + } selected.Add(item); } execution["checks"] = selected; repository.Write("artifacts/plan/plan.json", execution.ToJsonString()); string output = "artifacts/source-input-run-" + ++run; await repository.RunAsync(output: output); - using JsonDocument comparison = JsonDocument.Parse(File.ReadAllBytes( - repository.PathOf(output + "/documentation-api-managed-default.json"))); + using JsonDocument comparison = JsonDocument.Parse( + File.ReadAllBytes(repository.PathOf(output + "/documentation-api-managed-default.json")) + ); foreach (JsonElement owner in comparison.RootElement.GetProperty("projects").EnumerateArray()) - Assert.Equal(planned.RootElement.GetProperty("documentationSources") - .GetProperty("reference/api/facts.json\0" + owner.GetProperty("name").GetString()).GetString(), - owner.GetProperty("referenceIdentity").GetString()); + { + Assert.Equal( + planned.RootElement.GetProperty("documentationSources") + .GetProperty("reference/api/facts.json\0" + owner.GetProperty("name").GetString()) + .GetString(), + owner.GetProperty("referenceIdentity").GetString() + ); + } return JsonDocument.Parse(File.ReadAllBytes(repository.PathOf(output + "/results.json"))); } static JsonElement[] Proofs(JsonDocument evidence) { Assert.True(evidence.RootElement.GetProperty("completed").GetBoolean()); - JsonElement comparison = Assert.Single(evidence.RootElement.GetProperty("results").EnumerateArray() - .Where(result => result.GetProperty("id").GetString()!.StartsWith("documentation-api:", StringComparison.Ordinal))); + JsonElement comparison = Assert.Single( + evidence.RootElement.GetProperty("results") + .EnumerateArray() + .Where(result => result.GetProperty("id").GetString()!.StartsWith("documentation-api:", StringComparison.Ordinal)) + ); Assert.Equal("Passed", comparison.GetProperty("status").GetString()); return comparison.GetProperty("documentationInputs").EnumerateArray().ToArray(); } diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationFailureExecutionTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationFailureExecutionTests.cs index 8443bebaa..eb1f5a39a 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationFailureExecutionTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationFailureExecutionTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Linq; using System.Text.Json; using System.Text.Json.Nodes; using System.Threading.Tasks; -using Inno.Tooling.Validation; using Xunit; +using Inno.Testing.Validation; +using Inno.Tooling.Validation; namespace Inno.Tooling.Validation.Tests; @@ -39,19 +39,28 @@ public async Task FailedContractBlocksItsDependentButIndependentContextStillExec await Assert.ThrowsAsync(() => repository.RunAsync()); using JsonDocument evidence = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/run/results.json"))); JsonElement[] results = evidence.RootElement.GetProperty("results").EnumerateArray().ToArray(); - Assert.Equal("Failed", results.Single(result => result.GetProperty("id").GetString() == "contract-failure").GetProperty("status").GetString()); - Assert.Contains("Original contract failure", results.Single(result => result.GetProperty("id").GetString() == "contract-failure").GetProperty("detail").GetString()); + Assert.Equal( + "Failed", + results.Single(result => result.GetProperty("id").GetString() == "contract-failure").GetProperty("status").GetString() + ); + Assert.Contains( + "Original contract failure", + results.Single(result => result.GetProperty("id").GetString() == "contract-failure").GetProperty("detail").GetString() + ); string detail = results.Single(result => result.GetProperty("id").GetString() == "contract-failure") - .GetProperty("detail").GetString()!; + .GetProperty("detail") + .GetString()!; Assert.True(detail.Length < 5000, "An owner receipt must not duplicate the complete process log."); string log = repository.PathOf("artifacts/run/Failure.Tests.log"); Assert.Contains(log, detail); Assert.Contains(new string('x', 20000), File.ReadAllText(log)); - Assert.Equal("Passed", results.Single(result => result.GetProperty("id").GetString() == "independent-policy").GetProperty("status").GetString()); + Assert.Equal( + "Passed", + results.Single(result => result.GetProperty("id").GetString() == "independent-policy").GetProperty("status").GetString() + ); JsonElement blocked = results.Single(result => result.GetProperty("id").GetString() == "dependent-policy"); Assert.Equal("Blocked", blocked.GetProperty("status").GetString()); Assert.Contains("contract-failure (Failed)", blocked.GetProperty("detail").GetString()); Assert.True(evidence.RootElement.GetProperty("completed").GetBoolean()); } - } diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs index ae64e8ff3..7a480994f 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Linq; @@ -7,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Xunit; +using Inno.Testing.Validation; namespace Inno.Tooling.Validation.Integration.Tests; @@ -14,7 +14,7 @@ namespace Inno.Tooling.Validation.Integration.Tests; /// Isolates the process console while observing the public validation entry's live progress. /// [CollectionDefinition(nameof(ValidationProgressCollection), DisableParallelization = true)] -public sealed class ValidationProgressCollection { } +public sealed class ValidationProgressCollection; [Collection(nameof(ValidationProgressCollection))] public sealed class ValidationProgressTests @@ -71,7 +71,10 @@ public async Task QuietChildReportsActivityBeforeExitAndCancellationRetainsItsFa cancellation.Cancel(); if (running is not null) { - try { await running; } + try + { + await running; + } catch (Exception) when (cancellation.IsCancellationRequested) { } } Console.SetOut(original); @@ -90,14 +93,18 @@ public override void WriteLine(string? value) { base.WriteLine(value); if (value?.StartsWith("Process active:", StringComparison.Ordinal) == true) + { activity.TrySetResult(value); + } } } internal string Read() { lock (m_sync) + { return ToString(); + } } } } diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationRuntimeClosureTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationRuntimeClosureTests.cs index 6a7861e3d..97d8dd1cc 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationRuntimeClosureTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationRuntimeClosureTests.cs @@ -1,10 +1,10 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Threading.Tasks; using System.Xml.Linq; -using Inno.Testing.Source; using Xunit; +using Inno.Testing.Source; +using Inno.Testing.Validation; namespace Inno.Tooling.Validation.Integration.Tests; @@ -24,31 +24,45 @@ public async Task VerifiedDependenciesPreservePrivateTransitiveRuntimeFiles() """); - var targets = new XElement("Project", new XElement("Import", new XAttribute("Project", Path.Combine(root, "Directory.Build.targets")))); - targets.Add(XElement.Parse(""" + var targets = new XElement( + "Project", + new XElement("Import", new XAttribute("Project", Path.Combine(root, "Directory.Build.targets"))) + ); + targets.Add( + XElement.Parse(""" - """)); + """) + ); repository.Write("Directory.Build.targets", targets.ToString()); repository.Write("Leaf/Leaf.csproj", ValidationRepository.Project()); repository.Write("Leaf/Leaf.cs", "public sealed class Leaf {}"); - repository.Write("Middle/Middle.csproj", ValidationRepository.Project(""" + repository.Write( + "Middle/Middle.csproj", + ValidationRepository.Project(""" - """)); + """) + ); repository.Write("Middle/Middle.cs", "public sealed class Middle { public static System.Type LeafType => typeof(Leaf); }"); - repository.Write("Bridge/Bridge.csproj", ValidationRepository.Project(""" + repository.Write( + "Bridge/Bridge.csproj", + ValidationRepository.Project(""" true true - """)); + """) + ); repository.Write("Bridge/Bridge.cs", "public sealed class Bridge {}"); - repository.Write("App/App.csproj", ValidationRepository.Project(""" + repository.Write( + "App/App.csproj", + ValidationRepository.Project(""" Exetrue - """)); + """) + ); repository.Write("App/Program.cs", """ System.Reflection.Assembly.LoadFrom(System.IO.Path.Combine(System.AppContext.BaseDirectory, "Leaf.dll")); """); @@ -59,8 +73,17 @@ public async Task VerifiedDependenciesPreservePrivateTransitiveRuntimeFiles() byte[] leaf = File.ReadAllBytes(repository.PathOf("App/bin/Release/net10.0/Leaf.dll")); string[] builds = File.ReadAllLines(repository.PathOf("dependency-builds.log")); Assert.Contains("Leaf", builds); - await repository.SdkAsync("clean", "Build.slnx", "-c", "Release", "-p:BuildProjectReferences=false", "-p:InnoCleanProjectReferences=false", - "--disable-build-servers", "-m:1", "-nr:false"); + await repository.SdkAsync( + "clean", + "Build.slnx", + "-c", + "Release", + "-p:BuildProjectReferences=false", + "-p:InnoCleanProjectReferences=false", + "--disable-build-servers", + "-m:1", + "-nr:false" + ); Assert.False(File.Exists(application)); await repository.BuildAsync("Build.slnx", "-c", "Release", "-p:InnoUseVerifiedProjectOutputs=true"); await repository.SdkAsync(application); diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationShardExecutionTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationShardExecutionTests.cs index f07fbd4ef..0707b6143 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationShardExecutionTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationShardExecutionTests.cs @@ -7,10 +7,10 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Testing.Source; using Inno.Testing.Validation; -using Xunit; namespace Inno.Tooling.Validation.Tests; @@ -26,60 +26,117 @@ public async Task RestoreKeepsTheToolEnvironmentStableWhileChangedPackageBytesRe using (ZipArchive archive = ZipFile.Open(Path.Combine(feed, "Inno.Fixture.Dependency.1.0.0.nupkg"), ZipArchiveMode.Create)) { using (var manifest = new StreamWriter(archive.CreateEntry("Inno.Fixture.Dependency.nuspec").Open())) - manifest.Write("Inno.Fixture.Dependency1.0.0FixtureRestored input ownership fixture."); + { + manifest.Write( + "Inno.Fixture.Dependency1.0.0FixtureRestored input ownership fixture." + ); + } using var props = new StreamWriter(archive.CreateEntry("buildTransitive/Inno.Fixture.Dependency.props").Open()); props.Write("before"); } using var repository = new ValidationRepository(); - repository.Write("Directory.Build.props", "" + repository.Write( + "Directory.Build.props", + "" + System.Security.SecurityElement.Escape(feed) + "" - + System.Security.SecurityElement.Escape(packages) + ""); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project( - "")); + + System.Security.SecurityElement.Escape(packages) + "" + ); + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project( + "" + ) + ); repository.Write("src/Example/Contract.cs", "namespace Example; public static class Contract { public static int Value => 1; }"); repository.Write("tests/ci/Test-AgentRules.ps1", "Write-Output 'Policy passed'"); using JsonDocument cold = await repository.PlanAsync(profile: "full"); JsonObject accepted = SelectCompilation(cold); repository.Write("artifacts/cold.json", accepted.ToJsonString()); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["run", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/cold.json"), "--output", repository.PathOf("artifacts/cold")])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "run", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/cold.json"), + "--output", + repository.PathOf("artifacts/cold") + ]) + ); using JsonDocument restored = await repository.PlanAsync(profile: "full"); JsonObject current = SelectCompilation(restored); Assert.Equal(accepted["environment"]!.GetValue(), current["environment"]!.GetValue()); - Assert.Contains(restored.RootElement.GetProperty("contexts").GetProperty("managed").GetProperty("sdkGraph").EnumerateArray() - .SelectMany(static project => project.GetProperty("Imports").EnumerateArray()), - static import => import.GetString()!.EndsWith("Inno.Fixture.Dependency.props", StringComparison.Ordinal)); + Assert.Contains( + restored.RootElement.GetProperty("contexts") + .GetProperty("managed") + .GetProperty("sdkGraph") + .EnumerateArray() + .SelectMany(static project => project.GetProperty("Imports").EnumerateArray()), + static import => import.GetString()!.EndsWith("Inno.Fixture.Dependency.props", StringComparison.Ordinal) + ); repository.Write("artifacts/restored.json", current.ToJsonString()); Assert.Equal(0, await Resume("artifacts/reused")); Assert.False(File.Exists(repository.PathOf("artifacts/reused/managed-build.log"))); JsonNode reused = JsonNode.Parse(File.ReadAllText(repository.PathOf("artifacts/reused/results.json")))!; - Assert.Equal("Reused", reused["results"]!.AsArray().Single(result => result!["id"]!.GetValue() - == "build:src/Example/Example.csproj")!["status"]!.GetValue()); + Assert.Equal( + "Reused", + reused["results"]!.AsArray().Single(result => ( + result!["id"]!.GetValue() + == "build:src/Example/Example.csproj" + ))!["status"]!.GetValue() + ); string imported = Path.Combine(packages, "inno.fixture.dependency", "1.0.0", "buildTransitive", "Inno.Fixture.Dependency.props"); DateTime timestamp = File.GetLastWriteTimeUtc(imported); File.WriteAllText(imported, "edited"); File.SetLastWriteTimeUtc(imported, timestamp); await Assert.ThrowsAsync(() => repository.EvidenceAsync( - repository.PathOf("artifacts/reused/results.json"), repository.PathOf("artifacts/restored.json"))); + repository.PathOf("artifacts/reused/results.json"), + repository.PathOf("artifacts/restored.json") + )); Assert.Equal(0, await Resume("artifacts/package-changed")); Assert.True(File.Exists(repository.PathOf("artifacts/package-changed/managed-build.log"))); - Task Resume(string output) => ValidationCommand.ExecuteAsync(["resume", "--engine-root", repository.PathOf("."), - "--dotnet", repository.dotnet, "--plan", repository.PathOf("artifacts/restored.json"), - "--accepted-plan", repository.PathOf("artifacts/cold.json"), "--evidence", repository.PathOf("artifacts/cold/results.json"), - "--output", repository.PathOf(output)]); + Task Resume(string output) + => ValidationCommand.ExecuteAsync([ + "resume", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/restored.json"), + "--accepted-plan", + repository.PathOf("artifacts/cold.json"), + "--evidence", + repository.PathOf("artifacts/cold/results.json"), + "--output", + repository.PathOf(output) + ]); static JsonObject SelectCompilation(JsonDocument generated) { JsonObject plan = JsonNode.Parse(generated.RootElement.GetRawText())!.AsObject(); - JsonObject policy = plan["checks"]!.AsArray().Single(check => check!["id"]!.GetValue() == "instructions")!.DeepClone().AsObject(); - JsonObject build = plan["checks"]!.AsArray().Single(check => check!["id"]!.GetValue() == "build:src/Example/Example.csproj")!.DeepClone().AsObject(); + JsonObject policy = plan["checks"]! + .AsArray() + .Single(check => check!["id"]!.GetValue() == "instructions")! + .DeepClone() + .AsObject(); + JsonObject build = plan["checks"]! + .AsArray() + .Single(check => check!["id"]!.GetValue() == "build:src/Example/Example.csproj")! + .DeepClone() + .AsObject(); build["prerequisites"] = new JsonArray("instructions"); plan["checks"] = new JsonArray(policy, build); plan["shards"] = new JsonArray(new JsonObject { - ["id"] = "managed", ["checks"] = new JsonArray("instructions", build["id"]!.GetValue()), ["prerequisites"] = new JsonArray() + ["id"] = "managed", + ["checks"] = new JsonArray("instructions", build["id"]!.GetValue()), + ["prerequisites"] = new JsonArray() }); return plan; } @@ -91,23 +148,54 @@ public async Task ChangedExternalSdkInputExecutesCurrentChecksWithoutImportingRe using var sdkInput = new ValidationRepository(); sdkInput.Write("Environment.props", "before"); using var repository = new ValidationRepository(); - repository.Write("Shared.props", ""); + repository.Write( + "Shared.props", + "" + ); repository.Write("tests/ci/Test-AgentRules.ps1", "Add-Content -LiteralPath artifacts/policy-executions.txt -Value executed"); using JsonDocument before = await repository.PlanAsync(profile: "full"); JsonObject accepted = SelectPolicy(before); repository.Write("artifacts/accepted.json", accepted.ToJsonString()); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["run", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/accepted.json"), "--output", repository.PathOf("artifacts/accepted")])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "run", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/accepted.json"), + "--output", + repository.PathOf("artifacts/accepted") + ]) + ); sdkInput.Write("Environment.props", "after"); using JsonDocument after = await repository.PlanAsync(profile: "full"); JsonObject current = SelectPolicy(after); Assert.Equal(accepted["tree"]!.GetValue(), current["tree"]!.GetValue()); Assert.NotEqual(accepted["environment"]!.GetValue(), current["environment"]!.GetValue()); repository.Write("artifacts/current.json", current.ToJsonString()); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["resume", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/current.json"), "--accepted-plan", repository.PathOf("artifacts/accepted.json"), - "--evidence", repository.PathOf("artifacts/accepted/results.json"), "--retained-outputs", repository.PathOf("artifacts/unusable-outputs"), - "--output", repository.PathOf("artifacts/resumed")])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "resume", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/current.json"), + "--accepted-plan", + repository.PathOf("artifacts/accepted.json"), + "--evidence", + repository.PathOf("artifacts/accepted/results.json"), + "--retained-outputs", + repository.PathOf("artifacts/unusable-outputs"), + "--output", + repository.PathOf("artifacts/resumed") + ]) + ); Assert.Equal(2, File.ReadAllLines(repository.PathOf("artifacts/policy-executions.txt")).Length); JsonNode result = JsonNode.Parse(File.ReadAllText(repository.PathOf("artifacts/resumed/results.json")))!; Assert.Equal("Passed", result["results"]![0]!["status"]!.GetValue()); @@ -115,12 +203,18 @@ public async Task ChangedExternalSdkInputExecutesCurrentChecksWithoutImportingRe static JsonObject SelectPolicy(JsonDocument generated) { JsonObject plan = JsonNode.Parse(generated.RootElement.GetRawText())!.AsObject(); - JsonObject policy = plan["checks"]!.AsArray().Single(check => check!["id"]!.GetValue() == "instructions")!.DeepClone().AsObject(); + JsonObject policy = plan["checks"]! + .AsArray() + .Single(check => check!["id"]!.GetValue() == "instructions")! + .DeepClone() + .AsObject(); policy["reusable"] = true; plan["checks"] = new JsonArray(policy); plan["shards"] = new JsonArray(new JsonObject { - ["id"] = "architecture", ["checks"] = new JsonArray("instructions"), ["prerequisites"] = new JsonArray() + ["id"] = "architecture", + ["checks"] = new JsonArray("instructions"), + ["prerequisites"] = new JsonArray() }); return plan; } @@ -132,15 +226,25 @@ public async Task ContinuationRetainsARealCompiledUnionWithoutInvokingBuildAgain using var repository = new ValidationRepository(); repository.Write("tests/ci/Test-AgentRules.ps1", "Write-Output 'Policy passed'"); repository.Write("tests/ci/Compilation.Tests.ps1", "Write-Output 'Compilation fixture policy passed'"); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project(""" + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project(""" Exe - """)); - repository.Write("src/Example/TestRepository.cs", File.ReadAllText(Path.Combine( - TestRepository.GetRoot(typeof(ValidationShardExecutionTests).Assembly), "tests/source/Inno.Testing.Source/TestRepository.cs"))); + """) + ); + repository.Write( + "src/Example/TestRepository.cs", + File.ReadAllText( + Path.Combine( + TestRepository.GetRoot(typeof(ValidationShardExecutionTests).Assembly), + "tests/source/Inno.Testing.Source/TestRepository.cs" + ) + ) + ); repository.Write("src/Example/Program.cs", """ using System; using System.Reflection; @@ -157,28 +261,84 @@ public async Task ContinuationRetainsARealCompiledUnionWithoutInvokingBuildAgain repository.Git("commit", "-m", "Declare portable compilation fixture inputs"); using JsonDocument generated = await repository.PlanAsync(profile: "full"); JsonObject plan = JsonNode.Parse(generated.RootElement.GetRawText())!.AsObject(); - JsonObject policy = plan["checks"]!.AsArray().Single(check => check!["id"]!.GetValue() == "instructions")!.DeepClone().AsObject(); - JsonObject build = plan["checks"]!.AsArray().Single(check => check!["id"]!.GetValue() == "build:src/Example/Example.csproj")!.DeepClone().AsObject(); + JsonObject policy = plan["checks"]! + .AsArray() + .Single(check => check!["id"]!.GetValue() == "instructions")! + .DeepClone() + .AsObject(); + JsonObject build = plan["checks"]! + .AsArray() + .Single(check => check!["id"]!.GetValue() == "build:src/Example/Example.csproj")! + .DeepClone() + .AsObject(); build["prerequisites"] = new JsonArray("instructions"); plan["checks"] = new JsonArray(policy, build); plan["shards"] = new JsonArray(new JsonObject { - ["id"] = "managed", ["checks"] = new JsonArray("instructions", build["id"]!.GetValue()), ["prerequisites"] = new JsonArray() + ["id"] = "managed", + ["checks"] = new JsonArray("instructions", build["id"]!.GetValue()), + ["prerequisites"] = new JsonArray() }); repository.Write("artifacts/accepted.json", plan.ToJsonString()); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["run", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/accepted.json"), "--output", repository.PathOf("artifacts/accepted")])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "run", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/accepted.json"), + "--output", + repository.PathOf("artifacts/accepted") + ]) + ); Assert.True(File.Exists(repository.PathOf("artifacts/accepted/managed-build.log"))); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["resume", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/accepted.json"), "--accepted-plan", repository.PathOf("artifacts/accepted.json"), - "--evidence", repository.PathOf("artifacts/accepted/results.json"), "--output", repository.PathOf("artifacts/resumed")])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "resume", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/accepted.json"), + "--accepted-plan", + repository.PathOf("artifacts/accepted.json"), + "--evidence", + repository.PathOf("artifacts/accepted/results.json"), + "--output", + repository.PathOf("artifacts/resumed") + ]) + ); Assert.False(File.Exists(repository.PathOf("artifacts/resumed/managed-build.log"))); JsonNode evidence = JsonNode.Parse(File.ReadAllText(repository.PathOf("artifacts/resumed/results.json")))!; - Assert.Equal("Reused", evidence["results"]!.AsArray().Single(result => result!["id"]!.GetValue() == build["id"]!.GetValue())!["status"]!.GetValue()); - await Assert.ThrowsAsync(() => ValidationCommand.ExecuteAsync(["resume", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/accepted.json"), "--accepted-plan", repository.PathOf("artifacts/accepted.json"), - "--evidence", repository.PathOf("artifacts/accepted/results.json"), "--retained-outputs", repository.PathOf("artifacts/accepted"), - "--output", repository.PathOf("artifacts/refuse-overwrite")])); + Assert.Equal( + "Reused", + evidence["results"]! + .AsArray() + .Single(result => result!["id"]!.GetValue() == build["id"]!.GetValue())!["status"]! + .GetValue() + ); + await Assert.ThrowsAsync(() => ValidationCommand.ExecuteAsync([ + "resume", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/accepted.json"), + "--accepted-plan", + repository.PathOf("artifacts/accepted.json"), + "--evidence", + repository.PathOf("artifacts/accepted/results.json"), + "--retained-outputs", + repository.PathOf("artifacts/accepted"), + "--output", + repository.PathOf("artifacts/refuse-overwrite") + ])); Assert.False(File.Exists(repository.PathOf("artifacts/refuse-overwrite/managed-build.log"))); using var consumer = new ValidationRepository(repository.PathOf(".")); consumer.Write("artifacts/accepted.json", plan.ToJsonString()); @@ -190,31 +350,76 @@ await Assert.ThrowsAsync(() => ValidationCommand.ExecuteAs Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(file, destination); } - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["resume", "--engine-root", consumer.PathOf("."), "--dotnet", consumer.dotnet, - "--plan", consumer.PathOf("artifacts/accepted.json"), "--accepted-plan", consumer.PathOf("artifacts/accepted.json"), - "--evidence", consumer.PathOf("artifacts/evidence.json"), "--retained-outputs", consumer.PathOf("artifacts/retained"), - "--output", consumer.PathOf("artifacts/resumed")])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "resume", + "--engine-root", + consumer.PathOf("."), + "--dotnet", + consumer.dotnet, + "--plan", + consumer.PathOf("artifacts/accepted.json"), + "--accepted-plan", + consumer.PathOf("artifacts/accepted.json"), + "--evidence", + consumer.PathOf("artifacts/evidence.json"), + "--retained-outputs", + consumer.PathOf("artifacts/retained"), + "--output", + consumer.PathOf("artifacts/resumed") + ]) + ); Assert.True(File.Exists(consumer.PathOf("artifacts/resumed/managed-restore-retained.log"))); Assert.False(File.Exists(consumer.PathOf("artifacts/resumed/managed-build.log"))); string outputs = consumer.BindWorkspace(plan["artifacts"]!.GetValue()); - string assembly = consumer.BindWorkspace(plan["contexts"]!["managed"]!["sdkGraph"]!.AsArray() - .Single(node => node!["Path"]!.GetValue().Replace('\\', '/').EndsWith("/src/Example/Example.csproj", StringComparison.Ordinal))!["Properties"]!["TargetPath"]!.GetValue()); - string actual = await ToolchainEnvironment.CaptureOutputAsync(consumer.dotnet, [assembly], consumer.PathOf("."), CancellationToken.None, + string assembly = consumer.BindWorkspace( + plan["contexts"]!["managed"]!["sdkGraph"]!.AsArray() + .Single( + node => node!["Path"]! + .GetValue() + .Replace('\\', '/') + .EndsWith("/src/Example/Example.csproj", StringComparison.Ordinal) + )!["Properties"]!["TargetPath"]! + .GetValue() + ); + string actual = await ToolchainEnvironment.CaptureOutputAsync( + consumer.dotnet, + [assembly], + consumer.PathOf("."), + CancellationToken.None, new Dictionary { ["INNO_TESTING_REPOSITORY_ROOT"] = consumer.PathOf("."), ["INNO_TESTING_ARTIFACTS_PATH"] = outputs - }); + } + ); Assert.Equal(new[] { consumer.PathOf("."), outputs }, actual.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)); - string originalAssembly = repository.BindWorkspace(plan["contexts"]!["managed"]!["sdkGraph"]!.AsArray() - .Single(node => node!["Path"]!.GetValue().Replace('\\', '/').EndsWith("/src/Example/Example.csproj", StringComparison.Ordinal))!["Properties"]!["TargetPath"]!.GetValue()); - string independent = await ToolchainEnvironment.CaptureOutputAsync(repository.dotnet, [originalAssembly], repository.PathOf("."), CancellationToken.None, + string originalAssembly = repository.BindWorkspace( + plan["contexts"]!["managed"]!["sdkGraph"]!.AsArray() + .Single( + node => node!["Path"]! + .GetValue() + .Replace('\\', '/') + .EndsWith("/src/Example/Example.csproj", StringComparison.Ordinal) + )!["Properties"]!["TargetPath"]! + .GetValue() + ); + string independent = await ToolchainEnvironment.CaptureOutputAsync( + repository.dotnet, + [originalAssembly], + repository.PathOf("."), + CancellationToken.None, new Dictionary { ["INNO_TESTING_REPOSITORY_ROOT"] = consumer.PathOf("."), ["INNO_TESTING_ARTIFACTS_PATH"] = outputs - }); - Assert.Equal(new[] { repository.PathOf("."), originalOutputs }, independent.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)); + } + ); + Assert.Equal( + new[] { repository.PathOf("."), originalOutputs }, + independent.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries) + ); } [Fact] @@ -224,18 +429,36 @@ public async Task ContinuationExecutesOnlyMissingPolicyAndRejectsForeignEvidence repository.Write("tests/ci/Test-AgentRules.ps1", "Add-Content -LiteralPath artifacts/policy-executions.txt -Value executed"); using JsonDocument generated = await repository.PlanAsync(profile: "full"); JsonObject accepted = JsonNode.Parse(generated.RootElement.GetRawText())!.AsObject(); - JsonObject policy = accepted["checks"]!.AsArray().Single(check => check!["id"]!.GetValue() == "instructions")!.DeepClone().AsObject(); + JsonObject policy = accepted["checks"]! + .AsArray() + .Single(check => check!["id"]!.GetValue() == "instructions")! + .DeepClone() + .AsObject(); policy["reusable"] = true; accepted["checks"] = new JsonArray(policy); accepted["profile"] = 2; accepted["full"] = false; accepted["shards"] = new JsonArray(new JsonObject { - ["id"] = "architecture", ["checks"] = new JsonArray("instructions"), ["prerequisites"] = new JsonArray() + ["id"] = "architecture", + ["checks"] = new JsonArray("instructions"), + ["prerequisites"] = new JsonArray() }); repository.Write("artifacts/accepted.json", accepted.ToJsonString()); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["run", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/accepted.json"), "--output", repository.PathOf("artifacts/accepted")])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "run", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/accepted.json"), + "--output", + repository.PathOf("artifacts/accepted") + ]) + ); JsonObject current = accepted.DeepClone().AsObject(); current["profile"] = 3; current["full"] = true; @@ -259,9 +482,21 @@ public async Task ContinuationExecutesOnlyMissingPolicyAndRejectsForeignEvidence Task Resume( string evidencePath, string output - ) => ValidationCommand.ExecuteAsync(["resume", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/current.json"), "--accepted-plan", repository.PathOf("artifacts/accepted.json"), - "--evidence", repository.PathOf(evidencePath), "--output", repository.PathOf(output)]); + ) => ValidationCommand.ExecuteAsync([ + "resume", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/current.json"), + "--accepted-plan", + repository.PathOf("artifacts/accepted.json"), + "--evidence", + repository.PathOf(evidencePath), + "--output", + repository.PathOf(output) + ]); } [Fact] @@ -271,41 +506,95 @@ public async Task CompleteAcceptanceRequiresTheSameEnvironmentInputsAndCheckDefi repository.Write("tests/ci/Test-AgentRules.ps1", "Write-Output 'Actual policy execution'"); using JsonDocument generated = await repository.PlanAsync(profile: "full"); JsonObject plan = JsonNode.Parse(generated.RootElement.GetRawText())!.AsObject(); - JsonObject policy = plan["checks"]!.AsArray().Single(check => check!["id"]!.GetValue() == "instructions")!.DeepClone().AsObject(); + JsonObject policy = plan["checks"]! + .AsArray() + .Single(check => check!["id"]!.GetValue() == "instructions")! + .DeepClone() + .AsObject(); plan["checks"] = new JsonArray(policy); plan["shards"] = new JsonArray(new JsonObject { - ["id"] = "architecture", ["checks"] = new JsonArray("instructions"), ["prerequisites"] = new JsonArray() + ["id"] = "architecture", + ["checks"] = new JsonArray("instructions"), + ["prerequisites"] = new JsonArray() }); repository.Write("artifacts/accepted-plan.json", plan.ToJsonString()); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["run", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/accepted-plan.json"), "--output", repository.PathOf("artifacts/accepted")])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "run", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/accepted-plan.json"), + "--output", + repository.PathOf("artifacts/accepted") + ]) + ); JsonObject receipt = JsonNode.Parse(File.ReadAllText(repository.PathOf("artifacts/accepted/results.json")))!.AsObject(); - foreach (string change in new[] { "none", "environment", "tree", "commit", "checks", "configuration", "profile", "extended", "missing-result" }) - { + foreach (string change in new[] { + "none", + "environment", + "tree", + "commit", + "checks", + "configuration", + "profile", + "extended", + "missing-result" + }) { JsonObject current = plan.DeepClone().AsObject(); if (change is "environment" or "tree" or "commit" or "configuration") + { current[change] = "different"; + } else if (change == "checks") + { current["checks"]![0]!["reason"] = "Changed check contract"; + } else if (change == "profile") + { current["profile"] = 4; + } else if (change == "extended") + { current["extended"] = true; + } repository.Write("artifacts/current-plan.json", current.ToJsonString()); JsonObject evidence = receipt.DeepClone().AsObject(); if (change == "missing-result") + { evidence["results"] = new JsonArray(); + } repository.Write("artifacts/evidence.json", evidence.ToJsonString()); - Task Compare() => ValidationCommand.ExecuteAsync(["acceptance", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/current-plan.json"), "--accepted-plan", repository.PathOf("artifacts/accepted/plan.json"), - "--evidence", repository.PathOf("artifacts/evidence.json"), "--output", repository.PathOf("artifacts/comparison/" + change)]); + Task Compare() + => ValidationCommand.ExecuteAsync([ + "acceptance", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/current-plan.json"), + "--accepted-plan", + repository.PathOf("artifacts/accepted/plan.json"), + "--evidence", + repository.PathOf("artifacts/evidence.json"), + "--output", + repository.PathOf("artifacts/comparison/" + change) + ]); if (change == "missing-result") + { await Assert.ThrowsAsync(Compare); + } else { Assert.Equal(0, await Compare()); - using JsonDocument decision = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/comparison/" + change + "/acceptance.json"))); + using JsonDocument decision = JsonDocument.Parse( + File.ReadAllText(repository.PathOf("artifacts/comparison/" + change + "/acceptance.json")) + ); Assert.Equal(change == "none", decision.RootElement.GetProperty("reusable").GetBoolean()); } } @@ -324,16 +613,33 @@ public async Task FrozenPlanBindsAnotherCheckoutWithoutChangingItsIdentity() plan["checks"] = new JsonArray(policy); plan["shards"] = new JsonArray(new JsonObject { - ["id"] = "architecture", ["checks"] = new JsonArray("instructions"), ["prerequisites"] = new JsonArray() + ["id"] = "architecture", + ["checks"] = new JsonArray("instructions"), + ["prerequisites"] = new JsonArray() }); using var consumer = new ValidationRepository(producer.PathOf(".")); // Git checkout filters may change line endings. This transfer promises identical input bytes, not only a commit. foreach (JsonProperty input in generated.RootElement.GetProperty("inputs").EnumerateObject()) + { if (!input.Name.StartsWith('@') && File.Exists(producer.PathOf(input.Name))) + { consumer.Write(input.Name, File.ReadAllText(producer.PathOf(input.Name))); + } + } consumer.Write("artifacts/frozen.json", plan.ToJsonString()); - int exit = await ValidationCommand.ExecuteAsync(["run", "--engine-root", consumer.PathOf("."), "--dotnet", consumer.dotnet, - "--plan", consumer.PathOf("artifacts/frozen.json"), "--shard", "architecture", "--output", consumer.PathOf("artifacts/receipt")]); + int exit = await ValidationCommand.ExecuteAsync([ + "run", + "--engine-root", + consumer.PathOf("."), + "--dotnet", + consumer.dotnet, + "--plan", + consumer.PathOf("artifacts/frozen.json"), + "--shard", + "architecture", + "--output", + consumer.PathOf("artifacts/receipt") + ]); Assert.Equal(0, exit); using JsonDocument bound = JsonDocument.Parse(File.ReadAllBytes(consumer.PathOf("artifacts/receipt/execution-plan.json"))); Assert.Equal(consumer.PathOf("."), bound.RootElement.GetProperty("root").GetString()); @@ -346,26 +652,57 @@ public async Task FrozenPlanBindsAnotherCheckoutWithoutChangingItsIdentity() public async Task IndependentManagedExecutionRecordsExcludedNativeChecksWithoutOpeningTheirSdkContext() { using var repository = new ValidationRepository(); - repository.Write("tests/Native/Native.csproj", ValidationRepository.Project( - "trueeditornative")); + repository.Write( + "tests/Native/Native.csproj", + ValidationRepository.Project( + "trueeditornative" + ) + ); repository.Write("tests/ci/Test-AgentRules.ps1", "Write-Output 'Managed change'"); repository.Git("add", "."); repository.Git("commit", "-m", "Declare a separately deployed native test"); using JsonDocument generated = await repository.PlanAsync(profile: "fast", backendStore: "artifacts/b"); repository.Write("artifacts/packages.json", "[]"); string frozen = repository.PathOf("artifacts/bound.json"); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["bind-backends", "--packages", repository.PathOf("artifacts/packages.json"), - "--plan", repository.PathOf("artifacts/plan/plan.json"), "--engine-root", repository.PathOf("."), - "--dotnet", repository.dotnet, "--output", frozen])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "bind-backends", + "--packages", + repository.PathOf("artifacts/packages.json"), + "--plan", + repository.PathOf("artifacts/plan/plan.json"), + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--output", + frozen + ]) + ); JsonObject plan = JsonNode.Parse(File.ReadAllText(frozen))!.AsObject(); Assert.Null(plan["contexts"]!["native"]); - JsonNode excluded = plan["checks"]!.AsArray().Single(check => check!["id"]!.GetValue() == "test:tests/Native/Native.csproj")!; + JsonNode excluded = plan["checks"]! + .AsArray() + .Single(check => check!["id"]!.GetValue() == "test:tests/Native/Native.csproj")!; Assert.NotNull(excluded["exclusion"]); JsonNode policy = plan["checks"]!.AsArray().Single(check => check!["id"]!.GetValue() == "instructions")!; plan["checks"] = new JsonArray(policy.DeepClone(), excluded.DeepClone()); repository.Write("artifacts/selected.json", plan.ToJsonString()); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["run", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", repository.PathOf("artifacts/selected.json"), "--output", repository.PathOf("artifacts/executed")])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "run", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + repository.PathOf("artifacts/selected.json"), + "--output", + repository.PathOf("artifacts/executed") + ]) + ); using JsonDocument evidence = JsonDocument.Parse(File.ReadAllBytes(repository.PathOf("artifacts/executed/results.json"))); Assert.Equal("NotApplicable", evidence.RootElement.GetProperty("results")[1].GetProperty("status").GetString()); } @@ -377,7 +714,11 @@ public async Task IndependentShardReceiptsRequireCompleteExactCandidateCoverage( repository.Write("tests/ci/Test-AgentRules.ps1", "Write-Output 'Actual policy execution'"); using JsonDocument generated = await repository.PlanAsync(); JsonObject plan = JsonNode.Parse(generated.RootElement.GetRawText())!.AsObject(); - JsonObject policy = plan["checks"]!.AsArray().Single(check => check!["id"]!.GetValue() == "instructions")!.DeepClone().AsObject(); + JsonObject policy = plan["checks"]! + .AsArray() + .Single(check => check!["id"]!.GetValue() == "instructions")! + .DeepClone() + .AsObject(); JsonObject dependent = policy.DeepClone().AsObject(); dependent["id"] = "dependent-policy"; dependent["context"] = "managed"; @@ -385,49 +726,105 @@ public async Task IndependentShardReceiptsRequireCompleteExactCandidateCoverage( plan["checks"] = new JsonArray(policy, dependent); plan["shards"] = new JsonArray( new JsonObject { ["id"] = "architecture", ["checks"] = new JsonArray("instructions"), ["prerequisites"] = new JsonArray() }, - new JsonObject { ["id"] = "managed", ["checks"] = new JsonArray("dependent-policy"), ["prerequisites"] = new JsonArray("architecture") }); + new JsonObject + { + ["id"] = "managed", + ["checks"] = new JsonArray("dependent-policy"), + ["prerequisites"] = new JsonArray("architecture") + } + ); repository.Write("artifacts/frozen.json", plan.ToJsonString()); string frozen = repository.PathOf("artifacts/frozen.json"); await Execute("run", "--shard", "architecture", "--output", repository.PathOf("artifacts/receipts/architecture")); Assert.Equal("architecture", Read("artifacts/receipts/architecture/results.json")["shard"]!.GetValue()); - await Assert.ThrowsAsync(() => Execute("run", "--shard", "managed", "--output", repository.PathOf("artifacts/missing"))); - await Execute("run", "--shard", "managed", "--prerequisites", repository.PathOf("artifacts/receipts"), - "--output", repository.PathOf("artifacts/receipts/managed")); + await Assert.ThrowsAsync( + () => Execute("run", "--shard", "managed", "--output", repository.PathOf("artifacts/missing")) + ); + await Execute( + "run", + "--shard", + "managed", + "--prerequisites", + repository.PathOf("artifacts/receipts"), + "--output", + repository.PathOf("artifacts/receipts/managed") + ); JsonObject receipt = Read("artifacts/receipts/managed/results.json"); Assert.Single(receipt["results"]!.AsArray()); Assert.Equal("Passed", receipt["results"]![0]!["status"]!.GetValue()); - await Execute("join", "--prerequisites", repository.PathOf("artifacts/receipts"), "--output", repository.PathOf("artifacts/joined")); + await Execute( + "join", + "--prerequisites", + repository.PathOf("artifacts/receipts"), + "--output", + repository.PathOf("artifacts/joined") + ); JsonObject joined = Read("artifacts/joined/results.json"); Assert.True(joined["completed"]!.GetValue()); Assert.Null(joined["shard"]); Assert.Equal(2, joined["results"]!.AsArray().Count); - foreach (string damage in new[] { "commit", "environment", "planIdentity", "shard", "failed", "missing", "duplicate", "old-format", "run-failure" }) - { + foreach (string damage in new[] { + "commit", + "environment", + "planIdentity", + "shard", + "failed", + "missing", + "duplicate", + "old-format", + "run-failure" + }) { JsonObject changed = receipt.DeepClone().AsObject(); if (damage == "old-format") + { changed.Remove("version"); + } else if (damage == "run-failure") - changed["failures"] = new JsonArray(new JsonObject { ["stage"] = "test-execution", ["detail"] = "Shared test process exited with 1." }); + { + changed["failures"] = new JsonArray( + new JsonObject { ["stage"] = "test-execution", ["detail"] = "Shared test process exited with 1." } + ); + } else if (damage == "failed") + { changed["results"]![0]!["status"] = "Failed"; + } else if (damage == "missing") + { changed["results"] = new JsonArray(); + } else if (damage == "duplicate") + { changed["results"]!.AsArray().Add(changed["results"]![0]!.DeepClone()); + } else + { changed[damage] = "foreign"; + } repository.Write("artifacts/receipts/managed/results.json", changed.ToJsonString()); - await Assert.ThrowsAsync(() => Execute("join", "--prerequisites", repository.PathOf("artifacts/receipts"), - "--output", repository.PathOf("artifacts/rejected/" + damage))); + await Assert.ThrowsAsync(() => Execute( + "join", + "--prerequisites", + repository.PathOf("artifacts/receipts"), + "--output", + repository.PathOf("artifacts/rejected/" + damage) + )); } Task Execute( string operation, params string[] arguments - ) - => ValidationCommand.ExecuteAsync([operation, "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--plan", frozen, ..arguments]); + ) => ValidationCommand.ExecuteAsync([ + operation, + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + frozen, + ..arguments + ]); JsonObject Read(string relative) => JsonNode.Parse(File.ReadAllText(repository.PathOf(relative)))!.AsObject(); } diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationSolutionBuildTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationSolutionBuildTests.cs index 8c443dd23..e30a5112a 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationSolutionBuildTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationSolutionBuildTests.cs @@ -1,10 +1,10 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Linq; using System.Threading.Tasks; -using Inno.Testing.Source; using Xunit; +using Inno.Testing.Source; +using Inno.Testing.Validation; namespace Inno.Tooling.Validation.Integration.Tests; @@ -15,23 +15,38 @@ public async Task ParallelSolutionRootsShareOneFreshInvocationOwner() { using var repository = new ValidationRepository(); string source = TestRepository.GetRoot(typeof(ValidationSolutionBuildTests).Assembly); - foreach (string relative in new[] { "Directory.Solution.targets", "Directory.Build.targets", "build/msbuild/Inno.Build.Tasks.targets" }) + foreach (string relative in new[] { + "Directory.Solution.targets", + "Directory.Build.targets", + "build/msbuild/Inno.Build.Tasks.targets" + }) { repository.Write(relative, File.ReadAllText(Path.Combine(source, relative))); + } string targets = repository.PathOf("Directory.Build.targets"); - File.WriteAllText(targets, File.ReadAllText(targets).Replace("", """ + File.WriteAllText( + targets, + File.ReadAllText(targets).Replace("", """ - """, StringComparison.Ordinal)); + """, StringComparison.Ordinal) + ); repository.Write("src/Shared/Shared.csproj", ValidationRepository.Project()); repository.Write("src/Shared/Shared.cs", "namespace Shared; public static class Value { public static int Read() => 17; }"); foreach (string name in new[] { "RootA", "RootB" }) { - repository.Write("src/" + name + "/" + name + ".csproj", ValidationRepository.Project( - "")); - repository.Write("src/" + name + "/Value.cs", "namespace " + name + "; public static class Value { public static int Read() => Shared.Value.Read(); }"); + repository.Write( + "src/" + name + "/" + name + ".csproj", + ValidationRepository.Project( + "" + ) + ); + repository.Write( + "src/" + name + "/Value.cs", + "namespace " + name + "; public static class Value { public static int Read() => Shared.Value.Read(); }" + ); } repository.Write("artifacts/owners.slnx", """ @@ -41,11 +56,21 @@ public async Task ParallelSolutionRootsShareOneFreshInvocationOwner() { string traces = repository.PathOf("artifacts/owners-" + iteration); Directory.CreateDirectory(traces); - await repository.SdkAsync("build", "artifacts/owners.slnx", "-t:Rebuild", "--disable-build-servers", "-m:4", "-nr:false", - "-p:ArtifactsPath=" + repository.PathOf("artifacts/compilation"), "-p:InnoOwnerTraceDirectory=" + traces); + await repository.SdkAsync( + "build", + "artifacts/owners.slnx", + "-t:Rebuild", + "--disable-build-servers", + "-m:4", + "-nr:false", + "-p:ArtifactsPath=" + repository.PathOf("artifacts/compilation"), + "-p:InnoOwnerTraceDirectory=" + traces + ); string[] files = Directory.GetFiles(traces, "*.owner"); Assert.Equal(3, files.Length); - string owner = Assert.Single(files.Select(File.ReadAllText).Select(static value => value.Trim()).Distinct(StringComparer.Ordinal)); + string owner = Assert.Single( + files.Select(File.ReadAllText).Select(static value => value.Trim()).Distinct(StringComparer.Ordinal) + ); Assert.Matches("^[a-f0-9]{32}$", owner); Assert.NotEqual(previous, owner); Assert.Single(files.Where(path => Path.GetFileName(path).StartsWith("Shared.", StringComparison.Ordinal))); diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationSolutionTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationSolutionTests.cs index 2ef80ab85..53c563c43 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationSolutionTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationSolutionTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Linq; @@ -6,6 +5,7 @@ using System.Threading.Tasks; using System.Xml.Linq; using Xunit; +using Inno.Testing.Validation; namespace Inno.Tooling.Validation.Integration.Tests; @@ -18,13 +18,20 @@ public sealed class ValidationSolutionTests public async Task PlannedUnionBuildsOwnersExcludedByTheIdeSolution(string configuration) { using var repository = new ValidationRepository(); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project( - "")); - repository.Write("src/Other/Other.csproj", ValidationRepository.Project($""" + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project( + "" + ) + ); + repository.Write( + "src/Other/Other.csproj", + ValidationRepository.Project($""" - """)); + """) + ); repository.Write("InnoEngine.sln", """ Microsoft Visual Studio Solution File, Format Version 12.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example", "src/Example/Example.csproj", "{11111111-1111-1111-1111-111111111111}" @@ -47,15 +54,27 @@ public async Task PlannedUnionBuildsOwnersExcludedByTheIdeSolution(string config repository.Write("src/Example/Change.cs", "namespace Example; public sealed class Change { }"); using JsonDocument plan = await repository.PlanAsync(configuration: configuration); JsonElement context = plan.RootElement.GetProperty("contexts").GetProperty("managed"); - string[] properties = context.GetProperty("properties").EnumerateObject().Select(pair => "-p:" + pair.Name + "=" + repository.BindWorkspace(pair.Value.GetString()!)).ToArray(); - string target = context.GetProperty("sdkGraph").EnumerateArray().Single(snapshot => - repository.BindWorkspace(snapshot.GetProperty("Path").GetString()!) == repository.PathOf("src/Example/Example.csproj")) - .GetProperty("Properties").GetProperty("TargetPath").GetString()!; + string[] properties = context + .GetProperty("properties") + .EnumerateObject() + .Select(pair => "-p:" + pair.Name + "=" + repository.BindWorkspace(pair.Value.GetString()!)) + .ToArray(); + string target = context.GetProperty("sdkGraph") + .EnumerateArray() + .Single(snapshot => ( + repository.BindWorkspace(snapshot.GetProperty("Path").GetString()!) == repository.PathOf("src/Example/Example.csproj") + )) + .GetProperty("Properties") + .GetProperty("TargetPath") + .GetString()!; target = repository.BindWorkspace(target); - repository.Write("artifacts/ide.slnf", JsonSerializer.Serialize(new - { - solution = new { path = repository.PathOf("InnoEngine.sln"), projects = new[] { "src/Example/Example.csproj" } } - })); + repository.Write( + "artifacts/ide.slnf", + JsonSerializer.Serialize(new + { + solution = new { path = repository.PathOf("InnoEngine.sln"), projects = new[] { "src/Example/Example.csproj" } } + }) + ); await repository.BuildAsync([repository.PathOf("artifacts/ide.slnf"), ..properties]); Assert.False(File.Exists(target)); @@ -63,14 +82,25 @@ public async Task PlannedUnionBuildsOwnersExcludedByTheIdeSolution(string config await Assert.ThrowsAsync(() => repository.RunAsync()); string solution = repository.PathOf("artifacts/run/managed-Build.slnx"); XDocument union = XDocument.Load(solution); - string[] expected = plan.RootElement.GetProperty("checks").EnumerateArray() - .Where(check => check.GetProperty("kind").GetString() == "build" && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null) - .Select(check => repository.PathOf(check.GetProperty("owner").GetString()!)).Order(StringComparer.Ordinal).ToArray(); - Assert.Equal(expected, union.Descendants("Project").Select(project => Path.GetFullPath(project.Attribute("Path")!.Value)) - .Order(StringComparer.Ordinal).ToArray()); + string[] expected = plan.RootElement.GetProperty("checks") + .EnumerateArray() + .Where( + check => check.GetProperty("kind").GetString() == "build" && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null + ) + .Select(check => repository.PathOf(check.GetProperty("owner").GetString()!)) + .Order(StringComparer.Ordinal) + .ToArray(); + Assert.Equal( + expected, + union.Descendants("Project") + .Select(project => Path.GetFullPath(project.Attribute("Path")!.Value)) + .Order(StringComparer.Ordinal) + .ToArray() + ); Assert.Equal(configuration, union.Descendants("BuildType").Single().Attribute("Name")!.Value); - Assert.DoesNotContain(union.Descendants("Project"), project => - Path.GetFullPath(project.Attribute("Path")!.Value) == repository.PathOf("src/Other/Other.csproj")); + Assert.DoesNotContain(union.Descendants("Project"), project => ( + Path.GetFullPath(project.Attribute("Path")!.Value) == repository.PathOf("src/Other/Other.csproj") + )); Assert.False(File.Exists(target)); await repository.BuildAsync([solution, ..properties]); Assert.True(File.Exists(target)); diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/BackendInputTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/BackendInputTests.cs index dd2a7cb14..71813cfb0 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/BackendInputTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/BackendInputTests.cs @@ -4,8 +4,8 @@ using System.Text; using System.Text.Json; using System.Threading.Tasks; -using Inno.Testing.Validation; using Xunit; +using Inno.Testing.Validation; namespace Inno.Tooling.Validation.Tests; @@ -17,8 +17,12 @@ public async Task BindingRejectsMissingOwnersAndChangedInventoryBeforeWritingThe using var repository = new ValidationRepository(); const string C_STORE = "artifacts/backend-packages"; const string C_PROJECT = "backends/Probe/Probe.csproj"; - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "fixture")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "fixture" + ) + ); repository.Write(C_PROJECT, ValidationRepository.Project()); repository.Git("add", "."); repository.Git("commit", "-m", "Register host and backend"); @@ -28,17 +32,44 @@ public async Task BindingRejectsMissingOwnersAndChangedInventoryBeforeWritingThe await Assert.ThrowsAsync(Bind); Assert.False(File.Exists(repository.PathOf(C_STORE + "/selection.json"))); string inputPath = repository.PathOf("artifacts/current.json"); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["backend-inputs", "--target", "fixture", - "--plan", repository.PathOf("artifacts/plan/plan.json"), "--engine-root", repository.PathOf("."), - "--dotnet", repository.dotnet, "--output", inputPath])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "backend-inputs", + "--target", + "fixture", + "--plan", + repository.PathOf("artifacts/plan/plan.json"), + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--output", + inputPath + ]) + ); using JsonDocument inputs = JsonDocument.Parse(File.ReadAllBytes(inputPath)); string input = inputs.RootElement.GetProperty("projects").GetProperty(C_PROJECT).GetString()!; string native = """{"assets":[],"aggregates":[],"requests":[]}"""; - string inventory = JsonSerializer.Serialize(new { target = "fixture", files = new[] { - new { owner = "fixture", configuration = "all", input = Digest(native), path = "native/selection.json", sha256 = Digest(native) }, - new { owner = C_PROJECT, configuration = "Debug", input, path = "managed/probe.dll", sha256 = Digest("probe") } - } }); - string receipt = JsonSerializer.Serialize(new { target = "fixture", sha256 = Digest("archive"), manifestSha256 = Digest(inventory) }); + string inventory = JsonSerializer.Serialize(new + { + target = "fixture", + files = new[] + { + new + { + owner = "fixture", + configuration = "all", + input = Digest(native), + path = "native/selection.json", + sha256 = Digest(native) + }, + new { owner = C_PROJECT, configuration = "Debug", input, path = "managed/probe.dll", sha256 = Digest("probe") } + } + }); + string receipt = JsonSerializer.Serialize( + new { target = "fixture", sha256 = Digest("archive"), manifestSha256 = Digest(inventory) } + ); repository.Write("artifacts/packages.json", "[" + receipt + "]"); repository.Write(C_STORE + "/fixture/receipt.json", receipt); repository.Write(C_STORE + "/fixture/native/selection.json", native); @@ -51,9 +82,20 @@ public async Task BindingRejectsMissingOwnersAndChangedInventoryBeforeWritingThe Assert.Equal("fixture/Debug/" + C_PROJECT, Assert.Single(owners.EnumerateObject()).Name); Assert.Equal(Digest("archive"), bound.RootElement.GetProperty("backendPackages")[0].GetProperty("sha256").GetString()); - Task Bind() => ValidationCommand.ExecuteAsync(["bind-backends", "--packages", repository.PathOf("artifacts/packages.json"), - "--plan", repository.PathOf("artifacts/plan/plan.json"), "--engine-root", repository.PathOf("."), - "--dotnet", repository.dotnet, "--output", repository.PathOf("artifacts/bound.json")]); + Task Bind() + => ValidationCommand.ExecuteAsync([ + "bind-backends", + "--packages", + repository.PathOf("artifacts/packages.json"), + "--plan", + repository.PathOf("artifacts/plan/plan.json"), + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--output", + repository.PathOf("artifacts/bound.json") + ]); static string Digest(string value) => System.Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(value))); } @@ -61,40 +103,85 @@ Task Bind() => ValidationCommand.ExecuteAsync(["bind-backends", "--packages [InlineData("Debug", true)] [InlineData("Release", false)] public async Task ProductCoverageUsesTheRequestedConfigurationWhenItsOnlyToolIsAlwaysRelease( - string certifiedConfiguration, bool expected + string certifiedConfiguration, + bool expected ) { using var repository = new ValidationRepository(); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "fixture-target" - + repository.PathOf("Product.props") + "")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "fixture-target" + + repository.PathOf("Product.props") + "" + ) + ); repository.Write("Product.props", ""); - repository.Write("tests/Tool.Tests/Tool.Tests.csproj", ValidationRepository.Project( - "truenative" - + "tool-onlyfixture-target")); + repository.Write( + "tests/Tool.Tests/Tool.Tests.csproj", + ValidationRepository.Project( + "truenative" + + "tool-onlyfixture-target" + ) + ); using JsonDocument plan = await repository.PlanAsync(); - Assert.Contains(plan.RootElement.GetProperty("nativeRequests").EnumerateArray(), request => - request.GetProperty("product").GetString() == "tool-only" && request.GetProperty("configuration").GetString() == "Debug"); + Assert.Contains(plan.RootElement.GetProperty("nativeRequests").EnumerateArray(), request => ( + request.GetProperty("product").GetString() == "tool-only" && request.GetProperty("configuration").GetString() == "Debug" + )); string digest = new('a', 64); WriteSelection(digest); string output = repository.PathOf("artifacts/inputs.json"); Assert.Equal(0, await Evaluate()); using JsonDocument inputs = JsonDocument.Parse(File.ReadAllBytes(output)); - Assert.Equal(!expected, inputs.RootElement.GetProperty("missingNativeProducts").EnumerateArray().Any(item => item.GetString() == "tool-only")); + Assert.Equal( + !expected, + inputs.RootElement.GetProperty("missingNativeProducts").EnumerateArray().Any(item => item.GetString() == "tool-only") + ); if (expected) { WriteSelection(new string('b', 64)); await Assert.ThrowsAsync(() => Evaluate()); } - void WriteSelection(string certifiedDigest) => repository.Write("artifacts/native.json", JsonSerializer.Serialize(new { - assets = System.Array.Empty(), - aggregates = new[] { new { product = "tool-only", target = "fixture-target", configuration = "release", sha256 = digest } }, - requests = new[] { new { product = "tool-only", target = "fixture-target", configuration = certifiedConfiguration, digests = new[] { certifiedDigest } } } - })); + void WriteSelection(string certifiedDigest) + => repository.Write( + "artifacts/native.json", + JsonSerializer.Serialize(new + { + assets = System.Array.Empty(), + aggregates = new[] + { + new { product = "tool-only", target = "fixture-target", configuration = "release", sha256 = digest } + }, + requests = new[] + { + new + { + product = "tool-only", + target = "fixture-target", + configuration = certifiedConfiguration, + digests = new[] { certifiedDigest } + } + } + }) + ); - Task Evaluate() => ValidationCommand.ExecuteAsync(["backend-inputs", "--plan", repository.PathOf("artifacts/plan/plan.json"), - "--target", "fixture-target", "--configuration", "Debug", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--selection", repository.PathOf("artifacts/native.json"), "--output", output]); + Task Evaluate() + => ValidationCommand.ExecuteAsync([ + "backend-inputs", + "--plan", + repository.PathOf("artifacts/plan/plan.json"), + "--target", + "fixture-target", + "--configuration", + "Debug", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--selection", + repository.PathOf("artifacts/native.json"), + "--output", + output + ]); } [Fact] @@ -104,9 +191,22 @@ public async Task PureManagedChecksBindAnEmptyAcquisition() repository.Write("src/Example/Changed.cs", "class ManagedChange {}"); using JsonDocument plan = await repository.PlanAsync(profile: "fast", backendStore: "artifacts/backend-packages"); repository.Write("artifacts/packages.json", "[]"); - Assert.Equal(0, await ValidationCommand.ExecuteAsync(["bind-backends", "--packages", repository.PathOf("artifacts/packages.json"), - "--plan", repository.PathOf("artifacts/plan/plan.json"), "--engine-root", repository.PathOf("."), - "--dotnet", repository.dotnet, "--output", repository.PathOf("artifacts/bound.json")])); + Assert.Equal( + 0, + await ValidationCommand.ExecuteAsync([ + "bind-backends", + "--packages", + repository.PathOf("artifacts/packages.json"), + "--plan", + repository.PathOf("artifacts/plan/plan.json"), + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--output", + repository.PathOf("artifacts/bound.json") + ]) + ); using JsonDocument bound = JsonDocument.Parse(File.ReadAllBytes(repository.PathOf("artifacts/bound.json"))); Assert.Empty(bound.RootElement.GetProperty("backendPackages").EnumerateArray()); } @@ -118,12 +218,18 @@ public async Task TestEditsRetainCompilerInputsAndSharedProductionChangesReachTh const string C_BACKEND = "backends/Probe/Probe.csproj"; const string C_INDEPENDENT = "backends/Independent/Independent.csproj"; const string C_TEST = "tests/backends/Probe.Tests/Probe.Tests.csproj"; - repository.Write(C_BACKEND, ValidationRepository.Project("")); + repository.Write( + C_BACKEND, + ValidationRepository.Project("") + ); repository.Write(C_INDEPENDENT, ValidationRepository.Project()); - repository.Write(C_TEST, ValidationRepository.Project(""" + repository.Write( + C_TEST, + ValidationRepository.Project(""" truedomain - """)); + """) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Add the backend fixture"); using JsonDocument baseline = await Inputs(repository); @@ -134,7 +240,10 @@ public async Task TestEditsRetainCompilerInputsAndSharedProductionChangesReachTh Assert.Equal(original, Identity(testOnly, C_BACKEND)); Assert.Equal(independent, Identity(testOnly, C_INDEPENDENT)); Assert.Equal(new[] { C_TEST }, testOnly.RootElement.GetProperty("tests").EnumerateArray().Select(static item => item.GetString())); - Assert.Equal(new[] { C_BACKEND }, testOnly.RootElement.GetProperty("required").EnumerateArray().Select(static item => item.GetString())); + Assert.Equal( + new[] { C_BACKEND }, + testOnly.RootElement.GetProperty("required").EnumerateArray().Select(static item => item.GetString()) + ); repository.Write("src/Example/Changed.cs", "public class NewContract {}"); using JsonDocument changed = await Inputs(repository); Assert.NotEqual(original, Identity(changed, C_BACKEND)); @@ -151,9 +260,12 @@ public async Task PlatformBuildDefinitionsAffectTheirImportsAndCopies() const string C_PROPS = "backends/Tool/Platform.props"; repository.Write(C_TOOL, ValidationRepository.Project()); repository.Write(C_IMPORT, ValidationRepository.Project("""""")); - repository.Write(C_COPY, ValidationRepository.Project(""" + repository.Write( + C_COPY, + ValidationRepository.Project(""" - """)); + """) + ); repository.Write(C_PROPS, ""); repository.Git("add", "."); repository.Git("commit", "-m", "Add the platform build definition"); @@ -174,10 +286,13 @@ public async Task NewPlatformProductDerivesItsConsumersFromItsRegisteredSdkEntry const string player = "platforms/Fixture/player/Player.csproj"; repository.Write(backend, ValidationRepository.Project()); repository.Write("backends/Unrelated/Unrelated.csproj", ValidationRepository.Project()); - repository.Write(player, ValidationRepository.Project(""" + repository.Write( + player, + ValidationRepository.Project(""" playerfixture - """)); + """) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Register the fixture product"); using JsonDocument first = await Inputs(repository); @@ -185,20 +300,35 @@ public async Task NewPlatformProductDerivesItsConsumersFromItsRegisteredSdkEntry Assert.Equal(backend, Assert.Single(before.GetProperty("backendOwners").EnumerateArray()).GetString()); repository.Write("backends/Unrelated/Change.cs", "class Unrelated {}"); using JsonDocument unrelated = await Inputs(repository); - Assert.Equal(before.GetProperty("identity").GetString(), - unrelated.RootElement.GetProperty("consumers").GetProperty(player).GetProperty("identity").GetString()); + Assert.Equal( + before.GetProperty("identity").GetString(), + unrelated.RootElement.GetProperty("consumers").GetProperty(player).GetProperty("identity").GetString() + ); repository.Write("backends/NewAdapter/Change.cs", "class Changed {}"); using JsonDocument affected = await Inputs(repository); - Assert.NotEqual(before.GetProperty("identity").GetString(), - affected.RootElement.GetProperty("consumers").GetProperty(player).GetProperty("identity").GetString()); + Assert.NotEqual( + before.GetProperty("identity").GetString(), + affected.RootElement.GetProperty("consumers").GetProperty(player).GetProperty("identity").GetString() + ); } private static async Task Inputs(ValidationRepository repository) { using JsonDocument plan = await repository.PlanAsync(profile: "fast"); string output = repository.PathOf("artifacts/backend-inputs.json"); - int code = await ValidationCommand.ExecuteAsync(["backend-inputs", "--plan", repository.PathOf("artifacts/plan/plan.json"), - "--target", "fixture", "--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, "--output", output]); + int code = await ValidationCommand.ExecuteAsync([ + "backend-inputs", + "--plan", + repository.PathOf("artifacts/plan/plan.json"), + "--target", + "fixture", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--output", + output + ]); Assert.Equal(0, code); return JsonDocument.Parse(File.ReadAllBytes(output)); } diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationInputTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationInputTests.cs index 182e8bd1e..3f8ad4be7 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationInputTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationInputTests.cs @@ -1,11 +1,11 @@ -using Inno.Testing.Validation; using System.IO; using System.Linq; using System.Text.Json; using System.Text.Json.Nodes; using System.Threading.Tasks; -using Inno.Tooling.Documentation; using Xunit; +using Inno.Testing.Validation; +using Inno.Tooling.Documentation; namespace Inno.Tooling.Validation.Tests; @@ -17,11 +17,19 @@ public async Task EmptyForeignSurfaceRetainsSourceProofWithoutRestoringOrBuildin using var repository = new ValidationRepository(); const string C_FOREIGN = "src/Foreign/Foreign.Player/Foreign.Player.csproj"; repository.Write("Product.props", ""); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "host-fixture" - + repository.PathOf("Product.props") + "")); - repository.Write(C_FOREIGN, ValidationRepository.Project( - "playerforeign-fixture")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "host-fixture" + + repository.PathOf("Product.props") + "" + ) + ); + repository.Write( + C_FOREIGN, + ValidationRepository.Project( + "playerforeign-fixture" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare the foreign source-only product boundary"); var docs = new ValidationDocumentationFixture(repository); @@ -32,13 +40,18 @@ public async Task EmptyForeignSurfaceRetainsSourceProofWithoutRestoringOrBuildin repository.Write("src/Example/Changed.cs", "namespace Example; internal sealed class Changed { }"); using JsonDocument planned = await docs.PlanAsync(await docs.IndexAsync()); JsonNode execution = JsonNode.Parse(planned.RootElement.GetRawText())!; - execution["checks"] = new JsonArray(planned.RootElement.GetProperty("checks").EnumerateArray() - .Where(check => check.GetProperty("id").GetString() is "documentation" or "documentation-api:source:default") - .Select(check => JsonNode.Parse(check.GetRawText())).ToArray()); + execution["checks"] = new JsonArray( + planned.RootElement.GetProperty("checks") + .EnumerateArray() + .Where(check => check.GetProperty("id").GetString() is "documentation" or "documentation-api:source:default") + .Select(check => JsonNode.Parse(check.GetRawText())) + .ToArray() + ); repository.Write("artifacts/plan/plan.json", execution.ToJsonString()); Assert.Equal(0, await repository.RunAsync()); using JsonDocument result = JsonDocument.Parse(File.ReadAllBytes(repository.PathOf("artifacts/run/results.json"))); - JsonElement source = result.RootElement.GetProperty("results").EnumerateArray() + JsonElement source = result.RootElement.GetProperty("results") + .EnumerateArray() .Single(check => check.GetProperty("id").GetString() == "documentation-api:source:default"); Assert.Equal("Passed", source.GetProperty("status").GetString()); JsonElement proof = Assert.Single(source.GetProperty("documentationInputs").EnumerateArray()); diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs index 9f15f9f9b..8808821c9 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Linq; @@ -7,8 +6,9 @@ using System.Text.Json; using System.Text.Json.Nodes; using System.Threading.Tasks; -using Inno.Tooling.Documentation; using Xunit; +using Inno.Testing.Validation; +using Inno.Tooling.Documentation; namespace Inno.Tooling.Validation.Tests; @@ -27,7 +27,9 @@ public async Task PlatformProvenanceDoesNotRequireReaderEntriesButRequiredOwners var docs = new ValidationDocumentationFixture(repository); docs.Initialize(); if (missingEntry) + { docs.Write("content/en/Other.md", ValidationDocumentationFixture.Page("Other", "This is not a project entry.")); + } DocumentationResult indexed = await docs.IndexAsync(); using (DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(docs.cache, indexed.snapshot)) { @@ -41,9 +43,13 @@ public async Task PlatformProvenanceDoesNotRequireReaderEntriesButRequiredOwners Assert.True(plan.RootElement.GetProperty("inputSets").TryGetProperty(C_PLATFORM, out _)); // Execute this real catalog obligation independently of unrelated build/test prerequisites. JsonNode execution = JsonNode.Parse(plan.RootElement.GetRawText())!; - execution["checks"] = new JsonArray(plan.RootElement.GetProperty("checks").EnumerateArray() - .Where(check => check.GetProperty("id").GetString() == "documentation") - .Select(check => JsonNode.Parse(check.GetRawText())).ToArray()); + execution["checks"] = new JsonArray( + plan.RootElement.GetProperty("checks") + .EnumerateArray() + .Where(check => check.GetProperty("id").GetString() == "documentation") + .Select(check => JsonNode.Parse(check.GetRawText())) + .ToArray() + ); repository.Write("artifacts/plan/plan.json", execution.ToJsonString()); if (missingEntry) { @@ -54,7 +60,9 @@ public async Task PlatformProvenanceDoesNotRequireReaderEntriesButRequiredOwners Assert.Equal("Required canonical project entries are missing: Other", check.GetProperty("detail").GetString()); } else + { Assert.Equal(0, await repository.RunAsync()); + } } [Fact] @@ -63,14 +71,21 @@ public async Task ProjectedReferenceChangesSelectTheirCompilerAndIgnoreUnrelated using var repository = new ValidationRepository(); repository.Write("Product.props", ""); repository.Write("entry/InnoEngine.Build/InnoEngine.Build.csproj", ValidationRepository.Project()); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "editorfixture-target" - + repository.PathOf("Product.props") + "")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "editorfixture-target" + + repository.PathOf("Product.props") + "" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare the actual projection hosts"); var docs = new ValidationDocumentationFixture(repository); docs.Initialize(); - docs.Write("content/en/script.md", ValidationDocumentationFixture.Page("Example", "```csharp\nint value = 1;\n```\n", "runtime-script")); + docs.Write( + "content/en/script.md", + ValidationDocumentationFixture.Page("Example", "```csharp\nint value = 1;\n```\n", "runtime-script") + ); string root = repository.PathOf("artifacts/docs-source"); JsonNode inventory = JsonNode.Parse(File.ReadAllBytes(Path.Combine(root, "reference/projects/catalog.json")))!; inventory.AsArray().Single(owner => owner!["name"]!.GetValue() == "Example")!["surfaces"]!.AsArray().Add("runtime-script"); @@ -78,30 +93,46 @@ public async Task ProjectedReferenceChangesSelectTheirCompilerAndIgnoreUnrelated docs.Write("reference/projects/catalog.json", Encoding.UTF8.GetString(inventoryBytes)); JsonNode binding = JsonNode.Parse(File.ReadAllBytes(Path.Combine(root, "reference/engine.lock.json")))!; binding["projectManifestIdentity"] = Convert.ToHexStringLower(SHA256.HashData(inventoryBytes)); - binding["apiManifests"]!.AsArray().Add(JsonSerializer.SerializeToNode(new - { - path = "reference/api/scripts.json", model = "runtime-script", configuration = "Debug", - sourceRevision = new string('a', 40), sourceTree = new string('b', 40), sha256 = "" - })); + binding["apiManifests"]!.AsArray().Add( + JsonSerializer.SerializeToNode(new + { + path = "reference/api/scripts.json", + model = "runtime-script", + configuration = "Debug", + sourceRevision = new string('a', 40), + sourceTree = new string('b', 40), + sha256 = "" + }) + ); BindProjection("before"); DocumentationResult baseline = await docs.IndexAsync(); BindProjection("after"); DocumentationResult current = await docs.IndexAsync(); using JsonDocument plan = await docs.PlanAsync(current, baseline); - JsonElement check = plan.RootElement.GetProperty("checks").EnumerateArray() + JsonElement check = plan.RootElement.GetProperty("checks") + .EnumerateArray() .Single(candidate => candidate.GetProperty("id").GetString() == "documentation-examples:native"); - Assert.Contains("build:entry/InnoEngine.Build/InnoEngine.Build.csproj", check.GetProperty("prerequisites").EnumerateArray().Select(static value => value.GetString())); - Assert.Contains("reference/api/scripts.json", check.GetProperty("documentation").GetProperty("references").EnumerateArray().Select(static value => value.GetString())); + Assert.Contains( + "build:entry/InnoEngine.Build/InnoEngine.Build.csproj", + check.GetProperty("prerequisites").EnumerateArray().Select(static value => value.GetString()) + ); + Assert.Contains( + "reference/api/scripts.json", + check.GetProperty("documentation").GetProperty("references").EnumerateArray().Select(static value => value.GetString()) + ); string identity = check.GetProperty("documentation").GetProperty("contentIdentity").GetString()!; JsonNode sourceFacts = JsonNode.Parse(File.ReadAllBytes(Path.Combine(root, "reference/api/facts.json")))!; - sourceFacts["projects"]!.AsArray().Single(owner => owner!["name"]!.GetValue() == "Other")!["symbols"]!.AsArray() + sourceFacts["projects"]!.AsArray() + .Single(owner => owner!["name"]!.GetValue() == "Other")!["symbols"]! + .AsArray() .Add(JsonSerializer.SerializeToNode(new { id = "T:Other.Added" })); byte[] factsBytes = JsonSerializer.SerializeToUtf8Bytes(sourceFacts); docs.Write("reference/api/facts.json", Encoding.UTF8.GetString(factsBytes)); binding["apiManifests"]![0]!["sha256"] = Convert.ToHexStringLower(SHA256.HashData(factsBytes)); docs.Write("reference/engine.lock.json", binding.ToJsonString()); using JsonDocument unrelated = await docs.PlanAsync(await docs.IndexAsync(), baseline); - JsonElement same = unrelated.RootElement.GetProperty("checks").EnumerateArray() + JsonElement same = unrelated.RootElement.GetProperty("checks") + .EnumerateArray() .Single(candidate => candidate.GetProperty("id").GetString() == "documentation-examples:native"); Assert.Equal(identity, same.GetProperty("documentation").GetProperty("contentIdentity").GetString()); @@ -109,9 +140,16 @@ void BindProjection(string signature) { byte[] facts = JsonSerializer.SerializeToUtf8Bytes(new { - model = "runtime-script", configuration = "Debug", projects = new[] + model = "runtime-script", + configuration = "Debug", + projects = new[] { - new { project = "src/Example/Example.csproj", name = "Example", symbols = new[] { new { id = "T:Logical.Example", signature } } } + new + { + project = "src/Example/Example.csproj", + name = "Example", + symbols = new[] { new { id = "T:Logical.Example", signature } } + } } }); docs.Write("reference/api/scripts.json", Encoding.UTF8.GetString(facts)); @@ -130,8 +168,12 @@ public async Task AgentTextChangesKeepProductAndInstructionEvidenceSeparate( bool policyInput ) { using var repository = new ValidationRepository(); - repository.Write("tests/Native.Tests/Native.Tests.csproj", ValidationRepository.Project( - "truenativeeditor")); + repository.Write( + "tests/Native.Tests/Native.Tests.csproj", + ValidationRepository.Project( + "truenativeeditor" + ) + ); repository.Write(path, "before"); repository.Git("add", "."); repository.Git("commit", "-m", "Declare agent document and native sentinel"); @@ -145,7 +187,10 @@ bool policyInput Assert.DoesNotContain(checks, check => check.GetProperty("id").GetString() == "documentation"); JsonElement instructions = checks.Single(check => check.GetProperty("id").GetString() == "instructions"); Assert.Equal(policyInput, instructions.GetProperty("inputs").EnumerateArray().Any(input => input.GetString() == path)); - Assert.DoesNotContain(plan.RootElement.GetProperty("inputSets").GetProperty("tooling").EnumerateArray(), input => input.GetString() == path); + Assert.DoesNotContain( + plan.RootElement.GetProperty("inputSets").GetProperty("tooling").EnumerateArray(), + input => input.GetString() == path + ); } [Fact] @@ -154,23 +199,39 @@ public async Task CanonicalFragmentOwnersSelectOnlyTheirDeclaredExampleContext() using var repository = new ValidationRepository(); DocumentationResult snapshot = await PrepareDocumentationAsync(repository); repository.Write("src/Example/Changed.cs", "namespace Example; public class Changed { }"); - using JsonDocument plan = await repository.PlanAsync(documentationCache: repository.PathOf("artifacts/documentation"), documentationSnapshot: snapshot.snapshot); + using JsonDocument plan = await repository.PlanAsync( + documentationCache: repository.PathOf("artifacts/documentation"), + documentationSnapshot: snapshot.snapshot + ); JsonElement[] checks = plan.RootElement.GetProperty("checks").EnumerateArray().ToArray(); - Assert.Contains(checks, check => check.GetProperty("kind").GetString() == "build" - && check.GetProperty("owner").GetString() == "src/Example/Example.csproj"); - Assert.DoesNotContain(checks, check => check.GetProperty("kind").GetString() == "build" - && check.GetProperty("owner").GetString() == "src/Other/Other.csproj"); + Assert.Contains(checks, check => ( + check.GetProperty("kind").GetString() == "build" + && check.GetProperty("owner").GetString() == "src/Example/Example.csproj" + )); + Assert.DoesNotContain(checks, check => ( + check.GetProperty("kind").GetString() == "build" + && check.GetProperty("owner").GetString() == "src/Other/Other.csproj" + )); Assert.DoesNotContain(checks, check => check.GetProperty("kind").GetString() == "wiki"); JsonElement examples = checks.Single(check => check.GetProperty("kind").GetString() == "documentation-examples"); - Assert.Equal("task-fragment", Assert.Single(examples.GetProperty("documentation").GetProperty("pages").EnumerateArray()).GetString()); + Assert.Equal( + "task-fragment", + Assert.Single(examples.GetProperty("documentation").GetProperty("pages").EnumerateArray()).GetString() + ); JsonElement api = checks.Single(check => check.GetProperty("kind").GetString() == "documentation-api"); Assert.Equal("src/Example/Example.csproj", Assert.Single(api.GetProperty("projects").EnumerateArray()).GetString()); Assert.False(plan.RootElement.GetProperty("contexts").TryGetProperty("native", out _)); File.Delete(repository.PathOf("artifacts/docs-source/content/en/random/behavior.md")); - using JsonDocument retained = await repository.PlanAsync(documentationCache: repository.PathOf("artifacts/documentation"), documentationSnapshot: snapshot.snapshot); + using JsonDocument retained = await repository.PlanAsync( + documentationCache: repository.PathOf("artifacts/documentation"), + documentationSnapshot: snapshot.snapshot + ); Assert.Equal(snapshot.snapshot, retained.RootElement.GetProperty("documentation").GetProperty("snapshot").GetString()); - await Assert.ThrowsAsync(() => DocumentationStore.IndexAsync(repository.PathOf("."), - repository.PathOf("artifacts/docs-source"), repository.PathOf("artifacts/documentation"))); + await Assert.ThrowsAsync(() => DocumentationStore.IndexAsync( + repository.PathOf("."), + repository.PathOf("artifacts/docs-source"), + repository.PathOf("artifacts/documentation") + )); } [Fact] @@ -180,33 +241,68 @@ public async Task SharedHostAndScriptExamplesUseOnePreparedContextWithoutPromoti repository.Write("Product.props", ""); repository.Write("entry/InnoEngine.Build/InnoEngine.Build.csproj", ValidationRepository.Project()); repository.Write("src/Independent/Independent.csproj", ValidationRepository.Project()); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "editorfixture-target" - + repository.PathOf("Product.props") + "")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "editorfixture-target" + + repository.PathOf("Product.props") + "" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare independently prepared example owners"); var docs = new ValidationDocumentationFixture(repository); docs.Initialize(); DocumentationResult baseline = await docs.IndexAsync(); - docs.Write("content/en/script.md", ValidationDocumentationFixture.Page("Example", "```csharp\nint value = 1;\n```\n", "runtime-script")); - docs.Write("content/en/host.md", ValidationDocumentationFixture.Page("Example", "```csharp\nint value = 1;\n```\n", "host") - .Replace("uid: task-example", "uid: task-host", StringComparison.Ordinal)); - docs.Write("content/en/shared.md", ValidationDocumentationFixture.Page("Other", "```csharp\nint value = 1;\n```\n", "host") - .Replace("exampleProjects: [Other]", "exampleProjects: [Other, Example]", StringComparison.Ordinal)); - docs.Write("content/en/independent.md", ValidationDocumentationFixture.Page("Independent", "```csharp\nint value = 1;\n```\n", "host")); + docs.Write( + "content/en/script.md", + ValidationDocumentationFixture.Page("Example", "```csharp\nint value = 1;\n```\n", "runtime-script") + ); + docs.Write( + "content/en/host.md", + ValidationDocumentationFixture.Page("Example", "```csharp\nint value = 1;\n```\n", "host") + .Replace("uid: task-example", "uid: task-host", StringComparison.Ordinal) + ); + docs.Write( + "content/en/shared.md", + ValidationDocumentationFixture.Page("Other", "```csharp\nint value = 1;\n```\n", "host") + .Replace("exampleProjects: [Other]", "exampleProjects: [Other, Example]", StringComparison.Ordinal) + ); + docs.Write( + "content/en/independent.md", + ValidationDocumentationFixture.Page("Independent", "```csharp\nint value = 1;\n```\n", "host") + ); using JsonDocument plan = await docs.PlanAsync(await docs.IndexAsync(), baseline); JsonElement[] checks = plan.RootElement.GetProperty("checks").EnumerateArray().ToArray(); JsonElement native = checks.Single(check => check.GetProperty("id").GetString() == "documentation-examples:native"); - Assert.Equal(new[] { "task-example", "task-host", "task-other" }, native.GetProperty("documentation").GetProperty("pages").EnumerateArray().Select(page => page.GetString()).Order().ToArray()); + Assert.Equal( + new[] { "task-example", "task-host", "task-other" }, + native.GetProperty("documentation").GetProperty("pages").EnumerateArray().Select(page => page.GetString()).Order().ToArray() + ); JsonElement managed = checks.Single(check => check.GetProperty("id").GetString() == "documentation-examples:managed"); - Assert.Equal("task-independent", Assert.Single(managed.GetProperty("documentation").GetProperty("pages").EnumerateArray()).GetString()); + Assert.Equal( + "task-independent", + Assert.Single(managed.GetProperty("documentation").GetProperty("pages").EnumerateArray()).GetString() + ); foreach (string owner in new[] { "Example", "Other", "Independent" }) - Assert.Equal(owner == "Independent" ? "managed" : "native", checks.Single(check => check.GetProperty("id").GetString() == $"build:src/{owner}/{owner}.csproj").GetProperty("context").GetString()); + { + Assert.Equal( + owner == "Independent" ? "managed" : "native", + checks + .Single(check => check.GetProperty("id").GetString() == $"build:src/{owner}/{owner}.csproj") + .GetProperty("context") + .GetString() + ); + } var preceding = new System.Collections.Generic.HashSet(StringComparer.Ordinal); foreach (JsonElement check in checks) { if (check.GetProperty("exclusion").ValueKind == JsonValueKind.Null) - Assert.All(check.GetProperty("prerequisites").EnumerateArray(), prerequisite => Assert.Contains(prerequisite.GetString()!, preceding)); + { + Assert.All( + check.GetProperty("prerequisites").EnumerateArray(), + prerequisite => Assert.Contains(prerequisite.GetString()!, preceding) + ); + } preceding.Add(check.GetProperty("id").GetString()!); } } @@ -217,11 +313,19 @@ public async Task EmptyForeignProductSurfaceDoesNotClaimForeignExecutionOrRequir using var repository = new ValidationRepository(); const string C_FOREIGN = "src/Foreign/Foreign.Player/Foreign.Player.csproj"; repository.Write("Product.props", ""); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "host-fixture" - + repository.PathOf("Product.props") + "")); - repository.Write(C_FOREIGN, ValidationRepository.Project( - "playerforeign-fixture")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "host-fixture" + + repository.PathOf("Product.props") + "" + ) + ); + repository.Write( + C_FOREIGN, + ValidationRepository.Project( + "playerforeign-fixture" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare an internal foreign product entry"); var docs = new ValidationDocumentationFixture(repository); @@ -237,8 +341,10 @@ public async Task EmptyForeignProductSurfaceDoesNotClaimForeignExecutionOrRequir Assert.Contains(C_FOREIGN, source.GetProperty("inputs").EnumerateArray().Select(value => value.GetString())); JsonElement foreignBuild = checks.Single(check => check.GetProperty("id").GetString() == "build:" + C_FOREIGN); Assert.Contains("requires its own supported target", foreignBuild.GetProperty("exclusion").GetString()); - Assert.Contains(checks, check => check.GetProperty("id").GetString() == "test:tests/Example.Tests/Example.Tests.csproj" - && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null); + Assert.Contains(checks, check => ( + check.GetProperty("id").GetString() == "test:tests/Example.Tests/Example.Tests.csproj" + && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null + )); } [Fact] @@ -249,10 +355,15 @@ public async Task EngineChangesDoNotRequireADocumentationCandidateOrReadAnOldWik repository.Write("src/Example/Changed.cs", "namespace Example; public class Changed { }"); using JsonDocument plan = await repository.PlanAsync(); JsonElement[] checks = plan.RootElement.GetProperty("checks").EnumerateArray().ToArray(); - Assert.DoesNotContain(checks, check => check.GetProperty("kind").GetString()!.StartsWith("documentation", StringComparison.Ordinal)); + Assert.DoesNotContain( + checks, + check => check.GetProperty("kind").GetString()!.StartsWith("documentation", StringComparison.Ordinal) + ); Assert.Contains(checks, check => check.GetProperty("kind").GetString() == "build"); Assert.Contains(checks, check => check.GetProperty("kind").GetString() == "api"); - await Assert.ThrowsAsync(() => repository.PlanAsync(documentationCache: repository.PathOf("artifacts/documentation"))); + await Assert.ThrowsAsync( + () => repository.PlanAsync(documentationCache: repository.PathOf("artifacts/documentation")) + ); } [Fact] @@ -285,10 +396,15 @@ public async Task UnrelatedProsePreservesSelectedSourceReferenceInputs() docs.Write("content/en/other-guide.md", ValidationDocumentationFixture.Page("Other", "Updated usage guidance.")); DocumentationResult current = await docs.IndexAsync(); using JsonDocument next = await docs.PlanAsync(current, baseline); - JsonElement InitialApi(JsonDocument plan) => plan.RootElement.GetProperty("checks").EnumerateArray() - .Single(check => check.GetProperty("kind").GetString() == "documentation-api"); + JsonElement InitialApi(JsonDocument plan) + => plan.RootElement.GetProperty("checks") + .EnumerateArray() + .Single(check => check.GetProperty("kind").GetString() == "documentation-api"); Assert.Equal(InitialApi(first).GetRawText(), InitialApi(next).GetRawText()); - Assert.DoesNotContain(next.RootElement.GetProperty("checks").EnumerateArray(), check => check.GetProperty("id").GetString() == "build:src/Other/Other.csproj"); + Assert.DoesNotContain( + next.RootElement.GetProperty("checks").EnumerateArray(), + check => check.GetProperty("id").GetString() == "build:src/Other/Other.csproj" + ); Assert.NotEqual(baseline.snapshot, current.snapshot); } @@ -312,31 +428,49 @@ public async Task RemovingARequiredCaptureDoesNotBecomeAnEmptySuccessfulSelectio DocumentationResult current = await docs.IndexAsync(); if (changedSource) { - repository.Write("src/Example/Changed.cs", "namespace Example; /// A captured source contract.\npublic class Changed { }"); + repository.Write( + "src/Example/Changed.cs", + "namespace Example; /// A captured source contract.\npublic class Changed { }" + ); repository.Write("tests/ci/Test-AgentRules.ps1", "Write-Output 'Fixture policy passed'"); repository.Write("tests/ci/CapturePolicy.Tests.ps1", "Write-Output 'Fixture compilation policy passed'"); } using JsonDocument plan = await docs.PlanAsync(current, baseline); JsonElement[] checks = plan.RootElement.GetProperty("checks").EnumerateArray().ToArray(); - JsonElement missing = checks.Single(check => check.GetProperty("id").GetString() == "documentation-api-missing:src/Example/Example.csproj"); + JsonElement missing = checks.Single( + check => check.GetProperty("id").GetString() == "documentation-api-missing:src/Example/Example.csproj" + ); Assert.Equal("documentation-missing", missing.GetProperty("kind").GetString()); Assert.Equal(JsonValueKind.Null, missing.GetProperty("exclusion").ValueKind); if (changedSource) { JsonElement build = checks.Single(check => check.GetProperty("id").GetString() == "build:src/Example/Example.csproj"); Assert.Equal(build.GetProperty("context").GetString(), missing.GetProperty("context").GetString()); - Assert.Contains(missing.GetProperty("prerequisites").EnumerateArray(), prerequisite => prerequisite.GetString() == build.GetProperty("id").GetString()); + Assert.Contains( + missing.GetProperty("prerequisites").EnumerateArray(), + prerequisite => prerequisite.GetString() == build.GetProperty("id").GetString() + ); Assert.True(Array.IndexOf(checks, build) < Array.IndexOf(checks, missing)); Assert.Equal("src/Example/Example.csproj", Assert.Single(missing.GetProperty("projects").EnumerateArray()).GetString()); // Exercise the real executor and compiler with a finite fixture policy. Repository-wide // architecture and test discovery are separate contracts, not inputs to this capture test. JsonNode execution = JsonNode.Parse(plan.RootElement.GetRawText())!; JsonArray selected = new(); - foreach (JsonElement check in checks.Where(check => new[] { "instructions", "architecture", "documentation", build.GetProperty("id").GetString(), missing.GetProperty("id").GetString() }.Contains(check.GetProperty("id").GetString()))) - { + foreach (JsonElement check in checks.Where( + check => new[] + { + "instructions", + "architecture", + "documentation", + build.GetProperty("id").GetString(), + missing.GetProperty("id").GetString() + }.Contains(check.GetProperty("id").GetString()) + )) { JsonNode item = JsonNode.Parse(check.GetRawText())!; if (item["id"]!.GetValue() == "architecture") + { item["kind"] = "ci-contracts"; + } selected.Add(item); } execution["checks"] = selected; @@ -344,11 +478,28 @@ public async Task RemovingARequiredCaptureDoesNotBecomeAnEmptySuccessfulSelectio await Assert.ThrowsAsync(() => repository.RunAsync()); using JsonDocument evidence = JsonDocument.Parse(File.ReadAllBytes(repository.PathOf("artifacts/run/results.json"))); JsonElement[] results = evidence.RootElement.GetProperty("results").EnumerateArray().ToArray(); - Assert.True(results.Single(result => result.GetProperty("id").GetString() == build.GetProperty("id").GetString()).GetProperty("status").GetString() == "Passed", evidence.RootElement.GetRawText()); - Assert.Equal("Blocked", results.Single(result => result.GetProperty("id").GetString() == missing.GetProperty("id").GetString()).GetProperty("status").GetString()); - using JsonDocument captured = JsonDocument.Parse(File.ReadAllBytes(repository.PathOf("artifacts/run/documentation-captures/Example.json"))); + Assert.True( + results + .Single(result => result.GetProperty("id").GetString() == build.GetProperty("id").GetString()) + .GetProperty("status") + .GetString() == "Passed", + evidence.RootElement.GetRawText() + ); + Assert.Equal( + "Blocked", + results + .Single(result => result.GetProperty("id").GetString() == missing.GetProperty("id").GetString()) + .GetProperty("status") + .GetString() + ); + using JsonDocument captured = JsonDocument.Parse( + File.ReadAllBytes(repository.PathOf("artifacts/run/documentation-captures/Example.json")) + ); Assert.Equal("Unverified", captured.RootElement.GetProperty("sourceApiStatus").GetString()); - Assert.Contains(captured.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray(), symbol => symbol.GetProperty("id").GetString() == "T:Example.Changed"); + Assert.Contains( + captured.RootElement.GetProperty("projects")[0].GetProperty("symbols").EnumerateArray(), + symbol => symbol.GetProperty("id").GetString() == "T:Example.Changed" + ); } else { @@ -364,14 +515,24 @@ public async Task UnknownExecutableAgentInputIsNotExemptedAsDocumentation() repository.Write(".agents/check.ps1", "throw 'unknown executable input'"); using JsonDocument plan = await repository.PlanAsync(); Assert.True(plan.RootElement.GetProperty("full").GetBoolean()); - Assert.Contains(plan.RootElement.GetProperty("diagnostics").EnumerateArray(), item => item.GetString()!.Contains(".agents/check.ps1", StringComparison.Ordinal)); + Assert.Contains( + plan.RootElement.GetProperty("diagnostics").EnumerateArray(), + item => item.GetString()!.Contains(".agents/check.ps1", StringComparison.Ordinal) + ); } + private static async Task PrepareDocumentationAsync(ValidationRepository repository) { var docs = new ValidationDocumentationFixture(repository); docs.Initialize(); - docs.Write("content/en/Example.md", "---\nuid: project-example\nkind: project\nowners: [Example]\napiSurface: source-clr\n---\n# Example\n\nRead the declared contract.\n\n\n"); - docs.Write("content/en/random/behavior.md", "---\nuid: task-fragment\nkind: api\nowners: [Example]\napiSurface: source-clr\nexampleMode: host\nexampleProjects: [Example]\n---\n# Behavior\n\nDeclare a local value.\n\n```csharp\nint value = 1;\n```\n"); + docs.Write( + "content/en/Example.md", + "---\nuid: project-example\nkind: project\nowners: [Example]\napiSurface: source-clr\n---\n# Example\n\nRead the declared contract.\n\n\n" + ); + docs.Write( + "content/en/random/behavior.md", + "---\nuid: task-fragment\nkind: api\nowners: [Example]\napiSurface: source-clr\nexampleMode: host\nexampleProjects: [Example]\n---\n# Behavior\n\nDeclare a local value.\n\n```csharp\nint value = 1;\n```\n" + ); return await docs.IndexAsync(); } } diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationExecutionTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationExecutionTests.cs index e7264867b..d251443ac 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationExecutionTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationExecutionTests.cs @@ -1,12 +1,12 @@ -using Inno.Testing.Validation; using System; using System.IO; using System.Linq; using System.Text.Json; using System.Text.Json.Nodes; using System.Threading.Tasks; -using Inno.Tooling.Validation; using Xunit; +using Inno.Testing.Validation; +using Inno.Tooling.Validation; namespace Inno.Tooling.Validation.Tests; @@ -16,8 +16,10 @@ public sealed class ValidationExecutionTests public async Task UnrelatedCliPayloadDoesNotInvalidateTheValidationToolEnvironment() { using var repository = new ValidationRepository(); - string unrelated = Path.Combine(Path.GetDirectoryName(typeof(ValidationCommand).Assembly.Location)!, - "UnrelatedDocumentationPayload-" + Guid.NewGuid().ToString("N") + ".dll"); + string unrelated = Path.Combine( + Path.GetDirectoryName(typeof(ValidationCommand).Assembly.Location)!, + "UnrelatedDocumentationPayload-" + Guid.NewGuid().ToString("N") + ".dll" + ); try { File.WriteAllText(unrelated, "first"); @@ -26,7 +28,10 @@ public async Task UnrelatedCliPayloadDoesNotInvalidateTheValidationToolEnvironme File.WriteAllText(unrelated, "other"); File.SetLastWriteTimeUtc(unrelated, timestamp); using JsonDocument changed = await repository.PlanAsync(); - Assert.Equal(initial.RootElement.GetProperty("environment").GetString(), changed.RootElement.GetProperty("environment").GetString()); + Assert.Equal( + initial.RootElement.GetProperty("environment").GetString(), + changed.RootElement.GetProperty("environment").GetString() + ); } finally { @@ -42,7 +47,10 @@ public async Task ToolSourceInputsFollowEvaluatedReferencesAndPolicyIncludesRule const string C_DEPENDENCY = "src/Example/ToolDependency.cs"; const string C_UNRELATED = "tools/Inno.Unrelated/Unrelated.cs"; const string C_RULE = ".agents/rulebook/domains/example.md"; - repository.Write(C_TOOL, ValidationRepository.Project("")); + repository.Write( + C_TOOL, + ValidationRepository.Project("") + ); repository.Write(C_DEPENDENCY, "namespace Example; internal class ToolDependency { }"); repository.Write("tools/Inno.Unrelated/Inno.Unrelated.csproj", ValidationRepository.Project()); repository.Write(C_UNRELATED, "namespace Unrelated; internal class Unrelated { }"); @@ -50,13 +58,19 @@ public async Task ToolSourceInputsFollowEvaluatedReferencesAndPolicyIncludesRule repository.Git("add", "."); repository.Git("commit", "-m", "Declare actual tooling dependencies"); using JsonDocument plan = await repository.PlanAsync(); - string?[] inputs = plan.RootElement.GetProperty("inputSets").GetProperty("tooling").EnumerateArray() - .Select(static value => value.GetString()).ToArray(); + string?[] inputs = plan.RootElement.GetProperty("inputSets") + .GetProperty("tooling") + .EnumerateArray() + .Select(static value => value.GetString()) + .ToArray(); Assert.Contains(C_TOOL, inputs); Assert.Contains(C_DEPENDENCY, inputs); Assert.DoesNotContain(C_UNRELATED, inputs); Assert.DoesNotContain(C_RULE, inputs); - JsonElement policy = plan.RootElement.GetProperty("checks").EnumerateArray().Single(check => check.GetProperty("id").GetString() == "instructions"); + JsonElement policy = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(check => check.GetProperty("id").GetString() == "instructions"); Assert.Contains(C_RULE, policy.GetProperty("inputs").EnumerateArray().Select(static value => value.GetString())); } @@ -66,12 +80,18 @@ public async Task CompilationDeclaresItsPolicyPrerequisitesInThePlan() using var repository = new ValidationRepository(); repository.Write("src/Example/Changed.cs", "namespace Example; public sealed class Changed { }"); using JsonDocument plan = await repository.PlanAsync(); - JsonElement[] builds = plan.RootElement.GetProperty("checks").EnumerateArray() - .Where(check => check.GetProperty("kind").GetString() == "build").ToArray(); + JsonElement[] builds = plan.RootElement.GetProperty("checks") + .EnumerateArray() + .Where(check => check.GetProperty("kind").GetString() == "build") + .ToArray(); Assert.NotEmpty(builds); foreach (JsonElement build in builds) { - string?[] prerequisites = build.GetProperty("prerequisites").EnumerateArray().Select(static value => value.GetString()).ToArray(); + string?[] prerequisites = build + .GetProperty("prerequisites") + .EnumerateArray() + .Select(static value => value.GetString()) + .ToArray(); Assert.Contains("instructions", prerequisites); Assert.Contains("architecture", prerequisites); Assert.DoesNotContain("documentation", prerequisites); diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs index aab2f8c4b..e8051e139 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs @@ -1,4 +1,3 @@ -using Inno.Testing.Validation; using System; using System.Diagnostics; using System.IO; @@ -6,12 +5,13 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Xunit; using Inno.Build.Toolchains; using Inno.Core.IO; using Inno.Testing.Source; -using Inno.Tooling.Validation; +using Inno.Testing.Validation; using Inno.Tooling.Documentation; -using Xunit; +using Inno.Tooling.Validation; namespace Inno.Tooling.Validation.Tests; @@ -26,8 +26,20 @@ public async Task ScheduledPlanRebindsOnlyOnItsCapturedEnvironment() string output = repository.PathOf("artifacts/bound"); var plan = System.Text.Json.Nodes.JsonNode.Parse(planned.RootElement.GetRawText())!; File.WriteAllText(source, plan.ToJsonString()); - Task Bind() => ValidationCommand.ExecuteAsync(["plan", "--engine-root", repository.PathOf("."), - "--dotnet", repository.dotnet, "--plan", source, "--profile", "fast", "--output", output]); + Task Bind() + => ValidationCommand.ExecuteAsync([ + "plan", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--plan", + source, + "--profile", + "fast", + "--output", + output + ]); Assert.Equal(0, await Bind()); using JsonDocument bound = JsonDocument.Parse(File.ReadAllText(Path.Combine(output, "plan.json"))); Assert.Equal(planned.RootElement.GetProperty("environment").GetString(), bound.RootElement.GetProperty("environment").GetString()); @@ -43,16 +55,25 @@ public async Task BuildDefinitionAffectsOnlyTheEntryThatImportsIt() { using var repository = new ValidationRepository(); repository.Write("src/Example/Optional.props", ""); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project(""" + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project(""" - """)); - repository.Write("tests/Enabled/Enabled.csproj", ValidationRepository.Project(""" + """) + ); + repository.Write( + "tests/Enabled/Enabled.csproj", + ValidationRepository.Project(""" truedomain - """)); - repository.Write("tools/Inno.Tooling.Validation/Inno.Tooling.Validation.csproj", ValidationRepository.Project(""" + """) + ); + repository.Write( + "tools/Inno.Tooling.Validation/Inno.Tooling.Validation.csproj", + ValidationRepository.Project(""" - """)); + """) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Register distinct SDK entries"); using JsonDocument baseline = await repository.PlanAsync(); @@ -60,7 +81,8 @@ public async Task BuildDefinitionAffectsOnlyTheEntryThatImportsIt() File.WriteAllText(previous, baseline.RootElement.GetRawText()); repository.Write("src/Example/Optional.props", "2"); using JsonDocument plan = await repository.PlanAsync(); - var tests = plan.RootElement.GetProperty("checks").EnumerateArray() + var tests = plan.RootElement.GetProperty("checks") + .EnumerateArray() .Where(check => check.GetProperty("kind").GetString() == "test") .ToDictionary(check => check.GetProperty("owner").GetString()!); Assert.Equal(JsonValueKind.Null, tests["tests/Enabled/Enabled.csproj"].GetProperty("exclusion").ValueKind); @@ -69,7 +91,8 @@ public async Task BuildDefinitionAffectsOnlyTheEntryThatImportsIt() reason.GetString()!.Contains("src/Example/Optional.props is consumed by", StringComparison.Ordinal)); File.Delete(repository.PathOf("src/Example/Optional.props")); using JsonDocument removed = await repository.PlanAsync(baselinePlan: previous); - var afterDelete = removed.RootElement.GetProperty("checks").EnumerateArray() + var afterDelete = removed.RootElement.GetProperty("checks") + .EnumerateArray() .Where(check => check.GetProperty("kind").GetString() == "test") .ToDictionary(check => check.GetProperty("owner").GetString()!); Assert.Equal(JsonValueKind.Null, afterDelete["tests/Enabled/Enabled.csproj"].GetProperty("exclusion").ValueKind); @@ -80,35 +103,74 @@ public async Task BuildDefinitionAffectsOnlyTheEntryThatImportsIt() public async Task ManualProducerProfileSelectsOnlyDeclaredProducerRegressions() { using var repository = new ValidationRepository(); - repository.Write("tests/Producer/Suite.csproj", ValidationRepository.Project( - "trueperformance" - + "true")); + repository.Write( + "tests/Producer/Suite.csproj", + ValidationRepository.Project( + "trueperformance" + + "true" + ) + ); using JsonDocument plan = await repository.PlanAsync(profile: "native-producer"); Assert.False(plan.RootElement.GetProperty("full").GetBoolean()); - JsonElement selected = Assert.Single(plan.RootElement.GetProperty("checks").EnumerateArray() - .Where(check => check.GetProperty("kind").GetString() == "test" && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null)); + JsonElement selected = Assert.Single( + plan.RootElement.GetProperty("checks") + .EnumerateArray() + .Where( + check => ( + check.GetProperty("kind").GetString() == "test" + && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null + ) + ) + ); Assert.Equal("tests/Producer/Suite.csproj", selected.GetProperty("owner").GetString()); - await Assert.ThrowsAsync(() => repository.PlanAsync(profile: "native-producer", nativeDependencies: "artifacts/backend-store/selection.json")); + await Assert.ThrowsAsync( + () => repository.PlanAsync(profile: "native-producer", nativeDependencies: "artifacts/backend-store/selection.json") + ); } [Fact] public async Task ConsumeOnlyPerformanceNeverSelectsThirdPartyProducerBenchmarks() { using var repository = new ValidationRepository(); - repository.Write("tests/Producer/Suite.csproj", ValidationRepository.Project( - "trueperformance" - + "true")); - repository.Write("tests/Warm/Suite.csproj", ValidationRepository.Project( - "trueperformance")); - using JsonDocument plan = await repository.PlanAsync(profile: "performance", nativeDependencies: "artifacts/backend-store/selection.json"); + repository.Write( + "tests/Producer/Suite.csproj", + ValidationRepository.Project( + "trueperformance" + + "true" + ) + ); + repository.Write( + "tests/Warm/Suite.csproj", + ValidationRepository.Project( + "trueperformance" + ) + ); + using JsonDocument plan = await repository.PlanAsync( + profile: "performance", + nativeDependencies: "artifacts/backend-store/selection.json" + ); Assert.False(plan.RootElement.GetProperty("full").GetBoolean()); - JsonElement required = Assert.Single(plan.RootElement.GetProperty("checks").EnumerateArray() - .Where(item => item.GetProperty("kind").GetString() == "test" && item.GetProperty("exclusion").ValueKind == JsonValueKind.Null)); + JsonElement required = Assert.Single( + plan.RootElement.GetProperty("checks") + .EnumerateArray() + .Where( + item => item.GetProperty("kind").GetString() == "test" && item.GetProperty("exclusion").ValueKind == JsonValueKind.Null + ) + ); Assert.Equal("tests/Warm/Suite.csproj", required.GetProperty("owner").GetString()); - JsonElement check = plan.RootElement.GetProperty("checks").EnumerateArray() - .Single(item => item.GetProperty("kind").GetString() == "test" && item.GetProperty("owner").GetString() == "tests/Producer/Suite.csproj"); + JsonElement check = plan.RootElement.GetProperty("checks") + .EnumerateArray() + .Single( + item => ( + item.GetProperty("kind").GetString() == "test" + && item.GetProperty("owner").GetString() == "tests/Producer/Suite.csproj" + ) + ); Assert.Contains("producer benchmark", check.GetProperty("exclusion").GetString()); - Assert.DoesNotContain(plan.RootElement.GetProperty("checks").EnumerateArray(), item => item.GetProperty("kind").GetString() == "cold-inputs"); + Assert.DoesNotContain( + plan.RootElement.GetProperty("checks").EnumerateArray(), + item => item.GetProperty("kind").GetString() == "cold-inputs" + ); } [Fact] @@ -116,25 +178,46 @@ public async Task FastProfileDefersRealIntegrationAndNativeProductsWithoutDownlo { using var repository = new ValidationRepository(); foreach (string layer in new[] { "contract", "integration", "native", "performance" }) - repository.Write("tests/" + layer + "/Suite.csproj", ValidationRepository.Project( - "true" + layer - + "" + (layer == "native" ? "editor" : "") - + "")); - repository.Write("tests/Pack/Suite.csproj", ValidationRepository.Project(""" + { + repository.Write( + "tests/" + layer + "/Suite.csproj", + ValidationRepository.Project( + "true" + layer + + "" + (layer == "native" ? "editor" : "") + + "" + ) + ); + } + repository.Write( + "tests/Pack/Suite.csproj", + ValidationRepository.Project(""" truecontract - """)); + """) + ); using JsonDocument plan = await repository.PlanAsync(profile: "fast", nativeDependencies: "artifacts/backend-store/selection.json"); Assert.False(plan.RootElement.GetProperty("full").GetBoolean()); Assert.False(plan.RootElement.GetProperty("contexts").TryGetProperty("native", out _)); Assert.Empty(plan.RootElement.GetProperty("nativeRequests").EnumerateArray()); - JsonElement[] tests = plan.RootElement.GetProperty("checks").EnumerateArray().Where(check => check.GetProperty("kind").GetString() == "test").ToArray(); - Assert.Contains(tests, check => check.GetProperty("layer").GetString() == "contract" && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null); - Assert.All(tests.Where(check => check.GetProperty("layer").GetString() is "native" or "integration" or "performance"), - check => Assert.Equal(JsonValueKind.String, check.GetProperty("exclusion").ValueKind)); + JsonElement[] tests = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Where(check => check.GetProperty("kind").GetString() == "test") + .ToArray(); + Assert.Contains( + tests, + check => check.GetProperty("layer").GetString() == "contract" && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null + ); + Assert.All( + tests.Where(check => check.GetProperty("layer").GetString() is "native" or "integration" or "performance"), + check => Assert.Equal(JsonValueKind.String, check.GetProperty("exclusion").ValueKind) + ); Assert.False(Directory.Exists(repository.PathOf("artifacts/dependencies"))); - Assert.Equal(JsonValueKind.String, tests.Single(check => check.GetProperty("owner").GetString() == "tests/Pack/Suite.csproj") - .GetProperty("exclusion").ValueKind); + Assert.Equal( + JsonValueKind.String, + tests.Single(check => check.GetProperty("owner").GetString() == "tests/Pack/Suite.csproj") + .GetProperty("exclusion").ValueKind + ); } [Fact] @@ -148,9 +231,19 @@ public async Task ConsolePresentationKeepsItsContractsWithoutSelectingBuildInteg repository.Write(C_STYLE, changed); // Consume-only planning establishes scope without fetching source dependencies or preparing an Editor. string output = repository.PathOf("artifacts/console-selection"); - int status = await ValidationCommand.ExecuteAsync(["plan", "--engine-root", repository.PathOf("."), - "--dotnet", repository.dotnet, "--base", "HEAD", "--output", output, - "--backend-store", "artifacts/backend-store"]); + int status = await ValidationCommand.ExecuteAsync([ + "plan", + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--base", + "HEAD", + "--output", + output, + "--backend-store", + "artifacts/backend-store" + ]); Assert.Equal(0, status); Assert.False(File.Exists(Path.Combine(output, "preparation.json"))); using JsonDocument selection = JsonDocument.Parse(File.ReadAllText(Path.Combine(output, "plan.json"))); @@ -166,8 +259,12 @@ public async Task ConsolePresentationKeepsItsContractsWithoutSelectingBuildInteg public async Task NativeTestOwnersCannotOmitTheirProductDeployment() { using var repository = new ValidationRepository(); - repository.Write("tests/Native.Tests/Native.Tests.csproj", ValidationRepository.Project( - "truenative")); + repository.Write( + "tests/Native.Tests/Native.Tests.csproj", + ValidationRepository.Project( + "truenative" + ) + ); InvalidDataException failure = await Assert.ThrowsAsync(() => repository.PlanAsync()); Assert.Contains("Native test owner must declare its product deployment", failure.Message); Assert.Contains("tests/Native.Tests/Native.Tests.csproj", failure.Message); @@ -184,12 +281,20 @@ public async Task HostRoutingProofContainsOnlyExclusiveSourcesOfUnreferencedHost repository.Write("tests/Foreign/Shared.cs", "class SharedTest {}"); repository.Write("tests/Referenced/Referenced.csproj", ValidationRepository.Project(settings)); repository.Write("tests/Referenced/Utility.cs", "class ReferencedTest {}"); - repository.Write("tests/Consumer/Consumer.csproj", ValidationRepository.Project( - "")); + repository.Write( + "tests/Consumer/Consumer.csproj", + ValidationRepository.Project( + "" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare independent and shared host test inputs"); using JsonDocument plan = await repository.PlanAsync(); - string?[] excluded = plan.RootElement.GetProperty("hostExcludedSources").EnumerateArray().Select(static item => item.GetString()).ToArray(); + string?[] excluded = plan.RootElement + .GetProperty("hostExcludedSources") + .EnumerateArray() + .Select(static item => item.GetString()) + .ToArray(); Assert.Contains("tests/Foreign/Private.cs", excluded); Assert.DoesNotContain("tests/Foreign/Shared.cs", excluded); Assert.DoesNotContain("tests/Referenced/Utility.cs", excluded); @@ -201,8 +306,12 @@ public async Task SharedTestExecutionChangesSelectAllTestOwnersAndInvalidateOnly using var repository = new ValidationRepository(); const string C_EXECUTOR = "tests/Invoke-IsolatedTests.ps1"; const string C_PERFORMANCE = "tests/Performance.Tests/Performance.Tests.csproj"; - repository.Write(C_PERFORMANCE, ValidationRepository.Project( - "trueperformance")); + repository.Write( + C_PERFORMANCE, + ValidationRepository.Project( + "trueperformance" + ) + ); repository.Write(C_EXECUTOR, "Write-Host 'before'"); repository.Git("add", C_EXECUTOR, C_PERFORMANCE); repository.Git("commit", "-m", "Declare the shared test executor"); @@ -219,14 +328,21 @@ public async Task SharedTestExecutionChangesSelectAllTestOwnersAndInvalidateOnly Assert.All(checks.Where(check => check.GetProperty("kind").GetString() == "test"), test => { if (test.GetProperty("owner").GetString() == C_PERFORMANCE) + { Assert.Contains("Performance sampling belongs", test.GetProperty("exclusion").GetString()); + } else + { Assert.Equal(JsonValueKind.Null, test.GetProperty("exclusion").ValueKind); + } Assert.Contains(C_EXECUTOR, test.GetProperty("inputs").EnumerateArray().Select(static value => value.GetString())); }); Assert.All(checks.Where(check => check.GetProperty("kind").GetString() == "build"), build => Assert.DoesNotContain(C_EXECUTOR, build.GetProperty("inputs").EnumerateArray().Select(static value => value.GetString()))); - Assert.DoesNotContain(C_EXECUTOR, changed.RootElement.GetProperty("inputSets").GetProperty("tooling").EnumerateArray().Select(static value => value.GetString())); + Assert.DoesNotContain( + C_EXECUTOR, + changed.RootElement.GetProperty("inputSets").GetProperty("tooling").EnumerateArray().Select(static value => value.GetString()) + ); } [Fact] @@ -236,22 +352,31 @@ public async Task PerformanceSamplingRequiresItsExplicitProfileEvenWhenItsFixtur const string C_OWNER = "tests/Cost.Tests/Cost.Tests.csproj"; const string C_FIXTURE = "tests/fixtures/CostFixture/CostFixture.csproj"; repository.Write(C_FIXTURE, ValidationRepository.Project()); - repository.Write(C_OWNER, ValidationRepository.Project(""" + repository.Write( + C_OWNER, + ValidationRepository.Project(""" trueperformance - """)); + """) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare cost sampling owner"); repository.Write("src/Example/Changed.cs", "namespace Example; public class Changed { }"); using (JsonDocument plan = await repository.PlanAsync()) { - JsonElement check = plan.RootElement.GetProperty("checks").EnumerateArray().Single(item => item.GetProperty("id").GetString() == "test:" + C_OWNER); + JsonElement check = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(item => item.GetProperty("id").GetString() == "test:" + C_OWNER); Assert.Contains("Performance sampling belongs", check.GetProperty("exclusion").GetString()); } repository.Write("tests/fixtures/CostFixture/Changed.cs", "namespace CostFixture; public class Changed { }"); using (JsonDocument plan = await repository.PlanAsync()) { - JsonElement check = plan.RootElement.GetProperty("checks").EnumerateArray().Single(item => item.GetProperty("id").GetString() == "test:" + C_OWNER); + JsonElement check = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(item => item.GetProperty("id").GetString() == "test:" + C_OWNER); Assert.Contains("Performance sampling belongs", check.GetProperty("exclusion").GetString()); } repository.Git("add", "tests/fixtures/CostFixture/Changed.cs"); @@ -259,16 +384,25 @@ public async Task PerformanceSamplingRequiresItsExplicitProfileEvenWhenItsFixtur repository.Write("build/Changed.props", ""); using (JsonDocument plan = await repository.PlanAsync()) { - JsonElement check = plan.RootElement.GetProperty("checks").EnumerateArray().Single(item => item.GetProperty("id").GetString() == "test:" + C_OWNER); + JsonElement check = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(item => item.GetProperty("id").GetString() == "test:" + C_OWNER); Assert.Contains("Performance sampling belongs", check.GetProperty("exclusion").GetString()); Assert.False(check.GetProperty("reusable").GetBoolean()); } using (JsonDocument plan = await repository.PlanAsync(profile: "performance")) { - JsonElement check = plan.RootElement.GetProperty("checks").EnumerateArray().Single(item => item.GetProperty("id").GetString() == "test:" + C_OWNER); + JsonElement check = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(item => item.GetProperty("id").GetString() == "test:" + C_OWNER); Assert.Equal(JsonValueKind.Null, check.GetProperty("exclusion").ValueKind); Assert.False(check.GetProperty("reusable").GetBoolean()); - Assert.DoesNotContain(plan.RootElement.GetProperty("checks").EnumerateArray(), item => item.GetProperty("kind").GetString() == "cold-inputs"); + Assert.DoesNotContain( + plan.RootElement.GetProperty("checks").EnumerateArray(), + item => item.GetProperty("kind").GetString() == "cold-inputs" + ); } } @@ -278,8 +412,10 @@ public async Task AnotherHostOwnerDoesNotRequestNativePreparationAndUnknownHosts using var repository = new ValidationRepository(); string other = OperatingSystem.IsWindows() ? "macos" : "windows"; const string C_OWNER = "tests/Host.Tests/Host.Tests.csproj"; - string definition = ValidationRepository.Project("truenative" - + "" + other + "editor"); + string definition = ValidationRepository.Project( + "truenative" + + "" + other + "editor" + ); repository.Write(C_OWNER, definition); repository.Git("add", "."); repository.Git("commit", "-m", "Declare native host requirement"); @@ -287,11 +423,21 @@ public async Task AnotherHostOwnerDoesNotRequestNativePreparationAndUnknownHosts using (JsonDocument plan = await repository.PlanAsync()) { Assert.False(plan.RootElement.GetProperty("contexts").TryGetProperty("native", out _)); - JsonElement check = plan.RootElement.GetProperty("checks").EnumerateArray().Single(item => item.GetProperty("id").GetString() == "test:" + C_OWNER); + JsonElement check = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(item => item.GetProperty("id").GetString() == "test:" + C_OWNER); Assert.Contains("requires OS environment", check.GetProperty("exclusion").GetString()); } string current = OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linux"; - repository.Write(C_OWNER, definition.Replace(">" + other + "", ">" + current + ";unknown", StringComparison.Ordinal)); + repository.Write( + C_OWNER, + definition.Replace( + ">" + other + "", + ">" + current + ";unknown", + StringComparison.Ordinal + ) + ); await Assert.ThrowsAsync(() => repository.PlanAsync()); } @@ -341,7 +487,9 @@ public async Task GitLineEndingConversionDoesNotSelectUnchangedOwners(bool commi using var repository = new ValidationRepository(); repository.Git("config", "core.autocrlf", "false"); if (!committedCarriageReturns) + { repository.Write(".gitattributes", "*.cs text eol=crlf\n"); + } repository.Write("src/Example/Unchanged.cs", "namespace Example;\r\npublic class Unchanged { }\r\n"); repository.Git("add", "."); repository.Git("commit", "-m", "Declare checkout line endings"); @@ -357,19 +505,34 @@ public async Task SdkSelectedReferencePackContentInvalidatesEvidenceDespitePrese using var repository = new ValidationRepository(); using var external = new ValidationRepository(); string packs = external.PathOf("packs"); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project( - "" + System.Security.SecurityElement.Escape(packs) - + "")); + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project( + "" + System.Security.SecurityElement.Escape(packs) + + "" + ) + ); using JsonDocument initial = await repository.PlanAsync(); - JsonElement owner = initial.RootElement.GetProperty("contexts").GetProperty("managed").GetProperty("sdkGraph").EnumerateArray() - .Single(project => repository.BindWorkspace(project.GetProperty("Path").GetString()!) == repository.PathOf("src/Example/Example.csproj")); + JsonElement owner = initial.RootElement.GetProperty("contexts") + .GetProperty("managed") + .GetProperty("sdkGraph") + .EnumerateArray() + .Single( + project => ( + repository.BindWorkspace( + project.GetProperty("Path").GetString()! + ) == repository.PathOf("src/Example/Example.csproj") + ) + ); string path = Path.Combine(Assert.Single(owner.GetProperty("FrameworkPacks").EnumerateArray()).GetString()!, "reference.dll"); external.Write(path, "first"); using JsonDocument plan = await repository.PlanAsync(); DateTime timestamp = File.GetLastWriteTimeUtc(path); external.Write(path, "other"); File.SetLastWriteTimeUtc(path, timestamp); - InvalidDataException failure = await Assert.ThrowsAsync(() => repository.EvidenceAsync(repository.PathOf("artifacts/unread-evidence.json"))); + InvalidDataException failure = await Assert.ThrowsAsync( + () => repository.EvidenceAsync(repository.PathOf("artifacts/unread-evidence.json")) + ); Assert.Contains("another SDK or execution environment", failure.Message, StringComparison.Ordinal); } @@ -382,7 +545,10 @@ public async Task EmptyCiContractDiscoveryCannotCertifySuccess() using JsonDocument plan = await repository.PlanAsync(); await Assert.ThrowsAsync(() => repository.RunAsync()); using JsonDocument results = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/run/results.json"))); - JsonElement contracts = results.RootElement.GetProperty("results").EnumerateArray().Single(result => result.GetProperty("id").GetString() == "ci-contracts"); + JsonElement contracts = results.RootElement + .GetProperty("results") + .EnumerateArray() + .Single(result => result.GetProperty("id").GetString() == "ci-contracts"); Assert.Equal("Failed", contracts.GetProperty("status").GetString()); Assert.Contains("Required CI contract discovery is empty", contracts.GetProperty("detail").GetString(), StringComparison.Ordinal); } @@ -417,8 +583,12 @@ bool unknown Assert.False(plan.RootElement.GetProperty("contexts").TryGetProperty("native", out _)); } else - Assert.Contains(plan.RootElement.GetProperty("diagnostics").EnumerateArray(), - diagnostic => diagnostic.GetString()!.Contains("Unknown or shared input", StringComparison.Ordinal)); + { + Assert.Contains( + plan.RootElement.GetProperty("diagnostics").EnumerateArray(), + diagnostic => diagnostic.GetString()!.Contains("Unknown or shared input", StringComparison.Ordinal) + ); + } } [Fact] @@ -428,18 +598,31 @@ public async Task StaticContractRecognitionDoesNotHideAnExplicitProjectConsumer( const string C_SCRIPT = "tests/ci/Invoke-ValidationGate.ps1"; const string C_OWNER = "tests/Example.Tests/Example.Tests.csproj"; repository.Write(C_SCRIPT, "Write-Output 'Original'\n"); - repository.Write(C_OWNER, File.ReadAllText(repository.PathOf(C_OWNER)).Replace("", - "", StringComparison.Ordinal)); + repository.Write( + C_OWNER, + File.ReadAllText(repository.PathOf(C_OWNER)).Replace( + "", + "", + StringComparison.Ordinal + ) + ); repository.Git("add", C_SCRIPT, C_OWNER); repository.Git("commit", "-m", "Declare the contract's additional runtime consumer"); repository.Write(C_SCRIPT, "Write-Output 'Changed'\n"); using JsonDocument plan = await repository.PlanAsync(); Assert.False(plan.RootElement.GetProperty("full").GetBoolean()); Assert.Contains(C_OWNER, Owners(plan)); - Assert.DoesNotContain(C_SCRIPT, plan.RootElement.GetProperty("hostExcludedSources").EnumerateArray().Select(item => item.GetString())); - Assert.Contains(plan.RootElement.GetProperty("checks").EnumerateArray(), - check => check.GetProperty("id").GetString() == "build:" + C_OWNER - && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null); + Assert.DoesNotContain( + C_SCRIPT, + plan.RootElement.GetProperty("hostExcludedSources").EnumerateArray().Select(item => item.GetString()) + ); + Assert.Contains( + plan.RootElement.GetProperty("checks").EnumerateArray(), + check => ( + check.GetProperty("id").GetString() == "build:" + C_OWNER + && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null + ) + ); } [Theory] @@ -452,17 +635,27 @@ public async Task JourneySourceChangesSelectCiContractsAndInvalidateTheirEvidenc repository.Git("add", path); repository.Git("commit", "-m", "Declare shared journey input"); using JsonDocument initial = await repository.PlanAsync(); - Assert.DoesNotContain(initial.RootElement.GetProperty("checks").EnumerateArray(), - check => check.GetProperty("id").GetString() == "ci-contracts"); + Assert.DoesNotContain( + initial.RootElement.GetProperty("checks").EnumerateArray(), + check => check.GetProperty("id").GetString() == "ci-contracts" + ); repository.Write(path, "// After!\n"); using JsonDocument changed = await repository.PlanAsync(); - JsonElement contracts = changed.RootElement.GetProperty("checks").EnumerateArray() + JsonElement contracts = changed.RootElement.GetProperty("checks") + .EnumerateArray() .Single(check => check.GetProperty("id").GetString() == "ci-contracts"); Assert.Contains(path, contracts.GetProperty("inputs").EnumerateArray().Select(static input => input.GetString())); - Assert.NotEqual(initial.RootElement.GetProperty("inputs").GetProperty(path).GetString(), - changed.RootElement.GetProperty("inputs").GetProperty(path).GetString()); - Assert.DoesNotContain(path, changed.RootElement.GetProperty("inputSets").GetProperty("tooling").EnumerateArray() - .Select(static input => input.GetString())); + Assert.NotEqual( + initial.RootElement.GetProperty("inputs").GetProperty(path).GetString(), + changed.RootElement.GetProperty("inputs").GetProperty(path).GetString() + ); + Assert.DoesNotContain( + path, + changed.RootElement.GetProperty("inputSets") + .GetProperty("tooling") + .EnumerateArray() + .Select(static input => input.GetString()) + ); } [Theory] @@ -476,7 +669,10 @@ string content using var repository = new ValidationRepository(); repository.Write(path, content); using JsonDocument plan = await repository.PlanAsync(); - JsonElement source = plan.RootElement.GetProperty("checks").EnumerateArray().Single(check => check.GetProperty("id").GetString() == "architecture"); + JsonElement source = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(check => check.GetProperty("id").GetString() == "architecture"); Assert.Contains(source.GetProperty("inputs").EnumerateArray(), input => input.GetString() == path); Assert.True(plan.RootElement.GetProperty("inputs").TryGetProperty(path, out _)); } @@ -489,8 +685,12 @@ public async Task ExternalSourceContentInvalidatesEvidenceEvenWhenLengthAndTimes string path = external.PathOf("Linked.cs"); const string original = "namespace Example; public class Linked { public const int Value = 1; }"; external.Write("Linked.cs", original); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project( - "")); + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project( + "" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare external source input"); using JsonDocument plan = await repository.PlanAsync(); @@ -498,7 +698,9 @@ public async Task ExternalSourceContentInvalidatesEvidenceEvenWhenLengthAndTimes external.Write("Linked.cs", original.Replace("= 1", "= 2", StringComparison.Ordinal)); File.SetLastWriteTimeUtc(path, timestamp); Assert.Equal(original.Length, new FileInfo(path).Length); - InvalidDataException failure = await Assert.ThrowsAsync(() => repository.EvidenceAsync(repository.PathOf("artifacts/unread-evidence.json"))); + InvalidDataException failure = await Assert.ThrowsAsync( + () => repository.EvidenceAsync(repository.PathOf("artifacts/unread-evidence.json")) + ); Assert.Contains("another SDK or execution environment", failure.Message, StringComparison.Ordinal); } @@ -510,8 +712,10 @@ public async Task ExternalImportContentInvalidatesEvidenceEvenWhenLengthAndTimes string path = external.PathOf("Shared.props"); const string original = "4"; external.Write("Shared.props", original); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project( - "")); + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project("") + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare external SDK import"); using JsonDocument plan = await repository.PlanAsync(); @@ -519,7 +723,9 @@ public async Task ExternalImportContentInvalidatesEvidenceEvenWhenLengthAndTimes external.Write("Shared.props", original.Replace(">4<", ">3<", StringComparison.Ordinal)); File.SetLastWriteTimeUtc(path, timestamp); Assert.Equal(original.Length, new FileInfo(path).Length); - InvalidDataException failure = await Assert.ThrowsAsync(() => repository.EvidenceAsync(repository.PathOf("artifacts/unread-evidence.json"))); + InvalidDataException failure = await Assert.ThrowsAsync( + () => repository.EvidenceAsync(repository.PathOf("artifacts/unread-evidence.json")) + ); Assert.Contains("another SDK or execution environment", failure.Message, StringComparison.Ordinal); } @@ -532,13 +738,21 @@ public async Task ClosingFreshnessRejectsBothSourceAndExternalChangesDuringCheck external.Write("Shared.props", original); repository.Write("Shared.props", original); string dependency = external.PathOf("Shared.props"); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project( - "")); - string script = string.Join('\n', new[] { repository.PathOf("Shared.props"), dependency }.Select(path => - "$path = '" + path.Replace("'", "''", StringComparison.Ordinal) + "'; " - + "$stamp = [IO.File]::GetLastWriteTimeUtc($path); " - + "[IO.File]::WriteAllText($path, [IO.File]::ReadAllText($path).Replace('>4<', '>3<')); " - + "[IO.File]::SetLastWriteTimeUtc($path, $stamp)")); + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project( + "" + ) + ); + string script = string.Join( + '\n', + new[] { repository.PathOf("Shared.props"), dependency }.Select(path => ( + "$path = '" + path.Replace("'", "''", StringComparison.Ordinal) + "'; " + + "$stamp = [IO.File]::GetLastWriteTimeUtc($path); " + + "[IO.File]::WriteAllText($path, [IO.File]::ReadAllText($path).Replace('>4<', '>3<')); " + + "[IO.File]::SetLastWriteTimeUtc($path, $stamp)" + )) + ); repository.Write("tests/ci/Test-AgentRules.ps1", script); repository.Git("add", "."); repository.Git("commit", "-m", "Declare check-time source and environment mutations"); @@ -546,10 +760,17 @@ public async Task ClosingFreshnessRejectsBothSourceAndExternalChangesDuringCheck await Assert.ThrowsAsync(() => repository.RunAsync()); using JsonDocument evidence = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/run/results.json"))); JsonElement[] results = evidence.RootElement.GetProperty("results").EnumerateArray().ToArray(); - Assert.Contains(results, result => result.GetProperty("id").GetString() == "instructions" - && result.GetProperty("status").GetString() == "Passed"); + Assert.Contains(results, result => ( + result.GetProperty("id").GetString() == "instructions" + && result.GetProperty("status").GetString() == "Passed" + )); foreach (string id in new[] { "input-stability", "environment-stability" }) - Assert.Contains(evidence.RootElement.GetProperty("failures").EnumerateArray(), fault => fault.GetProperty("stage").GetString() == id); + { + Assert.Contains( + evidence.RootElement.GetProperty("failures").EnumerateArray(), + fault => fault.GetProperty("stage").GetString() == id + ); + } } [Fact] @@ -618,21 +839,37 @@ bool example ) { using var repository = new ValidationRepository(); const string C_OWNER = "tests/fixtures/Support/Support.csproj"; - repository.Write(C_OWNER, ValidationRepository.Project("" - + (test ? "truecontract" : string.Empty) - + (native ? "editor" : string.Empty) + "")); + repository.Write( + C_OWNER, + ValidationRepository.Project( + "" + + (test ? "truecontract" : string.Empty) + + (native ? "editor" : string.Empty) + "" + ) + ); repository.Write("Product.props", ""); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "fixture-target" - + repository.PathOf("Product.props") + "")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "fixture-target" + + repository.PathOf("Product.props") + "" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare the test or support owner and its guide"); var docs = new ValidationDocumentationFixture(repository); docs.Initialize(); DocumentationResult baseline = await docs.IndexAsync(); - docs.Write("content/en/guide.md", ValidationDocumentationFixture.Page("Support", "Updated execution instructions.\n" - + (example ? "~~~csharp\nusing System;\nConsole.WriteLine(1);\n~~~\n" : "```powershell\ndotnet --info\n```\n"), example ? "host" : null)); + docs.Write( + "content/en/guide.md", + ValidationDocumentationFixture.Page( + "Support", + "Updated execution instructions.\n" + + (example ? "~~~csharp\nusing System;\nConsole.WriteLine(1);\n~~~\n" : "```powershell\ndotnet --info\n```\n"), + example ? "host" : null + ) + ); DocumentationResult current = await docs.IndexAsync(); using JsonDocument plan = await docs.PlanAsync(current, baseline); JsonElement[] checks = plan.RootElement.GetProperty("checks").EnumerateArray().ToArray(); @@ -642,9 +879,13 @@ bool example JsonElement[] examples = checks.Where(check => check.GetProperty("kind").GetString() == "documentation-examples").ToArray(); Assert.Equal(example ? 1 : 0, examples.Length); if (example) + { Assert.Equal(native ? "native" : "managed", examples[0].GetProperty("context").GetString()); - Assert.DoesNotContain(checks, check => check.GetProperty("kind").GetString() == "test" - && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null); + } + Assert.DoesNotContain(checks, check => ( + check.GetProperty("kind").GetString() == "test" + && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null + )); if (!test && example) { JsonElement api = Assert.Single(checks.Where(check => check.GetProperty("kind").GetString() == "api")); @@ -671,7 +912,10 @@ public async Task SourceSelectedDocumentationRequiresCanonicalStructureAndOwnerI JsonElement api = checks.Single(check => check.GetProperty("kind").GetString() == "documentation-api"); Assert.Contains(api.GetProperty("prerequisites").EnumerateArray(), prerequisite => prerequisite.GetString() == "documentation"); Assert.Contains(api.GetProperty("inputs").EnumerateArray(), input => input.GetString() == "@src/Example/Example.csproj"); - Assert.Contains(plan.RootElement.GetProperty("inputSets").GetProperty("src/Example/Example.csproj").EnumerateArray(), input => input.GetString() == "src/Example/Existing.cs"); + Assert.Contains( + plan.RootElement.GetProperty("inputSets").GetProperty("src/Example/Example.csproj").EnumerateArray(), + input => input.GetString() == "src/Example/Existing.cs" + ); } [Fact] @@ -681,31 +925,46 @@ public async Task TestImplementationChangesKeepBehaviorWithoutRecheckingUnchange repository.Write("tests/Example.Tests/Changed.cs", "namespace Example.Tests; public sealed class Changed { }"); using JsonDocument tests = await repository.PlanAsync(); Assert.True(tests.RootElement.GetProperty("portableTestChanges").GetBoolean()); - JsonElement api = Assert.Single(tests.RootElement.GetProperty("checks").EnumerateArray().Where(check => check.GetProperty("kind").GetString() == "api")); + JsonElement api = Assert.Single( + tests.RootElement.GetProperty("checks").EnumerateArray().Where(check => check.GetProperty("kind").GetString() == "api") + ); Assert.False(string.IsNullOrWhiteSpace(api.GetProperty("exclusion").GetString())); - Assert.Contains(tests.RootElement.GetProperty("checks").EnumerateArray(), check => check.GetProperty("kind").GetString() == "test" - && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null); + Assert.Contains(tests.RootElement.GetProperty("checks").EnumerateArray(), check => ( + check.GetProperty("kind").GetString() == "test" + && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null + )); repository.Write("src/Example/Changed.cs", "namespace Example; public sealed class Changed { }"); using JsonDocument production = await repository.PlanAsync(); Assert.False(production.RootElement.GetProperty("portableTestChanges").GetBoolean()); - api = Assert.Single(production.RootElement.GetProperty("checks").EnumerateArray().Where(check => check.GetProperty("kind").GetString() == "api")); + api = Assert.Single( + production.RootElement.GetProperty("checks").EnumerateArray().Where(check => check.GetProperty("kind").GetString() == "api") + ); Assert.Equal(JsonValueKind.Null, api.GetProperty("exclusion").ValueKind); Assert.Contains(api.GetProperty("projects").EnumerateArray(), project => project.GetString() == "src/Example/Example.csproj"); - Assert.DoesNotContain(api.GetProperty("projects").EnumerateArray(), project => project.GetString() == "tests/Example.Tests/Example.Tests.csproj"); + Assert.DoesNotContain( + api.GetProperty("projects").EnumerateArray(), + project => project.GetString() == "tests/Example.Tests/Example.Tests.csproj" + ); } [Fact] public async Task ReferencePropertyVariantsPreserveConditionalSourceInputsAndNativeRequirements() { using var repository = new ValidationRepository(); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project(""" + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project(""" player - """)); - repository.Write("tests/Example.Tests/Example.Tests.csproj", ValidationRepository.Project(""" + """) + ); + repository.Write( + "tests/Example.Tests/Example.Tests.csproj", + ValidationRepository.Project(""" truedomain - """)); + """) + ); repository.Write("fixtures/Selected.cs", "namespace Example; public sealed class Selected { }"); repository.Git("add", "."); repository.Git("commit", "-m", "Declare conditional reference inputs"); @@ -726,10 +985,13 @@ public async Task SolutionTargetsInvalidateCompilationAndExpandSharedAcceptance( repository.Write("Directory.Solution.targets", ""); using JsonDocument plan = await repository.PlanAsync(); Assert.True(plan.RootElement.GetProperty("full").GetBoolean()); - Assert.Contains(plan.RootElement.GetProperty("inputSets").GetProperty("tooling").EnumerateArray(), - input => input.GetString() == "Directory.Solution.targets"); - Assert.Contains(plan.RootElement.GetProperty("checks").EnumerateArray(), check => - check.GetProperty("kind").GetString() == "build" && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null); + Assert.Contains( + plan.RootElement.GetProperty("inputSets").GetProperty("tooling").EnumerateArray(), + input => input.GetString() == "Directory.Solution.targets" + ); + Assert.Contains(plan.RootElement.GetProperty("checks").EnumerateArray(), check => ( + check.GetProperty("kind").GetString() == "build" && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null + )); } [Fact] @@ -739,15 +1001,26 @@ public async Task UnknownInputsExpandAndReportTheirReason() repository.Write("unknown.input", "unknown relation"); using JsonDocument plan = await repository.PlanAsync(); Assert.True(plan.RootElement.GetProperty("full").GetBoolean()); - Assert.Contains(plan.RootElement.GetProperty("diagnostics").EnumerateArray(), value => value.GetString()!.Contains("unknown.input", StringComparison.Ordinal)); + Assert.Contains( + plan.RootElement.GetProperty("diagnostics").EnumerateArray(), + value => value.GetString()!.Contains("unknown.input", StringComparison.Ordinal) + ); } [Fact] public async Task DomainSuiteCannotTransitivelyReachNativePreparation() { using var repository = new ValidationRepository(); - repository.Write("backends/Example/native/Native/Native.csproj", ValidationRepository.Project("fixture")); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project("")); + repository.Write( + "backends/Example/native/Native/Native.csproj", + ValidationRepository.Project("fixture") + ); + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project( + "" + ) + ); await Assert.ThrowsAsync(() => repository.PlanAsync()); } @@ -755,11 +1028,22 @@ public async Task DomainSuiteCannotTransitivelyReachNativePreparation() public async Task CommittedBindingDeclarationsDoNotRequireRuntimeDeployment() { using var repository = new ValidationRepository(); - repository.Write("backends/Example/native/Native/Native.csproj", ValidationRepository.Project("true")); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project("")); + repository.Write( + "backends/Example/native/Native/Native.csproj", + ValidationRepository.Project("true") + ); + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project( + "" + ) + ); using JsonDocument plan = await repository.PlanAsync(); Assert.False(plan.RootElement.GetProperty("contexts").TryGetProperty("native", out _)); - JsonElement check = plan.RootElement.GetProperty("checks").EnumerateArray().Single(check => check.GetProperty("id").GetString() == "test:tests/Example.Tests/Example.Tests.csproj"); + JsonElement check = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(check => check.GetProperty("id").GetString() == "test:tests/Example.Tests/Example.Tests.csproj"); Assert.Equal("managed", check.GetProperty("context").GetString()); Assert.Equal(JsonValueKind.Null, check.GetProperty("exclusion").ValueKind); } @@ -777,11 +1061,18 @@ public async Task AManagedInteropOwnerDoesNotBecomeNativePreparationBecauseOfIts { using var repository = new ValidationRepository(); repository.Write("backends/Example/native/Loader/Loader.csproj", ValidationRepository.Project()); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project( - "")); + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project( + "" + ) + ); using JsonDocument plan = await repository.PlanAsync(); Assert.False(plan.RootElement.GetProperty("contexts").TryGetProperty("native", out _)); - JsonElement domain = plan.RootElement.GetProperty("checks").EnumerateArray().Single(check => check.GetProperty("id").GetString() == "test:tests/Example.Tests/Example.Tests.csproj"); + JsonElement domain = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(check => check.GetProperty("id").GetString() == "test:tests/Example.Tests/Example.Tests.csproj"); Assert.Equal("managed", domain.GetProperty("context").GetString()); } @@ -791,14 +1082,17 @@ public async Task MissingOrStaleResultsCannotBecomeGreenEvidence() using var repository = new ValidationRepository(); using JsonDocument plan = await repository.PlanAsync(); string evidence = repository.PathOf("artifacts/empty.json"); - File.WriteAllText(evidence, JsonSerializer.Serialize(new - { - commit = plan.RootElement.GetProperty("commit").GetString(), - tree = plan.RootElement.GetProperty("tree").GetString(), - environment = plan.RootElement.GetProperty("environment").GetString(), - started = DateTimeOffset.UtcNow, - results = Array.Empty() - })); + File.WriteAllText( + evidence, + JsonSerializer.Serialize(new + { + commit = plan.RootElement.GetProperty("commit").GetString(), + tree = plan.RootElement.GetProperty("tree").GetString(), + environment = plan.RootElement.GetProperty("environment").GetString(), + started = DateTimeOffset.UtcNow, + results = Array.Empty() + }) + ); await Assert.ThrowsAsync(() => repository.EvidenceAsync(evidence)); repository.Write("tests/Example.Tests/Changed.cs", "namespace Example.Tests; public sealed class Changed { }"); await Assert.ThrowsAsync(() => repository.EvidenceAsync(evidence)); @@ -830,48 +1124,111 @@ public async Task NativeContextUsesTheDeclaredDevelopmentProductAndKeepsDomainOw using var repository = new ValidationRepository(); string properties = repository.PathOf("Product.props"); repository.Write("Product.props", ""); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "fixture-target" - + properties + "")); - repository.Write("backends/Example/native/Native/Native.csproj", ValidationRepository.Project( - "true" - + "fixture-targetRelease")); - repository.Write("tests/backends/Example/Native.Tests/Native.Tests.csproj", ValidationRepository.Project( - "truenativeeditorcross-target" - + "")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "fixture-target" + + properties + "" + ) + ); + repository.Write( + "backends/Example/native/Native/Native.csproj", + ValidationRepository.Project( + "true" + + "fixture-targetRelease" + ) + ); + repository.Write( + "tests/backends/Example/Native.Tests/Native.Tests.csproj", + ValidationRepository.Project( + "truenativeeditorcross-target" + + "" + ) + ); using JsonDocument plan = await repository.PlanAsync(); - Assert.Equal("fixture-target", plan.RootElement.GetProperty("contexts").GetProperty("native").GetProperty("properties").GetProperty("InnoNativeTarget").GetString()); - JsonElement domain = plan.RootElement.GetProperty("checks").EnumerateArray().Single(check => check.GetProperty("id").GetString() == "test:tests/Example.Tests/Example.Tests.csproj"); + Assert.Equal( + "fixture-target", + plan.RootElement + .GetProperty("contexts") + .GetProperty("native") + .GetProperty("properties") + .GetProperty("InnoNativeTarget") + .GetString() + ); + JsonElement domain = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(check => check.GetProperty("id").GetString() == "test:tests/Example.Tests/Example.Tests.csproj"); Assert.Equal("managed", domain.GetProperty("context").GetString()); - JsonElement native = plan.RootElement.GetProperty("checks").EnumerateArray().Single(check => check.GetProperty("id").GetString() == "test:tests/backends/Example/Native.Tests/Native.Tests.csproj"); + JsonElement native = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(check => check.GetProperty("id").GetString() == "test:tests/backends/Example/Native.Tests/Native.Tests.csproj"); Assert.Equal("native", native.GetProperty("context").GetString()); - Assert.Contains(plan.RootElement.GetProperty("nativeRequests").EnumerateArray(), request => + Assert.Contains(plan.RootElement.GetProperty("nativeRequests").EnumerateArray(), request => ( request.GetProperty("product").GetString() == "fixture-tools" && request.GetProperty("configuration").GetString() == "Release" - && request.GetProperty("target").GetString() == "fixture-target"); - Assert.Contains(plan.RootElement.GetProperty("nativeRequests").EnumerateArray(), request => - request.GetProperty("product").GetString() == "editor" && request.GetProperty("target").GetString() == "cross-target"); - Assert.DoesNotContain(plan.RootElement.GetProperty("nativeRequests").EnumerateArray(), request => - request.GetProperty("product").GetString() == "editor" && request.GetProperty("target").GetString() == "fixture-target"); + && request.GetProperty("target").GetString() == "fixture-target" + )); + Assert.Contains(plan.RootElement.GetProperty("nativeRequests").EnumerateArray(), request => ( + request.GetProperty("product").GetString() == "editor" && request.GetProperty("target").GetString() == "cross-target" + )); + Assert.DoesNotContain(plan.RootElement.GetProperty("nativeRequests").EnumerateArray(), request => ( + request.GetProperty("product").GetString() == "editor" && request.GetProperty("target").GetString() == "fixture-target" + )); JsonElement contexts = plan.RootElement.GetProperty("contexts"); - string Output(string context) => contexts.GetProperty(context).GetProperty("sdkGraph").EnumerateArray() - .Single(node => repository.BindWorkspace(node.GetProperty("Path").GetString()!) == repository.PathOf("src/Example/Example.csproj")) - .GetProperty("Properties").GetProperty("TargetPath").GetString()!; + string Output(string context) + => contexts.GetProperty(context) + .GetProperty("sdkGraph") + .EnumerateArray() + .Single( + node => ( + repository.BindWorkspace( + node.GetProperty("Path").GetString()! + ) == repository.PathOf("src/Example/Example.csproj") + ) + ) + .GetProperty("Properties") + .GetProperty("TargetPath") + .GetString()!; Assert.NotEqual(Output("managed"), Output("native")); - Assert.StartsWith(contexts.GetProperty("native").GetProperty("properties").GetProperty("ArtifactsPath").GetString()!, Output("native"), StringComparison.Ordinal); - string[] sequence = plan.RootElement.GetProperty("checks").EnumerateArray().Select(check => check.GetProperty("id").GetString()!).ToArray(); + Assert.StartsWith( + contexts.GetProperty("native").GetProperty("properties").GetProperty("ArtifactsPath").GetString()!, + Output("native"), + StringComparison.Ordinal + ); + string[] sequence = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Select(check => check.GetProperty("id").GetString()!) + .ToArray(); const string C_NATIVE_BUILD = "build:tests/backends/Example/Native.Tests/Native.Tests.csproj"; - Assert.Equal("managed", plan.RootElement.GetProperty("checks").EnumerateArray() - .Single(check => check.GetProperty("id").GetString() == "build:backends/Example/native/Native/Native.csproj") - .GetProperty("context").GetString()); + Assert.Equal( + "managed", + plan.RootElement.GetProperty("checks") + .EnumerateArray() + .Single(check => check.GetProperty("id").GetString() == "build:backends/Example/native/Native/Native.csproj") + .GetProperty("context") + .GetString() + ); Assert.True(Array.IndexOf(sequence, domain.GetProperty("id").GetString()!) < Array.IndexOf(sequence, C_NATIVE_BUILD)); await Assert.ThrowsAsync(() => repository.RunAsync()); using JsonDocument results = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/run/results.json"))); JsonElement[] recorded = results.RootElement.GetProperty("results").EnumerateArray().ToArray(); Assert.Equal(sequence, recorded.Select(result => result.GetProperty("id").GetString()!).ToArray()); - Assert.All(results.RootElement.GetProperty("failures").EnumerateArray(), fault => Assert.Equal("test-execution", fault.GetProperty("stage").GetString())); - Assert.Equal("Blocked", results.RootElement.GetProperty("results").EnumerateArray().Single(result => result.GetProperty("id").GetString() == C_NATIVE_BUILD) - .GetProperty("status").GetString()); + Assert.All( + results.RootElement.GetProperty("failures").EnumerateArray(), + fault => Assert.Equal("test-execution", fault.GetProperty("stage").GetString()) + ); + Assert.Equal( + "Blocked", + results.RootElement + .GetProperty("results") + .EnumerateArray() + .Single(result => result.GetProperty("id").GetString() == C_NATIVE_BUILD) + .GetProperty("status") + .GetString() + ); } [Theory] @@ -881,30 +1238,53 @@ public async Task BindingConsumptionUsesItsProductOwnerOrItsExplicitStandaloneSe { using var repository = new ValidationRepository(); repository.Write("Product.props", ""); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "fixture-target" - + repository.PathOf("Product.props") + "")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "fixture-target" + + repository.PathOf("Product.props") + "" + ) + ); const string C_BINDING = "backends/Example/native/Native/Native.csproj"; - repository.Write(C_BINDING, ValidationRepository.Project( - "trueeditor")); - string consumer = standalone ? "backends/Example/runtime/Adapter/Adapter.csproj" - : "tests/backends/Example/Native.Tests/Native.Tests.csproj"; - string reference = Path.GetRelativePath(Path.GetDirectoryName(repository.PathOf(consumer))!, repository.PathOf(C_BINDING)).Replace('\\', '/'); + repository.Write( + C_BINDING, + ValidationRepository.Project( + "trueeditor" + ) + ); + string consumer = standalone + ? "backends/Example/runtime/Adapter/Adapter.csproj" + : "tests/backends/Example/Native.Tests/Native.Tests.csproj"; + string reference = Path.GetRelativePath(Path.GetDirectoryName(repository.PathOf(consumer))!, repository.PathOf(C_BINDING)) + .Replace('\\', '/'); string prerequisite = standalone ? "" : "truenativeplayerfixture-target"; - repository.Write(consumer, ValidationRepository.Project(prerequisite - + "")); + repository.Write( + consumer, + ValidationRepository.Project( + prerequisite + + "" + ) + ); if (standalone) - repository.Write("tests/backends/Example/Adapter.Tests/Adapter.Tests.csproj", ValidationRepository.Project( - "truenativeplayerfixture-target" - + "")); + { + repository.Write( + "tests/backends/Example/Adapter.Tests/Adapter.Tests.csproj", + ValidationRepository.Project( + "truenativeplayerfixture-target" + + "" + ) + ); + } repository.Git("add", "."); repository.Git("commit", "-m", "Declare a native binding and its consumer ownership"); repository.Write(Path.GetDirectoryName(consumer) + "/Changed.cs", "public sealed class Changed { }"); using JsonDocument plan = await repository.PlanAsync(); - string[] products = plan.RootElement.GetProperty("nativeRequests").EnumerateArray() - .Select(request => request.GetProperty("product").GetString()!).ToArray(); + string[] products = plan.RootElement.GetProperty("nativeRequests") + .EnumerateArray() + .Select(request => request.GetProperty("product").GetString()!) + .ToArray(); if (standalone) { Assert.Contains("editor", products); @@ -922,25 +1302,43 @@ public async Task NativeDocumentationFragmentsUseTheirOwnerExecutionContext() { using var repository = new ValidationRepository(); repository.Write("Product.props", ""); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "fixture-target" - + repository.PathOf("Product.props") + "")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "fixture-target" + + repository.PathOf("Product.props") + "" + ) + ); const string C_OWNER = "backends/Example/runtime/Adapter/Adapter.csproj"; - repository.Write("backends/Example/native/Native/Native.csproj", ValidationRepository.Project("true")); - repository.Write(C_OWNER, ValidationRepository.Project("editorfixture-target" - + "")); + repository.Write( + "backends/Example/native/Native/Native.csproj", + ValidationRepository.Project("true") + ); + repository.Write( + C_OWNER, + ValidationRepository.Project( + "editorfixture-target" + + "" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare a managed adapter with native prerequisites"); var docs = new ValidationDocumentationFixture(repository); docs.Initialize(); DocumentationResult baseline = await docs.IndexAsync(); - docs.Write("content/en/arbitrary-contract.md", ValidationDocumentationFixture.Page("Adapter", "Use the managed adapter.\n\n```csharp\nint value = 1;\n```\n", "host")); + docs.Write( + "content/en/arbitrary-contract.md", + ValidationDocumentationFixture.Page("Adapter", "Use the managed adapter.\n\n```csharp\nint value = 1;\n```\n", "host") + ); DocumentationResult current = await docs.IndexAsync(); using JsonDocument plan = await docs.PlanAsync(current, baseline); JsonElement[] checks = plan.RootElement.GetProperty("checks").EnumerateArray().ToArray(); JsonElement examples = Assert.Single(checks.Where(check => check.GetProperty("kind").GetString() == "documentation-examples")); Assert.Equal("native", examples.GetProperty("context").GetString()); - Assert.Equal("task-adapter", Assert.Single(examples.GetProperty("documentation").GetProperty("pages").EnumerateArray()).GetString()); + Assert.Equal( + "task-adapter", + Assert.Single(examples.GetProperty("documentation").GetProperty("pages").EnumerateArray()).GetString() + ); Assert.Contains("build:" + C_OWNER, examples.GetProperty("prerequisites").EnumerateArray().Select(item => item.GetString())); } @@ -951,18 +1349,30 @@ public async Task ProductExamplesRequireTheirEvaluatedTargetWithoutPreparingFore { using var repository = new ValidationRepository(); repository.Write("Product.props", ""); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "fixture-target" - + repository.PathOf("Product.props") + "")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "fixture-target" + + repository.PathOf("Product.props") + "" + ) + ); const string C_OWNER = "src/Fixture/Product/Product.csproj"; - repository.Write(C_OWNER, ValidationRepository.Project("editor" - + (matchingTarget ? "fixture-target" : "foreign-target") + "")); + repository.Write( + C_OWNER, + ValidationRepository.Project( + "editor" + + (matchingTarget ? "fixture-target" : "foreign-target") + "" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare actual product and host target prerequisites"); var docs = new ValidationDocumentationFixture(repository); docs.Initialize(); DocumentationResult baseline = await docs.IndexAsync(); - docs.Write("content/en/product-example.md", ValidationDocumentationFixture.Page("Product", "Compose this product.\n\n```csharp\nint value = 1;\n```\n", "host")); + docs.Write( + "content/en/product-example.md", + ValidationDocumentationFixture.Page("Product", "Compose this product.\n\n```csharp\nint value = 1;\n```\n", "host") + ); DocumentationResult current = await docs.IndexAsync(); using JsonDocument plan = await docs.PlanAsync(current, baseline); JsonElement[] checks = plan.RootElement.GetProperty("checks").EnumerateArray().ToArray(); @@ -989,9 +1399,14 @@ public async Task ExecutionFailureRetainsAnExactPlanReceiptAndCannotCertifySucce using JsonDocument plan = await repository.PlanAsync(); await Assert.ThrowsAsync(() => repository.RunAsync()); using JsonDocument results = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/run/results.json"))); - Assert.Contains(results.RootElement.GetProperty("results").EnumerateArray(), result => result.GetProperty("status").GetString() == "Failed"); + Assert.Contains( + results.RootElement.GetProperty("results").EnumerateArray(), + result => result.GetProperty("status").GetString() == "Failed" + ); Assert.True(results.RootElement.GetProperty("completed").GetBoolean()); - string identity = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(repository.PathOf("artifacts/run/plan.json")))); + string identity = Convert.ToHexStringLower( + System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(repository.PathOf("artifacts/run/plan.json"))) + ); Assert.Equal(identity, results.RootElement.GetProperty("planIdentity").GetString()); await Assert.ThrowsAsync(() => repository.EvidenceAsync(repository.PathOf("artifacts/run/results.json"))); } @@ -1004,26 +1419,49 @@ public async Task ScriptFragmentsUseTheirExplicitProjectionContext(string fence) using var repository = new ValidationRepository(); repository.Write("Product.props", ""); repository.Write("entry/InnoEngine.Build/InnoEngine.Build.csproj", ValidationRepository.Project()); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "editorfixture-target" - + repository.PathOf("Product.props") + "")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "editorfixture-target" + + repository.PathOf("Product.props") + "" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare the script projection prerequisites"); var docs = new ValidationDocumentationFixture(repository); docs.Initialize(); DocumentationResult baseline = await docs.IndexAsync(); - docs.Write("content/en/arbitrary-script.md", ValidationDocumentationFixture.Page("Example", - "Read the projected contract.\n\n" + fence + "csharp\nusing InnoEngine;\n" + fence + "\n", "runtime-script")); + docs.Write( + "content/en/arbitrary-script.md", + ValidationDocumentationFixture.Page( + "Example", + "Read the projected contract.\n\n" + fence + "csharp\nusing InnoEngine;\n" + fence + "\n", + "runtime-script" + ) + ); DocumentationResult current = await docs.IndexAsync(); using JsonDocument plan = await docs.PlanAsync(current, baseline); JsonElement[] checks = plan.RootElement.GetProperty("checks").EnumerateArray().ToArray(); JsonElement examples = Assert.Single(checks.Where(check => check.GetProperty("kind").GetString() == "documentation-examples")); Assert.Equal("native", examples.GetProperty("context").GetString()); - Assert.Equal("task-example", Assert.Single(examples.GetProperty("documentation").GetProperty("pages").EnumerateArray()).GetString()); - Assert.Equal("native", checks.Single(check => check.GetProperty("id").GetString() == "build:src/Example/Example.csproj") - .GetProperty("context").GetString()); - Assert.Contains("build:entry/InnoEngine.Build/InnoEngine.Build.csproj", examples.GetProperty("prerequisites").EnumerateArray().Select(item => item.GetString())); - Assert.Contains("build:entry/InnoEngine.Editor/InnoEngine.Editor.csproj", examples.GetProperty("prerequisites").EnumerateArray().Select(item => item.GetString())); + Assert.Equal( + "task-example", + Assert.Single(examples.GetProperty("documentation").GetProperty("pages").EnumerateArray()).GetString() + ); + Assert.Equal( + "native", + checks.Single(check => check.GetProperty("id").GetString() == "build:src/Example/Example.csproj") + .GetProperty("context") + .GetString() + ); + Assert.Contains( + "build:entry/InnoEngine.Build/InnoEngine.Build.csproj", + examples.GetProperty("prerequisites").EnumerateArray().Select(item => item.GetString()) + ); + Assert.Contains( + "build:entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + examples.GetProperty("prerequisites").EnumerateArray().Select(item => item.GetString()) + ); } [Fact] @@ -1033,23 +1471,41 @@ public async Task ScriptExamplesPrepareTheirDeclaredProductWithoutAProductionSou string properties = repository.PathOf("Product.props"); repository.Write("Product.props", ""); repository.Write("entry/InnoEngine.Build/InnoEngine.Build.csproj", ValidationRepository.Project()); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "editorfixture-target" - + properties + "")); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "editorfixture-target" + + properties + "" + ) + ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare product and build entry"); var docs = new ValidationDocumentationFixture(repository); docs.Initialize(); DocumentationResult baseline = await docs.IndexAsync(); - docs.Write("content/en/script-guide.md", ValidationDocumentationFixture.Page("Example", "Use the editor API.\n\n```csharp\nusing InnoEngine;\n```\n", "editor-script")); + docs.Write( + "content/en/script-guide.md", + ValidationDocumentationFixture.Page("Example", "Use the editor API.\n\n```csharp\nusing InnoEngine;\n```\n", "editor-script") + ); DocumentationResult current = await docs.IndexAsync(); using JsonDocument plan = await docs.PlanAsync(current, baseline); Assert.Empty(Owners(plan)); - JsonElement examples = plan.RootElement.GetProperty("checks").EnumerateArray().Single(check => check.GetProperty("id").GetString() == "documentation-examples:native"); + JsonElement examples = plan.RootElement + .GetProperty("checks") + .EnumerateArray() + .Single(check => check.GetProperty("id").GetString() == "documentation-examples:native"); string[] prerequisites = examples.GetProperty("prerequisites").EnumerateArray().Select(value => value.GetString()!).ToArray(); Assert.Contains("build:entry/InnoEngine.Build/InnoEngine.Build.csproj", prerequisites); Assert.Contains("build:entry/InnoEngine.Editor/InnoEngine.Editor.csproj", prerequisites); - Assert.Equal("fixture-target", plan.RootElement.GetProperty("contexts").GetProperty("native").GetProperty("properties").GetProperty("InnoToolTarget").GetString()); + Assert.Equal( + "fixture-target", + plan.RootElement + .GetProperty("contexts") + .GetProperty("native") + .GetProperty("properties") + .GetProperty("InnoToolTarget") + .GetString() + ); } [Fact] @@ -1139,9 +1595,18 @@ bool documentation } repository.Write("src/Native/Changed.cs", "// An affected native owner requires explicit preparation."); string output = repository.PathOf("artifacts/preflight"); - int status = await ValidationCommand.ExecuteAsync([operation, "--engine-root", repository.PathOf("."), - "--dotnet", repository.dotnet, "--base", "HEAD", "--output", output, - ..snapshot is null ? Array.Empty() : new[] { "--docs-cache-root", docs.cache, "--docs-snapshot", snapshot.snapshot! }]); + int status = await ValidationCommand.ExecuteAsync([ + operation, + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--base", + "HEAD", + "--output", + output, + ..snapshot is null ? Array.Empty() : new[] { "--docs-cache-root", docs.cache, "--docs-snapshot", snapshot.snapshot! } + ]); Assert.Equal(2, status); using JsonDocument report = JsonDocument.Parse(File.ReadAllText(Path.Combine(output, "preparation.json"))); @@ -1200,8 +1665,12 @@ public async Task SubmoduleLinksAreVerifiedAsLinkTextWithoutFollowingTheirTarget using var repository = new ValidationRepository(); repository.Git("-c", "protocol.file.allow=always", "submodule", "add", source.PathOf("."), "extern/Native"); repository.Git("commit", "-am", "Pin source with a symbolic link"); - repository.Write("src/Example/Example.csproj", ValidationRepository.Project( - "")); + repository.Write( + "src/Example/Example.csproj", + ValidationRepository.Project( + "" + ) + ); source.Write("src/Probe.cs", "namespace Native; public class Probe { }"); source.Git("add", "src/Probe.cs"); source.Git("commit", "-m", "Declare a compiler input"); @@ -1210,10 +1679,14 @@ public async Task SubmoduleLinksAreVerifiedAsLinkTextWithoutFollowingTheirTarget repository.Git("add", "extern/Native"); repository.Git("commit", "-m", "Update compiler input owner"); using JsonDocument plan = await repository.PlanAsync(); - Assert.Contains(plan.RootElement.GetProperty("inputSets").GetProperty("src/Example/Example.csproj").EnumerateArray(), - input => input.GetString() == "extern/Native"); - Assert.Contains(plan.RootElement.GetProperty("inputSets").GetProperty("native-sources").EnumerateArray(), - input => input.GetString() == "extern/Native"); + Assert.Contains( + plan.RootElement.GetProperty("inputSets").GetProperty("src/Example/Example.csproj").EnumerateArray(), + input => input.GetString() == "extern/Native" + ); + Assert.Contains( + plan.RootElement.GetProperty("inputSets").GetProperty("native-sources").EnumerateArray(), + input => input.GetString() == "extern/Native" + ); string path = repository.PathOf("extern/Native/link.txt"); repository.Git("-C", "extern/Native", "update-index", "--assume-unchanged", "link.txt"); if (new FileInfo(path).LinkTarget is not null) @@ -1222,7 +1695,9 @@ public async Task SubmoduleLinksAreVerifiedAsLinkTextWithoutFollowingTheirTarget File.CreateSymbolicLink(path, "../../another-owner.txt"); } else + { File.WriteAllText(path, "../../another-owner.txt"); + } InvalidDataException failure = await Assert.ThrowsAsync(() => repository.PlanAsync()); Assert.Contains("uncommitted inputs", failure.Message, StringComparison.Ordinal); } @@ -1239,48 +1714,107 @@ public async Task ExtendedAcceptanceIncludesColdWarmLifecycleAndReleaseProductRe repository.Write("Product.props", ""); repository.Write("entry/InnoEngine.Build/InnoEngine.Build.csproj", ValidationRepository.Project()); repository.Write("src/PlayerOnly/PlayerOnly.csproj", ValidationRepository.Project()); - repository.Write("platforms/Fixture/player/Player.csproj", ValidationRepository.Project( - "playerfixture-target" - + "")); + repository.Write( + "platforms/Fixture/player/Player.csproj", + ValidationRepository.Project( + "playerfixture-target" + + "" + ) + ); // Native tests use the product preparation properties without becoming a publishable Player. - repository.Write("tests/Player.Tests/Player.Tests.csproj", ValidationRepository.Project( - "trueintegration" - + "playerfixture-target" - + "playerfixture-target")); - repository.Write("tests/fixtures/PlayerFixture/PlayerFixture.csproj", ValidationRepository.Project( - "trueplayer" - + "fixture-target")); - repository.Write("entry/InnoEngine.Editor/InnoEngine.Editor.csproj", ValidationRepository.Project( - "editorfixture-target" - + repository.PathOf("Product.props") + "")); + repository.Write( + "tests/Player.Tests/Player.Tests.csproj", + ValidationRepository.Project( + "trueintegration" + + "playerfixture-target" + + "playerfixture-target" + ) + ); + repository.Write( + "tests/fixtures/PlayerFixture/PlayerFixture.csproj", + ValidationRepository.Project( + "trueplayer" + + "fixture-target" + ) + ); + repository.Write( + "entry/InnoEngine.Editor/InnoEngine.Editor.csproj", + ValidationRepository.Project( + "editorfixture-target" + + repository.PathOf("Product.props") + "" + ) + ); using JsonDocument plan = await repository.PlanAsync(extended: true, configuration: configuration); Assert.True(plan.RootElement.GetProperty("full").GetBoolean()); Assert.True(plan.RootElement.GetProperty("extended").GetBoolean()); JsonElement.ArrayEnumerator checks = plan.RootElement.GetProperty("checks").EnumerateArray(); - foreach (string required in new[] { "cold-inputs", "native-hot-builds", "editor-products", "support-pack", "native-aot-restore", "release-bundle" }) - Assert.Contains(checks, check => check.GetProperty("id").GetString() == required && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null); + foreach (string required in new[] { + "cold-inputs", + "native-hot-builds", + "editor-products", + "support-pack", + "native-aot-restore", + "release-bundle" + }) { + Assert.Contains( + checks, + check => check.GetProperty("id").GetString() == required && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null + ); + } JsonElement bundle = checks.Single(check => check.GetProperty("id").GetString() == "release-bundle"); string releaseContext = bundle.GetProperty("context").GetString()!; - Assert.Equal("Release", plan.RootElement.GetProperty("contexts").GetProperty(releaseContext).GetProperty("properties").GetProperty("Configuration").GetString()); + Assert.Equal( + "Release", + plan.RootElement + .GetProperty("contexts") + .GetProperty(releaseContext) + .GetProperty("properties") + .GetProperty("Configuration") + .GetString() + ); if (configuration != "Release") { - Assert.Contains(checks, check => check.GetProperty("id").GetString() == "editor-release-products" - && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null); - Assert.NotEqual(plan.RootElement.GetProperty("contexts").GetProperty("native").GetProperty("properties").GetProperty("ArtifactsPath").GetString(), - plan.RootElement.GetProperty("contexts").GetProperty(releaseContext).GetProperty("properties").GetProperty("ArtifactsPath").GetString()); + Assert.Contains(checks, check => ( + check.GetProperty("id").GetString() == "editor-release-products" + && check.GetProperty("exclusion").ValueKind == JsonValueKind.Null + )); + Assert.NotEqual( + plan.RootElement + .GetProperty("contexts") + .GetProperty("native") + .GetProperty("properties") + .GetProperty("ArtifactsPath") + .GetString(), + plan.RootElement + .GetProperty("contexts") + .GetProperty(releaseContext) + .GetProperty("properties") + .GetProperty("ArtifactsPath") + .GetString() + ); } // Restore-only sources still invalidate the bundle, but their unbuilt standalone DLLs are not package inputs. string[] bundleInputs = bundle.GetProperty("inputs").EnumerateArray().Select(value => value.GetString()!).ToArray(); Assert.Contains("@platforms/Fixture/player/Player.csproj", bundleInputs); Assert.Contains("@src/PlayerOnly/PlayerOnly.csproj", bundleInputs); - Assert.Equal(new[] { "entry/InnoEngine.Build/InnoEngine.Build.csproj", "entry/InnoEngine.Editor/InnoEngine.Editor.csproj" }, - bundle.GetProperty("projects").EnumerateArray().Select(value => value.GetString()!).Order(StringComparer.Ordinal).ToArray()); + Assert.Equal( + new[] { "entry/InnoEngine.Build/InnoEngine.Build.csproj", "entry/InnoEngine.Editor/InnoEngine.Editor.csproj" }, + bundle.GetProperty("projects").EnumerateArray().Select(value => value.GetString()!).Order(StringComparer.Ordinal).ToArray() + ); Assert.Contains("native-aot-restore", bundle.GetProperty("prerequisites").EnumerateArray().Select(value => value.GetString())); - Assert.Equal("platforms/Fixture/player/Player.csproj", - checks.Single(check => check.GetProperty("id").GetString() == "native-aot-restore").GetProperty("owner").GetString()); - Assert.All(checks.Where(check => check.GetProperty("kind").GetString() == "test"), - check => Assert.Equal(check.GetProperty("owner").GetString() == "tests/Player.Tests/Player.Tests.csproj" ? "integration" : "domain", - check.GetProperty("layer").GetString())); + Assert.Equal( + "platforms/Fixture/player/Player.csproj", + checks.Single(check => check.GetProperty("id").GetString() == "native-aot-restore").GetProperty("owner").GetString() + ); + Assert.All( + checks.Where(check => check.GetProperty("kind").GetString() == "test"), + check => Assert.Equal( + check.GetProperty("owner").GetString() == "tests/Player.Tests/Player.Tests.csproj" + ? "integration" + : "domain", + check.GetProperty("layer").GetString() + ) + ); } private static string[] Changes(JsonDocument document) diff --git a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationDocumentationFixture.cs b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationDocumentationFixture.cs index b8861345a..bd232681f 100644 --- a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationDocumentationFixture.cs +++ b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationDocumentationFixture.cs @@ -22,36 +22,62 @@ public void Initialize() .Where(path => !path.StartsWith(repository.PathOf("artifacts") + Path.DirectorySeparatorChar, StringComparison.Ordinal)) .Select(path => new { - name = Path.GetFileNameWithoutExtension(path), path = Path.GetRelativePath(repository.PathOf("."), path).Replace('\\', '/'), - entry = "project-" + Path.GetFileNameWithoutExtension(path).ToLowerInvariant(), surfaces = new[] { "source-clr" } - }).ToArray(); + name = Path.GetFileNameWithoutExtension(path), + path = Path.GetRelativePath(repository.PathOf("."), path).Replace('\\', '/'), + entry = "project-" + Path.GetFileNameWithoutExtension(path).ToLowerInvariant(), + surfaces = new[] { "source-clr" } + }) + .ToArray(); byte[] inventory = JsonSerializer.SerializeToUtf8Bytes(owners); byte[] facts = JsonSerializer.SerializeToUtf8Bytes(new { - model = "source-clr", configuration = "Debug", projects = owners.Select(owner => new + model = "source-clr", + configuration = "Debug", + projects = owners.Select(owner => new { - name = owner.name, project = owner.path, symbols = Array.Empty() + name = owner.name, + project = owner.path, + symbols = Array.Empty() }) }); Write("reference/projects/catalog.json", Encoding.UTF8.GetString(inventory)); Write("reference/api/facts.json", Encoding.UTF8.GetString(facts)); string revision = new('a', 40); string tree = new('b', 40); - Write("reference/engine.lock.json", JsonSerializer.Serialize(new - { - repository = "https://github.com/Wolfiora/InnoEngine", revision, sourceTree = tree, toolingRevision = revision, - projectManifest = "reference/projects/catalog.json", projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(inventory)), - apiManifests = new[] { new + Write( + "reference/engine.lock.json", + JsonSerializer.Serialize(new { - path = "reference/api/facts.json", sha256 = Convert.ToHexStringLower(SHA256.HashData(facts)), model = "source-clr", - configuration = "Debug", sourceRevision = revision, sourceTree = tree - } } - })); + repository = "https://github.com/Wolfiora/InnoEngine", + revision, + sourceTree = tree, + toolingRevision = revision, + projectManifest = "reference/projects/catalog.json", + projectManifestIdentity = Convert.ToHexStringLower(SHA256.HashData(inventory)), + apiManifests = new[] + { + new + { + path = "reference/api/facts.json", + sha256 = Convert.ToHexStringLower(SHA256.HashData(facts)), + model = "source-clr", + configuration = "Debug", + sourceRevision = revision, + sourceTree = tree + } + } + }) + ); // Keep the complete project graph as provenance, but do not author pages // for platform implementations excluded from the documentation catalog. foreach (var owner in owners.Where(owner => !owner.path.StartsWith("platforms/", StringComparison.Ordinal))) - Write("content/en/" + owner.name + ".md", "---\nuid: " + owner.entry + "\nkind: project\nowners: [" + owner.name - + "]\napiSurface: source-clr\n---\n# " + owner.name + "\n\nRead this owner's contract.\n"); + { + Write( + "content/en/" + owner.name + ".md", + "---\nuid: " + owner.entry + "\nkind: project\nowners: [" + owner.name + + "]\napiSurface: source-clr\n---\n# " + owner.name + "\n\nRead this owner's contract.\n" + ); + } } public void Write( @@ -65,9 +91,19 @@ public async Task CaptureAsync(string project) { await repository.BuildAsync(project); string output = repository.PathOf("artifacts/captured-documentation.json"); - if (DocumentationReferences.ExportApi(["--engine-root", repository.PathOf("."), "--dotnet", repository.dotnet, - "--project", project, "--output", output]) != 0) + if (DocumentationReferences.ExportApi([ + "--engine-root", + repository.PathOf("."), + "--dotnet", + repository.dotnet, + "--project", + project, + "--output", + output + ]) != 0 + ) { throw new InvalidOperationException("The fixture's real source contract could not be captured."); + } JsonNode captured = JsonNode.Parse(File.ReadAllBytes(output))!; JsonNode facts = JsonNode.Parse(File.ReadAllBytes(Path.Combine(source, "reference/api/facts.json")))!; JsonArray projects = facts["projects"]!.AsArray(); @@ -86,13 +122,17 @@ public async Task CaptureAsync(string project) public Task PlanAsync( DocumentationResult current, DocumentationResult? previous = null - ) => repository.PlanAsync(documentationCache: cache, documentationSnapshot: current.snapshot, documentationBaseline: previous?.snapshot); + ) => repository.PlanAsync( + documentationCache: cache, + documentationSnapshot: current.snapshot, + documentationBaseline: previous?.snapshot + ); public static string Page( string owner, string body, string? mode = null ) => "---\nuid: task-" + owner.ToLowerInvariant() + "\nkind: how-to\nowners: [" + owner + "]\n" - + (mode is null ? string.Empty : "exampleMode: " + mode + "\nexampleProjects: [" + owner + "]\n") - + "---\n# Work with " + owner + "\n\n" + body; + + (mode is null ? string.Empty : "exampleMode: " + mode + "\nexampleProjects: [" + owner + "]\n") + + "---\n# Work with " + owner + "\n\n" + body; } diff --git a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs index 605135702..672de158f 100644 --- a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs +++ b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs @@ -12,10 +12,18 @@ namespace Inno.Testing.Validation; public sealed class ValidationRepository : IDisposable { - private readonly string m_root = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoValidation", Guid.NewGuid().ToString("N")); + private readonly string m_root = Path.Combine( + new PhysicalPathResolver().Resolve(Path.GetTempPath()), + "InnoValidation", + Guid.NewGuid().ToString("N") + ); + private readonly string m_dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") - ?? Path.Combine(Environment.GetEnvironmentVariable("DOTNET_ROOT") ?? throw new InvalidOperationException("The test requires its selected SDK host."), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet"); + ?? Path.Combine( + Environment.GetEnvironmentVariable("DOTNET_ROOT") + ?? throw new InvalidOperationException("The test requires its selected SDK host."), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); public ValidationRepository(string? source = null) { @@ -40,7 +48,9 @@ public ValidationRepository(string? source = null) File.Copy(original, destination, overwrite: true); } else + { File.Delete(destination); + } } if (changed.Length != 0 || added.Length != 0) { @@ -54,10 +64,13 @@ public ValidationRepository(string? source = null) Write("Shared.props", ""); Write("src/Example/Example.csproj", Project("")); Write("src/Other/Other.csproj", Project()); - Write("tests/Example.Tests/Example.Tests.csproj", Project(""" + Write( + "tests/Example.Tests/Example.Tests.csproj", + Project(""" truedomain - """)); + """) + ); Write("fixtures/plugin.txt", "initial input"); Git("init", "-b", "master"); Git("config", "user.name", "Aaron Liao"); @@ -69,12 +82,19 @@ public ValidationRepository(string? source = null) public void Dispose() { string root = Path.GetFullPath(m_root); - string parent = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoValidation") + Path.DirectorySeparatorChar; + string parent = Path.Combine(new PhysicalPathResolver().Resolve(Path.GetTempPath()), "InnoValidation") + + Path.DirectorySeparatorChar; if (!root.StartsWith(parent, StringComparison.OrdinalIgnoreCase)) + { throw new InvalidOperationException("The fixture owner escaped its temporary boundary."); + } foreach (string file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)) + { if (new FileInfo(file).LinkTarget is null) + { File.SetAttributes(file, FileAttributes.Normal); + } + } Directory.Delete(root, recursive: true); } @@ -95,15 +115,25 @@ string content public string Git(params string[] arguments) { - var start = new ProcessStartInfo("git") { WorkingDirectory = m_root, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + var start = new ProcessStartInfo("git") + { + WorkingDirectory = m_root, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task output = process.StandardOutput.ReadToEndAsync(); Task error = process.StandardError.ReadToEndAsync(); process.WaitForExit(); if (process.ExitCode != 0) + { throw new InvalidOperationException(output.Result + error.Result); + } return output.Result.Trim(); } @@ -120,55 +150,102 @@ public async Task PlanAsync( string? baselinePlan = null ) { string output = PathOf("artifacts/plan"); - await ValidationCommand.ExecuteAsync(["plan", "--engine-root", m_root, "--dotnet", m_dotnet, "--base", baseline, "--output", output, - "--extended", extended.ToString(), "--configuration", configuration, + await ValidationCommand.ExecuteAsync([ + "plan", + "--engine-root", + m_root, + "--dotnet", + m_dotnet, + "--base", + baseline, + "--output", + output, + "--extended", + extended.ToString(), + "--configuration", + configuration, ..profile is null ? Array.Empty() : new[] { "--profile", profile }, ..baselinePlan is null ? Array.Empty() : new[] { "--baseline-plan", baselinePlan }, ..backendStore is null ? Array.Empty() : new[] { "--backend-store", backendStore }, ..nativeDependencies is null ? Array.Empty() : new[] { "--native-dependencies", nativeDependencies }, ..documentationCache is null ? Array.Empty() : new[] { "--docs-cache-root", documentationCache }, ..documentationSnapshot is null ? Array.Empty() : new[] { "--docs-snapshot", documentationSnapshot }, - ..documentationBaseline is null ? Array.Empty() : new[] { "--docs-base-snapshot", documentationBaseline }]); + ..documentationBaseline is null ? Array.Empty() : new[] { "--docs-base-snapshot", documentationBaseline } + ]); return JsonDocument.Parse(File.ReadAllText(Path.Combine(output, "plan.json"))); } public Task EvidenceAsync( string evidence, string plan = "artifacts/plan/plan.json" - ) - => ValidationCommand.ExecuteAsync(["evidence", "--engine-root", m_root, "--dotnet", m_dotnet, - "--plan", PathOf(plan), "--evidence", evidence]); + ) => ValidationCommand.ExecuteAsync([ + "evidence", + "--engine-root", + m_root, + "--dotnet", + m_dotnet, + "--plan", + PathOf(plan), + "--evidence", + evidence + ]); public Task RunCurrentAsync( CancellationToken cancellation, string output - ) - => ValidationCommand.ExecuteAsync(["run", "--engine-root", m_root, "--dotnet", m_dotnet, - "--base", "HEAD", "--output", PathOf(output)], cancellation); + ) => ValidationCommand.ExecuteAsync([ + "run", + "--engine-root", + m_root, + "--dotnet", + m_dotnet, + "--base", + "HEAD", + "--output", + PathOf(output) + ], cancellation); public Task RunAsync( CancellationToken cancellation = default, string output = "artifacts/run", string? evidence = null - ) - => ValidationCommand.ExecuteAsync(["run", "--engine-root", m_root, "--dotnet", m_dotnet, - "--plan", PathOf("artifacts/plan/plan.json"), "--output", PathOf(output), - ..evidence is null ? Array.Empty() : new[] { "--evidence", PathOf(evidence) }], cancellation); + ) => ValidationCommand.ExecuteAsync([ + "run", + "--engine-root", + m_root, + "--dotnet", + m_dotnet, + "--plan", + PathOf("artifacts/plan/plan.json"), + "--output", + PathOf(output), + ..evidence is null ? Array.Empty() : new[] { "--evidence", PathOf(evidence) } + ], cancellation); public Task BuildAsync(params string[] arguments) => SdkAsync(["build", "--disable-build-servers", "-m:1", "-nr:false", ..arguments]); public async Task SdkAsync(params string[] arguments) { - var start = new ProcessStartInfo(m_dotnet) { WorkingDirectory = m_root, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + var start = new ProcessStartInfo(m_dotnet) + { + WorkingDirectory = m_root, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } using Process process = Process.Start(start)!; Task output = process.StandardOutput.ReadToEndAsync(); Task error = process.StandardError.ReadToEndAsync(); await process.WaitForExitAsync(); if (process.ExitCode != 0) + { throw new InvalidOperationException(await output + await error); + } } public static string Project(string content = "") diff --git a/tests/ui/Inno.UI.Tests/UiRuntimeTests.cs b/tests/ui/Inno.UI.Tests/UiRuntimeTests.cs index 2b70e9146..13c676694 100644 --- a/tests/ui/Inno.UI.Tests/UiRuntimeTests.cs +++ b/tests/ui/Inno.UI.Tests/UiRuntimeTests.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; - +using Xunit; using Inno.Assets; using Inno.Core.Input; using Inno.Core.Mathematics; @@ -8,7 +8,6 @@ using Inno.Runtime.Contracts; using Inno.Text; using Inno.UI.Runtime; -using Xunit; namespace Inno.UI.Tests; @@ -26,7 +25,8 @@ public void FrameScopeCapturesInputAndBindsTheScriptFacade() mousePosition: new Vector2(12f, 34f), scrollDelta: new Vector2(0f, 2f), modifiers: KeyModifier.Control, - textInput: ["界"]); + textInput: ["界"] + ); using IDisposable input = InputExecutionContext.EnterScope(new FixedInput(snapshot)); var frame = new RuntimeFrame(7, 1f, 1f, 0.016f, 0.016f, 1f, false); runtime.Attach(); @@ -50,11 +50,16 @@ private sealed class FixedInput(InputSnapshot snapshot) : IInputService private sealed class RejectingArtifacts : IAssetArtifactLookup { - public ArtifactLease AcquireArtifact(Guid persistentId, string outputName) - => throw new InvalidOperationException("No asset access was expected."); + public ArtifactLease AcquireArtifact( + Guid persistentId, + string outputName + ) => throw new InvalidOperationException("No asset access was expected."); - public bool TryGetArtifact(Guid persistentId, string outputName, out AssetArtifactInfo? artifact) - { + public bool TryGetArtifact( + Guid persistentId, + string outputName, + out AssetArtifactInfo? artifact + ) { artifact = null; return false; } @@ -68,22 +73,88 @@ private sealed class CapturingBackend : IUiBackend public UiBackendCapabilities capabilities { get; } = new([new("tests.ui-language")], true); public UiContextHandle CreateContext(UiContextOptions options) => new(1); - public void DestroyContext(UiContextHandle context) { } - public void SetViewport(UiContextHandle context, int width, int height, float density) { } - public UiDocumentHandle LoadDocument(UiContextHandle context, UiDocumentSource source) => new(1); - public void ShowDocument(UiContextHandle context, UiDocumentHandle document) { } - public void HideDocument(UiContextHandle context, UiDocumentHandle document) { } - public void CloseDocument(UiContextHandle context, UiDocumentHandle document) { } - public bool SetText(UiContextHandle context, UiDocumentHandle document, string elementId, string text) => true; - public bool SetContent(UiContextHandle context, UiDocumentHandle document, string elementId, UiDocumentFragment content) => true; - public bool SetAttribute(UiContextHandle context, UiDocumentHandle document, string elementId, string name, string value) => true; - public bool SetClass(UiContextHandle context, UiDocumentHandle document, string elementId, string className, bool active) => true; - public void RegisterFont(UiFontRegistration registration) { } - public void RegisterTexture(UiContextHandle context, string source, UiTextureData texture) { } - public bool HasElementAtPoint(UiContextHandle context, Inno.Core.Mathematics.Vector2 position) => false; - public void Update(UiContextHandle context, UiInputSnapshot input) => lastInput = input; + + public void DestroyContext(UiContextHandle context) {} + + public void SetViewport( + UiContextHandle context, + int width, + int height, + float density + ) {} + + public UiDocumentHandle LoadDocument( + UiContextHandle context, + UiDocumentSource source + ) => new(1); + + public void ShowDocument( + UiContextHandle context, + UiDocumentHandle document + ) {} + + public void HideDocument( + UiContextHandle context, + UiDocumentHandle document + ) {} + + public void CloseDocument( + UiContextHandle context, + UiDocumentHandle document + ) {} + + public bool SetText( + UiContextHandle context, + UiDocumentHandle document, + string elementId, + string text + ) => true; + + public bool SetContent( + UiContextHandle context, + UiDocumentHandle document, + string elementId, + UiDocumentFragment content + ) => true; + + public bool SetAttribute( + UiContextHandle context, + UiDocumentHandle document, + string elementId, + string name, + string value + ) => true; + + public bool SetClass( + UiContextHandle context, + UiDocumentHandle document, + string elementId, + string className, + bool active + ) => true; + + public void RegisterFont(UiFontRegistration registration) {} + + public void RegisterTexture( + UiContextHandle context, + string source, + UiTextureData texture + ) {} + + public bool HasElementAtPoint( + UiContextHandle context, + Inno.Core.Mathematics.Vector2 position + ) => false; + + public void Update( + UiContextHandle context, + UiInputSnapshot input + ) => lastInput = input; + public UiRenderFrame Render(UiContextHandle context) => UiRenderFrame.empty; + public IReadOnlyList DrainEvents(UiContextHandle context) => []; - public void Dispose() { } + + public void Dispose() {} } } diff --git a/tools/Inno.Tooling.Architecture/AgentDocumentValidator.cs b/tools/Inno.Tooling.Architecture/AgentDocumentValidator.cs index d9b3cd4c6..699df9713 100644 --- a/tools/Inno.Tooling.Architecture/AgentDocumentValidator.cs +++ b/tools/Inno.Tooling.Architecture/AgentDocumentValidator.cs @@ -14,7 +14,9 @@ ICollection failures ) { AgentLinkValidator.Validate(root, failures, ".agents"); foreach (string entry in new[] { "AGENTS.md", "CONTRIBUTING.md", "README.md" }) + { AgentLinkValidator.Validate(root, failures, entry); + } string instructionPath = Path.Combine(root, "AGENTS.md"); string instructions = File.Exists(instructionPath) ? File.ReadAllText(instructionPath) : string.Empty; foreach (string skill in RepositorySourceInventory.Files(Path.Combine(root, ".agents", "skills"), "SKILL.md")) @@ -22,17 +24,32 @@ ICollection failures string text = File.ReadAllText(skill).Replace("\r\n", "\n"); string name = Path.GetFileName(Path.GetDirectoryName(skill)!); if (!text.StartsWith("---\n", StringComparison.Ordinal) || !text.Contains("\nname: " + name + "\n", StringComparison.Ordinal) - || !Regex.IsMatch(text, @"(?m)^description: \S.+$") || text.IndexOf("\n---\n", 4, StringComparison.Ordinal) < 0) + || !Regex.IsMatch(text, @"(?m)^description: \S.+$") || text.IndexOf("\n---\n", 4, StringComparison.Ordinal) < 0 + ) { failures.Add("Invalid skill metadata: " + Path.GetRelativePath(root, skill)); + } if (!instructions.Contains("(.agents/skills/" + name + "/SKILL.md)", StringComparison.Ordinal)) { failures.Add("Skill is not listed in AGENTS.md: " + name); } } - foreach (string category in new[] { "rulebook", "records", "records/plans", "records/decisions", "records/acceptance", "records/history" }) + foreach (string category in new[] { + "rulebook", + "records", + "records/plans", + "records/decisions", + "records/acceptance", + "records/history" + }) { if (!File.Exists(Path.Combine(root, ".agents", category, "README.md"))) + { failures.Add("Missing agent category navigation: " + category); - if (Directory.Exists(Path.Combine(root, "records")) && Directory.EnumerateFiles(Path.Combine(root, "records"), "*", SearchOption.AllDirectories).Any()) + } + } + if (Directory.Exists(Path.Combine(root, "records")) + && Directory.EnumerateFiles(Path.Combine(root, "records"), "*", SearchOption.AllDirectories).Any() + ) { failures.Add("The retired root records owner still contains files."); + } } } diff --git a/tools/Inno.Tooling.Architecture/AgentLinkValidator.cs b/tools/Inno.Tooling.Architecture/AgentLinkValidator.cs index dae2b5aa1..3ee2245ba 100644 --- a/tools/Inno.Tooling.Architecture/AgentLinkValidator.cs +++ b/tools/Inno.Tooling.Architecture/AgentLinkValidator.cs @@ -14,7 +14,9 @@ namespace Inno.Tooling.Architecture; internal static class AgentLinkValidator { private static readonly MarkdownPipeline S_PIPELINE = new MarkdownPipelineBuilder() - .UsePipeTables().UseAutoIdentifiers(AutoIdentifierOptions.GitHub).Build(); + .UsePipeTables() + .UseAutoIdentifiers(AutoIdentifierOptions.GitHub) + .Build(); internal static void Validate( string root, @@ -26,18 +28,23 @@ string contentRoot foreach (string page in File.Exists(location) ? [location] : RepositorySourceInventory.Files(location, "*.md")) { MarkdownDocument parsed = Markdown.Parse(File.ReadAllText(page), S_PIPELINE); - foreach (string target in parsed.Descendants().Where(static link => link.Url is not null) - .Select(static link => link.Url!).Distinct(StringComparer.Ordinal)) - { + foreach (string target in parsed.Descendants() + .Where(static link => link.Url is not null) + .Select(static link => link.Url!) + .Distinct(StringComparer.Ordinal) + ) { if (target.Contains("://", StringComparison.Ordinal) || target.StartsWith("mailto:", StringComparison.Ordinal) - || target.StartsWith("data:", StringComparison.Ordinal)) + || target.StartsWith("data:", StringComparison.Ordinal) + ) { continue; + } string[] pieces = target.Split('#', 2); string path; try { - path = pieces[0].Length == 0 ? page - : Path.GetFullPath(Uri.UnescapeDataString(pieces[0]), Path.GetDirectoryName(page)!); + path = pieces[0].Length == 0 + ? page + : Path.GetFullPath(Uri.UnescapeDataString(pieces[0]), Path.GetDirectoryName(page)!); } catch (ArgumentException) { @@ -50,11 +57,17 @@ string contentRoot continue; } if (pieces.Length < 2 || pieces[1].Length == 0 || !path.EndsWith(".md", StringComparison.OrdinalIgnoreCase)) + { continue; + } if (!anchors.TryGetValue(path, out HashSet? names)) + { anchors.Add(path, names = Anchors(File.ReadAllText(path))); + } if (!names.Contains(Uri.UnescapeDataString(pieces[1]))) + { failures.Add($"Agent document '{Path.GetRelativePath(root, page)}' links to missing anchor '{target}'."); + } } } } @@ -62,12 +75,18 @@ string contentRoot private static HashSet Anchors(string text) { MarkdownDocument document = Markdown.Parse(text, S_PIPELINE); - var result = document.Descendants().Select(static heading => heading.GetAttributes().Id!) + var result = document.Descendants() + .Select(static heading => heading.GetAttributes().Id!) .ToHashSet(StringComparer.Ordinal); - foreach (string html in document.Descendants().Select(block => text[block.Span.Start..(block.Span.End + 1)]) - .Concat(document.Descendants().Select(static inline => inline.Tag))) + foreach (string html in document.Descendants() + .Select(block => text[block.Span.Start..(block.Span.End + 1)]) + .Concat(document.Descendants().Select(static inline => inline.Tag)) + ) { foreach (Match match in Regex.Matches(html, "\\b(?:id|name)=[\"'](?[^\"']+)[\"']")) + { result.Add(match.Groups["name"].Value); + } + } return result; } } diff --git a/tools/Inno.Tooling.Architecture/ArchitectureRules.cs b/tools/Inno.Tooling.Architecture/ArchitectureRules.cs index 964c53cc1..166ae2478 100644 --- a/tools/Inno.Tooling.Architecture/ArchitectureRules.cs +++ b/tools/Inno.Tooling.Architecture/ArchitectureRules.cs @@ -6,9 +6,11 @@ using System.Xml.Linq; namespace Inno.Tooling.Architecture; + internal static partial class ArchitectureRules { private static readonly string[] S_SCAN_ROOTS = ["entry", "src", "backends", "platforms", "build", "tests"]; + private static readonly string[] S_FORBIDDEN_PLAYER_PROJECT_FRAGMENTS = [ "Inno.Editor.", "Inno.Build", @@ -23,7 +25,9 @@ internal static partial class ArchitectureRules "Inno.Adapter.Serialization.DotNet", "Toolchains" ]; + private static readonly string[] S_FORBIDDEN_IMPLEMENTATION_WORDS = ["Legacy", "Compatibility", "Migration", "Former", "Deprecated"]; + private static readonly string[] S_REMOVED_PROJECT_NAMES = [ "Inno.Core.Framework", "Inno.Core.Assemblies", @@ -43,6 +47,7 @@ internal static partial class ArchitectureRules "Inno.Build.Platform.MacOS", "Inno.Build.Platform.Browser" ]; + private static readonly string[] S_CONCRETE_ADAPTER_MARKERS = [ "Inno.Adapter.Platform.Sdl3", "Inno.Adapter.Storage.FileSystem", @@ -55,6 +60,7 @@ internal static partial class ArchitectureRules "MiniAudioDevice", "PlatformImGuiContext" ]; + internal static void Validate( string repositoryRoot, ICollection failures @@ -65,7 +71,9 @@ ICollection failures NativePlatformPolicyValidator.Validate(repositoryRoot, failures); string backendRoot = Path.Combine(repositoryRoot, "backends"); if (Directory.Exists(backendRoot)) + { NativeBindingOwnershipValidator.Validate(repositoryRoot, EnumerateFiles(backendRoot, "*.csproj"), failures); + } ValidateRepositorySources(repositoryRoot, failures); Dictionary graph = LoadProjectGraph(repositoryRoot, failures); ValidateCycles(repositoryRoot, graph, failures); @@ -75,15 +83,11 @@ ICollection failures ValidateRemovedProjects(repositoryRoot, failures); } - internal static bool IsForbiddenPlayerDependency(string assemblyName) => S_FORBIDDEN_PLAYER_PROJECT_FRAGMENTS.Any(fragment => assemblyName.Contains(fragment, StringComparison.Ordinal)) - || assemblyName.StartsWith( - "Inno.Integration.", - StringComparison.Ordinal - ) - && assemblyName.EndsWith( - ".Bgfx", - StringComparison.Ordinal - ); + internal static bool IsForbiddenPlayerDependency(string assemblyName) + => S_FORBIDDEN_PLAYER_PROJECT_FRAGMENTS.Any(fragment => assemblyName.Contains(fragment, StringComparison.Ordinal)) + || assemblyName.StartsWith("Inno.Integration.", StringComparison.Ordinal) + && assemblyName.EndsWith(".Bgfx", StringComparison.Ordinal); + private static void ValidateHostIsolation( string repositoryRoot, ICollection failures @@ -103,23 +107,24 @@ ICollection failures "tools" } - ) - { + ) { foreach (string project in EnumerateFiles(Path.Combine(repositoryRoot, rootName), "*.csproj")) { XDocument document = XDocument.Load(project); bool test = RepositorySourceInventory.IsTestPath(Relative(repositoryRoot, project)); - if (document.Descendants("OutputType").Any(static value => value.Value == "Exe") && !test && !executables.Contains(Path.GetFileNameWithoutExtension(project))) - failures.Add($"{Relative(repositoryRoot, project)}: only the Editor and Build development entries may be production executable projects."); - if (Path.GetFileNameWithoutExtension(project).StartsWith( - "Inno.Native.", - StringComparison.Ordinal - ) - && Path.GetFileNameWithoutExtension(project).EndsWith( - ".Browser", - StringComparison.Ordinal - )) + if (document.Descendants("OutputType").Any(static value => value.Value == "Exe") + && !test + && !executables.Contains(Path.GetFileNameWithoutExtension(project)) + ) { + failures.Add( + $"{Relative(repositoryRoot, project)}: only the Editor and Build development entries may be production executable projects." + ); + } + if (Path.GetFileNameWithoutExtension(project).StartsWith("Inno.Native.", StringComparison.Ordinal) + && Path.GetFileNameWithoutExtension(project).EndsWith(".Browser", StringComparison.Ordinal) + ) { failures.Add($"{Relative(repositoryRoot, project)}: native targets must use binding profiles, not duplicate projects."); + } } } @@ -130,21 +135,30 @@ ICollection failures "src/composition/player/Inno.Player.Runtime" } - ) - { + ) { string root = Path.Combine(repositoryRoot, rootName); if (!Directory.Exists(root)) + { continue; + } foreach (string sourcePath in EnumerateFiles(root, "*.cs")) { if (File.ReadAllText(sourcePath).Contains("OperatingSystem.IsBrowser", StringComparison.Ordinal)) + { failures.Add($"{Relative(repositoryRoot, sourcePath)}: shared code must receive host capabilities through contracts."); + } } } - string browserProject = Path.Combine(repositoryRoot, "platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/Inno.Player.BrowserWasm32.csproj"); - if (File.Exists(browserProject) && XDocument.Load(browserProject).Descendants("Compile").Any(static item => item.Attribute("Link")is not null)) + string browserProject = Path.Combine( + repositoryRoot, + "platforms/BrowserWasm32/player/Inno.Player.BrowserWasm32/Inno.Player.BrowserWasm32.csproj" + ); + if (File.Exists(browserProject) + && XDocument.Load(browserProject).Descendants("Compile").Any(static item => item.Attribute("Link")is not null) + ) { failures.Add("Inno.Player.BrowserWasm32: shared Player source must be consumed through Inno.Player.Runtime."); + } } private static void ValidateRepositorySources( @@ -155,18 +169,26 @@ ICollection failures { string root = Path.Combine(repositoryRoot, rootName); if (!Directory.Exists(root)) + { continue; + } foreach (string path in EnumerateFiles(root, "*.cs")) { string relative = Relative(repositoryRoot, path); string source = File.ReadAllText(path); if (IsGenerated(source)) + { continue; + } ValidateForbiddenImplementationNames(relative, source, failures); if ((RepositorySourceInventory.IsTestPath(relative))) + { ValidateTestSource(relative, source, failures); + } else + { ValidateProductionSource(relative, source, failures); + } } } } @@ -180,7 +202,9 @@ ICollection failures foreach (string word in S_FORBIDDEN_IMPLEMENTATION_WORDS) { if (fileName.Contains(word, StringComparison.OrdinalIgnoreCase)) + { failures.Add($"{relative}: implementation file names cannot contain '{word}'."); + } } foreach (Match match in DeclaredTypePattern().Matches(source)) @@ -189,7 +213,9 @@ ICollection failures foreach (string word in S_FORBIDDEN_IMPLEMENTATION_WORDS) { if (name.Contains(word, StringComparison.OrdinalIgnoreCase)) + { failures.Add($"{relative}: declared implementation '{name}' cannot contain '{word}'."); + } } } } @@ -200,125 +226,71 @@ private static void ValidateProductionSource( ICollection failures ) { if (relative.StartsWith("tools/Inno.Tooling.Architecture/", StringComparison.Ordinal)) - return; - if (relative.StartsWith( - "src/services/platform/", - StringComparison.Ordinal - ) - && (source.Contains( - "PlatformNativeHandles", - StringComparison.Ordinal - ) - || source.Contains( - "PlatformNativeHandleId", - StringComparison.Ordinal - ) - || source.Contains( - "INativeWindowSurface", - StringComparison.Ordinal - ))) { + return; + } + if (relative.StartsWith("src/services/platform/", StringComparison.Ordinal) + && (source.Contains("PlatformNativeHandles", StringComparison.Ordinal) + || source.Contains("PlatformNativeHandleId", StringComparison.Ordinal) + || source.Contains("INativeWindowSurface", StringComparison.Ordinal)) + ) { failures.Add($"{relative}: native surface ABI belongs to platform adapters, not the shared platform service."); } - if (source.Contains( - ".With", - StringComparison.Ordinal - ) + if (source.Contains(".With", StringComparison.Ordinal) && !relative.EndsWith( - "src/content/assets/Inno.Assets/Serialization/AssetSerializationContext.cs", - StringComparison.Ordinal - )) - { + "src/content/assets/Inno.Assets/Serialization/AssetSerializationContext.cs", + StringComparison.Ordinal + ) + ) { failures.Add($"{relative}: asset-aware serialization must use the owner-complete AssetSerializationContext factory."); } if (StaticManagerDeclarationPattern().IsMatch(source)) + { failures.Add($"{relative}: process-wide static Manager ownership is forbidden."); + } if (StaticLogFacadeCallPattern().IsMatch(source)) - failures.Add($"{relative}: engine implementation must use an explicitly owned Logger."); - if ((relative.StartsWith( - "src/composition/editor/", - StringComparison.Ordinal - ) - || relative.StartsWith( - "src/composition/player/Inno.Player/", - StringComparison.Ordinal - )) - && source.Contains( - "_ = typeof(", - StringComparison.Ordinal - )) - { - failures.Add($"{relative}: composition roots must discover engine modules from their declared dependency closure, not typeof anchors."); - } - - if ((relative.StartsWith( - "src/composition/player/Inno.Player.Runtime/", - StringComparison.Ordinal - ) - || relative.StartsWith( - "src/composition/shell/", - StringComparison.Ordinal - )) - && S_CONCRETE_ADAPTER_MARKERS.Any(source.Contains)) - { - failures.Add($"{relative}: product composition must use Shell and backend-neutral adapter contracts instead of concrete backend types."); - } - - if (relative.StartsWith( - "src/adapters/audio/Inno.Adapter.Audio.MiniAudio/", - StringComparison.Ordinal - ) - && (source.Contains( - "AudioContentProvider", - StringComparison.Ordinal - ) - || source.Contains( - "AudioMixerExtension", - StringComparison.Ordinal - ) - || source.Contains( - "AudioMixerFeature", - StringComparison.Ordinal - ) - || source.Contains( - "TypeCatalog", - StringComparison.Ordinal - ) - || source.Contains( - "System.Reflection", - StringComparison.Ordinal - ))) - { - failures.Add($"{relative}: the real-time MiniAudio adapter cannot retain managed extension-generation objects or reflection state."); - } - - if (relative.StartsWith( - "src/services/audio/", - StringComparison.Ordinal - ) - && relative.EndsWith( - "/Properties/ScriptingApi.cs", - StringComparison.Ordinal - ) - && (source.Contains( - "typeof(IAudioDevice)", - StringComparison.Ordinal - ) - || source.Contains( - "typeof(AudioDevice)", - StringComparison.Ordinal - ) - || source.Contains( - "Inno.Native", - StringComparison.Ordinal - ) - || source.Contains( - "typeof(MiniAudio", - StringComparison.Ordinal - ))) { + failures.Add($"{relative}: engine implementation must use an explicitly owned Logger."); + } + if ((relative.StartsWith("src/composition/editor/", StringComparison.Ordinal) + || relative.StartsWith("src/composition/player/Inno.Player/", StringComparison.Ordinal)) + && source.Contains("_ = typeof(", StringComparison.Ordinal) + ) { + failures.Add( + $"{relative}: composition roots must discover engine modules from their declared dependency closure, not typeof anchors." + ); + } + + if ((relative.StartsWith("src/composition/player/Inno.Player.Runtime/", StringComparison.Ordinal) + || relative.StartsWith("src/composition/shell/", StringComparison.Ordinal)) + && S_CONCRETE_ADAPTER_MARKERS.Any(source.Contains) + ) { + failures.Add( + $"{relative}: product composition must use Shell and backend-neutral adapter contracts instead of concrete backend types." + ); + } + + if (relative.StartsWith("src/adapters/audio/Inno.Adapter.Audio.MiniAudio/", StringComparison.Ordinal) + && (source.Contains("AudioContentProvider", StringComparison.Ordinal) + || source.Contains("AudioMixerExtension", StringComparison.Ordinal) + || source.Contains("AudioMixerFeature", StringComparison.Ordinal) + || source.Contains("TypeCatalog", StringComparison.Ordinal) + || source.Contains("System.Reflection", StringComparison.Ordinal)) + ) { + failures.Add( + $"{relative}: the real-time MiniAudio adapter cannot retain managed extension-generation objects or reflection state." + ); + } + + if (relative.StartsWith("src/services/audio/", StringComparison.Ordinal) + && relative.EndsWith("/Properties/ScriptingApi.cs", StringComparison.Ordinal) + && (source.Contains("typeof(IAudioDevice)", StringComparison.Ordinal) + || source.Contains("typeof(AudioDevice)", StringComparison.Ordinal) + || source.Contains("Inno.Native", StringComparison.Ordinal) + || source.Contains("typeof(MiniAudio", StringComparison.Ordinal)) + ) { failures.Add($"{relative}: scripting API cannot export audio devices, native bindings, or backend adapters."); } @@ -347,9 +319,13 @@ private static void ValidateTestSource( ICollection failures ) { if (source.Contains("InternalsVisibleTo", StringComparison.Ordinal)) + { failures.Add($"{relative}: tests cannot introduce friend-assembly access."); + } if (NonPublicReflectionPattern().IsMatch(source)) + { failures.Add($"{relative}: tests cannot penetrate non-public implementation state through reflection."); + } } private static Dictionary LoadProjectGraph( @@ -366,7 +342,11 @@ ICollection failures } XDocument document = XDocument.Load(path); - string name = document.Descendants("AssemblyName").Select(static value => value.Value.Trim()).FirstOrDefault(static value => value.Length > 0) ?? Path.GetFileNameWithoutExtension(path); + string name = document + .Descendants("AssemblyName") + .Select(static value => value.Value.Trim()) + .FirstOrDefault(static value => value.Length > 0) + ?? Path.GetFileNameWithoutExtension(path); var node = new ProjectNode(path, relative, name); graph.Add(Path.GetFullPath(path), node); } @@ -379,13 +359,19 @@ ICollection failures foreach (XElement reference in document.Descendants("ProjectReference")) { if (string.Equals((string? )reference.Attribute("ReferenceOutputAssembly"), "false", StringComparison.OrdinalIgnoreCase)) + { continue; + } string? include = reference.Attribute("Include")?.Value; if (string.IsNullOrWhiteSpace(include)) + { continue; + } // SDK evaluation validates property-based references; this static pass does not invent property values. if (include.Contains("$(", StringComparison.Ordinal)) + { continue; + } string normalizedInclude = include.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); string targetPath = Path.GetFullPath(normalizedInclude, Path.GetDirectoryName(node.path)!); if (!graph.TryGetValue(targetPath, out ProjectNode? target)) @@ -416,25 +402,18 @@ ICollection failures foreach (XElement noWarn in document.Descendants("NoWarn")) { string value = noWarn.Value; - if (value.Contains( - "CS1572", - StringComparison.OrdinalIgnoreCase - ) - || value.Contains( - "CS1573", - StringComparison.OrdinalIgnoreCase - ) - || value.Contains( - "CS1591", - StringComparison.OrdinalIgnoreCase - )) - { + if (value.Contains("CS1572", StringComparison.OrdinalIgnoreCase) + || value.Contains("CS1573", StringComparison.OrdinalIgnoreCase) + || value.Contains("CS1591", StringComparison.OrdinalIgnoreCase) + ) { failures.Add($"{project.relative}: public XML contract warnings cannot be suppressed."); } } } - private static bool IsNativeProject(string path) => path.StartsWith("backends/", StringComparison.Ordinal) && path.Contains("/native/", StringComparison.Ordinal); + private static bool IsNativeProject(string path) + => path.StartsWith("backends/", StringComparison.Ordinal) && path.Contains("/native/", StringComparison.Ordinal); + private static void ValidateReferenceBoundary( ProjectNode project, ProjectNode target, @@ -444,162 +423,97 @@ ICollection failures string targetPath = target.relative; bool foundationTarget = targetPath.StartsWith("src/foundation/", StringComparison.Ordinal); if ((project.name is "Inno.Rendering" or "Inno.Content") && !foundationTarget) + { failures.Add($"{sourcePath}: neutral mechanisms may only reference Foundation contracts, not {targetPath}."); + } if (project.name == "Inno.Rendering.Assets" - && target.name is "Inno.Rendering.Runtime" or "Inno.Rendering.Shaders" or "Inno.Rendering.Assets.Authoring" or "Inno.Assets.Pipeline") + && target.name is "Inno.Rendering.Runtime" or "Inno.Rendering.Shaders" or "Inno.Rendering.Assets.Authoring" or "Inno.Assets.Pipeline" + ) { failures.Add($"{sourcePath}: runtime asset definitions cannot reference authoring or runtime owners in {targetPath}."); - if (project.name == "Inno.Rendering.Runtime" && target.name is "Inno.Rendering.Assets.Authoring" or "Inno.Assets.Pipeline" or "Inno.Rendering.Shaders") + } + if (project.name == "Inno.Rendering.Runtime" + && target.name is "Inno.Rendering.Assets.Authoring" or "Inno.Assets.Pipeline" or "Inno.Rendering.Shaders" + ) { failures.Add($"{sourcePath}: rendering runtime cannot include authoring implementation {targetPath}."); + } if (project.name == "Inno.Rendering.Shaders" && target.name == "Inno.Rendering.Runtime") + { failures.Add($"{sourcePath}: shader authoring cannot depend on the runtime owner {targetPath}."); + } if (project.name == "Inno.Adapter.Input" && (IsNativeProject(targetPath) || IsConcreteAdapter(target.name))) + { failures.Add($"{sourcePath}: shared event input cannot depend on native or platform adapters in {targetPath}."); + } if (project.name == "Inno.Build" - && (targetPath.StartsWith( - "build/composition/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "build/pipeline/Inno.Build.Platform.", - StringComparison.Ordinal - ) - || target.name == "Inno.Build.Managed.DotNet")) + && (targetPath.StartsWith("build/composition/", StringComparison.Ordinal) + || targetPath.StartsWith("build/pipeline/Inno.Build.Platform.", StringComparison.Ordinal) + || target.name == "Inno.Build.Managed.DotNet") + ) { failures.Add($"{sourcePath}: the build pipeline must receive providers instead of referencing {targetPath}."); - if (IsNativeProject(sourcePath) && !IsNativeProject(targetPath) && !(project.name == "Inno.Native.LibraryLoading" && target.name == "Inno.Core.IO")) - { + } + if (IsNativeProject(sourcePath) + && !IsNativeProject(targetPath) + && !(project.name == "Inno.Native.LibraryLoading" && target.name == "Inno.Core.IO") + ) { failures.Add($"{sourcePath}: Native cannot reference upper-layer project {targetPath}."); } - if (sourcePath.StartsWith("src/foundation/", StringComparison.Ordinal) && !targetPath.StartsWith("src/foundation/", StringComparison.Ordinal)) - { + if (sourcePath.StartsWith("src/foundation/", StringComparison.Ordinal) + && !targetPath.StartsWith("src/foundation/", StringComparison.Ordinal) + ) { failures.Add($"{sourcePath}: Core cannot reference upper-layer project {targetPath}."); } - if (sourcePath.StartsWith( - "build/", - StringComparison.Ordinal - ) - && !sourcePath.StartsWith( - "build/cli/", - StringComparison.Ordinal - ) - && targetPath.StartsWith( - "src/composition/editor/", - StringComparison.Ordinal - )) - { + if (sourcePath.StartsWith("build/", StringComparison.Ordinal) + && !sourcePath.StartsWith("build/cli/", StringComparison.Ordinal) + && targetPath.StartsWith("src/composition/editor/", StringComparison.Ordinal) + ) { failures.Add($"{sourcePath}: Build cannot reference Editor project {targetPath}."); } - if ((string.Equals( - project.name, - "Inno.Rendering", - StringComparison.Ordinal - ) - || string.Equals( - project.name, - "Inno.Rendering.Runtime", - StringComparison.Ordinal - )) - && (targetPath.StartsWith( - "build/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/adapters/", - StringComparison.Ordinal - ) - || IsNativeProject(targetPath))) - { + if ((string.Equals(project.name, "Inno.Rendering", StringComparison.Ordinal) + || string.Equals(project.name, "Inno.Rendering.Runtime", StringComparison.Ordinal)) + && (targetPath.StartsWith("build/", StringComparison.Ordinal) + || targetPath.StartsWith("src/adapters/", StringComparison.Ordinal) + || IsNativeProject(targetPath)) + ) { failures.Add($"{sourcePath}: backend-neutral Rendering cannot reference implementation project {targetPath}."); } - if (string.Equals(project.name, "Inno.Build", StringComparison.Ordinal) && targetPath.StartsWith("build/support/", StringComparison.Ordinal)) - { + if (string.Equals(project.name, "Inno.Build", StringComparison.Ordinal) + && targetPath.StartsWith("build/support/", StringComparison.Ordinal) + ) { failures.Add($"{sourcePath}: Build pipeline must depend on the provisioner contract, not Support Pack implementations."); } - if (sourcePath.Contains( - "Inno.Rendering/", - StringComparison.Ordinal - ) - && (targetPath.Contains( - "MaterialGraph", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/content/scene/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/composition/editor/", - StringComparison.Ordinal - ))) - { + if (sourcePath.Contains("Inno.Rendering/", StringComparison.Ordinal) + && (targetPath.Contains("MaterialGraph", StringComparison.Ordinal) + || targetPath.StartsWith("src/content/scene/", StringComparison.Ordinal) + || targetPath.StartsWith("src/composition/editor/", StringComparison.Ordinal)) + ) { failures.Add($"{sourcePath}: backend-neutral Rendering cannot reference {targetPath}."); } - if (string.Equals( - project.name, - "Inno.Audio", - StringComparison.Ordinal - ) - && (targetPath.StartsWith( - "src/services/audio/Inno.Audio.Runtime/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/adapters/audio/Inno.Adapter.Audio.MiniAudio/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/content/scene/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/runtime/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/composition/editor/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/services/platform/", - StringComparison.Ordinal - ) - || IsNativeProject(targetPath))) - { + if (string.Equals(project.name, "Inno.Audio", StringComparison.Ordinal) + && (targetPath.StartsWith("src/services/audio/Inno.Audio.Runtime/", StringComparison.Ordinal) + || targetPath.StartsWith("src/adapters/audio/Inno.Adapter.Audio.MiniAudio/", StringComparison.Ordinal) + || targetPath.StartsWith("src/content/scene/", StringComparison.Ordinal) + || targetPath.StartsWith("src/runtime/", StringComparison.Ordinal) + || targetPath.StartsWith("src/composition/editor/", StringComparison.Ordinal) + || targetPath.StartsWith("src/services/platform/", StringComparison.Ordinal) + || IsNativeProject(targetPath)) + ) { failures.Add($"{sourcePath}: backend-neutral Audio cannot reference {targetPath}."); } - if (string.Equals( - project.name, - "Inno.Animation", - StringComparison.Ordinal - ) - && (targetPath.StartsWith( - "src/runtime/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/content/scene/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/services/rendering/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/services/audio/", - StringComparison.Ordinal - ) - || targetPath.StartsWith( - "src/composition/editor/", - StringComparison.Ordinal - ) - || IsNativeProject(targetPath))) - { + if (string.Equals(project.name, "Inno.Animation", StringComparison.Ordinal) + && (targetPath.StartsWith("src/runtime/", StringComparison.Ordinal) + || targetPath.StartsWith("src/content/scene/", StringComparison.Ordinal) + || targetPath.StartsWith("src/services/rendering/", StringComparison.Ordinal) + || targetPath.StartsWith("src/services/audio/", StringComparison.Ordinal) + || targetPath.StartsWith("src/composition/editor/", StringComparison.Ordinal) + || IsNativeProject(targetPath)) + ) { failures.Add($"{sourcePath}: backend-neutral Animation cannot reference {targetPath}."); } @@ -637,7 +551,9 @@ ICollection failures var states = new Dictionary(); var stack = new List(); foreach (ProjectNode node in graph.Values) + { Visit(node); + } void Visit(ProjectNode node) { if (states.TryGetValue(node, out VisitState state)) @@ -655,7 +571,9 @@ void Visit(ProjectNode node) states[node] = VisitState.Visiting; stack.Add(node); foreach (ProjectNode target in node.references) + { Visit(target); + } stack.RemoveAt(stack.Count - 1); states[node] = VisitState.Visited; } @@ -680,14 +598,21 @@ ICollection failures { ProjectNode current = pending.Pop(); if (!visited.Add(current)) - continue; - if (!ReferenceEquals(current, player) && S_FORBIDDEN_PLAYER_PROJECT_FRAGMENTS.Any(fragment => current.name.Contains(fragment, StringComparison.OrdinalIgnoreCase))) { - failures.Add($"{Relative(repositoryRoot, player.path)}: Player dependency closure contains forbidden project {current.name}."); + continue; + } + if (!ReferenceEquals(current, player) + && S_FORBIDDEN_PLAYER_PROJECT_FRAGMENTS.Any(fragment => current.name.Contains(fragment, StringComparison.OrdinalIgnoreCase)) + ) { + failures.Add( + $"{Relative(repositoryRoot, player.path)}: Player dependency closure contains forbidden project {current.name}." + ); } foreach (ProjectNode target in current.references) + { pending.Push(target); + } } } @@ -699,7 +624,9 @@ ICollection failures foreach (string removed in S_REMOVED_PROJECT_NAMES) { if (solution.Contains("= \"" + removed + "\",", StringComparison.Ordinal)) + { failures.Add($"InnoEngine.sln: removed project '{removed}' remains in the solution."); + } foreach (string projectPath in EnumerateFiles(repositoryRoot, "*.csproj")) { if (string.Equals(Path.GetFileNameWithoutExtension(projectPath), removed, StringComparison.Ordinal)) @@ -718,12 +645,16 @@ ICollection failures { ConceptualLayer? sourceLayer = ClassifyConceptualLayer(project); if (sourceLayer is null) + { continue; + } foreach (ProjectNode target in project.references) { ConceptualLayer? targetLayer = ClassifyConceptualLayer(target); if (targetLayer is null || targetLayer <= sourceLayer) + { continue; + } failures.Add($"{project.relative}: {sourceLayer} project cannot reference upper {targetLayer} project {target.relative}."); } } @@ -749,9 +680,12 @@ void ValidateHost(string projectName) failures.Add($"{host.relative}: product composition must inherit the common Inno.Shell lifecycle."); } - foreach (ProjectNode target in host.references.Where(target => projectName == "Inno.Player.Runtime" && IsConcreteAdapter(target.name))) - { - failures.Add($"{host.relative}: product composition cannot reference concrete adapter project {target.relative}; use Inno.Adapter.Default and neutral contracts."); + foreach (ProjectNode target in host.references.Where( + target => projectName == "Inno.Player.Runtime" && IsConcreteAdapter(target.name) + )) { + failures.Add( + $"{host.relative}: product composition cannot reference concrete adapter project {target.relative}; use Inno.Adapter.Default and neutral contracts." + ); } } } @@ -759,7 +693,9 @@ void ValidateHost(string projectName) private static ConceptualLayer? ClassifyConceptualLayer(ProjectNode project) { if (!project.relative.StartsWith("src/", StringComparison.Ordinal)) + { return null; + } if (project.relative.StartsWith("src/foundation/", StringComparison.Ordinal)) { return ConceptualLayer.Foundation; @@ -778,193 +714,93 @@ void ValidateHost(string projectName) return ConceptualLayer.EngineCapability; } - private static bool IsAdapterContract(string name) => string.Equals( - name, - "Inno.Adapter", - StringComparison.Ordinal - ) - || string.Equals( - name, - "Inno.Adapter.Platform", - StringComparison.Ordinal - ) - || string.Equals( - name, - "Inno.Adapter.Input", - StringComparison.Ordinal - ) - || string.Equals( - name, - "Inno.Adapter.Storage", - StringComparison.Ordinal - ) - || string.Equals( - name, - "Inno.Adapter.Rendering", - StringComparison.Ordinal - ) - || string.Equals( - name, - "Inno.Adapter.Audio", - StringComparison.Ordinal - ) - || string.Equals( - name, - "Inno.Adapter.Text", - StringComparison.Ordinal - ) - || string.Equals( - name, - "Inno.Adapter.UI", - StringComparison.Ordinal - ) - || string.Equals( - name, - "Inno.Adapter.Presentation", - StringComparison.Ordinal - ); - private static bool IsConcreteAdapter(string name) => name.StartsWith( - "Inno.Adapter.Content.", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Adapter.Platform.", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Adapter.Input.", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Adapter.Storage.", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Adapter.Rendering.", - StringComparison.Ordinal - ) - && !string.Equals( - name, - "Inno.Adapter.Rendering.Authoring", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Adapter.Audio.", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Adapter.Text.", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Adapter.UI.", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Adapter.Presentation.", - StringComparison.Ordinal - ); - private static bool IsAllowedBgfxConsumer(string name) => name.StartsWith( - "Inno.Adapter.Rendering.Bgfx", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Adapter.Presentation.ImGui.Bgfx", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Build.Toolchains.Bgfx", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Native.Bgfx", - StringComparison.Ordinal - ) - || name.EndsWith( - ".Tests", - StringComparison.Ordinal - ); - private static bool IsAllowedSdlConsumer(string name) => name.StartsWith( - "Inno.Adapter.Platform.Sdl3", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Adapter.Presentation.ImGui.Sdl3", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Build.Toolchains.Sdl3", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Native.Sdl3", - StringComparison.Ordinal - ) - || name is "Inno.Integration.WindowsX64.Sdl3" or "Inno.Integration.MacOSArm64.Sdl3" or "Inno.Integration.BrowserWasm32.Sdl3" - || name.EndsWith( - ".Tests", - StringComparison.Ordinal - ); - private static bool IsAllowedMiniAudioConsumer(string name) => name.StartsWith( - "Inno.Adapter.Audio.MiniAudio", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Build.Toolchains.MiniAudio", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Native.MiniAudio", - StringComparison.Ordinal - ); - private static bool IsAllowedUiNativeConsumer(string name) => name.StartsWith( - "Inno.Adapter.UI.RmlUi", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Build.Toolchains.UI", - StringComparison.Ordinal - ) - || name.StartsWith( - "Inno.Native.UI", - StringComparison.Ordinal - ) - || name.EndsWith( - ".Tests", - StringComparison.Ordinal - ); + private static bool IsAdapterContract(string name) + => string.Equals(name, "Inno.Adapter", StringComparison.Ordinal) + || string.Equals(name, "Inno.Adapter.Platform", StringComparison.Ordinal) + || string.Equals(name, "Inno.Adapter.Input", StringComparison.Ordinal) + || string.Equals(name, "Inno.Adapter.Storage", StringComparison.Ordinal) + || string.Equals(name, "Inno.Adapter.Rendering", StringComparison.Ordinal) + || string.Equals(name, "Inno.Adapter.Audio", StringComparison.Ordinal) + || string.Equals(name, "Inno.Adapter.Text", StringComparison.Ordinal) + || string.Equals(name, "Inno.Adapter.UI", StringComparison.Ordinal) + || string.Equals(name, "Inno.Adapter.Presentation", StringComparison.Ordinal); + + private static bool IsConcreteAdapter(string name) + => name.StartsWith("Inno.Adapter.Content.", StringComparison.Ordinal) + || name.StartsWith("Inno.Adapter.Platform.", StringComparison.Ordinal) + || name.StartsWith("Inno.Adapter.Input.", StringComparison.Ordinal) + || name.StartsWith("Inno.Adapter.Storage.", StringComparison.Ordinal) + || name.StartsWith("Inno.Adapter.Rendering.", StringComparison.Ordinal) + && !string.Equals(name, "Inno.Adapter.Rendering.Authoring", StringComparison.Ordinal) + || name.StartsWith("Inno.Adapter.Audio.", StringComparison.Ordinal) + || name.StartsWith("Inno.Adapter.Text.", StringComparison.Ordinal) + || name.StartsWith("Inno.Adapter.UI.", StringComparison.Ordinal) + || name.StartsWith("Inno.Adapter.Presentation.", StringComparison.Ordinal); + + private static bool IsAllowedBgfxConsumer(string name) + => name.StartsWith("Inno.Adapter.Rendering.Bgfx", StringComparison.Ordinal) + || name.StartsWith("Inno.Adapter.Presentation.ImGui.Bgfx", StringComparison.Ordinal) + || name.StartsWith("Inno.Build.Toolchains.Bgfx", StringComparison.Ordinal) + || name.StartsWith("Inno.Native.Bgfx", StringComparison.Ordinal) + || name.EndsWith(".Tests", StringComparison.Ordinal); + + private static bool IsAllowedSdlConsumer(string name) + => name.StartsWith("Inno.Adapter.Platform.Sdl3", StringComparison.Ordinal) + || name.StartsWith("Inno.Adapter.Presentation.ImGui.Sdl3", StringComparison.Ordinal) + || name.StartsWith("Inno.Build.Toolchains.Sdl3", StringComparison.Ordinal) + || name.StartsWith("Inno.Native.Sdl3", StringComparison.Ordinal) + || name is "Inno.Integration.WindowsX64.Sdl3" or "Inno.Integration.MacOSArm64.Sdl3" or "Inno.Integration.BrowserWasm32.Sdl3" + || name.EndsWith(".Tests", StringComparison.Ordinal); + + private static bool IsAllowedMiniAudioConsumer(string name) + => name.StartsWith("Inno.Adapter.Audio.MiniAudio", StringComparison.Ordinal) + || name.StartsWith("Inno.Build.Toolchains.MiniAudio", StringComparison.Ordinal) + || name.StartsWith("Inno.Native.MiniAudio", StringComparison.Ordinal); + + private static bool IsAllowedUiNativeConsumer(string name) + => name.StartsWith("Inno.Adapter.UI.RmlUi", StringComparison.Ordinal) + || name.StartsWith("Inno.Build.Toolchains.UI", StringComparison.Ordinal) + || name.StartsWith("Inno.Native.UI", StringComparison.Ordinal) + || name.EndsWith(".Tests", StringComparison.Ordinal); + private static IEnumerable EnumerateFiles( string root, string pattern ) => RepositorySourceInventory.Files(root, pattern); - private static bool IsGenerated(string source) => source.Contains( - "", - StringComparison.OrdinalIgnoreCase - ) - || source.Contains( - "[GeneratedCode", - StringComparison.Ordinal - ); + + private static bool IsGenerated(string source) + => source.Contains("", StringComparison.OrdinalIgnoreCase) + || source.Contains("[GeneratedCode", StringComparison.Ordinal); + private static string Relative( string repositoryRoot, string path ) => Path.GetRelativePath(repositoryRoot, path).Replace('\\', '/'); + [GeneratedRegex(@"\b(class|struct|interface|enum|record)\s+([A-Za-z_]\w*)")] private static partial Regex DeclaredTypePattern(); - [GeneratedRegex(@"\bstatic\s+class\s+(DiagnosticManager|LogManager|IdentityManager|JobSystemManager|AssemblyManager|TypeCacheManager|SerializationManager|ProjectSettingsManager|AssetManager|PluginManager|Shell)\b")] + + [GeneratedRegex( + @"\bstatic\s+class\s+(DiagnosticManager|LogManager|IdentityManager|JobSystemManager|AssemblyManager|TypeCacheManager|SerializationManager|ProjectSettingsManager|AssetManager|PluginManager|Shell)\b" + )] private static partial Regex StaticManagerDeclarationPattern(); + [GeneratedRegex(@"\bLog\.(Debug|Info|Warn|Error|Fatal)\s*\(")] private static partial Regex StaticLogFacadeCallPattern(); + [GeneratedRegex(@"\b(public|protected)\b[^\r\n;{]*(Inno\.Native\.|bgfx_|SDL[A-Z]|ImGuiPtr|Ma[A-Z]\w*)")] private static partial Regex PublicNativeSignaturePattern(); - [GeneratedRegex(@"BindingFlags\s*\.[^\r\n;]*(NonPublic|Private)|(GetField|GetMethod|GetProperty|GetConstructor)\s*\([^\r\n;]*BindingFlags\s*\.[^\r\n;]*(NonPublic|Private)")] + + [GeneratedRegex( + @"BindingFlags\s*\.[^\r\n;]*(NonPublic|Private)|(GetField|GetMethod|GetProperty|GetConstructor)\s*\([^\r\n;]*BindingFlags\s*\.[^\r\n;]*(NonPublic|Private)" + )] private static partial Regex NonPublicReflectionPattern(); + private sealed class ProjectNode( string path, string relative, string name - ) - { + ) { internal string path { get; } = path; internal string relative { get; } = relative; internal string name { get; } = name; diff --git a/tools/Inno.Tooling.Architecture/AssemblyDocumentationProvider.cs b/tools/Inno.Tooling.Architecture/AssemblyDocumentationProvider.cs index af0583046..e1e131e2a 100644 --- a/tools/Inno.Tooling.Architecture/AssemblyDocumentationProvider.cs +++ b/tools/Inno.Tooling.Architecture/AssemblyDocumentationProvider.cs @@ -6,7 +6,6 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Xml.Linq; - using Microsoft.CodeAnalysis; namespace Inno.Tooling.Architecture; @@ -16,9 +15,7 @@ internal sealed class AssemblyDocumentationProvider : DocumentationProvider private readonly Lazy> m_members; internal AssemblyDocumentationProvider(string path) - : this(path, File.ReadAllBytes(path)) - { - } + : this(path, File.ReadAllBytes(path)) {} internal AssemblyDocumentationProvider( string path, @@ -77,7 +74,8 @@ byte[] document try { using var input = new MemoryStream(document, writable: false); - return XDocument.Load(input).Descendants("member") + return XDocument.Load(input) + .Descendants("member") .Where(static element => element.Attribute("name") is not null) .GroupBy(static element => (string)element.Attribute("name")!, StringComparer.Ordinal) .ToDictionary(static group => group.Key, static group => group.First().ToString(), StringComparer.Ordinal); diff --git a/tools/Inno.Tooling.Architecture/DocumentationApiExtractor.cs b/tools/Inno.Tooling.Architecture/DocumentationApiExtractor.cs index 178aa6a03..92840d4c2 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationApiExtractor.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationApiExtractor.cs @@ -27,14 +27,24 @@ internal static IReadOnlyList ReadExports(Compilation? compilation { if (attribute.AttributeClass?.ToDisplayString() != "Inno.Scripting.Api.ScriptingApiExportAttribute" || attribute.ConstructorArguments.Length < 2 - || attribute.ConstructorArguments[0].Value is not INamedTypeSymbol exported) continue; + || attribute.ConstructorArguments[0].Value is not INamedTypeSymbol exported + ) { + continue; + } TypedConstant scope = attribute.ConstructorArguments[^1]; - string? name = scope.Type?.GetMembers().OfType() + string? name = scope.Type?.GetMembers() + .OfType() .SingleOrDefault(field => field.HasConstantValue && Equals(field.ConstantValue, scope.Value))?.Name; - if (name is not ("Runtime" or "Editor" or "Authoring")) throw new InvalidDataException("Unknown scripting API scope for " + exported); + if (name is not ("Runtime" or "Editor" or "Authoring")) + { + throw new InvalidDataException("Unknown scripting API scope for " + exported); + } exports.Add(new(exported.ContainingAssembly.Name, exported.OriginalDefinition.GetDocumentationCommentId()!, name)); } - return exports.OrderBy(export => export.assembly, StringComparer.Ordinal).ThenBy(export => export.type, StringComparer.Ordinal).ToArray(); + return exports + .OrderBy(export => export.assembly, StringComparer.Ordinal) + .ThenBy(export => export.type, StringComparer.Ordinal) + .ToArray(); } private static readonly SymbolDisplayFormat S_SIGNATURE = new( @@ -44,14 +54,15 @@ internal static IReadOnlyList ReadExports(Compilation? compilation delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeParameters - | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers - | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeConstantValue - | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeRef, + | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeModifiers + | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeConstantValue + | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeRef, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName - | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeParamsRefOut, + | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeParamsRefOut, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier - | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers); + | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers + ); internal static IReadOnlyList Capture( string root, @@ -69,39 +80,60 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); SemanticModel model = compilation!.GetSemanticModel(tree); - foreach (SyntaxNode node in model.SyntaxTree.GetRoot(cancellationToken).DescendantNodes() - .Where(static node => node is BaseTypeDeclarationSyntax or DelegateDeclarationSyntax)) - { + foreach (SyntaxNode node in model.SyntaxTree.GetRoot(cancellationToken) + .DescendantNodes() + .Where(static node => node is BaseTypeDeclarationSyntax or DelegateDeclarationSyntax) + ) { if (model.GetDeclaredSymbol(node, cancellationToken) is not INamedTypeSymbol type) + { continue; + } foreach (ISymbol symbol in new ISymbol[] { type }.Concat(type.GetMembers())) { if (!IsVisible(symbol) || symbol is INamedTypeSymbol nested && !SymbolEqualityComparer.Default.Equals(nested, type) || symbol.Name.StartsWith('<') || symbol is IMethodSymbol { AssociatedSymbol: not null } || symbol is IMethodSymbol { IsImplicitlyDeclared: true, MethodKind: MethodKind.Constructor, - ContainingType.TypeKind: TypeKind.Struct or TypeKind.Enum }) + ContainingType.TypeKind: TypeKind.Struct or TypeKind.Enum } + ) { continue; + } string? id = symbol.GetDocumentationCommentId(); if (id is null || !seen.Add(id)) + { continue; + } if (HasUnresolvedContract(symbol)) - failures.Add($"API '{Path.GetRelativePath(root, project)}' cannot resolve the complete public signature of '{id}'; prepare its evaluated reference closure."); + { + failures.Add( + $"API '{Path.GetRelativePath(root, project)}' cannot resolve the complete public signature of '{id}'; prepare its evaluated reference closure." + ); + } string signature = Signature(symbol); string identity = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(signature))); Location location = symbol.Locations.FirstOrDefault(static location => location.IsInSource) ?? node.GetLocation(); string source = Path.GetRelativePath(root, location.SourceTree?.FilePath ?? tree.FilePath).Replace('\\', '/'); - result.Add(new(Path.GetFileNameWithoutExtension(project), id, signature, identity, source, - location.GetLineSpan().StartLinePosition.Line + 1, - page is null ? string.Empty : Path.GetRelativePath(root, page).Replace('\\', '/'), - Documentation(symbol, new HashSet(SymbolEqualityComparer.Default), cancellationToken), - symbol.IsImplicitlyDeclared, - symbol is IFieldSymbol { HasConstantValue: true } field ? field.ConstantValue : null, - symbol.Kind.ToString(), symbol.ContainingType?.GetDocumentationCommentId(), - symbol is INamedTypeSymbol named ? named.BaseType?.ToDisplayString() : null, - symbol is INamedTypeSymbol namedType - ? namedType.Interfaces.Select(static contract => contract.ToDisplayString()).ToArray() : [], - scriptingScope: scopes.GetValueOrDefault(type.GetDocumentationCommentId()!))); + result.Add( + new( + Path.GetFileNameWithoutExtension(project), + id, + signature, + identity, + source, + location.GetLineSpan().StartLinePosition.Line + 1, + page is null ? string.Empty : Path.GetRelativePath(root, page).Replace('\\', '/'), + Documentation(symbol, new HashSet(SymbolEqualityComparer.Default), cancellationToken), + symbol.IsImplicitlyDeclared, + symbol is IFieldSymbol { HasConstantValue: true } field ? field.ConstantValue : null, + symbol.Kind.ToString(), + symbol.ContainingType?.GetDocumentationCommentId(), + symbol is INamedTypeSymbol named ? named.BaseType?.ToDisplayString() : null, + symbol is INamedTypeSymbol namedType + ? namedType.Interfaces.Select(static contract => contract.ToDisplayString()).ToArray() + : [], + scriptingScope: scopes.GetValueOrDefault(type.GetDocumentationCommentId()!) + ) + ); } } } @@ -137,46 +169,82 @@ CancellationToken cancellationToken void VisitNamespace(INamespaceSymbol space) { foreach (INamespaceSymbol child in space.GetNamespaceMembers()) + { VisitNamespace(child); + } foreach (INamedTypeSymbol type in space.GetTypeMembers()) + { VisitType(type); + } } void VisitType(INamedTypeSymbol type) { cancellationToken.ThrowIfCancellationRequested(); if (!IsVisible(type)) + { return; + } foreach (ISymbol symbol in new ISymbol[] { type }.Concat(type.GetMembers())) { - if (!IsVisible(symbol) || symbol is INamedTypeSymbol nested && !SymbolEqualityComparer.Default.Equals(nested, type) - || symbol.Name.StartsWith('<') || symbol is IMethodSymbol { AssociatedSymbol: not null } - || symbol is IMethodSymbol { MethodKind: MethodKind.Constructor, ContainingType.TypeKind: TypeKind.Struct or TypeKind.Enum, - IsImplicitlyDeclared: true }) + if (!IsVisible(symbol) + || symbol is INamedTypeSymbol nested && !SymbolEqualityComparer.Default.Equals(nested, type) + || symbol.Name.StartsWith('<') + || symbol is IMethodSymbol { AssociatedSymbol: not null } + || symbol is IMethodSymbol + { + MethodKind: MethodKind.Constructor, + ContainingType.TypeKind: TypeKind.Struct or TypeKind.Enum, + IsImplicitlyDeclared: true + } + ) { continue; + } string? id = symbol.GetDocumentationCommentId(); if (id is null) + { continue; + } if (HasUnresolvedContract(symbol)) + { throw new InvalidDataException("The projected API reference closure is incomplete: " + id); + } DocumentationApiEntry origin = resolveOrigin(symbol); string signature = Signature(symbol); string documentation = Documentation(symbol, new HashSet(SymbolEqualityComparer.Default), cancellationToken); - entries.Add(id, new(origin.project, id, signature, - Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(signature))), origin.source, origin.line, - string.Empty, string.IsNullOrWhiteSpace(documentation) ? origin.documentation : documentation, - origin.implicitDeclaration, symbol is IFieldSymbol { HasConstantValue: true } field ? field.ConstantValue : null, - symbol.Kind.ToString(), symbol.ContainingType?.GetDocumentationCommentId(), - symbol is INamedTypeSymbol named ? named.BaseType?.ToDisplayString() : null, - symbol is INamedTypeSymbol namedType - ? namedType.Interfaces.Select(static contract => contract.ToDisplayString()).ToArray() : [], origin.projectionOnly, origin.scriptingScope)); + entries.Add( + id, + new( + origin.project, + id, + signature, + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(signature))), + origin.source, + origin.line, + string.Empty, + string.IsNullOrWhiteSpace(documentation) ? origin.documentation : documentation, + origin.implicitDeclaration, + symbol is IFieldSymbol { HasConstantValue: true } field ? field.ConstantValue : null, + symbol.Kind.ToString(), + symbol.ContainingType?.GetDocumentationCommentId(), + symbol is INamedTypeSymbol named ? named.BaseType?.ToDisplayString() : null, + symbol is INamedTypeSymbol namedType + ? namedType.Interfaces.Select(static contract => contract.ToDisplayString()).ToArray() + : [], + origin.projectionOnly, + origin.scriptingScope + ) + ); } foreach (INamedTypeSymbol child in type.GetTypeMembers()) + { VisitType(child); + } } } - private static bool IsUnresolved(ITypeSymbol type) => type switch + private static bool IsUnresolved(ITypeSymbol type) + => type switch { IErrorTypeSymbol => true, IArrayTypeSymbol array => IsUnresolved(array.ElementType), @@ -190,33 +258,49 @@ private static string Signature(ISymbol symbol) { string signature = symbol.ToDisplayString(S_SIGNATURE); if (symbol is not INamedTypeSymbol type) + { return signature; + } var modifiers = new List(); - modifiers.Add(type.DeclaredAccessibility switch - { - Accessibility.Public => "public", - Accessibility.Protected => "protected", - Accessibility.ProtectedOrInternal => "protected internal", - _ => throw new InvalidOperationException("A Wiki type signature must have externally visible accessibility.") - }); + modifiers.Add( + type.DeclaredAccessibility switch + { + Accessibility.Public => "public", + Accessibility.Protected => "protected", + Accessibility.ProtectedOrInternal => "protected internal", + _ => throw new InvalidOperationException("A Wiki type signature must have externally visible accessibility.") + } + ); if (type.IsStatic) + { modifiers.Add("static"); + } else if (type.TypeKind == TypeKind.Class) { if (type.IsAbstract) + { modifiers.Add("abstract"); + } if (type.IsSealed) + { modifiers.Add("sealed"); + } } signature = string.Join(' ', modifiers) + " " + signature; if (type.TypeKind == TypeKind.Delegate) + { return signature; + } SymbolDisplayFormat reference = S_SIGNATURE.WithKindOptions(SymbolDisplayKindOptions.None); var bases = new List(); if (type.EnumUnderlyingType is not null) + { bases.Add(type.EnumUnderlyingType.ToDisplayString(reference)); + } else if (type.BaseType is { SpecialType: not SpecialType.System_Object and not SpecialType.System_ValueType } parent) + { bases.Add(parent.ToDisplayString(reference)); + } bases.AddRange(type.Interfaces.Select(contract => contract.ToDisplayString(reference))); return bases.Count == 0 ? signature : signature + " : " + string.Join(", ", bases); } @@ -227,9 +311,13 @@ private static string Documentation( CancellationToken cancellationToken ) { if (!visited.Add(symbol)) + { return string.Empty; + } if (symbol is IMethodSymbol { MethodKind: MethodKind.DelegateInvoke } invoke) + { return Documentation(invoke.ContainingType, visited, cancellationToken); + } string xml = symbol.GetDocumentationCommentXml(expandIncludes: true, cancellationToken: cancellationToken) ?? string.Empty; XElement? own; try @@ -242,20 +330,25 @@ CancellationToken cancellationToken return string.Empty; } if (own is not null && own.Element("inheritdoc") is null) + { return xml; + } foreach (ISymbol inherited in PublicApiDocumentationValidator.InheritedMembers(symbol)) { string contract = Documentation(inherited, visited, cancellationToken); if (contract.Length == 0) + { continue; + } XElement merged = XElement.Parse(contract); if (own is not null) { foreach (XElement item in own.Elements().Where(static element => element.Name != "inheritdoc")) { string? identity = (string?)item.Attribute("name") ?? (string?)item.Attribute("cref"); - merged.Elements(item.Name).Where(element => - ((string?)element.Attribute("name") ?? (string?)element.Attribute("cref")) == identity).Remove(); + merged.Elements(item.Name).Where(element => ( + ((string?)element.Attribute("name") ?? (string?)element.Attribute("cref")) == identity + )).Remove(); merged.Add(new XElement(item)); } } @@ -267,10 +360,18 @@ CancellationToken cancellationToken private static bool IsVisible(ISymbol symbol) { if (symbol is not INamedTypeSymbol and not IMethodSymbol and not IPropertySymbol and not IFieldSymbol and not IEventSymbol) + { return false; + } for (ISymbol? current = symbol; current is not null && current is not INamespaceSymbol; current = current.ContainingType) - if (current.DeclaredAccessibility is not Accessibility.Public and not Accessibility.Protected and not Accessibility.ProtectedOrInternal) + { + if (current.DeclaredAccessibility is not Accessibility.Public + and not Accessibility.Protected + and not Accessibility.ProtectedOrInternal + ) { return false; + } + } return true; } diff --git a/tools/Inno.Tooling.Architecture/DocumentationExamples.cs b/tools/Inno.Tooling.Architecture/DocumentationExamples.cs index 2fd36f7a1..5f895a928 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationExamples.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationExamples.cs @@ -7,11 +7,11 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; -using Inno.Tooling.Documentation; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Inno.Core.IO; +using Inno.Tooling.Documentation; namespace Inno.Tooling.Architecture; @@ -62,60 +62,110 @@ public static async Task ExecuteAsync( { string key = arguments[index]; if (index + 1 == arguments.Length) + { throw new ArgumentException("Incomplete example validation option: " + key); + } if (key == "--page") { if (!selected.Add(arguments[index + 1])) + { throw new ArgumentException("Duplicate example page selection."); + } } else if (key is not ("--engine-root" or "--cache-root" or "--snapshot" or "--dotnet" or "--output" - or "--configuration" or "--target" or "--artifacts-path" or "--sdk-snapshot" or "--runtime-reference" or "--editor-reference" or "--operation") - || !options.TryAdd(key, arguments[index + 1])) + or "--configuration" + or "--target" + or "--artifacts-path" + or "--sdk-snapshot" + or "--runtime-reference" + or "--editor-reference" + or "--operation") + || !options.TryAdd(key, arguments[index + 1]) + ) { throw new ArgumentException("Unknown or duplicate example validation option: " + key); + } } foreach (string required in new[] { "--engine-root", "--cache-root", "--snapshot", "--dotnet", "--output" }) + { if (!options.ContainsKey(required)) + { throw new ArgumentException("Missing example validation option: " + required); + } + } string root = Path.GetFullPath(options["--engine-root"]); string configuration = options.GetValueOrDefault("--configuration", "Debug"); if (configuration is not ("Debug" or "SourceDebug" or "Release")) + { throw new ArgumentException("Unsupported example configuration."); + } string operation = options.GetValueOrDefault("--operation", "compile"); if (operation is not ("plan" or "compile")) throw new ArgumentException("Unsupported example operation."); - using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(options["--cache-root"], - options["--snapshot"], cancellationToken: cancellationToken).ConfigureAwait(false); + using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync( + options["--cache-root"], + options["--snapshot"], + cancellationToken: cancellationToken + ).ConfigureAwait(false); DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(cancellationToken).ConfigureAwait(false); foreach (string page in selected) + { if (!catalog.pages.Any(candidate => candidate.id == page)) + { throw new ArgumentException("Selected example page is missing: " + page); + } + } var projects = RepositorySourceInventory.Projects(root) .ToDictionary(static project => Path.GetFileNameWithoutExtension(project), StringComparer.Ordinal); var groups = catalog.pages.Where(page => selected.Count == 0 || selected.Contains(page.id)) - .Select(page => (page, blocks: page.codeBlocks.Where(static block => block.language is "csharp" or "cs" - && block.declarationSymbols.Count == 0).ToArray())) - .Where(static group => group.blocks.Length != 0).ToArray(); + .Select(page => (page, blocks: page.codeBlocks.Where(static block => ( + block.language is "csharp" or "cs" + && block.declarationSymbols.Count == 0 + )).ToArray())) + .Where(static group => group.blocks.Length != 0) + .ToArray(); var requested = groups.Where(static group => group.page.examples is not null) .SelectMany(static group => group.page.examples!.projects) - .Where(projects.ContainsKey).Select(name => projects[name]).ToHashSet(StringComparer.OrdinalIgnoreCase); + .Where(projects.ContainsKey) + .Select(name => projects[name]) + .ToHashSet(StringComparer.OrdinalIgnoreCase); if (operation == "plan") { - if (groups.Length == 0 || groups.Any(group => group.page.examples is null - || group.page.examples.projects.Count == 0 || group.page.examples.projects.Any(project => !projects.ContainsKey(project)))) + if (groups.Length == 0 || groups.Any(group => ( + group.page.examples is null + || group.page.examples.projects.Count == 0 || group.page.examples.projects.Any(project => !projects.ContainsKey(project)) + ))) { throw new InvalidDataException("Required example planning needs nonempty groups with actual source owners."); + } cancellationToken.ThrowIfCancellationRequested(); - AtomicFile.WriteAllBytes(Path.GetFullPath(options["--output"]), JsonSerializer.SerializeToUtf8Bytes(new - { - schema = "inno-example-plan/1", snapshot = catalog.snapshot, catalog.contentIdentity, configuration, - target = options.GetValueOrDefault("--target"), pages = groups.Select(group => group.page.id).ToArray(), - projects = requested.Order(StringComparer.Ordinal).Select(project => Path.GetRelativePath(root, project).Replace('\\', '/')).ToArray(), - needsScriptProjection = groups.Any(group => group.page.examples!.mode is "runtime-script" or "editor-script") - }, new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" })); + AtomicFile.WriteAllBytes( + Path.GetFullPath(options["--output"]), + JsonSerializer.SerializeToUtf8Bytes(new + { + schema = "inno-example-plan/1", + snapshot = catalog.snapshot, + catalog.contentIdentity, + configuration, + target = options.GetValueOrDefault("--target"), + pages = groups.Select(group => group.page.id).ToArray(), + projects = requested + .Order(StringComparer.Ordinal) + .Select(project => Path.GetRelativePath(root, project).Replace('\\', '/')) + .ToArray(), + needsScriptProjection = groups.Any(group => group.page.examples!.mode is "runtime-script" or "editor-script") + }, new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" }) + ); return 0; } - var sdk = new DocumentationProjectReferences(root, configuration, Path.GetFullPath(options["--dotnet"]), - options.GetValueOrDefault("--target"), options.TryGetValue("--artifacts-path", out string? artifacts) ? Path.GetFullPath(artifacts) : null, - selectedProjects: requested, sdkSnapshot: options.TryGetValue("--sdk-snapshot", out string? graphPath) - ? await File.ReadAllTextAsync(graphPath, cancellationToken).ConfigureAwait(false) : null); + var sdk = new DocumentationProjectReferences( + root, + configuration, + Path.GetFullPath(options["--dotnet"]), + options.GetValueOrDefault("--target"), + options.TryGetValue("--artifacts-path", out string? artifacts) ? Path.GetFullPath(artifacts) : null, + selectedProjects: requested, + sdkSnapshot: options.TryGetValue("--sdk-snapshot", out string? graphPath) + ? await File.ReadAllTextAsync(graphPath, cancellationToken).ConfigureAwait(false) + : null + ); var frozen = new Dictionary(StringComparer.OrdinalIgnoreCase); var results = new List(); foreach (var group in groups) @@ -128,41 +178,77 @@ public static async Task ExecuteAsync( try { if (context is null) + { throw new InvalidDataException("Declare exampleMode and exampleProjects; reference inference is not permitted."); + } if (context.projects.Any(name => !projects.ContainsKey(name))) + { throw new InvalidDataException("An example owner is absent from the actual engine project inventory."); + } CSharpCompilation compilation; if (context.mode == "host") { - CSharpCompilation[] contexts = context.projects.Select(name => sdk.GetCompilation(projects[name], cancellationToken)).ToArray(); - compilation = contexts[0].WithReferences(contexts.SelectMany(static item => item.References) - .OfType().Select(Freeze).Distinct()); + CSharpCompilation[] contexts = context.projects + .Select(name => sdk.GetCompilation(projects[name], cancellationToken)) + .ToArray(); + compilation = contexts[0].WithReferences( + contexts.SelectMany(static item => item.References) + .OfType() + .Select(Freeze) + .Distinct() + ); } else { - var scripts = new DocumentationScriptReferences(options.GetValueOrDefault("--runtime-reference"), - options.GetValueOrDefault("--editor-reference")); + var scripts = new DocumentationScriptReferences( + options.GetValueOrDefault("--runtime-reference"), + options.GetValueOrDefault("--editor-reference") + ); bool editor = context.mode == "editor-script"; IReadOnlyList references = scripts.GetReferences(editor); foreach (var identity in scripts.GetIdentities(editor)) + { identities.Add(identity.Key, identity.Value); - compilation = CSharpCompilation.Create("DocumentationScript", references: - sdk.GetFrameworkReferences(cancellationToken).OfType().Select(Freeze).Concat(references), - options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, - nullableContextOptions: NullableContextOptions.Enable)); + } + compilation = CSharpCompilation.Create( + "DocumentationScript", + references: + sdk + .GetFrameworkReferences(cancellationToken) + .OfType() + .Select(Freeze) + .Concat(references), + options: new CSharpCompilationOptions( + OutputKind.DynamicallyLinkedLibrary, + nullableContextOptions: NullableContextOptions.Enable + ) + ); } CSharpParseOptions parse = (CSharpParseOptions?)compilation.SyntaxTrees.FirstOrDefault()?.Options - ?? new CSharpParseOptions(LanguageVersion.CSharp14); - SyntaxTree[] trees = group.blocks.Select(block => CSharpSyntaxTree.ParseText(block.text, parse, - group.page.path + "#line-" + block.line, cancellationToken: cancellationToken)).ToArray(); - OutputKind output = trees.Any(tree => tree.GetRoot(cancellationToken).DescendantNodes().OfType().Any()) - ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary; - compilation = compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(trees).WithAssemblyName("DocumentationExample") + ?? new CSharpParseOptions(LanguageVersion.CSharp14); + SyntaxTree[] trees = group.blocks.Select(block => CSharpSyntaxTree.ParseText( + block.text, + parse, + group.page.path + "#line-" + block.line, + cancellationToken: cancellationToken + )).ToArray(); + OutputKind output = trees.Any( + tree => tree.GetRoot(cancellationToken).DescendantNodes().OfType().Any() + ) + ? OutputKind.ConsoleApplication + : OutputKind.DynamicallyLinkedLibrary; + compilation = compilation.RemoveAllSyntaxTrees() + .AddSyntaxTrees(trees) + .WithAssemblyName("DocumentationExample") .WithOptions(compilation.Options.WithOutputKind(output)); - errors.AddRange(compilation.GetDiagnostics(cancellationToken) - .Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) - .Select(static diagnostic => diagnostic.Id + ": " + diagnostic.GetMessage(CultureInfo.InvariantCulture) - + " (" + diagnostic.Location.GetLineSpan() + ")")); + errors.AddRange( + compilation.GetDiagnostics(cancellationToken) + .Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Select(static diagnostic => ( + diagnostic.Id + ": " + diagnostic.GetMessage(CultureInfo.InvariantCulture) + + " (" + diagnostic.Location.GetLineSpan() + ")" + )) + ); status = errors.Count == 0 ? "Passed" : "Failed"; } catch (Exception failure) when (failure is IOException or InvalidDataException or InvalidOperationException or JsonException) @@ -170,8 +256,18 @@ public static async Task ExecuteAsync( status = "Blocked"; errors.Add(failure.Message); } - results.Add(new(group.page.id, group.page.contentIdentity, context?.mode, context?.projects ?? [], group.blocks, - status, identities, errors)); + results.Add( + new( + group.page.id, + group.page.contentIdentity, + context?.mode, + context?.projects ?? [], + group.blocks, + status, + identities, + errors + ) + ); PortableExecutableReference Freeze(PortableExecutableReference reference) { @@ -179,39 +275,70 @@ PortableExecutableReference Freeze(PortableExecutableReference reference) if (!frozen.TryGetValue(path, out FrozenReference? value)) { byte[] bytes = File.ReadAllBytes(path); - value = new(MetadataReference.CreateFromImage(bytes, filePath: path, properties: reference.Properties), - Convert.ToHexStringLower(SHA256.HashData(bytes))); + value = new( + MetadataReference.CreateFromImage(bytes, filePath: path, properties: reference.Properties), + Convert.ToHexStringLower(SHA256.HashData(bytes)) + ); frozen.Add(path, value); } identities[path] = value.identity; return value.reference.WithProperties(reference.Properties); } } - IReadOnlyList scriptReferences = await DocumentationScriptApi.CompareAsync(snapshot, catalog, - results.Select(static result => result.mode).OfType().ToHashSet(StringComparer.Ordinal), configuration, + IReadOnlyList scriptReferences = await DocumentationScriptApi.CompareAsync( + snapshot, + catalog, + results.Select(static result => result.mode).OfType().ToHashSet(StringComparer.Ordinal), + configuration, options.GetValueOrDefault("--target"), - options.GetValueOrDefault("--runtime-reference"), options.GetValueOrDefault("--editor-reference"), - () => sdk.GetFrameworkReferences(cancellationToken), cancellationToken).ConfigureAwait(false); + options.GetValueOrDefault("--runtime-reference"), + options.GetValueOrDefault("--editor-reference"), + () => sdk.GetFrameworkReferences(cancellationToken), + cancellationToken + ).ConfigureAwait(false); string overall = groups.Length == 0 || results.Any(static result => result.status == "Blocked") - || scriptReferences.Any(static reference => reference.status == "Blocked") ? "Blocked" - : results.Any(static result => result.status == "Failed") || scriptReferences.Any(static reference => reference.status == "Failed") ? "Failed" : "Passed"; + || scriptReferences.Any(static reference => reference.status == "Blocked") + ? "Blocked" + : results.Any(static result => result.status == "Failed") + || scriptReferences.Any(static reference => reference.status == "Failed") + ? "Failed" + : "Passed"; cancellationToken.ThrowIfCancellationRequested(); - AtomicFile.WriteAllBytes(Path.GetFullPath(options["--output"]), JsonSerializer.SerializeToUtf8Bytes(new - { - schema = "inno-documentation-examples/1", catalog.repository, catalog.toolingRevision, - validatorIdentity = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(typeof(DocumentationExamples).Assembly.Location))), - compilerIdentity = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(typeof(CSharpCompilation).Assembly.Location))), - apiInputs = catalog.references.Where(static reference => reference.model != "project-inventory") - .Select(static reference => new { reference.model, reference.configuration, reference.target, reference.identity }) - .OrderBy(static reference => reference.model, StringComparer.Ordinal) - .ThenBy(static reference => reference.configuration, StringComparer.Ordinal) - .ThenBy(static reference => reference.target, StringComparer.Ordinal) - .ThenBy(static reference => reference.identity, StringComparer.Ordinal), - status = overall, catalog.snapshot, catalog.contentIdentity, catalog.revision, catalog.sourceTree, - sourceApiStatus = "Unverified", configuration, target = options.GetValueOrDefault("--target"), - reason = groups.Length == 0 ? "Required executable example discovery was empty." : null, results, scriptReferences - }, new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" })); - Console.WriteLine($"Documentation examples: {overall}; {results.Count} groups. Source and runtime behavior certification remain separate."); + AtomicFile.WriteAllBytes( + Path.GetFullPath(options["--output"]), + JsonSerializer.SerializeToUtf8Bytes(new + { + schema = "inno-documentation-examples/1", + catalog.repository, + catalog.toolingRevision, + validatorIdentity = Convert.ToHexStringLower( + SHA256.HashData(File.ReadAllBytes(typeof(DocumentationExamples).Assembly.Location)) + ), + compilerIdentity = Convert.ToHexStringLower( + SHA256.HashData(File.ReadAllBytes(typeof(CSharpCompilation).Assembly.Location)) + ), + apiInputs = catalog.references.Where(static reference => reference.model != "project-inventory") + .Select(static reference => new { reference.model, reference.configuration, reference.target, reference.identity }) + .OrderBy(static reference => reference.model, StringComparer.Ordinal) + .ThenBy(static reference => reference.configuration, StringComparer.Ordinal) + .ThenBy(static reference => reference.target, StringComparer.Ordinal) + .ThenBy(static reference => reference.identity, StringComparer.Ordinal), + status = overall, + catalog.snapshot, + catalog.contentIdentity, + catalog.revision, + catalog.sourceTree, + sourceApiStatus = "Unverified", + configuration, + target = options.GetValueOrDefault("--target"), + reason = groups.Length == 0 ? "Required executable example discovery was empty." : null, + results, + scriptReferences + }, new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" }) + ); + Console.WriteLine( + $"Documentation examples: {overall}; {results.Count} groups. Source and runtime behavior certification remain separate." + ); return overall == "Passed" ? 0 : 1; } diff --git a/tools/Inno.Tooling.Architecture/DocumentationExportCache.cs b/tools/Inno.Tooling.Architecture/DocumentationExportCache.cs index 727c4267e..f392d331e 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationExportCache.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationExportCache.cs @@ -6,10 +6,10 @@ using System.Text; using System.Text.Json; using System.Threading; -using Inno.Build.Toolchains; -using Inno.Core.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Tooling.Architecture; @@ -31,8 +31,10 @@ internal DocumentationExportCache( string engineRoot, CancellationToken cancellationToken ) { - m_root = PathBoundary.RequireUnlinkedPath(engineRoot, - Path.Combine(engineRoot, "artifacts", "documentation-export", "extraction-cache")); + m_root = PathBoundary.RequireUnlinkedPath( + engineRoot, + Path.Combine(engineRoot, "artifacts", "documentation-export", "extraction-cache") + ); m_publisher = new(m_root, BuildCacheArtifactRole.ImmutableArtifact); BuildCacheOwnerCatalog.Register(engineRoot, m_root, "documentation-api-extraction", m_publisher.role, cancellationToken); m_activity = m_publisher.AcquireUseAsync(cancellationToken).AsTask().GetAwaiter().GetResult(); @@ -49,8 +51,11 @@ CancellationToken cancellationToken string key = Hash(Encoding.UTF8.GetBytes(S_TOOL_IDENTITY + "\n" + inputIdentity)); string directory = PathBoundary.RequireUnlinkedPath(m_root, Path.Combine(m_root, "entries", key)); string leasePath = PathBoundary.RequireUnlinkedPath(m_root, Path.Combine(m_root, "leases", key + ".lock")); - using FileLease ownership = FileLease.AcquireAsync(leasePath, Timeout.InfiniteTimeSpan, - cancellationToken).AsTask().GetAwaiter().GetResult(); + using FileLease ownership = FileLease.AcquireAsync( + leasePath, + Timeout.InfiniteTimeSpan, + cancellationToken + ).AsTask().GetAwaiter().GetResult(); value = default; if (!BuildArtifactManifest.IsComplete(directory, key, ["facts"])) return false; try @@ -61,7 +66,10 @@ CancellationToken cancellationToken m_reused++; return true; } - catch (JsonException) { return false; } + catch (JsonException) + { + return false; + } } internal T Capture( @@ -74,15 +82,18 @@ CancellationToken cancellationToken string key = Hash(Encoding.UTF8.GetBytes(S_TOOL_IDENTITY + "\n" + inputIdentity)); string directory = PathBoundary.RequireUnlinkedPath(m_root, Path.Combine(m_root, "entries", key)); string leasePath = PathBoundary.RequireUnlinkedPath(m_root, Path.Combine(m_root, "leases", key + ".lock")); - using FileLease ownership = FileLease.AcquireAsync(leasePath, Timeout.InfiniteTimeSpan, - cancellationToken).AsTask().GetAwaiter().GetResult(); + using FileLease ownership = FileLease.AcquireAsync( + leasePath, + Timeout.InfiniteTimeSpan, + cancellationToken + ).AsTask().GetAwaiter().GetResult(); cancellationToken.ThrowIfCancellationRequested(); if (BuildArtifactManifest.IsComplete(directory, key, ["facts"])) { try { T result = JsonSerializer.Deserialize(File.ReadAllBytes(Path.Combine(directory, "facts", "project.json"))) - ?? throw new InvalidDataException("The extraction cache contains an empty owner result."); + ?? throw new InvalidDataException("The extraction cache contains an empty owner result."); m_publisher.Record(directory, leasePath, [], null, null, cancellationToken); m_reused++; return result; @@ -94,8 +105,10 @@ CancellationToken cancellationToken } T captured = capture(); cancellationToken.ThrowIfCancellationRequested(); - string staging = PathBoundary.RequireUnlinkedPath(m_root, - Path.Combine(m_root, "staging", Guid.NewGuid().ToString("N"))); + string staging = PathBoundary.RequireUnlinkedPath( + m_root, + Path.Combine(m_root, "staging", Guid.NewGuid().ToString("N")) + ); try { Directory.CreateDirectory(Path.Combine(staging, "facts")); @@ -106,8 +119,10 @@ CancellationToken cancellationToken string? quarantine = null; if (Directory.Exists(directory)) { - quarantine = PathBoundary.RequireUnlinkedPath(m_root, - Path.Combine(m_root, "quarantine", key + "-" + Guid.NewGuid().ToString("N"))); + quarantine = PathBoundary.RequireUnlinkedPath( + m_root, + Path.Combine(m_root, "quarantine", key + "-" + Guid.NewGuid().ToString("N")) + ); Directory.CreateDirectory(Path.GetDirectoryName(quarantine)!); Directory.Move(directory, quarantine); } @@ -118,7 +133,9 @@ CancellationToken cancellationToken catch { if (quarantine is not null && !Directory.Exists(directory)) + { Directory.Move(quarantine, directory); + } throw; } // Exported facts own their returned values. This acceleration artifact remains @@ -135,7 +152,9 @@ CancellationToken cancellationToken finally { if (Directory.Exists(staging)) + { Directory.Delete(staging, recursive: true); + } } } @@ -148,17 +167,21 @@ private static string ToolIdentity() string[] sources = assembly.GetManifestResourceNames().Where(static name => name.StartsWith("ApiExtractionSource/", StringComparison.Ordinal)).Order(StringComparer.Ordinal).ToArray(); if (sources.Length == 0) + { throw new InvalidDataException("The API extractor has no embedded input identity."); + } var identities = new List(); foreach (string source in sources) { using Stream stream = assembly.GetManifestResourceStream(source) - ?? throw new InvalidDataException("Missing extraction identity input: " + source); + ?? throw new InvalidDataException("Missing extraction identity input: " + source); using var reader = new StreamReader(stream); identities.Add(source + "\0" + Hash(Encoding.UTF8.GetBytes(reader.ReadToEnd().ReplaceLineEndings("\n")))); } foreach (var compiler in new[] { typeof(Compilation).Assembly, typeof(CSharpCompilation).Assembly }) + { identities.Add(compiler.GetName().Name + "\0" + Hash(File.ReadAllBytes(compiler.Location))); + } return Hash(Encoding.UTF8.GetBytes(string.Join('\n', identities))); } diff --git a/tools/Inno.Tooling.Architecture/DocumentationExportInputs.cs b/tools/Inno.Tooling.Architecture/DocumentationExportInputs.cs index 7aa6060ad..678989a3b 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationExportInputs.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationExportInputs.cs @@ -29,17 +29,27 @@ void AddFile(string file) return; } string content = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(file))); - inputs[relative.StartsWith("../", StringComparison.Ordinal) ? "external/" + Path.GetFileName(file) + "/" + content : relative] = content; + inputs[relative.StartsWith("../", StringComparison.Ordinal) + ? "external/" + Path.GetFileName(file) + "/" + content + : relative] = content; } AddFile(project); AddFile(Path.Combine(root, "global.json")); - foreach (JsonElement import in node.GetProperty("Imports").EnumerateArray()) AddFile(import.GetString()!); + foreach (JsonElement import in node.GetProperty("Imports").EnumerateArray()) + { + AddFile(import.GetString()!); + } foreach (JsonProperty kind in node.GetProperty("Items").EnumerateObject()) + { foreach (JsonElement item in kind.Value.EnumerateArray()) + { if (item.TryGetProperty("FullPath", out JsonElement full)) AddFile(full.GetString()!); + } + } // The evaluated item set detects additions, deletions and glob expansion. Normalize // checkout location only; actual SDK/package/target properties remain inputs. - string graph = node.GetRawText().Replace(root.Replace('\\', '/'), "", StringComparison.OrdinalIgnoreCase) + string graph = node.GetRawText() + .Replace(root.Replace('\\', '/'), "", StringComparison.OrdinalIgnoreCase) .Replace(JsonEncodedText.Encode(root).ToString(), "", StringComparison.OrdinalIgnoreCase); inputs["evaluation"] = graph; local[project] = Convert.ToHexStringLower(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(inputs))); @@ -51,13 +61,19 @@ void Visit(string current) { string relative = Path.GetRelativePath(root, current).Replace('\\', '/'); if (closure.ContainsKey(relative)) return; - if (!nodes.TryGetValue(current, out JsonElement node)) throw new InvalidDataException("Missing evaluated API dependency: " + relative); + if (!nodes.TryGetValue(current, out JsonElement node)) + { + throw new InvalidDataException("Missing evaluated API dependency: " + relative); + } closure[relative] = local[current]; foreach (JsonElement reference in node.GetProperty("Items").GetProperty("ProjectReference").EnumerateArray()) + { Visit(Path.GetFullPath(reference.GetProperty("FullPath").GetString()!)); + } } Visit(project); - result[Path.GetRelativePath(root, project).Replace('\\', '/')] = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(closure)))); + result[Path.GetRelativePath(root, project) + .Replace('\\', '/')] = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(closure)))); } return result; } diff --git a/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs b/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs index 74e5ae8d7..1155ba532 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs @@ -5,9 +5,9 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp; using Inno.Build.Toolchains; using Inno.Core.IO; -using Microsoft.CodeAnalysis.CSharp; namespace Inno.Tooling.Architecture; @@ -23,11 +23,14 @@ CancellationToken cancellationToken { string key = arguments[index]; if (key is not ("--engine-root" or "--dotnet" or "--output" or "--configuration" or "--artifacts-path" or "--record-completed") - || index + 1 >= arguments.Length || !options.TryAdd(key, arguments[index + 1])) + || index + 1 >= arguments.Length || !options.TryAdd(key, arguments[index + 1]) + ) { throw new ArgumentException("Unknown, duplicate or incomplete API export planning option: " + key); + } } - string Required(string key) => options.GetValueOrDefault(key) - ?? throw new ArgumentException("Missing API export planning option: " + key); + string Required(string key) + => options.GetValueOrDefault(key) + ?? throw new ArgumentException("Missing API export planning option: " + key); string root = Path.GetFullPath(Required("--engine-root")); if (options.TryGetValue("--record-completed", out string? completed)) { @@ -38,12 +41,14 @@ string Required(string key) => options.GetValueOrDefault(key) string output = Path.GetFullPath(Required("--output")); string configuration = options.GetValueOrDefault("--configuration", "Debug"); if (configuration is not ("Debug" or "SourceDebug" or "Release")) + { throw new ArgumentException("Unsupported API export configuration."); + } string[] projects = RepositorySourceInventory.Projects(root).Where(project => { string relative = Path.GetRelativePath(root, project).Replace('\\', '/'); return (relative.StartsWith("src/", StringComparison.Ordinal) || relative.StartsWith("build/", StringComparison.Ordinal)) - && !RepositorySourceInventory.IsDeclaredTestProject(project); + && !RepositorySourceInventory.IsDeclaredTestProject(project); }).Order(StringComparer.Ordinal).ToArray(); if (projects.Length == 0) throw new InvalidDataException("API export owner discovery is empty."); var properties = new Dictionary(StringComparer.Ordinal) @@ -52,32 +57,53 @@ string Required(string key) => options.GetValueOrDefault(key) ["DesignTimeBuild"] = "true" }; if (options.TryGetValue("--artifacts-path", out string? artifacts)) + { properties["ArtifactsPath"] = Path.GetFullPath(artifacts); + } // The operational Build entry supplies the existing SDK host selection. It is not // an API owner and must not acquire a documentation page merely to run extraction. string entry = Path.Combine(root, "entry", "InnoEngine.Build", "InnoEngine.Build.csproj"); string[] graphProjects = File.Exists(entry) ? [..projects, entry] : projects; - var nodes = new Dictionary(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + var nodes = new Dictionary( + OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal + ); while (graphProjects.Length != 0) { - string graphText = await ManagedProjectGraphCapture.CaptureAsync(root, dotnet, graphProjects, properties, - cancellationToken).ConfigureAwait(false); + string graphText = await ManagedProjectGraphCapture.CaptureAsync( + root, + dotnet, + graphProjects, + properties, + cancellationToken + ).ConfigureAwait(false); using JsonDocument graph = JsonDocument.Parse(graphText); foreach (JsonElement node in graph.RootElement.EnumerateArray()) + { nodes.Add(Path.GetFullPath(node.GetProperty("Path").GetString()!), node.Clone()); + } graphProjects = nodes.Values.SelectMany(node => node.GetProperty("Items").GetProperty("ProjectReference").EnumerateArray()) .Select(reference => Path.GetFullPath(reference.GetProperty("FullPath").GetString()!)) - .Distinct(nodes.Comparer).Where(project => !nodes.ContainsKey(project)).ToArray(); + .Distinct(nodes.Comparer) + .Where(project => !nodes.ContainsKey(project)) + .ToArray(); } IReadOnlyDictionary inputIdentities = DocumentationExportInputs.Capture(root, nodes); - string[] hosts = nodes.Values.Select(node => Property(node, "InnoDevelopmentTarget")).Where(value => value.Length != 0) - .Distinct(StringComparer.Ordinal).ToArray(); - if (hosts.Length != 1) throw new InvalidDataException("The actual development entry must resolve one SDK host target."); + string[] hosts = nodes.Values.Select(node => Property(node, "InnoDevelopmentTarget")) + .Where(value => value.Length != 0) + .Distinct(StringComparer.Ordinal) + .ToArray(); + if (hosts.Length != 1) + { + throw new InvalidDataException("The actual development entry must resolve one SDK host target."); + } string host = hosts[0]; string[] runtimes = nodes.Values.Select(node => Property(node, "NETCoreSdkRuntimeIdentifier")) - .Distinct(StringComparer.Ordinal).ToArray(); + .Distinct(StringComparer.Ordinal) + .ToArray(); if (runtimes.Length != 1 || runtimes[0].Length == 0) + { throw new InvalidDataException("The evaluated API graph does not identify one selected SDK runtime."); + } var owners = new List(); var builds = new SortedSet(StringComparer.Ordinal); var captures = new SortedDictionary>(StringComparer.Ordinal); @@ -92,23 +118,40 @@ string Required(string key) => options.GetValueOrDefault(key) string target = Property(node, "InnoProductTarget"); string language = Property(node, "LangVersion"); if (!LanguageVersionFacts.TryParse(language, out LanguageVersion version)) + { throw new InvalidDataException("Unsupported evaluated API language version: " + language); - string[] sources = node.GetProperty("Items").GetProperty("Compile").EnumerateArray() - .Select(item => item.GetProperty("FullPath").GetString()!).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); - var parse = new CSharpParseOptions(version, - preprocessorSymbols: Property(node, "DefineConstants").Split(';', StringSplitOptions.RemoveEmptyEntries)); + } + string[] sources = node.GetProperty("Items") + .GetProperty("Compile") + .EnumerateArray() + .Select(item => item.GetProperty("FullPath").GetString()!) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + var parse = new CSharpParseOptions( + version, + preprocessorSymbols: Property(node, "DefineConstants").Split(';', StringSplitOptions.RemoveEmptyEntries) + ); bool empty = DocumentationProjectReferences.HasNoPublicTypes(sources, parse, cancellationToken); bool local = target.Length == 0 || target == host; string context = target.Length == 0 ? host : target; - owners.Add(new { name = Path.GetFileNameWithoutExtension(project), path = relative, target, - authoredSurfaceEmpty = empty, preparation = local ? "CurrentHost" : empty ? "EvaluatedEmptySurface" : "OtherHostRequired" }); + owners.Add(new + { + name = Path.GetFileNameWithoutExtension(project), + path = relative, + target, + authoredSurfaceEmpty = empty, + preparation = local ? "CurrentHost" : empty ? "EvaluatedEmptySurface" : "OtherHostRequired" + }); if (local || empty) { if (!captures.TryGetValue(context, out List? batch)) captures.Add(context, batch = []); string key = DocumentationPreparedExports.Key(relative, inputIdentities[relative], configuration, context); if (cache.TryRead(key, out JsonElement reused, cancellationToken)) { - if (!reusedOwners.TryGetValue(context, out Dictionary? retained)) reusedOwners.Add(context, retained = []); + if (!reusedOwners.TryGetValue(context, out Dictionary? retained)) + { + reusedOwners.Add(context, retained = []); + } retained.Add(relative, reused); } else @@ -117,23 +160,53 @@ string Required(string key) => options.GetValueOrDefault(key) if (!empty) builds.Add(relative); } } - else foreign.Add(new { path = relative, target, reason = "Requires its actual target SDK producer; another host cannot certify this nonempty API." }); + else + { + foreign.Add( + new + { + path = relative, + target, + reason = "Requires its actual target SDK producer; another host cannot certify this nonempty API." + } + ); + } } cancellationToken.ThrowIfCancellationRequested(); string scriptInputIdentity = DocumentationPreparedExports.ScriptIdentity(inputIdentities); var reusedScripts = new Dictionary(StringComparer.Ordinal); foreach (string model in new[] { "runtime-script", "editor-script" }) - if (cache.TryRead(DocumentationPreparedExports.Key(model, scriptInputIdentity, configuration, host), out JsonElement reused, cancellationToken)) - reusedScripts.Add(model, reused); - AtomicFile.WriteAllBytes(output, JsonSerializer.SerializeToUtf8Bytes(new { - schema = "inno-api-export-plan/1", configuration, hostTarget = host, sdkRuntime = runtimes[0], - projects = owners, buildProjects = builds, inputIdentities, scriptInputIdentity, reusedOwners, reusedScripts, - captures = captures.Select(pair => new { target = pair.Key, projects = pair.Value }), - foreignOwners = foreign, - scope = "Evaluated source export preparation only. Empty authored surfaces do not certify generators or product execution. Closing input checks and complete multi-host reconciliation remain required." - }, new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" })); - Console.WriteLine($"Planned {projects.Length} eligible API owners for {host}; {builds.Count} managed preparations and {foreign.Count} nonempty owners require another host."); + if (cache.TryRead( + DocumentationPreparedExports.Key(model, scriptInputIdentity, configuration, host), + out JsonElement reused, + cancellationToken + )) { + reusedScripts.Add(model, reused); + } + } + AtomicFile.WriteAllBytes( + output, + JsonSerializer.SerializeToUtf8Bytes(new + { + schema = "inno-api-export-plan/1", + configuration, + hostTarget = host, + sdkRuntime = runtimes[0], + projects = owners, + buildProjects = builds, + inputIdentities, + scriptInputIdentity, + reusedOwners, + reusedScripts, + captures = captures.Select(pair => new { target = pair.Key, projects = pair.Value }), + foreignOwners = foreign, + scope = "Evaluated source export preparation only. Empty authored surfaces do not certify generators or product execution. Closing input checks and complete multi-host reconciliation remain required." + }, new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" }) + ); + Console.WriteLine( + $"Planned {projects.Length} eligible API owners for {host}; {builds.Count} managed preparations and {foreign.Count} nonempty owners require another host." + ); return 0; } diff --git a/tools/Inno.Tooling.Architecture/DocumentationPackageReferences.cs b/tools/Inno.Tooling.Architecture/DocumentationPackageReferences.cs index 36d7d1afe..54f50de2b 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationPackageReferences.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationPackageReferences.cs @@ -13,7 +13,9 @@ internal static IReadOnlyList Read(string projectDirectory) { string assets = Path.Combine(projectDirectory, "obj", "project.assets.json"); if (!File.Exists(assets)) + { return []; + } string project = Directory.EnumerateFiles(projectDirectory, "*.csproj").Single(); string framework = XDocument.Load(project).Descendants("TargetFramework").FirstOrDefault()?.Value ?? "net10.0"; using JsonDocument document = JsonDocument.Parse(File.ReadAllText(assets)); @@ -22,40 +24,58 @@ internal static IReadOnlyList Read(string projectDirectory) if (!targets.TryGetProperty(framework, out JsonElement target)) { if (!root.TryGetProperty("project", out JsonElement restoredProject) - || !restoredProject.TryGetProperty("frameworks", out JsonElement frameworks)) - throw new InvalidDataException($"Documentation restore inputs do not unambiguously describe '{framework}' for '{project}'."); - JsonProperty[] matching = frameworks.EnumerateObject().Where(item => item.Name == framework - || item.Value.TryGetProperty("targetAlias", out JsonElement alias) && alias.GetString() == framework).ToArray(); + || !restoredProject.TryGetProperty("frameworks", out JsonElement frameworks) + ) { + throw new InvalidDataException( + $"Documentation restore inputs do not unambiguously describe '{framework}' for '{project}'." + ); + } + JsonProperty[] matching = frameworks.EnumerateObject().Where(item => ( + item.Name == framework + || item.Value.TryGetProperty("targetAlias", out JsonElement alias) && alias.GetString() == framework + )).ToArray(); if (matching.Length != 1) + { throw new InvalidDataException($"Documentation restore inputs do not select one '{framework}' framework for '{project}'."); + } if (!targets.TryGetProperty(matching[0].Name, out target)) { // NuGet writes long names for netstandard targets. A single declared framework // and a single portable target establish the mapping without guessing a RID. JsonProperty[] portable = targets.EnumerateObject().Where(static item => !item.Name.Contains('/')).ToArray(); if (frameworks.EnumerateObject().Count() != 1 || portable.Length != 1) + { throw new InvalidDataException($"Documentation restore inputs do not select one portable target for '{project}'."); + } target = portable[0].Value; } } JsonElement libraries = root.GetProperty("libraries"); - string[] packageRoots = root.GetProperty("packageFolders").EnumerateObject() - .Select(static folder => folder.Name).ToArray(); + string[] packageRoots = root.GetProperty("packageFolders") + .EnumerateObject() + .Select(static folder => folder.Name) + .ToArray(); var paths = new List(); foreach (JsonProperty dependency in target.EnumerateObject()) { if (dependency.Value.GetProperty("type").GetString() != "package" - || !dependency.Value.TryGetProperty("compile", out JsonElement compile)) + || !dependency.Value.TryGetProperty("compile", out JsonElement compile) + ) { continue; + } string library = libraries.GetProperty(dependency.Name).GetProperty("path").GetString()!; foreach (JsonProperty input in compile.EnumerateObject()) { if (!input.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) + { continue; + } string? path = packageRoots.Select(folder => Path.GetFullPath(Path.Combine(folder, library, input.Name))) .FirstOrDefault(File.Exists); if (path is null) + { throw new FileNotFoundException($"Documentation requires the restored compile asset '{dependency.Name}/{input.Name}'."); + } paths.Add(path); } } diff --git a/tools/Inno.Tooling.Architecture/DocumentationPreparedExports.cs b/tools/Inno.Tooling.Architecture/DocumentationPreparedExports.cs index a8f48473c..c5b770143 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationPreparedExports.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationPreparedExports.cs @@ -18,7 +18,9 @@ string target ) => "prepared/1/" + project + "/" + input + "/" + configuration + "/" + target; internal static string ScriptIdentity(IReadOnlyDictionary inputs) - => Convert.ToHexStringLower(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(inputs.OrderBy(pair => pair.Key, StringComparer.Ordinal)))); + => Convert.ToHexStringLower( + SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(inputs.OrderBy(pair => pair.Key, StringComparer.Ordinal))) + ); internal static void Record( string root, @@ -30,7 +32,9 @@ CancellationToken cancellationToken JsonElement data = receipt.RootElement; string configuration = data.GetProperty("configuration").GetString()!; if (plan.RootElement.GetProperty("configuration").GetString() != configuration) + { throw new InvalidDataException("Prepared export plan differs from its completed context."); + } using var cache = new DocumentationExportCache(root, cancellationToken); foreach (JsonElement capture in data.GetProperty("captures").EnumerateArray()) { @@ -38,7 +42,9 @@ CancellationToken cancellationToken if (name != Path.GetFileName(name)) throw new InvalidDataException("Invalid prepared capture path."); byte[] bytes = File.ReadAllBytes(Path.Combine(completed, name)); if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != capture.GetProperty("sha256").GetString()) + { throw new InvalidDataException("Completed capture digest changed."); + } using JsonDocument facts = JsonDocument.Parse(bytes); string target = capture.GetProperty("target").GetString()!; string model = capture.GetProperty("model").GetString()!; @@ -50,13 +56,26 @@ CancellationToken cancellationToken string input = plan.RootElement.GetProperty("inputIdentities").GetProperty(owner).GetString()!; cache.Capture(owner, Key(owner, input, configuration, target), () => new { - fact = project.Clone(), producerRevision = data.GetProperty("revision").GetString(), inputIdentity = input + fact = project.Clone(), + producerRevision = data.GetProperty("revision").GetString(), + inputIdentity = input }, cancellationToken); } } - else cache.Capture(model, Key(model, plan.RootElement.GetProperty("scriptInputIdentity").GetString()!, configuration, target), - () => new { fact = facts.RootElement.Clone(), producerRevision = data.GetProperty("revision").GetString(), - inputIdentity = plan.RootElement.GetProperty("scriptInputIdentity").GetString() }, cancellationToken); + else + { + cache.Capture( + model, + Key(model, plan.RootElement.GetProperty("scriptInputIdentity").GetString()!, configuration, target), + () => new + { + fact = facts.RootElement.Clone(), + producerRevision = data.GetProperty("revision").GetString(), + inputIdentity = plan.RootElement.GetProperty("scriptInputIdentity").GetString() + }, + cancellationToken + ); + } } cache.Report(); } diff --git a/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs b/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs index d85be9759..4fab3764e 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs @@ -7,10 +7,10 @@ using System.Text.Json; using System.Threading; using System.Xml.Linq; -using Inno.Build.Toolchains; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Inno.Build.Toolchains; namespace Inno.Tooling.Architecture; @@ -40,7 +40,12 @@ internal DocumentationProjectReferences( string? sdkSnapshot = null ) { if (!Path.IsPathFullyQualified(dotnetHost) || !File.Exists(dotnetHost)) - throw new ArgumentException("Documentation SDK inspection requires an existing absolute dotnet executable.", nameof(dotnetHost)); + { + throw new ArgumentException( + "Documentation SDK inspection requires an existing absolute dotnet executable.", + nameof(dotnetHost) + ); + } m_root = root; m_configuration = configuration; m_dotnetHost = dotnetHost; @@ -51,34 +56,62 @@ internal DocumentationProjectReferences( { using JsonDocument graph = JsonDocument.Parse(sdkSnapshot); if (graph.RootElement.ValueKind != JsonValueKind.Array || graph.RootElement.GetArrayLength() == 0) + { throw new InvalidDataException("A supplied SDK snapshot must contain the selected project contexts."); - m_selectedProperties = graph.RootElement[0].GetProperty("GlobalProperties").EnumerateObject() - .ToDictionary(static property => property.Name, static property => property.Value.GetString()!, StringComparer.OrdinalIgnoreCase); + } + m_selectedProperties = graph.RootElement[0].GetProperty("GlobalProperties") + .EnumerateObject() + .ToDictionary( + static property => property.Name, + static property => property.Value.GetString()!, + StringComparer.OrdinalIgnoreCase + ); if (m_selectedProperties.GetValueOrDefault("Configuration") != configuration - || artifactsPath is not null && m_selectedProperties.GetValueOrDefault("ArtifactsPath") != artifactsPath) - throw new InvalidDataException("Documentation snapshot properties do not match the requested configuration and output owner."); + || artifactsPath is not null && m_selectedProperties.GetValueOrDefault("ArtifactsPath") != artifactsPath + ) { + throw new InvalidDataException( + "Documentation snapshot properties do not match the requested configuration and output owner." + ); + } bool resolved = graph.RootElement[0].GetProperty("Items").TryGetProperty("ReferencePath", out _); foreach (JsonElement snapshot in graph.RootElement.EnumerateArray()) { - var properties = snapshot.GetProperty("GlobalProperties").EnumerateObject() - .ToDictionary(static property => property.Name, static property => property.Value.GetString()!, StringComparer.OrdinalIgnoreCase); - if (properties.Count != m_selectedProperties.Count || properties.Any(property => - !m_selectedProperties.TryGetValue(property.Key, out string? value) || value != property.Value)) + var properties = snapshot.GetProperty("GlobalProperties") + .EnumerateObject() + .ToDictionary( + static property => property.Name, + static property => property.Value.GetString()!, + StringComparer.OrdinalIgnoreCase + ); + if (properties.Count != m_selectedProperties.Count || properties.Any(property => ( + !m_selectedProperties.TryGetValue(property.Key, out string? value) || value != property.Value + ))) { throw new InvalidDataException("SDK snapshot roots do not share one effective property context."); + } if (snapshot.GetProperty("Items").TryGetProperty("ReferencePath", out _) != resolved) + { throw new InvalidDataException("An SDK snapshot cannot mix resolved and unresolved reference contexts."); + } if (resolved && !m_snapshots.TryAdd(Path.GetFullPath(snapshot.GetProperty("Path").GetString()!), snapshot.Clone())) + { throw new InvalidDataException("A resolved SDK snapshot repeats a project owner."); + } } - if (resolved && selectedProjects is not null && selectedProjects.Any(project => !m_snapshots.ContainsKey(Path.GetFullPath(project)))) + if (resolved + && selectedProjects is not null + && selectedProjects.Any(project => !m_snapshots.ContainsKey(Path.GetFullPath(project))) + ) { throw new InvalidDataException("A resolved SDK snapshot is missing a selected documentation owner."); + } } } internal bool IsExcludedProduct(string project) { if (m_target is null) + { return false; + } string? target = XDocument.Load(project).Descendants("InnoProductTarget").FirstOrDefault()?.Value; return target is not null && !string.Equals(target, m_target, StringComparison.Ordinal); } @@ -86,13 +119,21 @@ internal bool IsExcludedProduct(string project) internal IReadOnlyList GetFrameworkReferences(CancellationToken cancellationToken) { if (m_frameworkReferences is not null) - return m_frameworkReferences; - foreach (string project in (m_selectedProjects is { Count: > 0 } ? m_selectedProjects - : RepositorySourceInventory.Files(Path.Combine(m_root, "src", "foundation"), "*.csproj")).Order(StringComparer.Ordinal)) { + return m_frameworkReferences; + } + foreach (string project in (m_selectedProjects is { Count: > 0 } + ? m_selectedProjects + : RepositorySourceInventory.Files( + Path.Combine(m_root, "src", "foundation"), + "*.csproj" + )).Order(StringComparer.Ordinal) + ) { _ = Evaluate(project, cancellationToken, frameworkOnly: true); if (m_frameworkReferences is not null) + { return m_frameworkReferences; + } } throw new InvalidDataException("The selected SDK did not provide framework references."); } @@ -104,10 +145,17 @@ CancellationToken cancellationToken CSharpCompilation compilation = Evaluate(project, cancellationToken); string target = m_outputs[project]; if (!File.Exists(target)) + { throw new InvalidDataException($"Build the selected Documentation project contract before validation: '{target}'."); - return compilation.AddReferences(MetadataReference.CreateFromFile(target, - documentation: File.Exists(Path.ChangeExtension(target, ".xml")) - ? new AssemblyDocumentationProvider(Path.ChangeExtension(target, ".xml")) : null)); + } + return compilation.AddReferences( + MetadataReference.CreateFromFile( + target, + documentation: File.Exists(Path.ChangeExtension(target, ".xml")) + ? new AssemblyDocumentationProvider(Path.ChangeExtension(target, ".xml")) + : null + ) + ); } internal CSharpCompilation GetSourceCompilation( @@ -120,12 +168,20 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); if (!File.Exists(source)) + { throw new InvalidDataException($"The evaluated Documentation source is missing: '{source}'."); - trees.Add(CSharpSyntaxTree.ParseText(File.ReadAllText(source), - (CSharpParseOptions)contract.SyntaxTrees.Single().Options, source, - cancellationToken: cancellationToken)); + } + trees.Add( + CSharpSyntaxTree.ParseText( + File.ReadAllText(source), + (CSharpParseOptions)contract.SyntaxTrees.Single().Options, + source, + cancellationToken: cancellationToken + ) + ); } - return contract.RemoveAllSyntaxTrees().AddSyntaxTrees(trees) + return contract.RemoveAllSyntaxTrees() + .AddSyntaxTrees(trees) .WithAssemblyName(Path.GetFileNameWithoutExtension(m_outputs[project])); } @@ -143,7 +199,9 @@ CancellationToken cancellationToken { path = Path.GetRelativePath(m_root, tree.FilePath).Replace('\\', '/'), content = Hash(Encoding.UTF8.GetBytes(tree.GetText(cancellationToken).ToString())), - parse.LanguageVersion, parse.Kind, parse.DocumentationMode, + parse.LanguageVersion, + parse.Kind, + parse.DocumentationMode, symbols = parse.PreprocessorSymbolNames.ToArray(), features = parse.Features.OrderBy(static item => item.Key, StringComparer.Ordinal).ToArray() }); @@ -152,30 +210,42 @@ CancellationToken cancellationToken { name = Path.GetFileName(reference.FilePath), input = m_frozenReferences[reference.FilePath!].identity, - reference.Properties.Kind, reference.Properties.EmbedInteropTypes, + reference.Properties.Kind, + reference.Properties.EmbedInteropTypes, aliases = reference.Properties.Aliases.ToArray() }).ToArray(); - return Hash(JsonSerializer.SerializeToUtf8Bytes(new - { - project = Path.GetRelativePath(m_root, project).Replace('\\', '/'), - configuration = m_configuration, target = m_target, - compilation.AssemblyName, compilation.Options.OutputKind, - compilation.Options.AllowUnsafe, compilation.Options.NullableContextOptions, - sources, references - })); + return Hash( + JsonSerializer.SerializeToUtf8Bytes(new + { + project = Path.GetRelativePath(m_root, project).Replace('\\', '/'), + configuration = m_configuration, + target = m_target, + compilation.AssemblyName, + compilation.Options.OutputKind, + compilation.Options.AllowUnsafe, + compilation.Options.NullableContextOptions, + sources, + references + }) + ); } private PortableExecutableReference FreezeReference(string path) { if (m_frozenReferences.TryGetValue(path, out FrozenReference? retained)) + { return retained.reference; + } byte[] image = File.ReadAllBytes(path); string xmlPath = Path.ChangeExtension(path, ".xml"); byte[]? xml = File.Exists(xmlPath) ? File.ReadAllBytes(xmlPath) : null; // Roslyn and the reuse identity consume the very same immutable bytes. A concurrent // compiler cannot replace a file between hashing it and lazy metadata/XML inspection. - PortableExecutableReference reference = MetadataReference.CreateFromImage(image, filePath: path, - documentation: xml is null ? null : new AssemblyDocumentationProvider(xmlPath, xml)); + PortableExecutableReference reference = MetadataReference.CreateFromImage( + image, + filePath: path, + documentation: xml is null ? null : new AssemblyDocumentationProvider(xmlPath, xml) + ); string identity = Hash(Encoding.UTF8.GetBytes(Hash(image) + "\n" + (xml is null ? "absent" : Hash(xml)))); m_frozenReferences.Add(path, new(reference, identity)); return reference; @@ -195,13 +265,21 @@ private CSharpCompilation Evaluate( bool sourceOnly = false ) { if (m_compilations.TryGetValue(project, out CSharpCompilation? compilation)) + { return compilation; + } if (m_snapshots.Count == 0) { - string[] projects = (m_selectedProjects is not null ? m_selectedProjects : new[] { "src", "entry", "build", "backends", "platforms", "tools", "tests" } - .SelectMany(folder => RepositorySourceInventory.Files(Path.Combine(m_root, folder), "*.csproj")) - .Where(path => !IsExcludedProduct(path) && !RepositorySourceInventory.IsDeclaredTestProject(path))).Append(project).Where(path => !IsExcludedProduct(path)) - .Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.Ordinal).ToArray(); + string[] projects = (m_selectedProjects is not null + ? m_selectedProjects + : new[] { "src", "entry", "build", "backends", "platforms", "tools", "tests" } + .SelectMany(folder => RepositorySourceInventory.Files(Path.Combine(m_root, folder), "*.csproj")) + .Where(path => !IsExcludedProduct(path) && !RepositorySourceInventory.IsDeclaredTestProject(path))) + .Append(project) + .Where(path => !IsExcludedProduct(path)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Order(StringComparer.Ordinal) + .ToArray(); var batchProperties = new Dictionary { ["DesignTimeBuild"] = "true", @@ -210,50 +288,97 @@ private CSharpCompilation Evaluate( ["Configuration"] = m_configuration }; if (m_artifactsPath is not null) + { batchProperties.Add("ArtifactsPath", m_artifactsPath); + } if (m_selectedProperties is not null) + { foreach (var property in m_selectedProperties) + { batchProperties[property.Key] = property.Value; + } + } // One SDK process resolves the entire requested reference set; no build or native preparation targets run. - string captured = ManagedProjectGraphCapture.CaptureAsync(m_root, m_dotnetHost, projects, batchProperties, - cancellationToken, resolveReferences: true).GetAwaiter().GetResult(); + string captured = ManagedProjectGraphCapture.CaptureAsync( + m_root, + m_dotnetHost, + projects, + batchProperties, + cancellationToken, + resolveReferences: true + ).GetAwaiter().GetResult(); using JsonDocument batch = JsonDocument.Parse(captured); foreach (JsonElement snapshot in batch.RootElement.EnumerateArray()) + { m_snapshots.Add(snapshot.GetProperty("Path").GetString()!, snapshot.Clone()); + } } JsonElement document = m_snapshots[Path.GetFullPath(project)]; JsonElement properties = document.GetProperty("Properties"); string target = properties.GetProperty("TargetPath").GetString()!; - string[] references = document.GetProperty("Items").GetProperty("ReferencePath") - .EnumerateArray().Select(static item => item.GetProperty("FullPath").GetString()!) - .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + string[] references = document.GetProperty("Items") + .GetProperty("ReferencePath") + .EnumerateArray() + .Select(static item => item.GetProperty("FullPath").GetString()!) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); if (m_frameworkReferences is null) { - string[] framework = document.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray() - .Where(static item => item.TryGetProperty("FrameworkReferenceName", out JsonElement name) - && name.GetString() == "Microsoft.NETCore.App") - .Select(static item => item.GetProperty("FullPath").GetString()!).ToArray(); + string[] framework = document.GetProperty("Items") + .GetProperty("ReferencePath") + .EnumerateArray() + .Where(static item => ( + item.TryGetProperty("FrameworkReferenceName", out JsonElement name) + && name.GetString() == "Microsoft.NETCore.App" + )) + .Select(static item => item.GetProperty("FullPath").GetString()!) + .ToArray(); if (framework.Length != 0) - m_frameworkReferences = framework.Select(static path => (MetadataReference)MetadataReference.CreateFromFile(path)).ToArray(); + { + m_frameworkReferences = framework + .Select(static path => (MetadataReference)MetadataReference.CreateFromFile(path)) + .ToArray(); + } } if (frameworkOnly) + { return CSharpCompilation.Create("DocumentationFramework", references: m_frameworkReferences); + } string language = properties.GetProperty("LangVersion").GetString()!; if (!LanguageVersionFacts.TryParse(language, out LanguageVersion version)) - throw new InvalidDataException($"Documentation project '{project}' selects unsupported C# language version '{language}'. The validator must support that version explicitly."); - var parse = new CSharpParseOptions(version, preprocessorSymbols: - properties.GetProperty("DefineConstants").GetString()!.Split(';', StringSplitOptions.RemoveEmptyEntries)); - string[] sources = document.GetProperty("Items").GetProperty("Compile") - .EnumerateArray().Select(static item => item.GetProperty("FullPath").GetString()!) - .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + { + throw new InvalidDataException( + $"Documentation project '{project}' selects unsupported C# language version '{language}'. The validator must support that version explicitly." + ); + } + var parse = new CSharpParseOptions( + version, + preprocessorSymbols: + properties.GetProperty("DefineConstants").GetString()!.Split(';', StringSplitOptions.RemoveEmptyEntries) + ); + string[] sources = document.GetProperty("Items") + .GetProperty("Compile") + .EnumerateArray() + .Select(static item => item.GetProperty("FullPath").GetString()!) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); // An evaluated source set with no public type declaration cannot expose CLR members. // This proves only the empty authored API surface, never product build or generator execution. bool referenceFree = sourceOnly && HasNoPublicTypes(sources, parse, cancellationToken); if (referenceFree) + { references = []; + } foreach (string reference in references) + { if (!File.Exists(reference)) - throw new FileNotFoundException($"Documentation project '{project}' requires its evaluated compile reference: '{reference}'. Build this target/configuration before validation.", reference); + { + throw new FileNotFoundException( + $"Documentation project '{project}' requires its evaluated compile reference: '{reference}'. Build this target/configuration before validation.", + reference + ); + } + } NullableContextOptions nullable = properties.GetProperty("Nullable").GetString() switch { "enable" => NullableContextOptions.Enable, @@ -261,15 +386,21 @@ private CSharpCompilation Evaluate( "warnings" => NullableContextOptions.Warnings, _ => NullableContextOptions.Disable }; - compilation = CSharpCompilation.Create("DocumentationProject", + compilation = CSharpCompilation.Create( + "DocumentationProject", [CSharpSyntaxTree.ParseText(string.Empty, parse)], references.Select(FreezeReference), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, + new CSharpCompilationOptions( + OutputKind.DynamicallyLinkedLibrary, allowUnsafe: properties.GetProperty("AllowUnsafeBlocks").GetString() == "true", - nullableContextOptions: nullable)); + nullableContextOptions: nullable + ) + ); // Do not let an API-only empty surface replace metadata needed by executable examples. if (!referenceFree) + { m_compilations.Add(project, compilation); + } m_outputs[project] = target; m_sources[project] = sources; return compilation; @@ -284,20 +415,29 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); if (!File.Exists(source)) + { throw new InvalidDataException($"The evaluated Documentation source is missing: '{source}'."); - SyntaxTree tree = CSharpSyntaxTree.ParseText(File.ReadAllText(source), parse, source, - cancellationToken: cancellationToken); + } + SyntaxTree tree = CSharpSyntaxTree.ParseText( + File.ReadAllText(source), + parse, + source, + cancellationToken: cancellationToken + ); if (tree.GetDiagnostics(cancellationToken).Any(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)) + { throw new InvalidDataException($"The evaluated Documentation source has invalid C# syntax: '{source}'."); + } if (tree.GetRoot(cancellationToken).DescendantNodes().Any(static node => node switch { BaseTypeDeclarationSyntax type => type.Modifiers.Any(SyntaxKind.PublicKeyword), DelegateDeclarationSyntax type => type.Modifiers.Any(SyntaxKind.PublicKeyword), _ => false - })) + }) + ) { return false; + } } return true; } - } diff --git a/tools/Inno.Tooling.Architecture/DocumentationReferences.cs b/tools/Inno.Tooling.Architecture/DocumentationReferences.cs index ced3563f1..d461ba3c5 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationReferences.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationReferences.cs @@ -7,9 +7,9 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Inno.Core.IO; using Inno.Tooling.Documentation; -using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Inno.Tooling.Architecture; @@ -93,41 +93,75 @@ public static int ExportApi( ) { ArgumentNullException.ThrowIfNull(arguments); if (arguments.Contains("--surface", StringComparer.Ordinal)) + { return DocumentationScriptApi.Export(arguments, cancellationToken); + } var options = new Dictionary(StringComparer.Ordinal); var requested = new HashSet(StringComparer.Ordinal); for (int index = 0; index < arguments.Length; index += 2) { string key = arguments[index]; if (index + 1 >= arguments.Length) + { throw new ArgumentException("Incomplete API export option: " + key); + } if (key == "--project") { if (!requested.Add(arguments[index + 1].Replace('\\', '/'))) + { throw new ArgumentException("Duplicate API project selection."); + } } - else if (key is not ("--engine-root" or "--dotnet" or "--output" or "--configuration" or "--target" or "--artifacts-path" or "--sdk-snapshot") - || !options.TryAdd(key, arguments[index + 1])) + else if (key is not ("--engine-root" + or "--dotnet" + or "--output" + or "--configuration" + or "--target" + or "--artifacts-path" + or "--sdk-snapshot") + || !options.TryAdd(key, arguments[index + 1]) + ) { throw new ArgumentException("Unknown or duplicate API export option: " + key); + } } if (!options.TryGetValue("--engine-root", out string? engineRoot) || !options.TryGetValue("--dotnet", out string? dotnet) - || !options.TryGetValue("--output", out string? output) || requested.Count == 0) - throw new ArgumentException("Usage: docs export-api --engine-root ROOT --dotnet SDK --project OWNER.csproj [--project OWNER.csproj] --output FACTS.json [--configuration Debug|SourceDebug|Release] [--target TARGET]."); + || !options.TryGetValue("--output", out string? output) || requested.Count == 0 + ) { + throw new ArgumentException( + "Usage: docs export-api --engine-root ROOT --dotnet SDK --project OWNER.csproj [--project OWNER.csproj] --output FACTS.json [--configuration Debug|SourceDebug|Release] [--target TARGET]." + ); + } string configuration = options.GetValueOrDefault("--configuration", "Debug"); if (configuration is not ("Debug" or "SourceDebug" or "Release")) + { throw new ArgumentException("Unsupported API extraction configuration."); + } string root = Path.GetFullPath(engineRoot); - IReadOnlyList inventory = CaptureApi(root, dotnet, configuration, - options.GetValueOrDefault("--target"), requested, cancellationToken, + IReadOnlyList inventory = CaptureApi( + root, + dotnet, + configuration, + options.GetValueOrDefault("--target"), + requested, + cancellationToken, options.GetValueOrDefault("--artifacts-path"), - options.TryGetValue("--sdk-snapshot", out string? graphPath) ? File.ReadAllText(graphPath) : null); + options.TryGetValue("--sdk-snapshot", out string? graphPath) ? File.ReadAllText(graphPath) : null + ); cancellationToken.ThrowIfCancellationRequested(); - AtomicFile.WriteAllBytes(Path.GetFullPath(output), JsonSerializer.SerializeToUtf8Bytes(new - { - model = "source-clr", configuration, target = options.GetValueOrDefault("--target"), - sourceApiStatus = "Unverified", projects = inventory - }, new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" })); - Console.WriteLine($"Exported {inventory.Count} evaluated CLR project surfaces. Script projections and source API certification remain separate."); + AtomicFile.WriteAllBytes( + Path.GetFullPath(output), + JsonSerializer.SerializeToUtf8Bytes(new + { + model = "source-clr", + configuration, + target = options.GetValueOrDefault("--target"), + sourceApiStatus = "Unverified", + projects = inventory + }, new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" }) + ); + Console.WriteLine( + $"Exported {inventory.Count} evaluated CLR project surfaces. Script projections and source API certification remain separate." + ); return 0; } @@ -172,39 +206,63 @@ public static async Task ValidateApiAsync( var options = new Dictionary(StringComparer.Ordinal); var selectedReferences = new HashSet(StringComparer.Ordinal); var selectedProjects = new HashSet(StringComparer.Ordinal); - var references = new Dictionary(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + var references = new Dictionary( + OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal + ); for (int index = 0; index < arguments.Length; index += 2) { if (index + 1 == arguments.Length) + { throw new ArgumentException("Incomplete reference validation option: " + arguments[index]); + } string key = arguments[index]; if (key == "--reference") { if (!selectedReferences.Add(arguments[index + 1])) + { throw new ArgumentException("Duplicate reference manifest: " + arguments[index + 1]); + } } else if (key == "--project") { if (!selectedProjects.Add(arguments[index + 1])) + { throw new ArgumentException("Duplicate source owner selection: " + arguments[index + 1]); + } } - else if (key is not ("--engine-root" or "--dotnet" or "--output" or "--cache-root" or "--snapshot" or "--artifacts-path" or "--sdk-snapshot") - || !options.TryAdd(key, arguments[index + 1])) + else if (key is not ("--engine-root" + or "--dotnet" + or "--output" + or "--cache-root" + or "--snapshot" + or "--artifacts-path" + or "--sdk-snapshot") + || !options.TryAdd(key, arguments[index + 1]) + ) { throw new ArgumentException("Unknown or duplicate reference validation option: " + key); + } } if (selectedReferences.Count == 0 || !options.TryGetValue("--engine-root", out string? root) - || !options.TryGetValue("--dotnet", out string? dotnet) || !options.TryGetValue("--output", out string? output)) - throw new ArgumentException("Usage: docs validate-api --engine-root ROOT --dotnet SDK --reference FACTS.json [--reference FACTS.json] --output REPORT.json [--cache-root CACHE --snapshot ID] [--project OWNER.csproj]"); + || !options.TryGetValue("--dotnet", out string? dotnet) || !options.TryGetValue("--output", out string? output) + ) { + throw new ArgumentException( + "Usage: docs validate-api --engine-root ROOT --dotnet SDK --reference FACTS.json [--reference FACTS.json] --output REPORT.json [--cache-root CACHE --snapshot ID] [--project OWNER.csproj]" + ); + } bool cached = options.TryGetValue("--cache-root", out string? cache); if (cached != options.ContainsKey("--snapshot")) + { throw new ArgumentException("A prepared reference comparison requires both cache-root and snapshot."); + } output = Path.GetFullPath(output); if (cached) { string relativeOutput = Path.GetRelativePath(Path.GetFullPath(cache!), output); if (!Path.IsPathRooted(relativeOutput) && relativeOutput != ".." - && !relativeOutput.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + && !relativeOutput.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) + ) { throw new ArgumentException("Comparison reports cannot modify the documentation cache owner."); + } } using DocumentationSnapshot? snapshot = cached ? await DocumentationStore.OpenAsync(cache!, options["--snapshot"], cancellationToken: cancellationToken).ConfigureAwait(false) @@ -213,13 +271,18 @@ public static async Task ValidateApiAsync( { cancellationToken.ThrowIfCancellationRequested(); string path = cached ? selected : Path.GetFullPath(selected); - byte[] bytes = snapshot is null ? await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false) - : await snapshot.ReadReferenceAsync(path, cancellationToken).ConfigureAwait(false); + byte[] bytes = snapshot is null + ? await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false) + : await snapshot.ReadReferenceAsync(path, cancellationToken).ConfigureAwait(false); if (!references.TryAdd(path, bytes)) + { throw new ArgumentException("Repeated reference manifest identity: " + path); + } } if (references.ContainsKey(output)) + { throw new ArgumentException("A comparison report cannot replace an input manifest."); + } string? configuration = null; string? target = null; var expected = new Dictionary(StringComparer.Ordinal); @@ -231,41 +294,76 @@ public static async Task ValidateApiAsync( string? selectedConfiguration = facts.GetProperty("configuration").GetString(); string? selectedTarget = facts.TryGetProperty("target", out JsonElement declaredTarget) ? declaredTarget.GetString() : null; if (facts.GetProperty("model").GetString() != "source-clr" - || selectedConfiguration is not ("Debug" or "SourceDebug" or "Release")) + || selectedConfiguration is not ("Debug" or "SourceDebug" or "Release") + ) { throw new InvalidDataException("Unsupported source reference context: " + reference.Key); + } if (configuration is not null && (configuration != selectedConfiguration || target != selectedTarget)) - throw new InvalidDataException("Reference manifests require separate evaluated batches for different configurations or targets."); + { + throw new InvalidDataException( + "Reference manifests require separate evaluated batches for different configurations or targets." + ); + } configuration = selectedConfiguration; target = selectedTarget; if (facts.GetProperty("projects").GetArrayLength() == 0) + { throw new InvalidDataException("Required source reference discovery is empty: " + reference.Key); + } foreach (JsonElement project in facts.GetProperty("projects").EnumerateArray()) { string source = project.GetProperty("project").GetString()!; string absolute = PathBoundary.Resolve(Path.GetFullPath(root), source); if (source != Path.GetRelativePath(Path.GetFullPath(root), absolute).Replace('\\', '/')) + { throw new InvalidDataException("Source reference paths must be canonical owner-relative paths: " + source); + } var identities = new HashSet(StringComparer.Ordinal); foreach (JsonElement symbol in project.GetProperty("symbols").EnumerateArray()) + { if (!identities.Add(symbol.GetProperty("id").GetString()!)) + { throw new InvalidDataException("Repeated reference symbol: " + symbol.GetProperty("id").GetString()); + } + } if (!expected.TryAdd(source, project.Clone())) - throw new InvalidDataException("Repeated source project in reference selection: " + project.GetProperty("project").GetString()); + { + throw new InvalidDataException( + "Repeated source project in reference selection: " + project.GetProperty("project").GetString() + ); + } } } if (expected.Count == 0) + { throw new InvalidDataException("Required source reference discovery is empty."); + } if (selectedProjects.Count != 0) { foreach (string project in selectedProjects) + { if (!expected.ContainsKey(project)) + { throw new InvalidDataException("Selected source owner is absent from the reference batch: " + project); + } + } foreach (string project in expected.Keys.Where(project => !selectedProjects.Contains(project)).ToArray()) + { expected.Remove(project); + } } - IReadOnlyList actual = CaptureApi(Path.GetFullPath(root), dotnet, configuration!, target, - expected.Keys, cancellationToken, options.GetValueOrDefault("--artifacts-path"), - options.TryGetValue("--sdk-snapshot", out string? graphPath) ? await File.ReadAllTextAsync(graphPath, cancellationToken).ConfigureAwait(false) : null); + IReadOnlyList actual = CaptureApi( + Path.GetFullPath(root), + dotnet, + configuration!, + target, + expected.Keys, + cancellationToken, + options.GetValueOrDefault("--artifacts-path"), + options.TryGetValue("--sdk-snapshot", out string? graphPath) + ? await File.ReadAllTextAsync(graphPath, cancellationToken).ConfigureAwait(false) + : null + ); var results = new List(); bool passed = true; foreach (ApiProject project in actual) @@ -274,40 +372,72 @@ public static async Task ValidateApiAsync( JsonElement previous = expected[project.project]; var differences = new List(); if (previous.GetProperty("name").GetString() != project.name) + { differences.Add("Project identity differs from the actual source owner."); + } var symbols = new Dictionary(StringComparer.Ordinal); foreach (JsonElement symbol in previous.GetProperty("symbols").EnumerateArray()) + { symbols.Add(symbol.GetProperty("id").GetString()!, symbol); + } foreach (var symbol in project.symbols) { if (!symbols.Remove(symbol.id, out JsonElement prior)) + { differences.Add("Missing current declaration: " + symbol.id); + } else if (ComparableSymbol(prior) != ComparableSymbol(JsonSerializer.SerializeToElement(symbol))) + { differences.Add("Declaration, XML, constant, source or type relationships changed: " + symbol.id); + } } - differences.AddRange(symbols.Keys.Order(StringComparer.Ordinal).Select(static id => "Reference declaration no longer exists: " + id)); + differences.AddRange( + symbols.Keys.Order(StringComparer.Ordinal).Select(static id => "Reference declaration no longer exists: " + id) + ); passed &= differences.Count == 0; - results.Add(new { project.project, project.name, status = differences.Count == 0 ? "Passed" : "Failed", + results.Add(new + { + project.project, + project.name, + status = differences.Count == 0 ? "Passed" : "Failed", referenceIdentity = Convert.ToHexStringLower(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(previous))), - symbols = project.symbols.Count, differences }); + symbols = project.symbols.Count, + differences + }); } if (snapshot is null) + { foreach (var reference in references) + { if (!File.ReadAllBytes(reference.Key).AsSpan().SequenceEqual(reference.Value)) + { throw new InvalidDataException("Reference input changed during source validation: " + reference.Key); + } + } + } cancellationToken.ThrowIfCancellationRequested(); - AtomicFile.WriteAllBytes(output, JsonSerializer.SerializeToUtf8Bytes(new - { - status = passed ? "Passed" : "Failed", scope = "SelectedSourceReferenceComparison", configuration, target, - sourceApiStatus = "Unverified", - documentationSnapshot = snapshot?.identity, documentationSourceTree = snapshot?.sourceTree, - references = references.OrderBy(static pair => pair.Key, StringComparer.Ordinal).Select(static pair => new + AtomicFile.WriteAllBytes( + output, + JsonSerializer.SerializeToUtf8Bytes(new { - path = pair.Key, identity = Convert.ToHexStringLower(SHA256.HashData(pair.Value)) - }), - projects = results - }, new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" })); - Console.WriteLine($"Compared {actual.Count} evaluated source owners in one batch: {(passed ? "Passed" : "Failed")}. Publication provenance and other validation remain separate."); + status = passed ? "Passed" : "Failed", + scope = "SelectedSourceReferenceComparison", + configuration, + target, + sourceApiStatus = "Unverified", + documentationSnapshot = snapshot?.identity, + documentationSourceTree = snapshot?.sourceTree, + references = references.OrderBy(static pair => pair.Key, StringComparer.Ordinal).Select(static pair => new + { + path = pair.Key, + identity = Convert.ToHexStringLower(SHA256.HashData(pair.Value)) + }), + projects = results + }, new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" }) + ); + Console.WriteLine( + $"Compared {actual.Count} evaluated source owners in one batch: {(passed ? "Passed" : "Failed")}. Publication provenance and other validation remain separate." + ); return passed ? 0 : 1; } @@ -345,31 +475,50 @@ public static int ExportProjects( { string key = arguments[index]; if (key is not ("--engine-root" or "--output") || index + 1 >= arguments.Length - || !options.TryAdd(key, arguments[index + 1])) + || !options.TryAdd(key, arguments[index + 1]) + ) { throw new ArgumentException("Unknown, duplicate or incomplete reference export option: " + key); + } } if (!options.TryGetValue("--engine-root", out string? engineRoot) || !options.TryGetValue("--output", out string? output)) + { throw new ArgumentException("Usage: docs export-projects --engine-root ROOT --output PROJECTS.json"); + } string root = Path.GetFullPath(engineRoot); var names = new HashSet(StringComparer.Ordinal); var projects = new List(); foreach (string project in RepositorySourceInventory.Projects(root) - .OrderBy(project => Path.GetRelativePath(root, project).Replace('\\', '/'), StringComparer.Ordinal)) - { + .OrderBy(project => Path.GetRelativePath(root, project).Replace('\\', '/'), StringComparer.Ordinal) + ) { cancellationToken.ThrowIfCancellationRequested(); PathBoundary.RequireUnlinkedPath(root, project); string name = Path.GetFileNameWithoutExtension(project); if (!names.Add(name)) + { throw new InvalidDataException("Duplicate source-project identity: " + name); + } // API surfaces require evaluated extraction; inventory must never invent them from a project name. - projects.Add(new { name, path = Path.GetRelativePath(root, project).Replace('\\', '/'), entry = (string?)null, - surfaces = Array.Empty(), isTest = RepositorySourceInventory.IsDeclaredTestProject(project) }); + projects.Add(new + { + name, + path = Path.GetRelativePath(root, project).Replace('\\', '/'), + entry = (string?)null, + surfaces = Array.Empty(), + isTest = RepositorySourceInventory.IsDeclaredTestProject(project) + }); } if (projects.Count == 0) + { throw new InvalidDataException("Source-project inventory is empty."); + } cancellationToken.ThrowIfCancellationRequested(); - AtomicFile.WriteAllBytes(Path.GetFullPath(output), JsonSerializer.SerializeToUtf8Bytes(projects, - new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" })); + AtomicFile.WriteAllBytes( + Path.GetFullPath(output), + JsonSerializer.SerializeToUtf8Bytes( + projects, + new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" } + ) + ); Console.WriteLine($"Exported {projects.Count} source projects. API surfaces and source validation remain unverified."); return 0; } @@ -391,12 +540,21 @@ private static IReadOnlyList CaptureApi( string absolute = PathBoundary.Resolve(root, project); PathBoundary.RequireUnlinkedPath(root, absolute); if (!projects.Contains(absolute, StringComparer.Ordinal)) + { throw new ArgumentException("Selected API owner is absent from the actual source inventory: " + project); + } selected.Add(absolute); } var failures = new List(); - var references = new DocumentationProjectReferences(root, configuration, Path.GetFullPath(dotnet), target, - artifactsPath is null ? null : Path.GetFullPath(artifactsPath), selectedProjects: selected, sdkSnapshot: sdkSnapshot); + var references = new DocumentationProjectReferences( + root, + configuration, + Path.GetFullPath(dotnet), + target, + artifactsPath is null ? null : Path.GetFullPath(artifactsPath), + selectedProjects: selected, + sdkSnapshot: sdkSnapshot + ); var models = new DocumentationSourceModels(root, configuration, references, cancellationToken, failures); var inventory = new List(); using var cache = new DocumentationExportCache(root, cancellationToken); @@ -405,32 +563,58 @@ private static IReadOnlyList CaptureApi( cancellationToken.ThrowIfCancellationRequested(); string directory = Path.GetDirectoryName(project)!; if (models.IsExcludedProduct(directory)) + { throw new InvalidDataException("Selected API project is outside the requested product target: " + project); + } var compilation = models.GetCompilation(directory) - ?? throw new InvalidDataException("Selected API compilation is unavailable: " + project - + (failures.Count == 0 ? string.Empty : "\n" + string.Join('\n', failures))); + ?? throw new InvalidDataException( + "Selected API compilation is unavailable: " + project + + (failures.Count == 0 ? string.Empty : "\n" + string.Join('\n', failures)) + ); string owner = Path.GetRelativePath(root, project).Replace('\\', '/'); ApiProject Capture() { var symbols = DocumentationApiExtractor.Capture(root, project, null, compilation, failures, cancellationToken); if (failures.Count != 0) - throw new InvalidDataException("API extraction did not establish complete source facts:\n" + string.Join('\n', failures)); - return new(owner, Path.GetFileNameWithoutExtension(project), symbols, - DocumentationApiExtractor.ReadExports(compilation), compilation.AssemblyName!); + { + throw new InvalidDataException( + "API extraction did not establish complete source facts:\n" + string.Join('\n', failures) + ); + } + return new( + owner, + Path.GetFileNameWithoutExtension(project), + symbols, + DocumentationApiExtractor.ReadExports(compilation), + compilation.AssemblyName! + ); } // External XML includes need their own frozen dependency closure. Until resolved, // preserve the normal fresh extraction instead of reusing an incomplete input identity. bool externalXml = compilation.SyntaxTrees.Any(tree => tree.GetRoot(cancellationToken) - .DescendantNodes(descendIntoTrivia: true).Any(static node => node is - XmlEmptyElementSyntax { Name.LocalName.ValueText: "include" } - or XmlElementSyntax { StartTag.Name.LocalName.ValueText: "include" })); - inventory.Add(externalXml ? Capture() : cache.Capture(owner + "|" + configuration + "|" + target, - references.GetSourceInputIdentity(project, compilation, cancellationToken), Capture, cancellationToken)); + .DescendantNodes(descendIntoTrivia: true) + .Any(static node => ( + node is + XmlEmptyElementSyntax { Name.LocalName.ValueText: "include" } + or XmlElementSyntax { StartTag.Name.LocalName.ValueText: "include" } + ))); + inventory.Add( + externalXml ? Capture() : cache.Capture( + owner + "|" + configuration + "|" + target, + references.GetSourceInputIdentity(project, compilation, cancellationToken), + Capture, + cancellationToken + ) + ); if (externalXml) + { Console.WriteLine("API extraction performed fresh for external XML includes: " + owner); + } } if (failures.Count != 0) + { throw new InvalidDataException("API extraction did not establish complete source facts:\n" + string.Join('\n', failures)); + } cache.Report(); return inventory; } @@ -442,10 +626,15 @@ internal static string ComparableSymbol(JsonElement symbol) { // Source offsets and the retired Wiki page field do not change an API contract. if (property.Name is "line" or "page") + { continue; - ordered.Add(property.Name, property.Name == "documentation" + } + ordered.Add( + property.Name, + property.Name == "documentation" ? JsonValue.Create(property.Value.GetString()!.ReplaceLineEndings("\n")) - : JsonNode.Parse(property.Value.GetRawText())); + : JsonNode.Parse(property.Value.GetRawText()) + ); } return JsonSerializer.Serialize(ordered); } diff --git a/tools/Inno.Tooling.Architecture/DocumentationScriptApi.cs b/tools/Inno.Tooling.Architecture/DocumentationScriptApi.cs index 07a64cd4e..486186e69 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationScriptApi.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationScriptApi.cs @@ -8,10 +8,10 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; -using Inno.Core.IO; -using Inno.Tooling.Documentation; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using Inno.Core.IO; +using Inno.Tooling.Documentation; namespace Inno.Tooling.Architecture; @@ -27,51 +27,101 @@ CancellationToken cancellationToken { string key = arguments[index]; if (index + 1 == arguments.Length) + { throw new ArgumentException("Incomplete script API export option: " + key); + } string value = arguments[index + 1]; if (key == "--source-reference") { string source = Path.GetFullPath(value); if (!sources.TryAdd(source, File.ReadAllBytes(source))) + { throw new ArgumentException("Repeated source reference: " + source); + } } else if (key is not ("--engine-root" or "--dotnet" or "--surface" or "--runtime-reference" or "--editor-reference" - or "--output" or "--configuration" or "--target" or "--sdk-snapshot" or "--artifacts-path" or "--framework-project") || !options.TryAdd(key, value)) + or "--output" or "--configuration" or "--target" or "--sdk-snapshot" or "--artifacts-path" or "--framework-project") + || !options.TryAdd(key, value) + ) { throw new ArgumentException("Unknown or duplicate script API export option: " + key); + } } - foreach (string required in new[] { "--engine-root", "--dotnet", "--surface", "--runtime-reference", "--output", "--framework-project" }) + foreach (string required in new[] { + "--engine-root", + "--dotnet", + "--surface", + "--runtime-reference", + "--output", + "--framework-project" + }) { if (!options.ContainsKey(required)) + { throw new ArgumentException("Missing script API export option: " + required); + } + } if (sources.Count == 0) + { throw new ArgumentException("Script API origins require the actual source reference manifests."); + } string root = Path.GetFullPath(options["--engine-root"]); string configuration = options.GetValueOrDefault("--configuration", "Debug"); if (configuration is not ("Debug" or "SourceDebug" or "Release")) + { throw new ArgumentException("Unsupported script API extraction configuration."); + } var owners = new HashSet(StringComparer.Ordinal) { PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, options["--framework-project"])) }; - var sdk = new DocumentationProjectReferences(root, configuration, options["--dotnet"], selectedProjects: owners, + var sdk = new DocumentationProjectReferences( + root, + configuration, + options["--dotnet"], + selectedProjects: owners, artifactsPath: options.GetValueOrDefault("--artifacts-path"), - sdkSnapshot: options.TryGetValue("--sdk-snapshot", out string? graph) ? File.ReadAllText(graph) : null); - Capture capture = Read(options["--surface"], configuration, options["--runtime-reference"], - options.GetValueOrDefault("--editor-reference"), sdk.GetFrameworkReferences(cancellationToken), sources.Values, cancellationToken); + sdkSnapshot: options.TryGetValue("--sdk-snapshot", out string? graph) ? File.ReadAllText(graph) : null + ); + Capture capture = Read( + options["--surface"], + configuration, + options["--runtime-reference"], + options.GetValueOrDefault("--editor-reference"), + sdk.GetFrameworkReferences(cancellationToken), + sources.Values, + cancellationToken + ); capture = capture with { target = options.GetValueOrDefault("--target") }; var inventory = RepositorySourceInventory.Projects(root).ToHashSet(StringComparer.OrdinalIgnoreCase); foreach (Project project in capture.projects) + { if (!inventory.Contains(PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, project.project)))) + { throw new InvalidDataException("Projected owner is absent from the actual project inventory: " + project.project); + } + } foreach (var source in sources) + { if (!File.ReadAllBytes(source.Key).AsSpan().SequenceEqual(source.Value)) + { throw new IOException("Source reference changed during script API preparation: " + source.Key); + } + } string output = Path.GetFullPath(options["--output"]); if (sources.ContainsKey(output)) + { throw new ArgumentException("Script API output cannot replace its source reference."); + } cancellationToken.ThrowIfCancellationRequested(); - AtomicFile.WriteAllBytes(output, JsonSerializer.SerializeToUtf8Bytes(capture, - new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" })); - Console.WriteLine($"Exported {capture.projects.Sum(static project => project.symbols.Count)} actual {capture.model} declarations; source certification remains separate."); + AtomicFile.WriteAllBytes( + output, + JsonSerializer.SerializeToUtf8Bytes( + capture, + new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" } + ) + ); + Console.WriteLine( + $"Exported {capture.projects.Sum(static project => project.symbols.Count)} actual {capture.model} declarations; source certification remains separate." + ); return 0; } @@ -91,7 +141,10 @@ internal static Capture Read( "editor-script" => true, _ => throw new ArgumentException("Expected runtime-script or editor-script surface.") }; - var sourceTypes = new Dictionary>(StringComparer.Ordinal); + var sourceTypes = new Dictionary< + string, + List<(string path, string assembly, DocumentationApiExtractor.DocumentationApiEntry symbol)> + >(StringComparer.Ordinal); var sourceMembers = new Dictionary(StringComparer.Ordinal); var ambiguousMembers = new HashSet(StringComparer.Ordinal); var declaredScopes = new Dictionary(StringComparer.Ordinal); @@ -99,23 +152,31 @@ internal static Capture Read( { using JsonDocument source = JsonDocument.Parse(bytes); if (source.RootElement.GetProperty("model").GetString() != "source-clr") + { continue; + } foreach (JsonElement project in source.RootElement.GetProperty("projects").EnumerateArray()) { // Export declarations can live in a feature assembly that does not own the exported type. // Collect them before filtering projected owners; compilation context is not a scope. if (project.TryGetProperty("scriptExports", out JsonElement exports)) + { foreach (JsonElement export in exports.EnumerateArray()) { string key = export.GetProperty("assembly").GetString() + "\0" + export.GetProperty("type").GetString(); string scope = export.GetProperty("scope").GetString()!; if (scope is not ("Runtime" or "Editor" or "Authoring") - || declaredScopes.TryGetValue(key, out string? earlier) && earlier != scope) + || declaredScopes.TryGetValue(key, out string? earlier) && earlier != scope + ) { throw new InvalidDataException("Conflicting or invalid declared scripting scope: " + key); + } declaredScopes[key] = scope; } + } if (selectedOwners is not null && !selectedOwners.Contains(project.GetProperty("name").GetString()!)) + { continue; + } foreach (JsonElement element in project.GetProperty("symbols").EnumerateArray()) { var symbol = element.Deserialize()!; @@ -123,14 +184,22 @@ internal static Capture Read( string memberKey = path + "\0" + symbol.id; if (!sourceMembers.TryAdd(memberKey, symbol) && DocumentationReferences.ComparableSymbol(JsonSerializer.SerializeToElement(sourceMembers[memberKey])) - != DocumentationReferences.ComparableSymbol(element)) + != DocumentationReferences.ComparableSymbol(element) + ) { ambiguousMembers.Add(memberKey); + } if (!symbol.id.StartsWith("T:", StringComparison.Ordinal)) + { continue; + } if (!sourceTypes.TryGetValue(symbol.id, out var candidates)) + { sourceTypes.Add(symbol.id, candidates = []); + } if (!candidates.Any(prior => prior.path == path && prior.symbol.signature == symbol.signature)) + { candidates.Add((path, project.GetProperty("assembly").GetString()!, symbol)); + } } } } @@ -142,20 +211,34 @@ internal static Capture Read( using var xmlStream = new MemoryStream(xmlBytes, writable: false); XDocument document = XDocument.Load(xmlStream); XElement provenance = document.Root?.Element("provenance") - ?? throw new InvalidDataException("The script reference lacks compiler-produced origin metadata; prepare current logical references."); + ?? throw new InvalidDataException( + "The script reference lacks compiler-produced origin metadata; prepare current logical references." + ); if ((string?)provenance.Attribute("format") != "inno-script-documentation/2") + { throw new InvalidDataException("Unsupported script documentation provenance."); + } var origins = provenance.Elements("type").ToDictionary( - static origin => (string)origin.Attribute("id")!, static origin => (string)origin.Attribute("source")!, StringComparer.Ordinal); + static origin => (string)origin.Attribute("id")!, + static origin => (string)origin.Attribute("source")!, + StringComparer.Ordinal + ); var originAssemblies = provenance.Elements("type").ToDictionary( - static origin => (string)origin.Attribute("id")!, static origin => (string?)origin.Attribute("assembly") - ?? throw new InvalidDataException("A script projection origin requires its actual assembly."), StringComparer.Ordinal); + static origin => (string)origin.Attribute("id")!, + static origin => ( + (string?)origin.Attribute("assembly") + ?? throw new InvalidDataException("A script projection origin requires its actual assembly.") + ), + StringComparer.Ordinal + ); var mappings = new Dictionary(origins, StringComparer.Ordinal); if (editor) { XDocument runtimeDocument = XDocument.Load(Path.ChangeExtension(runtimePath, ".xml")); foreach (XElement origin in runtimeDocument.Root?.Element("provenance")?.Elements("type") ?? []) + { mappings.Add((string)origin.Attribute("id")!, (string)origin.Attribute("source")!); + } } var toSource = new Dictionary(StringComparer.Ordinal); foreach (var mapping in mappings) @@ -166,82 +249,147 @@ internal static Capture Read( string name = mapping.Key[2..].Split('`')[0]; string original = mapping.Value[2..].Split('`')[0]; if (toSource.TryGetValue(name, out string? prior) && prior != original) + { throw new InvalidDataException("Ambiguous constructed generic script identity: " + name); + } toSource[name] = original; } } var toLogical = toSource.GroupBy(static pair => pair.Value, StringComparer.Ordinal) - .Where(static group => group.Count() == 1).ToDictionary(static group => group.Key, static group => group.Single().Key, StringComparer.Ordinal); + .Where(static group => group.Count() == 1) + .ToDictionary(static group => group.Key, static group => group.Single().Key, StringComparer.Ordinal); Regex reverseNames = IdentityPattern(toSource.Keys); Regex forwardNames = IdentityPattern(toLogical.Keys); var selected = (PortableExecutableReference)references[editor ? 1 : 0]; selected = ((AssemblyMetadata)selected.GetMetadata()).GetReference( - documentation: new AssemblyDocumentationProvider(xmlPath, xmlBytes), filePath: selectedPath); - var compilation = CSharpCompilation.Create("DocumentationScriptReference", + documentation: new AssemblyDocumentationProvider(xmlPath, xmlBytes), + filePath: selectedPath + ); + var compilation = CSharpCompilation.Create( + "DocumentationScriptReference", references: frameworkReferences.Concat(references.Where(reference => reference != references[editor ? 1 : 0])).Append(selected), - options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable, - metadataImportOptions: MetadataImportOptions.Public)); + options: new CSharpCompilationOptions( + OutputKind.DynamicallyLinkedLibrary, + nullableContextOptions: NullableContextOptions.Enable, + metadataImportOptions: MetadataImportOptions.Public + ) + ); var assembly = (IAssemblySymbol?)compilation.GetAssemblyOrModuleSymbol(selected) - ?? throw new InvalidDataException("The selected logical script assembly cannot be read."); + ?? throw new InvalidDataException("The selected logical script assembly cannot be read."); var paths = new Dictionary(StringComparer.Ordinal); - IReadOnlyList symbols = DocumentationApiExtractor.CaptureReference(assembly, Resolve, cancellationToken); + IReadOnlyList symbols = DocumentationApiExtractor.CaptureReference( + assembly, + Resolve, + cancellationToken + ); if (symbols.Count == 0) + { throw new InvalidDataException("Required projected declaration discovery is empty."); + } if (!File.ReadAllBytes(xmlPath).AsSpan().SequenceEqual(xmlBytes)) + { throw new IOException("Script documentation changed during capture."); + } Project[] projects = symbols.GroupBy(static symbol => symbol.project, StringComparer.Ordinal) .OrderBy(static group => group.Key, StringComparer.Ordinal) - .Select(group => new Project(paths[group.Key], group.Key, group.OrderBy(static symbol => symbol.id, StringComparer.Ordinal).ToArray())).ToArray(); - return new(surface, configuration, null, "Unverified", scripts.GetIdentities(editor), - Convert.ToHexStringLower(SHA256.HashData(xmlBytes)), projects); + .Select( + group => new Project( + paths[group.Key], + group.Key, + group.OrderBy(static symbol => symbol.id, StringComparer.Ordinal).ToArray() + ) + ) + .ToArray(); + return new( + surface, + configuration, + null, + "Unverified", + scripts.GetIdentities(editor), + Convert.ToHexStringLower(SHA256.HashData(xmlBytes)), + projects + ); DocumentationApiExtractor.DocumentationApiEntry Resolve(ISymbol symbol) { INamedTypeSymbol type = symbol as INamedTypeSymbol ?? symbol.ContainingType; string id = type.GetDocumentationCommentId()!; if (!origins.TryGetValue(id, out string? original) || !sourceTypes.TryGetValue(original, out var allCandidates)) + { throw new InvalidDataException("Projected type has no unambiguous compiler origin and captured engine owner: " + id); + } var candidates = allCandidates.Where(candidate => candidate.assembly == originAssemblies[id]).ToArray(); - if (candidates.Length != 1) throw new InvalidDataException("Projected type origin does not resolve to one captured assembly: " + id); + if (candidates.Length != 1) + { + throw new InvalidDataException("Projected type origin does not resolve to one captured assembly: " + id); + } var origin = candidates[0]; if (!declaredScopes.TryGetValue(origin.assembly + "\0" + original, out string? scope)) + { throw new InvalidDataException("Projected type lacks its actual export scope declaration: " + id); + } if (paths.TryGetValue(origin.symbol.project, out string? path) && path != origin.path) + { throw new InvalidDataException("A projected owner has inconsistent source paths."); + } paths[origin.symbol.project] = origin.path; string originalId = reverseNames.Replace(symbol.GetDocumentationCommentId()!, match => toSource[match.Value]); if (ambiguousMembers.Contains(origin.path + "\0" + originalId)) + { throw new InvalidDataException("Projected member has conflicting captured source contracts: " + originalId); + } if (!sourceMembers.TryGetValue(origin.path + "\0" + originalId, out var member)) { if (symbol is IMethodSymbol { MethodKind: MethodKind.Constructor, Parameters.Length: 0, ContainingType.IsValueType: true }) + { return origin.symbol with { documentation = string.Empty, implicitDeclaration = true, scriptingScope = scope }; + } if (symbol is IMethodSymbol { MethodKind: MethodKind.Constructor, Parameters.Length: 0 }) + { return origin.symbol with { - documentation = new XElement("member", new XAttribute("name", symbol.GetDocumentationCommentId()!), - new XElement("summary", "Appears in the generated script reference without a matching public or protected engine constructor."), - new XElement("remarks", "This is an IDE projection artifact, not a supported construction path. Do not call this constructor from scripts; obtain the instance through the containing type's documented owner or factory.")).ToString(SaveOptions.DisableFormatting), - implicitDeclaration = true, projectionOnly = true, scriptingScope = scope + documentation = new XElement( + "member", + new XAttribute("name", symbol.GetDocumentationCommentId()!), + new XElement( + "summary", + "Appears in the generated script reference without a matching public or protected engine constructor." + ), + new XElement( + "remarks", + "This is an IDE projection artifact, not a supported construction path. Do not call this constructor from scripts; obtain the instance through the containing type's documented owner or factory." + ) + ).ToString(SaveOptions.DisableFormatting), + implicitDeclaration = true, + projectionOnly = true, + scriptingScope = scope }; - throw new InvalidDataException("Projected member has no exact captured source declaration: " + symbol.GetDocumentationCommentId()); + } + throw new InvalidDataException( + "Projected member has no exact captured source declaration: " + symbol.GetDocumentationCommentId() + ); } string xml = member.documentation; if (!string.IsNullOrWhiteSpace(xml)) { XElement contract = XElement.Parse(xml); - foreach (XAttribute attribute in contract.DescendantsAndSelf().Attributes() - .Where(static attribute => attribute.Name.LocalName is "name" or "cref")) + foreach (XAttribute attribute in contract.DescendantsAndSelf() + .Attributes() + .Where(static attribute => attribute.Name.LocalName is "name" or "cref") + ) { attribute.Value = forwardNames.Replace(attribute.Value, match => toLogical[match.Value]); + } xml = contract.ToString(SaveOptions.DisableFormatting); } return member with { documentation = xml, scriptingScope = scope }; } } - private static Regex IdentityPattern(IEnumerable names) => new( - @"(? name.Length).Select(Regex.Escape)) + @")(?!\w)", - RegexOptions.CultureInvariant); + private static Regex IdentityPattern(IEnumerable names) + => new( + @"(? name.Length).Select(Regex.Escape)) + @")(?!\w)", + RegexOptions.CultureInvariant + ); internal static async Task> CompareAsync( DocumentationSnapshot snapshot, @@ -257,20 +405,29 @@ CancellationToken cancellationToken // A compile-only snapshot can contain no API facts. Its receipt has no projection // proof and cannot satisfy publication's separate API evidence requirements. if (!catalog.references.Any(reference => reference.model is "runtime-script" or "editor-script")) return []; - DocumentationReferenceInfo[] selected = catalog.references.Where(reference => reference.configuration == configuration - && (reference.target is null || reference.target == target)).Where(reference => - reference.model == "runtime-script" && (modes.Contains("runtime-script") || modes.Contains("editor-script")) - || reference.model == "editor-script" && modes.Contains("editor-script")).ToArray(); - if ((modes.Contains("runtime-script") || modes.Contains("editor-script")) && !selected.Any(reference => reference.model == "runtime-script") - || modes.Contains("editor-script") && !selected.Any(reference => reference.model == "editor-script")) + DocumentationReferenceInfo[] selected = catalog.references.Where(reference => ( + reference.configuration == configuration + && (reference.target is null || reference.target == target) + )).Where(reference => ( + reference.model == "runtime-script" && (modes.Contains("runtime-script") || modes.Contains("editor-script")) + || reference.model == "editor-script" && modes.Contains("editor-script") + )).ToArray(); + if ((modes.Contains("runtime-script") || modes.Contains("editor-script")) + && !selected.Any(reference => reference.model == "runtime-script") + || modes.Contains("editor-script") && !selected.Any(reference => reference.model == "editor-script") + ) { throw new InvalidDataException("Required script projection facts are absent for the selected configuration and target."); + } if (selected.Length == 0) return []; var sourceFacts = new List(); var requiredOwners = selected.SelectMany(static reference => reference.projects).ToHashSet(StringComparer.Ordinal); - foreach (DocumentationReferenceInfo source in catalog.references.Where(reference => reference.model == "source-clr" + foreach (DocumentationReferenceInfo source in catalog.references.Where(reference => ( + reference.model == "source-clr" && reference.configuration == configuration && (reference.target is null || reference.target == target) - && reference.projects.Any(requiredOwners.Contains))) + && reference.projects.Any(requiredOwners.Contains) + ))) { sourceFacts.Add(await snapshot.ReadReferenceAsync(source.path, cancellationToken).ConfigureAwait(false)); + } var results = new List(); foreach (DocumentationReferenceInfo reference in selected) { @@ -281,14 +438,27 @@ CancellationToken cancellationToken try { if (reference.configuration != configuration || reference.target is not null && reference.target != target) + { throw new InvalidDataException("The projected reference context differs from the selected script compiler context."); - Capture actual = Read(reference.model, configuration, runtimePath + } + Capture actual = Read( + reference.model, + configuration, + runtimePath ?? throw new InvalidDataException("The current logical Runtime reference is unavailable."), - editorPath, frameworkReferences(), sourceFacts, cancellationToken, reference.projects.ToHashSet(StringComparer.Ordinal)); + editorPath, + frameworkReferences(), + sourceFacts, + cancellationToken, + reference.projects.ToHashSet(StringComparer.Ordinal) + ); identities = actual.projectionIdentities; xmlIdentity = actual.documentationIdentity; - using JsonDocument expected = JsonDocument.Parse(await snapshot.ReadReferenceAsync(reference.path, cancellationToken).ConfigureAwait(false)); - var previous = expected.RootElement.GetProperty("projects").EnumerateArray() + using JsonDocument expected = JsonDocument.Parse( + await snapshot.ReadReferenceAsync(reference.path, cancellationToken).ConfigureAwait(false) + ); + var previous = expected.RootElement.GetProperty("projects") + .EnumerateArray() .ToDictionary(static project => project.GetProperty("name").GetString()!, StringComparer.Ordinal); foreach (Project project in actual.projects) { @@ -298,16 +468,23 @@ CancellationToken cancellationToken continue; } if (old.GetProperty("project").GetString() != project.project) + { differences.Add("Projected owner path changed: " + project.name); - var symbols = old.GetProperty("symbols").EnumerateArray() + } + var symbols = old.GetProperty("symbols") + .EnumerateArray() .ToDictionary(static symbol => symbol.GetProperty("id").GetString()!, StringComparer.Ordinal); foreach (DocumentationApiExtractor.DocumentationApiEntry symbol in project.symbols) { if (!symbols.Remove(symbol.id, out JsonElement previousSymbol)) + { differences.Add("Missing projected declaration: " + symbol.id); + } else if (DocumentationReferences.ComparableSymbol(previousSymbol) - != DocumentationReferences.ComparableSymbol(JsonSerializer.SerializeToElement(symbol))) + != DocumentationReferences.ComparableSymbol(JsonSerializer.SerializeToElement(symbol)) + ) { differences.Add("Projected declaration or contract changed: " + symbol.id); + } } differences.AddRange(symbols.Keys.Select(static id => "Declaration is no longer projected: " + id)); } @@ -319,8 +496,20 @@ CancellationToken cancellationToken status = "Blocked"; differences.Add(failure.Message); } - results.Add(new(reference.path, reference.identity, reference.model, configuration, reference.target, reference.projects, - status, identities, xmlIdentity, differences)); + results.Add( + new( + reference.path, + reference.identity, + reference.model, + configuration, + reference.target, + reference.projects, + status, + identities, + xmlIdentity, + differences + ) + ); } return results; } diff --git a/tools/Inno.Tooling.Architecture/DocumentationScriptReferences.cs b/tools/Inno.Tooling.Architecture/DocumentationScriptReferences.cs index 76e8ac55d..be27f7219 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationScriptReferences.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationScriptReferences.cs @@ -20,7 +20,9 @@ internal DocumentationScriptReferences( string? editorPath ) { if (editorPath is not null && runtimePath is null) + { throw new ArgumentException("The Editor script reference requires a Runtime script reference."); + } (m_runtime, m_runtimeIdentity) = Read(runtimePath, "Inno.ScriptApi.Runtime"); (m_editor, m_editorIdentity) = Read(editorPath, "Inno.ScriptApi.Editor"); } @@ -28,7 +30,11 @@ internal DocumentationScriptReferences( internal IReadOnlyList GetReferences(bool editor) { if (m_runtime is null || (editor && m_editor is null)) - throw new InvalidOperationException("Logical script examples require explicit current Inno.ScriptApi.Runtime references and, for Editor scripts, Inno.ScriptApi.Editor references."); + { + throw new InvalidOperationException( + "Logical script examples require explicit current Inno.ScriptApi.Runtime references and, for Editor scripts, Inno.ScriptApi.Editor references." + ); + } return editor ? [m_runtime, m_editor!] : [m_runtime]; } @@ -37,11 +43,16 @@ internal IReadOnlyDictionary GetIdentities(bool editor) var identities = new Dictionary(StringComparer.Ordinal) { ["Inno.ScriptApi.Runtime"] = m_runtimeIdentity - ?? throw new InvalidOperationException("The Runtime script reference is unavailable.") + ?? throw new InvalidOperationException("The Runtime script reference is unavailable.") }; if (editor) - identities.Add("Inno.ScriptApi.Editor", m_editorIdentity - ?? throw new InvalidOperationException("The Editor script reference is unavailable.")); + { + identities.Add( + "Inno.ScriptApi.Editor", + m_editorIdentity + ?? throw new InvalidOperationException("The Editor script reference is unavailable.") + ); + } return identities; } @@ -50,16 +61,22 @@ private static (MetadataReference? reference, string? identity) Read( string expectedName ) { if (path is null) + { return (null, null); + } string absolute = Path.GetFullPath(path); byte[] bytes = File.ReadAllBytes(absolute); using var stream = new MemoryStream(bytes, writable: false); using var pe = new PEReader(stream); if (!pe.HasMetadata) + { throw new InvalidDataException($"The script reference is not a managed assembly: {absolute}"); + } MetadataReader metadata = pe.GetMetadataReader(); if (!metadata.IsAssembly || metadata.GetString(metadata.GetAssemblyDefinition().Name) != expectedName) + { throw new InvalidDataException($"Expected the {expectedName} logical script reference: {absolute}"); + } // Compilation and evidence use the same frozen bytes, even if the source file changes later. return (MetadataReference.CreateFromImage(bytes, filePath: absolute), Convert.ToHexStringLower(SHA256.HashData(bytes))); diff --git a/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs b/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs index 4cc947191..c86de7b41 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs @@ -6,7 +6,6 @@ using System.Runtime.InteropServices; using System.Threading; using System.Xml.Linq; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -36,12 +35,12 @@ internal DocumentationSourceModels( m_cancellation = cancellationToken; m_failures = failures; string[] projects = new[] { "entry", "src", "backends", "platforms", "build", "tools", "tests" } - .SelectMany(folder => RepositorySourceInventory.Files( - Path.Combine(repositoryRoot, folder), "*.csproj")) + .SelectMany(folder => RepositorySourceInventory.Files(Path.Combine(repositoryRoot, folder), "*.csproj")) .Where(path => IsSourcePath(path) && !RepositorySourceInventory.IsDeclaredTestProject(path)) .ToArray(); m_projectNames = projects.Select(Path.GetFileNameWithoutExtension) - .OfType().ToHashSet(StringComparer.Ordinal); + .OfType() + .ToHashSet(StringComparer.Ordinal); if (m_projectReferences is not null) { m_references = []; @@ -50,53 +49,83 @@ internal DocumentationSourceModels( } var paths = new Dictionary(StringComparer.OrdinalIgnoreCase); string runtimeDirectory = RuntimeEnvironment.GetRuntimeDirectory().TrimEnd(Path.DirectorySeparatorChar); - string frameworkReferences = Path.GetFullPath(Path.Combine(runtimeDirectory, "..", "..", "..", - "packs", "Microsoft.NETCore.App.Ref", Path.GetFileName(runtimeDirectory), "ref", - "net" + Environment.Version.Major + ".0")); + string frameworkReferences = Path.GetFullPath( + Path.Combine( + runtimeDirectory, + "..", + "..", + "..", + "packs", + "Microsoft.NETCore.App.Ref", + Path.GetFileName(runtimeDirectory), + "ref", + "net" + Environment.Version.Major + ".0" + ) + ); StringComparison pathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; string[] platform = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? string.Empty) .Split(Path.PathSeparator); foreach (string path in platform.Where(File.Exists)) { if (Directory.Exists(frameworkReferences) && path.StartsWith(runtimeDirectory + Path.DirectorySeparatorChar, pathComparison)) + { continue; + } paths[Path.GetFileNameWithoutExtension(path)] = path; } if (Directory.Exists(frameworkReferences)) + { foreach (string reference in Directory.EnumerateFiles(frameworkReferences, "*.dll")) + { paths[Path.GetFileNameWithoutExtension(reference)] = reference; - m_frameworkReferences = paths.Values.Where(path => + } + } + m_frameworkReferences = paths.Values + .Where(path => ( path.StartsWith(frameworkReferences + Path.DirectorySeparatorChar, pathComparison) - || path.StartsWith(runtimeDirectory + Path.DirectorySeparatorChar, pathComparison)) - .Select(static path => (MetadataReference)MetadataReference.CreateFromFile(path)).ToArray(); + || path.StartsWith(runtimeDirectory + Path.DirectorySeparatorChar, pathComparison) + )) + .Select(static path => (MetadataReference)MetadataReference.CreateFromFile(path)) + .ToArray(); var projectOutputs = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string project in projects) { XDocument document = XDocument.Load(project); string framework = document.Descendants("TargetFramework").FirstOrDefault()?.Value ?? "net10.0"; string? target = document.Descendants("InnoProductTarget").FirstOrDefault()?.Value; - string directory = Path.Combine(Path.GetDirectoryName(project)!, + string directory = Path.Combine( + Path.GetDirectoryName(project)!, target is null ? "bin" : Path.Combine("bin", target), - configuration, framework); + configuration, + framework + ); if (!Directory.Exists(directory)) + { continue; + } string assemblyName = document.Descendants("AssemblyName").FirstOrDefault()?.Value - ?? Path.GetFileNameWithoutExtension(project); + ?? Path.GetFileNameWithoutExtension(project); string projectOutput = Path.Combine(directory, assemblyName + ".dll"); if (File.Exists(projectOutput)) + { projectOutputs[assemblyName] = projectOutput; + } foreach (string path in Directory.EnumerateFiles(directory, "*.dll").Where(IsManagedAssembly)) + { paths.TryAdd(Path.GetFileNameWithoutExtension(path), path); + } } // A consumer's copied dependency must not replace the owning project's contract snapshot. foreach (KeyValuePair output in projectOutputs) + { paths[output.Key] = output.Value; + } m_references = paths.Values.Select(static path => { string documentationPath = Path.ChangeExtension(path, ".xml"); DocumentationProvider? documentation = File.Exists(documentationPath) - ? new AssemblyDocumentationProvider(documentationPath) - : null; + ? new AssemblyDocumentationProvider(documentationPath) + : null; return (MetadataReference)MetadataReference.CreateFromFile(path, documentation: documentation); }).ToArray(); } @@ -108,27 +137,34 @@ internal DocumentationSourceModels( internal bool IsExcludedProduct(string projectDirectory) => m_projectReferences?.IsExcludedProduct(Directory.EnumerateFiles(projectDirectory, "*.csproj").Single()) == true; - internal IReadOnlyList frameworkReferences => m_projectReferences is null - ? m_frameworkReferences - : m_projectReferences.GetFrameworkReferences(m_cancellation); + internal IReadOnlyList frameworkReferences + => m_projectReferences is null + ? m_frameworkReferences + : m_projectReferences.GetFrameworkReferences(m_cancellation); internal SemanticModel? GetModel(string path) { string? projectDirectory = FindProjectDirectory(path); if (projectDirectory is null) + { return null; + } CSharpCompilation? compilation = GetCompilation(projectDirectory); return compilation is not null && m_trees.TryGetValue(Path.GetFullPath(path), out SyntaxTree? tree) - ? compilation.GetSemanticModel(tree) - : null; + ? compilation.GetSemanticModel(tree) + : null; } internal CSharpCompilation? GetCompilation(string projectDirectory) { if (IsExcludedProduct(projectDirectory)) + { return null; + } if (m_unavailableProjects.Contains(projectDirectory)) + { return null; + } if (!string.Equals(projectDirectory, m_projectDirectory, StringComparison.OrdinalIgnoreCase)) { m_projectDirectory = projectDirectory; @@ -139,7 +175,9 @@ internal bool IsExcludedProduct(string projectDirectory) try { m_compilation = m_projectReferences.GetSourceCompilation( - Directory.EnumerateFiles(projectDirectory, "*.csproj").Single(), m_cancellation); + Directory.EnumerateFiles(projectDirectory, "*.csproj").Single(), + m_cancellation + ); } catch (FileNotFoundException failure) when (m_failures is not null) { @@ -147,21 +185,30 @@ internal bool IsExcludedProduct(string projectDirectory) m_failures.Add(failure.Message); return null; } - m_trees = m_compilation.SyntaxTrees.ToDictionary(static tree => Path.GetFullPath(tree.FilePath), - StringComparer.OrdinalIgnoreCase); + m_trees = m_compilation.SyntaxTrees.ToDictionary( + static tree => Path.GetFullPath(tree.FilePath), + StringComparer.OrdinalIgnoreCase + ); return m_compilation; } m_trees = RepositorySourceInventory.Files(projectDirectory, "*.cs") .Where(IsSourcePath) - .ToDictionary(static value => Path.GetFullPath(value), static value => - (SyntaxTree)CSharpSyntaxTree.ParseText(File.ReadAllText(value), - new CSharpParseOptions(LanguageVersion.CSharp14), path: value), - StringComparer.OrdinalIgnoreCase); + .ToDictionary( + static value => Path.GetFullPath(value), + static value => + (SyntaxTree)CSharpSyntaxTree.ParseText( + File.ReadAllText(value), + new CSharpParseOptions(LanguageVersion.CSharp14), + path: value + ), + StringComparer.OrdinalIgnoreCase + ); m_compilation = CSharpCompilation.Create( Path.GetFileNameWithoutExtension(Directory.EnumerateFiles(projectDirectory, "*.csproj").Single()), m_trees.Values, GetReferences(projectDirectory), - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true)); + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true) + ); } return m_compilation; } @@ -170,14 +217,15 @@ private IEnumerable GetReferences(string projectDirectory) { var references = m_references.ToDictionary( static reference => Path.GetFileNameWithoutExtension(reference.Display)!, - StringComparer.OrdinalIgnoreCase); + StringComparer.OrdinalIgnoreCase + ); // Compile-only package contracts are intentionally absent from runtime deployment outputs. foreach (string path in DocumentationPackageReferences.Read(projectDirectory)) { string documentationPath = Path.ChangeExtension(path, ".xml"); DocumentationProvider? documentation = File.Exists(documentationPath) - ? new AssemblyDocumentationProvider(documentationPath) - : null; + ? new AssemblyDocumentationProvider(documentationPath) + : null; references[Path.GetFileNameWithoutExtension(path)] = MetadataReference.CreateFromFile(path, documentation: documentation); } return references.Values; @@ -189,7 +237,9 @@ private IEnumerable GetReferences(string projectDirectory) while (directory is not null) { if (Directory.EnumerateFiles(directory.FullName, "*.csproj").Any()) + { return directory.FullName; + } directory = directory.Parent; } return null; diff --git a/tools/Inno.Tooling.Architecture/EditorPresentationSourceValidator.cs b/tools/Inno.Tooling.Architecture/EditorPresentationSourceValidator.cs index 7c92df433..02477b768 100644 --- a/tools/Inno.Tooling.Architecture/EditorPresentationSourceValidator.cs +++ b/tools/Inno.Tooling.Architecture/EditorPresentationSourceValidator.cs @@ -16,36 +16,57 @@ internal static void Validate( ICollection failures ) { if (!relativePath.StartsWith("src/composition/editor/", StringComparison.Ordinal)) + { return; + } SyntaxNode root = tree.GetRoot(); - UsingDirectiveSyntax[] aliases = root.DescendantNodes().OfType() - .Where(static directive => directive.Alias is not null && directive.Name is not null).ToArray(); + UsingDirectiveSyntax[] aliases = root.DescendantNodes() + .OfType() + .Where(static directive => directive.Alias is not null && directive.Name is not null) + .ToArray(); foreach (IGrouping group in aliases.GroupBy( - static directive => directive.Name!.ToString(), StringComparer.Ordinal)) - { + static directive => directive.Name!.ToString(), + StringComparer.Ordinal + )) { if (group.Count() > 1) + { Report(relativePath, tree, group.First(), "one type cannot have multiple presentation aliases in the same file", failures); + } } var facadeAliases = aliases.Where(static directive => directive.Name!.ToString() == C_FACADE) - .Select(static directive => directive.Alias!.Name.Identifier.ValueText).ToHashSet(StringComparer.Ordinal); + .Select(static directive => directive.Alias!.Name.Identifier.ValueText) + .ToHashSet(StringComparer.Ordinal); facadeAliases.Add(C_FACADE); facadeAliases.Add("global::" + C_FACADE); foreach (BlockSyntax block in root.DescendantNodes().OfType()) { - if (block.Parent is not (ForStatementSyntax or ForEachStatementSyntax or ForEachVariableStatementSyntax or WhileStatementSyntax or DoStatementSyntax)) + if (block.Parent is not (ForStatementSyntax + or ForEachStatementSyntax + or ForEachVariableStatementSyntax + or WhileStatementSyntax + or DoStatementSyntax) + ) { continue; + } ExpressionStatementSyntax[] statements = block.Statements.OfType().ToArray(); foreach (ExpressionStatementSyntax push in statements.Where(statement => IsFacadeCall(statement, "PushId", facadeAliases))) { if (statements.Any(statement => statement.SpanStart > push.SpanStart && IsFacadeCall(statement, "PopId", facadeAliases))) + { Report(relativePath, tree, push, "presentation loop ID scopes require local try/finally cleanup", failures); + } } } foreach (DocumentationCommentTriviaSyntax comment in root.DescendantTrivia() - .Select(static trivia => trivia.GetStructure()).OfType()) - { - if (comment.Content.OfType().Count(static element => element.StartTag.Name.LocalName.ValueText == "summary") > 1) + .Select(static trivia => trivia.GetStructure()) + .OfType() + ) { + if (comment.Content + .OfType() + .Count(static element => element.StartTag.Name.LocalName.ValueText == "summary") > 1 + ) { Report(relativePath, tree, comment, "a declaration cannot retain multiple XML summary elements", failures); + } } } @@ -54,7 +75,7 @@ private static bool IsFacadeCall( string method, IReadOnlySet receivers ) => statement.Expression is InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax member } - && member.Name.Identifier.ValueText == method && receivers.Contains(member.Expression.ToString()); + && member.Name.Identifier.ValueText == method && receivers.Contains(member.Expression.ToString()); private static void Report( string relativePath, diff --git a/tools/Inno.Tooling.Architecture/EditorUiBoundaryValidator.cs b/tools/Inno.Tooling.Architecture/EditorUiBoundaryValidator.cs index bd8ac4808..f01885647 100644 --- a/tools/Inno.Tooling.Architecture/EditorUiBoundaryValidator.cs +++ b/tools/Inno.Tooling.Architecture/EditorUiBoundaryValidator.cs @@ -6,6 +6,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Inno.Tooling.Architecture; + internal static class EditorUiBoundaryValidator { internal static void Validate( @@ -16,7 +17,9 @@ ICollection failures var projects = new List(RepositorySourceInventory.Files(editorRoot, "*.csproj")); string sdkHost = Path.Combine(repositoryRoot, "build/cli/Inno.Build.Cli/Inno.Build.Cli.csproj"); if (File.Exists(sdkHost)) + { projects.Add(sdkHost); + } foreach (string path in projects) { string name = Path.GetFileNameWithoutExtension(path); @@ -27,41 +30,42 @@ ICollection failures { string dependency = Path.GetFileNameWithoutExtension(((string? )reference.Attribute("Include") ?? "").Replace('\\', '/')); if (feature - && (dependency.Contains( - "ImGui", - StringComparison.Ordinal - ) - || dependency.StartsWith( - "Inno.Native.", - StringComparison.Ordinal - ) - || dependency.StartsWith( - "Inno.Editor.Panel.", - StringComparison.Ordinal - ) - || dependency is "Inno.Editor.Workbench" or "Inno.Editor.Hosting")) + && (dependency.Contains("ImGui", StringComparison.Ordinal) + || dependency.StartsWith("Inno.Native.", StringComparison.Ordinal) + || dependency.StartsWith("Inno.Editor.Panel.", StringComparison.Ordinal) + || dependency is "Inno.Editor.Workbench" or "Inno.Editor.Hosting") + ) { failures.Add($"{relative}: Editor feature editing must be presentation-independent; remove {dependency}."); + } if (panel && dependency.StartsWith("Inno.Editor.Panel.", StringComparison.Ordinal)) - failures.Add($"{relative}: Panels cannot depend on other Panels; move shared behavior to its feature owner ({dependency})."); + { + failures.Add( + $"{relative}: Panels cannot depend on other Panels; move shared behavior to its feature owner ({dependency})." + ); + } if (name == "Inno.Build.Cli" && dependency.StartsWith("Inno.Editor.Panel.", StringComparison.Ordinal)) { string include = (string?)reference.Attribute("Include") ?? string.Empty; string referencedProject = Path.GetFullPath(include.Replace('\\', '/'), Path.GetDirectoryName(path)!); if (!DeclaresScriptingApi(referencedProject)) - failures.Add($"{relative}: the script SDK host must reference API owners instead of transitive Panel carriers ({dependency})."); + { + failures.Add( + $"{relative}: the script SDK host must reference API owners instead of transitive Panel carriers ({dependency})." + ); + } } - if (name != "Inno.Editor.ImGui" && name != "Inno.Editor.Hosting" && dependency.StartsWith("Inno.Native.", StringComparison.Ordinal)) + if (name != "Inno.Editor.ImGui" + && name != "Inno.Editor.Hosting" + && dependency.StartsWith("Inno.Native.", StringComparison.Ordinal) + ) { failures.Add($"{relative}: native UI access belongs to the Editor ImGui adapter, not {name}."); + } if (name is "Inno.Editor.Graph" or "Inno.Editor.Graph.ImGui" - && (dependency.Contains( - "Shader", - StringComparison.Ordinal - ) - || dependency.Contains( - "Rendering", - StringComparison.Ordinal - ))) + && (dependency.Contains("Shader", StringComparison.Ordinal) + || dependency.Contains("Rendering", StringComparison.Ordinal)) + ) { failures.Add($"{relative}: reusable Graph mechanisms cannot depend on Shader or Rendering semantics."); + } } } } @@ -70,7 +74,9 @@ private static bool DeclaresScriptingApi(string project) { string manifest = Path.Combine(Path.GetDirectoryName(project)!, "Properties/ScriptingApi.cs"); if (!File.Exists(manifest)) + { return false; + } var syntax = CSharpSyntaxTree.ParseText( File.ReadAllText(manifest), new CSharpParseOptions(LanguageVersion.CSharp14) @@ -78,10 +84,16 @@ private static bool DeclaresScriptingApi(string project) foreach (AttributeListSyntax list in syntax.AttributeLists) { if (list.Target?.Identifier.ValueText != "assembly") + { continue; + } foreach (AttributeSyntax attribute in list.Attributes) + { if (attribute.Name.GetLastToken().ValueText is "ScriptingApiExport" or "ScriptingApiExportAttribute") + { return true; + } + } } return false; } diff --git a/tools/Inno.Tooling.Architecture/GenerationCleanupValidator.cs b/tools/Inno.Tooling.Architecture/GenerationCleanupValidator.cs index 0f5fdde16..53811ed4a 100644 --- a/tools/Inno.Tooling.Architecture/GenerationCleanupValidator.cs +++ b/tools/Inno.Tooling.Architecture/GenerationCleanupValidator.cs @@ -20,23 +20,28 @@ ICollection failures if (type is "RetirementPendingException" or "RetirementTimeoutException") { int line = clause.GetLocation().GetLineSpan().StartLinePosition.Line + 1; - failures.Add($"{relative}:{line}: retirement catches must classify the full exception tree with RetirementPendingException.Find; direct typed catches bypass wrapped pending ownership."); + failures.Add( + $"{relative}:{line}: retirement catches must classify the full exception tree with RetirementPendingException.Find; direct typed catches bypass wrapped pending ownership." + ); } } foreach (InvocationExpressionSyntax invocation in root - .DescendantNodes().OfType()) - { + .DescendantNodes() + .OfType() + ) { string? name = invocation.Expression switch { IdentifierNameSyntax identifier => identifier.Identifier.ValueText, MemberAccessExpressionSyntax member => member.Name.Identifier.ValueText, _ => null }; - if (name == "OnCleanupFailed" && - !relative.EndsWith("/Inno.Extensibility.Types/TypeRegistry.cs", StringComparison.Ordinal)) - { + if (name == "OnCleanupFailed" + && !relative.EndsWith("/Inno.Extensibility.Types/TypeRegistry.cs", StringComparison.Ordinal) + ) { int line = invocation.GetLocation().GetLineSpan().StartLinePosition.Line + 1; - failures.Add($"{relative}:{line}: cleanup failures must propagate through registry retirement; a diagnostic-only OnCleanupFailed call bypasses the generation fault barrier."); + failures.Add( + $"{relative}:{line}: cleanup failures must propagate through registry retirement; a diagnostic-only OnCleanupFailed call bypasses the generation fault barrier." + ); } } } diff --git a/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs b/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs index 31766374b..adf05809f 100644 --- a/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs +++ b/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs @@ -1,11 +1,11 @@ using System; -using Inno.Build.Toolchains; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Inno.Build.Toolchains; namespace Inno.Tooling.Architecture; @@ -28,10 +28,13 @@ internal static async Task> ValidateAsync( IReadOnlySet? selectedOwners = null ) { if (!Path.IsPathFullyQualified(dotnetHost) || !File.Exists(dotnetHost)) + { throw new ArgumentException("Architecture SDK evaluation requires an existing absolute dotnet executable.", nameof(dotnetHost)); + } string[] projects = RepositorySourceInventory.Projects(root) .Where(project => selectedOwners is null || selectedOwners.Contains(Relative(root, project))) - .Order(StringComparer.Ordinal).ToArray(); + .Order(StringComparer.Ordinal) + .ToArray(); var evaluated = new List(); var properties = new Dictionary(StringComparer.OrdinalIgnoreCase) { @@ -41,21 +44,34 @@ internal static async Task> ValidateAsync( ["InnoProductRestore"] = "false" }; if (artifactsPath is not null) + { properties.Add("ArtifactsPath", artifactsPath); - string graph = capturedGraph ?? await ManagedProjectGraphCapture.CaptureAsync(root, dotnetHost, projects, properties, cancellationToken).ConfigureAwait(false); + } + string graph = capturedGraph + ?? await ManagedProjectGraphCapture.CaptureAsync( + root, + dotnetHost, + projects, + properties, + cancellationToken + ).ConfigureAwait(false); using JsonDocument snapshots = JsonDocument.Parse(graph); foreach (JsonElement snapshot in snapshots.RootElement.EnumerateArray()) { cancellationToken.ThrowIfCancellationRequested(); EvaluatedProject project = ReadSnapshot(root, snapshot); if (selectedOwners is not null && !selectedOwners.Contains(project.path)) + { continue; + } ValidateProject(root, project, failures); if (snapshot.TryGetProperty("Variants", out JsonElement variants)) { EvaluatedProject[] effective = variants.EnumerateArray().Select(variant => ReadSnapshot(root, variant)).ToArray(); foreach (EvaluatedProject variant in effective) + { ValidateProject(root, variant, failures); + } project = project with { references = effective.SelectMany(static variant => variant.references).Concat(project.references).Distinct().ToArray(), @@ -64,20 +80,29 @@ internal static async Task> ValidateAsync( } evaluated.Add(project); } - if (!projects.Select(project => Relative(root, project)).Order(StringComparer.Ordinal) - .SequenceEqual(evaluated.Select(static project => project.path).Order(StringComparer.Ordinal))) + if (!projects.Select(project => Relative(root, project)) + .Order(StringComparer.Ordinal) + .SequenceEqual(evaluated.Select(static project => project.path).Order(StringComparer.Ordinal)) + ) { throw new InvalidDataException("The SDK snapshot does not cover the exact current project inventory."); + } ValidateGraph(evaluated, failures); if (outputPath is not null) { string destination = Path.GetFullPath(outputPath); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); - await File.WriteAllTextAsync(destination, JsonSerializer.Serialize(evaluated, - new JsonSerializerOptions { WriteIndented = true }), cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync( + destination, + JsonSerializer.Serialize(evaluated, new JsonSerializerOptions { WriteIndented = true }), + cancellationToken + ).ConfigureAwait(false); } Console.WriteLine($"Evaluated MSBuild ownership for {evaluated.Count}/{projects.Length} projects without executing build targets."); - return evaluated.ToDictionary(project => Path.GetFullPath(project.path, root), - static project => project.targetPath, StringComparer.OrdinalIgnoreCase); + return evaluated.ToDictionary( + project => Path.GetFullPath(project.path, root), + static project => project.targetPath, + StringComparer.OrdinalIgnoreCase + ); } private static EvaluatedProject ReadSnapshot( @@ -87,22 +112,40 @@ JsonElement snapshot string project = snapshot.GetProperty("Path").GetString()!; JsonElement properties = snapshot.GetProperty("Properties"); JsonElement items = snapshot.GetProperty("Items"); - EvaluatedReference[] references = items.GetProperty("ProjectReference").EnumerateArray() - .Select(item => new EvaluatedReference(Relative(root, item.GetProperty("FullPath").GetString()!), + EvaluatedReference[] references = items.GetProperty("ProjectReference") + .EnumerateArray() + .Select(item => new EvaluatedReference( + Relative(root, item.GetProperty("FullPath").GetString()!), !string.Equals(Value(item, "ReferenceOutputAssembly"), "false", StringComparison.OrdinalIgnoreCase), - Value(item, "OutputItemType"))).ToArray(); - EvaluatedSource[] sources = items.GetProperty("Compile").EnumerateArray() - .Select(item => new EvaluatedSource(Relative(root, item.GetProperty("FullPath").GetString()!), - Value(item, "Link"))).ToArray(); - return new(Relative(root, project), Value(properties, "AssemblyName"), Value(properties, "OutputType"), - Value(properties, "InnoProductId"), Value(properties, "InnoProductTarget"), - Value(properties, "InnoNativeTarget"), Value(properties, "ImplicitUsings"), - items.GetProperty("Using").GetArrayLength(), references, sources, Value(properties, "TargetPath"), - Value(properties, "InnoValidationLayer"), Value(properties, "IsTestProject").Equals("true", StringComparison.OrdinalIgnoreCase), + Value(item, "OutputItemType") + )) + .ToArray(); + EvaluatedSource[] sources = items.GetProperty("Compile") + .EnumerateArray() + .Select(item => new EvaluatedSource( + Relative(root, item.GetProperty("FullPath").GetString()!), + Value(item, "Link") + )) + .ToArray(); + return new( + Relative(root, project), + Value(properties, "AssemblyName"), + Value(properties, "OutputType"), + Value(properties, "InnoProductId"), + Value(properties, "InnoProductTarget"), + Value(properties, "InnoNativeTarget"), + Value(properties, "ImplicitUsings"), + items.GetProperty("Using").GetArrayLength(), + references, + sources, + Value(properties, "TargetPath"), + Value(properties, "InnoValidationLayer"), + Value(properties, "IsTestProject").Equals("true", StringComparison.OrdinalIgnoreCase), Value(properties, "IsTestSupportProject").Equals("true", StringComparison.OrdinalIgnoreCase) - || items.TryGetProperty("PackageReference", out JsonElement packages) - && packages.EnumerateArray().Any(static item => RepositorySourceInventory.IsTestPackage(Value(item, "Identity"))), - Value(properties, "InnoTestNativeProduct").Length != 0 || Value(properties, "InnoProductId").Length != 0); + || items.TryGetProperty("PackageReference", out JsonElement packages) + && packages.EnumerateArray().Any(static item => RepositorySourceInventory.IsTestPackage(Value(item, "Identity"))), + Value(properties, "InnoTestNativeProduct").Length != 0 || Value(properties, "InnoProductId").Length != 0 + ); } private static void ValidateProject( @@ -112,39 +155,59 @@ ICollection failures ) { bool test = RepositorySourceInventory.IsTestPath(project.path); if ((project.isTest || project.testSupport) && !test) + { failures.Add($"{project.path}: effective test projects must belong to the root tests directory."); + } if (project.isTest && project.layer is not ("domain" or "contract" or "integration" or "native" or "product" or "performance")) + { failures.Add($"{project.path}: test execution layer must declare its actual execution requirements."); + } if (project.implicitUsings.Equals("enable", StringComparison.OrdinalIgnoreCase) || project.implicitUsings.Equals("true", StringComparison.OrdinalIgnoreCase) - || project.usingItems != 0) + || project.usingItems != 0 + ) { failures.Add($"{project.path}: effective compilation-wide using imports are forbidden."); + } if (!test && project.outputType == "Exe" && !ExecutableProducts.Contains(project.assemblyName)) + { failures.Add($"{project.path}: effective production executable is not an approved product."); + } if (project.path.StartsWith("platforms/", StringComparison.Ordinal) && project.outputType == "Exe" - && (project.productId.Length == 0 || project.target.Length == 0 || project.nativeTarget != project.target)) + && (project.productId.Length == 0 || project.target.Length == 0 || project.nativeTarget != project.target) + ) { failures.Add($"{project.path}: effective product target and native ABI must be explicitly assigned and equal."); + } foreach (EvaluatedReference reference in project.references) { if (!File.Exists(Path.GetFullPath(reference.path, root))) + { failures.Add($"{project.path}: effective project dependency is missing: {reference.path}."); + } if (!reference.runtime || reference.outputItemType == "Analyzer") + { continue; + } PlatformOwnershipValidator.ValidateDependency(project.path, reference.path, failures); if (project.assemblyName == "Inno.Rendering" - && !reference.path.StartsWith("src/foundation/", StringComparison.Ordinal)) + && !reference.path.StartsWith("src/foundation/", StringComparison.Ordinal) + ) { failures.Add($"{project.path}: effective Rendering Core dependencies must belong to Foundation: {reference.path}."); + } if (project.path.StartsWith("src/foundation/", StringComparison.Ordinal) - && !reference.path.StartsWith("src/foundation/", StringComparison.Ordinal)) + && !reference.path.StartsWith("src/foundation/", StringComparison.Ordinal) + ) { failures.Add($"{project.path}: effective Foundation dependency belongs to an upper layer: {reference.path}."); + } } foreach (EvaluatedSource source in project.sources) { bool generated = source.path.Contains("/Generated/", StringComparison.Ordinal) - || source.path.Contains("/obj/", StringComparison.Ordinal); + || source.path.Contains("/obj/", StringComparison.Ordinal); string owner = Path.GetDirectoryName(project.path)!.Replace('\\', '/') + "/"; if (!generated && (source.link.Length != 0 || !source.path.StartsWith(owner, StringComparison.Ordinal))) + { failures.Add($"{project.path}: effective hand-authored Compile source has a second owner: {source.path}."); + } } } @@ -156,9 +219,13 @@ ICollection failures // Reload fixtures intentionally compile distinct generations with the same assembly identity. foreach (IGrouping identity in projects .Where(static project => !RepositorySourceInventory.IsTestPath(project.path)) - .GroupBy(static project => project.assemblyName, StringComparer.Ordinal)) + .GroupBy(static project => project.assemblyName, StringComparer.Ordinal) + ) { if (identity.Count() != 1) + { failures.Add($"Effective assembly identity '{identity.Key}' has multiple project owners."); + } + } var visited = new HashSet(StringComparer.OrdinalIgnoreCase); var active = new HashSet(StringComparer.OrdinalIgnoreCase); void Visit(EvaluatedProject project) @@ -169,15 +236,24 @@ void Visit(EvaluatedProject project) return; } if (!visited.Add(project.path)) + { return; + } active.Add(project.path); - foreach (EvaluatedReference reference in project.references.Where(static reference => reference.runtime && reference.outputItemType != "Analyzer")) + foreach (EvaluatedReference reference in project.references.Where( + static reference => reference.runtime && reference.outputItemType != "Analyzer" + )) { if (graph.TryGetValue(reference.path, out EvaluatedProject? dependency)) + { Visit(dependency); + } + } active.Remove(project.path); } foreach (EvaluatedProject project in projects) + { Visit(project); + } foreach (EvaluatedProject domain in projects.Where(static project => project.isTest && project.layer == "domain")) { var pending = new Stack(); @@ -186,30 +262,50 @@ void Visit(EvaluatedProject project) while (pending.TryPop(out EvaluatedProject? current)) { if (!visited.Add(current.path)) + { continue; + } if (current.native) + { failures.Add($"{domain.path}: domain test build closure requires native preparation through {current.path}."); + } foreach (EvaluatedReference reference in current.references) + { if (graph.TryGetValue(reference.path, out EvaluatedProject? dependency)) + { pending.Push(dependency); + } else + { failures.Add($"{domain.path}: domain test build dependency has no evaluated owner: {reference.path}."); + } + } } } - foreach (EvaluatedProject player in projects.Where(static project => project.assemblyName.StartsWith("Inno.Player.", StringComparison.Ordinal))) - { + foreach (EvaluatedProject player in projects.Where( + static project => project.assemblyName.StartsWith("Inno.Player.", StringComparison.Ordinal) + )) { var pending = new Stack(); visited.Clear(); pending.Push(player); while (pending.TryPop(out EvaluatedProject? current)) { if (!visited.Add(current.path)) + { continue; + } if (ArchitectureRules.IsForbiddenPlayerDependency(current.assemblyName)) + { failures.Add($"{player.path}: effective Player closure includes forbidden authoring/build dependency {current.path}."); - foreach (EvaluatedReference reference in current.references.Where(static reference => reference.runtime && reference.outputItemType != "Analyzer")) + } + foreach (EvaluatedReference reference in current.references.Where( + static reference => reference.runtime && reference.outputItemType != "Analyzer" + )) { if (graph.TryGetValue(reference.path, out EvaluatedProject? dependency)) + { pending.Push(dependency); + } + } } } } diff --git a/tools/Inno.Tooling.Architecture/NativeBindingOwnershipValidator.cs b/tools/Inno.Tooling.Architecture/NativeBindingOwnershipValidator.cs index f122598bd..ed28a4373 100644 --- a/tools/Inno.Tooling.Architecture/NativeBindingOwnershipValidator.cs +++ b/tools/Inno.Tooling.Architecture/NativeBindingOwnershipValidator.cs @@ -18,12 +18,16 @@ ICollection failures foreach (string projectPath in projects) { if (!Path.GetFileName(projectPath).StartsWith("Inno.Native.", StringComparison.Ordinal)) + { continue; + } string bindings = Path.Combine(Path.GetDirectoryName(projectPath)!, "Bindings"); XDocument project = XDocument.Load(projectPath); bool generated = project.Descendants("BindGenGeneratedBindings").Any(static value => value.Value == "true"); if (!generated && !Directory.Exists(bindings)) + { continue; + } string relative = Path.GetRelativePath(repositoryRoot, projectPath).Replace('\\', '/'); string definition = Path.Combine(bindings, "bindings.props"); if (!File.Exists(definition)) @@ -31,40 +35,57 @@ ICollection failures failures.Add($"{relative}: generated bindings require the component's Bindings/bindings.props owner."); continue; } - if (project.Descendants("Import").Count(static import => - ((string?)import.Attribute("Project"))?.Replace('\\', '/') == "Bindings/bindings.props") != 1) + if (project.Descendants("Import").Count(static import => ( + ((string?)import.Attribute("Project"))?.Replace('\\', '/') == "Bindings/bindings.props" + )) != 1 + ) { failures.Add($"{relative}: the native project must import its binding definition exactly once."); + } try { XElement root = XDocument.Load(definition).Root - ?? throw new InvalidDataException("The binding definition is empty."); + ?? throw new InvalidDataException("The binding definition is empty."); if (root.Name != "Project" || root.HasAttributes) + { throw new InvalidDataException("The binding definition must contain declarative Project data."); + } Dictionary properties = new(StringComparer.Ordinal); foreach (XElement group in root.Elements()) { if (group.HasAttributes) + { throw new InvalidDataException("Binding definitions cannot evaluate conditions."); + } if (group.Name == "PropertyGroup") { foreach (XElement property in group.Elements()) { if (property.Name.LocalName is not ("InnoNativeComponentId" or "InnoBindingConfig") || property.HasAttributes || property.HasElements - || !properties.TryAdd(property.Name.LocalName, property.Value)) + || !properties.TryAdd(property.Name.LocalName, property.Value) + ) { throw new InvalidDataException("The binding definition has an unknown or repeated property."); + } } } else + { throw new InvalidDataException("Binding definitions cannot contain executable build logic."); + } } if (!properties.TryGetValue("InnoNativeComponentId", out string? componentId) - || string.IsNullOrWhiteSpace(componentId)) + || string.IsNullOrWhiteSpace(componentId) + ) { throw new InvalidDataException("A binding definition requires its component identity."); + } if (!components.TryAdd(componentId, relative)) + { failures.Add($"{relative}: binding component '{componentId}' already belongs to '{components[componentId]}'."); + } if (!properties.TryGetValue("InnoBindingConfig", out string? hostConfig)) + { throw new InvalidDataException("A binding definition requires its common Config input."); + } ValidateConfigPath(bindings, hostConfig); } catch (Exception failure) when (failure is InvalidDataException or XmlException) @@ -80,9 +101,13 @@ string path ) { if (string.IsNullOrWhiteSpace(path) || Path.IsPathFullyQualified(path) || path.IndexOfAny(['$', '@', ':']) >= 0 - || path.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..")) + || path.Replace('\\', '/').Split('/').Any(static part => part is "" or "." or "..") + ) { throw new InvalidDataException("Binding Config inputs must be literal relative children of their owner."); + } if (!File.Exists(Path.GetFullPath(path, bindings))) + { throw new InvalidDataException($"The declared binding Config input '{path}' is missing."); + } } } diff --git a/tools/Inno.Tooling.Architecture/NativePlatformPolicyValidator.cs b/tools/Inno.Tooling.Architecture/NativePlatformPolicyValidator.cs index e83d366e8..5e0469e5c 100644 --- a/tools/Inno.Tooling.Architecture/NativePlatformPolicyValidator.cs +++ b/tools/Inno.Tooling.Architecture/NativePlatformPolicyValidator.cs @@ -14,26 +14,44 @@ ICollection failures ) { string backends = Path.Combine(root, "backends"); if (!Directory.Exists(backends)) + { return; + } foreach (string definition in RepositorySourceInventory.Files(backends, "bindings.props")) { string bindings = Path.GetDirectoryName(definition)!; string relative = Path.GetRelativePath(root, bindings).Replace('\\', '/'); string common = Path.Combine(bindings, "bindgen.json"); if (!File.Exists(common)) + { continue; + } if (Directory.EnumerateFiles(bindings, "bindgen.*.json").Any()) + { failures.Add($"{relative}: platform binding presets belong to their platform integration."); + } try { using JsonDocument document = JsonDocument.Parse(File.ReadAllText(common)); foreach (string property in new[] { "targets", "extends", "sdk" }) + { if (document.RootElement.TryGetProperty(property, out _)) + { failures.Add($"{relative}/bindgen.json: target or SDK policy '{property}' belongs to a platform Profile."); + } + } if (document.RootElement.TryGetProperty("source", out JsonElement source)) + { foreach (string property in new[] { "systemIncludeDirectories", "cppSystemIncludeDirectories", "sysRoot", "compiler" }) + { if (source.TryGetProperty(property, out _)) - failures.Add($"{relative}/bindgen.json: SDK parser input '{property}' must be supplied by the platform provider."); + { + failures.Add( + $"{relative}/bindgen.json: SDK parser input '{property}' must be supplied by the platform provider." + ); + } + } + } } catch (JsonException failure) { diff --git a/tools/Inno.Tooling.Architecture/PackageDependencyBoundaryValidator.cs b/tools/Inno.Tooling.Architecture/PackageDependencyBoundaryValidator.cs index 6f761d288..ad7bfa40e 100644 --- a/tools/Inno.Tooling.Architecture/PackageDependencyBoundaryValidator.cs +++ b/tools/Inno.Tooling.Architecture/PackageDependencyBoundaryValidator.cs @@ -17,25 +17,34 @@ ICollection failures bool bindingProfile = project.StartsWith("platforms/", StringComparison.Ordinal) && project.Contains("/integrations/Inno.Integration.", StringComparison.Ordinal) && project.EndsWith(".Build.csproj", StringComparison.Ordinal) - && document.Descendants("ProjectReference").Any(static reference => - reference.Attribute("Include")?.Value.EndsWith("/Inno.Build.Bindings.csproj", StringComparison.Ordinal) == true); + && document.Descendants("ProjectReference").Any(static reference => ( + reference.Attribute("Include")?.Value.EndsWith("/Inno.Build.Bindings.csproj", StringComparison.Ordinal) == true + )); foreach (XElement package in document.Descendants("PackageReference")) { string? id = package.Attribute("Include")?.Value; if (id != "BGCS" && id?.StartsWith("BGCS.", StringComparison.Ordinal) != true) + { continue; + } if (id == "BGCS.Runtime") { if (!test && !project.StartsWith("backends/", StringComparison.Ordinal)) + { failures.Add($"{project}: the interop runtime dependency belongs to a backend boundary."); + } } else if (!test && !generator && !bindingProfile) + { failures.Add($"{project}: binding generator packages belong only to their build application or declared extension."); + } string version = package.Attribute("Version")?.Value - ?? package.Elements("Version").Select(static value => value.Value).SingleOrDefault() ?? string.Empty; + ?? package.Elements("Version").Select(static value => value.Value).SingleOrDefault() ?? string.Empty; if (version != "[$(InnoBgcsPackageVersion)]" - && !(version.StartsWith('[') && version.EndsWith(']') && !version.Contains(',') && !version.Contains('*'))) + && !(version.StartsWith('[') && version.EndsWith(']') && !version.Contains(',') && !version.Contains('*')) + ) { failures.Add($"{project}: BGCS packages require one exact published version, without floating or source fallback."); + } } } } diff --git a/tools/Inno.Tooling.Architecture/PlatformOwnershipValidator.cs b/tools/Inno.Tooling.Architecture/PlatformOwnershipValidator.cs index 47eb3cbb8..c8ba58de5 100644 --- a/tools/Inno.Tooling.Architecture/PlatformOwnershipValidator.cs +++ b/tools/Inno.Tooling.Architecture/PlatformOwnershipValidator.cs @@ -20,7 +20,9 @@ ICollection failures { string relative = Path.GetRelativePath(root, script).Replace('\\', '/'); if (!RepositorySourceInventory.IsTestPath(relative)) + { failures.Add($"{relative}: engine-owned test scripts must belong to the root tests directory."); + } } foreach (string path in projects.Keys) { @@ -28,30 +30,40 @@ ICollection failures XDocument project = XDocument.Load(path); if (!RepositorySourceInventory.IsTestPath(relative) && (RepositorySourceInventory.DeclaresTestSupport(project) - || Path.GetFileNameWithoutExtension(path).StartsWith("Inno.Testing.", StringComparison.Ordinal))) + || Path.GetFileNameWithoutExtension(path).StartsWith("Inno.Testing.", StringComparison.Ordinal)) + ) { failures.Add($"{relative}: engine-owned tests and test support must belong to the root tests directory."); + } ValidateEntryProject(relative, project, failures); bool product = project.Descendants("OutputType").Any(static item => item.Value == "Exe"); if (product && relative.StartsWith("platforms/", StringComparison.Ordinal) - && (!project.Descendants("InnoProductId").Any() || !project.Descendants("InnoProductTarget").Any())) + && (!project.Descendants("InnoProductId").Any() || !project.Descendants("InnoProductTarget").Any()) + ) { failures.Add($"{relative}: a platform product must declare its product and exact target before SDK evaluation."); + } foreach (XElement compile in project.Descendants("Compile").Where(static item => item.Attribute("Include") is not null)) { string include = compile.Attribute("Include")!.Value.Replace('\\', '/'); bool generated = include.Contains("Generated", StringComparison.Ordinal) - || include.Contains("$(BindGen", StringComparison.Ordinal); + || include.Contains("$(BindGen", StringComparison.Ordinal); if (!generated && (compile.Attribute("Link") is not null || include.StartsWith("../", StringComparison.Ordinal))) + { failures.Add($"{relative}: hand-authored implementation cannot have a second owner through Compile Link."); + } } foreach (XElement reference in project.Descendants("ProjectReference")) { string? include = reference.Attribute("Include")?.Value; if (include is null || include.Contains("$(", StringComparison.Ordinal)) + { continue; + } string target = Path.GetFullPath(include.Replace('\\', '/'), Path.GetDirectoryName(path)!); string dependency = Path.GetRelativePath(root, target).Replace('\\', '/'); if (!projects.ContainsKey(target)) + { failures.Add($"{relative}: explicit project dependency is missing: {dependency}."); + } ValidateDependency(relative, dependency, failures); } } @@ -60,13 +72,22 @@ ICollection failures string relative = Path.GetRelativePath(root, source).Replace('\\', '/'); // Core IO owns portable filesystem operations; these calls choose OS primitives, never product targets. if (relative.StartsWith("src/foundation/core/Inno.Core.IO/", StringComparison.Ordinal) - || relative.StartsWith("src/composition/adapters/", StringComparison.Ordinal)) + || relative.StartsWith("src/composition/adapters/", StringComparison.Ordinal) + ) { continue; + } var syntax = CSharpSyntaxTree.ParseText(File.ReadAllText(source)).GetRoot(); foreach (InvocationExpressionSyntax call in syntax.DescendantNodes().OfType()) + { if (call.Expression is MemberAccessExpressionSyntax access - && access.Expression.ToString() == "OperatingSystem" && access.Name.Identifier.ValueText.StartsWith("Is", StringComparison.Ordinal)) - failures.Add($"{relative}: shared code must receive capabilities instead of selecting a product or backend by host OS."); + && access.Expression.ToString() == "OperatingSystem" + && access.Name.Identifier.ValueText.StartsWith("Is", StringComparison.Ordinal) + ) { + failures.Add( + $"{relative}: shared code must receive capabilities instead of selecting a product or backend by host OS." + ); + } + } } } @@ -76,62 +97,92 @@ internal static void ValidateDependency( ICollection failures ) { if (!RepositorySourceInventory.IsTestPath(relative) && RepositorySourceInventory.IsTestPath(dependency)) + { failures.Add($"{relative}: production code cannot reference test support {dependency}."); + } bool shared = relative.StartsWith("src/", StringComparison.Ordinal) - && !relative.StartsWith("src/composition/adapters/", StringComparison.Ordinal); + && !relative.StartsWith("src/composition/adapters/", StringComparison.Ordinal); if (!relative.StartsWith("entry/", StringComparison.Ordinal) && !relative.StartsWith("tests/", StringComparison.Ordinal) - && dependency.StartsWith("entry/", StringComparison.Ordinal)) + && dependency.StartsWith("entry/", StringComparison.Ordinal) + ) { failures.Add($"{relative}: production mechanisms cannot depend on the development entry {dependency}."); + } string[] segments = relative.Split('/'); bool platformBase = relative.StartsWith("platforms/", StringComparison.Ordinal) - && segments.Length > 2 && segments[2] is "build" or "runtime"; + && segments.Length > 2 && segments[2] is "build" or "runtime"; bool runtimeIntegration = relative.Contains("/integrations/", StringComparison.Ordinal) - && relative.Contains(".Bgfx.Runtime/", StringComparison.Ordinal); + && relative.Contains(".Bgfx.Runtime/", StringComparison.Ordinal); if (runtimeIntegration && (dependency.Contains("/build/", StringComparison.Ordinal) - || dependency.StartsWith("build/", StringComparison.Ordinal) - || dependency.Contains("/Inno.Native.Bgfx/", StringComparison.Ordinal) - || dependency.StartsWith("platforms/", StringComparison.Ordinal) - && dependency.Contains("/integrations/", StringComparison.Ordinal) - && dependency.Contains(".Bgfx/", StringComparison.Ordinal))) + || dependency.StartsWith("build/", StringComparison.Ordinal) + || dependency.Contains("/Inno.Native.Bgfx/", StringComparison.Ordinal) + || dependency.StartsWith("platforms/", StringComparison.Ordinal) + && dependency.Contains("/integrations/", StringComparison.Ordinal) + && dependency.Contains(".Bgfx/", StringComparison.Ordinal)) + ) { failures.Add($"{relative}: runtime surface integrations cannot depend on build tools or native BGFX {dependency}."); + } if (platformBase && dependency.StartsWith("build/bindings/", StringComparison.Ordinal)) + { failures.Add($"{relative}: platform modules must borrow the neutral binding generator contract {dependency}."); + } if (relative.StartsWith("build/toolchains/", StringComparison.Ordinal) && (dependency.StartsWith("build/bindings/", StringComparison.Ordinal) - || dependency.StartsWith("build/tasks/", StringComparison.Ordinal))) + || dependency.StartsWith("build/tasks/", StringComparison.Ordinal)) + ) { failures.Add($"{relative}: neutral toolchains cannot depend on a generator implementation or MSBuild tasks {dependency}."); + } if (relative.StartsWith("build/bindings/", StringComparison.Ordinal) - && dependency.StartsWith("build/tasks/", StringComparison.Ordinal)) + && dependency.StartsWith("build/tasks/", StringComparison.Ordinal) + ) { failures.Add($"{relative}: binding generation cannot depend on MSBuild tasks {dependency}."); + } if (platformBase && dependency.StartsWith("backends/", StringComparison.Ordinal)) + { failures.Add($"{relative}: platform base modules cannot select backend implementations {dependency}."); + } if (platformBase && dependency.Contains("/integrations/", StringComparison.Ordinal)) + { failures.Add($"{relative}: platform base modules cannot depend on integration implementations {dependency}."); + } if (relative.Contains("/integrations/", StringComparison.Ordinal) - && dependency.StartsWith("build/distributions/", StringComparison.Ordinal)) + && dependency.StartsWith("build/distributions/", StringComparison.Ordinal) + ) { failures.Add($"{relative}: integrations cannot own distribution registration {dependency}."); + } if (relative.Contains("/integrations/", StringComparison.Ordinal) && relative.Contains(".Bgfx/", StringComparison.Ordinal) - && dependency.Contains("/Inno.Native.Bgfx/", StringComparison.Ordinal)) + && dependency.Contains("/Inno.Native.Bgfx/", StringComparison.Ordinal) + ) { failures.Add($"{relative}: build integrations must not expose or load native BGFX bindings {dependency}."); + } if (shared && dependency.StartsWith("platforms/", StringComparison.Ordinal)) + { failures.Add($"{relative}: shared mechanisms cannot reference a concrete platform {dependency}."); + } if (relative.StartsWith("backends/", StringComparison.Ordinal) - && dependency.StartsWith("platforms/", StringComparison.Ordinal)) + && dependency.StartsWith("platforms/", StringComparison.Ordinal) + ) { failures.Add($"{relative}: reusable backends cannot depend on platform packages {dependency}."); + } if (relative.StartsWith("platforms/", StringComparison.Ordinal) && dependency.StartsWith("platforms/", StringComparison.Ordinal) - && relative.Split('/')[1] != dependency.Split('/')[1]) + && relative.Split('/')[1] != dependency.Split('/')[1] + ) { failures.Add($"{relative}: one concrete platform cannot depend on another {dependency}."); + } if (relative.StartsWith("build/composition/", StringComparison.Ordinal) && (dependency.StartsWith("platforms/", StringComparison.Ordinal) || dependency.StartsWith("backends/", StringComparison.Ordinal) - || dependency.StartsWith("build/distributions/", StringComparison.Ordinal))) + || dependency.StartsWith("build/distributions/", StringComparison.Ordinal)) + ) { failures.Add($"{relative}: neutral build composition must receive concrete contributions {dependency}."); + } if (relative.StartsWith("src/composition/editor/hosting/", StringComparison.Ordinal) && (dependency.StartsWith("backends/", StringComparison.Ordinal) || dependency.StartsWith("build/distributions/", StringComparison.Ordinal) - || dependency.StartsWith("src/composition/adapters/", StringComparison.Ordinal))) + || dependency.StartsWith("src/composition/adapters/", StringComparison.Ordinal)) + ) { failures.Add($"{relative}: shared Editor hosting must receive concrete services {dependency}."); + } } private static void ValidateEntryProject( @@ -140,22 +191,31 @@ private static void ValidateEntryProject( ICollection failures ) { if (!relative.StartsWith("entry/", StringComparison.Ordinal)) + { return; + } XElement[] references = project.Descendants("ProjectReference").ToArray(); if (relative == "entry/InnoEngine.Editor/InnoEngine.Editor.csproj") { - XElement[] products = references.Where(static reference => - reference.Attribute("Include")?.Value == "$(InnoDevelopmentEditorProject)").ToArray(); + XElement[] products = references.Where(static reference => ( + reference.Attribute("Include")?.Value == "$(InnoDevelopmentEditorProject)" + )).ToArray(); if (products.Length != 1 || products[0].Attribute("Condition")?.Value != "'$(InnoDevelopmentEditorProject)' != ''") + { failures.Add($"{relative}: Editor startup must consume the platform-owned development product reference."); + } } else if (relative == "entry/InnoEngine.Build/InnoEngine.Build.csproj") { - if (!references.Any(static reference => - reference.Attribute("Include")?.Value.EndsWith("/Inno.Build.Cli.csproj", StringComparison.Ordinal) == true)) + if (!references.Any(static reference => ( + reference.Attribute("Include")?.Value.EndsWith("/Inno.Build.Cli.csproj", StringComparison.Ordinal) == true + ))) { failures.Add($"{relative}: Build startup must reference the shared CLI application directly."); + } } else + { failures.Add($"{relative}: only the two ordinary executable entry projects are maintained."); + } } } diff --git a/tools/Inno.Tooling.Architecture/PublicApiBoundaryValidator.cs b/tools/Inno.Tooling.Architecture/PublicApiBoundaryValidator.cs index 940f20e05..95f3915da 100644 --- a/tools/Inno.Tooling.Architecture/PublicApiBoundaryValidator.cs +++ b/tools/Inno.Tooling.Architecture/PublicApiBoundaryValidator.cs @@ -27,42 +27,64 @@ internal static void Validate( .Where(path => !path.Split(Path.DirectorySeparatorChar).Contains("Bindings", StringComparer.Ordinal)) .Where(path => !path.Split(Path.DirectorySeparatorChar).Contains("tests", StringComparer.Ordinal)) .Where(path => !XDocument.Load(path).Descendants("OutputType").Any(static item => item.Value == "Exe")) - .Select(path => Project.Read(path, configuration, evaluatedOutputs)).ToArray(); - bool Selected(Project project) => selectedProjects is null || selectedProjects.Contains(Path.GetRelativePath(root, project.path).Replace('\\', '/')); + .Select(path => Project.Read(path, configuration, evaluatedOutputs)) + .ToArray(); + bool Selected(Project project) + => selectedProjects is null || selectedProjects.Contains(Path.GetRelativePath(root, project.path).Replace('\\', '/')); var byName = projects.ToDictionary(project => project.name, StringComparer.Ordinal); var references = new Dictionary(StringComparer.OrdinalIgnoreCase); string[] platform = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? string.Empty).Split(Path.PathSeparator); foreach (string path in platform.Where(File.Exists)) + { references[Path.GetFileNameWithoutExtension(path)] = MetadataReference.CreateFromFile(path); + } // Public generator and analyzer contracts require the compiler metadata used by this audit. foreach (string path in new[] { typeof(Compilation).Assembly.Location, typeof(CSharpCompilation).Assembly.Location }) + { references[Path.GetFileNameWithoutExtension(path)] = MetadataReference.CreateFromFile(path); + } foreach (Project project in projects) { if (File.Exists(project.output)) + { references[project.name] = MetadataReference.CreateFromFile(project.output); + } else if (!project.product && Selected(project)) - failures.Add($"{Path.GetRelativePath(root, project.path)}: public API symbol audit requires a {configuration} solution build; output is missing."); + { + failures.Add( + $"{Path.GetRelativePath(root, project.path)}: public API symbol audit requires a {configuration} solution build; output is missing." + ); + } } - CSharpCompilation compilation = CSharpCompilation.Create("Inno.Architecture.SymbolAudit", references: references.Values, - options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); - foreach (Project project in projects.Where(project => Selected(project) && (project.product - || project.path.Contains(Path.DirectorySeparatorChar + "src" + Path.DirectorySeparatorChar, StringComparison.Ordinal)))) - { + CSharpCompilation compilation = CSharpCompilation.Create( + "Inno.Architecture.SymbolAudit", + references: references.Values, + options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + ); + foreach (Project project in projects.Where(project => ( + Selected(project) && (project.product + || project.path.Contains(Path.DirectorySeparatorChar + "src" + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + )) + ) { IAssemblySymbol assembly; bool compiledContract = false; if (references.TryGetValue(project.name, out PortableExecutableReference? assemblyReference) - && compilation.GetAssemblyOrModuleSymbol(assemblyReference) is IAssemblySymbol compiledAssembly) - { + && compilation.GetAssemblyOrModuleSymbol(assemblyReference) is IAssemblySymbol compiledAssembly + ) { if (evaluatedReferences is null) + { assembly = compiledAssembly; + } else { // Resolve this owner's real SDK references, including dependencies outside the audit selection. CSharpCompilation contract = evaluatedReferences.GetCompilation(project.path, cancellationToken); PortableExecutableReference output = contract.References.OfType() - .Single(reference => string.Equals(reference.FilePath, project.output, - OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)); + .Single(reference => string.Equals( + reference.FilePath, + project.output, + OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal + )); assembly = (IAssemblySymbol)contract.GetAssemblyOrModuleSymbol(output)!; } compiledContract = true; @@ -71,29 +93,46 @@ internal static void Validate( { // Foreign product SDKs are not needed to audit the public composition contract. SyntaxTree[] sources = RepositorySourceInventory.Files(Path.GetDirectoryName(project.path)!, "*.cs") - .Select(path => CSharpSyntaxTree.ParseText(File.ReadAllText(path), path: path)).ToArray(); - assembly = CSharpCompilation.Create(project.name, sources, references.Values, - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true)).Assembly; + .Select(path => CSharpSyntaxTree.ParseText(File.ReadAllText(path), path: path)) + .ToArray(); + assembly = CSharpCompilation.Create( + project.name, + sources, + references.Values, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true) + ).Assembly; } else + { continue; + } var dependencies = new HashSet(StringComparer.Ordinal); foreach (INamedTypeSymbol type in Types(assembly.GlobalNamespace)) { if (!Exposed(type)) + { continue; + } if (project.name.StartsWith("Inno.Adapter.", StringComparison.Ordinal) && project.name.Split('.').Length == 3 && type.TypeKind == TypeKind.Enum - && type.Name.EndsWith("Backend", StringComparison.Ordinal)) - { - failures.Add($"{Path.GetRelativePath(root, project.path)}: replaceable backend selections require open IDs and provider catalogs, not closed enums."); + && type.Name.EndsWith("Backend", StringComparison.Ordinal) + ) { + failures.Add( + $"{Path.GetRelativePath(root, project.path)}: replaceable backend selections require open IDs and provider catalogs, not closed enums." + ); } Inspect(type.BaseType, type); foreach (INamedTypeSymbol contract in type.Interfaces) + { Inspect(contract, type); + } foreach (ITypeParameterSymbol parameter in type.TypeParameters) + { foreach (ITypeSymbol constraint in parameter.ConstraintTypes) + { Inspect(constraint, type); + } + } foreach (ISymbol member in type.GetMembers().Where(Exposed)) { switch (member) @@ -101,15 +140,23 @@ internal static void Validate( case IMethodSymbol method: Inspect(method.ReturnType, member); foreach (IParameterSymbol parameter in method.Parameters) + { Inspect(parameter.Type, member); + } foreach (ITypeParameterSymbol parameter in method.TypeParameters) + { foreach (ITypeSymbol constraint in parameter.ConstraintTypes) + { Inspect(constraint, member); + } + } break; case IPropertySymbol property: Inspect(property.Type, member); foreach (IParameterSymbol parameter in property.Parameters) + { Inspect(parameter.Type, member); + } break; case IFieldSymbol field: Inspect(field.Type, member); break; case IEventSymbol signal: Inspect(signal.Type, member); break; @@ -119,29 +166,50 @@ internal static void Validate( if (project.name.StartsWith("Inno.Editor.", StringComparison.Ordinal)) { XElement[] referenceGroups = project.references.Select(reference => reference.Parent!).Distinct().ToArray(); - XElement[] implementationGroups = referenceGroups.Where(group => group.Elements("ProjectReference").Any(IsCompilePrivate)).ToArray(); - XElement[] publicGroups = referenceGroups.Where(group => group.Elements("ProjectReference").Any(reference => !IsCompilePrivate(reference))).ToArray(); - if (implementationGroups.Length > 1 || publicGroups.Length > 1 || - referenceGroups.Any(group => group.Elements("ProjectReference").Any(IsCompilePrivate) - && group.Elements("ProjectReference").Any(reference => !IsCompilePrivate(reference))) || - (referenceGroups.Length == 2 && publicGroups.Length == 1 && ReferenceEquals(referenceGroups[0], publicGroups[0]))) - { - failures.Add($"{Path.GetRelativePath(root, project.path)}: Editor references require one implementation group followed by one public API group."); + XElement[] implementationGroups = referenceGroups + .Where(group => group.Elements("ProjectReference").Any(IsCompilePrivate)) + .ToArray(); + XElement[] publicGroups = referenceGroups + .Where(group => group.Elements("ProjectReference").Any(reference => !IsCompilePrivate(reference))) + .ToArray(); + if (implementationGroups.Length > 1 || publicGroups.Length > 1 + || referenceGroups.Any(group => ( + group.Elements("ProjectReference").Any(IsCompilePrivate) + && group.Elements("ProjectReference").Any(reference => !IsCompilePrivate(reference)) + )) + || (referenceGroups.Length == 2 && publicGroups.Length == 1 && ReferenceEquals(referenceGroups[0], publicGroups[0])) + ) { + failures.Add( + $"{Path.GetRelativePath(root, project.path)}: Editor references require one implementation group followed by one public API group." + ); } foreach (string dependency in dependencies.Where(byName.ContainsKey).Order(StringComparer.Ordinal)) { - XElement? declaration = project.references.FirstOrDefault(element => - Path.GetFileNameWithoutExtension(element.Attribute("Include")?.Value.Replace('\\', '/') ?? string.Empty) == dependency); + XElement? declaration = project.references.FirstOrDefault(element => ( + Path.GetFileNameWithoutExtension( + element.Attribute("Include")?.Value.Replace('\\', '/') ?? string.Empty + ) == dependency + )); if (declaration is null || ((string?)declaration.Attribute("PrivateAssets"))?.Split(';').Contains("compile") == true) - failures.Add($"{Path.GetRelativePath(root, project.path)}: public/protected API exposes {dependency}; declare a direct public ProjectReference."); + { + failures.Add( + $"{Path.GetRelativePath(root, project.path)}: public/protected API exposes {dependency}; declare a direct public ProjectReference." + ); + } } foreach (XElement reference in project.references) { - string dependency = Path.GetFileNameWithoutExtension(reference.Attribute("Include")?.Value.Replace('\\', '/') ?? string.Empty); + string dependency = Path.GetFileNameWithoutExtension( + reference.Attribute("Include")?.Value.Replace('\\', '/') ?? string.Empty + ); // Source-only foreign product inspection cannot prove that generated public contracts are absent. if (compiledContract && byName.ContainsKey(dependency) - && !dependencies.Contains(dependency) && !IsCompilePrivate(reference)) - failures.Add($"{Path.GetRelativePath(root, project.path)}: {dependency} is an implementation dependency; declare PrivateAssets=compile."); + && !dependencies.Contains(dependency) && !IsCompilePrivate(reference) + ) { + failures.Add( + $"{Path.GetRelativePath(root, project.path)}: {dependency} is an implementation dependency; declare PrivateAssets=compile." + ); + } } } @@ -150,10 +218,14 @@ void Inspect( ISymbol member ) { if (value is null) + { return; + } if (value.TypeKind == TypeKind.Error) { - failures.Add($"{Path.GetRelativePath(root, project.path)}: {member.ToDisplayString()} has an unresolved public signature type {value.ToDisplayString()}."); + failures.Add( + $"{Path.GetRelativePath(root, project.path)}: {member.ToDisplayString()} has an unresolved public signature type {value.ToDisplayString()}." + ); return; } switch (value) @@ -163,25 +235,42 @@ ISymbol member case IFunctionPointerTypeSymbol pointer: Inspect(pointer.Signature.ReturnType, member); foreach (IParameterSymbol parameter in pointer.Signature.Parameters) + { Inspect(parameter.Type, member); + } return; case INamedTypeSymbol named: Inspect(named.ContainingType, member); foreach (ITypeSymbol argument in named.TypeArguments) + { Inspect(argument, member); + } break; } string? dependency = value.ContainingAssembly?.Identity.Name; if (dependency is null || dependency == project.name) + { return; + } dependencies.Add(dependency); - if (dependency.StartsWith("Inno.Native.Bgfx", StringComparison.Ordinal) || - dependency == "Inno.Native.MiniAudio" || dependency == "Inno.Native.Sdl3") - failures.Add($"{Path.GetRelativePath(root, project.path)}: {member.ToDisplayString()} exposes native symbol {value.ToDisplayString()} from {dependency}."); - if ((project.name == "Inno.Shell" || project.name.StartsWith("Inno.Editor.", StringComparison.Ordinal) || project.name == "Inno.Player") && - dependency.StartsWith("Inno.Adapter.", StringComparison.Ordinal) && - dependency.Split('.').Length >= 4 && !dependency.EndsWith("Default", StringComparison.Ordinal)) - failures.Add($"{Path.GetRelativePath(root, project.path)}: {member.ToDisplayString()} exposes concrete adapter {value.ToDisplayString()}."); + if (dependency.StartsWith("Inno.Native.Bgfx", StringComparison.Ordinal) + || dependency == "Inno.Native.MiniAudio" || dependency == "Inno.Native.Sdl3" + ) { + failures.Add( + $"{Path.GetRelativePath(root, project.path)}: {member.ToDisplayString()} exposes native symbol {value.ToDisplayString()} from {dependency}." + ); + } + if ((project.name == "Inno.Shell" + || project.name.StartsWith("Inno.Editor.", StringComparison.Ordinal) + || project.name == "Inno.Player") + && + dependency.StartsWith("Inno.Adapter.", StringComparison.Ordinal) + && dependency.Split('.').Length >= 4 && !dependency.EndsWith("Default", StringComparison.Ordinal) + ) { + failures.Add( + $"{Path.GetRelativePath(root, project.path)}: {member.ToDisplayString()} exposes concrete adapter {value.ToDisplayString()}." + ); + } } } } @@ -197,13 +286,19 @@ private static IEnumerable Types(INamespaceOrTypeSymbol owner) foreach (ISymbol member in owner.GetMembers()) { if (member is INamespaceSymbol space) + { foreach (INamedTypeSymbol type in Types(space)) + { yield return type; + } + } else if (member is INamedTypeSymbol type && Exposed(type)) { yield return type; foreach (INamedTypeSymbol nested in Types(type)) + { yield return nested; + } } } } @@ -225,11 +320,21 @@ internal static Project Read( string framework = document.Descendants("TargetFramework").FirstOrDefault()?.Value ?? "net10.0"; string? target = document.Descendants("InnoProductTarget").FirstOrDefault()?.Value; string output = evaluatedOutputs is null - ? Path.Combine(Path.GetDirectoryName(path)!, target is null ? "bin" : Path.Combine("bin", target), - configuration, framework, name + ".dll") - : evaluatedOutputs.TryGetValue(Path.GetFullPath(path), out string? selected) ? selected : string.Empty; - return new Project(path, name, output, - document.Descendants("ProjectReference").ToArray(), document.Descendants("InnoProductId").Any()); + ? Path.Combine( + Path.GetDirectoryName(path)!, + target is null ? "bin" : Path.Combine("bin", target), + configuration, + framework, + name + ".dll" + ) + : evaluatedOutputs.TryGetValue(Path.GetFullPath(path), out string? selected) ? selected : string.Empty; + return new Project( + path, + name, + output, + document.Descendants("ProjectReference").ToArray(), + document.Descendants("InnoProductId").Any() + ); } } } diff --git a/tools/Inno.Tooling.Architecture/PublicApiDocumentationValidator.cs b/tools/Inno.Tooling.Architecture/PublicApiDocumentationValidator.cs index 9d0292e7e..3852c937f 100644 --- a/tools/Inno.Tooling.Architecture/PublicApiDocumentationValidator.cs +++ b/tools/Inno.Tooling.Architecture/PublicApiDocumentationValidator.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Xml.Linq; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -20,11 +19,13 @@ internal static void Validate( bool validateInheritedContract = true ) { SyntaxNode root = model?.SyntaxTree.GetRoot() - ?? syntax.GetRoot(); + ?? syntax.GetRoot(); foreach (MemberDeclarationSyntax member in root.DescendantNodes().OfType()) { if (!RequiresDocumentation(member)) + { continue; + } DocumentationCommentTriviaSyntax? documentation = member.GetLeadingTrivia() .Select(static trivia => trivia.GetStructure()) @@ -38,36 +39,48 @@ internal static void Validate( continue; } if (documentation.ContainsDiagnostics) + { failures.Add($"{location}: public or protected XML documentation is malformed."); + } XmlEmptyElementSyntax? inherited = documentation.Content.OfType() .FirstOrDefault(static element => element.Name.LocalName.Text == "inheritdoc"); if (inherited is not null) { if (!validateInheritedContract) + { continue; + } SyntaxNode declaration = member is EventFieldDeclarationSyntax signal - ? signal.Declaration.Variables[0] - : member; + ? signal.Declaration.Variables[0] + : member; ISymbol? symbol = model?.GetDeclaredSymbol(declaration); XmlCrefAttributeSyntax? reference = inherited.Attributes.OfType().FirstOrDefault(); ISymbol? selected = reference is null ? null : model?.GetSymbolInfo(reference.Cref).Symbol; bool validReference = reference is null || symbol is not null && selected is not null - && InheritedMembers(symbol).Any(target => SymbolEqualityComparer.Default.Equals( - target.OriginalDefinition, selected.OriginalDefinition)); + && InheritedMembers(symbol).Any(target => SymbolEqualityComparer.Default.Equals( + target.OriginalDefinition, + selected.OriginalDefinition + )); if (!validReference || symbol is null - || !HasInheritedContract(symbol, models, new HashSet(SymbolEqualityComparer.Default))) + || !HasInheritedContract(symbol, models, new HashSet(SymbolEqualityComparer.Default)) + ) { failures.Add($"{location}: inheritdoc requires a documented overridden or implemented contract."); + } continue; } XmlElementSyntax? summary = FindElement(documentation, "summary"); if (summary is null || string.IsNullOrWhiteSpace(GetText(summary))) + { failures.Add($"{location}: public or protected declaration requires a meaningful summary."); + } ValidateTypeParameters(location, member, documentation, failures); ValidateParameters(location, member, documentation, failures); if (RequiresReturns(member) && FindElement(documentation, "returns") is null) + { failures.Add($"{location}: non-void public or protected operation requires a returns contract."); + } } } @@ -77,7 +90,9 @@ private static bool HasInheritedContract( ISet visited ) { if (!visited.Add(symbol)) + { return false; + } foreach (ISymbol target in InheritedMembers(symbol)) { string xml = target.GetDocumentationCommentXml() ?? string.Empty; @@ -85,7 +100,9 @@ ISet visited { // The repository owns its contracts; external framework documentation is supplied by its publisher. if (!models.OwnsAssembly(target.ContainingAssembly)) + { return true; + } continue; } XElement document; @@ -98,28 +115,40 @@ ISet visited continue; } if (document.Element("inheritdoc") is not null && HasInheritedContract(target, models, visited)) + { return true; + } if (string.IsNullOrWhiteSpace(document.Element("summary")?.Value)) + { continue; + } IEnumerable parameters = target switch { IMethodSymbol method => method.Parameters, IPropertySymbol property => property.Parameters, _ => [] }; - var documented = document.Elements("param").Select(static element => (string?)element.Attribute("name")) + var documented = document.Elements("param") + .Select(static element => (string?)element.Attribute("name")) .ToHashSet(StringComparer.Ordinal); if (parameters.Any(parameter => !documented.Contains(parameter.Name))) + { continue; + } if (target is IMethodSymbol generic) { var typeParameters = document.Elements("typeparam") - .Select(static element => (string?)element.Attribute("name")).ToHashSet(StringComparer.Ordinal); + .Select(static element => (string?)element.Attribute("name")) + .ToHashSet(StringComparer.Ordinal); if (generic.TypeParameters.Any(parameter => !typeParameters.Contains(parameter.Name))) + { continue; + } } if (target is IMethodSymbol { ReturnsVoid: false } && document.Element("returns") is null) + { continue; + } return true; } return false; @@ -135,15 +164,21 @@ internal static IEnumerable InheritedMembers(ISymbol symbol) _ => null }; if (overridden is not null) + { yield return overridden; + } if (symbol.ContainingType is not INamedTypeSymbol owner) + { yield break; + } foreach (INamedTypeSymbol contract in owner.AllInterfaces) { foreach (ISymbol member in contract.GetMembers()) { if (SymbolEqualityComparer.Default.Equals(owner.FindImplementationForInterfaceMember(member), symbol)) + { yield return member; + } } } } @@ -151,11 +186,17 @@ internal static IEnumerable InheritedMembers(ISymbol symbol) private static bool RequiresDocumentation(MemberDeclarationSyntax member) { if (member is EnumMemberDeclarationSyntax enumMember) + { return enumMember.Parent is EnumDeclarationSyntax declaration && RequiresDocumentation(declaration); + } if (member.Parent is InterfaceDeclarationSyntax) + { return true; - return member.Modifiers.Any(static modifier => modifier.IsKind(SyntaxKind.PublicKeyword) - || modifier.IsKind(SyntaxKind.ProtectedKeyword)); + } + return member.Modifiers.Any(static modifier => ( + modifier.IsKind(SyntaxKind.PublicKeyword) + || modifier.IsKind(SyntaxKind.ProtectedKeyword) + )); } private static void ValidateTypeParameters( @@ -172,12 +213,16 @@ ICollection failures _ => null }; if (parameters is null) + { return; + } HashSet documented = GetNamedElements(documentation, "typeparam"); foreach (TypeParameterSyntax parameter in parameters.Parameters) { if (!documented.Contains(parameter.Identifier.ValueText)) + { failures.Add($"{location}: type parameter '{parameter.Identifier.ValueText}' is missing XML documentation."); + } } } @@ -204,19 +249,21 @@ ICollection failures foreach (ParameterSyntax parameter in parameters) { if (!documented.Contains(parameter.Identifier.ValueText)) + { failures.Add($"{location}: parameter '{parameter.Identifier.ValueText}' is missing XML documentation."); + } } } private static bool RequiresReturns(MemberDeclarationSyntax member) => member switch - { - MethodDeclarationSyntax method => !IsVoid(method.ReturnType), - DelegateDeclarationSyntax callback => !IsVoid(callback.ReturnType), - OperatorDeclarationSyntax => true, - ConversionOperatorDeclarationSyntax => true, - _ => false - }; + { + MethodDeclarationSyntax method => !IsVoid(method.ReturnType), + DelegateDeclarationSyntax callback => !IsVoid(callback.ReturnType), + OperatorDeclarationSyntax => true, + ConversionOperatorDeclarationSyntax => true, + _ => false + }; private static bool IsVoid(TypeSyntax type) => type is PredefinedTypeSyntax predefined && predefined.Keyword.IsKind(SyntaxKind.VoidKeyword); @@ -224,21 +271,20 @@ private static bool IsVoid(TypeSyntax type) private static XmlElementSyntax? FindElement( DocumentationCommentTriviaSyntax documentation, string name - ) - => documentation.Content.OfType().FirstOrDefault(element => - element.StartTag.Name.LocalName.Text == name); + ) => documentation.Content.OfType().FirstOrDefault(element => ( + element.StartTag.Name.LocalName.Text == name + )); private static HashSet GetNamedElements( DocumentationCommentTriviaSyntax documentation, string name - ) - => documentation.Content - .OfType() - .Where(element => element.StartTag.Name.LocalName.Text == name) - .SelectMany(static element => element.StartTag.Attributes.OfType()) - .Where(static attribute => attribute.Name.LocalName.Text == "name") - .Select(static attribute => attribute.Identifier.Identifier.ValueText) - .ToHashSet(StringComparer.Ordinal); + ) => documentation.Content + .OfType() + .Where(element => element.StartTag.Name.LocalName.Text == name) + .SelectMany(static element => element.StartTag.Attributes.OfType()) + .Where(static attribute => attribute.Name.LocalName.Text == "name") + .Select(static attribute => attribute.Identifier.Identifier.ValueText) + .ToHashSet(StringComparer.Ordinal); private static string GetText(XmlElementSyntax element) => string.Concat(element.Content.Select(static content => content.ToString())).Trim(); diff --git a/tools/Inno.Tooling.Architecture/RepositorySourceInventory.cs b/tools/Inno.Tooling.Architecture/RepositorySourceInventory.cs index fbea1032b..54c9a398d 100644 --- a/tools/Inno.Tooling.Architecture/RepositorySourceInventory.cs +++ b/tools/Inno.Tooling.Architecture/RepositorySourceInventory.cs @@ -16,27 +16,29 @@ internal static bool IsTestPath(string relative) "bin", "obj", "Generated", "extern", "artifacts", ".git" }; - internal static IEnumerable Projects(string root) - => Files(root, "*.csproj"); + internal static IEnumerable Projects(string root) => Files(root, "*.csproj"); internal static bool DeclaresTestSupport(XDocument project) - => project.Descendants().Any(static item => - item.Name.LocalName is "IsTestProject" or "IsTestSupportProject" && item.Value.Equals("true", StringComparison.OrdinalIgnoreCase) - || item.Name.LocalName == "PackageReference" && IsTestPackage(item.Attribute("Include")?.Value ?? item.Attribute("Update")?.Value ?? string.Empty)); + => project.Descendants().Any(static item => ( + item.Name.LocalName is "IsTestProject" or "IsTestSupportProject" + && item.Value.Equals("true", StringComparison.OrdinalIgnoreCase) + || item.Name.LocalName == "PackageReference" + && IsTestPackage(item.Attribute("Include")?.Value ?? item.Attribute("Update")?.Value ?? string.Empty) + )); internal static bool IsTestPackage(string package) => package.Equals("Microsoft.NET.Test.Sdk", StringComparison.OrdinalIgnoreCase) - || package.Equals("xunit", StringComparison.OrdinalIgnoreCase) - || package.StartsWith("xunit.v3", StringComparison.OrdinalIgnoreCase) - || package.Equals("NUnit", StringComparison.OrdinalIgnoreCase) - || package.Equals("MSTest.TestFramework", StringComparison.OrdinalIgnoreCase); + || package.Equals("xunit", StringComparison.OrdinalIgnoreCase) + || package.StartsWith("xunit.v3", StringComparison.OrdinalIgnoreCase) + || package.Equals("NUnit", StringComparison.OrdinalIgnoreCase) + || package.Equals("MSTest.TestFramework", StringComparison.OrdinalIgnoreCase); internal static bool IsDeclaredTestProject(string project) { XElement? declaration = XDocument.Load(project).Descendants("IsTestProject").LastOrDefault(); // Only explicit unconditional test runners exempt their public test methods; support libraries retain API contracts. return declaration?.Attribute("Condition") is null && declaration?.Parent?.Attribute("Condition") is null - && declaration?.Value.Equals("true", StringComparison.OrdinalIgnoreCase) == true; + && declaration?.Value.Equals("true", StringComparison.OrdinalIgnoreCase) == true; } internal static IEnumerable Files( @@ -44,12 +46,20 @@ internal static IEnumerable Files( string pattern ) { if (!Directory.Exists(root)) + { yield break; + } foreach (string file in Directory.EnumerateFiles(root, pattern)) + { yield return file; + } foreach (string directory in Directories(root)) + { foreach (string file in Directory.EnumerateFiles(directory, pattern)) + { yield return file; + } + } } internal static IEnumerable Directories(string root) @@ -61,7 +71,9 @@ internal static IEnumerable Directories(string root) foreach (string child in Directory.EnumerateDirectories(pending.Pop())) { if (ExcludedDirectories.Contains(Path.GetFileName(child))) + { continue; + } yield return child; pending.Push(child); } diff --git a/tools/Inno.Tooling.Architecture/RuntimeContentBoundaryValidator.cs b/tools/Inno.Tooling.Architecture/RuntimeContentBoundaryValidator.cs index 3c82766b8..f3d6cdfbb 100644 --- a/tools/Inno.Tooling.Architecture/RuntimeContentBoundaryValidator.cs +++ b/tools/Inno.Tooling.Architecture/RuntimeContentBoundaryValidator.cs @@ -18,7 +18,7 @@ internal static class RuntimeContentBoundaryValidator internal static bool ShouldAudit(string relative) => IsContentOwner(relative) || relative.StartsWith("build/", StringComparison.Ordinal) - || relative.EndsWith("/EditorHost.cs", StringComparison.Ordinal); + || relative.EndsWith("/EditorHost.cs", StringComparison.Ordinal); internal static void Validate( string relative, @@ -26,28 +26,35 @@ internal static void Validate( ICollection failures ) { if (model is null) + { return; + } bool contentOwner = IsContentOwner(relative); bool compositionOwner = relative.StartsWith("build/composition/Inno.Build.Composition/", StringComparison.Ordinal); - foreach (SyntaxNode expression in model.SyntaxTree.GetRoot().DescendantNodes().Where(static node => - node is InvocationExpressionSyntax or ObjectCreationExpressionSyntax or ImplicitObjectCreationExpressionSyntax)) - { + foreach (SyntaxNode expression in model.SyntaxTree.GetRoot().DescendantNodes().Where(static node => ( + node is InvocationExpressionSyntax or ObjectCreationExpressionSyntax or ImplicitObjectCreationExpressionSyntax + )) + ) { ISymbol? symbol = model.GetSymbolInfo(expression).Symbol; string? type = symbol?.ContainingType?.ToDisplayString(); if (contentOwner && type is not null && PhysicalIoTypes.Contains(type)) + { failures.Add($"{relative}: shared content owners must receive reading contracts instead of calling {type}."); + } if (!compositionOwner && (expression is ObjectCreationExpressionSyntax or ImplicitObjectCreationExpressionSyntax) && (type is "Inno.Build.WindowsX64.WindowsX64GameBuildTarget" or "Inno.Build.MacOSArm64.MacOSArm64GameBuildTarget" - or "Inno.Build.BrowserWasm32.BrowserWasm32GameBuildTarget")) + or "Inno.Build.BrowserWasm32.BrowserWasm32GameBuildTarget") + ) { failures.Add($"{relative}: built-in targets must be registered by the shared build composition."); + } } } private static bool IsContentOwner(string relative) => relative.StartsWith("src/content/deployment/Inno.Content/", StringComparison.Ordinal) - || relative.StartsWith("src/composition/player/Inno.Player.Runtime/", StringComparison.Ordinal) - || relative.StartsWith("src/foundation/extensibility/Inno.Extensibility.Modules/", StringComparison.Ordinal) - || relative.StartsWith("src/content/assets/Inno.Assets/Runtime/AssetDatabase", StringComparison.Ordinal) - || relative.StartsWith("src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession", StringComparison.Ordinal); + || relative.StartsWith("src/composition/player/Inno.Player.Runtime/", StringComparison.Ordinal) + || relative.StartsWith("src/foundation/extensibility/Inno.Extensibility.Modules/", StringComparison.Ordinal) + || relative.StartsWith("src/content/assets/Inno.Assets/Runtime/AssetDatabase", StringComparison.Ordinal) + || relative.StartsWith("src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession", StringComparison.Ordinal); } diff --git a/tools/Inno.Tooling.Architecture/UsingPolicyValidator.cs b/tools/Inno.Tooling.Architecture/UsingPolicyValidator.cs index c56d70c87..ffd9b61a5 100644 --- a/tools/Inno.Tooling.Architecture/UsingPolicyValidator.cs +++ b/tools/Inno.Tooling.Architecture/UsingPolicyValidator.cs @@ -20,24 +20,41 @@ IReadOnlyDictionary sourceTrees { string relative = Path.GetRelativePath(root, file).Replace('\\', '/'); if (file.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) - || file.EndsWith(".cs.txt", StringComparison.OrdinalIgnoreCase)) - { - SyntaxTree tree = sourceTrees.TryGetValue(file, out SyntaxTree? parsed) ? parsed - : CSharpSyntaxTree.ParseText(File.ReadAllText(file), new CSharpParseOptions(LanguageVersion.CSharp14)); - if (tree.GetRoot().DescendantNodes().OfType().Any(static item => item.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword))) + || file.EndsWith(".cs.txt", StringComparison.OrdinalIgnoreCase) + ) { + SyntaxTree tree = sourceTrees.TryGetValue(file, out SyntaxTree? parsed) + ? parsed + : CSharpSyntaxTree.ParseText(File.ReadAllText(file), new CSharpParseOptions(LanguageVersion.CSharp14)); + if (tree + .GetRoot() + .DescendantNodes() + .OfType() + .Any(static item => item.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) + ) { failures.Add($"{relative}: global using directives are forbidden."); + } continue; } if (Path.GetExtension(file) is not (".csproj" or ".props" or ".targets")) + { continue; + } XDocument document = XDocument.Load(file); foreach (XElement property in document.Descendants("ImplicitUsings")) + { if (property.Value.Trim().Equals("enable", StringComparison.OrdinalIgnoreCase) - || property.Value.Trim().Equals("true", StringComparison.OrdinalIgnoreCase)) + || property.Value.Trim().Equals("true", StringComparison.OrdinalIgnoreCase) + ) { failures.Add($"{relative}: implicit usings must be disabled."); + } + } foreach (XElement item in document.Descendants("Using")) + { if (item.Attribute("Include") is not null || item.Attribute("Update") is not null) + { failures.Add($"{relative}: MSBuild Using items are forbidden."); + } + } } } } diff --git a/tools/Inno.Tooling.Documentation/DocumentationCatalogReport.cs b/tools/Inno.Tooling.Documentation/DocumentationCatalogReport.cs index fa19fb365..a25d10c10 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationCatalogReport.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationCatalogReport.cs @@ -52,6 +52,7 @@ IReadOnlyList references /// Gets the matching trusted source certificate identity, or null for an unverified catalog. /// public string? sourceEvidenceIdentity { get; init; } + /// /// Gets every original source identity, including individual API pages and their source-fact registry. /// diff --git a/tools/Inno.Tooling.Documentation/DocumentationCommand.cs b/tools/Inno.Tooling.Documentation/DocumentationCommand.cs index 5f302097c..b062b4c73 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationCommand.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationCommand.cs @@ -50,11 +50,23 @@ public static async Task ExecuteAsync( ) { ArgumentNullException.ThrowIfNull(arguments); if (arguments.Length > 0 && arguments[0] is "api-package" or "api-import") + { return await DocumentationApiPackage.ExecuteAsync(arguments[0], arguments[1..], cancellationToken).ConfigureAwait(false); + } if (arguments.Length > 0 && arguments[0] is "api-plan" or "api-check" or "api-sync") - return await DocumentationApiSynchronization.ExecuteAsync(arguments[0], arguments[1..], cancellationToken).ConfigureAwait(false); + { + return await DocumentationApiSynchronization.ExecuteAsync( + arguments[0], + arguments[1..], + cancellationToken + ).ConfigureAwait(false); + } if (arguments.Length == 0 || arguments[0] is not ("index" or "search" or "read" or "symbol" or "resource" or "status" or "catalog")) - throw new ArgumentException("Usage: docs --engine-root ROOT [--cache-root PATH] [--format text|json]. Index requires --docs-root CHECKOUT; reads require a prepared snapshot."); + { + throw new ArgumentException( + "Usage: docs --engine-root ROOT [--cache-root PATH] [--format text|json]. Index requires --docs-root CHECKOUT; reads require a prepared snapshot." + ); + } string operation = arguments[0]; string[] specific = operation switch { @@ -69,45 +81,81 @@ public static async Task ExecuteAsync( for (int index = 1; index < arguments.Length; index += 2) { string key = arguments[index]; - if ((key is not ("--engine-root" or "--cache-root" or "--format" or "--snapshot" or "--source-tree" or "--evidence-file" or "--evidence-sha256") && Array.IndexOf(specific, key) < 0) - || index + 1 >= arguments.Length || !options.TryAdd(key, arguments[index + 1])) + if ((key is not ("--engine-root" + or "--cache-root" + or "--format" + or "--snapshot" + or "--source-tree" + or "--evidence-file" + or "--evidence-sha256") + && Array.IndexOf(specific, key) < 0) + || index + 1 >= arguments.Length || !options.TryAdd(key, arguments[index + 1]) + ) { throw new ArgumentException("Unknown, duplicate or incomplete documentation option: " + key); + } } string format = options.GetValueOrDefault("--format", "text"); if (format is not ("text" or "json")) + { throw new ArgumentException("Documentation format must be text or json."); + } string root = Path.GetFullPath(options.GetValueOrDefault("--engine-root", Directory.GetCurrentDirectory())); string cache = Path.GetFullPath(options.GetValueOrDefault("--cache-root", Path.Combine(root, "artifacts", "documentation-query"))); bool evidence = options.ContainsKey("--evidence-file"); if (evidence != options.ContainsKey("--evidence-sha256") || operation == "index" && evidence) - throw new ArgumentException("Source evidence requires both a certificate file and independently trusted SHA-256 on a prepared-snapshot read."); + { + throw new ArgumentException( + "Source evidence requires both a certificate file and independently trusted SHA-256 on a prepared-snapshot read." + ); + } DocumentationResult result; if (operation == "index") { if (options.ContainsKey("--snapshot") || options.ContainsKey("--source-tree")) + { throw new ArgumentException("Index establishes its binding from engine.lock.json; snapshot selectors apply only to reads."); + } result = await DocumentationStore.IndexAsync(root, Required("--docs-root"), cache, cancellationToken).ConfigureAwait(false); } else { DocumentationEvidence? sourceEvidence = evidence - ? await DocumentationEvidence.ReadAsync(Required("--evidence-file"), Required("--evidence-sha256"), cancellationToken).ConfigureAwait(false) - : null; - using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, options.GetValueOrDefault("--snapshot"), - options.GetValueOrDefault("--source-tree"), cancellationToken, sourceEvidence).ConfigureAwait(false); + ? await DocumentationEvidence.ReadAsync( + Required("--evidence-file"), + Required("--evidence-sha256"), + cancellationToken + ).ConfigureAwait(false) + : null; + using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync( + cache, + options.GetValueOrDefault("--snapshot"), + options.GetValueOrDefault("--source-tree"), + cancellationToken, + sourceEvidence + ).ConfigureAwait(false); if (operation == "catalog") { DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(cancellationToken).ConfigureAwait(false); if (format == "json") + { Console.WriteLine(JsonSerializer.Serialize(catalog, DocumentationStore.json)); + } else { - Console.WriteLine($"Snapshot: {catalog.snapshot}; content: {catalog.contentIdentity}; source API: {catalog.sourceApiStatus}"); + Console.WriteLine( + $"Snapshot: {catalog.snapshot}; content: {catalog.contentIdentity}; source API: {catalog.sourceApiStatus}" + ); foreach (DocumentationPageInfo page in catalog.pages) + { Console.WriteLine($"{page.id}: {page.path} ({page.kind}; {page.sections.Count} sections)"); + } foreach (var project in catalog.projects) + { if (project.Value is null) + { Console.WriteLine("Missing project entry: " + project.Key); + } + } } return 0; } @@ -118,13 +166,24 @@ public static async Task ExecuteAsync( "resource" => Required("--uri"), _ => options.GetValueOrDefault("--page") }; - result = await snapshot.QueryAsync(new(operation, value, options.GetValueOrDefault("--project"), - options.GetValueOrDefault("--surface"), options.GetValueOrDefault("--section"), - int.Parse(options.GetValueOrDefault("--offset", "0"), CultureInfo.InvariantCulture), - int.Parse(options.GetValueOrDefault("--limit", "5"), CultureInfo.InvariantCulture), options.GetValueOrDefault("--scope")), cancellationToken).ConfigureAwait(false); + result = await snapshot.QueryAsync( + new( + operation, + value, + options.GetValueOrDefault("--project"), + options.GetValueOrDefault("--surface"), + options.GetValueOrDefault("--section"), + int.Parse(options.GetValueOrDefault("--offset", "0"), CultureInfo.InvariantCulture), + int.Parse(options.GetValueOrDefault("--limit", "5"), CultureInfo.InvariantCulture), + options.GetValueOrDefault("--scope") + ), + cancellationToken + ).ConfigureAwait(false); } if (format == "json") + { Console.WriteLine(JsonSerializer.Serialize(result, DocumentationStore.json)); + } else { Console.WriteLine($"{result.status}; snapshot: {result.snapshot}; source API: {result.sourceApiStatus}"); @@ -135,14 +194,22 @@ public static async Task ExecuteAsync( Console.WriteLine(hit.text); } foreach (DocumentationContinuation next in result.continuations) - Console.WriteLine($"Continue: docs read --page {next.pageId}" + (next.section is null ? "" : " --section " + next.section) - + $" --offset {next.offset} — {next.reason}"); + { + Console.WriteLine( + $"Continue: docs read --page {next.pageId}" + (next.section is null ? "" : " --section " + next.section) + + $" --offset {next.offset} — {next.reason}" + ); + } if (result.nextRequest is not null) + { Console.WriteLine("Next request: " + JsonSerializer.Serialize(result.nextRequest, DocumentationStore.json)); + } } return result.status is "Missing" or "Ambiguous" or "Mismatched" ? 2 : 0; - string Required(string option) => options.TryGetValue(option, out string? value) && !string.IsNullOrWhiteSpace(value) - ? value : throw new ArgumentException("Missing documentation option: " + option); + string Required(string option) + => options.TryGetValue(option, out string? value) && !string.IsNullOrWhiteSpace(value) + ? value + : throw new ArgumentException("Missing documentation option: " + option); } } diff --git a/tools/Inno.Tooling.Documentation/DocumentationEvidence.cs b/tools/Inno.Tooling.Documentation/DocumentationEvidence.cs index e96b3feca..25b4dda8f 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationEvidence.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationEvidence.cs @@ -64,34 +64,51 @@ public static async Task ReadAsync( PathBoundary.RequireUnlinkedPath(Path.GetPathRoot(path)!, path); using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true); if (stream.Length is <= 0 or > 16 * 1024 * 1024) + { throw new InvalidDataException("The source certificate exceeds its bounded metadata size."); + } var bytes = new byte[checked((int)stream.Length)]; await stream.ReadExactlyAsync(bytes, cancellationToken).ConfigureAwait(false); if (stream.ReadByte() != -1 || DocumentationMarkdown.Hash(bytes) != trustedIdentity) + { throw new InvalidDataException("Source certificate integrity does not match the trusted producer identity."); + } Certificate certificate; - try { certificate = DocumentationStore.Deserialize(bytes); } - catch (JsonException failure) { throw new InvalidDataException("Invalid source certificate structure.", failure); } + try + { + certificate = DocumentationStore.Deserialize(bytes); + } + catch (JsonException failure) + { + throw new InvalidDataException("Invalid source certificate structure.", failure); + } if (certificate.format != "inno-documentation-source/2" || string.IsNullOrWhiteSpace(certificate.repository) - || certificate.references is not { Length: > 0 } || certificate.producers is not { Length: > 0 }) + || certificate.references is not { Length: > 0 } || certificate.producers is not { Length: > 0 } + ) { throw new InvalidDataException("Source certification requires explicit source, reference and producer coverage."); + } DocumentationStore.RequireHash(certificate.sourceTree, "certified source tree", allowGitTree: true); DocumentationStore.RequireHash(certificate.projectManifestIdentity, "certified project inventory"); var paths = new HashSet(StringComparer.Ordinal); foreach (Reference reference in certificate.references) { if (reference is null || string.IsNullOrWhiteSpace(reference.path) || !paths.Add(reference.path) - || reference.model is not ("source-clr" or "runtime-script" or "editor-script") || string.IsNullOrWhiteSpace(reference.configuration) + || reference.model is not ("source-clr" or "runtime-script" or "editor-script") + || string.IsNullOrWhiteSpace(reference.configuration) || reference.projects is not { Length: > 0 } || reference.projects.Any(string.IsNullOrWhiteSpace) - || reference.projects.Distinct(StringComparer.Ordinal).Count() != reference.projects.Length) + || reference.projects.Distinct(StringComparer.Ordinal).Count() != reference.projects.Length + ) { throw new InvalidDataException("Source certificate reference coverage is invalid or duplicated."); + } DocumentationStore.RequireHash(reference.identity, "certified reference"); } foreach (Producer producer in certificate.producers) { if (producer is null || string.IsNullOrWhiteSpace(producer.origin)) + { throw new InvalidDataException("Source certificate producer provenance is missing."); + } DocumentationStore.RequireHash(producer.receiptIdentity, "producer receipt"); } RequireInputs(certificate); @@ -103,70 +120,107 @@ internal void RequireMatch(DocumentationManifest manifest) DocumentationReferenceInfo[] references = manifest.references!.Where(static item => item.model != "project-inventory").ToArray(); if (m_certificate.repository != manifest.binding.repository || m_certificate.sourceTree != manifest.binding.sourceTree || m_certificate.projectManifestIdentity != manifest.binding.projectManifestIdentity - || references.Length != m_certificate.references.Length) + || references.Length != m_certificate.references.Length + ) { throw new InvalidDataException("Source certificate does not cover the selected engine and reference snapshot."); + } foreach (DocumentationReferenceInfo reference in references) { Reference? proof = m_certificate.references.SingleOrDefault(item => item.path == reference.path); if (proof is null || proof.identity != reference.identity || proof.model != reference.model || proof.configuration != reference.configuration || proof.target != reference.target - || !proof.projects.Order(StringComparer.Ordinal).SequenceEqual(reference.projects.Order(StringComparer.Ordinal), StringComparer.Ordinal)) + || !proof.projects + .Order(StringComparer.Ordinal) + .SequenceEqual(reference.projects.Order(StringComparer.Ordinal), StringComparer.Ordinal) + ) { throw new InvalidDataException("Source certificate coverage differs for reference: " + reference.path); + } } } private static void RequireInputs(Certificate certificate) { if (certificate.sourceFiles is null || certificate.sourceSets is null || certificate.inputGroups is null - || certificate.inputs is null || certificate.examples is null || certificate.scriptReferences is null) + || certificate.inputs is null || certificate.examples is null || certificate.scriptReferences is null + ) { throw new InvalidDataException("Source certificate lacks its normalized input tables."); + } foreach (SourceFile file in certificate.sourceFiles) { if (file is null || string.IsNullOrWhiteSpace(file.path) || Path.IsPathRooted(file.path) - || file.path.IndexOfAny(['\\', ':', '\0']) >= 0 || file.path.Split('/').Any(static part => part is "." or "..")) + || file.path.IndexOfAny(['\\', ':', '\0']) >= 0 || file.path.Split('/').Any(static part => part is "." or "..") + ) { throw new InvalidDataException("Source certificate contains an invalid input path."); - if (file.identity != "missing") DocumentationStore.RequireHash(file.identity, "source file", allowGitTree: true); + } + if (file.identity != "missing") + { + DocumentationStore.RequireHash(file.identity, "source file", allowGitTree: true); + } } foreach (int[] set in certificate.sourceSets) { if (set is not { Length: > 0 } || set.Any(index => index < 0 || index >= certificate.sourceFiles.Length) - || set.Select(index => certificate.sourceFiles[index].path).Distinct(StringComparer.Ordinal).Count() != set.Length) + || set.Select(index => certificate.sourceFiles[index].path).Distinct(StringComparer.Ordinal).Count() != set.Length + ) { throw new InvalidDataException("Source certificate contains a missing or duplicated file reference."); + } } foreach (InputGroup group in certificate.inputGroups) { if (group is null || string.IsNullOrWhiteSpace(group.platform) || string.IsNullOrWhiteSpace(group.configuration) - || group.inputs is not { Length: > 0 }) + || group.inputs is not { Length: > 0 } + ) { throw new InvalidDataException("Source certificate has an incomplete execution input group."); + } DocumentationStore.RequireHash(group.reportIdentity, "input group report"); RequireProofs(group.inputs); } RequireProofs(certificate.inputs); foreach (Example example in certificate.examples) { - if (example?.contexts is not { Length: > 0 }) throw new InvalidDataException("Example evidence lacks execution contexts."); - foreach (Context context in example.contexts) RequireContext(context); + if (example?.contexts is not { Length: > 0 }) + { + throw new InvalidDataException("Example evidence lacks execution contexts."); + } + foreach (Context context in example.contexts) + { + RequireContext(context); + } + } + foreach (ScriptReference proof in certificate.scriptReferences) + { + RequireContext(proof); } - foreach (ScriptReference proof in certificate.scriptReferences) RequireContext(proof); foreach (Reference reference in certificate.references.Where(static reference => reference.model != "source-clr")) - if (!certificate.scriptReferences.Any(proof => proof.path == reference.path && proof.identity == reference.identity - && proof.model == reference.model && proof.configuration == reference.configuration)) + { + if (!certificate.scriptReferences.Any(proof => ( + proof.path == reference.path && proof.identity == reference.identity + && proof.model == reference.model && proof.configuration == reference.configuration + ))) { throw new InvalidDataException("Script reference lacks actual projection evidence."); + } + } void RequireProofs(InputProof[] proofs) { if (proofs.Any(proof => proof?.sourceSet is not int index || index < 0 || index >= certificate.sourceSets.Length)) + { throw new InvalidDataException("Source input proof references a missing source set."); + } } void RequireContext(Context context) { if (context?.inputGroup is not int index || index < 0 || index >= certificate.inputGroups.Length) + { throw new InvalidDataException("Source evidence references a missing execution input group."); + } InputGroup group = certificate.inputGroups[index]; if (context.platform != group.platform || context.configuration != group.configuration - || context.target != group.target || context.reportIdentity != group.reportIdentity) + || context.target != group.target || context.reportIdentity != group.reportIdentity + ) { throw new InvalidDataException("Source evidence references a different execution context."); + } } } @@ -189,7 +243,9 @@ private sealed record SourceFile( string path, string identity ); + private sealed record InputProof(int? sourceSet); + private record Context( string platform, string configuration, @@ -197,6 +253,7 @@ private record Context( string reportIdentity, int? inputGroup ); + private sealed record InputGroup( string platform, string configuration, @@ -204,7 +261,9 @@ private sealed record InputGroup( string reportIdentity, InputProof[] inputs ); + private sealed record Example(Context[] contexts); + private sealed record ScriptReference( string path, string identity, diff --git a/tools/Inno.Tooling.Documentation/DocumentationHit.cs b/tools/Inno.Tooling.Documentation/DocumentationHit.cs index cc9d4e3da..85071dc0f 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationHit.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationHit.cs @@ -55,18 +55,22 @@ string resource /// Gets the declared scripting scope when this result belongs to a script API. /// public string? scope { get; init; } + /// /// Gets the original symbol Markdown path, separately from its composed type page. /// public string? contentSource { get; init; } + /// /// Gets xml or manual for an exact API content unit, or null for ordinary guidance. /// public string? contentSourceKind { get; init; } + /// /// Gets the exact captured engine revision for the selected declaration. /// public string? declarationRevision { get; init; } + /// /// Gets actual compilation surfaces for the selected symbol, or the page for ordinary reads. /// diff --git a/tools/Inno.Tooling.Documentation/DocumentationPageInfo.cs b/tools/Inno.Tooling.Documentation/DocumentationPageInfo.cs index 28a9a8db9..658eb5bc2 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationPageInfo.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationPageInfo.cs @@ -65,10 +65,12 @@ public sealed record DocumentationPageInfo( /// Gets canonical composed Markdown shared by website rendering and snapshot reads. /// public string markdown { get; init; } = ""; + /// /// Gets the declared scripting scope, independent of the compilation surface. /// public string? scope { get; init; } + /// /// Gets the actual compilation surfaces available on this composed page. /// diff --git a/tools/Inno.Tooling.Documentation/DocumentationSnapshot.cs b/tools/Inno.Tooling.Documentation/DocumentationSnapshot.cs index 8f66b46c2..c7ba865fe 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationSnapshot.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationSnapshot.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Collections.Concurrent; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; @@ -68,24 +68,54 @@ public async Task ExportCatalogAsync(CancellationTok ObjectDisposedException.ThrowIf(m_disposed, this); cancellationToken.ThrowIfCancellationRequested(); if (m_expectedSourceTree is not null && m_expectedSourceTree != sourceTree) + { throw new InvalidOperationException("Cannot export a catalog bound to a different source tree."); + } var pages = new List(); foreach (string path in m_manifest.pages.Keys.Order(StringComparer.Ordinal)) { DocumentationPage page = await LoadAsync(m_manifest.pages[path].pageId, cancellationToken).ConfigureAwait(false); - pages.Add(new(page.metadata.uid, path, page.identity, page.title, page.metadata.kind, - page.metadata.owners, page.metadata.apiSurface, + pages.Add(new( + page.metadata.uid, + path, + page.identity, + page.title, + page.metadata.kind, + page.metadata.owners, + page.metadata.apiSurface, page.sections.ToDictionary(static section => section.anchor, static section => section.line, StringComparer.Ordinal), - page.symbols.ToDictionary(static symbol => symbol.id, - static symbol => new DocumentationSymbolInfo(symbol.anchor, symbol.signatureIdentity, symbol.code), StringComparer.Ordinal), - page.metadata.contracts, page.includes, page.codeBlocks, page.metadata.examples) { markdown = page.text, scope = page.metadata.apiScope, - surfaces = page.metadata.apiSurfaces ?? [], links = page.links }); - } - string contentIdentity = DocumentationMarkdown.Hash(string.Join('\n', pages.Select(static page => page.path + "\0" + page.contentIdentity))); - return new(identity, contentIdentity, m_manifest.binding.repository, m_manifest.binding.revision, - sourceTree, m_manifest.binding.toolingRevision, m_sourceEvidence is null ? "Unverified" : "Verified", - m_manifest.projects.ToDictionary(static project => project.name, static project => project.entry, StringComparer.Ordinal), pages, - m_manifest.references!) { sourceEvidenceIdentity = m_sourceEvidence?.identity, sourceFiles = m_manifest.sourceFiles! }; + page.symbols.ToDictionary( + static symbol => symbol.id, + static symbol => new DocumentationSymbolInfo(symbol.anchor, symbol.signatureIdentity, symbol.code), + StringComparer.Ordinal + ), + page.metadata.contracts, + page.includes, + page.codeBlocks, + page.metadata.examples + ) + { + markdown = page.text, + scope = page.metadata.apiScope, + surfaces = page.metadata.apiSurfaces ?? [], + links = page.links + }); + } + string contentIdentity = DocumentationMarkdown.Hash( + string.Join('\n', pages.Select(static page => page.path + "\0" + page.contentIdentity)) + ); + return new( + identity, + contentIdentity, + m_manifest.binding.repository, + m_manifest.binding.revision, + sourceTree, + m_manifest.binding.toolingRevision, + m_sourceEvidence is null ? "Unverified" : "Verified", + m_manifest.projects.ToDictionary(static project => project.name, static project => project.entry, StringComparer.Ordinal), + pages, + m_manifest.references! + ) { sourceEvidenceIdentity = m_sourceEvidence?.identity, sourceFiles = m_manifest.sourceFiles! }; } /// @@ -126,14 +156,20 @@ public async Task ReadReferenceAsync( ObjectDisposedException.ThrowIf(m_disposed, this); cancellationToken.ThrowIfCancellationRequested(); if (m_expectedSourceTree is not null && m_expectedSourceTree != sourceTree) + { throw new InvalidOperationException("Cannot read references bound to a different source tree."); + } if (!m_references.TryGetValue(path, out DocumentationReferenceInfo? reference)) + { throw new ArgumentException("Reference is absent from the selected snapshot: " + path, nameof(path)); + } DocumentationStore.RequireHash(reference.identity, "reference payload"); string file = PathBoundary.RequireUnlinkedPath(m_cache, Path.Combine(m_cache, "references", reference.identity, "reference.json")); byte[] bytes = await File.ReadAllBytesAsync(file, cancellationToken).ConfigureAwait(false); if (DocumentationMarkdown.Hash(bytes) != reference.identity) + { throw new InvalidDataException("Documentation reference integrity mismatch: " + path); + } return bytes; } @@ -192,7 +228,8 @@ public async Task QueryAsync( DocumentationResult result = await QueryCoreAsync(request, cancellationToken).ConfigureAwait(false); return m_sourceEvidence is null || result.status == "Mismatched" ? result : result with { - sourceApiStatus = "Verified", sourceEvidenceIdentity = m_sourceEvidence.identity + sourceApiStatus = "Verified", + sourceEvidenceIdentity = m_sourceEvidence.identity }; } @@ -204,62 +241,123 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(request); cancellationToken.ThrowIfCancellationRequested(); if (request.offset < 0 || request.limit is < 1 or > 100) + { throw new ArgumentException("Documentation offset must be nonnegative and limit must be between 1 and 100."); + } if (request.scope is not (null or "Runtime" or "Editor" or "Authoring")) + { throw new ArgumentException("Unknown declared scripting API scope."); + } if (m_expectedSourceTree is not null && m_expectedSourceTree != sourceTree) - return Result("Mismatched", "The selected documentation is bound to a different engine input tree. Select or prepare a matching snapshot."); + { + return Result( + "Mismatched", + "The selected documentation is bound to a different engine input tree. Select or prepare a matching snapshot." + ); + } if (request.project is not null && !m_manifest.projects.Any(project => project.name == request.project)) + { return Result("Missing", "Unknown project identity: " + request.project); + } if (request.operation == "status") - return Result("Ready", $"Bound to {m_manifest.binding.repository}@{m_manifest.binding.revision}; source tree {sourceTree}. A prepared snapshot does not certify a mutable checkout or source API."); + { + return Result( + "Ready", + $"Bound to {m_manifest.binding.repository}@{m_manifest.binding.revision}; source tree {sourceTree}. A prepared snapshot does not certify a mutable checkout or source API." + ); + } if (request.operation == "resource") + { return await ResourceAsync(request, cancellationToken).ConfigureAwait(false); + } if (request.operation == "search") + { return await SearchAsync(request, cancellationToken).ConfigureAwait(false); + } if (request.operation == "symbol") + { return await SymbolAsync(request, cancellationToken).ConfigureAwait(false); + } if (request.operation != "read") + { throw new ArgumentException("Unknown documentation query operation: " + request.operation); + } string? pageId = request.value; if (pageId is null && request.project is not null) + { pageId = m_manifest.projects.Single(project => project.name == request.project).entry; + } if (pageId is null) + { return Result("Missing", "Specify a page identity or a project with an authoritative entry."); + } if (!m_paths.ContainsKey(pageId)) { if (!m_manifest.pages.TryGetValue(pageId.Replace('\\', '/'), out DocumentationPageReference? reference)) + { return Result("Missing", "Unknown page in this snapshot: " + pageId); + } pageId = reference.pageId; } DocumentationPage page = await LoadAsync(pageId, cancellationToken).ConfigureAwait(false); - DocumentationSection? section = request.section is null ? null : page.sections.SingleOrDefault(candidate => candidate.anchor == request.section); + DocumentationSection? section = request.section is null + ? null + : page.sections.SingleOrDefault(candidate => candidate.anchor == request.section); if (request.section is not null && section is null) { DocumentationSymbol? symbol = page.symbols.SingleOrDefault(candidate => candidate.anchor == request.section); if (symbol is not null) - return await SymbolAsync(new("symbol", symbol.id, page.metadata.owners.Single(), page.metadata.apiSurface), cancellationToken).ConfigureAwait(false); + { + return await SymbolAsync( + new("symbol", symbol.id, page.metadata.owners.Single(), page.metadata.apiSurface), + cancellationToken + ).ConfigureAwait(false); + } return Result("Missing", "Unknown section: " + request.section); } string text = section is null ? page.text : page.text[section.start..section.end]; if (request.offset > text.Length) + { throw new ArgumentOutOfRangeException(nameof(request), "Continuation offset exceeds the selected content."); + } int end = Math.Min(text.Length, request.offset + C_MAX_CONTENT); if (end < text.Length) { int newline = text.LastIndexOf('\n', end - 1, end - request.offset); if (newline >= request.offset) + { end = newline + 1; + } if (char.IsHighSurrogate(text[end - 1])) + { end--; + } } var continuations = Contracts(page); if (end < text.Length) - continuations.Insert(0, new(pageId, section?.anchor, end, "Continue the original content before treating this selection as complete.")); - return new(end < text.Length || continuations.Count != 0 ? "Partial" : "Found", identity, "Unverified", + { + continuations.Insert( + 0, + new(pageId, section?.anchor, end, "Continue the original content before treating this selection as complete.") + ); + } + return new( + end < text.Length || continuations.Count != 0 ? "Partial" : "Found", + identity, + "Unverified", "Original Markdown from the selected snapshot. Related contracts and continuations remain explicit.", - [Hit(page, section?.anchor ?? "", section?.line ?? 1, null, "Exact page or section", end == text.Length ? "CompleteUnit" : "Partial", text[request.offset..end])], continuations, - end < text.Length ? request with { offset = end } : null); + [Hit( + page, + section?.anchor ?? "", + section?.line ?? 1, + null, + "Exact page or section", + end == text.Length ? "CompleteUnit" : "Partial", + text[request.offset..end] + )], + continuations, + end < text.Length ? request with { offset = end } : null + ); } /// @@ -268,7 +366,9 @@ CancellationToken cancellationToken public void Dispose() { if (m_disposed) + { return; + } m_disposed = true; m_reading.Dispose(); } @@ -280,36 +380,55 @@ CancellationToken cancellation ArgumentException.ThrowIfNullOrWhiteSpace(request.value); if (m_symbols.TryGetValue(request.value, out DocumentationSymbolReference[]? exact)) { - DocumentationSymbolReference[] matches = exact.Where(symbol => (request.project is null || symbol.project == request.project) - && (request.surface is null || symbol.surface == request.surface || (symbol.surfaces ?? []).Contains(request.surface, StringComparer.Ordinal)) - && Scope(m_manifest.pages[m_paths[symbol.pageId]].metadata, request)).ToArray(); + DocumentationSymbolReference[] matches = exact.Where(symbol => ( + (request.project is null || symbol.project == request.project) + && (request.surface is null + || symbol.surface == request.surface + || (symbol.surfaces ?? []).Contains(request.surface, StringComparer.Ordinal)) + && Scope(m_manifest.pages[m_paths[symbol.pageId]].metadata, request) + )).ToArray(); var symbolHits = new List(); foreach (DocumentationSymbolReference symbol in matches.Skip(request.offset).Take(request.limit)) { DocumentationPage page = await LoadAsync(symbol.pageId, cancellation).ConfigureAwait(false); symbolHits.Add(Hit(page, symbol.anchor, 1, symbol.id, "Exact qualified symbol", "Excerpt", symbol.id)); } - return Result(symbolHits.Count == 0 ? "Empty" : "Found", "Exact symbol navigation; use symbol or resource to read its contract.", symbolHits) - with { nextRequest = request.offset + symbolHits.Count < matches.Length ? request with { offset = request.offset + symbolHits.Count } : null }; + return Result( + symbolHits.Count == 0 ? "Empty" : "Found", + "Exact symbol navigation; use symbol or resource to read its contract.", + symbolHits + ) + with + { + nextRequest = request.offset + symbolHits.Count < matches.Length + ? request with { offset = request.offset + symbolHits.Count } + : null + }; } string[] tokens = DocumentationMarkdown.Tokens(request.value); if (tokens.Length == 0) + { return Result("Empty", "No searchable terms."); + } IEnumerable? selected = null; Dictionary terms = m_terms.Value; foreach (string token in tokens) { cancellation.ThrowIfCancellationRequested(); if (!terms.TryGetValue(token, out int[]? postings)) + { return Result("Empty", "No matching documentation. No content was inferred."); + } selected = selected is null ? postings : selected.Intersect(postings); } var ranked = selected!.Select(index => m_manifest.search[index]) .Where(entry => Scope(m_manifest.pages[m_paths[entry.pageId]].metadata, request)) .Select(entry => (entry, match: Score(entry, request.value, tokens))) - .OrderByDescending(static pair => pair.match.score).ThenByDescending(static pair => pair.match.taskGuide) + .OrderByDescending(static pair => pair.match.score) + .ThenByDescending(static pair => pair.match.taskGuide) .ThenBy(static pair => pair.entry.pageId, StringComparer.Ordinal) - .ThenBy(static pair => pair.entry.section, StringComparer.Ordinal).ToArray(); + .ThenBy(static pair => pair.entry.section, StringComparer.Ordinal) + .ToArray(); var hits = new List(); foreach (var pair in ranked.Skip(request.offset).Take(request.limit)) { @@ -319,19 +438,29 @@ CancellationToken cancellation string excerpt = body[..Math.Min(body.Length, 320)]; hits.Add(Hit(page, section.anchor, section.line, null, pair.match.reason, "Excerpt", excerpt)); } - return Result(hits.Count == 0 ? "Empty" : "Found", - $"{ranked.Length} matching sections; offset {request.offset}, returned {hits.Count}. Search excerpts are navigation, not complete contracts.", hits) - with { nextRequest = request.offset + hits.Count < ranked.Length ? request with { offset = request.offset + hits.Count } : null }; + return Result( + hits.Count == 0 ? "Empty" : "Found", + $"{ranked.Length} matching sections; offset {request.offset}, returned {hits.Count}. Search excerpts are navigation, not complete contracts.", + hits + ) + with + { + nextRequest = request.offset + hits.Count < ranked.Length ? request with { offset = request.offset + hits.Count } : null + }; } private static Dictionary CreateSearchPostings(DocumentationManifest manifest) - => manifest.search.SelectMany(( - entry, - index - ) => entry.tokens.Select(token => (token, index))) + => manifest.search + .SelectMany(( + entry, + index + ) => entry.tokens.Select(token => (token, index))) .GroupBy(static pair => pair.token, StringComparer.Ordinal) - .ToDictionary(static group => group.Key, - static group => group.Select(static pair => pair.index).Distinct().ToArray(), StringComparer.Ordinal); + .ToDictionary( + static group => group.Key, + static group => group.Select(static pair => pair.index).Distinct().ToArray(), + StringComparer.Ordinal + ); private (int score, bool taskGuide, string reason) Score( DocumentationSearchEntry entry, @@ -345,17 +474,22 @@ string[] tokens bool exactProject = metadata.owners.Contains(query, StringComparer.OrdinalIgnoreCase); bool exactAlias = metadata.aliases.Contains(query, StringComparer.OrdinalIgnoreCase); bool taskGuide = tokens.Length > 1 && query.Trim().Any(char.IsWhiteSpace) && matched == tokens.Length - && metadata.kind is "how-to" or "tutorial"; + && metadata.kind is "how-to" or "tutorial"; int score = (exactHeading ? 100 : 0) - + (entry.title.Contains(query, StringComparison.OrdinalIgnoreCase) ? 60 : 0) - + (exactAlias ? 80 : 0) + (exactProject ? 90 : 0) - + 50 * matched / tokens.Length; - string reason = exactHeading ? "Exact heading" - : exactProject ? "Exact project identity" - : exactAlias ? "Exact query alias" - : matched == tokens.Length ? "All query terms in heading" - : matched > 0 ? "Heading and indexed body terms" - : "Indexed body terms"; + + (entry.title.Contains(query, StringComparison.OrdinalIgnoreCase) ? 60 : 0) + + (exactAlias ? 80 : 0) + (exactProject ? 90 : 0) + + 50 * matched / tokens.Length; + string reason = exactHeading + ? "Exact heading" + : exactProject + ? "Exact project identity" + : exactAlias + ? "Exact query alias" + : matched == tokens.Length + ? "All query terms in heading" + : matched > 0 + ? "Heading and indexed body terms" + : "Indexed body terms"; return (score, taskGuide, reason); } @@ -365,25 +499,43 @@ CancellationToken cancellation ) { ArgumentException.ThrowIfNullOrWhiteSpace(request.value); DocumentationSymbolReference[] matches = m_symbols.GetValueOrDefault(request.value, []) - .Where(symbol => (request.project is null || symbol.project == request.project) - && (request.surface is null || symbol.surface == request.surface || (symbol.surfaces ?? []).Contains(request.surface, StringComparer.Ordinal)) - && Scope(m_manifest.pages[m_paths[symbol.pageId]].metadata, request)).ToArray(); + .Where(symbol => ( + (request.project is null || symbol.project == request.project) + && (request.surface is null + || symbol.surface == request.surface + || (symbol.surfaces ?? []).Contains(request.surface, StringComparer.Ordinal)) + && Scope(m_manifest.pages[m_paths[symbol.pageId]].metadata, request) + )) + .ToArray(); if (matches.Length != 1) { DocumentationSymbolReference[] candidates = matches.Length > 1 ? matches : m_manifest.symbols - .Where(symbol => symbol.id.Contains(request.value, StringComparison.OrdinalIgnoreCase) + .Where(symbol => ( + symbol.id.Contains(request.value, StringComparison.OrdinalIgnoreCase) && (request.project is null || symbol.project == request.project) - && (request.surface is null || symbol.surface == request.surface || (symbol.surfaces ?? []).Contains(request.surface, StringComparer.Ordinal)) - && Scope(m_manifest.pages[m_paths[symbol.pageId]].metadata, request)).ToArray(); + && (request.surface is null + || symbol.surface == request.surface + || (symbol.surfaces ?? []).Contains(request.surface, StringComparer.Ordinal)) + && Scope(m_manifest.pages[m_paths[symbol.pageId]].metadata, request) + )) + .ToArray(); var hits = new List(); foreach (DocumentationSymbolReference candidate in candidates.Skip(request.offset).Take(request.limit)) { DocumentationPage page = await LoadAsync(candidate.pageId, cancellation).ConfigureAwait(false); hits.Add(Hit(page, candidate.anchor, 1, candidate.id, "Qualified symbol candidate", "Excerpt", candidate.id)); } - return Result(candidates.Length == 0 ? "Missing" : "Ambiguous", - $"{candidates.Length} candidates; offset {request.offset}, returned {hits.Count}. Qualify the exact XML ID, project and surface. No overload was chosen.", hits) - with { nextRequest = request.offset + hits.Count < candidates.Length ? request with { offset = request.offset + hits.Count } : null }; + return Result( + candidates.Length == 0 ? "Missing" : "Ambiguous", + $"{candidates.Length} candidates; offset {request.offset}, returned {hits.Count}. Qualify the exact XML ID, project and surface. No overload was chosen.", + hits + ) + with + { + nextRequest = request.offset + hits.Count < candidates.Length + ? request with { offset = request.offset + hits.Count } + : null + }; } DocumentationPage owner = await LoadAsync(matches[0].pageId, cancellation).ConfigureAwait(false); DocumentationSymbol selected = owner.symbols.Single(symbol => symbol.id == request.value); @@ -393,12 +545,27 @@ CancellationToken cancellation string text = independentPage ? owner.text : selected.declaration; if (text.Length > C_MAX_CONTENT) { - continuations.Insert(0, new(owner.metadata.uid, independentPage ? null : section.anchor, 0, "Read the complete declaration and its constraints.")); - return new("Navigation", identity, "Unverified", "The symbol content requires an explicit page or section read.", [], continuations); + continuations.Insert( + 0, + new(owner.metadata.uid, independentPage ? null : section.anchor, 0, "Read the complete declaration and its constraints.") + ); + return new( + "Navigation", + identity, + "Unverified", + "The symbol content requires an explicit page or section read.", + [], + continuations + ); } - return new(continuations.Count == 0 ? "Found" : "Partial", identity, "Unverified", + return new( + continuations.Count == 0 ? "Found" : "Partial", + identity, + "Unverified", "Exact documented declaration; associated contracts remain explicit. Symbol presence is not source API verification.", - [Hit(owner, selected.anchor, section.line, selected.id, "Exact qualified symbol", "CompleteUnit", text)], continuations); + [Hit(owner, selected.anchor, section.line, selected.id, "Exact qualified symbol", "CompleteUnit", text)], + continuations + ); } private async Task ResourceAsync( @@ -406,15 +573,30 @@ private async Task ResourceAsync( CancellationToken cancellation ) { if (!Uri.TryCreate(request.value, UriKind.Absolute, out Uri? resource) || resource.Scheme != "inno-doc" - || resource.Host != "innoengine" || resource.Query.Length != 0 || resource.UserInfo.Length != 0) + || resource.Host != "innoengine" || resource.Query.Length != 0 || resource.UserInfo.Length != 0 + ) { throw new ArgumentException("Invalid documentation resource URI."); + } string[] parts = resource.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 4 || parts[0] != "snapshots" || parts[2] != "pages") + { throw new ArgumentException("Invalid documentation resource path."); + } if (parts[1] != identity) + { return Result("Mismatched", "The resource belongs to a different snapshot. Open that exact generation explicitly."); - return await QueryAsync(new("read", Uri.UnescapeDataString(parts[3]), section: resource.Fragment.Length == 0 - ? null : Uri.UnescapeDataString(resource.Fragment[1..]), offset: request.offset), cancellation).ConfigureAwait(false); + } + return await QueryAsync( + new( + "read", + Uri.UnescapeDataString(parts[3]), + section: resource.Fragment.Length == 0 + ? null + : Uri.UnescapeDataString(resource.Fragment[1..]), + offset: request.offset + ), + cancellation + ).ConfigureAwait(false); } private async Task LoadAsync( @@ -423,7 +605,9 @@ CancellationToken cancellation ) { cancellation.ThrowIfCancellationRequested(); if (m_pages.TryGetValue(pageId, out DocumentationPage? loaded)) + { return loaded; + } string path = m_paths[pageId]; DocumentationPageReference reference = m_manifest.pages[path]; DocumentationStore.RequireHash(reference.key, "page payload"); @@ -432,10 +616,14 @@ CancellationToken cancellation string payload = PathBoundary.RequireUnlinkedPath(m_cache, Path.Combine(m_cache, "pages", reference.key, "page.json")); byte[] bytes = await File.ReadAllBytesAsync(payload, cancellation).ConfigureAwait(false); if (DocumentationMarkdown.Hash(bytes) != reference.payloadIdentity) + { throw new InvalidDataException("Corrupt documentation page payload. Explicitly refresh its index: " + path); + } DocumentationPage page = DocumentationStore.Deserialize(bytes); if (page.path != path || page.metadata.uid != pageId) + { throw new InvalidDataException("Documentation page identity mismatch: " + path); + } return m_pages.GetOrAdd(pageId, page); } @@ -456,12 +644,26 @@ private DocumentationHit Hit( string text ) { DocumentationApiOrigin? origin = symbol is null ? null : m_origins.GetValueOrDefault(page.path + "\0" + symbol); - return new(page.metadata.uid, page.path, section, line, page.metadata.owners, page.metadata.apiSurface, symbol, reason, completeness, text, + return new( + page.metadata.uid, + page.path, + section, + line, + page.metadata.owners, + page.metadata.apiSurface, + symbol, + reason, + completeness, + text, "inno-doc://innoengine/snapshots/" + identity + "/pages/" + Uri.EscapeDataString(page.metadata.uid) - + (section.Length == 0 ? "" : "#" + Uri.EscapeDataString(section))) + + (section.Length == 0 ? "" : "#" + Uri.EscapeDataString(section)) + ) { - scope = page.metadata.apiScope, contentSource = origin?.path, contentSourceKind = origin?.source, - declarationRevision = origin?.revision, surfaces = origin?.surfaces ?? page.metadata.apiSurfaces ?? [] + scope = page.metadata.apiScope, + contentSource = origin?.path, + contentSourceKind = origin?.source, + declarationRevision = origin?.revision, + surfaces = origin?.surfaces ?? page.metadata.apiSurfaces ?? [] }; } @@ -475,6 +677,8 @@ private static bool Scope( DocumentationMetadata metadata, DocumentationRequest request ) => (request.project is null || metadata.owners.Contains(request.project, StringComparer.Ordinal)) - && (request.surface is null || metadata.apiSurface == request.surface || (metadata.apiSurfaces ?? []).Contains(request.surface, StringComparer.Ordinal)) - && (request.scope is null || metadata.apiScope == request.scope); + && (request.surface is null + || metadata.apiSurface == request.surface + || (metadata.apiSurfaces ?? []).Contains(request.surface, StringComparer.Ordinal)) + && (request.scope is null || metadata.apiScope == request.scope); } diff --git a/tools/Inno.Tooling.Documentation/DocumentationStore.cs b/tools/Inno.Tooling.Documentation/DocumentationStore.cs index 7002cbb22..1f1999a32 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationStore.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationStore.cs @@ -23,10 +23,18 @@ public static class DocumentationStore // Snapshot format compatibility is a parser/index protocol, not a compilation artifact identity. // MVID includes build provenance and can differ between adapters compiling identical parser sources. internal static string schema { get; } = CreateSchemaIdentity(); + private static string parserSchema { get; } = CreateSchemaIdentity( - "DocumentationMarkdown.cs", "DocumentationPage.cs", "DocumentationCodeBlockInfo.cs", - "DocumentationExampleContext.cs", "DocumentationApiComposition.cs", "DocumentationApiFragment.cs", - "DocumentationApiPresentation.cs", "DocumentationXml.cs", "Inno.Tooling.Documentation.csproj"); + "DocumentationMarkdown.cs", + "DocumentationPage.cs", + "DocumentationCodeBlockInfo.cs", + "DocumentationExampleContext.cs", + "DocumentationApiComposition.cs", + "DocumentationApiFragment.cs", + "DocumentationApiPresentation.cs", + "DocumentationXml.cs", + "Inno.Tooling.Documentation.csproj" + ); /// /// Explicitly scans a Docs checkout and publishes a consistent generation using reusable parsed pages. @@ -76,11 +84,17 @@ public static async Task IndexAsync( string content = PathBoundary.RequireUnlinkedPath(root, Path.Combine(root, "content", "en")); string output = PathBoundary.RequireUnlinkedPath(Path.GetFullPath(workspaceRoot), Path.GetFullPath(cacheRoot)); if (output == root || output.StartsWith(content + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { throw new ArgumentException("Documentation cache must be outside authored content.", nameof(cacheRoot)); + } var publisher = new BuildCachePublisher(output, BuildCacheArtifactRole.ImmutableArtifact); BuildCacheOwnerCatalog.Register(workspaceRoot, output, "documentation-snapshots", publisher.role, cancellationToken); using FileLease activity = await publisher.AcquireUseAsync(cancellationToken).ConfigureAwait(false); - using FileLease writing = await FileLease.AcquireAsync(Path.Combine(output, "writer.lock"), Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + using FileLease writing = await FileLease.AcquireAsync( + Path.Combine(output, "writer.lock"), + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); string bindingPath = PathBoundary.RequireUnlinkedPath(root, Path.Combine(root, "reference", "engine.lock.json")); byte[] bindingBytes = File.ReadAllBytes(bindingPath); DocumentationBinding binding = Deserialize(bindingBytes); @@ -89,15 +103,28 @@ public static async Task IndexAsync( string projectPath = PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, binding.projectManifest)); byte[] projectBytes = File.ReadAllBytes(projectPath); if (DocumentationMarkdown.Hash(projectBytes) != binding.projectManifestIdentity) + { throw new InvalidDataException("Project manifest does not match the engine binding."); + } DocumentationProject[] projects = Deserialize(projectBytes); - DocumentationReferenceStore.Prepared references = await DocumentationReferenceStore.PrepareAsync(root, output, - binding, projects, projectBytes, publisher, cancellationToken).ConfigureAwait(false); + DocumentationReferenceStore.Prepared references = await DocumentationReferenceStore.PrepareAsync( + root, + output, + binding, + projects, + projectBytes, + publisher, + cancellationToken + ).ConfigureAwait(false); DocumentationManifest? previous = TryReadCurrent(output); var reusable = previous?.parserSchema == parserSchema - ? previous.pages.Values.ToDictionary(static page => page.key, StringComparer.Ordinal) - : new Dictionary(StringComparer.Ordinal); - var raw = EnumerateContent(content).ToDictionary(path => Path.GetRelativePath(root, path).Replace('\\', '/'), File.ReadAllText, StringComparer.Ordinal); + ? previous.pages.Values.ToDictionary(static page => page.key, StringComparer.Ordinal) + : new Dictionary(StringComparer.Ordinal); + var raw = EnumerateContent(content).ToDictionary( + path => Path.GetRelativePath(root, path).Replace('\\', '/'), + File.ReadAllText, + StringComparer.Ordinal + ); DocumentationComposedContent composed = DocumentationApiComposition.Prepare(root, binding, raw); string[] sources = composed.pages.Keys.ToArray(); var prepared = new (DocumentationPage page, DocumentationPageReference reference)[sources.Length]; @@ -106,49 +133,61 @@ public static async Task IndexAsync( RecordPhase("SetupAndLockWait"); // Each content-addressed page has its own output and lease. Keep publication serialized, // bound filesystem pressure, and drain all preparation before validating the complete catalog. - await Parallel.ForEachAsync(Enumerable.Range(0, sources.Length), new ParallelOptions - { - MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), - CancellationToken = cancellationToken - }, async ( - int index, - CancellationToken cancellation - ) => - { - cancellation.ThrowIfCancellationRequested(); - string path = sources[index]; - string relative = path; - string text = composed.pages[path]; - string key = DocumentationMarkdown.Hash(parserSchema + "\n" + relative + "\n" + text); - string directory = Path.Combine(output, "pages", key); - string payload = PathBoundary.RequireUnlinkedPath(output, Path.Combine(directory, "page.json")); - string lease = Path.Combine(output, "leases", key + ".lock"); - using FileLease pageWriting = await FileLease.AcquireAsync(lease, Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false); - DocumentationPage? page = null; - byte[]? bytes = null; - if (reusable.TryGetValue(key, out DocumentationPageReference? known) && File.Exists(payload)) + await Parallel.ForEachAsync( + Enumerable.Range(0, sources.Length), + new ParallelOptions { - bytes = File.ReadAllBytes(payload); - if (DocumentationMarkdown.Hash(bytes) == known.payloadIdentity) - page = Deserialize(bytes); - if (page?.text != text || page.path != relative || page.identity != DocumentationMarkdown.Hash(text)) - page = null; - } - if (page is null) + MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), + CancellationToken = cancellationToken + }, + async ( + int index, + CancellationToken cancellation + ) => { - long started = Stopwatch.GetTimestamp(); - page = DocumentationMarkdown.Parse(relative, text); - Interlocked.Add(ref parsingTicks, Stopwatch.GetTimestamp() - started); - bytes = JsonSerializer.SerializeToUtf8Bytes(page, json); cancellation.ThrowIfCancellationRequested(); - AtomicFile.WriteAllBytes(payload, bytes); - Interlocked.Increment(ref parsed); + string path = sources[index]; + string relative = path; + string text = composed.pages[path]; + string key = DocumentationMarkdown.Hash(parserSchema + "\n" + relative + "\n" + text); + string directory = Path.Combine(output, "pages", key); + string payload = PathBoundary.RequireUnlinkedPath(output, Path.Combine(directory, "page.json")); + string lease = Path.Combine(output, "leases", key + ".lock"); + using FileLease pageWriting = await FileLease.AcquireAsync( + lease, + Timeout.InfiniteTimeSpan, + cancellation + ).ConfigureAwait(false); + DocumentationPage? page = null; + byte[]? bytes = null; + if (reusable.TryGetValue(key, out DocumentationPageReference? known) && File.Exists(payload)) + { + bytes = File.ReadAllBytes(payload); + if (DocumentationMarkdown.Hash(bytes) == known.payloadIdentity) + { + page = Deserialize(bytes); + } + if (page?.text != text || page.path != relative || page.identity != DocumentationMarkdown.Hash(text)) + { + page = null; + } + } + if (page is null) + { + long started = Stopwatch.GetTimestamp(); + page = DocumentationMarkdown.Parse(relative, text); + Interlocked.Add(ref parsingTicks, Stopwatch.GetTimestamp() - started); + bytes = JsonSerializer.SerializeToUtf8Bytes(page, json); + cancellation.ThrowIfCancellationRequested(); + AtomicFile.WriteAllBytes(payload, bytes); + Interlocked.Increment(ref parsed); + } + long registrationStarted = Stopwatch.GetTimestamp(); + publisher.EnsureImmutableRegistration(directory, lease, [], null, cancellation); + Interlocked.Add(ref registrationTicks, Stopwatch.GetTimestamp() - registrationStarted); + prepared[index] = (page, new(page.metadata.uid, key, DocumentationMarkdown.Hash(bytes!), page.metadata)); } - long registrationStarted = Stopwatch.GetTimestamp(); - publisher.EnsureImmutableRegistration(directory, lease, [], null, cancellation); - Interlocked.Add(ref registrationTicks, Stopwatch.GetTimestamp() - registrationStarted); - prepared[index] = (page, new(page.metadata.uid, key, DocumentationMarkdown.Hash(bytes!), page.metadata)); - }).ConfigureAwait(false); + ).ConfigureAwait(false); var pages = new List(prepared.Length); foreach (var item in prepared) { @@ -156,7 +195,9 @@ CancellationToken cancellation entries.Add(item.page.path, item.reference); } if (pages.Count == 0) + { throw new InvalidDataException("The selected Docs checkout has no content. Prepare a documentation source before querying."); + } RecordPhase("PagePreparation"); // Worker totals overlap; PagePreparation is the elapsed wall time, not their sum. timings.Add("MarkdownParsing", parsingTicks * 1000d / Stopwatch.Frequency); @@ -164,27 +205,53 @@ CancellationToken cancellation // The source manifest supplies project facts; authored page metadata supplies each canonical entry. // The complete graph remains reference provenance. Platform implementation projects // do not acquire reader entries, API pages or query ownership in cross-platform docs. - projects = projects.Where(project => !project.path.StartsWith("platforms/", StringComparison.Ordinal)).Select(project => project with - { - entry = pages.Where(page => page.metadata.kind == "project" && page.metadata.owners.Contains(project.name, StringComparer.Ordinal)) - .Select(static page => page.metadata.uid).SingleOrDefault() - }).ToArray(); + projects = projects + .Where(project => !project.path.StartsWith("platforms/", StringComparison.Ordinal)) + .Select(project => project with + { + entry = pages + .Where(page => page.metadata.kind == "project" && page.metadata.owners.Contains(project.name, StringComparer.Ordinal)) + .Select(static page => page.metadata.uid) + .SingleOrDefault() + }) + .ToArray(); DocumentationCatalog.Validate(root, pages, projects); RecordPhase("CatalogValidation"); var search = pages.SelectMany(page => page.sections.Select(section => { string body = DocumentationMarkdown.OwnText(page, section); string terms = section.title + " " + body + " " + string.Join(' ', page.metadata.aliases) - + " " + string.Join(' ', page.metadata.owners); - return new DocumentationSearchEntry(page.metadata.uid, section.anchor, section.title, - body[..Math.Min(body.Length, 320)], DocumentationMarkdown.Tokens(terms)); + + " " + string.Join(' ', page.metadata.owners); + return new DocumentationSearchEntry( + page.metadata.uid, + section.anchor, + section.title, + body[..Math.Min(body.Length, 320)], + DocumentationMarkdown.Tokens(terms) + ); })).ToArray(); var origins = composed.origins.ToDictionary(origin => origin.page + "\0" + origin.id, StringComparer.Ordinal); var symbols = pages.SelectMany(page => page.symbols.Select(symbol => new DocumentationSymbolReference( - page.metadata.owners.Single(), page.metadata.apiSurface!, symbol.id, page.metadata.uid, symbol.anchor, - origins.GetValueOrDefault(page.path + "\0" + symbol.id)?.surfaces))).ToArray(); - var manifest = new DocumentationManifest("", schema, parserSchema, binding, entries, projects, search, symbols, references.references, - composed.inputs, composed.origins); + page.metadata.owners.Single(), + page.metadata.apiSurface!, + symbol.id, + page.metadata.uid, + symbol.anchor, + origins.GetValueOrDefault(page.path + "\0" + symbol.id)?.surfaces + ))).ToArray(); + var manifest = new DocumentationManifest( + "", + schema, + parserSchema, + binding, + entries, + projects, + search, + symbols, + references.references, + composed.inputs, + composed.origins + ); string identity = DocumentationMarkdown.Hash(JsonSerializer.SerializeToUtf8Bytes(manifest, json)); manifest = manifest with { identity = identity }; string generation = Path.Combine(output, "generations", identity); @@ -193,11 +260,17 @@ CancellationToken cancellation // Recheck actual contents, including additions and same-length timestamp-preserving edits. string[] current = EnumerateContent(content).Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')).ToArray(); if (!current.SequenceEqual(raw.Keys.Order(StringComparer.Ordinal), StringComparer.Ordinal) - || composed.inputs.Any(input => !File.Exists(Path.Combine(root, input.Key)) - || DocumentationMarkdown.Hash(File.ReadAllText(Path.Combine(root, input.Key))) != input.Value) + || composed.inputs.Any(input => ( + !File.Exists(Path.Combine(root, input.Key)) + || DocumentationMarkdown.Hash(File.ReadAllText(Path.Combine(root, input.Key))) != input.Value + )) || !File.ReadAllBytes(bindingPath).SequenceEqual(bindingBytes) - || !File.ReadAllBytes(projectPath).SequenceEqual(projectBytes)) - throw new IOException("Documentation inputs changed during preparation. The previous snapshot remains selected; refresh a stable source."); + || !File.ReadAllBytes(projectPath).SequenceEqual(projectBytes) + ) { + throw new IOException( + "Documentation inputs changed during preparation. The previous snapshot remains selected; refresh a stable source." + ); + } cancellationToken.ThrowIfCancellationRequested(); DocumentationReferenceStore.Verify(references); RecordPhase("FreshnessValidation"); @@ -206,22 +279,45 @@ CancellationToken cancellation // Immutable CI payloads deliberately omit process-local ownership and leases. // Adopt an unchanged restored generation without rewriting it or waiting on // existing readers of a generation that is already registered locally. - using FileLease? restored = File.Exists(generationLease) ? null + using FileLease? restored = File.Exists(generationLease) + ? null : await FileLease.AcquireAsync(generationLease, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); - publisher.EnsureImmutableRegistration(generation, generationLease, + publisher.EnsureImmutableRegistration( + generation, + generationLease, entries.Values.Select(page => Path.Combine(output, "pages", page.key)) .Concat(references.references.Select(reference => Path.Combine(output, "references", reference.identity))) - .Distinct(StringComparer.Ordinal).ToArray(), null, cancellationToken); - return Finish($"Confirmed {pages.Count} pages; parsed {parsed}, reused {pages.Count - parsed}. Existing generation retained without rewriting its manifest."); + .Distinct(StringComparer.Ordinal) + .ToArray(), + null, + cancellationToken + ); + return Finish( + $"Confirmed {pages.Count} pages; parsed {parsed}, reused {pages.Count - parsed}. Existing generation retained without rewriting its manifest." + ); } - using FileLease publishing = await FileLease.AcquireAsync(generationLease, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + using FileLease publishing = await FileLease.AcquireAsync( + generationLease, + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); AtomicFile.WriteAllBytes(Path.Combine(generation, "manifest.json"), JsonSerializer.SerializeToUtf8Bytes(manifest, json)); - publisher.Record(generation, generationLease, entries.Values.Select(page => Path.Combine(output, "pages", page.key)) - .Concat(references.references.Select(reference => Path.Combine(output, "references", reference.identity))).Distinct(StringComparer.Ordinal).ToArray(), - "documentation", null, cancellationToken); + publisher.Record( + generation, + generationLease, + entries.Values.Select(page => Path.Combine(output, "pages", page.key)) + .Concat(references.references.Select(reference => Path.Combine(output, "references", reference.identity))) + .Distinct(StringComparer.Ordinal) + .ToArray(), + "documentation", + null, + cancellationToken + ); // Cancellation is observed before this commit point; selection cannot expose a partial generation. AtomicFile.WriteAllBytes(Path.Combine(output, "current.json"), JsonSerializer.SerializeToUtf8Bytes(identity)); - return Finish($"Published {pages.Count} pages; parsed {parsed}, reused {pages.Count - parsed}. No source API verification was performed."); + return Finish( + $"Published {pages.Count} pages; parsed {parsed}, reused {pages.Count - parsed}. No source API verification was performed." + ); void RecordPhase(string name) { @@ -279,12 +375,25 @@ public static async Task OpenAsync( PathBoundary.RequireUnlinkedPath(output, output); string activityPath = PathBoundary.RequireUnlinkedPath(output, Path.Combine(output, "owner.lock")); if (!File.Exists(activityPath)) - throw new FileNotFoundException("No prepared documentation snapshot. Run docs index with an explicit documentation source.", activityPath); - using FileLease activity = await FileLease.AcquireSharedAsync(activityPath, Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); - string identity = snapshot ?? Deserialize(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(output, Path.Combine(output, "current.json")))); + { + throw new FileNotFoundException( + "No prepared documentation snapshot. Run docs index with an explicit documentation source.", + activityPath + ); + } + using FileLease activity = await FileLease.AcquireSharedAsync( + activityPath, + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); + string identity = snapshot + ?? Deserialize(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(output, Path.Combine(output, "current.json")))); RequireHash(identity, "snapshot"); - FileLease reading = await FileLease.AcquireSharedAsync(PathBoundary.RequireUnlinkedPath(output, - Path.Combine(output, "leases", identity + ".lock")), Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + FileLease reading = await FileLease.AcquireSharedAsync( + PathBoundary.RequireUnlinkedPath(output, Path.Combine(output, "leases", identity + ".lock")), + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); try { DocumentationManifest manifest = ReadManifest(output, identity); @@ -308,27 +417,38 @@ internal static void RequireHash( bool allowGitTree = false ) { if (value is null || (value.Length != 64 && (!allowGitTree || value.Length != 40)) - || value.Any(static character => !char.IsAsciiHexDigitLower(character))) + || value.Any(static character => !char.IsAsciiHexDigitLower(character)) + ) { throw new InvalidDataException("Invalid " + label + " identity."); + } } private static string[] EnumerateContent(string content) - => PathBoundary.EnumerateFiles(content).Where(static path => path.EndsWith(".md", StringComparison.Ordinal)) - .OrderBy(path => Path.GetRelativePath(content, path).Replace('\\', '/'), StringComparer.Ordinal).ToArray(); + => PathBoundary.EnumerateFiles(content) + .Where(static path => path.EndsWith(".md", StringComparison.Ordinal)) + .OrderBy(path => Path.GetRelativePath(content, path).Replace('\\', '/'), StringComparer.Ordinal) + .ToArray(); private static string CreateSchemaIdentity(params string[] selectedInputs) { var assembly = typeof(DocumentationStore).Assembly; - string[] sources = assembly.GetManifestResourceNames().Where(static name => name.StartsWith("DocumentationSource/", StringComparison.Ordinal)) - .Where(name => selectedInputs.Length == 0 || selectedInputs.Contains(name["DocumentationSource/".Length..], StringComparer.Ordinal)) - .Order(StringComparer.Ordinal).ToArray(); + string[] sources = assembly + .GetManifestResourceNames() + .Where(static name => name.StartsWith("DocumentationSource/", StringComparison.Ordinal)) + .Where( + name => selectedInputs.Length == 0 || selectedInputs.Contains(name["DocumentationSource/".Length..], StringComparer.Ordinal) + ) + .Order(StringComparer.Ordinal) + .ToArray(); if (sources.Length == 0 || (selectedInputs.Length != 0 && sources.Length != selectedInputs.Length)) + { throw new InvalidDataException("Documentation tooling lacks its authored query protocol inputs."); + } var inputs = new List(); foreach (string source in sources) { using Stream stream = assembly.GetManifestResourceStream(source) - ?? throw new InvalidDataException("Missing query protocol input: " + source); + ?? throw new InvalidDataException("Missing query protocol input: " + source); using var reader = new StreamReader(stream); inputs.Add(source + "\0" + DocumentationMarkdown.Hash(reader.ReadToEnd().Replace("\r\n", "\n", StringComparison.Ordinal))); } @@ -344,8 +464,10 @@ private static DocumentationManifest ReadManifest( DocumentationManifest manifest = Deserialize(File.ReadAllBytes(path)); if (manifest.identity != identity || (requireCurrentSchema && (manifest.schema != schema || manifest.parserSchema != parserSchema || manifest.references is null)) - || DocumentationMarkdown.Hash(JsonSerializer.SerializeToUtf8Bytes(manifest with { identity = "" }, json)) != identity) + || DocumentationMarkdown.Hash(JsonSerializer.SerializeToUtf8Bytes(manifest with { identity = "" }, json)) != identity + ) { throw new InvalidDataException("Documentation snapshot integrity or schema mismatch; explicitly rebuild its index."); + } return manifest; } @@ -355,15 +477,26 @@ private static DocumentationManifest ReadManifest( { string pointer = PathBoundary.RequireUnlinkedPath(output, Path.Combine(output, "current.json")); if (!File.Exists(pointer)) + { return null; + } string identity = Deserialize(File.ReadAllBytes(pointer)); RequireHash(identity, "snapshot"); // A verified older query generation can still supply matching immutable parsed-page payloads. // It is never exposed through OpenAsync until the current catalog and index have been rebuilt. return ReadManifest(output, identity, requireCurrentSchema: false); } - catch (JsonException) { return null; } - catch (InvalidDataException) { return null; } - catch (FileNotFoundException) { return null; } + catch (JsonException) + { + return null; + } + catch (InvalidDataException) + { + return null; + } + catch (FileNotFoundException) + { + return null; + } } } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs index d23b8738f..e7e39c966 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs @@ -22,6 +22,7 @@ internal sealed record DocumentationApiOrigin( string revision, string[] surfaces ); + internal sealed record DocumentationComposedContent( IReadOnlyDictionary pages, IReadOnlyDictionary inputs, @@ -36,46 +37,67 @@ internal static DocumentationComposedContent Prepare( IReadOnlyDictionary raw ) { var pages = new SortedDictionary(raw.ToDictionary(pair => pair.Key, pair => pair.Value), StringComparer.Ordinal); - var inputs = new SortedDictionary(raw.ToDictionary(pair => pair.Key, pair => DocumentationMarkdown.Hash(pair.Value)), StringComparer.Ordinal); + var inputs = new SortedDictionary( + raw.ToDictionary(pair => pair.Key, pair => DocumentationMarkdown.Hash(pair.Value)), + StringComparer.Ordinal + ); var origins = new List(); string registryPath = DocumentationApiFacts.Resolve(root, DocumentationApiContent.C_REGISTRY); if (!File.Exists(registryPath)) return new(pages, inputs, origins); string registryText = File.ReadAllText(registryPath); inputs.Add(DocumentationApiContent.C_REGISTRY, DocumentationMarkdown.Hash(registryText)); DocumentationApiContentRegistry registry = JsonSerializer.Deserialize(registryText) - ?? throw new InvalidDataException("Missing API content registry."); - if (registry.schema != "inno-api-content/1") throw new InvalidDataException("Unsupported API content registry."); + ?? throw new InvalidDataException("Missing API content registry."); + if (registry.schema != "inno-api-content/1") + { + throw new InvalidDataException("Unsupported API content registry."); + } IReadOnlyDictionary facts = DocumentationApiFacts.Read(root, binding); var entries = registry.entries.ToDictionary(entry => entry.symbol, StringComparer.Ordinal); var fragments = new Dictionary(StringComparer.Ordinal); foreach (DocumentationApiContentEntry entry in registry.entries) { DocumentationApiContent.RequireApiPath(root, entry.path); - if (!raw.TryGetValue(entry.path, out string? text)) throw new InvalidDataException("Registered API fragment is missing: " + entry.path); + if (!raw.TryGetValue(entry.path, out string? text)) + { + throw new InvalidDataException("Registered API fragment is missing: " + entry.path); + } DocumentationApiFragment fragment = DocumentationApiFragment.Read(entry.path, text) - ?? throw new InvalidDataException("Registered API fragment has no symbol: " + entry.path); - if (fragment.symbol != entry.symbol) throw new InvalidDataException("API fragment identity does not match its registry: " + entry.path); + ?? throw new InvalidDataException("Registered API fragment has no symbol: " + entry.path); + if (fragment.symbol != entry.symbol) + { + throw new InvalidDataException("API fragment identity does not match its registry: " + entry.path); + } fragments.Add(entry.symbol, fragment); pages.Remove(entry.path); } foreach (string key in facts.Keys) - if (!entries.ContainsKey(key)) throw new InvalidDataException("API capture has no registered content: " + key); + { + if (!entries.ContainsKey(key)) + { + throw new InvalidDataException("API capture has no registered content: " + key); + } + } var contractPages = new Dictionary(StringComparer.Ordinal); foreach (var page in pages) { YamlMappingNode metadata = DocumentationApiFragment.ReadMetadata(page.Key, page.Value); string uid = ((YamlScalarNode)metadata.Children[new YamlScalarNode("uid")]).Value!; string title = metadata.Children.TryGetValue(new YamlScalarNode("title"), out YamlNode? value) - ? ((YamlScalarNode)value).Value ?? uid : uid; + ? ((YamlScalarNode)value).Value ?? uid + : uid; contractPages.Add(uid, (page.Key, title)); } foreach (DocumentationApiContentEntry typeEntry in entries.Values.Where(value => facts.ContainsKey(value.symbol))) + { contractPages.Add(fragments[typeEntry.symbol].uid, (typeEntry.path, typeEntry.title)); + } var byType = entries.Values.Where(entry => facts.ContainsKey(entry.symbol)) .Where(entry => DocumentationApiPresentation.Parent(facts[entry.symbol][0]) is not null) .GroupBy(entry => DocumentationApiPresentation.Parent(facts[entry.symbol][0])!, StringComparer.Ordinal) .ToDictionary(group => group.Key, group => group.OrderBy(member => member.title, StringComparer.OrdinalIgnoreCase) - .ThenBy(member => member.symbol, StringComparer.Ordinal).ToArray(), StringComparer.Ordinal); + .ThenBy(member => member.symbol, StringComparer.Ordinal) + .ToArray(), StringComparer.Ordinal); foreach (var type in facts.Values) { DocumentationApiFact fact = type[0]; @@ -93,18 +115,25 @@ IReadOnlyDictionary raw var text = new StringBuilder(header).Append("\n\n"); string body = fragment.body.Trim(); string status = Status(fragment, type); - text.Append("> [!").Append(status.ToUpperInvariant()).Append("]\n> ").Append(status switch - { - "Synced" => "This explanation is synchronized from the source XML documentation.", - "Outdated" => "This authored explanation may be out of date.", - _ => "This explanation is maintained by its named author." - }).Append("\n\n"); + text.Append("> [!").Append(status.ToUpperInvariant()).Append("]\n> ").Append( + status switch + { + "Synced" => "This explanation is synchronized from the source XML documentation.", + "Outdated" => "This authored explanation may be out of date.", + _ => "This explanation is maintained by its named author." + } + ).Append("\n\n"); text.Append("# ").Append(WebUtility.HtmlEncode(entry.title)).Append("\n\n"); // Preserve XML element boundaries: multiple paragraphs in one summary are still one item. DocumentationXmlContent xml = DocumentationXml.Read(fact.documentation); - string summary = string.Join("\n\n", fragment.Summaries(fact.documentation).Select(part => "- " + part.Replace("\n", "\n ", StringComparison.Ordinal))); + string summary = string.Join( + "\n\n", + fragment.Summaries(fact.documentation).Select(part => "- " + part.Replace("\n", "\n ", StringComparison.Ordinal)) + ); if (summary.Length != 0) + { text.Append("> ").Append(summary.Replace("\n", "\n> ", StringComparison.Ordinal)).Append("\n\n"); + } if (headerMetadata.Children[new YamlScalarNode("contracts")] is YamlSequenceNode contracts && contracts.Children.Count != 0) { text.Append("## Required contracts\n\n"); @@ -112,10 +141,21 @@ IReadOnlyDictionary raw { string[] target = (contract.Value ?? "").Split('#', 2); if (!contractPages.TryGetValue(target[0], out var destination)) + { throw new InvalidDataException("Missing associated API contract: " + contract.Value); + } string relative = Path.GetRelativePath(Path.GetDirectoryName(entry.path)!, destination.path).Replace('\\', '/'); - text.Append("- [").Append(WebUtility.HtmlEncode(destination.title).Replace("[", "\\[", StringComparison.Ordinal).Replace("]", "\\]", StringComparison.Ordinal)) - .Append("](").Append(relative).Append(target.Length == 2 ? "#" + target[1] : "").Append(")\n"); + text + .Append("- [") + .Append( + WebUtility.HtmlEncode(destination.title) + .Replace("[", "\\[", StringComparison.Ordinal) + .Replace("]", "\\]", StringComparison.Ordinal) + ) + .Append("](") + .Append(relative) + .Append(target.Length == 2 ? "#" + target[1] : "") + .Append(")\n"); } text.Append('\n'); } @@ -125,7 +165,10 @@ IReadOnlyDictionary raw ["Project"] = "`" + fact.project + "`" }; if (fact.baseType is not null) metadata.Add("Inherits", "`" + fact.baseType + "`"); - if (fact.interfaces.Count != 0) metadata.Add("Implements", string.Join(", ", fact.interfaces.Select(value => "`" + value + "`"))); + if (fact.interfaces.Count != 0) + { + metadata.Add("Implements", string.Join(", ", fact.interfaces.Select(value => "`" + value + "`"))); + } if (fact.scope is not null) metadata.Add("Scope", fact.scope); text.AppendJoin(" \n", metadata.Select(item => "**" + item.Key + ":** " + item.Value)).Append("\n\n"); AppendSymbol(text, type, fragment, entry.path, 2, "Declaration"); @@ -134,27 +177,50 @@ IReadOnlyDictionary raw if (members.Length != 0) { text.Append("\n## Members\n\n| Kind | Element | Description |\n| --- | --- | --- |\n"); - foreach (var group in members.GroupBy(member => Category(facts[member.symbol][0])).OrderBy(group => group.Key, StringComparer.Ordinal)) - { + foreach (var group in members + .GroupBy(member => Category(facts[member.symbol][0])) + .OrderBy(group => group.Key, StringComparer.Ordinal) + ) { foreach (DocumentationApiContentEntry member in group) { DocumentationApiFact child = facts[member.symbol][0]; string label = member.title; if (group.Count(other => other.title == member.title) > 1) + { label += child.id.Contains('(') ? child.id[child.id.IndexOf('(')..] : " (" + child.kind + ")"; - text.Append("| ").Append(group.Key).Append(" | [").Append(DocumentationApiPresentation.Cell(label)).Append("](") + } + text.Append("| ") + .Append(group.Key) + .Append(" | [") + .Append(DocumentationApiPresentation.Cell(label)) + .Append("](") .Append(Path.GetRelativePath(Path.GetDirectoryName(entry.path)!, member.path).Replace('\\', '/')) - .Append(") | ").Append(fragments[member.symbol].TableDescription(child.documentation)).Append(" |\n"); + .Append(") | ") + .Append(fragments[member.symbol].TableDescription(child.documentation)) + .Append(" |\n"); } } } - text.Append("\n\n[Source declaration](").Append(binding.repository).Append("/blob/").Append(fact.revision) - .Append('/').Append(fact.source).Append("#L").Append(fact.line).Append(")\n"); + text.Append("\n\n[Source declaration](") + .Append(binding.repository) + .Append("/blob/") + .Append(fact.revision) + .Append('/') + .Append(fact.source) + .Append("#L") + .Append(fact.line) + .Append(")\n"); pages.Add(entry.path, text.ToString()); } // Category tables and queries use the same effective summaries as type pages. - foreach (var category in DocumentationApiNavigation.Create(registry.entries, facts, DocumentationApiPresentation.ProjectDescriptions(root), fragments)) + foreach (var category in DocumentationApiNavigation.Create( + registry.entries, + facts, + DocumentationApiPresentation.ProjectDescriptions(root), + fragments + )) { pages[category.Key] = category.Value; + } DocumentationProjectGuides.Compose(root, binding, facts, fragments, entries, pages, inputs); return new(pages, inputs, origins); @@ -167,29 +233,66 @@ void AppendSymbol( string title ) { DocumentationApiFact fact = contexts[0]; - text.Append('\n').Append('#', level).Append(' ').Append(title).Append("\n\n\n\n\n"); + text.Append('\n') + .Append('#', level) + .Append(' ') + .Append(title) + .Append("\n\n\n\n\n"); foreach (var variants in contexts.GroupBy(value => value.signature, StringComparer.Ordinal)) { text.Append("\n\n```csharp\n") - .Append(variants.Key).Append("\n```\n\n"); + .Append(fact.id) + .Append(' ') + .Append(DocumentationMarkdown.Hash(variants.Key)) + .Append(" -->\n\n```csharp\n") + .Append(variants.Key) + .Append("\n```\n\n"); } - origins.Add(new(ownerPath, fact.id, fragment.path, fragment.source, Status(fragment, contexts), fact.scope, fact.revision, - contexts.Select(context => context.surface).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray())); + origins.Add( + new( + ownerPath, + fact.id, + fragment.path, + fragment.source, + Status(fragment, contexts), + fact.scope, + fact.revision, + contexts.Select(context => context.surface).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray() + ) + ); } } - private static string Category(DocumentationApiFact fact) => fact.id.Contains(".#ctor", StringComparison.Ordinal) ? "Constructors" - : fact.kind switch { "NamedType" => "Nested types", "Method" => "Methods", "Property" => "Properties", "Event" => "Events", "Field" => "Fields", _ => "Members" }; + private static string Category(DocumentationApiFact fact) + => fact.id.Contains(".#ctor", StringComparison.Ordinal) + ? "Constructors" + : fact.kind switch + { + "NamedType" => "Nested types", + "Method" => "Methods", + "Property" => "Properties", + "Event" => "Events", + "Field" => "Fields", + _ => "Members" + }; private static string Status( DocumentationApiFragment fragment, DocumentationApiFact[] contexts - ) => fragment.source == "xml" ? "Synced" - : fragment.IsOutdated(fragment.StaleProse(DocumentationApiContent.Contract(contexts, normalizeXml: true), - DocumentationApiContent.Contract(contexts))) ? "Outdated" : "Authored"; + ) => fragment.source == "xml" + ? "Synced" + : fragment.IsOutdated( + fragment.StaleProse( + DocumentationApiContent.Contract(contexts, normalizeXml: true), + DocumentationApiContent.Contract(contexts) + ) + ) ? "Outdated" : "Authored"; private static string Header( DocumentationApiFragment fragment, @@ -206,25 +309,51 @@ out YamlMappingNode metadata metadata.Children[new YamlScalarNode("title")] = new YamlScalarNode(title); metadata.Children[new YamlScalarNode("owners")] = new YamlSequenceNode(new YamlScalarNode(contexts[0].project)); metadata.Children[new YamlScalarNode("apiSurface")] = new YamlScalarNode(contexts[0].surface); - if (contexts[0].scope is string scope) metadata.Children[new YamlScalarNode("apiScope")] = new YamlScalarNode(scope); - else metadata.Children.Remove(new YamlScalarNode("apiScope")); - metadata.Children[new YamlScalarNode("apiSurfaces")] = new YamlSequenceNode(contexts.Select(context => context.surface) - .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).Select(value => new YamlScalarNode(value))); + if (contexts[0].scope is string scope) + { + metadata.Children[new YamlScalarNode("apiScope")] = new YamlScalarNode(scope); + } + else + { + metadata.Children.Remove(new YamlScalarNode("apiScope")); + } + metadata.Children[new YamlScalarNode("apiSurfaces")] = new YamlSequenceNode( + contexts.Select(context => context.surface) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .Select(value => new YamlScalarNode(value)) + ); var contracts = new SortedSet(StringComparer.Ordinal); foreach (DocumentationApiFragment member in new[] { fragment }.Concat(ancestors)) + { if (member.metadata.Children.TryGetValue(new YamlScalarNode("contracts"), out YamlNode? value)) { if (value is not YamlSequenceNode sequence || sequence.Children.Any(child => child is not YamlScalarNode)) + { throw new InvalidDataException("API contracts must be a sequence of stable references: " + member.path); - foreach (YamlScalarNode contract in sequence.Children) contracts.Add(contract.Value ?? ""); + } + foreach (YamlScalarNode contract in sequence.Children) + { + contracts.Add(contract.Value ?? ""); + } } - foreach (DocumentationApiFragment ancestor in ancestors) contracts.Add(ancestor.uid); + } + foreach (DocumentationApiFragment ancestor in ancestors) + { + contracts.Add(ancestor.uid); + } if (!metadata.Children.ContainsKey(new YamlScalarNode("exampleMode"))) { - DocumentationApiFragment? context = ancestors.FirstOrDefault(ancestor => ancestor.metadata.Children.ContainsKey(new YamlScalarNode("exampleMode"))); + DocumentationApiFragment? context = ancestors.FirstOrDefault( + ancestor => ancestor.metadata.Children.ContainsKey(new YamlScalarNode("exampleMode")) + ); if (context is not null) + { foreach (string key in new[] { "exampleMode", "exampleProjects" }) + { metadata.Children[new YamlScalarNode(key)] = context.metadata.Children[new YamlScalarNode(key)]; + } + } } metadata.Children[new YamlScalarNode("contracts")] = new YamlSequenceNode(contracts.Select(value => new YamlScalarNode(value))); using var writer = new StringWriter(); @@ -241,7 +370,10 @@ private static string Rebase( string pagePath, int level ) { - MarkdownDocument document = Markdown.Parse(body, new MarkdownPipelineBuilder().UsePreciseSourceLocation().EnableTrackTrivia().Build()); + MarkdownDocument document = Markdown.Parse( + body, + new MarkdownPipelineBuilder().UsePreciseSourceLocation().EnableTrackTrivia().Build() + ); var changes = new List<(int start, int length, string value)>(); foreach (HeadingBlock heading in document.Descendants()) { @@ -254,22 +386,36 @@ int level changes.Add((heading.Span.Start, 0, prefix + " ")); changes.Add((heading.Span.Start + underline, heading.Span.Length - underline, "")); } - else changes.Add((heading.Span.Start, heading.Level, prefix)); + else + { + changes.Add((heading.Span.Start, heading.Level, prefix)); + } } - var links = document.Descendants().Where(link => link.Url is not null && link.Reference is null) + var links = document.Descendants() + .Where(link => link.Url is not null && link.Reference is null) .Select(link => (url: link.Url!, span: link.UrlSpan)) - .Concat(document.Descendants().Where(link => link.Url is not null).Select(link => (url: link.Url!, span: link.UrlSpan))); + .Concat( + document + .Descendants() + .Where(link => link.Url is not null) + .Select(link => (url: link.Url!, span: link.UrlSpan)) + ); foreach (var link in links) { if (link.url.StartsWith('#') || Uri.TryCreate(link.url, UriKind.Absolute, out _)) continue; - if (link.span.Start < 0 || link.span.End < link.span.Start) throw new InvalidDataException("API link lacks a source span."); + if (link.span.Start < 0 || link.span.End < link.span.Start) + { + throw new InvalidDataException("API link lacks a source span."); + } string[] parts = link.url.Split('#', 2); string target = Path.GetFullPath(parts[0], Path.GetDirectoryName(Path.Combine(root, fragmentPath))!); string relative = Path.GetRelativePath(Path.GetDirectoryName(Path.Combine(root, pagePath))!, target).Replace('\\', '/'); changes.Add((link.span.Start, link.span.Length, relative + (parts.Length == 2 ? "#" + parts[1] : ""))); } foreach (var change in changes.OrderByDescending(change => change.start)) + { body = body.Remove(change.start, change.length).Insert(change.start, change.value); + } return body; } } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiContent.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiContent.cs index 7ce2e6648..7e6baa6da 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiContent.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiContent.cs @@ -4,8 +4,8 @@ using System.Linq; using System.Text; using System.Text.Json; -using YamlDotNet.RepresentationModel; using System.Text.RegularExpressions; +using YamlDotNet.RepresentationModel; using Inno.Core.IO; namespace Inno.Tooling.Documentation.Indexing; @@ -17,22 +17,26 @@ internal sealed record DocumentationApiContentEntry( string title, string contract ); + internal sealed record DocumentationApiContentRegistry( string schema, IReadOnlyList entries, IReadOnlyList? navigation = null ); + internal sealed record DocumentationApiEdit( string path, string? before, string? text ); + internal sealed record DocumentationApiWarning( string symbol, string path, string code, string message ); + internal sealed record DocumentationApiPlan( IReadOnlyList edits, IReadOnlyList warnings, @@ -48,15 +52,27 @@ internal static DocumentationApiPlan Plan( DocumentationBinding binding ) { IReadOnlyDictionary facts = DocumentationApiFacts.Read(root, binding); - if (facts.Count == 0) throw new InvalidDataException("Complete API synchronization discovered no eligible symbols."); + if (facts.Count == 0) + { + throw new InvalidDataException("Complete API synchronization discovered no eligible symbols."); + } string registryPath = DocumentationApiFacts.Resolve(root, C_REGISTRY); DocumentationApiContentRegistry? previous = File.Exists(registryPath) - ? JsonSerializer.Deserialize(File.ReadAllBytes(registryPath)) : null; - if (previous is not null && previous.schema != "inno-api-content/1") throw new InvalidDataException("Unsupported API content registry."); + ? JsonSerializer.Deserialize(File.ReadAllBytes(registryPath)) + : null; + if (previous is not null && previous.schema != "inno-api-content/1") + { + throw new InvalidDataException("Unsupported API content registry."); + } var prior = (previous?.entries ?? []).ToDictionary(entry => entry.symbol, StringComparer.Ordinal); - var registeredPaths = new HashSet((previous?.navigation ?? []).Concat(prior.Values.Select(entry => entry.path)), StringComparer.Ordinal); + var registeredPaths = new HashSet( + (previous?.navigation ?? []).Concat(prior.Values.Select(entry => entry.path)), + StringComparer.Ordinal + ); if (registeredPaths.Count != (previous?.navigation?.Count ?? 0) + prior.Count) + { throw new InvalidDataException("API content registry repeats an owned path."); + } var edits = new Dictionary(StringComparer.Ordinal); var warnings = new List(); var entries = new List(); @@ -73,19 +89,44 @@ DocumentationBinding binding } } foreach (var collision in typePaths.Where(pair => categoryPaths.Contains(pair.Value)).ToArray()) - typePaths[collision.Key] = collision.Value.Replace("/index.md", "-" + DocumentationMarkdown.Hash(collision.Key)[..12] + "/index.md", StringComparison.Ordinal); - foreach (var duplicates in typePaths.GroupBy(pair => pair.Value, StringComparer.OrdinalIgnoreCase).Where(group => group.Count() > 1).ToArray()) + { + typePaths[collision.Key] = collision.Value.Replace( + "/index.md", + "-" + DocumentationMarkdown.Hash(collision.Key)[..12] + "/index.md", + StringComparison.Ordinal + ); + } + foreach (var duplicates in typePaths + .GroupBy(pair => pair.Value, StringComparer.OrdinalIgnoreCase) + .Where(group => group.Count() > 1) + .ToArray() + ) { foreach (var duplicate in duplicates) - typePaths[duplicate.Key] = duplicate.Value.Replace("/index.md", "-" + DocumentationMarkdown.Hash(duplicate.Key)[..12] + "/index.md", StringComparison.Ordinal); + { + typePaths[duplicate.Key] = duplicate.Value.Replace( + "/index.md", + "-" + DocumentationMarkdown.Hash(duplicate.Key)[..12] + "/index.md", + StringComparison.Ordinal + ); + } + } foreach (var pair in facts.OrderBy(pair => pair.Key, StringComparer.Ordinal)) { DocumentationApiFact fact = pair.Value[0]; string type = fact.kind == "NamedType" ? fact.key : fact.family + ":" + fact.project + ":" + fact.containingType; - if (!typePaths.TryGetValue(type, out string? typePath)) throw new InvalidDataException("API member has no eligible declaring type: " + fact.key); + if (!typePaths.TryGetValue(type, out string? typePath)) + { + throw new InvalidDataException("API member has no eligible declaring type: " + fact.key); + } string title = DocumentationApiPresentation.Name(fact, facts); string fileName = string.Join('.', title.Split('.').Select(part => Slug(Regex.Replace(part, "<[^<>]+>", "")))); - string path = fact.kind == "NamedType" ? typePath - : typePath.Replace("index.md", fileName + "-" + DocumentationMarkdown.Hash(fact.key)[..16] + ".md", StringComparison.Ordinal); + string path = fact.kind == "NamedType" + ? typePath + : typePath.Replace( + "index.md", + fileName + "-" + DocumentationMarkdown.Hash(fact.key)[..16] + ".md", + StringComparison.Ordinal + ); string contract = Contract(pair.Value); var entry = new DocumentationApiContentEntry(fact.key, path, type, title, contract); entries.Add(entry); @@ -93,9 +134,15 @@ DocumentationBinding binding if (prior.TryGetValue(fact.key, out DocumentationApiContentEntry? old)) { string oldPath = RequireApiPath(root, old.path); - if (File.Exists(oldPath)) existing = DocumentationApiFragment.Read(old.path, File.ReadAllText(oldPath)) - ?? throw new InvalidDataException("Registered API file lacks symbol metadata: " + old.path); - if (existing is not null && existing.symbol != fact.key) throw new InvalidDataException("Registered API identity changed: " + old.path); + if (File.Exists(oldPath)) + { + existing = DocumentationApiFragment.Read(old.path, File.ReadAllText(oldPath)) + ?? throw new InvalidDataException("Registered API file lacks symbol metadata: " + old.path); + } + if (existing is not null && existing.symbol != fact.key) + { + throw new InvalidDataException("Registered API identity changed: " + old.path); + } if (old.path != path && existing is not null) Edit(old.path, null); } if (existing is not null && existing.source != "xml") @@ -105,14 +152,30 @@ DocumentationBinding binding string? staleProse = existing.StaleProse(fingerprint, contract); bool stale = existing.IsOutdated(staleProse); Edit(path, Fragment(entry, fact, existing.body, existing, fingerprint, staleProse)); - if (string.IsNullOrWhiteSpace(existing.body) || Normalize(existing.body) == Normalize(DocumentationXml.Read(fact.documentation).body)) + if (string.IsNullOrWhiteSpace(existing.body) + || Normalize(existing.body) == Normalize(DocumentationXml.Read(fact.documentation).body) + ) { warnings.Add(new(fact.key, path, "EmptyManual", "Manual ownership has no independent explanatory content.")); + } if (stale) - warnings.Add(new(fact.key, path, "ReviewRequired", "The authored explanation is marked outdated for the current source.")); + { + warnings.Add( + new(fact.key, path, "ReviewRequired", "The authored explanation is marked outdated for the current source.") + ); + } } else { - Edit(path, Fragment(entry, fact, DocumentationXml.Read(fact.documentation).body, existing, Contract(pair.Value, normalizeXml: true))); + Edit( + path, + Fragment( + entry, + fact, + DocumentationXml.Read(fact.documentation).body, + existing, + Contract(pair.Value, normalizeXml: true) + ) + ); warnings.Add(new(fact.key, path, "XmlOnly", "This API still uses XML-synchronized prose.")); } } @@ -122,32 +185,59 @@ DocumentationBinding binding if (!File.Exists(path)) continue; DocumentationApiFragment fragment = DocumentationApiFragment.Read(removed.path, File.ReadAllText(path)) ?? throw new InvalidDataException("Registered API file lacks symbol metadata: " + removed.path); - if (fragment.symbol != removed.symbol) throw new InvalidDataException("Removed API identity differs from its registration."); - if (fragment.source == "xml") Edit(removed.path, null); + if (fragment.symbol != removed.symbol) + { + throw new InvalidDataException("Removed API identity differs from its registration."); + } + if (fragment.source == "xml") + { + Edit(removed.path, null); + } else { entries.Add(removed); - warnings.Add(new(removed.symbol, removed.path, "RemovedApi", "Preserved manual prose for an API absent from the current input.")); + warnings.Add( + new(removed.symbol, removed.path, "RemovedApi", "Preserved manual prose for an API absent from the current input.") + ); } } - IReadOnlyDictionary navigation = DocumentationApiNavigation.Create(entries, facts, DocumentationApiPresentation.ProjectDescriptions(root)); - foreach (var page in navigation) Edit(page.Key, page.Value); - foreach (string removed in (previous?.navigation ?? []).Except(navigation.Keys, StringComparer.Ordinal)) Edit(removed, null); + IReadOnlyDictionary navigation = DocumentationApiNavigation.Create( + entries, + facts, + DocumentationApiPresentation.ProjectDescriptions(root) + ); + foreach (var page in navigation) + { + Edit(page.Key, page.Value); + } + foreach (string removed in (previous?.navigation ?? []).Except(navigation.Keys, StringComparer.Ordinal)) + { + Edit(removed, null); + } var moves = entries.Where(entry => prior.TryGetValue(entry.symbol, out var old) && old.path != entry.path) .ToDictionary(entry => prior[entry.symbol].path, entry => entry.path, StringComparer.Ordinal); var anchors = new Dictionary(StringComparer.Ordinal); - foreach (DocumentationApiContentEntry entry in entries.Where(entry => entry.type != entry.symbol && facts.ContainsKey(entry.symbol))) + foreach (DocumentationApiContentEntry entry in entries.Where( + entry => entry.type != entry.symbol && facts.ContainsKey(entry.symbol) + )) { if (prior.TryGetValue(entry.type, out var oldType)) + { anchors[oldType.path + "#api-" + DocumentationMarkdown.Hash(facts[entry.symbol][0].id)[..16]] = entry.path; + } + } if (moves.Count != 0) { var reverse = moves.ToDictionary(pair => pair.Value, pair => pair.Key, StringComparer.Ordinal); string[] paths = Directory.EnumerateFiles(Path.Combine(root, "content/en"), "*.md", SearchOption.AllDirectories) - .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')).Concat(edits.Keys.Where(path => path.EndsWith(".md", StringComparison.Ordinal))) - .Distinct(StringComparer.Ordinal).ToArray(); + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Concat(edits.Keys.Where(path => path.EndsWith(".md", StringComparison.Ordinal))) + .Distinct(StringComparer.Ordinal) + .ToArray(); foreach (string path in paths) { - string? text = edits.TryGetValue(path, out var edit) ? edit.text : File.ReadAllText(DocumentationApiFacts.Resolve(root, path)); + string? text = edits.TryGetValue(path, out var edit) + ? edit.text + : File.ReadAllText(DocumentationApiFacts.Resolve(root, path)); if (text is null) continue; string rewritten = DocumentationApiLinks.Rewrite(root, reverse.GetValueOrDefault(path) ?? path, path, text, moves, anchors); if (text == rewritten) continue; @@ -156,10 +246,22 @@ DocumentationBinding binding edits[path] = new(path, before, rewritten); } } - Edit(C_REGISTRY, JsonSerializer.Serialize(new DocumentationApiContentRegistry("inno-api-content/1", entries.OrderBy(entry => entry.symbol, StringComparer.Ordinal).ToArray(), navigation.Keys.Order(StringComparer.Ordinal).ToArray()), - new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" }) + "\n"); + Edit( + C_REGISTRY, + JsonSerializer.Serialize( + new DocumentationApiContentRegistry( + "inno-api-content/1", + entries.OrderBy(entry => entry.symbol, StringComparer.Ordinal).ToArray(), + navigation.Keys.Order(StringComparer.Ordinal).ToArray() + ), + new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" } + ) + "\n" + ); DocumentationApiPlan guides = DocumentationProjectGuides.Plan(root, binding, facts); - foreach (var edit in guides.edits) edits[edit.path] = edit; + foreach (var edit in guides.edits) + { + edits[edit.path] = edit; + } warnings.AddRange(guides.warnings); return new(edits.Values.OrderBy(edit => edit.path, StringComparer.Ordinal).ToArray(), warnings, facts.Count); @@ -171,7 +273,9 @@ void Edit( string? before = File.Exists(absolute) ? File.ReadAllText(absolute) : null; if (before == text) return; if (before is not null && path != C_REGISTRY && !registeredPaths.Contains(path)) + { throw new InvalidDataException("Synchronization cannot overwrite an unregistered API file: " + path); + } edits[path] = new(path, before is null ? null : DocumentationMarkdown.Hash(before), text); } } @@ -197,24 +301,37 @@ private static string Fragment( }; if (staleProse is not null) generated.Add("outdatedFor", staleProse); if (fact.scope is not null) generated.Add("apiScope", fact.scope); - generated.Add("contracts", previous is not null && previous.metadata.Children.TryGetValue(new YamlScalarNode("contracts"), out YamlNode? contracts) ? contracts : new YamlSequenceNode()); + generated.Add( + "contracts", + previous is not null && previous.metadata.Children.TryGetValue(new YamlScalarNode("contracts"), out YamlNode? contracts) + ? contracts + : new YamlSequenceNode() + ); var authored = new YamlMappingNode { { "source", manual ? previous!.source : "xml" }, - { "description", previous is not null && previous.metadata.Children.TryGetValue(new YamlScalarNode("description"), out YamlNode? description) ? description : new YamlScalarNode("null") { Style = YamlDotNet.Core.ScalarStyle.Plain } }, + { "description", previous is not null + && previous.metadata.Children.TryGetValue(new YamlScalarNode("description"), out YamlNode? description) + ? description + : new YamlScalarNode("null") { Style = YamlDotNet.Core.ScalarStyle.Plain } }, { "outdated", manual && previous!.ExplicitlyOutdated ? "true" : "false" } }; if (previous is not null) + { foreach (var field in previous.metadata.Children) { string key = ((YamlScalarNode)field.Key).Value!; if (generated.Children.ContainsKey(field.Key) || authored.Children.ContainsKey(field.Key) - || key is "apiScope" or "apiSurfaces" or "reviewed" or "outdatedFor") continue; + || key is "apiScope" or "apiSurfaces" or "reviewed" or "outdatedFor" + ) { + continue; + } authored.Add(field.Key, field.Value); } + } return "---\n# Generated metadata. Maintained by API synchronization tooling.\n" - + Serialize(generated) + "\n\n# Authoring metadata. Edit these fields and the explanation below.\n" - + Serialize(authored) + "\n---" + (manual ? body : body.Length == 0 ? "\n" : "\n\n" + body.Trim() + "\n"); + + Serialize(generated) + "\n\n# Authoring metadata. Edit these fields and the explanation below.\n" + + Serialize(authored) + "\n---" + (manual ? body : body.Length == 0 ? "\n" : "\n\n" + body.Trim() + "\n"); } private static string Serialize(YamlMappingNode metadata) @@ -228,9 +345,19 @@ private static string Serialize(YamlMappingNode metadata) internal static string Contract( IEnumerable contexts, bool normalizeXml = false - ) => DocumentationMarkdown.Hash(string.Join('\n', contexts.Select(fact => fact.signatureHash + "\0" - + (normalizeXml ? fact.documentation.ReplaceLineEndings("\n") : fact.documentation) - + "\0" + fact.scope + "\0" + fact.configuration + "\0" + fact.target + "\0" + fact.surface).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal))); + ) => DocumentationMarkdown.Hash( + string.Join( + '\n', + contexts + .Select(fact => ( + fact.signatureHash + "\0" + + (normalizeXml ? fact.documentation.ReplaceLineEndings("\n") : fact.documentation) + + "\0" + fact.scope + "\0" + fact.configuration + "\0" + fact.target + "\0" + fact.surface + )) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + ) + ); internal static string Title(DocumentationApiFact fact) { @@ -245,11 +372,15 @@ internal static string QualifiedTitle(DocumentationApiFact fact) if (!identity.Contains('`')) return identity; // Match the exact qualified type in the captured declaration. Type parameter names // come from source facts, never from editable XML prose or an invented T1/T2 list. - string pattern = string.Join(@"\.", identity.Split('.').Select(part => - "@?" + Regex.Replace(Regex.Escape(part), "`[0-9]+", "<[^<>]+>"))); + string pattern = string.Join( + @"\.", + identity.Split('.').Select(part => ("@?" + Regex.Replace(Regex.Escape(part), "`[0-9]+", "<[^<>]+>"))) + ); Match declaration = Regex.Match(fact.signature, @"(? Regex.Replace(text.ToLowerInvariant(), "[^a-z0-9]+", "-").Trim('-'); + internal static string Slug(string text) => Regex.Replace(text.ToLowerInvariant(), "[^a-z0-9]+", "-").Trim('-'); internal static string TypePath(DocumentationApiFact fact) { - string category = fact.family == "scripting" ? "scripting/" + fact.scope!.ToLowerInvariant() - : "engine/" + string.Join('/', (fact.project.StartsWith("Inno.", StringComparison.Ordinal) ? fact.project[5..] : fact.project).Split('.').Select(Slug)); + string category = fact.family == "scripting" + ? "scripting/" + fact.scope!.ToLowerInvariant() + : "engine/" + + string.Join( + '/', + (fact.project.StartsWith("Inno.", StringComparison.Ordinal) ? fact.project[5..] : fact.project).Split('.').Select(Slug) + ); return "content/en/api/" + category + "/" + Slug(PathName(fact)) + "/index.md"; } @@ -278,8 +414,10 @@ string path if (!path.StartsWith("content/en/api/engine/", StringComparison.Ordinal) && !path.StartsWith("content/en/api/scripting/", StringComparison.Ordinal) || !path.EndsWith(".md", StringComparison.Ordinal) - || path != Path.GetRelativePath(root, resolved).Replace('\\', '/')) + || path != Path.GetRelativePath(root, resolved).Replace('\\', '/') + ) { throw new InvalidDataException("Synchronization is restricted to registered engine/script API content: " + path); + } return resolved; } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFacts.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFacts.cs index 0f311fa0f..4008dd322 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFacts.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFacts.cs @@ -37,15 +37,21 @@ DocumentationBinding binding string inventoryPath = Resolve(root, binding.projectManifest); byte[] inventoryBytes = File.ReadAllBytes(inventoryPath); if (DocumentationMarkdown.Hash(inventoryBytes) != binding.projectManifestIdentity) + { throw new InvalidDataException("API project inventory identity differs from its binding."); + } using JsonDocument inventory = JsonDocument.Parse(inventoryBytes); var eligible = inventory.RootElement.EnumerateArray().Where(project => { string path = project.GetProperty("path").GetString()!; return (path.StartsWith("src/", StringComparison.Ordinal) || path.StartsWith("build/", StringComparison.Ordinal)) - && (!project.TryGetProperty("isTest", out JsonElement test) || !test.GetBoolean()) - && path.EndsWith(".csproj", StringComparison.Ordinal); - }).ToDictionary(project => project.GetProperty("name").GetString()!, project => project.GetProperty("path").GetString()!, StringComparer.Ordinal); + && (!project.TryGetProperty("isTest", out JsonElement test) || !test.GetBoolean()) + && path.EndsWith(".csproj", StringComparison.Ordinal); + }).ToDictionary( + project => project.GetProperty("name").GetString()!, + project => project.GetProperty("path").GetString()!, + StringComparer.Ordinal + ); var result = new Dictionary>(StringComparer.Ordinal); var captured = new HashSet(StringComparer.Ordinal); var projections = new Dictionary<(string configuration, string? target, string model), string>(); @@ -55,16 +61,21 @@ DocumentationBinding binding { byte[] bytes = File.ReadAllBytes(Resolve(root, capture.path)); if (DocumentationMarkdown.Hash(bytes) != capture.sha256) + { throw new InvalidDataException("API capture identity differs: " + capture.path); + } using JsonDocument document = JsonDocument.Parse(bytes); string model = document.RootElement.GetProperty("model").GetString()!; if (model != capture.model || String(document.RootElement, "configuration") != capture.configuration - || String(document.RootElement, "target") != capture.target) + || String(document.RootElement, "target") != capture.target + ) { throw new InvalidDataException("API context differs from its binding: " + capture.path); + } DocumentationStore.RequireHash(capture.sourceRevision, "API source revision", allowGitTree: true); DocumentationStore.RequireHash(capture.sourceTree, "API source tree", allowGitTree: true); string family = model == "source-clr" ? "engine" : model is "runtime-script" or "editor-script" - ? "scripting" : throw new InvalidDataException("Unsupported API capture model: " + model); + ? "scripting" + : throw new InvalidDataException("Unsupported API capture model: " + model); if (family == "scripting") { scriptModels.Add(model); @@ -72,9 +83,17 @@ DocumentationBinding binding { string runtime = identities.GetProperty("Inno.ScriptApi.Runtime").GetString()!; DocumentationStore.RequireHash(runtime, "Runtime projection identity"); - if (model == "editor-script") DocumentationStore.RequireHash(identities.GetProperty("Inno.ScriptApi.Editor").GetString()!, "Editor projection identity"); + if (model == "editor-script") + { + DocumentationStore.RequireHash( + identities.GetProperty("Inno.ScriptApi.Editor").GetString()!, + "Editor projection identity" + ); + } if (!projections.TryAdd((capture.configuration, capture.target, model), runtime)) + { throw new InvalidDataException("Repeated logical projection context."); + } } } foreach (JsonElement project in document.RootElement.GetProperty("projects").EnumerateArray()) @@ -82,69 +101,125 @@ DocumentationBinding binding string name = project.GetProperty("name").GetString()!; if (!eligible.TryGetValue(name, out string? path)) continue; if (project.GetProperty("project").GetString() != path) + { throw new InvalidDataException("API owner does not match the project inventory: " + name); + } if (family == "engine") captured.Add(name); if (family == "engine" && project.TryGetProperty("scriptExports", out JsonElement exports) && exports.GetArrayLength() != 0) + { declaresScriptExports = true; + } foreach (JsonElement symbol in project.GetProperty("symbols").EnumerateArray()) { string source = symbol.GetProperty("source").GetString()!; if (source.Split('/').Any(part => part is "" or "." or "..") || source.Contains('\\') - || Path.IsPathRooted(source) || symbol.GetProperty("line").GetInt32() < 1) + || Path.IsPathRooted(source) || symbol.GetProperty("line").GetInt32() < 1 + ) { throw new InvalidDataException("Invalid API source location: " + source); + } if (!source.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) - || !(source.StartsWith("src/", StringComparison.Ordinal) || source.StartsWith("build/", StringComparison.Ordinal))) continue; + || !(source.StartsWith("src/", StringComparison.Ordinal) || source.StartsWith("build/", StringComparison.Ordinal)) + ) { + continue; + } string id = symbol.GetProperty("id").GetString()!; string? scope = family == "scripting" ? String(symbol, "scriptingScope") : null; if (family == "scripting" && scope is not ("Runtime" or "Editor" or "Authoring")) + { throw new InvalidDataException("Projected API lacks its declared ScriptingApiScope: " + id); + } string signature = symbol.GetProperty("signature").GetString()!; string signatureHash = symbol.GetProperty("signatureHash").GetString()!; if (DocumentationMarkdown.Hash(signature) != signatureHash) + { throw new InvalidDataException("Invalid API declaration identity: " + id); + } string key = family + ":" + name + ":" + id; - var fact = new DocumentationApiFact(key, name, family, scope, id, String(symbol, "containingType"), - symbol.GetProperty("kind").GetString()!, signature, signatureHash, String(symbol, "documentation") ?? "", - source, symbol.GetProperty("line").GetInt32(), capture.sourceRevision, capture.configuration, - capture.target, model, String(symbol, "baseType"), symbol.GetProperty("interfaces").EnumerateArray().Select(item => item.GetString()!).ToArray()); - if (!result.TryGetValue(key, out List? contexts)) result.Add(key, contexts = []); + var fact = new DocumentationApiFact( + key, + name, + family, + scope, + id, + String(symbol, "containingType"), + symbol.GetProperty("kind").GetString()!, + signature, + signatureHash, + String(symbol, "documentation") ?? "", + source, + symbol.GetProperty("line").GetInt32(), + capture.sourceRevision, + capture.configuration, + capture.target, + model, + String(symbol, "baseType"), + symbol.GetProperty("interfaces").EnumerateArray().Select(item => item.GetString()!).ToArray() + ); + if (!result.TryGetValue(key, out List? contexts)) + { + result.Add(key, contexts = []); + } if (contexts.Any(prior => prior.scope != scope)) + { throw new InvalidDataException("One logical API has conflicting declared scopes: " + key); - DocumentationApiFact? duplicate = contexts.SingleOrDefault(prior => prior.configuration == fact.configuration - && prior.target == fact.target && prior.surface == fact.surface); + } + DocumentationApiFact? duplicate = contexts.SingleOrDefault(prior => ( + prior.configuration == fact.configuration + && prior.target == fact.target && prior.surface == fact.surface + )); if (duplicate is not null) + { throw new InvalidDataException("Repeated API capture in one context: " + key); + } contexts.Add(fact); } } } string[] missing = eligible.Keys.Except(captured, StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); - if (missing.Length != 0) throw new InvalidDataException("Complete API synchronization lacks source captures: " + string.Join(", ", missing)); + if (missing.Length != 0) + { + throw new InvalidDataException("Complete API synchronization lacks source captures: " + string.Join(", ", missing)); + } if (declaresScriptExports && (!scriptModels.Contains("runtime-script") || !scriptModels.Contains("editor-script"))) + { throw new InvalidDataException("Complete API synchronization requires both actual logical script projections."); + } foreach (List contexts in result.Values) + { foreach (DocumentationApiFact runtime in contexts.Where(fact => fact.surface == "runtime-script").ToArray()) { if (!projections.TryGetValue((runtime.configuration, runtime.target, "runtime-script"), out string? runtimeIdentity) - || !projections.TryGetValue((runtime.configuration, runtime.target, "editor-script"), out string? editorRuntimeIdentity)) continue; + || !projections.TryGetValue( + (runtime.configuration, runtime.target, "editor-script"), + out string? editorRuntimeIdentity + ) + ) { + continue; + } if (runtimeIdentity != editorRuntimeIdentity) + { throw new InvalidDataException("Editor and Runtime captures use different Runtime projection inputs."); - if (!contexts.Any(fact => fact.surface == "editor-script" && fact.configuration == runtime.configuration && fact.target == runtime.target)) + } + if (!contexts.Any( + fact => fact.surface == "editor-script" && fact.configuration == runtime.configuration && fact.target == runtime.target + )) { contexts.Add(runtime with { surface = "editor-script" }); + } } + } return result.ToDictionary(pair => pair.Key, pair => pair.Value.OrderBy(fact => fact.configuration, StringComparer.Ordinal) - .ThenBy(fact => fact.target, StringComparer.Ordinal).ThenBy(fact => fact.surface, StringComparer.Ordinal).ToArray(), StringComparer.Ordinal); + .ThenBy(fact => fact.target, StringComparer.Ordinal) + .ThenBy(fact => fact.surface, StringComparer.Ordinal) + .ToArray(), StringComparer.Ordinal); } internal static string Resolve( string root, string relative - ) - => PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, relative)); + ) => PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, relative)); private static string? String( JsonElement value, string name - ) - => value.TryGetProperty(name, out JsonElement result) && result.ValueKind != JsonValueKind.Null ? result.GetString() : null; + ) => value.TryGetProperty(name, out JsonElement result) && result.ValueKind != JsonValueKind.Null ? result.GetString() : null; } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFragment.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFragment.cs index 1090b224d..b5374608d 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFragment.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFragment.cs @@ -18,8 +18,7 @@ internal sealed record DocumentationApiFragment( string? outdatedFor, bool outdated, YamlMappingNode metadata -) -{ +) { private static readonly MarkdownPipeline S_PIPELINE = new MarkdownPipelineBuilder().UseYamlFrontMatter().Build(); internal static DocumentationApiFragment? Read( @@ -33,22 +32,44 @@ string text if (symbol is null) return null; string source = Field("source") ?? "xml"; if (string.IsNullOrWhiteSpace(source)) + { throw new InvalidDataException("API source must be xml or a nonempty author name: " + path); + } if (map.Children.TryGetValue(new YamlScalarNode("description"), out YamlNode? description) && !IsNull(description) && (description is not YamlSequenceNode items || items.Children.Count == 0 - || items.Children.Any(item => item is not YamlScalarNode scalar || (string.IsNullOrWhiteSpace(scalar.Value) || IsNull(scalar))))) + || items.Children.Any( + item => item is not YamlScalarNode scalar || (string.IsNullOrWhiteSpace(scalar.Value) || IsNull(scalar)) + )) + ) { throw new InvalidDataException("API description must be null or a nonempty list of text: " + path); + } string uid = Field("uid") ?? throw new InvalidDataException("API fragment has no stable identity: " + path); string body = text[(block.Span.End + 1)..]; string? stale = Field("outdated"); if (stale is not null && stale is not ("true" or "false")) + { throw new InvalidDataException("API outdated must be true or false: " + path); - return new(path, text, body, uid, symbol, source, Field("sourceFingerprint") ?? Field("reviewed"), Field("outdatedFor"), stale == "true", map); + } + return new( + path, + text, + body, + uid, + symbol, + source, + Field("sourceFingerprint") ?? Field("reviewed"), + Field("outdatedFor"), + stale == "true", + map + ); - string? Field(string name) => map.Children.TryGetValue(new YamlScalarNode(name), out YamlNode? node) - ? node is YamlScalarNode scalar ? scalar.Value : throw new InvalidDataException("API frontmatter requires a scalar " + name + ": " + path) - : null; + string? Field(string name) + => map.Children.TryGetValue(new YamlScalarNode(name), out YamlNode? node) + ? node is YamlScalarNode scalar + ? scalar.Value + : throw new InvalidDataException("API frontmatter requires a scalar " + name + ": " + path) + : null; } // Compare the prose that was present at the source change with the text being displayed. @@ -63,16 +84,20 @@ string text return changed || legacyStale ? ProseFingerprint() : outdatedFor; } - internal bool IsOutdated(string? staleProse) => source != "xml" - && (outdated || (staleProse is not null && staleProse == ProseFingerprint())); + internal bool IsOutdated(string? staleProse) + => source != "xml" + && (outdated || (staleProse is not null && staleProse == ProseFingerprint())); internal bool ExplicitlyOutdated => outdated && !metadata.Children.ContainsKey(new YamlScalarNode("reviewed")); - private string ProseFingerprint() => DocumentationMarkdown.Hash(System.Text.Json.JsonSerializer.Serialize(new - { - body = body.ReplaceLineEndings("\n").Trim(), - description = Summaries("").Select(value => value.ReplaceLineEndings("\n").Trim()) - })); + private string ProseFingerprint() + => DocumentationMarkdown.Hash( + System.Text.Json.JsonSerializer.Serialize(new + { + body = body.ReplaceLineEndings("\n").Trim(), + description = Summaries("").Select(value => value.ReplaceLineEndings("\n").Trim()) + }) + ); internal static bool IsNull(YamlNode node) => node is YamlScalarNode { Style: YamlDotNet.Core.ScalarStyle.Plain, Value: null or "" or "~" or "null" or "Null" or "NULL" }; @@ -80,21 +105,29 @@ internal static bool IsNull(YamlNode node) internal string[] Summaries(string documentation) { if (metadata.Children.TryGetValue(new YamlScalarNode("description"), out YamlNode? value) - && value is YamlSequenceNode sequence) + && value is YamlSequenceNode sequence + ) { return sequence.Children.Cast().Select(item => item.Value!).ToArray(); + } return DocumentationXml.Read(documentation).summaries.ToArray(); } internal string TableDescription(string documentation) - => string.Join("

", Summaries(documentation).Select(summary => DocumentationApiPresentation.Cell( - Markdown.ToPlainText(summary).Trim()))); + => string.Join( + "

", + Summaries(documentation).Select(summary => DocumentationApiPresentation.Cell( + Markdown.ToPlainText(summary).Trim() + )) + ); internal static YamlMappingNode ReadMetadata( string path, string text ) { YamlFrontMatterBlock? block = Markdown.Parse(text, S_PIPELINE).OfType().SingleOrDefault(); - return block is null ? throw new InvalidDataException("Documentation requires identity metadata: " + path) : ReadMetadata(path, block); + return block is null + ? throw new InvalidDataException("Documentation requires identity metadata: " + path) + : ReadMetadata(path, block); } private static YamlMappingNode ReadMetadata( @@ -104,7 +137,9 @@ YamlFrontMatterBlock block var yaml = new YamlStream(); yaml.Load(new StringReader(block.Lines.ToString())); if (yaml.Documents.Count != 1 || yaml.Documents[0].RootNode is not YamlMappingNode map) + { throw new InvalidDataException("Expected one frontmatter mapping: " + path); + } return map; } } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiLinks.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiLinks.cs index 2476ef445..f6e4e3f29 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiLinks.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiLinks.cs @@ -18,29 +18,44 @@ internal static string Rewrite( IReadOnlyDictionary moves, IReadOnlyDictionary anchors ) { - MarkdownDocument document = Markdown.Parse(text, new MarkdownPipelineBuilder().UseYamlFrontMatter().UsePreciseSourceLocation().EnableTrackTrivia().Build()); - var links = document.Descendants().Where(link => link.Url is not null && link.Reference is null) + MarkdownDocument document = Markdown.Parse( + text, + new MarkdownPipelineBuilder().UseYamlFrontMatter().UsePreciseSourceLocation().EnableTrackTrivia().Build() + ); + var links = document.Descendants() + .Where(link => link.Url is not null && link.Reference is null) .Select(link => (url: link.Url!, span: link.UrlSpan)) - .Concat(document.Descendants().Where(link => link.Url is not null) - .Select(link => (url: link.Url!, span: link.UrlSpan))); + .Concat( + document.Descendants() + .Where(link => link.Url is not null) + .Select(link => (url: link.Url!, span: link.UrlSpan)) + ); var changes = new List<(int start, int length, string value)>(); foreach (var link in links) { if (Uri.TryCreate(link.url, UriKind.Absolute, out _) || link.url.StartsWith('/')) continue; string[] parts = link.url.Split('#', 2); - string target = parts[0].Length == 0 ? originalPath : Path.GetRelativePath(root, - Path.GetFullPath(Uri.UnescapeDataString(parts[0]), Path.GetDirectoryName(Path.Combine(root, originalPath))!)).Replace('\\', '/'); + string target = parts[0].Length == 0 ? originalPath : Path.GetRelativePath( + root, + Path.GetFullPath(Uri.UnescapeDataString(parts[0]), Path.GetDirectoryName(Path.Combine(root, originalPath))!) + ).Replace('\\', '/'); string suffix = parts.Length == 2 ? "#" + parts[1] : ""; string mapped = anchors.GetValueOrDefault(target + suffix) ?? moves.GetValueOrDefault(target) ?? target; if (mapped == target && originalPath == destinationPath) continue; // Moving prose may rebase local references; only paths are changed, never its explanation. - string url = mapped == destinationPath && suffix.Length != 0 ? suffix - : Path.GetRelativePath(Path.GetDirectoryName(destinationPath)!, mapped).Replace('\\', '/') + suffix; - if (link.span.Start < 0 || link.span.End < link.span.Start) throw new InvalidDataException("API link has no source span: " + originalPath); + string url = mapped == destinationPath && suffix.Length != 0 + ? suffix + : Path.GetRelativePath(Path.GetDirectoryName(destinationPath)!, mapped).Replace('\\', '/') + suffix; + if (link.span.Start < 0 || link.span.End < link.span.Start) + { + throw new InvalidDataException("API link has no source span: " + originalPath); + } changes.Add((link.span.Start, link.span.Length, url)); } foreach (var change in changes.OrderByDescending(change => change.start)) + { text = text.Remove(change.start, change.length).Insert(change.start, change.value); + } return text; } } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiNavigation.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiNavigation.cs index 6b2a3c21c..bc949846d 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiNavigation.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiNavigation.cs @@ -17,10 +17,13 @@ internal static IReadOnlyDictionary Create( IReadOnlyDictionary? fragments = null ) { var pages = new SortedDictionary(StringComparer.Ordinal); - DocumentationApiContentEntry[] types = entries.Where(entry => entry.type == entry.symbol && facts.ContainsKey(entry.symbol)).ToArray(); + DocumentationApiContentEntry[] types = entries + .Where(entry => entry.type == entry.symbol && facts.ContainsKey(entry.symbol)) + .ToArray(); var categories = new SortedDictionary(StringComparer.Ordinal) { - ["engine"] = "Engine API", ["scripting"] = "Scripting API" + ["engine"] = "Engine API", + ["scripting"] = "Scripting API" }; foreach (DocumentationApiContentEntry type in types) { @@ -42,11 +45,35 @@ internal static IReadOnlyDictionary Create( { string path = "content/en/api/" + category.Key + "/index.md"; var text = new StringBuilder("---\nuid: api.directory.").Append(category.Key.Replace('/', '.')) - .Append("\ntitle: ").Append(JsonSerializer.Serialize(category.Value)).Append("\nkind: landing\nowners: []\n---\n\n# ") - .Append(category.Value).Append("\n\n"); - if (category.Key == "engine") text.Append("Browse public C# contracts from src/ and build/ by their owning project. All other source roots, tests and fixtures are outside Engine API.\n\n"); - else if (category.Key == "scripting") text.Append("Browse the actual projected script API by its declared scope. Runtime contracts are also available to Editor scripts; Authoring annotations are compilation-time contracts.\n\n"); - else text.Append("Find types in this ").Append(category.Key.StartsWith("scripting/", StringComparison.Ordinal) && category.Key.Count(character => character == '/') == 1 ? "declared script scope" : "project category").Append(". Each type links to its exact declarations and member contracts.\n\n"); + .Append("\ntitle: ") + .Append(JsonSerializer.Serialize(category.Value)) + .Append("\nkind: landing\nowners: []\n---\n\n# ") + .Append(category.Value) + .Append("\n\n"); + if (category.Key == "engine") + { + text.Append( + "Browse public C# contracts from src/ and build/ by their owning project. All other source roots, tests and fixtures are outside Engine API.\n\n" + ); + } + else if (category.Key == "scripting") + { + text.Append( + "Browse the actual projected script API by its declared scope. Runtime contracts are also available to Editor scripts; Authoring annotations are compilation-time contracts.\n\n" + ); + } + else + { + text + .Append("Find types in this ") + .Append( + category.Key.StartsWith("scripting/", StringComparison.Ordinal) + && category.Key.Count(character => character == '/') == 1 + ? "declared script scope" + : "project category" + ) + .Append(". Each type links to its exact declarations and member contracts.\n\n"); + } var children = categories.Where(child => Parent(child.Key) == category.Key).ToArray(); if (children.Length != 0) { @@ -54,24 +81,47 @@ internal static IReadOnlyDictionary Create( foreach (var child in children) { string prefix = "content/en/api/" + child.Key + "/"; - string[] projects = types.Where(type => (Category(facts[type.symbol][0]) + "/").StartsWith(child.Key + "/", StringComparison.Ordinal)) - .Select(type => facts[type.symbol][0].project).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + string[] projects = types + .Where(type => (Category(facts[type.symbol][0]) + "/").StartsWith(child.Key + "/", StringComparison.Ordinal)) + .Select(type => facts[type.symbol][0].project) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); string description = projects.Length == 1 && descriptions.TryGetValue(projects[0], out string? value) - ? value : "Browse " + child.Value + " contracts" + (projects.Length == 0 ? "." : " from " + string.Join(", ", projects.Take(4)) + (projects.Length > 4 ? " and related projects." : ".")); - text.Append("| [").Append(DocumentationApiPresentation.Cell(child.Value)).Append("](") - .Append(Relative(path, prefix + "index.md")).Append(") | ").Append(DocumentationApiPresentation.Cell(description)).Append(" |\n"); + ? value + : "Browse " + + child.Value + + " contracts" + + (projects.Length == 0 + ? "." + : " from " + string.Join(", ", projects.Take(4)) + (projects.Length > 4 ? " and related projects." : ".")); + text.Append("| [") + .Append(DocumentationApiPresentation.Cell(child.Value)) + .Append("](") + .Append(Relative(path, prefix + "index.md")) + .Append(") | ") + .Append(DocumentationApiPresentation.Cell(description)) + .Append(" |\n"); } text.Append('\n'); } DocumentationApiContentEntry[] direct = types.Where(type => Category(facts[type.symbol][0]) == category.Key) - .OrderBy(type => type.title, StringComparer.OrdinalIgnoreCase).ThenBy(type => type.symbol, StringComparer.Ordinal).ToArray(); + .OrderBy(type => type.title, StringComparer.OrdinalIgnoreCase) + .ThenBy(type => type.symbol, StringComparer.Ordinal) + .ToArray(); if (direct.Length != 0) { text.Append("## Types\n\n| Type | Purpose |\n| --- | --- |\n"); - foreach (DocumentationApiContentEntry type in direct) AppendType(text, path, type, direct, facts, fragments); + foreach (DocumentationApiContentEntry type in direct) + { + AppendType(text, path, type, direct, facts, fragments); + } text.Append('\n'); } - if (types.Any(type => type.path == path)) throw new InvalidDataException("API category conflicts with a registered type: " + path); + if (types.Any(type => type.path == path)) + { + throw new InvalidDataException("API category conflicts with a registered type: " + path); + } pages.Add(path, text.ToString()); } return pages; @@ -86,12 +136,20 @@ private static void AppendType( IReadOnlyDictionary? fragments ) { string title = siblings.Count(sibling => sibling.title == type.title) > 1 - ? DocumentationApiContent.QualifiedTitle(facts[type.symbol][0]) : type.title; - text.Append("| [").Append(DocumentationApiPresentation.Cell(title)).Append("](") - .Append(Relative(page, type.path)).Append(") | ") - .Append(fragments is not null && fragments.TryGetValue(type.symbol, out var fragment) + ? DocumentationApiContent.QualifiedTitle(facts[type.symbol][0]) + : type.title; + text.Append("| [") + .Append(DocumentationApiPresentation.Cell(title)) + .Append("](") + .Append(Relative(page, type.path)) + .Append(") | ") + .Append( + fragments is not null && fragments.TryGetValue(type.symbol, out var fragment) ? fragment.TableDescription(facts[type.symbol][0].documentation) - : DocumentationApiPresentation.Cell(DocumentationApiPresentation.Summary(DocumentationXml.Read(facts[type.symbol][0].documentation).summary))) + : DocumentationApiPresentation.Cell( + DocumentationApiPresentation.Summary(DocumentationXml.Read(facts[type.symbol][0].documentation).summary) + ) + ) .Append(" |\n"); } @@ -107,6 +165,7 @@ private static string Parent(string path) string parent = path.LastIndexOf('/') is int index && index >= 0 ? path[..index] : ""; return parent.EndsWith("/_projects", StringComparison.Ordinal) ? parent[..^10] : parent; } + private static string Relative( string from, string to diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPackage.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPackage.cs index b9dd8bdb4..0cafb4cf2 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPackage.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPackage.cs @@ -15,6 +15,7 @@ internal sealed record DocumentationApiPackageFile( string sha256, string text ); + internal sealed record DocumentationApiPackageData( string schema, string repository, @@ -37,14 +38,21 @@ CancellationToken cancellation ) { var options = new Dictionary(StringComparer.Ordinal); for (int index = 0; index < arguments.Length; index += 2) + { if (index + 1 == arguments.Length || arguments[index] is not ("--docs-root" or "--package") - || !options.TryAdd(arguments[index], arguments[index + 1])) + || !options.TryAdd(arguments[index], arguments[index + 1]) + ) { throw new ArgumentException("Usage: docs --docs-root CHECKOUT --package FILE"); + } + } if (options.Count != 2) throw new ArgumentException("Both docs-root and package are required."); string root = Path.GetFullPath(options["--docs-root"]); string packagePath = Path.GetFullPath(options["--package"]); - return await DocumentationApiSynchronization.WithOwnershipAsync(root, - () => Task.FromResult(ExecuteOwned(operation, root, packagePath, cancellation)), cancellation).ConfigureAwait(false); + return await DocumentationApiSynchronization.WithOwnershipAsync( + root, + () => Task.FromResult(ExecuteOwned(operation, root, packagePath, cancellation)), + cancellation + ).ConfigureAwait(false); } private static int ExecuteOwned( @@ -65,8 +73,15 @@ CancellationToken cancellation string text = File.ReadAllText(DocumentationApiFacts.Resolve(root, path)); return new DocumentationApiPackageFile(path, DocumentationMarkdown.Hash(text), text); }).ToArray(); - var package = new DocumentationApiPackageData("inno-api-package/1", binding.repository, binding.revision, - binding.sourceTree, binding.toolingRevision, Identity(files), files); + var package = new DocumentationApiPackageData( + "inno-api-package/1", + binding.repository, + binding.revision, + binding.sourceTree, + binding.toolingRevision, + Identity(files), + files + ); Validate(package); cancellation.ThrowIfCancellationRequested(); AtomicFile.WriteAllBytes(packagePath, JsonSerializer.SerializeToUtf8Bytes(package, DocumentationStore.json)); @@ -74,7 +89,7 @@ CancellationToken cancellation return 0; } DocumentationApiPackageData incoming = JsonSerializer.Deserialize(File.ReadAllBytes(packagePath)) - ?? throw new InvalidDataException("Missing API package."); + ?? throw new InvalidDataException("Missing API package."); DocumentationBinding candidate = Validate(incoming); string receiptPath = DocumentationApiFacts.Resolve(root, C_RECEIPT); if (File.Exists(receiptPath)) @@ -91,7 +106,9 @@ CancellationToken cancellation return new DocumentationApiPackageFile(path, DocumentationMarkdown.Hash(text), text); }).ToArray(); if (Identity(retainedFiles) != incoming.contentIdentity) + { throw new InvalidDataException("The retained API package does not match its import receipt."); + } Console.WriteLine("{\"status\":\"Unchanged\",\"changedFiles\":0}"); return 0; } @@ -101,10 +118,22 @@ CancellationToken cancellation if (File.Exists(oldBindingPath)) { DocumentationBinding previous = ReadBinding(File.ReadAllText(oldBindingPath)); - foreach (string retired in RequiredPaths(previous).Except(updates.Keys, StringComparer.Ordinal)) updates.Add(retired, null); + foreach (string retired in RequiredPaths(previous).Except(updates.Keys, StringComparer.Ordinal)) + { + updates.Add(retired, null); + } } - updates.Add(C_RECEIPT, JsonSerializer.Serialize(new { schema = "inno-api-import/1", incoming.revision, - incoming.sourceTree, incoming.toolingRevision, incoming.contentIdentity }) + "\n"); + updates.Add( + C_RECEIPT, + JsonSerializer.Serialize(new + { + schema = "inno-api-import/1", + incoming.revision, + incoming.sourceTree, + incoming.toolingRevision, + incoming.contentIdentity + }) + "\n" + ); var originals = updates.Keys.ToDictionary(path => path, path => { string absolute = DocumentationApiFacts.Resolve(root, path); @@ -116,8 +145,14 @@ CancellationToken cancellation foreach (var update in updates) { string path = DocumentationApiFacts.Resolve(root, update.Key); - if (update.Value is null) File.Delete(path); - else AtomicFile.WriteAllBytes(path, Encoding.UTF8.GetBytes(update.Value)); + if (update.Value is null) + { + File.Delete(path); + } + else + { + AtomicFile.WriteAllBytes(path, Encoding.UTF8.GetBytes(update.Value)); + } } _ = DocumentationApiFacts.Read(root, candidate); // The synchronization transaction restores content on failure. This outer transaction restores facts. @@ -128,8 +163,14 @@ CancellationToken cancellation foreach (var original in originals) { string path = DocumentationApiFacts.Resolve(root, original.Key); - if (original.Value is null) File.Delete(path); - else AtomicFile.WriteAllBytes(path, original.Value); + if (original.Value is null) + { + File.Delete(path); + } + else + { + AtomicFile.WriteAllBytes(path, original.Value); + } } throw; } @@ -139,8 +180,10 @@ CancellationToken cancellation private static DocumentationBinding Validate(DocumentationApiPackageData package) { if (package.schema != "inno-api-package/1" || package.repository != "https://github.com/Wolfiora/InnoEngine" - || package.files is null || package.files.Count == 0) + || package.files is null || package.files.Count == 0 + ) { throw new InvalidDataException("Unsupported API package provenance."); + } DocumentationStore.RequireHash(package.revision, "API revision", allowGitTree: true); DocumentationStore.RequireHash(package.sourceTree, "API source tree", allowGitTree: true); DocumentationStore.RequireHash(package.toolingRevision, "API tooling revision", allowGitTree: true); @@ -149,21 +192,32 @@ private static DocumentationBinding Validate(DocumentationApiPackageData package { RequireFactPath(file.path); if (!files.TryAdd(file.path, file) || DocumentationMarkdown.Hash(file.text) != file.sha256) + { throw new InvalidDataException("Repeated or corrupt API package file: " + file.path); + } } if (!files.TryGetValue(C_BINDING, out DocumentationApiPackageFile? bindingFile)) + { throw new InvalidDataException("API package has no binding."); + } DocumentationBinding binding = ReadBinding(bindingFile.text); if (binding.repository != package.repository || binding.revision != package.revision || binding.sourceTree != package.sourceTree - || binding.toolingRevision != package.toolingRevision || !RequiredPaths(binding).SequenceEqual(files.Keys.Order(StringComparer.Ordinal))) + || binding.toolingRevision != package.toolingRevision + || !RequiredPaths(binding).SequenceEqual(files.Keys.Order(StringComparer.Ordinal)) + ) { throw new InvalidDataException("API package file set or binding differs from its provenance."); + } if (binding.apiManifests is null || binding.apiManifests.Count == 0 - || binding.apiManifests.Any(capture => capture.sourceRevision != binding.revision || capture.sourceTree != binding.sourceTree)) + || binding.apiManifests.Any(capture => capture.sourceRevision != binding.revision || capture.sourceTree != binding.sourceTree) + ) { throw new InvalidDataException("A complete API package must describe one exact engine input."); + } if (files[binding.projectManifest].sha256 != binding.projectManifestIdentity || binding.apiManifests.Any(capture => files[capture.path].sha256 != capture.sha256) - || Identity(package.files) != package.contentIdentity) + || Identity(package.files) != package.contentIdentity + ) { throw new InvalidDataException("API package content identity differs from its manifests."); + } return binding; } @@ -173,24 +227,39 @@ private static DocumentationBinding ReadBinding(string text) private static string[] RequiredPaths(DocumentationBinding binding) { string[] paths = new[] { C_BINDING, binding.projectManifest }.Concat((binding.apiManifests ?? []).Select(capture => capture.path)) - .Order(StringComparer.Ordinal).ToArray(); - foreach (string path in paths) RequireFactPath(path); + .Order(StringComparer.Ordinal) + .ToArray(); + foreach (string path in paths) + { + RequireFactPath(path); + } if (paths.Distinct(StringComparer.OrdinalIgnoreCase).Count() != paths.Length) + { throw new InvalidDataException("API binding repeats a fact path."); + } return paths; } private static void RequireFactPath(string path) { if (path == C_BINDING) return; - if (!(path.StartsWith("reference/api/", StringComparison.Ordinal) || path.StartsWith("reference/projects/", StringComparison.Ordinal)) + if (!(path.StartsWith("reference/api/", StringComparison.Ordinal) + || path.StartsWith("reference/projects/", StringComparison.Ordinal)) || !path.EndsWith(".json", StringComparison.Ordinal) || path.Contains('\\') - || path.Split('/').Any(part => part is "" or "." or "..") || path is DocumentationApiContent.C_REGISTRY or C_RECEIPT) + || path.Split('/').Any(part => part is "" or "." or "..") || path is DocumentationApiContent.C_REGISTRY or C_RECEIPT + ) { throw new InvalidDataException("API packages can only replace registered JSON facts: " + path); + } } private static string Identity(IEnumerable files) // The binding revision may advance without any API/XML/projection change. Such exports must not create commits. - => DocumentationMarkdown.Hash(string.Join('\n', files.Where(file => file.path != C_BINDING).OrderBy(file => file.path, StringComparer.Ordinal) - .Select(file => file.path + "\0" + file.sha256))); + => DocumentationMarkdown.Hash( + string.Join( + '\n', + files.Where(file => file.path != C_BINDING) + .OrderBy(file => file.path, StringComparer.Ordinal) + .Select(file => file.path + "\0" + file.sha256) + ) + ); } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPresentation.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPresentation.cs index 81f6c911d..c23154417 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPresentation.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPresentation.cs @@ -31,17 +31,22 @@ IReadOnlyDictionary facts string? parent = Parent(fact); if (parent is null) break; if (!facts.TryGetValue(parent, out DocumentationApiFact[]? owner)) + { throw new InvalidDataException("Missing API containing type: " + parent); + } fact = owner[0]; } names.Reverse(); return string.Join('.', names); } - internal static string Cell(string text) => WebUtility.HtmlEncode(text) - .Replace("|", "\\|", StringComparison.Ordinal).Replace("[", "\\[", StringComparison.Ordinal) - .Replace("]", "\\]", StringComparison.Ordinal).Replace("\r", " ", StringComparison.Ordinal) - .Replace("\n", " ", StringComparison.Ordinal); + internal static string Cell(string text) + => WebUtility.HtmlEncode(text) + .Replace("|", "\\|", StringComparison.Ordinal) + .Replace("[", "\\[", StringComparison.Ordinal) + .Replace("]", "\\]", StringComparison.Ordinal) + .Replace("\r", " ", StringComparison.Ordinal) + .Replace("\n", " ", StringComparison.Ordinal); internal static string Summary(string markdown) { @@ -65,21 +70,35 @@ internal static IReadOnlyDictionary ProjectDescriptions(string r if (Markdown.Parse(text, S_MARKDOWN).OfType().FirstOrDefault() is null) continue; YamlMappingNode metadata = DocumentationApiFragment.ReadMetadata(relative, text); if (!metadata.Children.TryGetValue(new YamlScalarNode("kind"), out YamlNode? kind) - || kind is not YamlScalarNode { Value: "project" }) continue; + || kind is not YamlScalarNode { Value: "project" } + ) { + continue; + } if (!metadata.Children.TryGetValue(new YamlScalarNode("owners"), out YamlNode? owners) - || owners is not YamlSequenceNode sequence) continue; + || owners is not YamlSequenceNode sequence + ) { + continue; + } metadata.Children.TryGetValue(new YamlScalarNode("description"), out YamlNode? description); if (description is not null && DocumentationApiFragment.IsNull(description)) description = null; // A synchronized guide has no authored summary. Its generated body must not feed API navigation, // so creating or removing the guide leaves every other planned page unchanged. bool synchronized = metadata.Children.ContainsKey(new YamlScalarNode("symbol")) - && (!metadata.Children.TryGetValue(new YamlScalarNode("source"), out YamlNode? source) || source is YamlScalarNode { Value: "xml" }); + && (!metadata.Children.TryGetValue(new YamlScalarNode("source"), out YamlNode? source) + || source is YamlScalarNode { Value: "xml" }); if (description is null && synchronized) continue; - string summary = description is YamlScalarNode { Value: string value } ? value - : description is YamlSequenceNode items ? string.Join(" ", items.Children.Cast().Select(item => item.Value)) - : Summary(text); + string summary = description is YamlScalarNode { Value: string value } + ? value + : description is YamlSequenceNode items + ? string.Join(" ", items.Children.Cast().Select(item => item.Value)) + : Summary(text); foreach (YamlScalarNode owner in sequence.Children) - if (!result.TryAdd(owner.Value!, summary)) throw new InvalidDataException("Duplicate project guide: " + owner.Value); + { + if (!result.TryAdd(owner.Value!, summary)) + { + throw new InvalidDataException("Duplicate project guide: " + owner.Value); + } + } } return result; } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiSynchronization.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiSynchronization.cs index 414aa82ed..0344756c2 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiSynchronization.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiSynchronization.cs @@ -6,8 +6,8 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Inno.Core.IO; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Tooling.Documentation.Indexing; @@ -19,9 +19,15 @@ internal static async Task ExecuteAsync( CancellationToken cancellation ) { if (arguments.Length != 2 || arguments[0] != "--docs-root") + { throw new ArgumentException("Usage: docs --docs-root CHECKOUT"); + } string root = Path.GetFullPath(arguments[1]); - return await WithOwnershipAsync(root, () => Task.FromResult(ExecuteOwned(operation, root, cancellation)), cancellation).ConfigureAwait(false); + return await WithOwnershipAsync( + root, + () => Task.FromResult(ExecuteOwned(operation, root, cancellation)), + cancellation + ).ConfigureAwait(false); } internal static async Task WithOwnershipAsync( @@ -33,8 +39,11 @@ CancellationToken cancellation var publisher = new BuildCachePublisher(output, BuildCacheArtifactRole.ReusableWorkspace); BuildCacheOwnerCatalog.Register(root, output, "documentation-api-sync", publisher.role, cancellation); using FileLease activity = await publisher.AcquireUseAsync(cancellation).ConfigureAwait(false); - using FileLease writing = await FileLease.AcquireAsync(Path.Combine(output, "writer.lock"), - Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false); + using FileLease writing = await FileLease.AcquireAsync( + Path.Combine(output, "writer.lock"), + Timeout.InfiniteTimeSpan, + cancellation + ).ConfigureAwait(false); return await operation().ConfigureAwait(false); } @@ -46,7 +55,7 @@ CancellationToken cancellation string bindingPath = DocumentationApiFacts.Resolve(root, "reference/engine.lock.json"); byte[] bindingBytes = File.ReadAllBytes(bindingPath); DocumentationBinding binding = JsonSerializer.Deserialize(bindingBytes) - ?? throw new InvalidDataException("Missing engine API binding."); + ?? throw new InvalidDataException("Missing engine API binding."); DocumentationApiPlan plan = DocumentationApiContent.Plan(root, binding); if (operation == "api-plan") { @@ -55,9 +64,17 @@ CancellationToken cancellation } if (operation == "api-check") { - Console.WriteLine(JsonSerializer.Serialize(new { schema = "inno-api-editorial/1", status = plan.edits.Count == 0 ? "Passed" : "Failed", - plan.symbols, conclusion = plan.warnings.Count == 0 ? "success" : "neutral", plan.warnings, - pendingSynchronization = plan.edits.Select(edit => edit.path).ToArray() })); + Console.WriteLine( + JsonSerializer.Serialize(new + { + schema = "inno-api-editorial/1", + status = plan.edits.Count == 0 ? "Passed" : "Failed", + plan.symbols, + conclusion = plan.warnings.Count == 0 ? "success" : "neutral", + plan.warnings, + pendingSynchronization = plan.edits.Select(edit => edit.path).ToArray() + }) + ); return plan.edits.Count == 0 ? 0 : 1; } var originals = new Dictionary(StringComparer.Ordinal); @@ -66,10 +83,16 @@ CancellationToken cancellation string path = DocumentationApiFacts.Resolve(root, edit.path); byte[]? bytes = File.Exists(path) ? File.ReadAllBytes(path) : null; string? identity = bytes is null ? null : DocumentationMarkdown.Hash(File.ReadAllText(path)); - if (identity != edit.before) throw new IOException("API content changed before synchronization: " + edit.path); + if (identity != edit.before) + { + throw new IOException("API content changed before synchronization: " + edit.path); + } originals.Add(path, bytes); } - if (!File.ReadAllBytes(bindingPath).SequenceEqual(bindingBytes)) throw new IOException("API input binding changed before synchronization."); + if (!File.ReadAllBytes(bindingPath).SequenceEqual(bindingBytes)) + { + throw new IOException("API input binding changed before synchronization."); + } cancellation.ThrowIfCancellationRequested(); // This bounded local transaction is committed to Git only by the protected publisher. // Cancellation is observed before mutation; I/O failures restore every original byte. @@ -78,19 +101,41 @@ CancellationToken cancellation foreach (DocumentationApiEdit edit in plan.edits) { string path = DocumentationApiFacts.Resolve(root, edit.path); - if (edit.text is null) File.Delete(path); - else AtomicFile.WriteAllBytes(path, Encoding.UTF8.GetBytes(edit.text)); + if (edit.text is null) + { + File.Delete(path); + } + else + { + AtomicFile.WriteAllBytes(path, Encoding.UTF8.GetBytes(edit.text)); + } } } catch { foreach (var original in originals) - if (original.Value is null) File.Delete(original.Key); - else AtomicFile.WriteAllBytes(original.Key, original.Value); + { + if (original.Value is null) + { + File.Delete(original.Key); + } + else + { + AtomicFile.WriteAllBytes(original.Key, original.Value); + } + } throw; } - Console.WriteLine(JsonSerializer.Serialize(new { status = "Synchronized", plan.symbols, changedFiles = plan.edits.Count, - warnings = plan.warnings.Count, editorialConclusion = plan.warnings.Count == 0 ? "success" : "neutral" })); + Console.WriteLine( + JsonSerializer.Serialize(new + { + status = "Synchronized", + plan.symbols, + changedFiles = plan.edits.Count, + warnings = plan.warnings.Count, + editorialConclusion = plan.warnings.Count == 0 ? "success" : "neutral" + }) + ); return 0; } } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationCatalog.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationCatalog.cs index 076cfdccf..456ad7b5c 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationCatalog.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationCatalog.cs @@ -19,40 +19,69 @@ IReadOnlyList projects foreach (DocumentationProject project in projects) { if (project.entry is null) + { continue; + } if (!identities.TryGetValue(project.entry, out DocumentationPage? entry) - || entry.metadata.kind != "project" || !entry.metadata.owners.Contains(project.name, StringComparer.Ordinal)) + || entry.metadata.kind != "project" || !entry.metadata.owners.Contains(project.name, StringComparer.Ordinal) + ) { throw new InvalidDataException("Project entry does not identify its actual owner: " + project.name); + } } foreach (DocumentationPage page in pages) { foreach (string link in page.links) + { ValidateLink(page, link); + } foreach (string owner in page.metadata.owners) + { if (!owners.ContainsKey(owner)) + { throw new InvalidDataException("Unknown project owner " + owner + ": " + page.path); + } + } if (page.metadata.examples is DocumentationExampleContext examples) + { foreach (string project in examples.projects) + { if (!owners.ContainsKey(project)) + { throw new InvalidDataException("Unknown example project " + project + ": " + page.path); + } + } + } if (page.symbols.Count != 0 && (page.metadata.owners.Length != 1 || page.metadata.apiSurface is null)) + { throw new InvalidDataException("API pages require one actual owner and an explicit surface: " + page.path); - if (page.metadata.apiSurface is string surface && !page.metadata.owners.Any(owner => owners[owner].surfaces.Contains(surface, StringComparer.Ordinal))) + } + if (page.metadata.apiSurface is string surface + && !page.metadata.owners.Any(owner => owners[owner].surfaces.Contains(surface, StringComparer.Ordinal)) + ) { throw new InvalidDataException("API surface is absent from the source manifest: " + page.path); + } Visit(page, new HashSet(StringComparer.Ordinal)); foreach (string contract in page.metadata.contracts) { string[] target = contract.Split('#', 2); if (!identities.TryGetValue(target[0], out DocumentationPage? required) - || (target.Length == 2 && !required.sections.Any(section => section.anchor == target[1]))) + || (target.Length == 2 && !required.sections.Any(section => section.anchor == target[1])) + ) { throw new InvalidDataException("Missing associated contract " + contract + ": " + page.path); + } } } var declarations = new HashSet(StringComparer.Ordinal); foreach (DocumentationPage page in pages) + { foreach (DocumentationSymbol symbol in page.symbols) + { if (!declarations.Add(page.metadata.owners.Single() + ":" + page.metadata.apiSurface + ":" + symbol.id)) + { throw new InvalidDataException("Duplicate authoritative API symbol: " + symbol.id); + } + } + } void ValidateLink( DocumentationPage page, @@ -61,27 +90,36 @@ string link if (Uri.TryCreate(link, UriKind.Absolute, out Uri? external)) { if (external.Scheme is not ("https" or "http" or "mailto" or "inno-doc")) + { throw new InvalidDataException("Unsupported documentation link scheme: " + link); + } return; } string[] parts = link.Split('#', 2); string targetPath = Uri.UnescapeDataString(parts[0].Split('?', 2)[0]); - string target = targetPath.Length == 0 ? Path.Combine(root, page.path) - : Path.GetFullPath(targetPath, Path.GetDirectoryName(Path.Combine(root, page.path))!); + string target = targetPath.Length == 0 + ? Path.Combine(root, page.path) + : Path.GetFullPath(targetPath, Path.GetDirectoryName(Path.Combine(root, page.path))!); PathBoundary.RequireUnlinkedPath(root, target); string relative = Path.GetRelativePath(root, target).Replace('\\', '/'); if (!File.Exists(target)) + { throw new InvalidDataException("Missing documentation link " + link + ": " + page.path); + } if (relative.EndsWith(".md", StringComparison.OrdinalIgnoreCase)) { if (!paths.TryGetValue(relative, out DocumentationPage? selected)) + { throw new InvalidDataException("Markdown links must resolve within the selected content catalog: " + link); + } if (parts.Length == 2 && parts[1].Length != 0) { string anchor = Uri.UnescapeDataString(parts[1]); if (!selected.sections.Any(section => section.anchor == anchor) - && !selected.symbols.Any(symbol => symbol.anchor == anchor)) + && !selected.symbols.Any(symbol => symbol.anchor == anchor) + ) { throw new InvalidDataException("Missing documentation anchor " + link + ": " + page.path); + } } } } @@ -91,17 +129,23 @@ void Visit( HashSet visiting ) { if (!visiting.Add(page.path)) + { throw new InvalidDataException("Cyclic or duplicate API inclusion: " + page.path); + } foreach (string include in page.includes) { string target = Path.GetFullPath(include, Path.GetDirectoryName(Path.Combine(root, page.path))!); PathBoundary.RequireUnlinkedPath(Path.Combine(root, "content", "en"), target); string relative = Path.GetRelativePath(root, target).Replace('\\', '/'); if (!paths.TryGetValue(relative, out DocumentationPage? child)) + { throw new InvalidDataException("Missing included API page: " + relative); + } if (!page.metadata.owners.SequenceEqual(child.metadata.owners, StringComparer.Ordinal) - || page.metadata.apiSurface != child.metadata.apiSurface) + || page.metadata.apiSurface != child.metadata.apiSurface + ) { throw new InvalidDataException("API inclusion crosses project or surface ownership: " + relative); + } Visit(child, visiting); } } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationMarkdown.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationMarkdown.cs index a2cffa50e..58c8d9b9a 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationMarkdown.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationMarkdown.cs @@ -20,9 +20,13 @@ internal static class DocumentationMarkdown { // Changes to parsing, tokenization or cached contracts must change this schema identity. internal const string C_SCHEMA = "inno-doc/6;markdig/1.5.1;yaml/16.3.0;tokens/1"; + private static readonly MarkdownPipeline S_PIPELINE = new MarkdownPipelineBuilder() - .UseYamlFrontMatter().UsePipeTables().UseAutoIdentifiers(AutoIdentifierOptions.GitHub) - .UseGenericAttributes().Build(); + .UseYamlFrontMatter() + .UsePipeTables() + .UseAutoIdentifiers(AutoIdentifierOptions.GitHub) + .UseGenericAttributes() + .Build(); internal static DocumentationPage Parse( string path, @@ -31,41 +35,72 @@ string text MarkdownDocument document = Markdown.Parse(text, S_PIPELINE); YamlFrontMatterBlock? front = document.OfType().SingleOrDefault(); if (front is null) + { throw new InvalidDataException("Documentation requires identity metadata: " + path); + } var yaml = new YamlStream(); yaml.Load(new StringReader(front.Lines.ToString())); if (yaml.Documents.Count != 1 || yaml.Documents[0].RootNode is not YamlMappingNode metadata) + { throw new InvalidDataException("Documentation metadata must be one mapping: " + path); + } string uid = Scalar("uid") ?? throw new InvalidDataException("Missing page uid: " + path); if (!Regex.IsMatch(uid, "^[a-z0-9][a-z0-9._/-]*$") || uid.Split('/').Any(static segment => segment is "" or "." or "..")) + { throw new InvalidDataException("Invalid stable page identity: " + uid); + } string? exampleMode = Scalar("exampleMode"); string[] exampleProjects = Sequence("exampleProjects"); if (exampleMode is not (null or "host" or "runtime-script" or "editor-script") || (exampleMode is null) != (exampleProjects.Length == 0) - || exampleProjects.Distinct(StringComparer.Ordinal).Count() != exampleProjects.Length) + || exampleProjects.Distinct(StringComparer.Ordinal).Count() != exampleProjects.Length + ) { throw new InvalidDataException("Examples require an explicit reference mode and unique project identities: " + path); - var facts = new DocumentationMetadata(uid, Scalar("kind") ?? "", Sequence("owners"), - Sequence("aliases"), Sequence("contracts"), Scalar("apiSurface"), - exampleMode is null ? null : new DocumentationExampleContext(exampleMode, exampleProjects), Scalar("apiScope"), Sequence("apiSurfaces")); + } + var facts = new DocumentationMetadata( + uid, + Scalar("kind") ?? "", + Sequence("owners"), + Sequence("aliases"), + Sequence("contracts"), + Scalar("apiSurface"), + exampleMode is null ? null : new DocumentationExampleContext(exampleMode, exampleProjects), + Scalar("apiScope"), + Sequence("apiSurfaces") + ); if (facts.kind is not ("landing" or "tutorial" or "how-to" or "explanation" or "project" or "api" or "troubleshooting")) + { throw new InvalidDataException("Unknown documentation page kind: " + path); + } if (facts.kind == "project" && facts.owners.Length != 1) + { throw new InvalidDataException("A project entry requires exactly one actual owner: " + path); + } HeadingBlock[] headings = document.Descendants().ToArray(); if (headings.Count(static heading => heading.Level == 1) != 1) + { throw new InvalidDataException("Documentation requires exactly one H1: " + path); + } var sections = new List(); for (int index = 0; index < headings.Length; index++) { HeadingBlock heading = headings[index]; HeadingBlock? next = headings.Skip(index + 1).FirstOrDefault(candidate => candidate.Level <= heading.Level); - sections.Add(new(heading.GetAttributes().Id ?? throw new InvalidDataException("Missing section identity: " + path), - HeadingText(heading), heading.Level, heading.Span.Start, - next?.Span.Start ?? text.Length, heading.Line + 1)); + sections.Add( + new( + heading.GetAttributes().Id ?? throw new InvalidDataException("Missing section identity: " + path), + HeadingText(heading), + heading.Level, + heading.Span.Start, + next?.Span.Start ?? text.Length, + heading.Line + 1 + ) + ); } if (sections.Select(static section => section.anchor).Distinct(StringComparer.Ordinal).Count() != sections.Count) + { throw new InvalidDataException("Duplicate section identity: " + path); + } string[] html = document.Descendants().Select(block => text[block.Span.Start..(block.Span.End + 1)]).ToArray(); foreach (string fragment in html.Concat(document.Descendants().Select(static inline => inline.Tag))) { @@ -74,18 +109,29 @@ string text remaining = Regex.Replace(remaining, "|", string.Empty); remaining = remaining.Replace("
", string.Empty, StringComparison.Ordinal); if (!string.IsNullOrWhiteSpace(remaining)) + { throw new InvalidDataException("Documentation permits only comments and explicit API anchors as HTML: " + path); + } } var rows = new Dictionary(StringComparer.Ordinal); foreach (TableRow row in document.Descendants()) + { foreach (Match anchor in Regex.Matches(text[row.Span.Start..(row.Span.End + 1)], "id=\"(?api-[a-f0-9]+)\"")) + { if (!rows.TryAdd(anchor.Groups["id"].Value, row)) + { throw new InvalidDataException("Duplicate API anchor: " + path); + } + } + } FencedCodeBlock[] fences = document.Descendants().ToArray(); if (fences.Any(static block => block.ClosingFencedCharCount == 0)) + { throw new InvalidDataException("Documentation contains an unclosed code fence: " + path); + } var symbols = new List(); foreach (string block in html) + { foreach (Match marker in Regex.Matches(block, @"")) { string id = marker.Groups["id"].Value; @@ -95,39 +141,72 @@ string text DocumentationSection section = sections.Last(candidate => candidate.start <= start && candidate.end > start); string declaration = row is null ? text[section.start..section.end] : text[row.Span.Start..(row.Span.End + 1)]; string[] code = row is not null - ? row.Descendants().Select(static item => item.Content).ToArray() - : fences - .Where(item => item.Span.Start >= section.start && item.Span.End < section.end && item.Info == "csharp") - .Select(static item => item.Lines.ToString().Replace("\r\n", "\n").TrimEnd('\n')).ToArray(); + ? row.Descendants().Select(static item => item.Content).ToArray() + : fences + .Where(item => item.Span.Start >= section.start && item.Span.End < section.end && item.Info == "csharp") + .Select(static item => item.Lines.ToString().Replace("\r\n", "\n").TrimEnd('\n')) + .ToArray(); symbols.Add(new(id, marker.Groups["hash"].Value, anchor, section.anchor, declaration, code)); } + } string[] includes = html.SelectMany(block => Regex.Matches(block, @"") .Select(static marker => marker.Groups["path"].Value)).ToArray(); var declarations = new Dictionary(); foreach (HtmlBlock block in document.Descendants()) - foreach (Match marker in Regex.Matches(text[block.Span.Start..(block.Span.End + 1)], @"")) { + foreach (Match marker in Regex.Matches( + text[block.Span.Start..(block.Span.End + 1)], + @"" + )) { FencedCodeBlock? fence = fences.FirstOrDefault(candidate => candidate.Span.Start > block.Span.End); string id = marker.Groups["id"].Value; if (fence is null || fence.Info != "csharp" || !string.IsNullOrWhiteSpace(text[(block.Span.End + 1)..fence.Span.Start]) - || !symbols.Any(symbol => symbol.id == id && symbol.code.Contains(fence.Lines.ToString().Replace("\r\n", "\n").TrimEnd('\n'), StringComparer.Ordinal)) + || !symbols.Any( + symbol => ( + symbol.id == id + && symbol.code.Contains(fence.Lines.ToString().Replace("\r\n", "\n").TrimEnd('\n'), StringComparer.Ordinal) + ) + ) || Hash(fence.Lines.ToString().Replace("\r\n", "\n").TrimEnd('\n')) != marker.Groups["hash"].Value - || !declarations.TryAdd(fence.Span.Start, id)) + || !declarations.TryAdd(fence.Span.Start, id) + ) { throw new InvalidDataException("Invalid API declaration association: " + path); + } + } } DocumentationCodeBlockInfo[] codeBlocks = fences.Select(block => { string code = block.Lines.ToString().Replace("\r\n", "\n").TrimEnd('\n'); string identity = Hash(code); string? section = sections.LastOrDefault(candidate => candidate.start <= block.Span.Start)?.anchor; - return new DocumentationCodeBlockInfo(block.Info ?? "", code, identity, block.Line + 1, section, - declarations.TryGetValue(block.Span.Start, out string? declared) ? [declared] - : symbols.Where(symbol => symbol.signatureIdentity == identity).Select(static symbol => symbol.id).ToArray()); + return new DocumentationCodeBlockInfo( + block.Info ?? "", + code, + identity, + block.Line + 1, + section, + declarations.TryGetValue(block.Span.Start, out string? declared) + ? [declared] + : symbols.Where(symbol => symbol.signatureIdentity == identity).Select(static symbol => symbol.id).ToArray() + ); }).ToArray(); - return new(path, Hash(text), HeadingText(headings.Single(static heading => heading.Level == 1)), - text, facts, sections, symbols, includes, document.Descendants() - .Where(static link => link.Url is not null).Select(static link => link.Url!).Distinct(StringComparer.Ordinal).ToArray(), codeBlocks); + return new( + path, + Hash(text), + HeadingText(headings.Single(static heading => heading.Level == 1)), + text, + facts, + sections, + symbols, + includes, + document.Descendants() + .Where(static link => link.Url is not null) + .Select(static link => link.Url!) + .Distinct(StringComparer.Ordinal) + .ToArray(), + codeBlocks + ); string HeadingText(HeadingBlock heading) => Markdown.ToPlainText(text[heading.Span.Start..(heading.Span.End + 1)], S_PIPELINE).Trim(); @@ -135,28 +214,37 @@ string HeadingText(HeadingBlock heading) string? Scalar(string key) { if (!metadata.Children.TryGetValue(new YamlScalarNode(key), out YamlNode? node)) + { return null; + } return node is YamlScalarNode scalar ? scalar.Value : throw new InvalidDataException("Expected scalar " + key + ": " + path); } string[] Sequence(string key) { if (!metadata.Children.TryGetValue(new YamlScalarNode(key), out YamlNode? node)) + { return []; + } if (node is not YamlSequenceNode sequence || sequence.Children.Any(static child => child is not YamlScalarNode)) + { throw new InvalidDataException("Expected string sequence " + key + ": " + path); + } return sequence.Children.Cast().Select(static scalar => scalar.Value ?? "").ToArray(); } } internal static string Hash(string value) => Hash(Encoding.UTF8.GetBytes(value)); + internal static string Hash(byte[] value) => Convert.ToHexStringLower(SHA256.HashData(value)); internal static string[] Tokens(string text) { string expanded = Regex.Replace(text, "([a-z0-9])([A-Z])", "$1 $2"); return Regex.Matches(expanded.ToLowerInvariant(), @"[\p{L}\p{N}]+") - .Select(static match => match.Value).Distinct(StringComparer.Ordinal).ToArray(); + .Select(static match => match.Value) + .Distinct(StringComparer.Ordinal) + .ToArray(); } internal static string OwnText( diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs index d57f404f0..073238c8d 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs @@ -3,9 +3,9 @@ using System.IO; using System.Linq; using System.Net; -using System.Text.RegularExpressions; using System.Text; using System.Text.Json; +using System.Text.RegularExpressions; using YamlDotNet.RepresentationModel; namespace Inno.Tooling.Documentation.Indexing; @@ -15,6 +15,7 @@ internal sealed record DocumentationProjectGuide( string uid, string project ); + internal sealed record DocumentationProjectGuideRegistry( string schema, DocumentationProjectGuide[] entries @@ -33,18 +34,22 @@ internal static DocumentationProjectGuide[] Entries(string root) string path = DocumentationApiFacts.Resolve(root, C_REGISTRY); if (!File.Exists(path)) return []; var registry = JsonSerializer.Deserialize(File.ReadAllText(path)) - ?? throw new InvalidDataException("Missing project guide registry."); + ?? throw new InvalidDataException("Missing project guide registry."); if (registry.schema != "inno-project-guides/1" || registry.entries.Select(entry => entry.path).Distinct(StringComparer.OrdinalIgnoreCase).Count() != registry.entries.Length || registry.entries.Select(entry => entry.project).Distinct(StringComparer.Ordinal).Count() != registry.entries.Length - || registry.entries.Select(entry => entry.uid).Distinct(StringComparer.Ordinal).Count() != registry.entries.Length) + || registry.entries.Select(entry => entry.uid).Distinct(StringComparer.Ordinal).Count() != registry.entries.Length + ) { throw new InvalidDataException("Invalid project guide registry."); + } foreach (var entry in registry.entries) { if (!IsGuidePath(entry.path) || !entry.path.EndsWith(".md", StringComparison.Ordinal) - || entry.path.Split('/').Any(segment => segment is ".." or "." or "")) + || entry.path.Split('/').Any(segment => segment is ".." or "." or "") + ) { throw new InvalidDataException("Project guide is outside its registered content directory."); + } _ = DocumentationApiFacts.Resolve(root, entry.path); } return registry.entries; @@ -57,7 +62,10 @@ IReadOnlyDictionary facts ) { var edits = new List(); var warnings = new List(); - var projects = JsonSerializer.Deserialize(File.ReadAllText(DocumentationApiFacts.Resolve(root, binding.projectManifest)))! + var projects = JsonSerializer + .Deserialize( + File.ReadAllText(DocumentationApiFacts.Resolve(root, binding.projectManifest)) + )! .ToDictionary(project => project.name, StringComparer.Ordinal); var registered = Entries(root); string registryPath = DocumentationApiFacts.Resolve(root, C_REGISTRY); @@ -89,14 +97,32 @@ IReadOnlyDictionary facts string? staleProse = StaleProse(fragment, project, contexts, contract); bool stale = fragment.IsOutdated(staleProse); if (project is null) - warnings.Add(new(entry.project, entry.path, "RemovedProject", "The source project is absent; the registered guide is retained for editorial resolution.")); + { + warnings.Add( + new( + entry.project, + entry.path, + "RemovedProject", + "The source project is absent; the registered guide is retained for editorial resolution." + ) + ); + } else if (stale) + { warnings.Add(new(entry.project, entry.path, "ReviewRequired", "The authored project guide is outdated.")); + } if (!manual || string.IsNullOrWhiteSpace(fragment.body) || fragment.body.Trim() == Body(entry, contexts).Trim()) - warnings.Add(new(entry.project, entry.path, "ManualExplanationRequired", "This project guide uses generated source information.")); + { + warnings.Add( + new(entry.project, entry.path, "ManualExplanationRequired", "This project guide uses generated source information.") + ); + } string updated = Metadata(entry, fragment, contract, staleProse) - + (manual || project is null ? fragment.body : "\n\n" + Body(entry, contexts)); - if (updated != text) edits.Add(new(entry.path, text is null ? null : DocumentationMarkdown.Hash(text), updated)); + + (manual || project is null ? fragment.body : "\n\n" + Body(entry, contexts)); + if (updated != text) + { + edits.Add(new(entry.path, text is null ? null : DocumentationMarkdown.Hash(text), updated)); + } } if (created.Length != 0 || entries.Count != registered.Length) { @@ -105,19 +131,21 @@ IReadOnlyDictionary facts entries.OrderBy(entry => entry.path, StringComparer.Ordinal).ToArray() ); var options = new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" }; - edits.Add(new( - C_REGISTRY, - DocumentationMarkdown.Hash(File.ReadAllText(registryPath)), - JsonSerializer.Serialize(registry, options) + "\n" - )); + edits.Add( + new( + C_REGISTRY, + DocumentationMarkdown.Hash(File.ReadAllText(registryPath)), + JsonSerializer.Serialize(registry, options) + "\n" + ) + ); } return new(edits, warnings, 0); } private static bool IsGuidePath(string path) => path.StartsWith(C_GUIDES, StringComparison.Ordinal) - || path.StartsWith(C_BACKEND_GUIDES, StringComparison.Ordinal) - || path.StartsWith(C_TEST_GUIDES, StringComparison.Ordinal); + || path.StartsWith(C_BACKEND_GUIDES, StringComparison.Ordinal) + || path.StartsWith(C_TEST_GUIDES, StringComparison.Ordinal); // Plans a synchronized guide for each reader-facing project that no project page owns yet. // Authored project pages own their projects without a registry entry; synchronization never claims them. @@ -131,11 +159,14 @@ DocumentationProjectGuide[] registered var guides = new List(); foreach (var project in projects.OrderBy(project => project.name, StringComparer.Ordinal)) { - if (project.path.StartsWith("platforms/", StringComparison.Ordinal) || owned.Contains(project.name)) continue; + if (project.path.StartsWith("platforms/", StringComparison.Ordinal) || owned.Contains(project.name)) + { + continue; + } string slug = project.name.ToLowerInvariant().Replace('.', '-'); string directory = project.path.StartsWith("tests/", StringComparison.Ordinal) - ? C_TEST_GUIDES - : project.path.StartsWith("backends/", StringComparison.Ordinal) ? C_BACKEND_GUIDES : C_GUIDES; + ? C_TEST_GUIDES + : project.path.StartsWith("backends/", StringComparison.Ordinal) ? C_BACKEND_GUIDES : C_GUIDES; guides.Add(new(directory + slug + ".md", "project." + slug, project.name)); } return guides.ToArray(); @@ -153,7 +184,10 @@ IDictionary inputs var entries = Entries(root); if (entries.Length == 0) return; inputs[C_REGISTRY] = DocumentationMarkdown.Hash(File.ReadAllText(DocumentationApiFacts.Resolve(root, C_REGISTRY))); - var projects = JsonSerializer.Deserialize(File.ReadAllText(DocumentationApiFacts.Resolve(root, binding.projectManifest)))! + var projects = JsonSerializer + .Deserialize( + File.ReadAllText(DocumentationApiFacts.Resolve(root, binding.projectManifest)) + )! .ToDictionary(project => project.name, StringComparer.Ordinal); foreach (var entry in entries) { @@ -165,17 +199,32 @@ IDictionary inputs string[] summaries = fragment.Summaries(""); fragment.metadata.Children.Remove(new YamlScalarNode("description")); string header = "---\n" + Serialize(fragment.metadata) + "\n---"; - var text = new StringBuilder(header).Append("\n\n> [!").Append(status) - .Append("]\n> Project guide source status.\n\n# ").Append(entry.project).Append("\n\n"); + var text = new StringBuilder(header).Append("\n\n> [!") + .Append(status) + .Append("]\n> Project guide source status.\n\n# ") + .Append(entry.project) + .Append("\n\n"); if (summaries.Length != 0) - text.Append("> ").Append(string.Join("\n> ", summaries.Select(summary => "- " + summary.Replace("\n", "\n> ", StringComparison.Ordinal)))).Append("\n\n"); + { + text + .Append("> ") + .Append( + string.Join("\n> ", summaries.Select(summary => "- " + summary.Replace("\n", "\n> ", StringComparison.Ordinal))) + ) + .Append("\n\n"); + } text.Append(Regex.Replace(fragment.body, @"\A\s*# [^\r\n]+\r?\n", "")); if (project is not null) { - text.Append("\n\n## Source project facts\n\n**Project:** `").Append(project.name) - .Append("` \n**Source:** `").Append(project.path).Append("`\n\n"); - var types = contexts.Where(fact => fact.kind == "NamedType").GroupBy(fact => fact.key, StringComparer.Ordinal) - .OrderBy(group => group.Key, StringComparer.Ordinal).ToArray(); + text.Append("\n\n## Source project facts\n\n**Project:** `") + .Append(project.name) + .Append("` \n**Source:** `") + .Append(project.path) + .Append("`\n\n"); + var types = contexts.Where(fact => fact.kind == "NamedType") + .GroupBy(fact => fact.key, StringComparer.Ordinal) + .OrderBy(group => group.Key, StringComparer.Ordinal) + .ToArray(); if (types.Length != 0) { text.Append("| Type | API | Description |\n| --- | --- | --- |\n"); @@ -183,16 +232,28 @@ IDictionary inputs { var fact = type.First(); var api = apiEntries[fact.key]; - text.Append("| [").Append(DocumentationApiPresentation.Cell(api.title)).Append("](") + text.Append("| [") + .Append(DocumentationApiPresentation.Cell(api.title)) + .Append("](") .Append(Path.GetRelativePath(Path.GetDirectoryName(entry.path)!, api.path).Replace('\\', '/')) - .Append(") | ").Append(fact.scope ?? fact.family).Append(" | ") - .Append(fragments[fact.key].TableDescription(fact.documentation)).Append(" |\n"); + .Append(") | ") + .Append(fact.scope ?? fact.family) + .Append(" | ") + .Append(fragments[fact.key].TableDescription(fact.documentation)) + .Append(" |\n"); } } } if (project is not null) - text.Append("\n\n[Source declaration](").Append(binding.repository).Append("/blob/") - .Append(binding.revision).Append('/').Append(project.path).Append(")\n"); + { + text.Append("\n\n[Source declaration](") + .Append(binding.repository) + .Append("/blob/") + .Append(binding.revision) + .Append('/') + .Append(project.path) + .Append(")\n"); + } pages[entry.path] = text.ToString(); } } @@ -202,9 +263,11 @@ private static DocumentationApiFragment Read( string text ) { var fragment = DocumentationApiFragment.Read(entry.path, text) - ?? throw new InvalidDataException("Registered project guide is missing ownership metadata: " + entry.path); + ?? throw new InvalidDataException("Registered project guide is missing ownership metadata: " + entry.path); if (fragment.symbol != "project:" + entry.project || fragment.uid != entry.uid) + { throw new InvalidDataException("Project guide identity differs from registry: " + entry.path); + } return fragment; } @@ -214,8 +277,11 @@ DocumentationApiFact[] contexts ) { var identity = new { - metadata = project is null ? null : project with { surfaces = project.surfaces.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray() }, - symbols = contexts.GroupBy(fact => fact.key, StringComparer.Ordinal).OrderBy(group => group.Key, StringComparer.Ordinal) + metadata = project is null + ? null + : project with { surfaces = project.surfaces.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray() }, + symbols = contexts.GroupBy(fact => fact.key, StringComparer.Ordinal) + .OrderBy(group => group.Key, StringComparer.Ordinal) .Select(group => new { symbol = group.Key, contract = DocumentationApiContent.Contract(group, normalizeXml: true) }) }; return DocumentationMarkdown.Hash(JsonSerializer.Serialize(identity)); @@ -228,7 +294,9 @@ DocumentationApiFact[] contexts string contract ) { if (string.IsNullOrEmpty(fragment.sourceFingerprint) || fragment.sourceFingerprint == contract) + { return fragment.StaleProse(contract); + } string legacy = DocumentationMarkdown.Hash(JsonSerializer.Serialize(project) + "\n" + DocumentationApiContent.Contract(contexts)); return fragment.StaleProse(contract, legacy); } @@ -241,23 +309,35 @@ private static string Metadata( ) { var generated = new YamlMappingNode { - { "uid", entry.uid }, { "symbol", "project:" + entry.project }, { "title", entry.project }, - { "kind", "project" }, { "owners", new YamlSequenceNode(new YamlScalarNode(entry.project)) }, + { "uid", entry.uid }, + { "symbol", "project:" + entry.project }, + { "title", entry.project }, + { "kind", "project" }, + { "owners", new YamlSequenceNode(new YamlScalarNode(entry.project)) }, { "sourceFingerprint", fingerprint }, - { "contracts", fragment.metadata.Children.TryGetValue(new YamlScalarNode("contracts"), out var contracts) ? contracts : new YamlSequenceNode() } + { "contracts", fragment.metadata.Children.TryGetValue(new YamlScalarNode("contracts"), out var contracts) + ? contracts + : new YamlSequenceNode() } }; if (staleProse is not null) generated.Add("outdatedFor", staleProse); var authored = new YamlMappingNode { { "source", fragment.source }, - { "description", fragment.metadata.Children.TryGetValue(new YamlScalarNode("description"), out var description) ? description : new YamlScalarNode("null") { Style = YamlDotNet.Core.ScalarStyle.Plain } }, + { "description", fragment.metadata.Children.TryGetValue(new YamlScalarNode("description"), out var description) + ? description + : new YamlScalarNode("null") { Style = YamlDotNet.Core.ScalarStyle.Plain } }, { "outdated", fragment.source != "xml" && fragment.ExplicitlyOutdated ? "true" : "false" } }; foreach (var field in fragment.metadata.Children) + { if (((YamlScalarNode)field.Key).Value is not ("reviewed" or "outdatedFor") - && !generated.Children.ContainsKey(field.Key) && !authored.Children.ContainsKey(field.Key)) authored.Add(field.Key, field.Value); + && !generated.Children.ContainsKey(field.Key) && !authored.Children.ContainsKey(field.Key) + ) { + authored.Add(field.Key, field.Value); + } + } return "---\n# Generated metadata. Maintained by project synchronization tooling.\n" + Serialize(generated) - + "\n\n# Authoring metadata. Edit these fields and the explanation below.\n" + Serialize(authored) + "\n---"; + + "\n\n# Authoring metadata. Edit these fields and the explanation below.\n" + Serialize(authored) + "\n---"; } private static string Body( @@ -265,14 +345,21 @@ private static string Body( DocumentationApiFact[] contexts ) { var text = new StringBuilder("# ").Append(entry.project).Append("\n\n## Source contracts\n\n"); - var types = contexts.Where(fact => fact.kind == "NamedType").GroupBy(fact => fact.key, StringComparer.Ordinal) + var types = contexts.Where(fact => fact.kind == "NamedType") + .GroupBy(fact => fact.key, StringComparer.Ordinal) .OrderBy(group => group.Key, StringComparer.Ordinal); foreach (var type in types) { var fact = type.First(); - text.Append("### ").Append(WebUtility.HtmlEncode(fact.id[2..])).Append(" (") - .Append(fact.scope ?? fact.family).Append(")\n\n"); - foreach (string summary in DocumentationXml.Read(fact.documentation).summaries) text.Append(summary).Append("\n\n"); + text.Append("### ") + .Append(WebUtility.HtmlEncode(fact.id[2..])) + .Append(" (") + .Append(fact.scope ?? fact.family) + .Append(")\n\n"); + foreach (string summary in DocumentationXml.Read(fact.documentation).summaries) + { + text.Append(summary).Append("\n\n"); + } } if (!types.Any()) text.Append("No public type XML is present for this project in the selected API snapshot.\n"); return text.ToString(); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationReferenceStore.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationReferenceStore.cs index 414be8df7..e45309f1b 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationReferenceStore.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationReferenceStore.cs @@ -29,9 +29,22 @@ CancellationToken cancellation var inputs = new Dictionary(StringComparer.Ordinal); var references = new List(); var owners = projects.ToDictionary(static project => project.name, StringComparer.Ordinal); - await AddAsync(new(binding.projectManifest, binding.projectManifestIdentity, "project-inventory", null, null, - binding.revision, binding.sourceTree, projects.Select(static project => project.name).Order(StringComparer.Ordinal).ToArray()), - projectBytes).ConfigureAwait(false); + await AddAsync( + new( + binding.projectManifest, + binding.projectManifestIdentity, + "project-inventory", + null, + null, + binding.revision, + binding.sourceTree, + projects + .Select(static project => project.name) + .Order(StringComparer.Ordinal) + .ToArray() + ), + projectBytes + ).ConfigureAwait(false); foreach (DocumentationApiCapture capture in binding.apiManifests ?? []) { cancellation.ThrowIfCancellationRequested(); @@ -41,27 +54,46 @@ await AddAsync(new(binding.projectManifest, binding.projectManifestIdentity, "pr string path = Resolve(root, capture.path); byte[] bytes = File.ReadAllBytes(path); if (DocumentationMarkdown.Hash(bytes) != capture.sha256) + { throw new InvalidDataException("API reference identity differs from its binding: " + capture.path); + } using JsonDocument payload = JsonDocument.Parse(bytes); JsonElement facts = payload.RootElement; string? target = facts.TryGetProperty("target", out JsonElement selectedTarget) ? selectedTarget.GetString() : null; if (string.IsNullOrWhiteSpace(capture.model) || string.IsNullOrWhiteSpace(capture.configuration) || facts.GetProperty("model").GetString() != capture.model - || facts.GetProperty("configuration").GetString() != capture.configuration || target != capture.target) + || facts.GetProperty("configuration").GetString() != capture.configuration || target != capture.target + ) { throw new InvalidDataException("API reference context differs from its binding: " + capture.path); + } var selected = new HashSet(StringComparer.Ordinal); foreach (JsonElement project in facts.GetProperty("projects").EnumerateArray()) { string name = project.GetProperty("name").GetString()!; if (!owners.TryGetValue(name, out DocumentationProject? owner) || !selected.Add(name) || owner.path != project.GetProperty("project").GetString() - || !owner.surfaces.Contains(capture.model, StringComparer.Ordinal)) + || !owner.surfaces.Contains(capture.model, StringComparer.Ordinal) + ) { throw new InvalidDataException("API reference owner or surface is absent, repeated or mismatched: " + name); + } } if (selected.Count == 0) + { throw new InvalidDataException("API reference contains no project facts: " + capture.path); - await AddAsync(new(capture.path, capture.sha256, capture.model, capture.configuration, capture.target, - capture.sourceRevision, capture.sourceTree, selected.Order(StringComparer.Ordinal).ToArray()), bytes).ConfigureAwait(false); + } + await AddAsync( + new( + capture.path, + capture.sha256, + capture.model, + capture.configuration, + capture.target, + capture.sourceRevision, + capture.sourceTree, + selected.Order(StringComparer.Ordinal).ToArray() + ), + bytes + ).ConfigureAwait(false); } return new(references.OrderBy(static reference => reference.path, StringComparer.Ordinal).ToArray(), inputs); @@ -71,10 +103,15 @@ byte[] bytes ) { string source = Resolve(root, reference.path); if (!inputs.TryAdd(source, bytes)) + { throw new InvalidDataException("Repeated documentation reference path: " + reference.path); + } string directory = Path.Combine(output, "references", reference.identity); string file = PathBoundary.RequireUnlinkedPath(output, Path.Combine(directory, "reference.json")); - string lease = PathBoundary.RequireUnlinkedPath(output, Path.Combine(output, "leases", "reference-" + reference.identity + ".lock")); + string lease = PathBoundary.RequireUnlinkedPath( + output, + Path.Combine(output, "leases", "reference-" + reference.identity + ".lock") + ); using FileLease writing = await FileLease.AcquireAsync(lease, Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false); if (!File.Exists(file) || DocumentationMarkdown.Hash(File.ReadAllBytes(file)) != reference.identity) { @@ -89,8 +126,12 @@ byte[] bytes internal static void Verify(Prepared prepared) { foreach (var input in prepared.inputs) + { if (!File.ReadAllBytes(input.Key).AsSpan().SequenceEqual(input.Value)) + { throw new IOException("Documentation reference changed during preparation: " + input.Key); + } + } } private static string Resolve( @@ -99,8 +140,10 @@ string relative ) { string path = PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, relative)); if (!relative.StartsWith("reference/", StringComparison.Ordinal) || !relative.EndsWith(".json", StringComparison.Ordinal) - || relative != Path.GetRelativePath(root, path).Replace('\\', '/')) + || relative != Path.GetRelativePath(root, path).Replace('\\', '/') + ) { throw new InvalidDataException("Expected a canonical JSON path within the documentation reference owner: " + relative); + } return path; } } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationXml.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationXml.cs index 4611949ae..f3ef0ca73 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationXml.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationXml.cs @@ -19,35 +19,51 @@ internal static class DocumentationXml internal static DocumentationXmlContent Read(string xml) { if (string.IsNullOrWhiteSpace(xml)) return new(["No XML description is available."], ""); - using var reader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }); + using var reader = XmlReader.Create( + new StringReader(xml), + new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null } + ); XElement root = XElement.Load(reader); string[] summaries = []; - string body = string.Join("\n\n", root.Elements().GroupBy(element => element.Name.LocalName) - .OrderBy(group => group.Key == "summary" ? 0 : 1).Select(group => - { - string heading = group.Key switch - { - "summary" => "", "remarks" => "Remarks", "param" => "Parameters", "typeparam" => "Type parameters", - "returns" => "Returns", "value" => "Value", "exception" => "Exceptions", "example" => "Example", "seealso" => "See also", - "inheritdoc" => throw new InvalidDataException("Resolve inherited XML before publishing API content."), - _ => throw new InvalidDataException("Unsupported API XML element: " + group.Key) - }; - string[] parts = group.Select(element => element.Name.LocalName switch - { - "summary" or "remarks" or "returns" or "value" or "example" => Children(element).Trim(), - "param" => "**Parameter `" + element.Attribute("name")?.Value + "`:** " + Children(element).Trim(), - "typeparam" => "**Type parameter `" + element.Attribute("name")?.Value + "`:** " + Children(element).Trim(), - "exception" => "**Exception `" + element.Attribute("cref")?.Value + "`:** " + Children(element).Trim(), - "seealso" => Node(element), - _ => throw new InvalidDataException("Unsupported API XML element: " + element.Name) - }).Where(text => text.Length != 0).ToArray(); - if (group.Key == "summary") + string body = string.Join( + "\n\n", + root.Elements() + .GroupBy(element => element.Name.LocalName) + .OrderBy(group => group.Key == "summary" ? 0 : 1) + .Select(group => { - summaries = parts; - return ""; - } - return parts.Length == 0 ? "" : "## " + heading + "\n\n" + string.Join("\n\n", parts); - }).Where(text => text.Length != 0)); + string heading = group.Key switch + { + "summary" => "", + "remarks" => "Remarks", + "param" => "Parameters", + "typeparam" => "Type parameters", + "returns" => "Returns", + "value" => "Value", + "exception" => "Exceptions", + "example" => "Example", + "seealso" => "See also", + "inheritdoc" => throw new InvalidDataException("Resolve inherited XML before publishing API content."), + _ => throw new InvalidDataException("Unsupported API XML element: " + group.Key) + }; + string[] parts = group.Select(element => element.Name.LocalName switch + { + "summary" or "remarks" or "returns" or "value" or "example" => Children(element).Trim(), + "param" => "**Parameter `" + element.Attribute("name")?.Value + "`:** " + Children(element).Trim(), + "typeparam" => "**Type parameter `" + element.Attribute("name")?.Value + "`:** " + Children(element).Trim(), + "exception" => "**Exception `" + element.Attribute("cref")?.Value + "`:** " + Children(element).Trim(), + "seealso" => Node(element), + _ => throw new InvalidDataException("Unsupported API XML element: " + element.Name) + }).Where(text => text.Length != 0).ToArray(); + if (group.Key == "summary") + { + summaries = parts; + return ""; + } + return parts.Length == 0 ? "" : "## " + heading + "\n\n" + string.Join("\n\n", parts); + }) + .Where(text => text.Length != 0) + ); return new(summaries, body.Length == 0 ? "" : body + "\n"); } @@ -55,21 +71,32 @@ internal static DocumentationXmlContent Read(string xml) private static string Node(XNode node) { - if (node is XText text) return Regex.Replace(text.Value, @"\s+", " ") - .Replace("\\", "\\\\", StringComparison.Ordinal).Replace("<", "\\<", StringComparison.Ordinal) - .Replace(">", "\\>", StringComparison.Ordinal).Replace("[", "\\[", StringComparison.Ordinal) - .Replace("]", "\\]", StringComparison.Ordinal).Replace("*", "\\*", StringComparison.Ordinal) - .Replace("_", "\\_", StringComparison.Ordinal).Replace("`", "\\`", StringComparison.Ordinal); + if (node is XText text) + { + return Regex.Replace(text.Value, @"\s+", " ") + .Replace("\\", "\\\\", StringComparison.Ordinal) + .Replace("<", "\\<", StringComparison.Ordinal) + .Replace(">", "\\>", StringComparison.Ordinal) + .Replace("[", "\\[", StringComparison.Ordinal) + .Replace("]", "\\]", StringComparison.Ordinal) + .Replace("*", "\\*", StringComparison.Ordinal) + .Replace("_", "\\_", StringComparison.Ordinal) + .Replace("`", "\\`", StringComparison.Ordinal); + } if (node is XComment) return ""; if (node is not XElement element) throw new InvalidDataException("Unsupported XML documentation node."); return element.Name.LocalName switch { "see" or "seealso" => element.Attribute("href") is XAttribute href - ? "[" + (element.Value.Length == 0 ? href.Value : element.Value) + "](" + href.Value + ")" - : Code((element.Attribute("cref") ?? element.Attribute("langword"))?.Value - ?? throw new InvalidDataException("An XML reference requires cref, href or langword.")), - "paramref" or "typeparamref" => Code(element.Attribute("name")?.Value - ?? throw new InvalidDataException("An XML parameter reference requires its name.")), + ? "[" + (element.Value.Length == 0 ? href.Value : element.Value) + "](" + href.Value + ")" + : Code( + (element.Attribute("cref") ?? element.Attribute("langword"))?.Value + ?? throw new InvalidDataException("An XML reference requires cref, href or langword.") + ), + "paramref" or "typeparamref" => Code( + element.Attribute("name")?.Value + ?? throw new InvalidDataException("An XML parameter reference requires its name.") + ), "c" => Code(element.Value), "code" => CodeBlock(element), "para" => "\n\n" + Children(element).Trim() + "\n\n", @@ -92,14 +119,21 @@ private static string CodeBlock(XElement element) { string value = element.Value; string[] lines = value.ReplaceLineEndings("\n").Trim('\n').Split('\n'); - int indentation = lines.Where(line => !string.IsNullOrWhiteSpace(line)).Select(line => line.Length - line.TrimStart().Length).DefaultIfEmpty(0).Min(); + int indentation = lines + .Where(line => !string.IsNullOrWhiteSpace(line)) + .Select(line => line.Length - line.TrimStart().Length) + .DefaultIfEmpty(0) + .Min(); string code = string.Join('\n', lines.Select(line => line.Length >= indentation ? line[indentation..] : "")); // XML code inside an example is executable C#; an unlabelled formula in remarks is explanatory text. // This is structural XML metadata, not a guess based on whether a snippet happens to compile. string? language = (string?)element.Attribute("language") ?? (string?)element.Attribute("lang"); if (language is null && !element.Ancestors("example").Any() && !code.Contains('\n')) return Code(code.Trim()); language ??= element.Ancestors("example").Any() ? "csharp" : "text"; - if (!Regex.IsMatch(language, "^[a-zA-Z0-9#+-]+$")) throw new InvalidDataException("Invalid XML example language."); + if (!Regex.IsMatch(language, "^[a-zA-Z0-9#+-]+$")) + { + throw new InvalidDataException("Invalid XML example language."); + } string fence = new('`', Math.Max(3, Regex.Matches(code, "`+").Select(match => match.Length + 1).DefaultIfEmpty(3).Max())); return "\n\n" + fence + language + "\n" + code + "\n" + fence + "\n\n"; } @@ -109,7 +143,9 @@ private static string List(XElement element) string kind = (string?)element.Attribute("type") ?? "bullet"; XElement[] items = element.Elements("item").ToArray(); if (items.Length == 0 || element.Elements().Any(child => child.Name.LocalName is not ("item" or "listheader"))) + { throw new InvalidDataException("An XML list requires supported, nonempty items."); + } if (kind == "table") { XElement? header = element.Element("listheader"); @@ -117,16 +153,32 @@ private static string List(XElement element) { if (!row.Elements().Any() || row.Elements().Any(child => child.Name.LocalName is not ("term" or "description")) || row.Elements("term").Count() > 1 || row.Elements("description").Count() > 1 - || row.Nodes().OfType().Any(text => !string.IsNullOrWhiteSpace(text.Value))) - throw new InvalidDataException("An XML table requires explicit term and description cells; unstructured content cannot be discarded."); + || row.Nodes().OfType().Any(text => !string.IsNullOrWhiteSpace(text.Value)) + ) { + throw new InvalidDataException( + "An XML table requires explicit term and description cells; unstructured content cannot be discarded." + ); + } } - string Cell(XElement? value) => value is null ? "" : Children(value).Trim().Replace("|", "\\|", StringComparison.Ordinal).ReplaceLineEndings(" "); - return "\n\n| " + (header is null ? "Term | Description" : Cell(header.Element("term")) + " | " + Cell(header.Element("description"))) - + " |\n| --- | --- |\n" + string.Join('\n', items.Select(item => "| " + Cell(item.Element("term")) + " | " + Cell(item.Element("description")) + " |")) + "\n\n"; + string Cell(XElement? value) + => value is null ? "" : Children(value).Trim().Replace("|", "\\|", StringComparison.Ordinal).ReplaceLineEndings(" "); + return "\n\n| " + + (header is null ? "Term | Description" : Cell(header.Element("term")) + " | " + Cell(header.Element("description"))) + + " |\n| --- | --- |\n" + + string.Join( + '\n', + items.Select(item => "| " + Cell(item.Element("term")) + " | " + Cell(item.Element("description")) + " |") + ) + + "\n\n"; } if (kind is not ("bullet" or "number")) throw new InvalidDataException("Unsupported XML list type: " + kind); string prefix = kind == "number" ? "1. " : "- "; - return "\n\n" + string.Join('\n', items.Select(item => prefix + Children(item).Trim() - .Replace("\n", "\n" + new string(' ', prefix.Length), StringComparison.Ordinal))) + "\n\n"; + return "\n\n" + string.Join( + '\n', + items.Select(item => ( + prefix + Children(item).Trim() + .Replace("\n", "\n" + new string(' ', prefix.Length), StringComparison.Ordinal) + )) + ) + "\n\n"; } } diff --git a/tools/Inno.Tooling.Validation/ValidationAcceptance.cs b/tools/Inno.Tooling.Validation/ValidationAcceptance.cs index a4eefe27e..8c082d49b 100644 --- a/tools/Inno.Tooling.Validation/ValidationAcceptance.cs +++ b/tools/Inno.Tooling.Validation/ValidationAcceptance.cs @@ -15,8 +15,10 @@ ValidationEvidence evidence if (current.profile != ValidationProfile.Full || !current.full || current.extended || accepted.profile is not (ValidationProfile.Master or ValidationProfile.Full) || accepted.extended || current.commit != accepted.commit || current.tree != accepted.tree - || current.nativeDependencies != accepted.nativeDependencies) + || current.nativeDependencies != accepted.nativeDependencies + ) { throw new InvalidDataException("Continuation requires an exact functional candidate and default-branch execution policy."); + } } // This reuses a completed functional certification, never mutable runner outputs or performance samples. @@ -31,19 +33,25 @@ ValidationEvidence evidence || current.profile != ValidationProfile.Full || accepted.profile is not (ValidationProfile.Full or ValidationProfile.Master) || current.commit != accepted.commit || current.tree != accepted.tree || current.environment != accepted.environment || current.configuration != accepted.configuration - || current.nativeDependencies != accepted.nativeDependencies || current.checks.Length != accepted.checks.Length) + || current.nativeDependencies != accepted.nativeDependencies || current.checks.Length != accepted.checks.Length + ) { return false; + } foreach (ValidationCheck check in current.checks) { ValidationCheck? previous = accepted.checks.SingleOrDefault(candidate => candidate.id == check.id); if (previous is null || check.layer == "performance" && check.exclusion is null || ValidationInputs.CheckIdentity(current, check, current.inputs) - != ValidationInputs.CheckIdentity(accepted, previous, accepted.inputs)) + != ValidationInputs.CheckIdentity(accepted, previous, accepted.inputs) + ) { return false; + } ValidationResult result = evidence.results.Single(candidate => candidate.id == check.id); if (check.exclusion is null && result.outputs is null) + { throw new InvalidDataException("Completed acceptance has no output inventory: " + check.id); + } } return true; } diff --git a/tools/Inno.Tooling.Validation/ValidationBuildInputs.cs b/tools/Inno.Tooling.Validation/ValidationBuildInputs.cs index 1558abf1e..27123dbb4 100644 --- a/tools/Inno.Tooling.Validation/ValidationBuildInputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationBuildInputs.cs @@ -31,39 +31,62 @@ CancellationToken cancellation var variantInputs = new HashSet(StringComparer.Ordinal); foreach (ValidationCheck check in m_checks) { - JsonElement snapshot = plan.contexts[context].sdkGraph.EnumerateArray().Single(snapshot => - Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == check.owner); + JsonElement snapshot = plan.contexts[context].sdkGraph.EnumerateArray().Single(snapshot => ( + Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == check.owner + )); if (snapshot.GetProperty("Variants").GetArrayLength() != 0) + { variantInputs.UnionWith(plan.inputSets[check.owner]); + } var dependencyPaths = check.inputs.Where(input => input != "@" + check.owner) - .SelectMany(input => input.StartsWith('@') ? plan.inputSets[input[1..]] : [input]).ToHashSet(StringComparer.Ordinal); - m_selectedSources.UnionWith(snapshot.GetProperty("Items").GetProperty("Compile").EnumerateArray() - .Select(item => Path.GetRelativePath(plan.root, item.GetProperty("FullPath").GetString()!).Replace('\\', '/')) - .Where(path => plan.inputs.ContainsKey(path) && !dependencyPaths.Contains(path))); + .SelectMany(input => input.StartsWith('@') ? plan.inputSets[input[1..]] : [input]) + .ToHashSet(StringComparer.Ordinal); + m_selectedSources.UnionWith( + snapshot.GetProperty("Items") + .GetProperty("Compile") + .EnumerateArray() + .Select(item => Path.GetRelativePath(plan.root, item.GetProperty("FullPath").GetString()!).Replace('\\', '/')) + .Where(path => plan.inputs.ContainsKey(path) && !dependencyPaths.Contains(path)) + ); } // Root-only Clean does not cover additional property instances reached through another root's references. // Keep their complete inputs protected until every effective output instance has an explicit clean boundary. m_selectedSources.ExceptWith(variantInputs); m_path = PathBoundary.RequireUnlinkedPath(plan.artifacts, Path.Combine(plan.artifacts, "validation-build-" + context + ".json")); - m_completed = File.Exists(m_path) ? JsonSerializer.Deserialize>(File.ReadAllBytes(m_path)) - ?? throw new InvalidDataException("Completed compilation input identities are empty.") : new(StringComparer.Ordinal); + m_completed = File.Exists(m_path) + ? JsonSerializer.Deserialize>(File.ReadAllBytes(m_path)) + ?? throw new InvalidDataException("Completed compilation input identities are empty.") + : new(StringComparer.Ordinal); } internal bool RequiresCompilation(ValidationDependencyInputs dependencies) - => m_checks.Any(check => !m_completed.TryGetValue(check.owner, out Compilation? previous) + => m_checks.Any(check => ( + !m_completed.TryGetValue(check.owner, out Compilation? previous) || previous.inputs != Identity(check, dependencies, allowMissing: true) - || !ValidationOutputs.Matches(m_plan, check, new(check.id, "Passed", previous.inputs, 0, string.Empty, previous.outputs), - m_cancellation, m_outputDigests)); + || !ValidationOutputs.Matches( + m_plan, + check, + new(check.id, "Passed", previous.inputs, 0, string.Empty, previous.outputs), + m_cancellation, + m_outputDigests + ) + )); internal bool RequiresDependencyCompilation(ValidationDependencyInputs dependencies) { foreach (ValidationCheck check in m_checks) { - string? reason = !m_completed.TryGetValue(check.owner, out Compilation? previous) ? "no completed compilation" - : previous.dependencySources != Identity(check, dependencies, allowMissing: true, excludeSelectedSources: true) - ? "retained dependency inputs changed" - : !ValidationOutputs.Matches(m_plan, check, new(check.id, "Passed", previous.inputs, 0, string.Empty, previous.outputs), - m_cancellation, m_outputDigests) ? "compiled output content changed" : null; + string? reason = !m_completed.TryGetValue(check.owner, out Compilation? previous) + ? "no completed compilation" + : previous.dependencySources != Identity(check, dependencies, allowMissing: true, excludeSelectedSources: true) + ? "retained dependency inputs changed" + : !ValidationOutputs.Matches( + m_plan, + check, + new(check.id, "Passed", previous.inputs, 0, string.Empty, previous.outputs), + m_cancellation, + m_outputDigests + ) ? "compiled output content changed" : null; if (reason is not null) { Console.WriteLine($"Dependency clean required for {check.owner}: {reason}."); @@ -77,8 +100,13 @@ internal bool RequiresDependencyCompilation(ValidationDependencyInputs dependenc internal void Record(ValidationDependencyInputs dependencies) { foreach (ValidationCheck check in m_checks) - m_completed[check.owner] = new(Identity(check, dependencies), ValidationOutputs.Capture(m_plan, check, m_cancellation, m_outputDigests), - Identity(check, dependencies, excludeSelectedSources: true)); + { + m_completed[check.owner] = new( + Identity(check, dependencies), + ValidationOutputs.Capture(m_plan, check, m_cancellation, m_outputDigests), + Identity(check, dependencies, excludeSelectedSources: true) + ); + } // Publish only after closing freshness succeeds. Failed assertions do not invalidate a verified compilation. AtomicFile.WriteAllBytes(m_path, JsonSerializer.SerializeToUtf8Bytes(m_completed)); } @@ -94,8 +122,15 @@ private string Identity( { // Every selected root is explicitly cleaned. Preserve dependencies only when all remaining inputs and outputs match. // Shared inputs, imports, resources, generated files and tooling remain protected by their actual input sets. - sourceCheck = check with { sourceSets = null, inputs = ValidationInputs.SourcePaths(m_plan, check) - .Where(path => !m_selectedSources.Contains(path)).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray() }; + sourceCheck = check with + { + sourceSets = null, + inputs = ValidationInputs.SourcePaths(m_plan, check) + .Where(path => !m_selectedSources.Contains(path)) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray() + }; } return ValidationInputs.Identity(new Dictionary { diff --git a/tools/Inno.Tooling.Validation/ValidationCiContracts.cs b/tools/Inno.Tooling.Validation/ValidationCiContracts.cs index 0713d77c4..4350cbdc3 100644 --- a/tools/Inno.Tooling.Validation/ValidationCiContracts.cs +++ b/tools/Inno.Tooling.Validation/ValidationCiContracts.cs @@ -25,11 +25,12 @@ internal static class ValidationCiContracts internal static bool Owns(string path) => path == C_GATE || path.StartsWith(C_DIRECTORY, StringComparison.Ordinal) - && !path[C_DIRECTORY.Length..].Contains('/') - && path.EndsWith(".Tests.ps1", StringComparison.Ordinal); + && !path[C_DIRECTORY.Length..].Contains('/') + && path.EndsWith(".Tests.ps1", StringComparison.Ordinal); internal static string[] Discover(string root) => Directory.GetFiles(Path.Combine(root, "tests", "ci")) .Where(path => path.EndsWith(".Tests.ps1", StringComparison.Ordinal)) - .Order(StringComparer.Ordinal).ToArray(); + .Order(StringComparer.Ordinal) + .ToArray(); } diff --git a/tools/Inno.Tooling.Validation/ValidationCommand.cs b/tools/Inno.Tooling.Validation/ValidationCommand.cs index b81f7698a..2964a9e9a 100644 --- a/tools/Inno.Tooling.Validation/ValidationCommand.cs +++ b/tools/Inno.Tooling.Validation/ValidationCommand.cs @@ -56,8 +56,23 @@ public static async Task ExecuteAsync( CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(arguments); - if (arguments.Length == 0 || arguments[0] is not ("plan" or "run" or "full" or "evidence" or "join" or "acceptance" or "resume" or "pack-backends" or "import-backends" or "backend-inputs" or "bind-backends")) - throw new ArgumentException("Usage: validate --engine-root ROOT --dotnet HOST [--base REV] [--output DIR] [--plan FILE] [--accepted-plan FILE] [--evidence FILE] [--profile NAME] [--native-dependencies FILE] [--shard ID] [--prerequisites DIR]"); + if (arguments.Length == 0 + || arguments[0] is not ("plan" + or "run" + or "full" + or "evidence" + or "join" + or "acceptance" + or "resume" + or "pack-backends" + or "import-backends" + or "backend-inputs" + or "bind-backends") + ) { + throw new ArgumentException( + "Usage: validate --engine-root ROOT --dotnet HOST [--base REV] [--output DIR] [--plan FILE] [--accepted-plan FILE] [--evidence FILE] [--profile NAME] [--native-dependencies FILE] [--shard ID] [--prerequisites DIR]" + ); + } var options = new Dictionary(StringComparer.Ordinal); string[]? transportOptions = arguments[0] switch { @@ -70,25 +85,62 @@ public static async Task ExecuteAsync( for (int index = 1; index < arguments.Length; index += 2) { string key = arguments[index]; - bool allowed = transportOptions?.Contains(key, StringComparer.Ordinal) ?? key is ("--engine-root" or "--dotnet" or "--base" or "--configuration" or "--artifacts-path" or "--output" or "--plan" or "--accepted-plan" or "--evidence" or "--extended" or "--full" or "--cache-input" or "--cache-output" or "--docs-cache-root" or "--docs-snapshot" or "--docs-base-snapshot" or "--profile" or "--native-dependencies" or "--shard" or "--prerequisites" or "--retained-outputs" or "--backend-store"); + bool allowed = transportOptions?.Contains(key, StringComparer.Ordinal) + ?? key is ("--engine-root" + or "--dotnet" + or "--base" + or "--configuration" + or "--artifacts-path" + or "--output" + or "--plan" + or "--accepted-plan" + or "--evidence" + or "--extended" + or "--full" + or "--cache-input" + or "--cache-output" + or "--docs-cache-root" + or "--docs-snapshot" + or "--docs-base-snapshot" + or "--profile" + or "--native-dependencies" + or "--shard" + or "--prerequisites" + or "--retained-outputs" + or "--backend-store"); if (arguments[0] == "backend-inputs" && key is ("--selection" or "--configuration")) + { allowed = true; + } if (arguments[0] == "plan" && key == "--baseline-plan") + { allowed = true; + } if (arguments[0] == "bind-backends" && key == "--test-evidence") + { allowed = true; + } if (!allowed || index + 1 >= arguments.Length || !options.TryAdd(key, arguments[index + 1])) + { throw new ArgumentException($"Unknown, duplicate or incomplete validation option: {key}"); + } } if (transportOptions is not null) { if (transportOptions.Any(key => !options.ContainsKey(key))) + { throw new ArgumentException("Required backend transport options: " + string.Join(", ", transportOptions)); + } if (arguments[0] == "bind-backends") { string engine = Path.GetFullPath(options["--engine-root"]); ValidationPlan frozen = ValidationPlanTransport.Read(options["--plan"], engine, options["--dotnet"]); - ValidationPlan bound = await ValidationPlanner.BindBackendsAsync(frozen, options["--packages"], cancellationToken, options.GetValueOrDefault("--test-evidence")).ConfigureAwait(false); + ValidationPlan bound = await ValidationPlanner.BindBackendsAsync( + frozen, + options["--packages"], + cancellationToken, + options.GetValueOrDefault("--test-evidence") + ).ConfigureAwait(false); Inno.Core.IO.AtomicFile.WriteAllBytes(options["--output"], ValidationPlanTransport.Write(bound)); } else if (arguments[0] == "backend-inputs") @@ -96,15 +148,31 @@ public static async Task ExecuteAsync( string engine = Path.GetFullPath(options["--engine-root"]); ValidationPlan frozen = ValidationPlanTransport.Read(options["--plan"], engine, options["--dotnet"]); byte[]? native = options.TryGetValue("--selection", out string? selected) - ? await File.ReadAllBytesAsync(selected, cancellationToken).ConfigureAwait(false) : null; - var selection = await ValidationPlanner.BackendInputsAsync(frozen, options["--target"], cancellationToken, native, - options.GetValueOrDefault("--configuration")).ConfigureAwait(false); + ? await File.ReadAllBytesAsync(selected, cancellationToken).ConfigureAwait(false) + : null; + var selection = await ValidationPlanner.BackendInputsAsync( + frozen, + options["--target"], + cancellationToken, + native, + options.GetValueOrDefault("--configuration") + ).ConfigureAwait(false); Inno.Core.IO.AtomicFile.WriteAllBytes(options["--output"], JsonSerializer.SerializeToUtf8Bytes(selection)); } else if (arguments[0] == "pack-backends") + { BackendPrebuiltArchive.Create(options["--artifacts-path"], options["--inventory"], options["--output"], cancellationToken); + } else - await BackendPrebuiltArchive.ExtractAsync(options["--archive"], options["--sha256"], options["--target"], options["--output"], cancellationToken).ConfigureAwait(false); + { + await BackendPrebuiltArchive.ExtractAsync( + options["--archive"], + options["--sha256"], + options["--target"], + options["--output"], + cancellationToken + ).ConfigureAwait(false); + } return 0; } string root = Path.GetFullPath(options.GetValueOrDefault("--engine-root", Directory.GetCurrentDirectory())); @@ -112,85 +180,165 @@ public static async Task ExecuteAsync( bool full = arguments[0] == "full" || options.TryGetValue("--full", out string? complete) && bool.Parse(complete); ValidationProfile profile = ValidationProfiles.Parse(options.GetValueOrDefault("--profile", full ? "full" : "pull-request")); if (profile is (ValidationProfile.Fast or ValidationProfile.Performance) && (full || extended)) + { throw new ArgumentException("The selected profile cannot certify full or extended acceptance."); - string output = Path.GetFullPath(options.GetValueOrDefault("--output", Path.Combine(root, "artifacts", "validation", "runs", Guid.NewGuid().ToString("N")))); - string artifacts = Path.GetFullPath(options.GetValueOrDefault("--artifacts-path", Path.Combine(root, "artifacts", "validation", "workspaces", - options.GetValueOrDefault("--configuration", "Debug")))); + } + string output = Path.GetFullPath( + options.GetValueOrDefault("--output", Path.Combine(root, "artifacts", "validation", "runs", Guid.NewGuid().ToString("N"))) + ); + string artifacts = Path.GetFullPath( + options.GetValueOrDefault( + "--artifacts-path", + Path.Combine( + root, + "artifacts", + "validation", + "workspaces", + options.GetValueOrDefault("--configuration", "Debug") + ) + ) + ); string dotnet = options.GetValueOrDefault("--dotnet", "dotnet"); if (options.ContainsKey("--retained-outputs") && arguments[0] != "resume") + { throw new ArgumentException("Retained outputs may only be installed by resume."); + } Directory.CreateDirectory(output); if (options.ContainsKey("--plan") && (options.ContainsKey("--native-dependencies") || options.ContainsKey("--backend-store"))) + { throw new ArgumentException("The supplied plan already freezes its native dependency selection."); + } if (options.ContainsKey("--plan") && (options.ContainsKey("--docs-cache-root") || options.ContainsKey("--docs-snapshot") - || options.ContainsKey("--docs-base-snapshot"))) + || options.ContainsKey("--docs-base-snapshot")) + ) { throw new ArgumentException("A supplied plan already fixes its documentation selection; regenerate the plan to change it."); + } ValidationPlan plan; if (options.TryGetValue("--plan", out string? planPath)) + { plan = ValidationPlanTransport.Read(planPath, root, dotnet); + } else { - ValidationPlanningResult selected = await ValidationPlanner.CreateAsync(root, options.GetValueOrDefault("--base", "HEAD"), dotnet, - options.GetValueOrDefault("--configuration", "Debug"), artifacts, full, cancellationToken, extended, - options.GetValueOrDefault("--docs-cache-root"), options.GetValueOrDefault("--docs-snapshot"), - options.GetValueOrDefault("--docs-base-snapshot"), profile, options.GetValueOrDefault("--native-dependencies"), options.GetValueOrDefault("--backend-store"), - options.GetValueOrDefault("--baseline-plan")).ConfigureAwait(false); + ValidationPlanningResult selected = await ValidationPlanner.CreateAsync( + root, + options.GetValueOrDefault("--base", "HEAD"), + dotnet, + options.GetValueOrDefault("--configuration", "Debug"), + artifacts, + full, + cancellationToken, + extended, + options.GetValueOrDefault("--docs-cache-root"), + options.GetValueOrDefault("--docs-snapshot"), + options.GetValueOrDefault("--docs-base-snapshot"), + profile, + options.GetValueOrDefault("--native-dependencies"), + options.GetValueOrDefault("--backend-store"), + options.GetValueOrDefault("--baseline-plan") + ).ConfigureAwait(false); if (selected.preparation is not null) { - await File.WriteAllTextAsync(Path.Combine(output, "preparation.json"), JsonSerializer.Serialize(selected.preparation, - new JsonSerializerOptions { WriteIndented = true }), cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(output, "preparation.json"), + JsonSerializer.Serialize(selected.preparation, new JsonSerializerOptions { WriteIndented = true }), + cancellationToken + ).ConfigureAwait(false); Console.WriteLine("Planning blocked: " + selected.preparation.reason + " No new executable plan was produced. " + output); return 2; } - plan = selected.plan ?? throw new InvalidDataException("Planning produced neither an executable plan nor explicit preparation requirements."); + plan = selected.plan + ?? throw new InvalidDataException("Planning produced neither an executable plan nor explicit preparation requirements."); } if (options.ContainsKey("--profile") && profile != plan.profile) + { throw new InvalidDataException("The supplied plan uses a different execution profile."); + } if (plan.nativeDependencies is not null && (options.ContainsKey("--cache-input") || options.ContainsKey("--cache-output"))) + { throw new ArgumentException("Consume-only dependency validation does not use producer cache transport."); + } if (plan.backendStore is not null && plan.backendPackages is null && arguments[0] != "plan") + { throw new InvalidDataException("Backend acquisition must bind the exact packages before executing or certifying this plan."); + } if (arguments[0] == "acceptance") { if (planPath is null || !options.TryGetValue("--accepted-plan", out string? acceptedPath) - || !options.TryGetValue("--evidence", out string? acceptedEvidence)) + || !options.TryGetValue("--evidence", out string? acceptedEvidence) + ) { throw new ArgumentException("Acceptance comparison requires current plan, accepted-plan and evidence."); + } ValidationPlan accepted = ValidationPlanTransport.Read(acceptedPath, root, dotnet); bool reusable = ValidationAcceptance.Matches(plan, accepted, Read(acceptedEvidence)); - await File.WriteAllTextAsync(Path.Combine(output, "acceptance.json"), JsonSerializer.Serialize(new - { - reusable, - planIdentity = ValidationInputs.PlanIdentity(plan), - acceptedPlanIdentity = ValidationInputs.PlanIdentity(accepted), - reason = reusable ? "Exact completed functional inputs, checks and execution environment match." - : "Functional inputs, execution environment or acceptance policy changed; execute the current plan." - }), cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(output, "acceptance.json"), + JsonSerializer.Serialize(new + { + reusable, + planIdentity = ValidationInputs.PlanIdentity(plan), + acceptedPlanIdentity = ValidationInputs.PlanIdentity(accepted), + reason = reusable + ? "Exact completed functional inputs, checks and execution environment match." + : "Functional inputs, execution environment or acceptance policy changed; execute the current plan." + }), + cancellationToken + ).ConfigureAwait(false); return 0; } if (arguments[0] == "join") { if (planPath is null || !options.TryGetValue("--prerequisites", out string? receiptsDirectory)) + { throw new ArgumentException("Joining shards requires the frozen plan and its receipt directory."); + } ValidationEvidence joined = ValidationShards.Join(plan, ReadReceipts(receiptsDirectory)); - await File.WriteAllTextAsync(Path.Combine(output, "results.json"), JsonSerializer.Serialize(joined, - new JsonSerializerOptions { WriteIndented = true }), cancellationToken).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(output, "results.json"), + JsonSerializer.Serialize(joined, new JsonSerializerOptions { WriteIndented = true }), + cancellationToken + ).ConfigureAwait(false); return 0; } ValidationShard? shard = options.TryGetValue("--shard", out string? shardId) ? ValidationShards.Require(plan, shardId) : null; if (shard is not null && arguments[0] is not ("run" or "resume")) + { throw new ArgumentException("A shard is executed through validate run with a frozen plan."); - if (!Path.GetFullPath(plan.root).Equals(root, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + } + if (!Path.GetFullPath(plan.root) + .Equals(root, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) + ) { throw new InvalidDataException("The supplied plan belongs to another workspace."); - if (plan.checks.Length == 0 || plan.checks.Select(static check => check.id).Distinct(StringComparer.Ordinal).Count() != plan.checks.Length) + } + if (plan.checks.Length == 0 + || plan.checks.Select(static check => check.id).Distinct(StringComparer.Ordinal).Count() != plan.checks.Length + ) { throw new InvalidDataException("A validation plan must contain unique, explicit required checks."); + } if (full && !plan.full) + { throw new InvalidDataException("Full validation cannot execute a bounded supplied plan."); + } if (extended && !plan.extended) - throw new InvalidDataException("Extended acceptance cannot execute a supplied plan without its required depth."); - if (arguments[0] == "evidence" && options.TryGetValue("--cache-output", out string? retentionArchive) && plan.contexts.ContainsKey("native")) - Console.WriteLine($"Retained {await NativeArtifactTransfer.ExportAsync(root, retentionArchive, cancellationToken).ConfigureAwait(false)} complete immutable generations; reconciliation must still succeed independently."); - if (planPath is not null && plan.environment != await ValidationEnvironment.CaptureAsync(root, plan.dotnet, cancellationToken, plan.contexts.Values).ConfigureAwait(false)) { + throw new InvalidDataException("Extended acceptance cannot execute a supplied plan without its required depth."); + } + if (arguments[0] == "evidence" + && options.TryGetValue("--cache-output", out string? retentionArchive) + && plan.contexts.ContainsKey("native") + ) { + Console.WriteLine( + $"Retained {await NativeArtifactTransfer.ExportAsync(root, retentionArchive, cancellationToken).ConfigureAwait(false)} complete immutable generations; reconciliation must still succeed independently." + ); + } + if (planPath is not null + && plan.environment != await ValidationEnvironment.CaptureAsync( + root, + plan.dotnet, + cancellationToken, + plan.contexts.Values + ).ConfigureAwait(false) + ) { if (arguments[0] == "plan") { Console.WriteLine("The execution environment changed. Regenerate the plan on this runner."); @@ -198,47 +346,80 @@ await File.WriteAllTextAsync(Path.Combine(output, "results.json"), JsonSerialize } throw new InvalidDataException("The supplied plan belongs to another SDK or execution environment."); } - await File.WriteAllBytesAsync(Path.Combine(output, "plan.json"), ValidationPlanTransport.Write(plan), cancellationToken).ConfigureAwait(false); + await File.WriteAllBytesAsync( + Path.Combine(output, "plan.json"), + ValidationPlanTransport.Write(plan), + cancellationToken + ).ConfigureAwait(false); if (arguments[0] == "plan") { - Console.WriteLine($"Plan: {plan.owners.Length} affected owners, {plan.checks.Count(static check => check.exclusion is null)} required checks. {output}"); + Console.WriteLine( + $"Plan: {plan.owners.Length} affected owners, {plan.checks.Count(static check => check.exclusion is null)} required checks. {output}" + ); return 0; } - ValidationEvidence? previous = options.TryGetValue("--evidence", out string? evidencePath) ? Read(evidencePath) : null; + ValidationEvidence? previous = options.TryGetValue("--evidence", out string? evidencePath) + ? Read(evidencePath) + : null; bool continuation = arguments[0] == "resume"; string? retainedOutputs = options.GetValueOrDefault("--retained-outputs"); if (continuation) { if (planPath is null || previous is null || !options.TryGetValue("--accepted-plan", out string? acceptedPath)) + { throw new ArgumentException("Resume requires a frozen full plan, accepted-plan and completed evidence."); + } ValidationAcceptance.RequireContinuation(plan, ValidationPlanTransport.Read(acceptedPath, root, dotnet), previous); if (previous.environment != plan.environment) { retainedOutputs = null; - Console.WriteLine("The accepted execution environment changed. Retained compilation is not imported; the current frozen checks must execute."); + Console.WriteLine( + "The accepted execution environment changed. Retained compilation is not imported; the current frozen checks must execute." + ); } } if (arguments[0] == "evidence") { if (previous is null) + { throw new ArgumentException("Evidence reconciliation requires --evidence FILE."); - using DocumentationSnapshot? documentation = plan.documentation is null ? null - : await DocumentationStore.OpenAsync(plan.documentation.cacheRoot, plan.documentation.snapshot, - cancellationToken: cancellationToken).ConfigureAwait(false); + } + using DocumentationSnapshot? documentation = plan.documentation is null + ? null + : await DocumentationStore.OpenAsync( + plan.documentation.cacheRoot, + plan.documentation.snapshot, + cancellationToken: cancellationToken + ).ConfigureAwait(false); if (documentation is not null) + { _ = await ValidationDocumentation.ReadCatalogAsync(plan, documentation, cancellationToken).ConfigureAwait(false); + } using var outputOwnership = plan.checks.Any(static check => check.kind == "build" && check.exclusion is null) - ? await ValidationWorkspace.AcquireReadAsync(plan, cancellationToken).ConfigureAwait(false) : null; + ? await ValidationWorkspace.AcquireReadAsync(plan, cancellationToken).ConfigureAwait(false) + : null; Dictionary current = await ValidationInputs.CaptureAsync(root, cancellationToken).ConfigureAwait(false); if (ValidationInputs.Identity(current) != plan.tree || previous.tree != plan.tree || previous.environment != plan.environment) + { throw new InvalidDataException("Evidence does not certify the current tree and environment."); + } _ = ValidationShards.ValidateEvidence(plan, previous); var outputDigests = new Dictionary(StringComparer.Ordinal); var dependencies = new ValidationDependencyInputs(plan, cancellationToken); foreach (ValidationCheck check in plan.checks.Where(static check => check.exclusion is null)) - if (!ValidationOutputs.Matches(plan, check, previous.results.Single(result => result.id == check.id), cancellationToken, outputDigests) - || !dependencies.Matches(check, previous.results.Single(result => result.id == check.id).dependencyIdentity)) + { + if (!ValidationOutputs.Matches( + plan, + check, + previous.results.Single(result => result.id == check.id), + cancellationToken, + outputDigests + ) + || !dependencies.Matches(check, previous.results.Single(result => result.id == check.id).dependencyIdentity) + ) { throw new InvalidDataException($"Required output evidence is missing or changed: {check.id}"); + } + } return 0; } if (options.TryGetValue("--cache-input", out string? cacheInput) && File.Exists(cacheInput)) @@ -246,25 +427,43 @@ await File.WriteAllTextAsync(Path.Combine(output, "results.json"), JsonSerialize try { int imported = await NativeArtifactTransfer.ImportAsync(root, cacheInput, cancellationToken).ConfigureAwait(false); - Console.WriteLine($"Restored {imported} complete native candidates; publishers must verify their requested input identities before adoption."); + Console.WriteLine( + $"Restored {imported} complete native candidates; publishers must verify their requested input identities before adoption." + ); } catch (IOException failure) { File.Copy(cacheInput, Path.Combine(output, "rejected-native-cache.zip"), overwrite: false); - Console.Error.WriteLine("Rejected native cache transport; retained for diagnosis. Required producers will execute normally: " + failure.Message); + Console.Error.WriteLine( + "Rejected native cache transport; retained for diagnosis. Required producers will execute normally: " + failure.Message + ); } } - ValidationEvidence evidence = await ValidationRunner.RunAsync(plan, output, previous, cancellationToken, shard, - options.TryGetValue("--prerequisites", out string? receipts) ? ReadReceipts(receipts) : null, continuation, retainedOutputs).ConfigureAwait(false); + ValidationEvidence evidence = await ValidationRunner.RunAsync( + plan, + output, + previous, + cancellationToken, + shard, + options.TryGetValue("--prerequisites", out string? receipts) ? ReadReceipts(receipts) : null, + continuation, + retainedOutputs + ).ConfigureAwait(false); _ = ValidationShards.ValidateEvidence(plan, evidence, shard?.id); if (options.TryGetValue("--cache-output", out string? cacheOutput) && plan.contexts.ContainsKey("native")) - Console.WriteLine($"Exported {await NativeArtifactTransfer.ExportAsync(root, cacheOutput, cancellationToken).ConfigureAwait(false)} verified immutable generations."); + { + Console.WriteLine( + $"Exported {await NativeArtifactTransfer.ExportAsync(root, cacheOutput, cancellationToken).ConfigureAwait(false)} verified immutable generations." + ); + } return 0; } private static ValidationEvidence[] ReadReceipts(string directory) - => Directory.GetFiles(directory, "results.json", SearchOption.AllDirectories).Order(StringComparer.Ordinal) - .Select(Read).ToArray(); + => Directory.GetFiles(directory, "results.json", SearchOption.AllDirectories) + .Order(StringComparer.Ordinal) + .Select(Read) + .ToArray(); private static T Read(string path) => JsonSerializer.Deserialize(File.ReadAllText(path)) ?? throw new InvalidDataException($"Empty validation document: {path}"); diff --git a/tools/Inno.Tooling.Validation/ValidationCompiledGraph.cs b/tools/Inno.Tooling.Validation/ValidationCompiledGraph.cs index 2d947a893..73e996805 100644 --- a/tools/Inno.Tooling.Validation/ValidationCompiledGraph.cs +++ b/tools/Inno.Tooling.Validation/ValidationCompiledGraph.cs @@ -15,14 +15,17 @@ ValidationCheck check JsonElement[] snapshots = plan.contexts[check.context ?? "managed"].sdkGraph.EnumerateArray().ToArray(); var instances = snapshots.SelectMany(static snapshot => snapshot.GetProperty("Instances").EnumerateArray()) .ToDictionary(static instance => instance.GetProperty("Identity").GetString()!, StringComparer.Ordinal); - string[] roots = check.kind is "build" or "test" ? [check.owner] + string[] roots = check.kind is "build" or "test" + ? [check.owner] : check.projects ?? check.inputs.Where(static input => input.StartsWith('@') && input is not ("@tooling" or "@native-sources")) - .Select(static input => input[1..]).ToArray(); + .Select(static input => input[1..]) + .ToArray(); var pending = new Queue(); foreach (string root in roots) { - JsonElement snapshot = snapshots.Single(snapshot => - Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == root); + JsonElement snapshot = snapshots.Single(snapshot => ( + Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == root + )); JsonElement entry = Entry(snapshot); pending.Enqueue(entry.GetProperty("Identity").GetString()!); } @@ -30,12 +33,18 @@ ValidationCheck check while (pending.TryDequeue(out string? identity)) { if (!visited.Add(identity)) + { continue; + } if (!instances.TryGetValue(identity, out JsonElement instance)) + { throw new InvalidDataException("An actual compiled project instance has no captured owner: " + identity); + } yield return instance; foreach (JsonElement reference in instance.GetProperty("References").EnumerateArray()) + { pending.Enqueue(reference.GetString()!); + } } } @@ -49,9 +58,9 @@ internal static JsonElement Entry(JsonElement snapshot) internal static bool SameProperties( JsonElement left, JsonElement right - ) - => left.EnumerateObject().Count(static pair => pair.Name != "IsGraphBuild") - == right.EnumerateObject().Count(static pair => pair.Name != "IsGraphBuild") - && right.EnumerateObject().Where(static pair => pair.Name != "IsGraphBuild") - .All(pair => left.TryGetProperty(pair.Name, out JsonElement value) && value.GetString() == pair.Value.GetString()); + ) => left.EnumerateObject().Count(static pair => pair.Name != "IsGraphBuild") + == right.EnumerateObject().Count(static pair => pair.Name != "IsGraphBuild") + && right.EnumerateObject() + .Where(static pair => pair.Name != "IsGraphBuild") + .All(pair => left.TryGetProperty(pair.Name, out JsonElement value) && value.GetString() == pair.Value.GetString()); } diff --git a/tools/Inno.Tooling.Validation/ValidationDeliverables.cs b/tools/Inno.Tooling.Validation/ValidationDeliverables.cs index bb8cd14ca..a217e2ead 100644 --- a/tools/Inno.Tooling.Validation/ValidationDeliverables.cs +++ b/tools/Inno.Tooling.Validation/ValidationDeliverables.cs @@ -17,8 +17,9 @@ internal static void Create( ValidationCheck check, CancellationToken cancellation ) { - JsonElement editor = plan.contexts[check.context!].sdkGraph.EnumerateArray().Single(snapshot => - Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == check.owner); + JsonElement editor = plan.contexts[check.context!].sdkGraph.EnumerateArray().Single(snapshot => ( + Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == check.owner + )); string source = Path.GetDirectoryName(editor.GetProperty("Properties").GetProperty("TargetPath").GetString()!)!; string directory = Path.Combine(plan.artifacts, "deliverables"); string destination = Path.Combine(directory, "Editor.zip"); @@ -28,17 +29,24 @@ CancellationToken cancellation using (var stream = new FileStream(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) + { foreach (string file in PathBoundary.EnumerateFiles(source).Order(StringComparer.Ordinal)) { cancellation.ThrowIfCancellationRequested(); - ZipArchiveEntry entry = archive.CreateEntry(Path.GetRelativePath(source, file).Replace('\\', '/'), CompressionLevel.Fastest); + ZipArchiveEntry entry = archive.CreateEntry( + Path.GetRelativePath(source, file).Replace('\\', '/'), + CompressionLevel.Fastest + ); entry.LastWriteTime = new DateTimeOffset(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); if (!OperatingSystem.IsWindows()) + { entry.ExternalAttributes = ((int)File.GetUnixFileMode(file) | 0x8000) << 16; + } using Stream output = entry.Open(); using FileStream input = File.OpenRead(file); input.CopyTo(output); } + } stream.Flush(flushToDisk: true); } cancellation.ThrowIfCancellationRequested(); @@ -47,7 +55,9 @@ CancellationToken cancellation finally { if (File.Exists(candidate)) + { File.Delete(candidate); + } } var files = new Dictionary(StringComparer.Ordinal); foreach (string name in new[] { "Editor.zip", "PlayerSupportPack.zip" }) @@ -56,16 +66,19 @@ CancellationToken cancellation using FileStream stream = File.OpenRead(Path.Combine(directory, name)); files.Add(name, Convert.ToHexStringLower(SHA256.HashData(stream))); } - AtomicFile.WriteAllBytes(Path.Combine(directory, "deliverable-manifest.json"), JsonSerializer.SerializeToUtf8Bytes(new - { - format = 1, - plan.commit, - plan.tree, - plan.environment, - planIdentity = ValidationInputs.PlanIdentity(plan), - configuration = plan.contexts[check.context!].properties["Configuration"], - platform = Environment.GetEnvironmentVariable("VALIDATION_PLATFORM") ?? "local", - files - }, new JsonSerializerOptions { WriteIndented = true })); + AtomicFile.WriteAllBytes( + Path.Combine(directory, "deliverable-manifest.json"), + JsonSerializer.SerializeToUtf8Bytes(new + { + format = 1, + plan.commit, + plan.tree, + plan.environment, + planIdentity = ValidationInputs.PlanIdentity(plan), + configuration = plan.contexts[check.context!].properties["Configuration"], + platform = Environment.GetEnvironmentVariable("VALIDATION_PLATFORM") ?? "local", + files + }, new JsonSerializerOptions { WriteIndented = true }) + ); } } diff --git a/tools/Inno.Tooling.Validation/ValidationDependencyInputs.cs b/tools/Inno.Tooling.Validation/ValidationDependencyInputs.cs index a6b0587a8..62103252e 100644 --- a/tools/Inno.Tooling.Validation/ValidationDependencyInputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationDependencyInputs.cs @@ -18,8 +18,15 @@ CancellationToken cancellation private readonly Dictionary[]> m_packages = new(StringComparer.Ordinal); internal static bool Required(ValidationCheck check) - => check.kind is "build" or "test" or "api" or "documentation-api" or "documentation-examples" or "products" or "support-pack" or "release-bundle" - && check.inputs.Any(static input => input.StartsWith('@') && input is not ("@tooling" or "@native-sources")); + => check.kind is "build" + or "test" + or "api" + or "documentation-api" + or "documentation-examples" + or "products" + or "support-pack" + or "release-bundle" + && check.inputs.Any(static input => input.StartsWith('@') && input is not ("@tooling" or "@native-sources")); internal void Reset() { @@ -35,11 +42,14 @@ CancellationToken cancellation foreach (string assets in contexts.SelectMany(static context => context.sdkGraph.EnumerateArray()) .SelectMany(static snapshot => snapshot.GetProperty("Instances").EnumerateArray()) .Select(static instance => instance.GetProperty("ProjectAssetsFile").GetString()!) - .Where(static path => !string.IsNullOrWhiteSpace(path)).Distinct(StringComparer.Ordinal)) - { + .Where(static path => !string.IsNullOrWhiteSpace(path)) + .Distinct(StringComparer.Ordinal) + ) { cancellation.ThrowIfCancellationRequested(); if (File.Exists(assets)) + { packages.UnionWith(ReadPackages(assets, allowMissing: true).Select(static package => package.Value)); + } } return packages.Order(StringComparer.Ordinal).ToArray(); } @@ -48,8 +58,14 @@ internal bool Matches( ValidationCheck check, string identity ) { - try { return Capture(check) == identity; } - catch (Exception failure) when (failure is IOException or UnauthorizedAccessException) { return false; } + try + { + return Capture(check) == identity; + } + catch (Exception failure) when (failure is IOException or UnauthorizedAccessException) + { + return false; + } } internal string Capture( @@ -57,31 +73,42 @@ internal string Capture( bool allowMissing = false ) { if (!Required(check)) + { return string.Empty; + } var inputs = new Dictionary(StringComparer.Ordinal); foreach (string declared in ValidationCompiledGraph.Select(plan, check) - .Select(static instance => instance.GetProperty("ProjectAssetsFile").GetString()!).Distinct(StringComparer.Ordinal)) - { + .Select(static instance => instance.GetProperty("ProjectAssetsFile").GetString()!) + .Distinct(StringComparer.Ordinal) + ) { string assets = declared; if (string.IsNullOrWhiteSpace(assets)) + { throw new InvalidDataException("The SDK did not declare restored inputs for " + check.id); + } assets = Path.GetFullPath(assets); inputs[ValidationPlanTransport.Logical(plan.root, plan.dotnet, assets)] = HashAssets(assets); if (!File.Exists(assets)) { if (!allowMissing) + { throw new InvalidDataException("Required restored input is unavailable: " + assets); + } continue; } foreach (string package in Packages(assets, allowMissing).Select(static package => package.Value)) { if (!allowMissing && !Directory.Exists(package)) + { throw new InvalidDataException("A restored package is unavailable: " + package); + } inputs[ValidationPlanTransport.Logical(plan.root, plan.dotnet, package)] = Hash(package); } } if (inputs.Count == 0) + { throw new InvalidDataException("Required restored dependency discovery was empty: " + check.id); + } return ValidationInputs.Identity(inputs); } @@ -89,11 +116,15 @@ private string HashAssets(string path) { string key = "logical-assets:" + path; if (m_hashes.TryGetValue(key, out string? identity)) + { return identity; + } cancellation.ThrowIfCancellationRequested(); identity = File.Exists(path) - ? Convert.ToHexStringLower(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(LogicalAssets(JsonNode.Parse(File.ReadAllBytes(path)))))) - : "missing"; + ? Convert.ToHexStringLower( + SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(LogicalAssets(JsonNode.Parse(File.ReadAllBytes(path))))) + ) + : "missing"; m_hashes.Add(key, identity); return identity; } @@ -104,13 +135,19 @@ private string HashAssets(string path) { var result = new JsonObject(); foreach (var property in properties) + { result.Add(ValidationPlanTransport.Logical(plan.root, plan.dotnet, property.Key), LogicalAssets(property.Value)); + } return result; } if (node is JsonArray items) + { return new JsonArray(items.Select(LogicalAssets).ToArray()); + } if (node is JsonValue value && value.TryGetValue(out string? text)) + { return JsonValue.Create(ValidationPlanTransport.Logical(plan.root, plan.dotnet, text)); + } return node?.DeepClone(); } @@ -118,18 +155,25 @@ internal Dictionary CapturePackages(ValidationCheck check) { var packages = new Dictionary(StringComparer.Ordinal); foreach (string assets in ValidationCompiledGraph.Select(plan, check) - .Select(static instance => instance.GetProperty("ProjectAssetsFile").GetString()!).Distinct(StringComparer.Ordinal)) - { + .Select(static instance => instance.GetProperty("ProjectAssetsFile").GetString()!) + .Distinct(StringComparer.Ordinal) + ) { cancellation.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(assets) || !File.Exists(assets)) + { throw new InvalidDataException("Documentation source provenance requires actual restored dependency inputs."); + } foreach (var package in Packages(assets, false)) { if (!Directory.Exists(package.Value)) + { throw new InvalidDataException("A documented source dependency is unavailable: " + package.Key); + } string identity = Hash(package.Value); if (packages.TryGetValue(package.Key, out string? previous) && previous != identity) + { throw new InvalidDataException("The same restored package identity resolves to conflicting contents: " + package.Key); + } packages[package.Key] = identity; } } @@ -141,7 +185,9 @@ private KeyValuePair[] Packages( bool allowMissing ) { if (m_packages.TryGetValue(assets, out KeyValuePair[]? packages)) + { return packages; + } packages = ReadPackages(assets, allowMissing); m_packages.Add(assets, packages); return packages; @@ -152,18 +198,26 @@ private static KeyValuePair[] ReadPackages( bool allowMissing ) { using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(assets)); - string[] folders = document.RootElement.GetProperty("packageFolders").EnumerateObject() - .Select(static folder => Path.GetFullPath(folder.Name)).ToArray(); + string[] folders = document.RootElement.GetProperty("packageFolders") + .EnumerateObject() + .Select(static folder => Path.GetFullPath(folder.Name)) + .ToArray(); var selected = new Dictionary(StringComparer.Ordinal); foreach (JsonProperty library in document.RootElement.GetProperty("libraries").EnumerateObject()) { if (library.Value.GetProperty("type").GetString() != "package") + { continue; + } string relative = library.Value.GetProperty("path").GetString()!; string[] candidates = folders.Select(folder => PathBoundary.Resolve(folder, relative)).ToArray(); - selected.Add(relative, candidates.FirstOrDefault(Directory.Exists) - ?? (allowMissing && candidates.Length != 0 ? candidates[0] - : throw new InvalidDataException("A restored package is unavailable: " + library.Name))); + selected.Add( + relative, + candidates.FirstOrDefault(Directory.Exists) + ?? (allowMissing && candidates.Length != 0 + ? candidates[0] + : throw new InvalidDataException("A restored package is unavailable: " + library.Name)) + ); } return selected.OrderBy(static pair => pair.Key, StringComparer.Ordinal).ToArray(); } @@ -171,7 +225,9 @@ bool allowMissing private string Hash(string path) { if (m_hashes.TryGetValue(path, out string? cached)) + { return cached; + } cancellation.ThrowIfCancellationRequested(); string identity; if (Directory.Exists(path)) @@ -191,7 +247,9 @@ private string Hash(string path) identity = Convert.ToHexStringLower(SHA256.HashData(stream)); } else + { identity = "missing"; + } m_hashes.Add(path, identity); return identity; } diff --git a/tools/Inno.Tooling.Validation/ValidationDocumentation.cs b/tools/Inno.Tooling.Validation/ValidationDocumentation.cs index 238994f4e..3e4e93b40 100644 --- a/tools/Inno.Tooling.Validation/ValidationDocumentation.cs +++ b/tools/Inno.Tooling.Validation/ValidationDocumentation.cs @@ -40,47 +40,70 @@ IReadOnlySet changedReferenceOwners string? baseline = null ) { if ((cache is null) != (identity is null)) + { throw new ArgumentException("Documentation validation requires an explicit cache-root and snapshot pair."); + } if (cache is null) { if (baseline is not null) + { throw new ArgumentException("A documentation baseline requires the current cache and snapshot."); + } return null; } - using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, identity, - cancellationToken: cancellation).ConfigureAwait(false); + using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync( + cache, + identity, + cancellationToken: cancellation + ).ConfigureAwait(false); DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(cancellation).ConfigureAwait(false); DocumentationReferenceInfo inventory = catalog.references.Single(reference => reference.model == "project-inventory"); - using JsonDocument source = JsonDocument.Parse(await snapshot.ReadReferenceAsync(inventory.path, cancellation).ConfigureAwait(false)); + using JsonDocument source = JsonDocument.Parse( + await snapshot.ReadReferenceAsync(inventory.path, cancellation).ConfigureAwait(false) + ); var owners = new Dictionary(StringComparer.Ordinal); foreach (JsonElement owner in source.RootElement.EnumerateArray()) { string name = owner.GetProperty("name").GetString()!; string path = owner.GetProperty("path").GetString()!; if (!projects.TryGetValue(path, out ValidationProject? actual) || Path.GetFileNameWithoutExtension(path) != name) + { throw new InvalidDataException("Documentation inventory differs from the actual source owner: " + path); + } bool native = owner.TryGetProperty("apiDocumentation", out JsonElement scope) && scope.GetString() == "backend-native"; if (native && (!path.StartsWith("backends/", StringComparison.Ordinal) || !path.Contains("/native/", StringComparison.Ordinal))) + { throw new InvalidDataException("Native reference exclusion crosses its declared backend owner: " + path); + } if (!owners.TryAdd(name, new(path, actual.test, native))) + { throw new InvalidDataException("Duplicate documentation project identity: " + name); + } } Dictionary sourceIdentities = await SourceIdentitiesAsync(snapshot, catalog).ConfigureAwait(false); var changedPages = new HashSet(StringComparer.Ordinal); var changedOwners = new HashSet(StringComparer.Ordinal); if (baseline is not null && baseline != snapshot.identity) { - using DocumentationSnapshot previous = await DocumentationStore.OpenAsync(cache, baseline, cancellationToken: cancellation).ConfigureAwait(false); + using DocumentationSnapshot previous = await DocumentationStore.OpenAsync( + cache, + baseline, + cancellationToken: cancellation + ).ConfigureAwait(false); DocumentationCatalogReport prior = await previous.ExportCatalogAsync(cancellation).ConfigureAwait(false); var pages = prior.pages.ToDictionary(static page => page.id, StringComparer.Ordinal); var changedPaths = new HashSet(StringComparer.Ordinal); foreach (DocumentationPageInfo page in catalog.pages) - if (!pages.Remove(page.id, out DocumentationPageInfo? old) || old.contentIdentity != page.contentIdentity || old.path != page.path) - { + { + if (!pages.Remove(page.id, out DocumentationPageInfo? old) + || old.contentIdentity != page.contentIdentity + || old.path != page.path + ) { changedPages.Add(page.id); changedPaths.Add(page.path); if (old is not null) changedPaths.Add(old.path); } + } foreach (DocumentationPageInfo removed in pages.Values) { changedPages.Add(removed.id); @@ -91,42 +114,68 @@ IReadOnlySet changedReferenceOwners { expanded = false; foreach (DocumentationPageInfo page in catalog.pages) - if (page.includes.Any(changedPaths.Contains) || page.contracts.Any(contract => changedPages.Contains(contract.Split('#', 2)[0]))) - { + { + if (page.includes.Any(changedPaths.Contains) + || page.contracts.Any(contract => changedPages.Contains(contract.Split('#', 2)[0])) + ) { expanded |= changedPages.Add(page.id); changedPaths.Add(page.path); } - } while (expanded); + } + } + while (expanded); Dictionary earlier = await SourceIdentitiesAsync(previous, prior).ConfigureAwait(false); foreach (var input in sourceIdentities) + { if (earlier.GetValueOrDefault(input.Key) != input.Value) + { changedOwners.Add(input.Key.Split('\0')[1]); + } + } foreach (string removed in earlier.Keys.Except(sourceIdentities.Keys, StringComparer.Ordinal)) { string name = removed.Split('\0')[1]; if (owners.ContainsKey(name)) + { changedOwners.Add(name); + } } } - return new(new(Path.GetFullPath(cache), snapshot.identity, snapshot.sourceTree, baseline), catalog, owners, sourceIdentities, changedPages, changedOwners); + return new( + new(Path.GetFullPath(cache), snapshot.identity, snapshot.sourceTree, baseline), + catalog, + owners, + sourceIdentities, + changedPages, + changedOwners + ); async Task> SourceIdentitiesAsync( DocumentationSnapshot reader, DocumentationCatalogReport report ) { var identities = new Dictionary(StringComparer.Ordinal); - foreach (DocumentationReferenceInfo reference in report.references.Where(static reference => - reference.model is "source-clr" or "runtime-script" or "editor-script")) - { - using JsonDocument facts = JsonDocument.Parse(await reader.ReadReferenceAsync(reference.path, cancellation).ConfigureAwait(false)); + foreach (DocumentationReferenceInfo reference in report.references.Where(static reference => ( + reference.model is "source-clr" or "runtime-script" or "editor-script" + )) + ) { + using JsonDocument facts = JsonDocument.Parse( + await reader.ReadReferenceAsync(reference.path, cancellation).ConfigureAwait(false) + ); foreach (JsonElement project in facts.RootElement.GetProperty("projects").EnumerateArray()) { string key = reference.path + "\0" + project.GetProperty("name").GetString(); // Match the canonical per-project payload identity emitted by the actual // source comparator, including its JSON whitespace normalization. - if (!identities.TryAdd(key, new(Convert.ToHexStringLower(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(project))), - project.GetProperty("symbols").GetArrayLength() == 0))) + if (!identities.TryAdd( + key, + new( + Convert.ToHexStringLower(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(project))), + project.GetProperty("symbols").GetArrayLength() == 0 + ) + )) { throw new InvalidDataException("Repeated source facts in the documentation snapshot: " + key); + } } } return identities; @@ -137,14 +186,19 @@ internal static DocumentationPageInfo[] SelectExamples( Selection selection, IReadOnlySet affected, bool full - ) => selection.catalog.pages.Where(page => (full || selection.changedPages.Contains(page.id) - || page.examples?.mode is "runtime-script" or "editor-script" && selection.catalog.references.Any(reference => - reference.model is "runtime-script" or "editor-script" - && reference.projects.Any(owner => selection.changedReferenceOwners.Contains(owner) - || affected.Contains(selection.owners[owner].path))) - || page.owners.Concat(page.examples?.projects ?? []) - .Any(owner => selection.owners.TryGetValue(owner, out Owner? project) && affected.Contains(project.path))) - && page.codeBlocks.Any(static block => block.language is "csharp" or "cs" && block.declarationSymbols.Count == 0)).ToArray(); + ) => selection.catalog.pages.Where(page => ( + (full || selection.changedPages.Contains(page.id) + || page.examples?.mode is "runtime-script" or "editor-script" && selection.catalog.references.Any(reference => ( + reference.model is "runtime-script" or "editor-script" + && reference.projects.Any(owner => ( + selection.changedReferenceOwners.Contains(owner) + || affected.Contains(selection.owners[owner].path) + )) + )) + || page.owners.Concat(page.examples?.projects ?? []) + .Any(owner => selection.owners.TryGetValue(owner, out Owner? project) && affected.Contains(project.path))) + && page.codeBlocks.Any(static block => block.language is "csharp" or "cs" && block.declarationSymbols.Count == 0) + )).ToArray(); internal static async Task ReadCatalogAsync( ValidationPlan plan, @@ -152,13 +206,21 @@ internal static async Task ReadCatalogAsync( CancellationToken cancellation ) { if (plan.documentation is not { } binding || snapshot.identity != binding.snapshot || snapshot.sourceTree != binding.sourceTree) + { throw new InvalidDataException("Documentation inputs differ from the frozen validation binding."); + } DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(cancellation).ConfigureAwait(false); // A retained receipt still requires intact inputs, including the inventory that establishes project ownership. foreach (string reference in plan.checks.SelectMany(static check => check.documentation?.references ?? []) - .Concat(catalog.references.Where(static reference => reference.model == "project-inventory").Select(static reference => reference.path)) - .Distinct(StringComparer.Ordinal)) + .Concat( + catalog.references + .Where(static reference => reference.model == "project-inventory") + .Select(static reference => reference.path) + ) + .Distinct(StringComparer.Ordinal) + ) { _ = await snapshot.ReadReferenceAsync(reference, cancellation).ConfigureAwait(false); + } return catalog; } @@ -170,17 +232,29 @@ internal static string ExampleIdentity( IReadOnlyList pages, IReadOnlyList references ) { - var selected = selection.catalog.references.Where(reference => references.Contains(reference.path, StringComparer.Ordinal)).ToArray(); + var selected = selection.catalog.references + .Where(reference => references.Contains(reference.path, StringComparer.Ordinal)) + .ToArray(); var scriptOwners = selected.Where(static reference => reference.model is "runtime-script" or "editor-script") - .SelectMany(static reference => reference.projects).ToHashSet(StringComparer.Ordinal); + .SelectMany(static reference => reference.projects) + .ToHashSet(StringComparer.Ordinal); var inputs = pages.Select(static page => new KeyValuePair(page.id, page.contentIdentity)).ToList(); foreach (DocumentationReferenceInfo reference in selected) { if (reference.model == "source-clr") - inputs.AddRange(reference.projects.Where(scriptOwners.Contains).Select(owner => - new KeyValuePair(reference.path + "\0" + owner, selection.sourceIdentities[reference.path + "\0" + owner].identity))); + { + inputs.AddRange( + reference.projects.Where(scriptOwners.Contains).Select(owner => + new KeyValuePair( + reference.path + "\0" + owner, + selection.sourceIdentities[reference.path + "\0" + owner].identity + )) + ); + } else + { inputs.Add(new(reference.path, reference.identity)); + } } return ValidationInputs.Identity(inputs); } @@ -191,10 +265,15 @@ IReadOnlyList pages ) { bool editor = pages.Any(static page => page.examples?.mode == "editor-script"); bool runtime = editor || pages.Any(static page => page.examples?.mode == "runtime-script"); - DocumentationReferenceInfo[] projections = selection.catalog.references.Where(reference => - reference.model == "runtime-script" && runtime || reference.model == "editor-script" && editor).ToArray(); + DocumentationReferenceInfo[] projections = selection.catalog.references.Where(reference => ( + reference.model == "runtime-script" && runtime || reference.model == "editor-script" && editor + )).ToArray(); var owners = projections.SelectMany(static reference => reference.projects).ToHashSet(StringComparer.Ordinal); - return projections.Concat(selection.catalog.references.Where(reference => reference.model == "source-clr" - && reference.projects.Any(owners.Contains))).Select(static reference => reference.path).Order(StringComparer.Ordinal).ToArray(); + return projections.Concat( + selection.catalog.references.Where(reference => ( + reference.model == "source-clr" + && reference.projects.Any(owners.Contains) + )) + ).Select(static reference => reference.path).Order(StringComparer.Ordinal).ToArray(); } } diff --git a/tools/Inno.Tooling.Validation/ValidationDocumentationInputs.cs b/tools/Inno.Tooling.Validation/ValidationDocumentationInputs.cs index 06548eb4f..557b6efdd 100644 --- a/tools/Inno.Tooling.Validation/ValidationDocumentationInputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationDocumentationInputs.cs @@ -13,28 +13,43 @@ internal static ValidationDocumentationInput[] Capture( ValidationCheck check, ValidationDependencyInputs dependencies ) { - if (check.kind is not ("documentation-api" or "documentation-examples") || check.projects is not { Length: > 0 } || check.documentation is null) + if (check.kind is not ("documentation-api" or "documentation-examples") + || check.projects is not { Length: > 0 } + || check.documentation is null + ) { return []; + } var contexts = plan.contexts[check.context ?? "managed"].sdkGraph.EnumerateArray().ToArray(); - var owners = contexts.SelectMany(snapshot => snapshot.GetProperty("Instances").EnumerateArray() - .Select(instance => new KeyValuePair(instance.GetProperty("Identity").GetString()!, - Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/')))) + var owners = contexts + .SelectMany(snapshot => snapshot.GetProperty("Instances") + .EnumerateArray() + .Select(instance => new KeyValuePair( + instance.GetProperty("Identity").GetString()!, + Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') + ))) .ToDictionary(StringComparer.Ordinal); return check.projects.Select(project => { // Script example execution also consumes its separately declared projection hosts. // Keep those real build inputs, rather than certifying only the page's API owner. string[] roots = check.kind == "documentation-examples" - ? check.inputs.Where(static input => input.StartsWith('@') && input is not ("@tooling" or "@native-sources")) - .Select(static input => input[1..]).Append(project).Distinct(StringComparer.Ordinal).ToArray() - : [project]; + ? check.inputs.Where(static input => input.StartsWith('@') && input is not ("@tooling" or "@native-sources")) + .Select(static input => input[1..]) + .Append(project) + .Distinct(StringComparer.Ordinal) + .ToArray() + : [project]; ValidationCheck selected = check with { projects = roots }; JsonElement[] instances = ValidationCompiledGraph.Select(plan, selected).ToArray(); string[] closure = instances.Select(instance => owners[instance.GetProperty("Identity").GetString()!]) - .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); string[] inputSets = closure.Append("tooling") - .Concat(check.inputs.Contains("@native-sources", StringComparer.Ordinal) ? ["native-sources"] : []).ToArray(); - var inputs = inputSets.SelectMany(owner => plan.inputSets[owner]).Distinct(StringComparer.Ordinal) + .Concat(check.inputs.Contains("@native-sources", StringComparer.Ordinal) ? ["native-sources"] : []) + .ToArray(); + var inputs = inputSets.SelectMany(owner => plan.inputSets[owner]) + .Distinct(StringComparer.Ordinal) .Select(path => new KeyValuePair(path, plan.inputs.GetValueOrDefault(path, "missing"))) .ToDictionary(StringComparer.Ordinal); var sources = new Dictionary(inputs, StringComparer.Ordinal); @@ -42,9 +57,16 @@ ValidationDependencyInputs dependencies inputs.Add("target", check.documentation.target ?? string.Empty); inputs.Add("context", JsonSerializer.Serialize(plan.contexts[check.context ?? "managed"].properties)); inputs.Add("instances", JsonSerializer.Serialize(instances)); - return new ValidationDocumentationInput(project, closure, ValidationInputs.Identity(inputs), plan.environment, - check.documentation.configuration, check.documentation.target, - ValidationDependencyInputs.Required(check) ? dependencies.CapturePackages(selected) : new(StringComparer.Ordinal), sources); + return new ValidationDocumentationInput( + project, + closure, + ValidationInputs.Identity(inputs), + plan.environment, + check.documentation.configuration, + check.documentation.target, + ValidationDependencyInputs.Required(check) ? dependencies.CapturePackages(selected) : new(StringComparer.Ordinal), + sources + ); }).ToArray(); } } diff --git a/tools/Inno.Tooling.Validation/ValidationEntryInputs.cs b/tools/Inno.Tooling.Validation/ValidationEntryInputs.cs index 55a632c81..1c7f4ab6d 100644 --- a/tools/Inno.Tooling.Validation/ValidationEntryInputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationEntryInputs.cs @@ -32,11 +32,19 @@ Func, string[]> capture { JsonElement properties = instance.GetProperty("GlobalProperties"); bool entry = ValidationCompiledGraph.SameProperties(snapshot.GetProperty("GlobalProperties"), properties); - if (entry ? index != 0 : !variant.GetProperty("EquivalentGlobalProperties").EnumerateArray() - .Any(candidate => ValidationCompiledGraph.SameProperties(candidate, properties))) + if (entry ? index != 0 : !variant.GetProperty("EquivalentGlobalProperties") + .EnumerateArray() + .Any(candidate => ValidationCompiledGraph.SameProperties(candidate, properties)) + ) { continue; - m_nodes.Add(instance.GetProperty("Identity").GetString()!, (key, variant, instance.GetProperty("References") - .EnumerateArray().Select(static item => item.GetString()!).ToArray())); + } + m_nodes.Add( + instance.GetProperty("Identity").GetString()!, + (key, variant, instance.GetProperty("References") + .EnumerateArray() + .Select(static item => item.GetString()!) + .ToArray()) + ); } } } @@ -55,11 +63,15 @@ internal string[] Sources(string owner) while (pending.TryPop(out string? id)) { if (!visited.Add(id)) + { continue; + } var node = m_nodes[id]; keys.Add(node.key); foreach (string reference in node.references) + { pending.Push(reference); + } } return keys.Order(StringComparer.Ordinal).ToArray(); } diff --git a/tools/Inno.Tooling.Validation/ValidationEnvironment.cs b/tools/Inno.Tooling.Validation/ValidationEnvironment.cs index 0697482f4..df1cf90fb 100644 --- a/tools/Inno.Tooling.Validation/ValidationEnvironment.cs +++ b/tools/Inno.Tooling.Validation/ValidationEnvironment.cs @@ -33,13 +33,28 @@ CancellationToken cancellation ["sdk"] = sdk.sdkIdentity, ["host"] = sdk.hostPath }; - foreach (string name in new[] { "MSBuildSDKsPath", "DOTNET_ROLL_FORWARD", "DOTNET_ROOT", "NUGET_PACKAGES", "CC", "CXX", "CMAKE_GENERATOR", "SDKROOT", "MACOSX_DEPLOYMENT_TARGET", "ImageOS", "ImageVersion" }) + foreach (string name in new[] { + "MSBuildSDKsPath", + "DOTNET_ROLL_FORWARD", + "DOTNET_ROOT", + "NUGET_PACKAGES", + "CC", + "CXX", + "CMAKE_GENERATOR", + "SDKROOT", + "MACOSX_DEPLOYMENT_TARGET", + "ImageOS", + "ImageVersion" + }) { inputs.Add(name, Environment.GetEnvironmentVariable(name) ?? string.Empty); + } string sdkRoot = Path.GetDirectoryName(sdk.cliPath)!; string hostRoot = Path.GetDirectoryName(sdk.hostPath)!; var files = new HashSet(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal) { - sdk.hostPath, sdkRoot, RuntimeEnvironment.GetRuntimeDirectory() + sdk.hostPath, + sdkRoot, + RuntimeEnvironment.GetRuntimeDirectory() }; // The CLI output directory can also contain Editor, backend and documentation assemblies. // Only this tool's actual assembly-reference closure is an execution-environment input. @@ -50,24 +65,36 @@ CancellationToken cancellation { cancellation.ThrowIfCancellationRequested(); if (!examined.Add(assembly)) + { continue; + } if (assembly.IsDynamic || string.IsNullOrWhiteSpace(assembly.Location)) + { throw new InvalidDataException("Validation requires file-backed tool dependencies: " + assembly.FullName); + } files.Add(assembly.Location); AssemblyLoadContext context = AssemblyLoadContext.GetLoadContext(assembly) ?? throw new InvalidDataException("Validation dependency has no loading context: " + assembly.FullName); foreach (AssemblyName dependency in assembly.GetReferencedAssemblies()) + { pending.Enqueue(context.LoadFromAssemblyName(dependency)); + } } foreach (string directory in new[] { "shared", "host" }) + { if (Directory.Exists(Path.Combine(hostRoot, directory))) + { files.Add(Path.Combine(hostRoot, directory)); + } + } string shell = ToolchainEnvironment.ResolveExecutable("pwsh"); shell = File.ResolveLinkTarget(shell, returnFinalTarget: true)?.FullName ?? shell; files.Add(shell); string automation = Path.Combine(Path.GetDirectoryName(shell)!, "System.Management.Automation.dll"); if (File.Exists(automation)) + { files.Add(automation); + } return new(sdk, inputs, CaptureContents(root, sdk.hostPath, files, cancellation)); } @@ -81,49 +108,86 @@ internal static async Task CaptureAsync( tools ??= await CaptureToolsAsync(root, dotnet, cancellation).ConfigureAwait(false); var inputs = new Dictionary(tools.inputs, StringComparer.Ordinal); foreach (var content in tools.contents) + { inputs.Add("tool-content:" + content.Key, content.Value); + } var files = new HashSet(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); var examined = new HashSet(files.Comparer); ValidationContext[] selectedContexts = contexts?.ToArray() ?? []; string[] packageOwners = ValidationDependencyInputs.RestoredPackageDirectories(selectedContexts, cancellation); foreach (ValidationContext context in selectedContexts) + { foreach (JsonElement snapshot in context.sdkGraph.EnumerateArray()) + { foreach (JsonElement variant in snapshot.GetProperty("Variants").EnumerateArray().Append(snapshot)) { foreach (JsonElement pack in variant.GetProperty("FrameworkPacks").EnumerateArray()) + { IncludeExternal(pack.GetString()!); + } foreach (JsonElement import in variant.GetProperty("Imports").EnumerateArray()) + { IncludeExternal(import.GetString()!); + } foreach (JsonProperty group in variant.GetProperty("Items").EnumerateObject()) + { foreach (JsonElement item in group.Value.EnumerateArray()) + { if (item.TryGetProperty("FullPath", out JsonElement fullPath) && !string.IsNullOrWhiteSpace(fullPath.GetString())) + { IncludeExternal(fullPath.GetString()!); + } + } + } + } + } } foreach (var content in CaptureContents(root, dotnet, files, cancellation)) + { inputs.Add("external-content:" + content.Key, content.Value); - return ValidationInputs.Identity(inputs.Select(pair => new KeyValuePair( - ValidationPlanTransport.Logical(root, dotnet, pair.Key), ValidationPlanTransport.Logical(root, dotnet, pair.Value)))); + } + return ValidationInputs.Identity( + inputs.Select(pair => new KeyValuePair( + ValidationPlanTransport.Logical(root, dotnet, pair.Key), + ValidationPlanTransport.Logical(root, dotnet, pair.Value) + )) + ); void IncludeExternal(string declared) { string path = Path.GetFullPath(declared); if (!examined.Add(path)) + { return; + } string relative = Path.GetRelativePath(root, path); - if (!Path.IsPathRooted(relative) && relative != ".." && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + if (!Path.IsPathRooted(relative) + && relative != ".." + && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) + ) { return; + } if (tools.contents.Keys.Any(parent => Covers(parent, path))) + { return; + } // Restore exposes package imports and content items after the cold graph was captured. // Their complete bytes belong to each consuming check's restored dependency identity. StringComparison comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - if (packageOwners.Any(package => path.Equals(package, comparison) - || path.StartsWith(package.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, comparison))) + if (packageOwners.Any(package => ( + path.Equals(package, comparison) + || path.StartsWith(package.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, comparison) + ))) { return; + } if (File.Exists(path) || Directory.Exists(path)) + { files.Add(path); + } else + { inputs["absent-external:" + path] = "missing"; + } } } @@ -134,16 +198,36 @@ private static Dictionary CaptureContents( CancellationToken cancellation ) { var roots = new List(); - foreach (string path in files.Select(Path.GetFullPath).OrderBy(static path => path.Length).ThenBy(static path => path, StringComparer.Ordinal)) + foreach (string path in files + .Select(Path.GetFullPath) + .OrderBy(static path => path.Length) + .ThenBy(static path => path, StringComparer.Ordinal) + ) { if (!roots.Any(parent => Covers(parent, path))) + { roots.Add(path); + } + } var identities = new string[roots.Count]; // Each worker owns its input snapshot. All bytes and inventories are read again at the closing freshness check. - Parallel.For(0, roots.Count, new ParallelOptions { MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), CancellationToken = cancellation }, - index => identities[index] = NativeBuildFingerprint.Create([], [new NativeBuildInput("validation/" + ValidationPlanTransport.Logical(root, dotnet, roots[index]).Replace('\\', '/').TrimStart('/'), roots[index])], cancellation)); + Parallel.For( + 0, + roots.Count, + new ParallelOptions { MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), CancellationToken = cancellation }, + index => identities[index] = NativeBuildFingerprint.Create( + [], + [new NativeBuildInput( + "validation/" + ValidationPlanTransport.Logical(root, dotnet, roots[index]).Replace('\\', '/').TrimStart('/'), + roots[index] + )], + cancellation + ) + ); var contents = new Dictionary(StringComparer.Ordinal); for (int index = 0; index < roots.Count; index++) + { contents.Add(roots[index], identities[index]); + } return contents; } diff --git a/tools/Inno.Tooling.Validation/ValidationInputs.cs b/tools/Inno.Tooling.Validation/ValidationInputs.cs index 3e7d0a505..d3559f6ee 100644 --- a/tools/Inno.Tooling.Validation/ValidationInputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationInputs.cs @@ -16,50 +16,75 @@ internal static async Task> CaptureAsync( string root, CancellationToken cancellation ) { - Task fileCapture = ValidationProcess.RunAsync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], root, null, cancellation); + Task fileCapture = ValidationProcess.RunAsync( + "git", + ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], + root, + null, + cancellation + ); Task stageCapture = ValidationProcess.RunAsync("git", ["ls-files", "--stage", "-z"], root, null, cancellation); await Task.WhenAll(fileCapture, stageCapture).ConfigureAwait(false); string files = await fileCapture.ConfigureAwait(false); string staged = await stageCapture.ConfigureAwait(false); var submodules = new Dictionary(StringComparer.Ordinal); var links = new HashSet(StringComparer.Ordinal); - foreach (string entry in staged.Split('\0', StringSplitOptions.RemoveEmptyEntries).Where(static entry => entry.StartsWith("120000 ", StringComparison.Ordinal))) + foreach (string entry in staged + .Split('\0', StringSplitOptions.RemoveEmptyEntries) + .Where(static entry => entry.StartsWith("120000 ", StringComparison.Ordinal)) + ) { links.Add(entry[(entry.IndexOf('\t') + 1)..]); - foreach (string entry in staged.Split('\0', StringSplitOptions.RemoveEmptyEntries).Where(static entry => entry.StartsWith("160000 ", StringComparison.Ordinal))) - { + } + foreach (string entry in staged + .Split('\0', StringSplitOptions.RemoveEmptyEntries) + .Where(static entry => entry.StartsWith("160000 ", StringComparison.Ordinal)) + ) { int separator = entry.IndexOf('\t'); if (separator < 0 || !submodules.TryAdd(entry[(separator + 1)..], entry.Split(' ', 3)[1])) + { throw new InvalidDataException("The submodule index contains an invalid or conflicted identity."); + } } string[] paths = files.Split('\0', StringSplitOptions.RemoveEmptyEntries).Distinct().Order(StringComparer.Ordinal).ToArray(); var identities = new string[paths.Length]; // Independent owners may read concurrently, but every scan still reads current bytes and drains all workers. - await Parallel.ForAsync(0, paths.Length, new ParallelOptions - { - MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), CancellationToken = cancellation - }, async ( - index, - token - ) => - { - token.ThrowIfCancellationRequested(); - string file = paths[index]; - if (links.Contains(file)) + await Parallel.ForAsync( + 0, + paths.Length, + new ParallelOptions + { + MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), + CancellationToken = cancellation + }, + async ( + index, + token + ) => { - byte[]? link = ReadLink(root, file); - identities[index] = link is null ? "missing" : Convert.ToHexStringLower(SHA256.HashData(link)); - return; + token.ThrowIfCancellationRequested(); + string file = paths[index]; + if (links.Contains(file)) + { + byte[]? link = ReadLink(root, file); + identities[index] = link is null ? "missing" : Convert.ToHexStringLower(SHA256.HashData(link)); + return; + } + string path = Resolve(root, file); + if (submodules.TryGetValue(file, out string? expectedRevision)) + { + identities[index] = await CaptureSubmoduleAsync(path, expectedRevision, token).ConfigureAwait(false); + } + else + { + identities[index] = File.Exists(path) ? Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path))) : "missing"; + } } - string path = Resolve(root, file); - if (submodules.TryGetValue(file, out string? expectedRevision)) - identities[index] = await CaptureSubmoduleAsync(path, expectedRevision, token).ConfigureAwait(false); - else - identities[index] = File.Exists(path) ? Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path))) : "missing"; - }).ConfigureAwait(false); - return paths.Select(( - path, - index - ) => new KeyValuePair(path, identities[index])) + ).ConfigureAwait(false); + return paths + .Select(( + path, + index + ) => new KeyValuePair(path, identities[index])) .ToDictionary(StringComparer.Ordinal); } @@ -69,53 +94,90 @@ internal static async Task FindContentChangesAsync( IReadOnlyDictionary inputs, CancellationToken cancellation ) { - string tree = await ValidationProcess.RunAsync("git", ["ls-tree", "-r", "-z", commit], root, null, cancellation).ConfigureAwait(false); + string tree = await ValidationProcess.RunAsync( + "git", + ["ls-tree", "-r", "-z", commit], + root, + null, + cancellation + ).ConfigureAwait(false); var changes = new HashSet(StringComparer.Ordinal); var blobs = new List>(); foreach (string entry in tree.Split('\0', StringSplitOptions.RemoveEmptyEntries)) { int separator = entry.IndexOf('\t'); if (separator < 0) + { throw new InvalidDataException("The committed input tree contains an invalid entry."); + } string[] metadata = entry[..separator].Split(' '); if (metadata.Length != 3) + { throw new InvalidDataException("The committed input tree contains invalid object metadata."); + } string path = entry[(separator + 1)..]; if (metadata[1] == "commit") { - string current = inputs.TryGetValue(path, out string? captured) ? captured - : await CaptureSubmoduleAsync(Resolve(root, path), metadata[2], cancellation).ConfigureAwait(false); + string current = inputs.TryGetValue(path, out string? captured) + ? captured + : await CaptureSubmoduleAsync(Resolve(root, path), metadata[2], cancellation).ConfigureAwait(false); if (current != metadata[2] && current != "unavailable:" + metadata[2]) + { changes.Add(path); + } } else if (metadata[1] != "blob") + { throw new InvalidDataException($"Unsupported committed input type: {metadata[1]}"); + } else if (metadata[0] == "120000") { byte[]? link = ReadLink(root, path); if (link is null) + { changes.Add(path); + } else { - string identity = await ValidationProcess.RunAsync("git", ["hash-object", "--stdin", "--no-filters"], root, null, cancellation, - new UTF8Encoding(false, true).GetString(link)).ConfigureAwait(false); + string identity = await ValidationProcess.RunAsync( + "git", + ["hash-object", "--stdin", "--no-filters"], + root, + null, + cancellation, + new UTF8Encoding(false, true).GetString(link) + ).ConfigureAwait(false); if (identity.Trim() != metadata[2]) + { changes.Add(path); + } } } else if (!File.Exists(Resolve(root, path))) + { changes.Add(path); + } else + { blobs.Add(new(path, metadata[2])); + } } if (blobs.Count != 0) { // Read actual bytes through Git's clean filters; diff alone can reuse stale size/time index metadata. - string content = await ValidationProcess.RunAsync("git", ["hash-object", "--stdin-paths"], root, null, cancellation, - string.Join('\n', blobs.Select(static pair => QuoteGitPath(pair.Key))) + "\n").ConfigureAwait(false); + string content = await ValidationProcess.RunAsync( + "git", + ["hash-object", "--stdin-paths"], + root, + null, + cancellation, + string.Join('\n', blobs.Select(static pair => QuoteGitPath(pair.Key))) + "\n" + ).ConfigureAwait(false); string[] identities = content.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); if (identities.Length != blobs.Count) + { throw new InvalidDataException("Git did not return one content identity for every committed input."); + } KeyValuePair[] different = blobs.Where(( pair, index @@ -123,22 +185,42 @@ CancellationToken cancellation if (different.Length != 0) { // A committed CRLF blob can already equal its checkout, even when today's clean filter normalizes it. - string raw = await ValidationProcess.RunAsync("git", ["hash-object", "--no-filters", "--stdin-paths"], root, null, cancellation, - string.Join('\n', different.Select(static pair => QuoteGitPath(pair.Key))) + "\n").ConfigureAwait(false); + string raw = await ValidationProcess.RunAsync( + "git", + ["hash-object", "--no-filters", "--stdin-paths"], + root, + null, + cancellation, + string.Join('\n', different.Select(static pair => QuoteGitPath(pair.Key))) + "\n" + ).ConfigureAwait(false); string[] rawIdentities = raw.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); if (rawIdentities.Length != different.Length) + { throw new InvalidDataException("Git did not return one raw identity for every differing input."); + } for (int index = 0; index < different.Length; index++) + { if (rawIdentities[index] != different[index].Value) + { changes.Add(different[index].Key); + } + } } } return changes.Order(StringComparer.Ordinal).ToArray(); } internal static string Identity(IEnumerable> inputs) - => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\n', - inputs.OrderBy(static pair => pair.Key, StringComparer.Ordinal).Select(static pair => pair.Key + "\0" + pair.Value))))); + => Convert.ToHexStringLower( + SHA256.HashData( + Encoding.UTF8.GetBytes( + string.Join( + '\n', + inputs.OrderBy(static pair => pair.Key, StringComparer.Ordinal).Select(static pair => pair.Key + "\0" + pair.Value) + ) + ) + ) + ); internal static string PlanIdentity(ValidationPlan plan) => Convert.ToHexStringLower(SHA256.HashData(ValidationPlanTransport.Write(plan))); @@ -150,61 +232,102 @@ ValidationCheck check foreach (string input in check.inputs) { if (!input.StartsWith('@')) + { yield return input; + } else if (check.sourceSets is null || input is "@tooling" or "@native-sources") + { foreach (string path in plan.inputSets[input[1..]]) + { yield return path; + } + } } foreach (string key in check.sourceSets ?? []) + { foreach (string path in plan.inputSets[key]) + { yield return path; + } + } } internal static string CheckIdentity( ValidationPlan plan, ValidationCheck check, IReadOnlyDictionary inputs - ) => Identity(SourcePaths(plan, check) - .Distinct(StringComparer.Ordinal).Select(path => new KeyValuePair(path, inputs.GetValueOrDefault(path, "missing"))) - .Concat(BackendPayloads(plan, check)) - .Append(new("environment", plan.environment)).Append(new("configuration", plan.configuration)) - .Append(new("context", check.context is null ? string.Empty : System.Text.Json.JsonSerializer.Serialize(plan.contexts.GetValueOrDefault(check.context)?.properties - .ToDictionary(static pair => pair.Key, pair => ValidationPlanTransport.Logical(plan.root, plan.dotnet, pair.Value), StringComparer.Ordinal)))) - .Append(new("definition", System.Text.Json.JsonSerializer.Serialize(check)))); + ) => Identity( + SourcePaths(plan, check) + .Distinct(StringComparer.Ordinal) + .Select(path => new KeyValuePair(path, inputs.GetValueOrDefault(path, "missing"))) + .Concat(BackendPayloads(plan, check)) + .Append(new("environment", plan.environment)) + .Append(new("configuration", plan.configuration)) + .Append( + new( + "context", + check.context is null + ? string.Empty + : System.Text.Json.JsonSerializer.Serialize( + plan.contexts + .GetValueOrDefault(check.context)?.properties + .ToDictionary( + static pair => pair.Key, + pair => ValidationPlanTransport.Logical(plan.root, plan.dotnet, pair.Value), + StringComparer.Ordinal + ) + ) + ) + ) + .Append(new("definition", System.Text.Json.JsonSerializer.Serialize(check))) + ); private static IEnumerable> BackendPayloads( ValidationPlan plan, ValidationCheck check ) { if (plan.backendPackages is null || check.exclusion is not null || check.context is null) + { yield break; + } ValidationContext context = plan.contexts[check.context]; string configuration = context.properties.GetValueOrDefault("Configuration", plan.configuration); string[] owners = check.inputs.Where(static key => key.StartsWith("@backends/", StringComparison.Ordinal)) - .Select(input => plan.backendHost + "/" + configuration + "/" + input[1..]).ToArray(); + .Select(input => plan.backendHost + "/" + configuration + "/" + input[1..]) + .ToArray(); if (check.consumedProducts is { Length: > 0 } products && products.All(product => product.target == plan.backendHost) - && owners.All(owner => plan.backendOwnerPayloads?.ContainsKey(owner) == true)) - { - string[] keys = products.Select(product => product.target + "/" + product.configuration.ToLowerInvariant() + "/" + product.product).ToArray(); + && owners.All(owner => plan.backendOwnerPayloads?.ContainsKey(owner) == true) + ) { + string[] keys = products + .Select(product => product.target + "/" + product.configuration.ToLowerInvariant() + "/" + product.product) + .ToArray(); if (keys.All(key => plan.backendProductPayloads?.ContainsKey(key) == true)) { foreach (string key in keys) + { yield return new("deployed:" + key, plan.backendProductPayloads![key]); + } foreach (string owner in owners) + { yield return new("backend:" + owner, plan.backendOwnerPayloads![owner]); + } yield break; } } if (context.properties.ContainsKey("InnoNativeTarget") - || owners.Any(owner => plan.backendOwnerPayloads?.ContainsKey(owner) != true)) - { + || owners.Any(owner => plan.backendOwnerPayloads?.ContainsKey(owner) != true) + ) { // A product can load its entire deployed closure, including tools from another host. foreach (BackendPackageReceipt package in plan.backendPackages) + { yield return new("backend:" + package.target, package.sha256); + } yield break; } foreach (string owner in owners) + { yield return new("backend:" + owner, plan.backendOwnerPayloads![owner]); + } } internal static string Resolve( @@ -212,9 +335,12 @@ internal static string Resolve( string relative ) { string path = Path.GetFullPath(relative, root); - if (!path.StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, - OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + if (!path.StartsWith( + Path.GetFullPath(root) + Path.DirectorySeparatorChar, + OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal + )) { throw new InvalidDataException($"Validation input escapes the repository: {relative}"); + } return PathBoundary.RequireUnlinkedPath(Path.GetFullPath(root), path); } @@ -225,11 +351,29 @@ CancellationToken cancellation ) { // Check checkout contents, never the mutable Git object store or its size/time index cache. if (!File.Exists(Path.Combine(path, ".git")) && !Directory.Exists(Path.Combine(path, ".git"))) + { return "unavailable:" + expectedRevision; - string revision = (await ValidationProcess.RunAsync("git", ["rev-parse", "HEAD"], path, null, cancellation).ConfigureAwait(false)).Trim(); + } + string revision = (await ValidationProcess.RunAsync( + "git", + ["rev-parse", "HEAD"], + path, + null, + cancellation + ).ConfigureAwait(false)).Trim(); string dirty = await ValidationProcess.RunAsync("git", ["status", "--porcelain"], path, null, cancellation).ConfigureAwait(false); - if (dirty.Length != 0 || (await FindContentChangesAsync(path, revision, new Dictionary(), cancellation).ConfigureAwait(false)).Length != 0) - throw new InvalidDataException($"Submodule '{path}' has uncommitted inputs; commit or restore its explicit owner before certifying evidence."); + if (dirty.Length != 0 + || (await FindContentChangesAsync( + path, + revision, + new Dictionary(), + cancellation + ).ConfigureAwait(false)).Length != 0 + ) { + throw new InvalidDataException( + $"Submodule '{path}' has uncommitted inputs; commit or restore its explicit owner before certifying evidence." + ); + } return revision; } @@ -237,12 +381,20 @@ private static string QuoteGitPath(string path) { var quoted = new StringBuilder("\""); foreach (char character in path) + { if (character is '\\' or '"') + { quoted.Append('\\').Append(character); + } else if (character < ' ' || character == '\u007f') + { quoted.Append('\\').Append(Convert.ToString(character, 8).PadLeft(3, '0')); + } else + { quoted.Append(character); + } + } return quoted.Append('"').ToString(); } @@ -255,8 +407,10 @@ string relative PathBoundary.RequireUnlinkedPath(root, Path.GetDirectoryName(path)!); string? target = new FileInfo(path).LinkTarget; if (target is not null) + { // Git for Windows stores slash-separated link text but creates native backslash-separated targets. return Encoding.UTF8.GetBytes(OperatingSystem.IsWindows() ? target.Replace('\\', '/') : target); + } PathBoundary.RequireUnlinkedPath(root, path); return File.Exists(path) ? File.ReadAllBytes(path) : null; } diff --git a/tools/Inno.Tooling.Validation/ValidationOutputs.cs b/tools/Inno.Tooling.Validation/ValidationOutputs.cs index 23c34143a..18a55c2ff 100644 --- a/tools/Inno.Tooling.Validation/ValidationOutputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationOutputs.cs @@ -17,32 +17,49 @@ internal static Dictionary Capture( Dictionary? directoryCache = null ) { var outputs = new Dictionary(StringComparer.Ordinal); - if (check.kind is not ("build" or "test" or "api" or "documentation-api" or "documentation-examples" or "products" or "support-pack" or "release-bundle") + if (check.kind is not ("build" + or "test" + or "api" + or "documentation-api" + or "documentation-examples" + or "products" + or "support-pack" + or "release-bundle") || check.kind is "documentation-api" or "documentation-examples" - && !check.inputs.Any(static input => input.StartsWith('@') && input is not ("@tooling" or "@native-sources"))) + && !check.inputs.Any(static input => input.StartsWith('@') && input is not ("@tooling" or "@native-sources")) + ) { return outputs; + } var directories = new HashSet(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); if (check.kind is "support-pack" or "release-bundle") { - foreach (string name in check.kind == "support-pack" ? new[] { "PlayerSupportPack.zip" } - : new[] { "Editor.zip", "PlayerSupportPack.zip", "deliverable-manifest.json" }) - { + foreach (string name in check.kind == "support-pack" + ? new[] { "PlayerSupportPack.zip" } + : new[] { "Editor.zip", "PlayerSupportPack.zip", "deliverable-manifest.json" } + ) { string archive = Path.Combine(plan.artifacts, "deliverables", name); if (!File.Exists(archive)) + { throw new InvalidDataException($"Required verified deliverable is absent: {name}"); + } using FileStream stream = File.OpenRead(archive); outputs["deliverables/" + name] = Convert.ToHexStringLower(SHA256.HashData(stream)); } } foreach (string target in ValidationCompiledGraph.Select(plan, check) - .Select(static instance => instance.GetProperty("TargetPath").GetString()!).Distinct(StringComparer.Ordinal)) - { + .Select(static instance => instance.GetProperty("TargetPath").GetString()!) + .Distinct(StringComparer.Ordinal) + ) { if (string.IsNullOrEmpty(target) || !File.Exists(target)) + { throw new InvalidDataException($"Required compiled output is absent for {check.id}: {target}"); + } directories.Add(Path.GetDirectoryName(Path.GetFullPath(target))!); } if (directories.Count == 0) + { throw new InvalidDataException($"No SDK output directory was discovered for {check.id}."); + } foreach (string directory in directories.Order(StringComparer.Ordinal)) { string relativeDirectory = Path.GetRelativePath(plan.artifacts, directory); @@ -63,7 +80,9 @@ internal static Dictionary Capture( string identity = ValidationInputs.Identity(files); outputs[key] = identity; if (directoryCache is not null) + { directoryCache[key] = identity; + } } return outputs; } @@ -76,33 +95,45 @@ internal static bool Matches( Dictionary? directoryCache = null ) { if (result.outputs is null) + { return false; + } try { - return ValidationInputs.Identity(Capture(plan, check, cancellation, directoryCache)) == ValidationInputs.Identity(result.outputs); + return ValidationInputs.Identity( + Capture(plan, check, cancellation, directoryCache) + ) == ValidationInputs.Identity(result.outputs); } catch (Exception failure) when (failure is IOException or UnauthorizedAccessException) { return false; } } + private static IEnumerable EnumerateFiles(string directory) { if ((File.GetAttributes(directory) & FileAttributes.ReparsePoint) != 0) + { throw new InvalidDataException($"Output evidence cannot follow a linked directory: {directory}"); + } foreach (string entry in Directory.EnumerateFileSystemEntries(directory)) { FileAttributes attributes = File.GetAttributes(entry); if ((attributes & FileAttributes.ReparsePoint) != 0) + { throw new InvalidDataException($"Output evidence cannot follow a linked entry: {entry}"); + } if ((attributes & FileAttributes.Directory) != 0) { foreach (string file in EnumerateFiles(entry)) + { yield return file; + } } else + { yield return entry; + } } } - } diff --git a/tools/Inno.Tooling.Validation/ValidationPlan.cs b/tools/Inno.Tooling.Validation/ValidationPlan.cs index 8650420fa..13e42ff82 100644 --- a/tools/Inno.Tooling.Validation/ValidationPlan.cs +++ b/tools/Inno.Tooling.Validation/ValidationPlan.cs @@ -58,9 +58,11 @@ internal sealed record ValidationPlan( /// /// Indicates whether executing a selected check requires backend assemblies or native products. /// - public bool backendRequired => nativeRequests is { Length: > 0 } || Array.Exists(checks, static check => - check.exclusion is null && check.context is not null && (check.owner.StartsWith("backends/", StringComparison.Ordinal) - || Array.Exists(check.inputs, static input => input.StartsWith("@backends/", StringComparison.Ordinal)))); + public bool backendRequired + => nativeRequests is { Length: > 0 } || Array.Exists(checks, static check => ( + check.exclusion is null && check.context is not null && (check.owner.StartsWith("backends/", StringComparison.Ordinal) + || Array.Exists(check.inputs, static input => input.StartsWith("@backends/", StringComparison.Ordinal))) + )); } internal sealed record BackendPackageReceipt( diff --git a/tools/Inno.Tooling.Validation/ValidationPlanTransport.cs b/tools/Inno.Tooling.Validation/ValidationPlanTransport.cs index 71da80856..00094373e 100644 --- a/tools/Inno.Tooling.Validation/ValidationPlanTransport.cs +++ b/tools/Inno.Tooling.Validation/ValidationPlanTransport.cs @@ -8,12 +8,16 @@ using Inno.Build.Toolchains; namespace Inno.Tooling.Validation; + internal static class ValidationPlanTransport { internal static byte[] Write(ValidationPlan plan) { JsonNode document = JsonSerializer.SerializeToNode(plan)!; - return JsonSerializer.SerializeToUtf8Bytes(Rewrite(document, Locations(plan.root, plan.dotnet), bind: false), new JsonSerializerOptions { WriteIndented = true }); + return JsonSerializer.SerializeToUtf8Bytes( + Rewrite(document, Locations(plan.root, plan.dotnet), bind: false), + new JsonSerializerOptions { WriteIndented = true } + ); } internal static ValidationPlan Read( @@ -21,10 +25,14 @@ internal static ValidationPlan Read( string root, string dotnet ) { - JsonNode document = JsonNode.Parse(File.ReadAllBytes(path)) ?? throw new InvalidDataException("The portable validation plan is empty."); + JsonNode document = JsonNode.Parse(File.ReadAllBytes(path)) + ?? throw new InvalidDataException("The portable validation plan is empty."); if (document["root"]?.GetValue() != "${workspace}") + { throw new InvalidDataException("A validation plan must declare a logical workspace binding."); - return Rewrite(document, Locations(root, dotnet), bind: true).Deserialize() ?? throw new InvalidDataException("The portable validation plan could not be bound."); + } + return Rewrite(document, Locations(root, dotnet), bind: true).Deserialize() + ?? throw new InvalidDataException("The portable validation plan could not be bound."); } internal static string Logical( @@ -32,12 +40,14 @@ internal static string Logical( string dotnet, string value ) => Replace(value, Locations(root, dotnet), bind: false); + private static KeyValuePair[] Locations( string root, string dotnet ) { string host = Path.IsPathFullyQualified(dotnet) ? dotnet : ToolchainEnvironment.ResolveExecutable(dotnet); - string nuget = Environment.GetEnvironmentVariable("NUGET_PACKAGES") ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages"); + string nuget = Environment.GetEnvironmentVariable("NUGET_PACKAGES") + ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages"); return new Dictionary(StringComparer.Ordinal) { ["${workspace}"] = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar), @@ -53,11 +63,24 @@ private static JsonNode Rewrite( bool bind ) { if (node is JsonObject record) - return new JsonObject(record.Select(pair => new KeyValuePair(Replace(pair.Key, locations, bind), pair.Value is null ? null : Rewrite(pair.Value, locations, bind)))); + { + return new JsonObject( + record.Select( + pair => new KeyValuePair( + Replace(pair.Key, locations, bind), + pair.Value is null ? null : Rewrite(pair.Value, locations, bind) + ) + ) + ); + } if (node is JsonArray array) + { return new JsonArray(array.Select(value => value is null ? null : Rewrite(value, locations, bind)).ToArray()); + } if (node is JsonValue value && value.TryGetValue(out string? text)) + { return JsonValue.Create(Replace(text, locations, bind))!; + } return node.DeepClone(); } @@ -69,14 +92,25 @@ bool bind foreach (var location in locations) { if (bind) + { value = value.Replace(location.Key, location.Value, StringComparison.Ordinal); + } else + { foreach (string path in new[] { location.Value, location.Value.Replace('\\', '/') - }.Distinct(StringComparer.Ordinal)) - value = Regex.Replace(value, Regex.Escape(path) + "(?=$|[/\\\\;])", _ => location.Key, OperatingSystem.IsWindows() ? RegexOptions.IgnoreCase : RegexOptions.None); + }.Distinct(StringComparer.Ordinal) + ) { + value = Regex.Replace( + value, + Regex.Escape(path) + "(?=$|[/\\\\;])", + _ => location.Key, + OperatingSystem.IsWindows() ? RegexOptions.IgnoreCase : RegexOptions.None + ); + } + } } return value; diff --git a/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs b/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs index 5f093d4a2..640e07251 100644 --- a/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs +++ b/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs @@ -38,13 +38,21 @@ internal static async Task BindBackendsAsync( string? evidence = null ) { if (plan.backendStore is null || plan.backendPackages is not null || plan.nativeDependencies is null) + { throw new InvalidDataException("Only a pending backend plan can bind platform packages."); + } BackendPackageReceipt[] receipts = JsonSerializer.Deserialize(File.ReadAllBytes(packages)) - ?? throw new InvalidDataException("Missing backend acquisition receipts."); - if (receipts.Any(static item => item is null || string.IsNullOrEmpty(item.target) - || !item.target.All(static c => char.IsAsciiLetterOrDigit(c) || c == '-') || !Digest(item.sha256) || !Digest(item.manifestSha256)) - || receipts.Select(static receipt => receipt.target).Distinct(StringComparer.Ordinal).Count() != receipts.Length) + ?? throw new InvalidDataException("Missing backend acquisition receipts."); + if (receipts.Any(static item => ( + item is null || string.IsNullOrEmpty(item.target) + || !item.target.All(static c => char.IsAsciiLetterOrDigit(c) || c == '-') + || !Digest(item.sha256) + || !Digest(item.manifestSha256) + )) + || receipts.Select(static receipt => receipt.target).Distinct(StringComparer.Ordinal).Count() != receipts.Length + ) { throw new InvalidDataException("Incomplete or duplicate backend acquisition receipts."); + } string store = PathBoundary.RequireUnlinkedPath(plan.root, PathBoundary.Resolve(plan.root, plan.backendStore)); var assets = new JsonArray(); var aggregates = new JsonArray(); @@ -57,84 +65,142 @@ internal static async Task BindBackendsAsync( string directory = PathBoundary.Resolve(store, receipt.target); string installed = PathBoundary.RequireUnlinkedPath(store, Path.Combine(directory, "receipt.json")); if (JsonSerializer.Deserialize(File.ReadAllBytes(installed)) != receipt) + { throw new InvalidDataException("Installed backend payload belongs to a different archive: " + receipt.target); + } byte[] manifest = File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(store, Path.Combine(directory, "manifest.json"))); if (Convert.ToHexStringLower(SHA256.HashData(manifest)) != receipt.manifestSha256) + { throw new InvalidDataException("Installed backend inventory changed: " + receipt.target); + } using JsonDocument document = JsonDocument.Parse(manifest); JsonElement files = document.RootElement.GetProperty("files"); JsonElement selection = files.EnumerateArray().Single(item => item.GetProperty("path").GetString() == "native/selection.json"); byte[] native = File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(store, Path.Combine(directory, "native/selection.json"))); if (Convert.ToHexStringLower(SHA256.HashData(native)) != selection.GetProperty("sha256").GetString()) + { throw new InvalidDataException("The native selection changed after installation: " + receipt.target); + } JsonNode catalog = JsonNode.Parse(native) ?? throw new InvalidDataException("Missing native selection."); foreach (var family in new[] { ("assets", assets), ("aggregates", aggregates), ("requests", coverage) }) + { foreach (JsonNode? item in catalog[family.Item1]!.AsArray()) { if (item?["target"]?.GetValue() != receipt.target) + { throw new InvalidDataException("A native selection names another platform."); + } if (family.Item1 == "requests") { - string key = receipt.target + "/" + item["configuration"]!.GetValue().ToLowerInvariant() + "/" + item["product"]!.GetValue(); + string key = receipt.target + + "/" + + item["configuration"]!.GetValue().ToLowerInvariant() + + "/" + + item["product"]!.GetValue(); var digests = item["digests"]!.AsArray().Select(static node => node!.GetValue()).Order(StringComparer.Ordinal); - if (!productPayloads.TryAdd(key, ValidationInputs.Identity(digests.Select(static digest => KeyValuePair.Create(digest, digest))))) + if (!productPayloads.TryAdd( + key, + ValidationInputs.Identity(digests.Select(static digest => KeyValuePair.Create(digest, digest))) + )) { throw new InvalidDataException("Duplicate deployed product request: " + key); + } } family.Item2.Add(item.DeepClone()); } + } if (document.RootElement.GetProperty("target").GetString() != receipt.target) - throw new InvalidDataException("The backend inventory declares a different platform."); - foreach (JsonElement file in files.EnumerateArray().Where(item => item.GetProperty("path").GetString()!.StartsWith("managed/", StringComparison.Ordinal))) { + throw new InvalidDataException("The backend inventory declares a different platform."); + } + foreach (JsonElement file in files + .EnumerateArray() + .Where(item => item.GetProperty("path").GetString()!.StartsWith("managed/", StringComparison.Ordinal)) + ) { string owner = file.GetProperty("owner").GetString()!; string input = file.GetProperty("input").GetString()!; var variant = (receipt.target, file.GetProperty("configuration").GetString()!, owner); if (managed.TryGetValue(variant, out string? prior) && prior != input) + { throw new InvalidDataException("A backend owner has conflicting compiler inputs: " + owner); + } managed[variant] = input; string key = receipt.target + "/" + variant.Item2 + "/" + owner; if (!payloads.TryGetValue(key, out Dictionary? filesByPath)) + { payloads[key] = filesByPath = new(StringComparer.Ordinal); + } filesByPath.Add(file.GetProperty("path").GetString()!, file.GetProperty("sha256").GetString()!); } } string selectionPath = PathBoundary.RequireUnlinkedPath(plan.root, PathBoundary.Resolve(plan.root, plan.nativeDependencies)); - byte[] selectionBytes = JsonSerializer.SerializeToUtf8Bytes(new { layout = "platform-packages", assets, aggregates, requests = coverage }); + byte[] selectionBytes = JsonSerializer.SerializeToUtf8Bytes( + new { layout = "platform-packages", assets, aggregates, requests = coverage } + ); string host = plan.backendHost ?? ""; var requests = plan.nativeRequests ?? []; if (!plan.backendRequired && receipts.Length != 0) + { throw new InvalidDataException("An independent managed plan must not acquire backend packages."); + } var contexts = requests.Select(static request => (request.target, request.configuration)) - .Concat(plan.contexts.Values.Select(context => (host, context.properties.GetValueOrDefault("Configuration", plan.configuration)))) + .Concat( + plan.contexts.Values.Select(context => (host, context.properties.GetValueOrDefault("Configuration", plan.configuration))) + ) .Distinct(); foreach (var (target, configuration) in contexts.Where(_ => plan.backendRequired)) { - BackendInputPlan expected = await BackendInputsAsync(plan, target, cancellation, selectionBytes, configuration).ConfigureAwait(false); + BackendInputPlan expected = await BackendInputsAsync( + plan, + target, + cancellation, + selectionBytes, + configuration + ).ConfigureAwait(false); if (expected.missingNativeProducts.Length != 0) - throw new InvalidDataException($"Missing native product for {target}/{configuration}: {string.Join(", ", expected.missingNativeProducts)}."); + { + throw new InvalidDataException( + $"Missing native product for {target}/{configuration}: {string.Join(", ", expected.missingNativeProducts)}." + ); + } foreach (string owner in expected.required) + { if (!managed.TryGetValue((target, configuration, owner), out string? actual) || actual != expected.projects[owner]) + { throw new InvalidDataException($"Missing or stale backend owner {owner} for {target}/{configuration}."); + } + } } var bound = plan with { backendPackages = receipts.OrderBy(static receipt => receipt.target, StringComparer.Ordinal).ToArray(), backendProductPayloads = productPayloads, - backendOwnerPayloads = payloads.ToDictionary(static pair => pair.Key, static pair => ValidationInputs.Identity(pair.Value), StringComparer.Ordinal) + backendOwnerPayloads = payloads.ToDictionary( + static pair => pair.Key, + static pair => ValidationInputs.Identity(pair.Value), + StringComparer.Ordinal + ) }; if (evidence is not null) { var certificates = JsonSerializer.Deserialize(File.ReadAllBytes(evidence)) - ?? throw new InvalidDataException("Missing backend test certification inventory."); + ?? throw new InvalidDataException("Missing backend test certification inventory."); var selected = new List(); - foreach (ValidationCheck check in bound.checks.Where(static check => check.kind == "test" && check.reusable && check.exclusion is null - && check.owner.StartsWith("tests/backends/", StringComparison.Ordinal))) - { + foreach (ValidationCheck check in bound.checks.Where(static check => ( + check.kind == "test" + && check.reusable + && check.exclusion is null + && check.owner.StartsWith("tests/backends/", StringComparison.Ordinal) + )) + ) { string identity = ValidationInputs.CheckIdentity(bound, check, bound.inputs); - ValidationResult? result = certificates.FirstOrDefault(item => item.id == check.id && item.inputIdentity == identity - && item.status is ("Passed" or "Reused") && item.outputs is { Count: > 0 } && Digest(item.dependencyIdentity)); + ValidationResult? result = certificates.FirstOrDefault(item => ( + item.id == check.id && item.inputIdentity == identity + && item.status is ("Passed" or "Reused") && item.outputs is { Count: > 0 } && Digest(item.dependencyIdentity) + )); if (result is not null) + { selected.Add(result); + } } bound = bound with { backendTests = selected.ToArray() }; } @@ -151,28 +217,47 @@ private static string[] MissingNativeProducts( byte[]? selection ) { string[] required = (plan.nativeRequests ?? []).Where(request => request.target == target && request.configuration == configuration) - .Select(static request => request.product).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + .Select(static request => request.product) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); if (required.Length == 0 || selection is null) + { return required; + } using JsonDocument document = JsonDocument.Parse(selection); if (!document.RootElement.TryGetProperty("requests", out JsonElement requests)) + { return required; + } var available = new HashSet<(string? product, string? digest)>(); foreach (string family in new[] { "assets", "aggregates" }) + { foreach (JsonElement asset in document.RootElement.GetProperty(family).EnumerateArray()) + { if (asset.GetProperty("target").GetString() == target) + { available.Add((asset.GetProperty("product").GetString(), asset.GetProperty("sha256").GetString())); + } + } + } var certified = new HashSet(StringComparer.Ordinal); foreach (JsonElement request in requests.EnumerateArray()) { if (request.GetProperty("target").GetString() != target || request.GetProperty("configuration").GetString() != configuration) + { continue; + } string product = request.GetProperty("product").GetString()!; JsonElement digests = request.GetProperty("digests"); if (digests.GetArrayLength() == 0 || digests.EnumerateArray().Any(digest => !available.Contains((product, digest.GetString())))) + { throw new InvalidDataException($"Incomplete certified native closure for {target}/{product}/{configuration}."); + } if (!certified.Add(product)) + { throw new InvalidDataException($"Duplicate native closure for {target}/{product}/{configuration}."); + } } return required.Where(product => !certified.Contains(product)).ToArray(); } @@ -192,16 +277,23 @@ internal static async Task BackendInputsAsync( ) { configuration ??= plan.configuration; if (selectionBytes is null && plan.nativeDependencies is not null && File.Exists(Path.Combine(plan.root, plan.nativeDependencies))) + { selectionBytes = File.ReadAllBytes(Path.Combine(plan.root, plan.nativeDependencies)); + } string[] missing = MissingNativeProducts(plan, target, configuration, selectionBytes); if (configuration != plan.configuration && !plan.contexts.ContainsKey("backend-" + configuration.ToLowerInvariant()) && (plan.nativeRequests ?? []).Any(request => request.target == target && request.configuration == configuration) - && !plan.checks.Any(check => check.exclusion is null && check.context is not null - && plan.contexts[check.context].properties.GetValueOrDefault("Configuration") == configuration)) + && !plan.checks.Any(check => ( + check.exclusion is null && check.context is not null + && plan.contexts[check.context].properties.GetValueOrDefault("Configuration") == configuration + )) + ) { return new(plan.commit, target, configuration, new(StringComparer.Ordinal), [], [], missing, null); - ValidationContext graph = configuration == plan.configuration ? plan.contexts["managed"] - : plan.contexts.GetValueOrDefault("backend-" + configuration.ToLowerInvariant()) - ?? throw new InvalidDataException("The SDK graph has no captured configuration " + configuration); + } + ValidationContext graph = configuration == plan.configuration + ? plan.contexts["managed"] + : plan.contexts.GetValueOrDefault("backend-" + configuration.ToLowerInvariant()) + ?? throw new InvalidDataException("The SDK graph has no captured configuration " + configuration); var owners = new Dictionary>(StringComparer.Ordinal); var properties = new Dictionary>(StringComparer.Ordinal); var tools = new Dictionary>(StringComparer.Ordinal); @@ -222,19 +314,39 @@ internal static async Task BackendInputsAsync( JsonElement effective = variant.GetProperty("Properties"); string? variantTarget = effective.GetProperty("InnoNativeTarget").GetString(); if (!string.IsNullOrEmpty(variantTarget) && variantTarget != target) + { continue; + } foreach (JsonElement tool in variant.GetProperty("Items").GetProperty("InnoNativeDependency").EnumerateArray()) { string? hostTarget = tool.GetProperty("TargetId").GetString(); string? toolConfiguration = tool.GetProperty("Configuration").GetString(); - tools[project.path].Add(new(tool.GetProperty("Identity").GetString()!, - string.IsNullOrEmpty(hostTarget) ? plan.backendHost ?? target : hostTarget, - (string.IsNullOrEmpty(toolConfiguration) ? configuration : toolConfiguration).ToLowerInvariant())); + tools[project.path].Add( + new( + tool.GetProperty("Identity").GetString()!, + string.IsNullOrEmpty(hostTarget) ? plan.backendHost ?? target : hostTarget, + (string.IsNullOrEmpty(toolConfiguration) ? configuration : toolConfiguration).ToLowerInvariant() + ) + ); } - foreach (string name in new[] { "AssemblyName", "TargetFramework", "RuntimeIdentifier", "DefineConstants", "Nullable", "AllowUnsafeBlocks", "LangVersion", "NETCoreSdkVersion" }) + foreach (string name in new[] { + "AssemblyName", + "TargetFramework", + "RuntimeIdentifier", + "DefineConstants", + "Nullable", + "AllowUnsafeBlocks", + "LangVersion", + "NETCoreSdkVersion" + }) { properties[project.path].Add(name + "=" + effective.GetProperty(name).GetString()); + } foreach (JsonElement package in variant.GetProperty("Items").GetProperty("PackageReference").EnumerateArray()) - properties[project.path].Add("package:" + package.GetProperty("Identity").GetString() + "=" + package.GetProperty("Version").GetString()); + { + properties[project.path].Add( + "package:" + package.GetProperty("Identity").GetString() + "=" + package.GetProperty("Version").GetString() + ); + } foreach (JsonElement pack in variant.GetProperty("FrameworkPacks").EnumerateArray()) { var installed = new DirectoryInfo(pack.GetString()!); @@ -247,43 +359,69 @@ internal static async Task BackendInputsAsync( { using JsonDocument dependencies = JsonDocument.Parse(selectionBytes); foreach (string family in new[] { "assets", "aggregates" }) + { foreach (JsonElement asset in dependencies.RootElement.GetProperty(family).EnumerateArray()) { - var product = new BackendNativeProduct(asset.GetProperty("product").GetString()!, asset.GetProperty("target").GetString()!, - asset.GetProperty("configuration").GetString()!.ToLowerInvariant()); - var consumers = tools.Where(pair => pair.Value.Contains(product)).Select(static pair => pair.Key).ToHashSet(StringComparer.Ordinal); + var product = new BackendNativeProduct( + asset.GetProperty("product").GetString()!, + asset.GetProperty("target").GetString()!, + asset.GetProperty("configuration").GetString()!.ToLowerInvariant() + ); + var consumers = tools + .Where(pair => pair.Value.Contains(product)) + .Select(static pair => pair.Key) + .ToHashSet(StringComparer.Ordinal); if (product.target == target && string.Equals(product.configuration, configuration, StringComparison.OrdinalIgnoreCase)) - consumers.UnionWith(family == "assets" + { + consumers.UnionWith( + family == "assets" ? new[] { asset.GetProperty("nativeProject").GetString()!, asset.GetProperty("toolchainProject").GetString()! } - : asset.GetProperty("bindings").EnumerateObject().Select(static binding => binding.Name)); + : asset.GetProperty("bindings").EnumerateObject().Select(static binding => binding.Name) + ); + } foreach (string owner in consumers.Where(owners.ContainsKey)) { owners[owner].UnionWith(asset.GetProperty("sources").EnumerateObject().Select(static source => source.Name)); - properties[owner].Add("native:" + asset.GetProperty("component").GetString() + "/" + asset.GetProperty("fingerprint").GetString()); + properties[owner].Add( + "native:" + asset.GetProperty("component").GetString() + "/" + asset.GetProperty("fingerprint").GetString() + ); } } + } } DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync(plan.dotnet, plan.root, cancellation).ConfigureAwait(false); string sdkRoot = Path.GetDirectoryName(sdk.cliPath)!; - var common = new Dictionary(StringComparer.Ordinal) { ["target"] = target, ["sdk"] = sdk.sdkIdentity, ["configuration"] = configuration }; + var common = new Dictionary(StringComparer.Ordinal) + { + ["target"] = target, + ["sdk"] = sdk.sdkIdentity, + ["configuration"] = configuration + }; common["ShouldUnsetParentConfigurationAndPlatform"] = graph.properties["ShouldUnsetParentConfigurationAndPlatform"]; string? developmentProperties = null; if (DevelopmentProject(graph.sdkGraph, plan.root)?.GetProperty("Properties") is JsonElement development && development.GetProperty("InnoDevelopmentTarget").GetString() == target - && development.GetProperty("InnoDevelopmentEditorBuildProperties").GetString() is { Length: > 0 } path) - { + && development.GetProperty("InnoDevelopmentEditorBuildProperties").GetString() is { Length: > 0 } path + ) { developmentProperties = Path.GetRelativePath(plan.root, path).Replace('\\', '/'); common["development-context:" + developmentProperties] = plan.inputs[developmentProperties]; } - foreach (string compiler in new[] { "Microsoft.Build.dll", "Roslyn/bincore/csc.dll", "Roslyn/bincore/Microsoft.CodeAnalysis.dll", "Roslyn/bincore/Microsoft.CodeAnalysis.CSharp.dll" }) - { + foreach (string compiler in new[] { + "Microsoft.Build.dll", + "Roslyn/bincore/csc.dll", + "Roslyn/bincore/Microsoft.CodeAnalysis.dll", + "Roslyn/bincore/Microsoft.CodeAnalysis.CSharp.dll" + }) { using FileStream file = File.OpenRead(Path.Combine(sdkRoot, compiler)); common[compiler] = Convert.ToHexStringLower(await SHA256.HashDataAsync(file, cancellation).ConfigureAwait(false)); } - foreach (var pair in plan.inputs.Where(static pair => pair.Key is "global.json" or ".editorconfig" or "Directory.Packages.props" - || pair.Key.Equals("NuGet.Config", StringComparison.OrdinalIgnoreCase))) + foreach (var pair in plan.inputs.Where(static pair => ( + pair.Key is "global.json" or ".editorconfig" or "Directory.Packages.props" + || pair.Key.Equals("NuGet.Config", StringComparison.OrdinalIgnoreCase) + ))) { common[pair.Key] = pair.Value; + } string[] submodules = plan.inputSets["native-sources"]; var direct = new Dictionary(StringComparer.Ordinal); @@ -294,14 +432,20 @@ internal static async Task BackendInputsAsync( var current = new Dictionary(StringComparer.Ordinal); foreach (string source in pair.Value) { - string? key = plan.inputs.ContainsKey(source) ? source : submodules.FirstOrDefault(prefix => source.StartsWith(prefix + "/", StringComparison.Ordinal)); + string? key = plan.inputs.ContainsKey(source) + ? source + : submodules.FirstOrDefault(prefix => source.StartsWith(prefix + "/", StringComparison.Ordinal)); if (key is null) + { continue; + } string value = plan.inputs[key]; current[key] = value.StartsWith("unavailable:", StringComparison.Ordinal) ? value["unavailable:".Length..] : value; } foreach (string property in properties[pair.Key]) + { current["@" + property] = ""; + } direct[pair.Key] = ValidationInputs.Identity(current); references[pair.Key] = pair.Value.Where(owners.ContainsKey).ToArray(); } @@ -310,27 +454,43 @@ internal static async Task BackendInputsAsync( { var inputs = new Dictionary(common, StringComparer.Ordinal); foreach (string dependency in Closure(project)) + { inputs[dependency] = direct[dependency]; + } identities.Add(project, ValidationInputs.Identity(inputs)); } var required = new HashSet(StringComparer.Ordinal); - ValidationCheck[] checks = plan.checks.Where(check => check.exclusion is null && (check.context is null - ? configuration == plan.configuration : plan.contexts[check.context].properties.GetValueOrDefault("Configuration", plan.configuration) == configuration)).ToArray(); + ValidationCheck[] checks = plan.checks.Where(check => ( + check.exclusion is null && (check.context is null + ? configuration == plan.configuration + : plan.contexts[check.context].properties.GetValueOrDefault("Configuration", plan.configuration) == configuration) + )).ToArray(); foreach (ValidationCheck check in checks.Where(check => owners.ContainsKey(check.owner))) + { required.UnionWith(Closure(check.owner).Where(IsBackend)); + } foreach (string project in checks.SelectMany(static check => check.projects ?? []).Where(owners.ContainsKey)) + { required.UnionWith(Closure(project).Where(IsBackend)); + } const string C_BUILD = "entry/InnoEngine.Build/InnoEngine.Build.csproj"; - if ((plan.backendHost is null || target == plan.backendHost) && plan.nativeRequests is { Length: > 0 } && configuration == plan.configuration && owners.ContainsKey(C_BUILD)) + if ((plan.backendHost is null || target == plan.backendHost) + && plan.nativeRequests is { Length: > 0 } + && configuration == plan.configuration + && owners.ContainsKey(C_BUILD) + ) { required.UnionWith(Closure(C_BUILD).Where(IsBackend)); + } var productInputs = new Dictionary(StringComparer.Ordinal); foreach (JsonElement snapshot in graph.sdkGraph.EnumerateArray()) { JsonElement product = snapshot.GetProperty("Properties"); if (product.GetProperty("InnoProductTarget").GetString() != target - || string.IsNullOrEmpty(product.GetProperty("InnoProductId").GetString())) + || string.IsNullOrEmpty(product.GetProperty("InnoProductId").GetString()) + ) { continue; + } string owner = Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/'); string[] closure = Closure(owner).Order(StringComparer.Ordinal).ToArray(); var proofInputs = new Dictionary(common, StringComparer.Ordinal) @@ -339,16 +499,32 @@ internal static async Task BackendInputsAsync( ["entry"] = owner }; foreach (string project in closure) + { proofInputs[project] = direct[project]; - foreach (var input in plan.inputs.Where(static pair => pair.Key is "tests/ci/Build-BackendPrebuilt.ps1" or "tests/ci/New-BackendPrebuiltPackage.ps1" + } + foreach (var input in plan.inputs.Where(static pair => ( + pair.Key is "tests/ci/Build-BackendPrebuilt.ps1" or "tests/ci/New-BackendPrebuiltPackage.ps1" or "tests/ci/Initialize-BackendProduction.ps1" or "tests/ci/Prepare-BackendNativeInputs.ps1" - or ".github/workflows/backend-prebuilts.yml")) + or ".github/workflows/backend-prebuilts.yml" + ))) { proofInputs[input.Key] = input.Value; + } productInputs.Add(owner, new(ValidationInputs.Identity(proofInputs), closure.Where(IsBackend).ToArray())); } - return new(plan.commit, target, configuration, identities, required.Order(StringComparer.Ordinal).ToArray(), + return new( + plan.commit, + target, + configuration, + identities, + required.Order(StringComparer.Ordinal).ToArray(), checks.Where(static check => check.kind == "test" && check.owner.StartsWith("tests/backends/", StringComparison.Ordinal)) - .Select(static check => check.owner).Order(StringComparer.Ordinal).ToArray(), missing, developmentProperties, productInputs); + .Select(static check => check.owner) + .Order(StringComparer.Ordinal) + .ToArray(), + missing, + developmentProperties, + productInputs + ); IEnumerable Closure(string project) { @@ -356,9 +532,15 @@ IEnumerable Closure(string project) var pending = new Stack(); pending.Push(project); while (pending.TryPop(out string? current)) + { if (visited.Add(current)) + { foreach (string dependency in references[current]) + { pending.Push(dependency); + } + } + } return visited; } diff --git a/tools/Inno.Tooling.Validation/ValidationPlanner.cs b/tools/Inno.Tooling.Validation/ValidationPlanner.cs index b04d67104..945abb882 100644 --- a/tools/Inno.Tooling.Validation/ValidationPlanner.cs +++ b/tools/Inno.Tooling.Validation/ValidationPlanner.cs @@ -17,8 +17,10 @@ internal static partial class ValidationPlanner private static JsonElement? DevelopmentProject( JsonElement graph, string root - ) => graph.EnumerateArray().Cast().FirstOrDefault(snapshot => - Path.GetRelativePath(root, snapshot!.Value.GetProperty("Path").GetString()!).Replace('\\', '/') == "entry/InnoEngine.Editor/InnoEngine.Editor.csproj"); + ) => graph.EnumerateArray().Cast().FirstOrDefault(snapshot => ( + Path.GetRelativePath(root, snapshot!.Value.GetProperty("Path").GetString()!) + .Replace('\\', '/') == "entry/InnoEngine.Editor/InnoEngine.Editor.csproj" + )); internal static async Task CreateAsync( string root, @@ -40,20 +42,29 @@ internal static async Task CreateAsync( if (backendStore is not null) { if (nativeDependencies is not null) + { throw new ArgumentException("The backend store owns the native selection for this plan."); + } string store = Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, Path.GetFullPath(backendStore, root)); Inno.Core.IO.PathBoundary.RequireContained(Path.Combine(root, "artifacts"), store); backendStore = Path.GetRelativePath(root, store).Replace('\\', '/'); nativeDependencies = backendStore + "/selection.json"; } if (profile == ValidationProfile.NativeProducer && (nativeDependencies is not null || full || extended)) - throw new ArgumentException("Native producer acceptance requires explicit source production and cannot certify full functional acceptance."); + { + throw new ArgumentException( + "Native producer acceptance requires explicit source production and cannot certify full functional acceptance." + ); + } if (nativeDependencies is not null) { string selected = Path.GetFullPath(nativeDependencies, root); - nativeDependencies = Path.GetRelativePath(root, Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, selected)).Replace('\\', '/'); + nativeDependencies = Path.GetRelativePath(root, Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, selected)) + .Replace('\\', '/'); if (extended) + { throw new ArgumentException("Consume-only validation cannot certify a cold third-party rebuild."); + } } var elapsed = Stopwatch.StartNew(); var timings = new Dictionary(StringComparer.Ordinal); @@ -61,15 +72,47 @@ internal static async Task CreateAsync( Dictionary inputs = await ValidationInputs.CaptureAsync(root, cancellation).ConfigureAwait(false); string commit = (await GitAsync("rev-parse", "HEAD").ConfigureAwait(false)).Trim(); string mergeBase = (await GitAsync("merge-base", baseline, commit).ConfigureAwait(false)).Trim(); - var changes = new HashSet((await GitAsync("diff", "--name-only", "-z", "--no-renames", mergeBase, "HEAD").ConfigureAwait(false)) - .Split('\0', StringSplitOptions.RemoveEmptyEntries), StringComparer.Ordinal); - changes.UnionWith((await GitAsync("diff", "--name-only", "-z", "--no-renames", "HEAD").ConfigureAwait(false)).Split('\0', StringSplitOptions.RemoveEmptyEntries)); - changes.UnionWith((await GitAsync("diff", "--cached", "--name-only", "-z", "--no-renames", "HEAD").ConfigureAwait(false)).Split('\0', StringSplitOptions.RemoveEmptyEntries)); + var changes = new HashSet( + (await GitAsync("diff", "--name-only", "-z", "--no-renames", mergeBase, "HEAD").ConfigureAwait(false)) + .Split('\0', StringSplitOptions.RemoveEmptyEntries), + StringComparer.Ordinal + ); + changes.UnionWith( + (await GitAsync( + "diff", + "--name-only", + "-z", + "--no-renames", + "HEAD" + ).ConfigureAwait(false)).Split('\0', StringSplitOptions.RemoveEmptyEntries) + ); + changes.UnionWith( + (await GitAsync( + "diff", + "--cached", + "--name-only", + "-z", + "--no-renames", + "HEAD" + ).ConfigureAwait(false)).Split('\0', StringSplitOptions.RemoveEmptyEntries) + ); changes.UnionWith(await ValidationInputs.FindContentChangesAsync(root, commit, inputs, cancellation).ConfigureAwait(false)); - changes.UnionWith((await GitAsync("ls-files", "--others", "--exclude-standard", "-z").ConfigureAwait(false)).Split('\0', StringSplitOptions.RemoveEmptyEntries)); - string[] paths = inputs.Keys.Where(static path => path.EndsWith(".csproj", StringComparison.Ordinal) - && path.Split('/')[0] is "src" or "entry" or "build" or "backends" or "platforms" or "tools" or "tests") - .Where(path => inputs[path] != "missing").Order(StringComparer.Ordinal).ToArray(); + changes.UnionWith( + (await GitAsync( + "ls-files", + "--others", + "--exclude-standard", + "-z" + ).ConfigureAwait(false)).Split('\0', StringSplitOptions.RemoveEmptyEntries) + ); + string[] paths = inputs.Keys + .Where(static path => ( + path.EndsWith(".csproj", StringComparison.Ordinal) + && path.Split('/')[0] is "src" or "entry" or "build" or "backends" or "platforms" or "tools" or "tests" + )) + .Where(path => inputs[path] != "missing") + .Order(StringComparer.Ordinal) + .ToArray(); RecordStage("source-inputs"); var properties = new Dictionary { @@ -82,63 +125,106 @@ internal static async Task CreateAsync( ["ArtifactsPath"] = artifacts }; if (nativeDependencies is not null) + { properties["InnoNativeDependencyManifest"] = Path.Combine(root, nativeDependencies); - ValidationEnvironment.ToolSnapshot toolSnapshot = await ValidationEnvironment.CaptureToolsAsync(root, dotnet, cancellation).ConfigureAwait(false); + } + ValidationEnvironment.ToolSnapshot toolSnapshot = await ValidationEnvironment.CaptureToolsAsync( + root, + dotnet, + cancellation + ).ConfigureAwait(false); DotNetSdkDescriptor sdk = toolSnapshot.sdk; RecordStage("sdk-environment"); - string captured = await ManagedProjectGraphCapture.CaptureSelectedAsync(root, sdk, - paths.Select(path => Path.Combine(root, path)).ToArray(), properties, cancellation).ConfigureAwait(false); + string captured = await ManagedProjectGraphCapture.CaptureSelectedAsync( + root, + sdk, + paths.Select(path => Path.Combine(root, path)).ToArray(), + properties, + cancellation + ).ConfigureAwait(false); RecordStage("sdk-capture"); using JsonDocument graph = JsonDocument.Parse(captured); - string[] submoduleInputs = inputs.Where(pair => pair.Value.StartsWith("unavailable:", StringComparison.Ordinal) - || new DirectoryInfo(Path.GetFullPath(pair.Key, root)) is { Exists: true, LinkTarget: null }) - .Select(static pair => pair.Key).Order(StringComparer.Ordinal).ToArray(); + string[] submoduleInputs = inputs + .Where(pair => ( + pair.Value.StartsWith("unavailable:", StringComparison.Ordinal) + || new DirectoryInfo(Path.GetFullPath(pair.Key, root)) is { Exists: true, LinkTarget: null } + )) + .Select(static pair => pair.Key) + .Order(StringComparer.Ordinal) + .ToArray(); RequireCompilerInputs(graph.RootElement); - ValidationProject[] projects = graph.RootElement.EnumerateArray().Select(snapshot => ValidationProject.Read(root, snapshot)).ToArray(); + ValidationProject[] projects = graph.RootElement + .EnumerateArray() + .Select(snapshot => ValidationProject.Read(root, snapshot)) + .ToArray(); var byPath = projects.ToDictionary(static project => project.path, StringComparer.Ordinal); RecordStage("managed-graph"); var affected = new HashSet(StringComparer.Ordinal); var documentationOwners = new HashSet(StringComparer.Ordinal); - ValidationDocumentation.Selection? documentation = await ValidationDocumentation.CaptureAsync(documentationCache, - documentationSnapshot, byPath, cancellation, documentationBaseline).ConfigureAwait(false); + ValidationDocumentation.Selection? documentation = await ValidationDocumentation.CaptureAsync( + documentationCache, + documentationSnapshot, + byPath, + cancellation, + documentationBaseline + ).ConfigureAwait(false); var diagnostics = new List(); foreach (string change in changes) { - ValidationProject[] owners = projects.Where(project => project.inputs.Contains(change, StringComparer.Ordinal) - || change.StartsWith(DirectoryOf(project.path), StringComparison.Ordinal)).ToArray(); + ValidationProject[] owners = projects.Where(project => ( + project.inputs.Contains(change, StringComparer.Ordinal) + || change.StartsWith(DirectoryOf(project.path), StringComparison.Ordinal) + )).ToArray(); foreach (ValidationProject owner in owners) - affected.Add(owner.path); - if (owners.Length == 0 && inputs.GetValueOrDefault(change, "missing") != "missing" && !IsDocumentation(change) && change != ValidationRunner.C_TEST_EXECUTOR - && change != ValidationCiContracts.C_RULE_LOADER && !ValidationCiContracts.Owns(change)) { + affected.Add(owner.path); + } + if (owners.Length == 0 + && inputs.GetValueOrDefault(change, "missing") != "missing" + && !IsDocumentation(change) + && change != ValidationRunner.C_TEST_EXECUTOR + && change != ValidationCiContracts.C_RULE_LOADER && !ValidationCiContracts.Owns(change) + ) { diagnostics.Add($"Unknown or shared input '{change}': conservatively selecting every owner."); full = true; } } var removedEntries = new Dictionary>(StringComparer.Ordinal); - string[] removed = changes.Where(path => !IsDocumentation(path) - && (!inputs.TryGetValue(path, out string? value) || value == "missing")).ToArray(); + string[] removed = changes.Where(path => ( + !IsDocumentation(path) + && (!inputs.TryGetValue(path, out string? value) || value == "missing") + )).ToArray(); if (removed.Length != 0) { ValidationPlan? previous = baselinePlan is null ? null : ValidationPlanTransport.Read(baselinePlan, root, dotnet); if (previous is not null && previous.commit == mergeBase && previous.configuration == configuration - && previous.contexts.ContainsKey("managed")) - { + && previous.contexts.ContainsKey("managed") + ) { var mapped = new HashSet(StringComparer.Ordinal); var deleted = removed.ToHashSet(StringComparer.Ordinal); foreach (var pair in previous.contexts) { var sets = new Dictionary(StringComparer.Ordinal); - var graphInputs = new ValidationEntryInputs(root, pair.Value.sdkGraph, pair.Key, sets, - paths => paths.Where(deleted.Contains).ToArray()); - var matches = sets.Where(static set => set.Value.Length > 0).Select(static set => set.Key).ToHashSet(StringComparer.Ordinal); + var graphInputs = new ValidationEntryInputs( + root, + pair.Value.sdkGraph, + pair.Key, + sets, + paths => paths.Where(deleted.Contains).ToArray() + ); + var matches = sets + .Where(static set => set.Value.Length > 0) + .Select(static set => set.Key) + .ToHashSet(StringComparer.Ordinal); mapped.UnionWith(sets.Values.SelectMany(static values => values)); var entries = new HashSet(StringComparer.Ordinal); foreach (JsonElement snapshot in pair.Value.sdkGraph.EnumerateArray()) { string owner = Path.GetRelativePath(root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/'); if (graphInputs.Sources(owner).Any(matches.Contains)) + { entries.Add(owner); + } } removedEntries.Add(pair.Key, entries); affected.UnionWith(entries.Where(byPath.ContainsKey)); @@ -158,104 +244,185 @@ internal static async Task CreateAsync( } bool changedTestExecutor = changes.Contains(ValidationRunner.C_TEST_EXECUTOR); if (changedTestExecutor) + { affected.UnionWith(projects.Where(static project => project.test).Select(static project => project.path)); + } if (extended || profile == ValidationProfile.Full) + { full = true; + } if (full) + { affected.UnionWith(paths); + } bool expanded; do { expanded = false; foreach (ValidationProject project in projects) + { if (project.references.Any(affected.Contains)) + { expanded |= affected.Add(project.path); - } while (expanded); + } + } + } + while (expanded); if (profile == ValidationProfile.NativeProducer) { full = false; affected.Clear(); affected.UnionWith(projects.Where(static project => project.requiresNativeProducer).Select(static project => project.path)); - diagnostics.Add("Explicit native producer acceptance selects declared producer regressions; functional consumers remain separately required."); + diagnostics.Add( + "Explicit native producer acceptance selects declared producer regressions; functional consumers remain separately required." + ); } if (profile == ValidationProfile.Performance) { full = false; affected.Clear(); - affected.UnionWith(projects.Where(static project => project.test && project.layer == "performance") - .Select(static project => project.path)); + affected.UnionWith( + projects.Where(static project => project.test && project.layer == "performance") + .Select(static project => project.path) + ); const string C_EDITOR = "entry/InnoEngine.Editor/InnoEngine.Editor.csproj"; if (byPath.ContainsKey(C_EDITOR)) + { affected.Add(C_EDITOR); + } diagnostics.Add("Weekly sampling selects performance suites and the Editor lifecycle and warm-build owner."); } var executionExclusions = new Dictionary(StringComparer.Ordinal); foreach (ValidationProject project in projects) { if (project.environment.Length != 0 && project.environment is not ("any" or "native-host") - && !ValidationTestHosts.Applies(project.environment.Split(';'))) - executionExclusions.Add(project.path, $"This owner requires OS environment '{project.environment}'; it is not validated on this host."); - else if (project.layer == "performance" && !extended && profile is not (ValidationProfile.Performance or ValidationProfile.NativeProducer)) - executionExclusions.Add(project.path, "Performance sampling belongs to the explicit performance profile; functional regressions remain independently required."); + && !ValidationTestHosts.Applies(project.environment.Split(';')) + ) { + executionExclusions.Add( + project.path, + $"This owner requires OS environment '{project.environment}'; it is not validated on this host." + ); + } + else if (project.layer == "performance" + && !extended + && profile is not (ValidationProfile.Performance or ValidationProfile.NativeProducer) + ) { + executionExclusions.Add( + project.path, + "Performance sampling belongs to the explicit performance profile; functional regressions remain independently required." + ); + } else if (project.requiresNativeProducer && (nativeDependencies is not null || profile == ValidationProfile.Performance)) - executionExclusions.Add(project.path, "This producer benchmark may invoke third-party compilation; consume-only validation runs separate warm consumer and lifecycle checks."); + { + executionExclusions.Add( + project.path, + "This producer benchmark may invoke third-party compilation; consume-only validation runs separate warm consumer and lifecycle checks." + ); + } } JsonElement? development = DevelopmentProject(graph.RootElement, root); string target = development?.GetProperty("Properties").GetProperty("InnoDevelopmentTarget").GetString() ?? string.Empty; - DocumentationPageInfo[] examplePages = documentation is null ? [] : ValidationDocumentation.SelectExamples(documentation, affected, full); + DocumentationPageInfo[] examplePages = documentation is null + ? [] + : ValidationDocumentation.SelectExamples(documentation, affected, full); var exampleExclusions = new Dictionary(); foreach (DocumentationPageInfo page in examplePages) { string[] reasons = (page.examples?.projects ?? []).Select(name => byPath[documentation!.owners[name].path]) - .Select(project => executionExclusions.GetValueOrDefault(project.path) + .Select(project => ( + executionExclusions.GetValueOrDefault(project.path) ?? (target.Length != 0 && project.productTarget.Length != 0 && project.productTarget != target - ? $"Example owner '{project.path}' requires product target '{project.productTarget}'; this host selects '{target}'." : null)) - .OfType().Distinct(StringComparer.Ordinal).ToArray(); + ? $"Example owner '{project.path}' requires product target '{project.productTarget}'; this host selects '{target}'." + : null) + )) + .OfType() + .Distinct(StringComparer.Ordinal) + .ToArray(); if (reasons.Length != 0) + { exampleExclusions.Add(page, string.Join(" ", reasons)); + } } examplePages = examplePages.Where(page => !exampleExclusions.ContainsKey(page)).ToArray(); foreach (DocumentationPageInfo page in examplePages) + { foreach (string owner in page.examples?.projects ?? []) + { documentationOwners.Add(documentation!.owners[owner].path); + } + } foreach (string owner in documentation?.changedReferenceOwners ?? new HashSet()) - if (documentation!.catalog.references.Any(reference => reference.model == "source-clr" && reference.projects.Contains(owner, StringComparer.Ordinal))) + { + if (documentation!.catalog.references.Any( + reference => reference.model == "source-clr" && reference.projects.Contains(owner, StringComparer.Ordinal) + )) { documentationOwners.Add(documentation.owners[owner].path); + } + } var scriptPages = examplePages.Where(static page => page.examples?.mode is "runtime-script" or "editor-script") - .Select(static page => page.id).ToHashSet(StringComparer.Ordinal); + .Select(static page => page.id) + .ToHashSet(StringComparer.Ordinal); var nativeDocumentOwners = examplePages.Where(page => scriptPages.Contains(page.id)) - .SelectMany(static page => page.examples!.projects).Select(owner => documentation!.owners[owner].path).ToHashSet(StringComparer.Ordinal); + .SelectMany(static page => page.examples!.projects) + .Select(owner => documentation!.owners[owner].path) + .ToHashSet(StringComparer.Ordinal); bool scriptExamples = scriptPages.Count != 0; if (scriptExamples) { const string C_BUILD_ENTRY = "entry/InnoEngine.Build/InnoEngine.Build.csproj"; if (!byPath.ContainsKey(C_BUILD_ENTRY)) - throw new InvalidDataException("Script documentation examples require the existing Build entry and its evaluated projection closure."); + { + throw new InvalidDataException( + "Script documentation examples require the existing Build entry and its evaluated projection closure." + ); + } documentationOwners.Add(C_BUILD_ENTRY); const string C_EDITOR_ENTRY = "entry/InnoEngine.Editor/InnoEngine.Editor.csproj"; if (!byPath.ContainsKey(C_EDITOR_ENTRY)) - throw new InvalidDataException("Script documentation examples require the declared Editor product and its public script closure."); + { + throw new InvalidDataException( + "Script documentation examples require the declared Editor product and its public script closure." + ); + } documentationOwners.Add(C_EDITOR_ENTRY); } - var nativeOwners = new HashSet(projects.Where(static project => project.native).Select(static project => project.path), StringComparer.Ordinal); + var nativeOwners = new HashSet( + projects.Where(static project => project.native).Select(static project => project.path), + StringComparer.Ordinal + ); do { expanded = false; foreach (ValidationProject project in projects) + { if (project.references.Any(nativeOwners.Contains)) + { expanded |= nativeOwners.Add(project.path); - } while (expanded); + } + } + } + while (expanded); foreach (ValidationProject project in projects.Where(static project => project.layer == "domain")) + { if (nativeOwners.Contains(project.path)) + { throw new InvalidDataException($"Domain test transitively requires native preparation: {project.path}"); + } + } if (profile == ValidationProfile.Fast) { full = false; foreach (ValidationProject project in projects) + { if (nativeOwners.Contains(project.path) || project.test && project.layer is not ("domain" or "contract")) - executionExclusions.TryAdd(project.path, - "Branch fast checks defer this execution prerequisite to pull-request validation."); + { + executionExclusions.TryAdd( + project.path, + "Branch fast checks defer this execution prerequisite to pull-request validation." + ); + } + } diagnostics.Add("Fast profile: native products, real SDK integration and performance are deferred to the pull-request gate."); } // All owners of an executable example share its evaluated output context, including Host @@ -267,43 +434,89 @@ internal static async Task CreateAsync( { string[] owners = (page.examples?.projects ?? []).Select(name => documentation!.owners[name].path).ToArray(); if (owners.Any(owner => nativeOwners.Contains(owner) || nativeDocumentOwners.Contains(owner))) + { foreach (string owner in owners) + { expanded |= nativeDocumentOwners.Add(owner); + } + } } - } while (expanded); + } + while (expanded); var contexts = new Dictionary(StringComparer.Ordinal) { ["managed"] = new(new Dictionary { - ["Configuration"] = configuration, ["ArtifactsPath"] = artifacts, - ["BuildProjectReferences"] = "true", ["BuildingInsideVisualStudio"] = "false", + ["Configuration"] = configuration, + ["ArtifactsPath"] = artifacts, + ["BuildProjectReferences"] = "true", + ["BuildingInsideVisualStudio"] = "false", ["ShouldUnsetParentConfigurationAndPlatform"] = "false" }, graph.RootElement.Clone()) }; if (nativeDependencies is not null) + { contexts["managed"].properties["InnoNativeDependencyManifest"] = Path.Combine(root, nativeDependencies); + } Dictionary nativeProjects = byPath; - if (scriptExamples || nativeOwners.Any(owner => !executionExclusions.ContainsKey(owner) - && (affected.Contains(owner) || documentationOwners.Contains(owner)))) - { - string[] unavailable = inputs.Where(static pair => pair.Value.StartsWith("unavailable:", StringComparison.Ordinal)).Select(static pair => pair.Key).ToArray(); + if (scriptExamples || nativeOwners.Any(owner => ( + !executionExclusions.ContainsKey(owner) + && (affected.Contains(owner) || documentationOwners.Contains(owner)) + )) + ) { + string[] unavailable = inputs + .Where(static pair => pair.Value.StartsWith("unavailable:", StringComparison.Ordinal)) + .Select(static pair => pair.Key) + .ToArray(); if (unavailable.Length != 0 && nativeDependencies is null) - return new(null, new("Blocked", "NativeSources", root, commit, mergeBase, - ValidationInputs.Identity(inputs), "Selected owners require unavailable pinned native sources. Prepare these inputs explicitly, then generate a new plan.", - nativeOwners.Where(owner => !executionExclusions.ContainsKey(owner) && (affected.Contains(owner) || documentationOwners.Contains(owner))) - .Concat(nativeDocumentOwners).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(), - unavailable.ToDictionary(static path => path, - path => inputs[path]["unavailable:".Length..], StringComparer.Ordinal))); + { + return new( + null, + new( + "Blocked", + "NativeSources", + root, + commit, + mergeBase, + ValidationInputs.Identity(inputs), + "Selected owners require unavailable pinned native sources. Prepare these inputs explicitly, then generate a new plan.", + nativeOwners + .Where( + owner => ( + !executionExclusions.ContainsKey(owner) + && (affected.Contains(owner) || documentationOwners.Contains(owner)) + ) + ) + .Concat(nativeDocumentOwners) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(), + unavailable.ToDictionary( + static path => path, + path => inputs[path]["unavailable:".Length..], + StringComparer.Ordinal + ) + ) + ); + } if (backendStore is null && nativeDependencies is not null && !File.Exists(Path.Combine(root, nativeDependencies))) - throw new InvalidDataException("Native dependency selection is missing: " + nativeDependencies - + ". Bind the matching backend package selection before native validation."); + { + throw new InvalidDataException( + "Native dependency selection is missing: " + nativeDependencies + + ". Bind the matching backend package selection before native validation." + ); + } if (development is null) + { throw new InvalidDataException("Native validation requires the existing development product declaration."); + } JsonElement host = development.Value.GetProperty("Properties"); target = host.GetProperty("InnoDevelopmentTarget").GetString() ?? string.Empty; string productProperties = host.GetProperty("InnoDevelopmentEditorBuildProperties").GetString() ?? string.Empty; if (target.Length == 0 || !File.Exists(productProperties)) + { throw new InvalidDataException("This SDK host has no supported native validation product. Required checks are blocked."); + } var nativeProperties = new Dictionary(contexts["managed"].properties) { ["ArtifactsPath"] = Path.Combine(artifacts, "native", target), @@ -313,62 +526,175 @@ internal static async Task CreateAsync( }; var evaluationProperties = new Dictionary(properties); foreach (var pair in nativeProperties) + { evaluationProperties[pair.Key] = pair.Value; - string nativeCapture = await ManagedProjectGraphCapture.CaptureSelectedAsync(root, sdk, - paths.Select(path => Path.Combine(root, path)).ToArray(), evaluationProperties, cancellation).ConfigureAwait(false); + } + string nativeCapture = await ManagedProjectGraphCapture.CaptureSelectedAsync( + root, + sdk, + paths.Select(path => Path.Combine(root, path)).ToArray(), + evaluationProperties, + cancellation + ).ConfigureAwait(false); using JsonDocument nativeGraph = JsonDocument.Parse(nativeCapture); RequireCompilerInputs(nativeGraph.RootElement); contexts.Add("native", new(nativeProperties, nativeGraph.RootElement.Clone())); - nativeProjects = nativeGraph.RootElement.EnumerateArray().Select(snapshot => ValidationProject.Read(root, snapshot)) + nativeProjects = nativeGraph.RootElement.EnumerateArray() + .Select(snapshot => ValidationProject.Read(root, snapshot)) .ToDictionary(static project => project.path, StringComparer.Ordinal); RecordStage("native-graph"); } - string[] policyInputs = inputs.Keys.Where(static path => path == "AGENTS.md" || path.StartsWith(".agents/rulebook/", StringComparison.Ordinal) - || path is ValidationCiContracts.C_RULE_LOADER or ValidationCiContracts.C_RULE_EXAMPLES).Order(StringComparer.Ordinal).ToArray(); - var inputSets = projects.ToDictionary(static project => project.path, - project => CapturedInputs(project.inputs.Concat(nativeProjects[project.path].inputs)), StringComparer.Ordinal); - var entryInputs = contexts.ToDictionary(static pair => pair.Key, - pair => new ValidationEntryInputs(root, pair.Value.sdkGraph, pair.Key, inputSets, CapturedInputs), StringComparer.Ordinal); + string[] policyInputs = inputs.Keys + .Where(static path => ( + path == "AGENTS.md" || path.StartsWith(".agents/rulebook/", StringComparison.Ordinal) + || path is ValidationCiContracts.C_RULE_LOADER or ValidationCiContracts.C_RULE_EXAMPLES + )) + .Order(StringComparer.Ordinal) + .ToArray(); + var inputSets = projects.ToDictionary( + static project => project.path, + project => CapturedInputs(project.inputs.Concat(nativeProjects[project.path].inputs)), + StringComparer.Ordinal + ); + var entryInputs = contexts.ToDictionary( + static pair => pair.Key, + pair => new ValidationEntryInputs(root, pair.Value.sdkGraph, pair.Key, inputSets, CapturedInputs), + StringComparer.Ordinal + ); const string C_VALIDATOR = "tools/Inno.Tooling.Validation/Inno.Tooling.Validation.csproj"; IEnumerable validatorInputs = byPath.ContainsKey(C_VALIDATOR) - ? entryInputs["managed"].Sources(C_VALIDATOR).SelectMany(key => inputSets[key]) : []; - string[] toolingInputs = CapturedInputs(validatorInputs.Concat(inputs.Keys.Where(static path => path is "global.json" - or "Directory.Build.props" or "Directory.Build.targets" or "Directory.Solution.targets" or "InnoEngine.sln"))).Order(StringComparer.Ordinal).ToArray(); - var changedSets = inputSets.Where(pair => pair.Value.Any(changes.Contains)).ToDictionary(static pair => pair.Key, - pair => pair.Value.First(changes.Contains), StringComparer.Ordinal); - bool toolingChanged = toolingInputs.Any(changes.Contains) || removedEntries.TryGetValue("managed", out var priorTooling) && priorTooling.Contains(C_VALIDATOR); - bool effectiveBuildChange = changes.Count > 0 && changes.All(path => path != ValidationRunner.C_TEST_EXECUTOR && !IsCiContractInput(path) - && (removedEntries.Count > 0 && removed.Contains(path, StringComparer.Ordinal) - || inputs.TryGetValue(path, out string? value) && value != "missing" && projects.Any(project => project.inputs.Contains(path, StringComparer.Ordinal)))); + ? entryInputs["managed"].Sources(C_VALIDATOR).SelectMany(key => inputSets[key]) + : []; + string[] toolingInputs = CapturedInputs( + validatorInputs.Concat( + inputs.Keys.Where(static path => ( + path is "global.json" + or "Directory.Build.props" or "Directory.Build.targets" or "Directory.Solution.targets" or "InnoEngine.sln" + )) + ) + ).Order(StringComparer.Ordinal).ToArray(); + var changedSets = inputSets.Where(pair => pair.Value.Any(changes.Contains)).ToDictionary( + static pair => pair.Key, + pair => pair.Value.First(changes.Contains), + StringComparer.Ordinal + ); + bool toolingChanged = toolingInputs.Any(changes.Contains) + || removedEntries.TryGetValue("managed", out var priorTooling) && priorTooling.Contains(C_VALIDATOR); + bool effectiveBuildChange = changes.Count > 0 + && changes.All(path => ( + path != ValidationRunner.C_TEST_EXECUTOR && !IsCiContractInput(path) + && (removedEntries.Count > 0 && removed.Contains(path, StringComparer.Ordinal) + || inputs.TryGetValue(path, out string? value) + && value != "missing" + && projects.Any(project => project.inputs.Contains(path, StringComparer.Ordinal))) + )); inputSets.Add("tooling", toolingInputs); inputSets.Add("native-sources", submoduleInputs); var checks = new List { - new("instructions", "instructions", "AGENTS.md", "Rule front matter, size limits and routing examples.", "any", [], policyInputs, true, null), - new("architecture", "architecture", "tools/Inno.Tooling.Architecture", "Cheap repository-wide source, ownership and architecture invariants.", "any", [], - inputs.Keys.Where(static path => path.Split('/')[0] is "src" or "entry" or "backends" or "platforms" or "build" or "tools" - || path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) - || path.EndsWith(".Tests.ps1", StringComparison.OrdinalIgnoreCase) - || path.EndsWith(".cs.txt", StringComparison.OrdinalIgnoreCase) && !path.StartsWith(".agents/records/", StringComparison.Ordinal) - || Path.GetExtension(path) is ".csproj" or ".props" or ".targets" - || path is "InnoEngine.sln" or "Directory.Build.props" or "Directory.Build.targets" or "Directory.Solution.targets") - .Order(StringComparer.Ordinal).ToArray(), true, null) + new( + "instructions", + "instructions", + "AGENTS.md", + "Rule front matter, size limits and routing examples.", + "any", + [], + policyInputs, + true, + null + ), + new( + "architecture", + "architecture", + "tools/Inno.Tooling.Architecture", + "Cheap repository-wide source, ownership and architecture invariants.", + "any", + [], + inputs.Keys + .Where(static path => ( + path.Split('/')[0] is "src" or "entry" or "backends" or "platforms" or "build" or "tools" + || path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) + || path.EndsWith(".Tests.ps1", StringComparison.OrdinalIgnoreCase) + || path.EndsWith(".cs.txt", StringComparison.OrdinalIgnoreCase) + && !path.StartsWith(".agents/records/", StringComparison.Ordinal) + || Path.GetExtension(path) is ".csproj" or ".props" or ".targets" + || path is "InnoEngine.sln" or "Directory.Build.props" or "Directory.Build.targets" or "Directory.Solution.targets" + )) + .Order(StringComparer.Ordinal) + .ToArray(), + true, + null + ) }; - if (changes.Any(static path => path.StartsWith(".agents/", StringComparison.Ordinal) || path is "AGENTS.md" or "CONTRIBUTING.md") || full) - checks.Add(new("agent-documents", "agent-documents", ".agents", "Rule, skill and record structure and links; no product compilation.", "any", [], - inputs.Keys.Where(static path => path.StartsWith(".agents/", StringComparison.Ordinal) || path is "AGENTS.md" or "CONTRIBUTING.md") - .Append("@tooling").Order(StringComparer.Ordinal).ToArray(), true, null)); + if (changes.Any(static path => path.StartsWith(".agents/", StringComparison.Ordinal) || path is "AGENTS.md" or "CONTRIBUTING.md") + || full + ) { + checks.Add( + new( + "agent-documents", + "agent-documents", + ".agents", + "Rule, skill and record structure and links; no product compilation.", + "any", + [], + inputs.Keys + .Where( + static path => path.StartsWith(".agents/", StringComparison.Ordinal) || path is "AGENTS.md" or "CONTRIBUTING.md" + ) + .Append("@tooling") + .Order(StringComparer.Ordinal) + .ToArray(), + true, + null + ) + ); + } if (documentation is not null) - checks.Add(new("documentation", "documentation", "InnoEngine.Docs", - "Explicitly selected canonical project entries and immutable reference payloads.", "any", [], - inputs.Keys.Where(static path => path.EndsWith(".csproj", StringComparison.Ordinal)).Append("@tooling").ToArray(), true, null, - documentation: new([], [], documentation.catalog.contentIdentity, configuration, null))); - bool gateOnly = !full && affected.Count == 0 && changes.Count > 0 && changes.All(path => ValidationCiContracts.GateScripts.Contains(path, StringComparer.Ordinal)); - if (full || changes.Any(static path => path.StartsWith(".github/", StringComparison.Ordinal) || IsCiContractInput(path) - || path.StartsWith("tools/Inno.Tooling.Validation/", StringComparison.Ordinal))) - checks.Add(new("ci-contracts", gateOnly ? "gate-contracts" : "ci-contracts", "tests/ci", "Fail-closed aggregation contracts for missing, skipped, canceled, empty and tampered evidence.", - "any", [], inputs.Keys.Where(path => IsCiContractInput(path) || path == ".github/workflows/engine-ci.yml").Append("@tooling").ToArray(), true, null)); + { + checks.Add( + new( + "documentation", + "documentation", + "InnoEngine.Docs", + "Explicitly selected canonical project entries and immutable reference payloads.", + "any", + [], + inputs.Keys + .Where(static path => path.EndsWith(".csproj", StringComparison.Ordinal)) + .Append("@tooling") + .ToArray(), + true, + null, + documentation: new([], [], documentation.catalog.contentIdentity, configuration, null) + ) + ); + } + bool gateOnly = !full + && affected.Count == 0 + && changes.Count > 0 + && changes.All(path => ValidationCiContracts.GateScripts.Contains(path, StringComparer.Ordinal)); + if (full || changes.Any(static path => ( + path.StartsWith(".github/", StringComparison.Ordinal) || IsCiContractInput(path) + || path.StartsWith("tools/Inno.Tooling.Validation/", StringComparison.Ordinal) + ))) { + checks.Add( + new( + "ci-contracts", + gateOnly ? "gate-contracts" : "ci-contracts", + "tests/ci", + "Fail-closed aggregation contracts for missing, skipped, canceled, empty and tampered evidence.", + "any", + [], + inputs.Keys + .Where(path => IsCiContractInput(path) || path == ".github/workflows/engine-ci.yml") + .Append("@tooling") + .ToArray(), + true, + null + ) + ); + } foreach (ValidationProject project in projects.OrderBy(static project => project.path, StringComparer.Ordinal)) { bool native = nativeOwners.Contains(project.path); @@ -377,91 +703,235 @@ internal static async Task CreateAsync( var closure = new HashSet(StringComparer.Ordinal); Visit(selectedGraph[project.path]); if (project.test && project.layer is not ("domain" or "contract" or "integration" or "native" or "product" or "performance")) + { throw new InvalidDataException($"Test execution layer is absent or unknown: {project.path} ({project.layer})"); + } if (project.layer == "domain" && native) + { throw new InvalidDataException($"Domain test transitively requires native preparation: {project.path}"); - string[] selectedInputs = closure.Select(static path => "@" + path).Append("@tooling") + } + string[] selectedInputs = closure.Select(static path => "@" + path) + .Append("@tooling") .Concat(context == "native" ? ["@native-sources"] : []) - .Concat(context == "native" && nativeDependencies is not null ? [nativeDependencies] : []).Order(StringComparer.Ordinal).ToArray(); + .Concat(context == "native" && nativeDependencies is not null ? [nativeDependencies] : []) + .Order(StringComparer.Ordinal) + .ToArray(); string[]? sourceSets = entryInputs.TryGetValue(context, out ValidationEntryInputs? graphInputs) - ? graphInputs.Sources(project.path) : null; + ? graphInputs.Sources(project.path) + : null; bool selected = affected.Contains(project.path); string? matchedSet = sourceSets?.FirstOrDefault(changedSets.ContainsKey); - bool baselineMatch = removed.Length > 0 && (!removedEntries.TryGetValue(context, out var priorEntries) || priorEntries.Contains(project.path)); + bool baselineMatch = removed.Length > 0 + && (!removedEntries.TryGetValue(context, out var priorEntries) || priorEntries.Contains(project.path)); if (selected && !full && effectiveBuildChange && sourceSets is not null && profile is ValidationProfile.PullRequest or ValidationProfile.Fast - && matchedSet is null && !baselineMatch && !toolingChanged) - { + && matchedSet is null && !baselineMatch && !toolingChanged + ) { selected = false; // A conditional source still belongs to its project when compiled through another entry. if (!project.inputs.Any(changes.Contains)) + { affected.Remove(project.path); + } diagnostics.Add($"No changed input in the evaluated {context} entry for {project.path}."); } if (selected && !full && matchedSet is not null) + { diagnostics.Add($"Selected {context} entry {project.path}: {changedSets[matchedSet]} is consumed by {matchedSet}."); + } if (selected && !full && baselineMatch) + { diagnostics.Add($"Selected {context} entry {project.path} for removed inputs at {mergeBase}."); + } bool compile = selected || documentationOwners.Contains(project.path); string environment = project.environment.Length != 0 ? project.environment : native ? "native-host" : "any"; string? exclusion = executionExclusions.GetValueOrDefault(project.path) ?? (project.productTarget.Length != 0 && target.Length != 0 && project.productTarget != target - ? $"Product '{project.productTarget}' requires its own supported target environment; current SDK host selects '{target}'." : null); + ? $"Product '{project.productTarget}' requires its own supported target environment; current SDK host selects '{target}'." + : null); if (compile) - checks.Add(new("build:" + project.path, "build", project.path, "Changed owner or transitive consumer; compile the shared union once.", - environment, [], selectedInputs, false, exclusion, context, "compilation", sourceSets: sourceSets)); + { + checks.Add( + new( + "build:" + project.path, + "build", + project.path, + "Changed owner or transitive consumer; compile the shared union once.", + environment, + [], + selectedInputs, + false, + exclusion, + context, + "compilation", + sourceSets: sourceSets + ) + ); + } if (project.test) - checks.Add(new("test:" + project.path, "test", project.path, selected + { + checks.Add( + new( + "test:" + project.path, + "test", + project.path, + selected ? "Affected behavior or contract consumer; compiled SupportedOSPlatform requirements distinguish host exclusions from missing execution." : "No affected input in its evaluated closure.", - environment, ["build:" + project.path], [..selectedInputs, ValidationRunner.C_TEST_EXECUTOR], project.reusable && project.layer is not ("performance" or "product"), - selected ? exclusion : "Outside the affected evaluated dependency closure.", context, project.layer, sourceSets: sourceSets)); + environment, + ["build:" + project.path], + [..selectedInputs, ValidationRunner.C_TEST_EXECUTOR], + project.reusable + && project.layer is not ("performance" or "product"), + selected ? exclusion : "Outside the affected evaluated dependency closure.", + context, + project.layer, + sourceSets: sourceSets + ) + ); + } void Visit(ValidationProject node) { if (!closure.Add(node.path)) + { return; + } foreach (string dependency in node.references) + { if (selectedGraph.TryGetValue(dependency, out ValidationProject? next)) + { Visit(next); + } else + { throw new InvalidDataException($"Unknown evaluated dependency '{dependency}' from '{node.path}'."); + } + } } } - if (profile != ValidationProfile.Fast && checks.Any(check => check.kind == "build" && check.exclusion is null && affected.Contains(check.owner)) - && !checks.Any(static check => check.kind == "test" && check.exclusion is null)) - throw new InvalidDataException("Affected production inputs have no selected behavior tests. Declare their real public contract consumers."); + if (profile != ValidationProfile.Fast + && checks.Any(check => check.kind == "build" && check.exclusion is null && affected.Contains(check.owner)) + && !checks.Any(static check => check.kind == "test" && check.exclusion is null) + ) { + throw new InvalidDataException( + "Affected production inputs have no selected behavior tests. Declare their real public contract consumers." + ); + } ValidationCheck[] builds = checks.Where(static check => check.kind == "build" && check.exclusion is null).ToArray(); foreach (IGrouping group in builds.GroupBy(static check => check.context)) { - string[] apiOwners = group.Select(static check => check.owner).Where(owner => !byPath[owner].test) - .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); - checks.Add(new("compiled-api:" + group.Key, "api", "tools/Inno.Tooling.Architecture", "Public/protected signatures in affected owners and their evaluated dependencies.", - "any", group.Select(static check => check.id).ToArray(), group.SelectMany(static check => check.inputs).Distinct().Order(StringComparer.Ordinal).ToArray(), true, - apiOwners.Length == 0 ? "Only test implementations changed; their unchanged production dependencies have no affected API owner." : null, - group.Key, "contract", apiOwners)); + string[] apiOwners = group.Select(static check => check.owner) + .Where(owner => !byPath[owner].test) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); + checks.Add( + new( + "compiled-api:" + group.Key, + "api", + "tools/Inno.Tooling.Architecture", + "Public/protected signatures in affected owners and their evaluated dependencies.", + "any", + group.Select(static check => check.id).ToArray(), + group + .SelectMany(static check => check.inputs) + .Distinct() + .Order(StringComparer.Ordinal) + .ToArray(), + true, + apiOwners.Length == 0 ? "Only test implementations changed; their unchanged production dependencies have no affected API owner." : null, + group.Key, + "contract", + apiOwners + ) + ); } if (documentation is not null) + { AddDocumentationChecks(); - ValidationCheck? editorBuild = builds.SingleOrDefault(static check => check.owner == "entry/InnoEngine.Editor/InnoEngine.Editor.csproj"); + } + ValidationCheck? editorBuild = builds.SingleOrDefault( + static check => check.owner == "entry/InnoEngine.Editor/InnoEngine.Editor.csproj" + ); if (editorBuild is not null) - checks.Add(new("editor-products", "products", editorBuild.owner, "Real renderer startup, product workflows and native panel retirement for the affected Editor product.", - "native-host", [editorBuild.id], editorBuild.inputs.Concat(inputs.Keys.Where(static path => path.StartsWith("tests/fixtures/editor-ui/", StringComparison.Ordinal) - || path is "tests/Invoke-EditorSmoke.ps1" or "tests/Invoke-EditorUiProductJourney.ps1")).Distinct().Order(StringComparer.Ordinal).ToArray(), false, null, "native", "product")); + { + checks.Add( + new( + "editor-products", + "products", + editorBuild.owner, + "Real renderer startup, product workflows and native panel retirement for the affected Editor product.", + "native-host", + [editorBuild.id], + editorBuild.inputs + .Concat( + inputs.Keys.Where(static path => ( + path.StartsWith("tests/fixtures/editor-ui/", StringComparison.Ordinal) + || path is "tests/Invoke-EditorSmoke.ps1" or "tests/Invoke-EditorUiProductJourney.ps1" + )) + ) + .Distinct() + .Order(StringComparer.Ordinal) + .ToArray(), + false, + null, + "native", + "product" + ) + ); + } if (editorBuild is not null && (extended || profile == ValidationProfile.Performance)) - checks.Add(new("native-hot-builds", "hot-builds", editorBuild.owner, - "Ten unchanged native builds must retain content selections and start no native compiler or binding generation.", - "native-host", [editorBuild.id], editorBuild.inputs.Append("tests/Invoke-BuildCacheChecks.ps1").ToArray(), false, null, "native", "performance")); - if (profile == ValidationProfile.Performance && !checks.Any(static check => check.layer == "performance" && check.exclusion is null)) + { + checks.Add( + new( + "native-hot-builds", + "hot-builds", + editorBuild.owner, + "Ten unchanged native builds must retain content selections and start no native compiler or binding generation.", + "native-host", + [editorBuild.id], + editorBuild.inputs + .Append("tests/Invoke-BuildCacheChecks.ps1") + .ToArray(), + false, + null, + "native", + "performance" + ) + ); + } + if (profile == ValidationProfile.Performance + && !checks.Any(static check => check.layer == "performance" && check.exclusion is null) + ) { throw new InvalidDataException("Performance validation requires an applicable sampling check."); + } if (extended) - checks.Insert(0, new("cold-inputs", "cold-inputs", "build", "Explicit cold acceptance requires an initially unprepared native cache.", - "native-host", [], ["@tooling"], false, null, "native", "performance")); + { + checks.Insert( + 0, + new( + "cold-inputs", + "cold-inputs", + "build", + "Explicit cold acceptance requires an initially unprepared native cache.", + "native-host", + [], + ["@tooling"], + false, + null, + "native", + "performance" + ) + ); + } if ((full || profile == ValidationProfile.Master) && editorBuild?.context == "native") { const string C_BUILD_ENTRY = "entry/InnoEngine.Build/InnoEngine.Build.csproj"; if (!byPath.ContainsKey(C_BUILD_ENTRY)) + { throw new InvalidDataException("Complete product acceptance requires the declared Build entry."); + } string releaseContext = configuration == "Release" ? "native" : "native-release"; Dictionary releaseProjects = nativeProjects; if (releaseContext != "native") @@ -469,8 +939,13 @@ void Visit(ValidationProject node) if (backendStore is not null) { var releaseInputsProperties = new Dictionary(properties) { ["Configuration"] = "Release" }; - string backendCapture = await ManagedProjectGraphCapture.CaptureSelectedAsync(root, sdk, - paths.Select(path => Path.Combine(root, path)).ToArray(), releaseInputsProperties, cancellation).ConfigureAwait(false); + string backendCapture = await ManagedProjectGraphCapture.CaptureSelectedAsync( + root, + sdk, + paths.Select(path => Path.Combine(root, path)).ToArray(), + releaseInputsProperties, + cancellation + ).ConfigureAwait(false); using JsonDocument backendGraph = JsonDocument.Parse(backendCapture); RequireCompilerInputs(backendGraph.RootElement); contexts.Add("backend-release", new(releaseInputsProperties, backendGraph.RootElement.Clone())); @@ -482,19 +957,37 @@ void Visit(ValidationProject node) }; var evaluationProperties = new Dictionary(properties); foreach (var pair in releaseProperties) + { evaluationProperties[pair.Key] = pair.Value; - string releaseCapture = await ManagedProjectGraphCapture.CaptureSelectedAsync(root, sdk, - paths.Select(path => Path.Combine(root, path)).ToArray(), evaluationProperties, cancellation).ConfigureAwait(false); + } + string releaseCapture = await ManagedProjectGraphCapture.CaptureSelectedAsync( + root, + sdk, + paths.Select(path => Path.Combine(root, path)).ToArray(), + evaluationProperties, + cancellation + ).ConfigureAwait(false); using JsonDocument releaseGraph = JsonDocument.Parse(releaseCapture); RequireCompilerInputs(releaseGraph.RootElement); contexts.Add(releaseContext, new(releaseProperties, releaseGraph.RootElement.Clone())); - releaseProjects = releaseGraph.RootElement.EnumerateArray().Select(snapshot => ValidationProject.Read(root, snapshot)) + releaseProjects = releaseGraph.RootElement.EnumerateArray() + .Select(snapshot => ValidationProject.Read(root, snapshot)) .ToDictionary(static project => project.path, StringComparer.Ordinal); foreach (ValidationProject project in releaseProjects.Values) - inputSets[project.path] = inputSets[project.path].Concat(CapturedInputs(project.inputs)).Distinct(StringComparer.Ordinal).ToArray(); + { + inputSets[project.path] = inputSets[project.path] + .Concat(CapturedInputs(project.inputs)) + .Distinct(StringComparer.Ordinal) + .ToArray(); + } } if (!entryInputs.TryGetValue(releaseContext, out ValidationEntryInputs? releaseEntries)) - entryInputs.Add(releaseContext, releaseEntries = new(root, contexts[releaseContext].sdkGraph, releaseContext, inputSets, CapturedInputs)); + { + entryInputs.Add( + releaseContext, + releaseEntries = new(root, contexts[releaseContext].sdkGraph, releaseContext, inputSets, CapturedInputs) + ); + } var releaseInputs = new HashSet(StringComparer.Ordinal) { "@tooling", "@native-sources" }; var releaseBuilds = new List(); string[] releaseRoots = [editorBuild.owner, C_BUILD_ENTRY]; @@ -504,54 +997,175 @@ void Visit(ValidationProject node) string id = (releaseContext == "native" ? "build:" : "release-build:") + owner; releaseBuilds.Add(id); if (releaseContext != "native") - checks.Add(new(id, "build", owner, "Release product acceptance prepares its configuration once before execution and packaging.", - "native-host", [], releaseInputs.Order(StringComparer.Ordinal).ToArray(), false, null, releaseContext, "compilation", - sourceSets: releaseEntries.Sources(owner))); + { + checks.Add( + new( + id, + "build", + owner, + "Release product acceptance prepares its configuration once before execution and packaging.", + "native-host", + [], + releaseInputs + .Order(StringComparer.Ordinal) + .ToArray(), + false, + null, + releaseContext, + "compilation", + sourceSets: releaseEntries.Sources(owner) + ) + ); + } } if (releaseContext != "native") { - checks.Add(new("compiled-api:release", "api", "tools/Inno.Tooling.Architecture", "Release symbols retain the same public boundary requirements.", - "native-host", releaseBuilds.ToArray(), releaseInputs.Order(StringComparer.Ordinal).ToArray(), true, null, releaseContext, "contract", - releaseInputs.Where(input => input.StartsWith('@') && releaseProjects.ContainsKey(input[1..])).Select(static input => input[1..]).Order(StringComparer.Ordinal).ToArray())); - checks.Add(new("editor-release-products", "products", editorBuild.owner, "Execute the actual Release Editor renderer, workflow and lifecycle before packaging.", - "native-host", releaseBuilds.ToArray(), editorBuild.inputs.Concat(releaseInputs).Distinct(StringComparer.Ordinal).ToArray(), false, null, releaseContext, "product")); + checks.Add( + new( + "compiled-api:release", + "api", + "tools/Inno.Tooling.Architecture", + "Release symbols retain the same public boundary requirements.", + "native-host", + releaseBuilds.ToArray(), + releaseInputs + .Order(StringComparer.Ordinal) + .ToArray(), + true, + null, + releaseContext, + "contract", + releaseInputs + .Where(input => input.StartsWith('@') && releaseProjects.ContainsKey(input[1..])) + .Select(static input => input[1..]) + .Order(StringComparer.Ordinal) + .ToArray() + ) + ); + checks.Add( + new( + "editor-release-products", + "products", + editorBuild.owner, + "Execute the actual Release Editor renderer, workflow and lifecycle before packaging.", + "native-host", + releaseBuilds.ToArray(), + editorBuild.inputs + .Concat(releaseInputs) + .Distinct(StringComparer.Ordinal) + .ToArray(), + false, + null, + releaseContext, + "product" + ) + ); } - checks.Add(new("support-pack", "support-pack", C_BUILD_ENTRY, "Publish and verify the source-independent Release Player Support Pack under its existing read lease.", - "native-host", releaseBuilds.ToArray(), releaseInputs.Order(StringComparer.Ordinal).ToArray(), false, null, releaseContext, "product")); - JsonElement[] players = contexts[releaseContext].sdkGraph.EnumerateArray().Where(snapshot => + checks.Add( + new( + "support-pack", + "support-pack", + C_BUILD_ENTRY, + "Publish and verify the source-independent Release Player Support Pack under its existing read lease.", + "native-host", + releaseBuilds.ToArray(), + releaseInputs + .Order(StringComparer.Ordinal) + .ToArray(), + false, + null, + releaseContext, + "product" + ) + ); + JsonElement[] players = contexts[releaseContext].sdkGraph.EnumerateArray().Where(snapshot => ( snapshot.GetProperty("Properties").GetProperty("InnoProductId").GetString() == "player" && snapshot.GetProperty("Properties").GetProperty("InnoProductTarget").GetString() == target - && !string.Equals(snapshot.GetProperty("Properties").GetProperty("IsTestProject").GetString(), "true", StringComparison.OrdinalIgnoreCase) - && !string.Equals(snapshot.GetProperty("Properties").GetProperty("IsTestSupportProject").GetString(), "true", StringComparison.OrdinalIgnoreCase)).ToArray(); + && !string.Equals( + snapshot.GetProperty("Properties").GetProperty("IsTestProject").GetString(), + "true", + StringComparison.OrdinalIgnoreCase + ) + && !string.Equals( + snapshot.GetProperty("Properties").GetProperty("IsTestSupportProject").GetString(), + "true", + StringComparison.OrdinalIgnoreCase + ) + )).ToArray(); if (players.Length != 1) + { throw new InvalidDataException("Full host acceptance requires exactly one actual Player product declaration."); + } string playerOwner = Path.GetRelativePath(root, players[0].GetProperty("Path").GetString()!).Replace('\\', '/'); VisitRelease(playerOwner); - checks.Add(new("native-aot-restore", "restore-aot", playerOwner, - "Restore the actual host Player with NativeAOT SDK inputs in an independently owned restore layout.", - "native-host", releaseBuilds.ToArray(), releaseInputs.Order(StringComparer.Ordinal).ToArray(), false, null, releaseContext, "contract")); + checks.Add( + new( + "native-aot-restore", + "restore-aot", + playerOwner, + "Restore the actual host Player with NativeAOT SDK inputs in an independently owned restore layout.", + "native-host", + releaseBuilds.ToArray(), + releaseInputs + .Order(StringComparer.Ordinal) + .ToArray(), + false, + null, + releaseContext, + "contract" + ) + ); // Restore-only inputs still invalidate the bundle, but only built roots provide compiled output instances. - checks.Add(new("release-bundle", "release-bundle", editorBuild.owner, "Archive the exact verified Release product outputs; the final gate additionally requires every independent functional shard.", - "native-host", checks.Where(static check => check.exclusion is null && check.context != "managed").Select(static check => check.id).ToArray(), - releaseInputs.Order(StringComparer.Ordinal).ToArray(), false, null, releaseContext, "product", releaseRoots)); + checks.Add( + new( + "release-bundle", + "release-bundle", + editorBuild.owner, + "Archive the exact verified Release product outputs; the final gate additionally requires every independent functional shard.", + "native-host", + checks + .Where(static check => check.exclusion is null && check.context != "managed") + .Select(static check => check.id) + .ToArray(), + releaseInputs.Order(StringComparer.Ordinal).ToArray(), + false, + null, + releaseContext, + "product", + releaseRoots + ) + ); void VisitRelease(string owner) { if (!releaseInputs.Add("@" + owner)) + { return; + } if (!releaseProjects.TryGetValue(owner, out ValidationProject? project)) + { throw new InvalidDataException($"Unknown Release dependency: {owner}"); + } foreach (string reference in project.references) + { VisitRelease(reference); + } } } RecordStage("selection-and-release-graph"); - string environmentIdentity = await ValidationEnvironment.CaptureAsync(root, sdk.hostPath, cancellation, contexts.Values, toolSnapshot).ConfigureAwait(false); + string environmentIdentity = await ValidationEnvironment.CaptureAsync( + root, + sdk.hostPath, + cancellation, + contexts.Values, + toolSnapshot + ).ConfigureAwait(false); RecordStage("execution-environment"); - var phases = contexts.Keys.Select(static ( - string context, - int index - ) => new KeyValuePair(context, index + 1)) + var phases = contexts.Keys + .Select(static ( + string context, + int index + ) => new KeyValuePair(context, index + 1)) .ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.Ordinal); // Policy and architecture govern compilation; unrelated documentation/contract failures do not. // Cold acceptance is a native preparation prerequisite, not a global stop for managed checks. @@ -559,32 +1173,72 @@ int index { prerequisites = check.prerequisites .Concat(check.kind == "build" ? ["instructions", "architecture"] : Array.Empty()) - .Concat(extended && check.context is not (null or "managed") && check.kind != "cold-inputs" - ? ["cold-inputs"] : Array.Empty()) - .Distinct(StringComparer.Ordinal).ToArray() + .Concat( + extended && check.context is not (null or "managed") && check.kind != "cold-inputs" + ? ["cold-inputs"] + : Array.Empty() + ) + .Distinct(StringComparer.Ordinal) + .ToArray() }).ToList(); - ValidationCheck[] execution = checks.OrderBy(check => check.kind == "cold-inputs" ? -1 : check.kind == "release-bundle" ? int.MaxValue - : check.context is null ? 0 : phases.GetValueOrDefault(check.context, phases.Count + 1)) - .ThenBy(static check => check.kind switch { "build" => 0, "api" => 1, "documentation-api" or "documentation-examples" => 2, "test" => 3, _ => 4 }).ToArray(); + ValidationCheck[] execution = checks + .OrderBy(check => ( + check.kind == "cold-inputs" ? -1 : check.kind == "release-bundle" + ? int.MaxValue + : check.context is null ? 0 : phases.GetValueOrDefault(check.context, phases.Count + 1) + )) + .ThenBy( + static check => check.kind switch + { + "build" => 0, + "api" => 1, + "documentation-api" or "documentation-examples" => 2, + "test" => 3, + _ => 4 + } + ) + .ToArray(); var preceding = new HashSet(StringComparer.Ordinal); foreach (ValidationCheck check in execution) { if (check.exclusion is null && check.prerequisites.Any(prerequisite => !preceding.Contains(prerequisite))) + { throw new InvalidDataException($"Required prerequisites are missing or scheduled after '{check.id}'."); + } preceding.Add(check.id); } - execution = execution.Select(check => check.kind == "test" && check.layer == "native" && check.exclusion is null + execution = execution.Select(check => ( + check.kind == "test" && check.layer == "native" && check.exclusion is null && check.context is not null && contexts[check.context].properties.ContainsKey("InnoNativeTarget") - ? check with { consumedProducts = CollectNativeRequests(contexts[check.context], [check.owner]).Distinct() - .OrderBy(static request => request.target, StringComparer.Ordinal).ThenBy(static request => request.configuration, StringComparer.Ordinal) - .ThenBy(static request => request.product, StringComparer.Ordinal).ToArray() } : check).ToArray(); + ? check with + { + consumedProducts = CollectNativeRequests(contexts[check.context], [check.owner]).Distinct() + .OrderBy(static request => request.target, StringComparer.Ordinal) + .ThenBy(static request => request.configuration, StringComparer.Ordinal) + .ThenBy(static request => request.product, StringComparer.Ordinal) + .ToArray() + } + : check + )).ToArray(); ValidationNativeRequest[] requests = contexts.Values.Where(context => context.properties.ContainsKey("InnoNativeTarget")) - .SelectMany(context => CollectNativeRequests(context, checks.Where(check => check.exclusion is null && check.kind == "build" - && check.context is not null && ReferenceEquals(contexts[check.context], context)).Select(static check => check.owner))) - .Concat(checks.Where(static check => check.exclusion is null && check.kind == "support-pack") - .Select(check => new ValidationNativeRequest(contexts[check.context!].properties["InnoNativeTarget"], "Release", "player"))) - .Distinct().OrderBy(static request => request.target, StringComparer.Ordinal) - .ThenBy(static request => request.configuration, StringComparer.Ordinal).ThenBy(static request => request.product, StringComparer.Ordinal).ToArray(); + .SelectMany(context => CollectNativeRequests( + context, + checks.Where(check => ( + check.exclusion is null && check.kind == "build" + && check.context is not null && ReferenceEquals(contexts[check.context], context) + )).Select(static check => check.owner) + )) + .Concat( + checks.Where(static check => check.exclusion is null && check.kind == "support-pack") + .Select( + check => new ValidationNativeRequest(contexts[check.context!].properties["InnoNativeTarget"], "Release", "player") + ) + ) + .Distinct() + .OrderBy(static request => request.target, StringComparer.Ordinal) + .ThenBy(static request => request.configuration, StringComparer.Ordinal) + .ThenBy(static request => request.product, StringComparer.Ordinal) + .ToArray(); if (backendStore is not null) { foreach (ValidationContext context in contexts.Values) @@ -593,22 +1247,70 @@ int index context.properties["InnoBackendHostTarget"] = target; } } - return new(new(root, mergeBase, commit, ValidationInputs.Identity(inputs), environmentIdentity, configuration, sdk.hostPath, artifacts, - full, changes.Order(StringComparer.Ordinal).ToArray(), affected.Order(StringComparer.Ordinal).ToArray(), execution, diagnostics.ToArray(), inputs, inputSets, contexts, extended, timings, documentation?.binding, - documentation?.sourceIdentities.ToDictionary(static pair => pair.Key, static pair => pair.Value.identity, StringComparer.Ordinal), profile, nativeDependencies, requests, ValidationShards.Create(execution), backendStore, backendStore is null ? null : target, - hostExcludedSources: ValidationTestHosts.ExcludedSources(projects) - .Concat(ValidationCiContracts.GateScripts.Where(path => inputs.ContainsKey(path) - && !projects.Concat(nativeProjects.Values).Any(project => project.inputs.Contains(path, StringComparer.Ordinal)))) - .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(), - portableTestChanges: !full && profile is (ValidationProfile.Fast or ValidationProfile.PullRequest) - && changes.Count > 0 && removed.Length == 0 && affected.Count > 0 - && affected.All(owner => byPath[owner] is { test: true, layer: "domain" }) - && changes.All(change => change.EndsWith(".cs", StringComparison.Ordinal) - && affected.Any(owner => change.StartsWith(DirectoryOf(owner), StringComparison.Ordinal) - && byPath[owner].inputs.Contains(change, StringComparer.Ordinal))) - && execution.Any(static check => check.exclusion is null && check.kind == "test") - && execution.All(static check => check.exclusion is not null || check.kind is "instructions" or "architecture" - || check.context == "managed" && check.kind is ("test" or "build"))), null); + return new( + new( + root, + mergeBase, + commit, + ValidationInputs.Identity(inputs), + environmentIdentity, + configuration, + sdk.hostPath, + artifacts, + full, + changes.Order(StringComparer.Ordinal).ToArray(), + affected + .Order(StringComparer.Ordinal) + .ToArray(), + execution, + diagnostics.ToArray(), + inputs, + inputSets, + contexts, + extended, + timings, + documentation?.binding, + documentation?.sourceIdentities.ToDictionary( + static pair => pair.Key, + static pair => pair.Value.identity, + StringComparer.Ordinal + ), + profile, + nativeDependencies, + requests, + ValidationShards.Create(execution), + backendStore, + backendStore is null + ? null + : target, + hostExcludedSources: ValidationTestHosts.ExcludedSources(projects) + .Concat( + ValidationCiContracts.GateScripts.Where(path => ( + inputs.ContainsKey(path) + && !projects.Concat(nativeProjects.Values).Any(project => project.inputs.Contains(path, StringComparer.Ordinal)) + )) + ) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(), + portableTestChanges: !full && profile is (ValidationProfile.Fast or ValidationProfile.PullRequest) + && changes.Count > 0 && removed.Length == 0 && affected.Count > 0 + && affected.All(owner => byPath[owner] is { test: true, layer: "domain" }) + && changes.All(change => ( + change.EndsWith(".cs", StringComparison.Ordinal) + && affected.Any(owner => ( + change.StartsWith(DirectoryOf(owner), StringComparison.Ordinal) + && byPath[owner].inputs.Contains(change, StringComparer.Ordinal) + )) + )) + && execution.Any(static check => check.exclusion is null && check.kind == "test") + && execution.All(static check => ( + check.exclusion is not null || check.kind is "instructions" or "architecture" + || check.context == "managed" && check.kind is ("test" or "build") + )) + ), + null + ); IEnumerable CollectNativeRequests( ValidationContext context, @@ -616,33 +1318,44 @@ IEnumerable roots ) { string id = contexts.Single(pair => ReferenceEquals(pair.Value, context)).Key; if (!entryInputs.TryGetValue(id, out ValidationEntryInputs? entries)) + { entryInputs.Add(id, entries = new(root, context.sdkGraph, id, inputSets, CapturedInputs)); + } var pending = new Stack<(string instance, bool productOwned)>(roots.Select(owner => (entries.Entry(owner), false))); var visited = new HashSet<(string instance, bool productOwned)>(); while (pending.TryPop(out var request)) { if (!visited.Add(request)) + { continue; + } var node = entries.Instance(request.instance); JsonElement variant = node.variant; string owner = variant.GetProperty("Path").GetString()!; JsonElement declared = variant.GetProperty("Properties"); bool productOwned = request.productOwned - || !string.IsNullOrWhiteSpace(declared.GetProperty("InnoTestNativeProduct").GetString()) - || !string.IsNullOrWhiteSpace(declared.GetProperty("InnoProductId").GetString()); + || !string.IsNullOrWhiteSpace(declared.GetProperty("InnoTestNativeProduct").GetString()) + || !string.IsNullOrWhiteSpace(declared.GetProperty("InnoProductId").GetString()); foreach (string property in new[] { "InnoTestNativeProduct", "InnoProductId" }) + { if (declared.GetProperty(property).GetString() is { Length: > 0 } product) { string targetProperty = property == "InnoTestNativeProduct" ? "InnoTestNativeTarget" : "InnoProductTarget"; string declaredTarget = declared.GetProperty(targetProperty).GetString() ?? string.Empty; - yield return new(declaredTarget.Length == 0 ? context.properties["InnoNativeTarget"] : declaredTarget, - context.properties["Configuration"], product); + yield return new( + declaredTarget.Length == 0 ? context.properties["InnoNativeTarget"] : declaredTarget, + context.properties["Configuration"], + product + ); } + } // Product preparation supplies its exact binding selection to references. Only a standalone // binding consumer needs the component's explicit product declaration as an additional request. if (!productOwned && declared.GetProperty("BindGenGeneratedBindings").GetString() == "true" - && declared.GetProperty("InnoBindingProductId").GetString() is { Length: > 0 } bindingProduct) + && declared.GetProperty("InnoBindingProductId").GetString() is { Length: > 0 } bindingProduct + ) { yield return new(context.properties["InnoNativeTarget"], context.properties["Configuration"], bindingProduct); + } JsonElement items = variant.GetProperty("Items"); foreach (JsonElement dependency in items.GetProperty("InnoNativeDependency").EnumerateArray()) { @@ -650,12 +1363,18 @@ IEnumerable roots string dependencyTarget = dependency.GetProperty("TargetId").GetString()!; string dependencyConfiguration = dependency.GetProperty("Configuration").GetString()!; if (string.IsNullOrWhiteSpace(product) || string.IsNullOrWhiteSpace(dependencyTarget) - || dependencyConfiguration is not ("Debug" or "Release")) - throw new InvalidDataException("A native build dependency must declare product, target and configuration: " + owner); + || dependencyConfiguration is not ("Debug" or "Release") + ) { + throw new InvalidDataException( + "A native build dependency must declare product, target and configuration: " + owner + ); + } yield return new(dependencyTarget, dependencyConfiguration, product); } foreach (string reference in node.references) + { pending.Push((reference, productOwned)); + } } } @@ -663,84 +1382,225 @@ void AddDocumentationChecks() { ValidationDocumentation.Selection selected = documentation!; foreach (var excluded in exampleExclusions) - checks.Add(new("documentation-examples:excluded:" + excluded.Key.id, "documentation-examples", "InnoEngine.Docs", - "The example retains its declared product and environment obligations in the corresponding matrix cell.", "any", [], - ["@tooling"], false, excluded.Value, layer: "contract", documentation: new([], [excluded.Key.id], - ValidationDocumentation.PageIdentity([excluded.Key]), configuration, null))); + { + checks.Add( + new( + "documentation-examples:excluded:" + excluded.Key.id, + "documentation-examples", + "InnoEngine.Docs", + "The example retains its declared product and environment obligations in the corresponding matrix cell.", + "any", + [], + ["@tooling"], + false, + excluded.Value, + layer: "contract", + documentation: new( + [], + [excluded.Key.id], + ValidationDocumentation.PageIdentity([excluded.Key]), + configuration, + null + ) + ) + ); + } var owners = affected.Concat(selected.changedReferenceOwners.Select(owner => selected.owners[owner].path)) - .Where(owner => !byPath[owner].test && !executionExclusions.ContainsKey(owner) - && (byPath[owner].productTarget.Length == 0 || byPath[owner].productTarget == target)) + .Where(owner => ( + !byPath[owner].test && !executionExclusions.ContainsKey(owner) + && (byPath[owner].productTarget.Length == 0 || byPath[owner].productTarget == target) + )) .Where(owner => selected.owners.GetValueOrDefault(Path.GetFileNameWithoutExtension(owner))?.nativeReference != true) .ToHashSet(StringComparer.Ordinal); var covered = new HashSet(StringComparer.Ordinal); - var captures = selected.catalog.references.Where(reference => reference.model == "source-clr" && reference.configuration == configuration - && (reference.target is null || reference.target == target)) - .SelectMany(reference => reference.projects.Where(name => selected.owners.TryGetValue(name, out ValidationDocumentation.Owner? owner) - && owners.Contains(owner.path)) + var captures = selected.catalog.references + .Where(reference => ( + reference.model == "source-clr" && reference.configuration == configuration + && (reference.target is null || reference.target == target) + )) + .SelectMany(reference => reference.projects + .Where(name => ( + selected.owners.TryGetValue(name, out ValidationDocumentation.Owner? owner) + && owners.Contains(owner.path) + )) .Select(name => (reference, name, path: selected.owners[name].path))) - .GroupBy(item => (context: nativeOwners.Contains(item.path) || nativeDocumentOwners.Contains(item.path) ? "native" : "managed", item.reference.configuration, item.reference.target)); + .GroupBy( + item => (context: nativeOwners.Contains(item.path) || nativeDocumentOwners.Contains(item.path) + ? "native" + : "managed", item.reference.configuration, item.reference.target) + ); foreach (var group in captures) { - string[] paths = group.Select(static item => item.path).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); + string[] paths = group + .Select(static item => item.path) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); covered.UnionWith(paths); ValidationCheck[] required = builds.Where(check => paths.Contains(check.owner, StringComparer.Ordinal)).ToArray(); - string[] references = group.Select(static item => item.reference.path).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); - string identity = ValidationInputs.Identity(group.Select(item => new KeyValuePair(item.path, - selected.sourceIdentities[item.reference.path + "\0" + item.name].identity))); - checks.Add(new("documentation-api:" + group.Key.context + ":" + (group.Key.target ?? "default"), "documentation-api", "InnoEngine.Docs", - "Selected owner declarations and XML from protected source reference payloads.", "any", - required.Select(static check => check.id).Append("documentation").ToArray(), - required.SelectMany(static check => check.inputs).Append("@tooling").Distinct(StringComparer.Ordinal).ToArray(), true, null, - group.Key.context, "contract", paths, new(references, [], identity, configuration, group.Key.target))); + string[] references = group + .Select(static item => item.reference.path) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); + string identity = ValidationInputs.Identity( + group.Select(item => new KeyValuePair( + item.path, + selected.sourceIdentities[item.reference.path + "\0" + item.name].identity + )) + ); + checks.Add( + new( + "documentation-api:" + + group.Key.context + + ":" + + (group.Key.target ?? "default"), + "documentation-api", + "InnoEngine.Docs", + "Selected owner declarations and XML from protected source reference payloads.", + "any", + required.Select(static check => check.id).Append("documentation").ToArray(), + required + .SelectMany(static check => check.inputs) + .Append("@tooling") + .Distinct(StringComparer.Ordinal) + .ToArray(), + true, + null, + group.Key.context, + "contract", + paths, + new(references, [], identity, configuration, group.Key.target) + ) + ); } foreach (string owner in owners.Except(covered).Order(StringComparer.Ordinal)) { ValidationCheck? prepared = builds.SingleOrDefault(check => check.owner == owner); - checks.Add(new("documentation-api-missing:" + owner, "documentation-missing", owner, - "Required source API capture is absent for the selected configuration and target. Prepared owners may export unverified facts for review; capture does not pass this requirement.", - "any", prepared is null ? ["documentation"] : ["documentation", prepared.id], - prepared?.inputs ?? ["@" + owner], false, null, prepared?.context, "contract", - prepared is null ? null : [owner], prepared is null ? null : new([], [], "", configuration, - prepared.context == "native" ? target : null))); + checks.Add( + new( + "documentation-api-missing:" + owner, + "documentation-missing", + owner, + "Required source API capture is absent for the selected configuration and target. Prepared owners may export unverified facts for review; capture does not pass this requirement.", + "any", + prepared is null ? ["documentation"] : ["documentation", prepared.id], + prepared?.inputs ?? ["@" + owner], + false, + null, + prepared?.context, + "contract", + prepared is null ? null : [owner], + prepared is null ? null : new( + [], + [], + "", + configuration, + prepared.context == "native" ? target : null + ) + ) + ); } // Foreign product execution stays excluded. Its explicitly empty authored public surface // can still be checked against actual SDK-selected source without borrowing host binaries. - var emptyForeign = selected.catalog.references.Where(reference => reference.model == "source-clr" - && reference.configuration == configuration) - .SelectMany(reference => reference.projects.Where(name => selected.owners.TryGetValue(name, out ValidationDocumentation.Owner? owner) + var emptyForeign = selected.catalog.references + .Where(reference => (reference.model == "source-clr" && reference.configuration == configuration)) + .SelectMany(reference => reference.projects + .Where(name => ( + selected.owners.TryGetValue(name, out ValidationDocumentation.Owner? owner) && !owner.test && !owner.nativeReference && byPath[owner.path].productTarget.Length != 0 && byPath[owner.path].productTarget != target && (affected.Contains(owner.path) || selected.changedReferenceOwners.Contains(name)) - && selected.sourceIdentities[reference.path + "\0" + name].empty) + && selected.sourceIdentities[reference.path + "\0" + name].empty + )) .Select(name => (reference, name, path: selected.owners[name].path))) .GroupBy(static item => item.reference.target); foreach (var group in emptyForeign) { - string[] paths = group.Select(static item => item.path).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); - string[] references = group.Select(static item => item.reference.path).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); - string identity = ValidationInputs.Identity(group.Select(item => new KeyValuePair(item.path, - selected.sourceIdentities[item.reference.path + "\0" + item.name].identity))); - checks.Add(new("documentation-api:source:" + (group.Key ?? "default"), "documentation-api", "InnoEngine.Docs", - "Verify the recorded empty public surface from actual target-selected source; this does not certify foreign product execution.", - "any", ["documentation"], CapturedInputs(paths.SelectMany(path => byPath[path].inputs)).Append("@tooling").Order(StringComparer.Ordinal).ToArray(), - true, null, "managed", "contract", paths, new(references, [], identity, configuration, group.Key))); - } - foreach (var group in examplePages.GroupBy(page => scriptPages.Contains(page.id) - || (page.examples?.projects ?? []).Any(name => nativeOwners.Contains(selected.owners[name].path) - || nativeDocumentOwners.Contains(selected.owners[name].path)) ? "native" : "managed")) - { - string[] paths = group.SelectMany(static page => page.examples?.projects ?? []).Select(name => selected.owners[name].path) - .Distinct(StringComparer.Ordinal).ToArray(); - ValidationCheck[] required = builds.Where(check => paths.Contains(check.owner, StringComparer.Ordinal) - || group.Key == "native" && scriptExamples && check.owner is "entry/InnoEngine.Build/InnoEngine.Build.csproj" or "entry/InnoEngine.Editor/InnoEngine.Editor.csproj").ToArray(); + string[] paths = group + .Select(static item => item.path) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); + string[] references = group + .Select(static item => item.reference.path) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); + string identity = ValidationInputs.Identity( + group.Select(item => new KeyValuePair( + item.path, + selected.sourceIdentities[item.reference.path + "\0" + item.name].identity + )) + ); + checks.Add( + new( + "documentation-api:source:" + (group.Key ?? "default"), + "documentation-api", + "InnoEngine.Docs", + "Verify the recorded empty public surface from actual target-selected source; this does not certify foreign product execution.", + "any", + ["documentation"], + CapturedInputs(paths.SelectMany(path => byPath[path].inputs)) + .Append("@tooling") + .Order(StringComparer.Ordinal) + .ToArray(), + true, + null, + "managed", + "contract", + paths, + new(references, [], identity, configuration, group.Key) + ) + ); + } + foreach (var group in examplePages.GroupBy(page => ( + scriptPages.Contains(page.id) + || (page.examples?.projects ?? []).Any(name => ( + nativeOwners.Contains(selected.owners[name].path) + || nativeDocumentOwners.Contains(selected.owners[name].path) + )) ? "native" : "managed" + )) + ) { + string[] paths = group.SelectMany(static page => page.examples?.projects ?? []) + .Select(name => selected.owners[name].path) + .Distinct(StringComparer.Ordinal) + .ToArray(); + ValidationCheck[] required = builds.Where(check => ( + paths.Contains(check.owner, StringComparer.Ordinal) + || group.Key == "native" + && scriptExamples + && check.owner is "entry/InnoEngine.Build/InnoEngine.Build.csproj" or "entry/InnoEngine.Editor/InnoEngine.Editor.csproj" + )).ToArray(); string[] pages = group.Select(static page => page.id).Order(StringComparer.Ordinal).ToArray(); string[] scriptReferences = ValidationDocumentation.ExampleReferences(selected, group.ToArray()); - checks.Add(new("documentation-examples:" + group.Key, "documentation-examples", "InnoEngine.Docs", - "Canonical example blocks and their declared host or script context; no Markdown reparse or namespace guessing.", "any", - required.Select(static check => check.id).Append("documentation").ToArray(), - required.SelectMany(static check => check.inputs).Append("@tooling").Distinct(StringComparer.Ordinal).ToArray(), true, null, - group.Key, "contract", paths, new(scriptReferences, pages, ValidationDocumentation.ExampleIdentity(selected, group.ToArray(), scriptReferences), configuration, - group.Key == "native" ? target : null))); + checks.Add( + new( + "documentation-examples:" + group.Key, + "documentation-examples", + "InnoEngine.Docs", + "Canonical example blocks and their declared host or script context; no Markdown reparse or namespace guessing.", + "any", + required.Select(static check => check.id).Append("documentation").ToArray(), + required + .SelectMany(static check => check.inputs) + .Append("@tooling") + .Distinct(StringComparer.Ordinal) + .ToArray(), + true, + null, + group.Key, + "contract", + paths, + new( + scriptReferences, + pages, + ValidationDocumentation.ExampleIdentity(selected, group.ToArray(), scriptReferences), + configuration, + group.Key == "native" ? target : null + ) + ) + ); } } @@ -749,22 +1609,34 @@ void AddDocumentationChecks() string[] CapturedInputs(IEnumerable declared) { string[] paths = declared.ToArray(); - return paths.Where(inputs.ContainsKey).Concat(submoduleInputs.Where(parent => - paths.Any(path => path.StartsWith(parent + "/", StringComparison.Ordinal)))).Distinct(StringComparer.Ordinal).ToArray(); + return paths.Where(inputs.ContainsKey).Concat( + submoduleInputs.Where(parent => + paths.Any(path => path.StartsWith(parent + "/", StringComparison.Ordinal))) + ).Distinct(StringComparer.Ordinal).ToArray(); } void RequireCompilerInputs(JsonElement snapshot) { foreach (JsonElement project in snapshot.EnumerateArray()) + { foreach (JsonElement variant in project.GetProperty("Variants").EnumerateArray().Append(project)) + { foreach (JsonElement item in variant.GetProperty("Items").GetProperty("Compile").EnumerateArray()) { string path = Path.GetRelativePath(root, item.GetProperty("FullPath").GetString()!).Replace('\\', '/'); if (path.StartsWith("../", StringComparison.Ordinal) || Path.IsPathRooted(path) || inputs.ContainsKey(path) - || submoduleInputs.Any(parent => path.StartsWith(parent + "/", StringComparison.Ordinal))) + || submoduleInputs.Any(parent => path.StartsWith(parent + "/", StringComparison.Ordinal)) + ) { continue; + } if (File.Exists(ValidationInputs.Resolve(root, path))) - throw new InvalidDataException($"The SDK selected an untracked ignored compiler input: {path}. Make its source ownership explicit before validation."); + { + throw new InvalidDataException( + $"The SDK selected an untracked ignored compiler input: {path}. Make its source ownership explicit before validation." + ); + } + } + } } } @@ -781,11 +1653,12 @@ void RecordStage(string name) private static bool IsCiContractInput(string path) => path.StartsWith("tests/ci/", StringComparison.Ordinal) - || path.StartsWith("tests/fixtures/editor-ui/", StringComparison.Ordinal) - || path == "tests/Invoke-EditorUiProductJourney.ps1"; + || path.StartsWith("tests/fixtures/editor-ui/", StringComparison.Ordinal) + || path == "tests/Invoke-EditorUiProductJourney.ps1"; private static bool IsDocumentation(string path) => path.EndsWith(".md", StringComparison.OrdinalIgnoreCase) - || (path.StartsWith("docs/", StringComparison.Ordinal) || path.StartsWith(".agents/records/", StringComparison.Ordinal)) - && (Path.GetExtension(path) is ".json" or ".csv" or ".png" or ".jpg" or ".svg" || path.EndsWith(".cs.txt", StringComparison.Ordinal)); + || (path.StartsWith("docs/", StringComparison.Ordinal) || path.StartsWith(".agents/records/", StringComparison.Ordinal)) + && (Path.GetExtension(path) is ".json" or ".csv" or ".png" or ".jpg" or ".svg" + || path.EndsWith(".cs.txt", StringComparison.Ordinal)); } diff --git a/tools/Inno.Tooling.Validation/ValidationProcess.cs b/tools/Inno.Tooling.Validation/ValidationProcess.cs index d11e408dc..5459ef37c 100644 --- a/tools/Inno.Tooling.Validation/ValidationProcess.cs +++ b/tools/Inno.Tooling.Validation/ValidationProcess.cs @@ -32,17 +32,31 @@ internal static async Task RunAsync( StandardErrorEncoding = Encoding.UTF8 }; if (input is not null) + { start.StandardInputEncoding = new UTF8Encoding(false); + } foreach (string argument in arguments) + { start.ArgumentList.Add(argument); + } if (Path.GetFileNameWithoutExtension(executable).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) + { foreach (var pair in DotNetSdkEnvironment.Create(executable)) + { if (pair.Value is null) + { start.Environment.Remove(pair.Key); + } else + { start.Environment[pair.Key] = pair.Value; + } + } + } using TextWriter? writer = log is null ? null : TextWriter.Synchronized(new StreamWriter( - new FileStream(log, FileMode.CreateNew, FileAccess.Write, FileShare.Read), new UTF8Encoding(false)) { AutoFlush = true }); + new FileStream(log, FileMode.CreateNew, FileAccess.Write, FileShare.Read), + new UTF8Encoding(false) + ) { AutoFlush = true }); using var process = Process.Start(start) ?? throw new InvalidOperationException("Validation process did not start."); var elapsed = Stopwatch.StartNew(); long characters = 0; @@ -65,7 +79,9 @@ internal static async Task RunAsync( catch { if (!process.HasExited) + { process.Kill(entireProcessTree: true); + } await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false); throw; } @@ -82,19 +98,26 @@ internal static async Task RunAsync( } } if (log is not null) - Console.WriteLine($"Process exited: {Path.GetFileName(log)}; pid={process.Id}; exit={process.ExitCode}; elapsed={elapsed.Elapsed.TotalSeconds:F1}s."); + { + Console.WriteLine( + $"Process exited: {Path.GetFileName(log)}; pid={process.Id}; exit={process.ExitCode}; elapsed={elapsed.Elapsed.TotalSeconds:F1}s." + ); + } if (process.ExitCode != 0) { - string failure = log is null ? errors.Result + "\n" + output.Result - : $"Full process output: {log}\n{FailureExcerpt(errors.Result)}\n{FailureExcerpt(output.Result)}"; + string failure = log is null + ? errors.Result + "\n" + output.Result + : $"Full process output: {log}\n{FailureExcerpt(errors.Result)}\n{FailureExcerpt(output.Result)}"; throw new InvalidOperationException($"{executable} exited with {process.ExitCode}: {failure}"); } return output.Result; // A failed union is referenced by every affected owner. Preserve its full output once in the log, // while keeping receipts bounded and retaining both the first diagnostic and the final summary. - static string FailureExcerpt(string content) => content.Length <= 2048 ? content - : content[..1024] + "\n[Full output retained in the process log]\n" + content[^1024..]; + static string FailureExcerpt(string content) + => content.Length <= 2048 + ? content + : content[..1024] + "\n[Full output retained in the process log]\n" + content[^1024..]; async Task DrainAsync(StreamReader reader) { @@ -112,19 +135,25 @@ async Task DrainAsync(StreamReader reader) lastOutput = Stopwatch.GetTimestamp(); var tail = new StringBuilder(Math.Min(count, 200)); for (int index = Math.Max(0, count - 200); index < count; index++) + { tail.Append(char.IsControl(buffer[index]) ? ' ' : buffer[index]); + } excerpt = tail.ToString().Trim(); } } if (writer is not null) + { await writer.WriteAsync(buffer.AsMemory(0, count), CancellationToken.None).ConfigureAwait(false); + } } return content.ToString(); } async Task ReportProgressAsync() { - Console.WriteLine($"Process started: {Path.GetFileName(log)}; executable={Path.GetFileName(executable)}; pid={process.Id}; log={log}."); + Console.WriteLine( + $"Process started: {Path.GetFileName(log)}; executable={Path.GetFileName(executable)}; pid={process.Id}; log={log}." + ); using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30)); try { @@ -139,14 +168,17 @@ async Task ReportProgressAsync() try { process.Refresh(); - cpu = process.TotalProcessorTime.TotalSeconds.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) + "s"; + cpu = process.TotalProcessorTime.TotalSeconds.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) + + "s"; } catch (Exception failure) when (failure is InvalidOperationException or Win32Exception or NotSupportedException) { cpu = "unavailable"; } // A quiet parent may be waiting for active children. Activity is diagnostic, never a completion deadline. - Console.WriteLine($"Process active: {Path.GetFileName(log)}; pid={process.Id}; elapsed={elapsed.Elapsed.TotalSeconds:F1}s; parentCpu={cpu}; {activity}"); + Console.WriteLine( + $"Process active: {Path.GetFileName(log)}; pid={process.Id}; elapsed={elapsed.Elapsed.TotalSeconds:F1}s; parentCpu={cpu}; {activity}" + ); } } catch (OperationCanceledException) when (progressStop.IsCancellationRequested) { } diff --git a/tools/Inno.Tooling.Validation/ValidationProductInput.cs b/tools/Inno.Tooling.Validation/ValidationProductInput.cs index 2b049b271..aed34a9ec 100644 --- a/tools/Inno.Tooling.Validation/ValidationProductInput.cs +++ b/tools/Inno.Tooling.Validation/ValidationProductInput.cs @@ -18,30 +18,58 @@ internal static async Task PrepareAsync( string project, CancellationToken cancellation ) { - using JsonDocument document = JsonDocument.Parse(await File.ReadAllTextAsync( - Path.Combine(plan.root, "tests", "fixtures", "editor-ui", "consumer.json"), cancellation).ConfigureAwait(false)); + using JsonDocument document = JsonDocument.Parse( + await File.ReadAllTextAsync( + Path.Combine(plan.root, "tests", "fixtures", "editor-ui", "consumer.json"), + cancellation + ).ConfigureAwait(false) + ); string repository = document.RootElement.GetProperty("repository").GetString()!; string commit = document.RootElement.GetProperty("commit").GetString()!; string prefix = document.RootElement.GetProperty("project").GetString()!.TrimEnd('/') + "/"; if (!Uri.TryCreate(repository, UriKind.Absolute, out Uri? source) || source.Scheme != "https" - || source.Host != "github.com" || !System.Text.RegularExpressions.Regex.IsMatch(commit, "\\A[0-9a-f]{40}\\z")) + || source.Host != "github.com" || !System.Text.RegularExpressions.Regex.IsMatch(commit, "\\A[0-9a-f]{40}\\z") + ) { throw new InvalidDataException("The product consumer must declare an exact HTTPS repository revision."); - if (prefix.StartsWith('/') || prefix.Contains('\\') || Array.Exists(prefix.TrimEnd('/').Split('/'), - static segment => segment.Length == 0 || segment is "." or "..")) + } + if (prefix.StartsWith('/') || prefix.Contains('\\') || Array.Exists( + prefix.TrimEnd('/').Split('/'), + static segment => segment.Length == 0 || segment is "." or ".." + )) { throw new InvalidDataException("The consumer project must declare a relative repository directory."); + } // The validation workspace already owns the exclusive lease. Logs never determine dependency-cache identity. string identity = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(repository + "\n" + commit))); string checkout = PathBoundary.RequireUnlinkedPath(plan.artifacts, Path.Combine(plan.artifacts, "consumer-inputs", identity)); if (Directory.Exists(checkout)) { - string origin = await ValidationProcess.RunAsync("git", ["-C", checkout, "remote", "get-url", "origin"], plan.root, null, cancellation).ConfigureAwait(false); - string bare = await ValidationProcess.RunAsync("git", ["-C", checkout, "rev-parse", "--is-bare-repository"], plan.root, null, cancellation).ConfigureAwait(false); + string origin = await ValidationProcess.RunAsync( + "git", + ["-C", checkout, "remote", "get-url", "origin"], + plan.root, + null, + cancellation + ).ConfigureAwait(false); + string bare = await ValidationProcess.RunAsync( + "git", + ["-C", checkout, "rev-parse", "--is-bare-repository"], + plan.root, + null, + cancellation + ).ConfigureAwait(false); if (origin.Trim() != repository || bare.Trim() != "true") + { throw new InvalidDataException("The consumer dependency cache has a different repository or storage owner."); + } try { - await ValidationProcess.RunAsync("git", ["-C", checkout, "fsck", "--full", "--strict"], plan.root, - Path.Combine(directory, "consumer-integrity.log"), cancellation).ConfigureAwait(false); + await ValidationProcess.RunAsync( + "git", + ["-C", checkout, "fsck", "--full", "--strict"], + plan.root, + Path.Combine(directory, "consumer-integrity.log"), + cancellation + ).ConfigureAwait(false); } catch (InvalidOperationException) { @@ -53,11 +81,27 @@ await ValidationProcess.RunAsync("git", ["-C", checkout, "fsck", "--full", "--st if (!Directory.Exists(checkout)) { string staging = PathBoundary.RequireUnlinkedPath(plan.artifacts, checkout + ".staging-" + Guid.NewGuid().ToString("N")); - await ValidationProcess.RunAsync("git", ["-c", "core.longpaths=true", "init", "--bare", staging], plan.root, - Path.Combine(directory, "consumer-initialize.log"), cancellation).ConfigureAwait(false); - await ValidationProcess.RunAsync("git", ["-c", "core.longpaths=true", "-C", staging, "config", "core.longpaths", "true"], - plan.root, null, cancellation).ConfigureAwait(false); - await ValidationProcess.RunAsync("git", ["-C", staging, "remote", "add", "origin", repository], plan.root, null, cancellation).ConfigureAwait(false); + await ValidationProcess.RunAsync( + "git", + ["-c", "core.longpaths=true", "init", "--bare", staging], + plan.root, + Path.Combine(directory, "consumer-initialize.log"), + cancellation + ).ConfigureAwait(false); + await ValidationProcess.RunAsync( + "git", + ["-c", "core.longpaths=true", "-C", staging, "config", "core.longpaths", "true"], + plan.root, + null, + cancellation + ).ConfigureAwait(false); + await ValidationProcess.RunAsync( + "git", + ["-C", staging, "remote", "add", "origin", repository], + plan.root, + null, + cancellation + ).ConfigureAwait(false); cancellation.ThrowIfCancellationRequested(); Directory.Move(staging, checkout); } @@ -67,45 +111,94 @@ await ValidationProcess.RunAsync("git", ["-c", "core.longpaths=true", "-C", stag string adjacent = Path.Combine(Path.GetDirectoryName(plan.root)!, Path.GetFileNameWithoutExtension(source.AbsolutePath)); if (Directory.Exists(Path.Combine(adjacent, ".git")) || File.Exists(Path.Combine(adjacent, ".git"))) { - string origin = await ValidationProcess.RunAsync("git", ["-C", adjacent, "remote", "get-url", "origin"], plan.root, null, cancellation).ConfigureAwait(false); - if (origin.Trim().Equals(repository, StringComparison.OrdinalIgnoreCase) && await HasCommitAsync(adjacent).ConfigureAwait(false)) + string origin = await ValidationProcess.RunAsync( + "git", + ["-C", adjacent, "remote", "get-url", "origin"], + plan.root, + null, + cancellation + ).ConfigureAwait(false); + if (origin.Trim().Equals(repository, StringComparison.OrdinalIgnoreCase) + && await HasCommitAsync(adjacent).ConfigureAwait(false) + ) { input = adjacent; + } } Console.WriteLine($"Importing exact consumer commit {commit} from {input}; no consumer working-tree files are read."); - await File.WriteAllTextAsync(Path.Combine(directory, "consumer-source.json"), - JsonSerializer.Serialize(new { repository, commit, source = input }), cancellation).ConfigureAwait(false); - await ValidationProcess.RunAsync("git", ["-C", checkout, "fetch", "--no-tags", "--depth=1", input, commit], plan.root, - Path.Combine(directory, "consumer-fetch.log"), cancellation).ConfigureAwait(false); - await ValidationProcess.RunAsync("git", ["-C", checkout, "fsck", "--full", "--strict"], plan.root, - Path.Combine(directory, "consumer-import-integrity.log"), cancellation).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(directory, "consumer-source.json"), + JsonSerializer.Serialize(new { repository, commit, source = input }), + cancellation + ).ConfigureAwait(false); + await ValidationProcess.RunAsync( + "git", + ["-C", checkout, "fetch", "--no-tags", "--depth=1", input, commit], + plan.root, + Path.Combine(directory, "consumer-fetch.log"), + cancellation + ).ConfigureAwait(false); + await ValidationProcess.RunAsync( + "git", + ["-C", checkout, "fsck", "--full", "--strict"], + plan.root, + Path.Combine(directory, "consumer-import-integrity.log"), + cancellation + ).ConfigureAwait(false); } - string revision = await ValidationProcess.RunAsync("git", ["-C", checkout, "rev-parse", commit + "^{commit}"], plan.root, null, cancellation).ConfigureAwait(false); + string revision = await ValidationProcess.RunAsync( + "git", + ["-C", checkout, "rev-parse", commit + "^{commit}"], + plan.root, + null, + cancellation + ).ConfigureAwait(false); if (revision.Trim() != commit) + { throw new InvalidDataException("The consumer object does not match its declared revision."); + } string archive = Path.Combine(directory, "consumer-source.zip"); - await ValidationProcess.RunAsync("git", ["-C", checkout, "archive", "--format=zip", "--output=" + archive, commit, "--", prefix], - plan.root, Path.Combine(directory, "consumer-archive.log"), cancellation).ConfigureAwait(false); + await ValidationProcess.RunAsync( + "git", + ["-C", checkout, "archive", "--format=zip", "--output=" + archive, commit, "--", prefix], + plan.root, + Path.Combine(directory, "consumer-archive.log"), + cancellation + ).ConfigureAwait(false); using ZipArchive contents = ZipFile.OpenRead(archive); foreach (ZipArchiveEntry entry in contents.Entries) { cancellation.ThrowIfCancellationRequested(); string file = entry.FullName; - if (!file.StartsWith(prefix, StringComparison.Ordinal) || file.Contains('\\') || ((entry.ExternalAttributes >> 16) & 0xF000) == 0xA000) + if (!file.StartsWith(prefix, StringComparison.Ordinal) + || file.Contains('\\') + || ((entry.ExternalAttributes >> 16) & 0xF000) == 0xA000 + ) { throw new InvalidDataException("The consumer project selection escaped its declared prefix."); + } if (file.EndsWith('/')) + { continue; + } string destination = PathBoundary.RequireUnlinkedPath(project, ValidationInputs.Resolve(project, file[prefix.Length..])); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); entry.ExtractToFile(destination, overwrite: false); } if (!File.Exists(Path.Combine(project, "Assets", "FlappyBird", "FlappyBird.iscene"))) + { throw new InvalidDataException("The declared product consumer does not supply the required real scene."); + } async Task HasCommitAsync(string input) { try { - await ValidationProcess.RunAsync("git", ["-C", input, "cat-file", "-e", commit + "^{commit}"], plan.root, null, cancellation).ConfigureAwait(false); + await ValidationProcess.RunAsync( + "git", + ["-C", input, "cat-file", "-e", commit + "^{commit}"], + plan.root, + null, + cancellation + ).ConfigureAwait(false); return true; } catch (InvalidOperationException) diff --git a/tools/Inno.Tooling.Validation/ValidationProfile.cs b/tools/Inno.Tooling.Validation/ValidationProfile.cs index d804dc00e..586d37f3c 100644 --- a/tools/Inno.Tooling.Validation/ValidationProfile.cs +++ b/tools/Inno.Tooling.Validation/ValidationProfile.cs @@ -1,6 +1,7 @@ using System; namespace Inno.Tooling.Validation; + internal enum ValidationProfile { Fast, @@ -13,7 +14,8 @@ internal enum ValidationProfile internal static class ValidationProfiles { - internal static ValidationProfile Parse(string value) => value switch + internal static ValidationProfile Parse(string value) + => value switch { "fast" => ValidationProfile.Fast, "pull-request" => ValidationProfile.PullRequest, @@ -21,5 +23,6 @@ internal static class ValidationProfiles "full" => ValidationProfile.Full, "performance" => ValidationProfile.Performance, "native-producer" => ValidationProfile.NativeProducer, - _ => throw new ArgumentException("Unknown validation profile: " + value)}; + _ => throw new ArgumentException("Unknown validation profile: " + value) + }; } diff --git a/tools/Inno.Tooling.Validation/ValidationProject.cs b/tools/Inno.Tooling.Validation/ValidationProject.cs index fa9e529da..74909cec1 100644 --- a/tools/Inno.Tooling.Validation/ValidationProject.cs +++ b/tools/Inno.Tooling.Validation/ValidationProject.cs @@ -29,48 +29,71 @@ internal static ValidationProject Read( string Relative(string path) => Path.GetRelativePath(root, path).Replace('\\', '/'); string path = Relative(snapshot.GetProperty("Path").GetString()!); if (Value("IsTestProject").Equals("true", StringComparison.OrdinalIgnoreCase) - && Value("InnoValidationLayer") == "native" && string.IsNullOrWhiteSpace(Value("InnoTestNativeProduct"))) + && Value("InnoValidationLayer") == "native" && string.IsNullOrWhiteSpace(Value("InnoTestNativeProduct")) + ) { throw new InvalidDataException($"Native test owner must declare its product deployment: {path}"); + } var inputs = new HashSet(StringComparer.Ordinal) { path }; var references = new HashSet(StringComparer.Ordinal); bool native = false; - IEnumerable variants = selectedVariant is JsonElement selected ? [selected] : snapshot.GetProperty("Variants").EnumerateArray().Append(snapshot); + IEnumerable variants = selectedVariant is JsonElement selected + ? [selected] + : snapshot.GetProperty("Variants").EnumerateArray().Append(snapshot); foreach (JsonElement variant in variants) { string? variantTarget = variant.GetProperty("Properties").GetProperty("InnoNativeTarget").GetString(); if (backendTarget is not null && !string.IsNullOrEmpty(variantTarget) && variantTarget != backendTarget) + { continue; + } foreach (JsonElement import in variant.GetProperty("Imports").EnumerateArray()) + { inputs.Add(Relative(import.GetString()!)); + } foreach (JsonProperty group in variant.GetProperty("Items").EnumerateObject()) { if (group.Name is "PackageReference" or "Using" or "InnoNativeDependency") + { continue; + } foreach (JsonElement item in group.Value.EnumerateArray()) + { if (item.TryGetProperty("FullPath", out JsonElement fullPath) && !string.IsNullOrEmpty(fullPath.GetString())) { string file = Relative(fullPath.GetString()!); // The SDK lists adjacent build definitions as None even when this variant never imports them. // Copied or otherwise declared items and actual imports retain their own input edges. if ((backendTarget is not null || selectedVariant.HasValue) && group.Name == "None" - && (file.EndsWith(".props", StringComparison.OrdinalIgnoreCase) || file.EndsWith(".targets", StringComparison.OrdinalIgnoreCase)) - && item.EnumerateObject().All(static property => property.Name is "Identity" or "FullPath")) + && (file.EndsWith(".props", StringComparison.OrdinalIgnoreCase) + || file.EndsWith(".targets", StringComparison.OrdinalIgnoreCase)) + && item.EnumerateObject().All(static property => property.Name is "Identity" or "FullPath") + ) { continue; + } inputs.Add(file); if (group.Name == "ProjectReference") + { references.Add(file); + } } + } } JsonElement effective = variant.GetProperty("Properties"); native |= !string.IsNullOrEmpty(effective.GetProperty("InnoTestNativeProduct").GetString()) - || !string.IsNullOrEmpty(effective.GetProperty("InnoProductId").GetString()) - || variant.GetProperty("Items").GetProperty("InnoNativeDependency").GetArrayLength() != 0; + || !string.IsNullOrEmpty(effective.GetProperty("InnoProductId").GetString()) + || variant.GetProperty("Items").GetProperty("InnoNativeDependency").GetArrayLength() != 0; } - return new(path, references.Order(StringComparer.Ordinal).ToArray(), - inputs.Order(StringComparer.Ordinal).ToArray(), Value("InnoValidationLayer"), Value("InnoValidationEnvironment"), + return new( + path, + references.Order(StringComparer.Ordinal).ToArray(), + inputs.Order(StringComparer.Ordinal).ToArray(), + Value("InnoValidationLayer"), + Value("InnoValidationEnvironment"), Value("IsTestProject").Equals("true", StringComparison.OrdinalIgnoreCase), native, - !Value("InnoValidationReusable").Equals("false", StringComparison.OrdinalIgnoreCase), Value("InnoProductTarget"), - Value("InnoValidationRequiresNativeProducer").Equals("true", StringComparison.OrdinalIgnoreCase)); + !Value("InnoValidationReusable").Equals("false", StringComparison.OrdinalIgnoreCase), + Value("InnoProductTarget"), + Value("InnoValidationRequiresNativeProducer").Equals("true", StringComparison.OrdinalIgnoreCase) + ); } } diff --git a/tools/Inno.Tooling.Validation/ValidationRunner.cs b/tools/Inno.Tooling.Validation/ValidationRunner.cs index 69a043f21..704104a30 100644 --- a/tools/Inno.Tooling.Validation/ValidationRunner.cs +++ b/tools/Inno.Tooling.Validation/ValidationRunner.cs @@ -30,10 +30,15 @@ internal static async Task RunAsync( HashSet? selectedChecks = shard?.checks.ToHashSet(StringComparer.Ordinal); ValidationCheck[] checks = plan.checks.Where(check => selectedChecks is null || selectedChecks.Contains(check.id)).ToArray(); ValidationResult[] imported = shard is null ? [] : ValidationShards.Prerequisites(plan, shard, prerequisites ?? []); - using DocumentationSnapshot? documentationSnapshot = plan.documentation is null ? null - : await DocumentationStore.OpenAsync(plan.documentation.cacheRoot, plan.documentation.snapshot, - cancellationToken: cancellation).ConfigureAwait(false); - DocumentationCatalogReport? documentationCatalog = documentationSnapshot is null ? null + using DocumentationSnapshot? documentationSnapshot = plan.documentation is null + ? null + : await DocumentationStore.OpenAsync( + plan.documentation.cacheRoot, + plan.documentation.snapshot, + cancellationToken: cancellation + ).ConfigureAwait(false); + DocumentationCatalogReport? documentationCatalog = documentationSnapshot is null + ? null : await ValidationDocumentation.ReadCatalogAsync(plan, documentationSnapshot, cancellation).ConfigureAwait(false); var results = new List(imported); var failures = new List(); @@ -42,38 +47,69 @@ internal static async Task RunAsync( DateTimeOffset started = DateTimeOffset.UtcNow; string planIdentity = ValidationInputs.PlanIdentity(plan); Directory.CreateDirectory(directory); - await File.WriteAllTextAsync(Path.Combine(directory, "execution-plan.json"), JsonSerializer.Serialize(plan, - new JsonSerializerOptions { WriteIndented = true }), cancellation).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(directory, "execution-plan.json"), + JsonSerializer.Serialize(plan, new JsonSerializerOptions { WriteIndented = true }), + cancellation + ).ConfigureAwait(false); Console.WriteLine("Validation phase: acquire the selected workspace ownership and freeze current inputs."); using var workspace = checks.Any(static check => check.kind == "build" && check.exclusion is null) - ? await ValidationWorkspace.AcquireAsync(plan, cancellation).ConfigureAwait(false) : null; + ? await ValidationWorkspace.AcquireAsync(plan, cancellation).ConfigureAwait(false) + : null; if (retainedOutputs is not null) { if (!continuation || workspace is null) + { throw new InvalidDataException("Restoring compilation outputs requires a continuation with workspace ownership."); + } ValidationWorkspace.RestoreOutputs(plan, retainedOutputs, cancellation); } foreach (var context in plan.contexts) - await File.WriteAllTextAsync(Path.Combine(directory, context.Key + "-sdk-graph.json"), context.Value.sdkGraph.GetRawText(), cancellation).ConfigureAwait(false); + { + await File.WriteAllTextAsync( + Path.Combine(directory, context.Key + "-sdk-graph.json"), + context.Value.sdkGraph.GetRawText(), + cancellation + ).ConfigureAwait(false); + } Dictionary current = await ValidationInputs.CaptureAsync(plan.root, cancellation).ConfigureAwait(false); if (ValidationInputs.Identity(current) != plan.tree) { - string[] changed = current.Keys.Union(plan.inputs.Keys).Where(path => !path.StartsWith('@') - && current.GetValueOrDefault(path) != plan.inputs.GetValueOrDefault(path)).Order(StringComparer.Ordinal).Take(8).ToArray(); - throw new InvalidDataException("Validation plan inputs changed before execution. Generate a new plan. Changed inputs: " + string.Join(", ", changed)); + string[] changed = current.Keys.Union(plan.inputs.Keys).Where(path => ( + !path.StartsWith('@') + && current.GetValueOrDefault(path) != plan.inputs.GetValueOrDefault(path) + )).Order(StringComparer.Ordinal).Take(8).ToArray(); + throw new InvalidDataException( + "Validation plan inputs changed before execution. Generate a new plan. Changed inputs: " + string.Join(", ", changed) + ); } var buildSolutions = checks.Where(static check => check.kind == "build" && check.exclusion is null) - .GroupBy(static check => check.context!, StringComparer.Ordinal).ToDictionary(static group => group.Key, - group => WriteUnion(group.Key, "Build", group.Select(static check => check.owner).ToArray()), StringComparer.Ordinal); + .GroupBy(static check => check.context!, StringComparer.Ordinal) + .ToDictionary( + static group => group.Key, + group => WriteUnion(group.Key, "Build", group.Select(static check => check.owner).ToArray()), + StringComparer.Ordinal + ); if (retainedOutputs is not null) { // Restore rebinds SDK-generated absolute paths to this runner and obtains the exact // packages before comparing dependency identities. It does not compile the union. foreach (var solution in buildSolutions) - await ValidationProcess.RunAsync(plan.dotnet, ["restore", solution.Value, - ..plan.contexts[solution.Key].properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value), - "--disable-parallel", "-nr:false"], plan.root, - Path.Combine(directory, solution.Key + "-restore-retained.log"), cancellation).ConfigureAwait(false); + { + await ValidationProcess.RunAsync( + plan.dotnet, + [ + "restore", + solution.Value, + ..plan.contexts[solution.Key].properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value), + "--disable-parallel", + "-nr:false" + ], + plan.root, + Path.Combine(directory, solution.Key + "-restore-retained.log"), + cancellation + ).ConfigureAwait(false); + } } var built = new HashSet(StringComparer.Ordinal); var tested = new HashSet(StringComparer.Ordinal); @@ -110,13 +146,20 @@ await ValidationProcess.RunAsync(plan.dotnet, ["restore", solution.Value, status = "Blocked"; detail = "Validation was canceled before this required check completed."; } - else if (check.prerequisites.Any(prerequisite => !results.Any(result => result.id == prerequisite && result.status is "Passed" or "Reused"))) - { + else if (check.prerequisites.Any( + prerequisite => !results.Any(result => result.id == prerequisite && result.status is "Passed" or "Reused") + )) { status = "Blocked"; - detail = "Required prerequisites did not pass: " + string.Join(", ", check.prerequisites - .Select(prerequisite => (id: prerequisite, status: results.SingleOrDefault(result => result.id == prerequisite)?.status ?? "Missing")) - .Where(static prerequisite => prerequisite.status is not ("Passed" or "Reused")) - .Select(static prerequisite => prerequisite.id + " (" + prerequisite.status + ")")) + ". Dependent work was not executed."; + detail = "Required prerequisites did not pass: " + string.Join( + ", ", + check.prerequisites + .Select(prerequisite => ( + id: prerequisite, + status: results.SingleOrDefault(result => result.id == prerequisite)?.status ?? "Missing" + )) + .Where(static prerequisite => prerequisite.status is not ("Passed" or "Reused")) + .Select(static prerequisite => prerequisite.id + " (" + prerequisite.status + ")") + ) + ". Dependent work was not executed."; } else if (CanReuse(check)) { @@ -129,7 +172,9 @@ await ValidationProcess.RunAsync(plan.dotnet, ["restore", solution.Value, dependencyIdentity = old.dependencyIdentity; documentationInputs = old.documentationInputs; if (check.kind == "build") + { built.Add(contextId); + } } else { @@ -145,13 +190,26 @@ await ValidationProcess.RunAsync(plan.dotnet, ["restore", solution.Value, { string path = Path.Combine(plan.root, cache); if (Directory.Exists(path) && Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).Any()) - throw new InvalidDataException($"Cold validation requires a fresh checkout/cache owner; existing artifacts cannot be relabeled cold: {path}"); + { + throw new InvalidDataException( + $"Cold validation requires a fresh checkout/cache owner; existing artifacts cannot be relabeled cold: {path}" + ); + } } break; case "hot-builds": - await ShellAsync("tests/Invoke-BuildCacheChecks.ps1", ["-Dotnet", plan.dotnet, - "-PlanPath", Path.Combine(directory, "execution-plan.json"), "-Context", contextId, - "-ResultsDirectory", Path.Combine(directory, "hot-builds"), "-Iterations", "10"], "hot-builds.log").ConfigureAwait(false); + await ShellAsync("tests/Invoke-BuildCacheChecks.ps1", [ + "-Dotnet", + plan.dotnet, + "-PlanPath", + Path.Combine(directory, "execution-plan.json"), + "-Context", + contextId, + "-ResultsDirectory", + Path.Combine(directory, "hot-builds"), + "-Iterations", + "10" + ], "hot-builds.log").ConfigureAwait(false); break; case "instructions": await ShellAsync(ValidationCiContracts.C_RULE_LOADER, [], "instructions.log").ConfigureAwait(false); @@ -162,27 +220,62 @@ await ShellAsync("tests/Invoke-BuildCacheChecks.ps1", ["-Dotnet", plan.dotnet, ? ValidationCiContracts.GateContracts.Select(path => Path.Combine(plan.root, path)).ToArray() : ValidationCiContracts.Discover(plan.root); if (contracts.Length == 0) + { throw new InvalidDataException("Required CI contract discovery is empty."); + } foreach (string contract in contracts) - await ShellAsync(Path.GetRelativePath(plan.root, contract), [], Path.GetFileNameWithoutExtension(contract) + ".log").ConfigureAwait(false); + { + await ShellAsync( + Path.GetRelativePath(plan.root, contract), + [], + Path.GetFileNameWithoutExtension(contract) + ".log" + ).ConfigureAwait(false); + } break; case "restore-aot": { - JsonElement player = plan.contexts[contextId].sdkGraph.EnumerateArray().Single(snapshot => - Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == check.owner); + JsonElement player = plan.contexts[contextId].sdkGraph.EnumerateArray().Single(snapshot => ( + Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!) + .Replace('\\', '/') == check.owner + )); string runtime = player.GetProperty("Properties").GetProperty("NETCoreSdkRuntimeIdentifier").GetString()!; if (string.IsNullOrWhiteSpace(runtime)) + { throw new InvalidDataException("Host NativeAOT restore requires the evaluated SDK runtime identifier."); - await ValidationProcess.RunAsync(plan.dotnet, ["restore", Path.Combine(plan.root, check.owner), - "--runtime", runtime, "-p:Configuration=Release", "-p:PublishAot=true", - "-p:ArtifactsPath=" + Path.Combine(plan.artifacts, "restore", "native-aot"), - "--disable-parallel", "-nr:false"], plan.root, Path.Combine(directory, "native-aot-restore.log"), cancellation).ConfigureAwait(false); + } + await ValidationProcess.RunAsync( + plan.dotnet, + [ + "restore", + Path.Combine(plan.root, check.owner), + "--runtime", + runtime, + "-p:Configuration=Release", + "-p:PublishAot=true", + "-p:ArtifactsPath=" + Path.Combine(plan.artifacts, "restore", "native-aot"), + "--disable-parallel", + "-nr:false" + ], + plan.root, + Path.Combine(directory, "native-aot-restore.log"), + cancellation + ).ConfigureAwait(false); } break; case "architecture": - if (ArchitectureValidator.Execute([plan.root, "--configuration", plan.configuration, "--source-only", - "--dotnet", plan.dotnet, "--sdk-snapshot", graphPath], cancellation) != 0) + if (ArchitectureValidator.Execute([ + plan.root, + "--configuration", + plan.configuration, + "--source-only", + "--dotnet", + plan.dotnet, + "--sdk-snapshot", + graphPath + ], cancellation) != 0 + ) { throw new InvalidDataException("Repository architecture validation failed."); + } break; case "api": if (!built.Contains(contextId)) @@ -192,12 +285,26 @@ await ValidationProcess.RunAsync(plan.dotnet, ["restore", Path.Combine(plan.root break; } if (check.projects is not { Length: > 0 }) + { throw new InvalidDataException("Required compiled API owner selection is empty."); + } string[] projects = check.projects.SelectMany(static project => new[] { "--api-project", project }).ToArray(); - if (ArchitectureValidator.Execute([plan.root, "--metadata-only", "--configuration", plan.contexts[contextId].properties["Configuration"], - "--dotnet", plan.dotnet, "--artifacts-path", plan.contexts[contextId].properties["ArtifactsPath"], - "--sdk-snapshot", await ResolveCompilationGraphAsync(contextId).ConfigureAwait(false), ..projects], cancellation) != 0) + if (ArchitectureValidator.Execute([ + plan.root, + "--metadata-only", + "--configuration", + plan.contexts[contextId].properties["Configuration"], + "--dotnet", + plan.dotnet, + "--artifacts-path", + plan.contexts[contextId].properties["ArtifactsPath"], + "--sdk-snapshot", + await ResolveCompilationGraphAsync(contextId).ConfigureAwait(false), + ..projects + ], cancellation) != 0 + ) { throw new InvalidDataException("Affected compiled API boundaries failed."); + } break; case "documentation-missing": status = "Blocked"; @@ -206,159 +313,374 @@ await ValidationProcess.RunAsync(plan.dotnet, ["restore", Path.Combine(plan.root { string captureDirectory = Path.Combine(directory, "documentation-captures"); Directory.CreateDirectory(captureDirectory); - string capturePath = Path.Combine(captureDirectory, Path.GetFileNameWithoutExtension(check.owner) + ".json"); - string[] captureTarget = check.documentation.target is string selectedTarget ? ["--target", selectedTarget] : []; - DocumentationReferences.ExportApi(["--engine-root", plan.root, "--dotnet", plan.dotnet, - "--configuration", check.documentation.configuration, - "--artifacts-path", plan.contexts[contextId].properties["ArtifactsPath"], - "--sdk-snapshot", await ResolveCompilationGraphAsync(contextId).ConfigureAwait(false), - "--output", capturePath, ..captureTarget, - ..captureOwners.SelectMany(static owner => new[] { "--project", owner })], cancellation); + string capturePath = Path.Combine( + captureDirectory, + Path.GetFileNameWithoutExtension(check.owner) + ".json" + ); + string[] captureTarget = check.documentation.target is string selectedTarget + ? ["--target", selectedTarget] + : []; + DocumentationReferences.ExportApi([ + "--engine-root", + plan.root, + "--dotnet", + plan.dotnet, + "--configuration", + check.documentation.configuration, + "--artifacts-path", + plan.contexts[contextId].properties["ArtifactsPath"], + "--sdk-snapshot", + await ResolveCompilationGraphAsync(contextId).ConfigureAwait(false), + "--output", + capturePath, + ..captureTarget, + ..captureOwners.SelectMany(static owner => new[] { "--project", owner }) + ], cancellation); detail += " Unverified source facts retained at " + capturePath + "; review and compare the resulting documentation in a subsequent validation."; } break; case "documentation": if (documentationSnapshot is null) + { throw new InvalidDataException("Required external documentation snapshot is unavailable."); + } documentationCatalog ??= await documentationSnapshot.ExportCatalogAsync(cancellation).ConfigureAwait(false); string[] missing = plan.inputSets.Keys.Where(static path => path.EndsWith(".csproj", StringComparison.Ordinal)) // Platform implementations remain source provenance, not reader-facing documentation owners. .Where(static path => !path.StartsWith("platforms/", StringComparison.Ordinal)) .Select(static path => Path.GetFileNameWithoutExtension(path)) - .Where(name => !documentationCatalog.projects.TryGetValue(name, out string? entry) || entry is null).ToArray(); + .Where(name => !documentationCatalog.projects.TryGetValue(name, out string? entry) || entry is null) + .ToArray(); if (missing.Length != 0) - throw new InvalidDataException("Required canonical project entries are missing: " + string.Join(", ", missing)); + { + throw new InvalidDataException( + "Required canonical project entries are missing: " + string.Join(", ", missing) + ); + } if (documentationCatalog.contentIdentity != check.documentation!.contentIdentity) + { throw new InvalidDataException("Documentation content does not match the frozen plan."); + } break; case "documentation-api": ValidationDocumentationCheck referenceCheck = check.documentation ?? throw new InvalidDataException("Required reference selection is absent."); if (plan.documentation is null || check.projects is not { Length: > 0 }) + { throw new InvalidDataException("Required source reference discovery is empty."); + } string[] referenceArguments = referenceCheck.references.SelectMany(static path => new[] { "--reference", path }) - .Concat(check.projects.SelectMany(static project => new[] { "--project", project })).ToArray(); - if (await DocumentationReferences.ValidateApiAsync(["--engine-root", plan.root, "--dotnet", plan.dotnet, - "--cache-root", plan.documentation.cacheRoot, "--snapshot", plan.documentation.snapshot, - "--artifacts-path", plan.contexts[contextId].properties["ArtifactsPath"], - "--sdk-snapshot", await ResolveCompilationGraphAsync(contextId).ConfigureAwait(false), - "--output", Path.Combine(directory, check.id.Replace(':', '-') + ".json"), ..referenceArguments], cancellation).ConfigureAwait(false) != 0) + .Concat(check.projects.SelectMany(static project => new[] { "--project", project })) + .ToArray(); + if (await DocumentationReferences.ValidateApiAsync([ + "--engine-root", + plan.root, + "--dotnet", + plan.dotnet, + "--cache-root", + plan.documentation.cacheRoot, + "--snapshot", + plan.documentation.snapshot, + "--artifacts-path", + plan.contexts[contextId].properties["ArtifactsPath"], + "--sdk-snapshot", + await ResolveCompilationGraphAsync(contextId).ConfigureAwait(false), + "--output", + Path.Combine(directory, check.id.Replace(':', '-') + ".json"), + ..referenceArguments + ], cancellation).ConfigureAwait(false) + != 0 + ) { throw new InvalidDataException("Selected documentation source references differ from current source."); + } break; case "agent-documents": if (ArchitectureValidator.Execute([plan.root, "--agent-documents-only"], cancellation) != 0) + { throw new InvalidDataException("Agent document structure or links failed."); + } break; case "documentation-examples": if (documentationSnapshot is null || check.documentation is null || check.documentation.pages.Length == 0) + { throw new InvalidDataException("Required canonical example discovery is empty."); + } documentationCatalog ??= await documentationSnapshot.ExportCatalogAsync(cancellation).ConfigureAwait(false); string[] pages = check.documentation.pages.SelectMany(static page => new[] { "--page", page }).ToArray(); var scriptArguments = new List(); - if (documentationCatalog.pages.Any(page => check.documentation.pages.Contains(page.id, StringComparer.Ordinal) - && page.examples?.mode is "runtime-script" or "editor-script")) - { - string entryContext = checks.Single(candidate => candidate.kind == "build" + if (documentationCatalog.pages.Any(page => ( + check.documentation.pages.Contains(page.id, StringComparer.Ordinal) + && page.examples?.mode is "runtime-script" or "editor-script" + )) + ) { + string entryContext = checks.Single(candidate => ( + candidate.kind == "build" && candidate.owner == "entry/InnoEngine.Build/InnoEngine.Build.csproj" - && check.prerequisites.Contains(candidate.id, StringComparer.Ordinal)).context!; + && check.prerequisites.Contains(candidate.id, StringComparer.Ordinal) + )).context!; JsonElement snapshot = plan.contexts[entryContext].sdkGraph; - string entry = snapshot.EnumerateArray().Single(node => Path.GetFileName(node.GetProperty("Path").GetString()) == "InnoEngine.Build.csproj") - .GetProperty("Properties").GetProperty("TargetPath").GetString()!; + string entry = snapshot + .EnumerateArray() + .Single(node => Path.GetFileName(node.GetProperty("Path").GetString()) == "InnoEngine.Build.csproj") + .GetProperty("Properties") + .GetProperty("TargetPath") + .GetString()!; string project = Path.Combine(directory, contextId + "-documentation-project"); Directory.CreateDirectory(Path.Combine(project, "Assets")); - await File.WriteAllTextAsync(Path.Combine(project, "Assets", "DocumentationProbe.cs"), "public sealed class DocumentationProbe { }", cancellation).ConfigureAwait(false); - await ValidationProcess.RunAsync(plan.dotnet, [entry, "scripts", "--engine-root", plan.root, - "--dotnet", plan.dotnet, - "--project", project, "--output", Path.Combine(project, "Scripts"), "--ide"], plan.root, - Path.Combine(directory, contextId + "-documentation-projection.log"), cancellation).ConfigureAwait(false); + await File.WriteAllTextAsync( + Path.Combine(project, "Assets", "DocumentationProbe.cs"), + "public sealed class DocumentationProbe { }", + cancellation + ).ConfigureAwait(false); + await ValidationProcess.RunAsync( + plan.dotnet, + [ + entry, + "scripts", + "--engine-root", + plan.root, + "--dotnet", + plan.dotnet, + "--project", + project, + "--output", + Path.Combine(project, "Scripts"), + "--ide" + ], + plan.root, + Path.Combine(directory, contextId + "-documentation-projection.log"), + cancellation + ).ConfigureAwait(false); XDocument projection = XDocument.Load(Path.Combine(project, "Inno.EditorScripts.csproj")); foreach (string scope in new[] { "Runtime", "Editor" }) { - XElement reference = projection.Descendants("Reference").Single(element => (string?)element.Attribute("Include") == "Inno.ScriptApi." + scope); + XElement reference = projection + .Descendants("Reference") + .Single(element => (string?)element.Attribute("Include") == "Inno.ScriptApi." + scope); string path = Path.GetFullPath(reference.Element("HintPath")!.Value, project); if (!File.Exists(path)) - throw new InvalidDataException($"Current Documentation script projection reference is missing: {path}"); + { + throw new InvalidDataException( + $"Current Documentation script projection reference is missing: {path}" + ); + } scriptArguments.AddRange(["--" + scope.ToLowerInvariant() + "-reference", path]); } } - string[] targetArguments = check.documentation.target is string exampleTarget ? ["--target", exampleTarget] : []; - if (await DocumentationExamples.ExecuteAsync(["--engine-root", plan.root, "--configuration", plan.configuration, - "--dotnet", plan.dotnet, "--cache-root", plan.documentation!.cacheRoot, "--snapshot", plan.documentation.snapshot, - "--artifacts-path", plan.contexts[contextId].properties["ArtifactsPath"], - "--sdk-snapshot", await ResolveCompilationGraphAsync(contextId).ConfigureAwait(false), - "--output", Path.Combine(directory, contextId + "-documentation-examples.json"), - ..targetArguments, ..scriptArguments, ..pages], cancellation).ConfigureAwait(false) != 0) - throw new InvalidDataException("Selected documentation examples failed or require unavailable compilation inputs."); + string[] targetArguments = check.documentation.target is string exampleTarget + ? ["--target", exampleTarget] + : []; + if (await DocumentationExamples.ExecuteAsync([ + "--engine-root", + plan.root, + "--configuration", + plan.configuration, + "--dotnet", + plan.dotnet, + "--cache-root", + plan.documentation!.cacheRoot, + "--snapshot", + plan.documentation.snapshot, + "--artifacts-path", + plan.contexts[contextId].properties["ArtifactsPath"], + "--sdk-snapshot", + await ResolveCompilationGraphAsync(contextId).ConfigureAwait(false), + "--output", + Path.Combine(directory, contextId + "-documentation-examples.json"), + ..targetArguments, + ..scriptArguments, + ..pages + ], cancellation).ConfigureAwait(false) != 0 + ) { + throw new InvalidDataException( + "Selected documentation examples failed or require unavailable compilation inputs." + ); + } break; case "products": { JsonElement graph = plan.contexts[contextId].sdkGraph; - JsonElement editor = graph.EnumerateArray().Single(snapshot => - Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == check.owner); + JsonElement editor = graph.EnumerateArray().Single(snapshot => ( + Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!) + .Replace('\\', '/') == check.owner + )); string assembly = editor.GetProperty("Properties").GetProperty("TargetPath").GetString()!; - string backendPattern = editor.GetProperty("Properties").GetProperty("InnoValidationBackendPattern").GetString()!; + string backendPattern = editor + .GetProperty("Properties") + .GetProperty("InnoValidationBackendPattern") + .GetString()!; if (string.IsNullOrWhiteSpace(backendPattern)) - throw new InvalidDataException("Product acceptance requires its platform-owned renderer startup contract."); + { + throw new InvalidDataException( + "Product acceptance requires its platform-owned renderer startup contract." + ); + } string productDirectory = Path.Combine(directory, check.id); Directory.CreateDirectory(productDirectory); string project = Path.Combine(productDirectory, "Source"); - await ValidationProductInput.PrepareAsync(plan, productDirectory, project, cancellation).ConfigureAwait(false); - await ShellAsync("tests/Invoke-EditorSmoke.ps1", ["-EditorAssembly", assembly, "-ProjectDirectory", project, - "-BackendPattern", backendPattern, "-Dotnet", plan.dotnet, "-Frames", "300", "-HiddenWindow"], check.id + "-smoke.log").ConfigureAwait(false); + await ValidationProductInput.PrepareAsync( + plan, + productDirectory, + project, + cancellation + ).ConfigureAwait(false); + await ShellAsync( + "tests/Invoke-EditorSmoke.ps1", + [ + "-EditorAssembly", + assembly, + "-ProjectDirectory", + project, + "-BackendPattern", + backendPattern, + "-Dotnet", + plan.dotnet, + "-Frames", + "300", + "-HiddenWindow" + ], + check.id + + "-smoke.log" + ).ConfigureAwait(false); string[] renderers = Directory.GetFiles(Path.Combine(project, "Logs"), "*.log").SelectMany(path => - System.Text.RegularExpressions.Regex.Matches(File.ReadAllText(path), @"Rendering initialized with (\w+)") + System.Text.RegularExpressions.Regex + .Matches(File.ReadAllText(path), @"Rendering initialized with (\w+)") .Select(static match => match.Groups[1].Value)).Distinct(StringComparer.Ordinal).ToArray(); if (renderers.Length != 1) + { throw new InvalidDataException("Product smoke did not identify one actual initialized renderer."); + } foreach (string scenario in new[] { "Workflows", "Lifecycle" }) - await ShellAsync("tests/Invoke-EditorUiProductJourney.ps1", ["-EditorAssembly", assembly, "-ProjectDirectory", project, - "-ResultsDirectory", Path.Combine(productDirectory, scenario), "-Dotnet", plan.dotnet, - "-GraphicsApi", renderers[0], "-Scenario", scenario, - ..(plan.nativeDependencies is null ? Array.Empty() : ["-NativeDependencies", Path.Combine(plan.root, plan.nativeDependencies)]), - ..((plan.extended || plan.profile == ValidationProfile.Performance) && scenario == "Lifecycle" ? new[] { "-Cycles", "1000", "-Frames", "180000", "-TimeoutSeconds", "5400" } : [])], - check.id + "-" + scenario + ".log").ConfigureAwait(false); + { + await ShellAsync( + "tests/Invoke-EditorUiProductJourney.ps1", + [ + "-EditorAssembly", + assembly, + "-ProjectDirectory", + project, + "-ResultsDirectory", + Path.Combine(productDirectory, scenario), + "-Dotnet", + plan.dotnet, + "-GraphicsApi", + renderers[0], + "-Scenario", + scenario, + ..(plan.nativeDependencies is null + ? Array.Empty() + : ["-NativeDependencies", Path.Combine(plan.root, plan.nativeDependencies)]), + ..((plan.extended || plan.profile == ValidationProfile.Performance) && scenario == "Lifecycle" + ? new[] { "-Cycles", "1000", "-Frames", "180000", "-TimeoutSeconds", "5400" } + : []) + ], + check.id + "-" + scenario + ".log" + ).ConfigureAwait(false); + } } break; case "support-pack": { - string entry = plan.contexts[contextId].sdkGraph.EnumerateArray().Single(snapshot => - Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == check.owner) - .GetProperty("Properties").GetProperty("TargetPath").GetString()!; + string entry = plan.contexts[contextId].sdkGraph.EnumerateArray() + .Single(snapshot => ( + Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!) + .Replace('\\', '/') == check.owner + )) + .GetProperty("Properties") + .GetProperty("TargetPath") + .GetString()!; string deliverables = Path.Combine(plan.artifacts, "deliverables"); Directory.CreateDirectory(deliverables); - await ValidationProcess.RunAsync(plan.dotnet, [entry, "support-pack", "--engine-root", plan.root, - "--tools-target", plan.contexts[contextId].properties["InnoToolTarget"], "--dotnet", plan.dotnet, - "--configuration", "Release", "--archive", Path.Combine(deliverables, "PlayerSupportPack.zip"), - ..plan.nativeDependencies is null ? Array.Empty() : ["--native-dependencies", Path.Combine(plan.root, plan.nativeDependencies)]], - plan.root, Path.Combine(directory, "support-pack.log"), cancellation).ConfigureAwait(false); - await ShellAsync("tests/ci/Test-SupportPackClosure.ps1", ["-Archive", Path.Combine(deliverables, "PlayerSupportPack.zip")], - "support-pack-closure.log").ConfigureAwait(false); + await ValidationProcess.RunAsync( + plan.dotnet, + [ + entry, + "support-pack", + "--engine-root", + plan.root, + "--tools-target", + plan.contexts[contextId].properties["InnoToolTarget"], + "--dotnet", + plan.dotnet, + "--configuration", + "Release", + "--archive", + Path.Combine(deliverables, "PlayerSupportPack.zip"), + ..plan.nativeDependencies is null + ? Array.Empty() + : ["--native-dependencies", Path.Combine(plan.root, plan.nativeDependencies)] + ], + plan.root, + Path.Combine(directory, "support-pack.log"), + cancellation + ).ConfigureAwait(false); + await ShellAsync( + "tests/ci/Test-SupportPackClosure.ps1", + ["-Archive", Path.Combine(deliverables, "PlayerSupportPack.zip")], + "support-pack-closure.log" + ).ConfigureAwait(false); } break; case "build": if (buildFailures.TryGetValue(contextId, out string? buildFailure)) + { throw new InvalidOperationException(buildFailure); + } if (!built.Contains(contextId)) { string solution = buildSolutions[contextId]; try { var compilationInputs = new ValidationBuildInputs(plan, contextId, outputDigests, cancellation); - string[] properties = plan.contexts[contextId].properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Value).ToArray(); + string[] properties = plan.contexts[contextId].properties + .Select(static pair => "-p:" + pair.Key + "=" + pair.Value) + .ToArray(); bool retainDependencies = !compilationInputs.RequiresDependencyCompilation(dependencyInputs); - // Rebuild interleaves Clean and Build across root instances. Drain the one owned clean phase before any compiler starts. + // Rebuild interleaves Clean and Build across root instances. Drain the one owned clean phase + // before any compiler starts. if (compilationInputs.RequiresCompilation(dependencyInputs)) - await ValidationProcess.RunAsync(plan.dotnet, ["clean", solution, ..properties, - "-p:InnoPrepareProductNative=false", "-p:InnoTaskBootstrapOwner=" + Guid.NewGuid().ToString("N"), + { + await ValidationProcess.RunAsync( + plan.dotnet, + [ + "clean", + solution, + ..properties, + "-p:InnoPrepareProductNative=false", + "-p:InnoTaskBootstrapOwner=" + + Guid.NewGuid().ToString("N"), + ..retainDependencies + ? new[] { "-p:BuildProjectReferences=false", "-p:InnoCleanProjectReferences=false" } + : Array.Empty(), + "--disable-build-servers", + "-m:1", + "-nr:false" + ], + plan.root, + Path.Combine(directory, contextId + "-clean.log"), + cancellation + ).ConfigureAwait(false); + } + await ValidationProcess.RunAsync( + plan.dotnet, + [ + "build", + solution, + ..properties, + "-p:InnoTaskBootstrapOwner=" + Guid.NewGuid().ToString("N"), ..retainDependencies - ? new[] { "-p:BuildProjectReferences=false", "-p:InnoCleanProjectReferences=false" } : Array.Empty(), - "--disable-build-servers", "-m:1", "-nr:false"], - plan.root, Path.Combine(directory, contextId + "-clean.log"), cancellation).ConfigureAwait(false); - await ValidationProcess.RunAsync(plan.dotnet, - ["build", solution, ..properties, "-p:InnoTaskBootstrapOwner=" + Guid.NewGuid().ToString("N"), - ..retainDependencies ? new[] { "-p:InnoUseVerifiedProjectOutputs=true" } : Array.Empty(), - "--disable-build-servers", "-m:" + (contextId == "managed" ? Math.Min(Environment.ProcessorCount, 4) : 1), - "-nr:false", "-clp:PerformanceSummary"], plan.root, Path.Combine(directory, contextId + "-build.log"), cancellation).ConfigureAwait(false); + ? new[] { "-p:InnoUseVerifiedProjectOutputs=true" } + : Array.Empty(), + "--disable-build-servers", + "-m:" + + (contextId == "managed" ? Math.Min(Environment.ProcessorCount, 4) : 1), + "-nr:false", + "-clp:PerformanceSummary" + ], + plan.root, + Path.Combine(directory, contextId + "-build.log"), + cancellation + ).ConfigureAwait(false); built.Add(contextId); outputDigests.Clear(); dependencyInputs.Reset(); @@ -379,42 +701,92 @@ await ValidationProcess.RunAsync(plan.dotnet, break; } if (testFailures.TryGetValue(contextId, out string? testFailure)) + { throw new InvalidOperationException(testFailure); + } if (!tested.Contains(contextId)) { - string[] tests = checks.Where(candidate => candidate.kind == "test" && candidate.exclusion is null && candidate.context == contextId - && !CanReuse(candidate)) - .Select(static candidate => candidate.owner).ToArray(); + string[] tests = checks + .Where(candidate => ( + candidate.kind == "test" && candidate.exclusion is null && candidate.context == contextId + && !CanReuse(candidate) + )) + .Select(static candidate => candidate.owner) + .ToArray(); string solution = WriteUnion(contextId, "Tests", tests); string resultsDirectory = Path.Combine(directory, contextId + "-trx"); Dictionary properties = plan.contexts[contextId].properties; - string[] productArguments = contextId == "native" ? ["-Target", properties["InnoNativeTarget"], "-ToolTarget", properties["InnoToolTarget"], - "-ProductProperties", properties["InnoProductBuildProperties"]] : []; + string[] productArguments = contextId == "native" + ? [ + "-Target", + properties["InnoNativeTarget"], + "-ToolTarget", + properties["InnoToolTarget"], + "-ProductProperties", + properties["InnoProductBuildProperties"] + ] + : []; try { long batchStart = Stopwatch.GetTimestamp(); try { - await ShellAsync(C_TEST_EXECUTOR, - ["-Solution", solution, "-Configuration", properties["Configuration"], "-ArtifactsPath", properties["ArtifactsPath"], - "-Dotnet", plan.dotnet, "-SdkSnapshot", graphPath, "-ResultsDirectory", resultsDirectory, ..productArguments, - ..plan.nativeDependencies is null ? Array.Empty() : ["-NativeDependencies", Path.Combine(plan.root, plan.nativeDependencies)]], contextId + "-tests.log").ConfigureAwait(false); + await ShellAsync( + C_TEST_EXECUTOR, + [ + "-Solution", + solution, + "-Configuration", + properties["Configuration"], + "-ArtifactsPath", + properties["ArtifactsPath"], + "-Dotnet", + plan.dotnet, + "-SdkSnapshot", + graphPath, + "-ResultsDirectory", + resultsDirectory, + ..productArguments, + ..plan.nativeDependencies is null + ? Array.Empty() + : ["-NativeDependencies", Path.Combine(plan.root, plan.nativeDependencies)] + ], + contextId + "-tests.log" + ).ConfigureAwait(false); } catch (Exception failure) when (failure is not OperationCanceledException) { // Preserve the process failure even when individual owners have complete successful evidence. - failures.Add(new("test-execution", failure.Message.Split('\n')[0], contextId, contextId + "-tests.log", Stopwatch.GetElapsedTime(batchStart).TotalSeconds)); + failures.Add( + new( + "test-execution", + failure.Message.Split('\n')[0], + contextId, + contextId + "-tests.log", + Stopwatch.GetElapsedTime(batchStart).TotalSeconds + ) + ); await SaveAsync().ConfigureAwait(false); } finally { batchSeconds[contextId] = Stopwatch.GetElapsedTime(batchStart).TotalSeconds; } - foreach (var evidence in ValidationTestEvidence.Read(plan.root, tests.ToDictionary(static project => project, project => - plan.contexts[contextId].sdkGraph.EnumerateArray().Single(snapshot => - Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == project) - .GetProperty("Properties").GetProperty("TargetPath").GetString()!, StringComparer.Ordinal), resultsDirectory)) + foreach (var evidence in ValidationTestEvidence.Read( + plan.root, + tests.ToDictionary(static project => project, project => + plan.contexts[contextId].sdkGraph.EnumerateArray() + .Single(snapshot => ( + Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!) + .Replace('\\', '/') == project + )) + .GetProperty("Properties") + .GetProperty("TargetPath") + .GetString()!, StringComparer.Ordinal), + resultsDirectory + )) { testDetails.Add(evidence.Key, evidence.Value); + } elapsed.Restart(); executedTests.UnionWith(tests); tested.Add(contextId); @@ -428,9 +800,15 @@ await ShellAsync(C_TEST_EXECUTOR, } } if (!executedTests.Contains(check.owner)) - throw new InvalidDataException($"Previously reusable output changed before {check.id}; this test did not execute and cannot be certified."); + { + throw new InvalidDataException( + $"Previously reusable output changed before {check.id}; this test did not execute and cannot be certified." + ); + } if (!testDetails[check.owner].passed) + { throw new InvalidDataException(testDetails[check.owner].detail); + } detail = testDetails[check.owner].detail; break; default: @@ -454,7 +832,9 @@ await ShellAsync(C_TEST_EXECUTOR, detail = failure.Message; } } - results.Add(new(check.id, status, identity, elapsed.Elapsed.TotalSeconds, detail, outputs, dependencyIdentity, documentationInputs)); + results.Add( + new(check.id, status, identity, elapsed.Elapsed.TotalSeconds, detail, outputs, dependencyIdentity, documentationInputs) + ); string measurement = check.kind == "test" ? " owner reconciliation" : string.Empty; Console.WriteLine($"{status}: {check.id} ({elapsed.Elapsed.TotalSeconds:F2}s{measurement}) {detail}"); await SaveAsync().ConfigureAwait(false); @@ -463,7 +843,18 @@ await ShellAsync(C_TEST_EXECUTOR, { failures.Add(new("execution-canceled", "The run was canceled before closing verification.")); await SaveAsync().ConfigureAwait(false); - return new(plan.commit, plan.tree, plan.environment, started, OwnedResults(), ValidationShards.C_EVIDENCE_VERSION, failures.ToArray(), planIdentity, shard: shard?.id, batchSeconds: batchSeconds); + return new( + plan.commit, + plan.tree, + plan.environment, + started, + OwnedResults(), + ValidationShards.C_EVIDENCE_VERSION, + failures.ToArray(), + planIdentity, + shard: shard?.id, + batchSeconds: batchSeconds + ); } // Both closing snapshots read independent owners after all checks; neither may reuse planning-time bytes. long closingStart = Stopwatch.GetTimestamp(); @@ -480,13 +871,30 @@ await ShellAsync(C_TEST_EXECUTOR, } closingSeconds = Stopwatch.GetElapsedTime(closingStart).TotalSeconds; await SaveAsync(completed: true).ConfigureAwait(false); - return new(plan.commit, plan.tree, plan.environment, started, OwnedResults(), ValidationShards.C_EVIDENCE_VERSION, failures.ToArray(), planIdentity, completed: true, shard: shard?.id, closingSeconds: closingSeconds, batchSeconds: batchSeconds); + return new( + plan.commit, + plan.tree, + plan.environment, + started, + OwnedResults(), + ValidationShards.C_EVIDENCE_VERSION, + failures.ToArray(), + planIdentity, + completed: true, + shard: shard?.id, + closingSeconds: closingSeconds, + batchSeconds: batchSeconds + ); async Task VerifyClosingStateAsync() { Task> sourceCapture = ValidationInputs.CaptureAsync(plan.root, cancellation); Task environmentCapture = Task.Run(() => ValidationEnvironment.CaptureAsync( - plan.root, plan.dotnet, cancellation, plan.contexts.Values), cancellation); + plan.root, + plan.dotnet, + cancellation, + plan.contexts.Values + ), cancellation); await Task.WhenAll(sourceCapture, environmentCapture).ConfigureAwait(false); Dictionary after = await sourceCapture.ConfigureAwait(false); outputDigests.Clear(); @@ -496,11 +904,15 @@ async Task VerifyClosingStateAsync() { ValidationResult result = results.Single(record => record.id == check.id); if (result.status is "Passed" or "Reused" && (!ValidationOutputs.Matches(plan, check, result, cancellation, outputDigests) - || !dependencyInputs.Matches(check, result.dependencyIdentity))) - { + || !dependencyInputs.Matches(check, result.dependencyIdentity)) + ) { if (check.kind == "build") + { unstableCompilations.Add(check.context!); - failures.Add(new("output-stability", "Compiled outputs or restored dependencies changed after verification.", check.id)); + } + failures.Add( + new("output-stability", "Compiled outputs or restored dependencies changed after verification.", check.id) + ); await SaveAsync().ConfigureAwait(false); } } @@ -517,36 +929,68 @@ async Task VerifyClosingStateAsync() await SaveAsync().ConfigureAwait(false); } if (sourceStable && environmentStable) + { foreach (var compilation in pendingCompilations.Where(pair => !unstableCompilations.Contains(pair.Key))) + { compilation.Value.Record(dependencyInputs); + } + } if (workspace is not null) + { ValidationWorkspace.RecordCompleted(plan, cancellation); + } } Task ShellAsync( string script, string[] arguments, string log - ) => ValidationProcess.RunAsync("pwsh", ["-NoProfile", "-File", Path.Combine(plan.root, script), ..arguments], - plan.root, Path.Combine(directory, log), cancellation); + ) => ValidationProcess.RunAsync( + "pwsh", + ["-NoProfile", "-File", Path.Combine(plan.root, script), ..arguments], + plan.root, + Path.Combine(directory, log), + cancellation + ); async Task ResolveCompilationGraphAsync(string context) { if (compilationGraphs.TryGetValue(context, out string? existing)) + { return existing; - string[] projects = checks.Where(candidate => candidate.context == context && candidate.exclusion is null - && candidate.kind is "api" or "documentation-api" or "documentation-examples" - && candidate.prerequisites.All(prerequisite => results.Any(result => result.id == prerequisite && result.status is "Passed" or "Reused"))) + } + string[] projects = checks + .Where(candidate => ( + candidate.context == context && candidate.exclusion is null + && candidate.kind is "api" or "documentation-api" or "documentation-examples" + && candidate.prerequisites.All( + prerequisite => results.Any(result => result.id == prerequisite && result.status is "Passed" or "Reused") + ) + )) .SelectMany(static candidate => candidate.projects ?? []) // Consumer roots carry effective reference-edge properties, even when only their dependency exposes an API. - .Concat(checks.Where(candidate => candidate.kind == "build" && candidate.context == context && candidate.exclusion is null - && results.Any(result => result.id == candidate.id && result.status is "Passed" or "Reused")).Select(static candidate => candidate.owner)) + .Concat( + checks.Where(candidate => ( + candidate.kind == "build" && candidate.context == context && candidate.exclusion is null + && results.Any(result => result.id == candidate.id && result.status is "Passed" or "Reused") + )).Select(static candidate => candidate.owner) + ) .Distinct(StringComparer.Ordinal) - .Order(StringComparer.Ordinal).Select(project => Path.Combine(plan.root, project)).ToArray(); + .Order(StringComparer.Ordinal) + .Select(project => Path.Combine(plan.root, project)) + .ToArray(); if (projects.Length == 0) + { throw new InvalidDataException("Required compilation reference preparation has no eligible project owners."); - string graph = await ManagedProjectGraphCapture.CaptureAsync(plan.root, plan.dotnet, projects, - plan.contexts[context].properties, cancellation, resolveReferences: true).ConfigureAwait(false); + } + string graph = await ManagedProjectGraphCapture.CaptureAsync( + plan.root, + plan.dotnet, + projects, + plan.contexts[context].properties, + cancellation, + resolveReferences: true + ).ConfigureAwait(false); string destination = Path.Combine(directory, context + "-resolved-sdk-graph.json"); await File.WriteAllTextAsync(destination, graph, cancellation).ConfigureAwait(false); compilationGraphs.Add(context, destination); @@ -559,21 +1003,51 @@ string WriteUnion( string[] projects ) { if (projects.Length == 0) + { throw new InvalidDataException("A required build or test union is empty."); + } string destination = Path.Combine(directory, context + "-" + operation + ".slnx"); // IDE solution filters inherit Build.0 exclusions and configuration remapping. The plan owns this exact union. - new XDocument(new XElement("Solution", - new XElement("Configurations", new XElement("BuildType", new XAttribute("Name", plan.contexts[context].properties["Configuration"]))), - projects.Select(project => new XElement("Project", new XAttribute("Path", Path.Combine(plan.root, project).Replace('\\', '/')))))) + new XDocument( + new XElement( + "Solution", + new XElement( + "Configurations", + new XElement("BuildType", new XAttribute("Name", plan.contexts[context].properties["Configuration"])) + ), + projects.Select( + project => new XElement("Project", new XAttribute("Path", Path.Combine(plan.root, project).Replace('\\', '/'))) + ) + ) + ) .Save(destination); return destination; } ValidationResult[] OwnedResults() => results.Where(result => !imported.Contains(result)).ToArray(); - Task SaveAsync(bool completed = false) => File.WriteAllTextAsync(Path.Combine(directory, "results.json"), - JsonSerializer.Serialize(new ValidationEvidence(plan.commit, plan.tree, plan.environment, started, OwnedResults(), ValidationShards.C_EVIDENCE_VERSION, failures.ToArray(), planIdentity, completed, shard?.id, closingSeconds, batchSeconds), - new JsonSerializerOptions { WriteIndented = true }), CancellationToken.None); + Task SaveAsync(bool completed = false) + => File.WriteAllTextAsync( + Path.Combine(directory, "results.json"), + JsonSerializer.Serialize( + new ValidationEvidence( + plan.commit, + plan.tree, + plan.environment, + started, + OwnedResults(), + ValidationShards.C_EVIDENCE_VERSION, + failures.ToArray(), + planIdentity, + completed, + shard?.id, + closingSeconds, + batchSeconds + ), + new JsonSerializerOptions { WriteIndented = true } + ), + CancellationToken.None + ); bool CanReuse(ValidationCheck candidate) { @@ -596,26 +1070,39 @@ bool CanReuse(ValidationCheck candidate) bool MatchesRetained(ValidationCheck candidate) { if (candidate.layer == "performance") + { return false; + } ValidationResult? retained = (continuation || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CI"))) - && previous is { completed: true, version: ValidationShards.C_EVIDENCE_VERSION, failures: not null } && previous.environment == plan.environment + && previous is { completed: true, version: ValidationShards.C_EVIDENCE_VERSION, failures: not null } + && previous.environment == plan.environment && previous.failures.All(fault => fault.stage switch { "test-execution" => candidate.kind != "test" || candidate.context != fault.owner - || previous.results.Any(result => result.status == "Failed" && plan.checks.Any(check => check.id == result.id && check.kind == "test" && check.context == fault.owner)), + || previous.results.Any( + result => ( + result.status == "Failed" + && plan.checks.Any(check => check.id == result.id && check.kind == "test" && check.context == fault.owner) + ) + ), "output-stability" => false, _ => false }) - ? previous.results.SingleOrDefault(result => result.id == candidate.id) : null; + ? previous.results.SingleOrDefault(result => result.id == candidate.id) + : null; if (retained is null && candidate.kind == "test" && candidate.owner.StartsWith("tests/backends/", StringComparison.Ordinal)) + { retained = plan.backendTests?.SingleOrDefault(result => result.id == candidate.id); - if (retained is not { status: "Passed" or "Reused" } || retained.inputIdentity != ValidationInputs.CheckIdentity(plan, candidate, current) + } + if (retained is not { status: "Passed" or "Reused" } + || retained.inputIdentity != ValidationInputs.CheckIdentity(plan, candidate, current) || !dependencyInputs.Matches(candidate, retained.dependencyIdentity) - || !ValidationOutputs.Matches(plan, candidate, retained, cancellation, outputDigests)) + || !ValidationOutputs.Matches(plan, candidate, retained, cancellation, outputDigests) + ) { return false; + } reused[candidate.id] = retained; return true; } } - } diff --git a/tools/Inno.Tooling.Validation/ValidationShard.cs b/tools/Inno.Tooling.Validation/ValidationShard.cs index c3fbaca4e..af122a38c 100644 --- a/tools/Inno.Tooling.Validation/ValidationShard.cs +++ b/tools/Inno.Tooling.Validation/ValidationShard.cs @@ -4,33 +4,47 @@ using System.Linq; namespace Inno.Tooling.Validation; + internal sealed record ValidationShard( string id, string[] checks, string[] prerequisites ); + internal static class ValidationShards { internal const int C_EVIDENCE_VERSION = 2; internal static ValidationShard[] Create(ValidationCheck[] checks) { - var owners = checks.ToDictionary(static check => check.id, - static check => check.exclusion is not null || check.context is null ? "architecture" - : check.context == "managed" ? "managed" : "native", StringComparer.Ordinal); + var owners = checks.ToDictionary( + static check => check.id, + static check => ( + check.exclusion is not null || check.context is null + ? "architecture" + : check.context == "managed" ? "managed" : "native" + ), + StringComparer.Ordinal + ); var shards = new List(); foreach (var group in checks.GroupBy(check => owners[check.id], StringComparer.Ordinal)) { var prerequisites = new HashSet(StringComparer.Ordinal); foreach (string required in group.Where(static check => check.exclusion is null) - .SelectMany(static check => check.prerequisites)) - { + .SelectMany(static check => check.prerequisites) + ) { if (!owners.TryGetValue(required, out string? owner)) + { throw new InvalidDataException("A shard requires an unplanned check: " + required); + } if (owner != group.Key) + { prerequisites.Add(owner); + } } - shards.Add(new(group.Key, group.Select(static check => check.id).ToArray(), prerequisites.Order(StringComparer.Ordinal).ToArray())); + shards.Add( + new(group.Key, group.Select(static check => check.id).ToArray(), prerequisites.Order(StringComparer.Ordinal).ToArray()) + ); } return shards.ToArray(); } @@ -40,8 +54,22 @@ internal static ValidationShard Require( string id ) { ValidationShard[] expected = Create(plan.checks); - if (plan.shards is null || plan.shards.Length != expected.Length || expected.Any(shard => plan.shards.Count(actual => actual.id == shard.id && actual.checks.SequenceEqual(shard.checks, StringComparer.Ordinal) && actual.prerequisites.SequenceEqual(shard.prerequisites, StringComparer.Ordinal)) != 1)) + if (plan.shards is null + || plan.shards.Length != expected.Length + || expected.Any( + shard => ( + plan.shards.Count( + actual => ( + actual.id == shard.id + && actual.checks.SequenceEqual(shard.checks, StringComparer.Ordinal) + && actual.prerequisites.SequenceEqual(shard.prerequisites, StringComparer.Ordinal) + ) + ) != 1 + ) + ) + ) { throw new InvalidDataException("The frozen shard partition does not cover the exact plan."); + } return expected.SingleOrDefault(shard => shard.id == id) ?? throw new InvalidDataException("Unknown validation shard: " + id); } @@ -50,8 +78,11 @@ string id ValidationEvidence? previous ) { if (previous is not { completed: true, version: C_EVIDENCE_VERSION, failures: not null } - || previous.environment != plan.environment || previous.results.DistinctBy(result => result.id).Count() != previous.results.Length) + || previous.environment != plan.environment + || previous.results.DistinctBy(result => result.id).Count() != previous.results.Length + ) { return null; + } var invalid = new HashSet(StringComparer.Ordinal); foreach (ValidationRunFailure fault in previous.failures) @@ -60,20 +91,29 @@ string id { ValidationCheck? producer = plan.checks.SingleOrDefault(check => check.id == fault.owner); if (producer is null) + { return null; + } invalid.Add(producer.id); - foreach (ValidationCheck consumer in plan.checks.Where(check => check.context == producer.context - && check.inputs.Contains("@" + producer.owner, StringComparer.Ordinal))) + foreach (ValidationCheck consumer in plan.checks.Where(check => ( + check.context == producer.context + && check.inputs.Contains("@" + producer.owner, StringComparer.Ordinal) + ))) { invalid.Add(consumer.id); + } } else if (fault.stage == "test-execution") { ValidationCheck[] owners = plan.checks.Where(check => check.kind == "test" && check.context == fault.owner).ToArray(); if (!owners.Any(owner => previous.results.Any(result => result.id == owner.id && result.status == "Failed"))) + { invalid.UnionWith(owners.Select(owner => owner.id)); + } } else + { return null; + } } if (invalid.Count != 0) { @@ -82,8 +122,11 @@ string id { before = invalid.Count; foreach (ValidationCheck check in plan.checks.Where(check => check.prerequisites.Any(invalid.Contains))) + { invalid.Add(check.id); - } while (before != invalid.Count); + } + } + while (before != invalid.Count); } return invalid; } @@ -94,38 +137,62 @@ internal static ValidationResult[] ValidateEvidence( string? shard = null ) { if (evidence.version != C_EVIDENCE_VERSION || evidence.failures is null) + { throw new InvalidDataException("Validation evidence has an unsupported format."); - if (evidence.commit != plan.commit || evidence.tree != plan.tree || evidence.environment != plan.environment || evidence.planIdentity != ValidationInputs.PlanIdentity(plan) || evidence.shard != shard) + } + if (evidence.commit != plan.commit + || evidence.tree != plan.tree + || evidence.environment != plan.environment + || evidence.planIdentity != ValidationInputs.PlanIdentity(plan) + || evidence.shard != shard + ) { throw new InvalidDataException("Validation evidence has a different candidate, plan, environment or execution scope."); + } HashSet? selected = shard is null ? null : Require(plan, shard).checks.ToHashSet(StringComparer.Ordinal); ValidationCheck[] checks = plan.checks.Where(check => selected is null || selected.Contains(check.id)).ToArray(); if (checks.Length == 0) + { throw new InvalidDataException("No planned checks were discovered."); + } var expected = checks.Select(static check => check.id).ToHashSet(StringComparer.Ordinal); var observed = evidence.results.ToLookup(static result => result.id, StringComparer.Ordinal); var errors = new List(); foreach (var group in observed) { if (!expected.Contains(group.Key)) + { errors.Add("Unplanned check: " + group.Key); + } if (group.Count() != 1) + { errors.Add("Duplicate check: " + group.Key); + } } foreach (ValidationCheck check in checks) { ValidationResult? result = observed[check.id].FirstOrDefault(); if (result is null) + { errors.Add("Missing check: " + check.id); + } else if (result.inputIdentity != ValidationInputs.CheckIdentity(plan, check, plan.inputs)) + { errors.Add("Stale check: " + check.id); + } else if (check.exclusion is null ? result.status is not ("Passed" or "Reused") : result.status != "NotApplicable") + { errors.Add(check.id + ": " + result.detail); + } } errors.AddRange(evidence.failures.Select(static fault => fault.stage + ": " + fault.detail)); if (!evidence.completed) + { errors.Add("Validation did not complete closing verification."); + } if (errors.Count != 0) + { throw new InvalidDataException(string.Join(Environment.NewLine, errors)); + } return evidence.results; } @@ -135,12 +202,16 @@ internal static ValidationResult[] Prerequisites( IReadOnlyList evidence ) { if (evidence.Count != shard.prerequisites.Length) + { throw new InvalidDataException("The shard is missing prerequisites or received unrelated receipts."); + } return shard.prerequisites.SelectMany(id => { ValidationEvidence[] matches = evidence.Where(receipt => receipt.shard == id).ToArray(); if (matches.Length != 1) + { throw new InvalidDataException("Missing or duplicate prerequisite shard: " + id); + } return ValidateEvidence(plan, matches[0], id); }).ToArray(); } @@ -150,18 +221,32 @@ internal static ValidationEvidence Join( IReadOnlyList evidence ) { if (plan.shards is null || evidence.Count != plan.shards.Length) + { throw new InvalidDataException("The required shard matrix is incomplete or duplicated."); + } var results = new List(); foreach (ValidationShard shard in plan.shards) { _ = Require(plan, shard.id); ValidationEvidence[] matches = evidence.Where(receipt => receipt.shard == shard.id).ToArray(); if (matches.Length != 1) + { throw new InvalidDataException("Missing or duplicate execution shard: " + shard.id); + } results.AddRange(ValidateEvidence(plan, matches[0], shard.id)); } - var joined = new ValidationEvidence(plan.commit, plan.tree, plan.environment, evidence.Min(static receipt => receipt.started), results.ToArray(), C_EVIDENCE_VERSION, [], ValidationInputs.PlanIdentity(plan), completed: true); + var joined = new ValidationEvidence( + plan.commit, + plan.tree, + plan.environment, + evidence.Min(static receipt => receipt.started), + results.ToArray(), + C_EVIDENCE_VERSION, + [], + ValidationInputs.PlanIdentity(plan), + completed: true + ); _ = ValidateEvidence(plan, joined); return joined; } diff --git a/tools/Inno.Tooling.Validation/ValidationTestEvidence.cs b/tools/Inno.Tooling.Validation/ValidationTestEvidence.cs index 2b2842d49..3043b72b0 100644 --- a/tools/Inno.Tooling.Validation/ValidationTestEvidence.cs +++ b/tools/Inno.Tooling.Validation/ValidationTestEvidence.cs @@ -15,9 +15,16 @@ internal static class ValidationTestEvidence string directory ) { string[] reports = Directory.GetFiles(directory, "*.trx", SearchOption.AllDirectories); - var assemblies = projects.ToDictionary(static pair => Path.GetFileNameWithoutExtension(pair.Value), static pair => pair.Key, - StringComparer.OrdinalIgnoreCase); - var hosts = projects.ToDictionary(static pair => pair.Key, static pair => ValidationTestHosts.Read(pair.Value), StringComparer.Ordinal); + var assemblies = projects.ToDictionary( + static pair => Path.GetFileNameWithoutExtension(pair.Value), + static pair => pair.Key, + StringComparer.OrdinalIgnoreCase + ); + var hosts = projects.ToDictionary( + static pair => pair.Key, + static pair => ValidationTestHosts.Read(pair.Value), + StringComparer.Ordinal + ); var executed = projects.Keys.ToDictionary(static project => project, static _ => 0, StringComparer.Ordinal); var excluded = projects.Keys.ToDictionary(static project => project, static _ => new List(), StringComparer.Ordinal); var failures = projects.Keys.ToDictionary(static project => project, static _ => new List(), StringComparer.Ordinal); @@ -31,26 +38,38 @@ string directory int failed = records.Count(static result => (string?)result.Attribute("outcome") == "Failed"); if ((int?)counters.Attribute("executed") != passed + failed || (int?)counters.Attribute("failed") != failed || (int?)counters.Attribute("total") != records.Length || (int?)counters.Attribute("passed") != passed - || (int?)counters.Attribute("error") is not 0 || (string?)summary.Attribute("outcome") is not ("Completed" or "Passed" or "Failed") - || records.Any(static result => (string?)result.Attribute("outcome") is not ("Passed" or "Failed" or "NotExecuted"))) + || (int?)counters.Attribute("error") is not 0 + || (string?)summary.Attribute("outcome") is not ("Completed" or "Passed" or "Failed") + || records.Any(static result => (string?)result.Attribute("outcome") is not ("Passed" or "Failed" or "NotExecuted")) + ) { throw new InvalidDataException($"Invalid or incomplete test execution: {report}"); - var definitions = document.Descendants().Where(static element => element.Name.LocalName == "UnitTest") + } + var definitions = document.Descendants() + .Where(static element => element.Name.LocalName == "UnitTest") .ToDictionary(static definition => (string)definition.Attribute("id")!, StringComparer.Ordinal); foreach (XElement record in records) { XElement definition = definitions[(string)record.Attribute("testId")!]; string assembly = Path.GetFileNameWithoutExtension((string?)definition.Attribute("storage") ?? string.Empty); if (!assemblies.TryGetValue(assembly, out string? project)) + { throw new InvalidDataException($"Test evidence has an unplanned assembly: {assembly}"); + } XElement method = definition.Elements().Single(static element => element.Name.LocalName == "TestMethod"); string name = (string?)method.Attribute("className") + "." + (string?)method.Attribute("name"); if ((string?)record.Attribute("outcome") == "Failed") { - string message = record.Descendants().FirstOrDefault(element => element.Name.LocalName == "ErrorInfo") - ?.Elements().FirstOrDefault(element => element.Name.LocalName == "Message")?.Value ?? string.Empty; + string message = record.Descendants() + .FirstOrDefault(element => element.Name.LocalName == "ErrorInfo") + ?.Elements() + .FirstOrDefault(element => element.Name.LocalName == "Message")?.Value ?? string.Empty; if (message.Length > 1200) + { message = message[..1200]; - failures[project].Add($"Test failed: {name} (TRX duration {(string?)record.Attribute("duration")}). {message} See {Path.GetFileName(report)}."); + } + failures[project].Add( + $"Test failed: {name} (TRX duration {(string?)record.Attribute("duration")}). {message} See {Path.GetFileName(report)}." + ); continue; } if (hosts[project].TryGetValue(name, out string[]? required) && !ValidationTestHosts.Applies(required)) @@ -59,45 +78,72 @@ string directory continue; } if ((string?)record.Attribute("outcome") != "Passed") + { failures[project].Add("Required test was skipped without an inapplicable compiled OS contract: " + name); + } else + { executed[project]++; + } } } using JsonDocument execution = JsonDocument.Parse(File.ReadAllText(Path.Combine(directory, "execution-summary.json"))); JsonElement[] stages = execution.RootElement.EnumerateArray().ToArray(); if (stages.Count(static stage => stage.GetProperty("stage").GetString() == "Shared") != 1) + { throw new InvalidDataException("The test union is missing its unique shared execution receipt."); + } foreach (JsonElement stage in stages.Where(static stage => stage.GetProperty("stage").GetString() != "Shared")) { string owner = Path.GetRelativePath(root, stage.GetProperty("owner").GetString()!).Replace('\\', '/'); if (!projects.ContainsKey(owner) || stage.GetProperty("stage").GetString() is not ("Discovery" or "Isolated")) + { throw new InvalidDataException("The test union contains an unplanned owner or execution stage."); + } } foreach (string project in projects.Keys) { - JsonElement[] owned = stages.Where(stage => stage.GetProperty("stage").GetString() != "Shared" - && Path.GetRelativePath(root, stage.GetProperty("owner").GetString()!).Replace('\\', '/') == project).ToArray(); + JsonElement[] owned = stages.Where(stage => ( + stage.GetProperty("stage").GetString() != "Shared" + && Path.GetRelativePath(root, stage.GetProperty("owner").GetString()!).Replace('\\', '/') == project + )).ToArray(); JsonElement[] discovery = owned.Where(static stage => stage.GetProperty("stage").GetString() == "Discovery").ToArray(); if (discovery.Length != 1 || discovery[0].GetProperty("status").GetString() != "Passed") + { failures[project].Add("Required isolated-test discovery is missing, duplicated or unsuccessful."); + } else { - string[] expected = discovery[0].GetProperty("contracts").EnumerateArray().Select(static item => item.GetString()!).Order(StringComparer.Ordinal).ToArray(); + string[] expected = discovery[0] + .GetProperty("contracts") + .EnumerateArray() + .Select(static item => item.GetString()!) + .Order(StringComparer.Ordinal) + .ToArray(); JsonElement[] isolated = owned.Where(static stage => stage.GetProperty("stage").GetString() == "Isolated").ToArray(); - string[] actual = isolated.Select(static stage => stage.GetProperty("identity").GetString()!).Order(StringComparer.Ordinal).ToArray(); - if (expected.Distinct(StringComparer.Ordinal).Count() != expected.Length || !expected.SequenceEqual(actual, StringComparer.Ordinal) - || isolated.Any(static stage => stage.GetProperty("status").GetString() != "Passed")) + string[] actual = isolated + .Select(static stage => stage.GetProperty("identity").GetString()!) + .Order(StringComparer.Ordinal) + .ToArray(); + if (expected.Distinct(StringComparer.Ordinal).Count() != expected.Length + || !expected.SequenceEqual(actual, StringComparer.Ordinal) + || isolated.Any(static stage => stage.GetProperty("status").GetString() != "Passed") + ) { failures[project].Add("Required isolated execution is missing, duplicated or unsuccessful."); + } } if (executed[project] == 0) + { failures[project].Add("No executed test evidence for required owner: " + project); + } } - File.WriteAllText(Path.Combine(directory, "host-contracts.json"), JsonSerializer.Serialize(excluded, - new JsonSerializerOptions { WriteIndented = true })); + File.WriteAllText( + Path.Combine(directory, "host-contracts.json"), + JsonSerializer.Serialize(excluded, new JsonSerializerOptions { WriteIndented = true }) + ); return projects.Keys.ToDictionary(static project => project, project => (failures[project].Count == 0, failures[project].Count == 0 - ? $"{executed[project]} required cases passed; {excluded[project].Count} OS contracts NotApplicable. See host-contracts.json." - : string.Join(Environment.NewLine, failures[project])), StringComparer.Ordinal); + ? $"{executed[project]} required cases passed; {excluded[project].Count} OS contracts NotApplicable. See host-contracts.json." + : string.Join(Environment.NewLine, failures[project])), StringComparer.Ordinal); } } diff --git a/tools/Inno.Tooling.Validation/ValidationTestHosts.cs b/tools/Inno.Tooling.Validation/ValidationTestHosts.cs index 5ecf595f6..7e91e25f1 100644 --- a/tools/Inno.Tooling.Validation/ValidationTestHosts.cs +++ b/tools/Inno.Tooling.Validation/ValidationTestHosts.cs @@ -12,21 +12,30 @@ internal static class ValidationTestHosts internal static string[] ExcludedSources(ValidationProject[] projects) { var referenced = projects.SelectMany(static project => project.references).ToHashSet(StringComparer.Ordinal); - var candidates = projects.Where(project => project.test && !referenced.Contains(project.path) + var candidates = projects.Where(project => ( + project.test && !referenced.Contains(project.path) && project.environment.Length != 0 && project.environment is not ("any" or "native-host") - && !Applies(project.environment.Split(';'))).ToArray(); + && !Applies(project.environment.Split(';')) + )).ToArray(); if (candidates.Length == 0) + { return []; + } var excluded = new HashSet(StringComparer.Ordinal); foreach (ValidationProject candidate in candidates) { string directory = candidate.path[..(candidate.path.LastIndexOf('/') + 1)]; - foreach (string input in candidate.inputs.Where(path => path.StartsWith(directory, StringComparison.Ordinal) - && path.StartsWith("tests/", StringComparison.Ordinal) && path.EndsWith(".cs", StringComparison.Ordinal))) - { - if (!projects.Any(other => other != candidate && (Array.IndexOf(other.inputs, input) >= 0 - || input.StartsWith(other.path[..(other.path.LastIndexOf('/') + 1)], StringComparison.Ordinal)))) + foreach (string input in candidate.inputs.Where(path => ( + path.StartsWith(directory, StringComparison.Ordinal) + && path.StartsWith("tests/", StringComparison.Ordinal) && path.EndsWith(".cs", StringComparison.Ordinal) + )) + ) { + if (!projects.Any(other => ( + other != candidate && (Array.IndexOf(other.inputs, input) >= 0 + || input.StartsWith(other.path[..(other.path.LastIndexOf('/') + 1)], StringComparison.Ordinal)) + ))) { excluded.Add(input); + } } } return excluded.Order(StringComparer.Ordinal).ToArray(); @@ -48,12 +57,16 @@ internal static Dictionary Read(string assembly) MethodDefinition method = metadata.GetMethodDefinition(methodHandle); string[] hosts = Hosts(method.GetCustomAttributes()); if (hosts.Length == 0) + { hosts = typeHosts; + } if (hosts.Length != 0) { string key = name + "." + metadata.GetString(method.Name); if (contracts.TryGetValue(key, out string[]? existing) && !existing.SequenceEqual(hosts)) + { throw new InvalidDataException($"Overloaded test methods declare ambiguous OS contracts: {key}"); + } contracts[key] = hosts; } } @@ -77,21 +90,31 @@ string[] Hosts(CustomAttributeHandleCollection handles) EntityHandle parent = attribute.Constructor.Kind switch { HandleKind.MemberReference => metadata.GetMemberReference((MemberReferenceHandle)attribute.Constructor).Parent, - HandleKind.MethodDefinition => metadata.GetMethodDefinition((MethodDefinitionHandle)attribute.Constructor).GetDeclaringType(), + HandleKind.MethodDefinition => metadata + .GetMethodDefinition((MethodDefinitionHandle)attribute.Constructor) + .GetDeclaringType(), _ => default }; if (parent.Kind == HandleKind.TypeReference) { TypeReference type = metadata.GetTypeReference((TypeReferenceHandle)parent); if (metadata.GetString(type.Namespace) != "System.Runtime.Versioning" - || metadata.GetString(type.Name) != "SupportedOSPlatformAttribute") + || metadata.GetString(type.Name) != "SupportedOSPlatformAttribute" + ) { continue; + } BlobReader value = metadata.GetBlobReader(attribute.Value); if (value.ReadUInt16() != 1) + { throw new InvalidDataException("Invalid compiled test host contract."); + } string host = value.ReadSerializedString() ?? string.Empty; if (host is not ("windows" or "macos" or "linux")) - throw new InvalidDataException($"Unsupported test host contract '{host}'; declare an explicit supported OS without a version."); + { + throw new InvalidDataException( + $"Unsupported test host contract '{host}'; declare an explicit supported OS without a version." + ); + } hosts.Add(host); } } @@ -102,7 +125,9 @@ string[] Hosts(CustomAttributeHandleCollection handles) internal static bool Applies(string[] hosts) { if (hosts.Any(static host => host is not ("windows" or "macos" or "linux"))) + { throw new InvalidDataException("Unknown test host requirement."); + } return hosts.Any(static host => host switch { "windows" => OperatingSystem.IsWindows(), diff --git a/tools/Inno.Tooling.Validation/ValidationWorkspace.cs b/tools/Inno.Tooling.Validation/ValidationWorkspace.cs index 26b0a6b40..53842fd61 100644 --- a/tools/Inno.Tooling.Validation/ValidationWorkspace.cs +++ b/tools/Inno.Tooling.Validation/ValidationWorkspace.cs @@ -21,12 +21,18 @@ CancellationToken cancellation ) { source = Path.GetFullPath(source); if (!Directory.Exists(source)) + { throw new InvalidDataException("Retained compilation outputs are unavailable."); + } if (Directory.EnumerateFileSystemEntries(plan.artifacts).Any()) + { throw new InvalidDataException("Retained outputs require a fresh owned workspace; existing outputs cannot be overwritten."); + } string[] files = PathBoundary.EnumerateFiles(source).ToArray(); if (files.Length == 0) + { throw new InvalidDataException("Retained compilation output discovery is empty."); + } foreach (string file in files) { cancellation.ThrowIfCancellationRequested(); @@ -49,27 +55,43 @@ internal static async Task AcquireReadAsync( ValidationPlan plan, CancellationToken cancellation ) { - string parent = Path.GetDirectoryName(plan.artifacts) ?? throw new InvalidDataException("A validation output owner requires a parent directory."); + string parent = Path.GetDirectoryName(plan.artifacts) + ?? throw new InvalidDataException("A validation output owner requires a parent directory."); ValidationInputs.Resolve(plan.root, Path.GetRelativePath(plan.root, parent)); string owner = Path.Combine(parent, "owner.lock"); string leaf = plan.artifacts + ".lock"; if (!File.Exists(owner) || !File.Exists(leaf)) + { throw new InvalidDataException("Required validation output ownership is absent; evidence cannot adopt an unknown directory."); - return await CoordinatedFileLease.AcquireAsync(owner, leaf, Timeout.InfiniteTimeSpan, shared: true, cancellationToken: cancellation).ConfigureAwait(false); + } + return await CoordinatedFileLease.AcquireAsync( + owner, + leaf, + Timeout.InfiniteTimeSpan, + shared: true, + cancellationToken: cancellation + ).ConfigureAwait(false); } internal static async Task AcquireAsync( ValidationPlan plan, CancellationToken cancellation ) { - string parent = Path.GetDirectoryName(plan.artifacts) ?? throw new InvalidDataException("A validation output owner requires a parent directory."); + string parent = Path.GetDirectoryName(plan.artifacts) + ?? throw new InvalidDataException("A validation output owner requires a parent directory."); ValidationInputs.Resolve(plan.root, Path.GetRelativePath(plan.root, parent)); - string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetRelativePath(plan.root, parent).Replace('\\', '/')))); + string key = Convert.ToHexStringLower( + SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetRelativePath(plan.root, parent).Replace('\\', '/'))) + ); var publisher = new BuildCachePublisher(parent, BuildCacheArtifactRole.ReusableWorkspace); BuildCacheOwnerCatalog.Register(plan.root, parent, "validation-workspaces-" + key, publisher.role, cancellation); using FileLease activity = await publisher.AcquireUseAsync(cancellation).ConfigureAwait(false); - CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync(Path.Combine(parent, "owner.lock"), - plan.artifacts + ".lock", Timeout.InfiniteTimeSpan, cancellationToken: cancellation).ConfigureAwait(false); + CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync( + Path.Combine(parent, "owner.lock"), + plan.artifacts + ".lock", + Timeout.InfiniteTimeSpan, + cancellationToken: cancellation + ).ConfigureAwait(false); try { publisher.BeginWorkingDirectory(plan.artifacts, plan.artifacts + ".lock", null, cancellation); From 4f8b775383fcc14029dff18c6e61d1607427966e Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 19:52:01 +0000 Subject: [PATCH 09/33] chore(git): skip the C# layout commit in blame --- .git-blame-ignore-revs | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..e05b18f2f --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# style(csharp): apply the rulebook layout to all handwritten C# +9a88abf2030410838978c6a1be82c7612e99d9d8 From 0f4baa5efdb2472ef7a7db2b9707b1370c6fda0e Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 22:04:07 +0000 Subject: [PATCH 10/33] feat(tooling): check and fix typing, literal, attribute and comment style rules Add nine rulebook rules to the style command, each with fix and exemption tests: E-01 local types, M-04 target-typed field initializers, E-07 string.Empty, E-11 lambda parameters, E-10 numeric literals, M-05 attributes, D-02/D-04 XML documentation layout, D-05 comments and B-09 one statement per line. Record overloaded equality operators as an E-04 exception in the rulebook. --- .../rulebook/csharp-style/16-exceptions.md | 1 + .editorconfig | 90 +++++ .../StyleCommandTests.cs | 360 +++++++++++++++++- .../Style/Rules/AttributeStyleRule.cs | 94 +++++ .../Style/Rules/ChainStyleRule.cs | 2 +- .../Style/Rules/CommentStyleRule.cs | 78 ++++ .../Rules/DocumentationLayoutStyleRule.cs | 162 ++++++++ .../Style/Rules/EmbeddedBraceStyleRule.cs | 2 +- .../Style/Rules/EmptyStringStyleRule.cs | 50 +++ .../Style/Rules/FieldInitializerStyleRule.cs | 81 ++++ .../Style/Rules/FileTextStyleRule.cs | 10 +- .../Style/Rules/LambdaParameterStyleRule.cs | 46 +++ .../Style/Rules/LineWidthStyleRule.cs | 13 +- .../Style/Rules/LocalTypeStyleRule.cs | 98 +++++ .../Style/Rules/NumericLiteralStyleRule.cs | 118 ++++++ .../Style/Rules/ParameterCloseStyleRule.cs | 2 +- .../Style/Rules/ParameterListStyleRule.cs | 6 +- .../Style/Rules/StatementLineStyleRule.cs | 103 +++++ .../Style/Rules/TrailingCommaStyleRule.cs | 2 +- .../Style/Rules/UsingOrderStyleRule.cs | 2 +- .../Style/StyleEngine.cs | 11 +- .../Style/StyleLayout.cs | 4 +- .../Style/StyleLines.cs | 2 +- 23 files changed, 1314 insertions(+), 23 deletions(-) create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/AttributeStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/CommentStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/DocumentationLayoutStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/EmptyStringStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/FieldInitializerStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/LambdaParameterStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/LocalTypeStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/NumericLiteralStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/StatementLineStyleRule.cs diff --git a/.agents/rulebook/csharp-style/16-exceptions.md b/.agents/rulebook/csharp-style/16-exceptions.md index 79c827d19..2768f7aa8 100644 --- a/.agents/rulebook/csharp-style/16-exceptions.md +++ b/.agents/rulebook/csharp-style/16-exceptions.md @@ -20,5 +20,6 @@ The following cases follow an external contract. Do not rename or reformat them | Unsplittable string literals | Length beyond the line width (F-04) | paths, URLs | | Generator templates and their tests | `global::` and fully qualified names required by the generation protocol | | | Source text used as test data | Its own formatting (TS-03) | | +| Overloaded equality operators | `== null` and `!= null` where the type defines the result of the comparison (E-04) | `EngineObject`, whose destroyed instances compare equal to `null` | Keep each exception as small as possible: it covers the name or the layout bound by the contract, and the rest of the file follows the rulebook. diff --git a/.editorconfig b/.editorconfig index 411c8916c..88cec5f9e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -25,6 +25,96 @@ dotnet_diagnostic.CS1573.severity = warning dotnet_diagnostic.CS1591.severity = warning dotnet_diagnostic.IDE0005.severity = warning +# N-01: file-scoped namespaces. +csharp_style_namespace_declarations = file_scoped +dotnet_diagnostic.IDE0161.severity = warning +# T-01: every type and member states its accessibility. +dotnet_style_require_accessibility_modifiers = for_non_interface_members +dotnet_diagnostic.IDE0040.severity = warning +# T-02: modifier order. +csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async,partial +dotnet_diagnostic.IDE0036.severity = warning +# T-05: structs are readonly when they can be. +csharp_style_prefer_readonly_struct = true +dotnet_diagnostic.IDE0250.severity = warning +# M-02: one expression is an expression body; constructors use a block. +csharp_style_expression_bodied_methods = true +csharp_style_expression_bodied_properties = true +csharp_style_expression_bodied_indexers = true +csharp_style_expression_bodied_operators = true +csharp_style_expression_bodied_accessors = true +csharp_style_expression_bodied_local_functions = true +csharp_style_expression_bodied_lambdas = true +csharp_style_expression_bodied_constructors = false +dotnet_diagnostic.IDE0021.severity = warning +dotnet_diagnostic.IDE0022.severity = warning +dotnet_diagnostic.IDE0023.severity = warning +dotnet_diagnostic.IDE0024.severity = warning +dotnet_diagnostic.IDE0025.severity = warning +dotnet_diagnostic.IDE0026.severity = warning +dotnet_diagnostic.IDE0027.severity = warning +dotnet_diagnostic.IDE0053.severity = warning +dotnet_diagnostic.IDE0061.severity = warning +# I-02: collections use collection expressions. +dotnet_style_prefer_collection_expression = when_types_exactly_match +dotnet_diagnostic.IDE0028.severity = warning +dotnet_diagnostic.IDE0300.severity = warning +dotnet_diagnostic.IDE0301.severity = warning +dotnet_diagnostic.IDE0302.severity = warning +dotnet_diagnostic.IDE0303.severity = warning +dotnet_diagnostic.IDE0304.severity = warning +dotnet_diagnostic.IDE0305.severity = warning +# E-01, E-02: locals state their type. 'var' with 'new T(...)' is checked by 'InnoEngine.Build style'. +csharp_style_var_for_built_in_types = false +csharp_style_var_when_type_is_apparent = true +csharp_style_var_elsewhere = false +dotnet_diagnostic.IDE0008.severity = warning +# E-03: built-in types use keywords. +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true +dotnet_diagnostic.IDE0049.severity = warning +# E-04: null checks use patterns. +dotnet_style_prefer_is_null_check_over_reference_equality_method = true +csharp_style_prefer_not_pattern = true +dotnet_diagnostic.IDE0041.severity = warning +dotnet_diagnostic.IDE0083.severity = warning +# E-07: common values. +csharp_prefer_simple_default_expression = true +csharp_style_pattern_matching_over_as_with_null_check = true +csharp_style_pattern_matching_over_is_with_cast_check = true +csharp_style_conditional_delegate_call = true +dotnet_diagnostic.IDE0034.severity = warning +dotnet_diagnostic.IDE0019.severity = warning +dotnet_diagnostic.IDE0020.severity = warning +dotnet_diagnostic.IDE0038.severity = warning +dotnet_diagnostic.IDE1005.severity = warning +dotnet_diagnostic.IDE0100.severity = warning +dotnet_diagnostic.CA2200.severity = suggestion +# E-05: argument validation uses the ThrowIf helpers. +dotnet_diagnostic.CA1510.severity = suggestion +dotnet_diagnostic.CA1511.severity = suggestion +dotnet_diagnostic.CA1512.severity = suggestion +dotnet_diagnostic.CA1513.severity = suggestion +# E-09: identifiers use nameof; string operations state their comparison and culture. +dotnet_diagnostic.CA1507.severity = suggestion +dotnet_diagnostic.CA1304.severity = suggestion +dotnet_diagnostic.CA1305.severity = suggestion +dotnet_diagnostic.CA1307.severity = suggestion +dotnet_diagnostic.CA1309.severity = suggestion +dotnet_diagnostic.CA1310.severity = suggestion +dotnet_diagnostic.CA1311.severity = suggestion +# E-11: lambdas that capture nothing are static. +csharp_prefer_static_anonymous_function = true +dotnet_diagnostic.IDE0320.severity = warning +# E-12: using declarations. +csharp_prefer_simple_using_statement = true +dotnet_diagnostic.IDE0063.severity = warning +# T-03: internal classes without derived types are sealed. +dotnet_diagnostic.CA1852.severity = suggestion +# X-05: asynchronous code. +dotnet_diagnostic.CA2007.severity = suggestion +dotnet_diagnostic.CA2016.severity = suggestion + dotnet_naming_rule.properties_are_camel_case.symbols = properties dotnet_naming_rule.properties_are_camel_case.style = camel_case dotnet_naming_rule.properties_are_camel_case.severity = warning diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs index 701a34005..6e671ee29 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs @@ -734,6 +734,337 @@ internal void Run() } """ ) + }, + { + "E-01", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Probe value = new Probe(); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var value = new Probe(); + } + } + """ + ) + }, + { + "M-04", + Source( + """ + internal sealed class Probe + { + private readonly List m_values = new List(); + private int m_first = 1, m_second = 2; + } + """ + ), + Source( + """ + internal sealed class Probe + { + private readonly List m_values = new(); + private int m_first = 1; + private int m_second = 2; + } + """ + ) + }, + { + "E-07", + Source( + """ + internal sealed class Probe + { + internal string Run(string value = "") + { + string text = ""; + return text + value; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal string Run(string value = "") + { + string text = string.Empty; + return text + value; + } + } + """ + ) + }, + { + "E-11", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Func twice = (value) => value * 2; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + Func twice = value => value * 2; + } + } + """ + ) + }, + { + "E-10", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + float ratio = 1.0F; + uint mask = 0XFFu; + int count = 1000000; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + float ratio = 1f; + uint mask = 0xFFu; + int count = 1_000_000; + } + } + """ + ) + }, + { + "M-05", + Source( + """ + [Serializable, Obsolete()] + internal sealed class Probe + { + [ObsoleteAttribute] internal void Run() {} + } + """ + ), + Source( + """ + [Serializable] + [Obsolete] + internal sealed class Probe + { + [Obsolete] + internal void Run() {} + } + """ + ) + }, + { + "D-02", + Source( + """ + /// Runs the probe. + internal sealed class Probe + { + /// The value. + /// The input. + /// + /// + /// Returns null. + /// + internal object Run(object value) => null; + } + """ + ), + Source( + """ + /// + /// Runs the probe. + /// + internal sealed class Probe + { + /// + /// Returns . + /// + /// + /// The input. + /// + /// + /// The value. + /// + internal object Run(object value) => null; + } + """ + ) + }, + { + "D-05", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + int value = 1; //The first value. + Use(value); + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run() + { + // The first value. + int value = 1; + Use(value); + } + } + """ + ) + }, + { + "B-09", + Source( + """ + internal sealed class Probe + { + internal void Run(int kind) + { + int first = 1; int second = 2; + switch (kind) + { + case 0: Use(first); break; + default: Use(second); break; + } + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal void Run(int kind) + { + int first = 1; + int second = 2; + switch (kind) + { + case 0: + Use(first); + break; + default: + Use(second); + break; + } + } + } + """ + ) + } + }; + + public static TheoryData Kept() + => new() + { + { + "B-09", + Source( + """ + internal sealed class Probe + { + internal Probe( + float m11, + float m12, + float m21, + float m22 + ) { + this.m11 = m11; this.m12 = m12; + this.m21 = m21; this.m22 = m22; + } + } + """ + ) + }, + { + "E-01", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + var pair = new { name = "probe", count = 1 }; + var values = new int[4]; + int count = values.Length; + } + } + """ + ) + }, + { + "E-07", + Source( + """ + internal sealed class Probe + { + private const string C_NONE = ""; + + internal string Run(string value = "") + => value switch + { + "" => C_NONE, + _ => value + }; + } + """ + ) + }, + { + "E-10", + Source( + """ + internal sealed class Probe + { + internal void Run() + { + decimal price = 1.50m; + double ratio = 1.0; + int year = 2026; + } + } + """ + ) } }; @@ -765,6 +1096,28 @@ string after } } + [Theory] + [MemberData(nameof(Kept))] + public void ExemptConstructsAreNeitherReportedNorRewritten( + string rule, + string text + ) { + string root = CreateRoot(); + try + { + string path = Path.Combine(root, "src", "Probe.cs"); + File.WriteAllText(path, text); + + Assert.Equal(0, StyleCommand.Execute(["check", root, "--rule", rule])); + Assert.Equal(0, StyleCommand.Execute(["fix", root])); + Assert.Equal(text, File.ReadAllText(path)); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + [Theory] [InlineData("src/Generated/Probe.cs", "internal sealed class Probe { }\n")] [InlineData("src/Probe.cs", "// \ninternal sealed class Probe { }\n")] @@ -882,10 +1235,9 @@ public void PathsFromLimitsTheRunToTheListedSources() [InlineData("format", ".")] [InlineData("check", ".", "--rule")] [InlineData("check", ".", "--unknown", "value")] - public void InvalidArgumentsAreRejected(params string[] arguments) - { - Assert.Throws(() => StyleCommand.Execute(arguments)); - } + public void InvalidArgumentsAreRejected(params string[] arguments) => Assert.Throws( + () => StyleCommand.Execute(arguments) + ); private static string CreateRoot() { diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/AttributeStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/AttributeStyleRule.cs new file mode 100644 index 000000000..35d4b0ef0 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/AttributeStyleRule.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// M-05: one attribute per pair of brackets, on its own line above the declaration, without the 'Attribute' +// suffix and without empty parentheses. An attribute on a parameter stays on the line of the parameter. +internal sealed class AttributeStyleRule : StyleRule +{ + private const string C_ID = "M-05"; + + private const string C_SUFFIX = "Attribute"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((int position, string message, StyleEdit _) in Violations(source)) + { + findings.Add(source.Finding(C_ID, position, message)); + } + } + + // Edits of different kinds can touch the same list, so each round applies the first kind that is present. + internal override IReadOnlyList Fix(StyleSource source) + => Violations(source) + .GroupBy(static item => item.message, StringComparer.Ordinal) + .Select(static group => group.Select(static item => item.edit).ToArray()) + .FirstOrDefault() ?? []; + + private static IEnumerable<(int position, string message, StyleEdit edit)> Violations(StyleSource source) + { + foreach (AttributeListSyntax list in source.root.DescendantNodes().OfType()) + { + bool isInline = list.Parent is not (MemberDeclarationSyntax or CompilationUnitSyntax or LocalFunctionStatementSyntax); + var indent = new string(' ', source.Indentation(list.SpanStart)); + if (list.Attributes.Count > 1) + { + string target = list.Target is null ? string.Empty : list.Target.ToString().TrimEnd() + " "; + string separator = isInline ? " " : "\n" + indent; + string text = string.Join(separator, list.Attributes.Select(attribute => "[" + target + attribute + "]")); + yield return (list.SpanStart, "Write one attribute per pair of brackets.", new(list.SpanStart, list.Span.End, text)); + } + + foreach (AttributeSyntax attribute in list.Attributes) + { + SimpleNameSyntax name = attribute.Name switch + { + QualifiedNameSyntax qualified => qualified.Right, + AliasQualifiedNameSyntax alias => alias.Name, + SimpleNameSyntax simple => simple, + _ => throw new InvalidOperationException($"The attribute name '{attribute.Name}' has an unknown form.") + }; + string identifier = name.Identifier.Text; + if (identifier.Length > C_SUFFIX.Length && identifier.EndsWith(C_SUFFIX, StringComparison.Ordinal)) + { + yield return ( + attribute.SpanStart, + "Omit the 'Attribute' suffix.", + new(name.Identifier.Span.End - C_SUFFIX.Length, name.Identifier.Span.End, string.Empty) + ); + } + + if (attribute.ArgumentList is { Arguments.Count: 0 } arguments) + { + yield return (attribute.SpanStart, "Omit the empty parentheses.", new( + arguments.SpanStart, + arguments.Span.End, + string.Empty + )); + } + } + + if (isInline) continue; + SyntaxToken close = list.CloseBracketToken; + SyntaxToken next = close.GetNextToken(); + if (next.Span.Length > 0 && source.LineNumber(next.SpanStart) == source.LineNumber(close.SpanStart)) + { + yield return ( + list.SpanStart, + "Write the attribute on its own line above the declaration.", + new(close.Span.End, next.SpanStart, "\n" + indent) + ); + } + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ChainStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ChainStyleRule.cs index 3c2aca117..4bdb535cc 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/ChainStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ChainStyleRule.cs @@ -85,7 +85,7 @@ internal override IReadOnlyList Fix(StyleSource source) if (index == 0 || !IsCall(links[index - 1])) { // The first call keeps the statement line unless its own arguments are broken and calls follow it. - var arguments = ((InvocationExpressionSyntax)links[index].Parent!).ArgumentList; + ArgumentListSyntax arguments = ((InvocationExpressionSyntax)links[index].Parent!).ArgumentList; bool isSplit = source.LineNumber(arguments.OpenParenToken.SpanStart) != source.LineNumber( arguments.CloseParenToken.SpanStart ); diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/CommentStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/CommentStyleRule.cs new file mode 100644 index 000000000..bab33ff69 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/CommentStyleRule.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// D-05: a comment is on its own line above the code it explains, and '//' is followed by one space. +internal sealed class CommentStyleRule : StyleRule +{ + private const string C_ID = "D-05"; + + private const string C_PREFIX = "//"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((SyntaxTrivia comment, bool isTrailing) in Violations(source)) + { + findings.Add( + source.Finding( + C_ID, + comment.SpanStart, + isTrailing ? "Move the comment to its own line above the code." : "Write one space after '//'." + ) + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + var movedLines = new HashSet(); + foreach ((SyntaxTrivia comment, bool isTrailing) in Violations(source)) + { + if (!isTrailing) + { + edits.Add(new(comment.SpanStart + C_PREFIX.Length, comment.SpanStart + C_PREFIX.Length, " ")); + continue; + } + + TextLine line = source.Line(comment.SpanStart); + if (!movedLines.Add(line.LineNumber)) continue; + string code = source.content[line.Start..comment.SpanStart]; + string indent = code[..(code.Length - code.TrimStart().Length)]; + edits.Add(new(line.Start, line.Start, indent + comment + "\n")); + edits.Add(new(line.Start + code.TrimEnd().Length, comment.Span.End, string.Empty)); + } + + return edits; + } + + private static IEnumerable<(SyntaxTrivia comment, bool isTrailing)> Violations(StyleSource source) + { + foreach (SyntaxTrivia trivia in source.root.DescendantTrivia()) + { + if (!trivia.IsKind(SyntaxKind.SingleLineCommentTrivia)) continue; + TextLine line = source.Line(trivia.SpanStart); + if (source.content[line.Start..trivia.SpanStart].Trim().Length > 0) + { + yield return (trivia, true); + continue; + } + + string text = trivia.ToString(); + if (text.Length > C_PREFIX.Length && char.IsLetterOrDigit(text[C_PREFIX.Length])) + { + yield return (trivia, false); + } + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/DocumentationLayoutStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/DocumentationLayoutStyleRule.cs new file mode 100644 index 000000000..056ec24c3 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/DocumentationLayoutStyleRule.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// D-02 and D-04: every documentation element is expanded over separate lines, elements follow the tag order, +// a block has no empty lines, and references use the short forms. +internal sealed partial class DocumentationLayoutStyleRule : StyleRule +{ + private const string C_ID = "D-02"; + + private const string C_EXTERIOR = "///"; + + private static readonly string[] TAG_ORDER = ["summary", "typeparam", "param", "returns", "value", "exception", "remarks"]; + + // Elements whose inner line breaks and indentation carry meaning. + private static readonly string[] PRESERVED = [" C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (StyleEdit edit in Fix(source)) + { + findings.Add(source.Finding(C_ID, edit.start, "Expand the documentation elements, order them and remove empty lines.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + foreach (SyntaxTrivia trivia in source.root.DescendantTrivia()) + { + if (!trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)) continue; + if (trivia.GetStructure() is not DocumentationCommentTriviaSyntax comment) continue; + string original = source.content[trivia.FullSpan.Start..trivia.FullSpan.End]; + string? normal = Normalize(source, trivia, comment, original); + if (normal is not null && !string.Equals(normal, original, StringComparison.Ordinal)) + { + edits.Add(new(trivia.FullSpan.Start, trivia.FullSpan.End, normal)); + } + } + + return edits; + } + + private static string? Normalize( + StyleSource source, + SyntaxTrivia trivia, + DocumentationCommentTriviaSyntax comment, + string original + ) { + if (comment.ContainsDiagnostics) return null; + var elements = new List<(int rank, int order, List lines)>(); + IReadOnlyList signature = SignatureNames(trivia.Token.Parent); + foreach (XmlNodeSyntax node in comment.Content) + { + switch (node) + { + case XmlTextSyntax text: + if (StripExterior(text.ToFullString()).Any(static line => line.Trim().Length > 0)) return null; + break; + case XmlEmptyElementSyntax empty: + if (empty.ToString().Contains('\n')) return null; + elements.Add((Rank(empty.Name.ToString(), null, signature), elements.Count, [References(empty.ToString())])); + break; + case XmlElementSyntax element: + if (element.StartTag.ToString().Contains('\n') || element.EndTag.IsMissing) return null; + string inner = source.content[element.StartTag.Span.End..element.EndTag.SpanStart]; + bool isPreserved = PRESERVED.Any(marker => inner.Contains(marker, StringComparison.Ordinal)); + var lines = new List { element.StartTag.ToString() }; + List content = StripExterior(inner) + .Select(line => isPreserved ? (line.StartsWith(' ') ? line[1..] : line).TrimEnd() : References(line.Trim())) + .ToList(); + while (content.Count > 0 && content[0].Length == 0) + { + content.RemoveAt(0); + } + while (content.Count > 0 && content[^1].Length == 0) + { + content.RemoveAt(content.Count - 1); + } + if (!isPreserved) content.RemoveAll(static line => line.Length == 0); + lines.AddRange(content); + lines.Add(element.EndTag.ToString()); + string? name = element.StartTag.Attributes + .OfType() + .FirstOrDefault()?.Identifier.Identifier.ValueText; + elements.Add((Rank(element.StartTag.Name.ToString(), name, signature), elements.Count, lines)); + break; + default: + return null; + } + } + + if (elements.Count == 0) return null; + var indent = new string(' ', source.Column(trivia.FullSpan.Start)); + IEnumerable ordered = elements + .OrderBy(static element => element.rank) + .ThenBy(static element => element.order) + .SelectMany(static element => element.lines) + .Select(static line => line.Length == 0 ? C_EXTERIOR : C_EXTERIOR + " " + line); + return string.Join("\n" + indent, ordered) + (original.EndsWith('\n') ? "\n" : string.Empty); + } + + private static IEnumerable StripExterior(string text) + { + foreach (string line in text.Split('\n')) + { + string trimmed = line.TrimStart(); + yield return trimmed.StartsWith(C_EXTERIOR, StringComparison.Ordinal) ? trimmed[C_EXTERIOR.Length..] : line; + } + } + + private static int Rank( + string tag, + string? name, + IReadOnlyList signature + ) { + int group = Array.IndexOf(TAG_ORDER, tag); + if (group < 0) group = TAG_ORDER.Length; + int position = name is null ? -1 : signature.ToList().IndexOf(name); + // Parameters follow the signature; an unknown name keeps its place after the known ones. + return group * 1000 + (tag is "param" or "typeparam" ? (position < 0 ? 999 : position) : 0); + } + + private static IReadOnlyList SignatureNames(SyntaxNode? owner) + { + SyntaxNode? declaration = owner + ?.AncestorsAndSelf() + .FirstOrDefault(static node => node is MemberDeclarationSyntax or LocalFunctionStatementSyntax); + if (declaration is null) return []; + IEnumerable typeParameters = declaration.ChildNodes() + .OfType() + .SelectMany(static list => list.Parameters) + .Select(static parameter => parameter.Identifier.ValueText); + IEnumerable parameters = declaration.ChildNodes() + .OfType() + .SelectMany(static list => list.Parameters) + .Select(static parameter => parameter.Identifier.ValueText); + return typeParameters.Concat(parameters).ToArray(); + } + + // D-04: a self-closing tag has no space before '/>', and keywords use 'langword'. + private static string References(string line) + => KeywordPattern().Replace(SelfClosingPattern().Replace(line, "/>"), ""); + + [GeneratedRegex(@"\s+/>")] + private static partial Regex SelfClosingPattern(); + + [GeneratedRegex("(null|true|false)")] + private static partial Regex KeywordPattern(); +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/EmbeddedBraceStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/EmbeddedBraceStyleRule.cs index 874e2e5a2..374bf39d0 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/EmbeddedBraceStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/EmbeddedBraceStyleRule.cs @@ -35,7 +35,7 @@ internal override IReadOnlyList Fix(StyleSource source) { // Innermost bodies first: an outer body is braced once its content has settled. if (violations.Any(other => other.body != body && body.Span.Contains(other.body.Span))) continue; - string indent = new(' ', source.Indentation(owner.GetFirstToken().SpanStart)); + var indent = new string(' ', source.Indentation(owner.GetFirstToken().SpanStart)); SyntaxToken previous = body.GetFirstToken().GetPreviousToken(); SyntaxToken last = body.GetLastToken(); SyntaxToken next = last.GetNextToken(); diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/EmptyStringStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/EmptyStringStyleRule.cs new file mode 100644 index 000000000..c3de4dfb3 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/EmptyStringStyleRule.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// E-07: an empty string is written 'string.Empty' wherever a constant is not required. +internal sealed class EmptyStringStyleRule : StyleRule +{ + private const string C_ID = "E-07"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (LiteralExpressionSyntax literal in EmptyStrings(source.root)) + { + findings.Add(source.Finding(C_ID, literal.SpanStart, "Write 'string.Empty' for an empty string.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + => EmptyStrings(source.root).Select(static literal => new StyleEdit(literal.SpanStart, literal.Span.End, "string.Empty")).ToArray(); + + private static IEnumerable EmptyStrings(SyntaxNode root) + { + foreach (SyntaxNode node in root.DescendantNodes()) + { + if (node is not LiteralExpressionSyntax literal || !literal.IsKind(SyntaxKind.StringLiteralExpression)) + { + continue; + } + if (literal.Token.Text != "\"\"") continue; + if (literal.Ancestors().Any(IsConstantContext)) continue; + yield return literal; + } + } + + // These positions require a compile-time constant, which 'string.Empty' is not. + private static bool IsConstantContext(SyntaxNode node) + => node is AttributeSyntax or ParameterSyntax or PatternSyntax or CaseSwitchLabelSyntax or EnumMemberDeclarationSyntax + || node is FieldDeclarationSyntax field && field.Modifiers.Any(SyntaxKind.ConstKeyword) + || node is LocalDeclarationStatementSyntax local && local.Modifiers.Any(SyntaxKind.ConstKeyword); +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/FieldInitializerStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/FieldInitializerStyleRule.cs new file mode 100644 index 000000000..1515040b7 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/FieldInitializerStyleRule.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// M-04: a field or property initializer writes its type once, and one declaration declares one variable. +internal sealed class FieldInitializerStyleRule : StyleRule +{ + private const string C_ID = "M-04"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (ObjectCreationExpressionSyntax creation in Repeated(source.root)) + { + findings.Add(source.Finding(C_ID, creation.SpanStart, "Write 'new(...)' when the declaration already states the type.")); + } + + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (node is VariableDeclarationSyntax { Variables.Count: > 1, Parent: FieldDeclarationSyntax + or LocalDeclarationStatementSyntax } declaration + ) { + findings.Add(source.Finding(C_ID, declaration.SpanStart, "Declare one variable per declaration.")); + } + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + foreach (ObjectCreationExpressionSyntax creation in Repeated(source.root)) + { + edits.Add(new(creation.NewKeyword.Span.End, creation.Type.Span.End, creation.ArgumentList is null ? "()" : string.Empty)); + } + + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (node is not VariableDeclarationSyntax { Variables.Count: > 1 } declaration) continue; + if (declaration.Parent is not (FieldDeclarationSyntax or LocalDeclarationStatementSyntax)) continue; + SyntaxNode statement = declaration.Parent; + if (!source.IsFirstOnLine(statement.GetFirstToken()) || statement.ToString().Contains('\n')) continue; + string prefix = source.content[statement.SpanStart..declaration.Type.Span.End]; + string separator = ";\n" + new string(' ', source.Indentation(statement.SpanStart)) + prefix + " "; + for (int index = 0; index < declaration.Variables.SeparatorCount; index++) + { + SyntaxToken comma = declaration.Variables.GetSeparator(index); + edits.Add(new(comma.SpanStart, declaration.Variables[index + 1].SpanStart, separator)); + } + } + + return edits; + } + + private static IEnumerable Repeated(SyntaxNode root) + { + foreach (SyntaxNode node in root.DescendantNodes()) + { + (TypeSyntax? type, ExpressionSyntax? value) = node switch + { + VariableDeclarationSyntax { Variables.Count: 1, Parent: FieldDeclarationSyntax } declaration + => (declaration.Type, declaration.Variables[0].Initializer?.Value), + PropertyDeclarationSyntax property => (property.Type, property.Initializer?.Value), + _ => (null, null) + }; + if (type is null || value is not ObjectCreationExpressionSyntax creation) continue; + if (Compact(type) != Compact(creation.Type)) continue; + yield return creation; + } + } + + private static string Compact(SyntaxNode node) + => string.Concat(node.ToString().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/FileTextStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/FileTextStyleRule.cs index 01a0ffc3c..bc7c5d28b 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/FileTextStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/FileTextStyleRule.cs @@ -37,7 +37,7 @@ private static List Scan(StyleSource source) var violations = new List(); if (content.Length > 0 && content[0] == '\uFEFF') { - violations.Add(new(0, 1, "Remove the byte order mark.", "")); + violations.Add(new(0, 1, "Remove the byte order mark.", string.Empty)); } int blankRun = 0; @@ -52,7 +52,7 @@ private static List Scan(StyleSource source) if (textEnd > lineStart && content[textEnd - 1] == '\r') { textEnd--; - AddUnlessProtected(textEnd, textEnd + 1, "Use LF line endings.", ""); + AddUnlessProtected(textEnd, textEnd + 1, "Use LF line endings.", string.Empty); } int indentEnd = lineStart; @@ -68,11 +68,11 @@ private static List Scan(StyleSource source) // The whole surplus line is removed, including its line break. if (blankRun > 1 && next > lineStart) { - AddUnlessProtected(lineStart, next, "Keep at most one consecutive blank line.", ""); + AddUnlessProtected(lineStart, next, "Keep at most one consecutive blank line.", string.Empty); } else if (textEnd > lineStart) { - AddUnlessProtected(lineStart, textEnd, "Remove trailing whitespace.", ""); + AddUnlessProtected(lineStart, textEnd, "Remove trailing whitespace.", string.Empty); } } else @@ -92,7 +92,7 @@ private static List Scan(StyleSource source) if (trimmedEnd < textEnd) { - AddUnlessProtected(trimmedEnd, textEnd, "Remove trailing whitespace.", ""); + AddUnlessProtected(trimmedEnd, textEnd, "Remove trailing whitespace.", string.Empty); } } diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/LambdaParameterStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/LambdaParameterStyleRule.cs new file mode 100644 index 000000000..2d49c608f --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/LambdaParameterStyleRule.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// E-11: a lambda with one untyped parameter writes it without parentheses. +internal sealed class LambdaParameterStyleRule : StyleRule +{ + private const string C_ID = "E-11"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (ParenthesizedLambdaExpressionSyntax lambda in Violations(source.root)) + { + findings.Add(source.Finding(C_ID, lambda.SpanStart, "Write a single lambda parameter without parentheses.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + => Violations(source.root) + .Select(static lambda => new StyleEdit( + lambda.ParameterList.SpanStart, + lambda.ParameterList.Span.End, + lambda.ParameterList.Parameters[0].Identifier.Text + )) + .ToArray(); + + private static IEnumerable Violations(SyntaxNode root) + => root.DescendantNodes() + .OfType() + .Where(static lambda => ( + lambda.ReturnType is null + && lambda.AttributeLists.Count == 0 + && lambda.ParameterList.Parameters.Count == 1 + && lambda.ParameterList.Parameters[0] is { Type: null, Default: null, AttributeLists.Count: 0, Modifiers.Count: 0 } + && !lambda.ParameterList.DescendantTrivia().Any(static trivia => trivia.IsDirective || trivia.ToString().Contains('/')) + )); +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/LineWidthStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/LineWidthStyleRule.cs index 435355d60..60e34b5a8 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/LineWidthStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/LineWidthStyleRule.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; @@ -97,7 +98,11 @@ IReadOnlyList protectedSpans continue; } if (parameters.SpanStart < line.Start || parameters.Span.End > line.End) continue; - var list = new StyleList(parameters.OpenParenToken, parameters.CloseParenToken, parameters.Parameters.ToArray()); + var list = new StyleList( + parameters.OpenParenToken, + parameters.CloseParenToken, + parameters.Parameters.ToArray() + ); return StyleLayout.Expand(source, list, protectedSpans); } @@ -258,7 +263,7 @@ TextLine line SyntaxTrivia trivia = source.root.FindTrivia(position); if (trivia.Span.Length > 0 && !trivia.IsKind(SyntaxKind.WhitespaceTrivia)) { - longest = System.Math.Max(longest, System.Math.Min(trivia.Span.End, line.End) - position); + longest = Math.Max(longest, Math.Min(trivia.Span.End, line.End) - position); position = trivia.Span.End; continue; } @@ -274,8 +279,8 @@ TextLine line static node => node is InterpolatedStringExpressionSyntax or LiteralExpressionSyntax ); int end = literal is null ? token.Span.End : literal.Span.End; - if (literal is not null) longest = System.Math.Max(longest, System.Math.Min(end, line.End) - position); - position = System.Math.Max(end, position + 1); + if (literal is not null) longest = Math.Max(longest, Math.Min(end, line.End) - position); + position = Math.Max(end, position + 1); } return line.End - line.Start - longest <= StyleLayout.C_HARD_WIDTH - 20; diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/LocalTypeStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/LocalTypeStyleRule.cs new file mode 100644 index 000000000..85f33710f --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/LocalTypeStyleRule.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// E-01: a local variable states its type, and uses 'var' exactly when its value is 'new T(...)' or 'new T[...]'. +internal sealed class LocalTypeStyleRule : StyleRule +{ + private const string C_ID = "E-01"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((VariableDeclarationSyntax declaration, string message, string? _) in Violations(source.root)) + { + findings.Add(source.Finding(C_ID, declaration.SpanStart, message)); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + foreach ((VariableDeclarationSyntax declaration, string _, string? created) in Violations(source.root)) + { + if (created is null) continue; + edits.Add(new(declaration.Type.SpanStart, declaration.Type.Span.End, "var")); + if (declaration.Variables[0].Initializer!.Value is ImplicitObjectCreationExpressionSyntax creation) + { + edits.Add(new(creation.NewKeyword.Span.End, creation.NewKeyword.Span.End, " " + created)); + } + } + + return edits; + } + + private static IEnumerable<(VariableDeclarationSyntax declaration, string message, string? created)> Violations(SyntaxNode root) + { + foreach (SyntaxNode node in root.DescendantNodes()) + { + if (node is not VariableDeclarationSyntax { Variables.Count: 1 } declaration) continue; + if (declaration.Parent is not (LocalDeclarationStatementSyntax or UsingStatementSyntax or ForStatementSyntax)) + { + continue; + } + if (declaration.Parent is LocalDeclarationStatementSyntax local && local.Modifiers.Any(SyntaxKind.ConstKeyword)) + { + continue; + } + ExpressionSyntax? value = declaration.Variables[0].Initializer?.Value; + if (value is null) continue; + if (declaration.Type.IsVar) + { + // A value built from an anonymous type has no name to state. + if (value is not (ObjectCreationExpressionSyntax or ArrayCreationExpressionSyntax) + && !value.DescendantNodesAndSelf().Any(static part => part is AnonymousObjectCreationExpressionSyntax) + ) { + yield return (declaration, "State the type of the local variable instead of 'var'.", null); + } + + continue; + } + + // A nullable or pointer declaration may differ from the created type, so it keeps its written type. + if (declaration.Type is NullableTypeSyntax or PointerTypeSyntax or RefTypeSyntax or ScopedTypeSyntax) + { + continue; + } + string written = Compact(declaration.Type); + switch (value) + { + case ImplicitObjectCreationExpressionSyntax: + yield return (declaration, "Write 'var' with 'new T(...)' for a local variable.", declaration.Type.ToString()); + break; + case ObjectCreationExpressionSyntax creation when Compact(creation.Type) == written: + yield return (declaration, "Write 'var' when the value is 'new T(...)'.", written); + break; + case ArrayCreationExpressionSyntax { Initializer: null } array + when declaration.Type is ArrayTypeSyntax arrayType + && Compact(array.Type.ElementType) == Compact(arrayType.ElementType) + && array.Type.RankSpecifiers.Count == arrayType.RankSpecifiers.Count: + yield return (declaration, "Write 'var' when the value is 'new T[...]'.", written); + break; + } + } + } + + private static string Compact(SyntaxNode node) + => string.Concat(node.ToString().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/NumericLiteralStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/NumericLiteralStyleRule.cs new file mode 100644 index 000000000..01be85837 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/NumericLiteralStyleRule.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Inno.Tooling.Architecture; + +// E-10: numeric literals use one spelling for suffixes, hexadecimal digits, digit groups and 'float' values. +internal sealed class NumericLiteralStyleRule : StyleRule +{ + private const string C_ID = "E-10"; + + private const int C_DECIMAL_GROUP = 3; + + private const int C_HEX_GROUP = 4; + + // A decimal value is grouped from this many digits on. + private const int C_MIN_GROUPED_DIGITS = 5; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((SyntaxToken token, string normal) in Violations(source.root)) + { + findings.Add(source.Finding(C_ID, token.SpanStart, $"Write the numeric literal as '{normal}'.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + => Violations(source.root).Select(static item => new StyleEdit(item.token.SpanStart, item.token.Span.End, item.normal)).ToArray(); + + private static IEnumerable<(SyntaxToken token, string normal)> Violations(SyntaxNode root) + { + foreach (SyntaxToken token in root.DescendantTokens()) + { + if (!token.IsKind(SyntaxKind.NumericLiteralToken)) continue; + string normal = Normalize(token.Text); + if (!string.Equals(normal, token.Text, StringComparison.Ordinal)) yield return (token, normal); + } + } + + internal static string Normalize(string text) + { + bool isHex = text.StartsWith("0x", StringComparison.OrdinalIgnoreCase); + bool isBinary = text.StartsWith("0b", StringComparison.OrdinalIgnoreCase); + if (isHex || isBinary) + { + int end = text.Length; + while (end > 2 && text[end - 1] is 'u' or 'U' or 'l' or 'L') + { + end--; + } + string digits = text[2..end]; + if (isHex) + { + digits = digits.ToUpperInvariant(); + if (!digits.Contains('_') && digits.Length > C_HEX_GROUP) digits = Group(digits, C_HEX_GROUP); + } + + return (isHex ? "0x" : "0b") + digits + IntegerSuffix(text[end..]); + } + + bool isReal = text.Contains('.') || text.Contains('e') || text.Contains('E'); + char last = text[^1]; + if (last is 'f' or 'F') + { + string body = text[..^1]; + if (body.Contains('.') && !body.Contains('e') && !body.Contains('E')) + { + body = body.TrimEnd('0'); + if (body.EndsWith('.')) body = body[..^1]; + if (body.Length == 0 || body[0] == '.') body = "0" + body; + } + + return body + "f"; + } + + if (last is 'd' or 'D' or 'm' or 'M') return text[..^1] + char.ToLowerInvariant(last); + if (isReal) return text; + int suffixStart = text.Length; + while (suffixStart > 0 && !char.IsAsciiDigit(text[suffixStart - 1])) + { + suffixStart--; + } + string integer = text[..suffixStart]; + if (!integer.Contains('_') && integer.Length >= C_MIN_GROUPED_DIGITS) integer = Group(integer, C_DECIMAL_GROUP); + return integer + IntegerSuffix(text[suffixStart..]); + } + + private static string IntegerSuffix(string suffix) + => suffix.Length switch + { + 0 => string.Empty, + 1 when suffix is "u" or "U" => "u", + 1 => "L", + _ => "UL" + }; + + private static string Group( + string digits, + int size + ) { + var parts = new List(); + for (int end = digits.Length; end > 0; end -= size) + { + parts.Add(digits[Math.Max(0, end - size)..end]); + } + + parts.Reverse(); + return string.Join('_', parts); + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ParameterCloseStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ParameterCloseStyleRule.cs index 4d24ae5b5..26f0672fc 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/ParameterCloseStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ParameterCloseStyleRule.cs @@ -80,7 +80,7 @@ SyntaxToken next switch (next.Kind()) { case SyntaxKind.SemicolonToken: - return ""; + return string.Empty; case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.WhereKeyword: return " "; diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ParameterListStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ParameterListStyleRule.cs index d709ad89a..699834d4e 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/ParameterListStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ParameterListStyleRule.cs @@ -62,7 +62,11 @@ internal override IReadOnlyList Fix(StyleSource source) foreach (ParameterListSyntax parameters in source.root.DescendantNodes().OfType()) { if (parameters.OpenParenToken.IsMissing || parameters.CloseParenToken.IsMissing) continue; - var list = new StyleList(parameters.OpenParenToken, parameters.CloseParenToken, parameters.Parameters.ToArray()); + var list = new StyleList( + parameters.OpenParenToken, + parameters.CloseParenToken, + parameters.Parameters.ToArray() + ); bool multiLine = source.LineNumber(list.open.SpanStart) != source.LineNumber(list.close.SpanStart); if (list.items.Count >= 2) { diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/StatementLineStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/StatementLineStyleRule.cs new file mode 100644 index 000000000..782b628ba --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/StatementLineStyleRule.cs @@ -0,0 +1,103 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// B-09: a line holds one statement, and the statement after a 'case' label starts on the next line. +internal sealed class StatementLineStyleRule : StyleRule +{ + private const string C_ID = "B-09"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((StatementSyntax statement, int _) in Violations(source)) + { + findings.Add(source.Finding(C_ID, statement.SpanStart, "Start the statement on its own line.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + var edits = new List(); + IReadOnlyList protectedSpans = source.ProtectedSpans(); + int fixedLine = -1; + foreach ((StatementSyntax statement, int indentation) in Violations(source)) + { + // Statements that share lines with an already moved statement wait for the next round. + int first = source.LineNumber(statement.SpanStart); + if (first <= fixedLine) continue; + int last = source.LineNumber(statement.Span.End); + edits.Add(new(statement.GetFirstToken().GetPreviousToken().Span.End, statement.SpanStart, "\n" + new string(' ', indentation))); + int delta = indentation - source.Indentation(statement.SpanStart); + for (int line = first + 1; delta != 0 && line <= last; line++) + { + StyleEdit? shift = StyleLayout.Shift(source, line, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + + fixedLine = last; + } + + return edits; + } + + private static IEnumerable<(StatementSyntax statement, int indentation)> Violations(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + SyntaxList statements; + SyntaxToken anchor; + int first; + switch (node) + { + // The first statement of a block is placed by the brace rules. + case BlockSyntax block: + (statements, anchor, first) = (block.Statements, block.OpenBraceToken, 1); + break; + case SwitchSectionSyntax section: + (statements, anchor, first) = (section.Statements, section.Labels[0].GetFirstToken(), 0); + break; + default: + continue; + } + + if (anchor.IsMissing || StyleLayout.IsInInterpolation(node) || IsGrid(source, statements)) continue; + int indentation = source.Indentation(anchor.SpanStart) + StyleLayout.C_INDENT; + for (int index = first; index < statements.Count; index++) + { + StatementSyntax statement = statements[index]; + SyntaxToken token = statement.GetFirstToken(); + if (source.IsFirstOnLine(token)) continue; + if (!StyleLayout.IsBlank(source.content, token.GetPreviousToken().Span.End, token.SpanStart)) continue; + yield return (statement, indentation); + } + } + } + + // Rows of assignments with the same number of columns write a numeric matrix, which keeps its rows. + private static bool IsGrid( + StyleSource source, + SyntaxList statements + ) { + if (statements.Count == 0 || statements.Any(static statement => !IsAssignment(statement))) return false; + int[] rows = statements + .GroupBy(statement => source.LineNumber(statement.SpanStart)) + .Select(static row => row.Count()) + .ToArray(); + return rows.Length > 1 && rows[0] > 1 && rows.All(row => row == rows[0]); + } + + private static bool IsAssignment(StatementSyntax statement) + => statement is ExpressionStatementSyntax { Expression: AssignmentExpressionSyntax assignment } + && assignment.IsKind(SyntaxKind.SimpleAssignmentExpression); +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/TrailingCommaStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/TrailingCommaStyleRule.cs index 8e12f6974..28a3103ac 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/TrailingCommaStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/TrailingCommaStyleRule.cs @@ -29,7 +29,7 @@ internal override IReadOnlyList Fix(StyleSource source) var edits = new List(); foreach (SyntaxToken comma in TrailingCommas(source.root)) { - edits.Add(new(comma.SpanStart, comma.Span.End, "")); + edits.Add(new(comma.SpanStart, comma.Span.End, string.Empty)); } return edits; diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/UsingOrderStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/UsingOrderStyleRule.cs index 030819361..537165fce 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/UsingOrderStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/UsingOrderStyleRule.cs @@ -55,7 +55,7 @@ private static (int start, int end, string text)? Expected(StyleSource source) foreach (UsingDirectiveSyntax directive in usings.OrderBy(Group).ThenBy(Tier).ThenBy(Key, StringComparer.Ordinal)) { int group = Group(directive); - if (previousGroup >= 0 && group != previousGroup) lines.Add(""); + if (previousGroup >= 0 && group != previousGroup) lines.Add(string.Empty); lines.Add(source.content[directive.SpanStart..directive.Span.End]); previousGroup = group; } diff --git a/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs b/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs index 0179aeafb..a1ec6de89 100644 --- a/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs +++ b/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs @@ -42,6 +42,7 @@ internal static class StyleEngine new LeadingOperatorStyleRule(), new ChainStyleRule(), new SingleLineBlockStyleRule(), + new StatementLineStyleRule(), new BraceListStyleRule(), new BraceStyleRule(), new EmptyBodyStyleRule(), @@ -50,7 +51,15 @@ internal static class StyleEngine new EmbeddedBraceStyleRule(), new LambdaBodyStyleRule(), new OperatorAlignmentStyleRule(), - new TrailingCommaStyleRule() + new TrailingCommaStyleRule(), + new LocalTypeStyleRule(), + new FieldInitializerStyleRule(), + new EmptyStringStyleRule(), + new LambdaParameterStyleRule(), + new NumericLiteralStyleRule(), + new AttributeStyleRule(), + new DocumentationLayoutStyleRule(), + new CommentStyleRule() ]; internal static IEnumerable EnumerateSources(string root) diff --git a/tools/Inno.Tooling.Architecture/Style/StyleLayout.cs b/tools/Inno.Tooling.Architecture/Style/StyleLayout.cs index 8813b9c65..aa42a63c4 100644 --- a/tools/Inno.Tooling.Architecture/Style/StyleLayout.cs +++ b/tools/Inno.Tooling.Architecture/Style/StyleLayout.cs @@ -82,7 +82,7 @@ IReadOnlyList protectedSpans ) { string content = source.content; int indentation = source.Indentation(list.open.SpanStart); - string argumentIndent = new(' ', indentation + C_INDENT); + var argumentIndent = new string(' ', indentation + C_INDENT); var edits = new List(); int previousEnd = list.open.Span.End; foreach (SyntaxNode argument in list.items) @@ -175,7 +175,7 @@ SyntaxToken close if (!IsBlank(gap, 0, gap.Length)) return null; if (gap.Contains('\n')) { - gap = Glues(token, next) ? "" : " "; + gap = Glues(token, next) ? string.Empty : " "; } builder.Append(gap); diff --git a/tools/Inno.Tooling.Architecture/Style/StyleLines.cs b/tools/Inno.Tooling.Architecture/Style/StyleLines.cs index 652186420..0b45e7e7c 100644 --- a/tools/Inno.Tooling.Architecture/Style/StyleLines.cs +++ b/tools/Inno.Tooling.Architecture/Style/StyleLines.cs @@ -24,7 +24,7 @@ internal static StyleEdit Remove( int line ) { TextLine textLine = source.text.Lines[line]; - return new(textLine.Start, textLine.EndIncludingLineBreak, ""); + return new(textLine.Start, textLine.EndIncludingLineBreak, string.Empty); } internal static StyleEdit InsertBefore( From 29c9414af2d944067c9875f9400a2b0ea14464c0 Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sat, 21 Nov 2026 22:04:18 +0000 Subject: [PATCH 11/33] style(csharp): apply the rulebook typing, null-check and qualification rules Apply the new style rules to all handwritten C#, together with the semantic rules that need symbol information: E-04 `is null` patterns (kept as `==` where a type overloads equality), E-08 `this.` in constructors, N-05 short names through usings or role-based aliases, and N-06 alias names. No behavior change. Generated and third-party sources are untouched. --- .../ShaderArtifactBuilder.cs | 24 +- .../ShaderBuildInputs.cs | 2 +- .../BgfxAuthoringProvider.cs | 4 +- .../BgfxGameContentCompiler.cs | 2 +- .../BgfxShaderCompilerProfile.cs | 2 +- .../BgfxTargetCapabilities.cs | 2 +- .../BgfxTextureTargetCompiler.cs | 7 +- .../Execution/ToolRunner.cs | 4 +- .../BgfxShaderIrGenerator.Source.cs | 8 +- .../Intermediate/BgfxShaderIrGenerator.cs | 5 +- .../BgfxShadercToolchain.Reflection.cs | 2 +- .../BgfxShadercToolchain.Typed.cs | 2 +- .../Sources/BgfxSourceLexer.cs | 8 +- .../Sources/BgfxSourcePreprocessor.cs | 16 +- .../BgfxBindingProject.cs | 3 +- .../BgfxBuildRequest.cs | 26 +- .../BgfxNativeBuild.cs | 12 +- .../BgfxToolsBuild.cs | 12 +- .../BgfxCommandEncoder.Geometry.cs | 4 +- .../BgfxDevice.FrameBuffers.cs | 4 +- .../BgfxDevice.Frames.cs | 4 +- .../BgfxDevice.Graphs.cs | 10 +- .../BgfxDevice.Readback.cs | 4 +- .../BgfxDevice.Resources.cs | 8 +- .../BgfxDevice.Retirement.cs | 6 +- .../BgfxDevice.Surfaces.cs | 16 +- .../BgfxDevice.Textures.cs | 2 +- .../BgfxDevice.Transients.cs | 2 +- .../Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs | 17 +- .../BgfxNativeCalls.cs | 196 +++----- .../BgfxRenderingBackendProvider.cs | 4 +- .../Desktop/CoreClrDeploymentCompiler.cs | 8 +- .../NativeAot/NativeAotDeploymentCompiler.cs | 8 +- .../Publishing/DotNetPublishExecutor.cs | 11 +- .../WebAssembly/MonoWasmDeploymentCompiler.cs | 14 +- .../Discovery/ReflectionTypeCatalogSource.cs | 10 +- .../DotNetAssemblyCatalogSource.cs | 12 +- .../DotNetModuleSource.cs | 17 +- .../Loading/ModuleLoadContext.cs | 6 +- .../Reloading/DotNetModuleLifetime.cs | 2 +- .../Discovery/ReflectionCollectionMetadata.cs | 18 +- .../Discovery/ReflectionObjectMetadata.cs | 13 +- .../Discovery/ReflectionStructMetadata.cs | 12 +- .../ReflectionSerializationMetadataSource.cs | 2 +- .../ContentCacheGeneration.cs | 29 +- .../ContentCachePublication.cs | 7 +- .../ContentCacheValidator.cs | 8 +- .../FileContentDeployment.cs | 2 +- .../FileContentPreparation.cs | 3 +- .../FileContentStore.cs | 6 +- .../FileSystemStorageBackendProvider.cs | 2 +- .../CImguizmoBuildUtils.cs | 6 +- .../ImGuizmoToolchain.cs | 12 +- .../ImGuizmoModuleProvider.cs | 2 +- .../BgfxImGuiRenderer.cs | 46 +- .../BgfxImGuiShaderArtifacts.cs | 3 +- .../ImGuiPresentationProvider.cs | 2 +- .../Sdl3PlatformApplicationImGuiExtensions.cs | 11 +- .../Context/PlatformImGuiContext.Clipboard.cs | 4 +- .../Context/PlatformImGuiContext.cs | 384 ++++++++------- .../ImGuiFont.cs | 12 +- .../Interop/ImGuiPlatformIoNative.cs | 14 +- .../Rendering/ImGuiPackedColor.cs | 40 +- .../Rendering/PlatformImGuiSdlRenderer.cs | 117 +++-- .../PlatformImGuiViewportBackend.Monitors.cs | 8 +- ...PlatformImGuiViewportBackend.Retirement.cs | 6 +- .../Viewports/PlatformImGuiViewportBackend.cs | 248 +++++----- .../NativeDeploymentIndex.cs | 2 +- .../MiniAudioBackendProvider.cs | 6 +- .../MiniAudioClipPreparation.cs | 8 +- .../MiniAudioClipSourceLease.cs | 2 +- .../MiniAudioDevice.cs | 8 +- .../MiniAudioDeviceOptions.cs | 2 +- .../MiniAudioEncodedArtifactCache.cs | 2 +- .../RmlUiDocumentFrontend.cs | 2 +- .../Inno.Adapter.UI.RmlUi/RmlUiBackend.cs | 20 +- .../RmlUiBackendProvider.cs | 2 +- .../RmlUiNativeErrors.cs | 6 +- .../Inno.Adapter.UI.RmlUi/RmlUiUtf8String.cs | 5 +- .../Api/Sdl3FolderDialog.cs | 6 +- .../Api/Sdl3WindowOperations.cs | 2 +- .../Sdl3PlatformApplication.Internal.cs | 283 ++++++----- .../Sdl3PlatformApplication.Windows.cs | 9 +- .../Sdl3PlatformBackendProvider.cs | 7 +- .../Sdl3PlatformWindow.Internal.cs | 27 +- .../FreeTypeHarfBuzzTextBackend.cs | 10 +- .../FreeTypeHarfBuzzTextBackendProvider.cs | 7 +- .../TextNativeOperations.cs | 6 +- .../Configuration/BindingDefinitionReader.cs | 2 +- .../Configuration/NativeBindingProfile.cs | 6 +- .../Generation/BindingGenerationOperation.cs | 16 +- .../Generation/BindingHostExecution.cs | 24 +- .../Generation/BindingNativeCompilation.cs | 21 +- .../NativeBindingGenerationIdentity.cs | 23 +- .../NativeBindingGenerator.Inputs.cs | 2 +- .../NativeBindingGenerator.cs | 2 +- .../BindingGenerationPublication.cs | 9 +- build/cli/Inno.Build.Cli/BuildApplication.cs | 32 +- build/cli/Inno.Build.Cli/BuildCommand.cs | 10 +- .../cli/Inno.Build.Cli/BuildCommandContext.cs | 18 +- build/cli/Inno.Build.Cli/BuildComposition.cs | 29 +- build/cli/Inno.Build.Cli/BuildWorkspace.cs | 4 +- .../Cleanup/ProductCleanPlan.cs | 3 +- .../Inno.Build.Cli/Commands/BindingCommand.cs | 2 +- .../Inno.Build.Cli/Commands/CleanCommand.cs | 3 +- .../Commands/EditorBuildCommand.cs | 3 +- .../Commands/NativeDependenciesCommand.cs | 23 +- .../Inno.Build.Cli/Commands/ShaderCommand.cs | 2 +- .../NativeBindingsVerification.cs | 10 +- .../NativeVerificationOptions.cs | 2 +- .../Inno.Build.Cli/ProjectBuildWorkflow.cs | 3 +- .../BuildDistribution.cs | 17 +- .../ManagedDeploymentCatalog.cs | 2 +- .../Inno.Build.Managed/ManagedDeploymentId.cs | 2 +- build/pipeline/Inno.Build/BuildPipeline.cs | 24 +- .../pipeline/Inno.Build/BuildSettingsStore.cs | 13 +- .../Inno.Build/Content/ContentPackWriter.cs | 8 +- .../Inno.Build/Game/GameBuildPipeline.cs | 8 +- .../Game/PlayerCodeCompositionWriter.cs | 3 +- .../Inno.Build/Pipeline/BuildFileSystem.cs | 4 +- .../Player/PlayerSupportPackCatalog.cs | 15 +- .../Plugins/PluginPackageBuilder.cs | 10 +- .../SdkScriptCompilationEnvironment.cs | 2 +- .../Snapshots/BuildSnapshotFingerprint.cs | 5 +- .../StandardNativeComponents.cs | 24 +- .../StandardNativeDeployment.cs | 2 +- .../StandardSupportPackRequirements.cs | 6 +- .../FilePlayerSupportPackPreparation.cs | 21 +- .../PlayerSupportPackPlan.cs | 3 +- .../PlayerSupportPackPlanningContext.cs | 6 +- .../PlayerSupportPackPreparationIdentity.cs | 3 +- .../PlayerSupportPackPreparationIndex.cs | 3 +- .../PlayerSupportPackPublisher.cs | 14 +- .../SourcePlayerSupportPackProvisioner.cs | 18 +- .../BuildTaskRuntimeTask.cs | 24 +- .../PublishTaskHostTask.cs | 3 +- .../RestoreOwnedProjectTask.cs | 6 +- .../TaskRuntimeBootstrapOwner.cs | 6 +- .../TaskRuntimeRequestKey.cs | 27 +- .../Inno.Build.Tasks/CompileShaderTask.cs | 12 +- .../Inno.Build.Tasks/GenerateBindingsTask.cs | 14 +- .../PrepareProductNativeTask.cs | 16 +- .../PublishSupportPackTask.cs | 2 +- .../BuildArtifactManifest.cs | 4 +- .../BuildArtifactOptions.cs | 19 +- .../Cache/BackendPrebuiltArchive.cs | 12 +- .../Cache/BuildArtifactReadLease.cs | 11 +- .../Cache/BuildArtifactWriteLease.cs | 11 +- .../Cache/BuildCacheArtifactDescriptor.cs | 6 +- .../Cache/BuildCacheCleanupPlan.cs | 8 +- .../Cache/BuildCacheInventory.cs | 8 +- .../Cache/BuildCacheInventoryProgress.cs | 2 +- .../Cache/BuildCachePolicy.cs | 3 +- .../Cache/BuildCachePublisher.cs | 26 +- .../Cache/BuildCacheRetirement.cs | 9 +- .../Cache/NativeArtifactTransfer.cs | 6 +- .../NativeDependencyManifest.Aggregates.cs | 8 +- .../Cache/NativeDependencyManifest.cs | 8 +- .../Cache/NativeDependencySource.cs | 15 +- .../PhysicalToolchainWorkspaceProvider.cs | 4 +- .../BuildMaintenanceApplication.cs | 4 +- .../Managed/ManagedBuildExecution.cs | 8 +- .../Managed/ManagedBuildInputReader.cs | 2 +- .../Managed/ManagedBuildInputSnapshot.cs | 13 +- .../Managed/ManagedInputEvaluation.cs | 8 +- .../ManagedInputEvaluatorPreparation.cs | 2 +- .../Native/ComponentNativeProductExecutor.cs | 2 +- .../Native/NativeBindingCMake.cs | 4 +- .../NativeBindingGenerationDescriptor.cs | 6 +- .../Native/NativeBindingGenerationRequest.cs | 2 +- .../Native/NativeBindingGenerationResult.cs | 34 +- .../Native/NativeBindingInputPaths.cs | 2 +- .../Native/NativeBuildFingerprint.cs | 2 +- .../Native/NativeBuildInputState.cs | 9 +- .../Native/NativeBuildProduct.cs | 4 +- .../Native/NativeBuildRecipe.cs | 4 +- .../Native/NativeCMakeSource.cs | 5 +- .../Native/NativeComponentBuildOptions.cs | 6 +- .../Native/NativeInputMaterializer.cs | 4 +- .../Native/NativeInputSnapshot.cs | 8 +- .../Native/NativeInputVerificationScope.cs | 4 +- .../Native/NativeToolchainPreparation.cs | 6 +- .../Native/NativeToolchainSelection.cs | 8 +- .../Native/ProductNativeDeployment.cs | 24 +- .../Native/ProductNativePreparation.cs | 3 +- .../NativeBuildContext.cs | 19 +- .../ToolchainEnvironment.cs | 12 +- entry/InnoEngine.Editor/Program.cs | 3 +- .../EmscriptenToolchainResolver.cs | 8 +- .../BrowserWasm32NativeProductExecutor.cs | 4 +- .../BrowserWasm32PlayerSupportPackSource.cs | 16 +- .../Targets/BrowserWasm32GameBuildTarget.cs | 10 +- .../EmscriptenNativeToolchainProvider.cs | 2 +- .../BrowserWasm32BgfxShaderProfiles.cs | 2 +- .../BrowserWasm32Sdl3HostIntegration.cs | 15 +- .../BrowserWasm32StorageBackendProvider.cs | 7 +- .../Host/MacOSArm64BuildHostProvider.cs | 2 +- .../MacOSArm64PlayerSupportPackSource.cs | 18 +- .../MacOSArm64SupportPackValidator.cs | 6 +- .../Targets/MacOSArm64GameBuildTarget.cs | 10 +- .../MacOSArm64NativeToolchainProvider.cs | 2 +- .../MacOSArm64EditorComposition.cs | 14 +- .../MacOSArm64BgfxBuildProfile.cs | 14 +- .../Products/MacOSArm64NativeProducts.cs | 4 +- .../MacOSArm64Sdl3HostIntegration.cs | 25 +- .../MacOSArm64PlayerContentSource.cs | 10 +- .../Host/WindowsBuildHostProvider.cs | 2 +- .../Workspace/WindowsToolchainDirectory.cs | 10 +- .../WindowsToolchainWorkspaceProvider.cs | 6 +- .../WindowsX64PlayerSupportPackSource.cs | 18 +- .../WindowsX64SupportPackValidator.cs | 8 +- .../Targets/WindowsX64GameBuildTarget.cs | 10 +- .../WindowsX64NativeToolchainProvider.cs | 2 +- .../WindowsX64EditorComposition.cs | 14 +- .../WindowsX64BgfxBuildProfile.cs | 14 +- .../Products/WindowsX64NativeProducts.cs | 4 +- .../WindowsX64Sdl3HostIntegration.cs | 20 +- .../WindowsX64PlayerContentSource.cs | 10 +- .../Inno.Adapter.Audio/AudioBackendCatalog.cs | 6 +- .../EventInputBackendProvider.cs | 2 +- .../Inno.Adapter.Input/InputBackendCatalog.cs | 6 +- .../PlatformBackendCatalog.cs | 6 +- .../PlatformNativeHandles.cs | 8 +- .../PresentationBackendCatalog.cs | 6 +- .../RenderingAuthoringBackendCatalog.cs | 2 +- .../RenderingBackendCatalog.cs | 2 +- .../StorageBackendCatalog.cs | 6 +- .../Inno.Adapter.Text/TextBackendCatalog.cs | 6 +- .../ui/Inno.Adapter.UI/UiBackendCatalog.cs | 2 +- .../Animation/AnimationSubsystem.cs | 4 +- .../EngineSessionComposition.cs | 6 +- .../Creation/AssetCreationTemplate.cs | 5 +- .../Documents/AssetDraftDocuments.cs | 25 +- .../Editing/AssetEditingModule.Creation.cs | 26 +- .../Editing/AssetEditingModule.cs | 49 +- .../History/AssetHistoryData.cs | 2 +- .../History/AssetSourceArchive.cs | 2 +- .../AssetImportSettingsEdits.cs | 10 +- .../Samples/AssetSampleImportModule.cs | 2 +- .../Inno.Editor.Audio/IEditorAudioHost.cs | 6 +- .../Runtime/EditorExportService.cs | 12 +- .../Runtime/EditorPlayModeController.cs | 8 +- .../Runtime/EditorPlayModeModule.cs | 2 +- ...itorRenderTargetArtifactProvider.Drafts.cs | 14 +- .../EditorRenderTargetArtifactProvider.cs | 34 +- .../Pipelines/PipelineDocuments.cs | 14 +- .../EditorSceneWorkspace.Persistence.cs | 6 +- .../EditorSceneWorkspace.SourceChanges.cs | 2 +- .../Documents/SceneEdits.Elements.cs | 2 +- .../Documents/SceneEdits.Hierarchy.cs | 2 +- .../Documents/SceneEdits.History.cs | 2 +- .../Documents/SceneEdits.Objects.cs | 2 +- .../Documents/SceneEdits.Properties.cs | 11 +- .../Documents/SceneEdits.Selection.cs | 23 +- .../History/SceneDocumentHistoryData.cs | 4 +- .../History/SceneElementHistoryData.cs | 10 +- .../History/SceneElementHistoryHandler.cs | 2 +- .../History/SceneHierarchyHistoryData.cs | 6 +- .../History/ScenePropertyHistoryData.cs | 2 +- .../History/SceneScalarHistoryData.cs | 4 +- .../History/SceneScalarHistoryHandler.cs | 9 +- .../History/SceneSubtreeHistoryData.cs | 4 +- .../Runtime/EditorScripting.cs | 2 +- .../Materials/MaterialDocuments.cs | 18 +- .../Materials/ShaderParameterPresentation.cs | 18 +- .../Previews/ShaderPreviewProvider.cs | 18 +- .../Extensions/EditorModal.cs | 7 +- .../Extensions/EditorModule.cs | 26 +- .../Extensions/EditorPanel.cs | 26 +- .../Reloading/EditorReloadCoordinator.cs | 2 +- .../Inno.Editor.Core/Runtime/EditorContext.cs | 4 +- .../ConsoleFingerprint.cs | 5 +- .../EditorConsoleGroup.cs | 2 +- .../Inno.Editor.Graph/GraphCanvasState.cs | 3 +- .../GraphDocumentController.cs | 13 +- .../Inno.Editor.Graph/GraphHistory.cs | 2 +- .../BuiltInInspectorAttributeDrawers.cs | 59 ++- .../InspectorMemberMetadata.cs | 10 +- .../ObjectDrawing/DefaultInspectionDrawer.cs | 4 +- .../EditorCollectionUtility.cs | 18 +- .../MathematicsPropertyDrawers.cs | 20 +- .../PropertyDrawing/PropertyDrawerRegistry.cs | 2 +- .../SerializedPropertyRenderer.cs | 9 +- .../PropertyDrawing/StructPropertyDrawer.cs | 46 +- .../Actions/EditorAction.cs | 12 +- .../Actions/EditorActionRouter.cs | 2 +- .../Discovery/EditorExtensionActivator.cs | 2 +- .../Discovery/EditorExtensionCatalog.cs | 8 +- .../Documents/EditorDocumentContext.cs | 2 +- .../Documents/EditorDocumentService.cs | 10 +- .../DragDrop/EditorDragData.cs | 8 +- .../DragDrop/EditorDrop.cs | 2 +- .../Editing/EditorEditGesture.cs | 2 +- .../History/EditorHistory.cs | 6 +- .../History/EditorHistoryPayload.cs | 2 +- .../Menus/EditorMenuCatalog.cs | 6 +- .../Runtime/EditorInteractionRuntime.cs | 32 +- .../Runtime/EditorInteractions.cs | 12 +- .../Runtime/EditorPanelExtension.cs | 5 +- .../Viewport/EditorViewportTool.cs | 12 +- .../Definitions/ProjectSettingEditor.cs | 2 +- .../Runtime/EditorSettings.cs | 14 +- .../Runtime/EditorSettingsCatalog.cs | 2 +- .../Runtime/EditorSettingsHistory.cs | 2 +- .../Runtime/ProjectSettingsEditor.cs | 6 +- .../Runtime/ProjectSettingsHistory.cs | 2 +- .../EditorCommandLineOptions.cs | 5 +- .../Inno.Editor.Hosting/Hosting/EditorHost.cs | 13 +- .../Hosting/EditorLayer.cs | 14 +- .../Hosting/EditorRenderingHostService.cs | 4 +- .../Browser/FileBrowserChangeTracker.cs | 2 +- .../Browser/FileBrowserContextMenu.cs | 3 +- .../Browser/FileBrowserData.cs | 2 +- .../Browser/FileBrowserDragDrop.cs | 5 +- .../Browser/FileBrowserPanel.Filters.cs | 4 +- .../Browser/FileBrowserPanel.Grid.cs | 10 +- .../Browser/FileBrowserPanel.Layout.cs | 16 +- .../Browser/FileBrowserPanel.List.cs | 7 +- .../Browser/FileBrowserPanel.cs | 12 +- .../Browser/FileBrowserRename.cs | 5 +- .../Browser/FileBrowserTree.Rows.cs | 5 +- .../Browser/FileBrowserTree.cs | 2 +- .../Browser/FileBrowserUtility.cs | 2 +- .../Interactions/MoveAssetEntryDropHandler.cs | 6 +- .../Samples/AssetSampleImportModal.cs | 10 +- .../GameViewPanel.cs | 12 +- .../Interactions/ReorderSceneDropHandler.cs | 3 +- .../SavePrefabAssetDropHandler.cs | 5 +- .../Interactions/SaveSceneAssetDropHandler.cs | 5 +- .../Presentation/HierarchyPanel.Rows.cs | 5 +- .../Presentation/HierarchyPanel.cs | 2 +- .../Styling/HierarchyStyle.cs | 5 +- .../DragDrop/AssetReferenceDropHandler.cs | 9 +- .../Layers/GameLayersSetting.cs | 6 +- .../Presentation/InspectorCardControls.cs | 8 +- .../Presentation/InspectorTargetHeader.cs | 9 +- .../EngineObjectReferencePropertyDrawer.cs | 12 +- .../SceneInspectionPropertyEditService.cs | 2 +- .../Runtime/SceneInspectionModule.cs | 20 +- .../Styling/InspectorTargetStyle.cs | 2 +- .../Targets/GameObjectInspectionDrawer.cs | 2 +- .../Targets/GameSceneInspectionDrawer.cs | 2 +- .../Targets/GameTagsSetting.cs | 2 +- .../Targets/PipelineInspectionDrawer.cs | 24 +- .../Targets/SelectionInspectionDrawer.cs | 28 +- .../Console/ConsoleEntryImGuiIdentity.cs | 10 +- .../Console/ConsolePanel.Layout.cs | 16 +- .../Console/ConsolePanel.cs | 18 +- .../Console/ConsolePanelContent.cs | 18 +- .../Console/ConsoleView.cs | 4 +- .../Styling/ConsoleStyle.cs | 19 +- .../SceneViewPanel.cs | 36 +- .../Presentation/BuildSettingsPresentation.cs | 4 +- .../Presentation/SettingsModal.cs | 10 +- .../Presentation/SettingsPageView.cs | 20 +- .../Runtime/BuildSettingsHistory.cs | 2 +- .../Runtime/OpenSettingsAction.cs | 2 +- .../Runtime/SettingsEditSession.cs | 60 +-- .../Runtime/SettingsWindowModule.cs | 2 +- .../Styling/SettingsStyle.cs | 5 +- .../Canvas/ShaderEditorCanvas.Controls.cs | 53 +- .../Canvas/ShaderEditorCanvas.MiniMap.cs | 10 +- .../Canvas/ShaderEditorCanvas.Parameters.cs | 5 +- .../Canvas/ShaderEditorCanvas.PassSettings.cs | 22 +- .../Canvas/ShaderEditorCanvas.PortRepair.cs | 2 +- .../ShaderEditorCanvas.SourceSettings.cs | 18 +- .../Canvas/ShaderEditorCanvas.Target.cs | 2 +- .../Canvas/ShaderEditorCanvas.Techniques.cs | 7 +- .../Canvas/ShaderEditorCanvas.cs | 75 +-- .../ShaderEditorDocuments.CanvasEdits.cs | 2 +- .../ShaderEditorDocuments.Clipboard.cs | 5 +- .../ShaderEditorDocuments.Creation.cs | 24 +- .../Documents/ShaderEditorDocuments.cs | 59 +-- .../Inspection/ShaderInspectionDrawers.cs | 20 +- .../Interactions/ShaderCanvasActions.cs | 85 ++-- .../ShaderCanvasOrganizationActions.cs | 56 ++- .../Interactions/ShaderGraphAutoLayout.cs | 12 +- .../Presentation/ShaderCheckModal.cs | 8 +- .../ShaderEditorPanel.cs | 6 +- .../Inno.Editor.Panel.Stats/StatsPanel.cs | 11 +- .../AssetSelectionInspectionDrawer.cs | 4 +- .../Navigation/AssetBrowserModule.cs | 9 +- .../Navigation/AssetBrowserState.cs | 12 +- .../Canvas/GraphCanvasPointerController.cs | 2 +- .../Canvas/GraphCanvasView.Nodes.cs | 12 +- .../Canvas/GraphCanvasView.cs | 2 +- .../Inno.Editor.ImGui/Controls/ImGui.Input.cs | 5 +- .../Controls/Options/ImGuiButtonFlags.cs | 14 +- .../Controls/Options/ImGuiChildFlags.cs | 22 +- .../Controls/Options/ImGuiCol.cs | 128 ++--- .../Controls/Options/ImGuiColorEditFlags.cs | 66 +-- .../Controls/Options/ImGuiComboFlags.cs | 22 +- .../Controls/Options/ImGuiCond.cs | 12 +- .../Controls/Options/ImGuiFocusedFlags.cs | 16 +- .../Controls/Options/ImGuiHoveredFlags.cs | 44 +- .../Controls/Options/ImGuiInputTextFlags.cs | 54 ++- .../Controls/Options/ImGuiKey.cs | 332 ++++++------- .../Controls/Options/ImGuiMouseButton.cs | 10 +- .../Controls/Options/ImGuiMouseCursor.cs | 28 +- .../Controls/Options/ImGuiPopupFlags.cs | 28 +- .../Controls/Options/ImGuiSelectableFlags.cs | 18 +- .../Controls/Options/ImGuiSliderFlags.cs | 24 +- .../Controls/Options/ImGuiStyleVar.cs | 86 ++-- .../Controls/Options/ImGuiTabBarFlags.cs | 28 +- .../Controls/Options/ImGuiTabItemFlags.cs | 22 +- .../Controls/Options/ImGuiTableBgTarget.cs | 10 +- .../Controls/Options/ImGuiTableColumnFlags.cs | 58 +-- .../Controls/Options/ImGuiTableFlags.cs | 76 +-- .../Controls/Options/ImGuiTableRowFlags.cs | 6 +- .../Controls/Options/ImGuiTreeNodeFlags.cs | 46 +- .../Controls/Options/ImGuiWindowFlags.cs | 62 +-- .../Drawing/EditorDrawList.cs | 3 +- .../Drawing/ImGui.Drawing.cs | 17 +- .../presentation/Inno.Editor.ImGui/ImGui.cs | 65 +-- .../Properties/ScriptingApi.cs | 2 +- .../Runtime/EditorGameInputCapture.cs | 15 +- .../Runtime/EditorMenuRenderer.cs | 12 +- .../Runtime/EditorModalRenderer.cs | 10 +- .../Runtime/EditorUiInput.cs | 18 +- .../Runtime/EditorUiSession.cs | 11 +- .../Runtime/ImGuiEditorRuntime.cs | 17 +- .../Styling/EditorPalette.cs | 48 +- .../Styling/EditorStyleMetrics.cs | 8 +- .../Styling/EditorUiLayout.cs | 16 +- .../TextInput/EditorIconCatalog.cs | 9 +- .../Inno.Editor.ImGui/TextInput/ImGuiFont.cs | 7 +- .../Widgets/ImGuiWidget.Card.cs | 4 +- .../Widgets/ImGuiWidget.Clipping.cs | 2 +- .../Widgets/ImGuiWidget.ContextMenu.cs | 8 +- .../Widgets/ImGuiWidget.Controls.cs | 2 +- .../Widgets/ImGuiWidget.Dialog.cs | 12 +- .../Widgets/ImGuiWidget.DragDrop.cs | 14 +- .../Widgets/ImGuiWidget.Editing.cs | 5 +- .../Widgets/ImGuiWidget.Gizmo.cs | 21 +- .../Widgets/ImGuiWidget.HelpBox.cs | 8 +- .../Widgets/ImGuiWidget.InlineRename.cs | 7 +- .../Widgets/ImGuiWidget.Lifetime.cs | 6 +- .../Widgets/ImGuiWidget.Panel.cs | 17 +- .../Widgets/ImGuiWidget.Property.cs | 14 +- .../Widgets/ImGuiWidget.Search.cs | 6 +- .../Widgets/ImGuiWidget.Selection.cs | 32 +- .../Widgets/ImGuiWidget.Selector.cs | 6 +- .../Widgets/ImGuiWidget.Text.cs | 12 +- .../Widgets/ImGuiWidget.Tree.cs | 18 +- .../Widgets/ImGuiWidget.Trend.cs | 2 +- .../Materials/MaterialInspectionDrawer.cs | 60 +-- .../Materials/MaterialSelectionDrawer.cs | 33 +- .../Materials/ShaderPropertyInspector.cs | 10 +- .../Nodes/ShaderNodeDrawer.cs | 7 +- .../Previews/ShaderPreviews.cs | 16 +- .../Commands/CommandSearchModule.cs | 2 +- .../Exporting/GameExportModal.cs | 2 +- .../Exporting/GameExportProgressModal.cs | 11 +- .../Exporting/PluginExportModal.cs | 15 +- .../Scripting/ScriptCompilationModal.cs | 10 +- .../Settings/FramePacingSettings.cs | 3 +- .../Settings/IconSettings.cs | 2 +- .../Zoom/EditorZoomModule.cs | 16 +- .../Deployment/StaticPlayerModuleActivator.cs | 2 +- .../Inno.Player.Runtime/GamePlayerHost.cs | 4 +- .../Inno.Player.Runtime/PlayerApplication.cs | 8 +- src/composition/shell/Inno.Shell/Shell.cs | 2 +- .../AnimationBindingRuntime.cs | 2 +- .../AnimationClipSnapshot.cs | 6 +- .../AnimationRuntime.cs | 20 +- .../animation/Inno.Animation/Animation.cs | 12 +- .../AnimationPlaybackAllocator.cs | 6 +- .../Inno.Animation/AnimationTypes.cs | 6 +- .../Inno.Animation/IAnimationService.cs | 12 +- .../Inno.Assets.Pipeline/AssetCacheOptions.cs | 10 +- .../AssetPipeline.Artifacts.cs | 10 +- .../AssetPipeline.Changes.cs | 8 +- .../AssetPipeline.Discovery.cs | 2 +- .../AssetPipeline.Loading.cs | 2 +- .../AssetPipeline.Mutations.cs | 38 +- .../AssetPipeline.Retirement.cs | 2 +- .../Inno.Assets.Pipeline/AssetPipeline.cs | 26 +- .../AssetPipelineOptions.cs | 2 +- .../AssetSourceMountTransaction.cs | 2 +- .../Editing/AssetSourceStore.cs | 4 +- .../Artifacts/AssetArtifactManifest.cs | 26 +- .../Importing/Artifacts/AssetArtifactStore.cs | 15 +- .../Importing/AssetCatalogCandidate.cs | 5 +- .../Importing/AssetExportContext.cs | 6 +- .../Importing/AssetImportContext.cs | 14 +- .../Importing/AssetLoader.Catalog.cs | 4 +- .../Importing/AssetLoader.Dependencies.cs | 4 +- .../Importing/AssetLoader.Diagnostics.cs | 2 +- .../Importing/AssetLoader.ImportSettings.cs | 15 +- .../Importing/AssetLoader.Importing.cs | 13 +- .../Importing/AssetLoader.Loading.cs | 10 +- .../Importing/AssetLoader.Recovery.cs | 20 +- .../Importing/AssetLoader.Residency.cs | 30 +- .../Importing/AssetLoader.Retirement.cs | 4 +- .../Importing/AssetLoader.RuntimeExport.cs | 6 +- .../Importing/AssetLoader.Saving.cs | 14 +- .../Importing/AssetLoader.SourceChanges.cs | 2 +- .../Importing/AssetLoader.SourceIO.cs | 2 +- .../Importing/AssetLoader.cs | 24 +- .../Importing/Catalog/AssetCatalogSnapshot.cs | 7 +- .../Importing/Catalog/AssetSourceFileStamp.cs | 2 +- .../Importing/Catalog/AssetSourceMeta.cs | 15 +- .../Importing/Internal/AssetMeta.cs | 117 +++-- .../NativeAssetSourceSerialization.cs | 10 +- .../Sources/AssetChangeBatchNormalizer.cs | 2 +- .../Sources/AssetFileSystem.cs | 4 +- .../Sources/AssetPipeline.Samples.cs | 10 +- .../Sources/AssetPipeline.SourceMounts.cs | 5 +- .../Sources/AssetSample.cs | 9 +- .../Sources/AssetSampleImportTransaction.cs | 3 +- .../Sources/AssetSampleSnapshot.cs | 10 +- .../Sources/AssetSampleSourceRewriter.cs | 8 +- .../Sources/AssetSourceMount.cs | 4 +- .../Artifacts/ArtifactRetention.cs | 9 +- .../Inno.Assets/Artifacts/AssetArtifactKey.cs | 12 +- .../assets/Inno.Assets/AssetDependency.cs | 6 +- src/content/assets/Inno.Assets/AssetObject.cs | 20 +- src/content/assets/Inno.Assets/AssetPath.cs | 10 +- .../Runtime/AssetDatabase.Residency.cs | 12 +- .../Inno.Assets/Runtime/AssetDatabase.cs | 153 ++++-- .../Inno.Assets/Runtime/AssetResidency.cs | 25 +- .../Inno.Assets/Runtime/AssetRuntimeOwner.cs | 5 +- .../Inno.Assets/Runtime/ResidencyLease.cs | 5 +- .../AssetDependencyCollection.cs | 2 +- .../Serialization/IAssetReferenceResolver.cs | 3 +- .../deployment/Inno.Content/ContentKey.cs | 2 +- .../Inno.Content/ContentPackIndex.cs | 6 +- .../Inno.Content/ContentPackReader.cs | 8 +- .../Inno.Content/PackContentStore.cs | 32 +- .../ReferenceRecoveryChange.cs | 6 +- .../Importers/PrefabAssetImporter.cs | 10 +- .../Importers/SceneAssetImporter.cs | 10 +- .../scene/Inno.Scene/Assets/SceneAsset.cs | 10 +- .../Inno.Scene/Concrete/MissingGameSystem.cs | 2 +- .../scene/Inno.Scene/Core/EngineObject.cs | 6 +- .../scene/Inno.Scene/Core/GameObject.cs | 6 +- .../Core/GameTagSettingsComposer.cs | 2 +- .../scene/Inno.Scene/Layers/GameLayer.cs | 15 +- .../scene/Inno.Scene/Layers/GameLayerMask.cs | 24 +- .../Lifecycle/SceneSystemScheduler.cs | 2 +- .../Reloading/SceneReloadService.cs | 6 +- src/content/scene/Inno.Scene/SceneWorld.cs | 3 +- .../Converters/GameSceneConverter.cs | 2 +- .../Serialization/PrefabOverrideProcessor.cs | 4 +- .../Serialization/SceneElementState.cs | 38 +- .../SceneGraph/SceneGraphReferenceMap.cs | 6 +- .../SceneGraph/SceneGraphSerialization.cs | 18 +- .../SceneGraph/SceneGraphSourceIds.cs | 14 +- .../SceneGraph/ScenePropertyReferenceScope.cs | 4 +- .../ScenePropertySerialization.cs | 6 +- .../SceneSubtreeSerialization.cs | 12 +- .../Storage/SceneStructureSnapshot.cs | 5 +- .../IndexedObjectStore/IndexedObjectIndex.cs | 4 +- .../IndexedObjectStore/IndexedObjectKey.cs | 2 +- .../IndexedObjectStore/IndexedObjectQuery.cs | 23 +- .../IndexedObjectStore.Handles.cs | 6 +- .../IndexedObjectStore.Keys.cs | 28 +- .../IndexedObjectStore.OrderedQueries.cs | 20 +- .../IndexedObjectStore.Queries.cs | 92 ++-- .../IndexedObjectStore/IndexedObjectStore.cs | 28 +- .../KeyOrdering/SortedKeyOrdering.cs | 2 +- .../KeyStorage/MultiKeyStorage.cs | 18 +- .../KeyStorage/UniqueKeyStorage.cs | 6 +- .../IndexedObjectKeyCondition.cs | 20 +- .../IndexedObjectPredicateCondition.cs | 6 +- .../Inno.Core.Coroutines/CoroutineHandle.cs | 10 +- .../CoroutineScheduler.cs | 16 +- .../Inno.Core.Diagnostics/DiagnosticHub.cs | 5 +- .../DiagnosticLocation.cs | 12 +- .../DiagnosticReporter.cs | 2 +- .../Inno.Core.Diagnostics/DiagnosticSource.cs | 12 +- .../core/Inno.Core.Events/EventDispatcher.cs | 30 +- .../core/Inno.Core.Events/EventHub.cs | 20 +- .../core/Inno.Core.Events/Events/Event.cs | 34 +- .../Inno.Core.Events/Events/MouseEvents.cs | 10 +- .../core/Inno.Core.Execution/LifetimeScope.cs | 35 +- .../OwnerThreadExecution.cs | 8 +- .../Inno.Core.Execution/RetirementBarrier.cs | 13 +- .../core/Inno.Core.Graphs/GraphDocument.cs | 2 +- .../core/Inno.Core.IO/AtomicDirectory.cs | 24 +- .../core/Inno.Core.IO/AtomicFile.cs | 18 +- .../Inno.Core.IO/FileByteDocumentStore.cs | 18 +- src/foundation/core/Inno.Core.IO/FileLease.cs | 17 +- .../core/Inno.Core.IO/FileSystemRename.cs | 4 +- .../core/Inno.Core.IO/OwnedReadStream.cs | 30 +- .../Inno.Core.IO/ProcessOwnedDirectory.cs | 2 +- .../Inno.Core.IO/ReadOnlyByteDocumentStore.cs | 10 +- .../core/Inno.Core.Identity/Identity.cs | 6 +- .../Inno.Core.Identity/IdentityAllocator.cs | 7 +- .../Inno.Core.Identity/IdentityDomainId.cs | 3 +- .../core/Inno.Core.Identity/IdentityObject.cs | 4 +- .../Inno.Core.Identity/IdentityRegistry.cs | 21 +- .../Inno.Core.Identity/RuntimeIdentity.cs | 2 +- .../core/Inno.Core.Input/KeyCode.cs | 33 +- .../Internal/WorkStealingDeque.cs | 6 +- .../Inno.Core.Jobs/Internal/WorkerRuntime.cs | 6 +- .../Inno.Core.Jobs/JobSchedulerOptions.cs | 8 +- .../Systems/SingleThreadJobSystem.cs | 73 ++- .../Systems/WorkStealingJobSystem.cs | 95 ++-- src/foundation/core/Inno.Core.Layers/Layer.cs | 6 +- .../core/Inno.Core.Layers/LayerStack.cs | 5 +- .../core/Inno.Core.Logging/ConsoleLogSink.cs | 5 +- .../core/Inno.Core.Logging/FileLogSink.cs | 8 +- .../core/Inno.Core.Logging/LogRouter.cs | 18 +- .../core/Inno.Core.Logging/Logger.cs | 12 +- .../core/Inno.Core.Mathematics/Color.cs | 40 +- .../core/Inno.Core.Mathematics/MathHelper.cs | 406 ++++++++-------- .../core/Inno.Core.Mathematics/Matrix.cs | 295 +++++++----- .../core/Inno.Core.Mathematics/Quaternion.cs | 40 +- .../core/Inno.Core.Mathematics/Rect.cs | 57 ++- .../core/Inno.Core.Mathematics/RectInt.cs | 51 +- .../core/Inno.Core.Mathematics/SimdMath.cs | 40 +- .../core/Inno.Core.Mathematics/Vector2.cs | 12 +- .../core/Inno.Core.Mathematics/Vector2Int.cs | 6 +- .../core/Inno.Core.Mathematics/Vector3.cs | 46 +- .../core/Inno.Core.Mathematics/Vector3Int.cs | 9 +- .../core/Inno.Core.Mathematics/Vector4.cs | 45 +- .../core/Inno.Core.Mathematics/Vector4Int.cs | 12 +- .../SerializationConverterGenerator.cs | 2 +- .../SerializationMetadataGenerator.cs | 18 +- .../SerializationMetadataScope.cs | 9 +- .../SerializablePropertyAttribute.cs | 2 +- .../Capture/SerializationCaptureKeyBuilder.cs | 10 +- .../Context/SerializationContext.cs | 2 +- .../IO/SerializationWriter.cs | 23 +- .../Internal/BinarySerializationFormat.cs | 65 ++- .../Internal/ConverterRegistry.cs | 11 +- .../Internal/PropertySnapshotBinaryFormat.cs | 2 +- .../Internal/PropertySnapshotPipeline.cs | 7 +- .../Internal/SerializationNode.cs | 5 +- .../Internal/SerializationNodeReuse.cs | 2 +- .../Internal/SerializationOperation.cs | 2 +- .../Metadata/SerializationTypeMetadata.cs | 3 +- .../StaticSerializationMetadataSource.cs | 2 +- .../SerializationRegistry.cs | 18 +- .../SerializationSnapshot.cs | 13 +- .../SerializedIdentityRemapper.cs | 6 +- .../ProjectSettingContracts.cs | 2 +- .../Inno.Core.Settings/ProjectSettings.cs | 25 +- .../ProjectSettingsRegistry.cs | 8 +- .../ITypeCatalogRegistrar.cs | 14 +- .../Catalog/CompositeAssemblyUnloadProbe.cs | 8 +- .../Inno.Extensibility.Modules/ModuleHost.cs | 24 +- .../Reloading/AssemblyReloadSession.cs | 2 +- .../GenerationCoordinator.cs | 25 +- .../TypeCache/TypeCacheSnapshot.cs | 8 +- .../TypeCache/TypeCatalog.cs | 12 +- .../TypeCache/TypeIdentityRegistry.cs | 6 +- .../TypeCache/TypeQueryRegistry.cs | 33 +- .../TypeCache/TypeRef.cs | 6 +- .../Inno.Extensibility.Types/TypeRegistry.cs | 6 +- .../TypeRegistryCoordinator.cs | 6 +- .../RuntimeSubsystem.cs | 6 +- .../Inno.Runtime/Deployment/GameCodeModule.cs | 3 +- .../Deployment/RuntimeManifestEnvelope.cs | 4 +- .../engine/Inno.Runtime/Execution/Time.cs | 5 +- .../engine/Inno.Runtime/Hosting/EngineHost.cs | 15 +- .../Inno.Runtime/Hosting/EngineHostBuilder.cs | 8 +- .../Inno.Runtime/Hosting/RuntimeSession.cs | 9 +- .../Inno.Runtime/Hosting/SessionLogSink.cs | 4 +- .../StaticAssemblyCatalogSource.cs | 17 +- .../Registration/StaticModuleSource.cs | 20 +- .../Registration/StaticTypeCatalogSource.cs | 16 +- .../Subsystems/RuntimeSubsystemPipeline.cs | 9 +- .../Registration/RuntimeFactoryGenerator.cs | 11 +- .../RuntimeModuleCatalogGenerator.cs | 19 +- .../RuntimeSubsystemGenerator.cs | 8 +- .../Inno.Plugins.Authoring/PluginCatalog.cs | 2 +- .../PluginEnvironment.cs | 10 +- .../PluginSourceService.cs | 16 +- .../plugins/Inno.Plugins/PluginManifest.cs | 7 +- .../Compilation/FrameworkReferenceResolver.cs | 2 +- .../LogicalScriptingApiAnalyzer.cs | 9 +- .../Compilation/ScriptApiArtifactCache.cs | 2 +- .../Compilation/ScriptApiCatalog.cs | 7 +- .../ScriptApiDocumentationBuilder.cs | 9 +- .../Compilation/ScriptApiReferenceBuilder.cs | 2 +- .../Compilation/ScriptApiStubSourceBuilder.cs | 3 +- .../Compilation/ScriptApiUsingRewriter.cs | 2 +- .../Compilation/ScriptArtifactCache.cs | 2 +- .../ScriptAuthoringAnnotationRewriter.cs | 4 +- .../Compilation/ScriptCompilationResult.cs | 2 +- .../ScriptCompilerCacheSerialization.cs | 24 +- .../Compilation/ScriptCompilerEngine.cs | 42 +- .../ScriptDeploymentReferenceResolver.cs | 2 +- .../Compilation/ScriptSourceSet.cs | 5 +- .../Compilation/ScriptTypeAnalyzer.cs | 24 +- .../Compilation/ScriptTypeIdentity.cs | 2 +- .../SerializablePropertyOrderRewriter.cs | 37 +- .../Inno.Scripting.Compiler/ScriptCompiler.cs | 39 +- .../Inno.Scripting.Reload/ScriptReloadHost.cs | 34 +- .../Inno.Audio.Assets/AudioClipImporter.cs | 16 +- .../ArtifactAudioClipSource.cs | 6 +- .../Inno.Audio.Runtime/AudioClipRequest.cs | 8 +- .../Inno.Audio.Runtime/AudioContentOwner.cs | 2 +- .../AudioDeviceCandidate.cs | 5 +- .../AudioExtensionRegistry.cs | 6 +- .../audio/Inno.Audio.Runtime/AudioRuntime.cs | 32 +- .../Inno.Audio.Runtime/AudioVoiceOwner.cs | 2 +- .../Inno.Audio.Runtime/MutedAudioDevice.cs | 12 +- .../audio/Inno.Audio/AudioClipAsset.cs | 12 +- .../audio/Inno.Audio/AudioDeviceLimits.cs | 4 +- src/services/audio/Inno.Audio/AudioMixer.cs | 2 +- .../Compilation/ShaderCompilation.cs | 15 +- .../Compilation/ShaderGraphArtifact.cs | 43 +- .../Compilation/ShaderGraphCompilation.cs | 16 +- .../Compilation/ShaderLastGoodStore.cs | 5 +- .../Compilation/ShaderSourceBundle.cs | 23 +- .../Compilation/ShaderStageCompilation.cs | 9 +- .../Compilation/TextureTargetCompiler.cs | 3 +- .../Editing/ShaderGraphSourceStore.cs | 9 +- .../Importing/GeometryAssetImporter.cs | 3 +- .../Importing/GltfJson.cs | 3 +- .../Importing/GltfMeshParser.cs | 9 +- .../Importing/MaterialAssetImporter.cs | 3 +- .../Importing/RenderPipelineAssetImporter.cs | 3 +- .../RenderingAssetFormatException.cs | 3 +- .../Importing/ShaderAssetImporter.cs | 3 +- .../Importing/ShaderFunctionAsset.cs | 15 +- .../Importing/ShaderFunctionImporter.cs | 9 +- .../Importing/ShaderSourceImportSettings.cs | 18 +- .../Importing/TextureAssetImporter.cs | 11 +- .../Deployment/RenderShaderArtifact.cs | 11 +- .../Deployment/RenderShaderArtifactCodec.cs | 3 +- .../Deployment/RenderShaderPassArtifact.cs | 3 +- .../Deployment/RenderShaderStageArtifact.cs | 3 +- .../Deployment/RenderShaderVariant.cs | 3 +- .../Deployment/RenderTargetArtifactPath.cs | 3 +- .../Geometry/GeometryArtifact.cs | 5 +- .../Geometry/GeometryAssetRuntime.cs | 3 +- .../Geometry/GeometryData.cs | 3 +- .../Geometry/GeometrySection.cs | 3 +- .../Geometry/GeometryVertex.cs | 3 +- .../Materials/MaterialAsset.cs | 2 +- .../Materials/MaterialMetadataEntry.cs | 2 +- .../Materials/MaterialPassResolution.cs | 2 +- .../Materials/MaterialPassResolver.cs | 2 +- .../Materials/MaterialPropertyBlock.cs | 8 +- .../Materials/MaterialPropertyEntry.cs | 2 +- .../Materials/MaterialValue.cs | 4 +- .../Pipelines/RenderFeatureConfiguration.cs | 2 +- .../SerializedRenderExtensionState.cs | 14 +- ...SerializedRenderExtensionStateConverter.cs | 6 +- .../Shaders/ShaderAsset.cs | 16 +- .../Shaders/ShaderContractId.cs | 4 +- .../Shaders/ShaderDefinition.cs | 2 +- .../Shaders/ShaderDefinitionSnapshot.cs | 3 +- .../Shaders/ShaderDefinitionValidator.cs | 3 +- .../Shaders/ShaderDiagnostic.cs | 3 +- .../Shaders/ShaderKeywordDefinition.cs | 2 +- .../Shaders/ShaderMetadataEntry.cs | 2 +- .../Shaders/ShaderPassDefinition.cs | 2 +- .../Shaders/ShaderPassRoleId.cs | 4 +- .../Shaders/ShaderPropertyBindingOwner.cs | 2 +- .../Shaders/ShaderPropertyDefinition.cs | 2 +- .../Shaders/ShaderRenderState.cs | 8 +- .../Shaders/ShaderSourceLocation.cs | 3 +- .../Shaders/ShaderTechniqueDefinition.cs | 2 +- .../Shaders/ShaderTechniqueId.cs | 4 +- .../Shaders/ShaderTechniquePass.cs | 2 +- .../Textures/IRenderTextureArtifactSource.cs | 3 +- .../RenderTextureArtifactReference.cs | 3 +- .../Textures/RenderTextureArtifactSlot.cs | 3 +- .../Textures/TextureColorSpace.cs | 2 +- .../ContentRenderTargetArtifactProvider.cs | 8 +- .../IRenderTargetArtifactProvider.cs | 3 +- .../Deployment/RenderTargetArtifactStatus.cs | 3 +- .../GraphicsSettings.cs | 7 +- .../Models/IRenderModel.cs | 3 +- .../Models/RenderModelExtensionAttribute.cs | 3 +- .../Models/RenderModelOutput.cs | 3 +- .../Models/RenderOutputInput.cs | 3 +- .../Models/RenderOutputLayer.cs | 3 +- .../Models/RenderOutputRoute.cs | 3 +- .../Models/RenderOutputSession.cs | 3 +- .../Models/ViewContent.cs | 25 +- .../Pipelines/RenderExtensionStateContext.cs | 8 +- .../Pipelines/RenderFeatureContext.cs | 3 +- .../RenderFeatureExtensionAttribute.cs | 3 +- .../Pipelines/RenderPipeline.cs | 3 +- .../Pipelines/RenderPipelineContext.cs | 3 +- .../RenderPipelineExtensionAttribute.cs | 3 +- .../Pipelines/RenderPipelineFeature.cs | 3 +- .../Pipelines/RenderResourceMap.cs | 3 +- .../RenderExtensionRegistry.cs | 19 +- .../RenderFrameScratch.cs | 2 +- .../RenderFrameStatistics.cs | 3 +- .../RenderFrameUploadService.cs | 2 +- .../RenderLayerCompositor.cs | 2 +- .../RenderMaterialOwner.cs | 17 +- .../RenderPipelineGeneration.cs | 2 +- .../RenderResourceLimits.cs | 2 +- .../RenderResourceService.cs | 7 +- .../RenderRetirementQueue.cs | 5 +- .../RenderRuntime.Contributors.cs | 2 +- .../RenderRuntime.Diagnostics.cs | 6 +- .../RenderRuntime.Frames.cs | 2 +- .../RenderRuntime.Models.cs | 2 +- .../RenderRuntime.Pipelines.cs | 2 +- .../RenderRuntime.Presentation.cs | 2 +- .../RenderRuntime.Requests.cs | 7 +- .../RenderRuntime.Retirement.cs | 2 +- .../Inno.Rendering.Runtime/RenderRuntime.cs | 21 +- .../Requests/IRenderRequestSink.cs | 3 +- .../Requests/RenderFrameData.cs | 9 +- .../Requests/RenderRequest.cs | 3 +- .../Requests/RenderRequestProvider.cs | 7 +- .../Resources/IRenderResourceService.cs | 9 +- .../Resources/RenderGeometry.cs | 3 +- .../Resources/RenderGeometrySection.cs | 3 +- .../Resources/RenderMaterialPass.cs | 7 +- .../Resources/RenderPersistentResourceId.cs | 3 +- .../Resources/RenderResourceProvider.cs | 3 +- .../Resources/RenderTextureSubresourceData.cs | 3 +- .../Compilation/ShaderNodeCompilerCatalog.cs | 20 +- .../Compilation/ShaderNodeCompilerRegistry.cs | 5 +- .../Documents/ShaderGraphBindings.cs | 19 +- .../Documents/ShaderGraphClipboard.cs | 19 +- .../Documents/ShaderGraphDocument.cs | 34 +- .../Documents/ShaderGraphLiteral.cs | 15 +- .../Documents/ShaderGraphNodes.cs | 67 ++- .../Documents/ShaderGraphProgramCompiler.cs | 45 +- .../Documents/ShaderGraphTemplates.cs | 20 +- .../Documents/ShaderGraphType.cs | 36 +- .../Intermediate/ShaderIrBuilder.cs | 5 +- .../Intermediate/ShaderIrSemanticHash.cs | 3 +- .../Intermediate/ShaderIrStage.cs | 2 +- .../Sources/IShaderSourceFrontend.cs | 3 +- .../Sources/ShaderSourceFrontendCatalog.cs | 2 +- .../Sources/ShaderSourceFrontendRegistry.cs | 5 +- .../Sources/ShaderSourceModuleAnalysis.cs | 20 +- .../Sources/ShaderSourceType.cs | 4 +- .../Targets/ShaderTarget.cs | 8 +- .../Device/GraphicsCapabilities.cs | 26 +- .../Device/RecordedRenderCommandEncoder.cs | 74 ++- .../Device/RenderRasterState.cs | 2 +- .../Inno.Rendering/Device/RenderResources.cs | 14 +- .../Device/RenderSamplerState.cs | 6 +- .../Device/RenderVertexLayout.cs | 8 +- .../Graph/CompiledRenderGraph.cs | 25 +- .../Graph/RenderGraphBuilder.Mutations.cs | 2 +- .../Graph/RenderGraphBuilder.cs | 10 +- .../Graph/RenderGraphResourceAllocation.cs | 6 +- .../Graph/RenderGraphValidator.cs | 62 ++- .../Inno.Rendering/Graph/RenderPassBuilder.cs | 6 +- .../Shaders/ShaderPropertyId.cs | 2 +- .../Inno.Storage.Runtime/StorageRuntime.cs | 10 +- .../storage/Inno.Storage/StorageScope.cs | 2 +- .../text/Inno.Text.Assets/FontImporter.cs | 6 +- src/services/text/Inno.Text/FontAsset.cs | 8 +- .../ui/Inno.UI.Assets/UiDocumentFrontend.cs | 13 +- .../UiDocumentImportSettings.cs | 6 +- .../ui/Inno.UI.Assets/UiDocumentImporter.cs | 4 +- .../ui/Inno.UI/UiBackendCapabilities.cs | 4 +- src/services/ui/Inno.UI/UiDocumentAsset.cs | 2 +- src/services/ui/Inno.UI/UiTypes.cs | 3 +- .../AnimationRuntimeTests.cs | 5 +- .../AssetFileSystemChangeTests.cs | 14 +- .../AssetFileSystemTests.cs | 40 +- .../AssetLoaderTests.cs | 454 +++++++++--------- .../ImportSettingsTests.cs | 30 +- .../ImporterIntegrationTests.cs | 10 +- .../SettingsReferenceTests.cs | 28 +- .../DuplicateImporters.cs | 32 +- .../AudioClipImporterTests.cs | 16 +- .../AudioRuntimeTests.cs | 130 ++--- .../Inno.Audio.Tests/AudioContractTests.cs | 23 +- .../AudioScriptingApiTests.cs | 8 +- .../BgfxDeviceTests.cs | 49 +- .../BgfxShutdownTests.cs | 6 +- .../BgfxSurfaceRetirementTests.cs | 11 +- .../BgfxToolchainTests.cs | 9 +- .../ToolRunnerTests.cs | 4 +- .../BgfxShaderProfileTests.cs | 5 +- .../ToolRunnerTests.cs | 5 +- .../Inno.Native.Bgfx.Tests/BgfxInitTests.cs | 2 +- .../Inno.Testing.Bgfx/ShaderProfileFixture.cs | 34 +- .../ContentCacheCancellationTests.cs | 6 +- .../ContentCacheConcurrencyTests.cs | 2 +- .../ContentCacheFixture.cs | 4 +- .../ContentCacheIntegrityTests.cs | 16 +- .../ContentCacheRetirementTests.cs | 4 +- .../ImGuiAbiLayoutTests.cs | 2 +- .../Inno.Native.ImGui.Tests/ImGuiInitTests.cs | 8 +- .../ImGuiPlatformCallbackTests.cs | 30 +- .../ImGuizmoInitTests.cs | 4 +- .../EncodedAudioTestSource.cs | 2 +- .../EncodedContentTests.cs | 17 +- .../MiniAudioDeviceTests.cs | 40 +- .../UiServiceTests.cs | 6 +- .../HostIntegrationTests.cs | 4 +- .../Sdl3WindowOperationsTests.cs | 2 +- .../WindowOwnershipTests.cs | 16 +- .../WindowSurfaceTests.cs | 4 +- .../Inno.Native.Sdl3.Tests/Sdl3InitTests.cs | 10 +- .../BindingDefinitionTests.cs | 20 +- .../BindingGenerationBatchTests.cs | 100 ++-- .../BindingGenerationProcessTests.cs | 12 +- .../BindingSelectionLifetimeTests.cs | 12 +- .../NativeBindingGenerationTests.cs | 76 ++- .../NativeBindingProfileTests.cs | 21 +- .../DevelopmentEntryCommandTests.cs | 8 +- .../FileProductPublicationTests.cs | 4 +- .../GeneratorRestoreScopeTests.cs | 2 +- .../ManagedBuildInputSnapshotTests.cs | 13 +- .../NativeBindingCompilationTests.cs | 11 +- .../NativeBindingConfigurationTests.cs | 4 +- .../NuGetLoadedIdentityTests.cs | 5 +- .../OwnedRestoreTests.cs | 12 +- .../SolutionBootstrapOwnershipTests.cs | 2 +- .../TaskHostPublicationProcess.cs | 8 +- .../TaskHostPublicationTests.cs | 17 +- .../TaskPublisherBootstrapTests.cs | 4 +- .../TaskRegistrationBuildTests.cs | 3 +- .../TaskRestoreEvaluationTests.cs | 2 +- .../TaskRuntimeBuildTests.cs | 20 +- .../ProductNativeCostTests.cs | 8 +- .../StaticGraphRestoreTests.cs | 2 +- .../BuildCachePublisherTests.cs | 28 +- .../GameBuildWorkflowTests.cs | 5 +- .../NativeBuildContextTests.cs | 4 +- .../NativeComponentBuildOptionsTests.cs | 26 +- .../NativeRecipeClosureTests.cs | 14 +- .../PlatformBackendIntegrationTests.cs | 5 +- .../PlatformOwnershipContractTests.cs | 18 +- .../ShaderBuildInputsTests.cs | 9 +- .../ShaderToolSelectionTests.cs | 4 +- .../SupportPackPublisherTests.cs | 15 +- .../BackendPrebuiltArchiveTests.cs | 5 +- .../BuildCacheInventoryProgressTests.cs | 12 +- .../BuildCacheRetirementTests.cs | 4 +- .../DevelopmentBuildProvenanceTests.cs | 4 +- .../NativeArtifactIdentityTests.cs | 4 +- .../NativeArtifactImportTests.cs | 10 +- .../NativeBindingCompilationTests.cs | 11 +- .../NativeDependencyManifestTests.cs | 22 +- .../NativeDeploymentIndexTests.cs | 5 +- .../NativeVerificationPhaseTests.cs | 6 +- .../NativeWorkspaceReuseTests.cs | 7 +- .../ToolchainProcessTests.cs | 4 +- .../UnixFileLinksFactAttribute.cs | 2 +- .../BuildPipelineFixture.cs | 35 +- .../PlayerSupportPackFixture.cs | 19 +- .../ContentPackIndexTests.cs | 2 +- .../PackContentStoreTests.cs | 21 +- .../Inno.Content.CacheProbe/Program.cs | 2 +- .../Inno.Content.Testing/ContentTestStore.cs | 12 +- .../IndexedObjectStoreTests.cs | 38 +- .../CoroutineRetirementTests.cs | 2 +- .../CoroutineSchedulerTests.cs | 30 +- .../DiagnosticHubTests.cs | 10 +- .../EventDispatcherBehaviorTests.cs | 48 +- .../ExecutionSlotTests.cs | 6 +- .../LifetimeAdmissionTests.cs | 4 +- .../GraphValidatorTests.cs | 12 +- .../AtomicFilePublicationTests.cs | 7 +- .../core/Inno.Core.IO.Tests/FileLeaseTests.cs | 4 +- .../FileSystemSafetyTests.cs | 20 +- .../OwnedReadStreamTests.cs | 2 +- .../IdentityAllocatorTests.cs | 2 +- .../JobSystemPerformanceTests.cs | 44 +- .../JobSystemBehaviorTests.cs | 107 ++--- .../FileLogSinkTests.cs | 2 +- .../LoggingBehaviorTests.cs | 31 +- .../VectorMatrixTests.cs | 72 ++- .../SerializationBehaviorTests.CaptureKeys.cs | 32 +- .../SerializationBehaviorTests.Concurrency.cs | 11 +- .../SerializationBehaviorTests.Encoding.cs | 3 +- .../SerializationBehaviorTests.Snapshots.cs | 11 +- .../SerializationBehaviorTests.cs | 151 ++++-- .../EditorAudioHostTests.cs | 12 +- .../ExportPresentationTests.cs | 46 +- .../ExportWorkflowTests.cs | 15 +- .../GraphDocumentControllerTests.cs | 10 +- .../EditorApplicationTests.cs | 23 +- .../EditorCommandLineOptionsTests.cs | 2 +- .../RepositoryWikiTests.cs | 9 +- .../DynamicModalTests.cs | 40 +- .../FontCoverageTests.cs | 36 +- .../ImGuiInteractionOptionsTests.cs | 7 +- .../ViewportMetricsTests.cs | 64 +-- .../ViewportRetirementTests.cs | 38 +- .../WidgetLayoutTests.cs | 168 ++++--- .../ConditionalInspectionTests.cs | 63 ++- .../EditorHistoryTests.cs | 11 +- .../EditorPlanarNavigationTests.cs | 3 +- .../SceneHistoryTests.Selection.cs | 21 +- .../SceneHistoryTests.cs | 72 ++- .../LargePanelPerformanceTests.Input.cs | 8 +- .../LargePanelPerformanceTests.Workflows.cs | 5 +- .../LargePanelPerformanceTests.cs | 56 ++- .../ConsolePanelNativeLayoutTests.cs | 33 +- .../ConsoleSearchNativeTests.cs | 13 +- .../ConsoleVirtualizationNativeTests.cs | 8 +- .../DefaultLayoutNativeTests.cs | 11 +- .../EditorGameInputCaptureTests.cs | 7 +- .../EditorLayoutInitializationTests.cs | 8 +- .../EditorPlayModeTests.cs | 25 +- .../EditorPopupLayoutTests.cs | 14 +- .../GraphCanvasNativeTests.cs | 43 +- .../ListPanelKeyboardNativeTests.cs | 2 +- .../PlayModeLogRetentionTests.cs | 12 +- .../SceneDirtyCaptureTests.cs | 11 +- .../SettingsApplyNativeTests.cs | 33 +- .../StatisticsPanelNativeTests.cs | 7 +- .../TreeKeyboardOwnershipNativeTests.cs | 3 +- .../VisualScaleMatrixTests.cs | 15 +- .../AssetHistoryTests.cs | 6 +- .../EditorRuntimeTests.Commands.cs | 4 +- .../EditorRuntimeTests.Performance.cs | 3 +- .../EditorRuntimeTests.Selection.cs | 10 +- .../EditorRuntimeTests.Statistics.cs | 13 +- .../EditorRuntimeTests.cs | 49 +- .../EditorSettingsTests.cs | 9 +- .../GraphCanvasPointerTests.cs | 10 +- .../GraphCanvasPresentationTests.cs | 2 +- .../GraphCanvasViewTests.cs | 2 +- .../NativePanelHost.cs | 149 +++--- .../NativePanelInput.cs | 62 ++- .../NativeProjectPanelHost.cs | 36 +- .../NativeProjectPanelProbe.cs | 12 +- .../SettingsPanelServices.cs | 2 +- .../AssemblyManagerTests.cs | 6 +- .../HostLoadContextTests.cs | 4 +- .../ModuleRetirementTests.cs | 8 +- .../AssemblyExtensionsTests.cs | 20 +- .../TypeCacheTests.cs | 6 +- .../AssemblyATypes.cs | 25 +- .../AssemblyBTypes.cs | 25 +- .../editor-ui/PanelLifecycle.editor.cs | 4 +- .../Inno.Input.Tests/InputRuntimeTests.cs | 14 +- .../Inno.Input.Tests/ShellLifecycleTests.cs | 27 +- .../BrowserDependencyConsumptionTests.cs | 10 +- .../BrowserSupportPackAbiTests.cs | 4 +- .../BrowserSupportPackTests.cs | 2 +- .../SupportPackValidationTests.cs | 12 +- .../NativeBindingCMakeTests.cs | 13 +- .../ToolchainWorkingDirectoryBuildTests.cs | 4 +- .../SupportPackValidationTests.cs | 4 +- .../ToolchainWorkingDirectoryTests.cs | 4 +- .../PluginSourceServiceTests.cs | 50 +- .../DiscoveryLogger.cs | 10 +- .../ReferenceCatalogTests.cs | 10 +- .../RenderingImporterIntegrationTests.cs | 83 ++-- .../ShaderCompilerTests.cs | 2 +- .../ShaderGraphArtifactTests.cs | 10 +- .../EmptyRenderingKernelTests.cs | 43 +- ...nderRuntimeGenerationTests.Contributors.cs | 31 +- .../ShaderProgramPublicationTests.cs | 64 ++- .../RenderingBackendRegistrationTests.cs | 2 +- .../ShaderControlFlowIrTests.cs | 10 +- .../ShaderGraphInputDefaultTests.cs | 8 +- .../ShaderGraphLoweringTests.cs | 2 +- .../ShaderGraphProgramTests.cs | 14 +- .../ShaderGraphStorageTests.cs | 51 +- .../ShaderIrBuilderTests.cs | 4 +- .../ShaderIrStageTests.cs | 4 +- .../ShaderResourceIrTests.cs | 6 +- .../ShaderSourceFrontendRegistryTests.cs | 4 +- .../ShaderSourceModuleTests.cs | 10 +- .../ShaderTypedNativeCompilationTests.cs | 12 +- .../GraphicsProgramArtifactTests.cs | 2 +- .../ParallelCommandRecordingTests.cs | 22 +- .../PipelineResourceTests.cs | 58 +-- .../RenderGraphCompilerTests.cs | 30 +- .../RenderGraphMutationTests.cs | 20 +- .../RenderGraphValidationTests.cs | 10 +- .../ReloadableContributor.cs | 8 +- .../ReloadableRenderPipeline.cs | 8 +- .../RuntimeModuleCatalogGeneratorTests.cs | 10 +- .../SerializationMetadataGeneratorTests.cs | 40 +- .../Inno.Runtime.Tests/AdapterCatalogTests.cs | 21 +- .../PlayerContentSourceTests.cs | 4 +- .../PlayerWithoutFileSystemTests.Adapters.cs | 5 +- .../PlayerWithoutFileSystemTests.Startup.cs | 28 +- .../RuntimeSubsystemPolicyTests.cs | 30 +- .../StaticDeploymentTests.cs | 4 +- .../EngineAssetIntegrationTests.cs | 3 +- .../Inno.Scene.Tests/SceneFacadeTests.cs | 7 +- .../SceneSerializationTests.CaptureKeys.cs | 4 +- .../SceneSerializationTests.cs | 17 +- .../Inno.Scene.Tests/SceneTestsCollection.cs | 16 +- .../scene/Inno.Scene.Tests/TransformTests.cs | 6 +- .../ControlledSampleSourceRewriter.cs | 4 +- .../EditorStyleMetricsTests.cs | 292 +++++------ .../InspectionPipelineTests.cs | 80 ++- .../InspectorPresentationLayoutTests.cs | 12 +- .../ScriptingPipelineTests.UiLifecycle.cs | 6 +- .../ScriptingPipelineTests.cs | 193 ++++---- .../ShaderEditorWorkflowTests.Performance.cs | 9 +- .../ShaderEditorWorkflowTests.Visual.cs | 4 +- .../ShaderEditorWorkflowTests.cs | 74 +-- .../CSharp14ScriptingTests.cs | 8 +- .../CompilerFixture.cs | 12 +- .../ScriptCachePublicationTests.cs | 26 +- .../AgentDocumentTests.cs | 4 +- .../ArchitectureOutputOwnerTests.cs | 4 +- .../ArchitectureSymbolTests.cs | 11 +- .../DocumentationExampleTests.cs | 33 +- .../DocumentationReferenceTests.cs | 44 +- .../DocumentationSourceContractTests.cs | 11 +- .../NativePlatformPolicyTests.cs | 4 +- .../RepositoryInputTests.cs | 10 +- .../TestRepositoryInputsTests.cs | 2 +- .../DocumentationApiSynchronizationTests.cs | 50 +- .../DocumentationEvidenceTests.cs | 48 +- .../DocumentationSnapshotTests.cs | 10 +- .../ValidationCompletionTests.cs | 18 +- .../ValidationFailureExecutionTests.cs | 2 +- .../ValidationHostContractsTests.cs | 9 +- .../ValidationShardExecutionTests.cs | 7 +- .../ValidationTestOwnershipTests.cs | 8 +- .../BackendInputTests.cs | 7 +- .../ValidationDocumentationTests.cs | 7 +- .../ValidationPlanningTests.cs | 28 +- .../ValidationDocumentationFixture.cs | 4 +- .../ValidationRepository.cs | 16 +- tests/ui/Inno.UI.Tests/UiRuntimeTests.cs | 6 +- .../AgentLinkValidator.cs | 2 +- .../ArchitectureValidator.cs | 4 +- .../AssemblyDocumentationProvider.cs | 3 +- .../DocumentationApiExtractor.cs | 11 +- .../DocumentationExamples.cs | 11 +- .../DocumentationExportCache.cs | 7 +- .../DocumentationExportPlan.cs | 2 +- .../DocumentationProjectReferences.cs | 6 +- .../DocumentationReferences.cs | 26 +- .../DocumentationScriptApi.cs | 55 ++- .../DocumentationSourceModels.cs | 2 +- .../EditorPresentationSourceValidator.cs | 2 +- .../EditorUiBoundaryValidator.cs | 6 +- .../MSBuildProjectGraphValidator.cs | 5 +- .../NativeBindingOwnershipValidator.cs | 4 +- .../PlatformOwnershipValidator.cs | 5 +- .../PublicApiBoundaryValidator.cs | 18 +- .../PublicApiDocumentationValidator.cs | 7 +- .../DocumentationCommand.cs | 4 +- .../DocumentationPageInfo.cs | 2 +- .../DocumentationSnapshot.cs | 27 +- .../DocumentationStore.cs | 40 +- .../Indexing/DocumentationApiComposition.cs | 44 +- .../Indexing/DocumentationApiContent.cs | 35 +- .../Indexing/DocumentationApiFacts.cs | 4 +- .../Indexing/DocumentationApiFragment.cs | 8 +- .../Indexing/DocumentationApiLinks.cs | 8 +- .../Indexing/DocumentationApiNavigation.cs | 12 +- .../Indexing/DocumentationApiPackage.cs | 12 +- .../DocumentationApiSynchronization.cs | 2 +- .../Indexing/DocumentationCatalog.cs | 6 +- .../Indexing/DocumentationMarkdown.cs | 6 +- .../Indexing/DocumentationProjectGuides.cs | 78 +-- .../Indexing/DocumentationReferenceStore.cs | 4 +- .../Indexing/DocumentationXml.cs | 26 +- .../ValidationBuildInputs.cs | 2 +- .../ValidationCommand.cs | 13 +- .../ValidationCompiledGraph.cs | 3 +- .../ValidationDependencyInputs.cs | 8 +- .../ValidationDocumentation.cs | 14 +- .../ValidationDocumentationInputs.cs | 6 +- .../ValidationEntryInputs.cs | 2 +- .../ValidationEnvironment.cs | 8 +- .../ValidationInputs.cs | 5 +- .../ValidationOutputs.cs | 6 +- .../ValidationPlanTransport.cs | 2 +- .../ValidationPlanner.Backends.cs | 49 +- .../ValidationPlanner.cs | 81 ++-- .../ValidationProcess.cs | 13 +- .../ValidationProductInput.cs | 3 +- .../ValidationRunner.cs | 36 +- .../ValidationShard.cs | 10 +- .../ValidationTestEvidence.cs | 20 +- .../ValidationTestHosts.cs | 4 +- .../ValidationWorkspace.cs | 5 +- 1173 files changed, 10185 insertions(+), 8563 deletions(-) diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs index c2c2f7422..9ea91035c 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderArtifactBuilder.cs @@ -46,6 +46,12 @@ public static class ShaderArtifactBuilder /// /// The artifact destination, replaced atomically after successful compilation. /// + /// + /// The host-selected executable distribution, or null for the application's deployed tools. + /// + /// + /// Cancels import and native compilation before replacing the destination artifact. + /// /// /// Import or shader compilation fails. /// @@ -61,12 +67,6 @@ public static class ShaderArtifactBuilder /// /// Import, copying, verification or compilation was canceled before publication. /// - /// - /// The host-selected executable distribution, or null for the application's deployed tools. - /// - /// - /// Cancels import and native compilation before replacing the destination artifact. - /// public static void Compile( ShaderBuildInputs inputs, ProcessOwnedDirectory workspace, @@ -105,6 +105,12 @@ public static void Compile( /// /// The device artifact destination, atomically replaced after successful compilation. /// + /// + /// The host-selected executable distribution, or null for the application's deployed tools. + /// + /// + /// Cancels import and native compilation before replacing the destination artifact. + /// /// /// A required shader path or output path is blank. /// @@ -120,12 +126,6 @@ public static void Compile( /// /// Import, copying, verification or compilation was canceled before publication. /// - /// - /// The host-selected executable distribution, or null for the application's deployed tools. - /// - /// - /// Cancels import and native compilation before replacing the destination artifact. - /// public static void CompileGraphicsProgram( ShaderBuildInputs inputs, ProcessOwnedDirectory workspace, diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs index 80c525830..3b1bc9eab 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Shaders/ShaderBuildInputs.cs @@ -31,7 +31,7 @@ CancellationToken cancellationToken m_sourceRoot = sourceRoot; m_files = inventory.files; m_directories = inventory.directories; - fingerprint = ComputeFingerprint(inventory, cancellationToken); + this.fingerprint = ComputeFingerprint(inventory, cancellationToken); } /// diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs index 165d313a8..367e8f803 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxAuthoringProvider.cs @@ -32,9 +32,9 @@ public BgfxAuthoringProvider( m_tools = tools; } - /// + /// public override IShaderCompilerToolchain CreateShaderCompilerToolchain() => new BgfxShadercToolchain(m_target, m_tools); - /// + /// public override ITextureTargetCompiler CreateTextureTargetCompiler() => new BgfxTextureTargetCompiler(m_tools); } diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs index 75de7454e..e93f8e4e9 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxGameContentCompiler.cs @@ -87,7 +87,7 @@ ToolRunner tools m_backends = snapshot; } - /// + /// public BuildTargetId target => new(m_platform.id); /// diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs index d36cf958e..fccd3dc85 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxShaderCompilerProfile.cs @@ -65,7 +65,7 @@ public BgfxShaderCompilerProfile( this.fragmentProfile = fragmentProfile; this.computeProfile = computeProfile; this.defines = Array.AsReadOnly(snapshot); - key = CreateKey(capabilities); + this.key = CreateKey(capabilities); } /// diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs index 3bad4fe35..1d3b70334 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTargetCapabilities.cs @@ -29,7 +29,7 @@ public static GraphicsCapabilities Create(GraphicsApi backend) return new GraphicsCapabilities( backend, features, - new GraphicsLimits(256, 8, 16384, 16), + new GraphicsLimits(256, 8, 16_384, 16), formats, formats, formats, diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs index f87e13911..8a01913c6 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/BgfxTextureTargetCompiler.cs @@ -22,7 +22,10 @@ public sealed class BgfxTextureTargetCompiler : ITextureTargetCompiler /// /// The selected tool runner, or null for application-deployed tools. /// - public BgfxTextureTargetCompiler(ToolRunner? tools = null) => m_tools = tools ?? new ToolRunner(); + public BgfxTextureTargetCompiler(ToolRunner? tools = null) + { + m_tools = tools ?? new ToolRunner(); + } /// /// Compiles the supplied source into a validated runtime artifact. @@ -60,7 +63,7 @@ public async ValueTask CompileKtxAsync( try { string sourcePath = Path.Combine(temporaryDirectory, "source.image"); - await using (FileStream inputFile = new( + await using (var inputFile = new FileStream( sourcePath, FileMode.CreateNew, FileAccess.Write, diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs index 2a9695c86..2f1bf4643 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs @@ -27,7 +27,9 @@ public sealed class ToolRunner /// Explicit execution path policy, or null for physical execution. /// public ToolRunner(IToolchainWorkspaceProvider? workspaces = null) - => m_workspaces = workspaces ?? new PhysicalToolchainWorkspaceProvider(); + { + m_workspaces = workspaces ?? new PhysicalToolchainWorkspaceProvider(); + } /// /// Freezes executables selected and validated by the host's toolchain operation. diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs index 6bded9603..f23915efa 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.Source.cs @@ -29,7 +29,11 @@ private string EmitModule(ShaderSourceImplementationAnalysis implementation) Fail("The frozen source interface differs from its analyzed snapshot."); } string prefix = "inno_module_" + implementation.contentHash.ToLowerInvariant() + "_"; - var symbols = parser.globals.ToDictionary(static value => value, value => prefix + value, StringComparer.Ordinal); + Dictionary symbols = parser.globals.ToDictionary( + static value => value, + value => prefix + value, + StringComparer.Ordinal + ); // Shaderc injects varying macros before function declarations. Isolate module-local names // that collide with those generated bindings, including exported function parameters. foreach (string varying in stage.inputs.Where(static input => input.kind == ShaderIrInputKind.Varying) @@ -101,7 +105,7 @@ private string TypeName(ShaderSourceType type) if (!m_structures.TryGetValue(name, out ShaderSourceType? previous)) { m_structures.Add(name, type); - var declaration = new StringBuilder("struct ").Append(name).AppendLine(" {"); + StringBuilder declaration = new StringBuilder("struct ").Append(name).AppendLine(" {"); foreach (ShaderSourceField field in type.fields) { declaration.Append(" ").Append(Declaration(field.type, FieldName(field.name))).AppendLine(";"); diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs index 0c791f6c1..b89bb572c 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs @@ -110,7 +110,8 @@ internal BgfxGeneratedStage Generate() EmitStorageDeclaration(declarations, input, name); m_bindings.Add(new(input.id, name, input.location)); break; - default: throw Error("Unsupported stage input kind."); + default: + throw Error("Unsupported stage input kind."); } stageInputs.Add(input.id, name); } @@ -168,7 +169,7 @@ internal BgfxGeneratedStage Generate() ShaderIrValue value = stage.body.outputs[output.id]; Assign(m_body, value.type, destination, Value(value)); } - var source = new StringBuilder().Append(header).Append(m_types).Append(declarations).Append(m_modules); + StringBuilder source = new StringBuilder().Append(header).Append(m_types).Append(declarations).Append(m_modules); source.AppendLine("#line 1 \"inno-generated-stage\""); if (stage.stage == ShaderStage.Compute) { diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs index ac9591406..7a691d075 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Reflection.cs @@ -96,7 +96,7 @@ string nativeName throw new InvalidDataException($"The compiled GLSL uniform '{nativeName}' exceeds the BGFX binary limits."); } int registerCount = count * (type == ShaderUniformType.Mat3 ? 3 : type == ShaderUniformType.Mat4 ? 4 : 1); - byte[] record = new byte[1 + name.Length + C_SHADER_UNIFORM_METADATA_SIZE]; + var record = new byte[1 + name.Length + C_SHADER_UNIFORM_METADATA_SIZE]; record[0] = (byte)name.Length; name.CopyTo(record, 1); Span metadata = record.AsSpan(1 + name.Length); diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs index 114a81b03..2d5787c24 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShadercToolchain.Typed.cs @@ -24,7 +24,7 @@ public sealed partial class BgfxShadercToolchain private const int C_SHADER_BINARY_HEADER_SIZE = 12; private const int C_SHADER_UNIFORM_METADATA_SIZE = 10; private static readonly UTF8Encoding S_GLSL_ENCODING = new(false, true); - private static readonly IReadOnlyList s_languages = Array.AsReadOnly(new[] { "inno.shader-language.bgfx-sc" }); + private static readonly IReadOnlyList s_languages = Array.AsReadOnly(["inno.shader-language.bgfx-sc"]); /// /// Gets shader source languages accepted by this toolchain. diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs index 07993d9b0..f3e8dc510 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs @@ -64,13 +64,17 @@ internal static List Tokenize(ShaderSourceFile source) var position = new ShaderSourcePosition(source.assetPath, line, column); if (current == '/' && offset + 1 < text.Length && text[offset + 1] == '*') { - Advance(); Advance(); + Advance(); + Advance(); bool closed = false; while (offset < text.Length) { if (text[offset] == '*' && offset + 1 < text.Length && text[offset + 1] == '/') { - Advance(); Advance(); closed = true; break; + Advance(); + Advance(); + closed = true; + break; } if (text[offset] == '\n') { diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs index d8aa7659c..5e8246955 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourcePreprocessor.cs @@ -11,7 +11,7 @@ namespace Inno.Build.Toolchains.Bgfx.Tools; internal sealed class BgfxSourcePreprocessor(ShaderSourceRequest request) { private const int C_MAX_DEPTH = 128; - private const int C_MAX_TOKENS = 1000000; + private const int C_MAX_TOKENS = 1_000_000; private readonly Dictionary m_macros = new(StringComparer.Ordinal); private readonly HashSet m_dependencies = new(StringComparer.Ordinal); private readonly HashSet m_once = new(StringComparer.Ordinal); @@ -138,7 +138,9 @@ void ApplyDirective() { switch (directive.text) { - case "define": Define(arguments, directive); break; + case "define": + Define(arguments, directive); + break; case "undef": if (arguments.Count != 1 || !arguments[0].isIdentifier) { @@ -194,8 +196,12 @@ failure is IOException or UnauthorizedAccessException or InvalidOperationExcepti Fail("Unsupported module pragma; stage configuration belongs to the graph target.", directive); } break; - case "error": Fail(string.Join(" ", arguments.Select(static token => token.text)), directive); break; - default: Fail($"Unsupported module preprocessor directive '#{directive.text}'.", directive); break; + case "error": + Fail(string.Join(" ", arguments.Select(static token => token.text)), directive); + break; + default: + Fail($"Unsupported module preprocessor directive '#{directive.text}'.", directive); + break; } } } @@ -328,7 +334,7 @@ int depth { Fail("Shader macro expansion exceeded its depth budget.", tokens[0]); } - var pending = tokens.Select(token => new ExpansionToken(token, disabled)).ToList(); + List pending = tokens.Select(token => new ExpansionToken(token, disabled)).ToList(); var result = new List(); for (int i = 0; i < pending.Count; i++) { diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs index e88915de8..11eb6689b 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBindingProject.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; @@ -32,7 +33,7 @@ CancellationToken cancellationToken build, "inno_bgfx_binding" + context.RequireToolchain().linkPlan.GetFileExtension(NativeLibraryKind.Static) ); - var linking = profile.CreateBindingLinkSettings(archive); + (string reference, IReadOnlyList arguments) linking = profile.CreateBindingLinkSettings(archive); string script = Path.Combine(context.GetNativeBuildRoot(request.component), "BindingProject.lua"); string text = "dofile(" + Literal(Path.Combine(source, "scripts", "genie.lua")) + ")\n" + "project \"bgfx-shared-lib\"\nconfiguration {}\n" diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs index e0978ff09..f278e9a04 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildRequest.cs @@ -18,14 +18,14 @@ bool includeTools { throw new ArgumentException("The BGFX profile does not match the frozen toolchain target.", nameof(profile)); } - context = operation.WithToolchain(profile.SelectTools(operation, includeTools)); - component = includeTools ? BgfxToolsBuild.componentDescriptor : BgfxNativeBuild.componentDescriptor; + this.context = operation.WithToolchain(profile.SelectTools(operation, includeTools)); + this.component = includeTools ? BgfxToolsBuild.componentDescriptor : BgfxNativeBuild.componentDescriptor; NativeComponentBuildOptions options = context.RequireComponentOptions(component); if (options.libraryKind != NativeLibraryKind.Shared || options.cmakeArguments.Count != 0) { throw new NotSupportedException("The standalone graphics recipe requires shared linkage and its explicit generation profile."); } - artifactToken = profile.artifactPathToken; + this.artifactToken = profile.artifactPathToken; ArgumentException.ThrowIfNullOrWhiteSpace(artifactToken); string[] arguments = profile.generatorArguments?.ToArray() ?? throw new ArgumentException("The BGFX profile has no generator arguments.", nameof(profile)); @@ -33,20 +33,20 @@ bool includeTools { throw new ArgumentException("The BGFX profile requires assigned generator arguments.", nameof(profile)); } - generatorArguments = includeTools - ? ["--with-shared-lib", "--with-tools", .. arguments] - : ["--with-shared-lib", .. arguments]; - bindingCmakeArguments = includeTools ? [] : profile.bindingCmakeArguments.ToArray(); - invocation = profile.CreateBuildInvocation(context, includeTools) - ?? throw new ArgumentException("The BGFX profile returned no SDK invocation.", nameof(profile)); + this.generatorArguments = includeTools + ? ["--with-shared-lib", "--with-tools", .. arguments] + : ["--with-shared-lib", .. arguments]; + this.bindingCmakeArguments = includeTools ? [] : profile.bindingCmakeArguments.ToArray(); + this.invocation = profile.CreateBuildInvocation(context, includeTools) + ?? throw new ArgumentException("The BGFX profile returned no SDK invocation.", nameof(profile)); NativeToolchainSelection tools = context.RequireToolchain(); - compiler = tools.ResolveExecutable(invocation.tool); - externalDirectory = Path.Combine(context.engineRoot, "extern"); + this.compiler = tools.ResolveExecutable(invocation.tool); + this.externalDirectory = Path.Combine(context.engineRoot, "extern"); string bgfx = Path.Combine(externalDirectory, "bgfx"); string bx = Path.Combine(externalDirectory, "bx"); string bimg = Path.Combine(externalDirectory, "bimg"); BgfxBuildUtils.ValidateSubmodules(bgfx, bx, bimg); - genie = tools.ResolveExecutable("genie"); + this.genie = tools.ResolveExecutable("genie"); string[] declarations = [ "artifact=" + artifactToken, @@ -56,7 +56,7 @@ .. bindingCmakeArguments.Select(static value => "bridge=" + value), .. invocation.arguments.Select(static value => "compile=" + value) ]; string implementation = component.GetToolchainRoot(context.engineRoot); - recipe = NativeBuildRecipe.CreateForComponent( + this.recipe = NativeBuildRecipe.CreateForComponent( context, component, includeTools ? "bgfx-tools" : "bgfx", diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs index af98e8b0d..f40cbbad2 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxNativeBuild.cs @@ -30,12 +30,6 @@ public static class BgfxNativeBuild /// /// The checkout and configuration whose sources and outputs belong to this operation. /// - /// - /// The configuration is not debug or release. - /// - /// - /// A native build process fails. - /// /// /// The platform-owned project generation, SDK invocation and output selection. /// @@ -45,6 +39,12 @@ public static class BgfxNativeBuild /// /// The validated product with an exact graphics library or offline-tool output closure. /// + /// + /// The configuration is not debug or release. + /// + /// + /// A native build process fails. + /// /// /// The operation was canceled. /// diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs index 7d4c82db8..71cbe3463 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxToolsBuild.cs @@ -24,12 +24,6 @@ public static class BgfxToolsBuild /// /// The checkout and configuration whose sources and outputs belong to this operation. /// - /// - /// The configuration is not debug or release. - /// - /// - /// A native build process fails. - /// /// /// The platform-owned project generation, SDK invocation and output selection. /// @@ -39,6 +33,12 @@ public static class BgfxToolsBuild /// /// The validated product with an exact graphics library or offline-tool output closure. /// + /// + /// The configuration is not debug or release. + /// + /// + /// A native build process fails. + /// /// /// The operation was canceled. /// diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs index cbf95a3ba..29913c36e 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxCommandEncoder.Geometry.cs @@ -196,7 +196,7 @@ int vertexCount uint count = checked((uint)vertexCount); if (buffer.kind == BgfxBufferKind.Vertex) { - bgfx.VertexBufferHandle handle = new() { idx = buffer.nativeIndex }; + var handle = new bgfx.VertexBufferHandle() { idx = buffer.nativeIndex }; if (buffer.vertexLayout is null) { BgfxNativeCalls.EncoderSetVertexBufferWithLayout( @@ -218,7 +218,7 @@ int vertexCount if (buffer.kind == BgfxBufferKind.DynamicVertex) { - bgfx.DynamicVertexBufferHandle handle = new() { idx = buffer.nativeIndex }; + var handle = new bgfx.DynamicVertexBufferHandle() { idx = buffer.nativeIndex }; if (buffer.vertexLayout is null) { BgfxNativeCalls.EncoderSetDynamicVertexBufferWithLayout( diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs index 6553e80f9..e2c19ce81 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.FrameBuffers.cs @@ -11,7 +11,7 @@ namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { private void ConfigureViewTarget( ushort viewId, @@ -42,7 +42,7 @@ CompiledRenderPass pass { RetireSupersededFrameBuffer(pass.name); bgfx.Attachment* attachments = stackalloc bgfx.Attachment[pass.attachments.Count]; - GraphAttachmentSignature[] signature = new GraphAttachmentSignature[pass.attachments.Count]; + var signature = new GraphAttachmentSignature[pass.attachments.Count]; for (int index = 0; index < pass.attachments.Count; index++) { CompiledRenderAttachment attachment = pass.attachments[index]; diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs index 1820709fa..6f37611a6 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Frames.cs @@ -11,7 +11,7 @@ namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { /// /// Begins a frame-scoped operation and makes queued work visible. @@ -93,7 +93,7 @@ public uint EndFrame() throw new InvalidOperationException("No BGFX frame is open."); } - if (m_activeGraph is not null || m_activeEncoder != null) + if (m_activeGraph is not null || m_activeEncoder is not null) { throw new InvalidOperationException("All render graphs and encoders must end before BGFX frame submission."); } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs index 64f2e1ed4..6f0f127b3 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Graphs.cs @@ -11,7 +11,7 @@ namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { /// /// Begins recording commands for one validated compiled render graph. @@ -120,7 +120,7 @@ public void BeginGraph(CompiledRenderGraph graph) public RenderCommandEncoder BeginPass(CompiledRenderPass pass) { ArgumentNullException.ThrowIfNull(pass); - if (m_activeGraph is null || m_activeEncoder != null) + if (m_activeGraph is null || m_activeEncoder is not null) { throw new InvalidOperationException("Pass execution is outside a valid BGFX graph scope."); } @@ -140,7 +140,7 @@ public RenderCommandEncoder BeginPass(CompiledRenderPass pass) ApplyViewTransform(viewId, pass.viewTransform); ConfigureViewTarget(viewId, pass); m_activeEncoder = bgfx.Raw.encoder_begin(0); - if (m_activeEncoder == null) + if (m_activeEncoder is null) { throw new InvalidOperationException($"BGFX could not acquire an encoder for pass '{pass.name}'."); } @@ -158,7 +158,7 @@ public RenderCommandEncoder BeginPass(CompiledRenderPass pass) public void EndPass(CompiledRenderPass pass) { ArgumentNullException.ThrowIfNull(pass); - if (m_activeEncoder == null) + if (m_activeEncoder is null) { throw new InvalidOperationException("No BGFX encoder is active."); } @@ -176,7 +176,7 @@ public void EndPass(CompiledRenderPass pass) public void EndGraph(CompiledRenderGraph graph) { ArgumentNullException.ThrowIfNull(graph); - if (!ReferenceEquals(m_activeGraph, graph) || m_activeEncoder != null) + if (!ReferenceEquals(m_activeGraph, graph) || m_activeEncoder is not null) { throw new InvalidOperationException("BGFX graph cleanup does not match the active graph state."); } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs index 741b20a08..6698d1740 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Readback.cs @@ -11,7 +11,7 @@ namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { /// /// Schedules asynchronous texture readback into caller-provided destination storage. @@ -114,7 +114,7 @@ out RenderTextureReadbackResult? result { return false; } - byte[] bytes = new byte[pending.byteCount]; + var bytes = new byte[pending.byteCount]; Marshal.Copy(pending.data, bytes, 0, bytes.Length); result = new RenderTextureReadbackResult(pending.descriptor, pending.mipLevel, pending.rowPitch, bytes); return true; diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs index e7c49fabc..08f1f0de7 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Resources.cs @@ -691,7 +691,7 @@ IReadOnlyDictionary reflected } } - Dictionary result = new(StringComparer.Ordinal); + var result = new Dictionary(StringComparer.Ordinal); foreach (RenderShaderBindingDescriptor binding in declaredBindings) { if (binding.kind is RenderShaderBindingKind.StorageBuffer or RenderShaderBindingKind.StorageTexture) @@ -715,7 +715,7 @@ IReadOnlyDictionary reflected private static Dictionary ReflectShaders(params bgfx.ShaderHandle[] shaders) { - Dictionary result = new(StringComparer.Ordinal); + var result = new Dictionary(StringComparer.Ordinal); foreach (bgfx.ShaderHandle shader in shaders) { ushort count = BgfxNativeCalls.GetShaderUniforms(shader, null, 0); @@ -724,7 +724,7 @@ private static Dictionary ReflectShaders(params bgfx.S continue; } - bgfx.UniformHandle[] uniforms = new bgfx.UniformHandle[count]; + var uniforms = new bgfx.UniformHandle[count]; fixed (bgfx.UniformHandle* handles = uniforms) { ushort written = BgfxNativeCalls.GetShaderUniforms(shader, handles, count); @@ -733,7 +733,7 @@ private static Dictionary ReflectShaders(params bgfx.S bgfx.UniformInfo info = default; BgfxNativeCalls.GetUniformInfo(uniforms[index], &info); string name = UniformName(info); - ReflectedUniform reflected = new(uniforms[index], info.type, info.num); + var reflected = new ReflectedUniform(uniforms[index], info.type, info.num); if (result.TryGetValue(name, out ReflectedUniform current) && (current.type != reflected.type || current.count != reflected.count) ) { diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs index 337c61c14..88195d3cc 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Retirement.cs @@ -11,7 +11,7 @@ namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { /// /// Shuts down BGFX after releasing all active and queued backend resources. @@ -28,7 +28,7 @@ public void Dispose() } EnsureApiThread(); - if (m_activeEncoder != null || m_activeGraph is not null) + if (m_activeEncoder is not null || m_activeGraph is not null) { throw new InvalidOperationException("Cannot dispose BGFX while a render graph or encoder is active."); } @@ -205,7 +205,7 @@ private void DrainDeferredResourcesForShutdown() private string? GetManagedResourceClosureFailure() { - if (m_activeEncoder != null + if (m_activeEncoder is not null || m_activeGraph is not null || m_graphFrameBuffers.Count != 0 || m_graphTextures.Count != 0 diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs index 30ebf6518..884273018 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Surfaces.cs @@ -176,17 +176,17 @@ public Task RetireWindowSurface(RenderSurfaceHandle surface) /// /// Advances complete discard frames until all requested window retirements have been acknowledged. /// - /// - /// Call only on the API thread with no open frame, graph, encoder or native UI callback. - /// A failed drain retains the device and the borrowed native windows. - /// Presentation may advance while the primary window remains borrowed by the device. - /// /// /// The caller is not at a closed-frame API-thread safety point. /// /// /// The bounded retirement deadline expired; dependent owners must remain alive. /// + /// + /// Call only on the API thread with no open frame, graph, encoder or native UI callback. + /// A failed drain retains the device and the borrowed native windows. + /// Presentation may advance while the primary window remains borrowed by the device. + /// public void DrainWindowSurfaceRetirements() { EnsureSurfaceSafetyPoint(); @@ -225,12 +225,10 @@ private bool HasClosingSurface() return false; } - private void SubmitRetirementFrame() - { + private void SubmitRetirementFrame() => // Complete the backend frame, including command-buffer submission and frame-credit return. // A nonpresenting flush does not provide that completion boundary on every renderer. SubmitNativeFrame(bgfx.FrameFlags.Discard); - } private uint SubmitNativeFrame(bgfx.FrameFlags flags) { @@ -323,7 +321,7 @@ private void EnsureSurfaceSafetyPoint() { EnsureApiThread(); ObjectDisposedException.ThrowIf(m_disposed, this); - if (m_activeGraph is not null || m_activeEncoder != null) + if (m_activeGraph is not null || m_activeEncoder is not null) { throw new InvalidOperationException( "Window surface changes require an API-thread point outside graph execution." diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs index da26f8a6a..35eab6ef3 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Textures.cs @@ -11,7 +11,7 @@ namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { /// /// Creates a texture using this implementation's validated inputs. diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs index c765d6aa6..2c2dbc18a 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.Transients.cs @@ -11,7 +11,7 @@ namespace Inno.Adapter.Rendering.Bgfx; -sealed unsafe partial class BgfxDevice +public sealed unsafe partial class BgfxDevice { private bgfx.TextureHandle AcquireTransientTexture( RenderTextureDescriptor descriptor, diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs index fb6d4942f..ceac7de86 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxDevice.cs @@ -4,6 +4,7 @@ using System.Runtime.InteropServices; using System.Threading; using Inno.Adapter.Platform; +using Inno.Core.Execution; using Inno.Native.Bgfx; using Inno.Platform; using Inno.Rendering; @@ -24,7 +25,7 @@ public sealed unsafe partial class BgfxDevice : RenderDevice, IRenderDevice, IRe private readonly int m_deferredDestroyFrames; private readonly bool m_hasPrimarySurface; private readonly List m_surfaceRetirements = []; - private Inno.Core.Execution.RetirementBarrier? m_surfaceRetirementBarrier; + private RetirementBarrier? m_surfaceRetirementBarrier; private ulong m_submissionSequence; private readonly IBgfxSurfaceIntegration? m_surfaceIntegration; private readonly Dictionary m_persistentTextures = []; @@ -91,9 +92,9 @@ public BgfxDevice(BgfxDeviceOptions options) m_hasPrimarySurface = options.window is not null; int pixelWidth = options.backbufferWidth; int pixelHeight = options.backbufferHeight; - primaryPresentationSize = m_hasPrimarySurface && pixelWidth > 0 && pixelHeight > 0 - ? new RenderPresentationSize(pixelWidth, pixelHeight) - : null; + this.primaryPresentationSize = m_hasPrimarySurface && pixelWidth > 0 && pixelHeight > 0 + ? new RenderPresentationSize(pixelWidth, pixelHeight) + : null; m_backbufferWidth = Math.Max(1, pixelWidth); m_backbufferHeight = Math.Max(1, pixelHeight); m_resetFlags = (uint)( @@ -135,13 +136,13 @@ public BgfxDevice(BgfxDeviceOptions options) } nativeInitialized = true; - generation = unchecked((uint)Interlocked.Increment(ref s_nextGeneration)); + this.generation = unchecked((uint)Interlocked.Increment(ref s_nextGeneration)); if (generation == 0) { - generation = unchecked((uint)Interlocked.Increment(ref s_nextGeneration)); + this.generation = unchecked((uint)Interlocked.Increment(ref s_nextGeneration)); } - capabilities = BgfxCapabilityMapper.FromNative(bgfx.Raw.get_caps()); + this.capabilities = BgfxCapabilityMapper.FromNative(bgfx.Raw.get_caps()); } catch { @@ -240,7 +241,7 @@ private void EnsureFrameSafetyPoint() { EnsureApiThread(); ObjectDisposedException.ThrowIf(m_disposed, this); - if (!m_frameOpen || m_activeGraph is not null || m_activeEncoder != null) + if (!m_frameOpen || m_activeGraph is not null || m_activeEncoder is not null) { throw new InvalidOperationException("Operation requires an open frame before graph execution."); } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs index d2a4a210e..422217bf2 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxNativeCalls.cs @@ -15,9 +15,7 @@ internal static void AttachmentInit( ushort numLayers, ushort mip, byte resolve - ) { - bgfx.Raw.attachment_init(attachment, &handle, access, layer, numLayers, mip, resolve); - } + ) => bgfx.Raw.attachment_init(attachment, &handle, access, layer, numLayers, mip, resolve); internal static bgfx.DynamicVertexBufferHandle CreateDynamicVertexBuffer( uint count, @@ -155,25 +153,23 @@ internal static void EncoderBlit( ushort width, ushort height, ushort depth - ) { - bgfx.Raw.encoder_blit( - encoder, - id, - &dst, - dstMip, - dstX, - dstY, - dstZ, - &src, - srcMip, - srcX, - srcY, - srcZ, - width, - height, - depth - ); - } + ) => bgfx.Raw.encoder_blit( + encoder, + id, + &dst, + dstMip, + dstX, + dstY, + dstZ, + &src, + srcMip, + srcX, + srcY, + srcZ, + width, + height, + depth + ); internal static void EncoderDispatch( bgfx.Encoder* encoder, @@ -183,9 +179,7 @@ internal static void EncoderDispatch( uint numY, uint numZ, byte flags - ) { - bgfx.Raw.encoder_dispatch(encoder, id, &program, numX, numY, numZ, flags); - } + ) => bgfx.Raw.encoder_dispatch(encoder, id, &program, numX, numY, numZ, flags); internal static void EncoderDispatchIndirect( bgfx.Encoder* encoder, @@ -195,63 +189,49 @@ internal static void EncoderDispatchIndirect( uint start, uint count, byte flags - ) { - bgfx.Raw.encoder_dispatch_indirect(encoder, id, &program, &indirectHandle, start, count, flags); - } + ) => bgfx.Raw.encoder_dispatch_indirect(encoder, id, &program, &indirectHandle, start, count, flags); internal static void EncoderSetComputeDynamicIndexBuffer( bgfx.Encoder* encoder, byte stage, bgfx.DynamicIndexBufferHandle handle, bgfx.Access access - ) { - bgfx.Raw.encoder_set_compute_dynamic_index_buffer(encoder, stage, &handle, access); - } + ) => bgfx.Raw.encoder_set_compute_dynamic_index_buffer(encoder, stage, &handle, access); internal static void EncoderSetComputeDynamicVertexBuffer( bgfx.Encoder* encoder, byte stage, bgfx.DynamicVertexBufferHandle handle, bgfx.Access access - ) { - bgfx.Raw.encoder_set_compute_dynamic_vertex_buffer(encoder, stage, &handle, access); - } + ) => bgfx.Raw.encoder_set_compute_dynamic_vertex_buffer(encoder, stage, &handle, access); internal static void EncoderSetComputeIndexBuffer( bgfx.Encoder* encoder, byte stage, bgfx.IndexBufferHandle handle, bgfx.Access access - ) { - bgfx.Raw.encoder_set_compute_index_buffer(encoder, stage, &handle, access); - } + ) => bgfx.Raw.encoder_set_compute_index_buffer(encoder, stage, &handle, access); internal static void EncoderSetComputeIndirectBuffer( bgfx.Encoder* encoder, byte stage, bgfx.IndirectBufferHandle handle, bgfx.Access access - ) { - bgfx.Raw.encoder_set_compute_indirect_buffer(encoder, stage, &handle, access); - } + ) => bgfx.Raw.encoder_set_compute_indirect_buffer(encoder, stage, &handle, access); internal static void EncoderSetComputeVertexBuffer( bgfx.Encoder* encoder, byte stage, bgfx.VertexBufferHandle handle, bgfx.Access access - ) { - bgfx.Raw.encoder_set_compute_vertex_buffer(encoder, stage, &handle, access); - } + ) => bgfx.Raw.encoder_set_compute_vertex_buffer(encoder, stage, &handle, access); internal static void EncoderSetDynamicIndexBuffer( bgfx.Encoder* encoder, bgfx.DynamicIndexBufferHandle handle, uint firstIndex, uint numIndices - ) { - bgfx.Raw.encoder_set_dynamic_index_buffer(encoder, &handle, firstIndex, numIndices); - } + ) => bgfx.Raw.encoder_set_dynamic_index_buffer(encoder, &handle, firstIndex, numIndices); internal static void EncoderSetDynamicVertexBuffer( bgfx.Encoder* encoder, @@ -259,9 +239,7 @@ internal static void EncoderSetDynamicVertexBuffer( bgfx.DynamicVertexBufferHandle handle, uint startVertex, uint numVertices - ) { - bgfx.Raw.encoder_set_dynamic_vertex_buffer(encoder, stream, &handle, startVertex, numVertices); - } + ) => bgfx.Raw.encoder_set_dynamic_vertex_buffer(encoder, stream, &handle, startVertex, numVertices); internal static void EncoderSetDynamicVertexBufferWithLayout( bgfx.Encoder* encoder, @@ -270,16 +248,14 @@ internal static void EncoderSetDynamicVertexBufferWithLayout( uint startVertex, uint numVertices, bgfx.VertexLayoutHandle layoutHandle - ) { - bgfx.Raw.encoder_set_dynamic_vertex_buffer_with_layout( - encoder, - stream, - &handle, - startVertex, - numVertices, - &layoutHandle - ); - } + ) => bgfx.Raw.encoder_set_dynamic_vertex_buffer_with_layout( + encoder, + stream, + &handle, + startVertex, + numVertices, + &layoutHandle + ); internal static void EncoderSetImage( bgfx.Encoder* encoder, @@ -288,36 +264,28 @@ internal static void EncoderSetImage( byte mip, bgfx.Access access, bgfx.TextureFormat format - ) { - bgfx.Raw.encoder_set_image(encoder, stage, &handle, mip, access, format); - } + ) => bgfx.Raw.encoder_set_image(encoder, stage, &handle, mip, access, format); internal static void EncoderSetIndexBuffer( bgfx.Encoder* encoder, bgfx.IndexBufferHandle handle, uint firstIndex, uint numIndices - ) { - bgfx.Raw.encoder_set_index_buffer(encoder, &handle, firstIndex, numIndices); - } + ) => bgfx.Raw.encoder_set_index_buffer(encoder, &handle, firstIndex, numIndices); internal static void EncoderSetInstanceDataFromDynamicVertexBuffer( bgfx.Encoder* encoder, bgfx.DynamicVertexBufferHandle handle, uint startVertex, uint count - ) { - bgfx.Raw.encoder_set_instance_data_from_dynamic_vertex_buffer(encoder, &handle, startVertex, count); - } + ) => bgfx.Raw.encoder_set_instance_data_from_dynamic_vertex_buffer(encoder, &handle, startVertex, count); internal static void EncoderSetInstanceDataFromVertexBuffer( bgfx.Encoder* encoder, bgfx.VertexBufferHandle handle, uint startVertex, uint count - ) { - bgfx.Raw.encoder_set_instance_data_from_vertex_buffer(encoder, &handle, startVertex, count); - } + ) => bgfx.Raw.encoder_set_instance_data_from_vertex_buffer(encoder, &handle, startVertex, count); internal static void EncoderSetTexture( bgfx.Encoder* encoder, @@ -325,18 +293,14 @@ internal static void EncoderSetTexture( bgfx.UniformHandle sampler, bgfx.TextureHandle handle, uint flags - ) { - bgfx.Raw.encoder_set_texture(encoder, stage, &sampler, &handle, flags); - } + ) => bgfx.Raw.encoder_set_texture(encoder, stage, &sampler, &handle, flags); internal static void EncoderSetUniform( bgfx.Encoder* encoder, bgfx.UniformHandle handle, void* value, ushort count - ) { - bgfx.Raw.encoder_set_uniform(encoder, &handle, value, count); - } + ) => bgfx.Raw.encoder_set_uniform(encoder, &handle, value, count); internal static void EncoderSetVertexBuffer( bgfx.Encoder* encoder, @@ -344,9 +308,7 @@ internal static void EncoderSetVertexBuffer( bgfx.VertexBufferHandle handle, uint startVertex, uint numVertices - ) { - bgfx.Raw.encoder_set_vertex_buffer(encoder, stream, &handle, startVertex, numVertices); - } + ) => bgfx.Raw.encoder_set_vertex_buffer(encoder, stream, &handle, startVertex, numVertices); internal static void EncoderSetVertexBufferWithLayout( bgfx.Encoder* encoder, @@ -355,16 +317,14 @@ internal static void EncoderSetVertexBufferWithLayout( uint startVertex, uint numVertices, bgfx.VertexLayoutHandle layoutHandle - ) { - bgfx.Raw.encoder_set_vertex_buffer_with_layout( - encoder, - stream, - &handle, - startVertex, - numVertices, - &layoutHandle - ); - } + ) => bgfx.Raw.encoder_set_vertex_buffer_with_layout( + encoder, + stream, + &handle, + startVertex, + numVertices, + &layoutHandle + ); internal static void EncoderSubmit( bgfx.Encoder* encoder, @@ -372,9 +332,7 @@ internal static void EncoderSubmit( bgfx.ProgramHandle program, uint depth, byte flags - ) { - bgfx.Raw.encoder_submit(encoder, id, &program, depth, flags); - } + ) => bgfx.Raw.encoder_submit(encoder, id, &program, depth, flags); internal static void EncoderSubmitIndirect( bgfx.Encoder* encoder, @@ -385,80 +343,60 @@ internal static void EncoderSubmitIndirect( uint count, uint depth, byte flags - ) { - bgfx.Raw.encoder_submit_indirect(encoder, id, &program, &indirectHandle, start, count, depth, flags); - } + ) => bgfx.Raw.encoder_submit_indirect(encoder, id, &program, &indirectHandle, start, count, depth, flags); internal static ushort GetShaderUniforms( bgfx.ShaderHandle handle, bgfx.UniformHandle* uniforms, ushort max - ) { - return bgfx.Raw.get_shader_uniforms(&handle, uniforms, max); - } + ) => bgfx.Raw.get_shader_uniforms(&handle, uniforms, max); internal static void GetUniformInfo( bgfx.UniformHandle handle, bgfx.UniformInfo* info - ) { - bgfx.Raw.get_uniform_info(&handle, info); - } + ) => bgfx.Raw.get_uniform_info(&handle, info); internal static uint ReadTexture( bgfx.TextureHandle handle, void* data, byte mip - ) { - return bgfx.Raw.read_texture(&handle, data, mip); - } + ) => bgfx.Raw.read_texture(&handle, data, mip); internal static void SetIndexBufferName( bgfx.IndexBufferHandle handle, sbyte* name, int len - ) { - bgfx.Raw.set_index_buffer_name(&handle, name, len); - } + ) => bgfx.Raw.set_index_buffer_name(&handle, name, len); internal static void SetShaderName( bgfx.ShaderHandle handle, sbyte* name, int len - ) { - bgfx.Raw.set_shader_name(&handle, name, len); - } + ) => bgfx.Raw.set_shader_name(&handle, name, len); internal static void SetTextureName( bgfx.TextureHandle handle, sbyte* name, int len - ) { - bgfx.Raw.set_texture_name(&handle, name, len); - } + ) => bgfx.Raw.set_texture_name(&handle, name, len); internal static void SetVertexBufferName( bgfx.VertexBufferHandle handle, sbyte* name, int len - ) { - bgfx.Raw.set_vertex_buffer_name(&handle, name, len); - } + ) => bgfx.Raw.set_vertex_buffer_name(&handle, name, len); internal static void UpdateDynamicIndexBuffer( bgfx.DynamicIndexBufferHandle handle, uint startIndex, bgfx.Memory* memory - ) { - bgfx.Raw.update_dynamic_index_buffer(&handle, startIndex, memory); - } + ) => bgfx.Raw.update_dynamic_index_buffer(&handle, startIndex, memory); internal static void UpdateDynamicVertexBuffer( bgfx.DynamicVertexBufferHandle handle, uint startVertex, bgfx.Memory* memory - ) { - bgfx.Raw.update_dynamic_vertex_buffer(&handle, startVertex, memory); - } + ) => bgfx.Raw.update_dynamic_vertex_buffer(&handle, startVertex, memory); internal static void UpdateTexture2d( bgfx.TextureHandle handle, @@ -470,9 +408,7 @@ internal static void UpdateTexture2d( ushort height, bgfx.Memory* memory, ushort pitch - ) { - bgfx.Raw.update_texture_2d(&handle, layer, mip, x, y, width, height, memory, pitch); - } + ) => bgfx.Raw.update_texture_2d(&handle, layer, mip, x, y, width, height, memory, pitch); internal static void UpdateTexture3d( bgfx.TextureHandle handle, @@ -484,9 +420,7 @@ internal static void UpdateTexture3d( ushort height, ushort depth, bgfx.Memory* memory - ) { - bgfx.Raw.update_texture_3d(&handle, mip, x, y, z, width, height, depth, memory); - } + ) => bgfx.Raw.update_texture_3d(&handle, mip, x, y, z, width, height, depth, memory); internal static void UpdateTextureCube( bgfx.TextureHandle handle, @@ -499,7 +433,5 @@ internal static void UpdateTextureCube( ushort height, bgfx.Memory* memory, ushort pitch - ) { - bgfx.Raw.update_texture_cube(&handle, layer, side, mip, x, y, width, height, memory, pitch); - } + ) => bgfx.Raw.update_texture_cube(&handle, layer, side, mip, x, y, width, height, memory, pitch); } diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs index 867d98688..dd9443ae9 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxRenderingBackendProvider.cs @@ -26,7 +26,7 @@ public BgfxRenderingBackendProvider(IBgfxSurfaceIntegration surfaceIntegration) m_surfaceIntegration = surfaceIntegration; } - /// + /// public override IRenderDevice CreateDevice(RenderingBackendOptions options) { ArgumentNullException.ThrowIfNull(options); @@ -41,7 +41,7 @@ public override IRenderDevice CreateDevice(RenderingBackendOptions options) }); } - /// + /// public override IRenderLayerCompositionProgramProvider CreateCompositionProgramProvider() => new BgfxCompositionProgramProvider(); } diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs index 0be42fcb4..90262c89a 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/Desktop/CoreClrDeploymentCompiler.cs @@ -41,7 +41,7 @@ IToolchainWorkspaceProvider workspaces ArgumentNullException.ThrowIfNull(workspaces); m_hostPath = hostPath; m_workspaces = workspaces; - capabilities = new ManagedDeploymentCapabilities( + this.capabilities = new ManagedDeploymentCapabilities( runtimeIdentifiers, dynamicCode: true, aheadOfTime: false, @@ -49,13 +49,13 @@ IToolchainWorkspaceProvider workspaces ); } - /// + /// public ManagedDeploymentId id => ManagedDeploymentId.coreClr; - /// + /// public ManagedDeploymentCapabilities capabilities { get; } - /// + /// public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs index 3fc36c14e..afdc46dc1 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/NativeAot/NativeAotDeploymentCompiler.cs @@ -41,7 +41,7 @@ IToolchainWorkspaceProvider workspaces ArgumentNullException.ThrowIfNull(workspaces); m_hostPath = hostPath; m_workspaces = workspaces; - capabilities = new ManagedDeploymentCapabilities( + this.capabilities = new ManagedDeploymentCapabilities( runtimeIdentifiers, dynamicCode: false, aheadOfTime: true, @@ -49,13 +49,13 @@ IToolchainWorkspaceProvider workspaces ); } - /// + /// public ManagedDeploymentId id => ManagedDeploymentId.nativeAot; - /// + /// public ManagedDeploymentCapabilities capabilities { get; } - /// + /// public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs index 738d2912f..192b4cac8 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs @@ -107,14 +107,17 @@ private sealed class TailLogWriter : TextWriter private readonly StreamWriter m_log; private readonly Queue m_tail = new(); - internal TailLogWriter(string path) => m_log = new StreamWriter(path, append: false); + internal TailLogWriter(string path) + { + m_log = new StreamWriter(path, append: false); + } internal string tail => string.Join(Environment.NewLine, m_tail); - /// + /// public override Encoding Encoding => Encoding.UTF8; - /// + /// public override async Task WriteLineAsync(string? value) { await m_log.WriteLineAsync(value).ConfigureAwait(false); @@ -129,7 +132,7 @@ public override async Task WriteLineAsync(string? value) } } - /// + /// public override ValueTask DisposeAsync() => m_log.DisposeAsync(); } } diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs index 838462fa5..934af35af 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/WebAssembly/MonoWasmDeploymentCompiler.cs @@ -21,15 +21,15 @@ public sealed class MonoWasmDeploymentCompiler : IManagedDeploymentCompiler /// /// The .NET executable whose project resolution selects the matching WebAssembly workload. /// - /// - /// Whether managed code is compiled ahead of browser execution. - /// /// /// The platform-contributed managed targets authorized for this implementation. /// /// /// The explicit host execution path provider. /// + /// + /// Whether managed code is compiled ahead of browser execution. + /// /// /// The SDK host is empty or runtime targets are empty, unassigned, or repeated. /// @@ -47,7 +47,7 @@ bool aheadOfTime m_hostPath = hostPath; m_workspaces = workspaces; m_aheadOfTime = aheadOfTime; - capabilities = new ManagedDeploymentCapabilities( + this.capabilities = new ManagedDeploymentCapabilities( runtimeIdentifiers, dynamicCode: false, aheadOfTime: aheadOfTime, @@ -55,13 +55,13 @@ bool aheadOfTime ); } - /// + /// public ManagedDeploymentId id => m_aheadOfTime ? ManagedDeploymentId.monoWasmAot : ManagedDeploymentId.monoWasm; - /// + /// public ManagedDeploymentCapabilities capabilities { get; } - /// + /// public ValueTask CompileAsync( ManagedDeploymentRequest request, CancellationToken cancellationToken = default diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs index 1eca3583d..703235890 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Discovery/ReflectionTypeCatalogSource.cs @@ -13,14 +13,14 @@ namespace Inno.Adapter.Modules.DotNet; /// public sealed class ReflectionTypeCatalogSource : ITypeCatalogSource { - /// + /// public IReadOnlyList GetTypes(Assembly assembly) { ArgumentNullException.ThrowIfNull(assembly); return assembly.GetTypes(); } - /// + /// public TypeCatalogMetadata GetMetadata(Type type) { ArgumentNullException.ThrowIfNull(type); @@ -45,7 +45,7 @@ public TypeCatalogMetadata GetMetadata(Type type) ); } - /// + /// public Type? ConstructGenericType( Type definition, IReadOnlyList arguments @@ -71,7 +71,7 @@ IReadOnlyList arguments } } - /// + /// public bool CanCreateInstance(Type type) { ArgumentNullException.ThrowIfNull(type); @@ -84,7 +84,7 @@ public bool CanCreateInstance(Type type) ) is not null); } - /// + /// public object CreateInstance(Type type) { ArgumentNullException.ThrowIfNull(type); diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs index 2b6e4d771..dd0602de9 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetAssemblyCatalogSource.cs @@ -49,10 +49,10 @@ public DotNetAssemblyCatalogSource(params Assembly[] roots) AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoaded; } - /// + /// public event Action? changed; - /// + /// public IReadOnlyList GetAssemblies() { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -65,7 +65,7 @@ public IReadOnlyList GetAssemblies() } } - /// + /// public IReadOnlyList GetSharedAssemblies() { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -78,13 +78,13 @@ public IReadOnlyList GetSharedAssemblies() } } - /// + /// public bool IsFrameworkReference(string assemblyName) => m_trustedPlatformAssemblies.Contains(assemblyName); - /// + /// public bool IsFrameworkAssembly(Assembly assembly) => IsTrustedFrameworkAssembly(assembly); - /// + /// public void Dispose() { if (m_disposed) diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs index f47817714..edc2f6b39 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/DotNetModuleSource.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -68,7 +69,7 @@ public sealed class DotNetModuleSource : IModuleSource public IReadOnlyDictionary assemblyScopes { get; init; } = new Dictionary(StringComparer.OrdinalIgnoreCase); - /// + /// public IReadOnlyList GetAssemblyNames() { var names = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -93,7 +94,7 @@ private bool HasRequestedClassification( AssemblyScope requestedScope ) => assembly.GetInnoAssemblyDomain() == domain && assembly.GetInnoAssemblyScope() == requestedScope; - /// + /// public ModuleCatalogContribution Prepare(ModuleSourceContext context) { ArgumentNullException.ThrowIfNull(context); @@ -108,7 +109,7 @@ public ModuleCatalogContribution Prepare(ModuleSourceContext context) string generationDirectory = Path.Combine( artifactRootDirectory, SanitizePathSegment(request.moduleName), - context.generation.ToString(System.Globalization.CultureInfo.InvariantCulture) + "-" + Guid.NewGuid().ToString("N") + context.generation.ToString(CultureInfo.InvariantCulture) + "-" + Guid.NewGuid().ToString("N") ); Directory.CreateDirectory(generationDirectory); @@ -226,7 +227,7 @@ private static IReadOnlyDictionary BuildSharedAssemblies( ModuleSourceContext context, IEnumerable ownedNames ) { - var result = context.host.GetSharedAssemblies() + Dictionary result = context.host.GetSharedAssemblies() .GroupBy(static assembly => assembly.GetName().Name!, StringComparer.OrdinalIgnoreCase) .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.OrdinalIgnoreCase); var owned = new HashSet(ownedNames, StringComparer.OrdinalIgnoreCase); @@ -268,12 +269,12 @@ private static void ValidateLoadedModule( IReadOnlyList upstreamModules, IReadOnlyDictionary plannedAssemblies ) { - var ownByName = assemblies.ToDictionary( + Dictionary ownByName = assemblies.ToDictionary( static assembly => assembly.GetName().Name ?? string.Empty, StringComparer.OrdinalIgnoreCase ); ValidateOwnedDependencyGraph(ownByName); - var forbiddenDownstreamNames = context.activeModules + HashSet forbiddenDownstreamNames = context.activeModules .Where(module => ( request.domain == AssemblyDomain.InnoPlugin ? module.domain == AssemblyDomain.InnoScripting @@ -282,7 +283,7 @@ IReadOnlyDictionary plannedAssemblies .SelectMany(static module => module.assemblies) .Select(static assembly => assembly.GetName().Name ?? string.Empty) .ToHashSet(StringComparer.OrdinalIgnoreCase); - var upstreamByName = upstreamModules + Dictionary upstreamByName = upstreamModules .SelectMany(module => module.assemblies.Select(assembly => (module, assembly))) .ToDictionary( static pair => pair.assembly.GetName().Name ?? string.Empty, @@ -313,7 +314,7 @@ IReadOnlyDictionary plannedAssemblies $"Assembly '{assembly.GetName().Name}' has a forbidden downstream reference to '{name}'." ); } - if (upstreamByName.TryGetValue(name, out var upstream)) + if (upstreamByName.TryGetValue(name, out (ModuleCatalogContribution module, Assembly assembly) upstream)) { if (sourceScope == AssemblyScope.Runtime && upstream.module.assemblyScopes[upstream.assembly] == AssemblyScope.Editor diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs index 5249e8ccc..7212e2b76 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Loading/ModuleLoadContext.cs @@ -32,7 +32,7 @@ IEnumerable moduleAssemblyPaths static path => path, StringComparer.OrdinalIgnoreCase ); - Unloading += ReleaseSharedAssemblies; + this.Unloading += ReleaseSharedAssemblies; } /// @@ -60,13 +60,11 @@ IEnumerable moduleAssemblyPaths return null; } - private static void ReleaseSharedAssemblies(AssemblyLoadContext context) - { + private static void ReleaseSharedAssemblies(AssemblyLoadContext context) => // The runtime retains an unloading context until its loader allocator can retire. Keeping // another collectible assembly in this resolver can turn cross-context generic dependencies // into a retention cycle, even after every engine registry has released its generation. ((ModuleLoadContext)context).m_sharedAssemblies = FrozenDictionary.Empty; - } private static void ValidateSharedIdentity( AssemblyName requested, diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs index f11a863d6..834b08138 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/DotNetModuleLifetime.cs @@ -22,7 +22,7 @@ string description m_description = description; } - /// + /// public IAssemblyUnloadProbe BeginRetirement() { if (m_retirement is not null) diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs index afa397cd3..892e824b7 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionCollectionMetadata.cs @@ -338,16 +338,14 @@ params Type[] candidateArgumentTypes private static MethodInfo? FindFactory( Type targetType, Type argumentType - ) { - return targetType - .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) - .FirstOrDefault(method => ( - (method.Name == "CreateRange" || method.Name == "Create") - && targetType.IsAssignableFrom(method.ReturnType) - && method.GetParameters().Length == 1 - && method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType) - )); - } + ) => targetType + .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) + .FirstOrDefault(method => ( + (method.Name == "CreateRange" || method.Name == "Create") + && targetType.IsAssignableFrom(method.ReturnType) + && method.GetParameters().Length == 1 + && method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType) + )); private static MethodInfo? ResolveSequenceAddMethod( Type targetType, diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs index 329de03be..41f9736ed 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionObjectMetadata.cs @@ -92,10 +92,8 @@ private static SerializationMemberMetadata[] BuildSerializableMembers(Type runti } private static int GetSerializableOrder(MemberInfo member) - { - return member.GetCustomAttribute(inherit: true)?.order - ?? int.MaxValue; - } + => member.GetCustomAttribute(inherit: true)?.order + ?? int.MaxValue; private static SerializationMemberMetadata CreateFieldMember( Type runtimeType, @@ -157,12 +155,7 @@ PropertyVisibility visibility } private static MethodInfo[] GetRestoreHooks(Type runtimeType) - { - return S_RESTORE_HOOKS.GetValue( - runtimeType, - static value => new RestoreHooksBox(BuildRestoreHooks(value)) - ).hooks; - } + => S_RESTORE_HOOKS.GetValue(runtimeType, static value => new RestoreHooksBox(BuildRestoreHooks(value))).hooks; private static MethodInfo[] BuildRestoreHooks(Type runtimeType) { diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs index 7d80ec97c..4ec82e927 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/Discovery/ReflectionStructMetadata.cs @@ -15,9 +15,7 @@ internal static class ReflectionStructMetadata private static readonly ConditionalWeakTable S_CACHE = new(); internal static SerializationMemberMetadata[] GetMembers(Type structType) - { - return S_CACHE.GetValue(structType, static type => new MembersBox(BuildMembers(type))).members; - } + => S_CACHE.GetValue(structType, static type => new MembersBox(BuildMembers(type))).members; internal static bool HasPureFieldAccess( Type type, @@ -36,7 +34,7 @@ SerializationTypeMetadata metadata && field.FieldType != typeof(IntPtr) && field.FieldType != typeof(UIntPtr) && field.FieldType != typeof(char) - || field.FieldType == typeof(decimal) || field.FieldType == typeof(System.Guid) || field.FieldType == typeof(string)) + || field.FieldType == typeof(decimal) || field.FieldType == typeof(Guid) || field.FieldType == typeof(string)) ) { return false; } @@ -85,10 +83,8 @@ private static SerializationMemberMetadata[] BuildMembers(Type structType) } private static int GetSerializableOrder(MemberInfo member) - { - return member.GetCustomAttribute(inherit: true)?.order - ?? int.MaxValue; - } + => member.GetCustomAttribute(inherit: true)?.order + ?? int.MaxValue; private static SerializationMemberMetadata? TryCreateField( Type structType, diff --git a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs index ad6924fc8..d83a9e2f2 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Serialization.DotNet/ReflectionSerializationMetadataSource.cs @@ -14,7 +14,7 @@ public sealed class ReflectionSerializationMetadataSource : ISerializationMetada { private readonly ConditionalWeakTable m_metadata = new(); - /// + /// public SerializationTypeMetadata GetMetadata(Type type) { ArgumentNullException.ThrowIfNull(type); diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs index 355c4cf95..046b17284 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheGeneration.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Security.Cryptography; +using System.Threading; using Inno.Content; using Inno.Core.IO; @@ -94,63 +95,63 @@ Action release m_release = release; } - /// + /// public override bool CanRead => m_release is not null; - /// + /// public override bool CanSeek => m_release is not null; - /// + /// public override bool CanWrite => false; - /// + /// public override long Length => m_input.Length; - /// + /// public override long Position { get => m_input.Position; set => m_input.Position = value; } - /// + /// public override int Read( byte[] buffer, int offset, int count ) => m_input.Read(buffer, offset, count); - /// + /// public override int Read(Span buffer) => m_input.Read(buffer); - /// + /// public override int ReadByte() => m_input.ReadByte(); - /// + /// public override long Seek( long offset, SeekOrigin origin ) => m_input.Seek(offset, origin); - /// + /// public override void Flush() => throw new NotSupportedException(); - /// + /// public override void SetLength(long value) => throw new NotSupportedException(); - /// + /// public override void Write( byte[] buffer, int offset, int count ) => throw new NotSupportedException(); - /// + /// protected override void Dispose(bool disposing) { if (disposing) { - Action? release = System.Threading.Interlocked.Exchange(ref m_release, null); + Action? release = Interlocked.Exchange(ref m_release, null); if (release is not null) { try diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs index 2aaa91930..b6fbf48f3 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCachePublication.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.IO; using System.Text; using System.Threading; @@ -28,7 +29,7 @@ CancellationToken cancellationToken Directory.CreateDirectory(Path.GetDirectoryName(output)!); using ContentReadLease lease = source.Acquire(entry.key); using Stream input = lease.OpenRead(); - await using FileStream destination = new( + await using var destination = new FileStream( output, FileMode.CreateNew, FileAccess.Write, @@ -37,7 +38,7 @@ CancellationToken cancellationToken FileOptions.Asynchronous | FileOptions.SequentialScan ); long remaining = entry.length; - byte[] buffer = System.Buffers.ArrayPool.Shared.Rent(128 * 1024); + byte[] buffer = ArrayPool.Shared.Rent(128 * 1024); try { while (remaining > 0) @@ -62,7 +63,7 @@ CancellationToken cancellationToken } finally { - System.Buffers.ArrayPool.Shared.Return(buffer); + ArrayPool.Shared.Return(buffer); } } if (!ContentCacheValidator.Validate(candidate, source.index, cancellationToken)) diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs index 206aaa5b1..0ebf1ce6e 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/ContentCacheValidator.cs @@ -20,8 +20,8 @@ CancellationToken cancellationToken { return false; } - HashSet files = new(StringComparer.Ordinal); - HashSet directories = new(StringComparer.Ordinal); + var files = new HashSet(StringComparer.Ordinal); + var directories = new HashSet(StringComparer.Ordinal); foreach (ContentEntry entry in index.entries) { string key = entry.key.value!; @@ -31,7 +31,7 @@ CancellationToken cancellationToken directories.Add(key[..separator]); } } - Stack pending = new(); + var pending = new Stack(); pending.Push(root); while (pending.TryPop(out string? directory)) { @@ -68,7 +68,7 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); try { - using FileStream input = new(Resolve(root, entry.key), FileMode.Open, FileAccess.Read, FileShare.Read); + using var input = new FileStream(Resolve(root, entry.key), FileMode.Open, FileAccess.Read, FileShare.Read); if (input.Length != entry.length) { return false; diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs index f99df7743..7e0b5bbec 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentDeployment.cs @@ -155,7 +155,7 @@ CancellationToken cancellationToken { throw new InvalidDataException($"Deployment metadata '{fileName}' exceeds its document budget."); } - byte[] bytes = new byte[checked((int)stream.Length)]; + var bytes = new byte[checked((int)stream.Length)]; await stream.ReadExactlyAsync(bytes, cancellationToken).ConfigureAwait(false); if (stream.ReadByte() != -1) { diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs index 31f38f3b3..a785bac70 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentPreparation.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -76,7 +77,7 @@ public static async ValueTask PrepareAsync( ).ConfigureAwait(false); try { - var diagnostics = await ContentCacheRetirement.RetireAsync(cache, current!).ConfigureAwait(false); + IReadOnlyList diagnostics = await ContentCacheRetirement.RetireAsync(cache, current!).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); return new FileContentStore( source.descriptor, diff --git a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs index 483745064..672713e18 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Content.FileSystem/FileContentStore.cs @@ -25,10 +25,10 @@ IReadOnlyList retirementDiagnostics this.retirementDiagnostics = retirementDiagnostics; } - /// + /// public ContentPackDescriptor descriptor { get; } - /// + /// public ContentPackIndex index { get; } /// @@ -36,7 +36,7 @@ IReadOnlyList retirementDiagnostics /// public IReadOnlyList retirementDiagnostics { get; } - /// + /// public ContentReadLease Acquire(ContentKey key) { lock (m_sync) diff --git a/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs b/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs index 4834db4b3..6ae50f6f5 100644 --- a/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs +++ b/backends/FileSystem/runtime/Inno.Adapter.Storage.FileSystem/FileSystemStorageBackendProvider.cs @@ -31,7 +31,7 @@ public FileSystemStorageBackendProvider(string rootDirectory) m_rootDirectory = Path.GetFullPath(rootDirectory); } - /// + /// public override IApplicationStorage CreateStorage(StorageScope scope) { if (!scope.isValid) diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs index faa32839c..f29c8b2c0 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/CImguizmoBuildUtils.cs @@ -32,14 +32,14 @@ string cimguiDir ); } - var cimguizmoCpp = Path.Combine(cimguizmoDir, CImguizmoBuildConstants.CIMGUIMO_CPP_FILE); + string cimguizmoCpp = Path.Combine(cimguizmoDir, CImguizmoBuildConstants.CIMGUIMO_CPP_FILE); if (!File.Exists(cimguizmoCpp)) { throw new FileNotFoundException($"Missing {CImguizmoBuildConstants.CIMGUIMO_CPP_FILE}: {cimguizmoCpp}"); } - var imguizmoDir = Path.Combine(cimguizmoDir, CImguizmoBuildConstants.IMGUIZMO_DIR_NAME); - var imguizmoCpp = Path.Combine(imguizmoDir, CImguizmoBuildConstants.IMGUIZMO_CPP_FILE); + string imguizmoDir = Path.Combine(cimguizmoDir, CImguizmoBuildConstants.IMGUIZMO_DIR_NAME); + string imguizmoCpp = Path.Combine(imguizmoDir, CImguizmoBuildConstants.IMGUIZMO_CPP_FILE); if (!File.Exists(imguizmoCpp)) { throw new FileNotFoundException($"Missing {CImguizmoBuildConstants.IMGUIZMO_CPP_FILE}: {imguizmoCpp}"); diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs index 737a8a53f..7c730e16b 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs @@ -31,18 +31,18 @@ public static class ImGuizmoToolchain /// /// The matching published ImGui product providing the native link dependency. /// - /// - /// The configuration is invalid. - /// - /// - /// A native build process fails. - /// /// /// Cancels child processes and prevents artifact installation after cancellation. /// /// /// The validated gizmo library linked against the explicitly supplied ImGui product. /// + /// + /// The configuration is invalid. + /// + /// + /// A native build process fails. + /// /// /// The operation was canceled. /// diff --git a/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs b/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs index e964b415b..fa7e51acb 100644 --- a/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs +++ b/backends/ImGui/native/Inno.Native.ImGuizmo/ImGuizmoModuleProvider.cs @@ -18,7 +18,7 @@ INativeModuleProvider dependency m_dependency = dependency; } - /// + /// public bool TryGetExport( string name, out nint address diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs index a283c936f..761cdcea5 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiRenderer.cs @@ -109,7 +109,7 @@ GraphicsPipelineDescriptor pipelineDescriptor /// public bool supportsViewports => m_bgfxDevice.supportsAdditionalSurfaces; - /// + /// public bool supportsVertexOffsets => true; /// @@ -291,10 +291,7 @@ IntPtr drawData /// /// The existing target that receives the validated result. /// - public void PresentViewport(PlatformImGuiViewportTarget target) - { - ArgumentNullException.ThrowIfNull(target); - } + public void PresentViewport(PlatformImGuiViewportTarget target) => ArgumentNullException.ThrowIfNull(target); /// /// Destroys the auxiliary viewport and releases its rendering resources. @@ -323,7 +320,7 @@ public Task RetireViewport(PlatformImGuiViewportTarget target) return Task.CompletedTask; } - /// + /// public void DrainViewportRetirements() => m_bgfxDevice.DrainWindowSurfaceRetirements(); /// @@ -640,8 +637,8 @@ private void PrepareDrawPackets() } EnsureDynamicBuffers(vertexCount, indexCount); - byte[] vertices = new byte[checked(vertexCount * C_VERTEX_STRIDE)]; - byte[] indices = new byte[checked(indexCount * C_INDEX_STRIDE)]; + var vertices = new byte[checked(vertexCount * C_VERTEX_STRIDE)]; + var indices = new byte[checked(indexCount * C_INDEX_STRIDE)]; List prepared = []; int vertexBase = 0; int indexBase = 0; @@ -704,7 +701,7 @@ int indexCount new RenderBufferDescriptor(capacity, C_VERTEX_STRIDE, RenderBufferUsage.Vertex | RenderBufferUsage.Dynamic), S_VERTEX_LAYOUT ), - ReadOnlySpan.Empty, + [], "ImGui Vertices" ); if (m_vertexBuffer.isValid) @@ -724,7 +721,7 @@ int indexCount new RenderBufferDescriptor(capacity, C_INDEX_STRIDE, RenderBufferUsage.Index | RenderBufferUsage.Dynamic), indexFormat: RenderIndexFormat.UInt16 ), - ReadOnlySpan.Empty, + [], "ImGui Indices" ); if (m_indexBuffer.isValid) @@ -747,13 +744,13 @@ RenderSurfaceHandle surface return null; } - var drawData = (ImDrawData*)address; + ImDrawData* drawData = (ImDrawData*)address; if (drawData->Valid == 0 || drawData->TotalVtxCount <= 0 || drawData->TotalIdxCount <= 0) { return null; } - Vector2 clipScale = new(drawData->FramebufferScale.X, drawData->FramebufferScale.Y); + var clipScale = new Vector2(drawData->FramebufferScale.X, drawData->FramebufferScale.Y); int pixelWidth = checked((int)MathF.Round(drawData->DisplaySize.X * clipScale.X)); int pixelHeight = checked((int)MathF.Round(drawData->DisplaySize.Y * clipScale.Y)); if (pixelWidth <= 0 || pixelHeight <= 0) @@ -761,12 +758,12 @@ RenderSurfaceHandle surface return null; } ProcessTextureRequests(drawData); - byte[] vertices = new byte[checked(drawData->TotalVtxCount * C_VERTEX_STRIDE)]; - byte[] indices = new byte[checked(drawData->TotalIdxCount * C_INDEX_STRIDE)]; + var vertices = new byte[checked(drawData->TotalVtxCount * C_VERTEX_STRIDE)]; + var indices = new byte[checked(drawData->TotalIdxCount * C_INDEX_STRIDE)]; List commands = []; int vertexBase = 0; int indexBase = 0; - Vector2 clipOffset = new(drawData->DisplayPos.X, drawData->DisplayPos.Y); + var clipOffset = new Vector2(drawData->DisplayPos.X, drawData->DisplayPos.Y); for (int listIndex = 0; listIndex < drawData->CmdListsCount; listIndex++) { ImDrawList* drawList = drawData->CmdLists.Data[listIndex]; @@ -780,7 +777,7 @@ RenderSurfaceHandle surface for (int commandIndex = 0; commandIndex < drawList->CmdBuffer.Size; commandIndex++) { ImDrawCmd command = drawList->CmdBuffer.Data[commandIndex]; - if (command.UserCallback != null || command.ElemCount == 0) + if (command.UserCallback is not null || command.ElemCount == 0) { continue; } @@ -828,7 +825,7 @@ RenderSurfaceHandle surface private void ProcessTextureRequests(ImDrawData* drawData) { - var textures = drawData->Textures; + ImVectorImTextureDataPtr* textures = drawData->Textures; if (textures is null) { return; @@ -837,7 +834,7 @@ private void ProcessTextureRequests(ImDrawData* drawData) for (int index = 0; index < textures->Size; index++) { ImTextureData* textureData = textures->Data[index]; - if (textureData == null) + if (textureData is null) { continue; } @@ -886,7 +883,7 @@ private static byte[] CopyTexturePixels(ImTextureData* textureData) if (textureData->Format == ImTextureFormat.Rgba32) { int rowBytes = checked(textureData->Width * 4); - byte[] result = new byte[checked(rowBytes * textureData->Height)]; + var result = new byte[checked(rowBytes * textureData->Height)]; for (int y = 0; y < textureData->Height; y++) { new ReadOnlySpan(textureData->Pixels + (y * sourcePitch), rowBytes) @@ -896,7 +893,7 @@ private static byte[] CopyTexturePixels(ImTextureData* textureData) return result; } - byte[] expanded = new byte[checked(textureData->Width * textureData->Height * 4)]; + var expanded = new byte[checked(textureData->Width * textureData->Height * 4)]; for (int y = 0; y < textureData->Height; y++) { byte* source = textureData->Pixels + (y * sourcePitch); @@ -1032,14 +1029,14 @@ int minimum private static byte[] CreateOutputEncoding() { - byte[] data = new byte[16]; + var data = new byte[16]; BinaryPrimitives.WriteSingleLittleEndian(data, 1f); return data; } private static byte[] CreatePresentationVertices(bool originBottomLeft) { - byte[] data = new byte[4 * C_VERTEX_STRIDE]; + var data = new byte[4 * C_VERTEX_STRIDE]; float top = originBottomLeft ? 1f : 0f; float bottom = originBottomLeft ? 0f : 1f; WriteVertex(0, -1f, 1f, 0f, top); @@ -1114,7 +1111,10 @@ private sealed class ViewportState /// /// The existing target that receives the validated result. /// - public ViewportState(PlatformImGuiViewportTarget target) => this.target = target; + public ViewportState(PlatformImGuiViewportTarget target) + { + this.target = target; + } /// /// Gets the platform viewport whose render resources are tracked by this state. diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs index 8864a1671..0827f63ac 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/BgfxImGuiShaderArtifacts.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using Inno.Rendering; @@ -32,7 +33,7 @@ public static GraphicsPipelineDescriptor Load(GraphicsApi api) using var bytes = new MemoryStream(); source.CopyTo(bytes); GraphicsPipelineDescriptor program = GraphicsProgramArtifactCodec.Decode(bytes.ToArray(), BgfxImGuiRenderer.vertexLayout); - var bindings = program.bindings; + IReadOnlyList bindings = program.bindings; RenderShaderBindingDescriptor? texture = bindings.SingleOrDefault(static binding => binding.id.value == "s_tex"); RenderShaderBindingDescriptor? outputEncoding = bindings.SingleOrDefault(static binding => binding.id.value == "outputEncoding"); if (bindings.Count != 2 || texture is null || texture.kind != RenderShaderBindingKind.Texture diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs index ecc1e4593..f59bcb7e7 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Bgfx/ImGuiPresentationProvider.cs @@ -26,7 +26,7 @@ public ImGuiPresentationProvider(ImGuiInteractionOptions interaction) m_interaction = interaction; } - /// + /// public override IPresentationContext CreateContext(PresentationBackendOptions options) => new ImGuiPresentationContext(options, m_interaction); } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs index 9625fbd76..118fc563e 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/Sdl3PlatformApplicationImGuiExtensions.cs @@ -26,10 +26,7 @@ internal ImGuiState(Sdl3PlatformApplication application) internal Dictionary contexts { get; } = []; internal bool isRetiring => m_isRetiring; - internal void Register() - { - m_registration = m_application.RegisterExtension(this); - } + internal void Register() => m_registration = m_application.RegisterExtension(this); internal void Release( uint windowId, @@ -94,12 +91,12 @@ void ISdl3ApplicationExtension.OnApplicationDisposing(Sdl3PlatformApplication ap /// /// Target platform window. /// - /// - /// Explicit immutable keyboard and wheel conventions supplied by the product. - /// /// /// ImGui context feature flags. /// + /// + /// Explicit immutable keyboard and wheel conventions supplied by the product. + /// /// /// Optional presentation backend; ownership transfers on success and remains with the caller on failure. /// diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs index 0f4f056c3..7ac319ca6 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs @@ -40,7 +40,7 @@ private static void PlatformSetClipboardTextCallback( ) { try { - if (text != null && FindClipboardContext(context) is not null) + if (text is not null && FindClipboardContext(context) is not null) { _ = SDL.Raw.SetClipboardText(text); } @@ -53,7 +53,7 @@ private static void PlatformSetClipboardTextCallback( private static PlatformImGuiContext? FindClipboardContext(ImGuiNativeContext* context) { - if (context == null) + if (context is null) { return null; } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs index 7e9865784..ac92b75b7 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.cs @@ -19,9 +19,9 @@ namespace Inno.Adapter.Presentation.ImGui; public sealed unsafe partial class PlatformImGuiContext { private const float DEFAULT_KEY_REPEAT_DELAY_SECONDS = 0.275f; - private const float DEFAULT_KEY_REPEAT_RATE_SECONDS = 0.050f; - private const float DEFAULT_FONT_SIZE_PIXELS = 16.0f; - private const float DEFAULT_ICON_SIZE_PIXELS = 14.0f; + private const float DEFAULT_KEY_REPEAT_RATE_SECONDS = 0.05f; + private const float DEFAULT_FONT_SIZE_PIXELS = 16f; + private const float DEFAULT_ICON_SIZE_PIXELS = 14f; private const float DEFAULT_MOUSE_SCROLLING_UNITS = 0.3f; private const string DEFAULT_FONTS_DIRECTORY_RELATIVE_PATH = "BuiltIn/Fonts"; private const string DEFAULT_ICONS_DIRECTORY_RELATIVE_PATH = "BuiltIn/Icons"; @@ -64,8 +64,8 @@ internal PlatformImGuiContext( Action releaseRegistration ) { m_releaseRegistration = releaseRegistration ?? throw new ArgumentNullException(nameof(releaseRegistration)); - var enableViewports = (contextFlags & ImGuiContextFlags.EnableViewports) != 0; - var enableDocking = (contextFlags & ImGuiContextFlags.EnableDocking) != 0; + bool enableViewports = (contextFlags & ImGuiContextFlags.EnableViewports) != 0; + bool enableDocking = (contextFlags & ImGuiContextFlags.EnableDocking) != 0; m_enableSmoothResize = (contextFlags & ImGuiContextFlags.EnableSmoothResize) != 0; m_interaction = interaction; @@ -75,7 +75,7 @@ Action releaseRegistration try { - var io = ImGuiNative.Raw.GetIO(); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); // SDL cannot reliably identify the viewport beneath a transient NoInputs viewport while // docking, and the official SDL backend disables this capability on macOS. Let Dear ImGui // use its viewport heuristic instead of publishing incorrect hovered viewport identities. @@ -175,7 +175,7 @@ public partial void SetIniFile(string? filePath) } ImGuiNative.Raw.SetCurrentContext(m_context); - var io = ImGuiNative.Raw.GetIO(); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); if (m_iniFilename != IntPtr.Zero) { Marshal.FreeCoTaskMem(m_iniFilename); @@ -332,7 +332,7 @@ float fontSizePixels ImGuiNative.Raw.SetCurrentContext(m_context); ImGuiIO* io = ImGuiNative.Raw.GetIO(); ImFont* loadedFont = LoadFont(io->Fonts, fullPath, fontSizePixels); - if (loadedFont == null) + if (loadedFont is null) { throw new InvalidOperationException($"Could not load the font '{fullPath}'."); } @@ -350,17 +350,17 @@ private static void ConfigureFonts( ImGuiNativeContext* context, ImGuiIO* io ) { - var fonts = io->Fonts; + ImFontAtlas* fonts = io->Fonts; ImGuiNative.Raw.Clear(fonts); - ResolveFontPaths(out var fontPaths, out var iconFontPaths); + ResolveFontPaths(out List fontPaths, out List iconFontPaths); var styleFonts = new Dictionary(); ImFont* defaultFont = null; - var preferredIndex = FindPreferredFontIndex(fontPaths); - for (var i = 0; i < fontPaths.Count; i++) + int preferredIndex = FindPreferredFontIndex(fontPaths); + for (int i = 0; i < fontPaths.Count; i++) { ImFont* loadedFont = LoadFont(fonts, fontPaths[i], DEFAULT_FONT_SIZE_PIXELS); - if (loadedFont == null) + if (loadedFont is null) { continue; } @@ -371,23 +371,23 @@ private static void ConfigureFonts( { defaultFont = loadedFont; } - else if (defaultFont == null) + else if (defaultFont is null) { defaultFont = loadedFont; } } - if (defaultFont == null) + if (defaultFont is null) { defaultFont = LoadDefaultFont(fonts); - if (defaultFont != null) + if (defaultFont is not null) { MergeIconFontsIntoCurrentBaseFont(fonts, iconFontPaths); } } io->FontDefault = defaultFont; - if (defaultFont != null && !styleFonts.ContainsKey(ImGuiFontStyle.Regular)) + if (defaultFont is not null && !styleFonts.ContainsKey(ImGuiFontStyle.Regular)) { styleFonts[ImGuiFontStyle.Regular] = (nint)defaultFont; } @@ -410,9 +410,9 @@ private static int FindPreferredFontIndex(List fontPaths) return -1; } - for (var i = 0; i < fontPaths.Count; i++) + for (int i = 0; i < fontPaths.Count; i++) { - var fileName = Path.GetFileName(fontPaths[i]); + string fileName = Path.GetFileName(fontPaths[i]); if (fileName.Equals(DEFAULT_FONT_FILE_NAME, StringComparison.OrdinalIgnoreCase)) { return i; @@ -426,16 +426,16 @@ private static void ResolveFontPaths( out List baseFonts, out List iconFonts ) { - baseFonts = new List(); - iconFonts = new List(); + baseFonts = []; + iconFonts = []; var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var fontDirectory in ResolveAssetDirectories(DEFAULT_FONTS_DIRECTORY_RELATIVE_PATH)) + foreach (string fontDirectory in ResolveAssetDirectories(DEFAULT_FONTS_DIRECTORY_RELATIVE_PATH)) { CollectFontFiles(fontDirectory, baseFonts, seen, includeSubdirectories: false); } - foreach (var iconDirectory in ResolveAssetDirectories(DEFAULT_ICONS_DIRECTORY_RELATIVE_PATH)) + foreach (string iconDirectory in ResolveAssetDirectories(DEFAULT_ICONS_DIRECTORY_RELATIVE_PATH)) { CollectFontFiles(iconDirectory, iconFonts, seen, includeSubdirectories: false); } @@ -448,20 +448,20 @@ private static List ResolveAssetDirectories(string relativePath) { var directories = new List(); var seen = new HashSet(StringComparer.OrdinalIgnoreCase); - var candidates = new[] + string[] candidates = new[] { Path.Combine(AppContext.BaseDirectory, relativePath), Path.Combine(Path.GetDirectoryName(typeof(PlatformImGuiContext).Assembly.Location) ?? string.Empty, relativePath) }; - foreach (var candidate in candidates) + foreach (string candidate in candidates) { if (string.IsNullOrWhiteSpace(candidate)) { continue; } - var fullPath = Path.GetFullPath(candidate); + string fullPath = Path.GetFullPath(candidate); if (Directory.Exists(fullPath) && seen.Add(fullPath)) { directories.Add(fullPath); @@ -477,18 +477,18 @@ private static void CollectFontFiles( HashSet seen, bool includeSubdirectories ) { - var searchOption = includeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; - var fontFiles = Directory.GetFiles(directory, "*.*", searchOption); - foreach (var fontFile in fontFiles) + SearchOption searchOption = includeSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + string[] fontFiles = Directory.GetFiles(directory, "*.*", searchOption); + foreach (string fontFile in fontFiles) { - var extension = Path.GetExtension(fontFile); + string extension = Path.GetExtension(fontFile); if (!extension.Equals(".ttf", StringComparison.OrdinalIgnoreCase) && !extension.Equals(".otf", StringComparison.OrdinalIgnoreCase) ) { continue; } - var fullPath = Path.GetFullPath(fontFile); + string fullPath = Path.GetFullPath(fontFile); if (seen.Add(fullPath)) { output.Add(fullPath); @@ -505,7 +505,7 @@ List iconFontPaths return; } - for (var index = 0; index < iconFontPaths.Count; index++) + for (int index = 0; index < iconFontPaths.Count; index++) { ImFontConfig* mergeConfig = ImGuiNative.Raw.ImFontConfig(); mergeConfig->MergeMode = 1; @@ -529,16 +529,16 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) } ImGuiNative.Raw.SetCurrentContext(m_context); - var io = ImGuiNative.Raw.GetIO(); - var eventType = (SDLEventType)sdlEvent.Type; + ImGuiIO* io = ImGuiNative.Raw.GetIO(); + SDLEventType eventType = (SDLEventType)sdlEvent.Type; - if (!TryGetWindowId(ref sdlEvent, out var eventWindowId)) + if (!TryGetWindowId(ref sdlEvent, out uint eventWindowId)) { m_viewports?.ProcessEvent(ref sdlEvent, 0); return; } - if (eventWindowId != m_window.windowId && (m_viewports == null || !m_viewports.OwnsWindow(eventWindowId))) + if (eventWindowId != m_window.windowId && (m_viewports is null || !m_viewports.OwnsWindow(eventWindowId))) { return; } @@ -555,7 +555,7 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) case SDLEventType.KeyDown: case SDLEventType.KeyUp: { - var down = eventType == SDLEventType.KeyDown; + bool down = eventType == SDLEventType.KeyDown; if (down && sdlEvent.Key.Repeat != 0) { // Keep key-repeat timing driven by ImGui (io->KeyRepeatDelay/KeyRepeatRate). @@ -564,7 +564,7 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) UpdateKeyModifiers(io, (SDLKeymod)sdlEvent.Key.Mod); - var key = TranslateKey(sdlEvent.Key.Scancode); + ImGuiKey key = TranslateKey(sdlEvent.Key.Scancode); if (key != ImGuiKey.None) { ImGuiNative.Raw.AddKeyEvent(io, key, down ? (byte)1 : (byte)0); @@ -581,7 +581,7 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) case SDLEventType.TextInput: { - if (sdlEvent.Text.Text != null) + if (sdlEvent.Text.Text is not null) { ImGuiNative.Raw.AddInputCharactersUTF8(io, sdlEvent.Text.Text); } @@ -623,8 +623,8 @@ internal void ProcessEvent(ref SDLEvent sdlEvent) case SDLEventType.MouseWheel: { - var wheelX = sdlEvent.Wheel.X; - var wheelY = sdlEvent.Wheel.Y; + float wheelX = sdlEvent.Wheel.X; + float wheelY = sdlEvent.Wheel.Y; wheelX *= m_interaction.horizontalWheelDirection; @@ -681,15 +681,15 @@ internal void PrepareLiveResizeWindow(uint windowId) return; } - var ownsMainWindow = windowId == m_window.windowId; - var ownsViewportWindow = m_viewports?.OwnsWindow(windowId) == true; + bool ownsMainWindow = windowId == m_window.windowId; + bool ownsViewportWindow = m_viewports?.OwnsWindow(windowId) == true; if (!ownsMainWindow && !ownsViewportWindow) { return; } m_pendingLiveResizeWindowIds.Add(windowId); - var now = m_frameTimer.Elapsed; + TimeSpan now = m_frameTimer.Elapsed; m_liveResizeLockedWindowId = windowId; m_lastLiveResizeLockTime = now; } @@ -717,8 +717,8 @@ public partial IntPtr RenderFrame( throw new InvalidOperationException("An ImGui frame cannot be reentered."); } - var now = m_frameTimer.Elapsed; - var deltaSeconds = (float)(now - m_lastFrameTime).TotalSeconds; + TimeSpan now = m_frameTimer.Elapsed; + float deltaSeconds = (float)(now - m_lastFrameTime).TotalSeconds; m_lastFrameTime = now; m_isFrameOperationActive = true; @@ -782,7 +782,7 @@ private void BeginFrame( m_viewports?.ProcessRetirements(); m_hasStartedFrame = true; - var io = ImGuiNative.Raw.GetIO(); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); io->MouseDrawCursor = 0; UpdateDisplayMetrics(io); io->DeltaTime = deltaTimeSeconds > 0f ? deltaTimeSeconds : (1f / 60f); @@ -798,10 +798,10 @@ private void BeginFrame( ImGuiNative.NewFrame(); // During live resize, prevent the main viewport from hosting other windows. - var mainViewport = ImGuiNative.Raw.GetMainViewport(); + ImGuiViewport* mainViewport = ImGuiNative.Raw.GetMainViewport(); if (m_liveResizeLockedWindowId != 0 && (io->ConfigFlags & (int)ImGuiConfigFlags.ViewportsEnable) != 0 - && mainViewport != null + && mainViewport is not null ) { mainViewport->Flags &= ~(int)ImGuiViewportFlags.CanHostOtherWindows; } @@ -814,7 +814,7 @@ private IntPtr EndFrame() throw new ObjectDisposedException(nameof(PlatformImGuiContext)); } - var io = ImGuiNative.Raw.GetIO(); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); try { @@ -824,7 +824,7 @@ private IntPtr EndFrame() ImGuiNative.Render(); io->MouseDrawCursor = 0; - var drawData = ImGuiNative.Raw.GetDrawData(); + ImDrawData* drawData = ImGuiNative.Raw.GetDrawData(); m_renderer.RenderMain(GetDrawDataAddress(drawData)); if ((io->ConfigFlags & (int)ImGuiConfigFlags.ViewportsEnable) != 0) { @@ -853,14 +853,14 @@ ref SDLEvent sdlEvent float mouseX = 0f; float mouseY = 0f; - var mouseButtons = ((SDLMouseButtonFlags)SDL.Raw.GetMouseState(&mouseX, &mouseY)); + SDLMouseButtonFlags mouseButtons = ((SDLMouseButtonFlags)SDL.Raw.GetMouseState(&mouseX, &mouseY)); if ((mouseButtons & SDLMouseButtonFlags.Left) == 0) { m_liveResizeLockedWindowId = 0; return; } - var now = m_frameTimer.Elapsed; + TimeSpan now = m_frameTimer.Elapsed; if (eventType == SDLEventType.WindowExposed && eventWindowId == m_liveResizeLockedWindowId) { m_lastLiveResizeLockTime = now; @@ -889,13 +889,13 @@ ref SDLEvent sdlEvent /// /// Retires the context and its owned resources after the current frame operation has completed. /// + /// + /// A frame operation still owns the context; the caller must retry after that operation completes. + /// /// /// Successful retirement removes this context's application registration and releases its borrowed font data. /// Pending or failed retirement preserves both registration and ownership for a subsequent retry. /// - /// - /// A frame operation still owns the context; the caller must retry after that operation completes. - /// public partial void Dispose() { if (m_disposed) @@ -909,11 +909,11 @@ public partial void Dispose() } ImGuiNative.Raw.SetCurrentContext(m_context); - var io = ImGuiNative.Raw.GetIO(); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); UnregisterClipboardCallbacks(); if (m_textInputActive) { - var textInputWindow = m_textInputWindow == null ? m_window.GetSdlWindow() : m_textInputWindow; + SDLWindow* textInputWindow = m_textInputWindow is null ? m_window.GetSdlWindow() : m_textInputWindow; _ = SDL.Raw.StopTextInput(textInputWindow); m_textInputWindow = null; m_textInputActive = false; @@ -933,7 +933,7 @@ public partial void Dispose() m_viewports?.Dispose(); m_renderer.DrainViewportRetirements(); - foreach (var cursor in m_cursors.Values) + foreach (nint cursor in m_cursors.Values) { if (cursor != 0) { @@ -958,13 +958,13 @@ public partial void Dispose() private void UpdateDisplayMetrics(ImGuiIO* io) { - var windowWidth = 0; - var windowHeight = 0; + int windowWidth = 0; + int windowHeight = 0; SDLWindow* sdlWindow = m_window.GetSdlWindow(); SDL.Raw.GetWindowSize(sdlWindow, &windowWidth, &windowHeight); - var pixelWidth = 0; - var pixelHeight = 0; + int pixelWidth = 0; + int pixelHeight = 0; SDL.Raw.GetWindowSizeInPixels(sdlWindow, &pixelWidth, &pixelHeight); io->DisplaySize = new ImVec2C { X = windowWidth, Y = windowHeight }; @@ -985,12 +985,12 @@ private void UpdateDisplayMetrics(ImGuiIO* io) private void UpdateTextInputState(ImGuiIO* io) { - var targetWindow = ResolveTextInputWindow(); + SDLWindow* targetWindow = ResolveTextInputWindow(); if (io->WantTextInput != 0) { if (!m_textInputActive || m_textInputWindow != targetWindow) { - if (m_textInputActive && m_textInputWindow != null) + if (m_textInputActive && m_textInputWindow is not null) { _ = SDL.Raw.StopTextInput(m_textInputWindow); } @@ -1002,7 +1002,7 @@ private void UpdateTextInputState(ImGuiIO* io) } else if (m_textInputActive) { - var textInputWindow = m_textInputWindow == null ? targetWindow : m_textInputWindow; + SDLWindow* textInputWindow = m_textInputWindow is null ? targetWindow : m_textInputWindow; _ = SDL.Raw.StopTextInput(textInputWindow); m_textInputWindow = null; m_textInputActive = false; @@ -1012,9 +1012,7 @@ private void UpdateTextInputState(ImGuiIO* io) private static unsafe void SetIniFilename( ImGuiIO* io, IntPtr fileName - ) { - io->IniFilename = (sbyte*)fileName; - } + ) => io->IniFilename = (sbyte*)fileName; private static unsafe ImFont* LoadFont( ImFontAtlas* fonts, @@ -1038,14 +1036,14 @@ IntPtr fileName private SDLWindow* ResolveTextInputWindow() { - var keyboardFocus = SDL.Raw.GetKeyboardFocus(); - if (keyboardFocus == null) + SDLWindow* keyboardFocus = SDL.Raw.GetKeyboardFocus(); + if (keyboardFocus is null) { return m_window.GetSdlWindow(); } - var focusedWindowId = SDL.Raw.GetWindowId(keyboardFocus); - if (focusedWindowId == m_window.windowId || (m_viewports != null && m_viewports.OwnsWindow(focusedWindowId))) + uint focusedWindowId = SDL.Raw.GetWindowId(keyboardFocus); + if (focusedWindowId == m_window.windowId || (m_viewports is not null && m_viewports.OwnsWindow(focusedWindowId))) { return keyboardFocus; } @@ -1140,20 +1138,20 @@ private static Vector2 GetEventMousePosition( float localX, float localY ) { - Vector2 position = new(localX, localY); + var position = new Vector2(localX, localY); if ((io->ConfigFlags & (int)ImGuiConfigFlags.ViewportsEnable) == 0) { return position; } SDLWindow* window = SDL.Raw.GetWindowFromId(windowId); - if (window == null) + if (window is null) { return position; } - var windowX = 0; - var windowY = 0; + int windowX = 0; + int windowY = 0; _ = SDL.Raw.GetWindowPosition(window, &windowX, &windowY); return position + new Vector2(windowX, windowY); } @@ -1216,7 +1214,7 @@ private void UpdateMouseCursor(ImGuiIO* io) return; } - var imguiCursor = (ImGuiMouseCursor)ImGuiNative.GetMouseCursor(); + ImGuiMouseCursor imguiCursor = (ImGuiMouseCursor)ImGuiNative.GetMouseCursor(); if (imguiCursor == ImGuiMouseCursor.None || io->MouseDrawCursor != 0) { _ = SDL.HideCursor(); @@ -1224,8 +1222,8 @@ private void UpdateMouseCursor(ImGuiIO* io) return; } - var sdlCursor = GetOrCreateCursor(imguiCursor); - if (sdlCursor != null && m_currentCursor != imguiCursor) + SDLCursor* sdlCursor = GetOrCreateCursor(imguiCursor); + if (sdlCursor is not null && m_currentCursor != imguiCursor) { _ = SDL.Raw.SetCursor(sdlCursor); m_currentCursor = imguiCursor; @@ -1236,12 +1234,12 @@ private void UpdateMouseCursor(ImGuiIO* io) private SDLCursor* GetOrCreateCursor(ImGuiMouseCursor cursor) { - if (m_cursors.TryGetValue(cursor, out var cachedCursor)) + if (m_cursors.TryGetValue(cursor, out nint cachedCursor)) { return (SDLCursor*)cachedCursor; } - var sdlCursorType = cursor switch + SDLSystemCursor sdlCursorType = cursor switch { ImGuiMouseCursor.Arrow => SDLSystemCursor.Default, ImGuiMouseCursor.TextInput => SDLSystemCursor.Text, @@ -1257,7 +1255,7 @@ private void UpdateMouseCursor(ImGuiIO* io) _ => SDLSystemCursor.Default }; - var createdCursor = SDL.Raw.CreateSystemCursor(sdlCursorType); + SDLCursor* createdCursor = SDL.Raw.CreateSystemCursor(sdlCursorType); m_cursors[cursor] = (nint)createdCursor; return createdCursor; } @@ -1300,123 +1298,121 @@ SDLKeymod modifiers } private static ImGuiKey TranslateKey(SDLScancode scancode) + => scancode switch { - return scancode switch - { - SDLScancode.Tab => ImGuiKey.Tab, - SDLScancode.Left => ImGuiKey.LeftArrow, - SDLScancode.Right => ImGuiKey.RightArrow, - SDLScancode.Up => ImGuiKey.UpArrow, - SDLScancode.Down => ImGuiKey.DownArrow, - SDLScancode.Pageup => ImGuiKey.PageUp, - SDLScancode.Pagedown => ImGuiKey.PageDown, - SDLScancode.Home => ImGuiKey.Home, - SDLScancode.End => ImGuiKey.End, - SDLScancode.Insert => ImGuiKey.Insert, - SDLScancode.Delete => ImGuiKey.Delete, - SDLScancode.Backspace => ImGuiKey.Backspace, - SDLScancode.Space => ImGuiKey.Space, - SDLScancode.Return => ImGuiKey.Enter, - SDLScancode.Escape => ImGuiKey.Escape, - SDLScancode.Apostrophe => ImGuiKey.Apostrophe, - SDLScancode.Comma => ImGuiKey.Comma, - SDLScancode.Minus => ImGuiKey.Minus, - SDLScancode.Period => ImGuiKey.Period, - SDLScancode.Slash => ImGuiKey.Slash, - SDLScancode.Semicolon => ImGuiKey.Semicolon, - SDLScancode.Equals => ImGuiKey.Equal, - SDLScancode.Leftbracket => ImGuiKey.LeftBracket, - SDLScancode.Backslash => ImGuiKey.Backslash, - SDLScancode.Rightbracket => ImGuiKey.RightBracket, - SDLScancode.Grave => ImGuiKey.GraveAccent, - SDLScancode.Capslock => ImGuiKey.CapsLock, - SDLScancode.Scrolllock => ImGuiKey.ScrollLock, - SDLScancode.Numlockclear => ImGuiKey.NumLock, - SDLScancode.Printscreen => ImGuiKey.PrintScreen, - SDLScancode.Pause => ImGuiKey.Pause, - SDLScancode.Kp0 => ImGuiKey.Keypad0, - SDLScancode.Kp1 => ImGuiKey.Keypad1, - SDLScancode.Kp2 => ImGuiKey.Keypad2, - SDLScancode.Kp3 => ImGuiKey.Keypad3, - SDLScancode.Kp4 => ImGuiKey.Keypad4, - SDLScancode.Kp5 => ImGuiKey.Keypad5, - SDLScancode.Kp6 => ImGuiKey.Keypad6, - SDLScancode.Kp7 => ImGuiKey.Keypad7, - SDLScancode.Kp8 => ImGuiKey.Keypad8, - SDLScancode.Kp9 => ImGuiKey.Keypad9, - SDLScancode.KpPeriod => ImGuiKey.KeypadDecimal, - SDLScancode.KpDivide => ImGuiKey.KeypadDivide, - SDLScancode.KpMultiply => ImGuiKey.KeypadMultiply, - SDLScancode.KpMinus => ImGuiKey.KeypadSubtract, - SDLScancode.KpPlus => ImGuiKey.KeypadAdd, - SDLScancode.KpEnter => ImGuiKey.KeypadEnter, - SDLScancode.KpEquals => ImGuiKey.KeypadEqual, - SDLScancode.Lctrl => ImGuiKey.LeftCtrl, - SDLScancode.Lshift => ImGuiKey.LeftShift, - SDLScancode.Lalt => ImGuiKey.LeftAlt, - SDLScancode.Lgui => ImGuiKey.LeftSuper, - SDLScancode.Rctrl => ImGuiKey.RightCtrl, - SDLScancode.Rshift => ImGuiKey.RightShift, - SDLScancode.Ralt => ImGuiKey.RightAlt, - SDLScancode.Rgui => ImGuiKey.RightSuper, - SDLScancode.Menu => ImGuiKey.Menu, - SDLScancode._0 => ImGuiKey._0, - SDLScancode._1 => ImGuiKey._1, - SDLScancode._2 => ImGuiKey._2, - SDLScancode._3 => ImGuiKey._3, - SDLScancode._4 => ImGuiKey._4, - SDLScancode._5 => ImGuiKey._5, - SDLScancode._6 => ImGuiKey._6, - SDLScancode._7 => ImGuiKey._7, - SDLScancode._8 => ImGuiKey._8, - SDLScancode._9 => ImGuiKey._9, - SDLScancode.A => ImGuiKey.A, - SDLScancode.B => ImGuiKey.B, - SDLScancode.C => ImGuiKey.C, - SDLScancode.D => ImGuiKey.D, - SDLScancode.E => ImGuiKey.E, - SDLScancode.F => ImGuiKey.F, - SDLScancode.G => ImGuiKey.G, - SDLScancode.H => ImGuiKey.H, - SDLScancode.I => ImGuiKey.I, - SDLScancode.J => ImGuiKey.J, - SDLScancode.K => ImGuiKey.K, - SDLScancode.L => ImGuiKey.L, - SDLScancode.M => ImGuiKey.M, - SDLScancode.N => ImGuiKey.N, - SDLScancode.O => ImGuiKey.O, - SDLScancode.P => ImGuiKey.P, - SDLScancode.Q => ImGuiKey.Q, - SDLScancode.R => ImGuiKey.R, - SDLScancode.S => ImGuiKey.S, - SDLScancode.T => ImGuiKey.T, - SDLScancode.U => ImGuiKey.U, - SDLScancode.V => ImGuiKey.V, - SDLScancode.W => ImGuiKey.W, - SDLScancode.X => ImGuiKey.X, - SDLScancode.Y => ImGuiKey.Y, - SDLScancode.Z => ImGuiKey.Z, - SDLScancode.F1 => ImGuiKey.F1, - SDLScancode.F2 => ImGuiKey.F2, - SDLScancode.F3 => ImGuiKey.F3, - SDLScancode.F4 => ImGuiKey.F4, - SDLScancode.F5 => ImGuiKey.F5, - SDLScancode.F6 => ImGuiKey.F6, - SDLScancode.F7 => ImGuiKey.F7, - SDLScancode.F8 => ImGuiKey.F8, - SDLScancode.F9 => ImGuiKey.F9, - SDLScancode.F10 => ImGuiKey.F10, - SDLScancode.F11 => ImGuiKey.F11, - SDLScancode.F12 => ImGuiKey.F12, - _ => ImGuiKey.None - }; - } + SDLScancode.Tab => ImGuiKey.Tab, + SDLScancode.Left => ImGuiKey.LeftArrow, + SDLScancode.Right => ImGuiKey.RightArrow, + SDLScancode.Up => ImGuiKey.UpArrow, + SDLScancode.Down => ImGuiKey.DownArrow, + SDLScancode.Pageup => ImGuiKey.PageUp, + SDLScancode.Pagedown => ImGuiKey.PageDown, + SDLScancode.Home => ImGuiKey.Home, + SDLScancode.End => ImGuiKey.End, + SDLScancode.Insert => ImGuiKey.Insert, + SDLScancode.Delete => ImGuiKey.Delete, + SDLScancode.Backspace => ImGuiKey.Backspace, + SDLScancode.Space => ImGuiKey.Space, + SDLScancode.Return => ImGuiKey.Enter, + SDLScancode.Escape => ImGuiKey.Escape, + SDLScancode.Apostrophe => ImGuiKey.Apostrophe, + SDLScancode.Comma => ImGuiKey.Comma, + SDLScancode.Minus => ImGuiKey.Minus, + SDLScancode.Period => ImGuiKey.Period, + SDLScancode.Slash => ImGuiKey.Slash, + SDLScancode.Semicolon => ImGuiKey.Semicolon, + SDLScancode.Equals => ImGuiKey.Equal, + SDLScancode.Leftbracket => ImGuiKey.LeftBracket, + SDLScancode.Backslash => ImGuiKey.Backslash, + SDLScancode.Rightbracket => ImGuiKey.RightBracket, + SDLScancode.Grave => ImGuiKey.GraveAccent, + SDLScancode.Capslock => ImGuiKey.CapsLock, + SDLScancode.Scrolllock => ImGuiKey.ScrollLock, + SDLScancode.Numlockclear => ImGuiKey.NumLock, + SDLScancode.Printscreen => ImGuiKey.PrintScreen, + SDLScancode.Pause => ImGuiKey.Pause, + SDLScancode.Kp0 => ImGuiKey.Keypad0, + SDLScancode.Kp1 => ImGuiKey.Keypad1, + SDLScancode.Kp2 => ImGuiKey.Keypad2, + SDLScancode.Kp3 => ImGuiKey.Keypad3, + SDLScancode.Kp4 => ImGuiKey.Keypad4, + SDLScancode.Kp5 => ImGuiKey.Keypad5, + SDLScancode.Kp6 => ImGuiKey.Keypad6, + SDLScancode.Kp7 => ImGuiKey.Keypad7, + SDLScancode.Kp8 => ImGuiKey.Keypad8, + SDLScancode.Kp9 => ImGuiKey.Keypad9, + SDLScancode.KpPeriod => ImGuiKey.KeypadDecimal, + SDLScancode.KpDivide => ImGuiKey.KeypadDivide, + SDLScancode.KpMultiply => ImGuiKey.KeypadMultiply, + SDLScancode.KpMinus => ImGuiKey.KeypadSubtract, + SDLScancode.KpPlus => ImGuiKey.KeypadAdd, + SDLScancode.KpEnter => ImGuiKey.KeypadEnter, + SDLScancode.KpEquals => ImGuiKey.KeypadEqual, + SDLScancode.Lctrl => ImGuiKey.LeftCtrl, + SDLScancode.Lshift => ImGuiKey.LeftShift, + SDLScancode.Lalt => ImGuiKey.LeftAlt, + SDLScancode.Lgui => ImGuiKey.LeftSuper, + SDLScancode.Rctrl => ImGuiKey.RightCtrl, + SDLScancode.Rshift => ImGuiKey.RightShift, + SDLScancode.Ralt => ImGuiKey.RightAlt, + SDLScancode.Rgui => ImGuiKey.RightSuper, + SDLScancode.Menu => ImGuiKey.Menu, + SDLScancode._0 => ImGuiKey._0, + SDLScancode._1 => ImGuiKey._1, + SDLScancode._2 => ImGuiKey._2, + SDLScancode._3 => ImGuiKey._3, + SDLScancode._4 => ImGuiKey._4, + SDLScancode._5 => ImGuiKey._5, + SDLScancode._6 => ImGuiKey._6, + SDLScancode._7 => ImGuiKey._7, + SDLScancode._8 => ImGuiKey._8, + SDLScancode._9 => ImGuiKey._9, + SDLScancode.A => ImGuiKey.A, + SDLScancode.B => ImGuiKey.B, + SDLScancode.C => ImGuiKey.C, + SDLScancode.D => ImGuiKey.D, + SDLScancode.E => ImGuiKey.E, + SDLScancode.F => ImGuiKey.F, + SDLScancode.G => ImGuiKey.G, + SDLScancode.H => ImGuiKey.H, + SDLScancode.I => ImGuiKey.I, + SDLScancode.J => ImGuiKey.J, + SDLScancode.K => ImGuiKey.K, + SDLScancode.L => ImGuiKey.L, + SDLScancode.M => ImGuiKey.M, + SDLScancode.N => ImGuiKey.N, + SDLScancode.O => ImGuiKey.O, + SDLScancode.P => ImGuiKey.P, + SDLScancode.Q => ImGuiKey.Q, + SDLScancode.R => ImGuiKey.R, + SDLScancode.S => ImGuiKey.S, + SDLScancode.T => ImGuiKey.T, + SDLScancode.U => ImGuiKey.U, + SDLScancode.V => ImGuiKey.V, + SDLScancode.W => ImGuiKey.W, + SDLScancode.X => ImGuiKey.X, + SDLScancode.Y => ImGuiKey.Y, + SDLScancode.Z => ImGuiKey.Z, + SDLScancode.F1 => ImGuiKey.F1, + SDLScancode.F2 => ImGuiKey.F2, + SDLScancode.F3 => ImGuiKey.F3, + SDLScancode.F4 => ImGuiKey.F4, + SDLScancode.F5 => ImGuiKey.F5, + SDLScancode.F6 => ImGuiKey.F6, + SDLScancode.F7 => ImGuiKey.F7, + SDLScancode.F8 => ImGuiKey.F8, + SDLScancode.F9 => ImGuiKey.F9, + SDLScancode.F10 => ImGuiKey.F10, + SDLScancode.F11 => ImGuiKey.F11, + SDLScancode.F12 => ImGuiKey.F12, + _ => ImGuiKey.None + }; private static bool TryGetWindowId( ref SDLEvent sdlEvent, out uint windowId ) { - var eventType = (SDLEventType)sdlEvent.Type; + SDLEventType eventType = (SDLEventType)sdlEvent.Type; switch (eventType) { case SDLEventType.KeyDown: diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs index 4d076ba0c..cd75047b0 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs @@ -27,7 +27,7 @@ public static bool IsAvailable(ImGuiFontStyle style) { ValidateStyle(style); ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); - if (context == null) + if (context is null) { return false; } @@ -52,7 +52,7 @@ public static ImGuiFontScope PushStyle(ImGuiFontStyle style) { ValidateStyle(style); ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); - if (context == null) + if (context is null) { return default; } @@ -76,7 +76,7 @@ internal static void RegisterContext( ImGuiNativeContext* context, IReadOnlyDictionary fonts ) { - if (context == null) + if (context is null) { throw new ArgumentException("An ImGui context is required.", nameof(context)); } @@ -103,7 +103,7 @@ internal static void RegisterStyle( ImGuiFontStyle style, nint font ) { - if (context == null) + if (context is null) { throw new ArgumentException("An ImGui context is required.", nameof(context)); } @@ -127,7 +127,7 @@ nint font internal static void UnregisterContext(ImGuiNativeContext* context) { - if (context == null) + if (context is null) { return; } @@ -149,7 +149,7 @@ internal static void ValidateStyle(ImGuiFontStyle style) internal static void PopStyle(nuint contextKey) { ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); - if (context == null || GetContextKey(context) != contextKey) + if (context is null || GetContextKey(context) != contextKey) { throw new InvalidOperationException("The font style scope must be disposed in the context where it was created."); } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs index 258195b98..1dfa29169 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Interop/ImGuiPlatformIoNative.cs @@ -15,7 +15,7 @@ internal static unsafe class ImGuiPlatformIoNative delegate* unmanaged[Cdecl] setSize ) { void* registration = ImGuiNative.Raw.InnoCreatePlatformWindowCallbacks(context, setPosition, setSize); - if (registration == null) + if (registration is null) { throw new InvalidOperationException("The current ImGui context cannot own platform window callbacks."); } @@ -24,7 +24,7 @@ internal static unsafe class ImGuiPlatformIoNative internal static void DestroyWindowCallbacks(void* registration) { - if (registration == null) + if (registration is null) { return; } @@ -51,8 +51,9 @@ internal static void SetPlatformGetWindowPos( ImGuiPlatformIO* platformIo, PlatformGetWindowPosCallback callback ) { - var callbackPtr = Marshal.GetFunctionPointerForDelegate(callback); - var setterArg = (delegate* unmanaged[Cdecl])callbackPtr; + nint callbackPtr = Marshal.GetFunctionPointerForDelegate(callback); + delegate* unmanaged[Cdecl] setterArg = + (delegate* unmanaged[Cdecl])callbackPtr; ImGuiNative.Raw.PlatformIOSetPlatformGetWindowPos(platformIo, setterArg); } @@ -60,8 +61,9 @@ internal static void SetPlatformGetWindowSize( ImGuiPlatformIO* platformIo, PlatformGetWindowSizeCallback callback ) { - var callbackPtr = Marshal.GetFunctionPointerForDelegate(callback); - var setterArg = (delegate* unmanaged[Cdecl])callbackPtr; + nint callbackPtr = Marshal.GetFunctionPointerForDelegate(callback); + delegate* unmanaged[Cdecl] setterArg = + (delegate* unmanaged[Cdecl])callbackPtr; ImGuiNative.Raw.PlatformIOSetPlatformGetWindowSize(platformIo, setterArg); } } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs index 7084053c5..9ad3f0559 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/ImGuiPackedColor.cs @@ -21,20 +21,20 @@ internal static void EnsureInitialized() return; } - var probe = new Vector4(0.125f, 0.5f, 0.875f, 1.0f); - var packed = ImGuiNative.GetColorU32(probe); - var expectedR = (int)(probe.X * 255.0f + 0.5f); - var expectedG = (int)(probe.Y * 255.0f + 0.5f); - var expectedB = (int)(probe.Z * 255.0f + 0.5f); - var expectedA = (int)(probe.W * 255.0f + 0.5f); + var probe = new Vector4(0.125f, 0.5f, 0.875f, 1f); + uint packed = ImGuiNative.GetColorU32(probe); + int expectedR = (int)(probe.X * 255f + 0.5f); + int expectedG = (int)(probe.Y * 255f + 0.5f); + int expectedB = (int)(probe.Z * 255f + 0.5f); + int expectedA = (int)(probe.W * 255f + 0.5f); - var b0 = (int)(packed & 0xFF); - var b1 = (int)((packed >> 8) & 0xFF); - var b2 = (int)((packed >> 16) & 0xFF); - var b3 = (int)((packed >> 24) & 0xFF); - Span packedBytes = stackalloc int[4] { b0, b1, b2, b3 }; + int b0 = (int)(packed & 0xFF); + int b1 = (int)((packed >> 8) & 0xFF); + int b2 = (int)((packed >> 16) & 0xFF); + int b3 = (int)((packed >> 24) & 0xFF); + Span packedBytes = [b0, b1, b2, b3]; - var usedMask = 0; + int usedMask = 0; s_rShift = SelectBestShift(packedBytes, expectedR, ref usedMask); s_gShift = SelectBestShift(packedBytes, expectedG, ref usedMask); s_bShift = SelectBestShift(packedBytes, expectedB, ref usedMask); @@ -47,10 +47,10 @@ internal static SDLFColor ToSdlFColor(uint packedColor) EnsureInitialized(); const float inv255 = 1f / 255f; - var r = ((packedColor >> s_rShift) & 0xFF) * inv255; - var g = ((packedColor >> s_gShift) & 0xFF) * inv255; - var b = ((packedColor >> s_bShift) & 0xFF) * inv255; - var a = ((packedColor >> s_aShift) & 0xFF) * inv255; + float r = ((packedColor >> s_rShift) & 0xFF) * inv255; + float g = ((packedColor >> s_gShift) & 0xFF) * inv255; + float b = ((packedColor >> s_bShift) & 0xFF) * inv255; + float a = ((packedColor >> s_aShift) & 0xFF) * inv255; return new SDLFColor { R = r, G = g, B = b, A = a }; } @@ -59,16 +59,16 @@ private static int SelectBestShift( int expected, ref int usedMask ) { - var bestIndex = 0; - var bestError = int.MaxValue; - for (var i = 0; i < 4; i++) + int bestIndex = 0; + int bestError = int.MaxValue; + for (int i = 0; i < 4; i++) { if ((usedMask & (1 << i)) != 0) { continue; } - var error = Math.Abs(packedBytes[i] - expected); + int error = Math.Abs(packedBytes[i] - expected); if (error < bestError) { bestError = error; diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs index af920c566..74b4a4d05 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Rendering/PlatformImGuiSdlRenderer.cs @@ -21,7 +21,7 @@ internal sealed unsafe class PlatformImGuiSdlRenderer : IPlatformImGuiRenderer internal PlatformImGuiSdlRenderer(Sdl3PlatformWindow window) { m_renderer = SDL.Raw.CreateRenderer(window.GetSdlWindow(), null); - if (m_renderer == null) + if (m_renderer is null) { throw new InvalidOperationException(Marshal.PtrToStringUTF8((nint)SDL.Raw.GetError()) ?? "SDL_CreateRenderer failed."); } @@ -34,7 +34,7 @@ internal PlatformImGuiSdlRenderer(Sdl3PlatformWindow window) /// public bool supportsViewports => false; - /// + /// public bool supportsVertexOffsets => true; /// @@ -113,12 +113,12 @@ public void PresentViewport(PlatformImGuiViewportTarget target) {} /// public Task RetireViewport(PlatformImGuiViewportTarget target) => Task.CompletedTask; - /// + /// public void DrainViewportRetirements() {} internal void Render(ImDrawData* drawData) { - if (m_disposed || m_renderer == null || drawData == null || drawData->Valid == 0) + if (m_disposed || m_renderer is null || drawData is null || drawData->Valid == 0) { return; } @@ -131,43 +131,43 @@ internal void Render(ImDrawData* drawData) _ = SDL.Raw.SetRenderDrawColor(m_renderer, 20, 20, 22, 255); _ = SDL.Raw.RenderClear(m_renderer); - var clipOff = drawData->DisplayPos; - var clipScale = drawData->FramebufferScale; + ImVec2C clipOff = drawData->DisplayPos; + ImVec2C clipScale = drawData->FramebufferScale; - for (var listIndex = 0; listIndex < drawData->CmdListsCount; listIndex++) + for (int listIndex = 0; listIndex < drawData->CmdListsCount; listIndex++) { - var drawList = drawData->CmdLists.Data[listIndex]; - if (drawList == null) + ImDrawList* drawList = drawData->CmdLists.Data[listIndex]; + if (drawList is null) { continue; } - var vertexCount = drawList->VtxBuffer.Size; + int vertexCount = drawList->VtxBuffer.Size; if (vertexCount <= 0) { continue; } EnsureVertexCapacity(vertexCount); - var srcVertices = drawList->VtxBuffer.Data; - for (var i = 0; i < vertexCount; i++) + ImDrawVert* srcVertices = drawList->VtxBuffer.Data; + for (int i = 0; i < vertexCount; i++) { m_vertexScratch[i] = ToSdlVertex(srcVertices[i], clipOff, clipScale); } - var cmdBufferCount = drawList->CmdBuffer.Size; - for (var cmdIndex = 0; cmdIndex < cmdBufferCount; cmdIndex++) + int cmdBufferCount = drawList->CmdBuffer.Size; + for (int cmdIndex = 0; cmdIndex < cmdBufferCount; cmdIndex++) { - var drawCmd = drawList->CmdBuffer.Data[cmdIndex]; - if (drawCmd.UserCallback != null) + ImDrawCmd drawCmd = drawList->CmdBuffer.Data[cmdIndex]; + if (drawCmd.UserCallback is not null) { continue; } - var clipRectX = (drawCmd.ClipRect.X - clipOff.X) * clipScale.X; - var clipRectY = (drawCmd.ClipRect.Y - clipOff.Y) * clipScale.Y; - var clipRectZ = (drawCmd.ClipRect.Z - clipOff.X) * clipScale.X; - var clipRectW = (drawCmd.ClipRect.W - clipOff.Y) * clipScale.Y; + float clipRectX = (drawCmd.ClipRect.X - clipOff.X) * clipScale.X; + float clipRectY = (drawCmd.ClipRect.Y - clipOff.Y) * clipScale.Y; + float clipRectZ = (drawCmd.ClipRect.Z - clipOff.X) * clipScale.X; + float clipRectW = (drawCmd.ClipRect.W - clipOff.Y) * clipScale.Y; if (clipRectZ <= clipRectX || clipRectW <= clipRectY) { @@ -187,7 +187,7 @@ internal void Render(ImDrawData* drawData) continue; } - var elemCount = (int)drawCmd.ElemCount; + int elemCount = (int)drawCmd.ElemCount; if (elemCount <= 0) { continue; @@ -195,17 +195,17 @@ internal void Render(ImDrawData* drawData) EnsureIndexCapacity(elemCount); - var srcIndices = drawList->IdxBuffer.Data; - var idxOffset = (int)drawCmd.IdxOffset; - var vtxOffset = (int)drawCmd.VtxOffset; - for (var i = 0; i < elemCount; i++) + ushort* srcIndices = drawList->IdxBuffer.Data; + int idxOffset = (int)drawCmd.IdxOffset; + int vtxOffset = (int)drawCmd.VtxOffset; + for (int i = 0; i < elemCount; i++) { m_indexScratch[i] = srcIndices[idxOffset + i] + vtxOffset; } - var textureId = ImGuiNative.Raw.GetTexID(&drawCmd); - var texture = TextureFromImGui(textureId); - if (texture == null) + ulong textureId = ImGuiNative.Raw.GetTexID(&drawCmd); + SDLTexture* texture = TextureFromImGui(textureId); + if (texture is null) { texture = m_fontTexture; } @@ -227,7 +227,7 @@ internal void Render(ImDrawData* drawData) /// internal void SynchronizeOutputSize() { - if (m_disposed || m_renderer == null) + if (m_disposed || m_renderer is null) { return; } @@ -250,13 +250,13 @@ public void Dispose() return; } - if (m_fontTexture != null) + if (m_fontTexture is not null) { SDL.Raw.DestroyTexture(m_fontTexture); m_fontTexture = null; } - if (m_renderer != null) + if (m_renderer is not null) { SDL.Raw.DestroyRenderer(m_renderer); m_renderer = null; @@ -267,16 +267,16 @@ public void Dispose() private void ProcessTextureRequests(ImDrawData* drawData) { - var textures = drawData->Textures; - if (textures == null) + ImVectorImTextureDataPtr* textures = drawData->Textures; + if (textures is null) { return; } - for (var i = 0; i < textures->Size; i++) + for (int i = 0; i < textures->Size; i++) { - var textureData = textures->Data[i]; - if (textureData == null) + ImTextureData* textureData = textures->Data[i]; + if (textureData is null) { continue; } @@ -298,16 +298,16 @@ private void ProcessTextureRequests(ImDrawData* drawData) private void EnsureFontTexture() { - var io = ImGuiNative.Raw.GetIO(); - var fonts = io->Fonts; - if (fonts == null) + ImGuiIO* io = ImGuiNative.Raw.GetIO(); + ImFontAtlas* fonts = io->Fonts; + if (fonts is null) { return; } fonts->RendererHasTextures = 1; - var texData = fonts->TexData; - if (texData == null) + ImTextureData* texData = fonts->TexData; + if (texData is null) { return; } @@ -323,7 +323,7 @@ private void EnsureFontTexture() break; } - if (m_fontTexture == null) + if (m_fontTexture is null) { m_fontTexture = TextureFromImGui(texData->TexId); } @@ -333,11 +333,11 @@ private void CreateOrUpdateTexture( ImTextureData* textureData, bool createIfMissing ) { - var texture = TextureFromImGui(textureData->TexId); - if (texture == null && createIfMissing) + SDLTexture* texture = TextureFromImGui(textureData->TexId); + if (texture is null && createIfMissing) { texture = CreateTexture(textureData->Width, textureData->Height); - if (texture == null) + if (texture is null) { return; } @@ -345,16 +345,16 @@ bool createIfMissing ImGuiNative.Raw.SetTexID(textureData, (ulong)(nuint)texture); } - if (texture == null || textureData->Pixels == null) + if (texture is null || textureData->Pixels is null) { return; } - var pitch = ImGuiNative.Raw.GetPitch(textureData); + int pitch = ImGuiNative.Raw.GetPitch(textureData); _ = SDL.Raw.UpdateTexture(texture, null, textureData->Pixels, pitch); ImGuiNative.Raw.SetStatus(textureData, ImTextureStatus.Ok); - var io = ImGuiNative.Raw.GetIO(); + ImGuiIO* io = ImGuiNative.Raw.GetIO(); if (textureData->TexId == ImGuiNative.Raw.GetTexID(&io->Fonts->TexRef)) { m_fontTexture = texture; @@ -363,8 +363,8 @@ bool createIfMissing private void DestroyTexture(ImTextureData* textureData) { - var texture = TextureFromImGui(textureData->TexId); - if (texture != null) + SDLTexture* texture = TextureFromImGui(textureData->TexId); + if (texture is not null) { SDL.Raw.DestroyTexture(texture); } @@ -387,7 +387,7 @@ int height return null; } - var props = SDL.CreateProperties(); + uint props = SDL.CreateProperties(); try { _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, (long)SDLPixelFormat.Rgba32); @@ -395,8 +395,8 @@ int height _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, width); _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, height); - var texture = SDL.Raw.CreateTextureWithProperties(m_renderer, props); - if (texture == null) + SDLTexture* texture = SDL.Raw.CreateTextureWithProperties(m_renderer, props); + if (texture is null) { return null; } @@ -416,9 +416,9 @@ private static SDLVertex ToSdlVertex( ImVec2C displayPos, ImVec2C framebufferScale ) { - var color = ImGuiPackedColor.ToSdlFColor(vtx.Col); - var x = (vtx.Pos.X - displayPos.X) * framebufferScale.X; - var y = (vtx.Pos.Y - displayPos.Y) * framebufferScale.Y; + SDLFColor color = ImGuiPackedColor.ToSdlFColor(vtx.Col); + float x = (vtx.Pos.X - displayPos.X) * framebufferScale.X; + float y = (vtx.Pos.Y - displayPos.Y) * framebufferScale.Y; return new SDLVertex { @@ -428,10 +428,7 @@ ImVec2C framebufferScale }; } - private static SDLTexture* TextureFromImGui(ulong textureId) - { - return (SDLTexture*)(nuint)textureId; - } + private static SDLTexture* TextureFromImGui(ulong textureId) => (SDLTexture*)(nuint)textureId; private void EnsureVertexCapacity(int requiredCount) { diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs index 312f5b1b7..69ca31267 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Monitors.cs @@ -18,7 +18,7 @@ private static void RefreshMonitors(SDLWindow* fallbackWindow) try { uint primary = SDL.GetPrimaryDisplay(); - if (displays != null && displayCount > 0) + if (displays is not null && displayCount > 0) { if (primary != 0) { @@ -33,7 +33,7 @@ private static void RefreshMonitors(SDLWindow* fallbackWindow) } } } - if (monitors.Count == 0 && fallbackWindow != null) + if (monitors.Count == 0 && fallbackWindow is not null) { uint fallback = SDL.Raw.GetDisplayForWindow(fallbackWindow); if (fallback != 0) @@ -52,8 +52,8 @@ private static void RefreshMonitors(SDLWindow* fallbackWindow) if (monitors.Count > storage.Capacity) { uint bytes = checked((uint)monitors.Count * (uint)sizeof(ImGuiPlatformMonitor)); - var replacement = (ImGuiPlatformMonitor*)ImGuiNative.Raw.MemAlloc(bytes); - if (replacement == null) + ImGuiPlatformMonitor* replacement = (ImGuiPlatformMonitor*)ImGuiNative.Raw.MemAlloc(bytes); + if (replacement is null) { throw new OutOfMemoryException("Cannot allocate the ImGui monitor snapshot."); } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs index 115cddc11..4410b0ec8 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.Retirement.cs @@ -71,17 +71,17 @@ private static void DestroyViewportWindow(ViewportWindowData data) private static void DestroyRetiredWindow(ViewportWindowData data) { - if (data.fontTexture != null) + if (data.fontTexture is not null) { SDL.Raw.DestroyTexture(data.fontTexture); data.fontTexture = null; } - if (data.renderer != null) + if (data.renderer is not null) { SDL.Raw.DestroyRenderer(data.renderer); data.renderer = null; } - if (data.window != null) + if (data.window is not null) { SDL.Raw.DestroyWindow(data.window); data.window = null; diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs index bd2a7fa0b..8b7c079aa 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Viewports/PlatformImGuiViewportBackend.cs @@ -68,7 +68,7 @@ IPlatformImGuiRenderer renderer ) { ArgumentNullException.ThrowIfNull(renderer); ImGuiNativeContext* context = ImGuiNative.Raw.GetCurrentContext(); - if (context == null) + if (context is null) { throw new InvalidOperationException("An active ImGui context is required for viewport routing."); } @@ -85,8 +85,8 @@ IPlatformImGuiRenderer renderer _ = SDL.SetHint(SDL.Constants.SDL_HINT_WINDOW_ACTIVATE_WHEN_RAISED, "1"); m_mainWindow = mainWindow.GetSdlWindow(); - var platformIo = ImGuiNative.Raw.GetPlatformIO(); - if (ImGuiNative.Raw.GetIO()->BackendPlatformUserData != null) + ImGuiPlatformIO* platformIo = ImGuiNative.Raw.GetPlatformIO(); + if (ImGuiNative.Raw.GetIO()->BackendPlatformUserData is not null) { throw new InvalidOperationException("The current ImGui context already has platform backend state."); } @@ -104,7 +104,7 @@ IPlatformImGuiRenderer renderer ImGuiPlatformIoNative.SetPlatformGetWindowPos(platformIo, s_platformGetWindowPos); ImGuiPlatformIoNative.SetPlatformGetWindowSize(platformIo, s_platformGetWindowSize); - var mainViewport = ImGuiNative.Raw.GetMainViewport(); + ImGuiViewport* mainViewport = ImGuiNative.Raw.GetMainViewport(); SDLWindow* mainSdlWindow = mainWindow.GetSdlWindow(); mainViewport->PlatformHandle = (void*)mainSdlWindow; mainViewport->PlatformHandleRaw = (void*)mainWindow.nativeHandles.windowHandle; @@ -134,10 +134,7 @@ IPlatformImGuiRenderer renderer } } - internal bool OwnsWindow(uint windowId) - { - return m_windowToViewport.ContainsKey(windowId); - } + internal bool OwnsWindow(uint windowId) => m_windowToViewport.ContainsKey(windowId); internal bool TryGetWindowId( uint viewportId, @@ -156,7 +153,7 @@ internal void ProcessEvent( ref SDLEvent sdlEvent, uint windowId ) { - var eventType = (SDLEventType)sdlEvent.Type; + SDLEventType eventType = (SDLEventType)sdlEvent.Type; if (eventType >= SDLEventType.DisplayFirst && eventType <= SDLEventType.DisplayLast || eventType == SDLEventType.WindowDisplayChanged || eventType == SDLEventType.WindowDisplayScaleChanged @@ -191,7 +188,7 @@ internal void SynchronizeMetrics() RefreshMonitors(m_mainWindow); m_monitorsDirty = false; } - var main = ImGuiNative.Raw.GetMainViewport(); + ImGuiViewport* main = ImGuiNative.Raw.GetMainViewport(); Vector2 scale = GetWindowFramebufferScale(m_mainWindow); if (scale.X > 0 && scale.Y > 0) { @@ -215,7 +212,7 @@ internal void SynchronizeMetrics() /// internal void SynchronizeWindow(uint windowId) { - if (!m_windowToViewport.TryGetValue(windowId, out var viewportId)) + if (!m_windowToViewport.TryGetValue(windowId, out uint viewportId)) { return; } @@ -226,8 +223,8 @@ internal void SynchronizeWindow(uint windowId) } ImGuiViewport* viewport = data.viewport; - var width = 0; - var height = 0; + int width = 0; + int height = 0; SDL.Raw.GetWindowSize(data.window, &width, &height); if (width <= 0 || height <= 0) { @@ -276,7 +273,7 @@ public void Dispose() return; } - foreach (var kv in m_viewportsById) + foreach (KeyValuePair kv in m_viewportsById) { DestroyViewportWindow(kv.Value); } @@ -293,14 +290,14 @@ public void Dispose() throw new RetirementPendingException("Detached ImGui windows are still borrowed by their renderer."); } - var platformIo = ImGuiNative.Raw.GetPlatformIO(); + ImGuiPlatformIO* platformIo = ImGuiNative.Raw.GetPlatformIO(); ImGuiPlatformIoNative.DestroyWindowCallbacks(m_windowCallbacks); m_windowCallbacks = null; ImGuiNative.Raw.ClearPlatformHandlers(platformIo); ImGuiNative.Raw.ClearRendererHandlers(platformIo); - var mainViewport = ImGuiNative.Raw.GetMainViewport(); - if (mainViewport != null) + ImGuiViewport* mainViewport = ImGuiNative.Raw.GetMainViewport(); + if (mainViewport is not null) { mainViewport->PlatformHandle = null; mainViewport->PlatformHandleRaw = null; @@ -322,12 +319,12 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) { try { - if (viewport == null || viewport->PlatformUserData != null || (viewport->Flags & (int)ImGuiViewportFlags.OwnedByApp) != 0) + if (viewport is null || viewport->PlatformUserData is not null || (viewport->Flags & (int)ImGuiViewportFlags.OwnedByApp) != 0) { return; } - var flags = SDLWindowFlags.Hidden | SDLWindowFlags.Resizable | SDLWindowFlags.HighPixelDensity; + SDLWindowFlags flags = SDLWindowFlags.Hidden | SDLWindowFlags.Resizable | SDLWindowFlags.HighPixelDensity; if ((viewport->Flags & (int)ImGuiViewportFlags.NoDecoration) != 0) { flags |= SDLWindowFlags.Borderless; @@ -343,14 +340,14 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) flags |= SDLWindowFlags.AlwaysOnTop; } - var width = Math.Max(1, (int)viewport->Size.X); - var height = Math.Max(1, (int)viewport->Size.Y); + int width = Math.Max(1, (int)viewport->Size.X); + int height = Math.Max(1, (int)viewport->Size.Y); SDLWindow* window; fixed (byte* title = "ImGui\0"u8) { window = SDL.Raw.CreateWindow((sbyte*)title, width, height, (ulong)flags); } - if (window == null) + if (window is null) { return; } @@ -363,7 +360,7 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) if (!rendererBackend.supportsViewports) { renderer = SDL.Raw.CreateRenderer(window, null); - if (renderer == null) + if (renderer is null) { SDL.Raw.DestroyWindow(window); return; @@ -379,14 +376,14 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) } catch { - if (renderer != null) + if (renderer is not null) { SDL.Raw.DestroyRenderer(renderer); } SDL.Raw.DestroyWindow(window); throw; } - var data = new ViewportWindowData + var data = new ViewportWindowData { owner = backend, registeredWindow = registeredWindow, @@ -417,7 +414,7 @@ private static void PlatformCreateWindowCallback(ImGuiViewport* viewport) backend.m_viewportsById.Add(viewport->ID, data); backend.m_windowToViewport.Add(data.windowId, viewport->ID); - var handlePtr = GCHandle.ToIntPtr(data.gcHandle); + nint handlePtr = GCHandle.ToIntPtr(data.gcHandle); viewport->PlatformUserData = (void*)handlePtr; viewport->RendererUserData = (void*)handlePtr; viewport->PlatformHandle = (void*)window; @@ -442,12 +439,12 @@ private static void PlatformDestroyWindowCallback(ImGuiViewport* viewport) { try { - if (viewport == null || (viewport->Flags & (int)ImGuiViewportFlags.OwnedByApp) != 0) + if (viewport is null || (viewport->Flags & (int)ImGuiViewportFlags.OwnedByApp) != 0) { return; } - if (TryGetViewportData(viewport, out var data)) + if (TryGetViewportData(viewport, out ViewportWindowData data)) { data.owner.m_viewportsById.Remove(viewport->ID); data.owner.m_windowToViewport.Remove(data.windowId); @@ -470,7 +467,7 @@ private static void PlatformShowWindowCallback(ImGuiViewport* viewport) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -492,7 +489,7 @@ float y ) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -511,19 +508,19 @@ private static void PlatformGetWindowPosOutCallback( ) { try { - if (outPos == null) + if (outPos is null) { return; } - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { *outPos = default; return; } - var x = 0; - var y = 0; + int x = 0; + int y = 0; _ = SDL.Raw.GetWindowPosition(window, &x, &y); *outPos = new ImVec2C { X = x, Y = y }; } @@ -541,7 +538,7 @@ float height ) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -560,19 +557,19 @@ private static void PlatformGetWindowSizeOutCallback( ) { try { - if (outSize == null) + if (outSize is null) { return; } - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { *outSize = default; return; } - var width = 0; - var height = 0; + int width = 0; + int height = 0; SDL.Raw.GetWindowSize(window, &width, &height); *outSize = new ImVec2C { X = width, Y = height }; } @@ -587,7 +584,7 @@ private static void PlatformSetWindowFocusCallback(ImGuiViewport* viewport) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -605,12 +602,12 @@ private static byte PlatformGetWindowFocusCallback(ImGuiViewport* viewport) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return 0; } - var flags = (SDLWindowFlags)((SDLWindowFlags)SDL.Raw.GetWindowFlags(window)); + SDLWindowFlags flags = (SDLWindowFlags)((SDLWindowFlags)SDL.Raw.GetWindowFlags(window)); return (flags & SDLWindowFlags.InputFocus) != 0 ? (byte)1 : (byte)0; } catch (Exception failure) @@ -625,12 +622,12 @@ private static byte PlatformGetWindowMinimizedCallback(ImGuiViewport* viewport) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return 0; } - var flags = (SDLWindowFlags)((SDLWindowFlags)SDL.Raw.GetWindowFlags(window)); + SDLWindowFlags flags = (SDLWindowFlags)((SDLWindowFlags)SDL.Raw.GetWindowFlags(window)); return (flags & SDLWindowFlags.Minimized) != 0 ? (byte)1 : (byte)0; } catch (Exception failure) @@ -647,7 +644,7 @@ private static void PlatformSetWindowTitleCallback( ) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -667,7 +664,7 @@ float alpha ) { try { - if (!TryGetWindow(viewport, out var window)) + if (!TryGetWindow(viewport, out SDLWindow* window)) { return; } @@ -688,7 +685,7 @@ private static void RendererRenderWindowCallback( try { _ = renderArg; - if (!TryGetViewportData(viewport, out var data) || viewport == null || viewport->DrawData == null) + if (!TryGetViewportData(viewport, out ViewportWindowData data) || viewport is null || viewport->DrawData is null) { return; } @@ -723,7 +720,7 @@ private static void RendererSwapBuffersCallback( try { _ = renderArg; - if (!TryGetViewportData(viewport, out var data)) + if (!TryGetViewportData(viewport, out ViewportWindowData data)) { return; } @@ -753,13 +750,13 @@ private static bool TryGetViewportData( ImGuiViewport* viewport, out ViewportWindowData data ) { - if (viewport == null || viewport->PlatformUserData == null) + if (viewport is null || viewport->PlatformUserData is null) { data = null!; return false; } - var handle = GCHandle.FromIntPtr((IntPtr)viewport->PlatformUserData); + GCHandle handle = GCHandle.FromIntPtr((IntPtr)viewport->PlatformUserData); if (!handle.IsAllocated || handle.Target is not ViewportWindowData windowData) { data = null!; @@ -774,13 +771,13 @@ private static bool TryGetWindow( ImGuiViewport* viewport, out SDLWindow* window ) { - if (viewport != null && viewport->PlatformHandle != null) + if (viewport is not null && viewport->PlatformHandle is not null) { window = (SDLWindow*)viewport->PlatformHandle; return true; } - if (TryGetViewportData(viewport, out var data)) + if (TryGetViewportData(viewport, out ViewportWindowData data)) { window = data.window; return true; @@ -792,22 +789,22 @@ out SDLWindow* window private static void EnsureViewportFontTexture(ViewportWindowData data) { - var io = ImGuiNative.Raw.GetIO(); - if (io->Fonts == null) + ImGuiIO* io = ImGuiNative.Raw.GetIO(); + if (io->Fonts is null) { return; } io->Fonts->RendererHasTextures = 1; - var texData = io->Fonts->TexData; - if (texData == null) + ImTextureData* texData = io->Fonts->TexData; + if (texData is null) { return; } if (texData->Status == ImTextureStatus.WantDestroy) { - if (data.fontTexture != null) + if (data.fontTexture is not null) { SDL.Raw.DestroyTexture(data.fontTexture); data.fontTexture = null; @@ -823,24 +820,24 @@ private static void EnsureViewportFontTexture(ViewportWindowData data) return; } - if (texData->Pixels == null || texData->Width <= 0 || texData->Height <= 0) + if (texData->Pixels is null || texData->Width <= 0 || texData->Height <= 0) { return; } - var needsRecreate = data.fontTexture == null - || data.fontTextureWidth != texData->Width - || data.fontTextureHeight != texData->Height; + bool needsRecreate = data.fontTexture is null + || data.fontTextureWidth != texData->Width + || data.fontTextureHeight != texData->Height; if (needsRecreate) { - if (data.fontTexture != null) + if (data.fontTexture is not null) { SDL.Raw.DestroyTexture(data.fontTexture); data.fontTexture = null; } data.fontTexture = CreateTexture(data.renderer, texData->Width, texData->Height); - if (data.fontTexture == null) + if (data.fontTexture is null) { data.fontTextureWidth = 0; data.fontTextureHeight = 0; @@ -851,19 +848,19 @@ private static void EnsureViewportFontTexture(ViewportWindowData data) data.fontTextureHeight = texData->Height; } - var pitch = ImGuiNative.Raw.GetPitch(texData); - var pixelsPtr = (nint)texData->Pixels; - var uniqueId = texData->UniqueId; - var usedRect = texData->UsedRect; - var updateRect = texData->UpdateRect; - var needsUpload = needsRecreate - || data.fontPixelsPtr != pixelsPtr - || data.fontTexturePitch != pitch - || data.fontTextureUniqueId != uniqueId - || !TextureRectEquals(data.fontUsedRect, usedRect) - || !TextureRectEquals(data.fontUpdateRect, updateRect) - || texData->Status == ImTextureStatus.WantCreate - || texData->Status == ImTextureStatus.WantUpdates; + int pitch = ImGuiNative.Raw.GetPitch(texData); + nint pixelsPtr = (nint)texData->Pixels; + int uniqueId = texData->UniqueId; + ImTextureRect usedRect = texData->UsedRect; + ImTextureRect updateRect = texData->UpdateRect; + bool needsUpload = needsRecreate + || data.fontPixelsPtr != pixelsPtr + || data.fontTexturePitch != pitch + || data.fontTextureUniqueId != uniqueId + || !TextureRectEquals(data.fontUsedRect, usedRect) + || !TextureRectEquals(data.fontUpdateRect, updateRect) + || texData->Status == ImTextureStatus.WantCreate + || texData->Status == ImTextureStatus.WantUpdates; if (!needsUpload) { return; @@ -882,51 +879,51 @@ private static void RenderDrawData( SDLTexture* fontTexture, ImDrawData* drawDataNative ) { - var renderer = data.renderer; - if (renderer == null || drawDataNative == null || drawDataNative->Valid == 0) + SDLRenderer* renderer = data.renderer; + if (renderer is null || drawDataNative is null || drawDataNative->Valid == 0) { return; } - var drawData = drawDataNative; + ImDrawData* drawData = drawDataNative; _ = SDL.Raw.SetRenderViewport(renderer, null); _ = SDL.Raw.SetRenderClipRect(renderer, null); _ = SDL.Raw.SetRenderDrawColor(renderer, 0, 0, 0, 0); _ = SDL.Raw.RenderClear(renderer); - var clipOff = drawData->DisplayPos; - var clipScale = drawData->FramebufferScale; - var fontTexId = ImGuiNative.Raw.GetTexID(&ImGuiNative.Raw.GetIO()->Fonts->TexRef); + ImVec2C clipOff = drawData->DisplayPos; + ImVec2C clipScale = drawData->FramebufferScale; + ulong fontTexId = ImGuiNative.Raw.GetTexID(&ImGuiNative.Raw.GetIO()->Fonts->TexRef); - for (var listIndex = 0; listIndex < drawData->CmdListsCount; listIndex++) + for (int listIndex = 0; listIndex < drawData->CmdListsCount; listIndex++) { - var drawList = drawData->CmdLists.Data[listIndex]; - if (drawList == null || drawList->VtxBuffer.Size <= 0) + ImDrawList* drawList = drawData->CmdLists.Data[listIndex]; + if (drawList is null || drawList->VtxBuffer.Size <= 0) { continue; } - var vertexCount = drawList->VtxBuffer.Size; + int vertexCount = drawList->VtxBuffer.Size; EnsureVertexCapacity(data, vertexCount); - var srcVertices = drawList->VtxBuffer.Data; - for (var i = 0; i < vertexCount; i++) + ImDrawVert* srcVertices = drawList->VtxBuffer.Data; + for (int i = 0; i < vertexCount; i++) { data.vertexScratch[i] = ToSdlVertex(srcVertices[i], clipOff, clipScale); } - var cmdCount = drawList->CmdBuffer.Size; - for (var cmdIndex = 0; cmdIndex < cmdCount; cmdIndex++) + int cmdCount = drawList->CmdBuffer.Size; + for (int cmdIndex = 0; cmdIndex < cmdCount; cmdIndex++) { - var drawCmd = drawList->CmdBuffer.Data[cmdIndex]; - if (drawCmd.UserCallback != null || drawCmd.ElemCount == 0) + ImDrawCmd drawCmd = drawList->CmdBuffer.Data[cmdIndex]; + if (drawCmd.UserCallback is not null || drawCmd.ElemCount == 0) { continue; } - var clipRectX = (drawCmd.ClipRect.X - clipOff.X) * clipScale.X; - var clipRectY = (drawCmd.ClipRect.Y - clipOff.Y) * clipScale.Y; - var clipRectZ = (drawCmd.ClipRect.Z - clipOff.X) * clipScale.X; - var clipRectW = (drawCmd.ClipRect.W - clipOff.Y) * clipScale.Y; + float clipRectX = (drawCmd.ClipRect.X - clipOff.X) * clipScale.X; + float clipRectY = (drawCmd.ClipRect.Y - clipOff.Y) * clipScale.Y; + float clipRectZ = (drawCmd.ClipRect.Z - clipOff.X) * clipScale.X; + float clipRectW = (drawCmd.ClipRect.W - clipOff.Y) * clipScale.Y; if (clipRectZ <= clipRectX || clipRectW <= clipRectY) { continue; @@ -941,20 +938,20 @@ private static void RenderDrawData( }; _ = SDL.Raw.SetRenderClipRect(renderer, &clipRect); - var elemCount = (int)drawCmd.ElemCount; + int elemCount = (int)drawCmd.ElemCount; EnsureIndexCapacity(data, elemCount); - var srcIndices = drawList->IdxBuffer.Data; - var idxOffset = (int)drawCmd.IdxOffset; - var vtxOffset = (int)drawCmd.VtxOffset; - for (var i = 0; i < elemCount; i++) + ushort* srcIndices = drawList->IdxBuffer.Data; + int idxOffset = (int)drawCmd.IdxOffset; + int vtxOffset = (int)drawCmd.VtxOffset; + for (int i = 0; i < elemCount; i++) { data.indexScratch[i] = srcIndices[idxOffset + i] + vtxOffset; } - var texture = ImGuiNative.Raw.GetTexID(&drawCmd) == fontTexId - ? fontTexture - : TextureFromImGui(ImGuiNative.Raw.GetTexID(&drawCmd)); - if (texture == null) + SDLTexture* texture = ImGuiNative.Raw.GetTexID(&drawCmd) == fontTexId + ? fontTexture + : TextureFromImGui(ImGuiNative.Raw.GetTexID(&drawCmd)); + if (texture is null) { texture = fontTexture; } @@ -972,7 +969,7 @@ private static void RenderDrawData( private static void FocusWindow(SDLWindow* window) { - if (window != null) + if (window is not null) { _ = SDL.Raw.RaiseWindow(window); } @@ -981,7 +978,7 @@ private static void FocusWindow(SDLWindow* window) private static PlatformImGuiViewportBackend GetCurrentBackend() { ImGuiNativeContext* context = ImGuiNative.Raw.GetCurrentContext(); - if (context == null) + if (context is null) { throw new InvalidOperationException("No ImGui context is active for a viewport callback."); } @@ -997,7 +994,7 @@ private static PlatformImGuiViewportBackend GetCurrentBackend() private static void SynchronizeRendererOutput(SDLRenderer* renderer) { - if (renderer == null) + if (renderer is null) { return; } @@ -1036,15 +1033,15 @@ int required int width, int height ) { - var props = SDL.CreateProperties(); + uint props = SDL.CreateProperties(); try { _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, (long)SDLPixelFormat.Rgba32); _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_ACCESS_NUMBER, (long)SDLTextureAccess.Static); _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, width); _ = SDL.SetNumberProperty(props, SDL.Constants.SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, height); - var texture = SDL.Raw.CreateTextureWithProperties(renderer, props); - if (texture != null) + SDLTexture* texture = SDL.Raw.CreateTextureWithProperties(renderer, props); + if (texture is not null) { _ = SDL.Raw.SetTextureBlendMode(texture, SDL.Constants.SDL_BLENDMODE_BLEND); _ = SDL.Raw.SetTextureScaleMode(texture, SDLScaleMode.Linear); @@ -1060,16 +1057,16 @@ int height private static Vector2 GetWindowFramebufferScale(SDLWindow* window) { - var windowWidth = 0; - var windowHeight = 0; + int windowWidth = 0; + int windowHeight = 0; SDL.Raw.GetWindowSize(window, &windowWidth, &windowHeight); if (windowWidth <= 0 || windowHeight <= 0) { return Vector2.Zero; } - var pixelWidth = 0; - var pixelHeight = 0; + int pixelWidth = 0; + int pixelHeight = 0; SDL.Raw.GetWindowSizeInPixels(window, &pixelWidth, &pixelHeight); return new Vector2(pixelWidth / (float)windowWidth, pixelHeight / (float)windowHeight); } @@ -1093,9 +1090,9 @@ private static SDLVertex ToSdlVertex( ImVec2C displayPos, ImVec2C framebufferScale ) { - var color = ImGuiPackedColor.ToSdlFColor(vtx.Col); - var x = (vtx.Pos.X - displayPos.X) * framebufferScale.X; - var y = (vtx.Pos.Y - displayPos.Y) * framebufferScale.Y; + SDLFColor color = ImGuiPackedColor.ToSdlFColor(vtx.Col); + float x = (vtx.Pos.X - displayPos.X) * framebufferScale.X; + float y = (vtx.Pos.Y - displayPos.Y) * framebufferScale.Y; return new SDLVertex { @@ -1105,20 +1102,15 @@ ImVec2C framebufferScale }; } - private static SDLTexture* TextureFromImGui(ulong textureId) - { - return (SDLTexture*)(nuint)textureId; - } + private static SDLTexture* TextureFromImGui(ulong textureId) => (SDLTexture*)(nuint)textureId; private static bool TextureRectEquals( ImTextureRect a, ImTextureRect b - ) { - return a.X == b.X - && a.Y == b.Y - && a.W == b.W - && a.H == b.H; - } + ) => a.X == b.X + && a.Y == b.Y + && a.W == b.W + && a.H == b.H; private void RecordCallbackFailure(Exception failure) => m_callbackFailure = m_callbackFailure is null diff --git a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs index 6ea88aaa0..17eb50e79 100644 --- a/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs +++ b/backends/Interop/native/Inno.Native.LibraryLoading/NativeDeploymentIndex.cs @@ -101,7 +101,7 @@ public static NativeDeploymentIndex Decode(ReadOnlySpan bytes) using JsonDocument document = JsonDocument.Parse(bytes.ToArray()); JsonElement root = document.RootElement; string[] names = root.EnumerateObject().Select(static entry => entry.Name).Order(StringComparer.Ordinal).ToArray(); - if (!names.SequenceEqual(new[] { "files", "libraries", "targetId" }, StringComparer.Ordinal)) + if (!names.SequenceEqual(["files", "libraries", "targetId"], StringComparer.Ordinal)) { throw new InvalidDataException("The native deployment index must contain its exact current fields."); } diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs index 7447ec624..f5a95b0eb 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioBackendProvider.cs @@ -14,9 +14,7 @@ public sealed class MiniAudioBackendProvider : AudioBackendProvider public MiniAudioBackendProvider() : base(AudioBackendId.miniAudio) {} - /// + /// public override IAudioDevice CreateDevice(AudioBackendOptions options) - { - return new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = options.noDevice }); - } + => new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = options.noDevice }); } diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs index 4ac81fc2c..612fb10b7 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipPreparation.cs @@ -18,15 +18,15 @@ internal MiniAudioClipPreparation( string path, SemaphoreSlim slots ) { - contentHash = source.contentHash.ToUpperInvariant(); - length = source.length; + this.contentHash = source.contentHash.ToUpperInvariant(); + this.length = source.length; this.path = path; try { using AsyncFlowControl? suppression = ExecutionContext.IsFlowSuppressed() ? null : ExecutionContext.SuppressFlow(); - completion = Task.Run(() => PrepareAsync(source, slots), CancellationToken.None); + this.completion = Task.Run(() => PrepareAsync(source, slots), CancellationToken.None); } catch { @@ -43,7 +43,7 @@ SemaphoreSlim slots internal void Cancel() => m_cancellation.Cancel(); - /// + /// public void Dispose() { if (!completion.IsCompleted) diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipSourceLease.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipSourceLease.cs index ac935ab83..debb09f46 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipSourceLease.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioClipSourceLease.cs @@ -16,7 +16,7 @@ MiniAudioClipPreparation preparation internal MiniAudioClipPreparation preparation { get; } - /// + /// public void Dispose() { m_owner?.Release(preparation); diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs index bf23e5fbe..40a64f1be 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDevice.cs @@ -56,7 +56,7 @@ public MiniAudioDevice() public MiniAudioDevice(MiniAudioDeviceOptions options) { m_options = (options ?? throw new ArgumentNullException(nameof(options))).Validate(); - generation = NextGeneration(); + this.generation = NextGeneration(); m_state = AudioDeviceState.Initializing; m_engine = (MaEngine*)NativeMemory.AllocZeroed((nuint)sizeof(MaEngine)); @@ -75,7 +75,7 @@ public MiniAudioDevice(MiniAudioDeviceOptions options) m_engineInitialized = true; int actualSampleRate = checked((int)NativeApi.Raw.EngineGetSampleRate(m_engine)); - capabilities = new AudioCapabilities(true, true, true, m_options.listenerCount, actualSampleRate); + this.capabilities = new AudioCapabilities(true, true, true, m_options.listenerCount, actualSampleRate); if (m_options.noDevice) { m_processBuffer = (float*)NativeMemory.AllocZeroed( @@ -1012,7 +1012,7 @@ private void ProcessHeadlessFrames(float deltaTime) private void UpdateOutputDeviceState() { MaDevice* device = NativeApi.Raw.EngineGetDevice(m_engine); - if (device == null) + if (device is null) { m_state = AudioDeviceState.Lost; return; @@ -1137,7 +1137,7 @@ internal BusRecord( this.parent = parent; this.group = group; this.target = target; - tail = group; + this.tail = group; } } diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs index 222b3a804..5024dfa76 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioDeviceOptions.cs @@ -21,7 +21,7 @@ public sealed record MiniAudioDeviceOptions /// /// Gets or initializes the output sample rate in frames per second. /// - public int sampleRate { get; init; } = 48000; + public int sampleRate { get; init; } = 48_000; /// /// Gets or initializes the maximum listener count exposed by this backend generation. diff --git a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs index 8dd092f0b..351a9a744 100644 --- a/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs +++ b/backends/MiniAudio/runtime/Inno.Adapter.Audio.MiniAudio/MiniAudioEncodedArtifactCache.cs @@ -79,7 +79,7 @@ internal void CancelPreparation() } } - /// + /// public void Dispose() { if (m_disposed) diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs index 5f1059474..ee45f0ecd 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi.Authoring/RmlUiDocumentFrontend.cs @@ -88,7 +88,7 @@ public UiDocumentAnalysis Analyze(UiDocumentSourceFile source) string expanded; try { - expanded = ExpandStyles(source, documentPath, new HashSet()); + expanded = ExpandStyles(source, documentPath, []); } catch (Exception exception) when (exception is IOException or ArgumentException or InvalidOperationException) { diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs index d19047973..a8e922d68 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackend.cs @@ -48,7 +48,7 @@ public sealed unsafe class RmlUiBackend : IUiBackend public RmlUiBackend() { m_runtime = RmlUiNativeErrors.CreateSession(); - if (m_runtime == null) + if (m_runtime is null) { throw CreateNativeException("create UI runtime", Result.UnknownError); } @@ -586,11 +586,11 @@ public UiRenderFrame Render(UiContextHandle context) { InnoUIRmlUiAdapterMeshInfo mesh = default; ThrowIfFailed(RmlUiNativeFrames.GetMeshInfo(m_runtime, handle, checked((ulong)meshIndex), ref mesh), "query UI mesh"); - InnoUIRmlUiAdapterVertex[] nativeVertices = new InnoUIRmlUiAdapterVertex[checked((int)mesh.VertexCount)]; - uint[] indices = new uint[checked((int)mesh.IndexCount)]; + var nativeVertices = new InnoUIRmlUiAdapterVertex[checked((int)mesh.VertexCount)]; + var indices = new uint[checked((int)mesh.IndexCount)]; CopyMeshVertices(handle, mesh.Id, nativeVertices); CopyMeshIndices(handle, mesh.Id, indices); - UiVertex[] vertices = new UiVertex[nativeVertices.Length]; + var vertices = new UiVertex[nativeVertices.Length]; for (int vertexIndex = 0; vertexIndex < vertices.Length; ++vertexIndex) { InnoUIRmlUiAdapterVertex value = nativeVertices[vertexIndex]; @@ -603,7 +603,7 @@ public UiRenderFrame Render(UiContextHandle context) builder.AddReleasedMesh(new(mesh)); } - InnoUIRmlUiAdapterDrawCommand[] nativeCommands = new InnoUIRmlUiAdapterDrawCommand[checked((int)info.CommandCount)]; + var nativeCommands = new InnoUIRmlUiAdapterDrawCommand[checked((int)info.CommandCount)]; CopyCommands(handle, nativeCommands); foreach (InnoUIRmlUiAdapterDrawCommand value in nativeCommands) { @@ -621,7 +621,7 @@ public UiRenderFrame Render(UiContextHandle context) { InnoUIRmlUiAdapterTextureInfo texture = default; ThrowIfFailed(RmlUiNativeFrames.GetTextureInfo(m_runtime, handle, checked((ulong)index), ref texture), "query UI texture"); - byte[] pixels = new byte[checked((int)texture.ByteLength)]; + var pixels = new byte[checked((int)texture.ByteLength)]; if (pixels.Length > 0) { ThrowIfFailed( @@ -662,14 +662,14 @@ public IReadOnlyList DrainEvents(UiContextHandle context) ulong handle = Require(context); ulong eventCount = 0; ThrowIfFailed(RmlUiNativeFrames.GetEventCount(m_runtime, handle, ref eventCount), "query UI events"); - UiEvent[] events = new UiEvent[checked((int)eventCount)]; + var events = new UiEvent[checked((int)eventCount)]; try { for (int index = 0; index < events.Length; index++) { InnoUIRmlUiAdapterEventInfo info = default; ThrowIfFailed(RmlUiNativeFrames.GetEventInfo(m_runtime, handle, checked((ulong)index), ref info), "query UI event"); - byte[] targetBytes = new byte[checked((int)info.TargetIdLength + 1)]; + var targetBytes = new byte[checked((int)info.TargetIdLength + 1)]; ThrowIfFailed( RmlUiNativeFrames.CopyEventTargetId(m_runtime, handle, checked((ulong)index), targetBytes.AsSpan()), "copy UI event target" @@ -744,7 +744,7 @@ private ulong[] CopyReleasedMeshes( ulong context, ulong count ) { - ulong[] values = new ulong[checked((int)count)]; + var values = new ulong[checked((int)count)]; if (values.Length > 0) { ThrowIfFailed( @@ -759,7 +759,7 @@ private ulong[] CopyReleasedTextures( ulong context, ulong count ) { - ulong[] values = new ulong[checked((int)count)]; + var values = new ulong[checked((int)count)]; if (values.Length > 0) { ThrowIfFailed( diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs index 1d2751f49..a066858c3 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiBackendProvider.cs @@ -13,6 +13,6 @@ public sealed class RmlUiBackendProvider : UiBackendProvider public RmlUiBackendProvider() : base(UiBackendId.rmlUi) {} - /// + /// public override IUiBackend CreateBackend() => new RmlUiBackend(); } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs index 5be1d6706..455aa3174 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiNativeErrors.cs @@ -24,20 +24,20 @@ internal static void CheckBridge( int status, BgcsInnoRmluiError* error ) { - if (status == 0 && error == null) + if (status == 0 && error is null) { return; } try { - string? message = error == null ? null : Marshal.PtrToStringUTF8((nint)UiNative.Raw.BgcsInnoRmluiErrorMessage(error)); + string? message = error is null ? null : Marshal.PtrToStringUTF8((nint)UiNative.Raw.BgcsInnoRmluiErrorMessage(error)); throw new InvalidOperationException( $"The UI bridge failed with status {status}: {message ?? "No native error text is available."}" ); } finally { - if (error != null) + if (error is not null) { UiNative.Raw.BgcsInnoRmluiErrorRelease(error); } diff --git a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiUtf8String.cs b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiUtf8String.cs index d680e456d..8dcc127e9 100644 --- a/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiUtf8String.cs +++ b/backends/RmlUi/runtime/Inno.Adapter.UI.RmlUi/RmlUiUtf8String.cs @@ -6,7 +6,10 @@ internal readonly unsafe ref struct RmlUiUtf8String { private readonly nint m_memory; - internal RmlUiUtf8String(string value) => m_memory = Marshal.StringToCoTaskMemUTF8(value); + internal RmlUiUtf8String(string value) + { + m_memory = Marshal.StringToCoTaskMemUTF8(value); + } internal byte* pointer => (byte*)m_memory; diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs index 1afeea663..207a79fd3 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3FolderDialog.cs @@ -71,16 +71,16 @@ private static unsafe void Complete( sbyte** files, int filter ) { - var result = (TaskCompletionSource)GCHandle.FromIntPtr((nint)userData).Target!; + TaskCompletionSource result = (TaskCompletionSource)GCHandle.FromIntPtr((nint)userData).Target!; try { - if (files == null) + if (files is null) { result.TrySetException(new InvalidOperationException(Sdl3NativeText.ReadError() ?? "The native folder dialog failed.")); } else { - result.TrySetResult(files[0] == null ? null : Marshal.PtrToStringUTF8((nint)files[0])); + result.TrySetResult(files[0] is null ? null : Marshal.PtrToStringUTF8((nint)files[0])); } } catch (Exception failure) diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs index d5e63d87d..49b11b150 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Api/Sdl3WindowOperations.cs @@ -56,7 +56,7 @@ bool requireOpenGl throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL window properties could not be set."); } SDLWindow* window = SDL.Raw.CreateWindowWithProperties(properties); - if (window == null) + if (window is null) { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL window creation failed."); } diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs index 256c5148c..72734394c 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Internal.cs @@ -61,7 +61,7 @@ private unsafe void Initialize() m_liveResizeMainThreadCallbackPointer = (delegate* unmanaged[Cdecl]) Marshal.GetFunctionPointerForDelegate(m_liveResizeMainThreadCallback); m_liveResizeEventWatchHandle = GCHandle.Alloc(this, GCHandleType.Normal); - var userData = (nint)GCHandle.ToIntPtr(m_liveResizeEventWatchHandle); + nint userData = (nint)GCHandle.ToIntPtr(m_liveResizeEventWatchHandle); if (SDL.Raw.AddEventWatch(m_liveResizeEventWatchPointer, (void*)userData) == 0) { Exception failure = new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_AddEventWatch failed."); @@ -167,26 +167,26 @@ private void PollAndCoalescePendingEvents() m_pendingEvents.Clear(); m_pendingEventReadIndex = 0; - Dictionary latestEventIndicesByKey = new(); + Dictionary latestEventIndicesByKey = []; SDLEvent sdlEvent = default; while (SDL.Raw.PollEvent(&sdlEvent) != 0) { m_redrawFailure?.Throw(); DispatchNativeEvent(ref sdlEvent); - if (!TryTranslateEvent(ref sdlEvent, out var translatedEvent) || translatedEvent is null) + if (!TryTranslateEvent(ref sdlEvent, out Event? translatedEvent) || translatedEvent is null) { continue; } - if (TryCreatePendingEventCoalesceKey(translatedEvent, out var key) - && latestEventIndicesByKey.TryGetValue(key, out var index) + if (TryCreatePendingEventCoalesceKey(translatedEvent, out PendingEventCoalesceKey key) + && latestEventIndicesByKey.TryGetValue(key, out int index) ) { m_pendingEvents[index] = translatedEvent; continue; } - var nextIndex = m_pendingEvents.Count; + int nextIndex = m_pendingEvents.Count; m_pendingEvents.Add(translatedEvent); if (TryCreatePendingEventCoalesceKey(translatedEvent, out key)) { @@ -208,7 +208,7 @@ public partial void Dispose() if (m_liveResizeEventWatch is not null && m_liveResizeEventWatchHandle.IsAllocated) { - var userData = (nint)GCHandle.ToIntPtr(m_liveResizeEventWatchHandle); + nint userData = (nint)GCHandle.ToIntPtr(m_liveResizeEventWatchHandle); unsafe { SDL.Raw.RemoveEventWatch(m_liveResizeEventWatchPointer, (void*)userData); @@ -229,7 +229,7 @@ public partial void Dispose() } m_extensions.Clear(); - foreach (var window in new List(m_windows.Values)) + foreach (Sdl3PlatformWindow window in new List(m_windows.Values)) { window.Dispose(); } @@ -243,18 +243,18 @@ private static unsafe byte LiveResizeEventWatch( void* userData, SDLEvent* evnt ) { - if (userData == null || evnt == null) + if (userData is null || evnt is null) { return 1; } - var eventType = (SDLEventType)evnt->Type; + SDLEventType eventType = (SDLEventType)evnt->Type; if (eventType != SDLEventType.WindowExposed || evnt->Window.Data1 == 0) { return 1; } - var handle = GCHandle.FromIntPtr((IntPtr)userData); + GCHandle handle = GCHandle.FromIntPtr((IntPtr)userData); if (handle.Target is not Sdl3PlatformApplication application || application.m_disposed) { return 1; @@ -263,7 +263,7 @@ private static unsafe byte LiveResizeEventWatch( Volatile.Write(ref application.m_liveResizeWindowId, evnt->Window.WindowID); if (Interlocked.Exchange(ref application.m_liveResizeRedrawQueued, 1) == 0) { - var userDataPtr = (nint)GCHandle.ToIntPtr(application.m_liveResizeEventWatchHandle); + nint userDataPtr = (nint)GCHandle.ToIntPtr(application.m_liveResizeEventWatchHandle); if (SDL.Raw.RunOnMainThread(application.m_liveResizeMainThreadCallbackPointer, (void*)userDataPtr, 0) == 0) { Interlocked.Exchange(ref application.m_liveResizeRedrawQueued, 0); @@ -275,18 +275,18 @@ private static unsafe byte LiveResizeEventWatch( private static unsafe void LiveResizeMainThreadCallback(void* userData) { - if (userData == null) + if (userData is null) { return; } - var handle = GCHandle.FromIntPtr((IntPtr)userData); + GCHandle handle = GCHandle.FromIntPtr((IntPtr)userData); if (handle.Target is not Sdl3PlatformApplication application || application.m_disposed) { return; } - var windowId = Volatile.Read(ref application.m_liveResizeWindowId); + uint windowId = Volatile.Read(ref application.m_liveResizeWindowId); Interlocked.Exchange(ref application.m_liveResizeRedrawQueued, 0); if (windowId != 0) { @@ -304,7 +304,7 @@ private static unsafe void LiveResizeMainThreadCallback(void* userData) private unsafe void DispatchNativeEvent(ref SDLEvent sdlEvent) { - ReadOnlySpan nativeEventData = new(Unsafe.AsPointer(ref sdlEvent), sizeof(SDLEvent)); + var nativeEventData = new ReadOnlySpan(Unsafe.AsPointer(ref sdlEvent), sizeof(SDLEvent)); foreach (ISdl3ApplicationExtension extension in m_extensions.ToArray()) { extension.ProcessNativeEvent(this, nativeEventData); @@ -322,7 +322,8 @@ private void DispatchLiveResizeRedraw(uint windowId) { if (m_windows.TryGetValue(windowId, out Sdl3PlatformWindow? window)) { - int width = 0, height = 0; + int width = 0; + int height = 0; if (SDL.Raw.GetWindowSize(window.sdlWindow, &width, &height) == 0) { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_GetWindowSize failed during live resize."); @@ -369,7 +370,7 @@ private unsafe bool TryTranslateEvent( ref SDLEvent sdlEvent, out Event? evnt ) { - var eventType = (SDLEventType)sdlEvent.Type; + SDLEventType eventType = (SDLEventType)sdlEvent.Type; switch (eventType) { case SDLEventType.Quit: @@ -398,7 +399,7 @@ out Event? evnt return false; case SDLEventType.WindowResized: - if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out var resizedWindow)) + if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out Sdl3PlatformWindow? resizedWindow)) { resizedWindow.UpdateLogicalSize(sdlEvent.Window.Data1, sdlEvent.Window.Data2); } @@ -407,7 +408,7 @@ out Event? evnt return true; case SDLEventType.WindowPixelSizeChanged: - if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out var pixelResizedWindow)) + if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out Sdl3PlatformWindow? pixelResizedWindow)) { pixelResizedWindow.UpdatePixelSize(sdlEvent.Window.Data1, sdlEvent.Window.Data2); evnt = new WindowResizeEvent( @@ -422,7 +423,7 @@ out Event? evnt return false; case SDLEventType.WindowCloseRequested: - if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out var closingWindow)) + if (m_windows.TryGetValue(sdlEvent.Window.WindowID, out Sdl3PlatformWindow? closingWindow)) { closingWindow.MarkClosed(); } @@ -444,23 +445,23 @@ out Event? evnt case SDLEventType.KeyDown: { - var key = TranslateKey(sdlEvent.Key.Key); - var modifiers = TranslateModifiers((SDLKeymod)sdlEvent.Key.Mod); + KeyCode key = TranslateKey(sdlEvent.Key.Key); + KeyModifier modifiers = TranslateModifiers((SDLKeymod)sdlEvent.Key.Mod); evnt = new KeyPressedEvent(sdlEvent.Key.WindowID, key, modifiers, sdlEvent.Key.Repeat != 0); return true; } case SDLEventType.KeyUp: { - var key = TranslateKey(sdlEvent.Key.Key); - var modifiers = TranslateModifiers((SDLKeymod)sdlEvent.Key.Mod); + KeyCode key = TranslateKey(sdlEvent.Key.Key); + KeyModifier modifiers = TranslateModifiers((SDLKeymod)sdlEvent.Key.Mod); evnt = new KeyReleasedEvent(sdlEvent.Key.WindowID, key, modifiers); return true; } case SDLEventType.TextInput: { - string? text = sdlEvent.Text.Text == null + string? text = sdlEvent.Text.Text is null ? null : Marshal.PtrToStringUTF8((IntPtr)sdlEvent.Text.Text); if (!string.IsNullOrEmpty(text)) @@ -477,8 +478,8 @@ out Event? evnt case SDLEventType.MouseWheel: { - var wheelX = sdlEvent.Wheel.X; - var wheelY = sdlEvent.Wheel.Y; + float wheelX = sdlEvent.Wheel.X; + float wheelY = sdlEvent.Wheel.Y; if (sdlEvent.Wheel.Direction == SDLMouseWheelDirection.MousewheelFlipped) { wheelX = -wheelX; @@ -490,7 +491,7 @@ out Event? evnt } case SDLEventType.MouseButtonDown: - if (TryTranslateMouseButton(sdlEvent.Button.Button, out var pressedButton)) + if (TryTranslateMouseButton(sdlEvent.Button.Button, out MouseButton pressedButton)) { evnt = new MouseButtonPressedEvent(sdlEvent.Button.WindowID, pressedButton); return true; @@ -499,7 +500,7 @@ out Event? evnt break; case SDLEventType.MouseButtonUp: - if (TryTranslateMouseButton(sdlEvent.Button.Button, out var releasedButton)) + if (TryTranslateMouseButton(sdlEvent.Button.Button, out MouseButton releasedButton)) { evnt = new MouseButtonReleasedEvent(sdlEvent.Button.WindowID, releasedButton); return true; @@ -514,8 +515,8 @@ out Event? evnt private static KeyModifier TranslateModifiers(SDLKeymod modifiers) { - var sdlModifiers = (uint)modifiers; - var result = KeyModifier.None; + uint sdlModifiers = (uint)modifiers; + KeyModifier result = KeyModifier.None; if ((sdlModifiers & (SDL.Constants.SDL_KMOD_LSHIFT | SDL.Constants.SDL_KMOD_RSHIFT)) != 0) { @@ -568,117 +569,115 @@ out MouseButton button } private static KeyCode TranslateKey(uint sdlKey) + => sdlKey switch { - return sdlKey switch - { - SDL.Constants.SDLK_A => KeyCode.A, - SDL.Constants.SDLK_B => KeyCode.B, - SDL.Constants.SDLK_C => KeyCode.C, - SDL.Constants.SDLK_D => KeyCode.D, - SDL.Constants.SDLK_E => KeyCode.E, - SDL.Constants.SDLK_F => KeyCode.F, - SDL.Constants.SDLK_G => KeyCode.G, - SDL.Constants.SDLK_H => KeyCode.H, - SDL.Constants.SDLK_I => KeyCode.I, - SDL.Constants.SDLK_J => KeyCode.J, - SDL.Constants.SDLK_K => KeyCode.K, - SDL.Constants.SDLK_L => KeyCode.L, - SDL.Constants.SDLK_M => KeyCode.M, - SDL.Constants.SDLK_N => KeyCode.N, - SDL.Constants.SDLK_O => KeyCode.O, - SDL.Constants.SDLK_P => KeyCode.P, - SDL.Constants.SDLK_Q => KeyCode.Q, - SDL.Constants.SDLK_R => KeyCode.R, - SDL.Constants.SDLK_S => KeyCode.S, - SDL.Constants.SDLK_T => KeyCode.T, - SDL.Constants.SDLK_U => KeyCode.U, - SDL.Constants.SDLK_V => KeyCode.V, - SDL.Constants.SDLK_W => KeyCode.W, - SDL.Constants.SDLK_X => KeyCode.X, - SDL.Constants.SDLK_Y => KeyCode.Y, - SDL.Constants.SDLK_Z => KeyCode.Z, - - SDL.Constants.SDLK_0 => KeyCode.D0, - SDL.Constants.SDLK_1 => KeyCode.D1, - SDL.Constants.SDLK_2 => KeyCode.D2, - SDL.Constants.SDLK_3 => KeyCode.D3, - SDL.Constants.SDLK_4 => KeyCode.D4, - SDL.Constants.SDLK_5 => KeyCode.D5, - SDL.Constants.SDLK_6 => KeyCode.D6, - SDL.Constants.SDLK_7 => KeyCode.D7, - SDL.Constants.SDLK_8 => KeyCode.D8, - SDL.Constants.SDLK_9 => KeyCode.D9, - - SDL.Constants.SDLK_ESCAPE => KeyCode.Escape, - SDL.Constants.SDLK_SPACE => KeyCode.Space, - SDL.Constants.SDLK_RETURN => KeyCode.Enter, - SDL.Constants.SDLK_TAB => KeyCode.Tab, - SDL.Constants.SDLK_BACKSPACE => KeyCode.Backspace, - - SDL.Constants.SDLK_LEFT => KeyCode.LeftArrow, - SDL.Constants.SDLK_UP => KeyCode.UpArrow, - SDL.Constants.SDLK_RIGHT => KeyCode.RightArrow, - SDL.Constants.SDLK_DOWN => KeyCode.DownArrow, - - SDL.Constants.SDLK_LGUI => KeyCode.LeftSuper, - SDL.Constants.SDLK_RGUI => KeyCode.RightSuper, - SDL.Constants.SDLK_LSHIFT => KeyCode.LeftShift, - SDL.Constants.SDLK_RSHIFT => KeyCode.RightShift, - SDL.Constants.SDLK_LCTRL => KeyCode.LeftCtrl, - SDL.Constants.SDLK_RCTRL => KeyCode.RightCtrl, - SDL.Constants.SDLK_LALT => KeyCode.LeftAlt, - SDL.Constants.SDLK_RALT => KeyCode.RightAlt, - - SDL.Constants.SDLK_CAPSLOCK => KeyCode.CapsLock, - SDL.Constants.SDLK_INSERT => KeyCode.Insert, - SDL.Constants.SDLK_DELETE => KeyCode.Delete, - SDL.Constants.SDLK_HOME => KeyCode.Home, - SDL.Constants.SDLK_END => KeyCode.End, - SDL.Constants.SDLK_PAGEUP => KeyCode.PageUp, - SDL.Constants.SDLK_PAGEDOWN => KeyCode.PageDown, - - SDL.Constants.SDLK_KP_0 => KeyCode.NumPad0, - SDL.Constants.SDLK_KP_1 => KeyCode.NumPad1, - SDL.Constants.SDLK_KP_2 => KeyCode.NumPad2, - SDL.Constants.SDLK_KP_3 => KeyCode.NumPad3, - SDL.Constants.SDLK_KP_4 => KeyCode.NumPad4, - SDL.Constants.SDLK_KP_5 => KeyCode.NumPad5, - SDL.Constants.SDLK_KP_6 => KeyCode.NumPad6, - SDL.Constants.SDLK_KP_7 => KeyCode.NumPad7, - SDL.Constants.SDLK_KP_8 => KeyCode.NumPad8, - SDL.Constants.SDLK_KP_9 => KeyCode.NumPad9, - - SDL.Constants.SDLK_NUMLOCKCLEAR => KeyCode.NumLock, - SDL.Constants.SDLK_SCROLLLOCK => KeyCode.ScrollLock, - - SDL.Constants.SDLK_F1 => KeyCode.F1, - SDL.Constants.SDLK_F2 => KeyCode.F2, - SDL.Constants.SDLK_F3 => KeyCode.F3, - SDL.Constants.SDLK_F4 => KeyCode.F4, - SDL.Constants.SDLK_F5 => KeyCode.F5, - SDL.Constants.SDLK_F6 => KeyCode.F6, - SDL.Constants.SDLK_F7 => KeyCode.F7, - SDL.Constants.SDLK_F8 => KeyCode.F8, - SDL.Constants.SDLK_F9 => KeyCode.F9, - SDL.Constants.SDLK_F10 => KeyCode.F10, - SDL.Constants.SDLK_F11 => KeyCode.F11, - SDL.Constants.SDLK_F12 => KeyCode.F12, - - SDL.Constants.SDLK_PLUS => KeyCode.Plus, - SDL.Constants.SDLK_EQUALS => KeyCode.Plus, - SDL.Constants.SDLK_COMMA => KeyCode.Comma, - SDL.Constants.SDLK_MINUS => KeyCode.Minus, - SDL.Constants.SDLK_PERIOD => KeyCode.Period, - SDL.Constants.SDLK_SLASH => KeyCode.Slash, - SDL.Constants.SDLK_GRAVE => KeyCode.Tilde, - SDL.Constants.SDLK_BACKSLASH => KeyCode.Backslash, - SDL.Constants.SDLK_SEMICOLON => KeyCode.Semicolon, - SDL.Constants.SDLK_APOSTROPHE => KeyCode.Quote, - SDL.Constants.SDLK_LEFTBRACKET => KeyCode.LeftBracket, - SDL.Constants.SDLK_RIGHTBRACKET => KeyCode.RightBracket, - _ => KeyCode.Unknown - }; - } + SDL.Constants.SDLK_A => KeyCode.A, + SDL.Constants.SDLK_B => KeyCode.B, + SDL.Constants.SDLK_C => KeyCode.C, + SDL.Constants.SDLK_D => KeyCode.D, + SDL.Constants.SDLK_E => KeyCode.E, + SDL.Constants.SDLK_F => KeyCode.F, + SDL.Constants.SDLK_G => KeyCode.G, + SDL.Constants.SDLK_H => KeyCode.H, + SDL.Constants.SDLK_I => KeyCode.I, + SDL.Constants.SDLK_J => KeyCode.J, + SDL.Constants.SDLK_K => KeyCode.K, + SDL.Constants.SDLK_L => KeyCode.L, + SDL.Constants.SDLK_M => KeyCode.M, + SDL.Constants.SDLK_N => KeyCode.N, + SDL.Constants.SDLK_O => KeyCode.O, + SDL.Constants.SDLK_P => KeyCode.P, + SDL.Constants.SDLK_Q => KeyCode.Q, + SDL.Constants.SDLK_R => KeyCode.R, + SDL.Constants.SDLK_S => KeyCode.S, + SDL.Constants.SDLK_T => KeyCode.T, + SDL.Constants.SDLK_U => KeyCode.U, + SDL.Constants.SDLK_V => KeyCode.V, + SDL.Constants.SDLK_W => KeyCode.W, + SDL.Constants.SDLK_X => KeyCode.X, + SDL.Constants.SDLK_Y => KeyCode.Y, + SDL.Constants.SDLK_Z => KeyCode.Z, + + SDL.Constants.SDLK_0 => KeyCode.D0, + SDL.Constants.SDLK_1 => KeyCode.D1, + SDL.Constants.SDLK_2 => KeyCode.D2, + SDL.Constants.SDLK_3 => KeyCode.D3, + SDL.Constants.SDLK_4 => KeyCode.D4, + SDL.Constants.SDLK_5 => KeyCode.D5, + SDL.Constants.SDLK_6 => KeyCode.D6, + SDL.Constants.SDLK_7 => KeyCode.D7, + SDL.Constants.SDLK_8 => KeyCode.D8, + SDL.Constants.SDLK_9 => KeyCode.D9, + + SDL.Constants.SDLK_ESCAPE => KeyCode.Escape, + SDL.Constants.SDLK_SPACE => KeyCode.Space, + SDL.Constants.SDLK_RETURN => KeyCode.Enter, + SDL.Constants.SDLK_TAB => KeyCode.Tab, + SDL.Constants.SDLK_BACKSPACE => KeyCode.Backspace, + + SDL.Constants.SDLK_LEFT => KeyCode.LeftArrow, + SDL.Constants.SDLK_UP => KeyCode.UpArrow, + SDL.Constants.SDLK_RIGHT => KeyCode.RightArrow, + SDL.Constants.SDLK_DOWN => KeyCode.DownArrow, + + SDL.Constants.SDLK_LGUI => KeyCode.LeftSuper, + SDL.Constants.SDLK_RGUI => KeyCode.RightSuper, + SDL.Constants.SDLK_LSHIFT => KeyCode.LeftShift, + SDL.Constants.SDLK_RSHIFT => KeyCode.RightShift, + SDL.Constants.SDLK_LCTRL => KeyCode.LeftCtrl, + SDL.Constants.SDLK_RCTRL => KeyCode.RightCtrl, + SDL.Constants.SDLK_LALT => KeyCode.LeftAlt, + SDL.Constants.SDLK_RALT => KeyCode.RightAlt, + + SDL.Constants.SDLK_CAPSLOCK => KeyCode.CapsLock, + SDL.Constants.SDLK_INSERT => KeyCode.Insert, + SDL.Constants.SDLK_DELETE => KeyCode.Delete, + SDL.Constants.SDLK_HOME => KeyCode.Home, + SDL.Constants.SDLK_END => KeyCode.End, + SDL.Constants.SDLK_PAGEUP => KeyCode.PageUp, + SDL.Constants.SDLK_PAGEDOWN => KeyCode.PageDown, + + SDL.Constants.SDLK_KP_0 => KeyCode.NumPad0, + SDL.Constants.SDLK_KP_1 => KeyCode.NumPad1, + SDL.Constants.SDLK_KP_2 => KeyCode.NumPad2, + SDL.Constants.SDLK_KP_3 => KeyCode.NumPad3, + SDL.Constants.SDLK_KP_4 => KeyCode.NumPad4, + SDL.Constants.SDLK_KP_5 => KeyCode.NumPad5, + SDL.Constants.SDLK_KP_6 => KeyCode.NumPad6, + SDL.Constants.SDLK_KP_7 => KeyCode.NumPad7, + SDL.Constants.SDLK_KP_8 => KeyCode.NumPad8, + SDL.Constants.SDLK_KP_9 => KeyCode.NumPad9, + + SDL.Constants.SDLK_NUMLOCKCLEAR => KeyCode.NumLock, + SDL.Constants.SDLK_SCROLLLOCK => KeyCode.ScrollLock, + + SDL.Constants.SDLK_F1 => KeyCode.F1, + SDL.Constants.SDLK_F2 => KeyCode.F2, + SDL.Constants.SDLK_F3 => KeyCode.F3, + SDL.Constants.SDLK_F4 => KeyCode.F4, + SDL.Constants.SDLK_F5 => KeyCode.F5, + SDL.Constants.SDLK_F6 => KeyCode.F6, + SDL.Constants.SDLK_F7 => KeyCode.F7, + SDL.Constants.SDLK_F8 => KeyCode.F8, + SDL.Constants.SDLK_F9 => KeyCode.F9, + SDL.Constants.SDLK_F10 => KeyCode.F10, + SDL.Constants.SDLK_F11 => KeyCode.F11, + SDL.Constants.SDLK_F12 => KeyCode.F12, + + SDL.Constants.SDLK_PLUS => KeyCode.Plus, + SDL.Constants.SDLK_EQUALS => KeyCode.Plus, + SDL.Constants.SDLK_COMMA => KeyCode.Comma, + SDL.Constants.SDLK_MINUS => KeyCode.Minus, + SDL.Constants.SDLK_PERIOD => KeyCode.Period, + SDL.Constants.SDLK_SLASH => KeyCode.Slash, + SDL.Constants.SDLK_GRAVE => KeyCode.Tilde, + SDL.Constants.SDLK_BACKSLASH => KeyCode.Backslash, + SDL.Constants.SDLK_SEMICOLON => KeyCode.Semicolon, + SDL.Constants.SDLK_APOSTROPHE => KeyCode.Quote, + SDL.Constants.SDLK_LEFTBRACKET => KeyCode.LeftBracket, + SDL.Constants.SDLK_RIGHTBRACKET => KeyCode.RightBracket, + _ => KeyCode.Unknown + }; private static bool TryCreatePendingEventCoalesceKey( Event evnt, diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs index 3adbc71d8..a77f64187 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformApplication.Windows.cs @@ -108,7 +108,14 @@ bool ownsNativeWindow { throw new ArgumentException("The SDL window is invalid or already registered.", nameof(nativeWindow)); } - var window = new Sdl3PlatformWindow(nativeWindow, title, ownsNativeWindow, m_hostIntegration, RemoveWindow, m_ownerThreadId); + var window = new Sdl3PlatformWindow( + nativeWindow, + title, + ownsNativeWindow, + m_hostIntegration, + RemoveWindow, + m_ownerThreadId + ); m_windows.Add(id, window); return window; } diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs index f42c96f2e..0179943a3 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformBackendProvider.cs @@ -26,9 +26,6 @@ public Sdl3PlatformBackendProvider(ISdl3HostIntegration hostIntegration) m_hostIntegration = hostIntegration; } - /// - public override IPlatformApplication CreateApplication() - { - return new Sdl3PlatformApplication(m_hostIntegration); - } + /// + public override IPlatformApplication CreateApplication() => new Sdl3PlatformApplication(m_hostIntegration); } diff --git a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs index 7d121f471..cdc4ccd84 100644 --- a/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs +++ b/backends/Sdl3/runtime/Inno.Adapter.Platform.Sdl3/Sdl3PlatformWindow.Internal.cs @@ -47,8 +47,8 @@ int ownerThreadId m_ownsNativeWindow = ownsNativeWindow; m_windowId = SDL.Raw.GetWindowId(m_window); - var currentWidth = 0; - var currentHeight = 0; + int currentWidth = 0; + int currentHeight = 0; if (SDL.Raw.GetWindowSize(m_window, ¤tWidth, ¤tHeight) == 0) { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_GetWindowSize failed."); @@ -56,7 +56,7 @@ int ownerThreadId m_width = currentWidth; m_height = currentHeight; RefreshPixelSize(); - var flags = (SDLWindowFlags)SDL.Raw.GetWindowFlags(m_window); + SDLWindowFlags flags = (SDLWindowFlags)SDL.Raw.GetWindowFlags(m_window); m_isFocused = hostIntegration.GetInitialFocus(m_sdlWindowHandle); m_hidden = (flags & SDLWindowFlags.Hidden) != 0; m_minimized = (flags & SDLWindowFlags.Minimized) != 0; @@ -82,15 +82,9 @@ int height m_pixelHeight = height; } - internal void MarkClosed() - { - m_isClosed = true; - } + internal void MarkClosed() => m_isClosed = true; - internal void UpdateFocus(bool isFocused) - { - m_isFocused = isFocused; - } + internal void UpdateFocus(bool isFocused) => m_isFocused = isFocused; internal void UpdateVisibility(SDLEventType eventType) { @@ -113,8 +107,8 @@ internal void UpdateVisibility(SDLEventType eventType) private void RefreshPixelSize() { - var pixelWidth = 0; - var pixelHeight = 0; + int pixelWidth = 0; + int pixelHeight = 0; if (SDL.Raw.GetWindowSizeInPixels(m_window, &pixelWidth, &pixelHeight) == 0) { throw new InvalidOperationException(Sdl3NativeText.ReadError() ?? "SDL_GetWindowSizeInPixels failed."); @@ -125,10 +119,7 @@ private void RefreshPixelSize() /// /// Queues a close request for processing at the next platform safety point. /// - public partial void RequestClose() - { - m_isClosed = true; - } + public partial void RequestClose() => m_isClosed = true; /// /// Releases the resources owned by this instance. @@ -144,7 +135,7 @@ public partial void Dispose() return; } - if (m_window != null && m_ownsNativeWindow) + if (m_window is not null && m_ownsNativeWindow) { SDL.Raw.DestroyWindow(m_window); } diff --git a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs index 41813eb93..c4d1ac37d 100644 --- a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs +++ b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackend.cs @@ -19,7 +19,7 @@ public sealed unsafe class FreeTypeHarfBuzzTextBackend : ITextBackend public FreeTypeHarfBuzzTextBackend() { InnoTextFontAdapterRuntime* context = TextNativeOperations.CreateSession(); - if (context == null) + if (context is null) { throw new InvalidOperationException("The native text backend returned a null context."); } @@ -123,7 +123,7 @@ TextShapingOptions options ), "query shaped glyph count" ); - InnoTextFontAdapterGlyph[] nativeGlyphs = new InnoTextFontAdapterGlyph[checked((int)glyphCount)]; + var nativeGlyphs = new InnoTextFontAdapterGlyph[checked((int)glyphCount)]; if (nativeGlyphs.Length > 0) { fixed (InnoTextFontAdapterGlyph* glyphPointer = nativeGlyphs) @@ -147,7 +147,7 @@ TextShapingOptions options } } - TextGlyph[] glyphs = new TextGlyph[nativeGlyphs.Length]; + var glyphs = new TextGlyph[nativeGlyphs.Length]; float width = 0f; for (int index = 0; index < nativeGlyphs.Length; index++) { @@ -219,7 +219,7 @@ float fontSize TextNativeOperations.RasterizeGlyph(m_context, font.value, glyphId, fontSize, null, 0, &bitmap), "query glyph bitmap" ); - byte[] pixels = new byte[checked((int)bitmap.ByteLength)]; + var pixels = new byte[checked((int)bitmap.ByteLength)]; if (pixels.Length > 0) { fixed (byte* pixelPointer = pixels) @@ -257,7 +257,7 @@ public void Dispose() private static byte[] Utf8(string value) { - byte[] bytes = new byte[Encoding.UTF8.GetByteCount(value) + 1]; + var bytes = new byte[Encoding.UTF8.GetByteCount(value) + 1]; Encoding.UTF8.GetBytes(value, bytes); return bytes; } diff --git a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs index cd2189530..808c4bf4a 100644 --- a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs +++ b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/FreeTypeHarfBuzzTextBackendProvider.cs @@ -14,9 +14,6 @@ public sealed class FreeTypeHarfBuzzTextBackendProvider : TextBackendProvider public FreeTypeHarfBuzzTextBackendProvider() : base(TextBackendId.freeTypeHarfBuzz) {} - /// - public override ITextBackend CreateBackend() - { - return new FreeTypeHarfBuzzTextBackend(); - } + /// + public override ITextBackend CreateBackend() => new FreeTypeHarfBuzzTextBackend(); } diff --git a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs index 869dbe827..54167b6b7 100644 --- a/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs +++ b/backends/Text/runtime/Inno.Adapter.Text.FreeTypeHarfBuzz/TextNativeOperations.cs @@ -151,20 +151,20 @@ private static void CheckBridge( int status, BgcsInnoTextError* error ) { - if (status == 0 && error == null) + if (status == 0 && error is null) { return; } try { - string? message = error == null ? null : Marshal.PtrToStringUTF8((nint)TextNative.Raw.BgcsInnoTextErrorMessage(error)); + string? message = error is null ? null : Marshal.PtrToStringUTF8((nint)TextNative.Raw.BgcsInnoTextErrorMessage(error)); throw new InvalidOperationException( $"The text bridge failed with status {status}: {message ?? "No native error text is available."}" ); } finally { - if (error != null) + if (error is not null) { TextNative.Raw.BgcsInnoTextErrorRelease(error); } diff --git a/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs b/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs index f648603c9..baacae141 100644 --- a/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs +++ b/build/bindings/Inno.Build.Bindings/Configuration/BindingDefinitionReader.cs @@ -23,7 +23,7 @@ NativeBindingProfile profile { throw new InvalidDataException("Binding definitions must be declarative Project data."); } - Dictionary properties = new(StringComparer.Ordinal); + var properties = new Dictionary(StringComparer.Ordinal); foreach (XElement group in project.Elements()) { if (group.Attributes().Any()) diff --git a/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs b/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs index f6346f621..bb7cdc5b5 100644 --- a/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs +++ b/build/bindings/Inno.Build.Bindings/Configuration/NativeBindingProfile.cs @@ -3,9 +3,11 @@ using System.Collections.Immutable; using System.IO; using System.Linq; +using System.Reflection; using BGCS; using BGCS.Configuration; using BGCS.Core; +using BGCS.Core.Inputs; using BGCS.Core.Targets; using Inno.Build.Toolchains; @@ -100,7 +102,7 @@ public NativeBindingProfile( internal void Configure(BindingHostBuilder builder) => m_configureGenerator?.Invoke(builder); - internal IEnumerable GetExtensionAssemblies() + internal IEnumerable GetExtensionAssemblies() => m_configureGenerator?.GetInvocationList().Select(static action => action.Method.Module.Assembly) ?? []; internal GenerationRequest Apply( @@ -116,7 +118,7 @@ string engineRoot { settings = selected.settings with { - compilerPath = request.configuration.source.language == BGCS.Core.Inputs.SourceLanguage.Cpp + compilerPath = request.configuration.source.language == SourceLanguage.Cpp ? compiler.cppCompiler : compiler.cCompiler, sysRoot = compiler.sysRoot, diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs index 51242e26b..123b432bf 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs @@ -5,6 +5,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using BGCS; +using BGCS.Core; using Inno.Build.Toolchains; using Inno.Core.IO; @@ -70,16 +72,16 @@ internal async ValueTask ExecuteAsync(Cancellatio } m_context.RecordBindingBatch(); Verify(definitions, fingerprints, m_context.BeginInputVerification("binding-locks"), cancellation); - Dictionary results = new(StringComparer.Ordinal); - HashSet protectedTargets = new(StringComparer.Ordinal); + var results = new Dictionary(StringComparer.Ordinal); + var protectedTargets = new HashSet(StringComparer.Ordinal); for (int index = 0; index < definitions.Length; index++) { cancellation.ThrowIfCancellationRequested(); BindingGenerationConfiguration definition = definitions[index]; string fingerprint = fingerprints[index]; string output = definition.GetOutputRoot(m_context); - var loaded = definition.Load(m_context, cancellation); - bool usesRuntimeImports = loaded.configuration.api.importMode != BGCS.Core.BindingImportMode.FunctionTable; + GenerationRequest loaded = definition.Load(m_context, cancellation); + bool usesRuntimeImports = loaded.configuration.api.importMode != BindingImportMode.FunctionTable; if (m_request.outputMode == NativeBindingOutputMode.TargetArtifacts) { string destination = Path.Combine(output, fingerprint); @@ -114,7 +116,7 @@ await BuildArtifactReadLease.AcquireAsync( { // Invalid output is repaired only after exclusive artifact ownership is acquired at commit. } - var publication = BindingGenerationPublication.CreateTarget( + BindingGenerationPublication publication = BindingGenerationPublication.CreateTarget( Path.Combine(m_context.engineRoot, "artifacts", "bindings"), destination, cancellation @@ -133,7 +135,7 @@ await BuildArtifactReadLease.AcquireAsync( } else { - var publication = BindingGenerationPublication.CreateHost( + BindingGenerationPublication publication = BindingGenerationPublication.CreateHost( Path.Combine(m_context.engineRoot, "artifacts", "bindings"), output, definition.GetHostNativeRoot(m_context), @@ -296,7 +298,7 @@ private string Compute( NativeBuildContext context, CancellationToken cancellation ) { - var loaded = definition.Load(context, cancellation); + GenerationRequest loaded = definition.Load(context, cancellation); return NativeBindingGenerationIdentity.Compute(loaded, definition, context, cancellation); } } diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs index 8770c4114..3c0aba14e 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingHostExecution.cs @@ -1,9 +1,12 @@ using System; +using System.Collections.Generic; +using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using BGCS; +using BGCS.Core; using BGCS.Core.Artifacts; using BGCS.Core.Hosting; @@ -31,7 +34,7 @@ CancellationToken cancellation await using BindingHost host = BindingHostFactory.CreateBuilder(profile, cancellation).Build(); await using HostServices services = BindingHostFactory.CreateHostServices(engineRoot); GenerationResult result = await host.GenerateAsync(request, cancellation).ConfigureAwait(false); - foreach (var diagnostic in result.diagnostics) + foreach (BindingDiagnostic diagnostic in result.diagnostics) { Console.WriteLine($"BGCS {diagnostic.severity} {diagnostic.code}: {diagnostic.message}"); if (diagnostic.details is not null) @@ -46,18 +49,23 @@ CancellationToken cancellation Environment.NewLine, result.diagnostics .Where(static diagnostic => ( - diagnostic.severity is BGCS.Core.BindingDiagnosticSeverity.Error - or BGCS.Core.BindingDiagnosticSeverity.Critical + diagnostic.severity is BindingDiagnosticSeverity.Error + or BindingDiagnosticSeverity.Critical )) .Select(static diagnostic => diagnostic.code + ": " + diagnostic.message) ) ); } - foreach (var stage in result.cacheStages) + foreach (GenerationCacheStageResult stage in result.cacheStages) { Console.WriteLine($"BGCS cache {stage.targetId}/{stage.stage}: {stage.status}; {stage.reason}"); } - var artifacts = BindingArtifactManifest.Read(result.outputRoot, request.configuration.library.id, services.paths, cancellation); + ImmutableArray artifacts = BindingArtifactManifest.Read( + result.outputRoot, + request.configuration.library.id, + services.paths, + cancellation + ); ArtifactDescriptor[] managed = artifacts .Where(static artifact => artifact.relativePath.EndsWith("/managed/Bindings.cs", StringComparison.Ordinal)) .ToArray(); @@ -76,14 +84,14 @@ or BGCS.Core.BindingDiagnosticSeverity.Critical throw new InvalidDataException("A component generation requires exactly one native source manifest."); } NativeSourceManifest manifest = manifests[0]; - var generatedRoots = manifest.inputRoots.Where(static root => root.kind == "generated") + HashSet generatedRoots = manifest.inputRoots.Where(static root => root.kind == "generated") .Select(static root => root.id) .ToHashSet(StringComparer.Ordinal); - var nativePaths = manifest.sources.Concat(manifest.headers) + HashSet nativePaths = manifest.sources.Concat(manifest.headers) .Select(static artifact => artifact.relativePath) .Concat(manifest.inputs.Where(input => generatedRoots.Contains(input.rootId)).Select(static input => input.relativePath)) .ToHashSet(StringComparer.Ordinal); - var selectedArtifacts = artifacts.Where(artifact => nativePaths.Contains(artifact.relativePath)).ToArray(); + ArtifactDescriptor[] selectedArtifacts = artifacts.Where(artifact => nativePaths.Contains(artifact.relativePath)).ToArray(); if (selectedArtifacts.Length != nativePaths.Count) { throw new InvalidDataException("Every generated native input must belong to the SDK's verified publication."); diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs index 6e9fcf5c8..a968520b0 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingNativeCompilation.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; @@ -7,6 +8,8 @@ using BGCS; using BGCS.Core.Artifacts; using BGCS.Core.Inputs; +using BGCS.Core.Requests; +using BGCS.Core.Targets; using Inno.Build.Toolchains; namespace Inno.Build.Bindings; @@ -21,7 +24,8 @@ internal static void Write( string nativeOutput, CancellationToken cancellation ) { - var bindings = result.nativeInputRoots.Where(binding => binding.targetId == manifest.targetId) + Dictionary bindings = result.nativeInputRoots + .Where(binding => binding.targetId == manifest.targetId) .ToDictionary(static binding => binding.rootId, StringComparer.Ordinal); NativeBindingSourceRoot[] roots = manifest.inputRoots.Select(root => new NativeBindingSourceRoot( root.id, @@ -29,8 +33,8 @@ CancellationToken cancellation root.kind == "generated", root.kind is "generated" or "project" or "user" )).ToArray(); - var sources = manifest.sources.Select(static source => source.relativePath).ToHashSet(StringComparer.Ordinal); - var files = manifest.inputs.Select(input => new NativeBindingSourceFile( + HashSet sources = manifest.sources.Select(static source => source.relativePath).ToHashSet(StringComparer.Ordinal); + List files = manifest.inputs.Select(input => new NativeBindingSourceFile( input.rootId, input.relativePath, input.length, @@ -53,11 +57,12 @@ root.kind is "generated" or "project" or "user" ); } } - var table = manifest.staticExportTable; - var target = result.targetModels.Single(model => model.targetId == manifest.targetId).resolvedTarget - ?? throw new InvalidDataException("The SDK must return the resolved target used for generation."); - var parserDefines = target.toolchain.defines.ToHashSet(StringComparer.Ordinal); - var explicitDefines = request.configuration.source.defines.Concat(request.configuration.targets.Single().settings.defines) + StaticExportTableDescriptor? table = manifest.staticExportTable; + NativeTargetDescriptor target = result.targetModels.Single(model => model.targetId == manifest.targetId).resolvedTarget + ?? throw new InvalidDataException("The SDK must return the resolved target used for generation."); + HashSet parserDefines = target.toolchain.defines.ToHashSet(StringComparer.Ordinal); + HashSet explicitDefines = request.configuration.source.defines + .Concat(request.configuration.targets.Single().settings.defines) .ToHashSet(StringComparer.Ordinal); var compilation = new NativeBindingCompilation { diff --git a/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs b/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs index 68058f88b..a77e09822 100644 --- a/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs +++ b/build/bindings/Inno.Build.Bindings/Identity/NativeBindingGenerationIdentity.cs @@ -9,9 +9,12 @@ using System.Text.Json.Serialization; using System.Threading; using BGCS; +using BGCS.Configuration; +using BGCS.Core; using BGCS.Core.Hosting; using BGCS.Core.Inputs; using BGCS.Core.Targets; +using BGCS.Runtime; using Inno.Build.Toolchains; namespace Inno.Build.Bindings; @@ -30,7 +33,7 @@ internal static string Compute( CancellationToken cancellation ) { using HostServices services = BindingHostFactory.CreateHostServices(context.engineRoot); - var builder = BindingHostFactory.CreateBuilder(definition.profile, cancellation); + BindingHostBuilder builder = BindingHostFactory.CreateBuilder(definition.profile, cancellation); foreach (string plugin in request.configuration.extensions.plugins) { builder.AddPluginManifest(plugin, services.paths); @@ -38,10 +41,10 @@ CancellationToken cancellation BindingHost host = builder.Build(); try { - var config = request.configuration; - var target = config.targets.Single(); - var settings = target.settings; - var source = config.source; + BindingConfiguration config = request.configuration; + TargetConfiguration target = config.targets.Single(); + ToolchainConfiguration settings = target.settings; + SourceConfiguration source = config.source; AnalysisResult analysis = host.AnalyzeAsync(new AnalysisRequest(source.headers, source.language, request.baseDirectory) { targetId = target.id, @@ -81,10 +84,10 @@ CancellationToken cancellation definition.request.targetId, definition.request.outputMode.ToString() }; - var profileInputs = definition.profile.inputPaths.Select( + IEnumerable profileInputs = definition.profile.inputPaths.Select( path => NativeBuildInput.FromPath(context.engineRoot, Path.GetFullPath(path, context.engineRoot)) ); - var inputs = request.configurationSnapshot.files + List inputs = request.configurationSnapshot.files .Concat(request.pluginSnapshots.SelectMany(static snapshot => snapshot.files)) .Concat(analysis.snapshot.files) .Concat(analysis.argumentInputs?.files ?? []) @@ -96,11 +99,11 @@ CancellationToken cancellation .Single(attribute => attribute.Key == "Inno.BindingImplementation").Value ?? throw new InvalidDataException("The binding implementation must declare its content identity."); declarations.Add("bindingImplementation=" + implementationIdentity); - var assemblies = new[] + List assemblies = new[] { typeof(BindingHost).Assembly, - typeof(BGCS.Core.BindingDiagnostic).Assembly, - typeof(BGCS.Runtime.NativeModuleSession).Assembly + typeof(BindingDiagnostic).Assembly, + typeof(NativeModuleSession).Assembly }.Concat(definition.profile.GetExtensionAssemblies()).ToList(); foreach (AssemblyName reference in assemblies .Prepend(implementation) diff --git a/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs b/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs index 4afb10927..ac73066e2 100644 --- a/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs +++ b/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs @@ -9,10 +9,10 @@ namespace Inno.Build.Bindings; /// public sealed partial class NativeBindingGenerator { - /// /// /// Configuration inheritance uses a remote input without local build ownership. /// + /// public ValueTask ComputeInputFingerprintAsync( NativeBuildContext context, NativeBindingGenerationRequest request, diff --git a/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.cs b/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.cs index 640193808..57776ff62 100644 --- a/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.cs +++ b/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.cs @@ -24,7 +24,7 @@ public NativeBindingGenerator(NativeBindingProfile profile) m_profile = profile ?? throw new ArgumentNullException(nameof(profile)); } - /// + /// public async ValueTask GenerateAsync( NativeBuildContext context, NativeBindingGenerationRequest request, diff --git a/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs b/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs index e0ab53972..9c0ce4867 100644 --- a/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs +++ b/build/bindings/Inno.Build.Bindings/Publication/BindingGenerationPublication.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Threading; +using Inno.Build.Toolchains; using Inno.Core.IO; namespace Inno.Build.Bindings; @@ -22,8 +23,8 @@ private BindingGenerationPublication( bool target, CancellationToken cancellation ) { - managedDestination = destination; - nativeDestination = native; + this.managedDestination = destination; + this.nativeDestination = native; m_owner = ProcessOwnedDirectory.CreateAsync(workingRoot, cancellation).AsTask().GetAwaiter().GetResult(); m_workingRoot = workingRoot; m_target = target; @@ -75,7 +76,7 @@ internal void Commit() var installed = new List(); try { - foreach (var candidate in m_candidates) + foreach (KeyValuePair candidate in m_candidates) { Directory.CreateDirectory(Path.GetDirectoryName(candidate.Key)!); if (Directory.Exists(candidate.Key)) @@ -112,7 +113,7 @@ internal void Commit() if (failures.Count > 1) { m_preserveRecovery = true; - new Inno.Build.Toolchains.BuildCachePublisher(m_workingRoot, Inno.Build.Toolchains.BuildCacheArtifactRole.ImmutableArtifact) + new BuildCachePublisher(m_workingRoot, BuildCacheArtifactRole.ImmutableArtifact) .Record( m_owner.directory, m_owner.directory + ".work.lock", diff --git a/build/cli/Inno.Build.Cli/BuildApplication.cs b/build/cli/Inno.Build.Cli/BuildApplication.cs index ddabed792..1011f2116 100644 --- a/build/cli/Inno.Build.Cli/BuildApplication.cs +++ b/build/cli/Inno.Build.Cli/BuildApplication.cs @@ -4,7 +4,7 @@ using Inno.Tooling.Architecture; using Inno.Tooling.Validation; -using DocumentationCommand = Inno.Tooling.Documentation.DocumentationCommand; +using ToolingCommand = Inno.Tooling.Documentation.DocumentationCommand; namespace Inno.Build.Cli; @@ -89,7 +89,7 @@ CancellationToken cancellationToken { return await DocumentationExamples.ExecuteAsync([..options[1..], "--operation", "plan"], cancellationToken); } - return await DocumentationCommand.ExecuteAsync(options, cancellationToken); + return await ToolingCommand.ExecuteAsync(options, cancellationToken); case "validate": return await ValidationCommand.ExecuteAsync(options, cancellationToken); case "verify-native": @@ -128,13 +128,27 @@ CancellationToken cancellationToken var context = new BuildCommandContext(parsed); switch (command) { - case "native-dependencies": await NativeDependenciesCommand.RunAsync(context, parsed, cancellationToken); break; - case "support": await SupportBuildCommand.RunAsync(context, parsed, cancellationToken); break; - case "editor": await EditorBuildCommand.RunAsync(context, parsed, cancellationToken); break; - case "clean": await CleanCommand.RunAsync(context, parsed, cancellationToken); break; - case "bindings": await BindingCommand.RunAsync(context, parsed, cancellationToken); break; - case "support-pack": await SupportPackCommand.RunAsync(context, parsed, cancellationToken); break; - case "shader": await ShaderCommand.RunAsync(context, parsed, cancellationToken); break; + case "native-dependencies": + await NativeDependenciesCommand.RunAsync(context, parsed, cancellationToken); + break; + case "support": + await SupportBuildCommand.RunAsync(context, parsed, cancellationToken); + break; + case "editor": + await EditorBuildCommand.RunAsync(context, parsed, cancellationToken); + break; + case "clean": + await CleanCommand.RunAsync(context, parsed, cancellationToken); + break; + case "bindings": + await BindingCommand.RunAsync(context, parsed, cancellationToken); + break; + case "support-pack": + await SupportPackCommand.RunAsync(context, parsed, cancellationToken); + break; + case "shader": + await ShaderCommand.RunAsync(context, parsed, cancellationToken); + break; } if (command is "support" or "editor" or "support-pack" or "bindings" or "shader") { diff --git a/build/cli/Inno.Build.Cli/BuildCommand.cs b/build/cli/Inno.Build.Cli/BuildCommand.cs index 25642bdb7..edbaca3b6 100644 --- a/build/cli/Inno.Build.Cli/BuildCommand.cs +++ b/build/cli/Inno.Build.Cli/BuildCommand.cs @@ -30,10 +30,10 @@ IReadOnlyDictionary values { _ = Require(values, "target"); } - projectDirectory = Require(values, "project"); - supportPackRoot = kind == BuildCommandKind.Game - ? Require(values, "support-packs") - : values.GetValueOrDefault("support-packs", Path.Combine(AppContext.BaseDirectory, "SupportPacks")); + this.projectDirectory = Require(values, "project"); + this.supportPackRoot = kind == BuildCommandKind.Game + ? Require(values, "support-packs") + : values.GetValueOrDefault("support-packs", Path.Combine(AppContext.BaseDirectory, "SupportPacks")); } internal BuildCommandKind kind { get; } @@ -149,7 +149,7 @@ internal PluginBuildRequest CreatePluginRequest(ProjectId projectId) outputPath = Require(m_values, "output"), dependencies = m_values.TryGetValue("dependencies", out string? dependencyList) ? dependencyList.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) - : Array.Empty(), + : [], includeDependencies = m_values.ContainsKey("include-dependencies") }; diff --git a/build/cli/Inno.Build.Cli/BuildCommandContext.cs b/build/cli/Inno.Build.Cli/BuildCommandContext.cs index 6bc902245..ef88274d2 100644 --- a/build/cli/Inno.Build.Cli/BuildCommandContext.cs +++ b/build/cli/Inno.Build.Cli/BuildCommandContext.cs @@ -14,25 +14,25 @@ internal sealed class BuildCommandContext { internal BuildCommandContext(BuildCommandLine options) { - nativeDependencies = options.Read("native-dependencies", string.Empty); - root = ResolveEngineRoot(options.Read("engine-root", string.Empty)); + this.nativeDependencies = options.Read("native-dependencies", string.Empty); + this.root = ResolveEngineRoot(options.Read("engine-root", string.Empty)); if (nativeDependencies.Length > 0) { - nativeDependencies = Path.GetFullPath(nativeDependencies, root); + this.nativeDependencies = Path.GetFullPath(nativeDependencies, root); } - configuration = options.Read("configuration", "Release"); + this.configuration = options.Read("configuration", "Release"); ToolchainEnvironment.ValidateConfiguration(configuration.ToLowerInvariant()); - configuration = configuration.Equals("debug", StringComparison.OrdinalIgnoreCase) ? "Debug" : "Release"; - toolsTarget = new BuildTargetId(options.Require("tools-target")); - target = new BuildTargetId(options.Read("target", toolsTarget.value)); + this.configuration = configuration.Equals("debug", StringComparison.OrdinalIgnoreCase) ? "Debug" : "Release"; + this.toolsTarget = new BuildTargetId(options.Require("tools-target")); + this.target = new BuildTargetId(options.Read("target", toolsTarget.value)); string dotnet = ToolchainEnvironment.ResolveExecutable(options.Read("dotnet", "dotnet")); - composition = StandardBuildEnvironment.Capture( + this.composition = StandardBuildEnvironment.Capture( Path.GetDirectoryName(typeof(BuildApplication).Assembly.Location)!, toolsTarget, dotnet, nativeDependencies.Length == 0 ? null : nativeDependencies ); - distribution = StandardBuildDistribution.Create(composition).build; + this.distribution = StandardBuildDistribution.Create(composition).build; } internal string nativeDependencies { get; } diff --git a/build/cli/Inno.Build.Cli/BuildComposition.cs b/build/cli/Inno.Build.Cli/BuildComposition.cs index 87ac8f56c..c239796c8 100644 --- a/build/cli/Inno.Build.Cli/BuildComposition.cs +++ b/build/cli/Inno.Build.Cli/BuildComposition.cs @@ -28,7 +28,7 @@ internal static async Task PrepareNativeAsync( CancellationToken cancellationToken, string? nativeDependencies = null ) { - var distribution = StandardBuildDistribution.Create(context).build; + BuildDistribution distribution = StandardBuildDistribution.Create(context).build; NativeProductContribution contribution = distribution.ResolveNativeProduct(context.toolsTarget.value, "shader-tools"); if (nativeDependencies is not null) { @@ -41,10 +41,11 @@ internal static async Task PrepareNativeAsync( cancellationToken ).ConfigureAwait(false); } - var nativeContext = new NativeBuildContext(engineRoot, C_HOST_CONFIGURATION).WithBindingGenerator( + NativeBuildContext nativeContext = new NativeBuildContext(engineRoot, C_HOST_CONFIGURATION).WithBindingGenerator( StandardBuildDistribution.Create(context).build.ResolveBindingGenerator(context.toolsTarget.value) ); - var provider = StandardBuildDistribution.Create(context).build.ResolveNativeToolchain(context.toolsTarget.value); + INativeToolchainProvider provider = StandardBuildDistribution.Create(context).build + .ResolveNativeToolchain(context.toolsTarget.value); nativeContext = nativeContext.WithToolchain( await provider.ResolveAsync( nativeContext, @@ -65,16 +66,14 @@ internal static BuildPipeline CreatePipeline( ScriptCompiler compiler, string supportPackRoot, ToolRunner tools - ) { - return BuildPipelineFactory.Create( - context, - StandardBuildDistribution.Create(context, tools).build, - engine, - assets, - plugins, - settings, - compiler, - supportPackRoot - ); - } + ) => BuildPipelineFactory.Create( + context, + StandardBuildDistribution.Create(context, tools).build, + engine, + assets, + plugins, + settings, + compiler, + supportPackRoot + ); } diff --git a/build/cli/Inno.Build.Cli/BuildWorkspace.cs b/build/cli/Inno.Build.Cli/BuildWorkspace.cs index 3a30bc2ae..2890ad26b 100644 --- a/build/cli/Inno.Build.Cli/BuildWorkspace.cs +++ b/build/cli/Inno.Build.Cli/BuildWorkspace.cs @@ -126,7 +126,7 @@ CancellationToken cancellationToken } cancellationToken.ThrowIfCancellationRequested(); string[] assemblies = result.moduleDeployments - .Where(static request => request.domain == Inno.Extensibility.Modules.AssemblyDomain.InnoScripting) + .Where(static request => request.domain == AssemblyDomain.InnoScripting) .SelectMany(static request => new[] { request.mainAssemblyPath }.Concat(request.preloadAssemblyPaths)) .Distinct(StringComparer.OrdinalIgnoreCase) .ToArray(); @@ -309,7 +309,7 @@ CancellationToken cancellationToken + string.Join(Environment.NewLine, result.diagnostics.Select(static diagnostic => diagnostic.message)) ); } - using Inno.Extensibility.Modules.AssemblyReloadSession reload = engine.modules.BeginReload( + using AssemblyReloadSession reload = engine.modules.BeginReload( result.moduleDeployments.Select(deployment => CreateScriptModuleSource(deployment, artifactRootDirectory)).ToArray() ); _ = engine.generations.Execute("Build authoring generation", reload, [plugins.CreateReloadChange()]); diff --git a/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs b/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs index bfc9ec6a7..013db07a2 100644 --- a/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs +++ b/build/cli/Inno.Build.Cli/Cleanup/ProductCleanPlan.cs @@ -4,6 +4,7 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Inno.Build.Composition; using Inno.Build.Toolchains; using Inno.Core.IO; @@ -19,7 +20,7 @@ internal static async Task CreateAsync( CancellationToken cancellationToken ) { var projects = new List { project }; - foreach (var platform in context.distribution.platforms) + foreach (BuildPlatformContribution platform in context.distribution.platforms) { if (platform.descriptor.id == context.target && platform.editorProject is not null) { diff --git a/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs b/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs index f6389f902..33366127d 100644 --- a/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/BindingCommand.cs @@ -45,7 +45,7 @@ CancellationToken cancellationToken ).ConfigureAwait(false); return; } - NativeBuildContext bindings = new(root, configuration.ToLowerInvariant()); + var bindings = new NativeBuildContext(root, configuration.ToLowerInvariant()); bindings = bindings.WithBindingGenerator(distribution.ResolveBindingGenerator(target.value)); bindings = bindings.WithToolchain( await distribution.ResolveNativeToolchain(target.value) diff --git a/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs b/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs index 6e5c56e73..ae1a6ad9c 100644 --- a/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/CleanCommand.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Cli; @@ -26,7 +27,7 @@ CancellationToken cancellationToken throw new ArgumentException($"Unsupported cleanup scope '{scope}'."); } string project = await context.PreflightEditorAsync(cancellationToken).ConfigureAwait(false); - using var ownership = await ProductCleanExecutor.AcquireAsync(context, cancellationToken).ConfigureAwait(false); + using FileLease ownership = await ProductCleanExecutor.AcquireAsync(context, cancellationToken).ConfigureAwait(false); ProductCleanPlan plan = await ProductCleanPlan.CreateAsync(context, project, cancellationToken).ConfigureAwait(false); ProductCleanExecutor.Execute(plan, options.Has("dry-run"), cancellationToken); } diff --git a/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs b/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs index 887d235bd..e0362e9c1 100644 --- a/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/EditorBuildCommand.cs @@ -1,6 +1,7 @@ using System.Threading; using System.Threading.Tasks; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Cli; @@ -12,7 +13,7 @@ internal static async Task RunAsync( CancellationToken cancellationToken ) { string project = await context.PreflightEditorAsync(cancellationToken).ConfigureAwait(false); - using var ownership = await ProductCleanExecutor.AcquireAsync(context, cancellationToken).ConfigureAwait(false); + using FileLease ownership = await ProductCleanExecutor.AcquireAsync(context, cancellationToken).ConfigureAwait(false); if (options.Has("clean")) { ProductCleanPlan plan = await ProductCleanPlan.CreateAsync(context, project, cancellationToken).ConfigureAwait(false); diff --git a/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs b/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs index 651df8355..24d052267 100644 --- a/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; @@ -8,6 +9,7 @@ using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Cli; @@ -37,9 +39,9 @@ CancellationToken cancellation platform => platform.descriptor.id == request.target ) ?? throw new NotSupportedException("No native dependency platform is registered for '" + request.target + "'."); - Inno.Core.IO.AtomicFile.WriteAllBytes( + AtomicFile.WriteAllBytes( options.Require("output"), - System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new + JsonSerializer.SerializeToUtf8Bytes(new { target = platform.descriptor.id.value, products = platform.nativeProducts.Keys.Order(StringComparer.Ordinal).ToArray() @@ -55,15 +57,16 @@ CancellationToken cancellation { throw new ArgumentException("Producer binding verification cannot consume a prebuilt selection."); } - var steps = product.plan.steps.Where(static step => step.component.bindingDefinition is not null) + IGrouping[] steps = product.plan.steps + .Where(static step => step.component.bindingDefinition is not null) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) .ToArray(); if (steps.Length == 0) { return; } - var generator = request.distribution.ResolveBindingGenerator(request.target.value); - var bindingContext = new NativeBuildContext( + INativeBindingGenerator generator = request.distribution.ResolveBindingGenerator(request.target.value); + NativeBuildContext bindingContext = new NativeBuildContext( request.root, request.configuration.ToLowerInvariant() ).WithBindingGenerator(generator); @@ -101,7 +104,7 @@ await request.distribution.ResolveNativeToolchain(request.target.value) string output = options.Require("output"); try { - var assets = await NativeDependencyManifest.SelectAsync( + IReadOnlyList assets = await NativeDependencyManifest.SelectAsync( request.root, options.Require("native-dependencies"), request.target.value, @@ -112,11 +115,11 @@ await request.distribution.ResolveNativeToolchain(request.target.value) byte[] result = operation == "select" ? JsonSerializer.SerializeToUtf8Bytes(assets) : JsonSerializer.SerializeToUtf8Bytes(new { matched = true, assets }); - Inno.Core.IO.AtomicFile.WriteAllBytes(output, result); + AtomicFile.WriteAllBytes(output, result); } catch (InvalidDataException failure) when (operation == "evaluate") { - Inno.Core.IO.AtomicFile.WriteAllBytes( + AtomicFile.WriteAllBytes( output, JsonSerializer.SerializeToUtf8Bytes(new { matched = false, reason = failure.Message }) ); @@ -132,11 +135,11 @@ await request.distribution.ResolveNativeToolchain(request.target.value) { throw new ArgumentException("Dependency production cannot consume a prebuilt selection."); } - var phase = Stopwatch.StartNew(); + Stopwatch phase = Stopwatch.StartNew(); Console.WriteLine( $"Native producer: {product.plan.productId}/{request.target.value}/{request.configuration}; resolving the explicit toolchain." ); - var context = new NativeBuildContext(request.root, request.configuration.ToLowerInvariant()).WithBindingGenerator( + NativeBuildContext context = new NativeBuildContext(request.root, request.configuration.ToLowerInvariant()).WithBindingGenerator( request.distribution.ResolveBindingGenerator(request.target.value) ); context = context.WithToolchain( diff --git a/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs b/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs index 74277e57f..0dc59acdf 100644 --- a/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/ShaderCommand.cs @@ -59,7 +59,7 @@ await distribution.ResolveNativeToolchain(toolsTarget.value) ).ConfigureAwait(false); NativeBuildProduct product = products.Single(); string extension = context.host.services.executableExtension; - var executables = Enum.GetValues().ToDictionary( + Dictionary executables = Enum.GetValues().ToDictionary( static tool => tool, tool => product.files.Single(file => ( Path.GetFileName(file) == tool.ToString().ToLowerInvariant() diff --git a/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs b/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs index cbd1537b1..215ed4331 100644 --- a/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs +++ b/build/cli/Inno.Build.Cli/NativeBindingsVerification.cs @@ -53,7 +53,7 @@ CancellationToken cancellationToken ); } NativeProductContribution contribution = distribution.ResolveNativeProduct(options.target, "editor"); - var nativeContext = new NativeBuildContext(repositoryRoot, options.configuration.ToLowerInvariant()) + NativeBuildContext nativeContext = new NativeBuildContext(repositoryRoot, options.configuration.ToLowerInvariant()) .WithBindingGenerator(distribution.ResolveBindingGenerator(options.target)); NativeToolchainSelection sdk = await distribution.ResolveNativeToolchain(options.target) .ResolveAsync(nativeContext, execution.host, options.target, cancellationToken) @@ -131,7 +131,11 @@ await ToolchainEnvironment.RunAsync( DotNetSdkEnvironment.Create(options.dotnet) ); - var native = await BuildNativeDependenciesAsync(nativeContext, contribution, cancellationToken); + (ProductNativeBuildPlan plan, ProductNativeBuildResult products) native = await BuildNativeDependenciesAsync( + nativeContext, + contribution, + cancellationToken + ); using ProductNativeBuildResult nativeOwnership = native.products; Console.WriteLine("[inno-bindings] Build the complete InnoEngine solution."); @@ -300,7 +304,7 @@ CancellationToken cancellationToken private static IReadOnlyList DiscoverTestProjects(string repositoryRoot) { string nativeTestsRoot = Path.Combine(repositoryRoot, "backends"); - var projects = Directory.EnumerateFiles(nativeTestsRoot, "*.csproj", SearchOption.AllDirectories) + List projects = Directory.EnumerateFiles(nativeTestsRoot, "*.csproj", SearchOption.AllDirectories) .Where(static path => ( Path.GetFileNameWithoutExtension(path).StartsWith("Inno.Native.", StringComparison.Ordinal) && path.Contains(Path.DirectorySeparatorChar + "tests" + Path.DirectorySeparatorChar, StringComparison.Ordinal) diff --git a/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs b/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs index 60305fdf7..7e31072e2 100644 --- a/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs +++ b/build/cli/Inno.Build.Cli/NativeVerificationOptions.cs @@ -73,7 +73,7 @@ internal static NativeVerificationOptions Parse(IReadOnlyList args) } string[] knownKeys = ["engine-root", "configuration", "dotnet", "target"]; string? unknownKey = values.Keys.FirstOrDefault(key => !knownKeys.Contains(key, StringComparer.Ordinal)); - if (unknownKey != null) + if (unknownKey is not null) { throw new ArgumentException($"Unknown argument '--{unknownKey}'.{Environment.NewLine}{usage}"); } diff --git a/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs b/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs index f1907369e..3541dd21c 100644 --- a/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs +++ b/build/cli/Inno.Build.Cli/ProjectBuildWorkflow.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; @@ -72,7 +73,7 @@ CancellationToken cancellationToken ).ConfigureAwait(false); NativeBuildProduct product = products.Single(); string extension = context.host.services.executableExtension; - var executables = Enum.GetValues().ToDictionary( + Dictionary executables = Enum.GetValues().ToDictionary( static tool => tool, tool => product.files.Single(file => Path.GetFileName(file) == tool.ToString().ToLowerInvariant() + extension) ); diff --git a/build/composition/Inno.Build.Composition/BuildDistribution.cs b/build/composition/Inno.Build.Composition/BuildDistribution.cs index f3a7e956e..3e144df82 100644 --- a/build/composition/Inno.Build.Composition/BuildDistribution.cs +++ b/build/composition/Inno.Build.Composition/BuildDistribution.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using Inno.Assets.Pipeline; @@ -68,12 +69,12 @@ public BuildDistribution( { throw new ArgumentException("Platform target identities must be unique.", nameof(games)); } - var native = m_platforms.ToDictionary( + Dictionary native = m_platforms.ToDictionary( static platform => platform.descriptor.id.value, static platform => platform.toolchainProvider, StringComparer.Ordinal ); - var products = m_platforms.ToDictionary( + Dictionary> products = m_platforms.ToDictionary( static platform => platform.descriptor.id.value, static platform => platform.nativeProducts, StringComparer.Ordinal @@ -93,12 +94,14 @@ public BuildDistribution( m_bindingGenerators.Add(contribution.descriptor.id.value, contribution.bindingGenerator); } } - m_nativeProducts = new System.Collections.ObjectModel.ReadOnlyDictionary>(products); - m_nativeToolchains = new System.Collections.ObjectModel.ReadOnlyDictionary(native); - availableTargets = Array.AsReadOnly(m_targetIds.OrderBy(static id => id.value, StringComparer.Ordinal).ToArray()); - managedDeployments = new ManagedDeploymentCatalog(managedCompilers); - supportPacks = new PlayerSupportPackPublisher(m_platforms.Select(static contribution => contribution.supportPackSource).ToArray()); + m_nativeToolchains = new ReadOnlyDictionary(native); + this.availableTargets = Array.AsReadOnly(m_targetIds.OrderBy(static id => id.value, StringComparer.Ordinal).ToArray()); + this.managedDeployments = new ManagedDeploymentCatalog(managedCompilers); + this.supportPacks = new PlayerSupportPackPublisher( + m_platforms.Select(static contribution => contribution.supportPackSource).ToArray() + ); } /// diff --git a/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs b/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs index c07c7871b..0a22eaa58 100644 --- a/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs +++ b/build/managed/Inno.Build.Managed/ManagedDeploymentCatalog.cs @@ -32,7 +32,7 @@ compiler is null throw new ArgumentException("Managed providers require unique valid identities.", nameof(compilers)); } m_compilers = compilers.ToDictionary(static compiler => compiler.id); - availableDeployments = Array.AsReadOnly( + this.availableDeployments = Array.AsReadOnly( compilers.Select(static compiler => compiler.id) .OrderBy(static id => id.value, StringComparer.Ordinal) .ToArray() diff --git a/build/managed/Inno.Build.Managed/ManagedDeploymentId.cs b/build/managed/Inno.Build.Managed/ManagedDeploymentId.cs index a971b6221..aa84a8636 100644 --- a/build/managed/Inno.Build.Managed/ManagedDeploymentId.cs +++ b/build/managed/Inno.Build.Managed/ManagedDeploymentId.cs @@ -54,6 +54,6 @@ public ManagedDeploymentId(string value) /// public string value { get; } - /// + /// public override string ToString() => value ?? string.Empty; } diff --git a/build/pipeline/Inno.Build/BuildPipeline.cs b/build/pipeline/Inno.Build/BuildPipeline.cs index 8b8926909..d546bb22d 100644 --- a/build/pipeline/Inno.Build/BuildPipeline.cs +++ b/build/pipeline/Inno.Build/BuildPipeline.cs @@ -32,15 +32,9 @@ public sealed class BuildPipeline /// /// Creates a build pipeline from installed Player Support Packs and platform packagers. /// - /// - /// The directory containing one child directory per . - /// /// /// The active authoring asset pipeline captured by builds. /// - /// - /// The host-wide admission gate that remains pinned until the build snapshot is released. - /// /// /// The active Plugin environment captured by builds. /// @@ -50,9 +44,15 @@ public sealed class BuildPipeline /// /// The serialization registry used to pin and encode the build snapshot. /// + /// + /// The host-wide admission gate that remains pinned until the build snapshot is released. + /// /// /// The project compiler used to produce a fresh runtime-only assembly generation for each game build. /// + /// + /// The directory containing one child directory per . + /// /// /// The complete set of replaceable platform package implementations available to this host. /// @@ -232,12 +232,6 @@ public async ValueTask EnsurePlayerSupportPackAsync( /// /// Builds and installs one complete source-free game deployment with rollback protection. /// - /// - /// Prepare current packs with EnsurePlayerSupportPackAsync before invoking this method on the - /// authoring owner's thread. The synchronous snapshot phase never waits for asynchronous provisioning. - /// Coordinate readers and writers of the output directory during its two installation moves. - /// Post-commit backup, staging and progress observer failures are warnings on the successful result. - /// /// /// The exact profile, destination, and activated runtime compilation generation. /// @@ -265,6 +259,12 @@ public async ValueTask EnsurePlayerSupportPackAsync( /// /// Output installation and restoration both fail; the previous tree remains at the reported backup path. /// + /// + /// Prepare current packs with EnsurePlayerSupportPackAsync before invoking this method on the + /// authoring owner's thread. The synchronous snapshot phase never waits for asynchronous provisioning. + /// Coordinate readers and writers of the output directory during its two installation moves. + /// Post-commit backup, staging and progress observer failures are warnings on the successful result. + /// public async ValueTask BuildGameAsync( GameBuildRequest request, IProgress? progress = null, diff --git a/build/pipeline/Inno.Build/BuildSettingsStore.cs b/build/pipeline/Inno.Build/BuildSettingsStore.cs index a0320e893..4d9b1ac25 100644 --- a/build/pipeline/Inno.Build/BuildSettingsStore.cs +++ b/build/pipeline/Inno.Build/BuildSettingsStore.cs @@ -168,14 +168,9 @@ public void RestoreDocument(ReadOnlySpan document) public void ValidateDocument(ReadOnlySpan document) => _ = Deserialize(document); private BuildSettings LoadLocked() - { - return m_documents.exists - ? m_documents.LoadRequired() - : m_defaultSettings.Copy(); - } + => m_documents.exists + ? m_documents.LoadRequired() + : m_defaultSettings.Copy(); - private BuildSettings Deserialize(ReadOnlySpan document) - { - return m_documents.Deserialize(document); - } + private BuildSettings Deserialize(ReadOnlySpan document) => m_documents.Deserialize(document); } diff --git a/build/pipeline/Inno.Build/Content/ContentPackWriter.cs b/build/pipeline/Inno.Build/Content/ContentPackWriter.cs index 5a6429b85..9e6679eb9 100644 --- a/build/pipeline/Inno.Build/Content/ContentPackWriter.cs +++ b/build/pipeline/Inno.Build/Content/ContentPackWriter.cs @@ -32,7 +32,7 @@ CancellationToken cancellationToken _ = new ContentPackIndex(keys.Select(static key => new ContentEntry(key, 0, new string('0', 64)))); try { - await using (FileStream stream = new( + await using (var stream = new FileStream( temporary, FileMode.CreateNew, FileAccess.Write, @@ -49,7 +49,7 @@ CancellationToken cancellationToken ZipArchiveEntry entry = archive.CreateEntry(keys[index].value!, CompressionLevel.Optimal); entry.LastWriteTime = S_ARCHIVE_TIME; await using Stream output = entry.Open(); - await using FileStream input = new( + await using var input = new FileStream( files[index], FileMode.Open, FileAccess.Read, @@ -76,7 +76,7 @@ CancellationToken cancellationToken ArrayPool.Shared.Return(buffer); } } - ContentPackIndex inventory = new(entries); + var inventory = new ContentPackIndex(entries); ZipArchiveEntry indexEntry = archive.CreateEntry(ContentPackIndex.C_INDEX_KEY, CompressionLevel.Optimal); indexEntry.LastWriteTime = S_ARCHIVE_TIME; await using Stream indexOutput = indexEntry.Open(); @@ -87,7 +87,7 @@ await indexOutput.WriteAsync( } cancellationToken.ThrowIfCancellationRequested(); string contentHash; - await using (FileStream input = new( + await using (var input = new FileStream( temporary, FileMode.Open, FileAccess.Read, diff --git a/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs b/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs index 081a6c6a3..b02eae57c 100644 --- a/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs +++ b/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs @@ -106,7 +106,7 @@ CancellationToken cancellationToken cancellationToken ).ConfigureAwait(false); string staging = stagingOwner.directory; - using var stagingCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + using CancellationTokenSource stagingCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); Task? assetExportTask = null; Task? targetContentTask = null; var publicationDiagnostics = new List(); @@ -418,7 +418,7 @@ out AssemblyScope scope }) .Where(static candidate => candidate.assemblies.Length > 0) .ToArray(); - var includedNames = selected + HashSet includedNames = selected .Select(static candidate => candidate.request.moduleName) .ToHashSet(StringComparer.Ordinal); GameRuntimeModule[] candidates = selected.Select(candidate => new GameRuntimeModule @@ -434,7 +434,7 @@ out AssemblyScope scope .Where(includedNames.Contains) .ToArray() }).ToArray(); - var byName = candidates.ToDictionary(static module => module.name, StringComparer.Ordinal); + Dictionary byName = candidates.ToDictionary(static module => module.name, StringComparer.Ordinal); var visiting = new HashSet(StringComparer.Ordinal); var visited = new HashSet(StringComparer.Ordinal); var ordered = new List(candidates.Length); @@ -488,7 +488,7 @@ long expectedSettingsRevision private void ValidateOutputRoot(string outputRoot) { - var protectedRoots = m_assets.sourceMounts + List protectedRoots = m_assets.sourceMounts .Select(static mount => mount.rootPath) .Append(m_assets.libraryRoot) .ToList(); diff --git a/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs b/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs index 196dca1f9..6604550dc 100644 --- a/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs +++ b/build/pipeline/Inno.Build/Game/PlayerCodeCompositionWriter.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -81,7 +82,7 @@ private static string Quote(string value) } else if (char.IsControl(character)) { - literal.Append("\\u").Append(((int)character).ToString("x4", System.Globalization.CultureInfo.InvariantCulture)); + literal.Append("\\u").Append(((int)character).ToString("x4", CultureInfo.InvariantCulture)); } else { diff --git a/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs b/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs index b3ae5f298..b4f9b72ba 100644 --- a/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs +++ b/build/pipeline/Inno.Build/Pipeline/BuildFileSystem.cs @@ -65,7 +65,7 @@ internal static async ValueTask CopyFileAsync( string destination, CancellationToken cancellationToken ) { - await using FileStream input = new( + await using var input = new FileStream( source, FileMode.Open, FileAccess.Read, @@ -73,7 +73,7 @@ CancellationToken cancellationToken 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan ); - await using FileStream output = new( + await using var output = new FileStream( destination, FileMode.CreateNew, FileAccess.Write, diff --git a/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs b/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs index ebbc52261..494fd2082 100644 --- a/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs +++ b/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers.Binary; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; @@ -130,6 +131,12 @@ public async ValueTask SelectAsync( /// /// The platform and architecture identity of the required Support Pack. /// + /// + /// The target-owned validator for runtime or linker inputs. + /// + /// + /// Cancels ownership acquisition or complete content validation before returning a lease. + /// /// /// Reading ownership of the complete pack; dispose it after its final consumer finishes. /// @@ -139,12 +146,6 @@ public async ValueTask SelectAsync( /// /// Thrown when the pack is empty, contains build-time payload, or lacks its Player executable or native runtimes. /// - /// - /// The target-owned validator for runtime or linker inputs. - /// - /// - /// Cancels ownership acquisition or complete content validation before returning a lease. - /// /// /// Acquisition or validation was canceled; no reading ownership is transferred. /// @@ -430,7 +431,7 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(directory, file).Replace('\\', '/'); byte[] path = Encoding.UTF8.GetBytes(relative); - System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(length, path.Length); + BinaryPrimitives.WriteInt32LittleEndian(length, path.Length); hash.AppendData(length); hash.AppendData(path); using FileStream input = File.OpenRead(file); diff --git a/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs b/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs index 216f3ddd1..6d99cb1c0 100644 --- a/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs +++ b/build/pipeline/Inno.Build/Plugins/PluginPackageBuilder.cs @@ -67,7 +67,7 @@ CancellationToken cancellationToken string temporary = destination + ".staging-" + Guid.NewGuid().ToString("N"); try { - await using (FileStream stream = new( + await using (var stream = new FileStream( temporary, FileMode.CreateNew, FileAccess.Write, @@ -120,7 +120,7 @@ await WriteBytesAsync(nested, "Plugin.inno", dependency.manifest, cancellationTo EnsurePlanUnchanged(plan); cancellationToken.ThrowIfCancellationRequested(); string contentHash; - await using (FileStream stream = new( + await using (var stream = new FileStream( temporary, FileMode.Open, FileAccess.Read, @@ -157,7 +157,7 @@ private PluginPackagePlan CapturePlan(PluginBuildRequest request) PluginCandidate[] installedPlugins = m_plugins.activePlugins.ToArray(); ValidateDependencyGraph(installedPlugins); var selectedIds = new HashSet(StringComparer.Ordinal); - var installedById = installedPlugins.ToDictionary( + Dictionary installedById = installedPlugins.ToDictionary( static plugin => plugin.manifest.pluginId, StringComparer.Ordinal ); @@ -297,7 +297,7 @@ CancellationToken cancellationToken ZipArchiveEntry entry = archive.CreateEntry(source.archivePath, CompressionLevel.Optimal); entry.LastWriteTime = S_ARCHIVE_TIME; await using Stream output = entry.Open(); - await using FileStream input = new( + await using var input = new FileStream( source.sourcePath, FileMode.Open, FileAccess.Read, @@ -397,7 +397,7 @@ private static IEnumerable CollectDirectories(IEnumerable files) private void ValidateDestination(string destination) { - var protectedRoots = m_assets.sourceMounts + List protectedRoots = m_assets.sourceMounts .Select(static mount => mount.rootPath) .Append(m_assets.libraryRoot) .ToList(); diff --git a/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs b/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs index c5c38fb8b..023d91783 100644 --- a/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs +++ b/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs @@ -41,7 +41,7 @@ string projectRoot m_projectRoot = Path.GetFullPath(projectRoot); } - /// + /// public ScriptCompilationInputs Capture(CancellationToken cancellationToken = default) => CaptureAsync(cancellationToken).GetAwaiter().GetResult(); diff --git a/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs b/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs index cd78742dd..9e61dc407 100644 --- a/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs +++ b/build/pipeline/Inno.Build/Snapshots/BuildSnapshotFingerprint.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -20,7 +21,7 @@ internal static async ValueTask ComputeAsync( CancellationToken cancellationToken ) { using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - Append(hash, assetRevision.ToString(System.Globalization.CultureInfo.InvariantCulture)); + Append(hash, assetRevision.ToString(CultureInfo.InvariantCulture)); hash.AppendData(projectSettings.Span); foreach (PluginCandidate plugin in plugins) { @@ -31,7 +32,7 @@ CancellationToken cancellationToken { cancellationToken.ThrowIfCancellationRequested(); Append(hash, Path.GetFileName(assembly)); - await using FileStream stream = new( + await using var stream = new FileStream( assembly, FileMode.Open, FileAccess.Read, diff --git a/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs b/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs index 370679a3f..b957c9761 100644 --- a/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs +++ b/build/products/Inno.Build.Products.Standard/StandardNativeComponents.cs @@ -20,9 +20,6 @@ public static class StandardNativeComponents /// /// Composes the standard Player's reusable native components with explicit deployment policies. /// - /// - /// A fresh immutable Player plan without resolving tools or touching source files. - /// /// /// The selected integration-owned BGFX SDK invocation for standalone component builds. /// @@ -32,6 +29,9 @@ public static class StandardNativeComponents /// /// The platform-owned destination of each component output, or null to exclude it. /// + /// + /// A fresh immutable Player plan without resolving tools or touching source files. + /// public static ProductNativeBuildPlan CreatePlayer( BgfxNativeBuildProfile profile, Func options, @@ -41,9 +41,6 @@ public static ProductNativeBuildPlan CreatePlayer( /// /// Selects only the offline graphics compiler component needed for shader publication. /// - /// - /// An immutable tool product without runtime or Editor presentation dependencies. - /// /// /// The selected integration-owned BGFX SDK invocation for standalone component builds. /// @@ -53,6 +50,9 @@ public static ProductNativeBuildPlan CreatePlayer( /// /// The platform-owned destination of each component output, or null to exclude it. /// + /// + /// An immutable tool product without runtime or Editor presentation dependencies. + /// public static ProductNativeBuildPlan CreateShaderTools( BgfxNativeBuildProfile profile, Func options, @@ -62,9 +62,6 @@ public static ProductNativeBuildPlan CreateShaderTools( /// /// Composes the shared runtime closure and the Editor's presentation and authoring tools. /// - /// - /// A fresh immutable Editor plan with the ImGuizmo dependency declared explicitly. - /// /// /// The selected integration-owned BGFX SDK invocation for standalone component builds. /// @@ -74,6 +71,9 @@ public static ProductNativeBuildPlan CreateShaderTools( /// /// The platform-owned destination of each component output, or null to exclude it. /// + /// + /// A fresh immutable Editor plan with the ImGuizmo dependency declared explicitly. + /// public static ProductNativeBuildPlan CreateEditor( BgfxNativeBuildProfile profile, Func options, @@ -128,15 +128,15 @@ public static ProductNativeBuildPlan CreateEditor( /// /// Declares the real static component closure consumed by an explicit aggregate executor. /// - /// - /// A Player closure with static recipes and no unused standalone producers. - /// /// /// The platform-owned configuration for each named component. /// /// /// The platform-owned destination of each component output, or null to exclude it. /// + /// + /// A Player closure with static recipes and no unused standalone producers. + /// public static ProductNativeBuildPlan CreateStaticPlayer( Func options, Func layout diff --git a/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs b/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs index 64a25fc81..99e52c5ef 100644 --- a/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs +++ b/build/products/Inno.Build.Products.Standard/StandardNativeDeployment.cs @@ -97,7 +97,7 @@ private sealed class DeploymentValidator( string extension ) : IPlayerSupportPackValidator { - /// + /// public void Validate(string directory) { string root = PathBoundary.Resolve(directory, "native"); diff --git a/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs b/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs index 753efa160..64c279bb1 100644 --- a/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs +++ b/build/products/Inno.Build.Products.Standard/StandardSupportPackRequirements.cs @@ -54,12 +54,12 @@ string extension /// /// The exact platform target. /// - /// - /// Requirements matching the plan's actual component closure. - /// /// /// The explicit platform archive naming plan. /// + /// + /// Requirements matching the plan's actual component closure. + /// public static PlayerSupportPackRequirements CreateStatic( ProductNativeBuildPlan plan, BuildTargetId target, diff --git a/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs b/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs index d268aba01..9665f6746 100644 --- a/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs +++ b/build/support/Inno.Build.SupportPacks.Core/FilePlayerSupportPackPreparation.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Inno.Build; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.SupportPacks; @@ -55,15 +56,15 @@ public sealed class FilePlayerSupportPackPreparation /// /// The frozen product component closure. /// + /// + /// The product-selected native execution strategy. + /// /// /// The SDK provider for the explicit native target. /// /// /// The declared machine executing tools. /// - /// - /// The product-selected native execution strategy. - /// /// /// The borrowed generation service used by the frozen Native operation. /// @@ -141,13 +142,13 @@ CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); cancellationToken.ThrowIfCancellationRequested(); - string project = Inno.Core.IO.PathBoundary.Resolve(context.engineRoot, m_productProject); - string template = Inno.Core.IO.PathBoundary.Resolve(context.engineRoot, m_templateFile); + string project = PathBoundary.Resolve(context.engineRoot, m_productProject); + string template = PathBoundary.Resolve(context.engineRoot, m_templateFile); if (!File.Exists(template)) { throw new FileNotFoundException("The Player publication template is absent.", template); } - var native = new NativeBuildContext(context.engineRoot, ToolchainLayout.C_RELEASE_CONFIGURATION) + NativeBuildContext native = new NativeBuildContext(context.engineRoot, ToolchainLayout.C_RELEASE_CONFIGURATION) .WithBindingGenerator(m_bindingGenerator); if (context.nativeDependencies is null) { @@ -286,7 +287,7 @@ await ToolchainEnvironment.RunAsync( await CopyNativeRuntimeAsync(products, context.stagingDirectory, cancellationToken).ConfigureAwait(false); string link = Path.Combine(context.stagingDirectory, "PlayerLink"); Directory.CreateDirectory(link); - File.Copy(Inno.Core.IO.PathBoundary.Resolve(context.engineRoot, m_templateFile), Path.Combine(link, "Player.csproj")); + File.Copy(PathBoundary.Resolve(context.engineRoot, m_templateFile), Path.Combine(link, "Player.csproj")); await PlayerSupportPackFiles.CopyPlayerSourcesAsync( context, project, @@ -347,7 +348,7 @@ CancellationToken cancellationToken string destination = Path.Combine(playerDirectory, "native", Path.GetRelativePath(nativeRoot, input)); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); await using FileStream source = File.OpenRead(input); - await using FileStream output = new(destination, FileMode.CreateNew); + await using var output = new FileStream(destination, FileMode.CreateNew); await source.CopyToAsync(output, cancellationToken).ConfigureAwait(false); if (!OperatingSystem.IsWindows()) { @@ -365,10 +366,10 @@ private sealed class PreparationPlan( PlayerSupportPackPreparationIdentity identity ) : PlayerSupportPackPlan(owner.target, identity.fingerprint) { - /// + /// public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => identity.VerifyAsync(cancellationToken); - /// + /// public override ValueTask PrepareAsync( string stagingDirectory, CancellationToken cancellationToken diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs index 9ecb50f5c..1da2a8960 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlan.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Inno.Build; @@ -28,7 +29,7 @@ string preparationIdentity ) { ArgumentException.ThrowIfNullOrWhiteSpace(target.value); if (preparationIdentity is null || preparationIdentity.Length != 64 - || System.Linq.Enumerable.Any(preparationIdentity, static character => !char.IsAsciiHexDigitLower(character)) + || Enumerable.Any(preparationIdentity, static character => !char.IsAsciiHexDigitLower(character)) ) { throw new ArgumentException("A Support Pack requires a complete lowercase source input identity.", nameof(preparationIdentity)); } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlanningContext.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlanningContext.cs index f4584fc33..996921219 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlanningContext.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPlanningContext.cs @@ -16,12 +16,12 @@ public sealed class PlayerSupportPackPlanningContext /// /// The explicitly selected managed host executable. /// - /// - /// A required input is blank. - /// /// /// An exact dependency selection; null permits local source preparation. /// + /// + /// A required input is blank. + /// public PlayerSupportPackPlanningContext( string engineRoot, string dotnetHost, diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs index ca65b01ff..208045925 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIdentity.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Threading; @@ -98,7 +99,7 @@ public static async ValueTask CaptureAsync ArgumentNullException.ThrowIfNull(properties); ArgumentNullException.ThrowIfNull(preparationInputs); ArgumentException.ThrowIfNullOrWhiteSpace(project); - var frozen = new System.Collections.ObjectModel.ReadOnlyDictionary( + var frozen = new ReadOnlyDictionary( properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase) ); var result = new PlayerSupportPackPreparationIdentity( diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs index de7760094..06dbc247b 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPreparationIndex.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Linq; using System.Text; using Inno.Build.Toolchains; using Inno.Core.IO; @@ -57,5 +58,5 @@ string preparation private static bool IsIdentity(string identity) => identity.Length == 64 - && !System.Linq.Enumerable.Any(identity, static character => !char.IsAsciiHexDigitLower(character)); + && !Enumerable.Any(identity, static character => !char.IsAsciiHexDigitLower(character)); } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs index 73ba18210..ba160a927 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs @@ -58,13 +58,12 @@ public PlayerSupportPackPublisher(IEnumerable sources) /// /// Cancels preparation before directory installation begins. /// + /// + /// An explicit native selection disabling third-party production, or null for local source preparation. + /// /// /// Reading ownership of the selected Pack and any post-commit diagnostics. Dispose after consuming its files. /// - /// - /// Writers targeting the same pack share an exclusive, cancelable preparation lease. - /// Publication atomically selects a fingerprint directory; previous generations remain valid for readers. - /// /// /// A required path is blank or the target has no registered source. /// @@ -80,9 +79,10 @@ public PlayerSupportPackPublisher(IEnumerable sources) /// /// Preparation was canceled; the installed pack is unchanged. /// - /// - /// An explicit native selection disabling third-party production, or null for local source preparation. - /// + /// + /// Writers targeting the same pack share an exclusive, cancelable preparation lease. + /// Publication atomically selects a fingerprint directory; previous generations remain valid for readers. + /// public async ValueTask PublishAsync( string engineRoot, string outputRoot, diff --git a/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs b/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs index c10a6c22c..fdc054bd0 100644 --- a/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs +++ b/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs @@ -23,9 +23,6 @@ public sealed class SourcePlayerSupportPackProvisioner : IPlayerSupportPackProvi /// /// The directory containing InnoEngine.sln and the Player project. /// - /// - /// The directory is not an engine checkout. - /// /// /// The publisher containing the host-selected platform sources. /// @@ -38,6 +35,9 @@ public sealed class SourcePlayerSupportPackProvisioner : IPlayerSupportPackProvi /// /// An absolute dependency selection disabling third-party production, or null for local source preparation. /// + /// + /// The directory is not an engine checkout. + /// public SourcePlayerSupportPackProvisioner( string engineRoot, PlayerSupportPackPublisher publisher, @@ -70,12 +70,6 @@ public SourcePlayerSupportPackProvisioner( /// /// The host binary directory from which to search upward. /// - /// - /// A source provisioner, or null when the host is a source-independent distribution. - /// - /// - /// An explicit INNO_ENGINE_ROOT does not identify a complete engine checkout. - /// /// /// The publisher containing the host-selected platform sources. /// @@ -88,6 +82,12 @@ public SourcePlayerSupportPackProvisioner( /// /// The explicit consume-only selection retained by the returned provisioner, or null for local source preparation. /// + /// + /// A source provisioner, or null when the host is a source-independent distribution. + /// + /// + /// An explicit INNO_ENGINE_ROOT does not identify a complete engine checkout. + /// public static SourcePlayerSupportPackProvisioner? TryCreateForHost( string startDirectory, PlayerSupportPackPublisher publisher, diff --git a/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs b/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs index 9eddcca00..e6f327a99 100644 --- a/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/BuildTaskRuntimeTask.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading; using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; using Inno.Build.Toolchains; using Inno.Core.IO; @@ -13,7 +14,7 @@ namespace Inno.Build.TaskHosting; /// /// Coordinates shared task-runtime compilation before immutable publication and private loading. /// -public sealed class BuildTaskRuntimeTask : Microsoft.Build.Utilities.Task, ICancelableTask +public sealed class BuildTaskRuntimeTask : Task, ICancelableTask { private readonly object m_cancellationGate = new(); private readonly CancellationTokenSource m_cancellation = new(); @@ -95,7 +96,10 @@ public override bool Execute() // MSBuild's API applies undefinitions to the final request. Explicit task // properties must survive removal of identically named parent globals. removed = removed.Where(name => !properties.Contains(name)).ToArray(); - var workspaces = new BuildCachePublisher(Path.GetDirectoryName(artifacts)!, BuildCacheArtifactRole.ReusableWorkspace); + var workspaces = new BuildCachePublisher( + Path.GetDirectoryName(artifacts)!, + BuildCacheArtifactRole.ReusableWorkspace + ); ownerUses = AcquireOwnerUses( [ new(cache, BuildCacheArtifactRole.ImmutableArtifact), @@ -174,7 +178,7 @@ public override bool Execute() )) ) { var inputProperties = new Hashtable(StringComparer.OrdinalIgnoreCase); - foreach (var property in inputRestore.properties) + foreach (KeyValuePair property in inputRestore.properties) { inputProperties[property.Key] = property.Value; } @@ -340,10 +344,10 @@ private IDictionary FreezeProperties( string artifacts, IReadOnlyList removed ) { - Hashtable properties = new(StringComparer.OrdinalIgnoreCase); + var properties = new Hashtable(StringComparer.OrdinalIgnoreCase); if (BuildEngine is IBuildEngine6 engine) { - foreach (var property in engine.GetGlobalProperties()) + foreach (KeyValuePair property in engine.GetGlobalProperties()) { if (!removed.Contains(property.Key, StringComparer.OrdinalIgnoreCase)) { @@ -375,10 +379,12 @@ IReadOnlyList removed private static IDictionary RestoreProperties(IDictionary compilationProperties) { - var properties = new Hashtable(compilationProperties, StringComparer.OrdinalIgnoreCase); - // NuGet restore must not populate the build engine's compilation evaluation cache - // with package content items from the imports it is about to replace. - properties["ExcludeRestorePackageImports"] = "true"; + var properties = new Hashtable(compilationProperties, StringComparer.OrdinalIgnoreCase) + { + // NuGet restore must not populate the build engine's compilation evaluation cache + // with package content items from the imports it is about to replace. + ["ExcludeRestorePackageImports"] = "true" + }; return properties; } diff --git a/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs b/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs index 3bc08b9fb..0627efa3c 100644 --- a/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/PublishTaskHostTask.cs @@ -7,6 +7,7 @@ using System.Text; using System.Threading; using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; using Inno.Build.Toolchains; using Inno.Core.IO; @@ -16,7 +17,7 @@ namespace Inno.Build.TaskHosting; /// Publishes one immutable task runtime per content identity before a build loads its private closure. /// This bootstrap depends only on filesystem primitives and never loads the task runtime being built. /// -public sealed partial class PublishTaskHostTask : Microsoft.Build.Utilities.Task, ICancelableTask +public sealed partial class PublishTaskHostTask : Task, ICancelableTask { private readonly object m_cancellationGate = new(); private readonly CancellationTokenSource m_cancellation = new(); diff --git a/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs b/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs index 1268d4750..6a7ec45e6 100644 --- a/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/RestoreOwnedProjectTask.cs @@ -4,7 +4,9 @@ using System.IO; using System.Linq; using System.Threading; +using Microsoft.Build.Evaluation; using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; using Inno.Core.IO; namespace Inno.Build.TaskHosting; @@ -13,7 +15,7 @@ namespace Inno.Build.TaskHosting; /// Coordinates SDK restore writes for explicitly selected project closures. /// Parent solution entry points are excluded from these owned restores. /// -public sealed class RestoreOwnedProjectTask : Microsoft.Build.Utilities.Task, ICancelableTask +public sealed class RestoreOwnedProjectTask : Task, ICancelableTask { private readonly object m_gate = new(); private readonly CancellationTokenSource m_cancellation = new(); @@ -158,7 +160,7 @@ IDictionary properties { throw new ArgumentException("Restore properties require explicit name=value declarations."); } - properties[declaration[..separator]] = Microsoft.Build.Evaluation.ProjectCollection.Unescape(declaration[(separator + 1)..]); + properties[declaration[..separator]] = ProjectCollection.Unescape(declaration[(separator + 1)..]); } } } diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs index 5018a18f0..836560801 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeBootstrapOwner.cs @@ -5,12 +5,14 @@ using System.Threading.Tasks; using Microsoft.Build.Framework; +using BuildTask = Microsoft.Build.Utilities.Task; + namespace Inno.Build.TaskHosting; /// /// Claims bootstrap storage before SDK compilation without depending on the full task runtime. /// -public sealed class TaskRuntimeBootstrapOwner : Microsoft.Build.Utilities.Task +public sealed class TaskRuntimeBootstrapOwner : BuildTask { /// /// Gets or sets the absolute publisher root managed by the standard distribution. @@ -59,7 +61,7 @@ public override bool Execute() null )!; object pending = create.Invoke(null, [Root, Identity, CancellationToken.None])!; - var operation = (Task)pending + Task operation = (Task)pending .GetType() .GetMethod("AsTask", BindingFlags.Public | BindingFlags.Instance)! .Invoke(pending, null)!; diff --git a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs index a44365422..f9e5d7193 100644 --- a/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs +++ b/build/tasks/Inno.Build.TaskHosting/TaskRuntimeRequestKey.cs @@ -1,12 +1,14 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.Build.Evaluation; +using Microsoft.Build.Execution; using Microsoft.Build.Graph; namespace Inno.Build.TaskHosting; @@ -20,7 +22,7 @@ internal static TaskRuntimeRequestSnapshot Capture( IDictionary properties, CancellationToken cancellation ) { - var globals = properties.Cast().ToDictionary( + Dictionary globals = properties.Cast().ToDictionary( static entry => (string)entry.Key, static entry => (string)entry.Value!, StringComparer.OrdinalIgnoreCase @@ -39,14 +41,17 @@ CancellationToken cancellation .OrderBy(static entry => entry.Key, StringComparer.OrdinalIgnoreCase) .Select(static entry => entry.Key + "=" + entry.Value) ); - foreach (var node in graph.ProjectNodes.OrderBy(static node => node.ProjectInstance.FullPath, paths)) + foreach (ProjectGraphNode node in graph.ProjectNodes.OrderBy(static node => node.ProjectInstance.FullPath, paths)) { cancellation.ThrowIfCancellationRequested(); - var instance = node.ProjectInstance; - foreach (var item in instance.GetItems("InnoBuildInputRestoreProject")) + ProjectInstance instance = node.ProjectInstance; + foreach (ProjectItemInstance item in instance.GetItems("InnoBuildInputRestoreProject")) { string restoreProject = Path.GetFullPath(item.EvaluatedInclude, Path.GetDirectoryName(instance.FullPath)!); - var restoreProperties = new Dictionary(instance.GlobalProperties, StringComparer.OrdinalIgnoreCase); + var restoreProperties = new Dictionary( + instance.GlobalProperties, + StringComparer.OrdinalIgnoreCase + ); string[] removedProperties = item.GetMetadataValue("GlobalPropertiesToRemove") .Split(';', StringSplitOptions.RemoveEmptyEntries); foreach (string removedProperty in removedProperties) @@ -64,11 +69,7 @@ CancellationToken cancellation restoreProperties[declaration[..separator]] = ProjectCollection.Unescape(declaration[(separator + 1)..]); } restoreRequests.Add( - new( - restoreProject, - new System.Collections.ObjectModel.ReadOnlyDictionary(restoreProperties), - removedProperties - ) + new(restoreProject, new ReadOnlyDictionary(restoreProperties), removedProperties) ); } inputs.Add(instance.FullPath); @@ -99,7 +100,7 @@ CancellationToken cancellation }) { declarations.Add(instance.FullPath + "|" + property + "=" + instance.GetPropertyValue(property)); } - foreach (var item in instance.Items) + foreach (ProjectItemInstance item in instance.Items) { bool source = item.ItemType is "Compile" or "EmbeddedResource" or "Analyzer" or "AdditionalFiles" or "EditorConfigFiles" or "GlobalAnalyzerConfigFiles" or "AdditionalCompileInputs"; @@ -155,7 +156,7 @@ CancellationToken cancellation inputs.Add(path); } } - using var digest = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash digest = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); var hashes = new Dictionary(paths); foreach (string declaration in declarations) { @@ -173,7 +174,7 @@ CancellationToken cancellation return new TaskRuntimeRequestSnapshot( Convert.ToHexString(digest.GetHashAndReset()), needsRestore, - new System.Collections.ObjectModel.ReadOnlyDictionary(hashes), + new ReadOnlyDictionary(hashes), declarations.AsReadOnly(), restoreRequests.AsReadOnly() ); diff --git a/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs b/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs index b56fb0b77..8e0e14f93 100644 --- a/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs +++ b/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs @@ -83,7 +83,7 @@ public sealed class CompileShaderTask : BuildTask, ICancelableTask /// public override bool Execute() { - using CancellationTokenSource cancellation = new(); + using var cancellation = new CancellationTokenSource(); lock (m_gate) { m_cancellation = cancellation; @@ -94,7 +94,7 @@ public override bool Execute() } try { - var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); + BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); BgfxShaderTargetProfile platform = StandardBuildDistribution.Create(execution).ResolveShaderTarget(new BuildTargetId(Target)); if (!GraphicsApi.TryParse(Renderer, out GraphicsApi renderer)) { @@ -141,8 +141,8 @@ private ToolRunner PrepareTools( out string compilerFingerprint, out BuildArtifactReadLease reading ) { - NativeBuildContext context = new(EngineRoot, "release"); - var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); + var context = new NativeBuildContext(EngineRoot, "release"); + BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); context = context.WithBindingGenerator(StandardBuildDistribution.Create(execution).build.ResolveBindingGenerator(ToolTarget)); string cacheKey = "Inno.Build.ShaderTools|" + context.engineRoot @@ -175,7 +175,7 @@ out BuildArtifactReadLease reading .GetResult(); if (NativeDependencyManifestPath.Length != 0) { - var selected = NativeDependencyManifest.SelectAsync( + IReadOnlyList selected = NativeDependencyManifest.SelectAsync( EngineRoot, NativeDependencyManifestPath, ToolTarget, @@ -193,7 +193,7 @@ out BuildArtifactReadLease reading } if (record is null) { - var distribution = StandardBuildDistribution.Create(execution).build; + BuildDistribution distribution = StandardBuildDistribution.Create(execution).build; if (NativeDependencyManifestPath.Length == 0) { context = context.WithToolchain( diff --git a/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs b/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs index 53f639d55..d2f102f29 100644 --- a/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs +++ b/build/tasks/Inno.Build.Tasks/GenerateBindingsTask.cs @@ -201,7 +201,10 @@ public override bool Execute() plan, cancellation ).GetAwaiter().GetResult(); - NativeBindingGenerationDescriptor imported = products.bindingGenerations.TryGetValue(project, out var binding) + NativeBindingGenerationDescriptor imported = products.bindingGenerations.TryGetValue( + project, + out NativeBindingGenerationDescriptor? binding + ) ? binding : throw new InvalidDataException("The selected dependency does not contain its required bindings."); if (ExpectedFingerprint.Length != 0 && ExpectedFingerprint != imported.fingerprint) @@ -247,7 +250,14 @@ public override bool Execute() Dictionary? componentOptions = selectedOptions is null ? null : new(StringComparer.Ordinal) { [owner.nativeProject] = selectedOptions }; - var request = new NativeBindingGenerationRequest([owner], TargetId, mode, CheckOnly, expected, componentOptions); + var request = new NativeBindingGenerationRequest( + [owner], + TargetId, + mode, + CheckOnly, + expected, + componentOptions + ); using NativeBindingGenerationResult closure = generator.GenerateAsync(context, request, cancellation) .AsTask() .GetAwaiter() diff --git a/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs b/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs index 544441918..2c4ce0588 100644 --- a/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs +++ b/build/tasks/Inno.Build.Tasks/PrepareProductNativeTask.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using Microsoft.Build.Framework; using Inno.Build; using Inno.Build.Composition; @@ -89,8 +90,8 @@ public override bool Execute() try { long started = Stopwatch.GetTimestamp(); - var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(TargetId)); - var distribution = StandardBuildDistribution.Create(execution).build; + BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(TargetId)); + BuildDistribution distribution = StandardBuildDistribution.Create(execution).build; NativeProductContribution contribution = distribution.ResolveNativeProduct(TargetId, ProductId); ProductNativeBuildPlan plan = contribution.plan; if (NativeDependencyManifestPath.Length != 0) @@ -113,7 +114,7 @@ public override bool Execute() ); return true; } - var context = new NativeBuildContext(EngineRoot, Configuration.ToLowerInvariant()) + NativeBuildContext context = new NativeBuildContext(EngineRoot, Configuration.ToLowerInvariant()) .WithBindingGenerator(distribution.ResolveBindingGenerator(TargetId)); NativeToolchainSelection toolchain = distribution.ResolveNativeToolchain(TargetId) .ResolveAsync(context, execution.host, TargetId, cancellation.Token) @@ -152,7 +153,8 @@ public override bool Execute() requestIdentity = ProductNativePreparation.FreezeAsync(context, plan, cancellation.Token).GetAwaiter().GetResult(); } bool reused = prepared is not null; - using var products = prepared ?? contribution.BuildAsync(context, cancellation.Token).GetAwaiter().GetResult(); + using ProductNativeBuildResult products = prepared + ?? contribution.BuildAsync(context, cancellation.Token).GetAwaiter().GetResult(); cancellation.Token.ThrowIfCancellationRequested(); Deploy(products, plan, cancellation.Token); string[][]? completed = reused ? null : ProductNativePreparation.Capture(context, plan, products, requestIdentity); @@ -216,8 +218,8 @@ private void Deploy( ProductNativeBuildPlan plan, CancellationToken cancellationToken ) { - var generations = products.bindingGenerations; - var linkage = plan.steps.Where(step => generations.ContainsKey(step.component.nativeProject)) + IReadOnlyDictionary generations = products.bindingGenerations; + Dictionary linkage = plan.steps.Where(step => generations.ContainsKey(step.component.nativeProject)) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) .ToDictionary( static group => group.Key, @@ -240,7 +242,7 @@ private static FileLease AcquirePreparation( string path, CancellationToken cancellation ) { - System.Threading.Tasks.Task pending = FileLease.AcquireAsync(path, Timeout.InfiniteTimeSpan, cancellation).AsTask(); + Task pending = FileLease.AcquireAsync(path, Timeout.InfiniteTimeSpan, cancellation).AsTask(); if (pending.IsCompleted) { return pending.GetAwaiter().GetResult(); diff --git a/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs b/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs index e058f931a..b45fc3354 100644 --- a/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs +++ b/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs @@ -69,7 +69,7 @@ public override bool Execute() } try { - var execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); + BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId(ToolTarget)); var context = new BuildCompositionContext( ToolchainEnvironment.ResolveExecutable(DotnetHost), AppContext.BaseDirectory, diff --git a/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs b/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs index 0b942e0d7..3d0a985ba 100644 --- a/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs +++ b/build/toolchains/Inno.Build.Toolchains/BuildArtifactManifest.cs @@ -55,7 +55,7 @@ public static void Write( writer.WriteStartObject(); writer.WriteString("fingerprint", fingerprint); writer.WriteStartObject("files"); - foreach (var file in files.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) + foreach (KeyValuePair file in files.OrderBy(static pair => pair.Key, StringComparer.Ordinal)) { writer.WriteString(file.Key, file.Value); } @@ -138,7 +138,7 @@ private static Dictionary ReadFiles( ) { ArgumentNullException.ThrowIfNull(outputDirectories); string root = Path.GetFullPath(directory); - Dictionary files = new(StringComparer.Ordinal); + var files = new Dictionary(StringComparer.Ordinal); foreach (string relative in outputDirectories) { ArgumentException.ThrowIfNullOrWhiteSpace(relative); diff --git a/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs b/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs index 13beeb02f..1fd157f33 100644 --- a/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs +++ b/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs @@ -59,13 +59,13 @@ public static void CopyArtifacts( string config, BuildArtifactOptions options ) { - var buildDir = Path.Combine(buildRoot, options.buildDirName); + string buildDir = Path.Combine(buildRoot, options.buildDirName); if (!Directory.Exists(buildDir)) { throw new DirectoryNotFoundException($"Native artifact directory not found: {buildDir}"); } - var candidates = Directory.EnumerateFiles(buildDir, "*", SearchOption.AllDirectories) + List candidates = Directory.EnumerateFiles(buildDir, "*", SearchOption.AllDirectories) .Where(path => { if (path.Contains(DSYM_TOKEN, StringComparison.OrdinalIgnoreCase)) @@ -73,25 +73,25 @@ BuildArtifactOptions options return false; } - var ext = Path.GetExtension(path); + string ext = Path.GetExtension(path); if (!options.extensions.Contains(ext, StringComparer.OrdinalIgnoreCase)) { return false; } - var fileName = Path.GetFileName(path); + string fileName = Path.GetFileName(path); if (!ToolchainEnvironment.ContainsAny(fileName, options.libraryTokens.ToArray()) || !MatchesConfiguration(Path.GetRelativePath(buildDir, path), config) ) { return false; } - if (options.requiredPathTokens == null || options.requiredPathTokens.Count == 0) + if (options.requiredPathTokens is null || options.requiredPathTokens.Count == 0) { return true; } - var normalized = path.Replace('\\', '/'); + string normalized = path.Replace('\\', '/'); return ToolchainEnvironment.ContainsAny(normalized, options.requiredPathTokens.ToArray()); }) .Distinct(StringComparer.OrdinalIgnoreCase) @@ -102,10 +102,11 @@ BuildArtifactOptions options throw new FileNotFoundException($"No {config} native artifacts found under {buildDir}."); } - var artifacts = candidates.Select(source => ( + (string source, string name)[] artifacts = candidates.Select(source => ( source, name: options.normalizeOutputName(Path.GetFileName(source), config))).ToArray(); - var duplicate = artifacts.GroupBy(static artifact => artifact.name, StringComparer.OrdinalIgnoreCase) + IGrouping? duplicate = artifacts + .GroupBy(static artifact => artifact.name, StringComparer.OrdinalIgnoreCase) .FirstOrDefault(static group => group.Count() > 1); if (duplicate is not null) { @@ -113,7 +114,7 @@ BuildArtifactOptions options } Directory.CreateDirectory(outputDir); - foreach (var artifact in artifacts) + foreach ((string source, string name) artifact in artifacts) { File.Copy(artifact.source, Path.Combine(outputDir, artifact.name), overwrite: true); } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs index c6ea7f0a7..4ffe119a6 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BackendPrebuiltArchive.cs @@ -144,7 +144,7 @@ public static async Task ExtractAsync( stream.Position = 0; using var zip = new ZipArchive(stream, ZipArchiveMode.Read); ZipArchiveEntry metadata = zip.GetEntry(C_MANIFEST) ?? throw new InvalidDataException("Missing backend inventory."); - if (metadata.Length > 16 * 1024 * 1024 || zip.Entries.Count > 50001) + if (metadata.Length > 16 * 1024 * 1024 || zip.Entries.Count > 50_001) { throw new InvalidDataException("Backend ZIP inventory exceeds its limit."); } @@ -160,7 +160,7 @@ public static async Task ExtractAsync( using ProcessOwnedDirectory staging = await ProcessOwnedDirectory.CreateAsync(parent, cancellationToken).ConfigureAwait(false); string payload = Path.Combine(staging.directory, "payload"); Directory.CreateDirectory(payload); - var expected = inventory.files.ToDictionary(static file => file.path, StringComparer.Ordinal); + Dictionary expected = inventory.files.ToDictionary(static file => file.path, StringComparer.Ordinal); long total = 0; foreach (ZipArchiveEntry entry in zip.Entries) { @@ -168,7 +168,7 @@ public static async Task ExtractAsync( { continue; } - if (!expected.Remove(entry.FullName, out FileRecord? file) || ((entry.ExternalAttributes >> 16) & 0xf000) is not (0 or 0x8000) + if (!expected.Remove(entry.FullName, out FileRecord? file) || ((entry.ExternalAttributes >> 16) & 0xF000) is not (0 or 0x8000) || (entry.ExternalAttributes & (int)FileAttributes.ReparsePoint) != 0 || (total = checked(total + entry.Length)) > C_MAX_BYTES ) { @@ -201,7 +201,7 @@ public static async Task ExtractAsync( private static Inventory Read(Stream input) { Inventory inventory = JsonSerializer.Deserialize(input) ?? throw new InvalidDataException("Missing backend inventory."); - if (inventory.version != 1 || string.IsNullOrWhiteSpace(inventory.target) || inventory.files is not { Length: > 0 and <= 50000 }) + if (inventory.version != 1 || string.IsNullOrWhiteSpace(inventory.target) || inventory.files is not { Length: > 0 and <= 50_000 }) { throw new InvalidDataException("Unsupported or empty backend inventory."); } @@ -246,8 +246,8 @@ private static void CopyVerified( long length, CancellationToken cancellation ) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - byte[] buffer = new byte[81920]; + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[81_920]; long copied = 0; int read; while ((read = input.Read(buffer)) > 0) diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs index 7d195253a..e95aab2b7 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs @@ -14,17 +14,20 @@ public sealed class BuildArtifactReadLease : IDisposable { private CoordinatedFileLease? m_lease; - private BuildArtifactReadLease(CoordinatedFileLease lease) => m_lease = lease; + private BuildArtifactReadLease(CoordinatedFileLease lease) + { + m_lease = lease; + } /// /// Acquires reading ownership and verifies the complete artifact before exposing it to a consumer. /// - /// - /// The exact publisher root retaining the persistent owner.lock gate. - /// /// /// The absolute artifact directory owned by its publisher; its persistent lease is stored alongside it. /// + /// + /// The exact publisher root retaining the persistent owner.lock gate. + /// /// /// The exact input identity required by the consumer. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs index b559fbb4e..962f9729e 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactWriteLease.cs @@ -13,17 +13,20 @@ public sealed class BuildArtifactWriteLease : IDisposable { private CoordinatedFileLease? m_lease; - private BuildArtifactWriteLease(CoordinatedFileLease lease) => m_lease = lease; + private BuildArtifactWriteLease(CoordinatedFileLease lease) + { + m_lease = lease; + } /// /// Waits for all readers before allowing mutation of one immutable artifact directory. /// - /// - /// The exact publisher root retaining the persistent owner.lock gate. - /// /// /// The absolute artifact location controlled by the publisher. /// + /// + /// The exact publisher root retaining the persistent owner.lock gate. + /// /// /// Cancels this waiter without disturbing existing readers. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs index 1c45aab71..2a4622e84 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheArtifactDescriptor.cs @@ -20,13 +20,13 @@ public sealed class BuildCacheArtifactDescriptor /// /// The absolute persistent file used by this entry's actual producer and readers for Core.IO coordination. /// + /// + /// The explicit product target, or null for a shared host artifact that target-scoped cleanup must preserve. + /// /// /// The publisher-recorded sum of owned file lengths, captured under writing ownership for cache budgeting. /// It does not measure allocated disk blocks or count shared hardlinks as recovered volume space. /// - /// - /// The explicit product target, or null for a shared host artifact that target-scoped cleanup must preserve. - /// /// /// The publisher's last recorded use, used only to order retirement. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs index c522e6ebd..7580a92bf 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs @@ -67,13 +67,13 @@ Stopwatch elapsed /// /// Whether to propose all unreferenced generations regardless of size pressure. /// - /// - /// Cancels planning before any directory is removed. - /// /// /// An exact producer-declared target filter, or null to manage all registered scopes. /// Outside-scope generations and their dependencies remain protected. /// + /// + /// Cancels planning before any directory is removed. + /// /// /// A fixed proposal; execution rechecks ownership, roots and active readers before deletion. /// @@ -101,7 +101,7 @@ public static BuildCacheCleanupPlan Create( CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(policy); - using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + using CancellationTokenSource bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); bounded.CancelAfter(policy.timeBudget); Stopwatch elapsed = Stopwatch.StartNew(); try diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs index 2525d2576..4a631b7c8 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventory.cs @@ -74,7 +74,7 @@ bool HasArtifactAncestor(string path) } } var leasePaths = new HashSet(pathComparer); - foreach (var entry in result.artifacts.Values) + foreach ((BuildCacheOwnerDescriptor owner, BuildCacheArtifactDescriptor artifact) entry in result.artifacts.Values) { if (!leasePaths.Add(entry.artifact.leasePath) || owners.Any(owner => pathComparer.Equals(owner.coordinationPath, entry.artifact.leasePath)) @@ -90,8 +90,8 @@ bool HasArtifactAncestor(string path) throw new InvalidDataException($"Protected cache root '{root}' has no registered artifact owner."); } } - var incoming = result.artifacts.Keys.ToDictionary(static path => path, static _ => 0, pathComparer); - foreach (var entry in result.artifacts.Values) + Dictionary incoming = result.artifacts.Keys.ToDictionary(static path => path, static _ => 0, pathComparer); + foreach ((BuildCacheOwnerDescriptor owner, BuildCacheArtifactDescriptor artifact) entry in result.artifacts.Values) { foreach (string dependency in entry.artifact.dependencies.Distinct(pathComparer)) { @@ -133,7 +133,7 @@ internal HashSet Protect(IEnumerable roots) var pending = new Stack(roots); while (pending.TryPop(out string? path)) { - if (!artifacts.TryGetValue(path, out var entry)) + if (!artifacts.TryGetValue(path, out (BuildCacheOwnerDescriptor owner, BuildCacheArtifactDescriptor artifact) entry)) { throw new InvalidDataException($"Protected cache path '{path}' has no registered artifact owner."); } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs index 7b9899556..3fcb75db1 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheInventoryProgress.cs @@ -35,7 +35,7 @@ CancellationToken cancellation using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(PathBoundary.RequireUnlinkedPath(root, checkpoint))); JsonElement saved = document.RootElement; string relative = saved.GetProperty("directory").GetString() ?? throw new InvalidDataException("Inventory owner is absent."); - var role = (BuildCacheArtifactRole)saved.GetProperty("role").GetInt32(); + BuildCacheArtifactRole role = (BuildCacheArtifactRole)saved.GetProperty("role").GetInt32(); string key = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(relative + "\0" + role))); if (Path.GetFileName(checkpoint) != key + ".inventory") { diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs index bcd7fd211..ffa8b8fa9 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePolicy.cs @@ -1,4 +1,5 @@ using System; +using System.Threading; namespace Inno.Build.Toolchains; @@ -36,7 +37,7 @@ public BuildCachePolicy( throw new ArgumentOutOfRangeException(nameof(minimumFreeBytes)); } TimeSpan duration = timeBudget ?? TimeSpan.FromSeconds(5); - if (duration <= TimeSpan.Zero || duration == System.Threading.Timeout.InfiniteTimeSpan) + if (duration <= TimeSpan.Zero || duration == Timeout.InfiniteTimeSpan) { throw new ArgumentOutOfRangeException(nameof(timeBudget)); } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs index 18d1f9729..da68f9d6e 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCachePublisher.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -101,12 +102,12 @@ public async ValueTask AcquireUseAsync(CancellationToken cancellation /// /// A product/target/configuration root identity, or null for an unselected generation. /// - /// - /// Cancels before metadata selection. - /// /// /// The producer's product target, or null for a shared host generation. /// + /// + /// Cancels before metadata selection. + /// /// /// An owned path escapes the boundary, crosses a directory link, or contains an invalid file link. /// @@ -177,11 +178,6 @@ public void Record( /// /// Cancels inspection or initial registration before publication. /// - /// - /// This confirms ownership, not content integrity. The producer must verify the immutable payload itself. - /// Existing registration age is retained; use an active lease or a current generation dependency to protect - /// consumers. This operation neither selects a current root nor records a new use time. - /// /// /// This publisher does not own immutable artifacts. /// @@ -194,6 +190,11 @@ public void Record( /// /// Inspection or registration was canceled. /// + /// + /// This confirms ownership, not content integrity. The producer must verify the immutable payload itself. + /// Existing registration age is retained; use an active lease or a current generation dependency to protect + /// consumers. This operation neither selects a current root nor records a new use time. + /// public void EnsureImmutableRegistration( string directory, string leasePath, @@ -351,7 +352,7 @@ public void RecordProcessUse( string owners = Path.Combine(directory, "owners"); Directory.CreateDirectory(owners); ProcessOwnerStamp stamp = ProcessOwnerStamp.CaptureCurrent(); - string process = stamp.processId.ToString(System.Globalization.CultureInfo.InvariantCulture); + string process = stamp.processId.ToString(CultureInfo.InvariantCulture); AtomicFile.WriteAllBytes(Path.Combine(owners, process + ".pid"), JsonSerializer.SerializeToUtf8Bytes(stamp)); Record(directory, leasePath, closure, null, null, cancellationToken); } @@ -393,7 +394,7 @@ private void RetireMetadata(CancellationToken cancellation) HashSet currents = ReadRoots(cancellation).ToHashSet(BuildCacheInventory.pathComparer); foreach (string pointer in m_role == BuildCacheArtifactRole.ImmutableArtifact ? Directory.EnumerateFiles(m_root, "*.current") - : Enumerable.Empty() + : [] ) { string selected = PathBoundary.Resolve(m_root, File.ReadAllText(PathBoundary.RequireUnlinkedPath(m_root, pointer))); if (!Directory.Exists(selected)) @@ -567,7 +568,10 @@ private static bool IsProcessAlive(string marker) ) { return true; } - var stamp = new ProcessOwnerStamp(root.GetProperty("processId").GetInt32(), root.GetProperty("startedUtcTicks").GetInt64()); + var stamp = new ProcessOwnerStamp( + root.GetProperty("processId").GetInt32(), + root.GetProperty("startedUtcTicks").GetInt64() + ); return stamp.Query() != ProcessOwnerState.Exited; } catch (Exception exception) when (exception is JsonException or ArgumentException or InvalidOperationException diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs index 27235f26f..c8241ebae 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheRetirement.cs @@ -24,11 +24,14 @@ CancellationToken cancellation var failures = new Dictionary(BuildCacheInventory.pathComparer); var ownerLeases = new List(); var artifactLeases = new Dictionary(BuildCacheInventory.pathComparer); - var proposed = candidates.ToDictionary(static entry => entry.directory, BuildCacheInventory.pathComparer); + Dictionary proposed = candidates.ToDictionary( + static entry => entry.directory, + BuildCacheInventory.pathComparer + ); long reclaimed = 0; Stopwatch elapsed = Stopwatch.StartNew(); bool limited = false; - using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + using CancellationTokenSource bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellation); bounded.CancelAfter(policy.timeBudget); try { @@ -104,7 +107,7 @@ await FileLease.AcquireAsync( limited = true; break; } - var current = fresh.artifacts[path]; + (BuildCacheOwnerDescriptor owner, BuildCacheArtifactDescriptor artifact) current = fresh.artifacts[path]; BuildCacheArtifactDescriptor original = proposed[path]; if (protectedPaths.Contains(path) || !artifactLeases.ContainsKey(path) || original.bytes != current.artifact.bytes || original.lastUseUtc != current.artifact.lastUseUtc diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs index b530cb930..2b2cdce75 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs @@ -171,7 +171,7 @@ public static async Task ImportAsync( using (ZipArchive zip = ZipFile.OpenRead(archivePath)) { long expanded = 0; - if (zip.Entries.Count == 0 || zip.Entries.Count > 200000) + if (zip.Entries.Count == 0 || zip.Entries.Count > 200_000) { throw new InvalidDataException("Native transfer contains an empty or excessive file inventory."); } @@ -180,7 +180,7 @@ public static async Task ImportAsync( cancellationToken.ThrowIfCancellationRequested(); string[] parts = entry.FullName.Split('/'); if (parts.Length < 5 || parts.Any(static part => part is "" or "." or ".." || part.Contains('\\') || part.Contains(':')) - || !names.Add(entry.FullName) || ((entry.ExternalAttributes >> 16) & 0xf000) is not (0 or 0x8000) + || !names.Add(entry.FullName) || ((entry.ExternalAttributes >> 16) & 0xF000) is not (0 or 0x8000) || (expanded = checked(expanded + entry.Length)) > 32L * 1024 * 1024 * 1024 ) { throw new InvalidDataException("Native transfer contains an invalid, linked, duplicate or excessive entry."); @@ -197,7 +197,7 @@ public static async Task ImportAsync( } if (!OperatingSystem.IsWindows() && entry.ExternalAttributes != 0) { - File.SetUnixFileMode(output, (UnixFileMode)((entry.ExternalAttributes >> 16) & 0x1ff)); + File.SetUnixFileMode(output, (UnixFileMode)((entry.ExternalAttributes >> 16) & 0x1FF)); } } } diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs index 1ab6aca20..cb618661a 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs @@ -41,7 +41,7 @@ CancellationToken cancellation NativeBuildRecipe recipe = products.aggregateRecipe ?? throw new InvalidDataException("An aggregate export must retain its producer recipe."); NativeBuildProduct product = products.Single(); - var sources = await NativeDependencySource.CaptureAsync( + Dictionary sources = await NativeDependencySource.CaptureAsync( context.engineRoot, recipe.inputs .Where( @@ -67,7 +67,7 @@ CancellationToken cancellation .Append(recipe.owner.toolchainProject), cancellation ).ConfigureAwait(false); - var bindings = products.bindingGenerations.ToDictionary( + Dictionary bindings = products.bindingGenerations.ToDictionary( static pair => pair.Key, pair => new BindingAsset( pair.Value.fingerprint, @@ -78,7 +78,7 @@ CancellationToken cancellation ), StringComparer.Ordinal ); - var directories = bindings.Values + HashSet directories = bindings.Values .Select(static binding => binding.directory) .Append(Relative(product.directory)) .ToHashSet(StringComparer.Ordinal); @@ -164,7 +164,7 @@ CancellationToken cancellation try { var bindings = new Dictionary(StringComparer.Ordinal); - foreach (var pair in asset.bindings) + foreach (KeyValuePair pair in asset.bindings) { BindingAsset binding = pair.Value; string location = ResolveBinding(binding); diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs index 00225c617..f8d4b003c 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs @@ -108,7 +108,7 @@ public static async Task> SelectAsync( selectedComponents.Add(step.id, selected); RequireDigest(selected.sha256); assets.Add(new(selected.asset, selected.sha256)); - foreach (var pair in selected.sources) + foreach (KeyValuePair pair in selected.sources) { if (sources.TryGetValue(pair.Key, out string? previous) && previous != pair.Value) { @@ -213,7 +213,7 @@ public static async Task ExportAsync( .ToArray(); if (step.component.bindingDefinition is not null) { - var bindingContext = new NativeBuildContext(root, step.configuration ?? context.configuration) + NativeBuildContext bindingContext = new NativeBuildContext(root, step.configuration ?? context.configuration) .WithToolchain(context.RequireToolchain()) .WithBindingGenerator(context.RequireBindingGenerator()); await bindingContext @@ -400,7 +400,7 @@ public static async Task AcquireAsync( foreach (ProductNativeBuildStep step in plan.steps) { DependencyAsset asset = Select(step); - foreach (var pair in asset.sources) + foreach (KeyValuePair pair in asset.sources) { if (expectedSources.TryGetValue(pair.Key, out string? existing) && existing != pair.Value) { @@ -523,7 +523,7 @@ await BuildArtifactReadLease.AcquireAsync( bindingsPath = PathBoundary.Resolve(bindingDirectory, binding.managed), nativeDirectory = PathBoundary.Resolve(bindingDirectory, binding.native) }; - if (bindings.TryGetValue(step.component.nativeProject, out var previous) + if (bindings.TryGetValue(step.component.nativeProject, out NativeBindingGenerationDescriptor? previous) && previous.fingerprint != generation.fingerprint ) { throw new InvalidDataException("A dependency closure selected conflicting binding generations."); diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs index dd3eff97c..9bb89403f 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencySource.cs @@ -6,6 +6,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Inno.Core.IO; namespace Inno.Build.Toolchains; @@ -35,7 +36,7 @@ CancellationToken cancellation } foreach (string path in roots) { - _ = Inno.Core.IO.PathBoundary.Resolve(root, path); + _ = PathBoundary.Resolve(root, path); } string dirty = await GitAsync( ["status", "--porcelain", "--untracked-files=all", "--ignore-submodules=none", "--", ..roots] @@ -48,7 +49,7 @@ CancellationToken cancellation foreach (string[] batch in roots.Chunk(80)) { string tree = await GitAsync(["ls-tree", "-t", "-z", "HEAD", "--", ..batch]).ConfigureAwait(false); - var entries = tree + Dictionary entries = tree .Split('\0', StringSplitOptions.RemoveEmptyEntries) .ToDictionary(entry => entry[(entry.IndexOf('\t') + 1)..], StringComparer.Ordinal); foreach (string path in batch) @@ -94,11 +95,11 @@ CancellationToken cancellation throw new InvalidDataException("Native source tree returned incomplete object metadata."); } string relative = entry[(separator + 1)..]; - string path = Inno.Core.IO.PathBoundary.Resolve(root, relative); - Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, Path.GetDirectoryName(path)!); + string path = PathBoundary.Resolve(root, relative); + PathBoundary.RequireUnlinkedPath(root, Path.GetDirectoryName(path)!); if (metadata[1] == "commit") { - Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, path); + PathBoundary.RequireUnlinkedPath(root, path); // A consumer does not need a third-party checkout. An initialized checkout is mutable and must be checked. if (File.Exists(Path.Combine(path, ".git")) || Directory.Exists(Path.Combine(path, ".git"))) { @@ -131,7 +132,7 @@ CancellationToken cancellation } else { - Inno.Core.IO.PathBoundary.RequireUnlinkedPath(root, path); + PathBoundary.RequireUnlinkedPath(root, path); if (!File.Exists(path)) { throw new InvalidDataException("Native source is missing: " + relative); @@ -149,7 +150,7 @@ CancellationToken cancellation { throw new InvalidDataException("Native source hashing returned an incomplete input inventory."); } - var changed = batch.Where(( + KeyValuePair[] changed = batch.Where(( pair, index ) => hashes[index] != pair.Value).ToArray(); diff --git a/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs b/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs index eaefef319..8808aa8c3 100644 --- a/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs +++ b/build/toolchains/Inno.Build.Toolchains/Host/PhysicalToolchainWorkspaceProvider.cs @@ -10,10 +10,10 @@ namespace Inno.Build.Toolchains; /// public sealed class PhysicalToolchainWorkspaceProvider : IToolchainWorkspaceProvider { - /// + /// public string identity => "physical"; - /// + /// public ValueTask OpenAsync( string physicalPath, CancellationToken cancellationToken = default diff --git a/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs b/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs index 54f77ca6c..79c138427 100644 --- a/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs +++ b/build/toolchains/Inno.Build.Toolchains/Maintenance/BuildMaintenanceApplication.cs @@ -151,7 +151,7 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(policy); Stopwatch elapsed = Stopwatch.StartNew(); IReadOnlyList owners; - using (var inventoryBudget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) + using (CancellationTokenSource inventoryBudget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) { inventoryBudget.CancelAfter(policy.timeBudget); try @@ -192,7 +192,7 @@ CancellationToken cancellationToken Console.WriteLine( $"Cache: {plan.totalBytes} bytes; protected {plan.protectedBytes}; reclaimed {result.retiredBytes}; skipped {result.skipped.Count}." ); - foreach (var failure in result.failures) + foreach (KeyValuePair failure in result.failures) { Console.Error.WriteLine($"Cache retirement failed: {failure.Key}: {failure.Value}"); } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs index 1ae7afdae..4578ecbcf 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildExecution.cs @@ -165,10 +165,14 @@ CancellationToken cancellation string sourceRoot = Path.Combine(workspace, "Sources"); string metadata = Path.Combine(workspace, "inputs.json"); NativeInputSnapshot captured = context.inputState.CaptureRecordedInputs(context.engineRoot); - var selected = captured.entries.Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal)) + NativeInputSnapshot.Entry[] selected = captured.entries + .Where(static input => input.logicalPath.StartsWith("engine/", StringComparison.Ordinal)) .Where(input => IsSource(context.engineRoot, input.logicalPath["engine/".Length..])) .ToArray(); - var paths = new HashSet(selected.Select(static input => input.logicalPath["engine/".Length..]), StringComparer.Ordinal); + var paths = new HashSet( + selected.Select(static input => input.logicalPath["engine/".Length..]), + StringComparer.Ordinal + ); if (File.Exists(metadata)) { string[] previous = JsonSerializer.Deserialize(File.ReadAllText(metadata)) diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs index 630362b35..a9ab4ec5d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputReader.cs @@ -46,7 +46,7 @@ .. evaluation.properties.Select(static pair => "-p:" + pair.Key + "=" + pair.Val ).ConfigureAwait(false); _ = await EvaluateAsync(context, sdk, project, evaluation.properties, true, cancellation).ConfigureAwait(false); XElement captured = await EvaluateAsync(context, sdk, project, evaluation.properties, false, cancellation).ConfigureAwait(false); - var inputs = captured.Elements("Input").Select(element => NativeBuildInput.FromPath( + List inputs = captured.Elements("Input").Select(element => NativeBuildInput.FromPath( context.engineRoot, (string?)element.Attribute("Path") ?? throw new InvalidDataException("A managed input has no physical location.") )).ToList(); diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs index 7f4711bf4..2fc7a94d8 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedBuildInputSnapshot.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -31,7 +32,7 @@ ManagedBuildInputCapture captured m_sdk = sdk; m_project = project; m_properties = properties; - fingerprint = captured.fingerprint; + this.fingerprint = captured.fingerprint; m_declarations = captured.declarations; } @@ -80,10 +81,6 @@ public ValueTask CreateExecutionAsync(CancellationToken c /// /// A snapshot that can be freshly verified after waiting or executing; no Player compilation is performed. /// - /// - /// Restore and evaluation use an owned SDK output layout, independently of ordinary IDE outputs. - /// An explicit ArtifactsPath remains the caller's responsibility, including its concurrency protection. - /// /// /// A required operation, SDK or property collection is null. /// @@ -99,6 +96,10 @@ public ValueTask CreateExecutionAsync(CancellationToken c /// /// Evaluation or hashing was canceled. /// + /// + /// Restore and evaluation use an owned SDK output layout, independently of ordinary IDE outputs. + /// An explicit ArtifactsPath remains the caller's responsibility, including its concurrency protection. + /// public static async ValueTask CaptureAsync( NativeBuildContext context, DotNetSdkDescriptor sdk, @@ -117,7 +118,7 @@ public static async ValueTask CaptureAsync( { throw new FileNotFoundException("The managed input entry project is absent.", selected); } - var frozen = new System.Collections.ObjectModel.ReadOnlyDictionary( + var frozen = new ReadOnlyDictionary( properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase) ); ManagedBuildInputCapture identity = await ManagedBuildInputReader.CaptureAsync( diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs index 4832919ea..e70381d01 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluation.cs @@ -30,7 +30,7 @@ private ManagedInputEvaluation( m_targetId = targetId; } - /// + /// public void Dispose() => m_ownership?.Dispose(); internal IReadOnlyDictionary properties { get; } @@ -78,7 +78,11 @@ CancellationToken cancellation { string? target = properties.TryGetValue("InnoNativeTarget", out string? selected) ? selected : context.toolchain?.targetId; cache.BeginWorkingDirectory(directory, directory + ".lock", target, cancellation); - var isolated = properties.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.OrdinalIgnoreCase); + Dictionary isolated = properties.ToDictionary( + static pair => pair.Key, + static pair => pair.Value, + StringComparer.OrdinalIgnoreCase + ); isolated.Add("ArtifactsPath", directory); return new(new ReadOnlyDictionary(isolated), ownership, cache, directory, target); } diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs index 54b0e29bf..fc0f2c811 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs @@ -20,7 +20,7 @@ BuildArtifactReadLease reading internal string directory { get; } = directory; internal string fingerprint { get; } = fingerprint; - /// + /// public void Dispose() => reading.Dispose(); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs b/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs index 3db86107e..ac5549f73 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ComponentNativeProductExecutor.cs @@ -12,7 +12,7 @@ namespace Inno.Build.Toolchains; /// public sealed class ComponentNativeProductExecutor : INativeProductExecutor { - /// + /// public async Task BuildAsync( NativeBuildContext context, ProductNativeBuildPlan plan, diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs index ba84a26c9..a34a8687d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingCMake.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; @@ -18,7 +19,8 @@ internal static void Write( CancellationToken cancellationToken ) { var text = new StringBuilder("include_guard(GLOBAL)\nfunction(inno_apply_binding target owner)\n"); - foreach (var entry in context.selectedBindings.Where(entry => target is null || entry.Key == owner.nativeProject) + foreach (KeyValuePair entry in context.selectedBindings + .Where(entry => target is null || entry.Key == owner.nativeProject) .OrderBy(static entry => entry.Key, StringComparer.Ordinal) ) { NativeBindingGenerationDescriptor generation = entry.Value; diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs index 43530364e..9a1cb8a70 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationDescriptor.cs @@ -213,8 +213,10 @@ IReadOnlyDictionary linkage } var names = new HashSet(StringComparer.OrdinalIgnoreCase); var document = new XElement("Project"); - foreach (var entry in generations.OrderBy(static entry => entry.Key, StringComparer.Ordinal)) - { + foreach (KeyValuePair entry in generations.OrderBy( + static entry => entry.Key, + StringComparer.Ordinal + )) { string name = Path.GetFileNameWithoutExtension(entry.Key); if (string.IsNullOrWhiteSpace(name) || name.Any(static value => ( !char.IsAsciiLetterOrDigit(value) diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs index 2eff11305..35b77e77a 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs @@ -77,7 +77,7 @@ public NativeBindingGenerationRequest( this.targetId = targetId; this.outputMode = outputMode; this.checkOnly = checkOnly; - Dictionary expected = new(expectedFingerprints ?? new Dictionary(), StringComparer.Ordinal); + var expected = new Dictionary(expectedFingerprints ?? new Dictionary(), StringComparer.Ordinal); if (expected.Any(pair => ( !owners.Any(owner => owner.nativeProject == pair.Key) || string.IsNullOrWhiteSpace(pair.Value) diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs index cf8848360..5c137cae3 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationResult.cs @@ -47,28 +47,28 @@ IEnumerable ownership m_ownership = owners; } - /// /// /// Reading ownership has ended. /// + /// public int Count => RequireGenerations().Count; - /// + /// + /// Reading ownership has ended. + /// /// /// The returned sequence is borrowed and must be consumed before this result is disposed. /// + /// + public IEnumerable Keys => RequireGenerations().Keys; + /// /// Reading ownership has ended. /// - public IEnumerable Keys => RequireGenerations().Keys; - - /// /// /// Neither the returned sequence nor its descriptors extend the lifetime of reading protection. /// - /// - /// Reading ownership has ended. - /// + /// public IEnumerable Values => RequireGenerations().Values; /// @@ -88,31 +88,31 @@ IEnumerable ownership /// public NativeBindingGenerationDescriptor this[string key] => RequireGenerations()[key]; - /// /// /// Reading ownership has ended. /// + /// public bool ContainsKey(string key) => RequireGenerations().ContainsKey(key); - /// - /// - /// A returned descriptor is borrowed and must not be used to access files after this result is disposed. - /// /// /// Reading ownership has ended. /// + /// + /// A returned descriptor is borrowed and must not be used to access files after this result is disposed. + /// + /// public bool TryGetValue( string key, [MaybeNullWhen(false)] out NativeBindingGenerationDescriptor value ) => RequireGenerations().TryGetValue(key, out value); - /// - /// - /// Enumeration and all descriptor consumers must finish before the result's reading protection ends. - /// /// /// Reading ownership has ended. /// + /// + /// Enumeration and all descriptor consumers must finish before the result's reading protection ends. + /// + /// public IEnumerator> GetEnumerator() => RequireGenerations().GetEnumerator(); /// diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs index a56bc89a3..fecec415f 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingInputPaths.cs @@ -57,7 +57,7 @@ internal NativeBindingInputPaths(NativeBuildContext context) internal string? ResolveRelative(string path) { string absolute = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); - foreach (var entry in m_roots) + foreach ((string physical, string relative, bool file) entry in m_roots) { if (string.Equals(absolute, entry.physical, m_comparison)) { diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs index c45e26beb..5f6593078 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildFingerprint.cs @@ -43,7 +43,7 @@ public static string Create( ) { ArgumentNullException.ThrowIfNull(declarations); ArgumentNullException.ThrowIfNull(inputs); - NativeBuildInputState state = new(); + var state = new NativeBuildInputState(); return Create(declarations, state.CaptureInitial(inputs, cancellationToken)); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs index 9c2a07e83..51e0c63de 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildInputState.cs @@ -20,7 +20,10 @@ internal sealed class NativeBuildInputState private long m_managedProcesses; private readonly Dictionary m_phases = new(StringComparer.Ordinal); - internal NativeBuildInputState() => m_initialInputs = new(this); + internal NativeBuildInputState() + { + m_initialInputs = new(this); + } internal NativeBuildStatistics statistics => new() @@ -60,7 +63,7 @@ string phase Interlocked.Add(ref m_hashedBytes, bytes); lock (m_gate) { - m_phases.TryGetValue(phase, out var value); + m_phases.TryGetValue(phase, out (long files, long bytes, long reused) value); m_phases[phase] = (value.files + 1, value.bytes + bytes, value.reused); } } @@ -93,7 +96,7 @@ internal void RecordReuse(string phase) { lock (m_gate) { - m_phases.TryGetValue(phase, out var value); + m_phases.TryGetValue(phase, out (long files, long bytes, long reused) value); m_phases[phase] = (value.files, value.bytes, value.reused + 1); } } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildProduct.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildProduct.cs index fd99a3ee6..ddaa56504 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildProduct.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildProduct.cs @@ -30,8 +30,8 @@ BuildArtifactReadLease readLease m_readLease = readLease; try { - artifacts = NativeArtifact.Read(directory); - files = Array.AsReadOnly(artifacts.Select(static artifact => artifact.file).Order(StringComparer.Ordinal).ToArray()); + this.artifacts = NativeArtifact.Read(directory); + this.files = Array.AsReadOnly(artifacts.Select(static artifact => artifact.file).Order(StringComparer.Ordinal).ToArray()); } catch { diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs index 87fc889d7..7ac0c47c8 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBuildRecipe.cs @@ -271,7 +271,7 @@ string fingerprint targetId, inputs.Append(input), declarations.Append("dependency=" + fingerprint) - ) { toolchain = this.toolchain }; + ) { toolchain = toolchain }; } /// @@ -294,7 +294,7 @@ NativeBindingGenerationDescriptor generation inputs.Concat(generated), declarations.Append("bindings=" + generation.fingerprint) .Append("bindingNativeRoot=" + generation.nativeDirectory) - ) { toolchain = this.toolchain }; + ) { toolchain = toolchain }; } private static void ValidateSegment(string value) diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs index b15fbad0f..d92691596 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeSource.cs @@ -242,7 +242,10 @@ internal sealed class Preparation private readonly NativeInputSnapshot m_inputs; private Task? m_task; - internal Preparation(NativeInputSnapshot inputs) => m_inputs = inputs; + internal Preparation(NativeInputSnapshot inputs) + { + m_inputs = inputs; + } internal Task GetAsync( NativeBuildContext context, diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs index 40ec0e992..09bc52386 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs @@ -42,15 +42,15 @@ public sealed class NativeComponentBuildOptions /// /// Portable checkout-relative configuration files included in content hashing and stability checks. /// - /// - /// Component-specific platform link settings, or null for the selected SDK plan. - /// /// /// The explicit native import identity, or null to retain the component identity. /// /// /// Additional checkout-relative binding headers owned by an integration. /// + /// + /// Component-specific platform link settings, or null for the selected SDK plan. + /// /// /// Linkage is invalid, definitions are ambiguous or override SDK selection, or an input escapes the checkout. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs index 7664e3b0b..6905528bd 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputMaterializer.cs @@ -44,7 +44,7 @@ public static async ValueTask CopyAsync( ) { ArgumentNullException.ThrowIfNull(context); NativeBuildInput input = NativeBuildInput.FromPath(context.engineRoot, source); - NativeBuildInput output = new(input.logicalPath, destination); + var output = new NativeBuildInput(input.logicalPath, destination); cancellationToken.ThrowIfCancellationRequested(); byte[] expected = context.inputState.GetFrozenHash(input.physicalPath); if (File.Exists(destination)) @@ -60,7 +60,7 @@ public static async ValueTask CopyAsync( try { await using (FileStream read = File.OpenRead(input.physicalPath)) - await using (FileStream write = new( + await using (var write = new FileStream( candidate, FileMode.CreateNew, FileAccess.Write, diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs index 08085350a..3abc4c4a0 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputSnapshot.cs @@ -14,7 +14,9 @@ byte[] hash ); internal NativeInputSnapshot(IEnumerable entries) - => this.entries = Array.AsReadOnly(entries.OrderBy(static entry => entry.logicalPath, StringComparer.Ordinal).ToArray()); + { + this.entries = Array.AsReadOnly(entries.OrderBy(static entry => entry.logicalPath, StringComparer.Ordinal).ToArray()); + } internal IReadOnlyList entries { get; } @@ -23,7 +25,7 @@ internal static NativeInputSnapshot Capture( NativeInputReadCache cache, CancellationToken cancellationToken ) { - Dictionary paths = new(StringComparer.Ordinal); + var paths = new Dictionary(StringComparer.Ordinal); foreach (NativeBuildInput input in inputs) { cancellationToken.ThrowIfCancellationRequested(); @@ -41,7 +43,7 @@ CancellationToken cancellationToken paths.Add(logical, physical); } } - var ordered = paths.OrderBy(static pair => pair.Key, StringComparer.Ordinal).ToArray(); + KeyValuePair[] ordered = paths.OrderBy(static pair => pair.Key, StringComparer.Ordinal).ToArray(); byte[][] hashes = cache.Hash(ordered.Select(static pair => pair.Value).ToArray(), cancellationToken); return new NativeInputSnapshot( ordered.Select(( diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs index 6e49971af..be00878a1 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeInputVerificationScope.cs @@ -11,7 +11,9 @@ internal sealed class NativeInputVerificationScope internal NativeInputVerificationScope( NativeBuildInputState state, string phase - ) => m_inputs = new NativeInputReadCache(state, phase); + ) { + m_inputs = new NativeInputReadCache(state, phase); + } internal NativeInputSnapshot Capture( IEnumerable inputs, diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs index cf60634d9..2e430cb62 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainPreparation.cs @@ -53,12 +53,12 @@ public static Dictionary CreateEnvironment() /// /// Ordered target configuration arguments. /// - /// - /// Whether configuration is chosen during build. - /// /// /// The sole source of target library formats and linker capabilities. /// + /// + /// Whether configuration is chosen during build. + /// /// /// The selected SDK parser inputs, or null for a selection without parsing capability. /// diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs index 052a2c85e..02a0a1bce 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeToolchainSelection.cs @@ -34,12 +34,12 @@ public sealed class NativeToolchainSelection /// /// Ordered configuration arguments pinning compiler, generator and SDK. /// - /// - /// Whether configuration is selected during build rather than configure. - /// /// /// The sole source of target library formats and linker capabilities. /// + /// + /// Whether configuration is selected during build rather than configure. + /// /// /// Explicit SDK parser inputs, or null when no native parser is provided. /// @@ -115,7 +115,7 @@ public NativeToolchainSelection( this.multiConfiguration = multiConfiguration; this.compilerInputs = compilerInputs ?? new NativeCompilerInputs(); this.linkPlan = linkPlan; - declarations = Array.AsReadOnly( + this.declarations = Array.AsReadOnly( this.environment.OrderBy(static entry => entry.Key, StringComparer.Ordinal) .Select(static entry => entry.Key + "=" + entry.Value) .Concat( diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs index 7ae4d3429..156fe9c50 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativeDeployment.cs @@ -21,6 +21,12 @@ public static class ProductNativeDeployment /// Validated runtime and optional authoring products returned by the declared product plan. /// All products must use the same target; each component can appear once. /// + /// + /// The explicit component closure and deployment mapping used to produce these products. + /// + /// + /// The managed output directory receiving the complete native tree. + /// /// /// Cancels ownership acquisition or staging before the atomic installation starts. /// @@ -28,12 +34,6 @@ public static class ProductNativeDeployment /// Completion after the complete native tree has been validated under exclusive publication ownership. /// Identical deployments retain their files, including libraries loaded by a running application. /// - /// - /// The explicit component closure and deployment mapping used to produce these products. - /// - /// - /// The managed output directory receiving the complete native tree. - /// /// /// The product closure is empty, contains duplicate components or mixes targets. /// @@ -68,10 +68,6 @@ public static ValueTask InstallAsync( /// /// Completion after copying and verifying payload, without creating transaction metadata in the candidate. /// - /// - /// The caller must retain exclusive ownership and discard the entire candidate on failure or cancellation. - /// This operation neither selects a publication nor replaces an existing native tree. - /// /// /// The product closure or candidate path is invalid. /// @@ -84,6 +80,10 @@ public static ValueTask InstallAsync( /// /// Cancellation prevents completing the unpublished candidate. /// + /// + /// The caller must retain exclusive ownership and discard the entire candidate on failure or cancellation. + /// This operation neither selects a publication nor replaces an existing native tree. + /// public static ValueTask StageAsync( IReadOnlyList products, ProductNativeBuildPlan plan, @@ -136,7 +136,7 @@ CancellationToken cancellationToken ?? new Dictionary(); var metadata = new Dictionary(StringComparer.Ordinal); StringComparer paths = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; - var payloadPaths = files.Keys.Select(relative => PathBoundary.Resolve(destination, relative)).ToHashSet(paths); + HashSet payloadPaths = files.Keys.Select(relative => PathBoundary.Resolve(destination, relative)).ToHashSet(paths); var metadataPaths = new HashSet(paths); foreach ((string relative, byte[] content) in contributed) { @@ -173,7 +173,7 @@ CancellationToken cancellationToken string output = Path.Combine(staging, relative); Directory.CreateDirectory(Path.GetDirectoryName(output)!); await using (FileStream source = File.OpenRead(file)) - await using (FileStream target = new(output, FileMode.CreateNew)) + await using (var target = new FileStream(output, FileMode.CreateNew)) { await source.CopyToAsync(target, cancellationToken).ConfigureAwait(false); } diff --git a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs index d86b79f53..e5112394d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/ProductNativePreparation.cs @@ -58,7 +58,8 @@ public static async Task FreezeAsync( .ToArray(); if (components.Length != 0) { - var options = plan.steps.Where(static step => step.component.bindingDefinition is not null) + Dictionary options = plan.steps + .Where(static step => step.component.bindingDefinition is not null) .GroupBy(static step => step.component.nativeProject, StringComparer.Ordinal) .ToDictionary(static group => group.Key, static group => group.First().options, StringComparer.Ordinal); var request = new NativeBindingGenerationRequest( diff --git a/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs b/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs index 181bbf5a5..03767c1fc 100644 --- a/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs +++ b/build/toolchains/Inno.Build.Toolchains/NativeBuildContext.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; +using System.Threading; using Inno.Core.IO; namespace Inno.Build.Toolchains; @@ -70,7 +71,7 @@ private NativeBuildContext( string fingerprint ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { - sourcePreparation = origin.sourcePreparation; + this.sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; m_component = origin.m_component; @@ -78,7 +79,7 @@ string fingerprint m_buildOwner = buildOwner; m_targetId = targetId; m_fingerprint = fingerprint; - toolchain = origin.toolchain; + this.toolchain = origin.toolchain; m_bindings = origin.m_bindings; } @@ -87,7 +88,7 @@ private NativeBuildContext( NativeToolchainSelection toolchain ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { - sourcePreparation = origin.sourcePreparation; + this.sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; m_component = origin.m_component; @@ -106,7 +107,7 @@ private NativeBuildContext( NativeToolchainSelection? toolchain ) : this(origin.engineRoot, configuration, origin.m_inputState) { - sourcePreparation = origin.sourcePreparation; + this.sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; m_component = origin.m_component; @@ -121,7 +122,7 @@ private NativeBuildContext( NativeComponentBuildOptions options ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { - sourcePreparation = origin.sourcePreparation; + this.sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; m_component = component; @@ -130,7 +131,7 @@ NativeComponentBuildOptions options m_targetId = origin.m_targetId; m_fingerprint = origin.m_fingerprint; m_toolDirectory = origin.m_toolDirectory; - toolchain = origin.toolchain; + this.toolchain = origin.toolchain; m_bindings = origin.m_bindings; } @@ -139,7 +140,7 @@ private NativeBuildContext( string? toolDirectory ) : this(origin.engineRoot, origin.configuration, origin.m_inputState) { - sourcePreparation = origin.sourcePreparation; + this.sourcePreparation = origin.sourcePreparation; m_bindingGenerator = origin.m_bindingGenerator; m_verification = origin.m_verification; m_component = origin.m_component; @@ -147,7 +148,7 @@ private NativeBuildContext( m_buildOwner = origin.m_buildOwner; m_targetId = origin.m_targetId; m_fingerprint = origin.m_fingerprint; - toolchain = origin.toolchain; + this.toolchain = origin.toolchain; m_toolDirectory = toolDirectory; m_bindings = origin.m_bindings; } @@ -425,7 +426,7 @@ public NativeBuildContext BeginInputVerification(string phase) internal NativeInputSnapshot CaptureInputs( IEnumerable inputs, - System.Threading.CancellationToken cancellationToken + CancellationToken cancellationToken ) => m_verification?.Capture(inputs, cancellationToken) ?? m_inputState.CaptureInitial(inputs, cancellationToken); diff --git a/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs b/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs index 50d6d5901..19813a965 100644 --- a/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs +++ b/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs @@ -366,8 +366,8 @@ public static string FindRepoRoot() { string location = typeof(ToolchainEnvironment).Assembly.Location; string outputRoot = string.IsNullOrEmpty(location) ? AppContext.BaseDirectory : Path.GetDirectoryName(location)!; - var dir = new DirectoryInfo(outputRoot); - while (dir != null) + DirectoryInfo? dir = new DirectoryInfo(outputRoot); + while (dir is not null) { if (File.Exists(Path.Combine(dir.FullName, ToolchainLayout.C_REPOSITORY_MARKER_FILE))) { @@ -438,7 +438,7 @@ public static bool ContainsAny( string value, params string[] needles ) { - foreach (var needle in needles) + foreach (string needle in needles) { if (value.Contains(needle, StringComparison.OrdinalIgnoreCase)) { @@ -465,9 +465,9 @@ public static string NormalizeOutputName( string fileName, string config ) { - var ext = Path.GetExtension(fileName); - var baseName = Path.GetFileNameWithoutExtension(fileName); - var trimmed = TrimConfigSuffix(baseName); + string ext = Path.GetExtension(fileName); + string baseName = Path.GetFileNameWithoutExtension(fileName); + string trimmed = TrimConfigSuffix(baseName); return $"{trimmed}-{config}{ext}"; } diff --git a/entry/InnoEngine.Editor/Program.cs b/entry/InnoEngine.Editor/Program.cs index c9ed41fdc..7cc23b419 100644 --- a/entry/InnoEngine.Editor/Program.cs +++ b/entry/InnoEngine.Editor/Program.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Reflection; using System.Threading; using Inno.Core.IO; @@ -28,7 +29,7 @@ private static int Main(string[] arguments) { string ownership = ReadProductLock(); // Product clean must wait until the running Editor has released its deployment. - if (!System.IO.File.Exists(ownership)) + if (!File.Exists(ownership)) { FileLease.AcquireAsync(ownership, TimeSpan.FromSeconds(10), cancellation.Token) .GetAwaiter() diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs index af3ef3cae..8907f7735 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/EmscriptenToolchainResolver.cs @@ -28,10 +28,6 @@ public static class EmscriptenToolchainResolver /// /// Variables for native builds and binding generation, without changing the parent process. /// - /// - /// Compiler worker budgets remain inherited from the host environment or tool defaults. - /// Runtime threading policy does not constrain build-time parallelism. - /// /// /// The SDK host or a required Emscripten workload component is missing. /// @@ -47,6 +43,10 @@ public static class EmscriptenToolchainResolver /// /// The operation was canceled. /// + /// + /// Compiler worker budgets remain inherited from the host environment or tool defaults. + /// Runtime threading policy does not constrain build-time parallelism. + /// public static async Task> ResolveAsync( string dotnetHost, string projectPath, diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs index 9411db772..b9081f67c 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs @@ -56,7 +56,7 @@ public async Task BuildAsync( ArgumentNullException.ThrowIfNull(plan); cancellationToken.ThrowIfCancellationRequested(); NativeToolchainSelection tools = context.RequireToolchain(); - if (tools.targetId != Inno.Build.BrowserWasm32.BrowserWasm32BuildModule.target.id.value || context.configuration != "release") + if (tools.targetId != BrowserWasm32BuildModule.target.id.value || context.configuration != "release") { throw new InvalidOperationException("Browser static publication requires an explicit Release wasm32 selection."); } @@ -267,7 +267,7 @@ private static string CMakeLiteral(string value) { delimiter++; } - string equals = new('=', delimiter); + var equals = new string('=', delimiter); return "[" + equals + "[" + portable + "]" + equals + "]"; } } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs index 04222bc9b..077b9c1d9 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/SupportPacks/BrowserWasm32PlayerSupportPackSource.cs @@ -64,10 +64,10 @@ IPlayerSupportPackValidator supportPackValidator m_validator = supportPackValidator ?? throw new ArgumentNullException(nameof(supportPackValidator)); } - /// - public BuildTargetId target => Inno.Build.BrowserWasm32.BrowserWasm32BuildModule.target.id; + /// + public BuildTargetId target => BrowserWasm32BuildModule.target.id; - /// + /// public async ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken @@ -91,7 +91,7 @@ CancellationToken cancellationToken { throw new FileNotFoundException("The Browser publication template is absent.", template); } - var nativeContext = new NativeBuildContext(context.engineRoot, "release").WithBindingGenerator(m_bindingGenerator); + NativeBuildContext nativeContext = new NativeBuildContext(context.engineRoot, "release").WithBindingGenerator(m_bindingGenerator); NativeToolchainSelection tools = await new EmscriptenNativeToolchainProvider(context.dotnetHost) .ResolveAsync(nativeContext, m_host, target.value, cancellationToken) .ConfigureAwait(false); @@ -196,7 +196,7 @@ CancellationToken cancellationToken "-p:InnoShaderToolSourceRoot=" + nativeContext.engineRoot, "-p:InnoNativeBindingSelection=" + bindingSelection, ..(identity.nativeDependencies is string selection - ? new[] { "-p:InnoNativeDependencyManifest=" + selection } + ? ["-p:InnoNativeDependencyManifest=" + selection] : Array.Empty()), "-p:DebugType=None", "-p:DebugSymbols=false" @@ -231,7 +231,7 @@ await PlayerSupportPackFiles.CopyPlayerSourcesAsync( await execution.VerifyAsync(cancellationToken).ConfigureAwait(false); } - /// + /// public void Validate(string directory) => m_validator.Validate(directory); private static void CopyLinkTemplate( @@ -287,10 +287,10 @@ private sealed class PreparationPlan( PlayerSupportPackPreparationIdentity identity ) : PlayerSupportPackPlan(owner.target, identity.fingerprint) { - /// + /// public override ValueTask VerifyInputsAsync(CancellationToken cancellationToken) => identity.VerifyAsync(cancellationToken); - /// + /// public override ValueTask PrepareAsync( string stagingDirectory, CancellationToken cancellationToken diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs index 85b489ead..a35a46ab2 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Targets/BrowserWasm32GameBuildTarget.cs @@ -42,12 +42,12 @@ public BrowserWasm32GameBuildTarget(IPlayerSupportPackValidator supportPackValid /// /// Gets the browser WebAssembly target identity. /// - public BuildTargetId id => Inno.Build.BrowserWasm32.BrowserWasm32BuildModule.target.id; + public BuildTargetId id => BrowserWasm32BuildModule.target.id; - /// + /// public ManagedDeploymentId defaultManagedDeployment => ManagedDeploymentId.monoWasm; - /// + /// public string runtimeIdentifier => "browser-wasm"; /// @@ -104,8 +104,8 @@ CancellationToken cancellationToken string relativePath = Path.GetRelativePath(source, file); string target = Path.Combine(destination, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(target)!); - await using FileStream input = new(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, true); - await using FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131072, true); + await using var input = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131_072, true); + await using var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131_072, true); await input.CopyToAsync(output, cancellationToken); } } diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs index 78383d725..17ae18d1d 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Toolchain/EmscriptenNativeToolchainProvider.cs @@ -29,7 +29,7 @@ public EmscriptenNativeToolchainProvider(string dotnetHost) m_dotnetHost = dotnetHost; } - /// + /// public async ValueTask ResolveAsync( NativeBuildContext context, BuildHostDescriptor host, diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs index cedc25214..bce904179 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Bgfx/BrowserWasm32BgfxShaderProfiles.cs @@ -15,7 +15,7 @@ public static class BrowserWasm32BgfxShaderProfiles public static BgfxShaderTargetProfile target { get; } = new( BrowserWasm32BuildModule.target.id.value, [ - new(CreateCapabilities(), "asm.js", "300_es", "300_es", "") + new(CreateCapabilities(), "asm.js", "300_es", "300_es", string.Empty) ] ); diff --git a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs index 18fc215d5..abe345cd8 100644 --- a/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs +++ b/platforms/BrowserWasm32/integrations/Inno.Integration.BrowserWasm32.Sdl3/BrowserWasm32Sdl3HostIntegration.cs @@ -11,19 +11,16 @@ namespace Inno.Integration.BrowserWasm32.Sdl3; /// public sealed class BrowserWasm32Sdl3HostIntegration : ISdl3HostIntegration { - /// + /// public Sdl3HostCapabilities capabilities { get; } = new(multipleWindows: false, liveResize: false); - /// + /// public void ConfigureInitialization() {} - /// - public nint CreateWindow(PlatformWindowOptions options) - { - return Sdl3WindowOperations.CreateWindow(options, requireOpenGl: true); - } + /// + public nint CreateWindow(PlatformWindowOptions options) => Sdl3WindowOperations.CreateWindow(options, requireOpenGl: true); - /// + /// public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) { if (windowHandle == 0) @@ -43,7 +40,7 @@ public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) } } - /// + /// public bool GetInitialFocus(nint windowHandle) { if (windowHandle == 0) diff --git a/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs b/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs index f90c110ad..27b2efcae 100644 --- a/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs +++ b/platforms/BrowserWasm32/runtime/Inno.Adapter.Storage.BrowserWasm32/BrowserWasm32StorageBackendProvider.cs @@ -14,9 +14,6 @@ public sealed class BrowserWasm32StorageBackendProvider : StorageBackendProvider public BrowserWasm32StorageBackendProvider() : base(StorageBackendId.browser) {} - /// - public override IApplicationStorage CreateStorage(StorageScope scope) - { - return new BrowserWasm32ApplicationStorage(scope); - } + /// + public override IApplicationStorage CreateStorage(StorageScope scope) => new BrowserWasm32ApplicationStorage(scope); } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs index ea70703e7..4565ebc6d 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Host/MacOSArm64BuildHostProvider.cs @@ -9,7 +9,7 @@ namespace Inno.Build.MacOSArm64; /// public sealed class MacOSArm64BuildHostProvider : IBuildHostProvider { - /// + /// public BuildHostDescriptor? TryCapture() => !OperatingSystem.IsMacOS() || RuntimeInformation.ProcessArchitecture != Architecture.Arm64 diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs index b077025c6..a445be784 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64PlayerSupportPackSource.cs @@ -22,12 +22,12 @@ public sealed class MacOSArm64PlayerSupportPackSource : IPlayerSupportPackSource /// /// The declared machine executing platform tools. /// - /// - /// The borrowed shared binding implementation selected by distribution. - /// /// /// The explicit SDK executable for binding generation. /// + /// + /// The borrowed shared binding implementation selected by distribution. + /// /// /// The borrowed validator selected by the distribution. /// @@ -39,9 +39,9 @@ public MacOSArm64PlayerSupportPackSource( IPlayerSupportPackValidator supportPackValidator ) { m_preparation = new FilePlayerSupportPackPreparation( - Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, + MacOSArm64BuildModule.target.id, "osx-arm64", - Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id.value, + MacOSArm64BuildModule.target.id.value, ".dylib", supportPackValidator, "platforms/MacOSArm64/player/Inno.Player.MacOSArm64/Inno.Player.MacOSArm64.csproj", @@ -56,15 +56,15 @@ IPlayerSupportPackValidator supportPackValidator ); } - /// - public BuildTargetId target => Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id; + /// + public BuildTargetId target => MacOSArm64BuildModule.target.id; - /// + /// public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken ) => m_preparation.CreatePlanAsync(context, cancellationToken); - /// + /// public void Validate(string directory) => m_preparation.Validate(directory); } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs index c57926231..842b72de7 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/SupportPacks/MacOSArm64SupportPackValidator.cs @@ -29,7 +29,7 @@ public void Validate(string directory) if (foreignNativeExtensions.Contains(Path.GetExtension(file), StringComparer.OrdinalIgnoreCase)) { throw new InvalidDataException( - $"Player Support Pack '{Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'." + $"Player Support Pack '{MacOSArm64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'." ); } if (Path.GetExtension(file).Equals(".dylib", StringComparison.OrdinalIgnoreCase)) @@ -58,8 +58,8 @@ public void Validate(string directory) private static void ValidateLibrary(string file) { using var input = new BinaryReader(File.OpenRead(file)); - if (input.BaseStream.Length < 32 || input.ReadUInt32() != 0xfeedfacf - || input.ReadUInt32() != 0x0100000c + if (input.BaseStream.Length < 32 || input.ReadUInt32() != 0xFEED_FACF + || input.ReadUInt32() != 0x0100_000C ) { throw new InvalidDataException($"MacOSArm64 native library '{file}' does not target the Mach-O ARM64 ABI."); } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs index 784006065..ef7c1f703 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs @@ -42,12 +42,12 @@ public MacOSArm64GameBuildTarget(IPlayerSupportPackValidator supportPackValidato /// /// Gets the macOS ARM64 target identity. /// - public BuildTargetId id => Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id; + public BuildTargetId id => MacOSArm64BuildModule.target.id; - /// + /// public ManagedDeploymentId defaultManagedDeployment => ManagedDeploymentId.coreClr; - /// + /// public string runtimeIdentifier => "osx-arm64"; /// @@ -146,8 +146,8 @@ bool excludeCompilerReferences } string target = Path.Combine(destination, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(target)!); - await using FileStream input = new(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, true); - await using FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131072, true); + await using var input = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131_072, true); + await using var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131_072, true); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); if (!OperatingSystem.IsWindows()) { diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs index 9ca7b72cb..dfbc44c82 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Toolchain/MacOSArm64NativeToolchainProvider.cs @@ -30,7 +30,7 @@ public MacOSArm64NativeToolchainProvider(string dotnetHost) m_dotnetHost = dotnetHost; } - /// + /// public async ValueTask ResolveAsync( NativeBuildContext context, BuildHostDescriptor host, diff --git a/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs b/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs index 9d032d7e2..7523ed12f 100644 --- a/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs +++ b/platforms/MacOSArm64/editor/Inno.Editor.MacOSArm64/MacOSArm64EditorComposition.cs @@ -14,7 +14,9 @@ using Inno.Adapter.Storage; using Inno.Adapter.Storage.FileSystem; using Inno.Build; +using Inno.Build.Composition; using Inno.Build.Distribution.Standard; +using Inno.Build.MacOSArm64; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Execution; using Inno.Core.Input; @@ -44,13 +46,13 @@ public static class MacOSArm64EditorComposition /// /// An optional project directory and the shared Editor command-line options. /// - /// - /// Zero on normal exit or dialog cancellation, two on cancellation or invalid arguments, or one on startup failure. - /// /// /// Cancels preparation or requests orderly shutdown of the shared Editor host. /// An open native folder dialog retains its callback owner until the user completes or closes it. /// + /// + /// Zero on normal exit or dialog cancellation, two on cancellation or invalid arguments, or one on startup failure. + /// public static int Run( string[] arguments, CancellationToken cancellationToken @@ -83,14 +85,14 @@ CancellationToken cancellationToken [new BgfxAuthoringProvider(MacOSArm64BgfxIntegration.shaderProfile)], [new ImGuiPresentationProvider(new ImGuiInteractionOptions(commandKeyBehavior: true, horizontalWheelDirection: -1))] ); - var buildContext = StandardBuildEnvironment.Capture( + BuildCompositionContext buildContext = StandardBuildEnvironment.Capture( Path.GetDirectoryName(typeof(MacOSArm64EditorComposition).Assembly.Location)!, - Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, + MacOSArm64BuildModule.target.id, nativeDependencies: command.nativeDependencies ); var launch = new EditorLaunchOptions { - defaultBuildTarget = Inno.Build.MacOSArm64.MacOSArm64BuildModule.target.id, + defaultBuildTarget = MacOSArm64BuildModule.target.id, projectDirectory = project, keyboard = new EditorKeyboardPolicy(KeyModifier.Super, "Cmd"), adapterCatalog = adapters, diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs index 551103819..343ae86f0 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Bgfx/MacOSArm64BgfxBuildProfile.cs @@ -8,32 +8,32 @@ namespace Inno.Integration.MacOSArm64.Bgfx; internal sealed class MacOSArm64BgfxBuildProfile : BgfxNativeBuildProfile { - /// + /// public override NativeToolchainSelection SelectTools( NativeBuildContext context, bool includeTools ) => MacOSArm64BgfxToolContribution.Select(context, includeTools); - /// + /// public override string targetId => MacOSArm64BuildModule.target.id.value; - /// + /// public override IReadOnlyList generatorArguments => ["--gcc=osx-arm64", "gmake"]; - /// + /// public override string artifactPathToken => "/osx-arm64/bin/"; - /// + /// public override IReadOnlyList bindingCmakeArguments => []; - /// + /// public override (string reference, IReadOnlyList arguments) CreateBindingLinkSettings(string archivePath) { ArgumentException.ThrowIfNullOrWhiteSpace(archivePath); return (archivePath, ["-Xlinker", "-force_load", "-Xlinker", "\"" + archivePath + "\""]); } - /// + /// public override BgfxBuildInvocation CreateBuildInvocation( NativeBuildContext context, bool includeTools diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs index 1b1486eb8..b7c44216e 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs @@ -10,8 +10,7 @@ internal static class MacOSArm64NativeProducts private const string C_INPUT = "platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Build/Products/MacOSArm64NativeProducts.cs"; internal static NativeComponentBuildOptions Options(string component) - { - return new( + => new( NativeLibraryKind.Shared, inputPaths: [C_INPUT], bindingIncludeDirectories: component == "bgfx" ? ["extern/bx/include/compat/osx"] : [], @@ -19,5 +18,4 @@ internal static NativeComponentBuildOptions Options(string component) ? MacOSArm64LinkerSettings.Create(["@loader_path/../../cimgui/" + MacOSArm64BuildModule.target.id.value]) : null ); - } } diff --git a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs index 9fd6ef011..581938563 100644 --- a/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs +++ b/platforms/MacOSArm64/integrations/Inno.Integration.MacOSArm64.Sdl3/MacOSArm64Sdl3HostIntegration.cs @@ -11,22 +11,16 @@ namespace Inno.Integration.MacOSArm64.Sdl3; /// public sealed class MacOSArm64Sdl3HostIntegration : ISdl3HostIntegration { - /// + /// public Sdl3HostCapabilities capabilities { get; } = new(multipleWindows: true, liveResize: true); - /// - public void ConfigureInitialization() - { - _ = SDL.SetHint("SDL_MAC_PRESS_AND_HOLD", "0"); - } + /// + public void ConfigureInitialization() => _ = SDL.SetHint("SDL_MAC_PRESS_AND_HOLD", "0"); - /// - public nint CreateWindow(PlatformWindowOptions options) - { - return Sdl3WindowOperations.CreateWindow(options, requireOpenGl: false); - } + /// + public nint CreateWindow(PlatformWindowOptions options) => Sdl3WindowOperations.CreateWindow(options, requireOpenGl: false); - /// + /// public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) { if (windowHandle == 0) @@ -47,9 +41,6 @@ public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) return new PlatformNativeHandles(surface, handleKind: PlatformNativeHandleId.cocoa); } - /// - public bool GetInitialFocus(nint windowHandle) - { - return Sdl3WindowOperations.ReadFocus(windowHandle); - } + /// + public bool GetInitialFocus(nint windowHandle) => Sdl3WindowOperations.ReadFocus(windowHandle); } diff --git a/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs b/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs index efdf96a7e..5384acc3f 100644 --- a/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs +++ b/platforms/MacOSArm64/player/Inno.Player.MacOSArm64/MacOSArm64PlayerContentSource.cs @@ -16,10 +16,12 @@ internal sealed class MacOSArm64PlayerContentSource : IPlayerContentSource internal MacOSArm64PlayerContentSource( string applicationDirectory, string cacheRoot - ) => m_files = new FileContentDeployment( - MacOSArm64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), - cacheRoot - ); + ) { + m_files = new FileContentDeployment( + MacOSArm64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), + cacheRoot + ); + } /// /// Reads independently owned deployment metadata from the platform's explicit content source. diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs index fb98054ec..3ba0e4731 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/WindowsBuildHostProvider.cs @@ -9,7 +9,7 @@ namespace Inno.Build.WindowsX64; /// public sealed class WindowsBuildHostProvider : IBuildHostProvider { - /// + /// public BuildHostDescriptor? TryCapture() => !OperatingSystem.IsWindows() ? null diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs index 298c19b51..bcf2a853f 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainDirectory.cs @@ -9,8 +9,8 @@ namespace Inno.Build.WindowsX64; internal sealed class WindowsToolchainDirectory : IDisposable { - private const uint C_MOUNT_POINT_TAG = 0xA0000003; - private const uint C_SET_REPARSE_POINT = 0x000900A4; + private const uint C_MOUNT_POINT_TAG = 0xA000_0003; + private const uint C_SET_REPARSE_POINT = 0x0009_00A4; private readonly string m_physicalPath; private WindowsToolchainDirectory( @@ -45,7 +45,7 @@ internal static WindowsToolchainDirectory Create(string physicalPath) : "\\??\\" + physicalPath ); byte[] printable = Encoding.Unicode.GetBytes(physicalPath); - byte[] data = new byte[20 + substitute.Length + printable.Length]; + var data = new byte[20 + substitute.Length + printable.Length]; Write(data, 0, C_MOUNT_POINT_TAG); Write(data, 4, checked((ushort)(data.Length - 8))); Write(data, 10, checked((ushort)substitute.Length)); @@ -54,7 +54,7 @@ internal static WindowsToolchainDirectory Create(string physicalPath) substitute.CopyTo(data, 16); printable.CopyTo(data, 18 + substitute.Length); - using SafeFileHandle handle = CreateFile(alias, 0x40000000, 7, nint.Zero, 3, 0x02200000, nint.Zero); + using SafeFileHandle handle = CreateFile(alias, 0x4000_0000, 7, nint.Zero, 3, 0x0220_0000, nint.Zero); if (handle.IsInvalid) { throw new Win32Exception(Marshal.GetLastPInvokeError(), "Cannot open the owned toolchain directory alias."); @@ -72,7 +72,7 @@ internal static WindowsToolchainDirectory Create(string physicalPath) } } - /// + /// public void Dispose() { if (toolPath == m_physicalPath || !Directory.Exists(toolPath)) diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs index 24617f88a..bc7dc3881 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Host/Workspace/WindowsToolchainWorkspaceProvider.cs @@ -14,10 +14,10 @@ namespace Inno.Build.WindowsX64; /// public sealed class WindowsToolchainWorkspaceProvider : IToolchainWorkspaceProvider { - /// + /// public string identity => Path.Combine(Path.GetTempPath(), "InnoTools"); - /// + /// public async ValueTask OpenAsync( string physicalPath, CancellationToken cancellationToken = default @@ -68,7 +68,7 @@ private sealed class Ownership( string leaf ) : IDisposable { - /// + /// public void Dispose() { try diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs index f1502e623..3fa7f1f78 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64PlayerSupportPackSource.cs @@ -22,12 +22,12 @@ public sealed class WindowsX64PlayerSupportPackSource : IPlayerSupportPackSource /// /// The declared machine executing platform tools. /// - /// - /// The borrowed shared binding implementation selected by distribution. - /// /// /// The explicit SDK executable for binding generation. /// + /// + /// The borrowed shared binding implementation selected by distribution. + /// /// /// The borrowed validator selected by the distribution. /// @@ -39,9 +39,9 @@ public WindowsX64PlayerSupportPackSource( IPlayerSupportPackValidator supportPackValidator ) { m_preparation = new FilePlayerSupportPackPreparation( - Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, + WindowsX64BuildModule.target.id, "win-x64", - Inno.Build.WindowsX64.WindowsX64BuildModule.target.id.value, + WindowsX64BuildModule.target.id.value, ".dll", supportPackValidator, "platforms/WindowsX64/player/Inno.Player.WindowsX64/Inno.Player.WindowsX64.csproj", @@ -56,15 +56,15 @@ IPlayerSupportPackValidator supportPackValidator ); } - /// - public BuildTargetId target => Inno.Build.WindowsX64.WindowsX64BuildModule.target.id; + /// + public BuildTargetId target => WindowsX64BuildModule.target.id; - /// + /// public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken ) => m_preparation.CreatePlanAsync(context, cancellationToken); - /// + /// public void Validate(string directory) => m_preparation.Validate(directory); } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs index fb8e8fe96..4e12a76ac 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/SupportPacks/WindowsX64SupportPackValidator.cs @@ -29,7 +29,7 @@ public void Validate(string directory) if (foreignNativeExtensions.Contains(Path.GetExtension(file), StringComparer.OrdinalIgnoreCase)) { throw new InvalidDataException( - $"Player Support Pack '{Inno.Build.WindowsX64.WindowsX64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'." + $"Player Support Pack '{WindowsX64BuildModule.target.id}' contains foreign native runtime '{Path.GetFileName(file)}'." ); } if (Path.GetExtension(file).Equals(".dll", StringComparison.OrdinalIgnoreCase)) @@ -58,7 +58,7 @@ public void Validate(string directory) private static void ValidateLibrary(string file) { using var input = new BinaryReader(File.OpenRead(file)); - if (input.BaseStream.Length < 64 || input.ReadUInt16() != 0x5a4d) + if (input.BaseStream.Length < 64 || input.ReadUInt16() != 0x5A4D) { throw new InvalidDataException($"WindowsX64 native library '{file}' has no PE header."); } @@ -69,12 +69,12 @@ private static void ValidateLibrary(string file) throw new InvalidDataException($"WindowsX64 native library '{file}' has an invalid PE header offset."); } input.BaseStream.Position = offset; - if (input.ReadUInt32() != 0x00004550 || input.ReadUInt16() != 0x8664) + if (input.ReadUInt32() != 0x0000_4550 || input.ReadUInt16() != 0x8664) { throw new InvalidDataException($"WindowsX64 native library '{file}' does not target the AMD64 ABI."); } input.BaseStream.Position = offset + 22; - if ((input.ReadUInt16() & 0x2000) == 0 || input.ReadUInt16() != 0x020b) + if ((input.ReadUInt16() & 0x2000) == 0 || input.ReadUInt16() != 0x020B) { throw new InvalidDataException($"WindowsX64 native library '{file}' is not a PE32+ dynamic library."); } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs index 929b7ce72..c33e4d599 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs @@ -41,12 +41,12 @@ public WindowsX64GameBuildTarget(IPlayerSupportPackValidator supportPackValidato /// /// Gets the Windows x64 target identity. /// - public BuildTargetId id => Inno.Build.WindowsX64.WindowsX64BuildModule.target.id; + public BuildTargetId id => WindowsX64BuildModule.target.id; - /// + /// public ManagedDeploymentId defaultManagedDeployment => ManagedDeploymentId.coreClr; - /// + /// public string runtimeIdentifier => "win-x64"; /// @@ -121,8 +121,8 @@ bool excludeCompilerReferences } string target = Path.Combine(destination, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(target)!); - await using FileStream input = new(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, true); - await using FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131072, true); + await using var input = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 131_072, true); + await using var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, 131_072, true); await input.CopyToAsync(output, cancellationToken).ConfigureAwait(false); } } diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs index 2b053122d..61c215f24 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Toolchain/WindowsX64NativeToolchainProvider.cs @@ -30,7 +30,7 @@ public WindowsX64NativeToolchainProvider(string dotnetHost) m_dotnetHost = dotnetHost; } - /// + /// public async ValueTask ResolveAsync( NativeBuildContext context, BuildHostDescriptor host, diff --git a/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs b/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs index 9314a97d9..968eca493 100644 --- a/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs +++ b/platforms/WindowsX64/editor/Inno.Editor.WindowsX64/WindowsX64EditorComposition.cs @@ -14,8 +14,10 @@ using Inno.Adapter.Storage; using Inno.Adapter.Storage.FileSystem; using Inno.Build; +using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains.Bgfx.Tools; +using Inno.Build.WindowsX64; using Inno.Core.Execution; using Inno.Core.Input; using Inno.Core.Logging; @@ -44,13 +46,13 @@ public static class WindowsX64EditorComposition /// /// An optional project directory and the shared Editor command-line options. /// - /// - /// Zero on normal exit or dialog cancellation, two on cancellation or invalid arguments, or one on startup failure. - /// /// /// Cancels preparation or requests orderly shutdown of the shared Editor host. /// An open native folder dialog retains its callback owner until the user completes or closes it. /// + /// + /// Zero on normal exit or dialog cancellation, two on cancellation or invalid arguments, or one on startup failure. + /// public static int Run( string[] arguments, CancellationToken cancellationToken @@ -83,14 +85,14 @@ CancellationToken cancellationToken [new BgfxAuthoringProvider(WindowsX64BgfxIntegration.shaderProfile)], [new ImGuiPresentationProvider(new ImGuiInteractionOptions(commandKeyBehavior: false, horizontalWheelDirection: 1))] ); - var buildContext = StandardBuildEnvironment.Capture( + BuildCompositionContext buildContext = StandardBuildEnvironment.Capture( Path.GetDirectoryName(typeof(WindowsX64EditorComposition).Assembly.Location)!, - Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, + WindowsX64BuildModule.target.id, nativeDependencies: command.nativeDependencies ); var launch = new EditorLaunchOptions { - defaultBuildTarget = Inno.Build.WindowsX64.WindowsX64BuildModule.target.id, + defaultBuildTarget = WindowsX64BuildModule.target.id, projectDirectory = project, keyboard = new EditorKeyboardPolicy(KeyModifier.Control, "Super"), adapterCatalog = adapters, diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs index 9e3fcfdbc..af9835caa 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Bgfx/WindowsX64BgfxBuildProfile.cs @@ -9,26 +9,26 @@ namespace Inno.Integration.WindowsX64.Bgfx; internal sealed class WindowsX64BgfxBuildProfile : BgfxNativeBuildProfile { - /// + /// public override NativeToolchainSelection SelectTools( NativeBuildContext context, bool includeTools ) => WindowsX64BgfxToolContribution.Select(context, includeTools); - /// + /// public override string targetId => WindowsX64BuildModule.target.id.value; - /// + /// public override IReadOnlyList generatorArguments => ["vs2022"]; - /// + /// public override string artifactPathToken => "/win64_vs2022/bin/"; - /// + /// public override IReadOnlyList bindingCmakeArguments => ["-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded$<$:Debug>"]; - /// + /// public override (string reference, IReadOnlyList arguments) CreateBindingLinkSettings(string archivePath) { ArgumentException.ThrowIfNullOrWhiteSpace(archivePath); @@ -36,7 +36,7 @@ public override (string reference, IReadOnlyList arguments) CreateBindin return (Path.ChangeExtension(archivePath, null), ["/WHOLEARCHIVE:\"" + archivePath + "\""]); } - /// + /// public override BgfxBuildInvocation CreateBuildInvocation( NativeBuildContext context, bool includeTools diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs index 50d631d15..863760fe2 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs @@ -7,11 +7,9 @@ internal static class WindowsX64NativeProducts private const string C_INPUT = "platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Build/Products/WindowsX64NativeProducts.cs"; internal static NativeComponentBuildOptions Options(string component) - { - return new( + => new( NativeLibraryKind.Shared, cmakeArguments: component == "cimgui" ? ["-DINNO_CIMGUI_COMPILE_DEFINITIONS=IMGUI_API=__declspec(dllexport)"] : [], inputPaths: [C_INPUT] ); - } } diff --git a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs index 02d334181..b96dc29fd 100644 --- a/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs +++ b/platforms/WindowsX64/integrations/Inno.Integration.WindowsX64.Sdl3/WindowsX64Sdl3HostIntegration.cs @@ -11,19 +11,16 @@ namespace Inno.Integration.WindowsX64.Sdl3; /// public sealed class WindowsX64Sdl3HostIntegration : ISdl3HostIntegration { - /// + /// public Sdl3HostCapabilities capabilities { get; } = new(multipleWindows: true, liveResize: true); - /// + /// public void ConfigureInitialization() {} - /// - public nint CreateWindow(PlatformWindowOptions options) - { - return Sdl3WindowOperations.CreateWindow(options, requireOpenGl: false); - } + /// + public nint CreateWindow(PlatformWindowOptions options) => Sdl3WindowOperations.CreateWindow(options, requireOpenGl: false); - /// + /// public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) { if (windowHandle == 0) @@ -44,9 +41,6 @@ public unsafe PlatformNativeHandles ResolveNativeSurface(nint windowHandle) return new PlatformNativeHandles(surface, handleKind: PlatformNativeHandleId.win32); } - /// - public bool GetInitialFocus(nint windowHandle) - { - return Sdl3WindowOperations.ReadFocus(windowHandle); - } + /// + public bool GetInitialFocus(nint windowHandle) => Sdl3WindowOperations.ReadFocus(windowHandle); } diff --git a/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs b/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs index e0b0331d5..2c321cd70 100644 --- a/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs +++ b/platforms/WindowsX64/player/Inno.Player.WindowsX64/WindowsX64PlayerContentSource.cs @@ -16,10 +16,12 @@ internal sealed class WindowsX64PlayerContentSource : IPlayerContentSource internal WindowsX64PlayerContentSource( string applicationDirectory, string cacheRoot - ) => m_files = new FileContentDeployment( - WindowsX64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), - cacheRoot - ); + ) { + m_files = new FileContentDeployment( + WindowsX64ApplicationLocations.GetPlayerContentDirectory(applicationDirectory), + cacheRoot + ); + } /// /// Reads independently owned deployment metadata from the platform's explicit content source. diff --git a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs index cb65d7e8f..84633a2c3 100644 --- a/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs +++ b/src/adapters/audio/Inno.Adapter.Audio/AudioBackendCatalog.cs @@ -34,16 +34,16 @@ public AudioBackendCatalog(IEnumerable providers) throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// + /// public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// + /// public IAudioDevice CreateDevice( AudioBackendId backend, AudioBackendOptions options diff --git a/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs b/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs index 0d410802f..a5451c6eb 100644 --- a/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs +++ b/src/adapters/input/Inno.Adapter.Input/EventInputBackendProvider.cs @@ -14,7 +14,7 @@ public sealed class EventInputBackendProvider : InputBackendProvider public EventInputBackendProvider() : base(InputBackendId.events) {} - /// + /// public override IInputEventSource CreateEventSource( IPlatformWindow window, bool acceptAllWindows diff --git a/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs b/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs index 7626374f4..9dd9cdeeb 100644 --- a/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs +++ b/src/adapters/input/Inno.Adapter.Input/InputBackendCatalog.cs @@ -34,16 +34,16 @@ public InputBackendCatalog(IEnumerable providers) throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// + /// public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// + /// public IInputEventSource CreateEventSource( InputBackendId backend, IPlatformWindow window, diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs index 5dbdf68b5..f7b8058eb 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformBackendCatalog.cs @@ -34,16 +34,16 @@ public PlatformBackendCatalog(IEnumerable providers) throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// + /// public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// + /// public IPlatformApplication CreateApplication(PlatformBackendId backend) { if (!m_providers.TryGetValue(backend, out PlatformBackendProvider? provider)) diff --git a/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandles.cs b/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandles.cs index 7fd79cb35..8cb221d4f 100644 --- a/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandles.cs +++ b/src/adapters/platform/Inno.Adapter.Platform/PlatformNativeHandles.cs @@ -5,10 +5,6 @@ namespace Inno.Adapter.Platform; /// /// Borrows surface handles from a live window for cooperating native adapters. /// -/// -/// Handles remain valid only while their window is alive. Consumers must not release them. -/// The handle identifier selects the ABI; this value is not a runtime or scripting contract. -/// /// /// Native window handle, or a stable UTF-8 canvas selector for browser surfaces. /// @@ -21,6 +17,10 @@ namespace Inno.Adapter.Platform; /// /// A borrowed adapter-level surface description. /// +/// +/// Handles remain valid only while their window is alive. Consumers must not release them. +/// The handle identifier selects the ABI; this value is not a runtime or scripting contract. +/// public readonly record struct PlatformNativeHandles( IntPtr windowHandle, IntPtr displayHandle = default, diff --git a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs index 19b2fbdac..d23455b0f 100644 --- a/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs +++ b/src/adapters/presentation/Inno.Adapter.Presentation/PresentationBackendCatalog.cs @@ -33,16 +33,16 @@ public PresentationBackendCatalog(IEnumerable provi throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// + /// public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// + /// public IPresentationContext CreateContext( PresentationBackendId backend, PresentationBackendOptions options diff --git a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs index a6b3f0c77..2a7f9793e 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering.Authoring/RenderingAuthoringBackendCatalog.cs @@ -43,7 +43,7 @@ IEnumerable providers { throw new ArgumentException("Runtime and authoring rendering providers must register the same backend IDs.", nameof(providers)); } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } /// diff --git a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs index 7cab6b876..413567a7c 100644 --- a/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs +++ b/src/adapters/rendering/Inno.Adapter.Rendering/RenderingBackendCatalog.cs @@ -31,7 +31,7 @@ public RenderingBackendCatalog(IEnumerable providers) throw new ArgumentException("Rendering providers require unique, assigned backend IDs.", nameof(providers)); } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } /// diff --git a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs index 8c386d9ab..6c8e5d1e3 100644 --- a/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs +++ b/src/adapters/storage/Inno.Adapter.Storage/StorageBackendCatalog.cs @@ -34,16 +34,16 @@ public StorageBackendCatalog(IEnumerable providers) throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// + /// public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// + /// public IApplicationStorage CreateStorage( StorageBackendId backend, StorageScope scope diff --git a/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs b/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs index a573be2ad..366f4aacb 100644 --- a/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs +++ b/src/adapters/text/Inno.Adapter.Text/TextBackendCatalog.cs @@ -34,16 +34,16 @@ public TextBackendCatalog(IEnumerable providers) throw new ArgumentException("Providers require unique, assigned backend IDs.", nameof(providers)); } } - supportedBackends = new ReadOnlyCollection(new List(m_providers.Keys)); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } - /// + /// public IReadOnlyList supportedBackends { get; } - /// /// /// The selected provider returned no service. /// + /// public ITextBackend CreateBackend(TextBackendId backend) { if (!m_providers.TryGetValue(backend, out TextBackendProvider? provider)) diff --git a/src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs b/src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs index 21c4e2c64..80377aa5f 100644 --- a/src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs +++ b/src/adapters/ui/Inno.Adapter.UI/UiBackendCatalog.cs @@ -28,7 +28,7 @@ public UiBackendCatalog(IEnumerable providers) throw new ArgumentException("UI providers require unique, assigned backend IDs.", nameof(providers)); } } - supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); + this.supportedBackends = new ReadOnlyCollection([.. m_providers.Keys]); } /// diff --git a/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs b/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs index aa1ddba59..d9c256033 100644 --- a/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs +++ b/src/composition/default/Inno.Engine.Default/Animation/AnimationSubsystem.cs @@ -10,12 +10,12 @@ internal static class AnimationSubsystem internal static IRuntimeSubsystemFactory Create(EngineSessionComposition context) => new AnimationRuntimeFactory(owner => { - var reporter = owner.resources.Own( + DiagnosticReporter reporter = owner.resources.Own( owner.diagnostics.CreateReporter( new DiagnosticSource($"inno.animation.bindings.{owner.identities.domainId}", "Animation") ) ); - var bindings = owner.resources.Own(new AnimationBindingRuntime(owner.types, reporter)); + AnimationBindingRuntime bindings = owner.resources.Own(new AnimationBindingRuntime(owner.types, reporter)); return new AnimationRuntime(owner.events, bindings); }); } diff --git a/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs b/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs index 8e465bcfc..bead90d54 100644 --- a/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs +++ b/src/composition/default/Inno.Engine.Default/EngineSessionComposition.cs @@ -35,12 +35,12 @@ public sealed class EngineSessionComposition /// /// The portable audio defaults, captured during factory activation. /// - /// - /// An optional product-specific audio owner, such as Editor preview/Play isolation. - /// /// /// The host factory transferring one isolated storage service to the session. /// + /// + /// An optional product-specific audio owner, such as Editor preview/Play isolation. + /// public EngineSessionComposition( RuntimeSession session, IAdapterCatalog adapters, diff --git a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs index 2c5da03bd..44384309e 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs @@ -180,7 +180,10 @@ public sealed class AssetCreationContext /// Source serializer carrying the active reference context. /// [ScriptingApiIgnore] - public AssetCreationContext(AssetSourceStore sources) => m_sources = sources ?? throw new ArgumentNullException(nameof(sources)); + public AssetCreationContext(AssetSourceStore sources) + { + m_sources = sources ?? throw new ArgumentNullException(nameof(sources)); + } /// /// Encodes an Asset value through the current native structured source serializer. diff --git a/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs b/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs index 50b551990..9874df26a 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Documents/AssetDraftDocuments.cs @@ -4,6 +4,7 @@ using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Editor.Core; @@ -175,7 +176,7 @@ public void ReplaceMany( ) { ArgumentNullException.ThrowIfNull(candidates); var encoded = new Dictionary(); - foreach (var pair in candidates) + foreach (KeyValuePair pair in candidates) { if (m_drafts[pair.Key].readOnly) { @@ -185,7 +186,7 @@ public void ReplaceMany( } using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction("Edit " + m_label + " Selection"); - foreach (var pair in encoded) + foreach (KeyValuePair pair in encoded) { RecordReplace(m_drafts[pair.Key], pair.Value, mergeKey); } @@ -208,7 +209,11 @@ private void RecordReplace( before = before, after = next }; - var change = new EditorHistoryChange(m_historyKind, EditorHistoryPayload.FromBytes(m_serialization.Serialize(payload)), mergeKey); + var change = new EditorHistoryChange( + m_historyKind, + EditorHistoryPayload.FromBytes(m_serialization.Serialize(payload)), + mergeKey + ); draft.bytes = next; try { @@ -343,7 +348,7 @@ private void Changed(Draft draft) ); if (draft.error.StartsWith("Recovery write failed:", StringComparison.Ordinal)) { - draft.error = ""; + draft.error = string.Empty; } } catch (Exception error) when (Recoverable(error)) @@ -359,7 +364,7 @@ private bool Save(Draft draft) RefreshPath(draft); draft.hash = m_sources.Save(draft.path, draft.bytes, draft.hash); draft.baseline = draft.bytes; - draft.error = ""; + draft.error = string.Empty; m_imports.Add(draft.path); DeleteRecovery(draft.id); return true; @@ -381,7 +386,7 @@ private bool Revert(Draft draft) draft.hash = source.contentHash; draft.baseline = draft.bytes; draft.readOnly = source.isReadOnly; - draft.error = ""; + draft.error = string.Empty; DeleteRecovery(draft.id); return true; } @@ -522,7 +527,7 @@ private void SynchronizeSource(Draft draft) draft.bytes = source.bytes; draft.baseline = source.bytes; draft.hash = source.contentHash; - draft.error = ""; + draft.error = string.Empty; Changed(draft); } catch (Exception error) when (Recoverable(error)) @@ -562,7 +567,7 @@ private void DeleteRecovery(Guid id) private static bool Recoverable(Exception error) => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException - && Inno.Core.Execution.RetirementPendingException.Find(error) is null; + && RetirementPendingException.Find(error) is null; private sealed class Provider(AssetDraftDocuments owner) : EditorDocumentProvider { @@ -675,7 +680,7 @@ bool readOnly /// /// Gets the latest source, save or import diagnostic. /// - public string error { get; internal set; } = ""; + public string error { get; internal set; } = string.Empty; /// /// Gets whether detached bytes differ from the saved baseline. @@ -689,7 +694,7 @@ private sealed class Recovery : ISerializable internal Guid assetId { get; set; } [SerializableProperty] - internal string hash { get; set; } = ""; + internal string hash { get; set; } = string.Empty; [SerializableProperty] internal byte[] baseline { get; set; } = []; diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs index 6093a69fe..7289b59df 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.Creation.cs @@ -44,8 +44,17 @@ public AssetFileEntry CreateDirectory(AssetPath parent) } while (m_pipeline.TryGetFileSystemEntry(candidate, out _)); m_pipeline.CreateDirectory(candidate); - var data = new AssetHistoryData(AssetHistoryOperationKind.CreateDirectory, candidate.ToString(), string.Empty, true, []); - using var change = new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode())); + var data = new AssetHistoryData( + AssetHistoryOperationKind.CreateDirectory, + candidate.ToString(), + string.Empty, + true, + [] + ); + using var change = new EditorHistoryChange( + AssetHistoryKinds.SourceOperation, + EditorHistoryPayload.FromBytes(data.Encode()) + ); try { m_interactions.history.RecordApplied("Create Folder", change); @@ -102,8 +111,17 @@ ReadOnlySpan bytes { _ = m_pipeline.Import(path); byte[] archive = AssetSourceArchive.Capture(m_pipeline, path.ToString(), out bool isDirectory); - var data = new AssetHistoryData(AssetHistoryOperationKind.CreateAsset, path.ToString(), string.Empty, isDirectory, archive); - var change = new EditorHistoryChange(AssetHistoryKinds.SourceOperation, EditorHistoryPayload.FromBytes(data.Encode())); + var data = new AssetHistoryData( + AssetHistoryOperationKind.CreateAsset, + path.ToString(), + string.Empty, + isDirectory, + archive + ); + var change = new EditorHistoryChange( + AssetHistoryKinds.SourceOperation, + EditorHistoryPayload.FromBytes(data.Encode()) + ); try { m_interactions.history.RecordApplied("Create Asset", change); diff --git a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs index ff5e496c7..e03231eab 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Editing/AssetEditingModule.cs @@ -11,6 +11,7 @@ using Inno.Editor.Interactions; using Inno.Extensibility.Types; using Inno.Plugins.Authoring; +using Inno.Scripting.Api; namespace Inno.Editor.Assets; @@ -69,13 +70,13 @@ LogRouter logs /// /// Gets the editor interaction owner used by source operations. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public EditorInteractions interactions => m_interactions; /// /// Gets the authoritative authoring pipeline; mutations must use its existing ownership protocol. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetPipeline pipeline => m_pipeline; /// @@ -96,7 +97,7 @@ public IReadOnlyList creationTemplates /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool CanCreateAsset( string directory, string templateId @@ -124,7 +125,7 @@ string templateId /// /// The committed source identity, or a validation result describing why the operation is unavailable. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetFileEntry CreateAsset( string directory, string templateId @@ -181,7 +182,7 @@ string templateId /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool IsPluginSource(AssetSourceId source) => m_plugins.TryGet(source, out _); /// @@ -193,7 +194,7 @@ string templateId /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool IsPluginRoot(AssetFileEntry entry) { ArgumentNullException.ThrowIfNull(entry); @@ -215,7 +216,7 @@ public bool IsPluginRoot(AssetFileEntry entry) /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool TryCreateContext( EditorContext editor, string relativePath, @@ -251,7 +252,7 @@ out AssetEditorContext? context /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool Open(AssetEditorContext context) { AssetEditor editor = m_editors.Resolve(context.assetType); @@ -283,7 +284,7 @@ public bool Open(AssetEditorContext context) /// /// The committed source identity, or a validation result describing why the operation is unavailable. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public EditorValidationResult ValidateRename( AssetEditorContext context, string newName @@ -301,7 +302,7 @@ string newName /// /// The requested entry name without its protected file extension. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public void Rename( AssetEditorContext context, string newName @@ -357,7 +358,7 @@ out string targetPath /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool CanMoveToDirectory( string sourcePath, string targetDirectory @@ -378,7 +379,7 @@ string targetDirectory /// /// The committed source identity, or a validation result describing why the operation is unavailable. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetFileEntry MoveToDirectoryWithHistory( string sourcePath, string targetDirectory, @@ -405,7 +406,13 @@ out string targetPath { throw new InvalidOperationException(result.message); } - var data = new AssetHistoryData(AssetHistoryOperationKind.Move, normalizedSource, targetPath, context.isDirectory, archive: []); + var data = new AssetHistoryData( + AssetHistoryOperationKind.Move, + normalizedSource, + targetPath, + context.isDirectory, + archive: [] + ); try { history.RecordApplied( @@ -460,7 +467,7 @@ internal bool Delete(AssetEditorContext context) /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool DeleteWithHistory( AssetEditorContext asset, IEditorHistory history @@ -533,7 +540,7 @@ internal void DeleteFromHistory(string relativePath) /// /// The isolated source-relative path to resolve. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public void SelectPath(string relativePath) { object? target = m_pipeline.TryGetFileSystemEntry(AssetPath.Parse(relativePath), out AssetFileEntry entry) ? entry : null; @@ -552,7 +559,7 @@ public void SelectPath(string relativePath) /// /// True when the request is accepted; otherwise false. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public bool TryCreateDragData( AssetEditorContext context, out EditorDragData? data @@ -574,10 +581,7 @@ out EditorDragData? data /// /// The context that supplies state and services for this operation. /// - protected override void OnStart(EditorContext context) - { - m_context = context ?? throw new ArgumentNullException(nameof(context)); - } + protected override void OnStart(EditorContext context) => m_context = context ?? throw new ArgumentNullException(nameof(context)); /// /// Stops this feature before its owning runtime releases the active generation. @@ -585,10 +589,7 @@ protected override void OnStart(EditorContext context) /// /// The context that supplies state and services for this operation. /// - protected override void OnStop(EditorContext context) - { - m_context = null; - } + protected override void OnStop(EditorContext context) => m_context = null; /// /// Releases resources retained by this feature after it has stopped. diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs index 6242aa3f6..1576b0eb9 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetHistoryData.cs @@ -29,7 +29,7 @@ internal static AssetHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); - var kind = (AssetHistoryOperationKind)reader.ReadByte(); + AssetHistoryOperationKind kind = (AssetHistoryOperationKind)reader.ReadByte(); if (!Enum.IsDefined(kind)) { throw new InvalidDataException($"Unknown asset history operation kind '{kind}'."); diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs index eab30b895..2ed8795ee 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs @@ -80,7 +80,7 @@ CancellationToken cancellationToken ZipArchiveEntry entry = archive.CreateEntry(entryName, CompressionLevel.Fastest); using Stream output = entry.Open(); using FileStream input = File.OpenRead(source); - byte[] buffer = new byte[81920]; + var buffer = new byte[81_920]; int count; while ((count = input.Read(buffer)) != 0) { diff --git a/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs index 30446c334..40a42da4e 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs @@ -2,10 +2,12 @@ using System.IO; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Editor.Assets; @@ -36,7 +38,7 @@ public sealed partial class AssetImportSettingsEdits : EditorModule /// /// Shared Editor history owner. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetImportSettingsEdits( AssetPipeline assets, SerializationRegistry serialization, @@ -100,7 +102,7 @@ string expectedFingerprint { m_interactions.history.RecordApplied("Change Import Settings", change); } - catch (Exception failure) when (Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when (RetirementPendingException.Find(failure) is null) { change.Dispose(); try @@ -216,7 +218,7 @@ EditorHistoryDirection direction return EditorHistoryAvailability.Available(); } catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { return EditorHistoryAvailability.Unavailable(failure.Message); } @@ -248,7 +250,7 @@ EditorHistoryDirection direction return EditorHistoryResult.Success(); } catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { return EditorHistoryResult.Failure(failure.Message); } diff --git a/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs b/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs index 6f6432263..828aafaf6 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs @@ -316,7 +316,7 @@ private sealed class ImportProgress( long operation ) : IProgress { - /// + /// public void Report(ScriptCompilationProgress value) => owner.SetProgress(0.2f + value.fraction * 0.6f, value.stage, operation); } } diff --git a/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs b/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs index cf7bcbd96..c376b1066 100644 --- a/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs +++ b/src/composition/editor/features/Inno.Editor.Audio/IEditorAudioHost.cs @@ -13,12 +13,12 @@ public interface IEditorAudioHost : IDisposable /// /// Creates the reusable factory that contributes isolated audio runtimes to Editor sessions. /// - /// - /// A factory whose features are owned and released by their runtime sessions. - /// /// /// The explicit session being composed. /// + /// + /// A factory whose features are owned and released by their runtime sessions. + /// IRuntimeSubsystemFactory CreateRuntimeSubsystemFactory(RuntimeSession session); /// diff --git a/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs b/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs index 67b177782..cf9ab59ad 100644 --- a/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs +++ b/src/composition/editor/features/Inno.Editor.Exporting/Runtime/EditorExportService.cs @@ -177,7 +177,7 @@ private void EnsureIdle() /// protected override void OnUpdate(EditorContext context) { - while (m_progress.TryDequeue(out var update)) + while (m_progress.TryDequeue(out (long operation, BuildProgress value) update)) { if (update.operation != m_operation || m_cancellation is null || m_cancellation.IsCancellationRequested) { @@ -202,18 +202,12 @@ protected override void OnUpdate(EditorContext context) /// /// The active Editor context being stopped. /// - protected override void OnStop(EditorContext context) - { - RetireExports(); - } + protected override void OnStop(EditorContext context) => RetireExports(); /// /// Drains export cleanup before releasing cancellation resources owned by this module. /// - protected override void OnDispose() - { - RetireExports(); - } + protected override void OnDispose() => RetireExports(); private void RetireExports() { diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs index 5c13858a1..cdede9453 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeController.cs @@ -120,16 +120,16 @@ public EditorPlayModeController( /// public bool isPlaying => m_state == EditorPlayModeState.Playing; - /// + /// bool IEditorReloadGuard.canRequestReload => !m_disposed && m_state == EditorPlayModeState.Editing; - /// + /// bool IEditorReloadGuard.canActivateReload => !m_disposed && m_state is EditorPlayModeState.Editing or EditorPlayModeState.Compiling && m_runtimeSession is null && m_sceneLease is null && m_generationLease is null; - /// + /// string? IEditorReloadGuard.blockingReason => m_state == EditorPlayModeState.Editing ? null @@ -145,7 +145,7 @@ bool IEditorReloadGuard.canActivateReload /// public LogSessionId activeSessionId => m_activeSessionId; - /// + /// public IDisposable ListenStateChanges(Action listener) { ObjectDisposedException.ThrowIf(m_disposed, this); diff --git a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs index dc0cd7807..f44224d33 100644 --- a/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs +++ b/src/composition/editor/features/Inno.Editor.PlayMode/Runtime/EditorPlayModeModule.cs @@ -67,7 +67,7 @@ public override bool blocksFollowingUpdates /// public LogSessionId activeSessionId => m_controller.activeSessionId; - /// + /// public IDisposable ListenStateChanges(Action listener) => m_controller.ListenStateChanges(listener); /// diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs index 98864c8e7..b16dfc860 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs @@ -5,6 +5,7 @@ using System.Threading; using Inno.Assets; using Inno.Core.Diagnostics; +using Inno.Core.Execution; using Inno.Core.Graphs; using Inno.Rendering; using Inno.Rendering.Assets; @@ -104,22 +105,25 @@ GraphicsCapabilities capabilities ), entry.cancellation.Token); } } - catch (Exception failure) when (Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when (RetirementPendingException.Find(failure) is null) { Retire(entry.pending, entry.cancellation); - entry.pending = null; entry.cancellation = null; entry.semanticHash = ""; + entry.pending = null; + entry.cancellation = null; + entry.semanticHash = string.Empty; entry.latestSucceeded = false; entry.sourceDiagnostics = [new("SHADER_PREVIEW_CAPTURE", DiagnosticSeverity.Error, failure.Message)]; } } if (entry.pending is { IsCompleted: true } pending) { - if (pending.Exception is Exception failure && Inno.Core.Execution.RetirementPendingException.Find(failure) is not null) + if (pending.Exception is Exception failure && RetirementPendingException.Find(failure) is not null) { throw failure; } entry.pending = null; - entry.cancellation?.Dispose(); entry.cancellation = null; + entry.cancellation?.Dispose(); + entry.cancellation = null; ShaderCompilationResult result = pending.IsCompletedSuccessfully ? pending.Result : new( null, [new( @@ -164,7 +168,7 @@ private sealed class DraftEntry internal bool attempted; internal ulong revision; internal long assetRevision; - internal string targetVariant = ""; + internal string targetVariant = string.Empty; internal readonly ShaderEntry compilation = new(); } } diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs index 0d00a85ee..d43080d54 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.cs @@ -2,11 +2,13 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Diagnostics; +using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Rendering; @@ -30,7 +32,7 @@ public sealed partial class EditorRenderTargetArtifactProvider : IRenderTargetAr private readonly ITextureTargetCompiler m_textureCompiler; private readonly IDiagnosticReporter m_diagnostics; private readonly CancellationTokenSource m_lifetime = new(); - private readonly Inno.Core.Execution.LifetimeScope m_work = new(); + private readonly LifetimeScope m_work = new(); private readonly Dictionary m_shaders = []; private readonly Dictionary m_textures = []; private bool m_disposed; @@ -39,15 +41,18 @@ public sealed partial class EditorRenderTargetArtifactProvider : IRenderTargetAr /// /// Creates an Editor artifact provider backed by explicit shader and texture toolchains. /// - /// - /// The compiler that turns backend-neutral shader IR into device target programs. - /// /// /// The authoring asset pipeline that owns source mounts. /// /// /// The serialization registry that owns active Shader contracts. /// + /// + /// The shared authoring type generation owner for graph and source extensions. + /// + /// + /// The compiler that turns backend-neutral shader IR into device target programs. + /// /// /// The compiler that turns artist texture sources into portable KTX artifacts. /// @@ -57,9 +62,6 @@ public sealed partial class EditorRenderTargetArtifactProvider : IRenderTargetAr /// /// Thrown when any required service is null. /// - /// - /// The shared authoring type generation owner for graph and source extensions. - /// public EditorRenderTargetArtifactProvider( AssetPipeline assets, SerializationRegistry serialization, @@ -312,7 +314,7 @@ ShaderEntry entry token ), token); } - catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) + catch (Exception exception) when (RetirementPendingException.Find(exception) is null) { entry.cancellation.Dispose(); entry.cancellation = null; @@ -334,7 +336,7 @@ ShaderEntry entry { return; } - if (pending.Exception is Exception failure && Inno.Core.Execution.RetirementPendingException.Find(failure) is not null) + if (pending.Exception is Exception failure && RetirementPendingException.Find(failure) is not null) { throw failure; } @@ -357,7 +359,7 @@ [new ShaderDiagnostic( ); entry.latestSucceeded = result.succeeded; entry.sourceDiagnostics = Array.AsReadOnly(result.diagnostics.ToArray()); - var diagnostics = result.diagnostics + List diagnostics = result.diagnostics .Select(diagnostic => new Diagnostic( diagnostic.code, diagnostic.message, @@ -423,7 +425,7 @@ TextureEntry entry ).ConfigureAwait(false); }, token); } - catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) + catch (Exception exception) when (RetirementPendingException.Find(exception) is null) { entry.cancellation.Dispose(); entry.cancellation = null; @@ -440,7 +442,7 @@ TextureEntry entry { return; } - if (pending.Exception is Exception failure && Inno.Core.Execution.RetirementPendingException.Find(failure) is not null) + if (pending.Exception is Exception failure && RetirementPendingException.Find(failure) is not null) { throw failure; } @@ -489,7 +491,7 @@ CancellationToken token { return (await operation(cancellation).ConfigureAwait(false), null); } - catch (Exception failure) when (Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when (RetirementPendingException.Find(failure) is null) { return (default!, failure); } @@ -498,10 +500,10 @@ CancellationToken token static async Task Unwrap(Task<(T value, Exception? failure)> task) { - var result = await task.ConfigureAwait(false); + (T value, Exception? failure) result = await task.ConfigureAwait(false); if (result.failure is not null) { - System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(result.failure).Throw(); + ExceptionDispatchInfo.Capture(result.failure).Throw(); } return result.value; } @@ -586,7 +588,7 @@ private readonly record struct DiagnosticIdentity( private sealed class ShaderEntry { - internal string semanticHash { get; set; } = ""; + internal string semanticHash { get; set; } = string.Empty; internal long extensionGeneration { get; set; } = long.MinValue; internal bool latestSucceeded { get; set; } internal IReadOnlyList sourceDiagnostics { get; set; } = Array.Empty(); diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs index d0d3cd23d..8a439bac6 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs @@ -2,6 +2,7 @@ using System.IO; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Editor.Assets; using Inno.Editor.Core; @@ -9,6 +10,7 @@ using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; +using Inno.Scripting.Api; namespace Inno.Editor.Rendering; @@ -24,19 +26,19 @@ public sealed class PipelineDocuments : EditorModule /// /// Gets the authoritative asset pipeline used by source inspectors. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetPipeline assets { get; } /// /// Gets the current owner serialization registry. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public SerializationRegistry serialization { get; } /// /// Gets the source draft owner shared by Pipeline inspectors. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetDraftDocuments drafts { get; } internal PipelineDocuments( @@ -48,7 +50,7 @@ EditorInteractions interactions this.assets = assets; this.serialization = serialization; m_types = types; - drafts = new(assets, serialization, interactions, "inno.pipeline", C_HISTORY, ".irenderpipeline", "Pipeline"); + this.drafts = new(assets, serialization, interactions, "inno.pipeline", C_HISTORY, ".irenderpipeline", "Pipeline"); } /// @@ -126,7 +128,7 @@ public void ReplaceSettings( /// /// The detached settings, or null when the extension is temporarily unavailable. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public ISerializable? RestoreSettings(SerializedRenderExtensionState state) { if (state.stableTypeId == Guid.Empty) @@ -144,7 +146,7 @@ public void ReplaceSettings( internal static bool Recoverable(Exception error) => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException - && Inno.Core.Execution.RetirementPendingException.Find(error) is null; + && RetirementPendingException.Find(error) is null; /// /// Initializes this feature when its owning runtime becomes active. diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs index aab674f14..2825c18af 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs @@ -335,7 +335,7 @@ private byte[] ComputeSceneHash( { return document.observedHash!; } - using var algorithm = SHA256.Create(); + using SHA256 algorithm = SHA256.Create(); using (var digest = new CryptoStream(Stream.Null, algorithm, CryptoStreamMode.Write, leaveOpen: true)) using (var output = new BufferedStream(digest, 64 * 1024)) { @@ -373,7 +373,7 @@ string extension private static string CreateUniqueSceneName(IReadOnlyList scenes) { const string c_baseName = "Untitled Scene"; - var names = scenes.Select(static scene => scene.name).ToHashSet(StringComparer.Ordinal); + HashSet names = scenes.Select(static scene => scene.name).ToHashSet(StringComparer.Ordinal); if (!names.Contains(c_baseName)) { return c_baseName; @@ -397,7 +397,7 @@ private static string GetAssetName(string relativePath) private static string SanitizeFileName(string value) { char[] invalid = Path.GetInvalidFileNameChars(); - string sanitized = new( + var sanitized = new string( (value ?? string.Empty) .Trim() .Select(character => invalid.Contains(character) ? '_' : character) diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs index 5d1807e51..7a58e31c1 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.SourceChanges.cs @@ -71,7 +71,7 @@ string newRelativePath ) { string oldPath = NormalizePath(oldRelativePath); string newPath = NormalizePath(newRelativePath); - if (m_assets.TryGetFileSystemEntry(AssetPath.Parse(newPath), out Inno.Assets.Pipeline.AssetFileEntry entry) + if (m_assets.TryGetFileSystemEntry(AssetPath.Parse(newPath), out AssetFileEntry entry) && entry.isDirectory ) { ApplyDirectoryRename(oldPath, newPath); diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs index ef931eab1..8713e8c86 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Elements.cs @@ -12,7 +12,7 @@ namespace Inno.Editor.Scene; -sealed partial class SceneEdits +public sealed partial class SceneEdits { /// /// Adds one component and records its identity, stable type, index, and persistent properties. diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs index a9347be17..4dae805f0 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Hierarchy.cs @@ -12,7 +12,7 @@ namespace Inno.Editor.Scene; -sealed partial class SceneEdits +public sealed partial class SceneEdits { /// /// Moves a loaded scene to a hierarchy index and records the two integer positions. diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs index bbae50f7f..791d70209 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.History.cs @@ -12,7 +12,7 @@ namespace Inno.Editor.Scene; -sealed partial class SceneEdits +public sealed partial class SceneEdits { private void RecordDocument( string name, diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs index e14bb7fbb..35b8d1331 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Objects.cs @@ -12,7 +12,7 @@ namespace Inno.Editor.Scene; -sealed partial class SceneEdits +public sealed partial class SceneEdits { /// /// Creates a GameObject, optionally parents it, and records only the new subtree state. diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs index 34ff62aac..194972cbf 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Properties.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Runtime.ExceptionServices; using Inno.Core.Serialization; @@ -12,7 +13,7 @@ namespace Inno.Editor.Scene; -sealed partial class SceneEdits +public sealed partial class SceneEdits { /// /// Renames a loaded scene and records the two display strings. @@ -181,11 +182,9 @@ public void SetGameObjectLayer( ChangeScalar( gameObject, SceneScalarKind.GameObjectLayer, - gameObject.layer.index.ToString(System.Globalization.CultureInfo.InvariantCulture), - layer.index.ToString(System.Globalization.CultureInfo.InvariantCulture), - value => gameObject.layer = new GameLayer( - int.Parse(value, System.Globalization.CultureInfo.InvariantCulture) - ), + gameObject.layer.index.ToString(CultureInfo.InvariantCulture), + layer.index.ToString(CultureInfo.InvariantCulture), + value => gameObject.layer = new GameLayer(int.Parse(value, CultureInfo.InvariantCulture)), historyName, $"game-object-layer:{gameObject.identity.persistentId:N}" ); diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs index 231a07ae4..4c83cfee8 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/SceneEdits.Selection.cs @@ -6,10 +6,11 @@ using Inno.Core.Serialization; using Inno.Editor.Interactions; using Inno.Scene; +using Inno.Scene.Components; namespace Inno.Editor.Scene; -sealed partial class SceneEdits +public sealed partial class SceneEdits { /// /// Deletes selected subtrees atomically, omitting descendants already covered by a selected ancestor. @@ -34,7 +35,7 @@ public void DeleteGameObjects(IReadOnlyList targets) } } - var selected = unique.Select(value => value.identity.persistentId).ToHashSet(); + HashSet selected = unique.Select(value => value.identity.persistentId).ToHashSet(); GameObject[] roots = unique.Where(value => !HasSelectedAncestor(value, selected)).ToArray(); using EditorHistoryTransaction transaction = m_interactions.history.BeginTransaction("Delete GameObjects"); foreach (GameObject target in roots) @@ -224,13 +225,13 @@ public void MoveGameObjects( } } - var selected = unique.Select(value => value.identity.persistentId).ToHashSet(); + HashSet selected = unique.Select(value => value.identity.persistentId).ToHashSet(); GameObject[] roots = unique.Where(value => !HasSelectedAncestor(value, selected)).ToArray(); if (roots.Length == 0) { return; } - for (var ancestor = parent?.transform; ancestor is not null; ancestor = ancestor.parent) + for (Transform? ancestor = parent?.transform; ancestor is not null; ancestor = ancestor.parent) { if (selected.Contains(ancestor.gameObject.identity.persistentId)) { @@ -293,9 +294,15 @@ string componentName Vector3 value = existing.ToEulerAnglesXYZDegrees(); switch (componentName) { - case "euler.x": value.x = next.x; break; - case "euler.y": value.y = next.y; break; - case "euler.z": value.z = next.z; break; + case "euler.x": + value.x = next.x; + break; + case "euler.y": + value.y = next.y; + break; + case "euler.z": + value.z = next.z; + break; } return Quaternion.FromEulerAnglesXYZDegrees(value).normalized; } @@ -309,7 +316,7 @@ private static bool HasSelectedAncestor( GameObject target, ISet selected ) { - for (var parent = target.transform.parent; parent is not null; parent = parent.parent) + for (Transform? parent = target.transform.parent; parent is not null; parent = parent.parent) { if (selected.Contains(parent.gameObject.identity.persistentId)) { diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs index 7e3d2cca6..9f53363da 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneDocumentHistoryData.cs @@ -71,10 +71,10 @@ EditorSceneWorkspace.SceneDocumentSnapshot snapshot private static EditorSceneWorkspace.SceneDocumentSnapshot ReadSnapshot(BinaryReader reader) { - Guid sceneId = new(reader.ReadBytes(16)); + var sceneId = new Guid(reader.ReadBytes(16)); byte[] payload = ReadBytes(reader, "scene"); string sourcePath = reader.ReadString(); - Guid sourceAssetId = new(reader.ReadBytes(16)); + var sourceAssetId = new Guid(reader.ReadBytes(16)); byte[] savedHash = ReadBytes(reader, "saved hash"); bool isDirty = reader.ReadBoolean(); int sceneIndex = reader.ReadInt32(); diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs index 5199c018b..0f8416934 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryData.cs @@ -50,15 +50,15 @@ internal static SceneElementHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); - var elementKind = (SceneElementKind)reader.ReadByte(); + SceneElementKind elementKind = (SceneElementKind)reader.ReadByte(); if (!Enum.IsDefined(elementKind)) { throw new InvalidDataException($"Unknown scene element history kind '{elementKind}'."); } - Guid sceneId = new(reader.ReadBytes(16)); - Guid ownerId = new(reader.ReadBytes(16)); - Guid elementId = new(reader.ReadBytes(16)); - TypeRef type = new(new Guid(reader.ReadBytes(16))); + var sceneId = new Guid(reader.ReadBytes(16)); + var ownerId = new Guid(reader.ReadBytes(16)); + var elementId = new Guid(reader.ReadBytes(16)); + var type = new TypeRef(new Guid(reader.ReadBytes(16))); int beforeIndex = reader.ReadInt32(); int afterIndex = reader.ReadInt32(); bool existsBefore = reader.ReadBoolean(); diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs index ee6797686..db5963bbe 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneElementHistoryHandler.cs @@ -360,7 +360,7 @@ private EditorHistoryResult RollbackExisting( IReadOnlyList rollbackReferences, string failure ) { - var failures = new System.Collections.Generic.List(); + var failures = new List(); try { SceneElementSerialization.RestoreState( diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs index c5accbff4..3e3347c5c 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs @@ -30,7 +30,7 @@ internal static SceneHierarchyHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream); - Guid selectedId = new(reader.ReadBytes(16)); + var selectedId = new Guid(reader.ReadBytes(16)); SceneObjectPlacement[] before = ReadPlacements(reader); SceneObjectPlacement[] after = ReadPlacements(reader); if (stream.Position != stream.Length) @@ -69,8 +69,8 @@ private static SceneObjectPlacement[] ReadPlacements(BinaryReader reader) var placements = new SceneObjectPlacement[count]; for (int i = 0; i < placements.Length; i++) { - Guid sceneId = new(reader.ReadBytes(16)); - Guid objectId = new(reader.ReadBytes(16)); + var sceneId = new Guid(reader.ReadBytes(16)); + var objectId = new Guid(reader.ReadBytes(16)); Guid? parentId = reader.ReadBoolean() ? new Guid(reader.ReadBytes(16)) : null; placements[i] = new SceneObjectPlacement(sceneId, objectId, parentId, reader.ReadInt32()); } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs index b517badda..e932e1f97 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs @@ -55,7 +55,7 @@ internal static ScenePropertyHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); - Guid targetId = new(reader.ReadBytes(16)); + var targetId = new Guid(reader.ReadBytes(16)); string propertyName = reader.ReadString(); int count = reader.ReadInt32(); if (count <= 0) diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs index 7ab0268ff..9896d4045 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryData.cs @@ -36,8 +36,8 @@ internal static SceneScalarHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); - Guid targetId = new(reader.ReadBytes(16)); - var scalarKind = (SceneScalarKind)reader.ReadByte(); + var targetId = new Guid(reader.ReadBytes(16)); + SceneScalarKind scalarKind = (SceneScalarKind)reader.ReadByte(); if (!Enum.IsDefined(scalarKind)) { throw new InvalidDataException($"Unknown scene scalar history kind '{scalarKind}'."); diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs index 5fdf664a1..273748b79 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics; +using System.Globalization; using Inno.Editor.Interactions; using Inno.Scene; using Inno.Scene.Layers; @@ -184,9 +185,7 @@ SceneScalarKind kind SceneScalarKind.GameObjectName => ((GameObject)target).name, SceneScalarKind.GameObjectActive => ((GameObject)target).activeSelf ? "1" : "0", SceneScalarKind.GameObjectTag => ((GameObject)target).tag, - SceneScalarKind.GameObjectLayer => ((GameObject)target).layer.index.ToString( - System.Globalization.CultureInfo.InvariantCulture - ), + SceneScalarKind.GameObjectLayer => ((GameObject)target).layer.index.ToString(CultureInfo.InvariantCulture), _ => throw new InvalidOperationException($"Unsupported scene scalar '{kind}'.") }; @@ -210,9 +209,7 @@ string value ((GameObject)target).tag = value; break; case SceneScalarKind.GameObjectLayer: - ((GameObject)target).layer = new GameLayer( - int.Parse(value, System.Globalization.CultureInfo.InvariantCulture) - ); + ((GameObject)target).layer = new GameLayer(int.Parse(value, CultureInfo.InvariantCulture)); break; default: throw new InvalidOperationException($"Unsupported scene scalar '{kind}'."); diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs index a3b6259c5..50c70d42b 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneSubtreeHistoryData.cs @@ -45,8 +45,8 @@ internal static SceneSubtreeHistoryData Decode(ReadOnlySpan bytes) { using var stream = new MemoryStream(bytes.ToArray(), writable: false); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); - Guid sceneId = new(reader.ReadBytes(16)); - Guid rootId = new(reader.ReadBytes(16)); + var sceneId = new Guid(reader.ReadBytes(16)); + var rootId = new Guid(reader.ReadBytes(16)); Guid? parentId = ReadGuid(reader); int siblingIndex = reader.ReadInt32(); bool existsBefore = reader.ReadBoolean(); diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs index 6eb070eb5..51c340122 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/EditorScripting.cs @@ -199,10 +199,10 @@ internal void ReloadPlugins() } } - /// /// /// The observed request identity; stale actions are ignored. /// + /// public void CancelCompilation(long operationId) { if (m_manager?.progress.operationId == operationId) diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs index 4648b5c37..cb8f7ea68 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs @@ -4,6 +4,7 @@ using System.Runtime.CompilerServices; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Editor.Assets; @@ -13,6 +14,7 @@ using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; +using Inno.Scripting.Api; using Draft = Inno.Editor.Assets.AssetDraftDocuments.Draft; @@ -32,7 +34,7 @@ public sealed class MaterialDocuments : EditorModule /// /// Gets the authoritative asset catalog used by source-aware inspectors. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetPipeline assets { get; } internal readonly EditorInteractions interactions; @@ -40,7 +42,7 @@ public sealed class MaterialDocuments : EditorModule /// /// Gets the generation-scoped preview service shared by material presentations. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public IEditorPreviewService previews { get; } internal MaterialDocuments( @@ -119,7 +121,7 @@ public void ReplaceMany( /// /// The generation-scoped draft; callers must not retain it across a reload. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public Draft OpenDraft(AssetPath path) => m_documents.GetDraft(Open(path)); /// @@ -131,7 +133,7 @@ public void ReplaceMany( /// /// The generation-scoped editable source draft. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public Draft Open(MaterialAsset material) { if (!assets.TryGetInfo(material.identity.persistentId, out AssetInfo? info) || info is null) @@ -156,7 +158,7 @@ public Draft Open(MaterialAsset material) /// /// Detached presentation values; an unavailable graph uses the ordinary presentation defaults. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public ShaderParameterPresentation Presentation( ShaderAsset shader, ShaderPropertyId propertyId, @@ -167,7 +169,7 @@ out string error { cache.contentVersion = shader.contentVersion; cache.graph = null; - cache.error = ""; + cache.error = string.Empty; try { cache.graph = ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(shader, assets), m_serialization); @@ -202,7 +204,7 @@ out EditorHistoryChange? merged internal static bool Recoverable(Exception error) => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException - && Inno.Core.Execution.RetirementPendingException.Find(error) is null; + && RetirementPendingException.Find(error) is null; /// /// Initializes this feature when its owning runtime becomes active. @@ -236,7 +238,7 @@ private sealed class PresentationCache { internal long contentVersion = -1; internal GraphDocument? graph; - internal string error = ""; + internal string error = string.Empty; } } diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs index b851cfaf2..790410575 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/ShaderParameterPresentation.cs @@ -16,32 +16,38 @@ public sealed class ShaderParameterPresentation : ISerializable /// /// Gets or sets the Material Inspector section; empty uses the standard Parameters section. /// - [SerializableProperty] public string group { get; set; } = ""; + [SerializableProperty] + public string group { get; set; } = string.Empty; /// /// Gets or sets the hover description without adding a permanent paragraph. /// - [SerializableProperty] public string description { get; set; } = ""; + [SerializableProperty] + public string description { get; set; } = string.Empty; /// /// Gets or sets whether this Material-owned parameter appears in ordinary Material Inspectors. /// - [SerializableProperty] public bool visible { get; set; } = true; + [SerializableProperty] + public bool visible { get; set; } = true; /// /// Gets or sets whether a scalar Float control uses the declared editing bounds. /// - [SerializableProperty] public bool hasRange { get; set; } + [SerializableProperty] + public bool hasRange { get; set; } /// /// Gets or sets the inclusive editing minimum; existing values are not changed by presentation metadata. /// - [SerializableProperty] public double minimum { get; set; } + [SerializableProperty] + public double minimum { get; set; } /// /// Gets or sets the inclusive editing maximum. /// - [SerializableProperty] public double maximum { get; set; } = 1; + [SerializableProperty] + public double maximum { get; set; } = 1; /// /// Reads detached presentation for one binding, defaulting only when no presentation was authored. diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs index 10d17cd8d..4f33528ad 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs @@ -83,11 +83,19 @@ int pixelHeight { throw new ArgumentException("A resource identity is required.", nameof(resourceId)); } - ArgumentNullException.ThrowIfNull(material); ArgumentNullException.ThrowIfNull(artifact); - ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(diagnostics); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); - this.resourceId = resourceId; this.material = material; this.artifact = artifact; this.definition = definition; - this.diagnostics = diagnostics; this.pixelWidth = pixelWidth; this.pixelHeight = pixelHeight; + ArgumentNullException.ThrowIfNull(material); + ArgumentNullException.ThrowIfNull(artifact); + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(diagnostics); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); + this.resourceId = resourceId; + this.material = material; + this.artifact = artifact; + this.definition = definition; + this.diagnostics = diagnostics; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; } /// diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs index bdb316f92..d146a2686 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModal.cs @@ -1,3 +1,4 @@ +using System; using System.Numerics; using Inno.Scripting.Api; @@ -58,7 +59,7 @@ public abstract class EditorModal [ScriptingApiIgnore] public void Draw(EditorContext context) { - System.ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(context); OnDraw(context); } @@ -86,11 +87,11 @@ public void Draw(EditorContext context) EditorContext context, Vector2 availableContentSize ) { - System.ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(context); if (!float.IsFinite(availableContentSize.X) || !float.IsFinite(availableContentSize.Y) || availableContentSize.X <= 0f || availableContentSize.Y <= 0f ) { - throw new System.ArgumentOutOfRangeException(nameof(availableContentSize)); + throw new ArgumentOutOfRangeException(nameof(availableContentSize)); } return OnPrepare(context, availableContentSize); } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs index 2d3531cd5..99bab1e17 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorModule.cs @@ -86,9 +86,6 @@ public void Update(EditorContext context) /// /// Stops the module before the containing extension generation is released. /// - /// - /// Also compensates a partially failed Start. Completed stops are idempotent; pending stops may be retried. - /// /// /// The shared editor context for the runtime being stopped. /// @@ -101,6 +98,9 @@ public void Update(EditorContext context) /// /// Live work still depends on this module. Its owner must retain it and retry Stop before disposal. /// + /// + /// Also compensates a partially failed Start. Completed stops are idempotent; pending stops may be retried. + /// [ScriptingApiIgnore] public void Stop(EditorContext context) { @@ -148,39 +148,39 @@ protected virtual void OnUpdate(EditorContext context) {} /// /// Runs before the module generation is released and its disposable instances are destroyed. /// + /// + /// The shared editor context for the runtime being stopped. + /// /// /// This includes partial startup compensation. Pending retirement must throw RetirementPendingException /// and preserve unfinished ownership; completed steps must be idempotent across retries. /// - /// - /// The shared editor context for the runtime being stopped. - /// protected virtual void OnStop(EditorContext context) {} /// /// Captures readable project state owned by this module. /// + /// + /// The writable parameter that receives the complete readable state for this module. + /// /// /// Overriding this method opts the module into project-state IO. Modules that keep the base /// implementation are never registered with the persistence coordinator and therefore perform /// no state reads or writes. /// - /// - /// The writable parameter that receives the complete readable state for this module. - /// protected virtual void Capture(EditorState state) {} /// /// Restores readable project state owned by this module. /// - /// - /// This method is called only when is overridden. It runs once after the - /// module is started and before the module is allowed to capture replacement state. - /// /// /// The read-only state parameter for this module. Missing or incompatible values return the /// fallback supplied to . /// + /// + /// This method is called only when is overridden. It runs once after the + /// module is started and before the module is allowed to capture replacement state. + /// protected virtual void Restore(EditorState state) {} /// diff --git a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs index a369f3bcd..084e53238 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Extensions/EditorPanel.cs @@ -66,9 +66,6 @@ public void Attach(EditorContext context) /// /// Detaches the panel before its extension generation is released. /// - /// - /// Also compensates partial attachment. Completed detachment is idempotent; a pending panel cannot draw. - /// /// /// The shared editor context for the runtime being detached. /// @@ -78,6 +75,9 @@ public void Attach(EditorContext context) /// /// Panel work is still active. The owner must retain the panel and its dependencies and retry detachment. /// + /// + /// Also compensates partial attachment. Completed detachment is idempotent; a pending panel cannot draw. + /// [ScriptingApiIgnore] public void Detach(EditorContext context) { @@ -145,38 +145,38 @@ protected virtual void OnAttach(EditorContext context) {} /// /// Runs before the panel is detached from its active extension generation. /// + /// + /// The shared editor context for the runtime being detached. + /// /// /// This includes failed attachment compensation. Retain unfinished resources when throwing /// RetirementPendingException and avoid repeating completed cleanup steps on the next attempt. /// - /// - /// The shared editor context for the runtime being detached. - /// protected virtual void OnDetach(EditorContext context) {} /// /// Captures readable project state owned by this panel. /// + /// + /// The writable parameter that receives the complete readable state for this panel. + /// /// /// Overriding this method opts the panel into project-state IO. Panels that keep the base /// implementation are never registered with the persistence coordinator and therefore perform /// no state reads or writes. Panel visibility is persisted separately for every registered panel. /// - /// - /// The writable parameter that receives the complete readable state for this panel. - /// protected virtual void Capture(EditorState state) {} /// /// Restores readable project state owned by this panel. /// - /// - /// This method is called only when is overridden. It runs once after the - /// panel is attached and before the panel is allowed to capture replacement state. - /// /// /// The read-only state parameter for this panel. Missing or incompatible values return the /// fallback supplied to . /// + /// + /// This method is called only when is overridden. It runs once after the + /// panel is attached and before the panel is allowed to capture replacement state. + /// protected virtual void Restore(EditorState state) {} } diff --git a/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs b/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs index c79a4c950..f0fc0d8b1 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Reloading/EditorReloadCoordinator.cs @@ -342,7 +342,7 @@ IEditorReloadGuard guard internal Guid id { get; } = id; - /// + /// public void Dispose() { IEditorReloadGuard? retained = m_guard; diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs index ce6ceae03..ef7f6efd4 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorContext.cs @@ -49,8 +49,8 @@ public EditorContext( ArgumentNullException.ThrowIfNull(keyboard); this.keyboard = keyboard; this.projectDirectory = Path.GetFullPath(projectDirectory); - layout = new EditorLayoutSettings(this.projectDirectory, initialLayoutDocument); - statistics = new EditorStatistics(); + this.layout = new EditorLayoutSettings(this.projectDirectory, initialLayoutDocument); + this.statistics = new EditorStatistics(); } /// diff --git a/src/composition/editor/framework/Inno.Editor.Diagnostics/ConsoleFingerprint.cs b/src/composition/editor/framework/Inno.Editor.Diagnostics/ConsoleFingerprint.cs index 926e0a3b7..d1d4681bf 100644 --- a/src/composition/editor/framework/Inno.Editor.Diagnostics/ConsoleFingerprint.cs +++ b/src/composition/editor/framework/Inno.Editor.Diagnostics/ConsoleFingerprint.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Security.Cryptography; using System.Text; @@ -17,8 +18,8 @@ internal static string Create(EditorConsoleOccurrence occurrence) Append(builder, occurrence.category); Append(builder, occurrence.message); Append(builder, occurrence.file); - Append(builder, occurrence.line.ToString(System.Globalization.CultureInfo.InvariantCulture)); - Append(builder, occurrence.column.ToString(System.Globalization.CultureInfo.InvariantCulture)); + Append(builder, occurrence.line.ToString(CultureInfo.InvariantCulture)); + Append(builder, occurrence.column.ToString(CultureInfo.InvariantCulture)); Append(builder, occurrence.stackTrace); Append(builder, occurrence.sessionId.ToString()); return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(builder.ToString()))); diff --git a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleGroup.cs b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleGroup.cs index d64755925..777742287 100644 --- a/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleGroup.cs +++ b/src/composition/editor/framework/Inno.Editor.Diagnostics/EditorConsoleGroup.cs @@ -14,7 +14,7 @@ EditorConsoleOccurrence[] occurrences ) { this.identity = identity; this.occurrences = Array.AsReadOnly(occurrences); - latest = occurrences[^1]; + this.latest = occurrences[^1]; } /// diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs index 2d2c65d42..69c183a4c 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphCanvasState.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Frozen; using System.Collections.Generic; +using System.Numerics; using Inno.Core.Graphs; using Inno.Editor.Interactions; @@ -109,7 +110,7 @@ float pivotY } float next = Math.Clamp(zoom * factor, 0.1f, 4f); - System.Numerics.Vector2 origin = EditorPlanarNavigation.ZoomOrigin(new(pan.x, pan.y), new(pivotX, pivotY), zoom, next); + Vector2 origin = EditorPlanarNavigation.ZoomOrigin(new(pan.x, pan.y), new(pivotX, pivotY), zoom, next); pan = new GraphPosition(origin.X, origin.Y); zoom = next; } diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs index 1a67f38ee..65800bb7e 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs @@ -13,7 +13,10 @@ namespace Inno.Editor.Graph; /// public sealed class GraphClipboardData { - internal GraphClipboardData(GraphDocument fragment) => m_fragment = fragment; + internal GraphClipboardData(GraphDocument fragment) + { + m_fragment = fragment; + } private readonly GraphDocument m_fragment; @@ -365,12 +368,12 @@ public GraphClipboardData Copy(IEnumerable nodeIds) /// /// Offset added to every copied node position. /// - /// - /// New node identities in clipboard document order. - /// /// /// Optional synchronous domain remapping of neutral node values after identity allocation. The callback is never stored in History. /// + /// + /// New node identities in clipboard document order. + /// public IReadOnlyList Paste( GraphClipboardData clipboard, GraphPosition offset, @@ -431,7 +434,7 @@ Action mutation return; } - var change = GraphHistoryData.CreateChange(documentId, before, after, mergeKey); + EditorHistoryChange change = GraphHistoryData.CreateChange(documentId, before, after, mergeKey); try { m_history.RecordApplied(name, change); diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs index 2e02fb7fe..04a69c41e 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs @@ -96,7 +96,7 @@ public static EditorHistoryChange CreateChange( public byte[] Encode() { byte[] id = S_UTF8.GetBytes(documentId.ToString("D")); - byte[] result = new byte[checked((sizeof(int) * 3) + sizeof(long) + id.Length + before.Length + after.Length)]; + var result = new byte[checked((sizeof(int) * 3) + sizeof(long) + id.Length + before.Length + after.Length)]; Span span = result; BinaryPrimitives.WriteInt32LittleEndian(span, id.Length); id.CopyTo(span[sizeof(int)..]); diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs index e26cacf9a..4d9b0c7d1 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Globalization; +using System.Numerics; using System.Reflection; using Inno.Core.Serialization; using Inno.Editor.Annotations; @@ -23,7 +24,7 @@ internal sealed class HeaderInspectorAttributeDrawer : IInspectorAttributeDrawer /// public void DrawBefore(InspectorAttributeDrawContext context) { - var header = (HeaderAttribute)context.attribute; + HeaderAttribute header = (HeaderAttribute)context.attribute; EditorUI.current.widgets.SectionHeader(header.title, header.description); } } @@ -64,7 +65,7 @@ internal sealed class SpaceInspectorAttributeDrawer : IInspectorAttributeDrawer public void DrawBefore(InspectorAttributeDrawContext context) { float height = ((SpaceAttribute)context.attribute).height; - Ui.Dummy(new System.Numerics.Vector2(0f, height)); + Ui.Dummy(new Vector2(0f, height)); } } @@ -103,7 +104,7 @@ internal sealed class RangeInspectorAttributeDrawer : IInspectorAttributeDrawer /// public void Update(InspectorAttributeDrawContext context) { - var range = (RangeAttribute)context.attribute; + RangeAttribute range = (RangeAttribute)context.attribute; context.minimum = range.minimum; context.maximum = range.maximum; } @@ -132,7 +133,7 @@ internal sealed class ShowIfInspectorAttributeDrawer : IInspectorAttributeDrawer /// public void Update(InspectorAttributeDrawContext context) { - var condition = (ShowIfAttribute)context.attribute; + ShowIfAttribute condition = (ShowIfAttribute)context.attribute; context.isVisible &= InspectorConditionEvaluator.Evaluate( context.GetSiblingValue(condition.memberName), condition.condition, @@ -152,7 +153,7 @@ internal sealed class HideIfInspectorAttributeDrawer : IInspectorAttributeDrawer /// public void Update(InspectorAttributeDrawContext context) { - var condition = (HideIfAttribute)context.attribute; + HideIfAttribute condition = (HideIfAttribute)context.attribute; context.isVisible &= !InspectorConditionEvaluator.Evaluate( context.GetSiblingValue(condition.memberName), condition.condition, @@ -172,7 +173,7 @@ internal sealed class HelpBoxInspectorAttributeDrawer : IInspectorAttributeDrawe /// public void DrawBefore(InspectorAttributeDrawContext context) { - var help = (HelpBoxAttribute)context.attribute; + HelpBoxAttribute help = (HelpBoxAttribute)context.attribute; if (!string.IsNullOrWhiteSpace(help.conditionMember) && !InspectorConditionEvaluator.Evaluate( context.GetSiblingValue(help.conditionMember), @@ -183,11 +184,11 @@ public void DrawBefore(InspectorAttributeDrawContext context) return; } - System.Numerics.Vector4 color = help.messageType switch + Vector4 color = help.messageType switch { InspectorMessageType.Warning => EditorPalette.warning, InspectorMessageType.Error => EditorPalette.error, - _ => new System.Numerics.Vector4(0.42f, 0.66f, 0.88f, EditorPalette.opacityOpaque) + _ => new Vector4(0.42f, 0.66f, 0.88f, EditorPalette.opacityOpaque) }; string icon = help.messageType switch { @@ -205,32 +206,28 @@ internal static bool Evaluate( object? value, InspectorCondition condition, object? expected - ) { - return condition switch - { - InspectorCondition.Truthy => IsTruthy(value), - InspectorCondition.Falsy => !IsTruthy(value), - InspectorCondition.Equal => AreEqual(value, expected), - InspectorCondition.NotEqual => !AreEqual(value, expected), - InspectorCondition.Null => value is null, - InspectorCondition.NotNull => value is not null, - InspectorCondition.Assigned => IsAssigned(value), - InspectorCondition.NotAssigned => !IsAssigned(value), - _ => throw new ArgumentOutOfRangeException(nameof(condition), condition, "Unknown Inspector condition.") - }; - } + ) => condition switch + { + InspectorCondition.Truthy => IsTruthy(value), + InspectorCondition.Falsy => !IsTruthy(value), + InspectorCondition.Equal => AreEqual(value, expected), + InspectorCondition.NotEqual => !AreEqual(value, expected), + InspectorCondition.Null => value is null, + InspectorCondition.NotNull => value is not null, + InspectorCondition.Assigned => IsAssigned(value), + InspectorCondition.NotAssigned => !IsAssigned(value), + _ => throw new ArgumentOutOfRangeException(nameof(condition), condition, "Unknown Inspector condition.") + }; private static bool IsTruthy(object? value) + => value switch { - return value switch - { - null => false, - bool boolean => boolean, - string text => !string.IsNullOrWhiteSpace(text), - ICollection collection => collection.Count > 0, - _ => true - }; - } + null => false, + bool boolean => boolean, + string text => !string.IsNullOrWhiteSpace(text), + ICollection collection => collection.Count > 0, + _ => true + }; private static bool IsAssigned(object? value) { diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs index 97e9bebb1..9fef04ea8 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorMemberMetadata.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; +using Inno.Editor.Annotations; namespace Inno.Editor.Inspection; @@ -38,7 +39,7 @@ private static Attribute[] BuildAttributes(MemberInfo member) index ) => new OrderedAttribute( attribute, - attribute is Inno.Editor.Annotations.InspectorPresentationAttribute presentation + attribute is InspectorPresentationAttribute presentation ? presentation.order : 0, index @@ -50,7 +51,10 @@ attribute is Inno.Editor.Annotations.InspectorPresentationAttribute presentation private sealed class AttributesBox { - internal AttributesBox(MemberInfo member) => attributes = BuildAttributes(member); + internal AttributesBox(MemberInfo member) + { + this.attributes = BuildAttributes(member); + } internal Attribute[] attributes { get; } } @@ -75,7 +79,7 @@ internal TypeMembers(Type runtimeType) } } } - members = result; + this.members = result; } internal IReadOnlyDictionary members { get; } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs index 4e37481c1..5b7b5ebd7 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/DefaultInspectionDrawer.cs @@ -56,7 +56,5 @@ object target protected override void Draw( InspectionDrawContext context, object target - ) { - context.DrawProperties(); - } + ) => context.DrawProperties(); } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs index 9de71168a..1209fb98d 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/EditorCollectionUtility.cs @@ -337,16 +337,14 @@ params Type[] candidateArgumentTypes private static MethodInfo? FindFactory( Type targetType, Type argumentType - ) { - return targetType - .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) - .FirstOrDefault(method => ( - (method.Name == "CreateRange" || method.Name == "Create") - && targetType.IsAssignableFrom(method.ReturnType) - && method.GetParameters().Length == 1 - && method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType) - )); - } + ) => targetType + .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) + .FirstOrDefault(method => ( + (method.Name == "CreateRange" || method.Name == "Create") + && targetType.IsAssignableFrom(method.ReturnType) + && method.GetParameters().Length == 1 + && method.GetParameters()[0].ParameterType.IsAssignableFrom(argumentType) + )); private static MethodInfo? ResolveSequenceAddMethod( Type targetType, diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs index a32785f4c..8d21a2a21 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs @@ -22,18 +22,14 @@ internal static bool Float( string label, ref float value, float width - ) { - return EditorUI.current.widgets.AxisDragFloat(path, label, ref value, width); - } + ) => EditorUI.current.widgets.AxisDragFloat(path, label, ref value, width); internal static bool Int( string path, string label, ref int value, float width - ) { - return EditorUI.current.widgets.AxisDragInt(path, label, ref value, width); - } + ) => EditorUI.current.widgets.AxisDragInt(path, label, ref value, width); internal static void Next() => Ui.SameLine(0f, -1f); } @@ -301,12 +297,12 @@ public void Draw(PropertyDrawContext context) { Color value = context.GetValue() is Color current ? current : default; var nativeValue = new NumericsVector4(value.r, value.g, value.b, value.a); - var flags = context.hdrColor - ? Inno.Editor.ImGui.ImGuiColorEditFlags.Hdr - | Inno.Editor.ImGui.ImGuiColorEditFlags.Float - | Inno.Editor.ImGui.ImGuiColorEditFlags.InputRgb - | Inno.Editor.ImGui.ImGuiColorEditFlags.DisplayRgb - : Inno.Editor.ImGui.ImGuiColorEditFlags.None; + ImGuiColorEditFlags flags = context.hdrColor + ? ImGuiColorEditFlags.Hdr + | ImGuiColorEditFlags.Float + | ImGuiColorEditFlags.InputRgb + | ImGuiColorEditFlags.DisplayRgb + : ImGuiColorEditFlags.None; if (Ui.ColorEditLinear4($"##{context.path}", ref nativeValue, flags)) { context.SetValue(new Color(nativeValue.X, nativeValue.Y, nativeValue.Z, nativeValue.W)); diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs index 40be33cde..a77b85a13 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/PropertyDrawerRegistry.cs @@ -186,7 +186,7 @@ IReadOnlyList drawerServices throw new InvalidOperationException($"Property drawer '{type.FullName}' must declare exactly one constructor."); } ParameterInfo[] parameters = constructors[0].GetParameters(); - object?[] arguments = new object?[parameters.Length]; + var arguments = new object?[parameters.Length]; for (int index = 0; index < parameters.Length; index++) { Type parameterType = parameters[index].ParameterType; diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs index a27c63b47..0807deaba 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/SerializedPropertyRenderer.cs @@ -265,7 +265,14 @@ SerializedProperty property { return (true, readOnly); } - var context = new InspectorAttributeDrawContext(owner, member, property, property.name, property.name, readOnly); + var context = new InspectorAttributeDrawContext( + owner, + member, + property, + property.name, + property.name, + readOnly + ); m_attributes.Update(context, InspectorMemberMetadata.GetAttributes(member)); return (context.isVisible, context.isReadOnly); } diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs index e94f016e3..c124f13af 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/StructPropertyDrawer.cs @@ -64,8 +64,7 @@ public void Draw(PropertyDrawContext context) } private static MemberInfo[] GetMembers(Type type) - { - return S_MEMBER_CACHE.GetValue( + => S_MEMBER_CACHE.GetValue( type, static value => new MembersBox( value @@ -75,7 +74,6 @@ private static MemberInfo[] GetMembers(Type type) .ToArray() ) ).members; - } private static bool IsRuntimeVisibleMember(MemberInfo member) { @@ -97,41 +95,33 @@ private static bool IsRuntimeVisibleMember(MemberInfo member) } private static PropertyVisibility GetVisibility(MemberInfo member) - { - return member.GetCustomAttribute(true)?.propertyVisibility ?? PropertyVisibility.Show; - } + => member.GetCustomAttribute(true)?.propertyVisibility ?? PropertyVisibility.Show; private static Type GetMemberType(MemberInfo member) + => member switch { - return member switch - { - FieldInfo field => field.FieldType, - PropertyInfo property => property.PropertyType, - _ => throw new InvalidOperationException($"Unsupported struct member '{member.MemberType}'.") - }; - } + FieldInfo field => field.FieldType, + PropertyInfo property => property.PropertyType, + _ => throw new InvalidOperationException($"Unsupported struct member '{member.MemberType}'.") + }; private static object? GetMemberValue( MemberInfo member, object target - ) { - return member switch - { - FieldInfo field => field.GetValue(target), - PropertyInfo property => property.GetValue(target), - _ => null - }; - } + ) => member switch + { + FieldInfo field => field.GetValue(target), + PropertyInfo property => property.GetValue(target), + _ => null + }; private static bool CanWrite(MemberInfo member) + => member switch { - return member switch - { - FieldInfo field => !field.IsInitOnly, - PropertyInfo property => property.GetSetMethod(true) is not null, - _ => false - }; - } + FieldInfo field => !field.IsInitOnly, + PropertyInfo property => property.GetSetMethod(true) is not null, + _ => false + }; private static void SetMemberValue( MemberInfo member, diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs index 5087a4b99..60113821c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs @@ -220,12 +220,12 @@ public abstract class EditorAction : EditorAction /// /// Evaluates the operation's current availability and presentation state. /// - /// - /// The validated editor action state that represents the completed operation. - /// /// /// The context that supplies state and services for this operation. /// + /// + /// The validated editor action state that represents the completed operation. + /// protected sealed override EditorActionState Query(EditorActionContext context) => TryCreate( context, @@ -253,12 +253,12 @@ protected sealed override void Execute(EditorActionContext context) /// /// Presents this action through the current editor interaction surface. /// - /// - /// when the operation succeeds or its condition is satisfied; otherwise, . - /// /// /// The context that supplies state and services for this operation. /// + /// + /// when the operation succeeds or its condition is satisfied; otherwise, . + /// protected sealed override bool Present(EditorActionContext context) => TryCreate(context, out EditorActionContext typed) && Present(typed); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs index 0c3e13f52..7d23da7d2 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionRouter.cs @@ -433,7 +433,7 @@ private HotKeyGesture CreateGesture(EditorShortcutAttribute shortcut) { HotKeyGesture gesture = CreateGesture(shortcut); string area = string.IsNullOrEmpty(shortcut.area) ? registration.area ?? string.Empty : shortcut.area; - var key = (gesture.key, gesture.normalizedModifiers, area); + (KeyCode key, KeyModifier normalizedModifiers, string area) key = (gesture.key, gesture.normalizedModifiers, area); if (!candidates.TryGetValue(key, out HashSet? actions)) { candidates.Add(key, actions = new(StringComparer.Ordinal)); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs index 44d737b55..bd2324a3c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionActivator.cs @@ -50,7 +50,7 @@ internal EditorExtensionActivator( internal bool CanCreate(Type type) { ArgumentNullException.ThrowIfNull(type); - return CanCreate(type, new HashSet()); + return CanCreate(type, []); } internal EditorModule CreateModule(Type type) => (EditorModule)Create(type, typeof(EditorModule)); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs index ead1bdd6e..a799f1f85 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Discovery/EditorExtensionCatalog.cs @@ -387,9 +387,9 @@ Snapshot candidate { m_state.Save(GetAvailableState(previous), GetAvailablePanels(previous)); } - var existing = previous is null - ? new HashSet(ReferenceEqualityComparer.Instance) - : new HashSet(previous.instances, ReferenceEqualityComparer.Instance); + HashSet existing = previous is null + ? new HashSet(ReferenceEqualityComparer.Instance) + : new HashSet(previous.instances, ReferenceEqualityComparer.Instance); EditorHistory.HandlerUpdate handlers = m_interactions.historyHost.PrepareHandlerUpdate( CreateHistoryHandlerMap(candidate.historyHandlers) ); @@ -510,7 +510,7 @@ Snapshot candidate AttemptCleanup(() => RestorePrevious(activation), failures); m_activation = null; - var previousPanelIds = previous is null ? new HashSet(StringComparer.Ordinal) : new HashSet( + HashSet previousPanelIds = previous is null ? new HashSet(StringComparer.Ordinal) : new HashSet( GetAvailablePanels(previous).Select(static registration => registration.attribute.id), StringComparer.Ordinal ); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs index 48a067593..6e5c4d04f 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentContext.cs @@ -21,7 +21,7 @@ string providerId this.assetId = assetId; this.assetPath = assetPath; this.providerId = providerId; - title = Path.GetFileName(assetPath); + this.title = Path.GetFileName(assetPath); } /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs index 1b7de32d4..64df6bc7d 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/EditorDocumentService.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using Inno.Core.Events; @@ -11,7 +12,10 @@ internal sealed class EditorDocumentService : IEditorDocumentService private readonly Dictionary m_providers = new(StringComparer.Ordinal); private readonly EventDispatcher m_events; - internal EditorDocumentService(EventDispatcher events) => m_events = events; + internal EditorDocumentService(EventDispatcher events) + { + m_events = events; + } /// /// Gets an immutable snapshot of currently owned source documents. @@ -148,11 +152,11 @@ string assetPath { RetireStalePathOwner(pathOwner, path); } - bool defaultTitle = document.title == System.IO.Path.GetFileName(document.assetPath); + bool defaultTitle = document.title == Path.GetFileName(document.assetPath); document.assetPath = path; if (defaultTitle) { - document.title = System.IO.Path.GetFileName(path); + document.title = Path.GetFileName(path); } return true; } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs index 325999da0..c02083c37 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDragData.cs @@ -28,10 +28,10 @@ public EditorDragData( string label ) { ArgumentNullException.ThrowIfNull(source); - sourceIdentity = source.identity.runtimeIdentity - ?? throw new InvalidOperationException( - "An editor drag source must be registered in a live identity domain." - ); + this.sourceIdentity = source.identity.runtimeIdentity + ?? throw new InvalidOperationException( + "An editor drag source must be registered in a live identity domain." + ); this.label = label ?? string.Empty; } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs index 62428646c..edd0bbaa6 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs @@ -142,7 +142,7 @@ internal EditorDropContext( TSource source, TTarget target ) { - untyped = context; + this.untyped = context; this.source = source; this.target = target; } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs index 6abb262ff..59b03762a 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Editing/EditorEditGesture.cs @@ -30,7 +30,7 @@ string name ) { ArgumentNullException.ThrowIfNull(history); m_transaction = history.BeginTransaction(name); - mergeKey = "gesture:" + m_transaction.id.ToString("N"); + this.mergeKey = "gesture:" + m_transaction.id.ToString("N"); } /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs index a352f1108..ecefb7476 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistory.cs @@ -52,7 +52,7 @@ Logger log m_log = log ?? throw new ArgumentNullException(nameof(log)); options.Validate(); m_options = options; - capacity = options.maxEntries; + this.capacity = options.maxEntries; m_blobStore = new EditorHistoryBlobStore(options.cacheDirectory); } @@ -863,7 +863,7 @@ internal DelegateOperation( Func redo, object? mergeKey ) { - name = operationName; + this.name = operationName; m_undo = undo; m_redo = redo; m_mergeKey = mergeKey; @@ -1039,7 +1039,7 @@ internal ValueOperation( Action apply, object mergeKey ) { - name = operationName; + this.name = operationName; m_before = before; m_after = after; m_apply = apply; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs index f23d6eccb..27733da31 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryPayload.cs @@ -16,7 +16,7 @@ public sealed class EditorHistoryPayload : IDisposable private EditorHistoryPayload(byte[] bytes) { m_inlineBytes = bytes; - length = bytes.LongLength; + this.length = bytes.LongLength; } private EditorHistoryPayload( diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs index 303effd96..81afb4f3e 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuCatalog.cs @@ -36,11 +36,11 @@ internal EditorMenuModel Build(EditorMenuContext context) continue; } var placements = new List(builder.groups.Count + builder.items.Count); - foreach (var group in builder.groups) + foreach (EditorMenuGroupPlacement group in builder.groups) { placements.Add(CreatePlacement(group.path, null, group.order, group.separatorBefore, null)); } - foreach (var item in builder.items) + foreach (EditorMenuPlacement item in builder.items) { placements.Add(CreatePlacement(item.path, item.actionId, item.order, item.separatorBefore, item.argument)); } @@ -255,7 +255,7 @@ int depth placements[insertion] = placement; Array.Copy(current.placements, insertion, placements, insertion + 1, current.placements.Length - insertion); } - TemplateNode replacement = new( + var replacement = new TemplateNode( label, current.order, current.separatorBefore, diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs index ee22a6fc7..217f09968 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractionRuntime.cs @@ -13,7 +13,7 @@ namespace Inno.Editor.Interactions; /// /// Hosts attribute-discovered editor extensions without depending on a presentation backend. /// -public sealed class EditorInteractionRuntime : Inno.Editor.Core.EditorRuntime +public sealed class EditorInteractionRuntime : EditorRuntime { private readonly EditorInteractions m_interactions; private readonly EditorExtensionCatalog m_catalog; @@ -76,14 +76,14 @@ LogRouter logs /// /// The passive editor context shared with the presentation backend. /// - /// - /// Stable host-owned services that editor extension constructors may request by assignable contract. + /// + /// The type catalog that owns editor extension generations. /// /// /// The host-owned logging router used by editor infrastructure. /// - /// - /// The type catalog that owns editor extension generations. + /// + /// Stable host-owned services that editor extension constructors may request by assignable contract. /// /// /// Thrown when or is . @@ -208,13 +208,13 @@ public void SaveState() /// Freezes automatic extension-state persistence and writes the final state before modules /// begin shutting down. /// + /// + /// Thrown after this runtime has been disposed. + /// /// /// This operation is idempotent. After it succeeds, later disposal cannot recapture transient /// teardown state such as an empty scene workspace. /// - /// - /// Thrown after this runtime has been disposed. - /// public void PrepareShutdown() { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -260,10 +260,18 @@ public override void Dispose() { switch (m_shutdownStage) { - case 0: TryShutdownStage(m_catalog.PrepareShutdown, m_shutdownFailures); break; - case 1: TryShutdownStage(() => m_catalog.Shutdown(saveState: false), m_shutdownFailures); break; - case 2: TryShutdownStage(() => m_interactions.Shutdown(m_shutdownActions), m_shutdownFailures); break; - case 3: TryShutdownStage(m_catalog.Dispose, m_shutdownFailures); break; + case 0: + TryShutdownStage(m_catalog.PrepareShutdown, m_shutdownFailures); + break; + case 1: + TryShutdownStage(() => m_catalog.Shutdown(saveState: false), m_shutdownFailures); + break; + case 2: + TryShutdownStage(() => m_interactions.Shutdown(m_shutdownActions), m_shutdownFailures); + break; + case 3: + TryShutdownStage(m_catalog.Dispose, m_shutdownFailures); + break; } m_shutdownStage++; } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs index 5d9eae810..30bd2f187 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorInteractions.cs @@ -43,7 +43,7 @@ Logger log ArgumentNullException.ThrowIfNull(identityDomains); m_identityDomains = identityDomains.ToDictionary(static allocator => allocator.domainId); m_log = log ?? throw new ArgumentNullException(nameof(log)); - selection = new EditorSelectionState(this); + this.selection = new EditorSelectionState(this); m_documents = new EditorDocumentService(events); m_history = new EditorHistory( new EditorHistoryOptions { cacheDirectory = Path.Combine(editor.projectDirectory, "Library", "Editor", "History") }, @@ -114,16 +114,16 @@ public bool TryGetModule(out TModule? module) /// /// Starts an isolated temporary Undo and Redo branch while retaining the current editing branch. /// - /// - /// Disposing the returned scope releases every temporary operation and restores the retained branch. - /// This host-level boundary is intended for transient editor sessions such as Play Mode. - /// /// /// A scope that restores the retained history branch when disposed. /// /// /// Thrown during an Undo, Redo, transaction, or another isolated branch. /// + /// + /// Disposing the returned scope releases every temporary operation and restores the retained branch. + /// This host-level boundary is intended for transient editor sessions such as Play Mode. + /// [ScriptingApiIgnore] public IDisposable BeginHistoryIsolation() => m_history.BeginIsolation(); @@ -731,7 +731,7 @@ IdentityDomainId domain { private EditorInteractions? m_owner = owner; - /// + /// public void Dispose() { EditorInteractions? active = m_owner; diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs index 6ebd6a8aa..7e3b0ca53 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Runtime/EditorPanelExtension.cs @@ -1,5 +1,6 @@ using System; using System.Numerics; +using Inno.Core.Execution; using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -93,7 +94,7 @@ out Vector2 initialSize } return true; } - catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) + catch (Exception exception) when (RetirementPendingException.Find(exception) is null) { useWindowPadding = true; allowScrolling = true; @@ -124,7 +125,7 @@ public bool Draw(EditorContext context) m_panel.Draw(context); return true; } - catch (Exception exception) when (Inno.Core.Execution.RetirementPendingException.Find(exception) is null) + catch (Exception exception) when (RetirementPendingException.Find(exception) is null) { m_panel.isOpen = false; m_quarantine(exception); diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs index c47832fbb..d370dca25 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs @@ -233,9 +233,7 @@ public abstract class EditorViewportTool public virtual void OnPointerDown( EditorViewportToolContext context, EditorViewportPointerEvent pointer - ) { - ArgumentNullException.ThrowIfNull(context); - } + ) => ArgumentNullException.ThrowIfNull(context); /// /// Handles pointer movement or hover. @@ -249,9 +247,7 @@ EditorViewportPointerEvent pointer public virtual void OnPointerMove( EditorViewportToolContext context, EditorViewportPointerEvent pointer - ) { - ArgumentNullException.ThrowIfNull(context); - } + ) => ArgumentNullException.ThrowIfNull(context); /// /// Handles a pointer release. @@ -265,9 +261,7 @@ EditorViewportPointerEvent pointer public virtual void OnPointerUp( EditorViewportToolContext context, EditorViewportPointerEvent pointer - ) { - ArgumentNullException.ThrowIfNull(context); - } + ) => ArgumentNullException.ThrowIfNull(context); /// /// Handles platform cancellation of an active gesture. diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs index a0cc314fe..205d46ba5 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Definitions/ProjectSettingEditor.cs @@ -197,7 +197,7 @@ public abstract class ProjectSettingEditor : ProjectSettingEditor internal sealed override bool DrawValue(ISerializable value) { ValidateValue(value); - var setting = (TSetting)value; + TSetting setting = (TSetting)value; Baseline baseline = m_baselines.GetValue( setting, candidate => new Baseline(serialization.CapturePropertiesData(candidate)) diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs index d0e42463c..509cfaea3 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettings.cs @@ -32,13 +32,6 @@ public sealed class EditorSettings : EditorModule /// /// The runtime that owns the shared Undo and Redo history. /// - /// - /// Thrown when or is - /// . - /// - /// - /// Thrown when the project-root Settings document is malformed. - /// /// /// The host-owned type catalog used to discover setting presentations. /// @@ -48,6 +41,13 @@ public sealed class EditorSettings : EditorModule /// /// The host-owned current-generation serialization registry used for the project document. /// + /// + /// Thrown when or is + /// . + /// + /// + /// Thrown when the project-root Settings document is malformed. + /// internal EditorSettings( EditorContext context, EditorInteractions interactions, diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs index ff13f4ca1..f1b0c2d05 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsCatalog.cs @@ -40,7 +40,7 @@ protected override Snapshot Build(TypeCacheSnapshot types) throw new InvalidOperationException($"Editor setting path '{duplicatePath}' is registered more than once."); } - var byPath = definitions.ToDictionary(static setting => setting.path, StringComparer.Ordinal); + Dictionary byPath = definitions.ToDictionary(static setting => setting.path, StringComparer.Ordinal); return new Snapshot(types.version, definitions, byPath); } diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs index fb59f72a6..42afe5f76 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs @@ -13,7 +13,7 @@ internal static EditorHistoryChange CreateChange( ReadOnlySpan before, ReadOnlySpan after ) { - byte[] payload = new byte[sizeof(int) + before.Length + after.Length]; + var payload = new byte[sizeof(int) + before.Length + after.Length]; BinaryPrimitives.WriteInt32LittleEndian(payload, before.Length); before.CopyTo(payload.AsSpan(sizeof(int), before.Length)); after.CopyTo(payload.AsSpan(sizeof(int) + before.Length)); diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs index a87de9b23..35d2ddc86 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsEditor.cs @@ -25,9 +25,6 @@ public sealed class ProjectSettingsEditor : EditorModule /// /// The Editor interaction service that owns Undo and Redo. /// - /// - /// Thrown when is . - /// /// /// The host-owned type catalog used to discover setting presentations. /// @@ -37,6 +34,9 @@ public sealed class ProjectSettingsEditor : EditorModule /// /// The serialization registry used to compare staged setting values. /// + /// + /// Thrown when is . + /// internal ProjectSettingsEditor( EditorInteractions interactions, TypeCatalog types, diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs index a35d28eac..e87b44b4b 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs @@ -13,7 +13,7 @@ internal static EditorHistoryChange CreateChange( ReadOnlySpan before, ReadOnlySpan after ) { - byte[] payload = new byte[sizeof(int) + before.Length + after.Length]; + var payload = new byte[sizeof(int) + before.Length + after.Length]; BinaryPrimitives.WriteInt32LittleEndian(payload, before.Length); before.CopyTo(payload.AsSpan(sizeof(int), before.Length)); after.CopyTo(payload.AsSpan(sizeof(int) + before.Length)); diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs index 38fce6f64..61c6e5de5 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/EditorCommandLineOptions.cs @@ -10,7 +10,10 @@ namespace Inno.Editor.Hosting; /// public sealed class EditorCommandLineOptions { - private EditorCommandLineOptions(string projectDirectory) => this.projectDirectory = projectDirectory; + private EditorCommandLineOptions(string projectDirectory) + { + this.projectDirectory = projectDirectory; + } /// /// Gets the caller-selected authoring project. diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs index 6f7636d46..4d73d9a59 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHost.cs @@ -35,6 +35,7 @@ using Inno.Scene; using Inno.Scripting.Compiler; using Inno.Shell; +using Inno.Storage; using Inno.Storage.Runtime; using Inno.UI.Runtime; @@ -415,7 +416,7 @@ private void Initialize() () => engineHost.diagnostics.CreateReporter(new DiagnosticSource("inno.editor.rendering", "Rendering")), static sink => sink.Dispose() ); - var renderArtifacts = m_resources.Acquire( + EditorRenderTargetArtifactProvider renderArtifacts = m_resources.Acquire( () => new EditorRenderTargetArtifactProvider( activeAuthoring.assets, engineHost.serialization, @@ -469,7 +470,7 @@ private void Initialize() m_resources.Register(hostPipeline.Dispose); UseHostPipeline(hostPipeline); var reloadCoordinator = new EditorReloadCoordinator(); - var renderingHost = m_resources.Acquire( + EditorRenderingHostService renderingHost = m_resources.Acquire( () => new EditorRenderingHostService(renderingLayer, presentation, reloadCoordinator), static service => service.Dispose() ); @@ -490,7 +491,7 @@ private void Initialize() createSubsystems = owner => CreateStandardRuntimeSubsystems(activeAudio, gameInputSource, owner), referenceResolvers = [activeAuthoring.assets] }; - EditorLayer layer = new EditorLayer( + var layer = new EditorLayer( presentation, editorContext, engineHost.types, @@ -578,7 +579,7 @@ RuntimeSession owner ), () => adapters.storage.CreateStorage( adapterSelection.storage, - new Inno.Storage.StorageScope(owner.options.applicationId) + new StorageScope(owner.options.applicationId) ), activeAudio.CreateRuntimeSubsystemFactory(owner) ) @@ -681,12 +682,10 @@ private sealed class SmokeDiagnostics : IDiagnosticSink /// The current immutable report whose error messages are copied into the smoke snapshot. /// public void Replace(DiagnosticReport report) - { - m_reports[report.source] = report.diagnostics + => m_reports[report.source] = report.diagnostics .Where(static diagnostic => diagnostic.severity == DiagnosticSeverity.Error) .Select(diagnostic => report.source.id + "/" + diagnostic.code + ": " + diagnostic.message) .ToArray(); - } /// /// Removes errors when their diagnostic source is retired. diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs index 7cc66db2d..5a1f10779 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorLayer.cs @@ -36,7 +36,7 @@ internal EditorLayer( EditorContext context, TypeCatalog types, LogRouter logs, - System.Collections.Generic.IEnumerable? hostServices = null + IEnumerable? hostServices = null ) { m_presentation = presentation ?? throw new ArgumentNullException(nameof(presentation)); m_context = context; @@ -55,10 +55,7 @@ internal float totalTime set => m_totalTime = value; } - internal void DisposeUnattached() - { - m_resources.Dispose(); - } + internal void DisposeUnattached() => m_resources.Dispose(); internal void QuiescePlayMode() => m_playModeLoop.Quiesce(); @@ -101,10 +98,7 @@ public override void OnLateUpdate(float deltaTime) SaveLayoutIfChanged(); } - private void HandleKeyPressed(KeyPressedEvent keyEvent) - { - m_runtime.HandleKeyPressed(keyEvent); - } + private void HandleKeyPressed(KeyPressedEvent keyEvent) => m_runtime.HandleKeyPressed(keyEvent); internal bool PrepareShutdown() { @@ -172,7 +166,7 @@ private static IEnumerable CreateHostServices( IEnumerable? hostServices, EditorPlayModeLoop playModeLoop ) { - List services = hostServices is null ? [] : new List(hostServices); + List services = hostServices is null ? [] : [.. hostServices]; services.Add(playModeLoop); return services; } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs index 30d01ef7b..04b35ae73 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorRenderingHostService.cs @@ -652,9 +652,9 @@ RenderShaderArtifact artifact ) { this.documentId = documentId; this.revision = revision; - contentHash = artifact.contentHash; + this.contentHash = artifact.contentHash; this.artifact = artifact; - snapshot = new(EditorShaderCompilationState.Compiling, []); + this.snapshot = new(EditorShaderCompilationState.Compiling, []); } internal Guid documentId { get; set; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs index 211b3f609..76bec3cbc 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserChangeTracker.cs @@ -118,7 +118,7 @@ string removedPath } string fallback = FileBrowserUtility.GetParentDirectory(removedPath); while (!string.Equals(fallback, FileBrowserUtility.GetParentDirectory(fallback), StringComparison.Ordinal) - && (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(fallback), out var entry) + && (!assets.edits.pipeline.TryGetFileSystemEntry(AssetPath.Parse(fallback), out AssetFileEntry entry) || !entry.isDirectory) ) { fallback = FileBrowserUtility.GetParentDirectory(fallback); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs index a1bd3ff2e..23d6bda36 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserContextMenu.cs @@ -4,6 +4,7 @@ using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui; +using Inno.Editor.Interactions; using static Inno.Editor.Panel.FileBrowser.FileBrowserUtility; @@ -75,6 +76,6 @@ FileBrowserPresentation presentation } } - private Inno.Editor.Interactions.EditorInteraction CreateDirectoryInteraction(string relativePath) + private EditorInteraction CreateDirectoryInteraction(string relativePath) => assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, NormalizePath(relativePath)); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs index 28dd20ef8..2b4721b7b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs @@ -191,7 +191,7 @@ List entries internal List SortTreeEntries(IReadOnlyList entries) { - List sorted = new(entries); + List sorted = [.. entries]; sorted.Sort(static ( left, right diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs index 262703d01..86b491ecd 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserDragDrop.cs @@ -1,4 +1,5 @@ using System; +using System.Numerics; using Inno.Assets.Pipeline; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; @@ -63,8 +64,8 @@ string relativePath { return; } - System.Numerics.Vector2 minimum = Ui.GetItemMinimum(); - System.Numerics.Vector2 maximum = Ui.GetItemMaximum(); + Vector2 minimum = Ui.GetItemMinimum(); + Vector2 maximum = Ui.GetItemMaximum(); EditorDropWidgetResult result = EditorDragDropRenderer.Target( assets.edits.interactions.For(FileBrowserInteractionIds.C_AREA, relativePath) ); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs index dc8b560d5..ee223dd2a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Filters.cs @@ -72,7 +72,5 @@ FileBrowserEntryScopeFilter filter } private void DrawSearchInput() - { - _ = EditorUI.current.widgets.SearchInput("AssetSearch", ImGuiIcon.MagnifyingGlass, ref m_filter, (nuint)C_SEARCH_BUFFER_SIZE); - } + => _ = EditorUI.current.widgets.SearchInput("AssetSearch", ImGuiIcon.MagnifyingGlass, ref m_filter, (nuint)C_SEARCH_BUFFER_SIZE); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs index 233996039..43de10030 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Grid.cs @@ -88,7 +88,7 @@ IReadOnlyList entries "##FileBrowserGrid", columns, (ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoSavedSettings), - default(System.Numerics.Vector2), + default, 0f ); if (!tableStarted) @@ -142,7 +142,7 @@ FileBrowserDisplayEntry item string name = item.isPluginRoot ? item.displayName : entry.name; bool selected = m_assets.browser.IsSelected(context, entry); bool editing = m_rename.IsEditing(context, entry.assetPath.ToString(), FileBrowserPresentation.Grid); - Vector2 itemSize = new(cellSize - CurrentBrowserStyle.gridCellPadding, cellSize - CurrentBrowserStyle.gridCellPadding); + var itemSize = new Vector2(cellSize - CurrentBrowserStyle.gridCellPadding, cellSize - CurrentBrowserStyle.gridCellPadding); Ui.PushId(entry.assetPath.ToString()); Ui.PushStyleColor(ImGuiCol.Header, EditorPalette.transparent); Ui.PushStyleColor(ImGuiCol.HeaderHovered, EditorPalette.transparent); @@ -232,7 +232,7 @@ bool drawName float fontSize = Ui.GetFontSize(); float iconFontSize = fontSize * scale; Vector4 iconBounds = EditorUI.current.widgets.GetGlyphVisualBounds(iconFontSize, icon); - Vector2 iconSize = new(iconBounds.Z - iconBounds.X, iconBounds.W - iconBounds.Y); + var iconSize = new Vector2(iconBounds.Z - iconBounds.X, iconBounds.W - iconBounds.Y); string[] nameLines = FitTextToLines( name, MathF.Max(1f, size.X - CurrentBrowserStyle.gridLabelHorizontalPadding), @@ -257,7 +257,7 @@ bool drawName } float horizontalCenter = min.X + size.X * 0.5f; - Vector2 iconAreaCenter = new( + var iconAreaCenter = new Vector2( horizontalCenter + C_GRID_ICON_HORIZONTAL_OPTICAL_OFFSET * EditorUI.current.widgets.style.zoom, iconAreaTop + maximumIconHeight * 0.5f ); @@ -267,7 +267,7 @@ bool drawName for (int i = 0; drawName && i < nameLines.Length; i++) { Vector2 lineSize = Ui.MeasureText(nameLines[i]); - Vector2 linePosition = new(horizontalCenter - lineSize.X * 0.5f, labelY + lineAdvance * i); + var linePosition = new Vector2(horizontalCenter - lineSize.X * 0.5f, labelY + lineAdvance * i); Ui.DrawText(linePosition, textColor, nameLines[i]); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs index 111144916..209c73ecd 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.Layout.cs @@ -26,7 +26,7 @@ private void DrawBrowser(EditorContext context) m_navigation.SyncExternalDirectoryChange(m_assets.browser.root, m_assets.browser.currentDirectory); EditorUiLayout style = Ui.GetLayout(); float breadcrumbBarHeight = GetBreadcrumbBarHeight(m_assets.browser.root, m_assets.browser.currentDirectory); - Vector2 bodySize = new(0f, -(breadcrumbBarHeight + style.itemSpacing.Y)); + var bodySize = new Vector2(0f, -(breadcrumbBarHeight + style.itemSpacing.Y)); bool mainVisible = Ui.BeginChild( "##FileBrowserMain", bodySize, @@ -47,7 +47,7 @@ private void DrawBrowser(EditorContext context) Ui.PushStyleVar(ImGuiStyleVar.CellPadding, Vector2.Zero); try { - bool splitStarted = Ui.BeginTable("##FileBrowserSplit", 3, splitFlags, default(System.Numerics.Vector2), 0f); + bool splitStarted = Ui.BeginTable("##FileBrowserSplit", 3, splitFlags, default, 0f); try { if (splitStarted) @@ -91,16 +91,14 @@ private void DrawBrowser(EditorContext context) } private static float GetTreeSplitterWidth(EditorUiLayout style) - { - return MathF.Max(EditorUI.current.widgets.style.splitterMinimumWidth, style.dockingSeparatorSize); - } + => MathF.Max(EditorUI.current.widgets.style.splitterMinimumWidth, style.dockingSeparatorSize); private void DrawTreeSplitter( float width, float availableWidth, float treeWidth ) { - Vector2 size = new(width, MathF.Max(1f, Ui.GetContentRegionAvailable().Y)); + var size = new Vector2(width, MathF.Max(1f, Ui.GetContentRegionAvailable().Y)); _ = Ui.InvisibleButton("##TreeSplitterGrip", size); bool hovered = Ui.IsItemHovered(); bool active = Ui.IsItemActive(); @@ -160,7 +158,7 @@ private void DrawTreePane(EditorContext context) try { EditorUiLayout style = Ui.GetLayout(); - Vector2 treePaneSize = new(-style.windowPadding.X, 0f); + var treePaneSize = new Vector2(-style.windowPadding.X, 0f); bool treeVisible = Ui.BeginChild( "##TreePane", treePaneSize, @@ -296,13 +294,13 @@ IReadOnlyList entries } finally { - m_visibleSelection = Array.Empty(); + m_visibleSelection = Array.Empty(); m_drawKeyboardFocus = null; } RuntimeIdentity? activation = m_pendingActivation; m_pendingActivation = null; if (activation is RuntimeIdentity identity - && m_assets.edits.interactions.TryResolveIdentity(identity, out Inno.Core.Identity.IdentityObject? target) + && m_assets.edits.interactions.TryResolveIdentity(identity, out IdentityObject? target) && target is AssetFileEntry entry ) { m_navigation.OpenEntry(context, entry, m_tree); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs index 70521cb4a..45082edd8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.List.cs @@ -242,7 +242,7 @@ AssetFileEntry entry string name = item.isPluginRoot ? item.displayName : entry.nameWithoutExtension; bool selected = m_assets.browser.IsSelected(context, entry); bool editing = m_rename.IsEditing(context, entry.assetPath.ToString(), FileBrowserPresentation.List); - var table = Ui.GetTableBounds(); + (float minimumX, float maximumX, float rowMinimum, float rowMaximum) table = Ui.GetTableBounds(); float rowMinimumY = table.rowMinimum; float rowMaximumY = table.rowMaximum; InsetListCellContent(); @@ -328,10 +328,7 @@ Vector4 color Ui.PopStyleColor(); } - private static void InsetListCellContent() - { - Ui.SetCursorPosX(Ui.GetCursorPosX() + CurrentBrowserStyle.listContentHorizontalPadding); - } + private static void InsetListCellContent() => Ui.SetCursorPosX(Ui.GetCursorPosX() + CurrentBrowserStyle.listContentHorizontalPadding); private readonly record struct ListColumnSeparatorState( bool nameHovered, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs index 6f3bc355b..c4b7f7893 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserPanel.cs @@ -125,7 +125,7 @@ EditorUiSession ui ) { m_assets = assets; m_ui = ui ?? throw new ArgumentNullException(nameof(ui)); - AssetBrowserStyle style = new(ui.widgets.style); + var style = new AssetBrowserStyle(ui.widgets.style); m_gridScale = style.gridDefaultScale; m_listNameSeparatorPosition = style.listNameSeparatorPosition; m_listTypeSeparatorPosition = style.listTypeSeparatorPosition; @@ -144,10 +144,7 @@ EditorUiSession ui /// /// The context that supplies state and services for this operation. /// - protected override void OnAttach(EditorContext context) - { - m_changeTracker.Attach(context); - } + protected override void OnAttach(EditorContext context) => m_changeTracker.Attach(context); /// /// Detaches this feature and releases generation-scoped state. @@ -155,10 +152,7 @@ protected override void OnAttach(EditorContext context) /// /// The context that supplies state and services for this operation. /// - protected override void OnDetach(EditorContext context) - { - m_changeTracker.Detach(); - } + protected override void OnDetach(EditorContext context) => m_changeTracker.Detach(); /// /// Draws this feature using the current editor presentation context. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs index d4e9f63a4..2c49292cb 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs @@ -36,10 +36,7 @@ internal void Update(EditorContext context) m_activePresentation = m_lastPresentation; } - internal void MarkInteraction(FileBrowserPresentation presentation) - { - m_lastPresentation = presentation; - } + internal void MarkInteraction(FileBrowserPresentation presentation) => m_lastPresentation = presentation; internal bool IsEditing( EditorContext context, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs index 6c9a38a99..51f2479e8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.Rows.cs @@ -7,6 +7,7 @@ using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; +using Inno.Editor.ImGui.ImGuiWidget; using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; @@ -62,7 +63,7 @@ internal void Draw(EditorContext context) private void RefreshRows() { - var widgets = EditorUI.current.widgets; + ImGuiWidget widgets = EditorUI.current.widgets; AssetPipeline pipeline = m_assets.edits.pipeline; if (!m_rootOpenRequest && !m_currentDirectoryOpenRequest && m_rowsRoot == m_assets.browser.root && m_sourceRevision == pipeline.revision && m_expansionRevision == widgets.treeExpansionRevision @@ -94,7 +95,7 @@ private void RefreshRows() } } } - while (pending.TryPop(out var next)) + while (pending.TryPop(out (string path, string label, bool root, int depth) next)) { AssetFileEntry? entry = null; if (!next.root && (!pipeline.TryGetFileSystemEntry(AssetPath.Parse(next.path), out entry) || entry is null)) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs index 55b48e3f5..76594d777 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserTree.cs @@ -53,7 +53,7 @@ BrowserTreeRow row AssetFileEntry? entry = null; if (row.identity is { } identity) { - if (!m_assets.edits.interactions.TryResolveIdentity(identity, out Inno.Core.Identity.IdentityObject? resolved) + if (!m_assets.edits.interactions.TryResolveIdentity(identity, out IdentityObject? resolved) || resolved is not AssetFileEntry current ) { Ui.Dummy(new(1f, Ui.GetFrameHeight())); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs index f9b130296..2687c0059 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserUtility.cs @@ -260,7 +260,7 @@ int maxLines { elements.Add(enumerator.GetTextElement()); } - List lines = new(maxLines); + var lines = new List(maxLines); int offset = 0; for (int lineIndex = 0; lineIndex < maxLines && offset < elements.Count; lineIndex++) { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs index 46529a161..92aa233d9 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/MoveAssetEntryDropHandler.cs @@ -18,12 +18,12 @@ internal sealed class MoveAssetEntryDropHandler(AssetBrowserModule assets) : Edi /// /// Evaluates the operation's current availability and presentation state. /// - /// - /// The validated editor drop status that represents the completed operation. - /// /// /// The context that supplies state and services for this operation. /// + /// + /// The validated editor drop status that represents the completed operation. + /// protected override EditorDropStatus Query(EditorDropContext context) => assets.edits.CanMoveSelection( SelectedSources(context), diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs index 5bf4b2ae2..bfc6f8e1a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Samples/AssetSampleImportModal.cs @@ -13,18 +13,18 @@ internal sealed class AssetSampleImportModal(AssetSampleImportModule imports) : private DialogLayout m_layout; private long m_operation; - /// + /// public override bool isVisible => imports.isBusy; - /// + /// public override bool allowScrolling => false; - /// + /// protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize ) { - var snapshot = imports.progress; + AssetSampleImportProgress snapshot = imports.progress; m_operation = snapshot.operationId; m_content = new( snapshot.status, @@ -37,7 +37,7 @@ Vector2 availableContentSize return m_layout.size; } - /// + /// protected override void OnDraw(EditorContext context) { if (EditorUiSession.current.widgets.DrawDialog(m_content, m_layout)) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs index 11bec9a02..37e6f7485 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.GameView/GameViewPanel.cs @@ -15,6 +15,8 @@ using Inno.Runtime; using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using EngineColor = Inno.Core.Mathematics.Color; +using EngineVector2 = Inno.Core.Mathematics.Vector2; using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.GameView; @@ -94,7 +96,7 @@ protected override void OnDraw(EditorContext context) m_rendering.SetPresentation( C_VIEWPORT_ID, new EditorViewportPresentation( - new Inno.Core.Mathematics.Color(m_backgroundColor.X, m_backgroundColor.Y, m_backgroundColor.Z, m_backgroundColor.W), + new EngineColor(m_backgroundColor.X, m_backgroundColor.Y, m_backgroundColor.Z, m_backgroundColor.W), framebufferScale ) ); @@ -103,7 +105,7 @@ protected override void OnDraw(EditorContext context) Vector2 mouse = Ui.GetMousePos(); Vector2 local = mouse - outputOrigin; bool inside = local.X >= 0f && local.Y >= 0f && local.X < layout.size.X && local.Y < layout.size.Y; - var viewport = Ui.GetViewport(); + (uint id, Vector2 position) viewport = Ui.GetViewport(); bool gameViewFocused = m_playMode.isPlaying && Ui.IsWindowFocused(ImGuiFocusedFlags.RootAndChildWindows); bool imageHovered = inside && Ui.IsWindowHovered(ImGuiHoveredFlags.RootAndChildWindows); bool focused = m_inputCapture.Report(viewport.id, outputOrigin - viewport.position, layout.size, gameViewFocused, imageHovered); @@ -123,7 +125,7 @@ protected override void OnDraw(EditorContext context) { m_leftPointerActive = false; } - var io = Ui.GetInput(); + EditorUiInput io = Ui.GetInput(); KeyModifier modifiers = KeyModifier.None; if (io.alt) { @@ -145,12 +147,12 @@ protected override void OnDraw(EditorContext context) C_VIEWPORT_ID, focused ? new RenderOutputInput( - new Inno.Core.Mathematics.Vector2( + new EngineVector2( local.X * layout.pixelWidth / layout.size.X, local.Y * layout.pixelHeight / layout.size.Y ), acceptsPointer, - acceptsPointer ? new Inno.Core.Mathematics.Vector2(0f, io.wheel) : default, + acceptsPointer ? new EngineVector2(0f, io.wheel) : default, modifiers, [], [], diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs index d17f1b1a1..43929fb1d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/ReorderSceneDropHandler.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scene; @@ -62,7 +63,7 @@ protected override EditorDropResult Drop(EditorDropContext scenes, + IReadOnlyList scenes, GameScene scene ) { for (int index = 0; index < scenes.Count; index++) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs index a2c4a2d52..33a34bef7 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SavePrefabAssetDropHandler.cs @@ -1,3 +1,4 @@ +using System; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Core; @@ -17,8 +18,8 @@ internal SavePrefabAssetDropHandler( IEditorSceneWorkspace workspace, AssetPipeline assets ) { - m_workspace = workspace ?? throw new System.ArgumentNullException(nameof(workspace)); - m_assets = assets ?? throw new System.ArgumentNullException(nameof(assets)); + m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); + m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); } /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs index 6d3efefd8..7a9afde4c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Interactions/SaveSceneAssetDropHandler.cs @@ -1,3 +1,4 @@ +using System; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Core; @@ -17,8 +18,8 @@ internal SaveSceneAssetDropHandler( IEditorSceneWorkspace workspace, AssetPipeline assets ) { - m_workspace = workspace ?? throw new System.ArgumentNullException(nameof(workspace)); - m_assets = assets ?? throw new System.ArgumentNullException(nameof(assets)); + m_workspace = workspace ?? throw new ArgumentNullException(nameof(workspace)); + m_assets = assets ?? throw new ArgumentNullException(nameof(assets)); } /// diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs index 46dd44cb9..593b51e21 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.Rows.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Inno.Core.Identity; using Inno.Editor.Core; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Scene; using Inno.Scene.Components; @@ -23,7 +24,7 @@ int depth private void RefreshRows(IReadOnlyList scenes) { - var widgets = EditorUI.current.widgets; + ImGuiWidget widgets = EditorUI.current.widgets; foreach (GameScene scene in scenes) { if (m_initializedSceneIds.Add(scene.identity.persistentId)) @@ -70,7 +71,7 @@ private void RefreshRows(IReadOnlyList scenes) { pending.Push((roots[index], 1)); } - while (pending.TryPop(out var next)) + while (pending.TryPop(out (GameObject target, int depth) next)) { if (!next.target.isRuntimeValid) { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs index 29806aed3..eb000b8a3 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Presentation/HierarchyPanel.cs @@ -440,7 +440,7 @@ string id private void DrawBlankArea(EditorContext context) { Vector2 available = Ui.GetContentRegionAvailable(); - Vector2 size = new(MathF.Max(1f, available.X), MathF.Max(hierarchyStyle.blankMinimumHeight, available.Y)); + var size = new Vector2(MathF.Max(1f, available.X), MathF.Max(hierarchyStyle.blankMinimumHeight, available.Y)); _ = Ui.InvisibleButton("##hierarchy_blank", size); if (Ui.IsItemClicked((ImGuiMouseButton.Left))) { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Styling/HierarchyStyle.cs b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Styling/HierarchyStyle.cs index b8aeb77c1..04d51a4f6 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Styling/HierarchyStyle.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Hierarchy/Styling/HierarchyStyle.cs @@ -7,7 +7,10 @@ internal readonly struct HierarchyStyle { private readonly float m_zoom; - internal HierarchyStyle(EditorStyleMetrics metrics) => m_zoom = metrics.zoom; + internal HierarchyStyle(EditorStyleMetrics metrics) + { + m_zoom = metrics.zoom; + } /// /// Gets the text color of inactive hierarchy entries. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs index a0d994d55..4dc279ac6 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/DragDrop/AssetReferenceDropHandler.cs @@ -1,3 +1,4 @@ +using System; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Editor.Interactions; @@ -18,9 +19,9 @@ internal sealed class AssetReferenceDropHandler(AssetPipeline assets) : EditorDr /// protected override EditorDropStatus Query(EditorDropContext context) { - if (!assets.TryGetPersistentId(context.source.assetPath, out System.Guid persistentId) - || persistentId == System.Guid.Empty - || !assets.TryGetAssetType(context.source.assetPath, out System.Type? assetType) + if (!assets.TryGetPersistentId(context.source.assetPath, out Guid persistentId) + || persistentId == Guid.Empty + || !assets.TryGetAssetType(context.source.assetPath, out Type? assetType) || assetType is null || !context.target.expectedType.IsAssignableFrom(assetType) ) { @@ -44,7 +45,7 @@ protected override EditorDropResult Drop(EditorDropContext { - var component = (GameComponent)source; + GameComponent component = (GameComponent)source; int sourceIndex = component.gameObject.GetComponentIndex(component); int insertionBoundary = targetIndex + (insertAfter ? 1 : 0); int destinationIndex = insertionBoundary > sourceIndex ? insertionBoundary - 1 : insertionBoundary; @@ -181,7 +181,7 @@ source is GameSystem system insertAfter ) => { - var system = (GameSystem)source; + GameSystem system = (GameSystem)source; int sourceIndex = scene.GetSystemIndex(system); int insertionBoundary = targetIndex + (insertAfter ? 1 : 0); int destinationIndex = insertionBoundary > sourceIndex ? insertionBoundary - 1 : insertionBoundary; @@ -201,7 +201,7 @@ private void DrawDropTarget( Action move, string operation ) { - if (!Inno.Editor.ImGui.ImGui.HasDragPayload(payloadType) || cardMaximum.X <= cardMinimum.X || cardMaximum.Y <= cardMinimum.Y) + if (!Ui.HasDragPayload(payloadType) || cardMaximum.X <= cardMinimum.X || cardMaximum.Y <= cardMinimum.Y) { return; } @@ -245,7 +245,7 @@ bool dimmed Vector2 padding = EditorUI.current.widgets.style.cardHeaderPadding; Vector2 gripSize = Ui.MeasureText(ImGuiIcon.GripVertical); Vector2 titleSize = Ui.MeasureText(title); - Vector2 size = new( + var size = new Vector2( padding.X * 2f + gripSize.X + EditorUI.current.widgets.style.headerControlSpacing + titleSize.X, MathF.Max(gripSize.Y, titleSize.Y) + padding.Y * 2f ); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs index 1d3279970..f9f77e218 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Presentation/InspectorTargetHeader.cs @@ -1,5 +1,6 @@ using System; using System.Numerics; +using System.Runtime.CompilerServices; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Inspection; @@ -21,15 +22,15 @@ internal sealed class InspectorTargetHeader /// /// Resolves the target that should be presented after applying Inspector lock state. /// - /// - /// The current valid Inspector target, or when none is available. - /// /// /// Shared interaction service that resolves targets in their owning identity domains. /// /// /// The current inspection target used to render the header. /// + /// + /// The current valid Inspector target, or when none is available. + /// internal object? Resolve( EditorInteractions interactions, object? selectedTarget @@ -200,5 +201,5 @@ float rowHeight } private static string GetTargetId(object target) - => $"{target.GetType().FullName}_{System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(target)}"; + => $"{target.GetType().FullName}_{RuntimeHelpers.GetHashCode(target)}"; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs index 9176e24a9..6d804bdbe 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/EngineObjectReferencePropertyDrawer.cs @@ -106,12 +106,10 @@ private List CollectCandidates(Type targetType) } private static string GetDisplayName(EngineObject target) + => target switch { - return target switch - { - GameObject gameObject => gameObject.name, - GameComponent component => $"{component.gameObject.name} ({component.GetType().Name})", - _ => target.GetType().Name - }; - } + GameObject gameObject => gameObject.name, + GameComponent component => $"{component.gameObject.name} ({component.GetType().Name})", + _ => target.GetType().Name + }; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs index 763da8164..57dc02183 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/PropertyDrawing/SceneInspectionPropertyEditService.cs @@ -23,7 +23,7 @@ internal SceneInspectionPropertyEditService(SceneEdits edits) m_edits = edits ?? throw new ArgumentNullException(nameof(edits)); } - /// + /// public bool ChangeProperty( object owner, string propertyName, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs index 37a0e1061..23b98bd6f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Runtime/SceneInspectionModule.cs @@ -75,16 +75,16 @@ internal SceneInspectionModule( RuntimeSession runtimeSession, LogRouter logs ) { - System.ArgumentNullException.ThrowIfNull(interactions); - System.ArgumentNullException.ThrowIfNull(edits); - System.ArgumentNullException.ThrowIfNull(assetIcons); - System.ArgumentNullException.ThrowIfNull(classificationSettings); - System.ArgumentNullException.ThrowIfNull(settings); - System.ArgumentNullException.ThrowIfNull(assets); - System.ArgumentNullException.ThrowIfNull(types); - System.ArgumentNullException.ThrowIfNull(serialization); - System.ArgumentNullException.ThrowIfNull(runtimeSession); - System.ArgumentNullException.ThrowIfNull(logs); + ArgumentNullException.ThrowIfNull(interactions); + ArgumentNullException.ThrowIfNull(edits); + ArgumentNullException.ThrowIfNull(assetIcons); + ArgumentNullException.ThrowIfNull(classificationSettings); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(assets); + ArgumentNullException.ThrowIfNull(types); + ArgumentNullException.ThrowIfNull(serialization); + ArgumentNullException.ThrowIfNull(runtimeSession); + ArgumentNullException.ThrowIfNull(logs); m_assets = assets; var activator = new InspectionDrawerActivator( interactions, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Styling/InspectorTargetStyle.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Styling/InspectorTargetStyle.cs index 010d5e1ae..387443923 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Styling/InspectorTargetStyle.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Styling/InspectorTargetStyle.cs @@ -13,5 +13,5 @@ internal static class InspectorTargetStyle /// /// Gets the subdued background of Layer labels in Inspector target headers. /// - internal static Vector4 layerLabel { get; } = new(0.24f, 0.34f, 0.40f, EditorPalette.opacityOpaque); + internal static Vector4 layerLabel { get; } = new(0.24f, 0.34f, 0.4f, EditorPalette.opacityOpaque); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs index f1b852bbd..076066d2e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameObjectInspectionDrawer.cs @@ -195,7 +195,7 @@ GameObject gameObject : Array.Empty(); string componentId = component.identity.persistentId.ToString("N"); GameBehavior? behavior = component as GameBehavior; - var editorTarget = component; + GameComponent editorTarget = component; string title = missing?.missingTypeName ?? componentType.Name; bool canRemove = componentType != typeof(Transform); bool dimmed = behavior is { enabled: false }; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs index 979d8b89c..528a16bb5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameSceneInspectionDrawer.cs @@ -139,7 +139,7 @@ GameScene scene ? m_serialization.GetProperties(system) : Array.Empty(); string systemId = system.identity.persistentId.ToString("N"); - var editorTarget = system; + GameSystem editorTarget = system; string title = missing?.missingTypeName ?? system.GetType().Name; bool dimmed = !system.enabled; Vector2 cardMinimum = default; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs index ab626157f..efdf6b9e2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/GameTagsSetting.cs @@ -92,7 +92,7 @@ private static void DrawTags(GameTagCatalog setting) | ImGuiTableFlags.NoPadOuterX | ImGuiTableFlags.NoSavedSettings; Ui.PushStyleVar((ImGuiStyleVar.CellPadding), EditorUI.current.widgets.style.cellPadding); - if (!Ui.BeginTable("##project_tag_definitions", 2, flags, default(System.Numerics.Vector2), 0f)) + if (!Ui.BeginTable("##project_tag_definitions", 2, flags, default, 0f)) { Ui.PopStyleVar(); return; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs index ac1d5888d..555b959bc 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs @@ -1,7 +1,9 @@ using System; +using System.IO; using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Serialization; using Inno.Editor.Assets; using Inno.Editor.ImGui; @@ -21,7 +23,7 @@ internal sealed class PipelineInspectionDrawer(IInspectionIconProvider /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => Inno.Editor.ImGui.ImGuiIcon.File; + public override string icon => ImGuiIcon.File; /// /// Retrieves the current icon from authoritative state. @@ -38,7 +40,7 @@ internal sealed class PipelineInspectionDrawer(IInspectionIconProvider context.interactions.TryGetModule(out var documents) + ) => context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null && documents.assets.TryGetInfo(target.identity.persistentId, out AssetInfo? info) && info is not null @@ -77,7 +79,7 @@ protected override void DrawHeader( InspectionDrawContext context, RenderPipelineAsset target ) { - if (context.interactions.TryGetModule(out var documents) + if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null && documents.assets.TryGetInfo(target.identity.persistentId, out AssetInfo? info) && info is not null @@ -99,7 +101,7 @@ protected override void Draw( InspectionDrawContext context, RenderPipelineAsset target ) { - if (context.interactions.TryGetModule(out var documents) + if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null && documents.assets.TryGetInfo(target.identity.persistentId, out AssetInfo? info) && info is not null @@ -115,7 +117,7 @@ internal sealed class PipelineSourceDrawer(IInspectionIconProvider /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => Inno.Editor.ImGui.ImGuiIcon.File; + public override string icon => ImGuiIcon.File; /// /// Retrieves the current icon from authoritative state. @@ -176,7 +178,7 @@ protected override void DrawHeader( InspectionDrawContext context, AssetFileEntry target ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) + if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null) { PipelineInspector.DrawHeader(context, documents, documents.Open(target.assetPath)); } @@ -195,7 +197,7 @@ protected override void Draw( InspectionDrawContext context, AssetFileEntry target ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) + if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null) { PipelineInspector.Draw(context, documents, documents.Open(target.assetPath)); } @@ -368,12 +370,12 @@ Action assign ); } } - catch (Exception error) when ((error is System.IO.IOException + catch (Exception error) when ((error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(error) is null) + && RetirementPendingException.Find(error) is null) { EditorUI.current.widgets.Hint( "Settings unavailable · " + state.stableTypeId + " · " + error.Message + " · Stored properties and dependencies are retained." @@ -388,7 +390,7 @@ private sealed class DraftEdits( RenderPipelineAsset pipeline ) : IInspectionPropertyEditService { - /// + /// public bool ChangeProperty( object owner, string propertyName, @@ -408,7 +410,7 @@ private sealed class SettingsEdits( Action capture ) : IInspectionPropertyEditService { - /// + /// public bool ChangeProperty( object owner, string propertyName, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs index d70906fbe..efe3fb94a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/SelectionInspectionDrawer.cs @@ -4,10 +4,14 @@ using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Editor.ImGui; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Inspection; using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Scene; +using Inno.Scene.Components; + +using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Inspector; @@ -20,7 +24,7 @@ SceneProjectSettingsModule settings { private readonly GameObjectTagSelector m_tags = new(settings, edits); private readonly GameObjectLayerSelector m_layers = new(settings, edits); - private string m_componentSearch = ""; + private string m_componentSearch = string.Empty; /// public override string icon => ImGuiIcon.LayerGroup; @@ -103,7 +107,7 @@ IReadOnlyList targets transaction.Commit(); }); EditorUiSession.current.widgets.Hint(mixed ? "Active \u00b7 Mixed values" : "Active"); - float width = MathF.Max(1, Inno.Editor.ImGui.ImGui.GetContentRegionAvailable().X); + float width = MathF.Max(1, Ui.GetContentRegionAvailable().X); m_tags.Draw(targets, context.interactions, width); m_layers.Draw(targets, context.interactions, width); IReadOnlyList primary = targets[0].GetComponents(); @@ -126,7 +130,7 @@ IReadOnlyList targets )) { string id = $"selection.{type.FullName}.{occurrence}"; DrawCommon(context, state, matches.Cast().ToArray(), id); - if (Inno.Editor.ImGui.ImGui.Button("Reset Selected##" + id)) + if (Ui.Button("Reset Selected##" + id)) { using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Reset Components"); foreach (GameComponent match in matches.Cast()) @@ -136,10 +140,10 @@ IReadOnlyList targets transaction.Commit(); } - if (matches.All(value => value is not Inno.Scene.Components.Transform)) + if (matches.All(value => value is not Transform)) { - Inno.Editor.ImGui.ImGui.SameLine(0, -1); - if (Inno.Editor.ImGui.ImGui.Button("Remove Selected##" + id)) + Ui.SameLine(0, -1); + if (Ui.Button("Remove Selected##" + id)) { using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Remove Components"); foreach (GameComponent match in matches.Cast()) @@ -160,11 +164,11 @@ private void DrawAddComponents( InspectionDrawContext context, GameObject primary ) { - var widgets = EditorUiSession.current.widgets; + ImGuiWidget widgets = EditorUiSession.current.widgets; if (widgets.CenteredButton("Add Component to Selection", widgets.style.addButtonTopPadding)) { - m_componentSearch = ""; - Inno.Editor.ImGui.ImGui.OpenPopup("selection.add-component"); + m_componentSearch = string.Empty; + Ui.OpenPopup("selection.add-component"); } if (!widgets.BeginSearchPopup("selection.add-component", ref m_componentSearch, "Search components...", 256)) @@ -176,7 +180,7 @@ GameObject primary EditorInteraction interaction = context.interactions.For(InspectorInteractionIds.C_COMPONENT_AREA, primary); if (EditorUiSession.current.menus.DrawSearchItems(interaction, interaction.BuildMenu().items, m_componentSearch)) { - Inno.Editor.ImGui.ImGui.CloseCurrentPopup(); + Ui.CloseCurrentPopup(); } } finally @@ -207,7 +211,7 @@ string path { continue; } - var availability = properties.Select(( + (bool isVisible, bool isReadOnly)[] availability = properties.Select(( values, index ) => context.properties.GetPropertyAvailability( @@ -250,7 +254,7 @@ private sealed class SelectionEdits( IReadOnlyList targets ) : IInspectionPropertyEditService { - /// + /// public bool ChangeProperty( object owner, string propertyName, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs index ed397134f..85025bca4 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleEntryImGuiIdentity.cs @@ -4,13 +4,7 @@ namespace Inno.Editor.Panel.Logging; internal static class ConsoleEntryImGuiIdentity { - internal static void Push(string identity) - { - Ui.PushId(identity); - } + internal static void Push(string identity) => Ui.PushId(identity); - internal static void Pop() - { - Ui.PopId(); - } + internal static void Pop() => Ui.PopId(); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs index 8b592d596..dc2c98a83 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.Layout.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Numerics; +using Inno.Editor.ImGui; using EditorUI = Inno.Editor.ImGui.EditorUiSession; using Ui = Inno.Editor.ImGui.ImGui; @@ -60,7 +61,7 @@ private string AcquireCardWindow(string key) private void RetireCardWindows() { m_retiredCardKeys.Clear(); - foreach (var entry in m_cardSlots) + foreach (KeyValuePair entry in m_cardSlots) { if (entry.Value.lastFrame != m_cardFrame) { @@ -103,9 +104,14 @@ private void ClearLayout() private void RefreshLayout() { - var layout = Ui.GetLayout(); - var shape = (width: Ui.GetContentRegionAvailable().X, frameHeight: Ui.GetFrameHeight(), padding: layout.framePadding.Y, - spacing: layout.itemSpacing.Y, zoom: EditorUI.current.widgets.style.zoom); + EditorUiLayout layout = Ui.GetLayout(); + (float width, float frameHeight, float padding, float spacing, float zoom) shape = ( + width: Ui.GetContentRegionAvailable().X, + frameHeight: Ui.GetFrameHeight(), + padding: layout.framePadding.Y, + spacing: layout.itemSpacing.Y, + zoom: EditorUI.current.widgets.style.zoom + ); if (ReferenceEquals(m_layoutRows, m_view.rows) && m_layoutShape == shape && m_layoutOpenRevision == m_openRevision) { return; @@ -153,7 +159,7 @@ private void RefreshOffsets(int start) private void DrawVisibleEntries() { - var clip = Ui.GetClipBounds(); + (Vector2 minimum, Vector2 maximum) clip = Ui.GetClipBounds(); if (clip.maximum.Y <= clip.minimum.Y || clip.maximum.X <= clip.minimum.X) { return; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs index 2fa7a7b94..0204531b6 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanel.cs @@ -71,10 +71,7 @@ EditorInteractions interactions /// /// The project-level panel state that receives stable presentation values. /// - protected override void Capture(EditorState state) - { - state.Set("collapse", m_collapse); - } + protected override void Capture(EditorState state) => state.Set("collapse", m_collapse); /// /// Restores persistent Console layout preferences without restoring historical log content. @@ -82,12 +79,9 @@ protected override void Capture(EditorState state) /// /// The project-level panel state containing stable presentation values. /// - protected override void Restore(EditorState state) - { - m_collapse = state.Get("collapse", true); - } + protected override void Restore(EditorState state) => m_collapse = state.Get("collapse", true); - /// + /// protected override void OnDetach(EditorContext context) { ClearFocus(); @@ -414,7 +408,7 @@ out bool toggled content = m_content.FitTextWithEllipsis(m_content.GetFirstLine(entry.displayMessage), contentW); } - Vector2 tableOuterSize = new(tableOuterW, 0f); + var tableOuterSize = new Vector2(tableOuterW, 0f); ImGuiTableFlags flags = ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.NoHostExtendX | ImGuiTableFlags.NoPadOuterX @@ -635,7 +629,7 @@ string value ) { Ui.TableNextRow(); _ = Ui.TableSetColumnIndex(0); - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, label); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, label); _ = Ui.TableSetColumnIndex(1); EditorUI.current.widgets.WrappedText(value); } @@ -644,7 +638,7 @@ private static void DrawStackedField( string label, string value ) { - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, label); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, label); EditorUI.current.widgets.WrappedText(value); } #endregion diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs index 543486339..ee0d2100c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsolePanelContent.cs @@ -24,17 +24,15 @@ internal void DrawDisabledHint(string text) } internal (Vector4 color, string icon) GetLevelVisual(LogLevel level) + => level switch { - return level switch - { - LogLevel.Debug => (ConsoleStyle.debug, C_ICON_BUG), - LogLevel.Info => (ConsoleStyle.info, C_ICON_INFO), - LogLevel.Warn => (ConsoleStyle.warning, C_ICON_WARN), - LogLevel.Error => (ConsoleStyle.error, C_ICON_ERROR), - LogLevel.Fatal => (ConsoleStyle.fatal, C_ICON_FATAL), - _ => (EditorPalette.text, C_ICON_DEFAULT) - }; - } + LogLevel.Debug => (ConsoleStyle.debug, C_ICON_BUG), + LogLevel.Info => (ConsoleStyle.info, C_ICON_INFO), + LogLevel.Warn => (ConsoleStyle.warning, C_ICON_WARN), + LogLevel.Error => (ConsoleStyle.error, C_ICON_ERROR), + LogLevel.Fatal => (ConsoleStyle.fatal, C_ICON_FATAL), + _ => (EditorPalette.text, C_ICON_DEFAULT) + }; internal Vector4 GetCollapsedBgColor() => ConsoleStyle.collapsedCard; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs index 618f91075..78ea55391 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Console/ConsoleView.cs @@ -57,7 +57,7 @@ bool collapsed { if (Matches(occurrence, query, levels)) { - filtered.Add(new Row("occurrence/" + occurrence.sequence, occurrence, Array.AsReadOnly(new[] { occurrence }))); + filtered.Add(new Row("occurrence/" + occurrence.sequence, occurrence, Array.AsReadOnly([occurrence]))); } } } @@ -128,7 +128,7 @@ IReadOnlyList occurrences this.key = key; this.latest = latest; this.occurrences = occurrences; - copyTarget = new ConsoleEntryCopyTarget(latest, occurrences.Count); + this.copyTarget = new ConsoleEntryCopyTarget(latest, occurrences.Count); } internal string key { get; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Styling/ConsoleStyle.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Styling/ConsoleStyle.cs index ef94e75e6..b7f7ce3d0 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Styling/ConsoleStyle.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Styling/ConsoleStyle.cs @@ -7,32 +7,35 @@ internal readonly struct ConsoleStyle { private readonly float m_zoom; - internal ConsoleStyle(EditorStyleMetrics metrics) => m_zoom = metrics.zoom; + internal ConsoleStyle(EditorStyleMetrics metrics) + { + m_zoom = metrics.zoom; + } /// /// Gets debug log color. /// - internal static Vector4 debug { get; } = new(0.80f, 0.90f, 0.85f, EditorPalette.opacityOpaque); + internal static Vector4 debug { get; } = new(0.8f, 0.9f, 0.85f, EditorPalette.opacityOpaque); /// /// Gets informational log color. /// - internal static Vector4 info { get; } = new(0.20f, 1f, 0.20f, EditorPalette.opacityOpaque); + internal static Vector4 info { get; } = new(0.2f, 1f, 0.2f, EditorPalette.opacityOpaque); /// /// Gets warning log color. /// - internal static Vector4 warning { get; } = new(1f, 1f, 0.20f, EditorPalette.opacityOpaque); + internal static Vector4 warning { get; } = new(1f, 1f, 0.2f, EditorPalette.opacityOpaque); /// /// Gets error log color. /// - internal static Vector4 error { get; } = new(1f, 0.20f, 0.20f, EditorPalette.opacityOpaque); + internal static Vector4 error { get; } = new(1f, 0.2f, 0.2f, EditorPalette.opacityOpaque); /// /// Gets fatal log color. /// - internal static Vector4 fatal { get; } = new(1f, 0.20f, 1f, EditorPalette.opacityOpaque); + internal static Vector4 fatal { get; } = new(1f, 0.2f, 1f, EditorPalette.opacityOpaque); /// /// Gets collapsed log card background. @@ -47,7 +50,7 @@ internal readonly struct ConsoleStyle /// /// Gets the base expanded log card background. /// - internal static Vector4 expandedBase { get; } = new(0.10f, 0.10f, 0.10f, EditorPalette.opacityOpaque); + internal static Vector4 expandedBase { get; } = new(0.1f, 0.1f, 0.1f, EditorPalette.opacityOpaque); /// /// Gets the base expanded log card border. @@ -89,7 +92,7 @@ internal readonly struct ConsoleStyle /// /// The standard expanded-border base blended with the severity color. /// - internal static Vector4 GetExpandedBorder(Vector4 severityColor) => EditorPalette.Lerp(expandedBorderBase, severityColor, 0.20f); + internal static Vector4 GetExpandedBorder(Vector4 severityColor) => EditorPalette.Lerp(expandedBorderBase, severityColor, 0.2f); /// /// Gets the separator color used inside an expanded log card. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs index 1af843a9c..4bbec0f58 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.SceneView/SceneViewPanel.cs @@ -17,9 +17,11 @@ using Inno.Scene.Components; using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using EngineColor = Inno.Core.Mathematics.Color; using EngineMatrix = Inno.Core.Mathematics.Matrix; using EngineQuaternion = Inno.Core.Mathematics.Quaternion; using EngineVector3 = Inno.Core.Mathematics.Vector3; +using EngineVector4 = Inno.Core.Mathematics.Vector4; using ImGuizmoMode = Inno.Editor.ImGui.ImGuiWidget.TransformGizmoSpace; using ImGuizmoOperation = Inno.Editor.ImGui.ImGuiWidget.TransformGizmoOperation; using Ui = Inno.Editor.ImGui.ImGui; @@ -339,10 +341,7 @@ bool TryProject( EngineVector3 world, out Vector2 screen ) { - Inno.Core.Mathematics.Vector4 clip = Inno.Core.Mathematics.Vector4.Transform( - new Inno.Core.Mathematics.Vector4(world.x, world.y, world.z, 1f), - worldToClip - ); + EngineVector4 clip = EngineVector4.Transform(new EngineVector4(world.x, world.y, world.z, 1f), worldToClip); if (clip.w <= 0.000001f) { screen = default; @@ -735,7 +734,7 @@ string message } } - private static Inno.Core.Mathematics.Color ToEngineColor(Vector4 value) => new(value.X, value.Y, value.Z, value.W); + private static EngineColor ToEngineColor(Vector4 value) => new(value.X, value.Y, value.Z, value.W); private bool DrawManipulationToolbar(ManipulationToolbarLayout layout) { @@ -888,7 +887,7 @@ Vector2 viewportMaximum float spacing = 2f * zoom; float sectionSpacing = 8f * zoom; float itemExtent = MathF.Max(Ui.GetFrameHeight(), 26f * zoom); - Vector2 itemSize = new(itemExtent); + var itemSize = new Vector2(itemExtent); float width = itemExtent + padding * 2f; float height = padding * 2f + itemExtent * C_MANIPULATION_TOOL_COUNT + spacing * 2f + sectionSpacing; Vector2 minimum = viewportMinimum + new Vector2(inset); @@ -986,7 +985,14 @@ bool canInteract throw new InvalidOperationException("A transform gesture target is no longer available."); } EngineMatrix next = delta * transform.localToWorldMatrix; - if (!TryReadManipulatedTransform(next, transform, m_operation, out var position, out var rotation, out var scale) + if (!TryReadManipulatedTransform( + next, + transform, + m_operation, + out EngineVector3 position, + out EngineQuaternion rotation, + out EngineVector3 scale + ) || !IsUsable(position, rotation, scale) ) { throw new InvalidOperationException("The manipulated transform is not invertible or finite."); @@ -1026,7 +1032,7 @@ private Transform[] SelectedTransforms() GameComponent component => component.transform, _ => null }).OfType().Distinct().ToArray(); - var set = transforms.ToHashSet(); + HashSet set = transforms.ToHashSet(); return transforms.Where(value => !HasSelectedAncestor(value, set)).ToArray(); } @@ -1064,11 +1070,11 @@ private static bool TryReadManipulatedTransform( EngineMatrix matrix, Transform target, ImGuizmoOperation operation, - out Inno.Core.Mathematics.Vector3 position, + out EngineVector3 position, out EngineQuaternion rotation, - out Inno.Core.Mathematics.Vector3 scale + out EngineVector3 scale ) { - position = new Inno.Core.Mathematics.Vector3(matrix.m14, matrix.m24, matrix.m34); + position = new EngineVector3(matrix.m14, matrix.m24, matrix.m34); rotation = target.worldRotation; scale = target.worldScale; if (operation == ImGuizmoOperation.Translate) @@ -1078,7 +1084,7 @@ out Inno.Core.Mathematics.Vector3 scale if (operation == ImGuizmoOperation.Scale) { EngineMatrix original = target.localToWorldMatrix; - scale = new Inno.Core.Mathematics.Vector3( + scale = new EngineVector3( scale.x * SignedColumnRatio(original.m11, original.m21, original.m31, matrix.m11, matrix.m21, matrix.m31), scale.y * SignedColumnRatio(original.m12, original.m22, original.m32, matrix.m12, matrix.m22, matrix.m32), scale.z * SignedColumnRatio(original.m13, original.m23, original.m33, matrix.m13, matrix.m23, matrix.m33) @@ -1090,7 +1096,7 @@ out Inno.Core.Mathematics.Vector3 scale { return false; } - EngineMatrix normalized = new( + var normalized = new EngineMatrix( matrix.m11 / scale.x, matrix.m12 / scale.y, matrix.m13 / scale.z, @@ -1151,9 +1157,9 @@ private void CommitGesture() } private static bool IsUsable( - Inno.Core.Mathematics.Vector3 position, + EngineVector3 position, EngineQuaternion rotation, - Inno.Core.Mathematics.Vector3 scale + EngineVector3 scale ) => float.IsFinite(position.x) && float.IsFinite(position.y) && float.IsFinite(position.z) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs index c3522c4de..46e878acc 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs @@ -36,8 +36,8 @@ string description ) { this.key = key; this.path = path; - pagePath = path[..path.LastIndexOf('/')]; - label = path[(path.LastIndexOf('/') + 1)..]; + this.pagePath = path[..path.LastIndexOf('/')]; + this.label = path[(path.LastIndexOf('/') + 1)..]; this.section = section; this.description = description; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs index 61d027607..65b2b38fe 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsModal.cs @@ -302,9 +302,9 @@ float height Vector2 minimum = Ui.GetItemMinimum(); Vector2 maximum = Ui.GetItemMaximum(); - System.Numerics.Vector4 color = active - ? EditorPalette.contentAccent - : hovered ? EditorPalette.contentBorder : EditorPalette.contentBorderSoft; + Vector4 color = active + ? EditorPalette.contentAccent + : hovered ? EditorPalette.contentBorder : EditorPalette.contentBorderSoft; float centerX = (minimum.X + maximum.X) * 0.5f; Ui.DrawLine( new Vector2(centerX, minimum.Y), @@ -403,7 +403,7 @@ private void DrawNavigationButtons() float frameHeight = Ui.GetFrameHeight(); var buttonSize = new Vector2(frameHeight, frameHeight); Ui.BeginDisabled(!m_navigation.canGoBack); - if (Ui.Button($"{Inno.Editor.ImGui.ImGuiIcon.AngleLeft}##SettingsBack", buttonSize)) + if (Ui.Button($"{ImGuiIcon.AngleLeft}##SettingsBack", buttonSize)) { m_navigation.GoBack(); } @@ -411,7 +411,7 @@ private void DrawNavigationButtons() Ui.EndDisabled(); Ui.SameLine(0f, EditorUiSession.current.widgets.style.toolbarTightSpacing); Ui.BeginDisabled(!m_navigation.canGoForward); - if (Ui.Button($"{Inno.Editor.ImGui.ImGuiIcon.AngleRight}##SettingsForward", buttonSize)) + if (Ui.Button($"{ImGuiIcon.AngleRight}##SettingsForward", buttonSize)) { m_navigation.GoForward(); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs index e94cc77ad..7257c0348 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/SettingsPageView.cs @@ -23,11 +23,11 @@ Action navigate PushDisabledText(); EditorUI.current.widgets.WrappedText(page.description); Ui.PopStyleColor(); - Ui.Dummy(new System.Numerics.Vector2(0f, 16f * EditorUI.current.widgets.style.zoom)); + Ui.Dummy(new Vector2(0f, 16f * EditorUI.current.widgets.style.zoom)); if (page.children.Count != 0) { DrawOverview(page.children, navigate); - Ui.Dummy(new System.Numerics.Vector2(0f, 8f * EditorUI.current.widgets.style.zoom)); + Ui.Dummy(new Vector2(0f, 8f * EditorUI.current.widgets.style.zoom)); } if (!page.hasSettings) @@ -56,7 +56,7 @@ Action navigate private void DrawPageHeader(SettingsPage page) { ImGuiTableFlags flags = ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.NoPadOuterX; - if (!Ui.BeginTable("##settings_page_header", 2, flags, default(System.Numerics.Vector2), 0f)) + if (!Ui.BeginTable("##settings_page_header", 2, flags, default, 0f)) { return; } @@ -124,7 +124,7 @@ ref int fieldIndex bool tableStarted = false; try { - tableStarted = Ui.BeginTable("##settings_section", 3, flags, new System.Numerics.Vector2(tableWidth, 0f)); + tableStarted = Ui.BeginTable("##settings_section", 3, flags, new Vector2(tableWidth, 0f)); if (!tableStarted) { return; @@ -194,8 +194,8 @@ int fieldIndex private static void DrawFieldBackgroundGutters(uint background) { - var table = Ui.GetTableBounds(); - var window = Ui.GetWindowBounds(); + (float minimumX, float maximumX, float rowMinimum, float rowMaximum) table = Ui.GetTableBounds(); + (float minimumX, float maximumX, Vector2 workMaximum, Vector2 padding) window = Ui.GetWindowBounds(); float tableMinimumX = table.minimumX; float tableMaximumX = table.maximumX; float rowMinimumY = table.rowMinimum; @@ -213,8 +213,8 @@ private static void DrawFieldBackgroundGutters(uint background) if (tableMinimumX > windowMinimumX) { Ui.DrawFilledRectangle( - new System.Numerics.Vector2(windowMinimumX, rowMinimumY), - new System.Numerics.Vector2(tableMinimumX, rowMaximumY), + new Vector2(windowMinimumX, rowMinimumY), + new Vector2(tableMinimumX, rowMaximumY), background, 0 ); @@ -223,8 +223,8 @@ private static void DrawFieldBackgroundGutters(uint background) if (tableMaximumX < windowMaximumX) { Ui.DrawFilledRectangle( - new System.Numerics.Vector2(tableMaximumX, rowMinimumY), - new System.Numerics.Vector2(windowMaximumX, rowMaximumY), + new Vector2(tableMaximumX, rowMinimumY), + new Vector2(windowMaximumX, rowMaximumY), background, 0 ); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs index 5830de8e8..6552df6c9 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs @@ -14,7 +14,7 @@ internal static EditorHistoryChange CreateChange( ReadOnlySpan before, ReadOnlySpan after ) { - byte[] payload = new byte[sizeof(int) + before.Length + after.Length]; + var payload = new byte[sizeof(int) + before.Length + after.Length]; BinaryPrimitives.WriteInt32LittleEndian(payload, before.Length); before.CopyTo(payload.AsSpan(sizeof(int), before.Length)); after.CopyTo(payload.AsSpan(sizeof(int) + before.Length)); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/OpenSettingsAction.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/OpenSettingsAction.cs index 901ca08f3..48cfc5ac2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/OpenSettingsAction.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/OpenSettingsAction.cs @@ -6,7 +6,7 @@ namespace Inno.Editor.Panel.Settings; [EditorMenu(SettingsInteractionIds.C_MAIN_MENU_AREA, "Edit/Settings...", order: 1000)] internal sealed class OpenSettingsAction(SettingsWindowModule window) : EditorAction { - /// + /// protected override EditorActionState Query(EditorActionContext context) => new(true, window.canOpen, unavailableReason: window.unavailableReason); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs index c4618ba50..48011edac 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs @@ -25,37 +25,37 @@ internal sealed class SettingsField internal SettingsField(EditorSetting definition) { m_editor = definition; - scope = SettingsScope.Editor; - path = definition.path; - pagePath = definition.pagePath; - label = definition.label; - order = definition.order; - section = definition.section ?? string.Empty; - description = definition.description; + this.scope = SettingsScope.Editor; + this.path = definition.path; + this.pagePath = definition.pagePath; + this.label = definition.label; + this.order = definition.order; + this.section = definition.section ?? string.Empty; + this.description = definition.description; } internal SettingsField(ProjectSettingEditor definition) { m_project = definition; - scope = SettingsScope.Project; - path = definition.path; - pagePath = definition.pagePath; - label = definition.label; - order = definition.order; - section = definition.section ?? string.Empty; - description = definition.description; + this.scope = SettingsScope.Project; + this.path = definition.path; + this.pagePath = definition.pagePath; + this.label = definition.label; + this.order = definition.order; + this.section = definition.section ?? string.Empty; + this.description = definition.description; } internal SettingsField(BuildSettingsField definition) { m_build = definition; - scope = SettingsScope.Build; - path = definition.path; - pagePath = definition.pagePath; - label = definition.label; - order = 0; - section = definition.section; - description = definition.description; + this.scope = SettingsScope.Build; + this.path = definition.path; + this.pagePath = definition.pagePath; + this.label = definition.label; + this.order = 0; + this.section = definition.section; + this.description = definition.description; } internal SettingsScope scope { get; } @@ -105,8 +105,8 @@ IEditorHistory history m_buildPipeline = buildPipeline ?? throw new ArgumentNullException(nameof(buildPipeline)); m_buildSettings = buildSettings ?? throw new ArgumentNullException(nameof(buildSettings)); m_history = history ?? throw new ArgumentNullException(nameof(history)); - editorCatalogRevision = editorSettings.catalogRevision; - projectCatalogRevision = projectSettings.catalogRevision; + this.editorCatalogRevision = editorSettings.catalogRevision; + this.projectCatalogRevision = projectSettings.catalogRevision; m_buildDefault = buildSettings.defaultSettings; m_buildOriginal = buildSettings.Load(); m_buildValue = m_buildOriginal.Copy(); @@ -154,14 +154,14 @@ IEditorHistory history throw new InvalidOperationException($"Settings field path '{duplicatePath}' is registered more than once."); } - definitions = fields + this.definitions = fields .OrderBy(static field => field.path, StringComparer.Ordinal) .ThenBy(static field => field.order) .ToArray(); - pages = BuildPages(editorSettings.definitions, definitions); + this.pages = BuildPages(editorSettings.definitions, definitions); } - /// + /// public void Dispose() { m_applyTransaction?.Dispose(); @@ -384,7 +384,11 @@ internal bool Apply() private bool ApplyEditor() { - var values = m_editorModified.ToDictionary(path => path, path => m_editorValues[path], StringComparer.Ordinal); + Dictionary values = m_editorModified.ToDictionary( + path => path, + path => m_editorValues[path], + StringComparer.Ordinal + ); return m_editorSettings.Apply(values, m_editorResets); } @@ -408,7 +412,7 @@ private void AcceptEditorValues() private bool ApplyProject() { - var values = m_projectModified.ToDictionary(id => id, id => m_projectValues[id]); + Dictionary values = m_projectModified.ToDictionary(id => id, id => m_projectValues[id]); return m_projectSettings.Apply(values, m_projectResets); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs index 45460dfa5..2f72076a9 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsWindowModule.cs @@ -84,7 +84,7 @@ internal void FailPresentation() /// protected override void OnStart(EditorContext context) => m_reloadGuard = reloads.RegisterGuard(this); - /// + /// protected override void OnStop(EditorContext context) { Close(); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Styling/SettingsStyle.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Styling/SettingsStyle.cs index e08247097..fca00c371 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Styling/SettingsStyle.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Styling/SettingsStyle.cs @@ -7,7 +7,10 @@ internal readonly struct SettingsStyle { private readonly float m_zoom; - internal SettingsStyle(EditorStyleMetrics metrics) => m_zoom = metrics.zoom; + internal SettingsStyle(EditorStyleMetrics metrics) + { + m_zoom = metrics.zoom; + } internal static Vector4 field { get; } = new(0.36f, 0.36f, 0.38f, EditorPalette.opacityTrace); internal static Vector4 alternateField { get; } = new(0.52f, 0.52f, 0.56f, EditorPalette.opacityTrace); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs index fab3759af..02588d753 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Controls.cs @@ -1,9 +1,14 @@ using System; +using System.Globalization; +using System.IO; using System.Linq; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Graphs; using Inno.Editor.Core; using Inno.Editor.ImGui; +using Inno.Editor.Interactions; +using Inno.Editor.Rendering; using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; @@ -54,7 +59,7 @@ private void Controls(GraphNodeRecord node) "reroute.type", "Type", () => EditorUI.current.widgets.ColoredText( - Inno.Editor.ImGui.EditorPalette.textDisabled, + EditorPalette.textDisabled, Read(node, "valueType", new ShaderGraphType { id = "float" }).CreateType().id ) ); @@ -135,7 +140,7 @@ private void Controls(GraphNodeRecord node) EditorUI.current.widgets.WrappedText("Discard fragments where condition is true."); break; default: - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Extension node"); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Extension node"); break; } } @@ -143,13 +148,13 @@ private void Controls(GraphNodeRecord node) private void GraphCall(GraphNodeRecord node) { Guid selected = Read(node, "sourceId", Guid.Empty); - string path = Read(node, "sourcePath", ""); + string path = Read(node, "sourcePath", string.Empty); ShaderGraphNodeInterface nodeInterface = Read(node, ShaderGraphNodes.interfaceKey, new ShaderGraphNodeInterface()); InspectorRow("graph-node.asset", "Node Graph", () => { if (!EditorUI.current.widgets.BeginBoundedCombo( "##graph-node", - selected == Guid.Empty ? "Choose Shader node…" : System.IO.Path.GetFileName(path) + selected == Guid.Empty ? "Choose Shader node…" : Path.GetFileName(path) )) { return; } @@ -171,7 +176,7 @@ private void GraphCall(GraphNodeRecord node) candidate = owner.LoadGraphNodeInterface(id); } catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { continue; } @@ -180,7 +185,7 @@ private void GraphCall(GraphNodeRecord node) { continue; } - using var transaction = owner.interactions.history.BeginTransaction("Assign Graph Node"); + using EditorHistoryTransaction transaction = owner.interactions.history.BeginTransaction("Assign Graph Node"); Set(node, "sourceId", id); Set(node, "sourcePath", entry.assetPath.ToString()); Set(node, ShaderGraphNodes.interfaceKey, candidate); @@ -199,19 +204,19 @@ private void GraphCall(GraphNodeRecord node) InspectorRow( "graph-node.kind", "Kind", - () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.kind.ToString()) + () => EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, nodeInterface.kind.ToString()) ); InspectorRow( "graph-node.effect", "Effect", - () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.effect.ToString()) + () => EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, nodeInterface.effect.ToString()) ); if (nodeInterface.kind == ShaderGraphNodeKind.DomainOutput) { InspectorRow( "graph-node.role", "Target Role", - () => EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, nodeInterface.role) + () => EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, nodeInterface.role) ); } RepairPorts(node); @@ -452,7 +457,7 @@ Action apply }); } - InspectorRow("node-port.remove", "", () => + InspectorRow("node-port.remove", string.Empty, () => { if (EditorImGui.SmallButton("Remove")) { @@ -507,7 +512,7 @@ private void Scalar(GraphNodeRecord node) ) { if (EditorImGui.Selectable(candidate, type == candidate)) { - using var transaction = owner.interactions.history.BeginTransaction("Change Constant Type"); + using EditorHistoryTransaction transaction = owner.interactions.history.BeginTransaction("Change Constant Type"); Set(node, "type", candidate); switch (candidate) { @@ -572,7 +577,7 @@ private void Scalar(GraphNodeRecord node) }); break; case "uint": - string unsigned = Read(node, "value", 0u).ToString(System.Globalization.CultureInfo.InvariantCulture); + string unsigned = Read(node, "value", 0u).ToString(CultureInfo.InvariantCulture); InspectorRow("constant.value", "Value", () => { bool unsignedChanged = EditorImGui.InputText("##value", ref unsigned, 32, ImGuiInputTextFlags.CharsDecimal); @@ -589,13 +594,13 @@ private void Scalar(GraphNodeRecord node) private void Source(GraphNodeRecord node) { Guid selected = Read(node, "sourceId", Guid.Empty); - string path = Read(node, "sourcePath", ""); - string selectedFunction = Read(node, "function", ""); + string path = Read(node, "sourcePath", string.Empty); + string selectedFunction = Read(node, "function", string.Empty); InspectorRow("source.library", "Library", () => { if (!EditorUI.current.widgets.BeginBoundedCombo( "##library", - selected == Guid.Empty ? "Choose source library…" : System.IO.Path.GetFileName(path) + selected == Guid.Empty ? "Choose source library…" : Path.GetFileName(path) )) { return; } @@ -607,12 +612,12 @@ private void Source(GraphNodeRecord node) ) { if (EditorImGui.Selectable(entry.assetPath.ToString(), owner.AssetId(entry) == selected)) { - using var transaction = owner.interactions.history.BeginTransaction("Assign Shader Function"); + using EditorHistoryTransaction transaction = owner.interactions.history.BeginTransaction("Assign Shader Function"); Set(node, "sourceId", owner.AssetId(entry)); Set(node, "sourcePath", entry.assetPath.ToString()); if (owner.assets.TryLoad(entry.assetPath, out ShaderFunctionAsset? library) && library is not null) { - Set(node, "function", library.exports.FirstOrDefault() ?? ""); + Set(node, "function", library.exports.FirstOrDefault() ?? string.Empty); } transaction.Commit(); } @@ -627,7 +632,7 @@ private void Source(GraphNodeRecord node) if (selected == Guid.Empty) { EditorUI.current.widgets.ColoredText( - Inno.Editor.ImGui.EditorPalette.textDisabled, + EditorPalette.textDisabled, "Choose a library and one of its explicitly exported functions." ); } @@ -720,7 +725,7 @@ private void Input(GraphNodeRecord node) } if (kind == ShaderIrInputKind.Builtin) { - string stageId = Read(node, "stage", ""); + string stageId = Read(node, "stage", string.Empty); GraphNodeRecord? output = stageId.Length == 0 ? null : Controller.document.FindNode(new(stageId)); if (output is not null && Read(output, "settings", new ShaderGraphStageSettings()).stage == ShaderStage.Compute) { @@ -857,14 +862,14 @@ private void Input(GraphNodeRecord node) { ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(Controller.document, owner.serialization, owner.context); TextureAsset? texture = definition.properties.FirstOrDefault(value => value.id.value == input.id).defaultValue.texture; - if (texture is not null && owner.previews.TryGetTexture(texture, out var preview)) + if (texture is not null && owner.previews.TryGetTexture(texture, out EditorPreviewHandle preview)) { owner.previews.Draw(preview, new(120 * Canvas.zoom, 120 * Canvas.zoom)); } else { EditorUI.current.widgets.ColoredText( - Inno.Editor.ImGui.EditorPalette.textDisabled, + EditorPalette.textDisabled, texture is null ? "No default texture" : "Preparing preview…" ); } @@ -879,7 +884,7 @@ private void Output(GraphNodeRecord node) "output.passes", "Passes", () => EditorUI.current.widgets.ColoredText( - Inno.Editor.ImGui.EditorPalette.textDisabled, + EditorPalette.textDisabled, string.Join( ", ", ShaderGraphPrograms @@ -899,7 +904,9 @@ private void Output(GraphNodeRecord node) StageSettingsPopup(node, stage); if (stage.stage == ShaderStage.Compute) { - int x = stage.threadsX, y = stage.threadsY, z = stage.threadsZ; + int x = stage.threadsX; + int y = stage.threadsY; + int z = stage.threadsZ; InspectorRow("output.threads-x", "Threads X", () => { if (EditorImGui.InputInt("##threads-x", ref x, 1, 100, 0) && x > 0) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs index 2ceefcb61..2504d992f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.MiniMap.cs @@ -54,7 +54,7 @@ out Vector2 maximum return false; } float zoom = EditorUI.current.widgets.style.zoom; - Vector2 size = new(MathF.Min(C_MINI_MAP_WIDTH * zoom, m_size.X * 0.30f), MathF.Min(C_MINI_MAP_HEIGHT * zoom, m_size.Y * 0.30f)); + var size = new Vector2(MathF.Min(C_MINI_MAP_WIDTH * zoom, m_size.X * 0.3f), MathF.Min(C_MINI_MAP_HEIGHT * zoom, m_size.Y * 0.3f)); maximum = m_origin + new Vector2(m_size.X - C_MINI_MAP_MARGIN * zoom, C_MINI_MAP_MARGIN * zoom + size.Y); minimum = maximum - size; return true; @@ -100,7 +100,7 @@ private void DrawMiniMap() ); } - DrawMiniMapContents(Inno.Editor.ImGui.ImGui.GetDrawList(), layout); + DrawMiniMapContents(ImGuiApi.GetDrawList(), layout); } finally { @@ -126,7 +126,7 @@ Vector2 maximum foreach (GraphNodeRecord node in Controller.document.nodes) { GraphPosition position = draft.pointer.previewPositions.GetValueOrDefault(node.id, node.position); - Vector2 nodeMinimum = new(position.x, position.y); + var nodeMinimum = new Vector2(position.x, position.y); Vector2 nodeMaximum = nodeMinimum + new Vector2(NodeWidth(node), C_HEADER + Rows(node) * C_ROW + 20f); m_miniMapGeometry.Add(node.id, new(nodeMinimum, nodeMaximum)); worldMinimum = Vector2.Min(worldMinimum, nodeMinimum); @@ -158,7 +158,7 @@ MiniMapLayout layout foreach (GraphNodeRecord node in Controller.document.nodes) { MiniMapNodeGeometry geometry = m_miniMapGeometry[node.id]; - uint fill = Canvas.selectedNodes.Contains(node.id) ? Color(0.60f, 0.44f, 0.83f) : Color(0.34f, 0.37f, 0.44f); + uint fill = Canvas.selectedNodes.Contains(node.id) ? Color(0.6f, 0.44f, 0.83f) : Color(0.34f, 0.37f, 0.44f); draw.FilledRectangle(layout.ToScreen(geometry.minimum), layout.ToScreen(geometry.maximum), fill, 2f, false); } @@ -166,7 +166,7 @@ MiniMapLayout layout Vector2 viewMaximum = viewMinimum + m_size / Canvas.zoom; Vector2 screenMinimum = layout.ToScreen(viewMinimum); Vector2 screenMaximum = layout.ToScreen(viewMaximum); - draw.FilledRectangle(screenMinimum, screenMaximum, Color(0.65f, 0.47f, 0.88f, 0.10f), 0, false); + draw.FilledRectangle(screenMinimum, screenMaximum, Color(0.65f, 0.47f, 0.88f, 0.1f), 0, false); draw.Rectangle(screenMinimum, screenMaximum, Color(0.76f, 0.62f, 0.95f), 0f, 1.5f); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs index ced227d93..c04571b93 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Parameters.cs @@ -2,6 +2,7 @@ using System.Linq; using Inno.Core.Graphs; using Inno.Editor.ImGui; +using Inno.Editor.Inspection; using Inno.Editor.Shaders; using Inno.Editor.Shaders.ImGui; using Inno.Rendering; @@ -344,9 +345,9 @@ bool continuous } } - private sealed class ParameterEdits(ShaderEditorCanvas canvas) : Inno.Editor.Inspection.IInspectionPropertyEditService + private sealed class ParameterEdits(ShaderEditorCanvas canvas) : IInspectionPropertyEditService { - /// + /// public bool ChangeProperty( object owner, string propertyName, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs index 8e131390e..d22517526 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PassSettings.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using Inno.Core.Graphs; using Inno.Editor.ImGui; @@ -44,7 +45,7 @@ ShaderGraphStageSettings stage { activePass = programs.FirstOrDefault(program => program.stages.Contains(node.id.value, StringComparer.Ordinal)).pass ?? definition.passes.FirstOrDefault().name - ?? ""; + ?? string.Empty; } InspectorRow("settings.pass", "Pass State", () => { @@ -81,7 +82,10 @@ ShaderGraphStageSettings stage } if (assignmentChanged) { - var stageIds = (assignment.stages ?? []).Where(id => id != node.id.value).Select(static id => new GraphNodeId(id)).ToList(); + List stageIds = (assignment.stages ?? []) + .Where(id => id != node.id.value) + .Select(static id => new GraphNodeId(id)) + .ToList(); if (assigned) { stageIds.RemoveAll( @@ -124,7 +128,7 @@ ShaderGraphStageSettings stage changed = true; } - string semantic = output.semantic ?? ""; + string semantic = output.semantic ?? string.Empty; bool semanticChanged = false; InspectorRow( "output.semantic", @@ -226,8 +230,10 @@ ShaderGraphStageSettings stage changed = true; } - bool depthWrite = state.depthWrite, multisampling = state.multisampling; - bool depthWriteChanged = false, multisamplingChanged = false; + bool depthWrite = state.depthWrite; + bool multisampling = state.multisampling; + bool depthWriteChanged = false; + bool multisamplingChanged = false; InspectorRow( "state.depth-write", "Depth Write", @@ -316,7 +322,8 @@ ShaderGraphStageSettings stage RenderBlendFactor colorDestination = blend.colorDestination; RenderBlendFactor alphaSource = blend.alphaSource; RenderBlendFactor alphaDestination = blend.alphaDestination; - RenderBlendEquation colorEquation = blend.colorEquation, alphaEquation = blend.alphaEquation; + RenderBlendEquation colorEquation = blend.colorEquation; + RenderBlendEquation alphaEquation = blend.alphaEquation; if (EnumControl("RGB Source", ref colorSource)) { blend.colorSource = colorSource; @@ -394,7 +401,8 @@ ShaderGraphStageSettings stage for (int j = 0; j < keyword.options.Length; j++) { string option = keyword.options[j]; - bool optionChanged = false, remove = false; + bool optionChanged = false; + bool remove = false; InspectorRow("variant.option", "Option " + (j + 1), () => { optionChanged = EditorImGui.InputText("##option", ref option, 128); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs index 10540b7e0..8123a0c75 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.PortRepair.cs @@ -55,7 +55,7 @@ private void RepairPorts(GraphNodeRecord node) || old.type.IsEquivalentTo(replacement.type); ImGuiApi.BeginDisabled(occupied || !compatible); bool selected = ImGuiApi.Selectable( - replacement.id + (occupied ? " · connected" : !compatible ? " · different type" : "") + replacement.id + (occupied ? " · connected" : !compatible ? " · different type" : string.Empty) ); ImGuiApi.EndDisabled(); if (!selected) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs index 6d8fcc6c2..360dc976e 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.SourceSettings.cs @@ -3,6 +3,8 @@ using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; +using Inno.Editor.Assets.ImGui; using Inno.Editor.ImGui; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; @@ -23,7 +25,7 @@ private void SourceSettings(Guid sourceId) InspectorRow("source.actions", "Source", () => { if (EditorImGui.SmallButton("Show in File Browser") - && owner.interactions.TryGetModule(out var browser) + && owner.interactions.TryGetModule(out AssetBrowserModule? browser) && browser is not null ) { RevealShaderFunction.Reveal(owner, browser, sourceId); @@ -52,7 +54,10 @@ private void SourceSettings(Guid sourceId) EditorImGui.BeginDisabled(readOnly); try { - var settings = owner.serialization.Deserialize(draft.sourceSettings, owner.context); + ShaderSourceImportSettings settings = owner.serialization.Deserialize( + draft.sourceSettings, + owner.context + ); bool changed = false; InspectorRow("source.language", "Language", () => { @@ -121,7 +126,8 @@ private void SourceSettings(Guid sourceId) try { string function = settings.exports[i]; - bool functionChanged = false, remove = false; + bool functionChanged = false; + bool remove = false; InspectorRow("source.export", "Function " + (i + 1), () => { functionChanged = EditorImGui.InputText("##name", ref function, 256); @@ -251,7 +257,7 @@ out ShaderFunctionAsset? replacement if (readOnly) { EditorUI.current.widgets.ColoredText( - Inno.Editor.ImGui.EditorPalette.textDisabled, + EditorPalette.textDisabled, "Installed source settings are read-only." ); } @@ -261,7 +267,7 @@ out ShaderFunctionAsset? replacement } } catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.sourceSettingsStatus = failure.Message; EditorUI.current.widgets.WrappedText(draft.sourceSettingsStatus); @@ -284,6 +290,6 @@ Guid sourceId draft.settingsSource = sourceId; draft.sourceSettingsFingerprint = snapshot.fingerprint; draft.sourceSettings = owner.serialization.Serialize(settings, owner.context); - draft.sourceSettingsStatus = ""; + draft.sourceSettingsStatus = string.Empty; } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs index e75056e6e..460f5fb15 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Target.cs @@ -24,7 +24,7 @@ private void DrawTarget() { if (ImGuiApi.Selectable("Explicit Stages", current.Length == 0)) { - Assign(""); + Assign(string.Empty); } if (owner.targets is { } targets) { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs index c26447814..55275b99d 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.Techniques.cs @@ -26,7 +26,8 @@ private bool TechniqueControls(ShaderDefinition definition) try { ShaderTechniqueDefinition technique = definition.techniques[i]; - string id = technique.id.value ?? "", contract = technique.contract.value ?? ""; + string id = technique.id.value ?? string.Empty; + string contract = technique.contract.value ?? string.Empty; bool idChanged = false; InspectorRow("technique.id", "ID", () => idChanged = EditorImGui.InputText("##id", ref id, 128)); if (idChanged) @@ -68,7 +69,7 @@ private bool TechniqueControls(ShaderDefinition definition) try { ShaderTechniquePass mapping = technique.passes[j]; - string role = mapping.role.value ?? ""; + string role = mapping.role.value ?? string.Empty; bool roleChanged = false; InspectorRow("technique.role", "Role", () => roleChanged = EditorImGui.InputText("##role", ref role, 128)); if (roleChanged) @@ -130,7 +131,7 @@ private bool TechniqueControls(ShaderDefinition definition) new() { role = new("role-" + technique.passes.Length), - passName = definition.passes.FirstOrDefault().name ?? "" + passName = definition.passes.FirstOrDefault().name ?? string.Empty } ]; changed = true; diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs index ccc0bdff0..32c3c62a8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Canvas/ShaderEditorCanvas.cs @@ -1,13 +1,16 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Numerics; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Graphs; using Inno.Editor.Core; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; using Inno.Editor.ImGui; +using Inno.Editor.Inspection; using Inno.Editor.Interactions; using Inno.Editor.Rendering; using Inno.Editor.Shaders; @@ -30,7 +33,7 @@ GraphPortDirection direction ); internal const string C_AREA = "panel/rendering.shader-editor"; - private static readonly Vector4 C_EMPTY_GROUP_HEADER = new(0.16f, 0.17f, 0.20f, EditorPalette.opacityOpaque); + private static readonly Vector4 C_EMPTY_GROUP_HEADER = new(0.16f, 0.17f, 0.2f, EditorPalette.opacityOpaque); private const string C_NODE_WIDTH = "editor.width"; private const float C_DEFAULT_WIDTH = 270f; private const float C_MINIMUM_WIDTH = 180f; @@ -119,7 +122,8 @@ internal void Draw() Pointer(hovered && !miniMapHovered); if (draft.pointer.isBoxSelecting) { - Vector2 min = Vector2.Min(draft.pointer.boxStart, mouse), max = Vector2.Max(draft.pointer.boxStart, mouse); + Vector2 min = Vector2.Min(draft.pointer.boxStart, mouse); + Vector2 max = Vector2.Max(draft.pointer.boxStart, mouse); draw.FilledRectangle(min, max, Color(0.52f, 0.37f, 0.78f, EditorPalette.opacitySubtle), 0, false); draw.Rectangle(min, max, Color(0.65f, 0.47f, 0.88f), 0, 1f); } @@ -164,7 +168,7 @@ private void SynchronizeInspection() } internal void DrawInspector( - Inno.Editor.Inspection.InspectionDrawContext inspection, + InspectionDrawContext inspection, IReadOnlyList selected ) { m_inspection = inspection; @@ -188,7 +192,7 @@ private void DrawInspectorContents(IReadOnlyList selected) "Preview", "The preview uses the current draft without publishing it to Scene or Game views." )) { - var preview = owner.Preview(draft); + EditorShaderDraftCompilationSnapshot? preview = owner.Preview(draft); if (preview is null) { EditorUI.current.widgets.Hint("Run Check to build a preview for the current draft."); @@ -199,13 +203,13 @@ private void DrawInspectorContents(IReadOnlyList selected) } else if (preview.state == EditorShaderCompilationState.Succeeded && preview.artifact is not null - && owner.interactions.TryGetModule(out var images) + && owner.interactions.TryGetModule(out ShaderPreviews? images) && images is not null ) { - var shader = owner.assets.Load(draft.path); + ShaderAsset shader = owner.assets.Load(draft.path); images.Draw( draft.id, - new Inno.Rendering.Assets.MaterialAsset { shader = shader }, + new MaterialAsset { shader = shader }, preview, MathF.Max(1f, MathF.Min(256f, ImGuiApi.GetContentRegionAvailable().X)) ); @@ -255,8 +259,12 @@ or FormatException } if (Controller.document.metadata.ContainsKey(ShaderGraphDocument.definitionKey)) { - var definition = ShaderGraphDocument.ReadDefinition(Controller.document, owner.serialization, owner.context); - foreach (var property in definition.properties) + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + Controller.document, + owner.serialization, + owner.context + ); + foreach (ShaderPropertyDefinition property in definition.properties) { InspectorRow( "definition." + property.id.value, @@ -328,7 +336,7 @@ or FormatException } private GraphNodeRecord[]? m_inspectionNodes; - private Inno.Editor.Inspection.InspectionDrawContext? m_inspection; + private InspectionDrawContext? m_inspection; private static void InspectorRow( string id, @@ -346,7 +354,7 @@ internal static void DrawHeader( ImGuiApi.SetNextItemWidth(-1f); string title = draft is null ? "Select Shader" - : System.IO.Path.GetFileName(draft.path.localPath) + (owner.Controller(draft).isDirty ? " *" : ""); + : Path.GetFileName(draft.path.localPath) + (owner.Controller(draft).isDirty ? " *" : string.Empty); if (EditorUI.current.widgets.BeginBoundedCombo("##shader-header-select", title)) { try @@ -459,7 +467,7 @@ private void RefreshPorts() } } catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.nodeErrors[node.id] = failure.Message; } @@ -606,7 +614,7 @@ private void Pointer(bool hovered) { if (resizeTarget is not null) { - draft.selectedGroupId = ""; + draft.selectedGroupId = string.Empty; draft.selectedEdge = null; Canvas.SelectNodes([resizeTarget.id]); draft.resizingNode = resizeTarget.id; @@ -632,7 +640,7 @@ private void Pointer(bool hovered) } if (hitNode is null && HitPort(mouse) is null) { - draft.selectedGroupId = ""; + draft.selectedGroupId = string.Empty; draft.selectedEdge = HitEdge(mouse); if (draft.selectedEdge is not null) { @@ -657,7 +665,7 @@ private void Pointer(bool hovered) }); if (intent.nodePressed is GraphNodeId pressed && Controller.document.FindNode(pressed) is { } node) { - draft.selectedGroupId = ""; + draft.selectedGroupId = string.Empty; draft.selectedEdge = null; SetStage(node); SynchronizeInspection(); @@ -694,7 +702,7 @@ private void Node( GraphNodeRecord node, Vector2 mouse ) { - var rect = Rect(node); + (Vector2 min, Vector2 max) rect = Rect(node); if (rect.max.X < m_origin.X || rect.min.X > m_origin.X + m_size.X || rect.max.Y < m_origin.Y || rect.min.Y > m_origin.Y + m_size.Y) { return; @@ -737,7 +745,7 @@ Vector2 mouse EditorUI.current.widgets.DrawTooltip( port.type.id + (missing ? " · missing port; reconnect explicitly" - : optional ? " · optional input" : port.direction == GraphPortDirection.Input ? " · required input" : "") + : optional ? " · optional input" : port.direction == GraphPortDirection.Input ? " · required input" : string.Empty) ); } } @@ -796,7 +804,8 @@ private void Groups(EditorDrawList draw) { continue; } - Vector2 min = bounds.min, max = bounds.max; + Vector2 min = bounds.min; + Vector2 max = bounds.max; bool selected = draft.selectedGroupId == group.id; Vector4 headerColor = GroupHeaderColor(group); Vector4 bodyColor = EditorPalette.WithOpacity(headerColor, EditorPalette.opacitySoft); @@ -840,12 +849,13 @@ private void Groups(EditorDrawList draw) private (Vector2 min, Vector2 max)? GroupRect(ShaderCanvasGroup group) { - Vector2 min = new(float.MaxValue), max = new(float.MinValue); + var min = new Vector2(float.MaxValue); + var max = new Vector2(float.MinValue); foreach (string id in group.nodes) { if (Controller.document.FindNode(new(id)) is GraphNodeRecord node) { - var rect = Rect(node); + (Vector2 min, Vector2 max) rect = Rect(node); min = Vector2.Min(min, rect.min); max = Vector2.Max(max, rect.max); } @@ -972,9 +982,7 @@ void Curve( Vector2 a, Vector2 b, bool selected = false - ) { - View.DrawConnection(draw, a, b, selected ? Color(0.87f, 0.72f, 1f) : Color(0.59f, 0.46f, 0.82f), selected ? 3f : 2f); - } + ) => View.DrawConnection(draw, a, b, selected ? Color(0.87f, 0.72f, 1f) : Color(0.59f, 0.46f, 0.82f), selected ? 3f : 2f); } private GraphEdgeId? HitEdge(Vector2 mouse) @@ -1132,16 +1140,16 @@ private static Vector4 StableHeaderColor( float startHue, float hueRange ) { - uint hash = 2166136261; + uint hash = 2_166_136_261; foreach (char value in key) { hash ^= value; - hash *= 16777619; + hash *= 16_777_619; } - float hue = (startHue + hueRange * (hash & 0xffff) / 65535f) % 360f; - float saturation = 0.52f + 0.12f * ((hash >> 16) & 0xff) / 255f; - float brightness = 0.34f + 0.08f * ((hash >> 24) & 0xff) / 255f; + float hue = (startHue + hueRange * (hash & 0xFFFF) / 65535f) % 360f; + float saturation = 0.52f + 0.12f * ((hash >> 16) & 0xFF) / 255f; + float brightness = 0.34f + 0.08f * ((hash >> 24) & 0xFF) / 255f; float chroma = brightness * saturation; float sector = hue / 60f; float secondary = chroma * (1f - MathF.Abs(sector % 2f - 1f)); @@ -1235,7 +1243,7 @@ private void SetStage(GraphNodeRecord? node) { return; } - string stage = node.definitionId == ShaderGraphDocument.outputDefinitionId ? node.id.value : Read(node, "stage", ""); + string stage = node.definitionId == ShaderGraphDocument.outputDefinitionId ? node.id.value : Read(node, "stage", string.Empty); if (stage.Length != 0) { draft.activeStage = new(stage); @@ -1251,7 +1259,8 @@ private void Frame() { return; } - float minX = selection.Min(static node => node.position.x), minY = selection.Min(static node => node.position.y); + float minX = selection.Min(static node => node.position.x); + float minY = selection.Min(static node => node.position.y); float maxX = selection.Max(node => node.position.x + NodeWidth(node)); float maxY = selection.Max(node => node.position.y + C_HEADER + Rows(node) * C_ROW + 20); float scale = Math.Clamp( @@ -1284,7 +1293,7 @@ internal string Title(GraphNodeRecord node) if (node.definitionId == "inno.shader.source") { - string function = Read(node, "function", ""); + string function = Read(node, "function", string.Empty); return function.Length == 0 ? "Source Function" : function; } @@ -1304,6 +1313,8 @@ internal string Title(GraphNodeRecord node) { return "Function Outputs"; } - return EditorDisplayNames.Nicify(node.definitionId.Replace("inno.shader.", "", StringComparison.Ordinal).Replace('-', ' ')); + return EditorDisplayNames.Nicify( + node.definitionId.Replace("inno.shader.", string.Empty, StringComparison.Ordinal).Replace('-', ' ') + ); } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs index f17f9a89e..37ddfaa29 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.CanvasEdits.cs @@ -19,7 +19,7 @@ internal void CompleteCanvasEdit(Draft draft) if (draft.pendingMove is { } positions) { bool changed = false; - foreach (var entry in positions) + foreach (KeyValuePair entry in positions) { changed |= controller.document.FindNode(entry.Key) is not { } current || current.position != entry.Value; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs index e082cc263..b2866ac56 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs @@ -1,7 +1,9 @@ using System; +using System.Collections.Generic; using System.Linq; using Inno.Core.Graphs; using Inno.Editor.Graph; +using Inno.Rendering; using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; @@ -28,7 +30,8 @@ ShaderClipboardData data ) { GraphDocument destination = Controller(draft).document; GraphDocument fragment = GraphDocumentCodec.Decode(data.graph, serialization); - var existingStages = destination.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) + HashSet existingStages = destination.nodes + .Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) .Select(node => ShaderGraphDocument.Read(node, "settings", new ShaderGraphStageSettings(), serialization, context).stage) .ToHashSet(); return !fragment.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs index 44f39f85e..998cfa10c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using Inno.Assets; +using Inno.Core.Execution; using Inno.Core.Graphs; using Inno.Rendering; using Inno.Rendering.Assets; @@ -25,10 +26,13 @@ ShaderNodeCreation creation ) { GraphDocument graph = Controller(draft).document; GraphNodeId? stage = draft.createFromPort is GraphEndpoint endpoint - ? new(ShaderGraphDocument.Read(graph.FindNode(endpoint.nodeId)!, "stage", "", serialization, context)) + ? new(ShaderGraphDocument.Read(graph.FindNode(endpoint.nodeId)!, "stage", string.Empty, serialization, context)) : draft.activeStage ?? graph.nodes.FirstOrDefault(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId)?.id; - var node = new GraphNodeRecord(new(Guid.NewGuid().ToString("N")), creation.definitionId) { position = draft.menuPosition }; + var node = new GraphNodeRecord( + new(Guid.NewGuid().ToString("N")), + creation.definitionId + ) { position = draft.menuPosition }; if (stage is GraphNodeId id) { node.SetValue("stage", ShaderGraphDocument.Encode(id.value, serialization, context)); @@ -50,7 +54,7 @@ ShaderNodeCreation creation id = name, kind = ShaderIrInputKind.Uniform, type = new() { id = "float4" }, - semantic = "" + semantic = string.Empty }, serialization, context) ); } @@ -104,7 +108,7 @@ ShaderNodeCreation creation internal IReadOnlyList Describe(GraphNodeRecord node) { ShaderSourceModuleAnalysis? module = null; - string implementation = ""; + string implementation = string.Empty; ShaderIrStageInput? input = node.definitionId == "inno.shader.stage-input" ? ShaderGraphDocument.Read(node, "settings", new ShaderGraphInputSettings(), serialization, context).CreateBinding() : null; @@ -120,7 +124,7 @@ internal IReadOnlyList Describe(GraphNodeRecord node) } if (id != Guid.Empty && assets.TryLoad(id, out ShaderFunctionAsset? function) && function is not null && !function.isMissing) { - string selected = ShaderGraphDocument.Read(node, "function", "", serialization, context); + string selected = ShaderGraphDocument.Read(node, "function", string.Empty, serialization, context); module = frontends.AnalyzeModule( ShaderSourceBundle.Decode(ShaderSourceBundle.Read(function, assets), selected, serialization) ); @@ -148,11 +152,9 @@ internal IReadOnlyList Describe(GraphNodeRecord node) } internal ShaderGraphNodeInterface LoadGraphNodeInterface(Guid id) - { - return TryLoadGraphNodeInterface(id, out ShaderGraphNodeInterface? nodeInterface) - ? nodeInterface! - : throw new InvalidOperationException("Graph node Shader is unavailable or has import diagnostics."); - } + => TryLoadGraphNodeInterface(id, out ShaderGraphNodeInterface? nodeInterface) + ? nodeInterface! + : throw new InvalidOperationException("Graph node Shader is unavailable or has import diagnostics."); private bool TryLoadGraphNodeInterface( Guid id, @@ -205,7 +207,7 @@ ShaderNodeCreation creation return CompatibleInput(draft, PrepareNode(draft, creation)) is not null; } catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or IOException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { return false; } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs index b7a97feb5..ee387ad0b 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs @@ -3,9 +3,12 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Diagnostics; +using Inno.Core.Events; +using Inno.Core.Execution; using Inno.Core.Graphs; using Inno.Core.IO; using Inno.Core.Serialization; @@ -38,7 +41,7 @@ internal sealed partial class ShaderEditorDocuments : EditorModule private long m_sourceRevision = long.MinValue; private readonly GraphEditorModule m_graphs; private readonly ShaderGraphSourceStore m_sources; - private Inno.Core.Execution.LifetimeScope? m_lifetime; + private LifetimeScope? m_lifetime; private ShaderNodeCompilerRegistry? m_nodes; private ShaderSourceFrontendRegistry? m_frontends; internal ShaderNodeDrawerRegistry? drawers; @@ -104,7 +107,7 @@ internal EditorShaderDraftCompilationSnapshot Check(Draft draft) or ArgumentException or FormatException or NotSupportedException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { nodeSnapshot = new( EditorShaderCompilationState.Failed, @@ -281,7 +284,7 @@ internal void RefreshCompilation(Draft draft) { _ = ShaderGraphNodes.ReadInterface(document, serialization, context); draft.compilationStatus = "Reusable node · interface valid"; - draft.compilationDiagnostics = ""; + draft.compilationDiagnostics = string.Empty; return; } @@ -319,7 +322,7 @@ internal void RefreshCompilation(Draft draft) draft.diagnostics = snapshot.diagnostics.ToArray(); } catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.compilationStatus = "Compilation unavailable"; draft.compilationDiagnostics = failure.Message; @@ -342,7 +345,7 @@ internal void RemoveNodes(Draft draft) candidate.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, serialization, context)); if (draft.selectedGroupId.Length != 0 && !groups.Any(group => group.id == draft.selectedGroupId)) { - draft.selectedGroupId = ""; + draft.selectedGroupId = string.Empty; } controller.ReplaceDocument(candidate, "Delete Shader Nodes"); if (draft.activeStage is GraphNodeId stage && controller.document.FindNode(stage) is null) @@ -375,10 +378,10 @@ internal void Changed(Draft draft) try { PreserveRecovery(draft, controller); - draft.error = ""; + draft.error = string.Empty; } catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.error = "Recovery could not be written: " + failure.Message; } @@ -402,7 +405,7 @@ internal bool Save(Draft draft) controller.MarkSaved(); draft.observedRevision = controller.revision; m_pendingImports.Add(draft.path); - draft.error = ""; + draft.error = string.Empty; draft.status = "Saved"; draft.nextCompilationPoll = 0; string recovery = RecoveryPath(draft.id); @@ -414,7 +417,7 @@ internal bool Save(Draft draft) return true; } catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.error = failure.Message; draft.status = "Not saved · recovery retained"; @@ -433,7 +436,7 @@ internal bool Reload(Draft draft) draft.hash = source.contentHash; draft.readOnly = source.isReadOnly; draft.observedRevision = controller.revision; - draft.error = ""; + draft.error = string.Empty; draft.status = "Reloaded · compilation is separate"; string recovery = RecoveryPath(draft.id); if (File.Exists(recovery)) @@ -443,7 +446,7 @@ internal bool Reload(Draft draft) return true; } catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.error = failure.Message; return false; @@ -467,7 +470,7 @@ protected override void OnStart(EditorContext editor) templates = m_lifetime.Own(new ShaderGraphTemplateRegistry(m_types)); targets = m_lifetime.Own(new ShaderTargetRegistry(m_types)); _ = m_lifetime.Own(interactions.documents.RegisterProvider(new Provider(this))); - var operations = m_lifetime.Own(interactions.events.CreateHub(int.MaxValue - 1)); + EventHub operations = m_lifetime.Own(interactions.events.CreateHub(int.MaxValue - 1)); operations.Listen(_ => CompleteCanvasEdits()); } catch (Exception failure) @@ -516,7 +519,7 @@ protected override void OnUpdate(EditorContext editor) or UnauthorizedAccessException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { foreach (Draft draft in m_drafts.Values.Where(draft => draft.path == path)) { @@ -630,14 +633,14 @@ private void Open(EditorDocumentContext document) } ShaderGraphSourceSnapshot? source = null; - string missing = ""; + string missing = string.Empty; try { source = m_sources.Read(path); } catch (Exception failure) when ((recovery is not null && failure is IOException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { missing = failure.Message; } @@ -647,7 +650,7 @@ private void Open(EditorDocumentContext document) source?.document ?? new GraphDocument(), interactions.history ); - string staleRecovery = ""; + string staleRecovery = string.Empty; bool canRecover = recovery is not null && (source is null || recovery.hash == source.contentHash); if (canRecover && !controller.isDirty) { @@ -775,7 +778,7 @@ private void SynchronizeSources() { if (wasMissing) { - draft.error = ""; + draft.error = string.Empty; } continue; } @@ -790,14 +793,14 @@ private void SynchronizeSources() m_graphs.RebindDocument(draft.id, source.document); draft.hash = source.contentHash; draft.observedRevision = controller.revision; - draft.error = ""; + draft.error = string.Empty; draft.status = "Source updated · compilation is separate"; } catch (Exception failure) when ((failure is IOException or UnauthorizedAccessException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { draft.error = failure.Message; } @@ -902,10 +905,10 @@ bool readOnly internal string hash = hash; internal bool readOnly = readOnly; internal ulong observedRevision; - internal string error = ""; + internal string error = string.Empty; internal string status = "Saved"; internal string compilationStatus = "Waiting for import"; - internal string compilationDiagnostics = ""; + internal string compilationDiagnostics = string.Empty; internal ShaderDiagnostic[] diagnostics = []; internal ulong checkedRevision = ulong.MaxValue; internal EditorShaderCompilationState? checkedState; @@ -915,16 +918,16 @@ bool readOnly internal GraphEdgeId? selectedEdge; internal bool frameRequested; internal ShaderCanvasGroup[] groups = []; - internal string selectedGroupId = ""; + internal string selectedGroupId = string.Empty; internal readonly HashSet expandedPreviews = []; internal Guid settingsSource; internal byte[] sourceSettings = []; - internal string sourceSettingsFingerprint = ""; - internal string sourceSettingsStatus = ""; + internal string sourceSettingsFingerprint = string.Empty; + internal string sourceSettingsStatus = string.Empty; internal readonly GraphCanvasState canvas = new(); internal GraphPosition menuPosition; internal GraphNodeId? activeStage; - internal string inspectedPass = ""; + internal string inspectedPass = string.Empty; internal GraphNodeId[] inspectedNodes = []; internal ShaderInspectionSelection? inspectionSelection; internal string valueGesture = Guid.NewGuid().ToString("N"); @@ -939,7 +942,7 @@ bool readOnly internal GraphNodeId? resizingNode; internal float resizeStartWidth; internal float resizePreviewWidth; - internal System.Numerics.Vector2 resizePointerStart; + internal Vector2 resizePointerStart; internal ulong portRevision = ulong.MaxValue; internal long assetRevision = long.MinValue; internal long typeRevision = long.MinValue; @@ -961,13 +964,13 @@ private sealed class RecoveryData : ISerializable /// Gets or sets the diagnostic source path. /// [SerializableProperty] - public string path { get; set; } = ""; + public string path { get; set; } = string.Empty; /// /// Gets or sets the expected disk source fingerprint. /// [SerializableProperty] - public string hash { get; set; } = ""; + public string hash { get; set; } = string.Empty; /// /// Gets or sets the complete neutral unsaved graph. diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs index 8cf8dad58..66dbd00c9 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs @@ -80,7 +80,7 @@ protected override void Draw( InspectionDrawContext context, AssetFileEntry target ) { - if (context.interactions.TryGetModule(out var documents)) + if (context.interactions.TryGetModule(out ShaderEditorDocuments? documents)) { if (documents!.TryOpen(target, out ShaderEditorDocuments.Draft draft)) { @@ -88,7 +88,7 @@ AssetFileEntry target } else { - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Waiting for Shader asset import…"); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); } } } @@ -117,7 +117,7 @@ internal sealed class ShaderSelectionDrawer(IInspectionIconProvider context.interactions.TryGetModule(out var documents) + ) => context.interactions.TryGetModule(out ShaderEditorDocuments? documents) && documents is not null && documents.assets.TryGetInfo(target.assetId, out AssetInfo? info) && info is not null @@ -142,7 +142,7 @@ protected override (string name, Action? setter) BindName( InspectionDrawContext context, ShaderInspectionSelection target ) { - if (context.interactions.TryGetModule(out var documents) + if (context.interactions.TryGetModule(out ShaderEditorDocuments? documents) && documents is not null && documents.assets.TryGetInfo(target.assetId, out AssetInfo? info) && info is not null @@ -165,7 +165,7 @@ protected override void DrawHeader( InspectionDrawContext context, ShaderInspectionSelection target ) { - if (!context.interactions.TryGetModule(out var documents) + if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) || documents is null || !documents.assets.TryGetInfo(target.assetId, out AssetInfo? info) || info is null @@ -207,7 +207,7 @@ protected override void Draw( InspectionDrawContext context, ShaderInspectionSelection target ) { - if (!context.interactions.TryGetModule(out var documents) || documents is null) + if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) || documents is null) { return; } @@ -225,7 +225,7 @@ ShaderInspectionSelection target } else { - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Waiting for Shader asset import…"); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); } } } @@ -253,7 +253,7 @@ internal sealed class ShaderAssetDrawer(IInspectionIconProvider protected override string GetIcon( InspectionDrawContext context, ShaderAsset target - ) => context.interactions.TryGetModule(out var documents) + ) => context.interactions.TryGetModule(out ShaderEditorDocuments? documents) && documents is not null && documents.assets.TryGetFileSystemEntry( target.assetPath, @@ -290,7 +290,7 @@ protected override void Draw( InspectionDrawContext context, ShaderAsset target ) { - if (!context.interactions.TryGetModule(out var documents) || documents is null) + if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) || documents is null) { return; } @@ -304,7 +304,7 @@ ShaderAsset target } else { - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Waiting for Shader asset import…"); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); } } } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs index ea636e9b5..7121257ad 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs @@ -3,12 +3,15 @@ using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Core.Graphs; using Inno.Core.Input; using Inno.Editor.Core; +using Inno.Editor.Graph; using Inno.Editor.Interactions; using Inno.Editor.Shaders; using Inno.Editor.Shaders.ImGui; +using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Shaders; @@ -33,7 +36,7 @@ public override void Build( EditorMenuContext context, EditorMenuBuilder builder ) { - if (context.target is not AssetFileEntry entry || !documents.TryGet(entry, out var draft)) + if (context.target is not AssetFileEntry entry || !documents.TryGet(entry, out ShaderEditorDocuments.Draft draft)) { return; } @@ -72,7 +75,9 @@ EditorMenuBuilder builder + category + "/" + (documents.drawers?.GetDisplayName(definition) - ?? EditorDisplayNames.Nicify(definition.Replace("inno.shader.", "", StringComparison.Ordinal).Replace('-', ' '))), + ?? EditorDisplayNames.Nicify( + definition.Replace("inno.shader.", string.Empty, StringComparison.Ordinal).Replace('-', ' ') + )), "shader/create-node", order, argument: new ShaderNodeCreation(definition) @@ -84,7 +89,7 @@ EditorMenuBuilder builder foreach (AssetFileEntry source in documents.assets.GetFileSystemEntries(includeDirectories: false)) { if (source.extension == ".ishadersource" - && documents.assets.TryGetInfo(source.assetPath, out var info) + && documents.assets.TryGetInfo(source.assetPath, out AssetInfo? info) && info is not null && documents.assets.TryLoad(info.persistentId, out ShaderFunctionAsset? library) && library is not null @@ -93,7 +98,7 @@ EditorMenuBuilder builder functionLibraries.Add((source, info, library)); } } - foreach (var catalog in functionLibraries + foreach ((string name, int order) catalog in functionLibraries .Select(static value => (path: NormalizeCatalog(value.library.catalogPath), value.library.catalogOrder)) .Where(static value => value.path.Length != 0) .GroupBy(static value => value.path.Split('/')[0], StringComparer.Ordinal) @@ -141,7 +146,7 @@ EditorMenuBuilder builder nodeInterface = documents.LoadGraphNodeInterface(info.persistentId); } catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + && RetirementPendingException.Find(failure) is null) { continue; } @@ -153,7 +158,7 @@ EditorMenuBuilder builder } string catalog = NormalizeCatalog(nodeInterface.createPath); string root = nodeInterface.kind == ShaderGraphNodeKind.DomainOutput ? "Domain Outputs" : "Graph Nodes"; - string group = "Create/" + root + (catalog.Length == 0 ? "" : "/" + catalog); + string group = "Create/" + root + (catalog.Length == 0 ? string.Empty : "/" + catalog); builder.AddGroup( group, order: nodeInterface.createOrder, @@ -227,9 +232,9 @@ internal sealed class CreateShaderOutput(ShaderEditorDocuments documents) : Edit /// protected override EditorActionState Query(EditorActionContext context) { - if (!documents.TryGet(context.target, out var draft) + if (!documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) || draft.readOnly - || !Enum.TryParse(context.argument, out Inno.Rendering.ShaderStage stage) + || !Enum.TryParse(context.argument, out ShaderStage stage) ) { return EditorActionState.disabled; } @@ -262,20 +267,20 @@ protected override EditorActionState Query(EditorActionContext protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); - var controller = documents.Controller(draft); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); GraphDocument graph = controller.document.Clone(); - Inno.Rendering.Assets.ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( graph, documents.serialization, documents.context ); - Inno.Rendering.ShaderStage stage = Enum.Parse(context.argument); - Inno.Rendering.ShaderProgramKind kind = stage == Inno.Rendering.ShaderStage.Compute - ? Inno.Rendering.ShaderProgramKind.Compute - : Inno.Rendering.ShaderProgramKind.Raster; + ShaderStage stage = Enum.Parse(context.argument); + ShaderProgramKind kind = stage == ShaderStage.Compute + ? ShaderProgramKind.Compute + : ShaderProgramKind.Raster; ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(graph, documents.serialization, documents.context); - ShaderGraphPassProgram? incomplete = kind == Inno.Rendering.ShaderProgramKind.Raster + ShaderGraphPassProgram? incomplete = kind == ShaderProgramKind.Raster ? programs.FirstOrDefault( program => ( definition.passes.Any(pass => pass.name == program.pass && pass.programKind == kind) @@ -323,7 +328,7 @@ protected override void Execute(EditorActionContext cont stages = []; } - GraphNodeId id = new(Guid.NewGuid().ToString("N")); + var id = new GraphNodeId(Guid.NewGuid().ToString("N")); var node = new GraphNodeRecord(id, ShaderGraphDocument.outputDefinitionId) { position = draft.menuPosition @@ -334,13 +339,13 @@ protected override void Execute(EditorActionContext cont new ShaderGraphStageSettings { stage = stage, - outputs = stage == Inno.Rendering.ShaderStage.Compute - ? [] - : [new() - { - id = stage == Inno.Rendering.ShaderStage.Vertex ? "position" : "color", - kind = stage == Inno.Rendering.ShaderStage.Vertex ? ShaderIrOutputKind.ClipPosition : ShaderIrOutputKind.Color - }] + outputs = stage == ShaderStage.Compute + ? [] + : [new() + { + id = stage == ShaderStage.Vertex ? "position" : "color", + kind = stage == ShaderStage.Vertex ? ShaderIrOutputKind.ClipPosition : ShaderIrOutputKind.Color + }] }, documents.serialization, documents.context @@ -374,7 +379,7 @@ internal sealed class CreateShaderNode(ShaderEditorDocuments documents) : Editor /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) - => documents.TryGet(context.target, out var draft) + => documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) && documents.CanCreate(draft, context.argument) ? EditorActionState.enabled : EditorActionState.disabled; /// @@ -414,7 +419,7 @@ internal abstract class ShaderSelectionAction(ShaderEditorDocuments documents) : /// The validated editor action state that represents the completed operation. /// protected override EditorActionState Query(EditorActionContext context) - => documents.TryGet(context.target, out var draft) + => documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) && (!writes || !draft.readOnly) && (!needsSelection @@ -438,7 +443,7 @@ internal sealed class CopyShaderNodes(ShaderEditorDocuments documents) : ShaderS /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); documents.clipboard = documents.Copy(draft); } } @@ -461,9 +466,9 @@ internal sealed class DeleteShaderNodes(ShaderEditorDocuments documents) : Shade /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); - var controller = documents.Controller(draft); - using var transaction = context.history.BeginTransaction("Delete Shader Selection"); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + using EditorHistoryTransaction transaction = context.history.BeginTransaction("Delete Shader Selection"); if (draft.selectedEdge is GraphEdgeId edge) { controller.Disconnect(edge); @@ -488,7 +493,7 @@ internal sealed class CutShaderNodes(ShaderEditorDocuments documents) : ShaderSe /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); documents.clipboard = documents.Copy(draft); documents.RemoveNodes(draft); draft.canvas.ClearSelection(); @@ -517,7 +522,7 @@ internal sealed class PasteShaderNodes(ShaderEditorDocuments documents) : Shader protected override EditorActionState Query(EditorActionContext context) => base.Query(context).isEnabled && documents.clipboard is not null - && documents.TryGet(context.target, out var draft) + && documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) && documents.CanPaste(draft, documents.clipboard) ? EditorActionState.enabled : EditorActionState.disabled; /// @@ -528,7 +533,7 @@ protected override EditorActionState Query(EditorActionContext c /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); if (documents.clipboard is not null) { documents.Paste(draft, documents.clipboard); @@ -551,7 +556,7 @@ internal sealed class DuplicateShaderNodes(ShaderEditorDocuments documents) : Sh /// protected override EditorActionState Query(EditorActionContext context) { - if (!base.Query(context).isEnabled || !documents.TryGet(context.target, out var draft)) + if (!base.Query(context).isEnabled || !documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft)) { return EditorActionState.disabled; } @@ -570,7 +575,7 @@ protected override EditorActionState Query(EditorActionContext c /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); documents.Paste(draft, documents.Copy(draft)); } } @@ -586,9 +591,9 @@ internal sealed class DisconnectShaderNodes(ShaderEditorDocuments documents) : S /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); - var controller = documents.Controller(draft); - using var transaction = context.history.BeginTransaction("Disconnect Nodes"); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + using EditorHistoryTransaction transaction = context.history.BeginTransaction("Disconnect Nodes"); foreach (GraphEdgeRecord edge in controller.document.edges .Where( edge => draft.canvas.selectedNodes.Contains(edge.input.nodeId) || draft.canvas.selectedNodes.Contains(edge.output.nodeId) @@ -637,8 +642,8 @@ internal sealed class FormatShaderGraph(ShaderEditorDocuments documents) : Shade /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); - var controller = documents.Controller(draft); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); controller.ReplaceDocument( ShaderGraphAutoLayout.Apply(controller.document, documents.serialization, documents.context, documents.Describe), "Format Shader Graph" diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs index 22bfd7b9e..7859dd6f4 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs @@ -84,8 +84,8 @@ protected override EditorActionState Query(EditorActionContext c /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); - var controller = documents.Controller(draft); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); GraphDocument graph = controller.document.Clone(); GraphEdgeRecord edge = graph.edges.Single(value => value.id == draft.selectedEdge); ShaderNodePort source = draft.ports[edge.output.nodeId].Single(value => value.id == edge.output.portId.value); @@ -100,7 +100,7 @@ protected override void Execute(EditorActionContext context) string stage = ShaderGraphDocument.Read( graph.FindNode(edge.output.nodeId)!, "stage", - "", + string.Empty, documents.serialization, documents.context ); @@ -137,7 +137,7 @@ out GraphSerializedValue? value /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); GraphDocument graph = documents.Controller(draft).document.Clone(); ShaderCanvasGroup[] groups = Read(documents, graph); groups = @@ -168,9 +168,9 @@ internal sealed class UngroupShaderNodes(ShaderEditorDocuments documents) : Shad /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); GraphDocument graph = documents.Controller(draft).document.Clone(); - var groups = GroupShaderNodes + ShaderCanvasGroup[] groups = GroupShaderNodes .Read(documents, graph) .Where( group => ( @@ -182,7 +182,7 @@ protected override void Execute(EditorActionContext context) .ToArray(); graph.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); documents.Controller(draft).ReplaceDocument(graph, "Ungroup Shader Nodes"); - draft.selectedGroupId = ""; + draft.selectedGroupId = string.Empty; documents.Changed(draft); } } @@ -223,7 +223,15 @@ or ShaderGraphNodes.outputDefinitionId return EditorActionState.disabled; } string[] stages = selected - .Select(node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", documents.serialization, documents.context)) + .Select( + node => ShaderGraphDocument.Read( + node, + ShaderGraphDocument.stageKey, + string.Empty, + documents.serialization, + documents.context + ) + ) .Distinct(StringComparer.Ordinal) .ToArray(); if (stages.Length != 1 || stages[0].Length == 0) @@ -250,7 +258,15 @@ protected override void Execute(EditorActionContext context) HashSet selected = [..draft.canvas.selectedNodes]; GraphNodeRecord[] nodes = parent.nodes.Where(node => selected.Contains(node.id)).ToArray(); string stage = nodes - .Select(node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", documents.serialization, documents.context)) + .Select( + node => ShaderGraphDocument.Read( + node, + ShaderGraphDocument.stageKey, + string.Empty, + documents.serialization, + documents.context + ) + ) .Distinct(StringComparer.Ordinal) .Single(); GraphEdgeRecord[] incomingEdges = parent.edges @@ -259,8 +275,8 @@ protected override void Execute(EditorActionContext context) GraphEdgeRecord[] outgoingEdges = parent.edges .Where(edge => selected.Contains(edge.output.nodeId) && !selected.Contains(edge.input.nodeId)) .ToArray(); - var inputGroups = incomingEdges.GroupBy(static edge => edge.output).ToArray(); - var outputGroups = outgoingEdges.GroupBy(static edge => edge.output).ToArray(); + IGrouping[] inputGroups = incomingEdges.GroupBy(static edge => edge.output).ToArray(); + IGrouping[] outputGroups = outgoingEdges.GroupBy(static edge => edge.output).ToArray(); var inputNames = new HashSet(StringComparer.Ordinal); var outputNames = new HashSet(StringComparer.Ordinal); ShaderGraphNodePortDefinition[] inputs = inputGroups @@ -294,7 +310,7 @@ protected override void Execute(EditorActionContext context) ).id ) .ToHashSet(StringComparer.Ordinal); - ShaderDefinition childDefinition = new( + var childDefinition = new ShaderDefinition( "Graph Node", parentDefinition.properties.Where(property => ownedBindings.Contains(property.id.value)), [], @@ -434,7 +450,7 @@ protected override void Execute(EditorActionContext context) controller.ReplaceDocument(candidate, "Collapse Shader Subgraph"); transaction.Commit(); draft.canvas.SelectNodes([call.id]); - draft.selectedGroupId = ""; + draft.selectedGroupId = string.Empty; documents.Changed(draft); } @@ -481,15 +497,15 @@ private static AssetPath UniquePath( ShaderEditorDocuments documents ) { AssetSourceMount mount = documents.assets.sourceMounts.Single(value => value.id == source.source); - string directory = Path.GetDirectoryName(source.localPath)?.Replace('\\', '/') ?? ""; + string directory = Path.GetDirectoryName(source.localPath)?.Replace('\\', '/') ?? string.Empty; string safeName = string.Concat(name.Select(character => Path.GetInvalidFileNameChars().Contains(character) ? '_' : character)) .Trim(); if (safeName.Length == 0) { safeName = "Shader Node"; } - string prefix = directory.Length == 0 ? "" : directory + "/"; - AssetPath path = new(source.source, prefix + safeName + ".ishader"); + string prefix = directory.Length == 0 ? string.Empty : directory + "/"; + var path = new AssetPath(source.source, prefix + safeName + ".ishader"); for (int suffix = 2; File.Exists(mount.Resolve(path.localPath)) || File.Exists(mount.Resolve(path.localPath) + ".imeta"); suffix++) { path = new(source.source, prefix + safeName + " " + suffix + ".ishader"); @@ -524,7 +540,7 @@ protected override EditorActionState Query(EditorActionContext c { return EditorActionState.disabled; } - var draft = documents.Open(context.target); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); string? definition = draft.canvas.selectedNodes.Count == 1 ? documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())?.definitionId : null; @@ -541,7 +557,7 @@ protected override EditorActionState Query(EditorActionContext c /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); GraphNodeRecord node = documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())!; Reveal(documents, browser, ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, documents.serialization, documents.context)); } @@ -593,7 +609,7 @@ AssetBrowserModule browser /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); string parent = Path.GetDirectoryName(draft.path.localPath)?.Replace('\\', '/') ?? string.Empty; browser.browser.SetCurrentDirectory(new AssetPath(draft.path.source, parent).ToString()); if (!documents.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry entry)) @@ -651,7 +667,7 @@ AssetBrowserModule browser /// protected override void Execute(EditorActionContext context) { - var draft = documents.Open(context.target); + ShaderEditorDocuments.Draft draft = documents.Open(context.target); AssetSourceMount mount = documents.assets.sourceMounts.Single(value => value.id == AssetSourceId.project); string name = Path.GetFileNameWithoutExtension(draft.path.localPath) + " Copy"; AssetPath destination = AssetPath.Project(name + ".ishader"); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs index e334487a2..eff30c63a 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderGraphAutoLayout.cs @@ -48,7 +48,13 @@ Func> describePorts GraphNodeRecord[] members = output.definitionId == ShaderGraphDocument.outputDefinitionId ? graph.nodes.Where(node => ( node.id == output.id - || ShaderGraphDocument.Read(node, "stage", "", serialization, context) == output.id.value + || ShaderGraphDocument.Read( + node, + "stage", + string.Empty, + serialization, + context + ) == output.id.value )).ToArray() : graph.nodes.Where(node => !placed.Contains(node.id)).ToArray(); LayoutLane(output, members, ref laneY); @@ -69,7 +75,7 @@ void LayoutLane( GraphNodeRecord[] members, ref float y ) { - var memberIds = members.Select(static node => node.id).ToHashSet(); + HashSet memberIds = members.Select(static node => node.id).ToHashSet(); var distance = new Dictionary { [output.id] = 0 }; var queue = new Queue(); queue.Enqueue(output.id); @@ -137,7 +143,7 @@ bool towardOutput { return; } - var oldOrder = nodes.Select(static ( + Dictionary oldOrder = nodes.Select(static ( node, index ) => (node.id, index)).ToDictionary(); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs index a0d6830b2..01c5e1ea5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Presentation/ShaderCheckModal.cs @@ -11,13 +11,13 @@ internal sealed class ShaderCheckModal(ShaderEditorDocuments documents) : Editor private DialogPresentation m_content; private DialogLayout m_layout; - /// + /// public override bool isVisible => documents.TryGetCheckDraft(out _); - /// + /// public override bool allowScrolling => false; - /// + /// protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize @@ -27,6 +27,6 @@ Vector2 availableContentSize return m_layout.size; } - /// + /// protected override void OnDraw(EditorContext context) => EditorUiSession.current.widgets.DrawDialog(m_content, m_layout); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs index f45471b51..cdd4e16d8 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs @@ -1,7 +1,9 @@ using System; +using System.IO; using System.Numerics; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Execution; using Inno.Editor.Core; using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; @@ -66,8 +68,8 @@ protected override void OnDraw(EditorContext context) { new ShaderEditorCanvas(documents, documents.Open(entry)).Draw(); } - catch (Exception failure) when ((failure is System.IO.IOException or InvalidOperationException or FormatException) - && Inno.Core.Execution.RetirementPendingException.Find(failure) is null) + catch (Exception failure) when ((failure is IOException or InvalidOperationException or FormatException) + && RetirementPendingException.Find(failure) is null) { EditorUI.current.widgets.WrappedText(failure.Message); } diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs index eb782d298..1569547e4 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Stats/StatsPanel.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; @@ -75,7 +76,7 @@ protected override void OnDraw(EditorContext context) } } - /// + /// protected override void OnDetach(EditorContext context) { m_statistics.Reset(); @@ -89,20 +90,20 @@ private static void DrawGroup( ReadOnlySpan<(string label, string value)> values ) { EditorUI.current.widgets.CollectionSectionHeader(title); - System.Numerics.Vector2 padding = EditorUI.current.widgets.style.sectionPadding; + Vector2 padding = EditorUI.current.widgets.style.sectionPadding; ImGuiTableFlags flags = ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.RowBg | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.PadOuterX; Ui.PushStyleVar( (ImGuiStyleVar.CellPadding), - new System.Numerics.Vector2(padding.X, C_ROW_PADDING * EditorUI.current.widgets.style.zoom) + new Vector2(padding.X, C_ROW_PADDING * EditorUI.current.widgets.style.zoom) ); Ui.PushStyleColor((ImGuiCol.TableRowBg), EditorPalette.collectionRow); Ui.PushStyleColor((ImGuiCol.TableRowBgAlt), EditorPalette.collectionRowAlternate); try { - if (!Ui.BeginTable($"##stats_{title}", 2, flags, default(System.Numerics.Vector2), 0f)) + if (!Ui.BeginTable($"##stats_{title}", 2, flags, default, 0f)) { return; } @@ -114,7 +115,7 @@ private static void DrawGroup( { Ui.TableNextRow(); Ui.TableSetColumnIndex(0); - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, label); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, label); Ui.TableSetColumnIndex(1); EditorUI.current.widgets.WrappedText(value); } diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs index c02c7eb58..10ba12da3 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Inspection/AssetSelectionInspectionDrawer.cs @@ -117,7 +117,5 @@ AssetFileEntry entry private static void DrawMetadata( string label, string value - ) { - EditorUI.current.widgets.PropertyRow("asset.metadata." + label, label, () => EditorUI.current.widgets.Hint(value)); - } + ) => EditorUI.current.widgets.PropertyRow("asset.metadata." + label, label, () => EditorUI.current.widgets.Hint(value)); } diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs index 0eb3e0ed0..cdd14b6bf 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserModule.cs @@ -8,6 +8,7 @@ using Inno.Editor.Interactions; using Inno.Editor.Settings; using Inno.Extensibility.Types; +using Inno.Scripting.Api; namespace Inno.Editor.Assets.ImGui; @@ -38,7 +39,7 @@ public sealed class AssetBrowserModule : EditorModule, IInspectionIconProvider /// A required owner is null. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public AssetBrowserModule( AssetEditingModule edits, EditorInteractions interactions, @@ -48,7 +49,7 @@ TypeCatalog types this.edits = edits ?? throw new ArgumentNullException(nameof(edits)); m_settings = settings ?? throw new ArgumentNullException(nameof(settings)); m_icons = new AssetIconRegistry(settings, types); - browser = new AssetBrowserState(interactions, edits.pipeline); + this.browser = new AssetBrowserState(interactions, edits.pipeline); } /// @@ -64,7 +65,7 @@ TypeCatalog types /// /// Gets the configured folder glyph used by asset navigation. /// - public string folderIcon => m_settings.Get("Editor/Appearance/Icons/Folder").GetAsString("value", Inno.Editor.ImGui.ImGuiIcon.Folder)!; + public string folderIcon => m_settings.Get("Editor/Appearance/Icons/Folder").GetAsString("value", ImGuiIcon.Folder)!; /// /// Captures an immutable snapshot of the current observable state. @@ -151,7 +152,7 @@ public string GetIcon(AssetFileEntry entry) return icon; } - return m_settings.Get("Editor/Appearance/Icons/File").GetAsString("value", Inno.Editor.ImGui.ImGuiIcon.File)!; + return m_settings.Get("Editor/Appearance/Icons/File").GetAsString("value", ImGuiIcon.File)!; } /// diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs index 308241d10..11bf05a0f 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs @@ -84,7 +84,7 @@ AssetPipeline assets public string? GetSelectedPath(EditorContext context) { ArgumentNullException.ThrowIfNull(context); - return (m_interactions.selection.selectedTarget as Inno.Assets.Pipeline.AssetFileEntry)?.assetPath.ToString(); + return (m_interactions.selection.selectedTarget as AssetFileEntry)?.assetPath.ToString(); } /// @@ -116,9 +116,7 @@ AssetFileEntry entry public void ToggleSelection( EditorContext context, AssetFileEntry entry - ) { - m_interactions.ToggleSelection(entry); - } + ) => m_interactions.ToggleSelection(entry); /// /// Switches the displayed root while preserving the last directory visited in each root. @@ -169,10 +167,8 @@ public void Select( object? target = null; if (!string.IsNullOrWhiteSpace(relativePath)) { - if (m_assets.TryGetFileSystemEntry( - Inno.Assets.AssetPath.Parse(Normalize(relativePath)), - out Inno.Assets.Pipeline.AssetFileEntry entry - )) { + if (m_assets.TryGetFileSystemEntry(AssetPath.Parse(Normalize(relativePath)), out AssetFileEntry entry)) + { target = entry; } } diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs index 9e9fe5b5d..9d2e4cfbd 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasPointerController.cs @@ -98,7 +98,7 @@ Vector2 pointer } } Cancel(); - foreach (var entry in starts) + foreach (KeyValuePair entry in starts) { m_starts.Add(entry.Key, entry.Value); } diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs index 93b26d028..95a0370e7 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.Nodes.cs @@ -54,7 +54,7 @@ Vector2 point for (int index = layout.nodes.Count - 1; index >= 0; index--) { GraphCanvasNode node = layout.nodes[index]; - var bounds = NodeBounds(node); + (Vector2 minimum, Vector2 maximum) bounds = NodeBounds(node); if (Contains(bounds, point)) { return node; @@ -148,7 +148,7 @@ Vector2 second var nodes = new List(); foreach (GraphCanvasNode node in layout.nodes) { - var bounds = NodeBounds(node); + (Vector2 minimum, Vector2 maximum) bounds = NodeBounds(node); if (bounds.maximum.X >= minimum.X && bounds.minimum.X <= maximum.X && bounds.maximum.Y >= minimum.Y && bounds.minimum.Y <= maximum.Y ) { @@ -196,7 +196,7 @@ public bool DrawNode( Action? drawContent = null, GraphPosition? previewPosition = null ) { - var bounds = NodeBounds(node, previewPosition); + (Vector2 minimum, Vector2 maximum) bounds = NodeBounds(node, previewPosition); Vector2 minimum = bounds.minimum; Vector2 maximum = bounds.maximum; if (m_size.X == 0f || m_size.Y == 0f || maximum.X < m_origin.X || minimum.X > m_origin.X + m_size.X @@ -204,7 +204,7 @@ public bool DrawNode( ) { return false; } - var clip = CanvasDrawing.GetClipBounds(); + (Vector2 minimum, Vector2 maximum) clip = CanvasDrawing.GetClipBounds(); if (maximum.X < clip.minimum.X || minimum.X > clip.maximum.X || maximum.Y < clip.minimum.Y || minimum.Y > clip.maximum.Y) { return false; @@ -237,7 +237,7 @@ public bool DrawNode( foreach (GraphCanvasPort port in node.ports) { Vector2 point = minimum + port.position * zoom; - uint color = port.isMissing ? Pack(0.95f, 0.35f, 0.3f) : Pack(0.60f, 0.48f, 0.84f); + uint color = port.isMissing ? Pack(0.95f, 0.35f, 0.3f) : Pack(0.6f, 0.48f, 0.84f); draw.FilledCircle(point, 5f * zoom, color); if (port.isOptional && !port.isMissing) { @@ -250,7 +250,7 @@ public bool DrawNode( Vector2 labelMinimum = minimum + labelBounds.minimum * zoom; Vector2 labelMaximum = minimum + labelBounds.maximum * zoom; float padding = 12f * zoom; - var label = FitLabel(port.label, labelMaximum.X - labelMinimum.X - padding * 2f, zoom); + (string text, float width) label = FitLabel(port.label, labelMaximum.X - labelMinimum.X - padding * 2f, zoom); float textX = port.direction == GraphPortDirection.Input ? labelMinimum.X + padding : labelMaximum.X - padding - label.width; diff --git a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs index 33503b49d..108719bee 100644 --- a/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs +++ b/src/composition/editor/presentation/Inno.Editor.Graph.ImGui/Canvas/GraphCanvasView.cs @@ -170,7 +170,7 @@ public void DrawConnection( { throw new ArgumentOutOfRangeException(nameof(input), "Connection controls exceed finite screen coordinates."); } - var clip = CanvasDrawing.GetClipBounds(); + (Vector2 minimum, Vector2 maximum) clip = CanvasDrawing.GetClipBounds(); Vector2 minimum = Vector2.Min(Vector2.Min(output, input), Vector2.Min(first, second)) - new Vector2(thickness); Vector2 maximum = Vector2.Max(Vector2.Max(output, input), Vector2.Max(first, second)) + new Vector2(thickness); if (maximum.X < MathF.Max(m_origin.X, clip.minimum.X) || minimum.X > MathF.Min(m_origin.X + m_size.X, clip.maximum.X) diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs index 2dcb9f1ec..29590961c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/ImGui.Input.cs @@ -1,6 +1,7 @@ using System.Numerics; using Inno.Native.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; using RawImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; @@ -84,7 +85,7 @@ public static bool IsMouseDoubleClicked(ImGuiMouseButton button) public static bool IsKeyDown(ImGuiKey key) { EditorUiSession.current.EnsureDrawing(); - return RawImGui.IsKeyDown((Inno.Native.ImGui.ImGuiKey)key); + return RawImGui.IsKeyDown((NativeKey)key); } /// @@ -104,7 +105,7 @@ public static bool IsKeyPressed( bool repeat = true ) { EditorUiSession.current.EnsureDrawing(); - return RawImGui.IsKeyPressed((Inno.Native.ImGui.ImGuiKey)key, repeat); + return RawImGui.IsKeyPressed((NativeKey)key, repeat); } /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs index 67c32ca27..6002101a7 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiButtonFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeButtonFlags = Inno.Native.ImGui.ImGuiButtonFlags; + namespace Inno.Editor.ImGui; /// @@ -11,25 +13,25 @@ public enum ImGuiButtonFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiButtonFlags.None, + None = (int)NativeButtonFlags.None, /// /// React on left mouse button (default) /// - MouseButtonLeft = (int)Inno.Native.ImGui.ImGuiButtonFlags.MouseButtonLeft, + MouseButtonLeft = (int)NativeButtonFlags.MouseButtonLeft, /// /// React on right mouse button /// - MouseButtonRight = (int)Inno.Native.ImGui.ImGuiButtonFlags.MouseButtonRight, + MouseButtonRight = (int)NativeButtonFlags.MouseButtonRight, /// /// React on center mouse button /// - MouseButtonMiddle = (int)Inno.Native.ImGui.ImGuiButtonFlags.MouseButtonMiddle, + MouseButtonMiddle = (int)NativeButtonFlags.MouseButtonMiddle, /// /// Selects the mouse button mask presentation behavior. /// - MouseButtonMask = (int)Inno.Native.ImGui.ImGuiButtonFlags.MouseButtonMask, + MouseButtonMask = (int)NativeButtonFlags.MouseButtonMask, /// /// InvisibleButton(): do not disable navigation/tabbing. Otherwise disabled by default. /// - EnableNav = (int)Inno.Native.ImGui.ImGuiButtonFlags.EnableNav + EnableNav = (int)NativeButtonFlags.EnableNav } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs index 072b8a9c5..0b04dc914 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiChildFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeChildFlags = Inno.Native.ImGui.ImGuiChildFlags; + namespace Inno.Editor.ImGui; /// @@ -11,41 +13,41 @@ public enum ImGuiChildFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiChildFlags.None, + None = (int)NativeChildFlags.None, /// /// Show an outer border and enable WindowPadding. (IMPORTANT: this is always == 1 == true for legacy reason) /// - Borders = (int)Inno.Native.ImGui.ImGuiChildFlags.Borders, + Borders = (int)NativeChildFlags.Borders, /// /// Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) /// - AlwaysUseWindowPadding = (int)Inno.Native.ImGui.ImGuiChildFlags.AlwaysUseWindowPadding, + AlwaysUseWindowPadding = (int)NativeChildFlags.AlwaysUseWindowPadding, /// /// Allow resize from right border (layout direction). Enable .ini saving (unless ImGuiWindowFlags_NoSavedSettings passed to window flags) /// - ResizeX = (int)Inno.Native.ImGui.ImGuiChildFlags.ResizeX, + ResizeX = (int)NativeChildFlags.ResizeX, /// /// Allow resize from bottom border (layout direction). " /// - ResizeY = (int)Inno.Native.ImGui.ImGuiChildFlags.ResizeY, + ResizeY = (int)NativeChildFlags.ResizeY, /// /// Enable auto-resizing width. Read "IMPORTANT: Size measurement" details above. /// - AutoResizeX = (int)Inno.Native.ImGui.ImGuiChildFlags.AutoResizeX, + AutoResizeX = (int)NativeChildFlags.AutoResizeX, /// /// Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above. /// - AutoResizeY = (int)Inno.Native.ImGui.ImGuiChildFlags.AutoResizeY, + AutoResizeY = (int)NativeChildFlags.AutoResizeY, /// /// Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. /// - AlwaysAutoResize = (int)Inno.Native.ImGui.ImGuiChildFlags.AlwaysAutoResize, + AlwaysAutoResize = (int)NativeChildFlags.AlwaysAutoResize, /// /// Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. /// - FrameStyle = (int)Inno.Native.ImGui.ImGuiChildFlags.FrameStyle, + FrameStyle = (int)NativeChildFlags.FrameStyle, /// /// Share focus scope, allow keyboard/gamepad navigation to cross over parent border to this child or between sibling child windows. /// - NavFlattened = (int)Inno.Native.ImGui.ImGuiChildFlags.NavFlattened + NavFlattened = (int)NativeChildFlags.NavFlattened } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs index 2fb8941b2..ead46190b 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCol.cs @@ -1,5 +1,7 @@ using System; +using NativeCol = Inno.Native.ImGui.ImGuiCol; + namespace Inno.Editor.ImGui; /// @@ -10,253 +12,253 @@ public enum ImGuiCol : int /// /// Selects the text presentation behavior. /// - Text = (int)Inno.Native.ImGui.ImGuiCol.Text, + Text = (int)NativeCol.Text, /// /// Selects the text disabled presentation behavior. /// - TextDisabled = (int)Inno.Native.ImGui.ImGuiCol.TextDisabled, + TextDisabled = (int)NativeCol.TextDisabled, /// /// Selects the window bg presentation behavior. /// - WindowBg = (int)Inno.Native.ImGui.ImGuiCol.WindowBg, + WindowBg = (int)NativeCol.WindowBg, /// /// Selects the child bg presentation behavior. /// - ChildBg = (int)Inno.Native.ImGui.ImGuiCol.ChildBg, + ChildBg = (int)NativeCol.ChildBg, /// /// Selects the popup bg presentation behavior. /// - PopupBg = (int)Inno.Native.ImGui.ImGuiCol.PopupBg, + PopupBg = (int)NativeCol.PopupBg, /// /// Selects the border presentation behavior. /// - Border = (int)Inno.Native.ImGui.ImGuiCol.Border, + Border = (int)NativeCol.Border, /// /// Selects the border shadow presentation behavior. /// - BorderShadow = (int)Inno.Native.ImGui.ImGuiCol.BorderShadow, + BorderShadow = (int)NativeCol.BorderShadow, /// /// Selects the frame bg presentation behavior. /// - FrameBg = (int)Inno.Native.ImGui.ImGuiCol.FrameBg, + FrameBg = (int)NativeCol.FrameBg, /// /// Selects the frame bg hovered presentation behavior. /// - FrameBgHovered = (int)Inno.Native.ImGui.ImGuiCol.FrameBgHovered, + FrameBgHovered = (int)NativeCol.FrameBgHovered, /// /// Selects the frame bg active presentation behavior. /// - FrameBgActive = (int)Inno.Native.ImGui.ImGuiCol.FrameBgActive, + FrameBgActive = (int)NativeCol.FrameBgActive, /// /// Selects the title bg presentation behavior. /// - TitleBg = (int)Inno.Native.ImGui.ImGuiCol.TitleBg, + TitleBg = (int)NativeCol.TitleBg, /// /// Selects the title bg active presentation behavior. /// - TitleBgActive = (int)Inno.Native.ImGui.ImGuiCol.TitleBgActive, + TitleBgActive = (int)NativeCol.TitleBgActive, /// /// Selects the title bg collapsed presentation behavior. /// - TitleBgCollapsed = (int)Inno.Native.ImGui.ImGuiCol.TitleBgCollapsed, + TitleBgCollapsed = (int)NativeCol.TitleBgCollapsed, /// /// Selects the menu bar bg presentation behavior. /// - MenuBarBg = (int)Inno.Native.ImGui.ImGuiCol.MenuBarBg, + MenuBarBg = (int)NativeCol.MenuBarBg, /// /// Selects the scrollbar bg presentation behavior. /// - ScrollbarBg = (int)Inno.Native.ImGui.ImGuiCol.ScrollbarBg, + ScrollbarBg = (int)NativeCol.ScrollbarBg, /// /// Selects the scrollbar grab presentation behavior. /// - ScrollbarGrab = (int)Inno.Native.ImGui.ImGuiCol.ScrollbarGrab, + ScrollbarGrab = (int)NativeCol.ScrollbarGrab, /// /// Selects the scrollbar grab hovered presentation behavior. /// - ScrollbarGrabHovered = (int)Inno.Native.ImGui.ImGuiCol.ScrollbarGrabHovered, + ScrollbarGrabHovered = (int)NativeCol.ScrollbarGrabHovered, /// /// Selects the scrollbar grab active presentation behavior. /// - ScrollbarGrabActive = (int)Inno.Native.ImGui.ImGuiCol.ScrollbarGrabActive, + ScrollbarGrabActive = (int)NativeCol.ScrollbarGrabActive, /// /// Selects the check mark presentation behavior. /// - CheckMark = (int)Inno.Native.ImGui.ImGuiCol.CheckMark, + CheckMark = (int)NativeCol.CheckMark, /// /// Selects the slider grab presentation behavior. /// - SliderGrab = (int)Inno.Native.ImGui.ImGuiCol.SliderGrab, + SliderGrab = (int)NativeCol.SliderGrab, /// /// Selects the slider grab active presentation behavior. /// - SliderGrabActive = (int)Inno.Native.ImGui.ImGuiCol.SliderGrabActive, + SliderGrabActive = (int)NativeCol.SliderGrabActive, /// /// Selects the button presentation behavior. /// - Button = (int)Inno.Native.ImGui.ImGuiCol.Button, + Button = (int)NativeCol.Button, /// /// Selects the button hovered presentation behavior. /// - ButtonHovered = (int)Inno.Native.ImGui.ImGuiCol.ButtonHovered, + ButtonHovered = (int)NativeCol.ButtonHovered, /// /// Selects the button active presentation behavior. /// - ButtonActive = (int)Inno.Native.ImGui.ImGuiCol.ButtonActive, + ButtonActive = (int)NativeCol.ButtonActive, /// /// Selects the header presentation behavior. /// - Header = (int)Inno.Native.ImGui.ImGuiCol.Header, + Header = (int)NativeCol.Header, /// /// Selects the header hovered presentation behavior. /// - HeaderHovered = (int)Inno.Native.ImGui.ImGuiCol.HeaderHovered, + HeaderHovered = (int)NativeCol.HeaderHovered, /// /// Selects the header active presentation behavior. /// - HeaderActive = (int)Inno.Native.ImGui.ImGuiCol.HeaderActive, + HeaderActive = (int)NativeCol.HeaderActive, /// /// Selects the separator presentation behavior. /// - Separator = (int)Inno.Native.ImGui.ImGuiCol.Separator, + Separator = (int)NativeCol.Separator, /// /// Selects the separator hovered presentation behavior. /// - SeparatorHovered = (int)Inno.Native.ImGui.ImGuiCol.SeparatorHovered, + SeparatorHovered = (int)NativeCol.SeparatorHovered, /// /// Selects the separator active presentation behavior. /// - SeparatorActive = (int)Inno.Native.ImGui.ImGuiCol.SeparatorActive, + SeparatorActive = (int)NativeCol.SeparatorActive, /// /// Selects the resize grip presentation behavior. /// - ResizeGrip = (int)Inno.Native.ImGui.ImGuiCol.ResizeGrip, + ResizeGrip = (int)NativeCol.ResizeGrip, /// /// Selects the resize grip hovered presentation behavior. /// - ResizeGripHovered = (int)Inno.Native.ImGui.ImGuiCol.ResizeGripHovered, + ResizeGripHovered = (int)NativeCol.ResizeGripHovered, /// /// Selects the resize grip active presentation behavior. /// - ResizeGripActive = (int)Inno.Native.ImGui.ImGuiCol.ResizeGripActive, + ResizeGripActive = (int)NativeCol.ResizeGripActive, /// /// Selects the input text cursor presentation behavior. /// - InputTextCursor = (int)Inno.Native.ImGui.ImGuiCol.InputTextCursor, + InputTextCursor = (int)NativeCol.InputTextCursor, /// /// Selects the tab hovered presentation behavior. /// - TabHovered = (int)Inno.Native.ImGui.ImGuiCol.TabHovered, + TabHovered = (int)NativeCol.TabHovered, /// /// Selects the tab presentation behavior. /// - Tab = (int)Inno.Native.ImGui.ImGuiCol.Tab, + Tab = (int)NativeCol.Tab, /// /// Selects the tab selected presentation behavior. /// - TabSelected = (int)Inno.Native.ImGui.ImGuiCol.TabSelected, + TabSelected = (int)NativeCol.TabSelected, /// /// Selects the tab selected overline presentation behavior. /// - TabSelectedOverline = (int)Inno.Native.ImGui.ImGuiCol.TabSelectedOverline, + TabSelectedOverline = (int)NativeCol.TabSelectedOverline, /// /// Selects the tab dimmed presentation behavior. /// - TabDimmed = (int)Inno.Native.ImGui.ImGuiCol.TabDimmed, + TabDimmed = (int)NativeCol.TabDimmed, /// /// Selects the tab dimmed selected presentation behavior. /// - TabDimmedSelected = (int)Inno.Native.ImGui.ImGuiCol.TabDimmedSelected, + TabDimmedSelected = (int)NativeCol.TabDimmedSelected, /// /// Selects the tab dimmed selected overline presentation behavior. /// - TabDimmedSelectedOverline = (int)Inno.Native.ImGui.ImGuiCol.TabDimmedSelectedOverline, + TabDimmedSelectedOverline = (int)NativeCol.TabDimmedSelectedOverline, /// /// Selects the docking preview presentation behavior. /// - DockingPreview = (int)Inno.Native.ImGui.ImGuiCol.DockingPreview, + DockingPreview = (int)NativeCol.DockingPreview, /// /// Selects the docking empty bg presentation behavior. /// - DockingEmptyBg = (int)Inno.Native.ImGui.ImGuiCol.DockingEmptyBg, + DockingEmptyBg = (int)NativeCol.DockingEmptyBg, /// /// Selects the plot lines presentation behavior. /// - PlotLines = (int)Inno.Native.ImGui.ImGuiCol.PlotLines, + PlotLines = (int)NativeCol.PlotLines, /// /// Selects the plot lines hovered presentation behavior. /// - PlotLinesHovered = (int)Inno.Native.ImGui.ImGuiCol.PlotLinesHovered, + PlotLinesHovered = (int)NativeCol.PlotLinesHovered, /// /// Selects the plot histogram presentation behavior. /// - PlotHistogram = (int)Inno.Native.ImGui.ImGuiCol.PlotHistogram, + PlotHistogram = (int)NativeCol.PlotHistogram, /// /// Selects the plot histogram hovered presentation behavior. /// - PlotHistogramHovered = (int)Inno.Native.ImGui.ImGuiCol.PlotHistogramHovered, + PlotHistogramHovered = (int)NativeCol.PlotHistogramHovered, /// /// Selects the table header bg presentation behavior. /// - TableHeaderBg = (int)Inno.Native.ImGui.ImGuiCol.TableHeaderBg, + TableHeaderBg = (int)NativeCol.TableHeaderBg, /// /// Selects the table border strong presentation behavior. /// - TableBorderStrong = (int)Inno.Native.ImGui.ImGuiCol.TableBorderStrong, + TableBorderStrong = (int)NativeCol.TableBorderStrong, /// /// Selects the table border light presentation behavior. /// - TableBorderLight = (int)Inno.Native.ImGui.ImGuiCol.TableBorderLight, + TableBorderLight = (int)NativeCol.TableBorderLight, /// /// Selects the table row bg presentation behavior. /// - TableRowBg = (int)Inno.Native.ImGui.ImGuiCol.TableRowBg, + TableRowBg = (int)NativeCol.TableRowBg, /// /// Selects the table row bg alt presentation behavior. /// - TableRowBgAlt = (int)Inno.Native.ImGui.ImGuiCol.TableRowBgAlt, + TableRowBgAlt = (int)NativeCol.TableRowBgAlt, /// /// Selects the text link presentation behavior. /// - TextLink = (int)Inno.Native.ImGui.ImGuiCol.TextLink, + TextLink = (int)NativeCol.TextLink, /// /// Selects the text selected bg presentation behavior. /// - TextSelectedBg = (int)Inno.Native.ImGui.ImGuiCol.TextSelectedBg, + TextSelectedBg = (int)NativeCol.TextSelectedBg, /// /// Selects the tree lines presentation behavior. /// - TreeLines = (int)Inno.Native.ImGui.ImGuiCol.TreeLines, + TreeLines = (int)NativeCol.TreeLines, /// /// Selects the drag drop target presentation behavior. /// - DragDropTarget = (int)Inno.Native.ImGui.ImGuiCol.DragDropTarget, + DragDropTarget = (int)NativeCol.DragDropTarget, /// /// Selects the drag drop target bg presentation behavior. /// - DragDropTargetBg = (int)Inno.Native.ImGui.ImGuiCol.DragDropTargetBg, + DragDropTargetBg = (int)NativeCol.DragDropTargetBg, /// /// Selects the unsaved marker presentation behavior. /// - UnsavedMarker = (int)Inno.Native.ImGui.ImGuiCol.UnsavedMarker, + UnsavedMarker = (int)NativeCol.UnsavedMarker, /// /// Selects the nav cursor presentation behavior. /// - NavCursor = (int)Inno.Native.ImGui.ImGuiCol.NavCursor, + NavCursor = (int)NativeCol.NavCursor, /// /// Selects the nav windowing highlight presentation behavior. /// - NavWindowingHighlight = (int)Inno.Native.ImGui.ImGuiCol.NavWindowingHighlight, + NavWindowingHighlight = (int)NativeCol.NavWindowingHighlight, /// /// Selects the nav windowing dim bg presentation behavior. /// - NavWindowingDimBg = (int)Inno.Native.ImGui.ImGuiCol.NavWindowingDimBg, + NavWindowingDimBg = (int)NativeCol.NavWindowingDimBg, /// /// Selects the modal window dim bg presentation behavior. /// - ModalWindowDimBg = (int)Inno.Native.ImGui.ImGuiCol.ModalWindowDimBg, + ModalWindowDimBg = (int)NativeCol.ModalWindowDimBg, /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiCol.Count + Count = (int)NativeCol.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs index 6c48a6ce5..d7d5a015b 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiColorEditFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeColorEditFlags = Inno.Native.ImGui.ImGuiColorEditFlags; + namespace Inno.Editor.ImGui; /// @@ -11,129 +13,129 @@ public enum ImGuiColorEditFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiColorEditFlags.None, + None = (int)NativeColorEditFlags.None, /// /// // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). /// - NoAlpha = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoAlpha, + NoAlpha = (int)NativeColorEditFlags.NoAlpha, /// /// // ColorEdit: disable picker when clicking on color square. /// - NoPicker = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoPicker, + NoPicker = (int)NativeColorEditFlags.NoPicker, /// /// // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. /// - NoOptions = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoOptions, + NoOptions = (int)NativeColorEditFlags.NoOptions, /// /// // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) /// - NoSmallPreview = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoSmallPreview, + NoSmallPreview = (int)NativeColorEditFlags.NoSmallPreview, /// /// // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). /// - NoInputs = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoInputs, + NoInputs = (int)NativeColorEditFlags.NoInputs, /// /// // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. /// - NoTooltip = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoTooltip, + NoTooltip = (int)NativeColorEditFlags.NoTooltip, /// /// // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). /// - NoLabel = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoLabel, + NoLabel = (int)NativeColorEditFlags.NoLabel, /// /// // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. /// - NoSidePreview = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoSidePreview, + NoSidePreview = (int)NativeColorEditFlags.NoSidePreview, /// /// // ColorEdit: disable drag and drop target/source. ColorButton: disable drag and drop source. /// - NoDragDrop = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoDragDrop, + NoDragDrop = (int)NativeColorEditFlags.NoDragDrop, /// /// // ColorButton: disable border (which is enforced by default) /// - NoBorder = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoBorder, + NoBorder = (int)NativeColorEditFlags.NoBorder, /// /// // ColorEdit: disable rendering R/G/B/A color marker. May also be disabled globally by setting style.ColorMarkerSize = 0. /// - NoColorMarkers = (int)Inno.Native.ImGui.ImGuiColorEditFlags.NoColorMarkers, + NoColorMarkers = (int)NativeColorEditFlags.NoColorMarkers, /// /// // ColorEdit, ColorPicker, ColorButton: disable alpha in the preview,. Contrary to _NoAlpha it may still be edited when calling ColorEdit4()/ColorPicker4(). For ColorButton() this does the same as _NoAlpha. /// - AlphaOpaque = (int)Inno.Native.ImGui.ImGuiColorEditFlags.AlphaOpaque, + AlphaOpaque = (int)NativeColorEditFlags.AlphaOpaque, /// /// // ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color. /// - AlphaNoBg = (int)Inno.Native.ImGui.ImGuiColorEditFlags.AlphaNoBg, + AlphaNoBg = (int)NativeColorEditFlags.AlphaNoBg, /// /// // ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview. /// - AlphaPreviewHalf = (int)Inno.Native.ImGui.ImGuiColorEditFlags.AlphaPreviewHalf, + AlphaPreviewHalf = (int)NativeColorEditFlags.AlphaPreviewHalf, /// /// // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. /// - AlphaBar = (int)Inno.Native.ImGui.ImGuiColorEditFlags.AlphaBar, + AlphaBar = (int)NativeColorEditFlags.AlphaBar, /// /// Selects the hdr presentation behavior. /// - Hdr = (int)Inno.Native.ImGui.ImGuiColorEditFlags.Hdr, + Hdr = (int)NativeColorEditFlags.Hdr, /// /// Selects the display rgb presentation behavior. /// - DisplayRgb = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DisplayRgb, + DisplayRgb = (int)NativeColorEditFlags.DisplayRgb, /// /// Selects the display hsv presentation behavior. /// - DisplayHsv = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DisplayHsv, + DisplayHsv = (int)NativeColorEditFlags.DisplayHsv, /// /// // " /// - DisplayHex = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DisplayHex, + DisplayHex = (int)NativeColorEditFlags.DisplayHex, /// /// // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. /// - Uint8 = (int)Inno.Native.ImGui.ImGuiColorEditFlags.Uint8, + Uint8 = (int)NativeColorEditFlags.Uint8, /// /// // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. /// - Float = (int)Inno.Native.ImGui.ImGuiColorEditFlags.Float, + Float = (int)NativeColorEditFlags.Float, /// /// // ColorPicker: bar for Hue, rectangle for Sat/Value. /// - PickerHueBar = (int)Inno.Native.ImGui.ImGuiColorEditFlags.PickerHueBar, + PickerHueBar = (int)NativeColorEditFlags.PickerHueBar, /// /// // ColorPicker: wheel for Hue, triangle for Sat/Value. /// - PickerHueWheel = (int)Inno.Native.ImGui.ImGuiColorEditFlags.PickerHueWheel, + PickerHueWheel = (int)NativeColorEditFlags.PickerHueWheel, /// /// Selects the input rgb presentation behavior. /// - InputRgb = (int)Inno.Native.ImGui.ImGuiColorEditFlags.InputRgb, + InputRgb = (int)NativeColorEditFlags.InputRgb, /// /// Selects the input hsv presentation behavior. /// - InputHsv = (int)Inno.Native.ImGui.ImGuiColorEditFlags.InputHsv, + InputHsv = (int)NativeColorEditFlags.InputHsv, /// /// Selects the default options presentation behavior. /// - DefaultOptions = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DefaultOptions, + DefaultOptions = (int)NativeColorEditFlags.DefaultOptions, /// /// Selects the alpha mask presentation behavior. /// - AlphaMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.AlphaMask, + AlphaMask = (int)NativeColorEditFlags.AlphaMask, /// /// Selects the display mask presentation behavior. /// - DisplayMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DisplayMask, + DisplayMask = (int)NativeColorEditFlags.DisplayMask, /// /// Selects the data type mask presentation behavior. /// - DataTypeMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.DataTypeMask, + DataTypeMask = (int)NativeColorEditFlags.DataTypeMask, /// /// Selects the picker mask presentation behavior. /// - PickerMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.PickerMask, + PickerMask = (int)NativeColorEditFlags.PickerMask, /// /// Selects the input mask presentation behavior. /// - InputMask = (int)Inno.Native.ImGui.ImGuiColorEditFlags.InputMask + InputMask = (int)NativeColorEditFlags.InputMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs index 865868618..5f1cd1867 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiComboFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeComboFlags = Inno.Native.ImGui.ImGuiComboFlags; + namespace Inno.Editor.ImGui; /// @@ -11,41 +13,41 @@ public enum ImGuiComboFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiComboFlags.None, + None = (int)NativeComboFlags.None, /// /// Align the popup toward the left by default /// - PopupAlignLeft = (int)Inno.Native.ImGui.ImGuiComboFlags.PopupAlignLeft, + PopupAlignLeft = (int)NativeComboFlags.PopupAlignLeft, /// /// Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() /// - HeightSmall = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightSmall, + HeightSmall = (int)NativeComboFlags.HeightSmall, /// /// Max ~8 items visible (default) /// - HeightRegular = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightRegular, + HeightRegular = (int)NativeComboFlags.HeightRegular, /// /// Max ~20 items visible /// - HeightLarge = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightLarge, + HeightLarge = (int)NativeComboFlags.HeightLarge, /// /// As many fitting items as possible /// - HeightLargest = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightLargest, + HeightLargest = (int)NativeComboFlags.HeightLargest, /// /// Display on the preview box without the square arrow button /// - NoArrowButton = (int)Inno.Native.ImGui.ImGuiComboFlags.NoArrowButton, + NoArrowButton = (int)NativeComboFlags.NoArrowButton, /// /// Display only a square arrow button /// - NoPreview = (int)Inno.Native.ImGui.ImGuiComboFlags.NoPreview, + NoPreview = (int)NativeComboFlags.NoPreview, /// /// Width dynamically calculated from preview contents /// - WidthFitPreview = (int)Inno.Native.ImGui.ImGuiComboFlags.WidthFitPreview, + WidthFitPreview = (int)NativeComboFlags.WidthFitPreview, /// /// Selects the height mask presentation behavior. /// - HeightMask = (int)Inno.Native.ImGui.ImGuiComboFlags.HeightMask + HeightMask = (int)NativeComboFlags.HeightMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs index f4adddfff..a48ff4862 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiCond.cs @@ -1,5 +1,7 @@ using System; +using NativeCond = Inno.Native.ImGui.ImGuiCond; + namespace Inno.Editor.ImGui; /// @@ -11,21 +13,21 @@ public enum ImGuiCond : int /// /// No condition (always set the variable), same as _Always /// - None = (int)Inno.Native.ImGui.ImGuiCond.None, + None = (int)NativeCond.None, /// /// No condition (always set the variable), same as _None /// - Always = (int)Inno.Native.ImGui.ImGuiCond.Always, + Always = (int)NativeCond.Always, /// /// Set the variable once per runtime session (only the first call will succeed) /// - Once = (int)Inno.Native.ImGui.ImGuiCond.Once, + Once = (int)NativeCond.Once, /// /// Set the variable if the object/window has no persistently saved data (no entry in .ini file) /// - FirstUseEver = (int)Inno.Native.ImGui.ImGuiCond.FirstUseEver, + FirstUseEver = (int)NativeCond.FirstUseEver, /// /// Set the variable if the object/window is appearing after being hidden/inactive (or the first time) /// - Appearing = (int)Inno.Native.ImGui.ImGuiCond.Appearing + Appearing = (int)NativeCond.Appearing } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs index 79f4ca86f..039401efe 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiFocusedFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeFocusedFlags = Inno.Native.ImGui.ImGuiFocusedFlags; + namespace Inno.Editor.ImGui; /// @@ -11,29 +13,29 @@ public enum ImGuiFocusedFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiFocusedFlags.None, + None = (int)NativeFocusedFlags.None, /// /// Return true if any children of the window is focused /// - ChildWindows = (int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows, + ChildWindows = (int)NativeFocusedFlags.ChildWindows, /// /// Test from root window (top most parent of the current hierarchy) /// - RootWindow = (int)Inno.Native.ImGui.ImGuiFocusedFlags.RootWindow, + RootWindow = (int)NativeFocusedFlags.RootWindow, /// /// Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! /// - AnyWindow = (int)Inno.Native.ImGui.ImGuiFocusedFlags.AnyWindow, + AnyWindow = (int)NativeFocusedFlags.AnyWindow, /// /// Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) /// - NoPopupHierarchy = (int)Inno.Native.ImGui.ImGuiFocusedFlags.NoPopupHierarchy, + NoPopupHierarchy = (int)NativeFocusedFlags.NoPopupHierarchy, /// /// Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) /// - DockHierarchy = (int)Inno.Native.ImGui.ImGuiFocusedFlags.DockHierarchy, + DockHierarchy = (int)NativeFocusedFlags.DockHierarchy, /// /// Selects the root and child windows presentation behavior. /// - RootAndChildWindows = (int)Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows + RootAndChildWindows = (int)NativeFocusedFlags.RootAndChildWindows } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs index 7ad713732..e220b67b8 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiHoveredFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeHoveredFlags = Inno.Native.ImGui.ImGuiHoveredFlags; + namespace Inno.Editor.ImGui; /// @@ -11,85 +13,85 @@ public enum ImGuiHoveredFlags : int /// /// Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. /// - None = (int)Inno.Native.ImGui.ImGuiHoveredFlags.None, + None = (int)NativeHoveredFlags.None, /// /// IsWindowHovered() only: Return true if any children of the window is hovered /// - ChildWindows = (int)Inno.Native.ImGui.ImGuiHoveredFlags.ChildWindows, + ChildWindows = (int)NativeHoveredFlags.ChildWindows, /// /// IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) /// - RootWindow = (int)Inno.Native.ImGui.ImGuiHoveredFlags.RootWindow, + RootWindow = (int)NativeHoveredFlags.RootWindow, /// /// IsWindowHovered() only: Return true if any window is hovered /// - AnyWindow = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AnyWindow, + AnyWindow = (int)NativeHoveredFlags.AnyWindow, /// /// IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) /// - NoPopupHierarchy = (int)Inno.Native.ImGui.ImGuiHoveredFlags.NoPopupHierarchy, + NoPopupHierarchy = (int)NativeHoveredFlags.NoPopupHierarchy, /// /// IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) /// - DockHierarchy = (int)Inno.Native.ImGui.ImGuiHoveredFlags.DockHierarchy, + DockHierarchy = (int)NativeHoveredFlags.DockHierarchy, /// /// Return true even if a popup window is normally blocking access to this item/window /// - AllowWhenBlockedByPopup = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenBlockedByPopup, + AllowWhenBlockedByPopup = (int)NativeHoveredFlags.AllowWhenBlockedByPopup, /// /// Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. /// - AllowWhenBlockedByActiveItem = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, + AllowWhenBlockedByActiveItem = (int)NativeHoveredFlags.AllowWhenBlockedByActiveItem, /// /// IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item. /// - AllowWhenOverlappedByItem = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenOverlappedByItem, + AllowWhenOverlappedByItem = (int)NativeHoveredFlags.AllowWhenOverlappedByItem, /// /// IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window. /// - AllowWhenOverlappedByWindow = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenOverlappedByWindow, + AllowWhenOverlappedByWindow = (int)NativeHoveredFlags.AllowWhenOverlappedByWindow, /// /// IsItemHovered() only: Return true even if the item is disabled /// - AllowWhenDisabled = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenDisabled, + AllowWhenDisabled = (int)NativeHoveredFlags.AllowWhenDisabled, /// /// IsItemHovered() only: Disable using keyboard/gamepad navigation state when active, always query mouse /// - NoNavOverride = (int)Inno.Native.ImGui.ImGuiHoveredFlags.NoNavOverride, + NoNavOverride = (int)NativeHoveredFlags.NoNavOverride, /// /// Selects the allow when overlapped presentation behavior. /// - AllowWhenOverlapped = (int)Inno.Native.ImGui.ImGuiHoveredFlags.AllowWhenOverlapped, + AllowWhenOverlapped = (int)NativeHoveredFlags.AllowWhenOverlapped, /// /// Selects the rect only presentation behavior. /// - RectOnly = (int)Inno.Native.ImGui.ImGuiHoveredFlags.RectOnly, + RectOnly = (int)NativeHoveredFlags.RectOnly, /// /// Selects the root and child windows presentation behavior. /// - RootAndChildWindows = (int)Inno.Native.ImGui.ImGuiHoveredFlags.RootAndChildWindows, + RootAndChildWindows = (int)NativeHoveredFlags.RootAndChildWindows, /// /// Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence. /// - ForTooltip = (int)Inno.Native.ImGui.ImGuiHoveredFlags.ForTooltip, + ForTooltip = (int)NativeHoveredFlags.ForTooltip, /// /// Require mouse to be stationary for style.HoverStationaryDelay (~0.15 sec) _at least one time_. After this, can move on same item/window. Using the stationary test tends to reduces the need for a long delay. /// - Stationary = (int)Inno.Native.ImGui.ImGuiHoveredFlags.Stationary, + Stationary = (int)NativeHoveredFlags.Stationary, /// /// IsItemHovered() only: Return true immediately (default). As this is the default you generally ignore this. /// - DelayNone = (int)Inno.Native.ImGui.ImGuiHoveredFlags.DelayNone, + DelayNone = (int)NativeHoveredFlags.DelayNone, /// /// IsItemHovered() only: Return true after style.HoverDelayShort elapsed (~0.15 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). /// - DelayShort = (int)Inno.Native.ImGui.ImGuiHoveredFlags.DelayShort, + DelayShort = (int)NativeHoveredFlags.DelayShort, /// /// IsItemHovered() only: Return true after style.HoverDelayNormal elapsed (~0.40 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). /// - DelayNormal = (int)Inno.Native.ImGui.ImGuiHoveredFlags.DelayNormal, + DelayNormal = (int)NativeHoveredFlags.DelayNormal, /// /// IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) /// - NoSharedDelay = (int)Inno.Native.ImGui.ImGuiHoveredFlags.NoSharedDelay + NoSharedDelay = (int)NativeHoveredFlags.NoSharedDelay } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs index bd5c2b265..6a9dc3240 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiInputTextFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeInputTextFlags = Inno.Native.ImGui.ImGuiInputTextFlags; + namespace Inno.Editor.ImGui; /// @@ -11,105 +13,105 @@ public enum ImGuiInputTextFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiInputTextFlags.None, + None = (int)NativeInputTextFlags.None, /// /// Allow 0123456789.+-*/ /// - CharsDecimal = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CharsDecimal, + CharsDecimal = (int)NativeInputTextFlags.CharsDecimal, /// /// Allow 0123456789ABCDEFabcdef /// - CharsHexadecimal = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CharsHexadecimal, + CharsHexadecimal = (int)NativeInputTextFlags.CharsHexadecimal, /// /// Allow 0123456789.+-*/eE (Scientific notation input) /// - CharsScientific = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CharsScientific, + CharsScientific = (int)NativeInputTextFlags.CharsScientific, /// /// Turn a..z into A..Z /// - CharsUppercase = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CharsUppercase, + CharsUppercase = (int)NativeInputTextFlags.CharsUppercase, /// /// Filter out spaces, tabs /// - CharsNoBlank = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CharsNoBlank, + CharsNoBlank = (int)NativeInputTextFlags.CharsNoBlank, /// /// Pressing TAB input a '\t' character into the text field /// - AllowTabInput = (int)Inno.Native.ImGui.ImGuiInputTextFlags.AllowTabInput, + AllowTabInput = (int)NativeInputTextFlags.AllowTabInput, /// /// Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider using IsItemDeactivatedAfterEdit() instead! /// - EnterReturnsTrue = (int)Inno.Native.ImGui.ImGuiInputTextFlags.EnterReturnsTrue, + EnterReturnsTrue = (int)NativeInputTextFlags.EnterReturnsTrue, /// /// Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) /// - EscapeClearsAll = (int)Inno.Native.ImGui.ImGuiInputTextFlags.EscapeClearsAll, + EscapeClearsAll = (int)NativeInputTextFlags.EscapeClearsAll, /// /// In multi-line mode, validate with Enter, add new line with Ctrl+Enter (default is opposite: validate with Ctrl+Enter, add line with Enter). /// - CtrlEnterForNewLine = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CtrlEnterForNewLine, + CtrlEnterForNewLine = (int)NativeInputTextFlags.CtrlEnterForNewLine, /// /// Read-only mode /// - ReadOnly = (int)Inno.Native.ImGui.ImGuiInputTextFlags.ReadOnly, + ReadOnly = (int)NativeInputTextFlags.ReadOnly, /// /// Password mode, display all characters as '*', disable copy /// - Password = (int)Inno.Native.ImGui.ImGuiInputTextFlags.Password, + Password = (int)NativeInputTextFlags.Password, /// /// Overwrite mode /// - AlwaysOverwrite = (int)Inno.Native.ImGui.ImGuiInputTextFlags.AlwaysOverwrite, + AlwaysOverwrite = (int)NativeInputTextFlags.AlwaysOverwrite, /// /// Select entire text when first taking mouse focus /// - AutoSelectAll = (int)Inno.Native.ImGui.ImGuiInputTextFlags.AutoSelectAll, + AutoSelectAll = (int)NativeInputTextFlags.AutoSelectAll, /// /// InputFloat(), InputInt(), InputScalar() etc. only: parse empty string as zero value. /// - ParseEmptyRefVal = (int)Inno.Native.ImGui.ImGuiInputTextFlags.ParseEmptyRefVal, + ParseEmptyRefVal = (int)NativeInputTextFlags.ParseEmptyRefVal, /// /// InputFloat(), InputInt(), InputScalar() etc. only: when value is zero, do not display it. Generally used with ImGuiInputTextFlags_ParseEmptyRefVal. /// - DisplayEmptyRefVal = (int)Inno.Native.ImGui.ImGuiInputTextFlags.DisplayEmptyRefVal, + DisplayEmptyRefVal = (int)NativeInputTextFlags.DisplayEmptyRefVal, /// /// Disable following the cursor horizontally /// - NoHorizontalScroll = (int)Inno.Native.ImGui.ImGuiInputTextFlags.NoHorizontalScroll, + NoHorizontalScroll = (int)NativeInputTextFlags.NoHorizontalScroll, /// /// Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). /// - NoUndoRedo = (int)Inno.Native.ImGui.ImGuiInputTextFlags.NoUndoRedo, + NoUndoRedo = (int)NativeInputTextFlags.NoUndoRedo, /// /// When text doesn't fit, elide left side to ensure right side stays visible. Useful for path/filenames. Single-line only! /// - ElideLeft = (int)Inno.Native.ImGui.ImGuiInputTextFlags.ElideLeft, + ElideLeft = (int)NativeInputTextFlags.ElideLeft, /// /// Callback on pressing TAB (for completion handling) /// - CallbackCompletion = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackCompletion, + CallbackCompletion = (int)NativeInputTextFlags.CallbackCompletion, /// /// Callback on pressing Up/Down arrows (for history handling) /// - CallbackHistory = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackHistory, + CallbackHistory = (int)NativeInputTextFlags.CallbackHistory, /// /// Callback on each iteration. User code may query cursor position, modify text buffer. /// - CallbackAlways = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackAlways, + CallbackAlways = (int)NativeInputTextFlags.CallbackAlways, /// /// Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. /// - CallbackCharFilter = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackCharFilter, + CallbackCharFilter = (int)NativeInputTextFlags.CallbackCharFilter, /// /// Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) /// - CallbackResize = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackResize, + CallbackResize = (int)NativeInputTextFlags.CallbackResize, /// /// Callback on any edit. Note that InputText() already returns true on edit + you can always use IsItemEdited(). The callback is useful to manipulate the underlying buffer while focus is active. /// - CallbackEdit = (int)Inno.Native.ImGui.ImGuiInputTextFlags.CallbackEdit, + CallbackEdit = (int)NativeInputTextFlags.CallbackEdit, /// /// InputTextMultiline(): word-wrap lines that are too long. /// - WordWrap = (int)Inno.Native.ImGui.ImGuiInputTextFlags.WordWrap + WordWrap = (int)NativeInputTextFlags.WordWrap } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs index 619bd27a0..1264a8a64 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiKey.cs @@ -1,5 +1,7 @@ using System; +using NativeKey = Inno.Native.ImGui.ImGuiKey; + namespace Inno.Editor.ImGui; /// @@ -10,661 +12,661 @@ public enum ImGuiKey : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiKey.None, + None = (int)NativeKey.None, /// /// Identifies the NamedKeyBegin presentation key or modifier. /// - NamedKeyBegin = (int)Inno.Native.ImGui.ImGuiKey.NamedKeyBegin, + NamedKeyBegin = (int)NativeKey.NamedKeyBegin, /// /// == ImGuiKey_NamedKey_BEGIN /// - Tab = (int)Inno.Native.ImGui.ImGuiKey.Tab, + Tab = (int)NativeKey.Tab, /// /// Identifies the LeftArrow presentation key or modifier. /// - LeftArrow = (int)Inno.Native.ImGui.ImGuiKey.LeftArrow, + LeftArrow = (int)NativeKey.LeftArrow, /// /// Identifies the RightArrow presentation key or modifier. /// - RightArrow = (int)Inno.Native.ImGui.ImGuiKey.RightArrow, + RightArrow = (int)NativeKey.RightArrow, /// /// Identifies the UpArrow presentation key or modifier. /// - UpArrow = (int)Inno.Native.ImGui.ImGuiKey.UpArrow, + UpArrow = (int)NativeKey.UpArrow, /// /// Identifies the DownArrow presentation key or modifier. /// - DownArrow = (int)Inno.Native.ImGui.ImGuiKey.DownArrow, + DownArrow = (int)NativeKey.DownArrow, /// /// Identifies the PageUp presentation key or modifier. /// - PageUp = (int)Inno.Native.ImGui.ImGuiKey.PageUp, + PageUp = (int)NativeKey.PageUp, /// /// Identifies the PageDown presentation key or modifier. /// - PageDown = (int)Inno.Native.ImGui.ImGuiKey.PageDown, + PageDown = (int)NativeKey.PageDown, /// /// Identifies the Home presentation key or modifier. /// - Home = (int)Inno.Native.ImGui.ImGuiKey.Home, + Home = (int)NativeKey.Home, /// /// Identifies the End presentation key or modifier. /// - End = (int)Inno.Native.ImGui.ImGuiKey.End, + End = (int)NativeKey.End, /// /// Identifies the Insert presentation key or modifier. /// - Insert = (int)Inno.Native.ImGui.ImGuiKey.Insert, + Insert = (int)NativeKey.Insert, /// /// Identifies the Delete presentation key or modifier. /// - Delete = (int)Inno.Native.ImGui.ImGuiKey.Delete, + Delete = (int)NativeKey.Delete, /// /// Identifies the Backspace presentation key or modifier. /// - Backspace = (int)Inno.Native.ImGui.ImGuiKey.Backspace, + Backspace = (int)NativeKey.Backspace, /// /// Identifies the Space presentation key or modifier. /// - Space = (int)Inno.Native.ImGui.ImGuiKey.Space, + Space = (int)NativeKey.Space, /// /// Identifies the Enter presentation key or modifier. /// - Enter = (int)Inno.Native.ImGui.ImGuiKey.Enter, + Enter = (int)NativeKey.Enter, /// /// Identifies the Escape presentation key or modifier. /// - Escape = (int)Inno.Native.ImGui.ImGuiKey.Escape, + Escape = (int)NativeKey.Escape, /// /// Identifies the LeftCtrl presentation key or modifier. /// - LeftCtrl = (int)Inno.Native.ImGui.ImGuiKey.LeftCtrl, + LeftCtrl = (int)NativeKey.LeftCtrl, /// /// Identifies the LeftShift presentation key or modifier. /// - LeftShift = (int)Inno.Native.ImGui.ImGuiKey.LeftShift, + LeftShift = (int)NativeKey.LeftShift, /// /// Identifies the LeftAlt presentation key or modifier. /// - LeftAlt = (int)Inno.Native.ImGui.ImGuiKey.LeftAlt, + LeftAlt = (int)NativeKey.LeftAlt, /// /// Identifies the LeftSuper presentation key or modifier. /// - LeftSuper = (int)Inno.Native.ImGui.ImGuiKey.LeftSuper, + LeftSuper = (int)NativeKey.LeftSuper, /// /// Identifies the RightCtrl presentation key or modifier. /// - RightCtrl = (int)Inno.Native.ImGui.ImGuiKey.RightCtrl, + RightCtrl = (int)NativeKey.RightCtrl, /// /// Identifies the RightShift presentation key or modifier. /// - RightShift = (int)Inno.Native.ImGui.ImGuiKey.RightShift, + RightShift = (int)NativeKey.RightShift, /// /// Identifies the RightAlt presentation key or modifier. /// - RightAlt = (int)Inno.Native.ImGui.ImGuiKey.RightAlt, + RightAlt = (int)NativeKey.RightAlt, /// /// Identifies the RightSuper presentation key or modifier. /// - RightSuper = (int)Inno.Native.ImGui.ImGuiKey.RightSuper, + RightSuper = (int)NativeKey.RightSuper, /// /// Identifies the Menu presentation key or modifier. /// - Menu = (int)Inno.Native.ImGui.ImGuiKey.Menu, + Menu = (int)NativeKey.Menu, /// /// Identifies the _0 presentation key or modifier. /// - _0 = (int)Inno.Native.ImGui.ImGuiKey._0, + _0 = (int)NativeKey._0, /// /// Identifies the _1 presentation key or modifier. /// - _1 = (int)Inno.Native.ImGui.ImGuiKey._1, + _1 = (int)NativeKey._1, /// /// Identifies the _2 presentation key or modifier. /// - _2 = (int)Inno.Native.ImGui.ImGuiKey._2, + _2 = (int)NativeKey._2, /// /// Identifies the _3 presentation key or modifier. /// - _3 = (int)Inno.Native.ImGui.ImGuiKey._3, + _3 = (int)NativeKey._3, /// /// Identifies the _4 presentation key or modifier. /// - _4 = (int)Inno.Native.ImGui.ImGuiKey._4, + _4 = (int)NativeKey._4, /// /// Identifies the _5 presentation key or modifier. /// - _5 = (int)Inno.Native.ImGui.ImGuiKey._5, + _5 = (int)NativeKey._5, /// /// Identifies the _6 presentation key or modifier. /// - _6 = (int)Inno.Native.ImGui.ImGuiKey._6, + _6 = (int)NativeKey._6, /// /// Identifies the _7 presentation key or modifier. /// - _7 = (int)Inno.Native.ImGui.ImGuiKey._7, + _7 = (int)NativeKey._7, /// /// Identifies the _8 presentation key or modifier. /// - _8 = (int)Inno.Native.ImGui.ImGuiKey._8, + _8 = (int)NativeKey._8, /// /// Identifies the _9 presentation key or modifier. /// - _9 = (int)Inno.Native.ImGui.ImGuiKey._9, + _9 = (int)NativeKey._9, /// /// Identifies the A presentation key or modifier. /// - A = (int)Inno.Native.ImGui.ImGuiKey.A, + A = (int)NativeKey.A, /// /// Identifies the B presentation key or modifier. /// - B = (int)Inno.Native.ImGui.ImGuiKey.B, + B = (int)NativeKey.B, /// /// Identifies the C presentation key or modifier. /// - C = (int)Inno.Native.ImGui.ImGuiKey.C, + C = (int)NativeKey.C, /// /// Identifies the D presentation key or modifier. /// - D = (int)Inno.Native.ImGui.ImGuiKey.D, + D = (int)NativeKey.D, /// /// Identifies the E presentation key or modifier. /// - E = (int)Inno.Native.ImGui.ImGuiKey.E, + E = (int)NativeKey.E, /// /// Identifies the F presentation key or modifier. /// - F = (int)Inno.Native.ImGui.ImGuiKey.F, + F = (int)NativeKey.F, /// /// Identifies the G presentation key or modifier. /// - G = (int)Inno.Native.ImGui.ImGuiKey.G, + G = (int)NativeKey.G, /// /// Identifies the H presentation key or modifier. /// - H = (int)Inno.Native.ImGui.ImGuiKey.H, + H = (int)NativeKey.H, /// /// Identifies the I presentation key or modifier. /// - I = (int)Inno.Native.ImGui.ImGuiKey.I, + I = (int)NativeKey.I, /// /// Identifies the J presentation key or modifier. /// - J = (int)Inno.Native.ImGui.ImGuiKey.J, + J = (int)NativeKey.J, /// /// Identifies the K presentation key or modifier. /// - K = (int)Inno.Native.ImGui.ImGuiKey.K, + K = (int)NativeKey.K, /// /// Identifies the L presentation key or modifier. /// - L = (int)Inno.Native.ImGui.ImGuiKey.L, + L = (int)NativeKey.L, /// /// Identifies the M presentation key or modifier. /// - M = (int)Inno.Native.ImGui.ImGuiKey.M, + M = (int)NativeKey.M, /// /// Identifies the N presentation key or modifier. /// - N = (int)Inno.Native.ImGui.ImGuiKey.N, + N = (int)NativeKey.N, /// /// Identifies the O presentation key or modifier. /// - O = (int)Inno.Native.ImGui.ImGuiKey.O, + O = (int)NativeKey.O, /// /// Identifies the P presentation key or modifier. /// - P = (int)Inno.Native.ImGui.ImGuiKey.P, + P = (int)NativeKey.P, /// /// Identifies the Q presentation key or modifier. /// - Q = (int)Inno.Native.ImGui.ImGuiKey.Q, + Q = (int)NativeKey.Q, /// /// Identifies the R presentation key or modifier. /// - R = (int)Inno.Native.ImGui.ImGuiKey.R, + R = (int)NativeKey.R, /// /// Identifies the S presentation key or modifier. /// - S = (int)Inno.Native.ImGui.ImGuiKey.S, + S = (int)NativeKey.S, /// /// Identifies the T presentation key or modifier. /// - T = (int)Inno.Native.ImGui.ImGuiKey.T, + T = (int)NativeKey.T, /// /// Identifies the U presentation key or modifier. /// - U = (int)Inno.Native.ImGui.ImGuiKey.U, + U = (int)NativeKey.U, /// /// Identifies the V presentation key or modifier. /// - V = (int)Inno.Native.ImGui.ImGuiKey.V, + V = (int)NativeKey.V, /// /// Identifies the W presentation key or modifier. /// - W = (int)Inno.Native.ImGui.ImGuiKey.W, + W = (int)NativeKey.W, /// /// Identifies the X presentation key or modifier. /// - X = (int)Inno.Native.ImGui.ImGuiKey.X, + X = (int)NativeKey.X, /// /// Identifies the Y presentation key or modifier. /// - Y = (int)Inno.Native.ImGui.ImGuiKey.Y, + Y = (int)NativeKey.Y, /// /// Identifies the Z presentation key or modifier. /// - Z = (int)Inno.Native.ImGui.ImGuiKey.Z, + Z = (int)NativeKey.Z, /// /// Identifies the F1 presentation key or modifier. /// - F1 = (int)Inno.Native.ImGui.ImGuiKey.F1, + F1 = (int)NativeKey.F1, /// /// Identifies the F2 presentation key or modifier. /// - F2 = (int)Inno.Native.ImGui.ImGuiKey.F2, + F2 = (int)NativeKey.F2, /// /// Identifies the F3 presentation key or modifier. /// - F3 = (int)Inno.Native.ImGui.ImGuiKey.F3, + F3 = (int)NativeKey.F3, /// /// Identifies the F4 presentation key or modifier. /// - F4 = (int)Inno.Native.ImGui.ImGuiKey.F4, + F4 = (int)NativeKey.F4, /// /// Identifies the F5 presentation key or modifier. /// - F5 = (int)Inno.Native.ImGui.ImGuiKey.F5, + F5 = (int)NativeKey.F5, /// /// Identifies the F6 presentation key or modifier. /// - F6 = (int)Inno.Native.ImGui.ImGuiKey.F6, + F6 = (int)NativeKey.F6, /// /// Identifies the F7 presentation key or modifier. /// - F7 = (int)Inno.Native.ImGui.ImGuiKey.F7, + F7 = (int)NativeKey.F7, /// /// Identifies the F8 presentation key or modifier. /// - F8 = (int)Inno.Native.ImGui.ImGuiKey.F8, + F8 = (int)NativeKey.F8, /// /// Identifies the F9 presentation key or modifier. /// - F9 = (int)Inno.Native.ImGui.ImGuiKey.F9, + F9 = (int)NativeKey.F9, /// /// Identifies the F10 presentation key or modifier. /// - F10 = (int)Inno.Native.ImGui.ImGuiKey.F10, + F10 = (int)NativeKey.F10, /// /// Identifies the F11 presentation key or modifier. /// - F11 = (int)Inno.Native.ImGui.ImGuiKey.F11, + F11 = (int)NativeKey.F11, /// /// Identifies the F12 presentation key or modifier. /// - F12 = (int)Inno.Native.ImGui.ImGuiKey.F12, + F12 = (int)NativeKey.F12, /// /// Identifies the F13 presentation key or modifier. /// - F13 = (int)Inno.Native.ImGui.ImGuiKey.F13, + F13 = (int)NativeKey.F13, /// /// Identifies the F14 presentation key or modifier. /// - F14 = (int)Inno.Native.ImGui.ImGuiKey.F14, + F14 = (int)NativeKey.F14, /// /// Identifies the F15 presentation key or modifier. /// - F15 = (int)Inno.Native.ImGui.ImGuiKey.F15, + F15 = (int)NativeKey.F15, /// /// Identifies the F16 presentation key or modifier. /// - F16 = (int)Inno.Native.ImGui.ImGuiKey.F16, + F16 = (int)NativeKey.F16, /// /// Identifies the F17 presentation key or modifier. /// - F17 = (int)Inno.Native.ImGui.ImGuiKey.F17, + F17 = (int)NativeKey.F17, /// /// Identifies the F18 presentation key or modifier. /// - F18 = (int)Inno.Native.ImGui.ImGuiKey.F18, + F18 = (int)NativeKey.F18, /// /// Identifies the F19 presentation key or modifier. /// - F19 = (int)Inno.Native.ImGui.ImGuiKey.F19, + F19 = (int)NativeKey.F19, /// /// Identifies the F20 presentation key or modifier. /// - F20 = (int)Inno.Native.ImGui.ImGuiKey.F20, + F20 = (int)NativeKey.F20, /// /// Identifies the F21 presentation key or modifier. /// - F21 = (int)Inno.Native.ImGui.ImGuiKey.F21, + F21 = (int)NativeKey.F21, /// /// Identifies the F22 presentation key or modifier. /// - F22 = (int)Inno.Native.ImGui.ImGuiKey.F22, + F22 = (int)NativeKey.F22, /// /// Identifies the F23 presentation key or modifier. /// - F23 = (int)Inno.Native.ImGui.ImGuiKey.F23, + F23 = (int)NativeKey.F23, /// /// Identifies the F24 presentation key or modifier. /// - F24 = (int)Inno.Native.ImGui.ImGuiKey.F24, + F24 = (int)NativeKey.F24, /// /// Identifies the Apostrophe presentation key or modifier. /// - Apostrophe = (int)Inno.Native.ImGui.ImGuiKey.Apostrophe, + Apostrophe = (int)NativeKey.Apostrophe, /// /// Identifies the Comma presentation key or modifier. /// - Comma = (int)Inno.Native.ImGui.ImGuiKey.Comma, + Comma = (int)NativeKey.Comma, /// /// Identifies the Minus presentation key or modifier. /// - Minus = (int)Inno.Native.ImGui.ImGuiKey.Minus, + Minus = (int)NativeKey.Minus, /// /// Identifies the Period presentation key or modifier. /// - Period = (int)Inno.Native.ImGui.ImGuiKey.Period, + Period = (int)NativeKey.Period, /// /// Identifies the Slash presentation key or modifier. /// - Slash = (int)Inno.Native.ImGui.ImGuiKey.Slash, + Slash = (int)NativeKey.Slash, /// /// Identifies the Semicolon presentation key or modifier. /// - Semicolon = (int)Inno.Native.ImGui.ImGuiKey.Semicolon, + Semicolon = (int)NativeKey.Semicolon, /// /// Identifies the Equal presentation key or modifier. /// - Equal = (int)Inno.Native.ImGui.ImGuiKey.Equal, + Equal = (int)NativeKey.Equal, /// /// Identifies the LeftBracket presentation key or modifier. /// - LeftBracket = (int)Inno.Native.ImGui.ImGuiKey.LeftBracket, + LeftBracket = (int)NativeKey.LeftBracket, /// /// Identifies the Backslash presentation key or modifier. /// - Backslash = (int)Inno.Native.ImGui.ImGuiKey.Backslash, + Backslash = (int)NativeKey.Backslash, /// /// Identifies the RightBracket presentation key or modifier. /// - RightBracket = (int)Inno.Native.ImGui.ImGuiKey.RightBracket, + RightBracket = (int)NativeKey.RightBracket, /// /// Identifies the GraveAccent presentation key or modifier. /// - GraveAccent = (int)Inno.Native.ImGui.ImGuiKey.GraveAccent, + GraveAccent = (int)NativeKey.GraveAccent, /// /// Identifies the CapsLock presentation key or modifier. /// - CapsLock = (int)Inno.Native.ImGui.ImGuiKey.CapsLock, + CapsLock = (int)NativeKey.CapsLock, /// /// Identifies the ScrollLock presentation key or modifier. /// - ScrollLock = (int)Inno.Native.ImGui.ImGuiKey.ScrollLock, + ScrollLock = (int)NativeKey.ScrollLock, /// /// Identifies the NumLock presentation key or modifier. /// - NumLock = (int)Inno.Native.ImGui.ImGuiKey.NumLock, + NumLock = (int)NativeKey.NumLock, /// /// Identifies the PrintScreen presentation key or modifier. /// - PrintScreen = (int)Inno.Native.ImGui.ImGuiKey.PrintScreen, + PrintScreen = (int)NativeKey.PrintScreen, /// /// Identifies the Pause presentation key or modifier. /// - Pause = (int)Inno.Native.ImGui.ImGuiKey.Pause, + Pause = (int)NativeKey.Pause, /// /// Identifies the Keypad0 presentation key or modifier. /// - Keypad0 = (int)Inno.Native.ImGui.ImGuiKey.Keypad0, + Keypad0 = (int)NativeKey.Keypad0, /// /// Identifies the Keypad1 presentation key or modifier. /// - Keypad1 = (int)Inno.Native.ImGui.ImGuiKey.Keypad1, + Keypad1 = (int)NativeKey.Keypad1, /// /// Identifies the Keypad2 presentation key or modifier. /// - Keypad2 = (int)Inno.Native.ImGui.ImGuiKey.Keypad2, + Keypad2 = (int)NativeKey.Keypad2, /// /// Identifies the Keypad3 presentation key or modifier. /// - Keypad3 = (int)Inno.Native.ImGui.ImGuiKey.Keypad3, + Keypad3 = (int)NativeKey.Keypad3, /// /// Identifies the Keypad4 presentation key or modifier. /// - Keypad4 = (int)Inno.Native.ImGui.ImGuiKey.Keypad4, + Keypad4 = (int)NativeKey.Keypad4, /// /// Identifies the Keypad5 presentation key or modifier. /// - Keypad5 = (int)Inno.Native.ImGui.ImGuiKey.Keypad5, + Keypad5 = (int)NativeKey.Keypad5, /// /// Identifies the Keypad6 presentation key or modifier. /// - Keypad6 = (int)Inno.Native.ImGui.ImGuiKey.Keypad6, + Keypad6 = (int)NativeKey.Keypad6, /// /// Identifies the Keypad7 presentation key or modifier. /// - Keypad7 = (int)Inno.Native.ImGui.ImGuiKey.Keypad7, + Keypad7 = (int)NativeKey.Keypad7, /// /// Identifies the Keypad8 presentation key or modifier. /// - Keypad8 = (int)Inno.Native.ImGui.ImGuiKey.Keypad8, + Keypad8 = (int)NativeKey.Keypad8, /// /// Identifies the Keypad9 presentation key or modifier. /// - Keypad9 = (int)Inno.Native.ImGui.ImGuiKey.Keypad9, + Keypad9 = (int)NativeKey.Keypad9, /// /// Identifies the KeypadDecimal presentation key or modifier. /// - KeypadDecimal = (int)Inno.Native.ImGui.ImGuiKey.KeypadDecimal, + KeypadDecimal = (int)NativeKey.KeypadDecimal, /// /// Identifies the KeypadDivide presentation key or modifier. /// - KeypadDivide = (int)Inno.Native.ImGui.ImGuiKey.KeypadDivide, + KeypadDivide = (int)NativeKey.KeypadDivide, /// /// Identifies the KeypadMultiply presentation key or modifier. /// - KeypadMultiply = (int)Inno.Native.ImGui.ImGuiKey.KeypadMultiply, + KeypadMultiply = (int)NativeKey.KeypadMultiply, /// /// Identifies the KeypadSubtract presentation key or modifier. /// - KeypadSubtract = (int)Inno.Native.ImGui.ImGuiKey.KeypadSubtract, + KeypadSubtract = (int)NativeKey.KeypadSubtract, /// /// Identifies the KeypadAdd presentation key or modifier. /// - KeypadAdd = (int)Inno.Native.ImGui.ImGuiKey.KeypadAdd, + KeypadAdd = (int)NativeKey.KeypadAdd, /// /// Identifies the KeypadEnter presentation key or modifier. /// - KeypadEnter = (int)Inno.Native.ImGui.ImGuiKey.KeypadEnter, + KeypadEnter = (int)NativeKey.KeypadEnter, /// /// Identifies the KeypadEqual presentation key or modifier. /// - KeypadEqual = (int)Inno.Native.ImGui.ImGuiKey.KeypadEqual, + KeypadEqual = (int)NativeKey.KeypadEqual, /// /// Identifies the AppBack presentation key or modifier. /// - AppBack = (int)Inno.Native.ImGui.ImGuiKey.AppBack, + AppBack = (int)NativeKey.AppBack, /// /// Identifies the AppForward presentation key or modifier. /// - AppForward = (int)Inno.Native.ImGui.ImGuiKey.AppForward, + AppForward = (int)NativeKey.AppForward, /// /// Identifies the Oem102 presentation key or modifier. /// - Oem102 = (int)Inno.Native.ImGui.ImGuiKey.Oem102, + Oem102 = (int)NativeKey.Oem102, /// /// Identifies the GamepadStart presentation key or modifier. /// - GamepadStart = (int)Inno.Native.ImGui.ImGuiKey.GamepadStart, + GamepadStart = (int)NativeKey.GamepadStart, /// /// Identifies the GamepadBack presentation key or modifier. /// - GamepadBack = (int)Inno.Native.ImGui.ImGuiKey.GamepadBack, + GamepadBack = (int)NativeKey.GamepadBack, /// /// Identifies the GamepadFaceLeft presentation key or modifier. /// - GamepadFaceLeft = (int)Inno.Native.ImGui.ImGuiKey.GamepadFaceLeft, + GamepadFaceLeft = (int)NativeKey.GamepadFaceLeft, /// /// Identifies the GamepadFaceRight presentation key or modifier. /// - GamepadFaceRight = (int)Inno.Native.ImGui.ImGuiKey.GamepadFaceRight, + GamepadFaceRight = (int)NativeKey.GamepadFaceRight, /// /// Identifies the GamepadFaceUp presentation key or modifier. /// - GamepadFaceUp = (int)Inno.Native.ImGui.ImGuiKey.GamepadFaceUp, + GamepadFaceUp = (int)NativeKey.GamepadFaceUp, /// /// Identifies the GamepadFaceDown presentation key or modifier. /// - GamepadFaceDown = (int)Inno.Native.ImGui.ImGuiKey.GamepadFaceDown, + GamepadFaceDown = (int)NativeKey.GamepadFaceDown, /// /// Identifies the GamepadDpadLeft presentation key or modifier. /// - GamepadDpadLeft = (int)Inno.Native.ImGui.ImGuiKey.GamepadDpadLeft, + GamepadDpadLeft = (int)NativeKey.GamepadDpadLeft, /// /// Identifies the GamepadDpadRight presentation key or modifier. /// - GamepadDpadRight = (int)Inno.Native.ImGui.ImGuiKey.GamepadDpadRight, + GamepadDpadRight = (int)NativeKey.GamepadDpadRight, /// /// Identifies the GamepadDpadUp presentation key or modifier. /// - GamepadDpadUp = (int)Inno.Native.ImGui.ImGuiKey.GamepadDpadUp, + GamepadDpadUp = (int)NativeKey.GamepadDpadUp, /// /// Identifies the GamepadDpadDown presentation key or modifier. /// - GamepadDpadDown = (int)Inno.Native.ImGui.ImGuiKey.GamepadDpadDown, + GamepadDpadDown = (int)NativeKey.GamepadDpadDown, /// /// Identifies the GamepadL1 presentation key or modifier. /// - GamepadL1 = (int)Inno.Native.ImGui.ImGuiKey.GamepadL1, + GamepadL1 = (int)NativeKey.GamepadL1, /// /// Identifies the GamepadR1 presentation key or modifier. /// - GamepadR1 = (int)Inno.Native.ImGui.ImGuiKey.GamepadR1, + GamepadR1 = (int)NativeKey.GamepadR1, /// /// Identifies the GamepadL2 presentation key or modifier. /// - GamepadL2 = (int)Inno.Native.ImGui.ImGuiKey.GamepadL2, + GamepadL2 = (int)NativeKey.GamepadL2, /// /// Identifies the GamepadR2 presentation key or modifier. /// - GamepadR2 = (int)Inno.Native.ImGui.ImGuiKey.GamepadR2, + GamepadR2 = (int)NativeKey.GamepadR2, /// /// Identifies the GamepadL3 presentation key or modifier. /// - GamepadL3 = (int)Inno.Native.ImGui.ImGuiKey.GamepadL3, + GamepadL3 = (int)NativeKey.GamepadL3, /// /// Identifies the GamepadR3 presentation key or modifier. /// - GamepadR3 = (int)Inno.Native.ImGui.ImGuiKey.GamepadR3, + GamepadR3 = (int)NativeKey.GamepadR3, /// /// Identifies the GamepadLStickLeft presentation key or modifier. /// - GamepadLStickLeft = (int)Inno.Native.ImGui.ImGuiKey.GamepadLStickLeft, + GamepadLStickLeft = (int)NativeKey.GamepadLStickLeft, /// /// Identifies the GamepadLStickRight presentation key or modifier. /// - GamepadLStickRight = (int)Inno.Native.ImGui.ImGuiKey.GamepadLStickRight, + GamepadLStickRight = (int)NativeKey.GamepadLStickRight, /// /// Identifies the GamepadLStickUp presentation key or modifier. /// - GamepadLStickUp = (int)Inno.Native.ImGui.ImGuiKey.GamepadLStickUp, + GamepadLStickUp = (int)NativeKey.GamepadLStickUp, /// /// Identifies the GamepadLStickDown presentation key or modifier. /// - GamepadLStickDown = (int)Inno.Native.ImGui.ImGuiKey.GamepadLStickDown, + GamepadLStickDown = (int)NativeKey.GamepadLStickDown, /// /// Identifies the GamepadRStickLeft presentation key or modifier. /// - GamepadRStickLeft = (int)Inno.Native.ImGui.ImGuiKey.GamepadRStickLeft, + GamepadRStickLeft = (int)NativeKey.GamepadRStickLeft, /// /// Identifies the GamepadRStickRight presentation key or modifier. /// - GamepadRStickRight = (int)Inno.Native.ImGui.ImGuiKey.GamepadRStickRight, + GamepadRStickRight = (int)NativeKey.GamepadRStickRight, /// /// Identifies the GamepadRStickUp presentation key or modifier. /// - GamepadRStickUp = (int)Inno.Native.ImGui.ImGuiKey.GamepadRStickUp, + GamepadRStickUp = (int)NativeKey.GamepadRStickUp, /// /// Identifies the GamepadRStickDown presentation key or modifier. /// - GamepadRStickDown = (int)Inno.Native.ImGui.ImGuiKey.GamepadRStickDown, + GamepadRStickDown = (int)NativeKey.GamepadRStickDown, /// /// Identifies the MouseLeft presentation key or modifier. /// - MouseLeft = (int)Inno.Native.ImGui.ImGuiKey.MouseLeft, + MouseLeft = (int)NativeKey.MouseLeft, /// /// Identifies the MouseRight presentation key or modifier. /// - MouseRight = (int)Inno.Native.ImGui.ImGuiKey.MouseRight, + MouseRight = (int)NativeKey.MouseRight, /// /// Identifies the MouseMiddle presentation key or modifier. /// - MouseMiddle = (int)Inno.Native.ImGui.ImGuiKey.MouseMiddle, + MouseMiddle = (int)NativeKey.MouseMiddle, /// /// Identifies the MouseX1 presentation key or modifier. /// - MouseX1 = (int)Inno.Native.ImGui.ImGuiKey.MouseX1, + MouseX1 = (int)NativeKey.MouseX1, /// /// Identifies the MouseX2 presentation key or modifier. /// - MouseX2 = (int)Inno.Native.ImGui.ImGuiKey.MouseX2, + MouseX2 = (int)NativeKey.MouseX2, /// /// Identifies the MouseWheelX presentation key or modifier. /// - MouseWheelX = (int)Inno.Native.ImGui.ImGuiKey.MouseWheelX, + MouseWheelX = (int)NativeKey.MouseWheelX, /// /// Identifies the MouseWheelY presentation key or modifier. /// - MouseWheelY = (int)Inno.Native.ImGui.ImGuiKey.MouseWheelY, + MouseWheelY = (int)NativeKey.MouseWheelY, /// /// Identifies the ReservedForModCtrl presentation key or modifier. /// - ReservedForModCtrl = (int)Inno.Native.ImGui.ImGuiKey.ReservedForModCtrl, + ReservedForModCtrl = (int)NativeKey.ReservedForModCtrl, /// /// Identifies the ReservedForModShift presentation key or modifier. /// - ReservedForModShift = (int)Inno.Native.ImGui.ImGuiKey.ReservedForModShift, + ReservedForModShift = (int)NativeKey.ReservedForModShift, /// /// Identifies the ReservedForModAlt presentation key or modifier. /// - ReservedForModAlt = (int)Inno.Native.ImGui.ImGuiKey.ReservedForModAlt, + ReservedForModAlt = (int)NativeKey.ReservedForModAlt, /// /// Identifies the ReservedForModSuper presentation key or modifier. /// - ReservedForModSuper = (int)Inno.Native.ImGui.ImGuiKey.ReservedForModSuper, + ReservedForModSuper = (int)NativeKey.ReservedForModSuper, /// /// Identifies the NamedKeyEnd presentation key or modifier. /// - NamedKeyEnd = (int)Inno.Native.ImGui.ImGuiKey.NamedKeyEnd, + NamedKeyEnd = (int)NativeKey.NamedKeyEnd, /// /// Identifies the NamedKeyCount presentation key or modifier. /// - NamedKeyCount = (int)Inno.Native.ImGui.ImGuiKey.NamedKeyCount, + NamedKeyCount = (int)NativeKey.NamedKeyCount, /// /// Identifies the ImGuiModNone presentation key or modifier. /// - ImGuiModNone = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModNone, + ImGuiModNone = (int)NativeKey.ImGuiModNone, /// /// Identifies the ImGuiModCtrl presentation key or modifier. /// - ImGuiModCtrl = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModCtrl, + ImGuiModCtrl = (int)NativeKey.ImGuiModCtrl, /// /// Identifies the ImGuiModShift presentation key or modifier. /// - ImGuiModShift = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModShift, + ImGuiModShift = (int)NativeKey.ImGuiModShift, /// /// Identifies the ImGuiModAlt presentation key or modifier. /// - ImGuiModAlt = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModAlt, + ImGuiModAlt = (int)NativeKey.ImGuiModAlt, /// /// Identifies the ImGuiModSuper presentation key or modifier. /// - ImGuiModSuper = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModSuper, + ImGuiModSuper = (int)NativeKey.ImGuiModSuper, /// /// Identifies the ImGuiModMask presentation key or modifier. /// - ImGuiModMask = (int)Inno.Native.ImGui.ImGuiKey.ImGuiModMask + ImGuiModMask = (int)NativeKey.ImGuiModMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs index bc0c575a4..a10723cab 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseButton.cs @@ -1,5 +1,7 @@ using System; +using NativeMouseButton = Inno.Native.ImGui.ImGuiMouseButton; + namespace Inno.Editor.ImGui; /// @@ -10,17 +12,17 @@ public enum ImGuiMouseButton : int /// /// Selects the left presentation behavior. /// - Left = (int)Inno.Native.ImGui.ImGuiMouseButton.Left, + Left = (int)NativeMouseButton.Left, /// /// Selects the right presentation behavior. /// - Right = (int)Inno.Native.ImGui.ImGuiMouseButton.Right, + Right = (int)NativeMouseButton.Right, /// /// Selects the middle presentation behavior. /// - Middle = (int)Inno.Native.ImGui.ImGuiMouseButton.Middle, + Middle = (int)NativeMouseButton.Middle, /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiMouseButton.Count + Count = (int)NativeMouseButton.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs index dc05ca6b4..76affeb48 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiMouseCursor.cs @@ -1,5 +1,7 @@ using System; +using NativeMouseCursor = Inno.Native.ImGui.ImGuiMouseCursor; + namespace Inno.Editor.ImGui; /// @@ -10,53 +12,53 @@ public enum ImGuiMouseCursor : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiMouseCursor.None, + None = (int)NativeMouseCursor.None, /// /// Selects the arrow presentation behavior. /// - Arrow = (int)Inno.Native.ImGui.ImGuiMouseCursor.Arrow, + Arrow = (int)NativeMouseCursor.Arrow, /// /// Selects the text input presentation behavior. /// - TextInput = (int)Inno.Native.ImGui.ImGuiMouseCursor.TextInput, + TextInput = (int)NativeMouseCursor.TextInput, /// /// Selects the resize all presentation behavior. /// - ResizeAll = (int)Inno.Native.ImGui.ImGuiMouseCursor.ResizeAll, + ResizeAll = (int)NativeMouseCursor.ResizeAll, /// /// Selects the resize ns presentation behavior. /// - ResizeNs = (int)Inno.Native.ImGui.ImGuiMouseCursor.ResizeNs, + ResizeNs = (int)NativeMouseCursor.ResizeNs, /// /// Selects the resize ew presentation behavior. /// - ResizeEw = (int)Inno.Native.ImGui.ImGuiMouseCursor.ResizeEw, + ResizeEw = (int)NativeMouseCursor.ResizeEw, /// /// Selects the resize nesw presentation behavior. /// - ResizeNesw = (int)Inno.Native.ImGui.ImGuiMouseCursor.ResizeNesw, + ResizeNesw = (int)NativeMouseCursor.ResizeNesw, /// /// Selects the resize nwse presentation behavior. /// - ResizeNwse = (int)Inno.Native.ImGui.ImGuiMouseCursor.ResizeNwse, + ResizeNwse = (int)NativeMouseCursor.ResizeNwse, /// /// Selects the hand presentation behavior. /// - Hand = (int)Inno.Native.ImGui.ImGuiMouseCursor.Hand, + Hand = (int)NativeMouseCursor.Hand, /// /// Selects the wait presentation behavior. /// - Wait = (int)Inno.Native.ImGui.ImGuiMouseCursor.Wait, + Wait = (int)NativeMouseCursor.Wait, /// /// Selects the progress presentation behavior. /// - Progress = (int)Inno.Native.ImGui.ImGuiMouseCursor.Progress, + Progress = (int)NativeMouseCursor.Progress, /// /// Selects the not allowed presentation behavior. /// - NotAllowed = (int)Inno.Native.ImGui.ImGuiMouseCursor.NotAllowed, + NotAllowed = (int)NativeMouseCursor.NotAllowed, /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiMouseCursor.Count + Count = (int)NativeMouseCursor.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs index 91d52d6d3..18192ac2b 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiPopupFlags.cs @@ -1,5 +1,7 @@ using System; +using NativePopupFlags = Inno.Native.ImGui.ImGuiPopupFlags; + namespace Inno.Editor.ImGui; /// @@ -11,53 +13,53 @@ public enum ImGuiPopupFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiPopupFlags.None, + None = (int)NativePopupFlags.None, /// /// For BeginPopupContext*(): open on Left Mouse release. Only one button allowed! /// - MouseButtonLeft = (int)Inno.Native.ImGui.ImGuiPopupFlags.MouseButtonLeft, + MouseButtonLeft = (int)NativePopupFlags.MouseButtonLeft, /// /// For BeginPopupContext*(): open on Right Mouse release. Only one button allowed! (default) /// - MouseButtonRight = (int)Inno.Native.ImGui.ImGuiPopupFlags.MouseButtonRight, + MouseButtonRight = (int)NativePopupFlags.MouseButtonRight, /// /// For BeginPopupContext*(): open on Middle Mouse release. Only one button allowed! /// - MouseButtonMiddle = (int)Inno.Native.ImGui.ImGuiPopupFlags.MouseButtonMiddle, + MouseButtonMiddle = (int)NativePopupFlags.MouseButtonMiddle, /// /// For OpenPopup*(), BeginPopupContext*(): don't reopen same popup if already open (won't reposition, won't reinitialize navigation) /// - NoReopen = (int)Inno.Native.ImGui.ImGuiPopupFlags.NoReopen, + NoReopen = (int)NativePopupFlags.NoReopen, /// /// For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack /// - NoOpenOverExistingPopup = (int)Inno.Native.ImGui.ImGuiPopupFlags.NoOpenOverExistingPopup, + NoOpenOverExistingPopup = (int)NativePopupFlags.NoOpenOverExistingPopup, /// /// For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space /// - NoOpenOverItems = (int)Inno.Native.ImGui.ImGuiPopupFlags.NoOpenOverItems, + NoOpenOverItems = (int)NativePopupFlags.NoOpenOverItems, /// /// For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. /// - AnyPopupId = (int)Inno.Native.ImGui.ImGuiPopupFlags.AnyPopupId, + AnyPopupId = (int)NativePopupFlags.AnyPopupId, /// /// For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) /// - AnyPopupLevel = (int)Inno.Native.ImGui.ImGuiPopupFlags.AnyPopupLevel, + AnyPopupLevel = (int)NativePopupFlags.AnyPopupLevel, /// /// Selects the any popup presentation behavior. /// - AnyPopup = (int)Inno.Native.ImGui.ImGuiPopupFlags.AnyPopup, + AnyPopup = (int)NativePopupFlags.AnyPopup, /// /// Selects the mouse button shift presentation behavior. /// - MouseButtonShift = (int)Inno.Native.ImGui.ImGuiPopupFlags.MouseButtonShift, + MouseButtonShift = (int)NativePopupFlags.MouseButtonShift, /// /// Selects the mouse button mask presentation behavior. /// - MouseButtonMask = (int)Inno.Native.ImGui.ImGuiPopupFlags.MouseButtonMask, + MouseButtonMask = (int)NativePopupFlags.MouseButtonMask, /// /// Selects the invalid mask presentation behavior. /// - InvalidMask = (int)Inno.Native.ImGui.ImGuiPopupFlags.InvalidMask + InvalidMask = (int)NativePopupFlags.InvalidMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs index fd2ffdee7..a2adde01d 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSelectableFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeSelectableFlags = Inno.Native.ImGui.ImGuiSelectableFlags; + namespace Inno.Editor.ImGui; /// @@ -11,33 +13,33 @@ public enum ImGuiSelectableFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiSelectableFlags.None, + None = (int)NativeSelectableFlags.None, /// /// Clicking this doesn't close parent popup window (overrides ImGuiItemFlags_AutoClosePopups) /// - NoAutoClosePopups = (int)Inno.Native.ImGui.ImGuiSelectableFlags.NoAutoClosePopups, + NoAutoClosePopups = (int)NativeSelectableFlags.NoAutoClosePopups, /// /// Frame will span all columns of its container table (text will still fit in current column) /// - SpanAllColumns = (int)Inno.Native.ImGui.ImGuiSelectableFlags.SpanAllColumns, + SpanAllColumns = (int)NativeSelectableFlags.SpanAllColumns, /// /// Generate press events on double clicks too /// - AllowDoubleClick = (int)Inno.Native.ImGui.ImGuiSelectableFlags.AllowDoubleClick, + AllowDoubleClick = (int)NativeSelectableFlags.AllowDoubleClick, /// /// Cannot be selected, display grayed out text /// - Disabled = (int)Inno.Native.ImGui.ImGuiSelectableFlags.Disabled, + Disabled = (int)NativeSelectableFlags.Disabled, /// /// (WIP) Hit testing to allow subsequent widgets to overlap this one /// - AllowOverlap = (int)Inno.Native.ImGui.ImGuiSelectableFlags.AllowOverlap, + AllowOverlap = (int)NativeSelectableFlags.AllowOverlap, /// /// Make the item be displayed as if it is hovered /// - Highlight = (int)Inno.Native.ImGui.ImGuiSelectableFlags.Highlight, + Highlight = (int)NativeSelectableFlags.Highlight, /// /// Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block. /// - SelectOnNav = (int)Inno.Native.ImGui.ImGuiSelectableFlags.SelectOnNav + SelectOnNav = (int)NativeSelectableFlags.SelectOnNav } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs index 08715d4a0..7d52dfc5c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiSliderFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeSliderFlags = Inno.Native.ImGui.ImGuiSliderFlags; + namespace Inno.Editor.ImGui; /// @@ -11,45 +13,45 @@ public enum ImGuiSliderFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiSliderFlags.None, + None = (int)NativeSliderFlags.None, /// /// Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. /// - Logarithmic = (int)Inno.Native.ImGui.ImGuiSliderFlags.Logarithmic, + Logarithmic = (int)NativeSliderFlags.Logarithmic, /// /// Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). /// - NoRoundToFormat = (int)Inno.Native.ImGui.ImGuiSliderFlags.NoRoundToFormat, + NoRoundToFormat = (int)NativeSliderFlags.NoRoundToFormat, /// /// Disable Ctrl+Click or Enter key allowing to input text directly into the widget. /// - NoInput = (int)Inno.Native.ImGui.ImGuiSliderFlags.NoInput, + NoInput = (int)NativeSliderFlags.NoInput, /// /// Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now. /// - WrapAround = (int)Inno.Native.ImGui.ImGuiSliderFlags.WrapAround, + WrapAround = (int)NativeSliderFlags.WrapAround, /// /// Clamp value to min/max bounds when input manually with Ctrl+Click. By default Ctrl+Click allows going out of bounds. /// - ClampOnInput = (int)Inno.Native.ImGui.ImGuiSliderFlags.ClampOnInput, + ClampOnInput = (int)NativeSliderFlags.ClampOnInput, /// /// Clamp even if min==max==0.0f. Otherwise due to legacy reason DragXXX functions don't clamp with those values. When your clamping limits are dynamic you almost always want to use it. /// - ClampZeroRange = (int)Inno.Native.ImGui.ImGuiSliderFlags.ClampZeroRange, + ClampZeroRange = (int)NativeSliderFlags.ClampZeroRange, /// /// Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. /// - NoSpeedTweaks = (int)Inno.Native.ImGui.ImGuiSliderFlags.NoSpeedTweaks, + NoSpeedTweaks = (int)NativeSliderFlags.NoSpeedTweaks, /// /// DragScalarN(), SliderScalarN(): Draw R/G/B/A color markers on each component. /// - ColorMarkers = (int)Inno.Native.ImGui.ImGuiSliderFlags.ColorMarkers, + ColorMarkers = (int)NativeSliderFlags.ColorMarkers, /// /// Selects the always clamp presentation behavior. /// - AlwaysClamp = (int)Inno.Native.ImGui.ImGuiSliderFlags.AlwaysClamp, + AlwaysClamp = (int)NativeSliderFlags.AlwaysClamp, /// /// Selects the invalid mask presentation behavior. /// - InvalidMask = (int)Inno.Native.ImGui.ImGuiSliderFlags.InvalidMask + InvalidMask = (int)NativeSliderFlags.InvalidMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs index 2b333d75a..87b6ea40e 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiStyleVar.cs @@ -1,5 +1,7 @@ using System; +using NativeStyleVar = Inno.Native.ImGui.ImGuiStyleVar; + namespace Inno.Editor.ImGui; /// @@ -10,169 +12,169 @@ public enum ImGuiStyleVar : int /// /// Selects the alpha presentation behavior. /// - Alpha = (int)Inno.Native.ImGui.ImGuiStyleVar.Alpha, + Alpha = (int)NativeStyleVar.Alpha, /// /// Selects the disabled alpha presentation behavior. /// - DisabledAlpha = (int)Inno.Native.ImGui.ImGuiStyleVar.DisabledAlpha, + DisabledAlpha = (int)NativeStyleVar.DisabledAlpha, /// /// Selects the window padding presentation behavior. /// - WindowPadding = (int)Inno.Native.ImGui.ImGuiStyleVar.WindowPadding, + WindowPadding = (int)NativeStyleVar.WindowPadding, /// /// Selects the window rounding presentation behavior. /// - WindowRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.WindowRounding, + WindowRounding = (int)NativeStyleVar.WindowRounding, /// /// Selects the window border size presentation behavior. /// - WindowBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.WindowBorderSize, + WindowBorderSize = (int)NativeStyleVar.WindowBorderSize, /// /// Selects the window min size presentation behavior. /// - WindowMinSize = (int)Inno.Native.ImGui.ImGuiStyleVar.WindowMinSize, + WindowMinSize = (int)NativeStyleVar.WindowMinSize, /// /// Selects the window title align presentation behavior. /// - WindowTitleAlign = (int)Inno.Native.ImGui.ImGuiStyleVar.WindowTitleAlign, + WindowTitleAlign = (int)NativeStyleVar.WindowTitleAlign, /// /// Selects the child rounding presentation behavior. /// - ChildRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.ChildRounding, + ChildRounding = (int)NativeStyleVar.ChildRounding, /// /// Selects the child border size presentation behavior. /// - ChildBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.ChildBorderSize, + ChildBorderSize = (int)NativeStyleVar.ChildBorderSize, /// /// Selects the popup rounding presentation behavior. /// - PopupRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.PopupRounding, + PopupRounding = (int)NativeStyleVar.PopupRounding, /// /// Selects the popup border size presentation behavior. /// - PopupBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.PopupBorderSize, + PopupBorderSize = (int)NativeStyleVar.PopupBorderSize, /// /// Selects the frame padding presentation behavior. /// - FramePadding = (int)Inno.Native.ImGui.ImGuiStyleVar.FramePadding, + FramePadding = (int)NativeStyleVar.FramePadding, /// /// Selects the frame rounding presentation behavior. /// - FrameRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.FrameRounding, + FrameRounding = (int)NativeStyleVar.FrameRounding, /// /// Selects the frame border size presentation behavior. /// - FrameBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.FrameBorderSize, + FrameBorderSize = (int)NativeStyleVar.FrameBorderSize, /// /// Selects the item spacing presentation behavior. /// - ItemSpacing = (int)Inno.Native.ImGui.ImGuiStyleVar.ItemSpacing, + ItemSpacing = (int)NativeStyleVar.ItemSpacing, /// /// Selects the item inner spacing presentation behavior. /// - ItemInnerSpacing = (int)Inno.Native.ImGui.ImGuiStyleVar.ItemInnerSpacing, + ItemInnerSpacing = (int)NativeStyleVar.ItemInnerSpacing, /// /// Selects the indent spacing presentation behavior. /// - IndentSpacing = (int)Inno.Native.ImGui.ImGuiStyleVar.IndentSpacing, + IndentSpacing = (int)NativeStyleVar.IndentSpacing, /// /// Selects the cell padding presentation behavior. /// - CellPadding = (int)Inno.Native.ImGui.ImGuiStyleVar.CellPadding, + CellPadding = (int)NativeStyleVar.CellPadding, /// /// Selects the scrollbar size presentation behavior. /// - ScrollbarSize = (int)Inno.Native.ImGui.ImGuiStyleVar.ScrollbarSize, + ScrollbarSize = (int)NativeStyleVar.ScrollbarSize, /// /// Selects the scrollbar rounding presentation behavior. /// - ScrollbarRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.ScrollbarRounding, + ScrollbarRounding = (int)NativeStyleVar.ScrollbarRounding, /// /// Selects the scrollbar padding presentation behavior. /// - ScrollbarPadding = (int)Inno.Native.ImGui.ImGuiStyleVar.ScrollbarPadding, + ScrollbarPadding = (int)NativeStyleVar.ScrollbarPadding, /// /// Selects the grab min size presentation behavior. /// - GrabMinSize = (int)Inno.Native.ImGui.ImGuiStyleVar.GrabMinSize, + GrabMinSize = (int)NativeStyleVar.GrabMinSize, /// /// Selects the grab rounding presentation behavior. /// - GrabRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.GrabRounding, + GrabRounding = (int)NativeStyleVar.GrabRounding, /// /// Selects the image rounding presentation behavior. /// - ImageRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.ImageRounding, + ImageRounding = (int)NativeStyleVar.ImageRounding, /// /// Selects the image border size presentation behavior. /// - ImageBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.ImageBorderSize, + ImageBorderSize = (int)NativeStyleVar.ImageBorderSize, /// /// Selects the tab rounding presentation behavior. /// - TabRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.TabRounding, + TabRounding = (int)NativeStyleVar.TabRounding, /// /// Selects the tab border size presentation behavior. /// - TabBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.TabBorderSize, + TabBorderSize = (int)NativeStyleVar.TabBorderSize, /// /// Selects the tab min width base presentation behavior. /// - TabMinWidthBase = (int)Inno.Native.ImGui.ImGuiStyleVar.TabMinWidthBase, + TabMinWidthBase = (int)NativeStyleVar.TabMinWidthBase, /// /// Selects the tab min width shrink presentation behavior. /// - TabMinWidthShrink = (int)Inno.Native.ImGui.ImGuiStyleVar.TabMinWidthShrink, + TabMinWidthShrink = (int)NativeStyleVar.TabMinWidthShrink, /// /// Selects the tab bar border size presentation behavior. /// - TabBarBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.TabBarBorderSize, + TabBarBorderSize = (int)NativeStyleVar.TabBarBorderSize, /// /// Selects the tab bar overline size presentation behavior. /// - TabBarOverlineSize = (int)Inno.Native.ImGui.ImGuiStyleVar.TabBarOverlineSize, + TabBarOverlineSize = (int)NativeStyleVar.TabBarOverlineSize, /// /// Selects the table angled headers angle presentation behavior. /// - TableAngledHeadersAngle = (int)Inno.Native.ImGui.ImGuiStyleVar.TableAngledHeadersAngle, + TableAngledHeadersAngle = (int)NativeStyleVar.TableAngledHeadersAngle, /// /// Selects the table angled headers text align presentation behavior. /// - TableAngledHeadersTextAlign = (int)Inno.Native.ImGui.ImGuiStyleVar.TableAngledHeadersTextAlign, + TableAngledHeadersTextAlign = (int)NativeStyleVar.TableAngledHeadersTextAlign, /// /// Selects the tree lines size presentation behavior. /// - TreeLinesSize = (int)Inno.Native.ImGui.ImGuiStyleVar.TreeLinesSize, + TreeLinesSize = (int)NativeStyleVar.TreeLinesSize, /// /// Selects the tree lines rounding presentation behavior. /// - TreeLinesRounding = (int)Inno.Native.ImGui.ImGuiStyleVar.TreeLinesRounding, + TreeLinesRounding = (int)NativeStyleVar.TreeLinesRounding, /// /// Selects the button text align presentation behavior. /// - ButtonTextAlign = (int)Inno.Native.ImGui.ImGuiStyleVar.ButtonTextAlign, + ButtonTextAlign = (int)NativeStyleVar.ButtonTextAlign, /// /// Selects the selectable text align presentation behavior. /// - SelectableTextAlign = (int)Inno.Native.ImGui.ImGuiStyleVar.SelectableTextAlign, + SelectableTextAlign = (int)NativeStyleVar.SelectableTextAlign, /// /// Selects the separator text border size presentation behavior. /// - SeparatorTextBorderSize = (int)Inno.Native.ImGui.ImGuiStyleVar.SeparatorTextBorderSize, + SeparatorTextBorderSize = (int)NativeStyleVar.SeparatorTextBorderSize, /// /// Selects the separator text align presentation behavior. /// - SeparatorTextAlign = (int)Inno.Native.ImGui.ImGuiStyleVar.SeparatorTextAlign, + SeparatorTextAlign = (int)NativeStyleVar.SeparatorTextAlign, /// /// Selects the separator text padding presentation behavior. /// - SeparatorTextPadding = (int)Inno.Native.ImGui.ImGuiStyleVar.SeparatorTextPadding, + SeparatorTextPadding = (int)NativeStyleVar.SeparatorTextPadding, /// /// Selects the docking separator size presentation behavior. /// - DockingSeparatorSize = (int)Inno.Native.ImGui.ImGuiStyleVar.DockingSeparatorSize, + DockingSeparatorSize = (int)NativeStyleVar.DockingSeparatorSize, /// /// Marks the exclusive end of the valid option range. /// - Count = (int)Inno.Native.ImGui.ImGuiStyleVar.Count + Count = (int)NativeStyleVar.Count } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs index f0501d2a3..88b52b3f6 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabBarFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeTabBarFlags = Inno.Native.ImGui.ImGuiTabBarFlags; + namespace Inno.Editor.ImGui; /// @@ -11,53 +13,53 @@ public enum ImGuiTabBarFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTabBarFlags.None, + None = (int)NativeTabBarFlags.None, /// /// Allow manually dragging tabs to re-order them + New tabs are appended at the end of list /// - Reorderable = (int)Inno.Native.ImGui.ImGuiTabBarFlags.Reorderable, + Reorderable = (int)NativeTabBarFlags.Reorderable, /// /// Automatically select new tabs when they appear /// - AutoSelectNewTabs = (int)Inno.Native.ImGui.ImGuiTabBarFlags.AutoSelectNewTabs, + AutoSelectNewTabs = (int)NativeTabBarFlags.AutoSelectNewTabs, /// /// Disable buttons to open the tab list popup /// - TabListPopupButton = (int)Inno.Native.ImGui.ImGuiTabBarFlags.TabListPopupButton, + TabListPopupButton = (int)NativeTabBarFlags.TabListPopupButton, /// /// Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() & & IsMouseClicked(2)) *p_open = false. /// - NoCloseWithMiddleMouseButton = (int)Inno.Native.ImGui.ImGuiTabBarFlags.NoCloseWithMiddleMouseButton, + NoCloseWithMiddleMouseButton = (int)NativeTabBarFlags.NoCloseWithMiddleMouseButton, /// /// Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) /// - NoTabListScrollingButtons = (int)Inno.Native.ImGui.ImGuiTabBarFlags.NoTabListScrollingButtons, + NoTabListScrollingButtons = (int)NativeTabBarFlags.NoTabListScrollingButtons, /// /// Disable tooltips when hovering a tab /// - NoTooltip = (int)Inno.Native.ImGui.ImGuiTabBarFlags.NoTooltip, + NoTooltip = (int)NativeTabBarFlags.NoTooltip, /// /// Draw selected overline markers over selected tab /// - DrawSelectedOverline = (int)Inno.Native.ImGui.ImGuiTabBarFlags.DrawSelectedOverline, + DrawSelectedOverline = (int)NativeTabBarFlags.DrawSelectedOverline, /// /// Shrink down tabs when they don't fit, until width is style.TabMinWidthShrink, then enable scrolling buttons. /// - FittingPolicyMixed = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyMixed, + FittingPolicyMixed = (int)NativeTabBarFlags.FittingPolicyMixed, /// /// Shrink down tabs when they don't fit /// - FittingPolicyShrink = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyShrink, + FittingPolicyShrink = (int)NativeTabBarFlags.FittingPolicyShrink, /// /// Enable scrolling buttons when tabs don't fit /// - FittingPolicyScroll = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyScroll, + FittingPolicyScroll = (int)NativeTabBarFlags.FittingPolicyScroll, /// /// Selects the fitting policy mask presentation behavior. /// - FittingPolicyMask = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyMask, + FittingPolicyMask = (int)NativeTabBarFlags.FittingPolicyMask, /// /// Selects the fitting policy default presentation behavior. /// - FittingPolicyDefault = (int)Inno.Native.ImGui.ImGuiTabBarFlags.FittingPolicyDefault + FittingPolicyDefault = (int)NativeTabBarFlags.FittingPolicyDefault } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs index d270585b0..d22af2db9 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTabItemFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeTabItemFlags = Inno.Native.ImGui.ImGuiTabItemFlags; + namespace Inno.Editor.ImGui; /// @@ -11,41 +13,41 @@ public enum ImGuiTabItemFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTabItemFlags.None, + None = (int)NativeTabItemFlags.None, /// /// Display a dot next to the title + set ImGuiTabItemFlags_NoAssumedClosure. /// - UnsavedDocument = (int)Inno.Native.ImGui.ImGuiTabItemFlags.UnsavedDocument, + UnsavedDocument = (int)NativeTabItemFlags.UnsavedDocument, /// /// Trigger flag to programmatically make the tab selected when calling BeginTabItem() /// - SetSelected = (int)Inno.Native.ImGui.ImGuiTabItemFlags.SetSelected, + SetSelected = (int)NativeTabItemFlags.SetSelected, /// /// Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() & & IsMouseClicked(2)) *p_open = false. /// - NoCloseWithMiddleMouseButton = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoCloseWithMiddleMouseButton, + NoCloseWithMiddleMouseButton = (int)NativeTabItemFlags.NoCloseWithMiddleMouseButton, /// /// Don't call PushID()/PopID() on BeginTabItem()/EndTabItem() /// - NoPushId = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoPushId, + NoPushId = (int)NativeTabItemFlags.NoPushId, /// /// Disable tooltip for the given tab /// - NoTooltip = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoTooltip, + NoTooltip = (int)NativeTabItemFlags.NoTooltip, /// /// Disable reordering this tab or having another tab cross over this tab /// - NoReorder = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoReorder, + NoReorder = (int)NativeTabItemFlags.NoReorder, /// /// Enforce the tab position to the left of the tab bar (after the tab list popup button) /// - Leading = (int)Inno.Native.ImGui.ImGuiTabItemFlags.Leading, + Leading = (int)NativeTabItemFlags.Leading, /// /// Enforce the tab position to the right of the tab bar (before the scrolling buttons) /// - Trailing = (int)Inno.Native.ImGui.ImGuiTabItemFlags.Trailing, + Trailing = (int)NativeTabItemFlags.Trailing, /// /// Tab is selected when trying to close + closure is not immediately assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. /// - NoAssumedClosure = (int)Inno.Native.ImGui.ImGuiTabItemFlags.NoAssumedClosure + NoAssumedClosure = (int)NativeTabItemFlags.NoAssumedClosure } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs index 580b5379d..1852ec27a 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableBgTarget.cs @@ -1,5 +1,7 @@ using System; +using NativeTableBgTarget = Inno.Native.ImGui.ImGuiTableBgTarget; + namespace Inno.Editor.ImGui; /// @@ -10,17 +12,17 @@ public enum ImGuiTableBgTarget : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTableBgTarget.None, + None = (int)NativeTableBgTarget.None, /// /// Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) /// - RowBg0 = (int)Inno.Native.ImGui.ImGuiTableBgTarget.RowBg0, + RowBg0 = (int)NativeTableBgTarget.RowBg0, /// /// Set row background color 1 (generally used for selection marking) /// - RowBg1 = (int)Inno.Native.ImGui.ImGuiTableBgTarget.RowBg1, + RowBg1 = (int)NativeTableBgTarget.RowBg1, /// /// Set cell background color (top-most color) /// - CellBg = (int)Inno.Native.ImGui.ImGuiTableBgTarget.CellBg + CellBg = (int)NativeTableBgTarget.CellBg } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs index b3c41f574..578e6f21e 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableColumnFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeTableColumnFlags = Inno.Native.ImGui.ImGuiTableColumnFlags; + namespace Inno.Editor.ImGui; /// @@ -11,113 +13,113 @@ public enum ImGuiTableColumnFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.None, + None = (int)NativeTableColumnFlags.None, /// /// Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) /// - Disabled = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.Disabled, + Disabled = (int)NativeTableColumnFlags.Disabled, /// /// Default as a hidden/disabled column. /// - DefaultHide = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.DefaultHide, + DefaultHide = (int)NativeTableColumnFlags.DefaultHide, /// /// Default as a sorting column. /// - DefaultSort = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.DefaultSort, + DefaultSort = (int)NativeTableColumnFlags.DefaultSort, /// /// Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). /// - WidthStretch = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.WidthStretch, + WidthStretch = (int)NativeTableColumnFlags.WidthStretch, /// /// Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). /// - WidthFixed = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.WidthFixed, + WidthFixed = (int)NativeTableColumnFlags.WidthFixed, /// /// Disable manual resizing. /// - NoResize = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoResize, + NoResize = (int)NativeTableColumnFlags.NoResize, /// /// Disable manual reordering this column, this will also prevent other columns from crossing over this column. /// - NoReorder = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoReorder, + NoReorder = (int)NativeTableColumnFlags.NoReorder, /// /// Disable ability to hide/disable this column. /// - NoHide = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoHide, + NoHide = (int)NativeTableColumnFlags.NoHide, /// /// Disable clipping for this column (all NoClip columns will render in a same draw command). /// - NoClip = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoClip, + NoClip = (int)NativeTableColumnFlags.NoClip, /// /// Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). /// - NoSort = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoSort, + NoSort = (int)NativeTableColumnFlags.NoSort, /// /// Disable ability to sort in the ascending direction. /// - NoSortAscending = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoSortAscending, + NoSortAscending = (int)NativeTableColumnFlags.NoSortAscending, /// /// Disable ability to sort in the descending direction. /// - NoSortDescending = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoSortDescending, + NoSortDescending = (int)NativeTableColumnFlags.NoSortDescending, /// /// TableHeadersRow() will submit an empty label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. You may append into this cell by calling TableSetColumnIndex() right after the TableHeadersRow() call. /// - NoHeaderLabel = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoHeaderLabel, + NoHeaderLabel = (int)NativeTableColumnFlags.NoHeaderLabel, /// /// Disable header text width contribution to automatic column width. /// - NoHeaderWidth = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoHeaderWidth, + NoHeaderWidth = (int)NativeTableColumnFlags.NoHeaderWidth, /// /// Make the initial sort direction Ascending when first sorting on this column (default). /// - PreferSortAscending = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.PreferSortAscending, + PreferSortAscending = (int)NativeTableColumnFlags.PreferSortAscending, /// /// Make the initial sort direction Descending when first sorting on this column. /// - PreferSortDescending = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.PreferSortDescending, + PreferSortDescending = (int)NativeTableColumnFlags.PreferSortDescending, /// /// Use current Indent value when entering cell (default for column 0). /// - IndentEnable = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IndentEnable, + IndentEnable = (int)NativeTableColumnFlags.IndentEnable, /// /// Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. /// - IndentDisable = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IndentDisable, + IndentDisable = (int)NativeTableColumnFlags.IndentDisable, /// /// TableHeadersRow() will submit an angled header row for this column. Note this will add an extra row. /// - AngledHeader = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.AngledHeader, + AngledHeader = (int)NativeTableColumnFlags.AngledHeader, /// /// Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. /// - IsEnabled = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IsEnabled, + IsEnabled = (int)NativeTableColumnFlags.IsEnabled, /// /// Status: is visible == is enabled AND not clipped by scrolling. /// - IsVisible = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IsVisible, + IsVisible = (int)NativeTableColumnFlags.IsVisible, /// /// Status: is currently part of the sort specs /// - IsSorted = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IsSorted, + IsSorted = (int)NativeTableColumnFlags.IsSorted, /// /// Status: is hovered by mouse /// - IsHovered = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IsHovered, + IsHovered = (int)NativeTableColumnFlags.IsHovered, /// /// Selects the width mask presentation behavior. /// - WidthMask = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.WidthMask, + WidthMask = (int)NativeTableColumnFlags.WidthMask, /// /// Selects the indent mask presentation behavior. /// - IndentMask = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.IndentMask, + IndentMask = (int)NativeTableColumnFlags.IndentMask, /// /// Selects the status mask presentation behavior. /// - StatusMask = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.StatusMask, + StatusMask = (int)NativeTableColumnFlags.StatusMask, /// /// Selects the no direct resize presentation behavior. /// - NoDirectResize = (int)Inno.Native.ImGui.ImGuiTableColumnFlags.NoDirectResize + NoDirectResize = (int)NativeTableColumnFlags.NoDirectResize } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs index 086e9ee5c..7450453a1 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeTableFlags = Inno.Native.ImGui.ImGuiTableFlags; + namespace Inno.Editor.ImGui; /// @@ -11,149 +13,149 @@ public enum ImGuiTableFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTableFlags.None, + None = (int)NativeTableFlags.None, /// /// Enable resizing columns. /// - Resizable = (int)Inno.Native.ImGui.ImGuiTableFlags.Resizable, + Resizable = (int)NativeTableFlags.Resizable, /// /// Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) /// - Reorderable = (int)Inno.Native.ImGui.ImGuiTableFlags.Reorderable, + Reorderable = (int)NativeTableFlags.Reorderable, /// /// Enable hiding/disabling columns in context menu. /// - Hideable = (int)Inno.Native.ImGui.ImGuiTableFlags.Hideable, + Hideable = (int)NativeTableFlags.Hideable, /// /// Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. /// - Sortable = (int)Inno.Native.ImGui.ImGuiTableFlags.Sortable, + Sortable = (int)NativeTableFlags.Sortable, /// /// Disable persisting columns order, width, visibility and sort settings in the .ini file. /// - NoSavedSettings = (int)Inno.Native.ImGui.ImGuiTableFlags.NoSavedSettings, + NoSavedSettings = (int)NativeTableFlags.NoSavedSettings, /// /// Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). /// - ContextMenuInBody = (int)Inno.Native.ImGui.ImGuiTableFlags.ContextMenuInBody, + ContextMenuInBody = (int)NativeTableFlags.ContextMenuInBody, /// /// Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) /// - RowBg = (int)Inno.Native.ImGui.ImGuiTableFlags.RowBg, + RowBg = (int)NativeTableFlags.RowBg, /// /// Draw horizontal borders between rows. /// - BordersInnerH = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersInnerH, + BordersInnerH = (int)NativeTableFlags.BordersInnerH, /// /// Draw horizontal borders at the top and bottom. /// - BordersOuterH = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersOuterH, + BordersOuterH = (int)NativeTableFlags.BordersOuterH, /// /// Draw vertical borders between columns. /// - BordersInnerV = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersInnerV, + BordersInnerV = (int)NativeTableFlags.BordersInnerV, /// /// Draw vertical borders on the left and right sides. /// - BordersOuterV = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersOuterV, + BordersOuterV = (int)NativeTableFlags.BordersOuterV, /// /// Draw horizontal borders. /// - BordersH = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersH, + BordersH = (int)NativeTableFlags.BordersH, /// /// Draw vertical borders. /// - BordersV = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersV, + BordersV = (int)NativeTableFlags.BordersV, /// /// Draw inner borders. /// - BordersInner = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersInner, + BordersInner = (int)NativeTableFlags.BordersInner, /// /// Draw outer borders. /// - BordersOuter = (int)Inno.Native.ImGui.ImGuiTableFlags.BordersOuter, + BordersOuter = (int)NativeTableFlags.BordersOuter, /// /// Draw all borders. /// - Borders = (int)Inno.Native.ImGui.ImGuiTableFlags.Borders, + Borders = (int)NativeTableFlags.Borders, /// /// Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style /// - NoBordersInBody = (int)Inno.Native.ImGui.ImGuiTableFlags.NoBordersInBody, + NoBordersInBody = (int)NativeTableFlags.NoBordersInBody, /// /// Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style /// - NoBordersInBodyUntilResize = (int)Inno.Native.ImGui.ImGuiTableFlags.NoBordersInBodyUntilResize, + NoBordersInBodyUntilResize = (int)NativeTableFlags.NoBordersInBodyUntilResize, /// /// Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. /// - SizingFixedFit = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingFixedFit, + SizingFixedFit = (int)NativeTableFlags.SizingFixedFit, /// /// Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible. /// - SizingFixedSame = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingFixedSame, + SizingFixedSame = (int)NativeTableFlags.SizingFixedSame, /// /// Columns default to _WidthStretch with default weights proportional to each columns contents widths. /// - SizingStretchProp = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingStretchProp, + SizingStretchProp = (int)NativeTableFlags.SizingStretchProp, /// /// Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). /// - SizingStretchSame = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingStretchSame, + SizingStretchSame = (int)NativeTableFlags.SizingStretchSame, /// /// Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. /// - NoHostExtendX = (int)Inno.Native.ImGui.ImGuiTableFlags.NoHostExtendX, + NoHostExtendX = (int)NativeTableFlags.NoHostExtendX, /// /// Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. /// - NoHostExtendY = (int)Inno.Native.ImGui.ImGuiTableFlags.NoHostExtendY, + NoHostExtendY = (int)NativeTableFlags.NoHostExtendY, /// /// Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. /// - NoKeepColumnsVisible = (int)Inno.Native.ImGui.ImGuiTableFlags.NoKeepColumnsVisible, + NoKeepColumnsVisible = (int)NativeTableFlags.NoKeepColumnsVisible, /// /// Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. /// - PreciseWidths = (int)Inno.Native.ImGui.ImGuiTableFlags.PreciseWidths, + PreciseWidths = (int)NativeTableFlags.PreciseWidths, /// /// Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). /// - NoClip = (int)Inno.Native.ImGui.ImGuiTableFlags.NoClip, + NoClip = (int)NativeTableFlags.NoClip, /// /// Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. /// - PadOuterX = (int)Inno.Native.ImGui.ImGuiTableFlags.PadOuterX, + PadOuterX = (int)NativeTableFlags.PadOuterX, /// /// Default if BordersOuterV is off. Disable outermost padding. /// - NoPadOuterX = (int)Inno.Native.ImGui.ImGuiTableFlags.NoPadOuterX, + NoPadOuterX = (int)NativeTableFlags.NoPadOuterX, /// /// Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). /// - NoPadInnerX = (int)Inno.Native.ImGui.ImGuiTableFlags.NoPadInnerX, + NoPadInnerX = (int)NativeTableFlags.NoPadInnerX, /// /// Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. /// - ScrollX = (int)Inno.Native.ImGui.ImGuiTableFlags.ScrollX, + ScrollX = (int)NativeTableFlags.ScrollX, /// /// Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. /// - ScrollY = (int)Inno.Native.ImGui.ImGuiTableFlags.ScrollY, + ScrollY = (int)NativeTableFlags.ScrollY, /// /// Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). /// - SortMulti = (int)Inno.Native.ImGui.ImGuiTableFlags.SortMulti, + SortMulti = (int)NativeTableFlags.SortMulti, /// /// Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). /// - SortTristate = (int)Inno.Native.ImGui.ImGuiTableFlags.SortTristate, + SortTristate = (int)NativeTableFlags.SortTristate, /// /// Highlight column headers when hovered (may evolve into a fuller highlight) /// - HighlightHoveredColumn = (int)Inno.Native.ImGui.ImGuiTableFlags.HighlightHoveredColumn, + HighlightHoveredColumn = (int)NativeTableFlags.HighlightHoveredColumn, /// /// Selects the sizing mask presentation behavior. /// - SizingMask = (int)Inno.Native.ImGui.ImGuiTableFlags.SizingMask + SizingMask = (int)NativeTableFlags.SizingMask } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs index b5d5d8db8..7769dc082 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTableRowFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeTableRowFlags = Inno.Native.ImGui.ImGuiTableRowFlags; + namespace Inno.Editor.ImGui; /// @@ -11,9 +13,9 @@ public enum ImGuiTableRowFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTableRowFlags.None, + None = (int)NativeTableRowFlags.None, /// /// Identify header row (set default background color + width of its contents accounted differently for auto column width) /// - Headers = (int)Inno.Native.ImGui.ImGuiTableRowFlags.Headers + Headers = (int)NativeTableRowFlags.Headers } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs index 1558c82f8..2af5dc80c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiTreeNodeFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeTreeNodeFlags = Inno.Native.ImGui.ImGuiTreeNodeFlags; + namespace Inno.Editor.ImGui; /// @@ -11,89 +13,89 @@ public enum ImGuiTreeNodeFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.None, + None = (int)NativeTreeNodeFlags.None, /// /// Draw as selected /// - Selected = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.Selected, + Selected = (int)NativeTreeNodeFlags.Selected, /// /// Draw frame with background (e.g. for CollapsingHeader) /// - Framed = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.Framed, + Framed = (int)NativeTreeNodeFlags.Framed, /// /// Hit testing to allow subsequent widgets to overlap this one /// - AllowOverlap = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.AllowOverlap, + AllowOverlap = (int)NativeTreeNodeFlags.AllowOverlap, /// /// Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack /// - NoTreePushOnOpen = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.NoTreePushOnOpen, + NoTreePushOnOpen = (int)NativeTreeNodeFlags.NoTreePushOnOpen, /// /// Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) /// - NoAutoOpenOnLog = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.NoAutoOpenOnLog, + NoAutoOpenOnLog = (int)NativeTreeNodeFlags.NoAutoOpenOnLog, /// /// Default node to be open /// - DefaultOpen = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.DefaultOpen, + DefaultOpen = (int)NativeTreeNodeFlags.DefaultOpen, /// /// Open on double-click instead of simple click (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. /// - OpenOnDoubleClick = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.OpenOnDoubleClick, + OpenOnDoubleClick = (int)NativeTreeNodeFlags.OpenOnDoubleClick, /// /// Open when clicking on the arrow part (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. /// - OpenOnArrow = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.OpenOnArrow, + OpenOnArrow = (int)NativeTreeNodeFlags.OpenOnArrow, /// /// No collapsing, no arrow (use as a convenience for leaf nodes). /// - Leaf = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.Leaf, + Leaf = (int)NativeTreeNodeFlags.Leaf, /// /// Display a bullet instead of arrow. IMPORTANT: node can still be marked open/close if you don't set the _Leaf flag! /// - Bullet = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.Bullet, + Bullet = (int)NativeTreeNodeFlags.Bullet, /// /// Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding() before the node. /// - FramePadding = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.FramePadding, + FramePadding = (int)NativeTreeNodeFlags.FramePadding, /// /// Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line without using AllowOverlap mode. /// - SpanAvailWidth = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.SpanAvailWidth, + SpanAvailWidth = (int)NativeTreeNodeFlags.SpanAvailWidth, /// /// Extend hit box to the left-most and right-most edges (cover the indent area). /// - SpanFullWidth = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.SpanFullWidth, + SpanFullWidth = (int)NativeTreeNodeFlags.SpanFullWidth, /// /// Narrow hit box + narrow hovering highlight, will only cover the label text. /// - SpanLabelWidth = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.SpanLabelWidth, + SpanLabelWidth = (int)NativeTreeNodeFlags.SpanLabelWidth, /// /// Frame will span all columns of its container table (label will still fit in current column) /// - SpanAllColumns = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.SpanAllColumns, + SpanAllColumns = (int)NativeTreeNodeFlags.SpanAllColumns, /// /// Label will span all columns of its container table /// - LabelSpanAllColumns = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.LabelSpanAllColumns, + LabelSpanAllColumns = (int)NativeTreeNodeFlags.LabelSpanAllColumns, /// /// Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfulfilled Left nav request remaining. /// - NavLeftJumpsToParent = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.NavLeftJumpsToParent, + NavLeftJumpsToParent = (int)NativeTreeNodeFlags.NavLeftJumpsToParent, /// /// Selects the collapsing header presentation behavior. /// - CollapsingHeader = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.CollapsingHeader, + CollapsingHeader = (int)NativeTreeNodeFlags.CollapsingHeader, /// /// No lines drawn /// - DrawLinesNone = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.DrawLinesNone, + DrawLinesNone = (int)NativeTreeNodeFlags.DrawLinesNone, /// /// Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. Faster (for large trees). /// - DrawLinesFull = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.DrawLinesFull, + DrawLinesFull = (int)NativeTreeNodeFlags.DrawLinesFull, /// /// Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). /// - DrawLinesToNodes = (int)Inno.Native.ImGui.ImGuiTreeNodeFlags.DrawLinesToNodes + DrawLinesToNodes = (int)NativeTreeNodeFlags.DrawLinesToNodes } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs index 54b4f4811..74c3fdf89 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Controls/Options/ImGuiWindowFlags.cs @@ -1,5 +1,7 @@ using System; +using NativeWindowFlags = Inno.Native.ImGui.ImGuiWindowFlags; + namespace Inno.Editor.ImGui; /// @@ -11,121 +13,121 @@ public enum ImGuiWindowFlags : int /// /// Uses the ordinary behavior without additional options. /// - None = (int)Inno.Native.ImGui.ImGuiWindowFlags.None, + None = (int)NativeWindowFlags.None, /// /// Disable title-bar /// - NoTitleBar = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoTitleBar, + NoTitleBar = (int)NativeWindowFlags.NoTitleBar, /// /// Disable user resizing with the lower-right grip /// - NoResize = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoResize, + NoResize = (int)NativeWindowFlags.NoResize, /// /// Disable user moving the window /// - NoMove = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoMove, + NoMove = (int)NativeWindowFlags.NoMove, /// /// Disable scrollbars (window can still scroll with mouse or programmatically) /// - NoScrollbar = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoScrollbar, + NoScrollbar = (int)NativeWindowFlags.NoScrollbar, /// /// Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. /// - NoScrollWithMouse = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoScrollWithMouse, + NoScrollWithMouse = (int)NativeWindowFlags.NoScrollWithMouse, /// /// Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node). /// - NoCollapse = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoCollapse, + NoCollapse = (int)NativeWindowFlags.NoCollapse, /// /// Resize every window to its content every frame /// - AlwaysAutoResize = (int)Inno.Native.ImGui.ImGuiWindowFlags.AlwaysAutoResize, + AlwaysAutoResize = (int)NativeWindowFlags.AlwaysAutoResize, /// /// Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). /// - NoBackground = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoBackground, + NoBackground = (int)NativeWindowFlags.NoBackground, /// /// Never load/save settings in .ini file /// - NoSavedSettings = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoSavedSettings, + NoSavedSettings = (int)NativeWindowFlags.NoSavedSettings, /// /// Disable catching mouse, hovering test with pass through. /// - NoMouseInputs = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoMouseInputs, + NoMouseInputs = (int)NativeWindowFlags.NoMouseInputs, /// /// Has a menu-bar /// - MenuBar = (int)Inno.Native.ImGui.ImGuiWindowFlags.MenuBar, + MenuBar = (int)NativeWindowFlags.MenuBar, /// /// Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. /// - HorizontalScrollbar = (int)Inno.Native.ImGui.ImGuiWindowFlags.HorizontalScrollbar, + HorizontalScrollbar = (int)NativeWindowFlags.HorizontalScrollbar, /// /// Disable taking focus when transitioning from hidden to visible state /// - NoFocusOnAppearing = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoFocusOnAppearing, + NoFocusOnAppearing = (int)NativeWindowFlags.NoFocusOnAppearing, /// /// Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) /// - NoBringToFrontOnFocus = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoBringToFrontOnFocus, + NoBringToFrontOnFocus = (int)NativeWindowFlags.NoBringToFrontOnFocus, /// /// Always show vertical scrollbar (even if ContentSize.y < Size.y) /// - AlwaysVerticalScrollbar = (int)Inno.Native.ImGui.ImGuiWindowFlags.AlwaysVerticalScrollbar, + AlwaysVerticalScrollbar = (int)NativeWindowFlags.AlwaysVerticalScrollbar, /// /// Always show horizontal scrollbar (even if ContentSize.x < Size.x) /// - AlwaysHorizontalScrollbar = (int)Inno.Native.ImGui.ImGuiWindowFlags.AlwaysHorizontalScrollbar, + AlwaysHorizontalScrollbar = (int)NativeWindowFlags.AlwaysHorizontalScrollbar, /// /// No keyboard/gamepad navigation within the window /// - NoNavInputs = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoNavInputs, + NoNavInputs = (int)NativeWindowFlags.NoNavInputs, /// /// No focusing toward this window with keyboard/gamepad navigation (e.g. skipped by Ctrl+Tab) /// - NoNavFocus = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoNavFocus, + NoNavFocus = (int)NativeWindowFlags.NoNavFocus, /// /// Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. /// - UnsavedDocument = (int)Inno.Native.ImGui.ImGuiWindowFlags.UnsavedDocument, + UnsavedDocument = (int)NativeWindowFlags.UnsavedDocument, /// /// Disable docking of this window /// - NoDocking = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoDocking, + NoDocking = (int)NativeWindowFlags.NoDocking, /// /// Selects the no nav presentation behavior. /// - NoNav = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoNav, + NoNav = (int)NativeWindowFlags.NoNav, /// /// Selects the no decoration presentation behavior. /// - NoDecoration = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoDecoration, + NoDecoration = (int)NativeWindowFlags.NoDecoration, /// /// Selects the no inputs presentation behavior. /// - NoInputs = (int)Inno.Native.ImGui.ImGuiWindowFlags.NoInputs, + NoInputs = (int)NativeWindowFlags.NoInputs, /// /// Don't use! For internal use by Begin()/NewFrame() /// - DockNodeHost = (int)Inno.Native.ImGui.ImGuiWindowFlags.DockNodeHost, + DockNodeHost = (int)NativeWindowFlags.DockNodeHost, /// /// Don't use! For internal use by BeginChild() /// - ChildWindow = (int)Inno.Native.ImGui.ImGuiWindowFlags.ChildWindow, + ChildWindow = (int)NativeWindowFlags.ChildWindow, /// /// Don't use! For internal use by BeginTooltip() /// - Tooltip = (int)Inno.Native.ImGui.ImGuiWindowFlags.Tooltip, + Tooltip = (int)NativeWindowFlags.Tooltip, /// /// Don't use! For internal use by BeginPopup() /// - Popup = (int)Inno.Native.ImGui.ImGuiWindowFlags.Popup, + Popup = (int)NativeWindowFlags.Popup, /// /// Don't use! For internal use by BeginPopupModal() /// - Modal = (int)Inno.Native.ImGui.ImGuiWindowFlags.Modal, + Modal = (int)NativeWindowFlags.Modal, /// /// Don't use! For internal use by BeginMenu() /// - ChildMenu = (int)Inno.Native.ImGui.ImGuiWindowFlags.ChildMenu + ChildMenu = (int)NativeWindowFlags.ChildMenu } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs index dddf45269..eafb8739c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/EditorDrawList.cs @@ -182,7 +182,8 @@ public void PushClip( Vector2 maximum, bool intersect = true ) { - ImVec2C first = ImGui.ToNative(minimum), last = ImGui.ToNative(maximum); + ImVec2C first = ImGui.ToNative(minimum); + ImVec2C last = ImGui.ToNative(maximum); NativeImGui.Raw.PushClipRect(Resolve(), &first, &last, intersect ? (byte)1 : (byte)0); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs index 5d3c904b3..fd93fff7c 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Drawing/ImGui.Drawing.cs @@ -1,4 +1,7 @@ +using System; using System.Numerics; +using BGCS.Runtime; +using Inno.Native.ImGui; using NativeImGui = Inno.Native.ImGui.ImGui; @@ -57,7 +60,7 @@ public static Vector4 GetStyleColorValue(ImGuiCol color) public static (uint id, Vector2 position) GetViewport() { EditorUiSession.current.EnsureDrawing(); - var viewport = NativeImGui.Raw.GetWindowViewport(); + ImGuiViewport* viewport = NativeImGui.Raw.GetWindowViewport(); return (viewport->ID, FromNative(viewport->Pos)); } @@ -73,10 +76,10 @@ public static (uint id, Vector2 position) GetViewport() public static (float minimumX, float maximumX, float rowMinimum, float rowMaximum) GetTableBounds() { _ = EditorUiSession.current.RequireDrawingFrame(); - var table = NativeImGui.Raw.GetCurrentTable(); + ImGuiTable* table = NativeImGui.Raw.GetCurrentTable(); if (table is null) { - throw new System.InvalidOperationException("A table row layout requires an active table."); + throw new InvalidOperationException("A table row layout requires an active table."); } return (table->OuterRect.Min.X, table->OuterRect.Max.X, table->RowPosY1, table->RowPosY2); } @@ -93,7 +96,7 @@ public static (float minimumX, float maximumX, float rowMinimum, float rowMaximu public static (float minimumX, float maximumX, Vector2 workMaximum, Vector2 padding) GetWindowBounds() { _ = EditorUiSession.current.RequireDrawingFrame(); - var window = NativeImGui.Raw.GetCurrentWindow(); + ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); return (window->InnerRect.Min.X, window->InnerRect.Max.X, FromNative(window->WorkRect.Max), FromNative(window->WindowPadding)); } @@ -109,7 +112,7 @@ public static (float minimumX, float maximumX, Vector2 workMaximum, Vector2 padd public static (Vector2 minimum, Vector2 maximum) GetClipBounds() { _ = EditorUiSession.current.RequireDrawingFrame(); - var clip = NativeImGui.Raw.GetCurrentWindow()->ClipRect; + ImRect clip = NativeImGui.Raw.GetCurrentWindow()->ClipRect; return (FromNative(clip.Min), FromNative(clip.Max)); } @@ -133,12 +136,12 @@ public static (Vector2 minimum, Vector2 maximum) GetClipBounds() public static bool HasDragPayload(string protocol) { EditorUiSession.current.EnsureDrawing(); - var payload = NativeImGui.Raw.GetDragDropPayload(); + ImGuiPayload* payload = NativeImGui.Raw.GetDragDropPayload(); if (payload is null) { return false; } - using var text = BGCS.Runtime.Utf8Codec.EncodeNullTerminated(protocol, allowsNull: false); + using NativeStringLease text = Utf8Codec.EncodeNullTerminated(protocol, allowsNull: false); return NativeImGui.Raw.IsDataType(payload, (sbyte*)text.pointer) != 0; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs index 6a28adf1d..8751649e4 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/ImGui.cs @@ -48,12 +48,12 @@ public static bool Button( /// /// Draws a compact button. /// - /// - /// when the button is activated. - /// /// /// The visible label and optional ImGui identity suffix. /// + /// + /// when the button is activated. + /// public static bool SmallButton(string label) { EditorUiSession.current.EnsureDrawing(); @@ -66,12 +66,12 @@ public static bool SmallButton(string label) /// /// The control label. /// - /// - /// when the value changes. - /// /// /// The checked state, updated when the user toggles the control. /// + /// + /// when the value changes. + /// public static bool Checkbox( string label, ref bool value @@ -152,9 +152,6 @@ public static bool InputTextWithHint( /// /// The control label. /// - /// - /// when the value changes. - /// /// /// The integer displayed by the control and replaced after an accepted edit. /// @@ -167,6 +164,9 @@ public static bool InputTextWithHint( /// /// Text editing options for the numeric field. /// + /// + /// when the value changes. + /// public static bool InputInt( string label, ref int value, @@ -184,12 +184,12 @@ public static bool InputInt( /// /// The control label. /// - /// - /// when the value changes. - /// /// /// The number displayed with three fractional digits and replaced after an accepted edit. /// + /// + /// when the value changes. + /// public static bool InputFloat( string label, ref float value @@ -316,7 +316,7 @@ public static bool ColorEditLinear4( { throw new ArgumentException("Linear RGBA editing requires RGB input storage.", nameof(flags)); } - Vector4 display = new(LinearToSrgb(value.X), LinearToSrgb(value.Y), LinearToSrgb(value.Z), value.W); + var display = new Vector4(LinearToSrgb(value.X), LinearToSrgb(value.Y), LinearToSrgb(value.Z), value.W); Vector4 original = display; if (!ColorEdit4(label, ref display, flags | ImGuiColorEditFlags.InputRgb)) { @@ -343,12 +343,12 @@ public static bool ColorEditLinear4( /// /// Child-region behavior. /// - /// - /// when child contents should be submitted. - /// /// /// Scroll and window policies for the child. /// + /// + /// when child contents should be submitted. + /// public static bool BeginChild( string id, Vector2 size = default, @@ -383,12 +383,12 @@ public static void EndChild() /// /// The requested outer size. /// - /// - /// when table contents should be submitted. - /// /// /// Optional inner scrolling width; zero uses the outer size. /// + /// + /// when table contents should be submitted. + /// public static bool BeginTable( string id, int columns, @@ -513,12 +513,12 @@ public static void EndCombo() /// /// Selectable behavior. /// - /// - /// when the item is activated. - /// /// /// The interaction bounds, or zero for the ordinary content size. /// + /// + /// when the item is activated. + /// public static bool Selectable( string label, bool selected = false, @@ -646,9 +646,7 @@ public static unsafe bool BeginTabItem( string label, ref bool isOpen, ImGuiTabItemFlags flags = ImGuiTabItemFlags.None - ) { - return RawImGui.BeginTabItem(label, ref isOpen, (int)flags); - } + ) => RawImGui.BeginTabItem(label, ref isOpen, (int)flags); /// /// Ends the current tab item. @@ -1034,12 +1032,12 @@ public static Vector2 GetItemMaximum() /// /// Measures text using the current font. /// - /// - /// The measured width and height. - /// /// /// The text text validated by the measure text operation. /// + /// + /// The measured width and height. + /// public static Vector2 MeasureText(string text) { EditorUiSession.current.EnsureDrawing(); @@ -1170,12 +1168,12 @@ public static Vector2 GetMouseDragDelta( /// /// Converts a floating-point RGBA color to Dear ImGui packed color order. /// - /// - /// The packed color value. - /// /// /// The color consumed by to packed color; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The packed color value. + /// public static uint ToPackedColor(Vector4 color) { EditorUiSession.current.EnsureDrawing(); @@ -1293,7 +1291,10 @@ public static void DrawCubicCurve( float thickness = 1f ) { EditorUiSession.current.EnsureDrawing(); - ImVec2C a = ToNative(start), b = ToNative(firstControl), c = ToNative(secondControl), d = ToNative(end); + ImVec2C a = ToNative(start); + ImVec2C b = ToNative(firstControl); + ImVec2C c = ToNative(secondControl); + ImVec2C d = ToNative(end); RawImGui.Raw.AddBezierCubic(RawImGui.Raw.GetWindowDrawList(), &a, &b, &c, &d, color, thickness, 0); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs index 9b2887d60..e7750d56f 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Properties/ScriptingApi.cs @@ -10,7 +10,7 @@ [assembly: ScriptingApiExport(typeof(EditorPalette), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorStyleMetrics), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(ListNavigationResult), ScriptingApiScope.Editor)] -[assembly: ScriptingApiExport(typeof(Inno.Editor.ImGui.ImGui), ScriptingApiScope.Editor)] +[assembly: ScriptingApiExport(typeof(ImGui), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(EditorWidget), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(InlineRenameResult), ScriptingApiScope.Editor)] [assembly: ScriptingApiExport(typeof(TreeNodeDrawContext), ScriptingApiScope.Editor)] diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs index cf8f11468..3f0e0c28f 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorGameInputCapture.cs @@ -116,14 +116,14 @@ public uint CompleteFrame() /// /// A routed event or a synthetic focus reset, or null when the Game View must not receive input. /// + /// + /// Thrown when the event is null. + /// /// /// A globally consumed key, button, focus or close release is not replayed to the game. /// It returns a new focus-reset event so previously held input is released before simulation. /// Consumed pointer movement still updates hit-test bounds without reaching the game backend. /// - /// - /// Thrown when the event is null. - /// public Event? Route(Event evnt) { ArgumentNullException.ThrowIfNull(evnt); @@ -209,7 +209,7 @@ uint windowId private Event? RouteMove(MouseMovedEvent moved) { - Vector2 local = new(moved.x - m_origin.X, moved.y - m_origin.Y); + var local = new Vector2(moved.x - m_origin.X, moved.y - m_origin.Y); return m_pointerInside || m_pressedButtons.Count > 0 ? moved.WithPosition(local.X, local.Y) : null; @@ -217,7 +217,7 @@ uint windowId private void UpdatePointerBounds(MouseMovedEvent moved) { - Vector2 local = new(moved.x - m_origin.X, moved.y - m_origin.Y); + var local = new Vector2(moved.x - m_origin.X, moved.y - m_origin.Y); m_pointerInside = m_hovered && local.X >= 0f && local.Y >= 0f && local.X < m_size.X && local.Y < m_size.Y; } @@ -232,8 +232,5 @@ private void UpdatePointerBounds(MouseMovedEvent moved) return pressed; } - private Event? RouteRelease(MouseButtonReleasedEvent released) - { - return m_pressedButtons.Remove(released.button) ? released : null; - } + private Event? RouteRelease(MouseButtonReleasedEvent released) => m_pressedButtons.Remove(released.button) ? released : null; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs index 3d374103a..86115786d 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorMenuRenderer.cs @@ -8,6 +8,7 @@ using EditorUI = Inno.Editor.ImGui.EditorUiSession; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeMouseButton = Inno.Native.ImGui.ImGuiMouseButton; namespace Inno.Editor.ImGui; @@ -19,11 +20,14 @@ public sealed unsafe class EditorMenuRenderer private readonly EditorUiSession m_session; private readonly Dictionary<(string Owner, uint Popup), string> m_contextSearches = []; - internal EditorMenuRenderer(EditorUiSession session) => m_session = session; + internal EditorMenuRenderer(EditorUiSession session) + { + m_session = session; + } internal void RetireOwner(string owner) { - foreach (var key in m_contextSearches.Keys.Where(value => value.Owner == owner).ToArray()) + foreach ((string Owner, uint Popup) key in m_contextSearches.Keys.Where(value => value.Owner == owner).ToArray()) { m_contextSearches.Remove(key); } @@ -235,13 +239,13 @@ IReadOnlyList sections private bool ShouldResolveItemContextMenu(string id) => NativeImGui.IsPopupOpen(id) || NativeImGui.IsItemHovered() - && NativeImGui.IsMouseReleased((int)(Inno.Native.ImGui.ImGuiMouseButton.Right)); + && NativeImGui.IsMouseReleased((int)(NativeMouseButton.Right)); private bool ShouldResolveWindowContextMenu(string id) => NativeImGui.IsPopupOpen(id) || NativeImGui.IsWindowHovered() && !NativeImGui.IsAnyItemHovered() - && NativeImGui.IsMouseReleased((int)(Inno.Native.ImGui.ImGuiMouseButton.Right)); + && NativeImGui.IsMouseReleased((int)(NativeMouseButton.Right)); /// /// Draws the complete editor main menu bar for the supplied menu context. diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs index 4b590ceb5..645716303 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorModalRenderer.cs @@ -55,18 +55,18 @@ EditorContext context // The runtime established this session; revalidate below after invoking extension preparation. string popupId = $"{title}##{id}"; ImGuiViewport* viewport = NativeImGui.Raw.GetMainViewport(); - var style = NativeImGui.Raw.GetStyle(); + ImGuiStyle* style = NativeImGui.Raw.GetStyle(); Vector2 workSize = Vector2.Max(Vector2.One, ImGui.FromNative(viewport->WorkSize)); Vector2 padding = ImGui.FromNative(style->WindowPadding); Vector2 bounds = Vector2.Max(Vector2.One, workSize - padding * 2f); - Vector2 maximumSize = new(MathF.Floor(bounds.X), MathF.Floor(bounds.Y)); + var maximumSize = new Vector2(MathF.Floor(bounds.X), MathF.Floor(bounds.Y)); Vector2 minimumSize = Vector2.Min(presentation.minimumSize * EditorUI.current.widgets.style.zoom, maximumSize); Vector2 initialSize = presentation.initialSize * EditorUI.current.widgets.style.zoom; if (presentation.canResize && initialSize.Y <= 0f) { using NativeStringLease nativeTitle = Utf8Codec.EncodeNullTerminated(popupId, allowsNull: false); ImGuiWindow* existing = NativeImGui.Raw.FindWindowByName((sbyte*)nativeTitle.pointer); - if (existing != null && existing->WasActive != 0) + if (existing is not null && existing->WasActive != 0) { initialSize = ImGui.FromNative(existing->SizeFull); } @@ -79,7 +79,7 @@ EditorContext context ) ); float decorations = NativeImGui.GetFrameHeight(); - Vector2 available = new( + var available = new Vector2( MathF.Max(1f, width - padding.X * 2f), MathF.Max(1f, (initialSize.Y > 0f ? MathF.Min(initialSize.Y, maximumSize.Y) : maximumSize.Y) - padding.Y * 2f - decorations) ); @@ -108,7 +108,7 @@ EditorContext context { height += style->ScrollbarSize; } - Vector2 windowSize = new(width, MathF.Ceiling(Math.Clamp(height, MathF.Max(1f, minimumSize.Y), maximumSize.Y))); + var windowSize = new Vector2(width, MathF.Ceiling(Math.Clamp(height, MathF.Max(1f, minimumSize.Y), maximumSize.Y))); Vector2 center = ImGui.FromNative(viewport->WorkPos) + workSize * 0.5f; if (presentation.blocksInteraction) { diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs index f8009343a..5f2e17e52 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiInput.cs @@ -55,15 +55,15 @@ public readonly struct EditorUiInput internal unsafe EditorUiInput(ImGuiIO* io) { - alt = io->KeyAlt != 0; + this.alt = io->KeyAlt != 0; bool swapsModifiers = io->ConfigMacOsxBehaviors != 0; - control = (swapsModifiers ? io->KeySuper : io->KeyCtrl) != 0; - shift = io->KeyShift != 0; - super = (swapsModifiers ? io->KeyCtrl : io->KeySuper) != 0; - wantsText = io->WantTextInput != 0; - mouseDelta = ImGui.FromNative(io->MouseDelta); - framebufferScale = ImGui.FromNative(io->DisplayFramebufferScale); - wheel = io->MouseWheel; - deltaTime = io->DeltaTime; + this.control = (swapsModifiers ? io->KeySuper : io->KeyCtrl) != 0; + this.shift = io->KeyShift != 0; + this.super = (swapsModifiers ? io->KeyCtrl : io->KeySuper) != 0; + this.wantsText = io->WantTextInput != 0; + this.mouseDelta = ImGui.FromNative(io->MouseDelta); + this.framebufferScale = ImGui.FromNative(io->DisplayFramebufferScale); + this.wheel = io->MouseWheel; + this.deltaTime = io->DeltaTime; } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs index 3ad147f9c..493b57fa8 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorUiSession.cs @@ -2,6 +2,7 @@ using Inno.Core.Events; using Inno.Editor.Interactions; using Inno.Native.ImGui; +using Inno.Scripting.Api; using EditorControls = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; using NativeImGui = Inno.Native.ImGui.ImGui; @@ -30,8 +31,8 @@ public sealed unsafe class EditorUiSession : IDisposable /// public EditorUiSession() { - widgets = new EditorControls(this); - menus = new EditorMenuRenderer(this); + this.widgets = new EditorControls(this); + this.menus = new EditorMenuRenderer(this); } /// @@ -51,7 +52,7 @@ public static EditorUiSession current /// /// Gets the menu presenter whose search state belongs exclusively to this session. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public EditorMenuRenderer menus { get; } /// @@ -232,7 +233,7 @@ private sealed class Scope( { private bool m_disposed; - /// + /// public void Dispose() { owner.EnsureOwner(); @@ -258,7 +259,7 @@ private sealed class OwnerScope( { private bool m_disposed; - /// + /// public void Dispose() { if (m_disposed) diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs index faf70a31f..e3b44b163 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/ImGuiEditorRuntime.cs @@ -13,6 +13,7 @@ using Inno.Native.ImGui; using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using NativeFocusedFlags = Inno.Native.ImGui.ImGuiFocusedFlags; using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui; @@ -120,13 +121,13 @@ public void SaveState() /// Freezes automatic extension-state persistence and writes the final project state before editor /// modules begin shutting down. /// + /// + /// Thrown after this runtime has been disposed. + /// /// /// This operation is idempotent and prevents module teardown from overwriting the saved /// module sections with transient empty state. /// - /// - /// Thrown after this runtime has been disposed. - /// public void PrepareShutdown() { using IDisposable uiScope = m_ui.Enter(); @@ -203,7 +204,7 @@ private void DrawDockSpace() uint hostId = ImGui.HashNativeId($"WindowOverViewport_{viewport->ID:X8}"); m_dockspaceId = ImGui.HashNativeId("DockSpace", hostId); ImGuiDockNode* loaded = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceId); - if (loaded != null) + if (loaded is not null) { ResizeDockSplits(loaded, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); } @@ -212,7 +213,7 @@ private void DrawDockSpace() && (MathF.Abs(size.X - m_dockspaceSize.X) >= 0.5f || MathF.Abs(size.Y - m_dockspaceSize.Y) >= 0.5f) ) { ImGuiDockNode* root = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceId); - if (root != null) + if (root is not null) { ResizeDockSplits(root, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); } @@ -236,7 +237,7 @@ private void DrawDockSpace() if (m_dockspaceSize == Vector2.Zero) { ImGuiDockNode* root = NativeImGui.Raw.DockBuilderGetNode(m_dockspaceId); - if (root != null) + if (root is not null) { ResizeDockSplits(root, size, style->DockingSeparatorSize, ImGui.FromNative(style->WindowMinSize)); } @@ -253,7 +254,7 @@ Vector2 minimumWindowSize ) { ImGuiDockNode* first = node->ChildNodes[0]; ImGuiDockNode* second = node->ChildNodes[1]; - if (first == null || second == null || node->SplitAxis is not (ImGuiAxis.X or ImGuiAxis.Y)) + if (first is null || second is null || node->SplitAxis is not (ImGuiAxis.X or ImGuiAxis.Y)) { return; } @@ -399,7 +400,7 @@ private void DrawPanels(IReadOnlyList panels) } EditorUI.current.widgets.PanelWindow(extension.title, ref isOpen, () => { - if (extension.Draw(context) && NativeImGui.IsWindowFocused((int)(Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows))) + if (extension.Draw(context) && NativeImGui.IsWindowFocused((int)(NativeFocusedFlags.RootAndChildWindows))) { interactions.For($"panel/{extension.id}", interactions.selection.selectedTarget).Focus(); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs index 4d303eb82..f6b4b64d6 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorPalette.cs @@ -32,7 +32,7 @@ public static unsafe class EditorPalette /// /// Gets soft opacity for tinted container surfaces. /// - public const float opacitySoft = 0.20f; + public const float opacitySoft = 0.2f; /// /// Gets muted opacity for shadows and subdued outlines. @@ -52,7 +52,7 @@ public static unsafe class EditorPalette /// /// Gets prominent opacity for navigation emphasis. /// - public const float opacityProminent = 0.70f; + public const float opacityProminent = 0.7f; /// /// Gets emphasized opacity for borders and interactive grips. @@ -87,7 +87,7 @@ public static unsafe class EditorPalette /// /// Gets disabled text color. /// - public static Vector4 textDisabled { get; } = new(0.58f, 0.60f, 0.64f, opacityOpaque); + public static Vector4 textDisabled { get; } = new(0.58f, 0.6f, 0.64f, opacityOpaque); /// /// Gets the standard error color. @@ -177,12 +177,12 @@ public static unsafe class EditorPalette /// /// Gets the collapsed title background. /// - public static Vector4 titleCollapsed { get; } = new(0.065f, 0.070f, 0.080f, opacityOpaque); + public static Vector4 titleCollapsed { get; } = new(0.065f, 0.07f, 0.08f, opacityOpaque); /// /// Gets the standard scrollbar thumb. /// - public static Vector4 scrollbarGrab { get; } = new(0.30f, 0.32f, 0.36f, opacityEmphasized); + public static Vector4 scrollbarGrab { get; } = new(0.3f, 0.32f, 0.36f, opacityEmphasized); /// /// Gets the hovered scrollbar thumb. @@ -217,17 +217,17 @@ public static unsafe class EditorPalette /// /// Gets the hovered tab color. /// - public static Vector4 tabHovered { get; } = new(0.19f, 0.20f, 0.225f, opacityOpaque); + public static Vector4 tabHovered { get; } = new(0.19f, 0.2f, 0.225f, opacityOpaque); /// /// Gets the selected tab color. /// - public static Vector4 tabSelected { get; } = new(0.17f, 0.176f, 0.20f, opacityOpaque); + public static Vector4 tabSelected { get; } = new(0.17f, 0.176f, 0.2f, opacityOpaque); /// /// Gets the dimmed tab color. /// - public static Vector4 tabDimmed { get; } = new(0.082f, 0.088f, 0.10f, opacityOpaque); + public static Vector4 tabDimmed { get; } = new(0.082f, 0.088f, 0.1f, opacityOpaque); /// /// Gets the selected dimmed tab color. @@ -237,7 +237,7 @@ public static unsafe class EditorPalette /// /// Gets the selected tab overline color. /// - public static Vector4 tabSelectedOverline { get; } = new(0.72f, 0.66f, 0.90f, opacityOpaque); + public static Vector4 tabSelectedOverline { get; } = new(0.72f, 0.66f, 0.9f, opacityOpaque); /// /// Gets the table header background. @@ -292,7 +292,7 @@ public static unsafe class EditorPalette /// /// Gets the persistent target header border. /// - public static Vector4 targetHeaderBorder { get; } = new(0.30f, 0.29f, 0.34f, opacityOpaque); + public static Vector4 targetHeaderBorder { get; } = new(0.3f, 0.29f, 0.34f, opacityOpaque); /// /// Gets card body background. @@ -322,7 +322,7 @@ public static unsafe class EditorPalette /// /// Gets compact control hover color. /// - public static Vector4 compactControlHovered { get; } = new(0.74f, 0.70f, 0.90f, opacityOpaque); + public static Vector4 compactControlHovered { get; } = new(0.74f, 0.7f, 0.9f, opacityOpaque); /// /// Gets the deepest collection background. @@ -337,7 +337,7 @@ public static unsafe class EditorPalette /// /// Gets the alternate collection row background. /// - public static Vector4 collectionRowAlternate { get; } = new(0.135f, 0.144f, 0.160f, opacityOpaque); + public static Vector4 collectionRowAlternate { get; } = new(0.135f, 0.144f, 0.16f, opacityOpaque); /// /// Gets the content field background. @@ -347,7 +347,7 @@ public static unsafe class EditorPalette /// /// Gets the content border. /// - public static Vector4 contentBorder { get; } = new(0.31f, 0.30f, 0.35f, opacityOpaque); + public static Vector4 contentBorder { get; } = new(0.31f, 0.3f, 0.35f, opacityOpaque); /// /// Gets the soft content border. @@ -372,28 +372,28 @@ public static unsafe class EditorPalette /// /// Gets the opaque content accent. /// - public static Vector4 contentAccent { get; } = new(0.50f, 0.45f, 0.62f, opacityOpaque); + public static Vector4 contentAccent { get; } = new(0.5f, 0.45f, 0.62f, opacityOpaque); /// /// Gets a hover treatment derived from a base theme color. /// - /// - /// The base color blended toward the palette text color using the standard hover amount. - /// /// /// The color consumed by get hovered; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The base color blended toward the palette text color using the standard hover amount. + /// public static Vector4 GetHovered(Vector4 color) => Lerp(color, text, 0.16f); /// /// Gets an active treatment derived from a base theme color. /// - /// - /// The base color blended toward the palette text color using the standard active amount. - /// /// /// The color consumed by get active; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The base color blended toward the palette text color using the standard active amount. + /// public static Vector4 GetActive(Vector4 color) => Lerp(color, text, 0.24f); /// @@ -404,22 +404,22 @@ public static unsafe class EditorPalette /// /// Gets X axis color. /// - public static Vector4 axisX { get; } = new(0.76f, 0.20f, 0.22f, opacityOpaque); + public static Vector4 axisX { get; } = new(0.76f, 0.2f, 0.22f, opacityOpaque); /// /// Gets Y axis color. /// - public static Vector4 axisY { get; } = new(0.16f, 0.62f, 0.30f, opacityOpaque); + public static Vector4 axisY { get; } = new(0.16f, 0.62f, 0.3f, opacityOpaque); /// /// Gets Z axis color. /// - public static Vector4 axisZ { get; } = new(0.20f, 0.34f, 0.78f, opacityOpaque); + public static Vector4 axisZ { get; } = new(0.2f, 0.34f, 0.78f, opacityOpaque); /// /// Gets W axis color. /// - public static Vector4 axisW { get; } = new(0.48f, 0.48f, 0.50f, opacityOpaque); + public static Vector4 axisW { get; } = new(0.48f, 0.48f, 0.5f, opacityOpaque); /// /// Linearly interpolates two palette colors using a clamped amount. diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs index 96e8453be..9e0af6d77 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorStyleMetrics.cs @@ -21,12 +21,12 @@ public sealed class EditorStyleMetrics /// /// Defines the largest supported editor UI zoom. /// - public const float C_MAX_ZOOM = 1.50f; + public const float C_MAX_ZOOM = 1.5f; /// /// Defines one keyboard or menu zoom increment. /// - public const float C_ZOOM_STEP = 0.10f; + public const float C_ZOOM_STEP = 0.1f; private readonly WeakReference? m_owner; private float m_requestedZoom = 1f; @@ -149,7 +149,7 @@ public bool SetZoom(float value) /// /// Gets global content scale. /// - public float fontScale => Scale(m_compactMode ? 1.10f : 1.20f); + public float fontScale => Scale(m_compactMode ? 1.1f : 1.2f); /// /// Gets disabled content opacity. @@ -370,7 +370,7 @@ public bool SetZoom(float value) /// /// Gets property label width ratio. /// - public float propertyLabelRatio => 0.40f; + public float propertyLabelRatio => 0.4f; /// /// Gets the default width of searchable editor popups. diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs index 7e3796397..1cd702912 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Styling/EditorUiLayout.cs @@ -50,13 +50,13 @@ public readonly struct EditorUiLayout internal unsafe EditorUiLayout(ImGuiStyle* style) { - itemSpacing = ImGui.FromNative(style->ItemSpacing); - windowPadding = ImGui.FromNative(style->WindowPadding); - cellPadding = ImGui.FromNative(style->CellPadding); - itemInnerSpacing = ImGui.FromNative(style->ItemInnerSpacing); - framePadding = ImGui.FromNative(style->FramePadding); - dockingSeparatorSize = style->DockingSeparatorSize; - scrollbarSize = style->ScrollbarSize; - frameRounding = style->FrameRounding; + this.itemSpacing = ImGui.FromNative(style->ItemSpacing); + this.windowPadding = ImGui.FromNative(style->WindowPadding); + this.cellPadding = ImGui.FromNative(style->CellPadding); + this.itemInnerSpacing = ImGui.FromNative(style->ItemInnerSpacing); + this.framePadding = ImGui.FromNative(style->FramePadding); + this.dockingSeparatorSize = style->DockingSeparatorSize; + this.scrollbarSize = style->ScrollbarSize; + this.frameRounding = style->FrameRounding; } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs index 541fd8426..b906c8afb 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/EditorIconCatalog.cs @@ -1,7 +1,10 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; +using HostIcon = Inno.Adapter.Presentation.ImGui.ImGuiIcon; + namespace Inno.Editor.ImGui; /// @@ -12,12 +15,12 @@ public static class EditorIconCatalog /// /// Gets all named glyphs supplied by the installed UI font, in deterministic name order. /// - public static IReadOnlyList<(string Name, string Glyph)> standard { get; } = System.Array.AsReadOnly( - typeof(Inno.Adapter.Presentation.ImGui.ImGuiIcon) + public static IReadOnlyList<(string Name, string Glyph)> standard { get; } = Array.AsReadOnly( + typeof(HostIcon) .GetFields(BindingFlags.Public | BindingFlags.Static) .Where(static field => field.IsLiteral && field.FieldType == typeof(string)) .Select(static field => (field.Name, (string)field.GetRawConstantValue()!)) - .OrderBy(static value => value.Name, System.StringComparer.Ordinal) + .OrderBy(static value => value.Name, StringComparer.Ordinal) .ToArray() ); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs index ee4dc1a37..5d5c59192 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs @@ -1,6 +1,7 @@ using System; using HostFont = Inno.Adapter.Presentation.ImGui.ImGuiFont; +using HostScope = Inno.Adapter.Presentation.ImGui.ImGuiFontScope; using HostStyle = Inno.Adapter.Presentation.ImGui.ImGuiFontStyle; using NativeImGui = Inno.Native.ImGui.ImGui; @@ -59,7 +60,7 @@ public static ImGuiFontScope PushStyle(ImGuiFontStyle style) { EditorUiSession session = EditorUiSession.current; session.EnsureDrawing(); - var scope = HostFont.PushStyle((HostStyle)style); + HostScope scope = HostFont.PushStyle((HostStyle)style); return new ImGuiFontScope(session, scope, NativeImGui.GetFrameCount(), NativeImGui.Raw.GetCurrentContext()->FontStack.Size); } } @@ -70,13 +71,13 @@ public static ImGuiFontScope PushStyle(ImGuiFontStyle style) public unsafe ref struct ImGuiFontScope : IDisposable { private EditorUiSession? m_session; - private Inno.Adapter.Presentation.ImGui.ImGuiFontScope m_scope; + private HostScope m_scope; private readonly int m_frame; private readonly int m_depth; internal ImGuiFontScope( EditorUiSession session, - Inno.Adapter.Presentation.ImGui.ImGuiFontScope scope, + HostScope scope, int frame, int depth ) { diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs index 2ff00ca7c..e4b5509a9 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Card.cs @@ -82,8 +82,8 @@ public bool CollapsingCard( { Vector2 headerCursor = NativeImGui.GetCursorScreenPos(); (float cardLeft, float cardRight) = GetFullWidthCardBounds(headerCursor); - Vector2 persistentHeaderMin = new(cardLeft, headerCursor.Y); - Vector2 persistentHeaderMax = new(cardRight, headerCursor.Y + NativeImGui.GetFrameHeight()); + var persistentHeaderMin = new Vector2(cardLeft, headerCursor.Y); + var persistentHeaderMax = new Vector2(cardRight, headerCursor.Y + NativeImGui.GetFrameHeight()); ImGui.DrawNativeFilledRectangle( NativeImGui.Raw.GetWindowDrawList(), persistentHeaderMin, diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs index 48efe9ebc..ae9f76e9e 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Clipping.cs @@ -73,7 +73,7 @@ public void ClippedRows( return; } ImGuiListClipper* clipper = NativeImGui.Raw.ImGuiListClipper(); - if (clipper == null) + if (clipper is null) { throw new OutOfMemoryException("The native row clipper could not be allocated."); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs index 62ee3a9fe..7a3123b05 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.ContextMenu.cs @@ -117,7 +117,7 @@ public void DrawTooltip(string? text) return; } ImGuiViewport* viewport = NativeImGui.Raw.GetWindowViewport(); - Vector2 margin = new(6f * style.zoom); + var margin = new Vector2(6f * style.zoom); Vector2 available = Vector2.Max(Vector2.One, ImGui.FromNative(viewport->WorkSize) - margin * 2f); Vector2 padding = style.menuWindowPadding; float outerWidth = MathF.Min(C_TOOLTIP_WRAP_WIDTH * style.zoom, available.X); @@ -129,7 +129,7 @@ public void DrawTooltip(string? text) ); innerWidth = MathF.Max(1f, outerWidth - padding.X * 2f - style.menuBorderSize * 2f); textSize = NativeImGui.CalcTextSize(text, false, innerWidth); - Vector2 size = new(outerWidth, MathF.Min(available.Y, textSize.Y + padding.Y * 2f + style.menuBorderSize * 2f)); + var size = new Vector2(outerWidth, MathF.Min(available.Y, textSize.Y + padding.Y * 2f + style.menuBorderSize * 2f)); Vector2 workMin = ImGui.FromNative(viewport->WorkPos) + margin; Vector2 workMax = workMin + available; Vector2 mouse = NativeImGui.GetMousePos(); @@ -244,12 +244,10 @@ Vector2 maximum } [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])] - private static unsafe void RoundMenuPopupSize(ImGuiSizeCallbackData* data) - { + private static unsafe void RoundMenuPopupSize(ImGuiSizeCallbackData* data) => // ImGui truncates constrained sizes. Round content upward within integer bounds so // fractional padding cannot turn a fully fitting menu into a scrolling window. data->DesiredSize = ImGui.ToNative(new Vector2(MathF.Ceiling(data->DesiredSize.X), MathF.Ceiling(data->DesiredSize.Y))); - } private void PushContextMenuStyle() { diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs index 323565312..3e0179828 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Controls.cs @@ -203,7 +203,7 @@ public bool CompactCheckbox( ImGui.DrawNativeLine( drawList, min + new Vector2(size * 0.43f, size * 0.72f), - min + new Vector2(size * 0.80f, size * 0.28f), + min + new Vector2(size * 0.8f, size * 0.28f), checkColor, 1.5f ); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs index 60acb9047..294c7b3e7 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs @@ -3,7 +3,9 @@ using System.Runtime.CompilerServices; using Inno.Native.ImGui; +using NativeFocusedFlags = Inno.Native.ImGui.ImGuiFocusedFlags; using NativeGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; namespace Inno.Editor.ImGui.ImGuiWidget; @@ -123,7 +125,7 @@ public DialogLayout MeasureDialog( Vector2 availableSize ) { ImGuiNativeContext* native = m_session.RequireContext(); - if (native->WithinFrameScope == 0 || native->Font == null || native->FontBaked == null) + if (native->WithinFrameScope == 0 || native->Font is null || native->FontBaked is null) { throw new InvalidOperationException("Dialog measurement requires an active native frame and font."); } @@ -148,7 +150,7 @@ Vector2 availableSize bool memoize = font->OwnerAtlas->OwnerContext == native && font->RemapPairs.Data.Size == 0 && (long)presentation.message.Length + (presentation.details?.Length ?? 0) + (presentation.actionLabel?.Length ?? 0) <= C_MAX_CACHED_DIALOG_CHARS; - DialogMeasurementKey key = new( + var key = new DialogMeasurementKey( presentation.message, presentation.details, presentation.actionLabel, @@ -192,7 +194,7 @@ Vector2 availableSize float actionWidth = hasAction ? ImGuiUtf8Buffer.MeasureText(presentation.actionLabel!, -1f).X + nativeStyle->FramePadding.X * 2f : 0f; - DialogLayout result = new(new Vector2(width, MathF.Ceiling(height)), textWidth, visibleBody, body, spacing, frame, actionWidth); + var result = new DialogLayout(new Vector2(width, MathF.Ceiling(height)), textWidth, visibleBody, body, spacing, frame, actionWidth); if (memoize) { m_previousDialogKey = m_dialogKey; @@ -307,9 +309,9 @@ DialogLayout layout activated = DrawCenteredButton(presentation.actionLabel, origin + new Vector2(0f, y), layout.size.X, layout.actionWidth); if (presentation.cancelOnEscape && presentation.actionEnabled - && NativeGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.RootAndChildWindows) + && NativeGui.IsWindowFocused((int)NativeFocusedFlags.RootAndChildWindows) && - NativeGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Escape, false) + NativeGui.IsKeyPressed(NativeKey.Escape, false) ) { activated = true; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs index 7d3fcd7e3..5ac1fa2a0 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.DragDrop.cs @@ -123,10 +123,7 @@ public bool DragDropSource( public bool DragDropTarget( string payloadType, out TPayload payload - ) where TPayload : unmanaged - { - return DragDropTarget(payloadType, out payload, out _); - } + ) where TPayload : unmanaged => DragDropTarget(payloadType, out payload, out _); /// /// Accepts an unmanaged payload and reports its preview state on the most recently submitted item. @@ -150,10 +147,7 @@ public bool DragDropTarget( string payloadType, out TPayload payload, out bool isPreviewing - ) where TPayload : unmanaged - { - return DragDropTarget(payloadType, out payload, out isPreviewing, drawDefaultHighlight: true); - } + ) where TPayload : unmanaged => DragDropTarget(payloadType, out payload, out isPreviewing, drawDefaultHighlight: true); /// /// Accepts an unmanaged payload and controls whether ImGui draws its default target rectangle. @@ -258,7 +252,7 @@ public bool DragDropTarget( { return false; } - ImRect bounds = new() + var bounds = new ImRect() { Min = ImGui.ToNative(minimum), Max = ImGui.ToNative(maximum) @@ -305,7 +299,7 @@ out TPayload payload ) where TPayload : unmanaged { payload = default; - if ((nativePayload == null) || nativePayload->DataSize != sizeof(TPayload) || nativePayload->Data == null) + if ((nativePayload is null) || nativePayload->DataSize != sizeof(TPayload) || nativePayload->Data is null) { return false; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs index 1aad2e10b..b7170b9da 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Editing.cs @@ -4,6 +4,7 @@ using Inno.Scripting.Api; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; namespace Inno.Editor.ImGui.ImGuiWidget; @@ -72,7 +73,7 @@ string name m_session.EnsureDrawing(); ArgumentNullException.ThrowIfNull(history); ArgumentException.ThrowIfNullOrWhiteSpace(path); - var key = (m_session.owner, path); + (string owner, string path) key = (m_session.owner, path); if (m_propertyGesture is not null && m_propertyEditKey != key) { CommitEdits(); @@ -113,7 +114,7 @@ public void CompletePropertyEdit(string path) return; } m_propertyEditTouched = true; - if (NativeImGui.IsKeyPressed((Inno.Native.ImGui.ImGuiKey)ImGuiKey.Escape, false)) + if (NativeImGui.IsKeyPressed((NativeKey)ImGuiKey.Escape, false)) { CancelEdits(); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs index c6729e752..4c1ddb523 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs @@ -1,7 +1,8 @@ using System; using System.Numerics; +using Inno.Native.ImGuizmo; -using Matrix = Inno.Core.Mathematics.Matrix; +using EngineMatrix = Inno.Core.Mathematics.Matrix; using NativeGizmo = Inno.Native.ImGuizmo.ImGuizmo; using NativeImGui = Inno.Native.ImGui.ImGui; using NativeOperation = Inno.Native.ImGuizmo.ImGuizmoOperation; @@ -74,12 +75,12 @@ public readonly record struct TransformGizmoOptions /// /// Gets the column-vector view matrix. /// - public Matrix view { get; init; } + public EngineMatrix view { get; init; } /// /// Gets the projection matrix supplied by the viewport owner. /// - public Matrix projection { get; init; } + public EngineMatrix projection { get; init; } /// /// Gets whether this viewport uses an orthographic projection. @@ -133,7 +134,7 @@ public readonly record struct TransformGizmoOptions /// Whether the pointer is over a handle. /// public readonly record struct TransformGizmoResult( - Matrix matrix, + EngineMatrix matrix, bool changed, bool isUsing, bool isOver @@ -157,7 +158,7 @@ public sealed unsafe partial class ImGuiWidget /// Copied output with no native pointer or domain object. /// public TransformGizmoResult TransformGizmo( - Matrix world, + EngineMatrix world, TransformGizmoOptions options ) { m_session.EnsureDrawing(); @@ -169,7 +170,7 @@ TransformGizmoOptions options WriteColumnMajor(world, model); NativeOperation operation = ToNativeOperation(options.operation); NativeGizmo.BeginFrame(); - NativeGizmo.Raw.SetDrawlist((Inno.Native.ImGuizmo.ImDrawList*)(nint)NativeImGui.Raw.GetWindowDrawList()); + NativeGizmo.Raw.SetDrawlist((ImDrawList*)(nint)NativeImGui.Raw.GetWindowDrawList()); NativeGizmo.SetRect( options.minimum.X, options.minimum.Y, @@ -178,8 +179,8 @@ TransformGizmoOptions options ); NativeGizmo.SetOrthographic(options.orthographic); NativeGizmo.SetGizmoSizeClipSpace(0.21f); - var style = NativeGizmo.Raw.GetStyle(); - var previousStyle = *style; + Style* style = NativeGizmo.Raw.GetStyle(); + Style previousStyle = *style; try { style->TranslationLineThickness = 3.5f; @@ -245,7 +246,7 @@ private static NativeOperation ToNativeOperation(TransformGizmoOperation operati } private static unsafe void WriteColumnMajor( - Matrix matrix, + EngineMatrix matrix, float* destination ) { destination[0] = matrix.m11; @@ -266,7 +267,7 @@ private static unsafe void WriteColumnMajor( destination[15] = matrix.m44; } - private static unsafe Matrix ReadColumnMajor(float* source) + private static unsafe EngineMatrix ReadColumnMajor(float* source) => new( source[0], source[4], diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs index 1459dbe0d..ae87c8079 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.HelpBox.cs @@ -34,7 +34,7 @@ Vector4 color ArgumentNullException.ThrowIfNull(text); ArgumentNullException.ThrowIfNull(icon); Vector2 origin = NativeImGui.GetCursorScreenPos(); - Vector2 padding = new(10f * style.zoom, 8f * style.zoom); + var padding = new Vector2(10f * style.zoom, 8f * style.zoom); float width = MathF.Max(1f, NativeImGui.GetContentRegionAvail().X); float iconWidth = NativeImGui.CalcTextSize(icon).X; float gap = 8f * style.zoom; @@ -201,13 +201,13 @@ public bool EnsureSection( /// /// Optional interactive control drawn before the section title. /// - /// - /// Thrown when is . - /// /// /// when the section content should be drawn; otherwise, /// when the section is collapsed. /// + /// + /// Thrown when is . + /// public bool SectionHeader( string title, string? description = null, diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs index 68f4a6292..37ba6b46f 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs @@ -3,6 +3,7 @@ using Inno.Native.ImGui; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; namespace Inno.Editor.ImGui.ImGuiWidget; @@ -94,14 +95,14 @@ public InlineRenameResult InlineRename( } bool deactivated = NativeImGui.IsItemDeactivated(); - bool escapePressed = NativeImGui.IsKeyPressed((Inno.Native.ImGui.ImGuiKey)ImGuiKey.Escape); + bool escapePressed = NativeImGui.IsKeyPressed((NativeKey)ImGuiKey.Escape); bool active = NativeImGui.IsItemActive(); bool contextMenuRequested = active && NativeImGui.IsMouseReleased((int)(ImGuiMouseButton.Right)); if (selectAll && active) { uint inputId = NativeImGui.GetItemID(); ImGuiInputTextState* inputState = NativeImGui.Raw.GetInputTextState(inputId); - if (inputState != null) + if (inputState is not null) { NativeImGui.Raw.SelectAll(inputState); requestFocus = false; @@ -110,7 +111,7 @@ public InlineRenameResult InlineRename( if (active) { - Vector2 focusOffset = new(C_INLINE_RENAME_FOCUS_OFFSET); + var focusOffset = new Vector2(C_INLINE_RENAME_FOCUS_OFFSET); ImGui.DrawNativeRectangle( NativeImGui.Raw.GetForegroundDrawList((ImGuiViewport*)null), NativeImGui.GetItemRectMin() - focusOffset, diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs index 8b956d885..2b1a80375 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Lifetime.cs @@ -13,7 +13,7 @@ public sealed unsafe partial class ImGuiWidget internal ImGuiWidget(EditorUiSession session) { m_session = session ?? throw new ArgumentNullException(nameof(session)); - style = new EditorStyleMetrics(session); + this.style = new EditorStyleMetrics(session); } internal void RetireOwner(string owner) @@ -23,7 +23,7 @@ internal void RetireOwner(string owner) CancelEdits(); } var retired = new List<(string Owner, uint Window)>(); - foreach (var key in m_treeStatesByWindow.Keys) + foreach ((string Owner, uint Window) key in m_treeStatesByWindow.Keys) { if (string.Equals(key.Owner, owner, StringComparison.Ordinal)) { @@ -31,7 +31,7 @@ internal void RetireOwner(string owner) } } - foreach (var key in retired) + foreach ((string Owner, uint Window) key in retired) { m_treeStatesByWindow.Remove(key); } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs index 047cdf6d1..d703d9ddd 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Panel.cs @@ -230,24 +230,24 @@ private bool DrawPanelCloseButton(string title) } uint dockId = NativeImGui.GetWindowDockID(); ImGuiDockNode* dockNode = NativeImGui.Raw.DockBuilderGetNode(dockId); - if (dockNode == null || NativeImGui.Raw.DockNodeBeginAmendTabBar(dockNode) == 0) + if (dockNode is null || NativeImGui.Raw.DockNodeBeginAmendTabBar(dockNode) == 0) { return false; } try { ImGuiTabBar* tabBar = dockNode->TabBar; - if (tabBar == null) + if (tabBar is null) { return false; } ImRect tabBarBounds = tabBar->BarRect; float tabBarHeight = MathF.Max(1f, tabBarBounds.Max.Y - tabBarBounds.Min.Y); float iconSlotSize = MathF.Min(GetCompactIconSize().X, tabBarHeight); - Vector2 itemCenter = new(tabBarBounds.Max.X - iconSlotSize * 0.5f, (tabBarBounds.Min.Y + tabBarBounds.Max.Y) * 0.5f); + var itemCenter = new Vector2(tabBarBounds.Max.X - iconSlotSize * 0.5f, (tabBarBounds.Min.Y + tabBarBounds.Max.Y) * 0.5f); Vector2 itemMinimum = itemCenter - new Vector2(iconSlotSize * 0.5f); Vector2 itemMaximum = itemCenter + new Vector2(iconSlotSize * 0.5f); - ImRect itemBounds = new() + var itemBounds = new ImRect() { Min = ImGui.ToNative(itemMinimum), Max = ImGui.ToNative(itemMaximum) @@ -259,7 +259,7 @@ private bool DrawPanelCloseButton(string title) | (int)ImGuiButtonFlagsPrivate.NoNavFocus | (int)ImGuiButtonFlagsPrivate.PressedOnClickRelease); ImGuiWindow* hoveredWindow = NativeImGui.Raw.GetCurrentContext()->HoveredWindow; - bool hostHovered = hoveredWindow != null && hoveredWindow->RootWindowDockTree == dockNode->HostWindow->RootWindowDockTree; + bool hostHovered = hoveredWindow is not null && hoveredWindow->RootWindowDockTree == dockNode->HostWindow->RootWindowDockTree; bool mouseHovered = hostHovered && NativeImGui.IsMouseHoveringRect(itemMinimum, itemMaximum); bool itemAdded = NativeImGui.Raw.ItemAdd(&itemBounds, itemId, null, 0) != 0; bool pressed = hostHovered @@ -294,12 +294,12 @@ private bool DrawFloatingPanelCloseButton(string title) } ImGuiStyle* nativeStyle = NativeImGui.Raw.GetStyle(); float size = GetCompactIconSize().X; - Vector2 maximum = new( + var maximum = new Vector2( window->Pos.X + window->Size.X - nativeStyle->WindowBorderSize - nativeStyle->FramePadding.X, window->Pos.Y + (window->TitleBarHeight + size) * 0.5f ); Vector2 minimum = maximum - new Vector2(size); - ImRect bounds = new() + var bounds = new ImRect() { Min = ImGui.ToNative(minimum), Max = ImGui.ToNative(maximum) @@ -316,7 +316,8 @@ private bool DrawFloatingPanelCloseButton(string title) try { uint id = NativeImGui.GetID("##floating_panel_close"); - bool hovered = false, held = false; + bool hovered = false; + bool held = false; bool pressed = NativeImGui.Raw.ItemAdd(&bounds, id, null, 0) != 0 && NativeImGui.ButtonBehavior( bounds, diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs index 9009ea618..1ddef6131 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Property.cs @@ -487,13 +487,11 @@ private void ValidateFloatBounds( } private Vector4 GetAxisColor(string axis) + => axis.ToUpperInvariant() switch { - return axis.ToUpperInvariant() switch - { - "X" or "R" => EditorPalette.axisX, - "Y" or "G" => EditorPalette.axisY, - "Z" or "B" => EditorPalette.axisZ, - _ => EditorPalette.axisW - }; - } + "X" or "R" => EditorPalette.axisX, + "Y" or "G" => EditorPalette.axisY, + "Z" or "B" => EditorPalette.axisZ, + _ => EditorPalette.axisW + }; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs index dfc6acd73..4c71bb428 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Search.cs @@ -13,9 +13,6 @@ public sealed partial class ImGuiWidget /// /// Draws a single-line search field with a stable identifier. /// - /// - /// Escape clears a nonempty query before leaving text input on a subsequent press. - /// /// /// The stable control identifier. /// @@ -34,6 +31,9 @@ public sealed partial class ImGuiWidget /// /// when the query changed; otherwise, . /// + /// + /// Escape clears a nonempty query before leaving text input on a subsequent press. + /// public bool SearchInput( string id, string hint, diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs index ff1d5b649..d00d44920 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs @@ -6,7 +6,9 @@ using Inno.Editor.Interactions; using Inno.Native.ImGui; +using NativeFocusedFlags = Inno.Native.ImGui.ImGuiFocusedFlags; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; namespace Inno.Editor.ImGui.ImGuiWidget; @@ -96,7 +98,7 @@ public ListNavigationResult NavigateList( ImGuiIO* io = NativeImGui.Raw.GetIO(); ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); bool ownsActiveRow = RouteTreeNavigationKeys(context); - if (!NativeImGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows) + if (!NativeImGui.IsWindowFocused((int)NativeFocusedFlags.ChildWindows) || io->WantTextInput != 0 || (context->ActiveId != 0 && !ownsActiveRow) || ImGui.IsAnyPopupOpen() ) { return new(focusedIndex, false, false, false, false, false, false, false); @@ -106,27 +108,27 @@ public ListNavigationResult NavigateList( if (itemCount > 0) { navigation = true; - if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.DownArrow)) + if (NativeImGui.IsKeyPressed(NativeKey.DownArrow)) { next = focusedIndex < 0 ? 0 : Math.Min(itemCount - 1, focusedIndex + 1); } - else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.UpArrow)) + else if (NativeImGui.IsKeyPressed(NativeKey.UpArrow)) { next = focusedIndex < 0 ? itemCount - 1 : Math.Max(0, focusedIndex - 1); } - else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Home)) + else if (NativeImGui.IsKeyPressed(NativeKey.Home)) { next = 0; } - else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.End)) + else if (NativeImGui.IsKeyPressed(NativeKey.End)) { next = itemCount - 1; } - else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.PageDown)) + else if (NativeImGui.IsKeyPressed(NativeKey.PageDown)) { next = focusedIndex < 0 ? 0 : (int)Math.Min(itemCount - 1L, (long)focusedIndex + pageSize); } - else if (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.PageUp)) + else if (NativeImGui.IsKeyPressed(NativeKey.PageUp)) { next = focusedIndex < 0 ? 0 : Math.Max(0, focusedIndex - pageSize); } @@ -137,10 +139,10 @@ public ListNavigationResult NavigateList( } bool primary = HasPrimaryModifier(interactions.keyboard, io); bool extend = io->KeyShift != 0; - bool space = itemCount > 0 && NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Space, false); - bool activate = itemCount > 0 && (NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Enter, false) - || NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.KeypadEnter, false)); - bool cancel = NativeImGui.IsKeyPressed(Inno.Native.ImGui.ImGuiKey.Escape, false); + bool space = itemCount > 0 && NativeImGui.IsKeyPressed(NativeKey.Space, false); + bool activate = itemCount > 0 && (NativeImGui.IsKeyPressed(NativeKey.Enter, false) + || NativeImGui.IsKeyPressed(NativeKey.KeypadEnter, false)); + bool cancel = NativeImGui.IsKeyPressed(NativeKey.Escape, false); if ((space || activate) && next < 0) { next = 0; @@ -162,7 +164,7 @@ private bool RouteTreeNavigationKeys(ImGuiNativeContext* context) uint window = NativeImGui.Raw.GetCurrentWindow()->ID; if (!m_treeStatesByWindow.TryGetValue((m_session.owner, window), out TreeWidgetWindowState? state) || state.lastFrame != NativeImGui.GetFrameCount() - || !NativeImGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows) + || !NativeImGui.IsWindowFocused((int)NativeFocusedFlags.ChildWindows) || NativeImGui.Raw.GetIO()->WantTextInput != 0 || ImGui.IsAnyPopupOpen() ) { return false; @@ -174,9 +176,9 @@ private bool RouteTreeNavigationKeys(ImGuiNativeContext* context) // Native navigation must not activate the disclosure while the list owns selection/activation. // A distinct owner preserves text fields and overlay buttons, including their native navigation. uint owner = NativeImGui.GetID("##inno_list_navigation"); - NativeImGui.SetKeyOwner(Inno.Native.ImGui.ImGuiKey.Space, owner, 0); - NativeImGui.SetKeyOwner(Inno.Native.ImGui.ImGuiKey.Enter, owner, 0); - NativeImGui.SetKeyOwner(Inno.Native.ImGui.ImGuiKey.KeypadEnter, owner, 0); + NativeImGui.SetKeyOwner(NativeKey.Space, owner, 0); + NativeImGui.SetKeyOwner(NativeKey.Enter, owner, 0); + NativeImGui.SetKeyOwner(NativeKey.KeypadEnter, owner, 0); } return ownsActiveRow; } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs index 4434cdbef..b0b049e12 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selector.cs @@ -109,7 +109,7 @@ float minimumPopupWidth string popupId = $"##menu_selector_popup_{id}"; Vector2 minimum = NativeImGui.GetCursorScreenPos(); float height = NativeImGui.GetFrameHeight(); - Vector2 size = new(width, height); + var size = new Vector2(width, height); bool pressed = NativeImGui.InvisibleButton($"##menu_selector_{id}", size); bool hovered = NativeImGui.IsItemHovered(); bool active = NativeImGui.IsItemActive(); @@ -119,7 +119,7 @@ float minimumPopupWidth NativeImGui.OpenPopup(popupId); } DrawMenuSelectorFrame(minimum, size, preview, hovered, active || open); - Vector2 popupOrigin = new(minimum.X, minimum.Y + height); + var popupOrigin = new Vector2(minimum.X, minimum.Y + height); NativeImGui.SetNextWindowPos(popupOrigin, (int)ImGuiCond.Always, Vector2.Zero); ImGuiViewport* parentViewport = NativeImGui.Raw.GetWindowViewport(); NativeImGui.SetNextWindowViewport(parentViewport->ID); @@ -181,7 +181,7 @@ bool active (int)(size.X <= arrowSlot ? ImDrawFlags.RoundCornersAll : ImDrawFlags.RoundCornersRight) ); Vector2 textMinimum = minimum + ImGui.FromNative(nativeStyle->FramePadding); - Vector2 textMaximum = new(arrowMinimumX, maximum.Y); + var textMaximum = new Vector2(arrowMinimumX, maximum.Y); ImGui.PushNativeClipRectangle(drawList, textMinimum, textMaximum, 1); ImGui.DrawNativeText(drawList, textMinimum, NativeImGui.GetColorU32((int)(ImGuiCol.Text)), preview); NativeImGui.Raw.PopClipRect(drawList); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs index fbcdf5e45..a46b8d2dc 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Text.cs @@ -31,7 +31,7 @@ public float GetIconCatalogWidth() } float fontSize = NativeImGui.GetFontSize(); float width = NativeImGui.GetTextLineHeight(); - foreach (var entry in EditorIconCatalog.standard) + foreach ((string Name, string Glyph) entry in EditorIconCatalog.standard) { Vector4 bounds = GetGlyphVisualBounds(fontSize, entry.Glyph); width = MathF.Max(width, bounds.Z - bounds.X); @@ -122,7 +122,7 @@ string text int codepoint = char.ConvertToUtf32(text, 0); ImFontBaked* baked = NativeImGui.Raw.GetFontBaked(font, fontSize, -1f); ImFontGlyph* glyph = codepoint <= ushort.MaxValue ? NativeImGui.Raw.FindGlyph(baked, (ushort)codepoint) : null; - if (glyph != null) + if (glyph is not null) { return new Vector4(glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); } @@ -163,7 +163,7 @@ uint color ) { m_session.EnsureDrawing(); Vector4 bounds = GetGlyphVisualBoundsNative(font, fontSize, text); - Vector2 visibleCenterOffset = new((bounds.X + bounds.Z) * 0.5f, (bounds.Y + bounds.W) * 0.5f); + var visibleCenterOffset = new Vector2((bounds.X + bounds.Z) * 0.5f, (bounds.Y + bounds.W) * 0.5f); ImGui.DrawNativeText(drawList, font, fontSize, center - visibleCenterOffset, color, text); } @@ -427,7 +427,7 @@ Vector2 padding } Vector2 origin = NativeImGui.GetCursorScreenPos(); - Vector2 effectivePadding = new( + var effectivePadding = new Vector2( MathF.Min(padding.X, MathF.Max(0f, (areaSize.X - 1f) * 0.5f)), MathF.Min(padding.Y, MathF.Max(0f, (areaSize.Y - 1f) * 0.5f)) ); @@ -603,7 +603,7 @@ public Vector2 GetCompactClickableTextSize() { m_session.EnsureDrawing(); float iconSlotWidth = NativeImGui.GetTextLineHeight(); - return new Vector2(iconSlotWidth + this.style.iconLabelSpacing, NativeImGui.GetFrameHeight()); + return new Vector2(iconSlotWidth + style.iconLabelSpacing, NativeImGui.GetFrameHeight()); } /// @@ -664,7 +664,7 @@ bool highlight Vector4 glyphBounds = GetGlyphVisualBoundsNative(font, fontSize, icon); float iconSlotWidth = MathF.Max(lineHeight, glyphBounds.Z - glyphBounds.X); Vector2 textSize = NativeImGui.CalcTextSize(text); - Vector2 textPos = new(cursor.X + iconSlotWidth + style->ItemInnerSpacing.X, cursor.Y); + var textPos = new Vector2(cursor.X + iconSlotWidth + style->ItemInnerSpacing.X, cursor.Y); uint color = NativeImGui.GetColorU32((int)(ImGuiCol.Text)); ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); AddGlyphCenteredNative( diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs index 533a1a3d4..4e282baad 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs @@ -3,6 +3,7 @@ using System.Numerics; using Inno.Native.ImGui; +using NativeFocusedFlags = Inno.Native.ImGui.ImGuiFocusedFlags; using NativeImGui = Inno.Native.ImGui.ImGui; namespace Inno.Editor.ImGui.ImGuiWidget; @@ -228,7 +229,7 @@ bool drawContent bool isOpen; try { - if (options.requestFocus && NativeImGui.IsWindowFocused((int)Inno.Native.ImGui.ImGuiFocusedFlags.ChildWindows)) + if (options.requestFocus && NativeImGui.IsWindowFocused((int)NativeFocusedFlags.ChildWindows)) { NativeImGui.SetKeyboardFocusHere(); } @@ -341,7 +342,7 @@ public void SetNextTreeNodeOpen(bool open) private TreeWidgetWindowState GetTreeWindowState() { - var windowKey = (m_session.owner, NativeImGui.Raw.GetCurrentWindow()->ID); + (string owner, uint) windowKey = (m_session.owner, NativeImGui.Raw.GetCurrentWindow()->ID); if (!m_treeStatesByWindow.TryGetValue(windowKey, out TreeWidgetWindowState? state)) { state = new TreeWidgetWindowState(); @@ -380,12 +381,12 @@ out Vector2 interactionMin Vector2 contentMin = NativeImGui.GetItemRectMin(); Vector2 contentMax = NativeImGui.GetItemRectMax(); - TreeWidgetHighlightRect rect = new() + var rect = new TreeWidgetHighlightRect() { min = new Vector2(windowPos.X, MathF.Min(nodeCursor.Y, contentMin.Y)), max = new Vector2(contentRightX, MathF.Max(nativeRowMaxY, contentMax.Y)) }; - Vector2 hitMin = new(contentX, rect.min.Y); + var hitMin = new Vector2(contentX, rect.min.Y); Vector2 hitMax = rect.max; interactionMin = hitMin; DrawTreeNodeViewportOverlay(window, drawViewportOverlay); @@ -523,7 +524,7 @@ private void AddTreeLine( Vector2 from, Vector2 to ) { - TreeWidgetLineSegment line = new() + var line = new TreeWidgetLineSegment() { from = SnapTreeLinePoint(from), to = SnapTreeLinePoint(to) @@ -534,14 +535,11 @@ Vector2 to line.from, line.to, NativeImGui.ColorConvertFloat4ToU32(EditorPalette.treeGuide), - this.style.borderSize + style.borderSize ); } - private Vector2 SnapTreeLinePoint(Vector2 point) - { - return new Vector2(MathF.Floor(point.X) + 0.5f, MathF.Floor(point.Y) + 0.5f); - } + private Vector2 SnapTreeLinePoint(Vector2 point) => new Vector2(MathF.Floor(point.X) + 0.5f, MathF.Floor(point.Y) + 0.5f); private void DrawTreeRowBackground( ImDrawList* drawList, diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs index 287a90b6f..deb61ad29 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Trend.cs @@ -56,7 +56,7 @@ public void Trend( } NativeImGui.TextUnformatted(label); Vector2 origin = NativeImGui.GetCursorScreenPos(); - Vector2 size = new(MathF.Max(1f, NativeImGui.GetContentRegionAvail().X), style.trendHeight); + var size = new Vector2(MathF.Max(1f, NativeImGui.GetContentRegionAvail().X), style.trendHeight); _ = NativeImGui.InvisibleButton(label, size); EditorDrawList draw = ImGui.GetDrawList(); draw.FilledRectangle(origin, origin + size, NativeImGui.ColorConvertFloat4ToU32(EditorPalette.collectionRow)); diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs index 7457e9966..570940890 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs @@ -1,8 +1,10 @@ using System; using System.Linq; using Inno.Assets.Pipeline; +using Inno.Editor.Assets; using Inno.Editor.ImGui; using Inno.Editor.Inspection; +using Inno.Editor.Rendering; using Inno.Editor.Shaders; using Inno.Rendering; using Inno.Rendering.Assets; @@ -18,7 +20,7 @@ internal sealed class MaterialInspectionDrawer(IInspectionIconProvider /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => Inno.Editor.ImGui.ImGuiIcon.File; + public override string icon => ImGuiIcon.File; /// /// Retrieves the current icon from authoritative state. @@ -35,7 +37,7 @@ internal sealed class MaterialInspectionDrawer(IInspectionIconProvider context.interactions.TryGetModule(out var documents) + ) => context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null && documents.assets.TryGetFileSystemEntry( target.assetPath, @@ -72,7 +74,7 @@ protected override void DrawHeader( InspectionDrawContext context, MaterialAsset target ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) + if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) { MaterialInspector.DrawHeader(context, documents, documents.Open(target)); } @@ -91,7 +93,7 @@ protected override void Draw( InspectionDrawContext context, MaterialAsset target ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) + if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) { MaterialInspector.Draw(context, documents, documents.Open(target)); } @@ -104,7 +106,7 @@ internal sealed class MaterialSourceDrawer(IInspectionIconProvider /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => Inno.Editor.ImGui.ImGuiIcon.File; + public override string icon => ImGuiIcon.File; /// /// Retrieves the current icon from authoritative state. @@ -165,7 +167,7 @@ protected override void DrawHeader( InspectionDrawContext context, AssetFileEntry target ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) + if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) { MaterialInspector.DrawHeader(context, documents, documents.OpenDraft(target.assetPath)); } @@ -184,7 +186,7 @@ protected override void Draw( InspectionDrawContext context, AssetFileEntry target ) { - if (context.interactions.TryGetModule(out var documents) && documents is not null) + if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) { MaterialInspector.Draw(context, documents, documents.OpenDraft(target.assetPath)); } @@ -196,26 +198,24 @@ internal static class MaterialInspector internal static void DrawHeader( InspectionDrawContext context, MaterialDocuments documents, - Inno.Editor.Assets.AssetDraftDocuments.Draft draft - ) { - EditorUI.current.widgets.Disabled(draft.readOnly, () => + AssetDraftDocuments.Draft draft + ) => EditorUI.current.widgets.Disabled(draft.readOnly, () => + { + if (Ui.Button("Save")) { - if (Ui.Button("Save")) - { - _ = context.interactions.documents.Save(draft.documentId); - } - Ui.SameLine(0f, -1f); - if (Ui.Button("Revert")) - { - _ = context.interactions.documents.Revert(draft.documentId); - } - }); - } + _ = context.interactions.documents.Save(draft.documentId); + } + Ui.SameLine(0f, -1f); + if (Ui.Button("Revert")) + { + _ = context.interactions.documents.Revert(draft.documentId); + } + }); internal static void Draw( InspectionDrawContext context, MaterialDocuments documents, - Inno.Editor.Assets.AssetDraftDocuments.Draft draft + AssetDraftDocuments.Draft draft ) { MaterialAsset material = documents.Read(draft.id); var edits = new DraftEdits(documents, draft, material); @@ -228,8 +228,9 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft { EditorUI.current.widgets.Hint("Choose an available Shader to preview this Material."); } - else if (context.interactions.TryGetModule(out var shaderPreviews) && shaderPreviews is not null) - { + else if (context.interactions.TryGetModule(out ShaderPreviews? shaderPreviews) + && shaderPreviews is not null + ) { shaderPreviews.DrawMaterial(draft.id, material, MathF.Max(1f, MathF.Min(256f, Ui.GetContentRegionAvailable().X))); } else @@ -321,7 +322,7 @@ Inno.Editor.Assets.AssetDraftDocuments.Draft draft "Inherited values follow Shader defaults. Changing a field creates a Material override; Reset restores inheritance." ); bool groupOpen = parametersOpen; - string currentGroup = ""; + string currentGroup = string.Empty; int visibleParameters = 0; foreach (ShaderPropertyDefinition property in definition.properties.Where(IsEditable)) { @@ -381,8 +382,9 @@ out string presentationError if (value.kind == MaterialValueKind.Texture) { - if (value.texture is { isMissing: false } texture && documents.previews.TryGetTexture(texture, out var preview)) - { + if (value.texture is { isMissing: false } texture + && documents.previews.TryGetTexture(texture, out EditorPreviewHandle preview) + ) { float width = MathF.Max(1f, MathF.Min(128f, Ui.GetContentRegionAvailable().X)); float height = width * preview.pixelHeight / preview.pixelWidth; if (height > 128f) @@ -545,11 +547,11 @@ private static bool IsEditable(ShaderPropertyDefinition property) private sealed class DraftEdits( MaterialDocuments documents, - Inno.Editor.Assets.AssetDraftDocuments.Draft draft, + AssetDraftDocuments.Draft draft, MaterialAsset material ) : IInspectionPropertyEditService { - /// + /// public bool ChangeProperty( object owner, string propertyName, diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs index cc6ddab17..bc4b7c897 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSelectionDrawer.cs @@ -4,6 +4,7 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Identity; +using Inno.Editor.Assets; using Inno.Editor.ImGui; using Inno.Editor.Inspection; using Inno.Editor.Interactions; @@ -25,7 +26,7 @@ EditorInteractions interactions /// /// Gets the icon glyph used to represent this item in the editor. /// - public override string icon => Inno.Editor.ImGui.ImGuiIcon.File; + public override string icon => ImGuiIcon.File; /// /// Retrieves the current icon from authoritative state. @@ -45,7 +46,7 @@ EditorSelectionSnapshot target ) { Guid id = GetAssetIds(target).FirstOrDefault(); return id != Guid.Empty - && context.interactions.TryGetModule(out var documents) + && context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null && documents.assets.TryGetInfo(id, out AssetInfo? info) && info is not null @@ -85,7 +86,7 @@ protected override void DrawHeader( InspectionDrawContext context, EditorSelectionSnapshot target ) { - if (!TryOpenDrafts(context, target, out MaterialDocuments? documents, out var drafts)) + if (!TryOpenDrafts(context, target, out MaterialDocuments? documents, out List.Draft> drafts)) { return; } @@ -96,7 +97,7 @@ EditorSelectionSnapshot target if (ImGuiApi.Button("Save Selected")) { EditorUiSession.current.widgets.CommitEdits(); - foreach (var draft in drafts) + foreach (AssetDraftDocuments.Draft draft in drafts) { _ = context.interactions.documents.Save(draft.documentId); } @@ -106,8 +107,8 @@ EditorSelectionSnapshot target if (ImGuiApi.Button("Revert Selected")) { EditorUiSession.current.widgets.CommitEdits(); - using var transaction = context.interactions.history.BeginTransaction("Revert Materials"); - foreach (var draft in drafts) + using EditorHistoryTransaction transaction = context.interactions.history.BeginTransaction("Revert Materials"); + foreach (AssetDraftDocuments.Draft draft in drafts) { _ = context.interactions.documents.Revert(draft.documentId); } @@ -133,14 +134,14 @@ protected override void Draw( InspectionDrawContext context, EditorSelectionSnapshot target ) { - if (!TryOpenDrafts(context, target, out MaterialDocuments? documents, out var drafts)) + if (!TryOpenDrafts(context, target, out MaterialDocuments? documents, out List.Draft> drafts)) { EditorUI.current.widgets.Hint("Select Materials with compatible Shader interfaces to edit their common parameters."); return; } MaterialDocuments owner = documents!; - var materials = drafts.ToDictionary(value => value.id, value => owner.Read(value.id)); + Dictionary materials = drafts.ToDictionary(value => value.id, value => owner.Read(value.id)); bool readOnly = drafts.Any(value => value.readOnly); ImGuiApi.PushId("materials." + string.Join(".", GetAssetIds(target))); ImGuiApi.BeginDisabled(readOnly); @@ -151,7 +152,7 @@ EditorSelectionSnapshot target { EditorUI.current.widgets.Hint("Selection includes installed read-only content. Copy it to the project before editing."); } - foreach (var draft in drafts.Where(value => value.error.Length != 0)) + foreach (AssetDraftDocuments.Draft draft in drafts.Where(value => value.error.Length != 0)) { EditorUI.current.widgets.Hint(draft.path.localPath + ": " + draft.error); } @@ -287,7 +288,7 @@ void SetOption(string? next) "Only compatible Material-owned inputs appear here. Unrelated overrides are retained per Material." ); bool groupOpen = parametersOpen; - string currentGroup = ""; + string currentGroup = string.Empty; foreach (ShaderPropertyDefinition property in firstDefinition.properties) { if (property.bindingOwner != ShaderPropertyBindingOwner.Material @@ -353,7 +354,9 @@ void SetOption(string? next) } } - MaterialValue value = material.TryGet(property.id, out var overridden) ? overridden : declarations[index].defaultValue; + MaterialValue value = material.TryGet(property.id, out MaterialValue overridden) + ? overridden + : declarations[index].defaultValue; if (!ShaderPropertyInspector.Compatible(property.type, value.kind)) { compatible = false; @@ -453,7 +456,7 @@ protected override bool CanInspect(EditorSelectionSnapshot target) private IReadOnlyList GetAssetIds(EditorSelectionSnapshot target) { - if (!interactions.TryGetModule(out var materials) || materials is null) + if (!interactions.TryGetModule(out MaterialDocuments? materials) || materials is null) { return Array.Empty(); } @@ -484,7 +487,7 @@ private bool TryOpenDrafts( InspectionDrawContext context, EditorSelectionSnapshot target, out MaterialDocuments? documents, - out List.Draft> drafts + out List.Draft> drafts ) { drafts = []; if (!context.interactions.TryGetModule(out documents) || documents is null) @@ -500,7 +503,7 @@ out List.Draft> drafts ) { return false; } - var draft = documents.OpenDraft(info.assetPath); + AssetDraftDocuments.Draft draft = documents.OpenDraft(info.assetPath); drafts.Add(draft); } @@ -512,7 +515,7 @@ private sealed class SelectionEdits( IReadOnlyDictionary materials ) : IInspectionPropertyEditService { - /// + /// public bool ChangeProperty( object owner, string propertyName, diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs index b15ea1e28..ca0991881 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/ShaderPropertyInspector.cs @@ -86,7 +86,7 @@ public static void Draw( () => value.sampler, next => { - var candidate = value; + MaterialValue candidate = value; candidate.kind = MaterialValueKind.Texture; candidate.sampler = (RenderSamplerState)next!; setter(candidate); @@ -172,7 +172,9 @@ MaterialValue target } else if (edited.kind == MaterialValueKind.Matrix) { - Matrix b = before.matrix, e = edited.matrix, t = target.matrix; + Matrix b = before.matrix; + Matrix e = edited.matrix; + Matrix t = target.matrix; target.matrix = new( Merge(b.m11, e.m11, t.m11), Merge(b.m12, e.m12, t.m12), @@ -194,7 +196,9 @@ MaterialValue target } else { - Vector4 b = before.vector, e = edited.vector, t = target.vector; + Vector4 b = before.vector; + Vector4 e = edited.vector; + Vector4 t = target.vector; target.vector = new(Merge(b.x, e.x, t.x), Merge(b.y, e.y, t.y), Merge(b.z, e.z, t.z), Merge(b.w, e.w, t.w)); } diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs index 83692563e..9f6abe126 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs @@ -4,6 +4,7 @@ using Inno.Editor.Inspection; using Inno.Editor.Rendering; using Inno.Editor.Shaders; +using Inno.Rendering.Shaders; namespace Inno.Editor.Shaders.ImGui; @@ -221,7 +222,7 @@ bool readOnly public T Read( string key, T defaultValue - ) => Inno.Rendering.Shaders.ShaderGraphDocument.Read(m_node, key, defaultValue, m_serialization, m_context); + ) => ShaderGraphDocument.Read(m_node, key, defaultValue, m_serialization, m_context); /// /// Records an unsaved draft edit through shared history; only an explicit document save applies it to the asset. @@ -247,7 +248,7 @@ public void Write( { throw new InvalidOperationException("Copy this installed Shader into the project before editing."); } - m_write(key, Inno.Rendering.Shaders.ShaderGraphDocument.Encode(value, m_serialization, m_context), mergeKey); + m_write(key, ShaderGraphDocument.Encode(value, m_serialization, m_context), mergeKey); } /// @@ -293,7 +294,7 @@ T defaultValue private sealed class Edits(Action apply) : IInspectionPropertyEditService { - /// + /// public bool ChangeProperty( object owner, string propertyName, diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs index b8f2732c8..ee722cdb2 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Previews/ShaderPreviews.cs @@ -143,10 +143,20 @@ float logicalSize } int pixels = Math.Clamp((int)MathF.Ceiling(logicalSize * ImGuiApi.GetWindowDpiScale()), 1, 2048); - var context = new ShaderPreviewContext(new(state.viewportId), material, artifact, definition, state, pixels, pixels); + var context = new ShaderPreviewContext( + new(state.viewportId), + material, + artifact, + definition, + state, + pixels, + pixels + ); EditorViewportLayer layer = m_registry.providers[contracts[0]].CreateLayer(context); - if (m_previews.TryRender(new(state.viewportId, pixels, pixels, RenderTextureFormat.RGBA8, [layer]), out var handle)) - { + if (m_previews.TryRender( + new(state.viewportId, pixels, pixels, RenderTextureFormat.RGBA8, [layer]), + out EditorPreviewHandle handle + )) { m_previews.Draw(handle, new(logicalSize, logicalSize)); } else diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs index ddd2e7cbe..7ec9de12d 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Commands/CommandSearchModule.cs @@ -46,7 +46,7 @@ internal bool Draw(EditorUiSession ui) object? target = m_target is RuntimeIdentity id && interactions.TryResolveIdentity(id, out IdentityObject? live) ? live : null; EditorInteraction local = interactions.For(m_area, target); EditorMenuModel commands = local.BuildCommands(); - var localItems = Leaves(commands.items).Where(item => !globalIds.Contains(item.actionId)).ToArray(); + EditorMenuItem[] localItems = Leaves(commands.items).Where(item => !globalIds.Contains(item.actionId)).ToArray(); return ui.menus.DrawSearchItems(local, localItems, search); void Collect(IReadOnlyList items) { diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs index 39520cea2..7ff735d23 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportModal.cs @@ -120,7 +120,7 @@ private static bool BeginFields(string id) id, 2, ImGuiTableFlags.SizingStretchProp | ImGuiTableFlags.NoSavedSettings | ImGuiTableFlags.NoPadOuterX, - default(Vector2), + default, 0f ); diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs index 5ee0a48ae..626dbd9e9 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/GameExportProgressModal.cs @@ -1,5 +1,6 @@ using System.Numerics; using Inno.Editor.Core; +using Inno.Editor.Exporting; using Inno.Editor.ImGui; using Inno.Editor.ImGui.ImGuiWidget; @@ -12,18 +13,18 @@ internal sealed class GameExportProgressModal(ExportWindowModule window) : Edito private DialogLayout m_layout; private long m_operation; - /// + /// public override bool isVisible => window.isGameProgressVisible; - /// + /// public override bool allowScrolling => false; - /// + /// protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize ) { - var snapshot = window.progress; + EditorExportProgress snapshot = window.progress; m_operation = snapshot.operationId; m_content = new( string.IsNullOrEmpty(snapshot.error) ? snapshot.status : snapshot.error, @@ -37,7 +38,7 @@ Vector2 availableContentSize return m_layout.size; } - /// + /// protected override void OnDraw(EditorContext context) { if (EditorUiSession.current.widgets.DrawDialog(m_content, m_layout)) diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs index 1a822089b..8abeea815 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/PluginExportModal.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Numerics; using Inno.Editor.Core; +using Inno.Editor.Exporting; using Inno.Editor.ImGui; using Ui = Inno.Editor.ImGui.ImGui; @@ -24,21 +25,21 @@ internal sealed class PluginExportModal(ExportWindowModule window) : EditorModal private long m_operation; private float m_wrapWidth; - /// + /// public override bool isVisible => window.isPluginVisible; - /// + /// public override bool canMove => true; - /// + /// public override Vector2 initialSize => new(680f, 0f); - /// + /// protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize ) { - var progress = window.progress; + EditorExportProgress progress = window.progress; m_operation = progress.operationId; m_identity = $"{window.pluginId} (from Project ID)"; m_name = window.pluginDisplayName; @@ -61,7 +62,7 @@ Vector2 availableContentSize return new Vector2(MathF.Max(width, checkboxWidth), height); } - /// + /// protected override void OnDraw(EditorContext context) => Present(true, m_wrapWidth); private float Present( @@ -75,7 +76,7 @@ float width { m_rows.Clear(); } - var layout = Ui.GetLayout(); + EditorUiLayout layout = Ui.GetLayout(); float gap = layout.itemSpacing.Y; float frame = Ui.MeasureText("M").Y + layout.framePadding.Y * 2f; Text(C_DESCRIPTION, true); diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs index 28a7e7625..c35236284 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Scripting/ScriptCompilationModal.cs @@ -13,25 +13,25 @@ internal sealed class ScriptCompilationModal(IEditorScriptCompilation scripting) private DialogLayout m_layout; private long m_operation; - /// + /// public override bool isVisible => scripting.requiresExclusiveProgress; - /// + /// public override bool allowScrolling => false; - /// + /// protected override Vector2? OnPrepare( EditorContext context, Vector2 availableContentSize ) { - var snapshot = scripting.progress; + EditorScriptCompilationProgress snapshot = scripting.progress; m_operation = snapshot.operationId; m_content = new(snapshot.status, snapshot.fraction, actionLabel: "Cancel", actionEnabled: snapshot.canCancel, cancelOnEscape: true); m_layout = EditorUiSession.current.widgets.MeasureDialog(m_content, availableContentSize); return m_layout.size; } - /// + /// protected override void OnDraw(EditorContext context) { if (EditorUiSession.current.widgets.DrawDialog(m_content, m_layout)) diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs index e33260a5e..9bdf3c410 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs @@ -1,5 +1,6 @@ using System; using Inno.Editor.Core; +using Inno.Editor.ImGui; using Inno.Editor.Settings; using Inno.Platform; @@ -100,7 +101,7 @@ protected override void OnDraw(EditorSettingObject setting) } if (rate == 0) { - EditorUI.current.widgets.ColoredText(Inno.Editor.ImGui.EditorPalette.textDisabled, "Unlimited"); + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Unlimited"); } } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs index ef379f21d..8361e20ec 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs @@ -139,7 +139,7 @@ float iconSlotWidth new Vector2(origin.X + iconSlotWidth * 0.5f, origin.Y + lineHeight * 0.5f), color ); - Inno.Editor.ImGui.ImGui.DrawText(new Vector2(origin.X + iconSlotWidth + style.itemInnerSpacing.X, origin.Y), color, text); + Ui.DrawText(new Vector2(origin.X + iconSlotWidth + style.itemInnerSpacing.X, origin.Y), color, text); } } diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs index ad2d29b9a..24696e1be 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/EditorZoomModule.cs @@ -8,12 +8,12 @@ namespace Inno.Editor.Workbench; /// /// Applies the configured actual UI size and preserves project-local zoom multiples around it. /// -/// -/// The host-owned presentation session receiving the selected scale. -/// /// /// The validated configuration that controls this operation. /// +/// +/// The host-owned presentation session receiving the selected scale. +/// [EditorModule("editor-zoom", order: 10)] internal sealed class EditorZoomModule( EditorSettings settings, @@ -54,10 +54,7 @@ protected override void OnStart(EditorContext context) /// /// The context that supplies state and services for this operation. /// - protected override void OnStop(EditorContext context) - { - m_settingsSubscription?.Dispose(); - } + protected override void OnStop(EditorContext context) => m_settingsSubscription?.Dispose(); /// /// Captures the zoom step relative to the configured actual UI size. @@ -65,10 +62,7 @@ protected override void OnStop(EditorContext context) /// /// The project-local module state that receives the zoom step. /// - protected override void Capture(EditorState state) - { - state.Set("step", m_zoomStep); - } + protected override void Capture(EditorState state) => state.Set("step", m_zoomStep); /// /// Restores the bounded project-local zoom step after settings initialize. diff --git a/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs b/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs index 55dc29b29..9a708118a 100644 --- a/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs +++ b/src/composition/player/Inno.Player.Runtime/Deployment/StaticPlayerModuleActivator.cs @@ -58,7 +58,7 @@ IReadOnlyDictionary> assemblies m_sources = sources.AsReadOnly(); } - /// + /// public void Activate( ModuleHost modules, GameCodeDeployment deployment diff --git a/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs b/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs index 486ec9bc2..314e3ab94 100644 --- a/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs +++ b/src/composition/player/Inno.Player.Runtime/GamePlayerHost.cs @@ -175,7 +175,7 @@ protected override void OnEvent(Event evnt) } } - /// + /// protected override void OnSuspensionChanged(bool isSuspended) => session.events.Emit(new ApplicationSuspensionChangedEvent(isSuspended)); @@ -292,7 +292,7 @@ PlayerLaunchOptions options { using ContentReadLease document = m_content!.Acquire(new ContentKey(SettingsFileNames.project)); using Stream documentStream = document.OpenRead(); - byte[] documentBytes = new byte[checked((int)document.entry.length)]; + var documentBytes = new byte[checked((int)document.entry.length)]; documentStream.ReadExactly(documentBytes); m_settings = new ProjectSettingsStore( new ReadOnlyByteDocumentStore(document.entry.key.value!, documentBytes), diff --git a/src/composition/player/Inno.Player.Runtime/PlayerApplication.cs b/src/composition/player/Inno.Player.Runtime/PlayerApplication.cs index cfe87c5e2..65a21350e 100644 --- a/src/composition/player/Inno.Player.Runtime/PlayerApplication.cs +++ b/src/composition/player/Inno.Player.Runtime/PlayerApplication.cs @@ -21,10 +21,6 @@ public static class PlayerApplication /// /// Zero after orderly shutdown; startup, execution and retirement failures propagate. /// - /// - /// Hosts must preserve their owner thread across asynchronous startup and frame callbacks using - /// their synchronization context. A blocking host can use OwnerThreadExecution.Run. - /// /// /// Options or a required host service is null. /// @@ -37,6 +33,10 @@ public static class PlayerApplication /// /// A host factory does not provide its required product, or runtime startup or retirement fails. /// + /// + /// Hosts must preserve their owner thread across asynchronous startup and frame callbacks using + /// their synchronization context. A blocking host can use OwnerThreadExecution.Run. + /// public static async Task RunAsync( PlayerLaunchOptions options, CancellationToken cancellationToken = default diff --git a/src/composition/shell/Inno.Shell/Shell.cs b/src/composition/shell/Inno.Shell/Shell.cs index 7b27a8bf6..036f65679 100644 --- a/src/composition/shell/Inno.Shell/Shell.cs +++ b/src/composition/shell/Inno.Shell/Shell.cs @@ -65,7 +65,7 @@ ShellOptions options m_adapterSelection = options.adapters; m_suspendWhenHidden = options.suspendWhenHidden; this.options = options; - framePacing = new FramePacingOptions { verticalSync = options.verticalSync }; + this.framePacing = new FramePacingOptions { verticalSync = options.verticalSync }; } /// diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs b/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs index 01bbae2a2..80656367c 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationBindingRuntime.cs @@ -150,7 +150,7 @@ protected override Snapshot Build(TypeCacheSnapshot types) $"Animation provider '{declaration.id}' requires a concrete public parameterless implementation." ); } - var key = (declaration.bindingId, declaration.kind); + (AnimationBindingId bindingId, AnimationValueKind kind) key = (declaration.bindingId, declaration.kind); if (!ids.Add(declaration.id) || result.providers.ContainsKey(key)) { throw new InvalidOperationException( diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs b/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs index c7ed15dd9..60578449e 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationClipSnapshot.cs @@ -6,13 +6,13 @@ internal sealed class AnimationClipSnapshot { private AnimationClipSnapshot(AnimationClipAsset clip) { - duration = clip.duration; - tracks = clip.tracks.Select(static track => new AnimationTrack( + this.duration = clip.duration; + this.tracks = clip.tracks.Select(static track => new AnimationTrack( track.bindingId, track.interpolation, track.keyframes )).ToArray(); - events = clip.events.Select(static marker => new AnimationEventMarker + this.events = clip.events.Select(static marker => new AnimationEventMarker { time = marker.time, eventId = marker.eventId, diff --git a/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs b/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs index 3c44208ed..bd322a7c0 100644 --- a/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs +++ b/src/content/animation/Inno.Animation.Runtime/AnimationRuntime.cs @@ -55,7 +55,7 @@ public sealed class AnimationRuntime : RuntimeSubsystem, IAnimationService public AnimationRuntime( EventDispatcher events, IAnimationBindingSink bindings, - int maxPlaybacks = 16384 + int maxPlaybacks = 16_384 ) { m_events = events ?? throw new ArgumentNullException(nameof(events)); m_bindings = bindings ?? throw new ArgumentNullException(nameof(bindings)); @@ -70,6 +70,9 @@ public AnimationRuntime( /// /// Valid clip to sample until completion or explicit stop. /// + /// + /// The weak destination or explicit sampling-only policy. + /// /// /// A generation-checked handle owned by this runtime. /// @@ -82,9 +85,6 @@ public AnimationRuntime( /// /// Thrown when the clip is structurally invalid. /// - /// - /// The weak destination or explicit sampling-only policy. - /// public AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target @@ -96,6 +96,9 @@ AnimationTarget target /// /// Valid clip to sample until completion or explicit stop. /// + /// + /// The weak destination or explicit sampling-only policy. + /// /// /// Playback options validated before a runtime slot is allocated. /// @@ -114,9 +117,6 @@ AnimationTarget target /// /// Thrown when the clip is structurally invalid. /// - /// - /// The weak destination or explicit sampling-only policy. - /// public AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target, @@ -184,7 +184,7 @@ public bool Stop(AnimationPlaybackHandle handle) { return false; } - var identity = m_handles.Decode(handle); + (int slot, uint generation) identity = m_handles.Decode(handle); Retire(identity.slot, playback); return true; } @@ -432,7 +432,7 @@ private static void Sample( { AnimationTrack track = playback.clip.tracks[index]; var binding = new AnimationBindingId(track.bindingId); - var destination = (playback.target, binding); + (AnimationTarget target, AnimationBindingId binding) destination = (playback.target, binding); AnimationValue value = SampleTrack(track, playback.time); if (!samples.TryGetValue(destination, out BlendAccumulator accumulator) || playback.options.layer > accumulator.layer @@ -483,7 +483,7 @@ private bool TryGetPlayback( [NotNullWhen(true)] out Playback? playback ) { playback = null; - var identity = m_handles.Decode(handle); + (int slot, uint generation) identity = m_handles.Decode(handle); if (m_disposed || !handle.isValid || handle.runtimeGeneration != m_runtimeGeneration || identity.slot < 0 || identity.slot >= m_playbacks.Count ) { diff --git a/src/content/animation/Inno.Animation/Animation.cs b/src/content/animation/Inno.Animation/Animation.cs index cab9c35bb..4e89153c7 100644 --- a/src/content/animation/Inno.Animation/Animation.cs +++ b/src/content/animation/Inno.Animation/Animation.cs @@ -43,12 +43,12 @@ public static class Animation /// /// Valid imported animation clip. /// - /// - /// A generation-checked playback handle. - /// /// /// The weak destination or explicit sampling-only policy. /// + /// + /// A generation-checked playback handle. + /// public static AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target @@ -60,15 +60,15 @@ AnimationTarget target /// /// Valid imported animation clip. /// + /// + /// The weak destination or explicit sampling-only policy. + /// /// /// Playback and blend options. /// /// /// A generation-checked playback handle. /// - /// - /// The weak destination or explicit sampling-only policy. - /// public static AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target, diff --git a/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs b/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs index a0498752b..bd84f04ce 100644 --- a/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs +++ b/src/content/animation/Inno.Animation/AnimationPlaybackAllocator.cs @@ -23,7 +23,7 @@ public AnimationPlaybackAllocator() { throw new InvalidOperationException("Animation owner generations are exhausted."); } - generation = (uint)next; + this.generation = (uint)next; } /// @@ -55,7 +55,7 @@ uint slotGeneration { throw new ArgumentOutOfRangeException(nameof(slotGeneration)); } - return new AnimationPlaybackHandle(((ulong)slotGeneration << 32) | ((uint)slot + 1U), generation); + return new AnimationPlaybackHandle(((ulong)slotGeneration << 32) | ((uint)slot + 1u), generation); } /// @@ -74,6 +74,6 @@ uint slotGeneration return (-1, 0); } uint encodedSlot = (uint)(handle.value & uint.MaxValue); - return (checked((int)(encodedSlot - 1U)), (uint)(handle.value >> 32)); + return (checked((int)(encodedSlot - 1u)), (uint)(handle.value >> 32)); } } diff --git a/src/content/animation/Inno.Animation/AnimationTypes.cs b/src/content/animation/Inno.Animation/AnimationTypes.cs index 550b22510..51f5b09dc 100644 --- a/src/content/animation/Inno.Animation/AnimationTypes.cs +++ b/src/content/animation/Inno.Animation/AnimationTypes.cs @@ -325,15 +325,15 @@ public readonly record struct AnimationSample /// /// Creates one final animation sample. /// + /// + /// The weak destination or explicit sampling-only policy. + /// /// /// Stable target binding. /// /// /// Final blended value. /// - /// - /// The weak destination or explicit sampling-only policy. - /// public AnimationSample( AnimationTarget target, AnimationBindingId binding, diff --git a/src/content/animation/Inno.Animation/IAnimationService.cs b/src/content/animation/Inno.Animation/IAnimationService.cs index ccd9d7997..cc0430a11 100644 --- a/src/content/animation/Inno.Animation/IAnimationService.cs +++ b/src/content/animation/Inno.Animation/IAnimationService.cs @@ -14,12 +14,12 @@ public interface IAnimationService /// /// Valid imported animation clip. /// - /// - /// A generation-checked playback handle. - /// /// /// The weak destination or explicit sampling-only policy. /// + /// + /// A generation-checked playback handle. + /// AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target @@ -31,15 +31,15 @@ AnimationTarget target /// /// Valid imported animation clip. /// + /// + /// The weak destination or explicit sampling-only policy. + /// /// /// Playback clock, speed, blend, layer, and looping policy. /// /// /// A generation-checked playback handle. /// - /// - /// The weak destination or explicit sampling-only policy. - /// AnimationPlaybackHandle Play( AnimationClipAsset clip, AnimationTarget target, diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetCacheOptions.cs b/src/content/assets/Inno.Assets.Pipeline/AssetCacheOptions.cs index 292a9837b..5288217cf 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetCacheOptions.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetCacheOptions.cs @@ -24,11 +24,9 @@ public readonly struct AssetCacheOptions /// The default cache options. /// public static AssetCacheOptions CreateDefault() + => new AssetCacheOptions { - return new AssetCacheOptions - { - maximumSizeBytes = 4L * 1024 * 1024 * 1024, - garbageCollectionGracePeriod = TimeSpan.FromDays(7) - }; - } + maximumSizeBytes = 4L * 1024 * 1024 * 1024, + garbageCollectionGracePeriod = TimeSpan.FromDays(7) + }; } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs index b77ba5163..f2d6b9161 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Artifacts.cs @@ -18,7 +18,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Tries to resolve a named artifact output. @@ -115,10 +115,6 @@ public AssetRuntimeContentInfo ExportRuntimeArtifacts(string destinationContentR /// /// Exports a runtime-only artifact snapshot on a worker without loading artifact files into memory. /// - /// - /// Keeps generation admission and serialization pinned until the worker completes, fails or cancels. - /// A pending or faulted generation cannot start a new export. - /// /// /// The empty destination that receives the runtime asset database. /// @@ -135,6 +131,10 @@ public AssetRuntimeContentInfo ExportRuntimeArtifacts(string destinationContentR /// /// Thrown when cancellation is requested before export completes. /// + /// + /// Keeps generation admission and serialization pinned until the worker completes, fails or cancels. + /// A pending or faulted generation cannot start a new export. + /// [ScriptingApiIgnore] public async Task ExportRuntimeArtifactsAsync( string destinationContentRoot, diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs index bdfa855d6..e8647e18f 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs @@ -18,7 +18,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Reconciles source files, generated files and the persistent catalog. @@ -99,9 +99,7 @@ public IReadOnlyList GetFileSystemEntries(bool includeDirectorie public bool TryGetFileSystemEntry( AssetPath path, out AssetFileEntry entry - ) { - return GetFileSystem().TryGetEntry(path, out entry); - } + ) => GetFileSystem().TryGetEntry(path, out entry); private void ApplySourceChanges( IReadOnlyList changes, @@ -277,7 +275,7 @@ bool requiresFullRescan AssetChangeKind kind = moved ? AssetChangeKind.Moved : deleted - ? System.IO.File.Exists(Path.Combine(assetRoot, change.relativePath + ".imeta")) + ? File.Exists(Path.Combine(assetRoot, change.relativePath + ".imeta")) ? AssetChangeKind.Missing : AssetChangeKind.Removed : change.changeType.HasFlag(WatcherChangeTypes.Created) diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs index c74eab238..d6867432f 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Discovery.cs @@ -18,7 +18,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Ends initial authoring extension discovery and strictly retries dependent imports. diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs index 25f2e1654..332a3ca6f 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Loading.cs @@ -18,7 +18,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Loads a canonical asset by isolated source path. diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs index dc8f5d64c..f980c82a8 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs @@ -18,7 +18,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Imports one source asset from an isolated source mount. @@ -185,15 +185,15 @@ AssetPath target string absoluteSource = Path.Combine(assetRoot, sourcePath); string absoluteTarget = Path.Combine(assetRoot, targetPath); bool isDirectory = Directory.Exists(absoluteSource); - if (!isDirectory && !System.IO.File.Exists(absoluteSource)) + if (!isDirectory && !File.Exists(absoluteSource)) { throw new FileNotFoundException($"Asset source '{sourcePath}' does not exist.", absoluteSource); } - if (Directory.Exists(absoluteTarget) || System.IO.File.Exists(absoluteTarget)) + if (Directory.Exists(absoluteTarget) || File.Exists(absoluteTarget)) { throw new IOException($"Asset move target '{targetPath}' already exists."); } - if (System.IO.File.Exists(absoluteTarget + ".imeta")) + if (File.Exists(absoluteTarget + ".imeta")) { throw new IOException($"Asset move target metadata '{targetPath}.imeta' already exists."); } @@ -248,7 +248,7 @@ public void Delete(AssetPath path) string absoluteSource = Path.Combine(assetRoot, sourcePath); bool isDirectory = Directory.Exists(absoluteSource); - if (!isDirectory && !System.IO.File.Exists(absoluteSource)) + if (!isDirectory && !File.Exists(absoluteSource)) { throw new FileNotFoundException($"Asset source '{sourcePath}' does not exist.", absoluteSource); } @@ -271,9 +271,9 @@ public void Delete(AssetPath path) try { MovePhysicalSource(absoluteSource, stagedSource, isDirectory); - if (System.IO.File.Exists(sourceMeta)) + if (File.Exists(sourceMeta)) { - System.IO.File.Move(sourceMeta, stagedMeta); + File.Move(sourceMeta, stagedMeta); } loader.ApplySourceChanges(changes); fileSystem.Refresh(); @@ -329,11 +329,11 @@ public void CreateDirectory(AssetPath path) $"Asset directory parent '{Path.GetDirectoryName(sourcePath)}' does not exist." ); } - if (Directory.Exists(absolutePath) || System.IO.File.Exists(absolutePath)) + if (Directory.Exists(absolutePath) || File.Exists(absolutePath)) { throw new IOException($"Asset directory target '{sourcePath}' already exists."); } - if (System.IO.File.Exists(absolutePath + ".imeta")) + if (File.Exists(absolutePath + ".imeta")) { throw new IOException($"Asset directory target metadata '{sourcePath}.imeta' already exists."); } @@ -360,9 +360,9 @@ public void CreateDirectory(AssetPath path) { Directory.Delete(absolutePath, recursive: true); } - if (System.IO.File.Exists(absolutePath + ".imeta")) + if (File.Exists(absolutePath + ".imeta")) { - System.IO.File.Delete(absolutePath + ".imeta"); + File.Delete(absolutePath + ".imeta"); } loader.Rescan(); fileSystem.Refresh(); @@ -403,7 +403,7 @@ bool isDirectory } else { - System.IO.File.Move(sourcePath, targetPath); + File.Move(sourcePath, targetPath); } } @@ -414,8 +414,8 @@ bool isDirectory ) { try { - bool targetExists = isDirectory ? Directory.Exists(targetPath) : System.IO.File.Exists(targetPath); - bool sourceExists = isDirectory ? Directory.Exists(sourcePath) : System.IO.File.Exists(sourcePath); + bool targetExists = isDirectory ? Directory.Exists(targetPath) : File.Exists(targetPath); + bool sourceExists = isDirectory ? Directory.Exists(sourcePath) : File.Exists(sourcePath); if (targetExists && !sourceExists) { MovePhysicalSource(targetPath, sourcePath, isDirectory); @@ -433,9 +433,9 @@ string targetPath ) { try { - if (System.IO.File.Exists(targetPath) && !System.IO.File.Exists(sourcePath)) + if (File.Exists(targetPath) && !File.Exists(sourcePath)) { - System.IO.File.Move(targetPath, sourcePath); + File.Move(targetPath, sourcePath); } } catch @@ -449,7 +449,7 @@ private void RestoreStagedDeletion( string stagedSource, bool isDirectory ) { - if (isDirectory ? Directory.Exists(stagedSource) : System.IO.File.Exists(stagedSource)) + if (isDirectory ? Directory.Exists(stagedSource) : File.Exists(stagedSource)) { Directory.CreateDirectory(Path.GetDirectoryName(sourcePath)!); MovePhysicalSource(stagedSource, sourcePath, isDirectory); @@ -460,12 +460,12 @@ private void RestoreStagedMetadata( string metaPath, string stagedMetaPath ) { - if (!System.IO.File.Exists(stagedMetaPath)) + if (!File.Exists(stagedMetaPath)) { return; } Directory.CreateDirectory(Path.GetDirectoryName(metaPath)!); - System.IO.File.Move(stagedMetaPath, metaPath); + File.Move(stagedMetaPath, metaPath); } private static void DeleteTransactionDirectorySafely(string transactionRoot) diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs index 80831f51e..9cbf272de 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Retirement.cs @@ -18,7 +18,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetPipeline +public sealed partial class AssetPipeline { /// /// Releases watchers, catalog participants, canonical objects, and rebuildable staging state. diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs index b31700217..ee6195938 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.cs @@ -123,6 +123,9 @@ public AssetPropertySnapshot CaptureProperties(TValue value) /// /// Restores serialized properties to the existing asset object. /// + /// + /// Serialized asset object type receiving restored properties. + /// /// /// The stable type id consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. /// @@ -132,9 +135,6 @@ public AssetPropertySnapshot CaptureProperties(TValue value) /// /// The existing target that receives the validated result. /// - /// - /// Serialized asset object type receiving restored properties. - /// public void RestoreProperties( Guid stableTypeId, byte[] propertyData, @@ -185,12 +185,12 @@ TValue target /// /// The identity allocator that owns every canonical asset in this pipeline. /// - /// - /// The explicitly owned router receiving asset pipeline diagnostics. - /// /// /// The diagnostic hub that owns source database and asset processing reports. /// + /// + /// The explicitly owned router receiving asset pipeline diagnostics. + /// /// /// The asset source, artifact and watcher configuration. /// @@ -240,12 +240,12 @@ AssetPipelineOptions options { throw new ArgumentException("The project asset source mount must be writable.", nameof(options)); } - assetRoot = projectMount.rootPath; - libraryRoot = Path.GetFullPath(options.libraryRoot); + this.assetRoot = projectMount.rootPath; + this.libraryRoot = Path.GetFullPath(options.libraryRoot); DeleteCandidateCatalogRoots(libraryRoot); - artifactRoot = Path.Combine(libraryRoot, "Artifacts"); - sourceMounts = Array.AsReadOnly(mounts.ToArray()); - AssetLoader loader = new( + this.artifactRoot = Path.Combine(libraryRoot, "Artifacts"); + this.sourceMounts = Array.AsReadOnly(mounts.ToArray()); + var loader = new AssetLoader( types, serialization, identities, @@ -260,7 +260,7 @@ AssetPipelineOptions options { loader.DeferUnavailableExtensions(); } - AssetFileSystem fileSystem = new( + var fileSystem = new AssetFileSystem( mounts, autoStart: false, options.fileWatcherFlushDelayMs, @@ -282,7 +282,7 @@ AssetPipelineOptions options m_cacheOptions = options.cacheOptions; m_options = options with { sourceMounts = mounts }; m_lastArtifactCollectionTimestamp = 0; - isInitialized = true; + this.isInitialized = true; try { loader.Rescan(); diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs index 7dc04020c..1f0dea4bb 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipelineOptions.cs @@ -90,7 +90,7 @@ string libraryRoot enableFileSystemWatcher = true, fileWatcherFlushDelayMs = 80, sourcePolicy = AssetSourcePolicy.defaultPolicy, - sourceMounts = [new AssetSourceMount(Inno.Assets.AssetSourceId.project, assetRoot, isReadOnly: false)], + sourceMounts = [new AssetSourceMount(AssetSourceId.project, assetRoot, isReadOnly: false)], cacheOptions = AssetCacheOptions.CreateDefault() }; } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs b/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs index b737d7771..4fa23e95c 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetSourceMountTransaction.cs @@ -135,7 +135,7 @@ out AssetInfo? info return candidateLoader.TryGetInfo(path, out info); } - /// + /// [ScriptingApiIgnore] public ArtifactLease AcquireArtifact( Guid persistentId, diff --git a/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs index f0211b5cd..53dba09d6 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs @@ -171,8 +171,8 @@ internal AssetSourceSnapshot( bool readOnly ) { m_bytes = bytes; - contentHash = hash; - isReadOnly = readOnly; + this.contentHash = hash; + this.isReadOnly = readOnly; } /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs index 767836c04..b2143f625 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs @@ -4,15 +4,27 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetArtifactManifest : ISerializable { - [SerializableProperty] internal string key { get; set; } = string.Empty; - [SerializableProperty] internal AssetArtifactOutputData[] outputs { get; set; } = []; + [SerializableProperty] + internal string key { get; set; } = string.Empty; + + [SerializableProperty] + internal AssetArtifactOutputData[] outputs { get; set; } = []; } internal struct AssetArtifactOutputData { - [SerializableProperty] internal string name { get; set; } - [SerializableProperty] internal string fileName { get; set; } - [SerializableProperty] internal string contentHash { get; set; } - [SerializableProperty] internal long length { get; set; } - [SerializableProperty] internal AssetDeploymentScope deploymentScope { get; set; } + [SerializableProperty] + internal string name { get; set; } + + [SerializableProperty] + internal string fileName { get; set; } + + [SerializableProperty] + internal string contentHash { get; set; } + + [SerializableProperty] + internal long length { get; set; } + + [SerializableProperty] + internal AssetDeploymentScope deploymentScope { get; set; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs index af4276bb6..0de29b1bb 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactStore.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Security.Cryptography; using System.Text; +using System.Threading; using Inno.Assets; using Inno.Core.IO; using Inno.Core.Serialization; @@ -141,18 +142,16 @@ out AssetArtifactInfo? artifact internal byte[] Read( AssetArtifactKey key, string outputName - ) { - return TryGet(key, outputName, out AssetArtifactInfo? artifact) && artifact is not null - ? ReadOutputBytes(artifact, ResolveOutput(artifact)) - : []; - } + ) => TryGet(key, outputName, out AssetArtifactInfo? artifact) && artifact is not null + ? ReadOutputBytes(artifact, ResolveOutput(artifact)) + : []; internal Func CreateReadFactory(AssetArtifactInfo artifact) { string path = ResolveOutput(artifact); return () => { - FileStream input = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); + var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); try { if (input.Length != artifact.length @@ -331,7 +330,7 @@ private static AssetArtifactKey ComputeKey( IReadOnlyDictionary> outputs, IReadOnlySet? authoringOutputs ) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); Append(hash, "Inno.AssetArtifact"); Append(hash, inputFingerprint); foreach (KeyValuePair> output in outputs @@ -348,7 +347,7 @@ internal AssetArtifactKey ExportRuntime( AssetArtifactKey key, AssetArtifactStore destination, SerializationGeneration? serialization, - System.Threading.CancellationToken cancellationToken + CancellationToken cancellationToken ) { AssetArtifactManifest manifest = ReadManifest(key, serialization) ?? throw new InvalidDataException($"Artifact bundle '{key}' has no manifest."); diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs index 5109418aa..d9aa78465 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetCatalogCandidate.cs @@ -70,10 +70,7 @@ public void Dispose() GC.SuppressFinalize(this); } - private void EnsureOpen() - { - ObjectDisposedException.ThrowIf(m_disposed, this); - } + private void EnsureOpen() => ObjectDisposedException.ThrowIf(m_disposed, this); private static void DeleteCandidateRoot(string candidateLibraryRoot) { diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs index ea31e7293..29e804377 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetExportContext.cs @@ -13,12 +13,12 @@ public sealed class AssetExportContext internal AssetExportContext( TypeCatalog types, SerializationRegistry serialization, - Inno.Assets.IAssetArtifactLookup artifacts + IAssetArtifactLookup artifacts ) { this.types = types ?? throw new ArgumentNullException(nameof(types)); this.serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); this.artifacts = artifacts ?? throw new ArgumentNullException(nameof(artifacts)); - services = new AssetSerializationServices(types, serialization, references: null, dependencySink: null); + this.services = new AssetSerializationServices(types, serialization, references: null, dependencySink: null); } /// @@ -42,5 +42,5 @@ Inno.Assets.IAssetArtifactLookup artifacts /// Gets the owner-bound immutable outputs used to reconstruct editable sources. /// [ScriptingApiIgnore] - public Inno.Assets.IAssetArtifactLookup artifacts { get; } + public IAssetArtifactLookup artifacts { get; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs index 94e0ba061..c6a82dd25 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportContext.cs @@ -69,7 +69,7 @@ internal AssetImportContext( Func> sourceReader, IAssetArtifactLookup artifacts ) { - assetPath = AssetPath.Parse(relativePath ?? throw new ArgumentNullException(nameof(relativePath))); + this.assetPath = AssetPath.Parse(relativePath ?? throw new ArgumentNullException(nameof(relativePath))); this.absolutePath = absolutePath ?? throw new ArgumentNullException(nameof(absolutePath)); this.sourceBytes = sourceBytes; this.sourceHash = sourceHash ?? throw new ArgumentNullException(nameof(sourceHash)); @@ -77,7 +77,7 @@ IAssetArtifactLookup artifacts this.types = types ?? throw new ArgumentNullException(nameof(types)); this.serialization = serialization ?? throw new ArgumentNullException(nameof(serialization)); this.references = references ?? throw new ArgumentNullException(nameof(references)); - services = new AssetSerializationServices( + this.services = new AssetSerializationServices( types, serialization, references, @@ -176,10 +176,7 @@ string outputName /// /// The decoded text without an optional byte-order mark. /// - public string ReadUtf8Text() - { - return DecodeUtf8(sourceBytes.Span); - } + public string ReadUtf8Text() => DecodeUtf8(sourceBytes.Span); /// /// Reads another source from the same candidate mount snapshot and records it as an import dependency. @@ -244,10 +241,7 @@ public void DependsOnAsset(AssetPath path) /// /// The persistent dependency descriptor. /// - public void DependsOnAsset(AssetDependency dependency) - { - m_runtimeDependencies.Add(dependency); - } + public void DependsOnAsset(AssetDependency dependency) => m_runtimeDependencies.Add(dependency); /// /// Resolves and declares a strongly typed runtime asset dependency during import. diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs index fd4d5b348..911dc288b 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Catalog.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Creates an isolated source-mount and catalog candidate without changing the active catalog. @@ -422,7 +422,7 @@ private void RemoveRecordLocked( { return record.asset.GetType(); } - TypeRef typeRef = new(record.stableTypeId); + var typeRef = new TypeRef(record.stableTypeId); return m_types.TryResolve(typeRef, out Type? type) && typeof(AssetObject).IsAssignableFrom(type) ? type : m_importers.FindById(record.meta.importerId)?.targetAssetType; diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs index f2db586a3..ffe0b9aef 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Dependencies.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Gets direct or transitive runtime dependencies of an asset. @@ -113,7 +113,7 @@ private void AttachDependenciesLocked(AssetRecord record) private AssetDependency[] ResolveDeclaredDependenciesLocked(AssetImportContext context) { - var result = context.runtimeDependencies.ToDictionary(static value => value.persistentId); + Dictionary result = context.runtimeDependencies.ToDictionary(static value => value.persistentId); foreach (Guid persistentId in result.Keys.ToArray()) { AssetDependency dependency = result[persistentId]; diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs index fa32d6f19..cc81171bb 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Diagnostics.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Captures the current failure identity of every writable source without exposing catalog internals. diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs index c1b5de3a9..dedbdd1a8 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.ImportSettings.cs @@ -116,7 +116,7 @@ string expectedFingerprint { if (metadata is null) { - System.IO.File.Delete(metaPath); + File.Delete(metaPath); } else { @@ -134,7 +134,7 @@ string expectedFingerprint private AssetImporter RequireSettingsImporterLocked(string path) { - if (!System.IO.File.Exists(GetSourcePath(path))) + if (!File.Exists(GetSourcePath(path))) { throw new FileNotFoundException($"Import settings source '{path}' does not exist."); } @@ -270,8 +270,13 @@ exception is IOException or ArgumentException or InvalidOperationException or Fo private sealed class SerializedImportSettings : ISerializable { - [SerializableProperty] internal Guid stableTypeId { get; set; } - [SerializableProperty] internal byte[] properties { get; set; } = []; - [SerializableProperty] internal AssetDependency[] dependencies { get; set; } = []; + [SerializableProperty] + internal Guid stableTypeId { get; set; } + + [SerializableProperty] + internal byte[] properties { get; set; } = []; + + [SerializableProperty] + internal AssetDependency[] dependencies { get; set; } = []; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs index 02facb3e7..166e4eb5f 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Importing.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Imports one isolated source file into metadata and a runtime artifact. @@ -179,8 +179,10 @@ private bool ImportLocked( try { CommitBuildLocked(build, writeSource: false, sourceBytes); - if (m_unavailableImports.Remove(relativePath, out var recovered)) - { + if (m_unavailableImports.Remove( + relativePath, + out (long generation, AssetSourceFileStamp source, AssetSourceFileStamp metadata, string kind, string id) recovered + )) { foreach (string dependent in m_unavailableImports .Where(pair => pair.Value.kind == recovered.kind && pair.Value.id == recovered.id) .Select(static pair => pair.Key) @@ -229,7 +231,10 @@ private bool ImportLocked( private bool IsExtensionImportUnchanged(string relativePath) { - if (!m_unavailableImports.TryGetValue(relativePath, out var previous) + if (!m_unavailableImports.TryGetValue( + relativePath, + out (long generation, AssetSourceFileStamp source, AssetSourceFileStamp metadata, string kind, string id) previous + ) || previous.generation != m_types.current.version || !AssetSourceFileStamp.TryCapture(GetSourcePath(relativePath), out AssetSourceFileStamp sourceStamp) || sourceStamp != previous.source diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs index ad2ffae59..8f836d9a2 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Loading.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Loads a canonical asset by isolated source path. @@ -333,8 +333,12 @@ Type requestedAssetType ) { if (string.IsNullOrEmpty(record.meta.artifactKey) && record.meta.assetStateBytes.Length == 0) { - if (m_activeImports.Count != 0 && m_unavailableImports.TryGetValue(record.relativePath, out var unavailable)) - { + if (m_activeImports.Count != 0 + && m_unavailableImports.TryGetValue( + record.relativePath, + out (long generation, AssetSourceFileStamp source, AssetSourceFileStamp metadata, string kind, string id) unavailable + ) + ) { throw new AssetImportExtensionUnavailableException(unavailable.kind, unavailable.id); } return null; diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs index 99fec9704..a2679a88e 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Recovery.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { private bool IsSourceBackedTypeUnavailableLocked(Guid persistentId) { @@ -102,16 +102,14 @@ void Capture( string path, Guid stableTypeId, byte[] payload - ) { - states.Add( - id, - new SerializedMissingState( - new ReferenceKey(id, "$asset"), - new ReferenceDescriptor(AssetReferenceProtocol.id, id, stableTypeId, lastKnownPath: path), - payload - ) - ); - } + ) => states.Add( + id, + new SerializedMissingState( + new ReferenceKey(id, "$asset"), + new ReferenceDescriptor(AssetReferenceProtocol.id, id, stableTypeId, lastKnownPath: path), + payload + ) + ); }); internal void PreserveMissingRecoveryStates(IReadOnlyList changes) diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs index 1cb1723e4..8b5e72337 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Residency.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Collects unreachable content-addressed artifacts. @@ -40,22 +40,20 @@ sealed partial class AssetLoader public int CollectArtifacts( TimeSpan gracePeriod, long maximumSizeBytes - ) { - return Execute(() => + ) => Execute(() => + { + HashSet reachable = []; + foreach (AssetArtifactKey retained in m_artifactRetention.GetRetainedKeys()) { - HashSet reachable = []; - foreach (AssetArtifactKey retained in m_artifactRetention.GetRetainedKeys()) - { - AddArtifactKey(reachable, retained.value); - } - foreach (AssetRecord record in m_recordsByPath.Values) - { - AddArtifactKey(reachable, record.meta.artifactKey); - AddArtifactKey(reachable, record.meta.lastSuccessfulArtifactKey); - } - return m_artifacts.Collect(reachable, gracePeriod, maximumSizeBytes); - }); - } + AddArtifactKey(reachable, retained.value); + } + foreach (AssetRecord record in m_recordsByPath.Values) + { + AddArtifactKey(reachable, record.meta.artifactKey); + AddArtifactKey(reachable, record.meta.lastSuccessfulArtifactKey); + } + return m_artifacts.Collect(reachable, gracePeriod, maximumSizeBytes); + }); /// /// Tries to resolve a named output from the current artifact bundle. diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs index e3c71bbb7..34b41cfe7 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Retirement.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Stops new loads and releases canonical assets before their registries and diagnostics. @@ -122,7 +122,7 @@ private bool ReleaseRetiredCanonicalAssetsLocked() continue; } bool isCurrent = m_types.TryGetTypeRef(asset.GetType(), out _); - TypeRef persistedType = new(record.stableTypeId); + var persistedType = new TypeRef(record.stableTypeId); if (isCurrent && (record.stableTypeId == Guid.Empty || !m_types.TryResolve(persistedType, out Type? resolvedType) diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs index 58ad739c2..1d60b4ea1 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.RuntimeExport.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Writes a source-free runtime catalog and its exact immutable artifact closure. @@ -123,7 +123,7 @@ private AssetRuntimeContentInfo ExportRuntimeArtifactsLocked( .ToArray(); foreach (AssetRecord record in exported) { - AssetArtifactKey key = new(record.meta.artifactKey); + var key = new AssetArtifactKey(record.meta.artifactKey); if (!m_artifacts.TryGet(key, "asset-state", serialization, out _) || !m_artifacts.TryGet(key, "runtime", serialization, out _) ) { @@ -263,7 +263,7 @@ private void ValidateRuntimeArtifactsLocked() $"Runtime asset '{record.relativePath}' was not successfully imported before export." ); } - AssetArtifactKey key = new(record.meta.artifactKey); + var key = new AssetArtifactKey(record.meta.artifactKey); if (!m_artifacts.TryGet(key, "asset-state", out _) || !m_artifacts.TryGet(key, "runtime", out _) ) { diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs index d809b2ec2..098b33d4d 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.Saving.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Saves an asset back to its current source path. @@ -197,11 +197,9 @@ private byte[] CaptureAssetState(AssetObject asset) private void RestoreAssetState( AssetObject asset, ReadOnlySpan state - ) { - m_serialization.Decode(state, reader => - { - reader.RestoreProperties(asset); - return true; - }, m_serializationContext); - } + ) => m_serialization.Decode(state, reader => + { + reader.RestoreProperties(asset); + return true; + }, m_serializationContext); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs index 4bdb744b8..aa0067956 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceChanges.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { /// /// Reconciles source files, metadata, artifacts and the in-memory catalog. diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs index 9ed8653d9..18a36bc8c 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs @@ -23,7 +23,7 @@ namespace Inno.Assets.Pipeline; -sealed partial class AssetLoader +public sealed partial class AssetLoader { private bool IsStale( AssetRecord record, diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs index 5b32e68fc..bcd86986d 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs @@ -89,6 +89,9 @@ public sealed partial class AssetLoader : IDisposable, IAssetReferenceResolver, /// /// Restores serialized properties to the existing asset object. /// + /// + /// Serialized asset object type receiving restored properties. + /// /// /// The stable type id consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. /// @@ -98,9 +101,6 @@ public sealed partial class AssetLoader : IDisposable, IAssetReferenceResolver, /// /// The existing target that receives the validated result. /// - /// - /// Serialized asset object type receiving restored properties. - /// public void RestoreProperties( Guid stableTypeId, byte[] propertyData, @@ -132,12 +132,12 @@ TValue target /// /// The identity allocator that owns every canonical asset loaded by this instance. /// - /// - /// The explicitly owned router receiving importer and catalog diagnostics. - /// /// /// The diagnostic hub that owns import, build, catalog, and reference reports. /// + /// + /// The explicitly owned router receiving importer and catalog diagnostics. + /// /// /// The absolute source root. /// @@ -179,12 +179,12 @@ [new AssetSourceMount(AssetSourceId.project, assetRoot, isReadOnly: false)], /// /// The identity allocator that owns every canonical asset loaded by this instance. /// - /// - /// The explicitly owned router receiving importer and catalog diagnostics. - /// /// /// The diagnostic hub that owns import, build, catalog, and reference reports. /// + /// + /// The explicitly owned router receiving importer and catalog diagnostics. + /// /// /// Complete isolated source mount snapshot. /// @@ -279,7 +279,7 @@ internal AssetLoader( m_buildProcessors = new AssetBuildProcessorRegistry(types); m_mounts = byId; m_runtimeArtifactsOnly = runtimeArtifactsOnly; - assetRoot = project.rootPath; + this.assetRoot = project.rootPath; this.libraryRoot = Path.GetFullPath(libraryRoot); foreach (AssetSourceMount mount in mounts) { @@ -356,8 +356,7 @@ internal void ActivateExtensionDiscovery() /// when the importer registry changed. /// public bool RefreshRegistries() - { - return Execute(() => + => Execute(() => { long version = m_importers.snapshotVersion; long buildVersion = m_buildProcessors.snapshotVersion; @@ -369,7 +368,6 @@ public bool RefreshRegistries() RescanLocked(); return true; }); - } private void PublishReloaded(AssetObject asset) { diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogSnapshot.cs index fa2b92f7f..ee0698dcb 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogSnapshot.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogSnapshot.cs @@ -4,6 +4,9 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetCatalogSnapshot : ISerializable { - [SerializableProperty] internal long revision { get; set; } - [SerializableProperty] internal byte[][] entries { get; set; } = []; + [SerializableProperty] + internal long revision { get; set; } + + [SerializableProperty] + internal byte[][] entries { get; set; } = []; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs index 1103904ee..6686027af 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceFileStamp.cs @@ -13,7 +13,7 @@ long creationTimeUtcTicks this.length = length; this.lastWriteUtcTicks = lastWriteUtcTicks; this.creationTimeUtcTicks = creationTimeUtcTicks; - isValid = true; + this.isValid = true; } internal bool isValid { get; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs index cc4d79df3..16f35bb0b 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetSourceMeta.cs @@ -6,8 +6,15 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetSourceMeta : ISerializable { - [SerializableProperty] internal Guid persistentId { get; set; } - [SerializableProperty] internal int sourceKind { get; set; } = (int)AssetSourceKind.File; - [SerializableProperty] internal string importerId { get; set; } = string.Empty; - [SerializableProperty] internal byte[] importerSettingsBytes { get; set; } = []; + [SerializableProperty] + internal Guid persistentId { get; set; } + + [SerializableProperty] + internal int sourceKind { get; set; } = (int)AssetSourceKind.File; + + [SerializableProperty] + internal string importerId { get; set; } = string.Empty; + + [SerializableProperty] + internal byte[] importerSettingsBytes { get; set; } = []; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs index f1403e83c..447ace145 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs @@ -6,42 +6,99 @@ namespace Inno.Assets.Pipeline; internal sealed class AssetMeta : ISerializable { - [SerializableProperty] internal Guid persistentId { get; set; } - [SerializableProperty] internal string relativePath { get; set; } = string.Empty; - [SerializableProperty] internal string sourceHash { get; set; } = string.Empty; - [SerializableProperty] internal long sourceLength { get; set; } = -1; - [SerializableProperty] internal long sourceLastWriteUtcTicks { get; set; } - [SerializableProperty] internal long sourceCreationTimeUtcTicks { get; set; } - [SerializableProperty] internal string importerId { get; set; } = string.Empty; - [SerializableProperty] internal int deploymentScope { get; set; } = (int)AssetDeploymentScope.Runtime; - [SerializableProperty] internal Guid stableAssetTypeId { get; set; } - [SerializableProperty] internal byte[] assetStateBytes { get; set; } = []; - [SerializableProperty] internal AssetDependencyData[] runtimeDependencies { get; set; } = []; - [SerializableProperty] internal AssetImportDependencyData[] importDependencies { get; set; } = []; - [SerializableProperty] internal int importStatus { get; set; } = (int)AssetImportStatus.Pending; - [SerializableProperty] internal string importerImplementationFingerprint { get; set; } = string.Empty; - [SerializableProperty] internal string importerSettingsHash { get; set; } = string.Empty; - [SerializableProperty] internal string artifactKey { get; set; } = string.Empty; - [SerializableProperty] internal string lastSuccessfulArtifactKey { get; set; } = string.Empty; - [SerializableProperty] internal string[] diagnostics { get; set; } = []; - [SerializableProperty] internal bool isDirectory { get; set; } - [SerializableProperty] internal bool isTombstone { get; set; } + [SerializableProperty] + internal Guid persistentId { get; set; } + + [SerializableProperty] + internal string relativePath { get; set; } = string.Empty; + + [SerializableProperty] + internal string sourceHash { get; set; } = string.Empty; + + [SerializableProperty] + internal long sourceLength { get; set; } = -1; + + [SerializableProperty] + internal long sourceLastWriteUtcTicks { get; set; } + + [SerializableProperty] + internal long sourceCreationTimeUtcTicks { get; set; } + + [SerializableProperty] + internal string importerId { get; set; } = string.Empty; + + [SerializableProperty] + internal int deploymentScope { get; set; } = (int)AssetDeploymentScope.Runtime; + + [SerializableProperty] + internal Guid stableAssetTypeId { get; set; } + + [SerializableProperty] + internal byte[] assetStateBytes { get; set; } = []; + + [SerializableProperty] + internal AssetDependencyData[] runtimeDependencies { get; set; } = []; + + [SerializableProperty] + internal AssetImportDependencyData[] importDependencies { get; set; } = []; + + [SerializableProperty] + internal int importStatus { get; set; } = (int)AssetImportStatus.Pending; + + [SerializableProperty] + internal string importerImplementationFingerprint { get; set; } = string.Empty; + + [SerializableProperty] + internal string importerSettingsHash { get; set; } = string.Empty; + + [SerializableProperty] + internal string artifactKey { get; set; } = string.Empty; + + [SerializableProperty] + internal string lastSuccessfulArtifactKey { get; set; } = string.Empty; + + [SerializableProperty] + internal string[] diagnostics { get; set; } = []; + + [SerializableProperty] + internal bool isDirectory { get; set; } + + [SerializableProperty] + internal bool isTombstone { get; set; } } internal struct AssetDependencyData { - [SerializableProperty] internal Guid persistentId { get; set; } - [SerializableProperty] internal Guid stableTypeId { get; set; } - [SerializableProperty] internal string lastKnownPath { get; set; } + [SerializableProperty] + internal Guid persistentId { get; set; } + + [SerializableProperty] + internal Guid stableTypeId { get; set; } + + [SerializableProperty] + internal string lastKnownPath { get; set; } } internal struct AssetImportDependencyData { - [SerializableProperty] internal int kind { get; set; } - [SerializableProperty] internal string key { get; set; } - [SerializableProperty] internal string fingerprint { get; set; } - [SerializableProperty] internal bool sourceStampValid { get; set; } - [SerializableProperty] internal long sourceLength { get; set; } - [SerializableProperty] internal long sourceLastWriteUtcTicks { get; set; } - [SerializableProperty] internal long sourceCreationTimeUtcTicks { get; set; } + [SerializableProperty] + internal int kind { get; set; } + + [SerializableProperty] + internal string key { get; set; } + + [SerializableProperty] + internal string fingerprint { get; set; } + + [SerializableProperty] + internal bool sourceStampValid { get; set; } + + [SerializableProperty] + internal long sourceLength { get; set; } + + [SerializableProperty] + internal long sourceLastWriteUtcTicks { get; set; } + + [SerializableProperty] + internal long sourceCreationTimeUtcTicks { get; set; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs b/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs index 7ddad144f..af54af29f 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Serialization/NativeAssetSourceSerialization.cs @@ -55,12 +55,12 @@ AssetSerializationServices services /// /// Native source bytes. /// - /// - /// Receives persistent dependencies discovered during export. - /// /// /// The generation-bound serialization and reference services supplied by the import context. /// + /// + /// Receives persistent dependencies discovered during export. + /// /// /// A detached asset ready for an import transaction. /// @@ -83,8 +83,8 @@ out IReadOnlyList dependencies + $"'{expectedType.stableId:D}'." ); } - var asset = (TAsset)(Activator.CreateInstance(typeof(TAsset), nonPublic: true) - ?? throw new InvalidOperationException($"Asset type '{typeof(TAsset).FullName}' could not be created.")); + TAsset asset = (TAsset)(Activator.CreateInstance(typeof(TAsset), nonPublic: true) + ?? throw new InvalidOperationException($"Asset type '{typeof(TAsset).FullName}' could not be created.")); SerializationContext context = AssetSerializationContext.Create(services.references); _ = services.serialization.Decode(document.propertyData, reader => { diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs index ad78493e8..0f24d9cdd 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetChangeBatchNormalizer.cs @@ -161,7 +161,7 @@ private static bool ExistsAt( string relativePath ) { string full = Path.Combine(rootPath, relativePath); - return System.IO.File.Exists(full) || Directory.Exists(full); + return File.Exists(full) || Directory.Exists(full); } private static string NormalizeRelativePath(string relativePath) diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs index 99be8b3ff..6aae6f30b 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetFileSystem.cs @@ -150,7 +150,7 @@ bool activateIdentities throw new ArgumentException("A read-only project source cannot be watched for authoring changes.", nameof(autoStart)); } - assetRoot = project.rootPath; + this.assetRoot = project.rootPath; m_identities = identities; m_mounts = byId; m_persistentIdentityResolver = persistentIdentityResolver; @@ -601,7 +601,7 @@ private static Guid CreateFallbackPersistentId(string path) byte[] pathBytes = Encoding.UTF8.GetBytes(path); Span namespaceBytes = stackalloc byte[16]; new Guid("eac730be-e359-49f7-86c9-b3b09da457cc").TryWriteBytes(namespaceBytes); - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); hash.AppendData(namespaceBytes); hash.AppendData(pathBytes); return new Guid(hash.GetHashAndReset().AsSpan(0, 16)); diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs index 1e660b065..edc230c3c 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.Samples.cs @@ -139,9 +139,9 @@ CancellationToken cancellationToken string destination = Path.Combine(assetRoot, transaction.target.localPath); Directory.Move(transaction.stagedSource, destination); transaction.sourceMoved = true; - if (System.IO.File.Exists(transaction.stagedSource + ".imeta")) + if (File.Exists(transaction.stagedSource + ".imeta")) { - System.IO.File.Move(transaction.stagedSource + ".imeta", destination + ".imeta"); + File.Move(transaction.stagedSource + ".imeta", destination + ".imeta"); transaction.metaMoved = true; } AssetLoader activeLoader = GetLoader(); @@ -223,9 +223,9 @@ internal void RollbackSampleImport(AssetSampleImportTransaction transaction) EnsureSampleImportOwner(transaction); transaction.candidate?.Rollback(); string destination = Path.Combine(assetRoot, transaction.target.localPath); - if (transaction.metaMoved && System.IO.File.Exists(destination + ".imeta")) + if (transaction.metaMoved && File.Exists(destination + ".imeta")) { - System.IO.File.Move(destination + ".imeta", transaction.stagedSource + ".imeta"); + File.Move(destination + ".imeta", transaction.stagedSource + ".imeta"); transaction.metaMoved = false; } if (transaction.sourceMoved && Directory.Exists(destination)) @@ -258,7 +258,7 @@ private void FinishSampleImport(AssetSampleImportTransaction transaction) private void RequireSampleDestination(AssetPath target) { string destination = Path.Combine(assetRoot, target.localPath); - if (Directory.Exists(destination) || System.IO.File.Exists(destination) || System.IO.File.Exists(destination + ".imeta")) + if (Directory.Exists(destination) || File.Exists(destination) || File.Exists(destination + ".imeta")) { throw new IOException($"Sample import target '{target}' already exists."); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs index 57a5f44f2..9595c8756 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetPipeline.SourceMounts.cs @@ -416,7 +416,10 @@ AssetFileSystem candidateFiles } if (failures.Count > 1) { - var aggregate = new AggregateException("Asset identity publication could not restore its previous domain.", failures); + var aggregate = new AggregateException( + "Asset identity publication could not restore its previous domain.", + failures + ); m_generations.Fault(aggregate); throw aggregate; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs index b33115ce2..196719674 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSample.cs @@ -44,10 +44,7 @@ public static bool HasSampleDirectoryName(AssetPath path) /// segment starts with ~. A Project directory with the same name remains normal writable /// authoring content. /// - public static bool IsRoot(AssetPath path) - { - return path.source != AssetSourceId.project && HasSampleDirectoryName(path); - } + public static bool IsRoot(AssetPath path) => path.source != AssetSourceId.project && HasSampleDirectoryName(path); /// /// Determines whether a source path is a sample directory or is contained by one. @@ -65,9 +62,7 @@ public static bool IsRoot(AssetPath path) public static bool Contains( AssetPath path, bool isDirectory - ) { - return path.source != AssetSourceId.project && ContainsTildeDirectory(path, isDirectory); - } + ) => path.source != AssetSourceId.project && ContainsTildeDirectory(path, isDirectory); /// /// Gets the original sample directory name for a writable Project copy. diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs index 4b9d03804..1f06973af 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleImportTransaction.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; @@ -311,7 +312,7 @@ public void Rollback() internal IReadOnlyList recovery { get; set; } = []; internal AssetSourceMountTransaction? candidate { get; set; } internal string transactionRoot { get; } - internal string stagedSource => System.IO.Path.Combine(transactionRoot, "sample"); + internal string stagedSource => Path.Combine(transactionRoot, "sample"); internal List entries { get; private set; } = []; internal bool isIndexed { get; private set; } internal bool sourceMoved { get; set; } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs index d4f7c8295..5be45943e 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSnapshot.cs @@ -181,14 +181,14 @@ private static void CopyStableFile( CancellationToken cancellationToken ) { EnsureRegularFile(source); - FileInfo before = new(source); + var before = new FileInfo(source); long beforeLength = before.Length; DateTime beforeWriteTime = before.LastWriteTimeUtc; Directory.CreateDirectory(Path.GetDirectoryName(target)!); using (FileStream input = File.OpenRead(source)) - using (FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { - byte[] buffer = new byte[81920]; + var buffer = new byte[81_920]; int count; while ((count = input.Read(buffer)) != 0) { @@ -197,7 +197,7 @@ CancellationToken cancellationToken } } EnsureRegularFile(source); - FileInfo after = new(source); + var after = new FileInfo(source); if (after.Length != beforeLength || after.LastWriteTimeUtc != beforeWriteTime) { throw new IOException($"Sample source file '{source}' changed while it was being imported."); @@ -216,7 +216,7 @@ CancellationToken cancellationToken ) { using FileStream stream = File.OpenRead(path); using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - byte[] buffer = new byte[81920]; + var buffer = new byte[81_920]; int count; while ((count = stream.Read(buffer)) != 0) { diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs index c959408be..ccfcf17b0 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs @@ -76,7 +76,7 @@ public bool TryGetSourceIdentity( out Guid newId ) { ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); - if (m_sourceIdentities.TryGetValue(relativePath.Replace('\\', '/'), out var pair)) + if (m_sourceIdentities.TryGetValue(relativePath.Replace('\\', '/'), out (Guid oldId, Guid newId) pair)) { oldId = pair.oldId; newId = pair.newId; @@ -123,13 +123,13 @@ public interface IAssetSampleSourceRewriter /// /// Rewrites staged source files and registers any changed serialized type identities. /// + /// + /// The transaction-owned staged clone. + /// /// /// Runs on a worker with a pinned extension generation. Access only transaction-owned files /// and context data, observe cancellation, and do not access live Assets or Editor state. /// - /// - /// The transaction-owned staged clone. - /// void Transform(AssetSampleTransformContext context); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs index cc0b42ed8..292abafcf 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSourceMount.cs @@ -42,7 +42,7 @@ public AssetSourceMount( this.id = id; this.rootPath = Path.GetFullPath(rootPath); this.isReadOnly = isReadOnly; - dependencySourceIds = (dependencies ?? []) + this.dependencySourceIds = (dependencies ?? []) .Where(dependency => dependency.isValid && dependency != id) .ToFrozenSet(); } @@ -78,7 +78,7 @@ public AssetSourceMount( /// public string Resolve(string localPath) { - AssetPath path = new(id, localPath); + var path = new AssetPath(id, localPath); try { return PathBoundary.Resolve(rootPath, path.localPath); diff --git a/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs b/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs index 622f9e3bd..33c67c1fc 100644 --- a/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs +++ b/src/content/assets/Inno.Assets/Artifacts/ArtifactRetention.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; using Inno.Core.IO; namespace Inno.Assets; @@ -20,12 +21,12 @@ public sealed class ArtifactRetention : AssetResidencyProvider /// /// Verified immutable metadata; the provider must serialize acquisition with collection. /// - /// - /// A lease that releases exactly one reference, including when disposed from another thread. - /// /// /// Opens immutable bytes; this retention owner adds an independent stream pin before invoking it. /// + /// + /// A lease that releases exactly one reference, including when disposed from another thread. + /// public ArtifactLease Retain( AssetArtifactInfo artifact, Func openRead @@ -98,6 +99,6 @@ AssetArtifactKey key { private ArtifactRetention? m_owner = owner; - public void Dispose() => System.Threading.Interlocked.Exchange(ref m_owner, null)?.Release(key); + public void Dispose() => Interlocked.Exchange(ref m_owner, null)?.Release(key); } } diff --git a/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs b/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs index ac7923ca9..e0a1b677b 100644 --- a/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs +++ b/src/content/assets/Inno.Assets/Artifacts/AssetArtifactKey.cs @@ -59,23 +59,23 @@ public AssetArtifactKey(string value) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The value to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public bool Equals(AssetArtifactKey other) => string.Equals(value, other.value, StringComparison.Ordinal); /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is AssetArtifactKey other && Equals(other); /// diff --git a/src/content/assets/Inno.Assets/AssetDependency.cs b/src/content/assets/Inno.Assets/AssetDependency.cs index 79ca8d6d1..eb019ee5b 100644 --- a/src/content/assets/Inno.Assets/AssetDependency.cs +++ b/src/content/assets/Inno.Assets/AssetDependency.cs @@ -69,12 +69,12 @@ string lastKnownPath /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is AssetDependency other && Equals(other); /// diff --git a/src/content/assets/Inno.Assets/AssetObject.cs b/src/content/assets/Inno.Assets/AssetObject.cs index 810d4ccf1..b17345790 100644 --- a/src/content/assets/Inno.Assets/AssetObject.cs +++ b/src/content/assets/Inno.Assets/AssetObject.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Threading; using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Serialization; @@ -72,8 +73,10 @@ public void RestoreProperties( TValue target ) where TValue : class, ISerializable { - if (m_runtimeResourcesReleased || m_propertyStateOwner is null || !m_propertyStateOwner.TryGetTarget(out var owner)) - { + if (m_runtimeResourcesReleased + || m_propertyStateOwner is null + || !m_propertyStateOwner.TryGetTarget(out IAssetPropertyStateResolver? owner) + ) { throw new InvalidOperationException("The asset's property-state owner is unavailable."); } owner.RestoreProperties(stableTypeId, propertyData, target); @@ -96,13 +99,13 @@ ReadOnlyMemory currentPayload /// /// Releases the runtime resources owned by this asset without clearing its payload before quiescence. /// + /// + /// Owned work has not quiesced; runtime payload and ownership must remain intact until a later attempt. + /// /// /// An unfinished release may throw RetirementPendingException. The owner retains the asset and retries /// this hook; completed steps must not be repeated. Other failures are terminal and are reported by the owner. /// - /// - /// Owned work has not quiesced; runtime payload and ownership must remain intact until a later attempt. - /// protected virtual void OnUnloading() {} internal string sourceHash => m_sourceHash; @@ -111,7 +114,7 @@ internal void ClaimRuntimeOwner( object authority, WeakReference? properties ) { - object? previous = System.Threading.Interlocked.CompareExchange(ref m_runtimeOwner, authority, null); + object? previous = Interlocked.CompareExchange(ref m_runtimeOwner, authority, null); if (previous is not null && !ReferenceEquals(previous, authority)) { throw new InvalidOperationException("The asset belongs to another runtime owner."); @@ -154,10 +157,7 @@ long version } } - internal void UpdateAssetPath(AssetPath assetPath) - { - this.assetPath = assetPath; - } + internal void UpdateAssetPath(AssetPath assetPath) => this.assetPath = assetPath; internal void ReleaseRuntimeResources() { diff --git a/src/content/assets/Inno.Assets/AssetPath.cs b/src/content/assets/Inno.Assets/AssetPath.cs index b067bcfac..841e9ea49 100644 --- a/src/content/assets/Inno.Assets/AssetPath.cs +++ b/src/content/assets/Inno.Assets/AssetPath.cs @@ -53,7 +53,7 @@ public AssetSourceId(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() => value ?? string.Empty; + public override readonly string ToString() => value ?? string.Empty; } /// @@ -102,12 +102,12 @@ string localPath /// /// Creates a path in the writable project source. /// - /// - /// A project-owned asset path. - /// /// /// The local path text validated by the project operation. /// + /// + /// A project-owned asset path. + /// public static AssetPath Project(string localPath) => new(AssetSourceId.project, localPath); /// @@ -134,7 +134,7 @@ public static AssetPath Parse(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() + public override readonly string ToString() => source == AssetSourceId.project ? localPath ?? string.Empty : $"{source}{C_SOURCE_SEPARATOR}{localPath}"; diff --git a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs index 5ea5e88a4..98d928e11 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs @@ -130,7 +130,7 @@ CancellationToken cancellationToken { // Only immutable paths, hashes and IDs cross into IO; serializers and identities stay here. List reads = []; - CollectPayloadReads(record, new HashSet(), reads); + CollectPayloadReads(record, [], reads); long bytes = reads.Where(read => !m_payloadReads.ContainsKey(read)).Sum(static read => read.length); if (bytes > m_preparationBudgetBytes - m_preparingBytes) { @@ -170,7 +170,9 @@ CancellationToken cancellationToken } } shared.waiters++; - var completion = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); + var completion = new TaskCompletionSource>( + TaskCreationOptions.RunContinuationsAsynchronously + ); m_pendingLoads.Add( new PendingAcquisition( shared.preparation, @@ -252,7 +254,7 @@ private static async Task ReadPayloadContentAsync( CancellationToken token ) { using Stream stream = lease.OpenRead(); - byte[] bytes = new byte[checked((int)read.length)]; + var bytes = new byte[checked((int)read.length)]; await stream.ReadExactlyAsync(bytes, token).ConfigureAwait(false); token.ThrowIfCancellationRequested(); if (stream.ReadByte() != -1 || bytes.LongLength != read.length @@ -363,13 +365,13 @@ SemaphoreSlim slots { if (ExecutionContext.IsFlowSuppressed()) { - preparation = Task.Run(() => PrepareAsync(read, lease, cancellation.Token, slots)); + this.preparation = Task.Run(() => PrepareAsync(read, lease, cancellation.Token, slots)); } else { using (ExecutionContext.SuppressFlow()) { - preparation = Task.Run(() => PrepareAsync(read, lease, cancellation.Token, slots)); + this.preparation = Task.Run(() => PrepareAsync(read, lease, cancellation.Token, slots)); } } } diff --git a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs index 95bef6776..b059b0df1 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.cs @@ -49,6 +49,9 @@ public sealed partial class AssetDatabase : AssetResidencyProvider, /// /// Restores serialized properties to the existing asset object. /// + /// + /// Serialized asset object type receiving restored properties. + /// /// /// The stable type id consumed by restore properties; ownership remains with the caller unless explicitly stated otherwise. /// @@ -58,9 +61,6 @@ public sealed partial class AssetDatabase : AssetResidencyProvider, /// /// The existing target that receives the validated result. /// - /// - /// Serialized asset object type receiving restored properties. - /// public void RestoreProperties( Guid stableTypeId, byte[] propertyData, @@ -89,12 +89,12 @@ TValue target /// /// The immutable converter generation pinned by the owning runtime session. /// - /// - /// The session-owned allocator used for canonical runtime asset identities. - /// /// /// The immutable type generation pinned by this runtime session, without refreshing authoring registries. /// + /// + /// The session-owned allocator used for canonical runtime asset identities. + /// /// /// Maximum unpinned runtime payload bytes retained after lease release. /// @@ -929,7 +929,7 @@ private void ValidateArtifactBundle(RuntimeAssetRecord record) private RuntimeArtifactManifest ReadArtifactManifest(RuntimeAssetRecord record) { - ContentKey key = new(GetBundleRoot(record.artifactKey) + "/manifest"); + var key = new ContentKey(GetBundleRoot(record.artifactKey) + "/manifest"); return m_serialization.Deserialize(ReadContent(key)); } @@ -942,7 +942,7 @@ RuntimeArtifactOutput output ) { throw new InvalidDataException($"Runtime artifact bundle '{record.artifactKey}' contains an invalid output path."); } - ContentKey key = new(GetBundleRoot(record.artifactKey) + "/outputs/" + output.fileName); + var key = new ContentKey(GetBundleRoot(record.artifactKey) + "/outputs/" + output.fileName); if (!m_content.index.TryGetEntry(key, out ContentEntry? entry)) { throw new InvalidDataException($"Runtime artifact output '{record.artifactKey}/{output.name}' is missing."); @@ -969,7 +969,7 @@ private byte[] ReadContent(ContentKey key) throw new InvalidDataException($"Content '{key}' exceeds the supported array budget."); } using Stream input = lease.OpenRead(); - byte[] bytes = new byte[(int)lease.entry.length]; + var bytes = new byte[(int)lease.entry.length]; input.ReadExactly(bytes); if (input.ReadByte() != -1 || !string.Equals( Convert.ToHexString(SHA256.HashData(bytes)), @@ -1067,56 +1067,121 @@ private sealed class RuntimeAssetCatalog : ISerializable private sealed class RuntimeAssetData : ISerializable { - [SerializableProperty] internal Guid persistentId { get; set; } - [SerializableProperty] internal string relativePath { get; set; } = string.Empty; - [SerializableProperty] internal string sourceHash { get; set; } = string.Empty; - [SerializableProperty] internal long sourceLength { get; set; } - [SerializableProperty] internal long sourceLastWriteUtcTicks { get; set; } - [SerializableProperty] internal long sourceCreationTimeUtcTicks { get; set; } - [SerializableProperty] internal string importerId { get; set; } = string.Empty; - [SerializableProperty] internal int deploymentScope { get; set; } - [SerializableProperty] internal Guid stableAssetTypeId { get; set; } - [SerializableProperty] internal byte[] assetStateBytes { get; set; } = []; - [SerializableProperty] internal RuntimeDependencyData[] runtimeDependencies { get; set; } = []; - [SerializableProperty] internal RuntimeImportDependencyData[] importDependencies { get; set; } = []; - [SerializableProperty] internal int importStatus { get; set; } - [SerializableProperty] internal string importerImplementationFingerprint { get; set; } = string.Empty; - [SerializableProperty] internal string artifactKey { get; set; } = string.Empty; - [SerializableProperty] internal string lastSuccessfulArtifactKey { get; set; } = string.Empty; - [SerializableProperty] internal string[] diagnostics { get; set; } = []; - [SerializableProperty] internal bool isDirectory { get; set; } - [SerializableProperty] internal bool isTombstone { get; set; } + [SerializableProperty] + internal Guid persistentId { get; set; } + + [SerializableProperty] + internal string relativePath { get; set; } = string.Empty; + + [SerializableProperty] + internal string sourceHash { get; set; } = string.Empty; + + [SerializableProperty] + internal long sourceLength { get; set; } + + [SerializableProperty] + internal long sourceLastWriteUtcTicks { get; set; } + + [SerializableProperty] + internal long sourceCreationTimeUtcTicks { get; set; } + + [SerializableProperty] + internal string importerId { get; set; } = string.Empty; + + [SerializableProperty] + internal int deploymentScope { get; set; } + + [SerializableProperty] + internal Guid stableAssetTypeId { get; set; } + + [SerializableProperty] + internal byte[] assetStateBytes { get; set; } = []; + + [SerializableProperty] + internal RuntimeDependencyData[] runtimeDependencies { get; set; } = []; + + [SerializableProperty] + internal RuntimeImportDependencyData[] importDependencies { get; set; } = []; + + [SerializableProperty] + internal int importStatus { get; set; } + + [SerializableProperty] + internal string importerImplementationFingerprint { get; set; } = string.Empty; + + [SerializableProperty] + internal string artifactKey { get; set; } = string.Empty; + + [SerializableProperty] + internal string lastSuccessfulArtifactKey { get; set; } = string.Empty; + + [SerializableProperty] + internal string[] diagnostics { get; set; } = []; + + [SerializableProperty] + internal bool isDirectory { get; set; } + + [SerializableProperty] + internal bool isTombstone { get; set; } } private struct RuntimeDependencyData { - [SerializableProperty] internal Guid persistentId { get; set; } - [SerializableProperty] internal Guid stableTypeId { get; set; } - [SerializableProperty] internal string lastKnownPath { get; set; } + [SerializableProperty] + internal Guid persistentId { get; set; } + + [SerializableProperty] + internal Guid stableTypeId { get; set; } + + [SerializableProperty] + internal string lastKnownPath { get; set; } } private struct RuntimeImportDependencyData { - [SerializableProperty] internal int kind { get; set; } - [SerializableProperty] internal string key { get; set; } - [SerializableProperty] internal string fingerprint { get; set; } - [SerializableProperty] internal bool sourceStampValid { get; set; } - [SerializableProperty] internal long sourceLength { get; set; } - [SerializableProperty] internal long sourceLastWriteUtcTicks { get; set; } - [SerializableProperty] internal long sourceCreationTimeUtcTicks { get; set; } + [SerializableProperty] + internal int kind { get; set; } + + [SerializableProperty] + internal string key { get; set; } + + [SerializableProperty] + internal string fingerprint { get; set; } + + [SerializableProperty] + internal bool sourceStampValid { get; set; } + + [SerializableProperty] + internal long sourceLength { get; set; } + + [SerializableProperty] + internal long sourceLastWriteUtcTicks { get; set; } + + [SerializableProperty] + internal long sourceCreationTimeUtcTicks { get; set; } } private sealed class RuntimeArtifactManifest : ISerializable { - [SerializableProperty] internal string key { get; set; } = string.Empty; - [SerializableProperty] internal RuntimeArtifactOutput[] outputs { get; set; } = []; + [SerializableProperty] + internal string key { get; set; } = string.Empty; + + [SerializableProperty] + internal RuntimeArtifactOutput[] outputs { get; set; } = []; } private struct RuntimeArtifactOutput { - [SerializableProperty] internal string name { get; set; } - [SerializableProperty] internal string fileName { get; set; } - [SerializableProperty] internal string contentHash { get; set; } - [SerializableProperty] internal long length { get; set; } + [SerializableProperty] + internal string name { get; set; } + + [SerializableProperty] + internal string fileName { get; set; } + + [SerializableProperty] + internal string contentHash { get; set; } + + [SerializableProperty] + internal long length { get; set; } } } diff --git a/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs b/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs index 6201b0fa6..b34c0bc7d 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs @@ -149,16 +149,16 @@ Action release /// /// Releases this caller's residency ownership, retaining its value and callback while the provider reports Pending. /// - /// - /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. - /// Ordinary sibling failures remain observable after a later release attempt succeeds. - /// /// /// Provider retirement is unfinished or a concurrent release is in progress; retain this lease and retry at a safe point. /// /// /// The provider reports a wrapped failure, or release completes with ordinary errors retained from earlier pending attempts. /// + /// + /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. + /// Ordinary sibling failures remain observable after a later release attempt succeeds. + /// public void Dispose() => m_residency.Dispose(); } @@ -217,7 +217,7 @@ public byte[] ReadAllBytes() throw new InvalidDataException("The artifact payload exceeds the supported array budget."); } using Stream input = OpenRead(); - byte[] bytes = new byte[(int)length]; + var bytes = new byte[(int)length]; input.ReadExactly(bytes); if (input.ReadByte() != -1) { @@ -229,17 +229,17 @@ public byte[] ReadAllBytes() /// /// Releases artifact ownership, retaining metadata and callback while the provider reports Pending. /// - /// - /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. - /// Ordinary sibling failures remain observable after a later release attempt succeeds. - /// New reads stop when release begins; already opened streams retain their independent provider pins. - /// /// /// Provider retirement is unfinished or a concurrent release is in progress; retain this lease and retry at a safe point. /// /// /// The provider reports a wrapped failure, or release completes with ordinary errors retained from earlier pending attempts. /// + /// + /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. + /// Ordinary sibling failures remain observable after a later release attempt succeeds. + /// New reads stop when release begins; already opened streams retain their independent provider pins. + /// public void Dispose() { lock (m_sync) @@ -273,10 +273,7 @@ public sealed class RetentionScope : IDisposable /// Retirement has begun and the scope cannot accept another lease. /// public TLease Retain(TLease lease) - where TLease : IDisposable - { - return m_lifetime.Own(lease); - } + where TLease : IDisposable => m_lifetime.Own(lease); /// /// Releases all retained leases in reverse acquisition order. diff --git a/src/content/assets/Inno.Assets/Runtime/AssetRuntimeOwner.cs b/src/content/assets/Inno.Assets/Runtime/AssetRuntimeOwner.cs index 24d9727de..d175fe12d 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetRuntimeOwner.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetRuntimeOwner.cs @@ -21,7 +21,10 @@ public sealed class AssetRuntimeOwner /// /// Owner resolver, weakly referenced so stale assets cannot retain a retired database. /// - public AssetRuntimeOwner(IAssetPropertyStateResolver? properties = null) => m_properties = properties is null ? null : new(properties); + public AssetRuntimeOwner(IAssetPropertyStateResolver? properties = null) + { + m_properties = properties is null ? null : new(properties); + } /// /// Reads the source fingerprint of an asset claimed by this owner. diff --git a/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs b/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs index 79f8bf920..69b6d823f 100644 --- a/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs +++ b/src/content/assets/Inno.Assets/Runtime/ResidencyLease.cs @@ -97,7 +97,10 @@ private void Finish() private AggregateException TakeCompletedFailure() { - var failure = new AggregateException("Residency release completed with earlier cleanup failures.", m_completedFailures!); + var failure = new AggregateException( + "Residency release completed with earlier cleanup failures.", + m_completedFailures! + ); m_completedFailures = null; return failure; } diff --git a/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs b/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs index d1d71a218..e4ccd2a07 100644 --- a/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs +++ b/src/content/assets/Inno.Assets/Serialization/AssetDependencyCollection.cs @@ -45,7 +45,7 @@ public AssetDependencyCollection(bool includeLastKnownPaths) /// public IReadOnlyList dependencies => m_dependencies is null || m_dependencies.Count == 0 - ? Array.Empty() + ? [] : m_dependencies.Values.OrderBy(static dependency => dependency.persistentId).ToArray(); internal void Add( diff --git a/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs b/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs index 2034982e6..5704fe8b8 100644 --- a/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs +++ b/src/content/assets/Inno.Assets/Serialization/IAssetReferenceResolver.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using Inno.Assets; using Inno.Core.Execution; using Inno.Core.Identity; @@ -82,7 +83,7 @@ ReferenceResolution IReferenceResolver.Resolve(ReferenceDescriptor descriptor) { throw; } - catch (Exception exception) when (exception is InvalidOperationException or System.IO.InvalidDataException) + catch (Exception exception) when (exception is InvalidOperationException or InvalidDataException) { return new ReferenceResolution(descriptor, ReferenceResolutionState.Missing, diagnostic: exception.Message); } diff --git a/src/content/deployment/Inno.Content/ContentKey.cs b/src/content/deployment/Inno.Content/ContentKey.cs index cd20c859d..1ae512ac2 100644 --- a/src/content/deployment/Inno.Content/ContentKey.cs +++ b/src/content/deployment/Inno.Content/ContentKey.cs @@ -42,7 +42,7 @@ public ContentKey(string value) /// public string? value { get; } - /// + /// public override string ToString() => value ?? string.Empty; private static bool IsReserved(string segment) diff --git a/src/content/deployment/Inno.Content/ContentPackIndex.cs b/src/content/deployment/Inno.Content/ContentPackIndex.cs index a204687e8..8c2ce3010 100644 --- a/src/content/deployment/Inno.Content/ContentPackIndex.cs +++ b/src/content/deployment/Inno.Content/ContentPackIndex.cs @@ -29,8 +29,8 @@ public sealed class ContentPackIndex public ContentPackIndex(IEnumerable entries) { ArgumentNullException.ThrowIfNull(entries); - m_byKey = new(); - HashSet folded = new(StringComparer.OrdinalIgnoreCase) { C_INDEX_KEY }; + m_byKey = []; + var folded = new HashSet(StringComparer.OrdinalIgnoreCase) { C_INDEX_KEY }; List ordered = []; foreach (ContentEntry entry in entries) { @@ -41,7 +41,7 @@ public ContentPackIndex(IEnumerable entries) } m_byKey.Add(entry.key, entry); ordered.Add(entry); - totalLength = checked(totalLength + entry.length); + this.totalLength = checked(totalLength + entry.length); } ordered.Sort(static ( left, diff --git a/src/content/deployment/Inno.Content/ContentPackReader.cs b/src/content/deployment/Inno.Content/ContentPackReader.cs index aa592649d..dfa815686 100644 --- a/src/content/deployment/Inno.Content/ContentPackReader.cs +++ b/src/content/deployment/Inno.Content/ContentPackReader.cs @@ -73,7 +73,7 @@ public static PackContentStore Open( pack.Position = 0; archive = new ZipArchive(pack, ZipArchiveMode.Read, leaveOpen: false); Dictionary payloads = ReadInventory(archive, limits); - ContentKey indexKey = new(ContentPackIndex.C_INDEX_KEY); + var indexKey = new ContentKey(ContentPackIndex.C_INDEX_KEY); if (!payloads.Remove(indexKey, out ZipArchiveEntry? indexEntry)) { throw new InvalidDataException("The content pack has no inventory document."); @@ -82,7 +82,7 @@ public static PackContentStore Open( { throw new InvalidDataException("The content inventory exceeds its reading budget."); } - byte[] indexBytes = new byte[checked((int)indexEntry.Length)]; + var indexBytes = new byte[checked((int)indexEntry.Length)]; using (Stream indexStream = indexEntry.Open()) { indexStream.ReadExactly(indexBytes); @@ -136,8 +136,8 @@ ContentReadLimits limits { throw new InvalidDataException("The archive contains too many entries."); } - Dictionary entries = new(); - HashSet folded = new(StringComparer.OrdinalIgnoreCase); + Dictionary entries = []; + var folded = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (ZipArchiveEntry entry in archive.Entries) { int mode = (entry.ExternalAttributes >> 16) & 0xF000; diff --git a/src/content/deployment/Inno.Content/PackContentStore.cs b/src/content/deployment/Inno.Content/PackContentStore.cs index bc11ee8c9..feede8b78 100644 --- a/src/content/deployment/Inno.Content/PackContentStore.cs +++ b/src/content/deployment/Inno.Content/PackContentStore.cs @@ -28,13 +28,13 @@ Dictionary entries this.index = index; } - /// + /// public ContentPackDescriptor descriptor { get; } - /// + /// public ContentPackIndex index { get; } - /// + /// public ContentReadLease Acquire(ContentKey key) { lock (m_sync) @@ -99,33 +99,33 @@ Stream input m_input = input; } - /// + /// public override bool CanRead => m_input is not null; - /// + /// public override bool CanSeek => false; - /// + /// public override bool CanWrite => false; - /// + /// public override long Length => throw new NotSupportedException(); - /// + /// public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } - /// + /// public override int Read( byte[] buffer, int offset, int count ) => Read(buffer.AsSpan(offset, count)); - /// + /// public override int Read(Span buffer) { lock (m_owner.m_sync) @@ -134,7 +134,7 @@ public override int Read(Span buffer) } } - /// + /// public override int ReadByte() { lock (m_owner.m_sync) @@ -143,26 +143,26 @@ public override int ReadByte() } } - /// + /// public override void Flush() => throw new NotSupportedException(); - /// + /// public override long Seek( long offset, SeekOrigin origin ) => throw new NotSupportedException(); - /// + /// public override void SetLength(long value) => throw new NotSupportedException(); - /// + /// public override void Write( byte[] buffer, int offset, int count ) => throw new NotSupportedException(); - /// + /// protected override void Dispose(bool disposing) { if (disposing) diff --git a/src/content/references/Inno.References/ReferenceRecoveryChange.cs b/src/content/references/Inno.References/ReferenceRecoveryChange.cs index 1240f5f00..e80512417 100644 --- a/src/content/references/Inno.References/ReferenceRecoveryChange.cs +++ b/src/content/references/Inno.References/ReferenceRecoveryChange.cs @@ -1,3 +1,5 @@ +using System; + namespace Inno.References; /// @@ -21,8 +23,8 @@ public ReferenceRecoveryChange( SerializedMissingState missingState, ReferenceResolution resolution ) { - System.ArgumentNullException.ThrowIfNull(missingState); - System.ArgumentNullException.ThrowIfNull(resolution); + ArgumentNullException.ThrowIfNull(missingState); + ArgumentNullException.ThrowIfNull(resolution); this.missingState = missingState; this.resolution = resolution; } diff --git a/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs b/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs index 2c3fef2bc..f596f4a49 100644 --- a/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs +++ b/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs @@ -59,18 +59,18 @@ CancellationToken cancellationToken /// /// Writes a validated asset representation to its writable source mount. /// + /// + /// The generation-bound source export services. + /// /// /// The validated asset instance exported by this operation. /// - /// - /// The generation-bound source export services. + /// + /// The token that cancels the operation before it commits. /// /// /// An asynchronous operation that completes after all requested work has finished. /// - /// - /// The token that cancels the operation before it commits. - /// protected override ValueTask?> ExportAsync( AssetExportContext context, PrefabAsset asset, diff --git a/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs b/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs index cf2d95da7..441656f9a 100644 --- a/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs +++ b/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs @@ -59,18 +59,18 @@ CancellationToken cancellationToken /// /// Writes a validated asset representation to its writable source mount. /// + /// + /// The generation-bound source export services. + /// /// /// The validated asset instance exported by this operation. /// - /// - /// The generation-bound source export services. + /// + /// The token that cancels the operation before it commits. /// /// /// An asynchronous operation that completes after all requested work has finished. /// - /// - /// The token that cancels the operation before it commits. - /// protected override ValueTask?> ExportAsync( AssetExportContext context, SceneAsset asset, diff --git a/src/content/scene/Inno.Scene/Assets/SceneAsset.cs b/src/content/scene/Inno.Scene/Assets/SceneAsset.cs index 670fb0c8d..23177a3f8 100644 --- a/src/content/scene/Inno.Scene/Assets/SceneAsset.cs +++ b/src/content/scene/Inno.Scene/Assets/SceneAsset.cs @@ -76,15 +76,15 @@ IAssetReferenceResolver assets /// /// Creates an unloaded runtime scene and acquires its hard asset dependencies. /// - /// - /// A newly allocated scene. - /// /// /// The serialization registry that owns the active scene converter generation. /// /// /// The runtime asset generation used to resolve persistent references in the scene graph. /// + /// + /// A newly allocated scene. + /// [ScriptingApiIgnore] public GameScene Instantiate( SerializationRegistry serialization, @@ -165,7 +165,5 @@ private byte[] GetPayload() protected override void OnRuntimePayloadChanged( ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload - ) { - m_pendingPayload = []; - } + ) => m_pendingPayload = []; } diff --git a/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs b/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs index 454e9fd90..ab40ddb2d 100644 --- a/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs +++ b/src/content/scene/Inno.Scene/Concrete/MissingGameSystem.cs @@ -39,7 +39,7 @@ internal MissingGameSystem( : missingTypeName; m_serializedState = serializedState.ToArray(); m_dependencies = dependencies?.ToArray() ?? []; - enabled = false; + this.enabled = false; } /// diff --git a/src/content/scene/Inno.Scene/Core/EngineObject.cs b/src/content/scene/Inno.Scene/Core/EngineObject.cs index b1b1a8ccc..fa2b03d91 100644 --- a/src/content/scene/Inno.Scene/Core/EngineObject.cs +++ b/src/content/scene/Inno.Scene/Core/EngineObject.cs @@ -67,12 +67,12 @@ public abstract class EngineObject : IdentityObject /// /// Compares this instance to another object using reference identity. /// - /// - /// when is this instance. - /// /// /// The object to compare with this instance. /// + /// + /// when is this instance. + /// public override bool Equals(object? obj) => ReferenceEquals(this, obj); /// diff --git a/src/content/scene/Inno.Scene/Core/GameObject.cs b/src/content/scene/Inno.Scene/Core/GameObject.cs index 5d950f485..a804e2663 100644 --- a/src/content/scene/Inno.Scene/Core/GameObject.cs +++ b/src/content/scene/Inno.Scene/Core/GameObject.cs @@ -78,13 +78,13 @@ public string name /// /// Gets or sets the ordinal tag used to categorize and query this game object. /// + /// + /// Thrown when the assigned tag is empty or contains only white-space characters. + /// /// /// Tag definitions are project configuration stored separately from scene data. Scene and prefab /// serialization persist the assigned ordinal value even when its current project definition is absent. /// - /// - /// Thrown when the assigned tag is empty or contains only white-space characters. - /// public string tag { get diff --git a/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs b/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs index 1c15784a8..2a962d0a7 100644 --- a/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs +++ b/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs @@ -65,7 +65,7 @@ protected override void Compose( GameTagCatalog target, IReadOnlyList> contributions ) { - var owners = target.GetTags().ToDictionary(static tag => tag, static _ => "host", StringComparer.Ordinal); + Dictionary owners = target.GetTags().ToDictionary(static tag => tag, static _ => "host", StringComparer.Ordinal); foreach (ProjectSettingContribution contribution in contributions) { contribution.value.Validate(); diff --git a/src/content/scene/Inno.Scene/Layers/GameLayer.cs b/src/content/scene/Inno.Scene/Layers/GameLayer.cs index be619ee6f..d2cc02cf1 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayer.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayer.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; namespace Inno.Scene.Layers; @@ -43,12 +44,12 @@ public GameLayer(int index) /// /// Compares this layer with another layer by index. /// - /// - /// A signed value describing the relative index ordering. - /// /// /// The value to compare with this instance. /// + /// + /// A signed value describing the relative index ordering. + /// public int CompareTo(GameLayer other) => index.CompareTo(other.index); /// @@ -65,12 +66,12 @@ public GameLayer(int index) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is GameLayer other && Equals(other); /// @@ -87,7 +88,7 @@ public GameLayer(int index) /// /// The human-readable representation of this value. /// - public override string ToString() => index.ToString(System.Globalization.CultureInfo.InvariantCulture); + public override string ToString() => index.ToString(CultureInfo.InvariantCulture); /// /// Determines whether two layer identifiers contain the same index. diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs b/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs index ab69c7a3c..a08392de4 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerMask.cs @@ -60,34 +60,34 @@ public static GameLayerMask FromLayers(IEnumerable layers) /// /// Determines whether the supplied layer is contained in this mask. /// - /// - /// when the layer bit is enabled. - /// /// /// The layer consumed by contains; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// when the layer bit is enabled. + /// public bool Contains(GameLayer layer) => (value & (1u << layer.index)) != 0u; /// /// Returns a mask with the supplied layer enabled. /// - /// - /// The updated immutable mask. - /// /// /// The layer consumed by with; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The updated immutable mask. + /// public GameLayerMask With(GameLayer layer) => new(value | (1u << layer.index)); /// /// Returns a mask with the supplied layer disabled. /// - /// - /// The updated immutable mask. - /// /// /// The layer consumed by without; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The updated immutable mask. + /// public GameLayerMask Without(GameLayer layer) => new(value & ~(1u << layer.index)); /// @@ -104,12 +104,12 @@ public static GameLayerMask FromLayers(IEnumerable layers) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is GameLayerMask other && Equals(other); /// diff --git a/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs b/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs index 715ced862..1d08bbbaa 100644 --- a/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs +++ b/src/content/scene/Inno.Scene/Lifecycle/SceneSystemScheduler.cs @@ -55,7 +55,7 @@ bool invokeReset ); } - var system = (GameSystem)m_types.snapshot.CreateInstance(systemType); + GameSystem system = (GameSystem)m_types.snapshot.CreateInstance(systemType); Add(system, descriptor, persistentId, invokeReset); return system; } diff --git a/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs b/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs index 62927b0d3..0a1d1196b 100644 --- a/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs +++ b/src/content/scene/Inno.Scene/Reloading/SceneReloadService.cs @@ -17,12 +17,12 @@ public sealed class SceneReloadService /// /// Creates a scene reload service bound to one serialization generation owner. /// - /// - /// The serialization registry used to capture and restore scene state. - /// /// /// The isolated scene world whose active generation is captured. /// + /// + /// The serialization registry used to capture and restore scene state. + /// /// /// The asset reference generation used throughout capture, activation, and rollback. /// diff --git a/src/content/scene/Inno.Scene/SceneWorld.cs b/src/content/scene/Inno.Scene/SceneWorld.cs index ca351e0a0..24df07def 100644 --- a/src/content/scene/Inno.Scene/SceneWorld.cs +++ b/src/content/scene/Inno.Scene/SceneWorld.cs @@ -7,6 +7,7 @@ using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scene.Components; +using Inno.Scripting.Api; namespace Inno.Scene; @@ -69,7 +70,7 @@ TypeCatalog types /// /// The binding was already configured. /// - [Inno.Scripting.Api.ScriptingApiIgnore] + [ScriptingApiIgnore] public void ConfigurePrefabInstantiation( SerializationRegistry serialization, IAssetReferenceResolver assets diff --git a/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs b/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs index 77adecdd7..a44cea167 100644 --- a/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs +++ b/src/content/scene/Inno.Scene/Serialization/Converters/GameSceneConverter.cs @@ -149,7 +149,7 @@ bool preservePersistentIds ); IReadOnlyList systemReaders = reader.ReadObjectArray(SceneGraphSerialization.C_SYSTEMS_KEY); - var missingPlaceholders = graph.missingPlaceholders.ToList(); + List missingPlaceholders = graph.missingPlaceholders.ToList(); IReadOnlyList<(GameSystem system, byte[] state)> systemStates = SceneGraphSerialization.CreateSystems( scene, diff --git a/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs b/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs index 635ec6e3e..9058179f7 100644 --- a/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs +++ b/src/content/scene/Inno.Scene/Serialization/PrefabOverrideProcessor.cs @@ -256,8 +256,8 @@ PrefabOverrideSet overrides { return; } - var mappedObjectIds = connection.objectIdentities.Values.ToHashSet(); - var mappedComponentIds = connection.componentIdentities.Values.ToHashSet(); + HashSet mappedObjectIds = connection.objectIdentities.Values.ToHashSet(); + HashSet mappedComponentIds = connection.componentIdentities.Values.ToHashSet(); var stack = new Stack(); stack.Push(root); while (stack.Count != 0) diff --git a/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs b/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs index 31962193e..a31ef55bf 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneElementState.cs @@ -4,19 +4,35 @@ using System.Linq; using Inno.Assets; using Inno.Core.Serialization; +using Inno.Extensibility.Types; namespace Inno.Scene; internal sealed class SceneElementState : ISerializable { - [SerializableProperty] internal Guid typeId { get; set; } - [SerializableProperty] internal string typeName { get; set; } = string.Empty; - [SerializableProperty] internal byte[] properties { get; set; } = []; - [SerializableProperty] internal Guid[] dependencyIds { get; set; } = []; - [SerializableProperty] internal Guid[] dependencyTypes { get; set; } = []; - [SerializableProperty] internal string[] dependencyPaths { get; set; } = []; - [SerializableProperty] internal Guid[] aliasIds { get; set; } = []; - [SerializableProperty] internal Guid[] aliasTargets { get; set; } = []; + [SerializableProperty] + internal Guid typeId { get; set; } + + [SerializableProperty] + internal string typeName { get; set; } = string.Empty; + + [SerializableProperty] + internal byte[] properties { get; set; } = []; + + [SerializableProperty] + internal Guid[] dependencyIds { get; set; } = []; + + [SerializableProperty] + internal Guid[] dependencyTypes { get; set; } = []; + + [SerializableProperty] + internal string[] dependencyPaths { get; set; } = []; + + [SerializableProperty] + internal Guid[] aliasIds { get; set; } = []; + + [SerializableProperty] + internal Guid[] aliasTargets { get; set; } = []; internal void SetDependencies(IEnumerable dependencies) { @@ -37,11 +53,7 @@ internal AssetDependency[] GetDependencies() => dependencyIds.Select(( id, index - ) => new AssetDependency( - id, - new Inno.Extensibility.Types.TypeRef(dependencyTypes[index]), - dependencyPaths[index] - )).ToArray(); + ) => new AssetDependency(id, new TypeRef(dependencyTypes[index]), dependencyPaths[index])).ToArray(); internal IReadOnlyDictionary GetAliases() => aliasIds.Select(( diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs index 151da9bad..14eabb889 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphReferenceMap.cs @@ -10,7 +10,7 @@ namespace Inno.Scene; internal sealed class SceneGraphReferenceMap : SceneReferenceScope { private readonly IReadOnlyDictionary? m_sourceIdByObject; - private readonly Dictionary m_objectBySourceId = new(); + private readonly Dictionary m_objectBySourceId = []; internal SceneGraphReferenceMap( GameScene scene, @@ -54,7 +54,7 @@ internal EngineObject GetRegistered(Guid sourceId) $"Scene graph reference alias target '{sourceId}' could not be resolved." ); - /// + /// protected override bool TryGetSourceId( EngineObject engineObject, out Guid sourceId @@ -63,7 +63,7 @@ out Guid sourceId return m_sourceIdByObject is not null && m_sourceIdByObject.TryGetValue(engineObject, out sourceId); } - /// + /// protected override bool TryResolve( Guid sourceId, out EngineObject? engineObject diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs index df4699c09..6eab37916 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSerialization.cs @@ -423,12 +423,11 @@ internal static void WriteSystems( SerializationWriter writer, IReadOnlyCollection systems, IReadOnlyDictionary sourceIds - ) { - writer.WriteObjectArray(C_SYSTEMS_KEY, systems, ( - systemWriter, - system - ) => - { + ) => writer.WriteObjectArray(C_SYSTEMS_KEY, systems, ( + systemWriter, + system + ) => + { systemWriter.Write(C_SYSTEM_ID_KEY, GetSourceId(sourceIds, system)); if (system is MissingGameSystem missing) { @@ -443,7 +442,6 @@ IReadOnlyDictionary sourceIds AssetDependency[] dependencies = WriteState(systemWriter, system); WriteStateDependencies(systemWriter, dependencies); }); - } internal static IReadOnlyList<(GameSystem system, byte[] state)> CreateSystems( GameScene scene, @@ -680,7 +678,7 @@ IReadOnlyDictionary sourceIds return; } - var targetByPersistentId = sourceIds.Keys.ToDictionary( + Dictionary targetByPersistentId = sourceIds.Keys.ToDictionary( static engineObject => engineObject.identity.persistentId, engineObject => sourceIds[engineObject] ); @@ -914,9 +912,7 @@ private static bool TryResolve( TypeRef typeRef, SerializationContext context, out Type? type - ) { - return context.GetRequired().TryResolve(typeRef, out type); - } + ) => context.GetRequired().TryResolve(typeRef, out type); private static void WriteComponent( SerializationWriter writer, diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs index 47386c4ca..957589532 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/SceneGraphSourceIds.cs @@ -30,22 +30,22 @@ IReadOnlyList systems } } - /// + /// public int Count => checked(m_objects.Count + (m_systems?.Count ?? 0)); - /// + /// public IEnumerable Keys => EnumerateKeys(); - /// + /// public IEnumerable Values => EnumerateValues(); - /// + /// public Guid this[EngineObject key] => TryGetValue(key, out Guid value) ? value : throw new KeyNotFoundException(); - /// + /// public bool ContainsKey(EngineObject key) => TryGetValue(key, out _); - /// + /// public bool TryGetValue( EngineObject key, out Guid value @@ -62,7 +62,7 @@ out Guid value return false; } - /// + /// public IEnumerator> GetEnumerator() { foreach (KeyValuePair entry in m_objects) diff --git a/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs b/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs index f807987ad..ce48e7b7b 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneGraph/ScenePropertyReferenceScope.cs @@ -46,10 +46,10 @@ internal ScenePropertyReferenceScope( } } - /// /// /// The current allocator must still own the Scene and the exact registered object in that Scene. /// + /// protected override bool TryGetSourceId( EngineObject engineObject, out Guid sourceId @@ -65,10 +65,10 @@ out Guid sourceId return true; } - /// /// /// Neutral aliases resolve to current Core identities; destroyed or foreign Scene objects are rejected. /// + /// protected override bool TryResolve( Guid sourceId, out EngineObject? engineObject diff --git a/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs b/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs index 005fc6458..b14dce5c5 100644 --- a/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/ScenePropertySerialization.cs @@ -150,15 +150,15 @@ IAssetReferenceResolver assets /// /// Bytes produced by or . /// - /// - /// The policy applied to unavailable or mismatched current properties. - /// /// /// The serialization registry that owns the active converter generation. /// /// /// The resolver used to materialize canonical asset references in restored values. /// + /// + /// The policy applied to unavailable or mismatched current properties. + /// /// /// A summary of restored, ignored, and incompatible properties. /// diff --git a/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs b/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs index b3b5c8998..5ae52f3f4 100644 --- a/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs +++ b/src/content/scene/Inno.Scene/Serialization/SceneSubtreeSerialization.cs @@ -58,18 +58,18 @@ IAssetReferenceResolver assets /// /// Bytes created by . /// - /// - /// The optional external parent restored after the subtree is created. - /// - /// - /// The requested sibling index under or at the scene root. - /// /// /// The serialization registry that owns the active converter generation. /// /// /// The asset-reference resolver used to restore referenced asset identities. /// + /// + /// The optional external parent restored after the subtree is created. + /// + /// + /// The requested sibling index under or at the scene root. + /// /// /// The restored subtree root. /// diff --git a/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs b/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs index 5e5b33dfa..44e4e6c1f 100644 --- a/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs +++ b/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs @@ -26,7 +26,10 @@ internal sealed class SceneStructureSnapshot private Dictionary? m_sourceIds; private IReadOnlyDictionary? m_frozenSourceIds; - internal SceneStructureSnapshot(IReadOnlyList objects) => this.objects = objects; + internal SceneStructureSnapshot(IReadOnlyList objects) + { + this.objects = objects; + } internal IReadOnlyList objects { get; } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs index de2b99e8e..757ff7a91 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs @@ -181,7 +181,7 @@ public void AddOrUpdate( T item, TKey key ) { - if (m_keyByItem.TryGetValue(item, out var oldKey)) + if (m_keyByItem.TryGetValue(item, out TKey? oldKey)) { if (EqualityComparer.Default.Equals(oldKey, key)) { @@ -218,7 +218,7 @@ TKey key /// public void Remove(T item) { - if (!m_keyByItem.TryGetValue(item, out var key)) + if (!m_keyByItem.TryGetValue(item, out TKey? key)) { return; } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs index 32eb7111e..cba9e9168 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs @@ -47,7 +47,7 @@ public bool isValid [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - if (storeRef == null || !storeRef.TryGetTarget(out var store)) + if (storeRef is null || !storeRef.TryGetTarget(out IIndexedObjectStore? store)) { return false; } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs index c842a4589..7f69fdacf 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectQuery.cs @@ -13,7 +13,7 @@ public sealed class IndexedObjectQuery where T : class { private readonly IndexedObjectStore m_store; - private readonly List> m_conditions = new(); + private readonly List> m_conditions = []; private Func>? m_orderedFastExec; private Func>? m_orderedSnapshotExec; private Func? m_orderedFirstExec; @@ -34,7 +34,7 @@ internal IndexedObjectQuery(IndexedObjectStore store) /// public IndexedObjectQuery Where(IIndexedObjectQueryCondition condition) { - if (condition == null) + if (condition is null) { throw new ArgumentNullException(nameof(condition)); } @@ -63,12 +63,12 @@ public IndexedObjectQuery Where(IIndexedObjectQueryCondition condition) /// /// Key handle. /// - /// - /// The same query instance. - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// The same query instance. + /// public IndexedObjectQuery Find( IndexedObjectKey key, TKey value @@ -103,13 +103,13 @@ public IndexedObjectQuery OrderBy(IndexedObjectKey key) /// /// Executes the query and returns a lazy fail-fast enumerable of results. /// - /// - /// Enumeration is fail-fast and throws if the store is modified during iteration. - /// /// /// Lazy fail-fast enumerable of matching items. /// - public IEnumerable GetFast() => m_orderedFastExec != null ? m_orderedFastExec() : m_store.ExecuteQueryFast(m_conditions); + /// + /// Enumeration is fail-fast and throws if the store is modified during iteration. + /// + public IEnumerable GetFast() => m_orderedFastExec is not null ? m_orderedFastExec() : m_store.ExecuteQueryFast(m_conditions); /// /// Executes the query and returns a stable snapshot. @@ -117,7 +117,8 @@ public IndexedObjectQuery OrderBy(IndexedObjectKey key) /// /// A snapshot list detached from subsequent store mutations. /// - public IReadOnlyList Get() => m_orderedSnapshotExec != null ? m_orderedSnapshotExec() : m_store.ExecuteQuerySnapshot(m_conditions); + public IReadOnlyList Get() + => m_orderedSnapshotExec is not null ? m_orderedSnapshotExec() : m_store.ExecuteQuerySnapshot(m_conditions); /// /// Executes the query and returns the first matching item or null. @@ -125,5 +126,5 @@ public IndexedObjectQuery OrderBy(IndexedObjectKey key) /// /// The first matching item or null. /// - public T? First() => m_orderedFirstExec != null ? m_orderedFirstExec() : m_store.ExecuteFirst(m_conditions); + public T? First() => m_orderedFirstExec is not null ? m_orderedFirstExec() : m_store.ExecuteFirst(m_conditions); } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs index 216e0560f..73873489b 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Handles.cs @@ -5,13 +5,13 @@ namespace Inno.Core.Collections; -sealed partial class IndexedObjectStore +public sealed partial class IndexedObjectStore where T : class { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool IsValidItem(T item) { - if (item == null) + if (item is null) { return false; } @@ -43,7 +43,7 @@ internal bool TryGetHandle( T item, out IndexedObjectRuntimeHandle handle ) { - if (item == null) + if (item is null) { handle = default; return false; diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs index d53795f53..914d51880 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Keys.cs @@ -5,7 +5,7 @@ namespace Inno.Core.Collections; -sealed partial class IndexedObjectStore +public sealed partial class IndexedObjectStore where T : class { /// @@ -45,7 +45,7 @@ public IndexedObjectKey DefineKey( throw new InvalidOperationException($"Key '{name}' already exists."); } - if ((flags & IndexedObjectKeyFlags.Ordered) != 0 && orderComparer == null) + if ((flags & IndexedObjectKeyFlags.Ordered) != 0 && orderComparer is null) { throw new ArgumentNullException( nameof(orderComparer), @@ -54,7 +54,7 @@ public IndexedObjectKey DefineKey( } var index = new IndexedObjectIndex(name, flags, orderComparer); - var id = m_nextIndexId++; + int id = m_nextIndexId++; m_indexes[id] = index; m_indexByName[name] = id; BumpVersion(); @@ -84,7 +84,7 @@ public bool RemoveKey(IndexedObjectKey key) m_lock.EnterWriteLock(); try { - if (!m_indexes.Remove(key.id, out var removed)) + if (!m_indexes.Remove(key.id, out IIndexedObjectIndex? removed)) { return false; } @@ -127,13 +127,13 @@ out IndexedObjectKey key m_lock.EnterReadLock(); try { - if (!m_indexByName.TryGetValue(name, out var id)) + if (!m_indexByName.TryGetValue(name, out int id)) { key = default; return false; } - if (!m_indexes.TryGetValue(id, out var index) || index.keyType != typeof(TKey)) + if (!m_indexes.TryGetValue(id, out IIndexedObjectIndex? index) || index.keyType != typeof(TKey)) { key = default; return false; @@ -155,7 +155,7 @@ Type keyType m_lock.EnterReadLock(); try { - return m_indexes.TryGetValue(id, out var index) && index.keyType == keyType; + return m_indexes.TryGetValue(id, out IIndexedObjectIndex? index) && index.keyType == keyType; } finally { @@ -166,18 +166,18 @@ Type keyType /// /// Gets all defined key names as a lazy enumerable. /// - /// - /// Enumeration is fail-fast and throws if the store is modified during iteration. - /// /// /// Lazy enumerable of key names. /// + /// + /// Enumeration is fail-fast and throws if the store is modified during iteration. + /// public IEnumerable GetAllKeys() => EnumerateKeys(); private IEnumerable EnumerateKeys() { - var version = Volatile.Read(ref m_version); - foreach (var name in m_indexByName.Keys) + int version = Volatile.Read(ref m_version); + foreach (string name in m_indexByName.Keys) { EnsureVersion(version); yield return name; @@ -192,12 +192,12 @@ internal bool IsOrderedKey(IndexedObjectKey key) private IndexedObjectIndex GetIndex(IndexedObjectKey handle) where TKey : notnull { - if (handle.storeRef == null || !handle.storeRef.TryGetTarget(out var owner) || !ReferenceEquals(owner, this)) + if (handle.storeRef is null || !handle.storeRef.TryGetTarget(out IIndexedObjectStore? owner) || !ReferenceEquals(owner, this)) { throw new InvalidOperationException($"Key '{handle.name}' does not belong to this store."); } - if (!m_indexes.TryGetValue(handle.id, out var index)) + if (!m_indexes.TryGetValue(handle.id, out IIndexedObjectIndex? index)) { throw new InvalidOperationException($"Key '{handle.name}' not found."); } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs index fd5a7df8b..4a7baef60 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.OrderedQueries.cs @@ -5,7 +5,7 @@ namespace Inno.Core.Collections; -sealed partial class IndexedObjectStore +public sealed partial class IndexedObjectStore where T : class { internal IEnumerable ExecuteOrderedQueryFast( @@ -22,7 +22,7 @@ List> conditions m_lock.EnterReadLock(); try { - var index = GetIndex(orderKey); + IndexedObjectIndex index = GetIndex(orderKey); if ((index.flags & IndexedObjectKeyFlags.Ordered) == 0) { throw new InvalidOperationException($"Key '{orderKey.name}' is not ordered."); @@ -46,8 +46,8 @@ private IEnumerable EnumerateOrderedQuery( List> conditions ) where TKey : notnull { - var version = Volatile.Read(ref m_version); - var index = GetIndex(orderKey); + int version = Volatile.Read(ref m_version); + IndexedObjectIndex index = GetIndex(orderKey); if ((index.flags & IndexedObjectKeyFlags.Ordered) == 0) { throw new InvalidOperationException($"Key '{orderKey.name}' is not ordered."); @@ -63,10 +63,10 @@ List> conditions yield break; } - foreach (var key in index.EnumerateOrderedKeys()) + foreach (TKey key in index.EnumerateOrderedKeys()) { EnsureVersion(version); - if (index.TryGetSingle(key, out var single) && single != null) + if (index.TryGetSingle(key, out T? single) && single is not null) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -86,13 +86,13 @@ List> conditions continue; } - var set = index.FindUnsafe(key); - if (set == null || set.Count == 0) + HashSet? set = index.FindUnsafe(key); + if (set is null || set.Count == 0) { continue; } - foreach (var item in set) + foreach (T item in set) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -121,7 +121,7 @@ List> conditions m_lock.EnterReadLock(); try { - var index = GetIndex(orderKey); + IndexedObjectIndex index = GetIndex(orderKey); if ((index.flags & IndexedObjectKeyFlags.Ordered) == 0) { throw new InvalidOperationException($"Key '{orderKey.name}' is not ordered."); diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs index 91eafa928..fa12a05ef 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.Queries.cs @@ -5,15 +5,12 @@ namespace Inno.Core.Collections; -sealed partial class IndexedObjectStore +public sealed partial class IndexedObjectStore where T : class { /// /// Finds items by key and returns a lazy fail-fast enumerable. /// - /// - /// Enumeration throws if the store is modified during iteration. - /// /// /// Key type. /// @@ -26,21 +23,21 @@ sealed partial class IndexedObjectStore /// /// Lazy fail-fast enumerable of matching items. /// + /// + /// Enumeration throws if the store is modified during iteration. + /// public IEnumerable FindFast( IndexedObjectKey key, TKey value ) where TKey : notnull { - var index = GetIndex(key); + IndexedObjectIndex index = GetIndex(key); return EnumerateFind(index, value); } /// /// Finds items by key and returns a stable snapshot. /// - /// - /// The returned list is detached from subsequent store mutations. - /// /// /// Key type. /// @@ -53,6 +50,9 @@ TKey value /// /// A stable snapshot list of matching items. /// + /// + /// The returned list is detached from subsequent store mutations. + /// public IReadOnlyList Find( IndexedObjectKey key, TKey value @@ -61,7 +61,7 @@ TKey value m_lock.EnterReadLock(); try { - var index = GetIndex(key); + IndexedObjectIndex index = GetIndex(key); return BuildFindSnapshot(index, value); } finally @@ -75,21 +75,21 @@ private IEnumerable EnumerateFind( TKey value ) where TKey : notnull { - var version = Volatile.Read(ref m_version); - if ((index.flags & IndexedObjectKeyFlags.Unique) != 0 && index.TryGetSingle(value, out var single) && single != null) + int version = Volatile.Read(ref m_version); + if ((index.flags & IndexedObjectKeyFlags.Unique) != 0 && index.TryGetSingle(value, out T? single) && single is not null) { EnsureVersion(version); yield return single; yield break; } - var set = index.FindUnsafe(value); - if (set == null || set.Count == 0) + HashSet? set = index.FindUnsafe(value); + if (set is null || set.Count == 0) { yield break; } - foreach (var item in set) + foreach (T item in set) { EnsureVersion(version); yield return item; @@ -102,19 +102,19 @@ TKey value ) where TKey : notnull { var result = new List(); - if ((index.flags & IndexedObjectKeyFlags.Unique) != 0 && index.TryGetSingle(value, out var single) && single != null) + if ((index.flags & IndexedObjectKeyFlags.Unique) != 0 && index.TryGetSingle(value, out T? single) && single is not null) { result.Add(single); return result; } - var set = index.FindUnsafe(value); - if (set == null || set.Count == 0) + HashSet? set = index.FindUnsafe(value); + if (set is null || set.Count == 0) { return result; } - foreach (var item in set) + foreach (T item in set) { result.Add(item); } @@ -145,7 +145,7 @@ TKey value m_lock.EnterReadLock(); try { - if (GetIndex(key).TryGetSingle(value, out var item)) + if (GetIndex(key).TryGetSingle(value, out T? item)) { return item; } @@ -160,12 +160,12 @@ TKey value /// /// Returns all stored items as a stable snapshot. /// - /// - /// The returned list is detached from subsequent store mutations. - /// /// /// A snapshot list of all stored items. /// + /// + /// The returned list is detached from subsequent store mutations. + /// public IReadOnlyList All() { m_lock.EnterReadLock(); @@ -184,16 +184,16 @@ public IReadOnlyList All() /// /// Returns all stored items as a lazy fail-fast enumerable. /// - /// - /// Enumeration throws if the store is modified during iteration. - /// /// /// Lazy fail-fast enumerable of all stored items. /// + /// + /// Enumeration throws if the store is modified during iteration. + /// public IEnumerable AllFast() { - var version = Volatile.Read(ref m_version); - foreach (var item in m_activeList) + int version = Volatile.Read(ref m_version); + foreach (T item in m_activeList) { EnsureVersion(version); yield return item; @@ -239,7 +239,7 @@ internal IReadOnlyList ExecuteQuerySnapshot(List ExecuteQuerySnapshot(List? seed = conditions[seedIndex].GetSet(this); + if (seed is null) { - foreach (var item in m_activeList) + foreach (T item in m_activeList) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -283,7 +283,7 @@ internal IReadOnlyList ExecuteQuerySnapshot(List ExecuteQuerySnapshot(List EnumerateQuery(List> conditions) { - var version = Volatile.Read(ref m_version); + int version = Volatile.Read(ref m_version); if (conditions.Count == 0) { - foreach (var item in m_activeList) + foreach (T item in m_activeList) { EnsureVersion(version); yield return item; @@ -327,7 +327,7 @@ private IEnumerable EnumerateQuery(List> cond for (int i = 1; i < conditions.Count; i++) { - var candidateCount = conditions[i].GetCandidateCount(this); + int candidateCount = conditions[i].GetCandidateCount(this); if (candidateCount < seedCount) { seedCount = candidateCount; @@ -340,7 +340,7 @@ private IEnumerable EnumerateQuery(List> cond yield break; } - if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out var single)) + if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out T single)) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -360,10 +360,10 @@ private IEnumerable EnumerateQuery(List> cond yield break; } - var seed = conditions[seedIndex].GetSet(this); - if (seed == null) + HashSet? seed = conditions[seedIndex].GetSet(this); + if (seed is null) { - foreach (var item in m_activeList) + foreach (T item in m_activeList) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -390,7 +390,7 @@ private IEnumerable EnumerateQuery(List> cond yield break; } - foreach (var item in seed) + foreach (T item in seed) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -425,7 +425,7 @@ private IEnumerable EnumerateQuery(List> cond for (int i = 1; i < conditions.Count; i++) { - var candidateCount = conditions[i].GetCandidateCount(this); + int candidateCount = conditions[i].GetCandidateCount(this); if (candidateCount < seedCount) { seedCount = candidateCount; @@ -438,7 +438,7 @@ private IEnumerable EnumerateQuery(List> cond return null; } - if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out var single)) + if (seedCount == 1 && conditions[seedIndex].TryGetSingle(this, out T single)) { for (int i = 0; i < conditions.Count; i++) { @@ -451,10 +451,10 @@ private IEnumerable EnumerateQuery(List> cond return single; } - var seed = conditions[seedIndex].GetSet(this); - if (seed == null) + HashSet? seed = conditions[seedIndex].GetSet(this); + if (seed is null) { - foreach (var item in m_activeList) + foreach (T item in m_activeList) { bool ok = true; for (int i = 0; i < conditions.Count; i++) @@ -480,7 +480,7 @@ private IEnumerable EnumerateQuery(List> cond return null; } - foreach (var item in seed) + foreach (T item in seed) { bool ok = true; for (int i = 0; i < conditions.Count; i++) diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs index 5e6afd63e..4bfa1f8aa 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs @@ -38,14 +38,14 @@ public sealed partial class IndexedObjectStore : IIndexedObjectStore where T : class { private readonly WeakReference m_storeRef; - private readonly List m_activeList = new(); + private readonly List m_activeList = []; private readonly Dictionary m_activeIndex = new(ReferenceEqualityComparer.INSTANCE); private readonly Dictionary m_handleByItem = new(ReferenceEqualityComparer.INSTANCE); - private readonly List m_sparseToDense = new(); - private readonly List m_generations = new(); - private readonly List m_denseToSlot = new(); + private readonly List m_sparseToDense = []; + private readonly List m_generations = []; + private readonly List m_denseToSlot = []; private Stack m_freeSlots = new(); - private readonly Dictionary> m_indexes = new(); + private readonly Dictionary> m_indexes = []; private readonly Dictionary m_indexByName = new(StringComparer.Ordinal); private readonly ReaderWriterLockSlim m_lock = new(LockRecursionPolicy.NoRecursion); private int m_nextIndexId = 1; @@ -130,7 +130,7 @@ public void RemoveAll() m_activeIndex.Clear(); m_handleByItem.Clear(); m_denseToSlot.Clear(); - foreach (var index in m_indexes.Values) + foreach (IIndexedObjectIndex index in m_indexes.Values) { index.Clear(); } @@ -153,7 +153,7 @@ public void RemoveAll() /// public IndexedObjectEntry Add(T item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -192,7 +192,7 @@ public IndexedObjectEntry Add(T item) /// public bool Remove(T item) { - if (item == null) + if (item is null) { throw new ArgumentNullException(nameof(item)); } @@ -200,20 +200,20 @@ public bool Remove(T item) m_lock.EnterWriteLock(); try { - if (!m_activeIndex.TryGetValue(item, out var index)) + if (!m_activeIndex.TryGetValue(item, out int index)) { return false; } - foreach (var objectIndex in m_indexes.Values) + foreach (IIndexedObjectIndex objectIndex in m_indexes.Values) { objectIndex.Remove(item); } - var lastIndex = m_activeList.Count - 1; - var lastItem = m_activeList[lastIndex]; - var removedSlot = m_denseToSlot[index]; - var lastSlot = m_denseToSlot[lastIndex]; + int lastIndex = m_activeList.Count - 1; + T lastItem = m_activeList[lastIndex]; + int removedSlot = m_denseToSlot[index]; + int lastSlot = m_denseToSlot[lastIndex]; m_activeList.RemoveAt(lastIndex); m_denseToSlot.RemoveAt(lastIndex); m_activeIndex.Remove(item); diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs index e25b2e289..53aef8dcb 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyOrdering/SortedKeyOrdering.cs @@ -47,7 +47,7 @@ public SortedKeyOrdering(IComparer comparer) /// public IEnumerable Enumerate() { - foreach (var key in m_keys) + foreach (TKey key in m_keys) { yield return key; } diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs index b44fe9b23..b6b53e9a3 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/MultiKeyStorage.cs @@ -26,13 +26,13 @@ public bool Add( TKey key, T item ) { - if (!m_map.TryGetValue(key, out var set)) + if (!m_map.TryGetValue(key, out HashSet? set)) { set = new HashSet(IndexedObjectStore.ReferenceEqualityComparer.INSTANCE); m_map[key] = set; } - var added = set.Add(item); + bool added = set.Add(item); return added && set.Count == 1; } @@ -49,7 +49,7 @@ public void Remove( TKey key, T item ) { - if (!m_map.TryGetValue(key, out var set)) + if (!m_map.TryGetValue(key, out HashSet? set)) { return; } @@ -78,12 +78,12 @@ public bool TryGetSingle( out T? item ) { item = null; - if (!m_map.TryGetValue(key, out var set) || set.Count == 0) + if (!m_map.TryGetValue(key, out HashSet? set) || set.Count == 0) { return false; } - using var e = set.GetEnumerator(); + using HashSet.Enumerator e = set.GetEnumerator(); if (!e.MoveNext()) { return false; @@ -103,7 +103,7 @@ out T? item /// The scalar result calculated from the supplied inputs. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int GetCount(TKey key) => m_map.TryGetValue(key, out var set) ? set.Count : 0; + public int GetCount(TKey key) => m_map.TryGetValue(key, out HashSet? set) ? set.Count : 0; /// /// Determines whether current state contains the requested value value. @@ -121,7 +121,7 @@ out T? item public bool Contains( TKey key, T item - ) => m_map.TryGetValue(key, out var set) && set.Contains(item); + ) => m_map.TryGetValue(key, out HashSet? set) && set.Contains(item); /// /// Determines whether a key currently has no indexed values. @@ -133,7 +133,7 @@ T item /// when the requested condition is satisfied; otherwise, . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool IsKeyEmpty(TKey key) => !m_map.TryGetValue(key, out var set) || set.Count == 0; + public bool IsKeyEmpty(TKey key) => !m_map.TryGetValue(key, out HashSet? set) || set.Count == 0; /// /// Retrieves the requested set value from current authoritative state. @@ -145,7 +145,7 @@ T item /// The validated hash sett? that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public HashSet? GetSet(TKey key) => m_map.TryGetValue(key, out var set) ? set : EMPTY_SET; + public HashSet? GetSet(TKey key) => m_map.TryGetValue(key, out HashSet? set) ? set : EMPTY_SET; /// /// Removes all retained entries and returns the instance to an empty reusable state. diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs index b83fecdbf..d463afed1 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/KeyStorage/UniqueKeyStorage.cs @@ -26,7 +26,7 @@ public bool Add( TKey key, T item ) { - if (m_map.TryGetValue(key, out var existing) && !ReferenceEquals(existing, item)) + if (m_map.TryGetValue(key, out T? existing) && !ReferenceEquals(existing, item)) { throw new InvalidOperationException($"Duplicate key '{key}' in unique index."); } @@ -48,7 +48,7 @@ public void Remove( TKey key, T item ) { - if (m_map.TryGetValue(key, out var existing) && ReferenceEquals(existing, item)) + if (m_map.TryGetValue(key, out T? existing) && ReferenceEquals(existing, item)) { m_map.Remove(key); } @@ -99,7 +99,7 @@ out T? item public bool Contains( TKey key, T item - ) => m_map.TryGetValue(key, out var existing) && ReferenceEquals(existing, item); + ) => m_map.TryGetValue(key, out T? existing) && ReferenceEquals(existing, item); /// /// Determines whether a key currently has no indexed values. diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs index 0a6c8506d..aa51f78dd 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectKeyCondition.cs @@ -39,12 +39,12 @@ TKey value /// /// Gets a candidate count required by the implemented contract. /// - /// - /// The scalar result calculated from the supplied inputs. - /// /// /// The store consumed by get candidate count; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The scalar result calculated from the supplied inputs. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetCandidateCount(IndexedObjectStore store) => store.GetCountUnsafe(m_key, m_value); @@ -65,7 +65,7 @@ public bool TryGetSingle( IndexedObjectStore store, out T item ) { - if (store.TryGetSingleUnsafe(m_key, m_value, out var found) && found != null) + if (store.TryGetSingleUnsafe(m_key, m_value, out T? found) && found is not null) { item = found; return true; @@ -78,12 +78,12 @@ out T item /// /// Gets a set required by the implemented contract. /// - /// - /// The validated hash sett? that represents the completed operation. - /// /// /// The store consumed by get set; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The validated hash sett? that represents the completed operation. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public HashSet? GetSet(IndexedObjectStore store) => store.GetSetUnsafe(m_key, m_value); @@ -93,12 +93,12 @@ out T item /// /// The store consumed by validate; ownership remains with the caller unless explicitly stated otherwise. /// - /// - /// when the operation succeeds or its condition is satisfied; otherwise, . - /// /// /// The stored item associated with the validated handle. /// + /// + /// when the operation succeeds or its condition is satisfied; otherwise, . + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Validate( IndexedObjectStore store, diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs index 29e421172..87ed88892 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/QueryCondition/IndexedObjectPredicateCondition.cs @@ -77,12 +77,12 @@ out T item /// /// The store consumed by validate; ownership remains with the caller unless explicitly stated otherwise. /// - /// - /// when the operation succeeds or its condition is satisfied; otherwise, . - /// /// /// The stored item associated with the validated handle. /// + /// + /// when the operation succeeds or its condition is satisfied; otherwise, . + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Validate( IndexedObjectStore store, diff --git a/src/foundation/core/Inno.Core.Coroutines/CoroutineHandle.cs b/src/foundation/core/Inno.Core.Coroutines/CoroutineHandle.cs index 5587df7e8..364263196 100644 --- a/src/foundation/core/Inno.Core.Coroutines/CoroutineHandle.cs +++ b/src/foundation/core/Inno.Core.Coroutines/CoroutineHandle.cs @@ -41,10 +41,8 @@ public bool isValid } internal bool IsOwnedBy(CoroutineScheduler scheduler) - { - return m_id > 0 - && m_schedulerRef is not null - && m_schedulerRef.TryGetTarget(out CoroutineScheduler? target) - && ReferenceEquals(target, scheduler); - } + => m_id > 0 + && m_schedulerRef is not null + && m_schedulerRef.TryGetTarget(out CoroutineScheduler? target) + && ReferenceEquals(target, scheduler); } diff --git a/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs b/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs index 2bdcd3a4e..5e20826c5 100644 --- a/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs +++ b/src/foundation/core/Inno.Core.Coroutines/CoroutineScheduler.cs @@ -15,8 +15,8 @@ public sealed class CoroutineScheduler : IDisposable { private readonly ConcurrentQueue m_commands = new(); private readonly ConcurrentDictionary m_liveIds = new(); - private readonly Dictionary m_states = new(); - private readonly List m_active = new(); + private readonly Dictionary m_states = []; + private readonly List m_active = []; private readonly Lock m_tickGate = new(); private readonly WeakReference m_selfRef; private long m_nextId; @@ -46,10 +46,7 @@ public CoroutineScheduler() /// /// Coroutine handle. /// - public CoroutineHandle StartCoroutine(IEnumerator routine) - { - return StartCoroutine(null, routine); - } + public CoroutineHandle StartCoroutine(IEnumerator routine) => StartCoroutine(null, routine); /// /// Starts a coroutine with an owner token. @@ -238,10 +235,7 @@ internal bool Contains(CoroutineHandle handle) return handle.isValid; } - internal bool IsHandleValid(long id) - { - return Volatile.Read(ref m_disposed) == 0 && id > 0 && m_liveIds.ContainsKey(id); - } + internal bool IsHandleValid(long id) => Volatile.Read(ref m_disposed) == 0 && id > 0 && m_liveIds.ContainsKey(id); private void ApplyPendingCommands() { @@ -263,7 +257,7 @@ private void ApplyPendingCommands() { break; } - CoroutineState state = new(cmd.id, cmd.owner, cmd.routine); + var state = new CoroutineState(cmd.id, cmd.owner, cmd.routine); m_states.Add(state.id, state); m_active.Add(state.id); if (Volatile.Read(ref m_disposed) != 0) diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs index 4e421f515..b66d8294d 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticHub.cs @@ -93,10 +93,7 @@ long epoch /// /// A strict last-in-first-out scope owned by the caller. /// - public IDisposable EnterScope() - { - return S_CURRENT_SCOPE.Enter(this); - } + public IDisposable EnterScope() => S_CURRENT_SCOPE.Enter(this); /// /// Registers a sink and synchronously replays every active report before registration completes. diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs index 7b4e49e3e..166d591a9 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticLocation.cs @@ -65,12 +65,12 @@ public DiagnosticLocation( /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The value to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public bool Equals(DiagnosticLocation other) => string.Equals(sourcePath, other.sourcePath, StringComparison.Ordinal) && line == other.line @@ -79,12 +79,12 @@ public bool Equals(DiagnosticLocation other) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is DiagnosticLocation other && Equals(other); /// diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs index 0c8906e4a..8701b7425 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticReporter.cs @@ -115,7 +115,7 @@ public void Replace(IEnumerable diagnostics) DiagnosticHub hub = GetHub(); hub.SetOwned(m_source, m_epoch, candidate.Values.ToArray()); m_issues.Clear(); - foreach (var entry in candidate) + foreach (KeyValuePair entry in candidate) { m_issues.Add(entry.Key, entry.Value); } diff --git a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs index d1ec35c23..dae4ed24f 100644 --- a/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs +++ b/src/foundation/core/Inno.Core.Diagnostics/DiagnosticSource.cs @@ -48,23 +48,23 @@ string displayName /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The value to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public bool Equals(DiagnosticSource other) => string.Equals(id, other.id, StringComparison.Ordinal); /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is DiagnosticSource other && Equals(other); /// diff --git a/src/foundation/core/Inno.Core.Events/EventDispatcher.cs b/src/foundation/core/Inno.Core.Events/EventDispatcher.cs index 9a8925560..f310d24fa 100644 --- a/src/foundation/core/Inno.Core.Events/EventDispatcher.cs +++ b/src/foundation/core/Inno.Core.Events/EventDispatcher.cs @@ -42,7 +42,7 @@ public sealed class EventDispatcher /// A budget is not positive. /// public EventDispatcher( - int queueCapacity = 65536, + int queueCapacity = 65_536, int flushBudget = 4096 ) { if (queueCapacity <= 0) @@ -75,7 +75,7 @@ public EventHub CreateHub(int order = 0) { lock (m_hubsGate) { - EventHub hub = new(this, order, m_nextHubSequence++); + var hub = new EventHub(this, order, m_nextHubSequence++); List hubs = [..m_hubsSnapshot, hub]; SortHubs(hubs); Volatile.Write(ref m_hubsSnapshot, [..hubs]); @@ -157,13 +157,13 @@ public int DiscardPending() /// /// Immediately dispatches an event to all valid hubs in priority order. /// + /// + /// The event instance to dispatch. + /// /// /// Hub dispatch stops when the event is marked globally handled. Completion observers are still notified. /// A failed hub propagates its exception without reporting successful completion. /// - /// - /// The event instance to dispatch. - /// public void Emit(Event e) { ArgumentNullException.ThrowIfNull(e); @@ -210,19 +210,17 @@ internal void NotifyHubOrderChanged() } private static void SortHubs(List hubs) - { - hubs.Sort(static ( + => hubs.Sort(static ( a, b ) => { - int byOrder = b.order.CompareTo(a.order); - if (byOrder != 0) - { - return byOrder; - } - - return a.sequence.CompareTo(b.sequence); - }); - } + int byOrder = b.order.CompareTo(a.order); + if (byOrder != 0) + { + return byOrder; + } + + return a.sequence.CompareTo(b.sequence); + }); } diff --git a/src/foundation/core/Inno.Core.Events/EventHub.cs b/src/foundation/core/Inno.Core.Events/EventHub.cs index f3db3ed55..7b9e744a6 100644 --- a/src/foundation/core/Inno.Core.Events/EventHub.cs +++ b/src/foundation/core/Inno.Core.Events/EventHub.cs @@ -105,9 +105,9 @@ public IDisposable Listen( listenerOrder = m_nextListenerOrder++; Action invoker = e => handler((TEvent)e); - Listener listener = new(invoker, priority, listenerOrder); + var listener = new Listener(invoker, priority, listenerOrder); - Dictionary nextBuckets = new(Volatile.Read(ref m_state).buckets); + var nextBuckets = new Dictionary(Volatile.Read(ref m_state).buckets); Listener[] existing = nextBuckets.TryGetValue(eventType, out Listener[]? items) ? items : []; nextBuckets[eventType] = ListenerBucket.InsertSorted(existing, listener); Volatile.Write(ref m_state, new HubState(nextBuckets)); @@ -140,7 +140,7 @@ public IDisposable ListenOnce( ThrowIfInvalid(); ArgumentNullException.ThrowIfNull(handler); - OneShotSubscription oneShot = new(handler); + var oneShot = new OneShotSubscription(handler); IDisposable subscription = Listen(oneShot.Invoke, priority); oneShot.Bind(subscription); return oneShot; @@ -149,13 +149,13 @@ public IDisposable ListenOnce( /// /// Immediately dispatches an event inside this hub only. /// + /// + /// The event instance to dispatch locally. + /// /// /// This does not route through the dispatcher hub chain. /// Only listeners registered on this hub are invoked. /// - /// - /// The event instance to dispatch locally. - /// public void Announce(Event e) { ThrowIfInvalid(); @@ -244,7 +244,7 @@ long listenerOrder return; } - Dictionary nextBuckets = new(Volatile.Read(ref m_state).buckets); + var nextBuckets = new Dictionary(Volatile.Read(ref m_state).buckets); if (!nextBuckets.TryGetValue(eventType, out Listener[]? existing)) { return; @@ -412,7 +412,7 @@ public static Listener[] InsertSorted( Listener[] source, Listener listener ) { - Listener[] result = new Listener[source.Length + 1]; + var result = new Listener[source.Length + 1]; int index = 0; while (index < source.Length) { @@ -483,7 +483,7 @@ long listenerOrder return []; } - Listener[] result = new Listener[source.Length - 1]; + var result = new Listener[source.Length - 1]; if (index > 0) { Array.Copy(source, 0, result, 0, index); @@ -503,7 +503,7 @@ private sealed class HubState(Dictionary buckets) /// /// The empty value used as part of this type's public representation. /// - public static readonly HubState Empty = new(new Dictionary()); + public static readonly HubState Empty = new([]); /// /// Gets the immutable listener buckets captured for one dispatch operation. diff --git a/src/foundation/core/Inno.Core.Events/Events/Event.cs b/src/foundation/core/Inno.Core.Events/Events/Event.cs index d626beaab..b1d9a6f50 100644 --- a/src/foundation/core/Inno.Core.Events/Events/Event.cs +++ b/src/foundation/core/Inno.Core.Events/Events/Event.cs @@ -17,7 +17,10 @@ public abstract class Event /// /// Creates an event with an independent global consumption lifetime. /// - protected Event() => m_consumptionOwner = this; + protected Event() + { + m_consumptionOwner = this; + } /// /// Creates a routed representation that shares global consumption with its source event. @@ -45,21 +48,18 @@ protected Event(Event source) /// /// Global handling stops dispatch in the current hub and all following hubs. /// - public void HandleInGlobal() - { - Volatile.Write(ref m_consumptionOwner.m_globalHandled, 1); - } + public void HandleInGlobal() => Volatile.Write(ref m_consumptionOwner.m_globalHandled, 1); /// /// Marks this event as handled in the current hub only. /// + /// + /// Thrown when called outside a valid hub dispatch context for this event. + /// /// /// Hub handling stops remaining listeners in the current hub /// but does not affect following hubs. /// - /// - /// Thrown when called outside a valid hub dispatch context for this event. - /// public void HandleInHub() { HubFrameStack? frames = t_hubFrames; @@ -98,10 +98,7 @@ Event eventRef /// /// Releases the resources owned by this instance. /// - public void Dispose() - { - frames.PopIfCurrent(eventRef); - } + public void Dispose() => frames.PopIfCurrent(eventRef); } internal sealed class HubFrameStack @@ -145,10 +142,7 @@ public void Push(Event e) /// /// when the requested condition is satisfied; otherwise, . /// - public bool IsCurrent(Event e) - { - return m_count > 0 && ReferenceEquals(m_events[m_count - 1], e); - } + public bool IsCurrent(Event e) => m_count > 0 && ReferenceEquals(m_events[m_count - 1], e); /// /// Marks the current event handled without changing another event context. @@ -171,11 +165,9 @@ public void MarkHandledCurrent() /// when the requested condition is satisfied; otherwise, . /// public bool IsCurrentHandled(Event e) - { - return m_count > 0 - && ReferenceEquals(m_events[m_count - 1], e) - && m_handled[m_count - 1]; - } + => m_count > 0 + && ReferenceEquals(m_events[m_count - 1], e) + && m_handled[m_count - 1]; /// /// Removes the supplied event only when it is the current execution context. diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs b/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs index 5a825e954..611e5bec1 100644 --- a/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs +++ b/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs @@ -13,7 +13,10 @@ public abstract class MouseEvent : Event /// /// The platform window that produced the event. /// - protected MouseEvent(uint windowId) => this.windowId = windowId; + protected MouseEvent(uint windowId) + { + this.windowId = windowId; + } /// /// Creates a routed mouse event sharing its source's window and global consumption. @@ -25,7 +28,10 @@ public abstract class MouseEvent : Event /// The source event is null. /// protected MouseEvent(MouseEvent source) - : base(source) => windowId = source.windowId; + : base(source) + { + this.windowId = source.windowId; + } /// /// Gets the source window id for this event. diff --git a/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs b/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs index aaa992d92..702a085f6 100644 --- a/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs +++ b/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs @@ -179,13 +179,13 @@ public Task RunAsync( /// /// Stops new registrations and invokes cancellation callbacks on the calling thread. /// + /// + /// One or more cancellation callbacks fail. + /// /// /// Callbacks must return promptly. Dependent resources remain owned while cancellation callbacks execute, /// including when another thread attempts disposal. A callback reporting pending work permanently blocks release. /// - /// - /// One or more cancellation callbacks fail. - /// public void Cancel() { lock (m_sync) @@ -233,16 +233,16 @@ public void Cancel() /// /// Releases a quiescent lifetime in reverse registration order, continuing after ordinary cleanup failures. /// - /// - /// Pending retirement retains the current resource and all remaining dependencies for a later attempt. - /// Concurrent or reentrant retirement reports pending work without invoking a resource twice. - /// /// /// Tracked work remains active; drain it before retrying. /// /// /// Cancellation, work or resource retirement fails. /// + /// + /// Pending retirement retains the current resource and all remaining dependencies for a later attempt. + /// Concurrent or reentrant retirement reports pending work without invoking a resource twice. + /// public void Dispose() { lock (m_sync) @@ -286,16 +286,16 @@ public void Dispose() /// /// Cancels and asynchronously drains tracked work before reverse-order release. /// - /// - /// Only use asynchronous disposal for thread-neutral resources. Control-thread owners must await their work - /// and call synchronous disposal at their own safe point; this method does not marshal to an owner thread. - /// /// /// A task that completes only after work and resource retirement finish. /// /// /// Cancellation, work or resource retirement fails. /// + /// + /// Only use asynchronous disposal for thread-neutral resources. Control-thread owners must await their work + /// and call synchronous disposal at their own safe point; this method does not marshal to an owner thread. + /// public async ValueTask DisposeAsync() { try @@ -382,7 +382,10 @@ private void RetireResources() m_cancellation.Dispose(); if (m_retirementFailures.Count > 0) { - var failure = new AggregateException("Lifetime retirement failed after all resources were attempted.", m_retirementFailures); + var failure = new AggregateException( + "Lifetime retirement failed after all resources were attempted.", + m_retirementFailures + ); m_retirementFailures.Clear(); throw failure; } @@ -436,7 +439,7 @@ private void ObserveCompletion(Task task) { return; } - var owner = (LifetimeScope)state!; + LifetimeScope owner = (LifetimeScope)state!; lock (owner.m_sync) { owner.m_tasks.Remove(completed); @@ -459,8 +462,10 @@ TaskCompletionSource completion try { TResult result; - using (var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, m_cancellation.Token)) - { + using (CancellationTokenSource linked = CancellationTokenSource.CreateLinkedTokenSource( + cancellationToken, + m_cancellation.Token + )) { result = await operation(linked.Token).ConfigureAwait(false); } lock (m_sync) diff --git a/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs b/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs index 30719f897..fe964bf9b 100644 --- a/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs +++ b/src/foundation/core/Inno.Core.Execution/OwnerThreadExecution.cs @@ -58,7 +58,7 @@ private sealed class OwnerContext : SynchronizationContext, IDisposable private readonly BlockingCollection m_callbacks = new(); private readonly int m_threadId = Environment.CurrentManagedThreadId; - /// + /// public override void Post( SendOrPostCallback callback, object? state @@ -67,7 +67,7 @@ public override void Post( m_callbacks.Add(() => callback(state)); } - /// + /// public override void Send( SendOrPostCallback callback, object? state @@ -99,10 +99,10 @@ public override void Send( failure?.Throw(); } - /// + /// public override SynchronizationContext CreateCopy() => this; - /// + /// public void Dispose() => m_callbacks.Dispose(); internal void Pump(Task completion) diff --git a/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs b/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs index 79e140fc0..8da0e7a51 100644 --- a/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs +++ b/src/foundation/core/Inno.Core.Execution/RetirementBarrier.cs @@ -52,10 +52,6 @@ public RetirementBarrier( /// /// True after retirement completes, or false while work remains within its deadline. /// - /// - /// Wrapped pending failures retain their ownership semantics. A nested timeout is rethrown in its original - /// exception tree. Ordinary sibling failures survive retries and are reported once retirement completes. - /// /// /// Retirement completed after earlier ordinary failures, or the owner reported a wrapped terminal timeout. /// @@ -65,6 +61,10 @@ public RetirementBarrier( /// /// The caller is not the thread that created this barrier. /// + /// + /// Wrapped pending failures retain their ownership semantics. A nested timeout is rethrown in its original + /// exception tree. Ordinary sibling failures survive retries and are reported once retirement completes. + /// public bool TryComplete(Action retire) { ArgumentNullException.ThrowIfNull(retire); @@ -144,7 +144,10 @@ public void Wait(Action retire) private AggregateException TakeCompletedFailure() { - var failure = new AggregateException($"Owner '{m_owner}' retired with completed cleanup failures.", m_completedFailures); + var failure = new AggregateException( + $"Owner '{m_owner}' retired with completed cleanup failures.", + m_completedFailures + ); m_completedFailures.Clear(); return failure; } diff --git a/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs b/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs index 6a683b7bd..017da7972 100644 --- a/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs +++ b/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs @@ -272,7 +272,7 @@ public void ReplaceContents(GraphDocument source) edges.Add(new GraphEdgeRecord(sourceEdge.id, sourceEdge.output, sourceEdge.input)); } - Dictionary metadata = new(StringComparer.Ordinal); + var metadata = new Dictionary(StringComparer.Ordinal); foreach ((string key, GraphSerializedValue value) in source.metadata) { metadata.Add(key, value.Clone()); diff --git a/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs b/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs index 989625f7d..f062764ed 100644 --- a/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs +++ b/src/foundation/core/Inno.Core.IO/AtomicDirectory.cs @@ -21,11 +21,6 @@ public static class AtomicDirectory /// /// Cancels preparation or bounded waits before the rename commits. /// - /// - /// Windows access and sharing failures are retried for at most two seconds to tolerate temporary readers. - /// Cancellation observed after a blocked rename takes precedence over its timeout error. - /// Failure preserves the candidate and any existing destination. A committed rename is not canceled afterward. - /// /// /// A path is blank or the two directory trees overlap. /// @@ -41,6 +36,11 @@ public static class AtomicDirectory /// /// Cancellation is observed before publication, including while handling a failed rename. /// + /// + /// Windows access and sharing failures are retried for at most two seconds to tolerate temporary readers. + /// Cancellation observed after a blocked rename takes precedence over its timeout error. + /// Failure preserves the candidate and any existing destination. A committed rename is not canceled afterward. + /// public static void Publish( string source, string destination, @@ -81,13 +81,6 @@ public static void Publish( /// /// Cancels preparation or bounded rename waits before the candidate commits. /// - /// - /// The caller must serialize readers and writers while the two directory moves run. - /// Cancellation before commit restores the previous destination without canceling rollback. - /// Cancellation observed after a blocked rename takes precedence over its timeout error. - /// A committed candidate is not canceled afterward. - /// Backup cleanup runs after commit; its failure preserves the installed candidate and remaining backup. - /// /// /// Either path is blank, or the candidate and destination trees overlap. /// @@ -109,6 +102,13 @@ public static void Publish( /// /// Cancellation is observed before the candidate commits, including while handling a failed rename. Any moved previous tree is restored. /// + /// + /// The caller must serialize readers and writers while the two directory moves run. + /// Cancellation before commit restores the previous destination without canceling rollback. + /// Cancellation observed after a blocked rename takes precedence over its timeout error. + /// A committed candidate is not canceled afterward. + /// Backup cleanup runs after commit; its failure preserves the installed candidate and remaining backup. + /// public static void Install( string source, string destination, diff --git a/src/foundation/core/Inno.Core.IO/AtomicFile.cs b/src/foundation/core/Inno.Core.IO/AtomicFile.cs index e2f4eeb47..b0f79260e 100644 --- a/src/foundation/core/Inno.Core.IO/AtomicFile.cs +++ b/src/foundation/core/Inno.Core.IO/AtomicFile.cs @@ -19,12 +19,12 @@ public static class AtomicFile /// /// True for a nonempty destination name followed by the reserved marker and a complete hexadecimal operation identity. /// - /// - /// Recognition excludes transient payloads from source discovery. It does not establish ownership or authorize deletion. - /// /// /// The path is null. /// + /// + /// Recognition excludes transient payloads from source discovery. It does not establish ownership or authorize deletion. + /// public static bool IsCandidatePath(string path) { ArgumentNullException.ThrowIfNull(path); @@ -96,12 +96,6 @@ public static void WriteAllBytes( /// /// Whether an existing destination may be replaced; false never overwrites an external creator. /// - /// - /// A failed create-only publication preserves the candidate. After successful publication the - /// candidate is removed; a subsequent cleanup failure reports that the complete target exists. - /// Unix create-only publication requires same-directory hard-link support. The caller must own - /// the candidate and parent directory until the operation completes. - /// /// /// Publication fails, create-only mode finds an existing destination, or candidate retirement /// fails after the complete destination has been published. @@ -109,6 +103,12 @@ public static void WriteAllBytes( /// /// The host does not provide an atomic create-only filesystem primitive. /// + /// + /// A failed create-only publication preserves the candidate. After successful publication the + /// candidate is removed; a subsequent cleanup failure reports that the complete target exists. + /// Unix create-only publication requires same-directory hard-link support. The caller must own + /// the candidate and parent directory until the operation completes. + /// public static void Install( string source, string destination, diff --git a/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs b/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs index cdb4f140b..c9839b0ef 100644 --- a/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs +++ b/src/foundation/core/Inno.Core.IO/FileByteDocumentStore.cs @@ -29,26 +29,26 @@ public FileByteDocumentStore(string path) m_path = Path.GetFullPath(path); } - /// + /// public string documentName => m_path; - /// + /// public bool canWrite => true; - /// + /// public bool exists => File.Exists(m_path); - /// - /// - /// One rename-compatible handle pins the selected complete publication until its owned bytes are read. - /// Writers must atomically replace the document rather than modify the selected file in place. - /// /// /// The document cannot be read completely or exceeds the maximum supported byte-array size. /// /// /// The selected location denies reading or names a directory instead of a document. /// + /// + /// One rename-compatible handle pins the selected complete publication until its owned bytes are read. + /// Writers must atomically replace the document rather than modify the selected file in place. + /// + /// public byte[]? Read() { try @@ -73,6 +73,6 @@ public FileByteDocumentStore(string path) } } - /// + /// public void Write(ReadOnlySpan data) => AtomicFile.WriteAllBytes(m_path, data); } diff --git a/src/foundation/core/Inno.Core.IO/FileLease.cs b/src/foundation/core/Inno.Core.IO/FileLease.cs index cf3709ef4..27695e48a 100644 --- a/src/foundation/core/Inno.Core.IO/FileLease.cs +++ b/src/foundation/core/Inno.Core.IO/FileLease.cs @@ -13,7 +13,10 @@ public sealed class FileLease : IDisposable { private readonly FileStream m_stream; - private FileLease(FileStream stream) => m_stream = stream; + private FileLease(FileStream stream) + { + m_stream = stream; + } /// /// Waits for exclusive ownership without blocking an owner thread or changing shared data. @@ -30,10 +33,6 @@ public sealed class FileLease : IDisposable /// /// The exclusive lease whose disposal permits the next participant to acquire ownership. /// - /// - /// Lease files remain after disposal. Removing them would let Unix processes lock different - /// inodes for the same path while an earlier participant still owns the original inode. - /// /// /// The path is empty or relative, or the timeout is negative and not infinite. /// @@ -49,6 +48,10 @@ public sealed class FileLease : IDisposable /// /// The operating system denies access to the lease path. /// + /// + /// Lease files remain after disposal. Removing them would let Unix processes lock different + /// inodes for the same path while an earlier participant still owns the original inode. + /// public static async ValueTask AcquireAsync( string path, TimeSpan timeout, @@ -129,7 +132,7 @@ CancellationToken cancellationToken cancellationToken.ThrowIfCancellationRequested(); try { - FileStream stream = new(path, mode, access, sharing); + var stream = new FileStream(path, mode, access, sharing); if (cancellationToken.IsCancellationRequested) { stream.Dispose(); @@ -159,6 +162,6 @@ CancellationToken cancellationToken private static bool IsCompetingOwnership(IOException failure) // .NET reports Unix flock contention as raw errno; Darwin uses EWOULDBLOCK 35. => OperatingSystem.IsWindows() - ? (failure.HResult & 0xffff) is 32 or 33 + ? (failure.HResult & 0xFFFF) is 32 or 33 : failure.HResult == (OperatingSystem.IsMacOS() ? 35 : 11); } diff --git a/src/foundation/core/Inno.Core.IO/FileSystemRename.cs b/src/foundation/core/Inno.Core.IO/FileSystemRename.cs index 5c6f1b74d..fa875bbe1 100644 --- a/src/foundation/core/Inno.Core.IO/FileSystemRename.cs +++ b/src/foundation/core/Inno.Core.IO/FileSystemRename.cs @@ -72,6 +72,6 @@ CancellationToken cancellationToken private static bool IsTemporarilyBlocked(Exception exception) => OperatingSystem.IsWindows() && exception is IOException or UnauthorizedAccessException - && exception.HResult is unchecked((int)0x80070005) - or unchecked((int)0x80070020) or unchecked((int)0x80070021); + && exception.HResult is unchecked((int)0x8007_0005) + or unchecked((int)0x8007_0020) or unchecked((int)0x8007_0021); } diff --git a/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs b/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs index 45395d238..912500600 100644 --- a/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs +++ b/src/foundation/core/Inno.Core.IO/OwnedReadStream.cs @@ -41,45 +41,45 @@ IDisposable owner m_owner = owner; } - /// + /// public override bool CanRead => !m_inputClosed && m_input.CanRead; - /// + /// public override bool CanSeek => !m_inputClosed && m_input.CanSeek; - /// + /// public override bool CanWrite => false; - /// + /// public override long Length => m_input.Length; - /// + /// public override long Position { get => m_input.Position; set => m_input.Position = value; } - /// + /// public override int Read( byte[] buffer, int offset, int count ) => m_input.Read(buffer, offset, count); - /// + /// public override int Read(Span buffer) => m_input.Read(buffer); - /// + /// public override int ReadByte() => m_input.ReadByte(); - /// + /// public override ValueTask ReadAsync( Memory buffer, CancellationToken cancellationToken = default ) => m_input.ReadAsync(buffer, cancellationToken); - /// + /// public override Task ReadAsync( byte[] buffer, int offset, @@ -87,26 +87,26 @@ public override Task ReadAsync( CancellationToken cancellationToken ) => m_input.ReadAsync(buffer, offset, count, cancellationToken); - /// + /// public override long Seek( long offset, SeekOrigin origin ) => m_input.Seek(offset, origin); - /// + /// public override void Flush() => throw new NotSupportedException(); - /// + /// public override void SetLength(long value) => throw new NotSupportedException(); - /// + /// public override void Write( byte[] buffer, int offset, int count ) => throw new NotSupportedException(); - /// + /// protected override void Dispose(bool disposing) { if (disposing) diff --git a/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs b/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs index 586509ed6..1d80f25a8 100644 --- a/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs +++ b/src/foundation/core/Inno.Core.IO/ProcessOwnedDirectory.cs @@ -28,7 +28,7 @@ private ProcessOwnedDirectory( CoordinatedFileLease lease ) { m_root = root; - directory = path; + this.directory = path; m_record = record; m_owner = owner; m_lease = lease; diff --git a/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs b/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs index 335ad11f6..594824218 100644 --- a/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs +++ b/src/foundation/core/Inno.Core.IO/ReadOnlyByteDocumentStore.cs @@ -27,19 +27,19 @@ ReadOnlySpan data m_data = data.ToArray(); } - /// + /// public string documentName { get; } - /// + /// public bool canWrite => false; - /// + /// public bool exists => true; - /// + /// public byte[] Read() => (byte[])m_data.Clone(); - /// + /// public void Write(ReadOnlySpan data) => throw new NotSupportedException($"Document '{documentName}' is read-only."); } diff --git a/src/foundation/core/Inno.Core.Identity/Identity.cs b/src/foundation/core/Inno.Core.Identity/Identity.cs index 997bdc468..146809d18 100644 --- a/src/foundation/core/Inno.Core.Identity/Identity.cs +++ b/src/foundation/core/Inno.Core.Identity/Identity.cs @@ -22,7 +22,7 @@ public int? runtimeId { get { - if (m_registryRef == null || !m_registryRef.TryGetTarget(out IdentityRegistry? registry)) + if (m_registryRef is null || !m_registryRef.TryGetTarget(out IdentityRegistry? registry)) { return null; } @@ -41,7 +41,7 @@ public RuntimeIdentity? runtimeIdentity { get { - if (m_registryRef == null || !m_registryRef.TryGetTarget(out IdentityRegistry? registry)) + if (m_registryRef is null || !m_registryRef.TryGetTarget(out IdentityRegistry? registry)) { return null; } @@ -82,7 +82,7 @@ int runtimeId internal void Unbind(IdentityRegistry registry) { - if (m_registryRef != null + if (m_registryRef is not null && m_registryRef.TryGetTarget(out IdentityRegistry? current) && ReferenceEquals(current, registry) ) { diff --git a/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs b/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs index 98e6f9063..91acc52b6 100644 --- a/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs +++ b/src/foundation/core/Inno.Core.Identity/IdentityAllocator.cs @@ -28,7 +28,7 @@ public IdentityAllocator() { throw new InvalidOperationException("The process exhausted available identity domains."); } - domainId = new IdentityDomainId(nextDomainId); + this.domainId = new IdentityDomainId(nextDomainId); m_registry = new IdentityRegistry(domainId); } @@ -77,10 +77,7 @@ public IdentityAllocator() /// /// Thrown when scopes are disposed out of order. /// - public IDisposable EnterScope() - { - return S_CURRENT_SCOPE.Enter(this); - } + public IDisposable EnterScope() => S_CURRENT_SCOPE.Enter(this); /// /// Registers an object and assigns its session-local runtime identity. diff --git a/src/foundation/core/Inno.Core.Identity/IdentityDomainId.cs b/src/foundation/core/Inno.Core.Identity/IdentityDomainId.cs index 535a64c74..d6b4b57d2 100644 --- a/src/foundation/core/Inno.Core.Identity/IdentityDomainId.cs +++ b/src/foundation/core/Inno.Core.Identity/IdentityDomainId.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; namespace Inno.Core.Identity; @@ -61,7 +62,7 @@ internal IdentityDomainId(int value) /// /// The numeric domain value, or <invalid> when the value is not allocated. /// - public override string ToString() => isValid ? value.ToString(System.Globalization.CultureInfo.InvariantCulture) : ""; + public override string ToString() => isValid ? value.ToString(CultureInfo.InvariantCulture) : ""; /// /// Determines whether two values identify the same runtime domain. diff --git a/src/foundation/core/Inno.Core.Identity/IdentityObject.cs b/src/foundation/core/Inno.Core.Identity/IdentityObject.cs index 66376bba1..da046a2a2 100644 --- a/src/foundation/core/Inno.Core.Identity/IdentityObject.cs +++ b/src/foundation/core/Inno.Core.Identity/IdentityObject.cs @@ -1,3 +1,5 @@ +using System; + namespace Inno.Core.Identity; /// @@ -5,7 +7,7 @@ namespace Inno.Core.Identity; /// public abstract class IdentityObject { - private Identity m_identity = new(System.Guid.NewGuid()); + private Identity m_identity = new(Guid.NewGuid()); /// /// Gets this object's current persistent and optional session-local identity snapshot. diff --git a/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs b/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs index 10ec71cfe..f3f8862cf 100644 --- a/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs +++ b/src/foundation/core/Inno.Core.Identity/IdentityRegistry.cs @@ -16,12 +16,12 @@ internal sealed class IdentityRegistry private readonly ConditionalWeakTable m_slotByObject = new(); - private readonly List m_denseToSlot = new(); - private readonly List m_sparseToDense = new(); - private readonly List m_generations = new(); + private readonly List m_denseToSlot = []; + private readonly List m_sparseToDense = []; + private readonly List m_generations = []; private readonly Stack m_freeSlots = new(); - private readonly Dictionary m_slotByPersistent = new(); + private readonly Dictionary m_slotByPersistent = []; internal IdentityRegistry(IdentityDomainId domainId) { @@ -398,9 +398,7 @@ out int denseIndex private bool TryGetDenseIndexByRuntimeIdNoLock( int runtimeId, out int denseIndex - ) { - return TryResolveDenseIndexNoLock(runtimeId, out denseIndex) && TryGetEntryByDenseNoLock(denseIndex, out _); - } + ) => TryResolveDenseIndexNoLock(runtimeId, out denseIndex) && TryGetEntryByDenseNoLock(denseIndex, out _); private bool TryGetEntryByDenseNoLock( int denseIndex, @@ -499,9 +497,7 @@ out int slot private bool TryGetLiveObject( RegistryEntry entry, out IdentityObject? obj - ) { - return entry.TryGetObject(out obj); - } + ) => entry.TryGetObject(out obj); private void CleanupStaleSlotBySlotNoLock(int slot) { @@ -662,6 +658,9 @@ private sealed class RegistrySlot /// /// The dense storage slot encoded in this runtime handle. /// - public RegistrySlot(int slot) => this.slot = slot; + public RegistrySlot(int slot) + { + this.slot = slot; + } } } diff --git a/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs b/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs index 28fe582f4..49918e026 100644 --- a/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs +++ b/src/foundation/core/Inno.Core.Identity/RuntimeIdentity.cs @@ -7,7 +7,7 @@ namespace Inno.Core.Identity; /// /// /// This value is suitable for transient interaction payloads only and must never be persisted. - /// Equality compares the stored domain and runtime identifier; it does not verify that an object is still live. +/// Equality compares the stored domain and runtime identifier; it does not verify that an object is still live. /// public readonly struct RuntimeIdentity : IEquatable { diff --git a/src/foundation/core/Inno.Core.Input/KeyCode.cs b/src/foundation/core/Inno.Core.Input/KeyCode.cs index b1960d8e4..419512da1 100644 --- a/src/foundation/core/Inno.Core.Input/KeyCode.cs +++ b/src/foundation/core/Inno.Core.Input/KeyCode.cs @@ -348,45 +348,56 @@ public enum KeyCode /// /// The plus key. /// - Plus = 187, // '+' key + // '+' key + Plus = 187, /// /// The comma key. /// - Comma = 188, // ',' key + // ',' key + Comma = 188, /// /// The minus key. /// - Minus = 189, // '-' key + // '-' key + Minus = 189, /// /// The period key. /// - Period = 190, // '.' key + // '.' key + Period = 190, /// /// The slash key. /// - Slash = 191, // '/' key + // '/' key + Slash = 191, /// /// The tilde key. /// - Tilde = 192, // '`' key + // '`' key + Tilde = 192, /// /// The backslash key. /// - Backslash = 220, // '\' key + // '\' key + Backslash = 220, /// /// The semicolon key. /// - Semicolon = 186, // ';' key + // ';' key + Semicolon = 186, /// /// The quote key. /// - Quote = 222, // ''' key + // ''' key + Quote = 222, /// /// The left bracket key. /// - LeftBracket = 219, // '[' key + // '[' key + LeftBracket = 219, /// /// The right bracket key. /// - RightBracket = 221 // ']' key + // ']' key + RightBracket = 221 } diff --git a/src/foundation/core/Inno.Core.Jobs/Internal/WorkStealingDeque.cs b/src/foundation/core/Inno.Core.Jobs/Internal/WorkStealingDeque.cs index fa776a5f1..a9db4e931 100644 --- a/src/foundation/core/Inno.Core.Jobs/Internal/WorkStealingDeque.cs +++ b/src/foundation/core/Inno.Core.Jobs/Internal/WorkStealingDeque.cs @@ -79,10 +79,10 @@ private int CountNoLock() private void GrowNoLock() { - var oldBuffer = m_buffer; + T[] oldBuffer = m_buffer; var newBuffer = new T[oldBuffer.Length * 2]; - var count = CountNoLock(); - for (var i = 0; i < count; i++) + int count = CountNoLock(); + for (int i = 0; i < count; i++) { newBuffer[i] = oldBuffer[(m_head + i) % oldBuffer.Length]; } diff --git a/src/foundation/core/Inno.Core.Jobs/Internal/WorkerRuntime.cs b/src/foundation/core/Inno.Core.Jobs/Internal/WorkerRuntime.cs index 55af51831..86a3b49da 100644 --- a/src/foundation/core/Inno.Core.Jobs/Internal/WorkerRuntime.cs +++ b/src/foundation/core/Inno.Core.Jobs/Internal/WorkerRuntime.cs @@ -8,9 +8,9 @@ internal WorkerRuntime( int workerId, ThreadStart loopBody ) { - id = workerId; - localQueue = new WorkStealingDeque(); - thread = new Thread(loopBody) + this.id = workerId; + this.localQueue = new WorkStealingDeque(); + this.thread = new Thread(loopBody) { IsBackground = true, Name = $"Inno.JobWorker.{workerId}" diff --git a/src/foundation/core/Inno.Core.Jobs/JobSchedulerOptions.cs b/src/foundation/core/Inno.Core.Jobs/JobSchedulerOptions.cs index 4cbf0284c..c55b7f0f3 100644 --- a/src/foundation/core/Inno.Core.Jobs/JobSchedulerOptions.cs +++ b/src/foundation/core/Inno.Core.Jobs/JobSchedulerOptions.cs @@ -31,10 +31,10 @@ public readonly struct JobSchedulerOptions /// public int mainThreadDrainBudget { get; init; } - internal int ResolveFrameCapacity() => ResolvePositive(maxFrameJobs, 65536); + internal int ResolveFrameCapacity() => ResolvePositive(maxFrameJobs, 65_536); internal MainThreadWorkQueue CreateMainThreadQueue() - => new(ResolvePositive(mainThreadCapacity, 65536), ResolvePositive(mainThreadDrainBudget, 4096)); + => new(ResolvePositive(mainThreadCapacity, 65_536), ResolvePositive(mainThreadDrainBudget, 4096)); private static int ResolvePositive( int value, @@ -53,8 +53,8 @@ internal int ResolveWorkerCount() if (workerCount == 0) { - var cpuCount = Environment.ProcessorCount; - var resolved = cpuCount > 1 ? cpuCount - 1 : 1; + int cpuCount = Environment.ProcessorCount; + int resolved = cpuCount > 1 ? cpuCount - 1 : 1; return Math.Clamp(resolved, 1, DEFAULT_MAX_WORKER_THREADS); } diff --git a/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs b/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs index d21304f69..0220feac0 100644 --- a/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs +++ b/src/foundation/core/Inno.Core.Jobs/Systems/SingleThreadJobSystem.cs @@ -16,8 +16,8 @@ internal sealed class SingleThreadJobSystem : IJobSystem private static readonly Action s_parallelRangeInvoker = static state => { - var rangeState = (ParallelForRangeState?)state - ?? throw new InvalidOperationException("Parallel-for state cannot be null."); + ParallelForRangeState rangeState = (ParallelForRangeState?)state + ?? throw new InvalidOperationException("Parallel-for state cannot be null."); rangeState.body(rangeState.startInclusive, rangeState.endExclusive); }; @@ -107,10 +107,10 @@ public void EndFrame() } handles.Capacity = m_frameJobs.Count; - for (var i = 0; i < m_frameJobs.Count; i++) + for (int i = 0; i < m_frameJobs.Count; i++) { - var index = m_frameJobs[i]; - if (!TryGetActiveRecordNoLock(index, out var record)) + int index = m_frameJobs[i]; + if (!TryGetActiveRecordNoLock(index, out JobRecord record)) { continue; } @@ -120,7 +120,7 @@ public void EndFrame() } List? faults = null; - for (var i = 0; i < handles.Count; i++) + for (int i = 0; i < handles.Count; i++) { try { @@ -139,10 +139,10 @@ public void EndFrame() lock (m_jobsGate) { - for (var i = 0; i < m_frameJobs.Count; i++) + for (int i = 0; i < m_frameJobs.Count; i++) { - var index = m_frameJobs[i]; - if (!TryGetActiveRecordNoLock(index, out var record)) + int index = m_frameJobs[i]; + if (!TryGetActiveRecordNoLock(index, out JobRecord record)) { continue; } @@ -178,7 +178,7 @@ public void EndFrame() public JobHandle Schedule(Action job) { ArgumentNullException.ThrowIfNull(job); - return Schedule(s_actionInvoker, job, ReadOnlySpan.Empty); + return Schedule(s_actionInvoker, job, []); } /// @@ -219,19 +219,19 @@ ReadOnlySpan dependencies } _ = ResolveHandleNoLock(dependency); } - var index = AllocateJobIndexNoLock(job, state); - var record = m_jobs[index]; + int index = AllocateJobIndexNoLock(job, state); + JobRecord record = m_jobs[index]; - var dependencyCount = 0; - for (var i = 0; i < dependencies.Length; i++) + int dependencyCount = 0; + for (int i = 0; i < dependencies.Length; i++) { - var dependency = dependencies[i]; + JobHandle dependency = dependencies[i]; if (!dependency.isValid) { throw new ArgumentException("Dependency handle is invalid.", nameof(dependencies)); } - var dependencyRecord = ResolveHandleNoLock(dependency); + JobRecord dependencyRecord = ResolveHandleNoLock(dependency); if (dependencyRecord.executionState == JobExecutionState.Completed) { continue; @@ -269,10 +269,7 @@ ReadOnlySpan dependencies /// /// The validated job handle that represents the completed operation. /// - public JobHandle CombineDependencies(ReadOnlySpan dependencies) - { - return Schedule(s_noop, null, dependencies); - } + public JobHandle CombineDependencies(ReadOnlySpan dependencies) => Schedule(s_noop, null, dependencies); /// /// Schedules the indexed range in batches and returns its completion handle. @@ -307,22 +304,22 @@ Action body if (length == 0) { - return Schedule(s_noop, null, ReadOnlySpan.Empty); + return Schedule(s_noop, null, []); } ThrowIfDisposed(); lock (m_jobsGate) { EnsureFrameActiveNoLock(); - var chunkCount = 1 + (length - 1) / batchSize; + int chunkCount = 1 + (length - 1) / batchSize; RequireCapacityNoLock(checked(chunkCount + 1)); var handles = new JobHandle[chunkCount]; - var chunkIndex = 0; - for (var start = 0; start < length;) + int chunkIndex = 0; + for (int start = 0; start < length;) { - var end = start + Math.Min(batchSize, length - start); + int end = start + Math.Min(batchSize, length - start); var state = new ParallelForRangeState(body, start, end); - handles[chunkIndex++] = Schedule(s_parallelRangeInvoker, state, ReadOnlySpan.Empty); + handles[chunkIndex++] = Schedule(s_parallelRangeInvoker, state, []); start = end; } @@ -348,7 +345,7 @@ public void Complete(JobHandle handle) while (true) { - if (TryGetCompletion(handle, out var exception)) + if (TryGetCompletion(handle, out Exception? exception)) { if (exception is not null) { @@ -373,7 +370,7 @@ public void Complete(JobHandle handle) /// public void CompleteAll(ReadOnlySpan handles) { - for (var i = 0; i < handles.Length; i++) + for (int i = 0; i < handles.Length; i++) { Complete(handles[i]); } @@ -467,7 +464,7 @@ private bool TryExecuteSingleQueuedJob() } index = m_readyQueue.Dequeue(); - if (!TryGetActiveRecordNoLock(index, out var record) || record.executionState != JobExecutionState.Queued) + if (!TryGetActiveRecordNoLock(index, out JobRecord record) || record.executionState != JobExecutionState.Queued) { return false; } @@ -479,7 +476,7 @@ private bool TryExecuteSingleQueuedJob() object? state; lock (m_jobsGate) { - var record = m_jobs[index]; + JobRecord record = m_jobs[index]; callback = record.callback; state = record.state; } @@ -497,7 +494,7 @@ private bool TryExecuteSingleQueuedJob() List? readyIndices = null; lock (m_jobsGate) { - if (!TryGetActiveRecordNoLock(index, out var record)) + if (!TryGetActiveRecordNoLock(index, out JobRecord record)) { return true; } @@ -513,10 +510,10 @@ private bool TryExecuteSingleQueuedJob() if (record.dependents is { Count: > 0 }) { readyIndices = []; - for (var i = 0; i < record.dependents.Count; i++) + for (int i = 0; i < record.dependents.Count; i++) { - var dependentIndex = record.dependents[i]; - if (!TryGetActiveRecordNoLock(dependentIndex, out var dependent)) + int dependentIndex = record.dependents[i]; + if (!TryGetActiveRecordNoLock(dependentIndex, out JobRecord dependent)) { continue; } @@ -545,7 +542,7 @@ private void QueueReadyJobs(List readyIndices) { lock (m_jobsGate) { - for (var i = 0; i < readyIndices.Count; i++) + for (int i = 0; i < readyIndices.Count; i++) { m_readyQueue.Enqueue(readyIndices[i]); } @@ -577,7 +574,7 @@ private int AllocateJobIndexNoLock( m_jobs.Add(new JobRecord()); } - var record = m_jobs[index]; + JobRecord record = m_jobs[index]; record.ResetForAllocation(callback, state); m_frameJobs.Add(index); m_peakFrameJobs = Math.Max(m_peakFrameJobs, m_frameJobs.Count); @@ -590,7 +587,7 @@ out Exception? exception ) { lock (m_jobsGate) { - var record = ResolveHandleNoLock(handle); + JobRecord record = ResolveHandleNoLock(handle); if (record.executionState != JobExecutionState.Completed) { exception = null; @@ -609,7 +606,7 @@ private JobRecord ResolveHandleNoLock(JobHandle handle) throw new InvalidOperationException("Job handle index is out of range."); } - var record = m_jobs[handle.index]; + JobRecord record = m_jobs[handle.index]; if (!record.inUse || record.version != handle.version) { throw new InvalidOperationException("Job handle is stale or no longer valid."); diff --git a/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs b/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs index 8c405646c..985e4f89d 100644 --- a/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs +++ b/src/foundation/core/Inno.Core.Jobs/Systems/WorkStealingJobSystem.cs @@ -17,8 +17,8 @@ internal sealed class WorkStealingJobSystem : IJobSystem private static readonly Action s_parallelRangeInvoker = static state => { - var rangeState = (ParallelForRangeState?)state - ?? throw new InvalidOperationException("Parallel-for state cannot be null."); + ParallelForRangeState rangeState = (ParallelForRangeState?)state + ?? throw new InvalidOperationException("Parallel-for state cannot be null."); rangeState.body(rangeState.startInclusive, rangeState.endExclusive); }; @@ -65,9 +65,9 @@ internal WorkStealingJobSystem(JobSchedulerOptions options) int started = 0; try { - for (var i = 0; i < m_workers.Length; i++) + for (int i = 0; i < m_workers.Length; i++) { - var workerId = i; + int workerId = i; m_workers[i] = new WorkerRuntime(workerId, () => WorkerLoop(workerId)); } for (; started < m_workers.Length; started++) @@ -152,10 +152,10 @@ public void EndFrame() } handles.Capacity = m_frameJobs.Count; - for (var i = 0; i < m_frameJobs.Count; i++) + for (int i = 0; i < m_frameJobs.Count; i++) { - var index = m_frameJobs[i]; - if (!TryGetActiveRecordNoLock(index, out var record)) + int index = m_frameJobs[i]; + if (!TryGetActiveRecordNoLock(index, out JobRecord record)) { continue; } @@ -165,7 +165,7 @@ public void EndFrame() } List? exceptions = null; - for (var i = 0; i < handles.Count; i++) + for (int i = 0; i < handles.Count; i++) { try { @@ -184,10 +184,10 @@ public void EndFrame() lock (m_jobsGate) { - for (var i = 0; i < m_frameJobs.Count; i++) + for (int i = 0; i < m_frameJobs.Count; i++) { - var index = m_frameJobs[i]; - if (!TryGetActiveRecordNoLock(index, out var record)) + int index = m_frameJobs[i]; + if (!TryGetActiveRecordNoLock(index, out JobRecord record)) { continue; } @@ -223,7 +223,7 @@ public void EndFrame() public JobHandle Schedule(Action job) { ArgumentNullException.ThrowIfNull(job); - return Schedule(s_actionInvoker, job, ReadOnlySpan.Empty); + return Schedule(s_actionInvoker, job, []); } /// @@ -263,19 +263,19 @@ ReadOnlySpan dependencies } _ = ResolveHandleNoLock(dependency); } - var index = AllocateJobIndexNoLock(job, state); - var record = m_jobs[index]; + int index = AllocateJobIndexNoLock(job, state); + JobRecord record = m_jobs[index]; - var dependencyCount = 0; - for (var i = 0; i < dependencies.Length; i++) + int dependencyCount = 0; + for (int i = 0; i < dependencies.Length; i++) { - var dependency = dependencies[i]; + JobHandle dependency = dependencies[i]; if (!dependency.isValid) { throw new ArgumentException("Dependency handle is invalid.", nameof(dependencies)); } - var dependencyRecord = ResolveHandleNoLock(dependency); + JobRecord dependencyRecord = ResolveHandleNoLock(dependency); if (dependencyRecord.executionState == JobExecutionState.Completed) { continue; @@ -313,10 +313,7 @@ ReadOnlySpan dependencies /// /// The validated job handle that represents the completed operation. /// - public JobHandle CombineDependencies(ReadOnlySpan dependencies) - { - return Schedule(s_noop, null, dependencies); - } + public JobHandle CombineDependencies(ReadOnlySpan dependencies) => Schedule(s_noop, null, dependencies); /// /// Schedules the indexed range in batches and returns its completion handle. @@ -351,22 +348,22 @@ Action body if (length == 0) { - return Schedule(s_noop, null, ReadOnlySpan.Empty); + return Schedule(s_noop, null, []); } ThrowIfDisposed(); lock (m_jobsGate) { EnsureFrameActiveNoLock(); - var chunkCount = 1 + (length - 1) / batchSize; + int chunkCount = 1 + (length - 1) / batchSize; RequireCapacityNoLock(checked(chunkCount + 1)); var chunkHandles = new JobHandle[chunkCount]; - var chunkIndex = 0; - for (var start = 0; start < length;) + int chunkIndex = 0; + for (int start = 0; start < length;) { - var end = start + Math.Min(batchSize, length - start); + int end = start + Math.Min(batchSize, length - start); var rangeState = new ParallelForRangeState(body, start, end); - chunkHandles[chunkIndex++] = Schedule(s_parallelRangeInvoker, rangeState, ReadOnlySpan.Empty); + chunkHandles[chunkIndex++] = Schedule(s_parallelRangeInvoker, rangeState, []); start = end; } @@ -392,7 +389,7 @@ public void Complete(JobHandle handle) var spinner = new SpinWait(); while (true) { - if (TryGetCompletion(handle, out var exception)) + if (TryGetCompletion(handle, out Exception? exception)) { if (exception is not null) { @@ -428,7 +425,7 @@ public void Complete(JobHandle handle) /// public void CompleteAll(ReadOnlySpan handles) { - for (var i = 0; i < handles.Length; i++) + for (int i = 0; i < handles.Length; i++) { Complete(handles[i]); } @@ -502,12 +499,12 @@ public void Dispose() m_disposed = true; Interlocked.Exchange(ref m_running, 0); - for (var i = 0; i < m_workers.Length; i++) + for (int i = 0; i < m_workers.Length; i++) { m_wakeSignal.Release(); } - for (var i = 0; i < m_workers.Length; i++) + for (int i = 0; i < m_workers.Length; i++) { m_workers[i].thread.Join(); } @@ -547,7 +544,7 @@ private void WorkerLoop(int workerId) private bool TryExecuteOneAvailableJob() { - if (!TryDequeueWorkItem(out var jobIndex)) + if (!TryDequeueWorkItem(out int jobIndex)) { return false; } @@ -556,7 +553,7 @@ private bool TryExecuteOneAvailableJob() object? state = null; lock (m_jobsGate) { - if (!TryGetActiveRecordNoLock(jobIndex, out var record)) + if (!TryGetActiveRecordNoLock(jobIndex, out JobRecord record)) { return false; } @@ -584,7 +581,7 @@ private bool TryExecuteOneAvailableJob() List? readyIndices = null; lock (m_jobsGate) { - if (!TryGetActiveRecordNoLock(jobIndex, out var record)) + if (!TryGetActiveRecordNoLock(jobIndex, out JobRecord record)) { return true; } @@ -600,10 +597,10 @@ private bool TryExecuteOneAvailableJob() if (record.dependents is { Count: > 0 }) { readyIndices = []; - for (var i = 0; i < record.dependents.Count; i++) + for (int i = 0; i < record.dependents.Count; i++) { - var dependentIndex = record.dependents[i]; - if (!TryGetActiveRecordNoLock(dependentIndex, out var dependent)) + int dependentIndex = record.dependents[i]; + if (!TryGetActiveRecordNoLock(dependentIndex, out JobRecord dependent)) { continue; } @@ -631,7 +628,7 @@ private bool TryExecuteOneAvailableJob() private bool TryDequeueWorkItem(out int jobIndex) { - var workerId = m_currentWorkerId.Value; + int workerId = m_currentWorkerId.Value; if (workerId >= 0) { if (m_workers[workerId].localQueue.TryPopBottom(out jobIndex)) @@ -647,10 +644,10 @@ private bool TryDequeueWorkItem(out int jobIndex) if (workerId >= 0) { - var startVictim = (workerId + 1) % m_workers.Length; - for (var i = 0; i < m_workers.Length - 1; i++) + int startVictim = (workerId + 1) % m_workers.Length; + for (int i = 0; i < m_workers.Length - 1; i++) { - var victim = (startVictim + i) % m_workers.Length; + int victim = (startVictim + i) % m_workers.Length; if (m_workers[victim].localQueue.TryStealTop(out jobIndex)) { return true; @@ -659,7 +656,7 @@ private bool TryDequeueWorkItem(out int jobIndex) } else { - for (var i = 0; i < m_workers.Length; i++) + for (int i = 0; i < m_workers.Length; i++) { if (m_workers[i].localQueue.TryStealTop(out jobIndex)) { @@ -674,10 +671,10 @@ private bool TryDequeueWorkItem(out int jobIndex) private void QueueReadyJobs(List readyIndices) { - var workerId = m_currentWorkerId.Value; - for (var i = 0; i < readyIndices.Count; i++) + int workerId = m_currentWorkerId.Value; + for (int i = 0; i < readyIndices.Count; i++) { - var index = readyIndices[i]; + int index = readyIndices[i]; if (workerId >= 0) { m_workers[workerId].localQueue.PushBottom(index); @@ -716,7 +713,7 @@ private int AllocateJobIndexNoLock( m_jobs.Add(new JobRecord()); } - var record = m_jobs[index]; + JobRecord record = m_jobs[index]; record.ResetForAllocation(callback, state); m_frameJobs.Add(index); m_peakFrameJobs = Math.Max(m_peakFrameJobs, m_frameJobs.Count); @@ -729,7 +726,7 @@ out Exception? exception ) { lock (m_jobsGate) { - var record = ResolveHandleNoLock(handle); + JobRecord record = ResolveHandleNoLock(handle); if (record.executionState != JobExecutionState.Completed) { exception = null; @@ -748,7 +745,7 @@ private JobRecord ResolveHandleNoLock(JobHandle handle) throw new InvalidOperationException("Job handle index is out of range."); } - var record = m_jobs[handle.index]; + JobRecord record = m_jobs[handle.index]; if (!record.inUse || record.version != handle.version) { throw new InvalidOperationException("Job handle is stale or no longer valid."); diff --git a/src/foundation/core/Inno.Core.Layers/Layer.cs b/src/foundation/core/Inno.Core.Layers/Layer.cs index 20bee78e7..02034114b 100644 --- a/src/foundation/core/Inno.Core.Layers/Layer.cs +++ b/src/foundation/core/Inno.Core.Layers/Layer.cs @@ -97,13 +97,13 @@ public virtual void OnRender(float deltaTime) {} /// /// Completes frame-scoped rendering state after render submission. /// + /// + /// The elapsed frame time in seconds. + /// /// /// A invokes this callback in reverse order for every layer whose /// callback completed successfully, including when later work fails. /// - /// - /// The elapsed frame time in seconds. - /// public virtual void OnAfterRender(float deltaTime) {} /// diff --git a/src/foundation/core/Inno.Core.Layers/LayerStack.cs b/src/foundation/core/Inno.Core.Layers/LayerStack.cs index 74a7d86b6..763568afd 100644 --- a/src/foundation/core/Inno.Core.Layers/LayerStack.cs +++ b/src/foundation/core/Inno.Core.Layers/LayerStack.cs @@ -66,10 +66,7 @@ public LayerStack(Func eventHubFactory) /// /// Thrown when this stack has been disposed. /// - public void PushLayer(Layer layer) - { - Insert(layer, m_baseLayerCount, isBaseLayer: true); - } + public void PushLayer(Layer layer) => Insert(layer, m_baseLayerCount, isBaseLayer: true); /// /// Attaches an overlay above all base layers and existing overlays. diff --git a/src/foundation/core/Inno.Core.Logging/ConsoleLogSink.cs b/src/foundation/core/Inno.Core.Logging/ConsoleLogSink.cs index 9e4ed03e1..8d30ee145 100644 --- a/src/foundation/core/Inno.Core.Logging/ConsoleLogSink.cs +++ b/src/foundation/core/Inno.Core.Logging/ConsoleLogSink.cs @@ -15,7 +15,10 @@ public class ConsoleLogSink : ILogSink /// /// Whether the host supports console colors; redirected output always uses plain text. /// - public ConsoleLogSink(bool useColors = false) => m_useColors = useColors; + public ConsoleLogSink(bool useColors = false) + { + m_useColors = useColors; + } /// /// Writes the specified entry to standard output. diff --git a/src/foundation/core/Inno.Core.Logging/FileLogSink.cs b/src/foundation/core/Inno.Core.Logging/FileLogSink.cs index 2bbd072d2..1db267ebf 100644 --- a/src/foundation/core/Inno.Core.Logging/FileLogSink.cs +++ b/src/foundation/core/Inno.Core.Logging/FileLogSink.cs @@ -82,10 +82,6 @@ public FileLogSink( /// /// The immutable entry to persist. /// - /// - /// The router owns scheduling and backpressure. Write failures propagate to its sink quarantine. - /// Retention cannot remove files locked by another active writer and retries them on later rotation. - /// /// /// The sink has been disposed. /// @@ -98,6 +94,10 @@ public FileLogSink( /// /// A previous failed rotation left no writable file. /// + /// + /// The router owns scheduling and backpressure. Write failures propagate to its sink quarantine. + /// Retention cannot remove files locked by another active writer and retries them on later rotation. + /// public void Receive(LogEntry entry) { lock (m_lifecycleSync) diff --git a/src/foundation/core/Inno.Core.Logging/LogRouter.cs b/src/foundation/core/Inno.Core.Logging/LogRouter.cs index 800d98896..ffad0a411 100644 --- a/src/foundation/core/Inno.Core.Logging/LogRouter.cs +++ b/src/foundation/core/Inno.Core.Logging/LogRouter.cs @@ -57,7 +57,7 @@ public sealed class LogRouter : IDisposable /// A capacity or budget is not positive, or the delivery policy is not a defined mode. /// public LogRouter( - int queueCapacity = 65536, + int queueCapacity = 65_536, int drainBudget = 4096, LogDeliveryMode deliveryMode = LogDeliveryMode.Background ) { @@ -127,17 +127,17 @@ public void RegisterSink(ILogSink sink) /// /// Removes a sink from subsequent delivery snapshots without disposing it. /// - /// - /// An in-flight batch may still borrow the previous snapshot. This operation does not wait - /// for its callbacks; the host must coordinate quiescence before releasing sink resources. - /// Router disposal releases only sinks that remain registered. - /// /// /// The sink to remove when registered. /// /// /// Thrown when is null. /// + /// + /// An in-flight batch may still borrow the previous snapshot. This operation does not wait + /// for its callbacks; the host must coordinate quiescence before releasing sink resources. + /// Router disposal releases only sinks that remain registered. + /// public void UnregisterSink(ILogSink sink) { ArgumentNullException.ThrowIfNull(sink); @@ -218,13 +218,13 @@ public void Dispatch(LogEntry entry) /// /// True when accepted or filtered by policy; false when bounded queue capacity is exhausted. /// + /// + /// The router has stopped accepting work. + /// /// /// Inline callers serialize delivery. Entries written by a sink callback are queued until /// every sink has received the current entry, without recursively invoking callbacks. /// - /// - /// The router has stopped accepting work. - /// public bool TryDispatch(LogEntry entry) { lock (m_queueSync) diff --git a/src/foundation/core/Inno.Core.Logging/Logger.cs b/src/foundation/core/Inno.Core.Logging/Logger.cs index 14d460fc2..fd42e895b 100644 --- a/src/foundation/core/Inno.Core.Logging/Logger.cs +++ b/src/foundation/core/Inno.Core.Logging/Logger.cs @@ -42,18 +42,18 @@ string category /// /// Optional composite-format arguments. /// - /// - /// Thrown when is empty. - /// - /// - /// Thrown after the owning router has been disposed. - /// /// /// Source file supplied by the caller information attribute. /// /// /// Source line supplied by the caller information attribute. /// + /// + /// Thrown when is empty. + /// + /// + /// Thrown after the owning router has been disposed. + /// public void Write( LogLevel level, string message, diff --git a/src/foundation/core/Inno.Core.Mathematics/Color.cs b/src/foundation/core/Inno.Core.Mathematics/Color.cs index f5815911a..d31568afe 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Color.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Color.cs @@ -53,10 +53,10 @@ public Color( float b, float a = 1f ) { - this.r = Math.Clamp(r, 0.0f, 1.0f); - this.g = Math.Clamp(g, 0.0f, 1.0f); - this.b = Math.Clamp(b, 0.0f, 1.0f); - this.a = Math.Clamp(a, 0.0f, 1.0f); + this.r = Math.Clamp(r, 0f, 1f); + this.g = Math.Clamp(g, 0f, 1f); + this.b = Math.Clamp(b, 0f, 1f); + this.a = Math.Clamp(a, 0f, 1f); } /// @@ -82,9 +82,7 @@ public static Color FromBytes( byte g, byte b, byte a = 255 - ) { - return new Color(r / 255f, g / 255f, b / 255f, a / 255f); - } + ) => new Color(r / 255f, g / 255f, b / 255f, a / 255f); /// /// Converts normalized color channels to bytes by multiplying by 255 and truncating. @@ -93,14 +91,12 @@ public static Color FromBytes( /// Red, green, blue and alpha bytes. Inputs must already be finite and in [0, 1]; conversion does not clamp field writes. /// public (byte R, byte G, byte B, byte A) ToBytes() - { - return ( - (byte)(r * 255), - (byte)(g * 255), - (byte)(b * 255), - (byte)(a * 255) - ); - } + => ( + (byte)(r * 255), + (byte)(g * 255), + (byte)(b * 255), + (byte)(a * 255) + ); /// /// Packs normalized channels into the existing unsigned 0xAABBGGRR representation. @@ -231,9 +227,7 @@ public uint ToUInt32ARGB() public static Color operator *( Color c, float factor - ) { - return new Color(c.r * factor, c.g * factor, c.b * factor, c.a * factor); - } + ) => new Color(c.r * factor, c.g * factor, c.b * factor, c.a * factor); /// /// Determines whether the supplied values are equal under the type's equality tolerance. @@ -251,12 +245,10 @@ float factor public static bool operator ==( Color a, Color b - ) { - return MathHelper.AlmostEquals(a.r, b.r) - && MathHelper.AlmostEquals(a.g, b.g) - && MathHelper.AlmostEquals(a.b, b.b) - && MathHelper.AlmostEquals(a.a, b.a); - } + ) => MathHelper.AlmostEquals(a.r, b.r) + && MathHelper.AlmostEquals(a.g, b.g) + && MathHelper.AlmostEquals(a.b, b.b) + && MathHelper.AlmostEquals(a.a, b.a); /// /// Determines whether the supplied values differ under the type's equality tolerance. diff --git a/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs b/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs index 1c5f0a7b3..4ab731779 100644 --- a/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs +++ b/src/foundation/core/Inno.Core.Mathematics/MathHelper.cs @@ -15,92 +15,88 @@ public static class MathHelper /// public const float C_TOLERANCE = 1e-6f; - /// - /// Determines whether two floating-point numbers are approximately equal, - /// using a relative tolerance based on the magnitude of the numbers. - /// This is useful for comparing floats where rounding errors may occur. - /// - /// - /// The first float value to compare. - /// - /// - /// The second float value to compare. - /// - /// - /// The relative tolerance allowed between and . - /// Default is 1e-6. The comparison checks if the difference is within - /// relTolerance * max(|a|, |b|). - /// - /// - /// true if the absolute difference between and - /// is less than or equal to the relative tolerance multiplied by the larger magnitude of the two values; - /// otherwise, false. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool AlmostEquals( - float a, - float b, - float relTolerance = C_TOLERANCE - ) { - return MathF.Abs(a - b) <= relTolerance * MathF.Max(MathF.Abs(a), MathF.Abs(b)); - } + /// + /// Determines whether two floating-point numbers are approximately equal, + /// using a relative tolerance based on the magnitude of the numbers. + /// This is useful for comparing floats where rounding errors may occur. + /// + /// + /// The first float value to compare. + /// + /// + /// The second float value to compare. + /// + /// + /// The relative tolerance allowed between and . + /// Default is 1e-6. The comparison checks if the difference is within + /// relTolerance * max(|a|, |b|). + /// + /// + /// true if the absolute difference between and + /// is less than or equal to the relative tolerance multiplied by the larger magnitude of the two values; + /// otherwise, false. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AlmostEquals( + float a, + float b, + float relTolerance = C_TOLERANCE + ) => MathF.Abs(a - b) <= relTolerance * MathF.Max(MathF.Abs(a), MathF.Abs(b)); - /// - /// Returns the Cartesian coordinate for one axis of a point that is defined by a given triangle and two normalized barycentric (areal) coordinates. - /// - /// - /// The coordinate on one axis of vertex 1 of the defining triangle. - /// - /// - /// The coordinate on the same axis of vertex 2 of the defining triangle. - /// - /// - /// The coordinate on the same axis of vertex 3 of the defining triangle. - /// - /// - /// The normalized barycentric (areal) coordinate b2, equal to the weighting factor for vertex 2, the coordinate of which is specified in value2. - /// - /// - /// The normalized barycentric (areal) coordinate b3, equal to the weighting factor for vertex 3, the coordinate of which is specified in value3. - /// - /// - /// Cartesian coordinate of the specified point with respect to the axis being used. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float Barycentric( - float value1, - float value2, - float value3, - float amount1, - float amount2 - ) { - return (float) ((double) value1 - + ((double) value2 - (double) value1) * (double) amount1 - + ((double) value3 - (double) value1) * (double) amount2); - } + /// + /// Returns the Cartesian coordinate for one axis of a point that is defined by a given triangle and two normalized barycentric (areal) coordinates. + /// + /// + /// The coordinate on one axis of vertex 1 of the defining triangle. + /// + /// + /// The coordinate on the same axis of vertex 2 of the defining triangle. + /// + /// + /// The coordinate on the same axis of vertex 3 of the defining triangle. + /// + /// + /// The normalized barycentric (areal) coordinate b2, equal to the weighting factor for vertex 2, the coordinate of which is specified in value2. + /// + /// + /// The normalized barycentric (areal) coordinate b3, equal to the weighting factor for vertex 3, the coordinate of which is specified in value3. + /// + /// + /// Cartesian coordinate of the specified point with respect to the axis being used. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Barycentric( + float value1, + float value2, + float value3, + float amount1, + float amount2 + ) => (float)((double)value1 + + ((double)value2 - (double)value1) * (double)amount1 + + ((double)value3 - (double)value1) * (double)amount2); - /// - /// Performs a Catmull-Rom interpolation using the specified positions. - /// - /// - /// The first position in the interpolation. - /// - /// - /// The second position in the interpolation. - /// - /// - /// The third position in the interpolation. - /// - /// - /// The fourth position in the interpolation. - /// - /// - /// Weighting factor. - /// - /// - /// A position that is the result of the Catmull-Rom interpolation. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] + /// + /// Performs a Catmull-Rom interpolation using the specified positions. + /// + /// + /// The first position in the interpolation. + /// + /// + /// The second position in the interpolation. + /// + /// + /// The third position in the interpolation. + /// + /// + /// The fourth position in the interpolation. + /// + /// + /// Weighting factor. + /// + /// + /// A position that is the result of the Catmull-Rom interpolation. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float CatmullRom( float value1, float value2, @@ -123,12 +119,12 @@ float amount /// /// Source value. /// - /// - /// Distance between the two values. - /// /// /// The value2 consumed by distance; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// Distance between the two values. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance( float value1, @@ -181,119 +177,115 @@ float amount : value1; } - /// - /// Linearly interpolates between two values. - /// - /// - /// Source value. - /// - /// - /// Destination value. - /// - /// - /// Value between 0 and 1 indicating the weight of value2. - /// - /// - /// Interpolated value. - /// - /// This method performs the linear interpolation based on the following formula: - /// value1 + (value2 - value1) * amount - /// Passing amount a value of 0 will cause value1 to be returned, a value of 1 will cause value2 to be returned. - /// See for a less efficient version with more precision around edge cases. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float Lerp( - float value1, - float value2, - float amount - ) { - return value1 + (value2 - value1) * amount; - } + /// + /// Linearly interpolates between two values. + /// + /// + /// Source value. + /// + /// + /// Destination value. + /// + /// + /// Value between 0 and 1 indicating the weight of value2. + /// + /// + /// Interpolated value. + /// + /// + /// This method performs the linear interpolation based on the following formula: + /// value1 + (value2 - value1) * amount + /// Passing amount a value of 0 will cause value1 to be returned, a value of 1 will cause value2 to be returned. + /// See for a less efficient version with more precision around edge cases. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Lerp( + float value1, + float value2, + float amount + ) => value1 + (value2 - value1) * amount; - /// - /// Linearly interpolates between two values without clamping the amount. - /// - /// - /// The value1 consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The value2 consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The amount consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float LerpUnclamped( - float value1, - float value2, - float amount - ) { - return value1 + (value2 - value1) * amount; - } + /// + /// Linearly interpolates between two values without clamping the amount. + /// + /// + /// The value1 consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The value2 consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The amount consumed by lerp unclamped; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float LerpUnclamped( + float value1, + float value2, + float amount + ) => value1 + (value2 - value1) * amount; - /// - /// Linearly interpolates between two values. - /// This method is a less efficient, more precise version of . - /// See remarks for more info. - /// - /// - /// Source value. - /// - /// - /// Destination value. - /// - /// - /// Value between 0 and 1 indicating the weight of value2. - /// - /// - /// Interpolated value. - /// - /// This method performs the linear interpolation based on the following formula: - /// ((1 - amount) * value1) + (value2 * amount). - /// Passing amount a value of 0 will cause value1 to be returned, a value of 1 will cause value2 to be returned. - /// This method does not have the floating point precision issue that has. - /// i.e. If there is a big gap between value1 and value2 in magnitude (e.g. value1=10000000000000000, value2=1), - /// right at the edge of the interpolation range (amount=1), will return 0 (whereas it should return 1). - /// This also holds for value1=10^17, value2=10; value1=10^18,value2=10^2... so on. - /// For an in depth explanation of the issue, see below references: - /// Relevant Wikipedia Article: https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support - /// Relevant StackOverflow Answer: http://stackoverflow.com/questions/4353525/floating-point-linear-interpolation#answer-23716956 - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float LerpPrecise( - float value1, - float value2, - float amount - ) { - return (float) ((1.0 - (double) amount) * (double) value1 + (double) value2 * (double) amount); - } + /// + /// Linearly interpolates between two values. + /// This method is a less efficient, more precise version of . + /// See remarks for more info. + /// + /// + /// Source value. + /// + /// + /// Destination value. + /// + /// + /// Value between 0 and 1 indicating the weight of value2. + /// + /// + /// Interpolated value. + /// + /// + /// This method performs the linear interpolation based on the following formula: + /// ((1 - amount) * value1) + (value2 * amount). + /// Passing amount a value of 0 will cause value1 to be returned, a value of 1 will cause value2 to be returned. + /// This method does not have the floating point precision issue that has. + /// i.e. If there is a big gap between value1 and value2 in magnitude (e.g. value1=10000000000000000, value2=1), + /// right at the edge of the interpolation range (amount=1), will return 0 (whereas it should return 1). + /// This also holds for value1=10^17, value2=10; value1=10^18,value2=10^2... so on. + /// For an in depth explanation of the issue, see below references: + /// Relevant Wikipedia Article: https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support + /// Relevant StackOverflow Answer: http://stackoverflow.com/questions/4353525/floating-point-linear-interpolation#answer-23716956 + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float LerpPrecise( + float value1, + float value2, + float amount + ) => (float)((1.0 - (double)amount) * (double)value1 + (double)value2 * (double)amount); - /// - /// Interpolates between two values using a cubic equation. - /// - /// - /// Source value. - /// - /// - /// Source value. - /// - /// - /// Weighting value. - /// - /// - /// Interpolated value. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] + /// + /// Interpolates between two values using a cubic equation. + /// + /// + /// Source value. + /// + /// + /// Source value. + /// + /// + /// Weighting value. + /// + /// + /// Interpolated value. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float SmoothStep( float value1, float value2, float amount ) { - float amount1 = Math.Clamp(amount, 0.0f, 1f); - return Hermite(value1, 0.0f, value2, 0.0f, amount1); + float amount1 = Math.Clamp(amount, 0f, 1f); + return Hermite(value1, 0f, value2, 0f, amount1); } /// @@ -316,6 +308,9 @@ float amount /// /// Converts degrees to radians. /// + /// + /// The degrees consumed by to radians; ownership remains with the caller unless explicitly stated otherwise. + /// /// /// The angle in radians. /// @@ -324,9 +319,6 @@ float amount /// though it returns single float /// Factor = pi / 180 /// - /// - /// The degrees consumed by to radians; ownership remains with the caller unless explicitly stated otherwise. - /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float ToRadians(float degrees) => degrees * ((float) MathF.PI / 180f); @@ -339,12 +331,12 @@ float amount /// /// The min consumed by clamp; ownership remains with the caller unless explicitly stated otherwise. /// - /// - /// The scalar result calculated from the supplied inputs. - /// /// /// The max consumed by clamp; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// The scalar result calculated from the supplied inputs. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Clamp( float value, @@ -355,24 +347,24 @@ float max /// /// Clamps a value to the inclusive range [0, 1]. /// - /// - /// The scalar result calculated from the supplied inputs. - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// The scalar result calculated from the supplied inputs. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Saturate(float value) => Math.Clamp(value, 0f, 1f); /// /// Returns true if the value is finite (not NaN or infinity). /// - /// - /// when the operation succeeds or its condition is satisfied; otherwise, . - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// when the operation succeeds or its condition is satisfied; otherwise, . + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsFinite(float value) => !float.IsNaN(value) && !float.IsInfinity(value); @@ -403,12 +395,12 @@ public static float WrapAngle(float angle) /// /// Determines if value is powered by two. /// - /// - /// true if value is powered by two; otherwise false. - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// if value is powered by two; otherwise . + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsPowerOfTwo(int value) => value > 0 && (value & value - 1) == 0; } diff --git a/src/foundation/core/Inno.Core.Mathematics/Matrix.cs b/src/foundation/core/Inno.Core.Mathematics/Matrix.cs index 9ed83b2ef..8aeb71e47 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Matrix.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Matrix.cs @@ -1,4 +1,5 @@ using System; +using System.Numerics; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; @@ -31,82 +32,98 @@ public struct Matrix : IEquatable /// /// Row 1, Column 1. /// - [DataMember] public float m11; + [DataMember] + public float m11; /// /// Row 1, Column 2. /// - [DataMember] public float m12; + [DataMember] + public float m12; /// /// Row 1, Column 3. /// - [DataMember] public float m13; + [DataMember] + public float m13; /// /// Row 1, Column 4. /// - [DataMember] public float m14; + [DataMember] + public float m14; /// /// Row 2, Column 1. /// - [DataMember] public float m21; + [DataMember] + public float m21; /// /// Row 2, Column 2. /// - [DataMember] public float m22; + [DataMember] + public float m22; /// /// Row 2, Column 3. /// - [DataMember] public float m23; + [DataMember] + public float m23; /// /// Row 2, Column 4. /// - [DataMember] public float m24; + [DataMember] + public float m24; /// /// Row 3, Column 1. /// - [DataMember] public float m31; + [DataMember] + public float m31; /// /// Row 3, Column 2. /// - [DataMember] public float m32; + [DataMember] + public float m32; /// /// Row 3, Column 3. /// - [DataMember] public float m33; + [DataMember] + public float m33; /// /// Row 3, Column 4. /// - [DataMember] public float m34; + [DataMember] + public float m34; /// /// Row 4, Column 1 (translation X component for affine transforms). /// - [DataMember] public float m41; + [DataMember] + public float m41; /// /// Row 4, Column 2 (translation Y component for affine transforms). /// - [DataMember] public float m42; + [DataMember] + public float m42; /// /// Row 4, Column 3 (translation Z component for affine transforms). /// - [DataMember] public float m43; + [DataMember] + public float m43; /// /// Row 4, Column 4. /// - [DataMember] public float m44; + [DataMember] + public float m44; #endregion @@ -215,30 +232,28 @@ public static Matrix CreateTranslation( float x, float y, float z - ) { - return new Matrix(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); - } + ) => new Matrix(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); /// /// Creates a translation matrix. /// - /// - /// A translation matrix. - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// A translation matrix. + /// public static Matrix CreateTranslation(Vector3 v) => CreateTranslation(v.x, v.y, v.z); /// /// Creates a uniform scale matrix. /// - /// - /// A scale matrix. - /// /// /// The scale consumed by create scale; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// A scale matrix. + /// public static Matrix CreateScale(float scale) => CreateScale(scale, scale, scale); /// @@ -260,19 +275,17 @@ public static Matrix CreateScale( float x, float y, float z - ) { - return new Matrix(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); - } + ) => new Matrix(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); /// /// Creates a non-uniform scale matrix. /// - /// - /// A scale matrix. - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// A scale matrix. + /// public static Matrix CreateScale(Vector3 v) => CreateScale(v.x, v.y, v.z); /// @@ -334,9 +347,15 @@ public static Matrix CreateRotationZ(float radians) /// public static Matrix CreateFromQuaternion(Quaternion q) { - float xx = q.x * q.x, yy = q.y * q.y, zz = q.z * q.z; - float xy = q.x * q.y, xz = q.x * q.z, yz = q.y * q.z; - float wx = q.w * q.x, wy = q.w * q.y, wz = q.w * q.z; + float xx = q.x * q.x; + float yy = q.y * q.y; + float zz = q.z * q.z; + float xy = q.x * q.y; + float xz = q.x * q.z; + float yz = q.y * q.z; + float wx = q.w * q.x; + float wy = q.w * q.y; + float wz = q.w * q.z; return new Matrix( 1 - 2 * (yy + zz), @@ -445,9 +464,7 @@ public static Matrix CreateOrthographic( float height, float near, float far - ) { - return CreateOrthographicOffCenter(-width * 0.5f, width * 0.5f, -height * 0.5f, height * 0.5f, near, far); - } + ) => CreateOrthographicOffCenter(-width * 0.5f, width * 0.5f, -height * 0.5f, height * 0.5f, near, far); /// /// Creates an off-center orthographic projection matrix (depth range 0..1). @@ -516,9 +533,12 @@ public static Matrix CreateLookAt( Vector3 up ) { // LH: forward points from eye to target - Vector3 z = (target - eye).normalized; // forward (+Z) - Vector3 x = Vector3.Cross(up, z).normalized; // right - Vector3 y = Vector3.Cross(z, x); // up + // forward (+Z) + Vector3 z = (target - eye).normalized; + // right + Vector3 x = Vector3.Cross(up, z).normalized; + // up + Vector3 y = Vector3.Cross(z, x); return new Matrix( x.x, @@ -561,9 +581,12 @@ public static Matrix CreateLookAtRH( Vector3 up ) { // RH: forward points from eye to target but is -Z in view space - Vector3 z = (eye - target).normalized; // forward (-Z) - Vector3 x = Vector3.Cross(up, z).normalized; // right - Vector3 y = Vector3.Cross(z, x); // up + // forward (-Z) + Vector3 z = (eye - target).normalized; + // right + Vector3 x = Vector3.Cross(up, z).normalized; + // up + Vector3 y = Vector3.Cross(z, x); return new Matrix( x.x, @@ -607,15 +630,15 @@ Matrix b ) { if (Sse.IsSupported || AdvSimd.IsSupported) { - var col0 = Vector128.Create(b.m11, b.m21, b.m31, b.m41); - var col1 = Vector128.Create(b.m12, b.m22, b.m32, b.m42); - var col2 = Vector128.Create(b.m13, b.m23, b.m33, b.m43); - var col3 = Vector128.Create(b.m14, b.m24, b.m34, b.m44); + Vector128 col0 = Vector128.Create(b.m11, b.m21, b.m31, b.m41); + Vector128 col1 = Vector128.Create(b.m12, b.m22, b.m32, b.m42); + Vector128 col2 = Vector128.Create(b.m13, b.m23, b.m33, b.m43); + Vector128 col3 = Vector128.Create(b.m14, b.m24, b.m34, b.m44); - var row0 = Vector128.Create(a.m11, a.m12, a.m13, a.m14); - var row1 = Vector128.Create(a.m21, a.m22, a.m23, a.m24); - var row2 = Vector128.Create(a.m31, a.m32, a.m33, a.m34); - var row3 = Vector128.Create(a.m41, a.m42, a.m43, a.m44); + Vector128 row0 = Vector128.Create(a.m11, a.m12, a.m13, a.m14); + Vector128 row1 = Vector128.Create(a.m21, a.m22, a.m23, a.m24); + Vector128 row2 = Vector128.Create(a.m31, a.m32, a.m33, a.m34); + Vector128 row3 = Vector128.Create(a.m41, a.m42, a.m43, a.m44); return new Matrix( SimdMath.Dot4(row0, col0), @@ -674,10 +697,22 @@ Matrix b /// public static float Determinant(Matrix m) { - float a00 = m.m11, a01 = m.m12, a02 = m.m13, a03 = m.m14; - float a10 = m.m21, a11 = m.m22, a12 = m.m23, a13 = m.m24; - float a20 = m.m31, a21 = m.m32, a22 = m.m33, a23 = m.m34; - float a30 = m.m41, a31 = m.m42, a32 = m.m43, a33 = m.m44; + float a00 = m.m11; + float a01 = m.m12; + float a02 = m.m13; + float a03 = m.m14; + float a10 = m.m21; + float a11 = m.m22; + float a12 = m.m23; + float a13 = m.m24; + float a20 = m.m31; + float a21 = m.m32; + float a22 = m.m33; + float a23 = m.m34; + float a30 = m.m41; + float a31 = m.m42; + float a32 = m.m43; + float a33 = m.m44; float b00 = a00 * a11 - a01 * a10; float b01 = a00 * a12 - a02 * a10; @@ -722,9 +757,9 @@ out Vector3 translation ) { translation = new Vector3(m.m14, m.m24, m.m34); - Vector3 col0 = new Vector3(m.m11, m.m21, m.m31); - Vector3 col1 = new Vector3(m.m12, m.m22, m.m32); - Vector3 col2 = new Vector3(m.m13, m.m23, m.m33); + var col0 = new Vector3(m.m11, m.m21, m.m31); + var col1 = new Vector3(m.m12, m.m22, m.m32); + var col2 = new Vector3(m.m13, m.m23, m.m33); float sx = col0.Length(); float sy = col1.Length(); @@ -775,10 +810,7 @@ out Vector3 translation /// /// A matrix representing the 2D transform embedded in . /// - public static Matrix Extract2DTransform(Matrix m) - { - return new Matrix(m.m11, m.m12, 0, m.m14, m.m21, m.m22, 0, m.m24, 0, 0, 1, 0, 0, 0, 0, 1); - } + public static Matrix Extract2DTransform(Matrix m) => new Matrix(m.m11, m.m12, 0, m.m14, m.m21, m.m22, 0, m.m24, 0, 0, 1, 0, 0, 0, 0, 1); /// /// Returns the transpose of a matrix. @@ -790,8 +822,7 @@ public static Matrix Extract2DTransform(Matrix m) /// Transposed matrix. /// public static Matrix Transpose(Matrix a) - { - return new Matrix( + => new Matrix( a.m11, a.m21, a.m31, @@ -809,7 +840,6 @@ public static Matrix Transpose(Matrix a) a.m34, a.m44 ); - } /// /// Returns the inverse, or identity when the absolute determinant is below the default tolerance. @@ -822,10 +852,22 @@ public static Matrix Transpose(Matrix a) /// public static Matrix Invert(Matrix m) { - float a00 = m.m11, a01 = m.m12, a02 = m.m13, a03 = m.m14; - float a10 = m.m21, a11 = m.m22, a12 = m.m23, a13 = m.m24; - float a20 = m.m31, a21 = m.m32, a22 = m.m33, a23 = m.m34; - float a30 = m.m41, a31 = m.m42, a32 = m.m43, a33 = m.m44; + float a00 = m.m11; + float a01 = m.m12; + float a02 = m.m13; + float a03 = m.m14; + float a10 = m.m21; + float a11 = m.m22; + float a12 = m.m23; + float a13 = m.m24; + float a20 = m.m31; + float a21 = m.m32; + float a22 = m.m33; + float a23 = m.m34; + float a30 = m.m41; + float a31 = m.m42; + float a32 = m.m43; + float a33 = m.m44; float b00 = a00 * a11 - a01 * a10; float b01 = a00 * a12 - a02 * a10; @@ -889,7 +931,7 @@ public void CopyToColumnMajor( float[] destination, int startIndex = 0 ) { - if (destination == null) + if (destination is null) { throw new ArgumentNullException(nameof(destination)); } @@ -961,30 +1003,27 @@ Matrix b /// Second matrix. /// /// - /// true if all elements are approximately equal. + /// if all elements are approximately equal. /// public static bool operator ==( Matrix matrix1, Matrix matrix2 - ) { - return - MathHelper.AlmostEquals(matrix1.m11, matrix2.m11) - && MathHelper.AlmostEquals(matrix1.m12, matrix2.m12) - && MathHelper.AlmostEquals(matrix1.m13, matrix2.m13) - && MathHelper.AlmostEquals(matrix1.m14, matrix2.m14) - && MathHelper.AlmostEquals(matrix1.m21, matrix2.m21) - && MathHelper.AlmostEquals(matrix1.m22, matrix2.m22) - && MathHelper.AlmostEquals(matrix1.m23, matrix2.m23) - && MathHelper.AlmostEquals(matrix1.m24, matrix2.m24) - && MathHelper.AlmostEquals(matrix1.m31, matrix2.m31) - && MathHelper.AlmostEquals(matrix1.m32, matrix2.m32) - && MathHelper.AlmostEquals(matrix1.m33, matrix2.m33) - && MathHelper.AlmostEquals(matrix1.m34, matrix2.m34) - && MathHelper.AlmostEquals(matrix1.m41, matrix2.m41) - && MathHelper.AlmostEquals(matrix1.m42, matrix2.m42) - && MathHelper.AlmostEquals(matrix1.m43, matrix2.m43) - && MathHelper.AlmostEquals(matrix1.m44, matrix2.m44); - } + ) => MathHelper.AlmostEquals(matrix1.m11, matrix2.m11) + && MathHelper.AlmostEquals(matrix1.m12, matrix2.m12) + && MathHelper.AlmostEquals(matrix1.m13, matrix2.m13) + && MathHelper.AlmostEquals(matrix1.m14, matrix2.m14) + && MathHelper.AlmostEquals(matrix1.m21, matrix2.m21) + && MathHelper.AlmostEquals(matrix1.m22, matrix2.m22) + && MathHelper.AlmostEquals(matrix1.m23, matrix2.m23) + && MathHelper.AlmostEquals(matrix1.m24, matrix2.m24) + && MathHelper.AlmostEquals(matrix1.m31, matrix2.m31) + && MathHelper.AlmostEquals(matrix1.m32, matrix2.m32) + && MathHelper.AlmostEquals(matrix1.m33, matrix2.m33) + && MathHelper.AlmostEquals(matrix1.m34, matrix2.m34) + && MathHelper.AlmostEquals(matrix1.m41, matrix2.m41) + && MathHelper.AlmostEquals(matrix1.m42, matrix2.m42) + && MathHelper.AlmostEquals(matrix1.m43, matrix2.m43) + && MathHelper.AlmostEquals(matrix1.m44, matrix2.m44); /// /// Tests matrices for inequality. @@ -996,7 +1035,7 @@ Matrix matrix2 /// Second matrix. /// /// - /// true if matrices are not equal. + /// if matrices are not equal. /// public static bool operator !=( Matrix a, @@ -1013,9 +1052,8 @@ Matrix b /// /// The validated system.numerics.matrix4x4 that represents the completed operation. /// - public static implicit operator System.Numerics.Matrix4x4(Matrix m) - { - return new System.Numerics.Matrix4x4( + public static implicit operator Matrix4x4(Matrix m) + => new Matrix4x4( m.m11, m.m12, m.m13, @@ -1033,7 +1071,6 @@ public static implicit operator System.Numerics.Matrix4x4(Matrix m) m.m43, m.m44 ); - } /// /// Converts from preserving element order. @@ -1045,28 +1082,26 @@ public static implicit operator System.Numerics.Matrix4x4(Matrix m) /// /// The validated matrix that represents the completed operation. /// - public static implicit operator Matrix(System.Numerics.Matrix4x4 m) + public static implicit operator Matrix(Matrix4x4 m) + => new Matrix { - return new Matrix - { - m11 = m.M11, - m12 = m.M12, - m13 = m.M13, - m14 = m.M14, - m21 = m.M21, - m22 = m.M22, - m23 = m.M23, - m24 = m.M24, - m31 = m.M31, - m32 = m.M32, - m33 = m.M33, - m34 = m.M34, - m41 = m.M41, - m42 = m.M42, - m43 = m.M43, - m44 = m.M44 - }; - } + m11 = m.M11, + m12 = m.M12, + m13 = m.M13, + m14 = m.M14, + m21 = m.M21, + m22 = m.M22, + m23 = m.M23, + m24 = m.M24, + m31 = m.M31, + m32 = m.M32, + m33 = m.M33, + m34 = m.M34, + m41 = m.M41, + m42 = m.M42, + m43 = m.M43, + m44 = m.M44 + }; #endregion @@ -1079,19 +1114,19 @@ public static implicit operator Matrix(System.Numerics.Matrix4x4 m) /// Other matrix. /// /// - /// true if equal. + /// if equal. /// public bool Equals(Matrix other) => this == other; /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is Matrix other && Equals(other); /// @@ -1101,12 +1136,10 @@ public static implicit operator Matrix(System.Numerics.Matrix4x4 m) /// A hash code consistent with the implemented equality contract. /// public override int GetHashCode() - { - return this.m11.GetHashCode() + this.m12.GetHashCode() + this.m13.GetHashCode() + this.m14.GetHashCode() - + this.m21.GetHashCode() + this.m22.GetHashCode() + this.m23.GetHashCode() + this.m24.GetHashCode() - + this.m31.GetHashCode() + this.m32.GetHashCode() + this.m33.GetHashCode() + this.m34.GetHashCode() - + this.m41.GetHashCode() + this.m42.GetHashCode() + this.m43.GetHashCode() + this.m44.GetHashCode(); - } + => m11.GetHashCode() + m12.GetHashCode() + m13.GetHashCode() + m14.GetHashCode() + + m21.GetHashCode() + m22.GetHashCode() + m23.GetHashCode() + m24.GetHashCode() + + m31.GetHashCode() + m32.GetHashCode() + m33.GetHashCode() + m34.GetHashCode() + + m41.GetHashCode() + m42.GetHashCode() + m43.GetHashCode() + m44.GetHashCode(); /// /// Returns a multi-line string representation of the matrix in row-major layout. @@ -1115,12 +1148,10 @@ public override int GetHashCode() /// The human-readable representation of this value. /// public override string ToString() - { - return $"[{m11}, {m12}, {m13}, {m14}]\n" - + $"[{m21}, {m22}, {m23}, {m24}]\n" - + $"[{m31}, {m32}, {m33}, {m34}]\n" - + $"[{m41}, {m42}, {m43}, {m44}]"; - } + => $"[{m11}, {m12}, {m13}, {m14}]\n" + + $"[{m21}, {m22}, {m23}, {m24}]\n" + + $"[{m31}, {m32}, {m33}, {m34}]\n" + + $"[{m41}, {m42}, {m43}, {m44}]"; #endregion } diff --git a/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs b/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs index a9b20a8b4..6a668b024 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Quaternion.cs @@ -2,6 +2,8 @@ using System.Runtime.CompilerServices; using System.Runtime.Serialization; +using NumericsQuaternion = System.Numerics.Quaternion; + namespace Inno.Core.Mathematics; /// @@ -13,22 +15,26 @@ public struct Quaternion : IEquatable /// /// The horizontal or first component. /// - [DataMember] public float x; + [DataMember] + public float x; /// /// The vertical or second component. /// - [DataMember] public float y; + [DataMember] + public float y; /// /// The depth or third component. /// - [DataMember] public float z; + [DataMember] + public float z; /// /// The homogeneous or fourth component. /// - [DataMember] public float w; + [DataMember] + public float w; /// /// Creates a validated quaternion instance. @@ -134,7 +140,7 @@ public static Quaternion Inverse(Quaternion q) { return identity; } - var conj = Conjugate(q); + Quaternion conj = Conjugate(q); return new Quaternion(conj.x / lenSq, conj.y / lenSq, conj.z / lenSq, conj.w / lenSq); } @@ -169,7 +175,7 @@ float t if (dot > 0.9995f) { // Linear interpolation fallback - Quaternion result = new Quaternion( + var result = new Quaternion( a.x + t * (b.x - a.x), a.y + t * (b.y - a.y), a.z + t * (b.z - a.z), @@ -438,7 +444,7 @@ public static Quaternion FromEulerAnglesXYZ(Vector3 euler) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion FromEulerAnglesXYZDegrees(Vector3 eulerDegrees) { - var euler = eulerDegrees * (MathF.PI / 180f); + Vector3 euler = eulerDegrees * (MathF.PI / 180f); float cx = MathF.Cos(euler.x * 0.5f); float sx = MathF.Sin(euler.x * 0.5f); @@ -494,7 +500,7 @@ public static Quaternion FromEulerAnglesZYX(Vector3 euler) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion FromEulerAnglesZYXDegrees(Vector3 eulerDegrees) { - var euler = eulerDegrees * (MathF.PI / 180f); + Vector3 euler = eulerDegrees * (MathF.PI / 180f); float cz = MathF.Cos(euler.z * 0.5f); float sz = MathF.Sin(euler.z * 0.5f); @@ -526,14 +532,12 @@ public static Quaternion FromEulerAnglesZYXDegrees(Vector3 eulerDegrees) public static Quaternion operator *( Quaternion a, Quaternion b - ) { - return new Quaternion( - a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, - a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, - a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, - a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z - ); - } + ) => new Quaternion( + a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, + a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, + a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, + a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z + ); /// /// Determines whether the supplied values are equal under the type's equality tolerance. @@ -581,7 +585,7 @@ Quaternion b /// /// The validated system.numerics.quaternion that represents the completed operation. /// - public static implicit operator System.Numerics.Quaternion(Quaternion q) => new(q.x, q.y, q.z, q.w); + public static implicit operator NumericsQuaternion(Quaternion q) => new(q.x, q.y, q.z, q.w); /// /// Converts the supplied value to . @@ -592,7 +596,7 @@ Quaternion b /// /// The validated quaternion that represents the completed operation. /// - public static implicit operator Quaternion(System.Numerics.Quaternion q) => new(q.X, q.Y, q.Z, q.W); + public static implicit operator Quaternion(NumericsQuaternion q) => new(q.X, q.Y, q.Z, q.W); /// /// Determines whether this value and the supplied value represent the same logical state. diff --git a/src/foundation/core/Inno.Core.Mathematics/Rect.cs b/src/foundation/core/Inno.Core.Mathematics/Rect.cs index 288c9ffa0..b76d749ec 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Rect.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Rect.cs @@ -1,6 +1,8 @@ using System; using System.Runtime.CompilerServices; +using NumericsVector4 = System.Numerics.Vector4; + namespace Inno.Core.Mathematics; /// @@ -10,9 +12,24 @@ namespace Inno.Core.Mathematics; public struct Rect : IEquatable { /// - /// The horizontal or first component. + /// The horizontal position of the origin corner. + /// + public float x; + + /// + /// The vertical position of the origin corner. /// - public float x, y, width, height; + public float y; + + /// + /// The horizontal extent. + /// + public float width; + + /// + /// The vertical extent. + /// + public float height; /// /// Gets the scalar measurement or identity associated with the current state. @@ -91,13 +108,10 @@ float height /// when the operation succeeds or its condition is satisfied; otherwise, . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Overlaps(Rect other) - { - return !(right <= other.left - || left >= other.right - || bottom <= other.top - || top >= other.bottom); - } + public bool Overlaps(Rect other) => !(right <= other.left + || left >= other.right + || bottom <= other.top + || top >= other.bottom); /// /// Checks if this rectangle fully contains another rectangle. @@ -109,13 +123,10 @@ public bool Overlaps(Rect other) /// when the operation succeeds or its condition is satisfied; otherwise, . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Contains(Rect other) - { - return left <= other.left - && top <= other.top - && right >= other.right - && bottom >= other.bottom; - } + public bool Contains(Rect other) => left <= other.left + && top <= other.top + && right >= other.right + && bottom >= other.bottom; /// /// Checks if this rectangle contains a point. @@ -133,10 +144,8 @@ public bool Contains(Rect other) public bool Contains( float px, float py - ) { - return px >= left && px < right - && py >= top && py < bottom; - } + ) => px >= left && px < right + && py >= top && py < bottom; /// /// Determines whether current state contains the requested value value. @@ -166,9 +175,7 @@ float py public static Rect FromMinMax( Vector2 min, Vector2 max - ) { - return new Rect(min.x, min.y, max.x - min.x, max.y - min.y); - } + ) => new Rect(min.x, min.y, max.x - min.x, max.y - min.y); /// /// Returns the smallest axis-aligned rectangle containing both supplied rectangles. @@ -312,7 +319,7 @@ Rect b /// The validated system.numerics.vector4 that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator System.Numerics.Vector4(Rect r) => new System.Numerics.Vector4(r.x, r.y, r.width, r.height); + public static implicit operator NumericsVector4(Rect r) => new NumericsVector4(r.x, r.y, r.width, r.height); /// /// Converts the supplied value to . @@ -324,7 +331,7 @@ Rect b /// The validated rect that represents the completed operation. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator Rect(System.Numerics.Vector4 v) => new Rect(v.X, v.Y, v.Z, v.W); + public static implicit operator Rect(NumericsVector4 v) => new Rect(v.X, v.Y, v.Z, v.W); /// /// Determines whether this value and the supplied value represent the same logical state. diff --git a/src/foundation/core/Inno.Core.Mathematics/RectInt.cs b/src/foundation/core/Inno.Core.Mathematics/RectInt.cs index 45b0a4f18..d7cd2b5f2 100644 --- a/src/foundation/core/Inno.Core.Mathematics/RectInt.cs +++ b/src/foundation/core/Inno.Core.Mathematics/RectInt.cs @@ -11,9 +11,24 @@ namespace Inno.Core.Mathematics; public struct RectInt : IEquatable { /// - /// The horizontal or first component. + /// The horizontal position of the origin corner. + /// + public int x; + + /// + /// The vertical position of the origin corner. + /// + public int y; + + /// + /// The horizontal extent. + /// + public int width; + + /// + /// The vertical extent. /// - public int x, y, width, height; + public int height; /// /// Gets the scalar measurement or identity associated with the current state. @@ -92,13 +107,10 @@ int height /// when the operation succeeds or its condition is satisfied; otherwise, . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Overlaps(RectInt other) - { - return !(right <= other.left - || left >= other.right - || bottom <= other.top - || top >= other.bottom); - } + public bool Overlaps(RectInt other) => !(right <= other.left + || left >= other.right + || bottom <= other.top + || top >= other.bottom); /// /// Checks if this rectangle fully contains another rectangle. @@ -110,13 +122,10 @@ public bool Overlaps(RectInt other) /// when the operation succeeds or its condition is satisfied; otherwise, . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool Contains(RectInt other) - { - return left <= other.left - && top <= other.top - && right >= other.right - && bottom >= other.bottom; - } + public bool Contains(RectInt other) => left <= other.left + && top <= other.top + && right >= other.right + && bottom >= other.bottom; /// /// Checks if this rectangle contains a point. @@ -134,10 +143,8 @@ public bool Contains(RectInt other) public bool Contains( int px, int py - ) { - return px >= left && px < right - && py >= top && py < bottom; - } + ) => px >= left && px < right + && py >= top && py < bottom; /// /// Determines whether current state contains the requested value value. @@ -167,9 +174,7 @@ int py public static RectInt FromMinMax( Vector2Int min, Vector2Int max - ) { - return new RectInt(min.x, min.y, max.x - min.x, max.y - min.y); - } + ) => new RectInt(min.x, min.y, max.x - min.x, max.y - min.y); /// /// Returns the smallest axis-aligned rectangle containing both supplied rectangles. diff --git a/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs b/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs index f3a8d1d25..afa42d1d0 100644 --- a/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs +++ b/src/foundation/core/Inno.Core.Mathematics/SimdMath.cs @@ -26,13 +26,13 @@ Vector128 b ) { if (Sse.IsSupported) { - var mul = Sse.Multiply(a, b); + Vector128 mul = Sse.Multiply(a, b); return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2) + mul.GetElement(3); } if (AdvSimd.IsSupported) { - var mul = AdvSimd.Multiply(a, b); + Vector128 mul = AdvSimd.Multiply(a, b); return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2) + mul.GetElement(3); } @@ -69,17 +69,17 @@ float by ) { if (Sse.IsSupported) { - var a = Vector128.Create(ax, ay, 0f, 0f); - var b = Vector128.Create(bx, by, 0f, 0f); - var mul = Sse.Multiply(a, b); + Vector128 a = Vector128.Create(ax, ay, 0f, 0f); + Vector128 b = Vector128.Create(bx, by, 0f, 0f); + Vector128 mul = Sse.Multiply(a, b); return mul.GetElement(0) + mul.GetElement(1); } if (AdvSimd.IsSupported) { - var a = Vector128.Create(ax, ay, 0f, 0f); - var b = Vector128.Create(bx, by, 0f, 0f); - var mul = AdvSimd.Multiply(a, b); + Vector128 a = Vector128.Create(ax, ay, 0f, 0f); + Vector128 b = Vector128.Create(bx, by, 0f, 0f); + Vector128 mul = AdvSimd.Multiply(a, b); return mul.GetElement(0) + mul.GetElement(1); } @@ -121,17 +121,17 @@ float bz ) { if (Sse.IsSupported) { - var a = Vector128.Create(ax, ay, az, 0f); - var b = Vector128.Create(bx, by, bz, 0f); - var mul = Sse.Multiply(a, b); + Vector128 a = Vector128.Create(ax, ay, az, 0f); + Vector128 b = Vector128.Create(bx, by, bz, 0f); + Vector128 mul = Sse.Multiply(a, b); return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2); } if (AdvSimd.IsSupported) { - var a = Vector128.Create(ax, ay, az, 0f); - var b = Vector128.Create(bx, by, bz, 0f); - var mul = AdvSimd.Multiply(a, b); + Vector128 a = Vector128.Create(ax, ay, az, 0f); + Vector128 b = Vector128.Create(bx, by, bz, 0f); + Vector128 mul = AdvSimd.Multiply(a, b); return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2); } @@ -181,17 +181,17 @@ float bw ) { if (Sse.IsSupported) { - var a = Vector128.Create(ax, ay, az, aw); - var b = Vector128.Create(bx, by, bz, bw); - var mul = Sse.Multiply(a, b); + Vector128 a = Vector128.Create(ax, ay, az, aw); + Vector128 b = Vector128.Create(bx, by, bz, bw); + Vector128 mul = Sse.Multiply(a, b); return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2) + mul.GetElement(3); } if (AdvSimd.IsSupported) { - var a = Vector128.Create(ax, ay, az, aw); - var b = Vector128.Create(bx, by, bz, bw); - var mul = AdvSimd.Multiply(a, b); + Vector128 a = Vector128.Create(ax, ay, az, aw); + Vector128 b = Vector128.Create(bx, by, bz, bw); + Vector128 mul = AdvSimd.Multiply(a, b); return mul.GetElement(0) + mul.GetElement(1) + mul.GetElement(2) + mul.GetElement(3); } diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector2.cs b/src/foundation/core/Inno.Core.Mathematics/Vector2.cs index 570bbacff..fb3582a8b 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector2.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector2.cs @@ -2,6 +2,8 @@ using System.Runtime.CompilerServices; using System.Runtime.Serialization; +using NumericsVector2 = System.Numerics.Vector2; + namespace Inno.Core.Mathematics; /// @@ -13,12 +15,14 @@ public struct Vector2 : IEquatable /// /// The horizontal or first component. /// - [DataMember] public float x; + [DataMember] + public float x; /// /// The vertical or second component. /// - [DataMember] public float y; + [DataMember] + public float y; /// /// Creates a vector from explicit component values. @@ -478,7 +482,7 @@ Vector2 b /// /// The validated system.numerics.vector2 that represents the completed operation. /// - public static implicit operator System.Numerics.Vector2(Vector2 v) => new(v.x, v.y); + public static implicit operator NumericsVector2(Vector2 v) => new(v.x, v.y); /// /// Converts the supplied value to . @@ -489,7 +493,7 @@ Vector2 b /// /// The validated vector2 that represents the completed operation. /// - public static implicit operator Vector2(System.Numerics.Vector2 v) => new(v.X, v.Y); + public static implicit operator Vector2(NumericsVector2 v) => new(v.X, v.Y); /// /// Determines whether this value and the supplied value represent the same logical state. diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs b/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs index 59a44683f..10968fd7b 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector2Int.cs @@ -13,12 +13,14 @@ public struct Vector2Int : IEquatable /// /// The horizontal or first component. /// - [DataMember] public int x; + [DataMember] + public int x; /// /// The vertical or second component. /// - [DataMember] public int y; + [DataMember] + public int y; /// /// Creates a vector from explicit component values. diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector3.cs b/src/foundation/core/Inno.Core.Mathematics/Vector3.cs index e183613b9..681fee63d 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector3.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector3.cs @@ -5,6 +5,8 @@ using System.Runtime.Intrinsics.X86; using System.Runtime.Serialization; +using NumericsVector3 = System.Numerics.Vector3; + namespace Inno.Core.Mathematics; /// @@ -16,17 +18,20 @@ public struct Vector3 : IEquatable /// /// The horizontal or first component. /// - [DataMember] public float x; + [DataMember] + public float x; /// /// The vertical or second component. /// - [DataMember] public float y; + [DataMember] + public float y; /// /// The depth or third component. /// - [DataMember] public float z; + [DataMember] + public float z; /// /// Creates a vector from explicit component values. @@ -333,15 +338,15 @@ Vector3 normal /// /// Transforms a position as a column vector with an implicit homogeneous coordinate of one. /// - /// - /// The transformed XYZ components, including translation. No perspective divide is performed. - /// /// /// The input position. /// /// /// The transformation matrix applied to the supplied value. /// + /// + /// The transformed XYZ components, including translation. No perspective divide is performed. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform( Vector3 position, @@ -349,10 +354,10 @@ Matrix matrix ) { if (Sse.IsSupported || AdvSimd.IsSupported) { - var v = Vector128.Create(position.x, position.y, position.z, 1f); - var row1 = Vector128.Create(matrix.m11, matrix.m12, matrix.m13, matrix.m14); - var row2 = Vector128.Create(matrix.m21, matrix.m22, matrix.m23, matrix.m24); - var row3 = Vector128.Create(matrix.m31, matrix.m32, matrix.m33, matrix.m34); + Vector128 v = Vector128.Create(position.x, position.y, position.z, 1f); + Vector128 row1 = Vector128.Create(matrix.m11, matrix.m12, matrix.m13, matrix.m14); + Vector128 row2 = Vector128.Create(matrix.m21, matrix.m22, matrix.m23, matrix.m24); + Vector128 row3 = Vector128.Create(matrix.m31, matrix.m32, matrix.m33, matrix.m34); float x = SimdMath.Dot4(row1, v); float y = SimdMath.Dot4(row2, v); @@ -385,10 +390,10 @@ Matrix matrix ) { if (Sse.IsSupported || AdvSimd.IsSupported) { - var v = Vector128.Create(normal.x, normal.y, normal.z, 0f); - var row1 = Vector128.Create(matrix.m11, matrix.m12, matrix.m13, 0f); - var row2 = Vector128.Create(matrix.m21, matrix.m22, matrix.m23, 0f); - var row3 = Vector128.Create(matrix.m31, matrix.m32, matrix.m33, 0f); + Vector128 v = Vector128.Create(normal.x, normal.y, normal.z, 0f); + Vector128 row1 = Vector128.Create(matrix.m11, matrix.m12, matrix.m13, 0f); + Vector128 row2 = Vector128.Create(matrix.m21, matrix.m22, matrix.m23, 0f); + Vector128 row3 = Vector128.Create(matrix.m31, matrix.m32, matrix.m33, 0f); float x = SimdMath.Dot4(row1, v); float y = SimdMath.Dot4(row2, v); @@ -419,8 +424,13 @@ public static Vector3 Transform( Vector3 value, Quaternion rotation ) { - float x = value.x, y = value.y, z = value.z; - float qx = rotation.x, qy = rotation.y, qz = rotation.z, qw = rotation.w; + float x = value.x; + float y = value.y; + float z = value.z; + float qx = rotation.x; + float qy = rotation.y; + float qz = rotation.z; + float qw = rotation.w; float num1 = 2f * (qy * z - qz * y); float num2 = 2f * (qz * x - qx * z); @@ -584,7 +594,7 @@ Vector3 b /// /// The validated system.numerics.vector3 that represents the completed operation. /// - public static implicit operator System.Numerics.Vector3(Vector3 v) => new(v.x, v.y, v.z); + public static implicit operator NumericsVector3(Vector3 v) => new(v.x, v.y, v.z); /// /// Converts the supplied value to . @@ -595,7 +605,7 @@ Vector3 b /// /// The validated vector3 that represents the completed operation. /// - public static implicit operator Vector3(System.Numerics.Vector3 v) => new(v.X, v.Y, v.Z); + public static implicit operator Vector3(NumericsVector3 v) => new(v.X, v.Y, v.Z); /// /// Determines whether this value and the supplied value represent the same logical state. diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs b/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs index 9fdee8d59..99538eb07 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector3Int.cs @@ -13,17 +13,20 @@ public struct Vector3Int : IEquatable /// /// The horizontal or first component. /// - [DataMember] public int x; + [DataMember] + public int x; /// /// The vertical or second component. /// - [DataMember] public int y; + [DataMember] + public int y; /// /// The depth or third component. /// - [DataMember] public int z; + [DataMember] + public int z; /// /// Creates a vector from explicit component values. diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector4.cs b/src/foundation/core/Inno.Core.Mathematics/Vector4.cs index 3c2672c37..4d78fc56f 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector4.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector4.cs @@ -5,6 +5,8 @@ using System.Runtime.Intrinsics.X86; using System.Runtime.Serialization; +using NumericsVector4 = System.Numerics.Vector4; + namespace Inno.Core.Mathematics; /// @@ -16,22 +18,26 @@ public struct Vector4 : IEquatable /// /// The horizontal or first component. /// - [DataMember] public float x; + [DataMember] + public float x; /// /// The vertical or second component. /// - [DataMember] public float y; + [DataMember] + public float y; /// /// The depth or third component. /// - [DataMember] public float z; + [DataMember] + public float z; /// /// The homogeneous or fourth component. /// - [DataMember] public float w; + [DataMember] + public float w; /// /// Creates a vector from explicit component values. @@ -209,11 +215,11 @@ Matrix m ) { if (Sse.IsSupported || AdvSimd.IsSupported) { - var vec = Vector128.Create(v.x, v.y, v.z, v.w); - var row1 = Vector128.Create(m.m11, m.m12, m.m13, m.m14); - var row2 = Vector128.Create(m.m21, m.m22, m.m23, m.m24); - var row3 = Vector128.Create(m.m31, m.m32, m.m33, m.m34); - var row4 = Vector128.Create(m.m41, m.m42, m.m43, m.m44); + Vector128 vec = Vector128.Create(v.x, v.y, v.z, v.w); + Vector128 row1 = Vector128.Create(m.m11, m.m12, m.m13, m.m14); + Vector128 row2 = Vector128.Create(m.m21, m.m22, m.m23, m.m24); + Vector128 row3 = Vector128.Create(m.m31, m.m32, m.m33, m.m34); + Vector128 row4 = Vector128.Create(m.m41, m.m42, m.m43, m.m44); float tx = SimdMath.Dot4(row1, vec); float ty = SimdMath.Dot4(row2, vec); @@ -242,7 +248,8 @@ public Vector3 ProjectToVector3() { if (w == 0f) { - return new Vector3(x, y, z); // Avoid division by zero + // Avoid division by zero + return new Vector3(x, y, z); } return new Vector3(x / w, y / w, z / w); } @@ -349,14 +356,12 @@ Vector4 v public static Vector4 operator *( Matrix m, Vector4 v - ) { - return new Vector4( - m.m11 * v.x + m.m12 * v.y + m.m13 * v.z + m.m14 * v.w, - m.m21 * v.x + m.m22 * v.y + m.m23 * v.z + m.m24 * v.w, - m.m31 * v.x + m.m32 * v.y + m.m33 * v.z + m.m34 * v.w, - m.m41 * v.x + m.m42 * v.y + m.m43 * v.z + m.m44 * v.w - ); - } + ) => new Vector4( + m.m11 * v.x + m.m12 * v.y + m.m13 * v.z + m.m14 * v.w, + m.m21 * v.x + m.m22 * v.y + m.m23 * v.z + m.m24 * v.w, + m.m31 * v.x + m.m32 * v.y + m.m33 * v.z + m.m34 * v.w, + m.m41 * v.x + m.m42 * v.y + m.m43 * v.z + m.m44 * v.w + ); /// /// Divides the supplied value by the scalar divisor component by component. @@ -424,7 +429,7 @@ Vector4 b /// /// The validated system.numerics.vector4 that represents the completed operation. /// - public static implicit operator System.Numerics.Vector4(Vector4 v) => new(v.x, v.y, v.z, v.w); + public static implicit operator NumericsVector4(Vector4 v) => new(v.x, v.y, v.z, v.w); /// /// Converts the supplied value to . @@ -435,7 +440,7 @@ Vector4 b /// /// The validated vector4 that represents the completed operation. /// - public static implicit operator Vector4(System.Numerics.Vector4 v) => new(v.X, v.Y, v.Z, v.W); + public static implicit operator Vector4(NumericsVector4 v) => new(v.X, v.Y, v.Z, v.W); /// /// Determines whether this value and the supplied value represent the same logical state. diff --git a/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs b/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs index 4a022e445..ef650f12b 100644 --- a/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs +++ b/src/foundation/core/Inno.Core.Mathematics/Vector4Int.cs @@ -13,22 +13,26 @@ public struct Vector4Int : IEquatable /// /// The horizontal or first component. /// - [DataMember] public int x; + [DataMember] + public int x; /// /// The vertical or second component. /// - [DataMember] public int y; + [DataMember] + public int y; /// /// The depth or third component. /// - [DataMember] public int z; + [DataMember] + public int z; /// /// The homogeneous or fourth component. /// - [DataMember] public int w; + [DataMember] + public int w; /// /// Creates a vector from explicit component values. diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs index de78b0e27..adfcc9e75 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationConverterGenerator.cs @@ -210,7 +210,7 @@ private static ImmutableArray CollectMembers(INamedTypeSymbo hierarchy.Push(current); } - var members = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder members = ImmutableArray.CreateBuilder(); while (hierarchy.Count > 0) { INamedTypeSymbol current = hierarchy.Pop(); diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs index 693b987c7..f86366afd 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataGenerator.cs @@ -45,14 +45,12 @@ public sealed class SerializationMetadataGenerator : IIncrementalGenerator isEnabledByDefault: true ); - /// + /// public void Initialize(IncrementalGeneratorInitializationContext context) - { - context.RegisterSourceOutput(context.CompilationProvider, static ( + => context.RegisterSourceOutput(context.CompilationProvider, static ( output, compilation ) => Generate(output, compilation)); - } private static void Generate( SourceProductionContext output, @@ -414,7 +412,7 @@ StringBuilder accessors .Append(" Access") .Append(index) .Append("(") - .Append(isStruct ? "ref " : "") + .Append(isStruct ? "ref " : string.Empty) .Append(declaring) .Append(" target);\n"); return read @@ -446,10 +444,10 @@ StringBuilder accessors .Append(" Access") .Append(index) .Append("(") - .Append(isStruct ? "ref " : "") + .Append(isStruct ? "ref " : string.Empty) .Append(declaring) .Append(" target") - .Append(read ? "" : ", " + value + " value") + .Append(read ? string.Empty : ", " + value + " value") .Append(");\n"); return read ? "static target => Access" + index + "(" + target + ")" @@ -527,15 +525,15 @@ SourceProductionContext output .Append(")]\n private static extern void ") .Append(name) .Append("(") - .Append(ancestor.IsValueType ? "ref " : "") + .Append(ancestor.IsValueType ? "ref " : string.Empty) .Append(Name(ancestor)) .Append(" target") - .Append(hook.Parameters.Length == 0 ? "" : ", global::Inno.Core.Serialization.SerializationContext context") + .Append(hook.Parameters.Length == 0 ? string.Empty : ", global::Inno.Core.Serialization.SerializationContext context") .Append(");\n"); string target = ancestor.IsValueType ? "ref global::System.Runtime.CompilerServices.Unsafe.Unbox<" + Name(ancestor) + ">(target)" : "(" + Name(ancestor) + ")target"; - calls.Add(name + "(" + target + (hook.Parameters.Length == 0 ? "" : ", context") + ");"); + calls.Add(name + "(" + target + (hook.Parameters.Length == 0 ? string.Empty : ", context") + ");"); } } return calls.Count == 0 ? "null" : "static (target, context) => { " + string.Join(" ", calls) + " }"; diff --git a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs index 0fa74bccf..1155fa8c0 100644 --- a/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs +++ b/src/foundation/core/Inno.Core.Serialization.Generators/SerializationMetadataScope.cs @@ -13,7 +13,10 @@ internal sealed class SerializationMetadataScope private readonly List m_children = []; private int m_index; - internal SerializationMetadataScope(INamedTypeSymbol? owner) => this.owner = owner; + internal SerializationMetadataScope(INamedTypeSymbol? owner) + { + this.owner = owner; + } internal INamedTypeSymbol? owner { get; } internal StringBuilder registrations { get; } = new(); @@ -34,7 +37,7 @@ internal string Emit(string assemblyName) } string namespaceName = owner is null ? assemblyName + ".Generated" - : owner.ContainingNamespace.IsGlobalNamespace ? "" : owner.ContainingNamespace.ToDisplayString(); + : owner.ContainingNamespace.IsGlobalNamespace ? string.Empty : owner.ContainingNamespace.ToDisplayString(); if (namespaceName.Length > 0) { code.Append("namespace ").Append(namespaceName).Append(";\n"); @@ -138,7 +141,7 @@ private static string Declaration(INamedTypeSymbol type) Accessibility.ProtectedAndInternal => "private protected", _ => "internal" }; - string modifiers = type.IsStatic ? " static" : type.IsReadOnly ? " readonly" : ""; + string modifiers = type.IsStatic ? " static" : type.IsReadOnly ? " readonly" : string.Empty; string kind = type.IsRecord ? type.IsValueType ? "record struct" : "record class" : type.TypeKind == TypeKind.Struct ? "struct" : "class"; diff --git a/src/foundation/core/Inno.Core.Serialization/Attributes/SerializablePropertyAttribute.cs b/src/foundation/core/Inno.Core.Serialization/Attributes/SerializablePropertyAttribute.cs index d491dd6e6..4693f7751 100644 --- a/src/foundation/core/Inno.Core.Serialization/Attributes/SerializablePropertyAttribute.cs +++ b/src/foundation/core/Inno.Core.Serialization/Attributes/SerializablePropertyAttribute.cs @@ -32,6 +32,6 @@ public sealed class SerializablePropertyAttribute : Attribute /// public SerializablePropertyAttribute(PropertyVisibility visibility = PropertyVisibility.Show) { - propertyVisibility = visibility; + this.propertyVisibility = visibility; } } diff --git a/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs b/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs index b57adce30..ed3377277 100644 --- a/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs +++ b/src/foundation/core/Inno.Core.Serialization/Capture/SerializationCaptureKeyBuilder.cs @@ -4,6 +4,8 @@ using Inno.Core.Identity; using Inno.Core.Serialization.Converters; +using CoreIdentity = Inno.Core.Identity.Identity; + namespace Inno.Core.Serialization; /// @@ -34,7 +36,7 @@ public sealed class SerializationCaptureKeyBuilder internal SerializationCaptureKeyBuilder( SerializationOperation operation, Type rootType, - Inno.Core.Identity.Identity source, + CoreIdentity source, SerializationCaptureKey? previous ) : this(operation, previous) { @@ -109,7 +111,7 @@ public bool TryAddOwner( ) { RequireOperation(); ArgumentNullException.ThrowIfNull(source); - Inno.Core.Identity.Identity snapshot = source.identity; + CoreIdentity snapshot = source.identity; if (!revision.HasValue || snapshot.runtimeIdentity is not { } identity) { return Decline(); @@ -142,7 +144,7 @@ public bool TryAddProperties(ISerializable source) { return Decline(); } - Inno.Core.Identity.Identity snapshot = identified.identity; + CoreIdentity snapshot = identified.identity; if (snapshot.runtimeIdentity is not { } identity) { return Decline(); @@ -392,7 +394,7 @@ internal void ValidateIdentities() } internal readonly record struct SerializationCaptureIdentity( - Inno.Core.Identity.Identity identity, + CoreIdentity identity, RuntimeIdentity expected ) { internal void Validate() diff --git a/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs b/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs index 98f919c28..3b8d16289 100644 --- a/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs +++ b/src/foundation/core/Inno.Core.Serialization/Context/SerializationContext.cs @@ -50,7 +50,7 @@ public SerializationContext With(TContext value) { return new SerializationContext(m_values); } - var updated = (KeyValuePair[])m_values.Clone(); + KeyValuePair[] updated = (KeyValuePair[])m_values.Clone(); updated[index] = new(key, value); return new SerializationContext(updated); } diff --git a/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs b/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs index deec06e56..8ddd6fb9c 100644 --- a/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs +++ b/src/foundation/core/Inno.Core.Serialization/IO/SerializationWriter.cs @@ -44,13 +44,13 @@ Type valueType /// /// Borrows the immutable type snapshot pinned by this operation's converter generation. /// + /// + /// The writer no longer belongs to an active capture. + /// /// /// Use this snapshot for consistent type identities during a complete capture. It must not be retained beyond /// the writer's operation; keeping it would retain its collectible types after the converter lease is released. /// - /// - /// The writer no longer belongs to an active capture. - /// [ScriptingApiIgnore] public TypeCacheSnapshot typeSnapshot { @@ -165,7 +165,12 @@ Action write ValidateName(name); EnsureActive(); SerializationNode? previous = Previous(name); - var child = new SerializationWriter(m_operation, previous as ObjectSerializationNode, AppendPath(name), typeof(object)); + var child = new SerializationWriter( + m_operation, + previous as ObjectSerializationNode, + AppendPath(name), + typeof(object) + ); AddNode(name, previous ?? child.m_node!); write(child); ReplaceNode(name, child.Complete()); @@ -191,11 +196,6 @@ Action write /// a current Core identity owner and return true only for a complete proof. Snapshot capture alone /// can reuse a matching element; ordinary serialization always executes writeElement. /// - /// - /// The key builder belongs only to its synchronous callback. Uncertified rows and rows that invoke - /// nested converters execute the ordinary element writer on every capture. Callback failures and - /// changed declared inputs abort publication without modifying a previous snapshot. - /// /// /// Values or writeElement is null. /// @@ -205,6 +205,11 @@ Action write /// /// The writer has retired, a member is duplicated, or declared capture inputs change during writing. /// + /// + /// The key builder belongs only to its synchronous callback. Uncertified rows and rows that invoke + /// nested converters execute the ordinary element writer on every capture. Callback failures and + /// changed declared inputs abort publication without modifying a previous snapshot. + /// public void WriteObjectArray( string name, IEnumerable values, diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs index efbadee51..1e28021a8 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/BinarySerializationFormat.cs @@ -148,19 +148,58 @@ object value ) { switch (value) { - case bool typed: writer.Write((byte)NodeKind.Boolean); writer.Write(typed); return; - case byte typed: writer.Write((byte)NodeKind.Byte); writer.Write(typed); return; - case sbyte typed: writer.Write((byte)NodeKind.SByte); writer.Write(typed); return; - case short typed: writer.Write((byte)NodeKind.Int16); writer.Write(typed); return; - case ushort typed: writer.Write((byte)NodeKind.UInt16); writer.Write(typed); return; - case int typed: writer.Write((byte)NodeKind.Int32); writer.Write(typed); return; - case uint typed: writer.Write((byte)NodeKind.UInt32); writer.Write(typed); return; - case long typed: writer.Write((byte)NodeKind.Int64); writer.Write(typed); return; - case ulong typed: writer.Write((byte)NodeKind.UInt64); writer.Write(typed); return; - case float typed: writer.Write((byte)NodeKind.Single); writer.Write(typed); return; - case double typed: writer.Write((byte)NodeKind.Double); writer.Write(typed); return; - case decimal typed: writer.Write((byte)NodeKind.Decimal); writer.Write(typed); return; - case string typed: writer.Write((byte)NodeKind.String); writer.Write(typed); return; + case bool typed: + writer.Write((byte)NodeKind.Boolean); + writer.Write(typed); + return; + case byte typed: + writer.Write((byte)NodeKind.Byte); + writer.Write(typed); + return; + case sbyte typed: + writer.Write((byte)NodeKind.SByte); + writer.Write(typed); + return; + case short typed: + writer.Write((byte)NodeKind.Int16); + writer.Write(typed); + return; + case ushort typed: + writer.Write((byte)NodeKind.UInt16); + writer.Write(typed); + return; + case int typed: + writer.Write((byte)NodeKind.Int32); + writer.Write(typed); + return; + case uint typed: + writer.Write((byte)NodeKind.UInt32); + writer.Write(typed); + return; + case long typed: + writer.Write((byte)NodeKind.Int64); + writer.Write(typed); + return; + case ulong typed: + writer.Write((byte)NodeKind.UInt64); + writer.Write(typed); + return; + case float typed: + writer.Write((byte)NodeKind.Single); + writer.Write(typed); + return; + case double typed: + writer.Write((byte)NodeKind.Double); + writer.Write(typed); + return; + case decimal typed: + writer.Write((byte)NodeKind.Decimal); + writer.Write(typed); + return; + case string typed: + writer.Write((byte)NodeKind.String); + writer.Write(typed); + return; case Guid typed: Span bytes = stackalloc byte[16]; _ = typed.TryWriteBytes(bytes); diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs index 5cdd63e5b..474cf1c9e 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs @@ -135,7 +135,7 @@ out ConverterCandidate? candidate return false; } - var converter = (SerializationConverter)GetOrCreateConverter(snapshot, closedConverterType); + SerializationConverter converter = (SerializationConverter)GetOrCreateConverter(snapshot, closedConverterType); ConverterInvoker invoker = converter.CreateInvoker(); candidate = new ConverterCandidate(closedConverterType, GetTypeDistance(valueType, targetType), invoker); return true; @@ -422,14 +422,17 @@ internal bool CanReuseRevision( SerializationTypeMetadata metadata, ISerializationMetadataSource source ) { - var plans = Volatile.Read(ref m_revisionPlans); + ConcurrentDictionary? plans = Volatile.Read( + ref m_revisionPlans + ); if (plans is null) { var created = new ConcurrentDictionary(); plans = Interlocked.CompareExchange(ref m_revisionPlans, created, null) ?? created; } - if (plans.TryGetValue(metadata, out var known) && ReferenceEquals(known.source, source)) - { + if (plans.TryGetValue(metadata, out (ISerializationMetadataSource source, bool eligible) known) + && ReferenceEquals(known.source, source) + ) { return known.eligible; } bool eligible = !metadata.requiresConverter; diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs index 54eaf3047..9c144772e 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotBinaryFormat.cs @@ -15,7 +15,7 @@ internal static byte[] Encode(IReadOnlyList member in members) { byte[] data = BinarySerializationFormat.Encode(member.Value); writer.Write(member.Key); diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs index c4bacda6a..2b87318d7 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/PropertySnapshotPipeline.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Reflection; namespace Inno.Core.Serialization; @@ -42,7 +43,7 @@ internal static BinarySerializationNode CaptureData( operation.RetireCaptureMember(); if (captured is null && !ReferenceEquals(node, prior)) { - captured = new(before!); + captured = [.. before!]; captured.RemoveRange(count, captured.Count - count); } captured?.Add(new(member.name, node)); @@ -64,7 +65,7 @@ internal static BinarySerializationNode CaptureData( } if (captured is null) { - captured = new(before!); + captured = [.. before!]; captured.RemoveRange(count, captured.Count - count); } var state = new PropertyDataCapture([.. captured]) { hasConverters = operation.converterWrites != 0 }; @@ -243,7 +244,7 @@ and not AccessViolationException and not OperationCanceledException; private static Exception Unwrap(Exception exception) - => exception is System.Reflection.TargetInvocationException { InnerException: not null } invocation + => exception is TargetInvocationException { InnerException: not null } invocation ? invocation.InnerException! : exception; diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs index bec1016a3..fa6697f91 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs @@ -53,7 +53,10 @@ internal sealed record ArraySerializationNode : SerializationNode internal ArraySerializationNode() : this([]) {} - internal ArraySerializationNode(List values) => this.values = values; + internal ArraySerializationNode(List values) + { + this.values = values; + } internal List values { get; } } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs index fc2f16f45..fbf29db71 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNodeReuse.cs @@ -45,7 +45,7 @@ internal static ObjectSerializationNode CopyObject(ObjectSerializationNode previ { var result = new ObjectSerializationNode(); result.values.EnsureCapacity(previous.values.Count); - foreach (var pair in previous.values) + foreach (KeyValuePair pair in previous.values) { result.values.Add(pair.Key, pair.Value); } diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs index b7e0c019c..dfd5506b3 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationOperation.cs @@ -23,7 +23,7 @@ internal SerializationOperation( ArgumentNullException.ThrowIfNull(converters); this.context = context; m_converters = converters; - isSnapshotCapture = snapshotCapture; + this.isSnapshotCapture = snapshotCapture; } internal ConverterRegistryLease converters => m_converters; diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs index 9b7c06d62..e79d07c67 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/SerializationTypeMetadata.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Inno.Core.Identity; namespace Inno.Core.Serialization; @@ -148,7 +149,7 @@ public SerializationTypeMetadata WithCaptureRevision(Func readRe { ArgumentNullException.ThrowIfNull(readRevision); if (!type.IsSealed || type.IsValueType || !typeof(ISerializable).IsAssignableFrom(type) - || !typeof(Inno.Core.Identity.IdentityObject).IsAssignableFrom(type) + || !typeof(IdentityObject).IsAssignableFrom(type) ) { throw new InvalidOperationException( "Capture revision metadata requires a sealed serializable Core identity source." diff --git a/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs b/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs index 8433f3b15..a22737c60 100644 --- a/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs +++ b/src/foundation/core/Inno.Core.Serialization/Metadata/StaticSerializationMetadataSource.cs @@ -29,7 +29,7 @@ public StaticSerializationMetadataSource(IReadOnlyList + /// public SerializationTypeMetadata GetMetadata(Type type) { ArgumentNullException.ThrowIfNull(type); diff --git a/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs b/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs index c76fa145b..50c1f8d2d 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializationRegistry.cs @@ -22,12 +22,12 @@ public sealed class SerializationRegistry : IDisposable /// /// The type catalog that owns converter extension generations. /// - /// - /// Thrown when is null. - /// /// /// The declaration access provider selected by the same composition root. /// + /// + /// Thrown when is null. + /// [ScriptingApiIgnore] public SerializationRegistry( TypeCatalog types, @@ -404,12 +404,6 @@ public byte[] Serialize( /// Reference equality proves unchanged bytes; different instances may still encode identically. /// Ordinary serialization and snapshot encoding produce identical bytes. Capture failure publishes no snapshot. /// - /// - /// Writers borrowed by a snapshot converter belong to its synchronous callback and must not be used after it returns. - /// Default capture evaluates getters and converters in full. An explicitly opted-in converter may - /// reuse its prior node only after every current capture-key input has been verified. Ordinary - /// serialization never uses these keys; incomplete or unavailable declarations retain complete capture. - /// /// /// The source value is null. /// @@ -419,6 +413,12 @@ public byte[] Serialize( /// /// A converter, unsupported value or reference context prevents capture. /// + /// + /// Writers borrowed by a snapshot converter belong to its synchronous callback and must not be used after it returns. + /// Default capture evaluates getters and converters in full. An explicitly opted-in converter may + /// reuse its prior node only after every current capture-key input has been verified. Ordinary + /// serialization never uses these keys; incomplete or unavailable declarations retain complete capture. + /// [ScriptingApiIgnore] public SerializationSnapshot CaptureSnapshot( T value, diff --git a/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs b/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs index f9ebf6c66..f3de7573d 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializationSnapshot.cs @@ -13,7 +13,10 @@ namespace Inno.Core.Serialization; /// public sealed class SerializationSnapshot { - internal SerializationSnapshot(SerializationNode root) => this.root = root; + internal SerializationSnapshot(SerializationNode root) + { + this.root = root; + } /// /// Encodes this capture using the same deterministic binary format as ordinary serialization. @@ -29,10 +32,6 @@ public sealed class SerializationSnapshot /// /// The writable caller-owned stream, which remains open. /// - /// - /// Immutable keyed objects may retain canonical encoded blocks of at most 64 KiB each. Larger - /// objects remain streamed, and cached bytes never contain source objects or generation references. - /// /// /// The destination is null. /// @@ -42,6 +41,10 @@ public sealed class SerializationSnapshot /// /// The destination rejects a write; its partial bytes remain the caller's responsibility. /// + /// + /// Immutable keyed objects may retain canonical encoded blocks of at most 64 KiB each. Larger + /// objects remain streamed, and cached bytes never contain source objects or generation references. + /// public void WriteTo(Stream destination) { ArgumentNullException.ThrowIfNull(destination); diff --git a/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs b/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs index 94c18670a..c03f70658 100644 --- a/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs +++ b/src/foundation/core/Inno.Core.Serialization/SerializedIdentityRemapper.cs @@ -72,7 +72,7 @@ private static SerializationNode RewriteNode( return new BinarySerializationNode(Rewrite(binary.value, identities, paths)); case ObjectSerializationNode value: { - var rewritten = new ObjectSerializationNode(); + var rewritten = new ObjectSerializationNode(); foreach ((string name, SerializationNode child) in value.values) { rewritten.values.Add(name, RewriteNode(child, identities, paths)); @@ -81,7 +81,7 @@ private static SerializationNode RewriteNode( } case ArraySerializationNode value: { - var rewritten = new ArraySerializationNode(); + var rewritten = new ArraySerializationNode(); foreach (SerializationNode child in value.values) { rewritten.values.Add(RewriteNode(child, identities, paths)); @@ -90,7 +90,7 @@ private static SerializationNode RewriteNode( } case MapSerializationNode value: { - var rewritten = new MapSerializationNode(); + var rewritten = new MapSerializationNode(); foreach (KeyValuePair entry in value.values) { rewritten.values.Add( diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs index 7a853f687..f3951654f 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs @@ -38,7 +38,7 @@ public ProjectSettingId(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() => value ?? string.Empty; + public override readonly string ToString() => value ?? string.Empty; } /// diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs index 9b2b4e059..b77f14eb1 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettings.cs @@ -38,12 +38,12 @@ public sealed class ProjectSettings : IDisposable /// /// The project namespace used when the document has no authored identity override. /// - /// - /// Dependency-ordered default contributors. - /// /// /// The owner's complete reference resolver context, used for defaults, contributions and returned snapshots. /// + /// + /// Dependency-ordered default contributors. + /// /// /// A required service or the owner's serialization context is null. /// @@ -420,13 +420,11 @@ public void SetProjectOverride( ProjectSettingId id, ISerializable value, IReadOnlyList contributors - ) { - _ = ApplyProjectOverrides( - new Dictionary { [id] = value }, - resets: null, - contributors - ); - } + ) => _ = ApplyProjectOverrides( + new Dictionary { [id] = value }, + resets: null, + contributors + ); /// /// Applies multiple project contributions and removals as one atomic document update. @@ -454,7 +452,7 @@ IReadOnlyList contributors ValidateContributorOrder(contributors); ProjectSettingsRegistry.Snapshot registry = m_registry.settings; - var records = m_document.overrides.ToDictionary(static record => record.id); + Dictionary records = m_document.overrides.ToDictionary(static record => record.id); bool changed = false; if (resets is not null) { @@ -566,7 +564,10 @@ private static IReadOnlySet ExpandContributorClosure( IReadOnlySet directDependencies, IReadOnlyList contributors ) { - var byId = contributors.ToDictionary(static contributor => contributor.id, StringComparer.Ordinal); + Dictionary byId = contributors.ToDictionary( + static contributor => contributor.id, + StringComparer.Ordinal + ); var result = new HashSet(StringComparer.Ordinal); DependencyGraph graph = CreateContributorGraph(contributors); foreach (string id in directDependencies) diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs index 5fc8e878b..4f29940be 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsRegistry.cs @@ -72,13 +72,15 @@ protected override Snapshot Build(TypeCacheSnapshot types) } ProjectSettingComposerAttribute attribute = types.GetAttribute(typeRef, inherit: false)!; - if (!settingTypes.TryGetValue(attribute.settingId, out var setting)) - { + if (!settingTypes.TryGetValue( + attribute.settingId, + out (Guid stableTypeId, Type runtimeType, bool allowPluginContributions) setting + )) { throw new InvalidOperationException( $"Project setting composer '{type.FullName}' targets undefined setting '{attribute.settingId}'." ); } - var composer = OwnCandidateExtension((ProjectSettingComposer)types.CreateInstance(type)); + ProjectSettingComposer composer = OwnCandidateExtension((ProjectSettingComposer)types.CreateInstance(type)); if (composer.settingType != setting.runtimeType) { throw new InvalidOperationException( diff --git a/src/foundation/extensibility/Inno.Extensibility.Catalogs/ITypeCatalogRegistrar.cs b/src/foundation/extensibility/Inno.Extensibility.Catalogs/ITypeCatalogRegistrar.cs index d34311ac0..2518e0f8a 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Catalogs/ITypeCatalogRegistrar.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Catalogs/ITypeCatalogRegistrar.cs @@ -44,12 +44,12 @@ void Register( /// /// The type is not a fully closed generic construction. /// - /// - /// Repeated registrations of the same closed construction are idempotent; the first factory is retained. - /// /// /// The caller runs on another thread or retained this registrar after catalog composition completed. /// + /// + /// Repeated registrations of the same closed construction are idempotent; the first factory is retained. + /// void RegisterFactory( Type type, Func factory @@ -64,10 +64,6 @@ Func factory /// /// The complete closed argument set. The registrar copies this collection during registration. /// - /// - /// This fact lets static resolution skip an inapplicable converter without attempting dynamic generic creation. - /// Unknown constructions remain explicit deployment errors. Repeated rejections are idempotent. - /// /// /// The declaration or argument set is incomplete, open, or conflicts with a registered factory. /// @@ -77,6 +73,10 @@ Func factory /// /// The caller runs on another thread or retained this registrar after catalog composition completed. /// + /// + /// This fact lets static resolution skip an inapplicable converter without attempting dynamic generic creation. + /// Unknown constructions remain explicit deployment errors. Repeated rejections are idempotent. + /// void RejectGenericConstruction( Type definition, IReadOnlyList arguments diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs index 50e05c064..10ae21095 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CompositeAssemblyUnloadProbe.cs @@ -12,11 +12,13 @@ internal sealed class CompositeAssemblyUnloadProbe : IAssemblyUnloadProbe private readonly IAssemblyUnloadProbe[] m_children; internal CompositeAssemblyUnloadProbe(IReadOnlyList children) - => m_children = children.ToArray(); + { + m_children = children.ToArray(); + } - /// + /// public string description => string.Join(", ", m_children.Select(static child => child.description)); - /// + /// public bool isCompleted => m_children.All(static child => child.isCompleted); } diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs index bb8582587..64495fa61 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/ModuleHost.cs @@ -76,7 +76,7 @@ public ModuleHost(ModuleHostOptions options) ArgumentNullException.ThrowIfNull(m_options.catalogSource); m_options.catalogSource.changed += OnAssemblyLoaded; m_assemblyLoadSubscribed = true; - isInitialized = true; + this.isInitialized = true; m_hostCatalogDirty = true; try { @@ -182,7 +182,7 @@ public AssemblyModuleHandle Load(IModuleSource request) ValidateUniqueReloadBoundary(request.domain, request.scope); } - AssemblyModuleHandle handle = new(Guid.NewGuid()); + var handle = new AssemblyModuleHandle(Guid.NewGuid()); IReadOnlyDictionary plannedAssemblies = BuildPlannedAssemblyMap([request]); AssemblyModuleEntry module = StageModule( @@ -259,7 +259,7 @@ out AssemblyScope candidateScope ); } - AssemblyModuleHandle handle = new(Guid.NewGuid()); + var handle = new AssemblyModuleHandle(Guid.NewGuid()); var module = new AssemblyModuleEntry { handle = handle, @@ -487,7 +487,7 @@ public IAssemblyUnloadProbe Unload(IReadOnlyList modules) : module.scope == AssemblyScope.Runtime ? 1 : 2 )) .ToArray(); - var monitors = unloadOrder.Select(BeginUnload).ToArray(); + IAssemblyUnloadProbe[] monitors = unloadOrder.Select(BeginUnload).ToArray(); return monitors.Length == 1 ? monitors[0] : new CompositeAssemblyUnloadProbe(monitors); @@ -595,7 +595,11 @@ internal void Activate(ReloadState state) } catch (Exception rollbackFailure) { - var failure = new AggregateException("Module activation and rollback failed.", activationFailure, rollbackFailure); + var failure = new AggregateException( + "Module activation and rollback failed.", + activationFailure, + rollbackFailure + ); generations.Fault(failure); throw failure; } @@ -753,7 +757,7 @@ private AssemblyReloadSession BeginReloadLocked( candidates.Add(StageModule(handle, request, generation, upstream, plannedAssemblies)); } - var replacements = candidates.ToDictionary(static module => module.handle); + Dictionary replacements = candidates.ToDictionary(static module => module.handle); AssemblyCatalogSnapshot previousCatalog = m_currentCatalog; AssemblyCatalogSnapshot candidateCatalog = BuildCatalog( replacements, @@ -991,7 +995,11 @@ private void RebuildOnceLocked() } catch (Exception rollbackFailure) { - var aggregate = new AggregateException("Catalog activation and rollback failed.", failure, rollbackFailure); + var aggregate = new AggregateException( + "Catalog activation and rollback failed.", + failure, + rollbackFailure + ); generations.Fault(aggregate); throw aggregate; } @@ -1256,7 +1264,7 @@ IReadOnlyList removedModules private void ValidateUnloadClosure(IReadOnlyList handles) { - var removed = handles.ToHashSet(); + HashSet removed = handles.ToHashSet(); bool removesPlugin = m_modules.Values.Any(module => ( removed.Contains(module.handle) && module.domain == AssemblyDomain.InnoPlugin )); diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs index cf7448fab..8dcc99447 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs @@ -21,7 +21,7 @@ ReloadState state ) { m_owner = owner; m_state = state; - context = new AssemblyReloadContext( + this.context = new AssemblyReloadContext( state.previousCatalog, state.candidateCatalog, state.candidateModules.Select(static module => module.handle).ToArray(), diff --git a/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs b/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs index 0d9671e8e..0c4a3049a 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Reload/GenerationCoordinator.cs @@ -148,16 +148,16 @@ public IDisposable AcquireRead(string operation) /// /// A scope for the entire operation, or a borrowed scope inside publication on its own control thread. /// - /// - /// Published data remains readable while old contexts await collection. This scope does not authorize Play, - /// Build, Export or a new generation transaction; those owners must still use their strict admission boundary. - /// /// /// Another thread is publishing or the owner is Faulted. /// /// /// Retirement has failed without releasing its dependent owners. /// + /// + /// Published data remains readable while old contexts await collection. This scope does not authorize Play, + /// Build, Export or a new generation transaction; those owners must still use their strict admission boundary. + /// public IDisposable AcquireOperation(string operation) { ArgumentException.ThrowIfNullOrWhiteSpace(operation); @@ -346,13 +346,20 @@ IReadOnlyList changes catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) { retirementBlocked = true; - var combined = new AggregateException($"Generation '{operation}' failed and rollback remains pending.", error, failure); + var combined = new AggregateException( + $"Generation '{operation}' failed and rollback remains pending.", + error, + failure + ); RetainFailedRetirement(combined, (publication, snapshot)); throw combined; } if (rollback.Count > 0) { - var failure = new AggregateException($"Generation '{operation}' failed and rollback was incomplete.", [error, .. rollback]); + var failure = new AggregateException( + $"Generation '{operation}' failed and rollback was incomplete.", + [error, .. rollback] + ); Fault(failure); throw failure; } @@ -479,13 +486,13 @@ public void Fault(Exception exception) /// /// Rejects dependency destruction after a generation owner reported unfinished retirement. /// + /// + /// A failed generation still owns live work; its dependencies must remain owned until host restart. + /// /// /// Ordinary terminal cleanup failures do not prevent remaining cleanup. Unfinished retirement remains /// blocking even if an earlier ordinary error is the primary diagnostic failure. /// - /// - /// A failed generation still owns live work; its dependencies must remain owned until host restart. - /// public void EnsureRetirementSafe() { lock (m_sync) diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs index a5b90ec37..8b45ce7ef 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCacheSnapshot.cs @@ -94,6 +94,9 @@ public IReadOnlyList GetTypesWithAttribute() /// /// Gets the reference for a CLR type in this snapshot. /// + /// + /// The type consumed by get type ref; ownership remains with the caller unless explicitly stated otherwise. + /// /// /// The logical and generation-local identity of . /// @@ -103,9 +106,6 @@ public IReadOnlyList GetTypesWithAttribute() /// /// Thrown when the type does not belong to this snapshot. /// - /// - /// The type consumed by get type ref; ownership remains with the caller unless explicitly stated otherwise. - /// public TypeRef GetTypeRef(Type type) => m_identityRegistry.GetTypeRef(type); /// @@ -312,6 +312,6 @@ private static TypeCacheSnapshot CreateEmpty() identities.Rebuild([], previous: null); var queries = new TypeQueryRegistry(); queries.Rebuild([], identities); - return new TypeCacheSnapshot(0, null, [], [], new Dictionary(), identities, queries); + return new TypeCacheSnapshot(0, null, [], [], [], identities, queries); } } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs index fcbe3dc5e..65333cc52 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeCatalog.cs @@ -30,15 +30,15 @@ public sealed class TypeCatalog : IDisposable /// /// The module host that owns the assembly generations visible to this catalog. /// + /// + /// The metadata provider selected by the composition root for every contributed assembly. + /// /// /// Thrown when is null. /// /// /// Thrown when has already been disposed. /// - /// - /// The metadata provider selected by the composition root for every contributed assembly. - /// public TypeCatalog( ModuleHost modules, ITypeCatalogSource source @@ -179,6 +179,9 @@ public IReadOnlyList GetTypesWithAttribute() /// /// Gets the reference for an active CLR type. /// + /// + /// The type consumed by get type ref; ownership remains with the caller unless explicitly stated otherwise. + /// /// /// Its logical and generation-local identity. /// @@ -188,9 +191,6 @@ public IReadOnlyList GetTypesWithAttribute() /// /// Thrown when the type does not belong to the active catalog. /// - /// - /// The type consumed by get type ref; ownership remains with the caller unless explicitly stated otherwise. - /// public TypeRef GetTypeRef(Type type) => current.GetTypeRef(type); /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs index 8e4e93bf3..3dbe6243f 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeIdentityRegistry.cs @@ -117,7 +117,7 @@ public void Rebuild( stableByType[type] = stableId; } - var orderedTypes = sourceTypes + Type[] orderedTypes = sourceTypes .OrderBy(t => t.Assembly.GetName().Name, StringComparer.Ordinal) .ThenBy(t => t.FullName, StringComparer.Ordinal) .ToArray(); @@ -453,7 +453,7 @@ private static IReadOnlyDictionary type.FullName ?? type.Name, StringComparer.Ordinal); + Dictionary availableTypes = group.ToDictionary(static type => type.FullName ?? type.Name, StringComparer.Ordinal); var mappings = new Dictionary(StringComparer.Ordinal); foreach (AssemblyMetadataAttribute attribute in attributes) { @@ -506,7 +506,7 @@ string name SwapGuidByteOrder(ns); byte[] nameBytes = Encoding.UTF8.GetBytes(name); - byte[] data = new byte[ns.Length + nameBytes.Length]; + var data = new byte[ns.Length + nameBytes.Length]; Buffer.BlockCopy(ns, 0, data, 0, ns.Length); Buffer.BlockCopy(nameBytes, 0, data, ns.Length, nameBytes.Length); diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs index 72a12ccf6..7d692c962 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeQueryRegistry.cs @@ -76,12 +76,10 @@ TypeIdentityRegistry typeIdentityRegistry /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyList GetSubTypesOf(TypeIdentityRegistry typeIdentityRegistry) - { - return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(T), out int keyId) - && m_subclassCache.TryGetValue(keyId, out IReadOnlyList? set) - ? set - : []; - } + => typeIdentityRegistry.TryGetRuntimeTypeId(typeof(T), out int keyId) + && m_subclassCache.TryGetValue(keyId, out IReadOnlyList? set) + ? set + : []; /// /// Retrieves the requested types implementing value from current authoritative state. @@ -96,12 +94,10 @@ public IReadOnlyList GetSubTypesOf(TypeIdentityRegistry typeIdentity /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyList GetTypesImplementing(TypeIdentityRegistry typeIdentityRegistry) - { - return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(TInterface), out int keyId) - && m_interfaceCache.TryGetValue(keyId, out IReadOnlyList? set) - ? set - : []; - } + => typeIdentityRegistry.TryGetRuntimeTypeId(typeof(TInterface), out int keyId) + && m_interfaceCache.TryGetValue(keyId, out IReadOnlyList? set) + ? set + : []; /// /// Retrieves the requested types with attribute value from current authoritative state. @@ -116,13 +112,10 @@ public IReadOnlyList GetTypesImplementing(TypeIdentityRegis /// An immutable snapshot of the values selected by the operation. /// public IReadOnlyList GetTypesWithAttribute(TypeIdentityRegistry typeIdentityRegistry) - where TAttr : Attribute - { - return typeIdentityRegistry.TryGetRuntimeTypeId(typeof(TAttr), out int keyId) - && m_attributeCache.TryGetValue(keyId, out IReadOnlyList? set) - ? set - : []; - } + where TAttr : Attribute => typeIdentityRegistry.TryGetRuntimeTypeId(typeof(TAttr), out int keyId) + && m_attributeCache.TryGetValue(keyId, out IReadOnlyList? set) + ? set + : []; private static void AddToIndex( Dictionary> index, @@ -133,7 +126,7 @@ TypeIdentityRegistry typeIdentityRegistry int keyId = typeIdentityRegistry.GetOrAddRuntimeTypeId(keyType); if (!index.TryGetValue(keyId, out HashSet? set)) { - set = new HashSet(); + set = []; index[keyId] = set; } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs index d08985e38..3d34293d2 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeCache/TypeRef.cs @@ -119,12 +119,12 @@ public Type Resolve(TypeCacheSnapshot snapshot) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => obj is TypeRef other && Equals(other); /// diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs index b67404f5c..556f3779b 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs @@ -679,7 +679,11 @@ public void Activate() } catch (Exception rollbackFailure) { - var combined = new AggregateException("Registry activation and rollback failed.", activationFailure, rollbackFailure); + var combined = new AggregateException( + "Registry activation and rollback failed.", + activationFailure, + rollbackFailure + ); if (RetirementPendingException.Find(combined) is not null) { owner.RetainFailedRetirement(combined, this, "activation rollback"); diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs index af1475611..73d2e6336 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs @@ -215,7 +215,11 @@ internal void Activate() } catch (Exception rollbackFailure) { - var combined = new AggregateException("Type registry activation and rollback failed.", activationFailure, rollbackFailure); + var combined = new AggregateException( + "Type registry activation and rollback failed.", + activationFailure, + rollbackFailure + ); if (RetirementPendingException.Find(combined) is not null) { m_failure = combined; diff --git a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs index e9d662dcd..02e958d1b 100644 --- a/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs +++ b/src/runtime/contracts/Inno.Runtime.Contracts/RuntimeSubsystem.cs @@ -32,13 +32,13 @@ public abstract class RuntimeSubsystem : IRuntimeSubsystem /// /// Acquires session resources after every dependency has attached. /// + /// + /// The subsystem is already started. + /// /// /// The caller must own this instance before attachment. Failed attachment stops admission but leaves partial /// resources with that owner, which must drive Dispose through any pending retirement. /// - /// - /// The subsystem is already started. - /// public void Attach() { ObjectDisposedException.ThrowIf(m_disposed, this); diff --git a/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs b/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs index b5a65ba34..62f348170 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/GameCodeModule.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using Inno.Extensibility.Modules; @@ -38,7 +39,7 @@ IReadOnlyList dependencies ArgumentNullException.ThrowIfNull(dependencies); if (assemblies.Any(static assembly => assembly is null)) { - throw new System.IO.InvalidDataException("A code module contains a null assembly identity."); + throw new InvalidDataException("A code module contains a null assembly identity."); } var declaration = new GameRuntimeModule { diff --git a/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs b/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs index 3aca1fb53..ffeb055f8 100644 --- a/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs +++ b/src/runtime/engine/Inno.Runtime/Deployment/RuntimeManifestEnvelope.cs @@ -43,8 +43,8 @@ SerializationGeneration serialization manifest.persistentDataPath.Length == 0 ? manifest.applicationId : manifest.persistentDataPath ); byte[] payload = serialization.Serialize(manifest); - byte[] result = new byte[checked(magic.Length + sizeof(int) * 3 - + applicationId.Length + persistentDataPath.Length + payload.Length)]; + var result = new byte[checked(magic.Length + sizeof(int) * 3 + + applicationId.Length + persistentDataPath.Length + payload.Length)]; int offset = 0; magic.CopyTo(result); offset += magic.Length; diff --git a/src/runtime/engine/Inno.Runtime/Execution/Time.cs b/src/runtime/engine/Inno.Runtime/Execution/Time.cs index 6ebcd1a68..8010092f1 100644 --- a/src/runtime/engine/Inno.Runtime/Execution/Time.cs +++ b/src/runtime/engine/Inno.Runtime/Execution/Time.cs @@ -121,10 +121,7 @@ internal sealed class RuntimeClock internal long fixedStepCount { get; private set; } - internal IDisposable EnterScope() - { - return S_CURRENT_SCOPE.Enter(this); - } + internal IDisposable EnterScope() => S_CURRENT_SCOPE.Enter(this); internal RuntimeFrame Update(float unscaledDeltaTime) { diff --git a/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs b/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs index a43449cfe..0695fb551 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/EngineHost.cs @@ -34,16 +34,16 @@ internal EngineHost( ISerializationMetadataSource serializationMetadata ) { this.retirementTimeout = retirementTimeout; - logs = new LogRouter(deliveryMode: logDeliveryMode); - diagnostics = new DiagnosticHub(); + this.logs = new LogRouter(deliveryMode: logDeliveryMode); + this.diagnostics = new DiagnosticHub(); try { - modules = new ModuleHost(new ModuleHostOptions + this.modules = new ModuleHost(new ModuleHostOptions { catalogSource = moduleSource }); - types = new TypeCatalog(modules, typeSource); - serialization = new SerializationRegistry(types, serializationMetadata); + this.types = new TypeCatalog(modules, typeSource); + this.serialization = new SerializationRegistry(types, serializationMetadata); } catch { @@ -296,7 +296,10 @@ private void DisposeCore() } if (m_retirementFailures is not null) { - var failure = new AggregateException("Engine host disposal encountered one or more failures.", m_retirementFailures); + var failure = new AggregateException( + "Engine host disposal encountered one or more failures.", + m_retirementFailures + ); m_retirementFailures = null; throw failure; } diff --git a/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs b/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs index 5294b15fd..dd2377acc 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/EngineHostBuilder.cs @@ -51,7 +51,7 @@ public EngineHost Build() { throw new InvalidOperationException("The composition root must select module, type and serialization metadata sources."); } - EngineHost host = new( + var host = new EngineHost( m_retirementTimeout, m_logDeliveryMode, m_moduleSource, @@ -73,12 +73,12 @@ public EngineHost Build() /// /// The type metadata provider corresponding to the same code deployment strategy. /// - /// - /// This builder for fluent composition. - /// /// /// The declaration access provider corresponding to the same managed deployment. /// + /// + /// This builder for fluent composition. + /// public EngineHostBuilder UseMetadataSources( IAssemblyCatalogSource modules, ITypeCatalogSource types, diff --git a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs index 7a596205d..dd601e02d 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/RuntimeSession.cs @@ -42,10 +42,10 @@ RuntimeSessionOptions options ) { m_host = host; this.options = Validate(options); - sessionId = LogSessionId.Create(); + this.sessionId = LogSessionId.Create(); m_identities = new IdentityAllocator(); m_coroutines = new CoroutineScheduler(); - events = new EventDispatcher(); + this.events = new EventDispatcher(); m_retirement = new RetirementBarrier($"Runtime session {sessionId}", host.retirementTimeout); } @@ -410,7 +410,10 @@ private void DisposeCore() } if (m_retirementFailures is not null) { - var failure = new AggregateException("Runtime session disposal encountered one or more failures.", m_retirementFailures); + var failure = new AggregateException( + "Runtime session disposal encountered one or more failures.", + m_retirementFailures + ); m_retirementFailures = null; throw failure; } diff --git a/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs b/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs index 667b115b2..1dfb37ad0 100644 --- a/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs +++ b/src/runtime/engine/Inno.Runtime/Hosting/SessionLogSink.cs @@ -16,7 +16,7 @@ ILogSink sink m_sink = sink; } - /// + /// public void Receive(LogEntry entry) { if (entry.sessionId == m_sessionId) @@ -25,7 +25,7 @@ public void Receive(LogEntry entry) } } - /// + /// public void Dispose() { if (m_sink is IDisposable owner) diff --git a/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs b/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs index 323f1505b..d5e64deea 100644 --- a/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs +++ b/src/runtime/engine/Inno.Runtime/Registration/StaticAssemblyCatalogSource.cs @@ -44,31 +44,28 @@ IReadOnlyList frameworkAssemblies m_sharedAssemblies = Array.AsReadOnly(m_assemblies.Concat(frameworkAssemblies).Distinct().ToArray()); } - /// + /// public event Action? changed { - add - { - ObjectDisposedException.ThrowIf(m_disposed, this); - } + add => ObjectDisposedException.ThrowIf(m_disposed, this); remove {} } - /// + /// public IReadOnlyList GetAssemblies() { ObjectDisposedException.ThrowIf(m_disposed, this); return m_assemblies; } - /// + /// public IReadOnlyList GetSharedAssemblies() { ObjectDisposedException.ThrowIf(m_disposed, this); return m_sharedAssemblies; } - /// + /// public bool IsFrameworkReference(string assemblyName) { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -76,7 +73,7 @@ public bool IsFrameworkReference(string assemblyName) return m_frameworkNames.Contains(assemblyName); } - /// + /// public bool IsFrameworkAssembly(Assembly assembly) { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -84,6 +81,6 @@ public bool IsFrameworkAssembly(Assembly assembly) return m_framework.Contains(assembly); } - /// + /// public void Dispose() => m_disposed = true; } diff --git a/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs b/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs index 5aaf28fa4..b768dfd77 100644 --- a/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs +++ b/src/runtime/engine/Inno.Runtime/Registration/StaticModuleSource.cs @@ -52,35 +52,35 @@ IReadOnlyList dependencies assemblies, assemblies.ToDictionary(static assembly => assembly, _ => scope) ); - upstreamModuleNames = Array.AsReadOnly(dependencies.ToArray()); - assemblyScopes = new ReadOnlyDictionary( + this.upstreamModuleNames = Array.AsReadOnly(dependencies.ToArray()); + this.assemblyScopes = new ReadOnlyDictionary( assemblies.ToDictionary(static assembly => assembly.GetName().Name!, _ => scope, StringComparer.OrdinalIgnoreCase) ); } - /// + /// public string moduleName => m_contribution.moduleName; - /// + /// public AssemblyDomain domain => m_contribution.domain; - /// + /// public AssemblyScope scope => m_contribution.scope; - /// + /// public bool collectible => false; - /// + /// public IReadOnlyList upstreamModuleNames { get; } - /// + /// public IReadOnlyDictionary assemblyScopes { get; } - /// + /// public IReadOnlyList GetAssemblyNames() => m_contribution.assemblies.Select(static assembly => assembly.GetName().Name!).ToArray(); - /// + /// public ModuleCatalogContribution Prepare(ModuleSourceContext context) { ArgumentNullException.ThrowIfNull(context); diff --git a/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs b/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs index 849d93c8b..ef61a4641 100644 --- a/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs +++ b/src/runtime/engine/Inno.Runtime/Registration/StaticTypeCatalogSource.cs @@ -82,19 +82,19 @@ public StaticTypeCatalogSource(IReadOnlyList> cata } } - /// + /// public IReadOnlyList GetTypes(Assembly assembly) => m_types.TryGetValue(assembly, out IReadOnlyList? types) ? types : throw new InvalidOperationException($"Linked assembly '{assembly.GetName().Name}' has no generated type catalog."); - /// + /// public TypeCatalogMetadata GetMetadata(Type type) => m_metadata.TryGetValue(type, out TypeCatalogMetadata? metadata) ? metadata : throw new InvalidOperationException($"Linked declaration '{type}' has no generated metadata."); - /// + /// public Type? ConstructGenericType( Type definition, IReadOnlyList arguments @@ -123,11 +123,11 @@ IReadOnlyList arguments ); } - /// + /// public bool CanCreateInstance(Type type) => m_factories.TryGetValue(type, out Func? factory) && factory is not null; - /// + /// public object CreateInstance(Type type) { if (!m_factories.TryGetValue(type, out Func? factory) || factory is null) @@ -165,7 +165,7 @@ private sealed class Registration : ITypeCatalogRegistrar private bool m_sealed; private readonly int m_ownerThread = Environment.CurrentManagedThreadId; - /// + /// public void Register( TypeCatalogMetadata metadata, Func? factory @@ -179,7 +179,7 @@ public void Register( factories.Add(metadata.type, factory); } - /// + /// public void RegisterFactory( Type type, Func factory @@ -195,7 +195,7 @@ Func factory factories.TryAdd(type, factory); } - /// + /// public void RejectGenericConstruction( Type definition, IReadOnlyList arguments diff --git a/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs b/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs index 950a8a514..cf3740b09 100644 --- a/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs +++ b/src/runtime/engine/Inno.Runtime/Subsystems/RuntimeSubsystemPipeline.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.ExceptionServices; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Extensibility.Reload; @@ -294,7 +295,7 @@ public void RenderFrame( } if (failures.Count == 1) { - System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failures[0]).Throw(); + ExceptionDispatchInfo.Capture(failures[0]).Throw(); } if (failures.Count > 1) { @@ -394,11 +395,11 @@ private static IRuntimeSubsystemFactory[] Order(IReadOnlyList incoming = factories.ToDictionary( static factory => factory.descriptor.id, factory => factory.descriptor.dependencies.Count(byId.ContainsKey) ); - var dependants = factories.ToDictionary( + Dictionary> dependants = factories.ToDictionary( static factory => factory.descriptor.id, static _ => new List() ); @@ -636,7 +637,7 @@ private sealed class FactorySnapshot : IRuntimeSubsystemFactory internal FactorySnapshot(IRuntimeSubsystemFactory factory) { m_factory = factory ?? throw new ArgumentNullException(nameof(factory)); - descriptor = factory.descriptor ?? throw new InvalidOperationException("A subsystem descriptor cannot be null."); + this.descriptor = factory.descriptor ?? throw new InvalidOperationException("A subsystem descriptor cannot be null."); } /// diff --git a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs index f2798f3d7..f8b1d742d 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeFactoryGenerator.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Text; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; namespace Inno.Runtime.Generators; @@ -12,10 +13,12 @@ namespace Inno.Runtime.Generators; [Generator] public sealed class RuntimeFactoryGenerator : IIncrementalGenerator { - /// + /// public void Initialize(IncrementalGeneratorInitializationContext context) { - var inputs = context.CompilationProvider.Combine(context.AnalyzerConfigOptionsProvider); + IncrementalValueProvider<(Compilation Left, AnalyzerConfigOptionsProvider Right)> inputs = context.CompilationProvider.Combine( + context.AnalyzerConfigOptionsProvider + ); context.RegisterSourceOutput(inputs, static ( output, input @@ -67,14 +70,14 @@ Compilation compilation .Append("internal static class PlayerMetadataComposition\n{\n") .Append(" internal static global::Inno.Extensibility.Modules.IAssemblyCatalogSource CreateModules() =>\n") .Append(" new global::Inno.Runtime.StaticAssemblyCatalogSource([\n"); - foreach (var catalog in catalogs.Where(static catalog => catalog.host)) + foreach ((string name, bool host) catalog in catalogs.Where(static catalog => catalog.host)) { code.Append(" global::").Append(catalog.name).Append(".Generated.RuntimeModuleCatalog.assembly,\n"); } code.Append(" ], [typeof(object).Assembly]);\n\n") .Append(" internal static global::Inno.Extensibility.Types.ITypeCatalogSource CreateTypes() =>\n") .Append(" new global::Inno.Runtime.StaticTypeCatalogSource([\n"); - foreach (var catalog in catalogs) + foreach ((string name, bool host) catalog in catalogs) { code.Append(" global::").Append(catalog.name).Append(".Generated.RuntimeModuleCatalog.Register,\n"); } diff --git a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs index e4c8fff9d..13e7b4b88 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/Registration/RuntimeModuleCatalogGenerator.cs @@ -20,12 +20,10 @@ public sealed class RuntimeModuleCatalogGenerator : IIncrementalGenerator /// The compiler's incremental registration boundary. /// public void Initialize(IncrementalGeneratorInitializationContext context) - { - context.RegisterSourceOutput(context.CompilationProvider, static ( + => context.RegisterSourceOutput(context.CompilationProvider, static ( output, compilation ) => Generate(output, compilation)); - } private static void Generate( SourceProductionContext output, @@ -93,7 +91,10 @@ Compilation compilation .Append(factory) .Append(");\n"); } - var constructions = RuntimeTypeCatalogGenerator.Analyze(compilation, output); + ( + IReadOnlyList factories, + IReadOnlyList<(INamedTypeSymbol definition, ITypeSymbol[] arguments)> rejected + ) constructions = RuntimeTypeCatalogGenerator.Analyze(compilation, output); foreach (INamedTypeSymbol type in constructions.factories.Where(static type => ( !CanConstruct(type) && GetBaseTypes(type).Any(static parent => ( @@ -125,7 +126,7 @@ Compilation compilation } code.Append(" register.RegisterFactory(typeof(").Append(name).Append("), ").Append(factory).Append(");\n"); } - foreach (var rejection in constructions.rejected) + foreach ((INamedTypeSymbol definition, ITypeSymbol[] arguments) rejection in constructions.rejected) { code.Append(" register.RejectGenericConstruction(typeof(") .Append(GetTypeName(rejection.definition)) @@ -157,7 +158,7 @@ Compilation compilation foreach (INamedTypeSymbol type in types) { code.Append(" ") - .Append(Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true)) + .Append(SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true)) .Append(" => typeof(") .Append(GetTypeName(type)) .Append("),\n"); @@ -351,7 +352,7 @@ private static string FormatTypeReference(INamedTypeSymbol type) && type.ContainingAssembly.Name.StartsWith("Inno.", StringComparison.Ordinal) ) { return "global::" + type.ContainingAssembly.Name + ".Generated.RuntimeModuleCatalog.ResolveType(" - + Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true) + ")"; + + SymbolDisplay.FormatLiteral(GetMetadataName(type), quote: true) + ")"; } return "typeof(" + GetTypeName(type) + ")"; } @@ -383,7 +384,7 @@ private static string FormatOverrides(INamedTypeSymbol type) root = root.OverriddenMethod; } declarations.Add( - "(" + Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(method.Name, quote: true) + "(" + SymbolDisplay.FormatLiteral(method.Name, quote: true) + ", typeof(" + GetTypeName(root.ContainingType) + "))" ); } @@ -459,7 +460,7 @@ private static string FormatConstant(TypedConstant constant) return "new " + array.ElementType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + "[] { " + string.Join(", ", constant.Values.Select(FormatConstant)) + " }"; } - string literal = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatPrimitive( + string literal = SymbolDisplay.FormatPrimitive( constant.Value!, quoteStrings: true, useHexadecimalNumbers: false diff --git a/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs b/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs index a701e57d6..1ddadfacd 100644 --- a/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs +++ b/src/runtime/generators/Inno.Runtime.Generators/RuntimeSubsystemGenerator.cs @@ -31,7 +31,7 @@ public sealed class RuntimeSubsystemGenerator : IIncrementalGenerator /// public void Initialize(IncrementalGeneratorInitializationContext context) { - var registrations = context.SyntaxProvider.ForAttributeWithMetadataName( + IncrementalValueProvider> registrations = context.SyntaxProvider.ForAttributeWithMetadataName( "Inno.Runtime.Contracts.RuntimeSubsystemRegistrationAttribute", static ( node, @@ -45,7 +45,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) entry.Attributes[0].ConstructorArguments[0].Value as string ?? string.Empty ) ).Collect(); - var catalogs = context.SyntaxProvider.ForAttributeWithMetadataName( + IncrementalValueProvider> catalogs = context.SyntaxProvider.ForAttributeWithMetadataName( "Inno.Runtime.Contracts.RuntimeSubsystemCatalogAttribute", static ( node, @@ -106,7 +106,7 @@ ImmutableArray registrations )) .OrderBy(static registration => registration.id, StringComparer.Ordinal) .ToArray(); - var duplicate = matches.GroupBy(static registration => registration.id, StringComparer.Ordinal) + IGrouping duplicate = matches.GroupBy(static registration => registration.id, StringComparer.Ordinal) .FirstOrDefault(static group => group.Count() > 1); if (matches.Length == 0 || duplicate is not null) { @@ -160,7 +160,7 @@ duplicate is null code.Append(" };\n"); for (int index = 0; index < matches.Length; index++) { - string id = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(matches[index].id, true); + string id = SymbolDisplay.FormatLiteral(matches[index].id, true); code.Append(" if (factories[") .Append(index) .Append("].descriptor.id.value != ") diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs index 4d638e93d..769b398ca 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginCatalog.cs @@ -96,7 +96,7 @@ public void Activate(PluginScanResult result) { ArgumentNullException.ThrowIfNull(result); PluginCandidate[] ordered = PluginSourceService.GetActivatableCandidates(result).ToArray(); - var bySource = ordered.ToFrozenDictionary( + FrozenDictionary bySource = ordered.ToFrozenDictionary( static candidate => candidate.sourceMount.id, static candidate => candidate ); diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs index 9c63b6911..e6a5a122c 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginEnvironment.cs @@ -814,7 +814,7 @@ PluginScanResult candidate private string ComputeActiveFingerprint(PluginScanResult scan) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (PluginCandidate candidate in PluginSourceService.GetActivatableCandidates(scan)) { hash.AppendData(Encoding.UTF8.GetBytes(candidate.manifest.pluginId)); @@ -826,22 +826,22 @@ private string ComputeActiveFingerprint(PluginScanResult scan) private static string ComputeInstallationFingerprint(string pluginRoot) { Directory.CreateDirectory(pluginRoot); - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); string[] paths = Directory.EnumerateFileSystemEntries(pluginRoot, "*", SearchOption.TopDirectoryOnly) .ToArray(); foreach (string path in paths.OrderBy(static value => value, StringComparer.OrdinalIgnoreCase)) { - FileAttributes attributes = System.IO.File.GetAttributes(path); + FileAttributes attributes = File.GetAttributes(path); string relative = Path.GetRelativePath(pluginRoot, path).Replace('\\', '/'); hash.AppendData(Encoding.UTF8.GetBytes(relative)); hash.AppendData(BitConverter.GetBytes((int)attributes)); if ((attributes & FileAttributes.Directory) != 0) { - DirectoryInfo directory = new(path); + var directory = new DirectoryInfo(path); hash.AppendData(BitConverter.GetBytes(directory.LastWriteTimeUtc.Ticks)); continue; } - FileInfo file = new(path); + var file = new FileInfo(path); hash.AppendData(BitConverter.GetBytes(file.Length)); hash.AppendData(BitConverter.GetBytes(file.LastWriteTimeUtc.Ticks)); } diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs index c4a06989c..5b111a92d 100644 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceService.cs @@ -131,8 +131,7 @@ public static IReadOnlyList GetActivatableCandidates(PluginScan } private IEnumerable DiscoverPackages() - { - return Directory + => Directory .EnumerateFiles(m_pluginRoot, "*", SearchOption.TopDirectoryOnly) .Where(static path => string.Equals( Path.GetExtension(path), @@ -140,11 +139,9 @@ private IEnumerable DiscoverPackages() StringComparison.OrdinalIgnoreCase )) .OrderBy(static path => path, StringComparer.OrdinalIgnoreCase); - } private IEnumerable DiscoverUnsupportedSources() - { - return Directory + => Directory .EnumerateFileSystemEntries(m_pluginRoot, "*", SearchOption.TopDirectoryOnly) .Where(path => { @@ -157,7 +154,6 @@ private IEnumerable DiscoverUnsupportedSources() || !string.Equals(Path.GetExtension(path), ".iplugin", StringComparison.OrdinalIgnoreCase); }) .OrderBy(static path => path, StringComparer.OrdinalIgnoreCase); - } private IReadOnlyList ValidatePackage(string packagePath) { @@ -559,7 +555,7 @@ string destinationRoot } Directory.CreateDirectory(Path.GetDirectoryName(target)!); using Stream source = item.entry.Open(); - using FileStream output = new(target, FileMode.CreateNew, FileAccess.Write, FileShare.None); + using var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None); source.CopyTo(output); } @@ -617,7 +613,7 @@ string destinationRoot throw new InvalidDataException($"Plugin cache snapshot '{destinationRoot}' has an invalid length for '{item.path}'."); } using Stream expected = item.entry.Open(); - using FileStream materialized = new(physical, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + using var materialized = new FileStream(physical, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); if (!SHA256.HashData(materialized).AsSpan().SequenceEqual(SHA256.HashData(expected))) { throw new InvalidDataException($"Plugin cache snapshot '{destinationRoot}' has invalid bytes for '{item.path}'."); @@ -641,7 +637,7 @@ string relativePath private static string ComputePackageContentHash(IReadOnlyList entries) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (ValidatedPackageEntry item in entries.OrderBy(static entry => entry.path, StringComparer.Ordinal)) { AppendPath(hash, item.path); @@ -670,7 +666,7 @@ private static void AppendStream( IncrementalHash hash, Stream stream ) { - byte[] buffer = new byte[64 * 1024]; + var buffer = new byte[64 * 1024]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { diff --git a/src/runtime/plugins/Inno.Plugins/PluginManifest.cs b/src/runtime/plugins/Inno.Plugins/PluginManifest.cs index fdb2e32c1..8e389b0e7 100644 --- a/src/runtime/plugins/Inno.Plugins/PluginManifest.cs +++ b/src/runtime/plugins/Inno.Plugins/PluginManifest.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using Inno.Assets; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -63,13 +64,13 @@ public void Validate() { try { - _ = new Inno.Assets.AssetSourceId(pluginId); + _ = new AssetSourceId(pluginId); } catch (ArgumentException exception) { throw new InvalidDataException("Plugin.inno contains an invalid Plugin ID.", exception); } - if (string.Equals(pluginId, Inno.Assets.AssetSourceId.project.value, StringComparison.Ordinal)) + if (string.Equals(pluginId, AssetSourceId.project.value, StringComparison.Ordinal)) { throw new InvalidDataException("Plugin ID 'project' is reserved by the writable project source."); } @@ -127,7 +128,7 @@ string name } foreach (string value in values) { - _ = new Inno.Assets.AssetSourceId(value); + _ = new AssetSourceId(value); } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs index 869bb76d0..f9b617fff 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/FrameworkReferenceResolver.cs @@ -20,7 +20,7 @@ internal static ScriptCompilationEnvironment Resolve( ScriptCompilationInputs inputs = provider.Capture(cancellationToken); var references = new List(); var names = new HashSet(StringComparer.OrdinalIgnoreCase) { "System.Private.CoreLib" }; - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (string identity in new[] { ScriptCompilationEnvironment.C_TARGET_FRAMEWORK, diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs index 08cdb1017..5794c9cc3 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/LogicalScriptingApiAnalyzer.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -13,7 +14,7 @@ namespace Inno.Scripting.Compiler; /// Enforces logical scripting namespaces and rejects direct implementation namespace access. /// [DiagnosticAnalyzer(LanguageNames.CSharp)] -[System.Diagnostics.CodeAnalysis.SuppressMessage( +[SuppressMessage( "MicrosoftCodeAnalysisCorrectness", "RS1041", Justification = "This analyzer is loaded only by the .NET 10 SDK compiler shared by authoring and generated IDE projects." @@ -66,7 +67,7 @@ public sealed class LogicalScriptingApiAnalyzer : DiagnosticAnalyzer /// Gets the complete compiler diagnostic set enforced by this analyzer. /// public override ImmutableArray SupportedDiagnostics - => ImmutableArray.Create(s_directImplementationNamespace, s_missingLogicalNamespace, s_compilationWideUsing); + => [s_directImplementationNamespace, s_missingLogicalNamespace, s_compilationWideUsing]; /// /// Initializes owned resources and establishes the instance's active lifetime. @@ -105,7 +106,7 @@ public override void Initialize(AnalysisContext context) private static void AnalyzeCompilationWideUsing(SyntaxNodeAnalysisContext context) { - var usingDirective = (UsingDirectiveSyntax)context.Node; + UsingDirectiveSyntax usingDirective = (UsingDirectiveSyntax)context.Node; if (usingDirective.GlobalKeyword == default) { return; @@ -117,7 +118,7 @@ private static void AnalyzeUsing( SyntaxNodeAnalysisContext context, ScriptApiMap map ) { - var usingDirective = (UsingDirectiveSyntax)context.Node; + UsingDirectiveSyntax usingDirective = (UsingDirectiveSyntax)context.Node; if (usingDirective.Name is null) { return; diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs index 8facb6370..518ad406f 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiArtifactCache.cs @@ -18,7 +18,7 @@ internal static int Collect( { return 0; } - var protectedPaths = protectedDirectories + HashSet protectedPaths = protectedDirectories .Where(static path => !string.IsNullOrWhiteSpace(path)) .Select(static path => Path.GetFullPath(path!)) .ToHashSet(StringComparer.OrdinalIgnoreCase); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs index 735c7aee3..5ae4bde95 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Reflection; using System.Runtime.Loader; +using Microsoft.CodeAnalysis.CSharp; using Inno.Scripting.Api; namespace Inno.Scripting.Compiler; @@ -58,7 +59,7 @@ internal static ScriptApiProfile Build(bool includeEditor) && AssemblyLoadContext.GetLoadContext(assembly) == AssemblyLoadContext.Default )) .ToArray(); - var byName = loaded + Dictionary byName = loaded .Where(static assembly => assembly.GetName().Name is not null) .GroupBy(static assembly => assembly.GetName().Name!, StringComparer.OrdinalIgnoreCase) .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.OrdinalIgnoreCase); @@ -172,7 +173,7 @@ IReadOnlyList mappings { throw new InvalidOperationException($"Script API type '{type.FullName}' must be public."); } - if (!Microsoft.CodeAnalysis.CSharp.SyntaxFacts.IsValidIdentifier(export.name)) + if (!SyntaxFacts.IsValidIdentifier(export.name)) { throw new InvalidOperationException( $"Script API name '{export.name}' for type '{type.FullName}' is not a valid C# identifier." @@ -299,7 +300,7 @@ private static void LoadReferencedInnoAssemblies() && AssemblyLoadContext.GetLoadContext(assembly) == AssemblyLoadContext.Default )) .ToArray(); - var byName = loaded + Dictionary byName = loaded .Where(static assembly => assembly.GetName().Name is not null) .GroupBy(static assembly => assembly.GetName().Name!, StringComparer.OrdinalIgnoreCase) .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.OrdinalIgnoreCase); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs index 33645247e..b3bfeaffd 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiDocumentationBuilder.cs @@ -39,7 +39,7 @@ internal static Inputs Capture(IReadOnlyList exports) internal static void Verify(Inputs inputs) { - foreach (var input in inputs.documents) + foreach (KeyValuePair input in inputs.documents) { bool exists = File.Exists(input.Key); if (exists != (input.Value is not null) || exists && !File.ReadAllBytes(input.Key).AsSpan().SequenceEqual(input.Value)) @@ -126,7 +126,7 @@ Inputs inputs // Origin data is emitted from the same resolved exports as the logical facade. // Documentation consumers must still select members from the actual reference assembly. - var origins = exports.Select(export => + IOrderedEnumerable origins = exports.Select(export => { string sourceId = "T:" + GetDocumentationTypeName(export.type); string logicalId = sourceId; @@ -222,9 +222,9 @@ private static void RewriteDocumentationIdentities( private static (string source, string target)[] CreateIdentityReplacements( IReadOnlyDictionary namespaceMappings, IReadOnlyList typeMappings - ) { + ) => // Freeze the ordered rewrite once per document; unchanged names need no replacement. - return namespaceMappings + namespaceMappings .OrderByDescending(static pair => pair.Key.Length) .Select(static pair => (source: pair.Key, target: pair.Value)) .Concat( @@ -236,5 +236,4 @@ IReadOnlyList typeMappings ) .Where(static replacement => !string.Equals(replacement.source, replacement.target, StringComparison.Ordinal)) .ToArray(); - } } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs index 2d876a588..c63b28aa1 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs @@ -374,7 +374,7 @@ private static string CreateFingerprint(ScriptApiProfile profile) HashSet exportedTypes = allExports .Select(static export => export.type) .ToHashSet(); - var builder = new StringBuilder("Inno.ScriptApi.PublicContract") + StringBuilder builder = new StringBuilder("Inno.ScriptApi.PublicContract") .Append('|') .Append(profile.name); foreach (ScriptApiAssembly export in profile.exports diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs index 6740ac176..7c87034a3 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiStubSourceBuilder.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.Linq; using System.Reflection; +using System.Runtime.CompilerServices; using System.Text; using Inno.Scripting.Api; @@ -133,7 +134,7 @@ Type type } else { - if (type.IsDefined(typeof(System.Runtime.CompilerServices.IsReadOnlyAttribute), inherit: false)) + if (type.IsDefined(typeof(IsReadOnlyAttribute), inherit: false)) { builder.Append("readonly "); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs index 37fd36422..bfb5f6f9b 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiUsingRewriter.cs @@ -169,7 +169,7 @@ private IReadOnlyDictionary CreateSimpleTypeMappings( SyntaxList usings, IReadOnlyDictionary inherited ) { - var candidates = inherited + Dictionary candidates = inherited .ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.Ordinal); var ambiguous = new HashSet(StringComparer.Ordinal); foreach (UsingDirectiveSyntax usingDirective in usings) diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs index bc371de7b..f51cc5996 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptArtifactCache.cs @@ -21,7 +21,7 @@ internal ScriptArtifactCache(string root) internal int Collect(IEnumerable protectedDirectories) { - var protectedPaths = protectedDirectories + HashSet protectedPaths = protectedDirectories .Where(static value => !string.IsNullOrWhiteSpace(value)) .Select(static value => Path.GetFullPath(value!)) .ToHashSet(StringComparer.OrdinalIgnoreCase); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs index c9c6fb29a..d7c9bd87e 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptAuthoringAnnotationRewriter.cs @@ -40,8 +40,8 @@ CancellationToken cancellationToken .Select(export => export.type) .Distinct() .ToArray(); - var names = types.Select(type => type.FullName!).ToHashSet(StringComparer.Ordinal); - var namespaces = types.Select(type => type.Namespace!).ToHashSet(StringComparer.Ordinal); + HashSet names = types.Select(type => type.FullName!).ToHashSet(StringComparer.Ordinal); + HashSet namespaces = types.Select(type => type.Namespace!).ToHashSet(StringComparer.Ordinal); return compilation.SyntaxTrees.Select(tree => { var rewriter = new ScriptAuthoringAnnotationRewriter(compilation.GetSemanticModel(tree), names, namespaces); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs index 18f3e40d5..b7004c3ef 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilationResult.cs @@ -24,7 +24,7 @@ internal ScriptCompilationResult( this.diagnostics = diagnostics; this.outputDirectory = outputDirectory; this.moduleDeployments = Array.AsReadOnly((moduleDeployments ?? []).ToArray()); - runtimeAssemblyPaths = this.moduleDeployments + this.runtimeAssemblyPaths = this.moduleDeployments .SelectMany(static request => new[] { request.mainAssemblyPath }.Concat(request.preloadAssemblyPaths) .Where(path => ( diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs index 875e17d07..b7f37d030 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerCacheSerialization.cs @@ -8,8 +8,8 @@ namespace Inno.Scripting.Compiler; internal static class ScriptCompilerCacheSerialization { - private const int C_DIAGNOSTIC_MAGIC = 0x494E4447; - private const int C_TYPE_MANIFEST_MAGIC = 0x494E544D; + private const int C_DIAGNOSTIC_MAGIC = 0x494E_4447; + private const int C_TYPE_MANIFEST_MAGIC = 0x494E_544D; private const int C_MAX_ENTRY_COUNT = 1_000_000; internal static byte[] EncodeDiagnostics(IEnumerable diagnostics) @@ -17,8 +17,8 @@ internal static byte[] EncodeDiagnostics(IEnumerable diagnosti ArgumentNullException.ThrowIfNull(diagnostics); ScriptDiagnostic[] entries = diagnostics as ScriptDiagnostic[] ?? [.. diagnostics]; - using MemoryStream stream = new(); - using BinaryWriter writer = new(stream, Encoding.UTF8, leaveOpen: true); + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); writer.Write(C_DIAGNOSTIC_MAGIC); writer.Write(entries.Length); foreach (ScriptDiagnostic diagnostic in entries) @@ -42,11 +42,11 @@ internal static byte[] EncodeDiagnostics(IEnumerable diagnosti internal static ScriptDiagnostic[] DecodeDiagnostics(ReadOnlySpan bytes) { - using MemoryStream stream = new(bytes.ToArray(), writable: false); - using BinaryReader reader = new(stream, Encoding.UTF8, leaveOpen: false); + using var stream = new MemoryStream(bytes.ToArray(), writable: false); + using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); ValidateMagic(reader, C_DIAGNOSTIC_MAGIC, "script diagnostic cache"); int count = ReadCount(reader, "diagnostic"); - ScriptDiagnostic[] diagnostics = new ScriptDiagnostic[count]; + var diagnostics = new ScriptDiagnostic[count]; for (int index = 0; index < count; index++) { string id = reader.ReadString(); @@ -65,8 +65,8 @@ internal static ScriptDiagnostic[] DecodeDiagnostics(ReadOnlySpan bytes) internal static byte[] EncodeTypeManifest(ScriptTypeManifest manifest) { ArgumentNullException.ThrowIfNull(manifest); - using MemoryStream stream = new(); - using BinaryWriter writer = new(stream, Encoding.UTF8, leaveOpen: true); + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); writer.Write(C_TYPE_MANIFEST_MAGIC); writer.Write(manifest.assemblyName); writer.Write(manifest.types.Count); @@ -89,12 +89,12 @@ internal static byte[] EncodeTypeManifest(ScriptTypeManifest manifest) internal static ScriptTypeManifest DecodeTypeManifest(ReadOnlySpan bytes) { - using MemoryStream stream = new(bytes.ToArray(), writable: false); - using BinaryReader reader = new(stream, Encoding.UTF8, leaveOpen: false); + using var stream = new MemoryStream(bytes.ToArray(), writable: false); + using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); ValidateMagic(reader, C_TYPE_MANIFEST_MAGIC, "script type manifest cache"); string assemblyName = reader.ReadString(); int count = ReadCount(reader, "type manifest"); - ScriptTypeManifestEntry[] types = new ScriptTypeManifestEntry[count]; + var types = new ScriptTypeManifestEntry[count]; for (int index = 0; index < count; index++) { types[index] = new ScriptTypeManifestEntry( diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs index 0ede839c4..14c666b29 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptCompilerEngine.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Reflection; +using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading; @@ -22,6 +23,8 @@ using Inno.Plugins.Authoring; using Inno.Runtime.Generators; +using EngineSeverity = Inno.Core.Diagnostics.DiagnosticSeverity; + namespace Inno.Scripting.Compiler; internal static class ScriptCompilerEngine @@ -335,7 +338,7 @@ CancellationToken cancellationToken validationReferences[referencePath] = MetadataReference.CreateFromFile(referencePath); } - var validationCompilation = CSharpCompilation.Create( + CSharpCompilation validationCompilation = CSharpCompilation.Create( assemblyName, syntaxTrees, validationReferences.Values, @@ -360,8 +363,8 @@ CancellationToken cancellationToken assemblyName + ScriptApiMapBuilder.C_FILE_EXTENSION, ScriptApiMapBuilder.Build(api) ); - var analyzerOptions = new AnalyzerOptions(ImmutableArray.Create(apiMapFile)); - var analyzers = ImmutableArray.Create(new LogicalScriptingApiAnalyzer()); + var analyzerOptions = new AnalyzerOptions([apiMapFile]); + ImmutableArray analyzers = [new LogicalScriptingApiAnalyzer()]; progress.Begin($"Validating the {assemblyName} API surface..."); ImmutableArray analyzerDiagnostics = await validationCompilation .WithAnalyzers(analyzers, analyzerOptions) @@ -393,7 +396,12 @@ CancellationToken cancellationToken { logicalReferences[referencePath] = MetadataReference.CreateFromFile(referencePath); } - var logicalBindings = CSharpCompilation.Create(assemblyName, syntaxTrees, logicalReferences.Values, validationCompilation.Options); + CSharpCompilation logicalBindings = CSharpCompilation.Create( + assemblyName, + syntaxTrees, + logicalReferences.Values, + validationCompilation.Options + ); SyntaxTree[] runtimeTrees = syntaxTrees .Select(tree => CSharpSyntaxTree.Create( (CSharpSyntaxNode)usingRewriter.Visit( @@ -407,7 +415,7 @@ CancellationToken cancellationToken Encoding.UTF8 )) .ToArray(); - var contractCompilation = CSharpCompilation.Create( + CSharpCompilation contractCompilation = CSharpCompilation.Create( assemblyName, runtimeTrees, validationReferences.Values, @@ -426,7 +434,7 @@ CancellationToken cancellationToken { // User code has passed the same trimmed contract used by IDE projects. // Generated registration alone needs the owning assemblies' implementation metadata. - var implementationReferences = platformReferences.ToDictionary( + Dictionary implementationReferences = platformReferences.ToDictionary( static reference => reference.Display!, StringComparer.OrdinalIgnoreCase ); @@ -453,7 +461,7 @@ CancellationToken cancellationToken } runtimeReferences = targetReferences.Values; } - var runtimeCompilation = CSharpCompilation.Create( + CSharpCompilation runtimeCompilation = CSharpCompilation.Create( assemblyName, runtimeTrees, runtimeReferences, @@ -481,9 +489,7 @@ CancellationToken cancellationToken runtimeCompilation = runtimeCompilation.AddSyntaxTrees(mappingTree); } progress.Complete($"Resolved {assemblyName} script type identities."); - if (typeAnalysis.diagnostics.Any(static diagnostic => ( - diagnostic.severity == Inno.Core.Diagnostics.DiagnosticSeverity.Error - )) + if (typeAnalysis.diagnostics.Any(static diagnostic => (diagnostic.severity == EngineSeverity.Error)) ) { return new CompilationResult(false, typeAnalysis.diagnostics); } @@ -614,12 +620,12 @@ private static string ComputeAssemblyBuildKey( IReadOnlyDictionary dependencyKeys, IReadOnlyList defines ) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); AppendHash(hash, "Inno.ScriptAssemblyArtifact.SourceOwned"); AppendHash(hash, typeof(ScriptCompilerEngine).Module.ModuleVersionId.ToString("N")); AppendHash(hash, typeof(RuntimeModuleCatalogGenerator).Module.ModuleVersionId.ToString("N")); AppendHash(hash, typeof(SerializationConverterGenerator).Module.ModuleVersionId.ToString("N")); - AppendHash(hash, System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription); + AppendHash(hash, RuntimeInformation.FrameworkDescription); AppendHash(hash, Environment.Version.ToString()); AppendHash(hash, assembly.name); AppendHash(hash, assembly.scope.ToString()); @@ -667,7 +673,7 @@ private static string ComputeGenerationBuildKey( ScriptSourceSet sources, IReadOnlyDictionary assemblyKeys ) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); AppendHash(hash, "Inno.ScriptGenerationArtifact.Incremental"); foreach (ScriptAssemblyInput assembly in sources.assemblies) { @@ -910,7 +916,7 @@ private sealed class TemporaryDirectory : IDisposable internal TemporaryDirectory(string root) { Directory.CreateDirectory(root); - path = Path.Combine(root, Guid.NewGuid().ToString("N")); + this.path = Path.Combine(root, Guid.NewGuid().ToString("N")); Directory.CreateDirectory(path); } @@ -1070,9 +1076,9 @@ private static ScriptDiagnostic ToDiagnostic(Diagnostic diagnostic) diagnostic.Id, diagnostic.Severity switch { - DiagnosticSeverity.Error => Inno.Core.Diagnostics.DiagnosticSeverity.Error, - DiagnosticSeverity.Warning => Inno.Core.Diagnostics.DiagnosticSeverity.Warning, - _ => Inno.Core.Diagnostics.DiagnosticSeverity.Info + DiagnosticSeverity.Error => EngineSeverity.Error, + DiagnosticSeverity.Warning => EngineSeverity.Warning, + _ => EngineSeverity.Info }, diagnostic.GetMessage(), string.IsNullOrWhiteSpace(location.Path) ? null : location.Path, @@ -1094,7 +1100,7 @@ internal InMemoryAdditionalText( string path, string text ) { - Path = path; + this.Path = path; m_text = SourceText.From(text, Encoding.UTF8); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs index d1dc0854b..1cc02c451 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs @@ -38,7 +38,7 @@ internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) } var identities = new HashSet(StringComparer.OrdinalIgnoreCase); - using var fingerprint = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash fingerprint = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); Append(fingerprint, "Inno.ScriptDeploymentReferences"); foreach (string path in paths) { diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs index 059b4deee..ff8aee5c0 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptSourceSet.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Security.Cryptography; using System.Text; using Inno.Assets; using Inno.Assets.Pipeline; @@ -271,7 +272,7 @@ AssetPipeline assets using ArtifactLease lease = candidateAssets is null ? assets.AcquireArtifact(info.persistentId, "source") : candidateAssets.AcquireArtifact(info.persistentId, "source"); - using StreamReader reader = new(lease.OpenRead(), Encoding.UTF8, detectEncodingFromByteOrderMarks: true); + using var reader = new StreamReader(lease.OpenRead(), Encoding.UTF8, detectEncodingFromByteOrderMarks: true); return new ScriptSourceInput( entry.assetPath, mount.Resolve(entry.assetPath.localPath), @@ -295,7 +296,7 @@ private static string ComputeDefinitionHash(ScriptAssemblyDefinitionAsset asset) .Concat(asset.references.OrderBy(static value => value, StringComparer.Ordinal)) .Concat(asset.defines.OrderBy(static value => value, StringComparer.Ordinal)) ); - return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(normalized))); + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(normalized))); } private static void ValidateManifestDefinitions( diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs index 57b198103..8ffec956c 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeAnalyzer.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; using System.Threading; @@ -7,6 +8,8 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using EngineSeverity = Inno.Core.Diagnostics.DiagnosticSeverity; + namespace Inno.Scripting.Compiler; internal static class ScriptTypeAnalyzer @@ -20,7 +23,10 @@ internal static ScriptTypeAnalysisResult Analyze( IReadOnlyDictionary attachableTypes, CancellationToken cancellationToken ) { - var sourcesByPath = sources.ToDictionary(static source => source.sourcePath, StringComparer.OrdinalIgnoreCase); + Dictionary sourcesByPath = sources.ToDictionary( + static source => source.sourcePath, + StringComparer.OrdinalIgnoreCase + ); var discovered = new Dictionary(SymbolEqualityComparer.Default); foreach (SyntaxTree tree in compilation.SyntaxTrees) { @@ -54,7 +60,7 @@ CancellationToken cancellationToken var diagnostics = new List(); var manifestEntries = new List(); var mappings = new List(); - var implicitTypesBySource = discovered.Values + Dictionary implicitTypesBySource = discovered.Values .Where(static type => GetExplicitStableTypeId(type.symbol) is null) .SelectMany(static type => type.declarations.Select(declaration => (declaration.source.persistentId, type))) .GroupBy(static value => value.persistentId) @@ -78,7 +84,7 @@ CancellationToken cancellationToken diagnostics.Add( CreateDiagnostic( "INNO2000", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, + EngineSeverity.Error, $"Type '{typeName}' has invalid StableTypeId '{explicitIdValue}'.", declaration ) @@ -110,7 +116,7 @@ CancellationToken cancellationToken diagnostics.Add( CreateDiagnostic( "INNO2003", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, + EngineSeverity.Error, $"Partial type '{typeName}' has more than one source file matching its type name. " + "Keep one canonical source or add an explicit StableTypeId.", matchingDeclarations[0] @@ -130,7 +136,7 @@ CancellationToken cancellationToken diagnostics.Add( CreateDiagnostic( "INNO2002", - Inno.Core.Diagnostics.DiagnosticSeverity.Warning, + EngineSeverity.Warning, $"Attachable type '{typeName}' does not match its canonical script file name. " + "Its source identity is preserved, but matching names are recommended.", canonical @@ -143,7 +149,7 @@ CancellationToken cancellationToken diagnostics.Add( CreateDiagnostic( "INNO2001", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, + EngineSeverity.Error, $"Attachable type '{typeName}' has no unambiguous canonical script source. " + "Move it to a matching file or add an explicit StableTypeId.", declaration @@ -173,7 +179,7 @@ CancellationToken cancellationToken diagnostics.Add( new ScriptDiagnostic( "INNO2004", - Inno.Core.Diagnostics.DiagnosticSeverity.Error, + EngineSeverity.Error, $"Script source '{entry.sourcePath}' owns more than one attachable type identity: " + string.Join(", ", conflicting.Select(static value => value.typeName)) + ". Keep one canonical type or add explicit StableTypeId attributes.", @@ -250,7 +256,7 @@ private static string GetMetadataTypeName(INamedTypeSymbol symbol) private static string GetCanonicalFileName(string sourcePath) { - string name = System.IO.Path.GetFileNameWithoutExtension(sourcePath); + string name = Path.GetFileNameWithoutExtension(sourcePath); return name.EndsWith(".editor", StringComparison.OrdinalIgnoreCase) ? name[..^".editor".Length] : name; @@ -289,7 +295,7 @@ bool canonicalSource private static ScriptDiagnostic CreateDiagnostic( string id, - Inno.Core.Diagnostics.DiagnosticSeverity severity, + EngineSeverity severity, string message, ScriptDeclaration declaration ) { diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs index e3a05e6b3..87ab7aba0 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptTypeIdentity.cs @@ -25,7 +25,7 @@ string name byte[] namespaceBytes = namespaceId.ToByteArray(); SwapGuidByteOrder(namespaceBytes); byte[] nameBytes = Encoding.UTF8.GetBytes(name); - byte[] data = new byte[namespaceBytes.Length + nameBytes.Length]; + var data = new byte[namespaceBytes.Length + nameBytes.Length]; Buffer.BlockCopy(namespaceBytes, 0, data, 0, namespaceBytes.Length); Buffer.BlockCopy(nameBytes, 0, data, namespaceBytes.Length, nameBytes.Length); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs index c66e12d20..d5a7dbb05 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/SerializablePropertyOrderRewriter.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; @@ -51,9 +52,7 @@ internal sealed class SerializablePropertyOrderRewriter : CSharpSyntaxRewriter /// The validated syntax node? that represents the completed operation. /// public override SyntaxNode? VisitFieldDeclaration(FieldDeclarationSyntax node) - { - return base.VisitFieldDeclaration(RewriteMember(node, node.AttributeLists)); - } + => base.VisitFieldDeclaration(RewriteMember(node, node.AttributeLists)); /// /// Visits property declaration in deterministic order using the supplied visitor. @@ -65,9 +64,7 @@ internal sealed class SerializablePropertyOrderRewriter : CSharpSyntaxRewriter /// The validated syntax node? that represents the completed operation. /// public override SyntaxNode? VisitPropertyDeclaration(PropertyDeclarationSyntax node) - { - return base.VisitPropertyDeclaration(RewriteMember(node, node.AttributeLists)); - } + => base.VisitPropertyDeclaration(RewriteMember(node, node.AttributeLists)); private TMember RewriteMember( TMember member, @@ -115,23 +112,19 @@ out AttributeSyntax result } private static bool HasExplicitOrder(AttributeSyntax attribute) - { - return attribute.ArgumentList?.Arguments.Any(static argument => - string.Equals( - argument.NameEquals?.Name.Identifier.ValueText, - C_ORDER_PROPERTY_NAME, - System.StringComparison.Ordinal - )) == true; - } + => attribute.ArgumentList?.Arguments.Any(static argument => + string.Equals( + argument.NameEquals?.Name.Identifier.ValueText, + C_ORDER_PROPERTY_NAME, + StringComparison.Ordinal + )) == true; private static string GetRightmostName(NameSyntax name) + => name switch { - return name switch - { - IdentifierNameSyntax identifier => identifier.Identifier.ValueText, - QualifiedNameSyntax qualified => GetRightmostName(qualified.Right), - AliasQualifiedNameSyntax alias => alias.Name.Identifier.ValueText, - _ => name.ToString() - }; - } + IdentifierNameSyntax identifier => identifier.Identifier.ValueText, + QualifiedNameSyntax qualified => GetRightmostName(qualified.Right), + AliasQualifiedNameSyntax alias => alias.Name.Identifier.ValueText, + _ => name.ToString() + }; } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs index c3cacff11..7178ad991 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs @@ -49,7 +49,7 @@ PluginEnvironment plugins ArgumentException.ThrowIfNullOrWhiteSpace(options.projectRootDirectory); m_options = new ScriptCompilerOptions { - projectRootDirectory = System.IO.Path.GetFullPath(options.projectRootDirectory), + projectRootDirectory = Path.GetFullPath(options.projectRootDirectory), compilationEnvironment = options.compilationEnvironment }; m_assets = assets; @@ -63,27 +63,21 @@ PluginEnvironment plugins /// /// Thrown when the authoring asset pipeline is not initialized. /// - public void GenerateProjectFiles() - { - ScriptProjectGenerator.Generate(m_options, m_assets, m_plugins); - } + public void GenerateProjectFiles() => ScriptProjectGenerator.Generate(m_options, m_assets, m_plugins); /// /// Compiles a complete runtime and editor candidate generation without activating it. /// - /// - /// Source discovery captures live inputs on the owner thread. Reference generation, Roslyn and - /// artifact writes run in the background; progress observers must accept callbacks from either thread. - /// Retain the source generation until the returned operation drains, including after cancellation. - /// Complete cache trees use Core IO atomic publication and replacement. A committed cache remains - /// valid if cleanup of its previous tree fails; compilation does not activate either generation. - /// /// /// Optional observer for monotonic compiler progress. /// /// /// The token that cancels compilation before an artifact generation is committed. /// + /// + /// Optional isolated authoring sources. Capture on its owner thread and keep its transaction + /// alive until compilation drains; null selects the current Plugin candidate or active sources. + /// /// /// The immutable diagnostics and artifacts produced by the compilation attempt. /// @@ -99,10 +93,13 @@ public void GenerateProjectFiles() /// /// Cache replacement and restoration both fail; the exception identifies the preserved previous tree. /// - /// - /// Optional isolated authoring sources. Capture on its owner thread and keep its transaction - /// alive until compilation drains; null selects the current Plugin candidate or active sources. - /// + /// + /// Source discovery captures live inputs on the owner thread. Reference generation, Roslyn and + /// artifact writes run in the background; progress observers must accept callbacks from either thread. + /// Retain the source generation until the returned operation drains, including after cancellation. + /// Complete cache trees use Core IO atomic publication and replacement. A committed cache remains + /// valid if cleanup of its previous tree fails; compilation does not activate either generation. + /// public ValueTask CompileAuthoringGenerationAsync( IProgress? progress = null, CancellationToken cancellationToken = default, @@ -126,11 +123,6 @@ progress is null /// /// Compiles only the runtime assembly closure required by a deployed Player and binds it to that Player runtime. /// - /// - /// Complete cache trees use Core IO atomic publication and replacement. Cancellation before commit - /// preserves the previous tree; cancellation does not undo a committed cache. Cleanup failure after - /// commit preserves the installed tree and remaining backup without activating a generation. - /// /// /// The verified Player Support Pack directory whose runtime assemblies will execute the emitted scripts. /// @@ -164,6 +156,11 @@ progress is null /// /// Cache replacement and restoration both fail; the exception identifies the preserved previous tree. /// + /// + /// Complete cache trees use Core IO atomic publication and replacement. Cancellation before commit + /// preserves the previous tree; cancellation does not undo a committed cache. Cleanup failure after + /// commit preserves the installed tree and remaining backup without activating a generation. + /// public ValueTask CompileRuntimeDeploymentAsync( string targetRuntimeDirectory, IProgress? progress = null, diff --git a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs index 6dce6ef24..8a50461d8 100644 --- a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs +++ b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs @@ -1,8 +1,11 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Reflection; using System.Runtime.ExceptionServices; using System.Security.Cryptography; +using System.Text; using System.Threading; using System.Threading.Tasks; using Inno.Assets; @@ -297,15 +300,15 @@ public void Start() /// /// Requests cancellation of the active compilation without changing the active script generation. /// + /// + /// The observed request; a stale cancellation is rejected. + /// /// /// when an active compilation received the request. /// /// /// Thrown after the manager has been disposed. /// - /// - /// The observed request; a stale cancellation is rejected. - /// public bool CancelCompilation(long operationId) { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -343,10 +346,7 @@ public bool CancelCompilation(long operationId) /// /// Thrown after the manager has been disposed. /// - public void RecompileScripting() - { - QueueReload(ScriptReloadRequest.Recompile); - } + public void RecompileScripting() => QueueReload(ScriptReloadRequest.Recompile); /// /// Queues a complete rebuild of both scripting load contexts while retaining the plugin generation. @@ -369,15 +369,15 @@ public void RecompileScripting() /// /// Starts a pending compilation after the configured quiet period has elapsed. /// - /// - /// The initial automatic request is immediately ready and does not observe the debounce duration. - /// /// /// The started compilation task, or when none was ready. /// /// /// when a pending compilation was started. /// + /// + /// The initial automatic request is immediately ready and does not observe the debounce duration. + /// public bool TryCompilePending(out Task? compilation) { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -926,8 +926,8 @@ private ReloadPlan SelectReloadPlan(PendingReload pending) return new ReloadPlan([], []); } - var compiled = pending.compilation.compiledAssemblyNames.ToHashSet(StringComparer.OrdinalIgnoreCase); - var selected = requests + HashSet compiled = pending.compilation.compiledAssemblyNames.ToHashSet(StringComparer.OrdinalIgnoreCase); + HashSet selected = requests .Where(request => ( GetOwnedAssemblyNames(request).Any(compiled.Contains) || !m_activeModuleFingerprints.TryGetValue(request.moduleName, out string? activeFingerprint) @@ -1009,18 +1009,18 @@ private void UpdateActiveFingerprints(ReloadPlan plan) private static IEnumerable GetOwnedAssemblyNames(ScriptModuleDeployment request) => new[] { request.mainAssemblyPath } .Concat(request.preloadAssemblyPaths) - .Select(static path => System.Reflection.AssemblyName.GetAssemblyName(path).Name ?? string.Empty); + .Select(static path => AssemblyName.GetAssemblyName(path).Name ?? string.Empty); private static string ComputeRequestFingerprint(ScriptModuleDeployment request) { - using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); foreach (string path in new[] { request.mainAssemblyPath } .Concat(request.preloadAssemblyPaths) .OrderBy(static value => value, StringComparer.OrdinalIgnoreCase) ) { - byte[] name = System.Text.Encoding.UTF8.GetBytes(System.IO.Path.GetFileName(path)); + byte[] name = Encoding.UTF8.GetBytes(Path.GetFileName(path)); hash.AppendData(name); - hash.AppendData(System.IO.File.ReadAllBytes(path)); + hash.AppendData(File.ReadAllBytes(path)); } return Convert.ToHexString(hash.GetHashAndReset()); } @@ -1053,7 +1053,7 @@ private void CompletePendingReload(PendingReload applied) static plugin => plugin.contentHash, StringComparer.Ordinal ); - var removedModuleNames = m_plugins.activePlugins + HashSet removedModuleNames = m_plugins.activePlugins .Where(static plugin => plugin.containsCode) .Where(plugin => ( !candidatePluginHashes.TryGetValue(plugin.manifest.pluginId, out string? candidateHash) diff --git a/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs b/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs index 778111b93..49dbce8ca 100644 --- a/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs +++ b/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs @@ -90,7 +90,7 @@ private static AudioClipMetadata ReadWav(ReadOnlySpan bytes) throw new InvalidDataException("The WAV format chunk is truncated."); } ushort format = BinaryPrimitives.ReadUInt16LittleEndian(bytes.Slice(chunkStart, 2)); - if (format is not 1 and not 3 and not 0xfffe) + if (format is not 1 and not 3 and not 0xFFFE) { throw new InvalidDataException($"The WAV format code '{format}' is not supported."); } @@ -127,7 +127,7 @@ private static AudioClipMetadata ReadFlac(ReadOnlySpan bytes) while (offset <= bytes.Length - 4) { byte header = bytes[offset]; - int blockType = header & 0x7f; + int blockType = header & 0x7F; int length = (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3]; int dataStart = checked(offset + 4); int dataEnd = checked(dataStart + length); @@ -143,9 +143,9 @@ private static AudioClipMetadata ReadFlac(ReadOnlySpan bytes) } ReadOnlySpan packed = bytes.Slice(dataStart + 10, 8); ulong value = BinaryPrimitives.ReadUInt64BigEndian(packed); - sampleRate = (int)((value >> 44) & 0xfffff); + sampleRate = (int)((value >> 44) & 0xF_FFFF); channels = (int)((value >> 41) & 0x7) + 1; - frameCount = (long)(value & 0xfffffffffUL); + frameCount = (long)(value & 0xF_FFFF_FFFFUL); foundStreamInfo = true; } offset = dataEnd; @@ -230,20 +230,20 @@ out int channels sampleRate = 0; samples = 0; channels = 0; - if ((header & 0xffe00000) != 0xffe00000) + if ((header & 0xFFE0_0000) != 0xFFE0_0000) { return false; } int mpegBits = (int)((header >> 19) & 0x3); int layerBits = (int)((header >> 17) & 0x3); - int bitrateIndex = (int)((header >> 12) & 0xf); + int bitrateIndex = (int)((header >> 12) & 0xF); int sampleRateIndex = (int)((header >> 10) & 0x3); if (mpegBits == 1 || layerBits != 1 || bitrateIndex is 0 or 15 || sampleRateIndex == 3) { return false; } - int[] sampleRates = [44100, 48000, 32000]; + int[] sampleRates = [44_100, 48_000, 32_000]; sampleRate = sampleRates[sampleRateIndex]; bool mpegOne = mpegBits == 3; if (mpegBits == 2) @@ -258,7 +258,7 @@ out int channels int[] lowerBitrates = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; int bitrate = (mpegOne ? mpegOneBitrates : lowerBitrates)[bitrateIndex]; int padding = (int)((header >> 9) & 1); - frameLength = ((mpegOne ? 144000 : 72000) * bitrate / sampleRate) + padding; + frameLength = ((mpegOne ? 144_000 : 72_000) * bitrate / sampleRate) + padding; samples = mpegOne ? 1152 : 576; channels = ((header >> 6) & 0x3) == 3 ? 1 : 2; return frameLength > 4; diff --git a/src/services/audio/Inno.Audio.Runtime/ArtifactAudioClipSource.cs b/src/services/audio/Inno.Audio.Runtime/ArtifactAudioClipSource.cs index eb747907f..0008e9848 100644 --- a/src/services/audio/Inno.Audio.Runtime/ArtifactAudioClipSource.cs +++ b/src/services/audio/Inno.Audio.Runtime/ArtifactAudioClipSource.cs @@ -5,12 +5,12 @@ namespace Inno.Audio.Runtime; internal sealed class ArtifactAudioClipSource(ArtifactLease artifact) : IAudioClipSource { - /// + /// public string contentHash => artifact.info.contentHash; - /// + /// public long length => artifact.info.length; - /// + /// public Stream OpenRead() => artifact.OpenRead(); } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs b/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs index 5cad8fd2b..de548703a 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioClipRequest.cs @@ -13,10 +13,10 @@ internal AudioClipRequest( AudioClipAsset clip, IAssetArtifactLookup artifacts ) { - persistentId = clip.identity.persistentId; - contentVersion = clip.contentVersion; - assetPath = clip.assetPath; - metadata = clip.metadata; + this.persistentId = clip.identity.persistentId; + this.contentVersion = clip.contentVersion; + this.assetPath = clip.assetPath; + this.metadata = clip.metadata; try { if (clip.isMissing || metadata is null) diff --git a/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs b/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs index 632481d7f..21cfc0682 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioContentOwner.cs @@ -32,7 +32,7 @@ int capacity m_diagnostics = diagnostics; m_contentScopeProvider = contentScopeProvider; m_capacity = capacity; - statistics = new AudioContentStatistics(capacity, 0, 0); + this.statistics = new AudioContentStatistics(capacity, 0, 0); } internal AudioContentStatistics statistics { get; private set; } diff --git a/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs b/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs index 4fc0a42d2..d1126519c 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioDeviceCandidate.cs @@ -10,7 +10,10 @@ internal sealed class AudioDeviceCandidate : IDisposable private IAudioDevice? m_device; private AudioMixerOwner? m_mixer; - internal AudioDeviceCandidate(IAudioDevice device) => m_device = device; + internal AudioDeviceCandidate(IAudioDevice device) + { + m_device = device; + } internal AudioMixerOwner Prepare(AudioMixerOwner previous) => m_mixer = previous.PrepareReplacement(m_device!); diff --git a/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs b/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs index 09b7d4f83..0ab2c61ca 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioExtensionRegistry.cs @@ -55,9 +55,7 @@ internal void EnsureHealthy() protected override void OnCleanupFailed( string phase, Exception exception - ) { - m_retirementFailure ??= exception; - } + ) => m_retirementFailure ??= exception; /// /// Builds a complete validated audio extension snapshot from one type generation. @@ -127,7 +125,7 @@ internal Snapshot( Func createProvider ) { m_types = types; - typeCacheVersion = types.version; + this.typeCacheVersion = types.version; m_mixers = mixers; m_features = features; m_providers = providers; diff --git a/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs b/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs index eda109bdb..9efb26a51 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioRuntime.cs @@ -145,11 +145,8 @@ public AudioRuntime( /// public double dspTime => m_device.dspTime; - /// - protected override void OnStart() - { - m_events.dispatched += OnEventDispatched; - } + /// + protected override void OnStart() => m_events.dispatched += OnEventDispatched; /// /// Captures snapshots and binds service façades. @@ -568,7 +565,10 @@ public void ReplaceDevice(IAudioDevice replacement) failures.Add(error); } m_candidateRetirement = null; - var failure = new AggregateException("Audio device retirement failed; the previous generation cannot resume.", failures); + var failure = new AggregateException( + "Audio device retirement failed; the previous generation cannot resume.", + failures + ); m_extensions.Fault(failure); throw failure; } @@ -795,11 +795,21 @@ private List RetireBackend(AudioCompletionReason reason) { switch (m_retirementStage) { - case 0: m_voices.CompleteAll(reason); break; - case 1: m_content.Dispose(); break; - case 2: m_clipCache.Dispose(); break; - case 3: m_mixer.Dispose(); break; - case 4: m_device.Dispose(); break; + case 0: + m_voices.CompleteAll(reason); + break; + case 1: + m_content.Dispose(); + break; + case 2: + m_clipCache.Dispose(); + break; + case 3: + m_mixer.Dispose(); + break; + case 4: + m_device.Dispose(); + break; } } catch (Exception pendingRetirement) when (RetirementPendingException.Find(pendingRetirement) is not null) diff --git a/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs b/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs index 0a9619b7d..d3059aac7 100644 --- a/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs +++ b/src/services/audio/Inno.Audio.Runtime/AudioVoiceOwner.cs @@ -419,7 +419,7 @@ long sequence this.options = options; this.scheduledDspTime = scheduledDspTime; this.sequence = sequence; - parameters = new AudioVoiceParameters(options.volume, options.pitch, options.pan, options.spatial); + this.parameters = new AudioVoiceParameters(options.volume, options.pitch, options.pan, options.spatial); } internal AudioVoiceHandle handle { get; } diff --git a/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs b/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs index 16b682da4..aa212d812 100644 --- a/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs +++ b/src/services/audio/Inno.Audio.Runtime/MutedAudioDevice.cs @@ -33,17 +33,17 @@ public sealed class MutedAudioDevice : AudioDevice, IAudioDevice /// Optional finite device resource capacities. /// public MutedAudioDevice( - int sampleRate = 48000, + int sampleRate = 48_000, AudioDeviceLimits? limits = null ) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); m_limits = limits ?? new AudioDeviceLimits(); - generation = unchecked(++S_NEXT_GENERATION); + this.generation = unchecked(++S_NEXT_GENERATION); if (generation == 0) { - generation = unchecked(++S_NEXT_GENERATION); + this.generation = unchecked(++S_NEXT_GENERATION); } - capabilities = new AudioCapabilities(true, true, true, 4, sampleRate); + this.capabilities = new AudioCapabilities(true, true, true, 4, sampleRate); } /// @@ -480,8 +480,8 @@ double scheduledDspTime ) { this.clip = clip; this.duration = duration; - loop = options.loop; - parameters = new AudioVoiceParameters(options.volume, options.pitch, options.pan, options.spatial); + this.loop = options.loop; + this.parameters = new AudioVoiceParameters(options.volume, options.pitch, options.pan, options.spatial); this.state = state; this.scheduledDspTime = scheduledDspTime; } diff --git a/src/services/audio/Inno.Audio/AudioClipAsset.cs b/src/services/audio/Inno.Audio/AudioClipAsset.cs index 74bc327a6..05a1e6303 100644 --- a/src/services/audio/Inno.Audio/AudioClipAsset.cs +++ b/src/services/audio/Inno.Audio/AudioClipAsset.cs @@ -87,7 +87,7 @@ long encodedByteLength /// public static class AudioClipMetadataCodec { - private const uint C_MAGIC = 0x44554149; + private const uint C_MAGIC = 0x4455_4149; private const int C_FIXED_SIZE = 32; /// @@ -106,7 +106,7 @@ public static byte[] Encode(AudioClipMetadata metadata) { throw new ArgumentException("The codec identifier is too long.", nameof(metadata)); } - byte[] output = new byte[C_FIXED_SIZE + codec.Length]; + var output = new byte[C_FIXED_SIZE + codec.Length]; BinaryPrimitives.WriteUInt32LittleEndian(output.AsSpan(0, 4), C_MAGIC); output[4] = (byte)codec.Length; BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(8, 4), metadata.channels); @@ -187,9 +187,7 @@ public sealed class AudioClipAsset : AssetObject protected override void OnRuntimePayloadChanged( ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload - ) { - m_metadata = currentPayload.IsEmpty - ? null - : AudioClipMetadataCodec.Decode(currentPayload.Span); - } + ) => m_metadata = currentPayload.IsEmpty + ? null + : AudioClipMetadataCodec.Decode(currentPayload.Span); } diff --git a/src/services/audio/Inno.Audio/AudioDeviceLimits.cs b/src/services/audio/Inno.Audio/AudioDeviceLimits.cs index bf8710895..4073ec4b8 100644 --- a/src/services/audio/Inno.Audio/AudioDeviceLimits.cs +++ b/src/services/audio/Inno.Audio/AudioDeviceLimits.cs @@ -23,8 +23,8 @@ public sealed class AudioDeviceLimits /// A capacity is not positive. /// public AudioDeviceLimits( - int clips = 16384, - int voices = 65536, + int clips = 16_384, + int voices = 65_536, int buses = 4096 ) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(clips); diff --git a/src/services/audio/Inno.Audio/AudioMixer.cs b/src/services/audio/Inno.Audio/AudioMixer.cs index 5635992f3..12b0cf0bd 100644 --- a/src/services/audio/Inno.Audio/AudioMixer.cs +++ b/src/services/audio/Inno.Audio/AudioMixer.cs @@ -321,7 +321,7 @@ public struct SerializedAudioExtensionState /// public SerializedAudioExtensionState() { - propertyData = []; + this.propertyData = []; } /// diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs index 490903fb6..720958119 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Assets.Authoring; /// /// Selects one renderer profile and compilation policy. /// -[Inno.Extensibility.Types.StableTypeId("29e9c0f0-cb34-5b98-a6d6-356f744f3049")] +[StableTypeId("29e9c0f0-cb34-5b98-a6d6-356f744f3049")] public sealed class ShaderCompileTarget { /// @@ -73,7 +74,7 @@ public ShaderCompileTarget( /// /// Stores one immutable target stage binary. /// -[Inno.Extensibility.Types.StableTypeId("7de46626-7dd7-5112-b098-ef3eb53a0cda")] +[StableTypeId("7de46626-7dd7-5112-b098-ef3eb53a0cda")] public sealed class ShaderStageArtifact { private readonly byte[] m_bytes; @@ -124,7 +125,7 @@ ShaderSourceLocation sourceLocation /// /// Stores all compiled stages and state for one shader pass. /// -[Inno.Extensibility.Types.StableTypeId("6a66aac0-d44d-5d90-a801-d92605a92c91")] +[StableTypeId("6a66aac0-d44d-5d90-a801-d92605a92c91")] public sealed class CompiledShaderPass { private readonly ShaderPassDefinition m_definition; @@ -181,7 +182,7 @@ public ShaderPassDefinition definition /// /// Contains an immutable target shader artifact and expected reflected interface. /// -[Inno.Extensibility.Types.StableTypeId("25e556fe-a071-58b2-8e70-0e41bd434d83")] +[StableTypeId("25e556fe-a071-58b2-8e70-0e41bd434d83")] public sealed class CompiledShaderArtifact { private readonly byte[] m_definitionData; @@ -315,7 +316,7 @@ private static RenderRasterState ConvertRasterState(ShaderRenderState source) /// /// Returns a candidate artifact and structured diagnostics without mutating active state. /// -[Inno.Extensibility.Types.StableTypeId("72b304de-8a2b-5c08-b899-b4aef05be149")] +[StableTypeId("72b304de-8a2b-5c08-b899-b4aef05be149")] public sealed class ShaderCompilationResult { /// @@ -357,7 +358,7 @@ public bool succeeded /// /// Defines a backend-owned target compiler used by the common Shader IR pipeline. /// -[Inno.Extensibility.Types.StableTypeId("00437bae-b212-505f-8017-d59fd29fb005")] +[StableTypeId("00437bae-b212-505f-8017-d59fd29fb005")] public interface IShaderCompilerToolchain { /// @@ -412,7 +413,7 @@ ShaderCompileTarget CreateTarget( /// /// Compiles validated Shader IR through one target toolchain. /// -[Inno.Extensibility.Types.StableTypeId("85c9086c-63d5-51e6-82ec-548ad39702e2")] +[StableTypeId("85c9086c-63d5-51e6-82ec-548ad39702e2")] public sealed partial class ShaderCompiler { private readonly IShaderCompilerToolchain m_toolchain; diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs index f31b3c317..5753fb390 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Security.Cryptography; using System.Threading; +using Inno.Assets; using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Types; @@ -15,7 +16,7 @@ namespace Inno.Rendering.Assets.Authoring; /// /// Persists graph and frozen function inputs as an authoring artifact; Player export removes this payload. /// -[Inno.Extensibility.Types.StableTypeId("1bb0d88f-b8ca-5d43-a91c-8d6d4ac0f0c2")] +[StableTypeId("1bb0d88f-b8ca-5d43-a91c-8d6d4ac0f0c2")] public static partial class ShaderGraphArtifact { /// @@ -77,7 +78,7 @@ public static byte[] Capture( { continue; } - string path = ShaderGraphDocument.Read(node, "sourcePath", "", serialization, context); + string path = ShaderGraphDocument.Read(node, "sourcePath", string.Empty, serialization, context); sources.Add(node.id, readSource(id, path)); } return Encode(graph, sources, serialization, program); @@ -129,11 +130,11 @@ SerializationContext context /// public static byte[] Read( ShaderAsset shader, - Inno.Assets.IAssetArtifactLookup artifacts + IAssetArtifactLookup artifacts ) { ArgumentNullException.ThrowIfNull(shader); ArgumentNullException.ThrowIfNull(artifacts); - using Inno.Assets.ArtifactLease lease = artifacts.AcquireArtifact(shader.identity.persistentId, outputName); + using ArtifactLease lease = artifacts.AcquireArtifact(shader.identity.persistentId, outputName); return lease.ReadAllBytes(); } @@ -259,40 +260,46 @@ public static ShaderGraphProgramResult Lower( ) { ArtifactData data = serialization.Deserialize(bytes); GraphDocument graph = GraphDocumentCodec.Decode(data.program, serialization); - var sources = data.sources.ToDictionary(static source => new GraphNodeId(source.node), source => - { - GraphNodeRecord node = graph.FindNode(new(source.node)) - ?? throw new InvalidOperationException($"Captured source node '{source.node}' is unavailable."); - string function = ShaderGraphDocument.Read(node, "function", "", serialization, context); - if (string.IsNullOrWhiteSpace(function)) + Dictionary sources = data.sources.ToDictionary( + static source => new GraphNodeId(source.node), + source => { - throw new InvalidOperationException($"Source node '{source.node}' has no exported function selection."); + GraphNodeRecord node = graph.FindNode(new(source.node)) + ?? throw new InvalidOperationException($"Captured source node '{source.node}' is unavailable."); + string function = ShaderGraphDocument.Read(node, "function", string.Empty, serialization, context); + if (string.IsNullOrWhiteSpace(function)) + { + throw new InvalidOperationException($"Source node '{source.node}' has no exported function selection."); + } + return frontends.AnalyzeModule(ShaderSourceBundle.Decode(source.bundle, function, serialization, defines)); } - return frontends.AnalyzeModule(ShaderSourceBundle.Decode(source.bundle, function, serialization, defines)); - }); + ); return new ShaderGraphProgramCompiler(nodes).Lower(graph, implementationId, sources, serialization, context); } - [Inno.Extensibility.Types.StableTypeId("16182a41-f19b-5a28-a66f-5310360f8a32")] + [StableTypeId("16182a41-f19b-5a28-a66f-5310360f8a32")] private sealed class ArtifactData : ISerializable { /// /// Gets or sets native graph bytes. /// - [SerializableProperty] public byte[] document { get; set; } = []; + [SerializableProperty] + public byte[] document { get; set; } = []; /// /// Gets or sets explicit target-expanded stage graph bytes. /// - [SerializableProperty] public byte[] program { get; set; } = []; + [SerializableProperty] + public byte[] program { get; set; } = []; /// /// Gets or sets frozen functions by node identity. /// - [SerializableProperty] public SourceData[] sources { get; set; } = []; + [SerializableProperty] + public SourceData[] sources { get; set; } = []; } - [Inno.Extensibility.Types.StableTypeId("91d54277-1257-5bf0-904d-165e8092fe4a")] + [StableTypeId("91d54277-1257-5bf0-904d-165e8092fe4a")] private struct SourceData { /// diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs index 23e8889d6..f3a7dec7e 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Inno.Assets; using Inno.Core.Diagnostics; using Inno.Core.Serialization; using Inno.Extensibility.Types; @@ -54,7 +55,7 @@ public ValueTask CompileGraphAsync( TypeCatalog types, SerializationRegistry serialization, SerializationContext context, - Inno.Assets.IAssetArtifactLookup artifacts, + IAssetArtifactLookup artifacts, CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(shader); @@ -109,12 +110,15 @@ public ValueTask CompileGraphAsync( using var nodes = new ShaderNodeCompilerRegistry(types); using var frontends = new ShaderSourceFrontendRegistry(types); ShaderDefinition definition = ShaderGraphArtifact.ReadDefinition(artifact.Span, serialization, context); - var diagnostics = ShaderDefinitionValidator.Validate(definition, target.capabilities).ToList(); + List diagnostics = ShaderDefinitionValidator.Validate(definition, target.capabilities).ToList(); if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) { return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); } - var keywords = definition.keywords.ToDictionary(static value => value.id, StringComparer.Ordinal); + Dictionary keywords = definition.keywords.ToDictionary( + static value => value.id, + StringComparer.Ordinal + ); foreach ((string id, string value) in variant.options) { if (!keywords.TryGetValue(id, out ShaderKeywordDefinition keyword) || !keyword.options.Contains(value, StringComparer.Ordinal)) @@ -181,7 +185,7 @@ public ValueTask CompileAsync( ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(program); ArgumentNullException.ThrowIfNull(target); - var diagnostics = ShaderDefinitionValidator.Validate(definition, target.capabilities).ToList(); + List diagnostics = ShaderDefinitionValidator.Validate(definition, target.capabilities).ToList(); if (diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) { return ValueTask.FromResult(new ShaderCompilationResult(null, diagnostics)); @@ -241,7 +245,7 @@ CancellationToken cancellationToken ArgumentNullException.ThrowIfNull(definition); ArgumentNullException.ThrowIfNull(program); ArgumentNullException.ThrowIfNull(target); - var diagnostics = program.diagnostics + List diagnostics = program.diagnostics .Select(static value => new ShaderDiagnostic(value.code, value.severity, value.message)) .ToList(); diagnostics.AddRange(ShaderDefinitionValidator.Validate(definition, target.capabilities)); @@ -265,7 +269,7 @@ CancellationToken cancellationToken value.storageAccess, value.bindingOwner )).ToArray(); - var passes = definition.passes.Select(static value => new ShaderPassDefinition( + Dictionary passes = definition.passes.Select(static value => new ShaderPassDefinition( value.name, value.programKind, requiredFeatures: value.requiredFeatures, diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs index e2dcdde89..703c16a0a 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets.Authoring; /// /// Describes the artifact selected after evaluating a candidate compilation. /// -[Inno.Extensibility.Types.StableTypeId("2cbb2378-91ef-5c66-866e-e651e80a79a7")] +[StableTypeId("2cbb2378-91ef-5c66-866e-e651e80a79a7")] public sealed class ShaderArtifactSelection { /// @@ -64,7 +65,7 @@ IReadOnlyList diagnostics /// /// Atomically preserves last-good CPU shader artifacts by asset, target and variant. /// -[Inno.Extensibility.Types.StableTypeId("b238055f-335a-528f-bdee-cf0044f8e75e")] +[StableTypeId("b238055f-335a-528f-bdee-cf0044f8e75e")] public sealed class ShaderLastGoodStore { private readonly object m_gate = new(); diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs index c4ca92825..76bec0e38 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderSourceBundle.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using Inno.Assets; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Shaders; @@ -10,7 +12,7 @@ namespace Inno.Rendering.Assets.Authoring; /// /// Persists only frozen function compilation inputs, never a parser, live asset, resolver or generated main function. /// -[Inno.Extensibility.Types.StableTypeId("3387d371-94f4-5f59-a571-aa552e7eef0a")] +[StableTypeId("3387d371-94f4-5f59-a571-aa552e7eef0a")] public static partial class ShaderSourceBundle { /// @@ -32,11 +34,11 @@ public static partial class ShaderSourceBundle /// public static byte[] Read( ShaderFunctionAsset function, - Inno.Assets.IAssetArtifactLookup artifacts + IAssetArtifactLookup artifacts ) { ArgumentNullException.ThrowIfNull(function); ArgumentNullException.ThrowIfNull(artifacts); - using Inno.Assets.ArtifactLease lease = artifacts.AcquireArtifact(function.identity.persistentId, outputName); + using ArtifactLease lease = artifacts.AcquireArtifact(function.identity.persistentId, outputName); return lease.ReadAllBytes(); } @@ -130,17 +132,17 @@ public static IReadOnlyList Decode( ) { throw new InvalidOperationException("The frozen shader source bundle has inconsistent collection lengths."); } - var files = value.paths.Select(( + Dictionary files = value.paths.Select(( path, index ) => new ShaderSourceFile(path, value.texts[index])).ToDictionary(static file => file.assetPath, StringComparer.Ordinal); - var edges = value.includeOwners + Dictionary<(string includingFile, string include), ShaderSourceInclude> edges = value.includeOwners .Select(( owner, index ) => new ShaderSourceInclude(owner, value.includeNames[index], value.includePaths[index])) .ToDictionary(static edge => (edge.includingFile, edge.include)); - var macros = value.defineNames.Select(( + Dictionary macros = value.defineNames.Select(( name, index ) => new KeyValuePair(name, value.defineValues[index])).ToDictionary(StringComparer.Ordinal); @@ -187,16 +189,17 @@ string include : throw new InvalidOperationException($"Source dependency '{include}' from '{includingFile}' was not captured by import."); } - [Inno.Extensibility.Types.StableTypeId("0e035881-9850-5f9c-8037-283168890d0d")] + [StableTypeId("0e035881-9850-5f9c-8037-283168890d0d")] private sealed class BundleData : ISerializable { /// /// Gets the ordered shader functions in this source bundle. /// - [SerializableProperty] public FunctionData[] functions { get; set; } = []; + [SerializableProperty] + public FunctionData[] functions { get; set; } = []; } - [Inno.Extensibility.Types.StableTypeId("3c78ad4e-deb3-547b-984e-18de97667641")] + [StableTypeId("3c78ad4e-deb3-547b-984e-18de97667641")] private struct FunctionData { /// @@ -210,7 +213,7 @@ private struct FunctionData public ImplementationData[] implementations { get; set; } } - [Inno.Extensibility.Types.StableTypeId("4f51d0e8-599b-5fd7-b4cc-4694fe18e922")] + [StableTypeId("4f51d0e8-599b-5fd7-b4cc-4694fe18e922")] private struct ImplementationData { /// diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs index 61c25f9bd..37aa468bb 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Shaders; @@ -18,7 +19,7 @@ namespace Inno.Rendering.Assets.Authoring; /// /// Exact toolchain profile and capability snapshot. /// -[Inno.Extensibility.Types.StableTypeId("8a37ee08-a048-52fc-bbf4-bbc47fe425d4")] +[StableTypeId("8a37ee08-a048-52fc-bbf4-bbc47fe425d4")] public sealed record ShaderStageToolRequest( ShaderIrStage stage, ShaderCompileTarget target @@ -36,7 +37,7 @@ ShaderCompileTarget target /// /// Assigned texture slot; uniform locations are resolved by the runtime. /// -[Inno.Extensibility.Types.StableTypeId("00dff34d-f800-51e6-8a37-0141761958c8")] +[StableTypeId("00dff34d-f800-51e6-8a37-0141761958c8")] public sealed record ShaderStageBinding( string id, string nativeName, @@ -46,7 +47,7 @@ int location /// /// Returns a frozen typed-stage compilation candidate; failure never carries a usable artifact. /// -[Inno.Extensibility.Types.StableTypeId("cf544248-8a38-5999-b8aa-bbdcf94fa6e8")] +[StableTypeId("cf544248-8a38-5999-b8aa-bbdcf94fa6e8")] public sealed class ShaderStageToolResult { private readonly byte[] m_bytes; @@ -132,7 +133,7 @@ public async ValueTask CompileAsync( ArgumentNullException.ThrowIfNull(stage); ArgumentNullException.ThrowIfNull(target); cancellationToken.ThrowIfCancellationRequested(); - var key = (stage.contentHash, target.key, target.capabilities); + (string contentHash, string key, GraphicsCapabilities capabilities) key = (stage.contentHash, target.key, target.capabilities); lock (m_stageCacheLock) { if (m_stageCache.TryGetValue(key, out ShaderStageToolResult? previous)) diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs index 2e4937d26..11979651d 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs @@ -2,6 +2,7 @@ using System.IO; using System.Threading; using System.Threading.Tasks; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -10,7 +11,7 @@ namespace Inno.Rendering.Assets.Authoring; /// /// Converts supported artist texture sources into a validated portable runtime container. /// -[Inno.Extensibility.Types.StableTypeId("01400c3b-21c2-5193-ae8f-3cf3665f4261")] +[StableTypeId("01400c3b-21c2-5193-ae8f-3cf3665f4261")] public interface ITextureTargetCompiler { /// diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs index aee98f7a6..8a923b6e5 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs @@ -4,6 +4,7 @@ using Inno.Assets.Pipeline; using Inno.Core.Graphs; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets.Authoring; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Assets.Authoring; /// /// Reads and atomically saves the sole shader graph source format without requiring successful compilation. /// -[Inno.Extensibility.Types.StableTypeId("dcfd81b7-a22d-5b35-a79a-a608e69b7ad8")] +[StableTypeId("dcfd81b7-a22d-5b35-a79a-a608e69b7ad8")] public sealed class ShaderGraphSourceStore { private readonly AssetSourceStore m_sources; @@ -94,7 +95,7 @@ private static void Validate(AssetPath path) /// /// Contains detached graph source state, not a compiled or live runtime asset. /// -[Inno.Extensibility.Types.StableTypeId("fb1d9ba2-d37c-59f1-a7ef-17feeb3beb0e")] +[StableTypeId("fb1d9ba2-d37c-59f1-a7ef-17feeb3beb0e")] public sealed class ShaderGraphSourceSnapshot { private readonly GraphDocument m_document; @@ -105,8 +106,8 @@ internal ShaderGraphSourceSnapshot( bool readOnly ) { m_document = document; - contentHash = hash; - isReadOnly = readOnly; + this.contentHash = hash; + this.isReadOnly = readOnly; } /// diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs index 99e5f2196..902c5ae36 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs @@ -6,13 +6,14 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Mathematics; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.geometry")] -[Inno.Extensibility.Types.StableTypeId("a7278025-7d95-5fb3-a309-25458cef8765")] +[StableTypeId("a7278025-7d95-5fb3-a309-25458cef8765")] internal sealed class GeometryAssetImporter : AssetImporter { /// diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs index bf6627d30..7e8adb3cf 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfJson.cs @@ -1,10 +1,11 @@ using System; using System.Text.Json; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets.Authoring; -[Inno.Extensibility.Types.StableTypeId("d5d5c69c-6d36-541f-bdd6-305af58d8e18")] +[StableTypeId("d5d5c69c-6d36-541f-bdd6-305af58d8e18")] internal static class GltfJson { internal static JsonElement RequireObject( diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs index ffbadcba8..20e9d0a79 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs @@ -6,17 +6,18 @@ using System.Text; using System.Text.Json; using Inno.Core.Mathematics; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; -[Inno.Extensibility.Types.StableTypeId("c2a6add7-0201-527c-87a4-137904623ee6")] +[StableTypeId("c2a6add7-0201-527c-87a4-137904623ee6")] internal static partial class MeshSourceParser { - private const uint C_GLB_MAGIC = 0x46546c67; - private const uint C_JSON_CHUNK = 0x4e4f534a; - private const uint C_BIN_CHUNK = 0x004e4942; + private const uint C_GLB_MAGIC = 0x4654_6C67; + private const uint C_JSON_CHUNK = 0x4E4F_534A; + private const uint C_BIN_CHUNK = 0x004E_4942; internal static GeometryData ParseGltf( string sourcePath, diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs index 1426db37d..b5733d24a 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs @@ -5,13 +5,14 @@ using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.material")] -[Inno.Extensibility.Types.StableTypeId("64229f7a-85a7-5d65-9a50-3c8ea5bc3585")] +[StableTypeId("64229f7a-85a7-5d65-9a50-3c8ea5bc3585")] internal sealed class MaterialAssetImporter : AssetImporter { /// diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs index 3a5d9ac7d..071e3e53b 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs @@ -5,13 +5,14 @@ using System.Threading.Tasks; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.pipeline")] -[Inno.Extensibility.Types.StableTypeId("6753d2fb-9773-518d-9673-beae57f6daa7")] +[StableTypeId("6753d2fb-9773-518d-9673-beae57f6daa7")] internal sealed class RenderPipelineAssetImporter : AssetImporter { /// diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs index 75951dfd9..92993cf50 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderingAssetFormatException.cs @@ -1,9 +1,10 @@ using System; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets.Authoring; -[Inno.Extensibility.Types.StableTypeId("d9c542b3-2def-59a3-a8a5-7115eaa1e0ea")] +[StableTypeId("d9c542b3-2def-59a3-a8a5-7115eaa1e0ea")] internal sealed class RenderingAssetFormatException : FormatException { internal RenderingAssetFormatException( diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs index 3c2f87c80..38a02a6ba 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs @@ -7,6 +7,7 @@ using Inno.Assets.Pipeline; using Inno.Core.Graphs; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Shaders; @@ -14,7 +15,7 @@ namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.shader")] -[Inno.Extensibility.Types.StableTypeId("8e87052c-6ea6-52d3-9201-8544c4f75013")] +[StableTypeId("8e87052c-6ea6-52d3-9201-8544c4f75013")] internal sealed class ShaderAssetImporter : AssetImporter { /// diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs index 1402c26e2..780c577fa 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionAsset.cs @@ -14,25 +14,30 @@ public sealed class ShaderFunctionAsset : AssetObject /// /// Gets the configured source language identity. /// - [SerializableProperty] public string languageId { get; internal set; } = string.Empty; + [SerializableProperty] + public string languageId { get; internal set; } = string.Empty; /// /// Gets the explicitly exported functions available to graph source-function nodes. /// - [SerializableProperty] public string[] exports { get; internal set; } = []; + [SerializableProperty] + public string[] exports { get; internal set; } = []; /// /// Gets the adapter implementation identity. /// - [SerializableProperty] public string implementationId { get; internal set; } = string.Empty; + [SerializableProperty] + public string implementationId { get; internal set; } = string.Empty; /// /// Gets the author-declared catalog path used by Shader creation tools. /// - [SerializableProperty] public string catalogPath { get; internal set; } = string.Empty; + [SerializableProperty] + public string catalogPath { get; internal set; } = string.Empty; /// /// Gets the stable ordering value inside the authoring catalog. /// - [SerializableProperty] public int catalogOrder { get; internal set; } + [SerializableProperty] + public int catalogOrder { get; internal set; } } diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs index 8fb351965..23006f831 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs @@ -7,13 +7,14 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.shader-function")] -[Inno.Extensibility.Types.StableTypeId("17f67477-6d9c-5b85-9c98-f1c9df4961d3")] +[StableTypeId("17f67477-6d9c-5b85-9c98-f1c9df4961d3")] internal sealed class ShaderFunctionImporter : AssetImporter { /// @@ -54,8 +55,8 @@ protected override async ValueTask ImportAsync( AssetImportWriter output, CancellationToken cancellationToken ) { - var settings = context.importSettings as ShaderSourceImportSettings - ?? throw new InvalidOperationException("Shader source requires its standard import settings."); + ShaderSourceImportSettings settings = context.importSettings as ShaderSourceImportSettings + ?? throw new InvalidOperationException("Shader source requires its standard import settings."); ArgumentException.ThrowIfNullOrWhiteSpace(settings.languageId); ArgumentException.ThrowIfNullOrWhiteSpace(settings.implementationId); string[] exports = (settings.exports ?? []).Where(static value => !string.IsNullOrWhiteSpace(value)) @@ -148,7 +149,7 @@ string include owner.source, (Path.GetDirectoryName(owner.localPath)?.Replace('\\', '/') is { Length: > 0 } directory ? directory + "/" - : "") + normalized + : string.Empty) + normalized ); return new(path.ToString(), context.ReadSourceUtf8Text(path)); } diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs index b4814b2ae..a2e18305b 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderSourceImportSettings.cs @@ -13,30 +13,36 @@ public sealed class ShaderSourceImportSettings : ISerializable /// /// Gets or sets the registered language identity; an empty selection is an import error. /// - [SerializableProperty] public string languageId { get; set; } = string.Empty; + [SerializableProperty] + public string languageId { get; set; } = string.Empty; /// /// Gets or sets the explicitly exported function names. Unlisted helpers remain private to the source library. /// - [SerializableProperty] public string[] exports { get; set; } = ["Evaluate"]; + [SerializableProperty] + public string[] exports { get; set; } = ["Evaluate"]; /// /// Gets or sets the exact implementation key used by the selected rendering backend. /// - [SerializableProperty] public string implementationId { get; set; } = string.Empty; + [SerializableProperty] + public string implementationId { get; set; } = string.Empty; /// /// Gets or sets alternate source implementations; all must expose the same public interface with unique backend IDs. /// - [SerializableProperty] public ShaderFunctionAsset[] implementations { get; set; } = []; + [SerializableProperty] + public ShaderFunctionAsset[] implementations { get; set; } = []; /// /// Gets or sets the slash-delimited authoring catalog path used to group this library in creation UIs. /// - [SerializableProperty] public string catalogPath { get; set; } = string.Empty; + [SerializableProperty] + public string catalogPath { get; set; } = string.Empty; /// /// Gets or sets the stable ordering value of this library inside its authoring catalog group. /// - [SerializableProperty] public int catalogOrder { get; set; } + [SerializableProperty] + public int catalogOrder { get; set; } } diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs index 95dd0dd15..9a17a1028 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs @@ -6,13 +6,14 @@ using System.Threading; using System.Threading.Tasks; using Inno.Assets.Pipeline; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; [AssetImporter("inno.rendering.texture")] -[Inno.Extensibility.Types.StableTypeId("30731d81-b1e7-54f9-8637-9410a8724647")] +[StableTypeId("30731d81-b1e7-54f9-8637-9410a8724647")] internal sealed partial class TextureAssetImporter : AssetImporter { /// @@ -75,7 +76,7 @@ internal static (int width, int height) ReadPngSize(ReadOnlySpan bytes) internal static (int width, int height) ReadJpegSize(ReadOnlySpan bytes) { - if (bytes.Length < 4 || bytes[0] != 0xff || bytes[1] != 0xd8) + if (bytes.Length < 4 || bytes[0] != 0xFF || bytes[1] != 0xD8) { throw new RenderingAssetFormatException("texture.jpg", "Invalid JPEG start marker."); } @@ -83,7 +84,7 @@ internal static (int width, int height) ReadJpegSize(ReadOnlySpan bytes) int offset = 2; while (offset + 4 <= bytes.Length) { - while (offset < bytes.Length && bytes[offset] == 0xff) + while (offset < bytes.Length && bytes[offset] == 0xFF) { offset++; } @@ -94,7 +95,7 @@ internal static (int width, int height) ReadJpegSize(ReadOnlySpan bytes) } byte marker = bytes[offset++]; - if (marker is 0xd8 or 0xd9) + if (marker is 0xD8 or 0xD9) { continue; } @@ -148,7 +149,7 @@ internal static (int width, int height) ReadHdrSize(string text) return RequirePositiveSize(width, height, "texture.hdr"); } - private static bool IsStartOfFrame(byte marker) => marker is >= 0xc0 and <= 0xcf and not (0xc4 or 0xc8 or 0xcc); + private static bool IsStartOfFrame(byte marker) => marker is >= 0xC0 and <= 0xCF and not (0xC4 or 0xC8 or 0xCC); private static (int width, int height) RequirePositiveSize( int width, diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs index 39aea9394..46b3497ea 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifact.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Contains one immutable, source-free shader artifact ready for runtime GPU resource creation. /// -[Inno.Extensibility.Types.StableTypeId("43b40c10-c10b-5e97-b662-9bf9b4c9e34e")] +[StableTypeId("43b40c10-c10b-5e97-b662-9bf9b4c9e34e")] public sealed class RenderShaderArtifact { private readonly byte[] m_definitionData; @@ -33,12 +34,12 @@ public sealed class RenderShaderArtifact /// /// Every source-free pass available to the runtime shader definition. /// - /// - /// Thrown when a required identity is empty, no pass exists, or pass names are duplicated. - /// /// /// Native-serialized material, keyword, technique and pass contract captured with these programs; contains stable asset references only. /// + /// + /// Thrown when a required identity is empty, no pass exists, or pass names are duplicated. + /// public RenderShaderArtifact( string shaderName, string targetKey, @@ -70,7 +71,7 @@ ReadOnlySpan definitionData throw new ArgumentException("A shader publication requires its captured runtime contract.", nameof(definitionData)); } m_definitionData = definitionData.ToArray(); - contentHash = Convert.ToHexString(SHA256.HashData(RenderShaderArtifactCodec.Encode(this))); + this.contentHash = Convert.ToHexString(SHA256.HashData(RenderShaderArtifactCodec.Encode(this))); } /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs index efa81f951..a29fcdcb2 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderArtifactCodec.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Text; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -10,7 +11,7 @@ namespace Inno.Rendering.Assets; /// /// Encodes and validates the strict source-free binary format shared by game builds and Players. /// -[Inno.Extensibility.Types.StableTypeId("224813eb-a98c-5afa-a351-92e539a99d61")] +[StableTypeId("224813eb-a98c-5afa-a351-92e539a99d61")] public static class RenderShaderArtifactCodec { private const int C_MAX_BINDINGS = 4096; diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs index dcaa5504b..3442338e4 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderPassArtifact.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Carries one immutable compiled shader pass and its reflected runtime bindings. /// -[Inno.Extensibility.Types.StableTypeId("f22a2116-992d-5c69-bf6c-af05c191123b")] +[StableTypeId("f22a2116-992d-5c69-bf6c-af05c191123b")] public sealed class RenderShaderPassArtifact { private readonly IReadOnlyList m_stages; diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs index 8095cc426..2b7c78dbf 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderStageArtifact.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Stores one immutable target shader stage without retaining authoring source or compiler state. /// -[Inno.Extensibility.Types.StableTypeId("617ca942-9bab-528c-8052-e9cfb2ae0df5")] +[StableTypeId("617ca942-9bab-528c-8052-e9cfb2ae0df5")] public sealed class RenderShaderStageArtifact { private readonly byte[] m_bytes; diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs index 49d6cbd60..f48ee38f4 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderShaderVariant.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Identifies one deterministic selection of static shader keyword options shared by authoring and runtime. /// -[Inno.Extensibility.Types.StableTypeId("c6c7b7a6-5e4f-5822-af8f-e894d7bb2d38")] +[StableTypeId("c6c7b7a6-5e4f-5822-af8f-e894d7bb2d38")] public readonly struct RenderShaderVariant : IEquatable { private static readonly IReadOnlyDictionary S_EMPTY_OPTIONS = diff --git a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs index 86c4973f0..ec59cb537 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Deployment/RenderTargetArtifactPath.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.Security.Cryptography; using System.Text; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Defines deterministic relative paths shared by target-artifact producers and runtime consumers. /// -[Inno.Extensibility.Types.StableTypeId("85da30f1-a679-56d0-9cdf-7d6cf19b83f0")] +[StableTypeId("85da30f1-a679-56d0-9cdf-7d6cf19b83f0")] public static class RenderTargetArtifactPath { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs index 8808e47b1..4fc82f6e2 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryArtifact.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using Inno.Core.Mathematics; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,10 +10,10 @@ namespace Inno.Rendering.Assets; /// /// Encodes and validates the stable backend-neutral geometry artifact shared by import and runtime stages. /// -[Inno.Extensibility.Types.StableTypeId("8dc59951-b7e4-5c80-b34d-d2ce84174b65")] +[StableTypeId("8dc59951-b7e4-5c80-b34d-d2ce84174b65")] public static class GeometryArtifact { - private const ulong C_MAGIC = 0x4853454D4F4E4E49; + private const ulong C_MAGIC = 0x4853_454D_4F4E_4E49; /// /// Encodes normalized geometry into the immutable runtime artifact layout. diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs index 7968ed998..644b27453 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryAssetRuntime.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using Inno.Core.Mathematics; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Decodes normalized CPU geometry committed by mesh importers. /// -[Inno.Extensibility.Types.StableTypeId("81298da5-7d85-5964-8cb9-6f70a1e0564f")] +[StableTypeId("81298da5-7d85-5964-8cb9-6f70a1e0564f")] public static class GeometryAssetRuntime { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs index 459995228..7c6fcfce0 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryData.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using Inno.Core.Mathematics; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Contains normalized CPU mesh data ready for backend upload. /// -[Inno.Extensibility.Types.StableTypeId("9590e0d3-f8d2-58b1-9288-d0a20448ceb6")] +[StableTypeId("9590e0d3-f8d2-58b1-9288-d0a20448ceb6")] public sealed class GeometryData { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs index 79980d255..393acd5be 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometrySection.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using Inno.Core.Mathematics; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Identifies a contiguous triangle-index range. /// -[Inno.Extensibility.Types.StableTypeId("5da29d2a-b38b-5d50-b8ee-10e00503c0c5")] +[StableTypeId("5da29d2a-b38b-5d50-b8ee-10e00503c0c5")] public readonly record struct GeometrySection { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs index d60c82852..117282f2c 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Geometry/GeometryVertex.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using Inno.Core.Mathematics; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Stores one normalized vertex shared by all rendering backends. /// -[Inno.Extensibility.Types.StableTypeId("cfce5c30-dee4-5d62-9aa3-3e32ea5e7355")] +[StableTypeId("cfce5c30-dee4-5d62-9aa3-3e32ea5e7355")] public readonly record struct GeometryVertex { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs index 65fdc6c04..43c19fac7 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialAsset.cs @@ -141,7 +141,7 @@ public void SetKeyword( bool enabled ) { ArgumentException.ThrowIfNullOrWhiteSpace(keyword); - var values = m_keywords.ToHashSet(StringComparer.Ordinal); + HashSet values = m_keywords.ToHashSet(StringComparer.Ordinal); if (enabled) { values.Add(keyword); diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs index 18de130ac..6852d38c6 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialMetadataEntry.cs @@ -12,7 +12,7 @@ namespace Inno.Rendering.Assets; /// /// Stores one open material metadata key and value. /// -[Inno.Extensibility.Types.StableTypeId("38365af5-31ec-5646-8f17-42c31c98f7c2")] +[StableTypeId("38365af5-31ec-5646-8f17-42c31c98f7c2")] public struct MaterialMetadataEntry { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs index a614c5d2a..809261d98 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolution.cs @@ -12,7 +12,7 @@ namespace Inno.Rendering.Assets; /// /// Describes one capability-compatible material pass selection. /// -[Inno.Extensibility.Types.StableTypeId("e4a37a17-bfc1-5b29-9c57-f7b387271f9f")] +[StableTypeId("e4a37a17-bfc1-5b29-9c57-f7b387271f9f")] public sealed class MaterialPassResolution { private readonly ShaderTechniqueDefinition m_technique; diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs index 55d973a26..e234a52f2 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPassResolver.cs @@ -12,7 +12,7 @@ namespace Inno.Rendering.Assets; /// /// Resolves materials through open provider-owned shader contracts and roles. /// -[Inno.Extensibility.Types.StableTypeId("dcf92cc9-04c6-52cd-8fd3-b2dc48f73b5a")] +[StableTypeId("dcf92cc9-04c6-52cd-8fd3-b2dc48f73b5a")] public static class MaterialPassResolver { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs index c63169ad3..967d8959e 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyBlock.cs @@ -12,7 +12,7 @@ namespace Inno.Rendering.Assets; /// /// Holds frame-local material overrides without modifying a shared asset. /// -[Inno.Extensibility.Types.StableTypeId("aa10e23b-3f29-525e-af70-e48b77746037")] +[StableTypeId("aa10e23b-3f29-525e-af70-e48b77746037")] public sealed class MaterialPropertyBlock { private readonly Dictionary m_values = []; @@ -48,12 +48,12 @@ MaterialValue value /// /// Stable shader property identifier. /// - /// - /// when the override exists. - /// /// /// The concrete value read or transformed by this operation. /// + /// + /// when the override exists. + /// public bool TryGet( ShaderPropertyId id, out MaterialValue value diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs index 7f6c8ee2b..a99dd88ed 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialPropertyEntry.cs @@ -12,7 +12,7 @@ namespace Inno.Rendering.Assets; /// /// Stores one persistent material property entry. /// -[Inno.Extensibility.Types.StableTypeId("f4c298ba-cda4-5155-a050-d33f70175c7c")] +[StableTypeId("f4c298ba-cda4-5155-a050-d33f70175c7c")] public struct MaterialPropertyEntry { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs index cd6b81651..c48b12e20 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs @@ -12,7 +12,7 @@ namespace Inno.Rendering.Assets; /// /// Identifies the neutral value stored by a material property. /// -[Inno.Extensibility.Types.StableTypeId("a9af9e77-9a97-5f66-82a0-d720ac5604dc")] +[StableTypeId("a9af9e77-9a97-5f66-82a0-d720ac5604dc")] public enum MaterialValueKind { /// @@ -40,7 +40,7 @@ public enum MaterialValueKind /// /// Stores one native-serializable material value without a GPU binding. /// -[Inno.Extensibility.Types.StableTypeId("dc64bc3e-f26f-55e0-bffe-99e98bd95b4f")] +[StableTypeId("dc64bc3e-f26f-55e0-bffe-99e98bd95b4f")] public struct MaterialValue { private MaterialValue( diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs index a7e2ebe44..e986232d8 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/RenderFeatureConfiguration.cs @@ -12,7 +12,7 @@ namespace Inno.Rendering.Assets; /// /// Stores one ordered feature extension selection using only stable data. /// -[Inno.Extensibility.Types.StableTypeId("aa788bff-6891-5055-8762-899971ba3bed")] +[StableTypeId("aa788bff-6891-5055-8762-899971ba3bed")] public struct RenderFeatureConfiguration { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs index f5348d8f4..b3169e9f5 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionState.cs @@ -12,7 +12,7 @@ namespace Inno.Rendering.Assets; /// /// Stores reload-safe configuration for one pipeline or feature extension generation. /// -[Inno.Extensibility.Types.StableTypeId("8683f095-765d-5aa3-9a9f-fb95777885c5")] +[StableTypeId("8683f095-765d-5aa3-9a9f-fb95777885c5")] public struct SerializedRenderExtensionState { /// @@ -20,8 +20,8 @@ public struct SerializedRenderExtensionState /// public SerializedRenderExtensionState() { - propertyData = []; - dependencies = []; + this.propertyData = []; + this.dependencies = []; } /// @@ -39,7 +39,7 @@ ReadOnlySpan propertyData ) { this.stableTypeId = stableTypeId; this.propertyData = propertyData.ToArray(); - dependencies = []; + this.dependencies = []; } /// @@ -51,9 +51,9 @@ ReadOnlySpan propertyData public SerializedRenderExtensionState(AssetPropertySnapshot properties) { ArgumentNullException.ThrowIfNull(properties); - stableTypeId = properties.stableTypeId; - propertyData = properties.data.ToArray(); - dependencies = properties.dependencies.ToArray(); + this.stableTypeId = properties.stableTypeId; + this.propertyData = properties.data.ToArray(); + this.dependencies = properties.dependencies.ToArray(); } /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs index 36d7551e1..11a6777a2 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Pipelines/SerializedRenderExtensionStateConverter.cs @@ -1,11 +1,13 @@ +using System; using Inno.Assets; using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; -[Inno.Extensibility.Types.StableTypeId("a1b58cb9-3923-52f8-aa05-e9f282e5bdbd")] +[StableTypeId("a1b58cb9-3923-52f8-aa05-e9f282e5bdbd")] internal sealed class SerializedRenderExtensionStateConverter : SerializationConverter { /// @@ -45,7 +47,7 @@ SerializedRenderExtensionState value public override SerializedRenderExtensionState Read(SerializationReader reader) => new() { - stableTypeId = reader.Read("stableTypeId"), + stableTypeId = reader.Read("stableTypeId"), propertyData = reader.Read("propertyData"), dependencies = reader.Read("dependencies") }; diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs index 1c6fc999a..693f26c17 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderAsset.cs @@ -62,15 +62,9 @@ SerializationContext context } [OnSerializableRestored] - private void OnSerializableRestored(SerializationContext context) - { - m_definition = m_definitionData.Length == 0 - ? null - : new ShaderDefinitionSnapshot( - context.GetRequired().Deserialize( - m_definitionData, - context - ) - ); - } + private void OnSerializableRestored(SerializationContext context) => m_definition = m_definitionData.Length == 0 + ? null + : new ShaderDefinitionSnapshot( + context.GetRequired().Deserialize(m_definitionData, context) + ); } diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs index 1226cc70d..62d9b9b63 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderContractId.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Identifies an open shader and pipeline compatibility contract. /// -[Inno.Extensibility.Types.StableTypeId("741c24fb-b13e-5582-98b0-c13e12921fda")] +[StableTypeId("741c24fb-b13e-5582-98b0-c13e12921fda")] public record struct ShaderContractId { /// @@ -44,5 +44,5 @@ public ShaderContractId(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() => value ?? string.Empty; + public override readonly string ToString() => value ?? string.Empty; } diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs index 42b7f09c4..985ebe8cf 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinition.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Contains the source-of-truth definition shared by shader import and material tooling. /// -[Inno.Extensibility.Types.StableTypeId("5bce7c89-203f-5921-8efc-1bca0f364943")] +[StableTypeId("5bce7c89-203f-5921-8efc-1bca0f364943")] public sealed class ShaderDefinition : ISerializable { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs index 421ccc9dd..6872aaa41 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionSnapshot.cs @@ -1,10 +1,11 @@ using System; using System.Linq; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; -[Inno.Extensibility.Types.StableTypeId("3f7f8f3e-f933-57dd-a513-4165386a62ae")] +[StableTypeId("3f7f8f3e-f933-57dd-a513-4165386a62ae")] internal sealed class ShaderDefinitionSnapshot { private readonly ShaderDefinition m_definition; diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs index 6c302a9ca..4bd950745 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDefinitionValidator.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Validates the source-free material, pass and technique contract shared by graph compilation and deployed shaders. /// -[Inno.Extensibility.Types.StableTypeId("196d9066-fe0d-5bd7-b763-0395296f7d88")] +[StableTypeId("196d9066-fe0d-5bd7-b763-0395296f7d88")] public static class ShaderDefinitionValidator { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs index ebc7d7816..6b2b2bfc4 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderDiagnostic.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Reports one structured shader validation or compilation issue. /// -[Inno.Extensibility.Types.StableTypeId("31ce0701-357e-5b45-8364-171f59820d8f")] +[StableTypeId("31ce0701-357e-5b45-8364-171f59820d8f")] public sealed class ShaderDiagnostic { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs index ae4ce540b..3f460f36f 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderKeywordDefinition.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Declares one static shader keyword that may produce compiled variants. /// -[Inno.Extensibility.Types.StableTypeId("551868bd-dbca-5da5-9dd8-d7e6e2ca7983")] +[StableTypeId("551868bd-dbca-5da5-9dd8-d7e6e2ca7983")] public struct ShaderKeywordDefinition { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs index 6bb892cf1..aaeb209df 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderMetadataEntry.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Stores one open metadata key and value. /// -[Inno.Extensibility.Types.StableTypeId("239d558b-cead-5efc-82d8-aee339c78f59")] +[StableTypeId("239d558b-cead-5efc-82d8-aee339c78f59")] public struct ShaderMetadataEntry { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs index ffb53def2..b23bba551 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassDefinition.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Defines one backend-neutral raster or compute shader pass. /// -[Inno.Extensibility.Types.StableTypeId("0f50b92b-4d4b-55f8-a954-953630083303")] +[StableTypeId("0f50b92b-4d4b-55f8-a954-953630083303")] public struct ShaderPassDefinition { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs index 6bec0c349..d2f46eebd 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPassRoleId.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Identifies an open pass purpose defined by a rendering provider. /// -[Inno.Extensibility.Types.StableTypeId("56d381cc-a73a-595b-824c-05191b9ce303")] +[StableTypeId("56d381cc-a73a-595b-824c-05191b9ce303")] public record struct ShaderPassRoleId { /// @@ -44,5 +44,5 @@ public ShaderPassRoleId(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() => value ?? string.Empty; + public override readonly string ToString() => value ?? string.Empty; } diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs index d93add639..2c03ae630 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyBindingOwner.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Identifies which layer supplies a declared shader property's value for each dispatch or draw. /// -[Inno.Extensibility.Types.StableTypeId("0c1a224a-4d13-56de-bda2-93128c1374cb")] +[StableTypeId("0c1a224a-4d13-56de-bda2-93128c1374cb")] public enum ShaderPropertyBindingOwner { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs index 9e36a421d..b622010a8 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderPropertyDefinition.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Declares one shader property and its reflected stage visibility. /// -[Inno.Extensibility.Types.StableTypeId("4b05e49c-b844-535e-aec9-c2201cfdd93f")] +[StableTypeId("4b05e49c-b844-535e-aec9-c2201cfdd93f")] public struct ShaderPropertyDefinition { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs index 22e8147a7..50c411a54 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Selects the triangle face rejected by a raster pass. /// -[Inno.Extensibility.Types.StableTypeId("a0efdb24-2746-512d-aef5-46180c539581")] +[StableTypeId("a0efdb24-2746-512d-aef5-46180c539581")] public enum ShaderCullMode { /// @@ -33,7 +33,7 @@ public enum ShaderCullMode /// /// Selects the comparison used by depth testing. /// -[Inno.Extensibility.Types.StableTypeId("cababee4-46b3-5bd8-800f-46d58149959b")] +[StableTypeId("cababee4-46b3-5bd8-800f-46d58149959b")] public enum ShaderCompareFunction { /// @@ -73,7 +73,7 @@ public enum ShaderCompareFunction /// /// Declares backend-neutral fixed-function state for one shader pass. /// -[Inno.Extensibility.Types.StableTypeId("1ee6df72-41ef-5fd0-a32a-2a8220164675")] +[StableTypeId("1ee6df72-41ef-5fd0-a32a-2a8220164675")] public struct ShaderRenderState { /// @@ -88,7 +88,7 @@ public static ShaderRenderState opaque depthCompare = ShaderCompareFunction.LessEqual, depthWrite = true, blend = RenderBlendState.opaque, - colorWriteMask = 0x0f, + colorWriteMask = 0x0F, multisampling = true }; diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs index 12514d832..2e6524d64 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderSourceLocation.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Assets; /// /// Maps a shader diagnostic back to an asset, pass, stage, and source position. /// -[Inno.Extensibility.Types.StableTypeId("ab6474ed-51d0-570c-b15d-c477b5e9fecc")] +[StableTypeId("ab6474ed-51d0-570c-b15d-c477b5e9fecc")] public readonly record struct ShaderSourceLocation { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs index c8f7c9b74..5863ab987 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueDefinition.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Declares one contract-compatible pass mapping selectable by materials. /// -[Inno.Extensibility.Types.StableTypeId("461d82ac-0279-5044-b17b-776085f2ba35")] +[StableTypeId("461d82ac-0279-5044-b17b-776085f2ba35")] public struct ShaderTechniqueDefinition { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs index d8c2f212b..6083149a9 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniqueId.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Identifies one material-selectable technique in a shader. /// -[Inno.Extensibility.Types.StableTypeId("250032b9-5391-5f1c-a220-c66baf0d15d0")] +[StableTypeId("250032b9-5391-5f1c-a220-c66baf0d15d0")] public record struct ShaderTechniqueId { /// @@ -44,5 +44,5 @@ public ShaderTechniqueId(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() => value ?? string.Empty; + public override readonly string ToString() => value ?? string.Empty; } diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs index 71cae724a..c7f7b31dc 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderTechniquePass.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Maps one provider-defined role to one concrete shader pass. /// -[Inno.Extensibility.Types.StableTypeId("5ca78007-1d3e-53a0-a5e3-dce6b61088b4")] +[StableTypeId("5ca78007-1d3e-53a0-a5e3-dce6b61088b4")] public struct ShaderTechniquePass { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs index 8059326ac..7b8a43630 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/IRenderTextureArtifactSource.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -7,7 +8,7 @@ namespace Inno.Rendering.Assets; /// /// Exposes one or more portable image artifacts owned by an imported asset. /// -[Inno.Extensibility.Types.StableTypeId("a067587f-d6a5-56ed-860b-9ad0c9e1f8cb")] +[StableTypeId("a067587f-d6a5-56ed-860b-9ad0c9e1f8cb")] public interface IRenderTextureArtifactSource { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs index 8c367384d..318401ba6 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactReference.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -7,7 +8,7 @@ namespace Inno.Rendering.Assets; /// /// Identifies one immutable texture source across authoring, deployment, and runtime generations. /// -[Inno.Extensibility.Types.StableTypeId("045f13ba-3cc0-5470-b025-08f9febf40e6")] +[StableTypeId("045f13ba-3cc0-5470-b025-08f9febf40e6")] public readonly record struct RenderTextureArtifactReference { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs index ce6a832f5..af830f9bb 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/RenderTextureArtifactSlot.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Assets; @@ -7,7 +8,7 @@ namespace Inno.Rendering.Assets; /// /// Declares an immutable source artifact that is compiled into one sampled texture slot. /// -[Inno.Extensibility.Types.StableTypeId("e1b8347a-2b49-5793-b693-f32aba02030e")] +[StableTypeId("e1b8347a-2b49-5793-b693-f32aba02030e")] public readonly record struct RenderTextureArtifactSlot { /// diff --git a/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs b/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs index 7bd6a3303..6d752c34f 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Textures/TextureColorSpace.cs @@ -13,7 +13,7 @@ namespace Inno.Rendering.Assets; /// /// Selects how texture samples are decoded for shader use. /// -[Inno.Extensibility.Types.StableTypeId("da42452c-1c45-5a09-8040-e72e37c00361")] +[StableTypeId("da42452c-1c45-5a09-8040-e72e37c00361")] public enum TextureColorSpace { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs index 5b141337a..ec4471161 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Deployment/ContentRenderTargetArtifactProvider.cs @@ -24,15 +24,15 @@ public sealed class ContentRenderTargetArtifactProvider : IRenderTargetArtifactP /// /// The verified immutable content store, borrowed for this provider's lifetime. /// - /// - /// A required content or serialization service is null. - /// /// /// The runtime owner serialization registry. /// /// /// Complete runtime asset/reference context used to resolve captured texture defaults. /// + /// + /// A required content or serialization service is null. + /// public ContentRenderTargetArtifactProvider( IRuntimeContentStore content, SerializationRegistry serialization, @@ -172,7 +172,7 @@ private byte[] ReadContent(ContentKey key) throw new InvalidDataException($"Target artifact '{key}' exceeds the managed payload limit."); } using Stream stream = lease.OpenRead(); - byte[] bytes = new byte[checked((int)lease.entry.length)]; + var bytes = new byte[checked((int)lease.entry.length)]; stream.ReadExactly(bytes); if (stream.ReadByte() != -1) { diff --git a/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs index 8251668d4..4007af118 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Deployment/IRenderTargetArtifactProvider.cs @@ -1,4 +1,5 @@ using System; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -7,7 +8,7 @@ namespace Inno.Rendering.Runtime; /// /// Resolves immutable, source-free target artifacts for the active rendering device. /// -[Inno.Extensibility.Types.StableTypeId("44afaaec-de0d-543a-904d-90a09db07e36")] +[StableTypeId("44afaaec-de0d-543a-904d-90a09db07e36")] public interface IRenderTargetArtifactProvider { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs b/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs index 7a1f4b15a..c06f58b48 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Deployment/RenderTargetArtifactStatus.cs @@ -1,3 +1,4 @@ +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -5,7 +6,7 @@ namespace Inno.Rendering.Runtime; /// /// Describes the current availability of one target-specific rendering artifact. /// -[Inno.Extensibility.Types.StableTypeId("f3865bb4-5ff5-55c1-a910-27d7a65f84f2")] +[StableTypeId("f3865bb4-5ff5-55c1-a910-27d7a65f84f2")] public enum RenderTargetArtifactStatus { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs index a9292363b..7a41acfeb 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs @@ -1,6 +1,7 @@ using System; using System.Threading; using Inno.Core.Execution; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Runtime; /// /// Exposes current rendering configuration and immutable device state. /// -[Inno.Extensibility.Types.StableTypeId("6310eecc-3492-572c-a2f7-e29ec16e65b9")] +[StableTypeId("6310eecc-3492-572c-a2f7-e29ec16e65b9")] public static class GraphicsSettings { /// @@ -32,7 +33,7 @@ public static RenderPipelineAsset? defaultPipeline public static RenderFrameStatistics? frameStatistics => GraphicsSettingsExecutionContext.currentOrNull?.frameStatistics; } -[Inno.Extensibility.Types.StableTypeId("1af0f9ea-f6cf-544c-a2c5-0c3c306c6780")] +[StableTypeId("1af0f9ea-f6cf-544c-a2c5-0c3c306c6780")] internal sealed class GraphicsSettingsState { private readonly object m_sync = new(); @@ -92,7 +93,7 @@ internal void Clear() } } -[Inno.Extensibility.Types.StableTypeId("0f145d08-b261-54bf-92aa-5ee6605d819e")] +[StableTypeId("0f145d08-b261-54bf-92aa-5ee6605d819e")] internal static class GraphicsSettingsExecutionContext { private static readonly ExecutionSlot S_CURRENT = new("state"); diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs index 14d2e0fb1..067bcb1f9 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IRenderModel.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; using Inno.References; using Inno.Rendering; using Inno.Rendering.Assets; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Runtime; /// /// Builds view requests from host output sessions without owning a host window. /// -[Inno.Extensibility.Types.StableTypeId("52f335d4-64e4-5a11-96f3-c52e44295830")] +[StableTypeId("52f335d4-64e4-5a11-96f3-c52e44295830")] public interface IRenderModel : IDisposable { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs index 51ed88f00..872755142 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelExtensionAttribute.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; using Inno.References; using Inno.Rendering; using Inno.Rendering.Assets; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// Marks a reloadable rendering model with a stable identity. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[Inno.Extensibility.Types.StableTypeId("eccab85a-0b21-55e1-b581-885c4bbc5192")] +[StableTypeId("eccab85a-0b21-55e1-b581-885c4bbc5192")] public sealed class RenderModelExtensionAttribute : Attribute { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs index a3db0a3ec..e5c6f3b16 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderModelOutput.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; using Inno.References; using Inno.Rendering; using Inno.Rendering.Assets; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Runtime; /// /// Gets one model's prepared pipeline data for a host-owned target. /// -[Inno.Extensibility.Types.StableTypeId("3954390f-0d08-5114-82e4-5e35aa777472")] +[StableTypeId("3954390f-0d08-5114-82e4-5e35aa777472")] public sealed class RenderModelOutput { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs index 615c7859c..7e66f1a95 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputInput.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Inno.Core.Input; using Inno.Core.Mathematics; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Runtime; /// /// Frame-local input located in the output viewport's physical pixels. /// -[Inno.Extensibility.Types.StableTypeId("0fe2e29e-4826-5e41-9ebd-a3110e673b5e")] +[StableTypeId("0fe2e29e-4826-5e41-9ebd-a3110e673b5e")] public sealed class RenderOutputInput { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs index ee02a6da9..e11e464ef 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputLayer.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; using Inno.References; using Inno.Rendering; using Inno.Rendering.Assets; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Runtime; /// /// Assigns exactly one rendering model and its world-content sources to an output layer. /// -[Inno.Extensibility.Types.StableTypeId("7bdfe53d-72a0-5e9a-a922-fbc52362618f")] +[StableTypeId("7bdfe53d-72a0-5e9a-a922-fbc52362618f")] public sealed class RenderOutputLayer { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs index ceefcea55..d4df36caf 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputRoute.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; using Inno.References; using Inno.Rendering; using Inno.Rendering.Assets; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Runtime; /// /// States the exact model order and exclusive world-content assignment for one output. /// -[Inno.Extensibility.Types.StableTypeId("313e9d03-9423-53a6-8dd8-f4faad999439")] +[StableTypeId("313e9d03-9423-53a6-8dd8-f4faad999439")] public sealed class RenderOutputRoute { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs index 82d9cfd34..dcb3ae417 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderOutputSession.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Extensibility.Types; using Inno.References; using Inno.Rendering; using Inno.Rendering.Assets; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Runtime; /// /// Declares a host output without naming a camera or scene model. /// -[Inno.Extensibility.Types.StableTypeId("18d40f92-089a-5c0e-94a9-402b68225c2b")] +[StableTypeId("18d40f92-089a-5c0e-94a9-402b68225c2b")] public sealed class RenderOutputSession { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs index 8d8ec6f7b..b3fdec77f 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using Inno.Core.Identity; using Inno.Core.Mathematics; +using Inno.Extensibility.Types; using Inno.References; using Inno.Rendering; @@ -10,7 +11,7 @@ namespace Inno.Rendering.Runtime; /// /// Describes one backend-neutral view produced by a rendering model. /// -[Inno.Extensibility.Types.StableTypeId("eb2ef876-46a8-5155-8c45-c96b14ad2043")] +[StableTypeId("eb2ef876-46a8-5155-8c45-c96b14ad2043")] public readonly record struct RenderView { /// @@ -75,7 +76,7 @@ public RenderView( /// /// Supplies one content source with the host-selected scene roots and an exact view. /// -[Inno.Extensibility.Types.StableTypeId("733a6b3a-4cec-5734-83c3-261f0e34b6f8")] +[StableTypeId("733a6b3a-4cec-5734-83c3-261f0e34b6f8")] public sealed class ViewContentContext { /// @@ -170,7 +171,7 @@ public ViewContentContext( /// /// Prepares one model-independent drawable for a specific render pass. /// -[Inno.Extensibility.Types.StableTypeId("796c6186-c301-5cb2-a634-d03f8156a039")] +[StableTypeId("796c6186-c301-5cb2-a634-d03f8156a039")] public interface IViewDrawable { /// @@ -198,7 +199,7 @@ out IPreparedViewDrawable? prepared /// /// Encodes a resource-ready draw into the owning model's scene pass. /// -[Inno.Extensibility.Types.StableTypeId("d17ebef7-c2f5-543e-ad05-c38c6396ac3b")] +[StableTypeId("d17ebef7-c2f5-543e-ad05-c38c6396ac3b")] public interface IPreparedViewDrawable { /// @@ -213,7 +214,7 @@ public interface IPreparedViewDrawable /// /// Receives pointer input after the rendering model resolves visible draw order. /// -[Inno.Extensibility.Types.StableTypeId("8d770d54-025c-591a-b49e-9c12c4bde162")] +[StableTypeId("8d770d54-025c-591a-b49e-9c12c4bde162")] public interface IViewPointerTarget { /// @@ -278,7 +279,7 @@ ulong frameIndex /// /// One world item supplied to a rendering model without choosing its sort policy. /// -[Inno.Extensibility.Types.StableTypeId("4aecd31e-d107-56b4-bc92-e07bc89c125b")] +[StableTypeId("4aecd31e-d107-56b4-bc92-e07bc89c125b")] public sealed class ViewContentItem { /// @@ -352,7 +353,7 @@ public ViewContentItem( /// /// Receives world items without imposing a rendering-model sort key. /// -[Inno.Extensibility.Types.StableTypeId("ee4aa3b7-c773-5f05-9655-5a3cfd457c26")] +[StableTypeId("ee4aa3b7-c773-5f05-9655-5a3cfd457c26")] public interface IViewContentSink { /// @@ -367,7 +368,7 @@ public interface IViewContentSink /// /// Contributes model-independent world items to selected views. /// -[Inno.Extensibility.Types.StableTypeId("638698ee-7dd9-5d75-92aa-84a2457ed3f0")] +[StableTypeId("638698ee-7dd9-5d75-92aa-84a2457ed3f0")] public interface IViewContentSource : IDisposable { /// @@ -388,7 +389,7 @@ IViewContentSink sink /// /// Completes frame-local input after every output has routed its views. /// -[Inno.Extensibility.Types.StableTypeId("9242bf1f-a6dc-555f-ab73-494c7a7acc70")] +[StableTypeId("9242bf1f-a6dc-555f-ab73-494c7a7acc70")] public interface IViewContentFrameSource { /// @@ -404,7 +405,7 @@ public interface IViewContentFrameSource /// Discovers an independently reloadable world-content source. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[Inno.Extensibility.Types.StableTypeId("9e766605-2b84-5040-858e-ae84b6a5e7c3")] +[StableTypeId("9e766605-2b84-5040-858e-ae84b6a5e7c3")] public sealed class ViewContentSourceExtensionAttribute : Attribute { /// @@ -428,7 +429,7 @@ public ViewContentSourceExtensionAttribute(string id) /// /// Collects all active world-content sources for one exact view. /// -[Inno.Extensibility.Types.StableTypeId("b8d46505-dda2-52b6-b3c8-133e48641fed")] +[StableTypeId("b8d46505-dda2-52b6-b3c8-133e48641fed")] public interface IViewContentCollector { /// @@ -446,7 +447,7 @@ public interface IViewContentCollector /// /// Restricts a neutral world-content collector to an output layer's source IDs. /// -[Inno.Extensibility.Types.StableTypeId("f4217ba1-0650-58be-8e76-d6f2c2c303c5")] +[StableTypeId("f4217ba1-0650-58be-8e76-d6f2c2c303c5")] public sealed class SelectedViewContentCollector : IViewContentCollector { private readonly IViewContentCollector m_inner; diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs index 3e2782d6d..24c23b8b7 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderExtensionStateContext.cs @@ -1,6 +1,7 @@ using System; using Inno.Assets; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Runtime; /// /// Restores neutral render settings through the canonical asset's actual owner and pinned references. /// -[Inno.Extensibility.Types.StableTypeId("ad67f148-af5b-5383-ac2d-55a34e305e96")] +[StableTypeId("ad67f148-af5b-5383-ac2d-55a34e305e96")] public sealed class RenderExtensionStateContext { private readonly AssetObject m_owner; @@ -23,7 +24,10 @@ public sealed class RenderExtensionStateContext /// /// It must not outlive the asset generation. Authoring captures use the asset system's property snapshots. /// - public RenderExtensionStateContext(AssetObject owner) => m_owner = owner ?? throw new ArgumentNullException(nameof(owner)); + public RenderExtensionStateContext(AssetObject owner) + { + m_owner = owner ?? throw new ArgumentNullException(nameof(owner)); + } /// /// Restores a matching settings contract with this owner's asset references. diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs index 77a4dd6d5..471436dba 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureContext.cs @@ -3,6 +3,7 @@ using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Runtime; /// /// Supplies one configured feature with frame-scoped graph services. /// -[Inno.Extensibility.Types.StableTypeId("00810cb8-162a-5a95-9a30-1a01992ac501")] +[StableTypeId("00810cb8-162a-5a95-9a30-1a01992ac501")] public sealed class RenderFeatureContext { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs index d7ee8227f..be750bd93 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderFeatureExtensionAttribute.cs @@ -3,6 +3,7 @@ using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// Marks a reloadable pipeline feature implementation with a stable extension identifier. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[Inno.Extensibility.Types.StableTypeId("f290f8ca-3a8b-5e90-aa2d-1b0a541cd95a")] +[StableTypeId("f290f8ca-3a8b-5e90-aa2d-1b0a541cd95a")] public sealed class RenderFeatureExtensionAttribute : Attribute { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs index 5da784f06..0def80389 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipeline.cs @@ -3,6 +3,7 @@ using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Runtime; /// /// Builds frame-local passes without prescribing a rendering model. /// -[Inno.Extensibility.Types.StableTypeId("f3736feb-4238-54b6-9fe9-c40ffb095134")] +[StableTypeId("f3736feb-4238-54b6-9fe9-c40ffb095134")] public abstract class RenderPipeline : IDisposable { private bool m_disposed; diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs index d33e80860..a38577d66 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineContext.cs @@ -3,6 +3,7 @@ using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Runtime; /// /// Supplies one request and frame-scoped services to a render pipeline. /// -[Inno.Extensibility.Types.StableTypeId("fe6c1616-212d-521e-b4ab-9e61a72b9c45")] +[StableTypeId("fe6c1616-212d-521e-b4ab-9e61a72b9c45")] public sealed class RenderPipelineContext { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs index 730b1734c..76c84fdbb 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineExtensionAttribute.cs @@ -3,6 +3,7 @@ using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// Marks a reloadable render pipeline implementation with a stable extension identifier. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[Inno.Extensibility.Types.StableTypeId("bbaa3835-1ee7-5e0f-b690-304d4f6f98ed")] +[StableTypeId("bbaa3835-1ee7-5e0f-b690-304d4f6f98ed")] public sealed class RenderPipelineExtensionAttribute : Attribute { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs index 0d6cae0a2..ab6448e42 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderPipelineFeature.cs @@ -3,6 +3,7 @@ using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Runtime; /// /// Adds capability-aware passes without owning frame graph state. /// -[Inno.Extensibility.Types.StableTypeId("a16b9e1e-2bf1-5ba4-85aa-ee24ebda097b")] +[StableTypeId("a16b9e1e-2bf1-5ba4-85aa-ee24ebda097b")] public abstract class RenderPipelineFeature { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs index c41cba01b..b5b77ff3b 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Pipelines/RenderResourceMap.cs @@ -3,6 +3,7 @@ using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Serialization; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -11,7 +12,7 @@ namespace Inno.Rendering.Runtime; /// /// Stores open semantic graph resources for one pipeline request. /// -[Inno.Extensibility.Types.StableTypeId("f48ab8a3-a1f2-513a-9e4b-396be0f084a8")] +[StableTypeId("f48ab8a3-a1f2-513a-9e4b-396be0f084a8")] public sealed class RenderResourceMap { private readonly Dictionary m_textures = []; diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs index feb774166..749900aa2 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderExtensionRegistry.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; @@ -59,9 +60,7 @@ internal void EnsureHealthy() protected override void OnCleanupFailed( string phase, Exception exception - ) { - m_retirementFailure ??= exception; - } + ) => m_retirementFailure ??= exception; /// /// Builds a validated result from the current immutable input snapshot. @@ -110,8 +109,8 @@ protected override Snapshot Build(TypeCacheSnapshot types) internal static string GetConfigurationFingerprint(RenderPipelineAsset asset) { ArgumentNullException.ThrowIfNull(asset); - using var stream = new System.IO.MemoryStream(); - using var writer = new System.IO.BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); writer.Write(asset.pipelineTypeId ?? string.Empty); WriteState(writer, asset.pipelineState); foreach (RenderFeatureConfiguration feature in asset.features) @@ -125,7 +124,7 @@ internal static string GetConfigurationFingerprint(RenderPipelineAsset asset) } private static void WriteState( - System.IO.BinaryWriter writer, + BinaryWriter writer, SerializedRenderExtensionState state ) { writer.Write(state.stableTypeId.ToByteArray()); @@ -195,16 +194,16 @@ internal Snapshot( Action retire ) { m_types = types; - typeCacheVersion = types.version; + this.typeCacheVersion = types.version; m_pipelines = pipelines; m_features = features; m_requestProviders = requestProviders; m_contentSources = contentSources; m_renderModels = renderModels; m_retire = retire; - providers = CreateRequestProviders(createProvider); - sources = CreateContentSources(createSource); - models = CreateRenderModels(createModel); + this.providers = CreateRequestProviders(createProvider); + this.sources = CreateContentSources(createSource); + this.models = CreateRenderModels(createModel); } internal long typeCacheVersion { get; } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs index 1f4abf9bf..54c28c7e4 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs @@ -4,7 +4,7 @@ namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { private sealed class RenderFrameScratch { diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameStatistics.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameStatistics.cs index 87a883182..adb711059 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameStatistics.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameStatistics.cs @@ -1,4 +1,5 @@ using System; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -6,7 +7,7 @@ namespace Inno.Rendering.Runtime; /// /// Reports read-only statistics for the most recently completed render frame. /// -[Inno.Extensibility.Types.StableTypeId("f3924117-1829-5885-9f93-9010066fed48")] +[StableTypeId("f3924117-1829-5885-9f93-9010066fed48")] public sealed class RenderFrameStatistics { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs index df5e0c4af..4cf2f2b13 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderFrameUploadService.cs @@ -104,7 +104,7 @@ string name ); PersistentBufferHandle handle = m_device.CreateBuffer( bufferDescriptor, - ReadOnlySpan.Empty, + [], $"{name}/FrameUpload[{pool.pages.Count}]" ); page = new UploadPage(handle, capacity, bytes); diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs index 964b062d1..ebe9a5e63 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderLayerCompositor.cs @@ -260,7 +260,7 @@ RenderPassContext context private static byte[] CreateVertices(bool originBottomLeft) { - byte[] bytes = new byte[4 * 20]; + var bytes = new byte[4 * 20]; float top = originBottomLeft ? 1f : 0f; float bottom = originBottomLeft ? 0f : 1f; WriteVertex(0, -1f, 1f, 0f, top); diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs index 339f54375..333dc85c1 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderMaterialOwner.cs @@ -50,7 +50,7 @@ internal int count get { int result = 0; - foreach (var pair in m_programs) + foreach (KeyValuePair pair in m_programs) { result += pair.Value.programs.Count; } @@ -280,7 +280,7 @@ internal void ReleaseScope(string scope) internal bool HasScope(string scope) { - foreach (var pair in m_programs) + foreach (KeyValuePair pair in m_programs) { if (pair.Key.scope == scope) { @@ -294,7 +294,7 @@ private ArtifactResult QueryArtifact( ShaderAsset shader, RenderShaderVariant variant ) { - var key = new LookupKey(shader.identity.persistentId, variant.value, ""); + var key = new LookupKey(shader.identity.persistentId, variant.value, string.Empty); if (m_frameArtifacts.TryGetValue(key, out ArtifactResult result)) { return result; @@ -562,7 +562,9 @@ RenderShaderVariant variant throw new InvalidOperationException(diagnostic.message); } } - var properties = definition.properties.ToDictionary(static property => property.id); + Dictionary properties = definition.properties.ToDictionary( + static property => property.id + ); foreach (RenderShaderPassArtifact pass in artifact.passes) { ShaderPassDefinition declared = definition.passes.SingleOrDefault(value => value.name == pass.name); @@ -602,7 +604,10 @@ private void DrainFailed() } if (m_failedCleanupFailures.Count != 0) { - var failure = new AggregateException("Rejected shader publications retired with completed failures.", m_failedCleanupFailures); + var failure = new AggregateException( + "Rejected shader publications retired with completed failures.", + m_failedCleanupFailures + ); m_failedCleanupFailures.Clear(); throw failure; } @@ -739,7 +744,7 @@ static int Next(HashSet used) } foreach (ShaderInterfaceBinding binding in shaderInterface.bindings) { - RenderBindingId id = new(binding.id.value); + var id = new RenderBindingId(binding.id.value); switch (binding.bindingKind) { case ShaderPropertyBindingKind.Uniform: diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs index 7dced018f..97c25a1e5 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderPipelineGeneration.cs @@ -16,7 +16,7 @@ RenderPipeline pipeline ) { this.typeCacheVersion = typeCacheVersion; this.pipeline = m_lifetime.Own(pipeline); - features = new ReadOnlyDictionary(m_features); + this.features = new ReadOnlyDictionary(m_features); } internal long typeCacheVersion { get; } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs index 72066929f..e2dc0f6f2 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceLimits.cs @@ -10,7 +10,7 @@ public sealed class RenderResourceLimits /// /// Gets the maximum active entries in each buffer, texture or pipeline cache. /// - public int resourcesPerKind { get; init; } = 16384; + public int resourcesPerKind { get; init; } = 16_384; /// /// Gets the maximum readbacks that can retain GPU resources before owner-thread completion. diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs index 18a5d3ff4..0ebf30400 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderResourceService.cs @@ -603,7 +603,7 @@ out PersistentTextureHandle resolvedTexture return false; } - RenderPersistentResourceId resourceId = new($"asset:{texture.assetId:D}:texture:{texture.slot.id}"); + var resourceId = new RenderPersistentResourceId($"asset:{texture.assetId:D}:texture:{texture.slot.id}"); bool sRgb = texture.slot.colorSpace == TextureColorSpace.Srgb; if (m_textures.TryGetValue(resourceId, out TextureEntry? current) && current.kind == TextureEntryKind.Ktx @@ -834,10 +834,7 @@ public void Dispose() CompleteRetirement(); } - private void CompleteRetirement() - { - m_disposed = true; - } + private void CompleteRetirement() => m_disposed = true; internal RenderResourceStatistics statistics => new() diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs index fc2d4a1b5..a8485b2d1 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRetirementQueue.cs @@ -43,7 +43,10 @@ public void Dispose() } if (m_failures.Count > 0) { - var failure = new AggregateException("Rendering retirement failed after all quiescent owners were attempted.", m_failures); + var failure = new AggregateException( + "Rendering retirement failed after all quiescent owners were attempted.", + m_failures + ); m_failures.Clear(); throw failure; } diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs index 4bbc7081b..c8aff7251 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Contributors.cs @@ -14,7 +14,7 @@ namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Registers frame-final work without transferring frame ownership. diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs index 2cd87afaa..2212e6d35 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Diagnostics.cs @@ -14,12 +14,10 @@ namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { private void PublishModelDiagnostic(string message) - { - PublishFrameIssue(new Diagnostic("RENDER_OUTPUT_MODEL_UNAVAILABLE", message, DiagnosticSeverity.Warning)); - } + => PublishFrameIssue(new Diagnostic("RENDER_OUTPUT_MODEL_UNAVAILABLE", message, DiagnosticSeverity.Warning)); private void PublishFrameIssue(Diagnostic diagnostic) { diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs index 142076a5b..d4c435b51 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Frames.cs @@ -14,7 +14,7 @@ namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Captures snapshots and binds service façades. diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs index e2fe64885..ebb5ee15f 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Models.cs @@ -14,7 +14,7 @@ namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Sets the explicit model composition route for the primary output at a frame boundary. diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs index 3030ee434..7fd55e13c 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Pipelines.cs @@ -14,7 +14,7 @@ namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Validates and selects a project default while preserving its last-good generation. diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs index 8c08175e4..5fe7b20b9 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Presentation.cs @@ -14,7 +14,7 @@ namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { private RenderViewport ResolvePrimaryPresentationViewport(RenderPresentationSize size) { diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs index 6862eb191..e989cd229 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Requests.cs @@ -14,7 +14,7 @@ namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Submits validated work to the active backend for ordered processing. @@ -197,10 +197,7 @@ private bool TryBuildRequest( } } - private void EnsureRequestProviders() - { - m_requestProviders = m_extensions.extensions.providers; - } + private void EnsureRequestProviders() => m_requestProviders = m_extensions.extensions.providers; private sealed record CompositionRequest( string name, diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs index 2b9e3dfcb..131780e8b 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.Retirement.cs @@ -14,7 +14,7 @@ namespace Inno.Rendering.Runtime; -sealed partial class RenderRuntime +public sealed partial class RenderRuntime { /// /// Detaches this feature and releases generation-scoped state. diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs index 198bb809b..0651a025a 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.cs @@ -68,12 +68,12 @@ public sealed partial class RenderRuntime : RuntimeSubsystem, IRenderRequestSink /// /// Creates a render runtime without installing any concrete pipeline. /// - /// - /// Active backend-neutral device. - /// /// /// The type catalog that owns render extension generations. /// + /// + /// Active backend-neutral device. + /// /// /// Owner-bound structured diagnostic producer. /// @@ -91,10 +91,6 @@ public sealed partial class RenderRuntime : RuntimeSubsystem, IRenderRequestSink /// Optional host callback that selects the content region within the primary presentation surface. /// The complete surface is used when omitted. /// - /// - /// The contributor sequence contains a null entry or the same contributor more than once. - /// No rendering generation is registered in this case. - /// /// /// Finite native cache and asynchronous readback limits; omitted values use the engine defaults. /// @@ -107,6 +103,10 @@ public sealed partial class RenderRuntime : RuntimeSubsystem, IRenderRequestSink /// /// Backend-specific program provider used when the host composites multiple render layers. /// + /// + /// The contributor sequence contains a null entry or the same contributor more than once. + /// No rendering generation is registered in this case. + /// public RenderRuntime( TypeCatalog types, IRenderDevice device, @@ -146,7 +146,7 @@ public RenderRuntime( m_resourceService = new RenderResourceService(m_device, m_diagnostics, targetArtifacts, resourceLimits); m_uploads = new RenderFrameUploadService(m_device, resourceLimits); m_compositor = new RenderLayerCompositor(m_device, compositionProgramProvider); - targets = new RenderTargetStore(device, resourceLimits.targets); + this.targets = new RenderTargetStore(device, resourceLimits.targets); } /// @@ -254,10 +254,7 @@ public IDisposable EnterExecutionScope() /// /// Attaches this feature to its owning runtime generation. /// - protected override void OnStart() - { - EnsureActive(); - } + protected override void OnStart() => EnsureActive(); private void EnsureActive() { diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs index abaf25f73..86a36c232 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/IRenderRequestSink.cs @@ -1,4 +1,5 @@ using System; +using Inno.Extensibility.Types; using Inno.Rendering; namespace Inno.Rendering.Runtime; @@ -6,7 +7,7 @@ namespace Inno.Rendering.Runtime; /// /// Accepts rendering-model-neutral requests without exposing runtime or backend ownership. /// -[Inno.Extensibility.Types.StableTypeId("53812496-61bc-5128-8cf9-2865a9319980")] +[StableTypeId("53812496-61bc-5128-8cf9-2865a9319980")] public interface IRenderRequestSink { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs index 30b41ac65..f3e513090 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderFrameData.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// Values may use reloadable plugin types because a snapshot is retained only until the owning /// render frame completes. Persistent configuration must use stable identifiers and serialized bytes. /// -[Inno.Extensibility.Types.StableTypeId("08a1cd24-757d-5026-a05d-a72ab9fd2b2b")] +[StableTypeId("08a1cd24-757d-5026-a05d-a72ab9fd2b2b")] public sealed class RenderFrameData { private readonly Dictionary m_values = []; @@ -39,7 +40,7 @@ public sealed class RenderFrameData /// Thrown after the data has entered a request. /// public void Set( - Inno.Rendering.RenderDataChannelId channel, + RenderDataChannelId channel, TValue value ) where TValue : notnull { @@ -71,7 +72,7 @@ TValue value /// when the channel contains the exact requested type. /// public bool TryGet( - Inno.Rendering.RenderDataChannelId channel, + RenderDataChannelId channel, out TValue? value ) { if (channel.isValid @@ -113,7 +114,7 @@ internal RenderFrameData Snapshot() } private readonly record struct FrameDataKey( - Inno.Rendering.RenderDataChannelId channel, + RenderDataChannelId channel, Type type ); } diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs index 5f5cdec4b..257be2e3c 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequest.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -8,7 +9,7 @@ namespace Inno.Rendering.Runtime; /// /// Requests one pipeline-defined rendering operation without prescribing world semantics. /// -[Inno.Extensibility.Types.StableTypeId("b553fd8c-9410-53a7-8d8f-276e2a302e66")] +[StableTypeId("b553fd8c-9410-53a7-8d8f-276e2a302e66")] public sealed class RenderRequest { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs index 8470fff18..5136e17d6 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs @@ -1,5 +1,6 @@ using System; using Inno.Core.Execution; +using Inno.Extensibility.Types; using Inno.References; using Inno.Rendering; @@ -9,7 +10,7 @@ namespace Inno.Rendering.Runtime; /// Marks a reloadable provider that produces model-neutral render requests each frame. /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[Inno.Extensibility.Types.StableTypeId("54ca2eb2-0fc2-5b3e-91d1-0bd52d01caab")] +[StableTypeId("54ca2eb2-0fc2-5b3e-91d1-0bd52d01caab")] public sealed class RenderRequestProviderExtensionAttribute : Attribute { /// @@ -44,7 +45,7 @@ public RenderRequestProviderExtensionAttribute( /// /// Supplies frame timing, capabilities and the request sink to one provider invocation. /// -[Inno.Extensibility.Types.StableTypeId("67067617-9592-55b2-bbb0-739c6927984b")] +[StableTypeId("67067617-9592-55b2-bbb0-739c6927984b")] public sealed class RenderRequestProviderContext { /// @@ -162,7 +163,7 @@ public RenderRequestProviderContext( /// /// Produces arbitrary render requests without prescribing a scene or rendering model. /// -[Inno.Extensibility.Types.StableTypeId("5c4302ea-8da5-5627-8fbe-f34ee7b2aec1")] +[StableTypeId("5c4302ea-8da5-5627-8fbe-f34ee7b2aec1")] public abstract class RenderRequestProvider : IDisposable { private bool m_disposed; diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs index 4f76fca8a..82a1f5981 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/IRenderResourceService.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// /// Resolves neutral assets and provider-owned uploads into opaque resources for the active device generation. /// -[Inno.Extensibility.Types.StableTypeId("8f112b16-5cda-5171-949e-e2c5c4583b34")] +[StableTypeId("8f112b16-5cda-5171-949e-e2c5c4583b34")] public interface IRenderResourceService { /// @@ -409,10 +410,12 @@ out PersistentTextureHandle resolvedTexture /// /// Releases cached resources with this provider-owned identifier at a safe GPU mutation point. /// - /// Calls between frames or during graph execution queue neutral identities until the next frame; - /// runtime shutdown also retires them. Calls must occur on the rendering owner thread. Unused identities are ignored. /// /// Stable resource identifier to release. /// + /// + /// Calls between frames or during graph execution queue neutral identities until the next frame; + /// runtime shutdown also retires them. Calls must occur on the rendering owner thread. Unused identities are ignored. + /// void Release(RenderPersistentResourceId id); } diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs index b56b987b0..431459a33 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometry.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// /// Provides generation-scoped GPU buffers for an imported geometry helper asset. /// -[Inno.Extensibility.Types.StableTypeId("6ad78a05-1eae-5e6f-a5d2-ab40b6c35075")] +[StableTypeId("6ad78a05-1eae-5e6f-a5d2-ab40b6c35075")] public sealed class RenderGeometry { private readonly IReadOnlyList m_sections; diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs index 104b3ccfd..791cfaca2 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderGeometrySection.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// /// Describes one indexed range in resolved backend-neutral geometry. /// -[Inno.Extensibility.Types.StableTypeId("fc4ae91b-3a0b-59d3-b65e-4c0c3533d715")] +[StableTypeId("fc4ae91b-3a0b-59d3-b65e-4c0c3533d715")] public readonly record struct RenderGeometrySection { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs index d14549937..bef37ca12 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs @@ -4,19 +4,20 @@ using System.Threading; using System.Threading.Tasks; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; -[Inno.Extensibility.Types.StableTypeId("b5677cc4-c195-5f52-a52f-5efecec8314e")] +[StableTypeId("b5677cc4-c195-5f52-a52f-5efecec8314e")] internal enum RenderMaterialBindingKind { Uniform, Texture } -[Inno.Extensibility.Types.StableTypeId("702a1ec9-219b-5d44-b322-1a433e7e41b5")] +[StableTypeId("702a1ec9-219b-5d44-b322-1a433e7e41b5")] internal sealed record RenderMaterialBinding( RenderMaterialBindingKind kind, RenderBindingId id, @@ -32,7 +33,7 @@ RenderSamplerState sampler /// The instance is scoped to the active render device generation. Pipeline-owned graph textures and /// buffers remain explicit and are bound by the caller after this material state is applied. /// -[Inno.Extensibility.Types.StableTypeId("b1566a8a-dd0a-5dca-8f43-6bb12aa86973")] +[StableTypeId("b1566a8a-dd0a-5dca-8f43-6bb12aa86973")] public sealed class RenderMaterialPass { private readonly ShaderPassDefinition m_definition; diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs index 946c274f2..422344e16 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderPersistentResourceId.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// /// Identifies one provider-owned persistent GPU resource without exposing a native handle. /// -[Inno.Extensibility.Types.StableTypeId("c060d558-f0f1-5653-a77f-526e6b078507")] +[StableTypeId("c060d558-f0f1-5653-a77f-526e6b078507")] public readonly record struct RenderPersistentResourceId { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs index 37d671d45..6b7253ced 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderResourceProvider.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -13,7 +14,7 @@ namespace Inno.Rendering.Runtime; /// The boundary lets a runtime resource service create generation-scoped values while their mutable /// representation remains private to the Rendering assembly. /// -[Inno.Extensibility.Types.StableTypeId("c06ff3f1-8280-52cc-a57a-8d864eb358c6")] +[StableTypeId("c06ff3f1-8280-52cc-a57a-8d864eb358c6")] public abstract class RenderResourceProvider { /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs index d2feab991..ef2f21f30 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderTextureSubresourceData.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; using Inno.Rendering; using Inno.Rendering.Assets; @@ -12,7 +13,7 @@ namespace Inno.Rendering.Runtime; /// /// Stores one complete texture mip and addressable layer, slice, or cubemap-face upload. /// -[Inno.Extensibility.Types.StableTypeId("22ed6418-30e6-511e-8af3-5d830d3b0ce5")] +[StableTypeId("22ed6418-30e6-511e-8af3-5d830d3b0ce5")] public sealed class RenderTextureSubresourceData { private readonly byte[] m_data; diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs index 5bd7f80d3..46ac33a7b 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerCatalog.cs @@ -36,8 +36,8 @@ public ShaderNodeCompilerCatalog(IEnumerable compilers) throw new ArgumentException($"Duplicate shader node compiler '{compiler.definitionId}'.", nameof(compilers)); } } - providers = Array.AsReadOnly(m_compilers.Values.ToArray()); - definitionIds = Array.AsReadOnly(m_compilers.Keys.Order(StringComparer.Ordinal).ToArray()); + this.providers = Array.AsReadOnly(m_compilers.Values.ToArray()); + this.definitionIds = Array.AsReadOnly(m_compilers.Keys.Order(StringComparer.Ordinal).ToArray()); } /// @@ -136,7 +136,14 @@ public ShaderGraphLoweringResult Lower( } request.sourceModules.TryGetValue(node.id, out ShaderSourceModuleAnalysis? source); request.stageInputs.TryGetValue(node.id, out ShaderIrStageInput? input); - var description = new ShaderNodeDescriptionContext(node, serialization, context, source, request.implementationId, input); + var description = new ShaderNodeDescriptionContext( + node, + serialization, + context, + source, + request.implementationId, + input + ); descriptions.Add(node.id, description); IReadOnlyList describedPorts = compiler.GetPorts(description).ToArray(); nodePorts.Add(node.id, describedPorts); @@ -164,9 +171,12 @@ public ShaderGraphLoweringResult Lower( var connections = new Dictionary(); var inputDefaults = new Dictionary(); - var nodeConnections = nodes.ToDictionary(static node => node.id, static _ => new List<(string port, GraphEndpoint source)>()); + Dictionary> nodeConnections = nodes.ToDictionary( + static node => node.id, + static _ => new List<(string port, GraphEndpoint source)>() + ); var incoming = new int[nodes.Count]; - var following = Enumerable.Range(0, nodes.Count).Select(static _ => new List()).ToArray(); + List[] following = Enumerable.Range(0, nodes.Count).Select(static _ => new List()).ToArray(); foreach (GraphEdgeRecord edge in request.graph.edges) { if (!ports.TryGetValue(edge.input, out ShaderNodePort? input) || input.direction != GraphPortDirection.Input) diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs index 0e0930d5e..46af855ac 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompilerRegistry.cs @@ -22,7 +22,10 @@ public sealed class ShaderNodeCompilerRegistry : TypeRegistry public ShaderNodeCompilerRegistry(TypeCatalog types) - : base(types) => m_types = types; + : base(types) + { + m_types = types; + } /// /// Gets stable compiler identities without exposing provider instances. diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs index b0be3f145..07ce1d987 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphBindings.cs @@ -56,7 +56,7 @@ SerializationContext context .ToHashSet(StringComparer.Ordinal); foreach (GraphNodeRecord node in graph.nodes) { - if (stages.Contains(ShaderGraphDocument.Read(node, "stage", "", serialization, context))) + if (stages.Contains(ShaderGraphDocument.Read(node, "stage", string.Empty, serialization, context))) { removed.Add(node.id); } @@ -81,8 +81,9 @@ SerializationContext context } foreach (GraphNodeRecord node in graph.nodes) { - if (stages.Contains(node.id.value) || stages.Contains(ShaderGraphDocument.Read(node, "stage", "", serialization, context))) - { + if (stages.Contains(node.id.value) + || stages.Contains(ShaderGraphDocument.Read(node, "stage", string.Empty, serialization, context)) + ) { removed.Add(node.id); } } @@ -101,7 +102,7 @@ SerializationContext context { affectedBindings.Add(input.id); } - affectedBindings.Add(ShaderGraphDocument.Read(node, "bindingIdentity", "", serialization, context)); + affectedBindings.Add(ShaderGraphDocument.Read(node, "bindingIdentity", string.Empty, serialization, context)); } foreach (GraphNodeId id in removed) { @@ -131,13 +132,13 @@ SerializationContext context context ); string id = string.IsNullOrWhiteSpace(input.id) - ? ShaderGraphDocument.Read(node, "bindingIdentity", "", serialization, context) + ? ShaderGraphDocument.Read(node, "bindingIdentity", string.Empty, serialization, context) : input.id; if (!IsBinding(input) || !affectedBindings.Contains(id)) { continue; } - string stageId = ShaderGraphDocument.Read(node, "stage", "", serialization, context); + string stageId = ShaderGraphDocument.Read(node, "stage", string.Empty, serialization, context); GraphNodeRecord? output = string.IsNullOrWhiteSpace(stageId) ? null : candidate.FindNode(new(stageId)); ShaderStage stage = output is null ? ShaderStage.None @@ -212,11 +213,11 @@ SerializationContext context // Keep the last declared identity through incomplete text input; clearing a name must not erase its default value. if (string.IsNullOrWhiteSpace(previous.id)) { - previous.id = ShaderGraphDocument.Read(node, "bindingIdentity", "", serialization, context); + previous.id = ShaderGraphDocument.Read(node, "bindingIdentity", string.Empty, serialization, context); } node.SetValue("settings", ShaderGraphDocument.Encode(settings, serialization, context)); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(candidate, serialization, context); - var properties = definition.properties.ToList(); + List properties = definition.properties.ToList(); ShaderPropertyDefinition? previousProperty = properties .Where(value => value.id.value == previous.id) .Cast() @@ -265,7 +266,7 @@ SerializationContext context { continue; } - string stageId = ShaderGraphDocument.Read(input, "stage", "", serialization, context); + string stageId = ShaderGraphDocument.Read(input, "stage", string.Empty, serialization, context); GraphNodeRecord? output = string.IsNullOrWhiteSpace(stageId) ? null : candidate.FindNode(new(stageId)); if (output is not null) { diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs index b7af36caf..1b3c71294 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs @@ -44,8 +44,9 @@ SerializationContext context .ToHashSet(StringComparer.Ordinal); foreach (GraphNodeRecord node in fragment.nodes.ToArray()) { - if (!selected.Contains(node.id) && !stages.Contains(ShaderGraphDocument.Read(node, "stage", "", serialization, context))) - { + if (!selected.Contains(node.id) + && !stages.Contains(ShaderGraphDocument.Read(node, "stage", string.Empty, serialization, context)) + ) { fragment.RemoveNode(node.id); } } @@ -96,9 +97,9 @@ SerializationContext context static _ => new GraphNodeId(Guid.NewGuid().ToString("N")) ); var passes = new Dictionary(StringComparer.Ordinal); - var programs = candidate.metadata.ContainsKey(ShaderGraphPrograms.bindingsKey) - ? ShaderGraphPrograms.Read(candidate, serialization, context).ToList() - : []; + List programs = candidate.metadata.ContainsKey(ShaderGraphPrograms.bindingsKey) + ? ShaderGraphPrograms.Read(candidate, serialization, context).ToList() + : []; if (definition is not null && source is not null) { foreach (ShaderGraphPassProgram program in ShaderGraphPrograms.Read(fragment, serialization, context)) @@ -156,11 +157,11 @@ SerializationContext context { position = new(node.position.x + 32, node.position.y + 32) }; - foreach (var value in node.values) + foreach (KeyValuePair value in node.values) { clone.SetValue(value.Key, value.Value.Clone()); } - string stage = ShaderGraphDocument.Read(node, "stage", "", serialization, context); + string stage = ShaderGraphDocument.Read(node, "stage", string.Empty, serialization, context); if (stage.Length != 0) { if (remap.TryGetValue(new(stage), out GraphNodeId mapped)) @@ -247,8 +248,8 @@ internal ShaderGraphPasteResult( GraphDocument graph, GraphNodeId[] nodes ) { - document = graph; - insertedNodes = Array.AsReadOnly(nodes); + this.document = graph; + this.insertedNodes = Array.AsReadOnly(nodes); } /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs index e84201a8f..f305569ae 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs @@ -39,7 +39,9 @@ public static string ReadTarget( GraphDocument graph, SerializationRegistry serialization, SerializationContext context - ) => graph.metadata.TryGetValue(targetKey, out GraphSerializedValue? value) ? Decode(value, serialization, context) : ""; + ) => graph.metadata.TryGetValue(targetKey, out GraphSerializedValue? value) + ? Decode(value, serialization, context) + : string.Empty; /// /// Assigns a domain target by stable identity without retaining its current provider. @@ -246,27 +248,32 @@ public sealed class ShaderGraphStageSettings : ISerializable /// /// Gets or sets the programmable stage. /// - [SerializableProperty] public ShaderStage stage { get; set; } = ShaderStage.Fragment; + [SerializableProperty] + public ShaderStage stage { get; set; } = ShaderStage.Fragment; /// /// Gets or sets output ports and their GPU destinations. /// - [SerializableProperty] public ShaderGraphOutput[] outputs { get; set; } = []; + [SerializableProperty] + public ShaderGraphOutput[] outputs { get; set; } = []; /// /// Gets or sets compute workgroup width. /// - [SerializableProperty] public int threadsX { get; set; } = 1; + [SerializableProperty] + public int threadsX { get; set; } = 1; /// /// Gets or sets compute workgroup height. /// - [SerializableProperty] public int threadsY { get; set; } = 1; + [SerializableProperty] + public int threadsY { get; set; } = 1; /// /// Gets or sets compute workgroup depth. /// - [SerializableProperty] public int threadsZ { get; set; } = 1; + [SerializableProperty] + public int threadsZ { get; set; } = 1; } /// @@ -303,27 +310,32 @@ public sealed class ShaderGraphInputSettings : ISerializable /// /// Gets or sets the stable logical binding identity. /// - [SerializableProperty] public string id { get; set; } = "input"; + [SerializableProperty] + public string id { get; set; } = "input"; /// /// Gets or sets the complete neutral type descriptor. /// - [SerializableProperty] public ShaderGraphType type { get; set; } = new(); + [SerializableProperty] + public ShaderGraphType type { get; set; } = new(); /// /// Gets or sets the stage input category. /// - [SerializableProperty] public ShaderIrInputKind kind { get; set; } + [SerializableProperty] + public ShaderIrInputKind kind { get; set; } /// /// Gets or sets the target semantic, not a native expression. /// - [SerializableProperty] public string semantic { get; set; } = "position"; + [SerializableProperty] + public string semantic { get; set; } = "position"; /// /// Gets or sets the interface index. /// - [SerializableProperty] public int location { get; set; } + [SerializableProperty] + public int location { get; set; } /// /// Validates the persisted descriptor and freezes its stage binding. diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs index 26689fde8..b096fe78b 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteral.cs @@ -12,12 +12,14 @@ public sealed class ShaderGraphLiteral : ISerializable /// /// Gets or sets the complete value type, including named aggregates and fixed arrays. /// - [SerializableProperty] public ShaderGraphType type { get; set; } = new() { id = "float" }; + [SerializableProperty] + public ShaderGraphType type { get; set; } = new() { id = "float" }; /// /// Gets or sets scalar bit patterns in declaration order; matrices use column-major order. /// - [SerializableProperty] public uint[] scalarBits { get; set; } = [0]; + [SerializableProperty] + public uint[] scalarBits { get; set; } = [0]; /// /// Creates an explicit zero value for a supported scalar, vector, matrix, structure or array. @@ -158,7 +160,8 @@ private static ShaderSourceType[] Members(ShaderSourceType type) throw new NotSupportedException("An input literal array is too large."); } var elements = new ShaderSourceType[type.elementCount]; - Array.Fill(elements, type.elementType); return elements; + Array.Fill(elements, type.elementType); + return elements; } if (type.fields.Count != 0) { @@ -171,7 +174,7 @@ private static ShaderSourceType[] Members(ShaderSourceType type) } foreach (string scalar in new[] { "float", "int", "uint", "bool" }) { - string shape = type.id.StartsWith(scalar, StringComparison.Ordinal) ? type.id[scalar.Length..] : ""; + string shape = type.id.StartsWith(scalar, StringComparison.Ordinal) ? type.id[scalar.Length..] : string.Empty; int count = shape.Length == 1 && shape[0] is >= '2' and <= '4' ? shape[0] - '0' : scalar == "float" @@ -185,7 +188,9 @@ private static ShaderSourceType[] Members(ShaderSourceType type) { continue; } - var result = new ShaderSourceType[count]; Array.Fill(result, ShaderSourceType.Atomic(scalar)); return result; + var result = new ShaderSourceType[count]; + Array.Fill(result, ShaderSourceType.Atomic(scalar)); + return result; } throw new NotSupportedException($"Input type '{type.id}' has no literal representation."); } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs index 0761148c6..10f96ba06 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs @@ -45,32 +45,38 @@ public sealed class ShaderGraphNodeSettings : ISerializable /// /// Gets or sets the node title displayed to authors. /// - [SerializableProperty] public string displayName { get; set; } = "Graph Node"; + [SerializableProperty] + public string displayName { get; set; } = "Graph Node"; /// /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. /// - [SerializableProperty] public string createPath { get; set; } = "General"; + [SerializableProperty] + public string createPath { get; set; } = "General"; /// /// Gets or sets the deterministic order within the creation catalog. /// - [SerializableProperty] public int createOrder { get; set; } + [SerializableProperty] + public int createOrder { get; set; } /// /// Gets or sets how a reference to this graph participates in compilation. /// - [SerializableProperty] public ShaderGraphNodeKind kind { get; set; } + [SerializableProperty] + public ShaderGraphNodeKind kind { get; set; } /// /// Gets or sets the observable computation behavior of an inline function. /// - [SerializableProperty] public ShaderGraphNodeEffect effect { get; set; } + [SerializableProperty] + public ShaderGraphNodeEffect effect { get; set; } /// /// Gets or sets the domain role consumed by a Target; empty for ordinary inline functions. /// - [SerializableProperty] public string role { get; set; } = ""; + [SerializableProperty] + public string role { get; set; } = string.Empty; } /// @@ -81,17 +87,20 @@ public sealed class ShaderGraphNodePortDefinition : ISerializable /// /// Gets or sets the stable node-local port identity. /// - [SerializableProperty] public string id { get; set; } = "value"; + [SerializableProperty] + public string id { get; set; } = "value"; /// /// Gets or sets the complete backend-neutral value type. /// - [SerializableProperty] public ShaderGraphType type { get; set; } = new() { id = "float" }; + [SerializableProperty] + public ShaderGraphType type { get; set; } = new() { id = "float" }; /// /// Gets or sets whether callers must connect the input instead of using an explicit/default zero. /// - [SerializableProperty] public bool required { get; set; } = true; + [SerializableProperty] + public bool required { get; set; } = true; internal ShaderNodePort ToPort(GraphPortDirection direction) => new(id, type.CreateType(), direction, direction == GraphPortDirection.Input && required); @@ -105,7 +114,8 @@ public sealed class ShaderGraphNodeInputSettings : ISerializable /// /// Gets or sets values supplied by callers and exposed as outputs inside the node graph. /// - [SerializableProperty] public ShaderGraphNodePortDefinition[] ports { get; set; } = []; + [SerializableProperty] + public ShaderGraphNodePortDefinition[] ports { get; set; } = []; } /// @@ -116,7 +126,8 @@ public sealed class ShaderGraphNodeOutputSettings : ISerializable /// /// Gets or sets values collected inside the node graph and exposed as outputs to callers. /// - [SerializableProperty] public ShaderGraphNodePortDefinition[] ports { get; set; } = []; + [SerializableProperty] + public ShaderGraphNodePortDefinition[] ports { get; set; } = []; } /// @@ -127,42 +138,50 @@ public sealed class ShaderGraphNodeInterface : ISerializable /// /// Gets or sets the node title displayed to authors. /// - [SerializableProperty] public string displayName { get; set; } = "Graph Node"; + [SerializableProperty] + public string displayName { get; set; } = "Graph Node"; /// /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. /// - [SerializableProperty] public string createPath { get; set; } = "General"; + [SerializableProperty] + public string createPath { get; set; } = "General"; /// /// Gets or sets the deterministic order within the creation catalog. /// - [SerializableProperty] public int createOrder { get; set; } + [SerializableProperty] + public int createOrder { get; set; } /// /// Gets or sets whether the graph is inline computation or a Target-owned output boundary. /// - [SerializableProperty] public ShaderGraphNodeKind kind { get; set; } + [SerializableProperty] + public ShaderGraphNodeKind kind { get; set; } /// /// Gets or sets whether an inline function is pure or intentionally emits ordered effects. /// - [SerializableProperty] public ShaderGraphNodeEffect effect { get; set; } + [SerializableProperty] + public ShaderGraphNodeEffect effect { get; set; } /// /// Gets or sets the Target-owned role for a domain output. /// - [SerializableProperty] public string role { get; set; } = ""; + [SerializableProperty] + public string role { get; set; } = string.Empty; /// /// Gets or sets externally supplied inputs. /// - [SerializableProperty] public ShaderGraphNodePortDefinition[] inputs { get; set; } = []; + [SerializableProperty] + public ShaderGraphNodePortDefinition[] inputs { get; set; } = []; /// /// Gets or sets externally visible results. /// - [SerializableProperty] public ShaderGraphNodePortDefinition[] outputs { get; set; } = []; + [SerializableProperty] + public ShaderGraphNodePortDefinition[] outputs { get; set; } = []; /// /// Gets detached typed ports in deterministic input-then-output order. @@ -428,7 +447,7 @@ HashSet stack )) is { } call ) { Guid sourceId = ShaderGraphDocument.Read(call, "sourceId", Guid.Empty, serialization, context); - string sourcePath = ShaderGraphDocument.Read(call, "sourcePath", "", serialization, context); + string sourcePath = ShaderGraphDocument.Read(call, "sourcePath", string.Empty, serialization, context); if (sourceId == Guid.Empty) { throw new InvalidOperationException("A graph-node reference has no Shader asset identity."); @@ -462,7 +481,7 @@ SerializationContext context ) { GraphNodeRecord? inputNode = child.nodes.SingleOrDefault(static node => node.definitionId == inputDefinitionId); GraphNodeRecord? outputNode = child.nodes.SingleOrDefault(static node => node.definitionId == outputDefinitionId); - string stage = ShaderGraphDocument.Read(call, ShaderGraphDocument.stageKey, "", serialization, context); + string stage = ShaderGraphDocument.Read(call, ShaderGraphDocument.stageKey, string.Empty, serialization, context); MergeDefinition(parent, child, stage, serialization, context); var map = new Dictionary(); foreach (GraphNodeRecord node in child.nodes.Where(node => node.id != inputNode?.id && node.id != outputNode?.id)) @@ -490,10 +509,10 @@ SerializationContext context map.Add(node.id, mapped); } - var incoming = parent.edges.Where(edge => edge.input.nodeId == call.id) + Dictionary incoming = parent.edges.Where(edge => edge.input.nodeId == call.id) .GroupBy(static edge => edge.input.portId.value, StringComparer.Ordinal) .ToDictionary(static group => group.Key, static group => group.ToArray(), StringComparer.Ordinal); - var outgoing = parent.edges.Where(edge => edge.output.nodeId == call.id) + Dictionary outgoing = parent.edges.Where(edge => edge.output.nodeId == call.id) .GroupBy(static edge => edge.output.portId.value, StringComparer.Ordinal) .ToDictionary(static group => group.Key, static group => group.ToArray(), StringComparer.Ordinal); HashSet inputIds = nodeInterface.inputs.Select(static port => port.id).ToHashSet(StringComparer.Ordinal); @@ -611,7 +630,7 @@ SerializationContext context context ).stage; } - var properties = parentDefinition.properties.ToList(); + List properties = parentDefinition.properties.ToList(); foreach (ShaderPropertyDefinition childPropertyValue in childDefinition.properties) { ShaderPropertyDefinition childProperty = childPropertyValue; diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs index 8372880df..5055de3c8 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramCompiler.cs @@ -26,7 +26,9 @@ public sealed class ShaderGraphProgramCompiler /// The owner-scoped node registry. /// public ShaderGraphProgramCompiler(ShaderNodeCompilerRegistry nodes) - => m_nodes = nodes ?? throw new ArgumentNullException(nameof(nodes)); + { + m_nodes = nodes ?? throw new ArgumentNullException(nameof(nodes)); + } /// /// Validates the complete pass/stage graph without deleting invalid or unavailable records. @@ -78,7 +80,10 @@ public ShaderGraphProgramResult Lower( return new([], diagnostics); } ConnectRasterStages(graph, implementationId, sources, serialization, context); - var definitions = definition.passes.ToDictionary(static pass => pass.name, StringComparer.Ordinal); + Dictionary definitions = definition.passes.ToDictionary( + static pass => pass.name, + StringComparer.Ordinal + ); if (definitions.Count == 0) { throw new InvalidOperationException("A shader graph requires at least one pass."); @@ -90,13 +95,16 @@ public ShaderGraphProgramResult Lower( throw new InvalidOperationException("Program references must name unique declared passes."); } var stages = new Dictionary(StringComparer.Ordinal); - var outputs = graph.nodes.Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId).ToArray(); - var owners = graph.nodes.Where(static node => node.definitionId != ShaderGraphDocument.outputDefinitionId) + GraphNodeRecord[] outputs = graph.nodes + .Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) + .ToArray(); + Dictionary owners = graph.nodes + .Where(static node => node.definitionId != ShaderGraphDocument.outputDefinitionId) .ToDictionary( static node => node.id, - node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", serialization, context) + node => ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, string.Empty, serialization, context) ); - var outputIds = outputs.Select(static node => node.id.value).ToHashSet(StringComparer.Ordinal); + HashSet outputIds = outputs.Select(static node => node.id.value).ToHashSet(StringComparer.Ordinal); foreach ((GraphNodeId node, string owner) in owners) { if (!outputIds.Contains(owner)) @@ -120,7 +128,7 @@ public ShaderGraphProgramResult Lower( context ) ?? throw new InvalidOperationException("A stage output node requires its stage settings."); - var region = graph.Clone(); + GraphDocument region = graph.Clone(); foreach (GraphNodeRecord node in graph.nodes) { if (!owners.TryGetValue(node.id, out string? owner) || owner != output.id.value) @@ -163,7 +171,8 @@ public ShaderGraphProgramResult Lower( "Every stage output must have exactly one connection with its original port identity." ); } - var inputs = region.nodes.Where(static node => node.definitionId == "inno.shader.stage-input") + Dictionary inputs = region.nodes + .Where(static node => node.definitionId == "inno.shader.stage-input") .ToDictionary(static node => node.id, node => (ShaderGraphDocument.Read( node, @@ -205,7 +214,7 @@ public ShaderGraphProgramResult Lower( lowered.block!, inputs.Values, settings.outputs.Select( - static value => new ShaderIrStageOutput(value.id, value.kind, value.semantic ?? "", value.location) + static value => new ShaderIrStageOutput(value.id, value.kind, value.semantic ?? string.Empty, value.location) ), settings.threadsX, settings.threadsY, @@ -280,8 +289,8 @@ SerializationContext context GraphNodeRecord[] outputs = graph.nodes .Where(static node => node.definitionId == ShaderGraphDocument.outputDefinitionId) .ToArray(); - var outputById = outputs.ToDictionary(static node => node.id.value, StringComparer.Ordinal); - var stageById = outputs.ToDictionary( + Dictionary outputById = outputs.ToDictionary(static node => node.id.value, StringComparer.Ordinal); + Dictionary stageById = outputs.ToDictionary( static node => node.id.value, node => ShaderGraphDocument.Read( node, @@ -296,9 +305,15 @@ SerializationContext context string Owner(GraphNodeRecord node) => node.definitionId == ShaderGraphDocument.outputDefinitionId ? node.id.value - : ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, "", serialization, context); + : ShaderGraphDocument.Read(node, ShaderGraphDocument.stageKey, string.Empty, serialization, context); - var crossings = graph.edges + ( + GraphEdgeRecord edge, + GraphNodeRecord source, + GraphNodeRecord destination, + string sourceOwner, + string destinationOwner + )[] crossings = graph.edges .Select(edge => { GraphNodeRecord source = graph.FindNode(edge.output.nodeId) @@ -342,7 +357,7 @@ string Owner(GraphNodeRecord node) } } - var occupiedLocations = outputs.ToDictionary( + Dictionary> occupiedLocations = outputs.ToDictionary( static node => node.id.value, node => ShaderGraphDocument.Read( node, @@ -450,7 +465,7 @@ string Owner(GraphNodeRecord node) sourceBridges.Add(edge.output, sourceBridge); } - var key = (edge.output, destinationOwner); + (GraphEndpoint output, string destinationOwner) key = (edge.output, destinationOwner); if (!destinationBridges.TryGetValue(key, out GraphNodeRecord? inputNode)) { string token = Convert.ToHexString( diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs index c1a8c1b18..8989bc0c1 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTemplates.cs @@ -80,17 +80,26 @@ SerializationContext context for (int index = 0; index < 2; index++) { GraphNodeRecord extract = Node("axis-" + index, "inno.shader.extract", 340, 280 + index * 270, vertex); - Set(extract, "type", "float2"); Set(extract, "index", index); - Connect(position, "value", extract, "input"); Connect(extract, "value", construct, "component." + index); + Set(extract, "type", "float2"); + Set(extract, "index", index); + Connect(position, "value", extract, "input"); + Connect(extract, "value", construct, "component." + index); GraphNodeRecord constant = Node("homogeneous-" + index, "inno.shader.constant", 40, 370 + index * 250, vertex); - Set(constant, "value", (float)index); Connect(constant, "value", construct, "component." + (index + 2)); + Set(constant, "value", (float)index); + Connect(constant, "value", construct, "component." + (index + 2)); } Connect(construct, "value", vertex, "position"); GraphNodeRecord color = Node("color", "inno.shader.stage-input", 480, 920, fragment); Set( color, "settings", - new ShaderGraphInputSettings { id = "color", type = new() { id = "float4" }, kind = ShaderIrInputKind.Uniform, semantic = "" } + new ShaderGraphInputSettings + { + id = "color", + type = new() { id = "float4" }, + kind = ShaderIrInputKind.Uniform, + semantic = string.Empty + } ); Connect(color, "value", fragment, "color"); return ShaderGraphPrograms.Bind(graph, "Main", [vertex.id, fragment.id], serialization, context); @@ -107,7 +116,8 @@ GraphNodeRecord Node( { Set(node, "stage", stage.id.value); } - graph.AddNode(node); return node; + graph.AddNode(node); + return node; } void Set( GraphNodeRecord node, diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs index 529b9069c..45caf32a0 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphType.cs @@ -12,62 +12,74 @@ public sealed class ShaderGraphType : ISerializable /// /// Gets or sets the atomic or nominal structure type identity. /// - [SerializableProperty] public string id { get; set; } = "float4"; + [SerializableProperty] + public string id { get; set; } = "float4"; /// /// Gets or sets the fixed array element type, or null for a non-array. /// - [SerializableProperty] public ShaderGraphType? element { get; set; } + [SerializableProperty] + public ShaderGraphType? element { get; set; } /// /// Gets or sets the fixed array length. /// - [SerializableProperty] public int length { get; set; } + [SerializableProperty] + public int length { get; set; } /// /// Gets or sets ordered structure member names. /// - [SerializableProperty] public string[] fieldNames { get; set; } = []; + [SerializableProperty] + public string[] fieldNames { get; set; } = []; /// /// Gets or sets ordered structure member types. /// - [SerializableProperty] public ShaderGraphType[] fieldTypes { get; set; } = []; + [SerializableProperty] + public ShaderGraphType[] fieldTypes { get; set; } = []; /// /// Gets or sets whether the descriptor represents a storage binding. /// - [SerializableProperty] public bool isStorage { get; set; } + [SerializableProperty] + public bool isStorage { get; set; } /// /// Gets or sets whether storage is an image instead of a buffer. /// - [SerializableProperty] public bool isImage { get; set; } + [SerializableProperty] + public bool isImage { get; set; } /// /// Gets or sets the complete buffer element type. /// - [SerializableProperty] public ShaderGraphType? storageElement { get; set; } + [SerializableProperty] + public ShaderGraphType? storageElement { get; set; } /// /// Gets or sets storage access. /// - [SerializableProperty] public RenderStorageAccess access { get; set; } + [SerializableProperty] + public RenderStorageAccess access { get; set; } /// /// Gets or sets the image texel format. /// - [SerializableProperty] public RenderTextureFormat format { get; set; } + [SerializableProperty] + public RenderTextureFormat format { get; set; } /// /// Gets or sets the image spatial dimension. /// - [SerializableProperty] public RenderTextureDimension dimension { get; set; } = RenderTextureDimension.Texture2D; + [SerializableProperty] + public RenderTextureDimension dimension { get; set; } = RenderTextureDimension.Texture2D; /// /// Gets or sets whether an image has array layers. /// - [SerializableProperty] public bool isArray { get; set; } + [SerializableProperty] + public bool isArray { get; set; } /// /// Captures a full immutable source type as reload-safe authoring data. diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs index 9db82bff5..bf39844a2 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBuilder.cs @@ -23,7 +23,10 @@ public sealed partial class ShaderIrBuilder /// /// Creates an independent typed region builder and value identity scope. /// - public ShaderIrBuilder() => m_root = this; + public ShaderIrBuilder() + { + m_root = this; + } private ShaderIrBuilder(ShaderIrBuilder parent) { diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs index 8f6a6c6f2..db33911c3 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrSemanticHash.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -66,7 +67,7 @@ void WriteBlock(ShaderIrBlock block) } } writer.Write(block.outputs.Count); - foreach (var output in block.outputs.OrderBy(static value => value.Key, StringComparer.Ordinal)) + foreach (KeyValuePair output in block.outputs.OrderBy(static value => value.Key, StringComparer.Ordinal)) { writer.Write(output.Key); writer.Write(output.Value.index); diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs index 4fcddea1c..8c4555144 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs @@ -262,7 +262,7 @@ public ShaderIrStage( this.threadsY = threadsY; this.threadsZ = threadsZ; Validate(); - contentHash = ShaderIrSemanticHash.Compute(this); + this.contentHash = ShaderIrSemanticHash.Compute(this); } /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs index 2d235992c..c4c69a464 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using Inno.Core.Diagnostics; @@ -114,7 +115,7 @@ public ShaderSourceRequest( ArgumentException.ThrowIfNullOrWhiteSpace(entryPoint); this.entryPoint = entryPoint; this.resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); - this.defines = new System.Collections.ObjectModel.ReadOnlyDictionary( + this.defines = new ReadOnlyDictionary( defines is null ? new Dictionary(StringComparer.Ordinal) : new Dictionary(defines, StringComparer.Ordinal) diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs index 3b5a5181a..fc8328267 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendCatalog.cs @@ -33,7 +33,7 @@ public ShaderSourceFrontendCatalog(IEnumerable frontends) throw new ArgumentException("Source frontends require unique, assigned language IDs.", nameof(frontends)); } } - languageIds = new ReadOnlyCollection(new List(m_frontends.Keys)); + this.languageIds = new ReadOnlyCollection([.. m_frontends.Keys]); } /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs index 130948424..f8fef1972 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFrontendRegistry.cs @@ -19,7 +19,10 @@ public sealed class ShaderSourceFrontendRegistry : TypeRegistry public ShaderSourceFrontendRegistry(TypeCatalog types) - : base(types) => m_types = types; + : base(types) + { + m_types = types; + } /// /// Gets immutable language identities available in the current generation. diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs index 7a6aec711..0e3b1938c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs @@ -82,19 +82,19 @@ internal ShaderSourceImplementationAnalysis( IEnumerable files, IEnumerable includes ) { - implementationId = request.implementationId; - languageId = request.languageId; - sourcePath = request.source.source.assetPath; - entryPoint = request.source.entryPoint; - defines = request.source.defines; + this.implementationId = request.implementationId; + this.languageId = request.languageId; + this.sourcePath = request.source.source.assetPath; + this.entryPoint = request.source.entryPoint; + this.defines = request.source.defines; this.analysis = analysis; - sources = Array.AsReadOnly(files.OrderBy(static file => file.assetPath, StringComparer.Ordinal).ToArray()); + this.sources = Array.AsReadOnly(files.OrderBy(static file => file.assetPath, StringComparer.Ordinal).ToArray()); this.includes = Array.AsReadOnly( includes.OrderBy(static edge => edge.includingFile, StringComparer.Ordinal) .ThenBy(static edge => edge.include, StringComparer.Ordinal) .ToArray() ); - contentHash = ComputeContentHash(); + this.contentHash = ComputeContentHash(); } /// @@ -223,9 +223,9 @@ IEnumerable diagnostics ) { this.implementations = Array.AsReadOnly(implementations.ToArray()); this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - succeeded = this.implementations.Count != 0 && this.implementations.All(static item => item.analysis.succeeded) - && this.diagnostics.All(static item => item.severity != DiagnosticSeverity.Error); - function = succeeded ? this.implementations[0].analysis.function : null; + this.succeeded = this.implementations.Count != 0 && this.implementations.All(static item => item.analysis.succeeded) + && this.diagnostics.All(static item => item.severity != DiagnosticSeverity.Error); + this.function = succeeded ? this.implementations[0].analysis.function : null; } /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs index 216f911dd..8c6c0d768 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs @@ -18,8 +18,8 @@ private ShaderSourceType( ) { ArgumentException.ThrowIfNullOrWhiteSpace(id); this.id = id; - elementType = element; - elementCount = count; + this.elementType = element; + this.elementCount = count; this.fields = Array.AsReadOnly(fields); this.storage = storage; } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs index 241c1cd09..5be949a28 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs @@ -18,9 +18,11 @@ public sealed class ShaderTargetAttribute : Attribute /// Stable target identity persisted by Shader assets. /// public ShaderTargetAttribute(string id) - => this.id = string.IsNullOrWhiteSpace(id) - ? throw new ArgumentException("Shader target identity cannot be empty.", nameof(id)) - : id; + { + this.id = string.IsNullOrWhiteSpace(id) + ? throw new ArgumentException("Shader target identity cannot be empty.", nameof(id)) + : id; + } /// /// Gets the stable target identity persisted by Shader assets. diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs index 66c3ddc11..b712c50e7 100644 --- a/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs @@ -371,13 +371,13 @@ public GraphicsCapabilities( this.limits = limits; this.originBottomLeft = originBottomLeft; this.homogeneousDepth = homogeneousDepth; - m_sampledFormats = new HashSet(sampledFormats); - m_sampled3DFormats = new HashSet(sampled3DFormats ?? []); - m_sampledCubeFormats = new HashSet(sampledCubeFormats ?? []); - m_renderTargetFormats = new HashSet(renderTargetFormats); - m_multisampleRenderTargetFormats = new HashSet(multisampleRenderTargetFormats ?? []); - m_storageReadFormats = new HashSet(storageReadFormats); - m_storageWriteFormats = new HashSet(storageWriteFormats); + m_sampledFormats = [.. sampledFormats]; + m_sampled3DFormats = [.. sampled3DFormats ?? []]; + m_sampledCubeFormats = [.. sampledCubeFormats ?? []]; + m_renderTargetFormats = [.. renderTargetFormats]; + m_multisampleRenderTargetFormats = [.. multisampleRenderTargetFormats ?? []]; + m_storageReadFormats = [.. storageReadFormats]; + m_storageWriteFormats = [.. storageWriteFormats]; } /// @@ -408,12 +408,12 @@ public GraphicsCapabilities( /// /// Tests whether every requested optional feature is supported. /// - /// - /// when every requested feature is available. - /// /// /// The required consumed by supports; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// when every requested feature is available. + /// public bool Supports(GraphicsCapability required) => (features & required) == required; /// @@ -453,12 +453,12 @@ RenderTextureDimension dimension /// /// Tests whether a format is valid as a raster attachment. /// - /// - /// when the format can be attached. - /// /// /// The format consumed by supports render target; ownership remains with the caller unless explicitly stated otherwise. /// + /// + /// when the format can be attached. + /// public bool SupportsRenderTarget(RenderTextureFormat format) => m_renderTargetFormats.Contains(format); /// diff --git a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs index 75e95ad14..b78557d3c 100644 --- a/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs +++ b/src/services/rendering/Inno.Rendering/Device/RecordedRenderCommandEncoder.cs @@ -18,21 +18,21 @@ public void Dispose() m_buffer.Dispose(); } - /// + /// public override void BindGraphicsPipeline(GraphicsPipelineHandle pipeline) { Begin(Operation.BindGraphicsPipeline); m_buffer.Write(pipeline); } - /// + /// public override void BindComputePipeline(ComputePipelineHandle pipeline) { Begin(Operation.BindComputePipeline); m_buffer.Write(pipeline); } - /// + /// public override void BindTexture( RenderBindingId binding, RenderTextureHandle texture, @@ -44,7 +44,7 @@ RenderSamplerState sampler m_buffer.Write(sampler); } - /// + /// public override void BindTexture( RenderBindingId binding, PersistentTextureHandle texture, @@ -56,7 +56,7 @@ RenderSamplerState sampler m_buffer.Write(sampler); } - /// + /// public override void BindStorageTexture( RenderBindingId binding, RenderTextureHandle texture, @@ -68,7 +68,7 @@ public override void BindStorageTexture( m_buffer.Write(mipLevel); } - /// + /// public override void BindStorageTexture( RenderBindingId binding, PersistentTextureHandle texture, @@ -80,7 +80,7 @@ public override void BindStorageTexture( m_buffer.Write(mipLevel); } - /// + /// public override void BindBuffer( RenderBindingId binding, RenderBufferHandle buffer @@ -90,7 +90,7 @@ RenderBufferHandle buffer m_buffer.Write(buffer); } - /// + /// public override void BindBuffer( RenderBindingId binding, PersistentBufferHandle buffer @@ -100,10 +100,10 @@ PersistentBufferHandle buffer m_buffer.Write(buffer); } - /// /// /// Copies the borrowed uniform bytes into this recording before returning. /// + /// public override void SetUniform( RenderBindingId binding, ReadOnlySpan value @@ -113,17 +113,17 @@ ReadOnlySpan value m_buffer.WriteSnapshot(value); } - /// /// /// Copies the borrowed matrix values into this recording before returning. /// + /// public override void SetTransform(ReadOnlySpan columnMajorMatrix) { Begin(Operation.SetTransform); m_buffer.WriteSnapshot(MemoryMarshal.AsBytes(columnMajorMatrix)); } - /// + /// public override void SetRasterState(RenderRasterState state) { ArgumentNullException.ThrowIfNull(state); @@ -131,7 +131,7 @@ public override void SetRasterState(RenderRasterState state) m_buffer.WriteReference(state); } - /// + /// public override void SetStencil(RenderStencilState state) { ArgumentNullException.ThrowIfNull(state); @@ -139,7 +139,7 @@ public override void SetStencil(RenderStencilState state) m_buffer.WriteReference(state); } - /// + /// public override void SetViewport( int x, int y, @@ -153,7 +153,7 @@ int height m_buffer.Write(height); } - /// + /// public override void SetScissor( int x, int y, @@ -167,7 +167,7 @@ int height m_buffer.Write(height); } - /// + /// public override void BindVertexBuffer( RenderBufferHandle buffer, int firstVertex = 0 @@ -177,7 +177,7 @@ public override void BindVertexBuffer( m_buffer.Write(firstVertex); } - /// + /// public override void BindVertexBuffer( PersistentBufferHandle buffer, int firstVertex = 0 @@ -187,7 +187,7 @@ public override void BindVertexBuffer( m_buffer.Write(firstVertex); } - /// + /// public override void BindIndexBuffer( RenderBufferHandle buffer, int firstIndex = 0 @@ -197,7 +197,7 @@ public override void BindIndexBuffer( m_buffer.Write(firstIndex); } - /// + /// public override void BindIndexBuffer( PersistentBufferHandle buffer, int firstIndex = 0 @@ -207,7 +207,7 @@ public override void BindIndexBuffer( m_buffer.Write(firstIndex); } - /// + /// public override void BindInstanceBuffer( RenderBufferHandle buffer, int firstInstance, @@ -219,7 +219,7 @@ int instanceCount m_buffer.Write(instanceCount); } - /// + /// public override void BindInstanceBuffer( PersistentBufferHandle buffer, int firstInstance, @@ -231,34 +231,28 @@ int instanceCount m_buffer.Write(instanceCount); } - /// + /// [MethodImpl(MethodImplOptions.AggressiveOptimization)] public override void Draw( int vertexCount, int instanceCount = 1 - ) { - RecordDraw(Operation.Draw, vertexCount, instanceCount); - } + ) => RecordDraw(Operation.Draw, vertexCount, instanceCount); - /// + /// [MethodImpl(MethodImplOptions.AggressiveOptimization)] public override void DrawProcedural( int vertexCount, int instanceCount = 1 - ) { - RecordDraw(Operation.DrawProcedural, vertexCount, instanceCount); - } + ) => RecordDraw(Operation.DrawProcedural, vertexCount, instanceCount); - /// + /// [MethodImpl(MethodImplOptions.AggressiveOptimization)] public override void DrawIndexed( int indexCount, int instanceCount = 1 - ) { - RecordDraw(Operation.DrawIndexed, indexCount, instanceCount); - } + ) => RecordDraw(Operation.DrawIndexed, indexCount, instanceCount); - /// + /// public override void DrawIndirect( RenderBufferHandle buffer, int firstCommand = 0, @@ -270,7 +264,7 @@ public override void DrawIndirect( m_buffer.Write(commandCount); } - /// + /// public override void DrawIndirect( PersistentBufferHandle buffer, int firstCommand = 0, @@ -282,7 +276,7 @@ public override void DrawIndirect( m_buffer.Write(commandCount); } - /// + /// public override void Dispatch( int groupCountX, int groupCountY = 1, @@ -294,7 +288,7 @@ public override void Dispatch( m_buffer.Write(groupCountZ); } - /// + /// public override void DispatchIndirect( RenderBufferHandle buffer, int firstCommand = 0, @@ -306,7 +300,7 @@ public override void DispatchIndirect( m_buffer.Write(commandCount); } - /// + /// public override void DispatchIndirect( PersistentBufferHandle buffer, int firstCommand = 0, @@ -318,7 +312,7 @@ public override void DispatchIndirect( m_buffer.Write(commandCount); } - /// + /// public override void CopyTexture( RenderTextureHandle source, RenderTextureHandle destination @@ -328,7 +322,7 @@ RenderTextureHandle destination m_buffer.Write(destination); } - /// + /// public override void BlitTexture( RenderTextureHandle source, RenderTextureRegion sourceRegion, @@ -342,7 +336,7 @@ RenderTextureRegion destinationRegion m_buffer.Write(destinationRegion); } - /// + /// public override void CopyBuffer( RenderBufferHandle source, RenderBufferHandle destination diff --git a/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs b/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs index 1c9f77228..b837f0b90 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs @@ -167,7 +167,7 @@ RenderPrimitiveTopology topology /// /// Gets the four-bit RGBA write mask. /// - public byte colorWriteMask { get; init; } = 0x0f; + public byte colorWriteMask { get; init; } = 0x0F; /// /// Gets whether multisample rasterization is enabled for compatible targets. diff --git a/src/services/rendering/Inno.Rendering/Device/RenderResources.cs b/src/services/rendering/Inno.Rendering/Device/RenderResources.cs index d4522991d..5f17a3f2e 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderResources.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderResources.cs @@ -329,12 +329,12 @@ public bool Equals(RenderTextureDescriptor? other) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => Equals(obj as RenderTextureDescriptor); /// @@ -345,7 +345,7 @@ public bool Equals(RenderTextureDescriptor? other) /// public override int GetHashCode() { - HashCode hash = new(); + var hash = new HashCode(); hash.Add(width); hash.Add(height); hash.Add(format); @@ -421,12 +421,12 @@ public bool Equals(RenderBufferDescriptor? other) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => Equals(obj as RenderBufferDescriptor); /// diff --git a/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs b/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs index 042cf2093..91caf428b 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs @@ -127,12 +127,12 @@ public readonly bool Equals(RenderSamplerState other) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override readonly bool Equals(object? obj) => obj is RenderSamplerState other && Equals(other); /// diff --git a/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs b/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs index 0de817a85..0d923bf68 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs @@ -308,12 +308,12 @@ public bool Equals(RenderVertexLayout? other) /// /// Determines whether this instance and the supplied value represent the same logical state. /// - /// - /// when both values represent the same logical state; otherwise, . - /// /// /// The object to compare with this instance. /// + /// + /// when both values represent the same logical state; otherwise, . + /// public override bool Equals(object? obj) => Equals(obj as RenderVertexLayout); /// @@ -324,7 +324,7 @@ public bool Equals(RenderVertexLayout? other) /// public override int GetHashCode() { - HashCode hash = new(); + var hash = new HashCode(); foreach (RenderVertexAttribute attribute in m_attributes) { hash.Add(attribute); diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs index b85953cc3..144a518c3 100644 --- a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Runtime.ExceptionServices; @@ -166,16 +167,16 @@ public sealed class CompiledRenderAttachment { internal CompiledRenderAttachment(RenderAttachment attachment) { - texture = attachment.texture; - slot = attachment.slot; - isDepth = attachment.isDepth; - mipLevel = attachment.mipLevel; - arrayLayer = attachment.arrayLayer; - loadAction = attachment.loadAction; - storeAction = attachment.storeAction; - clearColor = attachment.clearColor; - clearDepth = attachment.clearDepth; - clearStencil = attachment.clearStencil; + this.texture = attachment.texture; + this.slot = attachment.slot; + this.isDepth = attachment.isDepth; + this.mipLevel = attachment.mipLevel; + this.arrayLayer = attachment.arrayLayer; + this.loadAction = attachment.loadAction; + this.storeAction = attachment.storeAction; + this.clearColor = attachment.clearColor; + this.clearDepth = attachment.clearDepth; + this.clearStencil = attachment.clearStencil; } /// @@ -516,9 +517,7 @@ ulong frameIndex private Dictionary RecordParallelPasses(ulong frameIndex) { - var recorded = new System.Collections.Concurrent.ConcurrentDictionary< - CompiledRenderPass, - RecordedRenderCommandEncoder>(); + var recorded = new ConcurrentDictionary(); try { Parallel.ForEach( diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs index 5db2441f6..7fc1d324b 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.Mutations.cs @@ -2,7 +2,7 @@ namespace Inno.Rendering; -sealed partial class RenderGraphBuilder +public sealed partial class RenderGraphBuilder { internal void EnsurePassMutable(RenderPassRecord pass) { diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs index 34b6a2e41..278f50f96 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphBuilder.cs @@ -68,7 +68,7 @@ RenderTextureDescriptor descriptor ) { EnsureMutating(); ValidateNameAndValue(name, descriptor); - RenderTextureHandle handle = new(m_textures.Count, m_generation, checked(++m_nextResourceId)); + var handle = new RenderTextureHandle(m_textures.Count, m_generation, checked(++m_nextResourceId)); m_textures.Add(new RenderTextureRecord(QualifyName(name), descriptor, false, default, handle.allocationId)); InvalidateValidation(); return handle; @@ -101,7 +101,7 @@ RenderTextureDescriptor descriptor throw new ArgumentException("Persistent texture handle is invalid.", nameof(texture)); } - RenderTextureHandle handle = new(m_textures.Count, m_generation, checked(++m_nextResourceId)); + var handle = new RenderTextureHandle(m_textures.Count, m_generation, checked(++m_nextResourceId)); m_textures.Add(new RenderTextureRecord(QualifyName(name), descriptor, true, texture, handle.allocationId)); InvalidateValidation(); return handle; @@ -125,7 +125,7 @@ RenderBufferDescriptor descriptor ) { EnsureMutating(); ValidateNameAndValue(name, descriptor); - RenderBufferHandle handle = new(m_buffers.Count, m_generation, checked(++m_nextResourceId)); + var handle = new RenderBufferHandle(m_buffers.Count, m_generation, checked(++m_nextResourceId)); m_buffers.Add(new RenderBufferRecord(QualifyName(name), descriptor, false, default, handle.allocationId)); InvalidateValidation(); return handle; @@ -158,7 +158,7 @@ RenderBufferDescriptor descriptor throw new ArgumentException("Persistent buffer handle is invalid.", nameof(buffer)); } - RenderBufferHandle handle = new(m_buffers.Count, m_generation, checked(++m_nextResourceId)); + var handle = new RenderBufferHandle(m_buffers.Count, m_generation, checked(++m_nextResourceId)); m_buffers.Add(new RenderBufferRecord(QualifyName(name), descriptor, true, buffer, handle.allocationId)); InvalidateValidation(); return handle; @@ -424,7 +424,7 @@ RenderPassExecute execute throw new ArgumentException($"Render pass '{qualifiedName}' already exists.", nameof(name)); } - RenderPassRecord pass = new() + var pass = new RenderPassRecord() { index = m_passes.Count, name = qualifiedName, diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs index 75f8f99b4..6dbfad6a5 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs @@ -46,9 +46,9 @@ private static int[] AllocateSlots( IReadOnlyList passes, IReadOnlyDictionary schedulePositions ) { - int[] firstUses = new int[resourceCount]; - int[] lastUses = new int[resourceCount]; - int[] slots = new int[resourceCount]; + var firstUses = new int[resourceCount]; + var lastUses = new int[resourceCount]; + var slots = new int[resourceCount]; Array.Fill(firstUses, int.MaxValue); Array.Fill(lastUses, -1); Array.Fill(slots, -1); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs index 8a43dbc72..f4a7647e6 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.cs @@ -28,7 +28,7 @@ RenderGraphValidationWorkspace analysis analysis.bufferCount = buffers.Count; analysis.passCount = passes.Count; // End-of-graph output and scheduling diagnostics are revision-local, not prefix state. - diagnostics = new List(diagnostics); + diagnostics = [.. diagnostics]; foreach (RenderResourceKey output in outputs) { if (!analysis.initialized.Contains(output)) @@ -588,34 +588,30 @@ private static void AddAttachmentUsageError( RenderTextureRecord texture, string role, List diagnostics - ) { - diagnostics.Add( - new RenderGraphDiagnostic( - "RENDER_GRAPH_ATTACHMENT_USAGE", - $"Texture '{texture.name}' is not declared for {role} attachment usage.", - DiagnosticSeverity.Error, - pass.name, - texture.name - ) - ); - } + ) => diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_ATTACHMENT_USAGE", + $"Texture '{texture.name}' is not declared for {role} attachment usage.", + DiagnosticSeverity.Error, + pass.name, + texture.name + ) + ); private static void AddResourceUsageError( RenderPassRecord pass, string resourceName, string requiredUsage, List diagnostics - ) { - diagnostics.Add( - new RenderGraphDiagnostic( - "RENDER_GRAPH_RESOURCE_USAGE", - $"Resource '{resourceName}' used by pass '{pass.name}' requires '{requiredUsage}' usage.", - DiagnosticSeverity.Error, - pass.name, - resourceName - ) - ); - } + ) => diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_RESOURCE_USAGE", + $"Resource '{resourceName}' used by pass '{pass.name}' requires '{requiredUsage}' usage.", + DiagnosticSeverity.Error, + pass.name, + resourceName + ) + ); private static void AddCapabilityError( RenderPassRecord pass, @@ -623,15 +619,13 @@ private static void AddCapabilityError( string operation, GraphicsCapability requiredFeature, List diagnostics - ) { - diagnostics.Add( - new RenderGraphDiagnostic( - "RENDER_GRAPH_CAPABILITY_UNSUPPORTED", - $"Pass '{pass.name}' requires '{requiredFeature}' for {operation} operations.", - DiagnosticSeverity.Error, - pass.name, - resourceName - ) - ); - } + ) => diagnostics.Add( + new RenderGraphDiagnostic( + "RENDER_GRAPH_CAPABILITY_UNSUPPORTED", + $"Pass '{pass.name}' requires '{requiredFeature}' for {operation} operations.", + DiagnosticSeverity.Error, + pass.name, + resourceName + ) + ); } diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs b/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs index 59ce7d6ca..2d66260ba 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderPassBuilder.cs @@ -70,13 +70,13 @@ public RenderPassBuilder HasSideEffect() /// /// Opts this pass into worker-thread recording through an isolated backend-neutral command list. /// + /// + /// This builder for fluent declarations. + /// /// /// Pass data and code reached by the callback must be safe for worker-thread access. GPU execution /// and backend view order remain identical to the compiled graph order. /// - /// - /// This builder for fluent declarations. - /// public RenderPassBuilder AllowParallelRecording() { m_graph.EnsurePassMutable(m_pass); diff --git a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs index 8976b2766..c9e921bfd 100644 --- a/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs +++ b/src/services/rendering/Inno.Rendering/Shaders/ShaderPropertyId.cs @@ -41,5 +41,5 @@ public ShaderPropertyId(string value) /// /// The human-readable representation of this value. /// - public readonly override string ToString() => value ?? string.Empty; + public override readonly string ToString() => value ?? string.Empty; } diff --git a/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs b/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs index 531be4cf8..8345e68b8 100644 --- a/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs +++ b/src/services/storage/Inno.Storage.Runtime/StorageRuntime.cs @@ -165,16 +165,10 @@ public ValueTask> ListAsync( /// /// The frame consumed by begin frame; ownership remains with the caller unless explicitly stated otherwise. /// - protected override void OnBeginFrame(RuntimeFrame frame) - { - OwnFrameScope(StorageExecutionContext.EnterScope(this)); - } + protected override void OnBeginFrame(RuntimeFrame frame) => OwnFrameScope(StorageExecutionContext.EnterScope(this)); /// /// Releases the storage backend after owned work has quiesced. /// - protected override void OnStop() - { - m_operations.Dispose(); - } + protected override void OnStop() => m_operations.Dispose(); } diff --git a/src/services/storage/Inno.Storage/StorageScope.cs b/src/services/storage/Inno.Storage/StorageScope.cs index 8e8da21db..76c24313f 100644 --- a/src/services/storage/Inno.Storage/StorageScope.cs +++ b/src/services/storage/Inno.Storage/StorageScope.cs @@ -60,6 +60,6 @@ public StorageScope(string value) /// public bool isValid => value is not null; - /// + /// public override string ToString() => value ?? string.Empty; } diff --git a/src/services/text/Inno.Text.Assets/FontImporter.cs b/src/services/text/Inno.Text.Assets/FontImporter.cs index 89b38e0f7..518980162 100644 --- a/src/services/text/Inno.Text.Assets/FontImporter.cs +++ b/src/services/text/Inno.Text.Assets/FontImporter.cs @@ -57,16 +57,16 @@ private static FontMetadata ReadMetadata(ReadOnlySpan source) } uint signature = BinaryPrimitives.ReadUInt32BigEndian(source); int faceCount; - if (signature == 0x74746366) + if (signature == 0x7474_6366) { uint count = BinaryPrimitives.ReadUInt32BigEndian(source[8..]); - if (count is 0 or > 65535 || source.Length < checked(12 + ((int)count * 4))) + if (count is 0 or > 65_535 || source.Length < checked(12 + ((int)count * 4))) { throw new InvalidDataException("The OpenType collection header is invalid."); } faceCount = (int)count; } - else if (signature is 0x00010000 or 0x4f54544f or 0x74727565 or 0x74797031) + else if (signature is 0x0001_0000 or 0x4F54_544F or 0x7472_7565 or 0x7479_7031) { faceCount = 1; } diff --git a/src/services/text/Inno.Text/FontAsset.cs b/src/services/text/Inno.Text/FontAsset.cs index aa694618b..f808e282a 100644 --- a/src/services/text/Inno.Text/FontAsset.cs +++ b/src/services/text/Inno.Text/FontAsset.cs @@ -45,7 +45,7 @@ long encodedByteLength /// public static class FontMetadataCodec { - private const uint C_MAGIC = 0x544E4649; + private const uint C_MAGIC = 0x544E_4649; private const int C_SIZE = 16; /// @@ -59,7 +59,7 @@ public static class FontMetadataCodec /// public static byte[] Encode(FontMetadata metadata) { - byte[] output = new byte[C_SIZE]; + var output = new byte[C_SIZE]; BinaryPrimitives.WriteUInt32LittleEndian(output, C_MAGIC); BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(4), metadata.faceCount); BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(8), metadata.encodedByteLength); @@ -120,7 +120,5 @@ public sealed class FontAsset : AssetObject protected override void OnRuntimePayloadChanged( ReadOnlyMemory previousPayload, ReadOnlyMemory currentPayload - ) { - m_metadata = currentPayload.IsEmpty ? null : FontMetadataCodec.Decode(currentPayload.Span); - } + ) => m_metadata = currentPayload.IsEmpty ? null : FontMetadataCodec.Decode(currentPayload.Span); } diff --git a/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs b/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs index 21c58cabc..956267ce7 100644 --- a/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs +++ b/src/services/ui/Inno.UI.Assets/UiDocumentFrontend.cs @@ -2,7 +2,9 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using Inno.Assets; using Inno.Extensibility.Types; +using Inno.Text; namespace Inno.UI.Assets; @@ -21,7 +23,7 @@ namespace Inno.UI.Assets; public sealed record UiDocumentSourceFile( string assetPath, string text, - Func? readSource = null + Func? readSource = null ); /// @@ -64,7 +66,7 @@ int column public sealed record UiDocumentFontDeclaration( string assetPath, string family, - Inno.Text.TextFontStyle style, + TextFontStyle style, int weight ); @@ -164,7 +166,7 @@ public UiDocumentFrontendCatalog(IEnumerable frontends) throw new ArgumentException("UI document frontends require unique, assigned language IDs.", nameof(frontends)); } } - languageIds = new ReadOnlyCollection([.. m_frontends.Keys]); + this.languageIds = new ReadOnlyCollection([.. m_frontends.Keys]); } /// @@ -208,7 +210,10 @@ public sealed class UiDocumentFrontendRegistry : TypeRegistry public UiDocumentFrontendRegistry(TypeCatalog types) - : base(types) => m_types = types; + : base(types) + { + m_types = types; + } /// /// Analyzes source while preventing provider retirement. diff --git a/src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs b/src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs index fe4e7aa11..f8a1aac93 100644 --- a/src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs +++ b/src/services/ui/Inno.UI.Assets/UiDocumentImportSettings.cs @@ -12,10 +12,12 @@ public sealed class UiDocumentImportSettings : ISerializable /// /// Gets or sets the registered source-language identity. /// - [SerializableProperty] public string languageId { get; set; } = string.Empty; + [SerializableProperty] + public string languageId { get; set; } = string.Empty; /// /// Gets or sets the exact runtime implementation identity. /// - [SerializableProperty] public string implementationId { get; set; } = string.Empty; + [SerializableProperty] + public string implementationId { get; set; } = string.Empty; } diff --git a/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs b/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs index cefd7f3be..3ff798750 100644 --- a/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs +++ b/src/services/ui/Inno.UI.Assets/UiDocumentImporter.cs @@ -50,8 +50,8 @@ protected override async ValueTask ImportAsync( AssetImportWriter output, CancellationToken cancellationToken ) { - var settings = context.importSettings as UiDocumentImportSettings - ?? throw new InvalidOperationException("UI source requires its standard import settings."); + UiDocumentImportSettings settings = context.importSettings as UiDocumentImportSettings + ?? throw new InvalidOperationException("UI source requires its standard import settings."); ArgumentException.ThrowIfNullOrWhiteSpace(settings.languageId); ArgumentException.ThrowIfNullOrWhiteSpace(settings.implementationId); await UiDocumentImportPipeline.ImportAsync( diff --git a/src/services/ui/Inno.UI/UiBackendCapabilities.cs b/src/services/ui/Inno.UI/UiBackendCapabilities.cs index 7d8e4a425..7df2c611b 100644 --- a/src/services/ui/Inno.UI/UiBackendCapabilities.cs +++ b/src/services/ui/Inno.UI/UiBackendCapabilities.cs @@ -81,7 +81,9 @@ public sealed class UiCapabilityUnavailableException : NotSupportedException /// public UiCapabilityUnavailableException(UiBackendCapability capability) : base($"The selected UI backend does not support capability '{capability}'.") - => this.capability = capability; + { + this.capability = capability; + } /// /// Gets the unavailable capability. diff --git a/src/services/ui/Inno.UI/UiDocumentAsset.cs b/src/services/ui/Inno.UI/UiDocumentAsset.cs index c61e67b62..29fdec312 100644 --- a/src/services/ui/Inno.UI/UiDocumentAsset.cs +++ b/src/services/ui/Inno.UI/UiDocumentAsset.cs @@ -15,7 +15,7 @@ namespace Inno.UI; [StableTypeId("8b34bafb-f34a-4c19-9853-282485c40b78")] public sealed class UiDocumentAsset : AssetObject { - private const uint C_PAYLOAD_MAGIC = 0x44495549; + private const uint C_PAYLOAD_MAGIC = 0x4449_5549; private UiDocumentSource? m_source; private IReadOnlyList m_fonts = []; private string m_implementationId = string.Empty; diff --git a/src/services/ui/Inno.UI/UiTypes.cs b/src/services/ui/Inno.UI/UiTypes.cs index f2f852607..f67fb624b 100644 --- a/src/services/ui/Inno.UI/UiTypes.cs +++ b/src/services/ui/Inno.UI/UiTypes.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Inno.Core.Events; using Inno.Core.Input; using Inno.Core.Mathematics; @@ -241,7 +242,7 @@ public enum UiEventType /// /// Describes one queued document event after a context update. /// -public sealed class UiEvent : Inno.Core.Events.Event +public sealed class UiEvent : Event { /// /// Creates a document event with its source document and target element. diff --git a/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs b/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs index e570e9ff2..33cba3b45 100644 --- a/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs +++ b/tests/animation/Inno.Animation.Tests/AnimationRuntimeTests.cs @@ -189,9 +189,6 @@ private sealed class RecordingSink : IAnimationBindingSink { internal IReadOnlyList lastSamples { get; private set; } = []; - public void Apply(ReadOnlySpan samples) - { - lastSamples = samples.ToArray(); - } + public void Apply(ReadOnlySpan samples) => lastSamples = samples.ToArray(); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs index 5e4a01b5e..9b2df1700 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemChangeTests.cs @@ -20,14 +20,14 @@ public void Watcher_CoalescesCreateChangeAndDeleteThroughPublicCoordinator() using var fileSystem = new AssetFileSystem(root, autoStart: true, flushDelayMs: 20); string path = Path.Combine(root, "Flow", "item.txt"); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - System.IO.File.WriteAllText(path, "one"); - System.IO.File.WriteAllText(path, "two"); + File.WriteAllText(path, "one"); + File.WriteAllText(path, "two"); IReadOnlyList observed = fileSystem.WaitForIdle(); Assert.True(fileSystem.TryGetEntry(AssetPath.Project("Flow/item.txt"), out AssetFileEntry created)); Assert.False(created.isDirectory); - System.IO.File.Delete(path); + File.Delete(path); observed = observed.Concat(fileSystem.WaitForIdle()).ToArray(); Assert.False(fileSystem.TryGetEntry(AssetPath.Project("Flow/item.txt"), out _)); @@ -50,9 +50,9 @@ public void Watcher_RenamePreservesOldAndNewRelativePaths() { string oldPath = Path.Combine(root, "old.txt"); string newPath = Path.Combine(root, "new.txt"); - System.IO.File.WriteAllText(oldPath, "value"); + File.WriteAllText(oldPath, "value"); using var fileSystem = new AssetFileSystem(root, autoStart: true, flushDelayMs: 20); - System.IO.File.Move(oldPath, newPath); + File.Move(oldPath, newPath); IReadOnlyList observed = fileSystem.WaitForIdle(); AssetChangedEvent renamed = Assert.Single( @@ -76,8 +76,8 @@ public void WatcherPublishesSettingsSidecarChangesWithoutExposingMetadataAsAsset try { using var fileSystem = new AssetFileSystem(root, autoStart: true, flushDelayMs: 20); - System.IO.File.WriteAllText(Path.Combine(root, "asset.txt.imeta"), "cache"); - System.IO.File.WriteAllText(Path.Combine(root, "asset.txt.abin"), "generated"); + File.WriteAllText(Path.Combine(root, "asset.txt.imeta"), "cache"); + File.WriteAllText(Path.Combine(root, "asset.txt.abin"), "generated"); Thread.Sleep(100); IReadOnlyList changes = fileSystem.WaitForIdle(); diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs index 775aa37d6..7c3f753b9 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AssetFileSystemTests.cs @@ -6,6 +6,7 @@ using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Core.Identity; namespace Inno.Assets.Pipeline.Tests; @@ -21,7 +22,7 @@ public void RefreshPreservesUnchangedEntryInstancesAndRuntimeIdentities() File.WriteAllText(Path.Combine(root, "Folder", "value.txt"), "value"); using var fileSystem = new AssetFileSystem(root, autoStart: false); AssetFileEntry[] previous = fileSystem.GetEntries().ToArray(); - var identities = previous.Select(static entry => entry.identity.runtimeIdentity).ToArray(); + RuntimeIdentity?[] identities = previous.Select(static entry => entry.identity.runtimeIdentity).ToArray(); fileSystem.Refresh(); for (int index = 0; index < previous.Length; index++) { @@ -46,7 +47,7 @@ public void FailedEnumerationKeepsThePreviousCompleteIndexAndItsIdentities() File.WriteAllText(Path.Combine(root, "value.txt"), "value"); using var fileSystem = new AssetFileSystem(root, autoStart: false); Assert.True(fileSystem.TryGetEntry(AssetPath.Project("value.txt"), out AssetFileEntry previous)); - var identity = previous.identity.runtimeIdentity; + RuntimeIdentity? identity = previous.identity.runtimeIdentity; Directory.Move(root, moved); try { @@ -121,18 +122,18 @@ public void Refresh_IndexesDirectoriesAndFiles() try { Directory.CreateDirectory(Path.Combine(root, "Config")); - System.IO.File.WriteAllText(Path.Combine(root, "Config", "a.json"), "{}"); - System.IO.File.WriteAllText(Path.Combine(root, "readme.txt"), "hi"); + File.WriteAllText(Path.Combine(root, "Config", "a.json"), "{}"); + File.WriteAllText(Path.Combine(root, "readme.txt"), "hi"); using var fs = new AssetFileSystem(root, autoStart: false); - var entries = fs.GetEntries(includeDirectories: true); + IReadOnlyList entries = fs.GetEntries(includeDirectories: true); Assert.Contains(entries, static x => x.assetPath == AssetPath.Project(string.Empty) && x.isDirectory); Assert.Contains(entries, static x => x.assetPath == AssetPath.Project("Config") && x.isDirectory); Assert.Contains(entries, static x => x.assetPath == AssetPath.Project("Config/a.json") && !x.isDirectory); Assert.Contains(entries, static x => x.assetPath == AssetPath.Project("readme.txt") && !x.isDirectory); - var rootChildren = fs.GetChildren(AssetPath.Project(string.Empty)); + IReadOnlyList rootChildren = fs.GetChildren(AssetPath.Project(string.Empty)); Assert.Equal(2, rootChildren.Count); Assert.Equal(AssetPath.Project("Config"), rootChildren[0].assetPath); Assert.Equal(AssetPath.Project("readme.txt"), rootChildren[1].assetPath); @@ -151,10 +152,10 @@ public void Watcher_PublishesChangesOnlyWhenOwnerPolls() { Directory.CreateDirectory(Path.Combine(root, "Config")); string file = Path.Combine(root, "Config", "watch.txt"); - System.IO.File.WriteAllText(file, "a"); + File.WriteAllText(file, "a"); using var fs = new AssetFileSystem(root, autoStart: true, flushDelayMs: 20); - System.IO.File.WriteAllText(file, "b"); + File.WriteAllText(file, "b"); IReadOnlyList batch = fs.WaitForIdle(); Assert.Contains(batch, static x => x.relativePath == "Config/watch.txt"); @@ -173,10 +174,10 @@ public void Entries_ExposeLastExtensionDisplayNameAndFilterDatabaseNoise() try { Directory.CreateDirectory(Path.Combine(root, "Scripts")); - System.IO.File.WriteAllText(Path.Combine(root, "Scripts", "Tool.editor.cs"), "class Tool {} "); - System.IO.File.WriteAllText(Path.Combine(root, "Scripts", "Tool.editor.cs.imeta"), "meta"); - System.IO.File.WriteAllText(Path.Combine(root, "Scripts", "Tool.pdb"), "symbols"); - System.IO.File.WriteAllText(Path.Combine(root, ".DS_Store"), "noise"); + File.WriteAllText(Path.Combine(root, "Scripts", "Tool.editor.cs"), "class Tool {} "); + File.WriteAllText(Path.Combine(root, "Scripts", "Tool.editor.cs.imeta"), "meta"); + File.WriteAllText(Path.Combine(root, "Scripts", "Tool.pdb"), "symbols"); + File.WriteAllText(Path.Combine(root, ".DS_Store"), "noise"); using var fileSystem = new AssetFileSystem(root, autoStart: false); AssetFileEntry entry = Assert.Single(fileSystem.GetEntries(includeDirectories: false)); @@ -198,11 +199,8 @@ public void Refresh_TreatsProjectTildeDirectoriesAsOrdinaryWritableContent() try { Directory.CreateDirectory(Path.Combine(root, "~Starter", "Scenes")); - System.IO.File.WriteAllText( - Path.Combine(root, "~Starter", "Scenes", "Game.cs"), - "public sealed class Game { }" - ); - System.IO.File.WriteAllText(Path.Combine(root, "~Standalone.cs"), "sample-like file"); + File.WriteAllText(Path.Combine(root, "~Starter", "Scenes", "Game.cs"), "public sealed class Game { }"); + File.WriteAllText(Path.Combine(root, "~Standalone.cs"), "sample-like file"); using var fileSystem = new AssetFileSystem(root, autoStart: false); @@ -234,8 +232,8 @@ public void MultipleSourcesKeepCanonicalPathsNamesAndReadOnlyStateIsolated() { Directory.CreateDirectory(project); Directory.CreateDirectory(plugin); - System.IO.File.WriteAllText(Path.Combine(project, "same.txt"), "project"); - System.IO.File.WriteAllText(Path.Combine(plugin, "same.txt"), "plugin"); + File.WriteAllText(Path.Combine(project, "same.txt"), "project"); + File.WriteAllText(Path.Combine(plugin, "same.txt"), "plugin"); var pluginId = new AssetSourceId("tests.mount"); using var fileSystem = new AssetFileSystem( [ @@ -284,10 +282,10 @@ public void Watcher_RenameCarriesOldAndNewPathsThroughOwnerPolling() { string oldPath = Path.Combine(root, "old.txt"); string newPath = Path.Combine(root, "new.txt"); - System.IO.File.WriteAllText(oldPath, "value"); + File.WriteAllText(oldPath, "value"); using var fileSystem = new AssetFileSystem(root, autoStart: true, flushDelayMs: 20); - System.IO.File.Move(oldPath, newPath); + File.Move(oldPath, newPath); IReadOnlyList changes = fileSystem.WaitForIdle(); AssetChangedEvent moved = Assert.Single(changes, static change => diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs index ceb83ffb8..c7987efbe 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Runtime.CompilerServices; +using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -79,8 +80,8 @@ public void Dispose() [Fact] public void ReadOnlyImportFailureDoesNotRewriteMetadataOrThrowAgainWhileRecordingFailure() { - using TestWorkspace workspace = new(); - using TestWorkspace package = new(); + using var workspace = new TestWorkspace(); + using var package = new TestWorkspace(); package.WriteText("README.md", "Documentation"); byte[] metadata = m_serialization.Serialize(new MountedSourceMetadata { @@ -88,7 +89,7 @@ public void ReadOnlyImportFailureDoesNotRewriteMetadataOrThrowAgainWhileRecordin sourceKind = (int)AssetSourceKind.File, importerId = "tests.unavailable.importer" }); - System.IO.File.WriteAllBytes(package.SourcePath("README.md.imeta"), metadata); + File.WriteAllBytes(package.SourcePath("README.md.imeta"), metadata); var source = new AssetSourceId("tests.readonly"); using var loader = new AssetLoader( m_types, @@ -104,7 +105,7 @@ public void ReadOnlyImportFailureDoesNotRewriteMetadataOrThrowAgainWhileRecordin ); Assert.False(loader.Import(new AssetPath(source, "README.md"))); - Assert.Equal(metadata, System.IO.File.ReadAllBytes(package.SourcePath("README.md.imeta"))); + Assert.Equal(metadata, File.ReadAllBytes(package.SourcePath("README.md.imeta"))); Assert.True(loader.TryGetInfo(new AssetPath(source, "README.md"), out AssetInfo? failure)); Assert.Equal(AssetImportStatus.Failed, failure!.status); Assert.Contains(failure.diagnostics, value => value.Contains("Read-only source metadata", StringComparison.Ordinal)); @@ -115,7 +116,7 @@ public void ReadOnlyImportFailureDoesNotRewriteMetadataOrThrowAgainWhileRecordin [InlineData(true)] public void FailedRuntimeDependencyRecoversAfterPublicationOrLoaderRestart(bool reopen) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("parent.depgraph", "child.deferredasset"); workspace.WriteText("child.deferredasset", "unchanged"); DeferredAssetImporter.isAvailable = false; @@ -176,7 +177,7 @@ public void FailedRuntimeDependencyRecoversAfterPublicationOrLoaderRestart(bool [InlineData(true)] public void ExtensionDiscoveryDefersOnlyMissingExtensionsAndRetriesOnceWhenCompleted(bool available) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("surface.extensionasset", "authored"); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); @@ -198,7 +199,7 @@ public void ExtensionDiscoveryDefersOnlyMissingExtensionsAndRetriesOnceWhenCompl Assert.True(pipeline.TryGetInfo(path, out AssetInfo? pending)); Assert.Equal(AssetImportStatus.Pending, pending!.status); Assert.Equal(DiagnosticSeverity.Info, Assert.Single(Assert.Single(sink.reports.Values).diagnostics).severity); - byte[] sidecar = System.IO.File.ReadAllBytes(workspace.SourcePath("surface.extensionasset.imeta")); + byte[] sidecar = File.ReadAllBytes(workspace.SourcePath("surface.extensionasset.imeta")); int attempts = ExtensionDependentImporter.attempts; for (int i = 0; i < 5; i++) { @@ -222,8 +223,8 @@ public void ExtensionDiscoveryDefersOnlyMissingExtensionsAndRetriesOnceWhenCompl Assert.Equal(DiagnosticSeverity.Error, Assert.Single(Assert.Single(sink.reports.Values).diagnostics).severity); } Assert.Equal(pending.persistentId, completed.persistentId); - Assert.Equal(sidecar, System.IO.File.ReadAllBytes(workspace.SourcePath("surface.extensionasset.imeta"))); - Assert.Equal("authored", System.IO.File.ReadAllText(workspace.SourcePath("surface.extensionasset"))); + Assert.Equal(sidecar, File.ReadAllBytes(workspace.SourcePath("surface.extensionasset.imeta"))); + Assert.Equal("authored", File.ReadAllText(workspace.SourcePath("surface.extensionasset"))); attempts = ExtensionDependentImporter.attempts; for (int i = 0; i < 5; i++) { @@ -247,8 +248,8 @@ public void ExtensionDiscoveryDefersOnlyMissingExtensionsAndRetriesOnceWhenCompl [Fact] public void ReadOnlyExtensionWaitPreservesSidecarAndBecomesStrictAfterDiscovery() { - using TestWorkspace workspace = new(); - using TestWorkspace package = new(); + using var workspace = new TestWorkspace(); + using var package = new TestWorkspace(); package.WriteText("surface.extensionasset", "authored"); byte[] metadata = m_serialization.Serialize(new MountedSourceMetadata { @@ -256,7 +257,7 @@ public void ReadOnlyExtensionWaitPreservesSidecarAndBecomesStrictAfterDiscovery( sourceKind = (int)AssetSourceKind.File, importerId = "tests.extension-dependent" }); - System.IO.File.WriteAllBytes(package.SourcePath("surface.extensionasset.imeta"), metadata); + File.WriteAllBytes(package.SourcePath("surface.extensionasset.imeta"), metadata); var source = new AssetSourceId("tests.readonly-extension"); using var pipeline = new AssetPipeline( m_modules, @@ -279,7 +280,7 @@ public void ReadOnlyExtensionWaitPreservesSidecarAndBecomesStrictAfterDiscovery( Assert.Throws(pipeline.CompleteExtensionDiscovery); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? failed)); Assert.Equal(AssetImportStatus.Failed, failed!.status); - Assert.Equal(metadata, System.IO.File.ReadAllBytes(package.SourcePath("surface.extensionasset.imeta"))); + Assert.Equal(metadata, File.ReadAllBytes(package.SourcePath("surface.extensionasset.imeta"))); ExtensionDependentImporter.available = true; Assert.True(pipeline.Import(path)); Assert.True(pipeline.TryGetInfo(path, out AssetInfo? recovered)); @@ -290,7 +291,7 @@ public void ReadOnlyExtensionWaitPreservesSidecarAndBecomesStrictAfterDiscovery( [Fact] public void DiscoveryDoesNotDeferMalformedContentAndCandidateActivationDoesNotHideMissingExtensions() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("bad.mutableasset", "!invalid!"); using var pipeline = new AssetPipeline( m_modules, @@ -330,7 +331,7 @@ public void DiscoveryDoesNotDeferMalformedContentAndCandidateActivationDoesNotHi [InlineData(true)] public void MissingExtensionPropagatesToImportDependentsWithoutHydratingEmptyArtifacts(bool reference) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("surface.extensionasset", "authored"); using var pipeline = new AssetPipeline( m_modules, @@ -368,7 +369,7 @@ public void MissingExtensionPropagatesToImportDependentsWithoutHydratingEmptyArt [InlineData(true)] public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingLastGood(bool reject) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "previous"); using var pipeline = new AssetPipeline( m_modules, @@ -380,7 +381,7 @@ public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingL new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } ); HookAsset previous = pipeline.Load(AssetPath.Project("value.hookasset")); - byte[] previousMeta = System.IO.File.ReadAllBytes(workspace.SourcePath("value.hookasset.imeta")); + byte[] previousMeta = File.ReadAllBytes(workspace.SourcePath("value.hookasset.imeta")); var observer = new CatalogObserver(); using IDisposable registration = m_modules.RegisterCatalogParticipant(observer); workspace.WriteText("value.hookasset", "candidate"); @@ -390,7 +391,7 @@ public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingL Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); Assert.Equal("previous", Encoding.UTF8.GetString(previous.runtimePayload.Span)); Assert.False(pipeline.TryGetInfo(AssetPath.Project("new.txt"), out _)); - Assert.False(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("new.txt.imeta"))); }; observer.activate = () => { @@ -398,7 +399,7 @@ public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingL Assert.NotSame(previous, published); Assert.Equal("candidate", Encoding.UTF8.GetString(published.runtimePayload.Span)); Assert.Equal("previous", Encoding.UTF8.GetString(previous.runtimePayload.Span)); - Assert.False(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("new.txt.imeta"))); if (reject) { throw new InvalidOperationException("Expected later participant rejection."); @@ -410,8 +411,8 @@ public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingL Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); Assert.Equal(0, previous.unloadingCount); Assert.Equal("previous", Encoding.UTF8.GetString(previous.runtimePayload.Span)); - Assert.Equal(previousMeta, System.IO.File.ReadAllBytes(workspace.SourcePath("value.hookasset.imeta"))); - Assert.False(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.Equal(previousMeta, File.ReadAllBytes(workspace.SourcePath("value.hookasset.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("new.txt.imeta"))); Assert.False(pipeline.TryGetInfo(AssetPath.Project("new.txt"), out _)); } else @@ -419,7 +420,7 @@ public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingL m_modules.Rebuild(); Assert.NotSame(previous, pipeline.Load(previous.identity.persistentId)); Assert.Equal(1, previous.unloadingCount); - Assert.True(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.True(File.Exists(workspace.SourcePath("new.txt.imeta"))); } observer.prepare = null; observer.activate = null; @@ -428,7 +429,7 @@ public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingL m_modules.Rebuild(); Assert.NotSame(previous, pipeline.Load(previous.identity.persistentId)); Assert.Equal(1, previous.unloadingCount); - Assert.True(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.True(File.Exists(workspace.SourcePath("new.txt.imeta"))); } } @@ -437,7 +438,7 @@ public void AssemblyCatalogPublishesAnIsolatedLoaderAndRollsBackWithoutTouchingL [InlineData(true)] public void AssemblyCatalogJoinsAnExistingSourceCandidateWithoutTakingItsPublicationOwnership(bool reject) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.txt", "previous"); using var pipeline = new AssetPipeline( m_modules, @@ -488,7 +489,7 @@ public void AssemblyCatalogJoinsAnExistingSourceCandidateWithoutTakingItsPublica [Fact] public void IntroducedImportFailureLeavesTheLiveAssetAndCatalogUntouched() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.mutableasset", "previous"); using var pipeline = new AssetPipeline( m_modules, @@ -500,14 +501,14 @@ public void IntroducedImportFailureLeavesTheLiveAssetAndCatalogUntouched() new AssetPipelineOptions { assetRoot = workspace.assetRoot, libraryRoot = workspace.libraryRoot } ); MutableAsset previous = pipeline.Load(AssetPath.Project("value.mutableasset")); - byte[] sidecar = System.IO.File.ReadAllBytes(workspace.SourcePath("value.mutableasset.imeta")); + byte[] sidecar = File.ReadAllBytes(workspace.SourcePath("value.mutableasset.imeta")); workspace.WriteText("value.mutableasset", "!invalid!"); Assert.Throws(m_modules.Rebuild); Assert.Same(previous, m_identities.Get(previous.identity.persistentId)); Assert.Equal("previous", previous.value); Assert.True(pipeline.TryGetInfo(previous.identity.persistentId, out AssetInfo? info)); Assert.Equal(AssetImportStatus.Imported, info!.status); - Assert.Equal(sidecar, System.IO.File.ReadAllBytes(workspace.SourcePath("value.mutableasset.imeta"))); + Assert.Equal(sidecar, File.ReadAllBytes(workspace.SourcePath("value.mutableasset.imeta"))); workspace.WriteText("value.mutableasset", "recovered"); m_modules.Rebuild(); MutableAsset recovered = pipeline.Load(previous.identity.persistentId); @@ -518,8 +519,8 @@ public void IntroducedImportFailureLeavesTheLiveAssetAndCatalogUntouched() [Fact] public void CandidateMetadataRejectsExternalChangesWithoutOverwritingThem() { - using TestWorkspace workspace = new(); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using var workspace = new TestWorkspace(); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); workspace.WriteText("new.txt", "candidate"); using AssetCatalogCandidate candidate = loader.PrepareCatalogCandidate( [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)] @@ -527,23 +528,23 @@ [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)] using AssetLoader candidateLoader = candidate.loader; candidateLoader.Rescan(); string sidecarPath = workspace.SourcePath("new.txt.imeta"); - Assert.False(System.IO.File.Exists(sidecarPath)); + Assert.False(File.Exists(sidecarPath)); byte[] external = m_serialization.Serialize(new MountedSourceMetadata { persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.File, importerId = "external.importer" }); - System.IO.File.WriteAllBytes(sidecarPath, external); + File.WriteAllBytes(sidecarPath, external); Assert.Throws(candidate.Commit); - Assert.Equal(external, System.IO.File.ReadAllBytes(sidecarPath)); + Assert.Equal(external, File.ReadAllBytes(sidecarPath)); } [Fact] public void CandidateMetadataCompensatesEarlierSidecarsWhenALaterWriteFails() { - using TestWorkspace workspace = new(); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using var workspace = new TestWorkspace(); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); workspace.WriteText("a.txt", "first"); workspace.WriteText("z.txt", "last"); using AssetCatalogCandidate candidate = loader.PrepareCatalogCandidate( @@ -554,7 +555,7 @@ [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)] Directory.CreateDirectory(workspace.SourcePath("z.txt.imeta")); Exception failure = Assert.ThrowsAny(candidate.Commit); Assert.True(failure is IOException or UnauthorizedAccessException, failure.ToString()); - Assert.False(System.IO.File.Exists(workspace.SourcePath("a.txt.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("a.txt.imeta"))); Assert.True(Directory.Exists(workspace.SourcePath("z.txt.imeta"))); } @@ -563,7 +564,7 @@ [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)] [InlineData(true)] public void CandidateDiagnosticsPublishOnlyWithTheirSourceGenerationAndRetireWithoutErasingAnotherOwner(bool commit) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("previous.mutableasset", "!invalid!"); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); @@ -602,13 +603,13 @@ public void CandidateDiagnosticsPublishOnlyWithTheirSourceGenerationAndRetireWit [Fact] public void CandidateCommitRestoresCatalogAndSidecarsWhenJournalRetirementFails() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("previous.txt", "last good"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); string snapshotPath = Path.Combine(workspace.libraryRoot, "AssetDatabase", "Catalog.snapshot"); string journalPath = Path.Combine(workspace.libraryRoot, "AssetDatabase", "Catalog.journal"); - byte[] previous = System.IO.File.ReadAllBytes(snapshotPath); + byte[] previous = File.ReadAllBytes(snapshotPath); workspace.WriteText("new.txt", "candidate"); using AssetCatalogCandidate candidate = loader.PrepareCatalogCandidate( [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)] @@ -619,8 +620,8 @@ [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)] Exception? failure = Record.Exception(candidate.Commit); Assert.True(failure is IOException or UnauthorizedAccessException, failure?.ToString()); - Assert.Equal(previous, System.IO.File.ReadAllBytes(snapshotPath)); - Assert.False(System.IO.File.Exists(workspace.SourcePath("new.txt.imeta"))); + Assert.Equal(previous, File.ReadAllBytes(snapshotPath)); + Assert.False(File.Exists(workspace.SourcePath("new.txt.imeta"))); Assert.True(Directory.Exists(journalPath)); Assert.False(loader.TryGetInfo(AssetPath.Project("new.txt"), out _)); } @@ -628,7 +629,7 @@ [new AssetSourceMount(AssetSourceId.project, workspace.assetRoot, false)] [Fact] public void CandidateDiagnosticRecoveryCanRollBackToThePreviousUnresolvedReport() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.mutableasset", "!invalid!"); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); @@ -685,7 +686,7 @@ public void Rollback() {} [InlineData(true)] public void SourceCandidatePublishesCanonicalIdentitiesOnlyDuringSharedRecovery(bool commit) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.txt", "old"); using var pipeline = new AssetPipeline( m_modules, @@ -738,7 +739,7 @@ public void SourceCandidatePublishesCanonicalIdentitiesOnlyDuringSharedRecovery( [Fact] public void SourceCandidateIdentityConflictRestoresThePreviousDomain() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("previous.txt", "old"); using var pipeline = new AssetPipeline( m_modules, @@ -772,7 +773,7 @@ public void SourceCandidateIdentityConflictRestoresThePreviousDomain() [Fact] public void SourceRemovalAndReturnKeepTheSameRecoverySlotAndNeutralState() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.txt", "preserved"); using var pipeline = new AssetPipeline( m_modules, @@ -785,8 +786,8 @@ public void SourceRemovalAndReturnKeepTheSameRecoverySlotAndNeutralState() ); TextAsset previous = pipeline.Load(AssetPath.Project("value.txt")); Guid id = previous.identity.persistentId; - byte[] metadata = System.IO.File.ReadAllBytes(workspace.SourcePath("value.txt.imeta")); - System.IO.File.Delete(workspace.SourcePath("value.txt")); + byte[] metadata = File.ReadAllBytes(workspace.SourcePath("value.txt.imeta")); + File.Delete(workspace.SourcePath("value.txt")); using AssetSourceMountTransaction removal = pipeline.PrepareSourceMounts(pipeline.sourceMounts); removal.Activate(); ReferenceRecoveryChange missing = Assert.Single(removal.recoveryChanges); @@ -801,7 +802,7 @@ public void SourceRemovalAndReturnKeepTheSameRecoverySlotAndNeutralState() Assert.Equal(ReferenceResolutionState.Missing, Assert.Single(stillMissing.recoveryChanges).resolution.state); stillMissing.Complete(); workspace.WriteText("value.txt", "preserved"); - System.IO.File.WriteAllBytes(workspace.SourcePath("value.txt.imeta"), metadata); + File.WriteAllBytes(workspace.SourcePath("value.txt.imeta"), metadata); using AssetSourceMountTransaction recovery = pipeline.PrepareSourceMounts(pipeline.sourceMounts); recovery.Activate(); ReferenceRecoveryChange restored = Assert.Single(recovery.recoveryChanges); @@ -817,7 +818,7 @@ public void SourceRemovalAndReturnKeepTheSameRecoverySlotAndNeutralState() [InlineData(true)] public void SourceRetirementDrainsPendingHooksBeforeCompletingTheTransaction(bool commit) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "previous"); using var pipeline = new AssetPipeline( m_modules, @@ -859,9 +860,9 @@ public void SourceRetirementDrainsPendingHooksBeforeCompletingTheTransaction(boo [Fact] public void LoaderRetirementRetainsPendingAssetPayloadAndRegistration() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "payload"); - var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); HookAsset asset = Assert.IsType(loader.Load(AssetPath.Project("value.hookasset"), typeof(HookAsset))); RuntimeIdentity identity = asset.identity.runtimeIdentity!.Value; asset.pendingUnloads = 1; @@ -880,7 +881,7 @@ public void LoaderRetirementRetainsPendingAssetPayloadAndRegistration() [Fact] public void PipelineShutdownDrainsCanonicalAssetsBeforeReleasingTheirOwners() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "payload"); var pipeline = new AssetPipeline( m_modules, @@ -903,10 +904,10 @@ public void PipelineShutdownDrainsCanonicalAssetsBeforeReleasingTheirOwners() [Fact] public void LoaderRetirementKeepsEarlierFailuresAcrossPendingResources() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("a.hookasset", "pending"); workspace.WriteText("b.hookasset", "failure"); - var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); HookAsset pending = Assert.IsType(loader.Load(AssetPath.Project("a.hookasset"), typeof(HookAsset))); HookAsset failing = Assert.IsType(loader.Load(AssetPath.Project("b.hookasset"), typeof(HookAsset))); pending.pendingUnloads = 1; @@ -925,11 +926,11 @@ public void LoaderRetirementKeepsEarlierFailuresAcrossPendingResources() [Fact] public void LoaderShutdownIncludesCanonicalTombstones() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "payload"); - var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); HookAsset asset = Assert.IsType(loader.Load(AssetPath.Project("value.hookasset"), typeof(HookAsset))); - System.IO.File.Delete(workspace.SourcePath("value.hookasset")); + File.Delete(workspace.SourcePath("value.hookasset")); loader.Rescan(); Assert.True(asset.isMissing); loader.Dispose(); @@ -940,9 +941,9 @@ public void LoaderShutdownIncludesCanonicalTombstones() [Fact] public async Task LoaderDisposalDoesNotBlockAnInFlightLoadOrAdmitNewWork() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.slowasset", "payload"); - var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Task loading = loader.LoadAsync(AssetPath.Project("value.slowasset"), typeof(SlowAsset)).AsTask(); try { @@ -965,7 +966,7 @@ public async Task LoaderDisposalDoesNotBlockAnInFlightLoadOrAdmitNewWork() [InlineData(true)] public void SourceRetirementTimeoutFaultsAdmissionAndKeepsBothGenerationsOwned(bool commit) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "previous"); var modules = new ModuleHost(new ModuleHostOptions { @@ -1017,9 +1018,9 @@ public void SourceRetirementTimeoutFaultsAdmissionAndKeepsBothGenerationsOwned(b [Fact] public void RuntimeDatabaseRetainsPendingPayloadAndRegistrationUntilShutdownCompletes() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "runtime payload"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("value.hookasset"), typeof(HookAsset))); string contentRoot = Path.Combine(workspace.libraryRoot, "Runtime"); loader.ExportRuntimeArtifacts(contentRoot); @@ -1045,10 +1046,10 @@ public void RuntimeDatabaseRetainsPendingPayloadAndRegistrationUntilShutdownComp [Fact] public void OneImporterCanKeepGraphInputsInAuthoringWhileExportingExecutableAssets() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("node.mixedscope", "authoring"); workspace.WriteText("shader.mixedscope", "runtime"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("node.mixedscope"), typeof(DependencyAsset))); Assert.NotNull(loader.Load(AssetPath.Project("shader.mixedscope"), typeof(DependencyAsset))); string contentRoot = Path.Combine(workspace.libraryRoot, "Runtime"); @@ -1065,9 +1066,9 @@ public void OneImporterCanKeepGraphInputsInAuthoringWhileExportingExecutableAsse [Fact] public async Task RuntimeLeaseRetriesPendingBudgetEvictionWithoutReleasingAnotherLease() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("value.hookasset", "leased payload"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("value.hookasset"), typeof(HookAsset))); string contentRoot = Path.Combine(workspace.libraryRoot, "Runtime"); loader.ExportRuntimeArtifacts(contentRoot); @@ -1117,19 +1118,26 @@ private sealed class IdentityConflict : IdentityObject; private sealed class MountedSourceMetadata : ISerializable { - [SerializableProperty] public Guid persistentId { get; set; } - [SerializableProperty] public int sourceKind { get; set; } - [SerializableProperty] public string importerId { get; set; } = string.Empty; - [SerializableProperty] public byte[] importerSettingsBytes { get; set; } = []; + [SerializableProperty] + public Guid persistentId { get; set; } + + [SerializableProperty] + public int sourceKind { get; set; } + + [SerializableProperty] + public string importerId { get; set; } = string.Empty; + + [SerializableProperty] + public byte[] importerSettingsBytes { get; set; } = []; } [Fact] public void MissingReferenceNeverBindsAnotherIdentityAtItsLastKnownPath() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/replaced.txt", "replacement"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); - var replacement = Assert.IsType(loader.Load(AssetPath.Project("Text/replaced.txt"), typeof(TextAsset))); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + TextAsset replacement = Assert.IsType(loader.Load(AssetPath.Project("Text/replaced.txt"), typeof(TextAsset))); Guid intended = Guid.NewGuid(); Assert.True(m_types.TryGetTypeRef(typeof(TextAsset), out TypeRef type)); @@ -1151,12 +1159,12 @@ public void ExtensionContractsUseImplementationIdentityWithoutManualVersions() [Fact] public void Import_WritesCacheWithoutCreatingCanonicalInstance() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Config/game.txt", "one"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.True(loader.Import(AssetPath.Project("Config/game.txt"))); - Assert.True(System.IO.File.Exists(workspace.SourcePath("Config/game.txt.imeta"))); + Assert.True(File.Exists(workspace.SourcePath("Config/game.txt.imeta"))); Assert.True(loader.TryGetPersistentId(AssetPath.Project("Config/game.txt"), out Guid persistentId)); Assert.NotEqual(Guid.Empty, persistentId); Assert.True(loader.TryGetArtifact(persistentId, "runtime", out AssetArtifactInfo? artifact)); @@ -1171,9 +1179,9 @@ public void Import_WritesCacheWithoutCreatingCanonicalInstance() [Fact] public void AutomaticallyDiscoveredPrivateImporter_LoadsWithoutRegistrationApi() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Private/item.privateasset", "private"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); PrivateConstructorAsset asset = Assert.IsType( loader.Load(AssetPath.Project("Private/item.privateasset"), typeof(PrivateConstructorAsset)) @@ -1187,10 +1195,10 @@ public void AutomaticallyDiscoveredPrivateImporter_LoadsWithoutRegistrationApi() [Fact] public void SameAssetType_CanUseMultipleImportersForDifferentExtensions() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Graphs/a.depgraph", string.Empty); workspace.WriteText("Graphs/b.depgraph2", string.Empty); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.IsType(loader.Load(AssetPath.Project("Graphs/a.depgraph"), typeof(DependencyAsset))); Assert.IsType(loader.Load(AssetPath.Project("Graphs/b.depgraph2"), typeof(DependencyAsset))); @@ -1199,9 +1207,9 @@ public void SameAssetType_CanUseMultipleImportersForDifferentExtensions() [Fact] public void DuplicateImporterId_IsRejectedDuringAutomaticDiscovery() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Conflict/initialize.txt", "initialize"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.True(loader.Import(AssetPath.Project("Conflict/initialize.txt"))); InvalidOperationException exception = Assert.Throws( () => m_modules.Load(new DotNetModuleSource @@ -1225,9 +1233,9 @@ public void DuplicateImporterId_IsRejectedDuringAutomaticDiscovery() [Fact] public void DuplicateImporterExtension_IsRejectedDuringAutomaticDiscovery() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Conflict/value.conflict", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); ImporterConflictProbe.duplicateExtension = true; InvalidOperationException exception = Assert.Throws( @@ -1240,9 +1248,9 @@ public void DuplicateImporterExtension_IsRejectedDuringAutomaticDiscovery() [Fact] public void PathAndPersistentIdLoads_ReturnCanonicalInstance() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/shared.txt", "shared"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset byPath = Assert.IsType(loader.Load(AssetPath.Project("Text/shared.txt"), typeof(TextAsset))); TextAsset byId = Assert.IsType(loader.Load(byPath.identity.persistentId, typeof(TextAsset))); @@ -1254,7 +1262,7 @@ public void PathAndPersistentIdLoads_ReturnCanonicalInstance() [Fact] public void BlockedSourceVerificationRetainsLastGoodArtifactAndReportsImportFailure() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/cached.txt", "cached"); using (AssetLoader first = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs)) { @@ -1282,15 +1290,15 @@ public void BlockedSourceVerificationRetainsLastGoodArtifactAndReportsImportFail [Fact] public void ChangedStampWithEqualContent_DoesNotReimportCanonicalAsset() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/touched.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset before = Assert.IsType( loader.Load(AssetPath.Project("Text/touched.txt"), typeof(TextAsset)) ); long version = before.contentVersion; string sourcePath = workspace.SourcePath("Text/touched.txt"); - System.IO.File.SetLastWriteTimeUtc(sourcePath, System.IO.File.GetLastWriteTimeUtc(sourcePath).AddSeconds(1)); + File.SetLastWriteTimeUtc(sourcePath, File.GetLastWriteTimeUtc(sourcePath).AddSeconds(1)); TextAsset after = Assert.IsType( loader.Load(AssetPath.Project("Text/touched.txt"), typeof(TextAsset)) @@ -1303,10 +1311,10 @@ public void ChangedStampWithEqualContent_DoesNotReimportCanonicalAsset() [Fact] public void BlockedDependencyVerificationRetainsLastGoodArtifactAndReportsImportFailure() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Import/schema.inc", "schema"); workspace.WriteText("Import/root.importgraph", "Import/schema.inc"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.True(loader.Import(AssetPath.Project("Import/root.importgraph"))); using var sourceLock = new FileStream( workspace.SourcePath("Import/schema.inc"), @@ -1327,9 +1335,9 @@ public void BlockedDependencyVerificationRetainsLastGoodArtifactAndReportsImport [Fact] public async Task ConcurrentAsyncLoads_ShareImportAndCancellationOnlyCancelsOneWaiter() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Slow/item.slowasset", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); using var cancellation = new CancellationTokenSource(); ValueTask first = loader.LoadAsync(AssetPath.Project("Slow/item.slowasset"), typeof(SlowAsset)); @@ -1352,18 +1360,18 @@ public async Task ConcurrentAsyncLoads_ShareImportAndCancellationOnlyCancelsOneW [Fact] public void ChangedDependencyWithPreservedTimestampReimportsTheCanonicalAsset() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Import/schema.inc", "first"); workspace.WriteText("Import/root.importgraph", "Import/schema.inc"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); ImportGraphAsset before = Assert.IsType( loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset)) ); long version = before.contentVersion; string dependency = workspace.SourcePath("Import/schema.inc"); - DateTime timestamp = System.IO.File.GetLastWriteTimeUtc(dependency); + DateTime timestamp = File.GetLastWriteTimeUtc(dependency); workspace.WriteText("Import/schema.inc", "other"); - System.IO.File.SetLastWriteTimeUtc(dependency, timestamp); + File.SetLastWriteTimeUtc(dependency, timestamp); ImportGraphAsset after = Assert.IsType( loader.Load(AssetPath.Project("Import/root.importgraph"), typeof(ImportGraphAsset)) @@ -1379,19 +1387,19 @@ public void ChangedDependencyWithPreservedTimestampReimportsTheCanonicalAsset() [InlineData(true)] public void StaleSource_ReimportsAndUpdatesCanonicalInstanceInPlace(bool preserveTimestamp) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/reload.txt", "one"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset before = Assert.IsType(loader.Load(AssetPath.Project("Text/reload.txt"), typeof(TextAsset))); Guid persistentId = before.identity.persistentId; long version = before.contentVersion; string sourcePath = workspace.SourcePath("Text/reload.txt"); - DateTime sourceTime = System.IO.File.GetLastWriteTimeUtc(sourcePath); + DateTime sourceTime = File.GetLastWriteTimeUtc(sourcePath); workspace.WriteText("Text/reload.txt", "two"); if (preserveTimestamp) { - System.IO.File.SetLastWriteTimeUtc(sourcePath, sourceTime); + File.SetLastWriteTimeUtc(sourcePath, sourceTime); } TextAsset after = Assert.IsType(loader.Load(AssetPath.Project("Text/reload.txt"), typeof(TextAsset))); @@ -1404,10 +1412,10 @@ public void StaleSource_ReimportsAndUpdatesCanonicalInstanceInPlace(bool preserv [Fact] public void RuntimeDependencyCycle_IsAllowedAndLoadsAsOneCanonicalSubgraph() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Graphs/a.depgraph", "Graphs/b.depgraph"); workspace.WriteText("Graphs/b.depgraph", "Graphs/a.depgraph"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); DependencyAsset root = Assert.IsType( loader.Load(AssetPath.Project("Graphs/a.depgraph"), typeof(DependencyAsset)) @@ -1427,7 +1435,7 @@ public void RuntimeDependencyCycle_IsAllowedAndLoadsAsOneCanonicalSubgraph() [InlineData("invalid")] public async Task AsyncRuntimeExportReleasesItsGenerationLeaseAfterEveryOutcome(string outcome) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("leaf.buildinput", "original"); using var pipeline = new AssetPipeline( m_modules, @@ -1475,9 +1483,9 @@ public void RuntimeExportRejectsTransitiveAuthoringInputsWithoutDiscardingLastGo string change, bool importChange ) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("leaf.buildinput", "original"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.True(loader.Import(AssetPath.Project("leaf.buildinput"))); AssetObject leaf = Assert.IsType(loader.Load(AssetPath.Project("leaf.buildinput"), typeof(DependencyAsset))); workspace.WriteText("middle.buildinput", leaf.identity.persistentId.ToString()); @@ -1517,11 +1525,11 @@ bool importChange [InlineData(true)] public async Task ColdRootsShareDependencyIoAndRetireReservationsAcrossRepeatedCycles(bool cancelFirst) { - using TestWorkspace workspace = new(); - workspace.WriteText("Shared.txt", new string('s', 65536)); + using var workspace = new TestWorkspace(); + workspace.WriteText("Shared.txt", new string('s', 65_536)); workspace.WriteText("A.depgraph", "Shared.txt"); workspace.WriteText("B.depgraph", "Shared.txt"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("A.depgraph"), typeof(DependencyAsset))); Assert.NotNull(loader.Load(AssetPath.Project("B.depgraph"), typeof(DependencyAsset))); string contentRoot = Path.Combine(workspace.libraryRoot, "Runtime"); @@ -1534,7 +1542,7 @@ public async Task ColdRootsShareDependencyIoAndRetireReservationsAcrossRepeatedC m_types.current, new IdentityAllocator(), residencyBudgetBytes: 0, - preparationBudgetBytes: 100000 + preparationBudgetBytes: 100_000 ); for (int cycle = 0; cycle < 32; cycle++) { @@ -1578,16 +1586,16 @@ public async Task ColdRootsShareDependencyIoAndRetireReservationsAcrossRepeatedC Assert.Equal(96, statistics.payloadReadsStarted); Assert.Equal(32, statistics.sharedPayloadReads); Assert.Equal(2, statistics.peakPendingRequests); - Assert.InRange(statistics.peakReservedBytes, 65536, 100000); + Assert.InRange(statistics.peakReservedBytes, 65_536, 100_000); Assert.Equal(0, statistics.rejectedRequests); } [Fact] public void ColdAdmissionCountersRemainBoundedAndDisposeDrainsEveryCanceledWaiter() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Shared.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("Shared.txt"), typeof(TextAsset))); string contentRoot = Path.Combine(workspace.libraryRoot, "Runtime"); loader.ExportRuntimeArtifacts(contentRoot); @@ -1611,11 +1619,11 @@ public void ColdAdmissionCountersRemainBoundedAndDisposeDrainsEveryCanceledWaite [Fact] public void CorruptSharedPayloadFailsBothRootsWithoutLeakingReservationsOrPublishingAssets() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Shared.txt", "payload"); workspace.WriteText("A.depgraph", "Shared.txt"); workspace.WriteText("B.depgraph", "Shared.txt"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.NotNull(loader.Load(AssetPath.Project("A.depgraph"), typeof(DependencyAsset))); Assert.NotNull(loader.Load(AssetPath.Project("B.depgraph"), typeof(DependencyAsset))); AssetObject shared = Assert.IsType(loader.Load(AssetPath.Project("Shared.txt"), typeof(TextAsset))); @@ -1634,7 +1642,7 @@ public void CorruptSharedPayloadFailsBothRootsWithoutLeakingReservationsOrPublis )) ).key; byte[] bytes = artifact.ReadAllBytes(); - bytes[0] ^= 0xff; + bytes[0] ^= 0xFF; contentStore.CorruptPayload(key, bytes); } Task> first = database.AcquireAsync(AssetPath.Project("A.depgraph")).AsTask(); @@ -1658,10 +1666,10 @@ public void CorruptSharedPayloadFailsBothRootsWithoutLeakingReservationsOrPublis [Fact] public void ImportDependencyCycle_IsRejectedWithClosedPathChain() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Import/a.importgraph", "Import/b.importgraph"); workspace.WriteText("Import/b.importgraph", "Import/a.importgraph"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); Assert.True(loader.Import(AssetPath.Project("Import/a.importgraph"))); Assert.False(loader.Import(AssetPath.Project("Import/b.importgraph"))); @@ -1678,15 +1686,15 @@ public void ImportDependencyCycle_IsRejectedWithClosedPathChain() [Fact] public void RenameAndDelete_UpdateCanonicalInstanceWithoutChangingIdentity() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/old.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset asset = Assert.IsType(loader.Load(AssetPath.Project("Text/old.txt"), typeof(TextAsset))); Guid persistentId = asset.identity.persistentId; workspace.Move("Text/old.txt", "Text/new.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Renamed, "Text/old.txt") + new AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Renamed, "Text/old.txt") ]); Assert.Equal("Text/new.txt", asset.assetPath.ToString()); @@ -1694,13 +1702,13 @@ public void RenameAndDelete_UpdateCanonicalInstanceWithoutChangingIdentity() workspace.DeleteSource("Text/new.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Deleted) + new AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Deleted) ]); Assert.True(asset.isMissing); Assert.Equal(persistentId, asset.identity.persistentId); Assert.True(asset.runtimePayload.IsEmpty); - Assert.False(System.IO.File.Exists(workspace.SourcePath("Text/new.txt.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("Text/new.txt.imeta"))); Assert.False(loader.TryGetInfo(AssetPath.Project("Text/new.txt"), out _)); Assert.True(loader.TryGetInfo(persistentId, out AssetInfo? tombstone)); Assert.NotNull(tombstone); @@ -1712,18 +1720,18 @@ public void RenameAndDelete_UpdateCanonicalInstanceWithoutChangingIdentity() [Fact] public void RecreatedSourceWithoutMetadata_ReceivesNewIdentity() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/recover.txt", "one"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset asset = Assert.IsType(loader.Load(AssetPath.Project("Text/recover.txt"), typeof(TextAsset))); workspace.DeleteSource("Text/recover.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Deleted) + new AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Deleted) ]); workspace.WriteText("Text/recover.txt", "two"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Created) + new AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Created) ]); TextAsset replacement = Assert.IsType( @@ -1739,7 +1747,7 @@ public void RecreatedSourceWithoutMetadata_ReceivesNewIdentity() [Fact] public void Tombstone_SurvivesCatalogRestartWithoutOccupyingItsFormerPath() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/value.txt", "one"); Guid oldId; using (AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs)) @@ -1748,7 +1756,7 @@ public void Tombstone_SurvivesCatalogRestartWithoutOccupyingItsFormerPath() Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/value.txt"), out oldId)); workspace.DeleteSource("Text/value.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/value.txt", WatcherChangeTypes.Deleted) + new AssetChangedEvent("Text/value.txt", WatcherChangeTypes.Deleted) ]); } @@ -1765,7 +1773,7 @@ public void Tombstone_SurvivesCatalogRestartWithoutOccupyingItsFormerPath() [Fact] public void CatalogRestart_PrefersCurrentSourceIdentityOverHistoricalPathRecord() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); const string path = "Text/identity.txt"; workspace.WriteText(path, "value"); Guid historicalId; @@ -1782,11 +1790,11 @@ public void CatalogRestart_PrefersCurrentSourceIdentityOverHistoricalPathRecord( string sidecarPath = workspace.SourcePath(path + ".imeta"); MountedSourceMetadata metadata = m_serialization.Deserialize( - System.IO.File.ReadAllBytes(sidecarPath) + File.ReadAllBytes(sidecarPath) ); Guid currentId = Guid.NewGuid(); metadata.persistentId = currentId; - System.IO.File.WriteAllBytes(sidecarPath, m_serialization.Serialize(metadata)); + File.WriteAllBytes(sidecarPath, m_serialization.Serialize(metadata)); using (AssetLoader recovered = workspace.CreateLoader( m_types, @@ -1813,7 +1821,7 @@ public void CatalogRestart_PrefersCurrentSourceIdentityOverHistoricalPathRecord( Assert.True(restarted.TryGetPersistentId(AssetPath.Project(path), out Guid stableId)); Assert.Equal(currentId, stableId); MountedSourceMetadata stableMetadata = m_serialization.Deserialize( - System.IO.File.ReadAllBytes(sidecarPath) + File.ReadAllBytes(sidecarPath) ); Assert.Equal(currentId, stableMetadata.persistentId); } @@ -1821,7 +1829,7 @@ public void CatalogRestart_PrefersCurrentSourceIdentityOverHistoricalPathRecord( [Fact] public void CatalogRestart_DoesNotPromoteHistoricalTombstonesToMissingReferences() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/removed.txt", "one"); Guid removedId; using (AssetLoader loader = workspace.CreateLoader( @@ -1835,7 +1843,7 @@ public void CatalogRestart_DoesNotPromoteHistoricalTombstonesToMissingReferences Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/removed.txt"), out removedId)); workspace.DeleteSource("Text/removed.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/removed.txt", WatcherChangeTypes.Deleted) + new AssetChangedEvent("Text/removed.txt", WatcherChangeTypes.Deleted) ]); } @@ -1895,21 +1903,21 @@ public void CatalogRestart_DoesNotPromoteHistoricalTombstonesToMissingReferences [Fact] public void RestoredSourceAndMetadata_ReactivatesOriginalIdentityInPlace() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/recover.txt", "one"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); TextAsset asset = Assert.IsType(loader.Load(AssetPath.Project("Text/recover.txt"), typeof(TextAsset))); Guid id = asset.identity.persistentId; - byte[] metadata = System.IO.File.ReadAllBytes(workspace.SourcePath("Text/recover.txt.imeta")); + byte[] metadata = File.ReadAllBytes(workspace.SourcePath("Text/recover.txt.imeta")); workspace.DeleteSource("Text/recover.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Deleted) + new AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Deleted) ]); workspace.WriteText("Text/recover.txt", "two"); - System.IO.File.WriteAllBytes(workspace.SourcePath("Text/recover.txt.imeta"), metadata); + File.WriteAllBytes(workspace.SourcePath("Text/recover.txt.imeta"), metadata); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Created) + new AssetChangedEvent("Text/recover.txt", WatcherChangeTypes.Created) ]); TextAsset restored = Assert.IsType(loader.Load(AssetPath.Project("Text/recover.txt"), typeof(TextAsset))); @@ -1922,31 +1930,31 @@ public void RestoredSourceAndMetadata_ReactivatesOriginalIdentityInPlace() [Fact] public void DeleteCreateRenameFallback_PreservesIdentityOnlyWhenFingerprintMatchIsUnique() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/old.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/old.txt"), out Guid id)); workspace.Move("Text/old.txt", "Text/new.txt"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/old.txt", WatcherChangeTypes.Deleted), - new Inno.Assets.Pipeline.AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Created) + new AssetChangedEvent("Text/old.txt", WatcherChangeTypes.Deleted), + new AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Created) ]); Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/new.txt"), out Guid movedId)); Assert.Equal(id, movedId); - Assert.False(System.IO.File.Exists(workspace.SourcePath("Text/old.txt.imeta"))); - Assert.True(System.IO.File.Exists(workspace.SourcePath("Text/new.txt.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("Text/old.txt.imeta"))); + Assert.True(File.Exists(workspace.SourcePath("Text/new.txt.imeta"))); } [Fact] public void AmbiguousDeleteCreateRenameFallback_DoesNotGuessAnIdentity() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/first.txt", "same"); workspace.WriteText("Text/second.txt", "same"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/first.txt"), out Guid firstId)); Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/second.txt"), out Guid secondId)); @@ -1955,9 +1963,9 @@ public void AmbiguousDeleteCreateRenameFallback_DoesNotGuessAnIdentity() workspace.DeleteSource("Text/second.txt"); workspace.WriteText("Text/new.txt", "same"); loader.ApplySourceChanges([ - new Inno.Assets.Pipeline.AssetChangedEvent("Text/first.txt", WatcherChangeTypes.Deleted), - new Inno.Assets.Pipeline.AssetChangedEvent("Text/second.txt", WatcherChangeTypes.Deleted), - new Inno.Assets.Pipeline.AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Created) + new AssetChangedEvent("Text/first.txt", WatcherChangeTypes.Deleted), + new AssetChangedEvent("Text/second.txt", WatcherChangeTypes.Deleted), + new AssetChangedEvent("Text/new.txt", WatcherChangeTypes.Created) ]); Assert.True(loader.TryGetPersistentId(AssetPath.Project("Text/new.txt"), out Guid newId)); @@ -1975,8 +1983,8 @@ public void AmbiguousDeleteCreateRenameFallback_DoesNotGuessAnIdentity() [Fact] public void Save_PreservesIdentityIncrementsVersionAndRejectsDifferentPath() { - using TestWorkspace workspace = new(); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using var workspace = new TestWorkspace(); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); var asset = new MutableAsset { value = "one" }; Assert.True(loader.Save(AssetPath.Project("Data/value.mutableasset"), asset)); @@ -1995,9 +2003,9 @@ public void Save_PreservesIdentityIncrementsVersionAndRejectsDifferentPath() [Fact] public void FailedReimport_KeepsPreviousCanonicalStateAndVersion() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Data/stable.mutableasset", "one"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); MutableAsset asset = Assert.IsType( loader.Load(AssetPath.Project("Data/stable.mutableasset"), typeof(MutableAsset)) ); @@ -2017,9 +2025,9 @@ public void FailedReimport_KeepsPreviousCanonicalStateAndVersion() [Fact] public void FailedReimport_PublishesCurrentDiagnosticUntilSuccessfulRetry() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Data/diagnostic.mutableasset", "valid"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); var sink = new TestDiagnosticSink(); m_diagnostics.RegisterSink(sink); try @@ -2054,9 +2062,9 @@ public void FailedReimport_PublishesCurrentDiagnosticUntilSuccessfulRetry() [Fact] public void UnchangedFailedSourceIsNotRetriedUntilItsInputChanges() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Data/retry.mutableasset", "!invalid!"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); AssetPath path = AssetPath.Project("Data/retry.mutableasset"); Assert.False(loader.Import(path)); int failedAttempts = MutableAssetImporter.attempts; @@ -2075,12 +2083,12 @@ public void UnchangedFailedSourceIsNotRetriedUntilItsInputChanges() [Fact] public void FailedSave_PreservesCommittedSourceMetaArtifactAndVersion() { - using TestWorkspace workspace = new(); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using var workspace = new TestWorkspace(); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); var asset = new MutableAsset { value = "one" }; Assert.True(loader.Save(AssetPath.Project("Data/rollback.mutableasset"), asset)); - byte[] sourceBefore = System.IO.File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset")); - byte[] metaBefore = System.IO.File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset.imeta")); + byte[] sourceBefore = File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset")); + byte[] metaBefore = File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset.imeta")); Assert.True(loader.TryGetArtifact(asset.identity.persistentId, "runtime", out AssetArtifactInfo? artifact)); Assert.NotNull(artifact); byte[] artifactBefore; @@ -2093,8 +2101,8 @@ public void FailedSave_PreservesCommittedSourceMetaArtifactAndVersion() Assert.Throws(() => loader.Save(asset)); - Assert.Equal(sourceBefore, System.IO.File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset"))); - Assert.Equal(metaBefore, System.IO.File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset.imeta"))); + Assert.Equal(sourceBefore, File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset"))); + Assert.Equal(metaBefore, File.ReadAllBytes(workspace.SourcePath("Data/rollback.mutableasset.imeta"))); using (ArtifactLease after = loader.AcquireArtifact(asset.identity.persistentId, "runtime")) { Assert.Equal(artifactBefore, after.ReadAllBytes()); @@ -2105,10 +2113,10 @@ public void FailedSave_PreservesCommittedSourceMetaArtifactAndVersion() [Fact] public void RuntimeDependencyRetention_KeepsDependencyAliveWhileRootIsReferenced() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/dependency.txt", "dependency"); workspace.WriteText("Graphs/root.depgraph", "Text/dependency.txt"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); DependencyAsset root = Assert.IsType( loader.Load(AssetPath.Project("Graphs/root.depgraph"), typeof(DependencyAsset)) ); @@ -2121,10 +2129,10 @@ public void RuntimeDependencyRetention_KeepsDependencyAliveWhileRootIsReferenced [Fact] public void UnusedRuntimeDependencyCycle_IsCollectedAsAUnit() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Graphs/a.depgraph", "Graphs/b.depgraph"); workspace.WriteText("Graphs/b.depgraph", "Graphs/a.depgraph"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); (WeakReference first, WeakReference second) = LoadCycleWithoutEscaping(loader); int released = loader.UnloadUnusedAssets(); @@ -2138,10 +2146,10 @@ public void UnusedRuntimeDependencyCycle_IsCollectedAsAUnit() [Fact] public void ReferenceDiagnostics_DoNotKeepAssetsAlive() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/dependency.txt", "dependency"); workspace.WriteText("Graphs/root.depgraph", "Text/dependency.txt"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); WeakReference weak = LoadAndInspectWithoutEscaping(loader); Assert.Equal(2, loader.UnloadUnusedAssets()); @@ -2151,9 +2159,9 @@ public void ReferenceDiagnostics_DoNotKeepAssetsAlive() [Fact] public void Dispose_ReleasesRuntimeResourcesExactlyOnce() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Hooks/value.hookasset", "value"); - var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); HookAsset asset = Assert.IsType(loader.Load(AssetPath.Project("Hooks/value.hookasset"), typeof(HookAsset))); loader.Dispose(); @@ -2167,29 +2175,29 @@ public void Dispose_ReleasesRuntimeResourcesExactlyOnce() [Fact] public void Rescan_TracksUnsupportedSourcesAndFolderIdentityWithoutFakeArtifacts() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); Directory.CreateDirectory(workspace.SourcePath("EmptyFolder")); workspace.WriteText("Unknown/value.unknown", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); Assert.True(loader.TryGetInfo(AssetPath.Project("EmptyFolder"), out AssetInfo? folder)); Assert.Equal(AssetSourceKind.Directory, folder!.sourceKind); Assert.Equal(AssetImportStatus.Imported, folder.status); - Assert.True(System.IO.File.Exists(workspace.SourcePath("EmptyFolder.imeta"))); + Assert.True(File.Exists(workspace.SourcePath("EmptyFolder.imeta"))); Assert.True(folder.artifactKey.isEmpty); Assert.True(loader.TryGetInfo(AssetPath.Project("Unknown/value.unknown"), out AssetInfo? unsupported)); Assert.Equal(AssetImportStatus.Unsupported, unsupported!.status); Assert.Equal(Guid.Empty, unsupported.persistentId); - Assert.False(System.IO.File.Exists(workspace.SourcePath("Unknown/value.unknown.imeta"))); + Assert.False(File.Exists(workspace.SourcePath("Unknown/value.unknown.imeta"))); Assert.True(unsupported.artifactKey.isEmpty); } [Fact] public void Rescan_RecoversAnonymousCatalogEntryFromSourceIdentityWithoutFalseMissingWarning() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); const string path = "Deferred/value.unavailable"; workspace.WriteText(path, "source awaiting its module generation"); using (AssetLoader first = workspace.CreateLoader( @@ -2206,7 +2214,7 @@ public void Rescan_RecoversAnonymousCatalogEntryFromSourceIdentityWithoutFalseMi Guid persistentId = Guid.NewGuid(); Guid expectedStableTypeId = Guid.NewGuid(); - System.IO.File.WriteAllBytes( + File.WriteAllBytes( workspace.SourcePath(path + ".imeta"), m_serialization.Serialize(new MountedSourceMetadata { @@ -2265,7 +2273,7 @@ public void Rescan_RecoversAnonymousCatalogEntryFromSourceIdentityWithoutFalseMi [Fact] public void Rescan_PreservesLastGoodCatalogWhileItsPathImporterIsUnavailable() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); const string path = "Deferred/value.deferredasset"; workspace.WriteText(path, "last-good source"); Guid persistentId; @@ -2292,32 +2300,26 @@ public void Rescan_PreservesLastGoodCatalogWhileItsPathImporterIsUnavailable() m_modules.Rebuild(); try { - using (AssetLoader restarted = workspace.CreateLoader( + using AssetLoader restarted = workspace.CreateLoader( m_types, m_serialization, m_identities, m_diagnostics, m_logs - )) { - restarted.Rescan(); - - Assert.True(restarted.TryGetInfo(AssetPath.Project(path), out AssetInfo? preserved)); - Assert.Equal(persistentId, preserved!.persistentId); - Assert.Equal(stableTypeId, preserved.stableAssetTypeId); - Assert.Equal(AssetImportStatus.Imported, preserved.status); - Assert.Equal(artifactKey, preserved.artifactKey); - AssetObject resolved = restarted.ResolveReference( - persistentId, - stableTypeId, - path, - typeof(AssetObject) - ); - Assert.False(resolved.isMissing); - Assert.DoesNotContain( - sink.reports.Values.SelectMany(static report => report.diagnostics), - static diagnostic => diagnostic.code == "ASSET-REFERENCE" - ); - } + ); + restarted.Rescan(); + + Assert.True(restarted.TryGetInfo(AssetPath.Project(path), out AssetInfo? preserved)); + Assert.Equal(persistentId, preserved!.persistentId); + Assert.Equal(stableTypeId, preserved.stableAssetTypeId); + Assert.Equal(AssetImportStatus.Imported, preserved.status); + Assert.Equal(artifactKey, preserved.artifactKey); + AssetObject resolved = restarted.ResolveReference(persistentId, stableTypeId, path, typeof(AssetObject)); + Assert.False(resolved.isMissing); + Assert.DoesNotContain( + sink.reports.Values.SelectMany(static report => report.diagnostics), + static diagnostic => diagnostic.code == "ASSET-REFERENCE" + ); } finally { @@ -2330,7 +2332,7 @@ public void Rescan_PreservesLastGoodCatalogWhileItsPathImporterIsUnavailable() [Fact] public void SourceMetadata_RestoresPersistentIdentityWhenLibraryIsRebuilt() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/value.txt", "value"); Guid id; using (AssetLoader first = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs)) @@ -2351,10 +2353,10 @@ public void SourceMetadata_RestoresPersistentIdentityWhenLibraryIsRebuilt() [Fact] public void ContentAddressedStore_DeduplicatesEqualImportsAndCollectsUnreachableBundles() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/first.txt", "same"); workspace.WriteText("Text/second.txt", "same"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/first.txt"), out AssetInfo? first)); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/second.txt"), out AssetInfo? second)); @@ -2368,38 +2370,38 @@ public void ContentAddressedStore_DeduplicatesEqualImportsAndCollectsUnreachable Assert.NotNull(currentArtifact); Assert.NotEqual(oldArtifact.key, currentArtifact.key); string oldPath = workspace.FindArtifactFile(oldArtifact); - Assert.True(System.IO.File.Exists(oldPath)); + Assert.True(File.Exists(oldPath)); Assert.Equal(0, loader.CollectArtifacts(TimeSpan.Zero, maximumSizeBytes: 0)); - Assert.True(System.IO.File.Exists(oldPath)); + Assert.True(File.Exists(oldPath)); workspace.DeleteSource("Text/second.txt"); - System.IO.File.Delete(workspace.SourcePath("Text/second.txt.imeta")); + File.Delete(workspace.SourcePath("Text/second.txt.imeta")); loader.Rescan(); Assert.True(loader.CollectArtifacts(TimeSpan.Zero, maximumSizeBytes: 0) >= 1); - Assert.False(System.IO.File.Exists(oldPath)); - Assert.True(System.IO.File.Exists(workspace.FindArtifactFile(currentArtifact))); + Assert.False(File.Exists(oldPath)); + Assert.True(File.Exists(workspace.FindArtifactFile(currentArtifact))); } [Fact] public void ArtifactLookupRejectsWrongLengthAndExportRejectsSameLengthCorruption() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/value.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/value.txt"), out AssetInfo? info)); Assert.True(loader.TryGetArtifact(info!.persistentId, "runtime", out AssetArtifactInfo? artifact)); string path = workspace.FindArtifactFile(artifact!); - byte[] original = System.IO.File.ReadAllBytes(path); + byte[] original = File.ReadAllBytes(path); - System.IO.File.WriteAllBytes(path, [1]); + File.WriteAllBytes(path, [1]); Assert.Throws(() => loader.TryGetArtifact(info.persistentId, "runtime", out _)); byte[] changed = (byte[])original.Clone(); changed[0] ^= 0x01; - System.IO.File.WriteAllBytes(path, changed); + File.WriteAllBytes(path, changed); Assert.True(loader.TryGetArtifact(info.persistentId, "runtime", out _)); Assert.Throws(() => loader.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "CorruptedRuntime"))); - System.IO.File.WriteAllBytes(path, original); + File.WriteAllBytes(path, original); Assert.True(loader.TryGetArtifact(info.persistentId, "runtime", out _)); loader.ExportRuntimeArtifacts(Path.Combine(workspace.libraryRoot, "ValidRuntime")); } @@ -2407,9 +2409,9 @@ public void ArtifactLookupRejectsWrongLengthAndExportRejectsSameLengthCorruption [Fact] public async Task AggregateBuildProcessor_ProducesStableContentAddressedOutput() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.WriteText("Text/input.txt", "value"); - using var loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); + using AssetLoader loader = workspace.CreateLoader(m_types, m_serialization, m_identities, m_diagnostics, m_logs); loader.Rescan(); Assert.True(loader.TryGetInfo(AssetPath.Project("Text/input.txt"), out AssetInfo? input)); Assert.NotNull(input); @@ -2483,9 +2485,7 @@ internal string FindArtifactFile(AssetArtifactInfo artifact) ); return Directory.EnumerateFiles(directory).Single(path => ( new FileInfo(path).Length == artifact.length - && Convert.ToHexString( - System.Security.Cryptography.SHA256.HashData(System.IO.File.ReadAllBytes(path)) - ) == artifact.contentHash + && Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))) == artifact.contentHash )); } @@ -2495,10 +2495,10 @@ string content ) { string path = SourcePath(relativePath); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - System.IO.File.WriteAllText(path, content, new UTF8Encoding(false)); + File.WriteAllText(path, content, new UTF8Encoding(false)); } - internal string ReadText(string relativePath) => System.IO.File.ReadAllText(SourcePath(relativePath)); + internal string ReadText(string relativePath) => File.ReadAllText(SourcePath(relativePath)); internal void Move( string oldRelativePath, @@ -2506,15 +2506,15 @@ string newRelativePath ) { string target = SourcePath(newRelativePath); Directory.CreateDirectory(Path.GetDirectoryName(target)!); - System.IO.File.Move(SourcePath(oldRelativePath), target); + File.Move(SourcePath(oldRelativePath), target); } internal void DeleteSource(string relativePath) { string path = SourcePath(relativePath); - if (System.IO.File.Exists(path)) + if (File.Exists(path)) { - System.IO.File.Delete(path); + File.Delete(path); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs index ad123c194..453e5f831 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs @@ -24,10 +24,10 @@ public void SettingsRoundTripReimportAndResetWithoutChangingSourceOrIdentity() { using var fixture = new Fixture(); using AssetLoader loader = fixture.CreateLoader(); - var asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); + ConfiguredAsset asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); Guid identity = asset.identity.persistentId; AssetImportSettingsSnapshot snapshot = loader.GetImportSettings(Fixture.path); - var settings = Assert.IsType(snapshot.value); + ConfiguredSettings settings = Assert.IsType(snapshot.value); Assert.Equal(1, settings.multiplier); settings.multiplier = 7; Assert.Equal(1, Assert.IsType(loader.GetImportSettings(Fixture.path).value).multiplier); @@ -54,7 +54,7 @@ public void SettingsSurviveColdLoaderAndLibraryRecreation() identity = loader.Load(Fixture.path, typeof(ConfiguredAsset))!.identity.persistentId; } using AssetLoader cold = fixture.CreateLoader("OtherLibrary"); - var asset = Assert.IsType(cold.Load(Fixture.path, typeof(ConfiguredAsset))); + ConfiguredAsset asset = Assert.IsType(cold.Load(Fixture.path, typeof(ConfiguredAsset))); Assert.Equal("12:source", asset.value); Assert.Equal(identity, asset.identity.persistentId); } @@ -81,7 +81,7 @@ public void InvalidSettingsPersistWhilePreviousArtifactRemainsLastGood() { using var fixture = new Fixture(); using AssetLoader loader = fixture.CreateLoader(); - var asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); + ConfiguredAsset asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); Assert.True(loader.TryGetInfo(Fixture.path, out AssetInfo? original)); AssetImportSettingsSnapshot snapshot = loader.GetImportSettings(Fixture.path); Assert.False(loader.SaveImportSettings(Fixture.path, new ConfiguredSettings { multiplier = -1 }, snapshot.fingerprint)); @@ -98,7 +98,7 @@ public void SidecarChangeInvalidatesArtifactWithoutSourceChangeAndSelfNotificati { using var fixture = new Fixture(); using AssetLoader loader = fixture.CreateLoader(); - var asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); + ConfiguredAsset asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); byte[] first = File.ReadAllBytes(fixture.sourcePath + ".imeta"); AssetImportSettingsSnapshot snapshot = loader.GetImportSettings(Fixture.path); Assert.True(loader.SaveImportSettings(Fixture.path, new ConfiguredSettings { multiplier = 2 }, snapshot.fingerprint)); @@ -117,8 +117,8 @@ public void SettingsReferencesAreImportDependenciesNotRuntimeDependencies() using var fixture = new Fixture(); File.WriteAllText(Path.Combine(fixture.assetRoot, "lookup.txt"), "first"); using AssetLoader loader = fixture.CreateLoader(); - var dependency = Assert.IsType(loader.Load(AssetPath.Project("lookup.txt"), typeof(TextAsset))); - var asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); + TextAsset dependency = Assert.IsType(loader.Load(AssetPath.Project("lookup.txt"), typeof(TextAsset))); + ConfiguredAsset asset = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); AssetImportSettingsSnapshot snapshot = loader.GetImportSettings(Fixture.path); Assert.True(loader.SaveImportSettings(Fixture.path, new ConfiguredSettings { lookup = dependency }, snapshot.fingerprint)); Assert.Contains(AssetPath.Project("lookup.txt"), loader.GetImportDependencies(asset)); @@ -126,7 +126,7 @@ public void SettingsReferencesAreImportDependenciesNotRuntimeDependencies() Assert.Equal("1:source:first", asset.value); File.WriteAllText(Path.Combine(fixture.assetRoot, "lookup.txt"), "second"); Assert.True(loader.Import(AssetPath.Project("lookup.txt"))); - var reloaded = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); + ConfiguredAsset reloaded = Assert.IsType(loader.Load(Fixture.path, typeof(ConfiguredAsset))); Assert.Equal("1:source:second", reloaded.value); } @@ -154,7 +154,7 @@ public void CorruptSidecarIsNotErasedByFailedImport() using var fixture = new Fixture(); using AssetLoader loader = fixture.CreateLoader(); Assert.True(loader.Import(Fixture.path)); - byte[] corrupt = [0xff, 0xee, 0xdd]; + byte[] corrupt = [0xFF, 0xEE, 0xDD]; File.WriteAllBytes(fixture.sourcePath + ".imeta", corrupt); Assert.False(loader.Import(Fixture.path)); Assert.Equal(corrupt, File.ReadAllBytes(fixture.sourcePath + ".imeta")); @@ -220,14 +220,18 @@ public void Dispose() [StableTypeId("f58eaeea-4bd5-4f3a-a7c0-c5a5414a6bb4")] internal sealed class ConfiguredSettings : ISerializable { - [SerializableProperty] internal int multiplier { get; set; } = 1; - [SerializableProperty] internal TextAsset? lookup { get; set; } + [SerializableProperty] + internal int multiplier { get; set; } = 1; + + [SerializableProperty] + internal TextAsset? lookup { get; set; } } [StableTypeId("bdb3db71-e9cb-4d46-839b-3cbe302c5555")] internal sealed class ConfiguredAsset : AssetObject { - [SerializableProperty] internal string value { get; set; } = string.Empty; + [SerializableProperty] + internal string value { get; set; } = string.Empty; } [AssetImporter("tests.configured")] @@ -242,7 +246,7 @@ protected override ValueTask ImportAsync( AssetImportWriter output, CancellationToken cancellationToken ) { - var settings = (ConfiguredSettings)context.importSettings!; + ConfiguredSettings settings = (ConfiguredSettings)context.importSettings!; if (settings.multiplier < 0) throw new InvalidOperationException("A negative multiplier is invalid."); string value = $"{settings.multiplier}:{context.ReadUtf8Text()}"; if (settings.lookup is not null) value += ":" + settings.lookup.content; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs index 5bb7c7c3d..aee623f25 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterIntegrationTests.cs @@ -56,7 +56,7 @@ public void TextExtensions_AreAutomaticallyDiscovered( string relativePath, string languageHint ) { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.Write(relativePath, Encoding.UTF8.GetBytes("content")); using var loader = new AssetLoader( m_types, @@ -78,7 +78,7 @@ string languageHint [Fact] public void BinaryImporter_CreatesRuntimeDescriptor() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); workspace.Write("Data/blob.bytes", [1, 2, 3, 4]); using var loader = new AssetLoader( m_types, @@ -98,7 +98,7 @@ public void BinaryImporter_CreatesRuntimeDescriptor() [Fact] public void ExportableBuiltInAsset_RoundTripsThroughPublicLoaderContract() { - using TestWorkspace workspace = new(); + using var workspace = new TestWorkspace(); using var loader = new AssetLoader( m_types, m_serialization, @@ -114,7 +114,7 @@ public void ExportableBuiltInAsset_RoundTripsThroughPublicLoaderContract() TextAsset loaded = Assert.IsType(loader.Load(AssetPath.Project("Text/saved.txt"), typeof(TextAsset))); Assert.Same(source, loaded); - Assert.Equal("saved", System.IO.File.ReadAllText(Path.Combine(workspace.assetRoot, "Text/saved.txt"))); + Assert.Equal("saved", File.ReadAllText(Path.Combine(workspace.assetRoot, "Text/saved.txt"))); } private sealed class TestWorkspace : IDisposable @@ -140,7 +140,7 @@ byte[] bytes ) { string path = Path.Combine(assetRoot, relativePath); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - System.IO.File.WriteAllBytes(path, bytes); + File.WriteAllBytes(path, bytes); } public void Dispose() diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs index c646cad08..bc2f5aaa1 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs @@ -82,9 +82,9 @@ public void RuntimeSettingsLoadTheirColdReferencesThroughTheSessionAssetOwner(bo using var database = new AssetDatabase(contentStore, serialization, fixture.types.current, identities); Assert.Null(identities.Get(clip.identity.persistentId)); - using ContentReadLease settingsLease = contentStore.Acquire(new Inno.Content.ContentKey("Settings.Project.inno")); + using ContentReadLease settingsLease = contentStore.Acquire(new ContentKey("Settings.Project.inno")); using Stream settingsInput = settingsLease.OpenRead(); - byte[] settingsBytes = new byte[checked((int)settingsLease.entry.length)]; + var settingsBytes = new byte[checked((int)settingsLease.entry.length)]; settingsInput.ReadExactly(settingsBytes); using var settings = new ProjectSettingsStore( new ReadOnlyByteDocumentStore("Settings.Project.inno", settingsBytes), @@ -198,16 +198,16 @@ private sealed class Fixture : IDisposable internal Fixture() { - root = Path.Combine(Path.GetTempPath(), "InnoSettingsReferences", Guid.NewGuid().ToString("N")); - assetRoot = Path.Combine(root, "Assets"); + this.root = Path.Combine(Path.GetTempPath(), "InnoSettingsReferences", Guid.NewGuid().ToString("N")); + this.assetRoot = Path.Combine(root, "Assets"); Directory.CreateDirectory(assetRoot); m_identityScope = m_identities.EnterScope(); m_modules = new ModuleHost( new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(SettingsReferenceTests).Assembly)} ); - types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - assets = new AssetPipeline( + this.types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); + this.serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); + this.assets = new AssetPipeline( m_modules, types, serialization, @@ -216,8 +216,8 @@ internal Fixture() m_logs, AssetPipelineOptions.Create(assetRoot, Path.Combine(root, "Library")) with { enableFileSystemWatcher = false } ); - context = AssetSerializationContext.Create(assets); - settings = new ProjectSettingsStore( + this.context = AssetSerializationContext.Create(assets); + this.settings = new ProjectSettingsStore( new FileByteDocumentStore(Path.GetFullPath(Path.Combine(root, "Settings.Project.inno"))), types, serialization, @@ -250,8 +250,11 @@ public void Dispose() internal abstract class ClipSettingsBase : ISerializable { - [SerializableProperty] public TextAsset? clip { get; set; } - [SerializableProperty] public string[] labels { get; set; } = []; + [SerializableProperty] + public TextAsset? clip { get; set; } + + [SerializableProperty] + public string[] labels { get; set; } = []; } [StableTypeId("2c7288db-eb9e-43a5-9894-bf9d10b22a2d")] @@ -271,7 +274,8 @@ internal sealed class ComposedClipSettings : ClipSettingsBase internal sealed class ClipContribution : ISerializable { - [SerializableProperty] public TextAsset? clip { get; set; } + [SerializableProperty] + public TextAsset? clip { get; set; } } [ProjectSettingComposer("tests.settings.composed-clip")] diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs index 06a112380..81113f431 100644 --- a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs +++ b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs @@ -27,10 +27,18 @@ public sealed class DuplicateImporterA : AssetImporter /// /// Supplies a fixture asset and writes the source bytes as its runtime artifact through the borrowed writer. /// - /// The current source snapshot owned by the import operation. - /// The borrowed writer receiving the candidate asset and artifact. - /// Cancels the artifact write without publishing a complete candidate. - /// The artifact write operation, preserving its failure or cancellation. + /// + /// The current source snapshot owned by the import operation. + /// + /// + /// The borrowed writer receiving the candidate asset and artifact. + /// + /// + /// Cancels the artifact write without publishing a complete candidate. + /// + /// + /// The artifact write operation, preserving its failure or cancellation. + /// protected override ValueTask ImportAsync( AssetImportContext context, AssetImportWriter output, @@ -55,10 +63,18 @@ public sealed class DuplicateImporterB : AssetImporter /// /// Supplies a fixture asset and writes the source bytes as its runtime artifact through the borrowed writer. /// - /// The current source snapshot owned by the import operation. - /// The borrowed writer receiving the candidate asset and artifact. - /// Cancels the artifact write without publishing a complete candidate. - /// The artifact write operation, preserving its failure or cancellation. + /// + /// The current source snapshot owned by the import operation. + /// + /// + /// The borrowed writer receiving the candidate asset and artifact. + /// + /// + /// Cancels the artifact write without publishing a complete candidate. + /// + /// + /// The artifact write operation, preserving its failure or cancellation. + /// protected override ValueTask ImportAsync( AssetImportContext context, AssetImportWriter output, diff --git a/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs b/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs index c35a6d8d8..8889e0073 100644 --- a/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs +++ b/tests/audio/Inno.Audio.Assets.Tests/AudioClipImporterTests.cs @@ -74,7 +74,7 @@ public void ImportsWavFlacAndMp3IntoMetadataAndSeparateEncodedArtifacts() Assert.Equal(AudioCodecId.wav, wav.metadata!.Value.codec); Assert.Equal(4, wav.metadata.Value.frameCount); Assert.Equal(AudioCodecId.flac, flac.metadata!.Value.codec); - Assert.Equal(48000, flac.metadata.Value.frameCount); + Assert.Equal(48_000, flac.metadata.Value.frameCount); Assert.Equal(AudioCodecId.mp3, mp3.metadata!.Value.codec); Assert.Equal(1152, mp3.metadata.Value.frameCount); AssertSeparateArtifact(loader, wav, CreateWav()); @@ -123,15 +123,15 @@ byte[] bytes private static byte[] CreateWav() { - byte[] bytes = new byte[60]; + var bytes = new byte[60]; "RIFF"u8.CopyTo(bytes); BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(4, 4), 52); "WAVEfmt "u8.CopyTo(bytes.AsSpan(8)); BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(16, 4), 16); BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(20, 2), 1); BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(22, 2), 2); - BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(24, 4), 48000); - BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(28, 4), 192000); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(24, 4), 48_000); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(28, 4), 192_000); BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(32, 2), 4); BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(34, 2), 16); "data"u8.CopyTo(bytes.AsSpan(36)); @@ -141,19 +141,19 @@ private static byte[] CreateWav() private static byte[] CreateFlac() { - byte[] bytes = new byte[42]; + var bytes = new byte[42]; "fLaC"u8.CopyTo(bytes); bytes[4] = 0x80; bytes[7] = 34; - ulong packed = ((ulong)48000 << 44) | (1UL << 41) | (15UL << 36) | 48000UL; + ulong packed = ((ulong)48_000 << 44) | (1UL << 41) | (15UL << 36) | 48_000UL; BinaryPrimitives.WriteUInt64BigEndian(bytes.AsSpan(18, 8), packed); return bytes; } private static byte[] CreateMp3() { - byte[] bytes = new byte[417]; - BinaryPrimitives.WriteUInt32BigEndian(bytes, 0xfffb9000); + var bytes = new byte[417]; + BinaryPrimitives.WriteUInt32BigEndian(bytes, 0xFFFB_9000); return bytes; } } diff --git a/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs b/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs index 96e3da04a..42f6495cc 100644 --- a/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs +++ b/tests/audio/Inno.Audio.Runtime.Tests/AudioRuntimeTests.cs @@ -25,8 +25,10 @@ public sealed class AudioRuntimeTests : IDisposable public void ConsumedApplicationLifecycleStillSuspendsAudioAndUnsubscribesOnStop() { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.suspension.consumed", "Suspension")); - using var consumer = m_events.CreateHub(int.MaxValue); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter( + new DiagnosticSource("test.suspension.consumed", "Suspension") + ); + using EventHub consumer = m_events.CreateHub(int.MaxValue); consumer.Listen(e => e.HandleInGlobal()); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); runtime.Attach(); @@ -46,10 +48,12 @@ public void ConsumedApplicationLifecycleStillSuspendsAudioAndUnsubscribesOnStop( public void FailedSuspensionRollsBackRetainedMixerRootsAndRemainsRetryable() { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.suspension.rollback", "Suspension")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter( + new DiagnosticSource("test.suspension.rollback", "Suspension") + ); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); runtime.Attach(); - runtime.Play(CreateClip(480000), new AudioPlayOptions(loop: true)); + runtime.Play(CreateClip(480_000), new AudioPlayOptions(loop: true)); runtime.Update(0); Assert.True(runtime.ApplyMixer(new AudioMixerAsset { mixerTypeId = "tests.audio.mixer" })); device.failBusPauseAt = device.busPauseCalls + 2; @@ -67,7 +71,7 @@ public void FailedSuspensionRollsBackRetainedMixerRootsAndRemainsRetryable() public void ApplicationSuspensionPreservesUserPauseAndReplacementMixerState() { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.suspension", "Suspension")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.suspension", "Suspension")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); runtime.Attach(); Assert.True(runtime.SetBusPaused(AudioBusId.master, true)); @@ -95,10 +99,10 @@ public void ApplicationSuspensionPreservesUserPauseAndReplacementMixerState() [Fact] public void InvalidPlaybackOptionsDoNotStealOrAcquireAnArtifact() { - using var runtime = CreateRuntime(maxVoices: 1); - AudioVoiceHandle previous = runtime.Play(CreateClip(48000), new AudioPlayOptions(loop: true)); + using AudioRuntime runtime = CreateRuntime(maxVoices: 1); + AudioVoiceHandle previous = runtime.Play(CreateClip(48_000), new AudioPlayOptions(loop: true)); runtime.Update(0); - AudioClipAsset next = CreateClip(48000); + AudioClipAsset next = CreateClip(48_000); int acquisitions = m_artifacts.acquisitions; Assert.Throws(() => runtime.Play(next, default)); Assert.Equal(acquisitions, m_artifacts.acquisitions); @@ -112,10 +116,10 @@ public void InvalidPlaybackOptionsDoNotStealOrAcquireAnArtifact() [Fact] public void ArtifactAcquisitionRetirementBarrierDoesNotStealOrBecomeDecodeFailure() { - using var runtime = CreateRuntime(maxVoices: 1); - AudioVoiceHandle previous = runtime.Play(CreateClip(48000), new AudioPlayOptions(loop: true)); + using AudioRuntime runtime = CreateRuntime(maxVoices: 1); + AudioVoiceHandle previous = runtime.Play(CreateClip(48_000), new AudioPlayOptions(loop: true)); runtime.Update(0); - AudioClipAsset next = CreateClip(48000); + AudioClipAsset next = CreateClip(48_000); m_artifacts.acquisitionFailure = new RetirementPendingException("Expected artifact retirement barrier."); Assert.Throws(() => runtime.Play(next)); Assert.Equal(0, runtime.statistics.stolenVoiceCount); @@ -130,7 +134,7 @@ public void AdmissionRetryAfterCompletionBackpressureReleasesCandidateLeaseAndSt { var events = new EventDispatcher(queueCapacity: 1); var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.admission", "Admission")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.admission", "Admission")); using var runtime = new AudioRuntime( m_types, device, @@ -142,9 +146,9 @@ public void AdmissionRetryAfterCompletionBackpressureReleasesCandidateLeaseAndSt using EventHub hub = events.CreateHub(); var completions = new List(); hub.Listen(completions.Add); - AudioVoiceHandle previous = runtime.Play(CreateClip(48000), new AudioPlayOptions(loop: true)); + AudioVoiceHandle previous = runtime.Play(CreateClip(48_000), new AudioPlayOptions(loop: true)); runtime.Update(0); - AudioClipAsset next = CreateClip(48000); + AudioClipAsset next = CreateClip(48_000); events.Enqueue(new AudioVoiceCompletedEvent(new AudioVoiceAllocator().Allocate(), AudioCompletionReason.Stopped)); m_artifacts.pendingReleaseId = next.identity.persistentId; m_artifacts.pendingReleases = 1; @@ -171,7 +175,7 @@ public void AdmissionRetryAfterCompletionBackpressureReleasesCandidateLeaseAndSt [Fact] public void OrdinaryMissingMetadataStillCompletesThroughTheAsynchronousVoiceProtocol() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); using EventHub hub = m_events.CreateHub(); var completed = new List(); hub.Listen(completed.Add); @@ -187,8 +191,8 @@ public void OrdinaryMissingMetadataStillCompletesThroughTheAsynchronousVoiceProt [Fact] public void UndefinedPreloadModeIsRejectedBeforeArtifactAcquisition() { - using var runtime = CreateRuntime(); - AudioClipAsset clip = CreateClip(48000); + using AudioRuntime runtime = CreateRuntime(); + AudioClipAsset clip = CreateClip(48_000); Assert.Throws(() => runtime.PreloadAsync(clip, (AudioClipLoadMode)999)); Assert.Equal(0, m_artifacts.acquisitions); Assert.Equal(0, runtime.statistics.loadedClips); @@ -199,11 +203,11 @@ public void MutedBackendRejectsInvalidValuesWithTheSameAdmissionPolicy() { using var device = new MutedAudioDevice(); IAudioDevice backend = device; - AudioClipAsset asset = CreateClip(48000); + AudioClipAsset asset = CreateClip(48_000); using ArtifactLease artifact = m_artifacts.AcquireArtifact(asset.identity.persistentId, "audio-data"); AudioBusHandle master = backend.CreateBus(AudioBusId.master); AudioClipHandle clip = backend.CreateClip( - new AudioClipDescriptor( AudioCodecId.wav, AudioClipLoadMode.Decode, 2, 48000, 48000, artifact.info.length), + new AudioClipDescriptor( AudioCodecId.wav, AudioClipLoadMode.Decode, 2, 48_000, 48_000, artifact.info.length), new LeaseAudioTestSource(artifact) ); Assert.False(backend.Play(clip, master, default).isValid); @@ -230,7 +234,7 @@ public void ProviderFailureDiscardsItsEntireContributionAndReleasesItsIdentities var content = new TestAudioContent(); var identities = new IdentityAllocator(); identities.Register(content); - AudioClipAsset clip = CreateClip(48000); + AudioClipAsset clip = CreateClip(48_000); var emitter = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); var listener = new AudioListenerSnapshot(Guid.NewGuid(), 0, default, true); content.first = context => @@ -247,7 +251,7 @@ public void ProviderFailureDiscardsItsEntireContributionAndReleasesItsIdentities var diagnostics = new DiagnosticHub(); var sink = new RecordingSink(); diagnostics.RegisterSink(sink); - using var reporter = diagnostics.CreateReporter(new DiagnosticSource("test.content", "Content")); + using DiagnosticReporter reporter = diagnostics.CreateReporter(new DiagnosticSource("test.content", "Content")); var device = new ReadyAudioDevice(); using var runtime = new AudioRuntime( m_types, @@ -275,7 +279,7 @@ public void CrossProviderDuplicateRejectsTheWholeBatchWithoutClaimingOtherIdenti var content = new TestAudioContent(); var identities = new IdentityAllocator(); identities.Register(content); - AudioClipAsset clip = CreateClip(48000); + AudioClipAsset clip = CreateClip(48_000); var first = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); var second = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); content.first = context => context.Submit(first); @@ -285,7 +289,7 @@ public void CrossProviderDuplicateRejectsTheWholeBatchWithoutClaimingOtherIdenti context.Submit(first); }; content.third = context => context.Submit(second); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.duplicate", "Duplicate")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.duplicate", "Duplicate")); using var runtime = new AudioRuntime( m_types, new ReadyAudioDevice(), @@ -306,7 +310,7 @@ public void RepeatedOverflowIsBoundedAndCannotBeHiddenByAProviderCatch() var content = new TestAudioContent(); var identities = new IdentityAllocator(); identities.Register(content); - AudioClipAsset clip = CreateClip(48000); + AudioClipAsset clip = CreateClip(48_000); var first = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); var overflow = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); var last = new AudioEmitterSnapshot(Guid.NewGuid(), clip, new AudioPlayOptions(loop: true), true); @@ -321,7 +325,7 @@ public void RepeatedOverflowIsBoundedAndCannotBeHiddenByAProviderCatch() catch (InvalidOperationException) { } }; content.third = context => context.Submit(last); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.capacity", "Capacity")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.capacity", "Capacity")); var options = new AudioRuntimeOptions { maxContentSnapshots = 2 }; using var runtime = new AudioRuntime( m_types, @@ -360,7 +364,7 @@ public void ProviderContextAndContentLookupAreRevokedAfterTheUpdate() captured = context; capturedScope = context.content; }; - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.scope", "Scope")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.scope", "Scope")); using var runtime = new AudioRuntime( m_types, new ReadyAudioDevice(), @@ -390,7 +394,7 @@ public void ProviderRetirementPendingIsNotConvertedToARejectedContribution() throw new RetirementPendingException("Expected provider work drain."); }; content.second = _ => nextInvoked = true; - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.pending-content", "Pending")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.pending-content", "Pending")); using var runtime = new AudioRuntime( m_types, new ReadyAudioDevice(), @@ -411,7 +415,7 @@ public void ProviderRetirementPendingIsNotConvertedToARejectedContribution() [InlineData(float.PositiveInfinity)] public void InvalidUpdateTimeIsRejectedBeforeProviderExecution(float deltaTime) { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); Assert.Throws(() => runtime.Update(deltaTime)); } @@ -464,9 +468,9 @@ public override void Submit(AudioContentProviderContext context) public async Task PendingClipRetirementPreservesDeviceAndRetriesExactlyOnce(bool playing) { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.pending", "Pending")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.pending", "Pending")); var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); - AudioClipAsset clip = CreateClip(48000); + AudioClipAsset clip = CreateClip(48_000); if (playing) { runtime.Play(clip); @@ -495,7 +499,7 @@ public async Task PendingClipRetirementPreservesDeviceAndRetriesExactlyOnce(bool public void PendingBusRetirementDoesNotDestroyTheDeviceBeforeRetry() { var device = new ReadyAudioDevice { pendingBusRetirements = 1 }; - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.bus", "Bus")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.bus", "Bus")); var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); Assert.Throws(runtime.Dispose); Assert.Equal(0, device.disposals); @@ -509,9 +513,9 @@ public void PendingReplacementRetirementDrainsBeforePublishingTheNewDevice() { var previous = new ReadyAudioDevice { pendingBusRetirements = 1 }; var replacement = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.replacement", "Replacement")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.replacement", "Replacement")); using var runtime = new AudioRuntime(m_types, previous, m_artifacts, m_events, reporter); - AudioVoiceHandle oldVoice = runtime.Play(CreateClip(48000)); + AudioVoiceHandle oldVoice = runtime.Play(CreateClip(48_000)); runtime.ReplaceDevice(replacement); Assert.Equal(2, previous.busRetirements); Assert.Equal(1, previous.disposals); @@ -525,7 +529,7 @@ public void PendingReplacementRetirementDrainsBeforePublishingTheNewDevice() [Fact] public void PendingProviderIsRetriedBeforeItsGenerationIsReleased() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); runtime.Update(0); RetirementProviderFirst.disposals = 0; RetirementProviderFirst.pendingRetirements = 1; @@ -545,7 +549,7 @@ public void PendingProviderIsRetriedBeforeItsGenerationIsReleased() public void CompletionBackpressureRetainsTheVoiceUntilItsEventIsAccepted() { var events = new EventDispatcher(queueCapacity: 1); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.completion", "Completion")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.completion", "Completion")); using var runtime = new AudioRuntime(m_types, new ReadyAudioDevice(), m_artifacts, events, reporter); using EventHub hub = events.CreateHub(); var completed = new List(); @@ -569,7 +573,7 @@ public void CompletionBackpressureRetainsTheVoiceUntilItsEventIsAccepted() [Fact] public void CandidateCleanupFailureFaultsInsteadOfReportingRecoverableMixerFailure() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); runtime.Update(0); RetirementProviderFirst.fail = true; RetirementProviderSecond.failConstruction = true; @@ -590,7 +594,7 @@ public void CandidateCleanupFailureFaultsInsteadOfReportingRecoverableMixerFailu public async Task CacheRetirementAttemptsEveryClipBeforeDeviceDisposal() { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.retire", "Retire")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.retire", "Retire")); var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); await runtime.PreloadAsync(CreateClip(4800)); await runtime.PreloadAsync(CreateClip(9600)); @@ -606,7 +610,7 @@ public void FailedOldDeviceRetirementConsumesCandidateAndFaultsWithoutFalseRecov { var previous = new ReadyAudioDevice { failDisposal = true }; var candidate = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.replace", "Replace")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.replace", "Replace")); var runtime = new AudioRuntime(m_types, previous, m_artifacts, m_events, reporter); Assert.Throws(() => runtime.ReplaceDevice(candidate)); Assert.Equal(1, previous.disposals); @@ -623,7 +627,7 @@ public void RecoveryClearsMutedAndRecoveryFailureDiagnostics() var diagnostics = new DiagnosticHub(); var sink = new RecordingSink(); diagnostics.RegisterSink(sink); - using var reporter = diagnostics.CreateReporter(new DiagnosticSource("test.device", "Device")); + using DiagnosticReporter reporter = diagnostics.CreateReporter(new DiagnosticSource("test.device", "Device")); using var runtime = new AudioRuntime(m_types, new MutedAudioDevice(), m_artifacts, m_events, reporter); Assert.Contains(sink.issues, issue => issue.code == "AUDIO_NO_DEVICE"); Assert.False(runtime.TryRecoverDevice(static () => throw new InvalidOperationException("Device unavailable."))); @@ -635,7 +639,7 @@ public void RecoveryClearsMutedAndRecoveryFailureDiagnostics() [Fact] public void ProviderRetirementAttemptsEveryInstanceAndFaultsSharedGeneration() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); runtime.Update(0); RetirementProviderFirst.disposals = 0; RetirementProviderSecond.disposals = 0; @@ -701,7 +705,7 @@ public void RecoveredMixerResolvesItsPreviousMissingDiagnostic() var diagnostics = new DiagnosticHub(); var sink = new RecordingSink(); diagnostics.RegisterSink(sink); - using var reporter = diagnostics.CreateReporter(new DiagnosticSource("test.mixer", "Mixer")); + using DiagnosticReporter reporter = diagnostics.CreateReporter(new DiagnosticSource("test.mixer", "Mixer")); using var runtime = new AudioRuntime(m_types, new MutedAudioDevice(), m_artifacts, m_events, reporter); var mixer = new AudioMixerAsset { mixerTypeId = "tests.unavailable" }; Assert.False(runtime.ApplyMixer(mixer)); @@ -753,7 +757,7 @@ public void Dispose() public void PlayTransitionsFromPreparingToNaturalCompletionOnMainThread() { AudioClipAsset clip = CreateClip(frameCount: 4800); - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); using EventHub hub = m_events.CreateHub(); var completions = new List(); hub.Listen(completions.Add); @@ -778,7 +782,7 @@ public void PlayTransitionsFromPreparingToNaturalCompletionOnMainThread() public void ScheduledLoopingVoiceSupportsPauseResumeAndSeek() { AudioClipAsset clip = CreateClip(frameCount: 4800); - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); AudioVoiceHandle voice = runtime.PlayScheduled(clip, 1d, new AudioPlayOptions(loop: true)); runtime.Update(0.1f); @@ -797,8 +801,8 @@ public void ScheduledLoopingVoiceSupportsPauseResumeAndSeek() [Fact] public void VoiceBudgetStealsLowestPriorityThenOldestVoice() { - AudioClipAsset clip = CreateClip(frameCount: 480000); - using var runtime = CreateRuntime(maxVoices: 2); + AudioClipAsset clip = CreateClip(frameCount: 480_000); + using AudioRuntime runtime = CreateRuntime(maxVoices: 2); using EventHub hub = m_events.CreateHub(); var completions = new List(); hub.Listen(completions.Add); @@ -823,7 +827,7 @@ public void VoiceBudgetStealsLowestPriorityThenOldestVoice() public async Task PreloadRetainsDistinctDecodeAndStreamEntriesUntilReleased() { AudioClipAsset clip = CreateClip(frameCount: 4800); - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); await runtime.PreloadAsync(clip, AudioClipLoadMode.Decode); await runtime.PreloadAsync(clip, AudioClipLoadMode.Stream); @@ -838,7 +842,7 @@ public async Task PreloadRetainsDistinctDecodeAndStreamEntriesUntilReleased() public async Task AutomaticPreparationStreamsWhenDecodedFootprintExceedsBudget() { AudioClipAsset clip = CreateClip(frameCount: 4800); - using var runtime = CreateRuntime( + using AudioRuntime runtime = CreateRuntime( decodedCacheBudgetBytes: 1024, automaticStreamingThresholdBytes: long.MaxValue ); @@ -853,7 +857,7 @@ public async Task AutomaticPreparationStreamsWhenDecodedFootprintExceedsBudget() [Fact] public void MixerExtensionBuildsOpenBusGraphAndMissingCandidateKeepsLastGood() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); var mixer = new AudioMixerAsset { mixerTypeId = "tests.audio.mixer" }; Assert.True(runtime.ApplyMixer(mixer)); @@ -867,8 +871,8 @@ public void MixerExtensionBuildsOpenBusGraphAndMissingCandidateKeepsLastGood() [Fact] public void DeviceReplacementCompletesOldHandlesAndUsesANewGeneration() { - AudioClipAsset clip = CreateClip(frameCount: 480000); - using var runtime = CreateRuntime(); + AudioClipAsset clip = CreateClip(frameCount: 480_000); + using AudioRuntime runtime = CreateRuntime(); AudioVoiceHandle oldVoice = runtime.Play(clip); runtime.Update(0f); @@ -884,10 +888,10 @@ public void DeviceReplacementCompletesOldHandlesAndUsesANewGeneration() [Fact] public void RecoveryCandidatePreservesTheLastGoodMixerGraph() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); var mixer = new AudioMixerAsset { mixerTypeId = "tests.audio.mixer" }; Assert.True(runtime.ApplyMixer(mixer)); - AudioBusId music = new("tests.audio.bus.music"); + var music = new AudioBusId("tests.audio.bus.music"); Assert.True(runtime.SetBusVolume(music, 0.25f)); Assert.True(runtime.SetBusPaused(music, true)); var replacement = new ReadyAudioDevice(); @@ -908,7 +912,7 @@ public async Task PreloadCompletesOnlyAfterPreparationAndCancellationReleasesRes device, m_artifacts, m_events, - new Inno.Core.Diagnostics.DiagnosticHub().CreateReporter(new Inno.Core.Diagnostics.DiagnosticSource("test.preload", "Preload")) + new DiagnosticHub().CreateReporter(new DiagnosticSource("test.preload", "Preload")) ); AudioClipAsset clip = CreateClip(4800); ValueTask ready = runtime.PreloadAsync(clip); @@ -933,7 +937,7 @@ public async Task PreloadCompletesOnlyAfterPreparationAndCancellationReleasesRes public async Task PreloadedArtifactRetirementResumesWithoutDestroyingTheNativeClipTwice(bool shutdown) { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.artifact", "Artifact")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.artifact", "Artifact")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); await runtime.PreloadAsync(clip); @@ -964,7 +968,7 @@ public async Task PreloadedArtifactRetirementResumesWithoutDestroyingTheNativeCl public void CanceledPreloadDoesNotCompleteBeforeItsPendingArtifactRetires() { var device = new ReadyAudioDevice { clipState = AudioClipState.Preparing }; - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.cancel", "Cancel")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.cancel", "Cancel")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); using var cancellation = new CancellationTokenSource(); @@ -987,7 +991,7 @@ public void CanceledPreloadDoesNotCompleteBeforeItsPendingArtifactRetires() public async Task APartiallyRetiredClipCannotBeReusedByANewVoice() { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.reuse", "Reuse")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.reuse", "Reuse")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); await runtime.PreloadAsync(clip); @@ -1009,7 +1013,7 @@ public async Task APartiallyRetiredClipCannotBeReusedByANewVoice() [Fact] public async Task CacheHitRequestRetiresItsExtraArtifactThroughTheSharedGenerationBarrier() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); AudioClipAsset clip = CreateClip(4800); await runtime.PreloadAsync(clip); m_artifacts.pendingReleaseId = clip.identity.persistentId; @@ -1025,7 +1029,7 @@ public async Task CacheHitRequestRetiresItsExtraArtifactThroughTheSharedGenerati [Fact] public async Task RetryingPreloadReleaseDoesNotConsumeAnotherLoadModeReservation() { - using var runtime = CreateRuntime(); + using AudioRuntime runtime = CreateRuntime(); AudioClipAsset clip = CreateClip(4800); await runtime.PreloadAsync(clip, AudioClipLoadMode.Decode); await runtime.PreloadAsync(clip, AudioClipLoadMode.Stream); @@ -1050,7 +1054,7 @@ public async Task FailedPreloadAdmissionRetiresOnlyItsOwnReservation( bool queryThrows ) { var device = new ReadyAudioDevice(); - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.query", "Query")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.query", "Query")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); if (cached) @@ -1094,7 +1098,7 @@ public void PreloadQueryAndRollbackFailureRetainBothDiagnosticsAndFaultTheGenera clipQueryFailure = new InvalidOperationException("Expected clip query failure."), failClipRetirement = true }; - using var reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.rollback", "Rollback")); + using DiagnosticReporter reporter = new DiagnosticHub().CreateReporter(new DiagnosticSource("test.rollback", "Rollback")); using var runtime = new AudioRuntime(m_types, device, m_artifacts, m_events, reporter); AudioClipAsset clip = CreateClip(4800); AggregateException failure = Assert.Throws(() => runtime.PreloadAsync(clip)); @@ -1117,7 +1121,7 @@ private AudioRuntime CreateRuntime( new MutedAudioDevice(), m_artifacts, m_events, - new Inno.Core.Diagnostics.DiagnosticHub().CreateReporter(new Inno.Core.Diagnostics.DiagnosticSource("tests.audio", "Audio")), + new DiagnosticHub().CreateReporter(new DiagnosticSource("tests.audio", "Audio")), options: new AudioRuntimeOptions { maxVoices = maxVoices, @@ -1130,7 +1134,7 @@ private AudioClipAsset CreateClip(long frameCount) { var clip = new AudioClipAsset(); byte[] payload = AudioClipMetadataCodec.Encode( - new AudioClipMetadata(AudioCodecId.wav, 2, 48000, frameCount, 256) + new AudioClipMetadata(AudioCodecId.wav, 2, 48_000, frameCount, 256) ); new AssetRuntimeOwner().Initialize( clip, @@ -1199,7 +1203,7 @@ internal void Add( Guid id, string path ) { - byte[] bytes = new byte[256]; + var bytes = new byte[256]; File.WriteAllBytes(path, bytes); m_paths[id] = path; m_artifacts[id] = new AssetArtifactInfo( diff --git a/tests/audio/Inno.Audio.Tests/AudioContractTests.cs b/tests/audio/Inno.Audio.Tests/AudioContractTests.cs index 4a3cfdcc3..59b9449ce 100644 --- a/tests/audio/Inno.Audio.Tests/AudioContractTests.cs +++ b/tests/audio/Inno.Audio.Tests/AudioContractTests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -29,8 +30,8 @@ public void ExecutionContext_ForwardsFacadeAndEnforcesLifoDisposal() public void MixerBuilder_ProducesParentBeforeChildGraphWithMasterBus() { var builder = new AudioMixerBuilder(); - AudioBusId music = new("game.audio.bus.music"); - AudioBusId ambience = new("game.audio.bus.ambience"); + var music = new AudioBusId("game.audio.bus.music"); + var ambience = new AudioBusId("game.audio.bus.ambience"); builder.AddBus(ambience, music); builder.AddBus(music, AudioBusId.master); builder.AddProcessor( @@ -43,10 +44,7 @@ [new AudioProcessorParameter(new AudioParameterId("frequency"), 12000f)] AudioMixer mixer = builder.Build(); - Assert.Equal( - [AudioBusId.master, music, ambience], - System.Linq.Enumerable.Select(mixer.buses, static bus => bus.id) - ); + Assert.Equal([AudioBusId.master, music, ambience], Enumerable.Select(mixer.buses, static bus => bus.id)); Assert.Single(mixer.buses[1].processors); } @@ -58,8 +56,8 @@ public void MixerBuilder_RejectsMissingParentsAndCycles() Assert.Throws(missingParent.Build); var cycle = new AudioMixerBuilder(); - AudioBusId first = new("game.audio.bus.first"); - AudioBusId second = new("game.audio.bus.second"); + var first = new AudioBusId("game.audio.bus.first"); + var second = new AudioBusId("game.audio.bus.second"); cycle.AddBus(first, second); cycle.AddBus(second, first); Assert.Throws(cycle.Build); @@ -68,7 +66,7 @@ public void MixerBuilder_RejectsMissingParentsAndCycles() [Fact] public void MetadataCodec_RoundTripsCompactRuntimeHeader() { - var expected = new AudioClipMetadata(AudioCodecId.flac, 2, 48000, 96000, 123456); + var expected = new AudioClipMetadata(AudioCodecId.flac, 2, 48_000, 96_000, 123_456); byte[] payload = AudioClipMetadataCodec.Encode(expected); AudioClipMetadata actual = AudioClipMetadataCodec.Decode(payload); @@ -93,7 +91,7 @@ private sealed class FakeAudioService(uint generation) : IAudioService { private readonly AudioVoiceAllocator m_voices = new(); - public AudioCapabilities capabilities { get; } = new(true, true, true, 4, 48000); + public AudioCapabilities capabilities { get; } = new(true, true, true, 4, 48_000); public AudioDeviceState deviceState => AudioDeviceState.Ready; @@ -103,10 +101,7 @@ private sealed class FakeAudioService(uint generation) : IAudioService public AudioVoiceHandle CreateTestVoice() => m_voices.Allocate(); - public bool Owns(AudioVoiceHandle voice) - { - return voice.isValid && voice.ownerGeneration == m_voices.generation; - } + public bool Owns(AudioVoiceHandle voice) => voice.isValid && voice.ownerGeneration == m_voices.generation; public AudioVoiceHandle Play(AudioClipAsset clip) { diff --git a/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs b/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs index ccd2312c4..e1e1f75c8 100644 --- a/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs +++ b/tests/audio/Inno.Audio.Tests/AudioScriptingApiTests.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; using Inno.Adapter.Modules.DotNet; @@ -8,6 +9,7 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Audio.Runtime; +using Inno.Build; using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Settings; @@ -29,7 +31,7 @@ public async Task FacadeMixerProviderAndSceneComponentsCompileThroughLogicalName Directory.CreateDirectory(Path.Combine(projectRoot, "Library")); try { - _ = typeof(Inno.Audio.Audio); + _ = typeof(Audio); _ = typeof(AudioProjectSettings); var identities = new IdentityAllocator(); using IDisposable identityScope = identities.EnterScope(); @@ -78,14 +80,14 @@ public async Task FacadeMixerProviderAndSceneComponentsCompileThroughLogicalName host.modules.generations ); string dotnetHost = Path.Combine( - Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" ); var compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = projectRoot, - compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, projectRoot) + compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) }, assets, plugins diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs index 5987559d5..015be3e53 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs @@ -24,7 +24,7 @@ public BgfxDeviceTests(BgfxDeviceFixture fixture) [Fact] public void NoopDevice_ExecutesOneGraphAndSubmitsOneFrame() { - RenderGraphBuilder builder = new(1, m_device.capabilities); + var builder = new RenderGraphBuilder(1, m_device.capabilities); builder .AddRasterPass("Noop Clear", C_FIRST, 0, static ( _, @@ -59,7 +59,7 @@ public void CreateWindowSurface_RejectsUnsupportedPlatformHandlesBeforeNativeCre m_device.BeginFrame(); Assert.Throws(() => m_device.CreateWindowSurface( - new PlatformNativeHandles(new IntPtr(1), handleKind: default(PlatformNativeHandleId)), + new PlatformNativeHandles(new IntPtr(1), handleKind: default), 32, 32, "Unsupported" @@ -71,7 +71,7 @@ public void CreateWindowSurface_RejectsUnsupportedPlatformHandlesBeforeNativeCre [Fact] public void NoopDevice_CreatesAndDefersPersistentTextureDestruction() { - RenderTextureDescriptor descriptor = new(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled); + var descriptor = new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled); m_device.BeginFrame(); PersistentTextureHandle texture = m_device.CreateTexture(descriptor, "Persistent Test"); @@ -90,7 +90,7 @@ public void NoopDevice_CreatesAndDefersPersistentTextureDestruction() [Fact] public void NoopDevice_UploadsCompletePersistentTextureSubresource() { - RenderTextureDescriptor descriptor = new(4, 4, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled); + var descriptor = new RenderTextureDescriptor(4, 4, RenderTextureFormat.RGBA8, RenderTextureUsage.Sampled); m_device.BeginFrame(); PersistentTextureHandle texture = m_device.CreateTexture(descriptor, "Upload Test"); @@ -105,7 +105,7 @@ public void NoopDevice_CreatesAndUpdatesVolumeAndCubemapSubresources() Assert.True(m_device.capabilities.Supports(GraphicsCapability.Texture3D)); Assert.True(m_device.capabilities.SupportsSampled(RenderTextureFormat.RGBA8, RenderTextureDimension.Texture3D)); Assert.True(m_device.capabilities.SupportsSampled(RenderTextureFormat.RGBA8, RenderTextureDimension.Cube)); - RenderTextureDescriptor volumeDescriptor = new( + var volumeDescriptor = new RenderTextureDescriptor( 4, 4, RenderTextureFormat.RGBA8, @@ -113,7 +113,7 @@ public void NoopDevice_CreatesAndUpdatesVolumeAndCubemapSubresources() dimension: RenderTextureDimension.Texture3D, depth: 2 ); - RenderTextureDescriptor cubeDescriptor = new( + var cubeDescriptor = new RenderTextureDescriptor( 4, 4, RenderTextureFormat.RGBA8, @@ -134,18 +134,18 @@ public void NoopDevice_CreatesAndUpdatesVolumeAndCubemapSubresources() [Fact] public void NoopDevice_UpdatesDynamicVertexBuffer() { - RenderVertexLayout layout = new( + var layout = new RenderVertexLayout( [ new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) ] ); - PersistentBufferDescriptor descriptor = new( + var descriptor = new PersistentBufferDescriptor( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex | RenderBufferUsage.Dynamic), layout ); m_device.BeginFrame(); - PersistentBufferHandle buffer = m_device.CreateBuffer(descriptor, ReadOnlySpan.Empty, "Dynamic"); + PersistentBufferHandle buffer = m_device.CreateBuffer(descriptor, [], "Dynamic"); m_device.UpdateBuffer(buffer, new byte[layout.stride * 3]); m_device.DestroyBuffer(buffer); m_device.EndFrame(); @@ -154,14 +154,14 @@ public void NoopDevice_UpdatesDynamicVertexBuffer() [Fact] public void NoopDevice_CreatesVertexBufferWithExplicitPadding() { - RenderVertexLayout layout = new( + var layout = new RenderVertexLayout( [ new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3, 0), new RenderVertexAttribute(RenderVertexSemantic.Color0, RenderVertexFormat.UInt8Normalized4, 16) ], stride: 32 ); - PersistentBufferDescriptor descriptor = new( + var descriptor = new PersistentBufferDescriptor( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex), layout ); @@ -181,16 +181,16 @@ public void NoopDevice_CreatesVertexBufferWithExplicitPadding() [Fact] public void NoopDevice_CreatesVertexAndIndexBuffersAtFrameSafetyPoint() { - RenderVertexLayout layout = new( + var layout = new RenderVertexLayout( [ new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) ] ); - PersistentBufferDescriptor vertices = new( + var vertices = new PersistentBufferDescriptor( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex), layout ); - PersistentBufferDescriptor indices = new( + var indices = new PersistentBufferDescriptor( new RenderBufferDescriptor(3, sizeof(ushort), RenderBufferUsage.Index), indexFormat: RenderIndexFormat.UInt16 ); @@ -209,7 +209,7 @@ public void NoopDevice_CreatesVertexAndIndexBuffersAtFrameSafetyPoint() [Fact] public void NoopDevice_AllocatesTransientStorageBufferForCompiledGraph() { - RenderGraphBuilder builder = new(8, m_device.capabilities); + var builder = new RenderGraphBuilder(8, m_device.capabilities); RenderBufferHandle buffer = builder.CreateBuffer( "Cluster Light List", new RenderBufferDescriptor(64, 16, RenderBufferUsage.Storage) @@ -235,7 +235,7 @@ public void NoopDevice_AllocatesTransientStorageTextureForCompiledGraph() { Assert.True(m_device.capabilities.Supports(GraphicsCapability.StorageTexture)); Assert.True(m_device.capabilities.SupportsStorage(RenderTextureFormat.RGBA8, RenderStorageAccess.Write)); - RenderGraphBuilder builder = new(9, m_device.capabilities); + var builder = new RenderGraphBuilder(9, m_device.capabilities); RenderTextureHandle texture = builder.CreateTexture( "Compute Output", new RenderTextureDescriptor(8, 8, RenderTextureFormat.RGBA8, RenderTextureUsage.Storage) @@ -298,7 +298,7 @@ public void NoopDevice_RetiresSupersededNamedFramebuffersDuringResizeChurn() const int passCount = 16; for (uint frame = 0; frame < 32; frame++) { - RenderGraphBuilder builder = new(1000 + frame, m_device.capabilities); + var builder = new RenderGraphBuilder(1000 + frame, m_device.capabilities); int extent = 64 + checked((int)frame); for (int passIndex = 0; passIndex < passCount; passIndex++) { @@ -335,12 +335,12 @@ public void NoopDevice_RetiresSupersededNamedFramebuffersDuringResizeChurn() [Fact] public void CreateBuffer_WithPartialInitialData_FailsWithoutClosingFrame() { - RenderVertexLayout layout = new( + var layout = new RenderVertexLayout( [ new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) ] ); - PersistentBufferDescriptor descriptor = new( + var descriptor = new PersistentBufferDescriptor( new RenderBufferDescriptor(3, layout.stride, RenderBufferUsage.Vertex), layout ); @@ -353,7 +353,7 @@ public void CreateBuffer_WithPartialInitialData_FailsWithoutClosingFrame() [Fact] public void NoopDevice_BindsRequestedTextureArrayLayer() { - RenderGraphBuilder builder = new(4, m_device.capabilities); + var builder = new RenderGraphBuilder(4, m_device.capabilities); RenderTextureHandle texture = builder.CreateTexture( "Layered Target", new RenderTextureDescriptor( @@ -381,10 +381,7 @@ public void NoopDevice_BindsRequestedTextureArrayLayer() } [Fact] - public void EndFrame_WithoutBeginFrame_Throws() - { - Assert.Throws(() => m_device.EndFrame()); - } + public void EndFrame_WithoutBeginFrame_Throws() => Assert.Throws(() => m_device.EndFrame()); [Fact] public void WindowlessDeviceDoesNotAdvertiseAnInternalBackbufferAsPresentation() @@ -419,7 +416,7 @@ private CompiledRenderGraph BuildColorTargetGraph( uint generation, string passName = "Stable Color Pass" ) { - RenderGraphBuilder builder = new(generation, m_device.capabilities); + var builder = new RenderGraphBuilder(generation, m_device.capabilities); RenderTextureHandle texture = builder.CreateTexture( "Stable Color Target", new RenderTextureDescriptor( @@ -450,7 +447,7 @@ public sealed class BgfxDeviceFixture : IDisposable { public BgfxDeviceFixture() { - device = CreateDevice(); + this.device = CreateDevice(); } public BgfxDevice device { get; } diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs index 3ae6e6202..0c1e736a2 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxShutdownTests.cs @@ -25,7 +25,7 @@ public void ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner() ? OperatingSystem.IsWindows() ? GraphicsApi.Direct3D11 : GraphicsApi.Metal : new GraphicsApi(requestedBackend); using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { title = "Resource retirement", width = 100, @@ -42,8 +42,8 @@ public void ShutdownAfterAnOffscreenGraphReleasesTheProcessOwner() using (var device = new BgfxDevice(options)) { Assert.Equal(backend, device.capabilities.backend); - RenderGraphBuilder builder = new(1, device.capabilities); - RenderTextureDescriptor descriptor = new( + var builder = new RenderGraphBuilder(1, device.capabilities); + var descriptor = new RenderTextureDescriptor( 32, 32, RenderTextureFormat.RGBA8, diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs index 4d61790bf..3409839da 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using Xunit; using Inno.Adapter.Platform; using Inno.Adapter.Platform.Sdl3; @@ -43,7 +44,7 @@ public void InvalidIntegrationFailsBeforeTakingTheProcessOwner() } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { title = "Invalid integration", width = 100, @@ -69,14 +70,14 @@ public void InvalidIntegrationFailsBeforeTakingTheProcessOwner() private static void VerifyRetirement(bool inline) { using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var primary = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow primary = application.CreateWindow(new PlatformWindowOptions { title = "Primary surface", width = 100, height = 90, visible = false }); - using var additional = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow additional = application.CreateWindow(new PlatformWindowOptions { title = "Additional surface", width = 100, @@ -101,7 +102,7 @@ private static void VerifyRetirement(bool inline) RenderSurfaceHandle surface = device.CreateWindowSurface(handles, 100, 90, "Custom surface"); device.ResizeWindowSurface(surface, 110, 95); device.ResizeWindowSurface(surface, 120, 100); - var retirement = device.RetireWindowSurface(surface); + Task retirement = device.RetireWindowSurface(surface); Assert.False(retirement.IsCompleted); Assert.Equal(2, integration.resolveCount); Assert.Throws(() => device.ResizeWindowSurface(surface, 120, 100)); @@ -119,7 +120,7 @@ private static void VerifyRetirement(bool inline) for (int cycle = 0; cycle < 8; cycle++) { RenderSurfaceHandle final = device.CreateWindowSurface(handles, 100, 90, "Drained surface"); - var drained = device.RetireWindowSurface(final); + Task drained = device.RetireWindowSurface(final); device.DrainWindowSurfaceRetirements(); Assert.True(drained.IsCompletedSuccessfully); Assert.False(primary.isClosed); diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs index 115270c52..8d170adb0 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Integration.Tests/BgfxToolchainTests.cs @@ -38,7 +38,10 @@ public sealed class BgfxToolchainTests : IDisposable Guid.NewGuid().ToString("N") ); - public BgfxToolchainTests() => Directory.CreateDirectory(m_root); + public BgfxToolchainTests() + { + Directory.CreateDirectory(m_root); + } [Fact] [SupportedOSPlatform("windows")] @@ -188,7 +191,7 @@ public async Task GlslReflectionPreservesUsedBindingsAndRemovesOptimizedBindings } [Fact] - public async System.Threading.Tasks.Task TextureCompilerProducesValidatedPortableContainer() + public async Task TextureCompilerProducesValidatedPortableContainer() { string sourcePath = Path.Combine(m_root, "checker.tga"); File.WriteAllBytes(sourcePath, CreateTga()); @@ -289,7 +292,7 @@ private static Dictionary ReadBinaryUniformTypes(ReadOnlySpan()) + foreach (BgfxTool tool in Enum.GetValues()) { - var toolName = tool.ToString().ToLowerInvariant(); + string toolName = tool.ToString().ToLowerInvariant(); ToolRunResult result = new ToolRunner().Run(tool, ["--help"]); Assert.InRange(result.exitCode, 0, 1); Assert.False(string.IsNullOrWhiteSpace(result.standardOutput + result.standardError)); diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs index 1450639e5..51b884db2 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/BgfxShaderProfileTests.cs @@ -2,6 +2,7 @@ using Xunit; using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Rendering; +using Inno.Rendering.Assets.Authoring; namespace Inno.Build.Toolchains.Bgfx.Tests; @@ -15,7 +16,7 @@ public void NewTargetAndRendererUseThePublicConfigurationBoundary() var profile = new BgfxShaderCompilerProfile(capabilities, "fixture-sdk", "vertex", "fragment", "compute"); var configuration = new BgfxShaderTargetProfile("fixture-console", [profile]); - var target = new BgfxShadercToolchain(configuration).CreateTarget(capabilities); + ShaderCompileTarget target = new BgfxShadercToolchain(configuration).CreateTarget(capabilities); Assert.Same(profile, configuration.Resolve(api)); Assert.Contains("fixture-console", target.profileKey, StringComparison.Ordinal); @@ -85,7 +86,7 @@ public void InvalidAndDuplicateProfilesFailBeforeCreatingACompiler() "osx", "metal", "metal", - "" + string.Empty )); Assert.Throws(() => new BgfxShadercToolchain(null!)); } diff --git a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs index 25a9fd2d7..78f0bca4c 100644 --- a/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs +++ b/tests/backends/Bgfx/Inno.Build.Toolchains.Bgfx.Tests/ToolRunnerTests.cs @@ -8,8 +8,5 @@ namespace Inno.Build.Toolchains.Bgfx.Tests; public sealed class ToolRunnerTests { [Fact] - public void Run_Throws_WhenToolMissing() - { - Assert.Throws(() => new ToolRunner().Run((BgfxTool)999, ["--help"])); - } + public void Run_Throws_WhenToolMissing() => Assert.Throws(() => new ToolRunner().Run((BgfxTool)999, ["--help"])); } diff --git a/tests/backends/Bgfx/Inno.Native.Bgfx.Tests/BgfxInitTests.cs b/tests/backends/Bgfx/Inno.Native.Bgfx.Tests/BgfxInitTests.cs index f79256c12..626eb1103 100644 --- a/tests/backends/Bgfx/Inno.Native.Bgfx.Tests/BgfxInitTests.cs +++ b/tests/backends/Bgfx/Inno.Native.Bgfx.Tests/BgfxInitTests.cs @@ -18,7 +18,7 @@ public unsafe void InitAndShutdown_ShouldSucceed() Assert.True(ok); try { - Assert.True(bgfx.Raw.get_caps() != null); + Assert.True(bgfx.Raw.get_caps() is not null); Assert.Equal(bgfx.RendererType.Noop, bgfx.get_renderer_type()); } finally diff --git a/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs b/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs index 49b1fea64..0e27d5e6c 100644 --- a/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs +++ b/tests/backends/Bgfx/fixtures/Inno.Testing.Bgfx/ShaderProfileFixture.cs @@ -4,10 +4,14 @@ namespace Inno.Testing.Bgfx; -/// Defines explicit shader target fixtures shared by metadata and real compiler tests. +/// +/// Defines explicit shader target fixtures shared by metadata and real compiler tests. +/// public static class ShaderProfileFixture { - /// Gets the explicit windows shader profile used by the tests. + /// + /// Gets the explicit windows shader profile used by the tests. + /// public static BgfxShaderTargetProfile windows { get; } = new( "fixture-windows", [ @@ -17,7 +21,9 @@ public static class ShaderProfileFixture ] ); - /// Gets the explicit mac shader profile used by the tests. + /// + /// Gets the explicit mac shader profile used by the tests. + /// public static BgfxShaderTargetProfile mac { get; } = new( "fixture-mac", [ @@ -27,7 +33,9 @@ public static class ShaderProfileFixture ] ); - /// Gets the explicit browser shader profile used by the tests. + /// + /// Gets the explicit browser shader profile used by the tests. + /// public static BgfxShaderTargetProfile browser { get; } = new( "fixture-browser", [new( @@ -45,14 +53,22 @@ public static class ShaderProfileFixture "asm.js", "300_es", "300_es", - "" + string.Empty )] ); - /// Creates the declared rendering capabilities without loading a native runtime. - /// The explicit graphics API. - /// The capabilities required by the test. - /// The immutable capability description. + /// + /// Creates the declared rendering capabilities without loading a native runtime. + /// + /// + /// The explicit graphics API. + /// + /// + /// The capabilities required by the test. + /// + /// + /// The immutable capability description. + /// public static GraphicsCapabilities CreateCapabilities( GraphicsApi backend, diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs index ad7eb8b9d..c2f34583a 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheCancellationTests.cs @@ -11,13 +11,13 @@ public sealed class ContentCacheCancellationTests [Fact] public async Task CancellationDuringCopyDiscardsCandidateAndPreservesThePreviousPointer() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); using (FileContentStore first = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options)) { } string previous = fixture.current; File.Delete(Path.Combine(previous, "AssetDatabase", "Catalog.snapshot")); - using CancellationTokenSource cancellation = new(); + using var cancellation = new CancellationTokenSource(); fixture.source.onRead = cancellation.Cancel; await Assert.ThrowsAnyAsync(() => FileContentPreparation.PrepareAsync( fixture.source, @@ -34,7 +34,7 @@ await Assert.ThrowsAnyAsync(() => FileContentPrepara [Fact] public async Task PriorCancellationCreatesNoCacheDirectory() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); await Assert.ThrowsAnyAsync(() => FileContentPreparation.PrepareAsync( fixture.source, fixture.options, diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs index 26ba49e69..bbbbd216f 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheConcurrencyTests.cs @@ -10,7 +10,7 @@ public sealed class ContentCacheConcurrencyTests [Fact] public async Task ConcurrentPreparationPublishesOneCompleteGeneration() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); FileContentStore[] readers = await Task.WhenAll( Enumerable.Range(0, 8).Select(_ => FileContentPreparation.PrepareAsync(fixture.source, fixture.options).AsTask()) diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs index b82340340..03b792107 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheFixture.cs @@ -40,7 +40,7 @@ internal sealed class MemoryContentStore : IRuntimeContentStore internal MemoryContentStore(Dictionary content) { m_content = content.ToDictionary(static pair => new ContentKey(pair.Key), static pair => (byte[])pair.Value.Clone()); - index = new ContentPackIndex( + this.index = new ContentPackIndex( m_content.Select(static pair => new ContentEntry( pair.Key, pair.Value.Length, @@ -54,7 +54,7 @@ internal MemoryContentStore(Dictionary content) ) ) ); - descriptor = new ContentPackDescriptor(hash, $"content-{hash}.pack"); + this.descriptor = new ContentPackDescriptor(hash, $"content-{hash}.pack"); } public ContentPackDescriptor descriptor { get; } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs index f4a28ddbb..9d9979c85 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheIntegrityTests.cs @@ -1,6 +1,8 @@ +using System; using System.IO; using System.Threading.Tasks; using Xunit; +using Xunit.Sdk; using Inno.Content; namespace Inno.Adapter.Content.FileSystem.Tests; @@ -16,7 +18,7 @@ public sealed class ContentCacheIntegrityTests [InlineData("missing-lease")] public async Task CompleteValidationRepairsEveryKindOfCacheCorruption(string fault) { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); using (FileContentStore first = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options)) { } @@ -34,7 +36,7 @@ public async Task CompleteValidationRepairsEveryKindOfCacheCorruption(string fau Directory.CreateDirectory(Path.Combine(original, "unindexed")); break; case "same-length-and-time": - var time = File.GetLastWriteTimeUtc(file); + DateTime time = File.GetLastWriteTimeUtc(file); File.WriteAllBytes(file, [3, 2, 1]); File.SetLastWriteTimeUtc(file, time); break; @@ -49,7 +51,7 @@ public async Task CompleteValidationRepairsEveryKindOfCacheCorruption(string fau Assert.NotEqual(original, fixture.current); using ContentReadLease lease = repaired.Acquire(new ContentKey("AssetDatabase/Catalog.snapshot")); using Stream input = lease.OpenRead(); - byte[] bytes = new byte[3]; + var bytes = new byte[3]; input.ReadExactly(bytes); Assert.Equal(new byte[] { 1, 2, 3 }, bytes); Assert.Equal(-1, input.ReadByte()); @@ -68,11 +70,11 @@ public async Task CompleteValidationRepairsEveryKindOfCacheCorruption(string fau [Fact] public async Task ContentChangedAfterPreparationFailsReadingAndReleasesTheFailedStreamPin() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); using FileContentStore store = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); string original = fixture.current; string file = Path.Combine(original, "AssetDatabase", "Catalog.snapshot"); - var time = File.GetLastWriteTimeUtc(file); + DateTime time = File.GetLastWriteTimeUtc(file); File.WriteAllBytes(file, [3, 2, 1]); File.SetLastWriteTimeUtc(file, time); using (ContentReadLease lease = store.Acquire(new ContentKey("AssetDatabase/Catalog.snapshot"))) @@ -88,10 +90,10 @@ public async Task ContentChangedAfterPreparationFailsReadingAndReleasesTheFailed [Fact] public async Task ValidCacheReusePreservesGenerationAndDoesNotReadSourcePayloads() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); using FileContentStore first = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); string generation = fixture.current; - fixture.source.onRead = () => throw new Xunit.Sdk.XunitException("A verified cache must not recopy payloads."); + fixture.source.onRead = () => throw new XunitException("A verified cache must not recopy payloads."); using FileContentStore second = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); Assert.Equal(generation, fixture.current); } diff --git a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs index 6bb53c8ac..0dda41fba 100644 --- a/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs +++ b/tests/backends/FileSystem/Inno.Adapter.Content.FileSystem.Tests/ContentCacheRetirementTests.cs @@ -10,7 +10,7 @@ public sealed class ContentCacheRetirementTests [Fact] public async Task RepairKeepsAnOldReaderGenerationUntilItsLastStreamCloses() { - using ContentCacheFixture fixture = new(); + using var fixture = new ContentCacheFixture(); FileContentStore old = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); string oldDirectory = fixture.current; ContentReadLease lease = old.Acquire(new ContentKey("Artifacts/aa/bb/data")); @@ -21,7 +21,7 @@ public async Task RepairKeepsAnOldReaderGenerationUntilItsLastStreamCloses() using FileContentStore replacement = await FileContentPreparation.PrepareAsync(fixture.source, fixture.options); Assert.NotEqual(oldDirectory, fixture.current); Assert.True(Directory.Exists(oldDirectory)); - byte[] bytes = new byte[3]; + var bytes = new byte[3]; input.ReadExactly(bytes); Assert.Equal(new byte[] { 4, 5, 6 }, bytes); input.Dispose(); diff --git a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiAbiLayoutTests.cs b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiAbiLayoutTests.cs index ec1eb0fb3..4655070f9 100644 --- a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiAbiLayoutTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiAbiLayoutTests.cs @@ -13,7 +13,7 @@ public void GeneratedVectorStoragePreservesNativeOffsetsAndBorrowedData() Assert.Equal(2 * sizeof(int), Marshal.OffsetOf(nameof(ImVectorInt.Data)).ToInt32()); int* values = stackalloc int[3] { 11, 23, 37 }; - ImVectorInt vector = new() { Size = 2, Capacity = 3, Data = values }; + var vector = new ImVectorInt() { Size = 2, Capacity = 3, Data = values }; Assert.Equal(2, vector.Size); Assert.Equal(3, vector.Capacity); Assert.Equal(11, vector.Data[0]); diff --git a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs index bf6f10186..6ccf5451e 100644 --- a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiInitTests.cs @@ -19,10 +19,10 @@ public ImGuiInitTests(ITestOutputHelper output) [Fact] public void CreateAndDestroyContext_ShouldSucceed() { - var context = ImGui.Raw.CreateContext(null); - Assert.True(context != null); + ImGuiNativeContext* context = ImGui.Raw.CreateContext(null); + Assert.True(context is not null); - var version = Marshal.PtrToStringUTF8((nint)ImGui.Raw.GetVersion()); + string? version = Marshal.PtrToStringUTF8((nint)ImGui.Raw.GetVersion()); output.WriteLine($"ImGui.GetVersion: {version}"); Assert.False(string.IsNullOrWhiteSpace(version)); @@ -32,7 +32,7 @@ public void CreateAndDestroyContext_ShouldSucceed() [Fact] public void TextDisabled_UsesTheLoadedCimguiSymbol() { - var context = ImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = ImGui.Raw.CreateContext(null); try { ImGuiIO* io = ImGui.Raw.GetIO(); diff --git a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs index 0d4266a14..6d8cdf541 100644 --- a/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGui.Tests/ImGuiPlatformCallbackTests.cs @@ -25,21 +25,21 @@ public void RegistrationRejectsForeignOwnersAndRequiresItsIdleContextThread() void* registration = null; try { - Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(null, &SetPosition, &SetSize) == null); - Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, null, &SetSize) == null); + Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(null, &SetPosition, &SetSize) is null); + Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, null, &SetSize) is null); ImGui.Raw.GetIO()->BackendPlatformUserData = (void*)1; - Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) == null); + Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) is null); Assert.Equal((nint)1, (nint)ImGui.Raw.GetIO()->BackendPlatformUserData); ImGui.Raw.GetIO()->BackendPlatformUserData = null; registration = ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize); - Assert.True(registration != null); + Assert.True(registration is not null); Assert.Equal((nint)registration, (nint)ImGui.Raw.GetIO()->BackendPlatformUserData); - Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) == null); + Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) is null); Assert.Equal(1, ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(registration)); nint address = (nint)registration; int foreignThreadResult = -1; - Thread worker = new(() => foreignThreadResult = ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks((void*)address)) + var worker = new Thread(() => foreignThreadResult = ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks((void*)address)) { IsBackground = true }; @@ -52,12 +52,12 @@ public void RegistrationRejectsForeignOwnersAndRequiresItsIdleContextThread() { ImGui.Raw.SetCurrentContext(second); Assert.Equal(0, ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(registration)); - Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) == null); + Assert.True(ImGui.Raw.InnoCreatePlatformWindowCallbacks(first, &SetPosition, &SetSize) is null); void* other = ImGui.Raw.InnoCreatePlatformWindowCallbacks(second, &SetPosition, &SetSize); - Assert.True(other != null); + Assert.True(other is not null); Assert.NotEqual((nint)registration, (nint)other); ImGui.Raw.InnoDestroyPlatformWindowCallbacks(other); - Assert.True(ImGui.Raw.GetIO()->BackendPlatformUserData == null); + Assert.True(ImGui.Raw.GetIO()->BackendPlatformUserData is null); } finally { @@ -69,7 +69,7 @@ public void RegistrationRejectsForeignOwnersAndRequiresItsIdleContextThread() { ImGui.Raw.SetCurrentContext(first); ImGui.Raw.InnoDestroyPlatformWindowCallbacks(registration); - Assert.True(ImGui.Raw.GetIO()->BackendPlatformUserData == null); + Assert.True(ImGui.Raw.GetIO()->BackendPlatformUserData is null); ImGui.Raw.DestroyContext(first); } } @@ -100,8 +100,8 @@ public void NativeViewportDispatchPreservesScalarsAndRejectsRetirementInsideCall platform->PlatformSetWindowTitle = &SetTitle; ImGui.Raw.PlatformIOSetPlatformGetWindowPos(platform, &GetPosition); ImGui.Raw.PlatformIOSetPlatformGetWindowSize(platform, &GetSize); - var monitor = (ImGuiPlatformMonitor*)ImGui.Raw.MemAlloc((nuint)sizeof(ImGuiPlatformMonitor)); - Assert.True(monitor != null); + ImGuiPlatformMonitor* monitor = (ImGuiPlatformMonitor*)ImGui.Raw.MemAlloc((nuint)sizeof(ImGuiPlatformMonitor)); + Assert.True(monitor is not null); *monitor = new ImGuiPlatformMonitor { MainSize = new ImVec2C { X = 1920, Y = 1080 }, @@ -110,7 +110,7 @@ public void NativeViewportDispatchPreservesScalarsAndRejectsRetirementInsideCall }; platform->Monitors = new ImVectorImGuiPlatformMonitor { Data = monitor, Size = 1, Capacity = 1 }; state.registration = ImGui.Raw.InnoCreatePlatformWindowCallbacks(context, &SetPosition, &SetSize); - Assert.True(state.registration != null); + Assert.True(state.registration is not null); for (int frame = 0; frame < 4; frame++) { @@ -144,7 +144,7 @@ private static void SetPosition( float x, float y ) { - var state = (CallbackState*)viewport->PlatformUserData; + CallbackState* state = (CallbackState*)viewport->PlatformUserData; state->positions++; state->invalid |= x != viewport->Pos.X || y != viewport->Pos.Y || ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(state->registration) != 0; @@ -156,7 +156,7 @@ private static void SetSize( float width, float height ) { - var state = (CallbackState*)viewport->PlatformUserData; + CallbackState* state = (CallbackState*)viewport->PlatformUserData; state->sizes++; state->invalid |= width != viewport->Size.X || height != viewport->Size.Y || ImGui.Raw.InnoCanDestroyPlatformWindowCallbacks(state->registration) != 0; diff --git a/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs b/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs index f84d2c884..8dbdb2053 100644 --- a/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs +++ b/tests/backends/ImGui/Inno.Native.ImGuizmo.Tests/ImGuizmoInitTests.cs @@ -25,9 +25,9 @@ public void Init_ShouldLoad() public unsafe void OwnedStyleCanRetireWithoutReleasingTheGlobalBorrow() { Style* borrowed = ImGuizmo.Raw.GetStyle(); - Assert.True(borrowed != null); + Assert.True(borrowed is not null); Style* owned = ImGuizmo.Raw.StyleStyle(); - Assert.True(owned != null); + Assert.True(owned is not null); Assert.True(owned != borrowed); try { diff --git a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs index 9b4117f15..651b3ab72 100644 --- a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs +++ b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedAudioTestSource.cs @@ -12,7 +12,7 @@ internal sealed class EncodedAudioTestSource : IAudioClipSource internal EncodedAudioTestSource(byte[] bytes) { m_bytes = (byte[])bytes.Clone(); - contentHash = Convert.ToHexString(SHA256.HashData(m_bytes)); + this.contentHash = Convert.ToHexString(SHA256.HashData(m_bytes)); } public string contentHash { get; } diff --git a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs index b260e4341..f982b6135 100644 --- a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs +++ b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/EncodedContentTests.cs @@ -88,7 +88,7 @@ public void InvalidEncodingIdentityFailsPreparationWithoutLeakingTheSource() private static AudioClipDescriptor Describe( IAudioClipSource source, AudioClipLoadMode mode - ) => new(AudioCodecId.wav, mode, 1, 48000, 4800, source.length); + ) => new(AudioCodecId.wav, mode, 1, 48_000, 4800, source.length); private static void WaitForReady( IAudioDevice backend, @@ -101,8 +101,7 @@ AudioClipHandle clip } private static void Retire(Func cleanup) - { - Assert.True( + => Assert.True( SpinWait.SpinUntil(() => { try @@ -116,7 +115,6 @@ private static void Retire(Func cleanup) } }, TimeSpan.FromSeconds(5)) ); - } private static byte[] CreateWave() { @@ -128,8 +126,8 @@ private static byte[] CreateWave() writer.Write(16); writer.Write((short)1); writer.Write((short)1); - writer.Write(48000); - writer.Write(96000); + writer.Write(48_000); + writer.Write(96_000); writer.Write((short)2); writer.Write((short)16); writer.Write("data"u8); @@ -150,7 +148,7 @@ private sealed class GatedSource : IAudioClipSource, IDisposable internal GatedSource(byte[] bytes) { m_bytes = bytes; - contentHash = Convert.ToHexString(SHA256.HashData(bytes)); + this.contentHash = Convert.ToHexString(SHA256.HashData(bytes)); } public string contentHash { get; init; } @@ -178,7 +176,10 @@ private sealed class GatedStream : MemoryStream private bool m_closed; internal GatedStream(GatedSource owner) - : base(owner.m_bytes, writable: false) => m_owner = owner; + : base(owner.m_bytes, writable: false) + { + m_owner = owner; + } public override async ValueTask ReadAsync( Memory buffer, diff --git a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs index ad1bda274..805d21d40 100644 --- a/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs +++ b/tests/backends/MiniAudio/Inno.Adapter.Audio.MiniAudio.Tests/MiniAudioDeviceTests.cs @@ -27,7 +27,7 @@ public void NativeAdmissionIncludesUndeliveredCompletionsAndReopensAfterDrain() AudioCodecId.wav, AudioClipLoadMode.Decode, 1, - 48000, + 48_000, 4800, new FileInfo(path).Length ); @@ -68,7 +68,7 @@ public void InvalidInputsDoNotAllocateNativeVoicesOrPoisonExistingPlayback() AudioCodecId.wav, AudioClipLoadMode.Decode, 1, - 48000, + 48_000, 4800, new FileInfo(clipPath).Length ), @@ -109,11 +109,11 @@ public void HeadlessDeviceAdvancesNativeGraphAndCompletesVoice() string clipPath = CreateWaveFile(frameCount: 2400); try { - using MiniAudioDevice device = new(new MiniAudioDeviceOptions + using var device = new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = true, channels = 2, - sampleRate = 48000, + sampleRate = 48_000, listenerCount = 2 }); IAudioDevice backend = device; @@ -123,7 +123,7 @@ public void HeadlessDeviceAdvancesNativeGraphAndCompletesVoice() AudioCodecId.wav, AudioClipLoadMode.Decode, 1, - 48000, + 48_000, 2400, new FileInfo(clipPath).Length ), @@ -177,7 +177,7 @@ public void StandardProcessorsAndScheduledControlsUseNativeNodes() string clipPath = CreateWaveFile(frameCount: 4800); try { - using MiniAudioDevice device = new(new MiniAudioDeviceOptions { noDevice = true }); + using var device = new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = true }); IAudioDevice backend = device; AudioBusHandle master = backend.CreateBus(AudioBusId.master); AudioBusHandle effects = backend.CreateBus(new AudioBusId("test.effects"), master); @@ -191,7 +191,7 @@ public void StandardProcessorsAndScheduledControlsUseNativeNodes() AudioCodecId.wav, AudioClipLoadMode.Stream, 1, - 48000, + 48_000, 4800, new FileInfo(clipPath).Length ), @@ -231,10 +231,10 @@ public void StandardProcessorsAndScheduledControlsUseNativeNodes() [Fact] public void MixerGenerationsCanOverlapUntilOldVoicesReleaseTheirGraph() { - string clipPath = CreateWaveFile(frameCount: 48000); + string clipPath = CreateWaveFile(frameCount: 48_000); try { - using MiniAudioDevice device = new(new MiniAudioDeviceOptions { noDevice = true }); + using var device = new MiniAudioDevice(new MiniAudioDeviceOptions { noDevice = true }); IAudioDevice backend = device; AudioBusHandle oldMaster = backend.CreateBus(AudioBusId.master); AudioBusHandle oldMusic = backend.CreateBus(new AudioBusId("test.music"), oldMaster); @@ -243,8 +243,8 @@ public void MixerGenerationsCanOverlapUntilOldVoicesReleaseTheirGraph() AudioCodecId.wav, AudioClipLoadMode.Decode, 1, - 48000, - 48000, + 48_000, + 48_000, new FileInfo(clipPath).Length ), new EncodedAudioTestSource(File.ReadAllBytes(clipPath)) @@ -282,14 +282,12 @@ AudioClipHandle clip private static void WaitForVoice( IAudioDevice device, AudioDeviceVoiceHandle voice - ) { - Assert.True( - SpinWait.SpinUntil(() => ( - device.TryGetVoiceState(voice, out AudioPlaybackState state) - && state != AudioPlaybackState.Preparing - ), TimeSpan.FromSeconds(5)) - ); - } + ) => Assert.True( + SpinWait.SpinUntil(() => ( + device.TryGetVoiceState(voice, out AudioPlaybackState state) + && state != AudioPlaybackState.Preparing + ), TimeSpan.FromSeconds(5)) + ); private static IEnumerable StandardProcessors() { @@ -329,12 +327,12 @@ private static AudioProcessorConfiguration CreateProcessor(AudioProcessorId id) private static string CreateWaveFile(int frameCount) { string path = Path.Combine(Path.GetTempPath(), $"inno-miniaudio-{Guid.NewGuid():N}.wav"); - const int sampleRate = 48000; + const int sampleRate = 48_000; const short channels = 1; const short bitsPerSample = 16; int dataLength = frameCount * channels * (bitsPerSample / 8); using FileStream stream = File.Create(path); - using BinaryWriter writer = new(stream); + using var writer = new BinaryWriter(stream); writer.Write("RIFF"u8); writer.Write(36 + dataLength); writer.Write("WAVE"u8); diff --git a/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs b/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs index b1ebdfba8..f82efce83 100644 --- a/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs +++ b/tests/backends/RmlUi/Inno.Adapter.UI.RmlUi.Tests/UiServiceTests.cs @@ -139,9 +139,9 @@ public void ElementHitTestIgnoresBlankCanvasAndPointerEventsNone() ); backend.ShowDocument(context, document); backend.Update(context, EmptyInput()); - Assert.True(backend.HasElementAtPoint(context, new Inno.Core.Mathematics.Vector2(30f, 30f))); - Assert.False(backend.HasElementAtPoint(context, new Inno.Core.Mathematics.Vector2(120f, 30f))); - Assert.False(backend.HasElementAtPoint(context, new Inno.Core.Mathematics.Vector2(200f, 100f))); + Assert.True(backend.HasElementAtPoint(context, new Vector2(30f, 30f))); + Assert.False(backend.HasElementAtPoint(context, new Vector2(120f, 30f))); + Assert.False(backend.HasElementAtPoint(context, new Vector2(200f, 100f))); } [Fact] diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs index a4cc13c52..ff4151393 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/HostIntegrationTests.cs @@ -36,7 +36,7 @@ public void WrappingFailureDestroysOnlyTheNewlyOwnedWindow() visible = false })); Assert.Empty(app.GetWindows()); - Assert.True(SDL.Raw.GetWindowFromId(host.lastId) == null); + Assert.True(SDL.Raw.GetWindowFromId(host.lastId) is null); } [Fact] @@ -50,7 +50,7 @@ public void SingleWindowCapabilityRejectsCreationBeforeCallingHostAgain() var host = new FailingHost { failSurface = false }; using var app = new Sdl3PlatformApplication(host); - using var window = app.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = app.CreateWindow(new PlatformWindowOptions { title = "Single surface", width = 40, diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs index 6d44cb1f1..dc9bae322 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/Sdl3WindowOperationsTests.cs @@ -59,7 +59,7 @@ bool highPixelDensity { SDL.Raw.DestroyWindow(native); } - Assert.True(SDL.Raw.GetWindowFromId(id) == null); + Assert.True(SDL.Raw.GetWindowFromId(id) is null); } [Fact] diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs index 28644b15d..28c2039db 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowOwnershipTests.cs @@ -20,7 +20,7 @@ public void ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows() using var first = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var second = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = first.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = first.CreateWindow(new PlatformWindowOptions { title = "Owned surface", width = 40, @@ -31,7 +31,7 @@ public void ApplicationDirectoryContainsOnlyCreatedOrAdoptedWindows() Assert.Empty(second.GetWindows()); window.Dispose(); Assert.Empty(first.GetWindows()); - Assert.True(SDL.Raw.GetWindowFromId(window.windowId) == null); + Assert.True(SDL.Raw.GetWindowFromId(window.windowId) is null); } [Fact] @@ -50,11 +50,11 @@ public void AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt() { native = SDL.Raw.CreateWindow((sbyte*)bytes, 40, 40, (ulong)SDLWindowFlags.Hidden); } - Assert.True(native != null); + Assert.True(native is not null); uint id = SDL.Raw.GetWindowId(native); try { - var borrowed = app.AdoptWindow((nint)native); + Sdl3PlatformWindow borrowed = app.AdoptWindow((nint)native); Assert.Single(app.GetWindows()); Assert.Throws(() => app.AdoptWindow((nint)native)); app.ReleaseWindow(borrowed); @@ -62,15 +62,15 @@ public void AdoptedWindowIsInvalidatedBeforeItsOriginalOwnerDestroysIt() Assert.True(borrowed.isClosed); Assert.Equal(0, borrowed.sdlWindowHandle); Assert.Throws(() => borrowed.nativeHandles); - Assert.True(SDL.Raw.GetWindowFromId(id) != null); + Assert.True(SDL.Raw.GetWindowFromId(id) is not null); borrowed.Dispose(); - Assert.True(SDL.Raw.GetWindowFromId(id) != null); + Assert.True(SDL.Raw.GetWindowFromId(id) is not null); } finally { SDL.Raw.DestroyWindow(native); } - Assert.True(SDL.Raw.GetWindowFromId(id) == null); + Assert.True(SDL.Raw.GetWindowFromId(id) is null); } [Fact] @@ -84,7 +84,7 @@ public void CrossApplicationReleaseAndCrossThreadCreationAreRejected() using var first = new Sdl3PlatformApplication(NativeHostFixture.Create()); using var second = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = first.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = first.CreateWindow(new PlatformWindowOptions { title = "Thread owner", width = 40, diff --git a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs index a5260a350..46627d8aa 100644 --- a/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs +++ b/tests/backends/Sdl3/Inno.Adapter.Platform.Sdl3.Tests/WindowSurfaceTests.cs @@ -17,9 +17,9 @@ public void OwnedAndBorrowedWrappersUseTheSameHostSurfaceResolution() return; } - var host = NativeHostFixture.Create(); + ISdl3HostIntegration host = NativeHostFixture.Create(); using var app = new Sdl3PlatformApplication(host); - using var window = app.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = app.CreateWindow(new PlatformWindowOptions { title = "Surface contract", width = 40, diff --git a/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/Sdl3InitTests.cs b/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/Sdl3InitTests.cs index c37cedd6a..0d33b32d7 100644 --- a/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/Sdl3InitTests.cs +++ b/tests/backends/Sdl3/Inno.Native.Sdl3.Tests/Sdl3InitTests.cs @@ -24,7 +24,7 @@ public Sdl3InitTests(ITestOutputHelper output) [Fact] public unsafe void InitAndQuit_ShouldSucceed() { - var initResult = SDL.Init(SDLInitFlags.Events); + bool initResult = SDL.Init(SDLInitFlags.Events); if (!initResult) { string message = Marshal.PtrToStringUTF8((nint)SDL.Raw.GetError()) ?? "SDL.Init returned false."; @@ -35,10 +35,10 @@ public unsafe void InitAndQuit_ShouldSucceed() output.WriteLine($"SDL.GetPlatform: {platform}"); Assert.False(string.IsNullOrWhiteSpace(platform)); - var version = SDL.GetVersion(); - var major = version / 1000000; - var minor = (version / 1000) % 1000; - var patch = version % 1000; + int version = SDL.GetVersion(); + int major = version / 1_000_000; + int minor = (version / 1000) % 1000; + int patch = version % 1000; output.WriteLine($"SDL.GetVersion: {major}.{minor}.{patch} ({version})"); Assert.True(version > 0); diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs index c3d992dd4..a7aa801f1 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingDefinitionTests.cs @@ -31,7 +31,12 @@ public async Task ExecutableOrNonLiteralDefinitionsFailBeforeOutputCreation(stri Path.Combine(m_root, "bindings.props"), "fixture" + body + "" ); - var descriptor = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); + var descriptor = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); var request = new NativeBindingGenerationRequest([descriptor], "fixture", NativeBindingOutputMode.HostSource); await Assert.ThrowsAsync(async () => await BindingTestProfiles.Generator() .GenerateAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); @@ -44,8 +49,17 @@ public async Task UndeclaredTargetNeverFallsBackToTheHostAbi() File.WriteAllText(Path.Combine(m_root, "bindings.props"), """ fixtureconfig.json """); - var descriptor = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var request = new NativeBindingGenerationRequest([descriptor], "unknown", NativeBindingOutputMode.TargetArtifacts); + var descriptor = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + var request = new NativeBindingGenerationRequest( + [descriptor], + "unknown", + NativeBindingOutputMode.TargetArtifacts + ); await Assert.ThrowsAsync(async () => await BindingTestProfiles.Generator() .GenerateAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None)); Assert.False(Directory.Exists(Path.Combine(m_root, "obj"))); diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs index ea8de06c1..ead334f77 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationBatchTests.cs @@ -36,9 +36,13 @@ public async Task SourceInputIdentityDetectsSelectedInputsWithoutGeneratingOrRea ); string unselected = Path.Combine(directory, "bindgen.unselected.json"); File.WriteAllText(unselected, "{}"); - var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); - var generator = BindingTestProfiles.Generator(); - NativeBuildContext initial = new(m_root, "release"); + var request = new NativeBindingGenerationRequest( + [component], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var initial = new NativeBuildContext(m_root, "release"); string identity = await generator.ComputeInputFingerprintAsync(initial, request, CancellationToken.None); File.WriteAllText(unselected, "{\"changed\":true}"); Assert.Equal( @@ -62,11 +66,15 @@ await generator.ComputeInputFingerprintAsync(new NativeBuildContext(m_root, "rel [Fact] public async Task OneBatchReusesSharedReadsOnlyWithinEachFreshPhase() { - var components = new[] { CreateComponent("first"), CreateComponent("second") }; + NativeComponentDescriptor[] components = new[] { CreateComponent("first"), CreateComponent("second") }; var context = new NativeBuildContext(m_root, "release"); - var generator = BindingTestProfiles.Generator(); - var request = new NativeBindingGenerationRequest(components, "fixture", NativeBindingOutputMode.TargetArtifacts); - using var result = await generator.GenerateAsync(context, request, CancellationToken.None); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var request = new NativeBindingGenerationRequest( + components, + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); + using NativeBindingGenerationResult result = await generator.GenerateAsync(context, request, CancellationToken.None); Assert.Equal(2, result.Count); Assert.Equal(1, context.statistics.bindingBatches); Assert.Equal(2, context.statistics.bindingGenerations); @@ -75,23 +83,31 @@ public async Task OneBatchReusesSharedReadsOnlyWithinEachFreshPhase() long expectedBytes = File.ReadAllBytes(Path.Combine(m_root, "Source", "shared.h")).Length; Assert.All(context.statistics.phases, phase => Assert.True(phase.bytes >= expectedBytes)); var hot = new NativeBuildContext(m_root, "release"); - using var hotResult = await generator.GenerateAsync(hot, request, CancellationToken.None); + using NativeBindingGenerationResult hotResult = await generator.GenerateAsync(hot, request, CancellationToken.None); Assert.Equal(0, hot.statistics.bindingGenerations); Assert.Equal(1, hot.statistics.bindingBatches); string header = Path.Combine(m_root, "Source", "shared.h"); DateTime timestamp = File.GetLastWriteTimeUtc(header); File.WriteAllText(header, "int change(int value);"); File.SetLastWriteTimeUtc(header, timestamp); - using var changed = await generator.GenerateAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + using NativeBindingGenerationResult changed = await generator.GenerateAsync( + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); Assert.All(result, entry => Assert.NotEqual(entry.Value.fingerprint, changed[entry.Key].fingerprint)); } [Fact] public async Task ActiveConsumersBlockReplacementAndReleaseAllowsRepair() { - var component = CreateComponent("reader"); - var generator = BindingTestProfiles.Generator(); - var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); + NativeComponentDescriptor component = CreateComponent("reader"); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var request = new NativeBindingGenerationRequest( + [component], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); var context = new NativeBuildContext(m_root, "release"); using NativeBindingGenerationResult first = await generator.GenerateAsync(context, request, CancellationToken.None); NativeBindingGenerationDescriptor descriptor = first[component.nativeProject]; @@ -133,11 +149,19 @@ await Assert.ThrowsAnyAsync(async () => [Fact] public async Task AFailedBatchPublishesNoPartialClosureAndPreservesEarlierOutputs() { - var first = CreateComponent("first"); - var second = CreateComponent("second"); - var generator = BindingTestProfiles.Generator(); - var request = new NativeBindingGenerationRequest([first, second], "fixture", NativeBindingOutputMode.TargetArtifacts); - using var completed = await generator.GenerateAsync(new NativeBuildContext(m_root, "release"), request, CancellationToken.None); + NativeComponentDescriptor first = CreateComponent("first"); + NativeComponentDescriptor second = CreateComponent("second"); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var request = new NativeBindingGenerationRequest( + [first, second], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); + using NativeBindingGenerationResult completed = await generator.GenerateAsync( + new NativeBuildContext(m_root, "release"), + request, + CancellationToken.None + ); string original = File.ReadAllText(completed[first.nativeProject].bindingsPath); File.WriteAllText(Path.Combine(m_root, "Source", "shared.h"), "int different(int value);"); File.WriteAllText(Path.Combine(m_root, "second", "broken.h"), "invalid C grammar;"); @@ -163,15 +187,27 @@ await Assert.ThrowsAnyAsync(async () => await genera public async Task FrozenSdkPathsSelectIndependentHeadersWithoutChangingTheProcessEnvironment() { string variable = "INNO_BINDING_SDK_" + Guid.NewGuid().ToString("N"); - var component = CreateSdkComponent(); + NativeComponentDescriptor component = CreateSdkComponent(); string firstSdk = CreateSdk("sdk-first", "int"); string secondSdk = CreateSdk("sdk-second", "long long"); string? original = Environment.GetEnvironmentVariable(variable); - var generator = BindingTestProfiles.Generator(); - var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var request = new NativeBindingGenerationRequest( + [component], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); - using var first = await generator.GenerateAsync(SdkContext(variable, firstSdk), request, CancellationToken.None); - using var second = await generator.GenerateAsync(SdkContext(variable, secondSdk), request, CancellationToken.None); + using NativeBindingGenerationResult first = await generator.GenerateAsync( + SdkContext(variable, firstSdk), + request, + CancellationToken.None + ); + using NativeBindingGenerationResult second = await generator.GenerateAsync( + SdkContext(variable, secondSdk), + request, + CancellationToken.None + ); Assert.NotEqual(first[component.nativeProject].fingerprint, second[component.nativeProject].fingerprint); Assert.Contains("int Sample(int value)", File.ReadAllText(first[component.nativeProject].bindingsPath)); @@ -183,14 +219,22 @@ public async Task FrozenSdkPathsSelectIndependentHeadersWithoutChangingTheProces public async Task MissingSelectedSdkFailsBeforeCreatingCandidatesAndPreservesPublishedBindings() { string variable = "INNO_BINDING_SDK_" + Guid.NewGuid().ToString("N"); - var component = CreateSdkComponent(); + NativeComponentDescriptor component = CreateSdkComponent(); string sdk = CreateSdk("sdk", "int"); - var generator = BindingTestProfiles.Generator(); - var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); - using var result = await generator.GenerateAsync(SdkContext(variable, sdk), request, CancellationToken.None); + NativeBindingGenerator generator = BindingTestProfiles.Generator(); + var request = new NativeBindingGenerationRequest( + [component], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); + using NativeBindingGenerationResult result = await generator.GenerateAsync( + SdkContext(variable, sdk), + request, + CancellationToken.None + ); string source = File.ReadAllText(result[component.nativeProject].bindingsPath); - var failure = await Assert.ThrowsAsync(async () => await generator.GenerateAsync( + InvalidDataException failure = await Assert.ThrowsAsync(async () => await generator.GenerateAsync( new NativeBuildContext(m_root, "release"), request, CancellationToken.None @@ -206,7 +250,7 @@ public async Task MissingSelectedSdkFailsBeforeCreatingCandidatesAndPreservesPub private NativeComponentDescriptor CreateSdkComponent() { - var component = CreateComponent("sdk-component"); + NativeComponentDescriptor component = CreateComponent("sdk-component"); File.WriteAllText(Path.Combine(m_root, "Source", "shared.h"), "#include \nOWNED_SDK_TYPE sample(OWNED_SDK_TYPE value);"); return component; } diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs index aba6a695b..a8233b80c 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingGenerationProcessTests.cs @@ -22,7 +22,9 @@ public sealed class BindingGenerationProcessTests /// /// Keeps unchanged mapping identities stable across processes and rejects a real mapping change. /// - /// A task completing after all independent hosts have exited and their identities agree. + /// + /// A task completing after all independent hosts have exited and their identities agree. + /// [Fact] public async Task DictionaryMappingsRemainStableAcrossIndependentProcesses() { @@ -35,7 +37,11 @@ public async Task DictionaryMappingsRemainStableAcrossIndependentProcesses() "Fixture.csproj", bindingDefinition: "bindings.props" ); - var request = new NativeBindingGenerationRequest([component], "fixture", NativeBindingOutputMode.TargetArtifacts); + var request = new NativeBindingGenerationRequest( + [component], + "fixture", + NativeBindingOutputMode.TargetArtifacts + ); string identity = await BindingTestProfiles.Generator().ComputeInputFingerprintAsync( new NativeBuildContext(inherited, "release"), request, @@ -60,7 +66,7 @@ public async Task DictionaryMappingsRemainStableAcrossIndependentProcesses() Path.Combine(root, "Native", "fixture.h"), Enumerable.Range(0, 64).Select(static index => $"int sample_{index}(int value);") ); - var names = Enumerable.Range(0, 64) + Dictionary names = Enumerable.Range(0, 64) .ToDictionary(static index => $"sample_{index}", static index => $"Sample{index}", StringComparer.Ordinal); WriteConfiguration(root, names); string first = await RunHost(root, "first"); diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs index b700d6e1e..ce4f4540e 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs @@ -39,9 +39,9 @@ public async Task PublicationWithoutItsCompiledSelectionFailsBeforePreparingTheT Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" ); - using CancellationTokenSource timeout = new(TimeSpan.FromMinutes(3)); - using StringWriter output = new(); - using StringWriter error = new(); + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + using var output = new StringWriter(); + using var error = new StringWriter(); Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( sdk, ["msbuild", project, "-t:PublishProductNativeDeployment", "-nodeReuse:false", "-v:minimal"], @@ -133,9 +133,9 @@ async Task Execute(string command) Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" ); - using CancellationTokenSource timeout = new(TimeSpan.FromMinutes(3)); - using StringWriter output = new(); - using StringWriter error = new(); + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + using var output = new StringWriter(); + using var error = new StringWriter(); Exception? failure = await Record.ExceptionAsync(() => ToolchainEnvironment.RunAsync( sdk, [command, project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "-v:minimal"], diff --git a/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs b/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs index 1a305592e..ab45ffaae 100644 --- a/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs @@ -6,6 +6,8 @@ using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; +using BGCS.Configuration; +using BGCS.Core; using Xunit; using Inno.Build.Bindings; using Inno.Build.Toolchains; @@ -32,7 +34,12 @@ public async Task DependencyPackageRetainsBindingsWithoutConsumerGeneration() await Git(m_root, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-m", "Binding source"); string consumer = Path.Combine(m_root, "consumer"); await Git(m_root, "clone", "--no-hardlinks", m_root, consumer); - var component = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); + var component = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); string sdk = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? ToolchainEnvironment.ResolveExecutable("dotnet"); var tools = new NativeToolchainSelection( "fixture-target", @@ -44,7 +51,7 @@ public async Task DependencyPackageRetainsBindingsWithoutConsumerGeneration() new NativeLinkPlan(sharedLibraryExtension: ".data"), false ); - var context = new NativeBuildContext(m_root, "release").WithToolchain(tools) + NativeBuildContext context = new NativeBuildContext(m_root, "release").WithToolchain(tools) .WithBindingGenerator(BindingTestProfiles.Generator("fixture-target")); int productions = 0; NativeBuildRecipe Recipe(NativeBuildContext current) @@ -210,7 +217,10 @@ public void IdenticalSelectionPreservesTheImportTimestampAndChangedSelectionRepl { ["Inno.Native.Text.csproj"] = SelectedGeneration("selected") }; - var linkage = new Dictionary { ["Inno.Native.Text.csproj"] = NativeLibraryKind.Shared }; + var linkage = new Dictionary + { + ["Inno.Native.Text.csproj"] = NativeLibraryKind.Shared + }; NativeBindingGenerationDescriptor.WriteSelection(output, generations, linkage); DateTime originalTime = DateTime.UtcNow.AddMinutes(-1); File.SetLastWriteTimeUtc(output, originalTime); @@ -233,7 +243,10 @@ public void PublicationRejectsChangedOrIncompleteManagedSelection() { ["Inno.Native.Text.csproj"] = SelectedGeneration("original") }; - var linkage = new Dictionary { ["Inno.Native.Text.csproj"] = NativeLibraryKind.Shared }; + var linkage = new Dictionary + { + ["Inno.Native.Text.csproj"] = NativeLibraryKind.Shared + }; NativeBindingGenerationDescriptor.WriteSelection(output, original, linkage); NativeBindingGenerationDescriptor.ValidateSelection(output, original, linkage); Assert.Throws(() => NativeBindingGenerationDescriptor.ValidateSelection( @@ -305,18 +318,27 @@ public void UnsafeManagedProjectNameIsRejectedBeforeCreatingSelectionOutput() } [Theory] - [InlineData(BGCS.Core.BindingImportMode.LibraryImport)] - [InlineData(BGCS.Core.BindingImportMode.DllImport)] + [InlineData(BindingImportMode.LibraryImport)] + [InlineData(BindingImportMode.DllImport)] [Trait("ExternalDependency", "BGCS")] - public async Task PlatformImportChoiceChangesOfficialGenerationAndFrozenSelection(BGCS.Core.BindingImportMode importMode) + public async Task PlatformImportChoiceChangesOfficialGenerationAndFrozenSelection(BindingImportMode importMode) { CreateConfig("unsigned long long sample(void* value);"); NativeBindingGenerationDescriptor provider = await GenerateAsync(); - var component = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var request = new NativeBindingGenerationRequest([component], "fixture-target", NativeBindingOutputMode.TargetArtifacts); + var component = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + var request = new NativeBindingGenerationRequest( + [component], + "fixture-target", + NativeBindingOutputMode.TargetArtifacts + ); var profile = new NativeBindingProfile( "fixture-target", - new BGCS.Configuration.TargetConfiguration { id = "windows-x64-msvc" }, + new TargetConfiguration { id = "windows-x64-msvc" }, importMode: importMode ); using NativeBindingGenerationResult result = await new NativeBindingGenerator(profile).GenerateAsync( @@ -370,8 +392,17 @@ public async Task SourceChangesSelectIndependentGenerationsAndTamperingIsRepaire public async Task UnselectedPlatformDoesNotInvalidateTheSelectedGeneration() { string config = CreateConfig("int sample(int value);"); - var owner = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var request = new NativeBindingGenerationRequest([owner], "fixture-target", NativeBindingOutputMode.TargetArtifacts); + var owner = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + var request = new NativeBindingGenerationRequest( + [owner], + "fixture-target", + NativeBindingOutputMode.TargetArtifacts + ); NativeBindingGenerationDescriptor first = await GenerateAsync(); string definitionPath = Path.Combine(m_root, "bindings.props"); XDocument definition = XDocument.Load(definitionPath); @@ -543,10 +574,17 @@ private async Task GenerateAsync( string? expected = null, CancellationToken cancellation = default ) { - var owner = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var fingerprints = expected is null ? null : new Dictionary { [owner.nativeProject] = expected }; + var owner = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + Dictionary? fingerprints = expected is null + ? null + : new Dictionary { [owner.nativeProject] = expected }; var request = new NativeBindingGenerationRequest([owner], "fixture-target", mode, checkOnly, fingerprints); - using var result = await BindingTestProfiles.Generator("fixture-target").GenerateAsync( + using NativeBindingGenerationResult result = await BindingTestProfiles.Generator("fixture-target").GenerateAsync( new NativeBuildContext(m_root, "release"), request, cancellation @@ -555,8 +593,7 @@ private async Task GenerateAsync( } private void WriteDefinition() - { - new XDocument( + => new XDocument( new XElement( "Project", new XElement( @@ -567,11 +604,9 @@ private void WriteDefinition() ) ) .Save(Path.Combine(m_root, "bindings.props")); - } private static void WriteCppConfig(string path) - { - File.WriteAllText( + => File.WriteAllText( path, JsonSerializer.Serialize(new { @@ -582,5 +617,4 @@ private static void WriteCppConfig(string path) output = new { root = "Generated", layout = "singleFile" } }) ); - } } diff --git a/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs b/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs index 1c82162d7..0761ac6df 100644 --- a/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/NativeBindingProfileTests.cs @@ -24,7 +24,9 @@ public sealed class NativeBindingProfileTests : IDisposable /// /// Requires an explicit Browser extension and publishes aggregate pointer adapters with remappable inputs. /// - /// The completion of generation, verification and a repeated cache hit. + /// + /// The completion of generation, verification and a repeated cache hit. + /// [Fact] public async Task BrowserAggregateBridgeRequiresExplicitExtensionAndReusesVerifiedGeneration() { @@ -46,8 +48,17 @@ public async Task BrowserAggregateBridgeRequiresExplicitExtensionAndReusesVerifi "api":{"namespace":"Fixture.Native","name":"Api"}, "output":{"layout":"singleFile","singleFileName":"Bindings.cs"}} """); - var component = new NativeComponentDescriptor("fixture", "Fixture.csproj", "Fixture.csproj", bindingDefinition: "bindings.props"); - var request = new NativeBindingGenerationRequest([component], "fixture-target", NativeBindingOutputMode.TargetArtifacts); + var component = new NativeComponentDescriptor( + "fixture", + "Fixture.csproj", + "Fixture.csproj", + bindingDefinition: "bindings.props" + ); + var request = new NativeBindingGenerationRequest( + [component], + "fixture-target", + NativeBindingOutputMode.TargetArtifacts + ); var target = new TargetConfiguration { id = "emscripten-wasm32-emscripten" }; var runtime = new ManagedRuntimeId("dotnet.mono-wasm"); var missing = new NativeBindingGenerator( @@ -72,7 +83,7 @@ await Assert.ThrowsAsync(async () => importMode: BindingImportMode.LibraryImport ) ); - NativeBuildContext cold = new(m_root, "release"); + var cold = new NativeBuildContext(m_root, "release"); using NativeBindingGenerationResult first = await generator.GenerateAsync(cold, request, CancellationToken.None); NativeBindingGenerationDescriptor generation = first[component.nativeProject]; NativeBindingCompilation compilation = NativeBindingCompilation.Load(generation.nativeDirectory); @@ -107,7 +118,7 @@ await Assert.ThrowsAsync(async () => Assert.Contains("FunctionTable", importFailure.Message, StringComparison.Ordinal); Assert.Equal(published, File.ReadAllBytes(generation.bindingsPath)); - NativeBuildContext hot = new(m_root, "release"); + var hot = new NativeBuildContext(m_root, "release"); using NativeBindingGenerationResult repeated = await generator.GenerateAsync(hot, request, CancellationToken.None); Assert.Equal(generation.fingerprint, repeated[component.nativeProject].fingerprint); Assert.Equal(0, hot.statistics.bindingGenerations); diff --git a/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs b/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs index e268adabd..b01d60ac7 100644 --- a/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs +++ b/tests/build/Inno.Build.Cli.Tests/DevelopmentEntryCommandTests.cs @@ -17,10 +17,10 @@ public sealed class DevelopmentEntryCommandTests [InlineData("support-pack", "--clean")] [InlineData("editor", "--dry-run")] [InlineData("editor", "--unrecognized", "value")] - public async Task InvalidCommandsFailBeforeSdkDiscoveryOrCleanup(params string[] arguments) - { - Assert.Equal(1, await BuildApplication.Run(arguments, CancellationToken.None)); - } + public async Task InvalidCommandsFailBeforeSdkDiscoveryOrCleanup(params string[] arguments) => Assert.Equal( + 1, + await BuildApplication.Run(arguments, CancellationToken.None) + ); [Fact] public async Task CancellationReturnsBeforeCreatingBuildState() diff --git a/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs b/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs index 4af7e2102..a0c9e8cec 100644 --- a/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/FileProductPublicationTests.cs @@ -57,8 +57,8 @@ string nativeFileName IToolchainWorkspaceProvider workspaces = OperatingSystem.IsWindows() ? new WindowsToolchainWorkspaceProvider() : new PhysicalToolchainWorkspaceProvider(); - CoreClrDeploymentCompiler compiler = new(host, [RuntimeInformation.RuntimeIdentifier], workspaces); - using CancellationTokenSource timeout = new(TimeSpan.FromMinutes(3)); + var compiler = new CoreClrDeploymentCompiler(host, [RuntimeInformation.RuntimeIdentifier], workspaces); + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3)); DotNetSdkDescriptor selectedSdk = await DotNetSdkResolver.ResolveAsync(host, project, timeout.Token); XDocument definition = XDocument.Load(project); definition.Root!.Add( diff --git a/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs b/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs index 2e42ffc48..81f7471e1 100644 --- a/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/GeneratorRestoreScopeTests.cs @@ -28,7 +28,7 @@ public async Task CompilerToolsKeepTheirSdkOutputOwnerWhenGivenAnExplicitRuntime { string root = TestRepository.GetRoot(typeof(GeneratorRestoreScopeTests).Assembly); string project = Path.Combine(root, relative); - using Process process = new() + using var process = new Process() { StartInfo = new ProcessStartInfo("dotnet") { diff --git a/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs b/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs index 88590924c..71e947bf8 100644 --- a/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/ManagedBuildInputSnapshotTests.cs @@ -1,6 +1,9 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; @@ -263,7 +266,7 @@ await ToolchainEnvironment.RunAsync( context, sdk, project, - new System.Collections.Generic.Dictionary { ["Configuration"] = "Release" } + new Dictionary { ["Configuration"] = "Release" } ); using ManagedBuildExecution execution = await snapshot.CreateExecutionAsync(); Assert.Equal("owned vendor tool", File.ReadAllText(Path.Combine(execution.engineRoot, "Vendor", "bin", "tool.dat"))); @@ -297,10 +300,10 @@ await ToolchainEnvironment.RunAsync( await execution.VerifyAsync(); string output = Path.Combine(Path.GetDirectoryName(execution.project)!, "bin", "Release", "net10.0", "App.dll"); using FileStream stream = File.OpenRead(output); - using var image = new System.Reflection.PortableExecutable.PEReader(stream); - System.Reflection.Metadata.MetadataReader metadata = System.Reflection.Metadata.PEReaderExtensions.GetMetadataReader(image); - string[] names = System.Linq.Enumerable.ToArray( - System.Linq.Enumerable.Select( + using var image = new PEReader(stream); + MetadataReader metadata = PEReaderExtensions.GetMetadataReader(image); + string[] names = Enumerable.ToArray( + Enumerable.Select( metadata.TypeDefinitions, handle => metadata.GetString(metadata.GetTypeDefinition(handle).Name) ) diff --git a/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs b/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs index c6b09d75c..381b2af22 100644 --- a/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NativeBindingCompilationTests.cs @@ -3,9 +3,11 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Runtime.InteropServices; using System.Text.Json; using System.Threading.Tasks; using System.Xml.Linq; +using BGCS.Runtime; using Xunit; using Inno.Build; using Inno.Build.Distribution.Standard; @@ -104,7 +106,7 @@ public async Task TargetCompilationReplacesHostSourceAndRejectsAMissingSelection new XElement( "Reference", new XAttribute("Include", "BGCS.Runtime"), - new XElement("HintPath", typeof(BGCS.Runtime.NativeModuleSession).Assembly.Location) + new XElement("HintPath", typeof(NativeModuleSession).Assembly.Location) ) ), new XElement( @@ -231,8 +233,11 @@ string selected ) { string middle = Path.Combine(root, "Consumers", "Middle", "Middle.csproj"); string host = Path.Combine(root, "Consumers", "Host", "Host.csproj"); - foreach (var entry in new[] { (path: middle, reference: nativeProject), (path: host, reference: middle) }) + foreach ((string path, string reference) entry in new[] { + (path: middle, reference: nativeProject), + (path: host, reference: middle) + }) { Directory.CreateDirectory(Path.GetDirectoryName(entry.path)!); var document = new XElement( "Project", @@ -282,7 +287,7 @@ string selected string[] arguments ) { string host = Path.Combine( - Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" ); var start = new ProcessStartInfo(host) diff --git a/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs b/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs index 820c6a02c..3e1c59ec2 100644 --- a/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NativeBindingConfigurationTests.cs @@ -25,7 +25,9 @@ public sealed class NativeBindingConfigurationTests /// /// Materializes every configured component without invoking native generation or selecting a platform SDK. /// - /// The completion of configuration validation for the declared product closure. + /// + /// The completion of configuration validation for the declared product closure. + /// [Fact] [Trait("ExternalDependency", "BGCS")] public async Task EveryDeclaredComponentConfigurationCanBeReadByTheInstalledSdk() diff --git a/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs b/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs index 3267f3916..6d1248924 100644 --- a/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/NuGetLoadedIdentityTests.cs @@ -11,6 +11,7 @@ using System.Xml.Linq; using BGCS.Runtime; using Xunit; +using Xunit.Sdk; using Inno.Build.Toolchains; using Inno.Testing.Source; @@ -152,7 +153,7 @@ bool staleDefault string mismatch = Path.Combine(root, "mismatched", "BGCS.Runtime.dll"); Directory.CreateDirectory(Path.GetDirectoryName(mismatch)!); File.WriteAllBytes(mismatch, File.ReadAllBytes(runtime)); - await using (FileStream altered = new(mismatch, FileMode.Append, FileAccess.Write)) + await using (var altered = new FileStream(mismatch, FileMode.Append, FileAccess.Write)) { await altered.WriteAsync(new byte[] { 0x49, 0x4E, 0x4E, 0x4F }, cancellation.Token); } @@ -214,7 +215,7 @@ Assembly loaded Assembly different = context.LoadFromAssemblyPath(mismatch); Assert.Equal(loaded.GetName().FullName, different.GetName().FullName); Assert.Equal(loaded.ManifestModule.ModuleVersionId, different.ManifestModule.ModuleVersionId); - Assert.Throws(() => AssertLoadedContent(expected, different)); + Assert.Throws(() => AssertLoadedContent(expected, different)); return (new WeakReference(context), new WeakReference(different)); } finally diff --git a/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs b/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs index 1ff6d9d64..13a9ca1da 100644 --- a/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/OwnedRestoreTests.cs @@ -11,6 +11,8 @@ using Inno.Build.TaskHosting; using Inno.Core.IO; +using AsyncTask = System.Threading.Tasks.Task; + namespace Inno.Build.Integration.Tests; public sealed class OwnedRestoreTests : IDisposable @@ -28,7 +30,7 @@ public OwnedRestoreTests() public void Dispose() => Directory.Delete(m_root, recursive: true); [Fact] - public async System.Threading.Tasks.Task WritersYieldAndNeverEnterRestoreTogether() + public async AsyncTask WritersYieldAndNeverEnterRestoreTogether() { using var entered = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); @@ -39,9 +41,9 @@ public async System.Threading.Tasks.Task WritersYieldAndNeverEnterRestoreTogethe return true; }); var secondEngine = new RecordingEngine(static () => true); - Task first = System.Threading.Tasks.Task.Run(Create(firstEngine).Execute); + Task first = AsyncTask.Run(Create(firstEngine).Execute); Assert.True(entered.Wait(TimeSpan.FromSeconds(10))); - Task second = System.Threading.Tasks.Task.Run(Create(secondEngine).Execute); + Task second = AsyncTask.Run(Create(secondEngine).Execute); try { Assert.True(SpinWait.SpinUntil(() => secondEngine.yielded, TimeSpan.FromSeconds(10))); @@ -57,13 +59,13 @@ public async System.Threading.Tasks.Task WritersYieldAndNeverEnterRestoreTogethe } [Fact] - public async System.Threading.Tasks.Task CancellationDoesNotEnterRestoreOrRemoveAnotherOwnersLock() + public async AsyncTask CancellationDoesNotEnterRestoreOrRemoveAnotherOwnersLock() { var engine = new RecordingEngine(static () => true); RestoreOwnedProjectTask canceled = Create(engine); using (FileLease lease = await FileLease.AcquireAsync(Path.Combine(m_root, "write.lock"), TimeSpan.FromSeconds(5))) { - Task pending = System.Threading.Tasks.Task.Run(canceled.Execute); + Task pending = AsyncTask.Run(canceled.Execute); Assert.True(SpinWait.SpinUntil(() => engine.yielded, TimeSpan.FromSeconds(10))); canceled.Cancel(); Assert.False(await pending); diff --git a/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs b/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs index 11bedf681..a5f5275cb 100644 --- a/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs @@ -43,7 +43,7 @@ bool explicitlyDisablePreparation "--artifacts-path", artifacts, "-p:InnoTaskArtifacts=" + tasks, - .. (explicitlyDisablePreparation ? new[] { "-p:InnoPrepareProductNative=false" } : Array.Empty()), + .. (explicitlyDisablePreparation ? ["-p:InnoPrepareProductNative=false"] : Array.Empty()), "--disable-build-servers", "-m:1", "-nr:false" diff --git a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs index c0e770a45..bf484c9dc 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs @@ -24,9 +24,9 @@ private TaskHostPublicationProcess( Task running, CancellationTokenSource budget ) { - loadDirectory = load; - publisherDirectory = publisher; - readyFile = ready; + this.loadDirectory = load; + this.publisherDirectory = publisher; + this.readyFile = ready; m_release = release; m_running = running; m_budget = budget; @@ -152,7 +152,7 @@ internal static async Task StartAsync(string root) } } - /// + /// public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref m_disposed, 1) != 0) diff --git a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs index f3fd60358..d81ad2bd8 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationTests.cs @@ -11,6 +11,8 @@ using Inno.Build.TaskHosting; using Inno.Build.Toolchains; +using AsyncTask = System.Threading.Tasks.Task; + namespace Inno.Build.Integration.Tests; public sealed class TaskHostPublicationTests : IDisposable @@ -41,14 +43,11 @@ public void RepeatedPublicationReusesOneVerifiedRuntimeWithoutChangingItsFiles() } [Fact] - public async System.Threading.Tasks.Task ConcurrentReadersShareTheCompleteContentIdentity() + public async AsyncTask ConcurrentReadersShareTheCompleteContentIdentity() { PublishTaskHostTask first = CreateTask(); PublishTaskHostTask second = CreateTask(); - bool[] results = await System.Threading.Tasks.Task.WhenAll( - System.Threading.Tasks.Task.Run(first.Execute), - System.Threading.Tasks.Task.Run(second.Execute) - ); + bool[] results = await AsyncTask.WhenAll(AsyncTask.Run(first.Execute), AsyncTask.Run(second.Execute)); Assert.All(results, result => Assert.True(result)); Assert.Equal(first.PublishedAssembly, second.PublishedAssembly); Assert.Single(Directory.GetDirectories(Path.Combine(m_root, "hosts"))); @@ -93,7 +92,7 @@ public void CanceledBootstrapNeverCreatesACacheOrReader() } [Fact] - public async System.Threading.Tasks.Task RetirementKeepsLiveReadersAndReleasesDeadReadersAndTheirUnreferencedRuntime() + public async AsyncTask RetirementKeepsLiveReadersAndReleasesDeadReadersAndTheirUnreferencedRuntime() { TaskHostPublicationProcess old = await TaskHostPublicationProcess.StartAsync(m_root); await using TaskHostPublicationProcess live = await TaskHostPublicationProcess.StartAsync(m_root); @@ -131,7 +130,7 @@ public void InvalidInputIdentityFailsBeforeCreatingOutput(string relative) } [Fact] - public async System.Threading.Tasks.Task BootstrapRetirementPreservesCurrentProcessAndRemovesOnlyConfirmedDeadOwners() + public async AsyncTask BootstrapRetirementPreservesCurrentProcessAndRemovesOnlyConfirmedDeadOwners() { await using TaskHostPublicationProcess previous = await TaskHostPublicationProcess.StartAsync(m_root); await previous.DisposeAsync(); @@ -148,7 +147,7 @@ public async System.Threading.Tasks.Task BootstrapRetirementPreservesCurrentProc private PublishTaskHostTask CreateTask() { string source = Path.Combine(m_root, "input", "Inno.Build.Tasks.dll"); - TaskItem file = new(source); + var file = new TaskItem(source); file.SetMetadata("RelativePath", "Inno.Build.Tasks.dll"); file.SetMetadata("FileHash", Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(source)))); return new PublishTaskHostTask @@ -160,7 +159,7 @@ private PublishTaskHostTask CreateTask() }; } - private async System.Threading.Tasks.Task MaintainAsync() + private async AsyncTask MaintainAsync() { BuildCacheOwnerDescriptor[] owners = [ diff --git a/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs index 75fd2393f..d2eb81ec4 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs @@ -66,9 +66,9 @@ public async Task ProjectGraphSharesCompilationButKeepsPrivateLoadsAndFreshBuild + "" + references + "" ); } - var first = await Build(root, configuration); + (string output, string binlog) first = await Build(root, configuration); string firstOwner = Validate(first.output, first.binlog); - var second = await Build(root, configuration); + (string output, string binlog) second = await Build(root, configuration); string secondOwner = Validate(second.output, second.binlog); Assert.NotEqual(firstOwner, secondOwner); } diff --git a/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs index 5c89598e4..8392532a2 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskRegistrationBuildTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Security; using System.Text.Json; @@ -166,7 +167,7 @@ public void Shutdown() { } """); string dotnet = ToolchainEnvironment.ResolveExecutable("dotnet"); using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(10)); - var environment = DotNetSdkEnvironment.Create(dotnet); + IReadOnlyDictionary environment = DotNetSdkEnvironment.Create(dotnet); await ToolchainEnvironment.RunAsync( dotnet, ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-p:UseSharedCompilation=false"], diff --git a/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs index 9a112c1fc..0104dcc1b 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskRestoreEvaluationTests.cs @@ -97,7 +97,7 @@ public async Task RestoreDoesNotReusePackageContentItemsDuringCompilation(bool o new XAttribute("LoadDirectory", Path.Combine(root, "loads", "reader", "Debug")), new XAttribute("Targets", "Restore;PublishRuntime") ); - XElement run = new("Target", new XAttribute("Name", "Run"), operation); + var run = new XElement("Target", new XAttribute("Name", "Run"), operation); if (ownedRestore) { run.Add( diff --git a/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs index 24b7f0da5..9afb34825 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskRuntimeBuildTests.cs @@ -14,7 +14,7 @@ using Inno.Build.Toolchains; using Inno.Core.IO; -using TaskItem = Microsoft.Build.Utilities.TaskItem; +using BuildTaskItem = Microsoft.Build.Utilities.TaskItem; namespace Inno.Build.Integration.Tests; @@ -106,15 +106,15 @@ public async Task CompletedPreparationProtectsWorkspaceDuringMaintenanceAndCache [Fact] public async Task SharedBuildsYieldWhileWaitingAndSerializeWrites() { - using ManualResetEventSlim entered = new(); - using ManualResetEventSlim release = new(); - RecordingEngine firstEngine = new(() => + using var entered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var firstEngine = new RecordingEngine(() => { entered.Set(); Assert.True(release.Wait(TimeSpan.FromSeconds(10))); return true; }); - RecordingEngine secondEngine = new(() => true); + var secondEngine = new RecordingEngine(() => true); BuildTaskRuntimeTask first = CreateTask(firstEngine); BuildTaskRuntimeTask second = CreateTask(secondEngine); Task firstRun = Task.Factory.StartNew( @@ -155,7 +155,7 @@ public async Task SharedBuildsYieldWhileWaitingAndSerializeWrites() [Fact] public async Task CancellationReleasesWaitAndAllowsTheNextBuild() { - RecordingEngine engine = new(() => true); + var engine = new RecordingEngine(() => true); BuildTaskRuntimeTask canceled = CreateTask(engine); using (FileLease lease = await FileLease.AcquireAsync( Path.Combine(m_root, "bootstrap") + ".lock", @@ -212,7 +212,7 @@ public void ValidPublicationIsReusedAcrossBuildsAndRejectsSameLengthSameTimeSour { var engine = new RecordingEngine(static () => true); Assert.True(CreateTask(engine).Execute(), string.Join("\n", engine.errors)); - var reused = CreateTask(engine); + BuildTaskRuntimeTask reused = CreateTask(engine); Assert.True(reused.Execute(), string.Join("\n", engine.errors)); Assert.Equal(1, engine.builds); Assert.Contains(Path.Combine(m_root, "hosts"), reused.TargetOutputs[0].ItemSpec); @@ -231,10 +231,10 @@ public void ValidPublicationIsReusedAcrossBuildsAndRejectsSameLengthSameTimeSour public void CorruptedImmutableRuntimeIsRepairedBeforeReuse() { var engine = new RecordingEngine(static () => true); - var first = CreateTask(engine); + BuildTaskRuntimeTask first = CreateTask(engine); Assert.True(first.Execute(), string.Join("\n", engine.errors)); File.WriteAllText(first.TargetOutputs[0].ItemSpec, "corrupted"); - var second = CreateTask(engine); + BuildTaskRuntimeTask second = CreateTask(engine); Assert.True(second.Execute(), string.Join("\n", engine.errors)); Assert.Equal(2, engine.builds); Assert.Equal("prepared-runtime", File.ReadAllText(second.TargetOutputs[0].ItemSpec)); @@ -471,7 +471,7 @@ bool returnTargetOutputs } properties = globalProperties[0]; removed = removeGlobalProperties[0]; - TaskItem output = new(outputPath); + var output = new BuildTaskItem(outputPath); output.SetMetadata("FileHash", Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(outputPath)))); output.SetMetadata("RelativePath", "Inno.Build.Tasks.dll"); return new(!returnTargetOutputs || m_build(), [new Dictionary { [targets[^1]] = [output] }]); diff --git a/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs b/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs index b525c2ee8..311fd4acf 100644 --- a/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs +++ b/tests/build/Inno.Build.NativePerformance.Tests/ProductNativeCostTests.cs @@ -43,7 +43,9 @@ public async Task RealPresentationBuildUsesDeclaredCMakeAndFrozenWindowSource() .ToArray(); var plan = new ProductNativeBuildPlan("presentation-acceptance", steps); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(15)); - var context = new NativeBuildContext(root, "debug").WithBindingGenerator(m_distribution.ResolveBindingGenerator("windows-x64")); + NativeBuildContext context = new NativeBuildContext(root, "debug").WithBindingGenerator( + m_distribution.ResolveBindingGenerator("windows-x64") + ); NativeToolchainSelection sdk = await new WindowsX64NativeToolchainProvider("dotnet").ResolveAsync( context, m_host, @@ -69,7 +71,9 @@ public async Task RealHotProductBatchReadsLessThanSequentialPublicProducers(int using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(20)); async Task Context() { - var context = new NativeBuildContext(root, "debug").WithBindingGenerator(m_distribution.ResolveBindingGenerator("windows-x64")); + NativeBuildContext context = new NativeBuildContext(root, "debug").WithBindingGenerator( + m_distribution.ResolveBindingGenerator("windows-x64") + ); NativeToolchainSelection sdk = await new WindowsX64NativeToolchainProvider("dotnet").ResolveAsync( context, m_host, diff --git a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs index 07d42877a..fd2fd9ba8 100644 --- a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs +++ b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs @@ -149,7 +149,7 @@ public async Task ProductRestoreAcceptsLargeInheritedProperties(bool inheritSolu Directory.CreateDirectory(fixture); string project = Path.Combine(root, "platforms", "WindowsX64", "editor", "Inno.Editor.WindowsX64", "Inno.Editor.WindowsX64.csproj"); string driver = Path.Combine(fixture, "Restore.proj"); - string inheritedMetadata = new('R', 65536); + var inheritedMetadata = new string('R', 65_536); try { await File.WriteAllTextAsync(driver, $""" diff --git a/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs b/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs index f6be6f963..3b91dc7d6 100644 --- a/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs +++ b/tests/build/Inno.Build.Products.Tests/BuildCachePublisherTests.cs @@ -5,6 +5,7 @@ using Xunit; using Inno.Build.Distribution.Standard; using Inno.Build.Toolchains; +using Inno.Core.IO; namespace Inno.Build.Products.Tests; @@ -15,7 +16,10 @@ public sealed class BuildCachePublisherTests : IDisposable [Fact] public async Task StandardOwnersPreserveReadersAndIgnoreUnregisteredDirectories() { - var publisher = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); + var publisher = new BuildCachePublisher( + Path.Combine(m_root, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); string old = Create("native", "old"); string current = Create("native", "current"); string unrelated = Create("native", "unregistered"); @@ -44,8 +48,14 @@ public async Task StandardOwnersPreserveReadersAndIgnoreUnregisteredDirectories( [Fact] public async Task NativeCurrentRetainsItsExactOlderBindingGeneration() { - var bindings = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "bindings"), BuildCacheArtifactRole.ImmutableArtifact); - var native = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); + var bindings = new BuildCachePublisher( + Path.Combine(m_root, "artifacts", "bindings"), + BuildCacheArtifactRole.ImmutableArtifact + ); + var native = new BuildCachePublisher( + Path.Combine(m_root, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); string oldBinding = Create("bindings", "old"); string newBinding = Create("bindings", "current"); string oldNative = Create("native", "old"); @@ -75,9 +85,12 @@ public async Task NativeCurrentRetainsItsExactOlderBindingGeneration() [Fact] public async Task ActivePublisherPreventsRetirementDuringReadingHandoff() { - var publisher = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); + var publisher = new BuildCachePublisher( + Path.Combine(m_root, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); string artifact = Create("native", "candidate"); - using var activity = await publisher.AcquireUseAsync(); + using FileLease activity = await publisher.AcquireUseAsync(); publisher.Record(artifact, artifact + ".read.lock", [], null, null); BuildCacheCleanupResult result = await Plan().ExecuteAsync(); Assert.Empty(result.retired); @@ -117,7 +130,10 @@ public async Task ProcessOwnedLoadsProtectTheirExactHostDependency() [Fact] public async Task SizeAccountingIsRecordedByTheProducerWithoutServingAsIntegrityValidation() { - var publisher = new BuildCachePublisher(Path.Combine(m_root, "artifacts", "native"), BuildCacheArtifactRole.ImmutableArtifact); + var publisher = new BuildCachePublisher( + Path.Combine(m_root, "artifacts", "native"), + BuildCacheArtifactRole.ImmutableArtifact + ); string artifact = Create("native", "owned"); using (await publisher.AcquireUseAsync()) { diff --git a/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs b/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs index 12d1004d4..297f3d3f2 100644 --- a/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs +++ b/tests/build/Inno.Build.Products.Tests/GameBuildWorkflowTests.cs @@ -24,6 +24,7 @@ using Inno.Core.Identity; using Inno.Core.Serialization; using Inno.Core.Settings; +using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Plugins.Authoring; using Inno.Runtime; @@ -42,7 +43,7 @@ public async Task GameBuildPublishesOnlyVerifiedContentPacksAndRuntimeAssemblies { SaveStartupScene(); TypeCacheSnapshot runtimeTypes = m_engine.types.current; - BuildTargetId target = new(targetValue); + var target = new BuildTargetId(targetValue); using SerializationGeneration serialization = m_engine.serialization.CaptureGeneration(); BuildProfile profile = CreateProfile(target); profile.persistentDataPath = "studio/testgame"; @@ -106,7 +107,7 @@ public async Task GameBuildPublishesOnlyVerifiedContentPacksAndRuntimeAssemblies GameRuntimeModule runtimeModule = Assert.Single(manifest.modules); Assert.Equal("RuntimeScripts", runtimeModule.name); Assert.Equal("Inno.GameScripts", Assert.Single(runtimeModule.assemblies).name); - Assert.Equal(Inno.Extensibility.Modules.AssemblyDomain.InnoScripting, runtimeModule.domain); + Assert.Equal(AssemblyDomain.InnoScripting, runtimeModule.domain); string persistentRoot = Path.Combine(m_root, "Persistent", manifest.applicationId); RuntimeContentCatalog contentCatalog = serialization.Deserialize( diff --git a/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs b/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs index ca08ec97b..257d3110f 100644 --- a/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs +++ b/tests/build/Inno.Build.Products.Tests/NativeBuildContextTests.cs @@ -25,8 +25,8 @@ public void EquivalentCheckoutSpellingsHaveOneRecipeIdentity() NativeBuildContext Context(string path) => new NativeBuildContext(path, "release") .WithComponentOptions(owner, new(NativeLibraryKind.Shared)); - var plain = Context(m_root); - var separated = Context(m_root + Path.DirectorySeparatorChar); + NativeBuildContext plain = Context(m_root); + NativeBuildContext separated = Context(m_root + Path.DirectorySeparatorChar); Assert.Equal(plain.engineRoot, separated.engineRoot); NativeBuildRecipe first = NativeBuildRecipe.CreateForComponent(plain, owner, "fixture", "fixture-target", [], [], []); NativeBuildRecipe second = NativeBuildRecipe.CreateForComponent(separated, owner, "fixture", "fixture-target", [], [], []); diff --git a/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs b/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs index eb4a30455..04da4f4c7 100644 --- a/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs +++ b/tests/build/Inno.Build.Products.Tests/NativeComponentBuildOptionsTests.cs @@ -27,11 +27,11 @@ public void OptionsFreezeOrderedDefinitionsAndRejectAmbiguousSdkOverrides() foreach (string[] invalid in new[] { new[] { "-DCMAKE_TOOLCHAIN_FILE=other" }, - new[] { "-DINNO_COMPONENT_BRIDGE=other" }, - new[] { "-DINNO_LIBRARY_KIND=SHARED" }, - new[] { "-DA=one", "-DA:STRING=two" }, - new[] { "--build" }, - new[] { "-DA=one\0two" } + ["-DINNO_COMPONENT_BRIDGE=other"], + ["-DINNO_LIBRARY_KIND=SHARED"], + ["-DA=one", "-DA:STRING=two"], + ["--build"], + ["-DA=one\0two"] }) { Assert.Throws(() => new NativeComponentBuildOptions(NativeLibraryKind.Shared, invalid)); } @@ -60,7 +60,7 @@ public async Task RecipeOwnedDefinitionsCannotBeReplacedBeforeAnyToolStarts() new NativeLinkPlan(".dll"), false ); - var context = new NativeBuildContext(root, "debug").WithToolchain(selection).WithComponentOptions( + NativeBuildContext context = new NativeBuildContext(root, "debug").WithToolchain(selection).WithComponentOptions( owner, new NativeComponentBuildOptions(NativeLibraryKind.Shared, ["-DLINKAGE:BOOL=OFF"]) ); @@ -125,11 +125,15 @@ public void LinkageOrderedArgumentsAndConfigurationBytesAllChangeRecipeIdentity( File.WriteAllText(Path.Combine(root, "component/Toolchain.csproj"), ""); string config = Path.Combine(root, "component/Profile.cs"); File.WriteAllText(config, "one"); - var owner = new NativeComponentDescriptor("fixture", "component/Native.csproj", "component/Toolchain.csproj"); + var owner = new NativeComponentDescriptor( + "fixture", + "component/Native.csproj", + "component/Toolchain.csproj" + ); string Identity(NativeComponentBuildOptions options) { - var context = new NativeBuildContext(root, "debug").WithComponentOptions(owner, options); + NativeBuildContext context = new NativeBuildContext(root, "debug").WithComponentOptions(owner, options); NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent( context, owner, @@ -151,7 +155,11 @@ string Identity(NativeComponentBuildOptions options) return NativeBuildFingerprint.Create(recipe.declarations, recipe.inputs); } - var options = new NativeComponentBuildOptions(NativeLibraryKind.Shared, ["-DA=one", "-DB=two"], ["component/Profile.cs"]); + var options = new NativeComponentBuildOptions( + NativeLibraryKind.Shared, + ["-DA=one", "-DB=two"], + ["component/Profile.cs"] + ); string identity = Identity(options); Assert.NotEqual(identity, Identity(new(NativeLibraryKind.Static, options.cmakeArguments, options.inputPaths))); Assert.NotEqual(identity, Identity(new(NativeLibraryKind.Shared, ["-DB=two", "-DA=one"], options.inputPaths))); diff --git a/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs b/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs index 9da3cc33b..8055c18e5 100644 --- a/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs +++ b/tests/build/Inno.Build.Products.Tests/NativeRecipeClosureTests.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Xunit; +using Xunit.Sdk; using Inno.Build.Toolchains; using Inno.Build.Toolchains.MiniAudio; using Inno.Build.Toolchains.Sdl3; @@ -108,7 +110,7 @@ public void ProductSourceDeclarationUsesEachSelectedOwnerWithoutExecutingProduce context, completed, cancellation - ) => throw new Xunit.Sdk.XunitException("Input declaration must not compile."), + ) => throw new XunitException("Input declaration must not compile."), context => { declarations++; @@ -131,7 +133,7 @@ public void ProductSourceDeclarationUsesEachSelectedOwnerWithoutExecutingProduce var plan = new ProductNativeBuildPlan("fixture", steps); IReadOnlyList recipes = plan.CreateRecipes(Context()); Assert.Equal(2, declarations); - Assert.Equal(new[] { "first", "second" }, System.Linq.Enumerable.Select(recipes, static recipe => recipe.component)); + Assert.Equal(new[] { "first", "second" }, Enumerable.Select(recipes, static recipe => recipe.component)); Assert.False(Directory.Exists(Path.Combine(m_root, "artifacts"))); } @@ -147,7 +149,7 @@ public void StandaloneStepsRejectMissingDeclarationsAndForeignRecipes() context, completed, cancellation - ) => throw new Xunit.Sdk.XunitException("Validation must not compile."), + ) => throw new XunitException("Validation must not compile."), null, static ( relative, @@ -163,7 +165,7 @@ public void StandaloneStepsRejectMissingDeclarationsAndForeignRecipes() context, completed, cancellation - ) => throw new Xunit.Sdk.XunitException("Validation must not compile."), + ) => throw new XunitException("Validation must not compile."), context => new NativeBuildRecipe(m_owner, "foreign", context.RequireToolchain().targetId, [], []), static ( relative, @@ -296,7 +298,7 @@ string bridge Path.Combine(bridge, "compilation.json"), JsonSerializer.Serialize(new NativeBindingCompilation { - roots = [new("generated", "", true, true)], + roots = [new("generated", string.Empty, true, true)], files = [], includeDirectories = [], defines = [], @@ -305,7 +307,7 @@ string bridge cStandard = 0, requiredExports = [], staticExportSymbols = [], - staticExportAbi = "", + staticExportAbi = string.Empty, staticExportNames = [] }) ); diff --git a/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs b/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs index b691bffe2..fd8fc13d0 100644 --- a/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs +++ b/tests/build/Inno.Build.Products.Tests/PlatformBackendIntegrationTests.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using Xunit; using Inno.Build.Bindings; using Inno.Build.Composition; @@ -19,11 +20,11 @@ public void IntegrationsPreserveExactShaderAndNativeTargetIdentities() Assert.Equal("macos-arm64", MacOSArm64BgfxIntegration.nativeProfile.targetId); var context = new BuildCompositionContext( "explicit-sdk", - System.IO.Path.GetTempPath(), + Path.GetTempPath(), new BuildHostDescriptor("Windows", "x64"), new BuildTargetId("windows-x64") ); - var standard = StandardBuildDistribution.Create(context); + StandardBuildDistribution standard = StandardBuildDistribution.Create(context); Assert.Same(WindowsX64BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetId("windows-x64"))); Assert.Same(MacOSArm64BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetId("macos-arm64"))); Assert.Same(BrowserWasm32BgfxIntegration.shaderProfile, standard.ResolveShaderTarget(new BuildTargetId("browser-wasm"))); diff --git a/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs b/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs index 373c612a9..484f21cc7 100644 --- a/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs +++ b/tests/build/Inno.Build.Products.Tests/PlatformOwnershipContractTests.cs @@ -1,10 +1,12 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Xunit; +using Xunit.Sdk; using Inno.Build.Bindings; using Inno.Build.Composition; using Inno.Build.Distribution.Standard; @@ -27,8 +29,10 @@ public void HostedTargetsCoverTheDistributionAndDeclareOneProducerHost() using JsonDocument packages = JsonDocument.Parse(File.ReadAllBytes(Path.Combine(root, ".github", "native-targets.json"))); using JsonDocument hosts = JsonDocument.Parse(File.ReadAllBytes(Path.Combine(root, ".github", "validation-hosts.json"))); JsonElement[] targets = packages.RootElement.EnumerateArray().ToArray(); - var runners = hosts.RootElement.EnumerateArray().ToDictionary(host => host.GetProperty("runner").GetString()!); - var distribution = BuildTestProducts.Distribution(); + Dictionary runners = hosts.RootElement + .EnumerateArray() + .ToDictionary(host => host.GetProperty("runner").GetString()!); + BuildDistribution distribution = BuildTestProducts.Distribution(); Assert.Equal( distribution.availableTargets.Select(id => id.value), targets.Select(target => target.GetProperty("target").GetString()).Order(StringComparer.Ordinal) @@ -74,9 +78,9 @@ public async Task RealPlatformPreflightRejectsUnavailableSdkOrHostWithoutCreatin { string output = Path.Combine(Path.GetTempPath(), "InnoPlatformPreflight", Guid.NewGuid().ToString("N")); string sdk = Path.Combine(output, "unavailable-dotnet.exe"); - var host = unsupportedHost - ? new BuildHostDescriptor("MacOS", "arm64") - : new BuildHostDescriptor("Windows", "x64"); + BuildHostDescriptor host = unsupportedHost + ? new BuildHostDescriptor("MacOS", "arm64") + : new BuildHostDescriptor("Windows", "x64"); var source = new WindowsX64PlayerSupportPackSource( BuildTestProducts.Distribution().ResolveNativeProduct("windows-x64", "player"), host, @@ -280,8 +284,8 @@ string[] dependencies context, completed, cancellation - ) => throw new Xunit.Sdk.XunitException("Preflight must not execute a component producer."), - static context => throw new Xunit.Sdk.XunitException("Preflight must reject missing tools before source declaration."), + ) => throw new XunitException("Preflight must not execute a component producer."), + static context => throw new XunitException("Preflight must reject missing tools before source declaration."), static ( relative, target diff --git a/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs b/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs index c2865d475..9e09d8139 100644 --- a/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs +++ b/tests/build/Inno.Build.Products.Tests/ShaderBuildInputsTests.cs @@ -18,7 +18,10 @@ public sealed class ShaderBuildInputsTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoShaderInputs", Guid.NewGuid().ToString("N")); - public ShaderBuildInputsTests() => Directory.CreateDirectory(m_root); + public ShaderBuildInputsTests() + { + Directory.CreateDirectory(m_root); + } [Fact] public void LivePublicationIsNotAnAssetButPermanentImportSettingsAreBuildInputs() @@ -30,7 +33,7 @@ public void LivePublicationIsNotAnAssetButPermanentImportSettingsAreBuildInputs( ShaderBuildInputs baseline = ShaderBuildInputs.Capture(m_root); string fingerprint = baseline.fingerprint; string candidate = source + ".imeta.staging-" + Guid.NewGuid().ToString("N"); - using (FileStream publication = new(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + using (var publication = new FileStream(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { publication.Write("not yet published"u8); Assert.True(AssetSourcePolicy.defaultPolicy.IsIgnored(Path.GetFileName(candidate), false)); @@ -152,7 +155,7 @@ public async Task CompilationWorkspaceMetadataUsesTheExistingRegisteredRetiremen { directory = workspace.directory; Assert.True(Directory.Exists(directory)); - var registration = Assert.Single(BuildCacheOwnerCatalog.ReadOwners(m_root)); + BuildCacheOwnerDescriptor registration = Assert.Single(BuildCacheOwnerCatalog.ReadOwners(m_root)); Assert.Equal("shader-requests", registration.id); Assert.Equal(Path.GetDirectoryName(directory), registration.directory); } diff --git a/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs b/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs index 7d18c6015..4e3b17149 100644 --- a/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs +++ b/tests/build/Inno.Build.Products.Tests/ShaderToolSelectionTests.cs @@ -75,7 +75,9 @@ public void OfflineToolsExcludeCmakeWhileRuntimeBindingsKeepTheSelectedSdk() Assert.Equal(sdk.cmakeArguments, runtime.cmakeArguments); Assert.False(runtime.TryResolveExecutable("dotnet", out _)); string archive = Path.Combine(root, "bridge.lib"); - var linking = WindowsX64BgfxIntegration.nativeProfile.CreateBindingLinkSettings(archive); + (string reference, IReadOnlyList arguments) linking = WindowsX64BgfxIntegration.nativeProfile.CreateBindingLinkSettings( + archive + ); Assert.Equal(Path.Combine(root, "bridge"), linking.reference); Assert.Equal(["/WHOLEARCHIVE:\"" + archive + "\""], linking.arguments); } diff --git a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs index cf6318dc6..0cd3e9454 100644 --- a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs +++ b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs @@ -1,9 +1,12 @@ using System; using System.IO; using System.Linq; +using System.Security.Cryptography; +using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; +using Xunit.Sdk; using Inno.Build.SupportPacks; namespace Inno.Build.SupportPacks.Tests; @@ -292,7 +295,9 @@ public async Task WaitingWriterCanCancelWithoutEnteringPreparationOrDisturbingTh Task publishing = first.PublishAsync(m_root, output, S_TARGET, "unused").AsTask(); await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)); using var cancellation = new CancellationTokenSource(); - var second = new PlayerSupportPackPublisher([new TestSource(new InvalidOperationException("Preparation must not run."))]); + var second = new PlayerSupportPackPublisher( + [new TestSource(new InvalidOperationException("Preparation must not run."))] + ); Task waiting = second.PublishAsync(m_root, output, S_TARGET, "unused", cancellation.Token).AsTask(); try { @@ -311,7 +316,7 @@ public async Task WaitingWriterCanCancelWithoutEnteringPreparationOrDisturbingTh } private static string InputIdentity(string input) - => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(input))); + => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(input))); private sealed class PendingSource( TaskCompletionSource entered, @@ -323,9 +328,7 @@ TaskCompletionSource release public ValueTask CreatePlanAsync( PlayerSupportPackPlanningContext context, CancellationToken cancellationToken - ) { - return ValueTask.FromResult(new PendingPlan(entered, release)); - } + ) => ValueTask.FromResult(new PendingPlan(entered, release)); private sealed class PendingPlan( TaskCompletionSource entered, @@ -375,7 +378,7 @@ private sealed class ForeignPlan(BuildTargetId? target = null) : PlayerSupportPa public override ValueTask PrepareAsync( string stagingDirectory, CancellationToken cancellationToken - ) => throw new Xunit.Sdk.XunitException("An unaccepted plan must never execute."); + ) => throw new XunitException("An unaccepted plan must never execute."); } private sealed class TestSource( diff --git a/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs index 3aea40115..0bd3f417d 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BackendPrebuiltArchiveTests.cs @@ -21,7 +21,10 @@ public sealed class BackendPrebuiltArchiveTests : IDisposable private string Inventory => Path.Combine(m_root, "inventory.json"); private string Archive => Path.Combine(m_root, "platform.zip"); - public BackendPrebuiltArchiveTests() => Directory.CreateDirectory(m_root); + public BackendPrebuiltArchiveTests() + { + Directory.CreateDirectory(m_root); + } [Fact] public async Task RepackingOneHundredRevisionsIncludesOnlyTheSelectedCurrentFiles() diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs index 84e353327..48cf7f413 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheInventoryProgressTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json.Nodes; @@ -38,7 +39,7 @@ public async Task ANewWriterInvalidatesItsMeasurementWithoutDiscardingOtherShard await PrepareAsync("second", "second payload"); await MaintainAsync(); string[] checkpoints = Directory.GetFiles(Path.Combine(m_root, "artifacts", "cache-owners", "inventory"), "*.inventory"); - var before = checkpoints.ToDictionary(static path => path, File.ReadAllText); + Dictionary before = checkpoints.ToDictionary(static path => path, File.ReadAllText); await PrepareAsync("first", "a longer changed payload"); await MaintainAsync(); Assert.Single(checkpoints.Where(path => before[path] != File.ReadAllText(path))); @@ -142,14 +143,14 @@ await Assert.ThrowsAnyAsync(() => Task.Run(() => completed.Length < C_COUNT, "The first checkpoint must interrupt discovery before the complete protection graph exists." ); - var snapshots = completed.ToDictionary( + Dictionary snapshots = completed.ToDictionary( static path => path, static path => (File.ReadAllText(path), File.GetLastWriteTimeUtc(path)) ); Assert.Equal(C_COUNT, Directory.GetDirectories(Path.Combine(m_root, "cache")).Length); await MaintainAsync(); Assert.Equal(C_COUNT, Directory.GetFiles(directory, "*.inventory").Length); - foreach (var snapshot in snapshots) + foreach (KeyValuePair snapshot in snapshots) { Assert.Equal(snapshot.Value.Item1, File.ReadAllText(snapshot.Key)); Assert.Equal(snapshot.Value.Item2, File.GetLastWriteTimeUtc(snapshot.Key)); @@ -176,9 +177,9 @@ string content private Task MaintainAsync( bool dryRun = false, bool retireAll = false - ) { + ) => // Full inventory and retirement assertions are foreground work, not a five-second automatic maintenance slice. - return BuildMaintenanceApplication.CleanAsync( + BuildMaintenanceApplication.CleanAsync( m_root, new(long.MaxValue, 0, TimeSpan.FromMinutes(2)), retireAll, @@ -186,7 +187,6 @@ private Task MaintainAsync( null, CancellationToken.None ); - } public void Dispose() { diff --git a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs index 1a9b0ee3a..9349dd383 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/BuildCacheRetirementTests.cs @@ -403,7 +403,7 @@ internal OwnedCache( string id ) { Directory.CreateDirectory(directory); - descriptor = new( + this.descriptor = new( id, directory, Path.Combine(directory, "owner.lock"), @@ -433,7 +433,7 @@ internal BuildCacheArtifactDescriptor Add( string directory = Path.Combine(descriptor.directory, name); Directory.CreateDirectory(Path.Combine(directory, "Outputs")); File.WriteAllBytes(Path.Combine(directory, "Outputs", "payload.bin"), new byte[bytes]); - var used = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(artifacts.Count); + DateTime used = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(artifacts.Count); var artifact = new BuildCacheArtifactDescriptor( directory, directory + ".read.lock", diff --git a/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs b/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs index d051d0443..aa69f44d4 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/DevelopmentBuildProvenanceTests.cs @@ -164,7 +164,7 @@ private static string ReadEmbeddedSource( string symbols, string fileName ) { - using var stream = File.OpenRead(symbols); + using FileStream stream = File.OpenRead(symbols); using MetadataReaderProvider provider = MetadataReaderProvider.FromPortablePdbStream(stream); MetadataReader reader = provider.GetMetadataReader(); DocumentHandle document = Assert.Single( @@ -190,7 +190,7 @@ string fileName private static string ReadSourceLink(string symbols) { - using var stream = File.OpenRead(symbols); + using FileStream stream = File.OpenRead(symbols); using MetadataReaderProvider provider = MetadataReaderProvider.FromPortablePdbStream(stream); MetadataReader reader = provider.GetMetadataReader(); CustomDebugInformation source = Assert.Single( diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs index 135f563af..e1bc355f4 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactIdentityTests.cs @@ -14,7 +14,7 @@ public void PythonBytecodeIsDerivedWhileSourceAndExplicitCompilerInputsRemainVer { string script = Write("sdk/compiler.py", "print('one')"); string compiler = Write("sdk/bin/clang", "compiler-one"); - var inputs = new[] + NativeBuildInput[] inputs = new[] { new NativeBuildInput("sdk", Path.GetDirectoryName(script)!), new NativeBuildInput("sdk/bin", Path.GetDirectoryName(compiler)!) @@ -41,7 +41,7 @@ public void MultipurposeRecipeOwnerIncludesOnlyItsDeclaredImplementationClosure( Path.GetRelativePath(m_root, project), Path.GetRelativePath(m_root, project) ); - var context = new NativeBuildContext(m_root, "release").WithComponentOptions(owner, new(NativeLibraryKind.Shared)); + NativeBuildContext context = new NativeBuildContext(m_root, "release").WithComponentOptions(owner, new(NativeLibraryKind.Shared)); NativeBuildRecipe recipe = NativeBuildRecipe.CreateForComponent( context, owner, diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs index 25f8ccc96..c4de55f38 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs @@ -1,7 +1,9 @@ using System; +using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -75,10 +77,10 @@ public async Task DamagedImportedContentsCannotBypassTheRealProducer(string dama { File.WriteAllText( Path.Combine(imported, "generation-manifest.json"), - System.Text.Json.JsonSerializer.Serialize(new + JsonSerializer.Serialize(new { fingerprint = damage == "wrong-identity" ? new string('0', 64) : source.fingerprint, - files = new System.Collections.Generic.Dictionary { ["../escape"] = new string('0', 64) } + files = new Dictionary { ["../escape"] = new string('0', 64) } }) ); } @@ -147,7 +149,7 @@ await NativeArtifactTransfer.ExportAsync( producer, archive, selectedArtifacts: exactSelection - ? new System.Collections.Generic.HashSet(StringComparer.Ordinal) { relative } + ? new HashSet(StringComparer.Ordinal) { relative } : null ) ); @@ -194,7 +196,7 @@ public async Task TransportRejectsIncompleteOrUnsafeArchivesBeforeInstallingAnyC } else if (damage == "link") { - output.ExternalAttributes = 0xa000 << 16; + output.ExternalAttributes = 0xA000 << 16; } else { diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs index 2ae83739b..60342e505 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeBindingCompilationTests.cs @@ -100,16 +100,21 @@ private static NativeBindingCompilation Create() string hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("verified"))); return new NativeBindingCompilation { - roots = [new("user", "source", false, true), new("nested", "source/nested", false, true), new("generated", "", true, true)], + roots = + [ + new("user", "source", false, true), + new("nested", "source/nested", false, true), + new("generated", string.Empty, true, true) + ], files = [new("user", "nested/api.hpp", 8, hash, false), new("nested", "api.hpp", 8, hash, true)], - includeDirectories = [new("user", "", false, false), new("nested", "", false, false)], + includeDirectories = [new("user", string.Empty, false, false), new("nested", string.Empty, false, false)], defines = ["first", "second"], compilerDefines = ["__COMPILER_FACT=1"], cxxStandard = 20, cStandard = 0, requiredExports = ["exported"], staticExportSymbols = [], - staticExportAbi = "", + staticExportAbi = string.Empty, staticExportNames = [] }; } diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs index d8b9fd93c..2cc31bd8d 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs @@ -24,7 +24,7 @@ public sealed class NativeDependencyManifestTests : IDisposable [Fact] public async Task ExactPublishedPayloadImportsWithoutAConsumerCompilerAndIsAdoptedByItsOwner() { - var fixture = await PrepareAsync(); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); using ProductNativeBuildResult result = await NativeDependencyManifest.AcquireAsync( fixture.consumer, fixture.selection, @@ -49,7 +49,7 @@ public async Task ExactPublishedPayloadImportsWithoutAConsumerCompilerAndIsAdopt [Fact] public async Task AggregateProductsRetainTheirExplicitLayoutWithoutPlatformBranches() { - var fixture = await PrepareAsync(aggregate: true); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(aggregate: true); using ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( fixture.consumer, fixture.selection, @@ -68,7 +68,7 @@ public async Task AggregateProductsRetainTheirExplicitLayoutWithoutPlatformBranc [InlineData(true)] public async Task SelectionIsReadOnlyAndRequiresNoArchive(bool aggregate) { - var fixture = await PrepareAsync(aggregate); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(aggregate); string downloads = Path.Combine(fixture.consumer, "artifacts", "fixture-target", "native"); foreach (string archive in Directory.GetFiles(downloads)) { @@ -92,7 +92,7 @@ public async Task SelectionIsReadOnlyAndRequiresNoArchive(bool aggregate) [InlineData("{\"assets\": [null], \"aggregates\": []}")] public async Task MalformedSelectionFailsBeforeTouchingArtifacts(string json) { - var fixture = await PrepareAsync(); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); File.WriteAllText(fixture.selection, json); await Assert.ThrowsAsync( () => NativeDependencyManifest.SelectAsync(fixture.consumer, fixture.selection, "fixture-target", "release", fixture.plan) @@ -110,7 +110,7 @@ await Assert.ThrowsAsync( [InlineData("added-recipe")] public async Task MissingOrChangedDependencyCannotInvokeTheProducer(string damage) { - var fixture = await PrepareAsync(); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); JsonObject selection = JsonNode.Parse(File.ReadAllText(fixture.selection))!.AsObject(); JsonObject asset = selection["assets"]![0]!.AsObject(); string archive = Path.Combine( @@ -163,7 +163,7 @@ public async Task MissingOrChangedDependencyCannotInvokeTheProducer(string damag [Fact] public async Task ModifiedInstalledArtifactFailsWithoutRepairOrProduction() { - var fixture = await PrepareAsync(); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); string output; using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( fixture.consumer, @@ -185,7 +185,7 @@ await Assert.ThrowsAsync( [Fact] public async Task ForeignDependencyClosureIsRejectedBeforeDownloadOrInstallation() { - var fixture = await PrepareAsync(); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); JsonObject selection = JsonNode.Parse(File.ReadAllText(fixture.selection))!.AsObject(); selection["assets"]![0]!["dependencies"] = new JsonObject { ["foreign"] = new string('a', 64) }; File.WriteAllText(fixture.selection, selection.ToJsonString()); @@ -210,7 +210,7 @@ await Assert.ThrowsAsync(() => NativeDependencyManifest.Ac [Fact] public async Task IndexFlagsCannotHideChangedConsumerSourceBytes() { - var fixture = await PrepareAsync(); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(); const string relative = "component/Source/source.h"; await Git(fixture.consumer, "update-index", "--assume-unchanged", relative); string source = Path.Combine(fixture.consumer, relative); @@ -232,7 +232,7 @@ await Assert.ThrowsAsync(() => NativeDependencyManifest.Se [Fact] public async Task PinnedSubmoduleNeedsNoConsumerCheckoutButMutableCheckoutCannotHideChanges() { - var fixture = await PrepareAsync(submodule: true); + (string consumer, string selection, ProductNativeBuildPlan plan) fixture = await PrepareAsync(submodule: true); using (ProductNativeBuildResult imported = await NativeDependencyManifest.AcquireAsync( fixture.consumer, fixture.selection, @@ -292,7 +292,7 @@ await Assert.ThrowsAsync(() => NativeDependencyManifest.Ac new NativeLinkPlan(staticLibraryExtension: ".data"), false ); - var context = new NativeBuildContext(producer, "release").WithToolchain(tools); + NativeBuildContext context = new NativeBuildContext(producer, "release").WithToolchain(tools); var plan = new ProductNativeBuildPlan("fixture", [new ProductNativeBuildStep( "fixture", m_component, @@ -322,7 +322,7 @@ await Assert.ThrowsAsync(() => NativeDependencyManifest.Ac products, Path.Combine(producer, "artifacts", "export") ); - var asset = JsonNode.Parse(File.ReadAllText(selection))![aggregate ? "aggregates" : "assets"]![0]!; + JsonNode asset = JsonNode.Parse(File.ReadAllText(selection))![aggregate ? "aggregates" : "assets"]![0]!; string downloads = Path.Combine(consumer, "artifacts", "fixture-target", "native"); Directory.CreateDirectory(downloads); File.Copy( diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs index 412659456..112dad13b 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeDeploymentIndexTests.cs @@ -10,7 +10,10 @@ public sealed class NativeDeploymentIndexTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoDeploymentIndex", Guid.NewGuid().ToString("N")); - public NativeDeploymentIndexTests() => Directory.CreateDirectory(m_root); + public NativeDeploymentIndexTests() + { + Directory.CreateDirectory(m_root); + } [Fact] public void UnknownSystemAndSuffixResolveThroughExplicitMappings() diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs index b94b122f5..df0eaba04 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeVerificationPhaseTests.cs @@ -72,17 +72,17 @@ public void FreshPhasesDetectSameLengthSameTimestampChangesAndReuseSharedReads() string file = Path.Combine(root, "input.txt"); File.WriteAllText(file, "first"); var context = new NativeBuildContext(root, "release"); - var inputs = new[] { new NativeBuildInput("first-owner", file), new NativeBuildInput("second-owner", file) }; + NativeBuildInput[] inputs = new[] { new NativeBuildInput("first-owner", file), new NativeBuildInput("second-owner", file) }; string initial = NativeBuildFingerprint.Create(context, ["recipe"], inputs, CancellationToken.None); Assert.Equal(1, context.statistics.hashedFiles); DateTime timestamp = File.GetLastWriteTimeUtc(file); File.WriteAllText(file, "other"); File.SetLastWriteTimeUtc(file, timestamp); - var verification = context.BeginInputVerification("after-lock"); + NativeBuildContext verification = context.BeginInputVerification("after-lock"); string verified = NativeBuildFingerprint.Create(verification, ["recipe"], inputs, CancellationToken.None); Assert.NotEqual(initial, verified); Assert.Equal(verified, NativeBuildFingerprint.Create(verification, ["recipe"], inputs, CancellationToken.None)); - var phase = context.statistics.phases.Single(phase => phase.phase == "after-lock"); + NativeBuildPhaseStatistics phase = context.statistics.phases.Single(phase => phase.phase == "after-lock"); Assert.Equal(1, phase.files); Assert.Equal(5, phase.bytes); Assert.Equal(3, phase.reusedReads); diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs index 291b8a2cc..e46bfe1a4 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeWorkspaceReuseTests.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Runtime.InteropServices; using System.Runtime.Versioning; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -145,9 +146,9 @@ bool externalBindings File.WriteAllText(managed, generation); File.WriteAllText( Path.Combine(bridge, "compilation.json"), - System.Text.Json.JsonSerializer.Serialize(new NativeBindingCompilation + JsonSerializer.Serialize(new NativeBindingCompilation { - roots = [new("generated", "", true, true)], + roots = [new("generated", string.Empty, true, true)], files = [], includeDirectories = [], defines = [], @@ -156,7 +157,7 @@ bool externalBindings cStandard = 0, requiredExports = [], staticExportSymbols = [], - staticExportAbi = "", + staticExportAbi = string.Empty, staticExportNames = [] }) ); diff --git a/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs index 3da827a55..b6b238745 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs @@ -34,8 +34,8 @@ public void Dispose() Directory.Delete(root, recursive: true); return; } - catch (IOException exception) when ((exception.HResult is unchecked((int)0x80070020) - or unchecked((int)0x80070021)) + catch (IOException exception) when ((exception.HResult is unchecked((int)0x8007_0020) + or unchecked((int)0x8007_0021)) && Stopwatch.GetElapsedTime(started).TotalMilliseconds < C_RETIREMENT_WINDOW_MILLISECONDS) { // Process termination does not promise that filesystem observers have released the directory. diff --git a/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs b/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs index 9b67f85a2..34acf2e3a 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/UnixFileLinksFactAttribute.cs @@ -9,7 +9,7 @@ public UnixFileLinksFactAttribute() { if (OperatingSystem.IsWindows()) { - Skip = "Unix compiler file-link semantics require a Unix filesystem; Windows directory-link rejection is tested separately."; + this.Skip = "Unix compiler file-link semantics require a Unix filesystem; Windows directory-link rejection is tested separately."; } } } diff --git a/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs b/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs index 058dd8440..ff9f23c9e 100644 --- a/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs +++ b/tests/build/fixtures/Inno.Testing.Build/BuildPipelineFixture.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using System.Threading.Tasks; @@ -17,6 +18,7 @@ using Inno.Build; using Inno.Build.MacOSArm64; using Inno.Build.Managed; +using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Build.WindowsX64; using Inno.Content; using Inno.Core.Execution; @@ -25,7 +27,10 @@ using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Extensibility.Types; +using Inno.Integration.MacOSArm64.Bgfx; +using Inno.Integration.WindowsX64.Bgfx; using Inno.Plugins.Authoring; +using Inno.Rendering; using Inno.Runtime; using Inno.Scene; using Inno.Scripting.Compiler; @@ -103,9 +108,9 @@ protected BuildPipelineFixture() new ScriptCompilerOptions { projectRootDirectory = m_projectRoot, - compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment( + compilationEnvironment = new SdkScriptCompilationEnvironment( Path.Combine( - Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" ), m_projectRoot @@ -165,29 +170,29 @@ protected BuildPipeline CreatePipeline( [ new GameBuildTargetBinding( new MacOSArm64GameBuildTarget(new MacOSArm64SupportPackValidator()), - new Inno.Build.Toolchains.Bgfx.Tools.BgfxGameContentCompiler( + new BgfxGameContentCompiler( m_assets, m_engine.serialization, m_engine.types, - Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxIntegration.shaderProfile, - [Inno.Rendering.GraphicsApi.Metal], - new Inno.Build.Toolchains.Bgfx.Tools.ToolRunner() + MacOSArm64BgfxIntegration.shaderProfile, + [GraphicsApi.Metal], + new ToolRunner() ) ), new GameBuildTargetBinding( new WindowsX64GameBuildTarget(new WindowsX64SupportPackValidator()), - new Inno.Build.Toolchains.Bgfx.Tools.BgfxGameContentCompiler( + new BgfxGameContentCompiler( m_assets, m_engine.serialization, m_engine.types, - Inno.Integration.WindowsX64.Bgfx.WindowsX64BgfxIntegration.shaderProfile, + WindowsX64BgfxIntegration.shaderProfile, [ - Inno.Rendering.GraphicsApi.Direct3D11, - Inno.Rendering.GraphicsApi.Direct3D12, - Inno.Rendering.GraphicsApi.Vulkan, - Inno.Rendering.GraphicsApi.OpenGL + GraphicsApi.Direct3D11, + GraphicsApi.Direct3D12, + GraphicsApi.Vulkan, + GraphicsApi.OpenGL ], - new Inno.Build.Toolchains.Bgfx.Tools.ToolRunner() + new ToolRunner() ) ) ], @@ -213,7 +218,7 @@ protected sealed class FixtureManagedDeploymentCompiler : IManagedDeploymentComp { public FixtureManagedDeploymentCompiler(IReadOnlyList? runtimeIdentifiers = null) { - capabilities = new ManagedDeploymentCapabilities( + this.capabilities = new ManagedDeploymentCapabilities( runtimeIdentifiers ?? ["win-x64", "osx-arm64"], dynamicCode: true, aheadOfTime: false, @@ -309,7 +314,7 @@ protected sealed class BlockingBuildTarget : IGameBuildTarget, IGameContentCompi public TaskCompletionSource release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - public void Validate(string directory) => new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator().Validate(directory); + public void Validate(string directory) => new MacOSArm64SupportPackValidator().Validate(directory); public BuildTargetId id => new BuildTargetId("macos-arm64"); public BuildTargetId target => id; diff --git a/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs b/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs index 14368b0ae..5e62f8a53 100644 --- a/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs +++ b/tests/build/fixtures/Inno.Testing.SupportPacks/PlayerSupportPackFixture.cs @@ -2,6 +2,9 @@ using System.IO; using System.Linq; using Inno.Build; +using Inno.Build.MacOSArm64; +using Inno.Build.WindowsX64; +using Inno.Core.Identity; namespace Inno.Testing.SupportPacks; @@ -12,7 +15,7 @@ public abstract class PlayerSupportPackFixture : IDisposable private readonly string[] m_referenceAssemblies; protected PlayerSupportPackFixture() - : this([typeof(Inno.Core.Identity.IdentityAllocator).Assembly.Location]) {} + : this([typeof(IdentityAllocator).Assembly.Location]) {} protected PlayerSupportPackFixture(string[] referenceAssemblies) { @@ -96,8 +99,8 @@ string executable File.WriteAllBytes(Path.Combine(linkNative, file), CreateNativeImage(target)); } IPlayerSupportPackValidator validator = target == new BuildTargetId("macos-arm64") - ? new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator() - : new Inno.Build.WindowsX64.WindowsX64SupportPackValidator(); + ? new MacOSArm64SupportPackValidator() + : new WindowsX64SupportPackValidator(); using PlayerSupportPackLease published = new PlayerSupportPackCatalog(m_supportPackRoot).PublishAsync( target, directory, @@ -117,22 +120,22 @@ protected static byte[] CreateNativeImage(BuildTargetId target) using var writer = new BinaryWriter(output); if (target == new BuildTargetId("macos-arm64")) { - writer.Write(0xfeedfacfu); - writer.Write(0x0100000cu); + writer.Write(0xFEED_FACFu); + writer.Write(0x0100_000Cu); writer.Write(0u); writer.Write(6u); writer.Write(new byte[16]); } else { - writer.Write((ushort)0x5a4d); + writer.Write((ushort)0x5A4D); writer.Write(new byte[58]); writer.Write(64); - writer.Write(0x00004550u); + writer.Write(0x0000_4550u); writer.Write((ushort)0x8664); writer.Write(new byte[16]); writer.Write((ushort)0x2000); - writer.Write((ushort)0x020b); + writer.Write((ushort)0x020B); } return output.ToArray(); } diff --git a/tests/content/Inno.Content.Tests/ContentPackIndexTests.cs b/tests/content/Inno.Content.Tests/ContentPackIndexTests.cs index 9a9a82005..c46f39871 100644 --- a/tests/content/Inno.Content.Tests/ContentPackIndexTests.cs +++ b/tests/content/Inno.Content.Tests/ContentPackIndexTests.cs @@ -11,7 +11,7 @@ public sealed class ContentPackIndexTests public void IndexCopiesSortsAndRejectsCollisionsAndFileDirectoryConflicts() { ContentEntry[] entries = [Entry("b/file", 2), Entry("a", 1)]; - ContentPackIndex index = new(entries); + var index = new ContentPackIndex(entries); entries[0] = Entry("changed", 7); Assert.Equal("a", index.entries[0].key.value); Assert.Equal(3, index.totalLength); diff --git a/tests/content/Inno.Content.Tests/PackContentStoreTests.cs b/tests/content/Inno.Content.Tests/PackContentStoreTests.cs index 53150fff0..8d145130a 100644 --- a/tests/content/Inno.Content.Tests/PackContentStoreTests.cs +++ b/tests/content/Inno.Content.Tests/PackContentStoreTests.cs @@ -4,6 +4,7 @@ using System.IO.Compression; using System.Linq; using System.Security.Cryptography; +using System.Threading; using System.Threading.Tasks; using Xunit; using Inno.Core.Serialization; @@ -73,19 +74,25 @@ public void BudgetsAndCancellationPrecedeStorePublication() { using EngineHost host = CreateHost(); using SerializationGeneration generation = host.serialization.CaptureGeneration(); - var (pack, descriptor) = CreatePack(generation, new Dictionary { ["a"] = [1, 2, 3] }); + (MemoryStream pack, ContentPackDescriptor descriptor) = CreatePack( + generation, + new Dictionary { ["a"] = [1, 2, 3] } + ); Assert.Throws(() => ContentPackReader.Open( pack, descriptor, generation, new ContentReadLimits(entryBytes: 2) )); - var (canceled, canceledDescriptor) = CreatePack(generation, new Dictionary { ["a"] = [] }); + (MemoryStream canceled, ContentPackDescriptor canceledDescriptor) = CreatePack( + generation, + new Dictionary { ["a"] = [] } + ); Assert.Throws(() => ContentPackReader.Open( canceled, canceledDescriptor, generation, - cancellationToken: new System.Threading.CancellationToken(true) + cancellationToken: new CancellationToken(true) )); Assert.False(canceled.CanRead); } @@ -110,10 +117,10 @@ ContentPackDescriptor descriptor pair.Value.Length + (fault == "length" ? 1 : 0), fault == "payload" ? new string('A', 64) : Convert.ToHexString(SHA256.HashData(pair.Value)) )).ToList(); - MemoryStream output = new(); - using (ZipArchive archive = new(output, ZipArchiveMode.Create, true)) + var output = new MemoryStream(); + using (var archive = new ZipArchive(output, ZipArchiveMode.Create, true)) { - foreach (var pair in payloads) + foreach (KeyValuePair pair in payloads) { if (fault == "missing") { @@ -143,7 +150,7 @@ ContentPackDescriptor descriptor private static byte[] Read(Stream input) { - using MemoryStream output = new(); + using var output = new MemoryStream(); input.CopyTo(output, 137); return output.ToArray(); } diff --git a/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs b/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs index aaa1519a4..bbedff474 100644 --- a/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs +++ b/tests/content/fixtures/Inno.Content.CacheProbe/Program.cs @@ -29,7 +29,7 @@ private static async Task Main(string[] arguments) { return 3; } - byte[] bytes = new byte[checked((int)lease.entry.length)]; + var bytes = new byte[checked((int)lease.entry.length)]; reader.ReadExactly(bytes); Console.WriteLine(Convert.ToHexString(bytes)); return 0; diff --git a/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs b/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs index 461cf83c4..4d90ab14d 100644 --- a/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs +++ b/tests/content/fixtures/Inno.Content.Testing/ContentTestStore.cs @@ -24,7 +24,7 @@ public sealed class ContentTestStore : IRuntimeContentStore public ContentTestStore(IEnumerable> payloads) { m_payloads = payloads.ToDictionary(static pair => pair.Key, static pair => (byte[])pair.Value.Clone()); - index = new ContentPackIndex( + this.index = new ContentPackIndex( m_payloads.Select(static pair => new ContentEntry( pair.Key, pair.Value.LongLength, @@ -36,13 +36,13 @@ public ContentTestStore(IEnumerable> payloads) index.entries.Select(static entry => (entry.key + ":" + entry.length + ":" + entry.contentHash)) ); string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity))); - descriptor = new ContentPackDescriptor(hash, $"content-{hash}.pack"); + this.descriptor = new ContentPackDescriptor(hash, $"content-{hash}.pack"); } - /// + /// public ContentPackDescriptor descriptor { get; } - /// + /// public ContentPackIndex index { get; } /// @@ -84,7 +84,7 @@ ReadOnlySpan bytes m_payloads[key] = bytes.ToArray(); } - /// + /// public ContentReadLease Acquire(ContentKey key) { ObjectDisposedException.ThrowIf(m_disposed, this); @@ -96,7 +96,7 @@ public ContentReadLease Acquire(ContentKey key) return new ContentReadLease(entry!, () => new MemoryStream(bytes, writable: false), static () => {}); } - /// + /// public void Dispose() { m_disposed = true; diff --git a/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs b/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs index 5afa8aa3a..e0fae4e50 100644 --- a/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs +++ b/tests/core/Inno.Core.Collections.Tests/IndexedObjectStoreTests.cs @@ -18,7 +18,7 @@ public Item( int category ) { this.name = name; - Category = category; + this.Category = category; } } @@ -45,7 +45,7 @@ public void Add_Remove_Count_Clear() public void DefineKey_UniqueAndLookup() { var store = new IndexedObjectStore(); - var key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); + IndexedObjectKey key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); var a = new Item("A", 1); var b = new Item("B", 2); @@ -53,10 +53,10 @@ public void DefineKey_UniqueAndLookup() store.Add(a).Set(key, 10); store.Add(b).Set(key, 20); - var found = store.First(key, 20); + Item? found = store.First(key, 20); Assert.Same(b, found); - var all = store.Find(key, 10).ToList(); + List all = store.Find(key, 10).ToList(); Assert.Single(all); Assert.Same(a, all[0]); } @@ -65,7 +65,7 @@ public void DefineKey_UniqueAndLookup() public void DefineKey_Unique_ThrowsOnDuplicateValueFromDifferentItems() { var store = new IndexedObjectStore(); - var key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); + IndexedObjectKey key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); var a = new Item("A", 1); var b = new Item("B", 2); @@ -81,7 +81,7 @@ public void DefineKey_Unique_ThrowsOnDuplicateValueFromDifferentItems() public void DefineKey_Unique_AllowsResettingSameValueOnSameItem() { var store = new IndexedObjectStore(); - var key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); + IndexedObjectKey key = store.DefineKey("id", IndexedObjectKeyFlags.Unique); var a = new Item("A", 1); @@ -96,7 +96,7 @@ public void DefineKey_Unique_AllowsResettingSameValueOnSameItem() public void DefineKey_MultiAndQuery() { var store = new IndexedObjectStore(); - var key = store.DefineKey("category", IndexedObjectKeyFlags.Unordered); + IndexedObjectKey key = store.DefineKey("category", IndexedObjectKeyFlags.Unordered); var a = new Item("A", 1); var b = new Item("B", 1); @@ -106,13 +106,13 @@ public void DefineKey_MultiAndQuery() store.Add(b).Set(key, 1); store.Add(c).Set(key, 2); - var results = store.Find(key, 1).ToList(); + List results = store.Find(key, 1).ToList(); Assert.Equal(2, results.Count); Assert.Contains(a, results); Assert.Contains(b, results); - var query = store.Query().Find(key, 2); - var single = query.First(); + IndexedObjectQuery query = store.Query().Find(key, 2); + Item? single = query.First(); Assert.Same(c, single); } @@ -175,7 +175,7 @@ public void OrderedQueryUsesSmallestIndexedCandidateSetAndReturnsAnIsolatedSnaps .OrderBy(orderKey) .GetFast() .ToArray(); - Assert.Equal(new[] { excluded, last }, fast); + Assert.Equal([excluded, last], fast); Assert.Equal(2, predicateCalls); } @@ -183,7 +183,7 @@ public void OrderedQueryUsesSmallestIndexedCandidateSetAndReturnsAnIsolatedSnaps public void OrderBy_UsesSortedKey() { var store = new IndexedObjectStore(); - var key = store.DefineKey("ordered", IndexedObjectKeyFlags.Ordered, Comparer.Default); + IndexedObjectKey key = store.DefineKey("ordered", IndexedObjectKeyFlags.Ordered, Comparer.Default); var a = new Item("A", 1); var b = new Item("B", 1); @@ -193,7 +193,7 @@ public void OrderBy_UsesSortedKey() store.Add(b).Set(key, 1); store.Add(c).Set(key, 2); - var ordered = store.Query().OrderBy(key).Get().ToList(); + List ordered = store.Query().OrderBy(key).Get().ToList(); Assert.Equal(3, ordered.Count); Assert.Same(b, ordered[0]); Assert.Same(c, ordered[1]); @@ -204,7 +204,7 @@ public void OrderBy_UsesSortedKey() public void RemoveKey_InvalidatesKey() { var store = new IndexedObjectStore(); - var key = store.DefineKey("temp"); + IndexedObjectKey key = store.DefineKey("temp"); var item = new Item("A", 1); store.Add(item).Set(key, 1); @@ -218,7 +218,7 @@ public void RemoveKey_InvalidatesKey() public void TryGetKey_ResolvesByName() { var store = new IndexedObjectStore(); - var key = store.DefineKey("resolve"); + IndexedObjectKey key = store.DefineKey("resolve"); Assert.True(store.TryGetKey("resolve", out IndexedObjectKey resolved)); Assert.True(resolved.isValid); @@ -235,7 +235,7 @@ public void PredicateQuery_Works() store.Add(a); store.Add(b); - var results = store.Query() + List results = store.Query() .Where(item => item.Category == 2) .Get() .ToList(); @@ -251,7 +251,7 @@ public void GetFast_IsFailFast_WhenStoreMutates() store.Add(new Item("A", 1)); store.Add(new Item("B", 2)); - using var enumerator = store.Query().GetFast().GetEnumerator(); + using IEnumerator enumerator = store.Query().GetFast().GetEnumerator(); Assert.True(enumerator.MoveNext()); store.Add(new Item("C", 3)); @@ -280,7 +280,7 @@ public void Get_ReturnsStableSnapshot_WhenStoreMutates() public void RemoveAll_KeepsKeys() { var store = new IndexedObjectStore(); - var key = store.DefineKey("category"); + IndexedObjectKey key = store.DefineKey("category"); var a = new Item("A", 1); store.Add(a).Set(key, 1); @@ -333,7 +333,7 @@ public void AllFast_IsFailFast_WhenStoreMutates() store.Add(new Item("A", 1)); store.Add(new Item("B", 2)); - using var enumerator = store.AllFast().GetEnumerator(); + using IEnumerator enumerator = store.AllFast().GetEnumerator(); Assert.True(enumerator.MoveNext()); store.Add(new Item("C", 3)); diff --git a/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs b/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs index db3a4f3f9..2aabb427d 100644 --- a/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs +++ b/tests/core/Inno.Core.Coroutines.Tests/CoroutineRetirementTests.cs @@ -138,7 +138,7 @@ public void CallbackFaultRetiresItsStackAndDoesNotSkipOtherCoroutines(string sta public void CleanupFailuresDoNotPreventParentOrOtherCoroutineCleanup(bool dispose) { using var scheduler = new CoroutineScheduler(); - var failures = new[] { new Exception("child"), new Exception("parent"), new Exception("other") }; + Exception[] failures = new[] { new Exception("child"), new Exception("parent"), new Exception("other") }; var cleaned = new List(); var child = new Probe(() => true, () => null, () => Fail(0)); scheduler.StartCoroutine(new Probe(() => true, () => child, () => Fail(1))); diff --git a/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs b/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs index dec5af81f..f9044653c 100644 --- a/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs +++ b/tests/core/Inno.Core.Coroutines.Tests/CoroutineSchedulerTests.cs @@ -14,7 +14,7 @@ public sealed class CoroutineSchedulerTests public void StartCoroutine_NullYield_RunsOnNextTick() { using var scheduler = new CoroutineScheduler(); - var ran = false; + bool ran = false; scheduler.StartCoroutine(Routine()); scheduler.Tick(0.016f); @@ -34,7 +34,7 @@ IEnumerator Routine() public void WaitForSeconds_WaitsByTime() { using var scheduler = new CoroutineScheduler(); - var ran = false; + bool ran = false; scheduler.StartCoroutine(Routine()); scheduler.Tick(0.3f); @@ -49,7 +49,7 @@ public void WaitForSeconds_WaitsByTime() IEnumerator Routine() { - yield return new WaitForSeconds(1.0f); + yield return new WaitForSeconds(1f); ran = true; } } @@ -58,8 +58,8 @@ IEnumerator Routine() public void WaitUntil_And_WaitWhile_Work() { using var scheduler = new CoroutineScheduler(); - var flag = false; - var done = false; + bool flag = false; + bool done = false; scheduler.StartCoroutine(Routine()); scheduler.Tick(0.016f); @@ -86,7 +86,7 @@ IEnumerator Routine() public void StopCoroutine_StopsTarget() { using var scheduler = new CoroutineScheduler(); - var count = 0; + int count = 0; CoroutineHandle handle = scheduler.StartCoroutine(Routine()); scheduler.Tick(0.016f); @@ -112,8 +112,8 @@ public void StopAllCoroutines_ByOwner_StopsOnlyThatOwner() using var scheduler = new CoroutineScheduler(); var ownerA = new object(); var ownerB = new object(); - var a = 0; - var b = 0; + int a = 0; + int b = 0; CoroutineHandle handleA = scheduler.StartCoroutine(ownerA, Loop(() => a++)); scheduler.StartCoroutine(ownerB, Loop(() => b++)); @@ -144,7 +144,7 @@ public void StopAllCoroutinesByOwnerReleasesOwnerAndEnumeratorBeforeReturning() public void NestedCoroutine_Works() { using var scheduler = new CoroutineScheduler(); - var order = ""; + string order = string.Empty; scheduler.StartCoroutine(Routine()); scheduler.Tick(0.016f); @@ -173,7 +173,7 @@ public void WaitForTask_WaitsCompletion() { using var scheduler = new CoroutineScheduler(); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var completed = false; + bool completed = false; scheduler.StartCoroutine(Routine()); scheduler.Tick(0.016f); @@ -195,7 +195,7 @@ IEnumerator Routine() public void ListenOnceStyle_YieldCoroutineHandle_WaitsTarget() { using var scheduler = new CoroutineScheduler(); - var done = false; + bool done = false; CoroutineHandle child = scheduler.StartCoroutine(Child()); scheduler.StartCoroutine(Parent(child)); @@ -223,7 +223,7 @@ public void ConcurrentStartAndTick_IsStable() using var scheduler = new CoroutineScheduler(); const int workers = 8; const int perWorker = 4000; - var count = 0; + int count = 0; Parallel.For(0, workers, _ => { @@ -251,8 +251,8 @@ public void ConcurrentStopByHandle_IsStable() { using var scheduler = new CoroutineScheduler(); const int count = 3000; - CoroutineHandle[] handles = new CoroutineHandle[count]; - var ran = 0; + var handles = new CoroutineHandle[count]; + int ran = 0; for (int i = 0; i < count; i++) { @@ -312,7 +312,7 @@ public void StopCoroutine_FromOtherScheduler_ReturnsFalseAndDoesNotAffectOwner() { using var schedulerA = new CoroutineScheduler(); using var schedulerB = new CoroutineScheduler(); - var count = 0; + int count = 0; CoroutineHandle handleA = schedulerA.StartCoroutine(Loop(() => Interlocked.Increment(ref count))); schedulerA.Tick(0.016f); diff --git a/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs b/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs index 3061252cb..f7fe932f1 100644 --- a/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs +++ b/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs @@ -157,7 +157,7 @@ public void ReporterReplacesIssueByIdentityAndResolvesOnlyItsOwnIssue() { var sink = new ProbeSink(); m_hub.RegisterSink(sink); - using var reporter = m_hub.CreateReporter(new DiagnosticSource("tests.audio", "Audio")); + using DiagnosticReporter reporter = m_hub.CreateReporter(new DiagnosticSource("tests.audio", "Audio")); reporter.Publish(new Diagnostic("LOAD", "First", DiagnosticSeverity.Warning, objectId: m_assetId)); reporter.Publish(new Diagnostic("LOAD", "Updated", DiagnosticSeverity.Error, objectId: m_assetId)); Assert.Equal("Updated", Assert.Single(Assert.Single(sink.reports).diagnostics).message); @@ -173,7 +173,7 @@ public void ReporterDoesNotRepublishUnchangedIssueOrAlreadyResolvedIdentity() { var sink = new CountingSink(); m_hub.RegisterSink(sink); - using var reporter = m_hub.CreateReporter(new DiagnosticSource("tests.frame", "Frame")); + using DiagnosticReporter reporter = m_hub.CreateReporter(new DiagnosticSource("tests.frame", "Frame")); reporter.Publish(Diagnostic.Error("FRAME", "Same failure")); int published = sink.replaceCount; @@ -193,9 +193,9 @@ public void OldReporterCannotPublishOrClearReplacementGeneration() var sink = new ProbeSink(); m_hub.RegisterSink(sink); var source = new DiagnosticSource("tests.renderer", "Renderer"); - using var previous = m_hub.CreateReporter(source); + using DiagnosticReporter previous = m_hub.CreateReporter(source); previous.Publish(Diagnostic.Error("OLD", "Old generation")); - using var current = m_hub.CreateReporter(source); + using DiagnosticReporter current = m_hub.CreateReporter(source); current.Publish(Diagnostic.Warning("NEW", "Current generation")); Assert.Throws(() => previous.Publish(Diagnostic.Error("OLD", "Stale"))); previous.Dispose(); @@ -207,7 +207,7 @@ public void ReporterRejectsDuplicateReplacementWithoutChangingLastReport() { var sink = new ProbeSink(); m_hub.RegisterSink(sink); - using var reporter = m_hub.CreateReporter(new DiagnosticSource("tests.graph", "Graph")); + using DiagnosticReporter reporter = m_hub.CreateReporter(new DiagnosticSource("tests.graph", "Graph")); reporter.Publish(Diagnostic.Info("GOOD", "Last good")); Diagnostic duplicate = Diagnostic.Error("BAD", "Duplicate"); Assert.Throws(() => reporter.Replace([duplicate, duplicate])); diff --git a/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs b/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs index 7e51db18d..2dbc523e5 100644 --- a/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs +++ b/tests/core/Inno.Core.Events.Tests/EventDispatcherBehaviorTests.cs @@ -87,7 +87,7 @@ public void ListenTokenDispose_UnsubscribesListener() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var count = 0; + int count = 0; IDisposable token = hub.Listen(_ => count++); dispatcher.Emit(new ProbeEvent(1)); @@ -102,7 +102,7 @@ public void ListenTokenDispose_ConcurrentDispose_IsSafeAndIdempotent() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var count = 0; + int count = 0; IDisposable token = hub.Listen(_ => Interlocked.Increment(ref count)); Parallel.For(0, 64, _ => token.Dispose()); @@ -116,7 +116,7 @@ public void ListenOnce_InvokesOnlyOneTime() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var count = 0; + int count = 0; hub.ListenOnce(_ => count++); @@ -132,7 +132,7 @@ public void ListenOnce_ConcurrentEmit_StillInvokesOnlyOneTime() const int iterations = 10_000; var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var count = 0; + int count = 0; hub.ListenOnce(_ => Interlocked.Increment(ref count)); Parallel.For(0, iterations, i => @@ -205,8 +205,8 @@ public void HandledStopsPropagation_WithinHubAndAcrossHubs() var dispatcher = new EventDispatcher(); using EventHub firstHub = dispatcher.CreateHub(order: 10); using EventHub secondHub = dispatcher.CreateHub(order: 0); - var firstHubSecondListenerCalled = false; - var secondHubCalled = false; + bool firstHubSecondListenerCalled = false; + bool secondHubCalled = false; firstHub.Listen(e => e.HandleInGlobal()); firstHub.Listen(_ => firstHubSecondListenerCalled = true); @@ -223,7 +223,7 @@ public void HandledEventBeforeEmit_SkipsDispatch() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var called = false; + bool called = false; hub.Listen(_ => called = true); @@ -240,8 +240,8 @@ public void HandleInHub_StopsOnlyCurrentHub() var dispatcher = new EventDispatcher(); using EventHub firstHub = dispatcher.CreateHub(order: 10); using EventHub secondHub = dispatcher.CreateHub(order: 0); - var firstHubSecondListenerCalled = false; - var secondHubCalled = false; + bool firstHubSecondListenerCalled = false; + bool secondHubCalled = false; firstHub.Listen(e => e.HandleInHub()); firstHub.Listen(_ => firstHubSecondListenerCalled = true); @@ -259,8 +259,8 @@ public void HandleInHub_DoesNotAffectNextHub() var dispatcher = new EventDispatcher(); using EventHub firstHub = dispatcher.CreateHub(order: 10); using EventHub secondHub = dispatcher.CreateHub(order: 0); - var secondHubFirstListenerCalled = false; - var secondHubSecondListenerCalled = false; + bool secondHubFirstListenerCalled = false; + bool secondHubSecondListenerCalled = false; firstHub.Listen(e => e.HandleInHub()); secondHub.Listen(_ => secondHubFirstListenerCalled = true); @@ -279,8 +279,8 @@ public void ConcurrentEmit_AcrossThreads_IsStable() var dispatcher = new EventDispatcher(); using EventHub hubA = dispatcher.CreateHub(order: 10); using EventHub hubB = dispatcher.CreateHub(order: 0); - var countA = 0; - var countB = 0; + int countA = 0; + int countB = 0; hubA.Listen(_ => Interlocked.Increment(ref countA)); hubB.Listen(_ => Interlocked.Increment(ref countB)); @@ -301,9 +301,9 @@ public void ConcurrentEmit_WithHandleInHub_StopsOnlyCurrentHub() var dispatcher = new EventDispatcher(); using EventHub hubA = dispatcher.CreateHub(order: 10); using EventHub hubB = dispatcher.CreateHub(order: 0); - var hubAFirst = 0; - var hubASecond = 0; - var hubBCount = 0; + int hubAFirst = 0; + int hubASecond = 0; + int hubBCount = 0; hubA.Listen(e => { @@ -333,9 +333,9 @@ public void ConcurrentEmit_WithHandleInGlobal_StopsFollowingHubs() var dispatcher = new EventDispatcher(); using EventHub hubA = dispatcher.CreateHub(order: 10); using EventHub hubB = dispatcher.CreateHub(order: 0); - var hubAFirst = 0; - var hubASecond = 0; - var hubBCount = 0; + int hubAFirst = 0; + int hubASecond = 0; + int hubBCount = 0; hubA.Listen(e => { @@ -364,8 +364,8 @@ public void Announce_DispatchesImmediately_OnlyInCurrentHub() var dispatcher = new EventDispatcher(); using EventHub hubA = dispatcher.CreateHub(order: 10); using EventHub hubB = dispatcher.CreateHub(order: 0); - var hubACalled = false; - var hubBCalled = false; + bool hubACalled = false; + bool hubBCalled = false; hubA.Listen(_ => hubACalled = true); hubB.Listen(_ => hubBCalled = true); @@ -381,7 +381,7 @@ public void Announce_RespectsHandleInHub_InSameHub() { var dispatcher = new EventDispatcher(); using EventHub hub = dispatcher.CreateHub(); - var secondCalled = false; + bool secondCalled = false; hub.Listen(e => e.HandleInHub()); hub.Listen(_ => secondCalled = true); @@ -396,7 +396,7 @@ public void DisposeHub_DuringDispatch_StopsRemainingListenersInSameHub() { var dispatcher = new EventDispatcher(); EventHub hub = dispatcher.CreateHub(); - var secondCalled = false; + bool secondCalled = false; hub.Listen(_ => hub.Dispose()); hub.Listen(_ => secondCalled = true); @@ -412,7 +412,7 @@ public void DisposeHub_DuringAnnounce_StopsRemainingListenersInSameHub() { var dispatcher = new EventDispatcher(); EventHub hub = dispatcher.CreateHub(); - var secondCalled = false; + bool secondCalled = false; hub.Listen(_ => hub.Dispose()); hub.Listen(_ => secondCalled = true); diff --git a/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs b/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs index ea4833b95..21c65d747 100644 --- a/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/ExecutionSlotTests.cs @@ -11,8 +11,8 @@ public sealed class ExecutionSlotTests public void RetirementIsLifoAndRestoresParent() { var slot = new ExecutionSlot("service"); - object first = new(); - object second = new(); + var first = new object(); + var second = new object(); using IDisposable outer = slot.Enter(first); IDisposable inner = slot.Enter(second); Assert.Throws(outer.Dispose); @@ -44,7 +44,7 @@ public async Task RetiredBindingIsRevokedInInheritedAsyncContext() public void SuspensionMasksAndRestoresParent() { var slot = new ExecutionSlot("service"); - object value = new(); + var value = new object(); using IDisposable outer = slot.Enter(value); using (slot.Suspend()) { diff --git a/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs b/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs index af45f3ea5..f5ed60545 100644 --- a/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs +++ b/tests/core/Inno.Core.Execution.Tests/LifetimeAdmissionTests.cs @@ -39,7 +39,9 @@ public void IdleLifetimeDoesNotRetainSuccessfulOperationResults() { using var owner = new LifetimeScope(); WeakReference result = Complete(owner); - GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); Assert.False(result.IsAlive); Assert.Equal(0, owner.trackedWorkCount); } diff --git a/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs b/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs index fb9dbe8f4..f4adb99e7 100644 --- a/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs +++ b/tests/core/Inno.Core.Graphs.Tests/GraphValidatorTests.cs @@ -83,8 +83,8 @@ public void Validate_WithIncompatibleTypes_ReportsError() [Fact] public void Validate_WithMissingNodeDefinition_PreservesDocumentAsWarning() { - GraphDocument document = new(); - GraphNodeRecord node = new(new GraphNodeId("missing"), "plugin.removed"); + var document = new GraphDocument(); + var node = new GraphNodeRecord(new GraphNodeId("missing"), "plugin.removed"); document.AddNode(node); GraphValidationResult result = GraphValidator.Validate(document, new Resolver(m_serialization)); @@ -97,7 +97,7 @@ public void Validate_WithMissingNodeDefinition_PreservesDocumentAsWarning() [Fact] public void Validate_WithCycle_ReportsError() { - GraphDocument document = new(); + var document = new GraphDocument(); GraphNodeRecord left = CreateNode("left", "float", "float"); GraphNodeRecord right = CreateNode("right", "float", "float"); document.AddNode(left); @@ -126,7 +126,7 @@ private GraphDocument CreateConnectedDocument( string outputType, string inputType ) { - GraphDocument document = new(); + var document = new GraphDocument(); GraphNodeRecord source = CreateNode("source", outputType, outputType); GraphNodeRecord destination = CreateNode("destination", inputType, inputType); document.AddNode(source); @@ -140,7 +140,7 @@ private GraphNodeRecord CreateNode( string inputType, string outputType ) { - GraphNodeRecord node = new(new GraphNodeId(id), $"node.{id}"); + var node = new GraphNodeRecord(new GraphNodeId(id), $"node.{id}"); node.SetValue("inputType", GraphSerializedValue.From(inputType, m_serialization)); node.SetValue("outputType", GraphSerializedValue.From(outputType, m_serialization)); return node; @@ -162,7 +162,7 @@ public bool TryResolve( string definitionId, out GraphNodeDefinition? definition ) { - if (!definitionId.StartsWith("node.", System.StringComparison.Ordinal)) + if (!definitionId.StartsWith("node.", StringComparison.Ordinal)) { definition = null; return false; diff --git a/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs b/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs index 337d74409..13e874172 100644 --- a/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs +++ b/tests/core/Inno.Core.IO.Tests/AtomicFilePublicationTests.cs @@ -14,7 +14,10 @@ public sealed class AtomicFilePublicationTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoAtomicPublication", Guid.NewGuid().ToString("N")); - public AtomicFilePublicationTests() => Directory.CreateDirectory(m_root); + public AtomicFilePublicationTests() + { + Directory.CreateDirectory(m_root); + } [Theory] [InlineData("document.imeta.staging-0123456789abcdef0123456789ABCDEF", true)] @@ -229,7 +232,7 @@ private Process Start(params string[] arguments) private static async Task WaitUntil(Func condition) { - long deadline = Environment.TickCount64 + 20000; + long deadline = Environment.TickCount64 + 20_000; while (!condition()) { Assert.True(Environment.TickCount64 < deadline, "The independent publishers did not reach their owned barrier."); diff --git a/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs b/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs index 9bc63c8c5..ac2e22fec 100644 --- a/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs +++ b/tests/core/Inno.Core.IO.Tests/FileLeaseTests.cs @@ -45,7 +45,7 @@ public async Task TimeoutAndCancellationDoNotReleaseAnotherOwner() string path = Path.Combine(m_root, "output.lock"); using FileLease owner = await FileLease.AcquireAsync(path, TimeSpan.Zero); await Assert.ThrowsAsync(() => FileLease.AcquireAsync(path, TimeSpan.Zero).AsTask()); - using CancellationTokenSource cancellation = new(); + using var cancellation = new CancellationTokenSource(); Task waiting = FileLease.AcquireAsync(path, Timeout.InfiniteTimeSpan, cancellation.Token).AsTask(); cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => waiting); @@ -58,7 +58,7 @@ public async Task InvalidRequestsAndPriorCancellationHaveNoFilesystemEffects() await Assert.ThrowsAsync(() => FileLease.AcquireAsync("relative.lock", TimeSpan.Zero).AsTask()); string path = Path.Combine(m_root, "output.lock"); await Assert.ThrowsAsync(() => FileLease.AcquireAsync(path, TimeSpan.FromSeconds(-2)).AsTask()); - using CancellationTokenSource cancellation = new(); + using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync( () => FileLease.AcquireAsync(path, TimeSpan.Zero, cancellation.Token).AsTask() diff --git a/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs b/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs index 8aae21770..609b6b28f 100644 --- a/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs +++ b/tests/core/Inno.Core.IO.Tests/FileSystemSafetyTests.cs @@ -128,7 +128,9 @@ public void DirectoryInstallReplacesACompleteTreeWithoutLeavingBackupDirectories /// /// Rejects canceled installation before creating parents or modifying either owned tree. /// - /// Whether a previous destination is already present. + /// + /// Whether a previous destination is already present. + /// [Theory] [InlineData(false)] [InlineData(true)] @@ -174,7 +176,7 @@ public void DirectoryInstallCancellationRestoresThePreviousTreeDuringABlockedRen string file = Path.Combine(candidate, "value.txt"); File.WriteAllText(file, "current"); File.WriteAllText(Path.Combine(destination, "previous.txt"), "previous"); - using var reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); using var cancellation = new CancellationTokenSource(); bool evacuated = false; ObserveBlockedRename( @@ -185,7 +187,7 @@ public void DirectoryInstallCancellationRestoresThePreviousTreeDuringABlockedRen }, () => { - var failure = Assert.ThrowsAny( + OperationCanceledException failure = Assert.ThrowsAny( () => AtomicDirectory.Install(candidate, destination, cancellation.Token) ); Assert.Equal(cancellation.Token, failure.CancellationToken); @@ -218,7 +220,7 @@ private void VerifyBlockedCancellation(bool expireWindow) string destination = Path.Combine(m_root, "published"); string file = Path.Combine(candidate, "value.txt"); File.WriteAllText(file, "complete"); - using var reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); using var cancellation = new CancellationTokenSource(); ObserveBlockedRename( () => @@ -231,7 +233,7 @@ private void VerifyBlockedCancellation(bool expireWindow) }, () => { - var failure = Assert.ThrowsAny( + OperationCanceledException failure = Assert.ThrowsAny( () => AtomicDirectory.Publish(candidate, destination, cancellation.Token) ); Assert.Equal(cancellation.Token, failure.CancellationToken); @@ -254,7 +256,7 @@ public void DirectoryPublicationToleratesATemporaryWindowsReaderWithoutDeleteSha string destination = Path.Combine(m_root, "published"); string file = Path.Combine(candidate, "value.txt"); File.WriteAllText(file, "complete"); - using var reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); using var cancellation = new CancellationTokenSource(); ObserveBlockedRename(reader.Dispose, () => AtomicDirectory.Publish(candidate, destination, cancellation.Token)); cancellation.Cancel(); @@ -274,7 +276,7 @@ public void PersistentReaderPreservesCandidateAndReturnsWindowsError() string destination = Path.Combine(m_root, "published"); string file = Path.Combine(candidate, "value.txt"); File.WriteAllText(file, "complete"); - using var reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream reader = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); Exception? failure = Record.Exception(() => AtomicDirectory.Publish(candidate, destination)); Assert.True(failure is IOException or UnauthorizedAccessException && IsSharingError(failure)); Assert.False(Directory.Exists(destination)); @@ -294,7 +296,7 @@ public void DirectoryPublicationPreservesAnExistingOwner() } private static bool IsSharingError(Exception exception) - => exception.HResult is unchecked((int)0x80070005) or unchecked((int)0x80070020) or unchecked((int)0x80070021); + => exception.HResult is unchecked((int)0x8007_0005) or unchecked((int)0x8007_0020) or unchecked((int)0x8007_0021); private void ObserveBlockedRename( Action onBlocked, @@ -302,7 +304,7 @@ Action operation ) { // The isolated test intercepts the actual Windows denial before the production catch filter runs. int thread = Environment.CurrentManagedThreadId; - var clock = Stopwatch.StartNew(); + Stopwatch clock = Stopwatch.StartNew(); long blocked = -1; long resumed = -1; int hresult = 0; diff --git a/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs b/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs index f2a95f618..69699f95f 100644 --- a/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs +++ b/tests/core/Inno.Core.IO.Tests/OwnedReadStreamTests.cs @@ -9,7 +9,7 @@ public sealed class OwnedReadStreamTests [Fact] public void ReaderClosesBeforeItsIndependentOwnerAndReleaseCanBeRetried() { - var input = new MemoryStream(new byte[] { 1, 2, 3 }); + var input = new MemoryStream([1, 2, 3]); var pin = new Pin(input); var reader = new OwnedReadStream(input, pin); Assert.Equal(1, reader.ReadByte()); diff --git a/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs b/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs index 21850dc2e..6cf5d0941 100644 --- a/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs +++ b/tests/core/Inno.Core.Identity.Tests/IdentityAllocatorTests.cs @@ -20,7 +20,7 @@ public sealed class IdentityAllocatorTests private WeakReference CreateRegisteredEntity(out int runtimeId) { - Entity entity = new(); + var entity = new Entity(); m_allocator.Register(entity); runtimeId = GetIdentity(entity).runtimeId!.Value; return new WeakReference(entity); diff --git a/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs b/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs index 56a78082d..4f3d698a0 100644 --- a/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs +++ b/tests/core/Inno.Core.Jobs.Performance.Tests/JobSystemPerformanceTests.cs @@ -15,16 +15,16 @@ public void SameScheduleFlow_MoreWorkersIsFasterThanSingleWorker() const int jobCount = 64; const int sleepMilliseconds = 4; - var multiWorkerCount = Math.Min(4, Environment.ProcessorCount); + int multiWorkerCount = Math.Min(4, Environment.ProcessorCount); - using var oneWorker = CreateWorkStealing(1); - using var multiWorker = CreateWorkStealing(multiWorkerCount); + using JobScheduler oneWorker = CreateWorkStealing(1); + using JobScheduler multiWorker = CreateWorkStealing(multiWorkerCount); _ = MeasureScheduleAndCompleteAll(oneWorker, 8, 1); _ = MeasureScheduleAndCompleteAll(multiWorker, 8, 1); - var oneWorkerBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(oneWorker, jobCount, sleepMilliseconds)); - var multiWorkerBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(multiWorker, jobCount, sleepMilliseconds)); + TimeSpan oneWorkerBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(oneWorker, jobCount, sleepMilliseconds)); + TimeSpan multiWorkerBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(multiWorker, jobCount, sleepMilliseconds)); Assert.True( multiWorkerBest < oneWorkerBest, @@ -39,16 +39,16 @@ public void WorkStealingScheduleCompleteAll_IsFasterThanSingleThread() const int jobCount = 48; const int sleepMilliseconds = 4; - var workerCount = Math.Min(4, Environment.ProcessorCount); + int workerCount = Math.Min(4, Environment.ProcessorCount); using var single = new JobScheduler(JobExecutionMode.SingleThread); - using var multi = CreateWorkStealing(workerCount); + using JobScheduler multi = CreateWorkStealing(workerCount); _ = MeasureScheduleAndCompleteAll(single, 8, 1); _ = MeasureScheduleAndCompleteAll(multi, 8, 1); - var singleBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(single, jobCount, sleepMilliseconds)); - var multiBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(multi, jobCount, sleepMilliseconds)); + TimeSpan singleBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(single, jobCount, sleepMilliseconds)); + TimeSpan multiBest = MeasureBestOf(3, () => MeasureScheduleAndCompleteAll(multi, jobCount, sleepMilliseconds)); Assert.True( multiBest < singleBest, @@ -64,16 +64,16 @@ public void WorkStealingParallelFor_IsFasterThanSingleThread() const int length = 48; const int batchSize = 1; const int sleepMilliseconds = 4; - var workerCount = Math.Min(4, Environment.ProcessorCount); + int workerCount = Math.Min(4, Environment.ProcessorCount); using var single = new JobScheduler(JobExecutionMode.SingleThread); - using var multi = CreateWorkStealing(workerCount); + using JobScheduler multi = CreateWorkStealing(workerCount); _ = MeasureParallelFor(single, 8, 1, 1); _ = MeasureParallelFor(multi, 8, 1, 1); - var singleBest = MeasureBestOf(3, () => MeasureParallelFor(single, length, batchSize, sleepMilliseconds)); - var multiBest = MeasureBestOf(3, () => MeasureParallelFor(multi, length, batchSize, sleepMilliseconds)); + TimeSpan singleBest = MeasureBestOf(3, () => MeasureParallelFor(single, length, batchSize, sleepMilliseconds)); + TimeSpan multiBest = MeasureBestOf(3, () => MeasureParallelFor(multi, length, batchSize, sleepMilliseconds)); Assert.True( multiBest < singleBest, @@ -82,21 +82,19 @@ public void WorkStealingParallelFor_IsFasterThanSingleThread() } private static JobScheduler CreateWorkStealing(int workerCount) - { - return new JobScheduler(JobExecutionMode.WorkerPool, new JobSchedulerOptions + => new JobScheduler(JobExecutionMode.WorkerPool, new JobSchedulerOptions { workerCount = workerCount }); - } private static TimeSpan MeasureBestOf( int runs, Func measure ) { - var best = TimeSpan.MaxValue; - for (var i = 0; i < runs; i++) + TimeSpan best = TimeSpan.MaxValue; + for (int i = 0; i < runs; i++) { - var current = measure(); + TimeSpan current = measure(); if (current < best) { best = current; @@ -114,8 +112,8 @@ int sleepMilliseconds jobs.BeginFrame(); var handles = new JobHandle[jobCount]; - var stopwatch = Stopwatch.StartNew(); - for (var i = 0; i < jobCount; i++) + Stopwatch stopwatch = Stopwatch.StartNew(); + for (int i = 0; i < jobCount; i++) { handles[i] = jobs.Schedule(() => Thread.Sleep(sleepMilliseconds)); } @@ -135,8 +133,8 @@ int sleepMilliseconds ) { jobs.BeginFrame(); - var stopwatch = Stopwatch.StartNew(); - var handle = jobs.ParallelFor(length, batchSize, ( + Stopwatch stopwatch = Stopwatch.StartNew(); + JobHandle handle = jobs.ParallelFor(length, batchSize, ( _, _ ) => Thread.Sleep(sleepMilliseconds)); diff --git a/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs b/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs index 113330a6b..30e16ec4a 100644 --- a/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs +++ b/tests/core/Inno.Core.Jobs.Tests/JobSystemBehaviorTests.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Xunit; +using Inno.Core.Execution; using Inno.Core.Jobs; namespace Inno.Core.JobsSystem.Tests; @@ -20,7 +21,7 @@ public void FrameAdmissionRemainsAtomicUnderRepeatedInvalidAndOversizedRequests( for (int frame = 0; frame < 256; frame++) { jobs.BeginFrame(); - Assert.Throws(() => jobs.Schedule(_ => {}, null, new JobHandle[] { default })); + Assert.Throws(() => jobs.Schedule(_ => {}, null, [default])); Assert.Equal(0, jobs.statistics.frameJobs); Assert.Throws(() => jobs.ParallelFor(8, 1, ( _, @@ -48,9 +49,9 @@ public void PendingMainThreadCallbackRemainsOwnedUntilRetry(JobExecutionMode mod int attempts = 0; jobs.EnqueueMainThread(() => { - if (++attempts == 1) throw new Inno.Core.Execution.RetirementPendingException("pending"); + if (++attempts == 1) throw new RetirementPendingException("pending"); }); - Assert.Throws(jobs.DrainMainThreadQueue); + Assert.Throws(jobs.DrainMainThreadQueue); Assert.Equal(1, jobs.statistics.mainThreadPending); jobs.DrainMainThreadQueue(); Assert.Equal(2, attempts); @@ -96,12 +97,12 @@ public void SingleThread_ExecutesDeterministicallyOnMainThread() using var jobs = new JobScheduler(JobExecutionMode.SingleThread); jobs.BeginFrame(); - var mainThread = Environment.CurrentManagedThreadId; + int mainThread = Environment.CurrentManagedThreadId; var observed = new List(); - var a = jobs.Schedule(() => observed.Add(Environment.CurrentManagedThreadId)); - var b = jobs.Schedule(() => observed.Add(Environment.CurrentManagedThreadId)); + JobHandle a = jobs.Schedule(() => observed.Add(Environment.CurrentManagedThreadId)); + JobHandle b = jobs.Schedule(() => observed.Add(Environment.CurrentManagedThreadId)); - jobs.CompleteAll(stackalloc[] { a, b }); + jobs.CompleteAll([a, b]); jobs.EndFrame(); Assert.Equal(2, observed.Count); @@ -137,11 +138,11 @@ public void SingleThread_RejectsCrossThreadUsage() [Fact] public void WorkStealing_ScheduleAndComplete_RunsJob() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - var value = 0; - var handle = jobs.Schedule(() => value = 7); + int value = 0; + JobHandle handle = jobs.Schedule(() => value = 7); jobs.Complete(handle); jobs.EndFrame(); @@ -151,12 +152,12 @@ public void WorkStealing_ScheduleAndComplete_RunsJob() [Fact] public void WorkStealing_ScheduleWithDependencies_RunsInOrder() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); var order = new ConcurrentQueue(); - var first = jobs.Schedule(() => order.Enqueue(1)); - var second = jobs.Schedule(_ => order.Enqueue(2), null, [first]); + JobHandle first = jobs.Schedule(() => order.Enqueue(1)); + JobHandle second = jobs.Schedule(_ => order.Enqueue(2), null, [first]); jobs.Complete(second); jobs.EndFrame(); @@ -167,13 +168,13 @@ public void WorkStealing_ScheduleWithDependencies_RunsInOrder() [Fact] public void WorkStealing_CombineDependencies_CompletesAfterAll() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - var sum = 0; - var a = jobs.Schedule(() => Interlocked.Add(ref sum, 3)); - var b = jobs.Schedule(() => Interlocked.Add(ref sum, 4)); - var barrier = jobs.CombineDependencies([a, b]); + int sum = 0; + JobHandle a = jobs.Schedule(() => Interlocked.Add(ref sum, 3)); + JobHandle b = jobs.Schedule(() => Interlocked.Add(ref sum, 4)); + JobHandle barrier = jobs.CombineDependencies([a, b]); jobs.Complete(barrier); jobs.EndFrame(); @@ -184,17 +185,17 @@ public void WorkStealing_CombineDependencies_CompletesAfterAll() [Fact] public void WorkStealing_ParallelFor_CoversEveryIndexExactlyOnce() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); const int length = 1024; var values = new int[length]; - var handle = jobs.ParallelFor(length, 32, ( + JobHandle handle = jobs.ParallelFor(length, 32, ( start, end ) => { - for (var i = start; i < end; i++) + for (int i = start; i < end; i++) { Interlocked.Increment(ref values[i]); } @@ -203,7 +204,7 @@ public void WorkStealing_ParallelFor_CoversEveryIndexExactlyOnce() jobs.Complete(handle); jobs.EndFrame(); - for (var i = 0; i < values.Length; i++) + for (int i = 0; i < values.Length; i++) { Assert.Equal(1, values[i]); } @@ -212,10 +213,10 @@ public void WorkStealing_ParallelFor_CoversEveryIndexExactlyOnce() [Fact] public void WorkStealing_MainThreadQueue_DrainExecutesOnMainThread() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - var mainThread = Environment.CurrentManagedThreadId; + int mainThread = Environment.CurrentManagedThreadId; var threadIds = new List(); jobs.EnqueueMainThread(() => threadIds.Add(Environment.CurrentManagedThreadId)); jobs.EnqueueMainThread(() => threadIds.Add(Environment.CurrentManagedThreadId)); @@ -229,7 +230,7 @@ public void WorkStealing_MainThreadQueue_DrainExecutesOnMainThread() [Fact] public void WorkStealing_MainThreadQueue_DrainFromWorkerThread_Throws() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); Exception? fault = null; @@ -254,28 +255,28 @@ public void WorkStealing_MainThreadQueue_DrainFromWorkerThread_Throws() [Fact] public void WorkStealing_WhenJobThrows_CompleteRethrowsAndEndFrameAggregates() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - var handle = jobs.Schedule(() => throw new InvalidOperationException("boom")); - var completeEx = Assert.Throws(() => jobs.Complete(handle)); + JobHandle handle = jobs.Schedule(() => throw new InvalidOperationException("boom")); + InvalidOperationException completeEx = Assert.Throws(() => jobs.Complete(handle)); Assert.IsType(completeEx.InnerException); - var endEx = Assert.Throws(() => jobs.EndFrame()); + AggregateException endEx = Assert.Throws(() => jobs.EndFrame()); Assert.NotEmpty(endEx.InnerExceptions); } [Fact] public void WorkStealing_EndFrameRecyclesHandle_AndStaleHandleThrows() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); - var handle = jobs.Schedule(() => {}); + JobHandle handle = jobs.Schedule(() => {}); jobs.EndFrame(); jobs.BeginFrame(); - var ex = Assert.Throws(() => jobs.Complete(handle)); + InvalidOperationException ex = Assert.Throws(() => jobs.Complete(handle)); jobs.EndFrame(); Assert.Contains("stale", ex.Message, StringComparison.OrdinalIgnoreCase); @@ -284,14 +285,14 @@ public void WorkStealing_EndFrameRecyclesHandle_AndStaleHandleThrows() [Fact] public void WorkStealing_ConcurrentSchedulingAcrossThreads_IsStable() { - using var jobs = CreateWorkStealing(workerCount: 4); + using JobScheduler jobs = CreateWorkStealing(workerCount: 4); jobs.BeginFrame(); const int taskCount = 2000; - var count = 0; + int count = 0; Parallel.For(0, taskCount, _ => { - var handle = jobs.Schedule(() => Interlocked.Increment(ref count)); + JobHandle handle = jobs.Schedule(() => Interlocked.Increment(ref count)); jobs.Complete(handle); }); @@ -302,12 +303,12 @@ public void WorkStealing_ConcurrentSchedulingAcrossThreads_IsStable() [Fact] public void WorkStealing_WorkerThreadsParticipateUnderLoad() { - using var jobs = CreateWorkStealing(workerCount: 4); + using JobScheduler jobs = CreateWorkStealing(workerCount: 4); jobs.BeginFrame(); var threadIds = new ConcurrentDictionary(); var handles = new JobHandle[256]; - for (var i = 0; i < handles.Length; i++) + for (int i = 0; i < handles.Length; i++) { handles[i] = jobs.Schedule(() => { @@ -325,13 +326,13 @@ public void WorkStealing_WorkerThreadsParticipateUnderLoad() [Fact] public void WorkStealing_NestedScheduleFromWorker_IsSupported() { - using var jobs = CreateWorkStealing(workerCount: 2); + using JobScheduler jobs = CreateWorkStealing(workerCount: 2); jobs.BeginFrame(); - var value = 0; - var outer = jobs.Schedule(() => + int value = 0; + JobHandle outer = jobs.Schedule(() => { - var inner = jobs.Schedule(() => Interlocked.Add(ref value, 3)); + JobHandle inner = jobs.Schedule(() => Interlocked.Add(ref value, 3)); jobs.Complete(inner); Interlocked.Add(ref value, 2); }); @@ -352,18 +353,18 @@ public void WorkStealing_AutoWorkerCount_IsInValidRange() [Fact] public void WorkStealing_CombineManyDependencies_CompletesReliably() { - using var jobs = CreateWorkStealing(workerCount: 4); + using JobScheduler jobs = CreateWorkStealing(workerCount: 4); jobs.BeginFrame(); const int count = 300; var handles = new JobHandle[count]; - var sum = 0; - for (var i = 0; i < count; i++) + int sum = 0; + for (int i = 0; i < count; i++) { handles[i] = jobs.Schedule(() => Interlocked.Increment(ref sum)); } - var barrier = jobs.CombineDependencies(handles); + JobHandle barrier = jobs.CombineDependencies(handles); jobs.Complete(barrier); jobs.EndFrame(); @@ -373,14 +374,14 @@ public void WorkStealing_CombineManyDependencies_CompletesReliably() [Fact] public void CommonApi_EndFrameWithoutBeginFrame_Throws() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); Assert.Throws(() => jobs.EndFrame()); } [Fact] public void CommonApi_BeginFrameTwice_Throws() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); Assert.Throws(() => jobs.BeginFrame()); jobs.EndFrame(); @@ -389,7 +390,7 @@ public void CommonApi_BeginFrameTwice_Throws() [Fact] public void CommonApi_ParallelForInvalidArguments_Throws() { - using var jobs = CreateWorkStealing(); + using JobScheduler jobs = CreateWorkStealing(); jobs.BeginFrame(); Assert.Throws(() => jobs.ParallelFor(-1, 8, ( @@ -407,7 +408,7 @@ public void CommonApi_ParallelForInvalidArguments_Throws() [Fact] public void CommonApi_DisposePreventsFurtherUse() { - var jobs = CreateWorkStealing(); + JobScheduler jobs = CreateWorkStealing(); jobs.Dispose(); Assert.Throws(() => jobs.BeginFrame()); @@ -415,10 +416,8 @@ public void CommonApi_DisposePreventsFurtherUse() } private static JobScheduler CreateWorkStealing(int workerCount = 2) + => new JobScheduler(JobExecutionMode.WorkerPool, new JobSchedulerOptions { - return new JobScheduler(JobExecutionMode.WorkerPool, new JobSchedulerOptions - { - workerCount = workerCount - }); - } + workerCount = workerCount + }); } diff --git a/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs b/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs index 1c0c9edd3..93f060638 100644 --- a/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs +++ b/tests/core/Inno.Core.Logging.Tests/FileLogSinkTests.cs @@ -62,7 +62,7 @@ public void RapidRotationRetainsTheCurrentEntryAndHonorsTheByteLimit() public void OversizedEntriesRemainCompleteAndRotateBeforeTheNextEntry() { using var sink = new FileLogSink(m_root, maxFileSizeBytes: 128, maxFiles: 2); - string oversized = new('x', 2_000); + var oversized = new string('x', 2_000); sink.Receive(CreateEntry(oversized)); sink.Receive(CreateEntry("next-entry")); diff --git a/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs b/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs index c74c1319b..456e40ad5 100644 --- a/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs +++ b/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Xunit; using Inno.Core.Logging; +using Inno.Extensibility.Modules; namespace Inno.Core.Logging.Tests; @@ -29,7 +30,7 @@ public LoggingBehaviorTests() public void InlineDeliveryIsImmediateAndQuarantinesAFailingSink() { using var router = new LogRouter(deliveryMode: LogDeliveryMode.Inline); - using var scope = router.EnterScope(); + using IDisposable scope = router.EnterScope(); using var healthy = new ProbeSink(); var failing = new FailingSink(); Exception? failure = null; @@ -56,16 +57,15 @@ public void ExplicitOwnershipAcceptsStaticSourcesAndRejectsMissingTypes() Assert.Throws(() => Log.Info(null!, "Missing source")); m_router.Flush(); LogEntry entry = Assert.Single(sink.entries); - Assert.Equal(Inno.Extensibility.Modules.AssemblyDomain.InnoInternal, entry.domain); + Assert.Equal(AssemblyDomain.InnoInternal, entry.domain); Assert.Equal("Explicit static source", entry.message); m_router.UnregisterSink(sink); } [Fact] - public void UnknownDeliveryPoliciesFailAtConstruction() - { - Assert.Throws(() => new LogRouter(deliveryMode: (LogDeliveryMode)99)); - } + public void UnknownDeliveryPoliciesFailAtConstruction() => Assert.Throws( + () => new LogRouter(deliveryMode: (LogDeliveryMode)99) + ); [Theory] [InlineData("/build/Game/PlayerBehavior.cs")] @@ -95,7 +95,7 @@ public async Task BrokenFailureReportingCannotStopHealthySinkDelivery( bool failingObserver ) { using var router = new LogRouter(deliveryMode: mode); - using var scope = router.EnterScope(); + using IDisposable scope = router.EnterScope(); using var healthy = new ProbeSink(); var failing = new FailingSink(); int reported = 0; @@ -161,7 +161,7 @@ public void CallSiteIsCapturedForPlainAndFormattedMessagesWithoutMethodReflectio Assert.Equal(nameof(LoggingBehaviorTests), entry.category); Assert.Equal("LoggingBehaviorTests.cs", Path.GetFileName(entry.file)); Assert.True(entry.line > 0); - Assert.Equal(Inno.Extensibility.Modules.AssemblyDomain.InnoInternal, entry.domain); + Assert.Equal(AssemblyDomain.InnoInternal, entry.domain); }); Assert.Equal("plain", sink.entries[0].message); Assert.Equal("formatted-73", sink.entries[1].message); @@ -271,13 +271,13 @@ public void FailingSinkIsReportedQuarantinedAndDoesNotBlockHealthySinks() [Fact] public void FileLogSink_WritesEntriesAndRotates() { - var dir = Path.Combine(Path.GetTempPath(), "InnoLoggingTests", Guid.NewGuid().ToString("N")); + string dir = Path.Combine(Path.GetTempPath(), "InnoLoggingTests", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dir); using var sink = new FileLogSink(dir, maxFileSizeBytes: 256, maxFiles: 3); m_router.RegisterSink(sink); - for (var i = 0; i < 80; i++) + for (int i = 0; i < 80; i++) { Log.Warn(typeof(LoggingBehaviorTests), "line-{0}", [i]); } @@ -286,8 +286,8 @@ public void FileLogSink_WritesEntriesAndRotates() m_router.UnregisterSink(sink); sink.Dispose(); - var files = Directory.GetFiles(dir, FileLogSink.C_LOG_FILE_PREFIX + "*.log"); - var combined = string.Join(Environment.NewLine, files.Select(File.ReadAllText)); + string[] files = Directory.GetFiles(dir, FileLogSink.C_LOG_FILE_PREFIX + "*.log"); + string combined = string.Join(Environment.NewLine, files.Select(File.ReadAllText)); Assert.Contains("line-79", combined); Assert.True(files.Length <= 3); Assert.All(files, static file => Assert.Equal(".log", Path.GetExtension(file))); @@ -316,7 +316,7 @@ public bool WaitForCount( int count, TimeSpan timeout ) { - var deadline = DateTime.UtcNow + timeout; + DateTime deadline = DateTime.UtcNow + timeout; while (DateTime.UtcNow < deadline) { if (m_entries.Count >= count) @@ -331,10 +331,7 @@ TimeSpan timeout return m_entries.Count >= count; } - public void Dispose() - { - m_signal.Dispose(); - } + public void Dispose() => m_signal.Dispose(); } private sealed class BrokenErrorWriter : TextWriter diff --git a/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs b/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs index 299b71821..5bacb5b55 100644 --- a/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs +++ b/tests/core/Inno.Core.Mathematics.Tests/VectorMatrixTests.cs @@ -39,7 +39,7 @@ public void EulerAnglesXYZ_RoundTripsCompoundRotation() public void Vector2_LengthSquared_MatchesDot() { var v = new Vector2(3f, 4f); - var dot = Vector2.Dot(v, v); + float dot = Vector2.Dot(v, v); Assert.True(MathHelper.AlmostEquals(25f, dot)); Assert.True(MathHelper.AlmostEquals(25f, v.LengthSquared())); Assert.True(MathHelper.AlmostEquals(5f, v.Length())); @@ -50,7 +50,7 @@ public void Vector3_Cross_IsOrthogonal() { var a = new Vector3(1f, 0f, 0f); var b = new Vector3(0f, 1f, 0f); - var c = Vector3.Cross(a, b); + Vector3 c = Vector3.Cross(a, b); Assert.True(MathHelper.AlmostEquals(0f, Vector3.Dot(a, c))); Assert.True(MathHelper.AlmostEquals(0f, Vector3.Dot(b, c))); @@ -63,8 +63,8 @@ public void Vector3_Cross_IsOrthogonal() public void Vector3_TransformNormal_IgnoresTranslation() { var normal = new Vector3(0f, 1f, 0f); - var translation = Matrix.CreateTranslation(10f, 20f, 30f); - var result = Vector3.TransformNormal(normal, translation); + Matrix translation = Matrix.CreateTranslation(10f, 20f, 30f); + Vector3 result = Vector3.TransformNormal(normal, translation); Assert.True(MathHelper.AlmostEquals(normal.x, result.x)); Assert.True(MathHelper.AlmostEquals(normal.y, result.y)); @@ -76,8 +76,8 @@ public void Vector2_Angle_SignedAngle() { var right = new Vector2(1f, 0f); var up = new Vector2(0f, 1f); - var angle = Vector2.Angle(right, up); - var signed = Vector2.SignedAngle(right, up); + float angle = Vector2.Angle(right, up); + float signed = Vector2.SignedAngle(right, up); Assert.True(MathHelper.AlmostEquals(MathF.PI * 0.5f, angle)); Assert.True(MathHelper.AlmostEquals(MathF.PI * 0.5f, signed)); @@ -86,12 +86,12 @@ public void Vector2_Angle_SignedAngle() [Fact] public void Matrix_Multiply_ColumnVector_Order() { - var scale = Matrix.CreateScale(2f); - var translate = Matrix.CreateTranslation(1f, 0f, 0f); - var combined = translate * scale; + Matrix scale = Matrix.CreateScale(2f); + Matrix translate = Matrix.CreateTranslation(1f, 0f, 0f); + Matrix combined = translate * scale; var v = new Vector3(1f, 0f, 0f); - var result = Vector3.Transform(v, combined); + Vector3 result = Vector3.Transform(v, combined); Assert.True(MathHelper.AlmostEquals(3f, result.x)); Assert.True(MathHelper.AlmostEquals(0f, result.y)); @@ -101,12 +101,12 @@ public void Matrix_Multiply_ColumnVector_Order() [Fact] public void Matrix_Determinant_Invert_Roundtrip() { - var m = Matrix.CreateTranslation(1f, 2f, 3f) * Matrix.CreateScale(2f, 3f, 4f); - var det = Matrix.Determinant(m); + Matrix m = Matrix.CreateTranslation(1f, 2f, 3f) * Matrix.CreateScale(2f, 3f, 4f); + float det = Matrix.Determinant(m); Assert.True(MathHelper.AlmostEquals(24f, det)); - var inv = Matrix.Invert(m); - var identity = m * inv; + Matrix inv = Matrix.Invert(m); + Matrix identity = m * inv; Assert.True(identity == Matrix.identity); } @@ -114,19 +114,19 @@ public void Matrix_Determinant_Invert_Roundtrip() public void Matrix_Decompose_Roundtrip() { var scale = new Vector3(2f, 3f, 4f); - var rotation = Quaternion.FromEulerAnglesXYZ(new Vector3(0.2f, 0.3f, 0.4f)); + Quaternion rotation = Quaternion.FromEulerAnglesXYZ(new Vector3(0.2f, 0.3f, 0.4f)); var translation = new Vector3(5f, 6f, 7f); - var m = Matrix.CreateTranslation(translation) * Matrix.CreateFromQuaternion(rotation) * Matrix.CreateScale(scale); + Matrix m = Matrix.CreateTranslation(translation) * Matrix.CreateFromQuaternion(rotation) * Matrix.CreateScale(scale); - var success = Matrix.Decompose(m, out var outScale, out var outRotation, out var outTranslation); + bool success = Matrix.Decompose(m, out Vector3 outScale, out Quaternion outRotation, out Vector3 outTranslation); Assert.True(success); Assert.True(outTranslation == translation); Assert.True(MathHelper.AlmostEquals(scale.x, outScale.x)); Assert.True(MathHelper.AlmostEquals(scale.y, outScale.y)); Assert.True(MathHelper.AlmostEquals(scale.z, outScale.z)); - var rotMatrix = outRotation.ToMatrix(); - var expected = rotation.ToMatrix(); + Matrix rotMatrix = outRotation.ToMatrix(); + Matrix expected = rotation.ToMatrix(); Assert.True(rotMatrix == expected); } @@ -134,7 +134,7 @@ public void Matrix_Decompose_Roundtrip() public void Matrix_Decompose_PreservesReflectedTransform() { var scale = new Vector3(-2f, 3f, 4f); - var rotation = Quaternion.FromEulerAnglesXYZ(new Vector3(0.2f, 0.3f, 0.4f)); + Quaternion rotation = Quaternion.FromEulerAnglesXYZ(new Vector3(0.2f, 0.3f, 0.4f)); var translation = new Vector3(5f, 6f, 7f); Matrix matrix = Matrix.CreateTranslation(translation) * Matrix.CreateFromQuaternion(rotation) @@ -160,7 +160,7 @@ public void Matrix_LookAtRH_IdentityForMinusZ() var eye = new Vector3(0f, 0f, 0f); var target = new Vector3(0f, 0f, -1f); var up = new Vector3(0f, 1f, 0f); - var view = Matrix.CreateLookAtRH(eye, target, up); + Matrix view = Matrix.CreateLookAtRH(eye, target, up); Assert.True(view == Matrix.identity); } @@ -170,13 +170,13 @@ public void Matrix_PerspectiveRH_MapsNearFar() { float near = 0.1f; float far = 10f; - var proj = Matrix.CreatePerspectiveFieldOfViewRH(MathF.PI / 2f, 1f, near, far); + Matrix proj = Matrix.CreatePerspectiveFieldOfViewRH(MathF.PI / 2f, 1f, near, far); var vNear = new Vector4(0f, 0f, -near, 1f); var vFar = new Vector4(0f, 0f, -far, 1f); - var pNear = Vector4.Transform(vNear, proj).ProjectToVector3(); - var pFar = Vector4.Transform(vFar, proj).ProjectToVector3(); + Vector3 pNear = Vector4.Transform(vNear, proj).ProjectToVector3(); + Vector3 pFar = Vector4.Transform(vFar, proj).ProjectToVector3(); Assert.True(MathHelper.AlmostEquals(0f, pNear.z)); Assert.True(MathHelper.AlmostEquals(1f, pFar.z)); @@ -187,7 +187,7 @@ public void Matrix_PerspectiveLH_MapsNearFar() { float near = 0.1f; float far = 10f; - var projection = Matrix.CreatePerspectiveFieldOfView(MathF.PI / 2f, 1f, near, far); + Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathF.PI / 2f, 1f, near, far); Vector3 projectedNear = (projection * new Vector4(0f, 0f, near, 1f)).ProjectToVector3(); Vector3 projectedFar = (projection * new Vector4(0f, 0f, far, 1f)).ProjectToVector3(); @@ -211,10 +211,10 @@ public void Matrix_LookAtLH_RotatesWorldIntoCameraAxes() [Fact] public void Matrix_OrthographicOffCenter_MapsEdges() { - var ortho = Matrix.CreateOrthographicOffCenter(-2f, 2f, -1f, 1f, 0f, 10f); + Matrix ortho = Matrix.CreateOrthographicOffCenter(-2f, 2f, -1f, 1f, 0f, 10f); - var left = Vector4.Transform(new Vector4(-2f, 0f, 0f, 1f), ortho).ProjectToVector3(); - var right = Vector4.Transform(new Vector4(2f, 0f, 0f, 1f), ortho).ProjectToVector3(); + Vector3 left = Vector4.Transform(new Vector4(-2f, 0f, 0f, 1f), ortho).ProjectToVector3(); + Vector3 right = Vector4.Transform(new Vector4(2f, 0f, 0f, 1f), ortho).ProjectToVector3(); Assert.True(MathHelper.AlmostEquals(-1f, left.x)); Assert.True(MathHelper.AlmostEquals(1f, right.x)); @@ -225,7 +225,7 @@ public void Matrix_ToColumnMajorArray_Layout() { var m = new Matrix(1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f); - var data = m.ToColumnMajorArray(); + float[] data = m.ToColumnMajorArray(); Assert.Equal(16, data.Length); Assert.True(MathHelper.AlmostEquals(1f, data[0])); @@ -242,17 +242,17 @@ public void Matrix_ToColumnMajorArray_Layout() public void Quaternion_Normalize_UnitLength() { var q = new Quaternion(1f, 2f, 3f, 4f); - var n = Quaternion.Normalize(q); - var len = n.Length(); + Quaternion n = Quaternion.Normalize(q); + float len = n.Length(); Assert.True(MathHelper.AlmostEquals(1f, len)); } [Fact] public void Quaternion_FromRotationMatrix_Roundtrip() { - var q = Quaternion.FromEulerAnglesXYZ(new Vector3(0.25f, 0.5f, 1.1f)); - var m = q.ToMatrix(); - var q2 = Quaternion.FromRotationMatrix(m); + Quaternion q = Quaternion.FromEulerAnglesXYZ(new Vector3(0.25f, 0.5f, 1.1f)); + Matrix m = q.ToMatrix(); + Quaternion q2 = Quaternion.FromRotationMatrix(m); if (Dot(q, q2) < 0f) { q2 = new Quaternion(-q2.x, -q2.y, -q2.z, -q2.w); @@ -268,9 +268,7 @@ public void Quaternion_FromRotationMatrix_Roundtrip() private static float Dot( Quaternion a, Quaternion b - ) { - return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; - } + ) => a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; [Fact] public void MathHelper_Clamp_Saturate_IsFinite() diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs index 9e148df0c..9f3f6e960 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Loader; using System.Threading.Tasks; @@ -191,17 +192,17 @@ public void CaptureKeyQueriesDoNotConstructOrSkipStatefulConverters() public void PureFieldMetadataPreservesExactFloatBitsAcrossTrackedPropertyChanges() { var identities = new IdentityAllocator(); - var properties = new PureFieldCaptureProperties { value = new PureCaptureFields { number = -0.0f } }; + var properties = new PureFieldCaptureProperties { value = new PureCaptureFields { number = -0f } }; var value = new CaptureKeyRoot { properties = properties }; Assert.True(identities.Register(value)); Assert.True(identities.Register(properties)); _ = m_serialization.CapturePropertiesData(properties); SerializationSnapshot before = m_serialization.CaptureSnapshot(value); Assert.Same(before, m_serialization.CaptureSnapshot(value, previous: before)); - properties.value = new PureCaptureFields { number = 0.0f }; + properties.value = new PureCaptureFields { number = 0f }; SerializationSnapshot zero = m_serialization.CaptureSnapshot(value, previous: before); Assert.NotEqual(before.ToArray(), zero.ToArray()); - foreach (int bits in new[] { 0x7fc00001, 0x7fc00002 }) + foreach (int bits in new[] { 0x7FC0_0001, 0x7FC0_0002 }) { properties.value = new PureCaptureFields { number = BitConverter.Int32BitsToSingle(bits) }; SerializationSnapshot changed = m_serialization.CaptureSnapshot(value, previous: zero); @@ -328,9 +329,9 @@ public void RetainedCaptureKeysAndRetiredBuildersDoNotPinACollectiblePropertyAss private (SerializationSnapshot, SerializationCaptureKeyBuilder, WeakReference, WeakReference) CaptureCollectibleProperties() { var context = new CapturePropertyLoadContext(); - var assembly = context.LoadFromAssemblyPath(typeof(CaptureRevisionProperties).Assembly.Location); + Assembly assembly = context.LoadFromAssemblyPath(typeof(CaptureRevisionProperties).Assembly.Location); Type type = assembly.GetType(typeof(CaptureRevisionProperties).FullName!, throwOnError: true)!; - var properties = (ISerializable)Activator.CreateInstance(type)!; + ISerializable properties = (ISerializable)Activator.CreateInstance(type)!; var identities = new IdentityAllocator(); var value = new CaptureKeyRoot { properties = properties }; Assert.True(identities.Register(value)); @@ -461,14 +462,17 @@ public int number internal sealed class UntrackedCaptureProperties : IdentityObject, ISerializable { - [SerializableProperty] public int number; + [SerializableProperty] + public int number; } [SerializationRevision("revision")] internal sealed class ConvertedCaptureProperties : IdentityObject, ISerializable { private ulong? revision => 0; - [SerializableProperty] public CaptureConvertedValue value = new() { number = 1 }; + + [SerializableProperty] + public CaptureConvertedValue value = new() { number = 1 }; } [SerializationRevision("m_revision")] @@ -498,7 +502,9 @@ internal struct PureCaptureFields internal sealed class GetterCaptureProperties : IdentityObject, ISerializable { private ulong? revision => 0; - [SerializableProperty] public CaptureGetterStruct value = new(); + + [SerializableProperty] + public CaptureGetterStruct value = new(); } internal struct CaptureGetterStruct @@ -526,7 +532,10 @@ internal sealed class CaptureConvertedValueConverter : SerializationConverter events = []; internal static int calls; - public CaptureConvertedValueConverter() => events.Add("construct"); + public CaptureConvertedValueConverter() + { + events.Add("construct"); + } public override void Write( SerializationWriter writer, @@ -543,7 +552,8 @@ CaptureConvertedValue value [SerializationRevision("revision")] internal sealed class SerializedCaptureCounter : IdentityObject, ISerializable { - [SerializableProperty(PropertyVisibility.Serialize)] public ulong revision => 0; + [SerializableProperty(PropertyVisibility.Serialize)] + public ulong revision => 0; } internal sealed class FreshCaptureMetadataSource : ISerializationMetadataSource @@ -559,6 +569,6 @@ public SerializationTypeMetadata GetMetadata(Type type) internal sealed class CapturePropertyLoadContext() : AssemblyLoadContext(isCollectible: true) { - protected override System.Reflection.Assembly? Load(System.Reflection.AssemblyName name) + protected override Assembly? Load(AssemblyName name) => Default.Assemblies.FirstOrDefault(assembly => assembly.GetName().Name == name.Name); } diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs index 212b11bfa..396ec562b 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs @@ -48,17 +48,20 @@ internal sealed class ConcurrentCaptureConverter : SerializationConverter /// Records construction of the converter owned by the captured generation. /// - public ConcurrentCaptureConverter() => Interlocked.Increment(ref constructions); + public ConcurrentCaptureConverter() + { + Interlocked.Increment(ref constructions); + } - /// + /// public override void Write( SerializationWriter writer, ConcurrentCaptureValue value ) => writer.Write("count", value.count); - /// + /// public override ConcurrentCaptureValue Read(SerializationReader reader) => new(reader.Read("count")); - /// + /// public void Dispose() => Interlocked.Increment(ref disposals); } diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs index c56b62cbf..77d8a445b 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Encoding.cs @@ -168,7 +168,8 @@ private static byte[] EncodeWithBinaryWriter(object? value) writer.Write((byte)14); writer.Write(scalar.ToByteArray()); break; - default: throw new InvalidOperationException("The independent byte oracle received an unsupported scalar."); + default: + throw new InvalidOperationException("The independent byte oracle received an unsupported scalar."); } writer.Flush(); return stream.ToArray(); diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs index 194b6f191..4ee366c1e 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs @@ -97,7 +97,7 @@ public void SnapshotCapturePreservesOrdinaryBytesAndEveryDirectValueChange() for (int index = 0; index < 12; index++) { value.count++; - value.ratio = BitConverter.Int32BitsToSingle(index % 2 == 0 ? unchecked((int)0x80000000) : 0x7fc00001 + index); + value.ratio = BitConverter.Int32BitsToSingle(index % 2 == 0 ? unchecked((int)0x8000_0000) : 0x7FC0_0001 + index); value.bytes[index % 2]++; value.values.Add(index); SerializationSnapshot next = m_serialization.CaptureSnapshot(value, previous: snapshot); @@ -258,8 +258,11 @@ internal sealed class MutatingPropertyCapture : ISerializable { private readonly byte[] m_bytes = [1]; - [SerializableProperty(PropertyVisibility.Serialize)] public byte[] bytes => m_bytes; - [SerializableProperty(PropertyVisibility.Serialize)] public int mutate => m_bytes[0] = 2; + [SerializableProperty(PropertyVisibility.Serialize)] + public byte[] bytes => m_bytes; + + [SerializableProperty(PropertyVisibility.Serialize)] + public int mutate => m_bytes[0] = 2; internal void Reset() => m_bytes[0] = 1; } @@ -284,7 +287,7 @@ SnapshotEnvelope value ) { value.writeCalls++; value.observedTypeGeneration = writer.typeSnapshot.version; - foreach (var pair in value.fields) + foreach (KeyValuePair pair in value.fields) { writer.Write(pair.Key, pair.Value); } diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs index 72f46ac65..09eb10164 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text; using System.Threading.Tasks; using Xunit; using Inno.Adapter.Modules.DotNet; @@ -302,14 +303,11 @@ public void PropertyData_RejectsMalformedOrTrailingBytes() new DefaultSample { count = 12 }, nameof(DefaultSample.count) ); - byte[] trailing = new byte[data.Length + 1]; + var trailing = new byte[data.Length + 1]; data.CopyTo(trailing, 0); Assert.Throws(() => m_serialization.RestorePropertiesData(new DefaultSample(), trailing)); - Assert.ThrowsAny(() => m_serialization.RestorePropertiesData( - new DefaultSample(), - new byte[] { 1, 2, 3 } - )); + Assert.ThrowsAny(() => m_serialization.RestorePropertiesData(new DefaultSample(), [1, 2, 3])); } [Fact] @@ -698,7 +696,7 @@ public void NonStringMapEncoding_IsDeterministic() public void ForeignFormatHeader_IsRejected() { using var stream = new MemoryStream(); - using (var writer = new BinaryWriter(stream, System.Text.Encoding.UTF8, leaveOpen: true)) + using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) { writer.Write("FOREIGN"); } @@ -718,16 +716,27 @@ internal enum SampleMode internal sealed class PreviousSchemaSample : ISerializable { - [SerializableProperty] public int changed { get; set; } - [SerializableProperty(PropertyVisibility.Hide)] public string compatible { get; set; } = string.Empty; - [SerializableProperty] public int removed { get; set; } + [SerializableProperty] + public int changed { get; set; } + + [SerializableProperty(PropertyVisibility.Hide)] + public string compatible { get; set; } = string.Empty; + + [SerializableProperty] + public int removed { get; set; } } internal sealed class CurrentSchemaSample : ISerializable { - [SerializableProperty] public string changed { get; set; } = "default"; - [SerializableProperty(PropertyVisibility.Hide)] public string compatible { get; set; } = "new"; - [SerializableProperty] public int added { get; set; } = 17; + [SerializableProperty] + public string changed { get; set; } = "default"; + + [SerializableProperty(PropertyVisibility.Hide)] + public string compatible { get; set; } = "new"; + + [SerializableProperty] + public int added { get; set; } = 17; + public int restoreCount { get; private set; } [OnSerializableRestored] @@ -736,19 +745,44 @@ internal sealed class CurrentSchemaSample : ISerializable internal sealed class DefaultSample : ISerializable { - [SerializableProperty] public bool enabled { get; set; } - [SerializableProperty] public int count { get; set; } - [SerializableProperty] public float ratio { get; set; } - [SerializableProperty] public decimal price { get; set; } - [SerializableProperty] public string name { get; set; } = string.Empty; - [SerializableProperty] public Guid identity { get; set; } - [SerializableProperty] public SampleMode mode { get; set; } - [SerializableProperty] public int? optional { get; set; } - [SerializableProperty] public byte[] bytes { get; set; } = []; - [SerializableProperty] public int[] numbers { get; set; } = []; - [SerializableProperty] public List values { get; set; } = []; - [SerializableProperty] public Dictionary map { get; set; } = []; - [SerializableProperty] public StructSample data { get; set; } + [SerializableProperty] + public bool enabled { get; set; } + + [SerializableProperty] + public int count { get; set; } + + [SerializableProperty] + public float ratio { get; set; } + + [SerializableProperty] + public decimal price { get; set; } + + [SerializableProperty] + public string name { get; set; } = string.Empty; + + [SerializableProperty] + public Guid identity { get; set; } + + [SerializableProperty] + public SampleMode mode { get; set; } + + [SerializableProperty] + public int? optional { get; set; } + + [SerializableProperty] + public byte[] bytes { get; set; } = []; + + [SerializableProperty] + public int[] numbers { get; set; } = []; + + [SerializableProperty] + public List values { get; set; } = []; + + [SerializableProperty] + public Dictionary map { get; set; } = []; + + [SerializableProperty] + public StructSample data { get; set; } } internal struct StructSample @@ -756,7 +790,10 @@ internal struct StructSample public int x; public int y { get; set; } public readonly int readOnly; - [SerializableProperty] private int m_hidden; + + [SerializableProperty] + private int m_hidden; + public readonly int computed => x + m_hidden; public readonly int hidden => m_hidden; @@ -767,7 +804,7 @@ int hidden ) { this.x = x; this.y = y; - readOnly = 99; + this.readOnly = 99; m_hidden = hidden; } @@ -780,18 +817,21 @@ int hidden internal sealed class PrivateConstructorSample : ISerializable { - [SerializableProperty] public int value { get; set; } + [SerializableProperty] + public int value { get; set; } + public bool wasConstructed { get; } private PrivateConstructorSample() { - wasConstructed = true; + this.wasConstructed = true; } } internal sealed class MissingConstructorSample : ISerializable { - [SerializableProperty] public int value { get; set; } + [SerializableProperty] + public int value { get; set; } public MissingConstructorSample(int value) { @@ -837,12 +877,23 @@ internal sealed class MissingRequiredConverterSample : ISerializable; internal sealed class VisibilitySample : ISerializable { - [SerializableProperty] public int shown { get; set; } - [SerializableProperty(PropertyVisibility.Hide)] public int hidden { get; set; } - [SerializableProperty(PropertyVisibility.Readonly)] public int readOnly { get; set; } - [SerializableProperty(PropertyVisibility.Transient)] public int transient { get; set; } - [SerializableProperty(PropertyVisibility.SerializeOnly)] public int serializeOnly { get; set; } - [SerializableProperty(PropertyVisibility.DeserializeOnly)] public int deserializeOnly { get; set; } + [SerializableProperty] + public int shown { get; set; } + + [SerializableProperty(PropertyVisibility.Hide)] + public int hidden { get; set; } + + [SerializableProperty(PropertyVisibility.Readonly)] + public int readOnly { get; set; } + + [SerializableProperty(PropertyVisibility.Transient)] + public int transient { get; set; } + + [SerializableProperty(PropertyVisibility.SerializeOnly)] + public int serializeOnly { get; set; } + + [SerializableProperty(PropertyVisibility.DeserializeOnly)] + public int deserializeOnly { get; set; } } internal sealed class MissingSetterSample : ISerializable @@ -870,12 +921,14 @@ internal sealed class MissingChild internal sealed class MissingClassHost : ISerializable { - [SerializableProperty] public MissingChild? child { get; set; } + [SerializableProperty] + public MissingChild? child { get; set; } } internal sealed class MissingClassCollectionHost : ISerializable { - [SerializableProperty] public List children { get; set; } = []; + [SerializableProperty] + public List children { get; set; } = []; } internal sealed class ConvertedChild @@ -885,7 +938,8 @@ internal sealed class ConvertedChild internal sealed class ConvertedChildHost : ISerializable { - [SerializableProperty] public ConvertedChild? child { get; set; } + [SerializableProperty] + public ConvertedChild? child { get; set; } } internal sealed class CycleValue @@ -895,7 +949,8 @@ internal sealed class CycleValue internal sealed class CycleHost : ISerializable { - [SerializableProperty] public CycleValue? value { get; set; } + [SerializableProperty] + public CycleValue? value { get; set; } } internal sealed class CycleValueConverter : SerializationConverter @@ -930,7 +985,8 @@ internal sealed class NearestLeaf : NearestMid; internal sealed class NearestHost : ISerializable { - [SerializableProperty] public NearestLeaf? item { get; set; } + [SerializableProperty] + public NearestLeaf? item { get; set; } } internal sealed class NearestBaseConverter : SerializationConverter @@ -965,7 +1021,8 @@ internal sealed class ExactLeaf : ExactBase; internal sealed class ExactHost : ISerializable { - [SerializableProperty] public ExactLeaf? item { get; set; } + [SerializableProperty] + public ExactLeaf? item { get; set; } } internal sealed class ExactBaseConverter : SerializationConverter @@ -998,7 +1055,8 @@ internal sealed class AmbiguousValue : IAmbiguousLeft, IAmbiguousRight; internal sealed class AmbiguousHost : ISerializable { - [SerializableProperty] public AmbiguousValue? item { get; set; } + [SerializableProperty] + public AmbiguousValue? item { get; set; } } internal sealed class AmbiguousLeftConverter : SerializationConverter @@ -1033,7 +1091,8 @@ public GenericBox(T value) internal sealed class GenericBoxHost : ISerializable { - [SerializableProperty] public GenericBox? box { get; set; } + [SerializableProperty] + public GenericBox? box { get; set; } } internal sealed class GenericBoxConverter : SerializationConverter> @@ -1073,7 +1132,9 @@ internal sealed class SampleContext : ISampleContext; internal class HookBaseSample : ISerializable { - [SerializableProperty] public int value { get; set; } + [SerializableProperty] + public int value { get; set; } + public List calls { get; } = []; [OnSerializableRestored] diff --git a/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs b/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs index 94783a98e..8dfe7296c 100644 --- a/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs +++ b/tests/editor/Inno.Editor.Audio.Tests/EditorAudioHostTests.cs @@ -11,6 +11,8 @@ using Inno.Runtime; using Inno.Runtime.Contracts; +using RuntimeAudio = Inno.Audio.Audio; + namespace Inno.Editor.Audio.Tests; public sealed class EditorAudioHostTests : IDisposable @@ -53,21 +55,21 @@ public void EditAndPlaySessionsOwnIndependentExecutionScopesAndLifetimes() using RuntimeSession edit = m_engine.CreateSession(CreateOptions(host, RuntimeSessionKind.Edit, "edit")); using (host.EnterExecutionScope(edit)) { - Assert.Equal(AudioDeviceState.Muted, Inno.Audio.Audio.deviceState); + Assert.Equal(AudioDeviceState.Muted, RuntimeAudio.deviceState); } using (RuntimeSession play = m_engine.CreateSession(CreateOptions(host, RuntimeSessionKind.Play, "play"))) { using (host.EnterExecutionScope(play)) { - Assert.Equal(AudioDeviceState.Muted, Inno.Audio.Audio.deviceState); + Assert.Equal(AudioDeviceState.Muted, RuntimeAudio.deviceState); } play.Tick(0.016f); } using (host.EnterExecutionScope(edit)) { - Assert.Equal(AudioDeviceState.Muted, Inno.Audio.Audio.deviceState); + Assert.Equal(AudioDeviceState.Muted, RuntimeAudio.deviceState); } edit.Tick(0.016f); } @@ -112,7 +114,7 @@ string name private AudioClipAsset CreateClip() { var clip = new AudioClipAsset(); - byte[] payload = AudioClipMetadataCodec.Encode(new AudioClipMetadata(AudioCodecId.wav, 1, 48000, 480000, 128)); + byte[] payload = AudioClipMetadataCodec.Encode(new AudioClipMetadata(AudioCodecId.wav, 1, 48_000, 480_000, 128)); new AssetRuntimeOwner().Initialize( clip, AssetPath.Project("Audio/Preview.wav"), @@ -151,7 +153,7 @@ public bool TryGetArtifact( string outputName, out AssetArtifactInfo? artifact ) { - if (outputName == "audio-data" && m_artifacts.TryGetValue(persistentId, out var found)) + if (outputName == "audio-data" && m_artifacts.TryGetValue(persistentId, out (AssetArtifactInfo info, string path) found)) { artifact = found.info; return true; diff --git a/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs b/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs index 3058274a1..6cb96a2c4 100644 --- a/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs +++ b/tests/editor/Inno.Editor.Exporting.Native.Tests/ExportPresentationTests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; @@ -38,10 +39,10 @@ using Inno.Scripting.Compiler; using Inno.Testing.Build; -using EditorUiSession = Inno.Editor.ImGui.EditorUiSession; -using ImGuiEditorRuntime = Inno.Editor.ImGui.ImGuiEditorRuntime; using NativeGui = Inno.Native.ImGui.ImGui; using NativeImGui = Inno.Native.ImGui.ImGui; +using UiRuntime = Inno.Editor.ImGui.ImGuiEditorRuntime; +using UiSession = Inno.Editor.ImGui.EditorUiSession; namespace Inno.Editor.Exporting.Native.Tests; @@ -55,7 +56,7 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe Directory.Delete(Path.Combine(m_supportPackRoot, new BuildTargetId("macos-arm64").value), recursive: true); var provisioner = new DrainingSupportPackProvisioner(); BuildPipeline pipeline = CreatePipeline(provisioner); - var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); + BuildSettings defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); var buildSettings = new BuildSettingsStore( Path.Combine(m_projectRoot, "Settings.Build.inno"), m_engine.serialization, @@ -65,7 +66,7 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe typeof(EditorExportService).Assembly, Assembly.Load(new AssemblyName("Inno.Editor.Workbench")) ]); - var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); + var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); using var runtime = new EditorInteractionRuntime( context, m_engine.types, @@ -80,7 +81,7 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new UiSession(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = new ImVec2C { X = 1200f, Y = 900f }; @@ -124,7 +125,7 @@ public unsafe void EditorShutdownDrainsSupportPackCleanupBeforeReleasingExportSe Assert.True(provisioner.canceled.Task.IsCompletedSuccessfully); Assert.False(provisioner.completed); provisioner.cleanup.SetResult(); - var retirement = System.Diagnostics.Stopwatch.StartNew(); + Stopwatch retirement = Stopwatch.StartNew(); while (true) { try @@ -167,9 +168,9 @@ public unsafe void ExportFormBalancesItsTablesWhenARegisteredTargetLabelFails() [new GameBuildTargetBinding(target, target)], CreateManagedDeployments() ); - var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", target.id); + BuildSettings defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", target.id); var settings = new BuildSettingsStore( - System.IO.Path.Combine(m_projectRoot, "Settings.Build.inno"), + Path.Combine(m_projectRoot, "Settings.Build.inno"), m_engine.serialization, defaults ); @@ -184,7 +185,7 @@ [new GameBuildTargetBinding(target, target)], { NativeGui.Raw.GetIO()->IniFilename = null; m_engine.logs.RegisterSink(logs); - using var session = new EditorUiSession(); + using var session = new UiSession(); using IDisposable scope = session.Enter(); using var runtime = new EditorInteractionRuntime( context, @@ -230,22 +231,26 @@ public unsafe void ExportPresentationUsesTheDeclaredWidthAndRealOverflow( int height, float dpi ) { - var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); - var settings = new BuildSettingsStore(Path.Combine(m_projectRoot, "Settings.Build.inno"), m_engine.serialization, defaults); + BuildSettings defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); + var settings = new BuildSettingsStore( + Path.Combine(m_projectRoot, "Settings.Build.inno"), + m_engine.serialization, + defaults + ); m_engine.modules.Register("Tests.ExportPresentation", [ typeof(EditorExportService).Assembly, Assembly.Load(new AssemblyName("Inno.Editor.Workbench")) ]); - var native = NativeGui.Raw.CreateContext(null); + ImGuiNativeContext* native = NativeGui.Raw.CreateContext(null); try { NativeGui.Raw.GetIO()->IniFilename = null; - var io = NativeGui.Raw.GetIO(); + ImGuiIO* io = NativeGui.Raw.GetIO(); io->DisplaySize = new ImVec2C { X = width, Y = height }; io->DeltaTime = 0.2f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; - using var runtime = new ImGuiEditorRuntime( + using var runtime = new UiRuntime( new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), m_engine.types, m_engine.logs, @@ -261,9 +266,12 @@ float dpi runtime.Draw(); NativeGui.Render(); } - using var title = BGCS.Runtime.Utf8Codec.EncodeNullTerminated("Export as Plugin##export.plugin", allowsNull: false); - var window = NativeGui.Raw.FindWindowByName((sbyte*)title.pointer); - Assert.True(window != null && window->WasActive != 0); + using NativeStringLease title = Utf8Codec.EncodeNullTerminated( + "Export as Plugin##export.plugin", + allowsNull: false + ); + ImGuiWindow* window = NativeGui.Raw.FindWindowByName((sbyte*)title.pointer); + Assert.True(window is not null && window->WasActive != 0); Assert.True(window->Size.X <= width && window->Size.Y <= height); if (width == 1280) { @@ -275,7 +283,7 @@ float dpi { Assert.True(window->ScrollMax.Y > 0f); } - Assert.True(runtime.interactions.TryGetModule(out var exports)); + Assert.True(runtime.interactions.TryGetModule(out EditorExportService? exports)); Assert.False(exports!.progress.isBusy); } finally @@ -296,7 +304,7 @@ EditorModalExtension modal try { bool drawn = modal.Draw(context); - bool leaked = NativeGui.Raw.GetCurrentTable() != null; + bool leaked = NativeGui.Raw.GetCurrentTable() is not null; // Retire only a table opened by this fixture's modal before reporting a failed regression. if (leaked) { diff --git a/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs b/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs index 30a948dc0..205d750da 100644 --- a/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs +++ b/tests/editor/Inno.Editor.Exporting.Tests/ExportWorkflowTests.cs @@ -4,6 +4,7 @@ using Inno.Core.Input; using Inno.Editor.Core; using Inno.Editor.Exporting; +using Inno.Editor.Interactions; using Inno.Testing.Build; namespace Inno.Editor.Exporting.Tests; @@ -13,24 +14,28 @@ public sealed class ExportWorkflowTests : BuildPipelineFixture [Fact] public void ExportPresentationKeepsUnknownProgressAndRejectsStaleCancellation() { - var defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); - var settings = new BuildSettingsStore(Path.Combine(m_projectRoot, "Settings.Build.inno"), m_engine.serialization, defaults); + BuildSettings defaults = BuildSettings.CreateDefault("Test Game", "Scenes/Startup.iscene", new BuildTargetId("macos-arm64")); + var settings = new BuildSettingsStore( + Path.Combine(m_projectRoot, "Settings.Build.inno"), + m_engine.serialization, + defaults + ); m_engine.modules.Register("Tests.ExportProgress", [typeof(EditorExportService).Assembly]); var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")); - using var runtime = new Inno.Editor.Interactions.EditorInteractionRuntime( + using var runtime = new EditorInteractionRuntime( context, m_engine.types, m_engine.logs, [m_pipeline, settings, m_settings] ); runtime.Start(); - Assert.True(runtime.interactions.TryGetModule(out var exports)); + Assert.True(runtime.interactions.TryGetModule(out EditorExportService? exports)); exports!.StartGame(new GameBuildRequest { profile = CreateProfile(new BuildTargetId("macos-arm64")), outputDirectory = Path.Combine(m_root, "ProgressOutput") }); - var observed = exports.progress; + EditorExportProgress observed = exports.progress; Assert.Null(observed.fraction); Assert.True(observed.isBusy); exports.Cancel(observed.operationId - 1); diff --git a/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs b/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs index e1c2ea4ac..5be86417e 100644 --- a/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs +++ b/tests/editor/Inno.Editor.Graph.Tests/GraphDocumentControllerTests.cs @@ -2,10 +2,12 @@ using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; +using System.Text; using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Core.Graphs; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Core; @@ -43,7 +45,7 @@ public GraphDocumentControllerTests() m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); m_runtime = new EditorInteractionRuntime( - new EditorContext(m_testRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_testRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_types, m_logs, [m_serialization, m_sink, m_reloads] @@ -131,7 +133,7 @@ public void OneHundredDocumentCyclesReleasePayloadsAndRejectRetiredControllers() GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); - foreach (var entry in retired) + foreach ((GraphDocumentController controller, WeakReference document) entry in retired) { Assert.False(entry.controller.isAvailable); Assert.False(entry.document.TryGetTarget(out _)); @@ -315,10 +317,10 @@ public void PasteRemapRunsInsideTheSameAtomicHistoryOperation() node, remap ) => - node.SetValue("owner", new(System.Text.Encoding.UTF8.GetBytes(remap[owner].value)))); + node.SetValue("owner", new(Encoding.UTF8.GetBytes(remap[owner].value)))); Assert.Equal( created[0].value, - System.Text.Encoding.UTF8.GetString(controller.document.FindNode(created[1])!.values["owner"].data.Span) + Encoding.UTF8.GetString(controller.document.FindNode(created[1])!.values["owner"].data.Span) ); Assert.True(history.Undo().succeeded); Assert.Equal(2, controller.document.nodes.Count); diff --git a/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs b/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs index cd56ecee3..abda41444 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/EditorApplicationTests.cs @@ -6,7 +6,12 @@ using Inno.Adapter; using Inno.Adapter.Authoring.Default; using Inno.Adapter.Default; +using Inno.Adapter.Platform; +using Inno.Adapter.Platform.Sdl3; using Inno.Adapter.Presentation; +using Inno.Adapter.Presentation.ImGui; +using Inno.Adapter.Rendering; +using Inno.Adapter.Rendering.Bgfx; using Inno.Adapter.Storage; using Inno.Adapter.Storage.FileSystem; using Inno.Build; @@ -17,6 +22,8 @@ using Inno.Core.Input; using Inno.Editor.Core; using Inno.Editor.Hosting; +using Inno.Integration.WindowsX64.Bgfx.Runtime; +using Inno.Integration.WindowsX64.Sdl3; using Inno.Shell; namespace Inno.Editor.Hosting.Tests; @@ -89,22 +96,16 @@ private static EditorLaunchOptions CreateOptions( var adapters = new DefaultAuthoringAdapterCatalog( new DefaultAdapterCatalogOptions { - platform = new Inno.Adapter.Platform.PlatformBackendCatalog( - [new Inno.Adapter.Platform.Sdl3.Sdl3PlatformBackendProvider( - new Inno.Integration.WindowsX64.Sdl3.WindowsX64Sdl3HostIntegration() - )] + platform = new PlatformBackendCatalog( + [new Sdl3PlatformBackendProvider(new WindowsX64Sdl3HostIntegration())] ), - rendering = new Inno.Adapter.Rendering.RenderingBackendCatalog( - [new Inno.Adapter.Rendering.Bgfx.BgfxRenderingBackendProvider( - new Inno.Integration.WindowsX64.Bgfx.Runtime.WindowsX64BgfxSurfaceIntegration() - )] + rendering = new RenderingBackendCatalog( + [new BgfxRenderingBackendProvider(new WindowsX64BgfxSurfaceIntegration())] ), storage = new StorageBackendCatalog([new FileSystemStorageBackendProvider(Path.Combine(project, "Data"))]) }, [new BgfxAuthoringProvider(standard.ResolveShaderTarget(new BuildTargetId("windows-x64")))], - [new Inno.Adapter.Presentation.ImGui.ImGuiPresentationProvider( - new Inno.Adapter.Presentation.ImGui.ImGuiInteractionOptions(false, 1) - )] + [new ImGuiPresentationProvider(new ImGuiInteractionOptions(false, 1))] ); return new EditorLaunchOptions { diff --git a/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs b/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs index 74dfe43df..caa1fb9fa 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/EditorCommandLineOptionsTests.cs @@ -14,7 +14,7 @@ public void DependencySelectionRemainsExplicitAndCannotFallBackToSourcePreparati Assert.Equal(selection, EditorCommandLineOptions.Parse(["project", "--native-dependencies", selection]).nativeDependencies); Assert.Null(EditorCommandLineOptions.Parse(["project"]).nativeDependencies); Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--native-dependencies", "relative.json"])); - Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--native-dependencies", ""])); + Assert.Throws(() => EditorCommandLineOptions.Parse(["project", "--native-dependencies", string.Empty])); Assert.Throws( () => EditorCommandLineOptions.Parse(["project", "--native-dependencies", selection, "--native-dependencies", selection]) ); diff --git a/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs b/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs index 90c4af562..73d8d07ae 100644 --- a/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs +++ b/tests/editor/Inno.Editor.Hosting.Tests/RepositoryWikiTests.cs @@ -2,13 +2,16 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; +using System.Runtime.InteropServices; using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.Cli; using Inno.Build.Toolchains; using Inno.Core.IO; @@ -95,7 +98,7 @@ public void LogicalEditorReferencesIncludeTheSharedProductFeatures() private static void GenerateReferences( string project, - params System.Reflection.Assembly[] roots + params Assembly[] roots ) { string assetsRoot = Path.Combine(project, "Assets"); string pluginsRoot = Path.Combine(project, "Plugins"); @@ -140,14 +143,14 @@ params System.Reflection.Assembly[] roots host.modules.generations ); string dotnetHost = Path.Combine( - Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" ); var compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = project, - compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, project) + compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, project) }, assets, plugins diff --git a/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs index 31547a590..d222e8656 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs @@ -15,6 +15,7 @@ using Inno.Native.ImGui; using NativeGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; namespace Inno.Editor.ImGui.Tests; @@ -22,7 +23,10 @@ public sealed unsafe class DynamicModalTests { private readonly ITestOutputHelper m_output; - public DynamicModalTests(ITestOutputHelper output) => m_output = output; + public DynamicModalTests(ITestOutputHelper output) + { + m_output = output; + } [Fact] [Trait("Acceptance", "Visual")] @@ -66,7 +70,7 @@ int height "First\nSecond", new string('W', 600), "中文状态 / café / Ελληνικά\n" + new string('x', 4000), - "", + string.Empty, "Short" ]; foreach (string text in messages) @@ -148,7 +152,7 @@ public void CurrentActionRectangleCancelsOnceAndBecomesDisabled() host.state.message = "Line one\nLine two\nLine three"; host.Frame(); Vector2 hit = (host.state.actionMin + host.state.actionMax) * 0.5f; - var io = NativeGui.Raw.GetIO(); + ImGuiIO* io = NativeGui.Raw.GetIO(); NativeGui.Raw.AddMousePosEvent(io, hit.X, hit.Y); NativeGui.Raw.AddMouseButtonEvent(io, 0, 1); host.Frame(); @@ -184,10 +188,10 @@ public void DetailsActivityAndActionChangesUseTheCurrentFrameLayout() host.state.showAction = true; host.state.message = "Cancel using the keyboard"; host.Frame(); - var io = NativeGui.Raw.GetIO(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Escape, 1); + ImGuiIO* io = NativeGui.Raw.GetIO(); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Escape, 1); host.Frame(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Escape, 0); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Escape, 0); host.Frame(); Assert.Equal(1, host.state.actions); } @@ -197,17 +201,17 @@ public void DetailsActivityAndActionChangesUseTheCurrentFrameLayout() public void TabAndEnterActivateTheCurrentEnabledAction() { using var host = new ModalHost(); - var io = NativeGui.Raw.GetIO(); - io->ConfigFlags |= (int)Inno.Native.ImGui.ImGuiConfigFlags.NavEnableKeyboard; + ImGuiIO* io = NativeGui.Raw.GetIO(); + io->ConfigFlags |= (int)ImGuiConfigFlags.NavEnableKeyboard; host.Frame(); host.Frame(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Tab, 1); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Tab, 1); host.Frame(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Tab, 0); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Tab, 0); host.Frame(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Enter, 1); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Enter, 1); host.Frame(); - NativeGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Enter, 0); + NativeGui.Raw.AddKeyEvent(io, NativeKey.Enter, 0); host.Frame(); Assert.Equal(1, host.state.actions); } @@ -246,14 +250,14 @@ public void FontAndZoomChangesInvalidatePreparedMeasurementsInTheSameSession() host.Frame(); float originalActionWidth = host.state.actionMax.X - host.state.actionMin.X; float originalHeight = host.state.layout.size.Y; - var io = NativeGui.Raw.GetIO(); - var configuration = NativeGui.Raw.ImFontConfig(); + ImGuiIO* io = NativeGui.Raw.GetIO(); + ImFontConfig* configuration = NativeGui.Raw.ImFontConfig(); try { configuration->SizePixels = 16f; configuration->GlyphExtraAdvanceX = 8f; io->FontDefault = NativeGui.Raw.AddFontDefault(io->Fonts, configuration); - Assert.True(io->FontDefault != null); + Assert.True(io->FontDefault is not null); } finally { @@ -334,7 +338,7 @@ internal ModalHost( Directory.CreateDirectory(m_root); m_native = NativeGui.Raw.CreateContext(null); NativeGui.Raw.SetCurrentContext(m_native); - var io = NativeGui.Raw.GetIO(); + ImGuiIO* io = NativeGui.Raw.GetIO(); io->DisplaySize = new ImVec2C { X = width, Y = height }; io->DeltaTime = 0.2f; io->IniFilename = null; @@ -448,13 +452,13 @@ protected override void OnDraw(EditorContext context) } state.actionMin = NativeGui.GetItemRectMin(); state.scrollMaxX = NativeGui.GetScrollMaxX(); - var window = NativeGui.Raw.GetCurrentWindow(); + ImGuiWindow* window = NativeGui.Raw.GetCurrentWindow(); state.wrapWidth = NativeGui.GetContentRegionAvail().X; state.bodyHeight = state.message.Length == 0 ? 0f : NativeGui.CalcTextSize(state.message, false, state.wrapWidth).Y; state.bodyContentHeight = state.bodyHeight; if (window->DC.ChildWindows.Size > 0) { - var child = window->DC.ChildWindows.Data[0]; + ImGuiWindow* child = window->DC.ChildWindows.Data[0]; state.wrapWidth = child->WorkRect.Max.X - child->WorkRect.Min.X; state.bodyHeight = child->Size.Y; state.bodyContentHeight = child->ContentSize.Y; diff --git a/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs index 6d0181776..1a1b5942f 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/FontCoverageTests.cs @@ -37,10 +37,10 @@ public void EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(float return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow( + using Sdl3PlatformWindow window = application.CreateWindow( new PlatformWindowOptions { title = "Glyph coverage", width = 640, height = 480, visible = false } ); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), @@ -72,7 +72,7 @@ public void EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(float Assert.Equal((uint)value, glyph->Codepoint); Assert.Equal(0u, glyph->SourceIdx); } - ImFontGlyph* icon = NativeImGui.Raw.FindGlyphNoFallback(baked, 0xf0e2); + ImFontGlyph* icon = NativeImGui.Raw.FindGlyphNoFallback(baked, 0xF0E2); Assert.True(icon is not null); Assert.InRange(icon->SourceIdx, 1u, 2u); ImFontGlyph* logo = NativeImGui.Raw.FindGlyphNoFallback(baked, ImGuiIcon.Inno[0]); @@ -81,7 +81,7 @@ public void EveryDefaultTextFaceHasEnglishAndIconsWithoutLanguageFallback(float Assert.Equal(3u, logo->SourceIdx); Assert.True(logo->AdvanceX > 0 && logo->X1 > logo->X0 && logo->Y1 > logo->Y0); Assert.Equal(4, font->Sources.Size); - Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, 0x6f22) is null); + Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, 0x6F22) is null); NativeImGui.TextUnformatted(ImGuiIcon.Inno + " English / undo"); } } @@ -102,10 +102,10 @@ public void SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow() return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow( + using Sdl3PlatformWindow window = application.CreateWindow( new PlatformWindowOptions { title = "Replacement context", width = 320, height = 240, visible = false } ); - var original = application.CreateImGuiContext( + PlatformImGuiContext original = application.CreateImGuiContext( window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), @@ -114,7 +114,7 @@ public void SuccessfulDisposalPermitsReplacementOnTheSameLiveWindow() original.SetIniFile(null); _ = CaptureSource(original); original.Dispose(); - using var replacement = application.CreateImGuiContext( + using PlatformImGuiContext replacement = application.CreateImGuiContext( window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), @@ -134,20 +134,20 @@ public void ApplicationShutdownRetiresBothRegisteredContexts() return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var firstWindow = application.CreateWindow( + using Sdl3PlatformWindow firstWindow = application.CreateWindow( new PlatformWindowOptions { title = "First context", width = 320, height = 240, visible = false } ); - using var secondWindow = application.CreateWindow( + using Sdl3PlatformWindow secondWindow = application.CreateWindow( new PlatformWindowOptions { title = "Second context", width = 320, height = 240, visible = false } ); - var first = application.CreateImGuiContext( + PlatformImGuiContext first = application.CreateImGuiContext( firstWindow, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), new NoOutputRenderer() ); first.SetIniFile(null); - var second = application.CreateImGuiContext( + PlatformImGuiContext second = application.CreateImGuiContext( secondWindow, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), @@ -171,10 +171,10 @@ public void RetiringTenContextsReleasesTheirSourcesAndPreservesAnotherContext() return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow( + using Sdl3PlatformWindow window = application.CreateWindow( new PlatformWindowOptions { title = "Retained font context", width = 320, height = 240, visible = false } ); - using var retained = application.CreateImGuiContext( + using PlatformImGuiContext retained = application.CreateImGuiContext( window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), @@ -203,10 +203,10 @@ public void CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons() return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow( + using Sdl3PlatformWindow window = application.CreateWindow( new PlatformWindowOptions { title = "Custom font", width = 320, height = 240, visible = false } ); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), @@ -226,7 +226,7 @@ public void CustomFontStyleUsesOnlyItsOwnTextSourceAndIcons() Assert.Equal(24f, font->Sources.Data[0]->SizePixels); Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, 'A') is not null); Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, ImGuiIcon.Inno[0]) is not null); - Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, 0x6f22) is null); + Assert.True(NativeImGui.Raw.FindGlyphNoFallback(baked, 0x6F22) is null); }); Assert.Throws(() => context.RegisterFontStyle(BackendFontStyle.Regular, fontPath)); } @@ -252,10 +252,10 @@ private static WeakReference CreateAndRetire( Sdl3PlatformApplication application, nint retainedSource ) { - using var window = application.CreateWindow( + using Sdl3PlatformWindow window = application.CreateWindow( new PlatformWindowOptions { title = "Retired font context", width = 320, height = 240, visible = false } ); - var context = application.CreateImGuiContext( + PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), diff --git a/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs index 09e0f8b16..a60532a0f 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/ImGuiInteractionOptionsTests.cs @@ -22,8 +22,7 @@ int wheelDirection [InlineData(0)] [InlineData(2)] [InlineData(-2)] - public void WheelDirectionCannotSilentlyDisableOrAmplifyInput(int direction) - { - Assert.Throws(() => new ImGuiInteractionOptions(false, direction)); - } + public void WheelDirectionCannotSilentlyDisableOrAmplifyInput(int direction) => Assert.Throws( + () => new ImGuiInteractionOptions(false, direction) + ); } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs index a03830707..62d8a0f38 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/ViewportMetricsTests.cs @@ -12,9 +12,9 @@ using Inno.Native.Sdl3; using Inno.Platform; -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using NativeImGui = Inno.Native.ImGui.ImGui; using NativeVector2 = Inno.Native.ImGui.ImVec2C; +using UiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; [assembly: CollectionBehavior(DisableTestParallelization = true)] @@ -31,14 +31,14 @@ public void FramePreparationRunsBeforeNativeCreationAndRejectsReentrantOperation return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { title = "Prepared presentation frame", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), @@ -81,7 +81,7 @@ public void FailedPreparationDoesNotBeginOrPublishANativeFrame() return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { title = "Failed frame preparation", width = 320, @@ -89,7 +89,7 @@ public void FailedPreparationDoesNotBeginOrPublishANativeFrame() visible = false }); var renderer = new FixtureRenderer(); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), @@ -114,14 +114,14 @@ public void AFailedDrawRetiresItsNativeFrameBeforeTheNextRequest() return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { title = "Failed presentation frame", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), @@ -155,14 +155,14 @@ public void ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability(bool return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { title = "Renderer capability", width = 320, height = 240, visible = false }); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.None, new ImGuiInteractionOptions(false, 1), @@ -171,7 +171,7 @@ public void ContextAdvertisesOnlyTheSelectedRenderersVertexOffsetCapability(bool context.SetIniFile(null); context.RenderFrame(() => Assert.Equal( supported, - (NativeImGui.Raw.GetIO()->BackendFlags & (int)Inno.Native.ImGui.ImGuiBackendFlags.RendererHasVtxOffset) != 0 + (NativeImGui.Raw.GetIO()->BackendFlags & (int)ImGuiBackendFlags.RendererHasVtxOffset) != 0 )); } @@ -186,10 +186,10 @@ public void FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback(bool comm return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow( + using Sdl3PlatformWindow window = application.CreateWindow( new PlatformWindowOptions { title = "Viewport metrics", width = 320, height = 240, visible = false, highPixelDensity = true } ); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(commandKeys, 1), @@ -206,7 +206,7 @@ public void FrameRefreshesDrawableMetricsWithoutAPlatformScaleCallback(bool comm int pixelHeight = 0; SDL.Raw.GetWindowSize((SDLWindow*)window.sdlWindowHandle, &logicalWidth, &logicalHeight); SDL.Raw.GetWindowSizeInPixels((SDLWindow*)window.sdlWindowHandle, &pixelWidth, &pixelHeight); - Vector2 expected = new(pixelWidth / (float)logicalWidth, pixelHeight / (float)logicalHeight); + var expected = new Vector2(pixelWidth / (float)logicalWidth, pixelHeight / (float)logicalHeight); Assert.Equal(expected, Unsafe.BitCast(NativeImGui.Raw.GetMainViewport()->FramebufferScale)); Assert.Equal( SDL.Raw.GetWindowDisplayScale((SDLWindow*)window.sdlWindowHandle) @@ -233,10 +233,10 @@ public void MetricRefreshPreservesRequestedViewportGeometry() return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow( + using Sdl3PlatformWindow window = application.CreateWindow( new PlatformWindowOptions { title = "Viewport geometry owner", width = 320, height = 240, visible = false } ); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), @@ -249,13 +249,13 @@ public void MetricRefreshPreservesRequestedViewportGeometry() Size = Unsafe.BitCast(new Vector2(100, 90)), Pos = Unsafe.BitCast(new Vector2(30, 30)) }; - var io = NativeImGui.Raw.GetPlatformIO(); + ImGuiPlatformIO* io = NativeImGui.Raw.GetPlatformIO(); io->PlatformCreateWindow(&viewport); try { // A drag owns a requested position before UpdatePlatformWindows applies it to SDL. - Vector2 requestedPosition = new(180, 140); - Vector2 requestedSize = new(140, 110); + var requestedPosition = new Vector2(180, 140); + var requestedSize = new Vector2(140, 110); viewport.Pos = viewport.WorkPos = Unsafe.BitCast(requestedPosition); viewport.Size = viewport.WorkSize = Unsafe.BitCast(requestedSize); context.RenderFrame(() => {}); @@ -282,28 +282,28 @@ public void DetachedWindowAppliesRequestsAfterPlatformEventReconciliation() return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow( + using Sdl3PlatformWindow window = application.CreateWindow( new PlatformWindowOptions { title = "Viewport movement", width = 320, height = 240, visible = false } ); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), new FixtureRenderer() ); context.SetIniFile(null); - var io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->ConfigViewportsNoAutoMerge = (true ? (byte)1 : (byte)0); for (int frame = 0; frame < 24; frame++) { - Vector2 requested = new(500 + frame * 7, 200 + frame * 3); + var requested = new Vector2(500 + frame * 7, 200 + frame * 3); uint viewportId = 0; context.RenderFrame(() => { NativeImGui.SetNextWindowPos(requested); NativeImGui.SetNextWindowSize(new Vector2(200, 120)); using NativeStringLease nativeTestText0 = Utf8Codec.EncodeNullTerminated("Detached movement", allowsNull: false); - NativeImGui.Raw.Begin((sbyte*)nativeTestText0.pointer, null, (int)(ImGuiWindowFlags.NoFocusOnAppearing)); + NativeImGui.Raw.Begin((sbyte*)nativeTestText0.pointer, null, (int)(UiWindowFlags.NoFocusOnAppearing)); viewportId = NativeImGui.Raw.GetWindowViewport()->ID; NativeImGui.TextUnformatted("Moving viewport"); NativeImGui.End(); @@ -322,7 +322,7 @@ public void DetachedWindowAppliesRequestsAfterPlatformEventReconciliation() context.RenderFrame(() => { using NativeStringLease nativeTestText1 = Utf8Codec.EncodeNullTerminated("Detached movement", allowsNull: false); - NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, (int)(ImGuiWindowFlags.NoFocusOnAppearing)); + NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, (int)(UiWindowFlags.NoFocusOnAppearing)); Assert.Equal(requested, NativeImGui.GetWindowPos()); NativeImGui.TextUnformatted("Moving viewport"); NativeImGui.End(); @@ -339,10 +339,10 @@ public void LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame( return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow( + using Sdl3PlatformWindow window = application.CreateWindow( new PlatformWindowOptions { title = "Logical DPI transition", width = 320, height = 240, visible = false } ); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), @@ -351,7 +351,7 @@ public void LogicalDpiTransitionRetainsThePreviousScaleUntilImGuiStartsItsFrame( context.SetIniFile(null); float previous = 0f; context.RenderFrame(() => previous = NativeImGui.Raw.GetMainViewport()->DpiScale); - var io = NativeImGui.Raw.GetPlatformIO(); + ImGuiPlatformIO* io = NativeImGui.Raw.GetPlatformIO(); Assert.True(io->Monitors.Size > 0); for (int index = 0; index < io->Monitors.Size; index++) { @@ -370,11 +370,11 @@ public void ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestructi return; } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow( + using Sdl3PlatformWindow window = application.CreateWindow( new PlatformWindowOptions { title = "Viewport ownership", width = 320, height = 240, visible = false } ); var renderer = new FixtureRenderer(); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), @@ -387,12 +387,12 @@ public void ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestructi Size = Unsafe.BitCast(new Vector2(100, 90)), Pos = Unsafe.BitCast(new Vector2(30, 30)) }; - var io = NativeImGui.Raw.GetPlatformIO(); + ImGuiPlatformIO* io = NativeImGui.Raw.GetPlatformIO(); io->PlatformCreateWindow(&viewport); try { Assert.Equal(2, application.GetWindows().Count); - var target = Assert.IsType(renderer.target); + PlatformImGuiViewportTarget target = Assert.IsType(renderer.target); Assert.True(context.TryGetWindowId(viewport.ID, out uint id)); Assert.Equal(target.windowId, id); Assert.Equal(target.nativeHandles.windowHandle, (nint)viewport.PlatformHandleRaw); @@ -405,7 +405,7 @@ public void ViewportCallbacksRegisterOneSurfaceAndReleaseItBeforeNativeDestructi Assert.Single(application.GetWindows()); Assert.Null(renderer.target); - Assert.True(viewport.PlatformUserData == null); + Assert.True(viewport.PlatformUserData is null); } private sealed class FixtureRenderer : IPlatformImGuiRenderer diff --git a/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs index 582b75bcc..0e105441e 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/ViewportRetirementTests.cs @@ -31,7 +31,7 @@ public void FaultedRetirementRetainsWindowRendererAndApplicationOwners() // A failed retirement intentionally retains dependencies until the host process restarts. // Run this contract in its own test process, rather than forcing unsafe cleanup. var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - var window = application.CreateWindow(new PlatformWindowOptions + Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { title = "Faulted retirement", width = 320, @@ -39,7 +39,7 @@ public void FaultedRetirementRetainsWindowRendererAndApplicationOwners() visible = false }); var renderer = new PendingRenderer(); - var context = application.CreateImGuiContext( + PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), @@ -47,7 +47,7 @@ public void FaultedRetirementRetainsWindowRendererAndApplicationOwners() ); context.SetIniFile(null); var viewport = new ImGuiViewport { ID = 4221, Size = Unsafe.BitCast(new Vector2(100, 90)) }; - var io = NativeImGui.Raw.GetPlatformIO(); + ImGuiPlatformIO* io = NativeImGui.Raw.GetPlatformIO(); io->PlatformCreateWindow(&viewport); uint id = renderer.target!.windowId; io->PlatformDestroyWindow(&viewport); @@ -56,7 +56,7 @@ public void FaultedRetirementRetainsWindowRendererAndApplicationOwners() Assert.Throws(() => context.RenderFrame(static () => {})); Assert.Throws(() => application.DestroyImGuiContext(window)); Assert.Throws(() => application.Dispose()); - Assert.False((SDL.Raw.GetWindowFromId(id) == null)); + Assert.False((SDL.Raw.GetWindowFromId(id) is null)); Assert.Equal(0, renderer.disposeCount); GC.KeepAlive(context); GC.KeepAlive(application); @@ -72,7 +72,7 @@ public void DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement() } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { title = "Retirement owner", width = 320, @@ -80,7 +80,7 @@ public void DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement() visible = false }); var renderer = new PendingRenderer(); - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), @@ -93,7 +93,7 @@ public void DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement() Size = Unsafe.BitCast(new Vector2(100, 90)), Pos = Unsafe.BitCast(new Vector2(30, 30)) }; - var io = NativeImGui.Raw.GetPlatformIO(); + ImGuiPlatformIO* io = NativeImGui.Raw.GetPlatformIO(); io->PlatformCreateWindow(&viewport); uint id = renderer.target!.windowId; @@ -101,15 +101,15 @@ public void DetachedWindowRemainsAliveUntilRenderingAcknowledgesRetirement() Assert.Single(application.GetWindows()); Assert.False(context.TryGetWindowId(viewport.ID, out _)); - Assert.True(viewport.PlatformUserData == null); - Assert.False((SDL.Raw.GetWindowFromId(id) == null)); + Assert.True(viewport.PlatformUserData is null); + Assert.False((SDL.Raw.GetWindowFromId(id) is null)); context.RenderFrame(static () => {}); - Assert.False((SDL.Raw.GetWindowFromId(id) == null)); + Assert.False((SDL.Raw.GetWindowFromId(id) is null)); Assert.Equal(1, renderer.retireCount); renderer.Complete(); context.RenderFrame(static () => {}); - Assert.True((SDL.Raw.GetWindowFromId(id) == null)); + Assert.True((SDL.Raw.GetWindowFromId(id) is null)); context.RenderFrame(static () => {}); Assert.Equal(1, renderer.retireCount); } @@ -124,7 +124,7 @@ public void IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoi } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { title = "Pending drain", width = 320, @@ -132,7 +132,7 @@ public void IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoi visible = false }); var renderer = new PendingRenderer(); - var context = application.CreateImGuiContext( + PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), @@ -149,7 +149,7 @@ public void IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoi uint id = renderer.target!.windowId; Assert.Throws(() => application.DestroyImGuiContext(window)); - Assert.False((SDL.Raw.GetWindowFromId(id) == null)); + Assert.False((SDL.Raw.GetWindowFromId(id) is null)); Assert.Equal(0, renderer.disposeCount); var replacement = new PendingRenderer(); Assert.Throws(() => application.CreateImGuiContext( @@ -162,7 +162,7 @@ public void IncompleteDrainRetainsContextOwnershipAndCanFinishAtTheNextSafetyPoi renderer.Complete(); application.DestroyImGuiContext(window); - Assert.True((SDL.Raw.GetWindowFromId(id) == null)); + Assert.True((SDL.Raw.GetWindowFromId(id) is null)); Assert.Equal(1, renderer.disposeCount); context.Dispose(); application.DestroyImGuiContext(window); @@ -180,7 +180,7 @@ public void CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup() } using var application = new Sdl3PlatformApplication(NativeHostFixture.Create()); - using var window = application.CreateWindow(new PlatformWindowOptions + using Sdl3PlatformWindow window = application.CreateWindow(new PlatformWindowOptions { title = "Failed creation", width = 320, @@ -188,7 +188,7 @@ public void CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup() visible = false }); var renderer = new PendingRenderer { failCreation = true }; - using var context = application.CreateImGuiContext( + using PlatformImGuiContext context = application.CreateImGuiContext( window, ImGuiContextFlags.EnableViewports, new ImGuiInteractionOptions(false, 1), @@ -199,11 +199,11 @@ public void CreationFailureIsReportedAtAManagedSafetyPointAfterCleanup() NativeImGui.Raw.GetPlatformIO()->PlatformCreateWindow(&viewport); uint id = renderer.target!.windowId; Assert.Single(application.GetWindows()); - Assert.False((SDL.Raw.GetWindowFromId(id) == null)); + Assert.False((SDL.Raw.GetWindowFromId(id) is null)); renderer.Complete(); Assert.Throws(() => context.RenderFrame(static () => {})); - Assert.True((SDL.Raw.GetWindowFromId(id) == null)); + Assert.True((SDL.Raw.GetWindowFromId(id) is null)); context.RenderFrame(static () => {}); } diff --git a/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs index a9b4e3288..63c942a2c 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/WidgetLayoutTests.cs @@ -1,17 +1,28 @@ using System; +using System.IO; using System.Numerics; using System.Runtime.CompilerServices; using BGCS.Runtime; using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Core.Diagnostics; +using Inno.Core.Input; +using Inno.Core.Logging; +using Inno.Editor.Core; +using Inno.Editor.ImGui.ImGuiWidget; +using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; using Inno.Native.ImGui; using EditorImGui = Inno.Editor.ImGui.ImGui; using EditorUI = Inno.Editor.ImGui.EditorUiSession; -using ImGuiCond = Inno.Editor.ImGui.ImGuiCond; -using ImGuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using NativeImGui = Inno.Native.ImGui.ImGui; +using NativeKey = Inno.Native.ImGui.ImGuiKey; using NativeVector2 = Inno.Native.ImGui.ImVec2C; +using UiCond = Inno.Editor.ImGui.ImGuiCond; +using UiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; +using UiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using Widget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; namespace Inno.Editor.ImGui.Tests; @@ -21,7 +32,7 @@ public sealed unsafe class WidgetLayoutTests [Fact] public void PackedColorConversionMatchesNativeSaturationRoundingAndChannelOrder() { - using (NativeContext context = new(1f)) + using (var context = new NativeContext(1f)) { context.Frame(() => { @@ -85,8 +96,8 @@ public void StandaloneMetricsApplyImmediatelyAndRetainedMetricsDoNotRootTheirRet [Fact] public void StyleRequestsDoNotChangeTheActiveNativeFrame() { - using NativeContext context = new(1f); - var widgets = EditorUI.current.widgets; + using var context = new NativeContext(1f); + Widget widgets = EditorUI.current.widgets; for (int frame = 0; frame < 2; frame++) { context.Frame(() => @@ -124,8 +135,8 @@ public void StyleRequestsDoNotChangeTheActiveNativeFrame() [Fact] public void AForeignNativeContextCannotPublishChangesIntoASuspendedOwnerFrame() { - using NativeContext context = new(1f); - var widgets = EditorUI.current.widgets; + using var context = new NativeContext(1f); + Widget widgets = EditorUI.current.widgets; context.Frame(() => { widgets.SetupStyle(); @@ -164,7 +175,7 @@ public void AForeignNativeContextCannotPublishChangesIntoASuspendedOwnerFrame() [Fact] public void CopiedWindowGeometryRequiresAnActiveNativeFrame() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); Assert.Throws(() => EditorImGui.GetClipBounds()); Assert.Throws(() => EditorImGui.GetWindowBounds()); context.Frame(() => @@ -172,7 +183,7 @@ public void CopiedWindowGeometryRequiresAnActiveNativeFrame() BeginWindow("Geometry owner", new(400f, 300f)); try { - var clip = EditorImGui.GetClipBounds(); + (Vector2 minimum, Vector2 maximum) clip = EditorImGui.GetClipBounds(); Assert.True(clip.maximum.X > clip.minimum.X && clip.maximum.Y > clip.minimum.Y); Assert.True(EditorImGui.GetWindowBounds().maximumX > EditorImGui.GetWindowBounds().minimumX); } @@ -188,7 +199,7 @@ public void CopiedWindowGeometryRequiresAnActiveNativeFrame() [Fact] public void FlattenedRowsRetainExpansionWithoutOwningNativeTreeScopes() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); for (int frame = 0; frame < 3; frame++) { context.Frame(() => @@ -196,17 +207,17 @@ public void FlattenedRowsRetainExpansionWithoutOwningNativeTreeScopes() BeginWindow("Flattened tree", new(400f, 300f)); try { - var widgets = EditorUI.current.widgets; + Widget widgets = EditorUI.current.widgets; widgets.SetTreeNodeOpen("root", true); ulong revision = widgets.treeExpansionRevision; widgets.SetTreeNodeOpen("root", true); Assert.Equal(revision, widgets.treeExpansionRevision); int nativeDepth = NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth; - var root = widgets.TreeNode("root", _ => NativeImGui.TextUnformatted("Root"), new() { depth = 0 }); + TreeNodeResult root = widgets.TreeNode("root", _ => NativeImGui.TextUnformatted("Root"), new() { depth = 0 }); Assert.True(root.isOpen); Assert.True(widgets.IsTreeNodeOpen("root")); Assert.Equal(nativeDepth, NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth); - var child = widgets.TreeNode( + TreeNodeResult child = widgets.TreeNode( "child", _ => NativeImGui.TextUnformatted("Deep child"), new() { depth = 7, isLeaf = true } @@ -233,14 +244,14 @@ public void FlattenedRowsRetainExpansionWithoutOwningNativeTreeScopes() [Fact] public void TenThousandTreeRowsSubmitCustomContentOnlyWithinTheViewport() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); for (int frame = 0; frame < 3; frame++) { context.Frame(() => { BeginWindow("Large tree", new(400f, 300f)); int drawn = 0; - Action draw = _ => + Action draw = _ => { drawn++; NativeImGui.TextUnformatted("Visible content"); @@ -262,7 +273,7 @@ public void TenThousandTreeRowsSubmitCustomContentOnlyWithinTheViewport() [Fact] public void FixedRowsRetainExplicitRowsAndBalanceTheirNativeOwner() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); context.Frame(() => { BeginWindow("Clipped rows", new(400f, 300f)); @@ -291,7 +302,7 @@ public void FixedRowsRetainExplicitRowsAndBalanceTheirNativeOwner() [Fact] public void FixedRowFailureReleasesTheClipperBeforeTheNextFrame() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); for (int frame = 0; frame < 2; frame++) { context.Frame(() => @@ -324,23 +335,23 @@ public void FixedRowFailureReleasesTheClipperBeforeTheNextFrame() [InlineData(1.5f)] public void TrendUsesOneBoundedRegionAndFiniteGeometry(float zoom) { - using NativeContext context = new(zoom); + using var context = new NativeContext(zoom); context.Frame(() => { BeginWindow("Trend bounds", new Vector2(400f, 400f)); - var widgets = EditorUI.current.widgets; - widgets.Trend("Finite extremes", new[] { float.MinValue, 0f, float.MaxValue }, offset: 1); + Widget widgets = EditorUI.current.widgets; + widgets.Trend("Finite extremes", [float.MinValue, 0f, float.MaxValue], offset: 1); Assert.Equal(widgets.style.trendHeight, NativeImGui.GetItemRectSize().Y, 3); Assert.True(NativeImGui.GetItemRectSize().X <= 400f); - var draw = NativeImGui.Raw.GetWindowDrawList(); + ImDrawList* draw = NativeImGui.Raw.GetWindowDrawList(); for (int index = 0; index < draw->VtxBuffer.Size; index++) { Vector2 point = Unsafe.BitCast(draw->VtxBuffer.Data[index].Pos); Assert.True(float.IsFinite(point.X) && float.IsFinite(point.Y)); } - widgets.Trend("Empty", ReadOnlySpan.Empty); - Assert.Throws(() => widgets.Trend("Offset", new[] { 1f }, offset: 1)); - Assert.Throws(() => widgets.Trend("Invalid", new[] { float.NaN })); + widgets.Trend("Empty", []); + Assert.Throws(() => widgets.Trend("Offset", [1f], offset: 1)); + Assert.Throws(() => widgets.Trend("Invalid", [float.NaN])); NativeImGui.End(); }); } @@ -348,35 +359,32 @@ public void TrendUsesOneBoundedRegionAndFiniteGeometry(float zoom) [Fact] public void ListNavigationUsesVisibleIndicesAndRespectsTextAndPopupOwnership() { - string root = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "InnoListNavigation", Guid.NewGuid().ToString("N")); - System.IO.Directory.CreateDirectory(root); + string root = Path.Combine(Path.GetTempPath(), "InnoListNavigation", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); try { - var diagnostics = new Inno.Core.Diagnostics.DiagnosticHub(); + var diagnostics = new DiagnosticHub(); using IDisposable diagnosticScope = diagnostics.EnterScope(); - using var modules = new Inno.Extensibility.Modules.ModuleHost(new() + using var modules = new ModuleHost(new() { - catalogSource = new Inno.Adapter.Modules.DotNet.DotNetAssemblyCatalogSource(typeof(WidgetLayoutTests).Assembly) + catalogSource = new DotNetAssemblyCatalogSource(typeof(WidgetLayoutTests).Assembly) }); - using var types = new Inno.Extensibility.Types.TypeCatalog( - modules, - new Inno.Adapter.Modules.DotNet.ReflectionTypeCatalogSource() - ); - using var logs = new Inno.Core.Logging.LogRouter(); - using var runtime = new Inno.Editor.Interactions.EditorInteractionRuntime( + using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); + using var logs = new LogRouter(); + using var runtime = new EditorInteractionRuntime( root, types, logs, - new Inno.Editor.Core.EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super") + new EditorKeyboardPolicy(KeyModifier.Control, "Super") ); runtime.Start(); - using NativeContext context = new(1f); - NativeImGui.Raw.GetIO()->ConfigFlags |= (int)Inno.Native.ImGui.ImGuiConfigFlags.NavEnableKeyboard; + using var context = new NativeContext(1f); + NativeImGui.Raw.GetIO()->ConfigFlags |= (int)ImGuiConfigFlags.NavEnableKeyboard; int focused = 4; bool textInput = false; bool popup = false; string query = string.Empty; - Inno.Editor.ImGui.ImGuiWidget.ListNavigationResult observed = default; + ListNavigationResult observed = default; Action draw = () => { BeginWindow("List navigation", new Vector2(500f, 400f)); @@ -400,40 +408,40 @@ public void ListNavigationUsesVisibleIndicesAndRespectsTextAndPopupOwnership() }; context.Frame(draw); context.Frame(draw); - var io = NativeImGui.Raw.GetIO(); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.PageDown, 1); + ImGuiIO* io = NativeImGui.Raw.GetIO(); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.PageDown, 1); context.Frame(draw); Assert.Equal(14, focused); Assert.True(observed.selectionRequested); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.PageDown, 0); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.PageDown, 0); context.Frame(draw); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.End, 1); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.End, 1); context.Frame(draw); Assert.Equal(99, focused); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.End, 0); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.End, 0); context.Frame(draw); textInput = true; context.Frame(draw); context.Frame(draw); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Home, 1); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.Home, 1); context.Frame(draw); Assert.Equal(99, focused); Assert.False(observed.selectionRequested); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.Home, 0); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.Home, 0); context.Frame(draw); textInput = false; popup = true; context.Frame(draw); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.UpArrow, 1); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.UpArrow, 1); context.Frame(draw); Assert.Equal(99, focused); Assert.False(observed.selectionRequested); - NativeImGui.Raw.AddKeyEvent(io, Inno.Native.ImGui.ImGuiKey.UpArrow, 0); + NativeImGui.Raw.AddKeyEvent(io, NativeKey.UpArrow, 0); context.Frame(draw); } finally { - System.IO.Directory.Delete(root, recursive: true); + Directory.Delete(root, recursive: true); } } @@ -445,7 +453,7 @@ public void ListNavigationUsesVisibleIndicesAndRespectsTextAndPopupOwnership() [InlineData("tree-overlay")] public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); for (int frame = 0; frame < 2; frame++) { context.Frame(() => @@ -454,7 +462,7 @@ public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) nint window = (nint)NativeImGui.Raw.GetCurrentWindow(); int depth = NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth; Vector2 padding = Unsafe.BitCast(NativeImGui.Raw.GetStyle()->FramePadding); - var widgets = EditorUI.current.widgets; + Widget widgets = EditorUI.current.widgets; Action rejected = () => throw new InvalidOperationException("Rejected extension draw"); Assert.Throws(() => { @@ -486,7 +494,7 @@ public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) Assert.Equal(depth, NativeImGui.Raw.GetCurrentWindow()->DC.TreeDepth); Assert.Equal(padding, Unsafe.BitCast(NativeImGui.Raw.GetStyle()->FramePadding)); widgets.SetNextTreeNodeOpen(true); - var next = widgets.TreeNode("next-tree", _ => EditorImGui.Text("Next valid row"), new()); + TreeNodeResult next = widgets.TreeNode("next-tree", _ => EditorImGui.Text("Next valid row"), new()); Assert.True(next.isOpen); NativeImGui.TreePop(); EditorImGui.GetDrawList().Line(new(30f, 30f), new(60f, 60f), uint.MaxValue); @@ -498,8 +506,8 @@ public void ExtensionDrawingFailureRestoresTheEnclosingWindow(string failure) [Fact] public void DrawingBorrowRejectsAnotherWindowOrFrame() { - using NativeContext context = new(1f); - Inno.Editor.ImGui.EditorDrawList borrow = default; + using var context = new NativeContext(1f); + EditorDrawList borrow = default; context.Frame(() => { BeginWindow("Drawing owner", new Vector2(400f, 300f)); @@ -516,13 +524,13 @@ public void DrawingBorrowRejectsAnotherWindowOrFrame() Assert.Throws(() => borrow.Line(Vector2.Zero, Vector2.One, 0)); NativeImGui.End(); }); - Assert.Throws(() => default(Inno.Editor.ImGui.EditorDrawList).Line(Vector2.Zero, Vector2.One, 0)); + Assert.Throws(() => default(EditorDrawList).Line(Vector2.Zero, Vector2.One, 0)); } [Fact] public void BoundedTextControlsDoNotAllocateOneBufferAndEncoderPerSubmission() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); string value = "Unicode: 漢字 😀"; long allocated = 0; Action draw = () => @@ -548,7 +556,7 @@ public void BoundedTextControlsDoNotAllocateOneBufferAndEncoderPerSubmission() [Fact] public void TimelineWorkspace_UsesOneBoundedChildScrollOwner() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); float childScroll = 0f; float parentScroll = 0f; for (int frame = 0; frame < 4; frame++) @@ -592,7 +600,7 @@ public void TimelineWorkspace_UsesOneBoundedChildScrollOwner() [Fact] public void TimelinePointer_UsesCumulativeUiDragUntilRelease() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); Vector2 hit = default; Vector2 drag = default; bool held = false; @@ -604,7 +612,7 @@ public void TimelinePointer_UsesCumulativeUiDragUntilRelease() hit = (EditorImGui.GetItemMinimum() + EditorImGui.GetItemMaximum()) * 0.5f; active = EditorImGui.IsItemActive(); held = EditorImGui.IsMouseButtonDown(); - drag = EditorImGui.GetMouseDragDelta(ImGuiMouseButton.Left, 0f); + drag = EditorImGui.GetMouseDragDelta(UiMouseButton.Left, 0f); NativeImGui.End(); }; context.Frame(draw); @@ -633,7 +641,7 @@ public void TimelinePointer_UsesCumulativeUiDragUntilRelease() [InlineData(1.5f)] public void PropertyRows_WrapWithinTwoToThreeColumnsWithoutScrollbars(float zoom) { - using NativeContext context = new(zoom); + using var context = new NativeContext(zoom); Vector2 labelSize = default; float labelWidth = 0f; float valueWidth = 0f; @@ -685,7 +693,7 @@ public void BoundedSelectors_OpenDownwardAndScrollOnlyWhenRequired( bool shouldScroll, float zoom ) { - using NativeContext context = new(zoom); + using var context = new NativeContext(zoom); Vector2 controlMinimum = default; Vector2 controlMaximum = default; Vector2 popupPosition = default; @@ -738,7 +746,7 @@ float zoom [InlineData(320f)] public void SelectorsNearWindowBottom_UseOnlyRemainingDownwardSpace(float verticalOffset) { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); Vector2 controlMinimum = default; Vector2 controlMaximum = default; Vector2 popupPosition = default; @@ -786,7 +794,7 @@ public void SelectorsNearWindowBottom_UseOnlyRemainingDownwardSpace(float vertic [InlineData(1.1f)] public void ContextMenu_SearchFillsItsActualContentWidthWithoutScrollbars(float zoom) { - using NativeContext context = new(zoom); + using var context = new NativeContext(zoom); Vector2 controlMinimum = default; Vector2 controlMaximum = default; Vector2 scroll = default; @@ -830,7 +838,7 @@ public void ContextMenu_SearchFillsItsActualContentWidthWithoutScrollbars(float [Fact] public void OverlappingWindows_OnlyForegroundClickableTextReceivesPress() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); int backgroundPresses = 0; int foregroundPresses = 0; Vector2 hit = default; @@ -868,13 +876,13 @@ public void TreeRows_ContentClickIsDeliveredOnce( bool isLeaf, float zoom ) { - using NativeContext context = new(zoom); + using var context = new NativeContext(zoom); int presses = 0; Vector2 hit = default; Action draw = () => { BeginWindow("Tree content", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode( + TreeNodeResult result = EditorUI.current.widgets.TreeNode( $"content-{isLeaf}-{zoom}", _ => EditorUI.current.widgets.IconText("O", "Selected object", false), new() @@ -908,14 +916,14 @@ float zoom [Fact] public void TreeRows_DisclosureClickExpandsWithoutSelectingContent() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); int presses = 0; bool opened = false; Vector2 hit = default; Action draw = () => { BeginWindow("Tree disclosure", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode( + TreeNodeResult result = EditorUI.current.widgets.TreeNode( "disclosure", _ => NativeImGui.TextUnformatted("Parent"), new() { isLeaf = false } @@ -945,14 +953,14 @@ public void TreeRows_DisclosureClickExpandsWithoutSelectingContent() [InlineData(false)] public void TreeRows_OverlayConsumesItsOwnClick(bool settleHover) { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); int rowPresses = 0; int overlayPresses = 0; Vector2 overlayHit = default; Action draw = () => { BeginWindow("Tree overlay", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode( + TreeNodeResult result = EditorUI.current.widgets.TreeNode( $"overlay-{settleHover}", _ => NativeImGui.TextUnformatted("Object"), new() @@ -986,7 +994,7 @@ public void TreeRows_OverlayConsumesItsOwnClick(bool settleHover) [Fact] public void TreeRows_ContentDoubleClickExpandsOnce() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); int presses = 0; int doublePresses = 0; bool opened = false; @@ -994,7 +1002,7 @@ public void TreeRows_ContentDoubleClickExpandsOnce() Action draw = () => { BeginWindow("Tree double click", new Vector2(400f, 300f)); - var result = EditorUI.current.widgets.TreeNode( + TreeNodeResult result = EditorUI.current.widgets.TreeNode( "double-click", _ => NativeImGui.TextUnformatted("Parent"), new() { isLeaf = false } @@ -1028,11 +1036,11 @@ public void TreeRows_ContentDoubleClickExpandsOnce() [Fact] public void MixedValueRestoresOuterStateAfterNestedGroupsAndFailures() { - using NativeContext context = new(1f); + using var context = new NativeContext(1f); context.Frame(() => { BeginWindow("Mixed scope", new Vector2(400f, 300f)); - var widgets = EditorUI.current.widgets; + Widget widgets = EditorUI.current.widgets; Assert.False(widgets.isMixedValue); widgets.MixedValue(true, () => { @@ -1052,7 +1060,7 @@ public void MixedValueRestoresOuterStateAfterNestedGroupsAndFailures() [MethodImpl(MethodImplOptions.NoInlining)] private static EditorStyleMetrics RetireStyleOwner(out WeakReference owner) { - using var session = new EditorUiSession(); + using EditorUI session = new EditorUiSession(); owner = new WeakReference(session); return session.widgets.style; } @@ -1061,20 +1069,20 @@ private static void BeginWindow( string name, Vector2 size ) { - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(size, (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(UiCond.Always), default); + NativeImGui.SetNextWindowSize(size, (int)(UiCond.Always)); using NativeStringLease nativeTestText0 = Utf8Codec.EncodeNullTerminated(name, allowsNull: false); NativeImGui.Raw.Begin( (sbyte*)nativeTestText0.pointer, null, - (int)(ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoSavedSettings) + (int)(UiWindowFlags.NoTitleBar | UiWindowFlags.NoResize | UiWindowFlags.NoMove | UiWindowFlags.NoSavedSettings) ); } private sealed class NativeContext : IDisposable { private readonly ImGuiNativeContext* m_context; - private readonly Inno.Editor.ImGui.EditorUiSession m_ui = new(); + private readonly EditorUI m_ui = new(); private readonly IDisposable m_uiScope; public NativeContext(float zoom) diff --git a/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs b/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs index 38f878294..6108b970d 100644 --- a/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs +++ b/tests/editor/Inno.Editor.Inspection.Tests/ConditionalInspectionTests.cs @@ -1,9 +1,11 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Annotations; @@ -30,7 +32,7 @@ public ConditionalInspectionTests() m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); m_runtime = new( - new EditorContext(m_root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_types, m_logs, [m_types, m_serialization] @@ -42,12 +44,32 @@ public ConditionalInspectionTests() public void ConditionalInspectorPeersResolveByPredicateAndRejectActualAmbiguity() { using var properties = new PropertyDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - var renderer = new SerializedPropertyRenderer(properties, attributes, m_runtime.interactions, new ProbePropertyEdits(), m_logs); - using var inspectors = new InspectionDrawerRegistry(m_runtime.interactions, CreateDrawer, m_types, m_serialization); - Assert.True(inspectors.TryResolve(m_runtime.context, new ConditionalTarget(1, false), renderer, out var first, out _)); + using var attributes = new InspectorAttributeDrawerRegistry( + m_runtime.interactions, + m_types, + m_serialization, + [] + ); + var renderer = new SerializedPropertyRenderer( + properties, + attributes, + m_runtime.interactions, + new ProbePropertyEdits(), + m_logs + ); + using var inspectors = new InspectionDrawerRegistry( + m_runtime.interactions, + CreateDrawer, + m_types, + m_serialization + ); + Assert.True( + inspectors.TryResolve(m_runtime.context, new ConditionalTarget(1, false), renderer, out IInspectionDrawer? first, out _) + ); Assert.IsType(first); - Assert.True(inspectors.TryResolveExact(m_runtime.context, new ConditionalTarget(2, false), renderer, out var second, out _)); + Assert.True( + inspectors.TryResolveExact(m_runtime.context, new ConditionalTarget(2, false), renderer, out IInspectionDrawer? second, out _) + ); Assert.IsType(second); InvalidOperationException error = Assert.Throws( () => inspectors.TryResolve(m_runtime.context, new ConditionalTarget(2, true), renderer, out _, out _) @@ -63,10 +85,21 @@ public void ConditionalInspectorPeersResolveByPredicateAndRejectActualAmbiguity( public void PropertyAvailabilityUsesCurrentOwnerConditionsWithoutRequiringNativeUi() { using var properties = new PropertyDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - var renderer = new SerializedPropertyRenderer(properties, attributes, m_runtime.interactions, new ProbePropertyEdits(), m_logs); + using var attributes = new InspectorAttributeDrawerRegistry( + m_runtime.interactions, + m_types, + m_serialization, + [] + ); + var renderer = new SerializedPropertyRenderer( + properties, + attributes, + m_runtime.interactions, + new ProbePropertyEdits(), + m_logs + ); var target = new AvailabilityTarget(); - var values = m_serialization.GetProperties(target); + IReadOnlyList values = m_serialization.GetProperties(target); SerializedProperty conditional = values.Single(value => value.name == nameof(AvailabilityTarget.value)); Assert.False(renderer.GetPropertyAvailability(target, conditional).isVisible); target.visible = true; @@ -84,10 +117,12 @@ public sealed class AvailabilityTarget : ISerializable { public bool visible { get; set; } - [SerializableProperty, ShowIf(nameof(visible))] + [SerializableProperty] + [ShowIf(nameof(visible))] public int value { get; set; } - [SerializableProperty, InspectorReadOnly] + [SerializableProperty] + [InspectorReadOnly] public int readOnlyValue { get; set; } } @@ -99,7 +134,7 @@ bool ambiguous [InspectionDrawer(typeof(ConditionalTarget), conditional: true)] public sealed class ConditionalFirst : InspectionDrawer { - public override string icon => ""; + public override string icon => string.Empty; protected override bool CanInspect(ConditionalTarget target) => target.kind == 1; @@ -117,7 +152,7 @@ ConditionalTarget target [InspectionDrawer(typeof(ConditionalTarget), conditional: true)] public sealed class ConditionalSecond : InspectionDrawer { - public override string icon => ""; + public override string icon => string.Empty; protected override bool CanInspect(ConditionalTarget target) => target.kind == 2; @@ -135,7 +170,7 @@ ConditionalTarget target [InspectionDrawer(typeof(ConditionalTarget), conditional: true)] public sealed class ConditionalOverlap : InspectionDrawer { - public override string icon => ""; + public override string icon => string.Empty; protected override bool CanInspect(ConditionalTarget target) => target.ambiguous; diff --git a/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs b/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs index 71c885c76..6eff66bd5 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs @@ -3,6 +3,7 @@ using System.IO; using Xunit; using Inno.Adapter.Modules.DotNet; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Editor.Interactions; @@ -252,7 +253,7 @@ public void MissingHandlerCreatesAnExplicitAvailabilityBarrier() public void LargePayloadUsesTheBoundedSessionDiskStore() { using var fixture = new HistoryFixture(); - byte[] payload = new byte[128 * 1024]; + var payload = new byte[128 * 1024]; BitConverter.GetBytes(1).CopyTo(payload, 0); BitConverter.GetBytes(9).CopyTo(payload, sizeof(int)); BitConverter.GetBytes(32).CopyTo(payload, sizeof(int) * 2); @@ -294,9 +295,9 @@ internal HistoryFixture() m_modules = new ModuleHost( new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorHistoryTests).Assembly) } ); - types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - runtime = new EditorInteractionRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + this.types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); + this.runtime = new EditorInteractionRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), types, m_logs, [types] @@ -335,7 +336,7 @@ public static EditorHistoryChange CreateChange( int after, string? mergeKey = null ) { - byte[] bytes = new byte[sizeof(int) * 3]; + var bytes = new byte[sizeof(int) * 3]; BitConverter.GetBytes(slot).CopyTo(bytes, 0); BitConverter.GetBytes(before).CopyTo(bytes, sizeof(int)); BitConverter.GetBytes(after).CopyTo(bytes, sizeof(int) * 2); diff --git a/tests/editor/Inno.Editor.Interactions.Tests/EditorPlanarNavigationTests.cs b/tests/editor/Inno.Editor.Interactions.Tests/EditorPlanarNavigationTests.cs index e243462ec..d34bcd8f1 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/EditorPlanarNavigationTests.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/EditorPlanarNavigationTests.cs @@ -30,7 +30,8 @@ public void AltOrbitDoesNotStealPanAndCancelReleasesCapture() [Fact] public void ZoomPreservesPointerAnchorAndIsIndependentOfDisplayDensity() { - Vector2 origin = new(50, 30), pivot = new(110, 150); + var origin = new Vector2(50, 30); + var pivot = new Vector2(110, 150); float scale = EditorPlanarNavigation.WheelFactor(3); Vector2 updated = EditorPlanarNavigation.ZoomOrigin(origin, pivot, 1, scale); Assert.True(Vector2.Distance(pivot - origin, (pivot - updated) / scale) < 0.0001f); diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs index 6f1315fcb..04c16fd76 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs @@ -1,6 +1,7 @@ using System; using Xunit; using Inno.Core.Identity; +using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Types; using Inno.Scene; @@ -14,8 +15,8 @@ public sealed partial class SceneHistoryTests public void BatchPropertyEditPreservesIndependentBeforeValuesInOneUndo() { GameScene scene = CreateScene(); - var first = scene.CreateObject("First").AddComponent(); - var second = scene.CreateObject("Second").AddComponent(); + HistoryComponent first = scene.CreateObject("First").AddComponent(); + HistoryComponent second = scene.CreateObject("Second").AddComponent(); first.value = 12; second.value = 34; Assert.False(m_edits.HaveSamePropertyValues([first, second], "value")); @@ -35,8 +36,8 @@ public void BatchPropertyEditPreservesIndependentBeforeValuesInOneUndo() public void BatchAxisEditPreservesUneditedComponentsIncludingEqualPrimarySamples() { GameScene scene = CreateScene(); - var first = scene.CreateObject("First").transform; - var second = scene.CreateObject("Second").transform; + Transform first = scene.CreateObject("First").transform; + Transform second = scene.CreateObject("Second").transform; first.localPosition = new(1, 2, 3); second.localPosition = new(4, 5, 6); Assert.True( @@ -48,11 +49,11 @@ public void BatchAxisEditPreservesUneditedComponentsIncludingEqualPrimarySamples componentName: "x" ) ); - Assert.Equal(new Inno.Core.Mathematics.Vector3(9, 5, 6), second.localPosition); + Assert.Equal(new Vector3(9, 5, 6), second.localPosition); Assert.True(m_runtime.interactions.history.Undo().succeeded); - Assert.Equal(new Inno.Core.Mathematics.Vector3(4, 5, 6), second.localPosition); + Assert.Equal(new Vector3(4, 5, 6), second.localPosition); Assert.True(m_edits.ChangeProperties([first, second], "localPosition", () => {}, "Use Primary X", componentName: "x")); - Assert.Equal(new Inno.Core.Mathematics.Vector3(1, 5, 6), second.localPosition); + Assert.Equal(new Vector3(1, 5, 6), second.localPosition); Assert.Throws( () => m_edits.ChangeProperties( [first, second], @@ -62,15 +63,15 @@ public void BatchAxisEditPreservesUneditedComponentsIncludingEqualPrimarySamples componentName: "notAComponent" ) ); - Assert.Equal(new Inno.Core.Mathematics.Vector3(1, 2, 3), first.localPosition); + Assert.Equal(new Vector3(1, 2, 3), first.localPosition); } [Fact] public void LaterBatchSetterFailureRestoresAllEarlierTargets() { GameScene scene = CreateScene(); - var first = scene.CreateObject("First").AddComponent(); - var second = scene.CreateObject("Second").AddComponent(); + BatchValidationComponent first = scene.CreateObject("First").AddComponent(); + BatchValidationComponent second = scene.CreateObject("Second").AddComponent(); first.value = 12; second.value = 34; second.rejectAnswer = true; diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs index 4c4696e42..5e0505513 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs @@ -8,7 +8,9 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Identity; +using Inno.Core.Input; using Inno.Core.Logging; +using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Scene; @@ -67,7 +69,7 @@ public SceneHistoryTests() )with { enableFileSystemWatcher = false } ); m_runtime = new EditorInteractionRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_host.types, m_host.logs, [m_host.types, m_host.serialization, m_session, m_assets, m_reloads] @@ -95,7 +97,7 @@ public void PropertyUndoRestoresOnlyThePropertyOnTheExistingSceneGraph() { GameScene scene = CreateScene(); GameObject gameObject = scene.CreateObject("Object"); - var component = gameObject.AddComponent(); + HistoryComponent component = gameObject.AddComponent(); component.value = 10; Guid sceneId = scene.identity.persistentId; Guid objectId = gameObject.identity.persistentId; @@ -123,7 +125,7 @@ public void PropertyUndoRestoresOnlyThePropertyOnTheExistingSceneGraph() [Fact] public void PropertyUndoRestoresEverySiblingChangedByThePrimarySetter() { - var component = CreateScene().CreateObject("Coupled").AddComponent(); + CoupledHistoryComponent component = CreateScene().CreateObject("Coupled").AddComponent(); Assert.True(component.primary); Assert.Equal(CoupledHistoryMode.Base, component.mode); Assert.True( @@ -151,9 +153,9 @@ public void TransformManipulationTransactionUndoesAllLocalValuesAtomically() { GameObject gameObject = CreateScene().CreateObject("Manipulated"); Transform transform = gameObject.transform; - var position = new Inno.Core.Mathematics.Vector3(3f, -2f, 4f); - Inno.Core.Mathematics.Quaternion rotation = Inno.Core.Mathematics.Quaternion.CreateFromYawPitchRoll(0.2f, 0.3f, 0.4f); - var scale = new Inno.Core.Mathematics.Vector3(2f, 3f, 4f); + var position = new Vector3(3f, -2f, 4f); + Quaternion rotation = Quaternion.CreateFromYawPitchRoll(0.2f, 0.3f, 0.4f); + var scale = new Vector3(2f, 3f, 4f); using (EditorHistoryTransaction transaction = m_runtime.interactions.history.BeginTransaction("Move GameObject")) { Assert.True( @@ -180,9 +182,9 @@ public void TransformManipulationTransactionUndoesAllLocalValuesAtomically() Assert.Equal("Move GameObject", m_runtime.interactions.history.undoName); Assert.True(m_runtime.interactions.history.Undo().succeeded); - Assert.Equal(Inno.Core.Mathematics.Vector3.ZERO, transform.localPosition); - Assert.Equal(Inno.Core.Mathematics.Quaternion.identity, transform.localRotation); - Assert.Equal(Inno.Core.Mathematics.Vector3.ONE, transform.localScale); + Assert.Equal(Vector3.ZERO, transform.localPosition); + Assert.Equal(Quaternion.identity, transform.localRotation); + Assert.Equal(Vector3.ONE, transform.localScale); Assert.True(m_runtime.interactions.history.Redo().succeeded); Assert.Equal(position, transform.localPosition); Assert.Equal(rotation, transform.localRotation); @@ -194,13 +196,13 @@ public void WorldPositionEditRestoresLocalStorageAndWorldResultThroughHistory() { GameScene scene = CreateScene(); Transform parent = scene.CreateObject("Parent").transform; - parent.localPosition = new Inno.Core.Mathematics.Vector3(3f, -2f, 4f); - parent.localScale = new Inno.Core.Mathematics.Vector3(2f, 3f, 4f); + parent.localPosition = new Vector3(3f, -2f, 4f); + parent.localScale = new Vector3(2f, 3f, 4f); Transform child = scene.CreateObject("Child").transform; child.SetParent(parent); - var beforeLocal = child.localPosition; - var beforeWorld = child.worldPosition; - var requestedWorld = new Inno.Core.Mathematics.Vector3(11f, 7f, 20f); + Vector3 beforeLocal = child.localPosition; + Vector3 beforeWorld = child.worldPosition; + var requestedWorld = new Vector3(11f, 7f, 20f); Assert.True( m_edits.ChangeProperty( child, @@ -209,7 +211,7 @@ public void WorldPositionEditRestoresLocalStorageAndWorldResultThroughHistory() "Edit World Position" ) ); - var afterLocal = child.localPosition; + Vector3 afterLocal = child.localPosition; Assert.Equal(requestedWorld, child.worldPosition); Assert.NotEqual(beforeLocal, afterLocal); Assert.True(m_runtime.interactions.history.Undo().succeeded); @@ -225,15 +227,15 @@ public void ComponentAddRemoveResetAndOrderPreserveLogicalIdentity() { GameScene scene = CreateScene(); GameObject gameObject = scene.CreateObject("Object"); - var first = (HistoryComponent)m_edits.AddComponent(gameObject, typeof(HistoryComponent)); + HistoryComponent first = (HistoryComponent)m_edits.AddComponent(gameObject, typeof(HistoryComponent)); Guid firstId = first.identity.persistentId; Assert.True(m_runtime.interactions.history.Undo().succeeded); Assert.Null(IdentityAllocator.current.Get(firstId)); Assert.True(m_runtime.interactions.history.Redo().succeeded); - var restoredFirst = Assert.IsType(IdentityAllocator.current.Get(firstId)); + HistoryComponent restoredFirst = Assert.IsType(IdentityAllocator.current.Get(firstId)); Assert.NotSame(first, restoredFirst); Assert.Equal(7, restoredFirst.value); - var second = (HistoryComponent)m_edits.AddComponent(gameObject, typeof(HistoryComponent)); + HistoryComponent second = (HistoryComponent)m_edits.AddComponent(gameObject, typeof(HistoryComponent)); m_edits.SetComponentIndex(second, 1); Assert.Equal(1, gameObject.GetComponentIndex(second)); Assert.True(m_runtime.interactions.history.Undo().succeeded); @@ -247,7 +249,7 @@ public void ComponentAddRemoveResetAndOrderPreserveLogicalIdentity() Assert.True(m_edits.RemoveComponent(restoredFirst)); Assert.Null(IdentityAllocator.current.Get(firstId)); Assert.True(m_runtime.interactions.history.Undo().succeeded); - var restoredAgain = Assert.IsType(IdentityAllocator.current.Get(firstId)); + HistoryComponent restoredAgain = Assert.IsType(IdentityAllocator.current.Get(firstId)); Assert.Equal(99, restoredAgain.value); } @@ -261,13 +263,15 @@ public void RemovingComponentRestoresSerializedAssetReferences() Assert.True(m_assets.Import(assetPath)); TextAsset asset = m_assets.Load(assetPath); GameObject owner = CreateScene().CreateObject("Audio Source Owner"); - var component = owner.AddComponent(); + HistoryAssetReferenceComponent component = owner.AddComponent(); component.asset = asset; Guid componentId = component.identity.persistentId; Assert.True(m_edits.RemoveComponent(component)); EditorHistoryResult undo = m_runtime.interactions.history.Undo(); Assert.True(undo.succeeded, undo.message); - var restored = Assert.IsType(IdentityAllocator.current.Get(componentId)); + HistoryAssetReferenceComponent restored = Assert.IsType( + IdentityAllocator.current.Get(componentId) + ); Assert.Same(asset, restored.asset); Assert.True(m_runtime.interactions.history.Redo().succeeded); Assert.Null(IdentityAllocator.current.Get(componentId)); @@ -531,10 +535,10 @@ public void RemovingAnElementAndSubtreeRestoresExternalSceneReferences() GameObject targetObject = scene.CreateObject("Target"); GameObject targetChild = scene.CreateObject("Child"); targetChild.transform.SetParent(targetObject.transform); - var targetComponent = targetChild.AddComponent(); + HistoryComponent targetComponent = targetChild.AddComponent(); targetComponent.value = 41; GameObject referenceObject = scene.CreateObject("References"); - var references = referenceObject.AddComponent(); + HistoryReferenceComponent references = referenceObject.AddComponent(); references.targetComponent = targetComponent; references.targetObject = targetChild; Guid componentId = targetComponent.identity.persistentId; @@ -543,7 +547,7 @@ public void RemovingAnElementAndSubtreeRestoresExternalSceneReferences() Assert.True(m_edits.RemoveComponent(targetComponent)); EditorHistoryResult restoreComponentResult = m_runtime.interactions.history.Undo(); Assert.True(restoreComponentResult.succeeded, restoreComponentResult.message); - var restoredComponent = Assert.IsType(IdentityAllocator.current.Get(componentId)); + HistoryComponent restoredComponent = Assert.IsType(IdentityAllocator.current.Get(componentId)); Assert.Same(restoredComponent, references.targetComponent); Assert.Equal(41, restoredComponent.value); Assert.True(m_edits.DeleteGameObject(targetObject)); @@ -562,7 +566,7 @@ public void ElementRestoreRejectsAnotherLogicalTypesPayloadBeforeAttachingElemen { GameScene scene = CreateScene(); GameObject sourceObject = scene.CreateObject("Source"); - var source = sourceObject.AddComponent(); + HistoryReferenceComponent source = sourceObject.AddComponent(); byte[] incompatibleState = SceneElementSerialization.CaptureState(source, m_host.serialization, m_assets); GameObject owner = scene.CreateObject("Owner"); TypeRef componentType = m_host.types.GetTypeRef(typeof(HistoryComponent)); @@ -602,7 +606,7 @@ public void ElementRestoreRemovesPartialElementWhenRestoreCallbackFails() { GameScene scene = CreateScene(); GameObject sourceOwner = scene.CreateObject("Source"); - var source = sourceOwner.AddComponent(); + RestoreCleanupFailureComponent source = sourceOwner.AddComponent(); byte[] state = SceneElementSerialization.CaptureState(source, m_host.serialization, m_assets); GameObject targetOwner = scene.CreateObject("Target"); TypeRef typeRef = m_host.types.GetTypeRef(typeof(RestoreCleanupFailureComponent)); @@ -702,8 +706,8 @@ public void HierarchyUndoRestoresOnlyAffectedPlacements() public void SystemHistoryPreservesIdentityStateAndExplicitOrder() { GameScene scene = CreateScene(); - var first = (HistorySystem)m_edits.AddSystem(scene, typeof(HistorySystem)); - var second = (HistorySystem)m_edits.AddSystem(scene, typeof(HistorySystem)); + HistorySystem first = (HistorySystem)m_edits.AddSystem(scene, typeof(HistorySystem)); + HistorySystem second = (HistorySystem)m_edits.AddSystem(scene, typeof(HistorySystem)); first.value = 30; Guid firstId = first.identity.persistentId; m_edits.SetSystemIndex(scene, second, 0); @@ -716,7 +720,7 @@ public void SystemHistoryPreservesIdentityStateAndExplicitOrder() Assert.Equal(30, first.value); Assert.True(m_edits.RemoveSystem(first)); Assert.True(m_runtime.interactions.history.Undo().succeeded); - var restored = Assert.IsType(IdentityAllocator.current.Get(firstId)); + HistorySystem restored = Assert.IsType(IdentityAllocator.current.Get(firstId)); Assert.Equal(30, restored.value); } @@ -837,10 +841,7 @@ internal sealed class HistoryComponent : GameBehavior [SerializableProperty] public int value { get; set; } - protected override void Reset() - { - value = 7; - } + protected override void Reset() => value = 7; } internal enum CoupledHistoryMode @@ -902,10 +903,7 @@ internal sealed class HistorySystem : GameSystem [SerializableProperty] public int value { get; set; } - protected override void Reset() - { - value = 11; - } + protected override void Reset() => value = 11; } [StableTypeId("71cc27da-2c47-47f2-a037-c9bc29615358")] diff --git a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs index e32f32b4e..118a26a1f 100644 --- a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs +++ b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Input.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Numerics; @@ -32,7 +33,10 @@ public sealed partial class LargePanelPerformanceTests [Trait("Acceptance", "Performance")] public unsafe void LargeViewsMeasureActualInputAndContinuousEditWork(string scenario) { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); bool hierarchy = scenario.StartsWith("hierarchy", StringComparison.Ordinal); GameScene? scene = hierarchy ? LoadInteractionHierarchy(host) : null; if (!hierarchy) @@ -200,7 +204,7 @@ Action operation } int repetitions = int.Parse( Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_REPETITIONS") ?? "5", - System.Globalization.CultureInfo.InvariantCulture + CultureInfo.InvariantCulture ); Assert.InRange(repetitions, 1, 5); using Process process = Process.GetCurrentProcess(); diff --git a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs index fc9d36278..c7e6b30e5 100644 --- a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs +++ b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.Workflows.cs @@ -25,7 +25,10 @@ public sealed partial class LargePanelPerformanceTests [Trait("Acceptance", "Workflows")] public unsafe void TenThousandEntriesKeepRangeRenameAndDragAcrossClippedRows(string view) { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); bool hierarchy = view == "hierarchy"; GameScene? scene = hierarchy ? LoadInteractionHierarchy(host) : null; if (!hierarchy) diff --git a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs index b15fe21fc..dfa76849e 100644 --- a/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs +++ b/tests/editor/Inno.Editor.Performance.Tests/LargePanelPerformanceTests.cs @@ -1,14 +1,17 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; +using System.Runtime.InteropServices; using System.Text.Json; using System.Threading; using Xunit; using Xunit.Abstractions; using Inno.Assets; +using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Editor.Interactions; using Inno.Scene; @@ -22,8 +25,11 @@ public sealed partial class LargePanelPerformanceTests(ITestOutputHelper output) [Trait("Acceptance", "Performance")] public void DueDirtyInspectionsMeasureTheCompleteSavedSceneTraversal() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); - Inno.Scene.GameScene scene = LoadSavedHierarchy(host); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); + GameScene scene = LoadSavedHierarchy(host); Measure( host, null, @@ -37,13 +43,16 @@ public void DueDirtyInspectionsMeasureTheCompleteSavedSceneTraversal() [Trait("Acceptance", "Performance")] public void ChangedDirtyInspectionsMeasureTheCompleteSavedSceneTraversal() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); GameScene scene = LoadSavedHierarchy(host); GameObject value = scene.GetObjects()[0]; int revision = 0; Measure(host, null, "10000-hierarchy-dirty-edits", () => { - value.transform.localPosition = new Inno.Core.Mathematics.Vector3(++revision % 2 + 1, 0, 0); + value.transform.localPosition = new Vector3(++revision % 2 + 1, 0, 0); Assert.True(host.workspace.IsDirty(scene)); }, static () => Thread.Sleep(110), consumer: "complete-authoritative-dirty-inspection-after-each-owned-write"); } @@ -52,8 +61,11 @@ public void ChangedDirtyInspectionsMeasureTheCompleteSavedSceneTraversal() [Trait("Acceptance", "Performance")] public void NeutralCaptureSeparatesSerializationFromSourceFreshness() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); - Inno.Scene.GameScene scene = LoadSavedHierarchy(host); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); + GameScene scene = LoadSavedHierarchy(host); SerializationContext context = AssetSerializationContext.Create( host.assets, new AssetDependencyCollection(includeLastKnownPaths: false) @@ -73,8 +85,11 @@ public void NeutralCaptureSeparatesSerializationFromSourceFreshness() [Trait("Acceptance", "Performance")] public void SourceFreshnessMeasuresTheActualSavedSceneLoadBoundary() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); - Inno.Scene.GameScene scene = LoadSavedHierarchy(host); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); + GameScene scene = LoadSavedHierarchy(host); Assert.True(host.workspace.TryGetSourcePath(scene, out string path)); SceneAsset asset = host.assets.Load(AssetPath.Project(path)); Measure( @@ -90,7 +105,10 @@ public void SourceFreshnessMeasuresTheActualSavedSceneLoadBoundary() [Trait("Acceptance", "Performance")] public void SceneMetadataReadsMeasureTheOwnedAttachmentBoundary() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); GameScene scene = LoadSavedHierarchy(host); IReadOnlyList objects = scene.GetObjects(); long checksum = 0; @@ -111,7 +129,10 @@ public void SceneMetadataReadsMeasureTheOwnedAttachmentBoundary() [Trait("Acceptance", "Performance")] public void TenThousandHierarchyRowsProduceRepeatableFrameMeasurements() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); string? input = InputDirectory("hierarchy"); if (input is not null && Directory.Exists(input)) { @@ -121,7 +142,7 @@ public void TenThousandHierarchyRowsProduceRepeatableFrameMeasurements() } else { - var scene = host.CreateScene(); + GameScene scene = host.CreateScene(); for (int index = 0; index < 10_000; index++) { _ = scene.CreateObject("Object " + index.ToString("D5")); @@ -140,7 +161,10 @@ public void TenThousandHierarchyRowsProduceRepeatableFrameMeasurements() [Trait("Acceptance", "Performance")] public void TenThousandAssetRowsProduceRepeatableFrameMeasurements() { - using var host = new NativeProjectPanelHost(typeof(LargePanelPerformanceTests).Assembly, supportsVertexOffsets: true); + using var host = new NativeProjectPanelHost( + typeof(LargePanelPerformanceTests).Assembly, + supportsVertexOffsets: true + ); string? input = InputDirectory("assets"); if (input is not null && Directory.Exists(input)) { @@ -163,10 +187,10 @@ public void TenThousandAssetRowsProduceRepeatableFrameMeasurements() Measure(host, panel, "10000-asset-directory-rows"); } - private static Inno.Scene.GameScene LoadSavedHierarchy(NativeProjectPanelHost host) + private static GameScene LoadSavedHierarchy(NativeProjectPanelHost host) { string? input = InputDirectory("hierarchy"); - Inno.Scene.GameScene scene; + GameScene scene; if (input is not null && Directory.Exists(input)) { CopyDirectory(input, Path.Combine(host.projectRoot, "Assets")); @@ -222,7 +246,7 @@ private void Measure( operation(); } string? requested = Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_REPETITIONS"); - int repetitions = requested is null ? 5 : int.Parse(requested, System.Globalization.CultureInfo.InvariantCulture); + int repetitions = requested is null ? 5 : int.Parse(requested, CultureInfo.InvariantCulture); Assert.InRange(repetitions, 1, 5); using Process process = Process.GetCurrentProcess(); var samples = new List(); @@ -268,7 +292,7 @@ private void Measure( ?.Configuration ?? throw new InvalidOperationException("The benchmark assembly has no SDK configuration metadata."), samples, - framework = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, + framework = RuntimeInformation.FrameworkDescription, viewport = "1000x800", warmupFrames = 5, measuredFramesPerRepetition = 10, diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs index d58756851..40cab55da 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsolePanelNativeLayoutTests.cs @@ -9,6 +9,8 @@ using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Core.Diagnostics; +using Inno.Core.Events; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Editor.Core; using Inno.Editor.Diagnostics; @@ -20,6 +22,7 @@ using ImGuiApi = Inno.Native.ImGui.ImGui; using NativeVector2 = Inno.Native.ImGui.ImVec2C; +using Ui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.PlayMode.Tests; @@ -50,7 +53,7 @@ public void SnapshotFailureQuarantinesTheConsoleWithoutLeakingChildWindows() using IDisposable diagnosticScope = diagnostics.EnterScope(); using var ui = new EditorUiSession(); using var runtime = new EditorInteractionRuntime( - new EditorContext(root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(root, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), types, logs, [new RejectedConsole()] @@ -72,7 +75,7 @@ [new RejectedConsole()] Assert.False(panel.isOpen); } Assert.Equal(parent, (nint)ImGuiApi.Raw.GetCurrentWindow()); - Inno.Editor.ImGui.ImGui.Text("Following valid drawing"); + Ui.Text("Following valid drawing"); ImGuiApi.End(); ImGuiApi.Render(); } @@ -113,10 +116,10 @@ float scale var hub = new DiagnosticHub(); using var console = new EditorConsole(logs, hub, new InactivePlayMode()); console.Start(); - using var reporter = hub.CreateReporter(new("shader", "Rendering")); + using DiagnosticReporter reporter = hub.CreateReporter(new("shader", "Rendering")); using var ui = new EditorUiSession(); using var runtime = new EditorInteractionRuntime( - new EditorContext(root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(root, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), types, logs, [console] @@ -148,7 +151,8 @@ void Draw(float width) ImGuiApi.Render(); Assert.Single(console.Capture().occurrences); } - Draw(960); Draw(960); + Draw(960); + Draw(960); ImGuiWindow* card = default; for (int i = 0; i < context->Windows.Size; i++) { @@ -158,29 +162,32 @@ void Draw(float width) card = window; } } - Assert.True(card != null); + Assert.True(card is not null); ImGuiTable* header = FindActiveTable(card, 3); - Assert.True(header != null); - Vector2 toggle = new(header->Columns.Data[0].WorkMinX + 6, header->RowPosY1 + ImGuiApi.GetFontSize() / 2); + Assert.True(header is not null); + var toggle = new Vector2(header->Columns.Data[0].WorkMinX + 6, header->RowPosY1 + ImGuiApi.GetFontSize() / 2); ImGuiApi.Raw.AddMousePosEvent(ImGuiApi.Raw.GetIO(), toggle.X, toggle.Y); Draw(960); Assert.True( context->HoveredId != 0, $"No toggle hovered: {toggle}; window {Marshal.PtrToStringUTF8((nint)context->HoveredWindow->Name)}" ); - ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (true ? (byte)1 : (byte)0)); Draw(960); + ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (true ? (byte)1 : (byte)0)); + Draw(960); Assert.True(context->ActiveId != 0, "Toggle did not activate."); - ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (false ? (byte)1 : (byte)0)); Draw(960); + ImGuiApi.Raw.AddMouseButtonEvent(ImGuiApi.Raw.GetIO(), 0, (false ? (byte)1 : (byte)0)); + Draw(960); // Switching from fixed height to AutoResizeY uses a native measurement frame. Draw(960); foreach (float width in new[] { 960f, 500f, 260f, 140f, 960f }) { Draw(width); ImGuiTable* table = FindActiveTable(card, 2); - bool details = table != null && table->LastFrameActive == ImGuiApi.GetFrameCount(); + bool details = table is not null && table->LastFrameActive == ImGuiApi.GetFrameCount(); if (details) { - ImGuiTableColumn label = table->Columns.Data[0], value = table->Columns.Data[1]; + ImGuiTableColumn label = table->Columns.Data[0]; + ImGuiTableColumn value = table->Columns.Data[1]; Assert.True(label.WidthGiven >= ImGuiApi.CalcTextSize("Session:").X - 1); Assert.True(value.MinX > label.MinX + ImGuiApi.CalcTextSize("Source:").X); Assert.True(label.ClipRect.Max.X >= label.WorkMinX + ImGuiApi.CalcTextSize("Source:").X); @@ -231,7 +238,7 @@ private sealed class InactivePlayMode : IEditorPlayMode public bool isPlaying => false; public string? lastFailure => null; public LogSessionId activeSessionId => LogSessionId.none; - private readonly Inno.Core.Events.EventDispatcher m_stateDispatcher = new(); + private readonly EventDispatcher m_stateDispatcher = new(); public IDisposable ListenStateChanges(Action listener) => m_stateDispatcher.CreateHub(); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs index c4d931850..2a0b6f0bd 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleSearchNativeTests.cs @@ -29,16 +29,16 @@ float height using var host = new NativePanelHost(typeof(ConsoleSearchNativeTests).Assembly, "Inno.Editor.Panel.Logging"); host.SetDisplayMetrics(new(width, height), density, zoom); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); for (int occurrence = 0; occurrence < 2; occurrence++) { logger.Write(LogLevel.Info, "Needle message"); } logger.Write(LogLevel.Warn, "Unrelated message"); - string longMessage = new('x', 300); + var longMessage = new string('x', 300); logger.Write(LogLevel.Info, longMessage); host.logs.Flush(); - using var reporter = host.diagnostics.CreateReporter(new("search-source", "SOURCE-NAME")); + using DiagnosticReporter reporter = host.diagnostics.CreateReporter(new("search-source", "SOURCE-NAME")); reporter.Publish( new("SEARCH_CODE", "A diagnostic", DiagnosticSeverity.Error, location: new DiagnosticLocation("Assets/漢字.shader", 42, 3)) ); @@ -70,7 +70,7 @@ float height using var host = new NativePanelHost(typeof(ConsoleSearchNativeTests).Assembly, "Inno.Editor.Panel.Logging"); host.SetDisplayMetrics(new(width, height), density, zoom); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); for (int occurrence = 0; occurrence < 2; occurrence++) { logger.Write(LogLevel.Info, "Needle message"); @@ -94,7 +94,10 @@ float height Assert.True(card->Size.Y > collapsedHeight + 1f); host.DrawPanel(panel, () => { - var context = host.runtime.interactions.For(host.runtime.interactions.focusedArea, host.runtime.interactions.focusedTarget); + EditorInteraction context = host.runtime.interactions.For( + host.runtime.interactions.focusedArea, + host.runtime.interactions.focusedTarget + ); Assert.True(context.Execute("console/copy-message")); Assert.Equal("Needle message", Marshal.PtrToStringUTF8((nint)NativeImGui.Raw.GetClipboardText())); Assert.True(context.Execute("console/copy-details")); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs index a1801ad19..b2b0e6f7c 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ConsoleVirtualizationNativeTests.cs @@ -20,7 +20,7 @@ public void RetiringTheContextRecordClosesItsPopup(bool clear) { using var host = new NativePanelHost(typeof(ConsoleVirtualizationNativeTests).Assembly, "Inno.Editor.Panel.Logging"); host.console.capacity = 16; - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); logger.Write(LogLevel.Info, "Original context record"); host.logs.Flush(); @@ -71,7 +71,7 @@ public void RepeatedContextMenusDoNotAccumulateRetiredOccurrenceWindows() { using var host = new NativePanelHost(typeof(ConsoleVirtualizationNativeTests).Assembly, "Inno.Editor.Panel.Logging"); host.console.capacity = 16; - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); ImGuiIO* io = NativeGui.Raw.GetIO(); for (int iteration = 0; iteration < 100; iteration++) @@ -113,7 +113,7 @@ public void TenThousandOccurrencesSubmitOnlyViewportCardsAndKeepKeyboardNavigati { using var host = new NativePanelHost(typeof(ConsoleVirtualizationNativeTests).Assembly, "Inno.Editor.Panel.Logging"); host.console.capacity = 10_000; - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); for (int index = 0; index < 10_000; index++) { logger.Write(LogLevel.Info, "Entry " + index.ToString("D5") + "\nDetails / 资源信息"); @@ -145,7 +145,7 @@ public void RetiredOccurrencesDoNotAccumulateNativeChildWindows() { using var host = new NativePanelHost(typeof(ConsoleVirtualizationNativeTests).Assembly, "Inno.Editor.Panel.Logging"); host.console.capacity = 16; - var logger = host.logs.CreateLogger(); + Logger logger = host.logs.CreateLogger(); EditorPanelExtension panel = host.GetPanel("diagnostics.console"); for (int iteration = 0; iteration < 150; iteration++) { diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs index dc94422a5..ad7cd33f5 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/DefaultLayoutNativeTests.cs @@ -37,7 +37,10 @@ float height ); using var types = new TypeCatalog(modules, new EmptyTypeSource()); using var logs = new LogRouter(); - var context = new EditorContext(host.runtime.context.projectDirectory, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")); + var context = new EditorContext( + host.runtime.context.projectDirectory, + new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl") + ); using var runtime = new ImGuiEditorRuntime(context, types, logs, []); ImGuiIO* io = NativeGui.Raw.GetIO(); io->ConfigFlags |= (int)ImGuiConfigFlags.DockingEnable; @@ -76,7 +79,7 @@ float height } }); } - foreach (var rectangle in rectangles.Values) + foreach ((Vector2 position, Vector2 size, uint dock) rectangle in rectangles.Values) { Assert.NotEqual(0u, rectangle.dock); Assert.True(rectangle.size.X > 0f && rectangle.size.Y > 0f); @@ -93,8 +96,8 @@ float height Assert.True(rectangles["Inspector"].position.X > rectangles["Hierarchy"].position.X); Assert.True(rectangles["Console"].position.Y > rectangles["Inspector"].position.Y); Assert.InRange(rectangles["File"].size.X / width, 0.43f, 0.49f); - Assert.InRange(rectangles["Hierarchy"].size.X / width, 0.25f, 0.30f); - Assert.InRange(rectangles["Inspector"].size.X / width, 0.25f, 0.30f); + Assert.InRange(rectangles["Hierarchy"].size.X / width, 0.25f, 0.3f); + Assert.InRange(rectangles["Inspector"].size.X / width, 0.25f, 0.3f); } private sealed class EmptyTypeSource : ITypeCatalogSource diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs index 1de80275c..521d0155d 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorGameInputCaptureTests.cs @@ -1,3 +1,4 @@ +using System; using System.Numerics; using Xunit; using Inno.Adapter.Input; @@ -76,7 +77,7 @@ public void DispatcherRoutesInputOnlyAfterEditorConsumption(bool globalConsumpti { var dispatcher = new EventDispatcher(); using EventHub ui = dispatcher.CreateHub(100); - using System.IDisposable subscription = ui.Listen(evnt => + using IDisposable subscription = ui.Listen(evnt => { if (globalConsumption) { @@ -113,7 +114,7 @@ public void ConsumedReleaseResetsInputDuringDispatchBeforeSimulation() { var dispatcher = new EventDispatcher(); using EventHub ui = dispatcher.CreateHub(100); - using System.IDisposable subscription = ui.Listen(evnt => evnt.HandleInGlobal()); + using IDisposable subscription = ui.Listen(evnt => evnt.HandleInGlobal()); var capture = new EditorGameInputCapture(_ => 42u); capture.BeginFrame(); capture.Report(9, Vector2.Zero, new Vector2(100f), focused: true, hovered: true); @@ -173,7 +174,7 @@ public void ConsumedReleasesResetHeldInputWithoutReplayingTheEvent(string releas "button" => new MouseButtonReleasedEvent(42, MouseButton.Left), "focus" => new WindowFocusChangedEvent(42, false), "close" => new WindowCloseEvent(42), - _ => throw new System.ArgumentException("Unknown release kind.", nameof(releaseKind)) + _ => throw new ArgumentException("Unknown release kind.", nameof(releaseKind)) }; release.HandleInGlobal(); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs index 3f2f77be9..a439bbb79 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorLayoutInitializationTests.cs @@ -29,7 +29,7 @@ public void MissingProjectDocumentReceivesOnlyTheStandardLayout() Assert.Equal(template, File.ReadAllText(context.layoutPath)); Assert.False(context.SaveLayoutIfChanged()); Assert.Equal(["Panels"], context.GetLayoutSectionNames()); - Assert.True(context.TryGetLayoutSection("Panels", out var panels)); + Assert.True(context.TryGetLayoutSection("Panels", out IReadOnlyDictionary panels)); Assert.Equal(8, panels.Count); Assert.All(panels.Values, value => Assert.Equal("true", value)); Assert.DoesNotContain("Module.", template, StringComparison.Ordinal); @@ -47,7 +47,7 @@ public void ExistingDocumentIsAuthoritativeIncludingAnIntentionallyEmptyFile(str { string path = Path.Combine(m_root, "editor.ini"); File.WriteAllText(path, document); - DateTime timestamp = new(2020, 2, 3, 4, 5, 6, DateTimeKind.Utc); + var timestamp = new DateTime(2020, 2, 3, 4, 5, 6, DateTimeKind.Utc); File.SetLastWriteTimeUtc(path, timestamp); byte[] bytes = File.ReadAllBytes(path); EditorContext context = CreateContext(ReadTemplate()); @@ -89,9 +89,9 @@ public void OrdinarySaveAndReopenRetainLayoutAndIndependentStateSections() byte[] saved = File.ReadAllBytes(context.layoutPath); EditorContext reopened = CreateContext(ReadTemplate()); Assert.Contains("[Window][User layout]", reopened.imguiLayout); - Assert.True(reopened.TryGetLayoutSection("Module.fixture", out var values)); + Assert.True(reopened.TryGetLayoutSection("Module.fixture", out IReadOnlyDictionary values)); Assert.Equal("42", values["value"]); - Assert.True(reopened.TryGetLayoutSection("Panels", out var panels)); + Assert.True(reopened.TryGetLayoutSection("Panels", out IReadOnlyDictionary panels)); Assert.Equal(8, panels.Count); Assert.Equal(saved, File.ReadAllBytes(reopened.layoutPath)); Assert.Single(Directory.GetFiles(m_root)); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs index 8a0d0c8d8..a8cf5ffce 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs @@ -18,6 +18,7 @@ using Inno.Editor.Interactions; using Inno.Editor.Scene; using Inno.Editor.Scripting; +using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.References; using Inno.Runtime; @@ -105,8 +106,8 @@ public void PlayShortcutStopsTheSessionFromAFocusedGameView() new FakeScriptCompilation(EditorScriptCompilationState.Ready), new FakeScenePlayMode() ); - using var modules = new Inno.Extensibility.Modules.ModuleHost( - new Inno.Extensibility.Modules.ModuleHostOptions + using var modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorPlayModeController).Assembly) } @@ -214,7 +215,13 @@ public void PendingStopRetainsHistoryAndBlocksNewGenerationUntilWorkDrains(bool throw new InvalidOperationException("Scene materialization failed"); } }); - using var harness = new PlayModeHarness(m_projectRoot, m_engineHost, scripting, scenes, new PendingPlayFactory(subsystem)); + using var harness = new PlayModeHarness( + m_projectRoot, + m_engineHost, + scripting, + scenes, + new PendingPlayFactory(subsystem) + ); try { Assert.True(harness.playMode.EnterPlayMode()); @@ -583,10 +590,7 @@ internal PlayModeHarness( internal void Simulate(float deltaTime) => m_controller.Tick(deltaTime); - public void Dispose() - { - m_controller.Dispose(); - } + public void Dispose() => m_controller.Dispose(); } private sealed class FakeScriptCompilation(EditorScriptCompilationState initialState) : IEditorScriptCompilation @@ -653,14 +657,12 @@ or ScriptCompilationTicketState.Canceled or ScriptCompilationTicketState.Superseded; internal void SetState(EditorScriptCompilationState value) - { - state = value switch + => state = value switch { EditorScriptCompilationState.Ready => ScriptCompilationTicketState.Succeeded, EditorScriptCompilationState.Failed => ScriptCompilationTicketState.Failed, _ => ScriptCompilationTicketState.Compiling }; - } } private sealed class FakeScenePlayMode(Action? populate = null) : IEditorScenePlayMode @@ -693,8 +695,7 @@ public void Dispose() private sealed class FakeSelectionCoordinator : IEditorSelectionCoordinator { - public IDisposable RegisterIdentityDomain(Inno.Core.Identity.IdentityAllocator allocator) - => new Inno.Core.Execution.LifetimeScope(); + public IDisposable RegisterIdentityDomain(IdentityAllocator allocator) => new LifetimeScope(); public object? selectedTarget { get; private set; } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs index 6495bb7c2..b4a96adec 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPopupLayoutTests.cs @@ -20,7 +20,7 @@ public void ContextMenuSearchUsesCompletePopupContentWidth() ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ConfigureContext(); EditorUI.current.widgets.SetupStyle(); @@ -62,14 +62,14 @@ public void TwoItemSelectorOpensBelowControlWithoutOverflow() ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ConfigureContext(); EditorUI.current.widgets.SetupStyle(); for (int frame = 0; frame < 3; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default(Vector2)); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default); NativeImGui.SetNextWindowSize(new Vector2(300f, 250f), (int)(ImGuiCond.Always)); using NativeStringLease nativeTestText1 = Utf8Codec.EncodeNullTerminated("Selector bounds", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, (int)(ImGuiWindowFlags.NoTitleBar)); @@ -106,14 +106,14 @@ public void LongSelectorNearWindowBottomScrollsWithoutOpeningUpward() ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ConfigureContext(); EditorUI.current.widgets.SetupStyle(); for (int frame = 0; frame < 3; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default(Vector2)); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default); NativeImGui.SetNextWindowSize(new Vector2(300f, 250f), (int)(ImGuiCond.Always)); using NativeStringLease nativeTestText2 = Utf8Codec.EncodeNullTerminated("Selector near bottom", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText2.pointer, null, (int)(ImGuiWindowFlags.NoTitleBar)); @@ -152,14 +152,14 @@ public void SelectorInsideLayoutChildUsesContainingPanelBounds() ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ConfigureContext(); EditorUI.current.widgets.SetupStyle(); for (int frame = 0; frame < 3; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default(Vector2)); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default); NativeImGui.SetNextWindowSize(new Vector2(300f, 250f), (int)(ImGuiCond.Always)); using NativeStringLease nativeTestText3 = Utf8Codec.EncodeNullTerminated("Panel with layout child", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText3.pointer, null, (int)(ImGuiWindowFlags.NoTitleBar)); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs index 4b1b3dcf2..6d421657b 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/GraphCanvasNativeTests.cs @@ -5,11 +5,15 @@ using Inno.Core.Graphs; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; +using Inno.Editor.Interactions; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; using NativeGui = Inno.Native.ImGui.ImGui; using Ui = Inno.Editor.ImGui.ImGui; +using UiDrawList = Inno.Editor.ImGui.EditorDrawList; +using UiHoveredFlags = Inno.Editor.ImGui.ImGuiHoveredFlags; +using UiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; namespace Inno.Editor.PlayMode.Tests; @@ -24,8 +28,8 @@ public void NonShaderPointerWorkflowUsesTheRealDocumentHistory() var second = new GraphNodeRecord(new("workflow.second"), "workflow.step") { position = new(300f, 20f) }; document.AddNode(first); document.AddNode(second); - var history = host.runtime.interactions.history; - var controller = host.graphs.OpenDocument(Guid.NewGuid(), document, history); + IEditorHistory history = host.runtime.interactions.history; + GraphDocumentController controller = host.graphs.OpenDocument(Guid.NewGuid(), document, history); var state = new GraphCanvasState(); var pointer = new GraphCanvasPointerController(state); var layout = new GraphCanvasLayout(); @@ -54,7 +58,7 @@ void Frame( Vector2 mouse, bool down ) { - var io = NativeGui.Raw.GetIO(); + ImGuiIO* io = NativeGui.Raw.GetIO(); NativeGui.Raw.AddMousePosEvent(io, mouse.X, mouse.Y); NativeGui.Raw.AddMouseButtonEvent(io, 0, down ? (byte)1 : (byte)0); host.native.Frame(() => @@ -85,10 +89,10 @@ bool down GraphCanvasPointerResult result = pointer.Step(view, layout, new() { position = Ui.GetMousePos(), - isHovered = Ui.IsItemHovered(Inno.Editor.ImGui.ImGuiHoveredFlags.AllowWhenBlockedByActiveItem), - isPressed = Ui.IsMouseClicked(Inno.Editor.ImGui.ImGuiMouseButton.Left), - isDown = Ui.IsMouseButtonDown(Inno.Editor.ImGui.ImGuiMouseButton.Left), - isReleased = Ui.IsMouseReleased(Inno.Editor.ImGui.ImGuiMouseButton.Left) + isHovered = Ui.IsItemHovered(UiHoveredFlags.AllowWhenBlockedByActiveItem), + isPressed = Ui.IsMouseClicked(UiMouseButton.Left), + isDown = Ui.IsMouseButtonDown(UiMouseButton.Left), + isReleased = Ui.IsMouseReleased(UiMouseButton.Left) }); if (result.movedNodes is { } positions) { @@ -98,13 +102,13 @@ bool down { _ = controller.Connect(output, input); } - var draw = Ui.GetDrawList(); + UiDrawList draw = Ui.GetDrawList(); foreach (GraphCanvasNode node in layout.nodes) { _ = view.DrawNode( draw, node, - 0xFF504030, + 0xFF50_4030, state.selectedNodes.Contains(node.id), previewPosition: pointer.previewPositions.TryGetValue(node.id, out GraphPosition position) ? position : null ); @@ -123,7 +127,7 @@ public void NonShaderNodeDrawingRestoresItsClipAfterAnExtensionThrows() { using var host = new NativePanelHost(typeof(GraphCanvasNativeTests).Assembly); var state = new GraphCanvasState(); - GraphNodeId id = new("workflow.begin"); + var id = new GraphNodeId("workflow.begin"); var node = new GraphCanvasNode( id, new(10f, 10f), @@ -144,7 +148,7 @@ public void NonShaderNodeDrawingRestoresItsClipAfterAnExtensionThrows() { ImGuiWindow* window = NativeGui.Raw.GetCurrentWindow(); int clipDepth = window->DrawList->ClipRectStack.Size; - var draw = Ui.GetDrawList(); + UiDrawList draw = Ui.GetDrawList(); var view = new GraphCanvasView(state, new(40f, 60f), new(540f, 300f)); var failure = new InvalidOperationException("Workflow node extension failed."); Assert.Same( @@ -152,19 +156,26 @@ public void NonShaderNodeDrawingRestoresItsClipAfterAnExtensionThrows() Assert.Throws(() => view.DrawNode( draw, node, - 0xFF504030, + 0xFF50_4030, true, () => throw failure )) ); Assert.Equal(clipDepth, window->DrawList->ClipRectStack.Size); - Assert.True(view.DrawNode(draw, node, 0xFF504030, false)); - var offscreen = new GraphCanvasNode(new("workflow.hidden"), new(5000f, 5000f), new(200f, 100f), 24f, "Hidden", []); + Assert.True(view.DrawNode(draw, node, 0xFF50_4030, false)); + var offscreen = new GraphCanvasNode( + new("workflow.hidden"), + new(5000f, 5000f), + new(200f, 100f), + 24f, + "Hidden", + [] + ); Assert.False( view.DrawNode( draw, offscreen, - 0xFF504030, + 0xFF50_4030, false, () => throw new InvalidOperationException("Culled content must not run.") ) @@ -182,7 +193,7 @@ public void NonShaderNodeDrawingRestoresItsClipAfterAnExtensionThrows() oversized.DrawNode( draw, outsideWindow, - 0xFF504030, + 0xFF50_4030, false, () => throw new InvalidOperationException("Parent-clipped content must not run.") ) diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs index 517ed060d..44da13ecb 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/ListPanelKeyboardNativeTests.cs @@ -130,7 +130,7 @@ float height NativePanelInput.Key(host.native, panel, ImGuiKey.End); Assert.Same(entries[^1], interactions.selection.selectedTarget); NativePanelInput.Key(host.native, panel, ImGuiKey.Enter); - Assert.True(interactions.TryGetModule(out var browser)); + Assert.True(interactions.TryGetModule(out AssetBrowserModule? browser)); Assert.Equal(entries[^1].assetPath.ToString(), browser!.browser.currentDirectory); Assert.False(interactions.history.canUndo); } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs index 7f13f06ac..4da50f996 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeLogRetentionTests.cs @@ -2,6 +2,7 @@ using System.Linq; using Xunit; using Inno.Core.Diagnostics; +using Inno.Core.Events; using Inno.Core.Logging; using Inno.Editor.Diagnostics; using Inno.Extensibility.Modules; @@ -194,15 +195,18 @@ private sealed class FakePlayMode : IEditorPlayMode public LogSessionId activeSessionId { get; private set; } - private readonly Inno.Core.Events.EventDispatcher m_stateDispatcher = new(); - private readonly Inno.Core.Events.EventHub m_stateEvents; + private readonly EventDispatcher m_stateDispatcher = new(); + private readonly EventHub m_stateEvents; - internal FakePlayMode() => m_stateEvents = m_stateDispatcher.CreateHub(); + internal FakePlayMode() + { + m_stateEvents = m_stateDispatcher.CreateHub(); + } public IDisposable ListenStateChanges(Action listener) => m_stateEvents.Listen(notification => listener(notification.state)); - private sealed class StateNotification(EditorPlayModeState state) : Inno.Core.Events.Event + private sealed class StateNotification(EditorPlayModeState state) : Event { internal EditorPlayModeState state { get; } = state; } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs index 4e2110d21..937254afd 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs @@ -189,9 +189,14 @@ GameScene scene [AllowMultipleComponent] internal sealed class DirtyCaptureComponent : GameComponent { - [SerializableProperty] public int number; - [SerializableProperty] public GameObject? target; - [SerializableProperty] public DirtyCaptureValue state { get; set; } = new(); + [SerializableProperty] + public int number; + + [SerializableProperty] + public GameObject? target; + + [SerializableProperty] + public DirtyCaptureValue state { get; set; } = new(); } internal sealed class DirtyCaptureValue diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs index a320842e5..fadb226b4 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs @@ -5,6 +5,7 @@ using System.Numerics; using System.Runtime.CompilerServices; using Xunit; +using Xunit.Sdk; using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -30,7 +31,7 @@ public void FaultedDrawerReleasesReloadAdmissionUntilItsExtensionsRecover() AtomicEditorSetting.throwOnDraw = true; try { - Assert.ThrowsAny(() => driver.Search("Atomic Editor")); + Assert.ThrowsAny(() => driver.Search("Atomic Editor")); } finally { @@ -59,7 +60,10 @@ public void OneHundredSettingsCyclesReleaseDrawnValuesAndReloadAdmission() AtomicEditorSetting.observe = true; try { - using var host = new NativeProjectPanelHost(typeof(SettingsApplyNativeTests).Assembly, includeSettings: true); + using var host = new NativeProjectPanelHost( + typeof(SettingsApplyNativeTests).Assembly, + includeSettings: true + ); for (int cycle = 0; cycle < 100; cycle++) { OpenAndClose(host); @@ -101,13 +105,15 @@ public void FailedRollbackKeepsHistoryFaultedAndPreventsFurtherApply() Directory.CreateDirectory(directory); try { - var document = new FailingSettingsDocument(new FileByteDocumentStore(Path.Combine(directory, "Project.inno"))); + var document = new FailingSettingsDocument( + new FileByteDocumentStore(Path.Combine(directory, "Project.inno")) + ); using var host = new NativeProjectPanelHost( typeof(SettingsApplyNativeTests).Assembly, includeSettings: true, settingsDocument: document ); - Assert.True(host.runtime.interactions.TryGetModule(out var editor)); + Assert.True(host.runtime.interactions.TryGetModule(out EditorSettings? editor)); var driver = new SettingsInput(host); Assert.True(host.runtime.interactions.For("editor/main-menu").Execute("editor.settings.open")); driver.Draw(); @@ -179,13 +185,15 @@ public void FailedSettingsBatchPreservesAllOwnersAndDraftsForRetry() Directory.CreateDirectory(directory); try { - var document = new FailingSettingsDocument(new FileByteDocumentStore(Path.Combine(directory, "Project.inno"))); + var document = new FailingSettingsDocument( + new FileByteDocumentStore(Path.Combine(directory, "Project.inno")) + ); using var host = new NativeProjectPanelHost( typeof(SettingsApplyNativeTests).Assembly, includeSettings: true, settingsDocument: document ); - Assert.True(host.runtime.interactions.TryGetModule(out var editor)); + Assert.True(host.runtime.interactions.TryGetModule(out EditorSettings? editor)); var driver = new SettingsInput(host); Assert.True(host.runtime.interactions.For("editor/main-menu").Execute("editor.settings.open")); driver.Draw(); @@ -249,8 +257,7 @@ private sealed class SettingsInput(NativeProjectPanelHost host) internal string diagnostic => $"Apply={m_apply}; Cancel={m_cancel}; Search={m_search}"; internal void Draw() - { - host.native.Frame(() => + => host.native.Frame(() => { NativeGui.SetNextWindowPos(new Vector2(20f), (int)ImGuiCond.Always); NativeGui.SetNextWindowSize(new Vector2(1000f, 800f), (int)ImGuiCond.Always); @@ -261,7 +268,7 @@ internal void Draw() Vector2 content = NativeGui.GetCursorScreenPos(); m_search = content + new Vector2(115f, NativeGui.GetFrameHeight() * 0.5f + 3f); EditorModalExtension modal = Assert.Single(host.runtime.modals, modal => modal.id == "editor.settings"); - Assert.True(modal.TryGetPresentation(out var presentation)); + Assert.True(modal.TryGetPresentation(out EditorModalExtension.Presentation presentation)); isVisible = presentation.isVisible; if (!isVisible) { @@ -269,7 +276,7 @@ internal void Draw() } Assert.True(modal.Draw(host.runtime.context), "The operational Settings failure must not quarantine the modal."); m_apply = (NativeGui.GetItemRectMin() + NativeGui.GetItemRectMax()) * 0.5f; - var style = NativeGui.Raw.GetStyle(); + ImGuiStyle* style = NativeGui.Raw.GetStyle(); m_cancel = new Vector2( NativeGui.GetItemRectMin().X - style->ItemSpacing.X - NativeGui.CalcTextSize("Cancel").X * 0.5f - style->FramePadding.X, @@ -281,7 +288,6 @@ internal void Draw() NativeGui.End(); } }); - } internal void Search(string text) { @@ -345,8 +351,9 @@ protected override void OnDraw(EditorSettingObject setting) { throw new InvalidOperationException("Controlled Settings drawer failure."); } - if (observe && (snapshots.Count == 0 || !snapshots[^1].TryGetTarget(out var last) || !ReferenceEquals(last, setting))) - { + if (observe + && (snapshots.Count == 0 || !snapshots[^1].TryGetTarget(out EditorSettingObject? last) || !ReferenceEquals(last, setting)) + ) { snapshots.Add(new WeakReference(setting)); } if (!stage) diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs index 7fe93907d..82f1ea478 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/StatisticsPanelNativeTests.cs @@ -7,6 +7,7 @@ using NativeImGui = Inno.Native.ImGui.ImGui; using Ui = Inno.Editor.ImGui.ImGui; +using UiCol = Inno.Editor.ImGui.ImGuiCol; namespace Inno.Editor.PlayMode.Tests; @@ -65,9 +66,9 @@ float deltaTime NativeImGui.SetNextWindowSize(new(1000f, 800f), (int)ImGuiCond.Always); bool open = true; _ = NativeImGui.Begin("Statistics acceptance", ref open, (int)ImGuiWindowFlags.NoSavedSettings); - Vector4 color = new(0.93f, 0.17f, 0.73f, 1f); + var color = new Vector4(0.93f, 0.17f, 0.73f, 1f); uint packed = Ui.ToPackedColor(color); - Ui.PushStyleColor(Inno.Editor.ImGui.ImGuiCol.PlotLines, color); + Ui.PushStyleColor(UiCol.PlotLines, color); try { Assert.True(panel.Draw(host.runtime.context)); @@ -75,7 +76,7 @@ float deltaTime for (int index = 0; index < draw->VtxBuffer.Size; index++) { uint vertex = draw->VtxBuffer.Data[index].Col; - if ((vertex & 0x00ffffff) == (packed & 0x00ffffff) && (vertex >> 24) != 0) + if ((vertex & 0x00FF_FFFF) == (packed & 0x00FF_FFFF) && (vertex >> 24) != 0) { count++; } diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs index 4cc7fa69e..90b5c15b4 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/TreeKeyboardOwnershipNativeTests.cs @@ -9,6 +9,7 @@ using NativeImGui = Inno.Native.ImGui.ImGui; using Ui = Inno.Editor.ImGui.ImGui; +using UiInput = Inno.Editor.ImGui.EditorUiInput; namespace Inno.Editor.PlayMode.Tests; @@ -99,7 +100,7 @@ KeyModifier primaryModifier Assert.Equal(0, overlayPresses); host.Frame(() => { - var input = Ui.GetInput(); + UiInput input = Ui.GetInput(); Assert.Equal(primaryModifier == KeyModifier.Control, input.control); Assert.Equal(primaryModifier == KeyModifier.Super, input.super); draw(); diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs index 56132ee54..8b4ebd550 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/VisualScaleMatrixTests.cs @@ -4,11 +4,14 @@ using System.Runtime.CompilerServices; using Xunit; using Inno.Editor.ImGui; +using Inno.Editor.ImGui.ImGuiWidget; using Inno.Native.ImGui; using Inno.Testing.Editor.Native; using NativeGui = Inno.Native.ImGui.ImGui; using NativeVector = Inno.Native.ImGui.ImVec2C; +using UiCond = Inno.Editor.ImGui.ImGuiCond; +using UiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; namespace Inno.Editor.PlayMode.Tests; @@ -16,9 +19,9 @@ public sealed unsafe class VisualScaleMatrixTests { public static IEnumerable Metrics() { - foreach (float zoom in new[] { 0.75f, 0.85f, 0.90f, 1f, 1.10f, 1.25f, 1.50f }) + foreach (float zoom in new[] { 0.75f, 0.85f, 0.9f, 1f, 1.1f, 1.25f, 1.5f }) { - foreach (float density in new[] { 1f, 1.25f, 1.50f, 2f }) + foreach (float density in new[] { 1f, 1.25f, 1.5f, 2f }) { foreach (Vector2 size in new[] { new Vector2(1280f, 720f), new Vector2(1920f, 1080f) }) { @@ -48,13 +51,13 @@ float height { host.Frame(() => { - NativeGui.SetNextWindowPos(new Vector2(20f, 20f), (int)Inno.Editor.ImGui.ImGuiCond.Always); - NativeGui.SetNextWindowSize(new Vector2(320f, 500f), (int)Inno.Editor.ImGui.ImGuiCond.Always); + NativeGui.SetNextWindowPos(new Vector2(20f, 20f), (int)UiCond.Always); + NativeGui.SetNextWindowSize(new Vector2(320f, 500f), (int)UiCond.Always); bool open = true; - _ = NativeGui.Begin("Narrow inspector matrix", ref open, (int)Inno.Editor.ImGui.ImGuiWindowFlags.NoSavedSettings); + _ = NativeGui.Begin("Narrow inspector matrix", ref open, (int)UiWindowFlags.NoSavedSettings); try { - var widgets = host.ui.widgets; + ImGuiWidget widgets = host.ui.widgets; widgets.PropertyRow( "reference", () => diff --git a/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs index 8bce5c1e5..95efc2145 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/AssetHistoryTests.cs @@ -8,12 +8,14 @@ using Inno.Core.Diagnostics; using Inno.Core.IO; using Inno.Core.Identity; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; +using Inno.Editor.ImGui; using Inno.Editor.Interactions; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; @@ -23,7 +25,7 @@ namespace Inno.Editor.Presentation.Tests; public sealed class AssetHistoryTests : IDisposable { - private readonly Inno.Editor.ImGui.EditorUiSession m_ui = new(); + private readonly EditorUiSession m_ui = new(); private readonly IdentityAllocator m_identities = new(); private readonly IDisposable m_identityScope; private readonly string m_projectRoot = Path.Combine(Path.GetTempPath(), "InnoAssetHistoryTests", Guid.NewGuid().ToString("N")); @@ -76,7 +78,7 @@ public AssetHistoryTests() m_modules.generations ); m_runtime = new EditorInteractionRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_types, m_logs, [m_types, m_serialization, m_identities, m_assets, m_plugins, m_ui] diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs index 3e395cda6..c56a5ff99 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs @@ -12,7 +12,7 @@ public sealed partial class EditorRuntimeTests public void StaticMenuTemplatesKeepAvailabilityLabelsAndReasonsFresh() { var target = new MenuStateTarget(); - var interaction = m_runtime.interactions.For("tests/static-menu", target); + EditorInteraction interaction = m_runtime.interactions.For("tests/static-menu", target); for (int index = 0; index < 3; index++) { target.label = "Current " + index; @@ -37,7 +37,7 @@ public void StaticMenuTemplatesKeepAvailabilityLabelsAndReasonsFresh() public void HiddenHigherOrderPlacementDoesNotEraseTheVisibleAction() { var target = new MenuStateTarget { visible = false }; - var interaction = m_runtime.interactions.For("tests/shared-menu", target); + EditorInteraction interaction = m_runtime.interactions.For("tests/shared-menu", target); Assert.Equal("tests.menu-fallback", Assert.Single(interaction.BuildMenu().items).actionId); target.visible = true; Assert.Equal("tests.menu-conditional", Assert.Single(interaction.BuildMenu().items).actionId); diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs index af23945b2..5eeadacb7 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Performance.cs @@ -5,6 +5,7 @@ using Inno.Core.Events; using Inno.Core.Input; using Inno.Editor.Core; +using Inno.Editor.Interactions; namespace Inno.Editor.Presentation.Tests; @@ -14,7 +15,7 @@ public sealed partial class EditorRuntimeTests [Trait("Category", "Performance")] public void PublicCommandAndStatisticsPathsProduceRepeatableSamples() { - var interaction = m_runtime.interactions.For("tests/menu"); + EditorInteraction interaction = m_runtime.interactions.For("tests/menu"); Measure("menu-open", () => Assert.NotEmpty(interaction.BuildMenu().items)); m_runtime.interactions.For("tests/multiple-shortcuts").Focus(); int beforeDispatch = MultiShortcutAction.executeCount; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs index 089bec356..007934dc9 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Selection.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using System.Threading; using Xunit; +using Inno.Core.Events; using Inno.Core.Identity; using Inno.Editor.Core; using Inno.Editor.Interactions; @@ -20,7 +22,7 @@ public void MissingIdentityRejectsTheEntireVisibleRangeWithoutChangingSelection( m_runtime.interactions.SetSelection(first); EditorSelectionSnapshot original = m_runtime.interactions.selection.Capture(); RuntimeIdentity firstId = first.identity.runtimeIdentity!.Value; - RuntimeIdentity missing = new(firstId.domainId, int.MaxValue); + var missing = new RuntimeIdentity(firstId.domainId, int.MaxValue); Assert.Throws(() => m_runtime.interactions.SelectRange( [firstId, missing, last.identity.runtimeIdentity!.Value], last @@ -99,7 +101,7 @@ public void RejectedDomainRetirementOnAnotherThreadPreservesTheRoutingLease() Assert.True(allocator.Register(target)); using IDisposable registration = m_runtime.interactions.RegisterIdentityDomain(allocator); Exception? failure = null; - var worker = new System.Threading.Thread(() => failure = Record.Exception(registration.Dispose)); + var worker = new Thread(() => failure = Record.Exception(registration.Dispose)); worker.Start(); Assert.True(worker.Join(TimeSpan.FromSeconds(5))); Assert.IsType(failure); @@ -144,7 +146,7 @@ public void SelectionFinishesPendingEditsBeforeChangingAndPreservesStateWhenPrep Assert.True(m_identities.Register(first)); Assert.True(m_identities.Register(second)); m_runtime.interactions.SetSelection(first); - using var hub = m_runtime.interactions.events.CreateHub(); + using EventHub hub = m_runtime.interactions.events.CreateHub(); using var gesture = new EditorEditGesture(m_runtime.interactions.history, "Pending Input"); using (hub.Listen(_ => { @@ -155,7 +157,7 @@ public void SelectionFinishesPendingEditsBeforeChangingAndPreservesStateWhenPrep } Assert.False(gesture.isActive); ulong revision = m_runtime.interactions.selection.version; - using var rejecting = hub.Listen( + using IDisposable rejecting = hub.Listen( _ => throw new InvalidOperationException("Pending edit cannot finish.") ); Assert.Throws(() => m_runtime.interactions.SetSelection(first)); diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs index 654a4136e..997ce4903 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Statistics.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using System.Linq; using Xunit; using Inno.Editor.Core; @@ -11,12 +12,12 @@ public void UnchangedStatisticsReuseAnImmutableSnapshot() { var statistics = new EditorStatistics(); statistics.Publish(new EditorStatistic(new("frame"), new("timing"), "Timing", "Frame", "16 ms")); - var first = statistics.GetSnapshot(); + IReadOnlyList first = statistics.GetSnapshot(); Assert.Same(first, statistics.GetSnapshot()); statistics.Publish(new EditorStatistic(new("frame"), new("timing"), "Timing", "Frame", "16 ms")); Assert.Same(first, statistics.GetSnapshot()); statistics.Publish(new EditorStatistic(new("frame"), new("timing"), "Timing", "Frame", "8 ms")); - var changed = statistics.GetSnapshot(); + IReadOnlyList changed = statistics.GetSnapshot(); Assert.NotSame(first, changed); Assert.Equal("16 ms", Assert.Single(first).value); Assert.Equal("8 ms", Assert.Single(changed).value); @@ -27,11 +28,11 @@ public void StatisticFrameHandoffRetainsLateProvidersAndRemovesExpiredContributi { EditorStatistics statistics = m_runtime.context.statistics; statistics.Publish(new EditorStatistic(new("first"), new("sampling"), "Sampling", "First", "1")); - var first = statistics.GetSnapshot(); + IReadOnlyList first = statistics.GetSnapshot(); m_runtime.Update(new EditorFrame(0.016f, 1f, isFocused: true)); Assert.Same(first, statistics.GetSnapshot()); statistics.Publish(new EditorStatistic(new("second"), new("sampling"), "Sampling", "Second", "2")); - var combined = statistics.GetSnapshot(); + IReadOnlyList combined = statistics.GetSnapshot(); Assert.Equal(2, combined.Count(value => value.groupId == new EditorStatisticGroupId("sampling"))); m_runtime.Update(new EditorFrame(0.016f, 2f, isFocused: true)); Assert.Equal( @@ -49,9 +50,9 @@ public void StatisticGroupingAndOrderChangesInvalidateTheSnapshot() var statistics = new EditorStatistics(); statistics.Publish(new EditorStatistic(new("a"), new("old"), "Old", "First", "1", groupOrder: 1)); statistics.Publish(new EditorStatistic(new("b"), new("second"), "Second", "Second", "2", groupOrder: 2)); - var original = statistics.GetSnapshot(); + IReadOnlyList original = statistics.GetSnapshot(); statistics.Publish(new EditorStatistic(new("b"), new("new"), "New", "Renamed", "2", groupOrder: 0)); - var changed = statistics.GetSnapshot(); + IReadOnlyList changed = statistics.GetSnapshot(); Assert.NotSame(original, changed); Assert.Equal("b", changed[0].id.value); Assert.Equal("New", changed[0].groupName); diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs index e20918da0..f7562973c 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs @@ -11,6 +11,7 @@ using Inno.Core.Identity; using Inno.Core.Input; using Inno.Core.Logging; +using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Editor.Core; @@ -77,7 +78,7 @@ public EditorRuntimeTests() ZThrowingDisposeModule.disposeCount = 0; ZThrowingDisposeModule.throwOnDispose = false; ShutdownOrder.events.Clear(); - m_runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super"))); + m_runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super"))); m_runtime.Start(); } @@ -102,13 +103,13 @@ params object[] hostServices [Fact] public void FeatureLookupReturnsOnlyStartedNonQuarantinedModules() { - Assert.True(m_runtime.interactions.TryGetModule(out var first)); + Assert.True(m_runtime.interactions.TryGetModule(out TestModule? first)); Assert.NotNull(first); - Assert.True(m_runtime.interactions.TryGetModule(out var again)); + Assert.True(m_runtime.interactions.TryGetModule(out TestModule? again)); Assert.Same(first, again); UpdateBarrierModule.throwWhenRead = true; m_runtime.Update(new EditorFrame()); - Assert.False(m_runtime.interactions.TryGetModule(out var quarantined)); + Assert.False(m_runtime.interactions.TryGetModule(out UpdateBarrierModule? quarantined)); Assert.Null(quarantined); } @@ -145,7 +146,7 @@ public void InteractionRuntimeInjectsOneStableAssignableHostService() var service = new TestHostService(); HostServicePanel.current = null; using EditorInteractionRuntime runtime = CreateRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), service ); runtime.Start(); @@ -158,7 +159,7 @@ public void InteractionRuntimeRejectsExtensionWhenHostServiceIsUnavailable() { HostServicePanel.current = null; using EditorInteractionRuntime runtime = CreateRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")) + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")) ); runtime.Start(); Assert.DoesNotContain(runtime.panels, static panel => panel.id == "tests.host-service"); @@ -275,8 +276,8 @@ public void ViewportToolCapturesOnePointerAndCommitsOneGestureTransaction() var down = new EditorViewportPointerEvent( 7, EditorViewportPointerPhase.Down, - new Inno.Core.Mathematics.Vector2(2f, 3f), - coordinates.ScreenToWorld(new Inno.Core.Mathematics.Vector2(2f, 3f)), + new Vector2(2f, 3f), + coordinates.ScreenToWorld(new Vector2(2f, 3f)), 0, KeyModifier.None ); @@ -437,7 +438,7 @@ public void MissingHistoryHandlerCreatesAnExplicitBarrier() public void LargeNeutralPayloadSpillsToTheBoundedSessionDiskStore() { NeutralHistoryHandler.value = 32; - byte[] bytes = new byte[128 * 1024]; + var bytes = new byte[128 * 1024]; BitConverter.GetBytes(9).CopyTo(bytes, 0); BitConverter.GetBytes(32).CopyTo(bytes, sizeof(int)); m_runtime.interactions.history.RecordApplied( @@ -515,7 +516,9 @@ public void EveryShortcutDeclaredByTheSameActionCanDispatch() [Fact] public void ProductKeyboardPolicyControlsDiscoveryLabelsAndShortcutDispatch() { - using var runtime = CreateRuntime(new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Super, "Cmd"))); + using EditorInteractionRuntime runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Super, "Cmd")) + ); runtime.Start(); NeutralHistoryHandler.value = 1; runtime.interactions.history.RecordApplied("Change Test Value", NeutralHistoryHandler.CreateChange(before: 0, after: 1)); @@ -687,8 +690,8 @@ public void FailedModuleStartIsStoppedBeforeCandidateDisposal() m_runtime.Dispose(); int stops = TestModule.stopCount; TestModule.throwOnStart = true; - using var runtime = CreateRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")) + using EditorInteractionRuntime runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")) ); try { @@ -708,8 +711,8 @@ public void FailedPanelAttachmentIsCompensatedBeforeItIsQuarantined() m_runtime.Dispose(); int detaches = TestPanel.detachCount; TestPanel.throwOnAttach = true; - using var runtime = CreateRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")) + using EditorInteractionRuntime runtime = CreateRuntime( + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")) ); try { @@ -794,7 +797,7 @@ public void ModuleStateAndPanelVisibilityRestoreForTheSameProject() Assert.Contains("[InnoEditor][Module.tests.state]", document); Assert.DoesNotContain("[InnoEditor][Module.tests.update-barrier]", document); using EditorInteractionRuntime restored = CreateRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")) + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")) ); restored.Start(); Assert.Equal(42, TestModule.restoredStateValue); @@ -805,7 +808,7 @@ public void ModuleStateAndPanelVisibilityRestoreForTheSameProject() public void MalformedModuleStateValueUsesTheExtensionFallback() { m_runtime.Dispose(); - var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); + var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); context.SetLayoutSection("Module.tests.state", new Dictionary { ["value"] = "not-json" }); context.SaveLayout(); TestModule.restoredStateValue = -1; @@ -842,11 +845,11 @@ public void ExtensionStateCaptureFailure_PublishesCurrentDiagnosticUntilRetrySuc public void UnifiedEditorIniPreservesLayoutAndExtensionStateSectionsTogether() { const string layout = "[Window][Hierarchy]\nPos=10,20\nSize=300,400"; - var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); + var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); context.SetImGuiLayout(layout); context.SetLayoutSection("Module.tests", new Dictionary { ["openScenes"] = "[\"Scenes/Test.iscene\"]" }); Assert.True(context.SaveLayoutIfChanged()); - var restored = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); + var restored = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); Assert.Equal(layout, restored.imguiLayout); Assert.True(restored.TryGetLayoutSection("Module.tests", out IReadOnlyDictionary values)); Assert.Equal("[\"Scenes/Test.iscene\"]", values["openScenes"]); @@ -861,14 +864,14 @@ public void UnifiedEditorIniPreservesLayoutAndExtensionStateSectionsTogether() public void StartupRegistryRefreshCannotOverwriteModuleStateBeforeRestore() { m_runtime.Dispose(); - var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")); + var context = new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); context.SetLayoutSection("Module.tests.state", new Dictionary { ["value"] = "91" }); context.SaveLayout(); TestModule.startCount = 0; TestModule.restoredStateValue = 0; TestModule.rebuildDuringRestore = true; using EditorInteractionRuntime restored = CreateRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")) + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")) ); restored.Start(); Assert.Equal(91, TestModule.restoredStateValue); @@ -924,7 +927,7 @@ public static EditorHistoryChange CreateChange( int before, int after ) { - byte[] bytes = new byte[sizeof(int) * 2]; + var bytes = new byte[sizeof(int) * 2]; BitConverter.GetBytes(before).CopyTo(bytes, 0); BitConverter.GetBytes(after).CopyTo(bytes, sizeof(int)); return new EditorHistoryChange(KIND, EditorHistoryPayload.FromBytes(bytes)); @@ -1377,9 +1380,9 @@ public override bool Save(EditorDocumentContext context) public sealed class TestViewportCoordinates : IEditorViewportCoordinateConverter { - public Inno.Core.Mathematics.Vector2 ScreenToWorld(Inno.Core.Mathematics.Vector2 screenPosition) => screenPosition * 2f; + public Vector2 ScreenToWorld(Vector2 screenPosition) => screenPosition * 2f; - public Inno.Core.Mathematics.Vector2 WorldToScreen(Inno.Core.Mathematics.Vector2 worldPosition) => worldPosition / 2f; + public Vector2 WorldToScreen(Vector2 worldPosition) => worldPosition / 2f; } public sealed class TestViewportTool(IEditorHistory history) : EditorViewportTool diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs index f8d5ed8de..a538cdbc6 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorSettingsTests.cs @@ -2,10 +2,13 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Core.Diagnostics; +using Inno.Core.Events; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Core; @@ -38,13 +41,13 @@ public EditorSettingsTests() new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EditorSettingsTests).Assembly) } ); _ = typeof(EditorSettings); - _ = System.Reflection.Assembly.Load("Inno.Editor.Panel.Logging"); + _ = Assembly.Load("Inno.Editor.Panel.Logging"); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); SettingsCaptureModule.current = null; SettingsCaptureModule.console = null; m_runtime = new EditorInteractionRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_types, m_logs, [m_types, m_serialization, m_diagnostics, m_playMode] @@ -289,7 +292,7 @@ private sealed class FakePlayMode : IEditorPlayMode public string? lastFailure => null; public LogSessionId activeSessionId => LogSessionId.none; - private readonly Inno.Core.Events.EventDispatcher m_stateDispatcher = new(); + private readonly EventDispatcher m_stateDispatcher = new(); public IDisposable ListenStateChanges(Action listener) => m_stateDispatcher.CreateHub(); diff --git a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs index c27827bc9..86a97af91 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPointerTests.cs @@ -16,8 +16,8 @@ public void ShiftBoxSelectionKeepsTheExistingSelectionAndAddsIntersectingNodes() var pointer = new GraphCanvasPointerController(state); var layout = new GraphCanvasLayout(); var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); - GraphNodeId original = new("workflow.original"); - GraphNodeId added = new("workflow.added"); + var original = new GraphNodeId("workflow.original"); + var added = new GraphNodeId("workflow.added"); _ = layout.SetNodes([ new(original, new(500f, 300f), new(100f, 80f), 24f, "Original", []), new(added, new(50f, 50f), new(100f, 80f), 24f, "Added", []) @@ -98,8 +98,8 @@ public void ConnectionsAreNeutralIntentsAndMissingEndpointsCannotBeConnected(boo var pointer = new GraphCanvasPointerController(state); var layout = new GraphCanvasLayout(); var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); - GraphEndpoint output = new(new("flow.source"), new("next")); - GraphEndpoint input = new(new("flow.target"), new("previous")); + var output = new GraphEndpoint(new("flow.source"), new("next")); + var input = new GraphEndpoint(new("flow.target"), new("previous")); _ = layout.SetNodes([ new(output.nodeId, default, new(200f, 100f), 24f, "Source", [new(output, GraphPortDirection.Output, new(200f, 40f), "Next")]), new( @@ -130,7 +130,7 @@ public void ReadOnlyChangesCancelEditsButStillAllowBoxSelection() var pointer = new GraphCanvasPointerController(state); var layout = new GraphCanvasLayout(); var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); - GraphNodeId id = new("flow.read-only"); + var id = new GraphNodeId("flow.read-only"); _ = layout.SetNodes([new(id, new(20f, 20f), new(200f, 100f), 24f, "Read only", [])]); _ = pointer.Step(view, layout, new() { position = new(30f, 25f), isHovered = true, isPressed = true, isDown = true }); _ = pointer.Step(view, layout, new() { position = new(100f, 100f), isDown = true }); diff --git a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs index 9ffcc5984..742729f83 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasPresentationTests.cs @@ -31,7 +31,7 @@ public void PortHitGeometryPreservesMissingAndExplicitLabelBounds() { var state = new GraphCanvasState(); var view = new GraphCanvasView(state, Vector2.Zero, new(800f, 600f)); - GraphNodeId id = new("workflow.output"); + var id = new GraphNodeId("workflow.output"); var port = new GraphCanvasPort( new(id, new("next")), GraphPortDirection.Output, diff --git a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs index fa8754951..9582d75d8 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/GraphCanvasViewTests.cs @@ -31,7 +31,7 @@ public void ViewportRoundTripPreservesTheGraphPoint(float zoom) var state = new GraphCanvasState(); state.SetViewport(new(-172f, 38f), zoom); var view = new GraphCanvasView(state, new(100f, 200f), new(800f, 600f)); - GraphPosition point = new(-21.25f, 90f); + var point = new GraphPosition(-21.25f, 90f); GraphPosition actual = view.ToGraph(view.ToScreen(point)); Assert.Equal(point.x, actual.x, 3); Assert.Equal(point.y, actual.y, 3); diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs index 7f93eb858..0bce5499e 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelHost.cs @@ -6,6 +6,7 @@ using System.Runtime.CompilerServices; using Inno.Adapter.Modules.DotNet; using Inno.Core.Diagnostics; +using Inno.Core.Events; using Inno.Core.Input; using Inno.Core.Logging; using Inno.Editor.Core; @@ -17,10 +18,10 @@ using Inno.Extensibility.Types; using Inno.Native.ImGui; -using ImGuiCond = Inno.Native.ImGui.ImGuiCond; -using ImGuiWindowFlags = Inno.Native.ImGui.ImGuiWindowFlags; +using NativeCond = Inno.Native.ImGui.ImGuiCond; using NativeImGui = Inno.Native.ImGui.ImGui; using NativeVector2 = Inno.Native.ImGui.ImVec2C; +using NativeWindowFlags = Inno.Native.ImGui.ImGuiWindowFlags; namespace Inno.Testing.Editor.Native; @@ -46,8 +47,12 @@ public sealed unsafe class NativePanelHost : IDisposable /// /// Creates a panel host with the default keyboard convention and vertex-offset validation disabled. /// - /// The calling test assembly owning the complete discovery closure. - /// Additional declared panel assemblies to load before discovery. + /// + /// The calling test assembly owning the complete discovery closure. + /// + /// + /// Additional declared panel assemblies to load before discovery. + /// public NativePanelHost( Assembly composition, params string[] assemblies @@ -56,9 +61,15 @@ params string[] assemblies /// /// Creates a panel host with an explicit vertex-offset capability. /// - /// The calling test assembly owning the complete discovery closure. - /// Whether to advertise and validate native vertex offsets. - /// Additional declared panel assemblies to load before discovery. + /// + /// The calling test assembly owning the complete discovery closure. + /// + /// + /// Whether to advertise and validate native vertex offsets. + /// + /// + /// Additional declared panel assemblies to load before discovery. + /// public NativePanelHost( Assembly composition, bool supportsVertexOffsets, @@ -68,10 +79,18 @@ params string[] assemblies /// /// Creates the owned diagnostics, discovery, interactions and native frame context. /// - /// The calling test assembly owning the complete discovery closure. - /// Whether to advertise and validate native vertex offsets. - /// The explicit keyboard convention used by the test. - /// Additional declared panel assemblies to load before discovery. + /// + /// The calling test assembly owning the complete discovery closure. + /// + /// + /// Whether to advertise and validate native vertex offsets. + /// + /// + /// The explicit keyboard convention used by the test. + /// + /// + /// Additional declared panel assemblies to load before discovery. + /// public NativePanelHost( Assembly composition, bool supportsVertexOffsets, @@ -85,16 +104,16 @@ params string[] assemblies { _ = Assembly.Load(assembly); } - diagnostics = new DiagnosticHub(); + this.diagnostics = new DiagnosticHub(); m_diagnosticScope = diagnostics.EnterScope(); - logs = new LogRouter(); + this.logs = new LogRouter(); m_modules = new ModuleHost(new() { catalogSource = new DotNetAssemblyCatalogSource(composition) }); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - console = new EditorConsole(logs, diagnostics, new InactivePlayMode()); + this.console = new EditorConsole(logs, diagnostics, new InactivePlayMode()); console.Start(); - runtime = new EditorInteractionRuntime(new EditorContext(m_root, keyboard), m_types, logs, [console]); + this.runtime = new EditorInteractionRuntime(new EditorContext(m_root, keyboard), m_types, logs, [console]); runtime.Start(); - ui = new EditorUiSession(); + this.ui = new EditorUiSession(); m_nativeContext = CreateNativeContext(ui, supportsVertexOffsets); m_clipboard = new NativeClipboard(m_nativeContext); logs.Flush(); @@ -148,9 +167,15 @@ internal NativePanelHost( /// /// Finds and opens exactly one discovered panel. /// - /// The registered panel identity. - /// The borrowed panel, valid until this host is disposed. - /// The identity has no unique discovered panel. + /// + /// The registered panel identity. + /// + /// + /// The borrowed panel, valid until this host is disposed. + /// + /// + /// The identity has no unique discovered panel. + /// public EditorPanelExtension GetPanel(string id) { EditorPanelExtension panel = runtime.panels.Single(value => value.id == id); @@ -161,8 +186,12 @@ public EditorPanelExtension GetPanel(string id) /// /// Executes a real native frame and validates its resulting draw data. /// - /// The drawing operation executed within the UI scope. - /// The explicit elapsed frame time in seconds. + /// + /// The drawing operation executed within the UI scope. + /// + /// + /// The explicit elapsed frame time in seconds. + /// public void Frame( Action draw, float deltaTime = 1f / 60f @@ -190,9 +219,15 @@ public void Frame( /// /// Sets the native display dimensions, framebuffer scale and UI zoom. /// - /// The logical display size in UI coordinates. - /// The physical framebuffer scale. - /// The UI style zoom. + /// + /// The logical display size in UI coordinates. + /// + /// + /// The physical framebuffer scale. + /// + /// + /// The UI style zoom. + /// public void SetDisplayMetrics( Vector2 logicalSize, float framebufferScale, @@ -210,42 +245,48 @@ float zoom /// /// Draws the actual panel inside a bounded native window and completes the frame. /// - /// The borrowed panel belonging to this host's interaction runtime. - /// An optional operation performed after the panel draws and before the window closes. - /// The explicit elapsed frame time in seconds. - /// The panel is quarantined by a real draw failure. + /// + /// The borrowed panel belonging to this host's interaction runtime. + /// + /// + /// An optional operation performed after the panel draws and before the window closes. + /// + /// + /// The explicit elapsed frame time in seconds. + /// + /// + /// The panel is quarantined by a real draw failure. + /// public void DrawPanel( EditorPanelExtension panel, Action? afterDraw = null, float deltaTime = 1f / 60f - ) { - Frame(() => + ) => Frame(() => + { + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)NativeCond.Always); + NativeImGui.SetNextWindowSize(m_panelSize, (int)NativeCond.Always); + bool open = true; + _ = NativeImGui.Begin("Panel acceptance", ref open, (int)NativeWindowFlags.NoSavedSettings); + try { - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)ImGuiCond.Always); - NativeImGui.SetNextWindowSize(m_panelSize, (int)ImGuiCond.Always); - bool open = true; - _ = NativeImGui.Begin("Panel acceptance", ref open, (int)ImGuiWindowFlags.NoSavedSettings); - try - { - if (panel.isOpen && !panel.Draw(runtime.context)) - { - logs.Flush(); - string failures = string.Join( - Environment.NewLine, - console.Capture().occurrences - .Where(static entry => entry.level >= LogLevel.Error) - .Select(static entry => entry.message + Environment.NewLine + entry.stackTrace) - ); - throw new InvalidOperationException("The actual panel was quarantined: " + panel.id + Environment.NewLine + failures); - } - afterDraw?.Invoke(); - } - finally + if (panel.isOpen && !panel.Draw(runtime.context)) { - NativeImGui.End(); + logs.Flush(); + string failures = string.Join( + Environment.NewLine, + console.Capture().occurrences + .Where(static entry => entry.level >= LogLevel.Error) + .Select(static entry => entry.message + Environment.NewLine + entry.stackTrace) + ); + throw new InvalidOperationException("The actual panel was quarantined: " + panel.id + Environment.NewLine + failures); } - }, deltaTime); - } + afterDraw?.Invoke(); + } + finally + { + NativeImGui.End(); + } + }, deltaTime); /// /// Releases the owned UI, native context and services on their creating thread. @@ -327,7 +368,7 @@ private static void ValidateDrawData() internal sealed class InactivePlayMode : IEditorPlayMode { - private readonly Inno.Core.Events.EventDispatcher m_events = new(); + private readonly EventDispatcher m_events = new(); public EditorPlayModeState state => EditorPlayModeState.Editing; public bool isPlaying => false; public string? lastFailure => null; diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs index c25303827..c48958ecc 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativePanelInput.cs @@ -15,40 +15,56 @@ public static unsafe class NativePanelInput /// /// Focuses the actual active native window matching the requested fragment. /// - /// The current thread's live native host. - /// The panel drawn to discover its window. - /// The required fragment of the actual native window name. - /// No active native window matches the fragment. + /// + /// The current thread's live native host. + /// + /// + /// The panel drawn to discover its window. + /// + /// + /// The required fragment of the actual native window name. + /// + /// + /// No active native window matches the fragment. + /// public static void Focus( NativePanelHost host, EditorPanelExtension panel, string windowFragment - ) { - host.DrawPanel(panel, () => + ) => host.DrawPanel(panel, () => + { + ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); + for (int index = 0; index < context->Windows.Size; index++) { - ImGuiNativeContext* context = NativeImGui.Raw.GetCurrentContext(); - for (int index = 0; index < context->Windows.Size; index++) + ImGuiWindow* window = context->Windows.Data[index]; + string? name = Marshal.PtrToStringUTF8((nint)window->Name); + if (window->Active != 0 && name?.Contains(windowFragment, StringComparison.Ordinal) == true) { - ImGuiWindow* window = context->Windows.Data[index]; - string? name = Marshal.PtrToStringUTF8((nint)window->Name); - if (window->Active != 0 && name?.Contains(windowFragment, StringComparison.Ordinal) == true) - { - NativeImGui.Raw.SetWindowFocus(window->Name); - return; - } + NativeImGui.Raw.SetWindowFocus(window->Name); + return; } - throw new InvalidOperationException("The actual input owner window is absent: " + windowFragment); - }); - } + } + throw new InvalidOperationException("The actual input owner window is absent: " + windowFragment); + }); /// /// Delivers a complete key press and release through actual native frames. /// - /// The current thread's live native host. - /// The panel receiving input. - /// The native key to press. - /// Whether to hold Shift during the key press. - /// Whether to hold the fixture's Control convention during the key press. + /// + /// The current thread's live native host. + /// + /// + /// The panel receiving input. + /// + /// + /// The native key to press. + /// + /// + /// Whether to hold Shift during the key press. + /// + /// + /// Whether to hold the fixture's Control convention during the key press. + /// public static void Key( NativePanelHost host, EditorPanelExtension panel, diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs index c1aab50c1..8087c1e3c 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelHost.cs @@ -43,10 +43,18 @@ public sealed class NativeProjectPanelHost : IDisposable /// /// Creates the explicit test composition and its isolated project resources. /// - /// The calling test assembly declaring all discovered modules and serialized test types. - /// Whether to advertise and validate native vertex offsets. - /// Whether to compose real project and build settings services. - /// An optional public document-store boundary for settings persistence. + /// + /// The calling test assembly declaring all discovered modules and serialized test types. + /// + /// + /// Whether to advertise and validate native vertex offsets. + /// + /// + /// Whether to compose real project and build settings services. + /// + /// + /// An optional public document-store boundary for settings persistence. + /// public NativeProjectPanelHost( Assembly composition, bool supportsVertexOffsets = false, @@ -75,7 +83,7 @@ public NativeProjectPanelHost( }); m_execution = m_session.EnterExecutionScope(); var identities = new IdentityAllocator(); - assets = new AssetPipeline( + this.assets = new AssetPipeline( m_engine.modules, m_engine.types, m_engine.serialization, @@ -104,7 +112,7 @@ public NativeProjectPanelHost( m_console = new EditorConsole(m_engine.logs, m_engine.diagnostics, new NativePanelHost.InactivePlayMode()); m_console.Start(); var ui = new EditorUiSession(); - reloads = new EditorReloadCoordinator(); + this.reloads = new EditorReloadCoordinator(); SettingsPanelServices? settingsServices = includeSettings ? new SettingsPanelServices(m_root, assets, m_plugins, m_settings, m_engine) : null; @@ -112,7 +120,7 @@ public NativeProjectPanelHost( { _ = Assembly.Load("Inno.Editor.Panel.Settings"); } - runtime = new EditorInteractionRuntime( + this.runtime = new EditorInteractionRuntime( new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Ctrl")), m_engine.types, m_engine.logs, @@ -133,11 +141,11 @@ public NativeProjectPanelHost( ); runtime.Start(); _ = runtime.panelCount; - Assert.True(runtime.interactions.TryGetModule(out var probe)); - workspace = probe!.workspace; - graphs = probe.graphs; - edits = probe.edits; - native = new NativePanelHost(runtime, ui, m_console, m_engine.logs, m_engine.diagnostics, supportsVertexOffsets); + Assert.True(runtime.interactions.TryGetModule(out NativeProjectPanelProbe? probe)); + this.workspace = probe!.workspace; + this.graphs = probe.graphs; + this.edits = probe.edits; + this.native = new NativePanelHost(runtime, ui, m_console, m_engine.logs, m_engine.diagnostics, supportsVertexOffsets); } /// @@ -193,7 +201,9 @@ public NativeProjectPanelHost( /// /// Creates and loads an additive scene in the owned Edit session. /// - /// The scene owned by this fixture's session. + /// + /// The scene owned by this fixture's session. + /// public GameScene CreateScene() => m_session.scenes.LoadNewSceneAdditive(); /// diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs index dd0d0e66e..ed7251eaa 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/NativeProjectPanelProbe.cs @@ -8,9 +8,15 @@ namespace Inno.Testing.Editor.Native; /// /// Resolves the actual workspace and editing services through public Editor module composition. /// -/// The composed scene workspace. -/// The composed graph editor module. -/// The composed scene editing service. +/// +/// The composed scene workspace. +/// +/// +/// The composed graph editor module. +/// +/// +/// The composed scene editing service. +/// [EditorModule("tests.native-project-panels", order: 2000)] public sealed class NativeProjectPanelProbe( IEditorSceneWorkspace workspace, diff --git a/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs b/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs index 6cf1b3155..6e0f6e3e7 100644 --- a/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs +++ b/tests/editor/fixtures/Inno.Testing.Editor.Native/SettingsPanelServices.cs @@ -49,7 +49,7 @@ [new GameBuildTargetBinding(target, target)], engine.serialization, BuildSettings.CreateDefault("Settings acceptance", string.Empty, target.id) ); - services = [pipeline, build]; + this.services = [pipeline, build]; } internal IReadOnlyList services { get; } diff --git a/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs b/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs index 3517587b2..4e50a13db 100644 --- a/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs +++ b/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs @@ -165,7 +165,7 @@ public void Dispose() public void LoadAndReloadPublishOnlyTheActiveGeneration() { AssemblyModuleHandle handle = LoadVersion("V1"); - TypeRef previousRef = new(S_RELOADABLE_TYPE_ID); + var previousRef = new TypeRef(S_RELOADABLE_TYPE_ID); Type previous = previousRef.Resolve(m_types); Assert.Equal(1, ReadVersion(previous)); int previousRuntimeId = m_types.GetTypeRef(previous).runtimeId; @@ -394,7 +394,7 @@ public void CompletionCleanupFailureDoesNotUndoPublicationOrSkipFollowingPartici Assert.Equal(1, throwing.completeCount); Assert.Equal(1, following.completeCount); Assert.Equal(2, m_modules.modules.Single().generation); - Assert.Equal(Inno.Extensibility.Reload.GenerationState.Faulted, m_modules.generations.state); + Assert.Equal(GenerationState.Faulted, m_modules.generations.state); throwing.throwOnComplete = false; } @@ -445,7 +445,7 @@ public void RollbackCleanupFailureDoesNotSkipRemainingParticipants() Assert.Equal(1, observer.rollbackCount); Assert.Equal(1, throwing.rollbackCount); Assert.Equal(1, m_modules.modules.Single().generation); - Assert.Equal(Inno.Extensibility.Reload.GenerationState.Faulted, m_modules.generations.state); + Assert.Equal(GenerationState.Faulted, m_modules.generations.state); } [Fact] diff --git a/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs b/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs index 9ecdff78f..64a730b05 100644 --- a/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs +++ b/tests/extensibility/Inno.Extensibility.Modules.Tests/HostLoadContextTests.cs @@ -53,11 +53,11 @@ private static WeakReference DiscoverInIsolatedContext(string cache) object options = Activator.CreateInstance(optionsType)!; optionsType.GetProperty(nameof(ModuleHostOptions.catalogSource))!.SetValue(options, source); Type hostType = modules.GetType(typeof(ModuleHost).FullName!, throwOnError: true)!; - using var host = (IDisposable)Activator.CreateInstance(hostType, options)!; + using IDisposable host = (IDisposable)Activator.CreateInstance(hostType, options)!; Type catalogType = types.GetType(typeof(TypeCatalog).FullName!, throwOnError: true)!; Type metadataType = adapter.GetType(typeof(ReflectionTypeCatalogSource).FullName!, throwOnError: true)!; object metadata = Activator.CreateInstance(metadataType)!; - using var catalog = (IDisposable)Activator.CreateInstance(catalogType, host, metadata)!; + using IDisposable catalog = (IDisposable)Activator.CreateInstance(catalogType, host, metadata)!; object snapshot = catalogType.GetProperty(nameof(TypeCatalog.current))!.GetValue(catalog)!; MethodInfo query = snapshot.GetType().GetMethod(nameof(TypeCacheSnapshot.TryGetTypeRef))!; Assert.True((bool)query.Invoke(snapshot, [hostType, null])!); diff --git a/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs b/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs index cb294facf..720e16709 100644 --- a/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs +++ b/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleRetirementTests.cs @@ -28,7 +28,7 @@ public void PendingParticipantDoesNotBeginUnloadingEitherLiveGeneration(string p var participant = new Participant(); using IDisposable registration = modules.RegisterCatalogParticipant(participant); participant.phase = phase; - var reload = modules.BeginReload(handle, Request("V2", cache)); + AssemblyReloadSession reload = modules.BeginReload(handle, Request("V2", cache)); AssemblyLoadContext previous = Context(reload.context.previousCatalog); AssemblyLoadContext candidate = Context(reload.context.candidateCatalog); int unloads = 0; @@ -83,7 +83,7 @@ public void WrappedPendingKeepsBothCollectibleContextsAndPreservesTheOriginalFai new InvalidOperationException("completed sibling"), new InvalidOperationException("native owner", new RetirementTimeoutException("callback still active")) ); - var reload = modules.BeginReload(handle, Request("V2", cache)); + AssemblyReloadSession reload = modules.BeginReload(handle, Request("V2", cache)); int unloads = 0; Context(reload.context.previousCatalog).Unloading += _ => unloads++; Context(reload.context.candidateCatalog).Unloading += _ => unloads++; @@ -135,7 +135,7 @@ public void CatalogParticipantErrorsBeforePendingDoNotDisappearOrUnloadEitherCon using IDisposable second = modules.RegisterCatalogParticipant(phase == "complete" ? pending : ordinary); ordinary.phase = phase; pending.phase = phase; - var reload = modules.BeginReload(handle, Request("V2", cache)); + AssemblyReloadSession reload = modules.BeginReload(handle, Request("V2", cache)); int unloads = 0; Context(reload.context.previousCatalog).Unloading += _ => unloads++; Context(reload.context.candidateCatalog).Unloading += _ => unloads++; @@ -173,7 +173,7 @@ public void RejectedCatalogActivationRemainsVisibleWhenItsRollbackIsPending() using IDisposable registration = modules.RegisterCatalogParticipant(participant); participant.phase = "rollback"; participant.activationFailure = new InvalidOperationException("catalog activation rejected"); - var reload = modules.BeginReload(handle, Request("V2", cache)); + AssemblyReloadSession reload = modules.BeginReload(handle, Request("V2", cache)); int unloads = 0; Context(reload.context.previousCatalog).Unloading += _ => unloads++; Context(reload.context.candidateCatalog).Unloading += _ => unloads++; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs index 7f0a554a6..818101692 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/AssemblyExtensionsTests.cs @@ -12,7 +12,7 @@ public sealed class AssemblyExtensionsTests [Fact] public void AssemblyClassificationReadsBothMetadataDimensions() { - var asm = BuildDynamicAssembly("InnoPlugin", "Editor"); + Assembly asm = BuildDynamicAssembly("InnoPlugin", "Editor"); Assert.Equal(AssemblyDomain.InnoPlugin, asm.GetInnoAssemblyDomain()); Assert.Equal(AssemblyScope.Editor, asm.GetInnoAssemblyScope()); } @@ -20,7 +20,7 @@ public void AssemblyClassificationReadsBothMetadataDimensions() [Fact] public void MissingClassificationIsRejected() { - var asm = BuildDynamicAssembly(null, null); + Assembly asm = BuildDynamicAssembly(null, null); Assert.Throws(() => asm.GetInnoAssemblyDomain()); Assert.Throws(() => asm.GetInnoAssemblyScope()); } @@ -30,21 +30,17 @@ private static Assembly BuildDynamicAssembly( string? scopeName ) { var asmName = new AssemblyName("Inno.Dynamic." + Guid.NewGuid().ToString("N")); - var asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); + AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); if (domainName is not null && scopeName is not null) { - var ctor = typeof(AssemblyMetadataAttribute).GetConstructor(new[] { typeof(string), typeof(string) })!; - asmBuilder.SetCustomAttribute( - new CustomAttributeBuilder(ctor, new object[] { "Inno.AssemblyDomain", domainName }) - ); - asmBuilder.SetCustomAttribute( - new CustomAttributeBuilder(ctor, new object[] { "Inno.AssemblyScope", scopeName }) - ); + ConstructorInfo ctor = typeof(AssemblyMetadataAttribute).GetConstructor([typeof(string), typeof(string)])!; + asmBuilder.SetCustomAttribute(new CustomAttributeBuilder(ctor, ["Inno.AssemblyDomain", domainName])); + asmBuilder.SetCustomAttribute(new CustomAttributeBuilder(ctor, ["Inno.AssemblyScope", scopeName])); } - var module = asmBuilder.DefineDynamicModule("main"); - var type = module.DefineType("Inno.Dynamic.Placeholder", TypeAttributes.Public | TypeAttributes.Class); + ModuleBuilder module = asmBuilder.DefineDynamicModule("main"); + TypeBuilder type = module.DefineType("Inno.Dynamic.Placeholder", TypeAttributes.Public | TypeAttributes.Class); _ = type.CreateType(); return asmBuilder; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs index 55e020382..bded39264 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs @@ -80,8 +80,8 @@ private sealed class CandidateOwnershipRegistry(TypeCatalog types) : TypeRegistr protected override object[] Build(TypeCacheSnapshot types) { - var first = OwnCandidateExtension(new Resource(this, ++m_nextId)); - var second = OwnCandidateExtension(new Resource(this, ++m_nextId)); + Resource first = OwnCandidateExtension(new Resource(this, ++m_nextId)); + Resource second = OwnCandidateExtension(new Resource(this, ++m_nextId)); if (failBuild) { throw new InvalidOperationException("Expected candidate validation failure."); @@ -187,7 +187,7 @@ public void NewlyLoadedHostAssemblyAppearsAfterCatalogRefresh() public void UnknownAndEmptyReferencesFailAgainstExplicitCatalog() { TypeRef empty = default; - TypeRef unknown = new(Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")); + var unknown = new TypeRef(Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")); Assert.False(empty.IsValid(m_types)); Assert.False(unknown.IsValid(m_types)); diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyATypes.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyATypes.cs index b60f4e75c..cc3f08153 100644 --- a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyATypes.cs +++ b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyATypes.cs @@ -1,16 +1,15 @@ using System; -namespace Inno.Extensibility.Types.TestAssets.A -{ - /// - /// Marks declarations from fixture assembly A for source-scoped discovery tests. - /// - [AttributeUsage(AttributeTargets.Class)] - public sealed class AssemblyAMarkerAttribute : Attribute; +namespace Inno.Extensibility.Types.TestAssets.A; - /// - /// Provides a marked declaration whose visibility follows fixture assembly A's active source registration. - /// - [AssemblyAMarker] - public sealed class AssemblyAMarkedType; -} +/// +/// Marks declarations from fixture assembly A for source-scoped discovery tests. +/// +[AttributeUsage(AttributeTargets.Class)] +public sealed class AssemblyAMarkerAttribute : Attribute; + +/// +/// Provides a marked declaration whose visibility follows fixture assembly A's active source registration. +/// +[AssemblyAMarker] +public sealed class AssemblyAMarkedType; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBTypes.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBTypes.cs index ac429e4ce..155f40eab 100644 --- a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBTypes.cs +++ b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBTypes.cs @@ -1,16 +1,15 @@ using System; -namespace Inno.Extensibility.Types.TestAssets.B -{ - /// - /// Marks declarations from fixture assembly B independently of fixture assembly A. - /// - [AttributeUsage(AttributeTargets.Class)] - public sealed class AssemblyBMarkerAttribute : Attribute; +namespace Inno.Extensibility.Types.TestAssets.B; - /// - /// Provides a distinct marked declaration for combined-source discovery and source-removal tests. - /// - [AssemblyBMarker] - public sealed class AssemblyBMarkedType; -} +/// +/// Marks declarations from fixture assembly B independently of fixture assembly A. +/// +[AttributeUsage(AttributeTargets.Class)] +public sealed class AssemblyBMarkerAttribute : Attribute; + +/// +/// Provides a distinct marked declaration for combined-source discovery and source-removal tests. +/// +[AssemblyBMarker] +public sealed class AssemblyBMarkedType; diff --git a/tests/fixtures/editor-ui/PanelLifecycle.editor.cs b/tests/fixtures/editor-ui/PanelLifecycle.editor.cs index 688a4abd3..82534e628 100644 --- a/tests/fixtures/editor-ui/PanelLifecycle.editor.cs +++ b/tests/fixtures/editor-ui/PanelLifecycle.editor.cs @@ -46,7 +46,7 @@ IEditorSceneWorkspace workspace private bool m_baselineCaptured; private bool m_completed; - /// + /// protected override void OnUpdate(EditorContext context) { if (m_completed) @@ -188,7 +188,7 @@ private static int ReadRequiredCycles() { string value = Environment.GetEnvironmentVariable("INNO_ACCEPTANCE_PANEL_CYCLES") ?? "100"; if (!int.TryParse(value, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int cycles) - || cycles < 100 || cycles > 10000 || cycles % 10 != 0 + || cycles < 100 || cycles > 10_000 || cycles % 10 != 0 ) { throw new InvalidOperationException("The lifecycle acceptance requires 100–10000 cycles in ten-cycle intervals."); } diff --git a/tests/input/Inno.Input.Tests/InputRuntimeTests.cs b/tests/input/Inno.Input.Tests/InputRuntimeTests.cs index 7c2f89c19..ab533ec3e 100644 --- a/tests/input/Inno.Input.Tests/InputRuntimeTests.cs +++ b/tests/input/Inno.Input.Tests/InputRuntimeTests.cs @@ -31,8 +31,8 @@ public void WindowSourcesRemainIsolatedAcrossTextWheelAndRelease() { using var first = new EventInputSource(7); using var second = new EventInputSource(8); - using var firstBackend = first.CreateBackend(); - using var secondBackend = second.CreateBackend(); + using IInputBackend firstBackend = first.CreateBackend(); + using IInputBackend secondBackend = second.CreateBackend(); Event[] events = [ new KeyPressedEvent(7, KeyCode.Space), @@ -61,7 +61,7 @@ public void WindowSourcesRemainIsolatedAcrossTextWheelAndRelease() public void ApplicationSuspensionClearsTransientInputAndRejectsBackgroundPresses() { using var source = new EventInputSource(windowId: 7); - using var backend = source.CreateBackend(); + using IInputBackend backend = source.CreateBackend(); source.ProcessEvent(new KeyPressedEvent(7, KeyCode.Space)); source.ProcessEvent(new MouseButtonPressedEvent(7, MouseButton.Left)); source.ProcessEvent(new TextInputEvent(7, "x")); @@ -83,7 +83,7 @@ public void ApplicationSuspensionClearsTransientInputAndRejectsBackgroundPresses public void GloballyConsumedPlatformEventsNeverReachSessionInput() { using var source = new EventInputSource(windowId: 0); - using var backend = source.CreateBackend(); + using IInputBackend backend = source.CreateBackend(); var consumed = new KeyPressedEvent(42, KeyCode.Space); consumed.HandleInGlobal(); source.ProcessEvent(consumed); @@ -96,8 +96,8 @@ public void GloballyConsumedPlatformEventsNeverReachSessionInput() public void DisposingOneSessionDoesNotDisconnectOtherSessionSubscriptions() { using var source = new EventInputSource(windowId: 0); - var retired = source.CreateBackend(); - using var current = source.CreateBackend(); + IInputBackend retired = source.CreateBackend(); + using IInputBackend current = source.CreateBackend(); retired.Dispose(); source.ProcessEvent(new KeyPressedEvent(42, KeyCode.Space)); Assert.True(current.Capture(1).IsKeyDown(KeyCode.Space)); @@ -130,7 +130,7 @@ public void EventBackendCapturesTransitionsAndClearsTransientState() public void AllWindowSourceAcceptsDetachedWindowAndClearsItOnFocusLoss() { using var source = new EventInputSource(windowId: 0); - using var backend = source.CreateBackend(); + using IInputBackend backend = source.CreateBackend(); source.ProcessEvent(new KeyPressedEvent(42, KeyCode.Space)); source.ProcessEvent(new MouseButtonPressedEvent(42, MouseButton.Left)); diff --git a/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs b/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs index 917532965..c77615003 100644 --- a/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs +++ b/tests/input/Inno.Input.Tests/ShellLifecycleTests.cs @@ -22,6 +22,8 @@ using Inno.Text; using Inno.UI; +using ShellHost = Inno.Shell.Shell; + namespace Inno.Input.Tests; public sealed class ShellLifecycleTests @@ -30,7 +32,7 @@ public sealed class ShellLifecycleTests public async Task SuspensionReasonsComposeWithoutFramesOrBackgroundClockCatchUp() { var catalog = new TestCatalog(); - var elapsed = Stopwatch.StartNew(); + Stopwatch elapsed = Stopwatch.StartNew(); using var shell = new TestShell(catalog, suspendWhenHidden: true); Assert.Equal(ShellState.Ready, shell.state); int opportunities = 0; @@ -123,22 +125,22 @@ await Assert.ThrowsAnyAsync(() => shell.RunAsync( Assert.Equal(0, catalog.application.redrawSubscribers); } - private sealed class TestShell : Inno.Shell.Shell + private sealed class TestShell : ShellHost { public TestShell( TestCatalog catalog, bool suspendWhenHidden ) : base(catalog, new ShellOptions { - adapters = new Inno.Adapter.AdapterSelection + adapters = new AdapterSelection { - platform = Inno.Adapter.Platform.PlatformBackendId.sdl3, - input = Inno.Adapter.Input.InputBackendId.events, - rendering = Inno.Adapter.Rendering.RenderingBackendId.bgfx, - storage = Inno.Adapter.Storage.StorageBackendId.fileSystem, - audio = Inno.Adapter.Audio.AudioBackendId.miniAudio, - text = Inno.Adapter.Text.TextBackendId.freeTypeHarfBuzz, - ui = Inno.Adapter.UI.UiBackendId.rmlUi + platform = PlatformBackendId.sdl3, + input = InputBackendId.events, + rendering = RenderingBackendId.bgfx, + storage = StorageBackendId.fileSystem, + audio = AudioBackendId.miniAudio, + text = TextBackendId.freeTypeHarfBuzz, + ui = UiBackendId.rmlUi }, suspendWhenHidden = suspendWhenHidden }) @@ -177,7 +179,10 @@ protected override void OnStopping() private sealed class TestCatalog : IAdapterCatalog, IPlatformBackendFactory, IInputBackendFactory, IRenderingBackendFactory, IStorageBackendFactory, IAudioBackendFactory, ITextBackendFactory, IUiBackendFactory { - public TestCatalog() => application = new TestApplication(retired); + public TestCatalog() + { + this.application = new TestApplication(retired); + } public TestApplication application { get; } public List retired { get; } = []; diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs index e77fe3205..c50ab75dc 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs @@ -5,6 +5,7 @@ using System.Threading; using System.Threading.Tasks; using Xunit; +using Inno.Build.Composition; using Inno.Build.Distribution.Standard; using Inno.Build.SupportPacks; using Inno.Testing.Source; @@ -22,8 +23,13 @@ public async Task MatchingStaticDependenciesProduceARealManagedPlayerSupportPack ?? throw new InvalidOperationException("Browser product acceptance requires an explicit consume-only native selection."); Assert.True(File.Exists(manifest), "The selected immutable native dependency manifest must exist."); string dotnet = StandardBuildEnvironment.ResolveManagedHost(); - var context = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetId("windows-x64"), dotnet, manifest); - var distribution = StandardBuildDistribution.Create(context).build; + BuildCompositionContext context = StandardBuildEnvironment.Capture( + AppContext.BaseDirectory, + new BuildTargetId("windows-x64"), + dotnet, + manifest + ); + BuildDistribution distribution = StandardBuildDistribution.Create(context).build; var target = new BuildTargetId("browser-wasm"); string output = Path.Combine(root, "artifacts", "validation", "browser-support-pack"); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(20)); diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs index 405b06896..77388317d 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackAbiTests.cs @@ -26,9 +26,9 @@ public void BrowserPlatformChecksObjectAbiWithoutKnowingTheSelectedBackend() + "0".PadRight(6) + "644".PadRight(8) + "8".PadRight(10) + "`\n"; byte[] bytes = [.. Encoding.ASCII.GetBytes("!\n" + header), 0, 97, 115, 109, 1, 0, 0, 0]; File.WriteAllBytes(archive, bytes); - var validator = new Inno.Build.BrowserWasm32.BrowserWasm32SupportPackValidator(); + var validator = new BrowserWasm32SupportPackValidator(); validator.Validate(m_root); - bytes[^8] = 0x7f; + bytes[^8] = 0x7F; File.WriteAllBytes(archive, bytes); Assert.Contains("ABI", Assert.Throws(() => validator.Validate(m_root)).Message); } diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs index 857580108..2404c96ee 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Tests/BrowserSupportPackTests.cs @@ -70,7 +70,7 @@ public async Task BrowserPackRequiresItsStaticGameLinkerClosure() foreach (ProductNativeBuildStep step in plan.steps) { foreach (string archive in step.component.staticBuild!.logicalOutputs.Select( - Inno.Build.BrowserWasm32.BrowserWasm32LinkerSettings.Create().GetStaticFileName + BrowserWasm32LinkerSettings.Create().GetStaticFileName )) { Write(pack, $"PlayerLink/Native/{step.id}/browser-wasm/{archive}"); } diff --git a/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs b/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs index 520d91f50..47359d30c 100644 --- a/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs +++ b/tests/platforms/MacOSArm64/Inno.Build.MacOSArm64.Tests/SupportPackValidationTests.cs @@ -11,7 +11,7 @@ public sealed class SupportPackValidationTests : PlayerSupportPackFixture [Fact] public void PlatformPackRejectsAMissingContentSource() { - BuildTargetId target = new BuildTargetId("macos-arm64"); + var target = new BuildTargetId("macos-arm64"); string pack = GetSupportPackDirectory(target); string source = "MacOSArm64PlayerContentSource.cs"; File.Delete(Path.Combine(pack, "PlayerLink", source)); @@ -30,7 +30,7 @@ public void SupportPackRejectsAuthoringAssetPipelineAssemblies() var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator()) + () => catalog.Acquire(new BuildTargetId("macos-arm64"), new MacOSArm64SupportPackValidator()) ); Assert.Contains("forbidden build-time file", exception.Message, StringComparison.OrdinalIgnoreCase); @@ -44,7 +44,7 @@ public void SupportPackRejectsMissingMiniAudioRuntime() var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator()) + () => catalog.Acquire(new BuildTargetId("macos-arm64"), new MacOSArm64SupportPackValidator()) ); Assert.Contains("no longer matches", exception.Message, StringComparison.Ordinal); @@ -53,7 +53,7 @@ public void SupportPackRejectsMissingMiniAudioRuntime() [Fact] public void PlatformValidatorRejectsForeignAbiDespiteTheExpectedFilename() { - BuildTargetId target = new BuildTargetId("macos-arm64"); + var target = new BuildTargetId("macos-arm64"); string directory = GetSupportPackDirectory(target); string library = "libminiaudio-release.dylib"; File.WriteAllBytes( @@ -73,7 +73,7 @@ public void SupportPackRejectsForeignNativeRuntime() var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator()) + () => catalog.Acquire(new BuildTargetId("macos-arm64"), new MacOSArm64SupportPackValidator()) ); Assert.Contains("foreign native runtime", exception.Message, StringComparison.Ordinal); @@ -89,7 +89,7 @@ public void SupportPackRejectsMissingTextOrUiRuntime(string nativeRuntime) var catalog = new PlayerSupportPackCatalog(m_supportPackRoot); InvalidDataException exception = Assert.Throws( - () => catalog.Acquire(new BuildTargetId("macos-arm64"), new Inno.Build.MacOSArm64.MacOSArm64SupportPackValidator()) + () => catalog.Acquire(new BuildTargetId("macos-arm64"), new MacOSArm64SupportPackValidator()) ); Assert.Contains("no longer matches", exception.Message, StringComparison.Ordinal); diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs index ddbbff035..57f4c6a97 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/NativeBindingCMakeTests.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Xunit; +using Xunit.Sdk; using Inno.Build.Toolchains; using Inno.Build.WindowsX64; @@ -80,16 +81,16 @@ public async Task WindowsCompilationUsesFrozenHeadersAndKeepsBindingDefinesOutOf """); var compilation = new NativeBindingCompilation { - roots = [new("generated", "", true, true), new("user", headerRoot, false, true)], + roots = [new("generated", string.Empty, true, true), new("user", headerRoot, false, true)], files = [Input("generated", "binding.c", unit, true), Input("user", "api.h", header, false)], - includeDirectories = [new("user", "", false, false)], + includeDirectories = [new("user", string.Empty, false, false)], defines = ["INNO_BINDING_ONLY=1"], compilerDefines = [], cxxStandard = 0, cStandard = 17, requiredExports = ["value", "upstream"], staticExportSymbols = [], - staticExportAbi = "", + staticExportAbi = string.Empty, staticExportNames = [] }; File.WriteAllBytes(Path.Combine(native, "compilation.json"), JsonSerializer.SerializeToUtf8Bytes(compilation)); @@ -112,7 +113,7 @@ public async Task WindowsCompilationUsesFrozenHeadersAndKeepsBindingDefinesOutOf new Dictionary { [owner.nativeProject] = descriptor }, [] ); - var tools = await new WindowsX64NativeToolchainProvider(ToolchainEnvironment.ResolveExecutable("dotnet")) + NativeToolchainSelection tools = await new WindowsX64NativeToolchainProvider(ToolchainEnvironment.ResolveExecutable("dotnet")) .ResolveAsync( new(root, "release"), (new WindowsBuildHostProvider().TryCapture() @@ -151,7 +152,7 @@ public async Task WindowsCompilationUsesFrozenHeadersAndKeepsBindingDefinesOutOf catch (InvalidOperationException exception) { string requirements = Path.Combine(operation.GetNativeBuildRoot(owner), "CMake", "BindingInputs.cmake"); - throw new Xunit.Sdk.XunitException(exception + Environment.NewLine + File.ReadAllText(requirements)); + throw new XunitException(exception + Environment.NewLine + File.ReadAllText(requirements)); } File.Copy(NativeCMakeExecutor.FindOutput(operation, build, "fixture.dll"), Path.Combine(output, "fixture.dll")); } @@ -196,7 +197,7 @@ public WindowsCompilerFactAttribute() { if (!OperatingSystem.IsWindows()) { - Skip = "Requires the Windows MSVC toolchain and its path-length contract."; + this.Skip = "Requires the Windows MSVC toolchain and its path-length contract."; } } } diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs index 62297a568..6c0c978d9 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Integration.Tests/ToolchainWorkingDirectoryBuildTests.cs @@ -96,7 +96,7 @@ await File.WriteAllTextAsync(Path.Combine(root, "Program.cs"), """ File.WriteAllText(args[2], execution ?? "cache"); return 0; """); - var environment = DotNetSdkEnvironment.Create(dotnet); + IReadOnlyDictionary environment = DotNetSdkEnvironment.Create(dotnet); await ToolchainEnvironment.RunAsync( dotnet, ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-p:UseSharedCompilation=false"], @@ -113,7 +113,7 @@ await ToolchainEnvironment.RunAsync( ("third", "first-temp", false), ("third", "second-temp", true) ]; - foreach (var call in calls) + foreach ((string value, string temporary, bool hit) call in calls) { string temporary = Path.Combine(root, call.temporary); Directory.CreateDirectory(temporary); diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs index c840a0062..6fc2ad9e3 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/SupportPackValidationTests.cs @@ -11,7 +11,7 @@ public sealed class SupportPackValidationTests : PlayerSupportPackFixture [Fact] public void PlatformPackRejectsAMissingContentSource() { - BuildTargetId target = new BuildTargetId("windows-x64"); + var target = new BuildTargetId("windows-x64"); string pack = GetSupportPackDirectory(target); string source = "WindowsX64PlayerContentSource.cs"; File.Delete(Path.Combine(pack, "PlayerLink", source)); @@ -25,7 +25,7 @@ public void PlatformPackRejectsAMissingContentSource() [Fact] public void PlatformValidatorRejectsForeignAbiDespiteTheExpectedFilename() { - BuildTargetId target = new BuildTargetId("windows-x64"); + var target = new BuildTargetId("windows-x64"); string directory = GetSupportPackDirectory(target); string library = "miniaudio-release.dll"; File.WriteAllBytes( diff --git a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs index 7fdf65153..c71c02346 100644 --- a/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs +++ b/tests/platforms/WindowsX64/Inno.Build.WindowsX64.Tests/ToolchainWorkingDirectoryTests.cs @@ -52,7 +52,7 @@ public async Task OpeningExistingToolOutputsPreservesThePublishedArtifactFileSet string outputs = Path.Combine(artifact, "Outputs"); Directory.CreateDirectory(outputs); File.WriteAllText(Path.Combine(outputs, "tool.bin"), "immutable"); - string fingerprint = new('c', 64); + var fingerprint = new string('c', 64); BuildArtifactManifest.Write(artifact, fingerprint, ["Outputs"]); Assert.True(BuildArtifactManifest.IsComplete(artifact, fingerprint, ["Outputs"])); using (ToolchainWorkingDirectory owner = await CreateProvider().OpenAsync(outputs)) @@ -74,7 +74,7 @@ await Assert.ThrowsAsync(async () => } string physical = Path.Combine(m_root, "Owned"); using ToolchainWorkingDirectory owner = await CreateProvider().OpenAsync(physical); - using CancellationTokenSource cancellation = new(TimeSpan.FromMilliseconds(150)); + using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(150)); await Assert.ThrowsAnyAsync(async () => await new WindowsToolchainWorkspaceProvider().OpenAsync(physical, cancellation.Token)); Assert.True(Directory.Exists(owner.toolPath)); diff --git a/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs b/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs index 626c32d58..bddcef0dc 100644 --- a/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs +++ b/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs @@ -3,6 +3,7 @@ using System.IO; using System.IO.Compression; using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -90,10 +91,10 @@ public void CorruptedMaterializedCacheIsRejectedAndCanBeRebuiltWithoutChangingPa PluginScanResult first = service.Scan(); PluginCandidate candidate = Assert.Single(first.candidates); string cachedFile = Directory.EnumerateFiles(candidate.sourceMount.rootPath, "*.txt", SearchOption.AllDirectories).Single(); - byte[] original = System.IO.File.ReadAllBytes(cachedFile); + byte[] original = File.ReadAllBytes(cachedFile); byte[] changed = original.ToArray(); changed[0] ^= 1; - System.IO.File.WriteAllBytes(cachedFile, changed); + File.WriteAllBytes(cachedFile, changed); PluginScanResult corrupted = service.Scan(); Assert.Empty(corrupted.candidates); Assert.Contains("invalid bytes", Assert.Single(corrupted.diagnostics).message); @@ -101,7 +102,7 @@ public void CorruptedMaterializedCacheIsRejectedAndCanBeRebuiltWithoutChangingPa PluginScanResult restored = service.Scan(); Assert.Empty(restored.diagnostics); Assert.Equal(candidate.contentHash, Assert.Single(restored.candidates).contentHash); - Assert.Equal(original, System.IO.File.ReadAllBytes(cachedFile)); + Assert.Equal(original, File.ReadAllBytes(cachedFile)); } [Fact] @@ -156,7 +157,7 @@ public void CodePluginActivatesImmediatelyAfterValidation() PluginCandidate active = Assert.Single(PluginSourceService.GetActivatableCandidates(scan)); Assert.True(active.sourceMount.isReadOnly); Assert.Equal("tests.code", active.sourceMount.id.value); - Assert.True(System.IO.File.Exists(Path.Combine(active.sourceMount.rootPath, "Plugin.cs"))); + Assert.True(File.Exists(Path.Combine(active.sourceMount.rootPath, "Plugin.cs"))); } [Fact] @@ -193,7 +194,7 @@ public void RemovingAnActiveCodePackageKeepsTheLastGoodSnapshotUntilAtomicRemova PluginCandidate active = Assert.Single(m_environment!.activePlugins); string activeSnapshotRoot = active.sourceMount.rootPath; - System.IO.File.Delete(sourcePath); + File.Delete(sourcePath); Assert.True(m_environment.Refresh()); Assert.True(m_environment.hasPendingActivation); @@ -236,7 +237,7 @@ public void StructurallyInvalidActivePluginStagesAnUnavailableGeneration() StartEnvironment(service.Scan()); Assert.Single(m_environment!.activePlugins); - System.IO.File.WriteAllBytes(sourcePath, [0x49, 0x4E, 0x4E, 0x4F]); + File.WriteAllBytes(sourcePath, [0x49, 0x4E, 0x4E, 0x4F]); Assert.True(m_environment.Refresh()); Assert.True(m_environment.hasPendingActivation); @@ -302,16 +303,16 @@ public void InvalidAssetMetadataUpdateStagesAnUnavailableGenerationWithoutThrowi public void OperatingSystemMetadataBesidePackageDoesNotAffectIdentity() { WritePlugin("metadata.iplugin", Manifest("tests.package-metadata"), TextContent("content")); - System.IO.File.WriteAllBytes(Path.Combine(m_plugins, ".DS_Store"), [1, 2, 3]); - System.IO.File.WriteAllBytes(Path.Combine(m_plugins, "Thumbs.db"), [4, 5, 6]); + File.WriteAllBytes(Path.Combine(m_plugins, ".DS_Store"), [1, 2, 3]); + File.WriteAllBytes(Path.Combine(m_plugins, "Thumbs.db"), [4, 5, 6]); var service = new PluginSourceService(m_serialization, m_plugins, m_library); PluginScanResult withMetadata = service.Scan(); Assert.Empty(withMetadata.diagnostics); string contentHash = Assert.Single(withMetadata.candidates).contentHash; - System.IO.File.Delete(Path.Combine(m_plugins, ".DS_Store")); - System.IO.File.Delete(Path.Combine(m_plugins, "Thumbs.db")); + File.Delete(Path.Combine(m_plugins, ".DS_Store")); + File.Delete(Path.Combine(m_plugins, "Thumbs.db")); PluginScanResult withoutMetadata = service.Scan(); Assert.Empty(withoutMetadata.diagnostics); Assert.Equal(contentHash, Assert.Single(withoutMetadata.candidates).contentHash); @@ -331,7 +332,7 @@ public void OperatingSystemMetadataInsidePackageDoesNotInvalidateOrChangeIdentit Assert.Empty(withMetadata.diagnostics); string contentHash = Assert.Single(withMetadata.candidates).contentHash; - System.IO.File.Delete(Path.Combine(m_plugins, "metadata.iplugin")); + File.Delete(Path.Combine(m_plugins, "metadata.iplugin")); WritePlugin("metadata.iplugin", manifest, TextContent("content")); PluginScanResult withoutMetadata = service.Scan(); Assert.Empty(withoutMetadata.diagnostics); @@ -436,12 +437,12 @@ string expectedMessage public void SymbolicLinksAndExcessiveEntryCountsAreRejectedBeforeExtraction() { string symbolicLinkPath = Path.Combine(m_plugins, "symbolic-link.iplugin"); - using (FileStream stream = System.IO.File.Create(symbolicLinkPath)) + using (FileStream stream = File.Create(symbolicLinkPath)) using (var archive = new ZipArchive(stream, ZipArchiveMode.Create)) { WriteEntry(archive, "Plugin.inno", m_serialization.Serialize(Manifest("tests.symbolic-link"))); ZipArchiveEntry link = archive.CreateEntry("Assets/link.txt"); - link.ExternalAttributes = unchecked((int)0xA1FF0000); + link.ExternalAttributes = unchecked((int)0xA1FF_0000); WriteEntry(archive, "Assets/link.txt.imeta", [1]); } @@ -451,7 +452,7 @@ public void SymbolicLinksAndExcessiveEntryCountsAreRejectedBeforeExtraction() Assert.Empty(symbolicLink.candidates); Assert.Contains("symbolic link", Assert.Single(symbolicLink.diagnostics).message, StringComparison.OrdinalIgnoreCase); - System.IO.File.Delete(symbolicLinkPath); + File.Delete(symbolicLinkPath); WritePlugin("entry-count.iplugin", Manifest("tests.entry-count"), TextContent("bounded")); var entryCountService = new PluginSourceService( m_serialization, @@ -475,7 +476,7 @@ public void ArchiveLimitsRejectOversizedOrSuspiciousContent( string expectedMessage ) { byte[] first = scenario == "ratio" ? new byte[4096] : CreateNoise(1024, seed: 17); - Dictionary entries = new() + var entries = new Dictionary() { ["Assets/first.data"] = first, ["Assets/first.data.imeta"] = [1] @@ -742,7 +743,10 @@ public void RollbackObserverPendingKeepsTheOwnerUntilAllRollbackStagesComplete() Assert.True(m_environment!.Refresh()); m_environment.ActivatePending(); AssetSourceMountTransaction candidate = m_environment.compilationAssets!; - var failure = new InvalidOperationException("observer context", new RetirementPendingException("rollback work")); + var failure = new InvalidOperationException( + "observer context", + new RetirementPendingException("rollback work") + ); bool laterCalled = false; Action blocked = () => throw failure; Action later = () => laterCalled = true; @@ -853,7 +857,7 @@ params string[] dependencies private static Dictionary TextContent(string value) => new() { - ["Assets/content.txt"] = System.Text.Encoding.UTF8.GetBytes(value), + ["Assets/content.txt"] = Encoding.UTF8.GetBytes(value), ["Assets/content.txt.imeta"] = [1] }; @@ -884,7 +888,7 @@ private void WritePluginWithManifestBytes( IReadOnlyDictionary entries ) { string path = Path.Combine(m_plugins, fileName); - using FileStream stream = System.IO.File.Create(path); + using FileStream stream = File.Create(path); using var archive = new ZipArchive(stream, ZipArchiveMode.Create); WriteEntry(archive, "Plugin.inno", manifestBytes); foreach ((string entryPath, byte[] bytes) in entries) @@ -900,19 +904,19 @@ IReadOnlyDictionary entries ) { string root = Path.Combine(m_plugins, directoryName); Directory.CreateDirectory(root); - System.IO.File.WriteAllBytes(Path.Combine(root, "Plugin.inno"), m_serialization.Serialize(manifest)); + File.WriteAllBytes(Path.Combine(root, "Plugin.inno"), m_serialization.Serialize(manifest)); foreach ((string entryPath, byte[] bytes) in entries) { string physicalPath = Path.Combine(root, entryPath.Replace('/', Path.DirectorySeparatorChar)); Directory.CreateDirectory(Path.GetDirectoryName(physicalPath)!); - System.IO.File.WriteAllBytes(physicalPath, bytes); + File.WriteAllBytes(physicalPath, bytes); } } private void WriteArchiveWithDuplicateEntry(string fileName) { string path = Path.Combine(m_plugins, fileName); - using FileStream stream = System.IO.File.Create(path); + using FileStream stream = File.Create(path); using var archive = new ZipArchive(stream, ZipArchiveMode.Create); WriteEntry(archive, "Plugin.inno", m_serialization.Serialize(Manifest("tests.duplicate-entry"))); WriteEntry(archive, "Assets/value.txt", [1]); @@ -950,8 +954,7 @@ defaults with } private void StartEnvironment(PluginScanResult scan) - { - m_environment = new PluginEnvironment( + => m_environment = new PluginEnvironment( m_assets ?? throw new InvalidOperationException("Project assets must be initialized first."), m_settings, m_serialization, @@ -960,7 +963,6 @@ private void StartEnvironment(PluginScanResult scan) scan, m_modules.generations ); - } private byte[] CreateTextSourceMeta() => m_serialization.Serialize(new TestAssetSourceMeta diff --git a/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs b/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs index ace074165..e14fd69c5 100644 --- a/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs +++ b/tests/process/Inno.Testing.Discovery.TestLogger/DiscoveryLogger.cs @@ -16,19 +16,19 @@ namespace Inno.Testing.Discovery; [FriendlyName("InnoDiscovery")] public sealed class DiscoveryLogger : ITestLoggerWithParameters { - /// /// /// The logger requires the parameterized overload with an explicit receipt path. /// + /// public void Initialize( TestLoggerEvents events, string testRunDirectory ) => throw new ArgumentException("Discovery requires an explicit receipt path."); - /// /// /// The Receipt parameter is missing or does not identify an absolute output path. /// + /// public void Initialize( TestLoggerEvents events, Dictionary parameters @@ -38,7 +38,9 @@ public void Initialize( throw new ArgumentException("Discovery requires an absolute receipt path."); } - var owners = new Dictionary(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + var owners = new Dictionary( + OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal + ); var errors = new List(); events.DiscoveryMessage += ( _, @@ -74,7 +76,7 @@ public void Initialize( completion ) => { - using FileStream output = new(receipt!, FileMode.CreateNew, FileAccess.Write, FileShare.None); + using var output = new FileStream(receipt!, FileMode.CreateNew, FileAccess.Write, FileShare.None); JsonSerializer.Serialize(output, new { completed = !completion.IsAborted && errors.Count == 0 diff --git a/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs b/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs index dae289364..b53b7ea65 100644 --- a/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs +++ b/tests/references/Inno.References.Tests/ReferenceCatalogTests.cs @@ -42,7 +42,7 @@ public void RecoveryTransaction_RollsBackAppliedParticipantsInReverseOrder() var target = new Target(); Assert.True(allocator.Register(target)); var descriptor = new ReferenceDescriptor(S_KIND, target.identity.persistentId); - var catalog = ReferenceCatalog.Create(1, [new FixedResolver(S_KIND, target.identity.runtimeIdentity)]); + ReferenceCatalog catalog = ReferenceCatalog.Create(1, [new FixedResolver(S_KIND, target.identity.runtimeIdentity)]); var events = new List(); var first = new RecordingParticipant("first", events); var second = new RecordingParticipant("second", events, failApply: true); @@ -68,10 +68,14 @@ public void RecoveryResolvesOnlyAfterObjectsExistAndRetainsNeutralResultsAfterCo var target = new Target(); allocator.Register(target); var descriptor = new ReferenceDescriptor(S_KIND, target.identity.persistentId); - var catalog = ReferenceCatalog.Create(1, [new FixedResolver(S_KIND, target.identity.runtimeIdentity)]); + ReferenceCatalog catalog = ReferenceCatalog.Create(1, [new FixedResolver(S_KIND, target.identity.runtimeIdentity)]); var events = new List(); var state = new SerializedMissingState(new ReferenceKey(Guid.NewGuid(), "asset"), descriptor, [1]); - var transaction = new ReferenceRecoveryTransaction(catalog, [state], [new RecordingParticipant("owner", events)]); + var transaction = new ReferenceRecoveryTransaction( + catalog, + [state], + [new RecordingParticipant("owner", events)] + ); Assert.Empty(events); Assert.Empty(transaction.changes); transaction.PrepareForActivation(); diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs index 9fbd65468..46ef7d479 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs @@ -54,7 +54,7 @@ public RenderingImporterIntegrationTests() _ = typeof(AssetSerializationServices); m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); - _ = new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target); + _ = new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target); m_types.Rebuild(); } @@ -95,13 +95,13 @@ public void LoaderUsesGraphShaderMaterialAndPipelineAssetsWithOneCompilationMode ); WriteBytes("Shaders/basic.ishader", GraphDocumentCodec.Encode(graph, m_serialization)); WriteText("Meshes/triangle.obj", "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"); - byte[] png = new byte[24]; + var png = new byte[24]; new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }.CopyTo(png, 0); BinaryPrimitives.WriteUInt32BigEndian(png.AsSpan(16, 4), 8); BinaryPrimitives.WriteUInt32BigEndian(png.AsSpan(20, 4), 4); WriteBytes("Textures/color.png", png); - using (var writer = CreateLoader(m_assets, m_library)) + using (AssetLoader writer = CreateLoader(m_assets, m_library)) { ShaderAsset shader = Assert.IsType(writer.Load(AssetPath.Project("Shaders/basic.ishader"), typeof(ShaderAsset))); @@ -119,7 +119,7 @@ public void LoaderUsesGraphShaderMaterialAndPipelineAssetsWithOneCompilationMode Assert.True(writer.Save(AssetPath.Project("Pipelines/default.irenderpipeline"), pipeline)); } - using var loader = CreateLoader(m_assets, m_library); + using AssetLoader loader = CreateLoader(m_assets, m_library); ShaderAsset loadedShader = Assert.IsType( loader.Load(AssetPath.Project("Shaders/basic.ishader"), typeof(ShaderAsset)) ); @@ -158,8 +158,8 @@ public void LoaderUsesGraphShaderMaterialAndPipelineAssetsWithOneCompilationMode [Fact] public void ShaderIncludesUseTheCandidateMountSnapshotAndDeclaredPluginDependencies() { - AssetSourceId providerId = new("tests.provider"); - AssetSourceId consumerId = new("tests.consumer"); + var providerId = new AssetSourceId("tests.provider"); + var consumerId = new AssetSourceId("tests.consumer"); string providerRoot = Path.Combine(m_root, "ProviderPlugin"); string consumerRoot = Path.Combine(m_root, "ConsumerPlugin"); Directory.CreateDirectory(providerRoot); @@ -185,11 +185,11 @@ public void ShaderIncludesUseTheCandidateMountSnapshotAndDeclaredPluginDependenc vec4 Evaluate() { return ProviderColor() * LocalValue(); } """ ); - AssetSourceMount project = new(AssetSourceId.project, m_assets, isReadOnly: false); - AssetSourceMount provider = new(providerId, providerRoot, isReadOnly: true); - AssetSourceMount undeclaredConsumer = new(consumerId, consumerRoot, isReadOnly: true); + var project = new AssetSourceMount(AssetSourceId.project, m_assets, isReadOnly: false); + var provider = new AssetSourceMount(providerId, providerRoot, isReadOnly: true); + var undeclaredConsumer = new AssetSourceMount(consumerId, consumerRoot, isReadOnly: true); - using (var undeclared = CreateLoader( + using (AssetLoader undeclared = CreateLoader( [project, provider, undeclaredConsumer], Path.Combine(m_root, "UndeclaredLibrary") )) { @@ -197,8 +197,8 @@ public void ShaderIncludesUseTheCandidateMountSnapshotAndDeclaredPluginDependenc Assert.Contains("did not declare dependency", error.Message, StringComparison.OrdinalIgnoreCase); } - AssetSourceMount declaredConsumer = new(consumerId, consumerRoot, isReadOnly: true, dependencies: [providerId]); - using var loader = CreateLoader([project, provider, declaredConsumer], Path.Combine(m_root, "DeclaredLibrary")); + var declaredConsumer = new AssetSourceMount(consumerId, consumerRoot, isReadOnly: true, dependencies: [providerId]); + using AssetLoader loader = CreateLoader([project, provider, declaredConsumer], Path.Combine(m_root, "DeclaredLibrary")); loader.Rescan(); ShaderFunctionAsset shader = Assert.IsType( loader.Load(new AssetPath(consumerId, "main.ishadersource"), typeof(ShaderFunctionAsset)) @@ -228,7 +228,7 @@ public void RuntimeExportStripsGraphAndFunctionArtifactsAndPreservesShaderIdenti GraphDocumentCodec.Encode(ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty), m_serialization) ); WriteReadOnlyShaderSource(m_assets, "Function.ishadersource", "vec4 Evaluate(vec4 color) { return color; }"); - using var loader = CreateLoader(m_assets, m_library); + using AssetLoader loader = CreateLoader(m_assets, m_library); ShaderAsset shader = Assert.IsType(loader.Load(AssetPath.Project("Surface.ishader"), typeof(ShaderAsset))); ShaderFunctionAsset function = Assert.IsType( loader.Load(AssetPath.Project("Function.ishadersource"), typeof(ShaderFunctionAsset)) @@ -265,7 +265,7 @@ public void OneShaderSourceLibraryExportsMultipleExplicitGraphFunctions() "Exposure", "Tint" ); - using var loader = CreateLoader(m_assets, m_library); + using AssetLoader loader = CreateLoader(m_assets, m_library); ShaderFunctionAsset library = Assert.IsType( loader.Load(AssetPath.Project("Library.ishadersource"), typeof(ShaderFunctionAsset)) ); @@ -300,13 +300,13 @@ public void InvalidGraphAutosaveSurvivesImportFailureAndRestartWithoutLosingMiss graph.AddNode(new(new("missing"), "unavailable.shader-node")); graph.AddEdge(new(new("unresolved"), new(new("missing"), new("old-output")), new(new("fragment"), new("old-input")))); byte[] expected = GraphDocumentCodec.Encode(graph, m_serialization); - using (var pipeline = CreatePipeline()) + using (AssetPipeline pipeline = CreatePipeline()) { var store = new ShaderGraphSourceStore(pipeline, m_serialization); _ = store.Save(path, graph, null); Assert.Equal(expected, GraphDocumentCodec.Encode(store.Read(path).document, m_serialization)); } - using var restarted = CreatePipeline(); + using AssetPipeline restarted = CreatePipeline(); var reopened = new ShaderGraphSourceStore(restarted, m_serialization); Assert.Equal(expected, GraphDocumentCodec.Encode(reopened.Read(path).document, m_serialization)); } @@ -314,7 +314,7 @@ public void InvalidGraphAutosaveSurvivesImportFailureAndRestartWithoutLosingMiss [Fact] public void ShaderSaveRejectsExternalEditsDeletionAndNewFileCollisions() { - using var pipeline = CreatePipeline(); + using AssetPipeline pipeline = CreatePipeline(); var store = new ShaderGraphSourceStore(pipeline, m_serialization); AssetPath path = AssetPath.Project("conflict.ishader"); GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); @@ -348,7 +348,7 @@ public void ReadOnlyInstalledGraphCanBeReadButNeverAutosaved() }) ); var id = new AssetSourceId("test.installed"); - using var pipeline = CreatePipeline([new(AssetSourceId.project, m_assets, false), new(id, installed, true)]); + using AssetPipeline pipeline = CreatePipeline([new(AssetSourceId.project, m_assets, false), new(id, installed, true)]); var store = new ShaderGraphSourceStore(pipeline, m_serialization); var path = new AssetPath(id, "shader.ishader"); ShaderGraphSourceSnapshot snapshot = store.Read(path); @@ -381,7 +381,7 @@ public void NativePipelineSettingsCaptureNestedReferencesAndRestoreAgainstTheirO WriteBytes("surface.ishader", GraphDocumentCodec.Encode(graph, m_serialization)); using AssetPipeline assets = CreatePipeline(); ShaderAsset shader = assets.Load(AssetPath.Project("surface.ishader")); - SerializedRenderExtensionState state = new( + var state = new SerializedRenderExtensionState( assets.CaptureProperties(new NestedPipelineSettings { nested = new NestedPipelineReferences { shader = shader } @@ -405,7 +405,7 @@ public void NativePipelineSettingsCaptureNestedReferencesAndRestoreAgainstTheirO () => new RenderPipelineAsset().RestoreProperties(state.stableTypeId, state.propertyData, new NestedPipelineSettings()) ); Assert.Throws(() => context.Restore(loaded.pipelineState, new OtherPipelineSettings())); - using (AssetLoader other = new( + using var other = new AssetLoader( m_types, m_serialization, new IdentityAllocator(), @@ -413,24 +413,24 @@ public void NativePipelineSettingsCaptureNestedReferencesAndRestoreAgainstTheirO m_logs, m_assets, Path.Combine(m_root, "IsolatedLibrary") - )) { - var otherPipeline = Assert.IsType(other.Load(path, typeof(RenderPipelineAsset))); - var otherShader = Assert.IsType(other.Load(AssetPath.Project("surface.ishader"), typeof(ShaderAsset))); - Assert.Equal(shader.identity.persistentId, otherShader.identity.persistentId); - Assert.NotSame(shader, otherShader); - var second = new NestedPipelineSettings(); - new RenderExtensionStateContext(otherPipeline).Restore(otherPipeline.pipelineState, second); - Assert.Same(otherShader, second.nested.shader); - var firstAgain = new NestedPipelineSettings(); - ownedContext.Restore(loaded.pipelineState, firstAgain); - Assert.Same(shader, firstAgain.nested.shader); - } + ); + RenderPipelineAsset otherPipeline = Assert.IsType(other.Load(path, typeof(RenderPipelineAsset))); + ShaderAsset otherShader = Assert.IsType(other.Load(AssetPath.Project("surface.ishader"), typeof(ShaderAsset))); + Assert.Equal(shader.identity.persistentId, otherShader.identity.persistentId); + Assert.NotSame(shader, otherShader); + var second = new NestedPipelineSettings(); + new RenderExtensionStateContext(otherPipeline).Restore(otherPipeline.pipelineState, second); + Assert.Same(otherShader, second.nested.shader); + var firstAgain = new NestedPipelineSettings(); + ownedContext.Restore(loaded.pipelineState, firstAgain); + Assert.Same(shader, firstAgain.nested.shader); } [StableTypeId("5c438963-794a-4fde-bd59-45c00d7479de")] private sealed class NestedPipelineSettings : ISerializable { - [SerializableProperty] public NestedPipelineReferences nested { get; set; } + [SerializableProperty] + public NestedPipelineReferences nested { get; set; } } private struct NestedPipelineReferences @@ -457,7 +457,7 @@ byte[] bytes ) { string path = Path.Combine(m_assets, relativePath.Replace('/', Path.DirectorySeparatorChar)); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - System.IO.File.WriteAllBytes(path, bytes); + File.WriteAllBytes(path, bytes); } private void WriteReadOnlyShaderSource( @@ -469,8 +469,8 @@ params string[] exports if (exports.Length == 0) exports = ["Evaluate"]; string path = Path.Combine(root, localPath.Replace('/', Path.DirectorySeparatorChar)); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - System.IO.File.WriteAllText(path, content, Encoding.UTF8); - System.IO.File.WriteAllBytes( + File.WriteAllText(path, content, Encoding.UTF8); + File.WriteAllBytes( path + ".imeta", m_serialization.Serialize( new RenderingAssetSourceMeta @@ -511,7 +511,12 @@ internal sealed class RenderingAssetSourceMeta : ISerializable internal sealed class RenderingImportSettingsEnvelope : ISerializable { - [SerializableProperty] public Guid stableTypeId { get; set; } - [SerializableProperty] public byte[] properties { get; set; } = []; - [SerializableProperty] public Guid[] dependencies { get; set; } = []; + [SerializableProperty] + public Guid stableTypeId { get; set; } + + [SerializableProperty] + public byte[] properties { get; set; } = []; + + [SerializableProperty] + public Guid[] dependencies { get; set; } = []; } diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs index a7e48e613..fa4f54a8c 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderCompilerTests.cs @@ -111,7 +111,7 @@ public async Task UnsupportedAlternativePassKeepsSupportedPassAndExactBindingLay node.SetValue( "stage", ShaderGraphDocument.Encode( - "alternate." + ShaderGraphDocument.Read(node, "stage", "", m_serialization, SerializationContext.empty), + "alternate." + ShaderGraphDocument.Read(node, "stage", string.Empty, m_serialization, SerializationContext.empty), m_serialization, SerializationContext.empty ) diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs index 0fa80df3a..66a2c4cdc 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/ShaderGraphArtifactTests.cs @@ -29,10 +29,8 @@ public sealed class ShaderGraphArtifactTests : IDisposable public ShaderGraphArtifactTests() { - m_types = new(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new( - m_types, - new ReflectionSerializationMetadataSource() - ); + m_types = new(m_modules, new ReflectionTypeCatalogSource()); + m_serialization = new(m_types, new ReflectionSerializationMetadataSource()); } [Theory] @@ -104,14 +102,14 @@ public void TemporarilyEmptyInputNameRetainsItsMaterialDefaultWhileTyping() { GraphDocument graph = ShaderGraphTemplates.CreateRaster(m_serialization, SerializationContext.empty); GraphNodeRecord input = graph.FindNode(new("color"))!; - var settings = ShaderGraphDocument.Read( + ShaderGraphInputSettings settings = ShaderGraphDocument.Read( input, "settings", new ShaderGraphInputSettings(), m_serialization, SerializationContext.empty ); - settings.id = ""; + settings.id = string.Empty; graph = ShaderGraphBindings.ChangeInput(graph, input.id, settings, m_serialization, SerializationContext.empty); settings.id = "renamed-color"; graph = ShaderGraphBindings.ChangeInput(graph, input.id, settings, m_serialization, SerializationContext.empty); diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs index 8e41172a3..925bbeb5e 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs @@ -12,10 +12,13 @@ using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.Identity; +using Inno.Core.Input; +using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; +using Inno.Input; using Inno.References; using Inno.Rendering; using Inno.Rendering.Assets; @@ -382,7 +385,12 @@ public void TargetCapacityRejectsBeforeNativeAllocationAndReopensAfterRelease() IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); using var targets = new RenderTargetStore(backend, capacity: 1); backend.BeginFrame(); - var descriptor = new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment); + var descriptor = new RenderTextureDescriptor( + 16, + 16, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment + ); var first = new RenderTexture("First", descriptor); var second = new RenderTexture("Second", descriptor); var graph = new RenderGraphBuilder(1, backend.capabilities); @@ -426,7 +434,12 @@ public void TargetRetirementRetainsProgressAndOrdinaryErrorsAcrossPendingRetries IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); var targets = new RenderTargetStore(device); device.BeginFrame(); - var descriptor = new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment); + var descriptor = new RenderTextureDescriptor( + 16, + 16, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment + ); var graph = new RenderGraphBuilder(1, device.capabilities); targets.Import(graph, new RenderTexture("First", descriptor)); targets.Import(graph, new RenderTexture("Second", descriptor)); @@ -781,10 +794,10 @@ public void PrimaryOutputScalesLogicalWindowPointerToPhysicalPixels() IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); proxy.presentationSize = new RenderPresentationSize(2560, 1440); TestRequestProvider.enabled = true; - var snapshot = new Inno.Input.InputSnapshot( + var snapshot = new InputSnapshot( 1, - mousePosition: new Inno.Core.Mathematics.Vector2(400f, 274f), - mouseButtonsPressed: [Inno.Core.Input.MouseButton.Left] + mousePosition: new Vector2(400f, 274f), + mouseButtonsPressed: [MouseButton.Left] ); using var runtime = new RenderRuntime( m_types, @@ -799,7 +812,7 @@ public void PrimaryOutputScalesLogicalWindowPointerToPhysicalPixels() runtime.AfterRender(default); runtime.EndFrame(default); - Assert.Equal(new Inno.Core.Mathematics.Vector2(800f, 548f), TestRequestProvider.lastInput.pointerPosition); + Assert.Equal(new Vector2(800f, 548f), TestRequestProvider.lastInput.pointerPosition); Assert.Single(TestRequestProvider.lastInput.buttonsPressed); } @@ -1567,7 +1580,10 @@ private sealed class DisposablePipeline : RenderPipeline internal static int retirementAttempts { get; private set; } internal static bool retirementExpired { get; set; } - public DisposablePipeline() => createdCount++; + public DisposablePipeline() + { + createdCount++; + } public override void Build(RenderPipelineContext context) => _ = context; @@ -1707,8 +1723,7 @@ private sealed class SideEffectPipeline : RenderPipeline internal const string extensionId = "tests.runtime.side-effect"; public override void Build(RenderPipelineContext context) - { - context.graph + => context.graph .AddRasterPass( "Visible", new RenderPhaseId("tests.runtime.visible"), @@ -1719,7 +1734,6 @@ public override void Build(RenderPipelineContext context) ) => {} ) .HasSideEffect(); - } } [RenderPipelineExtension(extensionId)] @@ -2089,10 +2103,7 @@ public uint EndFrame() return checked((uint)endFrameCount); } - public void SetPrimaryPresentationSize(RenderPresentationSize? size) - { - primaryPresentationSize = size; - } + public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; public PersistentTextureHandle CreateTexture( RenderTextureDescriptor descriptor, @@ -2261,7 +2272,7 @@ private sealed class RecordingRenderDevice : RenderDevice, IRenderDevice internal RecordingRenderDevice(bool supportsReadback = false) { - capabilities = new GraphicsCapabilities( + this.capabilities = new GraphicsCapabilities( GraphicsApi.Noop, supportsReadback ? GraphicsCapability.TextureReadback : GraphicsCapability.None, new GraphicsLimits(64, 4, 4096, 8), @@ -2272,7 +2283,7 @@ internal RecordingRenderDevice(bool supportsReadback = false) originBottomLeft: false, homogeneousDepth: false ); - textureHandle = CreatePersistentTextureHandle(1UL, generation); + this.textureHandle = CreatePersistentTextureHandle(1UL, generation); m_readbackHandle = CreateRenderTextureReadbackHandle(1UL, generation); } diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs index d1ff87e19..eb5668757 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.Contributors.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using System.Text.Json; using Xunit; using Inno.Adapter.Modules.DotNet; @@ -22,7 +23,11 @@ public void CompletedOrRejectedFramesReleaseCollectibleSnapshotScratchAndGraphCa { DotNetModuleSource plugin = CreateRenderingPluginRequest(); m_modules.Load(plugin); - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy proxy), new TestDiagnosticSink()); + using var runtime = new RenderRuntime( + m_types, + TestDeviceProxy.Create(out TestDeviceProxy proxy), + new TestDiagnosticSink() + ); runtime.SetPrimaryModelOutputEnabled(false); WeakReference contributor = CompleteCollectibleContributorFrame(runtime, proxy, rejectGraph); (IAssemblyUnloadProbe monitor, IRenderRuntimeReloadTransaction transaction) = @@ -38,7 +43,11 @@ public void CompletedOrRejectedFramesReleaseCollectibleSnapshotScratchAndGraphCa [Fact] public void ContributorRegistrationChangesTakeEffectOnTheNextFrame() { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy proxy), new TestDiagnosticSink()); + using var runtime = new RenderRuntime( + m_types, + TestDeviceProxy.Create(out TestDeviceProxy proxy), + new TestDiagnosticSink() + ); runtime.SetPrimaryModelOutputEnabled(false); var first = new CountingContributor(); var next = new CountingContributor(); @@ -110,7 +119,11 @@ public void FrameAllocationMeasurementsUseTheRealPublicLifecycle( int contributorCount, bool fail ) { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy proxy), new TestDiagnosticSink()); + using var runtime = new RenderRuntime( + m_types, + TestDeviceProxy.Create(out TestDeviceProxy proxy), + new TestDiagnosticSink() + ); runtime.SetPrimaryModelOutputEnabled(false); var contributors = new List(); for (int index = 0; index < contributorCount; index++) @@ -152,7 +165,7 @@ bool fail bytesPerFrame = allocatedBytes / (double)frames, millisecondsPerFrame = elapsedMs / frames, graphCompileCount = ReadGraphCompileCount(runtime), - runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription + runtime = RuntimeInformation.FrameworkDescription }, new JsonSerializerOptions { WriteIndented = true }) ); } @@ -164,7 +177,11 @@ bool fail [InlineData(32)] public void ContributorRetirementMeasurementsIncludeRegistrationAndTheFollowingEmptyFrame(int contributorCount) { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy proxy), new TestDiagnosticSink()); + using var runtime = new RenderRuntime( + m_types, + TestDeviceProxy.Create(out TestDeviceProxy proxy), + new TestDiagnosticSink() + ); runtime.SetPrimaryModelOutputEnabled(false); CountingContributor[] contributors = Enumerable.Range(0, contributorCount) .Select(static _ => new CountingContributor()) @@ -208,7 +225,7 @@ public void ContributorRetirementMeasurementsIncludeRegistrationAndTheFollowingE bytesPerCycle = allocatedBytes / (double)cycles, millisecondsPerCycle = elapsedMs / cycles, graphCompileCount = ReadGraphCompileCount(runtime), - runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription + runtime = RuntimeInformation.FrameworkDescription }, new JsonSerializerOptions { WriteIndented = true }) ); } @@ -256,7 +273,7 @@ bool rejectGraph Type type = m_types.current.GetTypesImplementing() .Select(reference => reference.Resolve(m_types)) .Single(type => type.Name == "ReloadableContributor"); - var contributor = (IRenderFrameGraphContributor)Activator.CreateInstance( + IRenderFrameGraphContributor contributor = (IRenderFrameGraphContributor)Activator.CreateInstance( type, new Action(value => Assert.True(runtime.UnregisterContributor(value))), rejectGraph diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs index c70a498aa..dac818ad9 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs @@ -21,10 +21,20 @@ public void ExplicitArtifactScopesDoNotPublishIntoCanonicalMaterialCachesAndRele var previewDiagnostics = new TestDiagnosticSink(); using var runtime = new RenderRuntime(m_types, device, projectDiagnostics, targetArtifacts: provider); RenderShaderArtifact draft = Publication("draft"); - GraphicsPipelineHandle canonical = default, preview = default; + GraphicsPipelineHandle canonical = default; + GraphicsPipelineHandle preview = default; ResourceProbePipeline.action = resources => { - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out var saved)); + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new("test.publication"), + new("draw"), + null, + null, + out RenderMaterialPass? saved + ) + ); Assert.True( resources.TryResolveMaterialArtifact( new("preview/document"), @@ -36,12 +46,13 @@ public void ExplicitArtifactScopesDoNotPublishIntoCanonicalMaterialCachesAndRele null, null, previewDiagnostics, - out var edited + out RenderMaterialPass? edited ) ); Assert.Equal("saved", saved!.definition.name); Assert.Equal("draft", edited!.definition.name); - canonical = saved.graphicsPipeline; preview = edited.graphicsPipeline; + canonical = saved.graphicsPipeline; + preview = edited.graphicsPipeline; Assert.NotEqual(canonical, preview); Assert.True( resources.TryResolveMaterialArtifact( @@ -54,7 +65,7 @@ out var edited null, null, previewDiagnostics, - out var sameFrame + out RenderMaterialPass? sameFrame ) ); Assert.Equal(preview, sameFrame!.graphicsPipeline); @@ -65,7 +76,16 @@ out var sameFrame Assert.DoesNotContain(preview, device.destroyedPrograms); ResourceProbePipeline.action = resources => { - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out var saved)); + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new("test.publication"), + new("draw"), + null, + null, + out RenderMaterialPass? saved + ) + ); Assert.Equal(canonical, saved!.graphicsPipeline); }; RunResourceFrame(runtime); @@ -98,7 +118,7 @@ public void InvalidDraftProgramKeepsOnlyItsOwnLastGoodAndReportsOnlyToItsConsume null, null, preview, - out var pass + out RenderMaterialPass? pass ) ); if (lastGood.isValid) Assert.Equal(lastGood, pass!.graphicsPipeline); @@ -112,7 +132,16 @@ out var pass Assert.Contains(preview.items, issue => issue.code == "RENDER_PROGRAM_CREATE_FAILED"); ResourceProbePipeline.action = resources => { - Assert.True(resources.TryResolveGraphicsMaterial(material, new("test.publication"), new("draw"), null, null, out var saved)); + Assert.True( + resources.TryResolveGraphicsMaterial( + material, + new("test.publication"), + new("draw"), + null, + null, + out RenderMaterialPass? saved + ) + ); Assert.Equal("saved", saved!.definition.name); Assert.NotEqual(lastGood, saved.graphicsPipeline); }; @@ -123,9 +152,9 @@ out var pass [Fact] public void ShaderProgramsFollowPublishedContentNotTheLatestAssetDefinitionOrItsVersion() { - var first = Publication("first"); - var second = Publication("second"); - var shader = PublicationShader("first"); + RenderShaderArtifact first = Publication("first"); + RenderShaderArtifact second = Publication("second"); + ShaderAsset shader = PublicationShader("first"); var material = new MaterialAsset { shader = shader }; var provider = new PublicationProvider(m_serialization) { artifact = first }; var device = new RecordingRenderDevice(); @@ -162,7 +191,7 @@ out pass [Fact] public void AllPreviouslyUsedPassesMustBeCreatedBeforeAnyReplacementIsPublished() { - var shader = PublicationShader("main", "shadow"); + ShaderAsset shader = PublicationShader("main", "shadow"); var material = new MaterialAsset { shader = shader }; var provider = new PublicationProvider(m_serialization) { artifact = Publication("main", "shadow") }; var device = new RecordingRenderDevice(); @@ -204,10 +233,15 @@ out RenderMaterialPass? pass public void ShaderArtifactChangesCannotSplitTheCurrentExtractionFrame() { var material = new MaterialAsset { shader = PublicationShader("first") }; - var first = Publication("first"); - var second = Publication("second"); + RenderShaderArtifact first = Publication("first"); + RenderShaderArtifact second = Publication("second"); var provider = new PublicationProvider(m_serialization) { artifact = first }; - using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), new TestDiagnosticSink(), targetArtifacts: provider); + using var runtime = new RenderRuntime( + m_types, + new RecordingRenderDevice(), + new TestDiagnosticSink(), + targetArtifacts: provider + ); ResourceProbePipeline.action = resources => { Assert.True( diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs index d2b650d4d..b4de71720 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/RenderingBackendRegistrationTests.cs @@ -56,7 +56,7 @@ public override IRenderLayerCompositionProgramProvider CreateCompositionProgramP private sealed class AuthoringProvider(RenderingBackendId id) : RenderingAuthoringBackendProvider(id) { public override IShaderCompilerToolchain CreateShaderCompilerToolchain() - => new BgfxShadercToolchain(Inno.Integration.WindowsX64.Bgfx.WindowsX64BgfxShaderProfiles.target); + => new BgfxShadercToolchain(WindowsX64BgfxShaderProfiles.target); public override ITextureTargetCompiler CreateTextureTargetCompiler() => new BgfxTextureTargetCompiler(); } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs index ff0372d84..586ebda7b 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderControlFlowIrTests.cs @@ -25,11 +25,9 @@ public void BranchCapturesOuterValuesButOnlyExposesMergedValues() builder.Constant(true), region => { - retained = region; leaked = region.Binary( - ShaderIrOperation.Add, - input, - input - ); return Values(("result", leaked)); + retained = region; + leaked = region.Binary(ShaderIrOperation.Add, input, input); + return Values(("result", leaked)); }, region => Values(("result", region.Constant(3f))) ); @@ -229,7 +227,7 @@ private static Dictionary Values(params (string name, Sha private static async Task Compile(ShaderIrStage stage) { - var toolchain = new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target); + var toolchain = new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target); var capabilities = new GraphicsCapabilities( GraphicsApi.Metal, GraphicsCapability.Compute | GraphicsCapability.StorageBuffer, diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs index 44122f73d..b3f2e1408 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphInputDefaultTests.cs @@ -41,9 +41,10 @@ public void RequiredInputsRejectStoredDefaultsAndAcceptExplicitGraphConstants() graph.AddNode(node); graph.AddNode(left); graph.AddNode(right); - Set(node, "type", "float"); Set(node, "operation", "multiply"); + Set(node, "type", "float"); + Set(node, "operation", "multiply"); ShaderGraphLiteral value = ShaderGraphLiteral.Zero(ShaderSourceType.Atomic("float")); - value.scalarBits = [0x3f800000]; + value.scalarBits = [0x3F80_0000]; Set(node, ShaderGraphDocument.inputDefaultPrefix + "left", value); Set(node, ShaderGraphDocument.inputDefaultPrefix + "right", value); GraphDocument restored = GraphDocumentCodec.Decode(GraphDocumentCodec.Encode(graph, m_serialization), m_serialization); @@ -66,7 +67,8 @@ public void ConnectedInputsIgnoreButRetainObsoleteStoredDefaults() var graph = new GraphDocument(); var node = new GraphNodeRecord(new("multiply"), "inno.shader.binary"); var constant = new GraphNodeRecord(new("source"), "inno.shader.constant"); - graph.AddNode(node); graph.AddNode(constant); + graph.AddNode(node); + graph.AddNode(constant); Set(node, "type", "float"); Set(node, ShaderGraphDocument.inputDefaultPrefix + "left", ShaderGraphLiteral.Zero(ShaderSourceType.Atomic("uint"))); Set(node, ShaderGraphDocument.inputDefaultPrefix + "right", ShaderGraphLiteral.Zero(ShaderSourceType.Atomic("float"))); diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs index c674d66a4..7f4c3cb60 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.cs @@ -64,7 +64,7 @@ out GraphNodeRecord color Assert.Contains(lowered.block.instructions, instruction => instruction.operation == ShaderIrOperation.Multiply); Assert.Equal(BitConverter.SingleToUInt32Bits(0.25f), lowered.block.instructions[0].constantBits); var stage = new ShaderIrStage(ShaderStage.Fragment, lowered.block, [], [new("color", ShaderIrOutputKind.Color)]); - var compiler = new ShaderCompiler(new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target)); + var compiler = new ShaderCompiler(new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target)); var caps = new GraphicsCapabilities( GraphicsApi.Metal, GraphicsCapability.None, diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs index 51abe5b1a..6d8aadeee 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.cs @@ -147,7 +147,7 @@ public void PartiallyTypedInputRemainsSerializableInsteadOfDiscardingItsNodeOrEd m_serialization, SerializationContext.empty ); - input.id = ""; + input.id = string.Empty; GraphDocument changed = ShaderGraphBindings.ChangeInput(graph, new("color"), input, m_serialization, SerializationContext.empty); Assert.Equal(graph.nodes.Count, changed.nodes.Count); Assert.Equal(graph.edges.Count, changed.edges.Count); @@ -183,7 +183,12 @@ public void RemovingOneSharedBindingPreservesItsDefaultAndRemainingStageVisibili var node = new GraphNodeRecord(new("vertex-color"), "inno.shader.stage-input"); node.SetValue("stage", ShaderGraphDocument.Encode("vertex", m_serialization, SerializationContext.empty)); graph.AddNode(node); - var settings = new ShaderGraphInputSettings { id = "color", kind = ShaderIrInputKind.Uniform, type = new() { id = "float4" } }; + var settings = new ShaderGraphInputSettings + { + id = "color", + kind = ShaderIrInputKind.Uniform, + type = new() { id = "float4" } + }; graph = ShaderGraphBindings.ChangeInput(graph, node.id, settings, m_serialization, SerializationContext.empty); ShaderPropertyDefinition original = Assert.Single( ShaderGraphDocument.ReadDefinition(graph, m_serialization, SerializationContext.empty).properties @@ -210,7 +215,10 @@ public void RemovingNodesFromAnIncompleteDocumentDoesNotRequireSuccessfulCompila public void Dispose() { - m_nodes.Dispose(); m_serialization.Dispose(); m_types.Dispose(); m_modules.Dispose(); + m_nodes.Dispose(); + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); if (Directory.Exists(m_root)) Directory.Delete(m_root, true); } } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs index d6750f362..d36b14ed3 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Runtime.Versioning; using System.Threading.Tasks; @@ -33,7 +34,7 @@ public async Task StorageGraphCompilesThroughTheSameMetalToolchainAsSourceNodes( { ShaderGraphProgramResult lowered = Lower(StorageGraph()); Assert.True(lowered.succeeded, string.Join("\n", lowered.diagnostics.Select(value => value.message))); - var compiler = new ShaderCompiler(new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target)); + var compiler = new ShaderCompiler(new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target)); RenderTextureFormat[] formats = Enum.GetValues(); var caps = new GraphicsCapabilities( GraphicsApi.Metal, @@ -70,7 +71,7 @@ public void RerouteRetainsAggregateAndStoragePortContracts() "valueType", ShaderGraphDocument.Encode(ShaderGraphType.Capture(type), m_serialization, SerializationContext.empty) ); - var ports = m_nodes.DescribePorts(node, m_serialization, SerializationContext.empty); + IReadOnlyList ports = m_nodes.DescribePorts(node, m_serialization, SerializationContext.empty); Assert.Equal(2, ports.Count); Assert.All(ports, port => Assert.True(type.IsEquivalentTo(port.type))); } @@ -92,31 +93,32 @@ private GraphDocument StorageGraph() storageElement = new() { id = "uint" } }; GraphNodeRecord resource = Node("resource", "inno.shader.stage-input"); - var settings = new ShaderGraphInputSettings { id = "buffer", kind = ShaderIrInputKind.Storage, type = resourceType }; + var settings = new ShaderGraphInputSettings + { + id = "buffer", + kind = ShaderIrInputKind.Storage, + type = resourceType + }; Set(resource, "settings", settings); - GraphNodeRecord coordinate = Node( - "coordinate", - "inno.shader.constant" - ); Set(coordinate, "type", "uint"); Set(coordinate, "value", 0u); - GraphNodeRecord value = Node("constant", "inno.shader.constant"); Set(value, "type", "uint"); Set(value, "value", 7u); - GraphNodeRecord store = Node( - "z-store", - "inno.shader.storage-store" - ), load = Node("m-load", "inno.shader.storage-load"), atomic = Node( - "a-atomic", - "inno.shader.storage-atomic-add" - ); + GraphNodeRecord coordinate = Node("coordinate", "inno.shader.constant"); + Set(coordinate, "type", "uint"); + Set(coordinate, "value", 0u); + GraphNodeRecord value = Node("constant", "inno.shader.constant"); + Set(value, "type", "uint"); + Set(value, "value", 7u); + GraphNodeRecord store = Node("z-store", "inno.shader.storage-store"); + GraphNodeRecord load = Node("m-load", "inno.shader.storage-load"); + GraphNodeRecord atomic = Node("a-atomic", "inno.shader.storage-atomic-add"); foreach (GraphNodeRecord effect in new[] { store, load, atomic }) { - Set(effect, "resource", resourceType); Connect(resource, "value", effect, "resource"); Connect( - coordinate, - "value", - effect, - "coordinate" - ); + Set(effect, "resource", resourceType); + Connect(resource, "value", effect, "resource"); + Connect(coordinate, "value", effect, "coordinate"); } - Connect(value, "value", store, "value"); Connect(value, "value", atomic, "value"); - Connect(store, "then", load, "after"); Connect(load, "then", atomic, "after"); + Connect(value, "value", store, "value"); + Connect(value, "value", atomic, "value"); + Connect(store, "then", load, "after"); + Connect(load, "then", atomic, "after"); graph = ShaderGraphPrograms.Bind(graph, "Main", [stage.id], m_serialization, SerializationContext.empty); return ShaderGraphBindings.ChangeInput(graph, resource.id, settings, m_serialization, SerializationContext.empty); @@ -126,7 +128,8 @@ string type ) { var node = new GraphNodeRecord(new(id), type); if (id != "compute") Set(node, "stage", "compute"); - graph.AddNode(node); return node; + graph.AddNode(node); + return node; } void Set( GraphNodeRecord node, diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs index 280bdc4b4..526293125 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrBuilderTests.cs @@ -25,7 +25,7 @@ public void NumericGraphLowersToTypedOrderedValuesInsteadOfSourceFragments() ShaderIrOperation.Minimum ], block.instructions.Select(static value => value.operation)); Assert.Equal("float", block.outputs["color"].type.id); - Assert.Equal(0x40000000UL, block.instructions[1].constantBits); + Assert.Equal(0x4000_0000UL, block.instructions[1].constantBits); Assert.Same(input, builder.Input("brightness", ShaderSourceType.Atomic("float"))); Assert.Throws(() => builder.Input("brightness", ShaderSourceType.Atomic("int"))); } @@ -39,7 +39,7 @@ public void ScalarConstantsKeepSignedZeroAndFullIntegerPrecision() _ = builder.Constant(int.MinValue); _ = builder.Constant(true); ShaderIrBlock block = builder.Build(new Dictionary()); - Assert.Equal([0x80000000UL, 0xffffffffUL, 0x80000000UL, 1UL], block.instructions.Select(static value => value.constantBits)); + Assert.Equal([0x8000_0000UL, 0xFFFF_FFFFUL, 0x8000_0000UL, 1UL], block.instructions.Select(static value => value.constantBits)); Assert.Throws(() => builder.Constant(float.NaN)); Assert.Throws(() => builder.Constant(float.PositiveInfinity)); } diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs index 92fccdffd..5f1da7efb 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderIrStageTests.cs @@ -47,8 +47,8 @@ public void VertexStageRequiresClipPositionAndExactBodyInterface() var builder = new ShaderIrBuilder(); ShaderIrValue position = builder.Input("position", ShaderSourceType.Atomic("float4")); ShaderIrBlock body = builder.Build(new Dictionary { ["clip"] = position }); - ShaderIrStageInput input = new("position", position.type, ShaderIrInputKind.VertexAttribute, "position"); - ShaderIrStageOutput output = new("clip", ShaderIrOutputKind.ClipPosition); + var input = new ShaderIrStageInput("position", position.type, ShaderIrInputKind.VertexAttribute, "position"); + var output = new ShaderIrStageOutput("clip", ShaderIrOutputKind.ClipPosition); var stage = new ShaderIrStage(ShaderStage.Vertex, body, [input], [output]); Assert.Same(body, stage.body); Assert.Throws(() => new ShaderIrStage(ShaderStage.Vertex, body, [], [output])); diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs index 5cd061f86..e23e7c8e4 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderResourceIrTests.cs @@ -147,7 +147,7 @@ public async Task TypedStorageBuffersCompileRealLoadsStoresAndAtomics() ShaderIrValue value = builder.LoadStorage(source, index); ShaderIrValue previous = builder.AtomicAddStorage(target, index, value); builder.StoreStorage(target, builder.Constant(1u), previous); - ShaderIrStage stage = new( + var stage = new ShaderIrStage( ShaderStage.Compute, builder.Build(new Dictionary()), [new("source", source.type, ShaderIrInputKind.Storage), new("target", target.type, ShaderIrInputKind.Storage, location: 1)], @@ -182,7 +182,7 @@ public async Task TypedStorageImagesCompileForTwoDimensionalArraysAndVolumes() : builder.Construct(ShaderSourceType.Atomic("int2"), zero, zero); ShaderIrValue loaded = builder.LoadStorage(image, coordinate); builder.StoreStorage(image, coordinate, builder.Binary(ShaderIrOperation.Add, loaded, loaded)); - ShaderIrStage stage = new( + var stage = new ShaderIrStage( ShaderStage.Compute, builder.Build(new Dictionary()), [new("image", type, ShaderIrInputKind.Storage)], @@ -238,7 +238,7 @@ private static async Task Compile( | GraphicsCapability.Texture2DArray | GraphicsCapability.Texture3D ) { - var toolchain = new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target); + var toolchain = new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target); var capabilities = new GraphicsCapabilities( GraphicsApi.Metal, features, diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs index 898804da5..6449c02ad 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs @@ -69,10 +69,10 @@ internal Fixture() RegistryFrontendProbe.created = 0; RegistryFrontendProbe.disposed = 0; RegistryFrontendProbe.conflict = false; - modules = new ModuleHost( + this.modules = new ModuleHost( new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(ShaderSourceFrontendRegistryTests).Assembly)} ); - types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); + this.types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); } public void Dispose() diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs index ef5f97a93..7657726ef 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceModuleTests.cs @@ -135,7 +135,7 @@ public void SuccessfulFrontendsCannotClaimDependenciesOutsideTheirFrozenSourceSe public void DuplicateOrEmptyImplementationSetsAreRejectedBeforeProvidersRun() { var catalog = new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]); - var request = Request("same", "float Shade(float value) { return value; }"); + ShaderSourceImplementationRequest request = Request("same", "float Shade(float value) { return value; }"); Assert.Throws(() => catalog.AnalyzeModule([])); Assert.Throws(() => catalog.AnalyzeModule([request, request])); } @@ -143,7 +143,7 @@ public void DuplicateOrEmptyImplementationSetsAreRejectedBeforeProvidersRun() [Fact] public void IncludeReadsCannotMixDifferentContentsForTheSameSourcePath() { - var request = Request( + ShaderSourceImplementationRequest request = Request( "first", "#include \"data.inc\"\n#include \"data.inc\"\nfloat Shade(float value) { return value; }", new ChangingIncludes() @@ -157,7 +157,11 @@ public void IncludeReadsCannotMixDifferentContentsForTheSameSourcePath() public void SourceErrorsCannotSwallowTheSharedRetirementBarrier() { var failure = new IOException("Source candidate is retiring.", new RetirementPendingException("Pending source owner.")); - var request = Request("first", "#include \"data.inc\"\nfloat Shade(float value) { return value; }", new FailingIncludes(failure)); + ShaderSourceImplementationRequest request = Request( + "first", + "#include \"data.inc\"\nfloat Shade(float value) { return value; }", + new FailingIncludes(failure) + ); IOException actual = Assert.Throws( () => new ShaderSourceFrontendCatalog([new BgfxShaderSourceFrontend()]).AnalyzeModule([request]) ); diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs index a50c1dea7..aa1fbe498 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs @@ -21,7 +21,7 @@ public MetalShaderFactAttribute() { if (!OperatingSystem.IsMacOS()) { - Skip = "Requires the macOS BGFX Metal compiler; Windows validation is explicitly deferred."; + this.Skip = "Requires the macOS BGFX Metal compiler; Windows validation is explicitly deferred."; } } } @@ -36,7 +36,7 @@ public async Task EveryRectangularMatrixShapeSupportsColumnConstructionAndExtrac { for (int rows = 2; rows <= 4; rows++) { - var builder = new ShaderIrBuilder(); + var builder = new ShaderIrBuilder(); ShaderIrValue matrix = builder.Construct( ShaderSourceType.Atomic($"float{columns}x{rows}"), Enumerable.Range(1, columns * rows).Select(value => builder.Constant((float)value)).ToArray() @@ -201,7 +201,7 @@ public async Task ComputeEntryAndWorkgroupAreGeneratedNotSuppliedByTheSourceModu ShaderIrValue id = builder.Input("invocation", ShaderSourceType.Atomic("uint3")); ShaderSourceModuleAnalysis module = Module("Compute.ishadersource", "void Shade(uvec3 gid) { if (gid.x > 0u) return; }"); _ = builder.Call(module, "metal", new Dictionary { ["gid"] = id }); - ShaderIrStage stage = new( + var stage = new ShaderIrStage( ShaderStage.Compute, builder.Build(new Dictionary()), [new("invocation", id.type, ShaderIrInputKind.Builtin, "global-invocation-id")], @@ -270,8 +270,8 @@ public async Task CancellationIsPreservedBeforeStartingNativeCompilation() { var builder = new ShaderIrBuilder(); ShaderIrStage stage = Fragment(builder, Color(builder, 1f)); - var toolchain = new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target); - var target = toolchain.CreateTarget(Capabilities(GraphicsCapability.None)); + var toolchain = new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target); + ShaderCompileTarget target = toolchain.CreateTarget(Capabilities(GraphicsCapability.None)); await Assert.ThrowsAnyAsync(async () => await toolchain.CompileAsync(new ShaderStageToolRequest(stage, target), new CancellationToken(true))); } @@ -314,7 +314,7 @@ private static async Task Compile( | GraphicsCapability.Texture2DArray | GraphicsCapability.Texture3D ) { - var compiler = new ShaderCompiler(new BgfxShadercToolchain(Inno.Integration.MacOSArm64.Bgfx.MacOSArm64BgfxShaderProfiles.target)); + var compiler = new ShaderCompiler(new BgfxShadercToolchain(MacOSArm64BgfxShaderProfiles.target)); return await compiler.CompileAsync(stage, compiler.CreateTarget(Capabilities(capabilities))); } diff --git a/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs b/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs index fc01e4b92..ff252ce5a 100644 --- a/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/GraphicsProgramArtifactTests.cs @@ -83,7 +83,7 @@ public void TruncationOversizedFieldsBadHeadersAndTrailingBytesFailBeforePublica byte[] header = (byte[])bytes.Clone(); header[0] = 0; Assert.Throws(() => GraphicsProgramArtifactCodec.Decode(header)); - byte[] trailing = new byte[bytes.Length + 1]; + var trailing = new byte[bytes.Length + 1]; bytes.CopyTo(trailing, 0); Assert.Throws(() => GraphicsProgramArtifactCodec.Decode(trailing)); } diff --git a/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs b/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs index 67f48009d..473f564c5 100644 --- a/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/ParallelCommandRecordingTests.cs @@ -119,7 +119,7 @@ private static RenderGraphBuilder CreateGraph() new GraphicsCapabilities( GraphicsApi.Noop, GraphicsCapability.Compute | GraphicsCapability.StorageBuffer | GraphicsCapability.StorageTexture, - new GraphicsLimits(16, 8, 16384, 16), + new GraphicsLimits(16, 8, 16_384, 16), [RenderTextureFormat.RGBA8], [RenderTextureFormat.RGBA8], [RenderTextureFormat.RGBA8], @@ -136,17 +136,17 @@ RenderCommandEncoder commands var binding = new RenderBindingId("weights.\u03b1"); for (int index = 0; index < 64; index++) { - byte[] uniform = new byte[4097]; + var uniform = new byte[4097]; for (int offset = 0; offset < uniform.Length; offset++) { uniform[offset] = unchecked((byte)(offset + index)); } - float[] transform = new float[16]; + var transform = new float[16]; for (int element = 0; element < transform.Length; element++) { transform[element] = index + element * 0.25f; } - var sampler = RenderSamplerState.linearClamp; + RenderSamplerState sampler = RenderSamplerState.linearClamp; var sourceRegion = new RenderTextureRegion(0, 1, 2, 0, 3, 4); var destinationRegion = new RenderTextureRegion(0, 5, 6, 0, 3, 4); commands.BindGraphicsPipeline(DeviceHandles.graphics); @@ -224,12 +224,12 @@ private sealed class ReferenceInputs(string phase) private sealed class DeviceHandles : RenderDevice { - internal static GraphicsPipelineHandle graphics => CreateGraphicsPipelineHandle(0x123456789, 7); - internal static ComputePipelineHandle compute => CreateComputePipelineHandle(0x987654321, 7); - internal static PersistentTextureHandle texture => CreatePersistentTextureHandle(0x123456781, 7); - internal static PersistentTextureHandle otherTexture => CreatePersistentTextureHandle(0x123456782, 7); - internal static PersistentBufferHandle buffer => CreatePersistentBufferHandle(0x123456783, 7); - internal static PersistentBufferHandle otherBuffer => CreatePersistentBufferHandle(0x123456784, 7); + internal static GraphicsPipelineHandle graphics => CreateGraphicsPipelineHandle(0x1_2345_6789, 7); + internal static ComputePipelineHandle compute => CreateComputePipelineHandle(0x9_8765_4321, 7); + internal static PersistentTextureHandle texture => CreatePersistentTextureHandle(0x1_2345_6781, 7); + internal static PersistentTextureHandle otherTexture => CreatePersistentTextureHandle(0x1_2345_6782, 7); + internal static PersistentBufferHandle buffer => CreatePersistentBufferHandle(0x1_2345_6783, 7); + internal static PersistentBufferHandle otherBuffer => CreatePersistentBufferHandle(0x1_2345_6784, 7); } private sealed class ProbeBackend : IRenderGraphBackend @@ -243,7 +243,7 @@ internal ProbeBackend( bool capture = true ) { m_phase = phase; - encoder = new ProbeEncoder(phase, capture); + this.encoder = new ProbeEncoder(phase, capture); } public void BeginGraph(CompiledRenderGraph graph) {} diff --git a/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs b/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs index d9bcbddb0..6e80a5713 100644 --- a/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/PipelineResourceTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using Xunit; using Inno.Rendering; @@ -10,8 +11,14 @@ public sealed class PipelineResourceTests [Fact] public void PipelineBindingSnapshotsRejectMutationOfPublishedStorage() { - var binding = new RenderShaderBindingDescriptor(new RenderBindingId("original"), RenderShaderBindingKind.Uniform); - var changed = new RenderShaderBindingDescriptor(new RenderBindingId("changed"), RenderShaderBindingKind.Uniform); + var binding = new RenderShaderBindingDescriptor( + new RenderBindingId("original"), + RenderShaderBindingKind.Uniform + ); + var changed = new RenderShaderBindingDescriptor( + new RenderBindingId("changed"), + RenderShaderBindingKind.Uniform + ); RenderShaderBindingDescriptor[] input = [binding]; var graphics = new GraphicsPipelineDescriptor([1], [2], input, null); var compute = new ComputePipelineDescriptor([1], input); @@ -19,10 +26,10 @@ public void PipelineBindingSnapshotsRejectMutationOfPublishedStorage() Assert.Same(binding, graphics.bindings[0]); Assert.Same(binding, compute.bindings[0]); Assert.Throws( - () => ((System.Collections.Generic.IList)graphics.bindings)[0] = changed + () => ((IList)graphics.bindings)[0] = changed ); Assert.Throws( - () => ((System.Collections.Generic.IList)compute.bindings)[0] = changed + () => ((IList)compute.bindings)[0] = changed ); } @@ -37,20 +44,16 @@ public void VertexLayoutAcceptsAllPortableSemanticChannels() Assert.Equal(semantics.Length, layout.attributes.Count); Assert.Equal(semantics.Length * 16, layout.stride); - Assert.Throws(() => - ((System.Collections.Generic.IList)layout.attributes)[0] = default); + Assert.Throws(() => ((IList)layout.attributes)[0] = default); } [Fact] - public void VertexLayout_RejectsDuplicateSemantic() - { - Assert.Throws(() => new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3), - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2) - ] - )); - } + public void VertexLayout_RejectsDuplicateSemantic() => Assert.Throws(() => new RenderVertexLayout( + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3), + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float2) + ] + )); [Fact] public void VertexLayout_PreservesExplicitOffsetsAndTrailingPadding() @@ -102,8 +105,8 @@ public void VertexLayout_RejectsOverlappingAttributesAndShortStride() [Fact] public void PersistentVertexBuffer_RequiresMatchingLayout() { - RenderBufferDescriptor buffer = new(3, 12, RenderBufferUsage.Vertex); - RenderVertexLayout mismatched = new( + var buffer = new RenderBufferDescriptor(3, 12, RenderBufferUsage.Vertex); + var mismatched = new RenderVertexLayout( [ new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float4) ] @@ -184,14 +187,14 @@ public void BlendStateSupportsSeparateColorAlphaEquationsAndConstantFactors() alphaSource = RenderBlendFactor.One, alphaDestination = RenderBlendFactor.DestinationAlpha, alphaEquation = RenderBlendEquation.Maximum, - constantRgba = 0x80402010, + constantRgba = 0x8040_2010, alphaToCoverage = true }; var raster = new RenderRasterState { blend = blend }; Assert.Equal(RenderBlendFactor.Constant, raster.blend.colorSource); Assert.Equal(RenderBlendEquation.Maximum, raster.blend.alphaEquation); - Assert.Equal(0x80402010u, raster.blend.constantRgba); + Assert.Equal(0x8040_2010u, raster.blend.constantRgba); Assert.True(raster.blend.alphaToCoverage); } @@ -204,7 +207,7 @@ public void FixedFunctionStateConstructorsPreserveCompleteImmutableConfiguration RenderStencilOperation.IncrementWrap, RenderStencilOperation.Replace ); - var stencil = new RenderStencilState(true, 7, 0x7f, 0x3f, face, face); + var stencil = new RenderStencilState(true, 7, 0x7F, 0x3F, face, face); var raster = new RenderRasterState( RenderCullMode.Front, RenderFrontFace.Clockwise, @@ -218,8 +221,8 @@ public void FixedFunctionStateConstructorsPreserveCompleteImmutableConfiguration Assert.True(stencil.enabled); Assert.Equal((byte)7, stencil.reference); - Assert.Equal((byte)0x7f, stencil.readMask); - Assert.Equal((byte)0x3f, stencil.writeMask); + Assert.Equal((byte)0x7F, stencil.readMask); + Assert.Equal((byte)0x3F, stencil.writeMask); Assert.Equal(RenderStencilCompare.NotEqual, stencil.front.compare); Assert.Equal(RenderStencilOperation.Replace, stencil.back.pass); Assert.Equal(RenderCullMode.Front, raster.cull); @@ -233,13 +236,10 @@ public void FixedFunctionStateConstructorsPreserveCompleteImmutableConfiguration } [Fact] - public void ShaderBinding_RejectsDefaultIdentifier() - { - Assert.Throws(() => new RenderShaderBindingDescriptor( - default, - RenderShaderBindingKind.Uniform - )); - } + public void ShaderBinding_RejectsDefaultIdentifier() => Assert.Throws(() => new RenderShaderBindingDescriptor( + default, + RenderShaderBindingKind.Uniform + )); [Fact] public void ShaderBinding_ModelsStorageTextureAccessWithoutBackendTypes() diff --git a/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs b/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs index 0128af2b4..989802c3c 100644 --- a/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/RenderGraphCompilerTests.cs @@ -231,7 +231,7 @@ public void Compile_ReusesCompatibleNonOverlappingTextures() [Fact] public void Compile_WhenViewLimitExceeded_FailsClearly() { - RenderGraphBuilder graph = new(1, CreateCapabilities(maxViews: 1)); + var graph = new RenderGraphBuilder(1, CreateCapabilities(maxViews: 1)); graph.AddRasterPass("A", C_GEOMETRY, 0, static ( _, _ @@ -250,8 +250,8 @@ public void Compile_WhenViewLimitExceeded_FailsClearly() [Fact] public void Compile_WithPhaseCycle_FailsClearly() { - RenderPhaseId left = new("tests.left"); - RenderPhaseId right = new("tests.right"); + var left = new RenderPhaseId("tests.left"); + var right = new RenderPhaseId("tests.right"); RenderGraphBuilder graph = CreateGraph(); RenderPassBuilder leftPass = graph.AddRasterPass("Left", left, 0, static ( _, @@ -369,7 +369,7 @@ public void Compile_WhenBufferCopyCapabilityIsMissing_FailsClearly() [Fact] public void Compile_WhenSampledFormatIsMissing_FailsClearly() { - RenderGraphBuilder graph = new( + var graph = new RenderGraphBuilder( 1, CreateCapabilities(maxViews: 64, sampledFormats: [RenderTextureFormat.RGBA8]) ); @@ -387,7 +387,7 @@ public void Compile_WhenSampledFormatIsMissing_FailsClearly() [Fact] public void Compile_WhenTextureArrayCapabilityIsMissing_FailsClearly() { - RenderGraphBuilder graph = new( + var graph = new RenderGraphBuilder( 1, CreateCapabilities( maxViews: 64, @@ -411,7 +411,7 @@ public void Compile_WhenTextureArrayCapabilityIsMissing_FailsClearly() [Fact] public void Compile_WhenUnsigned32BitIndexCapabilityIsMissing_FailsClearly() { - RenderGraphBuilder graph = new( + var graph = new RenderGraphBuilder( 1, CreateCapabilities( maxViews: 64, @@ -434,7 +434,7 @@ public void Compile_WhenUnsigned32BitIndexCapabilityIsMissing_FailsClearly() [Fact] public void Compile_WhenVolumeTextureCapabilityIsMissing_FailsClearly() { - RenderGraphBuilder graph = new(1, CreateCapabilities(maxViews: 64)); + var graph = new RenderGraphBuilder(1, CreateCapabilities(maxViews: 64)); _ = graph.CreateTexture( "Unsupported Volume", new RenderTextureDescriptor( @@ -456,7 +456,7 @@ public void Compile_WhenVolumeTextureCapabilityIsMissing_FailsClearly() [Fact] public void Compile_WithSupportedVolumeAndCubemapTextures_Succeeds() { - RenderGraphBuilder graph = new( + var graph = new RenderGraphBuilder( 1, CreateCapabilities( maxViews: 64, @@ -494,7 +494,7 @@ public void Compile_WithSupportedVolumeAndCubemapTextures_Succeeds() [Fact] public void Compile_WhenMultisampleFormatCapabilityIsMissing_FailsClearly() { - RenderGraphBuilder graph = new(1, CreateCapabilities(maxViews: 64)); + var graph = new RenderGraphBuilder(1, CreateCapabilities(maxViews: 64)); RenderTextureHandle target = graph.CreateTexture( "Unsupported MSAA", new RenderTextureDescriptor( @@ -522,7 +522,7 @@ public void Compile_WhenMultisampleFormatCapabilityIsMissing_FailsClearly() [Fact] public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() { - RenderGraphBuilder readGraph = new( + var readGraph = new RenderGraphBuilder( 1, CreateCapabilities(maxViews: 64, storageReadFormats: [RenderTextureFormat.RGBA8], storageWriteFormats: []) ); @@ -553,7 +553,7 @@ public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() Assert.True(readResult.succeeded); - RenderGraphBuilder writeGraph = new( + var writeGraph = new RenderGraphBuilder( 2, CreateCapabilities(maxViews: 64, storageReadFormats: [], storageWriteFormats: [RenderTextureFormat.RGBA8]) ); @@ -573,7 +573,7 @@ public void Compile_StorageTextureAccessHonorsReadAndWriteFormatCapabilities() Assert.True(writeResult.succeeded); - RenderGraphBuilder readWriteGraph = new( + var readWriteGraph = new RenderGraphBuilder( 3, CreateCapabilities(maxViews: 64, storageReadFormats: [], storageWriteFormats: [RenderTextureFormat.RGBA8]) ); @@ -614,7 +614,7 @@ public void Execute_WhenPassFails_StillEndsPassAndGraph() ) .HasSideEffect(); CompiledRenderGraph compiled = graph.Compile().graph!; - RecordingBackend backend = new(); + var backend = new RecordingBackend(); Assert.Throws(() => compiled.Execute(backend, 12)); @@ -659,7 +659,7 @@ RenderPassContext context graph.AddRasterPass("Serial", C_FINAL, 3, Record) .HasSideEffect(); CompiledRenderGraph compiled = graph.Compile().graph!; - RecordingBackend backend = new(); + var backend = new RecordingBackend(); compiled.Execute(backend, 42); @@ -702,7 +702,7 @@ private static GraphicsCapabilities CreateCapabilities( | GraphicsCapability.TextureBlit | GraphicsCapability.Texture2DArray | GraphicsCapability.Index32), - new GraphicsLimits(maxViews, 8, 16384, 16), + new GraphicsLimits(maxViews, 8, 16_384, 16), sampledFormats ?? Enum.GetValues(), Enum.GetValues(), storageReadFormats diff --git a/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs b/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs index 5ad9b2bf4..e6c4742e4 100644 --- a/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/RenderGraphMutationTests.cs @@ -10,7 +10,7 @@ public sealed class RenderGraphMutationTests [Fact] public void LaterScopeCannotChangeAnyPreviouslyAcceptedPassDeclaration() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RasterPassBuilder accepted = graph.AddRasterPass("Accepted", new("first"), 0, Execute); accepted.HasSideEffect(); using (RenderGraphMutationScope mutation = graph.BeginMutationScope()) @@ -27,7 +27,7 @@ public void LaterScopeCannotChangeAnyPreviouslyAcceptedPassDeclaration() [Fact] public void InvalidCommitRollsBackOutputsResourcesPhasesAndValidation() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); graph.AddRasterPass("Accepted", new("first"), 0, Execute).HasSideEffect(); RenderGraphValidationResult baseline = graph.Validate(); using (RenderGraphMutationScope mutation = graph.BeginMutationScope()) @@ -50,7 +50,7 @@ public void InvalidCommitRollsBackOutputsResourcesPhasesAndValidation() [Fact] public void RolledBackHandlesAndPassBuildersCannotAliasNewDeclarations() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle retired; RenderBufferHandle retiredBuffer; RasterPassBuilder retiredPass; @@ -75,7 +75,7 @@ public void RolledBackHandlesAndPassBuildersCannotAliasNewDeclarations() [Fact] public void NestedCommitRemainsOwnedByOuterRollbackAndScopesEnforceNesting() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RenderGraphMutationScope outer = graph.BeginMutationScope(); RenderGraphMutationScope inner = graph.BeginMutationScope(); graph.AddRasterPass("Nested", new("nested"), 0, Execute).HasSideEffect(); @@ -91,7 +91,7 @@ public void NestedCommitRemainsOwnedByOuterRollbackAndScopesEnforceNesting() [Fact] public void RollbackRemovesNameScopeWithoutLateDisposalRemovingAnotherScope() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RenderGraphNameScope retired; using (graph.BeginMutationScope()) { @@ -108,7 +108,7 @@ public void RollbackRemovesNameScopeWithoutLateDisposalRemovingAnotherScope() [Fact] public void MutationCannotCloseAnEarlierNameScopeOrChangeItsPrefix() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); using RenderGraphNameScope name = graph.BeginNameScope("Accepted"); using (graph.BeginMutationScope()) { @@ -124,7 +124,7 @@ private static RenderGraphBuilder CreateGraph() new GraphicsCapabilities( GraphicsApi.Noop, GraphicsCapability.None, - new GraphicsLimits(64, 8, 16384, 16), + new GraphicsLimits(64, 8, 16_384, 16), Enum.GetValues(), Enum.GetValues(), [], @@ -137,7 +137,7 @@ private static RenderGraphBuilder CreateGraph() [Fact] public void AcceptedFuturePhaseOrderingStillDetectsALaterCycleAndRollsBack() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); graph.AddRasterPass("First", new("first"), 0, Execute).HasSideEffect().Before(new("future")); using (RenderGraphMutationScope accepted = graph.BeginMutationScope()) { @@ -161,7 +161,7 @@ public void IncrementalSharedResourceAnalysisMatchesTheCompleteGraph() { string[] Build(bool incremental) { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RenderTextureHandle texture = graph.CreateTexture("Shared", Descriptor()); for (int index = 0; index < 12; index++) { @@ -180,7 +180,7 @@ string[] Build(bool incremental) [Fact] public void EditingAnUncommittedValidatedPassRebuildsItsAnalysis() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RasterPassBuilder first = graph.AddRasterPass("First", new("first"), 0, Execute); first.HasSideEffect(); graph.AddRasterPass("Last", new("last"), 0, Execute).HasSideEffect(); diff --git a/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs b/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs index 177966bfd..200fdfdbe 100644 --- a/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs +++ b/tests/rendering/Inno.Rendering.Tests/RenderGraphValidationTests.cs @@ -10,7 +10,7 @@ public sealed class RenderGraphValidationTests [Fact] public void ValidationIsFrozenAndReusedUntilAnyPassDeclarationChanges() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); RasterPassBuilder pass = graph.AddRasterPass("Visible", new("visible"), 0, Execute); RenderGraphValidationResult culled = graph.Validate(); Assert.True(culled.isValid); @@ -35,7 +35,7 @@ public void ValidationIsFrozenAndReusedUntilAnyPassDeclarationChanges() [Fact] public void LaterPhaseDeclarationInvalidatesCachedScheduleAndDetectsCycle() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); graph.AddRasterPass("First", new("first"), 0, Execute).HasSideEffect().After(new("second")); Assert.True(graph.Validate().isValid); graph.AddRasterPass("Second", new("second"), 0, Execute).HasSideEffect().After(new("first")); @@ -51,7 +51,7 @@ public void LaterPhaseDeclarationInvalidatesCachedScheduleAndDetectsCycle() [Fact] public void ValidationAndCompilationApplyTheSameViewLimit() { - var graph = CreateGraph(1); + RenderGraphBuilder graph = CreateGraph(1); graph.AddRasterPass("First", new("first"), 0, Execute).HasSideEffect(); graph.AddRasterPass("Second", new("second"), 0, Execute).HasSideEffect(); RenderGraphValidationResult validation = graph.Validate(); @@ -63,7 +63,7 @@ public void ValidationAndCompilationApplyTheSameViewLimit() [Fact] public void ValidationDoesNotInvokeCommandCallbacks() { - var graph = CreateGraph(); + RenderGraphBuilder graph = CreateGraph(); int calls = 0; graph.AddRasterPass("Visible", new("visible"), 0, ( payload, @@ -83,7 +83,7 @@ private static RenderGraphBuilder CreateGraph(int maxViews = 64) new GraphicsCapabilities( GraphicsApi.Noop, GraphicsCapability.None, - new GraphicsLimits(maxViews, 8, 16384, 16), + new GraphicsLimits(maxViews, 8, 16_384, 16), Enum.GetValues(), Enum.GetValues(), [], diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs index 361bca9ae..c92f18858 100644 --- a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableContributor.cs @@ -28,10 +28,10 @@ bool rejectGraph m_rejectGraph = rejectGraph; } - /// + /// public void PrepareFrame(ulong frameIndex) => m_unregister(this); - /// + /// public void AddRenderPasses( RenderGraphBuilder graph, ulong frameIndex @@ -51,7 +51,5 @@ ulong frameIndex private void Encode( int payload, RenderPassContext context - ) { - GC.KeepAlive(this); - } + ) => GC.KeepAlive(this); } diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs index 5097bd4d3..8a7bf91d7 100644 --- a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs @@ -26,8 +26,7 @@ internal sealed class ReloadableRenderPipeline : RenderPipeline /// The active pipeline context that owns the frame graph mutation. /// public override void Build(RenderPipelineContext context) - { - context.graph + => context.graph .AddRasterPass( "Reloadable Plugin Pass", new RenderPhaseId("tests.runtime.reloadable-plugin.visible"), @@ -38,7 +37,6 @@ public override void Build(RenderPipelineContext context) ) => {} ) .HasSideEffect(); - } } [RenderFeatureExtension(extensionId)] @@ -53,8 +51,7 @@ internal sealed class ReloadableRenderFeature : RenderPipelineFeature /// The active feature context that owns the frame graph mutation. /// public override void AddRenderPasses(RenderFeatureContext context) - { - context.graph + => context.graph .AddRasterPass( "Reloadable Plugin Feature Pass", new RenderPhaseId("tests.runtime.reloadable-plugin-feature.visible"), @@ -65,5 +62,4 @@ public override void AddRenderPasses(RenderFeatureContext context) ) => {} ) .HasSideEffect(); - } } diff --git a/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs b/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs index 5417a2abe..6341b5f27 100644 --- a/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs +++ b/tests/runtime/Inno.Runtime.Generators.Tests/RuntimeModuleCatalogGeneratorTests.cs @@ -1,11 +1,13 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; using Xunit; using Inno.Extensibility.Catalogs; using Inno.Runtime; @@ -41,7 +43,7 @@ public override void Write(Inno.Core.Serialization.SerializationWriter writer, B new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new RuntimeModuleCatalogGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(input, out _, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation(input, out _, out ImmutableArray diagnostics); Diagnostic failure = Assert.Single(diagnostics, static diagnostic => diagnostic.Id == "INNORUN002"); Assert.Equal(DiagnosticSeverity.Error, failure.Severity); Assert.Contains("parameterless constructor", failure.GetMessage()); @@ -106,10 +108,10 @@ public sealed class RequiredChild : RequiredBase { } new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new RuntimeModuleCatalogGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out ImmutableArray diagnostics); Assert.Empty(diagnostics.Where(static value => value.Severity == DiagnosticSeverity.Error)); using var stream = new MemoryStream(); - var emitted = output.Emit(stream); + EmitResult emitted = output.Emit(stream); Assert.True(emitted.Success, string.Join(Environment.NewLine, emitted.Diagnostics)); stream.Position = 0; var lifetime = new AssemblyLoadContext("static-catalog-test", isCollectible: true); @@ -118,7 +120,7 @@ public sealed class RequiredChild : RequiredBase { } Assembly assembly = lifetime.LoadFromStream(stream); MethodInfo entry = assembly.GetType("Inno.StaticCatalogFixture.Generated.RuntimeModuleCatalog", throwOnError: true)! .GetMethod("Register", BindingFlags.Public | BindingFlags.Static)!; - var register = entry.CreateDelegate>(); + Action register = entry.CreateDelegate>(); var catalog = new StaticTypeCatalogSource([register]); Type derivedType = assembly.GetType("Fixture.Derived", throwOnError: true)!; TypeCatalogMetadata derived = catalog.GetMetadata(derivedType); diff --git a/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs b/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs index ea69ab618..9d5a7fba8 100644 --- a/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs +++ b/tests/runtime/Inno.Runtime.Generators.Tests/SerializationMetadataGeneratorTests.cs @@ -1,10 +1,12 @@ using System; +using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Core.Serialization; @@ -27,7 +29,7 @@ string expectedDiagnostic string source = "using Inno.Core.Serialization; public class State : ISerializable { " + member + " }"; CSharpCompilation input = CreateCompilation("Inno.InvalidSerializationFixture", source, []); GeneratorDriver driver = CSharpGeneratorDriver.Create(new SerializationMetadataGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(input, out _, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation(input, out _, out ImmutableArray diagnostics); Assert.Contains(diagnostics, diagnostic => diagnostic.Id == expectedDiagnostic && diagnostic.Severity == DiagnosticSeverity.Error); } @@ -59,7 +61,7 @@ public sealed class Child : Parent { private Child() {} } "Inno.SerializationChildFixture.Generated.RuntimeSerializationMetadataCatalog", throwOnError: true )!; - var register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! + Action> register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! .CreateDelegate>>(); var source = new StaticSerializationMetadataSource([register]); Type declaration = assembly.GetType("Fixture.Child", throwOnError: true)!; @@ -170,10 +172,10 @@ public static bool Run(SerializationRegistry serialization) new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable) ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new SerializationMetadataGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation(input, out Compilation output, out ImmutableArray diagnostics); Assert.Empty(diagnostics.Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)); using var stream = new MemoryStream(); - var emitted = output.Emit(stream); + EmitResult emitted = output.Emit(stream); Assert.True(emitted.Success, string.Join(Environment.NewLine, emitted.Diagnostics)); stream.Position = 0; var lifetime = new AssemblyLoadContext("serialization-metadata-fixture", isCollectible: true); @@ -184,7 +186,7 @@ public static bool Run(SerializationRegistry serialization) "Inno.SerializationMetadataFixture.Generated.RuntimeSerializationMetadataCatalog", throwOnError: true )!; - var register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! + Action> register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! .CreateDelegate>>(); var metadata = new StaticSerializationMetadataSource([register]); using var modules = new ModuleHost(new ModuleHostOptions @@ -193,7 +195,7 @@ public static bool Run(SerializationRegistry serialization) }); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var serialization = new SerializationRegistry(types, metadata); - var run = assembly.GetType("Fixture.Scenario", throwOnError: true)! + Func run = assembly.GetType("Fixture.Scenario", throwOnError: true)! .GetMethod("Run")! .CreateDelegate>(); Assert.True(run(serialization)); @@ -236,16 +238,14 @@ internal static bool Execute(SerializationRegistry serialization) public static bool Run(SerializationRegistry serialization) => __RECEIVER__Execute(serialization); } """; - source = source.Replace("__OPEN__", nested ? "private static partial class Owner {" : "") - .Replace("__CLOSE__", nested ? "}" : "") - .Replace("__RECEIVER__", nested ? "Owner." : ""); + source = source.Replace("__OPEN__", nested ? "private static partial class Owner {" : string.Empty) + .Replace("__CLOSE__", nested ? "}" : string.Empty) + .Replace("__RECEIVER__", nested ? "Owner." : string.Empty); AssertScenario(source); } [Fact] - public void PublicDeclarationCanKeepPrivateSerializedMemberTypes() - { - AssertScenario(""" + public void PublicDeclarationCanKeepPrivateSerializedMemberTypes() => AssertScenario(""" using Inno.Core.Serialization; namespace Fixture; public sealed partial class State : ISerializable @@ -267,7 +267,6 @@ public static bool Run(SerializationRegistry serialization) } } """); - } [Fact] public void PrivateDeclarationsRequireAnExplicitPartialOwner() @@ -277,7 +276,7 @@ public void PrivateDeclarationsRequireAnExplicitPartialOwner() public static class Owner { private sealed class State : ISerializable {} } """, []); GeneratorDriver driver = CSharpGeneratorDriver.Create(new SerializationMetadataGenerator().AsSourceGenerator()); - driver.RunGeneratorsAndUpdateCompilation(input, out _, out var diagnostics); + driver.RunGeneratorsAndUpdateCompilation(input, out _, out ImmutableArray diagnostics); Assert.Contains(diagnostics, static diagnostic => ( diagnostic.Id == "INNOSER012" && diagnostic.Severity == DiagnosticSeverity.Error @@ -285,13 +284,10 @@ public static class Owner { private sealed class State : ISerializable {} } } [Fact] - public void OpenGenericContainingOwnersDoNotEmitUnboundShapes() - { - _ = Compile("Inno.OpenSerializationFixture", """ + public void OpenGenericContainingOwnersDoNotEmitUnboundShapes() => _ = Compile("Inno.OpenSerializationFixture", """ using Inno.Core.Serialization; public sealed class Owner { private sealed class State : ISerializable { } } """, []); - } private static void AssertScenario(string source) { @@ -304,7 +300,7 @@ private static void AssertScenario(string source) "Inno.PrivateSerializationFixture.Generated.RuntimeSerializationMetadataCatalog", throwOnError: true )!; - var register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! + Action> register = catalog.GetMethod("Register", BindingFlags.Public | BindingFlags.Static)! .CreateDelegate>>(); var metadata = new StaticSerializationMetadataSource([register]); using var modules = new ModuleHost(new ModuleHostOptions @@ -313,7 +309,7 @@ private static void AssertScenario(string source) }); using var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); using var serialization = new SerializationRegistry(types, metadata); - var run = assembly.GetType("Fixture.Scenario", throwOnError: true)! + Func run = assembly.GetType("Fixture.Scenario", throwOnError: true)! .GetMethod("Run")! .CreateDelegate>(); Assert.True(run(serialization)); @@ -348,11 +344,11 @@ MetadataReference[] additionalReferences driver.RunGeneratorsAndUpdateCompilation( CreateCompilation(assemblyName, source, additionalReferences), out Compilation output, - out var diagnostics + out ImmutableArray diagnostics ); Assert.Empty(diagnostics.Where(static diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)); using var stream = new MemoryStream(); - var emitted = output.Emit(stream); + EmitResult emitted = output.Emit(stream); Assert.True(emitted.Success, string.Join(Environment.NewLine, emitted.Diagnostics)); return stream.ToArray(); } diff --git a/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs b/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs index 66cc5ae0b..2386182bf 100644 --- a/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/AdapterCatalogTests.cs @@ -36,7 +36,12 @@ public void PresentationRegistrationUsesAnImmutableOpenCatalog() Assert.Equal(first.id, Assert.Single(catalog.supportedBackends)); Assert.Equal(0, first.creationCount); // This provider intentionally does not consume host resources; the catalog validates its return contract. - var options = new PresentationBackendOptions { window = null!, platformApplication = null!, renderDevice = null! }; + var options = new PresentationBackendOptions + { + window = null!, + platformApplication = null!, + renderDevice = null! + }; Assert.Throws(() => catalog.CreateContext(second.id, options)); Assert.Throws(() => catalog.CreateContext(first.id, null!)); Assert.Throws(() => catalog.CreateContext(first.id, options)); @@ -140,13 +145,13 @@ private sealed class TestCatalog : IAdapterCatalog public TestCatalog() { - platform = new PlatformBackendCatalog([m_platform]); - input = new InputBackendCatalog([m_input]); - storage = new StorageBackendCatalog([m_storage]); - audio = new AudioBackendCatalog([m_audio]); - text = new TextBackendCatalog([m_text]); - rendering = new RenderingBackendCatalog([m_rendering]); - ui = new UiBackendCatalog([m_ui]); + this.platform = new PlatformBackendCatalog([m_platform]); + this.input = new InputBackendCatalog([m_input]); + this.storage = new StorageBackendCatalog([m_storage]); + this.audio = new AudioBackendCatalog([m_audio]); + this.text = new TextBackendCatalog([m_text]); + this.rendering = new RenderingBackendCatalog([m_rendering]); + this.ui = new UiBackendCatalog([m_ui]); } public AdapterSelection selection diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs b/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs index 68642f713..c00bb8dab 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerContentSourceTests.cs @@ -61,7 +61,7 @@ public async Task PreparedContentIsCheckedAndRetiredBeforeAnyPlatformAdapterStar .Build()) using (SerializationGeneration serialization = metadataOwner.serialization.CaptureGeneration()) { - string hash = new string('A', 64); + var hash = new string('A', 64); metadata = new PlayerContentMetadata( RuntimeManifestEnvelope.Encode(manifest, serialization), serialization.Serialize(new RuntimeContentCatalog @@ -156,7 +156,7 @@ private static PlayerLaunchOptions CreateOptions( IPlayerModuleActivator? activator = null ) => new() { - adapterSelection = new Inno.Adapter.AdapterSelection(), + adapterSelection = new AdapterSelection(), modules = modules, types = new ReflectionTypeCatalogSource(), serializationMetadata = new ReflectionSerializationMetadataSource(), diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs index ea5ae0cfb..154bd0dea 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Adapters.cs @@ -14,6 +14,7 @@ using Inno.Audio; using Inno.Audio.Runtime; using Inno.Core.Events; +using Inno.Core.Mathematics; using Inno.Input; using Inno.Platform; using Inno.Rendering; @@ -32,7 +33,7 @@ private sealed class MemoryAdapters : IAdapterCatalog, IPlatformBackendFactory, public MemoryAdapters(bool failFrame) { - application = new MemoryApplication(retired); + this.application = new MemoryApplication(retired); m_render = new MemoryRenderDevice(retired, failFrame); } @@ -335,7 +336,7 @@ UiTextureData texture public bool HasElementAtPoint( UiContextHandle context, - Inno.Core.Mathematics.Vector2 position + Vector2 position ) => false; public void Update( diff --git a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs index 587fc882a..e83d6d84d 100644 --- a/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs +++ b/tests/runtime/Inno.Runtime.Tests/PlayerWithoutFileSystemTests.Startup.cs @@ -5,8 +5,16 @@ using System.Threading; using System.Threading.Tasks; using Xunit; +using Inno.Adapter; +using Inno.Adapter.Audio; +using Inno.Adapter.Input; using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Platform; +using Inno.Adapter.Rendering; using Inno.Adapter.Serialization.DotNet; +using Inno.Adapter.Storage; +using Inno.Adapter.Text; +using Inno.Adapter.UI; using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Content; @@ -37,18 +45,18 @@ public void CompletePlayerStartsFromOwnedMemoryAndRetiresAfterSuccessfulOrFailin MemoryPlayerSource source = CreateDeployment(root); Assert.False(Directory.Exists(root)); var modules = new DotNetAssemblyCatalogSource(typeof(PlayerWithoutFileSystemTests).Assembly); - var deployment = GameCodeDeployment.FromManifest(source.manifest.modules); + GameCodeDeployment deployment = GameCodeDeployment.FromManifest(source.manifest.modules); var options = new PlayerLaunchOptions { - adapterSelection = new Inno.Adapter.AdapterSelection + adapterSelection = new AdapterSelection { - platform = Inno.Adapter.Platform.PlatformBackendId.sdl3, - input = Inno.Adapter.Input.InputBackendId.events, - rendering = Inno.Adapter.Rendering.RenderingBackendId.bgfx, - storage = Inno.Adapter.Storage.StorageBackendId.fileSystem, - audio = Inno.Adapter.Audio.AudioBackendId.miniAudio, - text = Inno.Adapter.Text.TextBackendId.freeTypeHarfBuzz, - ui = Inno.Adapter.UI.UiBackendId.rmlUi + platform = PlatformBackendId.sdl3, + input = InputBackendId.events, + rendering = RenderingBackendId.bgfx, + storage = StorageBackendId.fileSystem, + audio = AudioBackendId.miniAudio, + text = TextBackendId.freeTypeHarfBuzz, + ui = UiBackendId.rmlUi }, modules = modules, types = new ReflectionTypeCatalogSource(), @@ -125,7 +133,7 @@ private static MemoryPlayerSource CreateDeployment(string root) string exported = Path.Combine(root, "Exported"); assets.ExportRuntimeArtifacts(exported); File.WriteAllBytes(Path.Combine(exported, SettingsFileNames.project), settings.CaptureDocument()); - var content = ContentTestStore.FromDirectory(exported); + ContentTestStore content = ContentTestStore.FromDirectory(exported); var manifest = new GameRuntimeManifest { applicationId = "tests.memory.player", diff --git a/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs b/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs index 4b50eee0a..c4d980f61 100644 --- a/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/RuntimeSubsystemPolicyTests.cs @@ -18,13 +18,15 @@ public sealed class RuntimeSubsystemPolicyTests : IDisposable private readonly EngineHost m_host; public RuntimeSubsystemPolicyTests() - => m_host = new EngineHostBuilder() + { + m_host = new EngineHostBuilder() .UseMetadataSources( new DotNetAssemblyCatalogSource(typeof(RuntimeSubsystemPolicyTests).Assembly), new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource() ) .Build(); + } public void Dispose() { @@ -38,7 +40,7 @@ public void Dispose() [Fact] public void MissingRequiredCapabilityRejectsBeforeFactoryAllocation() { - var factory = Create("test.required", capabilities: [new RuntimeCapabilityId("test.output")]); + Factory factory = Create("test.required", capabilities: [new RuntimeCapabilityId("test.output")]); InvalidOperationException error = Assert.Throws(() => m_host.CreateHostPipeline([factory])); Assert.Contains("test.output", error.Message); Assert.Equal(0, factory.createCount); @@ -49,7 +51,7 @@ public void MissingRequiredCapabilityRejectsBeforeFactoryAllocation() public void SuppliedCapabilitiesAndDescriptorCollectionsAreImmutableSnapshots() { RuntimeCapabilityId[] required = [new("test.output")]; - var factory = Create("test.ready", capabilities: required); + Factory factory = Create("test.ready", capabilities: required); required[0] = new RuntimeCapabilityId("test.changed"); RuntimeCapabilityId[] supplied = [new("test.output")]; RuntimeSubsystemPipeline pipeline = m_host.CreateHostPipeline([factory], supplied); @@ -65,18 +67,18 @@ public void SuppliedCapabilitiesAndDescriptorCollectionsAreImmutableSnapshots() [InlineData(true)] public void OptionalUnavailabilityPropagatesToOptionalConsumers(bool missingCapability) { - var unavailable = Create( + Factory unavailable = Create( "test.optional", RuntimeSubsystemRequirement.Optional, capabilities: missingCapability ? [new RuntimeCapabilityId("test.absent")] : [] ); unavailable.failCreate = !missingCapability; - var consumer = Create( + Factory consumer = Create( "test.consumer", RuntimeSubsystemRequirement.Optional, dependencies: [unavailable.descriptor.id] ); - var available = Create("test.available"); + Factory available = Create("test.available"); RuntimeSubsystemPipeline pipeline = m_host.CreateHostPipeline([consumer, available, unavailable]); Assert.Equal("test.available", Assert.Single(pipeline.descriptors).id.value); Assert.Equal(2, pipeline.startupDiagnostics.Count); @@ -88,9 +90,9 @@ public void OptionalUnavailabilityPropagatesToOptionalConsumers(bool missingCapa [Fact] public void RequiredConsumerCannotRunWithoutFailedOptionalDependency() { - var optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); + Factory optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); optional.failCreate = true; - var required = Create("test.required", dependencies: [optional.descriptor.id]); + Factory required = Create("test.required", dependencies: [optional.descriptor.id]); Assert.Throws(() => m_host.CreateHostPipeline([required, optional])); Assert.Equal(0, required.createCount); Assert.Equal(1, optional.releaseCount); @@ -101,7 +103,7 @@ public void RequiredConsumerCannotRunWithoutFailedOptionalDependency() [InlineData(true)] public void OptionalStartupIsUnavailableOnlyAfterFactoryResourcesRetire(bool failAttach) { - var optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); + Factory optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); optional.failCreate = !failAttach; optional.failAttach = failAttach; RuntimeSubsystemPipeline pipeline = m_host.CreateHostPipeline([optional]); @@ -115,7 +117,7 @@ public void OptionalStartupIsUnavailableOnlyAfterFactoryResourcesRetire(bool fai [Fact] public void OptionalRetirementFailureFaultsInsteadOfDegrading() { - var optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); + Factory optional = Create("test.optional", RuntimeSubsystemRequirement.Optional); optional.failCreate = true; optional.failRelease = true; Assert.Throws(() => m_host.CreateHostPipeline([optional])); @@ -128,14 +130,14 @@ public void OptionalRetirementFailureFaultsInsteadOfDegrading() [Fact] public void OptionalMissingDependencyIsDiagnosedButCyclesStillReject() { - var missing = Create( + Factory missing = Create( "test.missing", RuntimeSubsystemRequirement.Optional, dependencies: [new RuntimeSubsystemId("test.absent")] ); Assert.Single(m_host.CreateHostPipeline([missing]).startupDiagnostics); - var a = Create("test.a", RuntimeSubsystemRequirement.Optional, dependencies: [new RuntimeSubsystemId("test.b")]); - var b = Create("test.b", RuntimeSubsystemRequirement.Optional, dependencies: [a.descriptor.id]); + Factory a = Create("test.a", RuntimeSubsystemRequirement.Optional, dependencies: [new RuntimeSubsystemId("test.b")]); + Factory b = Create("test.b", RuntimeSubsystemRequirement.Optional, dependencies: [a.descriptor.id]); Assert.Throws(() => m_host.CreateHostPipeline([a, b])); Assert.Equal(0, a.createCount); Assert.Equal(0, b.createCount); @@ -154,7 +156,7 @@ public void StartupTimeoutKeepsPendingHostPipelineAndPermanentlyFaultsAdmission( .UseRetirementTimeout(TimeSpan.FromTicks(1)) .Build(); var pending = new TaskCompletionSource(); - var factory = Create("test.timeout"); + Factory factory = Create("test.timeout"); factory.pending = pending.Task; factory.failCreate = true; Assert.Throws(() => host.CreateHostPipeline([factory])); diff --git a/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs b/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs index af9ffaf87..8b6472668 100644 --- a/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs +++ b/tests/runtime/Inno.Runtime.Tests/StaticDeploymentTests.cs @@ -33,8 +33,8 @@ public void ManifestMutationCannotChangeFrozenDeployment() [Fact] public void LinkedIdentityRejectsDifferentCodeBeforeModuleActivation() { - GameCodeDeployment linked = new([CreateModule("Game", "Game.Code", 'a')]); - GameCodeDeployment replaced = new([CreateModule("Game", "Game.Code", 'b')]); + var linked = new GameCodeDeployment([CreateModule("Game", "Game.Code", 'a')]); + var replaced = new GameCodeDeployment([CreateModule("Game", "Game.Code", 'b')]); Assert.Throws(() => replaced.ValidateMatches(linked)); linked.ValidateMatches(new GameCodeDeployment([CreateModule("Game", "Game.Code", 'a')])); } diff --git a/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs b/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs index f3293f64d..9055136ba 100644 --- a/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs +++ b/tests/scene/Inno.Scene.Tests/EngineAssetIntegrationTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; @@ -296,7 +297,7 @@ public void MissingPrefabSource_PreservesConnectionAndRecoversInPlace() [Fact] public void EngineImporters_AreDiscoveredWithoutManualRegistration() { - var importerTypes = m_fixture.types.GetSubTypesOf(); + IReadOnlyList importerTypes = m_fixture.types.GetSubTypesOf(); Assert.Contains(importerTypes, type => type.Resolve(m_fixture.types).Name == "SceneAssetImporter"); Assert.Contains(importerTypes, type => type.Resolve(m_fixture.types).Name == "PrefabAssetImporter"); diff --git a/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs b/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs index 6d991d96e..06c60dfab 100644 --- a/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs +++ b/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs @@ -24,7 +24,7 @@ public void RootSiblingPositionsStayAuthoritativeAcrossHierarchyMutations() { roots.Add(scene.CreateObject("Root " + index).transform); } - var random = new Random(27102026); + var random = new Random(27_102_026); for (int iteration = 0; iteration < 200; iteration++) { ulong before = scene.hierarchyRevision; @@ -410,10 +410,7 @@ private class BaseResetComponent : GameComponent { public int baseResetCount; - protected override void Reset() - { - baseResetCount++; - } + protected override void Reset() => baseResetCount++; } private sealed class DerivedResetComponent : BaseResetComponent diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs index 2e0e3f73d..420c93422 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.CaptureKeys.cs @@ -24,7 +24,7 @@ public void StructuralCaptureDoesNotRetainRemovedSystemsWhileTheSceneRemainsAliv GC.Collect(); Assert.False(removed.IsAlive); - var replacement = scene.AddSystem(); + OrderSerializationSystemB replacement = scene.AddSystem(); SerializationSnapshot snapshot = m_serialization.CaptureSnapshot(scene, m_serializationContext); Assert.Same(replacement, Assert.Single(scene.GetSystems())); Assert.Equal(m_serialization.Serialize(scene, m_serializationContext), snapshot.ToArray()); @@ -125,7 +125,7 @@ public void UntrackedPluginPropertiesAndObjectReferencesRemainAuthoritativelyCap [MethodImpl(MethodImplOptions.NoInlining)] private WeakReference CaptureAndRemoveSystem(GameScene scene) { - var system = scene.AddSystem(); + OrderSerializationSystemA system = scene.AddSystem(); SerializationSnapshot snapshot = m_serialization.CaptureSnapshot(scene, m_serializationContext); Assert.Equal(m_serialization.Serialize(scene, m_serializationContext), snapshot.ToArray()); Assert.True(scene.RemoveSystem(system)); diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs index ad98c6ac1..26479a064 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs @@ -301,15 +301,18 @@ private static ( [StableTypeId("09d35197-7161-4fdf-8d60-95ecf3555c0c")] internal sealed class ReferenceComponent : GameComponent { - [SerializableProperty] public int value { get; set; } - [SerializableProperty] public GameObject? targetObject { get; set; } - [SerializableProperty] public ReferenceComponent? targetComponent { get; set; } + [SerializableProperty] + public int value { get; set; } + + [SerializableProperty] + public GameObject? targetObject { get; set; } + + [SerializableProperty] + public ReferenceComponent? targetComponent { get; set; } + public int resetCount { get; private set; } - protected override void Reset() - { - resetCount++; - } + protected override void Reset() => resetCount++; } [StableTypeId("f7bc9bf3-288a-45b3-9caa-26289d66c181")] diff --git a/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs b/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs index 029f41978..7fd17e116 100644 --- a/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs +++ b/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs @@ -34,21 +34,21 @@ public sealed class SceneTestsFixture : IDisposable public IdentityAllocator identities { get; } = new(); public DiagnosticHub diagnostics { get; } = new(); public LogRouter logs { get; } = new(); - public Inno.Scene.SceneWorld world { get; } + public SceneWorld world { get; } public SerializationContext serializationContext { get; } public SceneTestsFixture() { - _ = typeof(Inno.Scene.SceneAsset); - modules = new ModuleHost(new ModuleHostOptions + _ = typeof(SceneAsset); + this.modules = new ModuleHost(new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(SceneTestsCollection).Assembly) }); - types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); - serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - world = new Inno.Scene.SceneWorld(identities, types); - assets = new RejectingAssetReferenceResolver(); - serializationContext = AssetSerializationContext.Create(assets); + this.types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); + this.serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); + this.world = new SceneWorld(identities, types); + this.assets = new RejectingAssetReferenceResolver(); + this.serializationContext = AssetSerializationContext.Create(assets); } public void Dispose() diff --git a/tests/scene/Inno.Scene.Tests/TransformTests.cs b/tests/scene/Inno.Scene.Tests/TransformTests.cs index a86c80317..a67b7b975 100644 --- a/tests/scene/Inno.Scene.Tests/TransformTests.cs +++ b/tests/scene/Inno.Scene.Tests/TransformTests.cs @@ -47,8 +47,8 @@ public void SetParent_PreservesWorldTransform_AndComputesLocalWithNonUniformScal Assert.Equal(worldRotation, child.worldRotation); Assert.Equal(worldScale, child.worldScale); - Vector3 expectedLocalPosition = new Vector3(-0.5f, -0.33333334f, -0.25f); - Vector3 expectedLocalScale = new Vector3(1f, 0.6666667f, 0.5f); + var expectedLocalPosition = new Vector3(-0.5f, -0.33333334f, -0.25f); + var expectedLocalScale = new Vector3(1f, 0.6666667f, 0.5f); AssertEqualWithTolerance(worldPosition, child.worldPosition, 1e-5f); AssertEqualWithTolerance(worldRotation.normalized, child.worldRotation.normalized, 1e-5f); @@ -79,7 +79,7 @@ public void SetParent_WithRotation_PreservesWorldRotation_WithLocalRotationByInv child.SetParent(parent); - Vector3 expectedLocalPosition = new Vector3(0f, 2f, 0f); + var expectedLocalPosition = new Vector3(0f, 2f, 0f); Quaternion expectedLocalRotation = Quaternion.Inverse(parent.localRotation) * worldRotation; Quaternion normalizedExpectedRotation = expectedLocalRotation.normalized; diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs index 09cf10acd..b6b3fc971 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleSourceRewriter.cs @@ -21,7 +21,7 @@ internal static Control? current set => m_current.Value = value; } - /// + /// public void Transform(AssetSampleTransformContext context) { if (m_control is null) @@ -45,7 +45,7 @@ internal sealed class Control : IDisposable internal ManualResetEventSlim canceled { get; } = new(); internal int workerThread { get; set; } - /// + /// public void Dispose() { started.Dispose(); diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs index 53458af30..a0c5f44f7 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/EditorStyleMetricsTests.cs @@ -5,24 +5,26 @@ using System.Runtime.CompilerServices; using BGCS.Runtime; using Xunit; +using Inno.Editor.Assets.ImGui; using Inno.Editor.ImGui; using Inno.Native.ImGui; using EditorImGui = Inno.Editor.ImGui.ImGui; using EditorUI = Inno.Editor.ImGui.EditorUiSession; using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; -using ImGuiChildFlags = Inno.Editor.ImGui.ImGuiChildFlags; -using ImGuiCol = Inno.Editor.ImGui.ImGuiCol; -using ImGuiCond = Inno.Editor.ImGui.ImGuiCond; -using ImGuiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; -using ImGuiStyleVar = Inno.Editor.ImGui.ImGuiStyleVar; -using ImGuiTableRowFlags = Inno.Editor.ImGui.ImGuiTableRowFlags; -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; -using InlineRenameResult = Inno.Editor.ImGui.ImGuiWidget.InlineRenameResult; +using NativeCond = Inno.Native.ImGui.ImGuiCond; using NativeImGui = Inno.Native.ImGui.ImGui; using NativeVector2 = Inno.Native.ImGui.ImVec2C; -using TreeNodeOptions = Inno.Editor.ImGui.ImGuiWidget.TreeNodeOptions; -using TreeNodeResult = Inno.Editor.ImGui.ImGuiWidget.TreeNodeResult; +using UiChildFlags = Inno.Editor.ImGui.ImGuiChildFlags; +using UiCol = Inno.Editor.ImGui.ImGuiCol; +using UiCond = Inno.Editor.ImGui.ImGuiCond; +using UiInlineRenameResult = Inno.Editor.ImGui.ImGuiWidget.InlineRenameResult; +using UiMouseButton = Inno.Editor.ImGui.ImGuiMouseButton; +using UiStyleVar = Inno.Editor.ImGui.ImGuiStyleVar; +using UiTableRowFlags = Inno.Editor.ImGui.ImGuiTableRowFlags; +using UiTreeNodeOptions = Inno.Editor.ImGui.ImGuiWidget.TreeNodeOptions; +using UiTreeNodeResult = Inno.Editor.ImGui.ImGuiWidget.TreeNodeResult; +using UiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; namespace Inno.Editor.Scripting.Tests; @@ -32,18 +34,18 @@ public sealed unsafe class EditorStyleMetricsTests public void BrowserLayoutCapturesTheSharedScaleWithoutRetainingMutableMetrics() { var metrics = new EditorStyleMetrics(); - var browser = new Inno.Editor.Assets.ImGui.AssetBrowserStyle(metrics); + var browser = new AssetBrowserStyle(metrics); Assert.Equal(32f, browser.gridMinimumCellSize); metrics.SetZoom(1.5f); Assert.Equal(32f, browser.gridMinimumCellSize); - var scaled = new Inno.Editor.Assets.ImGui.AssetBrowserStyle(metrics); + var scaled = new AssetBrowserStyle(metrics); Assert.Equal(48f, scaled.gridMinimumCellSize); Assert.Equal(browser.gridDefaultScale, scaled.gridDefaultScale); Assert.Equal(browser.listNameSeparatorPosition, scaled.listNameSeparatorPosition); - Assert.Equal(32f, default(Inno.Editor.Assets.ImGui.AssetBrowserStyle).gridMinimumCellSize); + Assert.Equal(32f, default(AssetBrowserStyle).gridMinimumCellSize); Assert.Equal(7.5f, metrics.toolbarSectionSpacing); Assert.Equal(24f, metrics.paneMinimumVisibleWidth); - Assert.Throws(() => new Inno.Editor.Assets.ImGui.AssetBrowserStyle(null!)); + Assert.Throws(() => new AssetBrowserStyle(null!)); } [Fact] @@ -57,7 +59,7 @@ public void ZoomScalesDimensionsAndFontWhilePreservingRatios() Assert.Equal(3f, metrics.frameRounding, 3); Assert.Equal(1.8f, metrics.fontScale, 3); Assert.Equal(0.4f, metrics.propertyLabelRatio, 3); - Assert.Equal(3f, new Inno.Editor.Assets.ImGui.AssetBrowserStyle(metrics).gridDefaultScale, 3); + Assert.Equal(3f, new AssetBrowserStyle(metrics).gridDefaultScale, 3); Assert.Equal(new Vector2(7.5f, 4.5f), metrics.cellPadding); } @@ -79,19 +81,19 @@ public void ZoomCommandsClampAndResetToTheSupportedRange() [Fact] public void WrappedTextRendersThroughTheSafeLiteralTextPath() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(260f, 180f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(260f, 180f), (int)(UiCond.Always)); using NativeStringLease nativeTestText0 = Utf8Codec.EncodeNullTerminated("Wrapped Text Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText0.pointer, null, 0); float lineHeight = NativeImGui.GetTextLineHeight(); @@ -99,8 +101,8 @@ public void WrappedTextRendersThroughTheSafeLiteralTextPath() "Literal %s text remains safe and wraps. This deliberately long compilation status " + "must stay inside the modal content width instead of extending beyond its right edge." ); Assert.True(NativeImGui.GetItemRectSize().Y > lineHeight); - Inno.Native.ImGui.ImDrawList* windowDrawList = NativeImGui.Raw.GetWindowDrawList(); - Inno.Native.ImGui.ImDrawList* foregroundDrawList = NativeImGui.Raw.GetForegroundDrawList(NativeImGui.Raw.GetMainViewport()); + ImDrawList* windowDrawList = NativeImGui.Raw.GetWindowDrawList(); + ImDrawList* foregroundDrawList = NativeImGui.Raw.GetForegroundDrawList(NativeImGui.Raw.GetMainViewport()); int windowVertexCount = windowDrawList->VtxBuffer.Size; int foregroundVertexCount = foregroundDrawList->VtxBuffer.Size; EditorUI.current.widgets.DropTargetHighlight(new Vector2(20f, 20f), new Vector2(120f, 80f)); @@ -118,11 +120,11 @@ public void WrappedTextRendersThroughTheSafeLiteralTextPath() [Fact] public void CenteredWrappedTextStaysInsidePaddingAndUsesMultipleLines() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -130,7 +132,7 @@ public void CenteredWrappedTextStaysInsidePaddingAndUsesMultipleLines() io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(420f, 260f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(420f, 260f), (int)(UiCond.Always)); using NativeStringLease nativeTestText1 = Utf8Codec.EncodeNullTerminated("Centered Wrapped Text Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText1.pointer, null, 0); Vector2 origin = NativeImGui.GetCursorScreenPos(); @@ -138,15 +140,15 @@ public void CenteredWrappedTextStaysInsidePaddingAndUsesMultipleLines() var padding = new Vector2(36f, 24f); ImDrawList* drawList = NativeImGui.Raw.GetWindowDrawList(); int vertexStart = drawList->VtxBuffer.Size; - uint textColor = NativeImGui.GetColorU32((int)(ImGuiCol.Text)); + uint textColor = NativeImGui.GetColorU32((int)(UiCol.Text)); EditorUI.current.widgets.CenteredWrappedText( "A deliberately long viewport diagnostic wraps into several centered lines " + "without touching either horizontal edge of the presentation area.", area, padding ); Assert.Equal(area, NativeImGui.GetItemRectSize()); - Vector2 minimum = new(float.MaxValue); - Vector2 maximum = new(float.MinValue); + var minimum = new Vector2(float.MaxValue); + var maximum = new Vector2(float.MinValue); for (int i = vertexStart; i < drawList->VtxBuffer.Size; i++) { ImDrawVert vertex = drawList->VtxBuffer.Data[i]; @@ -176,13 +178,13 @@ public void CenteredWrappedTextStaysInsidePaddingAndUsesMultipleLines() [Fact] public void InlineRenameIsCenteredAndSelectsTheCompleteValueWhenFocused() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -214,10 +216,10 @@ public void InlineRenameIsCenteredAndSelectsTheCompleteValueWhenFocused() uint inputId = NativeImGui.GetItemID(); ImGuiInputTextState* inputState = NativeImGui.Raw.GetInputTextState(inputId); Assert.False(requestFocus); - Assert.False((inputState == null)); + Assert.False((inputState is null)); Assert.Equal(0, NativeImGui.Raw.GetSelectionStart(inputState)); Assert.Equal(value.Length, NativeImGui.Raw.GetSelectionEnd(inputState)); - uint navCursorColor = NativeImGui.GetColorU32((int)(ImGuiCol.NavCursor)); + uint navCursorColor = NativeImGui.GetColorU32((int)(UiCol.NavCursor)); AssertDrawListDoesNotContainColor( NativeImGui.Raw.GetWindowDrawList(), navCursorColor, @@ -242,11 +244,11 @@ public void InlineRenameIsCenteredAndSelectsTheCompleteValueWhenFocused() [Fact] public void InlineRenameReleasesFocusBeforeAContextMenuCanOpen() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -255,13 +257,13 @@ public void InlineRenameReleasesFocusBeforeAContextMenuCanOpen() io->Fonts->RendererHasTextures = 1; string value = "Untitled Scene"; bool requestFocus = true; - InlineRenameResult result = InlineRenameResult.None; + UiInlineRenameResult result = UiInlineRenameResult.None; Vector2 center = default; void Frame() { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(30f, 30f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(new Vector2(320f, 180f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(30f, 30f), (int)(UiCond.Always), default); + NativeImGui.SetNextWindowSize(new Vector2(320f, 180f), (int)(UiCond.Always)); using NativeStringLease nativeTestText4 = Utf8Codec.EncodeNullTerminated("Inline Rename Context Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText4.pointer, null, 0); result = EditorUI.current.widgets.InlineRename( @@ -281,11 +283,11 @@ void Frame() Assert.False(requestFocus); Assert.NotEqual(0u, NativeImGui.Raw.GetActiveID()); NativeImGui.Raw.AddMousePosEvent(io, center.X, center.Y); - NativeImGui.Raw.AddMouseButtonEvent(io, (int)ImGuiMouseButton.Right, (true ? (byte)1 : (byte)0)); + NativeImGui.Raw.AddMouseButtonEvent(io, (int)UiMouseButton.Right, (true ? (byte)1 : (byte)0)); Frame(); - NativeImGui.Raw.AddMouseButtonEvent(io, (int)ImGuiMouseButton.Right, (false ? (byte)1 : (byte)0)); + NativeImGui.Raw.AddMouseButtonEvent(io, (int)UiMouseButton.Right, (false ? (byte)1 : (byte)0)); Frame(); - Assert.Equal(InlineRenameResult.FocusLost, result); + Assert.Equal(UiInlineRenameResult.FocusLost, result); Assert.Equal(0u, NativeImGui.Raw.GetActiveID()); } finally @@ -297,11 +299,11 @@ void Frame() [Fact] public void InlineRenameCentersWithinTheNativeTableRowBounds() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -313,10 +315,10 @@ public void InlineRenameCentersWithinTheNativeTableRowBounds() NativeImGui.NewFrame(); using NativeStringLease nativeTestText5 = Utf8Codec.EncodeNullTerminated("Inline Rename Table Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText5.pointer, null, 0); - NativeImGui.PushStyleVar((int)(ImGuiStyleVar.CellPadding), new Vector2(6f, 3f)); - Assert.True(NativeImGui.BeginTable("##rename_table", 1, 0, default(Vector2), 0f)); + NativeImGui.PushStyleVar((int)(UiStyleVar.CellPadding), new Vector2(6f, 3f)); + Assert.True(NativeImGui.BeginTable("##rename_table", 1, 0, default, 0f)); float rowHeight = NativeImGui.GetTextLineHeight() + NativeImGui.Raw.GetStyle()->CellPadding.Y * 2f; - NativeImGui.TableNextRow((int)(ImGuiTableRowFlags.None), rowHeight); + NativeImGui.TableNextRow((int)(UiTableRowFlags.None), rowHeight); _ = NativeImGui.TableSetColumnIndex(0); ImGuiTable* table = NativeImGui.Raw.GetCurrentTable(); Vector2 cursor = NativeImGui.GetCursorScreenPos(); @@ -347,13 +349,13 @@ public void InlineRenameCentersWithinTheNativeTableRowBounds() [Fact] public void TreeGuideDepthRemainsBalancedAcrossSupportedZoomLevels() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -381,13 +383,13 @@ public void TreeGuideDepthRemainsBalancedAcrossSupportedZoomLevels() [Fact] public void MenuSelectorPopupIsBoundedAndScrollsLongContent() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -395,8 +397,8 @@ public void MenuSelectorPopupIsBoundedAndScrollsLongContent() for (int frame = 0; frame < 2; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(40f, 40f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(40f, 40f), (int)(UiCond.Always), default); + NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(UiCond.Always)); using NativeStringLease nativeTestText6 = Utf8Codec.EncodeNullTerminated("Menu Selector Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText6.pointer, null, 0); if (frame == 0) @@ -404,11 +406,11 @@ public void MenuSelectorPopupIsBoundedAndScrollsLongContent() NativeImGui.OpenPopup("##menu_selector_popup_test"); } Assert.True(EditorUI.current.widgets.BeginMenuSelector("test", "Untagged", 180f, 240f)); - ImGuiWindowFlags flags = (ImGuiWindowFlags)NativeImGui.Raw.GetCurrentWindow()->Flags; - Assert.True(flags.HasFlag(ImGuiWindowFlags.AlwaysAutoResize)); - Assert.False(flags.HasFlag(ImGuiWindowFlags.NoScrollbar)); - Assert.False(flags.HasFlag(ImGuiWindowFlags.NoScrollWithMouse)); - Assert.True(flags.HasFlag(ImGuiWindowFlags.NoSavedSettings)); + UiWindowFlags flags = (UiWindowFlags)NativeImGui.Raw.GetCurrentWindow()->Flags; + Assert.True(flags.HasFlag(UiWindowFlags.AlwaysAutoResize)); + Assert.False(flags.HasFlag(UiWindowFlags.NoScrollbar)); + Assert.False(flags.HasFlag(UiWindowFlags.NoScrollWithMouse)); + Assert.True(flags.HasFlag(UiWindowFlags.NoSavedSettings)); Assert.True(NativeImGui.GetWindowSize().X >= 240f); string newTag = string.Empty; NativeImGui.SetNextItemWidth(160f); @@ -446,11 +448,11 @@ public void MenuSelectorPopupIsBoundedAndScrollsLongContent() [Fact] public void SmallMenuSelectorDoesNotReserveAScrollbar() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -460,8 +462,8 @@ public void SmallMenuSelectorDoesNotReserveAScrollbar() for (int frame = 0; frame < 3; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(40f, 40f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(40f, 40f), (int)(UiCond.Always), default); + NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(UiCond.Always)); using NativeStringLease nativeTestText7 = Utf8Codec.EncodeNullTerminated("Small Menu Selector Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText7.pointer, null, 0); if (frame == 0) @@ -493,11 +495,11 @@ public void SmallMenuSelectorDoesNotReserveAScrollbar() [Fact] public void SmallContextMenuDoesNotReserveScrollbars() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -537,11 +539,11 @@ public void SmallContextMenuDoesNotReserveScrollbars() [Fact] public void BoundedComboPopupUsesTheSharedScrollingContract() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -553,8 +555,8 @@ public void BoundedComboPopupUsesTheSharedScrollingContract() for (int frame = 0; frame < 5; frame++) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(400f, 340f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(new Vector2(220f, 120f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(400f, 340f), (int)(UiCond.Always), default); + NativeImGui.SetNextWindowSize(new Vector2(220f, 120f), (int)(UiCond.Always)); using NativeStringLease nativeTestText9 = Utf8Codec.EncodeNullTerminated("Bounded Combo Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText9.pointer, null, 0); uint parentViewportId = NativeImGui.Raw.GetWindowViewport()->ID; @@ -609,11 +611,11 @@ public void BoundedComboPopupUsesTheSharedScrollingContract() [Fact] public void TreeRegionScrollsHorizontallyOnlyForRealContentOverflow() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -635,11 +637,11 @@ public void TreeRegionScrollsHorizontallyOnlyForRealContentOverflow() [Fact] public void TreeRegionReleasesViewportWidthAfterItShrinks() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -659,11 +661,11 @@ public void TreeRegionReleasesViewportWidthAfterItShrinks() [Fact] public void TreeGuideSegmentsRemainVisibleAcrossCompactRows() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -683,11 +685,11 @@ public void TreeGuideSegmentsRemainVisibleAcrossCompactRows() [Fact] public void ChildGuideRetainsAVisualGapBelowTheParentWithoutChangingCompactRowHeight() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -696,21 +698,21 @@ public void ChildGuideRetainsAVisualGapBelowTheParentWithoutChangingCompactRowHe io->Fonts->RendererHasTextures = 1; EditorUI.current.widgets.SetupStyle(); NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(UiCond.Always)); using NativeStringLease nativeTestText10 = Utf8Codec.EncodeNullTerminated("Gapped Parent Guide Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText10.pointer, null, 0); float expectedHeight = NativeImGui.GetTextLineHeight(); EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult parent = EditorUI.current.widgets.TreeNode( + UiTreeNodeResult parent = EditorUI.current.widgets.TreeNode( "connected_parent", static _ => NativeImGui.TextUnformatted("Parent"), - new TreeNodeOptions() + new UiTreeNodeOptions() ); Assert.True(parent.isOpen); - TreeNodeResult child = EditorUI.current.widgets.TreeNode( + UiTreeNodeResult child = EditorUI.current.widgets.TreeNode( "connected_child", static _ => NativeImGui.TextUnformatted("Child"), - new TreeNodeOptions { isLeaf = true } + new UiTreeNodeOptions { isLeaf = true } ); NativeImGui.TreePop(); Assert.Equal(expectedHeight, parent.max.Y - parent.min.Y, 3); @@ -728,11 +730,11 @@ public void ChildGuideRetainsAVisualGapBelowTheParentWithoutChangingCompactRowHe [Fact] public void TreeGuidesAreDrawnFromTheCurrentFrameWhileDragging() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -741,23 +743,23 @@ public void TreeGuidesAreDrawnFromTheCurrentFrameWhileDragging() io->Fonts->RendererHasTextures = 1; EditorUI.current.widgets.SetupStyle(); NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(UiCond.Always)); using NativeStringLease nativeTestText11 = Utf8Codec.EncodeNullTerminated("Dragging Tree Guide Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText11.pointer, null, 0); ImGuiNativeContext* currentContext = NativeImGui.Raw.GetCurrentContext(); currentContext->DragDropActive = 1; EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult root = EditorUI.current.widgets.TreeNode( + UiTreeNodeResult root = EditorUI.current.widgets.TreeNode( "drag_root", static _ => NativeImGui.TextUnformatted("Assets"), - new TreeNodeOptions() + new UiTreeNodeOptions() ); if (root.isOpen) { _ = EditorUI.current.widgets.TreeNode( "drag_child", static _ => NativeImGui.TextUnformatted("Scene"), - new TreeNodeOptions { isLeaf = true } + new UiTreeNodeOptions { isLeaf = true } ); NativeImGui.TreePop(); } @@ -776,11 +778,11 @@ public void TreeGuidesAreDrawnFromTheCurrentFrameWhileDragging() [Fact] public void TreeRowBackgroundsUseCurrentGeometryWhileTheWindowChanges() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -800,11 +802,11 @@ public void TreeRowBackgroundsUseCurrentGeometryWhileTheWindowChanges() [Fact] public void TreeRowsRetainTheirCompactContentHeight() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -813,14 +815,14 @@ public void TreeRowsRetainTheirCompactContentHeight() io->Fonts->RendererHasTextures = 1; EditorUI.current.widgets.SetupStyle(); NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(320f, 240f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(320f, 240f), (int)(UiCond.Always)); using NativeStringLease nativeTestText12 = Utf8Codec.EncodeNullTerminated("Compact Tree Row Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText12.pointer, null, 0); float expectedHeight = NativeImGui.GetTextLineHeight(); - TreeNodeResult row = EditorUI.current.widgets.TreeNode( + UiTreeNodeResult row = EditorUI.current.widgets.TreeNode( "compact_row", static _ => NativeImGui.TextUnformatted("GameObject"), - new TreeNodeOptions { isLeaf = true } + new UiTreeNodeOptions { isLeaf = true } ); Assert.Equal(expectedHeight, row.max.Y - row.min.Y, 3); NativeImGui.End(); @@ -835,11 +837,11 @@ public void TreeRowsRetainTheirCompactContentHeight() [Fact] public void DoubleClickingTreeContentTogglesNonLeafExpansion() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -847,17 +849,17 @@ public void DoubleClickingTreeContentTogglesNonLeafExpansion() io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; io->Fonts->RendererHasTextures = 1; EditorUI.current.widgets.SetupStyle(); - TreeNodeResult initial = DrawDoubleClickTreeFrame(); - Vector2 contentCenter = new(initial.contentMin.X + 20f, (initial.min.Y + initial.max.Y) * 0.5f); + UiTreeNodeResult initial = DrawDoubleClickTreeFrame(); + var contentCenter = new Vector2(initial.contentMin.X + 20f, (initial.min.Y + initial.max.Y) * 0.5f); NativeImGui.Raw.AddMousePosEvent(io, contentCenter.X, contentCenter.Y); NativeImGui.Raw.AddMouseButtonEvent(io, 0, (true ? (byte)1 : (byte)0)); _ = DrawDoubleClickTreeFrame(); NativeImGui.Raw.AddMouseButtonEvent(io, 0, (false ? (byte)1 : (byte)0)); _ = DrawDoubleClickTreeFrame(); NativeImGui.Raw.AddMouseButtonEvent(io, 0, (true ? (byte)1 : (byte)0)); - TreeNodeResult doubleClicked = DrawDoubleClickTreeFrame(); + UiTreeNodeResult doubleClicked = DrawDoubleClickTreeFrame(); NativeImGui.Raw.AddMouseButtonEvent(io, 0, (false ? (byte)1 : (byte)0)); - TreeNodeResult expanded = DrawDoubleClickTreeFrame(); + UiTreeNodeResult expanded = DrawDoubleClickTreeFrame(); Assert.True(doubleClicked.isDoubleClicked); Assert.True(expanded.isOpen); } @@ -870,11 +872,11 @@ public void DoubleClickingTreeContentTogglesNonLeafExpansion() [Fact] public void InspectorContentPreservesStandardPaddingWithoutArtificialHorizontalOverflow() { - var context = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* context = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); @@ -894,29 +896,29 @@ public void InspectorContentPreservesStandardPaddingWithoutArtificialHorizontalO private static void DrawTreeFrame(bool assertContinuousGuides = false) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(Inno.Native.ImGui.ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(480f, 320f), (int)(NativeCond.Always)); using NativeStringLease nativeTestText13 = Utf8Codec.EncodeNullTerminated("Tree Zoom Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText13.pointer, null, 0); EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult root = EditorUI.current.widgets.TreeNode( + UiTreeNodeResult root = EditorUI.current.widgets.TreeNode( "root", static _ => NativeImGui.TextUnformatted("Assets"), - new TreeNodeOptions() + new UiTreeNodeOptions() ); if (root.isOpen) { EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult folder = EditorUI.current.widgets.TreeNode( + UiTreeNodeResult folder = EditorUI.current.widgets.TreeNode( "folder", static _ => NativeImGui.TextUnformatted("Scene"), - new TreeNodeOptions() + new UiTreeNodeOptions() ); if (folder.isOpen) { _ = EditorUI.current.widgets.TreeNode( "nested-file", static _ => NativeImGui.TextUnformatted("TestScene1.iscene"), - new TreeNodeOptions { isLeaf = true } + new UiTreeNodeOptions { isLeaf = true } ); NativeImGui.TreePop(); } @@ -924,7 +926,7 @@ private static void DrawTreeFrame(bool assertContinuousGuides = false) _ = EditorUI.current.widgets.TreeNode( "sibling-folder", static _ => NativeImGui.TextUnformatted("Settings"), - new TreeNodeOptions { isLeaf = true } + new UiTreeNodeOptions { isLeaf = true } ); NativeImGui.TreePop(); } @@ -937,24 +939,24 @@ private static void DrawTreeFrame(bool assertContinuousGuides = false) NativeImGui.Render(); } - private static TreeNodeResult DrawDoubleClickTreeFrame() + private static UiTreeNodeResult DrawDoubleClickTreeFrame() { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(new Vector2(320f, 240f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(new Vector2(20f, 20f), (int)(UiCond.Always), default); + NativeImGui.SetNextWindowSize(new Vector2(320f, 240f), (int)(UiCond.Always)); using NativeStringLease nativeTestText14 = Utf8Codec.EncodeNullTerminated("Double Click Tree Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText14.pointer, null, 0); - TreeNodeResult result = EditorUI.current.widgets.TreeNode( + UiTreeNodeResult result = EditorUI.current.widgets.TreeNode( "double_click_parent", static _ => NativeImGui.TextUnformatted("Parent"), - new TreeNodeOptions() + new UiTreeNodeOptions() ); if (result.isOpen) { _ = EditorUI.current.widgets.TreeNode( "double_click_child", static _ => NativeImGui.TextUnformatted("Child"), - new TreeNodeOptions { isLeaf = true } + new UiTreeNodeOptions { isLeaf = true } ); NativeImGui.TreePop(); } @@ -967,25 +969,25 @@ private static TreeNodeResult DrawDoubleClickTreeFrame() private static void DrawTreeOverflowFrame(bool assertRanges) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(560f, 320f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(560f, 320f), (int)(UiCond.Always)); using NativeStringLease nativeTestText15 = Utf8Codec.EncodeNullTerminated("Tree Overflow Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText15.pointer, null, 0); if (NativeImGui.BeginChild( "##short_tree", new Vector2(220f, 100f), - (int)(ImGuiChildFlags.None), - (int)(ImGuiWindowFlags.HorizontalScrollbar) + (int)(UiChildFlags.None), + (int)(UiWindowFlags.HorizontalScrollbar) )) { _ = EditorUI.current.widgets.TreeNode( "short", static _ => NativeImGui.TextUnformatted("Object"), - new TreeNodeOptions { isLeaf = true } + new UiTreeNodeOptions { isLeaf = true } ); if (assertRanges) { Assert.Equal(0f, NativeImGui.GetScrollMaxX(), 3); Assert.False((NativeImGui.Raw.GetCurrentWindow()->ScrollbarX != 0)); - Assert.True((NativeImGui.Raw.GetCurrentWindow()->Flags & (int)ImGuiWindowFlags.HorizontalScrollbar) != 0); + Assert.True((NativeImGui.Raw.GetCurrentWindow()->Flags & (int)UiWindowFlags.HorizontalScrollbar) != 0); } } @@ -993,19 +995,19 @@ private static void DrawTreeOverflowFrame(bool assertRanges) if (NativeImGui.BeginChild( "##long_tree", new Vector2(220f, 100f), - (int)(ImGuiChildFlags.None), - (int)(ImGuiWindowFlags.HorizontalScrollbar) + (int)(UiChildFlags.None), + (int)(UiWindowFlags.HorizontalScrollbar) )) { _ = EditorUI.current.widgets.TreeNode( "long", static _ => NativeImGui.TextUnformatted("Object_With_A_Name_That_Is_Intentionally_Wider_Than_The_Tree_Viewport"), - new TreeNodeOptions { isLeaf = true } + new UiTreeNodeOptions { isLeaf = true } ); if (assertRanges) { Assert.True(NativeImGui.GetScrollMaxX() > 0f); Assert.True((NativeImGui.Raw.GetCurrentWindow()->ScrollbarX != 0)); - Assert.True((NativeImGui.Raw.GetCurrentWindow()->Flags & (int)ImGuiWindowFlags.HorizontalScrollbar) != 0); + Assert.True((NativeImGui.Raw.GetCurrentWindow()->Flags & (int)UiWindowFlags.HorizontalScrollbar) != 0); } } @@ -1019,22 +1021,22 @@ private static void DrawHorizontallyScrolledTreeFrame( bool assertGeometry ) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(360f, 220f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(360f, 220f), (int)(UiCond.Always)); using NativeStringLease nativeTestText16 = Utf8Codec.EncodeNullTerminated("Scrolled Tree Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText16.pointer, null, 0); NativeImGui.SetNextWindowScroll(new Vector2(requestedScroll, 0f)); if (NativeImGui.BeginChild( "##scrolled_tree", new Vector2(220f, 120f), - (int)(ImGuiChildFlags.None), - (int)(ImGuiWindowFlags.HorizontalScrollbar) + (int)(UiChildFlags.None), + (int)(UiWindowFlags.HorizontalScrollbar) )) { Vector2 contentCursor = default; - TreeNodeResult row = EditorUI.current.widgets.TreeNode("scrolled", _ => + UiTreeNodeResult row = EditorUI.current.widgets.TreeNode("scrolled", _ => { contentCursor = NativeImGui.GetCursorScreenPos(); NativeImGui.TextUnformatted("Scene_With_A_Name_That_Is_Intentionally_Wider_Than_The_Tree_Viewport"); - }, new TreeNodeOptions { isLeaf = true, showBackground = true, backgroundColor = EditorPalette.title }); + }, new UiTreeNodeOptions { isLeaf = true, showBackground = true, backgroundColor = EditorPalette.title }); if (assertGeometry) { ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); @@ -1056,26 +1058,26 @@ private static void DrawResizableTreeFrame( bool assertNoOverflow ) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(560f, 260f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(560f, 260f), (int)(UiCond.Always)); using NativeStringLease nativeTestText17 = Utf8Codec.EncodeNullTerminated("Resizable Tree Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText17.pointer, null, 0); NativeImGui.SetNextWindowScroll(new Vector2(requestedScroll, 0f)); if (NativeImGui.BeginChild( "##resizable_tree", new Vector2(width, 120f), - (int)(ImGuiChildFlags.None), - (int)(ImGuiWindowFlags.HorizontalScrollbar) + (int)(UiChildFlags.None), + (int)(UiWindowFlags.HorizontalScrollbar) )) { _ = EditorUI.current.widgets.TreeNode( "resizable_row", static _ => NativeImGui.TextUnformatted("GameObject"), - new TreeNodeOptions + new UiTreeNodeOptions { isLeaf = true, drawViewportOverlay = static () => { ImGuiWindow* window = NativeImGui.Raw.GetCurrentWindow(); - Vector2 overlaySize = new(NativeImGui.GetFontSize(), NativeImGui.GetTextLineHeight()); + var overlaySize = new Vector2(NativeImGui.GetFontSize(), NativeImGui.GetTextLineHeight()); NativeImGui.SameLine(0f, -1f); Vector2 cursor = NativeImGui.GetCursorScreenPos(); NativeImGui.SetCursorScreenPos(new Vector2(MathF.Max(cursor.X, window->WorkRect.Max.X - overlaySize.X), cursor.Y)); @@ -1121,22 +1123,22 @@ private static void DrawCurrentTreeBackgroundFrame( Vector2 size ) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowPos(position, (int)(ImGuiCond.Always), default(Vector2)); - NativeImGui.SetNextWindowSize(size, (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowPos(position, (int)(UiCond.Always), default); + NativeImGui.SetNextWindowSize(size, (int)(UiCond.Always)); using NativeStringLease nativeTestText18 = Utf8Codec.EncodeNullTerminated("Current Tree Background Test", allowsNull: false); _ = NativeImGui.Raw.Begin((sbyte*)nativeTestText18.pointer, null, 0); EditorUI.current.widgets.SetNextTreeNodeOpen(true); - TreeNodeResult root = EditorUI.current.widgets.TreeNode( + UiTreeNodeResult root = EditorUI.current.widgets.TreeNode( "current_background_root", static _ => NativeImGui.TextUnformatted("TestScene"), - new TreeNodeOptions { showBackground = true, backgroundColor = EditorPalette.title, suppressHoverHighlight = true } + new UiTreeNodeOptions { showBackground = true, backgroundColor = EditorPalette.title, suppressHoverHighlight = true } ); if (root.isOpen) { _ = EditorUI.current.widgets.TreeNode( "current_background_child", static _ => NativeImGui.TextUnformatted("GameObject"), - new TreeNodeOptions { isLeaf = true, selected = true } + new UiTreeNodeOptions { isLeaf = true, selected = true } ); NativeImGui.TreePop(); } @@ -1146,7 +1148,7 @@ Vector2 size "The current frame did not submit the Scene row background." ); AssertCurrentDrawListContainsColor( - NativeImGui.GetColorU32((int)(ImGuiCol.Header)), + NativeImGui.GetColorU32((int)(UiCol.Header)), "The current frame did not submit the selected row highlight." ); NativeImGui.End(); @@ -1190,8 +1192,8 @@ private static void AssertColorBoundsStayCloseToItem( Vector2 itemMax, float maximumExpansion ) { - Vector2 colorMin = new(float.MaxValue); - Vector2 colorMax = new(float.MinValue); + var colorMin = new Vector2(float.MaxValue); + var colorMax = new Vector2(float.MinValue); for (int i = 0; i < drawList->VtxBuffer.Size; i++) { ImDrawVert vertex = drawList->VtxBuffer.Data[i]; @@ -1240,13 +1242,13 @@ uint color private static void DrawInspectorCardFrame(bool assertHorizontalRange) { NativeImGui.NewFrame(); - NativeImGui.SetNextWindowSize(new Vector2(320f, 260f), (int)(ImGuiCond.Always)); + NativeImGui.SetNextWindowSize(new Vector2(320f, 260f), (int)(UiCond.Always)); bool isOpen = true; EditorUI.current.widgets.PanelWindow( "Inspector Width Test", ref isOpen, () => DrawInspectorCardBody(assertHorizontalRange), - ImGuiWindowFlags.NoSavedSettings, + UiWindowFlags.NoSavedSettings, useWindowPadding: false ); NativeImGui.Render(); @@ -1294,7 +1296,7 @@ private static void DrawInspectorCardBody(bool assertHorizontalRange) Assert.Equal(tagMaximumX, NativeImGui.GetItemRectMin().X, 3); } NativeImGui.SameLine(0f, EditorUI.current.widgets.style.headerSectionSpacing); - EditorUI.current.widgets.LabelChip("Layer", new Vector4(0.24f, 0.34f, 0.40f, 1f)); + EditorUI.current.widgets.LabelChip("Layer", new Vector4(0.24f, 0.34f, 0.4f, 1f)); float layerMaximumX = NativeImGui.GetItemRectMax().X; NativeImGui.SameLine(0f, 0f); NativeImGui.Dummy(new Vector2(80f, NativeImGui.GetFrameHeight())); diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs index c5402bbb7..aed0a8c3d 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs @@ -8,6 +8,7 @@ using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Editor.Annotations; @@ -44,7 +45,7 @@ public InspectionPipelineTests() m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); m_runtime = new EditorInteractionRuntime( - new EditorContext(m_projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_types, m_logs, [m_types, m_serialization] @@ -70,19 +71,30 @@ public unsafe void InlineChildFailureIsConsumedAndReadonlyDisabledScopeRemainsBa { EditorContext editor = m_runtime.context; using var drawers = new PropertyDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - var renderer = new SerializedPropertyRenderer(drawers, attributes, m_runtime.interactions, new NoopEditService(), m_logs); + using var attributes = new InspectorAttributeDrawerRegistry( + m_runtime.interactions, + m_types, + m_serialization, + [] + ); + var renderer = new SerializedPropertyRenderer( + drawers, + attributes, + m_runtime.interactions, + new NoopEditService(), + m_logs + ); Assert.IsType(drawers.Resolve(typeof(InlineParent))); var owner = new InlineOwner(); SerializedProperty property = Assert.Single(m_serialization.GetProperties(owner)); InlineParentDrawer.drewAfterFailure = false; - var nativeContext = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* nativeContext = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -114,11 +126,11 @@ public unsafe void InlineChildFailureIsConsumedAndReadonlyDisabledScopeRemainsBa [Fact] public unsafe void PanelWindowFailureStillEndsTheWindowAndAllowsLaterContent() { - var nativeContext = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* nativeContext = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); PrepareNativeFrame(); bool isOpen = true; @@ -146,9 +158,26 @@ public unsafe void TextEditStateIsScopedByRendererOwnerAndPropertyPath() { EditorContext editor = m_runtime.context; using var drawers = new PropertyDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - var firstRenderer = new SerializedPropertyRenderer(drawers, attributes, m_runtime.interactions, new NoopEditService(), m_logs); - var secondRenderer = new SerializedPropertyRenderer(drawers, attributes, m_runtime.interactions, new NoopEditService(), m_logs); + using var attributes = new InspectorAttributeDrawerRegistry( + m_runtime.interactions, + m_types, + m_serialization, + [] + ); + var firstRenderer = new SerializedPropertyRenderer( + drawers, + attributes, + m_runtime.interactions, + new NoopEditService(), + m_logs + ); + var secondRenderer = new SerializedPropertyRenderer( + drawers, + attributes, + m_runtime.interactions, + new NoopEditService(), + m_logs + ); var firstOwner = new TextStateOwner { value = new TextStateValue("First") @@ -160,11 +189,11 @@ public unsafe void TextEditStateIsScopedByRendererOwnerAndPropertyPath() SerializedProperty firstProperty = Assert.Single(m_serialization.GetProperties(firstOwner)); SerializedProperty secondProperty = Assert.Single(m_serialization.GetProperties(secondOwner)); TextStateDrawer.observations.Clear(); - var nativeContext = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* nativeContext = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); DrawPropertyFrame(firstRenderer, editor, firstOwner, firstProperty); DrawPropertyFrame(firstRenderer, editor, firstOwner, firstProperty); @@ -184,8 +213,19 @@ public unsafe void PresentationAttributesComposeAndCustomDrawersRemainExtensible { EditorContext editor = m_runtime.context; using var drawers = new PropertyDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - using var attributes = new InspectorAttributeDrawerRegistry(m_runtime.interactions, m_types, m_serialization, []); - var renderer = new SerializedPropertyRenderer(drawers, attributes, m_runtime.interactions, new NoopEditService(), m_logs); + using var attributes = new InspectorAttributeDrawerRegistry( + m_runtime.interactions, + m_types, + m_serialization, + [] + ); + var renderer = new SerializedPropertyRenderer( + drawers, + attributes, + m_runtime.interactions, + new NoopEditService(), + m_logs + ); var owner = new AttributeOwner(); SerializedProperty property = Assert.Single( m_serialization.GetProperties(owner), @@ -193,11 +233,11 @@ public unsafe void PresentationAttributesComposeAndCustomDrawersRemainExtensible ); AttributeValueDrawer.observations.Clear(); ProbeInspectorAttributeDrawer.observations.Clear(); - var nativeContext = NativeImGui.Raw.CreateContext(null); + ImGuiNativeContext* nativeContext = NativeImGui.Raw.CreateContext(null); try { NativeImGui.Raw.GetIO()->IniFilename = null; - using var uiSession = new Inno.Editor.ImGui.EditorUiSession(); + using var uiSession = new EditorUI(); using IDisposable uiScope = uiSession.Enter(); DrawPropertyFrame(renderer, editor, owner, property); Assert.Empty(AttributeValueDrawer.observations); @@ -219,7 +259,7 @@ public unsafe void PresentationAttributesComposeAndCustomDrawersRemainExtensible private static unsafe void PrepareNativeFrame() { - Inno.Native.ImGui.ImGuiIO* io = NativeImGui.Raw.GetIO(); + ImGuiIO* io = NativeImGui.Raw.GetIO(); io->DisplaySize = Unsafe.BitCast(new Vector2(640f, 480f)); io->DeltaTime = 1f / 60f; io->BackendFlags |= (int)ImGuiBackendFlags.RendererHasTextures; @@ -342,7 +382,7 @@ internal sealed class TextStateDrawer : IPropertyDrawer public void Draw(PropertyDrawContext context) { - var value = (TextStateValue)context.GetValue()!; + TextStateValue value = (TextStateValue)context.GetValue()!; bool hasState = context.TryGetTextState("editing", out string? state); observations.Add($"{value.id}:{(hasState ? state : "")}"); context.SetTextState("editing", value.id); @@ -356,7 +396,7 @@ internal sealed class InlineParentDrawer : IPropertyDrawer public void Draw(PropertyDrawContext context) { - var parent = (InlineParent)context.GetValue()!; + InlineParent parent = (InlineParent)context.GetValue()!; context.DrawInlineChild("child", typeof(InlineFailure), () => parent.child, static _ => {}, readOnly: true); drewAfterFailure = true; } diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs index 902106db2..c203fa6f8 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InspectorPresentationLayoutTests.cs @@ -8,10 +8,10 @@ using EditorUI = Inno.Editor.ImGui.EditorUiSession; using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; -using ImGuiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; using NativeImGui = Inno.Native.ImGui.ImGui; using NativeVector2 = Inno.Native.ImGui.ImVec2C; using NativeVector4 = Inno.Native.ImGui.ImVec4C; +using UiWindowFlags = Inno.Editor.ImGui.ImGuiWindowFlags; namespace Inno.Editor.Scripting.Tests; @@ -19,7 +19,7 @@ namespace Inno.Editor.Scripting.Tests; public sealed unsafe class InspectorPresentationLayoutTests : IDisposable { private readonly ImGuiNativeContext* m_context = NativeImGui.Raw.CreateContext(null); - private readonly Inno.Editor.ImGui.EditorUiSession m_ui = new(); + private readonly EditorUI m_ui = new(); private readonly IDisposable m_uiScope; public InspectorPresentationLayoutTests() @@ -107,7 +107,7 @@ void Frame() } using NativeStringLease nativeTestText2 = Utf8Codec.EncodeNullTerminated("##Tooltip_00", allowsNull: false); ImGuiWindow* tooltip = NativeImGui.Raw.FindWindowByName((sbyte*)nativeTestText2.pointer); - Assert.False((tooltip == null)); + Assert.False((tooltip is null)); Assert.True((tooltip->Active != 0)); Assert.InRange(tooltip->Pos.X, 0, width); Assert.InRange(tooltip->Pos.Y, 0, height); @@ -162,7 +162,7 @@ float framebufferScale NativeImGui.SetNextWindowPos(new Vector2(30, 30)); NativeImGui.SetNextWindowSize(new Vector2(320, 180)); using NativeStringLease nativeTestText4 = Utf8Codec.EncodeNullTerminated("Opaque surface", allowsNull: false); - NativeImGui.Raw.Begin((sbyte*)nativeTestText4.pointer, null, (int)(ImGuiWindowFlags.NoCollapse)); + NativeImGui.Raw.Begin((sbyte*)nativeTestText4.pointer, null, (int)(UiWindowFlags.NoCollapse)); NativeImGui.End(); NativeImGui.Render(); } @@ -174,7 +174,7 @@ float framebufferScale // conceal a transparent join between independently anti-aliased background shapes. for (int sample = -10; sample <= 10; sample++) { - Vector2 point = new(window->Pos.X + window->Size.X * 0.47f, seam + sample * 0.1f); + var point = new Vector2(window->Pos.X + window->Size.X * 0.47f, seam + sample * 0.1f); float coverage = CoverageAt(window->DrawList, point); Assert.True( coverage >= 0.999f, @@ -185,7 +185,7 @@ float framebufferScale for (int pixel = -2; pixel <= 2; pixel++) { float y = (MathF.Floor(seam * framebufferScale) + pixel + 0.5f) / framebufferScale; - Vector2 point = new(window->Pos.X + window->Size.X * 0.47f, y); + var point = new Vector2(window->Pos.X + window->Size.X * 0.47f, y); Assert.True( CoverageAt(window->DrawList, point) >= 0.999f, $"Transparent device pixel: zoom={zoom}, scale={framebufferScale}, y={y}" diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs index 7de2fd212..d439079aa 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UiLifecycle.cs @@ -47,7 +47,7 @@ public sealed class SnapshotPayload : ISerializable private static (SerializationSnapshot, WeakReference) CaptureScriptSnapshot(ScriptingFixture fixture) { Type type = fixture.ResolveActiveType("SnapshotPayload"); - var payload = (ISerializable)Activator.CreateInstance(type)!; + ISerializable payload = (ISerializable)Activator.CreateInstance(type)!; return (fixture.host.serialization.CaptureSnapshot(new CapturedScriptPayload(payload)), new WeakReference(type)); } @@ -92,8 +92,7 @@ public void TenActionMenuGenerationsRetireTypesAndPreserveLastGoodAfterFailure() GC.KeepAlive(retainedMenu); void WriteAction(int version) - { - m_fixture.Write("Editor/LifecycleAction.editor.cs", $$""" + => m_fixture.Write("Editor/LifecycleAction.editor.cs", $$""" using InnoEditor.Interactions; [EditorAction("tests.lifecycle.action", "tests/menu-lifecycle")] @@ -106,7 +105,6 @@ protected override EditorActionState Query(EditorActionContext context) protected override void Execute(EditorActionContext context) { } } """); - } } private static void AssertMenu( diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs index e74f762a2..725a3023b 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs @@ -4,9 +4,13 @@ using System.IO; using System.IO.Compression; using System.Linq; +using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Loader; +using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; @@ -15,9 +19,12 @@ using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Core.Diagnostics; +using Inno.Core.Execution; using Inno.Core.IO; using Inno.Core.Identity; +using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -87,7 +94,7 @@ public void SourceLocalAssetPathsFollowInstalledPluginOwnership(bool runtimeDepl ["Assets/Nested.imeta"] = serialization.Serialize( new ScriptingAssetSourceMeta { persistentId = Guid.NewGuid(), sourceKind = (int)AssetSourceKind.Directory } ), - ["Assets/Nested/SourceLocalPathProbe.cs"] = System.Text.Encoding.UTF8.GetBytes(""" + ["Assets/Nested/SourceLocalPathProbe.cs"] = Encoding.UTF8.GetBytes(""" using InnoEngine.Assets; public static class SourceLocalPathProbe { @@ -132,14 +139,14 @@ public static class SourceLocalPathProbe [MethodImpl(MethodImplOptions.NoInlining)] private static AssetPath InvokePublicPathProbe(string assemblyPath) { - var lifetime = new System.Runtime.Loader.AssemblyLoadContext("source-local-path-test", isCollectible: true); + var lifetime = new AssemblyLoadContext("source-local-path-test", isCollectible: true); try { using var stream = new MemoryStream(File.ReadAllBytes(assemblyPath)); - var assembly = lifetime.LoadFromStream(stream); + Assembly assembly = lifetime.LoadFromStream(stream); Func resolve = assembly.GetType("SourceLocalPathProbe", throwOnError: true)!.GetMethod( "Resolve", - System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static + BindingFlags.Public | BindingFlags.Static )!.CreateDelegate>(); return resolve(); } @@ -773,8 +780,8 @@ public void ProjectTildeDirectoriesRemainBrowsableAndParticipateInAuthoringCompi public void InstalledPluginSampleImportsAsAnImmediatelyCompilableWritableCopy() { using var fixture = new ScriptingFixture(WriteSamplePlugin); - AssetPath source = new(new AssetSourceId("tests.samples"), "~Starter"); - AssetPath sourceFile = new(new AssetSourceId("tests.samples"), "~Starter/StarterBehavior.cs"); + var source = new AssetPath(new AssetSourceId("tests.samples"), "~Starter"); + var sourceFile = new AssetPath(new AssetSourceId("tests.samples"), "~Starter/StarterBehavior.cs"); Assert.True(fixture.assets.TryGetFileSystemEntry(source, out AssetFileEntry sample)); Assert.True(sample.isReadOnly); Assert.True(sample.isSample); @@ -806,7 +813,7 @@ public void InstalledPluginSampleImportsAsAnImmediatelyCompilableWritableCopy() ); Assert.True(candidate.success, FormatDiagnostics(candidate)); }); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); import.Commit(); AssetPath imported = import.target; Assert.Equal(AssetPath.Project("~Starter"), imported); @@ -836,7 +843,7 @@ public void InvalidSampleScriptPreflightLeavesNoProjectCopy() root, serialization ) => WriteSamplePlugin(root, serialization, "public sealed class BrokenSample { this is invalid; }")); - AssetPath source = new(new AssetSourceId("tests.samples"), "~Starter"); + var source = new AssetPath(new AssetSourceId("tests.samples"), "~Starter"); using AssetSampleImportTransaction import = PrepareSample(fixture, source); import.BeginValidation(async ( sources, @@ -852,9 +859,9 @@ public void InvalidSampleScriptPreflightLeavesNoProjectCopy() throw new InvalidOperationException(FormatDiagnostics(candidate)); } }); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); Assert.Throws(() => import.Commit()); - new Inno.Core.Execution.RetirementBarrier("Test sample import").Wait(import.Rollback); + new RetirementBarrier("Test sample import").Wait(import.Rollback); Assert.False(Directory.Exists(Path.Combine(fixture.projectRoot, "Assets", "~Starter"))); Assert.False(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("~Starter"), out _)); } @@ -862,7 +869,7 @@ public void InvalidSampleScriptPreflightLeavesNoProjectCopy() [Fact] public void SampleImportPreservesEveryLeadingTildeAndRejectsDestinationCollisions() { - AssetPath source = new(new AssetSourceId("tests.samples"), "Samples/~~~Starter"); + var source = new AssetPath(new AssetSourceId("tests.samples"), "Samples/~~~Starter"); Assert.Equal("~~~Starter", AssetSample.GetImportName(source)); Assert.True(AssetSample.IsRuntimeExcluded(AssetPath.Project("~~~Starter/File.cs"), false)); Assert.False(AssetSample.Contains(AssetPath.Project("~~~Starter/File.cs"), false)); @@ -898,7 +905,7 @@ public void SampleValidationReturnsToOwnerWhileWorkIsPendingAndPublishesExactlyO Assert.Throws(() => fixture.assets.CreateDirectory(AssetPath.Project("Concurrent"))); Assert.Throws(() => fixture.host.modules.generations.EnsureReady("reload while importing")); completion.SetResult(); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); import.Commit(); Assert.Equal(1, notifications); Assert.Equal(revision + 1, fixture.assets.revision); @@ -919,13 +926,13 @@ public void SampleCancellationRetainsDependenciesUntilUncooperativeValidationDra _ ) => new ValueTask(completion.Task)); import.Cancel(); - Assert.Throws(() => import.Rollback()); - Assert.Throws(() => fixture.assets.Dispose()); + Assert.Throws(() => import.Rollback()); + Assert.Throws(() => fixture.assets.Dispose()); Assert.True(fixture.assets.isInitialized); Assert.Throws(() => fixture.host.modules.generations.EnsureReady("reload before drain")); completion.SetResult(); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); - new Inno.Core.Execution.RetirementBarrier("Test sample import").Wait(import.Rollback); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); + new RetirementBarrier("Test sample import").Wait(import.Rollback); Assert.False(fixture.assets.TryGetFileSystemEntry(import.target, out _)); Assert.False(File.Exists(Path.Combine(fixture.projectRoot, "Assets", "~Starter.imeta"))); Assert.Equal(0, notifications); @@ -943,9 +950,9 @@ public void SampleHistoryFinalizationFailureRollsBackWithoutPublication() _, _ ) => ValueTask.CompletedTask); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); Assert.Throws(() => import.Commit(_ => throw new IOException("History spill failed."))); - new Inno.Core.Execution.RetirementBarrier("Test sample import").Wait(import.Rollback); + new RetirementBarrier("Test sample import").Wait(import.Rollback); Assert.Equal(0, notifications); Assert.False(fixture.assets.TryGetFileSystemEntry(import.target, out _)); fixture.host.modules.generations.EnsureReady("continue after finalization failure"); @@ -967,11 +974,11 @@ public void SampleCopyCancellationLeavesNoProjectOrTransactionDirectory() import.Rollback(); return true; } - catch (Inno.Core.Execution.RetirementPendingException) + catch (RetirementPendingException) { return false; } - }, 15000) + }, 15_000) ); Assert.False(Directory.Exists(Path.Combine(fixture.projectRoot, "Assets", "~Starter"))); string transactions = Path.Combine(fixture.assets.libraryRoot, "AssetDatabase", "Transactions"); @@ -1000,14 +1007,14 @@ public void PendingAutomaticCompilationDefersUntilSampleRollback() import.Rollback(); return true; } - catch (Inno.Core.Execution.RetirementPendingException) + catch (RetirementPendingException) { return false; } - }, 15000) + }, 15_000) ); Assert.True(reload.TryCompilePending(out Task? compilation)); - Assert.True(SpinWait.SpinUntil(() => compilation!.IsCompleted, 15000)); + Assert.True(SpinWait.SpinUntil(() => compilation!.IsCompleted, 15_000)); Assert.True(compilation!.IsCompletedSuccessfully); Assert.True(reload.lastCompilation!.success); } @@ -1087,7 +1094,7 @@ out AssetFileEntry sample } }); runtime.Dispose(); - Assert.True(SpinWait.SpinUntil(() => shutdownObserver.IsCompleted, 15000)); + Assert.True(SpinWait.SpinUntil(() => shutdownObserver.IsCompleted, 15_000)); Assert.True(shutdownObserver.IsCompletedSuccessfully, shutdownObserver.Exception?.ToString()); } finally @@ -1102,11 +1109,11 @@ out AssetFileEntry sample runtime.Dispose(); return true; } - catch (Inno.Core.Execution.RetirementPendingException) + catch (RetirementPendingException) { return false; } - }, 15000) + }, 15_000) ); } @@ -1126,7 +1133,7 @@ public void SampleDirectoryMetadataRemapsNestedImportSettingsIdentities() { WriteSamplePlugin(root, serialization); string package = Path.Combine(root, "Plugins", "samples.iplugin"); - using var archive = ZipFile.Open(package, ZipArchiveMode.Update); + using ZipArchive archive = ZipFile.Open(package, ZipArchiveMode.Update); archive.GetEntry("Assets/~Starter.imeta")!.Delete(); WritePluginPackageEntry( archive, @@ -1158,7 +1165,7 @@ public void SampleDirectoryMetadataRemapsNestedImportSettingsIdentities() Assert.NotEqual(sourceId, settings.referenceId); return ValueTask.CompletedTask; }); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); import.Commit(); } @@ -1171,8 +1178,8 @@ public void SampleAssetPreimportRunsOnWorkerAndReceivesCancellation() ) => { WriteSamplePlugin(root, serialization); - using var package = ZipFile.Open(Path.Combine(root, "Plugins", "samples.iplugin"), ZipArchiveMode.Update); - WritePluginPackageEntry(package, "Assets/~Starter/Slow.samplebusy", System.Text.Encoding.UTF8.GetBytes("sample")); + using ZipArchive package = ZipFile.Open(Path.Combine(root, "Plugins", "samples.iplugin"), ZipArchiveMode.Update); + WritePluginPackageEntry(package, "Assets/~Starter/Slow.samplebusy", Encoding.UTF8.GetBytes("sample")); WritePluginPackageEntry( package, "Assets/~Starter/Slow.samplebusy.imeta", @@ -1198,7 +1205,7 @@ public void SampleAssetPreimportRunsOnWorkerAndReceivesCancellation() { Assert.False(import.Advance()); return control.started.IsSet; - }, 15000) + }, 15_000) ); Assert.NotEqual(Environment.CurrentManagedThreadId, control.workerThread); long revision = fixture.assets.revision; @@ -1215,7 +1222,7 @@ public void SampleAssetPreimportRunsOnWorkerAndReceivesCancellation() } finally { - new Inno.Core.Execution.RetirementBarrier("Test sample preimport").Wait(import.Dispose); + new RetirementBarrier("Test sample preimport").Wait(import.Dispose); ControlledSampleAssetImporter.current = null; } @@ -1256,7 +1263,7 @@ public void SampleCompilerReferencePreparationRunsOnWorker() finally { progress.release.Set(); - Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60000)); + Assert.True(SpinWait.SpinUntil(() => import.isValidationComplete, 60_000)); } import.Commit(); @@ -1274,7 +1281,11 @@ public void SampleCompilerReferencePreparationRunsOnWorker() [InlineData(true)] public void SampleIndexingDoesNotWaitForWatcherQuietPeriod(bool commit) { - using var fixture = new ScriptingFixture(WriteSamplePlugin, enableFileSystemWatcher: true, fileWatcherFlushDelayMs: 3000); + using var fixture = new ScriptingFixture( + WriteSamplePlugin, + enableFileSystemWatcher: true, + fileWatcherFlushDelayMs: 3000 + ); AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport( new AssetPath(new AssetSourceId("tests.samples"), "~Starter") ); @@ -1290,7 +1301,7 @@ public void SampleIndexingDoesNotWaitForWatcherQuietPeriod(bool commit) maximumAdvance = frame.Elapsed; } return ready; - }, 15000); + }, 15_000); Assert.True(indexed); Assert.True( maximumAdvance < TimeSpan.FromSeconds(2), @@ -1309,7 +1320,7 @@ public void SampleIndexingDoesNotWaitForWatcherQuietPeriod(bool commit) } else { - new Inno.Core.Execution.RetirementBarrier("Test canceled watched sample").Wait(import.Rollback); + new RetirementBarrier("Test canceled watched sample").Wait(import.Rollback); } fixture.assets.Update(); Assert.True(fixture.assets.TryGetFileSystemEntry(AssetPath.Project("External.txt"), out _)); @@ -1317,7 +1328,7 @@ public void SampleIndexingDoesNotWaitForWatcherQuietPeriod(bool commit) } finally { - new Inno.Core.Execution.RetirementBarrier("Test watched sample import").Wait(import.Dispose); + new RetirementBarrier("Test watched sample import").Wait(import.Dispose); } } @@ -1326,7 +1337,7 @@ private static AssetSampleImportTransaction PrepareSample( AssetPath source ) { AssetSampleImportTransaction import = fixture.assets.PrepareSampleImport(source); - Assert.True(SpinWait.SpinUntil(() => import.Advance(), 15000)); + Assert.True(SpinWait.SpinUntil(() => import.Advance(), 15_000)); return import; } @@ -1624,8 +1635,7 @@ public void NeutralSettingsCacheDoesNotPinRetiredScriptTypesWithoutAnExplicitReb Assert.False(previousType.IsAlive, "A neutral settings cache must not retain the old script type."); Assert.True(CaptureCachedSettingType(detachedSettings).IsAlive); void WriteSetting(int value) - { - fixture.Write("DetachedSetting.cs", $$""" + => fixture.Write("DetachedSetting.cs", $$""" using InnoEngine.Reflection; using InnoEngine.Serialization; using InnoEngine.Settings; @@ -1636,7 +1646,6 @@ public sealed class DetachedSetting : ISerializable [SerializableProperty] public int value { get; set; } = {{value}}; } """); - } } [MethodImpl(MethodImplOptions.NoInlining)] @@ -1978,7 +1987,7 @@ public void EditorQueuesLatestAutomaticChangeWithoutReplacingAcceptedTicketWhile runtime, () => scripting.state == EditorScriptCompilationState.Ready, () => $"{scripting.state}: {scripting.progress.status}; ticket={scripting.currentTicket?.state}", - timeoutMilliseconds: 120000 + timeoutMilliseconds: 120_000 ); ScriptCompilationResult initial = Assert.IsType(scripting.lastCompilation); IScriptCompilationTicket? accepted = scripting.currentTicket; @@ -2014,7 +2023,7 @@ public void EditorQueuesLatestAutomaticChangeWithoutReplacingAcceptedTicketWhile runtime, () => scripting.state == EditorScriptCompilationState.Ready && !ReferenceEquals(initial, scripting.lastCompilation), () => $"{scripting.state}: {scripting.progress.status}; ticket={scripting.currentTicket?.state}", - timeoutMilliseconds: 120000 + timeoutMilliseconds: 120_000 ); Assert.Equal(GenerationState.Ready, fixture.host.generations.state); Assert.Equal(3, ReadLatestVersion(fixture)); @@ -2052,7 +2061,7 @@ IEditorScriptCompilation scripting runtime, () => scripting.state is EditorScriptCompilationState.Ready or EditorScriptCompilationState.Failed, DescribeCompilation, - timeoutMilliseconds: 60000 + timeoutMilliseconds: 60_000 ); Assert.True(scripting.state == EditorScriptCompilationState.Ready, DescribeCompilation()); @@ -2069,7 +2078,7 @@ private static void PumpEditorUntil( Func completed, Func status, bool focused = true, - int timeoutMilliseconds = 15000 + int timeoutMilliseconds = 15_000 ) { long started = Environment.TickCount64; int frame = 0; @@ -2260,7 +2269,7 @@ public sealed class ProjectionRuntime : GameBehavior new PluginManifest { pluginId = "tests.projection", displayName = "Projection Plugin" }, new Dictionary { - ["Assets/ProjectionRuntime.cs"] = System.Text.Encoding.UTF8.GetBytes(c_source), + ["Assets/ProjectionRuntime.cs"] = Encoding.UTF8.GetBytes(c_source), ["Assets/ProjectionRuntime.cs.imeta"] = CreateScriptSourceMeta(serialization, Guid.NewGuid()) } ); @@ -2288,22 +2297,20 @@ private static void WriteUnavailableGenerationPlugin( string projectRoot, SerializationRegistry serialization, string source - ) { - WritePluginPackage( - projectRoot, - "unavailability.iplugin", - serialization, - new PluginManifest { pluginId = "tests.unavailability", displayName = "Unavailability Test Plugin" }, - new Dictionary - { - ["Assets/PluginBehavior.cs"] = System.Text.Encoding.UTF8.GetBytes(source), - ["Assets/PluginBehavior.cs.imeta"] = CreateScriptSourceMeta( - serialization, - Guid.Parse("37f9751f-a7de-43c7-94ac-c8e854762d49") - ) - } - ); - } + ) => WritePluginPackage( + projectRoot, + "unavailability.iplugin", + serialization, + new PluginManifest { pluginId = "tests.unavailability", displayName = "Unavailability Test Plugin" }, + new Dictionary + { + ["Assets/PluginBehavior.cs"] = Encoding.UTF8.GetBytes(source), + ["Assets/PluginBehavior.cs.imeta"] = CreateScriptSourceMeta( + serialization, + Guid.Parse("37f9751f-a7de-43c7-94ac-c8e854762d49") + ) + } + ); private static void WriteSamplePlugin( string projectRoot, @@ -2319,31 +2326,29 @@ private static void WriteSamplePlugin( string projectRoot, SerializationRegistry serialization, string source - ) { - WritePluginPackage( - projectRoot, - "samples.iplugin", - serialization, - new PluginManifest { pluginId = "tests.samples", displayName = "Sample Test Plugin" }, - new Dictionary - { - ["Assets/"] = [], - ["Assets/~Starter/"] = [], - ["Assets/~Starter.imeta"] = serialization.Serialize( - new ScriptingAssetSourceMeta - { - persistentId = Guid.Parse("7726b1d2-9aee-4d2c-a865-2fd53155095f"), - sourceKind = (int)AssetSourceKind.Directory - } - ), - ["Assets/~Starter/StarterBehavior.cs"] = System.Text.Encoding.UTF8.GetBytes(source), - ["Assets/~Starter/StarterBehavior.cs.imeta"] = CreateScriptSourceMeta( - serialization, - Guid.Parse("75f6a70b-93b2-47f0-8747-cc359474b7a3") - ) - } - ); - } + ) => WritePluginPackage( + projectRoot, + "samples.iplugin", + serialization, + new PluginManifest { pluginId = "tests.samples", displayName = "Sample Test Plugin" }, + new Dictionary + { + ["Assets/"] = [], + ["Assets/~Starter/"] = [], + ["Assets/~Starter.imeta"] = serialization.Serialize( + new ScriptingAssetSourceMeta + { + persistentId = Guid.Parse("7726b1d2-9aee-4d2c-a865-2fd53155095f"), + sourceKind = (int)AssetSourceKind.Directory + } + ), + ["Assets/~Starter/StarterBehavior.cs"] = Encoding.UTF8.GetBytes(source), + ["Assets/~Starter/StarterBehavior.cs.imeta"] = CreateScriptSourceMeta( + serialization, + Guid.Parse("75f6a70b-93b2-47f0-8747-cc359474b7a3") + ) + } + ); private static byte[] CreateScriptSourceMeta( SerializationRegistry serialization, @@ -2592,7 +2597,7 @@ internal ScriptingFixture( bool enableFileSystemWatcher = false, int fileWatcherFlushDelayMs = 100 ) { - projectRoot = Path.Combine(Path.GetTempPath(), "InnoScriptingPipelineTests", Guid.NewGuid().ToString("N")); + this.projectRoot = Path.Combine(Path.GetTempPath(), "InnoScriptingPipelineTests", Guid.NewGuid().ToString("N")); string assetRoot = Path.Combine(projectRoot, "Assets"); string pluginRoot = Path.Combine(projectRoot, "Plugins"); string libraryRoot = Path.Combine(projectRoot, "Library"); @@ -2600,7 +2605,7 @@ internal ScriptingFixture( Directory.CreateDirectory(pluginRoot); Directory.CreateDirectory(libraryRoot); m_identityScope = m_identities.EnterScope(); - host = new EngineHostBuilder().UseMetadataSources( + this.host = new EngineHostBuilder().UseMetadataSources( new DotNetAssemblyCatalogSource(typeof(ScriptingPipelineTests).Assembly), new ReflectionTypeCatalogSource(), new ReflectionSerializationMetadataSource() @@ -2610,7 +2615,7 @@ internal ScriptingFixture( var pluginSources = new PluginSourceService(host.serialization, pluginRoot, libraryRoot); PluginScanResult scan = pluginSources.Scan(); AssetPipelineOptions options = AssetPipelineOptions.Create(assetRoot, libraryRoot); - assets = new AssetPipeline( + this.assets = new AssetPipeline( host.modules, host.types, host.serialization, @@ -2633,14 +2638,14 @@ options with ); m_plugins = new PluginEnvironment(assets, m_settings, host.serialization, pluginRoot, libraryRoot, scan, host.modules.generations); string dotnetHost = Path.Combine( - Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" ); - compiler = new ScriptCompiler( + this.compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = projectRoot, - compilationEnvironment = new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, projectRoot) + compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) }, assets, m_plugins @@ -2789,7 +2794,7 @@ internal EditorInteractionRuntime CreateEditorRuntime(EditorReloadCoordinator? r reloads ??= new EditorReloadCoordinator(); RuntimeSession editorSession = CreateEditorSession(); return new EditorInteractionRuntime( - new EditorContext(projectRoot, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), host.types, host.logs, [ diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs index 970442b9e..04f7ba463 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Performance.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Numerics; using System.Reflection; +using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text.Json; using Xunit; @@ -12,6 +14,7 @@ using Inno.Assets.Pipeline; using Inno.Core.Graphs; using Inno.Core.Serialization; +using Inno.Editor.Graph; using Inno.Native.ImGui; using Inno.Rendering.Shaders; @@ -74,7 +77,7 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() } byte[] original = SHA256.HashData(File.ReadAllBytes(Path.Combine(source, name))); SelectAndDraw(entry); - var controller = Controller(entry); + GraphDocumentController controller = Controller(entry); Assert.Equal(2_000, controller.document.nodes.Count); Assert.True(controller.document.edges.Count >= 900); for (int warmup = 0; warmup < 5; warmup++) @@ -82,7 +85,7 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() DrawPerformanceCanvas(); } string? requested = Environment.GetEnvironmentVariable("INNO_UI_PERFORMANCE_REPETITIONS"); - int repetitions = requested is null ? 5 : int.Parse(requested, System.Globalization.CultureInfo.InvariantCulture); + int repetitions = requested is null ? 5 : int.Parse(requested, CultureInfo.InvariantCulture); Assert.InRange(repetitions, 1, 5); using Process process = Process.GetCurrentProcess(); var samples = new List(); @@ -135,7 +138,7 @@ public unsafe void TwoThousandShaderNodesProduceRepeatableFrameMeasurements() ?.Configuration ?? throw new InvalidOperationException("The benchmark assembly has no SDK configuration metadata."), samples, - framework = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription, + framework = RuntimeInformation.FrameworkDescription, viewport = "1200x800", warmupFrames = 5, measuredFramesPerRepetition = 10, diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs index 7835ba048..21c1148ac 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.Visual.cs @@ -6,9 +6,9 @@ public sealed partial class ShaderEditorWorkflowTests { public static IEnumerable CanvasMetrics() { - foreach (float zoom in new[] { 0.75f, 0.85f, 0.90f, 1f, 1.10f, 1.25f, 1.50f }) + foreach (float zoom in new[] { 0.75f, 0.85f, 0.9f, 1f, 1.1f, 1.25f, 1.5f }) { - foreach (float density in new[] { 1f, 1.25f, 1.50f, 2f }) + foreach (float density in new[] { 1f, 1.25f, 1.5f, 2f }) { foreach ((float width, float height) in new[] { (1280f, 720f), (1920f, 1080f) }) { diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs index 097022cf7..b2f0cab95 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ShaderEditorWorkflowTests.cs @@ -40,6 +40,8 @@ using Inno.Rendering.Shaders; using EditorUI = Inno.Editor.ImGui.EditorUiSession; +using EngineColor = Inno.Core.Mathematics.Color; +using EngineVector4 = Inno.Core.Mathematics.Vector4; using ImGuiApi = Inno.Native.ImGui.ImGui; using NativeVector2 = Inno.Native.ImGui.ImVec2C; @@ -128,7 +130,7 @@ public void ParameterPresentationRoundTripsWithoutChangingTheRuntimeDefinitionOr ShaderGraphArtifact.Encode(graph, new Dictionary(), m_serialization), m_serialization ); - ShaderPropertyId id = new("stable.tint"); + var id = new ShaderPropertyId("stable.tint"); Assert.True(ShaderParameterPresentation.Read(graph, id, m_serialization, context).visible); ShaderParameterPresentation.Write( graph, @@ -166,7 +168,7 @@ public void ParameterPresentationRejectsInvalidBoundsBeforeMutatingTheGraph() GraphDocument graph = m_source.Read(Create("Range.ishader").assetPath).document; byte[] before = GraphDocumentCodec.Encode(graph, m_serialization); SerializationContext context = AssetSerializationContext.Create(m_assets); - foreach (var range in new[] + foreach ((double, double) range in new[] { (double.NaN, 1d), (0d, double.PositiveInfinity), @@ -236,7 +238,7 @@ public void SourceSettingsUndoRedoRestoresValidAndInvalidImportStates() AssetPath path = CreateFunction(); var edits = new AssetImportSettingsEdits(m_assets, m_serialization, m_types, m_runtime.interactions); AssetImportSettingsSnapshot before = m_assets.GetImportSettings(path); - var settings = Assert.IsType(before.value); + ShaderSourceImportSettings settings = Assert.IsType(before.value); settings.exports = ["MissingFunction"]; Assert.False(edits.Apply(path, settings, before.fingerprint)); Assert.Equal( @@ -260,11 +262,11 @@ public void SourceSettingsUndoRefusesToOverwriteAnExternalSidecarEdit() AssetPath path = CreateFunction(); var edits = new AssetImportSettingsEdits(m_assets, m_serialization, m_types, m_runtime.interactions); AssetImportSettingsSnapshot before = m_assets.GetImportSettings(path); - var settings = Assert.IsType(before.value); + ShaderSourceImportSettings settings = Assert.IsType(before.value); settings.exports = ["MissingFunction"]; _ = edits.Apply(path, settings, before.fingerprint); AssetImportSettingsSnapshot current = m_assets.GetImportSettings(path); - var external = Assert.IsType(current.value); + ShaderSourceImportSettings external = Assert.IsType(current.value); external.exports = ["ExternalFunction"]; _ = m_assets.SaveImportSettings(path, external, current.fingerprint); Assert.False(m_runtime.interactions.history.Undo().succeeded); @@ -402,7 +404,8 @@ public void SeparateMovesAndUndoRedoRemainDraftsUntilExplicitSave() [Fact] public void SwitchingSelectionKeepsAnInvalidDraftAndExplicitCloseSavePersistsIt() { - AssetFileEntry first = Create("Incomplete.ishader"), second = Create("Other.ishader"); + AssetFileEntry first = Create("Incomplete.ishader"); + AssetFileEntry second = Create("Other.ishader"); SelectAndDraw(first); GraphNodeId missing = Controller(first).AddNode("tests.uninstalled.node", new(32, 64)); Tick(); @@ -477,7 +480,13 @@ public void FormatPlacesOutputsOnTheRightWithoutChangingShaderSemanticsAndIsUndo .Where( node => ( node.id != output.id - && ShaderGraphDocument.Read(node, "stage", "", m_serialization, AssetSerializationContext.Create(m_assets)) == output.id.value + && ShaderGraphDocument.Read( + node, + "stage", + string.Empty, + m_serialization, + AssetSerializationContext.Create(m_assets) + ) == output.id.value ) ) .Max(static node => node.position.x) @@ -605,7 +614,7 @@ public void DeleteKeysRemoveTheSelectedComputeStageAndItsDeclarationsAsOneUndo(K { AssetFileEntry entry = Create("Delete.ishader"); SelectAndDraw(entry); - var interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); + EditorInteraction interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); Assert.True(interaction.Execute("shader/create-output", "Compute")); Assert.False(interaction.Execute("shader/create-output", "Compute")); GraphDocumentController controller = Controller(entry); @@ -673,7 +682,7 @@ public void CutAndPasteStageKeepsItsContentsAndDoesNotCreateDuplicatePassDeclara { AssetFileEntry entry = Create("Clipboard.ishader"); SelectAndDraw(entry); - var interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); + EditorInteraction interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); Assert.True(interaction.Execute("shader/create-output", "Compute")); GraphDocumentController controller = Controller(entry); GraphNodeId stage = controller.document.nodes.Last().id; @@ -704,7 +713,7 @@ public void CutAndPasteStageKeepsItsContentsAndDoesNotCreateDuplicatePassDeclara ShaderGraphDocument.Read( node, "stage", - "", + string.Empty, m_serialization, AssetSerializationContext.Create(m_assets) ) == pasted.id.value @@ -738,7 +747,7 @@ public void SourceMenuUsesAssetIdentityAndDisconnectCommitsOneUndoWithoutSaving( AssetPath source = CreateFunction("Evaluate", "Secondary"); AssetFileEntry entry = Create("Source.ishader"); SelectAndDraw(entry); - var interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); + EditorInteraction interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); EditorMenuItem create = interaction.BuildMenu().items.Single(item => item.label == "Create"); EditorMenuItem functions = create.children.Single(item => item.label == "Functions"); EditorMenuItem general = Assert.Single(functions.children); @@ -756,7 +765,7 @@ public void SourceMenuUsesAssetIdentityAndDisconnectCommitsOneUndoWithoutSaving( ); Assert.Equal( "Evaluate", - ShaderGraphDocument.Read(node, "function", "", m_serialization, AssetSerializationContext.Create(m_assets)) + ShaderGraphDocument.Read(node, "function", string.Empty, m_serialization, AssetSerializationContext.Create(m_assets)) ); Tick(); using var nodes = new ShaderNodeCompilerRegistry(m_types); @@ -913,7 +922,7 @@ public void SavingAppliesTheGraphWithoutDependingOnFileWatcherAndUndoStaysDraftO controller.ReplaceDocument(graph, "Rename Shader"); Tick(); Assert.Equal(before, asset.contentVersion); - var interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); + EditorInteraction interaction = m_runtime.interactions.For("panel/rendering.shader-editor", entry); interaction.Focus(); HotKeyGesture save = HotKeyGesture.Primary(KeyCode.S, new EditorKeyboardPolicy(KeyModifier.Control, "Super")); m_runtime.HandleKeyPressed(new KeyPressedEvent(0, save.key, save.modifiers)); @@ -999,10 +1008,10 @@ public void DraftCompilationNeverReplacesTheCanonicalArtifactAndLayoutChangesDoN Assert.NotNull(canonical); GraphDocument draft = m_source.Read(entry.assetPath).document; - var context = AssetSerializationContext.Create(m_assets); + SerializationContext context = AssetSerializationContext.Create(m_assets); ShaderDefinition definition = ShaderGraphDocument.ReadDefinition(draft, m_serialization, context); ShaderPropertyDefinition property = definition.properties[0]; - property.defaultValue = MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.23f, 1, 1, 1)); + property.defaultValue = MaterialValue.FromColor(new EngineColor(0.23f, 1, 1, 1)); definition.properties[0] = property; draft.SetMetadata( ShaderGraphDocument.definitionKey, @@ -1021,7 +1030,7 @@ EditorShaderDraftCompilationSnapshot Poll(ulong revision) return result; } - var preview = Poll(1); + EditorShaderDraftCompilationSnapshot preview = Poll(1); Assert.Equal(EditorShaderCompilationState.Succeeded, preview.state); Assert.NotNull(preview.artifact); Assert.NotEqual(canonical!.contentHash, preview.artifact!.contentHash); @@ -1029,11 +1038,11 @@ EditorShaderDraftCompilationSnapshot Poll(ulong revision) Assert.Same(preview.artifact, Poll(2).artifact); GraphNodeRecord output = draft.nodes.First(value => value.definitionId == ShaderGraphDocument.outputDefinitionId); draft.RemoveNode(output.id); - var failed = Poll(3); + EditorShaderDraftCompilationSnapshot failed = Poll(3); Assert.Equal(EditorShaderCompilationState.Failed, failed.state); Assert.True(failed.usingLastGood); Assert.Same(preview.artifact, failed.artifact); - _ = m_artifacts.GetShaderArtifact(shader, RenderShaderVariant.empty, capabilities, out var unchanged); + _ = m_artifacts.GetShaderArtifact(shader, RenderShaderVariant.empty, capabilities, out RenderShaderArtifact? unchanged); Assert.Same(canonical, unchanged); Assert.Equal(disk, File.ReadAllBytes(Path.Combine(m_root, "Assets", entry.assetPath.localPath))); compilation.ReleaseDraft(previewId); @@ -1054,7 +1063,7 @@ private EditorInteractionRuntime CreateRuntime() false ); var runtime = new EditorInteractionRuntime( - new EditorContext(m_root, new EditorKeyboardPolicy(Inno.Core.Input.KeyModifier.Control, "Super")), + new EditorContext(m_root, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), m_types, m_logs, [ @@ -1086,7 +1095,7 @@ void Set( string? mergeKey = null ) { MaterialAsset candidate = documents.Read(id); - candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(value, 1, 1, 1))); + candidate.Set(property, MaterialValue.FromColor(new EngineColor(value, 1, 1, 1))); documents.Replace(id, candidate, mergeKey); } @@ -1134,7 +1143,7 @@ public void CancelledMaterialGestureRestoresDraftDirtyStateAndLeavesNoUndoEntry( Assert.False(m_runtime.interactions.history.canUndo); using var gesture = new EditorEditGesture(m_runtime.interactions.history, "Cancelled Material Edit"); MaterialAsset candidate = documents.Read(id); - candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.7f, 1, 1, 1))); + candidate.Set(property, MaterialValue.FromColor(new EngineColor(0.7f, 1, 1, 1))); documents.Replace(id, candidate, gesture.mergeKey); Assert.True(Assert.Single(m_runtime.interactions.documents.documents).isDirty); Assert.True(gesture.Cancel().succeeded); @@ -1150,12 +1159,12 @@ public void MaterialSaveConflictKeepsDiskAndRecoveredDraftDistinct() MaterialDocuments documents = Assert.IsType(m_sink.materials); Guid id = documents.Open(path); MaterialAsset candidate = documents.Read(id); - candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.3f, 1, 1, 1))); + candidate.Set(property, MaterialValue.FromColor(new EngineColor(0.3f, 1, 1, 1))); documents.Replace(id, candidate); AssetSourceStore sources = m_assets.CreateSourceStore(); AssetSourceSnapshot before = sources.Read(path); MaterialAsset external = sources.Decode(before.bytes); - external.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.9f, 1, 1, 1))); + external.Set(property, MaterialValue.FromColor(new EngineColor(0.9f, 1, 1, 1))); byte[] externalBytes = sources.Encode(external); sources.Save(path, externalBytes, before.contentHash); EditorDocumentContext context = Assert.Single(m_runtime.interactions.documents.documents); @@ -1181,7 +1190,7 @@ void External(float value) AssetSourceStore sources = m_assets.CreateSourceStore(); AssetSourceSnapshot captured = sources.Read(path); MaterialAsset material = sources.Decode(captured.bytes); - material.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(value, 1, 1, 1))); + material.Set(property, MaterialValue.FromColor(new EngineColor(value, 1, 1, 1))); sources.Save(path, sources.Encode(material), captured.contentHash); Assert.True(m_assets.Import(path)); Tick(); @@ -1192,7 +1201,7 @@ void External(float value) Assert.Equal(0.2f, inherited.vector.x); Assert.False(Assert.Single(m_runtime.interactions.documents.documents).isDirty); MaterialAsset candidate = documents.Read(id); - candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(0.5f, 1, 1, 1))); + candidate.Set(property, MaterialValue.FromColor(new EngineColor(0.5f, 1, 1, 1))); documents.Replace(id, candidate); External(0.8f); Assert.True(documents.Read(id).TryGet(property, out MaterialValue draft)); @@ -1210,7 +1219,8 @@ public void MultipleMaterialSamplesCommitAsOneIndependentUndoWithoutPublishing() sources.Save(secondPath, sources.Read(firstPath).bytes, null); Assert.True(m_assets.Import(secondPath)); MaterialDocuments documents = Assert.IsType(m_sink.materials); - Guid first = documents.Open(firstPath), second = documents.Open(secondPath); + Guid first = documents.Open(firstPath); + Guid second = documents.Open(secondPath); byte[] original = sources.Read(firstPath).bytes; void Sample( float value, @@ -1225,7 +1235,7 @@ void Sample( ) { MaterialAsset candidate = documents.Read(id); - candidate.Set(property, MaterialValue.FromColor(new Inno.Core.Mathematics.Color(value, 1, 1, 1))); + candidate.Set(property, MaterialValue.FromColor(new EngineColor(value, 1, 1, 1))); candidates.Add(id, candidate); } @@ -1286,11 +1296,11 @@ void Sample( [Fact] public void CommonMaterialEditingPreservesUntouchedMixedComponentsAndTextureReferences() { - var first = MaterialValue.FromVector(new Inno.Core.Mathematics.Vector4(1, 2, 3, 4)); - var edited = MaterialValue.FromVector(new Inno.Core.Mathematics.Vector4(8, 2, 3, 4)); - var other = MaterialValue.FromVector(new Inno.Core.Mathematics.Vector4(5, 6, 7, 9)); + MaterialValue first = MaterialValue.FromVector(new EngineVector4(1, 2, 3, 4)); + MaterialValue edited = MaterialValue.FromVector(new EngineVector4(8, 2, 3, 4)); + MaterialValue other = MaterialValue.FromVector(new EngineVector4(5, 6, 7, 9)); MaterialValue result = ShaderPropertyInspector.ApplyEdit(ShaderPropertyType.Vector4, first, edited, other); - Assert.Equal(new Inno.Core.Mathematics.Vector4(8, 6, 7, 9), result.vector); + Assert.Equal(new EngineVector4(8, 6, 7, 9), result.vector); var firstTexture = new TextureAsset(1, 1, TextureColorSpace.Linear, "first"); var secondTexture = new TextureAsset(1, 1, TextureColorSpace.Linear, "second"); first = MaterialValue.FromTexture(firstTexture); @@ -1362,7 +1372,7 @@ WorkflowPipelineSettings Read(RenderPipelineAsset pipeline) [Fact] public void PipelineMissingSettingsKeepOpaqueBytesThroughHistoryAndRecovery() { - var unknown = new SerializedRenderExtensionState(Guid.NewGuid(), new byte[] { 19, 42, 7 }); + var unknown = new SerializedRenderExtensionState(Guid.NewGuid(), [19, 42, 7]); var source = new RenderPipelineAsset { pipelineTypeId = "tests.missing-pipeline", diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs index a0644572f..3b660439b 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs @@ -13,8 +13,10 @@ using Xunit; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Build.Toolchains; using Inno.Plugins; +using Inno.Scene; using Inno.Scripting.Compiler; namespace Inno.Scripting.Compiler.Tests; @@ -318,7 +320,7 @@ public void FrameworkContentChangesSelectNewArtifacts() Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" ); - ScriptCompilationInputs selected = new Inno.Build.SdkScriptCompilationEnvironment(host, fixture.projectRoot).Capture(); + ScriptCompilationInputs selected = new SdkScriptCompilationEnvironment(host, fixture.projectRoot).Capture(); string destination = Path.Combine(fixture.projectRoot, "Framework"); Directory.CreateDirectory(destination); foreach (string path in selected.frameworkReferences) @@ -334,7 +336,7 @@ public void FrameworkContentChangesSelectNewArtifacts() Assert.True(first.success, string.Join(Environment.NewLine, first.diagnostics)); string referenceRoot = Path.Combine(fixture.projectRoot, "Library", "ScriptApi", "Runtime"); string[] references = Directory.GetDirectories(referenceRoot); - using (FileStream changed = new(Path.Combine(destination, "System.Runtime.dll"), FileMode.Append)) + using (var changed = new FileStream(Path.Combine(destination, "System.Runtime.dll"), FileMode.Append)) { changed.WriteByte(0); } @@ -352,7 +354,7 @@ public void FrameworkContentChangesSelectNewArtifacts() public void SourceDocumentationContentSelectsANewReferenceGeneration() { // This suite is serial. Only its own deployed XML sidecar is changed, and it is restored on failure. - string source = Path.ChangeExtension(typeof(Inno.Scene.SceneManager).Assembly.Location, ".xml"); + string source = Path.ChangeExtension(typeof(SceneManager).Assembly.Location, ".xml"); Assert.StartsWith(Path.GetFullPath(AppContext.BaseDirectory), Path.GetFullPath(source), StringComparison.OrdinalIgnoreCase); byte[] original = File.ReadAllBytes(source); DateTime timestamp = File.GetLastWriteTimeUtc(source); diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs index 18f789af8..34b372938 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/CompilerFixture.cs @@ -1,9 +1,11 @@ using System; using System.IO; +using System.Runtime.InteropServices; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; +using Inno.Build; using Inno.Core.IO; using Inno.Core.Identity; using Inno.Core.Serialization; @@ -28,7 +30,7 @@ internal CompilerFixture( Action? configure = null, IScriptCompilationEnvironmentProvider? compilationEnvironment = null ) { - projectRoot = Path.Combine(Path.GetTempPath(), "InnoCompilerTests", Guid.NewGuid().ToString("N")); + this.projectRoot = Path.Combine(Path.GetTempPath(), "InnoCompilerTests", Guid.NewGuid().ToString("N")); string assetsRoot = Path.Combine(projectRoot, "Assets"); string pluginsRoot = Path.Combine(projectRoot, "Plugins"); string libraryRoot = Path.Combine(projectRoot, "Library"); @@ -80,14 +82,14 @@ options with m_host.modules.generations ); string dotnetHost = Path.Combine( - Path.GetFullPath("../../..", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()), + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" ); - compiler = new ScriptCompiler( + this.compiler = new ScriptCompiler( new ScriptCompilerOptions { projectRootDirectory = projectRoot, - compilationEnvironment = compilationEnvironment ?? new Inno.Build.SdkScriptCompilationEnvironment(dotnetHost, projectRoot) + compilationEnvironment = compilationEnvironment ?? new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) }, m_assets, m_plugins @@ -98,7 +100,7 @@ options with internal ScriptCompiler compiler { get; } - /// + /// public void Dispose() { m_plugins.Dispose(); diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs index 475665953..2cc9ac68d 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs @@ -18,7 +18,9 @@ public sealed class ScriptCachePublicationTests /// /// Publishes a complete generation after a temporary filesystem reader releases its staging borrow. /// - /// The completed public compiler and artifact-equivalence checks. + /// + /// The completed public compiler and artifact-equivalence checks. + /// [WindowsDirectorySharingFact] public async Task ReusedAssembliesPublishAfterATemporaryStagingReaderReleasesThem() { @@ -87,7 +89,9 @@ public async Task ReusedAssembliesPublishAfterATemporaryStagingReaderReleasesThe /// /// Cancels a blocked publication without changing another completed generation. /// - /// The completed failure, previous-generation and explicit retry checks. + /// + /// The completed failure, previous-generation and explicit retry checks. + /// [WindowsDirectorySharingFact] public Task CanceledPublicationPreservesThePreviousGenerationAndAllowsAnotherRequest() => Task.Run(() => VerifyRejectedPublication(cancel: true)); @@ -95,7 +99,9 @@ public Task CanceledPublicationPreservesThePreviousGenerationAndAllowsAnotherReq /// /// Reports a persistent filesystem block without publishing incomplete or replacing previous artifacts. /// - /// The completed failure, previous-generation and explicit retry checks. + /// + /// The completed failure, previous-generation and explicit retry checks. + /// [WindowsDirectorySharingFact] public Task BlockedPublicationPreservesThePreviousGenerationAndAllowsAnotherRequest() => Task.Run(() => VerifyRejectedPublication(cancel: false)); @@ -103,7 +109,9 @@ public Task BlockedPublicationPreservesThePreviousGenerationAndAllowsAnotherRequ /// /// Preserves a rejected cache tree until its reader releases ownership and an explicit repair commits. /// - /// The completed replacement failure, byte-preservation and repair checks. + /// + /// The completed replacement failure, byte-preservation and repair checks. + /// [WindowsDirectorySharingFact] public Task BlockedReplacementPreservesTheEntireExistingTreeAndAllowsRepair() => Task.Run(VerifyRejectedReplacement); @@ -250,7 +258,7 @@ string stage m_stage = stage; } - /// + /// public void Report(ScriptCompilationProgress value) { lock (m_sync) @@ -276,7 +284,7 @@ public void Report(ScriptCompilationProgress value) } } - /// + /// public void Dispose() { lock (m_sync) @@ -292,12 +300,14 @@ public void Dispose() private sealed class WindowsDirectorySharingFactAttribute : FactAttribute { - /// Marks the Windows directory-sharing fixture as unexecuted on other hosts. + /// + /// Marks the Windows directory-sharing fixture as unexecuted on other hosts. + /// public WindowsDirectorySharingFactAttribute() { if (!OperatingSystem.IsWindows()) { - Skip = "This fixture requires Windows directory rename sharing semantics."; + this.Skip = "This fixture requires Windows directory rename sharing semantics."; } } } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs index f66a9aab3..7b0bf2195 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/AgentDocumentTests.cs @@ -37,7 +37,7 @@ public void AgentLinksUseParsedHeadingsReferencesAndExplicitAnchorsWithoutReadin File.WriteAllText(Path.Combine(m_root, ".agents/rulebook/README.md"), "# Hello *World*\n\n\n"); Assert.Equal(0, ArchitectureCommandFixture.Run(m_root, "--agent-documents-only").exitCode); File.AppendAllText(Path.Combine(m_root, "AGENTS.md"), "\n[Broken](.agents/rulebook/README.md#absent)\n"); - var rejected = ArchitectureCommandFixture.Run(m_root, "--agent-documents-only"); + (int exitCode, string output) rejected = ArchitectureCommandFixture.Run(m_root, "--agent-documents-only"); Assert.Equal(1, rejected.exitCode); Assert.Contains("missing anchor", rejected.output); File.AppendAllText(Path.Combine(m_root, "AGENTS.md"), "\n[Missing](absent.md)\n"); @@ -51,7 +51,7 @@ public void SkillsAreListedInTheRootInstructions() Directory.CreateDirectory(skill); File.WriteAllText(Path.Combine(skill, "SKILL.md"), "---\nname: example\ndescription: Example workflow.\n---\n\nSteps.\n"); File.WriteAllText(Path.Combine(m_root, "AGENTS.md"), "# Entry\n"); - var rejected = ArchitectureCommandFixture.Run(m_root, "--agent-documents-only"); + (int exitCode, string output) rejected = ArchitectureCommandFixture.Run(m_root, "--agent-documents-only"); Assert.Equal(1, rejected.exitCode); Assert.Contains("Skill is not listed in AGENTS.md: example", rejected.output); File.AppendAllText(Path.Combine(m_root, "AGENTS.md"), "\n- [example](.agents/skills/example/SKILL.md): example workflow.\n"); diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs index 4ccdc2d1f..a9a91abe9 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs @@ -168,15 +168,13 @@ await DocumentationReferences.ValidateApiAsync([ Assert.Contains("public/protected API exposes Inno.Core.Contract", rejected, StringComparison.Ordinal); async Task Build(string[] properties) - { - await ToolchainEnvironment.RunAsync( + => await ToolchainEnvironment.RunAsync( host, ["build", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet", .. properties], root, cancellation.Token, DotNetSdkEnvironment.Create(host) ); - } } finally { diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs index b99605b63..cb938a626 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureSymbolTests.cs @@ -5,6 +5,7 @@ using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Emit; using Xunit; namespace Inno.Tooling.Architecture.Tests; @@ -107,17 +108,17 @@ public void InheritedDocumentationRequiresACompleteImplementedContract( bool accepted ) { using var fixture = new SymbolFixture(); - string summary = scenario == "missing-summary" ? "" : """ + string summary = scenario == "missing-summary" ? string.Empty : """ /// /// Combines two values using the implementation's operation. /// """; - string right = scenario == "missing-parameter" ? "" : """ + string right = scenario == "missing-parameter" ? string.Empty : """ /// /// The second value supplied to the operation. /// """; - string returns = scenario == "missing-returns" ? "" : """ + string returns = scenario == "missing-returns" ? string.Empty : """ /// /// The combined value produced by the operation. /// @@ -144,7 +145,7 @@ bool accepted { source = "namespace Inno.Editor.Probe; public interface IContract {\n" + contract + "int Combine(int left, int right); }\npublic class Probe" - + (scenario == "standalone" ? "" : " : IContract") + " {\n" + + (scenario == "standalone" ? string.Empty : " : IContract") + " {\n" + (scenario == "wrong-cref" ? "/// \n" : "/// \n") + "public int Combine(int left, int right) => left + right; }"; } @@ -476,7 +477,7 @@ params string[] dependencies references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true) ); - var result = compilation.Emit(output, xmlDocumentationPath: Path.ChangeExtension(output, ".xml")); + EmitResult result = compilation.Emit(output, xmlDocumentationPath: Path.ChangeExtension(output, ".xml")); Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics)); return output; } diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs index 5ef15f34b..486c2fad6 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationExampleTests.cs @@ -104,7 +104,7 @@ public async Task ExplicitReferencesCompileIndependentGroupsAndMissingScriptCont Assert.Equal("inno-documentation-examples/1", report.RootElement.GetProperty("schema").GetString()); Assert.Matches("^[a-f0-9]{64}$", report.RootElement.GetProperty("validatorIdentity").GetString()!); Assert.Matches("^[a-f0-9]{64}$", report.RootElement.GetProperty("compilerIdentity").GetString()!); - var results = report.RootElement.GetProperty("results") + Dictionary results = report.RootElement.GetProperty("results") .EnumerateArray() .ToDictionary(static group => group.GetProperty("page").GetString()!); Assert.Equal("Passed", results["working"].GetProperty("status").GetString()); @@ -225,7 +225,12 @@ public async Task HostExamplesRejectUnreferencedAssembliesAndRespectMarkdownFenc EmitReference("Foreign", "public static class Foreign { public static int Read() => 7; }"), Path.Combine(directory, "Foreign.dll") ); - var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + var start = new ProcessStartInfo(host) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; foreach (string argument in new[] { "restore", @@ -263,7 +268,7 @@ public async Task HostExamplesRejectUnreferencedAssembliesAndRespectMarkdownFenc string output = Path.Combine(m_root, "fences.json"); Assert.Equal(1, await DocumentationExamples.ExecuteAsync(Arguments(index.snapshot, output))); using JsonDocument report = JsonDocument.Parse(File.ReadAllBytes(output)); - var results = report.RootElement + Dictionary results = report.RootElement .GetProperty("results") .EnumerateArray() .ToDictionary(static item => item.GetProperty("page").GetString()!); @@ -281,7 +286,12 @@ public async Task HostExamplesRejectUnreferencedAssembliesAndRespectMarkdownFenc [Fact] public async Task LogicalExamplesRetainBothScriptSurfacesAndNeverBorrowHostImplementation() { - var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + var start = new ProcessStartInfo(host) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; foreach (string argument in new[] { "restore", @@ -393,7 +403,12 @@ public static class EditorProbe { public static int Inspect() => 1; } public sealed class Owned { private Owned() { } } } """); - var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + var start = new ProcessStartInfo(host) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; foreach (string argument in new[] { "restore", @@ -481,7 +496,7 @@ public sealed class Owned { private Owned() { } } Assert.Single(captured.RootElement.GetProperty("projectionIdentities").EnumerateObject()); JsonElement project = captured.RootElement.GetProperty("projects")[0]; Assert.Equal("Inno.Probe", project.GetProperty("name").GetString()); - var symbols = project + Dictionary symbols = project .GetProperty("symbols") .EnumerateArray() .ToDictionary(static symbol => symbol.GetProperty("id").GetString()!); @@ -664,7 +679,7 @@ string sourceText string output = Path.Combine(m_root, name + ".dll"); string[] references = File.ReadAllLines(Path.Combine(AppContext.BaseDirectory, "DocumentationFrameworkReferences.txt")); Assert.NotEmpty(references); - var compilation = CSharpCompilation.Create( + CSharpCompilation compilation = CSharpCompilation.Create( name, [CSharpSyntaxTree.ParseText(sourceText)], references.Select(static path => MetadataReference.CreateFromFile(path)), @@ -686,8 +701,8 @@ private void Page( ) => Write( "documentation/content/en/" + id + ".md", "---\nuid: " + id + "\nkind: tutorial\n" - + (mode is null ? "" : "exampleMode: " + mode + "\nexampleProjects: [Inno.Probe]\n") - + "---\n# " + id + "\n\nExample contract.\n" + (code is null ? "" : "\n```csharp\n" + code + "\n```\n") + + (mode is null ? string.Empty : "exampleMode: " + mode + "\nexampleProjects: [Inno.Probe]\n") + + "---\n# " + id + "\n\nExample contract.\n" + (code is null ? string.Empty : "\n```csharp\n" + code + "\n```\n") ); private void Write( diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs index bc6b72d70..bba85cfe0 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationReferenceTests.cs @@ -50,8 +50,8 @@ public async Task ExportPlanningUsesActualTargetsAndExcludesNonProductOwnersWith }) { string product = owner.StartsWith("build/", StringComparison.Ordinal) ? "fixture-foreign" - : ""; - string test = owner == "src/Fixture" ? "true" : ""; + : string.Empty; + string test = owner == "src/Fixture" ? "true" : string.Empty; Write( owner + "/" + Path.GetFileName(owner) + ".csproj", "" + product + test @@ -194,7 +194,12 @@ public async Task ResolvedUnionSupportsIndependentSelectedSourceOwners() OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" ) ); - var start = new ProcessStartInfo(host) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + var start = new ProcessStartInfo(host) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; foreach (string argument in new[] { "restore", @@ -528,21 +533,20 @@ public async Task DifferentEvaluatedContextsCannotShareOneBatch( [Theory] [InlineData("--cache-root")] [InlineData("--snapshot")] - public async Task IncompleteSnapshotSelectionDoesNotOpenLocalFiles(string option) - { - await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([ - "--engine-root", - m_root, - "--dotnet", - "not-invoked", - "--reference", - "absent.json", - "--output", - "report.json", - option, - "missing" - ])); - } + public async Task IncompleteSnapshotSelectionDoesNotOpenLocalFiles( + string option + ) => await Assert.ThrowsAsync(() => DocumentationReferences.ValidateApiAsync([ + "--engine-root", + m_root, + "--dotnet", + "not-invoked", + "--reference", + "absent.json", + "--output", + "report.json", + option, + "missing" + ])); [Fact] public async Task RetiringSnapshotsPreservesReferencePayloadsForActiveReaders() @@ -645,8 +649,8 @@ string unrelated new { name = "Inno.Probe", path = selected, entry = "probe", surfaces = new[] { "source-clr" } }, new { name = "Inno.Unrelated", path = unrelated, entry = "unrelated", surfaces = new[] { "source-clr" } } }); - string revision = new('a', 40); - string tree = new('b', 40); + var revision = new string('a', 40); + var tree = new string('b', 40); Write("documentation/reference/projects/catalog.json", Encoding.UTF8.GetString(projects)); Write("documentation/reference/api/probe.json", Encoding.UTF8.GetString(facts)); Write( diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs index 3d3d0b2da..0dc82c6b5 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/DocumentationSourceContractTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; @@ -55,7 +56,7 @@ public class NotExported { } string facts = Path.Combine(m_root, "scope.json"); Assert.Equal(0, DocumentationReferences.ExportApi(ExportArguments(facts))); using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(facts)); - var symbols = document.RootElement.GetProperty("projects")[0] + Dictionary symbols = document.RootElement.GetProperty("projects")[0] .GetProperty("symbols") .EnumerateArray() .ToDictionary(symbol => symbol.GetProperty("id").GetString()!); @@ -138,7 +139,7 @@ string Signature(string id) public async Task CompileOnlyPackageContractsNeedNoRuntimeDeploymentAndCannotDisappear() { string reference = Path.Combine(m_root, "PackageContract.dll"); - var compilation = CSharpCompilation.Create( + CSharpCompilation compilation = CSharpCompilation.Create( "PackageContract", [CSharpSyntaxTree.ParseText("namespace PackageContract; public abstract class BaseContract { }")], ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!) @@ -350,7 +351,7 @@ public async Task ExtractionReusesOwnersAndInvalidatesSameLengthSourceWithPreser string cache = Path.Combine(m_root, "artifacts/documentation-export/extraction-cache/entries"); string[] originals = Directory.GetFiles(cache, "project.json", SearchOption.AllDirectories); Assert.Equal(2, originals.Length); - DateTime retainedTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var retainedTime = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); foreach (string file in originals) { File.SetLastWriteTimeUtc(file, retainedTime); @@ -419,7 +420,7 @@ public async Task ExtractionPayloadsCanMoveWithoutCopyingLocalOwnershipOrLeases( string payload = Assert.Single( Directory.GetFiles(Path.Combine(consumer.m_root, C_ENTRIES), "project.json", SearchOption.AllDirectories) ); - DateTime retainedTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var retainedTime = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); File.SetLastWriteTimeUtc(payload, retainedTime); string result = Path.Combine(consumer.m_root, "facts.json"); Assert.Equal(0, DocumentationReferences.ExportApi(consumer.ExportArguments(result))); @@ -434,7 +435,7 @@ public async Task ExtractionPayloadsCanMoveWithoutCopyingLocalOwnershipOrLeases( public async Task ExtractionInvalidatesInheritedXmlWithoutChangingTheReferenceAssembly() { string reference = Path.Combine(m_root, "BaseContract.dll"); - var compilation = CSharpCompilation.Create( + CSharpCompilation compilation = CSharpCompilation.Create( "BaseContract", [CSharpSyntaxTree.ParseText("namespace BaseContract; public abstract class Parent { public abstract void Read(); }")], ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator) diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs index 3aa6df152..b37f6580f 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/NativePlatformPolicyTests.cs @@ -17,9 +17,7 @@ public sealed class NativePlatformPolicyTests public void ComponentConfigurationCannotOwnPlatformPolicy( string configuration, bool rejected - ) { - Run(configuration, false, rejected); - } + ) => Run(configuration, false, rejected); [Fact] public void ComponentCannotKeepAnAdditionalTargetPreset() => Run("{}", true, true); diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs index bd9916c10..849e3561b 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/RepositoryInputTests.cs @@ -11,7 +11,10 @@ public sealed class RepositoryInputTests : IDisposable { private readonly string m_root = Path.Combine(Path.GetTempPath(), "InnoRepositoryInputs", Guid.NewGuid().ToString("N")); - public RepositoryInputTests() => Directory.CreateDirectory(m_root); + public RepositoryInputTests() + { + Directory.CreateDirectory(m_root); + } [Fact] public void EachAssemblyUsesItsOwnDeclaredSource() @@ -25,10 +28,7 @@ public void EachAssemblyUsesItsOwnDeclaredSource() } [Fact] - public void NullAssemblyIsRejectedBeforeReadingMetadata() - { - Assert.Throws(() => TestRepository.GetRoot(null!)); - } + public void NullAssemblyIsRejectedBeforeReadingMetadata() => Assert.Throws(() => TestRepository.GetRoot(null!)); [Fact] public void MissingRelativeAndUnavailableDeclarationsAreRejected() diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs index a4e709a11..26f8201ec 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/TestRepositoryInputsTests.cs @@ -66,7 +66,7 @@ await File.WriteAllTextAsync(project, $""" JsonElement[] declarations = result.RootElement.GetProperty("Items") .GetProperty("AssemblyAttribute") .EnumerateArray() - .Where(item => item.TryGetProperty("_Parameter1", out var key) && key.GetString() == "Inno.Testing.ArtifactsPath") + .Where(item => item.TryGetProperty("_Parameter1", out JsonElement key) && key.GetString() == "Inno.Testing.ArtifactsPath") .ToArray(); if (useArtifacts) { diff --git a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs index 1ec55d331..6feca04ac 100644 --- a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs +++ b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationApiSynchronizationTests.cs @@ -1,12 +1,15 @@ using System; using System.IO; using System.Linq; +using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; +using System.Xml; +using Markdig; using Xunit; using Inno.Core.IO; @@ -18,7 +21,10 @@ public sealed class DocumentationApiSynchronizationTests : IDisposable private const string C_TYPE = "T:Inno.Probe.Value"; private const string C_MEMBER = "P:Inno.Probe.Value.count"; - public DocumentationApiSynchronizationTests() => Bind(); + public DocumentationApiSynchronizationTests() + { + Bind(); + } public void Dispose() => Directory.Delete(m_root, recursive: true); @@ -51,8 +57,8 @@ public async Task ProjectGuideBecomesAuthoredOnEditAndTracksSubsequentSourceChan await Sync(); Assert.Equal(manual, File.ReadAllText(path)); string cache = Path.Combine(m_root, "artifacts/project-query"); - var initial = await DocumentationStore.IndexAsync(m_root, m_root, cache); - using (var initialSnapshot = await DocumentationStore.OpenAsync(cache, initial.snapshot)) + DocumentationResult initial = await DocumentationStore.IndexAsync(m_root, m_root, cache); + using (DocumentationSnapshot initialSnapshot = await DocumentationStore.OpenAsync(cache, initial.snapshot)) { Assert.Contains( "[!AUTHORED]", @@ -70,9 +76,9 @@ public async Task ProjectGuideBecomesAuthoredOnEditAndTracksSubsequentSourceChan Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); File.AppendAllText(path, "\nUpdated explanation.\n"); Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); - var indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); - using var snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - var page = (await snapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.probe"); + DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); + using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); + DocumentationPageInfo page = (await snapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.probe"); Assert.Contains("[!AUTHORED]", page.markdown); Assert.Contains("Independent lifetime guidance.", page.markdown); Assert.Contains("src/Inno.Probe.csproj", page.markdown); @@ -131,8 +137,8 @@ public async Task NewProjectsReceiveSynchronizedGuidesBesideTheirOwnerKind() ); Assert.Equal(0, await DocumentationCommand.ExecuteAsync(["api-check", "--docs-root", m_root])); string cache = Path.Combine(m_root, "artifacts/project-query"); - var indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); - using var snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); + DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); + using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); Assert.Contains( "[!SYNCED]", (await snapshot.ExportCatalogAsync()).pages.Single(page => page.id == "project.inno-probe-tests").markdown @@ -207,7 +213,7 @@ string expected using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); DocumentationPageInfo page = Assert.Single((await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api")); Assert.Equal(expected, page.title); - Assert.Contains("

" + System.Net.WebUtility.HtmlEncode(expected) + "

", Markdig.Markdown.ToHtml(page.markdown)); + Assert.Contains("

" + WebUtility.HtmlEncode(expected) + "

", Markdown.ToHtml(page.markdown)); Assert.Contains(expected, (await snapshot.QueryAsync(new("symbol", id, "Inno.Probe"))).hits.Single().text); } @@ -310,8 +316,8 @@ public async Task EditingADescriptionClearsAutomaticStalenessUntilTheNextSourceC string path = Path.Combine(m_root, "artifacts/query"); async Task AssertStatus(string status) { - var index = await DocumentationStore.IndexAsync(m_root, m_root, path); - using var snapshot = await DocumentationStore.OpenAsync(path, index.snapshot); + DocumentationResult index = await DocumentationStore.IndexAsync(m_root, m_root, path); + using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(path, index.snapshot); Assert.Contains("> [!" + status + "]", (await snapshot.QueryAsync(new("symbol", C_MEMBER, "Inno.Probe"))).hits.Single().text); } await AssertStatus("OUTDATED"); @@ -364,7 +370,7 @@ public async Task MissingSourceRemainsGeneratorOwned() { await Sync(); string member = Fragment(C_MEMBER); - File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml\n", "", StringComparison.Ordinal)); + File.WriteAllText(member, File.ReadAllText(member).Replace("source: xml\n", string.Empty, StringComparison.Ordinal)); Bind(description: "A fresh description."); await Sync(); Assert.Contains("source: xml", File.ReadAllText(member)); @@ -636,7 +642,10 @@ bool notice await Sync(); string member = Fragment(C_MEMBER); string original = File.ReadAllText(member); - File.WriteAllText(member, original.Replace("source: xml", source.Length == 0 ? "" : "source: " + source, StringComparison.Ordinal)); + File.WriteAllText( + member, + original.Replace("source: xml", source.Length == 0 ? string.Empty : "source: " + source, StringComparison.Ordinal) + ); string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); @@ -679,7 +688,7 @@ public async Task ElementsAreIndependentPagesWithNestedContainmentAndOverloadLin string cache = Path.Combine(m_root, "artifacts/query"); DocumentationResult indexed = await DocumentationStore.IndexAsync(m_root, m_root, cache); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache, indexed.snapshot); - var pages = (await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api").ToArray(); + DocumentationPageInfo[] pages = (await snapshot.ExportCatalogAsync()).pages.Where(page => page.kind == "api").ToArray(); Assert.Equal(7, pages.Length); Assert.All(pages, page => Assert.Single(page.symbols)); DocumentationPageInfo outer = pages.Single(page => page.symbols.ContainsKey(C_TYPE)); @@ -703,8 +712,11 @@ void Add( string parent ) { JsonNode symbol = symbols[0]!.DeepClone(); - symbol["id"] = id; symbol["kind"] = kind; symbol["signature"] = signature; - symbol["signatureHash"] = Hash(signature); symbol["containingType"] = parent; + symbol["id"] = id; + symbol["kind"] = kind; + symbol["signature"] = signature; + symbol["signatureHash"] = Hash(signature); + symbol["containingType"] = parent; symbols.Add(symbol); } } @@ -1094,7 +1106,7 @@ public async Task PartialSummariesRemainSeparateQuotedItemsWithoutSplittingTheir "> - First declaration.\n> \n> Still the first summary.\n> \n> - Second declaration with `Value`.", page.markdown ); - string html = Markdig.Markdown.ToHtml(page.markdown); + string html = Markdown.ToHtml(page.markdown); string summaryHtml = html[html.IndexOf("
\n
    ", StringComparison.Ordinal)..]; summaryHtml = summaryHtml[..summaryHtml.IndexOf("
", StringComparison.Ordinal)]; Assert.Equal(2, summaryHtml.Split("
  • ", StringSplitOptions.None).Length - 1); @@ -1166,7 +1178,7 @@ public async Task InvalidXmlCannotDiscardConstraintsOrReplaceLastGoodProse(strin SetTypeDocumentation(xml); Exception? failure = await Record.ExceptionAsync(Sync); Assert.NotNull(failure); - Assert.True(failure is InvalidDataException or System.Xml.XmlException); + Assert.True(failure is InvalidDataException or XmlException); Assert.Equal(previous, File.ReadAllText(Fragment(C_TYPE))); } @@ -1230,7 +1242,7 @@ private void SetTypes(params (string id, string signature)[] types) JsonNode facts = JsonNode.Parse(File.ReadAllText(Path.Combine(m_root, "reference/api/probe.json")))!; JsonNode prototype = facts["projects"]![0]!["symbols"]![0]!.DeepClone(); var symbols = new JsonArray(); - foreach (var type in types) + foreach ((string id, string signature) type in types) { JsonNode symbol = prototype.DeepClone(); symbol["id"] = type.id; diff --git a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationEvidenceTests.cs b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationEvidenceTests.cs index 81789437b..3b954262b 100644 --- a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationEvidenceTests.cs +++ b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationEvidenceTests.cs @@ -132,18 +132,42 @@ public async Task IncompleteOrAmbiguousCertificatesAreRejected(string change) JsonNode certificate = await PrepareAsync(); switch (change) { - case "missing-reference": certificate["references"] = new JsonArray(); break; - case "duplicate-reference": certificate["references"]!.AsArray().Add(certificate["references"]![0]!.DeepClone()); break; - case "duplicate-project": certificate["references"]![0]!["projects"] = new JsonArray("Probe", "Probe"); break; - case "unsupported-model": certificate["references"]![0]!["model"] = "unknown"; break; - case "missing-producer": certificate["producers"] = new JsonArray(); break; - case "bad-producer": certificate["producers"]![0]!["receiptIdentity"] = "not-a-digest"; break; - case "wrong-format": certificate["format"] = "unknown"; break; - case "missing-tables": certificate.AsObject().Remove("sourceFiles"); break; - case "missing-source-set": certificate["inputs"]![0]!["sourceSet"] = 9; break; - case "missing-source-file": certificate["sourceSets"]![0] = new JsonArray(9); break; - case "duplicate-source-file": certificate["sourceSets"]![0] = new JsonArray(0, 0); break; - case "escaping-source-file": certificate["sourceFiles"]![0]!["path"] = "../secret"; break; + case "missing-reference": + certificate["references"] = new JsonArray(); + break; + case "duplicate-reference": + certificate["references"]!.AsArray().Add(certificate["references"]![0]!.DeepClone()); + break; + case "duplicate-project": + certificate["references"]![0]!["projects"] = new JsonArray("Probe", "Probe"); + break; + case "unsupported-model": + certificate["references"]![0]!["model"] = "unknown"; + break; + case "missing-producer": + certificate["producers"] = new JsonArray(); + break; + case "bad-producer": + certificate["producers"]![0]!["receiptIdentity"] = "not-a-digest"; + break; + case "wrong-format": + certificate["format"] = "unknown"; + break; + case "missing-tables": + certificate.AsObject().Remove("sourceFiles"); + break; + case "missing-source-set": + certificate["inputs"]![0]!["sourceSet"] = 9; + break; + case "missing-source-file": + certificate["sourceSets"]![0] = new JsonArray(9); + break; + case "duplicate-source-file": + certificate["sourceSets"]![0] = new JsonArray(0, 0); + break; + case "escaping-source-file": + certificate["sourceFiles"]![0]!["path"] = "../secret"; + break; case "missing-input-group": case "different-input-group": certificate["examples"] = JsonSerializer.SerializeToNode(new[] diff --git a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationSnapshotTests.cs b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationSnapshotTests.cs index 77bf5a114..21247b9c7 100644 --- a/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationSnapshotTests.cs +++ b/tests/tooling/Inno.Tooling.Documentation.Tests/DocumentationSnapshotTests.cs @@ -426,7 +426,7 @@ string expectedWork { manifest["parserSchema"] = "prior-parser-implementation"; } - manifest["identity"] = ""; + manifest["identity"] = string.Empty; string previousIdentity = Hash(JsonSerializer.SerializeToUtf8Bytes(manifest)); manifest["identity"] = previousIdentity; string previousDirectory = Path.Combine(cache, "generations", previousIdentity); @@ -435,7 +435,11 @@ string expectedWork File.WriteAllBytes(Path.Combine(cache, "leases", previousIdentity + ".lock"), []); File.WriteAllBytes(Path.Combine(cache, "current.json"), JsonSerializer.SerializeToUtf8Bytes(previousIdentity)); string[] payloads = Directory.GetFiles(Path.Combine(cache, "pages"), "page.json", SearchOption.AllDirectories); - var timestamps = payloads.ToDictionary(static path => path, File.GetLastWriteTimeUtc, StringComparer.Ordinal); + Dictionary timestamps = payloads.ToDictionary( + static path => path, + File.GetLastWriteTimeUtc, + StringComparer.Ordinal + ); await Assert.ThrowsAsync(() => DocumentationStore.OpenAsync(cache)); DocumentationResult refreshed = await IndexAsync(); @@ -900,7 +904,7 @@ public async Task AProjectMoveChangesTheSnapshotThroughItsExplicitInventoryWitho public async Task LargePageReadsPreservePreambleAndNestedSectionsThroughExplicitContinuation() { string body = "---\nuid: long-contract\nkind: explanation\n---\nPreamble ownership contract.\n\n# First\nOwner contract.\n\n### Deep\n" - + new string('x', 18000) + "\n\n## Second\nRetirement contract.\n"; + + new string('x', 18_000) + "\n\n## Second\nRetirement contract.\n"; Write("content/en/long.md", body); await IndexAsync(); using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync(cache); diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs index acd34f107..136d81c05 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs @@ -1,10 +1,12 @@ using System; using System.IO; using System.Linq; +using System.Security; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Xunit; +using Inno.Core.IO; using Inno.Testing.Source; using Inno.Testing.Validation; using Inno.Tooling.Documentation; @@ -26,7 +28,9 @@ private static async Task ChangedUnionRootsAsync( bool variant, bool lateSelection = false ) { - using var repository = new ValidationRepository(TestRepository.GetRoot(typeof(ValidationCompletionTests).Assembly)); + using var repository = new ValidationRepository( + TestRepository.GetRoot(typeof(ValidationCompletionTests).Assembly) + ); // Source capture and three real compilation cycles prove content correctness, not a short latency budget. using var cancellation = new CancellationTokenSource(TimeSpan.FromHours(1)); const string C_FIXTURE = "tests/input/fixtures/Inno.Input.CompilationFixture"; @@ -145,7 +149,7 @@ await repository.SdkAsync( repository.Git("add", C_PROJECT); repository.Git("commit", "-m", "Consume a second effective property instance"); // The first real run has established workspace ownership. Restore the extra NuGet output instance before measuring it. - using (await Inno.Core.IO.CoordinatedFileLease.AcquireAsync( + using (await CoordinatedFileLease.AcquireAsync( Path.Combine(Path.GetDirectoryName(workspace)!, "owner.lock"), workspace + ".lock", Timeout.InfiniteTimeSpan, @@ -344,7 +348,9 @@ await repository.SdkAsync( [Fact] public async Task ChangedCompilationInputsCannotPublishReusableBuildIdentity() { - using var repository = new ValidationRepository(TestRepository.GetRoot(typeof(ValidationCompletionTests).Assembly)); + using var repository = new ValidationRepository( + TestRepository.GetRoot(typeof(ValidationCompletionTests).Assembly) + ); // Five real SDK validation cycles exercise identity correctness; their aggregate duration is not a latency contract. // Keep a generous runaway safeguard without canceling a healthy final build on a slower hosted runner. using var cancellation = new CancellationTokenSource(TimeSpan.FromHours(1)); @@ -464,7 +470,9 @@ await repository.EvidenceAsync(repository.PathOf("artifacts/repaired/results.jso [Fact] public async Task FailedClosingReadCannotCertifyOtherwisePassingIntermediateResults() { - using var repository = new ValidationRepository(TestRepository.GetRoot(typeof(ValidationCompletionTests).Assembly)); + using var repository = new ValidationRepository( + TestRepository.GetRoot(typeof(ValidationCompletionTests).Assembly) + ); using var external = new ValidationRepository(); string dependency = external.PathOf("Shared.props"); const string C_PROJECT = "tests/input/Inno.Input.Tests/Inno.Input.Tests.csproj"; @@ -472,7 +480,7 @@ public async Task FailedClosingReadCannotCertifyOtherwisePassingIntermediateResu C_PROJECT, File.ReadAllText(repository.PathOf(C_PROJECT)).Replace( "", - "", + "", StringComparison.Ordinal ) ); diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationFailureExecutionTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationFailureExecutionTests.cs index eb1f5a39a..4662d9cd0 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationFailureExecutionTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationFailureExecutionTests.cs @@ -53,7 +53,7 @@ public async Task FailedContractBlocksItsDependentButIndependentContextStillExec Assert.True(detail.Length < 5000, "An owner receipt must not duplicate the complete process log."); string log = repository.PathOf("artifacts/run/Failure.Tests.log"); Assert.Contains(log, detail); - Assert.Contains(new string('x', 20000), File.ReadAllText(log)); + Assert.Contains(new string('x', 20_000), File.ReadAllText(log)); Assert.Equal( "Passed", results.Single(result => result.GetProperty("id").GetString() == "independent-policy").GetProperty("status").GetString() diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationHostContractsTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationHostContractsTests.cs index 46dbd27c3..e9189012f 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationHostContractsTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationHostContractsTests.cs @@ -14,12 +14,17 @@ public sealed class ValidationHostContractsTests { private readonly ITestOutputHelper m_output; - public ValidationHostContractsTests(ITestOutputHelper output) => m_output = output; + public ValidationHostContractsTests(ITestOutputHelper output) + { + m_output = output; + } [Fact] public async Task ActualTrxDistinguishesCompiledHostExclusionsFromMissingRequiredExecution() { - using var repository = new ValidationRepository(TestRepository.GetRoot(typeof(ValidationHostContractsTests).Assembly)); + using var repository = new ValidationRepository( + TestRepository.GetRoot(typeof(ValidationHostContractsTests).Assembly) + ); string currentHost = OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linux"; string otherHost = currentHost == "linux" ? "windows" : "linux"; string source = $$""" diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationShardExecutionTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationShardExecutionTests.cs index 0707b6143..91d56b991 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationShardExecutionTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationShardExecutionTests.cs @@ -3,6 +3,7 @@ using System.IO; using System.IO.Compression; using System.Linq; +using System.Security; using System.Text.Json; using System.Text.Json.Nodes; using System.Threading; @@ -38,8 +39,8 @@ public async Task RestoreKeepsTheToolEnvironmentStableWhileChangedPackageBytesRe repository.Write( "Directory.Build.props", "" - + System.Security.SecurityElement.Escape(feed) + "" - + System.Security.SecurityElement.Escape(packages) + "" + + SecurityElement.Escape(feed) + "" + + SecurityElement.Escape(packages) + "" ); repository.Write( "src/Example/Example.csproj", @@ -150,7 +151,7 @@ public async Task ChangedExternalSdkInputExecutesCurrentChecksWithoutImportingRe using var repository = new ValidationRepository(); repository.Write( "Shared.props", - "" + "" ); repository.Write("tests/ci/Test-AgentRules.ps1", "Add-Content -LiteralPath artifacts/policy-executions.txt -Value executed"); using JsonDocument before = await repository.PlanAsync(profile: "full"); diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationTestOwnershipTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationTestOwnershipTests.cs index e9e868f96..68241d545 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationTestOwnershipTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationTestOwnershipTests.cs @@ -14,7 +14,9 @@ public sealed class ValidationTestOwnershipTests [Fact] public async Task AFailedUnionRetainsSuccessfulOwnersAndRejectsMissingIsolatedReceipts() { - using var repository = new ValidationRepository(TestRepository.GetRoot(typeof(ValidationTestOwnershipTests).Assembly)); + using var repository = new ValidationRepository( + TestRepository.GetRoot(typeof(ValidationTestOwnershipTests).Assembly) + ); const string C_INPUT = "tests/input/Inno.Input.Tests/Inno.Input.Tests.csproj"; const string C_UI = "tests/ui/Inno.UI.Tests/Inno.UI.Tests.csproj"; const string C_PROBE = "tests/input/Inno.Input.Tests/UnionFailureProbe.cs"; @@ -110,7 +112,9 @@ public sealed class UnionSuccessProbe repository.Git("add", C_EXECUTOR); repository.Git("commit", "-m", "Model a process failure after passing TRX output"); using (await repository.PlanAsync()) { } - var failure = await Assert.ThrowsAsync(() => repository.RunAsync(output: "artifacts/process-failure")); + InvalidDataException failure = await Assert.ThrowsAsync( + () => repository.RunAsync(output: "artifacts/process-failure") + ); Assert.Contains("exited with 17", failure.Message); using JsonDocument process = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/process-failure/results.json"))); JsonElement[] tests = process.RootElement.GetProperty("results") diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/BackendInputTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/BackendInputTests.cs index 71813cfb0..5f7a91bcd 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/BackendInputTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/BackendInputTests.cs @@ -1,3 +1,4 @@ +using System; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -96,7 +97,7 @@ Task Bind() "--output", repository.PathOf("artifacts/bound.json") ]); - static string Digest(string value) => System.Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(value))); + static string Digest(string value) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(value))); } [Theory] @@ -126,7 +127,7 @@ bool expected Assert.Contains(plan.RootElement.GetProperty("nativeRequests").EnumerateArray(), request => ( request.GetProperty("product").GetString() == "tool-only" && request.GetProperty("configuration").GetString() == "Debug" )); - string digest = new('a', 64); + var digest = new string('a', 64); WriteSelection(digest); string output = repository.PathOf("artifacts/inputs.json"); Assert.Equal(0, await Evaluate()); @@ -146,7 +147,7 @@ void WriteSelection(string certifiedDigest) "artifacts/native.json", JsonSerializer.Serialize(new { - assets = System.Array.Empty(), + assets = Array.Empty(), aggregates = new[] { new { product = "tool-only", target = "fixture-target", configuration = "release", sha256 = digest } diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs index 8808821c9..7996af7be 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationDocumentationTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -101,7 +102,7 @@ public async Task ProjectedReferenceChangesSelectTheirCompilerAndIgnoreUnrelated configuration = "Debug", sourceRevision = new string('a', 40), sourceTree = new string('b', 40), - sha256 = "" + sha256 = string.Empty }) ); BindProjection("before"); @@ -293,7 +294,7 @@ public async Task SharedHostAndScriptExamplesUseOnePreparedContextWithoutPromoti .GetString() ); } - var preceding = new System.Collections.Generic.HashSet(StringComparer.Ordinal); + var preceding = new HashSet(StringComparer.Ordinal); foreach (JsonElement check in checks) { if (check.GetProperty("exclusion").ValueKind == JsonValueKind.Null) @@ -455,7 +456,7 @@ public async Task RemovingARequiredCaptureDoesNotBecomeAnEmptySuccessfulSelectio // Exercise the real executor and compiler with a finite fixture policy. Repository-wide // architecture and test discovery are separate contracts, not inputs to this capture test. JsonNode execution = JsonNode.Parse(plan.RootElement.GetRawText())!; - JsonArray selected = new(); + var selected = new JsonArray(); foreach (JsonElement check in checks.Where( check => new[] { diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs index e8051e139..f0687548f 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs @@ -1,8 +1,12 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; +using System.Security; +using System.Security.Cryptography; using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -24,7 +28,7 @@ public async Task ScheduledPlanRebindsOnlyOnItsCapturedEnvironment() using JsonDocument planned = await repository.PlanAsync(profile: "fast"); string source = repository.PathOf("artifacts/scheduled.json"); string output = repository.PathOf("artifacts/bound"); - var plan = System.Text.Json.Nodes.JsonNode.Parse(planned.RootElement.GetRawText())!; + JsonNode plan = JsonNode.Parse(planned.RootElement.GetRawText())!; File.WriteAllText(source, plan.ToJsonString()); Task Bind() => ValidationCommand.ExecuteAsync([ @@ -81,7 +85,7 @@ public async Task BuildDefinitionAffectsOnlyTheEntryThatImportsIt() File.WriteAllText(previous, baseline.RootElement.GetRawText()); repository.Write("src/Example/Optional.props", "2"); using JsonDocument plan = await repository.PlanAsync(); - var tests = plan.RootElement.GetProperty("checks") + Dictionary tests = plan.RootElement.GetProperty("checks") .EnumerateArray() .Where(check => check.GetProperty("kind").GetString() == "test") .ToDictionary(check => check.GetProperty("owner").GetString()!); @@ -91,7 +95,7 @@ public async Task BuildDefinitionAffectsOnlyTheEntryThatImportsIt() reason.GetString()!.Contains("src/Example/Optional.props is consumed by", StringComparison.Ordinal)); File.Delete(repository.PathOf("src/Example/Optional.props")); using JsonDocument removed = await repository.PlanAsync(baselinePlan: previous); - var afterDelete = removed.RootElement.GetProperty("checks") + Dictionary afterDelete = removed.RootElement.GetProperty("checks") .EnumerateArray() .Where(check => check.GetProperty("kind").GetString() == "test") .ToDictionary(check => check.GetProperty("owner").GetString()!); @@ -183,8 +187,8 @@ public async Task FastProfileDefersRealIntegrationAndNativeProductsWithoutDownlo "tests/" + layer + "/Suite.csproj", ValidationRepository.Project( "true" + layer - + "" + (layer == "native" ? "editor" : "") - + "" + + "" + (layer == "native" ? "editor" : string.Empty) + + "" ) ); } @@ -508,7 +512,7 @@ public async Task SdkSelectedReferencePackContentInvalidatesEvidenceDespitePrese repository.Write( "src/Example/Example.csproj", ValidationRepository.Project( - "" + System.Security.SecurityElement.Escape(packs) + "" + SecurityElement.Escape(packs) + "" ) ); @@ -688,7 +692,7 @@ public async Task ExternalSourceContentInvalidatesEvidenceEvenWhenLengthAndTimes repository.Write( "src/Example/Example.csproj", ValidationRepository.Project( - "" + "" ) ); repository.Git("add", "."); @@ -714,7 +718,7 @@ public async Task ExternalImportContentInvalidatesEvidenceEvenWhenLengthAndTimes external.Write("Shared.props", original); repository.Write( "src/Example/Example.csproj", - ValidationRepository.Project("") + ValidationRepository.Project("") ); repository.Git("add", "."); repository.Git("commit", "-m", "Declare external SDK import"); @@ -740,9 +744,7 @@ public async Task ClosingFreshnessRejectsBothSourceAndExternalChangesDuringCheck string dependency = external.PathOf("Shared.props"); repository.Write( "src/Example/Example.csproj", - ValidationRepository.Project( - "" - ) + ValidationRepository.Project("") ); string script = string.Join( '\n', @@ -1405,7 +1407,7 @@ public async Task ExecutionFailureRetainsAnExactPlanReceiptAndCannotCertifySucce ); Assert.True(results.RootElement.GetProperty("completed").GetBoolean()); string identity = Convert.ToHexStringLower( - System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(repository.PathOf("artifacts/run/plan.json"))) + SHA256.HashData(File.ReadAllBytes(repository.PathOf("artifacts/run/plan.json"))) ); Assert.Equal(identity, results.RootElement.GetProperty("planIdentity").GetString()); await Assert.ThrowsAsync(() => repository.EvidenceAsync(repository.PathOf("artifacts/run/results.json"))); @@ -1605,7 +1607,7 @@ bool documentation "HEAD", "--output", output, - ..snapshot is null ? Array.Empty() : new[] { "--docs-cache-root", docs.cache, "--docs-snapshot", snapshot.snapshot! } + ..snapshot is null ? Array.Empty() : ["--docs-cache-root", docs.cache, "--docs-snapshot", snapshot.snapshot!] ]); Assert.Equal(2, status); diff --git a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationDocumentationFixture.cs b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationDocumentationFixture.cs index bd232681f..d267ce278 100644 --- a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationDocumentationFixture.cs +++ b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationDocumentationFixture.cs @@ -42,8 +42,8 @@ public void Initialize() }); Write("reference/projects/catalog.json", Encoding.UTF8.GetString(inventory)); Write("reference/api/facts.json", Encoding.UTF8.GetString(facts)); - string revision = new('a', 40); - string tree = new('b', 40); + var revision = new string('a', 40); + var tree = new string('b', 40); Write( "reference/engine.lock.json", JsonSerializer.Serialize(new diff --git a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs index 672de158f..99ac5c4ed 100644 --- a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs +++ b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs @@ -164,13 +164,13 @@ await ValidationCommand.ExecuteAsync([ extended.ToString(), "--configuration", configuration, - ..profile is null ? Array.Empty() : new[] { "--profile", profile }, - ..baselinePlan is null ? Array.Empty() : new[] { "--baseline-plan", baselinePlan }, - ..backendStore is null ? Array.Empty() : new[] { "--backend-store", backendStore }, - ..nativeDependencies is null ? Array.Empty() : new[] { "--native-dependencies", nativeDependencies }, - ..documentationCache is null ? Array.Empty() : new[] { "--docs-cache-root", documentationCache }, - ..documentationSnapshot is null ? Array.Empty() : new[] { "--docs-snapshot", documentationSnapshot }, - ..documentationBaseline is null ? Array.Empty() : new[] { "--docs-base-snapshot", documentationBaseline } + ..profile is null ? Array.Empty() : ["--profile", profile], + ..baselinePlan is null ? Array.Empty() : ["--baseline-plan", baselinePlan], + ..backendStore is null ? Array.Empty() : ["--backend-store", backendStore], + ..nativeDependencies is null ? Array.Empty() : ["--native-dependencies", nativeDependencies], + ..documentationCache is null ? Array.Empty() : ["--docs-cache-root", documentationCache], + ..documentationSnapshot is null ? Array.Empty() : ["--docs-snapshot", documentationSnapshot], + ..documentationBaseline is null ? Array.Empty() : ["--docs-base-snapshot", documentationBaseline] ]); return JsonDocument.Parse(File.ReadAllText(Path.Combine(output, "plan.json"))); } @@ -219,7 +219,7 @@ public Task RunAsync( PathOf("artifacts/plan/plan.json"), "--output", PathOf(output), - ..evidence is null ? Array.Empty() : new[] { "--evidence", PathOf(evidence) } + ..evidence is null ? Array.Empty() : ["--evidence", PathOf(evidence)] ], cancellation); public Task BuildAsync(params string[] arguments) diff --git a/tests/ui/Inno.UI.Tests/UiRuntimeTests.cs b/tests/ui/Inno.UI.Tests/UiRuntimeTests.cs index 13c676694..e787dc82c 100644 --- a/tests/ui/Inno.UI.Tests/UiRuntimeTests.cs +++ b/tests/ui/Inno.UI.Tests/UiRuntimeTests.cs @@ -18,7 +18,7 @@ public void FrameScopeCapturesInputAndBindsTheScriptFacade() { var backend = new CapturingBackend(); using var runtime = new UiRuntime(backend, new RejectingArtifacts()); - InputSnapshot snapshot = new( + var snapshot = new InputSnapshot( 7, keysPressed: [KeyCode.Enter], mouseButtonsReleased: [MouseButton.Left], @@ -32,7 +32,7 @@ public void FrameScopeCapturesInputAndBindsTheScriptFacade() runtime.Attach(); runtime.BeginFrame(frame); - Inno.UI.UI.Update(new UiContextHandle(10)); + UI.Update(new UiContextHandle(10)); UiInputSnapshot captured = Assert.IsType(backend.lastInput); Assert.Equal(new Vector2(12f, 34f), captured.mousePosition); @@ -143,7 +143,7 @@ UiTextureData texture public bool HasElementAtPoint( UiContextHandle context, - Inno.Core.Mathematics.Vector2 position + Vector2 position ) => false; public void Update( diff --git a/tools/Inno.Tooling.Architecture/AgentLinkValidator.cs b/tools/Inno.Tooling.Architecture/AgentLinkValidator.cs index 3ee2245ba..d83fb1f2d 100644 --- a/tools/Inno.Tooling.Architecture/AgentLinkValidator.cs +++ b/tools/Inno.Tooling.Architecture/AgentLinkValidator.cs @@ -75,7 +75,7 @@ string contentRoot private static HashSet Anchors(string text) { MarkdownDocument document = Markdown.Parse(text, S_PIPELINE); - var result = document.Descendants() + HashSet result = document.Descendants() .Select(static heading => heading.GetAttributes().Id!) .ToHashSet(StringComparer.Ordinal); foreach (string html in document.Descendants() diff --git a/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs b/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs index 75e7d2165..5455ad72f 100644 --- a/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs +++ b/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs @@ -622,7 +622,7 @@ ICollection failures return; } - var declaredTestProjects = paths + Dictionary declaredTestProjects = paths .Where(static pair => ( pair.Value.StartsWith("tests/", StringComparison.Ordinal) && pair.Value.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) @@ -730,7 +730,7 @@ ICollection failures } } - var declaredSourceProjects = paths + Dictionary declaredSourceProjects = paths .Where(static pair => ( S_PRODUCTION_ROOTS.Any(root => pair.Value.StartsWith(root + "/", StringComparison.Ordinal)) && pair.Value.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) diff --git a/tools/Inno.Tooling.Architecture/AssemblyDocumentationProvider.cs b/tools/Inno.Tooling.Architecture/AssemblyDocumentationProvider.cs index e1e131e2a..c49088acf 100644 --- a/tools/Inno.Tooling.Architecture/AssemblyDocumentationProvider.cs +++ b/tools/Inno.Tooling.Architecture/AssemblyDocumentationProvider.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Threading; +using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis; @@ -80,7 +81,7 @@ byte[] document .GroupBy(static element => (string)element.Attribute("name")!, StringComparer.Ordinal) .ToDictionary(static group => group.Key, static group => group.First().ToString(), StringComparer.Ordinal); } - catch (System.Xml.XmlException failure) + catch (XmlException failure) { throw new InvalidDataException($"The required inherited assembly documentation is invalid: '{path}'.", failure); } diff --git a/tools/Inno.Tooling.Architecture/DocumentationApiExtractor.cs b/tools/Inno.Tooling.Architecture/DocumentationApiExtractor.cs index 92840d4c2..b656ae535 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationApiExtractor.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationApiExtractor.cs @@ -6,6 +6,7 @@ using System.Text; using System.Text.Json.Serialization; using System.Threading; +using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -74,7 +75,7 @@ CancellationToken cancellationToken ) { var result = new List(); var seen = new HashSet(StringComparer.Ordinal); - var scopes = ReadExports(compilation).Where(export => export.assembly == compilation?.AssemblyName) + Dictionary scopes = ReadExports(compilation).Where(export => export.assembly == compilation?.AssemblyName) .ToDictionary(export => export.type, export => export.scope, StringComparer.Ordinal); foreach (SyntaxTree tree in compilation?.SyntaxTrees ?? []) { @@ -261,8 +262,8 @@ private static string Signature(ISymbol symbol) { return signature; } - var modifiers = new List(); - modifiers.Add( + var modifiers = new List + { type.DeclaredAccessibility switch { Accessibility.Public => "public", @@ -270,7 +271,7 @@ private static string Signature(ISymbol symbol) Accessibility.ProtectedOrInternal => "protected internal", _ => throw new InvalidOperationException("A Wiki type signature must have externally visible accessibility.") } - ); + }; if (type.IsStatic) { modifiers.Add("static"); @@ -324,7 +325,7 @@ CancellationToken cancellationToken { own = string.IsNullOrWhiteSpace(xml) ? null : XElement.Parse(xml); } - catch (System.Xml.XmlException) + catch (XmlException) { // The XML validator reports malformed source; inventory capture must still complete. return string.Empty; diff --git a/tools/Inno.Tooling.Architecture/DocumentationExamples.cs b/tools/Inno.Tooling.Architecture/DocumentationExamples.cs index 5f895a928..08562132e 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationExamples.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationExamples.cs @@ -113,16 +113,17 @@ public static async Task ExecuteAsync( throw new ArgumentException("Selected example page is missing: " + page); } } - var projects = RepositorySourceInventory.Projects(root) + Dictionary projects = RepositorySourceInventory.Projects(root) .ToDictionary(static project => Path.GetFileNameWithoutExtension(project), StringComparer.Ordinal); - var groups = catalog.pages.Where(page => selected.Count == 0 || selected.Contains(page.id)) + (DocumentationPageInfo page, DocumentationCodeBlockInfo[] blocks)[] groups = catalog.pages + .Where(page => selected.Count == 0 || selected.Contains(page.id)) .Select(page => (page, blocks: page.codeBlocks.Where(static block => ( block.language is "csharp" or "cs" && block.declarationSymbols.Count == 0 )).ToArray())) .Where(static group => group.blocks.Length != 0) .ToArray(); - var requested = groups.Where(static group => group.page.examples is not null) + HashSet requested = groups.Where(static group => group.page.examples is not null) .SelectMany(static group => group.page.examples!.projects) .Where(projects.ContainsKey) .Select(name => projects[name]) @@ -168,7 +169,7 @@ group.page.examples is null ); var frozen = new Dictionary(StringComparer.OrdinalIgnoreCase); var results = new List(); - foreach (var group in groups) + foreach ((DocumentationPageInfo page, DocumentationCodeBlockInfo[] blocks) group in groups) { cancellationToken.ThrowIfCancellationRequested(); DocumentationExampleContext? context = group.page.examples; @@ -206,7 +207,7 @@ group.page.examples is null ); bool editor = context.mode == "editor-script"; IReadOnlyList references = scripts.GetReferences(editor); - foreach (var identity in scripts.GetIdentities(editor)) + foreach (KeyValuePair identity in scripts.GetIdentities(editor)) { identities.Add(identity.Key, identity.Value); } diff --git a/tools/Inno.Tooling.Architecture/DocumentationExportCache.cs b/tools/Inno.Tooling.Architecture/DocumentationExportCache.cs index f392d331e..2c91935be 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationExportCache.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationExportCache.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.Json; @@ -40,7 +41,7 @@ CancellationToken cancellationToken m_activity = m_publisher.AcquireUseAsync(cancellationToken).AsTask().GetAwaiter().GetResult(); } - /// + /// public void Dispose() => m_activity.Dispose(); internal bool TryRead( @@ -163,7 +164,7 @@ internal void Report() private static string ToolIdentity() { - var assembly = typeof(DocumentationExportCache).Assembly; + Assembly assembly = typeof(DocumentationExportCache).Assembly; string[] sources = assembly.GetManifestResourceNames().Where(static name => name.StartsWith("ApiExtractionSource/", StringComparison.Ordinal)).Order(StringComparer.Ordinal).ToArray(); if (sources.Length == 0) @@ -178,7 +179,7 @@ private static string ToolIdentity() using var reader = new StreamReader(stream); identities.Add(source + "\0" + Hash(Encoding.UTF8.GetBytes(reader.ReadToEnd().ReplaceLineEndings("\n")))); } - foreach (var compiler in new[] { typeof(Compilation).Assembly, typeof(CSharpCompilation).Assembly }) + foreach (Assembly compiler in new[] { typeof(Compilation).Assembly, typeof(CSharpCompilation).Assembly }) { identities.Add(compiler.GetName().Name + "\0" + Hash(File.ReadAllBytes(compiler.Location))); } diff --git a/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs b/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs index 1155ba532..e7f57e492 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs @@ -213,5 +213,5 @@ string Required(string key) private static string Property( JsonElement node, string name - ) => node.GetProperty("Properties").GetProperty(name).GetString() ?? ""; + ) => node.GetProperty("Properties").GetProperty(name).GetString() ?? string.Empty; } diff --git a/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs b/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs index 4fab3764e..080d7a194 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs @@ -76,7 +76,7 @@ internal DocumentationProjectReferences( bool resolved = graph.RootElement[0].GetProperty("Items").TryGetProperty("ReferencePath", out _); foreach (JsonElement snapshot in graph.RootElement.EnumerateArray()) { - var properties = snapshot.GetProperty("GlobalProperties") + Dictionary properties = snapshot.GetProperty("GlobalProperties") .EnumerateObject() .ToDictionary( static property => property.Name, @@ -194,7 +194,7 @@ CancellationToken cancellationToken foreach (SyntaxTree tree in compilation.SyntaxTrees) { cancellationToken.ThrowIfCancellationRequested(); - var parse = (CSharpParseOptions)tree.Options; + CSharpParseOptions parse = (CSharpParseOptions)tree.Options; sources.Add(new { path = Path.GetRelativePath(m_root, tree.FilePath).Replace('\\', '/'), @@ -293,7 +293,7 @@ private CSharpCompilation Evaluate( } if (m_selectedProperties is not null) { - foreach (var property in m_selectedProperties) + foreach (KeyValuePair property in m_selectedProperties) { batchProperties[property.Key] = property.Value; } diff --git a/tools/Inno.Tooling.Architecture/DocumentationReferences.cs b/tools/Inno.Tooling.Architecture/DocumentationReferences.cs index d461ba3c5..58eb4641e 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationReferences.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationReferences.cs @@ -7,6 +7,7 @@ using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Inno.Core.IO; using Inno.Tooling.Documentation; @@ -286,7 +287,7 @@ public static async Task ValidateApiAsync( string? configuration = null; string? target = null; var expected = new Dictionary(StringComparer.Ordinal); - foreach (var reference in references) + foreach (KeyValuePair reference in references) { cancellationToken.ThrowIfCancellationRequested(); using JsonDocument manifest = JsonDocument.Parse(reference.Value); @@ -380,7 +381,7 @@ public static async Task ValidateApiAsync( { symbols.Add(symbol.GetProperty("id").GetString()!, symbol); } - foreach (var symbol in project.symbols) + foreach (DocumentationApiExtractor.DocumentationApiEntry symbol in project.symbols) { if (!symbols.Remove(symbol.id, out JsonElement prior)) { @@ -407,7 +408,7 @@ public static async Task ValidateApiAsync( } if (snapshot is null) { - foreach (var reference in references) + foreach (KeyValuePair reference in references) { if (!File.ReadAllBytes(reference.Key).AsSpan().SequenceEqual(reference.Value)) { @@ -566,15 +567,22 @@ private static IReadOnlyList CaptureApi( { throw new InvalidDataException("Selected API project is outside the requested product target: " + project); } - var compilation = models.GetCompilation(directory) - ?? throw new InvalidDataException( - "Selected API compilation is unavailable: " + project - + (failures.Count == 0 ? string.Empty : "\n" + string.Join('\n', failures)) - ); + CSharpCompilation compilation = models.GetCompilation(directory) + ?? throw new InvalidDataException( + "Selected API compilation is unavailable: " + project + + (failures.Count == 0 ? string.Empty : "\n" + string.Join('\n', failures)) + ); string owner = Path.GetRelativePath(root, project).Replace('\\', '/'); ApiProject Capture() { - var symbols = DocumentationApiExtractor.Capture(root, project, null, compilation, failures, cancellationToken); + IReadOnlyList symbols = DocumentationApiExtractor.Capture( + root, + project, + null, + compilation, + failures, + cancellationToken + ); if (failures.Count != 0) { throw new InvalidDataException( diff --git a/tools/Inno.Tooling.Architecture/DocumentationScriptApi.cs b/tools/Inno.Tooling.Architecture/DocumentationScriptApi.cs index 486186e69..ce9db8906 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationScriptApi.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationScriptApi.cs @@ -91,7 +91,7 @@ CancellationToken cancellationToken cancellationToken ); capture = capture with { target = options.GetValueOrDefault("--target") }; - var inventory = RepositorySourceInventory.Projects(root).ToHashSet(StringComparer.OrdinalIgnoreCase); + HashSet inventory = RepositorySourceInventory.Projects(root).ToHashSet(StringComparer.OrdinalIgnoreCase); foreach (Project project in capture.projects) { if (!inventory.Contains(PathBoundary.RequireUnlinkedPath(root, PathBoundary.Resolve(root, project.project)))) @@ -99,7 +99,7 @@ CancellationToken cancellationToken throw new InvalidDataException("Projected owner is absent from the actual project inventory: " + project.project); } } - foreach (var source in sources) + foreach (KeyValuePair source in sources) { if (!File.ReadAllBytes(source.Key).AsSpan().SequenceEqual(source.Value)) { @@ -145,7 +145,9 @@ internal static Capture Read( string, List<(string path, string assembly, DocumentationApiExtractor.DocumentationApiEntry symbol)> >(StringComparer.Ordinal); - var sourceMembers = new Dictionary(StringComparer.Ordinal); + var sourceMembers = new Dictionary( + StringComparer.Ordinal + ); var ambiguousMembers = new HashSet(StringComparer.Ordinal); var declaredScopes = new Dictionary(StringComparer.Ordinal); foreach (byte[] bytes in sourceReferences) @@ -179,7 +181,8 @@ internal static Capture Read( } foreach (JsonElement element in project.GetProperty("symbols").EnumerateArray()) { - var symbol = element.Deserialize()!; + DocumentationApiExtractor.DocumentationApiEntry symbol = element + .Deserialize()!; string path = project.GetProperty("project").GetString()!; string memberKey = path + "\0" + symbol.id; if (!sourceMembers.TryAdd(memberKey, symbol) @@ -192,8 +195,10 @@ internal static Capture Read( { continue; } - if (!sourceTypes.TryGetValue(symbol.id, out var candidates)) - { + if (!sourceTypes.TryGetValue( + symbol.id, + out List<(string path, string assembly, DocumentationApiExtractor.DocumentationApiEntry symbol)>? candidates + )) { sourceTypes.Add(symbol.id, candidates = []); } if (!candidates.Any(prior => prior.path == path && prior.symbol.signature == symbol.signature)) @@ -218,12 +223,12 @@ internal static Capture Read( { throw new InvalidDataException("Unsupported script documentation provenance."); } - var origins = provenance.Elements("type").ToDictionary( + Dictionary origins = provenance.Elements("type").ToDictionary( static origin => (string)origin.Attribute("id")!, static origin => (string)origin.Attribute("source")!, StringComparer.Ordinal ); - var originAssemblies = provenance.Elements("type").ToDictionary( + Dictionary originAssemblies = provenance.Elements("type").ToDictionary( static origin => (string)origin.Attribute("id")!, static origin => ( (string?)origin.Attribute("assembly") @@ -241,7 +246,7 @@ internal static Capture Read( } } var toSource = new Dictionary(StringComparer.Ordinal); - foreach (var mapping in mappings) + foreach (KeyValuePair mapping in mappings) { toSource.Add(mapping.Key[2..], mapping.Value[2..]); if (mapping.Key.Contains('`')) @@ -255,17 +260,17 @@ internal static Capture Read( toSource[name] = original; } } - var toLogical = toSource.GroupBy(static pair => pair.Value, StringComparer.Ordinal) + Dictionary toLogical = toSource.GroupBy(static pair => pair.Value, StringComparer.Ordinal) .Where(static group => group.Count() == 1) .ToDictionary(static group => group.Key, static group => group.Single().Key, StringComparer.Ordinal); Regex reverseNames = IdentityPattern(toSource.Keys); Regex forwardNames = IdentityPattern(toLogical.Keys); - var selected = (PortableExecutableReference)references[editor ? 1 : 0]; + PortableExecutableReference selected = (PortableExecutableReference)references[editor ? 1 : 0]; selected = ((AssemblyMetadata)selected.GetMetadata()).GetReference( documentation: new AssemblyDocumentationProvider(xmlPath, xmlBytes), filePath: selectedPath ); - var compilation = CSharpCompilation.Create( + CSharpCompilation compilation = CSharpCompilation.Create( "DocumentationScriptReference", references: frameworkReferences.Concat(references.Where(reference => reference != references[editor ? 1 : 0])).Append(selected), options: new CSharpCompilationOptions( @@ -274,8 +279,8 @@ internal static Capture Read( metadataImportOptions: MetadataImportOptions.Public ) ); - var assembly = (IAssemblySymbol?)compilation.GetAssemblyOrModuleSymbol(selected) - ?? throw new InvalidDataException("The selected logical script assembly cannot be read."); + IAssemblySymbol assembly = (IAssemblySymbol?)compilation.GetAssemblyOrModuleSymbol(selected) + ?? throw new InvalidDataException("The selected logical script assembly cannot be read."); var paths = new Dictionary(StringComparer.Ordinal); IReadOnlyList symbols = DocumentationApiExtractor.CaptureReference( assembly, @@ -314,16 +319,22 @@ DocumentationApiExtractor.DocumentationApiEntry Resolve(ISymbol symbol) { INamedTypeSymbol type = symbol as INamedTypeSymbol ?? symbol.ContainingType; string id = type.GetDocumentationCommentId()!; - if (!origins.TryGetValue(id, out string? original) || !sourceTypes.TryGetValue(original, out var allCandidates)) - { + if (!origins.TryGetValue(id, out string? original) + || !sourceTypes.TryGetValue( + original, + out List<(string path, string assembly, DocumentationApiExtractor.DocumentationApiEntry symbol)>? allCandidates + ) + ) { throw new InvalidDataException("Projected type has no unambiguous compiler origin and captured engine owner: " + id); } - var candidates = allCandidates.Where(candidate => candidate.assembly == originAssemblies[id]).ToArray(); + (string path, string assembly, DocumentationApiExtractor.DocumentationApiEntry symbol)[] candidates = allCandidates + .Where(candidate => candidate.assembly == originAssemblies[id]) + .ToArray(); if (candidates.Length != 1) { throw new InvalidDataException("Projected type origin does not resolve to one captured assembly: " + id); } - var origin = candidates[0]; + (string path, string assembly, DocumentationApiExtractor.DocumentationApiEntry symbol) origin = candidates[0]; if (!declaredScopes.TryGetValue(origin.assembly + "\0" + original, out string? scope)) { throw new InvalidDataException("Projected type lacks its actual export scope declaration: " + id); @@ -338,7 +349,7 @@ DocumentationApiExtractor.DocumentationApiEntry Resolve(ISymbol symbol) { throw new InvalidDataException("Projected member has conflicting captured source contracts: " + originalId); } - if (!sourceMembers.TryGetValue(origin.path + "\0" + originalId, out var member)) + if (!sourceMembers.TryGetValue(origin.path + "\0" + originalId, out DocumentationApiExtractor.DocumentationApiEntry? member)) { if (symbol is IMethodSymbol { MethodKind: MethodKind.Constructor, Parameters.Length: 0, ContainingType.IsValueType: true }) { @@ -420,7 +431,7 @@ CancellationToken cancellationToken } if (selected.Length == 0) return []; var sourceFacts = new List(); - var requiredOwners = selected.SelectMany(static reference => reference.projects).ToHashSet(StringComparer.Ordinal); + HashSet requiredOwners = selected.SelectMany(static reference => reference.projects).ToHashSet(StringComparer.Ordinal); foreach (DocumentationReferenceInfo source in catalog.references.Where(reference => ( reference.model == "source-clr" && reference.configuration == configuration && (reference.target is null || reference.target == target) @@ -457,7 +468,7 @@ CancellationToken cancellationToken using JsonDocument expected = JsonDocument.Parse( await snapshot.ReadReferenceAsync(reference.path, cancellationToken).ConfigureAwait(false) ); - var previous = expected.RootElement.GetProperty("projects") + Dictionary previous = expected.RootElement.GetProperty("projects") .EnumerateArray() .ToDictionary(static project => project.GetProperty("name").GetString()!, StringComparer.Ordinal); foreach (Project project in actual.projects) @@ -471,7 +482,7 @@ await snapshot.ReadReferenceAsync(reference.path, cancellationToken).ConfigureAw { differences.Add("Projected owner path changed: " + project.name); } - var symbols = old.GetProperty("symbols") + Dictionary symbols = old.GetProperty("symbols") .EnumerateArray() .ToDictionary(static symbol => symbol.GetProperty("id").GetString()!, StringComparer.Ordinal); foreach (DocumentationApiExtractor.DocumentationApiEntry symbol in project.symbols) diff --git a/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs b/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs index c86de7b41..2cc95f0e9 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs @@ -215,7 +215,7 @@ internal IReadOnlyList frameworkReferences private IEnumerable GetReferences(string projectDirectory) { - var references = m_references.ToDictionary( + Dictionary references = m_references.ToDictionary( static reference => Path.GetFileNameWithoutExtension(reference.Display)!, StringComparer.OrdinalIgnoreCase ); diff --git a/tools/Inno.Tooling.Architecture/EditorPresentationSourceValidator.cs b/tools/Inno.Tooling.Architecture/EditorPresentationSourceValidator.cs index 02477b768..dfc73e0b0 100644 --- a/tools/Inno.Tooling.Architecture/EditorPresentationSourceValidator.cs +++ b/tools/Inno.Tooling.Architecture/EditorPresentationSourceValidator.cs @@ -33,7 +33,7 @@ ICollection failures Report(relativePath, tree, group.First(), "one type cannot have multiple presentation aliases in the same file", failures); } } - var facadeAliases = aliases.Where(static directive => directive.Name!.ToString() == C_FACADE) + HashSet facadeAliases = aliases.Where(static directive => directive.Name!.ToString() == C_FACADE) .Select(static directive => directive.Alias!.Name.Identifier.ValueText) .ToHashSet(StringComparer.Ordinal); facadeAliases.Add(C_FACADE); diff --git a/tools/Inno.Tooling.Architecture/EditorUiBoundaryValidator.cs b/tools/Inno.Tooling.Architecture/EditorUiBoundaryValidator.cs index f01885647..32e2b26d7 100644 --- a/tools/Inno.Tooling.Architecture/EditorUiBoundaryValidator.cs +++ b/tools/Inno.Tooling.Architecture/EditorUiBoundaryValidator.cs @@ -28,7 +28,9 @@ ICollection failures bool panel = relative.StartsWith("src/composition/editor/panels/", StringComparison.Ordinal); foreach (XElement reference in XDocument.Load(path).Descendants("ProjectReference")) { - string dependency = Path.GetFileNameWithoutExtension(((string? )reference.Attribute("Include") ?? "").Replace('\\', '/')); + string dependency = Path.GetFileNameWithoutExtension( + ((string? )reference.Attribute("Include") ?? string.Empty).Replace('\\', '/') + ); if (feature && (dependency.Contains("ImGui", StringComparison.Ordinal) || dependency.StartsWith("Inno.Native.", StringComparison.Ordinal) @@ -77,7 +79,7 @@ private static bool DeclaresScriptingApi(string project) { return false; } - var syntax = CSharpSyntaxTree.ParseText( + CompilationUnitSyntax syntax = CSharpSyntaxTree.ParseText( File.ReadAllText(manifest), new CSharpParseOptions(LanguageVersion.CSharp14) ).GetCompilationUnitRoot(); diff --git a/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs b/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs index adf05809f..618a33c3b 100644 --- a/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs +++ b/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs @@ -215,7 +215,10 @@ private static void ValidateGraph( IReadOnlyList projects, ICollection failures ) { - var graph = projects.ToDictionary(static project => project.path, StringComparer.OrdinalIgnoreCase); + Dictionary graph = projects.ToDictionary( + static project => project.path, + StringComparer.OrdinalIgnoreCase + ); // Reload fixtures intentionally compile distinct generations with the same assembly identity. foreach (IGrouping identity in projects .Where(static project => !RepositorySourceInventory.IsTestPath(project.path)) diff --git a/tools/Inno.Tooling.Architecture/NativeBindingOwnershipValidator.cs b/tools/Inno.Tooling.Architecture/NativeBindingOwnershipValidator.cs index ed28a4373..e3cf55413 100644 --- a/tools/Inno.Tooling.Architecture/NativeBindingOwnershipValidator.cs +++ b/tools/Inno.Tooling.Architecture/NativeBindingOwnershipValidator.cs @@ -14,7 +14,7 @@ internal static void Validate( IEnumerable projects, ICollection failures ) { - Dictionary components = new(StringComparer.Ordinal); + var components = new Dictionary(StringComparer.Ordinal); foreach (string projectPath in projects) { if (!Path.GetFileName(projectPath).StartsWith("Inno.Native.", StringComparison.Ordinal)) @@ -49,7 +49,7 @@ ICollection failures { throw new InvalidDataException("The binding definition must contain declarative Project data."); } - Dictionary properties = new(StringComparer.Ordinal); + var properties = new Dictionary(StringComparer.Ordinal); foreach (XElement group in root.Elements()) { if (group.HasAttributes) diff --git a/tools/Inno.Tooling.Architecture/PlatformOwnershipValidator.cs b/tools/Inno.Tooling.Architecture/PlatformOwnershipValidator.cs index c8ba58de5..4635d8f4b 100644 --- a/tools/Inno.Tooling.Architecture/PlatformOwnershipValidator.cs +++ b/tools/Inno.Tooling.Architecture/PlatformOwnershipValidator.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Xml.Linq; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -14,7 +15,7 @@ internal static void Validate( string root, ICollection failures ) { - var projects = RepositorySourceInventory.Projects(root) + Dictionary projects = RepositorySourceInventory.Projects(root) .ToDictionary(path => Path.GetFullPath(path), StringComparer.OrdinalIgnoreCase); foreach (string script in RepositorySourceInventory.Files(root, "*.Tests.ps1")) { @@ -76,7 +77,7 @@ ICollection failures ) { continue; } - var syntax = CSharpSyntaxTree.ParseText(File.ReadAllText(source)).GetRoot(); + SyntaxNode syntax = CSharpSyntaxTree.ParseText(File.ReadAllText(source)).GetRoot(); foreach (InvocationExpressionSyntax call in syntax.DescendantNodes().OfType()) { if (call.Expression is MemberAccessExpressionSyntax access diff --git a/tools/Inno.Tooling.Architecture/PublicApiBoundaryValidator.cs b/tools/Inno.Tooling.Architecture/PublicApiBoundaryValidator.cs index 95f3915da..288d51cba 100644 --- a/tools/Inno.Tooling.Architecture/PublicApiBoundaryValidator.cs +++ b/tools/Inno.Tooling.Architecture/PublicApiBoundaryValidator.cs @@ -31,7 +31,7 @@ internal static void Validate( .ToArray(); bool Selected(Project project) => selectedProjects is null || selectedProjects.Contains(Path.GetRelativePath(root, project.path).Replace('\\', '/')); - var byName = projects.ToDictionary(project => project.name, StringComparer.Ordinal); + Dictionary byName = projects.ToDictionary(project => project.name, StringComparer.Ordinal); var references = new Dictionary(StringComparer.OrdinalIgnoreCase); string[] platform = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") ?? string.Empty).Split(Path.PathSeparator); foreach (string path in platform.Where(File.Exists)) @@ -158,8 +158,12 @@ bool Selected(Project project) Inspect(parameter.Type, member); } break; - case IFieldSymbol field: Inspect(field.Type, member); break; - case IEventSymbol signal: Inspect(signal.Type, member); break; + case IFieldSymbol field: + Inspect(field.Type, member); + break; + case IEventSymbol signal: + Inspect(signal.Type, member); + break; } } } @@ -230,8 +234,12 @@ ISymbol member } switch (value) { - case IArrayTypeSymbol array: Inspect(array.ElementType, member); return; - case IPointerTypeSymbol pointer: Inspect(pointer.PointedAtType, member); return; + case IArrayTypeSymbol array: + Inspect(array.ElementType, member); + return; + case IPointerTypeSymbol pointer: + Inspect(pointer.PointedAtType, member); + return; case IFunctionPointerTypeSymbol pointer: Inspect(pointer.Signature.ReturnType, member); foreach (IParameterSymbol parameter in pointer.Signature.Parameters) diff --git a/tools/Inno.Tooling.Architecture/PublicApiDocumentationValidator.cs b/tools/Inno.Tooling.Architecture/PublicApiDocumentationValidator.cs index 3852c937f..cb5dde8ce 100644 --- a/tools/Inno.Tooling.Architecture/PublicApiDocumentationValidator.cs +++ b/tools/Inno.Tooling.Architecture/PublicApiDocumentationValidator.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -110,7 +111,7 @@ ISet visited { document = XElement.Parse(xml); } - catch (System.Xml.XmlException) + catch (XmlException) { continue; } @@ -128,7 +129,7 @@ ISet visited IPropertySymbol property => property.Parameters, _ => [] }; - var documented = document.Elements("param") + HashSet documented = document.Elements("param") .Select(static element => (string?)element.Attribute("name")) .ToHashSet(StringComparer.Ordinal); if (parameters.Any(parameter => !documented.Contains(parameter.Name))) @@ -137,7 +138,7 @@ ISet visited } if (target is IMethodSymbol generic) { - var typeParameters = document.Elements("typeparam") + HashSet typeParameters = document.Elements("typeparam") .Select(static element => (string?)element.Attribute("name")) .ToHashSet(StringComparer.Ordinal); if (generic.TypeParameters.Any(parameter => !typeParameters.Contains(parameter.Name))) diff --git a/tools/Inno.Tooling.Documentation/DocumentationCommand.cs b/tools/Inno.Tooling.Documentation/DocumentationCommand.cs index b062b4c73..cd79608bc 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationCommand.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationCommand.cs @@ -149,7 +149,7 @@ public static async Task ExecuteAsync( { Console.WriteLine($"{page.id}: {page.path} ({page.kind}; {page.sections.Count} sections)"); } - foreach (var project in catalog.projects) + foreach (KeyValuePair project in catalog.projects) { if (project.Value is null) { @@ -196,7 +196,7 @@ public static async Task ExecuteAsync( foreach (DocumentationContinuation next in result.continuations) { Console.WriteLine( - $"Continue: docs read --page {next.pageId}" + (next.section is null ? "" : " --section " + next.section) + $"Continue: docs read --page {next.pageId}" + (next.section is null ? string.Empty : " --section " + next.section) + $" --offset {next.offset} — {next.reason}" ); } diff --git a/tools/Inno.Tooling.Documentation/DocumentationPageInfo.cs b/tools/Inno.Tooling.Documentation/DocumentationPageInfo.cs index 658eb5bc2..5a86a5d37 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationPageInfo.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationPageInfo.cs @@ -64,7 +64,7 @@ public sealed record DocumentationPageInfo( /// /// Gets canonical composed Markdown shared by website rendering and snapshot reads. /// - public string markdown { get; init; } = ""; + public string markdown { get; init; } = string.Empty; /// /// Gets the declared scripting scope, independent of the compilation surface. diff --git a/tools/Inno.Tooling.Documentation/DocumentationSnapshot.cs b/tools/Inno.Tooling.Documentation/DocumentationSnapshot.cs index c7ba865fe..b1f554412 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationSnapshot.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationSnapshot.cs @@ -17,7 +17,7 @@ namespace Inno.Tooling.Documentation; /// public sealed class DocumentationSnapshot : IDisposable { - private const int C_MAX_CONTENT = 16000; + private const int C_MAX_CONTENT = 16_000; private readonly string m_cache; private readonly DocumentationManifest m_manifest; private readonly FileLease m_reading; @@ -196,10 +196,6 @@ internal DocumentationSnapshot( /// /// Searches, reads, resolves symbols or resources, or reports binding status without mutating the index. /// - /// - /// Equally ranked multiword heading matches prefer task guides. Exact symbol and identifier searches - /// retain their reference priority; excerpts still require explicit contract reads. - /// /// /// A structured operation against this snapshot. Search excerpts are never returned as complete contracts. /// @@ -221,6 +217,10 @@ internal DocumentationSnapshot( /// /// The session has released its reading protection. /// + /// + /// Equally ranked multiword heading matches prefer task guides. Exact symbol and identifier searches + /// retain their reference priority; excerpts still require explicit contract reads. + /// public async Task QueryAsync( DocumentationRequest request, CancellationToken cancellationToken = default @@ -333,7 +333,7 @@ CancellationToken cancellationToken end--; } } - var continuations = Contracts(page); + List continuations = Contracts(page); if (end < text.Length) { continuations.Insert( @@ -348,7 +348,7 @@ CancellationToken cancellationToken "Original Markdown from the selected snapshot. Related contracts and continuations remain explicit.", [Hit( page, - section?.anchor ?? "", + section?.anchor ?? string.Empty, section?.line ?? 1, null, "Exact page or section", @@ -421,7 +421,8 @@ CancellationToken cancellation } selected = selected is null ? postings : selected.Intersect(postings); } - var ranked = selected!.Select(index => m_manifest.search[index]) + (DocumentationSearchEntry entry, (int score, bool taskGuide, string reason) match)[] ranked = selected! + .Select(index => m_manifest.search[index]) .Where(entry => Scope(m_manifest.pages[m_paths[entry.pageId]].metadata, request)) .Select(entry => (entry, match: Score(entry, request.value, tokens))) .OrderByDescending(static pair => pair.match.score) @@ -430,8 +431,10 @@ CancellationToken cancellation .ThenBy(static pair => pair.entry.section, StringComparer.Ordinal) .ToArray(); var hits = new List(); - foreach (var pair in ranked.Skip(request.offset).Take(request.limit)) - { + foreach ((DocumentationSearchEntry entry, (int score, bool taskGuide, string reason) match) pair in ranked + .Skip(request.offset) + .Take(request.limit) + ) { DocumentationPage page = await LoadAsync(pair.entry.pageId, cancellation).ConfigureAwait(false); DocumentationSection section = page.sections.Single(candidate => candidate.anchor == pair.entry.section); string body = DocumentationMarkdown.OwnText(page, section); @@ -540,7 +543,7 @@ CancellationToken cancellation DocumentationPage owner = await LoadAsync(matches[0].pageId, cancellation).ConfigureAwait(false); DocumentationSymbol selected = owner.symbols.Single(symbol => symbol.id == request.value); DocumentationSection section = owner.sections.Single(candidate => candidate.anchor == selected.section); - var continuations = Contracts(owner); + List continuations = Contracts(owner); bool independentPage = m_origins.ContainsKey(owner.path + "\0" + selected.id) && owner.symbols.Count == 1; string text = independentPage ? owner.text : selected.declaration; if (text.Length > C_MAX_CONTENT) @@ -656,7 +659,7 @@ string text completeness, text, "inno-doc://innoengine/snapshots/" + identity + "/pages/" + Uri.EscapeDataString(page.metadata.uid) - + (section.Length == 0 ? "" : "#" + Uri.EscapeDataString(section)) + + (section.Length == 0 ? string.Empty : "#" + Uri.EscapeDataString(section)) ) { scope = page.metadata.apiScope, diff --git a/tools/Inno.Tooling.Documentation/DocumentationStore.cs b/tools/Inno.Tooling.Documentation/DocumentationStore.cs index 1f1999a32..7955b6735 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationStore.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationStore.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Reflection; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -55,11 +56,6 @@ public static class DocumentationStore /// The published snapshot identity and the number of parsed and reused pages; source API remains unverified. /// Query-only changes rebuild the index while reusing pages whose parser, source and payload identities match. /// - /// - /// Independent page preparation uses at most four workers and retains each page's exclusive lease. - /// Catalog validation and generation publication occur only after all workers finish. Worker parsing - /// and registration timing totals can overlap; PagePreparation reports their enclosing wall time. - /// /// /// Inputs change during preparation, paths escape ownership, or a reference, contract or inclusion is invalid. /// @@ -69,14 +65,19 @@ public static class DocumentationStore /// /// Preparation is canceled. Completed immutable payloads remain registered for safe maintenance. /// + /// + /// Independent page preparation uses at most four workers and retains each page's exclusive lease. + /// Catalog validation and generation publication occur only after all workers finish. Worker parsing + /// and registration timing totals can overlap; PagePreparation reports their enclosing wall time. + /// public static async Task IndexAsync( string workspaceRoot, string documentationRoot, string cacheRoot, CancellationToken cancellationToken = default ) { - var total = Stopwatch.StartNew(); - var phase = Stopwatch.StartNew(); + Stopwatch total = Stopwatch.StartNew(); + Stopwatch phase = Stopwatch.StartNew(); var timings = new Dictionary(StringComparer.Ordinal); long parsingTicks = 0; long registrationTicks = 0; @@ -117,10 +118,10 @@ public static async Task IndexAsync( cancellationToken ).ConfigureAwait(false); DocumentationManifest? previous = TryReadCurrent(output); - var reusable = previous?.parserSchema == parserSchema - ? previous.pages.Values.ToDictionary(static page => page.key, StringComparer.Ordinal) - : new Dictionary(StringComparer.Ordinal); - var raw = EnumerateContent(content).ToDictionary( + Dictionary reusable = previous?.parserSchema == parserSchema + ? previous.pages.Values.ToDictionary(static page => page.key, StringComparer.Ordinal) + : new Dictionary(StringComparer.Ordinal); + Dictionary raw = EnumerateContent(content).ToDictionary( path => Path.GetRelativePath(root, path).Replace('\\', '/'), File.ReadAllText, StringComparer.Ordinal @@ -189,7 +190,7 @@ CancellationToken cancellation } ).ConfigureAwait(false); var pages = new List(prepared.Length); - foreach (var item in prepared) + foreach ((DocumentationPage page, DocumentationPageReference reference) item in prepared) { pages.Add(item.page); entries.Add(item.page.path, item.reference); @@ -217,7 +218,7 @@ CancellationToken cancellation .ToArray(); DocumentationCatalog.Validate(root, pages, projects); RecordPhase("CatalogValidation"); - var search = pages.SelectMany(page => page.sections.Select(section => + DocumentationSearchEntry[] search = pages.SelectMany(page => page.sections.Select(section => { string body = DocumentationMarkdown.OwnText(page, section); string terms = section.title + " " + body + " " + string.Join(' ', page.metadata.aliases) @@ -230,8 +231,11 @@ CancellationToken cancellation DocumentationMarkdown.Tokens(terms) ); })).ToArray(); - var origins = composed.origins.ToDictionary(origin => origin.page + "\0" + origin.id, StringComparer.Ordinal); - var symbols = pages.SelectMany(page => page.symbols.Select(symbol => new DocumentationSymbolReference( + Dictionary origins = composed.origins.ToDictionary( + origin => origin.page + "\0" + origin.id, + StringComparer.Ordinal + ); + DocumentationSymbolReference[] symbols = pages.SelectMany(page => page.symbols.Select(symbol => new DocumentationSymbolReference( page.metadata.owners.Single(), page.metadata.apiSurface!, symbol.id, @@ -240,7 +244,7 @@ CancellationToken cancellation origins.GetValueOrDefault(page.path + "\0" + symbol.id)?.surfaces ))).ToArray(); var manifest = new DocumentationManifest( - "", + string.Empty, schema, parserSchema, binding, @@ -431,7 +435,7 @@ private static string[] EnumerateContent(string content) private static string CreateSchemaIdentity(params string[] selectedInputs) { - var assembly = typeof(DocumentationStore).Assembly; + Assembly assembly = typeof(DocumentationStore).Assembly; string[] sources = assembly .GetManifestResourceNames() .Where(static name => name.StartsWith("DocumentationSource/", StringComparison.Ordinal)) @@ -464,7 +468,7 @@ private static DocumentationManifest ReadManifest( DocumentationManifest manifest = Deserialize(File.ReadAllBytes(path)); if (manifest.identity != identity || (requireCurrentSchema && (manifest.schema != schema || manifest.parserSchema != parserSchema || manifest.references is null)) - || DocumentationMarkdown.Hash(JsonSerializer.SerializeToUtf8Bytes(manifest with { identity = "" }, json)) != identity + || DocumentationMarkdown.Hash(JsonSerializer.SerializeToUtf8Bytes(manifest with { identity = string.Empty }, json)) != identity ) { throw new InvalidDataException("Documentation snapshot integrity or schema mismatch; explicitly rebuild its index."); } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs index e7e39c966..8af33f1d7 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs @@ -36,7 +36,10 @@ internal static DocumentationComposedContent Prepare( DocumentationBinding binding, IReadOnlyDictionary raw ) { - var pages = new SortedDictionary(raw.ToDictionary(pair => pair.Key, pair => pair.Value), StringComparer.Ordinal); + var pages = new SortedDictionary( + raw.ToDictionary(pair => pair.Key, pair => pair.Value), + StringComparer.Ordinal + ); var inputs = new SortedDictionary( raw.ToDictionary(pair => pair.Key, pair => DocumentationMarkdown.Hash(pair.Value)), StringComparer.Ordinal @@ -53,7 +56,10 @@ IReadOnlyDictionary raw throw new InvalidDataException("Unsupported API content registry."); } IReadOnlyDictionary facts = DocumentationApiFacts.Read(root, binding); - var entries = registry.entries.ToDictionary(entry => entry.symbol, StringComparer.Ordinal); + Dictionary entries = registry.entries.ToDictionary( + entry => entry.symbol, + StringComparer.Ordinal + ); var fragments = new Dictionary(StringComparer.Ordinal); foreach (DocumentationApiContentEntry entry in registry.entries) { @@ -79,7 +85,7 @@ IReadOnlyDictionary raw } } var contractPages = new Dictionary(StringComparer.Ordinal); - foreach (var page in pages) + foreach (KeyValuePair page in pages) { YamlMappingNode metadata = DocumentationApiFragment.ReadMetadata(page.Key, page.Value); string uid = ((YamlScalarNode)metadata.Children[new YamlScalarNode("uid")]).Value!; @@ -92,13 +98,13 @@ IReadOnlyDictionary raw { contractPages.Add(fragments[typeEntry.symbol].uid, (typeEntry.path, typeEntry.title)); } - var byType = entries.Values.Where(entry => facts.ContainsKey(entry.symbol)) + Dictionary byType = entries.Values.Where(entry => facts.ContainsKey(entry.symbol)) .Where(entry => DocumentationApiPresentation.Parent(facts[entry.symbol][0]) is not null) .GroupBy(entry => DocumentationApiPresentation.Parent(facts[entry.symbol][0])!, StringComparer.Ordinal) .ToDictionary(group => group.Key, group => group.OrderBy(member => member.title, StringComparer.OrdinalIgnoreCase) .ThenBy(member => member.symbol, StringComparer.Ordinal) .ToArray(), StringComparer.Ordinal); - foreach (var type in facts.Values) + foreach (DocumentationApiFact[] type in facts.Values) { DocumentationApiFact fact = type[0]; DocumentationApiContentEntry entry = entries[fact.key]; @@ -112,7 +118,7 @@ IReadOnlyDictionary raw ancestors.Add(fragments[ancestor]); } string header = Header(fragment, type, entry.title, ancestors, out YamlMappingNode headerMetadata); - var text = new StringBuilder(header).Append("\n\n"); + StringBuilder text = new StringBuilder(header).Append("\n\n"); string body = fragment.body.Trim(); string status = Status(fragment, type); text.Append("> [!").Append(status.ToUpperInvariant()).Append("]\n> ").Append( @@ -139,8 +145,8 @@ IReadOnlyDictionary raw text.Append("## Required contracts\n\n"); foreach (YamlScalarNode contract in contracts.Children) { - string[] target = (contract.Value ?? "").Split('#', 2); - if (!contractPages.TryGetValue(target[0], out var destination)) + string[] target = (contract.Value ?? string.Empty).Split('#', 2); + if (!contractPages.TryGetValue(target[0], out (string path, string title) destination)) { throw new InvalidDataException("Missing associated API contract: " + contract.Value); } @@ -154,7 +160,7 @@ IReadOnlyDictionary raw ) .Append("](") .Append(relative) - .Append(target.Length == 2 ? "#" + target[1] : "") + .Append(target.Length == 2 ? "#" + target[1] : string.Empty) .Append(")\n"); } text.Append('\n'); @@ -177,7 +183,7 @@ IReadOnlyDictionary raw if (members.Length != 0) { text.Append("\n## Members\n\n| Kind | Element | Description |\n| --- | --- | --- |\n"); - foreach (var group in members + foreach (IGrouping group in members .GroupBy(member => Category(facts[member.symbol][0])) .OrderBy(group => group.Key, StringComparer.Ordinal) ) { @@ -213,7 +219,7 @@ IReadOnlyDictionary raw pages.Add(entry.path, text.ToString()); } // Category tables and queries use the same effective summaries as type pages. - foreach (var category in DocumentationApiNavigation.Create( + foreach (KeyValuePair category in DocumentationApiNavigation.Create( registry.entries, facts, DocumentationApiPresentation.ProjectDescriptions(root), @@ -244,7 +250,7 @@ string title .Append(' ') .Append(fact.signatureHash) .Append(" -->\n\n"); - foreach (var variants in contexts.GroupBy(value => value.signature, StringComparer.Ordinal)) + foreach (IGrouping variants in contexts.GroupBy(value => value.signature, StringComparer.Ordinal)) { text.Append("")) @@ -146,7 +146,7 @@ string text .Where(item => item.Span.Start >= section.start && item.Span.End < section.end && item.Info == "csharp") .Select(static item => item.Lines.ToString().Replace("\r\n", "\n").TrimEnd('\n')) .ToArray(); - symbols.Add(new(id, marker.Groups["hash"].Value, anchor, section.anchor, declaration, code)); + symbols.Add(new DocumentationSymbol(id, marker.Groups["hash"].Value, anchor, section.anchor, declaration, code)); } } string[] includes = html.SelectMany(block => Regex.Matches(block, @"") diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs index 328a80f3c..6f94fa846 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs @@ -61,8 +61,8 @@ internal static DocumentationApiPlan Plan( DocumentationBinding binding, IReadOnlyDictionary facts ) { - var edits = new List(); - var warnings = new List(); + List edits = []; + List warnings = []; Dictionary projects = JsonSerializer .Deserialize( File.ReadAllText(DocumentationApiFacts.Resolve(root, binding.projectManifest)) @@ -72,7 +72,7 @@ IReadOnlyDictionary facts string registryPath = DocumentationApiFacts.Resolve(root, C_REGISTRY); // A checkout without the registry does not manage project guides. DocumentationProjectGuide[] created = File.Exists(registryPath) ? NewGuides(root, projects.Values, registered) : []; - var entries = new List(); + List entries = []; foreach (DocumentationProjectGuide entry in registered.Concat(created)) { bool isNew = !registered.Contains(entry); @@ -97,7 +97,7 @@ IReadOnlyDictionary facts { // The same removal rule as API pages: synchronized prose leaves with its source, // authored prose stays for editorial resolution. - edits.Add(new(entry.path, DocumentationMarkdown.Hash(text!), null)); + edits.Add(new DocumentationApiEdit(entry.path, DocumentationMarkdown.Hash(text!), null)); continue; } entries.Add(entry); @@ -106,7 +106,7 @@ IReadOnlyDictionary facts if (project is null) { warnings.Add( - new( + new DocumentationApiWarning( entry.project, entry.path, "RemovedProject", @@ -116,19 +116,26 @@ IReadOnlyDictionary facts } else if (stale) { - warnings.Add(new(entry.project, entry.path, "ReviewRequired", "The authored project guide is outdated.")); + warnings.Add( + new DocumentationApiWarning(entry.project, entry.path, "ReviewRequired", "The authored project guide is outdated.") + ); } if (!manual || string.IsNullOrWhiteSpace(fragment.body) || fragment.body.Trim() == Body(entry, contexts).Trim()) { warnings.Add( - new(entry.project, entry.path, "ManualExplanationRequired", "This project guide uses generated source information.") + new DocumentationApiWarning( + entry.project, + entry.path, + "ManualExplanationRequired", + "This project guide uses generated source information." + ) ); } string updated = Metadata(entry, fragment, contract, staleProse) + (manual || project is null ? fragment.body : "\n\n" + Body(entry, contexts)); if (updated != text) { - edits.Add(new(entry.path, text is null ? null : DocumentationMarkdown.Hash(text), updated)); + edits.Add(new DocumentationApiEdit(entry.path, text is null ? null : DocumentationMarkdown.Hash(text), updated)); } } if (created.Length != 0 || entries.Count != registered.Length) @@ -139,7 +146,7 @@ IReadOnlyDictionary facts ); var options = new JsonSerializerOptions { WriteIndented = true, NewLine = "\n" }; edits.Add( - new( + new DocumentationApiEdit( C_REGISTRY, DocumentationMarkdown.Hash(File.ReadAllText(registryPath)), JsonSerializer.Serialize(registry, options) + "\n" @@ -252,7 +259,7 @@ DocumentationProjectGuide[] registered ) { var owned = new HashSet(registered.Select(entry => entry.project), StringComparer.Ordinal); owned.UnionWith(DocumentationApiPresentation.ProjectDescriptions(root).Keys); - var guides = new List(); + List guides = []; foreach (DocumentationProject project in projects.OrderBy(project => project.name, StringComparer.Ordinal)) { if (project.path.StartsWith("platforms/", StringComparison.Ordinal) || owned.Contains(project.name)) @@ -263,7 +270,7 @@ DocumentationProjectGuide[] registered string directory = project.path.StartsWith("tests/", StringComparison.Ordinal) ? C_TEST_GUIDES : project.path.StartsWith("backends/", StringComparison.Ordinal) ? C_BACKEND_GUIDES : C_GUIDES; - guides.Add(new(directory + slug + ".md", "project." + slug, project.name)); + guides.Add(new DocumentationProjectGuide(directory + slug + ".md", "project." + slug, project.name)); } return guides.ToArray(); } diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationReferenceStore.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationReferenceStore.cs index daa715d0a..6bc9c6afa 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationReferenceStore.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationReferenceStore.cs @@ -19,13 +19,13 @@ internal static async Task PrepareAsync( IReadOnlyList projects, byte[] projectBytes, BuildCachePublisher publisher, - CancellationToken cancellation + CancellationToken cancellationToken ) { var inputs = new Dictionary(StringComparer.Ordinal); - var references = new List(); + List references = []; Dictionary owners = projects.ToDictionary(static project => project.name, StringComparer.Ordinal); await AddAsync( - new( + new DocumentationReferenceInfo( binding.projectManifest, binding.projectManifestIdentity, "project-inventory", @@ -42,7 +42,7 @@ await AddAsync( ).ConfigureAwait(false); foreach (DocumentationApiCapture capture in binding.apiManifests ?? []) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); DocumentationStore.RequireHash(capture.sha256, "API reference"); DocumentationStore.RequireHash(capture.sourceRevision, "API source revision", allowGitTree: true); DocumentationStore.RequireHash(capture.sourceTree, "API source tree", allowGitTree: true); @@ -77,7 +77,7 @@ await AddAsync( throw new InvalidDataException("API reference contains no project facts: " + capture.path); } await AddAsync( - new( + new DocumentationReferenceInfo( capture.path, capture.sha256, capture.model, @@ -107,13 +107,17 @@ byte[] bytes output, Path.Combine(output, "leases", "reference-" + reference.identity + ".lock") ); - using FileLease writing = await FileLease.AcquireAsync(lease, Timeout.InfiniteTimeSpan, cancellation).ConfigureAwait(false); + using FileLease writing = await FileLease.AcquireAsync( + lease, + Timeout.InfiniteTimeSpan, + cancellationToken + ).ConfigureAwait(false); if (!File.Exists(file) || DocumentationMarkdown.Hash(File.ReadAllBytes(file)) != reference.identity) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); AtomicFile.WriteAllBytes(file, bytes); } - publisher.EnsureImmutableRegistration(directory, lease, [], null, cancellation); + publisher.EnsureImmutableRegistration(directory, lease, [], null, cancellationToken); references.Add(reference); } } diff --git a/tools/Inno.Tooling.Validation/ValidationBuildInputs.cs b/tools/Inno.Tooling.Validation/ValidationBuildInputs.cs index a69af22fc..7d6ba8fb4 100644 --- a/tools/Inno.Tooling.Validation/ValidationBuildInputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationBuildInputs.cs @@ -22,11 +22,11 @@ internal ValidationBuildInputs( ValidationPlan plan, string context, Dictionary outputDigests, - CancellationToken cancellation + CancellationToken cancellationToken ) { m_plan = plan; m_outputDigests = outputDigests; - m_cancellation = cancellation; + m_cancellation = cancellationToken; m_checks = plan.checks.Where(check => check.kind == "build" && check.context == context && check.exclusion is null).ToArray(); var variantInputs = new HashSet(StringComparer.Ordinal); foreach (ValidationCheck check in m_checks) @@ -56,7 +56,7 @@ CancellationToken cancellation m_completed = File.Exists(m_path) ? JsonSerializer.Deserialize>(File.ReadAllBytes(m_path)) ?? throw new InvalidDataException("Completed compilation input identities are empty.") - : new(StringComparer.Ordinal); + : new Dictionary(StringComparer.Ordinal); } internal bool RequiresCompilation(ValidationDependencyInputs dependencies) @@ -66,7 +66,7 @@ internal bool RequiresCompilation(ValidationDependencyInputs dependencies) || !ValidationOutputs.Matches( m_plan, check, - new(check.id, "Passed", previous.inputs, 0, string.Empty, previous.outputs), + new ValidationResult(check.id, "Passed", previous.inputs, 0, string.Empty, previous.outputs), m_cancellation, m_outputDigests ) @@ -83,7 +83,7 @@ internal bool RequiresDependencyCompilation(ValidationDependencyInputs dependenc : !ValidationOutputs.Matches( m_plan, check, - new(check.id, "Passed", previous.inputs, 0, string.Empty, previous.outputs), + new ValidationResult(check.id, "Passed", previous.inputs, 0, string.Empty, previous.outputs), m_cancellation, m_outputDigests ) ? "compiled output content changed" : null; diff --git a/tools/Inno.Tooling.Validation/ValidationDeliverables.cs b/tools/Inno.Tooling.Validation/ValidationDeliverables.cs index a217e2ead..8200e3ba4 100644 --- a/tools/Inno.Tooling.Validation/ValidationDeliverables.cs +++ b/tools/Inno.Tooling.Validation/ValidationDeliverables.cs @@ -15,7 +15,7 @@ internal static class ValidationDeliverables internal static void Create( ValidationPlan plan, ValidationCheck check, - CancellationToken cancellation + CancellationToken cancellationToken ) { JsonElement editor = plan.contexts[check.context!].sdkGraph.EnumerateArray().Single(snapshot => ( Path.GetRelativePath(plan.root, snapshot.GetProperty("Path").GetString()!).Replace('\\', '/') == check.owner @@ -32,7 +32,7 @@ CancellationToken cancellation { foreach (string file in PathBoundary.EnumerateFiles(source).Order(StringComparer.Ordinal)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); ZipArchiveEntry entry = archive.CreateEntry( Path.GetRelativePath(source, file).Replace('\\', '/'), CompressionLevel.Fastest @@ -49,7 +49,7 @@ CancellationToken cancellation } stream.Flush(flushToDisk: true); } - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); AtomicFile.Install(candidate, destination); } finally @@ -62,7 +62,7 @@ CancellationToken cancellation var files = new Dictionary(StringComparer.Ordinal); foreach (string name in new[] { "Editor.zip", "PlayerSupportPack.zip" }) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); using FileStream stream = File.OpenRead(Path.Combine(directory, name)); files.Add(name, Convert.ToHexStringLower(SHA256.HashData(stream))); } diff --git a/tools/Inno.Tooling.Validation/ValidationDependencyInputs.cs b/tools/Inno.Tooling.Validation/ValidationDependencyInputs.cs index 61e2ceb97..aae79740e 100644 --- a/tools/Inno.Tooling.Validation/ValidationDependencyInputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationDependencyInputs.cs @@ -12,7 +12,7 @@ namespace Inno.Tooling.Validation; internal sealed class ValidationDependencyInputs( ValidationPlan plan, - CancellationToken cancellation + CancellationToken cancellationToken ) { private readonly Dictionary m_hashes = new(StringComparer.Ordinal); private readonly Dictionary[]> m_packages = new(StringComparer.Ordinal); @@ -88,7 +88,7 @@ internal Dictionary CapturePackages(ValidationCheck check) .Select(static instance => instance.GetProperty("ProjectAssetsFile").GetString()!) .Distinct(StringComparer.Ordinal) ) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(assets) || !File.Exists(assets)) { throw new InvalidDataException("Documentation source provenance requires actual restored dependency inputs."); @@ -123,7 +123,7 @@ internal static bool Required(ValidationCheck check) internal static string[] RestoredPackageDirectories( IEnumerable contexts, - CancellationToken cancellation + CancellationToken cancellationToken ) { var packages = new HashSet( OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal @@ -134,7 +134,7 @@ CancellationToken cancellation .Where(static path => !string.IsNullOrWhiteSpace(path)) .Distinct(StringComparer.Ordinal) ) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (File.Exists(assets)) { packages.UnionWith(ReadPackages(assets, allowMissing: true).Select(static package => package.Value)); @@ -150,7 +150,7 @@ private string HashAssets(string path) { return identity; } - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); identity = File.Exists(path) ? Convert.ToHexStringLower( SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(LogicalAssets(JsonNode.Parse(File.ReadAllBytes(path))))) @@ -201,14 +201,14 @@ private string Hash(string path) { return cached; } - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); string identity; if (Directory.Exists(path)) { var files = new Dictionary(StringComparer.Ordinal); foreach (string file in PathBoundary.EnumerateFiles(path).Order(StringComparer.Ordinal)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); using FileStream stream = File.OpenRead(file); files[Path.GetRelativePath(path, file).Replace('\\', '/')] = Convert.ToHexStringLower(SHA256.HashData(stream)); } diff --git a/tools/Inno.Tooling.Validation/ValidationDocumentation.cs b/tools/Inno.Tooling.Validation/ValidationDocumentation.cs index a97825a0b..029b10e3d 100644 --- a/tools/Inno.Tooling.Validation/ValidationDocumentation.cs +++ b/tools/Inno.Tooling.Validation/ValidationDocumentation.cs @@ -16,7 +16,7 @@ internal static class ValidationDocumentation string? cache, string? identity, IReadOnlyDictionary projects, - CancellationToken cancellation, + CancellationToken cancellationToken, string? baseline = null ) { if ((cache is null) != (identity is null)) @@ -34,12 +34,12 @@ internal static class ValidationDocumentation using DocumentationSnapshot snapshot = await DocumentationStore.OpenAsync( cache, identity, - cancellationToken: cancellation + cancellationToken: cancellationToken ).ConfigureAwait(false); - DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(cancellation).ConfigureAwait(false); + DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(cancellationToken).ConfigureAwait(false); DocumentationReferenceInfo inventory = catalog.references.Single(reference => reference.model == "project-inventory"); using JsonDocument source = JsonDocument.Parse( - await snapshot.ReadReferenceAsync(inventory.path, cancellation).ConfigureAwait(false) + await snapshot.ReadReferenceAsync(inventory.path, cancellationToken).ConfigureAwait(false) ); var owners = new Dictionary(StringComparer.Ordinal); foreach (JsonElement owner in source.RootElement.EnumerateArray()) @@ -55,7 +55,7 @@ await snapshot.ReadReferenceAsync(inventory.path, cancellation).ConfigureAwait(f { throw new InvalidDataException("Native reference exclusion crosses its declared backend owner: " + path); } - if (!owners.TryAdd(name, new(path, actual.test, native))) + if (!owners.TryAdd(name, new Owner(path, actual.test, native))) { throw new InvalidDataException("Duplicate documentation project identity: " + name); } @@ -68,9 +68,9 @@ await snapshot.ReadReferenceAsync(inventory.path, cancellation).ConfigureAwait(f using DocumentationSnapshot previous = await DocumentationStore.OpenAsync( cache, baseline, - cancellationToken: cancellation + cancellationToken: cancellationToken ).ConfigureAwait(false); - DocumentationCatalogReport prior = await previous.ExportCatalogAsync(cancellation).ConfigureAwait(false); + DocumentationCatalogReport prior = await previous.ExportCatalogAsync(cancellationToken).ConfigureAwait(false); Dictionary pages = prior.pages.ToDictionary(static page => page.id, StringComparer.Ordinal); var changedPaths = new HashSet(StringComparer.Ordinal); foreach (DocumentationPageInfo page in catalog.pages) @@ -122,7 +122,7 @@ await snapshot.ReadReferenceAsync(inventory.path, cancellation).ConfigureAwait(f } } return new( - new(Path.GetFullPath(cache), snapshot.identity, snapshot.sourceTree, baseline), + new ValidationDocumentationBinding(Path.GetFullPath(cache), snapshot.identity, snapshot.sourceTree, baseline), catalog, owners, sourceIdentities, @@ -140,7 +140,7 @@ reference.model is "source-clr" or "runtime-script" or "editor-script" )) ) { using JsonDocument facts = JsonDocument.Parse( - await reader.ReadReferenceAsync(reference.path, cancellation).ConfigureAwait(false) + await reader.ReadReferenceAsync(reference.path, cancellationToken).ConfigureAwait(false) ); foreach (JsonElement project in facts.RootElement.GetProperty("projects").EnumerateArray()) { @@ -149,7 +149,7 @@ await reader.ReadReferenceAsync(reference.path, cancellation).ConfigureAwait(fal // source comparator, including its JSON whitespace normalization. if (!identities.TryAdd( key, - new( + new SourceFacts( Convert.ToHexStringLower(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(project))), project.GetProperty("symbols").GetArrayLength() == 0 ) @@ -183,13 +183,13 @@ reference.model is "runtime-script" or "editor-script" internal static async Task ReadCatalogAsync( ValidationPlan plan, DocumentationSnapshot snapshot, - CancellationToken cancellation + CancellationToken cancellationToken ) { if (plan.documentation is not { } binding || snapshot.identity != binding.snapshot || snapshot.sourceTree != binding.sourceTree) { throw new InvalidDataException("Documentation inputs differ from the frozen validation binding."); } - DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(cancellation).ConfigureAwait(false); + DocumentationCatalogReport catalog = await snapshot.ExportCatalogAsync(cancellationToken).ConfigureAwait(false); // A retained receipt still requires intact inputs, including the inventory that establishes project ownership. foreach (string reference in plan.checks.SelectMany(static check => check.documentation?.references ?? []) .Concat( @@ -199,7 +199,7 @@ CancellationToken cancellation ) .Distinct(StringComparer.Ordinal) ) { - _ = await snapshot.ReadReferenceAsync(reference, cancellation).ConfigureAwait(false); + _ = await snapshot.ReadReferenceAsync(reference, cancellationToken).ConfigureAwait(false); } return catalog; } @@ -235,7 +235,7 @@ IReadOnlyList references } else { - inputs.Add(new(reference.path, reference.identity)); + inputs.Add(new KeyValuePair(reference.path, reference.identity)); } } return ValidationInputs.Identity(inputs); diff --git a/tools/Inno.Tooling.Validation/ValidationDocumentationInputs.cs b/tools/Inno.Tooling.Validation/ValidationDocumentationInputs.cs index 75f88abdf..0f01375e5 100644 --- a/tools/Inno.Tooling.Validation/ValidationDocumentationInputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationDocumentationInputs.cs @@ -64,7 +64,9 @@ ValidationDependencyInputs dependencies plan.environment, check.documentation.configuration, check.documentation.target, - ValidationDependencyInputs.Required(check) ? dependencies.CapturePackages(selected) : new(StringComparer.Ordinal), + ValidationDependencyInputs.Required(check) + ? dependencies.CapturePackages(selected) + : new Dictionary(StringComparer.Ordinal), sources ); }).ToArray(); diff --git a/tools/Inno.Tooling.Validation/ValidationEnvironment.cs b/tools/Inno.Tooling.Validation/ValidationEnvironment.cs index 1d817fb0b..4df360892 100644 --- a/tools/Inno.Tooling.Validation/ValidationEnvironment.cs +++ b/tools/Inno.Tooling.Validation/ValidationEnvironment.cs @@ -17,9 +17,9 @@ internal static class ValidationEnvironment internal static async Task CaptureToolsAsync( string root, string dotnet, - CancellationToken cancellation + CancellationToken cancellationToken ) { - DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync(dotnet, root, cancellation).ConfigureAwait(false); + DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync(dotnet, root, cancellationToken).ConfigureAwait(false); var inputs = new Dictionary(StringComparer.Ordinal) { ["os"] = RuntimeInformation.OSDescription, @@ -57,7 +57,7 @@ CancellationToken cancellation pending.Enqueue(typeof(ValidationCommand).Assembly); while (pending.TryDequeue(out Assembly? assembly)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); if (!examined.Add(assembly)) { continue; @@ -89,17 +89,17 @@ CancellationToken cancellation { files.Add(automation); } - return new(sdk, inputs, CaptureContents(root, sdk.hostPath, files, cancellation)); + return new(sdk, inputs, CaptureContents(root, sdk.hostPath, files, cancellationToken)); } internal static async Task CaptureAsync( string root, string dotnet, - CancellationToken cancellation, + CancellationToken cancellationToken, IEnumerable? contexts = null, ToolSnapshot? tools = null ) { - tools ??= await CaptureToolsAsync(root, dotnet, cancellation).ConfigureAwait(false); + tools ??= await CaptureToolsAsync(root, dotnet, cancellationToken).ConfigureAwait(false); var inputs = new Dictionary(tools.inputs, StringComparer.Ordinal); foreach (KeyValuePair content in tools.contents) { @@ -110,7 +110,7 @@ internal static async Task CaptureAsync( ); var examined = new HashSet(files.Comparer); ValidationContext[] selectedContexts = contexts?.ToArray() ?? []; - string[] packageOwners = ValidationDependencyInputs.RestoredPackageDirectories(selectedContexts, cancellation); + string[] packageOwners = ValidationDependencyInputs.RestoredPackageDirectories(selectedContexts, cancellationToken); foreach (ValidationContext context in selectedContexts) { foreach (JsonElement snapshot in context.sdkGraph.EnumerateArray()) @@ -138,7 +138,7 @@ internal static async Task CaptureAsync( } } } - foreach (KeyValuePair content in CaptureContents(root, dotnet, files, cancellation)) + foreach (KeyValuePair content in CaptureContents(root, dotnet, files, cancellationToken)) { inputs.Add("external-content:" + content.Key, content.Value); } @@ -191,9 +191,9 @@ private static Dictionary CaptureContents( string root, string dotnet, IEnumerable files, - CancellationToken cancellation + CancellationToken cancellationToken ) { - var roots = new List(); + List roots = []; foreach (string path in files .Select(Path.GetFullPath) .OrderBy(static path => path.Length) @@ -209,14 +209,14 @@ CancellationToken cancellation Parallel.For( 0, roots.Count, - new ParallelOptions { MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), CancellationToken = cancellation }, + new ParallelOptions { MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), CancellationToken = cancellationToken }, index => identities[index] = NativeBuildFingerprint.Create( [], [new NativeBuildInput( "validation/" + ValidationPlanTransport.Logical(root, dotnet, roots[index]).Replace('\\', '/').TrimStart('/'), roots[index] )], - cancellation + cancellationToken ) ); var contents = new Dictionary(StringComparer.Ordinal); diff --git a/tools/Inno.Tooling.Validation/ValidationInputs.cs b/tools/Inno.Tooling.Validation/ValidationInputs.cs index 5523ab259..ed839c432 100644 --- a/tools/Inno.Tooling.Validation/ValidationInputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationInputs.cs @@ -15,16 +15,16 @@ internal static class ValidationInputs { internal static async Task> CaptureAsync( string root, - CancellationToken cancellation + CancellationToken cancellationToken ) { Task fileCapture = ValidationProcess.RunAsync( "git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], root, null, - cancellation + cancellationToken ); - Task stageCapture = ValidationProcess.RunAsync("git", ["ls-files", "--stage", "-z"], root, null, cancellation); + Task stageCapture = ValidationProcess.RunAsync("git", ["ls-files", "--stage", "-z"], root, null, cancellationToken); await Task.WhenAll(fileCapture, stageCapture).ConfigureAwait(false); string files = await fileCapture.ConfigureAwait(false); string staged = await stageCapture.ConfigureAwait(false); @@ -55,7 +55,7 @@ await Parallel.ForAsync( new ParallelOptions { MaxDegreeOfParallelism = Math.Min(Environment.ProcessorCount, 4), - CancellationToken = cancellation + CancellationToken = cancellationToken }, async ( index, @@ -93,17 +93,17 @@ internal static async Task FindContentChangesAsync( string root, string commit, IReadOnlyDictionary inputs, - CancellationToken cancellation + CancellationToken cancellationToken ) { string tree = await ValidationProcess.RunAsync( "git", ["ls-tree", "-r", "-z", commit], root, null, - cancellation + cancellationToken ).ConfigureAwait(false); var changes = new HashSet(StringComparer.Ordinal); - var blobs = new List>(); + List> blobs = []; foreach (string entry in tree.Split('\0', StringSplitOptions.RemoveEmptyEntries)) { int separator = entry.IndexOf('\t'); @@ -121,7 +121,7 @@ CancellationToken cancellation { string current = inputs.TryGetValue(path, out string? captured) ? captured - : await CaptureSubmoduleAsync(Resolve(root, path), metadata[2], cancellation).ConfigureAwait(false); + : await CaptureSubmoduleAsync(Resolve(root, path), metadata[2], cancellationToken).ConfigureAwait(false); if (current != metadata[2] && current != "unavailable:" + metadata[2]) { changes.Add(path); @@ -145,7 +145,7 @@ CancellationToken cancellation ["hash-object", "--stdin", "--no-filters"], root, null, - cancellation, + cancellationToken, new UTF8Encoding(false, true).GetString(link) ).ConfigureAwait(false); if (identity.Trim() != metadata[2]) @@ -160,7 +160,7 @@ CancellationToken cancellation } else { - blobs.Add(new(path, metadata[2])); + blobs.Add(new KeyValuePair(path, metadata[2])); } } if (blobs.Count != 0) @@ -171,7 +171,7 @@ CancellationToken cancellation ["hash-object", "--stdin-paths"], root, null, - cancellation, + cancellationToken, string.Join('\n', blobs.Select(static pair => QuoteGitPath(pair.Key))) + "\n" ).ConfigureAwait(false); string[] identities = content.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); @@ -191,7 +191,7 @@ CancellationToken cancellation ["hash-object", "--no-filters", "--stdin-paths"], root, null, - cancellation, + cancellationToken, string.Join('\n', different.Select(static pair => QuoteGitPath(pair.Key))) + "\n" ).ConfigureAwait(false); string[] rawIdentities = raw.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); @@ -262,10 +262,10 @@ IReadOnlyDictionary inputs .Distinct(StringComparer.Ordinal) .Select(path => new KeyValuePair(path, inputs.GetValueOrDefault(path, "missing"))) .Concat(BackendPayloads(plan, check)) - .Append(new("environment", plan.environment)) - .Append(new("configuration", plan.configuration)) + .Append(new KeyValuePair("environment", plan.environment)) + .Append(new KeyValuePair("configuration", plan.configuration)) .Append( - new( + new KeyValuePair( "context", check.context is null ? string.Empty @@ -280,7 +280,7 @@ check.context is null ) ) ) - .Append(new("definition", JsonSerializer.Serialize(check))) + .Append(new KeyValuePair("definition", JsonSerializer.Serialize(check))) ); internal static string Resolve( @@ -320,11 +320,11 @@ ValidationCheck check { foreach (string key in keys) { - yield return new("deployed:" + key, plan.backendProductPayloads![key]); + yield return new KeyValuePair("deployed:" + key, plan.backendProductPayloads![key]); } foreach (string owner in owners) { - yield return new("backend:" + owner, plan.backendOwnerPayloads![owner]); + yield return new KeyValuePair("backend:" + owner, plan.backendOwnerPayloads![owner]); } yield break; } @@ -335,20 +335,20 @@ ValidationCheck check // A product can load its entire deployed closure, including tools from another host. foreach (BackendPackageReceipt package in plan.backendPackages) { - yield return new("backend:" + package.target, package.sha256); + yield return new KeyValuePair("backend:" + package.target, package.sha256); } yield break; } foreach (string owner in owners) { - yield return new("backend:" + owner, plan.backendOwnerPayloads![owner]); + yield return new KeyValuePair("backend:" + owner, plan.backendOwnerPayloads![owner]); } } private static async Task CaptureSubmoduleAsync( string path, string expectedRevision, - CancellationToken cancellation + CancellationToken cancellationToken ) { // Check checkout contents, never the mutable Git object store or its size/time index cache. if (!File.Exists(Path.Combine(path, ".git")) && !Directory.Exists(Path.Combine(path, ".git"))) @@ -360,15 +360,21 @@ CancellationToken cancellation ["rev-parse", "HEAD"], path, null, - cancellation + cancellationToken ).ConfigureAwait(false)).Trim(); - string dirty = await ValidationProcess.RunAsync("git", ["status", "--porcelain"], path, null, cancellation).ConfigureAwait(false); + string dirty = await ValidationProcess.RunAsync( + "git", + ["status", "--porcelain"], + path, + null, + cancellationToken + ).ConfigureAwait(false); if (dirty.Length != 0 || (await FindContentChangesAsync( path, revision, new Dictionary(), - cancellation + cancellationToken ).ConfigureAwait(false)).Length != 0 ) { throw new InvalidDataException( diff --git a/tools/Inno.Tooling.Validation/ValidationOutputs.cs b/tools/Inno.Tooling.Validation/ValidationOutputs.cs index 68aaa7acb..9305f3391 100644 --- a/tools/Inno.Tooling.Validation/ValidationOutputs.cs +++ b/tools/Inno.Tooling.Validation/ValidationOutputs.cs @@ -13,7 +13,7 @@ internal static class ValidationOutputs internal static Dictionary Capture( ValidationPlan plan, ValidationCheck check, - CancellationToken cancellation, + CancellationToken cancellationToken, Dictionary? directoryCache = null ) { var outputs = new Dictionary(StringComparer.Ordinal); @@ -75,7 +75,7 @@ internal static Dictionary Capture( var files = new Dictionary(StringComparer.Ordinal); foreach (string file in EnumerateFiles(directory).Order(StringComparer.Ordinal)) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); using FileStream stream = File.OpenRead(file); files[Path.GetRelativePath(directory, file).Replace('\\', '/')] = Convert.ToHexStringLower(SHA256.HashData(stream)); } @@ -93,7 +93,7 @@ internal static bool Matches( ValidationPlan plan, ValidationCheck check, ValidationResult result, - CancellationToken cancellation, + CancellationToken cancellationToken, Dictionary? directoryCache = null ) { if (result.outputs is null) @@ -103,7 +103,7 @@ internal static bool Matches( try { return ValidationInputs.Identity( - Capture(plan, check, cancellation, directoryCache) + Capture(plan, check, cancellationToken, directoryCache) ) == ValidationInputs.Identity(result.outputs); } catch (Exception failure) when (failure is IOException or UnauthorizedAccessException) diff --git a/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs b/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs index d14377fcb..def5c60ef 100644 --- a/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs +++ b/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs @@ -34,7 +34,7 @@ internal static partial class ValidationPlanner internal static async Task BindBackendsAsync( ValidationPlan plan, string packages, - CancellationToken cancellation, + CancellationToken cancellationToken, string? evidence = null ) { if (plan.backendStore is null || plan.backendPackages is not null || plan.nativeDependencies is null) @@ -155,7 +155,7 @@ internal static async Task BindBackendsAsync( BackendInputPlan expected = await BackendInputsAsync( plan, target, - cancellation, + cancellationToken, selectionBytes, configuration ).ConfigureAwait(false); @@ -187,7 +187,7 @@ internal static async Task BindBackendsAsync( { ValidationResult[] certificates = JsonSerializer.Deserialize(File.ReadAllBytes(evidence)) ?? throw new InvalidDataException("Missing backend test certification inventory."); - var selected = new List(); + List selected = []; foreach (ValidationCheck check in bound.checks.Where(static check => ( check.kind == "test" && check.reusable @@ -216,7 +216,7 @@ internal static async Task BindBackendsAsync( internal static async Task BackendInputsAsync( ValidationPlan plan, string target, - CancellationToken cancellation, + CancellationToken cancellationToken, byte[]? selectionBytes = null, string? configuration = null ) { @@ -233,7 +233,7 @@ check.exclusion is null && check.context is not null && plan.contexts[check.context].properties.GetValueOrDefault("Configuration") == configuration )) ) { - return new(plan.commit, target, configuration, new(StringComparer.Ordinal), [], [], missing, null); + return new(plan.commit, target, configuration, new Dictionary(StringComparer.Ordinal), [], [], missing, null); } ValidationContext graph = configuration == plan.configuration ? plan.contexts["managed"] @@ -267,7 +267,7 @@ check.exclusion is null && check.context is not null string? hostTarget = tool.GetProperty("TargetId").GetString(); string? toolConfiguration = tool.GetProperty("Configuration").GetString(); tools[project.path].Add( - new( + new BackendNativeProduct( tool.GetProperty("Identity").GetString()!, string.IsNullOrEmpty(hostTarget) ? plan.backendHost ?? target : hostTarget, (string.IsNullOrEmpty(toolConfiguration) ? configuration : toolConfiguration).ToLowerInvariant() @@ -335,7 +335,11 @@ check.exclusion is null && check.context is not null } } - DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync(plan.dotnet, plan.root, cancellation).ConfigureAwait(false); + DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync( + plan.dotnet, + plan.root, + cancellationToken + ).ConfigureAwait(false); string sdkRoot = Path.GetDirectoryName(sdk.cliPath)!; var common = new Dictionary(StringComparer.Ordinal) { @@ -359,7 +363,7 @@ check.exclusion is null && check.context is not null "Roslyn/bincore/Microsoft.CodeAnalysis.CSharp.dll" }) { using FileStream file = File.OpenRead(Path.Combine(sdkRoot, compiler)); - common[compiler] = Convert.ToHexStringLower(await SHA256.HashDataAsync(file, cancellation).ConfigureAwait(false)); + common[compiler] = Convert.ToHexStringLower(await SHA256.HashDataAsync(file, cancellationToken).ConfigureAwait(false)); } foreach (KeyValuePair pair in plan.inputs.Where(static pair => ( pair.Key is "global.json" or ".editorconfig" or "Directory.Packages.props" @@ -373,7 +377,7 @@ pair.Key is "global.json" or ".editorconfig" or "Directory.Packages.props" var references = new Dictionary(StringComparer.Ordinal); foreach (KeyValuePair> pair in owners) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); var current = new Dictionary(StringComparer.Ordinal); foreach (string source in pair.Value) { @@ -454,7 +458,7 @@ pair.Key is "tests/ci/Build-BackendPrebuilt.ps1" or "tests/ci/New-BackendPrebuil ))) { proofInputs[input.Key] = input.Value; } - productInputs.Add(owner, new(ValidationInputs.Identity(proofInputs), closure.Where(IsBackend).ToArray())); + productInputs.Add(owner, new BackendConsumerInputs(ValidationInputs.Identity(proofInputs), closure.Where(IsBackend).ToArray())); } return new( plan.commit, diff --git a/tools/Inno.Tooling.Validation/ValidationPlanner.cs b/tools/Inno.Tooling.Validation/ValidationPlanner.cs index b31f67ab2..3bf372b9e 100644 --- a/tools/Inno.Tooling.Validation/ValidationPlanner.cs +++ b/tools/Inno.Tooling.Validation/ValidationPlanner.cs @@ -22,7 +22,7 @@ internal static async Task CreateAsync( string configuration, string artifacts, bool full, - CancellationToken cancellation, + CancellationToken cancellationToken, bool extended = false, string? documentationCache = null, string? documentationSnapshot = null, @@ -62,7 +62,7 @@ internal static async Task CreateAsync( Stopwatch elapsed = Stopwatch.StartNew(); var timings = new Dictionary(StringComparer.Ordinal); double previousStage = 0; - Dictionary inputs = await ValidationInputs.CaptureAsync(root, cancellation).ConfigureAwait(false); + Dictionary inputs = await ValidationInputs.CaptureAsync(root, cancellationToken).ConfigureAwait(false); string commit = (await GitAsync("rev-parse", "HEAD").ConfigureAwait(false)).Trim(); string mergeBase = (await GitAsync("merge-base", baseline, commit).ConfigureAwait(false)).Trim(); var changes = new HashSet( @@ -89,7 +89,7 @@ internal static async Task CreateAsync( "HEAD" ).ConfigureAwait(false)).Split('\0', StringSplitOptions.RemoveEmptyEntries) ); - changes.UnionWith(await ValidationInputs.FindContentChangesAsync(root, commit, inputs, cancellation).ConfigureAwait(false)); + changes.UnionWith(await ValidationInputs.FindContentChangesAsync(root, commit, inputs, cancellationToken).ConfigureAwait(false)); changes.UnionWith( (await GitAsync( "ls-files", @@ -124,7 +124,7 @@ internal static async Task CreateAsync( ValidationEnvironment.ToolSnapshot toolSnapshot = await ValidationEnvironment.CaptureToolsAsync( root, dotnet, - cancellation + cancellationToken ).ConfigureAwait(false); DotNetSdkDescriptor sdk = toolSnapshot.sdk; RecordStage("sdk-environment"); @@ -133,7 +133,7 @@ internal static async Task CreateAsync( sdk, paths.Select(path => Path.Combine(root, path)).ToArray(), properties, - cancellation + cancellationToken ).ConfigureAwait(false); RecordStage("sdk-capture"); using JsonDocument graph = JsonDocument.Parse(captured); @@ -158,10 +158,10 @@ internal static async Task CreateAsync( documentationCache, documentationSnapshot, byPath, - cancellation, + cancellationToken, documentationBaseline ).ConfigureAwait(false); - var diagnostics = new List(); + List diagnostics = []; foreach (string change in changes) { ValidationProject[] owners = projects.Where(project => ( @@ -465,7 +465,7 @@ internal static async Task CreateAsync( { return new( null, - new( + new ValidationPreparation( "Blocked", "NativeSources", root, @@ -527,11 +527,11 @@ internal static async Task CreateAsync( sdk, paths.Select(path => Path.Combine(root, path)).ToArray(), evaluationProperties, - cancellation + cancellationToken ).ConfigureAwait(false); using JsonDocument nativeGraph = JsonDocument.Parse(nativeCapture); RequireCompilerInputs(nativeGraph.RootElement); - contexts.Add("native", new(nativeProperties, nativeGraph.RootElement.Clone())); + contexts.Add("native", new ValidationContext(nativeProperties, nativeGraph.RootElement.Clone())); nativeProjects = nativeGraph.RootElement.EnumerateArray() .Select(snapshot => ValidationProject.Read(root, snapshot)) .ToDictionary(static project => project.path, StringComparer.Ordinal); @@ -585,9 +585,9 @@ path is "global.json" )); inputSets.Add("tooling", toolingInputs); inputSets.Add("native-sources", submoduleInputs); - var checks = new List - { - new( + List checks = + [ + new ValidationCheck( "instructions", "instructions", "AGENTS.md", @@ -598,7 +598,7 @@ path is "global.json" true, null ), - new( + new ValidationCheck( "architecture", "architecture", "tools/Inno.Tooling.Architecture", @@ -620,12 +620,12 @@ path is "global.json" true, null ) - }; + ]; if (changes.Any(static path => path.StartsWith(".agents/", StringComparison.Ordinal) || path is "AGENTS.md" or "CONTRIBUTING.md") || full ) { checks.Add( - new( + new ValidationCheck( "agent-documents", "agent-documents", ".agents", @@ -647,7 +647,7 @@ path is "global.json" if (documentation is not null) { checks.Add( - new( + new ValidationCheck( "documentation", "documentation", "InnoEngine.Docs", @@ -660,7 +660,7 @@ path is "global.json" .ToArray(), true, null, - documentation: new([], [], documentation.catalog.contentIdentity, configuration, null) + documentation: new ValidationDocumentationCheck([], [], documentation.catalog.contentIdentity, configuration, null) ) ); } @@ -673,7 +673,7 @@ path is "global.json" || path.StartsWith("tools/Inno.Tooling.Validation/", StringComparison.Ordinal) ))) { checks.Add( - new( + new ValidationCheck( "ci-contracts", gateOnly ? "gate-contracts" : "ci-contracts", "tests/ci", @@ -747,7 +747,7 @@ path is "global.json" if (compile) { checks.Add( - new( + new ValidationCheck( "build:" + project.path, "build", project.path, @@ -766,7 +766,7 @@ path is "global.json" if (project.test) { checks.Add( - new( + new ValidationCheck( "test:" + project.path, "test", project.path, @@ -822,7 +822,7 @@ void Visit(ValidationProject node) .Order(StringComparer.Ordinal) .ToArray(); checks.Add( - new( + new ValidationCheck( "compiled-api:" + group.Key, "api", "tools/Inno.Tooling.Architecture", @@ -852,7 +852,7 @@ void Visit(ValidationProject node) if (editorBuild is not null) { checks.Add( - new( + new ValidationCheck( "editor-products", "products", editorBuild.owner, @@ -879,7 +879,7 @@ void Visit(ValidationProject node) if (editorBuild is not null && (extended || profile == ValidationProfile.Performance)) { checks.Add( - new( + new ValidationCheck( "native-hot-builds", "hot-builds", editorBuild.owner, @@ -905,7 +905,7 @@ void Visit(ValidationProject node) { checks.Insert( 0, - new( + new ValidationCheck( "cold-inputs", "cold-inputs", "build", @@ -942,11 +942,11 @@ void Visit(ValidationProject node) sdk, paths.Select(path => Path.Combine(root, path)).ToArray(), releaseInputsProperties, - cancellation + cancellationToken ).ConfigureAwait(false); using JsonDocument backendGraph = JsonDocument.Parse(backendCapture); RequireCompilerInputs(backendGraph.RootElement); - contexts.Add("backend-release", new(releaseInputsProperties, backendGraph.RootElement.Clone())); + contexts.Add("backend-release", new ValidationContext(releaseInputsProperties, backendGraph.RootElement.Clone())); } var releaseProperties = new Dictionary(contexts["native"].properties) { @@ -963,11 +963,11 @@ void Visit(ValidationProject node) sdk, paths.Select(path => Path.Combine(root, path)).ToArray(), evaluationProperties, - cancellation + cancellationToken ).ConfigureAwait(false); using JsonDocument releaseGraph = JsonDocument.Parse(releaseCapture); RequireCompilerInputs(releaseGraph.RootElement); - contexts.Add(releaseContext, new(releaseProperties, releaseGraph.RootElement.Clone())); + contexts.Add(releaseContext, new ValidationContext(releaseProperties, releaseGraph.RootElement.Clone())); releaseProjects = releaseGraph.RootElement.EnumerateArray() .Select(snapshot => ValidationProject.Read(root, snapshot)) .ToDictionary(static project => project.path, StringComparer.Ordinal); @@ -987,7 +987,7 @@ void Visit(ValidationProject node) ); } var releaseInputs = new HashSet(StringComparer.Ordinal) { "@tooling", "@native-sources" }; - var releaseBuilds = new List(); + List releaseBuilds = []; string[] releaseRoots = [editorBuild.owner, C_BUILD_ENTRY]; foreach (string owner in releaseRoots) { @@ -997,7 +997,7 @@ void Visit(ValidationProject node) if (releaseContext != "native") { checks.Add( - new( + new ValidationCheck( id, "build", owner, @@ -1019,7 +1019,7 @@ void Visit(ValidationProject node) if (releaseContext != "native") { checks.Add( - new( + new ValidationCheck( "compiled-api:release", "api", "tools/Inno.Tooling.Architecture", @@ -1041,7 +1041,7 @@ void Visit(ValidationProject node) ) ); checks.Add( - new( + new ValidationCheck( "editor-release-products", "products", editorBuild.owner, @@ -1060,7 +1060,7 @@ void Visit(ValidationProject node) ); } checks.Add( - new( + new ValidationCheck( "support-pack", "support-pack", C_BUILD_ENTRY, @@ -1097,7 +1097,7 @@ void Visit(ValidationProject node) string playerOwner = Path.GetRelativePath(root, players[0].GetProperty("Path").GetString()!).Replace('\\', '/'); VisitRelease(playerOwner); checks.Add( - new( + new ValidationCheck( "native-aot-restore", "restore-aot", playerOwner, @@ -1115,7 +1115,7 @@ void Visit(ValidationProject node) ); // Restore-only inputs still invalidate the bundle, but only built roots provide compiled output instances. checks.Add( - new( + new ValidationCheck( "release-bundle", "release-bundle", editorBuild.owner, @@ -1154,7 +1154,7 @@ void VisitRelease(string owner) string environmentIdentity = await ValidationEnvironment.CaptureAsync( root, sdk.hostPath, - cancellation, + cancellationToken, contexts.Values, toolSnapshot ).ConfigureAwait(false); @@ -1170,11 +1170,11 @@ int index checks = checks.Select(check => check with { prerequisites = check.prerequisites - .Concat(check.kind == "build" ? ["instructions", "architecture"] : Array.Empty()) + .Concat(check.kind == "build" ? ["instructions", "architecture"] : []) .Concat( extended && check.context is not (null or "managed") && check.kind != "cold-inputs" ? ["cold-inputs"] - : Array.Empty() + : [] ) .Distinct(StringComparer.Ordinal) .ToArray() @@ -1246,7 +1246,7 @@ int index } } return new( - new( + new ValidationPlan( root, mergeBase, commit, @@ -1342,7 +1342,7 @@ IEnumerable roots { string targetProperty = property == "InnoTestNativeProduct" ? "InnoTestNativeTarget" : "InnoProductTarget"; string declaredTarget = declared.GetProperty(targetProperty).GetString() ?? string.Empty; - yield return new( + yield return new ValidationNativeRequest( declaredTarget.Length == 0 ? context.properties["InnoNativeTarget"] : declaredTarget, context.properties["Configuration"], product @@ -1354,7 +1354,11 @@ IEnumerable roots if (!productOwned && declared.GetProperty("BindGenGeneratedBindings").GetString() == "true" && declared.GetProperty("InnoBindingProductId").GetString() is { Length: > 0 } bindingProduct ) { - yield return new(context.properties["InnoNativeTarget"], context.properties["Configuration"], bindingProduct); + yield return new ValidationNativeRequest( + context.properties["InnoNativeTarget"], + context.properties["Configuration"], + bindingProduct + ); } JsonElement items = variant.GetProperty("Items"); foreach (JsonElement dependency in items.GetProperty("InnoNativeDependency").EnumerateArray()) @@ -1369,7 +1373,7 @@ IEnumerable roots "A native build dependency must declare product, target and configuration: " + owner ); } - yield return new(dependencyTarget, dependencyConfiguration, product); + yield return new ValidationNativeRequest(dependencyTarget, dependencyConfiguration, product); } foreach (string reference in node.references) { @@ -1384,7 +1388,7 @@ void AddDocumentationChecks() foreach (KeyValuePair excluded in exampleExclusions) { checks.Add( - new( + new ValidationCheck( "documentation-examples:excluded:" + excluded.Key.id, "documentation-examples", "InnoEngine.Docs", @@ -1395,7 +1399,7 @@ void AddDocumentationChecks() false, excluded.Value, layer: "contract", - documentation: new( + documentation: new ValidationDocumentationCheck( [], [excluded.Key.id], ValidationDocumentation.PageIdentity([excluded.Key]), @@ -1459,7 +1463,7 @@ void AddDocumentationChecks() )) ); checks.Add( - new( + new ValidationCheck( "documentation-api:" + group.Key.context + ":" @@ -1479,7 +1483,7 @@ void AddDocumentationChecks() group.Key.context, "contract", paths, - new(references, [], identity, configuration, group.Key.target) + new ValidationDocumentationCheck(references, [], identity, configuration, group.Key.target) ) ); } @@ -1487,7 +1491,7 @@ void AddDocumentationChecks() { ValidationCheck? prepared = builds.SingleOrDefault(check => check.owner == owner); checks.Add( - new( + new ValidationCheck( "documentation-api-missing:" + owner, "documentation-missing", owner, @@ -1500,7 +1504,7 @@ void AddDocumentationChecks() prepared?.context, "contract", prepared is null ? null : [owner], - prepared is null ? null : new( + prepared is null ? null : new ValidationDocumentationCheck( [], [], string.Empty, @@ -1545,7 +1549,7 @@ void AddDocumentationChecks() )) ); checks.Add( - new( + new ValidationCheck( "documentation-api:source:" + (group.Key ?? "default"), "documentation-api", "InnoEngine.Docs", @@ -1561,7 +1565,7 @@ void AddDocumentationChecks() "managed", "contract", paths, - new(references, [], identity, configuration, group.Key) + new ValidationDocumentationCheck(references, [], identity, configuration, group.Key) ) ); } @@ -1586,7 +1590,7 @@ void AddDocumentationChecks() string[] pages = group.Select(static page => page.id).Order(StringComparer.Ordinal).ToArray(); string[] scriptReferences = ValidationDocumentation.ExampleReferences(selected, group.ToArray()); checks.Add( - new( + new ValidationCheck( "documentation-examples:" + group.Key, "documentation-examples", "InnoEngine.Docs", @@ -1603,7 +1607,7 @@ void AddDocumentationChecks() group.Key, "contract", paths, - new( + new ValidationDocumentationCheck( scriptReferences, pages, ValidationDocumentation.ExampleIdentity(selected, group.ToArray(), scriptReferences), @@ -1615,7 +1619,7 @@ void AddDocumentationChecks() } } - Task GitAsync(params string[] arguments) => ValidationProcess.RunAsync("git", arguments, root, null, cancellation); + Task GitAsync(params string[] arguments) => ValidationProcess.RunAsync("git", arguments, root, null, cancellationToken); string[] CapturedInputs(IEnumerable declared) { diff --git a/tools/Inno.Tooling.Validation/ValidationProcess.cs b/tools/Inno.Tooling.Validation/ValidationProcess.cs index 62f5714f2..3be5c08c8 100644 --- a/tools/Inno.Tooling.Validation/ValidationProcess.cs +++ b/tools/Inno.Tooling.Validation/ValidationProcess.cs @@ -18,7 +18,7 @@ internal static async Task RunAsync( IEnumerable arguments, string directory, string? log, - CancellationToken cancellation, + CancellationToken cancellationToken, string? input = null ) { var start = new ProcessStartInfo(executable) @@ -72,10 +72,10 @@ internal static async Task RunAsync( { if (input is not null) { - await process.StandardInput.WriteAsync(input.AsMemory(), cancellation).ConfigureAwait(false); + await process.StandardInput.WriteAsync(input.AsMemory(), cancellationToken).ConfigureAwait(false); process.StandardInput.Close(); } - await process.WaitForExitAsync(cancellation).ConfigureAwait(false); + await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); } catch { diff --git a/tools/Inno.Tooling.Validation/ValidationProductInput.cs b/tools/Inno.Tooling.Validation/ValidationProductInput.cs index 8f843fe09..f8616273b 100644 --- a/tools/Inno.Tooling.Validation/ValidationProductInput.cs +++ b/tools/Inno.Tooling.Validation/ValidationProductInput.cs @@ -17,12 +17,12 @@ internal static async Task PrepareAsync( ValidationPlan plan, string directory, string project, - CancellationToken cancellation + CancellationToken cancellationToken ) { using JsonDocument document = JsonDocument.Parse( await File.ReadAllTextAsync( Path.Combine(plan.root, "tests", "fixtures", "editor-ui", "consumer.json"), - cancellation + cancellationToken ).ConfigureAwait(false) ); string repository = document.RootElement.GetProperty("repository").GetString()!; @@ -49,14 +49,14 @@ await File.ReadAllTextAsync( ["-C", checkout, "remote", "get-url", "origin"], plan.root, null, - cancellation + cancellationToken ).ConfigureAwait(false); string bare = await ValidationProcess.RunAsync( "git", ["-C", checkout, "rev-parse", "--is-bare-repository"], plan.root, null, - cancellation + cancellationToken ).ConfigureAwait(false); if (origin.Trim() != repository || bare.Trim() != "true") { @@ -69,7 +69,7 @@ await ValidationProcess.RunAsync( ["-C", checkout, "fsck", "--full", "--strict"], plan.root, Path.Combine(directory, "consumer-integrity.log"), - cancellation + cancellationToken ).ConfigureAwait(false); } catch (InvalidOperationException) @@ -87,23 +87,23 @@ await ValidationProcess.RunAsync( ["-c", "core.longpaths=true", "init", "--bare", staging], plan.root, Path.Combine(directory, "consumer-initialize.log"), - cancellation + cancellationToken ).ConfigureAwait(false); await ValidationProcess.RunAsync( "git", ["-c", "core.longpaths=true", "-C", staging, "config", "core.longpaths", "true"], plan.root, null, - cancellation + cancellationToken ).ConfigureAwait(false); await ValidationProcess.RunAsync( "git", ["-C", staging, "remote", "add", "origin", repository], plan.root, null, - cancellation + cancellationToken ).ConfigureAwait(false); - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); Directory.Move(staging, checkout); } if (!await HasCommitAsync(checkout).ConfigureAwait(false)) @@ -117,7 +117,7 @@ await ValidationProcess.RunAsync( ["-C", adjacent, "remote", "get-url", "origin"], plan.root, null, - cancellation + cancellationToken ).ConfigureAwait(false); if (origin.Trim().Equals(repository, StringComparison.OrdinalIgnoreCase) && await HasCommitAsync(adjacent).ConfigureAwait(false) @@ -129,21 +129,21 @@ await ValidationProcess.RunAsync( await File.WriteAllTextAsync( Path.Combine(directory, "consumer-source.json"), JsonSerializer.Serialize(new { repository, commit, source = input }), - cancellation + cancellationToken ).ConfigureAwait(false); await ValidationProcess.RunAsync( "git", ["-C", checkout, "fetch", "--no-tags", "--depth=1", input, commit], plan.root, Path.Combine(directory, "consumer-fetch.log"), - cancellation + cancellationToken ).ConfigureAwait(false); await ValidationProcess.RunAsync( "git", ["-C", checkout, "fsck", "--full", "--strict"], plan.root, Path.Combine(directory, "consumer-import-integrity.log"), - cancellation + cancellationToken ).ConfigureAwait(false); } string revision = await ValidationProcess.RunAsync( @@ -151,7 +151,7 @@ await ValidationProcess.RunAsync( ["-C", checkout, "rev-parse", commit + "^{commit}"], plan.root, null, - cancellation + cancellationToken ).ConfigureAwait(false); if (revision.Trim() != commit) { @@ -163,12 +163,12 @@ await ValidationProcess.RunAsync( ["-C", checkout, "archive", "--format=zip", "--output=" + archive, commit, "--", prefix], plan.root, Path.Combine(directory, "consumer-archive.log"), - cancellation + cancellationToken ).ConfigureAwait(false); using ZipArchive contents = ZipFile.OpenRead(archive); foreach (ZipArchiveEntry entry in contents.Entries) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); string file = entry.FullName; if (!file.StartsWith(prefix, StringComparison.Ordinal) || file.Contains('\\') @@ -198,7 +198,7 @@ await ValidationProcess.RunAsync( ["-C", input, "cat-file", "-e", commit + "^{commit}"], plan.root, null, - cancellation + cancellationToken ).ConfigureAwait(false); return true; } diff --git a/tools/Inno.Tooling.Validation/ValidationRunner.cs b/tools/Inno.Tooling.Validation/ValidationRunner.cs index 3fcedd29c..8b448b9aa 100644 --- a/tools/Inno.Tooling.Validation/ValidationRunner.cs +++ b/tools/Inno.Tooling.Validation/ValidationRunner.cs @@ -23,7 +23,7 @@ internal static async Task RunAsync( ValidationPlan plan, string directory, ValidationEvidence? previous, - CancellationToken cancellation, + CancellationToken cancellationToken, ValidationShard? shard = null, IReadOnlyList? prerequisites = null, bool continuation = false, @@ -37,13 +37,13 @@ internal static async Task RunAsync( : await DocumentationStore.OpenAsync( plan.documentation.cacheRoot, plan.documentation.snapshot, - cancellationToken: cancellation + cancellationToken: cancellationToken ).ConfigureAwait(false); DocumentationCatalogReport? documentationCatalog = documentationSnapshot is null ? null - : await ValidationDocumentation.ReadCatalogAsync(plan, documentationSnapshot, cancellation).ConfigureAwait(false); + : await ValidationDocumentation.ReadCatalogAsync(plan, documentationSnapshot, cancellationToken).ConfigureAwait(false); var results = new List(imported); - var failures = new List(); + List failures = []; double closingSeconds = 0; var batchSeconds = new Dictionary(StringComparer.Ordinal); DateTimeOffset started = DateTimeOffset.UtcNow; @@ -52,11 +52,11 @@ internal static async Task RunAsync( await File.WriteAllTextAsync( Path.Combine(directory, "execution-plan.json"), JsonSerializer.Serialize(plan, new JsonSerializerOptions { WriteIndented = true }), - cancellation + cancellationToken ).ConfigureAwait(false); Console.WriteLine("Validation phase: acquire the selected workspace ownership and freeze current inputs."); using CoordinatedFileLease? workspace = checks.Any(static check => check.kind == "build" && check.exclusion is null) - ? await ValidationWorkspace.AcquireAsync(plan, cancellation).ConfigureAwait(false) + ? await ValidationWorkspace.AcquireAsync(plan, cancellationToken).ConfigureAwait(false) : null; if (retainedOutputs is not null) { @@ -64,17 +64,17 @@ await File.WriteAllTextAsync( { throw new InvalidDataException("Restoring compilation outputs requires a continuation with workspace ownership."); } - ValidationWorkspace.RestoreOutputs(plan, retainedOutputs, cancellation); + ValidationWorkspace.RestoreOutputs(plan, retainedOutputs, cancellationToken); } foreach (KeyValuePair context in plan.contexts) { await File.WriteAllTextAsync( Path.Combine(directory, context.Key + "-sdk-graph.json"), context.Value.sdkGraph.GetRawText(), - cancellation + cancellationToken ).ConfigureAwait(false); } - Dictionary current = await ValidationInputs.CaptureAsync(plan.root, cancellation).ConfigureAwait(false); + Dictionary current = await ValidationInputs.CaptureAsync(plan.root, cancellationToken).ConfigureAwait(false); if (ValidationInputs.Identity(current) != plan.tree) { string[] changed = current.Keys.Union(plan.inputs.Keys).Where(path => ( @@ -109,7 +109,7 @@ await ValidationProcess.RunAsync( ], plan.root, Path.Combine(directory, solution.Key + "-restore-retained.log"), - cancellation + cancellationToken ).ConfigureAwait(false); } } @@ -121,7 +121,7 @@ await ValidationProcess.RunAsync( var testFailures = new Dictionary(StringComparer.Ordinal); var testDetails = new Dictionary(StringComparer.Ordinal); var outputDigests = new Dictionary(StringComparer.Ordinal); - var dependencyInputs = new ValidationDependencyInputs(plan, cancellation); + var dependencyInputs = new ValidationDependencyInputs(plan, cancellationToken); var compilationGraphs = new Dictionary(StringComparer.Ordinal); HashSet? invalidated = ValidationShards.InvalidatedChecks(plan, previous); var reused = new Dictionary(StringComparer.Ordinal); @@ -143,7 +143,7 @@ await ValidationProcess.RunAsync( status = "NotApplicable"; detail = check.exclusion; } - else if (cancellation.IsCancellationRequested) + else if (cancellationToken.IsCancellationRequested) { status = "Blocked"; detail = "Validation was canceled before this required check completed."; @@ -185,7 +185,7 @@ await ValidationProcess.RunAsync( switch (check.kind) { case "release-bundle": - ValidationDeliverables.Create(plan, check, cancellation); + ValidationDeliverables.Create(plan, check, cancellationToken); break; case "cold-inputs": foreach (string cache in new[] { "artifacts/native", "artifacts/bindings" }) @@ -260,7 +260,7 @@ await ValidationProcess.RunAsync( ], plan.root, Path.Combine(directory, "native-aot-restore.log"), - cancellation + cancellationToken ).ConfigureAwait(false); } break; @@ -274,7 +274,7 @@ await ValidationProcess.RunAsync( plan.dotnet, "--sdk-snapshot", graphPath - ], cancellation) != 0 + ], cancellationToken) != 0 ) { throw new InvalidDataException("Repository architecture validation failed."); } @@ -303,7 +303,7 @@ await ValidationProcess.RunAsync( "--sdk-snapshot", await ResolveCompilationGraphAsync(contextID).ConfigureAwait(false), ..projects - ], cancellation) != 0 + ], cancellationToken) != 0 ) { throw new InvalidDataException("Affected compiled API boundaries failed."); } @@ -337,7 +337,7 @@ await ResolveCompilationGraphAsync(contextID).ConfigureAwait(false), capturePath, ..captureTarget, ..captureOwners.SelectMany(static owner => new[] { "--project", owner }) - ], cancellation); + ], cancellationToken); detail += " Unverified source facts retained at " + capturePath + "; review and compare the resulting documentation in a subsequent validation."; } break; @@ -346,7 +346,9 @@ await ResolveCompilationGraphAsync(contextID).ConfigureAwait(false), { throw new InvalidDataException("Required external documentation snapshot is unavailable."); } - documentationCatalog ??= await documentationSnapshot.ExportCatalogAsync(cancellation).ConfigureAwait(false); + documentationCatalog ??= await documentationSnapshot.ExportCatalogAsync( + cancellationToken + ).ConfigureAwait(false); string[] missing = plan.inputSets.Keys.Where(static path => path.EndsWith(".csproj", StringComparison.Ordinal)) // Platform implementations remain source provenance, not reader-facing documentation owners. .Where(static path => !path.StartsWith("platforms/", StringComparison.Ordinal)) @@ -390,14 +392,14 @@ await ResolveCompilationGraphAsync(contextID).ConfigureAwait(false), "--output", Path.Combine(directory, check.id.Replace(':', '-') + ".json"), ..referenceArguments - ], cancellation).ConfigureAwait(false) + ], cancellationToken).ConfigureAwait(false) != 0 ) { throw new InvalidDataException("Selected documentation source references differ from current source."); } break; case "agent-documents": - if (ArchitectureValidator.Execute([plan.root, "--agent-documents-only"], cancellation) != 0) + if (ArchitectureValidator.Execute([plan.root, "--agent-documents-only"], cancellationToken) != 0) { throw new InvalidDataException("Agent document structure or links failed."); } @@ -407,9 +409,11 @@ await ResolveCompilationGraphAsync(contextID).ConfigureAwait(false), { throw new InvalidDataException("Required canonical example discovery is empty."); } - documentationCatalog ??= await documentationSnapshot.ExportCatalogAsync(cancellation).ConfigureAwait(false); + documentationCatalog ??= await documentationSnapshot.ExportCatalogAsync( + cancellationToken + ).ConfigureAwait(false); string[] pages = check.documentation.pages.SelectMany(static page => new[] { "--page", page }).ToArray(); - var scriptArguments = new List(); + List scriptArguments = []; if (documentationCatalog.pages.Any(page => ( check.documentation.pages.Contains(page.id, StringComparer.Ordinal) && page.examples?.mode is "runtime-script" or "editor-script" @@ -432,7 +436,7 @@ await ResolveCompilationGraphAsync(contextID).ConfigureAwait(false), await File.WriteAllTextAsync( Path.Combine(project, "Assets", "DocumentationProbe.cs"), "public sealed class DocumentationProbe { }", - cancellation + cancellationToken ).ConfigureAwait(false); await ValidationProcess.RunAsync( plan.dotnet, @@ -451,7 +455,7 @@ await ValidationProcess.RunAsync( ], plan.root, Path.Combine(directory, contextID + "-documentation-projection.log"), - cancellation + cancellationToken ).ConfigureAwait(false); XDocument projection = XDocument.Load(Path.Combine(project, "Inno.EditorScripts.csproj")); foreach (string scope in new[] { "Runtime", "Editor" }) @@ -492,7 +496,7 @@ await ResolveCompilationGraphAsync(contextID).ConfigureAwait(false), ..targetArguments, ..scriptArguments, ..pages - ], cancellation).ConfigureAwait(false) != 0 + ], cancellationToken).ConfigureAwait(false) != 0 ) { throw new InvalidDataException( "Selected documentation examples failed or require unavailable compilation inputs." @@ -524,7 +528,7 @@ await ValidationProductInput.PrepareAsync( plan, productDirectory, project, - cancellation + cancellationToken ).ConfigureAwait(false); await ShellAsync( "tests/Invoke-EditorSmoke.ps1", @@ -614,7 +618,7 @@ ..plan.nativeDependencies is null ], plan.root, Path.Combine(directory, "support-pack.log"), - cancellation + cancellationToken ).ConfigureAwait(false); await ShellAsync( "tests/ci/Test-SupportPackClosure.ps1", @@ -637,7 +641,7 @@ await ShellAsync( plan, contextID, outputDigests, - cancellation + cancellationToken ); string[] properties = plan.contexts[contextID].properties .Select(static pair => "-p:" + pair.Key + "=" + pair.Value) @@ -665,7 +669,7 @@ await ValidationProcess.RunAsync( ], plan.root, Path.Combine(directory, contextID + "-clean.log"), - cancellation + cancellationToken ).ConfigureAwait(false); } await ValidationProcess.RunAsync( @@ -686,7 +690,7 @@ await ValidationProcess.RunAsync( ], plan.root, Path.Combine(directory, contextID + "-build.log"), - cancellation + cancellationToken ).ConfigureAwait(false); built.Add(contextID); outputDigests.Clear(); @@ -765,7 +769,7 @@ ..plan.nativeDependencies is null { // Preserve the process failure even when individual owners have complete successful evidence. failures.Add( - new( + new ValidationRunFailure( "test-execution", failure.Message.Split('\n')[0], contextID, @@ -823,7 +827,7 @@ ..plan.nativeDependencies is null } if (status != "Blocked") { - outputs = ValidationOutputs.Capture(plan, check, cancellation, outputDigests); + outputs = ValidationOutputs.Capture(plan, check, cancellationToken, outputDigests); dependencyIdentity = dependencyInputs.Capture(check); documentationInputs = ValidationDocumentationInputs.Capture(plan, check, dependencyInputs); status = "Passed"; @@ -840,15 +844,24 @@ ..plan.nativeDependencies is null } } results.Add( - new(check.id, status, identity, elapsed.Elapsed.TotalSeconds, detail, outputs, dependencyIdentity, documentationInputs) + new ValidationResult( + check.id, + status, + identity, + elapsed.Elapsed.TotalSeconds, + detail, + outputs, + dependencyIdentity, + documentationInputs + ) ); string measurement = check.kind == "test" ? " owner reconciliation" : string.Empty; Console.WriteLine($"{status}: {check.id} ({elapsed.Elapsed.TotalSeconds:F2}s{measurement}) {detail}"); await SaveAsync().ConfigureAwait(false); } - if (cancellation.IsCancellationRequested) + if (cancellationToken.IsCancellationRequested) { - failures.Add(new("execution-canceled", "The run was canceled before closing verification.")); + failures.Add(new ValidationRunFailure("execution-canceled", "The run was canceled before closing verification.")); await SaveAsync().ConfigureAwait(false); return new( plan.commit, @@ -872,7 +885,12 @@ ..plan.nativeDependencies is null catch (Exception failure) { closingSeconds = Stopwatch.GetElapsedTime(closingStart).TotalSeconds; - failures.Add(new(failure is OperationCanceledException ? "execution-canceled" : "closing-verification", failure.Message)); + failures.Add( + new ValidationRunFailure( + failure is OperationCanceledException ? "execution-canceled" : "closing-verification", + failure.Message + ) + ); await SaveAsync().ConfigureAwait(false); throw; } @@ -895,13 +913,13 @@ ..plan.nativeDependencies is null async Task VerifyClosingStateAsync() { - Task> sourceCapture = ValidationInputs.CaptureAsync(plan.root, cancellation); + Task> sourceCapture = ValidationInputs.CaptureAsync(plan.root, cancellationToken); Task environmentCapture = Task.Run(() => ValidationEnvironment.CaptureAsync( plan.root, plan.dotnet, - cancellation, + cancellationToken, plan.contexts.Values - ), cancellation); + ), cancellationToken); await Task.WhenAll(sourceCapture, environmentCapture).ConfigureAwait(false); Dictionary after = await sourceCapture.ConfigureAwait(false); outputDigests.Clear(); @@ -910,15 +928,20 @@ async Task VerifyClosingStateAsync() foreach (ValidationCheck check in checks.Where(static check => check.exclusion is null)) { ValidationResult result = results.Single(record => record.id == check.id); - if (result.status is "Passed" or "Reused" && (!ValidationOutputs.Matches(plan, check, result, cancellation, outputDigests) - || !dependencyInputs.Matches(check, result.dependencyIdentity)) + if (result.status is "Passed" or "Reused" + && (!ValidationOutputs.Matches(plan, check, result, cancellationToken, outputDigests) + || !dependencyInputs.Matches(check, result.dependencyIdentity)) ) { if (check.kind == "build") { unstableCompilations.Add(check.context!); } failures.Add( - new("output-stability", "Compiled outputs or restored dependencies changed after verification.", check.id) + new ValidationRunFailure( + "output-stability", + "Compiled outputs or restored dependencies changed after verification.", + check.id + ) ); await SaveAsync().ConfigureAwait(false); } @@ -927,12 +950,14 @@ async Task VerifyClosingStateAsync() bool environmentStable = plan.environment == await environmentCapture.ConfigureAwait(false); if (!sourceStable) { - failures.Add(new("input-stability", "Inputs changed during validation.")); + failures.Add(new ValidationRunFailure("input-stability", "Inputs changed during validation.")); await SaveAsync().ConfigureAwait(false); } if (!environmentStable) { - failures.Add(new("environment-stability", "SDK, runtime, shell or imports changed during validation.")); + failures.Add( + new ValidationRunFailure("environment-stability", "SDK, runtime, shell or imports changed during validation.") + ); await SaveAsync().ConfigureAwait(false); } if (sourceStable && environmentStable) @@ -945,7 +970,7 @@ async Task VerifyClosingStateAsync() } if (workspace is not null) { - ValidationWorkspace.RecordCompleted(plan, cancellation); + ValidationWorkspace.RecordCompleted(plan, cancellationToken); } } @@ -958,7 +983,7 @@ string log ["-NoProfile", "-File", Path.Combine(plan.root, script), ..arguments], plan.root, Path.Combine(directory, log), - cancellation + cancellationToken ); async Task ResolveCompilationGraphAsync(string context) @@ -996,11 +1021,11 @@ async Task ResolveCompilationGraphAsync(string context) plan.dotnet, projects, plan.contexts[context].properties, - cancellation, + cancellationToken, resolveReferences: true ).ConfigureAwait(false); string destination = Path.Combine(directory, context + "-resolved-sdk-graph.json"); - await File.WriteAllTextAsync(destination, graph, cancellation).ConfigureAwait(false); + await File.WriteAllTextAsync(destination, graph, cancellationToken).ConfigureAwait(false); compilationGraphs.Add(context, destination); return destination; } @@ -1105,7 +1130,7 @@ bool MatchesRetained(ValidationCheck candidate) if (retained is not { status: "Passed" or "Reused" } || retained.inputIdentity != ValidationInputs.CheckIdentity(plan, candidate, current) || !dependencyInputs.Matches(candidate, retained.dependencyIdentity) - || !ValidationOutputs.Matches(plan, candidate, retained, cancellation, outputDigests) + || !ValidationOutputs.Matches(plan, candidate, retained, cancellationToken, outputDigests) ) { return false; } diff --git a/tools/Inno.Tooling.Validation/ValidationShard.cs b/tools/Inno.Tooling.Validation/ValidationShard.cs index 63ef7126d..f65f8e505 100644 --- a/tools/Inno.Tooling.Validation/ValidationShard.cs +++ b/tools/Inno.Tooling.Validation/ValidationShard.cs @@ -26,7 +26,7 @@ check.exclusion is not null || check.context is null ), StringComparer.Ordinal ); - var shards = new List(); + List shards = []; foreach (IGrouping group in checks.GroupBy(check => owners[check.id], StringComparer.Ordinal)) { var prerequisites = new HashSet(StringComparer.Ordinal); @@ -43,7 +43,11 @@ check.exclusion is not null || check.context is null } } shards.Add( - new(group.Key, group.Select(static check => check.id).ToArray(), prerequisites.Order(StringComparer.Ordinal).ToArray()) + new ValidationShard( + group.Key, + group.Select(static check => check.id).ToArray(), + prerequisites.Order(StringComparer.Ordinal).ToArray() + ) ); } return shards.ToArray(); @@ -156,7 +160,7 @@ internal static ValidationResult[] ValidateEvidence( } HashSet expected = checks.Select(static check => check.id).ToHashSet(StringComparer.Ordinal); ILookup observed = evidence.results.ToLookup(static result => result.id, StringComparer.Ordinal); - var errors = new List(); + List errors = []; foreach (IGrouping group in observed) { if (!expected.Contains(group.Key)) @@ -224,7 +228,7 @@ IReadOnlyList evidence { throw new InvalidDataException("The required shard matrix is incomplete or duplicated."); } - var results = new List(); + List results = []; foreach (ValidationShard shard in plan.shards) { _ = Require(plan, shard.id); diff --git a/tools/Inno.Tooling.Validation/ValidationWorkspace.cs b/tools/Inno.Tooling.Validation/ValidationWorkspace.cs index 1e7866e27..bfb85df5c 100644 --- a/tools/Inno.Tooling.Validation/ValidationWorkspace.cs +++ b/tools/Inno.Tooling.Validation/ValidationWorkspace.cs @@ -17,7 +17,7 @@ internal static class ValidationWorkspace internal static void RestoreOutputs( ValidationPlan plan, string source, - CancellationToken cancellation + CancellationToken cancellationToken ) { source = Path.GetFullPath(source); if (!Directory.Exists(source)) @@ -35,7 +35,7 @@ CancellationToken cancellation } foreach (string file in files) { - cancellation.ThrowIfCancellationRequested(); + cancellationToken.ThrowIfCancellationRequested(); string relative = Path.GetRelativePath(source, file); string destination = PathBoundary.Resolve(plan.artifacts, relative); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); @@ -45,18 +45,18 @@ CancellationToken cancellation internal static void RecordCompleted( ValidationPlan plan, - CancellationToken cancellation + CancellationToken cancellationToken ) { var publisher = new BuildCachePublisher( Path.GetDirectoryName(plan.artifacts)!, BuildCacheArtifactRole.ReusableWorkspace ); - publisher.Record(plan.artifacts, plan.artifacts + ".lock", [], null, null, cancellation); + publisher.Record(plan.artifacts, plan.artifacts + ".lock", [], null, null, cancellationToken); } internal static async Task AcquireReadAsync( ValidationPlan plan, - CancellationToken cancellation + CancellationToken cancellationToken ) { string parent = Path.GetDirectoryName(plan.artifacts) ?? throw new InvalidDataException("A validation output owner requires a parent directory."); @@ -72,13 +72,13 @@ CancellationToken cancellation leaf, Timeout.InfiniteTimeSpan, shared: true, - cancellationToken: cancellation + cancellationToken: cancellationToken ).ConfigureAwait(false); } internal static async Task AcquireAsync( ValidationPlan plan, - CancellationToken cancellation + CancellationToken cancellationToken ) { string parent = Path.GetDirectoryName(plan.artifacts) ?? throw new InvalidDataException("A validation output owner requires a parent directory."); @@ -87,17 +87,17 @@ CancellationToken cancellation SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetRelativePath(plan.root, parent).Replace('\\', '/'))) ); var publisher = new BuildCachePublisher(parent, BuildCacheArtifactRole.ReusableWorkspace); - BuildCacheOwnerCatalog.Register(plan.root, parent, "validation-workspaces-" + key, publisher.role, cancellation); - using FileLease activity = await publisher.AcquireUseAsync(cancellation).ConfigureAwait(false); + BuildCacheOwnerCatalog.Register(plan.root, parent, "validation-workspaces-" + key, publisher.role, cancellationToken); + using FileLease activity = await publisher.AcquireUseAsync(cancellationToken).ConfigureAwait(false); CoordinatedFileLease ownership = await CoordinatedFileLease.AcquireAsync( Path.Combine(parent, "owner.lock"), plan.artifacts + ".lock", Timeout.InfiniteTimeSpan, - cancellationToken: cancellation + cancellationToken: cancellationToken ).ConfigureAwait(false); try { - publisher.BeginWorkingDirectory(plan.artifacts, plan.artifacts + ".lock", null, cancellation); + publisher.BeginWorkingDirectory(plan.artifacts, plan.artifacts + ".lock", null, cancellationToken); return ownership; } catch From e140472449e3a09368aa305cf1df95b35b1186c1 Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sun, 22 Nov 2026 02:36:42 +0000 Subject: [PATCH 25/33] feat(tooling): check thirteen more rulebook rules The style checker now reports E-04, E-05, E-06, E-08, E-09, E-12, I-02, M-02, P-03, W-04, D-06, N-05 and N-06, and fixes W-04 and E-12. The naming check no longer exempts the native backend tests. The decision record lists what each syntax-only check reports and what it leaves to review. --- .../decisions/CSHARP_STYLE_RULEBOOK.md | 32 +- .../StyleCommandTests.cs | 444 +++++++++++++++++- .../Style/Rules/ArgumentGuardStyleRule.cs | 121 +++++ .../Style/Rules/AssignmentBreakStyleRule.cs | 89 ++++ .../Rules/CancellationParameterStyleRule.cs | 37 ++ .../Rules/CollectionExpressionStyleRule.cs | 72 +++ .../Style/Rules/ExpressionBodyStyleRule.cs | 59 +++ .../Style/Rules/NamingStyleRule.cs | 3 +- .../Style/Rules/NullPatternStyleRule.cs | 45 ++ .../Style/Rules/ObjectCreationStyleRule.cs | 61 +++ .../Style/Rules/ProhibitedTriviaStyleRule.cs | 32 ++ .../Style/Rules/QualifiedNameStyleRule.cs | 157 +++++++ .../Style/Rules/StringBuildStyleRule.cs | 42 ++ .../Style/Rules/ThisQualifierStyleRule.cs | 147 ++++++ .../Style/Rules/UsingDeclarationStyleRule.cs | 157 +++++++ .../Style/StyleEngine.cs | 14 +- 16 files changed, 1490 insertions(+), 22 deletions(-) create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ArgumentGuardStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/AssignmentBreakStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/CancellationParameterStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/CollectionExpressionStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ExpressionBodyStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/NullPatternStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ObjectCreationStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ProhibitedTriviaStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/QualifiedNameStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/StringBuildStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/ThisQualifierStyleRule.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/UsingDeclarationStyleRule.cs diff --git a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md index 00e9336c6..29188a42e 100644 --- a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md +++ b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md @@ -51,20 +51,34 @@ The engine currently enforces these rules. A finding is reported under the first | Reported ID | Also covers | | --- | --- | | F-01, F-03, F-04, F-05 | | -| N-01, N-03, N-04 | | +| N-01, N-03, N-04, N-05 | N-06 | | NM-01 to NM-13 | | | T-01, T-02, T-03, T-04 | | -| M-03, M-04, M-05 | | +| M-02, M-03, M-04, M-05 | | | O-01 | O-02 | | B-01, B-04, B-05, B-07 | B-06, B-08 | | B-03 | T-06 | | B-09 | M-01 | -| P-01, P-02 | | +| P-01, P-02, P-03 | | | A-01, A-02 | A-03 | -| W-01, W-03, W-05 | W-02 | -| I-01, I-05 | I-03, I-04 | +| W-01, W-03, W-04, W-05 | W-02 | +| I-01, I-02, I-05 | I-03, I-04 | | S-03, S-04 | | -| E-01, E-03, E-07, E-10, E-11 | | -| D-02, D-05 | D-04 | - -Every other rule is not yet checked by the tool and is enforced in review: F-02, N-02, N-05, N-06, T-05, T-07, T-08, M-02, B-02, P-03, A-04, W-04, I-02, S-01, S-02, E-02, E-04 to E-06, E-08, E-09, E-12, all X rules, D-01, D-03, D-06 and all TS rules. The naming check reads syntax only: it trusts the names of overrides, interface implementations, native interop declarations and serialized members, and it exempts test methods from the `Async` suffix. `.editorconfig` states the same naming table for editors. +| E-01, E-03, E-04, E-05, E-06, E-07, E-08, E-09, E-10, E-11, E-12 | | +| D-02, D-05, D-06 | D-04 | + +Every other rule is not yet checked by the tool and is enforced in review: F-02, N-02, T-05, T-07, T-08, B-02, A-04, S-01, S-02, E-02, all X rules, D-03 and all TS rules. The compiler enforces D-01 through `CS1591`. The checks for N-05, E-04 and E-08 read syntax only: N-05 recognizes a qualified name by its root namespace, E-04 reports a negated `is null` and leaves `==` comparisons to review because an overloaded operator is not visible in syntax, and E-08 knows the members that the same type declaration declares. The naming check reads syntax only: it trusts the names of overrides, interface implementations, native interop declarations and serialized members, and it exempts test methods from the `Async` suffix. `.editorconfig` states the same naming table for editors. + +These checks read syntax only and report the part of a rule that syntax decides: + +| ID | Reported | Left to review | +| --- | --- | --- | +| M-02 | A block body that is one `return`, call, assignment or `throw`; a constructor with an expression body. | A body that holds a comment or a directive. | +| P-03 | A `CancellationToken` parameter of a declaration that is not named `cancellationToken`. | Its position in the list, and lambda parameters. | +| W-04 | A line break directly before or after `=`; the fix joins the lines. | | +| I-02 | A declaration typed as an array or `List` (or a `var` local) whose value is `new[] {}`, `new T[] {}`, `Array.Empty()` or a `List` creation without constructor arguments. | A creation without a target type: a call receiver, an inferred generic argument, an anonymous-type member. | +| E-05 | A hand-written `if` that throws `ArgumentNullException` for the tested name, and `?? throw new ArgumentNullException(nameof(x))` on a parameter in a statement of a block body. | Expression bodies and initializers, range checks, custom messages. | +| E-06 | `new()` as an argument, a collection element, an operand, a branch or a local initializer. | | +| E-09 | `string.Format` with a literal format and `string.Concat` with two or more arguments. | A format that is itself a value, and `string.Concat` of one sequence. | +| E-12 | A `using` statement with a declaration that ends its block; the fix writes the declaration. | A `using` statement over an expression, and one whose names collide with a sibling scope. | +| D-06 | `#region`, `#endregion`, `#nullable` and `/* */` block comments. | Comment language, markers, commented-out code and unexplained `#pragma`. | diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs index 37d71b152..4e0d6c445 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs @@ -86,6 +86,48 @@ string text [InlineData("NM-13", "internal sealed class UiProbe;")] [InlineData("NM-13", "internal sealed class Probe\n{\n internal int assetId => 0;\n}")] [InlineData("NM-13", "internal sealed class Probe\n{\n internal void Run(int[] assetIds) {}\n}")] + [InlineData( + "E-08", + "internal sealed class Probe\n{\n internal Probe()\n {\n count = 1;\n }\n\n internal int count { get; }\n}" + )] + [InlineData( + "E-08", + "internal sealed class Probe\n{\n internal int count { get; set; }\n\n internal int Read() => this.count;\n}" + )] + [InlineData("N-05", "internal sealed class Probe\n{\n internal System.Text.StringBuilder text => new();\n}")] + [InlineData("N-05", "internal sealed class Probe\n{\n internal bool Has(string path) => System.IO.File.Exists(path);\n}")] + [InlineData("N-06", "using Path = System.IO.Path;\n\ninternal sealed class Probe;")] + [InlineData("N-06", "using nativePath = System.IO.Path;\n\ninternal sealed class Probe;")] + [InlineData("N-06", "using FilePath = System.IO.Path;\nusing NativePath = System.IO.Path;\n\ninternal sealed class Probe;")] + [InlineData("E-04", "internal sealed class Probe\n{\n internal bool Has(object? value) => !(value is null);\n}")] + [InlineData( + "E-06", + "internal sealed class Probe\n{\n internal void Run()\n {\n Use(new());\n }\n\n private void Use(object value) {}\n}" + )] + [InlineData("E-06", "internal sealed class Probe\n{\n internal void Run()\n {\n object value = new();\n }\n}")] + [InlineData("I-02", "internal sealed class Probe\n{\n private readonly int[] m_values = new[] { 1, 2 };\n}")] + [InlineData("I-02", "internal sealed class Probe\n{\n private readonly int[] m_values = Array.Empty();\n}")] + [InlineData("I-02", "internal sealed class Probe\n{\n private readonly List m_values = new();\n}")] + [InlineData("I-02", "internal sealed class Probe\n{\n internal void Run()\n {\n var values = new List();\n }\n}")] + [InlineData( + "E-05", + "internal sealed class Probe\n{\n internal void Run(object value)\n {\n if (value is null) throw new ArgumentNullException(nameof(value));\n }\n}" + )] + [InlineData( + "E-05", + "internal sealed class Probe\n{\n internal object Run(object value)\n {\n return value ?? throw new ArgumentNullException(nameof(value));\n }\n}" + )] + [InlineData("P-03", "internal sealed class Probe\n{\n internal void Run(CancellationToken token) {}\n}")] + [InlineData("D-06", "internal sealed class Probe\n{\n #region State\n internal int count => 0;\n #endregion\n}")] + [InlineData("D-06", "#nullable disable\ninternal sealed class Probe;")] + [InlineData("D-06", "internal sealed class Probe\n{\n /* The count. */\n internal int count => 0;\n}")] + [InlineData("E-09", "internal sealed class Probe\n{\n internal string Name(int value) => string.Format(\"item-{0}\", value);\n}")] + [InlineData( + "E-09", + "internal sealed class Probe\n{\n internal string Name(string first, string second) => string.Concat(first, second);\n}" + )] + [InlineData("M-02", "internal sealed class Probe\n{\n internal int Read()\n {\n return 1;\n }\n}")] + [InlineData("M-02", "internal sealed class Probe\n{\n private int m_count;\n\n internal Probe() => m_count = 1;\n}")] public void FindingsThatNeedTheAuthorAreReportedAndLeftUnchanged( string rule, string text @@ -140,8 +182,7 @@ string content [InlineData("[GeneratedCode(\\\"Tool\\\", \\\"1\\\")]")] public void SourcesThatOnlyWriteAGeneratedMarkerAreHandwritten(string marker) { - string content = - "internal sealed class Probe\n{\n internal string Run() { return \"" + marker + "\"; }\n}\n"; + string content = "internal sealed class Probe\n{\n internal string Run() { return \"" + marker + "\"; }\n}\n"; string root = CreateRoot(); try @@ -369,6 +410,7 @@ internal sealed class Probe { internal void Run() { + Begin(); Register(firstArgumentWithALongName, secondArgumentWithALongName, thirdArgumentWithALongName, fourthArgumentWithALongName, fifthArgumentWithALongName); } @@ -381,6 +423,7 @@ internal sealed class Probe { internal void Run() { + Begin(); Register( firstArgumentWithALongName, secondArgumentWithALongName, @@ -426,6 +469,7 @@ internal void Run( int second ) { + Begin(); Step(); } } @@ -439,6 +483,7 @@ internal void Run( int first, int second ) { + Begin(); Step(); } } @@ -515,6 +560,7 @@ internal sealed class Probe { internal int Run() { + Begin(); return m_values.Where(static value => value > 0).Select(static value => value * 2). Sum(); } @@ -527,6 +573,7 @@ internal sealed class Probe { internal int Run() { + Begin(); return m_values.Where(static value => value > 0) .Select(static value => value * 2) .Sum(); @@ -541,7 +588,7 @@ internal int Run() """ internal sealed class Probe { - internal void Run() { Step(); } + internal Probe() { Step(); } } """ ), @@ -549,7 +596,7 @@ internal sealed class Probe """ internal sealed class Probe { - internal void Run() + internal Probe() { Step(); } @@ -628,7 +675,7 @@ internal void Run() Source( """ internal sealed class Probe { - internal void Run() { + internal Probe() { Step(); } } @@ -638,7 +685,7 @@ internal void Run() { """ internal sealed class Probe { - internal void Run() + internal Probe() { Step(); } @@ -824,6 +871,7 @@ internal sealed class Probe { internal void Run() { + Begin(); Register(firstArgumentWithALongName, secondArgumentWithALongName, thirdArgumentWithALongName, fourthArgumentWithALongName, fifthArgumentWithALongName); } } @@ -835,6 +883,7 @@ internal sealed class Probe { internal void Run() { + Begin(); Register( firstArgumentWithALongName, secondArgumentWithALongName, @@ -961,6 +1010,7 @@ internal sealed class Probe { internal void Run() { + Begin(); Report($"The viewport '{viewport.name}' does not support the requested mode '{Describe(defaultMode, viewport.capabilities)}' in '{viewport.owner}'."); } } @@ -972,6 +1022,7 @@ internal sealed class Probe { internal void Run() { + Begin(); Report( $"The viewport '{viewport.name}' does not support the requested mode '{Describe(defaultMode, viewport.capabilities)}' in '{viewport.owner}'." ); @@ -1011,7 +1062,7 @@ internal void Run() """ internal sealed class Probe { - private readonly List m_values = new List(); + private readonly StringBuilder m_values = new StringBuilder(); private int m_first = 1, m_second = 2; } """ @@ -1020,7 +1071,7 @@ internal sealed class Probe """ internal sealed class Probe { - private readonly List m_values = new(); + private readonly StringBuilder m_values = new(); private int m_first = 1; private int m_second = 2; } @@ -1309,7 +1360,7 @@ internal sealed class Probe { private readonly Int32 m_count = Int32.Parse("1"); - internal String Name(Object value) => String.Concat(value, m_count); + internal String Name(Object value) => String.Join("-", value, m_count); } """ ), @@ -1321,7 +1372,7 @@ internal sealed class Probe { private readonly int m_count = int.Parse("1"); - internal string Name(object value) => string.Concat(value, m_count); + internal string Name(object value) => string.Join("-", value, m_count); } """ ) @@ -1391,6 +1442,7 @@ public void Draw( int mesh, int material ) { + Begin(); Submit(mesh + material); } @@ -1422,6 +1474,7 @@ public void Draw( int mesh, int material ) { + Begin(); Submit(mesh + material); } @@ -1437,6 +1490,74 @@ private void Submit(int item) {} } """ ) + }, + { + "W-04", + Source( + """ + internal sealed class Probe + { + internal int Read(int first) + { + int total = + first + 1; + total + = total + 2; + return total; + } + } + """ + ), + Source( + """ + internal sealed class Probe + { + internal int Read(int first) + { + int total = first + 1; + total = total + 2; + return total; + } + } + """ + ) + }, + { + "E-12", + Source( + """ + using System.IO; + + internal sealed class Probe + { + internal int Read(string path) + { + int offset = 1; + using (FileStream stream = File.OpenRead(path)) + { + int value = stream.ReadByte(); + return value + offset; + } + } + } + """ + ), + Source( + """ + using System.IO; + + internal sealed class Probe + { + internal int Read(string path) + { + int offset = 1; + using FileStream stream = File.OpenRead(path); + int value = stream.ReadByte(); + return value + offset; + } + } + """ + ) } }; @@ -1605,7 +1726,7 @@ internal sealed class Probe { internal object String() => this; - internal string Describe() => nameof(Int32) + typeof(System.String).Name; + internal string Describe() => nameof(Int32) + nameof(String); /// /// Returns a . @@ -1764,6 +1885,307 @@ internal sealed class ImGuiProbe internal sealed record PageReference(string pageId); """ ) + }, + { + "N-05", + Source( + """ + using System.IO; + + using NativePath = System.IO.Path; + + namespace Inno.Probe; + + internal sealed class Probe + { + internal static string Name(string path) => NativePath.GetFileName(path) + Path.DirectorySeparatorChar; + } + """ + ) + }, + { + "N-06", + Source( + """ + using NativePath = System.IO.Path; + using TextBuffer = System.Text.StringBuilder; + + internal sealed class Probe + { + internal static string Name(string path) => new TextBuffer(NativePath.GetFileName(path)).ToString(); + } + """ + ) + }, + { + "E-04", + Source( + """ + internal sealed class Probe + { + internal bool Has(object? value) => value is not null && !(value is string); + + internal bool Lacks(Probe? value) => value == null; + } + """ + ) + }, + { + "E-08", + Source( + """ + internal sealed class Probe + { + private readonly int m_seed; + + internal Probe(int count) + { + m_seed = count; + this.count = count; + } + + internal int count { get; private set; } + + internal int seed => m_seed; + + internal void Reset(int count) + { + this.count = count; + Notify(); + } + } + """ + ) + }, + { + "W-04", + Source( + """ + internal sealed class Probe + { + internal int[] Read() + { + int[] values = + [ + 1, + 2 + ]; + return values; + } + } + """ + ) + }, + { + "E-12", + Source( + """ + using System; + using System.IO; + + internal sealed class Probe + { + internal int Read( + string path, + IDisposable scope + ) { + using (FileStream first = File.OpenRead(path)) + { + int value = first.ReadByte(); + if (value < 0) return value; + } + using (scope) + { + return 0; + } + } + + internal int ReadTwice(string path) + { + { + int value = 1; + if (value < 0) return value; + } + using (FileStream stream = File.OpenRead(path)) + { + int value = stream.ReadByte(); + return value; + } + } + } + """ + ) + }, + { + "E-06", + Source( + """ + using System.Collections.Generic; + using System.Text; + + internal sealed class Probe + { + private readonly StringBuilder m_text = new(); + + internal List values { get; set; } = new(4); + + internal StringBuilder Create() => new(); + + internal StringBuilder Reset() + { + var text = new StringBuilder(); + values = new(8); + Append(new StringBuilder()); + return new(); + } + + private void Append(StringBuilder text) {} + } + """ + ) + }, + { + "I-02", + Source( + """ + using System.Collections.Generic; + using System.Linq; + + internal sealed class Probe + { + private readonly List m_sized = new(16); + private readonly int[] m_buffer = new int[4]; + + internal int[] values { get; } = [1, 2]; + + internal int Count(IEnumerable source) + { + var copy = new List(source); + List empty = []; + return copy.Count + empty.Count + new[] { 1, 2 }.Sum(); + } + } + """ + ) + }, + { + "E-05", + Source( + """ + using System; + + internal sealed class Probe + { + private readonly string m_name; + + internal Probe(string name) + { + ArgumentNullException.ThrowIfNull(name); + m_name = name; + } + + internal string Name(string? other) => other ?? throw new ArgumentNullException(nameof(other)); + + internal string Require(string? value) + { + if (value is null) throw new InvalidOperationException("The value is missing."); + return m_name + value; + } + } + """ + ) + }, + { + "P-03", + Source( + """ + using System; + using System.Threading; + using System.Threading.Tasks; + + internal sealed class Probe + { + internal Task RunAsync(CancellationToken cancellationToken) + { + Func step = token => Task.Delay(1, token); + return step(cancellationToken); + } + } + """ + ) + }, + { + "D-06", + Source( + """ + // A line comment that mentions #region and /* text */ is not a directive. + internal sealed class Probe + { + #if DEBUG + internal string text => "#nullable /* kept */"; + #endif + } + """ + ) + }, + { + "E-09", + Source( + """ + using System.Collections.Generic; + using System.Globalization; + + internal sealed class Probe + { + internal string Join(IEnumerable parts) => string.Concat(parts); + + internal string Format( + string template, + int value + ) => string.Format(CultureInfo.InvariantCulture, template, value); + + internal string Name(int value) => $"item-{value}"; + } + """ + ) + }, + { + "M-02", + Source( + """ + using System; + + internal sealed class Probe + { + private int m_count; + + internal Probe() + { + m_count = 1; + } + + internal int count + { + get => m_count; + set => m_count = value; + } + + internal int Next() => m_count + 1; + + internal void Reset() + { + // The first frame starts from one. + m_count = 1; + } + + internal void Clear() + { + if (m_count == 0) throw new InvalidOperationException("The probe is empty."); + m_count = 0; + } + } + """ + ) } }; diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ArgumentGuardStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ArgumentGuardStyleRule.cs new file mode 100644 index 000000000..9265d9a3e --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ArgumentGuardStyleRule.cs @@ -0,0 +1,121 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// E-05: a null argument is rejected with `ArgumentNullException.ThrowIfNull`, not with `?? throw` or a +// hand-written `if`. A position that cannot hold a statement (an expression body, an initializer) is not reported. +internal sealed class ArgumentGuardStyleRule : StyleRule +{ + private const string C_ID = "E-05"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + switch (node) + { + case BinaryExpressionSyntax coalesce when coalesce.IsKind(SyntaxKind.CoalesceExpression) + && coalesce.Left is IdentifierNameSyntax name + && IsNullArgumentThrow(coalesce.Right, name.Identifier.ValueText) + && IsParameterOfBlockBody(coalesce, name.Identifier.ValueText): + findings.Add( + source.Finding( + C_ID, + coalesce.Right.SpanStart, + "Validate the parameter first with `ArgumentNullException.ThrowIfNull`." + ) + ); + break; + case IfStatementSyntax { Else: null } check when NullTested(check.Condition) is { } tested + && SingleStatement(check.Statement) is ThrowStatementSyntax { Expression: { } thrown } + && IsNullArgumentThrow(thrown, tested): + findings.Add( + source.Finding( + C_ID, + check.SpanStart, + "Write `ArgumentNullException.ThrowIfNull` instead of a hand-written null check." + ) + ); + break; + } + } + } + + // `throw new ArgumentNullException(nameof(name))` as a throw expression, or the creation itself. + private static bool IsNullArgumentThrow( + ExpressionSyntax expression, + string name + ) { + if (expression is ThrowExpressionSyntax thrown) expression = thrown.Expression; + return expression is ObjectCreationExpressionSyntax + { + Type: IdentifierNameSyntax { Identifier.ValueText: "ArgumentNullException" }, + ArgumentList.Arguments: { Count: 1 } arguments + } + && arguments[0].Expression is InvocationExpressionSyntax + { + Expression: IdentifierNameSyntax { Identifier.ValueText: "nameof" }, + ArgumentList.Arguments: { Count: 1 } names + } + && names[0].Expression is IdentifierNameSyntax named + && named.Identifier.ValueText == name; + } + + private static string? NullTested(ExpressionSyntax condition) + => condition switch + { + IsPatternExpressionSyntax + { + Expression: IdentifierNameSyntax name, + Pattern: ConstantPatternSyntax { Expression: LiteralExpressionSyntax { RawKind: (int)SyntaxKind.NullLiteralExpression } } + } => name.Identifier.ValueText, + BinaryExpressionSyntax + { + RawKind: (int)SyntaxKind.EqualsExpression, + Left: IdentifierNameSyntax name, + Right: LiteralExpressionSyntax { RawKind: (int)SyntaxKind.NullLiteralExpression } + } => name.Identifier.ValueText, + _ => null + }; + + private static StatementSyntax SingleStatement(StatementSyntax statement) + => statement is BlockSyntax { Statements.Count: 1 } block ? block.Statements[0] : statement; + + // The value is a parameter of a member with a block body, and the statement is not nested in control flow, + // so a guard statement at the top of the body can replace the throw expression. + private static bool IsParameterOfBlockBody( + SyntaxNode node, + string name + ) { + StatementSyntax? statement = node.FirstAncestorOrSelf(); + if (statement?.Parent is not BlockSyntax { Parent: BaseMethodDeclarationSyntax or LocalFunctionStatementSyntax } body) + { + return false; + } + if (node + .Ancestors() + .TakeWhile(ancestor => ancestor != statement) + .Any(static ancestor => ancestor is AnonymousFunctionExpressionSyntax) + ) { + return false; + } + + ParameterListSyntax? parameters = body.Parent switch + { + BaseMethodDeclarationSyntax method => method.ParameterList, + LocalFunctionStatementSyntax local => local.ParameterList, + _ => null + }; + return parameters is not null && parameters.Parameters.Any(parameter => parameter.Identifier.ValueText == name); + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/AssignmentBreakStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/AssignmentBreakStyleRule.cs new file mode 100644 index 000000000..80a7e898f --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/AssignmentBreakStyleRule.cs @@ -0,0 +1,89 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// W-04: a line is never broken directly before or after `=`. The value starts on the line of the `=`; +// the only exception is the opening bracket of a multi-line collection expression (I-03). +internal sealed class AssignmentBreakStyleRule : StyleRule +{ + private const string C_ID = "W-04"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Layout; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach ((SyntaxToken equals, SyntaxNode _, bool _) in Violations(source)) + { + findings.Add(source.Finding(C_ID, equals.SpanStart, "Keep `=` and the start of its value on one line.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + List edits = []; + int fixedLine = -1; + foreach ((SyntaxToken equals, SyntaxNode value, bool before) in Violations(source)) + { + SyntaxToken left = before ? equals.GetPreviousToken() : equals; + SyntaxToken right = before ? equals : value.GetFirstToken(); + int firstLine = source.LineNumber(right.SpanStart); + int lastLine = source.LineNumber(value.Span.End); + + // A value that an earlier fix of this round reaches waits for the next round. + if (source.LineNumber(left.SpanStart) <= fixedLine) continue; + if (!StyleLayout.IsBlank(source.content, left.Span.End, right.SpanStart)) continue; + edits.Add(new StyleEdit(left.Span.End, right.SpanStart, " ")); + + // The continuation lines were indented from the moved line; they now hang from the statement. + int delta = source.Indentation(left.SpanStart) - source.Indentation(right.SpanStart); + bool isDelimited = value.GetLastToken().Kind() is SyntaxKind.CloseParenToken + or SyntaxKind.CloseBraceToken + or SyntaxKind.CloseBracketToken + && source.IsFirstOnLine(value.GetLastToken()); + if (delta != 0 && isDelimited) + { + for (int line = firstLine + 1; line <= lastLine; line++) + { + StyleEdit? shift = StyleLayout.Shift(source, line, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + } + + fixedLine = lastLine; + } + + return edits; + } + + private static IEnumerable<(SyntaxToken equals, SyntaxNode value, bool before)> Violations(StyleSource source) + { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + (SyntaxToken equals, SyntaxNode? value) = node switch + { + EqualsValueClauseSyntax clause => (clause.EqualsToken, clause.Value), + AssignmentExpressionSyntax assignment => (assignment.OperatorToken, assignment.Right), + _ => (default(SyntaxToken), (SyntaxNode?)null) + }; + if (value is null || equals.IsMissing || value.IsMissing) continue; + if (source.IsFirstOnLine(equals)) + { + yield return (equals, value, true); + continue; + } + if (!source.IsLastOnLine(equals)) continue; + if (value is CollectionExpressionSyntax) continue; + yield return (equals, value, false); + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/CancellationParameterStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/CancellationParameterStyleRule.cs new file mode 100644 index 000000000..a784cbc9a --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/CancellationParameterStyleRule.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// P-03: a `CancellationToken` parameter of a declaration is named `cancellationToken`. +// A lambda parameter is not reported: it may have to differ from a token of the enclosing member. +internal sealed class CancellationParameterStyleRule : StyleRule +{ + private const string C_ID = "P-03"; + private const string C_NAME = "cancellationToken"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (ParameterSyntax parameter in source.root.DescendantNodes().OfType()) + { + if (parameter.Type is not IdentifierNameSyntax { Identifier.ValueText: "CancellationToken" }) continue; + if (parameter.Parent is not ParameterListSyntax { Parent: not AnonymousFunctionExpressionSyntax }) continue; + if (parameter.Identifier.ValueText == C_NAME) continue; + findings.Add( + source.Finding( + C_ID, + parameter.Identifier.SpanStart, + $"Name the parameter `{C_NAME}`. Found `{parameter.Identifier.ValueText}`." + ) + ); + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/CollectionExpressionStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/CollectionExpressionStyleRule.cs new file mode 100644 index 000000000..ecbdff04d --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/CollectionExpressionStyleRule.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// I-02: an array or a `List` is written as a collection expression where the declaration gives it a target type. +// A creation without a target type (a call receiver, an inferred generic argument, an anonymous-type member) +// has no collection expression form and is not reported. +internal sealed class CollectionExpressionStyleRule : StyleRule +{ + private const string C_ID = "I-02"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (EqualsValueClauseSyntax clause in source.root.DescendantNodes().OfType()) + { + TypeSyntax? declared = clause.Parent switch + { + VariableDeclaratorSyntax { Parent: VariableDeclarationSyntax declaration } => declaration.Type, + PropertyDeclarationSyntax property => property.Type, + _ => null + }; + if (declared is null) continue; + bool isLocal = clause.Parent is VariableDeclaratorSyntax { Parent.Parent: LocalDeclarationStatementSyntax }; + if (IsList(declared) || isLocal && declared.IsVar) + { + if (IsPlainListCreation(clause.Value) && (IsList(declared) || clause.Value is ObjectCreationExpressionSyntax)) + { + findings.Add( + source.Finding(C_ID, clause.Value.SpanStart, "Write the list as a collection expression: `List x = [...]`.") + ); + } + } + else if (declared is ArrayTypeSyntax && IsArrayCreation(clause.Value)) + { + findings.Add(source.Finding(C_ID, clause.Value.SpanStart, "Write the array as a collection expression: `T[] x = [...]`.")); + } + } + } + + private static bool IsList(TypeSyntax type) + => type is GenericNameSyntax { Identifier.ValueText: "List", TypeArgumentList.Arguments.Count: 1 }; + + // A constructor argument (a capacity or a source) keeps the constructor call. + private static bool IsPlainListCreation(ExpressionSyntax value) + => value is BaseObjectCreationExpressionSyntax creation + && (creation is ImplicitObjectCreationExpressionSyntax || creation is ObjectCreationExpressionSyntax typed && IsList(typed.Type)) + && creation.ArgumentList is null or { Arguments.Count: 0 } + && creation.Initializer is null or { RawKind: (int)SyntaxKind.CollectionInitializerExpression }; + + private static bool IsArrayCreation(ExpressionSyntax value) + => value is ImplicitArrayCreationExpressionSyntax + || value is ArrayCreationExpressionSyntax { Initializer: not null } + || value is InvocationExpressionSyntax + { + ArgumentList.Arguments.Count: 0, + Expression: MemberAccessExpressionSyntax + { + Expression: IdentifierNameSyntax { Identifier.ValueText: "Array" }, + Name: GenericNameSyntax { Identifier.ValueText: "Empty" } + } + }; +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ExpressionBodyStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ExpressionBodyStyleRule.cs new file mode 100644 index 000000000..7fa30810c --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ExpressionBodyStyleRule.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// M-02: a method, operator, local function or accessor whose body is one expression uses an expression body, +// and a constructor always uses a block body. +internal sealed class ExpressionBodyStyleRule : StyleRule +{ + private const string C_ID = "M-02"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + switch (node) + { + case ConstructorDeclarationSyntax { ExpressionBody: not null } constructor: + findings.Add(source.Finding(C_ID, constructor.Identifier.SpanStart, "Give the constructor a block body.")); + break; + case MethodDeclarationSyntax + or OperatorDeclarationSyntax + or ConversionOperatorDeclarationSyntax + or LocalFunctionStatementSyntax + or AccessorDeclarationSyntax: + BlockSyntax? body = node switch + { + BaseMethodDeclarationSyntax method => method.Body, + LocalFunctionStatementSyntax local => local.Body, + AccessorDeclarationSyntax accessor => accessor.Body, + _ => null + }; + if (body is not null && IsOneExpression(body)) + { + findings.Add( + source.Finding(C_ID, body.OpenBraceToken.SpanStart, "Write the single expression as an expression body.") + ); + } + + break; + } + } + } + + // A comment or a directive inside the body documents a statement, so the block stays. + private static bool IsOneExpression(BlockSyntax body) + => body.Statements.Count == 1 + && body.Statements[0] is ReturnStatementSyntax { Expression: not null } or ExpressionStatementSyntax or ThrowStatementSyntax + && !body.DescendantTrivia().Any(static trivia => trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) || trivia.IsDirective); +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/NamingStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/NamingStyleRule.cs index 22d01528b..75442e859 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/NamingStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/NamingStyleRule.cs @@ -39,7 +39,8 @@ internal override void Check( StyleSource source, ICollection findings ) { - bool isNative = source.path.Contains("/Inno.Native.", StringComparison.Ordinal); + bool isNative = source.path.Contains("/Inno.Native.", StringComparison.Ordinal) + && !source.path.StartsWith("tests/", StringComparison.Ordinal); foreach (SyntaxNode node in source.root.DescendantNodes()) { switch (node) diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/NullPatternStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/NullPatternStyleRule.cs new file mode 100644 index 000000000..0d49ab421 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/NullPatternStyleRule.cs @@ -0,0 +1,45 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// E-04: a negated null test is written `is not null`, not `!(value is null)`. +// A comparison with `==` or `!=` is not reported: whether a type overloads equality is not visible in syntax. +internal sealed class NullPatternStyleRule : StyleRule +{ + private const string C_ID = "E-04"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (PrefixUnaryExpressionSyntax negation in source.root.DescendantNodes().OfType()) + { + if (IsNegatedNullTest(negation)) + { + findings.Add(source.Finding(C_ID, negation.SpanStart, "Write `is not null` instead of negating `is null`.")); + } + } + } + + private static bool IsNegatedNullTest(PrefixUnaryExpressionSyntax negation) + => negation.IsKind(SyntaxKind.LogicalNotExpression) + && negation.Operand is ParenthesizedExpressionSyntax + { + Expression: IsPatternExpressionSyntax + { + Pattern: ConstantPatternSyntax + { + Expression: LiteralExpressionSyntax literal + } + } + } + && literal.IsKind(SyntaxKind.NullLiteralExpression); +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ObjectCreationStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ObjectCreationStyleRule.cs new file mode 100644 index 000000000..1649171bf --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ObjectCreationStyleRule.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// E-06: an argument, or a creation inside a larger expression, writes the type: `new T(...)`. +// A field or property initializer, an assignment and a directly returned object keep the target-typed form. +internal sealed class ObjectCreationStyleRule : StyleRule +{ + private const string C_ID = "E-06"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (ImplicitObjectCreationExpressionSyntax creation in source.root + .DescendantNodes() + .OfType() + ) { + if (IsLocalInitializer(creation)) + { + findings.Add(source.Finding(C_ID, creation.SpanStart, "Declare the local variable as `var x = new T(...)`.")); + } + else if (IsInsideExpression(creation)) + { + findings.Add(source.Finding(C_ID, creation.SpanStart, "Write the type of the created object: `new T(...)`.")); + } + } + } + + private static bool IsLocalInitializer(ImplicitObjectCreationExpressionSyntax creation) + => creation.Parent is EqualsValueClauseSyntax + { + Parent: VariableDeclaratorSyntax + { + Parent: VariableDeclarationSyntax + { + Parent: LocalDeclarationStatementSyntax + } + } + }; + + private static bool IsInsideExpression(ImplicitObjectCreationExpressionSyntax creation) + => creation.Parent is ArgumentSyntax { Parent: not TupleExpressionSyntax } + or ExpressionElementSyntax + or ConditionalExpressionSyntax + or SwitchExpressionArmSyntax + or YieldStatementSyntax + or BinaryExpressionSyntax + or SimpleLambdaExpressionSyntax + or ParenthesizedLambdaExpressionSyntax + || creation.Parent is InitializerExpressionSyntax initializer + && initializer.Kind() is SyntaxKind.CollectionInitializerExpression or SyntaxKind.ArrayInitializerExpression; +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ProhibitedTriviaStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ProhibitedTriviaStyleRule.cs new file mode 100644 index 000000000..112da2bc9 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ProhibitedTriviaStyleRule.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Inno.Tooling.Architecture; + +// D-06: `#region`, `#endregion`, `#nullable` inside a file and `/* */` block comments are not written. +internal sealed class ProhibitedTriviaStyleRule : StyleRule +{ + private const string C_ID = "D-06"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (SyntaxTrivia trivia in source.root.DescendantTrivia(descendIntoTrivia: true)) + { + string? message = trivia.Kind() switch + { + SyntaxKind.RegionDirectiveTrivia or SyntaxKind.EndRegionDirectiveTrivia => "Remove the region directive.", + SyntaxKind.NullableDirectiveTrivia => "Remove `#nullable`: the project sets the nullable context.", + SyntaxKind.MultiLineCommentTrivia => "Write the comment with `//`, not as a block comment.", + _ => null + }; + if (message is not null) findings.Add(source.Finding(C_ID, trivia.SpanStart, message)); + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/QualifiedNameStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/QualifiedNameStyleRule.cs new file mode 100644 index 000000000..00564414f --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/QualifiedNameStyleRule.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// N-05: code refers to a type by its short name instead of a namespace-qualified name. +// N-06: an alias is PascalCase, differs from the short name of its target and is the only alias of that target. +// The check reads syntax only, so it recognizes a qualified name by its root namespace. +internal sealed class QualifiedNameStyleRule : StyleRule +{ + private const string C_ID = "N-05"; + private const string C_ALIAS_ID = "N-06"; + + private static readonly string[] ROOT_NAMESPACES = + [ + "Inno", + "Microsoft", + "System", + "Xunit" + ]; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override bool Covers(string ruleID) + => string.Equals(ruleID, C_ID, StringComparison.Ordinal) || string.Equals(ruleID, C_ALIAS_ID, StringComparison.Ordinal); + + internal override void Check( + StyleSource source, + ICollection findings + ) { + HashSet aliases = source.root + .DescendantNodes() + .OfType() + .Where(static directive => directive.Alias is not null) + .Select(static directive => directive.Alias!.Name.Identifier.ValueText) + .ToHashSet(StringComparer.Ordinal); + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (node is UsingDirectiveSyntax directive) + { + CheckAlias(source, findings, directive); + } + else if (IsQualifiedUse(node, aliases)) + { + findings.Add( + source.Finding(C_ID, node.SpanStart, "Import the namespace and use the short name. Found `" + node + "`.") + ); + } + } + } + + private static void CheckAlias( + StyleSource source, + ICollection findings, + UsingDirectiveSyntax directive + ) { + if (directive.Alias is null) + { + return; + } + + string alias = directive.Alias.Name.Identifier.ValueText; + string target = ShortName(directive.NamespaceOrType); + if (!char.IsUpper(alias[0]) || alias.Contains('_', StringComparison.Ordinal)) + { + findings.Add(source.Finding(C_ALIAS_ID, directive.Alias.SpanStart, "Name an alias in PascalCase. Found `" + alias + "`.")); + } + else if (string.Equals(alias, target, StringComparison.Ordinal)) + { + findings.Add( + source.Finding( + C_ALIAS_ID, + directive.Alias.SpanStart, + "Name an alias after the role of its target, not after the target. Found `" + alias + "`." + ) + ); + } + else if (IsRepeatedTarget(directive)) + { + findings.Add( + source.Finding( + C_ALIAS_ID, + directive.Alias.SpanStart, + "Declare one alias per target. `" + alias + "` repeats the target of an earlier alias." + ) + ); + } + } + + private static bool IsRepeatedTarget(UsingDirectiveSyntax directive) + { + if (directive.Parent is null) + { + return false; + } + + string target = directive.NamespaceOrType.ToString(); + return directive.Parent + .ChildNodes() + .OfType() + .TakeWhile(other => other != directive) + .Any(other => other.Alias is not null && string.Equals(other.NamespaceOrType.ToString(), target, StringComparison.Ordinal)); + } + + private static string ShortName(TypeSyntax type) + => type switch + { + QualifiedNameSyntax qualified => qualified.Right.Identifier.ValueText, + AliasQualifiedNameSyntax qualified => qualified.Name.Identifier.ValueText, + SimpleNameSyntax simple => simple.Identifier.ValueText, + _ => string.Empty + }; + + // The outermost dotted name whose leftmost identifier is a root namespace, outside using directives and namespace declarations. + private static bool IsQualifiedUse( + SyntaxNode node, + HashSet aliases + ) { + if ( + node is not (QualifiedNameSyntax or MemberAccessExpressionSyntax) + || node.Parent is QualifiedNameSyntax + || (node.Parent is MemberAccessExpressionSyntax parent && parent.Expression == node) + ) { + return false; + } + + SyntaxNode current = node; + while (true) + { + switch (current) + { + case QualifiedNameSyntax qualified: + current = qualified.Left; + continue; + case MemberAccessExpressionSyntax access when access.IsKind(SyntaxKind.SimpleMemberAccessExpression): + current = access.Expression; + continue; + } + + break; + } + + return ( + current is IdentifierNameSyntax root + && current != node + && ROOT_NAMESPACES.Contains(root.Identifier.ValueText, StringComparer.Ordinal) + && !aliases.Contains(root.Identifier.ValueText) + && !node.Ancestors().Any(static ancestor => ancestor is UsingDirectiveSyntax or BaseNamespaceDeclarationSyntax) + ); + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/StringBuildStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/StringBuildStyleRule.cs new file mode 100644 index 000000000..6efddc293 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/StringBuildStyleRule.cs @@ -0,0 +1,42 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// E-09: a string is built from values with interpolation, not with `string.Format` or `string.Concat`. +// A format string that is itself a value, and the concatenation of one sequence, have no interpolated form. +internal sealed class StringBuildStyleRule : StyleRule +{ + private const string C_ID = "E-09"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (InvocationExpressionSyntax call in source.root.DescendantNodes().OfType()) + { + if (call.Expression is not MemberAccessExpressionSyntax { Expression: PredefinedTypeSyntax receiver } access) + { + continue; + } + if (!receiver.Keyword.IsKind(SyntaxKind.StringKeyword)) continue; + SeparatedSyntaxList arguments = call.ArgumentList.Arguments; + bool isFormat = access.Name.Identifier.ValueText == "Format" + && arguments.Any( + static argument => argument.Expression is LiteralExpressionSyntax or InterpolatedStringExpressionSyntax + ); + bool isConcat = access.Name.Identifier.ValueText == "Concat" && arguments.Count >= 2; + if (isFormat || isConcat) + { + findings.Add(source.Finding(C_ID, call.SpanStart, "Build the string with interpolation: `$\"...\"`.")); + } + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/ThisQualifierStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/ThisQualifierStyleRule.cs new file mode 100644 index 000000000..b84c08338 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/ThisQualifierStyleRule.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// E-08: a constructor assigns an instance member that is not an `m_` field through `this.`, and no other member +// writes `this.` unless a parameter or local variable hides the name. The check reads syntax only, so it knows +// the members that the same type declaration declares. +internal sealed class ThisQualifierStyleRule : StyleRule +{ + private const string C_ID = "E-08"; + private const string C_OWNER_PREFIX = "m_"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (TypeDeclarationSyntax type in source.root.DescendantNodes().OfType()) + { + HashSet instanceMembers = InstanceMembers(type); + HashSet members = type.Members.SelectMany(Names).ToHashSet(StringComparer.Ordinal); + foreach (MemberDeclarationSyntax member in type.Members) + { + if (member is BaseTypeDeclarationSyntax or DelegateDeclarationSyntax) continue; + HashSet hidden = Hidden(member); + if (member is ConstructorDeclarationSyntax constructor && !constructor.Modifiers.Any(SyntaxKind.StaticKeyword)) + { + CheckConstructor(source, findings, constructor, instanceMembers, hidden); + } + else + { + CheckMember(source, findings, member, members, hidden); + } + } + } + } + + private static void CheckConstructor( + StyleSource source, + ICollection findings, + ConstructorDeclarationSyntax constructor, + HashSet instanceMembers, + HashSet hidden + ) { + foreach (AssignmentExpressionSyntax assignment in constructor.DescendantNodes().OfType()) + { + if (assignment.Parent is InitializerExpressionSyntax) continue; + IEnumerable targets = assignment.Left is TupleExpressionSyntax tuple + ? tuple.Arguments.Select(static argument => argument.Expression) + : [assignment.Left]; + foreach (IdentifierNameSyntax target in targets.OfType()) + { + string name = target.Identifier.ValueText; + if (!instanceMembers.Contains(name) || hidden.Contains(name)) continue; + findings.Add( + source.Finding( + C_ID, + target.SpanStart, + "Assign an instance member through `this.` inside a constructor. Found `" + name + "`." + ) + ); + } + } + } + + private static void CheckMember( + StyleSource source, + ICollection findings, + MemberDeclarationSyntax member, + HashSet members, + HashSet hidden + ) { + foreach (MemberAccessExpressionSyntax access in member.DescendantNodes().OfType()) + { + if (access.Expression is not ThisExpressionSyntax) continue; + string name = access.Name.Identifier.ValueText; + if (!members.Contains(name) || hidden.Contains(name)) continue; + findings.Add( + source.Finding( + C_ID, + access.SpanStart, + "Write `this.` only inside a constructor or to disambiguate. Found `this." + name + "`." + ) + ); + } + } + + private static HashSet InstanceMembers(TypeDeclarationSyntax type) + => type.Members + .Where( + static member => ( + member is FieldDeclarationSyntax or PropertyDeclarationSyntax or EventFieldDeclarationSyntax + && !member.Modifiers.Any(SyntaxKind.StaticKeyword) + && !member.Modifiers.Any(SyntaxKind.ConstKeyword) + ) + ) + .SelectMany(Names) + .Where(static name => !name.StartsWith(C_OWNER_PREFIX, StringComparison.Ordinal)) + .ToHashSet(StringComparer.Ordinal); + + private static IEnumerable Names(MemberDeclarationSyntax member) + => member switch + { + BaseFieldDeclarationSyntax field => field.Declaration.Variables.Select(static variable => variable.Identifier.ValueText), + PropertyDeclarationSyntax property => [property.Identifier.ValueText], + EventDeclarationSyntax @event => [@event.Identifier.ValueText], + MethodDeclarationSyntax method => [method.Identifier.ValueText], + _ => [] + }; + + // The parameters and local variables that a member declares anywhere in its body can hide a member name. + private static HashSet Hidden(MemberDeclarationSyntax member) + { + var names = new HashSet(StringComparer.Ordinal); + foreach (SyntaxNode node in member.DescendantNodes()) + { + switch (node) + { + case ParameterSyntax parameter: + names.Add(parameter.Identifier.ValueText); + break; + case VariableDeclaratorSyntax variable: + names.Add(variable.Identifier.ValueText); + break; + case SingleVariableDesignationSyntax designation: + names.Add(designation.Identifier.ValueText); + break; + case ForEachStatementSyntax loop: + names.Add(loop.Identifier.ValueText); + break; + case LocalFunctionStatementSyntax function: + names.Add(function.Identifier.ValueText); + break; + } + } + + return names; + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/UsingDeclarationStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/UsingDeclarationStyleRule.cs new file mode 100644 index 000000000..d03ea748d --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/UsingDeclarationStyleRule.cs @@ -0,0 +1,157 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace Inno.Tooling.Architecture; + +// E-12: a resource that lives until the end of the enclosing block is a `using` declaration. +// A `using` statement that closes its block releases the resource at the same point, so it is rewritten. +internal sealed class UsingDeclarationStyleRule : StyleRule +{ + private const string C_ID = "E-12"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (UsingStatementSyntax statement in Violations(source.root)) + { + findings.Add( + source.Finding(C_ID, statement.SpanStart, "Write a `using` declaration: the resource lives until the block ends.") + ); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + IReadOnlyList protectedSpans = source.ProtectedSpans(); + List edits = []; + int fixedEnd = -1; + foreach (UsingStatementSyntax statement in Violations(source.root)) + { + // A statement nested in one that this round rewrites waits for the next round. + if (statement.SpanStart < fixedEnd) continue; + List? rewrite = Rewrite(source, statement, protectedSpans); + if (rewrite is null) continue; + edits.AddRange(rewrite); + fixedEnd = statement.Span.End; + } + + return edits; + } + + private static IEnumerable Violations(SyntaxNode root) + { + foreach (UsingStatementSyntax statement in root.DescendantNodes().OfType()) + { + // An expression without a variable has no declaration form. + if (statement.Declaration is null) continue; + if (statement.Parent is not BlockSyntax block || block.Statements.Last() != statement) continue; + + // A declaration cannot follow a label, and a jump into its scope is not allowed. + if (block.Statements.Any(static sibling => sibling is LabeledStatementSyntax)) continue; + + // A name declared in the statement and again in a sibling scope would collide in the shared block. + HashSet names = [.. DeclaredNames(statement)]; + if (block.Statements.Where(sibling => sibling != statement).SelectMany(DeclaredNames).Any(names.Contains)) + { + continue; + } + yield return statement; + } + } + + private static IEnumerable DeclaredNames(SyntaxNode scope) + { + foreach (SyntaxNode node in scope.DescendantNodes()) + { + SyntaxToken identifier = node switch + { + VariableDeclaratorSyntax declarator => declarator.Identifier, + SingleVariableDesignationSyntax designation => designation.Identifier, + ForEachStatementSyntax loop => loop.Identifier, + CatchDeclarationSyntax caught => caught.Identifier, + ParameterSyntax parameter => parameter.Identifier, + LocalFunctionStatementSyntax function => function.Identifier, + _ => default + }; + if (!identifier.IsKind(SyntaxKind.None)) yield return identifier.ValueText; + } + } + + private static List? Rewrite( + StyleSource source, + UsingStatementSyntax statement, + IReadOnlyList protectedSpans + ) { + VariableDeclarationSyntax declaration = statement.Declaration!; + if (!StyleLayout.IsBlank(source.content, statement.OpenParenToken.Span.End, declaration.SpanStart)) return null; + if (!StyleLayout.IsBlank(source.content, declaration.Span.End, statement.CloseParenToken.SpanStart)) + { + return null; + } + if (!source.IsLastOnLine(statement.CloseParenToken)) return null; + List edits = + [ + new StyleEdit(statement.UsingKeyword.Span.End, declaration.SpanStart, " "), + new StyleEdit(declaration.Span.End, statement.CloseParenToken.Span.End, ";") + ]; + int indentation = source.Indentation(statement.SpanStart); + if (statement.Statement is not BlockSyntax body) + { + AddShifts( + source, + edits, + source.LineNumber(statement.Statement.SpanStart), + source.LineNumber(statement.Statement.Span.End), + indentation - source.Indentation(statement.Statement.SpanStart), + protectedSpans + ); + return edits; + } + if (!source.IsFirstOnLine(body.OpenBraceToken) || !source.IsLastOnLine(body.OpenBraceToken)) return null; + if (!source.IsFirstOnLine(body.CloseBraceToken) || !source.IsLastOnLine(body.CloseBraceToken)) return null; + if (body.OpenBraceToken.HasLeadingTrivia && body.OpenBraceToken.LeadingTrivia.Any(IsComment)) return null; + if (body.CloseBraceToken.LeadingTrivia.Any(IsComment)) return null; + int openLine = source.LineNumber(body.OpenBraceToken.SpanStart); + int closeLine = source.LineNumber(body.CloseBraceToken.SpanStart); + edits.Add(RemoveLine(source, openLine)); + AddShifts(source, edits, openLine + 1, closeLine - 1, -StyleLayout.C_INDENT, protectedSpans); + edits.Add(RemoveLine(source, closeLine)); + return edits; + } + + private static bool IsComment(SyntaxTrivia trivia) + => trivia.Kind() is SyntaxKind.SingleLineCommentTrivia or SyntaxKind.MultiLineCommentTrivia || trivia.IsDirective; + + private static StyleEdit RemoveLine( + StyleSource source, + int line + ) { + TextLine textLine = source.text.Lines[line]; + return new StyleEdit(textLine.Start, textLine.EndIncludingLineBreak, string.Empty); + } + + private static void AddShifts( + StyleSource source, + List edits, + int firstLine, + int lastLine, + int delta, + IReadOnlyList protectedSpans + ) { + if (delta == 0) return; + for (int line = firstLine; line <= lastLine; line++) + { + StyleEdit? shift = StyleLayout.Shift(source, line, delta, protectedSpans); + if (shift is not null) edits.Add(shift); + } + } +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs b/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs index 18d460cb6..056d3b741 100644 --- a/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs +++ b/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs @@ -40,6 +40,7 @@ internal static class StyleEngine new ClauseStyleRule(), new ArrowMemberStyleRule(), new LeadingOperatorStyleRule(), + new AssignmentBreakStyleRule(), new ChainStyleRule(), new SingleLineBlockStyleRule(), new StatementLineStyleRule(), @@ -68,7 +69,18 @@ internal static class StyleEngine new UsingPlacementStyleRule(), new BuiltInTypeStyleRule(), new MemberOrderStyleRule(), - new NamingStyleRule() + new NamingStyleRule(), + new ThisQualifierStyleRule(), + new QualifiedNameStyleRule(), + new NullPatternStyleRule(), + new UsingDeclarationStyleRule(), + new ObjectCreationStyleRule(), + new CollectionExpressionStyleRule(), + new ArgumentGuardStyleRule(), + new CancellationParameterStyleRule(), + new ProhibitedTriviaStyleRule(), + new StringBuildStyleRule(), + new ExpressionBodyStyleRule() ]; internal static IEnumerable EnumerateSources(string root) From 8bbb116778710a631cb5716e81a1fe85c5abf04c Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sun, 22 Nov 2026 02:36:42 +0000 Subject: [PATCH 26/33] chore(git): skip the mechanical rule commit in blame --- .git-blame-ignore-revs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 1ff9b41b3..173b92727 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -10,3 +10,5 @@ c46af2ba7e19ca3a69f2ab46bdb4aa8d17d70bec # Rename test methods and remaining members to the naming table 49f33b29104df851a5ed5ad7cea453c68d527dc4 +# Apply the remaining mechanical rulebook rules +dce88f2ec6c70c91cdd7c9a9dcabd30e8d431a4d From 840d139fa9e9be55c8d9c370caca105b22b96e2b Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sun, 22 Nov 2026 03:23:27 +0000 Subject: [PATCH 27/33] style(csharp): keep one top-level type per file Apply F-02 to all handwritten C#. A file is named after its primary type, which comes first. Classes, structs, interfaces and records with a body move to their own files; an enum, a delegate or a positional record stays with the type it belongs to. Additional parts of a partial type are named Type.Part.cs. Using directives that a moved type no longer needs are removed. Declarations are moved verbatim. Compiler diagnostics and local test results match the previous commit. --- .../Intermediate/BgfxShaderIrGenerator.cs | 17 +- .../Sources/BgfxShaderSourceFrontend.cs | 454 --- .../Sources/BgfxSourceDeclarationParser.cs | 459 +++ .../Sources/BgfxSourceLexer.cs | 23 +- .../Sources/BgfxSourceSyntaxException.cs | 12 + .../BgfxBufferKind.cs | 10 + ...BgfxResources.cs => BgfxBufferResource.cs} | 111 - .../BgfxPipelineResource.cs | 75 + .../BgfxShaderBindingResource.cs | 34 + .../Surfaces/IBgfxSurfaceIntegration.cs | 30 +- .../Reloading/AssemblyUnloadMonitor.cs | 30 +- .../Api/IPlatformImGuiRenderer.Api.cs | 76 - .../Api/ImGuiTextureHandle.cs | 32 + .../Api/PlatformImGuiViewportTarget.cs | 48 + .../ImGuiFont.cs | 30 - .../ImGuiFontScope.cs | 31 + build/cli/Inno.Build.Cli/BuildCommand.cs | 17 +- build/pipeline/Inno.Build/BuildDiagnostic.cs | 38 +- .../BuildArtifactCopier.cs | 129 + .../BuildArtifactOptions.cs | 125 - .../Native/NativeArtifact.cs | 46 +- .../Native/NativeBindingGenerationRequest.cs | 30 +- .../Native/NativeComponentBuildOptions.cs | 30 +- .../HeaderAttribute.cs | 39 + .../HelpBoxAttribute.cs | 109 + .../HideIfAttribute.cs | 74 + .../InspectorCondition.cs | 40 + .../InspectorMessageType.cs | 20 + .../InspectorNameAttribute.cs | 28 + .../InspectorPresentationAttribute.cs | 21 + .../InspectorPresentationAttributes.cs | 503 ---- .../InspectorReadOnlyAttribute.cs | 9 + .../Inno.Editor.Annotations/RangeAttribute.cs | 46 + .../ShowIfAttribute.cs | 74 + .../Inno.Editor.Annotations/SpaceAttribute.cs | 28 + .../Inno.Editor.Annotations/TextAttribute.cs | 28 + .../TooltipAttribute.cs | 28 + .../Creation/AssetCreationContext.cs | 42 + .../Creation/AssetCreationMenuAttribute.cs | 116 + .../Creation/AssetCreationTemplate.cs | 150 - .../AssetImportSettingsEdits.cs | 68 - .../AssetImportSettingsHistory.cs | 74 + .../Compilation/EditorShaderCompilation.cs | 118 +- ...n.cs => IEditorShaderArtifactValidator.cs} | 28 +- .../EditorGizmoContext.cs | 59 + .../Inno.Editor.Rendering/EditorGizmoFrame.cs | 60 + .../EditorGizmoProvider.cs | 173 -- .../EditorGizmoProviderExtensionAttribute.cs | 27 + .../EditorPreviewHandle.cs | 67 + .../EditorViewportComposition.cs | 94 + .../EditorViewportContext.cs | 120 + .../EditorViewportContribution.cs | 60 + .../EditorViewportContributor.cs | 450 +-- ...orViewportContributorExtensionAttribute.cs | 59 + .../EditorViewportFocusBounds.cs | 53 + .../EditorViewportKindID.cs | 39 + .../EditorViewportLayer.cs | 60 + .../EditorViewportManipulationSpace.cs | 65 + .../EditorViewportNavigationCapabilities.cs | 39 + .../EditorViewportNavigationMode.cs | 20 + .../EditorViewportNavigationProfile.cs | 141 + .../EditorViewportNavigationProfileID.cs | 39 + ...on.cs => EditorViewportNavigationState.cs} | 292 -- .../EditorViewportOutput.cs | 203 -- .../EditorViewportPointerContext.cs | 41 + .../EditorViewportPresentation.cs | 41 + .../EditorViewportProjection.cs | 16 + .../Inno.Editor.Rendering/IEditorGizmoSink.cs | 42 + ...iewService.cs => IEditorPreviewService.cs} | 66 - .../IEditorRenderingHost.cs | 58 + .../Pipelines/PipelineDocuments.cs | 74 - .../Pipelines/PipelineDraftHistory.cs | 77 + .../History/SceneHierarchyHistoryData.cs | 14 +- .../History/ScenePropertyHistoryData.cs | 12 +- .../ReloadPluginsAction.cs | 28 + ...oadActions.cs => ReloadScriptingAction.cs} | 25 - .../Runtime/IEditorScriptCompilation.cs | 46 +- .../Materials/MaterialDocuments.cs | 73 - .../Materials/MaterialDraftHistory.cs | 77 + .../Previews/ShaderPreviewContext.cs | 99 + .../Previews/ShaderPreviewProvider.cs | 115 - .../ShaderPreviewProviderAttribute.cs | 20 + .../Runtime/EditorStatistic.cs | 100 + .../Runtime/EditorStatisticGroupID.cs | 42 + .../Runtime/EditorStatisticID.cs | 42 + .../Runtime/EditorStatistics.cs | 175 -- .../Inno.Editor.Graph/GraphClipboardData.cs | 28 + .../GraphDocumentController.cs | 25 - .../Inno.Editor.Graph/GraphHistory.cs | 378 --- .../Inno.Editor.Graph/GraphHistoryData.cs | 144 + .../GraphHistoryDocumentCodec.cs | 42 + .../Inno.Editor.Graph/GraphHistoryHandler.cs | 121 + .../GraphHistoryTransition.cs | 85 + .../BuiltInInspectorAttributeDrawers.cs | 273 -- .../HeaderInspectorAttributeDrawer.cs | 21 + .../HelpBoxInspectorAttributeDrawer.cs | 45 + .../HideIfInspectorAttributeDrawer.cs | 23 + .../InspectorConditionEvaluator.cs | 79 + .../NameInspectorAttributeDrawer.cs | 15 + .../RangeInspectorAttributeDrawer.cs | 20 + .../ReadOnlyInspectorAttributeDrawer.cs | 15 + .../ShowIfInspectorAttributeDrawer.cs | 23 + .../SpaceInspectorAttributeDrawer.cs | 22 + .../TextInspectorAttributeDrawer.cs | 31 + .../TooltipInspectorAttributeDrawer.cs | 15 + .../ObjectDrawing/IInspectionDrawer.cs | 59 + .../ObjectDrawing/InspectionDrawer.cs | 56 - .../PropertyDrawing/ColorPropertyDrawer.cs | 33 + .../PropertyDrawing/ComponentFieldDrawer.cs | 31 + .../MathematicsPropertyDrawers.cs | 342 --- .../QuaternionPropertyDrawer.cs | 34 + .../PropertyDrawing/RectIntPropertyDrawer.cs | 38 + .../PropertyDrawing/RectPropertyDrawer.cs | 38 + .../Vector2IntPropertyDrawer.cs | 28 + .../PropertyDrawing/Vector2PropertyDrawer.cs | 28 + .../Vector3IntPropertyDrawer.cs | 33 + .../PropertyDrawing/Vector3PropertyDrawer.cs | 33 + .../Vector4IntPropertyDrawer.cs | 38 + .../PropertyDrawing/Vector4PropertyDrawer.cs | 38 + .../Actions/EditorAction.cs | 97 - .../Actions/EditorActionArgumentContext.cs | 23 + .../Actions/EditorActionContext.cs | 22 - .../Actions/EditorArgumentAction.cs | 64 + .../Actions/EditorPresentationAction.cs | 37 + .../Documents/IEditorDocumentService.cs | 38 +- .../DragDrop/EditorDrop.cs | 60 - .../DragDrop/EditorDropContext.cs | 59 + .../Menus/EditorMenuBuilder.cs | 39 - .../Menus/EditorMenuPlacement.cs | 40 + .../Viewport/EditorViewportPointerEvent.cs | 77 + .../Viewport/EditorViewportShortcut.cs | 46 + .../Viewport/EditorViewportTool.cs | 262 +- .../IEditorViewportCoordinateConverter.cs | 31 + .../Runtime/EditorSettingsHistory.cs | 83 - .../Runtime/EditorSettingsHistoryHandler.cs | 88 + .../Runtime/ProjectSettingsHistory.cs | 83 - .../Runtime/ProjectSettingsHistoryHandler.cs | 88 + .../Browser/FileBrowserData.cs | 45 +- .../Browser/FileBrowserRename.cs | 16 +- .../Interactions/AssetCreationMenu.cs | 57 + .../Interactions/CreateAssetCommand.cs | 55 - .../Targets/PipelineInspectionDrawer.cs | 327 --- .../Targets/PipelineInspector.cs | 238 ++ .../Targets/PipelineSourceDrawer.cs | 100 + ...ttings.cs => ClearConsoleOnPlaySetting.cs} | 18 - .../Settings/ConsoleSettingsPage.cs | 12 + .../Settings/DiagnosticsSettingsPage.cs | 12 + .../Presentation/BuildSettingsField.cs | 255 ++ .../Presentation/BuildSettingsPresentation.cs | 284 +- .../Runtime/BuildSettingsHistory.cs | 84 - .../Runtime/BuildSettingsHistoryHandler.cs | 89 + .../Runtime/SettingsEditSession.cs | 68 +- .../Runtime/SettingsField.cs | 57 + .../ShaderEditorDocuments.Clipboard.cs | 10 +- .../ShaderEditorDocuments.Creation.cs | 13 +- .../Documents/ShaderEditorDocuments.cs | 25 - .../Documents/ShaderPortSnapshot.cs | 27 + .../Inspection/ShaderAssetDrawer.cs | 88 + .../Inspection/ShaderInspectionDrawers.cs | 310 -- .../Inspection/ShaderSelectionDrawer.cs | 148 + .../Inspection/ShaderSourceDrawer.cs | 89 + ...onActions.cs => CollapseShaderSubgraph.cs} | 358 --- .../Interactions/CopyShaderNodes.cs | 27 + .../Interactions/CopyShaderToProject.cs | 52 + .../Interactions/CreateShaderAsset.cs | 31 - .../Interactions/CreateShaderNode.cs | 30 + .../Interactions/CreateShaderOutput.cs | 159 ++ .../Interactions/CutShaderNodes.cs | 25 + .../Interactions/DeleteShaderNodes.cs | 40 + .../Interactions/DisconnectShaderNodes.cs | 35 + .../Interactions/DuplicateShaderNodes.cs | 46 + .../Interactions/FocusShaderNodes.cs | 26 + .../Interactions/FormatShaderGraph.cs | 32 + .../Interactions/GroupShaderNodes.cs | 49 + .../Interactions/InsertShaderReroute.cs | 82 + .../Interactions/PasteShaderNodes.cs | 45 + .../Interactions/ReloadShaderSource.cs | 27 + .../Interactions/RevealShaderAsset.cs | 43 + .../Interactions/RevealShaderFunction.cs | 82 + .../Interactions/SaveShader.cs | 24 + .../Interactions/ShaderCanvasActions.cs | 677 ----- .../Interactions/ShaderCanvasGroup.cs | 19 + .../Interactions/ShaderCanvasMenu.cs | 211 ++ .../Interactions/ShaderSelectionAction.cs | 38 + .../Interactions/ShaderTemplateMenu.cs | 33 + .../Interactions/ShowShaderDiagnostics.cs | 26 + .../Interactions/UngroupShaderNodes.cs | 38 + .../OpenShaderEditorAction.cs | 35 + .../ShaderEditorPanel.cs | 33 - .../Navigation/AssetBrowserState.cs | 33 +- .../Runtime/EditorDragDropRenderer.cs | 49 - .../Runtime/EditorDropWidgetResult.cs | 51 + .../Inno.Editor.ImGui/TextInput/ImGuiFont.cs | 70 +- .../TextInput/ImGuiFontScope.cs | 50 + .../Inno.Editor.ImGui/Widgets/DialogLayout.cs | 39 + .../Widgets/ImGuiWidget.Dialog.cs | 104 +- .../Widgets/ImGuiWidget.Gizmo.cs | 200 +- .../Widgets/ImGuiWidget.InlineRename.cs | 83 - .../Widgets/ImGuiWidget.Selection.cs | 66 - .../Widgets/ImGuiWidget.Tree.cs | 175 -- .../Widgets/InlineRenamePresentation.cs | 86 + .../Widgets/ListNavigationResult.cs | 67 + .../Widgets/TransformGizmoOptions.cs | 66 + .../Widgets/TreeNodeDrawContext.cs | 17 + .../Widgets/TreeNodeOptions.cs | 62 + .../Widgets/TreeNodeResult.cs | 70 + .../Widgets/TreeWidgetHighlightRect.cs | 9 + .../Widgets/TreeWidgetLineSegment.cs | 9 + .../Widgets/TreeWidgetNodeState.cs | 11 + .../Widgets/TreeWidgetWindowState.cs | 18 + .../Materials/MaterialInspectionDrawer.cs | 476 ---- .../Materials/MaterialInspector.cs | 388 +++ .../Materials/MaterialSourceDrawer.cs | 99 + .../Nodes/ShaderNodeDrawContext.cs | 177 ++ .../Nodes/ShaderNodeDrawer.cs | 297 -- .../Nodes/ShaderNodeDrawerAttribute.cs | 70 + .../Nodes/ShaderNodePresentation.cs | 54 + .../Actions/ClearEditorSelectionAction.cs | 15 + ...{HistoryActions.cs => RedoEditorAction.cs} | 31 - ...Actions.cs => SelectEditorTargetAction.cs} | 12 - .../Actions/UndoEditorAction.cs | 35 + .../Exporting/ExportGameAction.cs | 16 + ...ExportActions.cs => ExportPluginAction.cs} | 13 - .../Settings/AppearanceSettingsPage.cs | 12 + .../Settings/EditorFramePacingModule.cs | 41 + .../Settings/EditorRenderingSettingsPage.cs | 12 + .../Settings/FileIconSetting.cs | 13 + .../Settings/FolderIconSetting.cs | 13 + .../Settings/FramePacingSettings.cs | 142 - .../Settings/GameObjectIconSetting.cs | 13 + .../Settings/GlobalSettingsPage.cs | 12 + .../Settings/GlobalSettingsPages.cs | 30 - .../{IconSettings.cs => IconSetting.cs} | 93 - .../Settings/IconSettingsPage.cs | 12 + .../Settings/LayersIconSetting.cs | 13 + .../Settings/MaterialIconSetting.cs | 13 + .../Settings/MaximumFrameRateSetting.cs | 54 + .../Settings/PrefabIconSetting.cs | 13 + .../Settings/RenderPipelineIconSetting.cs | 13 + .../Settings/SceneIconSetting.cs | 13 + .../Settings/ShaderIconSetting.cs | 13 + .../Settings/ShaderSourceIconSetting.cs | 14 + .../Settings/VerticalSyncSetting.cs | 47 + .../Zoom/ActualSizeEditorAction.cs | 36 + .../Inno.Editor.Workbench/Zoom/ZoomActions.cs | 100 - .../Zoom/ZoomInEditorAction.cs | 36 + .../Zoom/ZoomOutEditorAction.cs | 36 + .../animation/Inno.Animation/Animation.cs | 32 - .../Inno.Animation/AnimationBindingID.cs | 39 + .../Inno.Animation/AnimationClipAsset.cs | 142 - .../Inno.Animation/AnimationClock.cs | 16 + .../Inno.Animation/AnimationEventMarker.cs | 27 + .../AnimationExecutionContext.cs | 32 + .../Inno.Animation/AnimationInterpolation.cs | 16 + .../Inno.Animation/AnimationKeyframe.cs | 43 + .../Inno.Animation/AnimationMarkerEvent.cs | 52 + .../Inno.Animation/AnimationPlayOptions.cs | 44 + .../Inno.Animation/AnimationPlaybackHandle.cs | 27 + .../Inno.Animation/AnimationPlaybackState.cs | 16 + .../Inno.Animation/AnimationSample.cs | 54 + .../Inno.Animation/AnimationTrack.cs | 84 + .../Inno.Animation/AnimationTypes.cs | 383 --- .../Inno.Animation/AnimationValue.cs | 168 ++ .../Inno.Animation/IAnimationBindingSink.cs | 17 + .../Inno.Animation/IAnimationService.cs | 51 - .../Editing/AssetSourceSnapshot.cs | 34 + .../Editing/AssetSourceStore.cs | 33 - .../Artifacts/AssetArtifactManifest.cs | 18 - .../Artifacts/AssetArtifactOutputData.cs | 21 + .../Importing/AssetImportProduct.cs | 23 + .../Importing/AssetImporter.cs | 44 - .../Importing/AssetImporterAttribute.cs | 27 + .../Importing/Building/AssetBuildProcessor.cs | 25 - .../Building/AssetBuildProcessorAttribute.cs | 27 + .../Importing/Internal/AssetDependencyData.cs | 16 + .../Internal/AssetImportDependencyData.cs | 27 + .../Importing/Internal/AssetMeta.cs | 37 - .../AssetSampleSourceRewriterAttribute.cs | 27 + ...iter.cs => AssetSampleTransformContext.cs} | 43 - .../Sources/IAssetSampleSourceRewriter.cs | 19 + .../Sources/Watching/AssetWatcher.cs | 8 - .../Sources/Watching/WatcherPollResult.cs | 11 + src/content/assets/Inno.Assets/AssetPath.cs | 52 - .../assets/Inno.Assets/AssetSourceID.cs | 56 + .../Inno.Assets/Runtime/ArtifactLease.cs | 94 + .../assets/Inno.Assets/Runtime/AssetLease.cs | 46 + .../Inno.Assets/Runtime/AssetResidency.cs | 332 --- .../Runtime/AssetResidencyProvider.cs | 52 + .../Runtime/AssetResidencyStatistics.cs | 44 + .../Inno.Assets/Runtime/IAssetResidency.cs | 71 + .../Inno.Assets/Runtime/RetentionScope.cs | 41 + .../Core/GameTagSettingContribution.cs | 41 + .../Core/GameTagSettingsComposer.cs | 37 - .../Layers/GameLayerSettingContribution.cs | 104 + .../Layers/GameLayerSettingsComposer.cs | 99 - .../Prefabs/PrefabStructureOverride.cs | 12 +- .../Serialization/EngineReferenceToken.cs | 10 +- .../scene/Inno.Scene/Storage/SceneStore.cs | 49 +- .../Storage/SceneStructureSnapshot.cs | 28 +- .../IndexedObjectStore/IIndexedObjectIndex.cs | 101 + .../IndexedObjectStore/IIndexedObjectStore.cs | 26 + .../IndexedObjectStore/IndexedObjectIndex.cs | 97 - .../IndexedObjectStore/IndexedObjectKey.cs | 40 +- .../IndexedObjectStore/IndexedObjectStore.cs | 23 - .../YieldInstructions/YieldInstruction.cs | 4 +- .../Events/ApplicationEvent.cs | 6 + ...ationEvents.cs => ApplicationQuitEvent.cs} | 5 - .../core/Inno.Core.Events/Events/KeyEvent.cs | 37 + .../core/Inno.Core.Events/Events/KeyEvents.cs | 111 - .../Events/KeyPressedEvent.cs | 31 + .../Events/KeyReleasedEvent.cs | 21 + .../Events/MouseButtonEvent.cs | 23 + .../Events/MouseButtonPressedEvent.cs | 17 + .../Events/MouseButtonReleasedEvent.cs | 17 + .../Inno.Core.Events/Events/MouseEvent.cs | 38 + .../Inno.Core.Events/Events/MouseEvents.cs | 182 -- .../Events/MouseMovedEvent.cs | 66 + .../Events/MouseScrolledEvent.cs | 30 + .../Inno.Core.Events/Events/TextInputEvent.cs | 30 + .../Events/WindowCloseEvent.cs | 9 + .../Inno.Core.Events/Events/WindowEvent.cs | 15 + .../Inno.Core.Events/Events/WindowEvents.cs | 72 - .../Events/WindowFocusChangedEvent.cs | 21 + .../Events/WindowResizeEvent.cs | 30 + .../core/Inno.Core.Graphs/GraphDefinitions.cs | 212 -- .../core/Inno.Core.Graphs/GraphDiagnostic.cs | 69 + .../core/Inno.Core.Graphs/GraphDocument.cs | 177 -- .../core/Inno.Core.Graphs/GraphEdgeID.cs | 37 + .../core/Inno.Core.Graphs/GraphEdgeRecord.cs | 44 + .../core/Inno.Core.Graphs/GraphEndpoint.cs | 34 + .../core/Inno.Core.Graphs/GraphIDs.cs | 138 - .../Inno.Core.Graphs/GraphNodeDefinition.cs | 61 + .../core/Inno.Core.Graphs/GraphNodeID.cs | 37 + .../core/Inno.Core.Graphs/GraphNodeRecord.cs | 106 + .../Inno.Core.Graphs/GraphPortCapacity.cs | 16 + .../Inno.Core.Graphs/GraphPortDefinition.cs | 78 + .../Inno.Core.Graphs/GraphPortDirection.cs | 16 + .../core/Inno.Core.Graphs/GraphPortID.cs | 37 + .../core/Inno.Core.Graphs/GraphPosition.cs | 34 + .../Inno.Core.Graphs/GraphValidationResult.cs | 50 + .../{GraphValidation.cs => GraphValidator.cs} | 110 - .../IGraphNodeDefinitionResolver.cs | 24 + .../Inno.Core.Graphs/IGraphTypeConversion.cs | 24 + .../Internal/ArraySerializationNode.cs | 16 + .../Internal/ConverterInvoker.cs | 153 + .../Internal/ConverterRegistry.cs | 270 -- .../Internal/ConverterRegistryLease.cs | 126 + .../Internal/MapSerializationNode.cs | 8 + .../Internal/NullSerializationNode.cs | 8 + .../Internal/ObjectSerializationNode.cs | 20 + .../Internal/SerializationNode.cs | 42 - .../core/Inno.Core.Settings/ProjectID.cs | 129 + .../Inno.Core.Settings/ProjectIdentity.cs | 320 --- .../ProjectIdentitySettings.cs | 50 + .../core/Inno.Core.Settings/ProjectLocalID.cs | 93 + .../Inno.Core.Settings/ProjectScopedID.cs | 57 + ...mposition.cs => ProjectSettingComposer.cs} | 127 - .../ProjectSettingComposerAttribute.cs | 28 + .../ProjectSettingCompositionEntry.cs | 6 + .../ProjectSettingContracts.cs | 207 -- .../ProjectSettingContribution.cs | 46 + .../ProjectSettingContributionContext.cs | 58 + .../ProjectSettingDefinitionAttribute.cs | 38 + .../Inno.Core.Settings/ProjectSettingID.cs | 39 + .../ProjectSettingRecord.cs | 54 + .../ProjectSettingsContributor.cs | 72 + .../ProjectSettingsDocument.cs | 15 + .../Catalog/AssemblyCatalogCoordinator.cs | 163 -- .../Catalog/AssemblyCatalogRefreshSet.cs | 145 + .../Catalog/CatalogParticipantRegistration.cs | 26 + .../Modules/AssemblyModuleInfo.cs | 23 +- .../Reloading/AssemblyReloadSession.cs | 12 - .../Reloading/ReloadState.cs | 13 + .../Inno.Extensibility.Types/ITypeRegistry.cs | 15 + .../ITypeRegistryTransaction.cs | 19 + .../TypeRegistryCoordinator.cs | 199 -- .../TypeRegistryNoopTransaction.cs | 21 + .../TypeRegistryRefreshSet.cs | 129 + .../TypeRegistryRegistration.cs | 26 + .../Inno.Runtime/Execution/RuntimeClock.cs | 65 + .../engine/Inno.Runtime/Execution/Time.cs | 63 - .../Presentation/GamePresentationSettings.cs | 57 - .../Presentation/GamePresentationViewport.cs | 60 + .../Subsystems/SceneRuntimeSubsystem.cs | 24 - .../SceneRuntimeSubsystemFactory.cs | 28 + .../Inno.Plugins.Authoring/PluginCandidate.cs | 75 + .../PluginDiagnostic.cs | 34 + .../PluginScanResult.cs | 29 + .../PluginSourceKind.cs | 16 + .../PluginSourceLimits.cs | 42 + .../PluginSourceModels.cs | 191 -- .../Assets/ScriptSourceTypeDeclaration.cs | 61 + .../Assets/ScriptSourceTypeManifest.cs | 60 - .../Compilation/ScriptApiCatalog.cs | 76 +- .../Compilation/ScriptApiMap.cs | 14 - .../Compilation/ScriptApiNamespaceMap.cs | 17 + .../Compilation/ScriptApiReferenceBuilder.cs | 19 +- .../ScriptDeploymentReferenceResolver.cs | 10 +- src/services/audio/Inno.Audio/Audio.cs | 35 - .../audio/Inno.Audio/AudioBusDefinition.cs | 86 + .../audio/Inno.Audio/AudioBusHandle.cs | 27 + src/services/audio/Inno.Audio/AudioBusID.cs | 44 + .../audio/Inno.Audio/AudioCapabilities.cs | 68 + .../audio/Inno.Audio/AudioClipAsset.cs | 153 - .../audio/Inno.Audio/AudioClipHandle.cs | 27 + .../audio/Inno.Audio/AudioClipLoadMode.cs | 20 + .../audio/Inno.Audio/AudioClipMetadata.cs | 79 + .../Inno.Audio/AudioClipMetadataCodec.cs | 80 + src/services/audio/Inno.Audio/AudioCodecID.cs | 54 + .../audio/Inno.Audio/AudioCompletionReason.cs | 28 + .../audio/Inno.Audio/AudioContentProvider.cs | 249 -- .../Inno.Audio/AudioContentProviderContext.cs | 217 ++ .../AudioContentProviderExtensionAttribute.cs | 38 + .../audio/Inno.Audio/AudioDeviceCompletion.cs | 40 + .../audio/Inno.Audio/AudioDeviceState.cs | 28 + .../audio/Inno.Audio/AudioDistanceModel.cs | 24 + ...udioContent.cs => AudioEmitterSnapshot.cs} | 57 - .../audio/Inno.Audio/AudioExecutionContext.cs | 38 + src/services/audio/Inno.Audio/AudioHandles.cs | 105 - .../audio/Inno.Audio/AudioListenerHandle.cs | 27 + .../audio/Inno.Audio/AudioListenerSnapshot.cs | 60 + .../audio/Inno.Audio/AudioListenerState.cs | 64 + src/services/audio/Inno.Audio/AudioMixer.cs | 417 --- .../audio/Inno.Audio/AudioMixerAsset.cs | 40 + .../audio/Inno.Audio/AudioMixerBuilder.cs | 130 + .../audio/Inno.Audio/AudioMixerExtension.cs | 21 + .../AudioMixerExtensionAttribute.cs | 27 + .../audio/Inno.Audio/AudioMixerExtensions.cs | 102 - .../audio/Inno.Audio/AudioMixerFeature.cs | 21 + .../AudioMixerFeatureConfiguration.cs | 56 + .../AudioMixerFeatureExtensionAttribute.cs | 38 + .../audio/Inno.Audio/AudioParameterID.cs | 69 + .../audio/Inno.Audio/AudioPlayOptions.cs | 134 + .../audio/Inno.Audio/AudioPlaybackState.cs | 32 + .../Inno.Audio/AudioProcessorConfiguration.cs | 48 + .../audio/Inno.Audio/AudioProcessorID.cs | 79 + .../Inno.Audio/AudioProcessorParameter.cs | 40 + .../audio/Inno.Audio/AudioProtocolIDs.cs | 237 -- .../audio/Inno.Audio/AudioSpatialOptions.cs | 158 ++ .../audio/Inno.Audio/AudioStatistics.cs | 60 + src/services/audio/Inno.Audio/AudioTypes.cs | 666 ----- .../audio/Inno.Audio/AudioVoiceHandle.cs | 27 + .../audio/Inno.Audio/AudioVoiceParameters.cs | 71 + src/services/audio/Inno.Audio/IAudioDevice.cs | 37 - .../SerializedAudioExtensionState.cs | 47 + src/services/input/Inno.Input/Input.cs | 45 - .../input/Inno.Input/InputExecutionContext.cs | 46 + .../Compilation/CompiledShaderArtifact.cs | 140 + .../Compilation/CompiledShaderPass.cs | 63 + .../Compilation/IShaderCompilerToolchain.cs | 61 + ...tCompiler.cs => ITextureTargetCompiler.cs} | 2 - .../Compilation/ShaderArtifactSelection.cs | 61 + .../Compilation/ShaderCompilation.cs | 453 --- .../Compilation/ShaderCompilationResult.cs | 49 + .../Compilation/ShaderCompileTarget.cs | 65 + ...Compilation.cs => ShaderCompiler.Graph.cs} | 2 - .../Compilation/ShaderCompiler.Stage.cs | 73 + .../Compilation/ShaderCompiler.cs | 46 + .../Compilation/ShaderLastGoodStore.cs | 58 - .../Compilation/ShaderStageArtifact.cs | 55 + .../Compilation/ShaderStageBinding.cs | 22 + .../Compilation/ShaderStageCompilation.cs | 168 -- .../Compilation/ShaderStageToolRequest.cs | 19 + .../Compilation/ShaderStageToolResult.cs | 65 + .../Editing/ShaderGraphSourceSnapshot.cs | 38 + .../Editing/ShaderGraphSourceStore.cs | 35 - ...MeshParser.cs => MeshSourceParser.Gltf.cs} | 4 - ...jMeshParser.cs => MeshSourceParser.Obj.cs} | 2 - .../Materials/MaterialValue.cs | 61 +- .../Shaders/ShaderRenderState.cs | 128 +- .../GraphicsSettings.cs | 83 - .../GraphicsSettingsExecutionContext.cs | 23 + .../GraphicsSettingsState.cs | 66 + .../Models/IPreparedViewDrawable.cs | 18 + .../Models/IViewContentCollector.cs | 22 + .../Models/IViewContentFrameSource.cs | 18 + .../Models/IViewContentSink.cs | 18 + .../Models/IViewContentSource.cs | 25 + .../Models/IViewDrawable.cs | 31 + .../Models/IViewPointerTarget.cs | 69 + .../Models/RenderView.cs | 70 + .../Models/SelectedViewContentCollector.cs | 60 + .../Models/ViewContent.cs | 502 ---- .../Models/ViewContentContext.cs | 102 + .../Models/ViewContentItem.cs | 81 + .../ViewContentSourceExtensionAttribute.cs | 29 + ...ratch.cs => RenderRuntime.FrameScratch.cs} | 1 - .../Requests/RenderRequestProvider.cs | 160 -- .../Requests/RenderRequestProviderContext.cs | 127 + ...RenderRequestProviderExtensionAttribute.cs | 40 + .../Resources/RenderMaterialPass.cs | 36 +- .../Compilation/IShaderNodeCompiler.cs | 36 + .../Compilation/ShaderBinaryNodeCompiler.cs | 69 + .../Compilation/ShaderBuiltinNodeCompilers.cs | 407 --- .../Compilation/ShaderConstantNodeCompiler.cs | 51 + .../ShaderConstructNodeCompiler.cs | 77 + .../Compilation/ShaderDiscardNodeCompiler.cs | 43 + .../Compilation/ShaderExtractNodeCompiler.cs | 50 + .../Compilation/ShaderGraphLoweringRequest.cs | 30 - .../Compilation/ShaderGraphLoweringResult.cs | 35 + .../Compilation/ShaderNodeCompiler.cs | 184 -- .../ShaderNodeDescriptionContext.cs | 81 + .../Compilation/ShaderNodeLoweringContext.cs | 50 + .../Compilation/ShaderNodePort.cs | 25 + ...mpilers.cs => ShaderSampleNodeCompiler.cs} | 46 - .../Compilation/ShaderSelectNodeCompiler.cs | 50 + .../Compilation/ShaderSourceNodeCompiler.cs | 139 + .../ShaderStageInputNodeCompiler.cs | 46 + .../ShaderStorageAtomicAddNodeCompiler.cs | 38 + .../ShaderStorageLoadNodeCompiler.cs | 38 + .../Compilation/ShaderStorageNodeCompilers.cs | 189 -- .../ShaderStorageStoreNodeCompiler.cs | 37 + .../Compilation/StorageNodePorts.cs | 46 + .../Documents/ShaderGraphCallNodeCompiler.cs | 39 + .../Documents/ShaderGraphClipboard.cs | 24 - .../Documents/ShaderGraphDocument.cs | 106 - .../Documents/ShaderGraphInputSettings.cs | 47 + .../ShaderGraphInputSettingsConverter.cs | 46 + .../Documents/ShaderGraphLiteralConverter.cs | 36 + .../Documents/ShaderGraphNodeInputSettings.cs | 15 + .../ShaderGraphNodeInputSettingsConverter.cs | 36 + .../ShaderGraphNodeInputsCompiler.cs | 43 + .../Documents/ShaderGraphNodeInterface.cs | 71 + .../ShaderGraphNodeInterfaceConverter.cs | 52 + .../ShaderGraphNodeOutputSettings.cs | 15 + .../ShaderGraphNodeOutputSettingsConverter.cs | 33 + .../ShaderGraphNodeOutputsCompiler.cs | 43 + .../ShaderGraphNodePortDefinition.cs | 31 + .../ShaderGraphNodePortDefinitionConverter.cs | 42 + .../Documents/ShaderGraphNodeSettings.cs | 45 + .../ShaderGraphNodeSettingsConverter.cs | 48 + .../Documents/ShaderGraphNodes.cs | 291 +- .../Documents/ShaderGraphOutput.cs | 27 + .../Documents/ShaderGraphPass.cs | 40 + .../Documents/ShaderGraphPassProgram.cs | 17 + .../Documents/ShaderGraphPasteResult.cs | 29 + ...Program.cs => ShaderGraphProgramResult.cs} | 35 - .../Documents/ShaderGraphPrograms.cs | 16 - .../Documents/ShaderGraphStageSettings.cs | 39 + .../ShaderGraphStageSettingsConverter.cs | 46 + .../Documents/ShaderGraphTypeConverter.cs | 60 + .../Documents/ShaderGraphValueConverters.cs | 367 --- .../Intermediate/ShaderIrBlock.cs | 128 +- .../Intermediate/ShaderIrInstruction.cs | 79 + .../Intermediate/ShaderIrStage.cs | 251 +- .../Intermediate/ShaderIrStageInput.cs | 82 + .../Intermediate/ShaderIrStageOutput.cs | 66 + .../Intermediate/ShaderIrValue.cs | 29 + .../Sources/IShaderSourceFrontend.cs | 183 +- .../Sources/IShaderSourceResolver.cs | 24 + .../Sources/ShaderSourceAnalysis.cs | 56 + .../Sources/ShaderSourceField.cs | 45 + .../Sources/ShaderSourceFunction.cs | 75 - .../ShaderSourceImplementationAnalysis.cs | 149 + .../ShaderSourceImplementationRequest.cs | 49 + .../Sources/ShaderSourceModuleAnalysis.cs | 275 +- .../Sources/ShaderSourceParameter.cs | 78 + .../Sources/ShaderSourceRequest.cs | 67 + .../Sources/ShaderSourceSnapshotResolver.cs | 57 + .../Sources/ShaderSourceType.cs | 42 - .../Targets/ShaderTarget.cs | 58 - .../Targets/ShaderTargetAttribute.cs | 28 + .../Targets/ShaderTargetContext.cs | 35 + .../Templates/RasterShaderGraphTemplate.cs | 25 + .../ReusableShaderGraphNodeTemplate.cs | 61 + .../Templates/ShaderBuiltInIDs.cs | 7 + .../Templates/ShaderGraphTemplate.cs | 123 - .../Templates/ShaderGraphTemplateAttribute.cs | 41 + .../Templates/ShaderGraphTemplateRegistry.cs | 28 +- .../Device/ComputePipelineHandle.cs | 23 + .../Inno.Rendering/Device/GraphicsApi.cs | 142 + .../Device/GraphicsCapabilities.cs | 380 +-- .../Inno.Rendering/Device/GraphicsLimits.cs | 60 + .../Device/GraphicsPipelineHandle.cs | 23 + .../Inno.Rendering/Device/IRenderDevice.cs | 57 +- .../Device/PersistentBufferHandle.cs | 23 + .../Device/PersistentTextureHandle.cs | 23 + .../Inno.Rendering/Device/RenderBindingID.cs | 31 + .../Inno.Rendering/Device/RenderBlendState.cs | 176 +- .../Device/RenderBufferDescriptor.cs | 82 + .../Device/RenderBufferHandle.cs | 26 + .../Device/RenderBufferSlice.cs | 44 + ...ads.cs => RenderBufferUploadDescriptor.cs} | 78 - .../Device/RenderBufferUsage.cs | 43 + ...derCommands.cs => RenderCommandEncoder.cs} | 203 -- ...rProtocolIDs.cs => RenderDataChannelID.cs} | 36 - .../Device/RenderDeviceFrameCounters.cs | 38 + .../Device/RenderFrameUploadProvider.cs | 36 + .../Device/RenderPassContext.cs | 25 + .../Device/RenderPassExecute.cs | 18 + .../Device/RenderRasterState.cs | 150 +- .../Inno.Rendering/Device/RenderResourceID.cs | 39 + .../Inno.Rendering/Device/RenderResources.cs | 555 ---- .../Device/RenderSamplerState.cs | 86 +- .../Device/RenderShaderBindingDescriptor.cs | 124 +- .../Device/RenderStencilFaceState.cs | 54 + .../Device/RenderStencilState.cs | 213 +- .../Device/RenderSurfaceHandle.cs | 23 + .../Device/RenderTextureDescriptor.cs | 218 ++ .../Device/RenderTextureDimension.cs | 20 + .../Device/RenderTextureFormat.cs | 48 + .../Device/RenderTextureHandle.cs | 26 + .../Device/RenderTextureReadbackHandle.cs | 23 + ...back.cs => RenderTextureReadbackResult.cs} | 22 - .../Device/RenderTextureRegion.cs | 93 + .../Device/RenderTextureUsage.cs | 39 + .../Device/RenderVertexAttribute.cs | 71 + .../Device/RenderVertexLayout.cs | 298 +- .../Graph/CompiledRenderAttachment.cs | 71 + .../Graph/CompiledRenderBuffer.cs | 53 + .../Graph/CompiledRenderGraph.cs | 390 --- .../Graph/CompiledRenderPass.cs | 92 + .../Graph/CompiledRenderTexture.cs | 53 + .../Graph/IRenderGraphBackend.cs | 42 + .../Inno.Rendering/Graph/RenderAttachment.cs | 14 + .../Graph/RenderBufferRecord.cs | 9 + .../Inno.Rendering/Graph/RenderClearColor.cs | 54 + .../Graph/RenderGraphCompileResult.cs | 44 + ...RenderGraphCompiler.ResourceAllocation.cs} | 1 - .../Graph/RenderGraphDiagnostic.cs | 69 + .../Inno.Rendering/Graph/RenderGraphTypes.cs | 356 --- ...enderGraphValidator.DependencyAnalysis.cs} | 1 - ....cs => RenderGraphValidator.Scheduling.cs} | 2 - .../Inno.Rendering/Graph/RenderLoadAction.cs | 20 + .../Inno.Rendering/Graph/RenderPassKind.cs | 20 + .../Inno.Rendering/Graph/RenderPassRecord.cs | 94 + .../Inno.Rendering/Graph/RenderPhaseID.cs | 34 + .../Graph/RenderResourceAccess.cs | 8 + .../Inno.Rendering/Graph/RenderResourceKey.cs | 6 + .../Inno.Rendering/Graph/RenderResourceUse.cs | 7 + .../Graph/RenderResourceUseKind.cs | 13 + .../Inno.Rendering/Graph/RenderStoreAction.cs | 16 + .../Graph/RenderTextureRecord.cs | 9 + .../Graph/RenderViewTransform.cs | 52 + .../Inno.Rendering/Targets/RenderTarget.cs | 30 +- src/services/storage/Inno.Storage/Storage.cs | 32 - .../Inno.Storage/StorageExecutionContext.cs | 35 + src/services/text/Inno.Text/FontAsset.cs | 91 - src/services/text/Inno.Text/FontMetadata.cs | 38 + .../text/Inno.Text/FontMetadataCodec.cs | 59 + src/services/text/Inno.Text/GlyphBitmap.cs | 88 + src/services/text/Inno.Text/Text.cs | 31 - src/services/text/Inno.Text/TextDirection.cs | 28 + .../text/Inno.Text/TextExecutionContext.cs | 32 + src/services/text/Inno.Text/TextFontHandle.cs | 15 + src/services/text/Inno.Text/TextFontStyle.cs | 20 + src/services/text/Inno.Text/TextGlyph.cs | 32 + src/services/text/Inno.Text/TextLayout.cs | 68 + src/services/text/Inno.Text/TextMetrics.cs | 27 + .../text/Inno.Text/TextShapingOptions.cs | 55 + src/services/text/Inno.Text/TextStyle.cs | 88 + src/services/text/Inno.Text/TextTypes.cs | 407 --- .../ui/Inno.UI.Assets/IUIDocumentFrontend.cs | 23 + .../ui/Inno.UI.Assets/UIDocumentAnalysis.cs | 57 + .../ui/Inno.UI.Assets/UIDocumentDiagnostic.cs | 23 + .../UIDocumentFontDeclaration.cs | 25 + .../ui/Inno.UI.Assets/UIDocumentFrontend.cs | 266 -- .../UIDocumentFrontendCatalog.cs | 58 + .../UIDocumentFrontendRegistry.cs | 75 + .../UIDocumentImportPipeline.cs | 90 + .../ui/Inno.UI.Assets/UIDocumentImporter.cs | 83 - .../ui/Inno.UI.Assets/UIDocumentSourceFile.cs | 22 + src/services/ui/Inno.UI/UI.cs | 30 - .../ui/Inno.UI/UIBackendCapabilities.cs | 23 - .../UICapabilityUnavailableException.cs | 26 + src/services/ui/Inno.UI/UIClipRectangle.cs | 23 + .../{UIHandles.cs => UIContextHandle.cs} | 14 - src/services/ui/Inno.UI/UIContextOptions.cs | 63 + src/services/ui/Inno.UI/UIDocumentFragment.cs | 41 + src/services/ui/Inno.UI/UIDocumentHandle.cs | 15 + ...Identifiers.cs => UIDocumentLanguageID.cs} | 0 src/services/ui/Inno.UI/UIDocumentSource.cs | 52 + src/services/ui/Inno.UI/UIDrawCommand.cs | 23 + src/services/ui/Inno.UI/UIEvent.cs | 83 + src/services/ui/Inno.UI/UIExecutionContext.cs | 32 + src/services/ui/Inno.UI/UIInputSnapshot.cs | 104 + src/services/ui/Inno.UI/UIMeshUpdate.cs | 45 + src/services/ui/Inno.UI/UIRenderFrame.cs | 90 + .../ui/Inno.UI/UIRenderFrameBuilder.cs | 179 ++ src/services/ui/Inno.UI/UIRendering.cs | 423 --- src/services/ui/Inno.UI/UITextureData.cs | 54 + src/services/ui/Inno.UI/UITextureUpdate.cs | 50 + src/services/ui/Inno.UI/UITypes.cs | 382 --- src/services/ui/Inno.UI/UIVertex.cs | 27 + .../AlternateDependencyAssetImporter.cs | 20 + .../AssetLoaderTests.cs | 418 --- .../BuildConsumerAssetImporter.cs | 22 + .../BuildInputAssetImporter.cs | 32 + .../ClipContribution.cs | 9 + .../ClipSettings.cs | 13 + .../ClipSettingsBase.cs | 12 + .../ClipSettingsComposer.cs | 25 + .../ComposedClipSettings.cs | 11 + .../ConfiguredAsset.cs | 11 + .../ConfiguredImporter.cs | 29 + .../ConfiguredSettings.cs | 14 + .../DeferredAsset.cs | 6 + .../DeferredAssetImporter.cs | 24 + .../DependencyAsset.cs | 6 + .../DependencyAssetImporter.cs | 25 + .../ExtensionConsumerImporter.cs | 36 + .../ExtensionDependentAsset.cs | 6 + .../ExtensionDependentImporter.cs | 27 + .../Inno.Assets.Pipeline.Tests/HookAsset.cs | 39 + .../HookAssetImporter.cs | 20 + .../ImportGraphAsset.cs | 6 + .../ImportGraphAssetImporter.cs | 25 + .../ImportSettingsTests.cs | 43 - .../ImporterConflictAsset.cs | 6 + .../ImporterConflictAssetImporterA.cs | 23 + .../ImporterConflictAssetImporterB.cs | 23 + .../ImporterConflictProbe.cs | 6 + .../MixedScopeAssetImporter.cs | 30 + .../MutableAsset.cs | 11 + .../MutableAssetImporter.cs | 36 + .../PrivateConstructorAsset.cs | 11 + .../PrivateConstructorAssetImporter.cs | 24 + .../SettingsReferenceTests.cs | 54 - .../Inno.Assets.Pipeline.Tests/SlowAsset.cs | 11 + .../SlowAssetImporter.cs | 38 + .../TestBuildDefinitionAsset.cs | 11 + .../TestBuildProcessor.cs | 18 + .../DuplicateImporterA.cs | 41 + .../DuplicateImporterAsset.cs | 9 + .../DuplicateImporterB.cs | 41 + .../DuplicateImporters.cs | 86 - .../BgfxDeviceCollection.cs | 9 + .../BgfxDeviceFixture.cs | 28 + .../BgfxDeviceTests.cs | 31 - .../BgfxSurfaceRetirementTests.cs | 3 - .../WindowedBgfxCollection.cs | 6 + .../DiagnoseCollection.cs | 6 + .../DiagnosticHubTests.cs | 4 - .../LoggingBehaviorTests.cs | 4 - .../LoggingCollection.cs | 6 + .../AmbiguousHost.cs | 7 + .../AmbiguousLeftConverter.cs | 13 + .../AmbiguousRightConverter.cs | 13 + .../AmbiguousValue.cs | 3 + .../CaptureArrayRoot.cs | 17 + .../CaptureArrayRootConverter.cs | 54 + .../CaptureArrayRow.cs | 11 + .../CaptureBlobRoot.cs | 8 + .../CaptureBlobRootConverter.cs | 19 + .../CaptureConvertedValue.cs | 6 + .../CaptureConvertedValueConverter.cs | 26 + .../CaptureGetterStruct.cs | 16 + .../CaptureKeyContext.cs | 6 + .../CaptureKeyRoot.cs | 24 + .../CaptureKeyRootConverter.cs | 57 + .../CapturePropertyLoadContext.cs | 11 + .../CaptureRevisionProperties.cs | 35 + .../ConcurrentCaptureConverter.cs | 31 + .../ConcurrentCaptureValue.cs | 6 + .../ConvertedCaptureProperties.cs | 12 + .../ConvertedChild.cs | 6 + .../ConvertedChildConverter.cs | 13 + .../ConvertedChildHost.cs | 7 + .../ConvertedConstructorSample.cs | 11 + .../ConvertedConstructorSampleConverter.cs | 18 + .../ConvertedHookSample.cs | 10 + .../ConvertedHookSampleConverter.cs | 18 + .../CurrentSchemaSample.cs | 18 + .../CycleHost.cs | 7 + .../CycleValue.cs | 6 + .../CycleValueConverter.cs | 13 + .../DefaultSample.cs | 46 + .../DuplicateKeyBaseSample.cs | 8 + .../DuplicateKeyDerivedSample.cs | 7 + .../ExactBase.cs | 8 + .../ExactBaseConverter.cs | 14 + .../ExactHost.cs | 7 + .../ExactLeaf.cs | 3 + .../ExactLeafConverter.cs | 14 + .../FreshCaptureMetadataSource.cs | 15 + .../GenericBox.cs | 11 + .../GenericBoxConverter.cs | 13 + .../GenericBoxHost.cs | 7 + .../GetterCaptureProperties.cs | 12 + .../HookBaseSample.cs | 15 + .../HookDerivedSample.cs | 7 + .../IAmbiguousLeft.cs | 3 + .../IAmbiguousRight.cs | 3 + .../ISampleContext.cs | 3 + .../IVariantValue.cs | 6 + .../Inno.Core.Serialization.Tests/MapHost.cs | 9 + .../MissingChild.cs | 6 + .../MissingClassCollectionHost.cs | 9 + .../MissingClassHost.cs | 7 + .../MissingConstructorSample.cs | 12 + .../MissingRequiredConverterSample.cs | 4 + .../MissingSetterSample.cs | 7 + .../MutatingBinaryCapture.cs | 6 + .../MutatingBinaryCaptureConverter.cs | 16 + .../MutatingPropertyCapture.cs | 14 + .../NearestBase.cs | 8 + .../NearestBaseConverter.cs | 14 + .../NearestHost.cs | 7 + .../NearestLeaf.cs | 3 + .../NearestMid.cs | 4 + .../NearestMidConverter.cs | 14 + .../OrdinalCapture.cs | 6 + .../OrdinalCaptureConverter.cs | 19 + .../PreviousSchemaSample.cs | 13 + .../PrivateConstructorSample.cs | 14 + .../PureCaptureFields.cs | 6 + .../PureFieldCaptureProperties.cs | 21 + .../RejectCaptureStream.cs | 9 + .../SampleContext.cs | 3 + .../SerializationBehaviorTests.ArrayKeys.cs | 98 - .../SerializationBehaviorTests.CaptureKeys.cs | 228 -- .../SerializationBehaviorTests.Concurrency.cs | 33 - ...SerializationBehaviorTests.OrdinalReuse.cs | 21 - .../SerializationBehaviorTests.Snapshots.cs | 80 - .../SerializationBehaviorTests.cs | 469 --- .../SerializedCaptureCounter.cs | 10 + .../SnapshotEnvelope.cs | 16 + .../SnapshotEnvelopeConverter.cs | 39 + .../StructSample.cs | 31 + .../ThrowingConstructorSample.cs | 11 + .../UntrackedCaptureProperties.cs | 9 + .../VariantValue.cs | 6 + .../VariantValueConverter.cs | 14 + .../VisibilitySample.cs | 22 + .../DynamicModalState.cs | 34 + .../DynamicModalTests.cs | 87 - .../DynamicTestModal.cs | 64 + .../BatchValidationComponent.cs | 25 + .../CoupledHistoryComponent.cs | 33 + .../EditorHistoryTests.cs | 93 - .../HistoryAssetReferenceComponent.cs | 14 + .../HistoryComponent.cs | 15 + .../HistoryReferenceComponent.cs | 15 + .../HistorySystem.cs | 15 + .../NeutralValueHistoryHandler.cs | 95 + .../RestoreCleanupFailureComponent.cs | 17 + .../SceneHistoryProbe.cs | 25 + .../SceneHistoryTests.Selection.cs | 21 - .../SceneHistoryTests.cs | 121 - .../SubtreeRestoreFailureComponent.cs | 27 + .../AtomicEditorSetting.cs | 43 + .../AtomicProjectEditor.cs | 19 + .../AtomicProjectSetting.cs | 12 + .../DirtyCaptureComponent.cs | 19 + .../DirtyCaptureValue.cs | 8 + .../DirtyCaptureValueConverter.cs | 22 + .../EditorPlayModeTests.cs | 12 - .../PlayModeAssetReferenceBehavior.cs | 16 + .../SceneDirtyCaptureTests.cs | 40 - .../SettingsApplyNativeTests.cs | 64 - .../ADisposeObserverModule.cs | 36 + .../AreaResolveAction.cs | 11 + .../BaseResolveAction.cs | 11 + .../BaseTarget.cs | 4 + .../CommitOnPresentationLostAction.cs | 27 + .../DeferredAction.cs | 11 + .../DerivedTarget.cs | 3 + .../DragSource.cs | 5 + .../DropTarget.cs | 6 + .../DynamicMenuSource.cs | 16 + .../EditorRuntimeTests.Commands.cs | 50 - .../EditorRuntimeTests.cs | 519 ---- .../FollowingUpdateModule.cs | 11 + .../HostServicePanel.cs | 16 + .../ITestHostService.cs | 3 + .../InteractionAction.cs | 44 + .../InteractionTarget.cs | 7 + .../MenuAction.cs | 10 + .../MenuConditionalAction.cs | 13 + .../MenuFallbackAction.cs | 10 + .../MenuStateAction.cs | 15 + .../MenuStateTarget.cs | 9 + .../MetadataAction.cs | 22 + .../MultiPresentationSetting.cs | 15 + .../MultiShortcutAction.cs | 14 + .../NeutralHistoryHandler.cs | 39 + .../PrimaryMultiPresentationEditor.cs | 9 + .../RejectedMenuSource.cs | 16 + .../SecondaryMultiPresentationEditor.cs | 9 + .../ShutdownOrder.cs | 8 + .../TestDocumentProvider.cs | 26 + .../TestDrop.cs | 15 + .../TestHostService.cs | 3 + .../TestModule.cs | 74 + .../TestPanel.cs | 50 + .../TestViewportCoordinates.cs | 11 + .../TestViewportTool.cs | 31 + .../ThrowAfterActivateAction.cs | 18 + .../ToolbarAction.cs | 16 + .../UpdateBarrierModule.cs | 21 + .../ZThrowingDisposeModule.cs | 20 + ...mblyManagerTests.cs => ModuleHostTests.cs} | 1 - .../AbstractAttributedType.cs | 4 + .../AttributedType.cs | 4 + .../DeterministicStableType.cs | 3 + .../GeneratedMappedType.cs | 3 + .../ITestContract.cs | 3 + .../OutsideNamespaceType.cs | 5 - .../OutsideStableAnnotatedType.cs | 6 + .../StableAnnotatedTypeA.cs | 4 + .../StableAnnotatedTypeB.cs | 4 + .../TestAbstractContractImpl.cs | 3 + .../TestAbstractDerived.cs | 3 + .../TestBase.cs | 4 + .../TestContractImpl.cs | 3 + .../TestDerived.cs | 3 + .../TestMarkerAttribute.cs | 6 + .../TypeCacheTests.cs | 33 - .../FirstConflictingExtension.cs | 9 + ...sions.cs => SecondConflictingExtension.cs} | 6 - .../AssemblyAMarkedType.cs | 7 + ...yATypes.cs => AssemblyAMarkerAttribute.cs} | 6 - .../AssemblyBMarkedType.cs | 7 + ...yBTypes.cs => AssemblyBMarkerAttribute.cs} | 6 - .../PluginDefaultTestSetting.cs | 15 + .../PluginSourceSerializationCollection.cs | 6 + .../PluginSourceServiceTests.cs | 30 - .../Inno.Plugins.Tests/TestAssetSourceMeta.cs | 19 + .../MeshAndStateTests.cs | 10 - .../RenderingAssetSourceMeta.cs | 19 + .../RenderingAssetsSerializationCollection.cs | 6 + .../RenderingImportSettingsEnvelope.cs | 16 + .../RenderingImporterIntegrationTests.cs | 29 - .../EmptyRenderingKernelTests.cs | 2500 ---------------- ...nerationTests.ShaderProgramPublication.cs} | 2 - .../RenderRuntimeGenerationTests.cs | 2503 +++++++++++++++++ .../MetalShaderFactAttribute.cs | 15 + .../NodeRegistryProbe.cs | 26 + .../RegistryFrontendProbe.cs | 33 + .../ShaderGraphLoweringTests.Validation.cs | 22 - ... ShaderGraphProgramTests.SharedProgram.cs} | 1 - ....cs => ShaderGraphProgramTests.Storage.cs} | 1 - .../ShaderSourceFrontendRegistryTests.cs | 30 - .../ShaderTypedNativeCompilationTests.cs | 13 - .../ReloadableFramePayload.cs | 6 + .../ReloadableRenderFeature.cs | 26 + .../ReloadableRenderPipeline.cs | 33 - .../Inno.Scene.Tests/EngineAssetComponents.cs | 39 - .../EngineAssetReferenceComponent.cs | 12 + .../EngineObjectReferenceComponent.cs | 14 + .../scene/Inno.Scene.Tests/GameSystemTests.cs | 24 - .../Inno.Scene.Tests/LayerValueComponent.cs | 15 + .../scene/Inno.Scene.Tests/OrderComponentA.cs | 3 + .../scene/Inno.Scene.Tests/OrderComponentB.cs | 3 + .../OrderSerializationSystemA.cs | 6 + .../OrderSerializationSystemB.cs | 6 + .../PrefabInstantiationBehavior.cs | 18 + .../PropertyElementEnvelope.cs | 34 + .../PropertyReferenceProbe.cs | 31 + .../PropertyReferenceTokenFixture.cs | 13 + .../Inno.Scene.Tests/ReferenceComponent.cs | 21 + .../Inno.Scene.Tests/SceneFacadeTests.cs | 6 - ...SceneSerializationTests.PropertyAliases.cs | 39 - ...neSerializationTests.PropertyReferences.cs | 28 - .../SceneSerializationTests.cs | 34 - .../Inno.Scene.Tests/SceneTestsCollection.cs | 68 - .../Inno.Scene.Tests/SceneTestsFixture.cs | 70 + tests/scene/Inno.Scene.Tests/StateSystem.cs | 18 + .../SystemReferenceComponent.cs | 11 + .../AttributeOwner.cs | 20 + .../AttributeValue.cs | 3 + .../AttributeValueDrawer.cs | 13 + .../CapturedScriptPayload.cs | 8 + .../CapturedScriptPayloadConverter.cs | 16 + .../InlineFailure.cs | 3 + .../InlineFailureDrawer.cs | 10 + .../InlineOwner.cs | 9 + .../InlineParent.cs | 6 + .../InlineParentDrawer.cs | 16 + .../InspectionPipelineTests.cs | 107 - .../ProbeInspectorAttribute.cs | 7 + .../ProbeInspectorAttributeDrawer.cs | 25 + .../SampleIdentitySettings.cs | 13 + .../SceneReloadProbe.cs | 17 + .../ScriptingAssetSourceMeta.cs | 19 + .../ScriptingCompilationProbe.cs | 16 + .../ScriptingFixture.cs | 296 ++ .../ScriptingPipelineTests.UILifecycle.cs | 17 - .../ScriptingPipelineTests.cs | 325 --- .../TextStateDrawer.cs | 18 + .../TextStateOwner.cs | 9 + .../ValidationProgressCollection.cs | 9 + .../ValidationProgressTests.cs | 6 - .../Style/Rules/EmptyBodyStyleRule.cs | 45 - .../Style/Rules/EmptyTypeStyleRule.cs | 50 + .../Indexing/DocumentationApiCapture.cs | 11 + .../Indexing/DocumentationApiComposition.cs | 34 +- .../Indexing/DocumentationApiContent.cs | 68 +- .../Indexing/DocumentationApiFacts.cs | 42 +- .../Indexing/DocumentationApiPackage.cs | 32 +- .../Indexing/DocumentationBinding.cs | 14 + .../Indexing/DocumentationManifest.cs | 18 + .../Indexing/DocumentationModels.cs | 69 - .../Indexing/DocumentationPage.cs | 24 +- .../Indexing/DocumentationPageReference.cs | 8 + .../Indexing/DocumentationProject.cs | 8 + .../Indexing/DocumentationProjectGuides.cs | 22 +- .../Indexing/DocumentationSearchEntry.cs | 9 + .../Indexing/DocumentationSymbolReference.cs | 10 + .../Indexing/DocumentationXml.cs | 14 +- .../Inno.Tooling.Validation/ValidationPlan.cs | 34 +- .../ValidationPlanner.Backends.cs | 34 +- .../ValidationProfile.cs | 17 - .../ValidationProfiles.cs | 18 + .../ValidationShard.cs | 250 -- .../ValidationShards.cs | 251 ++ 1006 files changed, 32848 insertions(+), 30873 deletions(-) create mode 100644 backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceDeclarationParser.cs create mode 100644 backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceSyntaxException.cs create mode 100644 backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferKind.cs rename backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/{BgfxResources.cs => BgfxBufferResource.cs} (59%) create mode 100644 backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxPipelineResource.cs create mode 100644 backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxShaderBindingResource.cs create mode 100644 backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiTextureHandle.cs create mode 100644 backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiViewportTarget.cs create mode 100644 backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontScope.cs create mode 100644 build/toolchains/Inno.Build.Toolchains/BuildArtifactCopier.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/HeaderAttribute.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/HelpBoxAttribute.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/HideIfAttribute.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/InspectorCondition.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/InspectorMessageType.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/InspectorNameAttribute.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttribute.cs delete mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/InspectorReadOnlyAttribute.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/RangeAttribute.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/ShowIfAttribute.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/SpaceAttribute.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/TextAttribute.cs create mode 100644 src/composition/editor/contracts/Inno.Editor.Annotations/TooltipAttribute.cs create mode 100644 src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationContext.cs create mode 100644 src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationMenuAttribute.cs create mode 100644 src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsHistory.cs rename src/composition/editor/features/Inno.Editor.Rendering/Compilation/{EditorShaderArtifactValidation.cs => IEditorShaderArtifactValidator.cs} (100%) create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoContext.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoFrame.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderExtensionAttribute.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewHandle.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportComposition.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContext.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContribution.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorExtensionAttribute.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportFocusBounds.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportKindID.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportLayer.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportManipulationSpace.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationCapabilities.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationMode.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfile.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfileID.cs rename src/composition/editor/features/Inno.Editor.Rendering/{EditorViewportNavigation.cs => EditorViewportNavigationState.cs} (50%) create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPointerContext.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPresentation.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/EditorViewportProjection.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/IEditorGizmoSink.cs rename src/composition/editor/features/Inno.Editor.Rendering/{EditorPreviewService.cs => IEditorPreviewService.cs} (63%) create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/IEditorRenderingHost.cs create mode 100644 src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDraftHistory.cs create mode 100644 src/composition/editor/features/Inno.Editor.Scripting/ReloadPluginsAction.cs rename src/composition/editor/features/Inno.Editor.Scripting/{ScriptingReloadActions.cs => ReloadScriptingAction.cs} (51%) create mode 100644 src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDraftHistory.cs create mode 100644 src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewContext.cs create mode 100644 src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProviderAttribute.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistic.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticGroupID.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticID.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Graph/GraphClipboardData.cs delete mode 100644 src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryData.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryDocumentCodec.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryTransition.cs delete mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HeaderInspectorAttributeDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HelpBoxInspectorAttributeDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HideIfInspectorAttributeDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorConditionEvaluator.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/NameInspectorAttributeDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/RangeInspectorAttributeDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ReadOnlyInspectorAttributeDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ShowIfInspectorAttributeDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/SpaceInspectorAttributeDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TextInspectorAttributeDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TooltipInspectorAttributeDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/IInspectionDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ColorPropertyDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ComponentFieldDrawer.cs delete mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/QuaternionPropertyDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectIntPropertyDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectPropertyDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2IntPropertyDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2PropertyDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3IntPropertyDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3PropertyDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4IntPropertyDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4PropertyDrawer.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionArgumentContext.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorArgumentAction.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorPresentationAction.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuPlacement.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportPointerEvent.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportShortcut.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Interactions/Viewport/IEditorViewportCoordinateConverter.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistoryHandler.cs create mode 100644 src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistoryHandler.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/AssetCreationMenu.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspector.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineSourceDrawer.cs rename src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/{ConsoleSettings.cs => ClearConsoleOnPlaySetting.cs} (71%) create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettingsPage.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/DiagnosticsSettingsPage.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsField.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistoryHandler.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsField.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderPortSnapshot.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderAssetDrawer.cs delete mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSelectionDrawer.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSourceDrawer.cs rename src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/{ShaderCanvasOrganizationActions.cs => CollapseShaderSubgraph.cs} (51%) create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderNodes.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderToProject.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderNode.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderOutput.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CutShaderNodes.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DeleteShaderNodes.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DisconnectShaderNodes.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DuplicateShaderNodes.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FocusShaderNodes.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FormatShaderGraph.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/GroupShaderNodes.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/InsertShaderReroute.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/PasteShaderNodes.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ReloadShaderSource.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderAsset.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderFunction.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/SaveShader.cs delete mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasGroup.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasMenu.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderSelectionAction.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderTemplateMenu.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShowShaderDiagnostics.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/UngroupShaderNodes.cs create mode 100644 src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/OpenShaderEditorAction.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDropWidgetResult.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFontScope.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/DialogLayout.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/InlineRenamePresentation.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ListNavigationResult.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TransformGizmoOptions.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeDrawContext.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeOptions.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeResult.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetWindowState.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspector.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSourceDrawer.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawContext.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerAttribute.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodePresentation.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Actions/ClearEditorSelectionAction.cs rename src/composition/editor/presentation/Inno.Editor.Workbench/Actions/{HistoryActions.cs => RedoEditorAction.cs} (52%) rename src/composition/editor/presentation/Inno.Editor.Workbench/Actions/{SelectionActions.cs => SelectEditorTargetAction.cs} (53%) create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Actions/UndoEditorAction.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportGameAction.cs rename src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/{ExportActions.cs => ExportPluginAction.cs} (54%) create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/AppearanceSettingsPage.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorFramePacingModule.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorRenderingSettingsPage.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FileIconSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FolderIconSetting.cs delete mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GameObjectIconSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPage.cs delete mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs rename src/composition/editor/presentation/Inno.Editor.Workbench/Settings/{IconSettings.cs => IconSetting.cs} (56%) create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettingsPage.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/LayersIconSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaterialIconSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaximumFrameRateSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/PrefabIconSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/RenderPipelineIconSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/SceneIconSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderIconSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderSourceIconSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Settings/VerticalSyncSetting.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeEditorAction.cs delete mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomInEditorAction.cs create mode 100644 src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomOutEditorAction.cs create mode 100644 src/content/animation/Inno.Animation/AnimationBindingID.cs create mode 100644 src/content/animation/Inno.Animation/AnimationClock.cs create mode 100644 src/content/animation/Inno.Animation/AnimationEventMarker.cs create mode 100644 src/content/animation/Inno.Animation/AnimationExecutionContext.cs create mode 100644 src/content/animation/Inno.Animation/AnimationInterpolation.cs create mode 100644 src/content/animation/Inno.Animation/AnimationKeyframe.cs create mode 100644 src/content/animation/Inno.Animation/AnimationMarkerEvent.cs create mode 100644 src/content/animation/Inno.Animation/AnimationPlayOptions.cs create mode 100644 src/content/animation/Inno.Animation/AnimationPlaybackHandle.cs create mode 100644 src/content/animation/Inno.Animation/AnimationPlaybackState.cs create mode 100644 src/content/animation/Inno.Animation/AnimationSample.cs create mode 100644 src/content/animation/Inno.Animation/AnimationTrack.cs delete mode 100644 src/content/animation/Inno.Animation/AnimationTypes.cs create mode 100644 src/content/animation/Inno.Animation/AnimationValue.cs create mode 100644 src/content/animation/Inno.Animation/IAnimationBindingSink.cs create mode 100644 src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceSnapshot.cs create mode 100644 src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactOutputData.cs create mode 100644 src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportProduct.cs create mode 100644 src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporterAttribute.cs create mode 100644 src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorAttribute.cs create mode 100644 src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetDependencyData.cs create mode 100644 src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportDependencyData.cs create mode 100644 src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriterAttribute.cs rename src/content/assets/Inno.Assets.Pipeline/Sources/{AssetSampleSourceRewriter.cs => AssetSampleTransformContext.cs} (72%) create mode 100644 src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSampleSourceRewriter.cs create mode 100644 src/content/assets/Inno.Assets.Pipeline/Sources/Watching/WatcherPollResult.cs create mode 100644 src/content/assets/Inno.Assets/AssetSourceID.cs create mode 100644 src/content/assets/Inno.Assets/Runtime/ArtifactLease.cs create mode 100644 src/content/assets/Inno.Assets/Runtime/AssetLease.cs delete mode 100644 src/content/assets/Inno.Assets/Runtime/AssetResidency.cs create mode 100644 src/content/assets/Inno.Assets/Runtime/AssetResidencyProvider.cs create mode 100644 src/content/assets/Inno.Assets/Runtime/AssetResidencyStatistics.cs create mode 100644 src/content/assets/Inno.Assets/Runtime/IAssetResidency.cs create mode 100644 src/content/assets/Inno.Assets/Runtime/RetentionScope.cs create mode 100644 src/content/scene/Inno.Scene/Core/GameTagSettingContribution.cs create mode 100644 src/content/scene/Inno.Scene/Layers/GameLayerSettingContribution.cs create mode 100644 src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectIndex.cs create mode 100644 src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectStore.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/ApplicationEvent.cs rename src/foundation/core/Inno.Core.Events/Events/{ApplicationEvents.cs => ApplicationQuitEvent.cs} (57%) create mode 100644 src/foundation/core/Inno.Core.Events/Events/KeyEvent.cs delete mode 100644 src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/KeyPressedEvent.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/KeyReleasedEvent.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/MouseButtonEvent.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/MouseButtonPressedEvent.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/MouseButtonReleasedEvent.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/MouseEvent.cs delete mode 100644 src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/MouseMovedEvent.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/MouseScrolledEvent.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/TextInputEvent.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/WindowCloseEvent.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/WindowEvent.cs delete mode 100644 src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/WindowFocusChangedEvent.cs create mode 100644 src/foundation/core/Inno.Core.Events/Events/WindowResizeEvent.cs delete mode 100644 src/foundation/core/Inno.Core.Graphs/GraphDefinitions.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphDiagnostic.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphEdgeID.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphEdgeRecord.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphEndpoint.cs delete mode 100644 src/foundation/core/Inno.Core.Graphs/GraphIDs.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphNodeDefinition.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphNodeID.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphNodeRecord.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphPortCapacity.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphPortDefinition.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphPortDirection.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphPortID.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphPosition.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/GraphValidationResult.cs rename src/foundation/core/Inno.Core.Graphs/{GraphValidation.cs => GraphValidator.cs} (78%) create mode 100644 src/foundation/core/Inno.Core.Graphs/IGraphNodeDefinitionResolver.cs create mode 100644 src/foundation/core/Inno.Core.Graphs/IGraphTypeConversion.cs create mode 100644 src/foundation/core/Inno.Core.Serialization/Internal/ArraySerializationNode.cs create mode 100644 src/foundation/core/Inno.Core.Serialization/Internal/ConverterInvoker.cs create mode 100644 src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistryLease.cs create mode 100644 src/foundation/core/Inno.Core.Serialization/Internal/MapSerializationNode.cs create mode 100644 src/foundation/core/Inno.Core.Serialization/Internal/NullSerializationNode.cs create mode 100644 src/foundation/core/Inno.Core.Serialization/Internal/ObjectSerializationNode.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectID.cs delete mode 100644 src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectIdentitySettings.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectLocalID.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectScopedID.cs rename src/foundation/core/Inno.Core.Settings/{ProjectSettingComposition.cs => ProjectSettingComposer.cs} (54%) create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectSettingComposerAttribute.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectSettingCompositionEntry.cs delete mode 100644 src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectSettingContribution.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectSettingContributionContext.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectSettingDefinitionAttribute.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectSettingID.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectSettingRecord.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectSettingsContributor.cs create mode 100644 src/foundation/core/Inno.Core.Settings/ProjectSettingsDocument.cs create mode 100644 src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogRefreshSet.cs create mode 100644 src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CatalogParticipantRegistration.cs create mode 100644 src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/ReloadState.cs create mode 100644 src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistry.cs create mode 100644 src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistryTransaction.cs create mode 100644 src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryNoopTransaction.cs create mode 100644 src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRefreshSet.cs create mode 100644 src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRegistration.cs create mode 100644 src/runtime/engine/Inno.Runtime/Execution/RuntimeClock.cs create mode 100644 src/runtime/engine/Inno.Runtime/Presentation/GamePresentationViewport.cs create mode 100644 src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystemFactory.cs create mode 100644 src/runtime/plugins/Inno.Plugins.Authoring/PluginCandidate.cs create mode 100644 src/runtime/plugins/Inno.Plugins.Authoring/PluginDiagnostic.cs create mode 100644 src/runtime/plugins/Inno.Plugins.Authoring/PluginScanResult.cs create mode 100644 src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceKind.cs create mode 100644 src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceLimits.cs delete mode 100644 src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs create mode 100644 src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeDeclaration.cs create mode 100644 src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiNamespaceMap.cs create mode 100644 src/services/audio/Inno.Audio/AudioBusDefinition.cs create mode 100644 src/services/audio/Inno.Audio/AudioBusHandle.cs create mode 100644 src/services/audio/Inno.Audio/AudioBusID.cs create mode 100644 src/services/audio/Inno.Audio/AudioCapabilities.cs create mode 100644 src/services/audio/Inno.Audio/AudioClipHandle.cs create mode 100644 src/services/audio/Inno.Audio/AudioClipLoadMode.cs create mode 100644 src/services/audio/Inno.Audio/AudioClipMetadata.cs create mode 100644 src/services/audio/Inno.Audio/AudioClipMetadataCodec.cs create mode 100644 src/services/audio/Inno.Audio/AudioCodecID.cs create mode 100644 src/services/audio/Inno.Audio/AudioCompletionReason.cs create mode 100644 src/services/audio/Inno.Audio/AudioContentProviderContext.cs create mode 100644 src/services/audio/Inno.Audio/AudioContentProviderExtensionAttribute.cs create mode 100644 src/services/audio/Inno.Audio/AudioDeviceCompletion.cs create mode 100644 src/services/audio/Inno.Audio/AudioDeviceState.cs create mode 100644 src/services/audio/Inno.Audio/AudioDistanceModel.cs rename src/services/audio/Inno.Audio/{AudioContent.cs => AudioEmitterSnapshot.cs} (58%) create mode 100644 src/services/audio/Inno.Audio/AudioExecutionContext.cs delete mode 100644 src/services/audio/Inno.Audio/AudioHandles.cs create mode 100644 src/services/audio/Inno.Audio/AudioListenerHandle.cs create mode 100644 src/services/audio/Inno.Audio/AudioListenerSnapshot.cs create mode 100644 src/services/audio/Inno.Audio/AudioListenerState.cs create mode 100644 src/services/audio/Inno.Audio/AudioMixerAsset.cs create mode 100644 src/services/audio/Inno.Audio/AudioMixerBuilder.cs create mode 100644 src/services/audio/Inno.Audio/AudioMixerExtension.cs create mode 100644 src/services/audio/Inno.Audio/AudioMixerExtensionAttribute.cs delete mode 100644 src/services/audio/Inno.Audio/AudioMixerExtensions.cs create mode 100644 src/services/audio/Inno.Audio/AudioMixerFeature.cs create mode 100644 src/services/audio/Inno.Audio/AudioMixerFeatureConfiguration.cs create mode 100644 src/services/audio/Inno.Audio/AudioMixerFeatureExtensionAttribute.cs create mode 100644 src/services/audio/Inno.Audio/AudioParameterID.cs create mode 100644 src/services/audio/Inno.Audio/AudioPlayOptions.cs create mode 100644 src/services/audio/Inno.Audio/AudioPlaybackState.cs create mode 100644 src/services/audio/Inno.Audio/AudioProcessorConfiguration.cs create mode 100644 src/services/audio/Inno.Audio/AudioProcessorID.cs create mode 100644 src/services/audio/Inno.Audio/AudioProcessorParameter.cs delete mode 100644 src/services/audio/Inno.Audio/AudioProtocolIDs.cs create mode 100644 src/services/audio/Inno.Audio/AudioSpatialOptions.cs create mode 100644 src/services/audio/Inno.Audio/AudioStatistics.cs delete mode 100644 src/services/audio/Inno.Audio/AudioTypes.cs create mode 100644 src/services/audio/Inno.Audio/AudioVoiceHandle.cs create mode 100644 src/services/audio/Inno.Audio/AudioVoiceParameters.cs create mode 100644 src/services/audio/Inno.Audio/SerializedAudioExtensionState.cs create mode 100644 src/services/input/Inno.Input/InputExecutionContext.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderArtifact.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderPass.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/IShaderCompilerToolchain.cs rename src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/{TextureTargetCompiler.cs => ITextureTargetCompiler.cs} (96%) create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderArtifactSelection.cs delete mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilationResult.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompileTarget.cs rename src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/{ShaderGraphCompilation.cs => ShaderCompiler.Graph.cs} (99%) create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Stage.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageArtifact.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageBinding.cs delete mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolRequest.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolResult.cs create mode 100644 src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceSnapshot.cs rename src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/{GltfMeshParser.cs => MeshSourceParser.Gltf.cs} (99%) rename src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/{ObjMeshParser.cs => MeshSourceParser.Obj.cs} (99%) create mode 100644 src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsExecutionContext.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsState.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/IPreparedViewDrawable.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentCollector.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentFrameSource.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSink.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSource.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/IViewDrawable.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/IViewPointerTarget.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/RenderView.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/SelectedViewContentCollector.cs delete mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentContext.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentItem.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentSourceExtensionAttribute.cs rename src/services/rendering/Inno.Rendering.Runtime/{RenderFrameScratch.cs => RenderRuntime.FrameScratch.cs} (98%) create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderContext.cs create mode 100644 src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderExtensionAttribute.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/IShaderNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBinaryNodeCompiler.cs delete mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstantNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstructNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderDiscardNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderExtractNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringResult.cs delete mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeDescriptionContext.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeLoweringContext.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodePort.cs rename src/services/rendering/Inno.Rendering.Shaders/Compilation/{ShaderValueNodeCompilers.cs => ShaderSampleNodeCompiler.cs} (59%) create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSelectNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSourceNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStageInputNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageAtomicAddNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageLoadNodeCompiler.cs delete mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageStoreNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Compilation/StorageNodePorts.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphCallNodeCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettings.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettingsConverter.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteralConverter.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettings.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettingsConverter.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputsCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterface.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterfaceConverter.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettings.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettingsConverter.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputsCompiler.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinition.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinitionConverter.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettings.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettingsConverter.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphOutput.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPass.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPassProgram.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPasteResult.cs rename src/services/rendering/Inno.Rendering.Shaders/Documents/{ShaderGraphProgram.cs => ShaderGraphProgramResult.cs} (54%) create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettings.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettingsConverter.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTypeConverter.cs delete mode 100644 src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrInstruction.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageInput.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageOutput.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrValue.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceResolver.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceAnalysis.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceField.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationAnalysis.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationRequest.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceParameter.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceRequest.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceSnapshotResolver.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetAttribute.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetContext.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Templates/RasterShaderGraphTemplate.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Templates/ReusableShaderGraphNodeTemplate.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderBuiltInIDs.cs create mode 100644 src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateAttribute.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/ComputePipelineHandle.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/GraphicsApi.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/GraphicsLimits.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/GraphicsPipelineHandle.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/PersistentBufferHandle.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/PersistentTextureHandle.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderBindingID.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderBufferDescriptor.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderBufferHandle.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderBufferSlice.cs rename src/services/rendering/Inno.Rendering/Device/{RenderBufferUploads.cs => RenderBufferUploadDescriptor.cs} (56%) create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderBufferUsage.cs rename src/services/rendering/Inno.Rendering/Device/{RenderCommands.cs => RenderCommandEncoder.cs} (78%) rename src/services/rendering/Inno.Rendering/Device/{RenderProtocolIDs.cs => RenderDataChannelID.cs} (51%) create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderDeviceFrameCounters.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderFrameUploadProvider.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderPassContext.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderPassExecute.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderResourceID.cs delete mode 100644 src/services/rendering/Inno.Rendering/Device/RenderResources.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderStencilFaceState.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderSurfaceHandle.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderTextureDescriptor.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderTextureDimension.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderTextureFormat.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderTextureHandle.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackHandle.cs rename src/services/rendering/Inno.Rendering/Device/{RenderTextureReadback.cs => RenderTextureReadbackResult.cs} (76%) create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderTextureRegion.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderTextureUsage.cs create mode 100644 src/services/rendering/Inno.Rendering/Device/RenderVertexAttribute.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/CompiledRenderAttachment.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/CompiledRenderBuffer.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/CompiledRenderPass.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/CompiledRenderTexture.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/IRenderGraphBackend.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderAttachment.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderBufferRecord.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderClearColor.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderGraphCompileResult.cs rename src/services/rendering/Inno.Rendering/Graph/{RenderGraphResourceAllocation.cs => RenderGraphCompiler.ResourceAllocation.cs} (99%) create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderGraphDiagnostic.cs delete mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs rename src/services/rendering/Inno.Rendering/Graph/{RenderGraphDependencyAnalysis.cs => RenderGraphValidator.DependencyAnalysis.cs} (99%) rename src/services/rendering/Inno.Rendering/Graph/{RenderGraphScheduling.cs => RenderGraphValidator.Scheduling.cs} (98%) create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderLoadAction.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderPassKind.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderPassRecord.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderPhaseID.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderResourceAccess.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderResourceKey.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderResourceUse.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderResourceUseKind.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderStoreAction.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderTextureRecord.cs create mode 100644 src/services/rendering/Inno.Rendering/Graph/RenderViewTransform.cs create mode 100644 src/services/storage/Inno.Storage/StorageExecutionContext.cs create mode 100644 src/services/text/Inno.Text/FontMetadata.cs create mode 100644 src/services/text/Inno.Text/FontMetadataCodec.cs create mode 100644 src/services/text/Inno.Text/GlyphBitmap.cs create mode 100644 src/services/text/Inno.Text/TextDirection.cs create mode 100644 src/services/text/Inno.Text/TextExecutionContext.cs create mode 100644 src/services/text/Inno.Text/TextFontHandle.cs create mode 100644 src/services/text/Inno.Text/TextFontStyle.cs create mode 100644 src/services/text/Inno.Text/TextGlyph.cs create mode 100644 src/services/text/Inno.Text/TextLayout.cs create mode 100644 src/services/text/Inno.Text/TextMetrics.cs create mode 100644 src/services/text/Inno.Text/TextShapingOptions.cs create mode 100644 src/services/text/Inno.Text/TextStyle.cs delete mode 100644 src/services/text/Inno.Text/TextTypes.cs create mode 100644 src/services/ui/Inno.UI.Assets/IUIDocumentFrontend.cs create mode 100644 src/services/ui/Inno.UI.Assets/UIDocumentAnalysis.cs create mode 100644 src/services/ui/Inno.UI.Assets/UIDocumentDiagnostic.cs create mode 100644 src/services/ui/Inno.UI.Assets/UIDocumentFontDeclaration.cs delete mode 100644 src/services/ui/Inno.UI.Assets/UIDocumentFrontend.cs create mode 100644 src/services/ui/Inno.UI.Assets/UIDocumentFrontendCatalog.cs create mode 100644 src/services/ui/Inno.UI.Assets/UIDocumentFrontendRegistry.cs create mode 100644 src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs create mode 100644 src/services/ui/Inno.UI.Assets/UIDocumentSourceFile.cs create mode 100644 src/services/ui/Inno.UI/UICapabilityUnavailableException.cs create mode 100644 src/services/ui/Inno.UI/UIClipRectangle.cs rename src/services/ui/Inno.UI/{UIHandles.cs => UIContextHandle.cs} (52%) create mode 100644 src/services/ui/Inno.UI/UIContextOptions.cs create mode 100644 src/services/ui/Inno.UI/UIDocumentFragment.cs create mode 100644 src/services/ui/Inno.UI/UIDocumentHandle.cs rename src/services/ui/Inno.UI/{UIIdentifiers.cs => UIDocumentLanguageID.cs} (100%) create mode 100644 src/services/ui/Inno.UI/UIDocumentSource.cs create mode 100644 src/services/ui/Inno.UI/UIDrawCommand.cs create mode 100644 src/services/ui/Inno.UI/UIEvent.cs create mode 100644 src/services/ui/Inno.UI/UIExecutionContext.cs create mode 100644 src/services/ui/Inno.UI/UIInputSnapshot.cs create mode 100644 src/services/ui/Inno.UI/UIMeshUpdate.cs create mode 100644 src/services/ui/Inno.UI/UIRenderFrame.cs create mode 100644 src/services/ui/Inno.UI/UIRenderFrameBuilder.cs delete mode 100644 src/services/ui/Inno.UI/UIRendering.cs create mode 100644 src/services/ui/Inno.UI/UITextureData.cs create mode 100644 src/services/ui/Inno.UI/UITextureUpdate.cs delete mode 100644 src/services/ui/Inno.UI/UITypes.cs create mode 100644 src/services/ui/Inno.UI/UIVertex.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ClipContribution.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ClipSettings.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsBase.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsComposer.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ComposedClipSettings.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredSettings.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/DeferredAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/DependencyAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/HookAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictProbe.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/MutableAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/SlowAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/TestBuildDefinitionAsset.cs create mode 100644 tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs create mode 100644 tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs create mode 100644 tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterAsset.cs create mode 100644 tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs delete mode 100644 tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs create mode 100644 tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceCollection.cs create mode 100644 tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceFixture.cs create mode 100644 tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/WindowedBgfxCollection.cs create mode 100644 tests/core/Inno.Core.Diagnostics.Tests/DiagnoseCollection.cs create mode 100644 tests/core/Inno.Core.Logging.Tests/LoggingCollection.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/AmbiguousHost.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/AmbiguousLeftConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/AmbiguousRightConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/AmbiguousValue.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureArrayRoot.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureArrayRootConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureArrayRow.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureBlobRoot.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureBlobRootConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValue.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValueConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureGetterStruct.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureKeyContext.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureKeyRoot.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureKeyRootConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CapturePropertyLoadContext.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CaptureRevisionProperties.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureValue.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ConvertedCaptureProperties.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ConvertedChild.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ConvertedChildConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ConvertedChildHost.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSampleConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ConvertedHookSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ConvertedHookSampleConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CurrentSchemaSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CycleHost.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CycleValue.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/CycleValueConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/DefaultSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/DuplicateKeyBaseSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/DuplicateKeyDerivedSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ExactBase.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ExactBaseConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ExactHost.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ExactLeaf.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ExactLeafConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/FreshCaptureMetadataSource.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/GenericBox.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/GenericBoxConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/GenericBoxHost.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/GetterCaptureProperties.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/HookBaseSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/HookDerivedSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/IAmbiguousLeft.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/IAmbiguousRight.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ISampleContext.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/IVariantValue.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/MapHost.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/MissingChild.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/MissingClassCollectionHost.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/MissingClassHost.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/MissingConstructorSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/MissingRequiredConverterSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/MissingSetterSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCapture.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCaptureConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/MutatingPropertyCapture.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/NearestBase.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/NearestBaseConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/NearestHost.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/NearestLeaf.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/NearestMid.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/NearestMidConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/OrdinalCapture.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/OrdinalCaptureConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/PreviousSchemaSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/PrivateConstructorSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/PureCaptureFields.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/PureFieldCaptureProperties.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/RejectCaptureStream.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/SampleContext.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/SerializedCaptureCounter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelope.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelopeConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/StructSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/ThrowingConstructorSample.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/UntrackedCaptureProperties.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/VariantValue.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/VariantValueConverter.cs create mode 100644 tests/core/Inno.Core.Serialization.Tests/VisibilitySample.cs create mode 100644 tests/editor/Inno.Editor.ImGui.Tests/DynamicModalState.cs create mode 100644 tests/editor/Inno.Editor.ImGui.Tests/DynamicTestModal.cs create mode 100644 tests/editor/Inno.Editor.Interactions.Tests/BatchValidationComponent.cs create mode 100644 tests/editor/Inno.Editor.Interactions.Tests/CoupledHistoryComponent.cs create mode 100644 tests/editor/Inno.Editor.Interactions.Tests/HistoryAssetReferenceComponent.cs create mode 100644 tests/editor/Inno.Editor.Interactions.Tests/HistoryComponent.cs create mode 100644 tests/editor/Inno.Editor.Interactions.Tests/HistoryReferenceComponent.cs create mode 100644 tests/editor/Inno.Editor.Interactions.Tests/HistorySystem.cs create mode 100644 tests/editor/Inno.Editor.Interactions.Tests/NeutralValueHistoryHandler.cs create mode 100644 tests/editor/Inno.Editor.Interactions.Tests/RestoreCleanupFailureComponent.cs create mode 100644 tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryProbe.cs create mode 100644 tests/editor/Inno.Editor.Interactions.Tests/SubtreeRestoreFailureComponent.cs create mode 100644 tests/editor/Inno.Editor.PlayMode.Tests/AtomicEditorSetting.cs create mode 100644 tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectEditor.cs create mode 100644 tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectSetting.cs create mode 100644 tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureComponent.cs create mode 100644 tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValue.cs create mode 100644 tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValueConverter.cs create mode 100644 tests/editor/Inno.Editor.PlayMode.Tests/PlayModeAssetReferenceBehavior.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/ADisposeObserverModule.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/AreaResolveAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/BaseResolveAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/BaseTarget.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/CommitOnPresentationLostAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/DeferredAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/DerivedTarget.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/DragSource.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/DropTarget.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/DynamicMenuSource.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/FollowingUpdateModule.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/HostServicePanel.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/ITestHostService.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/InteractionAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/InteractionTarget.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/MenuAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/MenuConditionalAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/MenuFallbackAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/MenuStateAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/MenuStateTarget.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/MetadataAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/MultiPresentationSetting.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/MultiShortcutAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/NeutralHistoryHandler.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/PrimaryMultiPresentationEditor.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/RejectedMenuSource.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/SecondaryMultiPresentationEditor.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/ShutdownOrder.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/TestDocumentProvider.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/TestDrop.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/TestHostService.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/TestModule.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/TestPanel.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/TestViewportCoordinates.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/TestViewportTool.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/ThrowAfterActivateAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/ToolbarAction.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/UpdateBarrierModule.cs create mode 100644 tests/editor/Inno.Editor.Presentation.Tests/ZThrowingDisposeModule.cs rename tests/extensibility/Inno.Extensibility.Modules.Tests/{AssemblyManagerTests.cs => ModuleHostTests.cs} (99%) create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/AbstractAttributedType.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/AttributedType.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/DeterministicStableType.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/GeneratedMappedType.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/ITestContract.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/OutsideStableAnnotatedType.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeA.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractContractImpl.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractDerived.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/TestBase.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/TestContractImpl.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/TestDerived.cs create mode 100644 tests/extensibility/Inno.Extensibility.Types.Tests/TestMarkerAttribute.cs create mode 100644 tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/FirstConflictingExtension.cs rename tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/{ConflictingExtensions.cs => SecondConflictingExtension.cs} (57%) create mode 100644 tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkedType.cs rename tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/{AssemblyATypes.cs => AssemblyAMarkerAttribute.cs} (58%) create mode 100644 tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkedType.cs rename tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/{AssemblyBTypes.cs => AssemblyBMarkerAttribute.cs} (59%) create mode 100644 tests/plugins/Inno.Plugins.Tests/PluginDefaultTestSetting.cs create mode 100644 tests/plugins/Inno.Plugins.Tests/PluginSourceSerializationCollection.cs create mode 100644 tests/plugins/Inno.Plugins.Tests/TestAssetSourceMeta.cs create mode 100644 tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetSourceMeta.cs create mode 100644 tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetsSerializationCollection.cs create mode 100644 tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImportSettingsEnvelope.cs rename tests/rendering/Inno.Rendering.Runtime.Tests/{ShaderProgramPublicationTests.cs => RenderRuntimeGenerationTests.ShaderProgramPublication.cs} (99%) create mode 100644 tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.cs create mode 100644 tests/rendering/Inno.Rendering.Shaders.Tests/MetalShaderFactAttribute.cs create mode 100644 tests/rendering/Inno.Rendering.Shaders.Tests/NodeRegistryProbe.cs create mode 100644 tests/rendering/Inno.Rendering.Shaders.Tests/RegistryFrontendProbe.cs rename tests/rendering/Inno.Rendering.Shaders.Tests/{ShaderGraphSharedProgramTests.cs => ShaderGraphProgramTests.SharedProgram.cs} (99%) rename tests/rendering/Inno.Rendering.Shaders.Tests/{ShaderGraphStorageTests.cs => ShaderGraphProgramTests.Storage.cs} (99%) create mode 100644 tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableFramePayload.cs create mode 100644 tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderFeature.cs delete mode 100644 tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs create mode 100644 tests/scene/Inno.Scene.Tests/EngineAssetReferenceComponent.cs create mode 100644 tests/scene/Inno.Scene.Tests/EngineObjectReferenceComponent.cs create mode 100644 tests/scene/Inno.Scene.Tests/LayerValueComponent.cs create mode 100644 tests/scene/Inno.Scene.Tests/OrderComponentA.cs create mode 100644 tests/scene/Inno.Scene.Tests/OrderComponentB.cs create mode 100644 tests/scene/Inno.Scene.Tests/OrderSerializationSystemA.cs create mode 100644 tests/scene/Inno.Scene.Tests/OrderSerializationSystemB.cs create mode 100644 tests/scene/Inno.Scene.Tests/PrefabInstantiationBehavior.cs create mode 100644 tests/scene/Inno.Scene.Tests/PropertyElementEnvelope.cs create mode 100644 tests/scene/Inno.Scene.Tests/PropertyReferenceProbe.cs create mode 100644 tests/scene/Inno.Scene.Tests/PropertyReferenceTokenFixture.cs create mode 100644 tests/scene/Inno.Scene.Tests/ReferenceComponent.cs create mode 100644 tests/scene/Inno.Scene.Tests/SceneTestsFixture.cs create mode 100644 tests/scene/Inno.Scene.Tests/StateSystem.cs create mode 100644 tests/scene/Inno.Scene.Tests/SystemReferenceComponent.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/AttributeOwner.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/AttributeValue.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/AttributeValueDrawer.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayload.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayloadConverter.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/InlineFailure.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/InlineFailureDrawer.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/InlineOwner.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/InlineParent.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/InlineParentDrawer.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttribute.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttributeDrawer.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/SampleIdentitySettings.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/SceneReloadProbe.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/ScriptingAssetSourceMeta.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/ScriptingCompilationProbe.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/TextStateDrawer.cs create mode 100644 tests/scripting/Inno.Editor.Scripting.Tests/TextStateOwner.cs create mode 100644 tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressCollection.cs create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/EmptyTypeStyleRule.cs create mode 100644 tools/Inno.Tooling.Documentation/Indexing/DocumentationApiCapture.cs create mode 100644 tools/Inno.Tooling.Documentation/Indexing/DocumentationBinding.cs create mode 100644 tools/Inno.Tooling.Documentation/Indexing/DocumentationManifest.cs delete mode 100644 tools/Inno.Tooling.Documentation/Indexing/DocumentationModels.cs create mode 100644 tools/Inno.Tooling.Documentation/Indexing/DocumentationPageReference.cs create mode 100644 tools/Inno.Tooling.Documentation/Indexing/DocumentationProject.cs create mode 100644 tools/Inno.Tooling.Documentation/Indexing/DocumentationSearchEntry.cs create mode 100644 tools/Inno.Tooling.Documentation/Indexing/DocumentationSymbolReference.cs create mode 100644 tools/Inno.Tooling.Validation/ValidationProfiles.cs create mode 100644 tools/Inno.Tooling.Validation/ValidationShards.cs diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs index fd9011052..2d0bc2dad 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Intermediate/BgfxShaderIrGenerator.cs @@ -1,23 +1,13 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; -using System.Security.Cryptography; using System.Text; using Inno.Rendering; -using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Shaders; namespace Inno.Build.Toolchains.Bgfx.Tools; -internal sealed record BgfxGeneratedStage( - string source, - string varying, - IReadOnlyList bindings, - IReadOnlyList sourcePositions -); - // SC spelling, hardware semantics and module symbol isolation belong only to this adapter. internal sealed partial class BgfxShaderIrGenerator(ShaderIrStage stage) { @@ -386,3 +376,10 @@ private void EmitCall(ShaderIrInstruction instruction) } } } + +internal sealed record BgfxGeneratedStage( + string source, + string varying, + IReadOnlyList bindings, + IReadOnlyList sourcePositions +); diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs index 66ae6bd24..c2c1aa6f8 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxShaderSourceFrontend.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Globalization; -using System.Linq; using Inno.Core.Diagnostics; using Inno.Rendering.Shaders; @@ -46,455 +44,3 @@ [new ShaderSourceDiagnostic("SHADER_SOURCE_INTERFACE", DiagnosticSeverity.Error, } } } - -internal sealed class BgfxSourceDeclarationParser( - List tokens, - ShaderSourceRequest request -) { - private readonly Dictionary m_types = new(StringComparer.Ordinal); - private readonly Dictionary m_constants = new(StringComparer.Ordinal); - private readonly List m_exports = []; - private readonly List<(IReadOnlyList parameters, List body)> m_bodies = []; - private int m_offset; - internal IReadOnlyDictionary types => m_types; - internal HashSet globals { get; } = new(StringComparer.Ordinal); - internal List<(int start, int end)> typeDeclarations { get; } = []; - - internal ShaderSourceFunction Parse() - { - while (m_offset < tokens.Count) - { - if (Match(";")) - { - continue; - } - int declarationStart = m_offset; - if (Peek("struct")) - { - ReadStructure(); - typeDeclarations.Add((declarationStart, m_offset)); - continue; - } - bool alias = Match("typedef"); - bool constant = false; - while (m_offset < tokens.Count && IsQualifier(tokens[m_offset].text)) - { - constant |= tokens[m_offset++].text == "const"; - } - ShaderSourceType type = ReadType(); - BgfxSourceToken name = ReadIdentifier(); - if (Match("(")) - { - if (alias) - { - Fail("Function typedefs are not source module value types.", name); - } - List parameters = ReadParameters(); - if (name.text == "main") - { - Fail("A source module cannot declare main(); shader entries are generated from graph outputs.", name); - } - globals.Add(name.text); - if (Match(";")) - { - continue; - } - Require("{"); - m_bodies.Add((parameters, ReadBody())); - if (name.text == request.entryPoint) - { - if (!StringComparer.Ordinal.Equals(name.position.assetPath, request.source.assetPath)) - { - Fail("The exported function must be declared in its selected source file, not an include.", name); - } - m_exports.Add(new ShaderSourceFunction(name.text, type, parameters, name.position)); - } - continue; - } - type = ReadArray(type); - if (alias) - { - if (!m_types.TryAdd(name.text, type)) - { - Fail($"Type '{name.text}' is already declared.", name); - } - Require(";"); - typeDeclarations.Add((declarationStart, m_offset)); - continue; - } - if (!constant) - { - Fail("Module globals must be constants; stage inputs and resource bindings belong to the graph target.", name); - } - globals.Add(name.text); - if (Match("=")) - { - List initializer = ReadUntilSemicolon(); - if (type.id is "int" or "uint") - { - m_constants[name.text] = EvaluateInteger(initializer, name); - } - } - else - { - Require(";"); - } - } - if (m_exports.Count != 1) - { - throw new BgfxSourceSyntaxException( - m_exports.Count == 0 - ? $"Source does not define the selected public function '{request.entryPoint}'." - : $"Public function '{request.entryPoint}' is overloaded or defined more than once; select an unambiguous export.", - new ShaderSourcePosition(request.source.assetPath, 1, 1) - ); - } - ValidateExplicitInterfaces(); - return m_exports[0]; - } - - private List ReadParameters() - { - List parameters = []; - if (Match(")")) - { - return parameters; - } - if (Peek("void") && m_offset + 1 < tokens.Count && tokens[m_offset + 1].text == ")") - { - m_offset += 2; - return parameters; - } - do - { - ShaderSourceParameterDirection direction = ShaderSourceParameterDirection.Input; - bool directionAssigned = false; - while (m_offset < tokens.Count) - { - BgfxSourceToken qualifier = tokens[m_offset]; - if (qualifier.text is "in" or "out" or "inout") - { - if (directionAssigned) - { - Fail("A parameter has more than one direction qualifier.", qualifier); - } - directionAssigned = true; - direction = qualifier.text switch - { - "out" => ShaderSourceParameterDirection.Output, - "inout" => ShaderSourceParameterDirection.InputOutput, - _ => ShaderSourceParameterDirection.Input - }; - m_offset++; - } - else if (IsQualifier(qualifier.text)) - { - m_offset++; - } - else - { - break; - } - } - ShaderSourceType type = ReadType(); - BgfxSourceToken name = ReadIdentifier(); - if (type.id == "void") - { - Fail("A parameter cannot have void type.", name); - } - type = ReadArray(type); - if (parameters.Any(parameter => parameter.name == name.text)) - { - Fail("Duplicate public parameter name.", name); - } - parameters.Add(new ShaderSourceParameter(name.text, type, direction)); - } - while (Match(",")); - Require(")"); - return parameters; - } - - private void ReadStructure() - { - Require("struct"); - BgfxSourceToken name = ReadIdentifier(); - Require("{"); - List fields = []; - while (!Match("}")) - { - while (m_offset < tokens.Count && IsQualifier(tokens[m_offset].text)) - { - m_offset++; - } - ShaderSourceType type = ReadType(); - if (type.id == "void") - { - Fail("A structure field cannot have void type.", name); - } - do - { - BgfxSourceToken field = ReadIdentifier(); - ShaderSourceType fieldType = ReadArray(type); - if (fields.Any(existing => existing.name == field.text)) - { - Fail("Duplicate structure member name.", field); - } - fields.Add(new ShaderSourceField(field.text, fieldType)); - } - while (Match(",")); - Require(";"); - } - Require(";"); - if (fields.Count == 0) - { - Fail("A structure requires at least one field.", name); - } - if (!m_types.TryAdd(name.text, ShaderSourceType.Structure("struct:" + name.text, fields))) - { - Fail($"Type '{name.text}' is already declared.", name); - } - } - - private ShaderSourceType ReadType() - { - BgfxSourceToken token = ReadIdentifier(); - if (m_types.TryGetValue(token.text, out ShaderSourceType? declared)) - { - return declared; - } - string? canonical = token.text switch - { - "void" or "bool" or "int" or "uint" or "float" or "double" => token.text, - "half" => "float16", - "vec2" or "float2" => "float2", - "vec3" or "float3" => "float3", - "vec4" or "float4" => "float4", - "ivec2" or "int2" => "int2", - "ivec3" or "int3" => "int3", - "ivec4" or "int4" => "int4", - "uvec2" or "uint2" => "uint2", - "uvec3" or "uint3" => "uint3", - "uvec4" or "uint4" => "uint4", - "bvec2" or "bool2" => "bool2", - "bvec3" or "bool3" => "bool3", - "bvec4" or "bool4" => "bool4", - "mat2" or "float2x2" => "float2x2", - "mat3" or "float3x3" => "float3x3", - "mat4" or "float4x4" => "float4x4", - "sampler2D" or "BgfxSampler2D" => "sampled-texture2d", - "sampler2DArray" or "BgfxSampler2DArray" => "sampled-texture2d-array", - "sampler3D" or "BgfxSampler3D" => "sampled-texture3d", - "samplerCube" or "BgfxSamplerCube" => "sampled-texture-cube", - _ => null - }; - if (canonical is null) - { - Fail($"Unsupported or undeclared source type '{token.text}'.", token); - } - return ShaderSourceType.Atomic(canonical!); - } - - private ShaderSourceType ReadArray(ShaderSourceType element) - { - List lengths = []; - while (Match("[")) - { - BgfxSourceToken start = Current(); - if (element.id == "void") - { - Fail("An array cannot contain void values.", start); - } - List expression = []; - while (!Match("]")) - { - expression.Add(Next()); - } - long count = EvaluateInteger(expression, start); - if (count <= 0 || count > int.MaxValue) - { - Fail("Function interface arrays require a positive, fixed 32-bit length.", start); - } - lengths.Add((int)count); - } - for (int i = lengths.Count - 1; i >= 0; i--) - { - element = ShaderSourceType.ArrayOf(element, lengths[i]); - } - return element; - } - - private long EvaluateInteger( - List expression, - BgfxSourceToken location - ) { - if (expression.Count == 0) - { - Fail("Expected a fixed integer expression.", location); - } - List values = []; - foreach (BgfxSourceToken token in expression) - { - if (!token.isIdentifier) - { - values.Add(token); - continue; - } - if (!m_constants.TryGetValue(token.text, out long constant)) - { - Fail($"Unresolved array constant '{token.text}'.", token); - } - values.Add(new BgfxSourceToken("(", token.position)); - foreach (BgfxSourceToken literal in BgfxSourceLexer.Tokenize( - new ShaderSourceFile(token.position.assetPath, constant.ToString(CultureInfo.InvariantCulture)) - )) { - values.Add(literal with { position = token.position }); - } - values.Add(new BgfxSourceToken(")", token.position)); - } - return new BgfxPreprocessorExpression(values).Evaluate(); - } - - private List ReadUntilSemicolon() - { - List result = []; - int braces = 0; - int parentheses = 0; - while (true) - { - BgfxSourceToken token = Next(); - if (token.text == ";" && braces == 0 && parentheses == 0) - { - return result; - } - if (token.text == "{") - { - braces++; - } - if (token.text == "}") - { - braces--; - } - if (token.text == "(") - { - parentheses++; - } - if (token.text == ")") - { - parentheses--; - } - result.Add(token); - } - } - - private List ReadBody() - { - List body = []; - int nesting = 1; - while (nesting != 0) - { - BgfxSourceToken token = Next(); - if (token.text == "{") - { - nesting++; - } - if (token.text == "}") - { - nesting--; - } - body.Add(token); - } - return body; - } - - private void ValidateExplicitInterfaces() - { - foreach ((IReadOnlyList parameters, List body) in m_bodies) - { - var explicitNames = new HashSet(parameters.Select(static value => value.name), StringComparer.Ordinal); - explicitNames.UnionWith(globals); - for (int index = 0; index < body.Count; index++) - { - BgfxSourceToken token = body[index]; - if (index != 0 && body[index - 1].text == ".") - { - continue; - } - if (!explicitNames.Contains(token.text) && IsImplicitStageName(token.text)) - { - Fail( - $"Source functions must receive '{token.text}' through an explicit parameter; native stage bindings are generated by the graph target.", - token - ); - } - } - } - } - - private BgfxSourceToken ReadIdentifier() - { - BgfxSourceToken token = Next(); - if (!token.isIdentifier) - { - Fail($"Expected an identifier, found '{token.text}'.", token); - } - return token; - } - - private BgfxSourceToken Current() - { - if (m_offset >= tokens.Count) - { - throw new BgfxSourceSyntaxException( - "Unexpected end of source declaration.", - tokens.Count == 0 - ? new ShaderSourcePosition(request.source.assetPath, 1, 1) - : tokens[^1].position - ); - } - return tokens[m_offset]; - } - - private BgfxSourceToken Next() - { - BgfxSourceToken token = Current(); - m_offset++; - return token; - } - - private bool Peek(string value) => m_offset < tokens.Count && tokens[m_offset].text == value; - - private bool Match(string value) - { - if (!Peek(value)) - { - return false; - } - m_offset++; - return true; - } - - private void Require(string value) - { - if (!Match(value)) - { - Fail($"Expected '{value}'.", Current()); - } - } - - private static bool IsImplicitStageName(string name) - => name.StartsWith("gl_", StringComparison.Ordinal) || name.StartsWith("inno_", StringComparison.Ordinal) - || name.StartsWith("u_inno_", StringComparison.Ordinal) || name.StartsWith("s_inno_", StringComparison.Ordinal) - || name.StartsWith("v_texcoord", StringComparison.Ordinal) || name.StartsWith("v_color", StringComparison.Ordinal) - || name.StartsWith("i_data", StringComparison.Ordinal) || name.StartsWith("a_texcoord", StringComparison.Ordinal) - || name.StartsWith("a_color", StringComparison.Ordinal) - || name is "a_position" or "a_normal" or "a_tangent" or "a_bitangent" or "a_weight" or "a_indices" - or "u_viewRect" or "u_viewTexel" or "u_view" or "u_invView" or "u_proj" or "u_invProj" or "u_viewProj" - or "u_invViewProj" or "u_model" or "u_modelView" or "u_invModelView" or "u_modelViewProj" or "u_alphaRef4"; - - private static bool IsQualifier(string value) => value is "const" or "static" or "inline" or "highp" or "mediump" or "lowp"; - - private static void Fail( - string message, - BgfxSourceToken token - ) => throw new BgfxSourceSyntaxException(message, token.position); -} diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceDeclarationParser.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceDeclarationParser.cs new file mode 100644 index 000000000..0a1fce5d8 --- /dev/null +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceDeclarationParser.cs @@ -0,0 +1,459 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using Inno.Rendering.Shaders; + +namespace Inno.Build.Toolchains.Bgfx.Tools; + +internal sealed class BgfxSourceDeclarationParser( + List tokens, + ShaderSourceRequest request +) { + private readonly Dictionary m_types = new(StringComparer.Ordinal); + private readonly Dictionary m_constants = new(StringComparer.Ordinal); + private readonly List m_exports = []; + private readonly List<(IReadOnlyList parameters, List body)> m_bodies = []; + private int m_offset; + internal IReadOnlyDictionary types => m_types; + internal HashSet globals { get; } = new(StringComparer.Ordinal); + internal List<(int start, int end)> typeDeclarations { get; } = []; + + internal ShaderSourceFunction Parse() + { + while (m_offset < tokens.Count) + { + if (Match(";")) + { + continue; + } + int declarationStart = m_offset; + if (Peek("struct")) + { + ReadStructure(); + typeDeclarations.Add((declarationStart, m_offset)); + continue; + } + bool alias = Match("typedef"); + bool constant = false; + while (m_offset < tokens.Count && IsQualifier(tokens[m_offset].text)) + { + constant |= tokens[m_offset++].text == "const"; + } + ShaderSourceType type = ReadType(); + BgfxSourceToken name = ReadIdentifier(); + if (Match("(")) + { + if (alias) + { + Fail("Function typedefs are not source module value types.", name); + } + List parameters = ReadParameters(); + if (name.text == "main") + { + Fail("A source module cannot declare main(); shader entries are generated from graph outputs.", name); + } + globals.Add(name.text); + if (Match(";")) + { + continue; + } + Require("{"); + m_bodies.Add((parameters, ReadBody())); + if (name.text == request.entryPoint) + { + if (!StringComparer.Ordinal.Equals(name.position.assetPath, request.source.assetPath)) + { + Fail("The exported function must be declared in its selected source file, not an include.", name); + } + m_exports.Add(new ShaderSourceFunction(name.text, type, parameters, name.position)); + } + continue; + } + type = ReadArray(type); + if (alias) + { + if (!m_types.TryAdd(name.text, type)) + { + Fail($"Type '{name.text}' is already declared.", name); + } + Require(";"); + typeDeclarations.Add((declarationStart, m_offset)); + continue; + } + if (!constant) + { + Fail("Module globals must be constants; stage inputs and resource bindings belong to the graph target.", name); + } + globals.Add(name.text); + if (Match("=")) + { + List initializer = ReadUntilSemicolon(); + if (type.id is "int" or "uint") + { + m_constants[name.text] = EvaluateInteger(initializer, name); + } + } + else + { + Require(";"); + } + } + if (m_exports.Count != 1) + { + throw new BgfxSourceSyntaxException( + m_exports.Count == 0 + ? $"Source does not define the selected public function '{request.entryPoint}'." + : $"Public function '{request.entryPoint}' is overloaded or defined more than once; select an unambiguous export.", + new ShaderSourcePosition(request.source.assetPath, 1, 1) + ); + } + ValidateExplicitInterfaces(); + return m_exports[0]; + } + + private List ReadParameters() + { + List parameters = []; + if (Match(")")) + { + return parameters; + } + if (Peek("void") && m_offset + 1 < tokens.Count && tokens[m_offset + 1].text == ")") + { + m_offset += 2; + return parameters; + } + do + { + ShaderSourceParameterDirection direction = ShaderSourceParameterDirection.Input; + bool directionAssigned = false; + while (m_offset < tokens.Count) + { + BgfxSourceToken qualifier = tokens[m_offset]; + if (qualifier.text is "in" or "out" or "inout") + { + if (directionAssigned) + { + Fail("A parameter has more than one direction qualifier.", qualifier); + } + directionAssigned = true; + direction = qualifier.text switch + { + "out" => ShaderSourceParameterDirection.Output, + "inout" => ShaderSourceParameterDirection.InputOutput, + _ => ShaderSourceParameterDirection.Input + }; + m_offset++; + } + else if (IsQualifier(qualifier.text)) + { + m_offset++; + } + else + { + break; + } + } + ShaderSourceType type = ReadType(); + BgfxSourceToken name = ReadIdentifier(); + if (type.id == "void") + { + Fail("A parameter cannot have void type.", name); + } + type = ReadArray(type); + if (parameters.Any(parameter => parameter.name == name.text)) + { + Fail("Duplicate public parameter name.", name); + } + parameters.Add(new ShaderSourceParameter(name.text, type, direction)); + } + while (Match(",")); + Require(")"); + return parameters; + } + + private void ReadStructure() + { + Require("struct"); + BgfxSourceToken name = ReadIdentifier(); + Require("{"); + List fields = []; + while (!Match("}")) + { + while (m_offset < tokens.Count && IsQualifier(tokens[m_offset].text)) + { + m_offset++; + } + ShaderSourceType type = ReadType(); + if (type.id == "void") + { + Fail("A structure field cannot have void type.", name); + } + do + { + BgfxSourceToken field = ReadIdentifier(); + ShaderSourceType fieldType = ReadArray(type); + if (fields.Any(existing => existing.name == field.text)) + { + Fail("Duplicate structure member name.", field); + } + fields.Add(new ShaderSourceField(field.text, fieldType)); + } + while (Match(",")); + Require(";"); + } + Require(";"); + if (fields.Count == 0) + { + Fail("A structure requires at least one field.", name); + } + if (!m_types.TryAdd(name.text, ShaderSourceType.Structure("struct:" + name.text, fields))) + { + Fail($"Type '{name.text}' is already declared.", name); + } + } + + private ShaderSourceType ReadType() + { + BgfxSourceToken token = ReadIdentifier(); + if (m_types.TryGetValue(token.text, out ShaderSourceType? declared)) + { + return declared; + } + string? canonical = token.text switch + { + "void" or "bool" or "int" or "uint" or "float" or "double" => token.text, + "half" => "float16", + "vec2" or "float2" => "float2", + "vec3" or "float3" => "float3", + "vec4" or "float4" => "float4", + "ivec2" or "int2" => "int2", + "ivec3" or "int3" => "int3", + "ivec4" or "int4" => "int4", + "uvec2" or "uint2" => "uint2", + "uvec3" or "uint3" => "uint3", + "uvec4" or "uint4" => "uint4", + "bvec2" or "bool2" => "bool2", + "bvec3" or "bool3" => "bool3", + "bvec4" or "bool4" => "bool4", + "mat2" or "float2x2" => "float2x2", + "mat3" or "float3x3" => "float3x3", + "mat4" or "float4x4" => "float4x4", + "sampler2D" or "BgfxSampler2D" => "sampled-texture2d", + "sampler2DArray" or "BgfxSampler2DArray" => "sampled-texture2d-array", + "sampler3D" or "BgfxSampler3D" => "sampled-texture3d", + "samplerCube" or "BgfxSamplerCube" => "sampled-texture-cube", + _ => null + }; + if (canonical is null) + { + Fail($"Unsupported or undeclared source type '{token.text}'.", token); + } + return ShaderSourceType.Atomic(canonical!); + } + + private ShaderSourceType ReadArray(ShaderSourceType element) + { + List lengths = []; + while (Match("[")) + { + BgfxSourceToken start = Current(); + if (element.id == "void") + { + Fail("An array cannot contain void values.", start); + } + List expression = []; + while (!Match("]")) + { + expression.Add(Next()); + } + long count = EvaluateInteger(expression, start); + if (count <= 0 || count > int.MaxValue) + { + Fail("Function interface arrays require a positive, fixed 32-bit length.", start); + } + lengths.Add((int)count); + } + for (int i = lengths.Count - 1; i >= 0; i--) + { + element = ShaderSourceType.ArrayOf(element, lengths[i]); + } + return element; + } + + private long EvaluateInteger( + List expression, + BgfxSourceToken location + ) { + if (expression.Count == 0) + { + Fail("Expected a fixed integer expression.", location); + } + List values = []; + foreach (BgfxSourceToken token in expression) + { + if (!token.isIdentifier) + { + values.Add(token); + continue; + } + if (!m_constants.TryGetValue(token.text, out long constant)) + { + Fail($"Unresolved array constant '{token.text}'.", token); + } + values.Add(new BgfxSourceToken("(", token.position)); + foreach (BgfxSourceToken literal in BgfxSourceLexer.Tokenize( + new ShaderSourceFile(token.position.assetPath, constant.ToString(CultureInfo.InvariantCulture)) + )) { + values.Add(literal with { position = token.position }); + } + values.Add(new BgfxSourceToken(")", token.position)); + } + return new BgfxPreprocessorExpression(values).Evaluate(); + } + + private List ReadUntilSemicolon() + { + List result = []; + int braces = 0; + int parentheses = 0; + while (true) + { + BgfxSourceToken token = Next(); + if (token.text == ";" && braces == 0 && parentheses == 0) + { + return result; + } + if (token.text == "{") + { + braces++; + } + if (token.text == "}") + { + braces--; + } + if (token.text == "(") + { + parentheses++; + } + if (token.text == ")") + { + parentheses--; + } + result.Add(token); + } + } + + private List ReadBody() + { + List body = []; + int nesting = 1; + while (nesting != 0) + { + BgfxSourceToken token = Next(); + if (token.text == "{") + { + nesting++; + } + if (token.text == "}") + { + nesting--; + } + body.Add(token); + } + return body; + } + + private void ValidateExplicitInterfaces() + { + foreach ((IReadOnlyList parameters, List body) in m_bodies) + { + var explicitNames = new HashSet(parameters.Select(static value => value.name), StringComparer.Ordinal); + explicitNames.UnionWith(globals); + for (int index = 0; index < body.Count; index++) + { + BgfxSourceToken token = body[index]; + if (index != 0 && body[index - 1].text == ".") + { + continue; + } + if (!explicitNames.Contains(token.text) && IsImplicitStageName(token.text)) + { + Fail( + $"Source functions must receive '{token.text}' through an explicit parameter; native stage bindings are generated by the graph target.", + token + ); + } + } + } + } + + private BgfxSourceToken ReadIdentifier() + { + BgfxSourceToken token = Next(); + if (!token.isIdentifier) + { + Fail($"Expected an identifier, found '{token.text}'.", token); + } + return token; + } + + private BgfxSourceToken Current() + { + if (m_offset >= tokens.Count) + { + throw new BgfxSourceSyntaxException( + "Unexpected end of source declaration.", + tokens.Count == 0 + ? new ShaderSourcePosition(request.source.assetPath, 1, 1) + : tokens[^1].position + ); + } + return tokens[m_offset]; + } + + private BgfxSourceToken Next() + { + BgfxSourceToken token = Current(); + m_offset++; + return token; + } + + private bool Peek(string value) => m_offset < tokens.Count && tokens[m_offset].text == value; + + private bool Match(string value) + { + if (!Peek(value)) + { + return false; + } + m_offset++; + return true; + } + + private void Require(string value) + { + if (!Match(value)) + { + Fail($"Expected '{value}'.", Current()); + } + } + + private static bool IsImplicitStageName(string name) + => name.StartsWith("gl_", StringComparison.Ordinal) || name.StartsWith("inno_", StringComparison.Ordinal) + || name.StartsWith("u_inno_", StringComparison.Ordinal) || name.StartsWith("s_inno_", StringComparison.Ordinal) + || name.StartsWith("v_texcoord", StringComparison.Ordinal) || name.StartsWith("v_color", StringComparison.Ordinal) + || name.StartsWith("i_data", StringComparison.Ordinal) || name.StartsWith("a_texcoord", StringComparison.Ordinal) + || name.StartsWith("a_color", StringComparison.Ordinal) + || name is "a_position" or "a_normal" or "a_tangent" or "a_bitangent" or "a_weight" or "a_indices" + or "u_viewRect" or "u_viewTexel" or "u_view" or "u_invView" or "u_proj" or "u_invProj" or "u_viewProj" + or "u_invViewProj" or "u_model" or "u_modelView" or "u_invModelView" or "u_modelViewProj" or "u_alphaRef4"; + + private static bool IsQualifier(string value) => value is "const" or "static" or "inline" or "highp" or "mediump" or "lowp"; + + private static void Fail( + string message, + BgfxSourceToken token + ) => throw new BgfxSourceSyntaxException(message, token.position); +} diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs index 9a08d6319..e77b4980d 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceLexer.cs @@ -1,24 +1,8 @@ -using System; using System.Collections.Generic; using Inno.Rendering.Shaders; namespace Inno.Build.Toolchains.Bgfx.Tools; -internal readonly record struct BgfxSourceToken( - string text, - ShaderSourcePosition position -) { - internal bool isIdentifier => text.Length != 0 && (char.IsLetter(text[0]) || text[0] == '_'); -} - -internal sealed class BgfxSourceSyntaxException( - string message, - ShaderSourcePosition position -) : Exception(message) -{ - internal ShaderSourcePosition position { get; } = position; -} - internal static class BgfxSourceLexer { internal static List Tokenize(ShaderSourceFile source) @@ -177,3 +161,10 @@ char second or ('<', '<') or ('>', '>') or ('#', '#') or ('+', '+') or ('-', '-') or ('+', '=') or ('-', '=') or ('*', '=') or ('/', '=') or ('&', '=') or ('|', '=') or ('^', '=') or ('%', '='); } + +internal readonly record struct BgfxSourceToken( + string text, + ShaderSourcePosition position +) { + internal bool isIdentifier => text.Length != 0 && (char.IsLetter(text[0]) || text[0] == '_'); +} diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceSyntaxException.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceSyntaxException.cs new file mode 100644 index 000000000..9e654a655 --- /dev/null +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Sources/BgfxSourceSyntaxException.cs @@ -0,0 +1,12 @@ +using System; +using Inno.Rendering.Shaders; + +namespace Inno.Build.Toolchains.Bgfx.Tools; + +internal sealed class BgfxSourceSyntaxException( + string message, + ShaderSourcePosition position +) : Exception(message) +{ + internal ShaderSourcePosition position { get; } = position; +} diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferKind.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferKind.cs new file mode 100644 index 000000000..56c8a9609 --- /dev/null +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferKind.cs @@ -0,0 +1,10 @@ +namespace Inno.Adapter.Rendering.Bgfx; + +internal enum BgfxBufferKind +{ + Vertex, + Index, + DynamicVertex, + DynamicIndex, + Indirect +} diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxResources.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferResource.cs similarity index 59% rename from backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxResources.cs rename to backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferResource.cs index b456c9c6e..f46ad024e 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxResources.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxBufferResource.cs @@ -1,19 +1,8 @@ -using System; -using System.Collections.Generic; using Inno.Native.Bgfx; using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx; -internal enum BgfxBufferKind -{ - Vertex, - Index, - DynamicVertex, - DynamicIndex, - Indirect -} - internal sealed class BgfxBufferResource { private BgfxBufferResource( @@ -156,103 +145,3 @@ public static BgfxBufferResource FromIndirect( bgfx.IndirectBufferHandle handle ) => new(descriptor, null, RenderIndexFormat.UInt32, BgfxBufferKind.Indirect, handle.idx); } - -internal sealed class BgfxShaderBindingResource -{ - /// - /// Creates a validated bgfx shader binding resource instance. - /// - /// - /// The descriptor consumed by bgfx shader binding resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The uniform consumed by bgfx shader binding resource; ownership remains with the caller unless explicitly stated otherwise. - /// - public BgfxShaderBindingResource( - RenderShaderBindingDescriptor descriptor, - bgfx.UniformHandle uniform - ) { - this.descriptor = descriptor; - this.uniform = uniform; - } - - /// - /// Gets the backend-neutral descriptor used to validate and recreate this resource. - /// - public RenderShaderBindingDescriptor descriptor { get; } - - /// - /// Gets the BGFX uniform handle backing this shader binding. - /// - public bgfx.UniformHandle uniform { get; } -} - -internal sealed class BgfxPipelineResource -{ - /// - /// Creates a validated bgfx pipeline resource instance. - /// - /// - /// The program consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The bindings consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The vertex layout consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The vertex layout handle consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The raster state consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// Whether compute behavior is enabled while bgfx pipeline resource executes. - /// - public BgfxPipelineResource( - bgfx.ProgramHandle program, - IReadOnlyDictionary bindings, - RenderVertexLayout? vertexLayout, - bgfx.VertexLayoutHandle vertexLayoutHandle, - RenderRasterState? rasterState, - bool compute - ) { - this.program = program; - this.bindings = bindings; - this.vertexLayout = vertexLayout; - this.vertexLayoutHandle = vertexLayoutHandle; - this.rasterState = rasterState; - this.compute = compute; - } - - /// - /// Gets the linked BGFX shader program owned by this pipeline resource. - /// - public bgfx.ProgramHandle program { get; } - - /// - /// Gets the immutable lookup of stable binding IDs to BGFX uniform resources. - /// - public IReadOnlyDictionary bindings { get; } - - /// - /// Gets the optional vertex layout required by this resource or pipeline. - /// - public RenderVertexLayout? vertexLayout { get; } - - /// - /// Gets the BGFX vertex-layout handle owned by this pipeline resource. - /// - public bgfx.VertexLayoutHandle vertexLayoutHandle { get; } - - /// - /// Gets the optional rasterization state encoded by this pipeline. - /// - public RenderRasterState? rasterState { get; } - - /// - /// Gets whether the caller-visible condition represented by this property is satisfied. - /// - public bool compute { get; } -} diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxPipelineResource.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxPipelineResource.cs new file mode 100644 index 000000000..a01645d1c --- /dev/null +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxPipelineResource.cs @@ -0,0 +1,75 @@ +using System.Collections.Generic; +using Inno.Native.Bgfx; +using Inno.Rendering; + +namespace Inno.Adapter.Rendering.Bgfx; + +internal sealed class BgfxPipelineResource +{ + /// + /// Creates a validated bgfx pipeline resource instance. + /// + /// + /// The program consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The bindings consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The vertex layout consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The vertex layout handle consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The raster state consumed by bgfx pipeline resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// Whether compute behavior is enabled while bgfx pipeline resource executes. + /// + public BgfxPipelineResource( + bgfx.ProgramHandle program, + IReadOnlyDictionary bindings, + RenderVertexLayout? vertexLayout, + bgfx.VertexLayoutHandle vertexLayoutHandle, + RenderRasterState? rasterState, + bool compute + ) { + this.program = program; + this.bindings = bindings; + this.vertexLayout = vertexLayout; + this.vertexLayoutHandle = vertexLayoutHandle; + this.rasterState = rasterState; + this.compute = compute; + } + + /// + /// Gets the linked BGFX shader program owned by this pipeline resource. + /// + public bgfx.ProgramHandle program { get; } + + /// + /// Gets the immutable lookup of stable binding IDs to BGFX uniform resources. + /// + public IReadOnlyDictionary bindings { get; } + + /// + /// Gets the optional vertex layout required by this resource or pipeline. + /// + public RenderVertexLayout? vertexLayout { get; } + + /// + /// Gets the BGFX vertex-layout handle owned by this pipeline resource. + /// + public bgfx.VertexLayoutHandle vertexLayoutHandle { get; } + + /// + /// Gets the optional rasterization state encoded by this pipeline. + /// + public RenderRasterState? rasterState { get; } + + /// + /// Gets whether the caller-visible condition represented by this property is satisfied. + /// + public bool compute { get; } +} diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxShaderBindingResource.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxShaderBindingResource.cs new file mode 100644 index 000000000..099478c28 --- /dev/null +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/BgfxShaderBindingResource.cs @@ -0,0 +1,34 @@ +using Inno.Native.Bgfx; +using Inno.Rendering; + +namespace Inno.Adapter.Rendering.Bgfx; + +internal sealed class BgfxShaderBindingResource +{ + /// + /// Creates a validated bgfx shader binding resource instance. + /// + /// + /// The descriptor consumed by bgfx shader binding resource; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The uniform consumed by bgfx shader binding resource; ownership remains with the caller unless explicitly stated otherwise. + /// + public BgfxShaderBindingResource( + RenderShaderBindingDescriptor descriptor, + bgfx.UniformHandle uniform + ) { + this.descriptor = descriptor; + this.uniform = uniform; + } + + /// + /// Gets the backend-neutral descriptor used to validate and recreate this resource. + /// + public RenderShaderBindingDescriptor descriptor { get; } + + /// + /// Gets the BGFX uniform handle backing this shader binding. + /// + public bgfx.UniformHandle uniform { get; } +} diff --git a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/IBgfxSurfaceIntegration.cs b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/IBgfxSurfaceIntegration.cs index 55706669b..7a95e7a2f 100644 --- a/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/IBgfxSurfaceIntegration.cs +++ b/backends/Bgfx/runtime/Inno.Adapter.Rendering.Bgfx/Surfaces/IBgfxSurfaceIntegration.cs @@ -2,21 +2,6 @@ namespace Inno.Adapter.Rendering.Bgfx; -/// -/// Identifies how a borrowed window is used by a BGFX device, independently of its system ABI. -/// -public enum BgfxSurfaceRole -{ - /// - /// The primary window supplied before device initialization. - /// - Primary, - /// - /// An additional window whose framebuffer is owned by an active device generation. - /// - Additional -} - /// /// Resolves an explicitly selected host's borrowed surface handles for the shared BGFX backend. /// @@ -54,3 +39,18 @@ BgfxSurfaceDescriptor Resolve( BgfxSurfaceRole role ); } + +/// +/// Identifies how a borrowed window is used by a BGFX device, independently of its system ABI. +/// +public enum BgfxSurfaceRole +{ + /// + /// The primary window supplied before device initialization. + /// + Primary, + /// + /// An additional window whose framebuffer is owned by an active device generation. + /// + Additional +} diff --git a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs index dd73ba4a2..3c129d28c 100644 --- a/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs +++ b/backends/DotNet/runtime/Inno.Adapter.Modules.DotNet/Reloading/AssemblyUnloadMonitor.cs @@ -6,21 +6,6 @@ namespace Inno.Adapter.Modules.DotNet; -/// -/// Describes whether a collectible load context is still reachable. -/// -internal enum AssemblyUnloadStatus -{ - /// - /// At least one runtime reference still keeps the load context alive. - /// - Pending, - /// - /// The load context is no longer reachable, or the module was not collectible. - /// - Completed -} - /// /// Observes cooperative unload completion without retaining the old load context. /// @@ -126,3 +111,18 @@ internal bool TryCleanupShadowDirectory() } } } + +/// +/// Describes whether a collectible load context is still reachable. +/// +internal enum AssemblyUnloadStatus +{ + /// + /// At least one runtime reference still keeps the load context alive. + /// + Pending, + /// + /// The load context is no longer reachable, or the module was not collectible. + /// + Completed +} diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs index 89ab7372f..62a66c8bf 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/IPlatformImGuiRenderer.Api.cs @@ -1,84 +1,8 @@ using System; using System.Threading.Tasks; -using Inno.Adapter.Platform; -using Inno.Platform; namespace Inno.Adapter.Presentation.ImGui; -/// -/// Identifies a backend-owned texture through an opaque ImGui token instead of a native graphics handle. -/// -public readonly record struct ImGuiTextureHandle -{ - /// - /// Creates an opaque texture token allocated by an ImGui presentation backend. - /// - /// - /// Non-zero backend token. - /// - public ImGuiTextureHandle(ulong value) - { - ArgumentOutOfRangeException.ThrowIfZero(value); - - this.value = value; - } - - /// - /// Gets the opaque token consumed only by the active ImGui backend. - /// - public ulong value { get; } - - /// - /// Gets whether this token identifies a registered texture. - /// - public bool isValid => value != 0; -} - -/// -/// Describes one detached ImGui viewport without exposing SDL or graphics-backend handles. -/// -public sealed class PlatformImGuiViewportTarget -{ - internal PlatformImGuiViewportTarget( - uint viewportID, - uint windowID, - PlatformNativeHandles nativeHandles, - int width, - int height - ) { - this.viewportID = viewportID; - this.windowID = windowID; - this.nativeHandles = nativeHandles; - this.width = width; - this.height = height; - } - - /// - /// Gets the stable Dear ImGui viewport identity. - /// - public uint viewportID { get; } - - /// - /// Gets the platform window identity. - /// - public uint windowID { get; } - - /// - /// Gets backend-neutral native-window integration handles. - /// - public PlatformNativeHandles nativeHandles { get; } - - /// - /// Gets the current framebuffer width. - /// - public int width { get; internal set; } - - /// - /// Gets the current framebuffer height. - /// - public int height { get; internal set; } -} - /// /// Presents ImGui draw data through a replaceable renderer while platform input and windows stay shared. /// diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiTextureHandle.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiTextureHandle.cs new file mode 100644 index 000000000..776cee9c3 --- /dev/null +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/ImGuiTextureHandle.cs @@ -0,0 +1,32 @@ +using System; + +namespace Inno.Adapter.Presentation.ImGui; + +/// +/// Identifies a backend-owned texture through an opaque ImGui token instead of a native graphics handle. +/// +public readonly record struct ImGuiTextureHandle +{ + /// + /// Creates an opaque texture token allocated by an ImGui presentation backend. + /// + /// + /// Non-zero backend token. + /// + public ImGuiTextureHandle(ulong value) + { + ArgumentOutOfRangeException.ThrowIfZero(value); + + this.value = value; + } + + /// + /// Gets the opaque token consumed only by the active ImGui backend. + /// + public ulong value { get; } + + /// + /// Gets whether this token identifies a registered texture. + /// + public bool isValid => value != 0; +} diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiViewportTarget.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiViewportTarget.cs new file mode 100644 index 000000000..904eacace --- /dev/null +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Api/PlatformImGuiViewportTarget.cs @@ -0,0 +1,48 @@ +using Inno.Adapter.Platform; + +namespace Inno.Adapter.Presentation.ImGui; + +/// +/// Describes one detached ImGui viewport without exposing SDL or graphics-backend handles. +/// +public sealed class PlatformImGuiViewportTarget +{ + internal PlatformImGuiViewportTarget( + uint viewportID, + uint windowID, + PlatformNativeHandles nativeHandles, + int width, + int height + ) { + this.viewportID = viewportID; + this.windowID = windowID; + this.nativeHandles = nativeHandles; + this.width = width; + this.height = height; + } + + /// + /// Gets the stable Dear ImGui viewport identity. + /// + public uint viewportID { get; } + + /// + /// Gets the platform window identity. + /// + public uint windowID { get; } + + /// + /// Gets backend-neutral native-window integration handles. + /// + public PlatformNativeHandles nativeHandles { get; } + + /// + /// Gets the current framebuffer width. + /// + public int width { get; internal set; } + + /// + /// Gets the current framebuffer height. + /// + public int height { get; internal set; } +} diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs index 3407861ef..b91dbdce7 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFont.cs @@ -178,33 +178,3 @@ out nint font return fonts.TryGetValue(ImGuiFontStyle.Regular, out font); } } - -/// -/// Restores the previous ImGui font when a scoped style ends. -/// -public ref struct ImGuiFontScope -{ - private readonly nuint m_contextKey; - private bool m_isPushed; - - internal ImGuiFontScope( - nuint contextKey, - bool isPushed - ) { - m_contextKey = contextKey; - m_isPushed = isPushed; - } - - /// - /// Restores the font that was active before this scope. - /// - public void Dispose() - { - if (!m_isPushed) - { - return; - } - ImGuiFont.PopStyle(m_contextKey); - m_isPushed = false; - } -} diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontScope.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontScope.cs new file mode 100644 index 000000000..5ab3d34c2 --- /dev/null +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/ImGuiFontScope.cs @@ -0,0 +1,31 @@ +namespace Inno.Adapter.Presentation.ImGui; + +/// +/// Restores the previous ImGui font when a scoped style ends. +/// +public ref struct ImGuiFontScope +{ + private readonly nuint m_contextKey; + private bool m_isPushed; + + internal ImGuiFontScope( + nuint contextKey, + bool isPushed + ) { + m_contextKey = contextKey; + m_isPushed = isPushed; + } + + /// + /// Restores the font that was active before this scope. + /// + public void Dispose() + { + if (!m_isPushed) + { + return; + } + ImGuiFont.PopStyle(m_contextKey); + m_isPushed = false; + } +} diff --git a/build/cli/Inno.Build.Cli/BuildCommand.cs b/build/cli/Inno.Build.Cli/BuildCommand.cs index 51e28b553..2d896ca14 100644 --- a/build/cli/Inno.Build.Cli/BuildCommand.cs +++ b/build/cli/Inno.Build.Cli/BuildCommand.cs @@ -2,20 +2,11 @@ using System.Collections.Generic; using System.IO; using Inno.Assets; -using Inno.Build; using Inno.Build.Managed; using Inno.Core.Settings; namespace Inno.Build.Cli; -internal enum BuildCommandKind -{ - Game, - Plugin, - ImportSample, - Scripts -} - internal sealed class BuildCommand { private readonly IReadOnlyDictionary m_values; @@ -168,3 +159,11 @@ private static string Usage() + " InnoEngine.Build import-sample --project --source [--dotnet ]\n" + " InnoEngine.Build scripts --project --output [--dotnet ] [--ide]"; } + +internal enum BuildCommandKind +{ + Game, + Plugin, + ImportSample, + Scripts +} diff --git a/build/pipeline/Inno.Build/BuildDiagnostic.cs b/build/pipeline/Inno.Build/BuildDiagnostic.cs index 940a95c7c..a7d065c9e 100644 --- a/build/pipeline/Inno.Build/BuildDiagnostic.cs +++ b/build/pipeline/Inno.Build/BuildDiagnostic.cs @@ -2,25 +2,6 @@ namespace Inno.Build; -/// -/// Identifies the severity of one structured build diagnostic. -/// -public enum BuildDiagnosticSeverity -{ - /// - /// Provides non-failing build context. - /// - Information, - /// - /// Reports a condition that did not prevent output creation. - /// - Warning, - /// - /// Reports a condition that prevented a valid build. - /// - Error -} - /// /// Describes one stable machine-readable build problem or informational event. /// @@ -68,3 +49,22 @@ string message /// public string message { get; } } + +/// +/// Identifies the severity of one structured build diagnostic. +/// +public enum BuildDiagnosticSeverity +{ + /// + /// Provides non-failing build context. + /// + Information, + /// + /// Reports a condition that did not prevent output creation. + /// + Warning, + /// + /// Reports a condition that prevented a valid build. + /// + Error +} diff --git a/build/toolchains/Inno.Build.Toolchains/BuildArtifactCopier.cs b/build/toolchains/Inno.Build.Toolchains/BuildArtifactCopier.cs new file mode 100644 index 000000000..6379573be --- /dev/null +++ b/build/toolchains/Inno.Build.Toolchains/BuildArtifactCopier.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Inno.Build.Toolchains; + +/// +/// Copies filtered native outputs into the engine's rebuildable dependency store. +/// +public static class BuildArtifactCopier +{ + private const string C_DSYM_TOKEN = ".dSYM"; + + /// + /// Copies all artifacts accepted by one product policy into its output directory. + /// + /// + /// The native dependency root containing the configured build directory. + /// + /// + /// The destination directory receiving normalized artifacts. + /// + /// + /// The normalized native build configuration. + /// + /// + /// The immutable filtering and naming policy. + /// + public static void CopyArtifacts( + string buildRoot, + string outputDir, + string config, + BuildArtifactOptions options + ) { + string buildDir = Path.Combine(buildRoot, options.buildDirName); + if (!Directory.Exists(buildDir)) + { + throw new DirectoryNotFoundException($"Native artifact directory not found: {buildDir}"); + } + + List candidates = Directory.EnumerateFiles(buildDir, "*", SearchOption.AllDirectories) + .Where(path => + { + if (path.Contains(C_DSYM_TOKEN, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + string ext = Path.GetExtension(path); + if (!options.extensions.Contains(ext, StringComparer.OrdinalIgnoreCase)) + { + return false; + } + + string fileName = Path.GetFileName(path); + if (!ToolchainEnvironment.ContainsAny(fileName, options.libraryTokens.ToArray()) + || !MatchesConfiguration(Path.GetRelativePath(buildDir, path), config) + ) { + return false; + } + + if (options.requiredPathTokens is null || options.requiredPathTokens.Count == 0) + { + return true; + } + + string normalized = path.Replace('\\', '/'); + return ToolchainEnvironment.ContainsAny(normalized, options.requiredPathTokens.ToArray()); + }) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + if (candidates.Count == 0) + { + throw new FileNotFoundException($"No {config} native artifacts found under {buildDir}."); + } + + (string source, string name)[] artifacts = candidates.Select(source => ( + source, + name: options.normalizeOutputName(Path.GetFileName(source), config))).ToArray(); + IGrouping? duplicate = artifacts + .GroupBy(static artifact => artifact.name, StringComparer.OrdinalIgnoreCase) + .FirstOrDefault(static group => group.Count() > 1); + if (duplicate is not null) + { + throw new InvalidOperationException($"Multiple native artifacts produce '{duplicate.Key}'."); + } + + Directory.CreateDirectory(outputDir); + foreach ((string source, string name) artifact in artifacts) + { + File.Copy(artifact.source, Path.Combine(outputDir, artifact.name), overwrite: true); + } + } + + private static bool MatchesConfiguration( + string path, + string config + ) { + string name = Path.GetFileNameWithoutExtension(path); + if (name.EndsWith("Debug", StringComparison.OrdinalIgnoreCase)) + { + return config.Equals("debug", StringComparison.OrdinalIgnoreCase); + } + if (name.EndsWith("Release", StringComparison.OrdinalIgnoreCase)) + { + return config.Equals("release", StringComparison.OrdinalIgnoreCase); + } + string? directory = Path.GetDirectoryName(path); + if (string.IsNullOrEmpty(directory)) + { + return true; + } + string[] segments = directory.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + for (int index = segments.Length - 1; index >= 0; index--) + { + if (segments[index].Equals("Debug", StringComparison.OrdinalIgnoreCase)) + { + return config.Equals("debug", StringComparison.OrdinalIgnoreCase); + } + if (segments[index].Equals("Release", StringComparison.OrdinalIgnoreCase)) + { + return config.Equals("release", StringComparison.OrdinalIgnoreCase); + } + } + return true; + } +} diff --git a/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs b/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs index 9a0863c8a..bd320573c 100644 --- a/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs +++ b/build/toolchains/Inno.Build.Toolchains/BuildArtifactOptions.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Linq; namespace Inno.Build.Toolchains; @@ -30,126 +28,3 @@ public sealed record BuildArtifactOptions( IReadOnlyCollection? requiredPathTokens, Func normalizeOutputName ); - -/// -/// Copies filtered native outputs into the engine's rebuildable dependency store. -/// -public static class BuildArtifactCopier -{ - private const string C_DSYM_TOKEN = ".dSYM"; - - /// - /// Copies all artifacts accepted by one product policy into its output directory. - /// - /// - /// The native dependency root containing the configured build directory. - /// - /// - /// The destination directory receiving normalized artifacts. - /// - /// - /// The normalized native build configuration. - /// - /// - /// The immutable filtering and naming policy. - /// - public static void CopyArtifacts( - string buildRoot, - string outputDir, - string config, - BuildArtifactOptions options - ) { - string buildDir = Path.Combine(buildRoot, options.buildDirName); - if (!Directory.Exists(buildDir)) - { - throw new DirectoryNotFoundException($"Native artifact directory not found: {buildDir}"); - } - - List candidates = Directory.EnumerateFiles(buildDir, "*", SearchOption.AllDirectories) - .Where(path => - { - if (path.Contains(C_DSYM_TOKEN, StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - string ext = Path.GetExtension(path); - if (!options.extensions.Contains(ext, StringComparer.OrdinalIgnoreCase)) - { - return false; - } - - string fileName = Path.GetFileName(path); - if (!ToolchainEnvironment.ContainsAny(fileName, options.libraryTokens.ToArray()) - || !MatchesConfiguration(Path.GetRelativePath(buildDir, path), config) - ) { - return false; - } - - if (options.requiredPathTokens is null || options.requiredPathTokens.Count == 0) - { - return true; - } - - string normalized = path.Replace('\\', '/'); - return ToolchainEnvironment.ContainsAny(normalized, options.requiredPathTokens.ToArray()); - }) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList(); - - if (candidates.Count == 0) - { - throw new FileNotFoundException($"No {config} native artifacts found under {buildDir}."); - } - - (string source, string name)[] artifacts = candidates.Select(source => ( - source, - name: options.normalizeOutputName(Path.GetFileName(source), config))).ToArray(); - IGrouping? duplicate = artifacts - .GroupBy(static artifact => artifact.name, StringComparer.OrdinalIgnoreCase) - .FirstOrDefault(static group => group.Count() > 1); - if (duplicate is not null) - { - throw new InvalidOperationException($"Multiple native artifacts produce '{duplicate.Key}'."); - } - - Directory.CreateDirectory(outputDir); - foreach ((string source, string name) artifact in artifacts) - { - File.Copy(artifact.source, Path.Combine(outputDir, artifact.name), overwrite: true); - } - } - - private static bool MatchesConfiguration( - string path, - string config - ) { - string name = Path.GetFileNameWithoutExtension(path); - if (name.EndsWith("Debug", StringComparison.OrdinalIgnoreCase)) - { - return config.Equals("debug", StringComparison.OrdinalIgnoreCase); - } - if (name.EndsWith("Release", StringComparison.OrdinalIgnoreCase)) - { - return config.Equals("release", StringComparison.OrdinalIgnoreCase); - } - string? directory = Path.GetDirectoryName(path); - if (string.IsNullOrEmpty(directory)) - { - return true; - } - string[] segments = directory.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - for (int index = segments.Length - 1; index >= 0; index--) - { - if (segments[index].Equals("Debug", StringComparison.OrdinalIgnoreCase)) - { - return config.Equals("debug", StringComparison.OrdinalIgnoreCase); - } - if (segments[index].Equals("Release", StringComparison.OrdinalIgnoreCase)) - { - return config.Equals("release", StringComparison.OrdinalIgnoreCase); - } - } - return true; - } -} diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs index 317c468c1..06a5a36af 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifact.cs @@ -7,29 +7,6 @@ namespace Inno.Build.Toolchains; -/// -/// Describes the link or deployment role explicitly assigned by a native producer. -/// -public enum NativeArtifactRole -{ - /// - /// A library loaded by the runtime. - /// - SharedLibrary, - /// - /// A separate linker input referring to a shared library. - /// - ImportLibrary, - /// - /// An archive linked into the final executable. - /// - StaticArchive, - /// - /// A tool, header or other supporting payload. - /// - SupportFile -} - /// /// Identifies one exact output and its producer-declared role. /// @@ -137,3 +114,26 @@ private sealed record Entry( NativeArtifactRole role ); } + +/// +/// Describes the link or deployment role explicitly assigned by a native producer. +/// +public enum NativeArtifactRole +{ + /// + /// A library loaded by the runtime. + /// + SharedLibrary, + /// + /// A separate linker input referring to a shared library. + /// + ImportLibrary, + /// + /// An archive linked into the final executable. + /// + StaticArchive, + /// + /// A tool, header or other supporting payload. + /// + SupportFile +} diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs index 06c992b88..d6ea9b749 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeBindingGenerationRequest.cs @@ -5,21 +5,6 @@ namespace Inno.Build.Toolchains; -/// -/// Selects the publication owner of generated sources. -/// -public enum NativeBindingOutputMode -{ - /// - /// Replaces the component's authored host source and bridge outputs together. - /// - HostSource, - /// - /// Publishes immutable target outputs under the component's generation fingerprint. - /// - TargetArtifacts -} - /// /// Freezes the complete binding request before ownership waits or candidate creation. /// @@ -123,3 +108,18 @@ public NativeBindingGenerationRequest( /// public IReadOnlyDictionary componentOptions { get; } } + +/// +/// Selects the publication owner of generated sources. +/// +public enum NativeBindingOutputMode +{ + /// + /// Replaces the component's authored host source and bridge outputs together. + /// + HostSource, + /// + /// Publishes immutable target outputs under the component's generation fingerprint. + /// + TargetArtifacts +} diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs index f68732cc7..67be166ae 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeComponentBuildOptions.cs @@ -5,21 +5,6 @@ namespace Inno.Build.Toolchains; -/// -/// Specifies the linkage required by a product's native component operation. -/// -public enum NativeLibraryKind -{ - /// - /// Produces archives for the selected final linker. - /// - Static, - /// - /// Produces libraries loaded by the deployed product. - /// - Shared -} - /// /// Freezes product-owned linkage, ordered component definitions and their configuration inputs. /// @@ -147,3 +132,18 @@ private static string ValidatePath(string path) return portable; } } + +/// +/// Specifies the linkage required by a product's native component operation. +/// +public enum NativeLibraryKind +{ + /// + /// Produces archives for the selected final linker. + /// + Static, + /// + /// Produces libraries loaded by the deployed product. + /// + Shared +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/HeaderAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/HeaderAttribute.cs new file mode 100644 index 000000000..da2e04af3 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/HeaderAttribute.cs @@ -0,0 +1,39 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Starts a visually separated Inspector section before the annotated property. +/// +[Conditional("INNO_EDITOR")] +public sealed class HeaderAttribute : InspectorPresentationAttribute +{ + /// + /// Creates a section header with optional explanatory text. + /// + /// + /// Visible section title. + /// + /// + /// Optional explanatory text displayed when the title is hovered. + /// + public HeaderAttribute( + string title, + string description = "" + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(title); + this.title = title; + this.description = description ?? string.Empty; + } + + /// + /// Gets the visible section title. + /// + public string title { get; } + + /// + /// Gets the optional explanatory text. + /// + public string description { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/HelpBoxAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/HelpBoxAttribute.cs new file mode 100644 index 000000000..e9bf266d9 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/HelpBoxAttribute.cs @@ -0,0 +1,109 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Draws a wrapped explanatory message before the annotated Inspector property. +/// +[Conditional("INNO_EDITOR")] +public sealed class HelpBoxAttribute : InspectorPresentationAttribute +{ + /// + /// Creates an Inspector help message. + /// + /// + /// Non-empty message text. + /// + /// + /// Visual severity. + /// + public HelpBoxAttribute( + string text, + InspectorMessageType messageType = InspectorMessageType.Info + ) : this(text, messageType, string.Empty, InspectorCondition.Truthy, null) {} + + /// + /// Creates an Inspector help message shown when a sibling satisfies a named condition. + /// + /// + /// Non-empty message text. + /// + /// + /// Sibling field or property name. + /// + /// + /// Comparison applied to the sibling value. + /// + /// + /// Visual severity. + /// + public HelpBoxAttribute( + string text, + string conditionMember, + InspectorCondition condition, + InspectorMessageType messageType = InspectorMessageType.Info + ) : this(text, messageType, conditionMember, condition, null) {} + + /// + /// Creates an Inspector help message shown when a sibling equals a compile-time value. + /// + /// + /// Non-empty message text. + /// + /// + /// Sibling field or property name. + /// + /// + /// The expected value consumed by help box attribute; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// Visual severity. + /// + public HelpBoxAttribute( + string text, + string conditionMember, + object? expectedValue, + InspectorMessageType messageType = InspectorMessageType.Info + ) : this(text, messageType, conditionMember, InspectorCondition.Equal, expectedValue) {} + + private HelpBoxAttribute( + string text, + InspectorMessageType messageType, + string conditionMember, + InspectorCondition condition, + object? expectedValue + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(text); + this.text = text; + this.messageType = messageType; + this.conditionMember = conditionMember ?? string.Empty; + this.condition = condition; + this.expectedValue = expectedValue; + } + + /// + /// Gets the message text. + /// + public string text { get; } + + /// + /// Gets the visual severity. + /// + public InspectorMessageType messageType { get; } + + /// + /// Gets the optional sibling member controlling message visibility. + /// + public string conditionMember { get; } + + /// + /// Gets the optional sibling comparison. + /// + public InspectorCondition condition { get; } + + /// + /// Gets the optional expected constant. + /// + public object? expectedValue { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/HideIfAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/HideIfAttribute.cs new file mode 100644 index 000000000..6bfc6bbd8 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/HideIfAttribute.cs @@ -0,0 +1,74 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Hides the annotated Inspector property when a sibling member satisfies a condition. +/// +[Conditional("INNO_EDITOR")] +public sealed class HideIfAttribute : InspectorPresentationAttribute +{ + /// + /// Creates a truthiness condition. + /// + /// + /// Sibling field or property name. + /// + public HideIfAttribute(string memberName) + : this(memberName, InspectorCondition.Truthy, null) {} + + /// + /// Creates an equality condition. + /// + /// + /// Sibling field or property name. + /// + /// + /// Compile-time value that hides the property. + /// + public HideIfAttribute( + string memberName, + object? expectedValue + ) : this(memberName, InspectorCondition.Equal, expectedValue) {} + + /// + /// Creates a named condition that does not require an expected value. + /// + /// + /// Sibling field or property name. + /// + /// + /// Comparison applied to the sibling value. + /// + public HideIfAttribute( + string memberName, + InspectorCondition condition + ) : this(memberName, condition, null) {} + + private HideIfAttribute( + string memberName, + InspectorCondition condition, + object? expectedValue + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(memberName); + this.memberName = memberName; + this.condition = condition; + this.expectedValue = expectedValue; + } + + /// + /// Gets the sibling member name. + /// + public string memberName { get; } + + /// + /// Gets the comparison. + /// + public InspectorCondition condition { get; } + + /// + /// Gets the optional expected constant. + /// + public object? expectedValue { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorCondition.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorCondition.cs new file mode 100644 index 000000000..e1c65928b --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorCondition.cs @@ -0,0 +1,40 @@ +namespace Inno.Editor.Annotations; + +/// +/// Defines the comparison used by conditional Inspector presentation. +/// +public enum InspectorCondition +{ + /// + /// Shows a value when it evaluates as true or non-empty. + /// + Truthy, + /// + /// Shows a value when it evaluates as false, null, or empty. + /// + Falsy, + /// + /// Compares the value with the supplied expected constant. + /// + Equal, + /// + /// Requires the value to differ from the supplied expected constant. + /// + NotEqual, + /// + /// Requires a null value. + /// + Null, + /// + /// Requires a non-null value. + /// + NotNull, + /// + /// Requires a reference-like value to expose an assigned resource. + /// + Assigned, + /// + /// Requires a reference-like value not to expose an assigned resource. + /// + NotAssigned +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorMessageType.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorMessageType.cs new file mode 100644 index 000000000..1b5be80f7 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorMessageType.cs @@ -0,0 +1,20 @@ +namespace Inno.Editor.Annotations; + +/// +/// Selects the visual severity of an Inspector help message. +/// +public enum InspectorMessageType +{ + /// + /// Neutral explanatory information. + /// + Info, + /// + /// A non-blocking configuration warning. + /// + Warning, + /// + /// An invalid or unusable configuration. + /// + Error +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorNameAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorNameAttribute.cs new file mode 100644 index 000000000..03c8c7ef0 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorNameAttribute.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Replaces the generated Inspector label for one property. +/// +[Conditional("INNO_EDITOR")] +public sealed class InspectorNameAttribute : InspectorPresentationAttribute +{ + /// + /// Creates a label override. + /// + /// + /// Non-empty visible label. + /// + public InspectorNameAttribute(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + this.name = name; + } + + /// + /// Gets the visible label. + /// + public string name { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttribute.cs new file mode 100644 index 000000000..19955fd09 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttribute.cs @@ -0,0 +1,21 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Provides editor-only presentation metadata for one serialized field or property. +/// +/// +/// Presentation attributes never participate in serialization. Concrete attributes are conditional on +/// INNO_EDITOR, so their applications are omitted from Player script assemblies. +/// +[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] +[Conditional("INNO_EDITOR")] +public abstract class InspectorPresentationAttribute : Attribute +{ + /// + /// Gets or sets the relative order among presentation attributes declared on the same member. + /// + public int order { get; set; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs deleted file mode 100644 index 21f7ed8e7..000000000 --- a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorPresentationAttributes.cs +++ /dev/null @@ -1,503 +0,0 @@ -using System; -using System.Diagnostics; - -namespace Inno.Editor.Annotations; - -/// -/// Provides editor-only presentation metadata for one serialized field or property. -/// -/// -/// Presentation attributes never participate in serialization. Concrete attributes are conditional on -/// INNO_EDITOR, so their applications are omitted from Player script assemblies. -/// -[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] -[Conditional("INNO_EDITOR")] -public abstract class InspectorPresentationAttribute : Attribute -{ - /// - /// Gets or sets the relative order among presentation attributes declared on the same member. - /// - public int order { get; set; } -} - -/// -/// Starts a visually separated Inspector section before the annotated property. -/// -[Conditional("INNO_EDITOR")] -public sealed class HeaderAttribute : InspectorPresentationAttribute -{ - /// - /// Creates a section header with optional explanatory text. - /// - /// - /// Visible section title. - /// - /// - /// Optional explanatory text displayed when the title is hovered. - /// - public HeaderAttribute( - string title, - string description = "" - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(title); - this.title = title; - this.description = description ?? string.Empty; - } - - /// - /// Gets the visible section title. - /// - public string title { get; } - - /// - /// Gets the optional explanatory text. - /// - public string description { get; } -} - -/// -/// Draws persistent wrapped explanatory text before the annotated Inspector property. -/// -[Conditional("INNO_EDITOR")] -public sealed class TextAttribute : InspectorPresentationAttribute -{ - /// - /// Creates persistent Inspector text. - /// - /// - /// Non-empty text displayed in the Inspector layout. - /// - public TextAttribute(string text) - { - ArgumentException.ThrowIfNullOrWhiteSpace(text); - this.text = text; - } - - /// - /// Gets the persistent Inspector text. - /// - public string text { get; } -} - -/// -/// Inserts vertical spacing before the annotated Inspector property. -/// -[Conditional("INNO_EDITOR")] -public sealed class SpaceAttribute : InspectorPresentationAttribute -{ - /// - /// Creates a spacing decorator. - /// - /// - /// Non-negative logical pixel height. - /// - public SpaceAttribute(float height = 8f) - { - ArgumentOutOfRangeException.ThrowIfNegative(height); - this.height = height; - } - - /// - /// Gets the logical pixel height. - /// - public float height { get; } -} - -/// -/// Provides hover help for one Inspector property label. -/// -[Conditional("INNO_EDITOR")] -public sealed class TooltipAttribute : InspectorPresentationAttribute -{ - /// - /// Creates property hover help. - /// - /// - /// Non-empty tooltip text. - /// - public TooltipAttribute(string text) - { - ArgumentException.ThrowIfNullOrWhiteSpace(text); - this.text = text; - } - - /// - /// Gets the tooltip text. - /// - public string text { get; } -} - -/// -/// Replaces the generated Inspector label for one property. -/// -[Conditional("INNO_EDITOR")] -public sealed class InspectorNameAttribute : InspectorPresentationAttribute -{ - /// - /// Creates a label override. - /// - /// - /// Non-empty visible label. - /// - public InspectorNameAttribute(string name) - { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - this.name = name; - } - - /// - /// Gets the visible label. - /// - public string name { get; } -} - -/// -/// Constrains a numeric Inspector control to an inclusive range. -/// -[Conditional("INNO_EDITOR")] -public sealed class RangeAttribute : InspectorPresentationAttribute -{ - /// - /// Creates an inclusive numeric range. - /// - /// - /// Inclusive lower bound. - /// - /// - /// Inclusive upper bound. - /// - public RangeAttribute( - double minimum, - double maximum - ) { - if (!double.IsFinite(minimum)) - { - throw new ArgumentOutOfRangeException(nameof(minimum)); - } - if (!double.IsFinite(maximum) || maximum < minimum) - { - throw new ArgumentOutOfRangeException(nameof(maximum)); - } - this.minimum = minimum; - this.maximum = maximum; - } - - /// - /// Gets the inclusive lower bound. - /// - public double minimum { get; } - - /// - /// Gets the inclusive upper bound. - /// - public double maximum { get; } -} - -/// -/// Makes an otherwise writable serialized property read-only in the Inspector. -/// -[Conditional("INNO_EDITOR")] -public sealed class InspectorReadOnlyAttribute : InspectorPresentationAttribute; - -/// -/// Defines the comparison used by conditional Inspector presentation. -/// -public enum InspectorCondition -{ - /// - /// Shows a value when it evaluates as true or non-empty. - /// - Truthy, - /// - /// Shows a value when it evaluates as false, null, or empty. - /// - Falsy, - /// - /// Compares the value with the supplied expected constant. - /// - Equal, - /// - /// Requires the value to differ from the supplied expected constant. - /// - NotEqual, - /// - /// Requires a null value. - /// - Null, - /// - /// Requires a non-null value. - /// - NotNull, - /// - /// Requires a reference-like value to expose an assigned resource. - /// - Assigned, - /// - /// Requires a reference-like value not to expose an assigned resource. - /// - NotAssigned -} - -/// -/// Shows the annotated Inspector property only when a sibling member satisfies a condition. -/// -[Conditional("INNO_EDITOR")] -public sealed class ShowIfAttribute : InspectorPresentationAttribute -{ - /// - /// Creates a truthiness condition. - /// - /// - /// Sibling field or property name. - /// - public ShowIfAttribute(string memberName) - : this(memberName, InspectorCondition.Truthy, null) {} - - /// - /// Creates an equality condition. - /// - /// - /// Sibling field or property name. - /// - /// - /// Compile-time value required for visibility. - /// - public ShowIfAttribute( - string memberName, - object? expectedValue - ) : this(memberName, InspectorCondition.Equal, expectedValue) {} - - /// - /// Creates a named condition that does not require an expected value. - /// - /// - /// Sibling field or property name. - /// - /// - /// Comparison applied to the sibling value. - /// - public ShowIfAttribute( - string memberName, - InspectorCondition condition - ) : this(memberName, condition, null) {} - - private ShowIfAttribute( - string memberName, - InspectorCondition condition, - object? expectedValue - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(memberName); - this.memberName = memberName; - this.condition = condition; - this.expectedValue = expectedValue; - } - - /// - /// Gets the sibling member name. - /// - public string memberName { get; } - - /// - /// Gets the comparison. - /// - public InspectorCondition condition { get; } - - /// - /// Gets the optional expected constant. - /// - public object? expectedValue { get; } -} - -/// -/// Hides the annotated Inspector property when a sibling member satisfies a condition. -/// -[Conditional("INNO_EDITOR")] -public sealed class HideIfAttribute : InspectorPresentationAttribute -{ - /// - /// Creates a truthiness condition. - /// - /// - /// Sibling field or property name. - /// - public HideIfAttribute(string memberName) - : this(memberName, InspectorCondition.Truthy, null) {} - - /// - /// Creates an equality condition. - /// - /// - /// Sibling field or property name. - /// - /// - /// Compile-time value that hides the property. - /// - public HideIfAttribute( - string memberName, - object? expectedValue - ) : this(memberName, InspectorCondition.Equal, expectedValue) {} - - /// - /// Creates a named condition that does not require an expected value. - /// - /// - /// Sibling field or property name. - /// - /// - /// Comparison applied to the sibling value. - /// - public HideIfAttribute( - string memberName, - InspectorCondition condition - ) : this(memberName, condition, null) {} - - private HideIfAttribute( - string memberName, - InspectorCondition condition, - object? expectedValue - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(memberName); - this.memberName = memberName; - this.condition = condition; - this.expectedValue = expectedValue; - } - - /// - /// Gets the sibling member name. - /// - public string memberName { get; } - - /// - /// Gets the comparison. - /// - public InspectorCondition condition { get; } - - /// - /// Gets the optional expected constant. - /// - public object? expectedValue { get; } -} - -/// -/// Selects the visual severity of an Inspector help message. -/// -public enum InspectorMessageType -{ - /// - /// Neutral explanatory information. - /// - Info, - /// - /// A non-blocking configuration warning. - /// - Warning, - /// - /// An invalid or unusable configuration. - /// - Error -} - -/// -/// Draws a wrapped explanatory message before the annotated Inspector property. -/// -[Conditional("INNO_EDITOR")] -public sealed class HelpBoxAttribute : InspectorPresentationAttribute -{ - /// - /// Creates an Inspector help message. - /// - /// - /// Non-empty message text. - /// - /// - /// Visual severity. - /// - public HelpBoxAttribute( - string text, - InspectorMessageType messageType = InspectorMessageType.Info - ) : this(text, messageType, string.Empty, InspectorCondition.Truthy, null) {} - - /// - /// Creates an Inspector help message shown when a sibling satisfies a named condition. - /// - /// - /// Non-empty message text. - /// - /// - /// Sibling field or property name. - /// - /// - /// Comparison applied to the sibling value. - /// - /// - /// Visual severity. - /// - public HelpBoxAttribute( - string text, - string conditionMember, - InspectorCondition condition, - InspectorMessageType messageType = InspectorMessageType.Info - ) : this(text, messageType, conditionMember, condition, null) {} - - /// - /// Creates an Inspector help message shown when a sibling equals a compile-time value. - /// - /// - /// Non-empty message text. - /// - /// - /// Sibling field or property name. - /// - /// - /// The expected value consumed by help box attribute; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// Visual severity. - /// - public HelpBoxAttribute( - string text, - string conditionMember, - object? expectedValue, - InspectorMessageType messageType = InspectorMessageType.Info - ) : this(text, messageType, conditionMember, InspectorCondition.Equal, expectedValue) {} - - private HelpBoxAttribute( - string text, - InspectorMessageType messageType, - string conditionMember, - InspectorCondition condition, - object? expectedValue - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(text); - this.text = text; - this.messageType = messageType; - this.conditionMember = conditionMember ?? string.Empty; - this.condition = condition; - this.expectedValue = expectedValue; - } - - /// - /// Gets the message text. - /// - public string text { get; } - - /// - /// Gets the visual severity. - /// - public InspectorMessageType messageType { get; } - - /// - /// Gets the optional sibling member controlling message visibility. - /// - public string conditionMember { get; } - - /// - /// Gets the optional sibling comparison. - /// - public InspectorCondition condition { get; } - - /// - /// Gets the optional expected constant. - /// - public object? expectedValue { get; } -} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorReadOnlyAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorReadOnlyAttribute.cs new file mode 100644 index 000000000..d48ae56b7 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/InspectorReadOnlyAttribute.cs @@ -0,0 +1,9 @@ +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Makes an otherwise writable serialized property read-only in the Inspector. +/// +[Conditional("INNO_EDITOR")] +public sealed class InspectorReadOnlyAttribute : InspectorPresentationAttribute; diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/RangeAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/RangeAttribute.cs new file mode 100644 index 000000000..e4fc014d1 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/RangeAttribute.cs @@ -0,0 +1,46 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Constrains a numeric Inspector control to an inclusive range. +/// +[Conditional("INNO_EDITOR")] +public sealed class RangeAttribute : InspectorPresentationAttribute +{ + /// + /// Creates an inclusive numeric range. + /// + /// + /// Inclusive lower bound. + /// + /// + /// Inclusive upper bound. + /// + public RangeAttribute( + double minimum, + double maximum + ) { + if (!double.IsFinite(minimum)) + { + throw new ArgumentOutOfRangeException(nameof(minimum)); + } + if (!double.IsFinite(maximum) || maximum < minimum) + { + throw new ArgumentOutOfRangeException(nameof(maximum)); + } + this.minimum = minimum; + this.maximum = maximum; + } + + /// + /// Gets the inclusive lower bound. + /// + public double minimum { get; } + + /// + /// Gets the inclusive upper bound. + /// + public double maximum { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/ShowIfAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/ShowIfAttribute.cs new file mode 100644 index 000000000..285ab796b --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/ShowIfAttribute.cs @@ -0,0 +1,74 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Shows the annotated Inspector property only when a sibling member satisfies a condition. +/// +[Conditional("INNO_EDITOR")] +public sealed class ShowIfAttribute : InspectorPresentationAttribute +{ + /// + /// Creates a truthiness condition. + /// + /// + /// Sibling field or property name. + /// + public ShowIfAttribute(string memberName) + : this(memberName, InspectorCondition.Truthy, null) {} + + /// + /// Creates an equality condition. + /// + /// + /// Sibling field or property name. + /// + /// + /// Compile-time value required for visibility. + /// + public ShowIfAttribute( + string memberName, + object? expectedValue + ) : this(memberName, InspectorCondition.Equal, expectedValue) {} + + /// + /// Creates a named condition that does not require an expected value. + /// + /// + /// Sibling field or property name. + /// + /// + /// Comparison applied to the sibling value. + /// + public ShowIfAttribute( + string memberName, + InspectorCondition condition + ) : this(memberName, condition, null) {} + + private ShowIfAttribute( + string memberName, + InspectorCondition condition, + object? expectedValue + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(memberName); + this.memberName = memberName; + this.condition = condition; + this.expectedValue = expectedValue; + } + + /// + /// Gets the sibling member name. + /// + public string memberName { get; } + + /// + /// Gets the comparison. + /// + public InspectorCondition condition { get; } + + /// + /// Gets the optional expected constant. + /// + public object? expectedValue { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/SpaceAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/SpaceAttribute.cs new file mode 100644 index 000000000..b1e94b8c7 --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/SpaceAttribute.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Inserts vertical spacing before the annotated Inspector property. +/// +[Conditional("INNO_EDITOR")] +public sealed class SpaceAttribute : InspectorPresentationAttribute +{ + /// + /// Creates a spacing decorator. + /// + /// + /// Non-negative logical pixel height. + /// + public SpaceAttribute(float height = 8f) + { + ArgumentOutOfRangeException.ThrowIfNegative(height); + this.height = height; + } + + /// + /// Gets the logical pixel height. + /// + public float height { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/TextAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/TextAttribute.cs new file mode 100644 index 000000000..99e36bebd --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/TextAttribute.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Draws persistent wrapped explanatory text before the annotated Inspector property. +/// +[Conditional("INNO_EDITOR")] +public sealed class TextAttribute : InspectorPresentationAttribute +{ + /// + /// Creates persistent Inspector text. + /// + /// + /// Non-empty text displayed in the Inspector layout. + /// + public TextAttribute(string text) + { + ArgumentException.ThrowIfNullOrWhiteSpace(text); + this.text = text; + } + + /// + /// Gets the persistent Inspector text. + /// + public string text { get; } +} diff --git a/src/composition/editor/contracts/Inno.Editor.Annotations/TooltipAttribute.cs b/src/composition/editor/contracts/Inno.Editor.Annotations/TooltipAttribute.cs new file mode 100644 index 000000000..3f1cc3b6f --- /dev/null +++ b/src/composition/editor/contracts/Inno.Editor.Annotations/TooltipAttribute.cs @@ -0,0 +1,28 @@ +using System; +using System.Diagnostics; + +namespace Inno.Editor.Annotations; + +/// +/// Provides hover help for one Inspector property label. +/// +[Conditional("INNO_EDITOR")] +public sealed class TooltipAttribute : InspectorPresentationAttribute +{ + /// + /// Creates property hover help. + /// + /// + /// Non-empty tooltip text. + /// + public TooltipAttribute(string text) + { + ArgumentException.ThrowIfNullOrWhiteSpace(text); + this.text = text; + } + + /// + /// Gets the tooltip text. + /// + public string text { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationContext.cs b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationContext.cs new file mode 100644 index 000000000..a1455237c --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationContext.cs @@ -0,0 +1,42 @@ +using System; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Scripting.Api; + +namespace Inno.Editor.Assets; + +/// +/// Provides source encoding services to one detached Asset creation template invocation. +/// +public sealed class AssetCreationContext +{ + private readonly AssetSourceStore m_sources; + + /// + /// Creates a context over the source serializer owned by the active Asset pipeline. + /// + /// + /// Source serializer carrying the active reference context. + /// + [ScriptingApiIgnore] + public AssetCreationContext(AssetSourceStore sources) + { + ArgumentNullException.ThrowIfNull(sources); + m_sources = sources; + } + + /// + /// Encodes an Asset value through the current native structured source serializer. + /// + /// + /// Detached Asset value to encode. + /// + /// + /// Complete native source bytes, including the concrete serialized type identity. + /// + public byte[] EncodeNative(AssetObject asset) + { + ArgumentNullException.ThrowIfNull(asset); + return m_sources.Encode(asset); + } +} diff --git a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationMenuAttribute.cs b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationMenuAttribute.cs new file mode 100644 index 000000000..a41f300f5 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationMenuAttribute.cs @@ -0,0 +1,116 @@ +using System; +using Inno.Assets; + +namespace Inno.Editor.Assets; + +/// +/// Declares the source name, extension, and menu placement that cannot be inferred from an +/// type alone. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AssetCreationMenuAttribute : Attribute +{ + /// + /// Creates one asset creation menu declaration. + /// + /// + /// Globally stable template identifier. + /// + /// + /// Slash-delimited path below the File Browser Create menu. + /// + /// + /// Native source extension, including its leading dot. + /// + /// + /// Default source name without an extension or numeric suffix. + /// + /// + /// Stable order of the top-level category below Create. + /// + /// + /// Stable order of the leaf within its immediate category. + /// + /// + /// Whether the top-level category starts after a separator. + /// + /// + /// Thrown when an identifier, path, source name, or native extension is invalid. + /// + public AssetCreationMenuAttribute( + string id, + string menuPath, + string extension, + string defaultName, + int groupOrder = 0, + int itemOrder = 0, + bool separatorBeforeGroup = false + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentException.ThrowIfNullOrWhiteSpace(menuPath); + ArgumentException.ThrowIfNullOrWhiteSpace(extension); + ArgumentException.ThrowIfNullOrWhiteSpace(defaultName); + if (extension.Length == 0 || extension[0] != '.' + || extension.IndexOfAny(['/', '\\']) >= 0 + ) { + throw new ArgumentException( + "A native source extension beginning with a dot is required.", + nameof(extension) + ); + } + + string normalizedPath = menuPath.Replace('\\', '/').Trim('/'); + if (normalizedPath.Length == 0 + || Array.Exists(normalizedPath.Split('/'), static segment => string.IsNullOrWhiteSpace(segment)) + ) { + throw new ArgumentException("A valid menu path is required.", nameof(menuPath)); + } + if (defaultName.IndexOfAny(['/', '\\']) >= 0) + { + throw new ArgumentException("The default name cannot contain a path separator.", nameof(defaultName)); + } + + this.id = id; + this.menuPath = normalizedPath; + this.extension = extension.ToLowerInvariant(); + this.defaultName = defaultName.Trim(); + this.groupOrder = groupOrder; + this.itemOrder = itemOrder; + this.separatorBeforeGroup = separatorBeforeGroup; + } + + /// + /// Gets the globally stable template identifier. + /// + public string id { get; } + + /// + /// Gets the slash-delimited path below the File Browser Create menu. + /// + public string menuPath { get; } + + /// + /// Gets the native source extension, including its leading dot. + /// + public string extension { get; } + + /// + /// Gets the default source name without an extension or numeric suffix. + /// + public string defaultName { get; } + + /// + /// Gets the stable order of the top-level category below Create. + /// + public int groupOrder { get; } + + /// + /// Gets the stable order of the leaf within its immediate category. + /// + public int itemOrder { get; } + + /// + /// Gets whether the top-level category starts after a separator. + /// + public bool separatorBeforeGroup { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs index 394084c93..407a25d51 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Creation/AssetCreationTemplate.cs @@ -1,122 +1,8 @@ using System; using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Scripting.Api; namespace Inno.Editor.Assets; -/// -/// Declares the source name, extension, and menu placement that cannot be inferred from an -/// type alone. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AssetCreationMenuAttribute : Attribute -{ - /// - /// Creates one asset creation menu declaration. - /// - /// - /// Globally stable template identifier. - /// - /// - /// Slash-delimited path below the File Browser Create menu. - /// - /// - /// Native source extension, including its leading dot. - /// - /// - /// Default source name without an extension or numeric suffix. - /// - /// - /// Stable order of the top-level category below Create. - /// - /// - /// Stable order of the leaf within its immediate category. - /// - /// - /// Whether the top-level category starts after a separator. - /// - /// - /// Thrown when an identifier, path, source name, or native extension is invalid. - /// - public AssetCreationMenuAttribute( - string id, - string menuPath, - string extension, - string defaultName, - int groupOrder = 0, - int itemOrder = 0, - bool separatorBeforeGroup = false - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentException.ThrowIfNullOrWhiteSpace(menuPath); - ArgumentException.ThrowIfNullOrWhiteSpace(extension); - ArgumentException.ThrowIfNullOrWhiteSpace(defaultName); - if (extension.Length == 0 || extension[0] != '.' - || extension.IndexOfAny(['/', '\\']) >= 0 - ) { - throw new ArgumentException( - "A native source extension beginning with a dot is required.", - nameof(extension) - ); - } - - string normalizedPath = menuPath.Replace('\\', '/').Trim('/'); - if (normalizedPath.Length == 0 - || Array.Exists(normalizedPath.Split('/'), static segment => string.IsNullOrWhiteSpace(segment)) - ) { - throw new ArgumentException("A valid menu path is required.", nameof(menuPath)); - } - if (defaultName.IndexOfAny(['/', '\\']) >= 0) - { - throw new ArgumentException("The default name cannot contain a path separator.", nameof(defaultName)); - } - - this.id = id; - this.menuPath = normalizedPath; - this.extension = extension.ToLowerInvariant(); - this.defaultName = defaultName.Trim(); - this.groupOrder = groupOrder; - this.itemOrder = itemOrder; - this.separatorBeforeGroup = separatorBeforeGroup; - } - - /// - /// Gets the globally stable template identifier. - /// - public string id { get; } - - /// - /// Gets the slash-delimited path below the File Browser Create menu. - /// - public string menuPath { get; } - - /// - /// Gets the native source extension, including its leading dot. - /// - public string extension { get; } - - /// - /// Gets the default source name without an extension or numeric suffix. - /// - public string defaultName { get; } - - /// - /// Gets the stable order of the top-level category below Create. - /// - public int groupOrder { get; } - - /// - /// Gets the stable order of the leaf within its immediate category. - /// - public int itemOrder { get; } - - /// - /// Gets whether the top-level category starts after a separator. - /// - public bool separatorBeforeGroup { get; } -} - /// /// Produces the detached initial value for one authorable native asset source. /// @@ -166,42 +52,6 @@ AssetObject asset } } -/// -/// Provides source encoding services to one detached Asset creation template invocation. -/// -public sealed class AssetCreationContext -{ - private readonly AssetSourceStore m_sources; - - /// - /// Creates a context over the source serializer owned by the active Asset pipeline. - /// - /// - /// Source serializer carrying the active reference context. - /// - [ScriptingApiIgnore] - public AssetCreationContext(AssetSourceStore sources) - { - ArgumentNullException.ThrowIfNull(sources); - m_sources = sources; - } - - /// - /// Encodes an Asset value through the current native structured source serializer. - /// - /// - /// Detached Asset value to encode. - /// - /// - /// Complete native source bytes, including the concrete serialized type identity. - /// - public byte[] EncodeNative(AssetObject asset) - { - ArgumentNullException.ThrowIfNull(asset); - return m_sources.Encode(asset); - } -} - /// /// Creates a default-constructed native source for an authorable asset type. /// diff --git a/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs index 9bdf0e066..24185c17f 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsEdits.cs @@ -192,71 +192,3 @@ private sealed class ChangeData : ISerializable internal byte[] after { get; set; } = []; } } - -[EditorHistoryHandler(AssetImportSettingsEdits.C_HISTORY)] -internal sealed class AssetImportSettingsHistory(AssetImportSettingsEdits edits) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - edits.Validate(change, direction); - return EditorHistoryAvailability.Available(); - } - catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && RetirementPendingException.Find(failure) is null) - { - return EditorHistoryAvailability.Unavailable(failure.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - edits.ApplyHistory(change, direction); - return EditorHistoryResult.Success(); - } - catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) - && RetirementPendingException.Find(failure) is null) - { - return EditorHistoryResult.Failure(failure.Message); - } - } -} diff --git a/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsHistory.cs b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsHistory.cs new file mode 100644 index 000000000..0f3c2e7c7 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Assets/ImportSettings/AssetImportSettingsHistory.cs @@ -0,0 +1,74 @@ +using System; +using System.IO; +using Inno.Core.Execution; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Assets; + +[EditorHistoryHandler(AssetImportSettingsEdits.C_HISTORY)] +internal sealed class AssetImportSettingsHistory(AssetImportSettingsEdits edits) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + edits.Validate(change, direction); + return EditorHistoryAvailability.Available(); + } + catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) + && RetirementPendingException.Find(failure) is null) + { + return EditorHistoryAvailability.Unavailable(failure.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + edits.ApplyHistory(change, direction); + return EditorHistoryResult.Success(); + } + catch (Exception failure) when ((failure is IOException or InvalidOperationException or ArgumentException or FormatException) + && RetirementPendingException.Find(failure) is null) + { + return EditorHistoryResult.Failure(failure.Message); + } + } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs index aefff44e3..a5edd7406 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderCompilation.cs @@ -7,65 +7,6 @@ namespace Inno.Editor.Rendering; -/// -/// Identifies native compilation state independently of document persistence. -/// -public enum EditorShaderCompilationState -{ - /// - /// The latest semantic candidate is being compiled. - /// - Compiling, - /// - /// The latest semantic candidate compiled successfully. - /// - Succeeded, - /// - /// The latest semantic candidate failed. - /// - Failed -} - -/// -/// Contains detached compiler state without retaining assets, tasks or extension instances. -/// -/// -/// Latest requested semantic candidate state. -/// -/// -/// Whether rendering still uses a previous successful candidate. -/// -/// -/// Immutable latest completed compiler diagnostics. -/// -public sealed record EditorShaderCompilationSnapshot( - EditorShaderCompilationState state, - bool usingLastGood, - IReadOnlyList diagnostics -); - -/// -/// Contains a preview-only immutable candidate, never registered as a canonical asset artifact. -/// -/// -/// Latest draft compilation state. -/// -/// -/// Whether the preview artifact belongs to an earlier successful draft. -/// -/// -/// Latest detached preview diagnostics, separate from project diagnostics. -/// -/// -/// Preview-only complete shader candidate, or null before the first success. -/// -public sealed record EditorShaderDraftCompilationSnapshot( - EditorShaderCompilationState state, - bool usingLastGood, - IReadOnlyList diagnostics, - RenderShaderArtifact? artifact -); - /// /// Schedules Editor shader compilation for the active device without exposing native handles to authoring panels. /// @@ -224,3 +165,62 @@ public void ReleaseDraft(Guid documentID) m_provider.ReleaseDraft(documentID); } } + +/// +/// Identifies native compilation state independently of document persistence. +/// +public enum EditorShaderCompilationState +{ + /// + /// The latest semantic candidate is being compiled. + /// + Compiling, + /// + /// The latest semantic candidate compiled successfully. + /// + Succeeded, + /// + /// The latest semantic candidate failed. + /// + Failed +} + +/// +/// Contains detached compiler state without retaining assets, tasks or extension instances. +/// +/// +/// Latest requested semantic candidate state. +/// +/// +/// Whether rendering still uses a previous successful candidate. +/// +/// +/// Immutable latest completed compiler diagnostics. +/// +public sealed record EditorShaderCompilationSnapshot( + EditorShaderCompilationState state, + bool usingLastGood, + IReadOnlyList diagnostics +); + +/// +/// Contains a preview-only immutable candidate, never registered as a canonical asset artifact. +/// +/// +/// Latest draft compilation state. +/// +/// +/// Whether the preview artifact belongs to an earlier successful draft. +/// +/// +/// Latest detached preview diagnostics, separate from project diagnostics. +/// +/// +/// Preview-only complete shader candidate, or null before the first success. +/// +public sealed record EditorShaderDraftCompilationSnapshot( + EditorShaderCompilationState state, + bool usingLastGood, + IReadOnlyList diagnostics, + RenderShaderArtifact? artifact +); diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderArtifactValidation.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/IEditorShaderArtifactValidator.cs similarity index 100% rename from src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderArtifactValidation.cs rename to src/composition/editor/features/Inno.Editor.Rendering/Compilation/IEditorShaderArtifactValidator.cs index 81cf35eab..04b224e4f 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorShaderArtifactValidation.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/IEditorShaderArtifactValidator.cs @@ -5,20 +5,6 @@ namespace Inno.Editor.Rendering; -/// -/// Contains active-device validation state for one immutable Editor shader candidate. -/// -/// -/// Pending, successful, or failed validation state. -/// -/// -/// Detached device validation diagnostics. -/// -public sealed record EditorShaderArtifactValidationSnapshot( - EditorShaderCompilationState state, - IReadOnlyList diagnostics -); - /// /// Queues immutable shader candidates for validation at the active device's next frame safety point. /// @@ -58,3 +44,17 @@ RenderShaderArtifact artifact /// void Release(Guid documentID); } + +/// +/// Contains active-device validation state for one immutable Editor shader candidate. +/// +/// +/// Pending, successful, or failed validation state. +/// +/// +/// Detached device validation diagnostics. +/// +public sealed record EditorShaderArtifactValidationSnapshot( + EditorShaderCompilationState state, + IReadOnlyList diagnostics +); diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoContext.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoContext.cs new file mode 100644 index 000000000..4afccf755 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoContext.cs @@ -0,0 +1,59 @@ +using System; +using Inno.Core.Identity; +using Inno.References; + +namespace Inno.Editor.Rendering; + +/// +/// Provides scene content and selection for transient Editor gizmos. +/// +public sealed class EditorGizmoContext +{ + /// + /// Creates a frame-scoped gizmo request. + /// + /// + /// The scenes presented by the Scene viewport. + /// + /// + /// The selected live object, when available. + /// + /// + /// The Scene viewport width. + /// + /// + /// The Scene viewport height. + /// + public EditorGizmoContext( + ContentReadScope content, + RuntimeIdentity? selected, + int pixelWidth, + int pixelHeight + ) { + ArgumentNullException.ThrowIfNull(content); + this.content = content; + this.selected = selected; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; + } + + /// + /// Gets the scene roots visible in this Editor viewport. + /// + public ContentReadScope content { get; } + + /// + /// Gets the transient selected identity. + /// + public RuntimeIdentity? selected { get; } + + /// + /// Gets the viewport width in physical pixels. + /// + public int pixelWidth { get; } + + /// + /// Gets the viewport height in physical pixels. + /// + public int pixelHeight { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoFrame.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoFrame.cs new file mode 100644 index 000000000..86dee56d9 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoFrame.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Identity; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Holds the transient gizmo primitives for one Scene viewport frame. +/// +public sealed class EditorGizmoFrame : IEditorGizmoSink +{ + private readonly List m_icons = []; + private readonly List m_lines = []; + + /// + /// Gets the ordered selectable icons. + /// + public IReadOnlyList icons => m_icons; + + /// + /// Gets the ordered non-interactive lines. + /// + public IReadOnlyList lines => m_lines; + + /// + /// Appends a selectable scene icon to the current gizmo frame. + /// + /// + /// The object that owns the resulting lifetime and state. + /// + /// + /// The position consumed by icon; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The stable icon identity resolved by the Scene View. + /// + public void Icon( + Identity owner, + Vector3 position, + string iconID + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(iconID); + m_icons.Add(new EditorGizmoIcon(owner, position, iconID)); + } + + /// + /// Appends a world space line to the current gizmo frame. + /// + /// + /// The start consumed by line; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The end consumed by line; ownership remains with the caller unless explicitly stated otherwise. + /// + public void Line( + Vector3 start, + Vector3 end + ) => m_lines.Add(new EditorGizmoLine(start, end)); +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs index 147ff79cb..95ef0ac5b 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProvider.cs @@ -1,103 +1,8 @@ -using System; -using System.Collections.Generic; using Inno.Core.Identity; using Inno.Core.Mathematics; -using Inno.References; namespace Inno.Editor.Rendering; -/// -/// Provides scene content and selection for transient Editor gizmos. -/// -public sealed class EditorGizmoContext -{ - /// - /// Creates a frame-scoped gizmo request. - /// - /// - /// The scenes presented by the Scene viewport. - /// - /// - /// The selected live object, when available. - /// - /// - /// The Scene viewport width. - /// - /// - /// The Scene viewport height. - /// - public EditorGizmoContext( - ContentReadScope content, - RuntimeIdentity? selected, - int pixelWidth, - int pixelHeight - ) { - ArgumentNullException.ThrowIfNull(content); - this.content = content; - this.selected = selected; - this.pixelWidth = pixelWidth; - this.pixelHeight = pixelHeight; - } - - /// - /// Gets the scene roots visible in this Editor viewport. - /// - public ContentReadScope content { get; } - - /// - /// Gets the transient selected identity. - /// - public RuntimeIdentity? selected { get; } - - /// - /// Gets the viewport width in physical pixels. - /// - public int pixelWidth { get; } - - /// - /// Gets the viewport height in physical pixels. - /// - public int pixelHeight { get; } -} - -/// -/// Receives transient world-space gizmo geometry from independent Editor extensions. -/// -public interface IEditorGizmoSink -{ - /// - /// Adds a visible, selectable icon at an object's world position. - /// - /// - /// The scene object selected when the icon is clicked. - /// - /// - /// The icon position in world space. - /// - /// - /// A stable semantic icon ID. Unknown IDs use the generic scene icon. - /// - void Icon( - Identity owner, - Vector3 position, - string iconID - ); - - /// - /// Adds a non-interactive world-space line, normally for selected bounds. - /// - /// - /// The first world-space endpoint. - /// - /// - /// The second world-space endpoint. - /// - void Line( - Vector3 start, - Vector3 end - ); -} - /// /// Contributes Editor-only icons and bounds without modifying a rendering model. /// @@ -118,30 +23,6 @@ IEditorGizmoSink sink ); } -/// -/// Marks one reloadable Editor gizmo provider. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class EditorGizmoProviderExtensionAttribute : Attribute -{ - /// - /// Creates a provider declaration with a stable identifier. - /// - /// - /// The globally unique provider identifier. - /// - public EditorGizmoProviderExtensionAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - } - - /// - /// Gets the stable provider identifier. - /// - public string id { get; } -} - /// /// One selectable Editor icon. /// @@ -173,57 +54,3 @@ public readonly record struct EditorGizmoLine( Vector3 start, Vector3 end ); - -/// -/// Holds the transient gizmo primitives for one Scene viewport frame. -/// -public sealed class EditorGizmoFrame : IEditorGizmoSink -{ - private readonly List m_icons = []; - private readonly List m_lines = []; - - /// - /// Gets the ordered selectable icons. - /// - public IReadOnlyList icons => m_icons; - - /// - /// Gets the ordered non-interactive lines. - /// - public IReadOnlyList lines => m_lines; - - /// - /// Appends a selectable scene icon to the current gizmo frame. - /// - /// - /// The object that owns the resulting lifetime and state. - /// - /// - /// The position consumed by icon; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The stable icon identity resolved by the Scene View. - /// - public void Icon( - Identity owner, - Vector3 position, - string iconID - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(iconID); - m_icons.Add(new EditorGizmoIcon(owner, position, iconID)); - } - - /// - /// Appends a world space line to the current gizmo frame. - /// - /// - /// The start consumed by line; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The end consumed by line; ownership remains with the caller unless explicitly stated otherwise. - /// - public void Line( - Vector3 start, - Vector3 end - ) => m_lines.Add(new EditorGizmoLine(start, end)); -} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderExtensionAttribute.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderExtensionAttribute.cs new file mode 100644 index 000000000..f38d3bc05 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorGizmoProviderExtensionAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Marks one reloadable Editor gizmo provider. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class EditorGizmoProviderExtensionAttribute : Attribute +{ + /// + /// Creates a provider declaration with a stable identifier. + /// + /// + /// The globally unique provider identifier. + /// + public EditorGizmoProviderExtensionAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + } + + /// + /// Gets the stable provider identifier. + /// + public string id { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewHandle.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewHandle.cs new file mode 100644 index 000000000..13af0c0b1 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewHandle.cs @@ -0,0 +1,67 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Identifies one preview texture owned by a specific rendering-device generation. +/// +public readonly record struct EditorPreviewHandle +{ + /// + /// Creates one generation-scoped preview handle. + /// + /// + /// Non-zero preview identity. + /// + /// + /// Non-zero rendering-device generation. + /// + /// + /// Positive source width. + /// + /// + /// Positive source height. + /// + public EditorPreviewHandle( + ulong value, + uint deviceGeneration, + int pixelWidth, + int pixelHeight + ) { + if (value == 0 || deviceGeneration == 0) + { + throw new ArgumentOutOfRangeException(nameof(value), "Preview identity and device generation must be non-zero."); + } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); + this.value = value; + this.deviceGeneration = deviceGeneration; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; + } + + /// + /// Gets the opaque preview identity. + /// + public ulong value { get; } + + /// + /// Gets the rendering-device generation that owns this handle. + /// + public uint deviceGeneration { get; } + + /// + /// Gets source width in pixels. + /// + public int pixelWidth { get; } + + /// + /// Gets source height in pixels. + /// + public int pixelHeight { get; } + + /// + /// Gets whether this handle identifies a usable generation-scoped preview. + /// + public bool isValid => value != 0 && deviceGeneration != 0 && pixelWidth > 0 && pixelHeight > 0; +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportComposition.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportComposition.cs new file mode 100644 index 000000000..60d6730ef --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportComposition.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Rendering; + +namespace Inno.Editor.Rendering; + +/// +/// Describes a complete ordered set of rendering-model layers targeting one Editor viewport. +/// +public sealed class EditorViewportComposition +{ + private readonly IReadOnlyList m_layers; + + /// + /// Creates an immutable viewport composition. + /// + /// + /// Stable panel viewport identity. + /// + /// + /// Positive target width. + /// + /// + /// Positive target height. + /// + /// + /// Shared presentation target format required by every layer. + /// + /// + /// Ordered non-empty rendering-model layer collection. + /// + public EditorViewportComposition( + string viewportID, + int pixelWidth, + int pixelHeight, + RenderTextureFormat targetFormat, + IEnumerable layers + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); + ArgumentNullException.ThrowIfNull(layers); + EditorViewportLayer[] materializedLayers = layers.ToArray(); + if (materializedLayers.Length == 0) + { + throw new ArgumentException("A viewport composition requires at least one model layer.", nameof(layers)); + } + if (materializedLayers.Any(static layer => layer is null)) + { + throw new ArgumentException("A viewport composition cannot contain null model layers.", nameof(layers)); + } + if (materializedLayers.Select(static layer => layer.contributorID).Distinct(StringComparer.Ordinal).Count() + != materializedLayers.Length + ) { + throw new ArgumentException("Viewport contributor identities must be unique.", nameof(layers)); + } + m_layers = Array.AsReadOnly( + materializedLayers + .OrderBy(static layer => layer.order) + .ThenBy(static layer => layer.contributorID, StringComparer.Ordinal) + .ToArray() + ); + this.viewportID = viewportID; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; + this.targetFormat = targetFormat; + } + + /// + /// Gets the stable viewport identity. + /// + public string viewportID { get; } + + /// + /// Gets the target width. + /// + public int pixelWidth { get; } + + /// + /// Gets the target height. + /// + public int pixelHeight { get; } + + /// + /// Gets the shared presentation target format. + /// + public RenderTextureFormat targetFormat { get; } + + /// + /// Gets the ordered rendering-model layers. + /// + public IReadOnlyList layers => m_layers; +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContext.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContext.cs new file mode 100644 index 000000000..2934ed803 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContext.cs @@ -0,0 +1,120 @@ +using System; +using Inno.Editor.Core; +using Inno.Editor.Interactions; +using Inno.References; +using Inno.Rendering.Runtime; + +namespace Inno.Editor.Rendering; + +/// +/// Supplies frame-only Editor interaction and output dimensions to a contributor. +/// +public sealed class EditorViewportContext +{ + internal EditorViewportContext( + EditorContext editor, + EditorInteractions interactions, + EditorViewportKindID kind, + string viewportID, + int pixelWidth, + int pixelHeight, + EditorViewportNavigationState navigation, + ContentReadScope content, + EditorViewportPresentation presentation, + IViewContentCollector viewContent, + ulong frameIndex, + RenderOutputInput input + ) { + this.editor = editor; + this.interactions = interactions; + this.kind = kind; + this.viewportID = viewportID; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; + this.navigation = navigation; + this.content = content; + this.presentation = presentation; + this.viewContent = viewContent; + this.frameIndex = frameIndex; + this.input = input; + } + + /// + /// Gets the current Editor context. + /// + public EditorContext editor { get; } + + /// + /// Gets the shared Editor interaction and selection service. + /// + public EditorInteractions interactions { get; } + + /// + /// Gets the open viewport purpose. + /// + public EditorViewportKindID kind { get; } + + /// + /// Gets the stable panel viewport identity. + /// + public string viewportID { get; } + + /// + /// Gets target width in physical pixels. + /// + public int pixelWidth { get; } + + /// + /// Gets target height in physical pixels. + /// + public int pixelHeight { get; } + + /// + /// Gets host-owned neutral navigation state that the selected controller can map to its camera model. + /// + public EditorViewportNavigationState navigation { get; } + + /// + /// Gets the explicit ordered host content visible to this viewport. + /// + public ContentReadScope content { get; } + + /// + /// Gets host-selected presentation preferences for this viewport. + /// + public EditorViewportPresentation presentation { get; } + + /// + /// Gets the active generation's model-independent world-content collector. + /// + public IViewContentCollector viewContent { get; } + + /// + /// Gets the frame index shared by all Editor views in this output frame. + /// + public ulong frameIndex { get; } + + /// + /// Gets input located in this viewport's physical pixels. + /// + public RenderOutputInput input { get; } + + internal EditorViewportContext ForLayer(RenderOutputLayer layer) + { + ArgumentNullException.ThrowIfNull(layer); + return new EditorViewportContext( + editor, + interactions, + kind, + viewportID, + pixelWidth, + pixelHeight, + navigation, + content, + presentation, + new SelectedViewContentCollector(viewContent, layer.sourceIDs), + frameIndex, + input + ); + } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContribution.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContribution.cs new file mode 100644 index 000000000..efc5186c5 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContribution.cs @@ -0,0 +1,60 @@ +using System; +using Inno.Rendering; +using Inno.Rendering.Assets; +using Inno.Rendering.Runtime; + +namespace Inno.Editor.Rendering; + +/// +/// Returns one rendering-model contribution without exposing a GPU backend. +/// +public sealed class EditorViewportContribution +{ + /// + /// Creates a viewport model contribution. + /// + /// + /// Pipeline-defined frame-only data. + /// + /// + /// Contributor-selected pipeline, or null for the project default. + /// + /// + /// Presentation target format expected by the pipeline. + /// + /// + /// Optional exact view/projection contract for host-owned transform manipulation tools. + /// + public EditorViewportContribution( + RenderFrameData data, + RenderPipelineAsset? pipeline = null, + RenderTextureFormat targetFormat = RenderTextureFormat.RGBA8Srgb, + EditorViewportManipulationSpace? manipulationSpace = null + ) { + ArgumentNullException.ThrowIfNull(data); + this.data = data; + this.pipeline = pipeline; + this.targetFormat = targetFormat; + this.manipulationSpace = manipulationSpace; + } + + /// + /// Gets pipeline-defined frame-only data. + /// + public RenderFrameData data { get; } + + /// + /// Gets the selected pipeline, or null for the project default. + /// + public RenderPipelineAsset? pipeline { get; } + + /// + /// Gets the presentation target format expected by the pipeline. + /// + public RenderTextureFormat targetFormat { get; } + + /// + /// Gets the optional exact view/projection contract used by host-owned transform manipulation tools. + /// + public EditorViewportManipulationSpace? manipulationSpace { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs index e61ec7e57..a8fd580c9 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributor.cs @@ -1,432 +1,5 @@ -using System; -using Inno.Core.Mathematics; -using Inno.Editor.Core; -using Inno.Editor.Interactions; -using Inno.References; -using Inno.Rendering; -using Inno.Rendering.Assets; -using Inno.Rendering.Runtime; - namespace Inno.Editor.Rendering; -/// -/// Identifies one open Editor viewport purpose without prescribing rendering semantics. -/// -public readonly record struct EditorViewportKindID -{ - /// - /// Creates a stable viewport purpose identifier. - /// - /// - /// Globally stable viewport purpose. - /// - public EditorViewportKindID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value.Trim(); - } - - /// - /// Gets the stable viewport purpose. - /// - public string value { get; } - - /// - /// Gets whether this identifier is usable. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value ?? string.Empty; -} - -/// -/// Marks a reloadable rendering-model contributor for one Editor viewport purpose. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class EditorViewportContributorExtensionAttribute : Attribute -{ - /// - /// Creates a viewport contributor declaration. - /// - /// - /// Globally stable contributor identity. - /// - /// - /// Open viewport purpose handled by the contributor. - /// - /// - /// Ascending model-composition order within the viewport. - /// - /// - /// Priority used to select the contributor that owns navigation, tools, and pointer interaction. - /// - public EditorViewportContributorExtensionAttribute( - string id, - string kind, - int order = 0, - int controllerPriority = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentException.ThrowIfNullOrWhiteSpace(kind); - this.id = id.Trim(); - this.kind = new EditorViewportKindID(kind); - this.order = order; - this.controllerPriority = controllerPriority; - } - - /// - /// Gets the globally stable contributor identity. - /// - public string id { get; } - - /// - /// Gets the open viewport purpose handled by the contributor. - /// - public EditorViewportKindID kind { get; } - - /// - /// Gets ascending model-composition order. - /// - public int order { get; } - - /// - /// Gets the priority used to select the viewport interaction controller. - /// - public int controllerPriority { get; } -} - -/// -/// Supplies frame-only Editor interaction and output dimensions to a contributor. -/// -public sealed class EditorViewportContext -{ - internal EditorViewportContext( - EditorContext editor, - EditorInteractions interactions, - EditorViewportKindID kind, - string viewportID, - int pixelWidth, - int pixelHeight, - EditorViewportNavigationState navigation, - ContentReadScope content, - EditorViewportPresentation presentation, - IViewContentCollector viewContent, - ulong frameIndex, - RenderOutputInput input - ) { - this.editor = editor; - this.interactions = interactions; - this.kind = kind; - this.viewportID = viewportID; - this.pixelWidth = pixelWidth; - this.pixelHeight = pixelHeight; - this.navigation = navigation; - this.content = content; - this.presentation = presentation; - this.viewContent = viewContent; - this.frameIndex = frameIndex; - this.input = input; - } - - /// - /// Gets the current Editor context. - /// - public EditorContext editor { get; } - - /// - /// Gets the shared Editor interaction and selection service. - /// - public EditorInteractions interactions { get; } - - /// - /// Gets the open viewport purpose. - /// - public EditorViewportKindID kind { get; } - - /// - /// Gets the stable panel viewport identity. - /// - public string viewportID { get; } - - /// - /// Gets target width in physical pixels. - /// - public int pixelWidth { get; } - - /// - /// Gets target height in physical pixels. - /// - public int pixelHeight { get; } - - /// - /// Gets host-owned neutral navigation state that the selected controller can map to its camera model. - /// - public EditorViewportNavigationState navigation { get; } - - /// - /// Gets the explicit ordered host content visible to this viewport. - /// - public ContentReadScope content { get; } - - /// - /// Gets host-selected presentation preferences for this viewport. - /// - public EditorViewportPresentation presentation { get; } - - /// - /// Gets the active generation's model-independent world-content collector. - /// - public IViewContentCollector viewContent { get; } - - /// - /// Gets the frame index shared by all Editor views in this output frame. - /// - public ulong frameIndex { get; } - - /// - /// Gets input located in this viewport's physical pixels. - /// - public RenderOutputInput input { get; } - - internal EditorViewportContext ForLayer(RenderOutputLayer layer) - { - ArgumentNullException.ThrowIfNull(layer); - return new EditorViewportContext( - editor, - interactions, - kind, - viewportID, - pixelWidth, - pixelHeight, - navigation, - content, - presentation, - new SelectedViewContentCollector(viewContent, layer.sourceIDs), - frameIndex, - input - ); - } -} - -/// -/// Describes host-selected presentation preferences without prescribing rendering behavior. -/// -public readonly record struct EditorViewportPresentation -{ - /// - /// Creates presentation preferences for one Editor viewport. - /// - /// - /// Linear clear color preferred by the host panel. - /// - /// - /// Physical render pixels per logical presentation unit. - /// - public EditorViewportPresentation( - Color backgroundColor, - float pixelDensity = 1f - ) { - if (!float.IsFinite(pixelDensity) || pixelDensity <= 0f) - { - throw new ArgumentOutOfRangeException(nameof(pixelDensity)); - } - this.backgroundColor = backgroundColor; - this.pixelDensity = pixelDensity; - } - - /// - /// Gets the linear clear color preferred by the host panel. - /// - public Color backgroundColor { get; } - - /// - /// Gets physical render pixels per logical presentation unit. - /// - public float pixelDensity { get; } -} - -/// -/// Selects whether transform handles use all axes or a contributor-declared planar orientation. -/// -public enum EditorViewportManipulationPlane -{ - /// - /// Keeps the full three-dimensional translation, rotation, and scale controls. - /// - Spatial, - /// - /// Uses the X/Y translation and scale axes with the Z rotation handle. - /// - XY, - /// - /// Uses the X/Z translation and scale axes with the Y rotation handle. - /// - XZ, - /// - /// Uses the Y/Z translation and scale axes with the X rotation handle. - /// - YZ -} - -/// -/// Describes the exact backend-neutral view and projection used to draw a viewport so host tools can manipulate -/// selected scene transforms without knowing the controller's camera model. -/// -public readonly record struct EditorViewportManipulationSpace -{ - /// - /// Creates a manipulation space matching one rendered viewport frame. - /// - /// - /// World-to-view matrix used by the submitted frame. - /// - /// - /// View-to-clip matrix used by the submitted frame. - /// - /// - /// Whether the projection is orthographic; this does not imply planar manipulation. - /// - /// - /// The contributor-selected transform handle orientation, independent of projection. - /// - /// - /// The plane is not one of the defined neutral manipulation orientations. - /// - public EditorViewportManipulationSpace( - Matrix viewMatrix, - Matrix projectionMatrix, - bool isOrthographic, - EditorViewportManipulationPlane plane = EditorViewportManipulationPlane.Spatial - ) { - if (!Enum.IsDefined(plane)) - { - throw new ArgumentOutOfRangeException(nameof(plane)); - } - this.viewMatrix = viewMatrix; - this.projectionMatrix = projectionMatrix; - this.isOrthographic = isOrthographic; - this.plane = plane; - } - - /// - /// Gets the world-to-view matrix used by the submitted frame. - /// - public Matrix viewMatrix { get; } - - /// - /// Gets the view-to-clip matrix used by the submitted frame. - /// - public Matrix projectionMatrix { get; } - - /// - /// Gets whether the submitted frame used an orthographic projection. - /// - public bool isOrthographic { get; } - - /// - /// Gets the contributor-declared neutral manipulation plane, or Spatial for all axes. - /// - public EditorViewportManipulationPlane plane { get; } -} - -/// -/// Returns one rendering-model contribution without exposing a GPU backend. -/// -public sealed class EditorViewportContribution -{ - /// - /// Creates a viewport model contribution. - /// - /// - /// Pipeline-defined frame-only data. - /// - /// - /// Contributor-selected pipeline, or null for the project default. - /// - /// - /// Presentation target format expected by the pipeline. - /// - /// - /// Optional exact view/projection contract for host-owned transform manipulation tools. - /// - public EditorViewportContribution( - RenderFrameData data, - RenderPipelineAsset? pipeline = null, - RenderTextureFormat targetFormat = RenderTextureFormat.RGBA8Srgb, - EditorViewportManipulationSpace? manipulationSpace = null - ) { - ArgumentNullException.ThrowIfNull(data); - this.data = data; - this.pipeline = pipeline; - this.targetFormat = targetFormat; - this.manipulationSpace = manipulationSpace; - } - - /// - /// Gets pipeline-defined frame-only data. - /// - public RenderFrameData data { get; } - - /// - /// Gets the selected pipeline, or null for the project default. - /// - public RenderPipelineAsset? pipeline { get; } - - /// - /// Gets the presentation target format expected by the pipeline. - /// - public RenderTextureFormat targetFormat { get; } - - /// - /// Gets the optional exact view/projection contract used by host-owned transform manipulation tools. - /// - public EditorViewportManipulationSpace? manipulationSpace { get; } -} - -/// -/// Supplies normalized pointer interaction over one rendered viewport. -/// -public sealed class EditorViewportPointerContext -{ - internal EditorViewportPointerContext( - EditorViewportContext viewport, - float x, - float y, - int button - ) { - this.viewport = viewport; - this.x = Math.Clamp(x, 0f, 1f); - this.y = Math.Clamp(y, 0f, 1f); - this.button = button; - } - - /// - /// Gets the owning frame-only viewport context. - /// - public EditorViewportContext viewport { get; } - - /// - /// Gets normalized horizontal pointer position. - /// - public float x { get; } - - /// - /// Gets normalized vertical pointer position. - /// - public float y { get; } - - /// - /// Gets the platform-independent pointer button index. - /// - public int button { get; } -} - /// /// Contributes one rendering model while the host owns viewport composition, targets, and presentation. /// @@ -487,3 +60,26 @@ public virtual void DrawToolbar(EditorViewportContext context) {} /// public virtual void HandlePointer(EditorViewportPointerContext context) {} } + +/// +/// Selects whether transform handles use all axes or a contributor-declared planar orientation. +/// +public enum EditorViewportManipulationPlane +{ + /// + /// Keeps the full three-dimensional translation, rotation, and scale controls. + /// + Spatial, + /// + /// Uses the X/Y translation and scale axes with the Z rotation handle. + /// + XY, + /// + /// Uses the X/Z translation and scale axes with the Y rotation handle. + /// + XZ, + /// + /// Uses the Y/Z translation and scale axes with the X rotation handle. + /// + YZ +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorExtensionAttribute.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorExtensionAttribute.cs new file mode 100644 index 000000000..e3fc96731 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportContributorExtensionAttribute.cs @@ -0,0 +1,59 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Marks a reloadable rendering-model contributor for one Editor viewport purpose. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class EditorViewportContributorExtensionAttribute : Attribute +{ + /// + /// Creates a viewport contributor declaration. + /// + /// + /// Globally stable contributor identity. + /// + /// + /// Open viewport purpose handled by the contributor. + /// + /// + /// Ascending model-composition order within the viewport. + /// + /// + /// Priority used to select the contributor that owns navigation, tools, and pointer interaction. + /// + public EditorViewportContributorExtensionAttribute( + string id, + string kind, + int order = 0, + int controllerPriority = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentException.ThrowIfNullOrWhiteSpace(kind); + this.id = id.Trim(); + this.kind = new EditorViewportKindID(kind); + this.order = order; + this.controllerPriority = controllerPriority; + } + + /// + /// Gets the globally stable contributor identity. + /// + public string id { get; } + + /// + /// Gets the open viewport purpose handled by the contributor. + /// + public EditorViewportKindID kind { get; } + + /// + /// Gets ascending model-composition order. + /// + public int order { get; } + + /// + /// Gets the priority used to select the viewport interaction controller. + /// + public int controllerPriority { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportFocusBounds.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportFocusBounds.cs new file mode 100644 index 000000000..5e0a480a2 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportFocusBounds.cs @@ -0,0 +1,53 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Describes a world-space sphere that can be framed by host navigation. +/// +public readonly record struct EditorViewportFocusBounds +{ + /// + /// Creates a finite focus bound. + /// + /// + /// World-space focus center. + /// + /// + /// Non-negative world-space radius. + /// + /// + /// Thrown when the center contains a non-finite value. + /// + /// + /// Thrown when the radius is negative or non-finite. + /// + public EditorViewportFocusBounds( + Vector3 center, + float radius + ) { + if (!IsFinite(center)) + { + throw new ArgumentException("Focus center components must be finite.", nameof(center)); + } + if (!float.IsFinite(radius) || radius < 0f) + { + throw new ArgumentOutOfRangeException(nameof(radius)); + } + this.center = center; + this.radius = radius; + } + + /// + /// Gets the world-space focus center. + /// + public Vector3 center { get; } + + /// + /// Gets the non-negative world-space radius. + /// + public float radius { get; } + + private static bool IsFinite(Vector3 value) => float.IsFinite(value.x) && float.IsFinite(value.y) && float.IsFinite(value.z); +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportKindID.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportKindID.cs new file mode 100644 index 000000000..9dad5ba0c --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportKindID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Identifies one open Editor viewport purpose without prescribing rendering semantics. +/// +public readonly record struct EditorViewportKindID +{ + /// + /// Creates a stable viewport purpose identifier. + /// + /// + /// Globally stable viewport purpose. + /// + public EditorViewportKindID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value.Trim(); + } + + /// + /// Gets the stable viewport purpose. + /// + public string value { get; } + + /// + /// Gets whether this identifier is usable. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value ?? string.Empty; +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportLayer.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportLayer.cs new file mode 100644 index 000000000..cd4d3e74e --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportLayer.cs @@ -0,0 +1,60 @@ +using System; +using Inno.Rendering.Assets; +using Inno.Rendering.Runtime; + +namespace Inno.Editor.Rendering; + +/// +/// Describes one model-neutral layer in an Editor viewport composition. +/// +public sealed class EditorViewportLayer +{ + /// + /// Creates one immutable model-neutral viewport layer. + /// + /// + /// Stable identity of the rendering-model contributor that produced the layer. + /// + /// + /// Contributor-selected pipeline, or null for the project default. + /// + /// + /// Contributor-defined frame-only data. + /// + /// + /// Ascending model-composition order. + /// + public EditorViewportLayer( + string contributorID, + RenderPipelineAsset? pipeline, + RenderFrameData data, + int order + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(contributorID); + ArgumentNullException.ThrowIfNull(data); + this.contributorID = contributorID; + this.pipeline = pipeline; + this.data = data; + this.order = order; + } + + /// + /// Gets the stable identity of the rendering-model contributor. + /// + public string contributorID { get; } + + /// + /// Gets the contributor-selected pipeline, or null for the project default. + /// + public RenderPipelineAsset? pipeline { get; } + + /// + /// Gets contributor-defined frame-only data. + /// + public RenderFrameData data { get; } + + /// + /// Gets ascending model-composition order. + /// + public int order { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportManipulationSpace.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportManipulationSpace.cs new file mode 100644 index 000000000..f48b2f977 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportManipulationSpace.cs @@ -0,0 +1,65 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Describes the exact backend-neutral view and projection used to draw a viewport so host tools can manipulate +/// selected scene transforms without knowing the controller's camera model. +/// +public readonly record struct EditorViewportManipulationSpace +{ + /// + /// Creates a manipulation space matching one rendered viewport frame. + /// + /// + /// World-to-view matrix used by the submitted frame. + /// + /// + /// View-to-clip matrix used by the submitted frame. + /// + /// + /// Whether the projection is orthographic; this does not imply planar manipulation. + /// + /// + /// The contributor-selected transform handle orientation, independent of projection. + /// + /// + /// The plane is not one of the defined neutral manipulation orientations. + /// + public EditorViewportManipulationSpace( + Matrix viewMatrix, + Matrix projectionMatrix, + bool isOrthographic, + EditorViewportManipulationPlane plane = EditorViewportManipulationPlane.Spatial + ) { + if (!Enum.IsDefined(plane)) + { + throw new ArgumentOutOfRangeException(nameof(plane)); + } + this.viewMatrix = viewMatrix; + this.projectionMatrix = projectionMatrix; + this.isOrthographic = isOrthographic; + this.plane = plane; + } + + /// + /// Gets the world-to-view matrix used by the submitted frame. + /// + public Matrix viewMatrix { get; } + + /// + /// Gets the view-to-clip matrix used by the submitted frame. + /// + public Matrix projectionMatrix { get; } + + /// + /// Gets whether the submitted frame used an orthographic projection. + /// + public bool isOrthographic { get; } + + /// + /// Gets the contributor-declared neutral manipulation plane, or Spatial for all axes. + /// + public EditorViewportManipulationPlane plane { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationCapabilities.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationCapabilities.cs new file mode 100644 index 000000000..a1575060e --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationCapabilities.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Declares navigation operations supported by one viewport interaction controller. +/// +[Flags] +public enum EditorViewportNavigationCapabilities +{ + /// + /// Disables host-owned navigation. + /// + None = 0, + /// + /// Allows translating the view parallel to its image plane. + /// + Pan = 1 << 0, + /// + /// Allows changing orthographic size or perspective focus distance. + /// + Zoom = 1 << 1, + /// + /// Allows the complete plane-oriented pan and zoom interaction model. + /// + Planar = Pan | Zoom, + /// + /// Allows pivot-oriented orbit and dolly. + /// + Orbit = 1 << 2, + /// + /// Allows free-look movement. + /// + Fly = 1 << 3, + /// + /// Allows framing a provider-supplied or host-derived selection bound. + /// + FrameSelection = 1 << 4 +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationMode.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationMode.cs new file mode 100644 index 000000000..da2d9f86c --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationMode.cs @@ -0,0 +1,20 @@ +namespace Inno.Editor.Rendering; + +/// +/// Identifies the active interaction model without prescribing a rendering camera type. +/// +public enum EditorViewportNavigationMode +{ + /// + /// Pans and zooms over a provider-defined plane. + /// + Planar, + /// + /// Rotates around a focus pivot and dollies along the view direction. + /// + Orbit, + /// + /// Moves and looks freely from the current view position. + /// + Fly +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfile.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfile.cs new file mode 100644 index 000000000..e63ab7b3c --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfile.cs @@ -0,0 +1,141 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Describes how the host may navigate one provider-owned viewport without exposing the provider's camera model. +/// +public sealed class EditorViewportNavigationProfile +{ + /// + /// Creates a provider-defined navigation profile. + /// + /// + /// Stable profile identity. + /// + /// + /// Operations accepted by the provider. + /// + /// + /// Preferred mode when current state is unsupported. + /// + public EditorViewportNavigationProfile( + EditorViewportNavigationProfileID id, + EditorViewportNavigationCapabilities capabilities, + EditorViewportNavigationMode defaultMode + ) { + if (!id.isValid) + { + throw new ArgumentException("A valid navigation profile ID is required.", nameof(id)); + } + const EditorViewportNavigationCapabilities C_VALID_CAPABILITIES = EditorViewportNavigationCapabilities.Pan + | EditorViewportNavigationCapabilities.Zoom + | EditorViewportNavigationCapabilities.Orbit + | EditorViewportNavigationCapabilities.Fly + | EditorViewportNavigationCapabilities.FrameSelection; + if ((capabilities & ~C_VALID_CAPABILITIES) != 0) + { + throw new ArgumentOutOfRangeException(nameof(capabilities)); + } + if (capabilities != EditorViewportNavigationCapabilities.None + && !SupportsMode(capabilities, defaultMode) + ) { + throw new ArgumentException( + "The default navigation mode must be enabled by the profile capabilities.", + nameof(defaultMode) + ); + } + this.id = id; + this.capabilities = capabilities; + this.defaultMode = defaultMode; + } + + /// + /// Gets the stable profile identity. + /// + public EditorViewportNavigationProfileID id { get; } + + /// + /// Gets the operations accepted by this provider. + /// + public EditorViewportNavigationCapabilities capabilities { get; } + + /// + /// Gets the mode selected when current state is not supported. + /// + public EditorViewportNavigationMode defaultMode { get; } + + /// + /// Gets or sets the provider-defined world-up direction. + /// + public Vector3 worldUp { get; set; } = Vector3.UP; + + /// + /// Gets or sets the optional current selection bound. + /// + public EditorViewportFocusBounds? focusBounds { get; set; } + + /// + /// Gets or sets pointer rotation sensitivity in radians per pixel. + /// + public float rotationSensitivity { get; set; } = 0.005f; + + /// + /// Gets or sets exponential wheel zoom sensitivity. + /// + public float zoomSensitivity { get; set; } = 0.16f; + + /// + /// Gets or sets minimum orthographic half-height. + /// + public float minimumOrthographicSize { get; set; } = 0.001f; + + /// + /// Gets or sets maximum orthographic half-height. + /// + public float maximumOrthographicSize { get; set; } = 100000f; + + /// + /// Gets or sets minimum orbit or framing distance. + /// + public float minimumFocusDistance { get; set; } = 0.01f; + + /// + /// Gets or sets maximum orbit or framing distance. + /// + public float maximumFocusDistance { get; set; } = 1000000f; + + /// + /// Gets or sets the multiplier used while fast fly movement is requested. + /// + public float fastMovementMultiplier { get; set; } = 4f; + + /// + /// Gets or sets additional framing space around selection bounds. + /// + public float framePadding { get; set; } = 1.25f; + + /// + /// Gets a disabled fallback profile used when no provider navigation contract exists. + /// + public static EditorViewportNavigationProfile disabled { get; } = new( + new EditorViewportNavigationProfileID("inno.editor.navigation.disabled"), + EditorViewportNavigationCapabilities.None, + EditorViewportNavigationMode.Planar + ); + + private static bool SupportsMode( + EditorViewportNavigationCapabilities capabilities, + EditorViewportNavigationMode mode + ) => mode switch + { + EditorViewportNavigationMode.Planar => + (capabilities & EditorViewportNavigationCapabilities.Planar) != 0, + EditorViewportNavigationMode.Orbit => + capabilities.HasFlag(EditorViewportNavigationCapabilities.Orbit), + EditorViewportNavigationMode.Fly => + capabilities.HasFlag(EditorViewportNavigationCapabilities.Fly), + _ => false + }; +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfileID.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfileID.cs new file mode 100644 index 000000000..8f69c2e0a --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationProfileID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Identifies a provider-defined navigation profile across reload generations. +/// +public readonly record struct EditorViewportNavigationProfileID +{ + /// + /// Creates a stable profile identifier. + /// + /// + /// Globally stable profile identity. + /// + public EditorViewportNavigationProfileID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value.Trim(); + } + + /// + /// Gets the stable profile identity. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value ?? string.Empty; +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigation.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationState.cs similarity index 50% rename from src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigation.cs rename to src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationState.cs index 1da1120db..d239230f0 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigation.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportNavigationState.cs @@ -3,298 +3,6 @@ namespace Inno.Editor.Rendering; -/// -/// Identifies the projection family represented by neutral Editor viewport navigation state. -/// -public enum EditorViewportProjection -{ - /// - /// Uses a parallel projection controlled by an orthographic half-height. - /// - Orthographic, - /// - /// Uses a perspective projection controlled by a vertical field of view. - /// - Perspective -} - -/// -/// Identifies the active interaction model without prescribing a rendering camera type. -/// -public enum EditorViewportNavigationMode -{ - /// - /// Pans and zooms over a provider-defined plane. - /// - Planar, - /// - /// Rotates around a focus pivot and dollies along the view direction. - /// - Orbit, - /// - /// Moves and looks freely from the current view position. - /// - Fly -} - -/// -/// Declares navigation operations supported by one viewport interaction controller. -/// -[Flags] -public enum EditorViewportNavigationCapabilities -{ - /// - /// Disables host-owned navigation. - /// - None = 0, - /// - /// Allows translating the view parallel to its image plane. - /// - Pan = 1 << 0, - /// - /// Allows changing orthographic size or perspective focus distance. - /// - Zoom = 1 << 1, - /// - /// Allows the complete plane-oriented pan and zoom interaction model. - /// - Planar = Pan | Zoom, - /// - /// Allows pivot-oriented orbit and dolly. - /// - Orbit = 1 << 2, - /// - /// Allows free-look movement. - /// - Fly = 1 << 3, - /// - /// Allows framing a provider-supplied or host-derived selection bound. - /// - FrameSelection = 1 << 4 -} - -/// -/// Identifies a provider-defined navigation profile across reload generations. -/// -public readonly record struct EditorViewportNavigationProfileID -{ - /// - /// Creates a stable profile identifier. - /// - /// - /// Globally stable profile identity. - /// - public EditorViewportNavigationProfileID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value.Trim(); - } - - /// - /// Gets the stable profile identity. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value ?? string.Empty; -} - -/// -/// Describes a world-space sphere that can be framed by host navigation. -/// -public readonly record struct EditorViewportFocusBounds -{ - /// - /// Creates a finite focus bound. - /// - /// - /// World-space focus center. - /// - /// - /// Non-negative world-space radius. - /// - /// - /// Thrown when the center contains a non-finite value. - /// - /// - /// Thrown when the radius is negative or non-finite. - /// - public EditorViewportFocusBounds( - Vector3 center, - float radius - ) { - if (!IsFinite(center)) - { - throw new ArgumentException("Focus center components must be finite.", nameof(center)); - } - if (!float.IsFinite(radius) || radius < 0f) - { - throw new ArgumentOutOfRangeException(nameof(radius)); - } - this.center = center; - this.radius = radius; - } - - /// - /// Gets the world-space focus center. - /// - public Vector3 center { get; } - - /// - /// Gets the non-negative world-space radius. - /// - public float radius { get; } - - private static bool IsFinite(Vector3 value) => float.IsFinite(value.x) && float.IsFinite(value.y) && float.IsFinite(value.z); -} - -/// -/// Describes how the host may navigate one provider-owned viewport without exposing the provider's camera model. -/// -public sealed class EditorViewportNavigationProfile -{ - /// - /// Creates a provider-defined navigation profile. - /// - /// - /// Stable profile identity. - /// - /// - /// Operations accepted by the provider. - /// - /// - /// Preferred mode when current state is unsupported. - /// - public EditorViewportNavigationProfile( - EditorViewportNavigationProfileID id, - EditorViewportNavigationCapabilities capabilities, - EditorViewportNavigationMode defaultMode - ) { - if (!id.isValid) - { - throw new ArgumentException("A valid navigation profile ID is required.", nameof(id)); - } - const EditorViewportNavigationCapabilities C_VALID_CAPABILITIES = EditorViewportNavigationCapabilities.Pan - | EditorViewportNavigationCapabilities.Zoom - | EditorViewportNavigationCapabilities.Orbit - | EditorViewportNavigationCapabilities.Fly - | EditorViewportNavigationCapabilities.FrameSelection; - if ((capabilities & ~C_VALID_CAPABILITIES) != 0) - { - throw new ArgumentOutOfRangeException(nameof(capabilities)); - } - if (capabilities != EditorViewportNavigationCapabilities.None - && !SupportsMode(capabilities, defaultMode) - ) { - throw new ArgumentException( - "The default navigation mode must be enabled by the profile capabilities.", - nameof(defaultMode) - ); - } - this.id = id; - this.capabilities = capabilities; - this.defaultMode = defaultMode; - } - - /// - /// Gets the stable profile identity. - /// - public EditorViewportNavigationProfileID id { get; } - - /// - /// Gets the operations accepted by this provider. - /// - public EditorViewportNavigationCapabilities capabilities { get; } - - /// - /// Gets the mode selected when current state is not supported. - /// - public EditorViewportNavigationMode defaultMode { get; } - - /// - /// Gets or sets the provider-defined world-up direction. - /// - public Vector3 worldUp { get; set; } = Vector3.UP; - - /// - /// Gets or sets the optional current selection bound. - /// - public EditorViewportFocusBounds? focusBounds { get; set; } - - /// - /// Gets or sets pointer rotation sensitivity in radians per pixel. - /// - public float rotationSensitivity { get; set; } = 0.005f; - - /// - /// Gets or sets exponential wheel zoom sensitivity. - /// - public float zoomSensitivity { get; set; } = 0.16f; - - /// - /// Gets or sets minimum orthographic half-height. - /// - public float minimumOrthographicSize { get; set; } = 0.001f; - - /// - /// Gets or sets maximum orthographic half-height. - /// - public float maximumOrthographicSize { get; set; } = 100000f; - - /// - /// Gets or sets minimum orbit or framing distance. - /// - public float minimumFocusDistance { get; set; } = 0.01f; - - /// - /// Gets or sets maximum orbit or framing distance. - /// - public float maximumFocusDistance { get; set; } = 1000000f; - - /// - /// Gets or sets the multiplier used while fast fly movement is requested. - /// - public float fastMovementMultiplier { get; set; } = 4f; - - /// - /// Gets or sets additional framing space around selection bounds. - /// - public float framePadding { get; set; } = 1.25f; - - /// - /// Gets a disabled fallback profile used when no provider navigation contract exists. - /// - public static EditorViewportNavigationProfile disabled { get; } = new( - new EditorViewportNavigationProfileID("inno.editor.navigation.disabled"), - EditorViewportNavigationCapabilities.None, - EditorViewportNavigationMode.Planar - ); - - private static bool SupportsMode( - EditorViewportNavigationCapabilities capabilities, - EditorViewportNavigationMode mode - ) => mode switch - { - EditorViewportNavigationMode.Planar => - (capabilities & EditorViewportNavigationCapabilities.Planar) != 0, - EditorViewportNavigationMode.Orbit => - capabilities.HasFlag(EditorViewportNavigationCapabilities.Orbit), - EditorViewportNavigationMode.Fly => - capabilities.HasFlag(EditorViewportNavigationCapabilities.Fly), - _ => false - }; -} - /// /// Stores rendering-model-neutral navigation state for one Editor viewport across provider reloads. /// diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs index e0f4ac18a..df78cf386 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportOutput.cs @@ -1,11 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using Inno.Adapter.Presentation; -using Inno.Rendering; -using Inno.Rendering.Assets; -using Inno.Rendering.Runtime; namespace Inno.Editor.Rendering; @@ -69,200 +63,3 @@ int pixelHeight /// public bool isReady => texture.isValid; } - -/// -/// Bridges editor extensions to a host-owned render request sink and opaque texture presenter. -/// -public interface IEditorRenderingHost -{ - /// - /// Gets the active generation's model-independent world-content collector. - /// - IViewContentCollector viewContent { get; } - - /// - /// Gets the current output frame index shared by Editor views. - /// - ulong currentFrameIndex { get; } - - /// - /// Submits or updates one composed offscreen editor viewport. - /// - /// - /// Complete ordered model composition for the current frame. - /// - /// - /// The current presentation output, which can be warming up for one frame. - /// - EditorViewportOutput Submit(EditorViewportComposition composition); - - /// - /// Draws a ready viewport output inside the current ImGui window. - /// - /// - /// Output returned by . - /// - /// - /// Destination size in logical UI pixels. - /// - void Draw( - EditorViewportOutput output, - Vector2 logicalSize - ); - - /// - /// Releases one viewport and queues its GPU target for frame-safe destruction. - /// - /// - /// Stable viewport identity. - /// - void Release(string viewportID); - - /// - /// Releases every viewport owned by this editor host service. - /// - void ReleaseAll(); -} - -/// -/// Describes one model-neutral layer in an Editor viewport composition. -/// -public sealed class EditorViewportLayer -{ - /// - /// Creates one immutable model-neutral viewport layer. - /// - /// - /// Stable identity of the rendering-model contributor that produced the layer. - /// - /// - /// Contributor-selected pipeline, or null for the project default. - /// - /// - /// Contributor-defined frame-only data. - /// - /// - /// Ascending model-composition order. - /// - public EditorViewportLayer( - string contributorID, - RenderPipelineAsset? pipeline, - RenderFrameData data, - int order - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(contributorID); - ArgumentNullException.ThrowIfNull(data); - this.contributorID = contributorID; - this.pipeline = pipeline; - this.data = data; - this.order = order; - } - - /// - /// Gets the stable identity of the rendering-model contributor. - /// - public string contributorID { get; } - - /// - /// Gets the contributor-selected pipeline, or null for the project default. - /// - public RenderPipelineAsset? pipeline { get; } - - /// - /// Gets contributor-defined frame-only data. - /// - public RenderFrameData data { get; } - - /// - /// Gets ascending model-composition order. - /// - public int order { get; } -} - -/// -/// Describes a complete ordered set of rendering-model layers targeting one Editor viewport. -/// -public sealed class EditorViewportComposition -{ - private readonly IReadOnlyList m_layers; - - /// - /// Creates an immutable viewport composition. - /// - /// - /// Stable panel viewport identity. - /// - /// - /// Positive target width. - /// - /// - /// Positive target height. - /// - /// - /// Shared presentation target format required by every layer. - /// - /// - /// Ordered non-empty rendering-model layer collection. - /// - public EditorViewportComposition( - string viewportID, - int pixelWidth, - int pixelHeight, - RenderTextureFormat targetFormat, - IEnumerable layers - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(viewportID); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); - ArgumentNullException.ThrowIfNull(layers); - EditorViewportLayer[] materializedLayers = layers.ToArray(); - if (materializedLayers.Length == 0) - { - throw new ArgumentException("A viewport composition requires at least one model layer.", nameof(layers)); - } - if (materializedLayers.Any(static layer => layer is null)) - { - throw new ArgumentException("A viewport composition cannot contain null model layers.", nameof(layers)); - } - if (materializedLayers.Select(static layer => layer.contributorID).Distinct(StringComparer.Ordinal).Count() - != materializedLayers.Length - ) { - throw new ArgumentException("Viewport contributor identities must be unique.", nameof(layers)); - } - m_layers = Array.AsReadOnly( - materializedLayers - .OrderBy(static layer => layer.order) - .ThenBy(static layer => layer.contributorID, StringComparer.Ordinal) - .ToArray() - ); - this.viewportID = viewportID; - this.pixelWidth = pixelWidth; - this.pixelHeight = pixelHeight; - this.targetFormat = targetFormat; - } - - /// - /// Gets the stable viewport identity. - /// - public string viewportID { get; } - - /// - /// Gets the target width. - /// - public int pixelWidth { get; } - - /// - /// Gets the target height. - /// - public int pixelHeight { get; } - - /// - /// Gets the shared presentation target format. - /// - public RenderTextureFormat targetFormat { get; } - - /// - /// Gets the ordered rendering-model layers. - /// - public IReadOnlyList layers => m_layers; -} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPointerContext.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPointerContext.cs new file mode 100644 index 000000000..fae74f060 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPointerContext.cs @@ -0,0 +1,41 @@ +using System; + +namespace Inno.Editor.Rendering; + +/// +/// Supplies normalized pointer interaction over one rendered viewport. +/// +public sealed class EditorViewportPointerContext +{ + internal EditorViewportPointerContext( + EditorViewportContext viewport, + float x, + float y, + int button + ) { + this.viewport = viewport; + this.x = Math.Clamp(x, 0f, 1f); + this.y = Math.Clamp(y, 0f, 1f); + this.button = button; + } + + /// + /// Gets the owning frame-only viewport context. + /// + public EditorViewportContext viewport { get; } + + /// + /// Gets normalized horizontal pointer position. + /// + public float x { get; } + + /// + /// Gets normalized vertical pointer position. + /// + public float y { get; } + + /// + /// Gets the platform-independent pointer button index. + /// + public int button { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPresentation.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPresentation.cs new file mode 100644 index 000000000..ee0262f22 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportPresentation.cs @@ -0,0 +1,41 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Describes host-selected presentation preferences without prescribing rendering behavior. +/// +public readonly record struct EditorViewportPresentation +{ + /// + /// Creates presentation preferences for one Editor viewport. + /// + /// + /// Linear clear color preferred by the host panel. + /// + /// + /// Physical render pixels per logical presentation unit. + /// + public EditorViewportPresentation( + Color backgroundColor, + float pixelDensity = 1f + ) { + if (!float.IsFinite(pixelDensity) || pixelDensity <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(pixelDensity)); + } + this.backgroundColor = backgroundColor; + this.pixelDensity = pixelDensity; + } + + /// + /// Gets the linear clear color preferred by the host panel. + /// + public Color backgroundColor { get; } + + /// + /// Gets physical render pixels per logical presentation unit. + /// + public float pixelDensity { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportProjection.cs b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportProjection.cs new file mode 100644 index 000000000..bba7fe691 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/EditorViewportProjection.cs @@ -0,0 +1,16 @@ +namespace Inno.Editor.Rendering; + +/// +/// Identifies the projection family represented by neutral Editor viewport navigation state. +/// +public enum EditorViewportProjection +{ + /// + /// Uses a parallel projection controlled by an orthographic half-height. + /// + Orthographic, + /// + /// Uses a perspective projection controlled by a vertical field of view. + /// + Perspective +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/IEditorGizmoSink.cs b/src/composition/editor/features/Inno.Editor.Rendering/IEditorGizmoSink.cs new file mode 100644 index 000000000..2e01c43e5 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/IEditorGizmoSink.cs @@ -0,0 +1,42 @@ +using Inno.Core.Identity; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Rendering; + +/// +/// Receives transient world-space gizmo geometry from independent Editor extensions. +/// +public interface IEditorGizmoSink +{ + /// + /// Adds a visible, selectable icon at an object's world position. + /// + /// + /// The scene object selected when the icon is clicked. + /// + /// + /// The icon position in world space. + /// + /// + /// A stable semantic icon ID. Unknown IDs use the generic scene icon. + /// + void Icon( + Identity owner, + Vector3 position, + string iconID + ); + + /// + /// Adds a non-interactive world-space line, normally for selected bounds. + /// + /// + /// The first world-space endpoint. + /// + /// + /// The second world-space endpoint. + /// + void Line( + Vector3 start, + Vector3 end + ); +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewService.cs b/src/composition/editor/features/Inno.Editor.Rendering/IEditorPreviewService.cs similarity index 63% rename from src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewService.cs rename to src/composition/editor/features/Inno.Editor.Rendering/IEditorPreviewService.cs index 364f49cd6..d37374b8e 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/EditorPreviewService.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/IEditorPreviewService.cs @@ -1,74 +1,8 @@ -using System; using System.Numerics; -using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Editor.Rendering; -/// -/// Identifies one preview texture owned by a specific rendering-device generation. -/// -public readonly record struct EditorPreviewHandle -{ - /// - /// Creates one generation-scoped preview handle. - /// - /// - /// Non-zero preview identity. - /// - /// - /// Non-zero rendering-device generation. - /// - /// - /// Positive source width. - /// - /// - /// Positive source height. - /// - public EditorPreviewHandle( - ulong value, - uint deviceGeneration, - int pixelWidth, - int pixelHeight - ) { - if (value == 0 || deviceGeneration == 0) - { - throw new ArgumentOutOfRangeException(nameof(value), "Preview identity and device generation must be non-zero."); - } - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); - this.value = value; - this.deviceGeneration = deviceGeneration; - this.pixelWidth = pixelWidth; - this.pixelHeight = pixelHeight; - } - - /// - /// Gets the opaque preview identity. - /// - public ulong value { get; } - - /// - /// Gets the rendering-device generation that owns this handle. - /// - public uint deviceGeneration { get; } - - /// - /// Gets source width in pixels. - /// - public int pixelWidth { get; } - - /// - /// Gets source height in pixels. - /// - public int pixelHeight { get; } - - /// - /// Gets whether this handle identifies a usable generation-scoped preview. - /// - public bool isValid => value != 0 && deviceGeneration != 0 && pixelWidth > 0 && pixelHeight > 0; -} - /// /// Provides one shared preview texture bridge for browsers, inspectors, and document canvases. /// diff --git a/src/composition/editor/features/Inno.Editor.Rendering/IEditorRenderingHost.cs b/src/composition/editor/features/Inno.Editor.Rendering/IEditorRenderingHost.cs new file mode 100644 index 000000000..60f7eadaf --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/IEditorRenderingHost.cs @@ -0,0 +1,58 @@ +using System.Numerics; +using Inno.Rendering.Runtime; + +namespace Inno.Editor.Rendering; + +/// +/// Bridges editor extensions to a host-owned render request sink and opaque texture presenter. +/// +public interface IEditorRenderingHost +{ + /// + /// Gets the active generation's model-independent world-content collector. + /// + IViewContentCollector viewContent { get; } + + /// + /// Gets the current output frame index shared by Editor views. + /// + ulong currentFrameIndex { get; } + + /// + /// Submits or updates one composed offscreen editor viewport. + /// + /// + /// Complete ordered model composition for the current frame. + /// + /// + /// The current presentation output, which can be warming up for one frame. + /// + EditorViewportOutput Submit(EditorViewportComposition composition); + + /// + /// Draws a ready viewport output inside the current ImGui window. + /// + /// + /// Output returned by . + /// + /// + /// Destination size in logical UI pixels. + /// + void Draw( + EditorViewportOutput output, + Vector2 logicalSize + ); + + /// + /// Releases one viewport and queues its GPU target for frame-safe destruction. + /// + /// + /// Stable viewport identity. + /// + void Release(string viewportID); + + /// + /// Releases every viewport owned by this editor host service. + /// + void ReleaseAll(); +} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs index c8505047d..495d12bfe 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDocuments.cs @@ -8,7 +8,6 @@ using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Scripting.Api; @@ -172,76 +171,3 @@ internal static bool Recoverable(Exception error) => error is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or FormatException && RetirementPendingException.Find(error) is null; } - -[EditorHistoryHandler(PipelineDocuments.C_HISTORY)] -internal sealed class PipelineDraftHistory(PipelineDocuments documents) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - documents.drafts.ValidateHistory(change, direction); - return EditorHistoryAvailability.Available(); - } - catch (Exception error) when (PipelineDocuments.Recoverable(error)) - { - return EditorHistoryAvailability.Unavailable(error.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - documents.drafts.ApplyHistory(change, direction); - return EditorHistoryResult.Success(); - } - catch (Exception error) when (PipelineDocuments.Recoverable(error)) - { - return EditorHistoryResult.Failure(error.Message); - } - } - - /// - protected override bool TryMerge( - EditorHistoryChange older, - EditorHistoryChange newer, - out EditorHistoryChange? merged - ) => documents.drafts.TryMergeHistory(older, newer, out merged); -} diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDraftHistory.cs b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDraftHistory.cs new file mode 100644 index 000000000..e24de0b43 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Rendering/Pipelines/PipelineDraftHistory.cs @@ -0,0 +1,77 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Rendering; + +[EditorHistoryHandler(PipelineDocuments.C_HISTORY)] +internal sealed class PipelineDraftHistory(PipelineDocuments documents) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + documents.drafts.ValidateHistory(change, direction); + return EditorHistoryAvailability.Available(); + } + catch (Exception error) when (PipelineDocuments.Recoverable(error)) + { + return EditorHistoryAvailability.Unavailable(error.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + documents.drafts.ApplyHistory(change, direction); + return EditorHistoryResult.Success(); + } + catch (Exception error) when (PipelineDocuments.Recoverable(error)) + { + return EditorHistoryResult.Failure(error.Message); + } + } + + /// + protected override bool TryMerge( + EditorHistoryChange older, + EditorHistoryChange newer, + out EditorHistoryChange? merged + ) => documents.drafts.TryMergeHistory(older, newer, out merged); +} diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs index f2a8ba2e2..5fd7e26fa 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneHierarchyHistoryData.cs @@ -3,13 +3,6 @@ namespace Inno.Editor.Scene; -internal readonly record struct SceneObjectPlacement( - Guid sceneID, - Guid objectID, - Guid? parentID, - int siblingIndex -); - internal sealed record SceneHierarchyHistoryData( SceneObjectPlacement[] before, SceneObjectPlacement[] after, @@ -77,3 +70,10 @@ private static SceneObjectPlacement[] ReadPlacements(BinaryReader reader) return placements; } } + +internal readonly record struct SceneObjectPlacement( + Guid sceneID, + Guid objectID, + Guid? parentID, + int siblingIndex +); diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs index 425d3cdf5..504819c32 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryData.cs @@ -6,12 +6,6 @@ namespace Inno.Editor.Scene; -internal sealed record ScenePropertyValueDelta( - string propertyName, - byte[] before, - byte[] after -); - internal sealed record ScenePropertyHistoryData( Guid targetID, string propertyName, @@ -110,3 +104,9 @@ string name return bytes; } } + +internal sealed record ScenePropertyValueDelta( + string propertyName, + byte[] before, + byte[] after +); diff --git a/src/composition/editor/features/Inno.Editor.Scripting/ReloadPluginsAction.cs b/src/composition/editor/features/Inno.Editor.Scripting/ReloadPluginsAction.cs new file mode 100644 index 000000000..9a4d2c056 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Scripting/ReloadPluginsAction.cs @@ -0,0 +1,28 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Scripting; + +[EditorAction(ScriptingInteractionIDs.C_RELOAD_PLUGINS, ScriptingInteractionIDs.C_MAIN_MENU_AREA)] +[EditorMenu(ScriptingInteractionIDs.C_MAIN_MENU_AREA, "Tools/Scripting/Reload Plugins", order: 120)] +internal sealed class ReloadPluginsAction(EditorScripting scripting) : EditorAction +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => scripting.canReload ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => scripting.ReloadPlugins(); +} diff --git a/src/composition/editor/features/Inno.Editor.Scripting/ScriptingReloadActions.cs b/src/composition/editor/features/Inno.Editor.Scripting/ReloadScriptingAction.cs similarity index 51% rename from src/composition/editor/features/Inno.Editor.Scripting/ScriptingReloadActions.cs rename to src/composition/editor/features/Inno.Editor.Scripting/ReloadScriptingAction.cs index 73be732a4..b00723374 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/ScriptingReloadActions.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/ReloadScriptingAction.cs @@ -26,28 +26,3 @@ protected override EditorActionState Query(EditorActionContext context) /// protected override void Execute(EditorActionContext context) => scripting.ReloadScripting(); } - -[EditorAction(ScriptingInteractionIDs.C_RELOAD_PLUGINS, ScriptingInteractionIDs.C_MAIN_MENU_AREA)] -[EditorMenu(ScriptingInteractionIDs.C_MAIN_MENU_AREA, "Tools/Scripting/Reload Plugins", order: 120)] -internal sealed class ReloadPluginsAction(EditorScripting scripting) : EditorAction -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - => scripting.canReload ? EditorActionState.enabled : EditorActionState.disabled; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => scripting.ReloadPlugins(); -} diff --git a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs index 1e4458cfe..8c40fda29 100644 --- a/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs +++ b/src/composition/editor/features/Inno.Editor.Scripting/Runtime/IEditorScriptCompilation.cs @@ -2,29 +2,6 @@ namespace Inno.Editor.Scripting; -/// -/// Identifies whether the active project script generation can safely start game simulation. -/// -public enum EditorScriptCompilationState -{ - /// - /// The script service has not produced its initial active generation. - /// - Initializing, - /// - /// A requested script generation is compiling, activating, or completing unload verification. - /// - Compiling, - /// - /// The most recent compilation succeeded, its generation is active, and retired generations passed GC verification. - /// - Ready, - /// - /// Compilation, activation, or generation retirement failed, so game simulation must not start. - /// - Failed -} - /// /// Exposes the minimal script-generation readiness contract required by editor workflows. /// @@ -72,3 +49,26 @@ public interface IEditorScriptCompilation /// IScriptCompilationTicket RequestCompilation(); } + +/// +/// Identifies whether the active project script generation can safely start game simulation. +/// +public enum EditorScriptCompilationState +{ + /// + /// The script service has not produced its initial active generation. + /// + Initializing, + /// + /// A requested script generation is compiling, activating, or completing unload verification. + /// + Compiling, + /// + /// The most recent compilation succeeded, its generation is active, and retired generations passed GC verification. + /// + Ready, + /// + /// Compilation, activation, or generation retirement failed, so game simulation must not start. + /// + Failed +} diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs index b99d75ad5..d80dfa364 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDocuments.cs @@ -240,76 +240,3 @@ private sealed class PresentationCache internal string error = string.Empty; } } - -[EditorHistoryHandler(MaterialDocuments.C_HISTORY)] -internal sealed class MaterialDraftHistory(MaterialDocuments documents) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - documents.ValidateHistory(change, direction); - return EditorHistoryAvailability.Available(); - } - catch (Exception error) when (MaterialDocuments.Recoverable(error)) - { - return EditorHistoryAvailability.Unavailable(error.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - documents.ApplyHistory(change, direction); - return EditorHistoryResult.Success(); - } - catch (Exception error) when (MaterialDocuments.Recoverable(error)) - { - return EditorHistoryResult.Failure(error.Message); - } - } - - /// - protected override bool TryMerge( - EditorHistoryChange older, - EditorHistoryChange newer, - out EditorHistoryChange? merged - ) => documents.TryMergeHistory(older, newer, out merged); -} diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDraftHistory.cs b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDraftHistory.cs new file mode 100644 index 000000000..84c94416a --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Shaders/Materials/MaterialDraftHistory.cs @@ -0,0 +1,77 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Shaders; + +[EditorHistoryHandler(MaterialDocuments.C_HISTORY)] +internal sealed class MaterialDraftHistory(MaterialDocuments documents) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + documents.ValidateHistory(change, direction); + return EditorHistoryAvailability.Available(); + } + catch (Exception error) when (MaterialDocuments.Recoverable(error)) + { + return EditorHistoryAvailability.Unavailable(error.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + documents.ApplyHistory(change, direction); + return EditorHistoryResult.Success(); + } + catch (Exception error) when (MaterialDocuments.Recoverable(error)) + { + return EditorHistoryResult.Failure(error.Message); + } + } + + /// + protected override bool TryMerge( + EditorHistoryChange older, + EditorHistoryChange newer, + out EditorHistoryChange? merged + ) => documents.TryMergeHistory(older, newer, out merged); +} diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewContext.cs b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewContext.cs new file mode 100644 index 000000000..bb6f35f25 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewContext.cs @@ -0,0 +1,99 @@ +using System; +using Inno.Core.Diagnostics; +using Inno.Rendering.Assets; +using Inno.Rendering.Runtime; + +namespace Inno.Editor.Shaders; + +/// +/// Carries frame-only preview inputs; persistent provider state must retain stable values rather than this object. +/// +public sealed class ShaderPreviewContext +{ + /// + /// Creates a preview invocation from host-owned detached inputs. + /// + /// + /// Isolated material publication and viewport resource identity. + /// + /// + /// Detached values with a current Shader reference; do not modify the reference. + /// + /// + /// Compiled candidate, never published as a canonical Shader. + /// + /// + /// Detached contract captured by the candidate. + /// + /// + /// Preview-local reporter; errors must not contaminate project diagnostics. + /// + /// + /// Positive target width. + /// + /// + /// Positive target height. + /// + public ShaderPreviewContext( + RenderPersistentResourceID resourceID, + MaterialAsset material, + RenderShaderArtifact artifact, + ShaderDefinition definition, + IDiagnosticReporter diagnostics, + int pixelWidth, + int pixelHeight + ) { + if (!resourceID.isValid) + { + throw new ArgumentException("A resource identity is required.", nameof(resourceID)); + } + ArgumentNullException.ThrowIfNull(material); + ArgumentNullException.ThrowIfNull(artifact); + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(diagnostics); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); + this.resourceID = resourceID; + this.material = material; + this.artifact = artifact; + this.definition = definition; + this.diagnostics = diagnostics; + this.pixelWidth = pixelWidth; + this.pixelHeight = pixelHeight; + } + + /// + /// Gets the publication scope released by the host when this preview closes. + /// + public RenderPersistentResourceID resourceID { get; } + + /// + /// Gets the invocation-local Material values. + /// + public MaterialAsset material { get; } + + /// + /// Gets the complete immutable GPU candidate. + /// + public RenderShaderArtifact artifact { get; } + + /// + /// Gets the candidate's exact contract, not the latest uncompiled source interface. + /// + public ShaderDefinition definition { get; } + + /// + /// Gets the host-owned, isolated diagnostic producer. + /// + public IDiagnosticReporter diagnostics { get; } + + /// + /// Gets target width in physical pixels. + /// + public int pixelWidth { get; } + + /// + /// Gets target height in physical pixels. + /// + public int pixelHeight { get; } +} diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs index 8a77caa31..9aafc3978 100644 --- a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs +++ b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProvider.cs @@ -1,29 +1,7 @@ -using System; -using Inno.Core.Diagnostics; using Inno.Editor.Rendering; -using Inno.Rendering; -using Inno.Rendering.Assets; -using Inno.Rendering.Runtime; namespace Inno.Editor.Shaders; -/// -/// Associates a reloadable preview implementation with one open Shader contract. -/// -/// -/// Non-empty domain-owned contract identity. -/// -[AttributeUsage(AttributeTargets.Class, Inherited = false)] -public sealed class ShaderPreviewProviderAttribute(string contractID) : Attribute -{ - /// - /// Gets the non-empty Shader contract consumed by this preview. - /// - public string contractID { get; } = string.IsNullOrWhiteSpace(contractID) - ? throw new ArgumentException("A preview contract is required.", nameof(contractID)) - : contractID; -} - /// /// Builds domain-owned preview geometry and pass inputs without changing a scene or canonical asset. /// @@ -40,96 +18,3 @@ public abstract class ShaderPreviewProvider /// public abstract EditorViewportLayer CreateLayer(ShaderPreviewContext context); } - -/// -/// Carries frame-only preview inputs; persistent provider state must retain stable values rather than this object. -/// -public sealed class ShaderPreviewContext -{ - /// - /// Creates a preview invocation from host-owned detached inputs. - /// - /// - /// Isolated material publication and viewport resource identity. - /// - /// - /// Detached values with a current Shader reference; do not modify the reference. - /// - /// - /// Compiled candidate, never published as a canonical Shader. - /// - /// - /// Detached contract captured by the candidate. - /// - /// - /// Preview-local reporter; errors must not contaminate project diagnostics. - /// - /// - /// Positive target width. - /// - /// - /// Positive target height. - /// - public ShaderPreviewContext( - RenderPersistentResourceID resourceID, - MaterialAsset material, - RenderShaderArtifact artifact, - ShaderDefinition definition, - IDiagnosticReporter diagnostics, - int pixelWidth, - int pixelHeight - ) { - if (!resourceID.isValid) - { - throw new ArgumentException("A resource identity is required.", nameof(resourceID)); - } - ArgumentNullException.ThrowIfNull(material); - ArgumentNullException.ThrowIfNull(artifact); - ArgumentNullException.ThrowIfNull(definition); - ArgumentNullException.ThrowIfNull(diagnostics); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelWidth); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pixelHeight); - this.resourceID = resourceID; - this.material = material; - this.artifact = artifact; - this.definition = definition; - this.diagnostics = diagnostics; - this.pixelWidth = pixelWidth; - this.pixelHeight = pixelHeight; - } - - /// - /// Gets the publication scope released by the host when this preview closes. - /// - public RenderPersistentResourceID resourceID { get; } - - /// - /// Gets the invocation-local Material values. - /// - public MaterialAsset material { get; } - - /// - /// Gets the complete immutable GPU candidate. - /// - public RenderShaderArtifact artifact { get; } - - /// - /// Gets the candidate's exact contract, not the latest uncompiled source interface. - /// - public ShaderDefinition definition { get; } - - /// - /// Gets the host-owned, isolated diagnostic producer. - /// - public IDiagnosticReporter diagnostics { get; } - - /// - /// Gets target width in physical pixels. - /// - public int pixelWidth { get; } - - /// - /// Gets target height in physical pixels. - /// - public int pixelHeight { get; } -} diff --git a/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProviderAttribute.cs b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProviderAttribute.cs new file mode 100644 index 000000000..cfec19d45 --- /dev/null +++ b/src/composition/editor/features/Inno.Editor.Shaders/Previews/ShaderPreviewProviderAttribute.cs @@ -0,0 +1,20 @@ +using System; + +namespace Inno.Editor.Shaders; + +/// +/// Associates a reloadable preview implementation with one open Shader contract. +/// +/// +/// Non-empty domain-owned contract identity. +/// +[AttributeUsage(AttributeTargets.Class, Inherited = false)] +public sealed class ShaderPreviewProviderAttribute(string contractID) : Attribute +{ + /// + /// Gets the non-empty Shader contract consumed by this preview. + /// + public string contractID { get; } = string.IsNullOrWhiteSpace(contractID) + ? throw new ArgumentException("A preview contract is required.", nameof(contractID)) + : contractID; +} diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistic.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistic.cs new file mode 100644 index 000000000..7ccd74d80 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistic.cs @@ -0,0 +1,100 @@ +using System; + +namespace Inno.Editor.Core; + +/// +/// Describes one immutable, presentation-ready statistic without retaining provider instances or types. +/// +public sealed class EditorStatistic +{ + /// + /// Creates one statistic contribution. + /// + /// + /// Globally stable statistic identity used for replacement within a frame. + /// + /// + /// Stable visual group identity. + /// + /// + /// User-facing group heading. + /// + /// + /// User-facing metric label. + /// + /// + /// Already formatted user-facing value. + /// + /// + /// Ascending group presentation order. + /// + /// + /// Ascending metric order within the group. + /// + /// + /// Thrown when an identifier, group name, label, or value is empty. + /// + public EditorStatistic( + EditorStatisticID id, + EditorStatisticGroupID groupID, + string groupName, + string label, + string value, + int groupOrder = 0, + int order = 0 + ) { + if (!id.isValid) + { + throw new ArgumentException("A statistic ID is required.", nameof(id)); + } + if (!groupID.isValid) + { + throw new ArgumentException("A statistic group ID is required.", nameof(groupID)); + } + ArgumentException.ThrowIfNullOrWhiteSpace(groupName); + ArgumentException.ThrowIfNullOrWhiteSpace(label); + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.id = id; + this.groupID = groupID; + this.groupName = groupName.Trim(); + this.label = label.Trim(); + this.value = value.Trim(); + this.groupOrder = groupOrder; + this.order = order; + } + + /// + /// Gets the globally stable statistic identity. + /// + public EditorStatisticID id { get; } + + /// + /// Gets the stable visual group identity. + /// + public EditorStatisticGroupID groupID { get; } + + /// + /// Gets the user-facing group heading. + /// + public string groupName { get; } + + /// + /// Gets the user-facing metric label. + /// + public string label { get; } + + /// + /// Gets the presentation-ready value. + /// + public string value { get; } + + /// + /// Gets ascending group presentation order. + /// + public int groupOrder { get; } + + /// + /// Gets ascending metric order within the group. + /// + public int order { get; } +} diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticGroupID.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticGroupID.cs new file mode 100644 index 000000000..28b660ef6 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticGroupID.cs @@ -0,0 +1,42 @@ +using System; + +namespace Inno.Editor.Core; + +/// +/// Identifies one visual group in the editor statistics presentation. +/// +public readonly record struct EditorStatisticGroupID +{ + /// + /// Creates a globally stable statistic-group identifier. + /// + /// + /// Non-empty globally stable identity. + /// + /// + /// Thrown when is empty. + /// + public EditorStatisticGroupID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value.Trim(); + } + + /// + /// Gets the globally stable identity. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value ?? string.Empty; +} diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticID.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticID.cs new file mode 100644 index 000000000..1e2543975 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatisticID.cs @@ -0,0 +1,42 @@ +using System; + +namespace Inno.Editor.Core; + +/// +/// Identifies one editor statistic across panels, modules, and reloadable extensions. +/// +public readonly record struct EditorStatisticID +{ + /// + /// Creates a globally stable statistic identifier. + /// + /// + /// Non-empty globally stable identity. + /// + /// + /// Thrown when is empty. + /// + public EditorStatisticID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value.Trim(); + } + + /// + /// Gets the globally stable identity. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value ?? string.Empty; +} diff --git a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs index 4d7cc1788..2b322541e 100644 --- a/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs +++ b/src/composition/editor/framework/Inno.Editor.Core/Runtime/EditorStatistics.cs @@ -4,181 +4,6 @@ namespace Inno.Editor.Core; -/// -/// Identifies one editor statistic across panels, modules, and reloadable extensions. -/// -public readonly record struct EditorStatisticID -{ - /// - /// Creates a globally stable statistic identifier. - /// - /// - /// Non-empty globally stable identity. - /// - /// - /// Thrown when is empty. - /// - public EditorStatisticID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value.Trim(); - } - - /// - /// Gets the globally stable identity. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value ?? string.Empty; -} - -/// -/// Identifies one visual group in the editor statistics presentation. -/// -public readonly record struct EditorStatisticGroupID -{ - /// - /// Creates a globally stable statistic-group identifier. - /// - /// - /// Non-empty globally stable identity. - /// - /// - /// Thrown when is empty. - /// - public EditorStatisticGroupID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value.Trim(); - } - - /// - /// Gets the globally stable identity. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value ?? string.Empty; -} - -/// -/// Describes one immutable, presentation-ready statistic without retaining provider instances or types. -/// -public sealed class EditorStatistic -{ - /// - /// Creates one statistic contribution. - /// - /// - /// Globally stable statistic identity used for replacement within a frame. - /// - /// - /// Stable visual group identity. - /// - /// - /// User-facing group heading. - /// - /// - /// User-facing metric label. - /// - /// - /// Already formatted user-facing value. - /// - /// - /// Ascending group presentation order. - /// - /// - /// Ascending metric order within the group. - /// - /// - /// Thrown when an identifier, group name, label, or value is empty. - /// - public EditorStatistic( - EditorStatisticID id, - EditorStatisticGroupID groupID, - string groupName, - string label, - string value, - int groupOrder = 0, - int order = 0 - ) { - if (!id.isValid) - { - throw new ArgumentException("A statistic ID is required.", nameof(id)); - } - if (!groupID.isValid) - { - throw new ArgumentException("A statistic group ID is required.", nameof(groupID)); - } - ArgumentException.ThrowIfNullOrWhiteSpace(groupName); - ArgumentException.ThrowIfNullOrWhiteSpace(label); - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.id = id; - this.groupID = groupID; - this.groupName = groupName.Trim(); - this.label = label.Trim(); - this.value = value.Trim(); - this.groupOrder = groupOrder; - this.order = order; - } - - /// - /// Gets the globally stable statistic identity. - /// - public EditorStatisticID id { get; } - - /// - /// Gets the stable visual group identity. - /// - public EditorStatisticGroupID groupID { get; } - - /// - /// Gets the user-facing group heading. - /// - public string groupName { get; } - - /// - /// Gets the user-facing metric label. - /// - public string label { get; } - - /// - /// Gets the presentation-ready value. - /// - public string value { get; } - - /// - /// Gets ascending group presentation order. - /// - public int groupOrder { get; } - - /// - /// Gets ascending metric order within the group. - /// - public int order { get; } -} - /// /// Exchanges frame-scoped, reload-safe statistics between independent editor features and viewers. /// diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphClipboardData.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphClipboardData.cs new file mode 100644 index 000000000..f3bb03bc0 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphClipboardData.cs @@ -0,0 +1,28 @@ +using Inno.Core.Graphs; + +namespace Inno.Editor.Graph; + +/// +/// Contains a neutral copied node fragment suitable for graph clipboard operations. +/// +public sealed class GraphClipboardData +{ + private readonly GraphDocument m_fragment; + + internal GraphClipboardData(GraphDocument fragment) + { + m_fragment = fragment; + } + + /// + /// Gets the copied node count. + /// + public int nodeCount => m_fragment.nodes.Count; + + /// + /// Gets the copied connection count whose endpoints both belong to the fragment. + /// + public int edgeCount => m_fragment.edges.Count; + + internal GraphDocument CloneFragment() => m_fragment.Clone(); +} diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs index 1c958a6fd..9a3c38930 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphDocumentController.cs @@ -8,31 +8,6 @@ namespace Inno.Editor.Graph; -/// -/// Contains a neutral copied node fragment suitable for graph clipboard operations. -/// -public sealed class GraphClipboardData -{ - private readonly GraphDocument m_fragment; - - internal GraphClipboardData(GraphDocument fragment) - { - m_fragment = fragment; - } - - /// - /// Gets the copied node count. - /// - public int nodeCount => m_fragment.nodes.Count; - - /// - /// Gets the copied connection count whose endpoints both belong to the fragment. - /// - public int edgeCount => m_fragment.edges.Count; - - internal GraphDocument CloneFragment() => m_fragment.Clone(); -} - /// /// Applies neutral graph edits atomically and records every data mutation in reload-safe Editor History. /// diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs deleted file mode 100644 index b47be328e..000000000 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistory.cs +++ /dev/null @@ -1,378 +0,0 @@ -using System; -using System.Buffers.Binary; -using System.Diagnostics; -using System.IO; -using System.Text; -using Inno.Core.Graphs; -using Inno.Core.Serialization; -using Inno.Editor.Interactions; - -namespace Inno.Editor.Graph; - -internal static class GraphHistoryDocumentCodec -{ - /// - /// Encodes the supplied value into deterministic structured data. - /// - /// - /// The document consumed by encode; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The serialization consumed by encode; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public static byte[] Encode( - GraphDocument document, - SerializationRegistry serialization - ) => GraphDocumentCodec.Encode(document, serialization); - - /// - /// Decodes deterministic structured data into a validated value. - /// - /// - /// The complete immutable byte payload consumed by this operation. - /// - /// - /// The serialization consumed by decode; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The validated graph document that represents the completed operation. - /// - public static GraphDocument Decode( - ReadOnlySpan bytes, - SerializationRegistry serialization - ) => GraphDocumentCodec.Decode(bytes, serialization); -} - -internal sealed record GraphHistoryData( - Guid documentID, - byte[] before, - byte[] after, - long timestamp -) { - /// - /// The c kind value used as part of this type's public representation. - /// - public const string C_KIND = "editor.graph.document"; - - private static readonly UTF8Encoding UTF8 = new(false, true); - - /// - /// Encodes the supplied value into deterministic structured data. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public byte[] Encode() - { - byte[] id = UTF8.GetBytes(documentID.ToString("D")); - var result = new byte[checked((sizeof(int) * 3) + sizeof(long) + id.Length + before.Length + after.Length)]; - Span span = result; - BinaryPrimitives.WriteInt32LittleEndian(span, id.Length); - id.CopyTo(span[sizeof(int)..]); - int offset = sizeof(int) + id.Length; - BinaryPrimitives.WriteInt32LittleEndian(span[offset..], before.Length); - offset += sizeof(int); - before.CopyTo(span[offset..]); - offset += before.Length; - BinaryPrimitives.WriteInt32LittleEndian(span[offset..], after.Length); - offset += sizeof(int); - after.CopyTo(span[offset..]); - offset += after.Length; - BinaryPrimitives.WriteInt64LittleEndian(span[offset..], timestamp); - return result; - } - - /// - /// Creates and validates a caller-owned change value. - /// - /// - /// The document id text validated by the create change operation. - /// - /// - /// The before consumed by create change; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The after consumed by create change; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The merge key text validated by the create change operation. - /// - /// - /// The validated editor history change that represents the completed operation. - /// - public static EditorHistoryChange CreateChange( - Guid documentID, - ReadOnlySpan before, - ReadOnlySpan after, - string? mergeKey - ) { - var data = new GraphHistoryData(documentID, before.ToArray(), after.ToArray(), Stopwatch.GetTimestamp()); - return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(data.Encode()), mergeKey); - } - - /// - /// Decodes deterministic structured data into a validated value. - /// - /// - /// The payload consumed by decode; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The serialization consumed by decode; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The validated graph history data that represents the completed operation. - /// - public static GraphHistoryData Decode( - ReadOnlySpan payload, - SerializationRegistry serialization - ) { - int offset = 0; - int idLength = ReadLength(payload, ref offset); - Guid id = Guid.ParseExact(UTF8.GetString(ReadSlice(payload, ref offset, idLength)), "D"); - if (id == Guid.Empty) - { - throw new InvalidDataException("Graph history requires a persistent document identity."); - } - int beforeLength = ReadLength(payload, ref offset); - byte[] before = ReadSlice(payload, ref offset, beforeLength).ToArray(); - int afterLength = ReadLength(payload, ref offset); - byte[] after = ReadSlice(payload, ref offset, afterLength).ToArray(); - if (payload.Length - offset != sizeof(long)) - { - throw new InvalidDataException("Graph History payload has an invalid timestamp boundary."); - } - - long timestamp = BinaryPrimitives.ReadInt64LittleEndian(payload[offset..]); - _ = GraphHistoryDocumentCodec.Decode(before, serialization); - _ = GraphHistoryDocumentCodec.Decode(after, serialization); - return new GraphHistoryData(id, before, after, timestamp); - } - - private static int ReadLength( - ReadOnlySpan payload, - ref int offset - ) { - if (payload.Length - offset < sizeof(int)) - { - throw new InvalidDataException("Graph History payload is truncated."); - } - - int length = BinaryPrimitives.ReadInt32LittleEndian(payload[offset..]); - offset += sizeof(int); - if (length < 0 || length > payload.Length - offset) - { - throw new InvalidDataException("Graph History payload contains an invalid length."); - } - - return length; - } - - private static ReadOnlySpan ReadSlice( - ReadOnlySpan payload, - ref int offset, - int length - ) { - ReadOnlySpan result = payload.Slice(offset, length); - offset += length; - return result; - } -} - -internal readonly record struct GraphHistoryTransitionResult( - EditorHistoryResult result, - bool stateIntegrityLost -); - -internal static class GraphHistoryTransition -{ - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The module consumed by apply; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated graph history transition result that represents the completed operation. - /// - public static GraphHistoryTransitionResult Apply( - GraphEditorModule module, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - GraphHistoryData data = GraphHistoryData.Decode(change.payload.ReadBytes(), module.serialization); - if (!module.TryResolve(data.documentID, out GraphDocumentSession? session) || session is null) - { - return new GraphHistoryTransitionResult( - EditorHistoryResult.Failure($"Graph document '{data.documentID}' is not open."), - false - ); - } - - GraphDocument original = session.document.Clone(); - try - { - session.document.ReplaceContents( - GraphHistoryDocumentCodec.Decode( - direction == EditorHistoryDirection.Undo ? data.before : data.after, - module.serialization - ) - ); - session.revision++; - session.isDirty = true; - return new GraphHistoryTransitionResult(EditorHistoryResult.Success(), false); - } - catch (Exception exception) - { - try - { - session.document.ReplaceContents(original); - } - catch (Exception rollbackException) - { - return new GraphHistoryTransitionResult( - EditorHistoryResult.Failure( - $"Graph transition failed: {exception.Message} Rollback failed: {rollbackException.Message}" - ), - true - ); - } - - return new GraphHistoryTransitionResult(EditorHistoryResult.Failure(exception.Message), false); - } - } - catch (Exception exception) - { - return new GraphHistoryTransitionResult( - EditorHistoryResult.Failure($"Graph History payload is invalid: {exception.Message}"), - false - ); - } - } -} - -[EditorHistoryHandler(GraphHistoryData.C_KIND)] -internal sealed class GraphHistoryHandler(GraphEditorModule module) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - _ = context; - _ = direction; - try - { - GraphHistoryData data = GraphHistoryData.Decode(change.payload.ReadBytes(), module.serialization); - return module.TryResolve(data.documentID, out _) - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable($"Graph document '{data.documentID}' is not open."); - } - catch (Exception exception) - { - return EditorHistoryAvailability.Unavailable($"Graph History payload is invalid: {exception.Message}"); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - _ = context; - GraphHistoryTransitionResult transition = GraphHistoryTransition.Apply(module, change, direction); - return transition.stateIntegrityLost - ? StateIntegrityFailure(transition.result.message) - : transition.result; - } - - /// - /// Attempts to merge without changing state when the operation cannot complete. - /// - /// - /// The earlier history payload considered for coalescing. - /// - /// - /// The later history payload considered for coalescing. - /// - /// - /// Receives the neutral coalesced payload when merging succeeds. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - protected override bool TryMerge( - EditorHistoryChange older, - EditorHistoryChange newer, - out EditorHistoryChange? merged - ) { - merged = null; - if (older.mergeKey is null || !StringComparer.Ordinal.Equals(older.mergeKey, newer.mergeKey)) - { - return false; - } - - try - { - GraphHistoryData previous = GraphHistoryData.Decode(older.payload.ReadBytes(), module.serialization); - GraphHistoryData current = GraphHistoryData.Decode(newer.payload.ReadBytes(), module.serialization); - if (previous.documentID != current.documentID - || Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > 1.0 - ) { - return false; - } - - var combined = new GraphHistoryData(previous.documentID, previous.before, current.after, current.timestamp); - merged = new EditorHistoryChange( - GraphHistoryData.C_KIND, - EditorHistoryPayload.FromBytes(combined.Encode()), - older.mergeKey - ); - return true; - } - catch - { - return false; - } - } -} diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryData.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryData.cs new file mode 100644 index 000000000..74eca1ac4 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryData.cs @@ -0,0 +1,144 @@ +using System; +using System.Buffers.Binary; +using System.Diagnostics; +using System.IO; +using System.Text; +using Inno.Core.Serialization; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Graph; + +internal sealed record GraphHistoryData( + Guid documentID, + byte[] before, + byte[] after, + long timestamp +) { + /// + /// The c kind value used as part of this type's public representation. + /// + public const string C_KIND = "editor.graph.document"; + + private static readonly UTF8Encoding UTF8 = new(false, true); + + /// + /// Encodes the supplied value into deterministic structured data. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public byte[] Encode() + { + byte[] id = UTF8.GetBytes(documentID.ToString("D")); + var result = new byte[checked((sizeof(int) * 3) + sizeof(long) + id.Length + before.Length + after.Length)]; + Span span = result; + BinaryPrimitives.WriteInt32LittleEndian(span, id.Length); + id.CopyTo(span[sizeof(int)..]); + int offset = sizeof(int) + id.Length; + BinaryPrimitives.WriteInt32LittleEndian(span[offset..], before.Length); + offset += sizeof(int); + before.CopyTo(span[offset..]); + offset += before.Length; + BinaryPrimitives.WriteInt32LittleEndian(span[offset..], after.Length); + offset += sizeof(int); + after.CopyTo(span[offset..]); + offset += after.Length; + BinaryPrimitives.WriteInt64LittleEndian(span[offset..], timestamp); + return result; + } + + /// + /// Creates and validates a caller-owned change value. + /// + /// + /// The document id text validated by the create change operation. + /// + /// + /// The before consumed by create change; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The after consumed by create change; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The merge key text validated by the create change operation. + /// + /// + /// The validated editor history change that represents the completed operation. + /// + public static EditorHistoryChange CreateChange( + Guid documentID, + ReadOnlySpan before, + ReadOnlySpan after, + string? mergeKey + ) { + var data = new GraphHistoryData(documentID, before.ToArray(), after.ToArray(), Stopwatch.GetTimestamp()); + return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(data.Encode()), mergeKey); + } + + /// + /// Decodes deterministic structured data into a validated value. + /// + /// + /// The payload consumed by decode; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The serialization consumed by decode; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The validated graph history data that represents the completed operation. + /// + public static GraphHistoryData Decode( + ReadOnlySpan payload, + SerializationRegistry serialization + ) { + int offset = 0; + int idLength = ReadLength(payload, ref offset); + Guid id = Guid.ParseExact(UTF8.GetString(ReadSlice(payload, ref offset, idLength)), "D"); + if (id == Guid.Empty) + { + throw new InvalidDataException("Graph history requires a persistent document identity."); + } + int beforeLength = ReadLength(payload, ref offset); + byte[] before = ReadSlice(payload, ref offset, beforeLength).ToArray(); + int afterLength = ReadLength(payload, ref offset); + byte[] after = ReadSlice(payload, ref offset, afterLength).ToArray(); + if (payload.Length - offset != sizeof(long)) + { + throw new InvalidDataException("Graph History payload has an invalid timestamp boundary."); + } + + long timestamp = BinaryPrimitives.ReadInt64LittleEndian(payload[offset..]); + _ = GraphHistoryDocumentCodec.Decode(before, serialization); + _ = GraphHistoryDocumentCodec.Decode(after, serialization); + return new GraphHistoryData(id, before, after, timestamp); + } + + private static int ReadLength( + ReadOnlySpan payload, + ref int offset + ) { + if (payload.Length - offset < sizeof(int)) + { + throw new InvalidDataException("Graph History payload is truncated."); + } + + int length = BinaryPrimitives.ReadInt32LittleEndian(payload[offset..]); + offset += sizeof(int); + if (length < 0 || length > payload.Length - offset) + { + throw new InvalidDataException("Graph History payload contains an invalid length."); + } + + return length; + } + + private static ReadOnlySpan ReadSlice( + ReadOnlySpan payload, + ref int offset, + int length + ) { + ReadOnlySpan result = payload.Slice(offset, length); + offset += length; + return result; + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryDocumentCodec.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryDocumentCodec.cs new file mode 100644 index 000000000..6390b3076 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryDocumentCodec.cs @@ -0,0 +1,42 @@ +using System; +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Editor.Graph; + +internal static class GraphHistoryDocumentCodec +{ + /// + /// Encodes the supplied value into deterministic structured data. + /// + /// + /// The document consumed by encode; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The serialization consumed by encode; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public static byte[] Encode( + GraphDocument document, + SerializationRegistry serialization + ) => GraphDocumentCodec.Encode(document, serialization); + + /// + /// Decodes deterministic structured data into a validated value. + /// + /// + /// The complete immutable byte payload consumed by this operation. + /// + /// + /// The serialization consumed by decode; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The validated graph document that represents the completed operation. + /// + public static GraphDocument Decode( + ReadOnlySpan bytes, + SerializationRegistry serialization + ) => GraphDocumentCodec.Decode(bytes, serialization); +} diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs new file mode 100644 index 000000000..9a789dc61 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs @@ -0,0 +1,121 @@ +using System; +using System.Diagnostics; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Graph; + +[EditorHistoryHandler(GraphHistoryData.C_KIND)] +internal sealed class GraphHistoryHandler(GraphEditorModule module) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + _ = context; + _ = direction; + try + { + GraphHistoryData data = GraphHistoryData.Decode(change.payload.ReadBytes(), module.serialization); + return module.TryResolve(data.documentID, out _) + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable($"Graph document '{data.documentID}' is not open."); + } + catch (Exception exception) + { + return EditorHistoryAvailability.Unavailable($"Graph History payload is invalid: {exception.Message}"); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + _ = context; + GraphHistoryTransitionResult transition = GraphHistoryTransition.Apply(module, change, direction); + return transition.stateIntegrityLost + ? StateIntegrityFailure(transition.result.message) + : transition.result; + } + + /// + /// Attempts to merge without changing state when the operation cannot complete. + /// + /// + /// The earlier history payload considered for coalescing. + /// + /// + /// The later history payload considered for coalescing. + /// + /// + /// Receives the neutral coalesced payload when merging succeeds. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + protected override bool TryMerge( + EditorHistoryChange older, + EditorHistoryChange newer, + out EditorHistoryChange? merged + ) { + merged = null; + if (older.mergeKey is null || !StringComparer.Ordinal.Equals(older.mergeKey, newer.mergeKey)) + { + return false; + } + + try + { + GraphHistoryData previous = GraphHistoryData.Decode(older.payload.ReadBytes(), module.serialization); + GraphHistoryData current = GraphHistoryData.Decode(newer.payload.ReadBytes(), module.serialization); + if (previous.documentID != current.documentID + || Stopwatch.GetElapsedTime(previous.timestamp, current.timestamp).TotalSeconds > 1.0 + ) { + return false; + } + + var combined = new GraphHistoryData(previous.documentID, previous.before, current.after, current.timestamp); + merged = new EditorHistoryChange( + GraphHistoryData.C_KIND, + EditorHistoryPayload.FromBytes(combined.Encode()), + older.mergeKey + ); + return true; + } + catch + { + return false; + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryTransition.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryTransition.cs new file mode 100644 index 000000000..b85b5d653 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryTransition.cs @@ -0,0 +1,85 @@ +using System; +using Inno.Core.Graphs; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Graph; + +internal static class GraphHistoryTransition +{ + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The module consumed by apply; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated graph history transition result that represents the completed operation. + /// + public static GraphHistoryTransitionResult Apply( + GraphEditorModule module, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + GraphHistoryData data = GraphHistoryData.Decode(change.payload.ReadBytes(), module.serialization); + if (!module.TryResolve(data.documentID, out GraphDocumentSession? session) || session is null) + { + return new GraphHistoryTransitionResult( + EditorHistoryResult.Failure($"Graph document '{data.documentID}' is not open."), + false + ); + } + + GraphDocument original = session.document.Clone(); + try + { + session.document.ReplaceContents( + GraphHistoryDocumentCodec.Decode( + direction == EditorHistoryDirection.Undo ? data.before : data.after, + module.serialization + ) + ); + session.revision++; + session.isDirty = true; + return new GraphHistoryTransitionResult(EditorHistoryResult.Success(), false); + } + catch (Exception exception) + { + try + { + session.document.ReplaceContents(original); + } + catch (Exception rollbackException) + { + return new GraphHistoryTransitionResult( + EditorHistoryResult.Failure( + $"Graph transition failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ), + true + ); + } + + return new GraphHistoryTransitionResult(EditorHistoryResult.Failure(exception.Message), false); + } + } + catch (Exception exception) + { + return new GraphHistoryTransitionResult( + EditorHistoryResult.Failure($"Graph History payload is invalid: {exception.Message}"), + false + ); + } + } +} + +internal readonly record struct GraphHistoryTransitionResult( + EditorHistoryResult result, + bool stateIntegrityLost +); diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs deleted file mode 100644 index 698502ca6..000000000 --- a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/BuiltInInspectorAttributeDrawers.cs +++ /dev/null @@ -1,273 +0,0 @@ -using System; -using System.Collections; -using System.Globalization; -using System.Numerics; -using System.Reflection; -using Inno.Core.Serialization; -using Inno.Editor.Annotations; -using Inno.Editor.ImGui; -using Inno.Editor.ImGui.ImGuiWidget; - -using EditorUI = Inno.Editor.ImGui.EditorUISession; -using Gui = Inno.Editor.ImGui.ImGui; - -namespace Inno.Editor.Inspection; - -[InspectorAttributeDrawer(typeof(HeaderAttribute))] -internal sealed class HeaderInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Renders the section heading before its annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void DrawBefore(InspectorAttributeDrawContext context) - { - HeaderAttribute header = (HeaderAttribute)context.attribute; - EditorUI.current.widgets.SectionHeader(header.title, header.description); - } -} - -[InspectorAttributeDrawer(typeof(TextAttribute))] -internal sealed class TextInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Renders persistent explanatory text before its annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void DrawBefore(InspectorAttributeDrawContext context) - { - string text = ((TextAttribute)context.attribute).text; - Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.textDisabled); - try - { - EditorUI.current.widgets.WrappedText(text); - } - finally - { - Gui.PopStyleColor(); - } - } -} - -[InspectorAttributeDrawer(typeof(SpaceAttribute))] -internal sealed class SpaceInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Renders the requested vertical spacing before its annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void DrawBefore(InspectorAttributeDrawContext context) - { - float height = ((SpaceAttribute)context.attribute).height; - Gui.Dummy(new Vector2(0f, height)); - } -} - -[InspectorAttributeDrawer(typeof(TooltipAttribute))] -internal sealed class TooltipInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Applies tooltip text to the annotated property row. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) => context.tooltip = ((TooltipAttribute)context.attribute).text; -} - -[InspectorAttributeDrawer(typeof(InspectorNameAttribute))] -internal sealed class NameInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Replaces the default serialized member label. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) => context.label = ((InspectorNameAttribute)context.attribute).name; -} - -[InspectorAttributeDrawer(typeof(RangeAttribute))] -internal sealed class RangeInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Applies inclusive numeric slider bounds to the annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) - { - RangeAttribute range = (RangeAttribute)context.attribute; - context.minimum = range.minimum; - context.maximum = range.maximum; - } -} - -[InspectorAttributeDrawer(typeof(InspectorReadOnlyAttribute))] -internal sealed class ReadOnlyInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Disables assignment for the annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) => context.isReadOnly = true; -} - -[InspectorAttributeDrawer(typeof(ShowIfAttribute))] -internal sealed class ShowIfInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Hides the annotated property unless its sibling condition succeeds. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) - { - ShowIfAttribute condition = (ShowIfAttribute)context.attribute; - context.isVisible &= InspectorConditionEvaluator.Evaluate( - context.GetSiblingValue(condition.memberName), - condition.condition, - condition.expectedValue - ); - } -} - -[InspectorAttributeDrawer(typeof(HideIfAttribute))] -internal sealed class HideIfInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Hides the annotated property when its sibling condition succeeds. - /// - /// - /// Active attribute drawing context. - /// - public void Update(InspectorAttributeDrawContext context) - { - HideIfAttribute condition = (HideIfAttribute)context.attribute; - context.isVisible &= !InspectorConditionEvaluator.Evaluate( - context.GetSiblingValue(condition.memberName), - condition.condition, - condition.expectedValue - ); - } -} - -[InspectorAttributeDrawer(typeof(HelpBoxAttribute))] -internal sealed class HelpBoxInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - /// - /// Renders a conditional diagnostic message before its annotated property. - /// - /// - /// Active attribute drawing context. - /// - public void DrawBefore(InspectorAttributeDrawContext context) - { - HelpBoxAttribute help = (HelpBoxAttribute)context.attribute; - if (!string.IsNullOrWhiteSpace(help.conditionMember) - && !InspectorConditionEvaluator.Evaluate( - context.GetSiblingValue(help.conditionMember), - help.condition, - help.expectedValue - ) - ) { - return; - } - - Vector4 color = help.messageType switch - { - InspectorMessageType.Warning => EditorPalette.warning, - InspectorMessageType.Error => EditorPalette.error, - _ => new Vector4(0.42f, 0.66f, 0.88f, EditorPalette.C_OPACITY_OPAQUE) - }; - string icon = help.messageType switch - { - InspectorMessageType.Warning => ImGuiIcon.C_TRIANGLE_EXCLAMATION, - InspectorMessageType.Error => ImGuiIcon.C_CIRCLE_XMARK, - _ => ImGuiIcon.C_CIRCLE_INFO - }; - EditorUI.current.widgets.HelpBox(help.text, icon, color); - } -} - -internal static class InspectorConditionEvaluator -{ - internal static bool Evaluate( - object? value, - InspectorCondition condition, - object? expected - ) => condition switch - { - InspectorCondition.Truthy => IsTruthy(value), - InspectorCondition.Falsy => !IsTruthy(value), - InspectorCondition.Equal => AreEqual(value, expected), - InspectorCondition.NotEqual => !AreEqual(value, expected), - InspectorCondition.Null => value is null, - InspectorCondition.NotNull => value is not null, - InspectorCondition.Assigned => IsAssigned(value), - InspectorCondition.NotAssigned => !IsAssigned(value), - _ => throw new ArgumentOutOfRangeException(nameof(condition), condition, "Unknown Inspector condition.") - }; - - private static bool IsTruthy(object? value) - => value switch - { - null => false, - bool boolean => boolean, - string text => !string.IsNullOrWhiteSpace(text), - ICollection collection => collection.Count > 0, - _ => true - }; - - private static bool IsAssigned(object? value) - { - if (value is null) - { - return false; - } - PropertyInfo? property = value - .GetType() - .GetProperty("isAssigned", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - return property?.PropertyType == typeof(bool) && property.GetIndexParameters().Length == 0 - ? (bool)(property.GetValue(value) ?? false) - : true; - } - - private static bool AreEqual( - object? value, - object? expected - ) { - if (Equals(value, expected)) - { - return true; - } - if (value is null || expected is null) - { - return false; - } - Type valueType = value.GetType(); - try - { - object converted = valueType.IsEnum - ? expected is string name - ? Enum.Parse(valueType, name, ignoreCase: false) - : Enum.ToObject(valueType, expected) - : Convert.ChangeType(expected, valueType, CultureInfo.InvariantCulture); - return Equals(value, converted); - } - catch (Exception exception) when (exception is ArgumentException or InvalidCastException or FormatException or OverflowException) - { - return false; - } - } -} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HeaderInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HeaderInspectorAttributeDrawer.cs new file mode 100644 index 000000000..00783c4f1 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HeaderInspectorAttributeDrawer.cs @@ -0,0 +1,21 @@ +using Inno.Editor.Annotations; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(HeaderAttribute))] +internal sealed class HeaderInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Renders the section heading before its annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void DrawBefore(InspectorAttributeDrawContext context) + { + HeaderAttribute header = (HeaderAttribute)context.attribute; + EditorUI.current.widgets.SectionHeader(header.title, header.description); + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HelpBoxInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HelpBoxInspectorAttributeDrawer.cs new file mode 100644 index 000000000..15009155c --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HelpBoxInspectorAttributeDrawer.cs @@ -0,0 +1,45 @@ +using System.Numerics; +using Inno.Editor.Annotations; +using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(HelpBoxAttribute))] +internal sealed class HelpBoxInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Renders a conditional diagnostic message before its annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void DrawBefore(InspectorAttributeDrawContext context) + { + HelpBoxAttribute help = (HelpBoxAttribute)context.attribute; + if (!string.IsNullOrWhiteSpace(help.conditionMember) + && !InspectorConditionEvaluator.Evaluate( + context.GetSiblingValue(help.conditionMember), + help.condition, + help.expectedValue + ) + ) { + return; + } + + Vector4 color = help.messageType switch + { + InspectorMessageType.Warning => EditorPalette.warning, + InspectorMessageType.Error => EditorPalette.error, + _ => new Vector4(0.42f, 0.66f, 0.88f, EditorPalette.C_OPACITY_OPAQUE) + }; + string icon = help.messageType switch + { + InspectorMessageType.Warning => ImGuiIcon.C_TRIANGLE_EXCLAMATION, + InspectorMessageType.Error => ImGuiIcon.C_CIRCLE_XMARK, + _ => ImGuiIcon.C_CIRCLE_INFO + }; + EditorUI.current.widgets.HelpBox(help.text, icon, color); + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HideIfInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HideIfInspectorAttributeDrawer.cs new file mode 100644 index 000000000..b2037a89f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/HideIfInspectorAttributeDrawer.cs @@ -0,0 +1,23 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(HideIfAttribute))] +internal sealed class HideIfInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Hides the annotated property when its sibling condition succeeds. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) + { + HideIfAttribute condition = (HideIfAttribute)context.attribute; + context.isVisible &= !InspectorConditionEvaluator.Evaluate( + context.GetSiblingValue(condition.memberName), + condition.condition, + condition.expectedValue + ); + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorConditionEvaluator.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorConditionEvaluator.cs new file mode 100644 index 000000000..c1741eb06 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/InspectorConditionEvaluator.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections; +using System.Globalization; +using System.Reflection; +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +internal static class InspectorConditionEvaluator +{ + internal static bool Evaluate( + object? value, + InspectorCondition condition, + object? expected + ) => condition switch + { + InspectorCondition.Truthy => IsTruthy(value), + InspectorCondition.Falsy => !IsTruthy(value), + InspectorCondition.Equal => AreEqual(value, expected), + InspectorCondition.NotEqual => !AreEqual(value, expected), + InspectorCondition.Null => value is null, + InspectorCondition.NotNull => value is not null, + InspectorCondition.Assigned => IsAssigned(value), + InspectorCondition.NotAssigned => !IsAssigned(value), + _ => throw new ArgumentOutOfRangeException(nameof(condition), condition, "Unknown Inspector condition.") + }; + + private static bool IsTruthy(object? value) + => value switch + { + null => false, + bool boolean => boolean, + string text => !string.IsNullOrWhiteSpace(text), + ICollection collection => collection.Count > 0, + _ => true + }; + + private static bool IsAssigned(object? value) + { + if (value is null) + { + return false; + } + PropertyInfo? property = value + .GetType() + .GetProperty("isAssigned", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + return property?.PropertyType == typeof(bool) && property.GetIndexParameters().Length == 0 + ? (bool)(property.GetValue(value) ?? false) + : true; + } + + private static bool AreEqual( + object? value, + object? expected + ) { + if (Equals(value, expected)) + { + return true; + } + if (value is null || expected is null) + { + return false; + } + Type valueType = value.GetType(); + try + { + object converted = valueType.IsEnum + ? expected is string name + ? Enum.Parse(valueType, name, ignoreCase: false) + : Enum.ToObject(valueType, expected) + : Convert.ChangeType(expected, valueType, CultureInfo.InvariantCulture); + return Equals(value, converted); + } + catch (Exception exception) when (exception is ArgumentException or InvalidCastException or FormatException or OverflowException) + { + return false; + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/NameInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/NameInspectorAttributeDrawer.cs new file mode 100644 index 000000000..56b229fbb --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/NameInspectorAttributeDrawer.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(InspectorNameAttribute))] +internal sealed class NameInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Replaces the default serialized member label. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) => context.label = ((InspectorNameAttribute)context.attribute).name; +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/RangeInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/RangeInspectorAttributeDrawer.cs new file mode 100644 index 000000000..f5db57ad9 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/RangeInspectorAttributeDrawer.cs @@ -0,0 +1,20 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(RangeAttribute))] +internal sealed class RangeInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Applies inclusive numeric slider bounds to the annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) + { + RangeAttribute range = (RangeAttribute)context.attribute; + context.minimum = range.minimum; + context.maximum = range.maximum; + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ReadOnlyInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ReadOnlyInspectorAttributeDrawer.cs new file mode 100644 index 000000000..a9ba5be9c --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ReadOnlyInspectorAttributeDrawer.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(InspectorReadOnlyAttribute))] +internal sealed class ReadOnlyInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Disables assignment for the annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) => context.isReadOnly = true; +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ShowIfInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ShowIfInspectorAttributeDrawer.cs new file mode 100644 index 000000000..af6b1528b --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/ShowIfInspectorAttributeDrawer.cs @@ -0,0 +1,23 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(ShowIfAttribute))] +internal sealed class ShowIfInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Hides the annotated property unless its sibling condition succeeds. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) + { + ShowIfAttribute condition = (ShowIfAttribute)context.attribute; + context.isVisible &= InspectorConditionEvaluator.Evaluate( + context.GetSiblingValue(condition.memberName), + condition.condition, + condition.expectedValue + ); + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/SpaceInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/SpaceInspectorAttributeDrawer.cs new file mode 100644 index 000000000..eb4d2df52 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/SpaceInspectorAttributeDrawer.cs @@ -0,0 +1,22 @@ +using System.Numerics; +using Inno.Editor.Annotations; + +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(SpaceAttribute))] +internal sealed class SpaceInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Renders the requested vertical spacing before its annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void DrawBefore(InspectorAttributeDrawContext context) + { + float height = ((SpaceAttribute)context.attribute).height; + Gui.Dummy(new Vector2(0f, height)); + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TextInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TextInspectorAttributeDrawer.cs new file mode 100644 index 000000000..1dc49e67b --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TextInspectorAttributeDrawer.cs @@ -0,0 +1,31 @@ +using Inno.Editor.Annotations; +using Inno.Editor.ImGui; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(TextAttribute))] +internal sealed class TextInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Renders persistent explanatory text before its annotated property. + /// + /// + /// Active attribute drawing context. + /// + public void DrawBefore(InspectorAttributeDrawContext context) + { + string text = ((TextAttribute)context.attribute).text; + Gui.PushStyleColor((ImGuiCol.Text), EditorPalette.textDisabled); + try + { + EditorUI.current.widgets.WrappedText(text); + } + finally + { + Gui.PopStyleColor(); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TooltipInspectorAttributeDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TooltipInspectorAttributeDrawer.cs new file mode 100644 index 000000000..dad3f87aa --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/AttributeDrawing/TooltipInspectorAttributeDrawer.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Annotations; + +namespace Inno.Editor.Inspection; + +[InspectorAttributeDrawer(typeof(TooltipAttribute))] +internal sealed class TooltipInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + /// + /// Applies tooltip text to the annotated property row. + /// + /// + /// Active attribute drawing context. + /// + public void Update(InspectorAttributeDrawContext context) => context.tooltip = ((TooltipAttribute)context.attribute).text; +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/IInspectionDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/IInspectionDrawer.cs new file mode 100644 index 000000000..65c23b24e --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/IInspectionDrawer.cs @@ -0,0 +1,59 @@ +using System; + +namespace Inno.Editor.Inspection; + +/// +/// Defines the runtime bridge used to render a discovered inspection drawer. +/// +public interface IInspectionDrawer +{ + /// + /// Determines whether a type-compatible selected value can be inspected by this drawer. + /// + /// + /// Selected value, never mutated by this query. + /// + /// + /// Whether this drawer accepts the value; ordinary type-only drawers accept by default. + /// + bool CanInspect(object target) => true; + + /// + /// Gets the icon glyph displayed in the Inspector target header. + /// + /// + /// The active Inspector drawing context. + /// + /// + /// The icon glyph for the current target. + /// + string GetIcon(InspectionDrawContext context); + + /// + /// Binds the target name displayed by the Inspector target header. + /// + /// + /// The active Inspector drawing context. + /// + /// + /// The current target name and a callback that accepts a requested replacement name, or + /// for the callback when the name is read-only. + /// + (string name, Action? setter) BindName(InspectionDrawContext context); + + /// + /// Draws the target-specific second header row. + /// + /// + /// The active Inspector drawing context. + /// + void DrawHeader(InspectionDrawContext context); + + /// + /// Draws the target-specific Inspector body. + /// + /// + /// The active Inspector drawing context. + /// + void Draw(InspectionDrawContext context); +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs index d872888c2..06723ce0e 100644 --- a/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs +++ b/src/composition/editor/framework/Inno.Editor.Inspection/ObjectDrawing/InspectionDrawer.cs @@ -114,59 +114,3 @@ private static TTarget GetTarget(InspectionDrawContext context) ); } } - -/// -/// Defines the runtime bridge used to render a discovered inspection drawer. -/// -public interface IInspectionDrawer -{ - /// - /// Determines whether a type-compatible selected value can be inspected by this drawer. - /// - /// - /// Selected value, never mutated by this query. - /// - /// - /// Whether this drawer accepts the value; ordinary type-only drawers accept by default. - /// - bool CanInspect(object target) => true; - - /// - /// Gets the icon glyph displayed in the Inspector target header. - /// - /// - /// The active Inspector drawing context. - /// - /// - /// The icon glyph for the current target. - /// - string GetIcon(InspectionDrawContext context); - - /// - /// Binds the target name displayed by the Inspector target header. - /// - /// - /// The active Inspector drawing context. - /// - /// - /// The current target name and a callback that accepts a requested replacement name, or - /// for the callback when the name is read-only. - /// - (string name, Action? setter) BindName(InspectionDrawContext context); - - /// - /// Draws the target-specific second header row. - /// - /// - /// The active Inspector drawing context. - /// - void DrawHeader(InspectionDrawContext context); - - /// - /// Draws the target-specific Inspector body. - /// - /// - /// The active Inspector drawing context. - /// - void Draw(InspectionDrawContext context); -} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ColorPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ColorPropertyDrawer.cs new file mode 100644 index 000000000..36a8b7a08 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ColorPropertyDrawer.cs @@ -0,0 +1,33 @@ +using Inno.Core.Mathematics; +using Inno.Editor.ImGui; + +using Gui = Inno.Editor.ImGui.ImGui; +using NumericsVector4 = System.Numerics.Vector4; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Color))] +internal sealed unsafe class ColorPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Color value = context.GetValue() is Color current ? current : default; + var nativeValue = new NumericsVector4(value.r, value.g, value.b, value.a); + ImGuiColorEditFlags flags = context.hdrColor + ? ImGuiColorEditFlags.Hdr + | ImGuiColorEditFlags.Float + | ImGuiColorEditFlags.InputRgb + | ImGuiColorEditFlags.DisplayRgb + : ImGuiColorEditFlags.None; + if (Gui.ColorEditLinear4($"##{context.path}", ref nativeValue, flags)) + { + context.SetValue(new Color(nativeValue.X, nativeValue.Y, nativeValue.Z, nativeValue.W)); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ComponentFieldDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ComponentFieldDrawer.cs new file mode 100644 index 000000000..b79801a0b --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/ComponentFieldDrawer.cs @@ -0,0 +1,31 @@ +using System; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Inspection; + +internal static unsafe class ComponentFieldDrawer +{ + internal static float GetWidth(int count) + { + float spacing = Gui.GetLayout().itemSpacing.X; + return MathF.Max(1f, (Gui.GetContentRegionAvailable().X - spacing * (count - 1)) / count); + } + + internal static bool Float( + string path, + string label, + ref float value, + float width + ) => EditorUI.current.widgets.AxisDragFloat(path, label, ref value, width); + + internal static bool Int( + string path, + string label, + ref int value, + float width + ) => EditorUI.current.widgets.AxisDragInt(path, label, ref value, width); + + internal static void Next() => Gui.SameLine(0f, -1f); +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs deleted file mode 100644 index 8439863b1..000000000 --- a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/MathematicsPropertyDrawers.cs +++ /dev/null @@ -1,342 +0,0 @@ -using System; -using Inno.Core.Mathematics; -using Inno.Editor.ImGui; -using Inno.Editor.ImGui.ImGuiWidget; - -using EditorUI = Inno.Editor.ImGui.EditorUISession; -using Gui = Inno.Editor.ImGui.ImGui; -using NumericsVector4 = System.Numerics.Vector4; - -namespace Inno.Editor.Inspection; - -internal static unsafe class ComponentFieldDrawer -{ - internal static float GetWidth(int count) - { - float spacing = Gui.GetLayout().itemSpacing.X; - return MathF.Max(1f, (Gui.GetContentRegionAvailable().X - spacing * (count - 1)) / count); - } - - internal static bool Float( - string path, - string label, - ref float value, - float width - ) => EditorUI.current.widgets.AxisDragFloat(path, label, ref value, width); - - internal static bool Int( - string path, - string label, - ref int value, - float width - ) => EditorUI.current.widgets.AxisDragInt(path, label, ref value, width); - - internal static void Next() => Gui.SameLine(0f, -1f); -} - -[PropertyDrawer(typeof(Vector2))] -internal sealed unsafe class Vector2PropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector2 value = context.GetValue() is Vector2 current ? current : default; - float width = ComponentFieldDrawer.GetWidth(2); - if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) - { - context.SetValue(value, "x"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) - { - context.SetValue(value, "y"); - } - } -} - -[PropertyDrawer(typeof(Vector3))] -internal sealed unsafe class Vector3PropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector3 value = context.GetValue() is Vector3 current ? current : default; - float width = ComponentFieldDrawer.GetWidth(3); - if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) - { - context.SetValue(value, "x"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) - { - context.SetValue(value, "y"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Z", ref value.z, width)) - { - context.SetValue(value, "z"); - } - } -} - -[PropertyDrawer(typeof(Vector4))] -internal sealed unsafe class Vector4PropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector4 value = context.GetValue() is Vector4 current ? current : default; - float width = ComponentFieldDrawer.GetWidth(4); - if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) - { - context.SetValue(value, "x"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) - { - context.SetValue(value, "y"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Z", ref value.z, width)) - { - context.SetValue(value, "z"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "W", ref value.w, width)) - { - context.SetValue(value, "w"); - } - } -} - -[PropertyDrawer(typeof(Vector2Int))] -internal sealed unsafe class Vector2IntPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector2Int value = context.GetValue() is Vector2Int current ? current : default; - float width = ComponentFieldDrawer.GetWidth(2); - if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) - { - context.SetValue(value, "x"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) - { - context.SetValue(value, "y"); - } - } -} - -[PropertyDrawer(typeof(Vector3Int))] -internal sealed unsafe class Vector3IntPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector3Int value = context.GetValue() is Vector3Int current ? current : default; - float width = ComponentFieldDrawer.GetWidth(3); - if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) - { - context.SetValue(value, "x"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) - { - context.SetValue(value, "y"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Z", ref value.z, width)) - { - context.SetValue(value, "z"); - } - } -} - -[PropertyDrawer(typeof(Vector4Int))] -internal sealed unsafe class Vector4IntPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Vector4Int value = context.GetValue() is Vector4Int current ? current : default; - float width = ComponentFieldDrawer.GetWidth(4); - if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) - { - context.SetValue(value, "x"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) - { - context.SetValue(value, "y"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Z", ref value.z, width)) - { - context.SetValue(value, "z"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "W", ref value.w, width)) - { - context.SetValue(value, "w"); - } - } -} - -[PropertyDrawer(typeof(Rect))] -internal sealed unsafe class RectPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Rect value = context.GetValue() is Rect current ? current : default; - float width = ComponentFieldDrawer.GetWidth(4); - if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) - { - context.SetValue(value, "x"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) - { - context.SetValue(value, "y"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "W", ref value.width, width)) - { - context.SetValue(value, "width"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "H", ref value.height, width)) - { - context.SetValue(value, "height"); - } - } -} - -[PropertyDrawer(typeof(RectInt))] -internal sealed unsafe class RectIntPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - RectInt value = context.GetValue() is RectInt current ? current : default; - float width = ComponentFieldDrawer.GetWidth(4); - if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) - { - context.SetValue(value, "x"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) - { - context.SetValue(value, "y"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "W", ref value.width, width)) - { - context.SetValue(value, "width"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Int(context.path, "H", ref value.height, width)) - { - context.SetValue(value, "height"); - } - } -} - -[PropertyDrawer(typeof(Color))] -internal sealed unsafe class ColorPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Color value = context.GetValue() is Color current ? current : default; - var nativeValue = new NumericsVector4(value.r, value.g, value.b, value.a); - ImGuiColorEditFlags flags = context.hdrColor - ? ImGuiColorEditFlags.Hdr - | ImGuiColorEditFlags.Float - | ImGuiColorEditFlags.InputRgb - | ImGuiColorEditFlags.DisplayRgb - : ImGuiColorEditFlags.None; - if (Gui.ColorEditLinear4($"##{context.path}", ref nativeValue, flags)) - { - context.SetValue(new Color(nativeValue.X, nativeValue.Y, nativeValue.Z, nativeValue.W)); - } - } -} - -[PropertyDrawer(typeof(Quaternion))] -internal sealed unsafe class QuaternionPropertyDrawer : IPropertyDrawer -{ - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The context that supplies state and services for this operation. - /// - public void Draw(PropertyDrawContext context) - { - Quaternion value = context.GetValue() is Quaternion current ? current : Quaternion.identity; - Vector3 eulerDegrees = value.ToEulerAnglesXYZDegrees(); - float width = ComponentFieldDrawer.GetWidth(3); - if (ComponentFieldDrawer.Float(context.path, "X", ref eulerDegrees.x, width)) - { - context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.x"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Y", ref eulerDegrees.y, width)) - { - context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.y"); - } - ComponentFieldDrawer.Next(); - if (ComponentFieldDrawer.Float(context.path, "Z", ref eulerDegrees.z, width)) - { - context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.z"); - } - } -} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/QuaternionPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/QuaternionPropertyDrawer.cs new file mode 100644 index 000000000..97350cacb --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/QuaternionPropertyDrawer.cs @@ -0,0 +1,34 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Quaternion))] +internal sealed unsafe class QuaternionPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Quaternion value = context.GetValue() is Quaternion current ? current : Quaternion.identity; + Vector3 eulerDegrees = value.ToEulerAnglesXYZDegrees(); + float width = ComponentFieldDrawer.GetWidth(3); + if (ComponentFieldDrawer.Float(context.path, "X", ref eulerDegrees.x, width)) + { + context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Y", ref eulerDegrees.y, width)) + { + context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Z", ref eulerDegrees.z, width)) + { + context.SetValue(Quaternion.FromEulerAnglesXYZDegrees(eulerDegrees).normalized, "euler.z"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectIntPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectIntPropertyDrawer.cs new file mode 100644 index 000000000..b9418491f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectIntPropertyDrawer.cs @@ -0,0 +1,38 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(RectInt))] +internal sealed unsafe class RectIntPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + RectInt value = context.GetValue() is RectInt current ? current : default; + float width = ComponentFieldDrawer.GetWidth(4); + if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "W", ref value.width, width)) + { + context.SetValue(value, "width"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "H", ref value.height, width)) + { + context.SetValue(value, "height"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectPropertyDrawer.cs new file mode 100644 index 000000000..bbcaea19f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/RectPropertyDrawer.cs @@ -0,0 +1,38 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Rect))] +internal sealed unsafe class RectPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Rect value = context.GetValue() is Rect current ? current : default; + float width = ComponentFieldDrawer.GetWidth(4); + if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "W", ref value.width, width)) + { + context.SetValue(value, "width"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "H", ref value.height, width)) + { + context.SetValue(value, "height"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2IntPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2IntPropertyDrawer.cs new file mode 100644 index 000000000..68b063c00 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2IntPropertyDrawer.cs @@ -0,0 +1,28 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector2Int))] +internal sealed unsafe class Vector2IntPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector2Int value = context.GetValue() is Vector2Int current ? current : default; + float width = ComponentFieldDrawer.GetWidth(2); + if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2PropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2PropertyDrawer.cs new file mode 100644 index 000000000..47336cc9f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector2PropertyDrawer.cs @@ -0,0 +1,28 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector2))] +internal sealed unsafe class Vector2PropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector2 value = context.GetValue() is Vector2 current ? current : default; + float width = ComponentFieldDrawer.GetWidth(2); + if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3IntPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3IntPropertyDrawer.cs new file mode 100644 index 000000000..60c6f12c0 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3IntPropertyDrawer.cs @@ -0,0 +1,33 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector3Int))] +internal sealed unsafe class Vector3IntPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector3Int value = context.GetValue() is Vector3Int current ? current : default; + float width = ComponentFieldDrawer.GetWidth(3); + if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Z", ref value.z, width)) + { + context.SetValue(value, "z"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3PropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3PropertyDrawer.cs new file mode 100644 index 000000000..d5ed4f2a6 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector3PropertyDrawer.cs @@ -0,0 +1,33 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector3))] +internal sealed unsafe class Vector3PropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector3 value = context.GetValue() is Vector3 current ? current : default; + float width = ComponentFieldDrawer.GetWidth(3); + if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Z", ref value.z, width)) + { + context.SetValue(value, "z"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4IntPropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4IntPropertyDrawer.cs new file mode 100644 index 000000000..7e09a74ef --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4IntPropertyDrawer.cs @@ -0,0 +1,38 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector4Int))] +internal sealed unsafe class Vector4IntPropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector4Int value = context.GetValue() is Vector4Int current ? current : default; + float width = ComponentFieldDrawer.GetWidth(4); + if (ComponentFieldDrawer.Int(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "Z", ref value.z, width)) + { + context.SetValue(value, "z"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Int(context.path, "W", ref value.w, width)) + { + context.SetValue(value, "w"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4PropertyDrawer.cs b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4PropertyDrawer.cs new file mode 100644 index 000000000..0dadebf62 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Inspection/PropertyDrawing/Vector4PropertyDrawer.cs @@ -0,0 +1,38 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Inspection; + +[PropertyDrawer(typeof(Vector4))] +internal sealed unsafe class Vector4PropertyDrawer : IPropertyDrawer +{ + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The context that supplies state and services for this operation. + /// + public void Draw(PropertyDrawContext context) + { + Vector4 value = context.GetValue() is Vector4 current ? current : default; + float width = ComponentFieldDrawer.GetWidth(4); + if (ComponentFieldDrawer.Float(context.path, "X", ref value.x, width)) + { + context.SetValue(value, "x"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Y", ref value.y, width)) + { + context.SetValue(value, "y"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "Z", ref value.z, width)) + { + context.SetValue(value, "z"); + } + ComponentFieldDrawer.Next(); + if (ComponentFieldDrawer.Float(context.path, "W", ref value.w, width)) + { + context.SetValue(value, "w"); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs index 894948632..010635ae7 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorAction.cs @@ -307,103 +307,6 @@ out EditorActionContext typed } } -/// -/// Defines a targetless editor action that requires one strongly typed command argument. -/// -/// -/// The command argument type accepted by the action. -/// -public abstract class EditorArgumentAction : EditorAction -{ - internal sealed override Type argumentType => typeof(TArgument); - - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected sealed override EditorActionState Query(EditorActionContext context) - => context.target is null - && context.argument is TArgument argument - ? Query(new EditorActionArgumentContext(context, argument)) - : EditorActionState.hidden; - - /// - /// Evaluates the action for a typed argument. - /// - /// - /// The typed contextual request. - /// - /// - /// The current presentation and availability state. - /// - protected virtual EditorActionState Query(EditorActionArgumentContext context) => EditorActionState.enabled; - - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected sealed override void Execute(EditorActionContext context) - { - if (context.target is not null || context.argument is not TArgument argument) - { - throw new InvalidOperationException($"Editor action '{GetType().FullName}' requires argument '{typeof(TArgument).FullName}'."); - } - - Execute(new EditorActionArgumentContext(context, argument)); - } - - /// - /// Executes the action for a typed argument. - /// - /// - /// The typed contextual request. - /// - protected abstract void Execute(EditorActionArgumentContext context); -} - -/// -/// Defines a target action with a typed presentation-only argument. -/// -/// -/// The target type accepted by the action. -/// -/// -/// The presentation data type. -/// -public abstract class EditorPresentationAction : EditorAction -{ - /// - /// Presents this action through the current editor interaction surface. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// when the operation succeeds or its condition is satisfied; otherwise, . - /// - protected sealed override bool Present(EditorActionContext context) - => context.argument is TPresentation presentation - && Present(new EditorActionContext(context, context.target, presentation)); - - /// - /// Presents active content using strongly typed presentation data. - /// - /// - /// The typed presentation request. - /// - /// - /// when content was presented. - /// - protected abstract bool Present(EditorActionContext context); -} - /// /// Defines a discoverable action whose target must be assignable to a specific reference type. /// diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionArgumentContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionArgumentContext.cs new file mode 100644 index 000000000..91b89a54a --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionArgumentContext.cs @@ -0,0 +1,23 @@ +namespace Inno.Editor.Interactions; + +/// +/// Provides a strongly typed action argument to a targetless editor action. +/// +/// +/// The action argument type required by the action. +/// +public sealed class EditorActionArgumentContext : EditorActionContext +{ + internal EditorActionArgumentContext( + EditorActionContext context, + TArgument argument + ) : base(context.editor, context.interactions, context.area, target: null, argument: argument) + { + this.argument = argument; + } + + /// + /// Gets the strongly typed action argument. + /// + public new TArgument argument { get; } +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs index ab4b55719..3b5840df4 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorActionContext.cs @@ -136,25 +136,3 @@ TArgument argument /// public new TArgument argument { get; } } - -/// -/// Provides a strongly typed action argument to a targetless editor action. -/// -/// -/// The action argument type required by the action. -/// -public sealed class EditorActionArgumentContext : EditorActionContext -{ - internal EditorActionArgumentContext( - EditorActionContext context, - TArgument argument - ) : base(context.editor, context.interactions, context.area, target: null, argument: argument) - { - this.argument = argument; - } - - /// - /// Gets the strongly typed action argument. - /// - public new TArgument argument { get; } -} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorArgumentAction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorArgumentAction.cs new file mode 100644 index 000000000..5474fd2c9 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorArgumentAction.cs @@ -0,0 +1,64 @@ +using System; + +namespace Inno.Editor.Interactions; + +/// +/// Defines a targetless editor action that requires one strongly typed command argument. +/// +/// +/// The command argument type accepted by the action. +/// +public abstract class EditorArgumentAction : EditorAction +{ + internal sealed override Type argumentType => typeof(TArgument); + + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected sealed override EditorActionState Query(EditorActionContext context) + => context.target is null + && context.argument is TArgument argument + ? Query(new EditorActionArgumentContext(context, argument)) + : EditorActionState.hidden; + + /// + /// Evaluates the action for a typed argument. + /// + /// + /// The typed contextual request. + /// + /// + /// The current presentation and availability state. + /// + protected virtual EditorActionState Query(EditorActionArgumentContext context) => EditorActionState.enabled; + + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected sealed override void Execute(EditorActionContext context) + { + if (context.target is not null || context.argument is not TArgument argument) + { + throw new InvalidOperationException($"Editor action '{GetType().FullName}' requires argument '{typeof(TArgument).FullName}'."); + } + + Execute(new EditorActionArgumentContext(context, argument)); + } + + /// + /// Executes the action for a typed argument. + /// + /// + /// The typed contextual request. + /// + protected abstract void Execute(EditorActionArgumentContext context); +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorPresentationAction.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorPresentationAction.cs new file mode 100644 index 000000000..ba0ec1803 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Actions/EditorPresentationAction.cs @@ -0,0 +1,37 @@ +namespace Inno.Editor.Interactions; + +/// +/// Defines a target action with a typed presentation-only argument. +/// +/// +/// The target type accepted by the action. +/// +/// +/// The presentation data type. +/// +public abstract class EditorPresentationAction : EditorAction +{ + /// + /// Presents this action through the current editor interaction surface. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// when the operation succeeds or its condition is satisfied; otherwise, . + /// + protected sealed override bool Present(EditorActionContext context) + => context.argument is TPresentation presentation + && Present(new EditorActionContext(context, context.target, presentation)); + + /// + /// Presents active content using strongly typed presentation data. + /// + /// + /// The typed presentation request. + /// + /// + /// when content was presented. + /// + protected abstract bool Present(EditorActionContext context); +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs index 55630510b..2161a6dac 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Documents/IEditorDocumentService.cs @@ -3,25 +3,6 @@ namespace Inno.Editor.Interactions; -/// -/// Selects how a dirty document responds to a close request. -/// -public enum EditorDocumentCloseMode -{ - /// - /// Keeps the document open. - /// - Cancel, - /// - /// Closes the document after saving. - /// - Save, - /// - /// Closes the document and discards unsaved state. - /// - Discard -} - /// /// Owns single-instance editor documents independently from reloadable providers and presentation. /// @@ -149,3 +130,22 @@ bool Close( EditorDocumentCloseMode mode ); } + +/// +/// Selects how a dirty document responds to a close request. +/// +public enum EditorDocumentCloseMode +{ + /// + /// Keeps the document open. + /// + Cancel, + /// + /// Closes the document after saving. + /// + Save, + /// + /// Closes the document and discards unsaved state. + /// + Discard +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs index edd0bbaa6..92275460a 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDrop.cs @@ -1,6 +1,5 @@ using System; using Inno.Core.Identity; -using Inno.Editor.Core; namespace Inno.Editor.Interactions; @@ -123,62 +122,3 @@ public sealed override EditorDropResult Drop(EditorDropContext context) /// protected abstract EditorDropResult Drop(EditorDropContext context); } - -/// -/// Provides strongly typed source and target values to a drop operation. -/// -/// -/// The managed drag-source type. -/// -/// -/// The managed drop-target type. -/// -public sealed class EditorDropContext - where TSource : class - where TTarget : class -{ - internal EditorDropContext( - EditorDropContext context, - TSource source, - TTarget target - ) { - this.untyped = context; - this.source = source; - this.target = target; - } - - /// - /// Gets the untyped drop context. - /// - public EditorDropContext untyped { get; } - - /// - /// Gets the active editor context. - /// - public EditorContext editor => untyped.editor; - - /// - /// Gets the active interaction entry point. - /// - public EditorInteractions interactions => untyped.interactions; - - /// - /// Gets the interaction area. - /// - public string area => untyped.area; - - /// - /// Gets the typed drag source. - /// - public TSource source { get; } - - /// - /// Gets the typed drop target. - /// - public TTarget target { get; } - - /// - /// Gets the requested placement. - /// - public EditorDropPlacement placement => untyped.placement; -} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs index 544ac3b3c..4861234d5 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/DragDrop/EditorDropContext.cs @@ -99,3 +99,62 @@ public EditorDropContext( /// public EditorDropPlacement placement { get; } } + +/// +/// Provides strongly typed source and target values to a drop operation. +/// +/// +/// The managed drag-source type. +/// +/// +/// The managed drop-target type. +/// +public sealed class EditorDropContext + where TSource : class + where TTarget : class +{ + internal EditorDropContext( + EditorDropContext context, + TSource source, + TTarget target + ) { + this.untyped = context; + this.source = source; + this.target = target; + } + + /// + /// Gets the untyped drop context. + /// + public EditorDropContext untyped { get; } + + /// + /// Gets the active editor context. + /// + public EditorContext editor => untyped.editor; + + /// + /// Gets the active interaction entry point. + /// + public EditorInteractions interactions => untyped.interactions; + + /// + /// Gets the interaction area. + /// + public string area => untyped.area; + + /// + /// Gets the typed drag source. + /// + public TSource source { get; } + + /// + /// Gets the typed drop target. + /// + public TTarget target { get; } + + /// + /// Gets the requested placement. + /// + public EditorDropPlacement placement => untyped.placement; +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs index 6faf07d82..bb42d490c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuBuilder.cs @@ -80,42 +80,3 @@ internal sealed record EditorMenuGroupPlacement( int order, bool separatorBefore ); - -internal sealed class EditorMenuPlacement -{ - internal EditorMenuPlacement( - string path, - string actionID, - int order, - bool separatorBefore, - object? argument - ) { - this.path = path; - this.actionID = actionID; - this.order = order; - this.separatorBefore = separatorBefore; - this.argument = argument; - } - - internal string path { get; } - - /// - /// Gets the action identifier. - /// - internal string actionID { get; } - - /// - /// Gets the stable menu order. - /// - internal int order { get; } - - /// - /// Gets whether a separator precedes this placement. - /// - internal bool separatorBefore { get; } - - /// - /// Gets the optional action argument. - /// - internal object? argument { get; } -} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuPlacement.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuPlacement.cs new file mode 100644 index 000000000..a4a63ece2 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Menus/EditorMenuPlacement.cs @@ -0,0 +1,40 @@ +namespace Inno.Editor.Interactions; + +internal sealed class EditorMenuPlacement +{ + internal EditorMenuPlacement( + string path, + string actionID, + int order, + bool separatorBefore, + object? argument + ) { + this.path = path; + this.actionID = actionID; + this.order = order; + this.separatorBefore = separatorBefore; + this.argument = argument; + } + + internal string path { get; } + + /// + /// Gets the action identifier. + /// + internal string actionID { get; } + + /// + /// Gets the stable menu order. + /// + internal int order { get; } + + /// + /// Gets whether a separator precedes this placement. + /// + internal bool separatorBefore { get; } + + /// + /// Gets the optional action argument. + /// + internal object? argument { get; } +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportPointerEvent.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportPointerEvent.cs new file mode 100644 index 000000000..aaf8bbcb2 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportPointerEvent.cs @@ -0,0 +1,77 @@ +using Inno.Core.Input; +using Inno.Core.Mathematics; + +namespace Inno.Editor.Interactions; + +/// +/// Contains one immutable viewport pointer sample in screen and world coordinates. +/// +public readonly record struct EditorViewportPointerEvent +{ + /// + /// Creates one viewport pointer sample. + /// + /// + /// Platform pointer identity. + /// + /// + /// Gesture lifecycle phase. + /// + /// + /// Viewport-local pixel position. + /// + /// + /// Corresponding world position. + /// + /// + /// Platform button number. + /// + /// + /// Active keyboard modifiers. + /// + public EditorViewportPointerEvent( + int pointerID, + EditorViewportPointerPhase phase, + Vector2 screenPosition, + Vector2 worldPosition, + int button, + KeyModifier modifiers + ) { + this.pointerID = pointerID; + this.phase = phase; + this.screenPosition = screenPosition; + this.worldPosition = worldPosition; + this.button = button; + this.modifiers = modifiers; + } + + /// + /// Gets the platform pointer identity. + /// + public int pointerID { get; } + + /// + /// Gets the gesture lifecycle phase. + /// + public EditorViewportPointerPhase phase { get; } + + /// + /// Gets the viewport-local pixel position. + /// + public Vector2 screenPosition { get; } + + /// + /// Gets the corresponding world position. + /// + public Vector2 worldPosition { get; } + + /// + /// Gets the platform button number. + /// + public int button { get; } + + /// + /// Gets active keyboard modifiers. + /// + public KeyModifier modifiers { get; } +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportShortcut.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportShortcut.cs new file mode 100644 index 000000000..d581d2462 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportShortcut.cs @@ -0,0 +1,46 @@ +using Inno.Core.Input; + +namespace Inno.Editor.Interactions; + +/// +/// Contains one presentation-independent shortcut sample for a focused viewport tool. +/// +public readonly record struct EditorViewportShortcut +{ + /// + /// Creates one viewport shortcut sample. + /// + /// + /// Pressed key. + /// + /// + /// Active keyboard modifiers. + /// + /// + /// Whether the platform generated an auto-repeat press. + /// + public EditorViewportShortcut( + KeyCode key, + KeyModifier modifiers = KeyModifier.None, + bool repeat = false + ) { + this.key = key; + this.modifiers = modifiers; + this.repeat = repeat; + } + + /// + /// Gets the pressed key. + /// + public KeyCode key { get; } + + /// + /// Gets active keyboard modifiers. + /// + public KeyModifier modifiers { get; } + + /// + /// Gets whether the shortcut is an auto-repeat press. + /// + public bool repeat { get; } +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs index 2f94116a0..9a5f54577 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/EditorViewportTool.cs @@ -1,211 +1,7 @@ using System; -using Inno.Core.Input; -using Inno.Core.Mathematics; namespace Inno.Editor.Interactions; -/// -/// Selects the lifecycle phase of one viewport pointer sample. -/// -public enum EditorViewportPointerPhase -{ - /// - /// The pointer button began a gesture. - /// - Down, - /// - /// The pointer moved or changed hover position. - /// - Move, - /// - /// The pointer button ended a gesture. - /// - Up, - /// - /// The platform cancelled the gesture. - /// - Cancel -} - -/// -/// Selects a presentation-independent cursor requested by a viewport tool. -/// -public enum EditorViewportCursor -{ - /// - /// Uses the normal arrow cursor. - /// - Arrow, - /// - /// Uses a precise crosshair. - /// - Crosshair, - /// - /// Uses a hand suitable for panning. - /// - Hand, - /// - /// Uses four-direction movement arrows. - /// - Move, - /// - /// Uses horizontal resizing arrows. - /// - ResizeHorizontal, - /// - /// Uses vertical resizing arrows. - /// - ResizeVertical, - /// - /// Hides the pointer while the tool owns it. - /// - Hidden -} - -/// -/// Contains one presentation-independent shortcut sample for a focused viewport tool. -/// -public readonly record struct EditorViewportShortcut -{ - /// - /// Creates one viewport shortcut sample. - /// - /// - /// Pressed key. - /// - /// - /// Active keyboard modifiers. - /// - /// - /// Whether the platform generated an auto-repeat press. - /// - public EditorViewportShortcut( - KeyCode key, - KeyModifier modifiers = KeyModifier.None, - bool repeat = false - ) { - this.key = key; - this.modifiers = modifiers; - this.repeat = repeat; - } - - /// - /// Gets the pressed key. - /// - public KeyCode key { get; } - - /// - /// Gets active keyboard modifiers. - /// - public KeyModifier modifiers { get; } - - /// - /// Gets whether the shortcut is an auto-repeat press. - /// - public bool repeat { get; } -} - -/// -/// Contains one immutable viewport pointer sample in screen and world coordinates. -/// -public readonly record struct EditorViewportPointerEvent -{ - /// - /// Creates one viewport pointer sample. - /// - /// - /// Platform pointer identity. - /// - /// - /// Gesture lifecycle phase. - /// - /// - /// Viewport-local pixel position. - /// - /// - /// Corresponding world position. - /// - /// - /// Platform button number. - /// - /// - /// Active keyboard modifiers. - /// - public EditorViewportPointerEvent( - int pointerID, - EditorViewportPointerPhase phase, - Vector2 screenPosition, - Vector2 worldPosition, - int button, - KeyModifier modifiers - ) { - this.pointerID = pointerID; - this.phase = phase; - this.screenPosition = screenPosition; - this.worldPosition = worldPosition; - this.button = button; - this.modifiers = modifiers; - } - - /// - /// Gets the platform pointer identity. - /// - public int pointerID { get; } - - /// - /// Gets the gesture lifecycle phase. - /// - public EditorViewportPointerPhase phase { get; } - - /// - /// Gets the viewport-local pixel position. - /// - public Vector2 screenPosition { get; } - - /// - /// Gets the corresponding world position. - /// - public Vector2 worldPosition { get; } - - /// - /// Gets the platform button number. - /// - public int button { get; } - - /// - /// Gets active keyboard modifiers. - /// - public KeyModifier modifiers { get; } -} - -/// -/// Converts coordinates for one viewport camera without exposing its presentation backend. -/// -public interface IEditorViewportCoordinateConverter -{ - /// - /// Converts viewport-local pixel coordinates to world coordinates. - /// - /// - /// Viewport-local pixel coordinates. - /// - /// - /// World coordinates. - /// - Vector2 ScreenToWorld(Vector2 screenPosition); - - /// - /// Converts world coordinates to viewport-local pixel coordinates. - /// - /// - /// World coordinates. - /// - /// - /// Viewport-local pixel coordinates. - /// - Vector2 WorldToScreen(Vector2 worldPosition); -} - /// /// Defines one presentation-independent, reloadable viewport editing tool. /// @@ -309,3 +105,61 @@ EditorViewportShortcut shortcut /// public virtual void DrawOverlay(EditorViewportToolContext context) => ArgumentNullException.ThrowIfNull(context); } + +/// +/// Selects the lifecycle phase of one viewport pointer sample. +/// +public enum EditorViewportPointerPhase +{ + /// + /// The pointer button began a gesture. + /// + Down, + /// + /// The pointer moved or changed hover position. + /// + Move, + /// + /// The pointer button ended a gesture. + /// + Up, + /// + /// The platform cancelled the gesture. + /// + Cancel +} + +/// +/// Selects a presentation-independent cursor requested by a viewport tool. +/// +public enum EditorViewportCursor +{ + /// + /// Uses the normal arrow cursor. + /// + Arrow, + /// + /// Uses a precise crosshair. + /// + Crosshair, + /// + /// Uses a hand suitable for panning. + /// + Hand, + /// + /// Uses four-direction movement arrows. + /// + Move, + /// + /// Uses horizontal resizing arrows. + /// + ResizeHorizontal, + /// + /// Uses vertical resizing arrows. + /// + ResizeVertical, + /// + /// Hides the pointer while the tool owns it. + /// + Hidden +} diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/IEditorViewportCoordinateConverter.cs b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/IEditorViewportCoordinateConverter.cs new file mode 100644 index 000000000..b01d6fd5f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Interactions/Viewport/IEditorViewportCoordinateConverter.cs @@ -0,0 +1,31 @@ +using Inno.Core.Mathematics; + +namespace Inno.Editor.Interactions; + +/// +/// Converts coordinates for one viewport camera without exposing its presentation backend. +/// +public interface IEditorViewportCoordinateConverter +{ + /// + /// Converts viewport-local pixel coordinates to world coordinates. + /// + /// + /// Viewport-local pixel coordinates. + /// + /// + /// World coordinates. + /// + Vector2 ScreenToWorld(Vector2 screenPosition); + + /// + /// Converts world coordinates to viewport-local pixel coordinates. + /// + /// + /// World coordinates. + /// + /// + /// Viewport-local pixel coordinates. + /// + Vector2 WorldToScreen(Vector2 worldPosition); +} diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs index 44e642b41..e036f7c31 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistory.cs @@ -37,86 +37,3 @@ internal static (ReadOnlyMemory before, ReadOnlyMemory after) Read(E return (before, after); } } - -[EditorHistoryHandler(EditorSettingsHistory.C_KIND)] -internal sealed class EditorSettingsHistoryHandler(EditorSettings settings) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = EditorSettingsHistory.Read(change); - settings.ValidateDocument(before.Span); - settings.ValidateDocument(after.Span); - return EditorHistoryAvailability.Available(); - } - catch (Exception exception) when ( - exception is InvalidDataException or IOException or UnauthorizedAccessException) - { - return EditorHistoryAvailability.Unavailable(exception.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - byte[] original = settings.CaptureDocument(); - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = EditorSettingsHistory.Read(change); - settings.RestoreFromHistory(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); - settings.NotifyChanged(); - return EditorHistoryResult.Success(); - } - catch (Exception exception) when ( - exception is InvalidDataException or IOException or UnauthorizedAccessException) - { - try - { - settings.RestoreFromHistory(original); - } - catch (Exception rollbackException) - { - return StateIntegrityFailure( - $"Settings transition failed: {exception.Message} Rollback failed: {rollbackException.Message}" - ); - } - return EditorHistoryResult.Failure(exception.Message); - } - } -} diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistoryHandler.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistoryHandler.cs new file mode 100644 index 000000000..eb3c5e91f --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/EditorSettingsHistoryHandler.cs @@ -0,0 +1,88 @@ +using System; +using System.IO; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Settings; + +[EditorHistoryHandler(EditorSettingsHistory.C_KIND)] +internal sealed class EditorSettingsHistoryHandler(EditorSettings settings) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = EditorSettingsHistory.Read(change); + settings.ValidateDocument(before.Span); + settings.ValidateDocument(after.Span); + return EditorHistoryAvailability.Available(); + } + catch (Exception exception) when ( + exception is InvalidDataException or IOException or UnauthorizedAccessException) + { + return EditorHistoryAvailability.Unavailable(exception.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + byte[] original = settings.CaptureDocument(); + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = EditorSettingsHistory.Read(change); + settings.RestoreFromHistory(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); + settings.NotifyChanged(); + return EditorHistoryResult.Success(); + } + catch (Exception exception) when ( + exception is InvalidDataException or IOException or UnauthorizedAccessException) + { + try + { + settings.RestoreFromHistory(original); + } + catch (Exception rollbackException) + { + return StateIntegrityFailure( + $"Settings transition failed: {exception.Message} Rollback failed: {rollbackException.Message}" + ); + } + return EditorHistoryResult.Failure(exception.Message); + } + } +} diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs index 8583c9c8a..edb5bdedd 100644 --- a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistory.cs @@ -37,86 +37,3 @@ internal static (ReadOnlyMemory before, ReadOnlyMemory after) Read(E return (before, after); } } - -[EditorHistoryHandler(ProjectSettingsHistory.C_KIND)] -internal sealed class ProjectSettingsHistoryHandler(ProjectSettingsEditor settings) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = ProjectSettingsHistory.Read(change); - settings.ValidateDocument(before.Span); - settings.ValidateDocument(after.Span); - return EditorHistoryAvailability.Available(); - } - catch (Exception exception) when ( - exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) - { - return EditorHistoryAvailability.Unavailable(exception.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - byte[] original = settings.CaptureDocument(); - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = ProjectSettingsHistory.Read(change); - settings.RestoreFromHistory(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); - return EditorHistoryResult.Success(); - } - catch (Exception exception) when ( - exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) - { - try - { - settings.RestoreFromHistory(original); - } - catch (Exception rollbackException) - { - return StateIntegrityFailure( - $"Project Settings transition failed: {exception.Message} " - + $"Rollback failed: {rollbackException.Message}" - ); - } - return EditorHistoryResult.Failure(exception.Message); - } - } -} diff --git a/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistoryHandler.cs b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistoryHandler.cs new file mode 100644 index 000000000..0026e7216 --- /dev/null +++ b/src/composition/editor/framework/Inno.Editor.Settings/Runtime/ProjectSettingsHistoryHandler.cs @@ -0,0 +1,88 @@ +using System; +using System.IO; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Settings; + +[EditorHistoryHandler(ProjectSettingsHistory.C_KIND)] +internal sealed class ProjectSettingsHistoryHandler(ProjectSettingsEditor settings) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = ProjectSettingsHistory.Read(change); + settings.ValidateDocument(before.Span); + settings.ValidateDocument(after.Span); + return EditorHistoryAvailability.Available(); + } + catch (Exception exception) when ( + exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) + { + return EditorHistoryAvailability.Unavailable(exception.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + byte[] original = settings.CaptureDocument(); + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = ProjectSettingsHistory.Read(change); + settings.RestoreFromHistory(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); + return EditorHistoryResult.Success(); + } + catch (Exception exception) when ( + exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) + { + try + { + settings.RestoreFromHistory(original); + } + catch (Exception rollbackException) + { + return StateIntegrityFailure( + $"Project Settings transition failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); + } + return EditorHistoryResult.Failure(exception.Message); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs index 5462101ac..33e1bf7fc 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserData.cs @@ -5,33 +5,10 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Identity; -using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; namespace Inno.Editor.Panel.FileBrowser; -internal enum FileBrowserEntryTypeFilter -{ - All, - FoldersOnly, - FilesOnly -} - -internal enum FileBrowserEntryScopeFilter -{ - CurrentOnly, - Recursive -} - -internal readonly record struct FileBrowserDisplayEntry( - RuntimeIdentity identity, - AssetPath path, - string displayName, - string extension, - bool isDirectory, - bool isPluginRoot = false -); - internal sealed class FileBrowserData(AssetBrowserModule assets) { private ViewInput? m_input; @@ -235,3 +212,25 @@ private readonly record struct ViewInput( string search ); } + +internal enum FileBrowserEntryTypeFilter +{ + All, + FoldersOnly, + FilesOnly +} + +internal enum FileBrowserEntryScopeFilter +{ + CurrentOnly, + Recursive +} + +internal readonly record struct FileBrowserDisplayEntry( + RuntimeIdentity identity, + AssetPath path, + string displayName, + string extension, + bool isDirectory, + bool isPluginRoot = false +); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs index c2d57b8a3..6d0f79582 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Browser/FileBrowserRename.cs @@ -1,21 +1,12 @@ using System; using Inno.Assets.Pipeline; using Inno.Core.Identity; -using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.ImGui.ImGuiWidget; -using Inno.Editor.Interactions; namespace Inno.Editor.Panel.FileBrowser; -internal enum FileBrowserPresentation -{ - Tree, - List, - Grid -} - internal sealed class FileBrowserRename(AssetBrowserModule assets) { private RuntimeIdentity? m_activeTarget; @@ -74,3 +65,10 @@ float rowHeight out IdentityObject? target ) ? target as AssetFileEntry : null; } + +internal enum FileBrowserPresentation +{ + Tree, + List, + Grid +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/AssetCreationMenu.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/AssetCreationMenu.cs new file mode 100644 index 000000000..89f766930 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/AssetCreationMenu.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Editor.Assets; +using Inno.Editor.Assets.ImGui; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.FileBrowser; + +[EditorMenuSource(FileBrowserInteractionIDs.C_AREA)] +internal sealed class AssetCreationMenu(AssetBrowserModule assets) : EditorMenuSource +{ + /// + /// Builds a validated result from the current immutable input snapshot. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. + /// + public override void Build( + EditorMenuContext context, + EditorMenuBuilder builder + ) { + IReadOnlyList templates = assets.edits.creationTemplates; + var declaredGroups = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (AssetCreationMenuAttribute declaration in templates) + { + string[] segments = declaration.menuPath.Split('/'); + if (segments.Length > 1) + { + string topLevel = "Create/" + segments[0]; + if (declaredGroups.Add(topLevel)) + { + builder.AddGroup(topLevel, declaration.groupOrder, declaration.separatorBeforeGroup); + } + + for (int depth = 1; depth < segments.Length - 1; depth++) + { + string group = "Create/" + string.Join('/', segments.Take(depth + 1)); + if (declaredGroups.Add(group)) + { + builder.AddGroup(group, declaration.itemOrder); + } + } + } + + builder.Add( + "Create/" + declaration.menuPath, + FileBrowserInteractionIDs.C_CREATE_ASSET, + declaration.itemOrder, + argument: declaration.id + ); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs index 5f42b7b47..fcbfae46f 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.FileBrowser/Interactions/CreateAssetCommand.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; using Inno.Editor.Interactions; @@ -42,52 +36,3 @@ protected override void Execute(EditorActionContext context) context.interactions.OpenPanel("scene.inspector"); } } - -[EditorMenuSource(FileBrowserInteractionIDs.C_AREA)] -internal sealed class AssetCreationMenu(AssetBrowserModule assets) : EditorMenuSource -{ - /// - /// Builds a validated result from the current immutable input snapshot. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. - /// - public override void Build( - EditorMenuContext context, - EditorMenuBuilder builder - ) { - IReadOnlyList templates = assets.edits.creationTemplates; - var declaredGroups = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (AssetCreationMenuAttribute declaration in templates) - { - string[] segments = declaration.menuPath.Split('/'); - if (segments.Length > 1) - { - string topLevel = "Create/" + segments[0]; - if (declaredGroups.Add(topLevel)) - { - builder.AddGroup(topLevel, declaration.groupOrder, declaration.separatorBeforeGroup); - } - - for (int depth = 1; depth < segments.Length - 1; depth++) - { - string group = "Create/" + string.Join('/', segments.Take(depth + 1)); - if (declaredGroups.Add(group)) - { - builder.AddGroup(group, declaration.itemOrder); - } - } - } - - builder.Add( - "Create/" + declaration.menuPath, - FileBrowserInteractionIDs.C_CREATE_ASSET, - declaration.itemOrder, - argument: declaration.id - ); - } - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs index e96cbfb06..7a9c8f001 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspectionDrawer.cs @@ -1,20 +1,11 @@ using System; -using System.IO; -using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Core.Execution; -using Inno.Core.Serialization; -using Inno.Editor.Assets; using Inno.Editor.ImGui; using Inno.Editor.Inspection; using Inno.Editor.Rendering; -using Inno.Rendering; using Inno.Rendering.Assets; -using EditorUI = Inno.Editor.ImGui.EditorUISession; -using ImGuiApi = Inno.Editor.ImGui.ImGui; - namespace Inno.Editor.Panel.Inspector; [InspectionDrawer(typeof(RenderPipelineAsset))] @@ -110,321 +101,3 @@ RenderPipelineAsset target } } } - -[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] -internal sealed class PipelineSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer -{ - /// - /// Gets the icon glyph used to represent this item in the editor. - /// - public override string icon => ImGuiIcon.C_FILE; - - /// - /// Retrieves the current icon from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated text representation owned by the caller. - /// - protected override string GetIcon( - InspectionDrawContext context, - AssetFileEntry target - ) => icons.GetIcon(target); - - /// - /// Checks whether this drawer supports the selected Inspector target. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// when the documented condition is satisfied; otherwise, . - /// - protected override bool CanInspect(AssetFileEntry target) - => !target.isDirectory && target.extension.Equals(".irenderpipeline", StringComparison.OrdinalIgnoreCase); - - /// - /// Binds a caller-visible label to the current inspection target. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated (string name, actionstring? setter) that represents the completed operation. - /// - protected override (string name, Action? setter) BindName( - InspectionDrawContext context, - AssetFileEntry target - ) => (target.nameWithoutExtension, null); - - /// - /// Renders the header presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void DrawHeader( - InspectionDrawContext context, - AssetFileEntry target - ) { - if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null) - { - PipelineInspector.DrawHeader(context, documents, documents.Open(target.assetPath)); - } - } - - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void Draw( - InspectionDrawContext context, - AssetFileEntry target - ) { - if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null) - { - PipelineInspector.Draw(context, documents, documents.Open(target.assetPath)); - } - } -} - -internal static class PipelineInspector -{ - internal static void DrawHeader( - InspectionDrawContext context, - PipelineDocuments documents, - Guid id - ) { - AssetDraftDocuments.Draft draft = documents.drafts.GetDraft(id); - ImGuiApi.BeginDisabled(draft.readOnly); - try - { - if (ImGuiApi.Button("Save")) - { - _ = context.interactions.documents.Save(draft.documentID); - } - ImGuiApi.SameLine(0f, -1f); - if (ImGuiApi.Button("Revert")) - { - _ = context.interactions.documents.Revert(draft.documentID); - } - } - finally - { - ImGuiApi.EndDisabled(); - } - } - - internal static void Draw( - InspectionDrawContext context, - PipelineDocuments documents, - Guid id - ) { - AssetDraftDocuments.Draft draft = documents.drafts.GetDraft(id); - RenderPipelineAsset pipeline = documents.Read(id); - var edits = new DraftEdits(documents, id, pipeline); - ImGuiApi.PushID(id.ToString("N")); - try - { - if (EditorUI.current.widgets.SectionHeader( - "Render Pipeline", - "This source is the configuration authority. Unsaved settings do not change Scene, Game or Player content." - )) { - EditorUI.current.widgets.Hint( - draft.isDirty ? "Unsaved changes · rendering unchanged" : "Saved · import and activation are separate" - ); - if (draft.error.Length != 0) - { - EditorUI.current.widgets.Hint(draft.error); - } - if (draft.readOnly) - { - EditorUI.current.widgets.Hint("Installed Pipeline · copy into the project to edit"); - } - EditorUI.current.widgets.Hint("Pipeline: " + pipeline.pipelineTypeId); - DrawSettings("pipeline.settings", pipeline.pipelineState, value => pipeline.pipelineState = value); - } - - bool featuresOpen = EditorUI.current.widgets.SectionHeader( - "Features", - "Ordered extension settings belong to this Pipeline. Each enabled feature participates in its render graph." - ); - RenderFeatureConfiguration[] features = pipeline.features; - for (int index = 0; featuresOpen && index < features.Length; index++) - { - int slot = index; - ImGuiApi.PushID(slot); - try - { - RenderFeatureConfiguration feature = features[slot]; - context.properties.DrawValue( - context.editorContext, - draft, - "pipeline.features." - + slot - + ".enabled", - feature.featureTypeId, - typeof(bool), - () => features[slot].enabled, - value => - { - features[slot].enabled = (bool)value!; - pipeline.features = features; - }, - edits, - draft.readOnly - ); - DrawSettings("pipeline.features." + slot, feature.state, value => - { - features[slot].state = value; - pipeline.features = features; - }); - ImGuiApi.BeginDisabled(draft.readOnly); - try - { - if (slot > 0 && ImGuiApi.SmallButton("Move Up")) - { - (features[slot - 1], features[slot]) = (features[slot], features[slot - 1]); - pipeline.features = features; - documents.Replace(id, pipeline); - break; - } - - if (slot + 1 < features.Length) - { - if (slot > 0) - { - ImGuiApi.SameLine(0f, -1f); - } - if (ImGuiApi.SmallButton("Move Down")) - { - (features[slot + 1], features[slot]) = (features[slot], features[slot + 1]); - pipeline.features = features; - documents.Replace(id, pipeline); - break; - } - } - } - finally - { - ImGuiApi.EndDisabled(); - } - } - finally - { - ImGuiApi.PopID(); - } - } - - if (featuresOpen && features.Length == 0) - { - EditorUI.current.widgets.Hint("No additional features"); - } - } - finally - { - ImGuiApi.PopID(); - } - - void DrawSettings( - string path, - SerializedRenderExtensionState state, - Action assign - ) { - try - { - ISerializable? settings = documents.RestoreSettings(state); - if (settings is null) - { - EditorUI.current.widgets.Hint("No typed settings"); - return; - } - - var settingsEdits = new SettingsEdits( - edits, - () => assign(new SerializedRenderExtensionState(documents.assets.CaptureProperties(settings))) - ); - foreach (SerializedProperty property in documents.serialization.GetProperties(settings)) - { - context.properties.DrawDraftProperty( - context.editorContext, - draft, - settings, - path, - property, - settingsEdits, - draft.readOnly - ); - } - } - catch (Exception error) when ((error is IOException - or UnauthorizedAccessException - or InvalidOperationException - or ArgumentException - or FormatException) - && RetirementPendingException.Find(error) is null) - { - EditorUI.current.widgets.Hint( - "Settings unavailable · " + state.stableTypeId + " · " + error.Message + " · Stored properties and dependencies are retained." - ); - } - } - } - - private sealed class DraftEdits( - PipelineDocuments documents, - Guid id, - RenderPipelineAsset pipeline - ) : IInspectionPropertyEditService - { - /// - public bool ChangeProperty( - object owner, - string propertyName, - Action mutation, - string historyName, - string? mergeKey, - string? componentName - ) { - mutation(); - documents.Replace(id, pipeline, mergeKey); - return true; - } - } - - private sealed class SettingsEdits( - DraftEdits edits, - Action capture - ) : IInspectionPropertyEditService - { - /// - public bool ChangeProperty( - object owner, - string propertyName, - Action mutation, - string historyName, - string? mergeKey, - string? componentName - ) => edits.ChangeProperty(owner, propertyName, () => - { - mutation(); - capture(); - }, historyName, mergeKey, componentName); - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspector.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspector.cs new file mode 100644 index 000000000..dd3f70add --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineInspector.cs @@ -0,0 +1,238 @@ +using System; +using System.IO; +using Inno.Core.Execution; +using Inno.Core.Serialization; +using Inno.Editor.Assets; +using Inno.Editor.Inspection; +using Inno.Editor.Rendering; +using Inno.Rendering.Assets; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using ImGuiApi = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Panel.Inspector; + +internal static class PipelineInspector +{ + internal static void DrawHeader( + InspectionDrawContext context, + PipelineDocuments documents, + Guid id + ) { + AssetDraftDocuments.Draft draft = documents.drafts.GetDraft(id); + ImGuiApi.BeginDisabled(draft.readOnly); + try + { + if (ImGuiApi.Button("Save")) + { + _ = context.interactions.documents.Save(draft.documentID); + } + ImGuiApi.SameLine(0f, -1f); + if (ImGuiApi.Button("Revert")) + { + _ = context.interactions.documents.Revert(draft.documentID); + } + } + finally + { + ImGuiApi.EndDisabled(); + } + } + + internal static void Draw( + InspectionDrawContext context, + PipelineDocuments documents, + Guid id + ) { + AssetDraftDocuments.Draft draft = documents.drafts.GetDraft(id); + RenderPipelineAsset pipeline = documents.Read(id); + var edits = new DraftEdits(documents, id, pipeline); + ImGuiApi.PushID(id.ToString("N")); + try + { + if (EditorUI.current.widgets.SectionHeader( + "Render Pipeline", + "This source is the configuration authority. Unsaved settings do not change Scene, Game or Player content." + )) { + EditorUI.current.widgets.Hint( + draft.isDirty ? "Unsaved changes · rendering unchanged" : "Saved · import and activation are separate" + ); + if (draft.error.Length != 0) + { + EditorUI.current.widgets.Hint(draft.error); + } + if (draft.readOnly) + { + EditorUI.current.widgets.Hint("Installed Pipeline · copy into the project to edit"); + } + EditorUI.current.widgets.Hint("Pipeline: " + pipeline.pipelineTypeId); + DrawSettings("pipeline.settings", pipeline.pipelineState, value => pipeline.pipelineState = value); + } + + bool featuresOpen = EditorUI.current.widgets.SectionHeader( + "Features", + "Ordered extension settings belong to this Pipeline. Each enabled feature participates in its render graph." + ); + RenderFeatureConfiguration[] features = pipeline.features; + for (int index = 0; featuresOpen && index < features.Length; index++) + { + int slot = index; + ImGuiApi.PushID(slot); + try + { + RenderFeatureConfiguration feature = features[slot]; + context.properties.DrawValue( + context.editorContext, + draft, + "pipeline.features." + + slot + + ".enabled", + feature.featureTypeId, + typeof(bool), + () => features[slot].enabled, + value => + { + features[slot].enabled = (bool)value!; + pipeline.features = features; + }, + edits, + draft.readOnly + ); + DrawSettings("pipeline.features." + slot, feature.state, value => + { + features[slot].state = value; + pipeline.features = features; + }); + ImGuiApi.BeginDisabled(draft.readOnly); + try + { + if (slot > 0 && ImGuiApi.SmallButton("Move Up")) + { + (features[slot - 1], features[slot]) = (features[slot], features[slot - 1]); + pipeline.features = features; + documents.Replace(id, pipeline); + break; + } + + if (slot + 1 < features.Length) + { + if (slot > 0) + { + ImGuiApi.SameLine(0f, -1f); + } + if (ImGuiApi.SmallButton("Move Down")) + { + (features[slot + 1], features[slot]) = (features[slot], features[slot + 1]); + pipeline.features = features; + documents.Replace(id, pipeline); + break; + } + } + } + finally + { + ImGuiApi.EndDisabled(); + } + } + finally + { + ImGuiApi.PopID(); + } + } + + if (featuresOpen && features.Length == 0) + { + EditorUI.current.widgets.Hint("No additional features"); + } + } + finally + { + ImGuiApi.PopID(); + } + + void DrawSettings( + string path, + SerializedRenderExtensionState state, + Action assign + ) { + try + { + ISerializable? settings = documents.RestoreSettings(state); + if (settings is null) + { + EditorUI.current.widgets.Hint("No typed settings"); + return; + } + + var settingsEdits = new SettingsEdits( + edits, + () => assign(new SerializedRenderExtensionState(documents.assets.CaptureProperties(settings))) + ); + foreach (SerializedProperty property in documents.serialization.GetProperties(settings)) + { + context.properties.DrawDraftProperty( + context.editorContext, + draft, + settings, + path, + property, + settingsEdits, + draft.readOnly + ); + } + } + catch (Exception error) when ((error is IOException + or UnauthorizedAccessException + or InvalidOperationException + or ArgumentException + or FormatException) + && RetirementPendingException.Find(error) is null) + { + EditorUI.current.widgets.Hint( + "Settings unavailable · " + state.stableTypeId + " · " + error.Message + " · Stored properties and dependencies are retained." + ); + } + } + } + + private sealed class DraftEdits( + PipelineDocuments documents, + Guid id, + RenderPipelineAsset pipeline + ) : IInspectionPropertyEditService + { + /// + public bool ChangeProperty( + object owner, + string propertyName, + Action mutation, + string historyName, + string? mergeKey, + string? componentName + ) { + mutation(); + documents.Replace(id, pipeline, mergeKey); + return true; + } + } + + private sealed class SettingsEdits( + DraftEdits edits, + Action capture + ) : IInspectionPropertyEditService + { + /// + public bool ChangeProperty( + object owner, + string propertyName, + Action mutation, + string historyName, + string? mergeKey, + string? componentName + ) => edits.ChangeProperty(owner, propertyName, () => + { + mutation(); + capture(); + }, historyName, mergeKey, componentName); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineSourceDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineSourceDrawer.cs new file mode 100644 index 000000000..fd8db373f --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Inspector/Targets/PipelineSourceDrawer.cs @@ -0,0 +1,100 @@ +using System; +using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; +using Inno.Editor.Rendering; + +namespace Inno.Editor.Panel.Inspector; + +[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] +internal sealed class PipelineSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer +{ + /// + /// Gets the icon glyph used to represent this item in the editor. + /// + public override string icon => ImGuiIcon.C_FILE; + + /// + /// Retrieves the current icon from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated text representation owned by the caller. + /// + protected override string GetIcon( + InspectionDrawContext context, + AssetFileEntry target + ) => icons.GetIcon(target); + + /// + /// Checks whether this drawer supports the selected Inspector target. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// when the documented condition is satisfied; otherwise, . + /// + protected override bool CanInspect(AssetFileEntry target) + => !target.isDirectory && target.extension.Equals(".irenderpipeline", StringComparison.OrdinalIgnoreCase); + + /// + /// Binds a caller-visible label to the current inspection target. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated (string name, actionstring? setter) that represents the completed operation. + /// + protected override (string name, Action? setter) BindName( + InspectionDrawContext context, + AssetFileEntry target + ) => (target.nameWithoutExtension, null); + + /// + /// Renders the header presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void DrawHeader( + InspectionDrawContext context, + AssetFileEntry target + ) { + if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null) + { + PipelineInspector.DrawHeader(context, documents, documents.Open(target.assetPath)); + } + } + + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void Draw( + InspectionDrawContext context, + AssetFileEntry target + ) { + if (context.interactions.TryGetModule(out PipelineDocuments? documents) && documents is not null) + { + PipelineInspector.Draw(context, documents, documents.Open(target.assetPath)); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettings.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ClearConsoleOnPlaySetting.cs similarity index 71% rename from src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettings.cs rename to src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ClearConsoleOnPlaySetting.cs index d7ac2b2fa..da0a130c2 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettings.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ClearConsoleOnPlaySetting.cs @@ -4,24 +4,6 @@ namespace Inno.Editor.Panel.Logging; -[EditorSettingPath("Editor/Diagnostics")] -internal sealed class DiagnosticsSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Configure diagnostic presentation and retention behavior for this editor."; -} - -[EditorSettingPath("Editor/Diagnostics/Console")] -internal sealed class ConsoleSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Configure how the Console retains ordinary logs across editor workflows."; -} - [EditorSettingPath(C_PATH)] internal sealed class ClearConsoleOnPlaySetting : EditorSetting { diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettingsPage.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettingsPage.cs new file mode 100644 index 000000000..621888974 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/ConsoleSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Panel.Logging; + +[EditorSettingPath("Editor/Diagnostics/Console")] +internal sealed class ConsoleSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Configure how the Console retains ordinary logs across editor workflows."; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/DiagnosticsSettingsPage.cs b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/DiagnosticsSettingsPage.cs new file mode 100644 index 000000000..35c8074fd --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Logging/Settings/DiagnosticsSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Panel.Logging; + +[EditorSettingPath("Editor/Diagnostics")] +internal sealed class DiagnosticsSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Configure diagnostic presentation and retention behavior for this editor."; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsField.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsField.cs new file mode 100644 index 000000000..b7862e9f1 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsField.cs @@ -0,0 +1,255 @@ +using System; +using Inno.Build; +using Inno.Build.Managed; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Panel.Settings; + +internal sealed class BuildSettingsField +{ + private const int C_TEXT_CAPACITY = 4096; + + internal BuildSettingsField( + BuildSettingsKey key, + string path, + string section, + string description + ) { + this.key = key; + this.path = path; + this.pagePath = path[..path.LastIndexOf('/')]; + this.label = path[(path.LastIndexOf('/') + 1)..]; + this.section = section; + this.description = description; + } + + internal BuildSettingsKey key { get; } + internal string path { get; } + internal string pagePath { get; } + internal string label { get; } + internal string section { get; } + internal string description { get; } + + internal bool Draw( + BuildSettings settings, + BuildPipeline buildPipeline + ) => key switch + { + BuildSettingsKey.GameProductName => DrawTextValue(settings.gameProductName, value => settings.gameProductName = value), + BuildSettingsKey.GamePersistentDataPath => DrawTextValue( + settings.gamePersistentDataPath, + value => settings.gamePersistentDataPath = value + ), + BuildSettingsKey.GameStartupScene => DrawTextValue(settings.gameStartupScene, value => settings.gameStartupScene = value), + BuildSettingsKey.GameWindowWidth => DrawPositiveInt(settings.gameWindowWidth, value => settings.gameWindowWidth = value), + BuildSettingsKey.GameWindowHeight => DrawPositiveInt(settings.gameWindowHeight, value => settings.gameWindowHeight = value), + BuildSettingsKey.GameTarget => DrawTarget(settings, buildPipeline), + BuildSettingsKey.GameManagedDeployment => DrawManagedDeployment(settings, buildPipeline), + BuildSettingsKey.GameOutputDirectory => DrawTextValue(settings.gameOutputDirectory, value => settings.gameOutputDirectory = value), + BuildSettingsKey.PluginDisplayName => DrawTextValue(settings.pluginDisplayName, value => settings.pluginDisplayName = value), + BuildSettingsKey.PluginOutputPath => DrawTextValue(settings.pluginOutputPath, value => settings.pluginOutputPath = value), + BuildSettingsKey.IncludePluginDependencies => DrawIncludeDependencies(settings), + _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.") + }; + + internal bool IsDefault( + BuildSettings settings, + BuildSettings defaults + ) => key switch + { + BuildSettingsKey.GameProductName => settings.gameProductName == defaults.gameProductName, + BuildSettingsKey.GamePersistentDataPath => settings.gamePersistentDataPath == defaults.gamePersistentDataPath, + BuildSettingsKey.GameStartupScene => settings.gameStartupScene == defaults.gameStartupScene, + BuildSettingsKey.GameWindowWidth => settings.gameWindowWidth == defaults.gameWindowWidth, + BuildSettingsKey.GameWindowHeight => settings.gameWindowHeight == defaults.gameWindowHeight, + BuildSettingsKey.GameTarget => settings.gameTarget == defaults.gameTarget, + BuildSettingsKey.GameManagedDeployment => settings.gameManagedDeployment == defaults.gameManagedDeployment, + BuildSettingsKey.GameOutputDirectory => settings.gameOutputDirectory == defaults.gameOutputDirectory, + BuildSettingsKey.PluginDisplayName => settings.pluginDisplayName == defaults.pluginDisplayName, + BuildSettingsKey.PluginOutputPath => settings.pluginOutputPath == defaults.pluginOutputPath, + BuildSettingsKey.IncludePluginDependencies => settings.includePluginDependencies == defaults.includePluginDependencies, + _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.") + }; + + internal void Reset( + BuildSettings settings, + BuildSettings defaults + ) { + switch (key) + { + case BuildSettingsKey.GameProductName: + settings.gameProductName = defaults.gameProductName; + break; + case BuildSettingsKey.GamePersistentDataPath: + settings.gamePersistentDataPath = defaults.gamePersistentDataPath; + break; + case BuildSettingsKey.GameStartupScene: + settings.gameStartupScene = defaults.gameStartupScene; + break; + case BuildSettingsKey.GameWindowWidth: + settings.gameWindowWidth = defaults.gameWindowWidth; + break; + case BuildSettingsKey.GameWindowHeight: + settings.gameWindowHeight = defaults.gameWindowHeight; + break; + case BuildSettingsKey.GameManagedDeployment: + settings.gameManagedDeployment = defaults.gameManagedDeployment; + break; + case BuildSettingsKey.GameTarget: + settings.gameTarget = defaults.gameTarget; + break; + case BuildSettingsKey.GameOutputDirectory: + settings.gameOutputDirectory = defaults.gameOutputDirectory; + break; + case BuildSettingsKey.PluginDisplayName: + settings.pluginDisplayName = defaults.pluginDisplayName; + break; + case BuildSettingsKey.PluginOutputPath: + settings.pluginOutputPath = defaults.pluginOutputPath; + break; + case BuildSettingsKey.IncludePluginDependencies: + settings.includePluginDependencies = defaults.includePluginDependencies; + break; + default: + throw new InvalidOperationException($"Unknown Build Settings field '{key}'."); + } + } + + internal static bool ValuesEqual( + BuildSettings left, + BuildSettings right + ) => string.Equals(left.gameProductName, right.gameProductName, StringComparison.Ordinal) + && string.Equals(left.gamePersistentDataPath, right.gamePersistentDataPath, StringComparison.Ordinal) + && string.Equals(left.gameStartupScene, right.gameStartupScene, StringComparison.Ordinal) + && string.Equals(left.gameOutputDirectory, right.gameOutputDirectory, StringComparison.Ordinal) + && left.gameWindowWidth == right.gameWindowWidth + && left.gameWindowHeight == right.gameWindowHeight + && left.gameTarget == right.gameTarget + && left.gameManagedDeployment == right.gameManagedDeployment + && string.Equals(left.pluginDisplayName, right.pluginDisplayName, StringComparison.Ordinal) + && string.Equals(left.pluginOutputPath, right.pluginOutputPath, StringComparison.Ordinal) + && left.includePluginDependencies == right.includePluginDependencies; + + private static bool DrawTextValue( + string value, + Action apply + ) { + Gui.SetNextItemWidth(-1f); + if (!Gui.InputText("##value", ref value, C_TEXT_CAPACITY)) + { + return false; + } + apply(value); + return true; + } + + private static bool DrawPositiveInt( + int value, + Action apply + ) { + Gui.SetNextItemWidth(-1f); + if (!Gui.InputInt("##value", ref value, 1, 100, 0)) + { + return false; + } + apply(Math.Max(1, value)); + return true; + } + + private static bool DrawManagedDeployment( + BuildSettings settings, + BuildPipeline buildPipeline + ) { + bool changed = false; + Gui.SetNextItemWidth(-1f); + if (!EditorUI.current.widgets.BeginBoundedCombo("##value", settings.gameManagedDeployment?.value ?? "Platform default")) + { + return false; + } + try + { + if (Gui.Selectable("Platform default", settings.gameManagedDeployment is null)) + { + settings.gameManagedDeployment = null; + changed = true; + } + + foreach (ManagedDeploymentID deployment in buildPipeline.GetManagedDeployments(settings.gameTarget)) + { + if (!Gui.Selectable(deployment.value, settings.gameManagedDeployment == deployment)) + { + continue; + } + settings.gameManagedDeployment = deployment; + changed = true; + } + } + finally + { + EditorUI.current.widgets.EndBoundedCombo(); + } + + return changed; + } + + private static bool DrawTarget( + BuildSettings settings, + BuildPipeline buildPipeline + ) { + bool changed = false; + Gui.SetNextItemWidth(-1f); + if (!EditorUI.current.widgets.BeginBoundedCombo("##value", GetTargetLabel(settings.gameTarget, buildPipeline))) + { + return false; + } + try + { + foreach (BuildTargetID target in buildPipeline.availableGameTargets) + { + changed |= DrawTargetChoice(settings, target, buildPipeline); + } + } + finally + { + EditorUI.current.widgets.EndBoundedCombo(); + } + + return changed; + } + + private static bool DrawIncludeDependencies(BuildSettings settings) + { + bool value = settings.includePluginDependencies; + if (!Gui.Checkbox("##value", ref value)) + { + return false; + } + settings.includePluginDependencies = value; + return true; + } + + private static bool DrawTargetChoice( + BuildSettings settings, + BuildTargetID target, + BuildPipeline buildPipeline + ) { + bool selected = settings.gameTarget == target; + bool changed = Gui.Selectable(GetTargetLabel(target, buildPipeline), selected); + if (changed) + { + settings.gameTarget = target; + } + if (selected) + { + Gui.SetItemDefaultFocus(); + } + return changed; + } + + private static string GetTargetLabel( + BuildTargetID target, + BuildPipeline buildPipeline + ) => buildPipeline.TryGetGameTargetDisplayName(target, out string displayName) ? displayName : $"Missing ({target})"; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs index 9cd955866..7fb541719 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Presentation/BuildSettingsPresentation.cs @@ -1,276 +1,7 @@ -using System; using System.Collections.Generic; -using Inno.Build; -using Inno.Build.Managed; -using Inno.Editor.ImGui; - -using EditorUI = Inno.Editor.ImGui.EditorUISession; -using Gui = Inno.Editor.ImGui.ImGui; namespace Inno.Editor.Panel.Settings; -internal enum BuildSettingsKey -{ - GameProductName, - GamePersistentDataPath, - GameStartupScene, - GameWindowWidth, - GameWindowHeight, - GameTarget, - GameManagedDeployment, - GameOutputDirectory, - PluginDisplayName, - PluginOutputPath, - IncludePluginDependencies -} - -internal sealed class BuildSettingsField -{ - private const int C_TEXT_CAPACITY = 4096; - - internal BuildSettingsField( - BuildSettingsKey key, - string path, - string section, - string description - ) { - this.key = key; - this.path = path; - this.pagePath = path[..path.LastIndexOf('/')]; - this.label = path[(path.LastIndexOf('/') + 1)..]; - this.section = section; - this.description = description; - } - - internal BuildSettingsKey key { get; } - internal string path { get; } - internal string pagePath { get; } - internal string label { get; } - internal string section { get; } - internal string description { get; } - - internal bool Draw( - BuildSettings settings, - BuildPipeline buildPipeline - ) => key switch - { - BuildSettingsKey.GameProductName => DrawTextValue(settings.gameProductName, value => settings.gameProductName = value), - BuildSettingsKey.GamePersistentDataPath => DrawTextValue( - settings.gamePersistentDataPath, - value => settings.gamePersistentDataPath = value - ), - BuildSettingsKey.GameStartupScene => DrawTextValue(settings.gameStartupScene, value => settings.gameStartupScene = value), - BuildSettingsKey.GameWindowWidth => DrawPositiveInt(settings.gameWindowWidth, value => settings.gameWindowWidth = value), - BuildSettingsKey.GameWindowHeight => DrawPositiveInt(settings.gameWindowHeight, value => settings.gameWindowHeight = value), - BuildSettingsKey.GameTarget => DrawTarget(settings, buildPipeline), - BuildSettingsKey.GameManagedDeployment => DrawManagedDeployment(settings, buildPipeline), - BuildSettingsKey.GameOutputDirectory => DrawTextValue(settings.gameOutputDirectory, value => settings.gameOutputDirectory = value), - BuildSettingsKey.PluginDisplayName => DrawTextValue(settings.pluginDisplayName, value => settings.pluginDisplayName = value), - BuildSettingsKey.PluginOutputPath => DrawTextValue(settings.pluginOutputPath, value => settings.pluginOutputPath = value), - BuildSettingsKey.IncludePluginDependencies => DrawIncludeDependencies(settings), - _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.") - }; - - internal bool IsDefault( - BuildSettings settings, - BuildSettings defaults - ) => key switch - { - BuildSettingsKey.GameProductName => settings.gameProductName == defaults.gameProductName, - BuildSettingsKey.GamePersistentDataPath => settings.gamePersistentDataPath == defaults.gamePersistentDataPath, - BuildSettingsKey.GameStartupScene => settings.gameStartupScene == defaults.gameStartupScene, - BuildSettingsKey.GameWindowWidth => settings.gameWindowWidth == defaults.gameWindowWidth, - BuildSettingsKey.GameWindowHeight => settings.gameWindowHeight == defaults.gameWindowHeight, - BuildSettingsKey.GameTarget => settings.gameTarget == defaults.gameTarget, - BuildSettingsKey.GameManagedDeployment => settings.gameManagedDeployment == defaults.gameManagedDeployment, - BuildSettingsKey.GameOutputDirectory => settings.gameOutputDirectory == defaults.gameOutputDirectory, - BuildSettingsKey.PluginDisplayName => settings.pluginDisplayName == defaults.pluginDisplayName, - BuildSettingsKey.PluginOutputPath => settings.pluginOutputPath == defaults.pluginOutputPath, - BuildSettingsKey.IncludePluginDependencies => settings.includePluginDependencies == defaults.includePluginDependencies, - _ => throw new InvalidOperationException($"Unknown Build Settings field '{key}'.") - }; - - internal void Reset( - BuildSettings settings, - BuildSettings defaults - ) { - switch (key) - { - case BuildSettingsKey.GameProductName: - settings.gameProductName = defaults.gameProductName; - break; - case BuildSettingsKey.GamePersistentDataPath: - settings.gamePersistentDataPath = defaults.gamePersistentDataPath; - break; - case BuildSettingsKey.GameStartupScene: - settings.gameStartupScene = defaults.gameStartupScene; - break; - case BuildSettingsKey.GameWindowWidth: - settings.gameWindowWidth = defaults.gameWindowWidth; - break; - case BuildSettingsKey.GameWindowHeight: - settings.gameWindowHeight = defaults.gameWindowHeight; - break; - case BuildSettingsKey.GameManagedDeployment: - settings.gameManagedDeployment = defaults.gameManagedDeployment; - break; - case BuildSettingsKey.GameTarget: - settings.gameTarget = defaults.gameTarget; - break; - case BuildSettingsKey.GameOutputDirectory: - settings.gameOutputDirectory = defaults.gameOutputDirectory; - break; - case BuildSettingsKey.PluginDisplayName: - settings.pluginDisplayName = defaults.pluginDisplayName; - break; - case BuildSettingsKey.PluginOutputPath: - settings.pluginOutputPath = defaults.pluginOutputPath; - break; - case BuildSettingsKey.IncludePluginDependencies: - settings.includePluginDependencies = defaults.includePluginDependencies; - break; - default: - throw new InvalidOperationException($"Unknown Build Settings field '{key}'."); - } - } - - internal static bool ValuesEqual( - BuildSettings left, - BuildSettings right - ) => string.Equals(left.gameProductName, right.gameProductName, StringComparison.Ordinal) - && string.Equals(left.gamePersistentDataPath, right.gamePersistentDataPath, StringComparison.Ordinal) - && string.Equals(left.gameStartupScene, right.gameStartupScene, StringComparison.Ordinal) - && string.Equals(left.gameOutputDirectory, right.gameOutputDirectory, StringComparison.Ordinal) - && left.gameWindowWidth == right.gameWindowWidth - && left.gameWindowHeight == right.gameWindowHeight - && left.gameTarget == right.gameTarget - && left.gameManagedDeployment == right.gameManagedDeployment - && string.Equals(left.pluginDisplayName, right.pluginDisplayName, StringComparison.Ordinal) - && string.Equals(left.pluginOutputPath, right.pluginOutputPath, StringComparison.Ordinal) - && left.includePluginDependencies == right.includePluginDependencies; - - private static bool DrawTextValue( - string value, - Action apply - ) { - Gui.SetNextItemWidth(-1f); - if (!Gui.InputText("##value", ref value, C_TEXT_CAPACITY)) - { - return false; - } - apply(value); - return true; - } - - private static bool DrawPositiveInt( - int value, - Action apply - ) { - Gui.SetNextItemWidth(-1f); - if (!Gui.InputInt("##value", ref value, 1, 100, 0)) - { - return false; - } - apply(Math.Max(1, value)); - return true; - } - - private static bool DrawManagedDeployment( - BuildSettings settings, - BuildPipeline buildPipeline - ) { - bool changed = false; - Gui.SetNextItemWidth(-1f); - if (!EditorUI.current.widgets.BeginBoundedCombo("##value", settings.gameManagedDeployment?.value ?? "Platform default")) - { - return false; - } - try - { - if (Gui.Selectable("Platform default", settings.gameManagedDeployment is null)) - { - settings.gameManagedDeployment = null; - changed = true; - } - - foreach (ManagedDeploymentID deployment in buildPipeline.GetManagedDeployments(settings.gameTarget)) - { - if (!Gui.Selectable(deployment.value, settings.gameManagedDeployment == deployment)) - { - continue; - } - settings.gameManagedDeployment = deployment; - changed = true; - } - } - finally - { - EditorUI.current.widgets.EndBoundedCombo(); - } - - return changed; - } - - private static bool DrawTarget( - BuildSettings settings, - BuildPipeline buildPipeline - ) { - bool changed = false; - Gui.SetNextItemWidth(-1f); - if (!EditorUI.current.widgets.BeginBoundedCombo("##value", GetTargetLabel(settings.gameTarget, buildPipeline))) - { - return false; - } - try - { - foreach (BuildTargetID target in buildPipeline.availableGameTargets) - { - changed |= DrawTargetChoice(settings, target, buildPipeline); - } - } - finally - { - EditorUI.current.widgets.EndBoundedCombo(); - } - - return changed; - } - - private static bool DrawIncludeDependencies(BuildSettings settings) - { - bool value = settings.includePluginDependencies; - if (!Gui.Checkbox("##value", ref value)) - { - return false; - } - settings.includePluginDependencies = value; - return true; - } - - private static bool DrawTargetChoice( - BuildSettings settings, - BuildTargetID target, - BuildPipeline buildPipeline - ) { - bool selected = settings.gameTarget == target; - bool changed = Gui.Selectable(GetTargetLabel(target, buildPipeline), selected); - if (changed) - { - settings.gameTarget = target; - } - if (selected) - { - Gui.SetItemDefaultFocus(); - } - return changed; - } - - private static string GetTargetLabel( - BuildTargetID target, - BuildPipeline buildPipeline - ) => buildPipeline.TryGetGameTargetDisplayName(target, out string displayName) ? displayName : $"Missing ({target})"; -} - internal static class BuildSettingsPresentation { internal static IReadOnlyList fields { get; } = @@ -343,3 +74,18 @@ internal static class BuildSettingsPresentation ) ]; } + +internal enum BuildSettingsKey +{ + GameProductName, + GamePersistentDataPath, + GameStartupScene, + GameWindowWidth, + GameWindowHeight, + GameTarget, + GameManagedDeployment, + GameOutputDirectory, + PluginDisplayName, + PluginOutputPath, + IncludePluginDependencies +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs index 3a6f78913..5eb4750f0 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistory.cs @@ -1,7 +1,6 @@ using System; using System.Buffers.Binary; using System.IO; -using Inno.Build; using Inno.Editor.Interactions; namespace Inno.Editor.Panel.Settings; @@ -38,86 +37,3 @@ internal static (ReadOnlyMemory before, ReadOnlyMemory after) Read(E payload.AsMemory(sizeof(int) + beforeLength)); } } - -[EditorHistoryHandler(BuildSettingsHistory.C_KIND)] -internal sealed class BuildSettingsHistoryHandler(BuildSettingsStore settings) : EditorHistoryHandler -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history availability that represents the completed operation. - /// - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = BuildSettingsHistory.Read(change); - settings.ValidateDocument(before.Span); - settings.ValidateDocument(after.Span); - return EditorHistoryAvailability.Available(); - } - catch (Exception exception) when ( - exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) - { - return EditorHistoryAvailability.Unavailable(exception.Message); - } - } - - /// - /// Applies a validated change atomically at the caller-controlled commit point. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The neutral change payload to query or apply. - /// - /// - /// The history direction that determines which state is applied. - /// - /// - /// The validated editor history result that represents the completed operation. - /// - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - byte[] original = settings.CaptureDocument(); - try - { - (ReadOnlyMemory before, ReadOnlyMemory after) = BuildSettingsHistory.Read(change); - settings.RestoreDocument(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); - return EditorHistoryResult.Success(); - } - catch (Exception exception) when ( - exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) - { - try - { - settings.RestoreDocument(original); - } - catch (Exception rollbackException) - { - return StateIntegrityFailure( - $"Build Settings transition failed: {exception.Message} " - + $"Rollback failed: {rollbackException.Message}" - ); - } - return EditorHistoryResult.Failure(exception.Message); - } - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistoryHandler.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistoryHandler.cs new file mode 100644 index 000000000..6830a1a96 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/BuildSettingsHistoryHandler.cs @@ -0,0 +1,89 @@ +using System; +using System.IO; +using Inno.Build; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.Settings; + +[EditorHistoryHandler(BuildSettingsHistory.C_KIND)] +internal sealed class BuildSettingsHistoryHandler(BuildSettingsStore settings) : EditorHistoryHandler +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history availability that represents the completed operation. + /// + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = BuildSettingsHistory.Read(change); + settings.ValidateDocument(before.Span); + settings.ValidateDocument(after.Span); + return EditorHistoryAvailability.Available(); + } + catch (Exception exception) when ( + exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) + { + return EditorHistoryAvailability.Unavailable(exception.Message); + } + } + + /// + /// Applies a validated change atomically at the caller-controlled commit point. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The neutral change payload to query or apply. + /// + /// + /// The history direction that determines which state is applied. + /// + /// + /// The validated editor history result that represents the completed operation. + /// + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + byte[] original = settings.CaptureDocument(); + try + { + (ReadOnlyMemory before, ReadOnlyMemory after) = BuildSettingsHistory.Read(change); + settings.RestoreDocument(direction == EditorHistoryDirection.Undo ? before.Span : after.Span); + return EditorHistoryResult.Success(); + } + catch (Exception exception) when ( + exception is InvalidDataException or InvalidOperationException or IOException or UnauthorizedAccessException) + { + try + { + settings.RestoreDocument(original); + } + catch (Exception rollbackException) + { + return StateIntegrityFailure( + $"Build Settings transition failed: {exception.Message} " + + $"Rollback failed: {rollbackException.Message}" + ); + } + return EditorHistoryResult.Failure(exception.Message); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs index e0168d6ff..dc951466c 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsEditSession.cs @@ -9,67 +9,6 @@ namespace Inno.Editor.Panel.Settings; -internal enum SettingsScope -{ - Editor, - Project, - Build -} - -internal sealed class SettingsField -{ - private readonly BuildSettingsField? m_build; - private readonly EditorSetting? m_editor; - private readonly ProjectSettingEditor? m_project; - - internal SettingsField(EditorSetting definition) - { - m_editor = definition; - this.scope = SettingsScope.Editor; - this.path = definition.path; - this.pagePath = definition.pagePath; - this.label = definition.label; - this.order = definition.order; - this.section = definition.section ?? string.Empty; - this.description = definition.description; - } - - internal SettingsField(ProjectSettingEditor definition) - { - m_project = definition; - this.scope = SettingsScope.Project; - this.path = definition.path; - this.pagePath = definition.pagePath; - this.label = definition.label; - this.order = definition.order; - this.section = definition.section ?? string.Empty; - this.description = definition.description; - } - - internal SettingsField(BuildSettingsField definition) - { - m_build = definition; - this.scope = SettingsScope.Build; - this.path = definition.path; - this.pagePath = definition.pagePath; - this.label = definition.label; - this.order = 0; - this.section = definition.section; - this.description = definition.description; - } - - internal SettingsScope scope { get; } - internal string path { get; } - internal string pagePath { get; } - internal string label { get; } - internal int order { get; } - internal string section { get; } - internal string description { get; } - internal EditorSetting? editor => m_editor; - internal ProjectSettingEditor? project => m_project; - internal BuildSettingsField? build => m_build; -} - internal sealed class SettingsEditSession : IDisposable { private readonly EditorSettings m_editorSettings; @@ -605,6 +544,13 @@ internal SettingsPage Build() } } +internal enum SettingsScope +{ + Editor, + Project, + Build +} + internal sealed record SettingsPage( string path, string label, diff --git a/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsField.cs b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsField.cs new file mode 100644 index 000000000..1918fcaa6 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.Settings/Runtime/SettingsField.cs @@ -0,0 +1,57 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Panel.Settings; + +internal sealed class SettingsField +{ + private readonly BuildSettingsField? m_build; + private readonly EditorSetting? m_editor; + private readonly ProjectSettingEditor? m_project; + + internal SettingsField(EditorSetting definition) + { + m_editor = definition; + this.scope = SettingsScope.Editor; + this.path = definition.path; + this.pagePath = definition.pagePath; + this.label = definition.label; + this.order = definition.order; + this.section = definition.section ?? string.Empty; + this.description = definition.description; + } + + internal SettingsField(ProjectSettingEditor definition) + { + m_project = definition; + this.scope = SettingsScope.Project; + this.path = definition.path; + this.pagePath = definition.pagePath; + this.label = definition.label; + this.order = definition.order; + this.section = definition.section ?? string.Empty; + this.description = definition.description; + } + + internal SettingsField(BuildSettingsField definition) + { + m_build = definition; + this.scope = SettingsScope.Build; + this.path = definition.path; + this.pagePath = definition.pagePath; + this.label = definition.label; + this.order = 0; + this.section = definition.section; + this.description = definition.description; + } + + internal SettingsScope scope { get; } + internal string path { get; } + internal string pagePath { get; } + internal string label { get; } + internal int order { get; } + internal string section { get; } + internal string description { get; } + internal EditorSetting? editor => m_editor; + internal ProjectSettingEditor? project => m_project; + internal BuildSettingsField? build => m_build; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs index 970d42312..238c6d503 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Clipboard.cs @@ -8,11 +8,6 @@ namespace Inno.Editor.Panel.ShaderEditor; -internal sealed record ShaderClipboardData( - byte[] graph, - Guid owner -); - internal sealed partial class ShaderEditorDocuments { internal ShaderClipboardData Copy(Draft draft) @@ -61,3 +56,8 @@ ShaderClipboardData clipboard Changed(draft); } } + +internal sealed record ShaderClipboardData( + byte[] graph, + Guid owner +); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs index 101856471..cd3f627bf 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.Creation.cs @@ -5,19 +5,12 @@ using Inno.Assets; using Inno.Core.Execution; using Inno.Core.Graphs; -using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; -internal sealed record ShaderNodeCreation( - string definitionID, - Guid sourceID = default, - string function = "" -); - internal sealed partial class ShaderEditorDocuments { internal GraphNodeRecord PrepareNode( @@ -252,3 +245,9 @@ out ShaderGraphNodeInterface? nodeInterface return true; } } + +internal sealed record ShaderNodeCreation( + string definitionID, + Guid sourceID = default, + string function = "" +); diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs index bd7444bf7..d9c95f9a5 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderEditorDocuments.cs @@ -13,7 +13,6 @@ using Inno.Core.IO; using Inno.Core.Serialization; using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using Inno.Editor.Core; using Inno.Editor.Graph; using Inno.Editor.Graph.ImGui; @@ -22,7 +21,6 @@ using Inno.Editor.Shaders; using Inno.Editor.Shaders.ImGui; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Shaders; @@ -980,26 +978,3 @@ private sealed class RecoveryData : ISerializable public byte[] graph { get; set; } = []; } } - -internal struct ShaderPortSnapshot -{ - /// - /// Gets the stable identity used to reference this value across subsystem boundaries. - /// - public string id { get; set; } - - /// - /// Gets the graph port's shader value type. - /// - public ShaderGraphType type { get; set; } - - /// - /// Gets the graph port's input or output direction. - /// - public GraphPortDirection direction { get; set; } - - /// - /// Gets whether required is active for the current instance. - /// - public bool required { get; set; } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderPortSnapshot.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderPortSnapshot.cs new file mode 100644 index 000000000..4e147b56f --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Documents/ShaderPortSnapshot.cs @@ -0,0 +1,27 @@ +using Inno.Core.Graphs; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +internal struct ShaderPortSnapshot +{ + /// + /// Gets the stable identity used to reference this value across subsystem boundaries. + /// + public string id { get; set; } + + /// + /// Gets the graph port's shader value type. + /// + public ShaderGraphType type { get; set; } + + /// + /// Gets the graph port's input or output direction. + /// + public GraphPortDirection direction { get; set; } + + /// + /// Gets whether required is active for the current instance. + /// + public bool required { get; set; } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderAssetDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderAssetDrawer.cs new file mode 100644 index 000000000..00cac263c --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderAssetDrawer.cs @@ -0,0 +1,88 @@ +using System; +using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; +using Inno.Rendering.Assets; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; + +namespace Inno.Editor.Panel.ShaderEditor; + +[InspectionDrawer(typeof(ShaderAsset))] +internal sealed class ShaderAssetDrawer(IInspectionIconProvider icons) : InspectionDrawer +{ + /// + /// Gets the icon glyph used to represent this item in the editor. + /// + public override string icon => "S"; + + /// + /// Retrieves the current icon from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated text representation owned by the caller. + /// + protected override string GetIcon( + InspectionDrawContext context, + ShaderAsset target + ) => context.interactions.TryGetModule(out ShaderEditorDocuments? documents) + && documents is not null + && documents.assets.TryGetFileSystemEntry( + target.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; + + /// + /// Binds a caller-visible label to the current inspection target. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated (string name, actionstring? setter) that represents the completed operation. + /// + protected override (string name, Action? setter) BindName( + InspectionDrawContext context, + ShaderAsset target + ) => (target.name, null); + + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void Draw( + InspectionDrawContext context, + ShaderAsset target + ) { + if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) || documents is null) + { + return; + } + if (!documents.assets.TryGetFileSystemEntry(target.assetPath, out AssetFileEntry entry)) + { + return; + } + if (documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) + { + new ShaderEditorCanvas(documents, draft).DrawInspector(context, []); + } + else + { + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs deleted file mode 100644 index 9544ba7f3..000000000 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderInspectionDrawers.cs +++ /dev/null @@ -1,310 +0,0 @@ -using System; -using System.IO; -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Core.Graphs; -using Inno.Editor.ImGui; -using Inno.Editor.Inspection; -using Inno.Editor.Shaders; -using Inno.Rendering; -using Inno.Rendering.Assets; - -using EditorUI = Inno.Editor.ImGui.EditorUISession; - -namespace Inno.Editor.Panel.ShaderEditor; - -[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] -internal sealed class ShaderSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer -{ - /// - /// Gets the icon glyph used to represent this item in the editor. - /// - public override string icon => "S"; - - /// - /// Retrieves the current icon from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated text representation owned by the caller. - /// - protected override string GetIcon( - InspectionDrawContext context, - AssetFileEntry target - ) => icons.GetIcon(target); - - /// - /// Checks whether this drawer supports the selected Inspector target. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// when the documented condition is satisfied; otherwise, . - /// - protected override bool CanInspect(AssetFileEntry target) - => !target.isDirectory && target.extension.Equals(".ishader", StringComparison.OrdinalIgnoreCase); - - /// - /// Binds a caller-visible label to the current inspection target. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated (string name, actionstring? setter) that represents the completed operation. - /// - protected override (string name, Action? setter) BindName( - InspectionDrawContext context, - AssetFileEntry target - ) => (target.nameWithoutExtension, null); - - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void Draw( - InspectionDrawContext context, - AssetFileEntry target - ) { - if (context.interactions.TryGetModule(out ShaderEditorDocuments? documents)) - { - if (documents!.TryOpen(target, out ShaderEditorDocuments.Draft draft)) - { - new ShaderEditorCanvas(documents, draft).DrawInspector(context, []); - } - else - { - EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); - } - } - } -} - -[InspectionDrawer(typeof(ShaderInspectionSelection))] -internal sealed class ShaderSelectionDrawer(IInspectionIconProvider icons) : InspectionDrawer -{ - /// - /// Gets the icon glyph used to represent this item in the editor. - /// - public override string icon => "S"; - - /// - /// Retrieves the current icon from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated text representation owned by the caller. - /// - protected override string GetIcon( - InspectionDrawContext context, - ShaderInspectionSelection target - ) => context.interactions.TryGetModule(out ShaderEditorDocuments? documents) - && documents is not null - && documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) - && info is not null - && documents.assets.TryGetFileSystemEntry( - info.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; - - /// - /// Binds a caller-visible label to the current inspection target. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated (string name, actionstring? setter) that represents the completed operation. - /// - protected override (string name, Action? setter) BindName( - InspectionDrawContext context, - ShaderInspectionSelection target - ) { - if (context.interactions.TryGetModule(out ShaderEditorDocuments? documents) - && documents is not null - && documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) - && info is not null - ) { - return (Path.GetFileName(info.assetPath.localPath), null); - } - return ("Shader", null); - } - - /// - /// Renders the header presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void DrawHeader( - InspectionDrawContext context, - ShaderInspectionSelection target - ) { - if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) - || documents is null - || !documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) - || info is null - || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) - ) { - EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Node selection unavailable"); - return; - } - - if (!documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) - { - EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Waiting for Shader asset import…"); - return; - } - - if (target.nodes.Count == 1 && documents.Controller(draft).document.FindNode(target.nodes[0]) is GraphNodeRecord node) - { - EditorUI.current.widgets.ColoredText( - EditorPalette.contextText, - "Node: " + new ShaderEditorCanvas(documents, draft).Title(node) - ); - } - else - { - EditorUI.current.widgets.ColoredText(EditorPalette.contextText, $"Nodes: {target.nodes.Count} selected"); - } - } - - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void Draw( - InspectionDrawContext context, - ShaderInspectionSelection target - ) { - if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) || documents is null) - { - return; - } - if (!documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) - || info is null - || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) - ) { - EditorUI.current.widgets.WrappedText("Shader source unavailable. Selection identities are retained."); - return; - } - - if (documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) - { - new ShaderEditorCanvas(documents, draft).DrawInspector(context, target.nodes); - } - else - { - EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); - } - } -} - -[InspectionDrawer(typeof(ShaderAsset))] -internal sealed class ShaderAssetDrawer(IInspectionIconProvider icons) : InspectionDrawer -{ - /// - /// Gets the icon glyph used to represent this item in the editor. - /// - public override string icon => "S"; - - /// - /// Retrieves the current icon from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated text representation owned by the caller. - /// - protected override string GetIcon( - InspectionDrawContext context, - ShaderAsset target - ) => context.interactions.TryGetModule(out ShaderEditorDocuments? documents) - && documents is not null - && documents.assets.TryGetFileSystemEntry( - target.assetPath, - out AssetFileEntry entry - ) ? icons.GetIcon(entry) : icon; - - /// - /// Binds a caller-visible label to the current inspection target. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated (string name, actionstring? setter) that represents the completed operation. - /// - protected override (string name, Action? setter) BindName( - InspectionDrawContext context, - ShaderAsset target - ) => (target.name, null); - - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void Draw( - InspectionDrawContext context, - ShaderAsset target - ) { - if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) || documents is null) - { - return; - } - if (!documents.assets.TryGetFileSystemEntry(target.assetPath, out AssetFileEntry entry)) - { - return; - } - if (documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) - { - new ShaderEditorCanvas(documents, draft).DrawInspector(context, []); - } - else - { - EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); - } - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSelectionDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSelectionDrawer.cs new file mode 100644 index 000000000..b5e647fc4 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSelectionDrawer.cs @@ -0,0 +1,148 @@ +using System; +using System.IO; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; +using Inno.Editor.Shaders; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; + +namespace Inno.Editor.Panel.ShaderEditor; + +[InspectionDrawer(typeof(ShaderInspectionSelection))] +internal sealed class ShaderSelectionDrawer(IInspectionIconProvider icons) : InspectionDrawer +{ + /// + /// Gets the icon glyph used to represent this item in the editor. + /// + public override string icon => "S"; + + /// + /// Retrieves the current icon from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated text representation owned by the caller. + /// + protected override string GetIcon( + InspectionDrawContext context, + ShaderInspectionSelection target + ) => context.interactions.TryGetModule(out ShaderEditorDocuments? documents) + && documents is not null + && documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) + && info is not null + && documents.assets.TryGetFileSystemEntry( + info.assetPath, + out AssetFileEntry entry + ) ? icons.GetIcon(entry) : icon; + + /// + /// Binds a caller-visible label to the current inspection target. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated (string name, actionstring? setter) that represents the completed operation. + /// + protected override (string name, Action? setter) BindName( + InspectionDrawContext context, + ShaderInspectionSelection target + ) { + if (context.interactions.TryGetModule(out ShaderEditorDocuments? documents) + && documents is not null + && documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) + && info is not null + ) { + return (Path.GetFileName(info.assetPath.localPath), null); + } + return ("Shader", null); + } + + /// + /// Renders the header presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void DrawHeader( + InspectionDrawContext context, + ShaderInspectionSelection target + ) { + if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) + || documents is null + || !documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) + || info is null + || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) + ) { + EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Node selection unavailable"); + return; + } + + if (!documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) + { + EditorUI.current.widgets.ColoredText(EditorPalette.contextText, "Waiting for Shader asset import…"); + return; + } + + if (target.nodes.Count == 1 && documents.Controller(draft).document.FindNode(target.nodes[0]) is GraphNodeRecord node) + { + EditorUI.current.widgets.ColoredText( + EditorPalette.contextText, + "Node: " + new ShaderEditorCanvas(documents, draft).Title(node) + ); + } + else + { + EditorUI.current.widgets.ColoredText(EditorPalette.contextText, $"Nodes: {target.nodes.Count} selected"); + } + } + + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void Draw( + InspectionDrawContext context, + ShaderInspectionSelection target + ) { + if (!context.interactions.TryGetModule(out ShaderEditorDocuments? documents) || documents is null) + { + return; + } + if (!documents.assets.TryGetInfo(target.assetID, out AssetInfo? info) + || info is null + || !documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry) + ) { + EditorUI.current.widgets.WrappedText("Shader source unavailable. Selection identities are retained."); + return; + } + + if (documents.TryOpen(entry, out ShaderEditorDocuments.Draft draft)) + { + new ShaderEditorCanvas(documents, draft).DrawInspector(context, target.nodes); + } + else + { + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSourceDrawer.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSourceDrawer.cs new file mode 100644 index 000000000..7be921242 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Inspection/ShaderSourceDrawer.cs @@ -0,0 +1,89 @@ +using System; +using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; + +namespace Inno.Editor.Panel.ShaderEditor; + +[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] +internal sealed class ShaderSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer +{ + /// + /// Gets the icon glyph used to represent this item in the editor. + /// + public override string icon => "S"; + + /// + /// Retrieves the current icon from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated text representation owned by the caller. + /// + protected override string GetIcon( + InspectionDrawContext context, + AssetFileEntry target + ) => icons.GetIcon(target); + + /// + /// Checks whether this drawer supports the selected Inspector target. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// when the documented condition is satisfied; otherwise, . + /// + protected override bool CanInspect(AssetFileEntry target) + => !target.isDirectory && target.extension.Equals(".ishader", StringComparison.OrdinalIgnoreCase); + + /// + /// Binds a caller-visible label to the current inspection target. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated (string name, actionstring? setter) that represents the completed operation. + /// + protected override (string name, Action? setter) BindName( + InspectionDrawContext context, + AssetFileEntry target + ) => (target.nameWithoutExtension, null); + + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void Draw( + InspectionDrawContext context, + AssetFileEntry target + ) { + if (context.interactions.TryGetModule(out ShaderEditorDocuments? documents)) + { + if (documents!.TryOpen(target, out ShaderEditorDocuments.Draft draft)) + { + new ShaderEditorCanvas(documents, draft).DrawInspector(context, []); + } + else + { + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Waiting for Shader asset import…"); + } + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CollapseShaderSubgraph.cs similarity index 51% rename from src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs rename to src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CollapseShaderSubgraph.cs index 0318cb44c..3ddda7479 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasOrganizationActions.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CollapseShaderSubgraph.cs @@ -5,200 +5,14 @@ using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Graphs; -using Inno.Editor.Assets; using Inno.Editor.Assets.ImGui; using Inno.Editor.Graph; using Inno.Editor.Interactions; -using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; -internal struct ShaderCanvasGroup -{ - /// - /// Gets the stable identity used to reference this value across subsystem boundaries. - /// - public string id { get; set; } - - /// - /// Gets the title text used by the current instance. - /// - public string title { get; set; } - - /// - /// Gets graph nodes affected by this organization action. - /// - public string[] nodes { get; set; } -} - -[EditorAction("shader/focus", ShaderEditorCanvas.C_AREA)] -internal sealed class FocusShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => documents.Open(context.target).frameRequested = true; -} - -[EditorAction("shader/reroute", ShaderEditorCanvas.C_AREA)] -internal sealed class InsertShaderReroute(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - => base.Query(context).isEnabled - && documents.Open(context.target).selectedEdge is not null ? EditorActionState.enabled : EditorActionState.disabled; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - GraphDocumentController controller = documents.Controller(draft); - GraphDocument graph = controller.document.Clone(); - GraphEdgeRecord edge = graph.edges.Single(value => value.id == draft.selectedEdge); - ShaderNodePort source = draft.ports[edge.output.nodeID].Single(value => value.id == edge.output.portID.value); - var node = new GraphNodeRecord(new GraphNodeID(Guid.NewGuid().ToString("N")), "inno.shader.reroute") - { - position = draft.menuPosition - }; - node.SetValue( - "valueType", - ShaderGraphDocument.Encode(ShaderGraphType.Capture(source.type), documents.serialization, documents.context) - ); - string stage = ShaderGraphDocument.Read( - graph.FindNode(edge.output.nodeID)!, - "stage", - string.Empty, - documents.serialization, - documents.context - ); - node.SetValue("stage", ShaderGraphDocument.Encode(stage, documents.serialization, documents.context)); - graph.AddNode(node); - graph.RemoveEdge(edge.id); - graph.AddEdge( - new GraphEdgeRecord( - new GraphEdgeID(Guid.NewGuid().ToString("N")), - edge.output, - new GraphEndpoint(node.id, new GraphPortID("input")) - ) - ); - graph.AddEdge( - new GraphEdgeRecord( - new GraphEdgeID(Guid.NewGuid().ToString("N")), - new GraphEndpoint(node.id, new GraphPortID("value")), - edge.input - ) - ); - controller.ReplaceDocument(graph, "Insert Shader Reroute"); - draft.selectedEdge = null; - draft.canvas.SelectNodes([node.id]); - documents.Changed(draft); - } -} - -[EditorAction("shader/group", ShaderEditorCanvas.C_AREA)] -internal sealed class GroupShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - internal const string C_GROUPS = "inno.editor.shader.groups"; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - GraphDocument graph = documents.Controller(draft).document.Clone(); - ShaderCanvasGroup[] groups = Read(documents, graph); - groups = - [ - ..groups, - new ShaderCanvasGroup() - { - id = Guid.NewGuid().ToString("N"), - title = "Group " + (groups.Length + 1), - nodes = draft.canvas.selectedNodes.Select(static id => id.value).ToArray() - } - ]; - graph.SetMetadata(C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); - documents.Controller(draft).ReplaceDocument(graph, "Group Shader Nodes"); - draft.selectedGroupID = groups[^1].id; - documents.Changed(draft); - } - - internal static ShaderCanvasGroup[] Read( - ShaderEditorDocuments documents, - GraphDocument graph - ) => graph.metadata.TryGetValue( - C_GROUPS, - out GraphSerializedValue? value - ) ? ShaderGraphDocument.Decode(value, documents.serialization, documents.context) : []; -} - -[EditorAction("shader/ungroup", ShaderEditorCanvas.C_AREA)] -internal sealed class UngroupShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - GraphDocument graph = documents.Controller(draft).document.Clone(); - ShaderCanvasGroup[] groups = GroupShaderNodes - .Read(documents, graph) - .Where( - group => ( - draft.selectedGroupID.Length != 0 - ? group.id != draft.selectedGroupID - : !group.nodes.All(id => draft.canvas.selectedNodes.Contains(new GraphNodeID(id))) - ) - ) - .ToArray(); - graph.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); - documents.Controller(draft).ReplaceDocument(graph, "Ungroup Shader Nodes"); - draft.selectedGroupID = string.Empty; - documents.Changed(draft); - } -} - [EditorAction("shader/collapse-subgraph", ShaderEditorCanvas.C_AREA)] internal sealed class CollapseShaderSubgraph( ShaderEditorDocuments documents, @@ -540,175 +354,3 @@ ShaderEditorDocuments documents return path; } } - -[EditorAction("shader/reveal-source", ShaderEditorCanvas.C_AREA)] -internal sealed class RevealShaderFunction( - ShaderEditorDocuments documents, - AssetBrowserModule browser -) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - { - if (!base.Query(context).isEnabled) - { - return EditorActionState.disabled; - } - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - string? definition = draft.canvas.selectedNodes.Count == 1 - ? documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())?.definitionID - : null; - return definition is "inno.shader.source" or ShaderGraphNodes.C_CALL_DEFINITION_ID - ? EditorActionState.enabled - : EditorActionState.disabled; - } - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - GraphNodeRecord node = documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())!; - Reveal(documents, browser, ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, documents.serialization, documents.context)); - } - - internal static void Reveal( - ShaderEditorDocuments documents, - AssetBrowserModule browser, - Guid sourceID - ) { - if (!documents.assets.TryGetInfo(sourceID, out AssetInfo? info) || info is null) - { - throw new IOException("Referenced Shader authoring asset is missing. Select a replacement in the node."); - } - if (!documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry)) - { - throw new FileNotFoundException( - "Referenced Shader authoring asset is missing from the Asset Browser.", - info.assetPath.ToString() - ); - } - string parent = Path.GetDirectoryName(info.assetPath.localPath)?.Replace('\\', '/') ?? string.Empty; - browser.browser.SetCurrentDirectory(new AssetPath(info.assetPath.source, parent).ToString()); - documents.interactions.SetSelection(entry); - documents.interactions.OpenPanel("asset.file-browser"); - } -} - -[EditorAction("shader/reveal-shader", ShaderEditorCanvas.C_AREA)] -internal sealed class RevealShaderAsset( - ShaderEditorDocuments documents, - AssetBrowserModule browser -) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - string parent = Path.GetDirectoryName(draft.path.localPath)?.Replace('\\', '/') ?? string.Empty; - browser.browser.SetCurrentDirectory(new AssetPath(draft.path.source, parent).ToString()); - if (!documents.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry entry)) - { - throw new FileNotFoundException("Shader source is missing from the Asset Browser.", draft.path.ToString()); - } - documents.interactions.SetSelection(entry); - documents.interactions.OpenPanel("asset.file-browser"); - } -} - -[EditorAction("shader/check", ShaderEditorCanvas.C_AREA)] -internal sealed class ShowShaderDiagnostics(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => documents.ShowCheck(documents.Open(context.target)); -} - -[EditorAction("shader/copy-to-project", ShaderEditorCanvas.C_AREA)] -internal sealed class CopyShaderToProject( - ShaderEditorDocuments documents, - AssetBrowserModule browser -) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - AssetSourceMount mount = documents.assets.sourceMounts.Single(value => value.id == AssetSourceID.project); - string name = Path.GetFileNameWithoutExtension(draft.path.localPath) + " Copy"; - AssetPath destination = AssetPath.Project(name + ".ishader"); - for (int index = 2; File.Exists(mount.Resolve(destination.localPath)) - || File.Exists(mount.Resolve(destination.localPath) + ".imeta"); index++ - ) { - destination = AssetPath.Project(name + " " + index + ".ishader"); - } - AssetFileEntry entry = browser.edits.CreateSource( - destination, - GraphDocumentCodec.Encode(documents.Controller(draft).document, documents.serialization) - ); - _ = context.interactions.For("panel/asset.file-browser", entry).Select(); - _ = context.interactions.For("panel/asset.file-browser", entry).Execute("file-browser/rename"); - context.interactions.OpenPanel("rendering.shader-editor"); - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderNodes.cs new file mode 100644 index 000000000..08192e296 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderNodes.cs @@ -0,0 +1,27 @@ +using Inno.Assets.Pipeline; +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/copy", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.C, primary: true)] +internal sealed class CopyShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + documents.clipboard = documents.Copy(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderToProject.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderToProject.cs new file mode 100644 index 000000000..a90ebaba8 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CopyShaderToProject.cs @@ -0,0 +1,52 @@ +using System.IO; +using System.Linq; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Assets.ImGui; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/copy-to-project", ShaderEditorCanvas.C_AREA)] +internal sealed class CopyShaderToProject( + ShaderEditorDocuments documents, + AssetBrowserModule browser +) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + AssetSourceMount mount = documents.assets.sourceMounts.Single(value => value.id == AssetSourceID.project); + string name = Path.GetFileNameWithoutExtension(draft.path.localPath) + " Copy"; + AssetPath destination = AssetPath.Project(name + ".ishader"); + for (int index = 2; File.Exists(mount.Resolve(destination.localPath)) + || File.Exists(mount.Resolve(destination.localPath) + ".imeta"); index++ + ) { + destination = AssetPath.Project(name + " " + index + ".ishader"); + } + AssetFileEntry entry = browser.edits.CreateSource( + destination, + GraphDocumentCodec.Encode(documents.Controller(draft).document, documents.serialization) + ); + _ = context.interactions.For("panel/asset.file-browser", entry).Select(); + _ = context.interactions.For("panel/asset.file-browser", entry).Execute("file-browser/rename"); + context.interactions.OpenPanel("rendering.shader-editor"); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs index 088f8a537..113c555ad 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderAsset.cs @@ -5,9 +5,7 @@ using Inno.Assets.Pipeline; using Inno.Core.Graphs; using Inno.Editor.Assets; -using Inno.Editor.Assets.ImGui; using Inno.Editor.Interactions; -using Inno.Rendering.Shaders; namespace Inno.Editor.Panel.ShaderEditor; @@ -67,32 +65,3 @@ protected override void Execute(EditorActionContext context) context.interactions.OpenPanel("rendering.shader-editor"); } } - -[EditorMenuSource("panel/asset.file-browser")] -internal sealed class ShaderTemplateMenu(ShaderEditorDocuments documents) : EditorMenuSource -{ - /// - /// Builds a validated result from the current immutable input snapshot. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. - /// - public override void Build( - EditorMenuContext context, - EditorMenuBuilder builder - ) { - if (documents.templates is null) - { - return; - } - builder.AddGroup("Create/Rendering", order: 200, separatorBefore: true); - builder.AddGroup("Create/Rendering/Shaders", order: 0); - foreach (ShaderGraphTemplateInfo template in documents.templates.templates) - { - builder.Add("Create/Rendering/Shaders/" + template.displayName, "shader/create-asset", argument: template.id, order: 0); - } - } -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderNode.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderNode.cs new file mode 100644 index 000000000..97cac6243 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderNode.cs @@ -0,0 +1,30 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/create-node", ShaderEditorCanvas.C_AREA)] +internal sealed class CreateShaderNode(ShaderEditorDocuments documents) : EditorAction +{ + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) + && documents.CanCreate(draft, context.argument) ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + => documents.Create(documents.Open(context.target), context.argument); +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderOutput.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderOutput.cs new file mode 100644 index 000000000..c693164ad --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CreateShaderOutput.cs @@ -0,0 +1,159 @@ +using System; +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; +using Inno.Rendering; +using Inno.Rendering.Assets; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/create-output", ShaderEditorCanvas.C_AREA)] +internal sealed class CreateShaderOutput(ShaderEditorDocuments documents) : EditorAction +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + { + if (!documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) + || draft.readOnly + || !Enum.TryParse(context.argument, out ShaderStage stage) + ) { + return EditorActionState.disabled; + } + GraphDocument graph = documents.Controller(draft).document; + if (ShaderGraphDocument.ReadTarget(graph, documents.serialization, documents.context).Length != 0) + { + return EditorActionState.disabled; + } + bool exists = graph.nodes + .Where(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + .Any( + node => ( + ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphStageSettings(), + documents.serialization, + documents.context + ).stage == stage + ) + ); + return exists ? EditorActionState.disabled : EditorActionState.enabled; + } + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + GraphDocument graph = controller.document.Clone(); + ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( + graph, + documents.serialization, + documents.context + ); + ShaderStage stage = Enum.Parse(context.argument); + ShaderProgramKind kind = stage == ShaderStage.Compute + ? ShaderProgramKind.Compute + : ShaderProgramKind.Raster; + ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(graph, documents.serialization, documents.context); + ShaderGraphPassProgram? incomplete = kind == ShaderProgramKind.Raster + ? programs.FirstOrDefault( + program => ( + definition.passes.Any(pass => pass.name == program.pass && pass.programKind == kind) + && !program.stages + .Select(id => graph.FindNode(new GraphNodeID(id))) + .OfType() + .Any( + node => ( + ShaderGraphDocument.Read( + node, + "settings", + new ShaderGraphStageSettings(), + documents.serialization, + documents.context + ).stage == stage + ) + ) + ) + ) + : null; + string name; + string[] stages; + if (incomplete is ShaderGraphPassProgram existing && existing.pass is not null) + { + name = existing.pass; + stages = existing.stages; + } + else + { + string prefix = kind.ToString(); + name = prefix; + for (int suffix = 2; definition.passes.Any(pass => pass.name == name); suffix++) + { + name = prefix + " " + suffix; + } + definition.passes = [..definition.passes, new ShaderPassDefinition(name, kind)]; + graph.SetMetadata( + ShaderGraphDocument.C_DEFINITION_KEY, + ShaderGraphDocument.Encode( + documents.serialization.Serialize(definition, documents.context), + documents.serialization, + documents.context + ) + ); + stages = []; + } + + var id = new GraphNodeID(Guid.NewGuid().ToString("N")); + var node = new GraphNodeRecord(id, ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) + { + position = draft.menuPosition + }; + node.SetValue( + "settings", + ShaderGraphDocument.Encode( + new ShaderGraphStageSettings + { + stage = stage, + outputs = stage == ShaderStage.Compute + ? [] + : [new ShaderGraphOutput() + { + id = stage == ShaderStage.Vertex ? "position" : "color", + kind = stage == ShaderStage.Vertex ? ShaderIrOutputKind.ClipPosition : ShaderIrOutputKind.Color + }] + }, + documents.serialization, + documents.context + ) + ); + graph.AddNode(node); + graph = ShaderGraphPrograms.Bind( + graph, + name, + stages.Select(static value => new GraphNodeID(value)).Append(id), + documents.serialization, + documents.context + ); + controller.ReplaceDocument(graph, "Create " + stage + " Output"); + draft.canvas.SelectNodes([id]); + draft.activeStage = id; + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CutShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CutShaderNodes.cs new file mode 100644 index 000000000..c5b4f43e5 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/CutShaderNodes.cs @@ -0,0 +1,25 @@ +using Inno.Assets.Pipeline; +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/cut", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.X, primary: true)] +internal sealed class CutShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + documents.clipboard = documents.Copy(draft); + documents.RemoveNodes(draft); + draft.canvas.ClearSelection(); + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DeleteShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DeleteShaderNodes.cs new file mode 100644 index 000000000..bc4bd2305 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DeleteShaderNodes.cs @@ -0,0 +1,40 @@ +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Core.Input; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/delete", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.Delete)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.Backspace)] +internal sealed class DeleteShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + using EditorHistoryTransaction transaction = context.history.BeginTransaction("Delete Shader Selection"); + if (draft.selectedEdge is GraphEdgeID edge) + { + controller.Disconnect(edge); + } + documents.RemoveNodes(draft); + transaction.Commit(); + draft.selectedEdge = null; + draft.canvas.ClearSelection(); + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DisconnectShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DisconnectShaderNodes.cs new file mode 100644 index 000000000..46d9f7c15 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DisconnectShaderNodes.cs @@ -0,0 +1,35 @@ +using System; +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/disconnect", ShaderEditorCanvas.C_AREA)] +internal sealed class DisconnectShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + using EditorHistoryTransaction transaction = context.history.BeginTransaction("Disconnect Nodes"); + foreach (GraphEdgeRecord edge in controller.document.edges + .Where( + edge => draft.canvas.selectedNodes.Contains(edge.input.nodeID) || draft.canvas.selectedNodes.Contains(edge.output.nodeID) + ) + .ToArray() + ) { + controller.Disconnect(edge.id); + } + transaction.Commit(); + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DuplicateShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DuplicateShaderNodes.cs new file mode 100644 index 000000000..b4adcb6f6 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/DuplicateShaderNodes.cs @@ -0,0 +1,46 @@ +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Input; +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/duplicate", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.D, primary: true)] +internal sealed class DuplicateShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + { + if (!base.Query(context).isEnabled || !documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft)) + { + return EditorActionState.disabled; + } + return draft.canvas.selectedNodes.Any( + id => documents.Controller(draft).document.FindNode(id)?.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID + ) + ? EditorActionState.disabled + : EditorActionState.enabled; + } + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + documents.Paste(draft, documents.Copy(draft)); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FocusShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FocusShaderNodes.cs new file mode 100644 index 000000000..2768a8fbf --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FocusShaderNodes.cs @@ -0,0 +1,26 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/focus", ShaderEditorCanvas.C_AREA)] +internal sealed class FocusShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => documents.Open(context.target).frameRequested = true; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FormatShaderGraph.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FormatShaderGraph.cs new file mode 100644 index 000000000..7ddeb30d8 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/FormatShaderGraph.cs @@ -0,0 +1,32 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/format", ShaderEditorCanvas.C_AREA)] +internal sealed class FormatShaderGraph(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + controller.ReplaceDocument( + ShaderGraphAutoLayout.Apply(controller.document, documents.serialization, documents.context, documents.Describe), + "Format Shader Graph" + ); + draft.frameRequested = true; + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/GroupShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/GroupShaderNodes.cs new file mode 100644 index 000000000..ef0586205 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/GroupShaderNodes.cs @@ -0,0 +1,49 @@ +using System; +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/group", ShaderEditorCanvas.C_AREA)] +internal sealed class GroupShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + internal const string C_GROUPS = "inno.editor.shader.groups"; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocument graph = documents.Controller(draft).document.Clone(); + ShaderCanvasGroup[] groups = Read(documents, graph); + groups = + [ + ..groups, + new ShaderCanvasGroup() + { + id = Guid.NewGuid().ToString("N"), + title = "Group " + (groups.Length + 1), + nodes = draft.canvas.selectedNodes.Select(static id => id.value).ToArray() + } + ]; + graph.SetMetadata(C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); + documents.Controller(draft).ReplaceDocument(graph, "Group Shader Nodes"); + draft.selectedGroupID = groups[^1].id; + documents.Changed(draft); + } + + internal static ShaderCanvasGroup[] Read( + ShaderEditorDocuments documents, + GraphDocument graph + ) => graph.metadata.TryGetValue( + C_GROUPS, + out GraphSerializedValue? value + ) ? ShaderGraphDocument.Decode(value, documents.serialization, documents.context) : []; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/InsertShaderReroute.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/InsertShaderReroute.cs new file mode 100644 index 000000000..88e9608b0 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/InsertShaderReroute.cs @@ -0,0 +1,82 @@ +using System; +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Graph; +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/reroute", ShaderEditorCanvas.C_AREA)] +internal sealed class InsertShaderReroute(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => base.Query(context).isEnabled + && documents.Open(context.target).selectedEdge is not null ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocumentController controller = documents.Controller(draft); + GraphDocument graph = controller.document.Clone(); + GraphEdgeRecord edge = graph.edges.Single(value => value.id == draft.selectedEdge); + ShaderNodePort source = draft.ports[edge.output.nodeID].Single(value => value.id == edge.output.portID.value); + var node = new GraphNodeRecord(new GraphNodeID(Guid.NewGuid().ToString("N")), "inno.shader.reroute") + { + position = draft.menuPosition + }; + node.SetValue( + "valueType", + ShaderGraphDocument.Encode(ShaderGraphType.Capture(source.type), documents.serialization, documents.context) + ); + string stage = ShaderGraphDocument.Read( + graph.FindNode(edge.output.nodeID)!, + "stage", + string.Empty, + documents.serialization, + documents.context + ); + node.SetValue("stage", ShaderGraphDocument.Encode(stage, documents.serialization, documents.context)); + graph.AddNode(node); + graph.RemoveEdge(edge.id); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(Guid.NewGuid().ToString("N")), + edge.output, + new GraphEndpoint(node.id, new GraphPortID("input")) + ) + ); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID(Guid.NewGuid().ToString("N")), + new GraphEndpoint(node.id, new GraphPortID("value")), + edge.input + ) + ); + controller.ReplaceDocument(graph, "Insert Shader Reroute"); + draft.selectedEdge = null; + draft.canvas.SelectNodes([node.id]); + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/PasteShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/PasteShaderNodes.cs new file mode 100644 index 000000000..285fe0257 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/PasteShaderNodes.cs @@ -0,0 +1,45 @@ +using Inno.Assets.Pipeline; +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/paste", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.V, primary: true)] +internal sealed class PasteShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => base.Query(context).isEnabled + && documents.clipboard is not null + && documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) + && documents.CanPaste(draft, documents.clipboard) ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + if (documents.clipboard is not null) + { + documents.Paste(draft, documents.clipboard); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ReloadShaderSource.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ReloadShaderSource.cs new file mode 100644 index 000000000..15b8d595d --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ReloadShaderSource.cs @@ -0,0 +1,27 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/reload", ShaderEditorCanvas.C_AREA)] +internal sealed class ReloadShaderSource(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + => context.interactions.documents.Revert(documents.Open(context.target).documentID); +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderAsset.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderAsset.cs new file mode 100644 index 000000000..e626a5998 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderAsset.cs @@ -0,0 +1,43 @@ +using System.IO; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Editor.Assets.ImGui; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/reveal-shader", ShaderEditorCanvas.C_AREA)] +internal sealed class RevealShaderAsset( + ShaderEditorDocuments documents, + AssetBrowserModule browser +) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + string parent = Path.GetDirectoryName(draft.path.localPath)?.Replace('\\', '/') ?? string.Empty; + browser.browser.SetCurrentDirectory(new AssetPath(draft.path.source, parent).ToString()); + if (!documents.assets.TryGetFileSystemEntry(draft.path, out AssetFileEntry entry)) + { + throw new FileNotFoundException("Shader source is missing from the Asset Browser.", draft.path.ToString()); + } + documents.interactions.SetSelection(entry); + documents.interactions.OpenPanel("asset.file-browser"); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderFunction.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderFunction.cs new file mode 100644 index 000000000..58e92a0e8 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/RevealShaderFunction.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using System.Linq; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Assets.ImGui; +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/reveal-source", ShaderEditorCanvas.C_AREA)] +internal sealed class RevealShaderFunction( + ShaderEditorDocuments documents, + AssetBrowserModule browser +) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + { + if (!base.Query(context).isEnabled) + { + return EditorActionState.disabled; + } + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + string? definition = draft.canvas.selectedNodes.Count == 1 + ? documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())?.definitionID + : null; + return definition is "inno.shader.source" or ShaderGraphNodes.C_CALL_DEFINITION_ID + ? EditorActionState.enabled + : EditorActionState.disabled; + } + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphNodeRecord node = documents.Controller(draft).document.FindNode(draft.canvas.selectedNodes.First())!; + Reveal(documents, browser, ShaderGraphDocument.Read(node, "sourceId", Guid.Empty, documents.serialization, documents.context)); + } + + internal static void Reveal( + ShaderEditorDocuments documents, + AssetBrowserModule browser, + Guid sourceID + ) { + if (!documents.assets.TryGetInfo(sourceID, out AssetInfo? info) || info is null) + { + throw new IOException("Referenced Shader authoring asset is missing. Select a replacement in the node."); + } + if (!documents.assets.TryGetFileSystemEntry(info.assetPath, out AssetFileEntry entry)) + { + throw new FileNotFoundException( + "Referenced Shader authoring asset is missing from the Asset Browser.", + info.assetPath.ToString() + ); + } + string parent = Path.GetDirectoryName(info.assetPath.localPath)?.Replace('\\', '/') ?? string.Empty; + browser.browser.SetCurrentDirectory(new AssetPath(info.assetPath.source, parent).ToString()); + documents.interactions.SetSelection(entry); + documents.interactions.OpenPanel("asset.file-browser"); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/SaveShader.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/SaveShader.cs new file mode 100644 index 000000000..cf19807fd --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/SaveShader.cs @@ -0,0 +1,24 @@ +using Inno.Assets.Pipeline; +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/save", ShaderEditorCanvas.C_AREA)] +[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.S, primary: true)] +internal sealed class SaveShader(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + => context.interactions.documents.Save(documents.Open(context.target).documentID); +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs deleted file mode 100644 index 856cfd77b..000000000 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasActions.cs +++ /dev/null @@ -1,677 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Core.Execution; -using Inno.Core.Graphs; -using Inno.Core.Input; -using Inno.Editor.Core; -using Inno.Editor.Graph; -using Inno.Editor.Interactions; -using Inno.Editor.Shaders; -using Inno.Editor.Shaders.ImGui; -using Inno.Rendering; -using Inno.Rendering.Assets; -using Inno.Rendering.Assets.Authoring; -using Inno.Rendering.Shaders; - -using EditorUI = Inno.Editor.ImGui.EditorUISession; - -namespace Inno.Editor.Panel.ShaderEditor; - -[EditorMenuSource(ShaderEditorCanvas.C_AREA)] -internal sealed class ShaderCanvasMenu(ShaderEditorDocuments documents) : EditorMenuSource -{ - /// - /// Builds a validated result from the current immutable input snapshot. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. - /// - public override void Build( - EditorMenuContext context, - EditorMenuBuilder builder - ) { - if (context.target is not AssetFileEntry entry || !documents.TryGet(entry, out ShaderEditorDocuments.Draft draft)) - { - return; - } - builder.AddGroup("Create/Functions", order: 500, separatorBefore: true); - builder.AddGroup("Create/Graph Nodes", order: 550, separatorBefore: true); - builder.AddGroup("Create/Domain Outputs", order: 800, separatorBefore: true); - bool explicitStages = ShaderGraphDocument.ReadTarget( - documents.Controller(draft).document, - documents.serialization, - documents.context - ).Length == 0; - if (draft.createFromPort is null && explicitStages) - { - builder.Add("Create/Outputs/Vertex Output", "shader/create-output", order: 0, argument: "Vertex"); - builder.Add("Create/Outputs/Fragment Output", "shader/create-output", order: 10, argument: "Fragment"); - builder.Add("Create/Outputs/Compute Output", "shader/create-output", order: 20, argument: "Compute"); - } - - foreach (string definition in documents.nodes.definitionIDs) - { - if (definition is not ("inno.shader.source" or ShaderGraphNodes.C_CALL_DEFINITION_ID) - && documents.CanCreate(draft, new ShaderNodeCreation(definition)) - ) { - string category = Category(definition); - int order = CategoryOrder(category); - if (documents.drawers?.TryGetPresentation(definition, out ShaderNodePresentation presentation) == true - && presentation.createPath.Length != 0 - ) { - category = presentation.createPath; - order = presentation.createOrder; - builder.AddGroup("Create/" + category, order, presentation.separatorBefore); - } - - builder.Add( - "Create/" - + category - + "/" - + (documents.drawers?.GetDisplayName(definition) - ?? EditorDisplayNames.Nicify( - definition.Replace("inno.shader.", string.Empty, StringComparison.Ordinal).Replace('-', ' ') - )), - "shader/create-node", - order, - argument: new ShaderNodeCreation(definition) - ); - } - } - - List<(AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)> functionLibraries = []; - foreach (AssetFileEntry source in documents.assets.GetFileSystemEntries(includeDirectories: false)) - { - if (source.extension == ".ishadersource" - && documents.assets.TryGetInfo(source.assetPath, out AssetInfo? info) - && info is not null - && documents.assets.TryLoad(info.persistentID, out ShaderFunctionAsset? library) - && library is not null - && !library.isMissing - ) { - functionLibraries.Add((source, info, library)); - } - } - foreach ((string name, int order) catalog in functionLibraries - .Select(static value => (path: NormalizeCatalog(value.library.catalogPath), value.library.catalogOrder)) - .Where(static value => value.path.Length != 0) - .GroupBy(static value => value.path.Split('/')[0], StringComparer.Ordinal) - .Select(static group => (name: group.Key, order: group.Min(static value => value.catalogOrder))) - .OrderBy(static value => value.order) - .ThenBy(static value => value.name, StringComparer.Ordinal) - ) { - builder.AddGroup("Create/Functions/" + catalog.name, order: 500 + catalog.order, separatorBefore: true); - } - foreach ((AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)in functionLibraries - .OrderBy(static value => value.library.catalogOrder) - .ThenBy(static value => value.source.nameWithoutExtension, StringComparer.Ordinal) - ) { - foreach (string function in library.exports) - { - if (documents.CanCreate(draft, new ShaderNodeCreation("inno.shader.source", info.persistentID, function))) - { - string catalog = NormalizeCatalog(library.catalogPath); - string prefix = "Create/Functions/" + (catalog.Length == 0 ? "General" : catalog); - builder.Add( - prefix + "/" + source.nameWithoutExtension + "/" + function, - "shader/create-node", - order: 500 + library.catalogOrder, - argument: new ShaderNodeCreation("inno.shader.source", info.persistentID, function) - ); - } - } - } - - foreach (AssetFileEntry source in documents.assets - .GetFileSystemEntries(includeDirectories: false) - .Where(static entry => entry.extension == ".ishader") - .OrderBy(static entry => entry.assetPath.ToString(), StringComparer.Ordinal) - ) { - if (!documents.assets.TryGetInfo(source.assetPath, out AssetInfo? info) - || info is null - || info.persistentID == draft.id - || info.status != AssetImportStatus.Imported - ) { - continue; - } - ShaderGraphNodeInterface nodeInterface; - try - { - nodeInterface = documents.LoadGraphNodeInterface(info.persistentID); - } - catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) - && RetirementPendingException.Find(failure) is null) - { - continue; - } - - var creation = new ShaderNodeCreation(ShaderGraphNodes.C_CALL_DEFINITION_ID, info.persistentID); - if (!documents.CanCreate(draft, creation)) - { - continue; - } - string catalog = NormalizeCatalog(nodeInterface.createPath); - string root = nodeInterface.kind == ShaderGraphNodeKind.DomainOutput ? "Domain Outputs" : "Graph Nodes"; - string group = "Create/" + root + (catalog.Length == 0 ? string.Empty : "/" + catalog); - builder.AddGroup( - group, - order: nodeInterface.createOrder, - separatorBefore: nodeInterface.kind == ShaderGraphNodeKind.DomainOutput - ); - builder.Add( - group + "/" + nodeInterface.displayName, - "shader/create-node", - order: nodeInterface.createOrder, - argument: creation - ); - } - - builder.Add("View/Focus Selection", "shader/focus", order: 900); - builder.Add("Edit/Copy", "shader/copy", order: 1000); - builder.Add("Edit/Cut", "shader/cut", order: 110); - builder.Add("Edit/Paste", "shader/paste", order: 120); - builder.Add("Edit/Duplicate", "shader/duplicate", order: 130); - builder.Add("Edit/Delete", "shader/delete", order: 140, separatorBefore: true); - builder.Add("Connections/Disconnect", "shader/disconnect", order: 1500); - builder.Add("Connections/Insert Reroute", "shader/reroute", order: 160); - builder.Add("Organize/Group Selection", "shader/group", order: 1700); - builder.Add("Organize/Ungroup Selection", "shader/ungroup", order: 180); - builder.Add("Organize/Collapse to Subgraph", "shader/collapse-subgraph", order: 190, separatorBefore: true); - builder.Add("Assets/Show Shader in File Browser", "shader/reveal-shader", order: 1900); - builder.Add("Assets/Show Source in File Browser", "shader/reveal-source", order: 1910); - builder.Add("Assets/Copy Shader To Project", "shader/copy-to-project", order: 1920, separatorBefore: true); - static string Category(string definition) - => definition switch - { - "inno.shader.constant" or "inno.shader.stage-input" => "Inputs", - ShaderGraphNodes.C_INPUT_DEFINITION_ID or ShaderGraphNodes.C_OUTPUT_DEFINITION_ID => "Interface", - "inno.shader.sample" => "Textures", - "inno.shader.binary" or "inno.shader.construct" or "inno.shader.extract" or "inno.shader.select" => "Math", - "inno.shader.storage-load" or "inno.shader.storage-store" or "inno.shader.storage-atomic-add" => "Resources", - "inno.shader.discard" => "Flow", - "inno.shader.reroute" => "Utility", - _ when definition.Contains("surface-output", StringComparison.Ordinal) => "Domain Outputs", - _ => "Domain" - }; - static int CategoryOrder(string category) - => category switch - { - "Outputs" => 0, - "Interface" => 50, - "Inputs" => 100, - "Textures" => 200, - "Math" => 300, - "Resources" => 400, - "Flow" => 600, - "Utility" => 700, - "Domain Outputs" => 800, - _ => 850 - }; - static string NormalizeCatalog(string value) - => string.Join('/', value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); - } -} - -[EditorAction("shader/create-output", ShaderEditorCanvas.C_AREA)] -internal sealed class CreateShaderOutput(ShaderEditorDocuments documents) : EditorAction -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - { - if (!documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) - || draft.readOnly - || !Enum.TryParse(context.argument, out ShaderStage stage) - ) { - return EditorActionState.disabled; - } - GraphDocument graph = documents.Controller(draft).document; - if (ShaderGraphDocument.ReadTarget(graph, documents.serialization, documents.context).Length != 0) - { - return EditorActionState.disabled; - } - bool exists = graph.nodes - .Where(static node => node.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) - .Any( - node => ( - ShaderGraphDocument.Read( - node, - "settings", - new ShaderGraphStageSettings(), - documents.serialization, - documents.context - ).stage == stage - ) - ); - return exists ? EditorActionState.disabled : EditorActionState.enabled; - } - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - GraphDocumentController controller = documents.Controller(draft); - GraphDocument graph = controller.document.Clone(); - ShaderDefinition definition = ShaderGraphDocument.ReadDefinition( - graph, - documents.serialization, - documents.context - ); - ShaderStage stage = Enum.Parse(context.argument); - ShaderProgramKind kind = stage == ShaderStage.Compute - ? ShaderProgramKind.Compute - : ShaderProgramKind.Raster; - ShaderGraphPassProgram[] programs = ShaderGraphPrograms.Read(graph, documents.serialization, documents.context); - ShaderGraphPassProgram? incomplete = kind == ShaderProgramKind.Raster - ? programs.FirstOrDefault( - program => ( - definition.passes.Any(pass => pass.name == program.pass && pass.programKind == kind) - && !program.stages - .Select(id => graph.FindNode(new GraphNodeID(id))) - .OfType() - .Any( - node => ( - ShaderGraphDocument.Read( - node, - "settings", - new ShaderGraphStageSettings(), - documents.serialization, - documents.context - ).stage == stage - ) - ) - ) - ) - : null; - string name; - string[] stages; - if (incomplete is ShaderGraphPassProgram existing && existing.pass is not null) - { - name = existing.pass; - stages = existing.stages; - } - else - { - string prefix = kind.ToString(); - name = prefix; - for (int suffix = 2; definition.passes.Any(pass => pass.name == name); suffix++) - { - name = prefix + " " + suffix; - } - definition.passes = [..definition.passes, new ShaderPassDefinition(name, kind)]; - graph.SetMetadata( - ShaderGraphDocument.C_DEFINITION_KEY, - ShaderGraphDocument.Encode( - documents.serialization.Serialize(definition, documents.context), - documents.serialization, - documents.context - ) - ); - stages = []; - } - - var id = new GraphNodeID(Guid.NewGuid().ToString("N")); - var node = new GraphNodeRecord(id, ShaderGraphDocument.C_OUTPUT_DEFINITION_ID) - { - position = draft.menuPosition - }; - node.SetValue( - "settings", - ShaderGraphDocument.Encode( - new ShaderGraphStageSettings - { - stage = stage, - outputs = stage == ShaderStage.Compute - ? [] - : [new ShaderGraphOutput() - { - id = stage == ShaderStage.Vertex ? "position" : "color", - kind = stage == ShaderStage.Vertex ? ShaderIrOutputKind.ClipPosition : ShaderIrOutputKind.Color - }] - }, - documents.serialization, - documents.context - ) - ); - graph.AddNode(node); - graph = ShaderGraphPrograms.Bind( - graph, - name, - stages.Select(static value => new GraphNodeID(value)).Append(id), - documents.serialization, - documents.context - ); - controller.ReplaceDocument(graph, "Create " + stage + " Output"); - draft.canvas.SelectNodes([id]); - draft.activeStage = id; - documents.Changed(draft); - } -} - -[EditorAction("shader/create-node", ShaderEditorCanvas.C_AREA)] -internal sealed class CreateShaderNode(ShaderEditorDocuments documents) : EditorAction -{ - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - => documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) - && documents.CanCreate(draft, context.argument) ? EditorActionState.enabled : EditorActionState.disabled; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - => documents.Create(documents.Open(context.target), context.argument); -} - -internal abstract class ShaderSelectionAction(ShaderEditorDocuments documents) : EditorAction -{ - /// - /// Gets documents presented by this Shader Editor action. - /// - protected ShaderEditorDocuments documents { get; } = documents; - - /// - /// Gets whether writes is active for the current instance. - /// - protected virtual bool writes => true; - - /// - /// Gets whether needs selection is active for the current instance. - /// - protected virtual bool needsSelection => true; - - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - => documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) - && (!writes - || !draft.readOnly) - && (!needsSelection - || draft.canvas.selectedNodes.Count != 0) ? EditorActionState.enabled : EditorActionState.disabled; -} - -[EditorAction("shader/copy", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.C, primary: true)] -internal sealed class CopyShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - documents.clipboard = documents.Copy(draft); - } -} - -[EditorAction("shader/delete", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.Delete)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.Backspace)] -internal sealed class DeleteShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - GraphDocumentController controller = documents.Controller(draft); - using EditorHistoryTransaction transaction = context.history.BeginTransaction("Delete Shader Selection"); - if (draft.selectedEdge is GraphEdgeID edge) - { - controller.Disconnect(edge); - } - documents.RemoveNodes(draft); - transaction.Commit(); - draft.selectedEdge = null; - draft.canvas.ClearSelection(); - documents.Changed(draft); - } -} - -[EditorAction("shader/cut", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.X, primary: true)] -internal sealed class CutShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - documents.clipboard = documents.Copy(draft); - documents.RemoveNodes(draft); - draft.canvas.ClearSelection(); - documents.Changed(draft); - } -} - -[EditorAction("shader/paste", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.V, primary: true)] -internal sealed class PasteShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - => base.Query(context).isEnabled - && documents.clipboard is not null - && documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) - && documents.CanPaste(draft, documents.clipboard) ? EditorActionState.enabled : EditorActionState.disabled; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - if (documents.clipboard is not null) - { - documents.Paste(draft, documents.clipboard); - } - } -} - -[EditorAction("shader/duplicate", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.D, primary: true)] -internal sealed class DuplicateShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - { - if (!base.Query(context).isEnabled || !documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft)) - { - return EditorActionState.disabled; - } - return draft.canvas.selectedNodes.Any( - id => documents.Controller(draft).document.FindNode(id)?.definitionID == ShaderGraphDocument.C_OUTPUT_DEFINITION_ID - ) - ? EditorActionState.disabled - : EditorActionState.enabled; - } - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - documents.Paste(draft, documents.Copy(draft)); - } -} - -[EditorAction("shader/disconnect", ShaderEditorCanvas.C_AREA)] -internal sealed class DisconnectShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - GraphDocumentController controller = documents.Controller(draft); - using EditorHistoryTransaction transaction = context.history.BeginTransaction("Disconnect Nodes"); - foreach (GraphEdgeRecord edge in controller.document.edges - .Where( - edge => draft.canvas.selectedNodes.Contains(edge.input.nodeID) || draft.canvas.selectedNodes.Contains(edge.output.nodeID) - ) - .ToArray() - ) { - controller.Disconnect(edge.id); - } - transaction.Commit(); - documents.Changed(draft); - } -} - -[EditorAction("shader/save", ShaderEditorCanvas.C_AREA)] -[EditorShortcut(ShaderEditorCanvas.C_AREA, KeyCode.S, primary: true)] -internal sealed class SaveShader(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - => context.interactions.documents.Save(documents.Open(context.target).documentID); -} - -[EditorAction("shader/format", ShaderEditorCanvas.C_AREA)] -internal sealed class FormatShaderGraph(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) - { - ShaderEditorDocuments.Draft draft = documents.Open(context.target); - GraphDocumentController controller = documents.Controller(draft); - controller.ReplaceDocument( - ShaderGraphAutoLayout.Apply(controller.document, documents.serialization, documents.context, documents.Describe), - "Format Shader Graph" - ); - draft.frameRequested = true; - documents.Changed(draft); - } -} - -[EditorAction("shader/reload", ShaderEditorCanvas.C_AREA)] -internal sealed class ReloadShaderSource(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) -{ - /// - /// Gets whether needs selection is active for the current instance. - /// - protected override bool needsSelection => false; - - /// - /// Gets whether writes is active for the current instance. - /// - protected override bool writes => false; - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - => context.interactions.documents.Revert(documents.Open(context.target).documentID); -} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasGroup.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasGroup.cs new file mode 100644 index 000000000..b9c92259b --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasGroup.cs @@ -0,0 +1,19 @@ +namespace Inno.Editor.Panel.ShaderEditor; + +internal struct ShaderCanvasGroup +{ + /// + /// Gets the stable identity used to reference this value across subsystem boundaries. + /// + public string id { get; set; } + + /// + /// Gets the title text used by the current instance. + /// + public string title { get; set; } + + /// + /// Gets graph nodes affected by this organization action. + /// + public string[] nodes { get; set; } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasMenu.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasMenu.cs new file mode 100644 index 000000000..90a850254 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderCanvasMenu.cs @@ -0,0 +1,211 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Core.Execution; +using Inno.Editor.Core; +using Inno.Editor.Interactions; +using Inno.Editor.Shaders.ImGui; +using Inno.Rendering.Assets.Authoring; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorMenuSource(ShaderEditorCanvas.C_AREA)] +internal sealed class ShaderCanvasMenu(ShaderEditorDocuments documents) : EditorMenuSource +{ + /// + /// Builds a validated result from the current immutable input snapshot. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. + /// + public override void Build( + EditorMenuContext context, + EditorMenuBuilder builder + ) { + if (context.target is not AssetFileEntry entry || !documents.TryGet(entry, out ShaderEditorDocuments.Draft draft)) + { + return; + } + builder.AddGroup("Create/Functions", order: 500, separatorBefore: true); + builder.AddGroup("Create/Graph Nodes", order: 550, separatorBefore: true); + builder.AddGroup("Create/Domain Outputs", order: 800, separatorBefore: true); + bool explicitStages = ShaderGraphDocument.ReadTarget( + documents.Controller(draft).document, + documents.serialization, + documents.context + ).Length == 0; + if (draft.createFromPort is null && explicitStages) + { + builder.Add("Create/Outputs/Vertex Output", "shader/create-output", order: 0, argument: "Vertex"); + builder.Add("Create/Outputs/Fragment Output", "shader/create-output", order: 10, argument: "Fragment"); + builder.Add("Create/Outputs/Compute Output", "shader/create-output", order: 20, argument: "Compute"); + } + + foreach (string definition in documents.nodes.definitionIDs) + { + if (definition is not ("inno.shader.source" or ShaderGraphNodes.C_CALL_DEFINITION_ID) + && documents.CanCreate(draft, new ShaderNodeCreation(definition)) + ) { + string category = Category(definition); + int order = CategoryOrder(category); + if (documents.drawers?.TryGetPresentation(definition, out ShaderNodePresentation presentation) == true + && presentation.createPath.Length != 0 + ) { + category = presentation.createPath; + order = presentation.createOrder; + builder.AddGroup("Create/" + category, order, presentation.separatorBefore); + } + + builder.Add( + "Create/" + + category + + "/" + + (documents.drawers?.GetDisplayName(definition) + ?? EditorDisplayNames.Nicify( + definition.Replace("inno.shader.", string.Empty, StringComparison.Ordinal).Replace('-', ' ') + )), + "shader/create-node", + order, + argument: new ShaderNodeCreation(definition) + ); + } + } + + List<(AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)> functionLibraries = []; + foreach (AssetFileEntry source in documents.assets.GetFileSystemEntries(includeDirectories: false)) + { + if (source.extension == ".ishadersource" + && documents.assets.TryGetInfo(source.assetPath, out AssetInfo? info) + && info is not null + && documents.assets.TryLoad(info.persistentID, out ShaderFunctionAsset? library) + && library is not null + && !library.isMissing + ) { + functionLibraries.Add((source, info, library)); + } + } + foreach ((string name, int order) catalog in functionLibraries + .Select(static value => (path: NormalizeCatalog(value.library.catalogPath), value.library.catalogOrder)) + .Where(static value => value.path.Length != 0) + .GroupBy(static value => value.path.Split('/')[0], StringComparer.Ordinal) + .Select(static group => (name: group.Key, order: group.Min(static value => value.catalogOrder))) + .OrderBy(static value => value.order) + .ThenBy(static value => value.name, StringComparer.Ordinal) + ) { + builder.AddGroup("Create/Functions/" + catalog.name, order: 500 + catalog.order, separatorBefore: true); + } + foreach ((AssetFileEntry source, AssetInfo info, ShaderFunctionAsset library)in functionLibraries + .OrderBy(static value => value.library.catalogOrder) + .ThenBy(static value => value.source.nameWithoutExtension, StringComparer.Ordinal) + ) { + foreach (string function in library.exports) + { + if (documents.CanCreate(draft, new ShaderNodeCreation("inno.shader.source", info.persistentID, function))) + { + string catalog = NormalizeCatalog(library.catalogPath); + string prefix = "Create/Functions/" + (catalog.Length == 0 ? "General" : catalog); + builder.Add( + prefix + "/" + source.nameWithoutExtension + "/" + function, + "shader/create-node", + order: 500 + library.catalogOrder, + argument: new ShaderNodeCreation("inno.shader.source", info.persistentID, function) + ); + } + } + } + + foreach (AssetFileEntry source in documents.assets + .GetFileSystemEntries(includeDirectories: false) + .Where(static entry => entry.extension == ".ishader") + .OrderBy(static entry => entry.assetPath.ToString(), StringComparer.Ordinal) + ) { + if (!documents.assets.TryGetInfo(source.assetPath, out AssetInfo? info) + || info is null + || info.persistentID == draft.id + || info.status != AssetImportStatus.Imported + ) { + continue; + } + ShaderGraphNodeInterface nodeInterface; + try + { + nodeInterface = documents.LoadGraphNodeInterface(info.persistentID); + } + catch (Exception failure) when ((failure is InvalidOperationException or ArgumentException or FormatException) + && RetirementPendingException.Find(failure) is null) + { + continue; + } + + var creation = new ShaderNodeCreation(ShaderGraphNodes.C_CALL_DEFINITION_ID, info.persistentID); + if (!documents.CanCreate(draft, creation)) + { + continue; + } + string catalog = NormalizeCatalog(nodeInterface.createPath); + string root = nodeInterface.kind == ShaderGraphNodeKind.DomainOutput ? "Domain Outputs" : "Graph Nodes"; + string group = "Create/" + root + (catalog.Length == 0 ? string.Empty : "/" + catalog); + builder.AddGroup( + group, + order: nodeInterface.createOrder, + separatorBefore: nodeInterface.kind == ShaderGraphNodeKind.DomainOutput + ); + builder.Add( + group + "/" + nodeInterface.displayName, + "shader/create-node", + order: nodeInterface.createOrder, + argument: creation + ); + } + + builder.Add("View/Focus Selection", "shader/focus", order: 900); + builder.Add("Edit/Copy", "shader/copy", order: 1000); + builder.Add("Edit/Cut", "shader/cut", order: 110); + builder.Add("Edit/Paste", "shader/paste", order: 120); + builder.Add("Edit/Duplicate", "shader/duplicate", order: 130); + builder.Add("Edit/Delete", "shader/delete", order: 140, separatorBefore: true); + builder.Add("Connections/Disconnect", "shader/disconnect", order: 1500); + builder.Add("Connections/Insert Reroute", "shader/reroute", order: 160); + builder.Add("Organize/Group Selection", "shader/group", order: 1700); + builder.Add("Organize/Ungroup Selection", "shader/ungroup", order: 180); + builder.Add("Organize/Collapse to Subgraph", "shader/collapse-subgraph", order: 190, separatorBefore: true); + builder.Add("Assets/Show Shader in File Browser", "shader/reveal-shader", order: 1900); + builder.Add("Assets/Show Source in File Browser", "shader/reveal-source", order: 1910); + builder.Add("Assets/Copy Shader To Project", "shader/copy-to-project", order: 1920, separatorBefore: true); + static string Category(string definition) + => definition switch + { + "inno.shader.constant" or "inno.shader.stage-input" => "Inputs", + ShaderGraphNodes.C_INPUT_DEFINITION_ID or ShaderGraphNodes.C_OUTPUT_DEFINITION_ID => "Interface", + "inno.shader.sample" => "Textures", + "inno.shader.binary" or "inno.shader.construct" or "inno.shader.extract" or "inno.shader.select" => "Math", + "inno.shader.storage-load" or "inno.shader.storage-store" or "inno.shader.storage-atomic-add" => "Resources", + "inno.shader.discard" => "Flow", + "inno.shader.reroute" => "Utility", + _ when definition.Contains("surface-output", StringComparison.Ordinal) => "Domain Outputs", + _ => "Domain" + }; + static int CategoryOrder(string category) + => category switch + { + "Outputs" => 0, + "Interface" => 50, + "Inputs" => 100, + "Textures" => 200, + "Math" => 300, + "Resources" => 400, + "Flow" => 600, + "Utility" => 700, + "Domain Outputs" => 800, + _ => 850 + }; + static string NormalizeCatalog(string value) + => string.Join('/', value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderSelectionAction.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderSelectionAction.cs new file mode 100644 index 000000000..4ebf80165 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderSelectionAction.cs @@ -0,0 +1,38 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +internal abstract class ShaderSelectionAction(ShaderEditorDocuments documents) : EditorAction +{ + /// + /// Gets documents presented by this Shader Editor action. + /// + protected ShaderEditorDocuments documents { get; } = documents; + + /// + /// Gets whether writes is active for the current instance. + /// + protected virtual bool writes => true; + + /// + /// Gets whether needs selection is active for the current instance. + /// + protected virtual bool needsSelection => true; + + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => documents.TryGet(context.target, out ShaderEditorDocuments.Draft draft) + && (!writes + || !draft.readOnly) + && (!needsSelection + || draft.canvas.selectedNodes.Count != 0) ? EditorActionState.enabled : EditorActionState.disabled; +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderTemplateMenu.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderTemplateMenu.cs new file mode 100644 index 000000000..051b430d9 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShaderTemplateMenu.cs @@ -0,0 +1,33 @@ +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorMenuSource("panel/asset.file-browser")] +internal sealed class ShaderTemplateMenu(ShaderEditorDocuments documents) : EditorMenuSource +{ + /// + /// Builds a validated result from the current immutable input snapshot. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The builder consumed by build; ownership remains with the caller unless explicitly stated otherwise. + /// + public override void Build( + EditorMenuContext context, + EditorMenuBuilder builder + ) { + if (documents.templates is null) + { + return; + } + builder.AddGroup("Create/Rendering", order: 200, separatorBefore: true); + builder.AddGroup("Create/Rendering/Shaders", order: 0); + foreach (ShaderGraphTemplateInfo template in documents.templates.templates) + { + builder.Add("Create/Rendering/Shaders/" + template.displayName, "shader/create-asset", argument: template.id, order: 0); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShowShaderDiagnostics.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShowShaderDiagnostics.cs new file mode 100644 index 000000000..c44e64f7c --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/ShowShaderDiagnostics.cs @@ -0,0 +1,26 @@ +using Inno.Assets.Pipeline; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/check", ShaderEditorCanvas.C_AREA)] +internal sealed class ShowShaderDiagnostics(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Gets whether writes is active for the current instance. + /// + protected override bool writes => false; + + /// + /// Gets whether needs selection is active for the current instance. + /// + protected override bool needsSelection => false; + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => documents.ShowCheck(documents.Open(context.target)); +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/UngroupShaderNodes.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/UngroupShaderNodes.cs new file mode 100644 index 000000000..2ce604930 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/Interactions/UngroupShaderNodes.cs @@ -0,0 +1,38 @@ +using System; +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Graphs; +using Inno.Editor.Interactions; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("shader/ungroup", ShaderEditorCanvas.C_AREA)] +internal sealed class UngroupShaderNodes(ShaderEditorDocuments documents) : ShaderSelectionAction(documents) +{ + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) + { + ShaderEditorDocuments.Draft draft = documents.Open(context.target); + GraphDocument graph = documents.Controller(draft).document.Clone(); + ShaderCanvasGroup[] groups = GroupShaderNodes + .Read(documents, graph) + .Where( + group => ( + draft.selectedGroupID.Length != 0 + ? group.id != draft.selectedGroupID + : !group.nodes.All(id => draft.canvas.selectedNodes.Contains(new GraphNodeID(id))) + ) + ) + .ToArray(); + graph.SetMetadata(GroupShaderNodes.C_GROUPS, ShaderGraphDocument.Encode(groups, documents.serialization, documents.context)); + documents.Controller(draft).ReplaceDocument(graph, "Ungroup Shader Nodes"); + draft.selectedGroupID = string.Empty; + documents.Changed(draft); + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/OpenShaderEditorAction.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/OpenShaderEditorAction.cs new file mode 100644 index 000000000..8a1efeb23 --- /dev/null +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/OpenShaderEditorAction.cs @@ -0,0 +1,35 @@ +using System; +using Inno.Editor.Interactions; +using Inno.Rendering.Assets; + +namespace Inno.Editor.Panel.ShaderEditor; + +[EditorAction("editor/open", priority: 1000)] +internal sealed class OpenShaderEditorAction : EditorAction +{ + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; + + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) + { + context.interactions.SetSelection(context.target); + if (!context.interactions.OpenPanel("rendering.shader-editor")) + { + throw new InvalidOperationException("Shader Editor is unavailable."); + } + } +} diff --git a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs index 9d77f2351..513a0c2fa 100644 --- a/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs +++ b/src/composition/editor/panels/Inno.Editor.Panel.ShaderEditor/ShaderEditorPanel.cs @@ -5,10 +5,7 @@ using Inno.Assets.Pipeline; using Inno.Core.Execution; using Inno.Editor.Core; -using Inno.Editor.ImGui.ImGuiWidget; -using Inno.Editor.Interactions; using Inno.Editor.Shaders; -using Inno.Rendering; using Inno.Rendering.Assets; using EditorUI = Inno.Editor.ImGui.EditorUISession; @@ -75,33 +72,3 @@ protected override void OnDraw(EditorContext context) } } } - -[EditorAction("editor/open", priority: 1000)] -internal sealed class OpenShaderEditorAction : EditorAction -{ - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) => EditorActionState.enabled; - - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) - { - context.interactions.SetSelection(context.target); - if (!context.interactions.OpenPanel("rendering.shader-editor")) - { - throw new InvalidOperationException("Shader Editor is unavailable."); - } - } -} diff --git a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs index f2608caba..214c4dec3 100644 --- a/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs +++ b/src/composition/editor/presentation/Inno.Editor.Assets.ImGui/Navigation/AssetBrowserState.cs @@ -1,29 +1,11 @@ using System; -using System.Linq; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Editor.Assets; using Inno.Editor.Core; -using Inno.Editor.Inspection; using Inno.Editor.Interactions; namespace Inno.Editor.Assets.ImGui; -/// -/// Identifies the authoring or installed-content root displayed by the Asset Browser. -/// -public enum AssetBrowserRoot -{ - /// - /// The writable project Assets authoring root. - /// - Assets, - /// - /// The read-only Plugins installation root. - /// - Plugins -} - /// /// Stores asset browser navigation independently from global object selection. /// @@ -254,3 +236,18 @@ private static string Normalize(string? relativePath) return AssetPath.Parse(relativePath.Replace('\\', '/').Trim()).ToString(); } } + +/// +/// Identifies the authoring or installed-content root displayed by the Asset Browser. +/// +public enum AssetBrowserRoot +{ + /// + /// The writable project Assets authoring root. + /// + Assets, + /// + /// The read-only Plugins installation root. + /// + Plugins +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs index 331a0f6e9..95246561f 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDragDropRenderer.cs @@ -1,7 +1,6 @@ using System; using System.Globalization; using Inno.Core.Identity; -using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Interactions; using EditorUI = Inno.Editor.ImGui.EditorUISession; @@ -86,51 +85,3 @@ public static EditorDropWidgetResult Target( private static string GetPayloadType(IdentityDomainID domainID) => C_IDENTITY_PAYLOAD_PREFIX + domainID.value.ToString("X8", CultureInfo.InvariantCulture); } - -/// -/// Reports the preview and delivery state of an ImGui editor drop target. -/// -public readonly record struct EditorDropWidgetResult -{ - /// - /// Creates a combined native-preview and managed-drop result. - /// - /// - /// Whether a compatible native payload is currently hovering the target. - /// - /// - /// The compatibility and visual state returned by the managed drop router. - /// - /// - /// The result produced when the payload was delivered. - /// - public EditorDropWidgetResult( - bool isPreviewing, - EditorDropStatus status, - EditorDropResult result - ) { - this.isPreviewing = isPreviewing; - this.status = status; - this.result = result; - } - - /// - /// Gets whether a compatible native payload is hovering the target. - /// - public bool isPreviewing { get; } - - /// - /// Gets the managed drop compatibility status. - /// - public EditorDropStatus status { get; } - - /// - /// Gets the delivered drop result. - /// - public EditorDropResult result { get; } - - /// - /// Gets an inactive drop target result. - /// - public static EditorDropWidgetResult none => new(false, EditorDropStatus.rejected, EditorDropResult.rejected); -} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDropWidgetResult.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDropWidgetResult.cs new file mode 100644 index 000000000..7d06ce308 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Runtime/EditorDropWidgetResult.cs @@ -0,0 +1,51 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.ImGui; + +/// +/// Reports the preview and delivery state of an ImGui editor drop target. +/// +public readonly record struct EditorDropWidgetResult +{ + /// + /// Creates a combined native-preview and managed-drop result. + /// + /// + /// Whether a compatible native payload is currently hovering the target. + /// + /// + /// The compatibility and visual state returned by the managed drop router. + /// + /// + /// The result produced when the payload was delivered. + /// + public EditorDropWidgetResult( + bool isPreviewing, + EditorDropStatus status, + EditorDropResult result + ) { + this.isPreviewing = isPreviewing; + this.status = status; + this.result = result; + } + + /// + /// Gets whether a compatible native payload is hovering the target. + /// + public bool isPreviewing { get; } + + /// + /// Gets the managed drop compatibility status. + /// + public EditorDropStatus status { get; } + + /// + /// Gets the delivered drop result. + /// + public EditorDropResult result { get; } + + /// + /// Gets an inactive drop target result. + /// + public static EditorDropWidgetResult none => new(false, EditorDropStatus.rejected, EditorDropResult.rejected); +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs index 5a6b046bf..d12b4a6f2 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFont.cs @@ -7,26 +7,6 @@ namespace Inno.Editor.ImGui; -/// -/// Chooses composable font emphasis while leaving actual font ownership with the presentation host. -/// -[Flags] -public enum ImGuiFontStyle -{ - /// - /// Uses the ordinary face. - /// - Regular = 0, - /// - /// Emphasizes text with the bold face. - /// - Bold = 1, - /// - /// Emphasizes text with the italic face. - /// - Italic = 2 -} - /// /// Uses the host's context-owned font catalog without exposing backend types to Editor features. /// @@ -66,45 +46,21 @@ public static ImGuiFontScope PushStyle(ImGuiFontStyle style) } /// -/// Restores a font push only in its original session, frame and native stack position. +/// Chooses composable font emphasis while leaving actual font ownership with the presentation host. /// -public unsafe ref struct ImGuiFontScope : IDisposable +[Flags] +public enum ImGuiFontStyle { - private EditorUISession? m_session; - private HostScope m_scope; - private readonly int m_frame; - private readonly int m_depth; - - internal ImGuiFontScope( - EditorUISession session, - HostScope scope, - int frame, - int depth - ) { - m_session = session; - m_scope = scope; - m_frame = frame; - m_depth = depth; - } - /// - /// Restores the preceding font after validating scope order; default and retired scopes are inert. + /// Uses the ordinary face. /// - /// - /// The scope is used in another context, frame or stack position. - /// - public void Dispose() - { - if (m_session is null) - { - return; - } - m_session.EnsureDrawing(); - if (NativeImGui.GetFrameCount() != m_frame || NativeImGui.Raw.GetCurrentContext()->FontStack.Size != m_depth) - { - throw new InvalidOperationException("Font scopes must retire in their original frame and reverse stack order."); - } - m_scope.Dispose(); - m_session = null; - } + Regular = 0, + /// + /// Emphasizes text with the bold face. + /// + Bold = 1, + /// + /// Emphasizes text with the italic face. + /// + Italic = 2 } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFontScope.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFontScope.cs new file mode 100644 index 000000000..5cceb3810 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/TextInput/ImGuiFontScope.cs @@ -0,0 +1,50 @@ +using System; + +using HostScope = Inno.Adapter.Presentation.ImGui.ImGuiFontScope; +using NativeImGui = Inno.Native.ImGui.ImGui; + +namespace Inno.Editor.ImGui; + +/// +/// Restores a font push only in its original session, frame and native stack position. +/// +public unsafe ref struct ImGuiFontScope : IDisposable +{ + private EditorUISession? m_session; + private HostScope m_scope; + private readonly int m_frame; + private readonly int m_depth; + + internal ImGuiFontScope( + EditorUISession session, + HostScope scope, + int frame, + int depth + ) { + m_session = session; + m_scope = scope; + m_frame = frame; + m_depth = depth; + } + + /// + /// Restores the preceding font after validating scope order; default and retired scopes are inert. + /// + /// + /// The scope is used in another context, frame or stack position. + /// + public void Dispose() + { + if (m_session is null) + { + return; + } + m_session.EnsureDrawing(); + if (NativeImGui.GetFrameCount() != m_frame || NativeImGui.Raw.GetCurrentContext()->FontStack.Size != m_depth) + { + throw new InvalidOperationException("Font scopes must retire in their original frame and reverse stack order."); + } + m_scope.Dispose(); + m_session = null; + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/DialogLayout.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/DialogLayout.cs new file mode 100644 index 000000000..c714a157c --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/DialogLayout.cs @@ -0,0 +1,39 @@ +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Carries a measured dialog layout. Only its required extent is public; drawing mechanics remain owned by the widget. +/// +public readonly struct DialogLayout +{ + internal DialogLayout( + Vector2 size, + float textWidth, + float bodyHeight, + float bodyContentHeight, + float spacing, + float frameHeight, + float actionWidth + ) { + this.size = size; + this.textWidth = textWidth; + this.bodyHeight = bodyHeight; + this.bodyContentHeight = bodyContentHeight; + this.spacing = spacing; + this.frameHeight = frameHeight; + this.actionWidth = actionWidth; + } + + /// + /// Gets the content extent, excluding the window title, border and padding. + /// + public Vector2 size { get; } + + internal float textWidth { get; } + internal float bodyHeight { get; } + internal float bodyContentHeight { get; } + internal float spacing { get; } + internal float frameHeight { get; } + internal float actionWidth { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs index ce26e0b8d..2b48367dd 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Dialog.cs @@ -9,76 +9,6 @@ namespace Inno.Editor.ImGui.ImGuiWidget; -/// -/// Describes immutable content for a measured message dialog. Actions are returned to its owner, never retained as callbacks. -/// -/// -/// The current status or error text. -/// -/// -/// A completed fraction, or null when no progress bar is needed. -/// -/// -/// Whether to show activity without inventing a completed fraction. -/// -/// -/// The optional centered action label. -/// -/// -/// Whether the current operation admits the action. -/// -/// -/// Optional expanded diagnostic text sharing the message scroll owner. -/// -/// -/// Whether Escape activates this action; opt in only for cancellation or dismissal. -/// -public readonly record struct DialogPresentation( - string message, - float? progress = null, - bool indeterminate = false, - string? actionLabel = null, - bool actionEnabled = true, - string? details = null, - bool cancelOnEscape = false -); - -/// -/// Carries a measured dialog layout. Only its required extent is public; drawing mechanics remain owned by the widget. -/// -public readonly struct DialogLayout -{ - internal DialogLayout( - Vector2 size, - float textWidth, - float bodyHeight, - float bodyContentHeight, - float spacing, - float frameHeight, - float actionWidth - ) { - this.size = size; - this.textWidth = textWidth; - this.bodyHeight = bodyHeight; - this.bodyContentHeight = bodyContentHeight; - this.spacing = spacing; - this.frameHeight = frameHeight; - this.actionWidth = actionWidth; - } - - /// - /// Gets the content extent, excluding the window title, border and padding. - /// - public Vector2 size { get; } - - internal float textWidth { get; } - internal float bodyHeight { get; } - internal float bodyContentHeight { get; } - internal float spacing { get; } - internal float frameHeight { get; } - internal float actionWidth { get; } -} - /// /// Presents measured message dialogs through the owning editor UI session. /// @@ -391,3 +321,37 @@ private readonly record struct DialogMeasurementKey( float scrollbar ); } + +/// +/// Describes immutable content for a measured message dialog. Actions are returned to its owner, never retained as callbacks. +/// +/// +/// The current status or error text. +/// +/// +/// A completed fraction, or null when no progress bar is needed. +/// +/// +/// Whether to show activity without inventing a completed fraction. +/// +/// +/// The optional centered action label. +/// +/// +/// Whether the current operation admits the action. +/// +/// +/// Optional expanded diagnostic text sharing the message scroll owner. +/// +/// +/// Whether Escape activates this action; opt in only for cancellation or dismissal. +/// +public readonly record struct DialogPresentation( + string message, + float? progress = null, + bool indeterminate = false, + string? actionLabel = null, + bool actionEnabled = true, + string? details = null, + bool cancelOnEscape = false +); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs index 4c1ddb523..7a37e579a 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Gizmo.cs @@ -1,5 +1,4 @@ using System; -using System.Numerics; using Inno.Native.ImGuizmo; using EngineMatrix = Inno.Core.Mathematics.Matrix; @@ -10,136 +9,6 @@ namespace Inno.Editor.ImGui.ImGuiWidget; -/// -/// Chooses the transform handles rendered by the viewport presenter. -/// -[Flags] -public enum TransformGizmoOperation -{ - /// - /// Renders translation handles. - /// - Translate = 1, - /// - /// Renders rotation handles. - /// - Rotate = 2, - /// - /// Renders the X scale handle. - /// - ScaleX = 4, - /// - /// Renders the Y scale handle. - /// - ScaleY = 8, - /// - /// Renders the Z scale handle. - /// - ScaleZ = 16, - /// - /// Renders all local scale handles. - /// - Scale = ScaleX | ScaleY | ScaleZ -} - -/// -/// Chooses how the manipulation axes are oriented. -/// -public enum TransformGizmoSpace -{ - /// - /// Uses the object's local orientation. - /// - Local, - /// - /// Uses the world's orientation. - /// - World -} - -/// -/// Supplies frame-local matrices and interaction policy without native handles. -/// -public readonly record struct TransformGizmoOptions -{ - /// - /// Gets the viewport's screen-space minimum. - /// - public Vector2 minimum { get; init; } - - /// - /// Gets the viewport's screen-space maximum. - /// - public Vector2 maximum { get; init; } - - /// - /// Gets the column-vector view matrix. - /// - public EngineMatrix view { get; init; } - - /// - /// Gets the projection matrix supplied by the viewport owner. - /// - public EngineMatrix projection { get; init; } - - /// - /// Gets whether this viewport uses an orthographic projection. - /// - public bool orthographic { get; init; } - - /// - /// Gets whether manipulation can consume pointer input. - /// - public bool enabled { get; init; } - - /// - /// Gets the requested handles. - /// - public TransformGizmoOperation operation { get; init; } - - /// - /// Gets the handle coordinate space. - /// - public TransformGizmoSpace space { get; init; } - - /// - /// Gets whether the X translation axis is excluded by the viewport plane. - /// - public bool maskX { get; init; } - - /// - /// Gets whether the Y translation axis is excluded by the viewport plane. - /// - public bool maskY { get; init; } - - /// - /// Gets whether the Z translation axis is excluded by the viewport plane. - /// - public bool maskZ { get; init; } -} - -/// -/// Returns copied manipulation output; the domain owner decides how to apply and record it. -/// -/// -/// The resulting world matrix. -/// -/// -/// Whether the native presenter reported an edited value. -/// -/// -/// Whether the handle currently captures the pointer. -/// -/// -/// Whether the pointer is over a handle. -/// -public readonly record struct TransformGizmoResult( - EngineMatrix matrix, - bool changed, - bool isUsing, - bool isOver -); - /// /// Owns session-local controls, native adaptation and reversible edit gestures. /// @@ -287,3 +156,72 @@ private static unsafe EngineMatrix ReadColumnMajor(float* source) source[15] ); } + +/// +/// Chooses the transform handles rendered by the viewport presenter. +/// +[Flags] +public enum TransformGizmoOperation +{ + /// + /// Renders translation handles. + /// + Translate = 1, + /// + /// Renders rotation handles. + /// + Rotate = 2, + /// + /// Renders the X scale handle. + /// + ScaleX = 4, + /// + /// Renders the Y scale handle. + /// + ScaleY = 8, + /// + /// Renders the Z scale handle. + /// + ScaleZ = 16, + /// + /// Renders all local scale handles. + /// + Scale = ScaleX | ScaleY | ScaleZ +} + +/// +/// Chooses how the manipulation axes are oriented. +/// +public enum TransformGizmoSpace +{ + /// + /// Uses the object's local orientation. + /// + Local, + /// + /// Uses the world's orientation. + /// + World +} + +/// +/// Returns copied manipulation output; the domain owner decides how to apply and record it. +/// +/// +/// The resulting world matrix. +/// +/// +/// Whether the native presenter reported an edited value. +/// +/// +/// Whether the handle currently captures the pointer. +/// +/// +/// Whether the pointer is over a handle. +/// +public readonly record struct TransformGizmoResult( + EngineMatrix matrix, + bool changed, + bool isUsing, + bool isOver +); diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs index 5c658b5c4..b493d4d1d 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.InlineRename.cs @@ -149,89 +149,6 @@ public InlineRenameResult InlineRename( } } -/// -/// Describes the view-owned geometry used to present an active inline rename action. -/// -public sealed class InlineRenamePresentation -{ - /// - /// Creates inline rename presentation data. - /// - /// - /// The stable ImGui identifier used by the input field. - /// - /// - /// The requested input width in logical pixels. - /// - /// - /// The height of the row area in which the field is centered. - /// - /// - /// The maximum UTF-8 buffer size accepted by the input. - /// - /// - /// Thrown when is empty. - /// - /// - /// Thrown when or is not finite and - /// positive, or when is zero. - /// - public InlineRenamePresentation( - string id, - float width, - float rowHeight, - nuint bufferSize = 512 - ) { - if (string.IsNullOrWhiteSpace(id)) - { - throw new ArgumentException("An inline rename identifier is required.", nameof(id)); - } - if (!float.IsFinite(width) || width <= 0f) - { - throw new ArgumentOutOfRangeException(nameof(width), width, "The inline rename width must be finite and positive."); - } - - if (!float.IsFinite(rowHeight) || rowHeight <= 0f) - { - throw new ArgumentOutOfRangeException( - nameof(rowHeight), - rowHeight, - "The inline rename row height must be finite and positive." - ); - } - - if (bufferSize == 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, "The inline rename buffer size must be positive."); - } - - this.id = id; - this.width = width; - this.rowHeight = rowHeight; - this.bufferSize = bufferSize; - } - - /// - /// Gets the stable ImGui identifier used by the input field. - /// - public string id { get; } - - /// - /// Gets the requested input width in logical pixels. - /// - public float width { get; } - - /// - /// Gets the height of the row area in which the input field is centered. - /// - public float rowHeight { get; } - - /// - /// Gets the maximum UTF-8 buffer size accepted by the input. - /// - public nuint bufferSize { get; } -} - /// /// Describes the outcome of an inline rename control. /// diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs index c1a51ef70..b81ff6e37 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Selection.cs @@ -208,69 +208,3 @@ private static bool HasPrimaryModifier( return (modifiers & keyboard.primaryModifier) == keyboard.primaryModifier; } } - -/// -/// Carries frame-local list navigation intents over visible indices without owning objects or selection state. -/// -public readonly struct ListNavigationResult -{ - internal ListNavigationResult( - int focusedIndex, - bool focusChanged, - bool selectionRequested, - bool extendRange, - bool additive, - bool toggle, - bool activate, - bool cancel - ) { - this.focusedIndex = focusedIndex; - this.focusChanged = focusChanged; - this.selectionRequested = selectionRequested; - this.extendRange = extendRange; - this.additive = additive; - this.toggle = toggle; - this.activate = activate; - this.cancel = cancel; - } - - /// - /// Gets the resulting visible focus index, or minus one for no focus. - /// - public int focusedIndex { get; } - - /// - /// Gets whether the visible focus index changed. - /// - public bool focusChanged { get; } - - /// - /// Gets whether the caller should apply a domain selection operation. - /// - public bool selectionRequested { get; } - - /// - /// Gets whether the selection should extend from its existing anchor. - /// - public bool extendRange { get; } - - /// - /// Gets whether the product's primary modifier requests preserving other selected entries. - /// - public bool additive { get; } - - /// - /// Gets whether Space with the primary modifier requests toggling the focused entry. - /// - public bool toggle { get; } - - /// - /// Gets whether Enter requests activation of the focused entry. - /// - public bool activate { get; } - - /// - /// Gets whether Escape requests canceling the current list workflow. - /// - public bool cancel { get; } -} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs index 2fbc406d1..4c4c4ab21 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ImGuiWidget.Tree.cs @@ -552,178 +552,3 @@ uint color NativeImGui.Raw.ChannelsSetCurrent(drawList, 1); } } - -/// -/// Provides the native geometry of a tree row while its custom content is being drawn. -/// -public readonly struct TreeNodeDrawContext -{ - internal TreeNodeDrawContext(float rowHeight) - { - this.rowHeight = rowHeight; - } - - /// - /// Gets the actual native row height established for the current tree node. - /// - public float rowHeight { get; } -} - -/// -/// Configures an interactive tree row. -/// -public readonly struct TreeNodeOptions -{ - /// - /// Gets explicit indentation for a flattened row, or null for a nested native tree. - /// Explicit-depth rows never push a native tree scope; callers must not call TreePop for them. - /// - public int? depth { get; init; } - - /// - /// Gets whether this row should receive keyboard focus during this submission when its tree window is focused. - /// - public bool requestFocus { get; init; } - - /// - /// Gets whether an active edit requires content submission even while its row is clipped. - /// - public bool keepContentActive { get; init; } - - /// - /// Gets whether the row is selected. - /// - public bool selected { get; init; } - - /// - /// Gets whether the row has no expandable children. - /// - public bool isLeaf { get; init; } - - /// - /// Gets whether a custom background is drawn behind an unselected row. - /// - public bool showBackground { get; init; } - - /// - /// Gets the custom background color used when is enabled. - /// - public Vector4 backgroundColor { get; init; } - - /// - /// Gets whether the row keeps its configured background while hovered. - /// - public bool suppressHoverHighlight { get; init; } - - /// - /// Gets whether ancestor and branch guide lines are omitted for this row. - /// - public bool hideGuideLines { get; init; } - - /// - /// Gets the callback that draws controls fixed to the current viewport without extending the - /// tree's horizontal content boundary. - /// - public Action? drawViewportOverlay { get; init; } -} - -/// -/// Describes interaction state produced by a tree row. -/// -public readonly struct TreeNodeResult -{ - internal TreeNodeResult( - bool isOpen, - bool isClicked, - bool isDoubleClicked, - bool isHovered, - Vector2 min, - Vector2 max, - Vector2 contentMin, - bool isSubmitted - ) { - this.isOpen = isOpen; - this.isClicked = isClicked; - this.isDoubleClicked = isDoubleClicked; - this.isHovered = isHovered; - this.min = min; - this.max = max; - this.contentMin = contentMin; - this.isSubmitted = isSubmitted; - } - - /// - /// Gets whether row controls were submitted; ordinary clipped rows are false, while preserved active edits remain true. - /// - public bool isSubmitted { get; } - - /// - /// Gets whether child content should be rendered. - /// - public bool isOpen { get; } - - /// - /// Gets whether the content row was clicked. - /// - public bool isClicked { get; } - - /// - /// Gets whether the content row was double-clicked. Double-clicking a non-leaf content row - /// also toggles its retained expansion state for the next frame. - /// - public bool isDoubleClicked { get; } - - /// - /// Gets whether the full row is hovered. - /// - public bool isHovered { get; } - - /// - /// Gets the row minimum screen coordinate. - /// - public Vector2 min { get; } - - /// - /// Gets the row maximum screen coordinate. - /// - public Vector2 max { get; } - - /// - /// Gets the minimum screen coordinate of the row's interactive content, excluding tree indentation. - /// - public Vector2 contentMin { get; } -} - -internal sealed class TreeWidgetWindowState -{ - internal readonly HashSet navigationItemIDs = []; - internal readonly List treeNodeStack = []; - internal readonly List lastNodeIDsByDepth = []; - internal readonly List lineSegments = []; - internal readonly Dictionary hasNextSiblingByID = new(StringComparer.Ordinal); - internal readonly Dictionary openStatesByID = new(StringComparer.Ordinal); - internal ulong expansionRevision; - internal uint activeContentID; - internal string? activeContentOwner; - internal int lastFrame = -1; -} - -internal struct TreeWidgetNodeState -{ - internal string id; - internal Vector2 cursor; - internal float rowMaxY; - internal bool hasNextSibling; -} - -internal struct TreeWidgetLineSegment -{ - internal Vector2 from; - internal Vector2 to; -} - -internal struct TreeWidgetHighlightRect -{ - internal Vector2 min; - internal Vector2 max; -} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/InlineRenamePresentation.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/InlineRenamePresentation.cs new file mode 100644 index 000000000..ae419cb5b --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/InlineRenamePresentation.cs @@ -0,0 +1,86 @@ +using System; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Describes the view-owned geometry used to present an active inline rename action. +/// +public sealed class InlineRenamePresentation +{ + /// + /// Creates inline rename presentation data. + /// + /// + /// The stable ImGui identifier used by the input field. + /// + /// + /// The requested input width in logical pixels. + /// + /// + /// The height of the row area in which the field is centered. + /// + /// + /// The maximum UTF-8 buffer size accepted by the input. + /// + /// + /// Thrown when is empty. + /// + /// + /// Thrown when or is not finite and + /// positive, or when is zero. + /// + public InlineRenamePresentation( + string id, + float width, + float rowHeight, + nuint bufferSize = 512 + ) { + if (string.IsNullOrWhiteSpace(id)) + { + throw new ArgumentException("An inline rename identifier is required.", nameof(id)); + } + if (!float.IsFinite(width) || width <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(width), width, "The inline rename width must be finite and positive."); + } + + if (!float.IsFinite(rowHeight) || rowHeight <= 0f) + { + throw new ArgumentOutOfRangeException( + nameof(rowHeight), + rowHeight, + "The inline rename row height must be finite and positive." + ); + } + + if (bufferSize == 0) + { + throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, "The inline rename buffer size must be positive."); + } + + this.id = id; + this.width = width; + this.rowHeight = rowHeight; + this.bufferSize = bufferSize; + } + + /// + /// Gets the stable ImGui identifier used by the input field. + /// + public string id { get; } + + /// + /// Gets the requested input width in logical pixels. + /// + public float width { get; } + + /// + /// Gets the height of the row area in which the input field is centered. + /// + public float rowHeight { get; } + + /// + /// Gets the maximum UTF-8 buffer size accepted by the input. + /// + public nuint bufferSize { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ListNavigationResult.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ListNavigationResult.cs new file mode 100644 index 000000000..43df7ae66 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/ListNavigationResult.cs @@ -0,0 +1,67 @@ +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Carries frame-local list navigation intents over visible indices without owning objects or selection state. +/// +public readonly struct ListNavigationResult +{ + internal ListNavigationResult( + int focusedIndex, + bool focusChanged, + bool selectionRequested, + bool extendRange, + bool additive, + bool toggle, + bool activate, + bool cancel + ) { + this.focusedIndex = focusedIndex; + this.focusChanged = focusChanged; + this.selectionRequested = selectionRequested; + this.extendRange = extendRange; + this.additive = additive; + this.toggle = toggle; + this.activate = activate; + this.cancel = cancel; + } + + /// + /// Gets the resulting visible focus index, or minus one for no focus. + /// + public int focusedIndex { get; } + + /// + /// Gets whether the visible focus index changed. + /// + public bool focusChanged { get; } + + /// + /// Gets whether the caller should apply a domain selection operation. + /// + public bool selectionRequested { get; } + + /// + /// Gets whether the selection should extend from its existing anchor. + /// + public bool extendRange { get; } + + /// + /// Gets whether the product's primary modifier requests preserving other selected entries. + /// + public bool additive { get; } + + /// + /// Gets whether Space with the primary modifier requests toggling the focused entry. + /// + public bool toggle { get; } + + /// + /// Gets whether Enter requests activation of the focused entry. + /// + public bool activate { get; } + + /// + /// Gets whether Escape requests canceling the current list workflow. + /// + public bool cancel { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TransformGizmoOptions.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TransformGizmoOptions.cs new file mode 100644 index 000000000..d53f4f68a --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TransformGizmoOptions.cs @@ -0,0 +1,66 @@ +using System.Numerics; + +using EngineMatrix = Inno.Core.Mathematics.Matrix; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Supplies frame-local matrices and interaction policy without native handles. +/// +public readonly record struct TransformGizmoOptions +{ + /// + /// Gets the viewport's screen-space minimum. + /// + public Vector2 minimum { get; init; } + + /// + /// Gets the viewport's screen-space maximum. + /// + public Vector2 maximum { get; init; } + + /// + /// Gets the column-vector view matrix. + /// + public EngineMatrix view { get; init; } + + /// + /// Gets the projection matrix supplied by the viewport owner. + /// + public EngineMatrix projection { get; init; } + + /// + /// Gets whether this viewport uses an orthographic projection. + /// + public bool orthographic { get; init; } + + /// + /// Gets whether manipulation can consume pointer input. + /// + public bool enabled { get; init; } + + /// + /// Gets the requested handles. + /// + public TransformGizmoOperation operation { get; init; } + + /// + /// Gets the handle coordinate space. + /// + public TransformGizmoSpace space { get; init; } + + /// + /// Gets whether the X translation axis is excluded by the viewport plane. + /// + public bool maskX { get; init; } + + /// + /// Gets whether the Y translation axis is excluded by the viewport plane. + /// + public bool maskY { get; init; } + + /// + /// Gets whether the Z translation axis is excluded by the viewport plane. + /// + public bool maskZ { get; init; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeDrawContext.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeDrawContext.cs new file mode 100644 index 000000000..a7d8f8f14 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeDrawContext.cs @@ -0,0 +1,17 @@ +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Provides the native geometry of a tree row while its custom content is being drawn. +/// +public readonly struct TreeNodeDrawContext +{ + internal TreeNodeDrawContext(float rowHeight) + { + this.rowHeight = rowHeight; + } + + /// + /// Gets the actual native row height established for the current tree node. + /// + public float rowHeight { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeOptions.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeOptions.cs new file mode 100644 index 000000000..a0ae78418 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeOptions.cs @@ -0,0 +1,62 @@ +using System; +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Configures an interactive tree row. +/// +public readonly struct TreeNodeOptions +{ + /// + /// Gets explicit indentation for a flattened row, or null for a nested native tree. + /// Explicit-depth rows never push a native tree scope; callers must not call TreePop for them. + /// + public int? depth { get; init; } + + /// + /// Gets whether this row should receive keyboard focus during this submission when its tree window is focused. + /// + public bool requestFocus { get; init; } + + /// + /// Gets whether an active edit requires content submission even while its row is clipped. + /// + public bool keepContentActive { get; init; } + + /// + /// Gets whether the row is selected. + /// + public bool selected { get; init; } + + /// + /// Gets whether the row has no expandable children. + /// + public bool isLeaf { get; init; } + + /// + /// Gets whether a custom background is drawn behind an unselected row. + /// + public bool showBackground { get; init; } + + /// + /// Gets the custom background color used when is enabled. + /// + public Vector4 backgroundColor { get; init; } + + /// + /// Gets whether the row keeps its configured background while hovered. + /// + public bool suppressHoverHighlight { get; init; } + + /// + /// Gets whether ancestor and branch guide lines are omitted for this row. + /// + public bool hideGuideLines { get; init; } + + /// + /// Gets the callback that draws controls fixed to the current viewport without extending the + /// tree's horizontal content boundary. + /// + public Action? drawViewportOverlay { get; init; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeResult.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeResult.cs new file mode 100644 index 000000000..910331ebc --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeNodeResult.cs @@ -0,0 +1,70 @@ +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +/// +/// Describes interaction state produced by a tree row. +/// +public readonly struct TreeNodeResult +{ + internal TreeNodeResult( + bool isOpen, + bool isClicked, + bool isDoubleClicked, + bool isHovered, + Vector2 min, + Vector2 max, + Vector2 contentMin, + bool isSubmitted + ) { + this.isOpen = isOpen; + this.isClicked = isClicked; + this.isDoubleClicked = isDoubleClicked; + this.isHovered = isHovered; + this.min = min; + this.max = max; + this.contentMin = contentMin; + this.isSubmitted = isSubmitted; + } + + /// + /// Gets whether row controls were submitted; ordinary clipped rows are false, while preserved active edits remain true. + /// + public bool isSubmitted { get; } + + /// + /// Gets whether child content should be rendered. + /// + public bool isOpen { get; } + + /// + /// Gets whether the content row was clicked. + /// + public bool isClicked { get; } + + /// + /// Gets whether the content row was double-clicked. Double-clicking a non-leaf content row + /// also toggles its retained expansion state for the next frame. + /// + public bool isDoubleClicked { get; } + + /// + /// Gets whether the full row is hovered. + /// + public bool isHovered { get; } + + /// + /// Gets the row minimum screen coordinate. + /// + public Vector2 min { get; } + + /// + /// Gets the row maximum screen coordinate. + /// + public Vector2 max { get; } + + /// + /// Gets the minimum screen coordinate of the row's interactive content, excluding tree indentation. + /// + public Vector2 contentMin { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs new file mode 100644 index 000000000..1a59e8945 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs @@ -0,0 +1,9 @@ +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +internal struct TreeWidgetHighlightRect +{ + internal Vector2 min; + internal Vector2 max; +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs new file mode 100644 index 000000000..5f4b1283a --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs @@ -0,0 +1,9 @@ +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +internal struct TreeWidgetLineSegment +{ + internal Vector2 from; + internal Vector2 to; +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs new file mode 100644 index 000000000..53a36b009 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs @@ -0,0 +1,11 @@ +using System.Numerics; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +internal struct TreeWidgetNodeState +{ + internal string id; + internal Vector2 cursor; + internal float rowMaxY; + internal bool hasNextSibling; +} diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetWindowState.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetWindowState.cs new file mode 100644 index 000000000..2497beb9c --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetWindowState.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Editor.ImGui.ImGuiWidget; + +internal sealed class TreeWidgetWindowState +{ + internal readonly HashSet navigationItemIDs = []; + internal readonly List treeNodeStack = []; + internal readonly List lastNodeIDsByDepth = []; + internal readonly List lineSegments = []; + internal readonly Dictionary hasNextSiblingByID = new(StringComparer.Ordinal); + internal readonly Dictionary openStatesByID = new(StringComparer.Ordinal); + internal ulong expansionRevision; + internal uint activeContentID; + internal string? activeContentOwner; + internal int lastFrame = -1; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs index ba9334e44..4d2d14daf 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspectionDrawer.cs @@ -1,18 +1,9 @@ using System; -using System.Linq; -using System.Numerics; using Inno.Assets.Pipeline; -using Inno.Editor.Assets; using Inno.Editor.ImGui; using Inno.Editor.Inspection; -using Inno.Editor.Rendering; -using Inno.Editor.Shaders; -using Inno.Rendering; using Inno.Rendering.Assets; -using EditorUI = Inno.Editor.ImGui.EditorUISession; -using Gui = Inno.Editor.ImGui.ImGui; - namespace Inno.Editor.Shaders.ImGui; [InspectionDrawer(typeof(MaterialAsset))] @@ -100,470 +91,3 @@ MaterialAsset target } } } - -[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] -internal sealed class MaterialSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer -{ - /// - /// Gets the icon glyph used to represent this item in the editor. - /// - public override string icon => ImGuiIcon.C_FILE; - - /// - /// Retrieves the current icon from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated text representation owned by the caller. - /// - protected override string GetIcon( - InspectionDrawContext context, - AssetFileEntry target - ) => icons.GetIcon(target); - - /// - /// Checks whether this drawer supports the selected Inspector target. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// when the documented condition is satisfied; otherwise, . - /// - protected override bool CanInspect(AssetFileEntry target) - => !target.isDirectory && target.extension.Equals(".imaterial", StringComparison.OrdinalIgnoreCase); - - /// - /// Binds a caller-visible label to the current inspection target. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - /// - /// The validated (string name, actionstring? setter) that represents the completed operation. - /// - protected override (string name, Action? setter) BindName( - InspectionDrawContext context, - AssetFileEntry target - ) => (target.nameWithoutExtension, null); - - /// - /// Renders the header presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void DrawHeader( - InspectionDrawContext context, - AssetFileEntry target - ) { - if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) - { - MaterialInspector.DrawHeader(context, documents, documents.OpenDraft(target.assetPath)); - } - } - - /// - /// Renders the value presentation for the current editor frame. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The existing target that receives the validated result. - /// - protected override void Draw( - InspectionDrawContext context, - AssetFileEntry target - ) { - if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) - { - MaterialInspector.Draw(context, documents, documents.OpenDraft(target.assetPath)); - } - } -} - -internal static class MaterialInspector -{ - internal static void DrawHeader( - InspectionDrawContext context, - MaterialDocuments documents, - AssetDraftDocuments.Draft draft - ) => EditorUI.current.widgets.Disabled(draft.readOnly, () => - { - if (Gui.Button("Save")) - { - _ = context.interactions.documents.Save(draft.documentID); - } - Gui.SameLine(0f, -1f); - if (Gui.Button("Revert")) - { - _ = context.interactions.documents.Revert(draft.documentID); - } - }); - - internal static void Draw( - InspectionDrawContext context, - MaterialDocuments documents, - AssetDraftDocuments.Draft draft - ) { - MaterialAsset material = documents.Read(draft.id); - var edits = new DraftEdits(documents, draft, material); - Gui.PushID(draft.id.ToString("N")); - try - { - if (EditorUI.current.widgets.SectionHeader("Preview", "Shows an isolated preview of the current Material draft.")) - { - if (material.shader is null || material.shader.isMissing) - { - EditorUI.current.widgets.Hint("Choose an available Shader to preview this Material."); - } - else if (context.interactions.TryGetModule(out ShaderPreviews? shaderPreviews) - && shaderPreviews is not null - ) { - shaderPreviews.DrawMaterial(draft.id, material, MathF.Max(1f, MathF.Min(256f, Gui.GetContentRegionAvailable().X))); - } - else - { - EditorUI.current.widgets.Hint("Material preview is unavailable."); - } - } - - bool materialOpen = EditorUI.current.widgets.SectionHeader( - "Material", - "Edits stay in this draft. Save publishes through normal asset import; Revert reloads the source." - ); - if (materialOpen) - { - EditorUI.current.widgets.Hint( - draft.isDirty ? "Unsaved changes · Scene/Game unchanged" : "Saved · compilation and import are separate" - ); - if (draft.error.Length != 0) - { - EditorUI.current.widgets.Hint(draft.error); - } - if (draft.readOnly) - { - EditorUI.current.widgets.Hint("Installed material · copy to the project to edit"); - } - Draw("shader", "Shader", typeof(ShaderAsset), () => material.shader, value => material.shader = (ShaderAsset? )value); - } - - ShaderDefinition? definition = material.shader?.definition; - if (material.shader is null || material.shader.isMissing || definition is null) - { - if (materialOpen) - { - EditorUI.current.widgets.Hint( - "Choose an available Shader. Existing overrides are retained until its interface can be resolved." - ); - } - return; - } - - if (materialOpen && Gui.SmallButton("Open Shader Editor")) - { - context.interactions.SetSelection(material.shader); - context.interactions.OpenPanel("rendering.shader-editor"); - } - - if (materialOpen) - { - Gui.SameLine(0f, -1f); - if (Gui.SmallButton("Locate Shader") - && documents.assets.TryGetFileSystemEntry(material.shader.assetPath, out AssetFileEntry shaderEntry) - ) { - context.interactions.SetSelection(shaderEntry); - } - } - - if (materialOpen && (definition.techniques.Length > 1 || material.techniqueId.isValid)) - { - if (EditorUI.current.widgets.BeginBoundedCombo( - "##technique", - material.techniqueId.isValid ? material.techniqueId.value : "Automatic" - )) { - try - { - if (Gui.Selectable("Automatic", !material.techniqueId.isValid) && !draft.readOnly) - { - material.techniqueId = default; - documents.Replace(draft.id, material); - } - - foreach (ShaderTechniqueDefinition technique in definition.techniques) - { - if (Gui.Selectable(technique.id.value, material.techniqueId == technique.id) && !draft.readOnly) - { - material.techniqueId = technique.id; - documents.Replace(draft.id, material); - } - } - } - finally - { - EditorUI.current.widgets.EndBoundedCombo(); - } - } - } - - bool parametersOpen = EditorUI.current.widgets.SectionHeader( - "Parameters", - "Inherited values follow Shader defaults. Changing a field creates a Material override; Reset restores inheritance." - ); - bool groupOpen = parametersOpen; - string currentGroup = string.Empty; - int visibleParameters = 0; - foreach (ShaderPropertyDefinition property in definition.properties.Where(IsEditable)) - { - ShaderParameterPresentation presentation = documents.Presentation( - material.shader, - property.id, - out string presentationError - ); - if (presentationError.Length != 0) - { - EditorUI.current.widgets.Hint("Parameter presentation unavailable: " + presentationError); - } - if (!presentation.visible) - { - continue; - } - visibleParameters++; - if (presentation.group != currentGroup) - { - currentGroup = presentation.group; - groupOpen = EditorUI.current.widgets.SectionHeader(currentGroup.Length == 0 ? "Parameters" : currentGroup); - } - - if (!groupOpen) - { - continue; - } - bool overridden = material.TryGet(property.id, out MaterialValue value); - if (overridden && !ShaderPropertyInspector.Compatible(property.type, value.kind)) - { - continue; - } - if (!overridden) - { - value = property.defaultValue; - } - Gui.PushID(property.id.value); - try - { - ShaderPropertyInspector.Draw( - context, - draft, - "material." + property.id.value, - property, - value, - next => material.Set(property.id, next), - edits, - draft.readOnly, - presentation - ); - EditorUI.current.widgets.Hint(overridden ? "Material override" : "Inherited from Shader"); - if (overridden && !draft.readOnly && Gui.SmallButton("Reset override")) - { - material.ReplaceProperties(material.properties.Where(entry => entry.id != property.id).ToArray()); - documents.Replace(draft.id, material); - } - - if (value.kind == MaterialValueKind.Texture) - { - if (value.texture is { isMissing: false } texture - && documents.previews.TryGetTexture(texture, out EditorPreviewHandle preview) - ) { - float width = MathF.Max(1f, MathF.Min(128f, Gui.GetContentRegionAvailable().X)); - float height = width * preview.pixelHeight / preview.pixelWidth; - if (height > 128f) - { - width *= 128f / height; - height = 128f; - } - - documents.previews.Draw(preview, new Vector2(width, height)); - } - } - } - finally - { - Gui.PopID(); - } - } - - if (parametersOpen && visibleParameters == 0 && definition.keywords.Length == 0) - { - EditorUI.current.widgets.Hint("No editable parameters."); - } - if (parametersOpen && material.properties.Count != 0 && !draft.readOnly && Gui.Button("Reset all overrides")) - { - material.ReplaceProperties([]); - documents.Replace(draft.id, material); - } - - foreach (ShaderKeywordDefinition keyword in parametersOpen ? definition.keywords : []) - { - string selected = keyword.options.FirstOrDefault(option => material.keywords.Contains(option)) ?? "None"; - if (!EditorUI.current.widgets.BeginBoundedCombo(keyword.id, selected)) - { - continue; - } - try - { - if (Gui.Selectable("None", selected == "None")) - { - SetOption(null); - } - foreach (string option in keyword.options) - { - if (Gui.Selectable(option, selected == option)) - { - SetOption(option); - } - } - } - finally - { - EditorUI.current.widgets.EndBoundedCombo(); - } - - void SetOption(string? next) - { - if (draft.readOnly) - { - return; - } - foreach (string option in keyword.options) - { - material.SetKeyword(option, option == next); - } - documents.Replace(draft.id, material); - } - } - - MaterialPropertyEntry[] orphaned = material.properties - .Where( - entry => !definition.properties.Any( - property => ( - property.id == entry.id - && IsEditable(property) - && ShaderPropertyInspector.Compatible(property.type, entry.value.kind) - ) - ) - ) - .ToArray(); - if (orphaned.Length != 0) - { - if (EditorUI.current.widgets.SectionHeader( - "Unresolved Overrides", - "These values were retained after an interface change. Remove them explicitly or restore a compatible Shader before publishing." - )) { - foreach (MaterialPropertyEntry entry in orphaned) - { - Gui.Text(entry.id.value + " · " + entry.value.kind); - if (!draft.readOnly && Gui.SmallButton("Remove##" + entry.id.value)) - { - material.ReplaceProperties(material.properties.Where(value => value.id != entry.id).ToArray()); - documents.Replace(draft.id, material); - } - } - } - } - - ShaderPropertyDefinition[] passBindings = definition.properties.Where(property => !IsEditable(property)).ToArray(); - string[] unknownKeywords = material.keywords - .Where(value => !definition.keywords.Any(keyword => keyword.options.Contains(value))) - .ToArray(); - if (unknownKeywords.Length != 0) - { - if (EditorUI.current.widgets.SectionHeader( - "Unresolved Keywords", - "These overrides no longer belong to the Shader interface. They remain until explicitly removed." - )) { - foreach (string keyword in unknownKeywords) - { - Gui.Text(keyword); - if (!draft.readOnly && Gui.SmallButton("Remove##keyword." + keyword)) - { - material.SetKeyword(keyword, false); - documents.Replace(draft.id, material); - } - } - } - } - - if (passBindings.Length != 0) - { - if (EditorUI.current.widgets.SectionHeader( - "Pipeline Bindings", - "These resources are supplied by the Render Pass, not by this Material." - )) { - foreach (ShaderPropertyDefinition property in passBindings) - { - EditorUI.current.widgets.Hint(property.displayName + " · " + property.type + " · " + property.bindingOwner); - } - } - } - } - finally - { - Gui.PopID(); - } - - void Draw( - string path, - string label, - Type type, - Func getter, - Action setter - ) => context.properties.DrawValue( - context.editorContext, - draft, - "material." + path, - label, - type, - getter, - setter, - edits, - draft.readOnly - ); - } - - private static bool IsEditable(ShaderPropertyDefinition property) - => property.bindingOwner == ShaderPropertyBindingOwner.Material - && property.bindingKind is ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture; - - private sealed class DraftEdits( - MaterialDocuments documents, - AssetDraftDocuments.Draft draft, - MaterialAsset material - ) : IInspectionPropertyEditService - { - /// - public bool ChangeProperty( - object owner, - string propertyName, - Action mutation, - string historyName, - string? mergeKey, - string? componentName - ) { - mutation(); - documents.Replace(draft.id, material, mergeKey); - return true; - } - } -} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspector.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspector.cs new file mode 100644 index 000000000..b4ecfa71d --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialInspector.cs @@ -0,0 +1,388 @@ +using System; +using System.Linq; +using System.Numerics; +using Inno.Assets.Pipeline; +using Inno.Editor.Assets; +using Inno.Editor.Inspection; +using Inno.Editor.Rendering; +using Inno.Rendering; +using Inno.Rendering.Assets; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Shaders.ImGui; + +internal static class MaterialInspector +{ + internal static void DrawHeader( + InspectionDrawContext context, + MaterialDocuments documents, + AssetDraftDocuments.Draft draft + ) => EditorUI.current.widgets.Disabled(draft.readOnly, () => + { + if (Gui.Button("Save")) + { + _ = context.interactions.documents.Save(draft.documentID); + } + Gui.SameLine(0f, -1f); + if (Gui.Button("Revert")) + { + _ = context.interactions.documents.Revert(draft.documentID); + } + }); + + internal static void Draw( + InspectionDrawContext context, + MaterialDocuments documents, + AssetDraftDocuments.Draft draft + ) { + MaterialAsset material = documents.Read(draft.id); + var edits = new DraftEdits(documents, draft, material); + Gui.PushID(draft.id.ToString("N")); + try + { + if (EditorUI.current.widgets.SectionHeader("Preview", "Shows an isolated preview of the current Material draft.")) + { + if (material.shader is null || material.shader.isMissing) + { + EditorUI.current.widgets.Hint("Choose an available Shader to preview this Material."); + } + else if (context.interactions.TryGetModule(out ShaderPreviews? shaderPreviews) + && shaderPreviews is not null + ) { + shaderPreviews.DrawMaterial(draft.id, material, MathF.Max(1f, MathF.Min(256f, Gui.GetContentRegionAvailable().X))); + } + else + { + EditorUI.current.widgets.Hint("Material preview is unavailable."); + } + } + + bool materialOpen = EditorUI.current.widgets.SectionHeader( + "Material", + "Edits stay in this draft. Save publishes through normal asset import; Revert reloads the source." + ); + if (materialOpen) + { + EditorUI.current.widgets.Hint( + draft.isDirty ? "Unsaved changes · Scene/Game unchanged" : "Saved · compilation and import are separate" + ); + if (draft.error.Length != 0) + { + EditorUI.current.widgets.Hint(draft.error); + } + if (draft.readOnly) + { + EditorUI.current.widgets.Hint("Installed material · copy to the project to edit"); + } + Draw("shader", "Shader", typeof(ShaderAsset), () => material.shader, value => material.shader = (ShaderAsset? )value); + } + + ShaderDefinition? definition = material.shader?.definition; + if (material.shader is null || material.shader.isMissing || definition is null) + { + if (materialOpen) + { + EditorUI.current.widgets.Hint( + "Choose an available Shader. Existing overrides are retained until its interface can be resolved." + ); + } + return; + } + + if (materialOpen && Gui.SmallButton("Open Shader Editor")) + { + context.interactions.SetSelection(material.shader); + context.interactions.OpenPanel("rendering.shader-editor"); + } + + if (materialOpen) + { + Gui.SameLine(0f, -1f); + if (Gui.SmallButton("Locate Shader") + && documents.assets.TryGetFileSystemEntry(material.shader.assetPath, out AssetFileEntry shaderEntry) + ) { + context.interactions.SetSelection(shaderEntry); + } + } + + if (materialOpen && (definition.techniques.Length > 1 || material.techniqueId.isValid)) + { + if (EditorUI.current.widgets.BeginBoundedCombo( + "##technique", + material.techniqueId.isValid ? material.techniqueId.value : "Automatic" + )) { + try + { + if (Gui.Selectable("Automatic", !material.techniqueId.isValid) && !draft.readOnly) + { + material.techniqueId = default; + documents.Replace(draft.id, material); + } + + foreach (ShaderTechniqueDefinition technique in definition.techniques) + { + if (Gui.Selectable(technique.id.value, material.techniqueId == technique.id) && !draft.readOnly) + { + material.techniqueId = technique.id; + documents.Replace(draft.id, material); + } + } + } + finally + { + EditorUI.current.widgets.EndBoundedCombo(); + } + } + } + + bool parametersOpen = EditorUI.current.widgets.SectionHeader( + "Parameters", + "Inherited values follow Shader defaults. Changing a field creates a Material override; Reset restores inheritance." + ); + bool groupOpen = parametersOpen; + string currentGroup = string.Empty; + int visibleParameters = 0; + foreach (ShaderPropertyDefinition property in definition.properties.Where(IsEditable)) + { + ShaderParameterPresentation presentation = documents.Presentation( + material.shader, + property.id, + out string presentationError + ); + if (presentationError.Length != 0) + { + EditorUI.current.widgets.Hint("Parameter presentation unavailable: " + presentationError); + } + if (!presentation.visible) + { + continue; + } + visibleParameters++; + if (presentation.group != currentGroup) + { + currentGroup = presentation.group; + groupOpen = EditorUI.current.widgets.SectionHeader(currentGroup.Length == 0 ? "Parameters" : currentGroup); + } + + if (!groupOpen) + { + continue; + } + bool overridden = material.TryGet(property.id, out MaterialValue value); + if (overridden && !ShaderPropertyInspector.Compatible(property.type, value.kind)) + { + continue; + } + if (!overridden) + { + value = property.defaultValue; + } + Gui.PushID(property.id.value); + try + { + ShaderPropertyInspector.Draw( + context, + draft, + "material." + property.id.value, + property, + value, + next => material.Set(property.id, next), + edits, + draft.readOnly, + presentation + ); + EditorUI.current.widgets.Hint(overridden ? "Material override" : "Inherited from Shader"); + if (overridden && !draft.readOnly && Gui.SmallButton("Reset override")) + { + material.ReplaceProperties(material.properties.Where(entry => entry.id != property.id).ToArray()); + documents.Replace(draft.id, material); + } + + if (value.kind == MaterialValueKind.Texture) + { + if (value.texture is { isMissing: false } texture + && documents.previews.TryGetTexture(texture, out EditorPreviewHandle preview) + ) { + float width = MathF.Max(1f, MathF.Min(128f, Gui.GetContentRegionAvailable().X)); + float height = width * preview.pixelHeight / preview.pixelWidth; + if (height > 128f) + { + width *= 128f / height; + height = 128f; + } + + documents.previews.Draw(preview, new Vector2(width, height)); + } + } + } + finally + { + Gui.PopID(); + } + } + + if (parametersOpen && visibleParameters == 0 && definition.keywords.Length == 0) + { + EditorUI.current.widgets.Hint("No editable parameters."); + } + if (parametersOpen && material.properties.Count != 0 && !draft.readOnly && Gui.Button("Reset all overrides")) + { + material.ReplaceProperties([]); + documents.Replace(draft.id, material); + } + + foreach (ShaderKeywordDefinition keyword in parametersOpen ? definition.keywords : []) + { + string selected = keyword.options.FirstOrDefault(option => material.keywords.Contains(option)) ?? "None"; + if (!EditorUI.current.widgets.BeginBoundedCombo(keyword.id, selected)) + { + continue; + } + try + { + if (Gui.Selectable("None", selected == "None")) + { + SetOption(null); + } + foreach (string option in keyword.options) + { + if (Gui.Selectable(option, selected == option)) + { + SetOption(option); + } + } + } + finally + { + EditorUI.current.widgets.EndBoundedCombo(); + } + + void SetOption(string? next) + { + if (draft.readOnly) + { + return; + } + foreach (string option in keyword.options) + { + material.SetKeyword(option, option == next); + } + documents.Replace(draft.id, material); + } + } + + MaterialPropertyEntry[] orphaned = material.properties + .Where( + entry => !definition.properties.Any( + property => ( + property.id == entry.id + && IsEditable(property) + && ShaderPropertyInspector.Compatible(property.type, entry.value.kind) + ) + ) + ) + .ToArray(); + if (orphaned.Length != 0) + { + if (EditorUI.current.widgets.SectionHeader( + "Unresolved Overrides", + "These values were retained after an interface change. Remove them explicitly or restore a compatible Shader before publishing." + )) { + foreach (MaterialPropertyEntry entry in orphaned) + { + Gui.Text(entry.id.value + " · " + entry.value.kind); + if (!draft.readOnly && Gui.SmallButton("Remove##" + entry.id.value)) + { + material.ReplaceProperties(material.properties.Where(value => value.id != entry.id).ToArray()); + documents.Replace(draft.id, material); + } + } + } + } + + ShaderPropertyDefinition[] passBindings = definition.properties.Where(property => !IsEditable(property)).ToArray(); + string[] unknownKeywords = material.keywords + .Where(value => !definition.keywords.Any(keyword => keyword.options.Contains(value))) + .ToArray(); + if (unknownKeywords.Length != 0) + { + if (EditorUI.current.widgets.SectionHeader( + "Unresolved Keywords", + "These overrides no longer belong to the Shader interface. They remain until explicitly removed." + )) { + foreach (string keyword in unknownKeywords) + { + Gui.Text(keyword); + if (!draft.readOnly && Gui.SmallButton("Remove##keyword." + keyword)) + { + material.SetKeyword(keyword, false); + documents.Replace(draft.id, material); + } + } + } + } + + if (passBindings.Length != 0) + { + if (EditorUI.current.widgets.SectionHeader( + "Pipeline Bindings", + "These resources are supplied by the Render Pass, not by this Material." + )) { + foreach (ShaderPropertyDefinition property in passBindings) + { + EditorUI.current.widgets.Hint(property.displayName + " · " + property.type + " · " + property.bindingOwner); + } + } + } + } + finally + { + Gui.PopID(); + } + + void Draw( + string path, + string label, + Type type, + Func getter, + Action setter + ) => context.properties.DrawValue( + context.editorContext, + draft, + "material." + path, + label, + type, + getter, + setter, + edits, + draft.readOnly + ); + } + + private static bool IsEditable(ShaderPropertyDefinition property) + => property.bindingOwner == ShaderPropertyBindingOwner.Material + && property.bindingKind is ShaderPropertyBindingKind.Uniform or ShaderPropertyBindingKind.SampledTexture; + + private sealed class DraftEdits( + MaterialDocuments documents, + AssetDraftDocuments.Draft draft, + MaterialAsset material + ) : IInspectionPropertyEditService + { + /// + public bool ChangeProperty( + object owner, + string propertyName, + Action mutation, + string historyName, + string? mergeKey, + string? componentName + ) { + mutation(); + documents.Replace(draft.id, material, mergeKey); + return true; + } + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSourceDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSourceDrawer.cs new file mode 100644 index 000000000..f8b986de4 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Materials/MaterialSourceDrawer.cs @@ -0,0 +1,99 @@ +using System; +using Inno.Assets.Pipeline; +using Inno.Editor.ImGui; +using Inno.Editor.Inspection; + +namespace Inno.Editor.Shaders.ImGui; + +[InspectionDrawer(typeof(AssetFileEntry), priority: 100, conditional: true)] +internal sealed class MaterialSourceDrawer(IInspectionIconProvider icons) : InspectionDrawer +{ + /// + /// Gets the icon glyph used to represent this item in the editor. + /// + public override string icon => ImGuiIcon.C_FILE; + + /// + /// Retrieves the current icon from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated text representation owned by the caller. + /// + protected override string GetIcon( + InspectionDrawContext context, + AssetFileEntry target + ) => icons.GetIcon(target); + + /// + /// Checks whether this drawer supports the selected Inspector target. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// when the documented condition is satisfied; otherwise, . + /// + protected override bool CanInspect(AssetFileEntry target) + => !target.isDirectory && target.extension.Equals(".imaterial", StringComparison.OrdinalIgnoreCase); + + /// + /// Binds a caller-visible label to the current inspection target. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + /// + /// The validated (string name, actionstring? setter) that represents the completed operation. + /// + protected override (string name, Action? setter) BindName( + InspectionDrawContext context, + AssetFileEntry target + ) => (target.nameWithoutExtension, null); + + /// + /// Renders the header presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void DrawHeader( + InspectionDrawContext context, + AssetFileEntry target + ) { + if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) + { + MaterialInspector.DrawHeader(context, documents, documents.OpenDraft(target.assetPath)); + } + } + + /// + /// Renders the value presentation for the current editor frame. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The existing target that receives the validated result. + /// + protected override void Draw( + InspectionDrawContext context, + AssetFileEntry target + ) { + if (context.interactions.TryGetModule(out MaterialDocuments? documents) && documents is not null) + { + MaterialInspector.Draw(context, documents, documents.OpenDraft(target.assetPath)); + } + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawContext.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawContext.cs new file mode 100644 index 000000000..835106669 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawContext.cs @@ -0,0 +1,177 @@ +using System; +using Inno.Core.Graphs; +using Inno.Core.Serialization; +using Inno.Editor.Inspection; +using Inno.Editor.Rendering; +using Inno.Rendering.Shaders; + +namespace Inno.Editor.Shaders.ImGui; + +/// +/// Exposes detached node values and one-gesture writes without exposing the live graph document. +/// +public sealed class ShaderNodeDrawContext +{ + private readonly GraphNodeRecord m_node; + private readonly SerializationRegistry m_serialization; + private readonly SerializationContext m_context; + private readonly Action m_write; + private readonly InspectionDrawContext m_inspection; + private readonly bool m_readOnly; + + /// + /// Creates invocation-scoped access for a graph or Inspector host. + /// + /// + /// Detached node values for this invocation. + /// + /// + /// Current owner converter registry. + /// + /// + /// Complete owner reference context. + /// + /// + /// Host callback recording changes in the shared draft history. + /// + /// + /// Current generation preview service. + /// + /// + /// Shared Inspector context, including native property controls and drag/drop. + /// + /// + /// Whether the source belongs to an immutable installation. + /// + public ShaderNodeDrawContext( + GraphNodeRecord node, + SerializationRegistry serialization, + SerializationContext context, + Action write, + IEditorPreviewService previews, + InspectionDrawContext inspection, + bool readOnly + ) { + m_node = node; + m_serialization = serialization; + m_context = context; + m_write = write; + this.previews = previews; + m_inspection = inspection; + m_readOnly = readOnly; + } + + /// + /// Gets the shared generation-scoped preview service for optional inline texture previews; valid only during this draw. + /// + public IEditorPreviewService previews { get; } + + /// + /// Gets the stable node identity for Editor widget IDs. + /// + public GraphNodeID nodeID => m_node.id; + + /// + /// Reads a detached property value; missing values use the node's declared default. + /// + /// + /// Native serializable property type. + /// + /// + /// Stable node-local property key. + /// + /// + /// Default used only when the property is absent. + /// + /// + /// The detached value. Malformed stored data is not silently replaced. + /// + public T Read( + string key, + T defaultValue + ) => ShaderGraphDocument.Read(m_node, key, defaultValue, m_serialization, m_context); + + /// + /// Records an unsaved draft edit through shared history; only an explicit document save applies it to the asset. + /// + /// + /// Native serializable property type. + /// + /// + /// Stable node-local property key. + /// + /// + /// New detached value. + /// + /// + /// The current shared gesture key, or null for an independent edit. + /// + public void Write( + string key, + T value, + string? mergeKey = null + ) { + if (m_readOnly) + { + throw new InvalidOperationException("Copy this installed Shader into the project before editing."); + } + m_write(key, ShaderGraphDocument.Encode(value, m_serialization, m_context), mergeKey); + } + + /// + /// Draws a node property through the existing Inspector controls, including precise numbers and asset picking. + /// + /// + /// Supported native property type. + /// + /// + /// Stable node property identity. + /// + /// + /// Artist-facing property label. + /// + /// + /// Value used only when no property is stored. + /// + public void DrawProperty( + string key, + string label, + T defaultValue + ) { + T value = Read(key, defaultValue); + m_inspection.properties.DrawValue( + m_inspection.editorContext, + m_node, + "shader.node." + key, + label, + typeof(T), + () => value, + edited => value = (T)edited!, + new Edits(( + mutation, + mergeKey + ) => + { + mutation(); + Write(key, value, mergeKey); + }), + m_readOnly + ); + } + + private sealed class Edits(Action apply) : IInspectionPropertyEditService + { + /// + public bool ChangeProperty( + object owner, + string propertyName, + Action mutation, + string historyName, + string? mergeKey, + string? componentName + ) { + apply(mutation, mergeKey); + return true; + } + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs index fed992189..8e1b2a7aa 100644 --- a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawer.cs @@ -1,133 +1,5 @@ -using System; -using Inno.Core.Graphs; -using Inno.Core.Serialization; -using Inno.Editor.Inspection; -using Inno.Editor.Rendering; -using Inno.Editor.Shaders; -using Inno.Rendering.Shaders; - namespace Inno.Editor.Shaders.ImGui; -/// -/// Registers Editor-only node controls independently from a node's shader compiler. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class ShaderNodeDrawerAttribute : Attribute -{ - /// - /// Associates the drawer with one stable node definition. - /// - /// - /// The compiler-independent graph node identity. - /// - /// - /// Optional artist-facing name used in node headers and creation menus. - /// - /// - /// Optional slash-delimited path below Create. Empty uses the host's built-in classification. - /// - /// - /// Stable ordering value among sibling creation groups and nodes. - /// - /// - /// Whether the contributed creation group is preceded by a separator at its own level. - /// - public ShaderNodeDrawerAttribute( - string definitionID, - string displayName = "", - string createPath = "", - int createOrder = 0, - bool separatorBefore = false - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(definitionID); - ArgumentNullException.ThrowIfNull(displayName); - ArgumentNullException.ThrowIfNull(createPath); - this.definitionID = definitionID; - this.displayName = displayName; - this.createPath = createPath; - this.createOrder = createOrder; - this.separatorBefore = separatorBefore; - } - - /// - /// Gets the stable node identity handled by this drawer. - /// - public string definitionID { get; } - - /// - /// Gets the optional presentation-only name; it does not participate in Shader compilation or identity. - /// - public string displayName { get; } - - /// - /// Gets the optional creation-menu path below Create. - /// - public string createPath { get; } - - /// - /// Gets the creation-menu order. - /// - public int createOrder { get; } - - /// - /// Gets whether the contributed creation group starts a new visual section. - /// - public bool separatorBefore { get; } -} - -/// -/// Immutable authoring presentation contributed for one Shader node definition. -/// -public readonly record struct ShaderNodePresentation -{ - /// - /// Creates presentation metadata for one Shader node definition. - /// - /// - /// Optional artist-facing node name. - /// - /// - /// Optional slash-delimited creation-menu path. - /// - /// - /// Stable ordering value within the creation menu. - /// - /// - /// Whether the contributed group starts a visual section. - /// - public ShaderNodePresentation( - string displayName, - string createPath, - int createOrder, - bool separatorBefore - ) { - this.displayName = displayName; - this.createPath = createPath; - this.createOrder = createOrder; - this.separatorBefore = separatorBefore; - } - - /// - /// Gets the optional artist-facing node name. - /// - public string displayName { get; } - - /// - /// Gets the optional slash-delimited creation-menu path. - /// - public string createPath { get; } - - /// - /// Gets the stable ordering value within the creation menu. - /// - public int createOrder { get; } - - /// - /// Gets whether the contributed group starts a visual section. - /// - public bool separatorBefore { get; } -} - /// /// Provides reloadable Inspector controls; instances must not retain frame contexts or asset objects. /// @@ -141,172 +13,3 @@ public abstract class ShaderNodeDrawer /// public abstract void Draw(ShaderNodeDrawContext context); } - -/// -/// Exposes detached node values and one-gesture writes without exposing the live graph document. -/// -public sealed class ShaderNodeDrawContext -{ - private readonly GraphNodeRecord m_node; - private readonly SerializationRegistry m_serialization; - private readonly SerializationContext m_context; - private readonly Action m_write; - private readonly InspectionDrawContext m_inspection; - private readonly bool m_readOnly; - - /// - /// Creates invocation-scoped access for a graph or Inspector host. - /// - /// - /// Detached node values for this invocation. - /// - /// - /// Current owner converter registry. - /// - /// - /// Complete owner reference context. - /// - /// - /// Host callback recording changes in the shared draft history. - /// - /// - /// Current generation preview service. - /// - /// - /// Shared Inspector context, including native property controls and drag/drop. - /// - /// - /// Whether the source belongs to an immutable installation. - /// - public ShaderNodeDrawContext( - GraphNodeRecord node, - SerializationRegistry serialization, - SerializationContext context, - Action write, - IEditorPreviewService previews, - InspectionDrawContext inspection, - bool readOnly - ) { - m_node = node; - m_serialization = serialization; - m_context = context; - m_write = write; - this.previews = previews; - m_inspection = inspection; - m_readOnly = readOnly; - } - - /// - /// Gets the shared generation-scoped preview service for optional inline texture previews; valid only during this draw. - /// - public IEditorPreviewService previews { get; } - - /// - /// Gets the stable node identity for Editor widget IDs. - /// - public GraphNodeID nodeID => m_node.id; - - /// - /// Reads a detached property value; missing values use the node's declared default. - /// - /// - /// Native serializable property type. - /// - /// - /// Stable node-local property key. - /// - /// - /// Default used only when the property is absent. - /// - /// - /// The detached value. Malformed stored data is not silently replaced. - /// - public T Read( - string key, - T defaultValue - ) => ShaderGraphDocument.Read(m_node, key, defaultValue, m_serialization, m_context); - - /// - /// Records an unsaved draft edit through shared history; only an explicit document save applies it to the asset. - /// - /// - /// Native serializable property type. - /// - /// - /// Stable node-local property key. - /// - /// - /// New detached value. - /// - /// - /// The current shared gesture key, or null for an independent edit. - /// - public void Write( - string key, - T value, - string? mergeKey = null - ) { - if (m_readOnly) - { - throw new InvalidOperationException("Copy this installed Shader into the project before editing."); - } - m_write(key, ShaderGraphDocument.Encode(value, m_serialization, m_context), mergeKey); - } - - /// - /// Draws a node property through the existing Inspector controls, including precise numbers and asset picking. - /// - /// - /// Supported native property type. - /// - /// - /// Stable node property identity. - /// - /// - /// Artist-facing property label. - /// - /// - /// Value used only when no property is stored. - /// - public void DrawProperty( - string key, - string label, - T defaultValue - ) { - T value = Read(key, defaultValue); - m_inspection.properties.DrawValue( - m_inspection.editorContext, - m_node, - "shader.node." + key, - label, - typeof(T), - () => value, - edited => value = (T)edited!, - new Edits(( - mutation, - mergeKey - ) => - { - mutation(); - Write(key, value, mergeKey); - }), - m_readOnly - ); - } - - private sealed class Edits(Action apply) : IInspectionPropertyEditService - { - /// - public bool ChangeProperty( - object owner, - string propertyName, - Action mutation, - string historyName, - string? mergeKey, - string? componentName - ) { - apply(mutation, mergeKey); - return true; - } - } -} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerAttribute.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerAttribute.cs new file mode 100644 index 000000000..071cdf4ea --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodeDrawerAttribute.cs @@ -0,0 +1,70 @@ +using System; + +namespace Inno.Editor.Shaders.ImGui; + +/// +/// Registers Editor-only node controls independently from a node's shader compiler. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class ShaderNodeDrawerAttribute : Attribute +{ + /// + /// Associates the drawer with one stable node definition. + /// + /// + /// The compiler-independent graph node identity. + /// + /// + /// Optional artist-facing name used in node headers and creation menus. + /// + /// + /// Optional slash-delimited path below Create. Empty uses the host's built-in classification. + /// + /// + /// Stable ordering value among sibling creation groups and nodes. + /// + /// + /// Whether the contributed creation group is preceded by a separator at its own level. + /// + public ShaderNodeDrawerAttribute( + string definitionID, + string displayName = "", + string createPath = "", + int createOrder = 0, + bool separatorBefore = false + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(definitionID); + ArgumentNullException.ThrowIfNull(displayName); + ArgumentNullException.ThrowIfNull(createPath); + this.definitionID = definitionID; + this.displayName = displayName; + this.createPath = createPath; + this.createOrder = createOrder; + this.separatorBefore = separatorBefore; + } + + /// + /// Gets the stable node identity handled by this drawer. + /// + public string definitionID { get; } + + /// + /// Gets the optional presentation-only name; it does not participate in Shader compilation or identity. + /// + public string displayName { get; } + + /// + /// Gets the optional creation-menu path below Create. + /// + public string createPath { get; } + + /// + /// Gets the creation-menu order. + /// + public int createOrder { get; } + + /// + /// Gets whether the contributed creation group starts a new visual section. + /// + public bool separatorBefore { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodePresentation.cs b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodePresentation.cs new file mode 100644 index 000000000..a42b3cf36 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Shaders.ImGui/Nodes/ShaderNodePresentation.cs @@ -0,0 +1,54 @@ +namespace Inno.Editor.Shaders.ImGui; + +/// +/// Immutable authoring presentation contributed for one Shader node definition. +/// +public readonly record struct ShaderNodePresentation +{ + /// + /// Creates presentation metadata for one Shader node definition. + /// + /// + /// Optional artist-facing node name. + /// + /// + /// Optional slash-delimited creation-menu path. + /// + /// + /// Stable ordering value within the creation menu. + /// + /// + /// Whether the contributed group starts a visual section. + /// + public ShaderNodePresentation( + string displayName, + string createPath, + int createOrder, + bool separatorBefore + ) { + this.displayName = displayName; + this.createPath = createPath; + this.createOrder = createOrder; + this.separatorBefore = separatorBefore; + } + + /// + /// Gets the optional artist-facing node name. + /// + public string displayName { get; } + + /// + /// Gets the optional slash-delimited creation-menu path. + /// + public string createPath { get; } + + /// + /// Gets the stable ordering value within the creation menu. + /// + public int createOrder { get; } + + /// + /// Gets whether the contributed group starts a visual section. + /// + public bool separatorBefore { get; } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/ClearEditorSelectionAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/ClearEditorSelectionAction.cs new file mode 100644 index 000000000..5fd47220b --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/ClearEditorSelectionAction.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +[EditorAction(GlobalInteractionIDs.C_CLEAR_SELECTION)] +internal sealed class ClearEditorSelectionAction : EditorAction +{ + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => context.interactions.SetSelection(null); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/HistoryActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/RedoEditorAction.cs similarity index 52% rename from src/composition/editor/presentation/Inno.Editor.Workbench/Actions/HistoryActions.cs rename to src/composition/editor/presentation/Inno.Editor.Workbench/Actions/RedoEditorAction.cs index be491f07a..2e9c27937 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/HistoryActions.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/RedoEditorAction.cs @@ -3,37 +3,6 @@ namespace Inno.Editor.Workbench; -[EditorAction(GlobalInteractionIDs.C_UNDO, priority: 1000)] -[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "Edit/Undo", order: 100)] -[EditorShortcut(KeyCode.Z, primary: true)] -internal sealed class UndoEditorAction : EditorAction -{ - /// - /// Evaluates whether the requested change can be applied to the current generation. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - => new( - isVisible: true, - isEnabled: context.history.canUndo, - displayName: context.history.undoName is { } name ? $"Undo {name}" : "Undo", - unavailableReason: context.history.undoUnavailableReason - ); - - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => _ = context.history.Undo(); -} - [EditorAction(GlobalInteractionIDs.C_REDO, priority: 1000)] [EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "Edit/Redo", order: 110)] [EditorShortcut(KeyCode.Z, KeyModifier.Shift, primary: true)] diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectionActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectEditorTargetAction.cs similarity index 53% rename from src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectionActions.cs rename to src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectEditorTargetAction.cs index 99286fe74..3535d3b61 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectionActions.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/SelectEditorTargetAction.cs @@ -2,18 +2,6 @@ namespace Inno.Editor.Workbench; -[EditorAction(GlobalInteractionIDs.C_CLEAR_SELECTION)] -internal sealed class ClearEditorSelectionAction : EditorAction -{ - /// - /// Executes the prepared operation and publishes only a completed result. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - protected override void Execute(EditorActionContext context) => context.interactions.SetSelection(null); -} - [EditorAction(GlobalInteractionIDs.C_SELECT)] internal sealed class SelectEditorTargetAction : EditorAction { diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/UndoEditorAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/UndoEditorAction.cs new file mode 100644 index 000000000..30aa47bfe --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Actions/UndoEditorAction.cs @@ -0,0 +1,35 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +[EditorAction(GlobalInteractionIDs.C_UNDO, priority: 1000)] +[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "Edit/Undo", order: 100)] +[EditorShortcut(KeyCode.Z, primary: true)] +internal sealed class UndoEditorAction : EditorAction +{ + /// + /// Evaluates whether the requested change can be applied to the current generation. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => new( + isVisible: true, + isEnabled: context.history.canUndo, + displayName: context.history.undoName is { } name ? $"Undo {name}" : "Undo", + unavailableReason: context.history.undoUnavailableReason + ); + + /// + /// Executes the prepared operation and publishes only a completed result. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + protected override void Execute(EditorActionContext context) => _ = context.history.Undo(); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportGameAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportGameAction.cs new file mode 100644 index 000000000..8a4c7cbe7 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportGameAction.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +[EditorAction(ExportInteractionIDs.C_EXPORT_GAME)] +[EditorMenu(ExportInteractionIDs.C_MAIN_MENU_AREA, "File/Export as Game...", order: 810)] +internal sealed class ExportGameAction(ExportWindowModule window) : EditorAction +{ + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) => window.OpenGame(); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportPluginAction.cs similarity index 54% rename from src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportActions.cs rename to src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportPluginAction.cs index 05ce4dba9..73f6f937a 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportActions.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Exporting/ExportPluginAction.cs @@ -14,16 +14,3 @@ internal sealed class ExportPluginAction(ExportWindowModule window) : EditorActi /// protected override void Execute(EditorActionContext context) => window.OpenPlugin(); } - -[EditorAction(ExportInteractionIDs.C_EXPORT_GAME)] -[EditorMenu(ExportInteractionIDs.C_MAIN_MENU_AREA, "File/Export as Game...", order: 810)] -internal sealed class ExportGameAction(ExportWindowModule window) : EditorAction -{ - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => window.OpenGame(); -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/AppearanceSettingsPage.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/AppearanceSettingsPage.cs new file mode 100644 index 000000000..941f3638e --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/AppearanceSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance")] +internal sealed class AppearanceSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Customize editor appearance, scaling, and semantic presentation."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorFramePacingModule.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorFramePacingModule.cs new file mode 100644 index 000000000..7fefd2f32 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorFramePacingModule.cs @@ -0,0 +1,41 @@ +using System; +using Inno.Editor.Core; +using Inno.Editor.Settings; +using Inno.Platform; + +namespace Inno.Editor.Workbench; + +[EditorModule("editor-frame-pacing", order: 20)] +internal sealed class EditorFramePacingModule( + EditorSettings settings, + FramePacingOptions pacing +) : EditorModule +{ + private IDisposable? m_settingsSubscription; + + /// + /// Initializes this feature when its owning runtime becomes active. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void OnStart(EditorContext context) + { + Apply(settings); + m_settingsSubscription = settings.ListenChanges(Apply); + } + + /// + /// Stops this feature before its owning runtime releases the active generation. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void OnStop(EditorContext context) => m_settingsSubscription?.Dispose(); + + private void Apply(EditorSettings current) + { + pacing.verticalSync = current.Get("Editor/Rendering/Vertical Sync").GetAsBoolean("enabled", false); + pacing.maximumFrameRate = Math.Clamp(current.Get("Editor/Rendering/Maximum Frame Rate").GetAsInt32("value", 0), 0, 1000); + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorRenderingSettingsPage.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorRenderingSettingsPage.cs new file mode 100644 index 000000000..9ad2fc917 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/EditorRenderingSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Rendering")] +internal sealed class EditorRenderingSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Control editor presentation independently of game simulation timing."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FileIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FileIconSetting.cs new file mode 100644 index 000000000..496120ccb --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FileIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/File")] +internal sealed class FileIconSetting() : IconSetting(ImGuiIcon.C_FILE) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a generic source file."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FolderIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FolderIconSetting.cs new file mode 100644 index 000000000..89a1197e4 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FolderIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Folder")] +internal sealed class FolderIconSetting() : IconSetting(ImGuiIcon.C_FOLDER) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a source directory."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs deleted file mode 100644 index d81b22c1c..000000000 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/FramePacingSettings.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using Inno.Editor.Core; -using Inno.Editor.ImGui; -using Inno.Editor.Settings; -using Inno.Platform; - -using EditorUI = Inno.Editor.ImGui.EditorUISession; -using Gui = Inno.Editor.ImGui.ImGui; - -namespace Inno.Editor.Workbench; - -[EditorSettingPath("Editor/Rendering")] -internal sealed class EditorRenderingSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Control editor presentation independently of game simulation timing."; -} - -[EditorSettingPath("Editor/Rendering/Vertical Sync", order: 10)] -internal sealed class VerticalSyncSetting : EditorSetting -{ - /// - /// Gets a new value initialized to this setting's canonical default state. - /// - public override EditorSettingObject defaultValue - { - get - { - var result = new EditorSettingObject(); - result.SetAsBoolean("enabled", false); - return result; - } - } - - /// - /// Gets the presentation section that groups this setting. - /// - public override string section => "Frame Rate"; - - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Synchronize presentation to the display refresh rate. Disable to allow higher frame rates."; - - /// - /// Draws this feature using the current editor presentation context. - /// - /// - /// The mutable editor setting value currently being presented. - /// - protected override void OnDraw(EditorSettingObject setting) - { - bool enabled = setting.GetAsBoolean("enabled", false); - if (Gui.Checkbox("##vsync", ref enabled)) - { - setting.SetAsBoolean("enabled", enabled); - } - } -} - -[EditorSettingPath("Editor/Rendering/Maximum Frame Rate", order: 20)] -internal sealed class MaximumFrameRateSetting : EditorSetting -{ - /// - /// Gets a new value initialized to this setting's canonical default state. - /// - public override EditorSettingObject defaultValue - { - get - { - var result = new EditorSettingObject(); - result.SetAsInt32("value", 0); - return result; - } - } - - /// - /// Gets the presentation section that groups this setting. - /// - public override string section => "Frame Rate"; - - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Software frame-rate limit. Zero means Unlimited. Fixed-step simulation is unaffected."; - - /// - /// Draws this feature using the current editor presentation context. - /// - /// - /// The mutable editor setting value currently being presented. - /// - protected override void OnDraw(EditorSettingObject setting) - { - int rate = setting.GetAsInt32("value", 0); - if (Gui.InputInt("##maximum_fps", ref rate, 1, 100, 0)) - { - setting.SetAsInt32("value", Math.Clamp(rate, 0, 1000)); - } - if (rate == 0) - { - EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Unlimited"); - } - } -} - -[EditorModule("editor-frame-pacing", order: 20)] -internal sealed class EditorFramePacingModule( - EditorSettings settings, - FramePacingOptions pacing -) : EditorModule -{ - private IDisposable? m_settingsSubscription; - - /// - /// Initializes this feature when its owning runtime becomes active. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void OnStart(EditorContext context) - { - Apply(settings); - m_settingsSubscription = settings.ListenChanges(Apply); - } - - /// - /// Stops this feature before its owning runtime releases the active generation. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void OnStop(EditorContext context) => m_settingsSubscription?.Dispose(); - - private void Apply(EditorSettings current) - { - pacing.verticalSync = current.Get("Editor/Rendering/Vertical Sync").GetAsBoolean("enabled", false); - pacing.maximumFrameRate = Math.Clamp(current.Get("Editor/Rendering/Maximum Frame Rate").GetAsInt32("value", 0), 0, 1000); - } -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GameObjectIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GameObjectIconSetting.cs new file mode 100644 index 000000000..a7774e651 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GameObjectIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/GameObject")] +internal sealed class GameObjectIconSetting() : IconSetting(ImGuiIcon.C_CUBE) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a scene GameObject."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPage.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPage.cs new file mode 100644 index 000000000..4fe179c92 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor")] +internal sealed class GlobalSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Configure editor-wide appearance, behavior, and user-facing tools."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs deleted file mode 100644 index 6e6249528..000000000 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/GlobalSettingsPages.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Inno.Editor.Settings; - -namespace Inno.Editor.Workbench; - -[EditorSettingPath("Editor")] -internal sealed class GlobalSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Configure editor-wide appearance, behavior, and user-facing tools."; -} - -[EditorSettingPath("Editor/Appearance")] -internal sealed class AppearanceSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Customize editor appearance, scaling, and semantic presentation."; -} - -[EditorSettingPath("Editor/Appearance/Icons")] -internal sealed class IconSettingsPage : EditorSetting -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Choose the glyph used for each semantic object throughout the editor."; -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSetting.cs similarity index 56% rename from src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs rename to src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSetting.cs index 4edf61f5b..0d8788248 100644 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettings.cs +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSetting.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Numerics; using Inno.Editor.ImGui; -using Inno.Editor.ImGui.ImGuiWidget; using Inno.Editor.Settings; using EditorUI = Inno.Editor.ImGui.EditorUISession; @@ -142,94 +140,3 @@ float iconSlotWidth Gui.DrawText(new Vector2(origin.X + iconSlotWidth + style.itemInnerSpacing.X, origin.Y), color, text); } } - -[EditorSettingPath("Editor/Appearance/Icons/Scene")] -internal sealed class SceneIconSetting() : IconSetting(ImGuiIcon.C_CUBES) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a scene document or loaded scene."; -} - -[EditorSettingPath("Editor/Appearance/Icons/GameObject")] -internal sealed class GameObjectIconSetting() : IconSetting(ImGuiIcon.C_CUBE) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a scene GameObject."; -} - -[EditorSettingPath("Editor/Appearance/Icons/Prefab")] -internal sealed class PrefabIconSetting() : IconSetting(ImGuiIcon.C_DICE_D_6) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a reusable prefab object."; -} - -[EditorSettingPath("Editor/Appearance/Icons/Layers")] -internal sealed class LayersIconSetting() : IconSetting(ImGuiIcon.C_LAYER_GROUP) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a project layer configuration."; -} - -[EditorSettingPath("Editor/Appearance/Icons/Folder")] -internal sealed class FolderIconSetting() : IconSetting(ImGuiIcon.C_FOLDER) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a source directory."; -} - -[EditorSettingPath("Editor/Appearance/Icons/File")] -internal sealed class FileIconSetting() : IconSetting(ImGuiIcon.C_FILE) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used wherever the editor presents a generic source file."; -} - -[EditorSettingPath("Editor/Appearance/Icons/Shader")] -internal sealed class ShaderIconSetting() : IconSetting(ImGuiIcon.C_SHADER) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used consistently for Shader graph assets and their Inspector headers."; -} - -[EditorSettingPath("Editor/Appearance/Icons/ShaderSource")] -internal sealed class ShaderSourceIconSetting() : IconSetting(ImGuiIcon.C_RUPEE_SIGN) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description - => "Selects the icon used consistently for Shader source-function libraries. The default function symbol distinguishes reusable code from complete Shader graphs."; -} - -[EditorSettingPath("Editor/Appearance/Icons/Material")] -internal sealed class MaterialIconSetting() : IconSetting(ImGuiIcon.C_PALETTE) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used consistently for Material assets and their Inspector headers."; -} - -[EditorSettingPath("Editor/Appearance/Icons/RenderPipeline")] -internal sealed class RenderPipelineIconSetting() : IconSetting(ImGuiIcon.C_RUPIAH_SIGN) -{ - /// - /// Gets the user-facing explanation of this feature or setting. - /// - public override string description => "Selects the icon used consistently for Render Pipeline assets and their Inspector headers."; -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettingsPage.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettingsPage.cs new file mode 100644 index 000000000..3cc555388 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/IconSettingsPage.cs @@ -0,0 +1,12 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons")] +internal sealed class IconSettingsPage : EditorSetting +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Choose the glyph used for each semantic object throughout the editor."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/LayersIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/LayersIconSetting.cs new file mode 100644 index 000000000..2ee0d74a5 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/LayersIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Layers")] +internal sealed class LayersIconSetting() : IconSetting(ImGuiIcon.C_LAYER_GROUP) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a project layer configuration."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaterialIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaterialIconSetting.cs new file mode 100644 index 000000000..658e905a5 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaterialIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Material")] +internal sealed class MaterialIconSetting() : IconSetting(ImGuiIcon.C_PALETTE) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used consistently for Material assets and their Inspector headers."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaximumFrameRateSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaximumFrameRateSetting.cs new file mode 100644 index 000000000..bed2a4ea5 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/MaximumFrameRateSetting.cs @@ -0,0 +1,54 @@ +using System; +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +using EditorUI = Inno.Editor.ImGui.EditorUISession; +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Rendering/Maximum Frame Rate", order: 20)] +internal sealed class MaximumFrameRateSetting : EditorSetting +{ + /// + /// Gets a new value initialized to this setting's canonical default state. + /// + public override EditorSettingObject defaultValue + { + get + { + var result = new EditorSettingObject(); + result.SetAsInt32("value", 0); + return result; + } + } + + /// + /// Gets the presentation section that groups this setting. + /// + public override string section => "Frame Rate"; + + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Software frame-rate limit. Zero means Unlimited. Fixed-step simulation is unaffected."; + + /// + /// Draws this feature using the current editor presentation context. + /// + /// + /// The mutable editor setting value currently being presented. + /// + protected override void OnDraw(EditorSettingObject setting) + { + int rate = setting.GetAsInt32("value", 0); + if (Gui.InputInt("##maximum_fps", ref rate, 1, 100, 0)) + { + setting.SetAsInt32("value", Math.Clamp(rate, 0, 1000)); + } + if (rate == 0) + { + EditorUI.current.widgets.ColoredText(EditorPalette.textDisabled, "Unlimited"); + } + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/PrefabIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/PrefabIconSetting.cs new file mode 100644 index 000000000..3101c7d17 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/PrefabIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Prefab")] +internal sealed class PrefabIconSetting() : IconSetting(ImGuiIcon.C_DICE_D_6) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a reusable prefab object."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/RenderPipelineIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/RenderPipelineIconSetting.cs new file mode 100644 index 000000000..9da26e959 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/RenderPipelineIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/RenderPipeline")] +internal sealed class RenderPipelineIconSetting() : IconSetting(ImGuiIcon.C_RUPIAH_SIGN) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used consistently for Render Pipeline assets and their Inspector headers."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/SceneIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/SceneIconSetting.cs new file mode 100644 index 000000000..e17d7677f --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/SceneIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Scene")] +internal sealed class SceneIconSetting() : IconSetting(ImGuiIcon.C_CUBES) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used wherever the editor presents a scene document or loaded scene."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderIconSetting.cs new file mode 100644 index 000000000..679b03d30 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderIconSetting.cs @@ -0,0 +1,13 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/Shader")] +internal sealed class ShaderIconSetting() : IconSetting(ImGuiIcon.C_SHADER) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Selects the icon used consistently for Shader graph assets and their Inspector headers."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderSourceIconSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderSourceIconSetting.cs new file mode 100644 index 000000000..f0acc497f --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/ShaderSourceIconSetting.cs @@ -0,0 +1,14 @@ +using Inno.Editor.ImGui; +using Inno.Editor.Settings; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Appearance/Icons/ShaderSource")] +internal sealed class ShaderSourceIconSetting() : IconSetting(ImGuiIcon.C_RUPEE_SIGN) +{ + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description + => "Selects the icon used consistently for Shader source-function libraries. The default function symbol distinguishes reusable code from complete Shader graphs."; +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/VerticalSyncSetting.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/VerticalSyncSetting.cs new file mode 100644 index 000000000..60751f0df --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Settings/VerticalSyncSetting.cs @@ -0,0 +1,47 @@ +using Inno.Editor.Settings; + +using Gui = Inno.Editor.ImGui.ImGui; + +namespace Inno.Editor.Workbench; + +[EditorSettingPath("Editor/Rendering/Vertical Sync", order: 10)] +internal sealed class VerticalSyncSetting : EditorSetting +{ + /// + /// Gets a new value initialized to this setting's canonical default state. + /// + public override EditorSettingObject defaultValue + { + get + { + var result = new EditorSettingObject(); + result.SetAsBoolean("enabled", false); + return result; + } + } + + /// + /// Gets the presentation section that groups this setting. + /// + public override string section => "Frame Rate"; + + /// + /// Gets the user-facing explanation of this feature or setting. + /// + public override string description => "Synchronize presentation to the display refresh rate. Disable to allow higher frame rates."; + + /// + /// Draws this feature using the current editor presentation context. + /// + /// + /// The mutable editor setting value currently being presented. + /// + protected override void OnDraw(EditorSettingObject setting) + { + bool enabled = setting.GetAsBoolean("enabled", false); + if (Gui.Checkbox("##vsync", ref enabled)) + { + setting.SetAsBoolean("enabled", enabled); + } + } +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeEditorAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeEditorAction.cs new file mode 100644 index 000000000..6ffb300c0 --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ActualSizeEditorAction.cs @@ -0,0 +1,36 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +/// +/// Restores UI zoom to the configured actual size. +/// +/// +/// The zoom used to initialize this instance. +/// +[EditorAction(GlobalInteractionIDs.C_ZOOM_RESET)] +[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "View/Actual Size", order: 120)] +[EditorShortcut(KeyCode.D0, primary: true)] +internal sealed class ActualSizeEditorAction(EditorZoomModule zoom) : EditorAction +{ + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => zoom.isActualSize ? EditorActionState.disabled : EditorActionState.enabled; + + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) => _ = zoom.UseActualSize(); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs deleted file mode 100644 index 64edd2573..000000000 --- a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomActions.cs +++ /dev/null @@ -1,100 +0,0 @@ -using Inno.Core.Input; -using Inno.Editor.Interactions; - -namespace Inno.Editor.Workbench; - -/// -/// Increases UI zoom by one multiple of the configured actual size. -/// -/// -/// The zoom used to initialize this instance. -/// -[EditorAction(GlobalInteractionIDs.C_ZOOM_IN)] -[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "View/Zoom In", order: 100)] -[EditorShortcut(KeyCode.Plus, primary: true)] -internal sealed class ZoomInEditorAction(EditorZoomModule zoom) : EditorAction -{ - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - => zoom.canZoomIn ? EditorActionState.enabled : EditorActionState.disabled; - - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => _ = zoom.ZoomIn(); -} - -/// -/// Decreases UI zoom by one multiple of the configured actual size. -/// -/// -/// The zoom used to initialize this instance. -/// -[EditorAction(GlobalInteractionIDs.C_ZOOM_OUT)] -[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "View/Zoom Out", order: 110)] -[EditorShortcut(KeyCode.Minus, primary: true)] -internal sealed class ZoomOutEditorAction(EditorZoomModule zoom) : EditorAction -{ - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - => zoom.canZoomOut ? EditorActionState.enabled : EditorActionState.disabled; - - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => _ = zoom.ZoomOut(); -} - -/// -/// Restores UI zoom to the configured actual size. -/// -/// -/// The zoom used to initialize this instance. -/// -[EditorAction(GlobalInteractionIDs.C_ZOOM_RESET)] -[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "View/Actual Size", order: 120)] -[EditorShortcut(KeyCode.D0, primary: true)] -internal sealed class ActualSizeEditorAction(EditorZoomModule zoom) : EditorAction -{ - /// - /// Evaluates the operation's current availability and presentation state. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated editor action state that represents the completed operation. - /// - protected override EditorActionState Query(EditorActionContext context) - => zoom.isActualSize ? EditorActionState.disabled : EditorActionState.enabled; - - /// - /// Applies the editor action to the supplied interaction context. - /// - /// - /// The context that supplies state and services for this operation. - /// - protected override void Execute(EditorActionContext context) => _ = zoom.UseActualSize(); -} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomInEditorAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomInEditorAction.cs new file mode 100644 index 000000000..ad959c7cb --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomInEditorAction.cs @@ -0,0 +1,36 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +/// +/// Increases UI zoom by one multiple of the configured actual size. +/// +/// +/// The zoom used to initialize this instance. +/// +[EditorAction(GlobalInteractionIDs.C_ZOOM_IN)] +[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "View/Zoom In", order: 100)] +[EditorShortcut(KeyCode.Plus, primary: true)] +internal sealed class ZoomInEditorAction(EditorZoomModule zoom) : EditorAction +{ + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => zoom.canZoomIn ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) => _ = zoom.ZoomIn(); +} diff --git a/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomOutEditorAction.cs b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomOutEditorAction.cs new file mode 100644 index 000000000..c1404ec2d --- /dev/null +++ b/src/composition/editor/presentation/Inno.Editor.Workbench/Zoom/ZoomOutEditorAction.cs @@ -0,0 +1,36 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Workbench; + +/// +/// Decreases UI zoom by one multiple of the configured actual size. +/// +/// +/// The zoom used to initialize this instance. +/// +[EditorAction(GlobalInteractionIDs.C_ZOOM_OUT)] +[EditorMenu(GlobalInteractionIDs.C_MAIN_MENU_AREA, "View/Zoom Out", order: 110)] +[EditorShortcut(KeyCode.Minus, primary: true)] +internal sealed class ZoomOutEditorAction(EditorZoomModule zoom) : EditorAction +{ + /// + /// Evaluates the operation's current availability and presentation state. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated editor action state that represents the completed operation. + /// + protected override EditorActionState Query(EditorActionContext context) + => zoom.canZoomOut ? EditorActionState.enabled : EditorActionState.disabled; + + /// + /// Applies the editor action to the supplied interaction context. + /// + /// + /// The context that supplies state and services for this operation. + /// + protected override void Execute(EditorActionContext context) => _ = zoom.ZoomOut(); +} diff --git a/src/content/animation/Inno.Animation/Animation.cs b/src/content/animation/Inno.Animation/Animation.cs index b7b99b01e..fa894f654 100644 --- a/src/content/animation/Inno.Animation/Animation.cs +++ b/src/content/animation/Inno.Animation/Animation.cs @@ -1,37 +1,5 @@ -using System; -using System.Threading; -using Inno.Core.Execution; - namespace Inno.Animation; -/// -/// Binds one animation service to the current asynchronous execution context. -/// -public static class AnimationExecutionContext -{ - private static readonly ExecutionSlot CURRENT_SCOPE = new("animation"); - - /// - /// Gets the animation service bound to the current execution context. - /// - public static IAnimationService current => CURRENT_SCOPE.current; - - /// - /// Binds one animation service until the returned strict scope is disposed. - /// - /// - /// Session-owned animation service. - /// - /// - /// A strict last-in-first-out execution scope. - /// - public static IDisposable EnterScope(IAnimationService animation) - { - ArgumentNullException.ThrowIfNull(animation); - return CURRENT_SCOPE.Enter(animation); - } -} - /// /// Provides script-friendly animation control through the current runtime context. /// diff --git a/src/content/animation/Inno.Animation/AnimationBindingID.cs b/src/content/animation/Inno.Animation/AnimationBindingID.cs new file mode 100644 index 000000000..c96639229 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationBindingID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Animation; + +/// +/// Identifies one backend-neutral value destination inside an animation binding scope. +/// +public readonly record struct AnimationBindingID +{ + /// + /// Creates a stable animation binding identifier. + /// + /// + /// The non-empty binding protocol value. + /// + public AnimationBindingID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the stable binding protocol value. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this identifier for diagnostics and persistence. + /// + /// + /// The protocol value, or an empty string for an uninitialized identifier. + /// + public override string ToString() => value ?? string.Empty; +} diff --git a/src/content/animation/Inno.Animation/AnimationClipAsset.cs b/src/content/animation/Inno.Animation/AnimationClipAsset.cs index 5d36a51e4..223e70a04 100644 --- a/src/content/animation/Inno.Animation/AnimationClipAsset.cs +++ b/src/content/animation/Inno.Animation/AnimationClipAsset.cs @@ -1,153 +1,11 @@ using System; using System.Collections.Generic; -using System.Linq; using Inno.Assets; using Inno.Core.Serialization; using Inno.Extensibility.Types; namespace Inno.Animation; -/// -/// Stores one timestamped value inside an animation track. -/// -public struct AnimationKeyframe -{ - /// - /// Creates one animation keyframe. - /// - /// - /// Non-negative clip-local time in seconds. - /// - /// - /// Value sampled at the keyframe time. - /// - public AnimationKeyframe( - float time, - AnimationValue value - ) { - if (!float.IsFinite(time) || time < 0f) - { - throw new ArgumentOutOfRangeException(nameof(time)); - } - this.time = time; - this.value = value; - } - - /// - /// Gets or sets clip-local time in seconds. - /// - [SerializableProperty] - public float time { get; set; } - - /// - /// Gets or sets the sampled value. - /// - [SerializableProperty] - public AnimationValue value { get; set; } -} - -/// -/// Stores one ordered value track targeting a stable binding. -/// -public sealed class AnimationTrack : ISerializable -{ - /// - /// Creates an empty track for structured deserialization. - /// - public AnimationTrack() {} - - /// - /// Creates one validated animation track. - /// - /// - /// Stable target binding identifier. - /// - /// - /// Sampling rule between adjacent keyframes. - /// - /// - /// Keyframes ordered by non-decreasing clip-local time. - /// - public AnimationTrack( - string bindingID, - AnimationInterpolation interpolation, - IEnumerable keyframes - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(bindingID); - ArgumentNullException.ThrowIfNull(keyframes); - this.bindingId = bindingID; - this.interpolation = interpolation; - this.keyframes = keyframes.ToArray(); - Validate(float.PositiveInfinity); - } - - /// - /// Gets or sets the stable target binding identifier. - /// - [SerializableProperty] - public string bindingId { get; set; } = string.Empty; - - /// - /// Gets or sets the sampling rule between adjacent keyframes. - /// - [SerializableProperty] - public AnimationInterpolation interpolation { get; set; } - - /// - /// Gets or sets ordered keyframes. - /// - [SerializableProperty] - public AnimationKeyframe[] keyframes { get; set; } = []; - - internal void Validate(float duration) - { - ArgumentException.ThrowIfNullOrWhiteSpace(bindingId); - if (keyframes is null || keyframes.Length == 0) - { - throw new InvalidOperationException($"Animation track '{bindingId}' requires at least one keyframe."); - } - AnimationValueKind kind = keyframes[0].value.kind; - float previous = -1f; - for (int index = 0; index < keyframes.Length; index++) - { - AnimationKeyframe keyframe = keyframes[index]; - if (!float.IsFinite(keyframe.time) || keyframe.time < previous || keyframe.time > duration) - { - throw new InvalidOperationException($"Animation track '{bindingId}' contains invalid keyframe times."); - } - if (keyframe.value.kind != kind) - { - throw new InvalidOperationException($"Animation track '{bindingId}' mixes incompatible value kinds."); - } - previous = keyframe.time; - } - } -} - -/// -/// Stores one stable event marker embedded in an animation clip. -/// -public sealed class AnimationEventMarker : ISerializable -{ - /// - /// Gets or sets clip-local marker time in seconds. - /// - [SerializableProperty] - public float time { get; set; } - - /// - /// Gets or sets the stable event protocol identifier. - /// - [SerializableProperty] - public string eventId { get; set; } = string.Empty; - - /// - /// Gets or sets opaque reload-safe event payload bytes. - /// - [SerializableProperty] - public byte[] payload { get; set; } = []; -} - /// /// Represents one imported backend-neutral collection of tracks and event markers. /// diff --git a/src/content/animation/Inno.Animation/AnimationClock.cs b/src/content/animation/Inno.Animation/AnimationClock.cs new file mode 100644 index 000000000..14b81258f --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationClock.cs @@ -0,0 +1,16 @@ +namespace Inno.Animation; + +/// +/// Selects the session clock used to advance an animation playback. +/// +public enum AnimationClock +{ + /// + /// Uses scaled simulation time and stops while the session is paused. + /// + Scaled, + /// + /// Uses unscaled session time and continues while simulation is paused. + /// + Unscaled +} diff --git a/src/content/animation/Inno.Animation/AnimationEventMarker.cs b/src/content/animation/Inno.Animation/AnimationEventMarker.cs new file mode 100644 index 000000000..21c91bb3c --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationEventMarker.cs @@ -0,0 +1,27 @@ +using Inno.Core.Serialization; + +namespace Inno.Animation; + +/// +/// Stores one stable event marker embedded in an animation clip. +/// +public sealed class AnimationEventMarker : ISerializable +{ + /// + /// Gets or sets clip-local marker time in seconds. + /// + [SerializableProperty] + public float time { get; set; } + + /// + /// Gets or sets the stable event protocol identifier. + /// + [SerializableProperty] + public string eventId { get; set; } = string.Empty; + + /// + /// Gets or sets opaque reload-safe event payload bytes. + /// + [SerializableProperty] + public byte[] payload { get; set; } = []; +} diff --git a/src/content/animation/Inno.Animation/AnimationExecutionContext.cs b/src/content/animation/Inno.Animation/AnimationExecutionContext.cs new file mode 100644 index 000000000..ee535bdb5 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationExecutionContext.cs @@ -0,0 +1,32 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Animation; + +/// +/// Binds one animation service to the current asynchronous execution context. +/// +public static class AnimationExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("animation"); + + /// + /// Gets the animation service bound to the current execution context. + /// + public static IAnimationService current => CURRENT_SCOPE.current; + + /// + /// Binds one animation service until the returned strict scope is disposed. + /// + /// + /// Session-owned animation service. + /// + /// + /// A strict last-in-first-out execution scope. + /// + public static IDisposable EnterScope(IAnimationService animation) + { + ArgumentNullException.ThrowIfNull(animation); + return CURRENT_SCOPE.Enter(animation); + } +} diff --git a/src/content/animation/Inno.Animation/AnimationInterpolation.cs b/src/content/animation/Inno.Animation/AnimationInterpolation.cs new file mode 100644 index 000000000..3b8b2f2ca --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationInterpolation.cs @@ -0,0 +1,16 @@ +namespace Inno.Animation; + +/// +/// Selects how values are sampled between adjacent keyframes. +/// +public enum AnimationInterpolation +{ + /// + /// Holds the previous keyframe value until the next keyframe. + /// + Step, + /// + /// Blends linearly between adjacent keyframes. + /// + Linear +} diff --git a/src/content/animation/Inno.Animation/AnimationKeyframe.cs b/src/content/animation/Inno.Animation/AnimationKeyframe.cs new file mode 100644 index 000000000..ebd03234f --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationKeyframe.cs @@ -0,0 +1,43 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Animation; + +/// +/// Stores one timestamped value inside an animation track. +/// +public struct AnimationKeyframe +{ + /// + /// Creates one animation keyframe. + /// + /// + /// Non-negative clip-local time in seconds. + /// + /// + /// Value sampled at the keyframe time. + /// + public AnimationKeyframe( + float time, + AnimationValue value + ) { + if (!float.IsFinite(time) || time < 0f) + { + throw new ArgumentOutOfRangeException(nameof(time)); + } + this.time = time; + this.value = value; + } + + /// + /// Gets or sets clip-local time in seconds. + /// + [SerializableProperty] + public float time { get; set; } + + /// + /// Gets or sets the sampled value. + /// + [SerializableProperty] + public AnimationValue value { get; set; } +} diff --git a/src/content/animation/Inno.Animation/AnimationMarkerEvent.cs b/src/content/animation/Inno.Animation/AnimationMarkerEvent.cs new file mode 100644 index 000000000..82bcded4e --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationMarkerEvent.cs @@ -0,0 +1,52 @@ +using System; +using Inno.Core.Events; + +namespace Inno.Animation; + +/// +/// Publishes a stable marker reached by one animation playback on the main runtime thread. +/// +public sealed class AnimationMarkerEvent : Event +{ + /// + /// Creates one immutable animation marker event. + /// + /// + /// Playback that crossed the marker. + /// + /// + /// Stable marker protocol identifier. + /// + /// + /// Opaque reload-safe marker payload bytes. + /// + public AnimationMarkerEvent( + AnimationPlaybackHandle playback, + string eventID, + ReadOnlyMemory payload + ) { + if (!playback.isValid) + { + throw new ArgumentException("A valid animation playback handle is required.", nameof(playback)); + } + ArgumentException.ThrowIfNullOrWhiteSpace(eventID); + this.playback = playback; + this.eventID = eventID; + this.payload = payload.ToArray(); + } + + /// + /// Gets the playback that crossed the marker. + /// + public AnimationPlaybackHandle playback { get; } + + /// + /// Gets the stable marker protocol identifier. + /// + public string eventID { get; } + + /// + /// Gets an immutable copy of the marker payload. + /// + public ReadOnlyMemory payload { get; } +} diff --git a/src/content/animation/Inno.Animation/AnimationPlayOptions.cs b/src/content/animation/Inno.Animation/AnimationPlayOptions.cs new file mode 100644 index 000000000..4cc823a5d --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationPlayOptions.cs @@ -0,0 +1,44 @@ +namespace Inno.Animation; + +/// +/// Stores immutable options used to begin one animation playback. +/// +public struct AnimationPlayOptions +{ + /// + /// Gets the default playback options. + /// + public static AnimationPlayOptions defaultValue + => new() + { + speed = 1f, + weight = 1f, + layer = 0, + clock = AnimationClock.Scaled + }; + + /// + /// Gets or sets the non-negative playback speed multiplier. + /// + public float speed { get; set; } + + /// + /// Gets or sets the finite blend weight in the inclusive zero-to-one range. + /// + public float weight { get; set; } + + /// + /// Gets or sets the deterministic blend layer. + /// + public int layer { get; set; } + + /// + /// Gets or sets whether the clip repeats after its duration. + /// + public bool loop { get; set; } + + /// + /// Gets or sets the session clock used by the playback. + /// + public AnimationClock clock { get; set; } +} diff --git a/src/content/animation/Inno.Animation/AnimationPlaybackHandle.cs b/src/content/animation/Inno.Animation/AnimationPlaybackHandle.cs new file mode 100644 index 000000000..d4ef2c7f8 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationPlaybackHandle.cs @@ -0,0 +1,27 @@ +namespace Inno.Animation; + +/// +/// Identifies one generation-checked animation playback owned by a runtime service. +/// +public readonly record struct AnimationPlaybackHandle +{ + internal AnimationPlaybackHandle( + ulong value, + uint runtimeGeneration + ) { + this.value = value; + this.runtimeGeneration = runtimeGeneration; + } + + /// + /// Gets whether the handle was initialized by an animation service. + /// + public bool isValid => value != 0 && runtimeGeneration != 0; + + internal ulong value { get; } + + /// + /// Gets the isolated runtime generation that created this handle. + /// + public uint runtimeGeneration { get; } +} diff --git a/src/content/animation/Inno.Animation/AnimationPlaybackState.cs b/src/content/animation/Inno.Animation/AnimationPlaybackState.cs new file mode 100644 index 000000000..da645acde --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationPlaybackState.cs @@ -0,0 +1,16 @@ +namespace Inno.Animation; + +/// +/// Describes the observable lifecycle of one animation playback. +/// +public enum AnimationPlaybackState +{ + /// + /// The playback is advancing and producing samples. + /// + Playing, + /// + /// The playback retains its position without advancing. + /// + Paused +} diff --git a/src/content/animation/Inno.Animation/AnimationSample.cs b/src/content/animation/Inno.Animation/AnimationSample.cs new file mode 100644 index 000000000..5ccaac047 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationSample.cs @@ -0,0 +1,54 @@ +using System; + +namespace Inno.Animation; + +/// +/// Stores one final blended value emitted for a stable binding identifier. +/// +public readonly record struct AnimationSample +{ + /// + /// Creates one final animation sample. + /// + /// + /// The weak destination or explicit sampling-only policy. + /// + /// + /// Stable target binding. + /// + /// + /// Final blended value. + /// + public AnimationSample( + AnimationTarget target, + AnimationBindingID binding, + AnimationValue value + ) { + if (!target.isValid) + { + throw new ArgumentException("A valid animation destination is required.", nameof(target)); + } + if (!binding.isValid) + { + throw new ArgumentException("A valid animation binding is required.", nameof(binding)); + } + this.binding = binding; + this.target = target; + this.value = value; + } + + /// + /// Gets the stable target binding. + /// + public AnimationBindingID binding { get; } + + /// + /// Gets the generation-qualified destination for this sample. + /// + public AnimationTarget target { get; } + + /// + /// Gets the final blended value. + /// + public AnimationValue value { get; } +} diff --git a/src/content/animation/Inno.Animation/AnimationTrack.cs b/src/content/animation/Inno.Animation/AnimationTrack.cs new file mode 100644 index 000000000..4cbe3f299 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationTrack.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Serialization; + +namespace Inno.Animation; + +/// +/// Stores one ordered value track targeting a stable binding. +/// +public sealed class AnimationTrack : ISerializable +{ + /// + /// Creates an empty track for structured deserialization. + /// + public AnimationTrack() {} + + /// + /// Creates one validated animation track. + /// + /// + /// Stable target binding identifier. + /// + /// + /// Sampling rule between adjacent keyframes. + /// + /// + /// Keyframes ordered by non-decreasing clip-local time. + /// + public AnimationTrack( + string bindingID, + AnimationInterpolation interpolation, + IEnumerable keyframes + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(bindingID); + ArgumentNullException.ThrowIfNull(keyframes); + this.bindingId = bindingID; + this.interpolation = interpolation; + this.keyframes = keyframes.ToArray(); + Validate(float.PositiveInfinity); + } + + /// + /// Gets or sets the stable target binding identifier. + /// + [SerializableProperty] + public string bindingId { get; set; } = string.Empty; + + /// + /// Gets or sets the sampling rule between adjacent keyframes. + /// + [SerializableProperty] + public AnimationInterpolation interpolation { get; set; } + + /// + /// Gets or sets ordered keyframes. + /// + [SerializableProperty] + public AnimationKeyframe[] keyframes { get; set; } = []; + + internal void Validate(float duration) + { + ArgumentException.ThrowIfNullOrWhiteSpace(bindingId); + if (keyframes is null || keyframes.Length == 0) + { + throw new InvalidOperationException($"Animation track '{bindingId}' requires at least one keyframe."); + } + AnimationValueKind kind = keyframes[0].value.kind; + float previous = -1f; + for (int index = 0; index < keyframes.Length; index++) + { + AnimationKeyframe keyframe = keyframes[index]; + if (!float.IsFinite(keyframe.time) || keyframe.time < previous || keyframe.time > duration) + { + throw new InvalidOperationException($"Animation track '{bindingId}' contains invalid keyframe times."); + } + if (keyframe.value.kind != kind) + { + throw new InvalidOperationException($"Animation track '{bindingId}' mixes incompatible value kinds."); + } + previous = keyframe.time; + } + } +} diff --git a/src/content/animation/Inno.Animation/AnimationTypes.cs b/src/content/animation/Inno.Animation/AnimationTypes.cs deleted file mode 100644 index 11c2590ec..000000000 --- a/src/content/animation/Inno.Animation/AnimationTypes.cs +++ /dev/null @@ -1,383 +0,0 @@ -using System; -using Inno.Core.Serialization; - -namespace Inno.Animation; - -/// -/// Identifies one backend-neutral value destination inside an animation binding scope. -/// -public readonly record struct AnimationBindingID -{ - /// - /// Creates a stable animation binding identifier. - /// - /// - /// The non-empty binding protocol value. - /// - public AnimationBindingID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the stable binding protocol value. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this identifier for diagnostics and persistence. - /// - /// - /// The protocol value, or an empty string for an uninitialized identifier. - /// - public override string ToString() => value ?? string.Empty; -} - -/// -/// Describes the number and interpretation of components in an animation value. -/// -public enum AnimationValueKind -{ - /// - /// A single scalar component. - /// - Scalar, - /// - /// Two independent components. - /// - Vector2, - /// - /// Three independent components. - /// - Vector3, - /// - /// Four independent components. - /// - Vector4, - /// - /// Four normalized rotation components. - /// - Quaternion -} - -/// -/// Stores one backend-neutral scalar, vector, or quaternion animation value. -/// -public struct AnimationValue -{ - /// - /// Creates a four-component animation value. - /// - /// - /// Interpretation of the populated components. - /// - /// - /// First component. - /// - /// - /// Second component. - /// - /// - /// Third component. - /// - /// - /// Fourth component. - /// - public AnimationValue( - AnimationValueKind kind, - float x, - float y = 0f, - float z = 0f, - float w = 0f - ) { - this.kind = kind; - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - - /// - /// Gets or sets the component interpretation. - /// - [SerializableProperty] - public AnimationValueKind kind { get; set; } - - /// - /// Gets or sets the first component. - /// - [SerializableProperty] - public float x { get; set; } - - /// - /// Gets or sets the second component. - /// - [SerializableProperty] - public float y { get; set; } - - /// - /// Gets or sets the third component. - /// - [SerializableProperty] - public float z { get; set; } - - /// - /// Gets or sets the fourth component. - /// - [SerializableProperty] - public float w { get; set; } - - internal static AnimationValue Lerp( - AnimationValue left, - AnimationValue right, - float amount - ) { - if (left.kind != right.kind) - { - throw new InvalidOperationException("Animation values with different kinds cannot be interpolated."); - } - float t = Math.Clamp(amount, 0f, 1f); - var value = new AnimationValue( - left.kind, - left.x + ((right.x - left.x) * t), - left.y + ((right.y - left.y) * t), - left.z + ((right.z - left.z) * t), - left.w + ((right.w - left.w) * t) - ); - return left.kind == AnimationValueKind.Quaternion ? NormalizeQuaternion(value) : value; - } - - internal static AnimationValue WeightedAverage( - AnimationValue sum, - float inverseWeight - ) { - var value = new AnimationValue( - sum.kind, - sum.x * inverseWeight, - sum.y * inverseWeight, - sum.z * inverseWeight, - sum.w * inverseWeight - ); - return sum.kind == AnimationValueKind.Quaternion ? NormalizeQuaternion(value) : value; - } - - internal static AnimationValue AddWeighted( - AnimationValue sum, - AnimationValue value, - float weight - ) { - if (sum.kind != value.kind) - { - throw new InvalidOperationException("Animation tracks targeting one binding must use one value kind."); - } - sum.x += value.x * weight; - sum.y += value.y * weight; - sum.z += value.z * weight; - sum.w += value.w * weight; - return sum; - } - - private static AnimationValue NormalizeQuaternion(AnimationValue value) - { - float length = MathF.Sqrt( - (value.x * value.x) - + (value.y * value.y) - + (value.z * value.z) - + (value.w * value.w) - ); - return length <= float.Epsilon - ? new AnimationValue(AnimationValueKind.Quaternion, 0f, 0f, 0f, 1f) - : new AnimationValue( - AnimationValueKind.Quaternion, - value.x / length, - value.y / length, - value.z / length, - value.w / length - ); - } -} - -/// -/// Selects how values are sampled between adjacent keyframes. -/// -public enum AnimationInterpolation -{ - /// - /// Holds the previous keyframe value until the next keyframe. - /// - Step, - /// - /// Blends linearly between adjacent keyframes. - /// - Linear -} - -/// -/// Selects the session clock used to advance an animation playback. -/// -public enum AnimationClock -{ - /// - /// Uses scaled simulation time and stops while the session is paused. - /// - Scaled, - /// - /// Uses unscaled session time and continues while simulation is paused. - /// - Unscaled -} - -/// -/// Describes the observable lifecycle of one animation playback. -/// -public enum AnimationPlaybackState -{ - /// - /// The playback is advancing and producing samples. - /// - Playing, - /// - /// The playback retains its position without advancing. - /// - Paused -} - -/// -/// Stores immutable options used to begin one animation playback. -/// -public struct AnimationPlayOptions -{ - /// - /// Gets the default playback options. - /// - public static AnimationPlayOptions defaultValue - => new() - { - speed = 1f, - weight = 1f, - layer = 0, - clock = AnimationClock.Scaled - }; - - /// - /// Gets or sets the non-negative playback speed multiplier. - /// - public float speed { get; set; } - - /// - /// Gets or sets the finite blend weight in the inclusive zero-to-one range. - /// - public float weight { get; set; } - - /// - /// Gets or sets the deterministic blend layer. - /// - public int layer { get; set; } - - /// - /// Gets or sets whether the clip repeats after its duration. - /// - public bool loop { get; set; } - - /// - /// Gets or sets the session clock used by the playback. - /// - public AnimationClock clock { get; set; } -} - -/// -/// Identifies one generation-checked animation playback owned by a runtime service. -/// -public readonly record struct AnimationPlaybackHandle -{ - internal AnimationPlaybackHandle( - ulong value, - uint runtimeGeneration - ) { - this.value = value; - this.runtimeGeneration = runtimeGeneration; - } - - /// - /// Gets whether the handle was initialized by an animation service. - /// - public bool isValid => value != 0 && runtimeGeneration != 0; - - internal ulong value { get; } - - /// - /// Gets the isolated runtime generation that created this handle. - /// - public uint runtimeGeneration { get; } -} - -/// -/// Stores one final blended value emitted for a stable binding identifier. -/// -public readonly record struct AnimationSample -{ - /// - /// Creates one final animation sample. - /// - /// - /// The weak destination or explicit sampling-only policy. - /// - /// - /// Stable target binding. - /// - /// - /// Final blended value. - /// - public AnimationSample( - AnimationTarget target, - AnimationBindingID binding, - AnimationValue value - ) { - if (!target.isValid) - { - throw new ArgumentException("A valid animation destination is required.", nameof(target)); - } - if (!binding.isValid) - { - throw new ArgumentException("A valid animation binding is required.", nameof(binding)); - } - this.binding = binding; - this.target = target; - this.value = value; - } - - /// - /// Gets the stable target binding. - /// - public AnimationBindingID binding { get; } - - /// - /// Gets the generation-qualified destination for this sample. - /// - public AnimationTarget target { get; } - - /// - /// Gets the final blended value. - /// - public AnimationValue value { get; } -} - -/// -/// Receives final backend-neutral samples after runtime blending has completed. -/// -public interface IAnimationBindingSink -{ - /// - /// Applies one immutable frame of final animation samples. - /// - /// - /// Samples sorted by stable binding identifier. - /// - void Apply(ReadOnlySpan samples); -} diff --git a/src/content/animation/Inno.Animation/AnimationValue.cs b/src/content/animation/Inno.Animation/AnimationValue.cs new file mode 100644 index 000000000..a9e72f206 --- /dev/null +++ b/src/content/animation/Inno.Animation/AnimationValue.cs @@ -0,0 +1,168 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Animation; + +/// +/// Stores one backend-neutral scalar, vector, or quaternion animation value. +/// +public struct AnimationValue +{ + /// + /// Creates a four-component animation value. + /// + /// + /// Interpretation of the populated components. + /// + /// + /// First component. + /// + /// + /// Second component. + /// + /// + /// Third component. + /// + /// + /// Fourth component. + /// + public AnimationValue( + AnimationValueKind kind, + float x, + float y = 0f, + float z = 0f, + float w = 0f + ) { + this.kind = kind; + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + + /// + /// Gets or sets the component interpretation. + /// + [SerializableProperty] + public AnimationValueKind kind { get; set; } + + /// + /// Gets or sets the first component. + /// + [SerializableProperty] + public float x { get; set; } + + /// + /// Gets or sets the second component. + /// + [SerializableProperty] + public float y { get; set; } + + /// + /// Gets or sets the third component. + /// + [SerializableProperty] + public float z { get; set; } + + /// + /// Gets or sets the fourth component. + /// + [SerializableProperty] + public float w { get; set; } + + internal static AnimationValue Lerp( + AnimationValue left, + AnimationValue right, + float amount + ) { + if (left.kind != right.kind) + { + throw new InvalidOperationException("Animation values with different kinds cannot be interpolated."); + } + float t = Math.Clamp(amount, 0f, 1f); + var value = new AnimationValue( + left.kind, + left.x + ((right.x - left.x) * t), + left.y + ((right.y - left.y) * t), + left.z + ((right.z - left.z) * t), + left.w + ((right.w - left.w) * t) + ); + return left.kind == AnimationValueKind.Quaternion ? NormalizeQuaternion(value) : value; + } + + internal static AnimationValue WeightedAverage( + AnimationValue sum, + float inverseWeight + ) { + var value = new AnimationValue( + sum.kind, + sum.x * inverseWeight, + sum.y * inverseWeight, + sum.z * inverseWeight, + sum.w * inverseWeight + ); + return sum.kind == AnimationValueKind.Quaternion ? NormalizeQuaternion(value) : value; + } + + internal static AnimationValue AddWeighted( + AnimationValue sum, + AnimationValue value, + float weight + ) { + if (sum.kind != value.kind) + { + throw new InvalidOperationException("Animation tracks targeting one binding must use one value kind."); + } + sum.x += value.x * weight; + sum.y += value.y * weight; + sum.z += value.z * weight; + sum.w += value.w * weight; + return sum; + } + + private static AnimationValue NormalizeQuaternion(AnimationValue value) + { + float length = MathF.Sqrt( + (value.x * value.x) + + (value.y * value.y) + + (value.z * value.z) + + (value.w * value.w) + ); + return length <= float.Epsilon + ? new AnimationValue(AnimationValueKind.Quaternion, 0f, 0f, 0f, 1f) + : new AnimationValue( + AnimationValueKind.Quaternion, + value.x / length, + value.y / length, + value.z / length, + value.w / length + ); + } +} + +/// +/// Describes the number and interpretation of components in an animation value. +/// +public enum AnimationValueKind +{ + /// + /// A single scalar component. + /// + Scalar, + /// + /// Two independent components. + /// + Vector2, + /// + /// Three independent components. + /// + Vector3, + /// + /// Four independent components. + /// + Vector4, + /// + /// Four normalized rotation components. + /// + Quaternion +} diff --git a/src/content/animation/Inno.Animation/IAnimationBindingSink.cs b/src/content/animation/Inno.Animation/IAnimationBindingSink.cs new file mode 100644 index 000000000..9e51a96a0 --- /dev/null +++ b/src/content/animation/Inno.Animation/IAnimationBindingSink.cs @@ -0,0 +1,17 @@ +using System; + +namespace Inno.Animation; + +/// +/// Receives final backend-neutral samples after runtime blending has completed. +/// +public interface IAnimationBindingSink +{ + /// + /// Applies one immutable frame of final animation samples. + /// + /// + /// Samples sorted by stable binding identifier. + /// + void Apply(ReadOnlySpan samples); +} diff --git a/src/content/animation/Inno.Animation/IAnimationService.cs b/src/content/animation/Inno.Animation/IAnimationService.cs index 0b76c62bf..f48acf97c 100644 --- a/src/content/animation/Inno.Animation/IAnimationService.cs +++ b/src/content/animation/Inno.Animation/IAnimationService.cs @@ -1,6 +1,3 @@ -using System; -using Inno.Core.Events; - namespace Inno.Animation; /// @@ -117,51 +114,3 @@ bool TryGetState( out float time ); } - -/// -/// Publishes a stable marker reached by one animation playback on the main runtime thread. -/// -public sealed class AnimationMarkerEvent : Event -{ - /// - /// Creates one immutable animation marker event. - /// - /// - /// Playback that crossed the marker. - /// - /// - /// Stable marker protocol identifier. - /// - /// - /// Opaque reload-safe marker payload bytes. - /// - public AnimationMarkerEvent( - AnimationPlaybackHandle playback, - string eventID, - ReadOnlyMemory payload - ) { - if (!playback.isValid) - { - throw new ArgumentException("A valid animation playback handle is required.", nameof(playback)); - } - ArgumentException.ThrowIfNullOrWhiteSpace(eventID); - this.playback = playback; - this.eventID = eventID; - this.payload = payload.ToArray(); - } - - /// - /// Gets the playback that crossed the marker. - /// - public AnimationPlaybackHandle playback { get; } - - /// - /// Gets the stable marker protocol identifier. - /// - public string eventID { get; } - - /// - /// Gets an immutable copy of the marker payload. - /// - public ReadOnlyMemory payload { get; } -} diff --git a/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceSnapshot.cs b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceSnapshot.cs new file mode 100644 index 000000000..2eb1bab58 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceSnapshot.cs @@ -0,0 +1,34 @@ +namespace Inno.Assets.Pipeline; + +/// +/// Contains detached authoring bytes and conflict-detection state. +/// +public sealed class AssetSourceSnapshot +{ + private readonly byte[] m_bytes; + + internal AssetSourceSnapshot( + byte[] bytes, + string hash, + bool readOnly + ) { + m_bytes = bytes; + this.contentHash = hash; + this.isReadOnly = readOnly; + } + + /// + /// Gets a copy of the captured native source bytes. + /// + public byte[] bytes => (byte[])m_bytes.Clone(); + + /// + /// Gets the source fingerprint required by a subsequent save. + /// + public string contentHash { get; } + + /// + /// Gets whether the installation source cannot be edited in place. + /// + public bool isReadOnly { get; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs index 581d47d36..1bfb51d6a 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Editing/AssetSourceStore.cs @@ -157,36 +157,3 @@ string expectedHash private static string Hash(ReadOnlySpan bytes) => Convert.ToHexString(SHA256.HashData(bytes)); } - -/// -/// Contains detached authoring bytes and conflict-detection state. -/// -public sealed class AssetSourceSnapshot -{ - private readonly byte[] m_bytes; - - internal AssetSourceSnapshot( - byte[] bytes, - string hash, - bool readOnly - ) { - m_bytes = bytes; - this.contentHash = hash; - this.isReadOnly = readOnly; - } - - /// - /// Gets a copy of the captured native source bytes. - /// - public byte[] bytes => (byte[])m_bytes.Clone(); - - /// - /// Gets the source fingerprint required by a subsequent save. - /// - public string contentHash { get; } - - /// - /// Gets whether the installation source cannot be edited in place. - /// - public bool isReadOnly { get; } -} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs index b2143f625..d11e660c7 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactManifest.cs @@ -10,21 +10,3 @@ internal sealed class AssetArtifactManifest : ISerializable [SerializableProperty] internal AssetArtifactOutputData[] outputs { get; set; } = []; } - -internal struct AssetArtifactOutputData -{ - [SerializableProperty] - internal string name { get; set; } - - [SerializableProperty] - internal string fileName { get; set; } - - [SerializableProperty] - internal string contentHash { get; set; } - - [SerializableProperty] - internal long length { get; set; } - - [SerializableProperty] - internal AssetDeploymentScope deploymentScope { get; set; } -} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactOutputData.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactOutputData.cs new file mode 100644 index 000000000..2e68a4f93 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactOutputData.cs @@ -0,0 +1,21 @@ +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline; + +internal struct AssetArtifactOutputData +{ + [SerializableProperty] + internal string name { get; set; } + + [SerializableProperty] + internal string fileName { get; set; } + + [SerializableProperty] + internal string contentHash { get; set; } + + [SerializableProperty] + internal long length { get; set; } + + [SerializableProperty] + internal AssetDeploymentScope deploymentScope { get; set; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportProduct.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportProduct.cs new file mode 100644 index 000000000..3513c38f2 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImportProduct.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Assets.Pipeline; + +internal readonly struct AssetImportProduct( + AssetObject asset, + IReadOnlyDictionary> outputs, + IReadOnlyList diagnostics, + IReadOnlySet authoringOutputs, + AssetDeploymentScope? deploymentScope +) { + internal AssetObject asset { get; } = asset ?? throw new ArgumentNullException(nameof(asset)); + internal IReadOnlyDictionary> outputs { get; } = outputs; + internal IReadOnlyList diagnostics { get; } = diagnostics; + internal IReadOnlySet authoringOutputs { get; } = authoringOutputs; + internal AssetDeploymentScope? deploymentScope { get; } = deploymentScope; + + internal ReadOnlyMemory runtimePayload + => outputs.TryGetValue("runtime", out ReadOnlyMemory bytes) + ? bytes + : ReadOnlyMemory.Empty; +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs index 1a8aeac8e..62c0c71ea 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporter.cs @@ -2,35 +2,10 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Inno.Assets; using Inno.Core.Serialization; namespace Inno.Assets.Pipeline; -/// -/// Declares the immutable protocol identity of an automatically discovered asset importer. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AssetImporterAttribute : Attribute -{ - /// - /// Creates importer discovery metadata. - /// - /// - /// Globally stable importer protocol identifier. - /// - public AssetImporterAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id.Trim(); - } - - /// - /// Gets the globally stable importer protocol identifier. - /// - public string id { get; } -} - /// /// Defines metadata shared by automatically discovered asset importers. /// @@ -172,22 +147,3 @@ CancellationToken cancellationToken return ValueTask.FromResult?>(null); } } - -internal readonly struct AssetImportProduct( - AssetObject asset, - IReadOnlyDictionary> outputs, - IReadOnlyList diagnostics, - IReadOnlySet authoringOutputs, - AssetDeploymentScope? deploymentScope -) { - internal AssetObject asset { get; } = asset ?? throw new ArgumentNullException(nameof(asset)); - internal IReadOnlyDictionary> outputs { get; } = outputs; - internal IReadOnlyList diagnostics { get; } = diagnostics; - internal IReadOnlySet authoringOutputs { get; } = authoringOutputs; - internal AssetDeploymentScope? deploymentScope { get; } = deploymentScope; - - internal ReadOnlyMemory runtimePayload - => outputs.TryGetValue("runtime", out ReadOnlyMemory bytes) - ? bytes - : ReadOnlyMemory.Empty; -} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporterAttribute.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporterAttribute.cs new file mode 100644 index 000000000..4051891f7 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetImporterAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace Inno.Assets.Pipeline; + +/// +/// Declares the immutable protocol identity of an automatically discovered asset importer. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AssetImporterAttribute : Attribute +{ + /// + /// Creates importer discovery metadata. + /// + /// + /// Globally stable importer protocol identifier. + /// + public AssetImporterAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id.Trim(); + } + + /// + /// Gets the globally stable importer protocol identifier. + /// + public string id { get; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs index 2475eb02c..037fc48e0 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessor.cs @@ -2,34 +2,9 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Inno.Assets; namespace Inno.Assets.Pipeline; -/// -/// Declares the immutable cache protocol identity of an automatically discovered asset build processor. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AssetBuildProcessorAttribute : Attribute -{ - /// - /// Creates build-processor discovery metadata. - /// - /// - /// Globally stable build processor identifier. - /// - public AssetBuildProcessorAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id.Trim(); - } - - /// - /// Gets the globally stable build processor identifier. - /// - public string id { get; } -} - /// /// Defines an automatically discovered aggregate asset build processor. /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorAttribute.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorAttribute.cs new file mode 100644 index 000000000..26f900ea9 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Building/AssetBuildProcessorAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace Inno.Assets.Pipeline; + +/// +/// Declares the immutable cache protocol identity of an automatically discovered asset build processor. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AssetBuildProcessorAttribute : Attribute +{ + /// + /// Creates build-processor discovery metadata. + /// + /// + /// Globally stable build processor identifier. + /// + public AssetBuildProcessorAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id.Trim(); + } + + /// + /// Gets the globally stable build processor identifier. + /// + public string id { get; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetDependencyData.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetDependencyData.cs new file mode 100644 index 000000000..f01722fc6 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetDependencyData.cs @@ -0,0 +1,16 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline; + +internal struct AssetDependencyData +{ + [SerializableProperty] + internal Guid persistentId { get; set; } + + [SerializableProperty] + internal Guid stableTypeId { get; set; } + + [SerializableProperty] + internal string lastKnownPath { get; set; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportDependencyData.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportDependencyData.cs new file mode 100644 index 000000000..c87469f26 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetImportDependencyData.cs @@ -0,0 +1,27 @@ +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline; + +internal struct AssetImportDependencyData +{ + [SerializableProperty] + internal int kind { get; set; } + + [SerializableProperty] + internal string key { get; set; } + + [SerializableProperty] + internal string fingerprint { get; set; } + + [SerializableProperty] + internal bool sourceStampValid { get; set; } + + [SerializableProperty] + internal long sourceLength { get; set; } + + [SerializableProperty] + internal long sourceLastWriteUtcTicks { get; set; } + + [SerializableProperty] + internal long sourceCreationTimeUtcTicks { get; set; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs index 447ace145..fd90d75e4 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Internal/AssetMeta.cs @@ -1,5 +1,4 @@ using System; -using Inno.Assets; using Inno.Core.Serialization; namespace Inno.Assets.Pipeline; @@ -66,39 +65,3 @@ internal sealed class AssetMeta : ISerializable [SerializableProperty] internal bool isTombstone { get; set; } } - -internal struct AssetDependencyData -{ - [SerializableProperty] - internal Guid persistentId { get; set; } - - [SerializableProperty] - internal Guid stableTypeId { get; set; } - - [SerializableProperty] - internal string lastKnownPath { get; set; } -} - -internal struct AssetImportDependencyData -{ - [SerializableProperty] - internal int kind { get; set; } - - [SerializableProperty] - internal string key { get; set; } - - [SerializableProperty] - internal string fingerprint { get; set; } - - [SerializableProperty] - internal bool sourceStampValid { get; set; } - - [SerializableProperty] - internal long sourceLength { get; set; } - - [SerializableProperty] - internal long sourceLastWriteUtcTicks { get; set; } - - [SerializableProperty] - internal long sourceCreationTimeUtcTicks { get; set; } -} diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriterAttribute.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriterAttribute.cs new file mode 100644 index 000000000..417574f33 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriterAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace Inno.Assets.Pipeline; + +/// +/// Registers a source-language sample transformer through the reloadable type catalog. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AssetSampleSourceRewriterAttribute : Attribute +{ + /// + /// Creates one ordered source-language transformer declaration. + /// + /// + /// Stable extension identity used for diagnostics and ordering. + /// + public AssetSampleSourceRewriterAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + } + + /// + /// Gets the stable extension identity. + /// + public string id { get; } +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleTransformContext.cs similarity index 72% rename from src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs rename to src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleTransformContext.cs index 8c0888a6d..53cec08e5 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleSourceRewriter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/AssetSampleTransformContext.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Threading; -using Inno.Assets; namespace Inno.Assets.Pipeline; @@ -114,45 +113,3 @@ Guid newID m_identityMap[oldID] = newID; } } - -/// -/// Rewrites a source language in a private sample clone before source assets are published. -/// -public interface IAssetSampleSourceRewriter -{ - /// - /// Rewrites staged source files and registers any changed serialized type identities. - /// - /// - /// The transaction-owned staged clone. - /// - /// - /// Runs on a worker with a pinned extension generation. Access only transaction-owned files - /// and context data, observe cancellation, and do not access live Assets or Editor state. - /// - void Transform(AssetSampleTransformContext context); -} - -/// -/// Registers a source-language sample transformer through the reloadable type catalog. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AssetSampleSourceRewriterAttribute : Attribute -{ - /// - /// Creates one ordered source-language transformer declaration. - /// - /// - /// Stable extension identity used for diagnostics and ordering. - /// - public AssetSampleSourceRewriterAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - } - - /// - /// Gets the stable extension identity. - /// - public string id { get; } -} diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSampleSourceRewriter.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSampleSourceRewriter.cs new file mode 100644 index 000000000..697218937 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/IAssetSampleSourceRewriter.cs @@ -0,0 +1,19 @@ +namespace Inno.Assets.Pipeline; + +/// +/// Rewrites a source language in a private sample clone before source assets are published. +/// +public interface IAssetSampleSourceRewriter +{ + /// + /// Rewrites staged source files and registers any changed serialized type identities. + /// + /// + /// The transaction-owned staged clone. + /// + /// + /// Runs on a worker with a pinned extension generation. Access only transaction-owned files + /// and context data, observe cancellation, and do not access live Assets or Editor state. + /// + void Transform(AssetSampleTransformContext context); +} diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs index 1fe120ff9..ea1c73beb 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/AssetWatcher.cs @@ -206,11 +206,3 @@ private static string NormalizeRelativePath(string relativePath) return path == "." ? string.Empty : path; } } - -internal readonly struct WatcherPollResult( - IReadOnlyList changes, - bool requiresFullRescan -) { - internal IReadOnlyList changes { get; } = changes ?? []; - internal bool requiresFullRescan { get; } = requiresFullRescan; -} diff --git a/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/WatcherPollResult.cs b/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/WatcherPollResult.cs new file mode 100644 index 000000000..6c5d34692 --- /dev/null +++ b/src/content/assets/Inno.Assets.Pipeline/Sources/Watching/WatcherPollResult.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; + +namespace Inno.Assets.Pipeline; + +internal readonly struct WatcherPollResult( + IReadOnlyList changes, + bool requiresFullRescan +) { + internal IReadOnlyList changes { get; } = changes ?? []; + internal bool requiresFullRescan { get; } = requiresFullRescan; +} diff --git a/src/content/assets/Inno.Assets/AssetPath.cs b/src/content/assets/Inno.Assets/AssetPath.cs index cd84c36f4..003c894b1 100644 --- a/src/content/assets/Inno.Assets/AssetPath.cs +++ b/src/content/assets/Inno.Assets/AssetPath.cs @@ -4,58 +4,6 @@ namespace Inno.Assets; -/// -/// Identifies one isolated asset source mount. -/// -public record struct AssetSourceID -{ - /// - /// Creates a globally stable source identifier. - /// - /// - /// Lowercase project or Plugin source identity. - /// - public AssetSourceID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - string normalized = value.Trim(); - if (normalized.Any(static character => - !(character is >= 'a' and <= 'z' - || character is >= '0' and <= '9' - || character is '.' or '_' or '-')) - ) { - throw new ArgumentException( - "An asset source ID may contain lowercase ASCII letters, digits, '.', '_', and '-' only.", - nameof(value) - ); - } - this.value = normalized; - } - - /// - /// Gets the writable project source identifier. - /// - public static AssetSourceID project => new("project"); - - /// - /// Gets or sets the globally stable source value. - /// - public string value { get; set; } - - /// - /// Gets whether the source identity has a usable value. - /// - public readonly bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override readonly string ToString() => value ?? string.Empty; -} - /// /// Addresses one asset without conflating isolated source mounts. /// diff --git a/src/content/assets/Inno.Assets/AssetSourceID.cs b/src/content/assets/Inno.Assets/AssetSourceID.cs new file mode 100644 index 000000000..0d1a8c73d --- /dev/null +++ b/src/content/assets/Inno.Assets/AssetSourceID.cs @@ -0,0 +1,56 @@ +using System; +using System.Linq; + +namespace Inno.Assets; + +/// +/// Identifies one isolated asset source mount. +/// +public record struct AssetSourceID +{ + /// + /// Creates a globally stable source identifier. + /// + /// + /// Lowercase project or Plugin source identity. + /// + public AssetSourceID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + string normalized = value.Trim(); + if (normalized.Any(static character => + !(character is >= 'a' and <= 'z' + || character is >= '0' and <= '9' + || character is '.' or '_' or '-')) + ) { + throw new ArgumentException( + "An asset source ID may contain lowercase ASCII letters, digits, '.', '_', and '-' only.", + nameof(value) + ); + } + this.value = normalized; + } + + /// + /// Gets the writable project source identifier. + /// + public static AssetSourceID project => new("project"); + + /// + /// Gets or sets the globally stable source value. + /// + public string value { get; set; } + + /// + /// Gets whether the source identity has a usable value. + /// + public readonly bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override readonly string ToString() => value ?? string.Empty; +} diff --git a/src/content/assets/Inno.Assets/Runtime/ArtifactLease.cs b/src/content/assets/Inno.Assets/Runtime/ArtifactLease.cs new file mode 100644 index 000000000..721a1c2bd --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/ArtifactLease.cs @@ -0,0 +1,94 @@ +using System; +using System.IO; +using Inno.Core.Execution; + +namespace Inno.Assets; + +/// +/// Keeps one verified immutable artifact generation available for an explicit lifetime. +/// +public sealed class ArtifactLease : IDisposable +{ + private readonly ResidencyLease m_residency; + private readonly object m_sync = new(); + private Func? m_openRead; + + internal ArtifactLease( + AssetArtifactInfo artifact, + Func openRead, + Action release + ) { + ArgumentNullException.ThrowIfNull(openRead); + m_residency = new ResidencyLease(artifact, release); + m_openRead = openRead; + } + + /// + /// Gets verified metadata for the retained artifact. + /// + public AssetArtifactInfo info => m_residency.value; + + /// + /// Opens a read-only stream over the retained immutable artifact. + /// + /// + /// A new independently owned read stream. + /// + public Stream OpenRead() + { + lock (m_sync) + { + _ = m_residency.value; + return (m_openRead ?? throw new ObjectDisposedException(nameof(ArtifactLease)))(); + } + } + + /// + /// Reads one indexed payload through this lease's independently pinned stream. + /// + /// + /// Newly owned bytes with the exact indexed length; oversized or truncated payloads fail explicitly. + /// + /// + /// The payload exceeds the supported array size or does not have its indexed length. + /// + public byte[] ReadAllBytes() + { + long length = info.length; + if (length < 0 || length > Array.MaxLength) + { + throw new InvalidDataException("The artifact payload exceeds the supported array budget."); + } + using Stream input = OpenRead(); + var bytes = new byte[(int)length]; + input.ReadExactly(bytes); + if (input.ReadByte() != -1) + { + throw new InvalidDataException("The artifact payload exceeds its indexed length."); + } + return bytes; + } + + /// + /// Releases artifact ownership, retaining metadata and callback while the provider reports Pending. + /// + /// + /// Provider retirement is unfinished or a concurrent release is in progress; retain this lease and retry at a safe point. + /// + /// + /// The provider reports a wrapped failure, or release completes with ordinary errors retained from earlier pending attempts. + /// + /// + /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. + /// Ordinary sibling failures remain observable after a later release attempt succeeds. + /// New reads stop when release begins; already opened streams retain their independent provider pins. + /// + public void Dispose() + { + lock (m_sync) + { + m_openRead = null; + } + m_residency.Dispose(); + } +} diff --git a/src/content/assets/Inno.Assets/Runtime/AssetLease.cs b/src/content/assets/Inno.Assets/Runtime/AssetLease.cs new file mode 100644 index 000000000..5f541e946 --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/AssetLease.cs @@ -0,0 +1,46 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Assets; + +/// +/// Keeps one canonical asset generation resident for an explicit lifetime. +/// +/// +/// Concrete retained asset type. +/// +public sealed class AssetLease : IDisposable + where TAsset : AssetObject +{ + private readonly ResidencyLease m_residency; + + internal AssetLease( + TAsset asset, + Action release + ) { + m_residency = new ResidencyLease(asset, release); + } + + /// + /// Gets the retained canonical asset while this lease is active. + /// + /// + /// Thrown after the lease has been released. + /// + public TAsset asset => m_residency.value; + + /// + /// Releases this caller's residency ownership, retaining its value and callback while the provider reports Pending. + /// + /// + /// Provider retirement is unfinished or a concurrent release is in progress; retain this lease and retry at a safe point. + /// + /// + /// The provider reports a wrapped failure, or release completes with ordinary errors retained from earlier pending attempts. + /// + /// + /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. + /// Ordinary sibling failures remain observable after a later release attempt succeeds. + /// + public void Dispose() => m_residency.Dispose(); +} diff --git a/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs b/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs deleted file mode 100644 index eebfd8cee..000000000 --- a/src/content/assets/Inno.Assets/Runtime/AssetResidency.cs +++ /dev/null @@ -1,332 +0,0 @@ -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Inno.Core.Execution; - -namespace Inno.Assets; - -/// -/// Exposes explicit asynchronous asset and artifact residency ownership. -/// -public interface IAssetResidency -{ - /// - /// Acquires a canonical asset by logical path and keeps it resident until the lease is released. - /// - /// - /// Required asset contract. - /// - /// - /// Mount-qualified logical asset path. - /// - /// - /// Cancellation for this caller's asynchronous wait. - /// - /// - /// A lease that owns residency for the canonical asset. - /// - ValueTask> AcquireAsync( - AssetPath path, - CancellationToken cancellationToken = default - ) where TAsset : AssetObject; - - /// - /// Acquires a canonical asset by persistent identity and keeps it resident until release. - /// - /// - /// Required asset contract. - /// - /// - /// Non-empty persistent asset identity. - /// - /// - /// Cancellation for this caller's asynchronous wait. - /// - /// - /// A lease that owns residency for the canonical asset. - /// - ValueTask> AcquireAsync( - Guid persistentID, - CancellationToken cancellationToken = default - ) where TAsset : AssetObject; - - /// - /// Acquires one verified immutable artifact output. - /// - /// - /// Persistent identity of the artifact owner. - /// - /// - /// Stable artifact output name. - /// - /// - /// A lease that keeps the artifact generation available to the caller. - /// - /// - /// Thrown when the requested artifact does not exist or fails verification. - /// - ArtifactLease AcquireArtifact( - Guid persistentID, - string outputName - ); -} - -/// -/// Provides controlled lease construction to concrete asset residency implementations. -/// -public abstract class AssetResidencyProvider -{ - /// - /// Creates one strongly typed asset residency lease. - /// - /// - /// Concrete canonical asset type. - /// - /// - /// Canonical asset retained by the lease. - /// - /// - /// Provider-owned release callback. Pending retirement must be retryable without repeating completed effects. - /// - /// - /// A lease that retains its value until release completes; a Pending callback is retried by the owning lifecycle. - /// - protected static AssetLease CreateAssetLease( - TAsset asset, - Action release - ) where TAsset : AssetObject - => new(asset, release); - - /// - /// Creates one immutable artifact residency lease. - /// - /// - /// Verified artifact metadata retained by the lease. - /// - /// - /// Opens immutable bytes with an independent provider pin owned by the returned stream. - /// - /// - /// Provider-owned release callback. Pending retirement must be retryable without repeating completed effects. - /// - /// - /// A lease that retains its value until release completes; a Pending callback is retried by the owning lifecycle. - /// - protected static ArtifactLease CreateArtifactLease( - AssetArtifactInfo artifact, - Func openRead, - Action release - ) => new(artifact, openRead, release); -} - -/// -/// Keeps one canonical asset generation resident for an explicit lifetime. -/// -/// -/// Concrete retained asset type. -/// -public sealed class AssetLease : IDisposable - where TAsset : AssetObject -{ - private readonly ResidencyLease m_residency; - - internal AssetLease( - TAsset asset, - Action release - ) { - m_residency = new ResidencyLease(asset, release); - } - - /// - /// Gets the retained canonical asset while this lease is active. - /// - /// - /// Thrown after the lease has been released. - /// - public TAsset asset => m_residency.value; - - /// - /// Releases this caller's residency ownership, retaining its value and callback while the provider reports Pending. - /// - /// - /// Provider retirement is unfinished or a concurrent release is in progress; retain this lease and retry at a safe point. - /// - /// - /// The provider reports a wrapped failure, or release completes with ordinary errors retained from earlier pending attempts. - /// - /// - /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. - /// Ordinary sibling failures remain observable after a later release attempt succeeds. - /// - public void Dispose() => m_residency.Dispose(); -} - -/// -/// Keeps one verified immutable artifact generation available for an explicit lifetime. -/// -public sealed class ArtifactLease : IDisposable -{ - private readonly ResidencyLease m_residency; - private readonly object m_sync = new(); - private Func? m_openRead; - - internal ArtifactLease( - AssetArtifactInfo artifact, - Func openRead, - Action release - ) { - ArgumentNullException.ThrowIfNull(openRead); - m_residency = new ResidencyLease(artifact, release); - m_openRead = openRead; - } - - /// - /// Gets verified metadata for the retained artifact. - /// - public AssetArtifactInfo info => m_residency.value; - - /// - /// Opens a read-only stream over the retained immutable artifact. - /// - /// - /// A new independently owned read stream. - /// - public Stream OpenRead() - { - lock (m_sync) - { - _ = m_residency.value; - return (m_openRead ?? throw new ObjectDisposedException(nameof(ArtifactLease)))(); - } - } - - /// - /// Reads one indexed payload through this lease's independently pinned stream. - /// - /// - /// Newly owned bytes with the exact indexed length; oversized or truncated payloads fail explicitly. - /// - /// - /// The payload exceeds the supported array size or does not have its indexed length. - /// - public byte[] ReadAllBytes() - { - long length = info.length; - if (length < 0 || length > Array.MaxLength) - { - throw new InvalidDataException("The artifact payload exceeds the supported array budget."); - } - using Stream input = OpenRead(); - var bytes = new byte[(int)length]; - input.ReadExactly(bytes); - if (input.ReadByte() != -1) - { - throw new InvalidDataException("The artifact payload exceeds its indexed length."); - } - return bytes; - } - - /// - /// Releases artifact ownership, retaining metadata and callback while the provider reports Pending. - /// - /// - /// Provider retirement is unfinished or a concurrent release is in progress; retain this lease and retry at a safe point. - /// - /// - /// The provider reports a wrapped failure, or release completes with ordinary errors retained from earlier pending attempts. - /// - /// - /// Pending may be wrapped in another exception; classify the complete failure with RetirementPendingException.Find. - /// Ordinary sibling failures remain observable after a later release attempt succeeds. - /// New reads stop when release begins; already opened streams retain their independent provider pins. - /// - public void Dispose() - { - lock (m_sync) - { - m_openRead = null; - } - m_residency.Dispose(); - } -} - -/// -/// Owns multiple asset, artifact, or subsystem leases as one reverse-order lifetime. -/// -public sealed class RetentionScope : IDisposable -{ - private readonly LifetimeScope m_lifetime = new(); - - /// - /// Transfers one lease into this scope. - /// - /// - /// Disposable lease type. - /// - /// - /// Lease whose disposal ownership transfers to this scope. - /// - /// - /// The same lease for convenient initialization. - /// - /// - /// Retirement has begun and the scope cannot accept another lease. - /// - public TLease Retain(TLease lease) - where TLease : IDisposable => m_lifetime.Own(lease); - - /// - /// Releases all retained leases in reverse acquisition order. - /// - /// - /// Thrown after every lease is attempted when one or more releases fail. - /// - /// - /// A lease is not retired. The current and remaining dependencies are retained for retry. - /// - public void Dispose() => m_lifetime.Dispose(); -} - -/// -/// Reports current explicit runtime asset residency accounting. -/// -public readonly record struct AssetResidencyStatistics -{ - /// - /// Creates one immutable residency snapshot. - /// - /// - /// Number of currently materialized canonical assets. - /// - /// - /// Runtime payload bytes retained by materialized assets. - /// - /// - /// Configured runtime payload budget. - /// - public AssetResidencyStatistics( - int residentAssetCount, - long residentBytes, - long budgetBytes - ) { - this.residentAssetCount = residentAssetCount; - this.residentBytes = residentBytes; - this.budgetBytes = budgetBytes; - } - - /// - /// Gets the number of materialized canonical assets. - /// - public int residentAssetCount { get; } - - /// - /// Gets retained runtime payload bytes. - /// - public long residentBytes { get; } - - /// - /// Gets the configured runtime payload budget. - /// - public long budgetBytes { get; } -} diff --git a/src/content/assets/Inno.Assets/Runtime/AssetResidencyProvider.cs b/src/content/assets/Inno.Assets/Runtime/AssetResidencyProvider.cs new file mode 100644 index 000000000..ba2eb2b8f --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/AssetResidencyProvider.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; + +namespace Inno.Assets; + +/// +/// Provides controlled lease construction to concrete asset residency implementations. +/// +public abstract class AssetResidencyProvider +{ + /// + /// Creates one strongly typed asset residency lease. + /// + /// + /// Concrete canonical asset type. + /// + /// + /// Canonical asset retained by the lease. + /// + /// + /// Provider-owned release callback. Pending retirement must be retryable without repeating completed effects. + /// + /// + /// A lease that retains its value until release completes; a Pending callback is retried by the owning lifecycle. + /// + protected static AssetLease CreateAssetLease( + TAsset asset, + Action release + ) where TAsset : AssetObject + => new(asset, release); + + /// + /// Creates one immutable artifact residency lease. + /// + /// + /// Verified artifact metadata retained by the lease. + /// + /// + /// Opens immutable bytes with an independent provider pin owned by the returned stream. + /// + /// + /// Provider-owned release callback. Pending retirement must be retryable without repeating completed effects. + /// + /// + /// A lease that retains its value until release completes; a Pending callback is retried by the owning lifecycle. + /// + protected static ArtifactLease CreateArtifactLease( + AssetArtifactInfo artifact, + Func openRead, + Action release + ) => new(artifact, openRead, release); +} diff --git a/src/content/assets/Inno.Assets/Runtime/AssetResidencyStatistics.cs b/src/content/assets/Inno.Assets/Runtime/AssetResidencyStatistics.cs new file mode 100644 index 000000000..dd531b4a2 --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/AssetResidencyStatistics.cs @@ -0,0 +1,44 @@ +namespace Inno.Assets; + +/// +/// Reports current explicit runtime asset residency accounting. +/// +public readonly record struct AssetResidencyStatistics +{ + /// + /// Creates one immutable residency snapshot. + /// + /// + /// Number of currently materialized canonical assets. + /// + /// + /// Runtime payload bytes retained by materialized assets. + /// + /// + /// Configured runtime payload budget. + /// + public AssetResidencyStatistics( + int residentAssetCount, + long residentBytes, + long budgetBytes + ) { + this.residentAssetCount = residentAssetCount; + this.residentBytes = residentBytes; + this.budgetBytes = budgetBytes; + } + + /// + /// Gets the number of materialized canonical assets. + /// + public int residentAssetCount { get; } + + /// + /// Gets retained runtime payload bytes. + /// + public long residentBytes { get; } + + /// + /// Gets the configured runtime payload budget. + /// + public long budgetBytes { get; } +} diff --git a/src/content/assets/Inno.Assets/Runtime/IAssetResidency.cs b/src/content/assets/Inno.Assets/Runtime/IAssetResidency.cs new file mode 100644 index 000000000..2e7fee9c4 --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/IAssetResidency.cs @@ -0,0 +1,71 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets; + +/// +/// Exposes explicit asynchronous asset and artifact residency ownership. +/// +public interface IAssetResidency +{ + /// + /// Acquires a canonical asset by logical path and keeps it resident until the lease is released. + /// + /// + /// Required asset contract. + /// + /// + /// Mount-qualified logical asset path. + /// + /// + /// Cancellation for this caller's asynchronous wait. + /// + /// + /// A lease that owns residency for the canonical asset. + /// + ValueTask> AcquireAsync( + AssetPath path, + CancellationToken cancellationToken = default + ) where TAsset : AssetObject; + + /// + /// Acquires a canonical asset by persistent identity and keeps it resident until release. + /// + /// + /// Required asset contract. + /// + /// + /// Non-empty persistent asset identity. + /// + /// + /// Cancellation for this caller's asynchronous wait. + /// + /// + /// A lease that owns residency for the canonical asset. + /// + ValueTask> AcquireAsync( + Guid persistentID, + CancellationToken cancellationToken = default + ) where TAsset : AssetObject; + + /// + /// Acquires one verified immutable artifact output. + /// + /// + /// Persistent identity of the artifact owner. + /// + /// + /// Stable artifact output name. + /// + /// + /// A lease that keeps the artifact generation available to the caller. + /// + /// + /// Thrown when the requested artifact does not exist or fails verification. + /// + ArtifactLease AcquireArtifact( + Guid persistentID, + string outputName + ); +} diff --git a/src/content/assets/Inno.Assets/Runtime/RetentionScope.cs b/src/content/assets/Inno.Assets/Runtime/RetentionScope.cs new file mode 100644 index 000000000..73b34103f --- /dev/null +++ b/src/content/assets/Inno.Assets/Runtime/RetentionScope.cs @@ -0,0 +1,41 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Assets; + +/// +/// Owns multiple asset, artifact, or subsystem leases as one reverse-order lifetime. +/// +public sealed class RetentionScope : IDisposable +{ + private readonly LifetimeScope m_lifetime = new(); + + /// + /// Transfers one lease into this scope. + /// + /// + /// Disposable lease type. + /// + /// + /// Lease whose disposal ownership transfers to this scope. + /// + /// + /// The same lease for convenient initialization. + /// + /// + /// Retirement has begun and the scope cannot accept another lease. + /// + public TLease Retain(TLease lease) + where TLease : IDisposable => m_lifetime.Own(lease); + + /// + /// Releases all retained leases in reverse acquisition order. + /// + /// + /// Thrown after every lease is attempted when one or more releases fail. + /// + /// + /// A lease is not retired. The current and remaining dependencies are retained for retry. + /// + public void Dispose() => m_lifetime.Dispose(); +} diff --git a/src/content/scene/Inno.Scene/Core/GameTagSettingContribution.cs b/src/content/scene/Inno.Scene/Core/GameTagSettingContribution.cs new file mode 100644 index 000000000..3e7d9b216 --- /dev/null +++ b/src/content/scene/Inno.Scene/Core/GameTagSettingContribution.cs @@ -0,0 +1,41 @@ +using System; +using System.Linq; +using Inno.Core.Serialization; + +namespace Inno.Scene; + +/// +/// Stores sparse semantic operations for one GameTag setting contribution. +/// +internal sealed class GameTagSettingContribution : ISerializable +{ + [SerializableProperty] + internal string[] additions { get; set; } = []; + + [SerializableProperty] + internal string[] removals { get; set; } = []; + + internal void Validate() + { + if (additions is null || removals is null) + { + throw new InvalidOperationException("GameTag contribution arrays cannot be null."); + } + string[] normalizedAdditions = additions.Select(GameTagCatalog.Normalize).Order(StringComparer.Ordinal).ToArray(); + string[] normalizedRemovals = removals.Select(GameTagCatalog.Normalize).Order(StringComparer.Ordinal).ToArray(); + if (!normalizedAdditions.SequenceEqual(additions, StringComparer.Ordinal) + || normalizedAdditions.Distinct(StringComparer.Ordinal).Count() != normalizedAdditions.Length + ) { + throw new InvalidOperationException("GameTag additions must be unique, normalized, and ordered."); + } + if (!normalizedRemovals.SequenceEqual(removals, StringComparer.Ordinal) + || normalizedRemovals.Distinct(StringComparer.Ordinal).Count() != normalizedRemovals.Length + ) { + throw new InvalidOperationException("GameTag removals must be unique, normalized, and ordered."); + } + if (normalizedAdditions.Intersect(normalizedRemovals, StringComparer.Ordinal).Any()) + { + throw new InvalidOperationException("A GameTag contribution cannot add and remove the same tag."); + } + } +} diff --git a/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs b/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs index edf8a0529..11e7b8038 100644 --- a/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs +++ b/src/content/scene/Inno.Scene/Core/GameTagSettingsComposer.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Core.Serialization; using Inno.Core.Settings; namespace Inno.Scene; @@ -103,39 +102,3 @@ IReadOnlyList> contributi } } } - -/// -/// Stores sparse semantic operations for one GameTag setting contribution. -/// -internal sealed class GameTagSettingContribution : ISerializable -{ - [SerializableProperty] - internal string[] additions { get; set; } = []; - - [SerializableProperty] - internal string[] removals { get; set; } = []; - - internal void Validate() - { - if (additions is null || removals is null) - { - throw new InvalidOperationException("GameTag contribution arrays cannot be null."); - } - string[] normalizedAdditions = additions.Select(GameTagCatalog.Normalize).Order(StringComparer.Ordinal).ToArray(); - string[] normalizedRemovals = removals.Select(GameTagCatalog.Normalize).Order(StringComparer.Ordinal).ToArray(); - if (!normalizedAdditions.SequenceEqual(additions, StringComparer.Ordinal) - || normalizedAdditions.Distinct(StringComparer.Ordinal).Count() != normalizedAdditions.Length - ) { - throw new InvalidOperationException("GameTag additions must be unique, normalized, and ordered."); - } - if (!normalizedRemovals.SequenceEqual(removals, StringComparer.Ordinal) - || normalizedRemovals.Distinct(StringComparer.Ordinal).Count() != normalizedRemovals.Length - ) { - throw new InvalidOperationException("GameTag removals must be unique, normalized, and ordered."); - } - if (normalizedAdditions.Intersect(normalizedRemovals, StringComparer.Ordinal).Any()) - { - throw new InvalidOperationException("A GameTag contribution cannot add and remove the same tag."); - } - } -} diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerSettingContribution.cs b/src/content/scene/Inno.Scene/Layers/GameLayerSettingContribution.cs new file mode 100644 index 000000000..ccbc23fa9 --- /dev/null +++ b/src/content/scene/Inno.Scene/Layers/GameLayerSettingContribution.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Serialization; +using Inno.Core.Settings; + +namespace Inno.Scene.Layers; + +/// +/// Stores sparse semantic operations for one GameLayer setting contribution. +/// +internal sealed class GameLayerSettingContribution : ISerializable +{ + [SerializableProperty] + internal int[] removedSlots { get; set; } = []; + + [SerializableProperty] + internal string[] removedLocalIds { get; set; } = []; + + [SerializableProperty] + internal int[] upsertSlots { get; set; } = []; + + [SerializableProperty] + internal string[] upsertLocalIds { get; set; } = []; + + [SerializableProperty] + internal string[] upsertNames { get; set; } = []; + + [SerializableProperty] + internal int[] interactionFirstSlots { get; set; } = []; + + [SerializableProperty] + internal int[] interactionSecondSlots { get; set; } = []; + + [SerializableProperty] + internal bool[] interactionValues { get; set; } = []; + + internal void Validate() + { + if (removedSlots is null + || removedLocalIds is null + || upsertSlots is null + || upsertLocalIds is null + || upsertNames is null + || interactionFirstSlots is null + || interactionSecondSlots is null + || interactionValues is null + ) { + throw new InvalidOperationException("GameLayer contribution arrays cannot be null."); + } + if (removedSlots.Length != removedLocalIds.Length) + { + throw new InvalidOperationException("GameLayer removal contribution arrays must have equal lengths."); + } + if (upsertSlots.Length != upsertLocalIds.Length || upsertSlots.Length != upsertNames.Length) + { + throw new InvalidOperationException("GameLayer upsert contribution arrays must have equal lengths."); + } + if (interactionFirstSlots.Length != interactionSecondSlots.Length + || interactionFirstSlots.Length != interactionValues.Length + ) { + throw new InvalidOperationException("GameLayer interaction contribution arrays must have equal lengths."); + } + + var slots = new HashSet(); + for (int index = 0; index < removedSlots.Length; index++) + { + _ = new GameLayer(removedSlots[index]); + _ = new ProjectLocalID(removedLocalIds[index]); + if (!slots.Add(removedSlots[index])) + { + throw new InvalidOperationException($"GameLayer slot {removedSlots[index]} is removed more than once."); + } + } + slots.Clear(); + for (int index = 0; index < upsertSlots.Length; index++) + { + _ = new GameLayer(upsertSlots[index]); + _ = new ProjectLocalID(upsertLocalIds[index]); + _ = GameLayerCatalog.NormalizeName(upsertNames[index]); + if (!slots.Add(upsertSlots[index])) + { + throw new InvalidOperationException($"GameLayer slot {upsertSlots[index]} is upserted more than once."); + } + } + var pairs = new HashSet<(int first, int second)>(); + for (int index = 0; index < interactionFirstSlots.Length; index++) + { + int first = interactionFirstSlots[index]; + int second = interactionSecondSlots[index]; + _ = new GameLayer(first); + _ = new GameLayer(second); + if (first > second) + { + throw new InvalidOperationException("GameLayer interaction pairs must use canonical slot order."); + } + if (!pairs.Add((first, second))) + { + throw new InvalidOperationException( + $"GameLayer interaction ({first}, {second}) is contributed more than once." + ); + } + } + } +} diff --git a/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs b/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs index e8d71c45a..31f9515d5 100644 --- a/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs +++ b/src/content/scene/Inno.Scene/Layers/GameLayerSettingsComposer.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Inno.Core.Serialization; using Inno.Core.Settings; namespace Inno.Scene.Layers; @@ -261,101 +260,3 @@ private static InvalidOperationException Conflict( string message ) => new($"GameLayer contribution '{context.contributorID}' {message}"); } - -/// -/// Stores sparse semantic operations for one GameLayer setting contribution. -/// -internal sealed class GameLayerSettingContribution : ISerializable -{ - [SerializableProperty] - internal int[] removedSlots { get; set; } = []; - - [SerializableProperty] - internal string[] removedLocalIds { get; set; } = []; - - [SerializableProperty] - internal int[] upsertSlots { get; set; } = []; - - [SerializableProperty] - internal string[] upsertLocalIds { get; set; } = []; - - [SerializableProperty] - internal string[] upsertNames { get; set; } = []; - - [SerializableProperty] - internal int[] interactionFirstSlots { get; set; } = []; - - [SerializableProperty] - internal int[] interactionSecondSlots { get; set; } = []; - - [SerializableProperty] - internal bool[] interactionValues { get; set; } = []; - - internal void Validate() - { - if (removedSlots is null - || removedLocalIds is null - || upsertSlots is null - || upsertLocalIds is null - || upsertNames is null - || interactionFirstSlots is null - || interactionSecondSlots is null - || interactionValues is null - ) { - throw new InvalidOperationException("GameLayer contribution arrays cannot be null."); - } - if (removedSlots.Length != removedLocalIds.Length) - { - throw new InvalidOperationException("GameLayer removal contribution arrays must have equal lengths."); - } - if (upsertSlots.Length != upsertLocalIds.Length || upsertSlots.Length != upsertNames.Length) - { - throw new InvalidOperationException("GameLayer upsert contribution arrays must have equal lengths."); - } - if (interactionFirstSlots.Length != interactionSecondSlots.Length - || interactionFirstSlots.Length != interactionValues.Length - ) { - throw new InvalidOperationException("GameLayer interaction contribution arrays must have equal lengths."); - } - - var slots = new HashSet(); - for (int index = 0; index < removedSlots.Length; index++) - { - _ = new GameLayer(removedSlots[index]); - _ = new ProjectLocalID(removedLocalIds[index]); - if (!slots.Add(removedSlots[index])) - { - throw new InvalidOperationException($"GameLayer slot {removedSlots[index]} is removed more than once."); - } - } - slots.Clear(); - for (int index = 0; index < upsertSlots.Length; index++) - { - _ = new GameLayer(upsertSlots[index]); - _ = new ProjectLocalID(upsertLocalIds[index]); - _ = GameLayerCatalog.NormalizeName(upsertNames[index]); - if (!slots.Add(upsertSlots[index])) - { - throw new InvalidOperationException($"GameLayer slot {upsertSlots[index]} is upserted more than once."); - } - } - var pairs = new HashSet<(int first, int second)>(); - for (int index = 0; index < interactionFirstSlots.Length; index++) - { - int first = interactionFirstSlots[index]; - int second = interactionSecondSlots[index]; - _ = new GameLayer(first); - _ = new GameLayer(second); - if (first > second) - { - throw new InvalidOperationException("GameLayer interaction pairs must use canonical slot order."); - } - if (!pairs.Add((first, second))) - { - throw new InvalidOperationException( - $"GameLayer interaction ({first}, {second}) is contributed more than once." - ); - } - } - } -} diff --git a/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs b/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs index f10c97c2c..0b8b6a8d5 100644 --- a/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs +++ b/src/content/scene/Inno.Scene/Prefabs/PrefabStructureOverride.cs @@ -2,6 +2,12 @@ namespace Inno.Scene; +internal sealed record PrefabStructureOverride( + Guid sourceObjectID, + PrefabObjectOverrideKind kind, + bool isOrphaned = false +); + [Flags] internal enum PrefabObjectOverrideKind { @@ -12,9 +18,3 @@ internal enum PrefabObjectOverrideKind SiblingIndex = 1 << 3, Tag = 1 << 4 } - -internal sealed record PrefabStructureOverride( - Guid sourceObjectID, - PrefabObjectOverrideKind kind, - bool isOrphaned = false -); diff --git a/src/content/scene/Inno.Scene/Serialization/EngineReferenceToken.cs b/src/content/scene/Inno.Scene/Serialization/EngineReferenceToken.cs index 8e3f69b3e..20af5449c 100644 --- a/src/content/scene/Inno.Scene/Serialization/EngineReferenceToken.cs +++ b/src/content/scene/Inno.Scene/Serialization/EngineReferenceToken.cs @@ -2,14 +2,14 @@ namespace Inno.Scene; +internal readonly record struct EngineReferenceToken( + EngineReferenceKind kind, + Guid sourceID +); + internal enum EngineReferenceKind { GameObject = 1, GameComponent = 2, GameSystem = 3 } - -internal readonly record struct EngineReferenceToken( - EngineReferenceKind kind, - Guid sourceID -); diff --git a/src/content/scene/Inno.Scene/Storage/SceneStore.cs b/src/content/scene/Inno.Scene/Storage/SceneStore.cs index 2aaa60737..581ccafc9 100644 --- a/src/content/scene/Inno.Scene/Storage/SceneStore.cs +++ b/src/content/scene/Inno.Scene/Storage/SceneStore.cs @@ -4,35 +4,10 @@ using System.Linq; using System.Threading; using Inno.Core.Collections; -using Inno.Extensibility.Types; using Inno.Scene.Layers; namespace Inno.Scene; -/// -/// Describes the structural result of removing a component. -/// -internal enum SceneStoreRemovalKind -{ - /// - /// The none key. - /// - None, - /// - /// The canceled pending addition key. - /// - CanceledPendingAddition, - /// - /// The removed committed key. - /// - RemovedCommitted -} - -internal readonly record struct SceneStoreRemovedComponent( - GameComponent component, - bool wasCommitted -); - internal sealed class SceneStore { private static readonly Lock TYPE_CACHE_SYNC = new(); @@ -1000,3 +975,27 @@ public void Dispose() } } } + +/// +/// Describes the structural result of removing a component. +/// +internal enum SceneStoreRemovalKind +{ + /// + /// The none key. + /// + None, + /// + /// The canceled pending addition key. + /// + CanceledPendingAddition, + /// + /// The removed committed key. + /// + RemovedCommitted +} + +internal readonly record struct SceneStoreRemovedComponent( + GameComponent component, + bool wasCommitted +); diff --git a/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs b/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs index f2df89e46..8c98817d7 100644 --- a/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs +++ b/src/content/scene/Inno.Scene/Storage/SceneStructureSnapshot.cs @@ -4,20 +4,6 @@ namespace Inno.Scene; -/// -/// Captures the stable attachment order for one scene object. -/// -/// -/// The game object used to initialize this instance. -/// -/// -/// The components used to initialize this instance. -/// -internal sealed record SceneObjectStructureSnapshot( - GameObject gameObject, - IReadOnlyList components -); - /// /// Owns one attachment snapshot and its frozen object/component serialization identities. /// @@ -75,3 +61,17 @@ private static bool HasCurrentIdentities(Dictionary sourceID return true; } } + +/// +/// Captures the stable attachment order for one scene object. +/// +/// +/// The game object used to initialize this instance. +/// +/// +/// The components used to initialize this instance. +/// +internal sealed record SceneObjectStructureSnapshot( + GameObject gameObject, + IReadOnlyList components +); diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectIndex.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectIndex.cs new file mode 100644 index 000000000..28fe7069f --- /dev/null +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectIndex.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Core.Collections; + +internal interface IIndexedObjectIndex + where T : class +{ + /// + /// Gets the human-readable name used for presentation and diagnostics. + /// + string name { get; } + + /// + /// Gets the key type accepted by this index implementation. + /// + Type keyType { get; } + + /// + /// Adds a new keyed value or atomically replaces the existing value for that key. + /// + /// + /// The stored item associated with the validated handle. + /// + /// + /// The backend-neutral physical key associated with this event. + /// + void AddOrUpdate( + T item, + object key + ); + + /// + /// Removes the requested value while preserving the collection's invariants. + /// + /// + /// The stored item associated with the validated handle. + /// + void Remove(T item); + + /// + /// Removes all retained entries and returns the instance to an empty reusable state. + /// + void Clear(); + + /// + /// Retrieves the requested count value from current authoritative state. + /// + /// + /// The backend-neutral physical key associated with this event. + /// + /// + /// The scalar result calculated from the supplied inputs. + /// + int GetCount(object key); + + /// + /// Attempts to get single without changing state when the operation cannot complete. + /// + /// + /// The backend-neutral physical key associated with this event. + /// + /// + /// The stored item associated with the validated handle. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + bool TryGetSingle( + object key, + out T? item + ); + + /// + /// Determines whether current state contains the requested value value. + /// + /// + /// The backend-neutral physical key associated with this event. + /// + /// + /// The stored item associated with the validated handle. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + bool Contains( + object key, + T item + ); + + /// + /// Retrieves the requested set value from current authoritative state. + /// + /// + /// The backend-neutral physical key associated with this event. + /// + /// + /// The validated hash sett? that represents the completed operation. + /// + HashSet? GetSet(object key); +} diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectStore.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectStore.cs new file mode 100644 index 000000000..618595feb --- /dev/null +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IIndexedObjectStore.cs @@ -0,0 +1,26 @@ +using System; + +namespace Inno.Core.Collections; + +/// +/// Internal store validation surface for IndexedObjectKey. +/// +internal interface IIndexedObjectStore +{ + /// + /// Determines whether the key belongs to a live slot in the current storage generation. + /// + /// + /// The stable identity used to locate the requested value. + /// + /// + /// The key type consumed by is valid key; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// when the requested condition is satisfied; otherwise, . + /// + bool IsValidKey( + int id, + Type keyType + ); +} diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs index 86d7cc04d..e1eb0dc9c 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectIndex.cs @@ -4,103 +4,6 @@ namespace Inno.Core.Collections; -internal interface IIndexedObjectIndex - where T : class -{ - /// - /// Gets the human-readable name used for presentation and diagnostics. - /// - string name { get; } - - /// - /// Gets the key type accepted by this index implementation. - /// - Type keyType { get; } - - /// - /// Adds a new keyed value or atomically replaces the existing value for that key. - /// - /// - /// The stored item associated with the validated handle. - /// - /// - /// The backend-neutral physical key associated with this event. - /// - void AddOrUpdate( - T item, - object key - ); - - /// - /// Removes the requested value while preserving the collection's invariants. - /// - /// - /// The stored item associated with the validated handle. - /// - void Remove(T item); - - /// - /// Removes all retained entries and returns the instance to an empty reusable state. - /// - void Clear(); - - /// - /// Retrieves the requested count value from current authoritative state. - /// - /// - /// The backend-neutral physical key associated with this event. - /// - /// - /// The scalar result calculated from the supplied inputs. - /// - int GetCount(object key); - - /// - /// Attempts to get single without changing state when the operation cannot complete. - /// - /// - /// The backend-neutral physical key associated with this event. - /// - /// - /// The stored item associated with the validated handle. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - bool TryGetSingle( - object key, - out T? item - ); - - /// - /// Determines whether current state contains the requested value value. - /// - /// - /// The backend-neutral physical key associated with this event. - /// - /// - /// The stored item associated with the validated handle. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - bool Contains( - object key, - T item - ); - - /// - /// Retrieves the requested set value from current authoritative state. - /// - /// - /// The backend-neutral physical key associated with this event. - /// - /// - /// The validated hash sett? that represents the completed operation. - /// - HashSet? GetSet(object key); -} - internal sealed class IndexedObjectIndex : IIndexedObjectIndex where T : class where TKey : notnull diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs index 6be828dd5..832e3bb6d 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectKey.cs @@ -3,26 +3,6 @@ namespace Inno.Core.Collections; -/// -/// Defines indexing and cardinality behavior for an object-store key. -/// -[Flags] -public enum IndexedObjectKeyFlags -{ - /// - /// Uses hash-based lookup without key ordering. - /// - Unordered = 1 << 0, - /// - /// Maintains key ordering using the supplied comparer. - /// - Ordered = 1 << 1, - /// - /// Allows at most one item for each key value. - /// - Unique = 1 << 2 -} - /// /// Opaque handle used to query a key without exposing its implementation. /// @@ -66,3 +46,23 @@ public bool isValid } } } + +/// +/// Defines indexing and cardinality behavior for an object-store key. +/// +[Flags] +public enum IndexedObjectKeyFlags +{ + /// + /// Uses hash-based lookup without key ordering. + /// + Unordered = 1 << 0, + /// + /// Maintains key ordering using the supplied comparer. + /// + Ordered = 1 << 1, + /// + /// Allows at most one item for each key value. + /// + Unique = 1 << 2 +} diff --git a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs index 5f18cff75..c121b275f 100644 --- a/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs +++ b/src/foundation/core/Inno.Core.Collections/IndexedObjectStore/IndexedObjectStore.cs @@ -5,29 +5,6 @@ namespace Inno.Core.Collections; -/// -/// Internal store validation surface for IndexedObjectKey. -/// -internal interface IIndexedObjectStore -{ - /// - /// Determines whether the key belongs to a live slot in the current storage generation. - /// - /// - /// The stable identity used to locate the requested value. - /// - /// - /// The key type consumed by is valid key; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// when the requested condition is satisfied; otherwise, . - /// - bool IsValidKey( - int id, - Type keyType - ); -} - /// /// Thread-safe object store with optional query keys over stored items. /// diff --git a/src/foundation/core/Inno.Core.Coroutines/YieldInstructions/YieldInstruction.cs b/src/foundation/core/Inno.Core.Coroutines/YieldInstructions/YieldInstruction.cs index a9c6a7b8b..4bf5440b6 100644 --- a/src/foundation/core/Inno.Core.Coroutines/YieldInstructions/YieldInstruction.cs +++ b/src/foundation/core/Inno.Core.Coroutines/YieldInstructions/YieldInstruction.cs @@ -1,7 +1,5 @@ namespace Inno.Core.Coroutines; -internal delegate bool CoroutineWaitDelegate(CoroutineScheduler scheduler); - /// /// Base type for the scheduler's built-in coroutine wait instructions. /// @@ -16,3 +14,5 @@ internal abstract CoroutineWaitDelegate CreateWaiter( ulong frame ); } + +internal delegate bool CoroutineWaitDelegate(CoroutineScheduler scheduler); diff --git a/src/foundation/core/Inno.Core.Events/Events/ApplicationEvent.cs b/src/foundation/core/Inno.Core.Events/Events/ApplicationEvent.cs new file mode 100644 index 000000000..e47fc69db --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/ApplicationEvent.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Events; + +/// +/// Base class for application lifecycle events. +/// +public abstract class ApplicationEvent : Event; diff --git a/src/foundation/core/Inno.Core.Events/Events/ApplicationEvents.cs b/src/foundation/core/Inno.Core.Events/Events/ApplicationQuitEvent.cs similarity index 57% rename from src/foundation/core/Inno.Core.Events/Events/ApplicationEvents.cs rename to src/foundation/core/Inno.Core.Events/Events/ApplicationQuitEvent.cs index b401e0621..7aeeec5da 100644 --- a/src/foundation/core/Inno.Core.Events/Events/ApplicationEvents.cs +++ b/src/foundation/core/Inno.Core.Events/Events/ApplicationQuitEvent.cs @@ -1,10 +1,5 @@ namespace Inno.Core.Events; -/// -/// Base class for application lifecycle events. -/// -public abstract class ApplicationEvent : Event; - /// /// Raised when the application requests shutdown. /// diff --git a/src/foundation/core/Inno.Core.Events/Events/KeyEvent.cs b/src/foundation/core/Inno.Core.Events/Events/KeyEvent.cs new file mode 100644 index 000000000..6da42180c --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/KeyEvent.cs @@ -0,0 +1,37 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Base class for keyboard events. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The key used to initialize this instance. +/// +/// +/// The modifiers used to initialize this instance. +/// +public abstract class KeyEvent( + uint windowID, + KeyCode key, + KeyModifier modifiers = KeyModifier.None +) : Event +{ + /// + /// Gets the source window id for this event. + /// + public uint windowID { get; } = windowID; + + /// + /// Gets the key code for this keyboard event. + /// + public KeyCode key { get; } = key; + + /// + /// Gets active key modifiers for this keyboard event. + /// + public KeyModifier modifiers { get; } = modifiers; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs b/src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs deleted file mode 100644 index 5163f44f0..000000000 --- a/src/foundation/core/Inno.Core.Events/Events/KeyEvents.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System; -using Inno.Core.Input; - -namespace Inno.Core.Events; - -/// -/// Base class for keyboard events. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The key used to initialize this instance. -/// -/// -/// The modifiers used to initialize this instance. -/// -public abstract class KeyEvent( - uint windowID, - KeyCode key, - KeyModifier modifiers = KeyModifier.None -) : Event -{ - /// - /// Gets the source window id for this event. - /// - public uint windowID { get; } = windowID; - - /// - /// Gets the key code for this keyboard event. - /// - public KeyCode key { get; } = key; - - /// - /// Gets active key modifiers for this keyboard event. - /// - public KeyModifier modifiers { get; } = modifiers; -} - -/// -/// Raised when a key is pressed. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The key used to initialize this instance. -/// -/// -/// The modifiers used to initialize this instance. -/// -/// -/// The repeat used to initialize this instance. -/// -public sealed class KeyPressedEvent( - uint windowID, - KeyCode key, - KeyModifier modifiers = KeyModifier.None, - bool repeat = false -) : KeyEvent(windowID, key, modifiers) -{ - /// - /// Gets whether this key press is an auto-repeat event. - /// - public bool repeat { get; } = repeat; -} - -/// -/// Raised when a key is released. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The key used to initialize this instance. -/// -/// -/// The modifiers used to initialize this instance. -/// -public sealed class KeyReleasedEvent( - uint windowID, - KeyCode key, - KeyModifier modifiers = KeyModifier.None -) : KeyEvent(windowID, key, modifiers); - -/// -/// Raised when the platform commits UTF-8 text through keyboard, IME, or virtual-keyboard input. -/// -/// -/// The source window identifier. -/// -/// -/// The committed Unicode text. -/// -public sealed class TextInputEvent( - uint windowID, - string text -) : Event -{ - /// - /// Gets the source window identifier. - /// - public uint windowID { get; } = windowID; - - /// - /// Gets the committed Unicode text. - /// - public string text { get; } = string.IsNullOrEmpty(text) - ? throw new ArgumentException("Committed text cannot be empty.", nameof(text)) - : text; -} diff --git a/src/foundation/core/Inno.Core.Events/Events/KeyPressedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/KeyPressedEvent.cs new file mode 100644 index 000000000..b63345dd7 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/KeyPressedEvent.cs @@ -0,0 +1,31 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Raised when a key is pressed. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The key used to initialize this instance. +/// +/// +/// The modifiers used to initialize this instance. +/// +/// +/// The repeat used to initialize this instance. +/// +public sealed class KeyPressedEvent( + uint windowID, + KeyCode key, + KeyModifier modifiers = KeyModifier.None, + bool repeat = false +) : KeyEvent(windowID, key, modifiers) +{ + /// + /// Gets whether this key press is an auto-repeat event. + /// + public bool repeat { get; } = repeat; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/KeyReleasedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/KeyReleasedEvent.cs new file mode 100644 index 000000000..b088e70e7 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/KeyReleasedEvent.cs @@ -0,0 +1,21 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Raised when a key is released. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The key used to initialize this instance. +/// +/// +/// The modifiers used to initialize this instance. +/// +public sealed class KeyReleasedEvent( + uint windowID, + KeyCode key, + KeyModifier modifiers = KeyModifier.None +) : KeyEvent(windowID, key, modifiers); diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseButtonEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseButtonEvent.cs new file mode 100644 index 000000000..de1171e9f --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseButtonEvent.cs @@ -0,0 +1,23 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Base class for mouse button events. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The button used to initialize this instance. +/// +public abstract class MouseButtonEvent( + uint windowID, + MouseButton button +) : MouseEvent(windowID) +{ + /// + /// Gets the mouse button for this event. + /// + public MouseButton button { get; } = button; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseButtonPressedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseButtonPressedEvent.cs new file mode 100644 index 000000000..dc13fd7df --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseButtonPressedEvent.cs @@ -0,0 +1,17 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Raised when a mouse button is pressed. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The button used to initialize this instance. +/// +public sealed class MouseButtonPressedEvent( + uint windowID, + MouseButton button +) : MouseButtonEvent(windowID, button); diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseButtonReleasedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseButtonReleasedEvent.cs new file mode 100644 index 000000000..e183ac3fd --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseButtonReleasedEvent.cs @@ -0,0 +1,17 @@ +using Inno.Core.Input; + +namespace Inno.Core.Events; + +/// +/// Raised when a mouse button is released. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The button used to initialize this instance. +/// +public sealed class MouseButtonReleasedEvent( + uint windowID, + MouseButton button +) : MouseButtonEvent(windowID, button); diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseEvent.cs new file mode 100644 index 000000000..4d6623f47 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseEvent.cs @@ -0,0 +1,38 @@ +namespace Inno.Core.Events; + +/// +/// Base class for mouse events. +/// +public abstract class MouseEvent : Event +{ + /// + /// Creates an independent mouse event belonging to one platform window. + /// + /// + /// The platform window that produced the event. + /// + protected MouseEvent(uint windowID) + { + this.windowID = windowID; + } + + /// + /// Creates a routed mouse event sharing its source's window and global consumption. + /// + /// + /// The mouse event whose input lifetime remains authoritative. + /// + /// + /// The source event is null. + /// + protected MouseEvent(MouseEvent source) + : base(source) + { + this.windowID = source.windowID; + } + + /// + /// Gets the source window id for this event. + /// + public uint windowID { get; } +} diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs b/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs deleted file mode 100644 index 13c333789..000000000 --- a/src/foundation/core/Inno.Core.Events/Events/MouseEvents.cs +++ /dev/null @@ -1,182 +0,0 @@ -using Inno.Core.Input; - -namespace Inno.Core.Events; - -/// -/// Base class for mouse events. -/// -public abstract class MouseEvent : Event -{ - /// - /// Creates an independent mouse event belonging to one platform window. - /// - /// - /// The platform window that produced the event. - /// - protected MouseEvent(uint windowID) - { - this.windowID = windowID; - } - - /// - /// Creates a routed mouse event sharing its source's window and global consumption. - /// - /// - /// The mouse event whose input lifetime remains authoritative. - /// - /// - /// The source event is null. - /// - protected MouseEvent(MouseEvent source) - : base(source) - { - this.windowID = source.windowID; - } - - /// - /// Gets the source window id for this event. - /// - public uint windowID { get; } -} - -/// -/// Raised when the cursor moves. -/// -public sealed class MouseMovedEvent : MouseEvent -{ - /// - /// Creates a pointer movement in platform-window coordinates. - /// - /// - /// The platform window that produced the movement. - /// - /// - /// The horizontal pointer coordinate in logical pixels. - /// - /// - /// The vertical pointer coordinate in logical pixels. - /// - public MouseMovedEvent( - uint windowID, - float x, - float y - ) : base(windowID) - { - this.x = x; - this.y = y; - } - - private MouseMovedEvent( - MouseMovedEvent source, - float x, - float y - ) : base(source) - { - this.x = x; - this.y = y; - } - - /// - /// Gets cursor X coordinate. - /// - public float x { get; } - - /// - /// Gets cursor Y coordinate. - /// - public float y { get; } - - /// - /// Repositions this movement without starting a new global consumption lifetime. - /// - /// - /// The routed horizontal coordinate in logical pixels. - /// - /// - /// The routed vertical coordinate in logical pixels. - /// - /// - /// A new coordinate representation sharing global consumption with this movement. - /// - public MouseMovedEvent WithPosition( - float x, - float y - ) => new(this, x, y); -} - -/// -/// Raised when mouse wheel scrolls. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The offset x used to initialize this instance. -/// -/// -/// The offset y used to initialize this instance. -/// -public sealed class MouseScrolledEvent( - uint windowID, - float offsetX, - float offsetY -) : MouseEvent(windowID) -{ - /// - /// Gets horizontal scroll offset. - /// - public float offsetX { get; } = offsetX; - - /// - /// Gets vertical scroll offset. - /// - public float offsetY { get; } = offsetY; -} - -/// -/// Base class for mouse button events. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The button used to initialize this instance. -/// -public abstract class MouseButtonEvent( - uint windowID, - MouseButton button -) : MouseEvent(windowID) -{ - /// - /// Gets the mouse button for this event. - /// - public MouseButton button { get; } = button; -} - -/// -/// Raised when a mouse button is pressed. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The button used to initialize this instance. -/// -public sealed class MouseButtonPressedEvent( - uint windowID, - MouseButton button -) : MouseButtonEvent(windowID, button); - -/// -/// Raised when a mouse button is released. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The button used to initialize this instance. -/// -public sealed class MouseButtonReleasedEvent( - uint windowID, - MouseButton button -) : MouseButtonEvent(windowID, button); diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseMovedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseMovedEvent.cs new file mode 100644 index 000000000..81a0c2324 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseMovedEvent.cs @@ -0,0 +1,66 @@ +namespace Inno.Core.Events; + +/// +/// Raised when the cursor moves. +/// +public sealed class MouseMovedEvent : MouseEvent +{ + /// + /// Creates a pointer movement in platform-window coordinates. + /// + /// + /// The platform window that produced the movement. + /// + /// + /// The horizontal pointer coordinate in logical pixels. + /// + /// + /// The vertical pointer coordinate in logical pixels. + /// + public MouseMovedEvent( + uint windowID, + float x, + float y + ) : base(windowID) + { + this.x = x; + this.y = y; + } + + private MouseMovedEvent( + MouseMovedEvent source, + float x, + float y + ) : base(source) + { + this.x = x; + this.y = y; + } + + /// + /// Gets cursor X coordinate. + /// + public float x { get; } + + /// + /// Gets cursor Y coordinate. + /// + public float y { get; } + + /// + /// Repositions this movement without starting a new global consumption lifetime. + /// + /// + /// The routed horizontal coordinate in logical pixels. + /// + /// + /// The routed vertical coordinate in logical pixels. + /// + /// + /// A new coordinate representation sharing global consumption with this movement. + /// + public MouseMovedEvent WithPosition( + float x, + float y + ) => new(this, x, y); +} diff --git a/src/foundation/core/Inno.Core.Events/Events/MouseScrolledEvent.cs b/src/foundation/core/Inno.Core.Events/Events/MouseScrolledEvent.cs new file mode 100644 index 000000000..f1b43f3c9 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/MouseScrolledEvent.cs @@ -0,0 +1,30 @@ +namespace Inno.Core.Events; + +/// +/// Raised when mouse wheel scrolls. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The offset x used to initialize this instance. +/// +/// +/// The offset y used to initialize this instance. +/// +public sealed class MouseScrolledEvent( + uint windowID, + float offsetX, + float offsetY +) : MouseEvent(windowID) +{ + /// + /// Gets horizontal scroll offset. + /// + public float offsetX { get; } = offsetX; + + /// + /// Gets vertical scroll offset. + /// + public float offsetY { get; } = offsetY; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/TextInputEvent.cs b/src/foundation/core/Inno.Core.Events/Events/TextInputEvent.cs new file mode 100644 index 000000000..a6b762e6f --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/TextInputEvent.cs @@ -0,0 +1,30 @@ +using System; + +namespace Inno.Core.Events; + +/// +/// Raised when the platform commits UTF-8 text through keyboard, IME, or virtual-keyboard input. +/// +/// +/// The source window identifier. +/// +/// +/// The committed Unicode text. +/// +public sealed class TextInputEvent( + uint windowID, + string text +) : Event +{ + /// + /// Gets the source window identifier. + /// + public uint windowID { get; } = windowID; + + /// + /// Gets the committed Unicode text. + /// + public string text { get; } = string.IsNullOrEmpty(text) + ? throw new ArgumentException("Committed text cannot be empty.", nameof(text)) + : text; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowCloseEvent.cs b/src/foundation/core/Inno.Core.Events/Events/WindowCloseEvent.cs new file mode 100644 index 000000000..b71ac02bb --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/WindowCloseEvent.cs @@ -0,0 +1,9 @@ +namespace Inno.Core.Events; + +/// +/// Raised when the window requests close. +/// +/// +/// The window id used to initialize this instance. +/// +public sealed class WindowCloseEvent(uint windowID) : WindowEvent(windowID); diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowEvent.cs b/src/foundation/core/Inno.Core.Events/Events/WindowEvent.cs new file mode 100644 index 000000000..1417e4308 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/WindowEvent.cs @@ -0,0 +1,15 @@ +namespace Inno.Core.Events; + +/// +/// Base class for window lifecycle events. +/// +/// +/// The window id used to initialize this instance. +/// +public abstract class WindowEvent(uint windowID) : Event +{ + /// + /// Gets the source window id for this event. + /// + public uint windowID { get; } = windowID; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs b/src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs deleted file mode 100644 index d8a13eaab..000000000 --- a/src/foundation/core/Inno.Core.Events/Events/WindowEvents.cs +++ /dev/null @@ -1,72 +0,0 @@ -namespace Inno.Core.Events; - -/// -/// Base class for window lifecycle events. -/// -/// -/// The window id used to initialize this instance. -/// -public abstract class WindowEvent(uint windowID) : Event -{ - /// - /// Gets the source window id for this event. - /// - public uint windowID { get; } = windowID; -} - -/// -/// Raised when the window size changes. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The width in logical units or pixels required by this operation. -/// -/// -/// The height in logical units or pixels required by this operation. -/// -public sealed class WindowResizeEvent( - uint windowID, - int width, - int height -) : WindowEvent(windowID) -{ - /// - /// Gets the new window width. - /// - public int width { get; } = width; - - /// - /// Gets the new window height. - /// - public int height { get; } = height; -} - -/// -/// Raised when the window requests close. -/// -/// -/// The window id used to initialize this instance. -/// -public sealed class WindowCloseEvent(uint windowID) : WindowEvent(windowID); - -/// -/// Raised when a window gains or loses input focus. -/// -/// -/// The window id used to initialize this instance. -/// -/// -/// The is focused used to initialize this instance. -/// -public sealed class WindowFocusChangedEvent( - uint windowID, - bool isFocused -) : WindowEvent(windowID) -{ - /// - /// Gets whether the window has input focus after the change. - /// - public bool isFocused { get; } = isFocused; -} diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowFocusChangedEvent.cs b/src/foundation/core/Inno.Core.Events/Events/WindowFocusChangedEvent.cs new file mode 100644 index 000000000..f11fe4035 --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/WindowFocusChangedEvent.cs @@ -0,0 +1,21 @@ +namespace Inno.Core.Events; + +/// +/// Raised when a window gains or loses input focus. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The is focused used to initialize this instance. +/// +public sealed class WindowFocusChangedEvent( + uint windowID, + bool isFocused +) : WindowEvent(windowID) +{ + /// + /// Gets whether the window has input focus after the change. + /// + public bool isFocused { get; } = isFocused; +} diff --git a/src/foundation/core/Inno.Core.Events/Events/WindowResizeEvent.cs b/src/foundation/core/Inno.Core.Events/Events/WindowResizeEvent.cs new file mode 100644 index 000000000..983d7bc1a --- /dev/null +++ b/src/foundation/core/Inno.Core.Events/Events/WindowResizeEvent.cs @@ -0,0 +1,30 @@ +namespace Inno.Core.Events; + +/// +/// Raised when the window size changes. +/// +/// +/// The window id used to initialize this instance. +/// +/// +/// The width in logical units or pixels required by this operation. +/// +/// +/// The height in logical units or pixels required by this operation. +/// +public sealed class WindowResizeEvent( + uint windowID, + int width, + int height +) : WindowEvent(windowID) +{ + /// + /// Gets the new window width. + /// + public int width { get; } = width; + + /// + /// Gets the new window height. + /// + public int height { get; } = height; +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphDefinitions.cs b/src/foundation/core/Inno.Core.Graphs/GraphDefinitions.cs deleted file mode 100644 index 08861ef78..000000000 --- a/src/foundation/core/Inno.Core.Graphs/GraphDefinitions.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Inno.Core.Graphs; - -/// -/// Declares the direction in which values flow through a graph port. -/// -public enum GraphPortDirection -{ - /// - /// Receives a value from another node. - /// - Input, - /// - /// Produces a value for another node. - /// - Output -} - -/// -/// Declares how many edges may connect to a graph port. -/// -public enum GraphPortCapacity -{ - /// - /// At most one edge may connect to the port. - /// - Single, - /// - /// Any number of edges may connect to the port. - /// - Multiple -} - -/// -/// Describes one dynamically or statically resolved node port. -/// -public sealed class GraphPortDefinition -{ - /// - /// Creates a graph port definition. - /// - /// - /// Stable node-local port identifier. - /// - /// - /// Artist-facing display name. - /// - /// - /// Stable value type identifier. - /// - /// - /// Value-flow direction. - /// - /// - /// Allowed edge capacity. - /// - /// - /// Whether an input must be connected. - /// - public GraphPortDefinition( - GraphPortID id, - string displayName, - string valueTypeID, - GraphPortDirection direction, - GraphPortCapacity capacity = GraphPortCapacity.Single, - bool required = false - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(displayName); - ArgumentException.ThrowIfNullOrWhiteSpace(valueTypeID); - this.id = id; - this.displayName = displayName; - this.valueTypeID = valueTypeID; - this.direction = direction; - this.capacity = capacity; - this.required = required; - } - - /// - /// Gets the stable node-local port identifier. - /// - public GraphPortID id { get; } - - /// - /// Gets the artist-facing display name. - /// - public string displayName { get; } - - /// - /// Gets the stable value type identifier. - /// - public string valueTypeID { get; } - - /// - /// Gets the value-flow direction. - /// - public GraphPortDirection direction { get; } - - /// - /// Gets the allowed edge capacity. - /// - public GraphPortCapacity capacity { get; } - - /// - /// Gets whether an input must be connected. - /// - public bool required { get; } -} - -/// -/// Describes node presentation and resolves ports without entering graph persistence. -/// -public abstract class GraphNodeDefinition -{ - /// - /// Creates a graph node definition. - /// - /// - /// Globally stable definition identifier. - /// - /// - /// Artist-facing display name. - /// - /// - /// Search-menu category path. - /// - protected GraphNodeDefinition( - string id, - string displayName, - string category - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentException.ThrowIfNullOrWhiteSpace(displayName); - ArgumentException.ThrowIfNullOrWhiteSpace(category); - this.id = id; - this.displayName = displayName; - this.category = category; - } - - /// - /// Gets the globally stable definition identifier. - /// - public string id { get; } - - /// - /// Gets the artist-facing display name. - /// - public string displayName { get; } - - /// - /// Gets the search-menu category path. - /// - public string category { get; } - - /// - /// Resolves ports for one node record, including any data-driven dynamic ports. - /// - /// - /// Neutral node record to inspect. - /// - /// - /// The complete port definitions for the current node state. - /// - public abstract IReadOnlyList GetPorts(GraphNodeRecord node); -} - -/// -/// Resolves generation-scoped node definitions by stable identifier. -/// -public interface IGraphNodeDefinitionResolver -{ - /// - /// Tries to resolve an active node definition. - /// - /// - /// Stable definition identifier. - /// - /// - /// Receives the generation-scoped definition. - /// - /// - /// when active; otherwise . - /// - bool TryResolve( - string definitionID, - out GraphNodeDefinition? definition - ); -} - -/// -/// Determines whether one graph value type can be converted to another. -/// -public interface IGraphTypeConversion -{ - /// - /// Tests a directed value conversion. - /// - /// - /// Source value type identifier. - /// - /// - /// Destination value type identifier. - /// - /// - /// when the conversion is valid; otherwise . - /// - bool CanConvert( - string sourceTypeID, - string destinationTypeID - ); -} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphDiagnostic.cs b/src/foundation/core/Inno.Core.Graphs/GraphDiagnostic.cs new file mode 100644 index 000000000..51a58650f --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphDiagnostic.cs @@ -0,0 +1,69 @@ +using System; +using Inno.Core.Diagnostics; + +namespace Inno.Core.Graphs; + +/// +/// Reports one graph validation problem using stable document identifiers. +/// +public sealed class GraphDiagnostic +{ + /// + /// Creates a graph diagnostic. + /// + /// + /// Stable machine-readable diagnostic code. + /// + /// + /// Artist-facing diagnostic text. + /// + /// + /// Diagnostic impact. + /// + /// + /// Optional related node identifier. + /// + /// + /// Optional related edge identifier. + /// + public GraphDiagnostic( + string code, + string message, + DiagnosticSeverity severity, + GraphNodeID? nodeID = null, + GraphEdgeID? edgeID = null + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(code); + ArgumentException.ThrowIfNullOrWhiteSpace(message); + this.code = code; + this.message = message; + this.severity = severity; + this.nodeID = nodeID; + this.edgeID = edgeID; + } + + /// + /// Gets the stable machine-readable diagnostic code. + /// + public string code { get; } + + /// + /// Gets the artist-facing diagnostic text. + /// + public string message { get; } + + /// + /// Gets the diagnostic impact. + /// + public DiagnosticSeverity severity { get; } + + /// + /// Gets the related node identifier, if any. + /// + public GraphNodeID? nodeID { get; } + + /// + /// Gets the related edge identifier, if any. + /// + public GraphEdgeID? edgeID { get; } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs b/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs index 92c18250f..74fddfdd0 100644 --- a/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs +++ b/src/foundation/core/Inno.Core.Graphs/GraphDocument.cs @@ -4,183 +4,6 @@ namespace Inno.Core.Graphs; -/// -/// Stores one node without retaining a CLR type or runtime extension instance. -/// -public sealed class GraphNodeRecord -{ - private readonly Dictionary m_values = new(StringComparer.Ordinal); - private readonly ReadOnlyDictionary m_valueView; - - /// - /// Creates a graph node record. - /// - /// - /// Stable identifier within the document. - /// - /// - /// Stable node definition identifier. - /// - public GraphNodeRecord( - GraphNodeID id, - string definitionID - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(definitionID); - this.id = id; - this.definitionID = definitionID; - m_valueView = new(m_values); - } - - /// - /// Gets the stable node identifier. - /// - public GraphNodeID id { get; } - - /// - /// Gets the stable node definition identifier. - /// - public string definitionID { get; } - - /// - /// Gets or sets the graph-space node position. - /// - public GraphPosition position { get; set; } - - /// - /// Gets neutral serialized property values keyed by stable property identifier. - /// - public IReadOnlyDictionary values => m_valueView; - - /// - /// Creates or replaces a neutral serialized property value. - /// - /// - /// Stable property identifier. - /// - /// - /// Serialized value. - /// - public void SetValue( - string propertyID, - GraphSerializedValue value - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); - ArgumentNullException.ThrowIfNull(value); - m_values[propertyID] = value; - } - - /// - /// Tries to read a neutral serialized property value. - /// - /// - /// Stable property identifier. - /// - /// - /// Receives the value when present. - /// - /// - /// when the property exists; otherwise . - /// - public bool TryGetValue( - string propertyID, - out GraphSerializedValue? value - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); - return m_values.TryGetValue(propertyID, out value); - } - - /// - /// Removes a neutral serialized property value. - /// - /// - /// Stable property identifier. - /// - /// - /// when a property was removed; otherwise . - /// - public bool RemoveValue(string propertyID) - { - ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); - return m_values.Remove(propertyID); - } -} - -/// -/// Identifies one endpoint of a graph edge. -/// -public readonly record struct GraphEndpoint -{ - /// - /// Creates a graph edge endpoint. - /// - /// - /// Owning node identifier. - /// - /// - /// Port identifier within the node definition. - /// - public GraphEndpoint( - GraphNodeID nodeID, - GraphPortID portID - ) { - this.nodeID = nodeID; - this.portID = portID; - } - - /// - /// Gets the owning node identifier. - /// - public GraphNodeID nodeID { get; } - - /// - /// Gets the node-local port identifier. - /// - public GraphPortID portID { get; } -} - -/// -/// Stores one typed connection between two graph endpoints. -/// -public sealed class GraphEdgeRecord -{ - /// - /// Creates a graph edge record. - /// - /// - /// Stable edge identifier within the document. - /// - /// - /// Source endpoint. - /// - /// - /// Destination endpoint. - /// - public GraphEdgeRecord( - GraphEdgeID id, - GraphEndpoint output, - GraphEndpoint input - ) { - this.id = id; - this.output = output; - this.input = input; - } - - /// - /// Gets the stable edge identifier. - /// - public GraphEdgeID id { get; } - - /// - /// Gets the source endpoint. - /// - public GraphEndpoint output { get; } - - /// - /// Gets the destination endpoint. - /// - public GraphEndpoint input { get; } -} - /// /// Owns neutral graph records and graph-level canvas metadata. /// diff --git a/src/foundation/core/Inno.Core.Graphs/GraphEdgeID.cs b/src/foundation/core/Inno.Core.Graphs/GraphEdgeID.cs new file mode 100644 index 000000000..e99d635a2 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphEdgeID.cs @@ -0,0 +1,37 @@ +using System; + +namespace Inno.Core.Graphs; + +/// +/// Identifies an edge within one graph document using a stable serialized value. +/// +public readonly record struct GraphEdgeID +{ + /// + /// Creates a stable graph edge identifier. + /// + /// + /// Non-empty identifier value. + /// + /// + /// Thrown when is empty. + /// + public GraphEdgeID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the serialized identifier value. + /// + public string value { get; } + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphEdgeRecord.cs b/src/foundation/core/Inno.Core.Graphs/GraphEdgeRecord.cs new file mode 100644 index 000000000..7811ecbde --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphEdgeRecord.cs @@ -0,0 +1,44 @@ +namespace Inno.Core.Graphs; + +/// +/// Stores one typed connection between two graph endpoints. +/// +public sealed class GraphEdgeRecord +{ + /// + /// Creates a graph edge record. + /// + /// + /// Stable edge identifier within the document. + /// + /// + /// Source endpoint. + /// + /// + /// Destination endpoint. + /// + public GraphEdgeRecord( + GraphEdgeID id, + GraphEndpoint output, + GraphEndpoint input + ) { + this.id = id; + this.output = output; + this.input = input; + } + + /// + /// Gets the stable edge identifier. + /// + public GraphEdgeID id { get; } + + /// + /// Gets the source endpoint. + /// + public GraphEndpoint output { get; } + + /// + /// Gets the destination endpoint. + /// + public GraphEndpoint input { get; } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphEndpoint.cs b/src/foundation/core/Inno.Core.Graphs/GraphEndpoint.cs new file mode 100644 index 000000000..111ea7a4c --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphEndpoint.cs @@ -0,0 +1,34 @@ +namespace Inno.Core.Graphs; + +/// +/// Identifies one endpoint of a graph edge. +/// +public readonly record struct GraphEndpoint +{ + /// + /// Creates a graph edge endpoint. + /// + /// + /// Owning node identifier. + /// + /// + /// Port identifier within the node definition. + /// + public GraphEndpoint( + GraphNodeID nodeID, + GraphPortID portID + ) { + this.nodeID = nodeID; + this.portID = portID; + } + + /// + /// Gets the owning node identifier. + /// + public GraphNodeID nodeID { get; } + + /// + /// Gets the node-local port identifier. + /// + public GraphPortID portID { get; } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphIDs.cs b/src/foundation/core/Inno.Core.Graphs/GraphIDs.cs deleted file mode 100644 index 350d6d313..000000000 --- a/src/foundation/core/Inno.Core.Graphs/GraphIDs.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System; - -namespace Inno.Core.Graphs; - -/// -/// Identifies a node within one graph document using a stable serialized value. -/// -public readonly record struct GraphNodeID -{ - /// - /// Creates a stable graph node identifier. - /// - /// - /// Non-empty identifier value. - /// - /// - /// Thrown when is empty. - /// - public GraphNodeID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the serialized identifier value. - /// - public string value { get; } - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} - -/// -/// Identifies an edge within one graph document using a stable serialized value. -/// -public readonly record struct GraphEdgeID -{ - /// - /// Creates a stable graph edge identifier. - /// - /// - /// Non-empty identifier value. - /// - /// - /// Thrown when is empty. - /// - public GraphEdgeID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the serialized identifier value. - /// - public string value { get; } - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} - -/// -/// Identifies a port within its owning node definition. -/// -public readonly record struct GraphPortID -{ - /// - /// Creates a stable graph port identifier. - /// - /// - /// Non-empty identifier value. - /// - /// - /// Thrown when is empty. - /// - public GraphPortID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the serialized identifier value. - /// - public string value { get; } - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} - -/// -/// Stores a graph-space position independently from any editor UI framework. -/// -public readonly record struct GraphPosition -{ - /// - /// Creates a graph-space position. - /// - /// - /// Horizontal graph-space coordinate. - /// - /// - /// Vertical graph-space coordinate. - /// - public GraphPosition( - float x, - float y - ) { - this.x = x; - this.y = y; - } - - /// - /// Gets the horizontal graph-space coordinate. - /// - public float x { get; } - - /// - /// Gets the vertical graph-space coordinate. - /// - public float y { get; } -} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphNodeDefinition.cs b/src/foundation/core/Inno.Core.Graphs/GraphNodeDefinition.cs new file mode 100644 index 000000000..acaf7c84b --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphNodeDefinition.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Core.Graphs; + +/// +/// Describes node presentation and resolves ports without entering graph persistence. +/// +public abstract class GraphNodeDefinition +{ + /// + /// Creates a graph node definition. + /// + /// + /// Globally stable definition identifier. + /// + /// + /// Artist-facing display name. + /// + /// + /// Search-menu category path. + /// + protected GraphNodeDefinition( + string id, + string displayName, + string category + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentException.ThrowIfNullOrWhiteSpace(displayName); + ArgumentException.ThrowIfNullOrWhiteSpace(category); + this.id = id; + this.displayName = displayName; + this.category = category; + } + + /// + /// Gets the globally stable definition identifier. + /// + public string id { get; } + + /// + /// Gets the artist-facing display name. + /// + public string displayName { get; } + + /// + /// Gets the search-menu category path. + /// + public string category { get; } + + /// + /// Resolves ports for one node record, including any data-driven dynamic ports. + /// + /// + /// Neutral node record to inspect. + /// + /// + /// The complete port definitions for the current node state. + /// + public abstract IReadOnlyList GetPorts(GraphNodeRecord node); +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphNodeID.cs b/src/foundation/core/Inno.Core.Graphs/GraphNodeID.cs new file mode 100644 index 000000000..93801570a --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphNodeID.cs @@ -0,0 +1,37 @@ +using System; + +namespace Inno.Core.Graphs; + +/// +/// Identifies a node within one graph document using a stable serialized value. +/// +public readonly record struct GraphNodeID +{ + /// + /// Creates a stable graph node identifier. + /// + /// + /// Non-empty identifier value. + /// + /// + /// Thrown when is empty. + /// + public GraphNodeID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the serialized identifier value. + /// + public string value { get; } + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphNodeRecord.cs b/src/foundation/core/Inno.Core.Graphs/GraphNodeRecord.cs new file mode 100644 index 000000000..7d508e88d --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphNodeRecord.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.Core.Graphs; + +/// +/// Stores one node without retaining a CLR type or runtime extension instance. +/// +public sealed class GraphNodeRecord +{ + private readonly Dictionary m_values = new(StringComparer.Ordinal); + private readonly ReadOnlyDictionary m_valueView; + + /// + /// Creates a graph node record. + /// + /// + /// Stable identifier within the document. + /// + /// + /// Stable node definition identifier. + /// + public GraphNodeRecord( + GraphNodeID id, + string definitionID + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(definitionID); + this.id = id; + this.definitionID = definitionID; + m_valueView = new(m_values); + } + + /// + /// Gets the stable node identifier. + /// + public GraphNodeID id { get; } + + /// + /// Gets the stable node definition identifier. + /// + public string definitionID { get; } + + /// + /// Gets or sets the graph-space node position. + /// + public GraphPosition position { get; set; } + + /// + /// Gets neutral serialized property values keyed by stable property identifier. + /// + public IReadOnlyDictionary values => m_valueView; + + /// + /// Creates or replaces a neutral serialized property value. + /// + /// + /// Stable property identifier. + /// + /// + /// Serialized value. + /// + public void SetValue( + string propertyID, + GraphSerializedValue value + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); + ArgumentNullException.ThrowIfNull(value); + m_values[propertyID] = value; + } + + /// + /// Tries to read a neutral serialized property value. + /// + /// + /// Stable property identifier. + /// + /// + /// Receives the value when present. + /// + /// + /// when the property exists; otherwise . + /// + public bool TryGetValue( + string propertyID, + out GraphSerializedValue? value + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); + return m_values.TryGetValue(propertyID, out value); + } + + /// + /// Removes a neutral serialized property value. + /// + /// + /// Stable property identifier. + /// + /// + /// when a property was removed; otherwise . + /// + public bool RemoveValue(string propertyID) + { + ArgumentException.ThrowIfNullOrWhiteSpace(propertyID); + return m_values.Remove(propertyID); + } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphPortCapacity.cs b/src/foundation/core/Inno.Core.Graphs/GraphPortCapacity.cs new file mode 100644 index 000000000..8d2264cf3 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphPortCapacity.cs @@ -0,0 +1,16 @@ +namespace Inno.Core.Graphs; + +/// +/// Declares how many edges may connect to a graph port. +/// +public enum GraphPortCapacity +{ + /// + /// At most one edge may connect to the port. + /// + Single, + /// + /// Any number of edges may connect to the port. + /// + Multiple +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphPortDefinition.cs b/src/foundation/core/Inno.Core.Graphs/GraphPortDefinition.cs new file mode 100644 index 000000000..d86a54848 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphPortDefinition.cs @@ -0,0 +1,78 @@ +using System; + +namespace Inno.Core.Graphs; + +/// +/// Describes one dynamically or statically resolved node port. +/// +public sealed class GraphPortDefinition +{ + /// + /// Creates a graph port definition. + /// + /// + /// Stable node-local port identifier. + /// + /// + /// Artist-facing display name. + /// + /// + /// Stable value type identifier. + /// + /// + /// Value-flow direction. + /// + /// + /// Allowed edge capacity. + /// + /// + /// Whether an input must be connected. + /// + public GraphPortDefinition( + GraphPortID id, + string displayName, + string valueTypeID, + GraphPortDirection direction, + GraphPortCapacity capacity = GraphPortCapacity.Single, + bool required = false + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(displayName); + ArgumentException.ThrowIfNullOrWhiteSpace(valueTypeID); + this.id = id; + this.displayName = displayName; + this.valueTypeID = valueTypeID; + this.direction = direction; + this.capacity = capacity; + this.required = required; + } + + /// + /// Gets the stable node-local port identifier. + /// + public GraphPortID id { get; } + + /// + /// Gets the artist-facing display name. + /// + public string displayName { get; } + + /// + /// Gets the stable value type identifier. + /// + public string valueTypeID { get; } + + /// + /// Gets the value-flow direction. + /// + public GraphPortDirection direction { get; } + + /// + /// Gets the allowed edge capacity. + /// + public GraphPortCapacity capacity { get; } + + /// + /// Gets whether an input must be connected. + /// + public bool required { get; } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphPortDirection.cs b/src/foundation/core/Inno.Core.Graphs/GraphPortDirection.cs new file mode 100644 index 000000000..839df0ee6 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphPortDirection.cs @@ -0,0 +1,16 @@ +namespace Inno.Core.Graphs; + +/// +/// Declares the direction in which values flow through a graph port. +/// +public enum GraphPortDirection +{ + /// + /// Receives a value from another node. + /// + Input, + /// + /// Produces a value for another node. + /// + Output +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphPortID.cs b/src/foundation/core/Inno.Core.Graphs/GraphPortID.cs new file mode 100644 index 000000000..409bf8938 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphPortID.cs @@ -0,0 +1,37 @@ +using System; + +namespace Inno.Core.Graphs; + +/// +/// Identifies a port within its owning node definition. +/// +public readonly record struct GraphPortID +{ + /// + /// Creates a stable graph port identifier. + /// + /// + /// Non-empty identifier value. + /// + /// + /// Thrown when is empty. + /// + public GraphPortID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the serialized identifier value. + /// + public string value { get; } + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphPosition.cs b/src/foundation/core/Inno.Core.Graphs/GraphPosition.cs new file mode 100644 index 000000000..4f9f9a7d8 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphPosition.cs @@ -0,0 +1,34 @@ +namespace Inno.Core.Graphs; + +/// +/// Stores a graph-space position independently from any editor UI framework. +/// +public readonly record struct GraphPosition +{ + /// + /// Creates a graph-space position. + /// + /// + /// Horizontal graph-space coordinate. + /// + /// + /// Vertical graph-space coordinate. + /// + public GraphPosition( + float x, + float y + ) { + this.x = x; + this.y = y; + } + + /// + /// Gets the horizontal graph-space coordinate. + /// + public float x { get; } + + /// + /// Gets the vertical graph-space coordinate. + /// + public float y { get; } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphValidationResult.cs b/src/foundation/core/Inno.Core.Graphs/GraphValidationResult.cs new file mode 100644 index 000000000..98ced9e75 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/GraphValidationResult.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Diagnostics; + +namespace Inno.Core.Graphs; + +/// +/// Contains deterministic graph validation diagnostics. +/// +public sealed class GraphValidationResult +{ + private readonly IReadOnlyList m_diagnostics; + + /// + /// Creates a graph validation result. + /// + /// + /// Diagnostics in deterministic validation order. + /// + public GraphValidationResult(IReadOnlyList diagnostics) + { + ArgumentNullException.ThrowIfNull(diagnostics); + m_diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets diagnostics in deterministic validation order. + /// + public IReadOnlyList diagnostics => m_diagnostics; + + /// + /// Gets whether no error diagnostic is present. + /// + public bool isValid + { + get + { + foreach (GraphDiagnostic diagnostic in m_diagnostics) + { + if (diagnostic.severity == DiagnosticSeverity.Error) + { + return false; + } + } + + return true; + } + } +} diff --git a/src/foundation/core/Inno.Core.Graphs/GraphValidation.cs b/src/foundation/core/Inno.Core.Graphs/GraphValidator.cs similarity index 78% rename from src/foundation/core/Inno.Core.Graphs/GraphValidation.cs rename to src/foundation/core/Inno.Core.Graphs/GraphValidator.cs index 61584bb1d..d8900e956 100644 --- a/src/foundation/core/Inno.Core.Graphs/GraphValidation.cs +++ b/src/foundation/core/Inno.Core.Graphs/GraphValidator.cs @@ -1,120 +1,10 @@ using System; using System.Collections.Generic; -using System.Linq; using Inno.Core.Collections; using Inno.Core.Diagnostics; namespace Inno.Core.Graphs; -/// -/// Reports one graph validation problem using stable document identifiers. -/// -public sealed class GraphDiagnostic -{ - /// - /// Creates a graph diagnostic. - /// - /// - /// Stable machine-readable diagnostic code. - /// - /// - /// Artist-facing diagnostic text. - /// - /// - /// Diagnostic impact. - /// - /// - /// Optional related node identifier. - /// - /// - /// Optional related edge identifier. - /// - public GraphDiagnostic( - string code, - string message, - DiagnosticSeverity severity, - GraphNodeID? nodeID = null, - GraphEdgeID? edgeID = null - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(code); - ArgumentException.ThrowIfNullOrWhiteSpace(message); - this.code = code; - this.message = message; - this.severity = severity; - this.nodeID = nodeID; - this.edgeID = edgeID; - } - - /// - /// Gets the stable machine-readable diagnostic code. - /// - public string code { get; } - - /// - /// Gets the artist-facing diagnostic text. - /// - public string message { get; } - - /// - /// Gets the diagnostic impact. - /// - public DiagnosticSeverity severity { get; } - - /// - /// Gets the related node identifier, if any. - /// - public GraphNodeID? nodeID { get; } - - /// - /// Gets the related edge identifier, if any. - /// - public GraphEdgeID? edgeID { get; } -} - -/// -/// Contains deterministic graph validation diagnostics. -/// -public sealed class GraphValidationResult -{ - private readonly IReadOnlyList m_diagnostics; - - /// - /// Creates a graph validation result. - /// - /// - /// Diagnostics in deterministic validation order. - /// - public GraphValidationResult(IReadOnlyList diagnostics) - { - ArgumentNullException.ThrowIfNull(diagnostics); - m_diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - - /// - /// Gets diagnostics in deterministic validation order. - /// - public IReadOnlyList diagnostics => m_diagnostics; - - /// - /// Gets whether no error diagnostic is present. - /// - public bool isValid - { - get - { - foreach (GraphDiagnostic diagnostic in m_diagnostics) - { - if (diagnostic.severity == DiagnosticSeverity.Error) - { - return false; - } - } - - return true; - } - } -} - /// /// Validates neutral graph topology against generation-scoped node definitions. /// diff --git a/src/foundation/core/Inno.Core.Graphs/IGraphNodeDefinitionResolver.cs b/src/foundation/core/Inno.Core.Graphs/IGraphNodeDefinitionResolver.cs new file mode 100644 index 000000000..67acad2f2 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/IGraphNodeDefinitionResolver.cs @@ -0,0 +1,24 @@ +namespace Inno.Core.Graphs; + +/// +/// Resolves generation-scoped node definitions by stable identifier. +/// +public interface IGraphNodeDefinitionResolver +{ + /// + /// Tries to resolve an active node definition. + /// + /// + /// Stable definition identifier. + /// + /// + /// Receives the generation-scoped definition. + /// + /// + /// when active; otherwise . + /// + bool TryResolve( + string definitionID, + out GraphNodeDefinition? definition + ); +} diff --git a/src/foundation/core/Inno.Core.Graphs/IGraphTypeConversion.cs b/src/foundation/core/Inno.Core.Graphs/IGraphTypeConversion.cs new file mode 100644 index 000000000..51dd8d143 --- /dev/null +++ b/src/foundation/core/Inno.Core.Graphs/IGraphTypeConversion.cs @@ -0,0 +1,24 @@ +namespace Inno.Core.Graphs; + +/// +/// Determines whether one graph value type can be converted to another. +/// +public interface IGraphTypeConversion +{ + /// + /// Tests a directed value conversion. + /// + /// + /// Source value type identifier. + /// + /// + /// Destination value type identifier. + /// + /// + /// when the conversion is valid; otherwise . + /// + bool CanConvert( + string sourceTypeID, + string destinationTypeID + ); +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ArraySerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ArraySerializationNode.cs new file mode 100644 index 000000000..78714f3e5 --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ArraySerializationNode.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization; + +internal sealed record ArraySerializationNode : SerializationNode +{ + internal ArraySerializationNode() + : this([]) {} + + internal ArraySerializationNode(List values) + { + this.values = values; + } + + internal List values { get; } +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterInvoker.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterInvoker.cs new file mode 100644 index 000000000..a633f8b66 --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterInvoker.cs @@ -0,0 +1,153 @@ +using System; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization; + +internal abstract class ConverterInvoker +{ + /// + /// Creates a validated converter invoker instance. + /// + /// + /// The target type consumed by converter invoker; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The converter type consumed by converter invoker; ownership remains with the caller unless explicitly stated otherwise. + /// + protected ConverterInvoker( + Type targetType, + Type converterType + ) { + this.targetType = targetType; + this.converterType = converterType; + } + + internal Type targetType { get; } + + internal Type converterType { get; } + + internal abstract SerializationNode Write( + SerializationOperation operation, + string path, + Type valueType, + object value, + SerializationNode? previous + ); + + internal abstract object Read( + SerializationOperation operation, + string path, + Type valueType, + ObjectSerializationNode node + ); + + internal abstract void Restore( + SerializationOperation operation, + string path, + Type valueType, + ObjectSerializationNode node, + object target + ); +} + +internal sealed class ConverterInvoker : ConverterInvoker +{ + private readonly SerializationConverter m_converter; + + internal ConverterInvoker( + SerializationConverter converter, + Type converterType + ) : base(typeof(T), converterType) + { + m_converter = converter; + } + + internal override SerializationNode Write( + SerializationOperation operation, + string path, + Type valueType, + object value, + SerializationNode? previous + ) { + if (value is not T typed) + { + throw new InvalidOperationException( + $"Converter '{converterType.FullName}' cannot write runtime value '{value.GetType().FullName}' at '{path}'." + ); + } + + ObjectSerializationNode? prior = previous as ObjectSerializationNode; + operation.RecordConverterWrite(); + long converterWrites = operation.converterWrites; + SerializationCaptureAttempt attempt = SerializationCaptureAttempt.Capture( + operation, + valueType, + typed, + prior?.captureKey, + m_converter + ); + SerializationCaptureKey? key = attempt.key; + if (key is not null && ReferenceEquals(key, prior?.captureKey)) + { + return prior!; + } + var writer = new SerializationWriter(operation, prior, path, valueType); + m_converter.Write(writer, typed); + ObjectSerializationNode result = writer.Complete(); + if (key is not null) + { + attempt.ValidateIdentities(); + key = attempt.Verify(SerializationCaptureAttempt.Capture(operation, valueType, typed, key, m_converter)); + if (operation.converterWrites != converterWrites) + { + key = null; + } + } + return SerializationNodeReuse.WithCaptureKey(result, prior, key); + } + + internal override object Read( + SerializationOperation operation, + string path, + Type valueType, + ObjectSerializationNode node + ) { + T result = m_converter.Read(new SerializationReader(operation, node, path, valueType)); + if (result is null) + { + throw new InvalidOperationException($"Converter '{converterType.FullName}' returned null at '{path}'."); + } + if (!valueType.IsInstanceOfType(result)) + { + throw new InvalidOperationException( + $"Converter '{converterType.FullName}' returned '{result.GetType().FullName}', which is incompatible with '{valueType.FullName}' at '{path}'." + ); + } + if (result is ISerializable serializable) + { + operation.ScheduleRestoredObject(serializable); + } + return result; + } + + internal override void Restore( + SerializationOperation operation, + string path, + Type valueType, + ObjectSerializationNode node, + object target + ) { + if (target is not T typed) + { + throw new InvalidOperationException( + $"Converter '{converterType.FullName}' cannot restore target '{target.GetType().FullName}' at '{path}'." + ); + } + + m_converter.Restore(new SerializationReader(operation, node, path, valueType), typed); + if (target is ISerializable serializable) + { + operation.ScheduleRestoredObject(serializable); + } + } +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs index 828ba722d..e0f07430f 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistry.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Reflection; using System.Threading; using Inno.Core.Serialization.Converters; using Inno.Extensibility.Types; @@ -404,272 +403,3 @@ internal void Release() } } } - -internal sealed class ConverterRegistryLease : IDisposable -{ - private ConcurrentDictionary? m_revisionPlans; - private ConverterRegistry.ConverterRegistrySnapshot? m_snapshot; - - internal ConverterRegistryLease(ConverterRegistry.ConverterRegistrySnapshot snapshot) - { - m_snapshot = snapshot; - } - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - ConverterRegistry.ConverterRegistrySnapshot? snapshot = Interlocked.Exchange(ref m_snapshot, null); - m_revisionPlans?.Clear(); - snapshot?.Release(); - } - - internal TypeCacheSnapshot types => (m_snapshot ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease))).types; - internal Guid captureIdentity => (m_snapshot ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease))).captureIdentity; - - internal bool CanReuseRevision( - SerializationTypeMetadata metadata, - ISerializationMetadataSource source - ) { - ConcurrentDictionary? plans = Volatile.Read( - ref m_revisionPlans - ); - if (plans is null) - { - var created = new ConcurrentDictionary(); - plans = Interlocked.CompareExchange(ref m_revisionPlans, created, null) ?? created; - } - if (plans.TryGetValue(metadata, out (ISerializationMetadataSource source, bool eligible) known) - && ReferenceEquals(known.source, source) - ) { - return known.eligible; - } - bool eligible = !metadata.requiresConverter; - foreach (SerializationMemberMetadata member in metadata.members) - { - if (!eligible) - { - break; - } - if ((member.visibility & PropertyVisibility.Serialize) == 0) - { - continue; - } - if (!IsKnownDefault(member.type)) - { - eligible = false; - break; - } - if (ValuePipeline.IsPrimitive(member.type) || member.type.IsEnum) - { - continue; - } - SerializationTypeMetadata nested = source.GetMetadata(member.type); - if (!nested.hasPureFieldAccess) - { - eligible = false; - break; - } - foreach (SerializationMemberMetadata field in nested.members) - { - if ((field.visibility & PropertyVisibility.Serialize) != 0 && !IsKnownDefault(field.type)) - { - eligible = false; - break; - } - } - } - // An unresolved fact can become known through an ordinary write in this same operation. - // Cache only positive proofs; a key query still never invokes the resolver itself. - if (eligible) - { - plans[metadata] = (source, true); - } - return eligible; - } - - internal ConverterInvoker? Resolve(Type valueType) - { - ArgumentNullException.ThrowIfNull(valueType); - ConverterRegistry.ConverterRegistrySnapshot snapshot = m_snapshot - ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); - Type normalizedType = Nullable.GetUnderlyingType(valueType) ?? valueType; - if (snapshot.cache.TryGetValue(normalizedType, out ConverterInvoker? cached)) - { - return cached; - } - lock (snapshot.sync) - { - if (snapshot.cache.TryGetValue(normalizedType, out cached)) - { - return cached; - } - ConverterInvoker? resolved = ConverterRegistry.ResolveSnapshot(snapshot, normalizedType); - if (!snapshot.cache.TryAdd(normalizedType, resolved)) - { - throw new InvalidOperationException("The serialization converter resolution was published twice."); - } - return resolved; - } - } - - private bool IsKnownDefault(Type type) - { - ConverterRegistry.ConverterRegistrySnapshot snapshot = m_snapshot - ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); - Type normalized = Nullable.GetUnderlyingType(type) ?? type; - // Reuse only facts established by the authoritative resolver. A key query must not - // construct converters, change their execution order, or introduce another resolver. - return snapshot.cache.TryGetValue(normalized, out ConverterInvoker? converter) && converter is null; - } -} - -internal abstract class ConverterInvoker -{ - /// - /// Creates a validated converter invoker instance. - /// - /// - /// The target type consumed by converter invoker; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The converter type consumed by converter invoker; ownership remains with the caller unless explicitly stated otherwise. - /// - protected ConverterInvoker( - Type targetType, - Type converterType - ) { - this.targetType = targetType; - this.converterType = converterType; - } - - internal Type targetType { get; } - - internal Type converterType { get; } - - internal abstract SerializationNode Write( - SerializationOperation operation, - string path, - Type valueType, - object value, - SerializationNode? previous - ); - - internal abstract object Read( - SerializationOperation operation, - string path, - Type valueType, - ObjectSerializationNode node - ); - - internal abstract void Restore( - SerializationOperation operation, - string path, - Type valueType, - ObjectSerializationNode node, - object target - ); -} - -internal sealed class ConverterInvoker : ConverterInvoker -{ - private readonly SerializationConverter m_converter; - - internal ConverterInvoker( - SerializationConverter converter, - Type converterType - ) : base(typeof(T), converterType) - { - m_converter = converter; - } - - internal override SerializationNode Write( - SerializationOperation operation, - string path, - Type valueType, - object value, - SerializationNode? previous - ) { - if (value is not T typed) - { - throw new InvalidOperationException( - $"Converter '{converterType.FullName}' cannot write runtime value '{value.GetType().FullName}' at '{path}'." - ); - } - - ObjectSerializationNode? prior = previous as ObjectSerializationNode; - operation.RecordConverterWrite(); - long converterWrites = operation.converterWrites; - SerializationCaptureAttempt attempt = SerializationCaptureAttempt.Capture( - operation, - valueType, - typed, - prior?.captureKey, - m_converter - ); - SerializationCaptureKey? key = attempt.key; - if (key is not null && ReferenceEquals(key, prior?.captureKey)) - { - return prior!; - } - var writer = new SerializationWriter(operation, prior, path, valueType); - m_converter.Write(writer, typed); - ObjectSerializationNode result = writer.Complete(); - if (key is not null) - { - attempt.ValidateIdentities(); - key = attempt.Verify(SerializationCaptureAttempt.Capture(operation, valueType, typed, key, m_converter)); - if (operation.converterWrites != converterWrites) - { - key = null; - } - } - return SerializationNodeReuse.WithCaptureKey(result, prior, key); - } - - internal override object Read( - SerializationOperation operation, - string path, - Type valueType, - ObjectSerializationNode node - ) { - T result = m_converter.Read(new SerializationReader(operation, node, path, valueType)); - if (result is null) - { - throw new InvalidOperationException($"Converter '{converterType.FullName}' returned null at '{path}'."); - } - if (!valueType.IsInstanceOfType(result)) - { - throw new InvalidOperationException( - $"Converter '{converterType.FullName}' returned '{result.GetType().FullName}', which is incompatible with '{valueType.FullName}' at '{path}'." - ); - } - if (result is ISerializable serializable) - { - operation.ScheduleRestoredObject(serializable); - } - return result; - } - - internal override void Restore( - SerializationOperation operation, - string path, - Type valueType, - ObjectSerializationNode node, - object target - ) { - if (target is not T typed) - { - throw new InvalidOperationException( - $"Converter '{converterType.FullName}' cannot restore target '{target.GetType().FullName}' at '{path}'." - ); - } - - m_converter.Restore(new SerializationReader(operation, node, path, valueType), typed); - if (target is ISerializable serializable) - { - operation.ScheduleRestoredObject(serializable); - } - } -} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistryLease.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistryLease.cs new file mode 100644 index 000000000..5ac8b785e --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ConverterRegistryLease.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Concurrent; +using System.Threading; +using Inno.Extensibility.Types; + +namespace Inno.Core.Serialization; + +internal sealed class ConverterRegistryLease : IDisposable +{ + private ConcurrentDictionary? m_revisionPlans; + private ConverterRegistry.ConverterRegistrySnapshot? m_snapshot; + + internal ConverterRegistryLease(ConverterRegistry.ConverterRegistrySnapshot snapshot) + { + m_snapshot = snapshot; + } + + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + ConverterRegistry.ConverterRegistrySnapshot? snapshot = Interlocked.Exchange(ref m_snapshot, null); + m_revisionPlans?.Clear(); + snapshot?.Release(); + } + + internal TypeCacheSnapshot types => (m_snapshot ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease))).types; + internal Guid captureIdentity => (m_snapshot ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease))).captureIdentity; + + internal bool CanReuseRevision( + SerializationTypeMetadata metadata, + ISerializationMetadataSource source + ) { + ConcurrentDictionary? plans = Volatile.Read( + ref m_revisionPlans + ); + if (plans is null) + { + var created = new ConcurrentDictionary(); + plans = Interlocked.CompareExchange(ref m_revisionPlans, created, null) ?? created; + } + if (plans.TryGetValue(metadata, out (ISerializationMetadataSource source, bool eligible) known) + && ReferenceEquals(known.source, source) + ) { + return known.eligible; + } + bool eligible = !metadata.requiresConverter; + foreach (SerializationMemberMetadata member in metadata.members) + { + if (!eligible) + { + break; + } + if ((member.visibility & PropertyVisibility.Serialize) == 0) + { + continue; + } + if (!IsKnownDefault(member.type)) + { + eligible = false; + break; + } + if (ValuePipeline.IsPrimitive(member.type) || member.type.IsEnum) + { + continue; + } + SerializationTypeMetadata nested = source.GetMetadata(member.type); + if (!nested.hasPureFieldAccess) + { + eligible = false; + break; + } + foreach (SerializationMemberMetadata field in nested.members) + { + if ((field.visibility & PropertyVisibility.Serialize) != 0 && !IsKnownDefault(field.type)) + { + eligible = false; + break; + } + } + } + // An unresolved fact can become known through an ordinary write in this same operation. + // Cache only positive proofs; a key query still never invokes the resolver itself. + if (eligible) + { + plans[metadata] = (source, true); + } + return eligible; + } + + internal ConverterInvoker? Resolve(Type valueType) + { + ArgumentNullException.ThrowIfNull(valueType); + ConverterRegistry.ConverterRegistrySnapshot snapshot = m_snapshot + ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); + Type normalizedType = Nullable.GetUnderlyingType(valueType) ?? valueType; + if (snapshot.cache.TryGetValue(normalizedType, out ConverterInvoker? cached)) + { + return cached; + } + lock (snapshot.sync) + { + if (snapshot.cache.TryGetValue(normalizedType, out cached)) + { + return cached; + } + ConverterInvoker? resolved = ConverterRegistry.ResolveSnapshot(snapshot, normalizedType); + if (!snapshot.cache.TryAdd(normalizedType, resolved)) + { + throw new InvalidOperationException("The serialization converter resolution was published twice."); + } + return resolved; + } + } + + private bool IsKnownDefault(Type type) + { + ConverterRegistry.ConverterRegistrySnapshot snapshot = m_snapshot + ?? throw new ObjectDisposedException(nameof(ConverterRegistryLease)); + Type normalized = Nullable.GetUnderlyingType(type) ?? type; + // Reuse only facts established by the authoritative resolver. A key query must not + // construct converters, change their execution order, or introduce another resolver. + return snapshot.cache.TryGetValue(normalized, out ConverterInvoker? converter) && converter is null; + } +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/MapSerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/MapSerializationNode.cs new file mode 100644 index 000000000..c305d2543 --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/MapSerializationNode.cs @@ -0,0 +1,8 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization; + +internal sealed record MapSerializationNode : SerializationNode +{ + internal List> values { get; } = []; +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/NullSerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/NullSerializationNode.cs new file mode 100644 index 000000000..f7010c0c6 --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/NullSerializationNode.cs @@ -0,0 +1,8 @@ +namespace Inno.Core.Serialization; + +internal sealed record NullSerializationNode : SerializationNode +{ + private NullSerializationNode() {} + + internal static NullSerializationNode instance { get; } = new(); +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/ObjectSerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/ObjectSerializationNode.cs new file mode 100644 index 000000000..7e6ce6ca6 --- /dev/null +++ b/src/foundation/core/Inno.Core.Serialization/Internal/ObjectSerializationNode.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Threading; + +namespace Inno.Core.Serialization; + +internal sealed record ObjectSerializationNode : SerializationNode +{ + private byte[]? m_encodedCapture; + private int m_encodingTooLarge; + + internal SerializationCaptureKey? captureKey { get; set; } + internal OrderedDictionary values { get; } = new(StringComparer.Ordinal); + internal byte[]? encodedCapture => Volatile.Read(ref m_encodedCapture); + internal bool encodingTooLarge => Volatile.Read(ref m_encodingTooLarge) != 0; + + internal byte[] PublishEncodedCapture(byte[] data) => Interlocked.CompareExchange(ref m_encodedCapture, data, null) ?? data; + + internal void RejectEncodedCapture() => Volatile.Write(ref m_encodingTooLarge, 1); +} diff --git a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs index 98557c9b2..568f5fb49 100644 --- a/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs +++ b/src/foundation/core/Inno.Core.Serialization/Internal/SerializationNode.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using System.Threading; namespace Inno.Core.Serialization; @@ -19,49 +17,9 @@ internal void RememberPath(string path) } } -internal sealed record NullSerializationNode : SerializationNode -{ - private NullSerializationNode() {} - - internal static NullSerializationNode instance { get; } = new(); -} - internal sealed record ScalarSerializationNode(object value) : SerializationNode; internal sealed record BinarySerializationNode(byte[] value) : SerializationNode { internal PropertyDataCapture? properties { get; init; } } - -internal sealed record ObjectSerializationNode : SerializationNode -{ - private byte[]? m_encodedCapture; - private int m_encodingTooLarge; - - internal SerializationCaptureKey? captureKey { get; set; } - internal OrderedDictionary values { get; } = new(StringComparer.Ordinal); - internal byte[]? encodedCapture => Volatile.Read(ref m_encodedCapture); - internal bool encodingTooLarge => Volatile.Read(ref m_encodingTooLarge) != 0; - - internal byte[] PublishEncodedCapture(byte[] data) => Interlocked.CompareExchange(ref m_encodedCapture, data, null) ?? data; - - internal void RejectEncodedCapture() => Volatile.Write(ref m_encodingTooLarge, 1); -} - -internal sealed record ArraySerializationNode : SerializationNode -{ - internal ArraySerializationNode() - : this([]) {} - - internal ArraySerializationNode(List values) - { - this.values = values; - } - - internal List values { get; } -} - -internal sealed record MapSerializationNode : SerializationNode -{ - internal List> values { get; } = []; -} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectID.cs b/src/foundation/core/Inno.Core.Settings/ProjectID.cs new file mode 100644 index 000000000..99e451597 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectID.cs @@ -0,0 +1,129 @@ +using System; +using System.Text; + +namespace Inno.Core.Settings; + +/// +/// Identifies one project namespace used to qualify project-authored logical names. +/// +public readonly record struct ProjectID +{ + /// + /// Creates a portable project identifier. + /// + /// + /// Lowercase ASCII namespace segments. + /// + public ProjectID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + string normalized = value.Trim(); + ValidatePortable(normalized, "Project ID", nameof(value)); + this.value = normalized; + } + + /// + /// Gets the canonical identifier text. + /// + public string value { get; } + + /// + /// Gets whether the value contains a usable identifier. + /// + public bool isValid => !string.IsNullOrEmpty(value); + + /// + /// Qualifies a local project name beneath this project namespace. + /// + /// + /// The portable local name. + /// + /// + /// The complete project-scoped identity. + /// + public ProjectScopedID Qualify(ProjectLocalID name) => new(this, name); + + /// + /// Formats the canonical identifier. + /// + /// + /// The canonical identifier text. + /// + public override string ToString() => value ?? string.Empty; + + /// + /// Creates a portable initial project identifier from a user-facing project name. + /// + /// + /// The project name used to derive the initial namespace. + /// + /// + /// A portable initial project identifier. + /// + public static ProjectID FromName(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + var builder = new StringBuilder(name.Length); + bool pendingSeparator = false; + foreach (char character in name.Trim()) + { + if (character is >= 'A' and <= 'Z') + { + Append((char)(character + ('a' - 'A'))); + } + else if (character is >= 'a' and <= 'z' or >= '0' and <= '9') + { + Append(character); + } + else + { + pendingSeparator = builder.Length > 0; + } + } + string value = builder.Length == 0 ? "inno.project" : builder.ToString(); + return new ProjectID(string.Equals(value, "project", StringComparison.Ordinal) ? "inno.project" : value); + + void Append(char character) + { + if (pendingSeparator) + { + builder.Append('-'); + } + pendingSeparator = false; + builder.Append(character); + } + } + + internal static void ValidatePortable( + string value, + string label, + string parameterName + ) { + if (value.Length > 128) + { + throw new ArgumentException($"{label} cannot exceed 128 characters.", parameterName); + } + for (int index = 0; index < value.Length; index++) + { + char character = value[index]; + bool valid = character is >= 'a' and <= 'z' + || character is >= '0' and <= '9' + || character is '.' or '-' or '_'; + if (!valid) + { + throw new ArgumentException( + $"{label} must use lowercase ASCII letters, digits, dots, hyphens, or underscores.", + parameterName + ); + } + } + if (value[0] is '.' or '-' or '_' || value[^1] is '.' or '-' or '_') + { + throw new ArgumentException($"{label} must begin and end with a letter or digit.", parameterName); + } + if (value.Contains("..", StringComparison.Ordinal)) + { + throw new ArgumentException($"{label} cannot contain empty namespace segments.", parameterName); + } + } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs b/src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs deleted file mode 100644 index e525b7f58..000000000 --- a/src/foundation/core/Inno.Core.Settings/ProjectIdentity.cs +++ /dev/null @@ -1,320 +0,0 @@ -using System; -using System.Text; -using Inno.Core.Serialization; -using Inno.Extensibility.Types; - -namespace Inno.Core.Settings; - -/// -/// Identifies one project namespace used to qualify project-authored logical names. -/// -public readonly record struct ProjectID -{ - /// - /// Creates a portable project identifier. - /// - /// - /// Lowercase ASCII namespace segments. - /// - public ProjectID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - string normalized = value.Trim(); - ValidatePortable(normalized, "Project ID", nameof(value)); - this.value = normalized; - } - - /// - /// Gets the canonical identifier text. - /// - public string value { get; } - - /// - /// Gets whether the value contains a usable identifier. - /// - public bool isValid => !string.IsNullOrEmpty(value); - - /// - /// Qualifies a local project name beneath this project namespace. - /// - /// - /// The portable local name. - /// - /// - /// The complete project-scoped identity. - /// - public ProjectScopedID Qualify(ProjectLocalID name) => new(this, name); - - /// - /// Formats the canonical identifier. - /// - /// - /// The canonical identifier text. - /// - public override string ToString() => value ?? string.Empty; - - /// - /// Creates a portable initial project identifier from a user-facing project name. - /// - /// - /// The project name used to derive the initial namespace. - /// - /// - /// A portable initial project identifier. - /// - public static ProjectID FromName(string name) - { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - var builder = new StringBuilder(name.Length); - bool pendingSeparator = false; - foreach (char character in name.Trim()) - { - if (character is >= 'A' and <= 'Z') - { - Append((char)(character + ('a' - 'A'))); - } - else if (character is >= 'a' and <= 'z' or >= '0' and <= '9') - { - Append(character); - } - else - { - pendingSeparator = builder.Length > 0; - } - } - string value = builder.Length == 0 ? "inno.project" : builder.ToString(); - return new ProjectID(string.Equals(value, "project", StringComparison.Ordinal) ? "inno.project" : value); - - void Append(char character) - { - if (pendingSeparator) - { - builder.Append('-'); - } - pendingSeparator = false; - builder.Append(character); - } - } - - internal static void ValidatePortable( - string value, - string label, - string parameterName - ) { - if (value.Length > 128) - { - throw new ArgumentException($"{label} cannot exceed 128 characters.", parameterName); - } - for (int index = 0; index < value.Length; index++) - { - char character = value[index]; - bool valid = character is >= 'a' and <= 'z' - || character is >= '0' and <= '9' - || character is '.' or '-' or '_'; - if (!valid) - { - throw new ArgumentException( - $"{label} must use lowercase ASCII letters, digits, dots, hyphens, or underscores.", - parameterName - ); - } - } - if (value[0] is '.' or '-' or '_' || value[^1] is '.' or '-' or '_') - { - throw new ArgumentException($"{label} must begin and end with a letter or digit.", parameterName); - } - if (value.Contains("..", StringComparison.Ordinal)) - { - throw new ArgumentException($"{label} cannot contain empty namespace segments.", parameterName); - } - } -} - -/// -/// Stores the project-independent portion of one project-scoped identity. -/// -public readonly record struct ProjectLocalID -{ - /// - /// Creates a portable local identity. - /// - /// - /// Lowercase ASCII local namespace segments. - /// - public ProjectLocalID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - string normalized = value.Trim(); - ProjectID.ValidatePortable(normalized, "Project-local ID", nameof(value)); - this.value = normalized; - } - - /// - /// Gets the canonical local identity text. - /// - public string value { get; } - - /// - /// Formats the canonical local identity. - /// - /// - /// The canonical local identity text. - /// - public override string ToString() => value ?? string.Empty; - - /// - /// Creates a deterministic portable local identity from a display name. - /// - /// - /// The user-facing name. - /// - /// - /// The normalized local identity. - /// - public static ProjectLocalID FromName(string name) - { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - var builder = new StringBuilder(name.Length); - bool pendingSeparator = false; - foreach (char character in name.Trim()) - { - if (character is >= 'A' and <= 'Z') - { - AppendSeparator(builder, ref pendingSeparator); - builder.Append((char)(character + ('a' - 'A'))); - } - else if (character is >= 'a' and <= 'z' or >= '0' and <= '9') - { - AppendSeparator(builder, ref pendingSeparator); - builder.Append(character); - } - else if (character is ' ' or '\t' or '.' or '-' or '_') - { - pendingSeparator = builder.Length > 0; - } - else - { - throw new ArgumentException( - "A project-scoped name must use ASCII letters, digits, spaces, dots, hyphens, or underscores.", - nameof(name) - ); - } - } - if (builder.Length == 0) - { - throw new ArgumentException("A project-scoped name must contain a letter or digit.", nameof(name)); - } - return new ProjectLocalID(builder.ToString()); - } - - private static void AppendSeparator( - StringBuilder builder, - ref bool pendingSeparator - ) { - if (pendingSeparator && builder.Length > 0) - { - builder.Append('-'); - } - pendingSeparator = false; - } -} - -/// -/// Combines a mutable project namespace with a stable project-independent local identity. -/// -public readonly record struct ProjectScopedID -{ - /// - /// Creates a qualified project identity. - /// - /// - /// The current project namespace. - /// - /// - /// The stable local identity. - /// - public ProjectScopedID( - ProjectID projectID, - ProjectLocalID name - ) { - if (!projectID.isValid) - { - throw new ArgumentException("A valid Project ID is required.", nameof(projectID)); - } - if (string.IsNullOrEmpty(name.value)) - { - throw new ArgumentException("A valid project-local ID is required.", nameof(name)); - } - this.projectID = projectID; - this.name = name; - } - - /// - /// Gets the project namespace. - /// - public ProjectID projectID { get; } - - /// - /// Gets the project-independent local identity. - /// - public ProjectLocalID name { get; } - - /// - /// Gets the canonical projectId.name representation. - /// - public string value => $"{projectID.value}.{name.value}"; - - /// - /// Formats the canonical qualified identity. - /// - /// - /// The projectId.name representation. - /// - public override string ToString() => value; -} - -/// -/// Stores the editable identity namespace of the current project. -/// -[StableTypeID("d5f90462-506d-4ff7-aa9f-0f14da28b9c3")] -[ProjectSettingDefinition(ProjectIdentitySettings.C_SETTING_PROTOCOL_ID, allowPluginContributions: false)] -public sealed class ProjectIdentitySettings : ISerializable -{ - /// - /// Gets the immutable project-setting protocol value used by discovery metadata. - /// - public const string C_SETTING_PROTOCOL_ID = "inno.project.identity"; - - private string m_projectID = "inno.project"; - - /// - /// Gets the stable project setting protocol identity. - /// - public static ProjectSettingID settingID => new(C_SETTING_PROTOCOL_ID); - - /// - /// Gets or sets the editable project namespace. - /// - [SerializableProperty] - public string projectId - { - get => m_projectID; - set => m_projectID = new ProjectID(value).value; - } - - /// - /// Gets the validated project identifier. - /// - public ProjectID id => new(m_projectID); - - /// - /// Qualifies a display name under the current project identifier. - /// - /// - /// The project-local display name. - /// - /// - /// The complete project-scoped identity. - /// - public ProjectScopedID Qualify(string name) => id.Qualify(ProjectLocalID.FromName(name)); -} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectIdentitySettings.cs b/src/foundation/core/Inno.Core.Settings/ProjectIdentitySettings.cs new file mode 100644 index 000000000..9a1b646f2 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectIdentitySettings.cs @@ -0,0 +1,50 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Core.Settings; + +/// +/// Stores the editable identity namespace of the current project. +/// +[StableTypeID("d5f90462-506d-4ff7-aa9f-0f14da28b9c3")] +[ProjectSettingDefinition(ProjectIdentitySettings.C_SETTING_PROTOCOL_ID, allowPluginContributions: false)] +public sealed class ProjectIdentitySettings : ISerializable +{ + /// + /// Gets the immutable project-setting protocol value used by discovery metadata. + /// + public const string C_SETTING_PROTOCOL_ID = "inno.project.identity"; + + private string m_projectID = "inno.project"; + + /// + /// Gets the stable project setting protocol identity. + /// + public static ProjectSettingID settingID => new(C_SETTING_PROTOCOL_ID); + + /// + /// Gets or sets the editable project namespace. + /// + [SerializableProperty] + public string projectId + { + get => m_projectID; + set => m_projectID = new ProjectID(value).value; + } + + /// + /// Gets the validated project identifier. + /// + public ProjectID id => new(m_projectID); + + /// + /// Qualifies a display name under the current project identifier. + /// + /// + /// The project-local display name. + /// + /// + /// The complete project-scoped identity. + /// + public ProjectScopedID Qualify(string name) => id.Qualify(ProjectLocalID.FromName(name)); +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectLocalID.cs b/src/foundation/core/Inno.Core.Settings/ProjectLocalID.cs new file mode 100644 index 000000000..91ef890fb --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectLocalID.cs @@ -0,0 +1,93 @@ +using System; +using System.Text; + +namespace Inno.Core.Settings; + +/// +/// Stores the project-independent portion of one project-scoped identity. +/// +public readonly record struct ProjectLocalID +{ + /// + /// Creates a portable local identity. + /// + /// + /// Lowercase ASCII local namespace segments. + /// + public ProjectLocalID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + string normalized = value.Trim(); + ProjectID.ValidatePortable(normalized, "Project-local ID", nameof(value)); + this.value = normalized; + } + + /// + /// Gets the canonical local identity text. + /// + public string value { get; } + + /// + /// Formats the canonical local identity. + /// + /// + /// The canonical local identity text. + /// + public override string ToString() => value ?? string.Empty; + + /// + /// Creates a deterministic portable local identity from a display name. + /// + /// + /// The user-facing name. + /// + /// + /// The normalized local identity. + /// + public static ProjectLocalID FromName(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + var builder = new StringBuilder(name.Length); + bool pendingSeparator = false; + foreach (char character in name.Trim()) + { + if (character is >= 'A' and <= 'Z') + { + AppendSeparator(builder, ref pendingSeparator); + builder.Append((char)(character + ('a' - 'A'))); + } + else if (character is >= 'a' and <= 'z' or >= '0' and <= '9') + { + AppendSeparator(builder, ref pendingSeparator); + builder.Append(character); + } + else if (character is ' ' or '\t' or '.' or '-' or '_') + { + pendingSeparator = builder.Length > 0; + } + else + { + throw new ArgumentException( + "A project-scoped name must use ASCII letters, digits, spaces, dots, hyphens, or underscores.", + nameof(name) + ); + } + } + if (builder.Length == 0) + { + throw new ArgumentException("A project-scoped name must contain a letter or digit.", nameof(name)); + } + return new ProjectLocalID(builder.ToString()); + } + + private static void AppendSeparator( + StringBuilder builder, + ref bool pendingSeparator + ) { + if (pendingSeparator && builder.Length > 0) + { + builder.Append('-'); + } + pendingSeparator = false; + } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectScopedID.cs b/src/foundation/core/Inno.Core.Settings/ProjectScopedID.cs new file mode 100644 index 000000000..256f0904f --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectScopedID.cs @@ -0,0 +1,57 @@ +using System; + +namespace Inno.Core.Settings; + +/// +/// Combines a mutable project namespace with a stable project-independent local identity. +/// +public readonly record struct ProjectScopedID +{ + /// + /// Creates a qualified project identity. + /// + /// + /// The current project namespace. + /// + /// + /// The stable local identity. + /// + public ProjectScopedID( + ProjectID projectID, + ProjectLocalID name + ) { + if (!projectID.isValid) + { + throw new ArgumentException("A valid Project ID is required.", nameof(projectID)); + } + if (string.IsNullOrEmpty(name.value)) + { + throw new ArgumentException("A valid project-local ID is required.", nameof(name)); + } + this.projectID = projectID; + this.name = name; + } + + /// + /// Gets the project namespace. + /// + public ProjectID projectID { get; } + + /// + /// Gets the project-independent local identity. + /// + public ProjectLocalID name { get; } + + /// + /// Gets the canonical projectId.name representation. + /// + public string value => $"{projectID.value}.{name.value}"; + + /// + /// Formats the canonical qualified identity. + /// + /// + /// The projectId.name representation. + /// + public override string ToString() => value; +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingComposition.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingComposer.cs similarity index 54% rename from src/foundation/core/Inno.Core.Settings/ProjectSettingComposition.cs rename to src/foundation/core/Inno.Core.Settings/ProjectSettingComposer.cs index 6b24ae3af..1d4fb8bbb 100644 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingComposition.cs +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingComposer.cs @@ -4,128 +4,6 @@ namespace Inno.Core.Settings; -/// -/// Declares the protocol-owned composer used to combine contributions for one project setting. -/// Settings without a composer retain the default whole-value replacement behavior. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class ProjectSettingComposerAttribute : Attribute -{ - /// - /// Creates a composer declaration for one stable setting protocol. - /// - /// - /// The setting protocol composed by the attributed type. - /// - public ProjectSettingComposerAttribute(string settingID) - { - ArgumentException.ThrowIfNullOrWhiteSpace(settingID); - this.settingID = new ProjectSettingID(settingID); - } - - /// - /// Gets the stable setting protocol composed by the attributed type. - /// - public ProjectSettingID settingID { get; } -} - -/// -/// Identifies where one setting contribution originated. -/// -public enum ProjectSettingContributionSource -{ - /// - /// The contribution is a default supplied by an activated Plugin. - /// - Plugin, - /// - /// The contribution is the project-authored delta with highest precedence. - /// - Project -} - -/// -/// Exposes ownership and dependency information while a protocol-owned composer combines one contribution. -/// -public sealed class ProjectSettingContributionContext -{ - private readonly IReadOnlySet m_dependencies; - private readonly IReadOnlySet m_overrides; - - internal ProjectSettingContributionContext( - string contributorID, - ProjectSettingContributionSource source, - IReadOnlySet dependencies, - IReadOnlySet overrides - ) { - this.contributorID = contributorID; - this.source = source; - m_dependencies = dependencies; - m_overrides = overrides; - } - - /// - /// Gets the stable Plugin ID, or project for the project-authored contribution. - /// - public string contributorID { get; } - - /// - /// Gets the contribution source. - /// - public ProjectSettingContributionSource source { get; } - - /// - /// Gets whether this is the project-authored highest-precedence contribution. - /// - public bool isProject => source == ProjectSettingContributionSource.Project; - - /// - /// Gets whether this contribution may explicitly replace data owned by another contributor. - /// - /// - /// The stable owner whose data would be replaced. - /// - /// - /// for project data, or when the Plugin both depends on and explicitly overrides - /// . - /// - public bool CanOverride(string ownerID) - { - ArgumentException.ThrowIfNullOrWhiteSpace(ownerID); - return isProject - || string.Equals(ownerID, "host", StringComparison.Ordinal) - || (m_dependencies.Contains(ownerID) && m_overrides.Contains(ownerID)); - } -} - -/// -/// Provides one decoded contribution and its immutable composition context. -/// -/// -/// The protocol-owned neutral contribution type. -/// -public sealed class ProjectSettingContribution - where TContribution : class, ISerializable -{ - internal ProjectSettingContribution( - ProjectSettingContributionContext context, - TContribution value - ) { - this.context = context; - this.value = value; - } - - /// - /// Gets the ownership and dependency context for this contribution. - /// - public ProjectSettingContributionContext context { get; } - - /// - /// Gets the decoded protocol-owned contribution value. - /// - public TContribution value { get; } -} - /// /// Defines the non-generic base for a protocol-owned project setting composer. /// @@ -260,8 +138,3 @@ IReadOnlyList contributions return target; } } - -internal sealed record ProjectSettingCompositionEntry( - ProjectSettingContributionContext context, - byte[] data -); diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingComposerAttribute.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingComposerAttribute.cs new file mode 100644 index 000000000..550d59c42 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingComposerAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace Inno.Core.Settings; + +/// +/// Declares the protocol-owned composer used to combine contributions for one project setting. +/// Settings without a composer retain the default whole-value replacement behavior. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class ProjectSettingComposerAttribute : Attribute +{ + /// + /// Creates a composer declaration for one stable setting protocol. + /// + /// + /// The setting protocol composed by the attributed type. + /// + public ProjectSettingComposerAttribute(string settingID) + { + ArgumentException.ThrowIfNullOrWhiteSpace(settingID); + this.settingID = new ProjectSettingID(settingID); + } + + /// + /// Gets the stable setting protocol composed by the attributed type. + /// + public ProjectSettingID settingID { get; } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingCompositionEntry.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingCompositionEntry.cs new file mode 100644 index 000000000..4326f9fe8 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingCompositionEntry.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Settings; + +internal sealed record ProjectSettingCompositionEntry( + ProjectSettingContributionContext context, + byte[] data +); diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs deleted file mode 100644 index 70ba180ae..000000000 --- a/src/foundation/core/Inno.Core.Settings/ProjectSettingContracts.cs +++ /dev/null @@ -1,207 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Inno.Core.Serialization; - -namespace Inno.Core.Settings; - -/// -/// Identifies one host-neutral project setting protocol. -/// -public record struct ProjectSettingID -{ - /// - /// Creates a project setting identifier. - /// - /// - /// Globally stable setting value. - /// - public ProjectSettingID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value.Trim(); - } - - /// - /// Gets or sets the globally stable setting value. - /// - public string value { get; set; } - - /// - /// Gets whether the identifier has a usable value. - /// - public readonly bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override readonly string ToString() => value ?? string.Empty; -} - -/// -/// Declares a reloadable settings type under one stable protocol identity. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class ProjectSettingDefinitionAttribute : Attribute -{ - /// - /// Creates a project setting declaration. - /// - /// - /// Globally stable setting identifier. - /// - /// - /// Whether Plugin packages may contribute values to this protocol. - /// - public ProjectSettingDefinitionAttribute( - string id, - bool allowPluginContributions = true - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - this.allowPluginContributions = allowPluginContributions; - } - - /// - /// Gets the globally stable setting identifier. - /// - public string id { get; } - - /// - /// Gets whether Plugin packages may contribute values to this protocol. - /// - public bool allowPluginContributions { get; } -} - -/// -/// Stores one protocol-owned neutral setting contribution for persistence and composition. -/// -public struct ProjectSettingRecord -{ - /// - /// Creates a setting record. - /// - /// - /// Stable setting identity. - /// - /// - /// Stable settings type identity. - /// - /// - /// Composer-owned contribution bytes, or complete property bytes for replacement settings. - /// - public ProjectSettingRecord( - ProjectSettingID id, - Guid stableTypeID, - ReadOnlySpan propertyData - ) { - if (!id.isValid) - { - throw new ArgumentException("A project setting ID must be valid.", nameof(id)); - } - if (stableTypeID == Guid.Empty) - { - throw new ArgumentException("A project setting requires a stable type ID.", nameof(stableTypeID)); - } - this.id = id; - this.stableTypeId = stableTypeID; - this.propertyData = propertyData.ToArray(); - } - - /// - /// Gets or sets the stable setting identity. - /// - public ProjectSettingID id { get; set; } - - /// - /// Gets or sets the stable settings type identity. - /// - public Guid stableTypeId { get; set; } - - /// - /// Gets or sets the composer-owned payload or default complete-property payload. - /// - public byte[] propertyData { get; set; } -} - -/// -/// Stores project-authored setting contributions in one native document. -/// -public sealed class ProjectSettingsDocument : ISerializable -{ - /// - /// Gets or sets project-authored protocol contributions. - /// - [SerializableProperty] - public ProjectSettingRecord[] overrides { get; set; } = []; -} - -/// -/// Describes one dependency-ordered provider of default setting values. -/// -public sealed class ProjectSettingsContributor -{ - private readonly ProjectSettingRecord[] m_settings; - - /// - /// Creates one settings contributor. - /// - /// - /// Stable contributor identity. - /// - /// - /// Contributors that must precede this contributor. - /// - /// - /// Dependencies whose defaults may be explicitly replaced. - /// - /// - /// Default setting contributions. - /// - public ProjectSettingsContributor( - string id, - IEnumerable dependencies, - IEnumerable overrides, - IEnumerable settings - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentNullException.ThrowIfNull(dependencies); - ArgumentNullException.ThrowIfNull(overrides); - ArgumentNullException.ThrowIfNull(settings); - this.id = id; - this.dependencies = Array.AsReadOnly(dependencies.ToArray()); - this.overrides = Array.AsReadOnly(overrides.ToArray()); - m_settings = settings.Select(Clone).ToArray(); - } - - /// - /// Gets the stable contributor identity. - /// - public string id { get; } - - /// - /// Gets contributors that must precede this contributor. - /// - public IReadOnlyList dependencies { get; } - - /// - /// Gets dependencies whose defaults may be replaced. - /// - public IReadOnlyList overrides { get; } - - /// - /// Gets a detached read-only contribution snapshot, including independently owned payload bytes. - /// - public IReadOnlyList settings => Array.AsReadOnly(m_settings.Select(Clone).ToArray()); - - private static ProjectSettingRecord Clone(ProjectSettingRecord record) - => new() - { - id = record.id, - stableTypeId = record.stableTypeId, - propertyData = record.propertyData?.ToArray()! - }; -} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingContribution.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingContribution.cs new file mode 100644 index 000000000..9530bcd8f --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingContribution.cs @@ -0,0 +1,46 @@ +using Inno.Core.Serialization; + +namespace Inno.Core.Settings; + +/// +/// Provides one decoded contribution and its immutable composition context. +/// +/// +/// The protocol-owned neutral contribution type. +/// +public sealed class ProjectSettingContribution + where TContribution : class, ISerializable +{ + internal ProjectSettingContribution( + ProjectSettingContributionContext context, + TContribution value + ) { + this.context = context; + this.value = value; + } + + /// + /// Gets the ownership and dependency context for this contribution. + /// + public ProjectSettingContributionContext context { get; } + + /// + /// Gets the decoded protocol-owned contribution value. + /// + public TContribution value { get; } +} + +/// +/// Identifies where one setting contribution originated. +/// +public enum ProjectSettingContributionSource +{ + /// + /// The contribution is a default supplied by an activated Plugin. + /// + Plugin, + /// + /// The contribution is the project-authored delta with highest precedence. + /// + Project +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingContributionContext.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingContributionContext.cs new file mode 100644 index 000000000..dda7cc226 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingContributionContext.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Core.Settings; + +/// +/// Exposes ownership and dependency information while a protocol-owned composer combines one contribution. +/// +public sealed class ProjectSettingContributionContext +{ + private readonly IReadOnlySet m_dependencies; + private readonly IReadOnlySet m_overrides; + + internal ProjectSettingContributionContext( + string contributorID, + ProjectSettingContributionSource source, + IReadOnlySet dependencies, + IReadOnlySet overrides + ) { + this.contributorID = contributorID; + this.source = source; + m_dependencies = dependencies; + m_overrides = overrides; + } + + /// + /// Gets the stable Plugin ID, or project for the project-authored contribution. + /// + public string contributorID { get; } + + /// + /// Gets the contribution source. + /// + public ProjectSettingContributionSource source { get; } + + /// + /// Gets whether this is the project-authored highest-precedence contribution. + /// + public bool isProject => source == ProjectSettingContributionSource.Project; + + /// + /// Gets whether this contribution may explicitly replace data owned by another contributor. + /// + /// + /// The stable owner whose data would be replaced. + /// + /// + /// for project data, or when the Plugin both depends on and explicitly overrides + /// . + /// + public bool CanOverride(string ownerID) + { + ArgumentException.ThrowIfNullOrWhiteSpace(ownerID); + return isProject + || string.Equals(ownerID, "host", StringComparison.Ordinal) + || (m_dependencies.Contains(ownerID) && m_overrides.Contains(ownerID)); + } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingDefinitionAttribute.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingDefinitionAttribute.cs new file mode 100644 index 000000000..6964202ff --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingDefinitionAttribute.cs @@ -0,0 +1,38 @@ +using System; + +namespace Inno.Core.Settings; + +/// +/// Declares a reloadable settings type under one stable protocol identity. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class ProjectSettingDefinitionAttribute : Attribute +{ + /// + /// Creates a project setting declaration. + /// + /// + /// Globally stable setting identifier. + /// + /// + /// Whether Plugin packages may contribute values to this protocol. + /// + public ProjectSettingDefinitionAttribute( + string id, + bool allowPluginContributions = true + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + this.allowPluginContributions = allowPluginContributions; + } + + /// + /// Gets the globally stable setting identifier. + /// + public string id { get; } + + /// + /// Gets whether Plugin packages may contribute values to this protocol. + /// + public bool allowPluginContributions { get; } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingID.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingID.cs new file mode 100644 index 000000000..8c56e988c --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Core.Settings; + +/// +/// Identifies one host-neutral project setting protocol. +/// +public record struct ProjectSettingID +{ + /// + /// Creates a project setting identifier. + /// + /// + /// Globally stable setting value. + /// + public ProjectSettingID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value.Trim(); + } + + /// + /// Gets or sets the globally stable setting value. + /// + public string value { get; set; } + + /// + /// Gets whether the identifier has a usable value. + /// + public readonly bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override readonly string ToString() => value ?? string.Empty; +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingRecord.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingRecord.cs new file mode 100644 index 000000000..6acf8a24f --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingRecord.cs @@ -0,0 +1,54 @@ +using System; + +namespace Inno.Core.Settings; + +/// +/// Stores one protocol-owned neutral setting contribution for persistence and composition. +/// +public struct ProjectSettingRecord +{ + /// + /// Creates a setting record. + /// + /// + /// Stable setting identity. + /// + /// + /// Stable settings type identity. + /// + /// + /// Composer-owned contribution bytes, or complete property bytes for replacement settings. + /// + public ProjectSettingRecord( + ProjectSettingID id, + Guid stableTypeID, + ReadOnlySpan propertyData + ) { + if (!id.isValid) + { + throw new ArgumentException("A project setting ID must be valid.", nameof(id)); + } + if (stableTypeID == Guid.Empty) + { + throw new ArgumentException("A project setting requires a stable type ID.", nameof(stableTypeID)); + } + this.id = id; + this.stableTypeId = stableTypeID; + this.propertyData = propertyData.ToArray(); + } + + /// + /// Gets or sets the stable setting identity. + /// + public ProjectSettingID id { get; set; } + + /// + /// Gets or sets the stable settings type identity. + /// + public Guid stableTypeId { get; set; } + + /// + /// Gets or sets the composer-owned payload or default complete-property payload. + /// + public byte[] propertyData { get; set; } +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsContributor.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsContributor.cs new file mode 100644 index 000000000..aec17433a --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsContributor.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Core.Settings; + +/// +/// Describes one dependency-ordered provider of default setting values. +/// +public sealed class ProjectSettingsContributor +{ + private readonly ProjectSettingRecord[] m_settings; + + /// + /// Creates one settings contributor. + /// + /// + /// Stable contributor identity. + /// + /// + /// Contributors that must precede this contributor. + /// + /// + /// Dependencies whose defaults may be explicitly replaced. + /// + /// + /// Default setting contributions. + /// + public ProjectSettingsContributor( + string id, + IEnumerable dependencies, + IEnumerable overrides, + IEnumerable settings + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentNullException.ThrowIfNull(dependencies); + ArgumentNullException.ThrowIfNull(overrides); + ArgumentNullException.ThrowIfNull(settings); + this.id = id; + this.dependencies = Array.AsReadOnly(dependencies.ToArray()); + this.overrides = Array.AsReadOnly(overrides.ToArray()); + m_settings = settings.Select(Clone).ToArray(); + } + + /// + /// Gets the stable contributor identity. + /// + public string id { get; } + + /// + /// Gets contributors that must precede this contributor. + /// + public IReadOnlyList dependencies { get; } + + /// + /// Gets dependencies whose defaults may be replaced. + /// + public IReadOnlyList overrides { get; } + + /// + /// Gets a detached read-only contribution snapshot, including independently owned payload bytes. + /// + public IReadOnlyList settings => Array.AsReadOnly(m_settings.Select(Clone).ToArray()); + + private static ProjectSettingRecord Clone(ProjectSettingRecord record) + => new() + { + id = record.id, + stableTypeId = record.stableTypeId, + propertyData = record.propertyData?.ToArray()! + }; +} diff --git a/src/foundation/core/Inno.Core.Settings/ProjectSettingsDocument.cs b/src/foundation/core/Inno.Core.Settings/ProjectSettingsDocument.cs new file mode 100644 index 000000000..5dd117b25 --- /dev/null +++ b/src/foundation/core/Inno.Core.Settings/ProjectSettingsDocument.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; + +namespace Inno.Core.Settings; + +/// +/// Stores project-authored setting contributions in one native document. +/// +public sealed class ProjectSettingsDocument : ISerializable +{ + /// + /// Gets or sets project-authored protocol contributions. + /// + [SerializableProperty] + public ProjectSettingRecord[] overrides { get; set; } = []; +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs index d35d5962a..d97cb10c4 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogCoordinator.cs @@ -106,166 +106,3 @@ private readonly record struct ParticipantReference( WeakReference participant ); } - -internal sealed class CatalogParticipantRegistration( - AssemblyCatalogCoordinator owner, - Guid id -) : IDisposable -{ - private bool m_disposed; - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - if (m_disposed) - { - return; - } - m_disposed = true; - owner.Unregister(id); - } - - internal Guid id { get; } = id; -} - -internal sealed class AssemblyCatalogRefreshSet(IReadOnlyList transactions) -{ - private int m_activatedCount; - private bool m_finished; - private Exception? m_failure; - - internal IReadOnlyList contexts - { - get - { - var result = new List(transactions.Count); - foreach (IAssemblyCatalogTransaction transaction in transactions) - { - if (transaction.context is not null) - { - result.Add(transaction.context); - } - } - return result; - } - } - - internal void Activate() - { - if (m_failure is not null) - { - throw m_failure; - } - if (m_finished) - { - throw new InvalidOperationException("Assembly catalog refresh set is already finished."); - } - try - { - for (; m_activatedCount < transactions.Count; m_activatedCount++) - { - transactions[m_activatedCount].Activate(); - } - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) - { - m_failure = failure; - throw; - } - catch (Exception activationFailure) - { - try - { - Rollback(); - } - catch (Exception rollbackFailure) - { - var combined = new AggregateException( - "Assembly catalog activation and rollback failed.", - activationFailure, - rollbackFailure - ); - if (RetirementPendingException.Find(combined) is not null) - { - m_failure = combined; - } - throw combined; - } - throw; - } - } - - internal void Complete() - { - if (m_failure is not null) - { - throw m_failure; - } - if (m_finished) - { - return; - } - List failures = []; - for (int i = 0; i < transactions.Count; i++) - { - TryCleanup(transactions[i].Complete, failures); - } - m_finished = true; - transactions = []; - if (failures.Count > 0) - { - throw new AggregateException("Assembly catalog completion failed after all participants were attempted.", failures); - } - } - - internal void Rollback() - { - if (m_failure is not null) - { - throw m_failure; - } - if (m_finished) - { - return; - } - List failures = []; - for (int i = transactions.Count - 1; i >= 0; i--) - { - TryCleanup(transactions[i].Rollback, failures); - } - m_finished = true; - transactions = []; - if (failures.Count > 0) - { - throw new AggregateException("Assembly catalog rollback failed after all participants were attempted.", failures); - } - } - - private void TryCleanup( - Action cleanup, - List failures - ) { - try - { - cleanup(); - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) - { - m_failure = failures.Count == 0 ? failure : new AggregateException( - "Catalog cleanup remains pending after earlier failures.", - [.. failures, failure] - ); - if (ReferenceEquals(m_failure, failure)) - { - throw; - } - throw m_failure; - } - catch (Exception exception) - { - failures.Add(exception); - } - } -} diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogRefreshSet.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogRefreshSet.cs new file mode 100644 index 000000000..87d8f902c --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/AssemblyCatalogRefreshSet.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Execution; + +namespace Inno.Extensibility.Modules; + +internal sealed class AssemblyCatalogRefreshSet(IReadOnlyList transactions) +{ + private int m_activatedCount; + private bool m_finished; + private Exception? m_failure; + + internal IReadOnlyList contexts + { + get + { + var result = new List(transactions.Count); + foreach (IAssemblyCatalogTransaction transaction in transactions) + { + if (transaction.context is not null) + { + result.Add(transaction.context); + } + } + return result; + } + } + + internal void Activate() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + throw new InvalidOperationException("Assembly catalog refresh set is already finished."); + } + try + { + for (; m_activatedCount < transactions.Count; m_activatedCount++) + { + transactions[m_activatedCount].Activate(); + } + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) + { + m_failure = failure; + throw; + } + catch (Exception activationFailure) + { + try + { + Rollback(); + } + catch (Exception rollbackFailure) + { + var combined = new AggregateException( + "Assembly catalog activation and rollback failed.", + activationFailure, + rollbackFailure + ); + if (RetirementPendingException.Find(combined) is not null) + { + m_failure = combined; + } + throw combined; + } + throw; + } + } + + internal void Complete() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + return; + } + List failures = []; + for (int i = 0; i < transactions.Count; i++) + { + TryCleanup(transactions[i].Complete, failures); + } + m_finished = true; + transactions = []; + if (failures.Count > 0) + { + throw new AggregateException("Assembly catalog completion failed after all participants were attempted.", failures); + } + } + + internal void Rollback() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + return; + } + List failures = []; + for (int i = transactions.Count - 1; i >= 0; i--) + { + TryCleanup(transactions[i].Rollback, failures); + } + m_finished = true; + transactions = []; + if (failures.Count > 0) + { + throw new AggregateException("Assembly catalog rollback failed after all participants were attempted.", failures); + } + } + + private void TryCleanup( + Action cleanup, + List failures + ) { + try + { + cleanup(); + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) + { + m_failure = failures.Count == 0 ? failure : new AggregateException( + "Catalog cleanup remains pending after earlier failures.", + [.. failures, failure] + ); + if (ReferenceEquals(m_failure, failure)) + { + throw; + } + throw m_failure; + } + catch (Exception exception) + { + failures.Add(exception); + } + } +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CatalogParticipantRegistration.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CatalogParticipantRegistration.cs new file mode 100644 index 000000000..21a6332b8 --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Catalog/CatalogParticipantRegistration.cs @@ -0,0 +1,26 @@ +using System; + +namespace Inno.Extensibility.Modules; + +internal sealed class CatalogParticipantRegistration( + AssemblyCatalogCoordinator owner, + Guid id +) : IDisposable +{ + private bool m_disposed; + + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + m_disposed = true; + owner.Unregister(id); + } + + internal Guid id { get; } = id; +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleInfo.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleInfo.cs index 4f4d676bf..59e3af5d2 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleInfo.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Modules/AssemblyModuleInfo.cs @@ -1,19 +1,7 @@ -using System; using System.Collections.Generic; namespace Inno.Extensibility.Modules; -/// -/// Describes the catalog state of a published assembly module generation. -/// -public enum AssemblyModuleStatus -{ - /// - /// The module generation is visible to assembly catalog participants. - /// - Active -} - /// /// Provides non-owning diagnostic information about an active assembly module. /// @@ -60,3 +48,14 @@ IReadOnlyList assemblyNames /// public IReadOnlyList upstreamModuleNames { get; init; } = []; } + +/// +/// Describes the catalog state of a published assembly module generation. +/// +public enum AssemblyModuleStatus +{ + /// + /// The module generation is visible to assembly catalog participants. + /// + Active +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs index 8dcc99447..f09cf3e01 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/AssemblyReloadSession.cs @@ -138,15 +138,3 @@ private void EnsureRetirementSafe() } } } - -internal sealed class ReloadState -{ - internal required AssemblyModuleEntry?[] previousModules { get; init; } - internal required AssemblyModuleEntry[] removedModules { get; init; } - internal required AssemblyModuleEntry[] candidateModules { get; init; } - internal required AssemblyCatalogSnapshot previousCatalog { get; init; } - internal required AssemblyCatalogSnapshot candidateCatalog { get; init; } - internal required AssemblyCatalogRefreshSet refresh { get; init; } - internal bool activated { get; set; } - internal bool finished { get; set; } -} diff --git a/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/ReloadState.cs b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/ReloadState.cs new file mode 100644 index 000000000..e276c12fe --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Modules/Reloading/ReloadState.cs @@ -0,0 +1,13 @@ +namespace Inno.Extensibility.Modules; + +internal sealed class ReloadState +{ + internal required AssemblyModuleEntry?[] previousModules { get; init; } + internal required AssemblyModuleEntry[] removedModules { get; init; } + internal required AssemblyModuleEntry[] candidateModules { get; init; } + internal required AssemblyCatalogSnapshot previousCatalog { get; init; } + internal required AssemblyCatalogSnapshot candidateCatalog { get; init; } + internal required AssemblyCatalogRefreshSet refresh { get; init; } + internal bool activated { get; set; } + internal bool finished { get; set; } +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistry.cs new file mode 100644 index 000000000..1d85fbca9 --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistry.cs @@ -0,0 +1,15 @@ +namespace Inno.Extensibility.Types; + +internal interface ITypeRegistry +{ + /// + /// Builds and validates candidate state without changing the active generation. + /// + /// + /// The active type catalog generation used for extension resolution. + /// + /// + /// The validated itype registry transaction that represents the completed operation. + /// + ITypeRegistryTransaction Prepare(TypeCacheSnapshot types); +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistryTransaction.cs b/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistryTransaction.cs new file mode 100644 index 000000000..207b02866 --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Types/ITypeRegistryTransaction.cs @@ -0,0 +1,19 @@ +namespace Inno.Extensibility.Types; + +internal interface ITypeRegistryTransaction +{ + /// + /// Makes the prepared value active at the owning subsystem's safety point. + /// + void Activate(); + + /// + /// Finalizes candidate activation and releases temporary transaction state. + /// + void Complete(); + + /// + /// Restores the state captured before the current transaction began. + /// + void Rollback(); +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs index 3464b9049..741bdbfcd 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryCoordinator.cs @@ -4,58 +4,6 @@ namespace Inno.Extensibility.Types; -internal interface ITypeRegistry -{ - /// - /// Builds and validates candidate state without changing the active generation. - /// - /// - /// The active type catalog generation used for extension resolution. - /// - /// - /// The validated itype registry transaction that represents the completed operation. - /// - ITypeRegistryTransaction Prepare(TypeCacheSnapshot types); -} - -internal interface ITypeRegistryTransaction -{ - /// - /// Makes the prepared value active at the owning subsystem's safety point. - /// - void Activate(); - - /// - /// Finalizes candidate activation and releases temporary transaction state. - /// - void Complete(); - - /// - /// Restores the state captured before the current transaction began. - /// - void Rollback(); -} - -internal sealed class TypeRegistryNoopTransaction : ITypeRegistryTransaction -{ - /// - /// Makes the prepared value active at the owning subsystem's safety point. - /// - public void Activate() {} - - /// - /// Finalizes candidate activation and releases temporary transaction state. - /// - public void Complete() {} - - /// - /// Restores the state captured before the current transaction began. - /// - public void Rollback() {} - - internal static TypeRegistryNoopTransaction instance { get; } = new(); -} - internal sealed class TypeRegistryCoordinator { private readonly object m_sync = new(); @@ -155,150 +103,3 @@ private readonly record struct RegistryReference( WeakReference registry ); } - -internal sealed class TypeRegistryRegistration( - TypeRegistryCoordinator owner, - Guid id -) : IDisposable -{ - private bool m_disposed; - - /// - /// Releases the resources owned by this instance. - /// - public void Dispose() - { - if (m_disposed) - { - return; - } - m_disposed = true; - owner.Unregister(id); - } - - internal Guid id { get; } = id; -} - -internal sealed class TypeRegistryRefreshSet(IReadOnlyList transactions) -{ - private int m_activatedCount; - private bool m_finished; - private Exception? m_failure; - - internal void Activate() - { - if (m_failure is not null) - { - throw m_failure; - } - if (m_finished) - { - throw new InvalidOperationException("Type registry refresh set is already finished."); - } - try - { - for (; m_activatedCount < transactions.Count; m_activatedCount++) - { - transactions[m_activatedCount].Activate(); - } - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) - { - m_failure = failure; - throw; - } - catch (Exception activationFailure) - { - try - { - Rollback(); - } - catch (Exception rollbackFailure) - { - var combined = new AggregateException( - "Type registry activation and rollback failed.", - activationFailure, - rollbackFailure - ); - if (RetirementPendingException.Find(combined) is not null) - { - m_failure = combined; - } - throw combined; - } - throw; - } - } - - internal void Complete() - { - if (m_failure is not null) - { - throw m_failure; - } - if (m_finished) - { - return; - } - List failures = []; - for (int i = 0; i < transactions.Count; i++) - { - TryCleanup(transactions[i].Complete, failures); - } - m_finished = true; - transactions = []; - if (failures.Count > 0) - { - throw new AggregateException("Type registry completion failed after all participants were attempted.", failures); - } - } - - internal void Rollback() - { - if (m_failure is not null) - { - throw m_failure; - } - if (m_finished) - { - return; - } - List failures = []; - for (int i = transactions.Count - 1; i >= 0; i--) - { - TryCleanup(transactions[i].Rollback, failures); - } - m_finished = true; - transactions = []; - if (failures.Count > 0) - { - throw new AggregateException("Type registry rollback failed after all participants were attempted.", failures); - } - } - - private void TryCleanup( - Action cleanup, - List failures - ) { - try - { - cleanup(); - } - catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) - { - m_failure = failures.Count == 0 ? failure : new AggregateException( - "Registry cleanup remains pending after earlier failures.", - [.. failures, failure] - ); - if (ReferenceEquals(m_failure, failure)) - { - throw; - } - throw m_failure; - } - catch (Exception exception) - { - failures.Add(exception); - } - } -} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryNoopTransaction.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryNoopTransaction.cs new file mode 100644 index 000000000..05090b41f --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryNoopTransaction.cs @@ -0,0 +1,21 @@ +namespace Inno.Extensibility.Types; + +internal sealed class TypeRegistryNoopTransaction : ITypeRegistryTransaction +{ + /// + /// Makes the prepared value active at the owning subsystem's safety point. + /// + public void Activate() {} + + /// + /// Finalizes candidate activation and releases temporary transaction state. + /// + public void Complete() {} + + /// + /// Restores the state captured before the current transaction began. + /// + public void Rollback() {} + + internal static TypeRegistryNoopTransaction instance { get; } = new(); +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRefreshSet.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRefreshSet.cs new file mode 100644 index 000000000..f05856586 --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRefreshSet.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Execution; + +namespace Inno.Extensibility.Types; + +internal sealed class TypeRegistryRefreshSet(IReadOnlyList transactions) +{ + private int m_activatedCount; + private bool m_finished; + private Exception? m_failure; + + internal void Activate() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + throw new InvalidOperationException("Type registry refresh set is already finished."); + } + try + { + for (; m_activatedCount < transactions.Count; m_activatedCount++) + { + transactions[m_activatedCount].Activate(); + } + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) + { + m_failure = failure; + throw; + } + catch (Exception activationFailure) + { + try + { + Rollback(); + } + catch (Exception rollbackFailure) + { + var combined = new AggregateException( + "Type registry activation and rollback failed.", + activationFailure, + rollbackFailure + ); + if (RetirementPendingException.Find(combined) is not null) + { + m_failure = combined; + } + throw combined; + } + throw; + } + } + + internal void Complete() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + return; + } + List failures = []; + for (int i = 0; i < transactions.Count; i++) + { + TryCleanup(transactions[i].Complete, failures); + } + m_finished = true; + transactions = []; + if (failures.Count > 0) + { + throw new AggregateException("Type registry completion failed after all participants were attempted.", failures); + } + } + + internal void Rollback() + { + if (m_failure is not null) + { + throw m_failure; + } + if (m_finished) + { + return; + } + List failures = []; + for (int i = transactions.Count - 1; i >= 0; i--) + { + TryCleanup(transactions[i].Rollback, failures); + } + m_finished = true; + transactions = []; + if (failures.Count > 0) + { + throw new AggregateException("Type registry rollback failed after all participants were attempted.", failures); + } + } + + private void TryCleanup( + Action cleanup, + List failures + ) { + try + { + cleanup(); + } + catch (Exception failure) when (RetirementPendingException.Find(failure) is not null) + { + m_failure = failures.Count == 0 ? failure : new AggregateException( + "Registry cleanup remains pending after earlier failures.", + [.. failures, failure] + ); + if (ReferenceEquals(m_failure, failure)) + { + throw; + } + throw m_failure; + } + catch (Exception exception) + { + failures.Add(exception); + } + } +} diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRegistration.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRegistration.cs new file mode 100644 index 000000000..d247ec82c --- /dev/null +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistryRegistration.cs @@ -0,0 +1,26 @@ +using System; + +namespace Inno.Extensibility.Types; + +internal sealed class TypeRegistryRegistration( + TypeRegistryCoordinator owner, + Guid id +) : IDisposable +{ + private bool m_disposed; + + /// + /// Releases the resources owned by this instance. + /// + public void Dispose() + { + if (m_disposed) + { + return; + } + m_disposed = true; + owner.Unregister(id); + } + + internal Guid id { get; } = id; +} diff --git a/src/runtime/engine/Inno.Runtime/Execution/RuntimeClock.cs b/src/runtime/engine/Inno.Runtime/Execution/RuntimeClock.cs new file mode 100644 index 000000000..dcc8e5ab6 --- /dev/null +++ b/src/runtime/engine/Inno.Runtime/Execution/RuntimeClock.cs @@ -0,0 +1,65 @@ +using System; +using Inno.Core.Execution; +using Inno.Runtime.Contracts; + +namespace Inno.Runtime; + +internal sealed class RuntimeClock +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("clock"); + + internal static RuntimeClock current => CURRENT_SCOPE.current; + + internal float time { get; private set; } + + internal float deltaTime { get; private set; } + + internal float unscaledTime { get; private set; } + + internal float unscaledDeltaTime { get; private set; } + + internal float fixedTime { get; private set; } + + internal float fixedDeltaTime { get; private set; } + + internal float timeScale { get; private set; } = 1f; + + internal bool isPaused { get; private set; } + + internal long frameCount { get; private set; } + + internal long fixedStepCount { get; private set; } + + internal IDisposable EnterScope() => CURRENT_SCOPE.Enter(this); + + internal RuntimeFrame Update(float unscaledDeltaTime) + { + this.unscaledDeltaTime = unscaledDeltaTime; + unscaledTime += unscaledDeltaTime; + deltaTime = isPaused ? 0f : unscaledDeltaTime * timeScale; + time += deltaTime; + var frame = new RuntimeFrame(frameCount, time, unscaledTime, deltaTime, unscaledDeltaTime, timeScale, isPaused); + frameCount++; + return frame; + } + + internal RuntimeFixedFrame BeginFixedStep(float fixedDeltaTime) + { + this.fixedDeltaTime = fixedDeltaTime; + fixedTime += fixedDeltaTime; + var frame = new RuntimeFixedFrame(fixedStepCount, fixedTime, fixedDeltaTime); + fixedStepCount++; + return frame; + } + + internal void SetTimeScale(float value) + { + if (!float.IsFinite(value) || value < 0f) + { + throw new ArgumentOutOfRangeException(nameof(value), "Time scale must be finite and non-negative."); + } + timeScale = value; + } + + internal void SetPaused(bool value) => isPaused = value; +} diff --git a/src/runtime/engine/Inno.Runtime/Execution/Time.cs b/src/runtime/engine/Inno.Runtime/Execution/Time.cs index 5898004f0..254f47cd9 100644 --- a/src/runtime/engine/Inno.Runtime/Execution/Time.cs +++ b/src/runtime/engine/Inno.Runtime/Execution/Time.cs @@ -1,7 +1,4 @@ using System; -using System.Threading; -using Inno.Core.Execution; -using Inno.Runtime.Contracts; namespace Inno.Runtime; @@ -94,63 +91,3 @@ public static bool isPaused /// public static long frameCount => RuntimeClock.current.frameCount; } - -internal sealed class RuntimeClock -{ - private static readonly ExecutionSlot CURRENT_SCOPE = new("clock"); - - internal static RuntimeClock current => CURRENT_SCOPE.current; - - internal float time { get; private set; } - - internal float deltaTime { get; private set; } - - internal float unscaledTime { get; private set; } - - internal float unscaledDeltaTime { get; private set; } - - internal float fixedTime { get; private set; } - - internal float fixedDeltaTime { get; private set; } - - internal float timeScale { get; private set; } = 1f; - - internal bool isPaused { get; private set; } - - internal long frameCount { get; private set; } - - internal long fixedStepCount { get; private set; } - - internal IDisposable EnterScope() => CURRENT_SCOPE.Enter(this); - - internal RuntimeFrame Update(float unscaledDeltaTime) - { - this.unscaledDeltaTime = unscaledDeltaTime; - unscaledTime += unscaledDeltaTime; - deltaTime = isPaused ? 0f : unscaledDeltaTime * timeScale; - time += deltaTime; - var frame = new RuntimeFrame(frameCount, time, unscaledTime, deltaTime, unscaledDeltaTime, timeScale, isPaused); - frameCount++; - return frame; - } - - internal RuntimeFixedFrame BeginFixedStep(float fixedDeltaTime) - { - this.fixedDeltaTime = fixedDeltaTime; - fixedTime += fixedDeltaTime; - var frame = new RuntimeFixedFrame(fixedStepCount, fixedTime, fixedDeltaTime); - fixedStepCount++; - return frame; - } - - internal void SetTimeScale(float value) - { - if (!float.IsFinite(value) || value < 0f) - { - throw new ArgumentOutOfRangeException(nameof(value), "Time scale must be finite and non-negative."); - } - timeScale = value; - } - - internal void SetPaused(bool value) => isPaused = value; -} diff --git a/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs b/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs index 4b07fcd4d..f9d138106 100644 --- a/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs +++ b/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationSettings.cs @@ -86,60 +86,3 @@ int availableHeight ); } } - -/// -/// Stores one centered game-content region within a presentation surface. -/// -public readonly record struct GamePresentationViewport -{ - /// - /// Creates a validated game presentation viewport. - /// - /// - /// Non-negative horizontal offset. - /// - /// - /// Non-negative vertical offset. - /// - /// - /// Positive content width. - /// - /// - /// Positive content height. - /// - public GamePresentationViewport( - int x, - int y, - int width, - int height - ) { - ArgumentOutOfRangeException.ThrowIfNegative(x); - ArgumentOutOfRangeException.ThrowIfNegative(y); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - this.x = x; - this.y = y; - this.width = width; - this.height = height; - } - - /// - /// Gets the horizontal content offset. - /// - public int x { get; } - - /// - /// Gets the vertical content offset. - /// - public int y { get; } - - /// - /// Gets the content width. - /// - public int width { get; } - - /// - /// Gets the content height. - /// - public int height { get; } -} diff --git a/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationViewport.cs b/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationViewport.cs new file mode 100644 index 000000000..8fc7e1487 --- /dev/null +++ b/src/runtime/engine/Inno.Runtime/Presentation/GamePresentationViewport.cs @@ -0,0 +1,60 @@ +using System; + +namespace Inno.Runtime; + +/// +/// Stores one centered game-content region within a presentation surface. +/// +public readonly record struct GamePresentationViewport +{ + /// + /// Creates a validated game presentation viewport. + /// + /// + /// Non-negative horizontal offset. + /// + /// + /// Non-negative vertical offset. + /// + /// + /// Positive content width. + /// + /// + /// Positive content height. + /// + public GamePresentationViewport( + int x, + int y, + int width, + int height + ) { + ArgumentOutOfRangeException.ThrowIfNegative(x); + ArgumentOutOfRangeException.ThrowIfNegative(y); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + this.x = x; + this.y = y; + this.width = width; + this.height = height; + } + + /// + /// Gets the horizontal content offset. + /// + public int x { get; } + + /// + /// Gets the vertical content offset. + /// + public int y { get; } + + /// + /// Gets the content width. + /// + public int width { get; } + + /// + /// Gets the content height. + /// + public int height { get; } +} diff --git a/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs b/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs index 23cfca303..a736b8015 100644 --- a/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs +++ b/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystem.cs @@ -3,30 +3,6 @@ namespace Inno.Runtime; -internal sealed class SceneRuntimeSubsystemFactory( - SceneWorld scenes, - RuntimeSessionKind kind -) : IRuntimeSubsystemFactory -{ - internal static readonly RuntimeSubsystemID SUBSYSTEM_ID = new("inno.runtime.scene"); - - /// - /// Gets the stable descriptor for the built-in scene simulation subsystem. - /// - public RuntimeSubsystemDescriptor descriptor { get; } = new(SUBSYSTEM_ID, order: 0); - - /// - /// Creates the scene subsystem for the isolated runtime session. - /// - /// - /// The session context that supplies the scene world and session kind. - /// - /// - /// A new subsystem that advances the context's scene world. - /// - public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => new SceneRuntimeSubsystem(scenes, kind); -} - internal sealed class SceneRuntimeSubsystem( SceneWorld scenes, RuntimeSessionKind sessionKind diff --git a/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystemFactory.cs b/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystemFactory.cs new file mode 100644 index 000000000..7ec9f0a82 --- /dev/null +++ b/src/runtime/engine/Inno.Runtime/Subsystems/SceneRuntimeSubsystemFactory.cs @@ -0,0 +1,28 @@ +using Inno.Runtime.Contracts; +using Inno.Scene; + +namespace Inno.Runtime; + +internal sealed class SceneRuntimeSubsystemFactory( + SceneWorld scenes, + RuntimeSessionKind kind +) : IRuntimeSubsystemFactory +{ + internal static readonly RuntimeSubsystemID SUBSYSTEM_ID = new("inno.runtime.scene"); + + /// + /// Gets the stable descriptor for the built-in scene simulation subsystem. + /// + public RuntimeSubsystemDescriptor descriptor { get; } = new(SUBSYSTEM_ID, order: 0); + + /// + /// Creates the scene subsystem for the isolated runtime session. + /// + /// + /// The session context that supplies the scene world and session kind. + /// + /// + /// A new subsystem that advances the context's scene world. + /// + public IRuntimeSubsystem Create(RuntimeSubsystemContext context) => new SceneRuntimeSubsystem(scenes, kind); +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginCandidate.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginCandidate.cs new file mode 100644 index 000000000..35be76c2b --- /dev/null +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginCandidate.cs @@ -0,0 +1,75 @@ +using System.Linq; +using Inno.Assets.Pipeline; +using Inno.Core.Settings; + +namespace Inno.Plugins.Authoring; + +/// +/// Describes one validated installed Plugin source candidate. +/// +public sealed class PluginCandidate +{ + private readonly PluginManifest m_manifest; + + internal PluginCandidate( + string sourcePath, + PluginSourceKind sourceKind, + string contentHash, + PluginManifest manifest, + AssetSourceMount sourceMount, + bool containsCode + ) { + this.sourcePath = sourcePath; + this.sourceKind = sourceKind; + this.contentHash = contentHash; + m_manifest = CloneManifest(manifest); + this.sourceMount = sourceMount; + this.containsCode = containsCode; + } + + /// + /// Gets the installed .iplugin package path. + /// + public string sourcePath { get; } + + /// + /// Gets the physical source container kind. + /// + public PluginSourceKind sourceKind { get; } + + /// + /// Gets the deterministic complete source-content hash. + /// + public string contentHash { get; } + + /// + /// Gets a detached copy of the validated native manifest, including its nested contribution payloads. + /// + public PluginManifest manifest => CloneManifest(m_manifest); + + /// + /// Gets the isolated read-only asset source mount. + /// + public AssetSourceMount sourceMount { get; } + + /// + /// Gets whether source code exists in this Plugin. + /// + public bool containsCode { get; } + + private static PluginManifest CloneManifest(PluginManifest value) + => new() + { + pluginId = value.pluginId, + displayName = value.displayName, + dependencies = value.dependencies.ToArray(), + overrides = value.overrides.ToArray(), + contentRoots = value.contentRoots.ToArray(), + assemblyDefinitions = value.assemblyDefinitions.ToArray(), + settingContributions = value.settingContributions.Select(static record => new ProjectSettingRecord( + record.id, + record.stableTypeId, + record.propertyData + )).ToArray() + }; +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginDiagnostic.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginDiagnostic.cs new file mode 100644 index 000000000..155f3c94d --- /dev/null +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginDiagnostic.cs @@ -0,0 +1,34 @@ +namespace Inno.Plugins.Authoring; + +/// +/// Reports one Plugin discovery, validation, or dependency problem. +/// +public sealed class PluginDiagnostic +{ + /// + /// Creates a Plugin source diagnostic. + /// + /// + /// Related .iplugin package path or invalid installation entry. + /// + /// + /// Actionable problem description. + /// + public PluginDiagnostic( + string sourcePath, + string message + ) { + this.sourcePath = sourcePath ?? string.Empty; + this.message = message ?? string.Empty; + } + + /// + /// Gets the related .iplugin package path or invalid installation entry. + /// + public string sourcePath { get; } + + /// + /// Gets the actionable problem description. + /// + public string message { get; } +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginScanResult.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginScanResult.cs new file mode 100644 index 000000000..91825bb9b --- /dev/null +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginScanResult.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Plugins.Authoring; + +/// +/// Contains a complete immutable Plugin discovery result. +/// +public sealed class PluginScanResult +{ + internal PluginScanResult( + IReadOnlyList candidates, + IReadOnlyList diagnostics + ) { + this.candidates = Array.AsReadOnly(candidates.ToArray()); + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets dependency-ordered valid candidates. + /// + public IReadOnlyList candidates { get; } + + /// + /// Gets isolated diagnostics for rejected candidates. + /// + public IReadOnlyList diagnostics { get; } +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceKind.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceKind.cs new file mode 100644 index 000000000..83581dfe5 --- /dev/null +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceKind.cs @@ -0,0 +1,16 @@ +namespace Inno.Plugins.Authoring; + +/// +/// Identifies how an .iplugin package participates in one installation. +/// +public enum PluginSourceKind +{ + /// + /// The Plugin is installed as one top-level .iplugin package. + /// + Package, + /// + /// The Plugin is embedded as one complete .iplugin dependency package. + /// + EmbeddedPackage +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceLimits.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceLimits.cs new file mode 100644 index 000000000..49b86e9dc --- /dev/null +++ b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceLimits.cs @@ -0,0 +1,42 @@ +namespace Inno.Plugins.Authoring; + +/// +/// Controls bounded validation and archive extraction for installed Plugin packages. +/// +public sealed class PluginSourceLimits +{ + /// + /// Gets default conservative local Plugin limits. + /// + public static PluginSourceLimits defaults { get; } = new(); + + /// + /// Gets or initializes the maximum number of source entries. + /// + public int maximumEntryCount { get; init; } = 100_000; + + /// + /// Gets or initializes the maximum size of one source file. + /// + public long maximumFileBytes { get; init; } = 64L * 1024 * 1024; + + /// + /// Gets or initializes the maximum total source size. + /// + public long maximumTotalBytes { get; init; } = 1024L * 1024 * 1024; + + /// + /// Gets or initializes the maximum accepted archive uncompressed-to-compressed ratio. + /// + public double maximumCompressionRatio { get; init; } = 200d; + + /// + /// Gets or initializes the maximum number of embedded dependency packages in one installation. + /// + public int maximumEmbeddedPluginCount { get; init; } = 256; + + /// + /// Gets or initializes the maximum nested embedded dependency depth. + /// + public int maximumEmbeddedDepth { get; init; } = 16; +} diff --git a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs b/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs deleted file mode 100644 index 0f086303e..000000000 --- a/src/runtime/plugins/Inno.Plugins.Authoring/PluginSourceModels.cs +++ /dev/null @@ -1,191 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Inno.Assets.Pipeline; -using Inno.Core.Settings; -using Inno.Plugins; - -namespace Inno.Plugins.Authoring; - -/// -/// Identifies how an .iplugin package participates in one installation. -/// -public enum PluginSourceKind -{ - /// - /// The Plugin is installed as one top-level .iplugin package. - /// - Package, - /// - /// The Plugin is embedded as one complete .iplugin dependency package. - /// - EmbeddedPackage -} - -/// -/// Controls bounded validation and archive extraction for installed Plugin packages. -/// -public sealed class PluginSourceLimits -{ - /// - /// Gets default conservative local Plugin limits. - /// - public static PluginSourceLimits defaults { get; } = new(); - - /// - /// Gets or initializes the maximum number of source entries. - /// - public int maximumEntryCount { get; init; } = 100_000; - - /// - /// Gets or initializes the maximum size of one source file. - /// - public long maximumFileBytes { get; init; } = 64L * 1024 * 1024; - - /// - /// Gets or initializes the maximum total source size. - /// - public long maximumTotalBytes { get; init; } = 1024L * 1024 * 1024; - - /// - /// Gets or initializes the maximum accepted archive uncompressed-to-compressed ratio. - /// - public double maximumCompressionRatio { get; init; } = 200d; - - /// - /// Gets or initializes the maximum number of embedded dependency packages in one installation. - /// - public int maximumEmbeddedPluginCount { get; init; } = 256; - - /// - /// Gets or initializes the maximum nested embedded dependency depth. - /// - public int maximumEmbeddedDepth { get; init; } = 16; -} - -/// -/// Describes one validated installed Plugin source candidate. -/// -public sealed class PluginCandidate -{ - private readonly PluginManifest m_manifest; - - internal PluginCandidate( - string sourcePath, - PluginSourceKind sourceKind, - string contentHash, - PluginManifest manifest, - AssetSourceMount sourceMount, - bool containsCode - ) { - this.sourcePath = sourcePath; - this.sourceKind = sourceKind; - this.contentHash = contentHash; - m_manifest = CloneManifest(manifest); - this.sourceMount = sourceMount; - this.containsCode = containsCode; - } - - /// - /// Gets the installed .iplugin package path. - /// - public string sourcePath { get; } - - /// - /// Gets the physical source container kind. - /// - public PluginSourceKind sourceKind { get; } - - /// - /// Gets the deterministic complete source-content hash. - /// - public string contentHash { get; } - - /// - /// Gets a detached copy of the validated native manifest, including its nested contribution payloads. - /// - public PluginManifest manifest => CloneManifest(m_manifest); - - /// - /// Gets the isolated read-only asset source mount. - /// - public AssetSourceMount sourceMount { get; } - - /// - /// Gets whether source code exists in this Plugin. - /// - public bool containsCode { get; } - - private static PluginManifest CloneManifest(PluginManifest value) - => new() - { - pluginId = value.pluginId, - displayName = value.displayName, - dependencies = value.dependencies.ToArray(), - overrides = value.overrides.ToArray(), - contentRoots = value.contentRoots.ToArray(), - assemblyDefinitions = value.assemblyDefinitions.ToArray(), - settingContributions = value.settingContributions.Select(static record => new ProjectSettingRecord( - record.id, - record.stableTypeId, - record.propertyData - )).ToArray() - }; -} - -/// -/// Reports one Plugin discovery, validation, or dependency problem. -/// -public sealed class PluginDiagnostic -{ - /// - /// Creates a Plugin source diagnostic. - /// - /// - /// Related .iplugin package path or invalid installation entry. - /// - /// - /// Actionable problem description. - /// - public PluginDiagnostic( - string sourcePath, - string message - ) { - this.sourcePath = sourcePath ?? string.Empty; - this.message = message ?? string.Empty; - } - - /// - /// Gets the related .iplugin package path or invalid installation entry. - /// - public string sourcePath { get; } - - /// - /// Gets the actionable problem description. - /// - public string message { get; } -} - -/// -/// Contains a complete immutable Plugin discovery result. -/// -public sealed class PluginScanResult -{ - internal PluginScanResult( - IReadOnlyList candidates, - IReadOnlyList diagnostics - ) { - this.candidates = Array.AsReadOnly(candidates.ToArray()); - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - - /// - /// Gets dependency-ordered valid candidates. - /// - public IReadOnlyList candidates { get; } - - /// - /// Gets isolated diagnostics for rejected candidates. - /// - public IReadOnlyList diagnostics { get; } -} diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeDeclaration.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeDeclaration.cs new file mode 100644 index 000000000..c4bb9c7a0 --- /dev/null +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeDeclaration.cs @@ -0,0 +1,61 @@ +namespace Inno.Scripting.Compiler; + +internal struct ScriptSourceTypeDeclaration +{ + /// + /// Creates a validated script source type declaration instance. + /// + /// + /// The type name text validated by the script source type declaration operation. + /// + /// + /// The declaration kind text validated by the script source type declaration operation. + /// + /// + /// Whether partial behavior is enabled while script source type declaration executes. + /// + /// + /// The line consumed by script source type declaration; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The column consumed by script source type declaration; ownership remains with the caller unless explicitly stated otherwise. + /// + public ScriptSourceTypeDeclaration( + string typeName, + string declarationKind, + bool partial, + int line, + int column + ) { + this.typeName = typeName; + this.declarationKind = declarationKind; + this.partial = partial; + this.line = line; + this.column = column; + } + + /// + /// Gets text used for stable identity, presentation, or diagnostics by this contract. + /// + public string typeName { get; set; } + + /// + /// Gets text used for stable identity, presentation, or diagnostics by this contract. + /// + public string declarationKind { get; set; } + + /// + /// Gets whether the caller-visible condition represented by this property is satisfied. + /// + public bool partial { get; set; } + + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public int line { get; set; } + + /// + /// Gets the scalar measurement or identity associated with the current state. + /// + public int column { get; set; } +} diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs index e0ff3d9b0..b98d80101 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Assets/ScriptSourceTypeManifest.cs @@ -50,63 +50,3 @@ ScriptSourceTypeDeclaration[] declarations [SerializableProperty] public ScriptSourceTypeDeclaration[] declarations { get; set; } = []; } - -internal struct ScriptSourceTypeDeclaration -{ - /// - /// Creates a validated script source type declaration instance. - /// - /// - /// The type name text validated by the script source type declaration operation. - /// - /// - /// The declaration kind text validated by the script source type declaration operation. - /// - /// - /// Whether partial behavior is enabled while script source type declaration executes. - /// - /// - /// The line consumed by script source type declaration; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The column consumed by script source type declaration; ownership remains with the caller unless explicitly stated otherwise. - /// - public ScriptSourceTypeDeclaration( - string typeName, - string declarationKind, - bool partial, - int line, - int column - ) { - this.typeName = typeName; - this.declarationKind = declarationKind; - this.partial = partial; - this.line = line; - this.column = column; - } - - /// - /// Gets text used for stable identity, presentation, or diagnostics by this contract. - /// - public string typeName { get; set; } - - /// - /// Gets text used for stable identity, presentation, or diagnostics by this contract. - /// - public string declarationKind { get; set; } - - /// - /// Gets whether the caller-visible condition represented by this property is satisfied. - /// - public bool partial { get; set; } - - /// - /// Gets the scalar measurement or identity associated with the current state. - /// - public int line { get; set; } - - /// - /// Gets the scalar measurement or identity associated with the current state. - /// - public int column { get; set; } -} diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs index 4593c9377..89f66e458 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiCatalog.cs @@ -9,44 +9,6 @@ namespace Inno.Scripting.Compiler; -internal sealed record ScriptApiAssembly( - Assembly assembly, - IReadOnlyList exports -); - -internal sealed record ScriptApiTypeExport( - Type type, - string name -); - -internal sealed record ScriptApiNamespaceMapping( - string apiNamespace, - string implementationNamespace -); - -internal sealed record ScriptApiTypeMapping( - string apiNamespace, - string apiName, - string implementationNamespace, - string implementationName, - int arity -); - -internal sealed record ScriptApiAttachableType( - string implementationName, - string kind -); - -internal sealed record ScriptApiProfile( - string name, - IReadOnlyList exports, - IReadOnlyList implementationAssemblies, - IReadOnlyList apiNamespaces, - IReadOnlyList namespaceMappings, - IReadOnlyList typeMappings, - IReadOnlyList attachableTypes -); - internal static class ScriptApiCatalog { internal static ScriptApiProfile Build(bool includeEditor) @@ -341,3 +303,41 @@ private sealed record DeclaredTypeExport( string name ); } + +internal sealed record ScriptApiAssembly( + Assembly assembly, + IReadOnlyList exports +); + +internal sealed record ScriptApiTypeExport( + Type type, + string name +); + +internal sealed record ScriptApiNamespaceMapping( + string apiNamespace, + string implementationNamespace +); + +internal sealed record ScriptApiTypeMapping( + string apiNamespace, + string apiName, + string implementationNamespace, + string implementationName, + int arity +); + +internal sealed record ScriptApiAttachableType( + string implementationName, + string kind +); + +internal sealed record ScriptApiProfile( + string name, + IReadOnlyList exports, + IReadOnlyList implementationAssemblies, + IReadOnlyList apiNamespaces, + IReadOnlyList namespaceMappings, + IReadOnlyList typeMappings, + IReadOnlyList attachableTypes +); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs index cead48cb3..fed727b87 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiMap.cs @@ -62,17 +62,3 @@ CancellationToken cancellationToken return new ScriptApiMap(namespaces); } } - -internal sealed class ScriptApiNamespaceMap -{ - internal ScriptApiNamespaceMap( - string apiNamespace, - ImmutableArray implementationNamespaces - ) { - this.apiNamespace = apiNamespace; - this.implementationNamespaces = implementationNamespaces; - } - - internal string apiNamespace { get; } - internal ImmutableArray implementationNamespaces { get; } -} diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiNamespaceMap.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiNamespaceMap.cs new file mode 100644 index 000000000..54e703eab --- /dev/null +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiNamespaceMap.cs @@ -0,0 +1,17 @@ +using System.Collections.Immutable; + +namespace Inno.Scripting.Compiler; + +internal sealed class ScriptApiNamespaceMap +{ + internal ScriptApiNamespaceMap( + string apiNamespace, + ImmutableArray implementationNamespaces + ) { + this.apiNamespace = apiNamespace; + this.implementationNamespaces = implementationNamespaces; + } + + internal string apiNamespace { get; } + internal ImmutableArray implementationNamespaces { get; } +} diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs index 37adec85c..0c371d162 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptApiReferenceBuilder.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading; @@ -13,15 +12,6 @@ namespace Inno.Scripting.Compiler; -internal sealed record ScriptApiReferenceSet( - IReadOnlyList runtimeReferencePaths, - IReadOnlyList ideReferencePaths, - string contractFingerprint, - string artifactFingerprint, - ScriptCompilationEnvironment environment, - string cacheDirectory -); - internal static class ScriptApiReferenceBuilder { private static readonly SemaphoreSlim BUILD_GATE = new(1, 1); @@ -441,3 +431,12 @@ private static string CreateFingerprint(ScriptApiProfile profile) return Convert.ToHexStringLower(hash); } } + +internal sealed record ScriptApiReferenceSet( + IReadOnlyList runtimeReferencePaths, + IReadOnlyList ideReferencePaths, + string contractFingerprint, + string artifactFingerprint, + ScriptCompilationEnvironment environment, + string cacheDirectory +); diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs index 1cc02c451..acdc08ee6 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Compilation/ScriptDeploymentReferenceResolver.cs @@ -8,11 +8,6 @@ namespace Inno.Scripting.Compiler; -internal sealed record ScriptDeploymentReferenceSet( - IReadOnlyList paths, - string fingerprint -); - internal static class ScriptDeploymentReferenceResolver { internal static ScriptDeploymentReferenceSet Resolve(string runtimeDirectory) @@ -83,3 +78,8 @@ string value hash.AppendData(bytes); } } + +internal sealed record ScriptDeploymentReferenceSet( + IReadOnlyList paths, + string fingerprint +); diff --git a/src/services/audio/Inno.Audio/Audio.cs b/src/services/audio/Inno.Audio/Audio.cs index 7f78b65ab..c3623976e 100644 --- a/src/services/audio/Inno.Audio/Audio.cs +++ b/src/services/audio/Inno.Audio/Audio.cs @@ -1,44 +1,9 @@ using System; using System.Threading; using System.Threading.Tasks; -using Inno.Core.Execution; namespace Inno.Audio; -/// -/// Binds one host-owned audio service to the current asynchronous execution context. -/// -public static class AudioExecutionContext -{ - private static readonly ExecutionSlot CURRENT_SCOPE = new("audio"); - - /// - /// Gets the audio service bound to the current asynchronous execution context. - /// - /// - /// Thrown when no audio service is active for the caller. - /// - public static IAudioService current => CURRENT_SCOPE.current; - - /// - /// Binds an audio service until the returned strict last-in-first-out scope is disposed. - /// - /// - /// Host-owned audio service exposed to script-facing operations. - /// - /// - /// A strict last-in-first-out scope owned by the caller. - /// - /// - /// Thrown when is . - /// - public static IDisposable EnterScope(IAudioService audio) - { - ArgumentNullException.ThrowIfNull(audio); - return CURRENT_SCOPE.Enter(audio); - } -} - /// /// Provides script-friendly access to the audio service in the current execution context. /// diff --git a/src/services/audio/Inno.Audio/AudioBusDefinition.cs b/src/services/audio/Inno.Audio/AudioBusDefinition.cs new file mode 100644 index 000000000..4803a1f3e --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioBusDefinition.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Audio; + +/// +/// Describes one bus and its ordered processor chain in a compiled mixer graph. +/// +public sealed class AudioBusDefinition +{ + private readonly AudioProcessorConfiguration[] m_processors; + + /// + /// Creates an immutable mixer bus definition. + /// + /// + /// Stable bus identifier. + /// + /// + /// Parent bus identifier, or only for the master bus. + /// + /// + /// Non-negative linear bus gain. + /// + /// + /// Whether output from the bus is initially silenced. + /// + /// + /// Ordered processor chain. + /// + public AudioBusDefinition( + AudioBusID id, + AudioBusID? parent, + float volume, + bool muted, + IEnumerable? processors = null + ) { + if (!id.isValid) + { + throw new ArgumentException("A valid bus identifier is required.", nameof(id)); + } + if (volume < 0f) + { + throw new ArgumentOutOfRangeException(nameof(volume)); + } + if (id == AudioBusID.master && parent is not null) + { + throw new ArgumentException("The master bus cannot have a parent.", nameof(parent)); + } + if (id != AudioBusID.master && (parent is null || !parent.Value.isValid)) + { + throw new ArgumentException("A non-master bus requires a valid parent.", nameof(parent)); + } + this.id = id; + this.parent = parent; + this.volume = volume; + this.muted = muted; + m_processors = processors?.ToArray() ?? []; + } + + /// + /// Gets the stable bus identifier. + /// + public AudioBusID id { get; } + + /// + /// Gets the parent bus, or for the master bus. + /// + public AudioBusID? parent { get; } + + /// + /// Gets the initial linear bus gain. + /// + public float volume { get; } + + /// + /// Gets whether output from the bus is initially silenced. + /// + public bool muted { get; } + + /// + /// Gets the ordered immutable processor chain. + /// + public IReadOnlyList processors => Array.AsReadOnly(m_processors); +} diff --git a/src/services/audio/Inno.Audio/AudioBusHandle.cs b/src/services/audio/Inno.Audio/AudioBusHandle.cs new file mode 100644 index 000000000..954a70ecd --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioBusHandle.cs @@ -0,0 +1,27 @@ +namespace Inno.Audio; + +/// +/// Identifies one backend mixer bus within a device generation. +/// +public readonly record struct AudioBusHandle +{ + internal AudioBusHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + + /// + /// Gets the generation of the device that created this handle. + /// + public uint deviceGeneration { get; } + + /// + /// Gets whether the handle contains a non-zero backend identity and generation. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/audio/Inno.Audio/AudioBusID.cs b/src/services/audio/Inno.Audio/AudioBusID.cs new file mode 100644 index 000000000..d95bd8cda --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioBusID.cs @@ -0,0 +1,44 @@ +using System; + +namespace Inno.Audio; + +/// +/// Identifies a mixer bus without imposing a closed bus catalog. +/// +public readonly record struct AudioBusID +{ + /// + /// Creates an open mixer bus identifier. + /// + /// + /// Globally stable bus protocol value. + /// + public AudioBusID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the mandatory root bus identifier. + /// + public static AudioBusID master { get; } = new("inno.audio.bus.master"); + + /// + /// Gets the globally stable protocol value. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats the identifier for diagnostics and persistence. + /// + /// + /// The stable protocol value. + /// + public override string ToString() => value; +} diff --git a/src/services/audio/Inno.Audio/AudioCapabilities.cs b/src/services/audio/Inno.Audio/AudioCapabilities.cs new file mode 100644 index 000000000..dd5305d21 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioCapabilities.cs @@ -0,0 +1,68 @@ +using System; + +namespace Inno.Audio; + +/// +/// Describes backend-neutral features and limits for one device generation. +/// +public sealed record AudioCapabilities +{ + /// + /// Creates an immutable audio capability snapshot. + /// + /// + /// Whether clips can be decoded incrementally. + /// + /// + /// Whether voices can start against the audio clock. + /// + /// + /// Whether listener-relative spatial playback is available. + /// + /// + /// Maximum simultaneously active listeners. + /// + /// + /// Device output sample rate in frames per second. + /// + public AudioCapabilities( + bool supportsStreaming, + bool supportsScheduledPlayback, + bool supportsSpatialAudio, + int maxListeners, + int sampleRate + ) { + ArgumentOutOfRangeException.ThrowIfNegative(maxListeners); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); + this.supportsStreaming = supportsStreaming; + this.supportsScheduledPlayback = supportsScheduledPlayback; + this.supportsSpatialAudio = supportsSpatialAudio; + this.maxListeners = maxListeners; + this.sampleRate = sampleRate; + } + + /// + /// Gets whether clips can be decoded incrementally. + /// + public bool supportsStreaming { get; } + + /// + /// Gets whether voices can start against the audio clock. + /// + public bool supportsScheduledPlayback { get; } + + /// + /// Gets whether listener-relative spatial playback is available. + /// + public bool supportsSpatialAudio { get; } + + /// + /// Gets the maximum simultaneously active listener count. + /// + public int maxListeners { get; } + + /// + /// Gets the output sample rate in frames per second. + /// + public int sampleRate { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioClipAsset.cs b/src/services/audio/Inno.Audio/AudioClipAsset.cs index 52cf55614..41abee7e4 100644 --- a/src/services/audio/Inno.Audio/AudioClipAsset.cs +++ b/src/services/audio/Inno.Audio/AudioClipAsset.cs @@ -1,162 +1,9 @@ using System; -using System.Buffers.Binary; -using System.Text; using Inno.Assets; using Inno.Extensibility.Types; namespace Inno.Audio; -/// -/// Describes imported encoded audio independently from its runtime storage path. -/// -public readonly record struct AudioClipMetadata -{ - /// - /// Creates imported audio metadata. - /// - /// - /// Codec protocol of the encoded artifact. - /// - /// - /// Encoded channel count. - /// - /// - /// Sample rate in frames per second. - /// - /// - /// Total decoded frame count. - /// - /// - /// Encoded artifact length in bytes. - /// - public AudioClipMetadata( - AudioCodecID codec, - int channels, - int sampleRate, - long frameCount, - long encodedByteLength - ) { - if (!codec.isValid) - { - throw new ArgumentException("A valid codec identifier is required.", nameof(codec)); - } - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(channels); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); - ArgumentOutOfRangeException.ThrowIfNegative(frameCount); - ArgumentOutOfRangeException.ThrowIfNegative(encodedByteLength); - this.codec = codec; - this.channels = channels; - this.sampleRate = sampleRate; - this.frameCount = frameCount; - this.encodedByteLength = encodedByteLength; - } - - /// - /// Gets the codec protocol of the encoded artifact. - /// - public AudioCodecID codec { get; } - - /// - /// Gets the encoded channel count. - /// - public int channels { get; } - - /// - /// Gets the sample rate in frames per second. - /// - public int sampleRate { get; } - - /// - /// Gets the total decoded frame count. - /// - public long frameCount { get; } - - /// - /// Gets the encoded artifact length in bytes. - /// - public long encodedByteLength { get; } - - /// - /// Gets the clip duration derived from frame count and sample rate. - /// - public TimeSpan duration => TimeSpan.FromSeconds((double)frameCount / sampleRate); -} - -/// -/// Encodes the compact runtime header shared by audio importers and runtime asset loading. -/// -public static class AudioClipMetadataCodec -{ - private const uint C_MAGIC = 0x4455_4149; - private const int C_FIXED_SIZE = 32; - - /// - /// Encodes audio metadata into a compact deterministic runtime header. - /// - /// - /// Valid metadata to encode. - /// - /// - /// Newly allocated runtime header bytes. - /// - public static byte[] Encode(AudioClipMetadata metadata) - { - byte[] codec = Encoding.UTF8.GetBytes(metadata.codec.value); - if (codec.Length > byte.MaxValue) - { - throw new ArgumentException("The codec identifier is too long.", nameof(metadata)); - } - var output = new byte[C_FIXED_SIZE + codec.Length]; - BinaryPrimitives.WriteUInt32LittleEndian(output.AsSpan(0, 4), C_MAGIC); - output[4] = (byte)codec.Length; - BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(8, 4), metadata.channels); - BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(12, 4), metadata.sampleRate); - BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(16, 8), metadata.frameCount); - BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(24, 8), metadata.encodedByteLength); - codec.CopyTo(output.AsSpan(C_FIXED_SIZE)); - return output; - } - - /// - /// Decodes and validates one compact audio runtime header. - /// - /// - /// Complete runtime header bytes. - /// - /// - /// Valid imported audio metadata. - /// - /// - /// Thrown when the header is truncated, corrupt, or semantically invalid. - /// - public static AudioClipMetadata Decode(ReadOnlySpan payload) - { - if (payload.Length < C_FIXED_SIZE || BinaryPrimitives.ReadUInt32LittleEndian(payload) != C_MAGIC) - { - throw new InvalidOperationException("The audio runtime header is invalid."); - } - int codecLength = payload[4]; - if (payload.Length != C_FIXED_SIZE + codecLength || codecLength == 0) - { - throw new InvalidOperationException("The audio runtime header length is invalid."); - } - try - { - return new AudioClipMetadata( - new AudioCodecID(Encoding.UTF8.GetString(payload[C_FIXED_SIZE..])), - BinaryPrimitives.ReadInt32LittleEndian(payload[8..12]), - BinaryPrimitives.ReadInt32LittleEndian(payload[12..16]), - BinaryPrimitives.ReadInt64LittleEndian(payload[16..24]), - BinaryPrimitives.ReadInt64LittleEndian(payload[24..32]) - ); - } - catch (ArgumentException exception) - { - throw new InvalidOperationException("The audio runtime header contains invalid metadata.", exception); - } - } -} - /// /// Represents one imported audio source and its compact runtime metadata. /// diff --git a/src/services/audio/Inno.Audio/AudioClipHandle.cs b/src/services/audio/Inno.Audio/AudioClipHandle.cs new file mode 100644 index 000000000..12837a1c7 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioClipHandle.cs @@ -0,0 +1,27 @@ +namespace Inno.Audio; + +/// +/// Identifies one backend clip allocation within a device generation. +/// +public readonly record struct AudioClipHandle +{ + internal AudioClipHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + + /// + /// Gets the generation of the device that created this handle. + /// + public uint deviceGeneration { get; } + + /// + /// Gets whether the handle contains a non-zero backend identity and generation. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/audio/Inno.Audio/AudioClipLoadMode.cs b/src/services/audio/Inno.Audio/AudioClipLoadMode.cs new file mode 100644 index 000000000..67c146c3d --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioClipLoadMode.cs @@ -0,0 +1,20 @@ +namespace Inno.Audio; + +/// +/// Selects how encoded clip data is prepared for playback. +/// +public enum AudioClipLoadMode +{ + /// + /// Lets the runtime choose between decoded and streamed storage. + /// + Automatic, + /// + /// Decodes the complete clip before playback. + /// + Decode, + /// + /// Decodes encoded data incrementally while playback advances. + /// + Stream +} diff --git a/src/services/audio/Inno.Audio/AudioClipMetadata.cs b/src/services/audio/Inno.Audio/AudioClipMetadata.cs new file mode 100644 index 000000000..f2464ce52 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioClipMetadata.cs @@ -0,0 +1,79 @@ +using System; + +namespace Inno.Audio; + +/// +/// Describes imported encoded audio independently from its runtime storage path. +/// +public readonly record struct AudioClipMetadata +{ + /// + /// Creates imported audio metadata. + /// + /// + /// Codec protocol of the encoded artifact. + /// + /// + /// Encoded channel count. + /// + /// + /// Sample rate in frames per second. + /// + /// + /// Total decoded frame count. + /// + /// + /// Encoded artifact length in bytes. + /// + public AudioClipMetadata( + AudioCodecID codec, + int channels, + int sampleRate, + long frameCount, + long encodedByteLength + ) { + if (!codec.isValid) + { + throw new ArgumentException("A valid codec identifier is required.", nameof(codec)); + } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(channels); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); + ArgumentOutOfRangeException.ThrowIfNegative(frameCount); + ArgumentOutOfRangeException.ThrowIfNegative(encodedByteLength); + this.codec = codec; + this.channels = channels; + this.sampleRate = sampleRate; + this.frameCount = frameCount; + this.encodedByteLength = encodedByteLength; + } + + /// + /// Gets the codec protocol of the encoded artifact. + /// + public AudioCodecID codec { get; } + + /// + /// Gets the encoded channel count. + /// + public int channels { get; } + + /// + /// Gets the sample rate in frames per second. + /// + public int sampleRate { get; } + + /// + /// Gets the total decoded frame count. + /// + public long frameCount { get; } + + /// + /// Gets the encoded artifact length in bytes. + /// + public long encodedByteLength { get; } + + /// + /// Gets the clip duration derived from frame count and sample rate. + /// + public TimeSpan duration => TimeSpan.FromSeconds((double)frameCount / sampleRate); +} diff --git a/src/services/audio/Inno.Audio/AudioClipMetadataCodec.cs b/src/services/audio/Inno.Audio/AudioClipMetadataCodec.cs new file mode 100644 index 000000000..7e7dd17d3 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioClipMetadataCodec.cs @@ -0,0 +1,80 @@ +using System; +using System.Buffers.Binary; +using System.Text; + +namespace Inno.Audio; + +/// +/// Encodes the compact runtime header shared by audio importers and runtime asset loading. +/// +public static class AudioClipMetadataCodec +{ + private const uint C_MAGIC = 0x4455_4149; + private const int C_FIXED_SIZE = 32; + + /// + /// Encodes audio metadata into a compact deterministic runtime header. + /// + /// + /// Valid metadata to encode. + /// + /// + /// Newly allocated runtime header bytes. + /// + public static byte[] Encode(AudioClipMetadata metadata) + { + byte[] codec = Encoding.UTF8.GetBytes(metadata.codec.value); + if (codec.Length > byte.MaxValue) + { + throw new ArgumentException("The codec identifier is too long.", nameof(metadata)); + } + var output = new byte[C_FIXED_SIZE + codec.Length]; + BinaryPrimitives.WriteUInt32LittleEndian(output.AsSpan(0, 4), C_MAGIC); + output[4] = (byte)codec.Length; + BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(8, 4), metadata.channels); + BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(12, 4), metadata.sampleRate); + BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(16, 8), metadata.frameCount); + BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(24, 8), metadata.encodedByteLength); + codec.CopyTo(output.AsSpan(C_FIXED_SIZE)); + return output; + } + + /// + /// Decodes and validates one compact audio runtime header. + /// + /// + /// Complete runtime header bytes. + /// + /// + /// Valid imported audio metadata. + /// + /// + /// Thrown when the header is truncated, corrupt, or semantically invalid. + /// + public static AudioClipMetadata Decode(ReadOnlySpan payload) + { + if (payload.Length < C_FIXED_SIZE || BinaryPrimitives.ReadUInt32LittleEndian(payload) != C_MAGIC) + { + throw new InvalidOperationException("The audio runtime header is invalid."); + } + int codecLength = payload[4]; + if (payload.Length != C_FIXED_SIZE + codecLength || codecLength == 0) + { + throw new InvalidOperationException("The audio runtime header length is invalid."); + } + try + { + return new AudioClipMetadata( + new AudioCodecID(Encoding.UTF8.GetString(payload[C_FIXED_SIZE..])), + BinaryPrimitives.ReadInt32LittleEndian(payload[8..12]), + BinaryPrimitives.ReadInt32LittleEndian(payload[12..16]), + BinaryPrimitives.ReadInt64LittleEndian(payload[16..24]), + BinaryPrimitives.ReadInt64LittleEndian(payload[24..32]) + ); + } + catch (ArgumentException exception) + { + throw new InvalidOperationException("The audio runtime header contains invalid metadata.", exception); + } + } +} diff --git a/src/services/audio/Inno.Audio/AudioCodecID.cs b/src/services/audio/Inno.Audio/AudioCodecID.cs new file mode 100644 index 000000000..b44c11a76 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioCodecID.cs @@ -0,0 +1,54 @@ +using System; + +namespace Inno.Audio; + +/// +/// Identifies encoded audio data without constraining codec providers to a closed enum. +/// +public readonly record struct AudioCodecID +{ + /// + /// Creates an open codec identifier. + /// + /// + /// Globally stable codec protocol value. + /// + public AudioCodecID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the standard Waveform Audio codec identifier. + /// + public static AudioCodecID wav { get; } = new("audio/wav"); + + /// + /// Gets the standard Free Lossless Audio Codec identifier. + /// + public static AudioCodecID flac { get; } = new("audio/flac"); + + /// + /// Gets the standard MPEG Layer III codec identifier. + /// + public static AudioCodecID mp3 { get; } = new("audio/mpeg"); + + /// + /// Gets the globally stable protocol value. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats the identifier for diagnostics and persistence. + /// + /// + /// The stable protocol value. + /// + public override string ToString() => value; +} diff --git a/src/services/audio/Inno.Audio/AudioCompletionReason.cs b/src/services/audio/Inno.Audio/AudioCompletionReason.cs new file mode 100644 index 000000000..2c7fe4f25 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioCompletionReason.cs @@ -0,0 +1,28 @@ +namespace Inno.Audio; + +/// +/// Explains why a voice stopped accepting playback commands. +/// +public enum AudioCompletionReason +{ + /// + /// The clip reached its natural end. + /// + NaturalEnd, + /// + /// A caller explicitly stopped the voice. + /// + Stopped, + /// + /// The runtime reclaimed the voice to satisfy its voice budget. + /// + Stolen, + /// + /// Encoded data could not be prepared or decoded. + /// + DecodeFailed, + /// + /// Playback ended because the owning device generation was lost. + /// + DeviceLost +} diff --git a/src/services/audio/Inno.Audio/AudioContentProvider.cs b/src/services/audio/Inno.Audio/AudioContentProvider.cs index c2019909e..181dc8134 100644 --- a/src/services/audio/Inno.Audio/AudioContentProvider.cs +++ b/src/services/audio/Inno.Audio/AudioContentProvider.cs @@ -1,257 +1,8 @@ using System; -using System.Collections.Generic; using Inno.Core.Execution; -using Inno.References; namespace Inno.Audio; -/// -/// Marks a reloadable provider that converts host content into immutable audio snapshots. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AudioContentProviderExtensionAttribute : Attribute -{ - /// - /// Creates an audio content provider declaration. - /// - /// - /// Globally stable provider identifier. - /// - /// - /// Provider invocation priority; lower values run first. - /// - public AudioContentProviderExtensionAttribute( - string id, - int priority = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - this.priority = priority; - } - - /// - /// Gets the globally stable provider identifier. - /// - public string id { get; } - - /// - /// Gets the provider invocation priority. - /// - public int priority { get; } -} - -/// -/// Collects one bounded, atomic provider contribution on the owning control thread. -/// -/// -/// The host disposes this borrowed context when the provider returns. A rejected submission invalidates the -/// entire contribution, even if the provider catches the exception. The context does not own the content scope. -/// -public sealed class AudioContentProviderContext : IDisposable -{ - private readonly List m_emitters = []; - private readonly List m_listeners = []; - private readonly HashSet m_ids = []; - private readonly int m_ownerThread = Environment.CurrentManagedThreadId; - private ContentReadScope? m_content; - private bool m_rejected; - - /// - /// Opens a control-thread snapshot collector over one content read scope. - /// - /// - /// The caller-owned identity read scope. - /// - /// - /// Finite non-negative time elapsed since the previous update. - /// - /// - /// Maximum combined emitter and listener count accepted by this contribution. Zero permits an empty contribution only. - /// - /// - /// The elapsed time is invalid or capacity is negative. - /// - /// - /// The borrowed content scope is null. - /// - public AudioContentProviderContext( - ContentReadScope content, - float deltaTime, - int capacity = 1024 - ) { - ArgumentNullException.ThrowIfNull(content); - if (!float.IsFinite(deltaTime) || deltaTime < 0f) - { - throw new ArgumentOutOfRangeException(nameof(deltaTime)); - } - ArgumentOutOfRangeException.ThrowIfNegative(capacity); - m_content = content; - this.deltaTime = deltaTime; - this.capacity = capacity; - } - - /// - /// Gets explicit host content visible during this update. - /// - /// - /// This provider invocation has ended. - /// - /// - /// Access occurs off the owning control thread or a submission was rejected. - /// - public ContentReadScope content - { - get - { - EnsureActive(); - return m_content!; - } - } - - /// - /// Gets non-negative elapsed frame time in seconds. - /// - public float deltaTime { get; } - - /// - /// Gets the immutable combined snapshot budget assigned to this invocation. - /// - public int capacity { get; } - - /// - /// Gets a frozen copy of submitted source state in provider order. - /// - /// - /// This provider invocation has ended. - /// - /// - /// The contribution was rejected or access occurs off the owning control thread. - /// - public IReadOnlyList emitters - { - get - { - EnsureActive(); - return Array.AsReadOnly(m_emitters.ToArray()); - } - } - - /// - /// Gets a frozen copy of submitted listener state in provider order. - /// - /// - /// This provider invocation has ended. - /// - /// - /// The contribution was rejected or access occurs off the owning control thread. - /// - public IReadOnlyList listeners - { - get - { - EnsureActive(); - return Array.AsReadOnly(m_listeners.ToArray()); - } - } - - /// - /// Submits one immutable emitter snapshot for runtime synchronization. - /// - /// - /// Current state for one stable emitter identity. - /// - /// - /// The emitter is uninitialized or its identity duplicates a submission in this contribution. - /// - /// - /// The budget is exhausted, the contribution was rejected, or access occurs off the owner thread. - /// - /// - /// This provider invocation has ended. - /// - public void Submit(AudioEmitterSnapshot emitter) - { - EnsureActive(); - if (emitter.clip is null || !emitter.options.bus.isValid) - { - m_rejected = true; - throw new ArgumentException("An audio emitter requires an initialized clip and playback options.", nameof(emitter)); - } - Admit(emitter.id); - m_emitters.Add(emitter); - } - - /// - /// Submits one immutable listener snapshot for runtime selection. - /// - /// - /// Current state for one stable listener identity. - /// - /// - /// The listener is uninitialized or its identity duplicates a submission in this contribution. - /// - /// - /// The budget is exhausted, the contribution was rejected, or access occurs off the owner thread. - /// - /// - /// This provider invocation has ended. - /// - public void Submit(AudioListenerSnapshot listener) - { - EnsureActive(); - Admit(listener.id); - m_listeners.Add(listener); - } - - /// - /// Revokes submission and releases collected references without disposing the borrowed content scope. - /// - /// - /// Disposal occurs off the owning control thread. - /// - public void Dispose() - { - EnsureOwnerThread(); - m_content = null; - m_emitters.Clear(); - m_listeners.Clear(); - m_ids.Clear(); - } - - private void Admit(Guid id) - { - if (id == Guid.Empty || m_ids.Contains(id)) - { - m_rejected = true; - throw new ArgumentException($"Audio content identity '{id:D}' is empty or duplicated."); - } - if (m_ids.Count >= capacity) - { - m_rejected = true; - throw new InvalidOperationException("The audio content contribution exceeds its snapshot capacity."); - } - m_ids.Add(id); - } - - private void EnsureActive() - { - EnsureOwnerThread(); - ObjectDisposedException.ThrowIf(m_content is null, this); - if (m_rejected) - { - throw new InvalidOperationException("The audio content contribution contains a rejected submission."); - } - } - - private void EnsureOwnerThread() - { - if (Environment.CurrentManagedThreadId != m_ownerThread) - { - throw new InvalidOperationException("Audio content collection requires its owning control thread."); - } - } -} - /// /// Converts arbitrary host-owned content into backend-neutral emitter and listener snapshots. /// diff --git a/src/services/audio/Inno.Audio/AudioContentProviderContext.cs b/src/services/audio/Inno.Audio/AudioContentProviderContext.cs new file mode 100644 index 000000000..99e6c2464 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioContentProviderContext.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using Inno.References; + +namespace Inno.Audio; + +/// +/// Collects one bounded, atomic provider contribution on the owning control thread. +/// +/// +/// The host disposes this borrowed context when the provider returns. A rejected submission invalidates the +/// entire contribution, even if the provider catches the exception. The context does not own the content scope. +/// +public sealed class AudioContentProviderContext : IDisposable +{ + private readonly List m_emitters = []; + private readonly List m_listeners = []; + private readonly HashSet m_ids = []; + private readonly int m_ownerThread = Environment.CurrentManagedThreadId; + private ContentReadScope? m_content; + private bool m_rejected; + + /// + /// Opens a control-thread snapshot collector over one content read scope. + /// + /// + /// The caller-owned identity read scope. + /// + /// + /// Finite non-negative time elapsed since the previous update. + /// + /// + /// Maximum combined emitter and listener count accepted by this contribution. Zero permits an empty contribution only. + /// + /// + /// The elapsed time is invalid or capacity is negative. + /// + /// + /// The borrowed content scope is null. + /// + public AudioContentProviderContext( + ContentReadScope content, + float deltaTime, + int capacity = 1024 + ) { + ArgumentNullException.ThrowIfNull(content); + if (!float.IsFinite(deltaTime) || deltaTime < 0f) + { + throw new ArgumentOutOfRangeException(nameof(deltaTime)); + } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); + m_content = content; + this.deltaTime = deltaTime; + this.capacity = capacity; + } + + /// + /// Gets explicit host content visible during this update. + /// + /// + /// This provider invocation has ended. + /// + /// + /// Access occurs off the owning control thread or a submission was rejected. + /// + public ContentReadScope content + { + get + { + EnsureActive(); + return m_content!; + } + } + + /// + /// Gets non-negative elapsed frame time in seconds. + /// + public float deltaTime { get; } + + /// + /// Gets the immutable combined snapshot budget assigned to this invocation. + /// + public int capacity { get; } + + /// + /// Gets a frozen copy of submitted source state in provider order. + /// + /// + /// This provider invocation has ended. + /// + /// + /// The contribution was rejected or access occurs off the owning control thread. + /// + public IReadOnlyList emitters + { + get + { + EnsureActive(); + return Array.AsReadOnly(m_emitters.ToArray()); + } + } + + /// + /// Gets a frozen copy of submitted listener state in provider order. + /// + /// + /// This provider invocation has ended. + /// + /// + /// The contribution was rejected or access occurs off the owning control thread. + /// + public IReadOnlyList listeners + { + get + { + EnsureActive(); + return Array.AsReadOnly(m_listeners.ToArray()); + } + } + + /// + /// Submits one immutable emitter snapshot for runtime synchronization. + /// + /// + /// Current state for one stable emitter identity. + /// + /// + /// The emitter is uninitialized or its identity duplicates a submission in this contribution. + /// + /// + /// The budget is exhausted, the contribution was rejected, or access occurs off the owner thread. + /// + /// + /// This provider invocation has ended. + /// + public void Submit(AudioEmitterSnapshot emitter) + { + EnsureActive(); + if (emitter.clip is null || !emitter.options.bus.isValid) + { + m_rejected = true; + throw new ArgumentException("An audio emitter requires an initialized clip and playback options.", nameof(emitter)); + } + Admit(emitter.id); + m_emitters.Add(emitter); + } + + /// + /// Submits one immutable listener snapshot for runtime selection. + /// + /// + /// Current state for one stable listener identity. + /// + /// + /// The listener is uninitialized or its identity duplicates a submission in this contribution. + /// + /// + /// The budget is exhausted, the contribution was rejected, or access occurs off the owner thread. + /// + /// + /// This provider invocation has ended. + /// + public void Submit(AudioListenerSnapshot listener) + { + EnsureActive(); + Admit(listener.id); + m_listeners.Add(listener); + } + + /// + /// Revokes submission and releases collected references without disposing the borrowed content scope. + /// + /// + /// Disposal occurs off the owning control thread. + /// + public void Dispose() + { + EnsureOwnerThread(); + m_content = null; + m_emitters.Clear(); + m_listeners.Clear(); + m_ids.Clear(); + } + + private void Admit(Guid id) + { + if (id == Guid.Empty || m_ids.Contains(id)) + { + m_rejected = true; + throw new ArgumentException($"Audio content identity '{id:D}' is empty or duplicated."); + } + if (m_ids.Count >= capacity) + { + m_rejected = true; + throw new InvalidOperationException("The audio content contribution exceeds its snapshot capacity."); + } + m_ids.Add(id); + } + + private void EnsureActive() + { + EnsureOwnerThread(); + ObjectDisposedException.ThrowIf(m_content is null, this); + if (m_rejected) + { + throw new InvalidOperationException("The audio content contribution contains a rejected submission."); + } + } + + private void EnsureOwnerThread() + { + if (Environment.CurrentManagedThreadId != m_ownerThread) + { + throw new InvalidOperationException("Audio content collection requires its owning control thread."); + } + } +} diff --git a/src/services/audio/Inno.Audio/AudioContentProviderExtensionAttribute.cs b/src/services/audio/Inno.Audio/AudioContentProviderExtensionAttribute.cs new file mode 100644 index 000000000..ac7b1be50 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioContentProviderExtensionAttribute.cs @@ -0,0 +1,38 @@ +using System; + +namespace Inno.Audio; + +/// +/// Marks a reloadable provider that converts host content into immutable audio snapshots. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AudioContentProviderExtensionAttribute : Attribute +{ + /// + /// Creates an audio content provider declaration. + /// + /// + /// Globally stable provider identifier. + /// + /// + /// Provider invocation priority; lower values run first. + /// + public AudioContentProviderExtensionAttribute( + string id, + int priority = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + this.priority = priority; + } + + /// + /// Gets the globally stable provider identifier. + /// + public string id { get; } + + /// + /// Gets the provider invocation priority. + /// + public int priority { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioDeviceCompletion.cs b/src/services/audio/Inno.Audio/AudioDeviceCompletion.cs new file mode 100644 index 000000000..ba05cfcbb --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioDeviceCompletion.cs @@ -0,0 +1,40 @@ +using System; + +namespace Inno.Audio; + +/// +/// Reports one backend-detected terminal voice transition. +/// +public readonly record struct AudioDeviceCompletion +{ + /// + /// Creates a backend voice completion record. + /// + /// + /// Voice that reached a terminal state. + /// + /// + /// Reason playback ended. + /// + public AudioDeviceCompletion( + AudioDeviceVoiceHandle voice, + AudioCompletionReason reason + ) { + if (!voice.isValid) + { + throw new ArgumentException("A valid voice handle is required.", nameof(voice)); + } + this.voice = voice; + this.reason = reason; + } + + /// + /// Gets the completed voice handle. + /// + public AudioDeviceVoiceHandle voice { get; } + + /// + /// Gets the terminal playback reason. + /// + public AudioCompletionReason reason { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioDeviceState.cs b/src/services/audio/Inno.Audio/AudioDeviceState.cs new file mode 100644 index 000000000..18052e5ba --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioDeviceState.cs @@ -0,0 +1,28 @@ +namespace Inno.Audio; + +/// +/// Describes the availability of the active audio output generation. +/// +public enum AudioDeviceState +{ + /// + /// The device has not completed initialization. + /// + Initializing, + /// + /// The device is available for audible playback. + /// + Ready, + /// + /// Playback is advancing without an output device. + /// + Muted, + /// + /// The active output device was lost and recovery is pending. + /// + Lost, + /// + /// The device has been released and cannot accept work. + /// + Disposed +} diff --git a/src/services/audio/Inno.Audio/AudioDistanceModel.cs b/src/services/audio/Inno.Audio/AudioDistanceModel.cs new file mode 100644 index 000000000..5a81cb270 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioDistanceModel.cs @@ -0,0 +1,24 @@ +namespace Inno.Audio; + +/// +/// Selects the distance attenuation model for one spatial voice. +/// +public enum AudioDistanceModel +{ + /// + /// Disables distance attenuation while retaining spatial direction. + /// + None, + /// + /// Uses inverse-distance attenuation. + /// + Inverse, + /// + /// Uses linear-distance attenuation. + /// + Linear, + /// + /// Uses exponential-distance attenuation. + /// + Exponential +} diff --git a/src/services/audio/Inno.Audio/AudioContent.cs b/src/services/audio/Inno.Audio/AudioEmitterSnapshot.cs similarity index 58% rename from src/services/audio/Inno.Audio/AudioContent.cs rename to src/services/audio/Inno.Audio/AudioEmitterSnapshot.cs index e151a818c..9219f23f8 100644 --- a/src/services/audio/Inno.Audio/AudioContent.cs +++ b/src/services/audio/Inno.Audio/AudioEmitterSnapshot.cs @@ -69,60 +69,3 @@ public AudioEmitterSnapshot( /// public ulong playbackRevision { get; } } - -/// -/// Describes one immutable listener candidate produced by a content provider. -/// -public readonly record struct AudioListenerSnapshot -{ - /// - /// Creates an immutable listener snapshot. - /// - /// - /// Stable listener identity across updates. - /// - /// - /// Selection priority; larger values win. - /// - /// - /// Current listener transform. - /// - /// - /// Whether the listener is eligible for selection. - /// - public AudioListenerSnapshot( - Guid id, - int priority, - AudioListenerState state, - bool active - ) { - if (id == Guid.Empty) - { - throw new ArgumentException("A listener identity cannot be empty.", nameof(id)); - } - this.id = id; - this.priority = priority; - this.state = state; - this.active = active; - } - - /// - /// Gets the stable listener identity. - /// - public Guid id { get; } - - /// - /// Gets the selection priority. - /// - public int priority { get; } - - /// - /// Gets the current listener transform. - /// - public AudioListenerState state { get; } - - /// - /// Gets whether the listener is eligible for selection. - /// - public bool active { get; } -} diff --git a/src/services/audio/Inno.Audio/AudioExecutionContext.cs b/src/services/audio/Inno.Audio/AudioExecutionContext.cs new file mode 100644 index 000000000..571a84b10 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioExecutionContext.cs @@ -0,0 +1,38 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Audio; + +/// +/// Binds one host-owned audio service to the current asynchronous execution context. +/// +public static class AudioExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("audio"); + + /// + /// Gets the audio service bound to the current asynchronous execution context. + /// + /// + /// Thrown when no audio service is active for the caller. + /// + public static IAudioService current => CURRENT_SCOPE.current; + + /// + /// Binds an audio service until the returned strict last-in-first-out scope is disposed. + /// + /// + /// Host-owned audio service exposed to script-facing operations. + /// + /// + /// A strict last-in-first-out scope owned by the caller. + /// + /// + /// Thrown when is . + /// + public static IDisposable EnterScope(IAudioService audio) + { + ArgumentNullException.ThrowIfNull(audio); + return CURRENT_SCOPE.Enter(audio); + } +} diff --git a/src/services/audio/Inno.Audio/AudioHandles.cs b/src/services/audio/Inno.Audio/AudioHandles.cs deleted file mode 100644 index e16b4820b..000000000 --- a/src/services/audio/Inno.Audio/AudioHandles.cs +++ /dev/null @@ -1,105 +0,0 @@ -namespace Inno.Audio; - -/// -/// Identifies one backend clip allocation within a device generation. -/// -public readonly record struct AudioClipHandle -{ - internal AudioClipHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - - /// - /// Gets the generation of the device that created this handle. - /// - public uint deviceGeneration { get; } - - /// - /// Gets whether the handle contains a non-zero backend identity and generation. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Identifies one playback voice within a device generation. -/// -public readonly record struct AudioVoiceHandle -{ - internal AudioVoiceHandle( - ulong value, - uint ownerGeneration - ) { - this.value = value; - this.ownerGeneration = ownerGeneration; - } - - internal ulong value { get; } - - /// - /// Gets the generation of the device that created this handle. - /// - public uint ownerGeneration { get; } - - /// - /// Gets whether the handle contains a non-zero backend identity and generation. - /// - public bool isValid => value != 0 && ownerGeneration != 0; -} - -/// -/// Identifies one backend mixer bus within a device generation. -/// -public readonly record struct AudioBusHandle -{ - internal AudioBusHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - - /// - /// Gets the generation of the device that created this handle. - /// - public uint deviceGeneration { get; } - - /// - /// Gets whether the handle contains a non-zero backend identity and generation. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Identifies one spatial listener within a device generation. -/// -public readonly record struct AudioListenerHandle -{ - internal AudioListenerHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - - /// - /// Gets the generation of the device that created this handle. - /// - public uint deviceGeneration { get; } - - /// - /// Gets whether the handle contains a non-zero backend identity and generation. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} diff --git a/src/services/audio/Inno.Audio/AudioListenerHandle.cs b/src/services/audio/Inno.Audio/AudioListenerHandle.cs new file mode 100644 index 000000000..349d7744e --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioListenerHandle.cs @@ -0,0 +1,27 @@ +namespace Inno.Audio; + +/// +/// Identifies one spatial listener within a device generation. +/// +public readonly record struct AudioListenerHandle +{ + internal AudioListenerHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + + /// + /// Gets the generation of the device that created this handle. + /// + public uint deviceGeneration { get; } + + /// + /// Gets whether the handle contains a non-zero backend identity and generation. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/audio/Inno.Audio/AudioListenerSnapshot.cs b/src/services/audio/Inno.Audio/AudioListenerSnapshot.cs new file mode 100644 index 000000000..7fd6c540a --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioListenerSnapshot.cs @@ -0,0 +1,60 @@ +using System; + +namespace Inno.Audio; + +/// +/// Describes one immutable listener candidate produced by a content provider. +/// +public readonly record struct AudioListenerSnapshot +{ + /// + /// Creates an immutable listener snapshot. + /// + /// + /// Stable listener identity across updates. + /// + /// + /// Selection priority; larger values win. + /// + /// + /// Current listener transform. + /// + /// + /// Whether the listener is eligible for selection. + /// + public AudioListenerSnapshot( + Guid id, + int priority, + AudioListenerState state, + bool active + ) { + if (id == Guid.Empty) + { + throw new ArgumentException("A listener identity cannot be empty.", nameof(id)); + } + this.id = id; + this.priority = priority; + this.state = state; + this.active = active; + } + + /// + /// Gets the stable listener identity. + /// + public Guid id { get; } + + /// + /// Gets the selection priority. + /// + public int priority { get; } + + /// + /// Gets the current listener transform. + /// + public AudioListenerState state { get; } + + /// + /// Gets whether the listener is eligible for selection. + /// + public bool active { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioListenerState.cs b/src/services/audio/Inno.Audio/AudioListenerState.cs new file mode 100644 index 000000000..029e78e0c --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioListenerState.cs @@ -0,0 +1,64 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Audio; + +/// +/// Contains one listener transform used by backend spatialization. +/// +public readonly record struct AudioListenerState +{ + /// + /// Creates a listener transform snapshot. + /// + /// + /// World-space listener position. + /// + /// + /// World-space listener forward direction. + /// + /// + /// World-space listener up direction. + /// + /// + /// World-space listener velocity. + /// + /// + /// Any position, direction, up, or velocity component is non-finite. + /// + public AudioListenerState( + Vector3 position, + Vector3 direction, + Vector3 up, + Vector3 velocity + ) { + AudioValueValidation.RequireFinite(position, nameof(position)); + AudioValueValidation.RequireFinite(direction, nameof(direction)); + AudioValueValidation.RequireFinite(up, nameof(up)); + AudioValueValidation.RequireFinite(velocity, nameof(velocity)); + this.position = position; + this.direction = direction; + this.up = up; + this.velocity = velocity; + } + + /// + /// Gets the world-space listener position. + /// + public Vector3 position { get; } + + /// + /// Gets the world-space listener forward direction. + /// + public Vector3 direction { get; } + + /// + /// Gets the world-space listener up direction. + /// + public Vector3 up { get; } + + /// + /// Gets the world-space listener velocity. + /// + public Vector3 velocity { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioMixer.cs b/src/services/audio/Inno.Audio/AudioMixer.cs index 47660a592..50051dd59 100644 --- a/src/services/audio/Inno.Audio/AudioMixer.cs +++ b/src/services/audio/Inno.Audio/AudioMixer.cs @@ -1,173 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Assets; -using Inno.Core.Serialization; -using Inno.Extensibility.Types; namespace Inno.Audio; -/// -/// Stores one neutral numeric parameter assigned to an audio processor. -/// -public readonly record struct AudioProcessorParameter -{ - /// - /// Creates a processor parameter value. - /// - /// - /// Open parameter identifier understood by the processor protocol. - /// - /// - /// Neutral numeric value interpreted by the processor. - /// - public AudioProcessorParameter( - AudioParameterID id, - float value - ) { - if (!id.isValid) - { - throw new ArgumentException("A valid parameter identifier is required.", nameof(id)); - } - this.id = id; - this.value = value; - } - - /// - /// Gets the open parameter identifier. - /// - public AudioParameterID id { get; } - - /// - /// Gets the neutral numeric value. - /// - public float value { get; } -} - -/// -/// Describes one ordered processor instance attached to a mixer bus. -/// -public sealed class AudioProcessorConfiguration -{ - private readonly AudioProcessorParameter[] m_parameters; - - /// - /// Creates an immutable processor configuration. - /// - /// - /// Open processor protocol identifier. - /// - /// - /// Complete processor parameter set. - /// - public AudioProcessorConfiguration( - AudioProcessorID id, - IEnumerable? parameters = null - ) { - if (!id.isValid) - { - throw new ArgumentException("A valid processor identifier is required.", nameof(id)); - } - this.id = id; - m_parameters = parameters?.ToArray() ?? []; - if (m_parameters.Select(static parameter => parameter.id).Distinct().Count() != m_parameters.Length) - { - throw new ArgumentException("Processor parameter identifiers must be unique.", nameof(parameters)); - } - } - - /// - /// Gets the open processor protocol identifier. - /// - public AudioProcessorID id { get; } - - /// - /// Gets the immutable processor parameter set. - /// - public IReadOnlyList parameters => Array.AsReadOnly(m_parameters); -} - -/// -/// Describes one bus and its ordered processor chain in a compiled mixer graph. -/// -public sealed class AudioBusDefinition -{ - private readonly AudioProcessorConfiguration[] m_processors; - - /// - /// Creates an immutable mixer bus definition. - /// - /// - /// Stable bus identifier. - /// - /// - /// Parent bus identifier, or only for the master bus. - /// - /// - /// Non-negative linear bus gain. - /// - /// - /// Whether output from the bus is initially silenced. - /// - /// - /// Ordered processor chain. - /// - public AudioBusDefinition( - AudioBusID id, - AudioBusID? parent, - float volume, - bool muted, - IEnumerable? processors = null - ) { - if (!id.isValid) - { - throw new ArgumentException("A valid bus identifier is required.", nameof(id)); - } - if (volume < 0f) - { - throw new ArgumentOutOfRangeException(nameof(volume)); - } - if (id == AudioBusID.master && parent is not null) - { - throw new ArgumentException("The master bus cannot have a parent.", nameof(parent)); - } - if (id != AudioBusID.master && (parent is null || !parent.Value.isValid)) - { - throw new ArgumentException("A non-master bus requires a valid parent.", nameof(parent)); - } - this.id = id; - this.parent = parent; - this.volume = volume; - this.muted = muted; - m_processors = processors?.ToArray() ?? []; - } - - /// - /// Gets the stable bus identifier. - /// - public AudioBusID id { get; } - - /// - /// Gets the parent bus, or for the master bus. - /// - public AudioBusID? parent { get; } - - /// - /// Gets the initial linear bus gain. - /// - public float volume { get; } - - /// - /// Gets whether output from the bus is initially silenced. - /// - public bool muted { get; } - - /// - /// Gets the ordered immutable processor chain. - /// - public IReadOnlyList processors => Array.AsReadOnly(m_processors); -} - /// /// Contains one validated backend-neutral mixer graph. /// @@ -185,256 +21,3 @@ internal AudioMixer(IEnumerable buses) /// public IReadOnlyList buses => Array.AsReadOnly(m_buses); } - -/// -/// Builds and validates an open backend-neutral mixer graph. -/// -public sealed class AudioMixerBuilder -{ - private readonly Dictionary m_buses = new() - { - [AudioBusID.master] = new(AudioBusID.master, null, 1f, false) - }; - - /// - /// Adds one semantic bus to the graph. - /// - /// - /// Stable bus identifier. - /// - /// - /// Parent bus identifier. - /// - /// - /// Initial non-negative linear gain. - /// - /// - /// Whether output is initially silenced. - /// - /// - /// Thrown when the bus identifier is invalid or duplicated. - /// - public void AddBus( - AudioBusID id, - AudioBusID parent, - float volume = 1f, - bool muted = false - ) { - if (!id.isValid || id == AudioBusID.master) - { - throw new ArgumentException("A valid non-master bus identifier is required.", nameof(id)); - } - if (m_buses.ContainsKey(id)) - { - throw new ArgumentException($"Audio bus '{id}' is already defined.", nameof(id)); - } - m_buses.Add(id, new AudioBusDefinition(id, parent, volume, muted)); - } - - /// - /// Appends one processor to an existing bus chain. - /// - /// - /// Existing bus identifier. - /// - /// - /// Immutable processor configuration to append. - /// - /// - /// Thrown when the bus is not defined. - /// - public void AddProcessor( - AudioBusID bus, - AudioProcessorConfiguration processor - ) { - ArgumentNullException.ThrowIfNull(processor); - if (!m_buses.TryGetValue(bus, out AudioBusDefinition? definition)) - { - throw new KeyNotFoundException($"Audio bus '{bus}' is not defined."); - } - m_buses[bus] = new AudioBusDefinition( - definition.id, - definition.parent, - definition.volume, - definition.muted, - definition.processors.Append(processor) - ); - } - - /// - /// Validates the graph and returns an immutable parent-before-child snapshot. - /// - /// - /// A validated mixer graph containing the mandatory master bus. - /// - /// - /// Thrown when a parent is missing or bus routing contains a cycle. - /// - public AudioMixer Build() - { - var order = new List(m_buses.Count); - var visiting = new HashSet(); - var visited = new HashSet(); - Visit(AudioBusID.master, order, visiting, visited); - foreach (AudioBusID id in m_buses.Keys.OrderBy(static id => id.value, StringComparer.Ordinal)) - { - Visit(id, order, visiting, visited); - } - return new AudioMixer(order); - } - - private void Visit( - AudioBusID id, - ICollection order, - ISet visiting, - ISet visited - ) { - if (visited.Contains(id)) - { - return; - } - if (!m_buses.TryGetValue(id, out AudioBusDefinition? definition)) - { - throw new InvalidOperationException($"Audio mixer references missing bus '{id}'."); - } - if (!visiting.Add(id)) - { - throw new InvalidOperationException($"Audio mixer bus routing contains a cycle at '{id}'."); - } - if (definition.parent is AudioBusID parent) - { - Visit(parent, order, visiting, visited); - } - visiting.Remove(id); - visited.Add(id); - order.Add(definition); - } -} - -/// -/// Stores reload-safe configuration for one mixer or feature extension generation. -/// -public struct SerializedAudioExtensionState -{ - /// - /// Creates empty extension state for deserialization. - /// - public SerializedAudioExtensionState() - { - this.propertyData = []; - } - - /// - /// Creates neutral extension state. - /// - /// - /// Stable settings type identity, or empty when no typed settings exist. - /// - /// - /// Neutral serialized property bytes. - /// - public SerializedAudioExtensionState( - Guid stableTypeID, - ReadOnlySpan propertyData - ) { - this.stableTypeId = stableTypeID; - this.propertyData = propertyData.ToArray(); - } - - /// - /// Gets or sets the stable settings type identity. - /// - [SerializableProperty] - public Guid stableTypeId { get; set; } - - /// - /// Gets or sets neutral serialized property bytes. - /// - [SerializableProperty] - public byte[] propertyData { get; set; } -} - -/// -/// Stores one ordered mixer feature selection using only stable data. -/// -public struct AudioMixerFeatureConfiguration -{ - /// - /// Creates an empty feature configuration for deserialization. - /// - public AudioMixerFeatureConfiguration() {} - - /// - /// Creates a mixer feature configuration. - /// - /// - /// Globally stable feature extension identifier. - /// - /// - /// Optional reload-safe feature state. - /// - /// - /// Whether the feature participates in graph construction. - /// - public AudioMixerFeatureConfiguration( - string featureTypeID, - SerializedAudioExtensionState? state = null, - bool enabled = true - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(featureTypeID); - this.featureTypeId = featureTypeID; - this.state = state ?? new SerializedAudioExtensionState(); - this.enabled = enabled; - } - - /// - /// Gets or sets the stable feature extension identifier. - /// - [SerializableProperty] - public string featureTypeId { get; set; } = string.Empty; - - /// - /// Gets or sets reload-safe feature settings. - /// - [SerializableProperty] - public SerializedAudioExtensionState state { get; set; } - - /// - /// Gets or sets whether the feature participates in graph construction. - /// - [SerializableProperty] - public bool enabled { get; set; } = true; -} - -/// -/// Selects a mixer extension and ordered features without defining a game-specific mixing model. -/// -[StableTypeID("6e167326-d078-45e9-ad33-993300ee5fed")] -public sealed class AudioMixerAsset : AssetObject -{ - /// - /// Gets or sets the globally stable mixer extension identifier. - /// - [SerializableProperty] - public string mixerTypeId { get; set; } = string.Empty; - - /// - /// Gets or sets reload-safe mixer settings. - /// - [SerializableProperty] - public SerializedAudioExtensionState mixerState { get; set; } = new(); - - /// - /// Gets or sets ordered feature configurations. - /// - [SerializableProperty] - public AudioMixerFeatureConfiguration[] features - { - get; - set - { - ArgumentNullException.ThrowIfNull(value); - field = value.ToArray(); - } - } = []; -} diff --git a/src/services/audio/Inno.Audio/AudioMixerAsset.cs b/src/services/audio/Inno.Audio/AudioMixerAsset.cs new file mode 100644 index 000000000..7af6acbc9 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerAsset.cs @@ -0,0 +1,40 @@ +using System; +using System.Linq; +using Inno.Assets; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Audio; + +/// +/// Selects a mixer extension and ordered features without defining a game-specific mixing model. +/// +[StableTypeID("6e167326-d078-45e9-ad33-993300ee5fed")] +public sealed class AudioMixerAsset : AssetObject +{ + /// + /// Gets or sets the globally stable mixer extension identifier. + /// + [SerializableProperty] + public string mixerTypeId { get; set; } = string.Empty; + + /// + /// Gets or sets reload-safe mixer settings. + /// + [SerializableProperty] + public SerializedAudioExtensionState mixerState { get; set; } = new(); + + /// + /// Gets or sets ordered feature configurations. + /// + [SerializableProperty] + public AudioMixerFeatureConfiguration[] features + { + get; + set + { + ArgumentNullException.ThrowIfNull(value); + field = value.ToArray(); + } + } = []; +} diff --git a/src/services/audio/Inno.Audio/AudioMixerBuilder.cs b/src/services/audio/Inno.Audio/AudioMixerBuilder.cs new file mode 100644 index 000000000..5fb76328d --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerBuilder.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Audio; + +/// +/// Builds and validates an open backend-neutral mixer graph. +/// +public sealed class AudioMixerBuilder +{ + private readonly Dictionary m_buses = new() + { + [AudioBusID.master] = new(AudioBusID.master, null, 1f, false) + }; + + /// + /// Adds one semantic bus to the graph. + /// + /// + /// Stable bus identifier. + /// + /// + /// Parent bus identifier. + /// + /// + /// Initial non-negative linear gain. + /// + /// + /// Whether output is initially silenced. + /// + /// + /// Thrown when the bus identifier is invalid or duplicated. + /// + public void AddBus( + AudioBusID id, + AudioBusID parent, + float volume = 1f, + bool muted = false + ) { + if (!id.isValid || id == AudioBusID.master) + { + throw new ArgumentException("A valid non-master bus identifier is required.", nameof(id)); + } + if (m_buses.ContainsKey(id)) + { + throw new ArgumentException($"Audio bus '{id}' is already defined.", nameof(id)); + } + m_buses.Add(id, new AudioBusDefinition(id, parent, volume, muted)); + } + + /// + /// Appends one processor to an existing bus chain. + /// + /// + /// Existing bus identifier. + /// + /// + /// Immutable processor configuration to append. + /// + /// + /// Thrown when the bus is not defined. + /// + public void AddProcessor( + AudioBusID bus, + AudioProcessorConfiguration processor + ) { + ArgumentNullException.ThrowIfNull(processor); + if (!m_buses.TryGetValue(bus, out AudioBusDefinition? definition)) + { + throw new KeyNotFoundException($"Audio bus '{bus}' is not defined."); + } + m_buses[bus] = new AudioBusDefinition( + definition.id, + definition.parent, + definition.volume, + definition.muted, + definition.processors.Append(processor) + ); + } + + /// + /// Validates the graph and returns an immutable parent-before-child snapshot. + /// + /// + /// A validated mixer graph containing the mandatory master bus. + /// + /// + /// Thrown when a parent is missing or bus routing contains a cycle. + /// + public AudioMixer Build() + { + var order = new List(m_buses.Count); + var visiting = new HashSet(); + var visited = new HashSet(); + Visit(AudioBusID.master, order, visiting, visited); + foreach (AudioBusID id in m_buses.Keys.OrderBy(static id => id.value, StringComparer.Ordinal)) + { + Visit(id, order, visiting, visited); + } + return new AudioMixer(order); + } + + private void Visit( + AudioBusID id, + ICollection order, + ISet visiting, + ISet visited + ) { + if (visited.Contains(id)) + { + return; + } + if (!m_buses.TryGetValue(id, out AudioBusDefinition? definition)) + { + throw new InvalidOperationException($"Audio mixer references missing bus '{id}'."); + } + if (!visiting.Add(id)) + { + throw new InvalidOperationException($"Audio mixer bus routing contains a cycle at '{id}'."); + } + if (definition.parent is AudioBusID parent) + { + Visit(parent, order, visiting, visited); + } + visiting.Remove(id); + visited.Add(id); + order.Add(definition); + } +} diff --git a/src/services/audio/Inno.Audio/AudioMixerExtension.cs b/src/services/audio/Inno.Audio/AudioMixerExtension.cs new file mode 100644 index 000000000..f99ac3c60 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerExtension.cs @@ -0,0 +1,21 @@ +namespace Inno.Audio; + +/// +/// Builds a base mixer graph on the host control thread. +/// +public abstract class AudioMixerExtension +{ + /// + /// Adds base buses and processors to a candidate mixer graph. + /// + /// + /// Candidate graph builder valid only for this invocation. + /// + /// + /// Reload-safe neutral extension state. + /// + public abstract void Build( + AudioMixerBuilder builder, + SerializedAudioExtensionState state + ); +} diff --git a/src/services/audio/Inno.Audio/AudioMixerExtensionAttribute.cs b/src/services/audio/Inno.Audio/AudioMixerExtensionAttribute.cs new file mode 100644 index 000000000..09a153afb --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerExtensionAttribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace Inno.Audio; + +/// +/// Marks a reloadable extension that creates the base audio mixer graph. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AudioMixerExtensionAttribute : Attribute +{ + /// + /// Creates a mixer extension declaration. + /// + /// + /// Globally stable mixer extension identifier. + /// + public AudioMixerExtensionAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + } + + /// + /// Gets the globally stable mixer extension identifier. + /// + public string id { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioMixerExtensions.cs b/src/services/audio/Inno.Audio/AudioMixerExtensions.cs deleted file mode 100644 index fc4168032..000000000 --- a/src/services/audio/Inno.Audio/AudioMixerExtensions.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; - -namespace Inno.Audio; - -/// -/// Marks a reloadable extension that creates the base audio mixer graph. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AudioMixerExtensionAttribute : Attribute -{ - /// - /// Creates a mixer extension declaration. - /// - /// - /// Globally stable mixer extension identifier. - /// - public AudioMixerExtensionAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - } - - /// - /// Gets the globally stable mixer extension identifier. - /// - public string id { get; } -} - -/// -/// Marks a reloadable extension that contributes to an audio mixer graph. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class AudioMixerFeatureExtensionAttribute : Attribute -{ - /// - /// Creates a mixer feature declaration. - /// - /// - /// Globally stable feature extension identifier. - /// - /// - /// Feature invocation priority; lower values build first. - /// - public AudioMixerFeatureExtensionAttribute( - string id, - int priority = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - this.priority = priority; - } - - /// - /// Gets the globally stable feature extension identifier. - /// - public string id { get; } - - /// - /// Gets the feature invocation priority. - /// - public int priority { get; } -} - -/// -/// Builds a base mixer graph on the host control thread. -/// -public abstract class AudioMixerExtension -{ - /// - /// Adds base buses and processors to a candidate mixer graph. - /// - /// - /// Candidate graph builder valid only for this invocation. - /// - /// - /// Reload-safe neutral extension state. - /// - public abstract void Build( - AudioMixerBuilder builder, - SerializedAudioExtensionState state - ); -} - -/// -/// Contributes optional buses and processors to a candidate mixer graph. -/// -public abstract class AudioMixerFeature -{ - /// - /// Adds feature-owned graph declarations on the host control thread. - /// - /// - /// Candidate graph builder valid only for this invocation. - /// - /// - /// Reload-safe neutral feature state. - /// - public abstract void Build( - AudioMixerBuilder builder, - SerializedAudioExtensionState state - ); -} diff --git a/src/services/audio/Inno.Audio/AudioMixerFeature.cs b/src/services/audio/Inno.Audio/AudioMixerFeature.cs new file mode 100644 index 000000000..3c1ad0edb --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerFeature.cs @@ -0,0 +1,21 @@ +namespace Inno.Audio; + +/// +/// Contributes optional buses and processors to a candidate mixer graph. +/// +public abstract class AudioMixerFeature +{ + /// + /// Adds feature-owned graph declarations on the host control thread. + /// + /// + /// Candidate graph builder valid only for this invocation. + /// + /// + /// Reload-safe neutral feature state. + /// + public abstract void Build( + AudioMixerBuilder builder, + SerializedAudioExtensionState state + ); +} diff --git a/src/services/audio/Inno.Audio/AudioMixerFeatureConfiguration.cs b/src/services/audio/Inno.Audio/AudioMixerFeatureConfiguration.cs new file mode 100644 index 000000000..69f80c1bf --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerFeatureConfiguration.cs @@ -0,0 +1,56 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Audio; + +/// +/// Stores one ordered mixer feature selection using only stable data. +/// +public struct AudioMixerFeatureConfiguration +{ + /// + /// Creates an empty feature configuration for deserialization. + /// + public AudioMixerFeatureConfiguration() {} + + /// + /// Creates a mixer feature configuration. + /// + /// + /// Globally stable feature extension identifier. + /// + /// + /// Optional reload-safe feature state. + /// + /// + /// Whether the feature participates in graph construction. + /// + public AudioMixerFeatureConfiguration( + string featureTypeID, + SerializedAudioExtensionState? state = null, + bool enabled = true + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(featureTypeID); + this.featureTypeId = featureTypeID; + this.state = state ?? new SerializedAudioExtensionState(); + this.enabled = enabled; + } + + /// + /// Gets or sets the stable feature extension identifier. + /// + [SerializableProperty] + public string featureTypeId { get; set; } = string.Empty; + + /// + /// Gets or sets reload-safe feature settings. + /// + [SerializableProperty] + public SerializedAudioExtensionState state { get; set; } + + /// + /// Gets or sets whether the feature participates in graph construction. + /// + [SerializableProperty] + public bool enabled { get; set; } = true; +} diff --git a/src/services/audio/Inno.Audio/AudioMixerFeatureExtensionAttribute.cs b/src/services/audio/Inno.Audio/AudioMixerFeatureExtensionAttribute.cs new file mode 100644 index 000000000..56e8aae81 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioMixerFeatureExtensionAttribute.cs @@ -0,0 +1,38 @@ +using System; + +namespace Inno.Audio; + +/// +/// Marks a reloadable extension that contributes to an audio mixer graph. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class AudioMixerFeatureExtensionAttribute : Attribute +{ + /// + /// Creates a mixer feature declaration. + /// + /// + /// Globally stable feature extension identifier. + /// + /// + /// Feature invocation priority; lower values build first. + /// + public AudioMixerFeatureExtensionAttribute( + string id, + int priority = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + this.priority = priority; + } + + /// + /// Gets the globally stable feature extension identifier. + /// + public string id { get; } + + /// + /// Gets the feature invocation priority. + /// + public int priority { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioParameterID.cs b/src/services/audio/Inno.Audio/AudioParameterID.cs new file mode 100644 index 000000000..6096c3356 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioParameterID.cs @@ -0,0 +1,69 @@ +using System; + +namespace Inno.Audio; + +/// +/// Identifies one processor parameter without imposing a processor-specific enum. +/// +public readonly record struct AudioParameterID +{ + /// + /// Creates an open processor parameter identifier. + /// + /// + /// Stable parameter name within its processor protocol. + /// + public AudioParameterID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the standard cutoff or center-frequency parameter in hertz. + /// + public static AudioParameterID frequency { get; } = new("inno.audio.parameter.frequency-hz"); + + /// + /// Gets the standard filter quality-factor parameter. + /// + public static AudioParameterID quality { get; } = new("inno.audio.parameter.quality"); + + /// + /// Gets the standard equalizer gain parameter in decibels. + /// + public static AudioParameterID gainDecibels { get; } = new("inno.audio.parameter.gain-db"); + + /// + /// Gets the standard equalizer shelf-slope parameter. + /// + public static AudioParameterID shelfSlope { get; } = new("inno.audio.parameter.shelf-slope"); + + /// + /// Gets the standard delay duration parameter in milliseconds. + /// + public static AudioParameterID delayMilliseconds { get; } = new("inno.audio.parameter.delay-ms"); + + /// + /// Gets the standard delay feedback decay factor. + /// + public static AudioParameterID decay { get; } = new("inno.audio.parameter.decay"); + + /// + /// Gets the stable parameter protocol value. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats the identifier for diagnostics and persistence. + /// + /// + /// The stable protocol value. + /// + public override string ToString() => value; +} diff --git a/src/services/audio/Inno.Audio/AudioPlayOptions.cs b/src/services/audio/Inno.Audio/AudioPlayOptions.cs new file mode 100644 index 000000000..ef607d0a1 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioPlayOptions.cs @@ -0,0 +1,134 @@ +using System; + +namespace Inno.Audio; + +/// +/// Contains immutable parameters used to create one playback voice. +/// +public readonly record struct AudioPlayOptions +{ + /// + /// Creates default playback parameters. + /// + public AudioPlayOptions() + : this(1f, 1f, 0f, false, 0, AudioBusID.master, AudioClipLoadMode.Automatic, null) {} + + /// + /// Creates playback parameters. + /// + /// + /// Linear gain applied to the voice. + /// + /// + /// Playback-rate multiplier. + /// + /// + /// Stereo pan from negative one to positive one. + /// + /// + /// Whether playback restarts after reaching the clip end. + /// + /// + /// Voice retention priority; larger values are retained first. + /// + /// + /// Destination mixer bus. + /// + /// + /// Clip preparation override. + /// + /// + /// Optional spatial playback parameters. + /// + /// + /// Gain, pitch, or pan is non-finite or outside its valid range, or the load mode is undefined. + /// + /// + /// The supplied destination bus is uninitialized. + /// + public AudioPlayOptions( + float volume = 1f, + float pitch = 1f, + float pan = 0f, + bool loop = false, + int priority = 0, + AudioBusID? bus = null, + AudioClipLoadMode loadMode = AudioClipLoadMode.Automatic, + AudioSpatialOptions? spatial = null + ) { + if (!float.IsFinite(volume) || volume < 0f) + { + throw new ArgumentOutOfRangeException(nameof(volume)); + } + if (!float.IsFinite(pitch) || pitch <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(pitch)); + } + if (!float.IsFinite(pan) || pan is < -1f or > 1f) + { + throw new ArgumentOutOfRangeException(nameof(pan)); + } + if (!Enum.IsDefined(loadMode)) + { + throw new ArgumentOutOfRangeException(nameof(loadMode)); + } + AudioBusID resolvedBus = bus ?? AudioBusID.master; + if (!resolvedBus.isValid) + { + throw new ArgumentException("A valid destination bus is required.", nameof(bus)); + } + this.volume = volume; + this.pitch = pitch; + this.pan = pan; + this.loop = loop; + this.priority = priority; + this.bus = resolvedBus; + this.loadMode = loadMode; + this.spatial = spatial; + } + + /// + /// Gets the default playback parameters. + /// + public static AudioPlayOptions defaultValue { get; } = new(); + + /// + /// Gets the linear voice gain. + /// + public float volume { get; } + + /// + /// Gets the playback-rate multiplier. + /// + public float pitch { get; } + + /// + /// Gets the stereo pan value. + /// + public float pan { get; } + + /// + /// Gets whether playback loops at the clip end. + /// + public bool loop { get; } + + /// + /// Gets the voice retention priority. + /// + public int priority { get; } + + /// + /// Gets the destination mixer bus. + /// + public AudioBusID bus { get; } + + /// + /// Gets the clip preparation override. + /// + public AudioClipLoadMode loadMode { get; } + + /// + /// Gets optional spatial playback parameters. + /// + public AudioSpatialOptions? spatial { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioPlaybackState.cs b/src/services/audio/Inno.Audio/AudioPlaybackState.cs new file mode 100644 index 000000000..018bf0d9d --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioPlaybackState.cs @@ -0,0 +1,32 @@ +namespace Inno.Audio; + +/// +/// Describes the observable lifecycle of one playback voice. +/// +public enum AudioPlaybackState +{ + /// + /// The voice is waiting for clip preparation. + /// + Preparing, + /// + /// The voice is scheduled against the audio clock. + /// + Scheduled, + /// + /// The voice is actively advancing. + /// + Playing, + /// + /// The voice is paused at its current cursor. + /// + Paused, + /// + /// The voice has completed and no longer accepts control commands. + /// + Completed, + /// + /// The handle is invalid, stale, or unknown to the active runtime. + /// + Invalid +} diff --git a/src/services/audio/Inno.Audio/AudioProcessorConfiguration.cs b/src/services/audio/Inno.Audio/AudioProcessorConfiguration.cs new file mode 100644 index 000000000..bcf5fc3ec --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioProcessorConfiguration.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Audio; + +/// +/// Describes one ordered processor instance attached to a mixer bus. +/// +public sealed class AudioProcessorConfiguration +{ + private readonly AudioProcessorParameter[] m_parameters; + + /// + /// Creates an immutable processor configuration. + /// + /// + /// Open processor protocol identifier. + /// + /// + /// Complete processor parameter set. + /// + public AudioProcessorConfiguration( + AudioProcessorID id, + IEnumerable? parameters = null + ) { + if (!id.isValid) + { + throw new ArgumentException("A valid processor identifier is required.", nameof(id)); + } + this.id = id; + m_parameters = parameters?.ToArray() ?? []; + if (m_parameters.Select(static parameter => parameter.id).Distinct().Count() != m_parameters.Length) + { + throw new ArgumentException("Processor parameter identifiers must be unique.", nameof(parameters)); + } + } + + /// + /// Gets the open processor protocol identifier. + /// + public AudioProcessorID id { get; } + + /// + /// Gets the immutable processor parameter set. + /// + public IReadOnlyList parameters => Array.AsReadOnly(m_parameters); +} diff --git a/src/services/audio/Inno.Audio/AudioProcessorID.cs b/src/services/audio/Inno.Audio/AudioProcessorID.cs new file mode 100644 index 000000000..db2439269 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioProcessorID.cs @@ -0,0 +1,79 @@ +using System; + +namespace Inno.Audio; + +/// +/// Identifies an audio processor implementation without imposing a closed effect catalog. +/// +public readonly record struct AudioProcessorID +{ + /// + /// Creates an open processor identifier. + /// + /// + /// Globally stable processor protocol value. + /// + public AudioProcessorID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the standard low-pass filter processor identifier. + /// + public static AudioProcessorID lowPass { get; } = new("inno.audio.processor.low-pass"); + + /// + /// Gets the standard high-pass filter processor identifier. + /// + public static AudioProcessorID highPass { get; } = new("inno.audio.processor.high-pass"); + + /// + /// Gets the standard band-pass filter processor identifier. + /// + public static AudioProcessorID bandPass { get; } = new("inno.audio.processor.band-pass"); + + /// + /// Gets the standard notch filter processor identifier. + /// + public static AudioProcessorID notch { get; } = new("inno.audio.processor.notch"); + + /// + /// Gets the standard peak equalizer processor identifier. + /// + public static AudioProcessorID peak { get; } = new("inno.audio.processor.peak"); + + /// + /// Gets the standard low-shelf equalizer processor identifier. + /// + public static AudioProcessorID lowShelf { get; } = new("inno.audio.processor.low-shelf"); + + /// + /// Gets the standard high-shelf equalizer processor identifier. + /// + public static AudioProcessorID highShelf { get; } = new("inno.audio.processor.high-shelf"); + + /// + /// Gets the standard delay processor identifier. + /// + public static AudioProcessorID delay { get; } = new("inno.audio.processor.delay"); + + /// + /// Gets the globally stable protocol value. + /// + public string value { get; } + + /// + /// Gets whether this identifier contains a usable protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats the identifier for diagnostics and persistence. + /// + /// + /// The stable protocol value. + /// + public override string ToString() => value; +} diff --git a/src/services/audio/Inno.Audio/AudioProcessorParameter.cs b/src/services/audio/Inno.Audio/AudioProcessorParameter.cs new file mode 100644 index 000000000..910631791 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioProcessorParameter.cs @@ -0,0 +1,40 @@ +using System; + +namespace Inno.Audio; + +/// +/// Stores one neutral numeric parameter assigned to an audio processor. +/// +public readonly record struct AudioProcessorParameter +{ + /// + /// Creates a processor parameter value. + /// + /// + /// Open parameter identifier understood by the processor protocol. + /// + /// + /// Neutral numeric value interpreted by the processor. + /// + public AudioProcessorParameter( + AudioParameterID id, + float value + ) { + if (!id.isValid) + { + throw new ArgumentException("A valid parameter identifier is required.", nameof(id)); + } + this.id = id; + this.value = value; + } + + /// + /// Gets the open parameter identifier. + /// + public AudioParameterID id { get; } + + /// + /// Gets the neutral numeric value. + /// + public float value { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioProtocolIDs.cs b/src/services/audio/Inno.Audio/AudioProtocolIDs.cs deleted file mode 100644 index 65e8b7325..000000000 --- a/src/services/audio/Inno.Audio/AudioProtocolIDs.cs +++ /dev/null @@ -1,237 +0,0 @@ -using System; - -namespace Inno.Audio; - -/// -/// Identifies a mixer bus without imposing a closed bus catalog. -/// -public readonly record struct AudioBusID -{ - /// - /// Creates an open mixer bus identifier. - /// - /// - /// Globally stable bus protocol value. - /// - public AudioBusID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the mandatory root bus identifier. - /// - public static AudioBusID master { get; } = new("inno.audio.bus.master"); - - /// - /// Gets the globally stable protocol value. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats the identifier for diagnostics and persistence. - /// - /// - /// The stable protocol value. - /// - public override string ToString() => value; -} - -/// -/// Identifies an audio processor implementation without imposing a closed effect catalog. -/// -public readonly record struct AudioProcessorID -{ - /// - /// Creates an open processor identifier. - /// - /// - /// Globally stable processor protocol value. - /// - public AudioProcessorID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the standard low-pass filter processor identifier. - /// - public static AudioProcessorID lowPass { get; } = new("inno.audio.processor.low-pass"); - - /// - /// Gets the standard high-pass filter processor identifier. - /// - public static AudioProcessorID highPass { get; } = new("inno.audio.processor.high-pass"); - - /// - /// Gets the standard band-pass filter processor identifier. - /// - public static AudioProcessorID bandPass { get; } = new("inno.audio.processor.band-pass"); - - /// - /// Gets the standard notch filter processor identifier. - /// - public static AudioProcessorID notch { get; } = new("inno.audio.processor.notch"); - - /// - /// Gets the standard peak equalizer processor identifier. - /// - public static AudioProcessorID peak { get; } = new("inno.audio.processor.peak"); - - /// - /// Gets the standard low-shelf equalizer processor identifier. - /// - public static AudioProcessorID lowShelf { get; } = new("inno.audio.processor.low-shelf"); - - /// - /// Gets the standard high-shelf equalizer processor identifier. - /// - public static AudioProcessorID highShelf { get; } = new("inno.audio.processor.high-shelf"); - - /// - /// Gets the standard delay processor identifier. - /// - public static AudioProcessorID delay { get; } = new("inno.audio.processor.delay"); - - /// - /// Gets the globally stable protocol value. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats the identifier for diagnostics and persistence. - /// - /// - /// The stable protocol value. - /// - public override string ToString() => value; -} - -/// -/// Identifies one processor parameter without imposing a processor-specific enum. -/// -public readonly record struct AudioParameterID -{ - /// - /// Creates an open processor parameter identifier. - /// - /// - /// Stable parameter name within its processor protocol. - /// - public AudioParameterID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the standard cutoff or center-frequency parameter in hertz. - /// - public static AudioParameterID frequency { get; } = new("inno.audio.parameter.frequency-hz"); - - /// - /// Gets the standard filter quality-factor parameter. - /// - public static AudioParameterID quality { get; } = new("inno.audio.parameter.quality"); - - /// - /// Gets the standard equalizer gain parameter in decibels. - /// - public static AudioParameterID gainDecibels { get; } = new("inno.audio.parameter.gain-db"); - - /// - /// Gets the standard equalizer shelf-slope parameter. - /// - public static AudioParameterID shelfSlope { get; } = new("inno.audio.parameter.shelf-slope"); - - /// - /// Gets the standard delay duration parameter in milliseconds. - /// - public static AudioParameterID delayMilliseconds { get; } = new("inno.audio.parameter.delay-ms"); - - /// - /// Gets the standard delay feedback decay factor. - /// - public static AudioParameterID decay { get; } = new("inno.audio.parameter.decay"); - - /// - /// Gets the stable parameter protocol value. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats the identifier for diagnostics and persistence. - /// - /// - /// The stable protocol value. - /// - public override string ToString() => value; -} - -/// -/// Identifies encoded audio data without constraining codec providers to a closed enum. -/// -public readonly record struct AudioCodecID -{ - /// - /// Creates an open codec identifier. - /// - /// - /// Globally stable codec protocol value. - /// - public AudioCodecID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the standard Waveform Audio codec identifier. - /// - public static AudioCodecID wav { get; } = new("audio/wav"); - - /// - /// Gets the standard Free Lossless Audio Codec identifier. - /// - public static AudioCodecID flac { get; } = new("audio/flac"); - - /// - /// Gets the standard MPEG Layer III codec identifier. - /// - public static AudioCodecID mp3 { get; } = new("audio/mpeg"); - - /// - /// Gets the globally stable protocol value. - /// - public string value { get; } - - /// - /// Gets whether this identifier contains a usable protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats the identifier for diagnostics and persistence. - /// - /// - /// The stable protocol value. - /// - public override string ToString() => value; -} diff --git a/src/services/audio/Inno.Audio/AudioSpatialOptions.cs b/src/services/audio/Inno.Audio/AudioSpatialOptions.cs new file mode 100644 index 000000000..0169ff8e7 --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioSpatialOptions.cs @@ -0,0 +1,158 @@ +using System; +using Inno.Core.Mathematics; + +namespace Inno.Audio; + +/// +/// Contains listener-relative positioning and attenuation parameters for one voice. +/// +public readonly record struct AudioSpatialOptions +{ + /// + /// Creates spatial playback parameters. + /// + /// + /// World-space source position. + /// + /// + /// World-space source forward direction. + /// + /// + /// World-space source velocity used for Doppler calculation. + /// + /// + /// Distance attenuation model. + /// + /// + /// Distance at which attenuation begins. + /// + /// + /// Distance beyond which attenuation is clamped. + /// + /// + /// Attenuation strength for the selected distance model. + /// + /// + /// Full-volume source cone angle in degrees. + /// + /// + /// Outer source cone angle in degrees. + /// + /// + /// Gain outside the outer cone. + /// + /// + /// Doppler effect multiplier. + /// + /// + /// A vector or scalar is non-finite, a spatial bound is invalid, or the distance model is undefined. + /// + public AudioSpatialOptions( + Vector3 position, + Vector3 direction, + Vector3 velocity, + AudioDistanceModel distanceModel = AudioDistanceModel.Inverse, + float minDistance = 1f, + float maxDistance = 100f, + float rolloff = 1f, + float coneInnerAngle = 360f, + float coneOuterAngle = 360f, + float coneOuterGain = 1f, + float dopplerFactor = 1f + ) { + AudioValueValidation.RequireFinite(position, nameof(position)); + AudioValueValidation.RequireFinite(direction, nameof(direction)); + AudioValueValidation.RequireFinite(velocity, nameof(velocity)); + if (!Enum.IsDefined(distanceModel)) + { + throw new ArgumentOutOfRangeException(nameof(distanceModel)); + } + if (!float.IsFinite(minDistance) || !float.IsFinite(maxDistance) || minDistance < 0f || maxDistance < minDistance) + { + throw new ArgumentOutOfRangeException(nameof(minDistance), "Spatial distance bounds are invalid."); + } + if (!float.IsFinite(rolloff) || rolloff < 0f) + { + throw new ArgumentOutOfRangeException(nameof(rolloff)); + } + if (!float.IsFinite(coneInnerAngle) || !float.IsFinite(coneOuterAngle) + || coneInnerAngle is < 0f or > 360f || coneOuterAngle < coneInnerAngle || coneOuterAngle > 360f + ) { + throw new ArgumentOutOfRangeException(nameof(coneOuterAngle), "Spatial cone angles are invalid."); + } + if (!float.IsFinite(coneOuterGain) || coneOuterGain is < 0f or > 1f) + { + throw new ArgumentOutOfRangeException(nameof(coneOuterGain)); + } + if (!float.IsFinite(dopplerFactor) || dopplerFactor < 0f) + { + throw new ArgumentOutOfRangeException(nameof(dopplerFactor)); + } + this.position = position; + this.direction = direction; + this.velocity = velocity; + this.distanceModel = distanceModel; + this.minDistance = minDistance; + this.maxDistance = maxDistance; + this.rolloff = rolloff; + this.coneInnerAngle = coneInnerAngle; + this.coneOuterAngle = coneOuterAngle; + this.coneOuterGain = coneOuterGain; + this.dopplerFactor = dopplerFactor; + } + + /// + /// Gets the world-space source position. + /// + public Vector3 position { get; } + + /// + /// Gets the world-space source forward direction. + /// + public Vector3 direction { get; } + + /// + /// Gets the world-space source velocity. + /// + public Vector3 velocity { get; } + + /// + /// Gets the distance attenuation model. + /// + public AudioDistanceModel distanceModel { get; } + + /// + /// Gets the distance at which attenuation begins. + /// + public float minDistance { get; } + + /// + /// Gets the distance beyond which attenuation is clamped. + /// + public float maxDistance { get; } + + /// + /// Gets the distance attenuation strength. + /// + public float rolloff { get; } + + /// + /// Gets the full-volume cone angle in degrees. + /// + public float coneInnerAngle { get; } + + /// + /// Gets the outer cone angle in degrees. + /// + public float coneOuterAngle { get; } + + /// + /// Gets the gain outside the outer cone. + /// + public float coneOuterGain { get; } + + /// + /// Gets the Doppler effect multiplier. + /// + public float dopplerFactor { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioStatistics.cs b/src/services/audio/Inno.Audio/AudioStatistics.cs new file mode 100644 index 000000000..2a9af245f --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioStatistics.cs @@ -0,0 +1,60 @@ +using System; + +namespace Inno.Audio; + +/// +/// Reports an immutable snapshot of runtime and backend resource usage. +/// +public readonly record struct AudioStatistics +{ + /// + /// Creates an audio statistics snapshot. + /// + /// + /// Voices that currently consume runtime budget. + /// + /// + /// Clip allocations held by the backend. + /// + /// + /// Approximate decoded clip bytes held in memory. + /// + /// + /// Voices reclaimed since runtime creation. + /// + public AudioStatistics( + int activeVoices, + int loadedClips, + long decodedBytes, + long stolenVoiceCount + ) { + ArgumentOutOfRangeException.ThrowIfNegative(activeVoices); + ArgumentOutOfRangeException.ThrowIfNegative(loadedClips); + ArgumentOutOfRangeException.ThrowIfNegative(decodedBytes); + ArgumentOutOfRangeException.ThrowIfNegative(stolenVoiceCount); + this.activeVoices = activeVoices; + this.loadedClips = loadedClips; + this.decodedBytes = decodedBytes; + this.stolenVoiceCount = stolenVoiceCount; + } + + /// + /// Gets voices that currently consume runtime budget. + /// + public int activeVoices { get; } + + /// + /// Gets clip allocations held by the backend. + /// + public int loadedClips { get; } + + /// + /// Gets approximate decoded clip bytes held in memory. + /// + public long decodedBytes { get; } + + /// + /// Gets voices reclaimed since runtime creation. + /// + public long stolenVoiceCount { get; } +} diff --git a/src/services/audio/Inno.Audio/AudioTypes.cs b/src/services/audio/Inno.Audio/AudioTypes.cs deleted file mode 100644 index 2814367de..000000000 --- a/src/services/audio/Inno.Audio/AudioTypes.cs +++ /dev/null @@ -1,666 +0,0 @@ -using System; -using Inno.Core.Mathematics; - -namespace Inno.Audio; - -/// -/// Selects how encoded clip data is prepared for playback. -/// -public enum AudioClipLoadMode -{ - /// - /// Lets the runtime choose between decoded and streamed storage. - /// - Automatic, - /// - /// Decodes the complete clip before playback. - /// - Decode, - /// - /// Decodes encoded data incrementally while playback advances. - /// - Stream -} - -/// -/// Describes the availability of the active audio output generation. -/// -public enum AudioDeviceState -{ - /// - /// The device has not completed initialization. - /// - Initializing, - /// - /// The device is available for audible playback. - /// - Ready, - /// - /// Playback is advancing without an output device. - /// - Muted, - /// - /// The active output device was lost and recovery is pending. - /// - Lost, - /// - /// The device has been released and cannot accept work. - /// - Disposed -} - -/// -/// Describes the observable lifecycle of one playback voice. -/// -public enum AudioPlaybackState -{ - /// - /// The voice is waiting for clip preparation. - /// - Preparing, - /// - /// The voice is scheduled against the audio clock. - /// - Scheduled, - /// - /// The voice is actively advancing. - /// - Playing, - /// - /// The voice is paused at its current cursor. - /// - Paused, - /// - /// The voice has completed and no longer accepts control commands. - /// - Completed, - /// - /// The handle is invalid, stale, or unknown to the active runtime. - /// - Invalid -} - -/// -/// Explains why a voice stopped accepting playback commands. -/// -public enum AudioCompletionReason -{ - /// - /// The clip reached its natural end. - /// - NaturalEnd, - /// - /// A caller explicitly stopped the voice. - /// - Stopped, - /// - /// The runtime reclaimed the voice to satisfy its voice budget. - /// - Stolen, - /// - /// Encoded data could not be prepared or decoded. - /// - DecodeFailed, - /// - /// Playback ended because the owning device generation was lost. - /// - DeviceLost -} - -/// -/// Selects the distance attenuation model for one spatial voice. -/// -public enum AudioDistanceModel -{ - /// - /// Disables distance attenuation while retaining spatial direction. - /// - None, - /// - /// Uses inverse-distance attenuation. - /// - Inverse, - /// - /// Uses linear-distance attenuation. - /// - Linear, - /// - /// Uses exponential-distance attenuation. - /// - Exponential -} - -/// -/// Describes backend-neutral features and limits for one device generation. -/// -public sealed record AudioCapabilities -{ - /// - /// Creates an immutable audio capability snapshot. - /// - /// - /// Whether clips can be decoded incrementally. - /// - /// - /// Whether voices can start against the audio clock. - /// - /// - /// Whether listener-relative spatial playback is available. - /// - /// - /// Maximum simultaneously active listeners. - /// - /// - /// Device output sample rate in frames per second. - /// - public AudioCapabilities( - bool supportsStreaming, - bool supportsScheduledPlayback, - bool supportsSpatialAudio, - int maxListeners, - int sampleRate - ) { - ArgumentOutOfRangeException.ThrowIfNegative(maxListeners); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sampleRate); - this.supportsStreaming = supportsStreaming; - this.supportsScheduledPlayback = supportsScheduledPlayback; - this.supportsSpatialAudio = supportsSpatialAudio; - this.maxListeners = maxListeners; - this.sampleRate = sampleRate; - } - - /// - /// Gets whether clips can be decoded incrementally. - /// - public bool supportsStreaming { get; } - - /// - /// Gets whether voices can start against the audio clock. - /// - public bool supportsScheduledPlayback { get; } - - /// - /// Gets whether listener-relative spatial playback is available. - /// - public bool supportsSpatialAudio { get; } - - /// - /// Gets the maximum simultaneously active listener count. - /// - public int maxListeners { get; } - - /// - /// Gets the output sample rate in frames per second. - /// - public int sampleRate { get; } -} - -/// -/// Reports an immutable snapshot of runtime and backend resource usage. -/// -public readonly record struct AudioStatistics -{ - /// - /// Creates an audio statistics snapshot. - /// - /// - /// Voices that currently consume runtime budget. - /// - /// - /// Clip allocations held by the backend. - /// - /// - /// Approximate decoded clip bytes held in memory. - /// - /// - /// Voices reclaimed since runtime creation. - /// - public AudioStatistics( - int activeVoices, - int loadedClips, - long decodedBytes, - long stolenVoiceCount - ) { - ArgumentOutOfRangeException.ThrowIfNegative(activeVoices); - ArgumentOutOfRangeException.ThrowIfNegative(loadedClips); - ArgumentOutOfRangeException.ThrowIfNegative(decodedBytes); - ArgumentOutOfRangeException.ThrowIfNegative(stolenVoiceCount); - this.activeVoices = activeVoices; - this.loadedClips = loadedClips; - this.decodedBytes = decodedBytes; - this.stolenVoiceCount = stolenVoiceCount; - } - - /// - /// Gets voices that currently consume runtime budget. - /// - public int activeVoices { get; } - - /// - /// Gets clip allocations held by the backend. - /// - public int loadedClips { get; } - - /// - /// Gets approximate decoded clip bytes held in memory. - /// - public long decodedBytes { get; } - - /// - /// Gets voices reclaimed since runtime creation. - /// - public long stolenVoiceCount { get; } -} - -/// -/// Contains listener-relative positioning and attenuation parameters for one voice. -/// -public readonly record struct AudioSpatialOptions -{ - /// - /// Creates spatial playback parameters. - /// - /// - /// World-space source position. - /// - /// - /// World-space source forward direction. - /// - /// - /// World-space source velocity used for Doppler calculation. - /// - /// - /// Distance attenuation model. - /// - /// - /// Distance at which attenuation begins. - /// - /// - /// Distance beyond which attenuation is clamped. - /// - /// - /// Attenuation strength for the selected distance model. - /// - /// - /// Full-volume source cone angle in degrees. - /// - /// - /// Outer source cone angle in degrees. - /// - /// - /// Gain outside the outer cone. - /// - /// - /// Doppler effect multiplier. - /// - /// - /// A vector or scalar is non-finite, a spatial bound is invalid, or the distance model is undefined. - /// - public AudioSpatialOptions( - Vector3 position, - Vector3 direction, - Vector3 velocity, - AudioDistanceModel distanceModel = AudioDistanceModel.Inverse, - float minDistance = 1f, - float maxDistance = 100f, - float rolloff = 1f, - float coneInnerAngle = 360f, - float coneOuterAngle = 360f, - float coneOuterGain = 1f, - float dopplerFactor = 1f - ) { - AudioValueValidation.RequireFinite(position, nameof(position)); - AudioValueValidation.RequireFinite(direction, nameof(direction)); - AudioValueValidation.RequireFinite(velocity, nameof(velocity)); - if (!Enum.IsDefined(distanceModel)) - { - throw new ArgumentOutOfRangeException(nameof(distanceModel)); - } - if (!float.IsFinite(minDistance) || !float.IsFinite(maxDistance) || minDistance < 0f || maxDistance < minDistance) - { - throw new ArgumentOutOfRangeException(nameof(minDistance), "Spatial distance bounds are invalid."); - } - if (!float.IsFinite(rolloff) || rolloff < 0f) - { - throw new ArgumentOutOfRangeException(nameof(rolloff)); - } - if (!float.IsFinite(coneInnerAngle) || !float.IsFinite(coneOuterAngle) - || coneInnerAngle is < 0f or > 360f || coneOuterAngle < coneInnerAngle || coneOuterAngle > 360f - ) { - throw new ArgumentOutOfRangeException(nameof(coneOuterAngle), "Spatial cone angles are invalid."); - } - if (!float.IsFinite(coneOuterGain) || coneOuterGain is < 0f or > 1f) - { - throw new ArgumentOutOfRangeException(nameof(coneOuterGain)); - } - if (!float.IsFinite(dopplerFactor) || dopplerFactor < 0f) - { - throw new ArgumentOutOfRangeException(nameof(dopplerFactor)); - } - this.position = position; - this.direction = direction; - this.velocity = velocity; - this.distanceModel = distanceModel; - this.minDistance = minDistance; - this.maxDistance = maxDistance; - this.rolloff = rolloff; - this.coneInnerAngle = coneInnerAngle; - this.coneOuterAngle = coneOuterAngle; - this.coneOuterGain = coneOuterGain; - this.dopplerFactor = dopplerFactor; - } - - /// - /// Gets the world-space source position. - /// - public Vector3 position { get; } - - /// - /// Gets the world-space source forward direction. - /// - public Vector3 direction { get; } - - /// - /// Gets the world-space source velocity. - /// - public Vector3 velocity { get; } - - /// - /// Gets the distance attenuation model. - /// - public AudioDistanceModel distanceModel { get; } - - /// - /// Gets the distance at which attenuation begins. - /// - public float minDistance { get; } - - /// - /// Gets the distance beyond which attenuation is clamped. - /// - public float maxDistance { get; } - - /// - /// Gets the distance attenuation strength. - /// - public float rolloff { get; } - - /// - /// Gets the full-volume cone angle in degrees. - /// - public float coneInnerAngle { get; } - - /// - /// Gets the outer cone angle in degrees. - /// - public float coneOuterAngle { get; } - - /// - /// Gets the gain outside the outer cone. - /// - public float coneOuterGain { get; } - - /// - /// Gets the Doppler effect multiplier. - /// - public float dopplerFactor { get; } -} - -/// -/// Contains immutable parameters used to create one playback voice. -/// -public readonly record struct AudioPlayOptions -{ - /// - /// Creates default playback parameters. - /// - public AudioPlayOptions() - : this(1f, 1f, 0f, false, 0, AudioBusID.master, AudioClipLoadMode.Automatic, null) {} - - /// - /// Creates playback parameters. - /// - /// - /// Linear gain applied to the voice. - /// - /// - /// Playback-rate multiplier. - /// - /// - /// Stereo pan from negative one to positive one. - /// - /// - /// Whether playback restarts after reaching the clip end. - /// - /// - /// Voice retention priority; larger values are retained first. - /// - /// - /// Destination mixer bus. - /// - /// - /// Clip preparation override. - /// - /// - /// Optional spatial playback parameters. - /// - /// - /// Gain, pitch, or pan is non-finite or outside its valid range, or the load mode is undefined. - /// - /// - /// The supplied destination bus is uninitialized. - /// - public AudioPlayOptions( - float volume = 1f, - float pitch = 1f, - float pan = 0f, - bool loop = false, - int priority = 0, - AudioBusID? bus = null, - AudioClipLoadMode loadMode = AudioClipLoadMode.Automatic, - AudioSpatialOptions? spatial = null - ) { - if (!float.IsFinite(volume) || volume < 0f) - { - throw new ArgumentOutOfRangeException(nameof(volume)); - } - if (!float.IsFinite(pitch) || pitch <= 0f) - { - throw new ArgumentOutOfRangeException(nameof(pitch)); - } - if (!float.IsFinite(pan) || pan is < -1f or > 1f) - { - throw new ArgumentOutOfRangeException(nameof(pan)); - } - if (!Enum.IsDefined(loadMode)) - { - throw new ArgumentOutOfRangeException(nameof(loadMode)); - } - AudioBusID resolvedBus = bus ?? AudioBusID.master; - if (!resolvedBus.isValid) - { - throw new ArgumentException("A valid destination bus is required.", nameof(bus)); - } - this.volume = volume; - this.pitch = pitch; - this.pan = pan; - this.loop = loop; - this.priority = priority; - this.bus = resolvedBus; - this.loadMode = loadMode; - this.spatial = spatial; - } - - /// - /// Gets the default playback parameters. - /// - public static AudioPlayOptions defaultValue { get; } = new(); - - /// - /// Gets the linear voice gain. - /// - public float volume { get; } - - /// - /// Gets the playback-rate multiplier. - /// - public float pitch { get; } - - /// - /// Gets the stereo pan value. - /// - public float pan { get; } - - /// - /// Gets whether playback loops at the clip end. - /// - public bool loop { get; } - - /// - /// Gets the voice retention priority. - /// - public int priority { get; } - - /// - /// Gets the destination mixer bus. - /// - public AudioBusID bus { get; } - - /// - /// Gets the clip preparation override. - /// - public AudioClipLoadMode loadMode { get; } - - /// - /// Gets optional spatial playback parameters. - /// - public AudioSpatialOptions? spatial { get; } -} - -/// -/// Contains mutable voice parameters that can be changed after playback begins. -/// -public readonly record struct AudioVoiceParameters -{ - /// - /// Creates a voice parameter snapshot. - /// - /// - /// Linear voice gain. - /// - /// - /// Playback-rate multiplier. - /// - /// - /// Stereo pan from negative one to positive one. - /// - /// - /// Optional spatial playback parameters. - /// - /// - /// Gain, pitch, or pan is non-finite or outside its valid range. - /// - public AudioVoiceParameters( - float volume, - float pitch, - float pan, - AudioSpatialOptions? spatial = null - ) { - if (!float.IsFinite(volume) || volume < 0f) - { - throw new ArgumentOutOfRangeException(nameof(volume)); - } - if (!float.IsFinite(pitch) || pitch <= 0f) - { - throw new ArgumentOutOfRangeException(nameof(pitch)); - } - if (!float.IsFinite(pan) || pan is < -1f or > 1f) - { - throw new ArgumentOutOfRangeException(nameof(pan)); - } - this.volume = volume; - this.pitch = pitch; - this.pan = pan; - this.spatial = spatial; - } - - /// - /// Gets the linear voice gain. - /// - public float volume { get; } - - /// - /// Gets the playback-rate multiplier. - /// - public float pitch { get; } - - /// - /// Gets the stereo pan value. - /// - public float pan { get; } - - /// - /// Gets optional spatial playback parameters. - /// - public AudioSpatialOptions? spatial { get; } -} - -/// -/// Contains one listener transform used by backend spatialization. -/// -public readonly record struct AudioListenerState -{ - /// - /// Creates a listener transform snapshot. - /// - /// - /// World-space listener position. - /// - /// - /// World-space listener forward direction. - /// - /// - /// World-space listener up direction. - /// - /// - /// World-space listener velocity. - /// - /// - /// Any position, direction, up, or velocity component is non-finite. - /// - public AudioListenerState( - Vector3 position, - Vector3 direction, - Vector3 up, - Vector3 velocity - ) { - AudioValueValidation.RequireFinite(position, nameof(position)); - AudioValueValidation.RequireFinite(direction, nameof(direction)); - AudioValueValidation.RequireFinite(up, nameof(up)); - AudioValueValidation.RequireFinite(velocity, nameof(velocity)); - this.position = position; - this.direction = direction; - this.up = up; - this.velocity = velocity; - } - - /// - /// Gets the world-space listener position. - /// - public Vector3 position { get; } - - /// - /// Gets the world-space listener forward direction. - /// - public Vector3 direction { get; } - - /// - /// Gets the world-space listener up direction. - /// - public Vector3 up { get; } - - /// - /// Gets the world-space listener velocity. - /// - public Vector3 velocity { get; } -} diff --git a/src/services/audio/Inno.Audio/AudioVoiceHandle.cs b/src/services/audio/Inno.Audio/AudioVoiceHandle.cs new file mode 100644 index 000000000..8a7bd8bbf --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioVoiceHandle.cs @@ -0,0 +1,27 @@ +namespace Inno.Audio; + +/// +/// Identifies one playback voice within a device generation. +/// +public readonly record struct AudioVoiceHandle +{ + internal AudioVoiceHandle( + ulong value, + uint ownerGeneration + ) { + this.value = value; + this.ownerGeneration = ownerGeneration; + } + + internal ulong value { get; } + + /// + /// Gets the generation of the device that created this handle. + /// + public uint ownerGeneration { get; } + + /// + /// Gets whether the handle contains a non-zero backend identity and generation. + /// + public bool isValid => value != 0 && ownerGeneration != 0; +} diff --git a/src/services/audio/Inno.Audio/AudioVoiceParameters.cs b/src/services/audio/Inno.Audio/AudioVoiceParameters.cs new file mode 100644 index 000000000..25b06db0c --- /dev/null +++ b/src/services/audio/Inno.Audio/AudioVoiceParameters.cs @@ -0,0 +1,71 @@ +using System; + +namespace Inno.Audio; + +/// +/// Contains mutable voice parameters that can be changed after playback begins. +/// +public readonly record struct AudioVoiceParameters +{ + /// + /// Creates a voice parameter snapshot. + /// + /// + /// Linear voice gain. + /// + /// + /// Playback-rate multiplier. + /// + /// + /// Stereo pan from negative one to positive one. + /// + /// + /// Optional spatial playback parameters. + /// + /// + /// Gain, pitch, or pan is non-finite or outside its valid range. + /// + public AudioVoiceParameters( + float volume, + float pitch, + float pan, + AudioSpatialOptions? spatial = null + ) { + if (!float.IsFinite(volume) || volume < 0f) + { + throw new ArgumentOutOfRangeException(nameof(volume)); + } + if (!float.IsFinite(pitch) || pitch <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(pitch)); + } + if (!float.IsFinite(pan) || pan is < -1f or > 1f) + { + throw new ArgumentOutOfRangeException(nameof(pan)); + } + this.volume = volume; + this.pitch = pitch; + this.pan = pan; + this.spatial = spatial; + } + + /// + /// Gets the linear voice gain. + /// + public float volume { get; } + + /// + /// Gets the playback-rate multiplier. + /// + public float pitch { get; } + + /// + /// Gets the stereo pan value. + /// + public float pan { get; } + + /// + /// Gets optional spatial playback parameters. + /// + public AudioSpatialOptions? spatial { get; } +} diff --git a/src/services/audio/Inno.Audio/IAudioDevice.cs b/src/services/audio/Inno.Audio/IAudioDevice.cs index f59c7ca11..271913c0f 100644 --- a/src/services/audio/Inno.Audio/IAudioDevice.cs +++ b/src/services/audio/Inno.Audio/IAudioDevice.cs @@ -2,43 +2,6 @@ namespace Inno.Audio; -/// -/// Reports one backend-detected terminal voice transition. -/// -public readonly record struct AudioDeviceCompletion -{ - /// - /// Creates a backend voice completion record. - /// - /// - /// Voice that reached a terminal state. - /// - /// - /// Reason playback ended. - /// - public AudioDeviceCompletion( - AudioDeviceVoiceHandle voice, - AudioCompletionReason reason - ) { - if (!voice.isValid) - { - throw new ArgumentException("A valid voice handle is required.", nameof(voice)); - } - this.voice = voice; - this.reason = reason; - } - - /// - /// Gets the completed voice handle. - /// - public AudioDeviceVoiceHandle voice { get; } - - /// - /// Gets the terminal playback reason. - /// - public AudioCompletionReason reason { get; } -} - /// /// Owns one replaceable audio backend generation and all device-side audio objects. /// diff --git a/src/services/audio/Inno.Audio/SerializedAudioExtensionState.cs b/src/services/audio/Inno.Audio/SerializedAudioExtensionState.cs new file mode 100644 index 000000000..ba67c3318 --- /dev/null +++ b/src/services/audio/Inno.Audio/SerializedAudioExtensionState.cs @@ -0,0 +1,47 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Audio; + +/// +/// Stores reload-safe configuration for one mixer or feature extension generation. +/// +public struct SerializedAudioExtensionState +{ + /// + /// Creates empty extension state for deserialization. + /// + public SerializedAudioExtensionState() + { + this.propertyData = []; + } + + /// + /// Creates neutral extension state. + /// + /// + /// Stable settings type identity, or empty when no typed settings exist. + /// + /// + /// Neutral serialized property bytes. + /// + public SerializedAudioExtensionState( + Guid stableTypeID, + ReadOnlySpan propertyData + ) { + this.stableTypeId = stableTypeID; + this.propertyData = propertyData.ToArray(); + } + + /// + /// Gets or sets the stable settings type identity. + /// + [SerializableProperty] + public Guid stableTypeId { get; set; } + + /// + /// Gets or sets neutral serialized property bytes. + /// + [SerializableProperty] + public byte[] propertyData { get; set; } +} diff --git a/src/services/input/Inno.Input/Input.cs b/src/services/input/Inno.Input/Input.cs index 07d6e293b..8672df558 100644 --- a/src/services/input/Inno.Input/Input.cs +++ b/src/services/input/Inno.Input/Input.cs @@ -1,53 +1,8 @@ -using System; -using System.Threading; -using Inno.Core.Execution; using Inno.Core.Input; using Inno.Core.Mathematics; namespace Inno.Input; -/// -/// Binds one input service to the current asynchronous execution context. -/// -public static class InputExecutionContext -{ - private static readonly ExecutionSlot CURRENT_SCOPE = new("input"); - - /// - /// Gets the input service bound to the current execution context. - /// - /// - /// Thrown when no input scope is active. - /// - public static IInputService current => CURRENT_SCOPE.current; - - /// - /// Tries to read input when a host has installed an input subsystem for this frame. - /// - /// - /// Bound service, or null when unavailable. - /// - /// - /// Whether a live input service is bound. - /// - public static bool TryGet(out IInputService? input) => CURRENT_SCOPE.TryGet(out input); - - /// - /// Binds an input service until the returned strict last-in-first-out scope is disposed. - /// - /// - /// The host-owned input service. - /// - /// - /// A strict last-in-first-out execution scope. - /// - public static IDisposable EnterScope(IInputService input) - { - ArgumentNullException.ThrowIfNull(input); - return CURRENT_SCOPE.Enter(input); - } -} - /// /// Provides script-friendly access to the current frame's input snapshot. /// diff --git a/src/services/input/Inno.Input/InputExecutionContext.cs b/src/services/input/Inno.Input/InputExecutionContext.cs new file mode 100644 index 000000000..f307c623b --- /dev/null +++ b/src/services/input/Inno.Input/InputExecutionContext.cs @@ -0,0 +1,46 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Input; + +/// +/// Binds one input service to the current asynchronous execution context. +/// +public static class InputExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("input"); + + /// + /// Gets the input service bound to the current execution context. + /// + /// + /// Thrown when no input scope is active. + /// + public static IInputService current => CURRENT_SCOPE.current; + + /// + /// Tries to read input when a host has installed an input subsystem for this frame. + /// + /// + /// Bound service, or null when unavailable. + /// + /// + /// Whether a live input service is bound. + /// + public static bool TryGet(out IInputService? input) => CURRENT_SCOPE.TryGet(out input); + + /// + /// Binds an input service until the returned strict last-in-first-out scope is disposed. + /// + /// + /// The host-owned input service. + /// + /// + /// A strict last-in-first-out execution scope. + /// + public static IDisposable EnterScope(IInputService input) + { + ArgumentNullException.ThrowIfNull(input); + return CURRENT_SCOPE.Enter(input); + } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderArtifact.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderArtifact.cs new file mode 100644 index 000000000..dbd9c091a --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderArtifact.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Contains an immutable target shader artifact and expected reflected interface. +/// +[StableTypeID("25e556fe-a071-58b2-8e70-0e41bd434d83")] +public sealed class CompiledShaderArtifact +{ + private readonly byte[] m_definitionData; + + /// + /// Creates a compiled shader artifact. + /// + /// + /// Artist-facing shader name. + /// + /// + /// Stable target cache key. + /// + /// + /// Static keyword variant. + /// + /// + /// Manifest-derived binding contract. + /// + /// + /// Compiled pass binaries. + /// + /// + /// Native-serialized runtime definition captured before asynchronous compilation. + /// + public CompiledShaderArtifact( + string shaderName, + string targetKey, + RenderShaderVariant variant, + ShaderInterface shaderInterface, + IReadOnlyList passes, + ReadOnlySpan definitionData + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(shaderName); + ArgumentException.ThrowIfNullOrWhiteSpace(targetKey); + ArgumentNullException.ThrowIfNull(shaderInterface); + ArgumentNullException.ThrowIfNull(passes); + this.shaderName = shaderName; + this.targetKey = targetKey; + this.variant = variant; + this.shaderInterface = shaderInterface; + this.passes = Array.AsReadOnly(passes.ToArray()); + if (definitionData.IsEmpty) + { + throw new ArgumentException("Compiled programs require a captured runtime contract.", nameof(definitionData)); + } + m_definitionData = definitionData.ToArray(); + } + + /// + /// Gets the artist-facing shader name. + /// + public string shaderName { get; } + + /// + /// Gets the stable target cache key. + /// + public string targetKey { get; } + + /// + /// Gets the static keyword variant. + /// + public RenderShaderVariant variant { get; } + + /// + /// Gets the manifest-derived binding contract. + /// + public ShaderInterface shaderInterface { get; } + + /// + /// Gets compiled pass binaries. + /// + public IReadOnlyList passes { get; } + + /// + /// Creates the source-free deployment artifact consumed by Editor preview sessions and Players. + /// + /// + /// A deep immutable runtime artifact containing only target binaries, fixed-function state, and binding contracts. + /// + public RenderShaderArtifact CreateRuntimeArtifact() + => new( + shaderName, + targetKey, + variant, + shaderInterface, + passes.Select(static pass => new RenderShaderPassArtifact( + pass.definition.name, + pass.definition.programKind, + ConvertRasterState(pass.definition.renderState), + pass.shaderInterface, + pass.stages.Select(static stage => new RenderShaderStageArtifact( + stage.stage, + stage.bytes.Span + )).ToArray() + )).ToArray(), + m_definitionData + ); + + private static RenderRasterState ConvertRasterState(ShaderRenderState source) + => new() + { + topology = source.topology, + cull = source.cull switch + { + ShaderCullMode.None => RenderCullMode.None, + ShaderCullMode.Front => RenderCullMode.Front, + ShaderCullMode.Back => RenderCullMode.Back, + _ => throw new ArgumentOutOfRangeException(nameof(source)) + }, + frontFace = source.frontFace, + depthCompare = source.depthCompare switch + { + ShaderCompareFunction.Never => RenderDepthCompare.Never, + ShaderCompareFunction.Less => RenderDepthCompare.Less, + ShaderCompareFunction.Equal => RenderDepthCompare.Equal, + ShaderCompareFunction.LessEqual => RenderDepthCompare.LessEqual, + ShaderCompareFunction.Greater => RenderDepthCompare.Greater, + ShaderCompareFunction.NotEqual => RenderDepthCompare.NotEqual, + ShaderCompareFunction.GreaterEqual => RenderDepthCompare.GreaterEqual, + ShaderCompareFunction.Always => RenderDepthCompare.Always, + _ => throw new ArgumentOutOfRangeException(nameof(source)) + }, + depthWrite = source.depthWrite, + blend = source.blend, + colorWriteMask = source.colorWriteMask, + multisampling = source.multisampling + }; +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderPass.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderPass.cs new file mode 100644 index 000000000..8886dc240 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/CompiledShaderPass.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Stores all compiled stages and state for one shader pass. +/// +[StableTypeID("6a66aac0-d44d-5d90-a801-d92605a92c91")] +public sealed class CompiledShaderPass +{ + private readonly ShaderPassDefinition m_definition; + + /// + /// Creates a compiled pass artifact. + /// + /// + /// Stable pass definition. + /// + /// + /// Compiled target stages. + /// + /// + /// Pass-local manifest binding contract. + /// + public CompiledShaderPass( + ShaderPassDefinition definition, + IReadOnlyList stages, + ShaderInterface shaderInterface + ) { + ArgumentNullException.ThrowIfNull(stages); + ArgumentNullException.ThrowIfNull(shaderInterface); + definition.metadata = definition.metadata?.ToArray() ?? []; + m_definition = definition; + this.stages = Array.AsReadOnly(stages.ToArray()); + this.shaderInterface = shaderInterface; + } + + /// + /// Gets the stable pass definition. + /// + public ShaderPassDefinition definition + { + get + { + ShaderPassDefinition value = m_definition; + value.metadata = value.metadata.ToArray(); + return value; + } + } + + /// + /// Gets compiled target stages. + /// + public IReadOnlyList stages { get; } + + /// + /// Gets the pass-local manifest binding contract. + /// + public ShaderInterface shaderInterface { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/IShaderCompilerToolchain.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/IShaderCompilerToolchain.cs new file mode 100644 index 000000000..fe00c6e18 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/IShaderCompilerToolchain.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Defines a backend-owned target compiler used by the common Shader IR pipeline. +/// +[StableTypeID("00437bae-b212-505f-8017-d59fd29fb005")] +public interface IShaderCompilerToolchain +{ + /// + /// Gets the stable source implementation identity paired with this rendering adapter. + /// + string implementationID { get; } + + /// + /// Gets the explicit source-language identities accepted by this adapter's typed IR generator. + /// + IReadOnlyList supportedSourceLanguages { get; } + + /// + /// Generates and compiles one typed stage, including its frozen function modules and resource layout. + /// + /// + /// Typed stage and exact target profile. + /// + /// + /// Cancellation before publishing the candidate. + /// + /// + /// Immutable compiled bytes, generated binding names and structured diagnostics. + /// + ValueTask CompileAsync( + ShaderStageToolRequest request, + CancellationToken cancellationToken + ); + + /// + /// Creates a target supported by this toolchain and capability snapshot. + /// + /// + /// Target renderer capabilities. + /// + /// + /// Whether release optimization is enabled. + /// + /// + /// Whether compiler debug information is emitted. + /// + /// + /// A stable target description accepted by this toolchain. + /// + ShaderCompileTarget CreateTarget( + GraphicsCapabilities capabilities, + bool optimize = true, + bool debugInformation = false + ); +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ITextureTargetCompiler.cs similarity index 96% rename from src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs rename to src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ITextureTargetCompiler.cs index 68062ed77..44cf9c516 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/TextureTargetCompiler.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ITextureTargetCompiler.cs @@ -3,8 +3,6 @@ using System.Threading; using System.Threading.Tasks; using Inno.Extensibility.Types; -using Inno.Rendering; -using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderArtifactSelection.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderArtifactSelection.cs new file mode 100644 index 000000000..37d8773ea --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderArtifactSelection.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Describes the artifact selected after evaluating a candidate compilation. +/// +[StableTypeID("2cbb2378-91ef-5c66-866e-e651e80a79a7")] +public sealed class ShaderArtifactSelection +{ + /// + /// Creates an artifact selection result. + /// + /// + /// Selected candidate or last-good artifact. + /// + /// + /// Whether the candidate replaced active state. + /// + /// + /// Whether a previous artifact was preserved. + /// + /// + /// Candidate diagnostics. + /// + public ShaderArtifactSelection( + CompiledShaderArtifact? artifact, + bool candidateSucceeded, + bool usingLastGood, + IReadOnlyList diagnostics + ) { + ArgumentNullException.ThrowIfNull(diagnostics); + this.artifact = artifact; + this.candidateSucceeded = candidateSucceeded; + this.usingLastGood = usingLastGood; + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets the selected candidate or last-good artifact. + /// + public CompiledShaderArtifact? artifact { get; } + + /// + /// Gets whether the candidate replaced active state. + /// + public bool candidateSucceeded { get; } + + /// + /// Gets whether a previous artifact was preserved. + /// + public bool usingLastGood { get; } + + /// + /// Gets candidate diagnostics. + /// + public IReadOnlyList diagnostics { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs deleted file mode 100644 index fd0512ea9..000000000 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilation.cs +++ /dev/null @@ -1,453 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Inno.Core.Diagnostics; -using Inno.Extensibility.Types; -using Inno.Rendering; -using Inno.Rendering.Assets; - -namespace Inno.Rendering.Assets.Authoring; - -/// -/// Selects one renderer profile and compilation policy. -/// -[StableTypeID("29e9c0f0-cb34-5b98-a6d6-356f744f3049")] -public sealed class ShaderCompileTarget -{ - /// - /// Creates a shader compilation target. - /// - /// - /// Backend compiler-owned stable profile key. - /// - /// - /// Target renderer capabilities. - /// - /// - /// Whether release optimization is enabled. - /// - /// - /// Whether shader debug information is emitted. - /// - public ShaderCompileTarget( - string profileKey, - GraphicsCapabilities capabilities, - bool optimize = true, - bool debugInformation = false - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(profileKey); - ArgumentNullException.ThrowIfNull(capabilities); - this.profileKey = profileKey; - this.capabilities = capabilities; - this.optimize = optimize; - this.debugInformation = debugInformation; - } - - /// - /// Gets the backend compiler-owned stable profile key. - /// - public string profileKey { get; } - - /// - /// Gets target renderer capabilities. - /// - public GraphicsCapabilities capabilities { get; } - - /// - /// Gets whether release optimization is enabled. - /// - public bool optimize { get; } - - /// - /// Gets whether shader debug information is emitted. - /// - public bool debugInformation { get; } - - /// - /// Gets a stable target cache-key fragment. - /// - public string key => $"{profileKey}:opt={optimize}:debug={debugInformation}"; -} - -/// -/// Stores one immutable target stage binary. -/// -[StableTypeID("7de46626-7dd7-5112-b098-ef3eb53a0cda")] -public sealed class ShaderStageArtifact -{ - private readonly byte[] m_bytes; - - /// - /// Creates a stage artifact. - /// - /// - /// Single compiled shader stage. - /// - /// - /// Target binary bytes. - /// - /// - /// Original source mapping. - /// - public ShaderStageArtifact( - ShaderStage stage, - ReadOnlySpan bytes, - ShaderSourceLocation sourceLocation - ) { - if (bytes.IsEmpty) - { - throw new ArgumentException("A compiled shader stage cannot be empty.", nameof(bytes)); - } - - this.stage = stage; - m_bytes = bytes.ToArray(); - this.sourceLocation = sourceLocation; - } - - /// - /// Gets the compiled shader stage. - /// - public ShaderStage stage { get; } - - /// - /// Gets immutable target binary bytes. - /// - public ReadOnlyMemory bytes => m_bytes; - - /// - /// Gets the original source mapping. - /// - public ShaderSourceLocation sourceLocation { get; } -} - -/// -/// Stores all compiled stages and state for one shader pass. -/// -[StableTypeID("6a66aac0-d44d-5d90-a801-d92605a92c91")] -public sealed class CompiledShaderPass -{ - private readonly ShaderPassDefinition m_definition; - - /// - /// Creates a compiled pass artifact. - /// - /// - /// Stable pass definition. - /// - /// - /// Compiled target stages. - /// - /// - /// Pass-local manifest binding contract. - /// - public CompiledShaderPass( - ShaderPassDefinition definition, - IReadOnlyList stages, - ShaderInterface shaderInterface - ) { - ArgumentNullException.ThrowIfNull(stages); - ArgumentNullException.ThrowIfNull(shaderInterface); - definition.metadata = definition.metadata?.ToArray() ?? []; - m_definition = definition; - this.stages = Array.AsReadOnly(stages.ToArray()); - this.shaderInterface = shaderInterface; - } - - /// - /// Gets the stable pass definition. - /// - public ShaderPassDefinition definition - { - get - { - ShaderPassDefinition value = m_definition; - value.metadata = value.metadata.ToArray(); - return value; - } - } - - /// - /// Gets compiled target stages. - /// - public IReadOnlyList stages { get; } - - /// - /// Gets the pass-local manifest binding contract. - /// - public ShaderInterface shaderInterface { get; } -} - -/// -/// Contains an immutable target shader artifact and expected reflected interface. -/// -[StableTypeID("25e556fe-a071-58b2-8e70-0e41bd434d83")] -public sealed class CompiledShaderArtifact -{ - private readonly byte[] m_definitionData; - - /// - /// Creates a compiled shader artifact. - /// - /// - /// Artist-facing shader name. - /// - /// - /// Stable target cache key. - /// - /// - /// Static keyword variant. - /// - /// - /// Manifest-derived binding contract. - /// - /// - /// Compiled pass binaries. - /// - /// - /// Native-serialized runtime definition captured before asynchronous compilation. - /// - public CompiledShaderArtifact( - string shaderName, - string targetKey, - RenderShaderVariant variant, - ShaderInterface shaderInterface, - IReadOnlyList passes, - ReadOnlySpan definitionData - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(shaderName); - ArgumentException.ThrowIfNullOrWhiteSpace(targetKey); - ArgumentNullException.ThrowIfNull(shaderInterface); - ArgumentNullException.ThrowIfNull(passes); - this.shaderName = shaderName; - this.targetKey = targetKey; - this.variant = variant; - this.shaderInterface = shaderInterface; - this.passes = Array.AsReadOnly(passes.ToArray()); - if (definitionData.IsEmpty) - { - throw new ArgumentException("Compiled programs require a captured runtime contract.", nameof(definitionData)); - } - m_definitionData = definitionData.ToArray(); - } - - /// - /// Gets the artist-facing shader name. - /// - public string shaderName { get; } - - /// - /// Gets the stable target cache key. - /// - public string targetKey { get; } - - /// - /// Gets the static keyword variant. - /// - public RenderShaderVariant variant { get; } - - /// - /// Gets the manifest-derived binding contract. - /// - public ShaderInterface shaderInterface { get; } - - /// - /// Gets compiled pass binaries. - /// - public IReadOnlyList passes { get; } - - /// - /// Creates the source-free deployment artifact consumed by Editor preview sessions and Players. - /// - /// - /// A deep immutable runtime artifact containing only target binaries, fixed-function state, and binding contracts. - /// - public RenderShaderArtifact CreateRuntimeArtifact() - => new( - shaderName, - targetKey, - variant, - shaderInterface, - passes.Select(static pass => new RenderShaderPassArtifact( - pass.definition.name, - pass.definition.programKind, - ConvertRasterState(pass.definition.renderState), - pass.shaderInterface, - pass.stages.Select(static stage => new RenderShaderStageArtifact( - stage.stage, - stage.bytes.Span - )).ToArray() - )).ToArray(), - m_definitionData - ); - - private static RenderRasterState ConvertRasterState(ShaderRenderState source) - => new() - { - topology = source.topology, - cull = source.cull switch - { - ShaderCullMode.None => RenderCullMode.None, - ShaderCullMode.Front => RenderCullMode.Front, - ShaderCullMode.Back => RenderCullMode.Back, - _ => throw new ArgumentOutOfRangeException(nameof(source)) - }, - frontFace = source.frontFace, - depthCompare = source.depthCompare switch - { - ShaderCompareFunction.Never => RenderDepthCompare.Never, - ShaderCompareFunction.Less => RenderDepthCompare.Less, - ShaderCompareFunction.Equal => RenderDepthCompare.Equal, - ShaderCompareFunction.LessEqual => RenderDepthCompare.LessEqual, - ShaderCompareFunction.Greater => RenderDepthCompare.Greater, - ShaderCompareFunction.NotEqual => RenderDepthCompare.NotEqual, - ShaderCompareFunction.GreaterEqual => RenderDepthCompare.GreaterEqual, - ShaderCompareFunction.Always => RenderDepthCompare.Always, - _ => throw new ArgumentOutOfRangeException(nameof(source)) - }, - depthWrite = source.depthWrite, - blend = source.blend, - colorWriteMask = source.colorWriteMask, - multisampling = source.multisampling - }; -} - -/// -/// Returns a candidate artifact and structured diagnostics without mutating active state. -/// -[StableTypeID("72b304de-8a2b-5c08-b899-b4aef05be149")] -public sealed class ShaderCompilationResult -{ - /// - /// Creates a shader compilation result. - /// - /// - /// Candidate artifact, or after failure. - /// - /// - /// Validation and compiler diagnostics. - /// - public ShaderCompilationResult( - CompiledShaderArtifact? artifact, - IReadOnlyList diagnostics - ) { - ArgumentNullException.ThrowIfNull(diagnostics); - this.artifact = artifact; - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - - /// - /// Gets the candidate artifact, or after failure. - /// - public CompiledShaderArtifact? artifact { get; } - - /// - /// Gets validation and compiler diagnostics. - /// - public IReadOnlyList diagnostics { get; } - - /// - /// Gets whether a complete candidate artifact was produced. - /// - public bool succeeded - => artifact is not null - && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); -} - -/// -/// Defines a backend-owned target compiler used by the common Shader IR pipeline. -/// -[StableTypeID("00437bae-b212-505f-8017-d59fd29fb005")] -public interface IShaderCompilerToolchain -{ - /// - /// Gets the stable source implementation identity paired with this rendering adapter. - /// - string implementationID { get; } - - /// - /// Gets the explicit source-language identities accepted by this adapter's typed IR generator. - /// - IReadOnlyList supportedSourceLanguages { get; } - - /// - /// Generates and compiles one typed stage, including its frozen function modules and resource layout. - /// - /// - /// Typed stage and exact target profile. - /// - /// - /// Cancellation before publishing the candidate. - /// - /// - /// Immutable compiled bytes, generated binding names and structured diagnostics. - /// - ValueTask CompileAsync( - ShaderStageToolRequest request, - CancellationToken cancellationToken - ); - - /// - /// Creates a target supported by this toolchain and capability snapshot. - /// - /// - /// Target renderer capabilities. - /// - /// - /// Whether release optimization is enabled. - /// - /// - /// Whether compiler debug information is emitted. - /// - /// - /// A stable target description accepted by this toolchain. - /// - ShaderCompileTarget CreateTarget( - GraphicsCapabilities capabilities, - bool optimize = true, - bool debugInformation = false - ); -} - -/// -/// Compiles validated Shader IR through one target toolchain. -/// -[StableTypeID("85c9086c-63d5-51e6-82ec-548ad39702e2")] -public sealed partial class ShaderCompiler -{ - private readonly IShaderCompilerToolchain m_toolchain; - - /// - /// Creates a common IR compiler with one backend-owned target toolchain. - /// - /// - /// Backend compiler implementation. - /// - public ShaderCompiler(IShaderCompilerToolchain toolchain) - { - ArgumentNullException.ThrowIfNull(toolchain); - m_toolchain = toolchain; - } - - /// - /// Creates a target supported by the configured backend compiler. - /// - /// - /// Target renderer capabilities. - /// - /// - /// Whether release optimization is enabled. - /// - /// - /// Whether compiler debug information is emitted. - /// - /// - /// A stable target description accepted by this compiler. - /// - public ShaderCompileTarget CreateTarget( - GraphicsCapabilities capabilities, - bool optimize = true, - bool debugInformation = false - ) => m_toolchain.CreateTarget(capabilities, optimize, debugInformation); -} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilationResult.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilationResult.cs new file mode 100644 index 000000000..6117fcc80 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompilationResult.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Returns a candidate artifact and structured diagnostics without mutating active state. +/// +[StableTypeID("72b304de-8a2b-5c08-b899-b4aef05be149")] +public sealed class ShaderCompilationResult +{ + /// + /// Creates a shader compilation result. + /// + /// + /// Candidate artifact, or after failure. + /// + /// + /// Validation and compiler diagnostics. + /// + public ShaderCompilationResult( + CompiledShaderArtifact? artifact, + IReadOnlyList diagnostics + ) { + ArgumentNullException.ThrowIfNull(diagnostics); + this.artifact = artifact; + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets the candidate artifact, or after failure. + /// + public CompiledShaderArtifact? artifact { get; } + + /// + /// Gets validation and compiler diagnostics. + /// + public IReadOnlyList diagnostics { get; } + + /// + /// Gets whether a complete candidate artifact was produced. + /// + public bool succeeded + => artifact is not null + && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompileTarget.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompileTarget.cs new file mode 100644 index 000000000..3cee16c93 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompileTarget.cs @@ -0,0 +1,65 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Selects one renderer profile and compilation policy. +/// +[StableTypeID("29e9c0f0-cb34-5b98-a6d6-356f744f3049")] +public sealed class ShaderCompileTarget +{ + /// + /// Creates a shader compilation target. + /// + /// + /// Backend compiler-owned stable profile key. + /// + /// + /// Target renderer capabilities. + /// + /// + /// Whether release optimization is enabled. + /// + /// + /// Whether shader debug information is emitted. + /// + public ShaderCompileTarget( + string profileKey, + GraphicsCapabilities capabilities, + bool optimize = true, + bool debugInformation = false + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(profileKey); + ArgumentNullException.ThrowIfNull(capabilities); + this.profileKey = profileKey; + this.capabilities = capabilities; + this.optimize = optimize; + this.debugInformation = debugInformation; + } + + /// + /// Gets the backend compiler-owned stable profile key. + /// + public string profileKey { get; } + + /// + /// Gets target renderer capabilities. + /// + public GraphicsCapabilities capabilities { get; } + + /// + /// Gets whether release optimization is enabled. + /// + public bool optimize { get; } + + /// + /// Gets whether shader debug information is emitted. + /// + public bool debugInformation { get; } + + /// + /// Gets a stable target cache-key fragment. + /// + public string key => $"{profileKey}:opt={optimize}:debug={debugInformation}"; +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Graph.cs similarity index 99% rename from src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs rename to src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Graph.cs index cb2eade1b..b5cf3e683 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphCompilation.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Graph.cs @@ -7,8 +7,6 @@ using Inno.Core.Diagnostics; using Inno.Core.Serialization; using Inno.Extensibility.Types; -using Inno.Rendering; -using Inno.Rendering.Assets; using Inno.Rendering.Shaders; namespace Inno.Rendering.Assets.Authoring; diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Stage.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Stage.cs new file mode 100644 index 000000000..36f60c9dc --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.Stage.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Inno.Rendering.Shaders; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Carries validated inputs and outputs for one shader compilation stage. +/// +public sealed partial class ShaderCompiler +{ + private readonly object m_stageCacheLock = new(); + private readonly Dictionary<(string stage, string target, GraphicsCapabilities capabilities), ShaderStageToolResult> m_stageCache = []; + private long m_stageCacheBytes; + + /// + /// Compiles a typed stage through the configured adapter without an intermediate complete-source authoring asset. + /// + /// + /// Typed stage and frozen function modules. + /// + /// + /// Configured target capability/profile snapshot. + /// + /// + /// Cancellation before publishing the candidate. + /// + /// + /// Compiled stage bytes, exact generated binding names and structured diagnostics. + /// + public async ValueTask CompileAsync( + ShaderIrStage stage, + ShaderCompileTarget target, + CancellationToken cancellationToken = default + ) { + ArgumentNullException.ThrowIfNull(stage); + ArgumentNullException.ThrowIfNull(target); + cancellationToken.ThrowIfCancellationRequested(); + (string contentHash, string key, GraphicsCapabilities capabilities) key = (stage.contentHash, target.key, target.capabilities); + lock (m_stageCacheLock) + { + if (m_stageCache.TryGetValue(key, out ShaderStageToolResult? previous)) + { + return previous; + } + } + ShaderStageToolResult result = await m_toolchain.CompileAsync( + new ShaderStageToolRequest(stage, target), + cancellationToken + ).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + // The bounded cache contains immutable backend results only, never IR, providers or source assets. + // Failed and cancelled requests are not cached, and layout-only graph edits reuse the semantic key. + if (result.succeeded && result.bytes.Length <= 32 * 1024 * 1024) + { + lock (m_stageCacheLock) + { + if (m_stageCache.Count >= 256 || m_stageCacheBytes + result.bytes.Length > 32 * 1024 * 1024) + { + m_stageCache.Clear(); + m_stageCacheBytes = 0; + } + if (m_stageCache.TryAdd(key, result)) + { + m_stageCacheBytes += result.bytes.Length; + } + } + } + return result; + } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.cs new file mode 100644 index 000000000..ec81bb505 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderCompiler.cs @@ -0,0 +1,46 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Compiles validated Shader IR through one target toolchain. +/// +[StableTypeID("85c9086c-63d5-51e6-82ec-548ad39702e2")] +public sealed partial class ShaderCompiler +{ + private readonly IShaderCompilerToolchain m_toolchain; + + /// + /// Creates a common IR compiler with one backend-owned target toolchain. + /// + /// + /// Backend compiler implementation. + /// + public ShaderCompiler(IShaderCompilerToolchain toolchain) + { + ArgumentNullException.ThrowIfNull(toolchain); + m_toolchain = toolchain; + } + + /// + /// Creates a target supported by the configured backend compiler. + /// + /// + /// Target renderer capabilities. + /// + /// + /// Whether release optimization is enabled. + /// + /// + /// Whether compiler debug information is emitted. + /// + /// + /// A stable target description accepted by this compiler. + /// + public ShaderCompileTarget CreateTarget( + GraphicsCapabilities capabilities, + bool optimize = true, + bool debugInformation = false + ) => m_toolchain.CreateTarget(capabilities, optimize, debugInformation); +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs index fb0d31f0a..24cce1508 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderLastGoodStore.cs @@ -1,67 +1,9 @@ using System; using System.Collections.Generic; -using System.Linq; using Inno.Extensibility.Types; -using Inno.Rendering; -using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; -/// -/// Describes the artifact selected after evaluating a candidate compilation. -/// -[StableTypeID("2cbb2378-91ef-5c66-866e-e651e80a79a7")] -public sealed class ShaderArtifactSelection -{ - /// - /// Creates an artifact selection result. - /// - /// - /// Selected candidate or last-good artifact. - /// - /// - /// Whether the candidate replaced active state. - /// - /// - /// Whether a previous artifact was preserved. - /// - /// - /// Candidate diagnostics. - /// - public ShaderArtifactSelection( - CompiledShaderArtifact? artifact, - bool candidateSucceeded, - bool usingLastGood, - IReadOnlyList diagnostics - ) { - ArgumentNullException.ThrowIfNull(diagnostics); - this.artifact = artifact; - this.candidateSucceeded = candidateSucceeded; - this.usingLastGood = usingLastGood; - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - - /// - /// Gets the selected candidate or last-good artifact. - /// - public CompiledShaderArtifact? artifact { get; } - - /// - /// Gets whether the candidate replaced active state. - /// - public bool candidateSucceeded { get; } - - /// - /// Gets whether a previous artifact was preserved. - /// - public bool usingLastGood { get; } - - /// - /// Gets candidate diagnostics. - /// - public IReadOnlyList diagnostics { get; } -} - /// /// Atomically preserves last-good CPU shader artifacts by asset, target and variant. /// diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageArtifact.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageArtifact.cs new file mode 100644 index 000000000..f3632c902 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageArtifact.cs @@ -0,0 +1,55 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Stores one immutable target stage binary. +/// +[StableTypeID("7de46626-7dd7-5112-b098-ef3eb53a0cda")] +public sealed class ShaderStageArtifact +{ + private readonly byte[] m_bytes; + + /// + /// Creates a stage artifact. + /// + /// + /// Single compiled shader stage. + /// + /// + /// Target binary bytes. + /// + /// + /// Original source mapping. + /// + public ShaderStageArtifact( + ShaderStage stage, + ReadOnlySpan bytes, + ShaderSourceLocation sourceLocation + ) { + if (bytes.IsEmpty) + { + throw new ArgumentException("A compiled shader stage cannot be empty.", nameof(bytes)); + } + + this.stage = stage; + m_bytes = bytes.ToArray(); + this.sourceLocation = sourceLocation; + } + + /// + /// Gets the compiled shader stage. + /// + public ShaderStage stage { get; } + + /// + /// Gets immutable target binary bytes. + /// + public ReadOnlyMemory bytes => m_bytes; + + /// + /// Gets the original source mapping. + /// + public ShaderSourceLocation sourceLocation { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageBinding.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageBinding.cs new file mode 100644 index 000000000..c424801ed --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageBinding.cs @@ -0,0 +1,22 @@ +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Maps one logical binding to the adapter-generated native name, without exposing a GPU handle. +/// +/// +/// Stable logical binding identity from the typed stage. +/// +/// +/// Generated name used for reflection and runtime uniform binding. +/// +/// +/// Assigned texture slot; uniform locations are resolved by the runtime. +/// +[StableTypeID("00dff34d-f800-51e6-8a37-0141761958c8")] +public sealed record ShaderStageBinding( + string id, + string nativeName, + int location +); diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs deleted file mode 100644 index 72b2317ba..000000000 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageCompilation.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Inno.Core.Diagnostics; -using Inno.Extensibility.Types; -using Inno.Rendering; -using Inno.Rendering.Shaders; - -namespace Inno.Rendering.Assets.Authoring; - -/// -/// Supplies typed stage semantics and frozen source modules to a target compiler. -/// -/// -/// Typed stage with target-assigned interface/resource locations. -/// -/// -/// Exact toolchain profile and capability snapshot. -/// -[StableTypeID("8a37ee08-a048-52fc-bbf4-bbc47fe425d4")] -public sealed record ShaderStageToolRequest( - ShaderIrStage stage, - ShaderCompileTarget target -); - -/// -/// Maps one logical binding to the adapter-generated native name, without exposing a GPU handle. -/// -/// -/// Stable logical binding identity from the typed stage. -/// -/// -/// Generated name used for reflection and runtime uniform binding. -/// -/// -/// Assigned texture slot; uniform locations are resolved by the runtime. -/// -[StableTypeID("00dff34d-f800-51e6-8a37-0141761958c8")] -public sealed record ShaderStageBinding( - string id, - string nativeName, - int location -); - -/// -/// Returns a frozen typed-stage compilation candidate; failure never carries a usable artifact. -/// -[StableTypeID("cf544248-8a38-5999-b8aa-bbdcf94fa6e8")] -public sealed class ShaderStageToolResult -{ - private readonly byte[] m_bytes; - - /// - /// Creates a candidate result from adapter-owned generation, compilation and diagnostics. - /// - /// - /// Compiled binary, or empty after failure. - /// - /// - /// Logical-to-native resource layout used by this exact binary. - /// - /// - /// Structured adapter diagnostics with original source positions. - /// - public ShaderStageToolResult( - ReadOnlySpan bytes, - IEnumerable bindings, - IEnumerable diagnostics - ) { - ArgumentNullException.ThrowIfNull(bindings); - ArgumentNullException.ThrowIfNull(diagnostics); - this.bindings = Array.AsReadOnly(bindings.ToArray()); - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - if (!bytes.IsEmpty && this.diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) - { - throw new ArgumentException("A failed candidate cannot publish compiled bytes.", nameof(bytes)); - } - m_bytes = bytes.ToArray(); - } - - /// - /// Gets immutable target binary data, empty on failure. - /// - public ReadOnlyMemory bytes => m_bytes; - - /// - /// Gets the exact generated logical-to-native resource layout. - /// - public IReadOnlyList bindings { get; } - - /// - /// Gets generation and native compiler diagnostics. - /// - public IReadOnlyList diagnostics { get; } - - /// - /// Gets whether a nonempty binary was compiled without error diagnostics. - /// - public bool succeeded => !bytes.IsEmpty && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); -} - -/// -/// Carries validated inputs and outputs for one shader compilation stage. -/// -public sealed partial class ShaderCompiler -{ - private readonly object m_stageCacheLock = new(); - private readonly Dictionary<(string stage, string target, GraphicsCapabilities capabilities), ShaderStageToolResult> m_stageCache = []; - private long m_stageCacheBytes; - - /// - /// Compiles a typed stage through the configured adapter without an intermediate complete-source authoring asset. - /// - /// - /// Typed stage and frozen function modules. - /// - /// - /// Configured target capability/profile snapshot. - /// - /// - /// Cancellation before publishing the candidate. - /// - /// - /// Compiled stage bytes, exact generated binding names and structured diagnostics. - /// - public async ValueTask CompileAsync( - ShaderIrStage stage, - ShaderCompileTarget target, - CancellationToken cancellationToken = default - ) { - ArgumentNullException.ThrowIfNull(stage); - ArgumentNullException.ThrowIfNull(target); - cancellationToken.ThrowIfCancellationRequested(); - (string contentHash, string key, GraphicsCapabilities capabilities) key = (stage.contentHash, target.key, target.capabilities); - lock (m_stageCacheLock) - { - if (m_stageCache.TryGetValue(key, out ShaderStageToolResult? previous)) - { - return previous; - } - } - ShaderStageToolResult result = await m_toolchain.CompileAsync( - new ShaderStageToolRequest(stage, target), - cancellationToken - ).ConfigureAwait(false); - cancellationToken.ThrowIfCancellationRequested(); - // The bounded cache contains immutable backend results only, never IR, providers or source assets. - // Failed and cancelled requests are not cached, and layout-only graph edits reuse the semantic key. - if (result.succeeded && result.bytes.Length <= 32 * 1024 * 1024) - { - lock (m_stageCacheLock) - { - if (m_stageCache.Count >= 256 || m_stageCacheBytes + result.bytes.Length > 32 * 1024 * 1024) - { - m_stageCache.Clear(); - m_stageCacheBytes = 0; - } - if (m_stageCache.TryAdd(key, result)) - { - m_stageCacheBytes += result.bytes.Length; - } - } - } - return result; - } -} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolRequest.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolRequest.cs new file mode 100644 index 000000000..61e31bf37 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolRequest.cs @@ -0,0 +1,19 @@ +using Inno.Extensibility.Types; +using Inno.Rendering.Shaders; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Supplies typed stage semantics and frozen source modules to a target compiler. +/// +/// +/// Typed stage with target-assigned interface/resource locations. +/// +/// +/// Exact toolchain profile and capability snapshot. +/// +[StableTypeID("8a37ee08-a048-52fc-bbf4-bbc47fe425d4")] +public sealed record ShaderStageToolRequest( + ShaderIrStage stage, + ShaderCompileTarget target +); diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolResult.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolResult.cs new file mode 100644 index 000000000..fbd884cc6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderStageToolResult.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Diagnostics; +using Inno.Extensibility.Types; +using Inno.Rendering.Shaders; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Returns a frozen typed-stage compilation candidate; failure never carries a usable artifact. +/// +[StableTypeID("cf544248-8a38-5999-b8aa-bbdcf94fa6e8")] +public sealed class ShaderStageToolResult +{ + private readonly byte[] m_bytes; + + /// + /// Creates a candidate result from adapter-owned generation, compilation and diagnostics. + /// + /// + /// Compiled binary, or empty after failure. + /// + /// + /// Logical-to-native resource layout used by this exact binary. + /// + /// + /// Structured adapter diagnostics with original source positions. + /// + public ShaderStageToolResult( + ReadOnlySpan bytes, + IEnumerable bindings, + IEnumerable diagnostics + ) { + ArgumentNullException.ThrowIfNull(bindings); + ArgumentNullException.ThrowIfNull(diagnostics); + this.bindings = Array.AsReadOnly(bindings.ToArray()); + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + if (!bytes.IsEmpty && this.diagnostics.Any(static value => value.severity == DiagnosticSeverity.Error)) + { + throw new ArgumentException("A failed candidate cannot publish compiled bytes.", nameof(bytes)); + } + m_bytes = bytes.ToArray(); + } + + /// + /// Gets immutable target binary data, empty on failure. + /// + public ReadOnlyMemory bytes => m_bytes; + + /// + /// Gets the exact generated logical-to-native resource layout. + /// + public IReadOnlyList bindings { get; } + + /// + /// Gets generation and native compiler diagnostics. + /// + public IReadOnlyList diagnostics { get; } + + /// + /// Gets whether a nonempty binary was compiled without error diagnostics. + /// + public bool succeeded => !bytes.IsEmpty && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceSnapshot.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceSnapshot.cs new file mode 100644 index 000000000..05c07cf1a --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceSnapshot.cs @@ -0,0 +1,38 @@ +using Inno.Core.Graphs; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Assets.Authoring; + +/// +/// Contains detached graph source state, not a compiled or live runtime asset. +/// +[StableTypeID("fb1d9ba2-d37c-59f1-a7ef-17feeb3beb0e")] +public sealed class ShaderGraphSourceSnapshot +{ + private readonly GraphDocument m_document; + + internal ShaderGraphSourceSnapshot( + GraphDocument document, + string hash, + bool readOnly + ) { + m_document = document; + this.contentHash = hash; + this.isReadOnly = readOnly; + } + + /// + /// Gets a detached copy of authored graph records. + /// + public GraphDocument document => m_document.Clone(); + + /// + /// Gets the source fingerprint used to reject external-edit conflicts. + /// + public string contentHash { get; } + + /// + /// Gets whether the source belongs to an immutable installation mount. + /// + public bool isReadOnly { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs index d9758b4e1..2e41aee4c 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Editing/ShaderGraphSourceStore.cs @@ -5,7 +5,6 @@ using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Extensibility.Types; -using Inno.Rendering; namespace Inno.Rendering.Assets.Authoring; @@ -92,37 +91,3 @@ private static void Validate(AssetPath path) } } } - -/// -/// Contains detached graph source state, not a compiled or live runtime asset. -/// -[StableTypeID("fb1d9ba2-d37c-59f1-a7ef-17feeb3beb0e")] -public sealed class ShaderGraphSourceSnapshot -{ - private readonly GraphDocument m_document; - - internal ShaderGraphSourceSnapshot( - GraphDocument document, - string hash, - bool readOnly - ) { - m_document = document; - this.contentHash = hash; - this.isReadOnly = readOnly; - } - - /// - /// Gets a detached copy of authored graph records. - /// - public GraphDocument document => m_document.Clone(); - - /// - /// Gets the source fingerprint used to reject external-edit conflicts. - /// - public string contentHash { get; } - - /// - /// Gets whether the source belongs to an immutable installation mount. - /// - public bool isReadOnly { get; } -} diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Gltf.cs similarity index 99% rename from src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs rename to src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Gltf.cs index 59fbc8d90..a6882ca92 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GltfMeshParser.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Gltf.cs @@ -1,14 +1,10 @@ using System; using System.Buffers.Binary; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Text; using System.Text.Json; using Inno.Core.Mathematics; using Inno.Extensibility.Types; -using Inno.Rendering; -using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ObjMeshParser.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Obj.cs similarity index 99% rename from src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ObjMeshParser.cs rename to src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Obj.cs index cf56fdefd..6b2330c69 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ObjMeshParser.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MeshSourceParser.Obj.cs @@ -3,8 +3,6 @@ using System.Globalization; using System.Linq; using Inno.Core.Mathematics; -using Inno.Rendering; -using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring; diff --git a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs index 37d35ba4a..a6abcf9cb 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Materials/MaterialValue.cs @@ -1,42 +1,9 @@ using System; -using System.Collections.Generic; -using System.Linq; -using Inno.Assets; using Inno.Core.Mathematics; -using Inno.Core.Serialization; using Inno.Extensibility.Types; -using Inno.Rendering; namespace Inno.Rendering.Assets; -/// -/// Identifies the neutral value stored by a material property. -/// -[StableTypeID("a9af9e77-9a97-5f66-82a0-d720ac5604dc")] -public enum MaterialValueKind -{ - /// - /// Scalar floating-point value. - /// - Float, - /// - /// Four-component vector value. - /// - Vector, - /// - /// Linear color value. - /// - Color, - /// - /// Four-by-four matrix value. - /// - Matrix, - /// - /// Texture asset reference. - /// - Texture -} - /// /// Stores one native-serializable material value without a GPU binding. /// @@ -154,3 +121,31 @@ public static MaterialValue FromTexture( ); } } + +/// +/// Identifies the neutral value stored by a material property. +/// +[StableTypeID("a9af9e77-9a97-5f66-82a0-d720ac5604dc")] +public enum MaterialValueKind +{ + /// + /// Scalar floating-point value. + /// + Float, + /// + /// Four-component vector value. + /// + Vector, + /// + /// Linear color value. + /// + Color, + /// + /// Four-by-four matrix value. + /// + Matrix, + /// + /// Texture asset reference. + /// + Texture +} diff --git a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs index f24365f46..a3ba7f061 100644 --- a/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs +++ b/src/services/rendering/Inno.Rendering.Assets/Shaders/ShaderRenderState.cs @@ -1,75 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Inno.Assets; -using Inno.Core.Mathematics; -using Inno.Core.Serialization; using Inno.Extensibility.Types; -using Inno.Rendering; -using Inno.Scripting.Api; namespace Inno.Rendering.Assets; -/// -/// Selects the triangle face rejected by a raster pass. -/// -[StableTypeID("a0efdb24-2746-512d-aef5-46180c539581")] -public enum ShaderCullMode -{ - /// - /// Does not reject either face orientation. - /// - None, - /// - /// Rejects front-facing triangles. - /// - Front, - /// - /// Rejects back-facing triangles. - /// - Back -} - -/// -/// Selects the comparison used by depth testing. -/// -[StableTypeID("cababee4-46b3-5bd8-800f-46d58149959b")] -public enum ShaderCompareFunction -{ - /// - /// Always rejects the fragment. - /// - Never, - /// - /// Accepts a fragment with a smaller depth. - /// - Less, - /// - /// Accepts a fragment with an equal depth. - /// - Equal, - /// - /// Accepts a fragment with a smaller or equal depth. - /// - LessEqual, - /// - /// Accepts a fragment with a greater depth. - /// - Greater, - /// - /// Accepts a fragment with a different depth. - /// - NotEqual, - /// - /// Accepts a fragment with a greater or equal depth. - /// - GreaterEqual, - /// - /// Always accepts the fragment. - /// - Always -} - /// /// Declares backend-neutral fixed-function state for one shader pass. /// @@ -132,3 +64,63 @@ public static ShaderRenderState opaque /// public bool multisampling { get; set; } } + +/// +/// Selects the triangle face rejected by a raster pass. +/// +[StableTypeID("a0efdb24-2746-512d-aef5-46180c539581")] +public enum ShaderCullMode +{ + /// + /// Does not reject either face orientation. + /// + None, + /// + /// Rejects front-facing triangles. + /// + Front, + /// + /// Rejects back-facing triangles. + /// + Back +} + +/// +/// Selects the comparison used by depth testing. +/// +[StableTypeID("cababee4-46b3-5bd8-800f-46d58149959b")] +public enum ShaderCompareFunction +{ + /// + /// Always rejects the fragment. + /// + Never, + /// + /// Accepts a fragment with a smaller depth. + /// + Less, + /// + /// Accepts a fragment with an equal depth. + /// + Equal, + /// + /// Accepts a fragment with a smaller or equal depth. + /// + LessEqual, + /// + /// Accepts a fragment with a greater depth. + /// + Greater, + /// + /// Accepts a fragment with a different depth. + /// + NotEqual, + /// + /// Accepts a fragment with a greater or equal depth. + /// + GreaterEqual, + /// + /// Always accepts the fragment. + /// + Always +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs index 9b2a714f8..95f558929 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettings.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using Inno.Core.Execution; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; @@ -32,82 +28,3 @@ public static RenderPipelineAsset? defaultPipeline /// public static RenderFrameStatistics? frameStatistics => GraphicsSettingsExecutionContext.currentOrNull?.frameStatistics; } - -[StableTypeID("1af0f9ea-f6cf-544c-a2c5-0c3c306c6780")] -internal sealed class GraphicsSettingsState -{ - private readonly object m_sync = new(); - private RenderPipelineAsset? m_defaultPipeline; - private RenderFrameStatistics? m_frameStatistics; - - internal GraphicsSettingsState(GraphicsCapabilities capabilities) - { - ArgumentNullException.ThrowIfNull(capabilities); - this.capabilities = capabilities; - } - - internal GraphicsCapabilities capabilities { get; } - - internal RenderPipelineAsset? defaultPipeline - { - get - { - lock (m_sync) - { - return m_defaultPipeline; - } - } - set - { - lock (m_sync) - { - m_defaultPipeline = value; - } - } - } - - internal RenderFrameStatistics? frameStatistics - { - get - { - lock (m_sync) - { - return m_frameStatistics; - } - } - set - { - lock (m_sync) - { - m_frameStatistics = value; - } - } - } - - internal void Clear() - { - lock (m_sync) - { - m_defaultPipeline = null; - m_frameStatistics = null; - } - } -} - -[StableTypeID("0f145d08-b261-54bf-92aa-5ee6605d819e")] -internal static class GraphicsSettingsExecutionContext -{ - private static readonly ExecutionSlot CURRENT = new("state"); - - internal static GraphicsSettingsState current - => currentOrNull - ?? throw new InvalidOperationException("No rendering runtime is bound to the current execution context."); - - internal static GraphicsSettingsState? currentOrNull => CURRENT.TryGet(out GraphicsSettingsState? state) ? state : null; - - internal static IDisposable Enter(GraphicsSettingsState state) - { - ArgumentNullException.ThrowIfNull(state); - return CURRENT.Enter(state); - } -} diff --git a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsExecutionContext.cs b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsExecutionContext.cs new file mode 100644 index 000000000..483153033 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsExecutionContext.cs @@ -0,0 +1,23 @@ +using System; +using Inno.Core.Execution; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +[StableTypeID("0f145d08-b261-54bf-92aa-5ee6605d819e")] +internal static class GraphicsSettingsExecutionContext +{ + private static readonly ExecutionSlot CURRENT = new("state"); + + internal static GraphicsSettingsState current + => currentOrNull + ?? throw new InvalidOperationException("No rendering runtime is bound to the current execution context."); + + internal static GraphicsSettingsState? currentOrNull => CURRENT.TryGet(out GraphicsSettingsState? state) ? state : null; + + internal static IDisposable Enter(GraphicsSettingsState state) + { + ArgumentNullException.ThrowIfNull(state); + return CURRENT.Enter(state); + } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsState.cs b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsState.cs new file mode 100644 index 000000000..7f9e4b42f --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/GraphicsSettingsState.cs @@ -0,0 +1,66 @@ +using System; +using Inno.Extensibility.Types; +using Inno.Rendering.Assets; + +namespace Inno.Rendering.Runtime; + +[StableTypeID("1af0f9ea-f6cf-544c-a2c5-0c3c306c6780")] +internal sealed class GraphicsSettingsState +{ + private readonly object m_sync = new(); + private RenderPipelineAsset? m_defaultPipeline; + private RenderFrameStatistics? m_frameStatistics; + + internal GraphicsSettingsState(GraphicsCapabilities capabilities) + { + ArgumentNullException.ThrowIfNull(capabilities); + this.capabilities = capabilities; + } + + internal GraphicsCapabilities capabilities { get; } + + internal RenderPipelineAsset? defaultPipeline + { + get + { + lock (m_sync) + { + return m_defaultPipeline; + } + } + set + { + lock (m_sync) + { + m_defaultPipeline = value; + } + } + } + + internal RenderFrameStatistics? frameStatistics + { + get + { + lock (m_sync) + { + return m_frameStatistics; + } + } + set + { + lock (m_sync) + { + m_frameStatistics = value; + } + } + } + + internal void Clear() + { + lock (m_sync) + { + m_defaultPipeline = null; + m_frameStatistics = null; + } + } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IPreparedViewDrawable.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IPreparedViewDrawable.cs new file mode 100644 index 000000000..fb89e7412 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IPreparedViewDrawable.cs @@ -0,0 +1,18 @@ +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Encodes a resource-ready draw into the owning model's scene pass. +/// +[StableTypeID("d17ebef7-c2f5-543e-ad05-c38c6396ac3b")] +public interface IPreparedViewDrawable +{ + /// + /// Encodes commands while the owning model controls attachments and view state. + /// + /// + /// Backend-neutral scene pass encoder. + /// + void Encode(RenderCommandEncoder commands); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentCollector.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentCollector.cs new file mode 100644 index 000000000..e7cac1ec2 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentCollector.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Collects all active world-content sources for one exact view. +/// +[StableTypeID("b8d46505-dda2-52b6-b3c8-133e48641fed")] +public interface IViewContentCollector +{ + /// + /// Collects active source items in deterministic source order. + /// + /// + /// Frame-scoped host content and view. + /// + /// + /// Frame-local items; the caller owns their sort and composition. + /// + IReadOnlyList Collect(ViewContentContext context); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentFrameSource.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentFrameSource.cs new file mode 100644 index 000000000..4dcb388e3 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentFrameSource.cs @@ -0,0 +1,18 @@ +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Completes frame-local input after every output has routed its views. +/// +[StableTypeID("9242bf1f-a6dc-555f-ab73-494c7a7acc70")] +public interface IViewContentFrameSource +{ + /// + /// Advances retained content once after all output views have supplied input. + /// + /// + /// The shared render frame whose input routing has completed. + /// + void CompleteFrame(ulong frameIndex); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSink.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSink.cs new file mode 100644 index 000000000..7692b628b --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSink.cs @@ -0,0 +1,18 @@ +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Receives world items without imposing a rendering-model sort key. +/// +[StableTypeID("ee4aa3b7-c773-5f05-9655-5a3cfd457c26")] +public interface IViewContentSink +{ + /// + /// Adds an item to the current view. + /// + /// + /// Frame-local content item. + /// + void Submit(ViewContentItem item); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSource.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSource.cs new file mode 100644 index 000000000..c6ecd62dd --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewContentSource.cs @@ -0,0 +1,25 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Contributes model-independent world items to selected views. +/// +[StableTypeID("638698ee-7dd9-5d75-92aa-84a2457ed3f0")] +public interface IViewContentSource : IDisposable +{ + /// + /// Collects items for one exact view. + /// + /// + /// Frame-scoped host content and view. + /// + /// + /// Collector receiving items. + /// + void Collect( + ViewContentContext context, + IViewContentSink sink + ); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewDrawable.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewDrawable.cs new file mode 100644 index 000000000..587965189 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewDrawable.cs @@ -0,0 +1,31 @@ +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Prepares one model-independent drawable for a specific render pass. +/// +[StableTypeID("796c6186-c301-5cb2-a634-d03f8156a039")] +public interface IViewDrawable +{ + /// + /// Resolves reusable resources before render graph execution. + /// + /// + /// Active pipeline build context. + /// + /// + /// View that will draw this item. + /// + /// + /// Prepared frame-local draw when resources are available. + /// + /// + /// Whether the drawable is ready for this pass. + /// + bool TryPrepare( + RenderPipelineContext context, + RenderView view, + out IPreparedViewDrawable? prepared + ); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/IViewPointerTarget.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewPointerTarget.cs new file mode 100644 index 000000000..d29ef4b9c --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/IViewPointerTarget.cs @@ -0,0 +1,69 @@ +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Receives pointer input after the rendering model resolves visible draw order. +/// +[StableTypeID("8d770d54-025c-591a-b49e-9c12c4bde162")] +public interface IViewPointerTarget +{ + /// + /// Gets whether this target retains pointer ownership from an earlier press. + /// Rendering models route captured input before ordinary hit testing. + /// + bool hasPointerCapture { get; } + + /// + /// Gets whether keyboard and text input should continue reaching this target. + /// + bool hasKeyboardFocus { get; } + + /// + /// Changes keyboard focus after the rendering model resolves a pointer press. + /// + /// + /// Whether this target owns subsequent keyboard input. + /// + void SetKeyboardFocus(bool focused); + + /// + /// Maps one output pointer onto this item's local surface. + /// + /// + /// Exact rendered view. + /// + /// + /// Viewport-local input. + /// + /// + /// Local target coordinates when hit. + /// + /// + /// Whether this target is eligible to receive pointer input. + /// + bool TryHit( + RenderView view, + RenderOutputInput input, + out Vector2 localPosition + ); + + /// + /// Advances this target once for the frame with either routed input or an empty snapshot. + /// + /// + /// Routed viewport-local input, or an empty snapshot. + /// + /// + /// Target-local pointer coordinates. + /// + /// + /// Shared output frame index. + /// + void Advance( + RenderOutputInput input, + Vector2 localPosition, + ulong frameIndex + ); +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/RenderView.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderView.cs new file mode 100644 index 000000000..a07192d7b --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/RenderView.cs @@ -0,0 +1,70 @@ +using System; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Describes one backend-neutral view produced by a rendering model. +/// +[StableTypeID("eb2ef876-46a8-5155-8c45-c96b14ad2043")] +public readonly record struct RenderView +{ + /// + /// Creates the exact view used to render content into a viewport. + /// + /// + /// Stable identity within the current output session. + /// + /// + /// Destination pixel rectangle. + /// + /// + /// World-to-view transform. + /// + /// + /// View-to-clip transform. + /// + /// + /// Model-defined visible content bits. + /// + public RenderView( + string id, + RenderViewport viewport, + Matrix viewMatrix, + Matrix projectionMatrix, + ulong visibilityMask = ulong.MaxValue + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + this.viewport = viewport; + this.viewMatrix = viewMatrix; + this.projectionMatrix = projectionMatrix; + this.visibilityMask = visibilityMask; + } + + /// + /// Gets the view identity within its output session. + /// + public string id { get; } + + /// + /// Gets the destination pixel rectangle. + /// + public RenderViewport viewport { get; } + + /// + /// Gets the world-to-view transform. + /// + public Matrix viewMatrix { get; } + + /// + /// Gets the view-to-clip transform. + /// + public Matrix projectionMatrix { get; } + + /// + /// Gets the model-defined visible content bits. + /// + public ulong visibilityMask { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/SelectedViewContentCollector.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/SelectedViewContentCollector.cs new file mode 100644 index 000000000..385ada4ae --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/SelectedViewContentCollector.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Restricts a neutral world-content collector to an output layer's source IDs. +/// +[StableTypeID("f4217ba1-0650-58be-8e76-d6f2c2c303c5")] +public sealed class SelectedViewContentCollector : IViewContentCollector +{ + private readonly IViewContentCollector m_inner; + private readonly IReadOnlyList m_sourceIDs; + + /// + /// Creates a collector that forwards only the selected source identities. + /// + /// + /// Active generation's source collector. + /// + /// + /// Source IDs exclusively assigned to this layer. + /// + public SelectedViewContentCollector( + IViewContentCollector inner, + IReadOnlyList sourceIDs + ) { + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(sourceIDs); + m_inner = inner; + m_sourceIDs = sourceIDs; + } + + /// + /// Collects only the assigned world-content sources for one exact view. + /// + /// + /// The original model view, output input, and frame timing. + /// + /// + /// Frame-local content emitted by the assigned sources. + /// + public IReadOnlyList Collect(ViewContentContext context) + { + ArgumentNullException.ThrowIfNull(context); + return m_inner.Collect( + new ViewContentContext( + context.content, + context.sessionID, + context.view, + context.frameIndex, + context.deltaTime, + context.input, + context.views, + m_sourceIDs + ) + ); + } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs deleted file mode 100644 index 2f8c08b4d..000000000 --- a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContent.cs +++ /dev/null @@ -1,502 +0,0 @@ -using System; -using System.Collections.Generic; -using Inno.Core.Identity; -using Inno.Core.Mathematics; -using Inno.Extensibility.Types; -using Inno.References; -using Inno.Rendering; - -namespace Inno.Rendering.Runtime; - -/// -/// Describes one backend-neutral view produced by a rendering model. -/// -[StableTypeID("eb2ef876-46a8-5155-8c45-c96b14ad2043")] -public readonly record struct RenderView -{ - /// - /// Creates the exact view used to render content into a viewport. - /// - /// - /// Stable identity within the current output session. - /// - /// - /// Destination pixel rectangle. - /// - /// - /// World-to-view transform. - /// - /// - /// View-to-clip transform. - /// - /// - /// Model-defined visible content bits. - /// - public RenderView( - string id, - RenderViewport viewport, - Matrix viewMatrix, - Matrix projectionMatrix, - ulong visibilityMask = ulong.MaxValue - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - this.viewport = viewport; - this.viewMatrix = viewMatrix; - this.projectionMatrix = projectionMatrix; - this.visibilityMask = visibilityMask; - } - - /// - /// Gets the view identity within its output session. - /// - public string id { get; } - - /// - /// Gets the destination pixel rectangle. - /// - public RenderViewport viewport { get; } - - /// - /// Gets the world-to-view transform. - /// - public Matrix viewMatrix { get; } - - /// - /// Gets the view-to-clip transform. - /// - public Matrix projectionMatrix { get; } - - /// - /// Gets the model-defined visible content bits. - /// - public ulong visibilityMask { get; } -} - -/// -/// Supplies one content source with the host-selected scene roots and an exact view. -/// -[StableTypeID("733a6b3a-4cec-5734-83c3-261f0e34b6f8")] -public sealed class ViewContentContext -{ - /// - /// Creates a frame-scoped content collection context. - /// - /// - /// Ordered roots selected by the host. - /// - /// - /// Stable identity of the host output session. - /// - /// - /// Exact view that will consume the content. - /// - /// - /// Monotonic output frame number. - /// - /// - /// Elapsed frame time in seconds. - /// - /// - /// Pointer and keyboard input in output pixel coordinates. - /// - /// - /// All views in the same model output, used to choose shared content resolution. - /// - /// - /// Optional explicit source allowlist for a routed model layer. - /// - public ViewContentContext( - ContentReadScope content, - string sessionID, - RenderView view, - ulong frameIndex, - float deltaTime, - RenderOutputInput? input = null, - IReadOnlyList? views = null, - IReadOnlyList? sourceIDs = null - ) { - ArgumentNullException.ThrowIfNull(content); - this.content = content; - ArgumentException.ThrowIfNullOrWhiteSpace(sessionID); - this.sessionID = sessionID; - this.view = view; - this.frameIndex = frameIndex; - this.deltaTime = deltaTime; - this.input = input ?? RenderOutputInput.empty; - this.views = views ?? [view]; - this.sourceIDs = sourceIDs; - } - - /// - /// Gets the ordered host-selected content roots. - /// - public ContentReadScope content { get; } - - /// - /// Gets the stable host output session identity. - /// - public string sessionID { get; } - - /// - /// Gets the exact destination view. - /// - public RenderView view { get; } - - /// - /// Gets the monotonic output frame number. - /// - public ulong frameIndex { get; } - - /// - /// Gets elapsed time in seconds. - /// - public float deltaTime { get; } - - /// - /// Gets frame-local input for this output. - /// - public RenderOutputInput input { get; } - - /// - /// Gets every view in the same model output. - /// - public IReadOnlyList views { get; } - - /// - /// Gets the exclusive source allowlist; null collects every active source. - /// - public IReadOnlyList? sourceIDs { get; } -} - -/// -/// Prepares one model-independent drawable for a specific render pass. -/// -[StableTypeID("796c6186-c301-5cb2-a634-d03f8156a039")] -public interface IViewDrawable -{ - /// - /// Resolves reusable resources before render graph execution. - /// - /// - /// Active pipeline build context. - /// - /// - /// View that will draw this item. - /// - /// - /// Prepared frame-local draw when resources are available. - /// - /// - /// Whether the drawable is ready for this pass. - /// - bool TryPrepare( - RenderPipelineContext context, - RenderView view, - out IPreparedViewDrawable? prepared - ); -} - -/// -/// Encodes a resource-ready draw into the owning model's scene pass. -/// -[StableTypeID("d17ebef7-c2f5-543e-ad05-c38c6396ac3b")] -public interface IPreparedViewDrawable -{ - /// - /// Encodes commands while the owning model controls attachments and view state. - /// - /// - /// Backend-neutral scene pass encoder. - /// - void Encode(RenderCommandEncoder commands); -} - -/// -/// Receives pointer input after the rendering model resolves visible draw order. -/// -[StableTypeID("8d770d54-025c-591a-b49e-9c12c4bde162")] -public interface IViewPointerTarget -{ - /// - /// Gets whether this target retains pointer ownership from an earlier press. - /// Rendering models route captured input before ordinary hit testing. - /// - bool hasPointerCapture { get; } - - /// - /// Gets whether keyboard and text input should continue reaching this target. - /// - bool hasKeyboardFocus { get; } - - /// - /// Changes keyboard focus after the rendering model resolves a pointer press. - /// - /// - /// Whether this target owns subsequent keyboard input. - /// - void SetKeyboardFocus(bool focused); - - /// - /// Maps one output pointer onto this item's local surface. - /// - /// - /// Exact rendered view. - /// - /// - /// Viewport-local input. - /// - /// - /// Local target coordinates when hit. - /// - /// - /// Whether this target is eligible to receive pointer input. - /// - bool TryHit( - RenderView view, - RenderOutputInput input, - out Vector2 localPosition - ); - - /// - /// Advances this target once for the frame with either routed input or an empty snapshot. - /// - /// - /// Routed viewport-local input, or an empty snapshot. - /// - /// - /// Target-local pointer coordinates. - /// - /// - /// Shared output frame index. - /// - void Advance( - RenderOutputInput input, - Vector2 localPosition, - ulong frameIndex - ); -} - -/// -/// One world item supplied to a rendering model without choosing its sort policy. -/// -[StableTypeID("4aecd31e-d107-56b4-bc92-e07bc89c125b")] -public sealed class ViewContentItem -{ - /// - /// Creates an item whose lifetime is limited to the current frame. - /// - /// - /// Scene object identity used for model-owned sorting and visibility. - /// - /// - /// Exact transform of its local geometry. - /// - /// - /// Local minimum corner for conservative culling. - /// - /// - /// Local maximum corner for conservative culling. - /// - /// - /// Drawable inserted into the model's scene pass. - /// - /// - /// Optional input target routed by the rendering model. - /// - public ViewContentItem( - Identity owner, - Matrix localToWorld, - Vector3 localBoundsMin, - Vector3 localBoundsMax, - IViewDrawable drawable, - IViewPointerTarget? pointerTarget = null - ) { - ArgumentNullException.ThrowIfNull(drawable); - this.owner = owner; - this.localToWorld = localToWorld; - this.localBoundsMin = localBoundsMin; - this.localBoundsMax = localBoundsMax; - this.drawable = drawable; - this.pointerTarget = pointerTarget; - } - - /// - /// Gets the owner identity for model-owned sorting and visibility. - /// - public Identity owner { get; } - - /// - /// Gets the local-to-world transform. - /// - public Matrix localToWorld { get; } - - /// - /// Gets the local minimum corner. - /// - public Vector3 localBoundsMin { get; } - - /// - /// Gets the local maximum corner. - /// - public Vector3 localBoundsMax { get; } - - /// - /// Gets the drawable encoded by the selected rendering model. - /// - public IViewDrawable drawable { get; } - - /// - /// Gets the optional pointer target associated with this draw item. - /// - public IViewPointerTarget? pointerTarget { get; } -} - -/// -/// Receives world items without imposing a rendering-model sort key. -/// -[StableTypeID("ee4aa3b7-c773-5f05-9655-5a3cfd457c26")] -public interface IViewContentSink -{ - /// - /// Adds an item to the current view. - /// - /// - /// Frame-local content item. - /// - void Submit(ViewContentItem item); -} - -/// -/// Contributes model-independent world items to selected views. -/// -[StableTypeID("638698ee-7dd9-5d75-92aa-84a2457ed3f0")] -public interface IViewContentSource : IDisposable -{ - /// - /// Collects items for one exact view. - /// - /// - /// Frame-scoped host content and view. - /// - /// - /// Collector receiving items. - /// - void Collect( - ViewContentContext context, - IViewContentSink sink - ); -} - -/// -/// Completes frame-local input after every output has routed its views. -/// -[StableTypeID("9242bf1f-a6dc-555f-ab73-494c7a7acc70")] -public interface IViewContentFrameSource -{ - /// - /// Advances retained content once after all output views have supplied input. - /// - /// - /// The shared render frame whose input routing has completed. - /// - void CompleteFrame(ulong frameIndex); -} - -/// -/// Discovers an independently reloadable world-content source. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[StableTypeID("9e766605-2b84-5040-858e-ae84b6a5e7c3")] -public sealed class ViewContentSourceExtensionAttribute : Attribute -{ - /// - /// Creates a source declaration with a stable identifier. - /// - /// - /// Globally stable source identifier. - /// - public ViewContentSourceExtensionAttribute(string id) - { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - } - - /// - /// Gets the globally stable source identifier. - /// - public string id { get; } -} - -/// -/// Collects all active world-content sources for one exact view. -/// -[StableTypeID("b8d46505-dda2-52b6-b3c8-133e48641fed")] -public interface IViewContentCollector -{ - /// - /// Collects active source items in deterministic source order. - /// - /// - /// Frame-scoped host content and view. - /// - /// - /// Frame-local items; the caller owns their sort and composition. - /// - IReadOnlyList Collect(ViewContentContext context); -} - -/// -/// Restricts a neutral world-content collector to an output layer's source IDs. -/// -[StableTypeID("f4217ba1-0650-58be-8e76-d6f2c2c303c5")] -public sealed class SelectedViewContentCollector : IViewContentCollector -{ - private readonly IViewContentCollector m_inner; - private readonly IReadOnlyList m_sourceIDs; - - /// - /// Creates a collector that forwards only the selected source identities. - /// - /// - /// Active generation's source collector. - /// - /// - /// Source IDs exclusively assigned to this layer. - /// - public SelectedViewContentCollector( - IViewContentCollector inner, - IReadOnlyList sourceIDs - ) { - ArgumentNullException.ThrowIfNull(inner); - ArgumentNullException.ThrowIfNull(sourceIDs); - m_inner = inner; - m_sourceIDs = sourceIDs; - } - - /// - /// Collects only the assigned world-content sources for one exact view. - /// - /// - /// The original model view, output input, and frame timing. - /// - /// - /// Frame-local content emitted by the assigned sources. - /// - public IReadOnlyList Collect(ViewContentContext context) - { - ArgumentNullException.ThrowIfNull(context); - return m_inner.Collect( - new ViewContentContext( - context.content, - context.sessionID, - context.view, - context.frameIndex, - context.deltaTime, - context.input, - context.views, - m_sourceIDs - ) - ); - } -} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentContext.cs new file mode 100644 index 000000000..85f014125 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentContext.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using Inno.Extensibility.Types; +using Inno.References; + +namespace Inno.Rendering.Runtime; + +/// +/// Supplies one content source with the host-selected scene roots and an exact view. +/// +[StableTypeID("733a6b3a-4cec-5734-83c3-261f0e34b6f8")] +public sealed class ViewContentContext +{ + /// + /// Creates a frame-scoped content collection context. + /// + /// + /// Ordered roots selected by the host. + /// + /// + /// Stable identity of the host output session. + /// + /// + /// Exact view that will consume the content. + /// + /// + /// Monotonic output frame number. + /// + /// + /// Elapsed frame time in seconds. + /// + /// + /// Pointer and keyboard input in output pixel coordinates. + /// + /// + /// All views in the same model output, used to choose shared content resolution. + /// + /// + /// Optional explicit source allowlist for a routed model layer. + /// + public ViewContentContext( + ContentReadScope content, + string sessionID, + RenderView view, + ulong frameIndex, + float deltaTime, + RenderOutputInput? input = null, + IReadOnlyList? views = null, + IReadOnlyList? sourceIDs = null + ) { + ArgumentNullException.ThrowIfNull(content); + this.content = content; + ArgumentException.ThrowIfNullOrWhiteSpace(sessionID); + this.sessionID = sessionID; + this.view = view; + this.frameIndex = frameIndex; + this.deltaTime = deltaTime; + this.input = input ?? RenderOutputInput.empty; + this.views = views ?? [view]; + this.sourceIDs = sourceIDs; + } + + /// + /// Gets the ordered host-selected content roots. + /// + public ContentReadScope content { get; } + + /// + /// Gets the stable host output session identity. + /// + public string sessionID { get; } + + /// + /// Gets the exact destination view. + /// + public RenderView view { get; } + + /// + /// Gets the monotonic output frame number. + /// + public ulong frameIndex { get; } + + /// + /// Gets elapsed time in seconds. + /// + public float deltaTime { get; } + + /// + /// Gets frame-local input for this output. + /// + public RenderOutputInput input { get; } + + /// + /// Gets every view in the same model output. + /// + public IReadOnlyList views { get; } + + /// + /// Gets the exclusive source allowlist; null collects every active source. + /// + public IReadOnlyList? sourceIDs { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentItem.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentItem.cs new file mode 100644 index 000000000..d9f6c9b3e --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentItem.cs @@ -0,0 +1,81 @@ +using System; +using Inno.Core.Identity; +using Inno.Core.Mathematics; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// One world item supplied to a rendering model without choosing its sort policy. +/// +[StableTypeID("4aecd31e-d107-56b4-bc92-e07bc89c125b")] +public sealed class ViewContentItem +{ + /// + /// Creates an item whose lifetime is limited to the current frame. + /// + /// + /// Scene object identity used for model-owned sorting and visibility. + /// + /// + /// Exact transform of its local geometry. + /// + /// + /// Local minimum corner for conservative culling. + /// + /// + /// Local maximum corner for conservative culling. + /// + /// + /// Drawable inserted into the model's scene pass. + /// + /// + /// Optional input target routed by the rendering model. + /// + public ViewContentItem( + Identity owner, + Matrix localToWorld, + Vector3 localBoundsMin, + Vector3 localBoundsMax, + IViewDrawable drawable, + IViewPointerTarget? pointerTarget = null + ) { + ArgumentNullException.ThrowIfNull(drawable); + this.owner = owner; + this.localToWorld = localToWorld; + this.localBoundsMin = localBoundsMin; + this.localBoundsMax = localBoundsMax; + this.drawable = drawable; + this.pointerTarget = pointerTarget; + } + + /// + /// Gets the owner identity for model-owned sorting and visibility. + /// + public Identity owner { get; } + + /// + /// Gets the local-to-world transform. + /// + public Matrix localToWorld { get; } + + /// + /// Gets the local minimum corner. + /// + public Vector3 localBoundsMin { get; } + + /// + /// Gets the local maximum corner. + /// + public Vector3 localBoundsMax { get; } + + /// + /// Gets the drawable encoded by the selected rendering model. + /// + public IViewDrawable drawable { get; } + + /// + /// Gets the optional pointer target associated with this draw item. + /// + public IViewPointerTarget? pointerTarget { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentSourceExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentSourceExtensionAttribute.cs new file mode 100644 index 000000000..aa8342757 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Models/ViewContentSourceExtensionAttribute.cs @@ -0,0 +1,29 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Discovers an independently reloadable world-content source. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +[StableTypeID("9e766605-2b84-5040-858e-ae84b6a5e7c3")] +public sealed class ViewContentSourceExtensionAttribute : Attribute +{ + /// + /// Creates a source declaration with a stable identifier. + /// + /// + /// Globally stable source identifier. + /// + public ViewContentSourceExtensionAttribute(string id) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + } + + /// + /// Gets the globally stable source identifier. + /// + public string id { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.FrameScratch.cs similarity index 98% rename from src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs rename to src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.FrameScratch.cs index 54c28c7e4..bc57ec8e0 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/RenderFrameScratch.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/RenderRuntime.FrameScratch.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Inno.Rendering.Assets; diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs index eb6408e7a..0aee1d9ea 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProvider.cs @@ -1,169 +1,9 @@ using System; using Inno.Core.Execution; using Inno.Extensibility.Types; -using Inno.References; -using Inno.Rendering; namespace Inno.Rendering.Runtime; -/// -/// Marks a reloadable provider that produces model-neutral render requests each frame. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -[StableTypeID("54ca2eb2-0fc2-5b3e-91d1-0bd52d01caab")] -public sealed class RenderRequestProviderExtensionAttribute : Attribute -{ - /// - /// Creates a render request provider declaration. - /// - /// - /// Globally stable provider identifier. - /// - /// - /// Provider invocation priority; lower values run first. - /// - public RenderRequestProviderExtensionAttribute( - string id, - int priority = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - this.id = id; - this.priority = priority; - } - - /// - /// Gets the globally stable provider identifier. - /// - public string id { get; } - - /// - /// Gets the provider invocation priority. - /// - public int priority { get; } -} - -/// -/// Supplies frame timing, capabilities and the request sink to one provider invocation. -/// -[StableTypeID("67067617-9592-55b2-bbb0-739c6927984b")] -public sealed class RenderRequestProviderContext -{ - /// - /// Creates a frame-scoped provider context. - /// - /// - /// Sink accepting requests for the current frame. - /// - /// - /// Host-selected content roots visible to request providers this frame. - /// - /// - /// Active backend-neutral capability snapshot. - /// - /// - /// Current primary pixel extent, or null while no primary output is available. - /// - /// - /// Host-selected content region, or null when the primary extent is unavailable. - /// - /// - /// Monotonic render frame index. - /// - /// - /// Elapsed frame time in seconds. - /// - /// - /// Collector for model-independent world items. - /// - /// - /// Viewport-local input for the primary output. - /// - public RenderRequestProviderContext( - IRenderRequestSink requests, - ContentReadScope content, - GraphicsCapabilities capabilities, - RenderPresentationSize? primaryPresentationSize, - RenderViewport? primaryPresentationViewport, - ulong frameIndex, - float deltaTime, - IViewContentCollector viewContent, - RenderOutputInput? input = null - ) { - ArgumentNullException.ThrowIfNull(requests); - ArgumentNullException.ThrowIfNull(content); - ArgumentNullException.ThrowIfNull(capabilities); - ArgumentNullException.ThrowIfNull(viewContent); - this.requests = requests; - this.content = content; - this.capabilities = capabilities; - this.primaryPresentationSize = primaryPresentationSize; - if (primaryPresentationSize.HasValue != primaryPresentationViewport.HasValue) - { - throw new ArgumentException("Primary presentation size and viewport must have the same availability."); - } - if (primaryPresentationSize is RenderPresentationSize size && primaryPresentationViewport is RenderViewport viewport - && (!size.isValid || viewport.width <= 0 || viewport.height <= 0 - || (long)viewport.x + viewport.width > size.width - || (long)viewport.y + viewport.height > size.height) - ) { - throw new ArgumentException( - "The primary presentation viewport must fit inside the primary presentation surface.", - nameof(primaryPresentationViewport) - ); - } - this.primaryPresentationViewport = primaryPresentationViewport; - this.frameIndex = frameIndex; - this.deltaTime = deltaTime; - this.viewContent = viewContent; - this.input = primaryPresentationSize.HasValue ? input ?? RenderOutputInput.empty : RenderOutputInput.suspended; - } - - /// - /// Gets the sink accepting requests for the current frame. - /// - public IRenderRequestSink requests { get; } - - /// - /// Gets the explicit ordered host content visible to request providers this frame. - /// - public ContentReadScope content { get; } - - /// - /// Gets the active backend-neutral capability snapshot. - /// - public GraphicsCapabilities capabilities { get; } - - /// - /// Gets the current primary pixel extent, or null while only offscreen outputs are available. - /// - public RenderPresentationSize? primaryPresentationSize { get; } - - /// - /// Gets the host-selected primary region, or null while no primary output is available. - /// - public RenderViewport? primaryPresentationViewport { get; } - - /// - /// Gets the monotonic render frame index. - /// - public ulong frameIndex { get; } - - /// - /// Gets the elapsed frame time in seconds. - /// - public float deltaTime { get; } - - /// - /// Gets the active generation's world-content collector. - /// - public IViewContentCollector viewContent { get; } - - /// - /// Gets viewport-local input for the primary output. - /// - public RenderOutputInput input { get; } -} - /// /// Produces arbitrary render requests without prescribing a scene or rendering model. /// diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderContext.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderContext.cs new file mode 100644 index 000000000..1a73b0c27 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderContext.cs @@ -0,0 +1,127 @@ +using System; +using Inno.Extensibility.Types; +using Inno.References; + +namespace Inno.Rendering.Runtime; + +/// +/// Supplies frame timing, capabilities and the request sink to one provider invocation. +/// +[StableTypeID("67067617-9592-55b2-bbb0-739c6927984b")] +public sealed class RenderRequestProviderContext +{ + /// + /// Creates a frame-scoped provider context. + /// + /// + /// Sink accepting requests for the current frame. + /// + /// + /// Host-selected content roots visible to request providers this frame. + /// + /// + /// Active backend-neutral capability snapshot. + /// + /// + /// Current primary pixel extent, or null while no primary output is available. + /// + /// + /// Host-selected content region, or null when the primary extent is unavailable. + /// + /// + /// Monotonic render frame index. + /// + /// + /// Elapsed frame time in seconds. + /// + /// + /// Collector for model-independent world items. + /// + /// + /// Viewport-local input for the primary output. + /// + public RenderRequestProviderContext( + IRenderRequestSink requests, + ContentReadScope content, + GraphicsCapabilities capabilities, + RenderPresentationSize? primaryPresentationSize, + RenderViewport? primaryPresentationViewport, + ulong frameIndex, + float deltaTime, + IViewContentCollector viewContent, + RenderOutputInput? input = null + ) { + ArgumentNullException.ThrowIfNull(requests); + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(capabilities); + ArgumentNullException.ThrowIfNull(viewContent); + this.requests = requests; + this.content = content; + this.capabilities = capabilities; + this.primaryPresentationSize = primaryPresentationSize; + if (primaryPresentationSize.HasValue != primaryPresentationViewport.HasValue) + { + throw new ArgumentException("Primary presentation size and viewport must have the same availability."); + } + if (primaryPresentationSize is RenderPresentationSize size && primaryPresentationViewport is RenderViewport viewport + && (!size.isValid || viewport.width <= 0 || viewport.height <= 0 + || (long)viewport.x + viewport.width > size.width + || (long)viewport.y + viewport.height > size.height) + ) { + throw new ArgumentException( + "The primary presentation viewport must fit inside the primary presentation surface.", + nameof(primaryPresentationViewport) + ); + } + this.primaryPresentationViewport = primaryPresentationViewport; + this.frameIndex = frameIndex; + this.deltaTime = deltaTime; + this.viewContent = viewContent; + this.input = primaryPresentationSize.HasValue ? input ?? RenderOutputInput.empty : RenderOutputInput.suspended; + } + + /// + /// Gets the sink accepting requests for the current frame. + /// + public IRenderRequestSink requests { get; } + + /// + /// Gets the explicit ordered host content visible to request providers this frame. + /// + public ContentReadScope content { get; } + + /// + /// Gets the active backend-neutral capability snapshot. + /// + public GraphicsCapabilities capabilities { get; } + + /// + /// Gets the current primary pixel extent, or null while only offscreen outputs are available. + /// + public RenderPresentationSize? primaryPresentationSize { get; } + + /// + /// Gets the host-selected primary region, or null while no primary output is available. + /// + public RenderViewport? primaryPresentationViewport { get; } + + /// + /// Gets the monotonic render frame index. + /// + public ulong frameIndex { get; } + + /// + /// Gets the elapsed frame time in seconds. + /// + public float deltaTime { get; } + + /// + /// Gets the active generation's world-content collector. + /// + public IViewContentCollector viewContent { get; } + + /// + /// Gets viewport-local input for the primary output. + /// + public RenderOutputInput input { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderExtensionAttribute.cs b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderExtensionAttribute.cs new file mode 100644 index 000000000..6f098ef8d --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Runtime/Requests/RenderRequestProviderExtensionAttribute.cs @@ -0,0 +1,40 @@ +using System; +using Inno.Extensibility.Types; + +namespace Inno.Rendering.Runtime; + +/// +/// Marks a reloadable provider that produces model-neutral render requests each frame. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +[StableTypeID("54ca2eb2-0fc2-5b3e-91d1-0bd52d01caab")] +public sealed class RenderRequestProviderExtensionAttribute : Attribute +{ + /// + /// Creates a render request provider declaration. + /// + /// + /// Globally stable provider identifier. + /// + /// + /// Provider invocation priority; lower values run first. + /// + public RenderRequestProviderExtensionAttribute( + string id, + int priority = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + this.id = id; + this.priority = priority; + } + + /// + /// Gets the globally stable provider identifier. + /// + public string id { get; } + + /// + /// Gets the provider invocation priority. + /// + public int priority { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs index 19072932a..cc9a9e52e 100644 --- a/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs +++ b/src/services/rendering/Inno.Rendering.Runtime/Resources/RenderMaterialPass.cs @@ -1,31 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Inno.Core.Diagnostics; using Inno.Extensibility.Types; -using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Rendering.Runtime; -[StableTypeID("b5677cc4-c195-5f52-a52f-5efecec8314e")] -internal enum RenderMaterialBindingKind -{ - Uniform, - Texture -} - -[StableTypeID("702a1ec9-219b-5d44-b322-1a433e7e41b5")] -internal sealed record RenderMaterialBinding( - RenderMaterialBindingKind kind, - RenderBindingID id, - byte[]? uniformData, - PersistentTextureHandle texture, - RenderSamplerState sampler -); - /// /// Represents one frame-resolved material pass and its material-owned bindings. /// @@ -181,3 +161,19 @@ private static RenderShaderBindingKind ToRenderBindingKind(ShaderPropertyBinding _ => throw new ArgumentOutOfRangeException(nameof(kind)) }; } + +[StableTypeID("b5677cc4-c195-5f52-a52f-5efecec8314e")] +internal enum RenderMaterialBindingKind +{ + Uniform, + Texture +} + +[StableTypeID("702a1ec9-219b-5d44-b322-1a433e7e41b5")] +internal sealed record RenderMaterialBinding( + RenderMaterialBindingKind kind, + RenderBindingID id, + byte[]? uniformData, + PersistentTextureHandle texture, + RenderSamplerState sampler +); diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/IShaderNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/IShaderNodeCompiler.cs new file mode 100644 index 000000000..fd4c0d18d --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/IShaderNodeCompiler.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +/// +/// Defines one shader node's typed ports and lowering; drawing belongs to a separate editor extension. +/// +public interface IShaderNodeCompiler +{ + /// + /// Gets the exact graph node definition identity implemented by this compiler. + /// + string definitionID { get; } + + /// + /// Describes ports for the current neutral properties and resolved source/target inputs. + /// + /// + /// Invocation-scoped node properties and frozen source/target data. + /// + /// + /// Complete typed ports; duplicate identities are invalid. + /// + IReadOnlyList GetPorts(ShaderNodeDescriptionContext context); + + /// + /// Lowers the node into the supplied typed builder without generating source strings. + /// + /// + /// Connected typed inputs and the shared region builder. + /// + /// + /// Exactly the declared output ports by stable identity. + /// + IReadOnlyDictionary Lower(ShaderNodeLoweringContext context); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBinaryNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBinaryNodeCompiler.cs new file mode 100644 index 000000000..6f237c7fb --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBinaryNodeCompiler.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Lowers an explicit arithmetic/comparison operation; operation IDs are node configuration, not backend code. +/// +public sealed class ShaderBinaryNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.binary"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float")); + ShaderIrOperation operation = Operation(context); + return [ + new ShaderNodePort("left", type, GraphPortDirection.Input), + new ShaderNodePort("right", type, GraphPortDirection.Input), + new ShaderNodePort( + "value", + operation is ShaderIrOperation.Equal or ShaderIrOperation.LessThan ? ShaderSourceType.Atomic("bool") : type, + GraphPortDirection.Output + ) + ]; + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary + { + ["value"] = context.builder.Binary(Operation(context.description), context.Input("left"), context.Input("right")) + }; + + private static ShaderIrOperation Operation(ShaderNodeDescriptionContext context) + => context.Read("operation", "add") switch + { + "add" => ShaderIrOperation.Add, + "subtract" => ShaderIrOperation.Subtract, + "multiply" => ShaderIrOperation.Multiply, + "divide" => ShaderIrOperation.Divide, + "minimum" => ShaderIrOperation.Minimum, + "maximum" => ShaderIrOperation.Maximum, + "equal" => ShaderIrOperation.Equal, + "less-than" => ShaderIrOperation.LessThan, + _ => throw new InvalidOperationException("Unknown binary shader operation.") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs deleted file mode 100644 index 979c5ffac..000000000 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderBuiltinNodeCompilers.cs +++ /dev/null @@ -1,407 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Inno.Core.Graphs; - -namespace Inno.Rendering.Shaders; - -/// -/// Lowers an exact scalar constant; its type/value are native graph properties. -/// -public sealed class ShaderConstantNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionID => "inno.shader.constant"; - - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => [new ShaderNodePort("value", ShaderSourceType.Atomic(context.Read("type", "float")), GraphPortDirection.Output)]; - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - ShaderNodeDescriptionContext node = context.description; - ShaderIrValue value = node.Read("type", "float") switch - { - "float" => context.builder.Constant(node.Read("value", 0f)), - "int" => context.builder.Constant(node.Read("value", 0)), - "uint" => context.builder.Constant(node.Read("value", 0u)), - "bool" => context.builder.Constant(node.Read("value", false)), - _ => throw new InvalidOperationException("A scalar constant must declare float, int, uint or bool.") - }; - return new Dictionary { ["value"] = value }; - } -} - -/// -/// Lowers an explicit arithmetic/comparison operation; operation IDs are node configuration, not backend code. -/// -public sealed class ShaderBinaryNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionID => "inno.shader.binary"; - - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float")); - ShaderIrOperation operation = Operation(context); - return [ - new ShaderNodePort("left", type, GraphPortDirection.Input), - new ShaderNodePort("right", type, GraphPortDirection.Input), - new ShaderNodePort( - "value", - operation is ShaderIrOperation.Equal or ShaderIrOperation.LessThan ? ShaderSourceType.Atomic("bool") : type, - GraphPortDirection.Output - ) - ]; - } - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary - { - ["value"] = context.builder.Binary(Operation(context.description), context.Input("left"), context.Input("right")) - }; - - private static ShaderIrOperation Operation(ShaderNodeDescriptionContext context) - => context.Read("operation", "add") switch - { - "add" => ShaderIrOperation.Add, - "subtract" => ShaderIrOperation.Subtract, - "multiply" => ShaderIrOperation.Multiply, - "divide" => ShaderIrOperation.Divide, - "minimum" => ShaderIrOperation.Minimum, - "maximum" => ShaderIrOperation.Maximum, - "equal" => ShaderIrOperation.Equal, - "less-than" => ShaderIrOperation.LessThan, - _ => throw new InvalidOperationException("Unknown binary shader operation.") - }; -} - -/// -/// Constructs a vector or column-major matrix from individually connected scalar components. -/// -public sealed class ShaderConstructNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionID => "inno.shader.construct"; - - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - (ShaderSourceType type, ShaderSourceType scalar, int count) = Shape(context); - return Enumerable.Range(0, count) - .Select(index => new ShaderNodePort("component." + index, scalar, GraphPortDirection.Input)) - .Append(new ShaderNodePort("value", type, GraphPortDirection.Output)) - .ToArray(); - } - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - (ShaderSourceType type, _, int count) = Shape(context.description); - return new Dictionary - { - ["value"] = context.builder.Construct( - type, - Enumerable.Range(0, count).Select(index => context.Input("component." + index)).ToArray() - ) - }; - } - - private static (ShaderSourceType type, ShaderSourceType scalar, int count) Shape(ShaderNodeDescriptionContext context) - { - string id = context.Read("type", "float4"); - foreach (string scalar in new[] { "float", "int", "uint", "bool" }) - { - if (id.Length == scalar.Length + 1 && id.StartsWith(scalar, StringComparison.Ordinal) && id[^1] is >= '2' and <= '4') - { - return (ShaderSourceType.Atomic(id), ShaderSourceType.Atomic(scalar), id[^1] - '0'); - } - } - if (id.Length == 8 - && id.StartsWith("float", StringComparison.Ordinal) - && id[5] is >= '2' and <= '4' - && id[6] == 'x' - && id[7] is >= '2' and <= '4' - ) { - return (ShaderSourceType.Atomic(id), ShaderSourceType.Atomic("float"), (id[5] - '0') * (id[7] - '0')); - } - throw new InvalidOperationException("Construction requires a numeric vector or floating-point matrix."); - } -} - -/// -/// Reads one target-assigned stage/resource input without choosing a native variable name. -/// -public sealed class ShaderStageInputNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionID => "inno.shader.stage-input"; - - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => [new ShaderNodePort("value", RequireBinding(context).type, GraphPortDirection.Output)]; - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - ShaderIrStageInput input = RequireBinding(context.description); - return new Dictionary { ["value"] = context.builder.Input(input.id, input.type) }; - } - - private static ShaderIrStageInput RequireBinding(ShaderNodeDescriptionContext context) - => context.stageInput ?? throw new InvalidOperationException("The target has not resolved this stage input binding."); -} - -/// -/// Selects between equal typed values; all producer effects remain evaluated before selection. -/// -public sealed class ShaderSelectNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionID => "inno.shader.select"; - - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float")); - return [ - new ShaderNodePort("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), - new ShaderNodePort("true", type, GraphPortDirection.Input), - new ShaderNodePort("false", type, GraphPortDirection.Input), - new ShaderNodePort("value", type, GraphPortDirection.Output) - ]; - } - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary - { - ["value"] = context.builder.Select(context.Input("condition"), context.Input("true"), context.Input("false")) - }; -} - -/// -/// Lowers a parsed function module with name-based ports and explicit aggregate/member connection alternatives. -/// -public sealed class ShaderSourceNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionID => "inno.shader.source"; - - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - ShaderSourceFunction function = RequireModule(context).function!; - List ports = []; - foreach (ShaderSourceParameter parameter in function.parameters) - { - if (parameter.direction != ShaderSourceParameterDirection.Output) - { - Add("input." + parameter.name, parameter.type, GraphPortDirection.Input); - } - if (parameter.direction != ShaderSourceParameterDirection.Input) - { - Add("output." + parameter.name, parameter.type, GraphPortDirection.Output); - } - } - if (function.returnType.id != "void") - { - Add("return", function.returnType, GraphPortDirection.Output); - } - return ports.AsReadOnly(); - void Add( - string name, - ShaderSourceType type, - GraphPortDirection direction - ) { - ports.Add(new ShaderNodePort(name, type, direction, required: false)); - foreach (ShaderSourceField field in type.fields) - { - Add(name + "." + field.name, field.type, direction); - } - } - } - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - ShaderSourceModuleAnalysis module = RequireModule(context.description); - var arguments = new Dictionary(StringComparer.Ordinal); - foreach (ShaderSourceParameter parameter in module.function!.parameters) - { - if (parameter.direction != ShaderSourceParameterDirection.Output) - { - arguments.Add(parameter.name, Resolve("input." + parameter.name, parameter.type)); - } - } - IReadOnlyDictionary values = context.builder.Call(module, context.description.implementationID, arguments); - var outputs = new Dictionary(StringComparer.Ordinal); - foreach ((string name, ShaderIrValue value) in values) - { - Add(name, value); - } - return outputs; - - ShaderIrValue Resolve( - string name, - ShaderSourceType type - ) { - if (context.inputs.TryGetValue(name, out ShaderIrValue? aggregate)) - { - if (context.inputs.Keys.Any(key => key.StartsWith(name + ".", StringComparison.Ordinal))) - { - throw new InvalidOperationException( - $"'{name}' connects both its aggregate and a member; choose one representation explicitly." - ); - } - return aggregate; - } - if (type.fields.Count == 0) - { - return context.Input(name); - } - return context.builder.Construct(type, type.fields.Select(field => Resolve(name + "." + field.name, field.type)).ToArray()); - } - - void Add( - string name, - ShaderIrValue value - ) { - outputs.Add(name, value); - for (int index = 0; index < value.type.fields.Count; index++) - { - Add(name + "." + value.type.fields[index].name, context.builder.Extract(value, index)); - } - } - } - - private static ShaderSourceModuleAnalysis RequireModule(ShaderNodeDescriptionContext context) - { - ShaderSourceModuleAnalysis? module = context.sourceModule; - if (module is null) - { - throw new InvalidOperationException( - "The source module is unassigned or unavailable; its stored reference and connections must remain intact." - ); - } - if (!module.succeeded) - { - throw new InvalidOperationException( - "The source module has no valid common interface: " - + string.Join("; ", module.diagnostics.Select(static value => value.message)) - ); - } - return module; - } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstantNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstantNodeCompiler.cs new file mode 100644 index 000000000..78d37c7e0 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstantNodeCompiler.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Lowers an exact scalar constant; its type/value are native graph properties. +/// +public sealed class ShaderConstantNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.constant"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => [new ShaderNodePort("value", ShaderSourceType.Atomic(context.Read("type", "float")), GraphPortDirection.Output)]; + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + ShaderNodeDescriptionContext node = context.description; + ShaderIrValue value = node.Read("type", "float") switch + { + "float" => context.builder.Constant(node.Read("value", 0f)), + "int" => context.builder.Constant(node.Read("value", 0)), + "uint" => context.builder.Constant(node.Read("value", 0u)), + "bool" => context.builder.Constant(node.Read("value", false)), + _ => throw new InvalidOperationException("A scalar constant must declare float, int, uint or bool.") + }; + return new Dictionary { ["value"] = value }; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstructNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstructNodeCompiler.cs new file mode 100644 index 000000000..f9af4af5a --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderConstructNodeCompiler.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Constructs a vector or column-major matrix from individually connected scalar components. +/// +public sealed class ShaderConstructNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.construct"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + (ShaderSourceType type, ShaderSourceType scalar, int count) = Shape(context); + return Enumerable.Range(0, count) + .Select(index => new ShaderNodePort("component." + index, scalar, GraphPortDirection.Input)) + .Append(new ShaderNodePort("value", type, GraphPortDirection.Output)) + .ToArray(); + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + (ShaderSourceType type, _, int count) = Shape(context.description); + return new Dictionary + { + ["value"] = context.builder.Construct( + type, + Enumerable.Range(0, count).Select(index => context.Input("component." + index)).ToArray() + ) + }; + } + + private static (ShaderSourceType type, ShaderSourceType scalar, int count) Shape(ShaderNodeDescriptionContext context) + { + string id = context.Read("type", "float4"); + foreach (string scalar in new[] { "float", "int", "uint", "bool" }) + { + if (id.Length == scalar.Length + 1 && id.StartsWith(scalar, StringComparison.Ordinal) && id[^1] is >= '2' and <= '4') + { + return (ShaderSourceType.Atomic(id), ShaderSourceType.Atomic(scalar), id[^1] - '0'); + } + } + if (id.Length == 8 + && id.StartsWith("float", StringComparison.Ordinal) + && id[5] is >= '2' and <= '4' + && id[6] == 'x' + && id[7] is >= '2' and <= '4' + ) { + return (ShaderSourceType.Atomic(id), ShaderSourceType.Atomic("float"), (id[5] - '0') * (id[7] - '0')); + } + throw new InvalidOperationException("Construction requires a numeric vector or floating-point matrix."); + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderDiscardNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderDiscardNodeCompiler.cs new file mode 100644 index 000000000..935ad1215 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderDiscardNodeCompiler.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderDiscardNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// +public string definitionID => "inno.shader.discard"; + + /// + /// Retrieves the current ports from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => [ + new ShaderNodePort("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), + new ShaderNodePort("after", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input, false), + new ShaderNodePort("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output) + ]; + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + context.builder.Discard(context.Input("condition")); + return new Dictionary { ["then"] = context.builder.Constant(true) }; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderExtractNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderExtractNodeCompiler.cs new file mode 100644 index 000000000..893704f4b --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderExtractNodeCompiler.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Extracts one statically selected component from a vector or matrix. +/// +public sealed class ShaderExtractNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.extract"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float4")); + var builder = new ShaderIrBuilder(); + ShaderIrValue member = builder.Extract(builder.Input("input", type), context.Read("index", 0)); + return [ + new ShaderNodePort("input", type, GraphPortDirection.Input), + new ShaderNodePort("value", member.type, GraphPortDirection.Output) + ]; + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary + { + ["value"] = context.builder.Extract(context.Input("input"), context.description.Read("index", 0)) + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs index d0b7a5134..65991639f 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringRequest.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Linq; using Inno.Core.Diagnostics; using Inno.Core.Graphs; @@ -107,32 +106,3 @@ public sealed record ShaderGraphDiagnostic( GraphNodeID? nodeID = null, string? portID = null ); - -/// -/// Contains a detached typed region only after all graph, port and node lowering validation succeeds. -/// -public sealed class ShaderGraphLoweringResult -{ - internal ShaderGraphLoweringResult( - ShaderIrBlock? block, - IEnumerable diagnostics - ) { - this.block = block; - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - - /// - /// Gets the immutable typed region, or null on failure. - /// - public ShaderIrBlock? block { get; } - - /// - /// Gets located graph diagnostics, including missing definitions and stale source ports. - /// - public IReadOnlyList diagnostics { get; } - - /// - /// Gets whether lowering produced a complete region without errors; native compilation is a separate gate. - /// - public bool succeeded => block is not null && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringResult.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringResult.cs new file mode 100644 index 000000000..afc39f480 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderGraphLoweringResult.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Diagnostics; + +namespace Inno.Rendering.Shaders; + +/// +/// Contains a detached typed region only after all graph, port and node lowering validation succeeds. +/// +public sealed class ShaderGraphLoweringResult +{ + internal ShaderGraphLoweringResult( + ShaderIrBlock? block, + IEnumerable diagnostics + ) { + this.block = block; + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets the immutable typed region, or null on failure. + /// + public ShaderIrBlock? block { get; } + + /// + /// Gets located graph diagnostics, including missing definitions and stale source ports. + /// + public IReadOnlyList diagnostics { get; } + + /// + /// Gets whether lowering produced a complete region without errors; native compilation is a separate gate. + /// + public bool succeeded => block is not null && diagnostics.All(static value => value.severity != DiagnosticSeverity.Error); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs deleted file mode 100644 index 7ca6833cf..000000000 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeCompiler.cs +++ /dev/null @@ -1,184 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using Inno.Core.Graphs; -using Inno.Core.Serialization; - -namespace Inno.Rendering.Shaders; - -/// -/// Declares a typed shader port independently of editor presentation and backend source syntax. -/// -/// -/// Stable node-local port identity. -/// -/// -/// Complete value type, including all aggregate fields. -/// -/// -/// Input or output value flow. -/// -/// -/// Whether an input must be connected; alternative aggregate/member inputs validate in their compiler. -/// -public sealed record ShaderNodePort( - string id, - ShaderSourceType type, - GraphPortDirection direction, - bool required = true -); - -/// -/// Defines one shader node's typed ports and lowering; drawing belongs to a separate editor extension. -/// -public interface IShaderNodeCompiler -{ - /// - /// Gets the exact graph node definition identity implemented by this compiler. - /// - string definitionID { get; } - - /// - /// Describes ports for the current neutral properties and resolved source/target inputs. - /// - /// - /// Invocation-scoped node properties and frozen source/target data. - /// - /// - /// Complete typed ports; duplicate identities are invalid. - /// - IReadOnlyList GetPorts(ShaderNodeDescriptionContext context); - - /// - /// Lowers the node into the supplied typed builder without generating source strings. - /// - /// - /// Connected typed inputs and the shared region builder. - /// - /// - /// Exactly the declared output ports by stable identity. - /// - IReadOnlyDictionary Lower(ShaderNodeLoweringContext context); -} - -/// -/// Provides invocation-scoped property decoding through the complete owner serialization context. -/// -public sealed class ShaderNodeDescriptionContext -{ - private readonly GraphNodeRecord m_node; - private readonly SerializationRegistry m_serialization; - private readonly SerializationContext m_context; - - internal ShaderNodeDescriptionContext( - GraphNodeRecord node, - SerializationRegistry serialization, - SerializationContext context, - ShaderSourceModuleAnalysis? sourceModule, - string implementationID, - ShaderIrStageInput? stageInput - ) { - m_node = node; - m_serialization = serialization; - m_context = context; - this.sourceModule = sourceModule; - this.implementationID = implementationID; - this.stageInput = stageInput; - } - - /// - /// Gets the node's stable identity, never its editor runtime handle. - /// - public GraphNodeID nodeID => m_node.id; - - /// - /// Gets the node definition's stable identity. - /// - public string definitionID => m_node.definitionID; - - /// - /// Gets a frozen module resolved by the asset owner; null means unassigned or unavailable. - /// - public ShaderSourceModuleAnalysis? sourceModule { get; } - - /// - /// Gets the exact implementation key chosen by the target. - /// - public string implementationID { get; } - - /// - /// Gets the target-assigned stage input for this node, when applicable. - /// - public ShaderIrStageInput? stageInput { get; } - - /// - /// Reads a property using the owner's converter generation and complete reference resolver context. - /// - /// - /// Declared property type supported by the native serializer. - /// - /// - /// Stable property identity. - /// - /// - /// Value used only when the property is absent, never after corrupt-data failure. - /// - /// - /// The deserialized value or the supplied absent-property default. - /// - public T Read( - string id, - T defaultValue - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - return m_node.TryGetValue(id, out GraphSerializedValue? value) - ? m_serialization.Decode(value!.data.Span, reader => reader.Read("value"), m_context) - : defaultValue; - } -} - -/// -/// Supplies one node's connected values and the region builder during lowering only. -/// -public sealed class ShaderNodeLoweringContext -{ - internal ShaderNodeLoweringContext( - ShaderNodeDescriptionContext description, - ShaderIrBuilder builder, - IReadOnlyDictionary inputs - ) { - this.description = description; - this.builder = builder; - this.inputs = new ReadOnlyDictionary(new Dictionary(inputs, StringComparer.Ordinal)); - } - - /// - /// Gets the invocation-scoped node description. - /// - public ShaderNodeDescriptionContext description { get; } - - /// - /// Gets the builder shared by nodes in this typed region. - /// - public ShaderIrBuilder builder { get; } - - /// - /// Gets connected values keyed by semantic input port identity, never connection order. - /// - public IReadOnlyDictionary inputs { get; } - - /// - /// Requires one connected input without implicit defaults or positional rebinding. - /// - /// - /// Exact semantic input port identity. - /// - /// - /// The connected typed value. - /// - public ShaderIrValue Input(string id) - => inputs.TryGetValue(id, out ShaderIrValue? value) - ? value - : throw new InvalidOperationException($"Input '{id}' is not connected."); -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeDescriptionContext.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeDescriptionContext.cs new file mode 100644 index 000000000..0db17c888 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeDescriptionContext.cs @@ -0,0 +1,81 @@ +using System; +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Provides invocation-scoped property decoding through the complete owner serialization context. +/// +public sealed class ShaderNodeDescriptionContext +{ + private readonly GraphNodeRecord m_node; + private readonly SerializationRegistry m_serialization; + private readonly SerializationContext m_context; + + internal ShaderNodeDescriptionContext( + GraphNodeRecord node, + SerializationRegistry serialization, + SerializationContext context, + ShaderSourceModuleAnalysis? sourceModule, + string implementationID, + ShaderIrStageInput? stageInput + ) { + m_node = node; + m_serialization = serialization; + m_context = context; + this.sourceModule = sourceModule; + this.implementationID = implementationID; + this.stageInput = stageInput; + } + + /// + /// Gets the node's stable identity, never its editor runtime handle. + /// + public GraphNodeID nodeID => m_node.id; + + /// + /// Gets the node definition's stable identity. + /// + public string definitionID => m_node.definitionID; + + /// + /// Gets a frozen module resolved by the asset owner; null means unassigned or unavailable. + /// + public ShaderSourceModuleAnalysis? sourceModule { get; } + + /// + /// Gets the exact implementation key chosen by the target. + /// + public string implementationID { get; } + + /// + /// Gets the target-assigned stage input for this node, when applicable. + /// + public ShaderIrStageInput? stageInput { get; } + + /// + /// Reads a property using the owner's converter generation and complete reference resolver context. + /// + /// + /// Declared property type supported by the native serializer. + /// + /// + /// Stable property identity. + /// + /// + /// Value used only when the property is absent, never after corrupt-data failure. + /// + /// + /// The deserialized value or the supplied absent-property default. + /// + public T Read( + string id, + T defaultValue + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + return m_node.TryGetValue(id, out GraphSerializedValue? value) + ? m_serialization.Decode(value!.data.Span, reader => reader.Read("value"), m_context) + : defaultValue; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeLoweringContext.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeLoweringContext.cs new file mode 100644 index 000000000..ff2fe55e7 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodeLoweringContext.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.Rendering.Shaders; + +/// +/// Supplies one node's connected values and the region builder during lowering only. +/// +public sealed class ShaderNodeLoweringContext +{ + internal ShaderNodeLoweringContext( + ShaderNodeDescriptionContext description, + ShaderIrBuilder builder, + IReadOnlyDictionary inputs + ) { + this.description = description; + this.builder = builder; + this.inputs = new ReadOnlyDictionary(new Dictionary(inputs, StringComparer.Ordinal)); + } + + /// + /// Gets the invocation-scoped node description. + /// + public ShaderNodeDescriptionContext description { get; } + + /// + /// Gets the builder shared by nodes in this typed region. + /// + public ShaderIrBuilder builder { get; } + + /// + /// Gets connected values keyed by semantic input port identity, never connection order. + /// + public IReadOnlyDictionary inputs { get; } + + /// + /// Requires one connected input without implicit defaults or positional rebinding. + /// + /// + /// Exact semantic input port identity. + /// + /// + /// The connected typed value. + /// + public ShaderIrValue Input(string id) + => inputs.TryGetValue(id, out ShaderIrValue? value) + ? value + : throw new InvalidOperationException($"Input '{id}' is not connected."); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodePort.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodePort.cs new file mode 100644 index 000000000..448660749 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderNodePort.cs @@ -0,0 +1,25 @@ +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Declares a typed shader port independently of editor presentation and backend source syntax. +/// +/// +/// Stable node-local port identity. +/// +/// +/// Complete value type, including all aggregate fields. +/// +/// +/// Input or output value flow. +/// +/// +/// Whether an input must be connected; alternative aggregate/member inputs validate in their compiler. +/// +public sealed record ShaderNodePort( + string id, + ShaderSourceType type, + GraphPortDirection direction, + bool required = true +); diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderValueNodeCompilers.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSampleNodeCompiler.cs similarity index 59% rename from src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderValueNodeCompilers.cs rename to src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSampleNodeCompiler.cs index d71021e5e..6aeb24a23 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderValueNodeCompilers.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSampleNodeCompiler.cs @@ -4,52 +4,6 @@ namespace Inno.Rendering.Shaders; -/// -/// Extracts one statically selected component from a vector or matrix. -/// -public sealed class ShaderExtractNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionID => "inno.shader.extract"; - - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - { - ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float4")); - var builder = new ShaderIrBuilder(); - ShaderIrValue member = builder.Extract(builder.Input("input", type), context.Read("index", 0)); - return [ - new ShaderNodePort("input", type, GraphPortDirection.Input), - new ShaderNodePort("value", member.type, GraphPortDirection.Output) - ]; - } - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary - { - ["value"] = context.builder.Extract(context.Input("input"), context.description.Read("index", 0)) - }; -} - /// /// Samples a graph-connected texture with implicit derivatives or an explicit level of detail. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSelectNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSelectNodeCompiler.cs new file mode 100644 index 000000000..37d750504 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSelectNodeCompiler.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Selects between equal typed values; all producer effects remain evaluated before selection. +/// +public sealed class ShaderSelectNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.select"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + ShaderSourceType type = ShaderSourceType.Atomic(context.Read("type", "float")); + return [ + new ShaderNodePort("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), + new ShaderNodePort("true", type, GraphPortDirection.Input), + new ShaderNodePort("false", type, GraphPortDirection.Input), + new ShaderNodePort("value", type, GraphPortDirection.Output) + ]; + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary + { + ["value"] = context.builder.Select(context.Input("condition"), context.Input("true"), context.Input("false")) + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSourceNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSourceNodeCompiler.cs new file mode 100644 index 000000000..021566b48 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderSourceNodeCompiler.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Lowers a parsed function module with name-based ports and explicit aggregate/member connection alternatives. +/// +public sealed class ShaderSourceNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.source"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + { + ShaderSourceFunction function = RequireModule(context).function!; + List ports = []; + foreach (ShaderSourceParameter parameter in function.parameters) + { + if (parameter.direction != ShaderSourceParameterDirection.Output) + { + Add("input." + parameter.name, parameter.type, GraphPortDirection.Input); + } + if (parameter.direction != ShaderSourceParameterDirection.Input) + { + Add("output." + parameter.name, parameter.type, GraphPortDirection.Output); + } + } + if (function.returnType.id != "void") + { + Add("return", function.returnType, GraphPortDirection.Output); + } + return ports.AsReadOnly(); + void Add( + string name, + ShaderSourceType type, + GraphPortDirection direction + ) { + ports.Add(new ShaderNodePort(name, type, direction, required: false)); + foreach (ShaderSourceField field in type.fields) + { + Add(name + "." + field.name, field.type, direction); + } + } + } + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + ShaderSourceModuleAnalysis module = RequireModule(context.description); + var arguments = new Dictionary(StringComparer.Ordinal); + foreach (ShaderSourceParameter parameter in module.function!.parameters) + { + if (parameter.direction != ShaderSourceParameterDirection.Output) + { + arguments.Add(parameter.name, Resolve("input." + parameter.name, parameter.type)); + } + } + IReadOnlyDictionary values = context.builder.Call(module, context.description.implementationID, arguments); + var outputs = new Dictionary(StringComparer.Ordinal); + foreach ((string name, ShaderIrValue value) in values) + { + Add(name, value); + } + return outputs; + + ShaderIrValue Resolve( + string name, + ShaderSourceType type + ) { + if (context.inputs.TryGetValue(name, out ShaderIrValue? aggregate)) + { + if (context.inputs.Keys.Any(key => key.StartsWith(name + ".", StringComparison.Ordinal))) + { + throw new InvalidOperationException( + $"'{name}' connects both its aggregate and a member; choose one representation explicitly." + ); + } + return aggregate; + } + if (type.fields.Count == 0) + { + return context.Input(name); + } + return context.builder.Construct(type, type.fields.Select(field => Resolve(name + "." + field.name, field.type)).ToArray()); + } + + void Add( + string name, + ShaderIrValue value + ) { + outputs.Add(name, value); + for (int index = 0; index < value.type.fields.Count; index++) + { + Add(name + "." + value.type.fields[index].name, context.builder.Extract(value, index)); + } + } + } + + private static ShaderSourceModuleAnalysis RequireModule(ShaderNodeDescriptionContext context) + { + ShaderSourceModuleAnalysis? module = context.sourceModule; + if (module is null) + { + throw new InvalidOperationException( + "The source module is unassigned or unavailable; its stored reference and connections must remain intact." + ); + } + if (!module.succeeded) + { + throw new InvalidOperationException( + "The source module has no valid common interface: " + + string.Join("; ", module.diagnostics.Select(static value => value.message)) + ); + } + return module; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStageInputNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStageInputNodeCompiler.cs new file mode 100644 index 000000000..ccd26045d --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStageInputNodeCompiler.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Reads one target-assigned stage/resource input without choosing a native variable name. +/// +public sealed class ShaderStageInputNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => "inno.shader.stage-input"; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => [new ShaderNodePort("value", RequireBinding(context).type, GraphPortDirection.Output)]; + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + ShaderIrStageInput input = RequireBinding(context.description); + return new Dictionary { ["value"] = context.builder.Input(input.id, input.type) }; + } + + private static ShaderIrStageInput RequireBinding(ShaderNodeDescriptionContext context) + => context.stageInput ?? throw new InvalidOperationException("The target has not resolved this stage input binding."); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageAtomicAddNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageAtomicAddNodeCompiler.cs new file mode 100644 index 000000000..5fa4708bb --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageAtomicAddNodeCompiler.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderStorageAtomicAddNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// +public string definitionID => "inno.shader.storage-atomic-add"; + + /// + /// Retrieves the current ports from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, true, true); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary +{ + ["previous"] = context.builder.AtomicAddStorage(context.Input("resource"), context.Input("coordinate"), context.Input("value")), + ["then"] = context.builder.Constant(true) +}; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageLoadNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageLoadNodeCompiler.cs new file mode 100644 index 000000000..4cd536535 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageLoadNodeCompiler.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderStorageLoadNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// +public string definitionID => "inno.shader.storage-load"; + + /// + /// Retrieves the current ports from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, false, false); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => new Dictionary +{ + ["value"] = context.builder.LoadStorage(context.Input("resource"), context.Input("coordinate")), + ["then"] = context.builder.Constant(true) +}; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs deleted file mode 100644 index 49a4a8a5e..000000000 --- a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageNodeCompilers.cs +++ /dev/null @@ -1,189 +0,0 @@ -using System; -using System.Collections.Generic; -using Inno.Core.Graphs; - -namespace Inno.Rendering.Shaders; - -internal static class StorageNodePorts -{ - internal static ShaderSourceType Resource(ShaderNodeDescriptionContext context) - => context - .Read( - "resource", - new ShaderGraphType { isStorage = true, storageElement = new() { id = "float4" }, access = RenderStorageAccess.ReadWrite } - ) - .CreateType(); - - internal static ShaderSourceType Coordinate(ShaderStorageType storage) - => ShaderSourceType.Atomic( - !storage.isImage ? "uint" : storage.array || storage.dimension == RenderTextureDimension.Texture3D ? "int3" : "int2" - ); - - internal static IReadOnlyList Describe( - ShaderNodeDescriptionContext context, - bool write, - bool atomic - ) { - ShaderSourceType type = Resource(context); - ShaderStorageType storage = type.storage ?? throw new ArgumentException("A storage node requires a storage resource descriptor."); - List ports = - [ - new ShaderNodePort("resource", type, GraphPortDirection.Input), - new ShaderNodePort("coordinate", Coordinate(storage), GraphPortDirection.Input), - new ShaderNodePort("after", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input, false), - new ShaderNodePort("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output) - ]; - if (write) - { - ports.Add(new ShaderNodePort("value", storage.valueType, GraphPortDirection.Input)); - } - if (!write || atomic) - { - ports.Add(new ShaderNodePort(atomic ? "previous" : "value", storage.valueType, GraphPortDirection.Output)); - } - return ports; - } -} - -internal sealed class ShaderStorageLoadNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// -public string definitionID => "inno.shader.storage-load"; - - /// - /// Retrieves the current ports from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, false, false); - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary -{ - ["value"] = context.builder.LoadStorage(context.Input("resource"), context.Input("coordinate")), - ["then"] = context.builder.Constant(true) -}; -} - -internal sealed class ShaderStorageStoreNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// -public string definitionID => "inno.shader.storage-store"; - - /// - /// Retrieves the current ports from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, true, false); - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - context.builder.StoreStorage(context.Input("resource"), context.Input("coordinate"), context.Input("value")); - return new Dictionary { ["then"] = context.builder.Constant(true) }; - } -} - -internal sealed class ShaderStorageAtomicAddNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// -public string definitionID => "inno.shader.storage-atomic-add"; - - /// - /// Retrieves the current ports from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, true, true); - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => new Dictionary -{ - ["previous"] = context.builder.AtomicAddStorage(context.Input("resource"), context.Input("coordinate"), context.Input("value")), - ["then"] = context.builder.Constant(true) -}; -} - -internal sealed class ShaderDiscardNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// -public string definitionID => "inno.shader.discard"; - - /// - /// Retrieves the current ports from authoritative state. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => [ - new ShaderNodePort("condition", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input), - new ShaderNodePort("after", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input, false), - new ShaderNodePort("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output) - ]; - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// -public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - { - context.builder.Discard(context.Input("condition")); - return new Dictionary { ["then"] = context.builder.Constant(true) }; - } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageStoreNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageStoreNodeCompiler.cs new file mode 100644 index 000000000..292b3f01c --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/ShaderStorageStoreNodeCompiler.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderStorageStoreNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// +public string definitionID => "inno.shader.storage-store"; + + /// + /// Retrieves the current ports from authoritative state. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => StorageNodePorts.Describe(context, true, false); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// +public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + { + context.builder.StoreStorage(context.Input("resource"), context.Input("coordinate"), context.Input("value")); + return new Dictionary { ["then"] = context.builder.Constant(true) }; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Compilation/StorageNodePorts.cs b/src/services/rendering/Inno.Rendering.Shaders/Compilation/StorageNodePorts.cs new file mode 100644 index 000000000..cc4400a88 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Compilation/StorageNodePorts.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +internal static class StorageNodePorts +{ + internal static ShaderSourceType Resource(ShaderNodeDescriptionContext context) + => context + .Read( + "resource", + new ShaderGraphType { isStorage = true, storageElement = new() { id = "float4" }, access = RenderStorageAccess.ReadWrite } + ) + .CreateType(); + + internal static ShaderSourceType Coordinate(ShaderStorageType storage) + => ShaderSourceType.Atomic( + !storage.isImage ? "uint" : storage.array || storage.dimension == RenderTextureDimension.Texture3D ? "int3" : "int2" + ); + + internal static IReadOnlyList Describe( + ShaderNodeDescriptionContext context, + bool write, + bool atomic + ) { + ShaderSourceType type = Resource(context); + ShaderStorageType storage = type.storage ?? throw new ArgumentException("A storage node requires a storage resource descriptor."); + List ports = + [ + new ShaderNodePort("resource", type, GraphPortDirection.Input), + new ShaderNodePort("coordinate", Coordinate(storage), GraphPortDirection.Input), + new ShaderNodePort("after", ShaderSourceType.Atomic("bool"), GraphPortDirection.Input, false), + new ShaderNodePort("then", ShaderSourceType.Atomic("bool"), GraphPortDirection.Output) + ]; + if (write) + { + ports.Add(new ShaderNodePort("value", storage.valueType, GraphPortDirection.Input)); + } + if (!write || atomic) + { + ports.Add(new ShaderNodePort(atomic ? "previous" : "value", storage.valueType, GraphPortDirection.Output)); + } + return ports; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphCallNodeCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphCallNodeCompiler.cs new file mode 100644 index 000000000..f541682b0 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphCallNodeCompiler.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes graph-authored node references before they are expanded or consumed by a Target. +/// +public sealed class ShaderGraphCallNodeCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => ShaderGraphNodes.C_CALL_DEFINITION_ID; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => context.Read(ShaderGraphNodes.C_INTERFACE_KEY, new ShaderGraphNodeInterface()).GetPorts(); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => throw new InvalidOperationException("A graph-authored node must be expanded or consumed by its Shader Target before lowering."); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs index 7e0f52f42..631eae61c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphClipboard.cs @@ -244,27 +244,3 @@ .. source.properties.Where(property => ( return new(candidate, remap.Values.ToArray()); } } - -/// -/// Contains a detached paste candidate and its newly allocated node identities. -/// -public sealed class ShaderGraphPasteResult -{ - internal ShaderGraphPasteResult( - GraphDocument graph, - GraphNodeID[] nodes - ) { - this.document = graph; - this.insertedNodes = Array.AsReadOnly(nodes); - } - - /// - /// Gets the complete detached candidate; the caller owns its subsequent edits. - /// - public GraphDocument document { get; } - - /// - /// Gets new identities suitable for selecting the pasted nodes. - /// - public IReadOnlyList insertedNodes { get; } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs index e7761faec..463e8ce69 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphDocument.cs @@ -239,109 +239,3 @@ public static T Read( SerializationContext context ) => node.TryGetValue(key, out GraphSerializedValue? value) ? Decode(value!, serialization, context) : defaultValue; } - -/// -/// Stores one stage's explicit output interface and compute dimensions inside its output node. -/// -public sealed class ShaderGraphStageSettings : ISerializable -{ - /// - /// Gets or sets the programmable stage. - /// - [SerializableProperty] - public ShaderStage stage { get; set; } = ShaderStage.Fragment; - - /// - /// Gets or sets output ports and their GPU destinations. - /// - [SerializableProperty] - public ShaderGraphOutput[] outputs { get; set; } = []; - - /// - /// Gets or sets compute workgroup width. - /// - [SerializableProperty] - public int threadsX { get; set; } = 1; - - /// - /// Gets or sets compute workgroup height. - /// - [SerializableProperty] - public int threadsY { get; set; } = 1; - - /// - /// Gets or sets compute workgroup depth. - /// - [SerializableProperty] - public int threadsZ { get; set; } = 1; -} - -/// -/// Stores one stable output port's destination, independent of adapter source syntax. -/// -public struct ShaderGraphOutput -{ - /// - /// Gets or sets the stable input port identity on the stage output node. - /// - public string id { get; set; } - - /// - /// Gets or sets the GPU destination category. - /// - public ShaderIrOutputKind kind { get; set; } - - /// - /// Gets or sets the varying semantic; empty for fixed position, color or depth outputs. - /// - public string semantic { get; set; } - - /// - /// Gets or sets the varying or attachment index. - /// - public int location { get; set; } -} - -/// -/// Stores a stage input node's logical interface without native names or GPU handles. -/// -public sealed class ShaderGraphInputSettings : ISerializable -{ - /// - /// Gets or sets the stable logical binding identity. - /// - [SerializableProperty] - public string id { get; set; } = "input"; - - /// - /// Gets or sets the complete neutral type descriptor. - /// - [SerializableProperty] - public ShaderGraphType type { get; set; } = new(); - - /// - /// Gets or sets the stage input category. - /// - [SerializableProperty] - public ShaderIrInputKind kind { get; set; } - - /// - /// Gets or sets the target semantic, not a native expression. - /// - [SerializableProperty] - public string semantic { get; set; } = "position"; - - /// - /// Gets or sets the interface index. - /// - [SerializableProperty] - public int location { get; set; } - - /// - /// Validates the persisted descriptor and freezes its stage binding. - /// - /// - /// An immutable backend-neutral input binding. - /// - public ShaderIrStageInput CreateBinding() => new(id, type.CreateType(), kind, semantic, location); -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettings.cs new file mode 100644 index 000000000..d9513b4cb --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettings.cs @@ -0,0 +1,47 @@ +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores a stage input node's logical interface without native names or GPU handles. +/// +public sealed class ShaderGraphInputSettings : ISerializable +{ + /// + /// Gets or sets the stable logical binding identity. + /// + [SerializableProperty] + public string id { get; set; } = "input"; + + /// + /// Gets or sets the complete neutral type descriptor. + /// + [SerializableProperty] + public ShaderGraphType type { get; set; } = new(); + + /// + /// Gets or sets the stage input category. + /// + [SerializableProperty] + public ShaderIrInputKind kind { get; set; } + + /// + /// Gets or sets the target semantic, not a native expression. + /// + [SerializableProperty] + public string semantic { get; set; } = "position"; + + /// + /// Gets or sets the interface index. + /// + [SerializableProperty] + public int location { get; set; } + + /// + /// Validates the persisted descriptor and freezes its stage binding. + /// + /// + /// An immutable backend-neutral input binding. + /// + public ShaderIrStageInput CreateBinding() => new(id, type.CreateType(), kind, semantic, location); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettingsConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettingsConverter.cs new file mode 100644 index 000000000..aec6986b6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphInputSettingsConverter.cs @@ -0,0 +1,46 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphInputSettingsConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphInputSettings value + ) { + writer.Write("id", value.id); + writer.Write("type", value.type); + writer.Write("kind", value.kind); + writer.Write("semantic", value.semantic); + writer.Write("location", value.location); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph input settings that represents the completed operation. + /// + public override ShaderGraphInputSettings Read(SerializationReader reader) + => new() + { + id = reader.Read("id"), + type = reader.Read("type"), + kind = reader.Read("kind"), + semantic = reader.Read("semantic"), + location = reader.Read("location") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteralConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteralConverter.cs new file mode 100644 index 000000000..5f3a24237 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphLiteralConverter.cs @@ -0,0 +1,36 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphLiteralConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphLiteral value + ) { + writer.Write("type", value.type); + writer.Write("scalarBits", value.scalarBits); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph literal that represents the completed operation. + /// + public override ShaderGraphLiteral Read(SerializationReader reader) + => new() { type = reader.Read("type"), scalarBits = reader.Read("scalarBits") }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettings.cs new file mode 100644 index 000000000..de1402364 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettings.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores values supplied by callers to a graph-authored node. +/// +public sealed class ShaderGraphNodeInputSettings : ISerializable +{ + /// + /// Gets or sets values supplied by callers and exposed as outputs inside the node graph. + /// + [SerializableProperty] + public ShaderGraphNodePortDefinition[] ports { get; set; } = []; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettingsConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettingsConverter.cs new file mode 100644 index 000000000..b9cc2433e --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputSettingsConverter.cs @@ -0,0 +1,36 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphNodeInputSettingsConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphNodeInputSettings value + ) => writer.Write("ports", value.ports); + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph node input settings that represents the completed operation. + /// + public override ShaderGraphNodeInputSettings Read(SerializationReader reader) + => new() + { + ports = reader.Read("ports") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputsCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputsCompiler.cs new file mode 100644 index 000000000..c68992d21 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInputsCompiler.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes the multi-port external inputs while editing a graph-authored node asset. +/// +public sealed class ShaderGraphNodeInputsCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => ShaderGraphNodes.C_INPUT_DEFINITION_ID; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => context.Read(ShaderGraphDocument.C_SETTINGS_KEY, new ShaderGraphNodeInputSettings()).ports + .Select(static value => value.ToPort(GraphPortDirection.Output)) + .ToArray(); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => throw new InvalidOperationException("Node Inputs exist only inside a graph-authored node definition."); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterface.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterface.cs new file mode 100644 index 000000000..d74120a05 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterface.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Freezes the complete public interface resolved from one graph-authored node asset. +/// +public sealed class ShaderGraphNodeInterface : ISerializable +{ + /// + /// Gets or sets the node title displayed to authors. + /// + [SerializableProperty] + public string displayName { get; set; } = "Graph Node"; + + /// + /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. + /// + [SerializableProperty] + public string createPath { get; set; } = "General"; + + /// + /// Gets or sets the deterministic order within the creation catalog. + /// + [SerializableProperty] + public int createOrder { get; set; } + + /// + /// Gets or sets whether the graph is inline computation or a Target-owned output boundary. + /// + [SerializableProperty] + public ShaderGraphNodeKind kind { get; set; } + + /// + /// Gets or sets whether an inline function is pure or intentionally emits ordered effects. + /// + [SerializableProperty] + public ShaderGraphNodeEffect effect { get; set; } + + /// + /// Gets or sets the Target-owned role for a domain output. + /// + [SerializableProperty] + public string role { get; set; } = string.Empty; + + /// + /// Gets or sets externally supplied inputs. + /// + [SerializableProperty] + public ShaderGraphNodePortDefinition[] inputs { get; set; } = []; + + /// + /// Gets or sets externally visible results. + /// + [SerializableProperty] + public ShaderGraphNodePortDefinition[] outputs { get; set; } = []; + + /// + /// Gets detached typed ports in deterministic input-then-output order. + /// + /// + /// A provider-free port snapshot suitable for Editor presentation and validation. + /// + public IReadOnlyList GetPorts() + => inputs.Select(static value => value.ToPort(GraphPortDirection.Input)) + .Concat(outputs.Select(static value => value.ToPort(GraphPortDirection.Output))) + .ToArray(); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterfaceConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterfaceConverter.cs new file mode 100644 index 000000000..df4cc4f8d --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeInterfaceConverter.cs @@ -0,0 +1,52 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphNodeInterfaceConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphNodeInterface value + ) { + writer.Write("displayName", value.displayName); + writer.Write("createPath", value.createPath); + writer.Write("createOrder", value.createOrder); + writer.Write("kind", value.kind); + writer.Write("effect", value.effect); + writer.Write("role", value.role); + writer.Write("inputs", value.inputs); + writer.Write("outputs", value.outputs); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph node interface that represents the completed operation. + /// + public override ShaderGraphNodeInterface Read(SerializationReader reader) + => new() + { + displayName = reader.Read("displayName"), + createPath = reader.Read("createPath"), + createOrder = reader.Read("createOrder"), + kind = reader.Read("kind"), + effect = reader.Read("effect"), + role = reader.Read("role"), + inputs = reader.Read("inputs"), + outputs = reader.Read("outputs") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettings.cs new file mode 100644 index 000000000..0f3f46129 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettings.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores values returned by a graph-authored function node. +/// +public sealed class ShaderGraphNodeOutputSettings : ISerializable +{ + /// + /// Gets or sets values collected inside the node graph and exposed as outputs to callers. + /// + [SerializableProperty] + public ShaderGraphNodePortDefinition[] ports { get; set; } = []; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettingsConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettingsConverter.cs new file mode 100644 index 000000000..d38439f0e --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputSettingsConverter.cs @@ -0,0 +1,33 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphNodeOutputSettingsConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphNodeOutputSettings value + ) => writer.Write("ports", value.ports); + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph node output settings that represents the completed operation. + /// + public override ShaderGraphNodeOutputSettings Read(SerializationReader reader) + => new() { ports = reader.Read("ports") }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputsCompiler.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputsCompiler.cs new file mode 100644 index 000000000..9b83e15d9 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeOutputsCompiler.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes the multi-port returned values while editing a graph-authored function node asset. +/// +public sealed class ShaderGraphNodeOutputsCompiler : IShaderNodeCompiler +{ + /// + /// Gets the definition id text used by the current instance. + /// + public string definitionID => ShaderGraphNodes.C_OUTPUT_DEFINITION_ID; + + /// + /// Gets a ports required by the implemented contract. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) + => context.Read(ShaderGraphDocument.C_SETTINGS_KEY, new ShaderGraphNodeOutputSettings()).ports + .Select(static value => value.ToPort(GraphPortDirection.Input)) + .ToArray(); + + /// + /// Lowers this graph node to typed shader IR after validating its inputs. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// An immutable snapshot of the values selected by the operation. + /// + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) + => throw new InvalidOperationException("Node Outputs exist only inside a graph-authored node definition."); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinition.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinition.cs new file mode 100644 index 000000000..b0424044c --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinition.cs @@ -0,0 +1,31 @@ +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Declares one stable, typed port on a graph-authored node interface. +/// +public sealed class ShaderGraphNodePortDefinition : ISerializable +{ + /// + /// Gets or sets the stable node-local port identity. + /// + [SerializableProperty] + public string id { get; set; } = "value"; + + /// + /// Gets or sets the complete backend-neutral value type. + /// + [SerializableProperty] + public ShaderGraphType type { get; set; } = new() { id = "float" }; + + /// + /// Gets or sets whether callers must connect the input instead of using an explicit/default zero. + /// + [SerializableProperty] + public bool required { get; set; } = true; + + internal ShaderNodePort ToPort(GraphPortDirection direction) + => new(id, type.CreateType(), direction, direction == GraphPortDirection.Input && required); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinitionConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinitionConverter.cs new file mode 100644 index 000000000..3f095cbe8 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodePortDefinitionConverter.cs @@ -0,0 +1,42 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphNodePortDefinitionConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphNodePortDefinition value + ) { + writer.Write("id", value.id); + writer.Write("type", value.type); + writer.Write("required", value.required); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph node port definition that represents the completed operation. + /// + public override ShaderGraphNodePortDefinition Read(SerializationReader reader) + => new() + { + id = reader.Read("id"), + type = reader.Read("type"), + required = reader.Read("required") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettings.cs new file mode 100644 index 000000000..aba37b9f2 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettings.cs @@ -0,0 +1,45 @@ +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores graph-level identity and catalog metadata for a reusable Shader node. +/// +public sealed class ShaderGraphNodeSettings : ISerializable +{ + /// + /// Gets or sets the node title displayed to authors. + /// + [SerializableProperty] + public string displayName { get; set; } = "Graph Node"; + + /// + /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. + /// + [SerializableProperty] + public string createPath { get; set; } = "General"; + + /// + /// Gets or sets the deterministic order within the creation catalog. + /// + [SerializableProperty] + public int createOrder { get; set; } + + /// + /// Gets or sets how a reference to this graph participates in compilation. + /// + [SerializableProperty] + public ShaderGraphNodeKind kind { get; set; } + + /// + /// Gets or sets the observable computation behavior of an inline function. + /// + [SerializableProperty] + public ShaderGraphNodeEffect effect { get; set; } + + /// + /// Gets or sets the domain role consumed by a Target; empty for ordinary inline functions. + /// + [SerializableProperty] + public string role { get; set; } = string.Empty; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettingsConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettingsConverter.cs new file mode 100644 index 000000000..ce984435e --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodeSettingsConverter.cs @@ -0,0 +1,48 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphNodeSettingsConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphNodeSettings value + ) { + writer.Write("displayName", value.displayName); + writer.Write("createPath", value.createPath); + writer.Write("createOrder", value.createOrder); + writer.Write("kind", value.kind); + writer.Write("effect", value.effect); + writer.Write("role", value.role); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph node settings that represents the completed operation. + /// + public override ShaderGraphNodeSettings Read(SerializationReader reader) + => new() + { + displayName = reader.Read("displayName"), + createPath = reader.Read("createPath"), + createOrder = reader.Read("createOrder"), + kind = reader.Read("kind"), + effect = reader.Read("effect"), + role = reader.Read("role") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs index d05d5ec31..70892d88c 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphNodes.cs @@ -7,194 +7,6 @@ namespace Inno.Rendering.Shaders; -/// -/// Chooses whether a graph-authored node is inlined or consumed by a domain Target. -/// -public enum ShaderGraphNodeKind -{ - /// - /// Inlines the node graph into the caller before Target expansion and typed lowering. - /// - Function, - /// - /// Leaves the node as a typed domain boundary for the selected Shader Target. - /// - DomainOutput -} - -/// -/// Declares whether a graph-authored function is pure or intentionally emits ordered effects. -/// -public enum ShaderGraphNodeEffect -{ - /// - /// The function only computes returned values and therefore requires at least one output. - /// - Pure, - /// - /// The function may contain ordered GPU effects and can intentionally expose no returned values. - /// - SideEffect -} - -/// -/// Stores graph-level identity and catalog metadata for a reusable Shader node. -/// -public sealed class ShaderGraphNodeSettings : ISerializable -{ - /// - /// Gets or sets the node title displayed to authors. - /// - [SerializableProperty] - public string displayName { get; set; } = "Graph Node"; - - /// - /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. - /// - [SerializableProperty] - public string createPath { get; set; } = "General"; - - /// - /// Gets or sets the deterministic order within the creation catalog. - /// - [SerializableProperty] - public int createOrder { get; set; } - - /// - /// Gets or sets how a reference to this graph participates in compilation. - /// - [SerializableProperty] - public ShaderGraphNodeKind kind { get; set; } - - /// - /// Gets or sets the observable computation behavior of an inline function. - /// - [SerializableProperty] - public ShaderGraphNodeEffect effect { get; set; } - - /// - /// Gets or sets the domain role consumed by a Target; empty for ordinary inline functions. - /// - [SerializableProperty] - public string role { get; set; } = string.Empty; -} - -/// -/// Declares one stable, typed port on a graph-authored node interface. -/// -public sealed class ShaderGraphNodePortDefinition : ISerializable -{ - /// - /// Gets or sets the stable node-local port identity. - /// - [SerializableProperty] - public string id { get; set; } = "value"; - - /// - /// Gets or sets the complete backend-neutral value type. - /// - [SerializableProperty] - public ShaderGraphType type { get; set; } = new() { id = "float" }; - - /// - /// Gets or sets whether callers must connect the input instead of using an explicit/default zero. - /// - [SerializableProperty] - public bool required { get; set; } = true; - - internal ShaderNodePort ToPort(GraphPortDirection direction) - => new(id, type.CreateType(), direction, direction == GraphPortDirection.Input && required); -} - -/// -/// Stores values supplied by callers to a graph-authored node. -/// -public sealed class ShaderGraphNodeInputSettings : ISerializable -{ - /// - /// Gets or sets values supplied by callers and exposed as outputs inside the node graph. - /// - [SerializableProperty] - public ShaderGraphNodePortDefinition[] ports { get; set; } = []; -} - -/// -/// Stores values returned by a graph-authored function node. -/// -public sealed class ShaderGraphNodeOutputSettings : ISerializable -{ - /// - /// Gets or sets values collected inside the node graph and exposed as outputs to callers. - /// - [SerializableProperty] - public ShaderGraphNodePortDefinition[] ports { get; set; } = []; -} - -/// -/// Freezes the complete public interface resolved from one graph-authored node asset. -/// -public sealed class ShaderGraphNodeInterface : ISerializable -{ - /// - /// Gets or sets the node title displayed to authors. - /// - [SerializableProperty] - public string displayName { get; set; } = "Graph Node"; - - /// - /// Gets or sets the slash-separated creation catalog beneath Graph Nodes. - /// - [SerializableProperty] - public string createPath { get; set; } = "General"; - - /// - /// Gets or sets the deterministic order within the creation catalog. - /// - [SerializableProperty] - public int createOrder { get; set; } - - /// - /// Gets or sets whether the graph is inline computation or a Target-owned output boundary. - /// - [SerializableProperty] - public ShaderGraphNodeKind kind { get; set; } - - /// - /// Gets or sets whether an inline function is pure or intentionally emits ordered effects. - /// - [SerializableProperty] - public ShaderGraphNodeEffect effect { get; set; } - - /// - /// Gets or sets the Target-owned role for a domain output. - /// - [SerializableProperty] - public string role { get; set; } = string.Empty; - - /// - /// Gets or sets externally supplied inputs. - /// - [SerializableProperty] - public ShaderGraphNodePortDefinition[] inputs { get; set; } = []; - - /// - /// Gets or sets externally visible results. - /// - [SerializableProperty] - public ShaderGraphNodePortDefinition[] outputs { get; set; } = []; - - /// - /// Gets detached typed ports in deterministic input-then-output order. - /// - /// - /// A provider-free port snapshot suitable for Editor presentation and validation. - /// - public IReadOnlyList GetPorts() - => inputs.Select(static value => value.ToPort(GraphPortDirection.Input)) - .Concat(outputs.Select(static value => value.ToPort(GraphPortDirection.Output))) - .ToArray(); -} - /// /// Reads and expands reusable node graphs without retaining assets or provider instances. /// @@ -754,110 +566,31 @@ string direction } /// -/// Describes graph-authored node references before they are expanded or consumed by a Target. -/// -public sealed class ShaderGraphCallNodeCompiler : IShaderNodeCompiler -{ - /// - /// Gets the definition id text used by the current instance. - /// - public string definitionID => ShaderGraphNodes.C_CALL_DEFINITION_ID; - - /// - /// Gets a ports required by the implemented contract. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => context.Read(ShaderGraphNodes.C_INTERFACE_KEY, new ShaderGraphNodeInterface()).GetPorts(); - - /// - /// Lowers this graph node to typed shader IR after validating its inputs. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => throw new InvalidOperationException("A graph-authored node must be expanded or consumed by its Shader Target before lowering."); -} - -/// -/// Describes the multi-port external inputs while editing a graph-authored node asset. +/// Chooses whether a graph-authored node is inlined or consumed by a domain Target. /// -public sealed class ShaderGraphNodeInputsCompiler : IShaderNodeCompiler +public enum ShaderGraphNodeKind { /// - /// Gets the definition id text used by the current instance. - /// - public string definitionID => ShaderGraphNodes.C_INPUT_DEFINITION_ID; - - /// - /// Gets a ports required by the implemented contract. + /// Inlines the node graph into the caller before Target expansion and typed lowering. /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => context.Read(ShaderGraphDocument.C_SETTINGS_KEY, new ShaderGraphNodeInputSettings()).ports - .Select(static value => value.ToPort(GraphPortDirection.Output)) - .ToArray(); - + Function, /// - /// Lowers this graph node to typed shader IR after validating its inputs. + /// Leaves the node as a typed domain boundary for the selected Shader Target. /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => throw new InvalidOperationException("Node Inputs exist only inside a graph-authored node definition."); + DomainOutput } /// -/// Describes the multi-port returned values while editing a graph-authored function node asset. +/// Declares whether a graph-authored function is pure or intentionally emits ordered effects. /// -public sealed class ShaderGraphNodeOutputsCompiler : IShaderNodeCompiler +public enum ShaderGraphNodeEffect { /// - /// Gets the definition id text used by the current instance. - /// - public string definitionID => ShaderGraphNodes.C_OUTPUT_DEFINITION_ID; - - /// - /// Gets a ports required by the implemented contract. + /// The function only computes returned values and therefore requires at least one output. /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) - => context.Read(ShaderGraphDocument.C_SETTINGS_KEY, new ShaderGraphNodeOutputSettings()).ports - .Select(static value => value.ToPort(GraphPortDirection.Input)) - .ToArray(); - + Pure, /// - /// Lowers this graph node to typed shader IR after validating its inputs. + /// The function may contain ordered GPU effects and can intentionally expose no returned values. /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// An immutable snapshot of the values selected by the operation. - /// - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) - => throw new InvalidOperationException("Node Outputs exist only inside a graph-authored node definition."); + SideEffect } diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphOutput.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphOutput.cs new file mode 100644 index 000000000..f29715989 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphOutput.cs @@ -0,0 +1,27 @@ +namespace Inno.Rendering.Shaders; + +/// +/// Stores one stable output port's destination, independent of adapter source syntax. +/// +public struct ShaderGraphOutput +{ + /// + /// Gets or sets the stable input port identity on the stage output node. + /// + public string id { get; set; } + + /// + /// Gets or sets the GPU destination category. + /// + public ShaderIrOutputKind kind { get; set; } + + /// + /// Gets or sets the varying semantic; empty for fixed position, color or depth outputs. + /// + public string semantic { get; set; } + + /// + /// Gets or sets the varying or attachment index. + /// + public int location { get; set; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPass.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPass.cs new file mode 100644 index 000000000..726068292 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPass.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Rendering.Shaders; + +/// +/// Freezes the graph-lowered stages of one material-selectable GPU pass. +/// +public sealed class ShaderGraphPass +{ + /// + /// Captures a pass's ordered typed stages. + /// + /// + /// Exact pass identity in the program contract. + /// + /// + /// Complete raster or compute stage set. + /// + public ShaderGraphPass( + string name, + IEnumerable stages + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(stages); + this.name = name; + this.stages = Array.AsReadOnly(stages.ToArray()); + } + + /// + /// Gets the stable pass identity. + /// + public string name { get; } + + /// + /// Gets immutable graph-lowered stages. + /// + public IReadOnlyList stages { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPassProgram.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPassProgram.cs new file mode 100644 index 000000000..31300e676 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPassProgram.cs @@ -0,0 +1,17 @@ +namespace Inno.Rendering.Shaders; + +/// +/// References shared stage output identities from a material-selectable pass. +/// +public struct ShaderGraphPassProgram +{ + /// + /// Gets or sets the exact pass identity in the runtime shader definition. + /// + public string pass { get; set; } + + /// + /// Gets or sets stable stage output node identities; computation remains owned by those nodes. + /// + public string[] stages { get; set; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPasteResult.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPasteResult.cs new file mode 100644 index 000000000..5d6ff47ec --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPasteResult.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Graphs; + +namespace Inno.Rendering.Shaders; + +/// +/// Contains a detached paste candidate and its newly allocated node identities. +/// +public sealed class ShaderGraphPasteResult +{ + internal ShaderGraphPasteResult( + GraphDocument graph, + GraphNodeID[] nodes + ) { + this.document = graph; + this.insertedNodes = Array.AsReadOnly(nodes); + } + + /// + /// Gets the complete detached candidate; the caller owns its subsequent edits. + /// + public GraphDocument document { get; } + + /// + /// Gets new identities suitable for selecting the pasted nodes. + /// + public IReadOnlyList insertedNodes { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgram.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramResult.cs similarity index 54% rename from src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgram.cs rename to src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramResult.cs index 345befc46..f67105029 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgram.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphProgramResult.cs @@ -5,41 +5,6 @@ namespace Inno.Rendering.Shaders; -/// -/// Freezes the graph-lowered stages of one material-selectable GPU pass. -/// -public sealed class ShaderGraphPass -{ - /// - /// Captures a pass's ordered typed stages. - /// - /// - /// Exact pass identity in the program contract. - /// - /// - /// Complete raster or compute stage set. - /// - public ShaderGraphPass( - string name, - IEnumerable stages - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - ArgumentNullException.ThrowIfNull(stages); - this.name = name; - this.stages = Array.AsReadOnly(stages.ToArray()); - } - - /// - /// Gets the stable pass identity. - /// - public string name { get; } - - /// - /// Gets immutable graph-lowered stages. - /// - public IReadOnlyList stages { get; } -} - /// /// Contains the result of lowering an entire shader graph, before target-native compilation. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs index d72660660..ebf7f2219 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphPrograms.cs @@ -7,22 +7,6 @@ namespace Inno.Rendering.Shaders; -/// -/// References shared stage output identities from a material-selectable pass. -/// -public struct ShaderGraphPassProgram -{ - /// - /// Gets or sets the exact pass identity in the runtime shader definition. - /// - public string pass { get; set; } - - /// - /// Gets or sets stable stage output node identities; computation remains owned by those nodes. - /// - public string[] stages { get; set; } -} - /// /// Edits pass-to-program references without copying computation or changing runtime render states. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettings.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettings.cs new file mode 100644 index 000000000..bc71896d5 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettings.cs @@ -0,0 +1,39 @@ +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores one stage's explicit output interface and compute dimensions inside its output node. +/// +public sealed class ShaderGraphStageSettings : ISerializable +{ + /// + /// Gets or sets the programmable stage. + /// + [SerializableProperty] + public ShaderStage stage { get; set; } = ShaderStage.Fragment; + + /// + /// Gets or sets output ports and their GPU destinations. + /// + [SerializableProperty] + public ShaderGraphOutput[] outputs { get; set; } = []; + + /// + /// Gets or sets compute workgroup width. + /// + [SerializableProperty] + public int threadsX { get; set; } = 1; + + /// + /// Gets or sets compute workgroup height. + /// + [SerializableProperty] + public int threadsY { get; set; } = 1; + + /// + /// Gets or sets compute workgroup depth. + /// + [SerializableProperty] + public int threadsZ { get; set; } = 1; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettingsConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettingsConverter.cs new file mode 100644 index 000000000..f5b5ff4bc --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphStageSettingsConverter.cs @@ -0,0 +1,46 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphStageSettingsConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphStageSettings value + ) { + writer.Write("stage", value.stage); + writer.Write("outputs", value.outputs); + writer.Write("threadsX", value.threadsX); + writer.Write("threadsY", value.threadsY); + writer.Write("threadsZ", value.threadsZ); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph stage settings that represents the completed operation. + /// + public override ShaderGraphStageSettings Read(SerializationReader reader) + => new() + { + stage = reader.Read("stage"), + outputs = reader.Read("outputs"), + threadsX = reader.Read("threadsX"), + threadsY = reader.Read("threadsY"), + threadsZ = reader.Read("threadsZ") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTypeConverter.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTypeConverter.cs new file mode 100644 index 000000000..ad266c9bd --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphTypeConverter.cs @@ -0,0 +1,60 @@ +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderGraphTypeConverter : SerializationConverter +{ + /// + /// Writes the complete value through the configured serialization contract. + /// + /// + /// The writer that receives the serialized representation. + /// + /// + /// The concrete value read or transformed by this operation. + /// + public override void Write( + SerializationWriter writer, + ShaderGraphType value + ) { + writer.Write("id", value.id); + writer.Write("element", value.element); + writer.Write("length", value.length); + writer.Write("fieldNames", value.fieldNames); + writer.Write("fieldTypes", value.fieldTypes); + writer.Write("isStorage", value.isStorage); + writer.Write("isImage", value.isImage); + writer.Write("storageElement", value.storageElement); + writer.Write("access", value.access); + writer.Write("format", value.format); + writer.Write("dimension", value.dimension); + writer.Write("isArray", value.isArray); + } + + /// + /// Reconstructs a complete value through the configured serialization contract. + /// + /// + /// The reader that supplies the serialized representation. + /// + /// + /// The validated shader graph type that represents the completed operation. + /// + public override ShaderGraphType Read(SerializationReader reader) + => new() + { + id = reader.Read("id"), + element = reader.Read("element"), + length = reader.Read("length"), + fieldNames = reader.Read("fieldNames"), + fieldTypes = reader.Read("fieldTypes"), + isStorage = reader.Read("isStorage"), + isImage = reader.Read("isImage"), + storageElement = reader.Read("storageElement"), + access = reader.Read("access"), + format = reader.Read("format"), + dimension = reader.Read("dimension"), + isArray = reader.Read("isArray") + }; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs b/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs deleted file mode 100644 index ecfaae9ca..000000000 --- a/src/services/rendering/Inno.Rendering.Shaders/Documents/ShaderGraphValueConverters.cs +++ /dev/null @@ -1,367 +0,0 @@ -using Inno.Core.Serialization; -using Inno.Core.Serialization.Converters; - -namespace Inno.Rendering.Shaders; - -internal sealed class ShaderGraphLiteralConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphLiteral value - ) { - writer.Write("type", value.type); - writer.Write("scalarBits", value.scalarBits); - } - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph literal that represents the completed operation. - /// - public override ShaderGraphLiteral Read(SerializationReader reader) - => new() { type = reader.Read("type"), scalarBits = reader.Read("scalarBits") }; -} - -internal sealed class ShaderGraphStageSettingsConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphStageSettings value - ) { - writer.Write("stage", value.stage); - writer.Write("outputs", value.outputs); - writer.Write("threadsX", value.threadsX); - writer.Write("threadsY", value.threadsY); - writer.Write("threadsZ", value.threadsZ); - } - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph stage settings that represents the completed operation. - /// - public override ShaderGraphStageSettings Read(SerializationReader reader) - => new() - { - stage = reader.Read("stage"), - outputs = reader.Read("outputs"), - threadsX = reader.Read("threadsX"), - threadsY = reader.Read("threadsY"), - threadsZ = reader.Read("threadsZ") - }; -} - -internal sealed class ShaderGraphInputSettingsConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphInputSettings value - ) { - writer.Write("id", value.id); - writer.Write("type", value.type); - writer.Write("kind", value.kind); - writer.Write("semantic", value.semantic); - writer.Write("location", value.location); - } - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph input settings that represents the completed operation. - /// - public override ShaderGraphInputSettings Read(SerializationReader reader) - => new() - { - id = reader.Read("id"), - type = reader.Read("type"), - kind = reader.Read("kind"), - semantic = reader.Read("semantic"), - location = reader.Read("location") - }; -} - -internal sealed class ShaderGraphNodePortDefinitionConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphNodePortDefinition value - ) { - writer.Write("id", value.id); - writer.Write("type", value.type); - writer.Write("required", value.required); - } - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph node port definition that represents the completed operation. - /// - public override ShaderGraphNodePortDefinition Read(SerializationReader reader) - => new() - { - id = reader.Read("id"), - type = reader.Read("type"), - required = reader.Read("required") - }; -} - -internal sealed class ShaderGraphNodeSettingsConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphNodeSettings value - ) { - writer.Write("displayName", value.displayName); - writer.Write("createPath", value.createPath); - writer.Write("createOrder", value.createOrder); - writer.Write("kind", value.kind); - writer.Write("effect", value.effect); - writer.Write("role", value.role); - } - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph node settings that represents the completed operation. - /// - public override ShaderGraphNodeSettings Read(SerializationReader reader) - => new() - { - displayName = reader.Read("displayName"), - createPath = reader.Read("createPath"), - createOrder = reader.Read("createOrder"), - kind = reader.Read("kind"), - effect = reader.Read("effect"), - role = reader.Read("role") - }; -} - -internal sealed class ShaderGraphNodeInputSettingsConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphNodeInputSettings value - ) => writer.Write("ports", value.ports); - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph node input settings that represents the completed operation. - /// - public override ShaderGraphNodeInputSettings Read(SerializationReader reader) - => new() - { - ports = reader.Read("ports") - }; -} - -internal sealed class ShaderGraphNodeOutputSettingsConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphNodeOutputSettings value - ) => writer.Write("ports", value.ports); - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph node output settings that represents the completed operation. - /// - public override ShaderGraphNodeOutputSettings Read(SerializationReader reader) - => new() { ports = reader.Read("ports") }; -} - -internal sealed class ShaderGraphNodeInterfaceConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphNodeInterface value - ) { - writer.Write("displayName", value.displayName); - writer.Write("createPath", value.createPath); - writer.Write("createOrder", value.createOrder); - writer.Write("kind", value.kind); - writer.Write("effect", value.effect); - writer.Write("role", value.role); - writer.Write("inputs", value.inputs); - writer.Write("outputs", value.outputs); - } - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph node interface that represents the completed operation. - /// - public override ShaderGraphNodeInterface Read(SerializationReader reader) - => new() - { - displayName = reader.Read("displayName"), - createPath = reader.Read("createPath"), - createOrder = reader.Read("createOrder"), - kind = reader.Read("kind"), - effect = reader.Read("effect"), - role = reader.Read("role"), - inputs = reader.Read("inputs"), - outputs = reader.Read("outputs") - }; -} - -internal sealed class ShaderGraphTypeConverter : SerializationConverter -{ - /// - /// Writes the complete value through the configured serialization contract. - /// - /// - /// The writer that receives the serialized representation. - /// - /// - /// The concrete value read or transformed by this operation. - /// - public override void Write( - SerializationWriter writer, - ShaderGraphType value - ) { - writer.Write("id", value.id); - writer.Write("element", value.element); - writer.Write("length", value.length); - writer.Write("fieldNames", value.fieldNames); - writer.Write("fieldTypes", value.fieldTypes); - writer.Write("isStorage", value.isStorage); - writer.Write("isImage", value.isImage); - writer.Write("storageElement", value.storageElement); - writer.Write("access", value.access); - writer.Write("format", value.format); - writer.Write("dimension", value.dimension); - writer.Write("isArray", value.isArray); - } - - /// - /// Reconstructs a complete value through the configured serialization contract. - /// - /// - /// The reader that supplies the serialized representation. - /// - /// - /// The validated shader graph type that represents the completed operation. - /// - public override ShaderGraphType Read(SerializationReader reader) - => new() - { - id = reader.Read("id"), - element = reader.Read("element"), - length = reader.Read("length"), - fieldNames = reader.Read("fieldNames"), - fieldTypes = reader.Read("fieldTypes"), - isStorage = reader.Read("isStorage"), - isImage = reader.Read("isImage"), - storageElement = reader.Read("storageElement"), - access = reader.Read("access"), - format = reader.Read("format"), - dimension = reader.Read("dimension"), - isArray = reader.Read("isArray") - }; -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs index c96580d80..ec336d064 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrBlock.cs @@ -6,31 +6,29 @@ namespace Inno.Rendering.Shaders; /// -/// Identifies a typed single-assignment value within one intermediate block. +/// Contains immutable ordered instructions and nested structured regions without retaining builder callbacks. /// -public sealed class ShaderIrValue +public sealed class ShaderIrBlock { - internal ShaderIrValue( - object owner, - int index, - ShaderSourceType type + internal ShaderIrBlock( + IEnumerable instructions, + IReadOnlyDictionary outputs ) { - this.owner = owner; - this.index = index; - this.type = type; + this.instructions = Array.AsReadOnly(instructions.ToArray()); + this.outputs = new ReadOnlyDictionary( + new Dictionary(outputs, StringComparer.Ordinal) + ); } /// - /// Gets the deterministic block-local value index, not a GPU register or resource slot. + /// Gets instructions in evaluation order, including source calls whose outputs are unused. /// - public int index { get; } + public IReadOnlyList instructions { get; } /// - /// Gets the complete language-independent value type. + /// Gets named values returned to the enclosing stage or region. /// - public ShaderSourceType type { get; } - - internal object owner { get; } + public IReadOnlyDictionary outputs { get; } } /// @@ -131,103 +129,3 @@ public enum ShaderIrOperation /// Loop } - -/// -/// Stores one immutable typed instruction without generated stage source or backend expressions. -/// -public sealed class ShaderIrInstruction -{ - internal ShaderIrInstruction( - ShaderIrOperation operation, - IEnumerable inputs, - IEnumerable outputs, - string? inputName = null, - ulong constantBits = 0, - int memberIndex = 0, - ShaderSourceImplementationAnalysis? source = null, - IEnumerable? regions = null - ) { - this.operation = operation; - this.inputs = Array.AsReadOnly(inputs.ToArray()); - this.outputs = Array.AsReadOnly(outputs.ToArray()); - this.inputName = inputName; - this.constantBits = constantBits; - this.memberIndex = memberIndex; - this.source = source; - this.regions = Array.AsReadOnly(regions?.ToArray() ?? []); - } - - /// - /// Gets the semantic operation independent of any source language. - /// - public ShaderIrOperation operation { get; } - - /// - /// Gets immutable operands in operation or function-declaration order. - /// - public IReadOnlyList inputs { get; } - - /// - /// Gets produced values; a call orders its return value first, then out/inout parameters. - /// - public IReadOnlyList outputs { get; } - - /// - /// Gets the stable interface or region-parameter identity, only for Input or RegionInput. - /// - public string? inputName { get; } - - /// - /// Gets exact scalar bits for a Constant instruction; the result type determines interpretation. - /// - public ulong constantBits { get; } - - /// - /// Gets the zero-based component/member/element ordinal for an Extract instruction. - /// - public int memberIndex { get; } - - /// - /// Gets a frozen, analyzed function implementation only for a SourceCall instruction. - /// - public ShaderSourceImplementationAnalysis? source { get; } - - /// - /// Gets immutable nested regions: true/false for Branch, or one body for Loop. - /// - public IReadOnlyList regions { get; } - - /// - /// Gets whether removing or reordering this instruction may change observable behavior. - /// - public bool hasSideEffects - => operation is ShaderIrOperation.SourceCall or ShaderIrOperation.StorageLoad - or ShaderIrOperation.StorageStore or ShaderIrOperation.StorageAtomicAdd or ShaderIrOperation.Discard - or ShaderIrOperation.Branch or ShaderIrOperation.Loop; -} - -/// -/// Contains immutable ordered instructions and nested structured regions without retaining builder callbacks. -/// -public sealed class ShaderIrBlock -{ - internal ShaderIrBlock( - IEnumerable instructions, - IReadOnlyDictionary outputs - ) { - this.instructions = Array.AsReadOnly(instructions.ToArray()); - this.outputs = new ReadOnlyDictionary( - new Dictionary(outputs, StringComparer.Ordinal) - ); - } - - /// - /// Gets instructions in evaluation order, including source calls whose outputs are unused. - /// - public IReadOnlyList instructions { get; } - - /// - /// Gets named values returned to the enclosing stage or region. - /// - public IReadOnlyDictionary outputs { get; } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrInstruction.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrInstruction.cs new file mode 100644 index 000000000..4796610e5 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrInstruction.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Rendering.Shaders; + +/// +/// Stores one immutable typed instruction without generated stage source or backend expressions. +/// +public sealed class ShaderIrInstruction +{ + internal ShaderIrInstruction( + ShaderIrOperation operation, + IEnumerable inputs, + IEnumerable outputs, + string? inputName = null, + ulong constantBits = 0, + int memberIndex = 0, + ShaderSourceImplementationAnalysis? source = null, + IEnumerable? regions = null + ) { + this.operation = operation; + this.inputs = Array.AsReadOnly(inputs.ToArray()); + this.outputs = Array.AsReadOnly(outputs.ToArray()); + this.inputName = inputName; + this.constantBits = constantBits; + this.memberIndex = memberIndex; + this.source = source; + this.regions = Array.AsReadOnly(regions?.ToArray() ?? []); + } + + /// + /// Gets the semantic operation independent of any source language. + /// + public ShaderIrOperation operation { get; } + + /// + /// Gets immutable operands in operation or function-declaration order. + /// + public IReadOnlyList inputs { get; } + + /// + /// Gets produced values; a call orders its return value first, then out/inout parameters. + /// + public IReadOnlyList outputs { get; } + + /// + /// Gets the stable interface or region-parameter identity, only for Input or RegionInput. + /// + public string? inputName { get; } + + /// + /// Gets exact scalar bits for a Constant instruction; the result type determines interpretation. + /// + public ulong constantBits { get; } + + /// + /// Gets the zero-based component/member/element ordinal for an Extract instruction. + /// + public int memberIndex { get; } + + /// + /// Gets a frozen, analyzed function implementation only for a SourceCall instruction. + /// + public ShaderSourceImplementationAnalysis? source { get; } + + /// + /// Gets immutable nested regions: true/false for Branch, or one body for Loop. + /// + public IReadOnlyList regions { get; } + + /// + /// Gets whether removing or reordering this instruction may change observable behavior. + /// + public bool hasSideEffects + => operation is ShaderIrOperation.SourceCall or ShaderIrOperation.StorageLoad + or ShaderIrOperation.StorageStore or ShaderIrOperation.StorageAtomicAdd or ShaderIrOperation.Discard + or ShaderIrOperation.Branch or ShaderIrOperation.Loop; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs index 8c4555144..34a963793 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStage.cs @@ -1,206 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; -using Inno.Rendering; namespace Inno.Rendering.Shaders; -/// -/// Identifies the GPU interface through which a stage receives a value. -/// -public enum ShaderIrInputKind -{ - /// - /// A vertex stream attribute, including instance-rate streams. - /// - VertexAttribute, - /// - /// An interpolated value written by the preceding raster stage. - /// - Varying, - /// - /// A material, frame or draw uniform identified by a stable binding identity. - /// - Uniform, - /// - /// A sampled texture binding whose slot is assigned by target resource layout. - /// - SampledTexture, - /// - /// A typed storage buffer or image whose access, shape and layout are explicit. - /// - Storage, - /// - /// A standard GPU stage input identified by a target semantic, not native source text. - /// - Builtin -} - -/// -/// Identifies where a typed stage output is written. -/// -public enum ShaderIrOutputKind -{ - /// - /// The vertex position in homogeneous clip space. - /// - ClipPosition, - /// - /// A value interpolated for the next raster stage. - /// - Varying, - /// - /// A fragment color attachment at its explicit location. - /// - Color, - /// - /// The fragment depth value. - /// - Depth -} - -/// -/// Describes a stage input without embedding native declarations or expressions. -/// -public sealed class ShaderIrStageInput -{ - /// - /// Creates an immutable stage input binding. - /// - /// - /// Stable binding identity, also used by the block's named Input instruction. - /// - /// - /// Complete non-void type. - /// - /// - /// Source of the GPU value. - /// - /// - /// Target semantic, such as position, texcoord, color, instance-data or fragment-coordinate. - /// - /// - /// Attribute/semantic index or assigned texture slot, never a native handle. - /// - public ShaderIrStageInput( - string id, - ShaderSourceType type, - ShaderIrInputKind kind, - string semantic = "", - int location = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentNullException.ThrowIfNull(type); - ArgumentOutOfRangeException.ThrowIfNegative(location); - if (type.id == "void" || !Enum.IsDefined(kind)) - { - throw new ArgumentException("A stage input requires a value type and defined interface kind."); - } - if (kind == ShaderIrInputKind.SampledTexture - && (type.fields.Count != 0 || type.elementType is not null || type.storage is not null) - ) { - throw new ArgumentException("A sampled texture binding requires an opaque atomic resource type.", nameof(type)); - } - if (kind is ShaderIrInputKind.VertexAttribute or ShaderIrInputKind.Varying or ShaderIrInputKind.Builtin) - { - ArgumentException.ThrowIfNullOrWhiteSpace(semantic); - } - this.id = id; - this.type = type; - this.kind = kind; - this.semantic = semantic; - this.location = location; - } - - /// - /// Gets the logical binding identity. - /// - public string id { get; } - - /// - /// Gets the complete typed value received by the stage. - /// - public ShaderSourceType type { get; } - - /// - /// Gets the GPU input category. - /// - public ShaderIrInputKind kind { get; } - - /// - /// Gets the target semantic; an adapter must reject unsupported semantics. - /// - public string semantic { get; } - - /// - /// Gets the target-assigned interface location or sampled-texture slot. - /// - public int location { get; } -} - -/// -/// Describes a named block output's GPU destination. -/// -public sealed class ShaderIrStageOutput -{ - /// - /// Creates an immutable stage output binding. - /// - /// - /// The exact name in the block's output map. - /// - /// - /// GPU output category. - /// - /// - /// Varying semantic matched by the next stage; otherwise empty. - /// - /// - /// Varying index or color attachment index. - /// - public ShaderIrStageOutput( - string id, - ShaderIrOutputKind kind, - string semantic = "", - int location = 0 - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(id); - ArgumentOutOfRangeException.ThrowIfNegative(location); - if (!Enum.IsDefined(kind)) - { - throw new ArgumentException("A stage output requires a defined destination kind.", nameof(kind)); - } - if (kind == ShaderIrOutputKind.Varying) - { - ArgumentException.ThrowIfNullOrWhiteSpace(semantic); - } - this.id = id; - this.kind = kind; - this.semantic = semantic; - this.location = location; - } - - /// - /// Gets the exact block output identity. - /// - public string id { get; } - - /// - /// Gets the GPU output category. - /// - public ShaderIrOutputKind kind { get; } - - /// - /// Gets the varying semantic, not native assignment syntax. - /// - public string semantic { get; } - - /// - /// Gets the target-assigned varying or attachment index. - /// - public int location { get; } -} - /// /// Freezes a typed GPU stage and its explicit interface. It contains no main function, varying declarations or source expressions. /// Targets own stage/resource layout; adapters translate these semantics into their native language. @@ -404,3 +207,57 @@ or ShaderIrOperation.Discard || instruction.regions.Any(RequiresFragment) )); } + +/// +/// Identifies the GPU interface through which a stage receives a value. +/// +public enum ShaderIrInputKind +{ + /// + /// A vertex stream attribute, including instance-rate streams. + /// + VertexAttribute, + /// + /// An interpolated value written by the preceding raster stage. + /// + Varying, + /// + /// A material, frame or draw uniform identified by a stable binding identity. + /// + Uniform, + /// + /// A sampled texture binding whose slot is assigned by target resource layout. + /// + SampledTexture, + /// + /// A typed storage buffer or image whose access, shape and layout are explicit. + /// + Storage, + /// + /// A standard GPU stage input identified by a target semantic, not native source text. + /// + Builtin +} + +/// +/// Identifies where a typed stage output is written. +/// +public enum ShaderIrOutputKind +{ + /// + /// The vertex position in homogeneous clip space. + /// + ClipPosition, + /// + /// A value interpolated for the next raster stage. + /// + Varying, + /// + /// A fragment color attachment at its explicit location. + /// + Color, + /// + /// The fragment depth value. + /// + Depth +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageInput.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageInput.cs new file mode 100644 index 000000000..b37e5afbe --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageInput.cs @@ -0,0 +1,82 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes a stage input without embedding native declarations or expressions. +/// +public sealed class ShaderIrStageInput +{ + /// + /// Creates an immutable stage input binding. + /// + /// + /// Stable binding identity, also used by the block's named Input instruction. + /// + /// + /// Complete non-void type. + /// + /// + /// Source of the GPU value. + /// + /// + /// Target semantic, such as position, texcoord, color, instance-data or fragment-coordinate. + /// + /// + /// Attribute/semantic index or assigned texture slot, never a native handle. + /// + public ShaderIrStageInput( + string id, + ShaderSourceType type, + ShaderIrInputKind kind, + string semantic = "", + int location = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentNullException.ThrowIfNull(type); + ArgumentOutOfRangeException.ThrowIfNegative(location); + if (type.id == "void" || !Enum.IsDefined(kind)) + { + throw new ArgumentException("A stage input requires a value type and defined interface kind."); + } + if (kind == ShaderIrInputKind.SampledTexture + && (type.fields.Count != 0 || type.elementType is not null || type.storage is not null) + ) { + throw new ArgumentException("A sampled texture binding requires an opaque atomic resource type.", nameof(type)); + } + if (kind is ShaderIrInputKind.VertexAttribute or ShaderIrInputKind.Varying or ShaderIrInputKind.Builtin) + { + ArgumentException.ThrowIfNullOrWhiteSpace(semantic); + } + this.id = id; + this.type = type; + this.kind = kind; + this.semantic = semantic; + this.location = location; + } + + /// + /// Gets the logical binding identity. + /// + public string id { get; } + + /// + /// Gets the complete typed value received by the stage. + /// + public ShaderSourceType type { get; } + + /// + /// Gets the GPU input category. + /// + public ShaderIrInputKind kind { get; } + + /// + /// Gets the target semantic; an adapter must reject unsupported semantics. + /// + public string semantic { get; } + + /// + /// Gets the target-assigned interface location or sampled-texture slot. + /// + public int location { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageOutput.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageOutput.cs new file mode 100644 index 000000000..d15e6e1d3 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrStageOutput.cs @@ -0,0 +1,66 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes a named block output's GPU destination. +/// +public sealed class ShaderIrStageOutput +{ + /// + /// Creates an immutable stage output binding. + /// + /// + /// The exact name in the block's output map. + /// + /// + /// GPU output category. + /// + /// + /// Varying semantic matched by the next stage; otherwise empty. + /// + /// + /// Varying index or color attachment index. + /// + public ShaderIrStageOutput( + string id, + ShaderIrOutputKind kind, + string semantic = "", + int location = 0 + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentOutOfRangeException.ThrowIfNegative(location); + if (!Enum.IsDefined(kind)) + { + throw new ArgumentException("A stage output requires a defined destination kind.", nameof(kind)); + } + if (kind == ShaderIrOutputKind.Varying) + { + ArgumentException.ThrowIfNullOrWhiteSpace(semantic); + } + this.id = id; + this.kind = kind; + this.semantic = semantic; + this.location = location; + } + + /// + /// Gets the exact block output identity. + /// + public string id { get; } + + /// + /// Gets the GPU output category. + /// + public ShaderIrOutputKind kind { get; } + + /// + /// Gets the varying semantic, not native assignment syntax. + /// + public string semantic { get; } + + /// + /// Gets the target-assigned varying or attachment index. + /// + public int location { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrValue.cs b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrValue.cs new file mode 100644 index 000000000..e8e7ff30a --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Intermediate/ShaderIrValue.cs @@ -0,0 +1,29 @@ +namespace Inno.Rendering.Shaders; + +/// +/// Identifies a typed single-assignment value within one intermediate block. +/// +public sealed class ShaderIrValue +{ + internal ShaderIrValue( + object owner, + int index, + ShaderSourceType type + ) { + this.owner = owner; + this.index = index; + this.type = type; + } + + /// + /// Gets the deterministic block-local value index, not a GPU register or resource slot. + /// + public int index { get; } + + /// + /// Gets the complete language-independent value type. + /// + public ShaderSourceType type { get; } + + internal object owner { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs index bee6b0955..40f261012 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceFrontend.cs @@ -1,11 +1,29 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; using Inno.Core.Diagnostics; namespace Inno.Rendering.Shaders; +/// +/// Parses one source language into canonical function interfaces; it does not create GPU objects. +/// +public interface IShaderSourceFrontend +{ + /// + /// Gets the open source language identity, distinct from a rendering backend or GPU API. + /// + string languageID { get; } + + /// + /// Analyzes an immutable source candidate with explicit preprocessing inputs. + /// + /// + /// Source, selected function, dependencies, and target inputs. + /// + /// + /// A successful interface or a recoverable set of original-source diagnostics. + /// + ShaderSourceAnalysis Analyze(ShaderSourceRequest request); +} + /// /// Identifies an original source position, not a generated temporary compiler filename. /// @@ -59,160 +77,3 @@ public sealed record ShaderSourceFile( string assetPath, string text ); - -/// -/// Reads dependencies only from the current source candidate and records their import dependencies. -/// -public interface IShaderSourceResolver -{ - /// - /// Resolves and reads an include without bypassing asset mount permissions. - /// - /// - /// Resolved path of the including source. - /// - /// - /// Source-local include spelling. - /// - /// - /// A resolved immutable source snapshot. - /// - ShaderSourceFile ReadInclude( - string includingFile, - string include - ); -} - -/// -/// Carries the immutable inputs required to execute one shader source request. -/// -public sealed class ShaderSourceRequest -{ - /// - /// Creates an analysis request for an explicitly selected function. - /// - /// - /// Root source snapshot. - /// - /// - /// The one public function selected by source import settings. - /// - /// - /// Candidate-scoped include resolver. - /// - /// - /// Target and variant preprocessing inputs, or null for no defines. - /// - public ShaderSourceRequest( - ShaderSourceFile source, - string entryPoint, - IShaderSourceResolver resolver, - IReadOnlyDictionary? defines = null - ) { - ArgumentNullException.ThrowIfNull(source); - ArgumentNullException.ThrowIfNull(resolver); - this.source = source; - ArgumentException.ThrowIfNullOrWhiteSpace(source.assetPath); - ArgumentNullException.ThrowIfNull(source.text); - ArgumentException.ThrowIfNullOrWhiteSpace(entryPoint); - this.entryPoint = entryPoint; - this.resolver = resolver; - this.defines = new ReadOnlyDictionary( - defines is null - ? new Dictionary(StringComparer.Ordinal) - : new Dictionary(defines, StringComparer.Ordinal) - ); - } - - /// - /// Gets the root source snapshot. - /// - public ShaderSourceFile source { get; } - - /// - /// Gets the explicitly selected export function name. - /// - public string entryPoint { get; } - - /// - /// Gets the candidate-scoped dependency resolver. - /// - public IShaderSourceResolver resolver { get; } - - /// - /// Gets immutable preprocessing inputs included in analysis cache identity. - /// - public IReadOnlyDictionary defines { get; } -} - -/// -/// Returns a recoverable source analysis result and complete original-source dependencies. -/// -public sealed class ShaderSourceAnalysis -{ - /// - /// Captures a completed analysis without retaining compiler objects. - /// - /// - /// Parsed interface, or null when parsing failed. - /// - /// - /// Resolved included sources, excluding the root. - /// - /// - /// All problems discovered by the frontend. - /// - public ShaderSourceAnalysis( - ShaderSourceFunction? function, - IEnumerable dependencies, - IEnumerable diagnostics - ) { - ArgumentNullException.ThrowIfNull(dependencies); - ArgumentNullException.ThrowIfNull(diagnostics); - this.function = function; - this.dependencies = Array.AsReadOnly(dependencies.Distinct(StringComparer.Ordinal).ToArray()); - this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - } - - /// - /// Gets the parsed interface, or null after an analysis failure. - /// - public ShaderSourceFunction? function { get; } - - /// - /// Gets original source dependencies for invalidation. - /// - public IReadOnlyList dependencies { get; } - - /// - /// Gets immutable, provider-neutral diagnostics. - /// - public IReadOnlyList diagnostics { get; } - - /// - /// Gets whether a usable interface was found without errors. - /// - public bool succeeded => function is not null && !diagnostics.Any(static item => item.severity == DiagnosticSeverity.Error); -} - -/// -/// Parses one source language into canonical function interfaces; it does not create GPU objects. -/// -public interface IShaderSourceFrontend -{ - /// - /// Gets the open source language identity, distinct from a rendering backend or GPU API. - /// - string languageID { get; } - - /// - /// Analyzes an immutable source candidate with explicit preprocessing inputs. - /// - /// - /// Source, selected function, dependencies, and target inputs. - /// - /// - /// A successful interface or a recoverable set of original-source diagnostics. - /// - ShaderSourceAnalysis Analyze(ShaderSourceRequest request); -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceResolver.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceResolver.cs new file mode 100644 index 000000000..6e684e79a --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/IShaderSourceResolver.cs @@ -0,0 +1,24 @@ +namespace Inno.Rendering.Shaders; + +/// +/// Reads dependencies only from the current source candidate and records their import dependencies. +/// +public interface IShaderSourceResolver +{ + /// + /// Resolves and reads an include without bypassing asset mount permissions. + /// + /// + /// Resolved path of the including source. + /// + /// + /// Source-local include spelling. + /// + /// + /// A resolved immutable source snapshot. + /// + ShaderSourceFile ReadInclude( + string includingFile, + string include + ); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceAnalysis.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceAnalysis.cs new file mode 100644 index 000000000..8cb05b6e9 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceAnalysis.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Core.Diagnostics; + +namespace Inno.Rendering.Shaders; + +/// +/// Returns a recoverable source analysis result and complete original-source dependencies. +/// +public sealed class ShaderSourceAnalysis +{ + /// + /// Captures a completed analysis without retaining compiler objects. + /// + /// + /// Parsed interface, or null when parsing failed. + /// + /// + /// Resolved included sources, excluding the root. + /// + /// + /// All problems discovered by the frontend. + /// + public ShaderSourceAnalysis( + ShaderSourceFunction? function, + IEnumerable dependencies, + IEnumerable diagnostics + ) { + ArgumentNullException.ThrowIfNull(dependencies); + ArgumentNullException.ThrowIfNull(diagnostics); + this.function = function; + this.dependencies = Array.AsReadOnly(dependencies.Distinct(StringComparer.Ordinal).ToArray()); + this.diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + } + + /// + /// Gets the parsed interface, or null after an analysis failure. + /// + public ShaderSourceFunction? function { get; } + + /// + /// Gets original source dependencies for invalidation. + /// + public IReadOnlyList dependencies { get; } + + /// + /// Gets immutable, provider-neutral diagnostics. + /// + public IReadOnlyList diagnostics { get; } + + /// + /// Gets whether a usable interface was found without errors. + /// + public bool succeeded => function is not null && !diagnostics.Any(static item => item.severity == DiagnosticSeverity.Error); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceField.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceField.cs new file mode 100644 index 000000000..a0afa5445 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceField.cs @@ -0,0 +1,45 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes one immutable named structure field. +/// +public sealed class ShaderSourceField +{ + /// + /// Creates a structure field. + /// + /// + /// Stable field name. + /// + /// + /// Complete field type. + /// + /// + /// The field has void type or is an opaque storage binding. + /// + public ShaderSourceField( + string name, + ShaderSourceType type + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(type); + if (type.id == "void" || type.storage is not null) + { + throw new ArgumentException("A structure field cannot have void type or contain an opaque storage binding.", nameof(type)); + } + this.name = name; + this.type = type; + } + + /// + /// Gets the public field name. + /// + public string name { get; } + + /// + /// Gets the complete field type. + /// + public ShaderSourceType type { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs index 1624d5ffb..3a03a9b7f 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceFunction.cs @@ -4,81 +4,6 @@ namespace Inno.Rendering.Shaders; -/// -/// Declares value flow across a source function parameter. -/// -public enum ShaderSourceParameterDirection -{ - /// - /// The caller supplies a value. - /// - Input, - /// - /// The function produces a value. - /// - Output, - /// - /// The caller supplies a value and the function produces its replacement. - /// - InputOutput -} - -/// -/// Describes one parameter parsed from a public source declaration. -/// -public sealed class ShaderSourceParameter -{ - /// - /// Creates a validated function parameter. - /// - /// - /// Public parameter name, used for semantic port matching rather than ordinal matching. - /// - /// - /// Canonical value type. - /// - /// - /// Declared value flow. - /// - /// - /// The parameter has void type. - /// - public ShaderSourceParameter( - string name, - ShaderSourceType type, - ShaderSourceParameterDirection direction - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - ArgumentNullException.ThrowIfNull(type); - if (!Enum.IsDefined(direction)) - { - throw new ArgumentOutOfRangeException(nameof(direction)); - } - if (type.id == "void") - { - throw new ArgumentException("A parameter cannot have void type.", nameof(type)); - } - this.name = name; - this.type = type; - this.direction = direction; - } - - /// - /// Gets the public parameter name. - /// - public string name { get; } - - /// - /// Gets the complete canonical value type. - /// - public ShaderSourceType type { get; } - - /// - /// Gets the declared value flow. - /// - public ShaderSourceParameterDirection direction { get; } -} - /// /// Contains the single callable interface exported by a source asset. /// diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationAnalysis.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationAnalysis.cs new file mode 100644 index 000000000..e1c9dc1b6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationAnalysis.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; + +namespace Inno.Rendering.Shaders; + +/// +/// Freezes a parsed implementation and its complete source inputs without retaining a frontend or resolver. +/// +public sealed class ShaderSourceImplementationAnalysis +{ + internal ShaderSourceImplementationAnalysis( + ShaderSourceImplementationRequest request, + ShaderSourceAnalysis analysis, + IEnumerable files, + IEnumerable includes + ) { + this.implementationID = request.implementationID; + this.languageID = request.languageID; + this.sourcePath = request.source.source.assetPath; + this.entryPoint = request.source.entryPoint; + this.defines = request.source.defines; + this.analysis = analysis; + this.sources = Array.AsReadOnly(files.OrderBy(static file => file.assetPath, StringComparer.Ordinal).ToArray()); + this.includes = Array.AsReadOnly( + includes.OrderBy(static edge => edge.includingFile, StringComparer.Ordinal) + .ThenBy(static edge => edge.include, StringComparer.Ordinal) + .ToArray() + ); + this.contentHash = ComputeContentHash(); + } + + /// + /// Gets the stable implementation/configuration key. + /// + public string implementationID { get; } + + /// + /// Gets the selected source language. + /// + public string languageID { get; } + + /// + /// Gets the root source path in the frozen source set. + /// + public string sourcePath { get; } + + /// + /// Gets the implementation's selected callable function name. + /// + public string entryPoint { get; } + + /// + /// Gets the immutable preprocessing inputs used for this implementation. + /// + public IReadOnlyDictionary defines { get; } + + /// + /// Gets every successfully read source, including the root, ordered by path. + /// + public IReadOnlyList sources { get; } + + /// + /// Gets the original resolver's frozen include edges, including aliases and mounted source paths. + /// + public IReadOnlyList includes { get; } + + /// + /// Gets the parsed interface and implementation-local diagnostics. + /// + public ShaderSourceAnalysis analysis { get; } + + /// + /// Gets a deterministic source-input hash. A compiler cache must additionally include its toolchain, + /// target, graph semantics and binding layout; this hash alone is not a compiled artifact key. + /// + public string contentHash { get; } + + /// + /// Recreates a compiler input backed only by immutable captured sources and resolution edges. + /// + /// + /// A request with no filesystem access or reference to the original frontend, resolver or generation. + /// + public ShaderSourceRequest CreateSourceRequest() + => new(sources.Single(file => file.assetPath == sourcePath), entryPoint, new FrozenResolver(sources, includes), defines); + + private string ComputeContentHash() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); + writer.Write(languageID); + writer.Write(sourcePath); + writer.Write(entryPoint); + writer.Write(defines.Count); + foreach ((string key, string value) in defines.OrderBy(static item => item.Key, StringComparer.Ordinal)) + { + writer.Write(key); + writer.Write(value); + } + writer.Write(sources.Count); + foreach (ShaderSourceFile file in sources) + { + writer.Write(file.assetPath); + writer.Write(file.text); + } + writer.Write(includes.Count); + foreach (ShaderSourceInclude edge in includes) + { + writer.Write(edge.includingFile); + writer.Write(edge.include); + writer.Write(edge.resolvedPath); + } + writer.Flush(); + return Convert.ToHexString(SHA256.HashData(stream.GetBuffer().AsSpan(0, checked((int)stream.Length)))); + } + + private sealed class FrozenResolver( + IReadOnlyList sources, + IReadOnlyList includes + ) : IShaderSourceResolver + { + /// + /// Reads and validates the include value from its authoritative source. + /// + /// + /// The including file text validated by the read include operation. + /// + /// + /// The include text validated by the read include operation. + /// + /// + /// The validated shader source file that represents the completed operation. + /// +public ShaderSourceFile ReadInclude( + string includingFile, + string include +) { + ShaderSourceInclude edge = includes.FirstOrDefault(value => value.includingFile == includingFile && value.include == include) + ?? throw new InvalidOperationException( + $"Include '{include}' from '{includingFile}' was not captured during source analysis." + ); + return sources.Single(file => file.assetPath == edge.resolvedPath); + } + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationRequest.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationRequest.cs new file mode 100644 index 000000000..19a1642f6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceImplementationRequest.cs @@ -0,0 +1,49 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Identifies one explicitly selected implementation and preprocessing configuration of a source module. +/// +public sealed class ShaderSourceImplementationRequest +{ + /// + /// Creates a candidate without inferring a language or adapter from its filename. + /// + /// + /// Unique owner-defined key, including the target or variant when applicable. + /// + /// + /// Registered source language identity. + /// + /// + /// Source function and candidate-scoped dependency resolver. + /// + public ShaderSourceImplementationRequest( + string implementationID, + string languageID, + ShaderSourceRequest source + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(implementationID); + ArgumentException.ThrowIfNullOrWhiteSpace(languageID); + ArgumentNullException.ThrowIfNull(source); + this.implementationID = implementationID; + this.languageID = languageID; + this.source = source; + } + + /// + /// Gets the stable owner-defined implementation/configuration key. + /// + public string implementationID { get; } + + /// + /// Gets the explicitly selected language identity. + /// + public string languageID { get; } + + /// + /// Gets the transient candidate request, which must not be persisted or retained after analysis. + /// + public ShaderSourceRequest source { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs index b4a6aa37e..a8b764061 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceModuleAnalysis.cs @@ -1,218 +1,10 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Security.Cryptography; -using System.Text; using Inno.Core.Diagnostics; namespace Inno.Rendering.Shaders; -/// -/// Records an include resolution edge so compilation never reinterprets authoring paths against live files. -/// -/// -/// Source that requested the include. -/// -/// -/// Original include spelling passed to the source resolver. -/// -/// -/// Exact source identity within the frozen file set. -/// -public sealed record ShaderSourceInclude( - string includingFile, - string include, - string resolvedPath -); - -/// -/// Identifies one explicitly selected implementation and preprocessing configuration of a source module. -/// -public sealed class ShaderSourceImplementationRequest -{ - /// - /// Creates a candidate without inferring a language or adapter from its filename. - /// - /// - /// Unique owner-defined key, including the target or variant when applicable. - /// - /// - /// Registered source language identity. - /// - /// - /// Source function and candidate-scoped dependency resolver. - /// - public ShaderSourceImplementationRequest( - string implementationID, - string languageID, - ShaderSourceRequest source - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(implementationID); - ArgumentException.ThrowIfNullOrWhiteSpace(languageID); - ArgumentNullException.ThrowIfNull(source); - this.implementationID = implementationID; - this.languageID = languageID; - this.source = source; - } - - /// - /// Gets the stable owner-defined implementation/configuration key. - /// - public string implementationID { get; } - - /// - /// Gets the explicitly selected language identity. - /// - public string languageID { get; } - - /// - /// Gets the transient candidate request, which must not be persisted or retained after analysis. - /// - public ShaderSourceRequest source { get; } -} - -/// -/// Freezes a parsed implementation and its complete source inputs without retaining a frontend or resolver. -/// -public sealed class ShaderSourceImplementationAnalysis -{ - internal ShaderSourceImplementationAnalysis( - ShaderSourceImplementationRequest request, - ShaderSourceAnalysis analysis, - IEnumerable files, - IEnumerable includes - ) { - this.implementationID = request.implementationID; - this.languageID = request.languageID; - this.sourcePath = request.source.source.assetPath; - this.entryPoint = request.source.entryPoint; - this.defines = request.source.defines; - this.analysis = analysis; - this.sources = Array.AsReadOnly(files.OrderBy(static file => file.assetPath, StringComparer.Ordinal).ToArray()); - this.includes = Array.AsReadOnly( - includes.OrderBy(static edge => edge.includingFile, StringComparer.Ordinal) - .ThenBy(static edge => edge.include, StringComparer.Ordinal) - .ToArray() - ); - this.contentHash = ComputeContentHash(); - } - - /// - /// Gets the stable implementation/configuration key. - /// - public string implementationID { get; } - - /// - /// Gets the selected source language. - /// - public string languageID { get; } - - /// - /// Gets the root source path in the frozen source set. - /// - public string sourcePath { get; } - - /// - /// Gets the implementation's selected callable function name. - /// - public string entryPoint { get; } - - /// - /// Gets the immutable preprocessing inputs used for this implementation. - /// - public IReadOnlyDictionary defines { get; } - - /// - /// Gets every successfully read source, including the root, ordered by path. - /// - public IReadOnlyList sources { get; } - - /// - /// Gets the original resolver's frozen include edges, including aliases and mounted source paths. - /// - public IReadOnlyList includes { get; } - - /// - /// Gets the parsed interface and implementation-local diagnostics. - /// - public ShaderSourceAnalysis analysis { get; } - - /// - /// Gets a deterministic source-input hash. A compiler cache must additionally include its toolchain, - /// target, graph semantics and binding layout; this hash alone is not a compiled artifact key. - /// - public string contentHash { get; } - - /// - /// Recreates a compiler input backed only by immutable captured sources and resolution edges. - /// - /// - /// A request with no filesystem access or reference to the original frontend, resolver or generation. - /// - public ShaderSourceRequest CreateSourceRequest() - => new(sources.Single(file => file.assetPath == sourcePath), entryPoint, new FrozenResolver(sources, includes), defines); - - private string ComputeContentHash() - { - using var stream = new MemoryStream(); - using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); - writer.Write(languageID); - writer.Write(sourcePath); - writer.Write(entryPoint); - writer.Write(defines.Count); - foreach ((string key, string value) in defines.OrderBy(static item => item.Key, StringComparer.Ordinal)) - { - writer.Write(key); - writer.Write(value); - } - writer.Write(sources.Count); - foreach (ShaderSourceFile file in sources) - { - writer.Write(file.assetPath); - writer.Write(file.text); - } - writer.Write(includes.Count); - foreach (ShaderSourceInclude edge in includes) - { - writer.Write(edge.includingFile); - writer.Write(edge.include); - writer.Write(edge.resolvedPath); - } - writer.Flush(); - return Convert.ToHexString(SHA256.HashData(stream.GetBuffer().AsSpan(0, checked((int)stream.Length)))); - } - - private sealed class FrozenResolver( - IReadOnlyList sources, - IReadOnlyList includes - ) : IShaderSourceResolver - { - /// - /// Reads and validates the include value from its authoritative source. - /// - /// - /// The including file text validated by the read include operation. - /// - /// - /// The include text validated by the read include operation. - /// - /// - /// The validated shader source file that represents the completed operation. - /// -public ShaderSourceFile ReadInclude( - string includingFile, - string include -) { - ShaderSourceInclude edge = includes.FirstOrDefault(value => value.includingFile == includingFile && value.include == include) - ?? throw new InvalidOperationException( - $"Include '{include}' from '{includingFile}' was not captured during source analysis." - ); - return sources.Single(file => file.assetPath == edge.resolvedPath); - } - } -} - /// /// Reports whether every supplied implementation and variant has the same callable graph interface. /// @@ -250,55 +42,20 @@ IEnumerable diagnostics public bool succeeded { get; } } -internal sealed class ShaderSourceSnapshotResolver : IShaderSourceResolver -{ - private readonly IShaderSourceResolver m_resolver; - private readonly Dictionary m_files = new(StringComparer.Ordinal); - private readonly Dictionary<(string, string), ShaderSourceInclude> m_includes = []; - - internal ShaderSourceSnapshotResolver(ShaderSourceRequest request) - { - m_resolver = request.resolver; - m_files.Add(request.source.assetPath, request.source); - } - - /// - /// Reads and validates the include value from its authoritative source. - /// - /// - /// The including file text validated by the read include operation. - /// - /// - /// The include text validated by the read include operation. - /// - /// - /// The validated shader source file that represents the completed operation. - /// -public ShaderSourceFile ReadInclude( +/// +/// Records an include resolution edge so compilation never reinterprets authoring paths against live files. +/// +/// +/// Source that requested the include. +/// +/// +/// Original include spelling passed to the source resolver. +/// +/// +/// Exact source identity within the frozen file set. +/// +public sealed record ShaderSourceInclude( string includingFile, - string include -) { - if (!m_files.ContainsKey(includingFile)) - { - throw new InvalidOperationException("An include must originate from an already captured source."); - } - ShaderSourceFile file = m_resolver.ReadInclude(includingFile, include) - ?? throw new InvalidOperationException("The source resolver returned no source snapshot."); - ArgumentException.ThrowIfNullOrWhiteSpace(file.assetPath); - ArgumentNullException.ThrowIfNull(file.text); - if (m_files.TryGetValue(file.assetPath, out ShaderSourceFile? previous) && previous.text != file.text) - { - throw new InvalidOperationException($"Source '{file.assetPath}' changed during module analysis."); - } - if (m_includes.TryGetValue((includingFile, include), out ShaderSourceInclude? edge) && edge.resolvedPath != file.assetPath) - { - throw new InvalidOperationException($"Include '{include}' changed resolution during module analysis."); - } - m_includes[(includingFile, include)] = new(includingFile, include, file.assetPath); - m_files[file.assetPath] = file; - return file; - } - - internal IEnumerable files => m_files.Values; - internal IEnumerable includes => m_includes.Values; -} + string include, + string resolvedPath +); diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceParameter.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceParameter.cs new file mode 100644 index 000000000..680b7271b --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceParameter.cs @@ -0,0 +1,78 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Describes one parameter parsed from a public source declaration. +/// +public sealed class ShaderSourceParameter +{ + /// + /// Creates a validated function parameter. + /// + /// + /// Public parameter name, used for semantic port matching rather than ordinal matching. + /// + /// + /// Canonical value type. + /// + /// + /// Declared value flow. + /// + /// + /// The parameter has void type. + /// + public ShaderSourceParameter( + string name, + ShaderSourceType type, + ShaderSourceParameterDirection direction + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(type); + if (!Enum.IsDefined(direction)) + { + throw new ArgumentOutOfRangeException(nameof(direction)); + } + if (type.id == "void") + { + throw new ArgumentException("A parameter cannot have void type.", nameof(type)); + } + this.name = name; + this.type = type; + this.direction = direction; + } + + /// + /// Gets the public parameter name. + /// + public string name { get; } + + /// + /// Gets the complete canonical value type. + /// + public ShaderSourceType type { get; } + + /// + /// Gets the declared value flow. + /// + public ShaderSourceParameterDirection direction { get; } +} + +/// +/// Declares value flow across a source function parameter. +/// +public enum ShaderSourceParameterDirection +{ + /// + /// The caller supplies a value. + /// + Input, + /// + /// The function produces a value. + /// + Output, + /// + /// The caller supplies a value and the function produces its replacement. + /// + InputOutput +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceRequest.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceRequest.cs new file mode 100644 index 000000000..7c77fc1d9 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceRequest.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.Rendering.Shaders; + +/// +/// Carries the immutable inputs required to execute one shader source request. +/// +public sealed class ShaderSourceRequest +{ + /// + /// Creates an analysis request for an explicitly selected function. + /// + /// + /// Root source snapshot. + /// + /// + /// The one public function selected by source import settings. + /// + /// + /// Candidate-scoped include resolver. + /// + /// + /// Target and variant preprocessing inputs, or null for no defines. + /// + public ShaderSourceRequest( + ShaderSourceFile source, + string entryPoint, + IShaderSourceResolver resolver, + IReadOnlyDictionary? defines = null + ) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(resolver); + this.source = source; + ArgumentException.ThrowIfNullOrWhiteSpace(source.assetPath); + ArgumentNullException.ThrowIfNull(source.text); + ArgumentException.ThrowIfNullOrWhiteSpace(entryPoint); + this.entryPoint = entryPoint; + this.resolver = resolver; + this.defines = new ReadOnlyDictionary( + defines is null + ? new Dictionary(StringComparer.Ordinal) + : new Dictionary(defines, StringComparer.Ordinal) + ); + } + + /// + /// Gets the root source snapshot. + /// + public ShaderSourceFile source { get; } + + /// + /// Gets the explicitly selected export function name. + /// + public string entryPoint { get; } + + /// + /// Gets the candidate-scoped dependency resolver. + /// + public IShaderSourceResolver resolver { get; } + + /// + /// Gets immutable preprocessing inputs included in analysis cache identity. + /// + public IReadOnlyDictionary defines { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceSnapshotResolver.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceSnapshotResolver.cs new file mode 100644 index 000000000..f38512796 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceSnapshotResolver.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders; + +internal sealed class ShaderSourceSnapshotResolver : IShaderSourceResolver +{ + private readonly IShaderSourceResolver m_resolver; + private readonly Dictionary m_files = new(StringComparer.Ordinal); + private readonly Dictionary<(string, string), ShaderSourceInclude> m_includes = []; + + internal ShaderSourceSnapshotResolver(ShaderSourceRequest request) + { + m_resolver = request.resolver; + m_files.Add(request.source.assetPath, request.source); + } + + /// + /// Reads and validates the include value from its authoritative source. + /// + /// + /// The including file text validated by the read include operation. + /// + /// + /// The include text validated by the read include operation. + /// + /// + /// The validated shader source file that represents the completed operation. + /// +public ShaderSourceFile ReadInclude( + string includingFile, + string include +) { + if (!m_files.ContainsKey(includingFile)) + { + throw new InvalidOperationException("An include must originate from an already captured source."); + } + ShaderSourceFile file = m_resolver.ReadInclude(includingFile, include) + ?? throw new InvalidOperationException("The source resolver returned no source snapshot."); + ArgumentException.ThrowIfNullOrWhiteSpace(file.assetPath); + ArgumentNullException.ThrowIfNull(file.text); + if (m_files.TryGetValue(file.assetPath, out ShaderSourceFile? previous) && previous.text != file.text) + { + throw new InvalidOperationException($"Source '{file.assetPath}' changed during module analysis."); + } + if (m_includes.TryGetValue((includingFile, include), out ShaderSourceInclude? edge) && edge.resolvedPath != file.assetPath) + { + throw new InvalidOperationException($"Include '{include}' changed resolution during module analysis."); + } + m_includes[(includingFile, include)] = new(includingFile, include, file.assetPath); + m_files[file.assetPath] = file; + return file; + } + + internal IEnumerable files => m_files.Values; + internal IEnumerable includes => m_includes.Values; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs index c46fa4d7e..5d34cd727 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Sources/ShaderSourceType.cs @@ -167,45 +167,3 @@ IEnumerable fields return new(id, null, 0, snapshot); } } - -/// -/// Describes one immutable named structure field. -/// -public sealed class ShaderSourceField -{ - /// - /// Creates a structure field. - /// - /// - /// Stable field name. - /// - /// - /// Complete field type. - /// - /// - /// The field has void type or is an opaque storage binding. - /// - public ShaderSourceField( - string name, - ShaderSourceType type - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - ArgumentNullException.ThrowIfNull(type); - if (type.id == "void" || type.storage is not null) - { - throw new ArgumentException("A structure field cannot have void type or contain an opaque storage binding.", nameof(type)); - } - this.name = name; - this.type = type; - } - - /// - /// Gets the public field name. - /// - public string name { get; } - - /// - /// Gets the complete field type. - /// - public ShaderSourceType type { get; } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs index 5be949a28..e1064cd4d 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTarget.cs @@ -1,35 +1,8 @@ -using System; using System.Threading; using Inno.Core.Graphs; -using Inno.Core.Serialization; namespace Inno.Rendering.Shaders; -/// -/// Declares the immutable identity used to select a Shader Target from an authored graph. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class ShaderTargetAttribute : Attribute -{ - /// - /// Creates target discovery metadata. - /// - /// - /// Stable target identity persisted by Shader assets. - /// - public ShaderTargetAttribute(string id) - { - this.id = string.IsNullOrWhiteSpace(id) - ? throw new ArgumentException("Shader target identity cannot be empty.", nameof(id)) - : id; - } - - /// - /// Gets the stable target identity persisted by Shader assets. - /// - public string id { get; } -} - /// /// Expands a domain's surface contract into ordinary graph stages before source dependency capture. /// @@ -52,34 +25,3 @@ public abstract GraphDocument Expand( CancellationToken cancellationToken ); } - -/// -/// Supplies neutral authoring data to a domain target without exposing an adapter or live asset. -/// -public sealed class ShaderTargetContext -{ - internal ShaderTargetContext( - GraphDocument document, - SerializationRegistry serialization, - SerializationContext references - ) { - this.document = document; - this.serialization = serialization; - this.references = references; - } - - /// - /// Gets a private document copy; expansion cannot modify the authored source. - /// - public GraphDocument document { get; } - - /// - /// Gets the current owner converter registry, valid only during expansion. - /// - public SerializationRegistry serialization { get; } - - /// - /// Gets the complete owner reference context used for generated resource defaults. - /// - public SerializationContext references { get; } -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetAttribute.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetAttribute.cs new file mode 100644 index 000000000..2961ef8d0 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Declares the immutable identity used to select a Shader Target from an authored graph. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class ShaderTargetAttribute : Attribute +{ + /// + /// Creates target discovery metadata. + /// + /// + /// Stable target identity persisted by Shader assets. + /// + public ShaderTargetAttribute(string id) + { + this.id = string.IsNullOrWhiteSpace(id) + ? throw new ArgumentException("Shader target identity cannot be empty.", nameof(id)) + : id; + } + + /// + /// Gets the stable target identity persisted by Shader assets. + /// + public string id { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetContext.cs b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetContext.cs new file mode 100644 index 000000000..531065662 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Targets/ShaderTargetContext.cs @@ -0,0 +1,35 @@ +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +/// +/// Supplies neutral authoring data to a domain target without exposing an adapter or live asset. +/// +public sealed class ShaderTargetContext +{ + internal ShaderTargetContext( + GraphDocument document, + SerializationRegistry serialization, + SerializationContext references + ) { + this.document = document; + this.serialization = serialization; + this.references = references; + } + + /// + /// Gets a private document copy; expansion cannot modify the authored source. + /// + public GraphDocument document { get; } + + /// + /// Gets the current owner converter registry, valid only during expansion. + /// + public SerializationRegistry serialization { get; } + + /// + /// Gets the complete owner reference context used for generated resource defaults. + /// + public SerializationContext references { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/RasterShaderGraphTemplate.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/RasterShaderGraphTemplate.cs new file mode 100644 index 000000000..d4fe0631e --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/RasterShaderGraphTemplate.cs @@ -0,0 +1,25 @@ +using Inno.Core.Graphs; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Shaders; + +[ShaderGraphTemplate(ShaderBuiltInIDs.C_RASTER_TEMPLATE, "Raster")] +internal sealed class RasterShaderGraphTemplate : ShaderGraphTemplate +{ + /// + /// Creates and validates a caller-owned value value. + /// + /// + /// The serialization consumed by create; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The operation scope that provides state, services, and ownership boundaries. + /// + /// + /// The validated graph document that represents the completed operation. + /// +public override GraphDocument Create( + SerializationRegistry serialization, + SerializationContext context +) => ShaderGraphTemplates.CreateRaster(serialization, context); +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ReusableShaderGraphNodeTemplate.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ReusableShaderGraphNodeTemplate.cs new file mode 100644 index 000000000..c0c702660 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ReusableShaderGraphNodeTemplate.cs @@ -0,0 +1,61 @@ +using Inno.Core.Graphs; +using Inno.Core.Serialization; +using Inno.Rendering.Assets; + +namespace Inno.Rendering.Shaders; + +[ShaderGraphTemplate(ShaderBuiltInIDs.C_NODE_TEMPLATE, "Reusable Node")] +internal sealed class ReusableShaderGraphNodeTemplate : ShaderGraphTemplate +{ + /// + /// Creates a value using this implementation's validated inputs. + /// + /// + /// The serialization consumed by create; ownership remains with the caller unless explicitly stated otherwise. + /// + /// + /// The context that supplies state and services for this operation. + /// + /// + /// The validated graph document that represents the completed operation. + /// + public override GraphDocument Create( + SerializationRegistry serialization, + SerializationContext context + ) { + GraphDocument graph = ShaderGraphDocument.Create(new ShaderDefinition("Graph Node", [], [], []), serialization, context); + ShaderGraphNodes.WriteSettings(graph, new ShaderGraphNodeSettings(), serialization, context); + var input = new GraphNodeRecord(new GraphNodeID("node-inputs"), ShaderGraphNodes.C_INPUT_DEFINITION_ID) + { + position = new(40, 120) + }; + input.SetValue( + ShaderGraphDocument.C_SETTINGS_KEY, + ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings + { + ports = [new ShaderGraphNodePortDefinition() { id = "value", type = new() { id = "float" } }] + }, serialization, context) + ); + var output = new GraphNodeRecord(new GraphNodeID("node-outputs"), ShaderGraphNodes.C_OUTPUT_DEFINITION_ID) + { + position = new(620, 120) + }; + output.SetValue( + ShaderGraphDocument.C_SETTINGS_KEY, + ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings + { + ports = [new ShaderGraphNodePortDefinition() { id = "value", type = new() { id = "float" } }] + }, serialization, context) + ); + graph.AddNode(input); + graph.AddNode(output); + graph.AddEdge( + new GraphEdgeRecord( + new GraphEdgeID("node-value"), + new GraphEndpoint(input.id, new GraphPortID("value")), + new GraphEndpoint(output.id, new GraphPortID("value")) + ) + ); + return graph; + } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderBuiltInIDs.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderBuiltInIDs.cs new file mode 100644 index 000000000..ce6ff58b9 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderBuiltInIDs.cs @@ -0,0 +1,7 @@ +namespace Inno.Rendering.Shaders; + +internal static class ShaderBuiltInIDs +{ + internal const string C_RASTER_TEMPLATE = "inno.shader.raster"; + internal const string C_NODE_TEMPLATE = "inno.shader.node"; +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs index 850556ea0..383627445 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplate.cs @@ -1,48 +1,8 @@ -using System; using Inno.Core.Graphs; using Inno.Core.Serialization; -using Inno.Rendering.Assets; namespace Inno.Rendering.Shaders; -/// -/// Declares immutable creation metadata for a Shader graph template. -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] -public sealed class ShaderGraphTemplateAttribute : Attribute -{ - /// - /// Creates Shader graph template discovery metadata. - /// - /// - /// Stable template identity used by creation commands. - /// - /// - /// User-facing creation menu label. - /// - public ShaderGraphTemplateAttribute( - string id, - string displayName - ) { - this.id = string.IsNullOrWhiteSpace(id) - ? throw new ArgumentException("Shader graph template identity cannot be empty.", nameof(id)) - : id; - this.displayName = string.IsNullOrWhiteSpace(displayName) - ? throw new ArgumentException("Shader graph template display name cannot be empty.", nameof(displayName)) - : displayName; - } - - /// - /// Gets the stable template identity used by creation commands. - /// - public string id { get; } - - /// - /// Gets the user-facing creation menu label. - /// - public string displayName { get; } -} - /// /// Contributes an ordinary shader graph to the shared asset creation workflow. /// @@ -65,86 +25,3 @@ public abstract GraphDocument Create( SerializationContext context ); } - -[ShaderGraphTemplate(ShaderBuiltInIDs.C_RASTER_TEMPLATE, "Raster")] -internal sealed class RasterShaderGraphTemplate : ShaderGraphTemplate -{ - /// - /// Creates and validates a caller-owned value value. - /// - /// - /// The serialization consumed by create; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The operation scope that provides state, services, and ownership boundaries. - /// - /// - /// The validated graph document that represents the completed operation. - /// -public override GraphDocument Create( - SerializationRegistry serialization, - SerializationContext context -) => ShaderGraphTemplates.CreateRaster(serialization, context); -} - -[ShaderGraphTemplate(ShaderBuiltInIDs.C_NODE_TEMPLATE, "Reusable Node")] -internal sealed class ReusableShaderGraphNodeTemplate : ShaderGraphTemplate -{ - /// - /// Creates a value using this implementation's validated inputs. - /// - /// - /// The serialization consumed by create; ownership remains with the caller unless explicitly stated otherwise. - /// - /// - /// The context that supplies state and services for this operation. - /// - /// - /// The validated graph document that represents the completed operation. - /// - public override GraphDocument Create( - SerializationRegistry serialization, - SerializationContext context - ) { - GraphDocument graph = ShaderGraphDocument.Create(new ShaderDefinition("Graph Node", [], [], []), serialization, context); - ShaderGraphNodes.WriteSettings(graph, new ShaderGraphNodeSettings(), serialization, context); - var input = new GraphNodeRecord(new GraphNodeID("node-inputs"), ShaderGraphNodes.C_INPUT_DEFINITION_ID) - { - position = new(40, 120) - }; - input.SetValue( - ShaderGraphDocument.C_SETTINGS_KEY, - ShaderGraphDocument.Encode(new ShaderGraphNodeInputSettings - { - ports = [new ShaderGraphNodePortDefinition() { id = "value", type = new() { id = "float" } }] - }, serialization, context) - ); - var output = new GraphNodeRecord(new GraphNodeID("node-outputs"), ShaderGraphNodes.C_OUTPUT_DEFINITION_ID) - { - position = new(620, 120) - }; - output.SetValue( - ShaderGraphDocument.C_SETTINGS_KEY, - ShaderGraphDocument.Encode(new ShaderGraphNodeOutputSettings - { - ports = [new ShaderGraphNodePortDefinition() { id = "value", type = new() { id = "float" } }] - }, serialization, context) - ); - graph.AddNode(input); - graph.AddNode(output); - graph.AddEdge( - new GraphEdgeRecord( - new GraphEdgeID("node-value"), - new GraphEndpoint(input.id, new GraphPortID("value")), - new GraphEndpoint(output.id, new GraphPortID("value")) - ) - ); - return graph; - } -} - -internal static class ShaderBuiltInIDs -{ - internal const string C_RASTER_TEMPLATE = "inno.shader.raster"; - internal const string C_NODE_TEMPLATE = "inno.shader.node"; -} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateAttribute.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateAttribute.cs new file mode 100644 index 000000000..a58ae9fa5 --- /dev/null +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateAttribute.cs @@ -0,0 +1,41 @@ +using System; + +namespace Inno.Rendering.Shaders; + +/// +/// Declares immutable creation metadata for a Shader graph template. +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +public sealed class ShaderGraphTemplateAttribute : Attribute +{ + /// + /// Creates Shader graph template discovery metadata. + /// + /// + /// Stable template identity used by creation commands. + /// + /// + /// User-facing creation menu label. + /// + public ShaderGraphTemplateAttribute( + string id, + string displayName + ) { + this.id = string.IsNullOrWhiteSpace(id) + ? throw new ArgumentException("Shader graph template identity cannot be empty.", nameof(id)) + : id; + this.displayName = string.IsNullOrWhiteSpace(displayName) + ? throw new ArgumentException("Shader graph template display name cannot be empty.", nameof(displayName)) + : displayName; + } + + /// + /// Gets the stable template identity used by creation commands. + /// + public string id { get; } + + /// + /// Gets the user-facing creation menu label. + /// + public string displayName { get; } +} diff --git a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs index 38854bf4e..2f308cf84 100644 --- a/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs +++ b/src/services/rendering/Inno.Rendering.Shaders/Templates/ShaderGraphTemplateRegistry.cs @@ -8,20 +8,6 @@ namespace Inno.Rendering.Shaders; -/// -/// Describes a creation menu item without retaining a plugin instance. -/// -/// -/// Stable template identity. -/// -/// -/// User-facing label. -/// -public sealed record ShaderGraphTemplateInfo( - string id, - string displayName -); - /// /// Owns generation-safe template discovery and invocation for editor asset creation. /// @@ -160,3 +146,17 @@ protected override void DisposeSnapshot(IReadOnlyDictionary snaps => DisposeExtensions(snapshot.Values.Select(static value => value.template)); } } + +/// +/// Describes a creation menu item without retaining a plugin instance. +/// +/// +/// Stable template identity. +/// +/// +/// User-facing label. +/// +public sealed record ShaderGraphTemplateInfo( + string id, + string displayName +); diff --git a/src/services/rendering/Inno.Rendering/Device/ComputePipelineHandle.cs b/src/services/rendering/Inno.Rendering/Device/ComputePipelineHandle.cs new file mode 100644 index 000000000..1e23cc7d3 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/ComputePipelineHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies a backend-neutral compute pipeline object. +/// +public readonly record struct ComputePipelineHandle +{ + internal ComputePipelineHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a compute pipeline. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsApi.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsApi.cs new file mode 100644 index 000000000..b5723a271 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsApi.cs @@ -0,0 +1,142 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Identifies the graphics API family selected by the host without exposing a backend-native enum. +/// Pipelines use this value only for capability-aware choices and target artifact selection; +/// it does not require separate pipeline or shader source implementations. +/// +public readonly record struct GraphicsApi : IComparable +{ + /// + /// Creates an open, stable backend identity without registering a backend implementation. + /// + /// + /// A portable case-sensitive identifier used in target artifact paths. + /// + /// + /// The identifier is empty or contains nonportable characters. + /// + public GraphicsApi(string value) + { + if (!IsPortableIdentifier(value)) + { + throw new ArgumentException( + "Graphics API IDs must begin with a letter or digit and use only portable letters, numbers, dots, underscores or hyphens.", + nameof(value) + ); + } + this.value = value; + } + + /// + /// Headless validation backend. + /// + public static GraphicsApi noop { get; } = new("Noop"); + + /// + /// Direct3D 11 renderer. + /// + public static GraphicsApi direct3D11 { get; } = new("Direct3D11"); + + /// + /// Direct3D 12 renderer. + /// + public static GraphicsApi direct3D12 { get; } = new("Direct3D12"); + + /// + /// Apple Metal renderer. + /// + public static GraphicsApi metal { get; } = new("Metal"); + + /// + /// Khronos Vulkan renderer. + /// + public static GraphicsApi vulkan { get; } = new("Vulkan"); + + /// + /// Desktop OpenGL renderer. + /// + public static GraphicsApi openGL { get; } = new("OpenGL"); + + /// + /// OpenGL ES renderer. + /// + public static GraphicsApi openGLES { get; } = new("OpenGLES"); + + /// + /// WebGPU renderer. + /// + public static GraphicsApi webGPU { get; } = new("WebGPU"); + + /// + /// Gets the stable backend identity used by target artifacts and provider selection. + /// + public string value { get; } + + /// + /// Gets whether this value contains an initialized backend identity. + /// + public bool isValid => !string.IsNullOrEmpty(value); + + /// + /// Compares two backend identities using stable ordinal ordering. + /// + /// + /// The other backend identity. + /// + /// + /// A negative, zero, or positive value according to ordinal identifier order. + /// + public int CompareTo(GraphicsApi other) => string.Compare(value, other.value, StringComparison.Ordinal); + + /// + /// Formats the exact stable backend identity. + /// + /// + /// The identity, or an empty string for an uninitialized value. + /// + public override string ToString() => value ?? string.Empty; + + /// + /// Parses an open backend identity without consulting a closed engine-side backend list. + /// + /// + /// The exact stable backend identity. + /// + /// + /// The parsed value, or default when parsing fails. + /// + /// + /// True when the identifier is portable and nonempty. + /// + public static bool TryParse( + string? value, + out GraphicsApi api + ) { + api = default; + if (!IsPortableIdentifier(value)) + { + return false; + } + api = new GraphicsApi(value!); + return true; + } + + private static bool IsPortableIdentifier(string? candidate) + { + if (string.IsNullOrEmpty(candidate) || !char.IsAsciiLetterOrDigit(candidate[0])) + { + return false; + } + foreach (char character in candidate) + { + if (!(char.IsAsciiLetterOrDigit(character) || character is '-' or '_' or '.')) + { + return false; + } + } + return true; + } +} diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs index a38e17661..58c4fb06b 100644 --- a/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsCapabilities.cs @@ -3,294 +3,6 @@ namespace Inno.Rendering; -/// -/// Identifies the graphics API family selected by the host without exposing a backend-native enum. -/// Pipelines use this value only for capability-aware choices and target artifact selection; -/// it does not require separate pipeline or shader source implementations. -/// -public readonly record struct GraphicsApi : IComparable -{ - /// - /// Creates an open, stable backend identity without registering a backend implementation. - /// - /// - /// A portable case-sensitive identifier used in target artifact paths. - /// - /// - /// The identifier is empty or contains nonportable characters. - /// - public GraphicsApi(string value) - { - if (!IsPortableIdentifier(value)) - { - throw new ArgumentException( - "Graphics API IDs must begin with a letter or digit and use only portable letters, numbers, dots, underscores or hyphens.", - nameof(value) - ); - } - this.value = value; - } - - /// - /// Headless validation backend. - /// - public static GraphicsApi noop { get; } = new("Noop"); - - /// - /// Direct3D 11 renderer. - /// - public static GraphicsApi direct3D11 { get; } = new("Direct3D11"); - - /// - /// Direct3D 12 renderer. - /// - public static GraphicsApi direct3D12 { get; } = new("Direct3D12"); - - /// - /// Apple Metal renderer. - /// - public static GraphicsApi metal { get; } = new("Metal"); - - /// - /// Khronos Vulkan renderer. - /// - public static GraphicsApi vulkan { get; } = new("Vulkan"); - - /// - /// Desktop OpenGL renderer. - /// - public static GraphicsApi openGL { get; } = new("OpenGL"); - - /// - /// OpenGL ES renderer. - /// - public static GraphicsApi openGLES { get; } = new("OpenGLES"); - - /// - /// WebGPU renderer. - /// - public static GraphicsApi webGPU { get; } = new("WebGPU"); - - /// - /// Gets the stable backend identity used by target artifacts and provider selection. - /// - public string value { get; } - - /// - /// Gets whether this value contains an initialized backend identity. - /// - public bool isValid => !string.IsNullOrEmpty(value); - - /// - /// Compares two backend identities using stable ordinal ordering. - /// - /// - /// The other backend identity. - /// - /// - /// A negative, zero, or positive value according to ordinal identifier order. - /// - public int CompareTo(GraphicsApi other) => string.Compare(value, other.value, StringComparison.Ordinal); - - /// - /// Formats the exact stable backend identity. - /// - /// - /// The identity, or an empty string for an uninitialized value. - /// - public override string ToString() => value ?? string.Empty; - - /// - /// Parses an open backend identity without consulting a closed engine-side backend list. - /// - /// - /// The exact stable backend identity. - /// - /// - /// The parsed value, or default when parsing fails. - /// - /// - /// True when the identifier is portable and nonempty. - /// - public static bool TryParse( - string? value, - out GraphicsApi api - ) { - api = default; - if (!IsPortableIdentifier(value)) - { - return false; - } - api = new GraphicsApi(value!); - return true; - } - - private static bool IsPortableIdentifier(string? candidate) - { - if (string.IsNullOrEmpty(candidate) || !char.IsAsciiLetterOrDigit(candidate[0])) - { - return false; - } - foreach (char character in candidate) - { - if (!(char.IsAsciiLetterOrDigit(character) || character is '-' or '_' or '.')) - { - return false; - } - } - return true; - } -} - -/// -/// Declares backend-neutral optional graphics functionality. -/// -[Flags] -public enum GraphicsCapability -{ - /// - /// No optional feature. - /// - None = 0, - /// - /// Compute shader dispatch. - /// - Compute = 1 << 0, - /// - /// Shader-readable and writable storage buffers. - /// - StorageBuffer = 1 << 1, - /// - /// Indirect draw and dispatch commands. - /// - Indirect = 1 << 2, - /// - /// Independent blend state per color attachment. - /// - IndependentBlend = 1 << 3, - /// - /// Multiple command encoders may record concurrently. - /// - ConcurrentEncoders = 1 << 4, - /// - /// Texture copy operations are supported directly. - /// - TextureBlit = 1 << 5, - /// - /// General GPU buffer copy operations are supported directly. - /// - BufferCopy = 1 << 6, - /// - /// Alpha-to-coverage rasterization is supported. - /// - AlphaToCoverage = 1 << 7, - /// - /// Unsigned 32-bit index buffers are supported. - /// - Index32 = 1 << 8, - /// - /// Instanced draw input is supported. - /// - Instancing = 1 << 9, - /// - /// Additional native presentation surfaces are supported. - /// - SwapChain = 1 << 10, - /// - /// Two-dimensional texture arrays are supported. - /// - Texture2DArray = 1 << 11, - /// - /// Three-dimensional textures are supported. - /// - Texture3D = 1 << 12, - /// - /// Cubemap texture arrays are supported. - /// - TextureCubeArray = 1 << 13, - /// - /// Half-precision vertex attributes are supported. - /// - VertexAttributeHalf = 1 << 14, - /// - /// Packed 10:10:10:2 vertex attributes are supported. - /// - VertexAttributeUInt10 = 1 << 15, - /// - /// Procedural draws using shader vertex identifiers are supported. - /// - ProceduralDraw = 1 << 16, - /// - /// Fragment shaders may write depth explicitly. - /// - FragmentDepth = 1 << 17, - /// - /// Shader-readable and writable storage textures are supported. - /// - StorageTexture = 1 << 18, - /// - /// Asynchronous texture transfer from GPU memory to CPU-visible bytes. - /// - TextureReadback = 1 << 19 -} - -/// -/// Captures device limits used to validate and compile render graphs. -/// -public sealed class GraphicsLimits -{ - /// - /// Creates a graphics limits snapshot. - /// - /// - /// Maximum logical backend views in one frame. - /// - /// - /// Maximum color attachments in one raster pass. - /// - /// - /// Maximum two-dimensional texture extent. - /// - /// - /// Maximum storage bindings in one compute pass. - /// - public GraphicsLimits( - int maxViews, - int maxColorAttachments, - int maxTextureSize, - int maxComputeBindings - ) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxViews); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxColorAttachments); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxTextureSize); - ArgumentOutOfRangeException.ThrowIfNegative(maxComputeBindings); - this.maxViews = maxViews; - this.maxColorAttachments = maxColorAttachments; - this.maxTextureSize = maxTextureSize; - this.maxComputeBindings = maxComputeBindings; - } - - /// - /// Gets the maximum logical backend views in one frame. - /// - public int maxViews { get; } - - /// - /// Gets the maximum color attachments in one raster pass. - /// - public int maxColorAttachments { get; } - - /// - /// Gets the maximum two-dimensional texture extent. - /// - public int maxTextureSize { get; } - - /// - /// Gets the maximum storage bindings in one compute pass. - /// - public int maxComputeBindings { get; } -} - /// /// Provides an immutable capability snapshot for one device generation. /// @@ -496,3 +208,95 @@ RenderStorageAccess access _ => false }; } + +/// +/// Declares backend-neutral optional graphics functionality. +/// +[Flags] +public enum GraphicsCapability +{ + /// + /// No optional feature. + /// + None = 0, + /// + /// Compute shader dispatch. + /// + Compute = 1 << 0, + /// + /// Shader-readable and writable storage buffers. + /// + StorageBuffer = 1 << 1, + /// + /// Indirect draw and dispatch commands. + /// + Indirect = 1 << 2, + /// + /// Independent blend state per color attachment. + /// + IndependentBlend = 1 << 3, + /// + /// Multiple command encoders may record concurrently. + /// + ConcurrentEncoders = 1 << 4, + /// + /// Texture copy operations are supported directly. + /// + TextureBlit = 1 << 5, + /// + /// General GPU buffer copy operations are supported directly. + /// + BufferCopy = 1 << 6, + /// + /// Alpha-to-coverage rasterization is supported. + /// + AlphaToCoverage = 1 << 7, + /// + /// Unsigned 32-bit index buffers are supported. + /// + Index32 = 1 << 8, + /// + /// Instanced draw input is supported. + /// + Instancing = 1 << 9, + /// + /// Additional native presentation surfaces are supported. + /// + SwapChain = 1 << 10, + /// + /// Two-dimensional texture arrays are supported. + /// + Texture2DArray = 1 << 11, + /// + /// Three-dimensional textures are supported. + /// + Texture3D = 1 << 12, + /// + /// Cubemap texture arrays are supported. + /// + TextureCubeArray = 1 << 13, + /// + /// Half-precision vertex attributes are supported. + /// + VertexAttributeHalf = 1 << 14, + /// + /// Packed 10:10:10:2 vertex attributes are supported. + /// + VertexAttributeUInt10 = 1 << 15, + /// + /// Procedural draws using shader vertex identifiers are supported. + /// + ProceduralDraw = 1 << 16, + /// + /// Fragment shaders may write depth explicitly. + /// + FragmentDepth = 1 << 17, + /// + /// Shader-readable and writable storage textures are supported. + /// + StorageTexture = 1 << 18, + /// + /// Asynchronous texture transfer from GPU memory to CPU-visible bytes. + /// + TextureReadback = 1 << 19 +} diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsLimits.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsLimits.cs new file mode 100644 index 000000000..c4b57d6bf --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsLimits.cs @@ -0,0 +1,60 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Captures device limits used to validate and compile render graphs. +/// +public sealed class GraphicsLimits +{ + /// + /// Creates a graphics limits snapshot. + /// + /// + /// Maximum logical backend views in one frame. + /// + /// + /// Maximum color attachments in one raster pass. + /// + /// + /// Maximum two-dimensional texture extent. + /// + /// + /// Maximum storage bindings in one compute pass. + /// + public GraphicsLimits( + int maxViews, + int maxColorAttachments, + int maxTextureSize, + int maxComputeBindings + ) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxViews); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxColorAttachments); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxTextureSize); + ArgumentOutOfRangeException.ThrowIfNegative(maxComputeBindings); + this.maxViews = maxViews; + this.maxColorAttachments = maxColorAttachments; + this.maxTextureSize = maxTextureSize; + this.maxComputeBindings = maxComputeBindings; + } + + /// + /// Gets the maximum logical backend views in one frame. + /// + public int maxViews { get; } + + /// + /// Gets the maximum color attachments in one raster pass. + /// + public int maxColorAttachments { get; } + + /// + /// Gets the maximum two-dimensional texture extent. + /// + public int maxTextureSize { get; } + + /// + /// Gets the maximum storage bindings in one compute pass. + /// + public int maxComputeBindings { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineHandle.cs b/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineHandle.cs new file mode 100644 index 000000000..c1ad500e9 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/GraphicsPipelineHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies a backend-neutral graphics pipeline object. +/// +public readonly record struct GraphicsPipelineHandle +{ + internal GraphicsPipelineHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a graphics pipeline. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/IRenderDevice.cs b/src/services/rendering/Inno.Rendering/Device/IRenderDevice.cs index 3cb19bd8e..8f14a80f9 100644 --- a/src/services/rendering/Inno.Rendering/Device/IRenderDevice.cs +++ b/src/services/rendering/Inno.Rendering/Device/IRenderDevice.cs @@ -2,52 +2,6 @@ namespace Inno.Rendering; -/// -/// Identifies a portable encoded texture container accepted by a render device. -/// -public enum RenderTextureContainer -{ - /// - /// Khronos Texture container containing validated GPU texture payloads. - /// - Ktx -} - -/// -/// Contains backend-recorded GPU command submissions for the current frame. -/// -public readonly record struct RenderDeviceFrameCounters -{ - /// - /// Creates immutable device frame counters. - /// - /// - /// Direct and indirect draw commands submitted so far. - /// - /// - /// Direct and indirect compute dispatches submitted so far. - /// - public RenderDeviceFrameCounters( - int drawCount, - int dispatchCount - ) { - ArgumentOutOfRangeException.ThrowIfNegative(drawCount); - ArgumentOutOfRangeException.ThrowIfNegative(dispatchCount); - this.drawCount = drawCount; - this.dispatchCount = dispatchCount; - } - - /// - /// Gets direct and indirect draw commands submitted during the current frame. - /// - public int drawCount { get; } - - /// - /// Gets direct and indirect compute dispatches submitted during the current frame. - /// - public int dispatchCount { get; } -} - /// /// Owns one graphics backend generation and its frame submission boundary. /// @@ -365,3 +319,14 @@ string name /// void DestroyComputePipeline(ComputePipelineHandle pipeline); } + +/// +/// Identifies a portable encoded texture container accepted by a render device. +/// +public enum RenderTextureContainer +{ + /// + /// Khronos Texture container containing validated GPU texture payloads. + /// + Ktx +} diff --git a/src/services/rendering/Inno.Rendering/Device/PersistentBufferHandle.cs b/src/services/rendering/Inno.Rendering/Device/PersistentBufferHandle.cs new file mode 100644 index 000000000..bfc12f46b --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/PersistentBufferHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies a persistent device buffer without exposing a backend-native handle. +/// +public readonly record struct PersistentBufferHandle +{ + internal PersistentBufferHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a device buffer. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/PersistentTextureHandle.cs b/src/services/rendering/Inno.Rendering/Device/PersistentTextureHandle.cs new file mode 100644 index 000000000..c2c99c47d --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/PersistentTextureHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies a persistent device texture without exposing a backend-native handle. +/// +public readonly record struct PersistentTextureHandle +{ + internal PersistentTextureHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a device texture. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBindingID.cs b/src/services/rendering/Inno.Rendering/Device/RenderBindingID.cs new file mode 100644 index 000000000..6dd4f7175 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderBindingID.cs @@ -0,0 +1,31 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Identifies a shader binding by stable manifest name. +/// +public readonly record struct RenderBindingID +{ + /// + /// Creates a stable shader binding identifier. + /// + /// + /// Stable manifest binding name. + /// + public RenderBindingID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the stable manifest binding name. + /// + public string value { get; } + + /// + /// Gets whether the identifier contains a stable manifest name. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs b/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs index c74446c8c..19c7e773a 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderBlendState.cs @@ -1,95 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace Inno.Rendering; -/// -/// Selects one source or destination blend multiplier. -/// -public enum RenderBlendFactor -{ - /// - /// Multiplies by zero. - /// - Zero, - /// - /// Multiplies by one. - /// - One, - /// - /// Multiplies by source color. - /// - SourceColor, - /// - /// Multiplies by one minus source color. - /// - InverseSourceColor, - /// - /// Multiplies by source alpha. - /// - SourceAlpha, - /// - /// Multiplies by one minus source alpha. - /// - InverseSourceAlpha, - /// - /// Multiplies by destination alpha. - /// - DestinationAlpha, - /// - /// Multiplies by one minus destination alpha. - /// - InverseDestinationAlpha, - /// - /// Multiplies by destination color. - /// - DestinationColor, - /// - /// Multiplies by one minus destination color. - /// - InverseDestinationColor, - /// - /// Uses the saturated source-alpha factor. - /// - SourceAlphaSaturate, - /// - /// Multiplies by the packed constant blend color. - /// - Constant, - /// - /// Multiplies by one minus the packed constant blend color. - /// - InverseConstant -} - -/// -/// Selects the arithmetic operation combining source and destination blend terms. -/// -public enum RenderBlendEquation -{ - /// - /// Adds source and destination terms. - /// - Add, - /// - /// Subtracts the destination term from the source term. - /// - Subtract, - /// - /// Subtracts the source term from the destination term. - /// - ReverseSubtract, - /// - /// Selects the component-wise minimum. - /// - Minimum, - /// - /// Selects the component-wise maximum. - /// - Maximum -} - /// /// Describes independent color and alpha blending without backend-native flags. /// @@ -192,3 +102,89 @@ public static RenderBlendState premultiplied /// public bool alphaToCoverage { get; set; } } + +/// +/// Selects one source or destination blend multiplier. +/// +public enum RenderBlendFactor +{ + /// + /// Multiplies by zero. + /// + Zero, + /// + /// Multiplies by one. + /// + One, + /// + /// Multiplies by source color. + /// + SourceColor, + /// + /// Multiplies by one minus source color. + /// + InverseSourceColor, + /// + /// Multiplies by source alpha. + /// + SourceAlpha, + /// + /// Multiplies by one minus source alpha. + /// + InverseSourceAlpha, + /// + /// Multiplies by destination alpha. + /// + DestinationAlpha, + /// + /// Multiplies by one minus destination alpha. + /// + InverseDestinationAlpha, + /// + /// Multiplies by destination color. + /// + DestinationColor, + /// + /// Multiplies by one minus destination color. + /// + InverseDestinationColor, + /// + /// Uses the saturated source-alpha factor. + /// + SourceAlphaSaturate, + /// + /// Multiplies by the packed constant blend color. + /// + Constant, + /// + /// Multiplies by one minus the packed constant blend color. + /// + InverseConstant +} + +/// +/// Selects the arithmetic operation combining source and destination blend terms. +/// +public enum RenderBlendEquation +{ + /// + /// Adds source and destination terms. + /// + Add, + /// + /// Subtracts the destination term from the source term. + /// + Subtract, + /// + /// Subtracts the source term from the destination term. + /// + ReverseSubtract, + /// + /// Selects the component-wise minimum. + /// + Minimum, + /// + /// Selects the component-wise maximum. + /// + Maximum +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferDescriptor.cs new file mode 100644 index 000000000..04fc0067f --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferDescriptor.cs @@ -0,0 +1,82 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Describes a render-graph buffer independently from a graphics backend. +/// +public sealed class RenderBufferDescriptor : IEquatable +{ + /// + /// Creates a buffer descriptor. + /// + /// + /// Number of addressable elements. + /// + /// + /// Element size in bytes. + /// + /// + /// Permitted operations. + /// + public RenderBufferDescriptor( + int elementCount, + int elementStride, + RenderBufferUsage usage + ) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(elementCount); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(elementStride); + this.elementCount = elementCount; + this.elementStride = elementStride; + this.usage = usage; + } + + /// + /// Gets the number of addressable elements. + /// + public int elementCount { get; } + + /// + /// Gets the element size in bytes. + /// + public int elementStride { get; } + + /// + /// Gets permitted operations. + /// + public RenderBufferUsage usage { get; } + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The value to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public bool Equals(RenderBufferDescriptor? other) + => other is not null + && elementCount == other.elementCount + && elementStride == other.elementStride + && usage == other.usage; + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The object to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public override bool Equals(object? obj) => Equals(obj as RenderBufferDescriptor); + + /// + /// Computes a hash code from the fields that participate in logical equality. + /// + /// + /// A hash code consistent with the implemented equality contract. + /// + public override int GetHashCode() => HashCode.Combine(elementCount, elementStride, usage); +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferHandle.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferHandle.cs new file mode 100644 index 000000000..96e80f674 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferHandle.cs @@ -0,0 +1,26 @@ +namespace Inno.Rendering; + +/// +/// Identifies a frame-scoped render-graph buffer. +/// +public readonly record struct RenderBufferHandle +{ + internal RenderBufferHandle( + int index, + uint generation, + ulong allocationID + ) { + this.index = index; + this.generation = generation; + this.allocationID = allocationID; + } + + internal int index { get; } + internal uint generation { get; } + internal ulong allocationID { get; } + + /// + /// Gets whether the handle was created by a render graph. + /// + public bool isValid => index >= 0 && generation != 0 && allocationID != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferSlice.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferSlice.cs new file mode 100644 index 000000000..09afb84db --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferSlice.cs @@ -0,0 +1,44 @@ +namespace Inno.Rendering; + +/// +/// Identifies one range in a frame upload page without exposing its persistent backing buffer. +/// +public readonly record struct RenderBufferSlice +{ + internal RenderBufferSlice( + PersistentBufferHandle buffer, + int firstElement, + int elementCount, + RenderBufferUsage usage, + ulong frameIndex + ) { + this.buffer = buffer; + this.firstElement = firstElement; + this.elementCount = elementCount; + this.usage = usage; + this.frameIndex = frameIndex; + } + + internal PersistentBufferHandle buffer { get; } + internal ulong frameIndex { get; } + + /// + /// Gets the first uploaded element in the backing frame page. + /// + public int firstElement { get; } + + /// + /// Gets the number of uploaded elements. + /// + public int elementCount { get; } + + /// + /// Gets permitted GPU uses for this slice. + /// + public RenderBufferUsage usage { get; } + + /// + /// Gets whether this slice was produced by a frame upload service. + /// + public bool isValid => buffer.isValid && elementCount > 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferUploads.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferUploadDescriptor.cs similarity index 56% rename from src/services/rendering/Inno.Rendering/Device/RenderBufferUploads.cs rename to src/services/rendering/Inno.Rendering/Device/RenderBufferUploadDescriptor.cs index dcf9b9934..88ae2a69f 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderBufferUploads.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferUploadDescriptor.cs @@ -81,81 +81,3 @@ public RenderBufferUploadDescriptor( /// public RenderIndexFormat indexFormat { get; } } - -/// -/// Identifies one range in a frame upload page without exposing its persistent backing buffer. -/// -public readonly record struct RenderBufferSlice -{ - internal RenderBufferSlice( - PersistentBufferHandle buffer, - int firstElement, - int elementCount, - RenderBufferUsage usage, - ulong frameIndex - ) { - this.buffer = buffer; - this.firstElement = firstElement; - this.elementCount = elementCount; - this.usage = usage; - this.frameIndex = frameIndex; - } - - internal PersistentBufferHandle buffer { get; } - internal ulong frameIndex { get; } - - /// - /// Gets the first uploaded element in the backing frame page. - /// - public int firstElement { get; } - - /// - /// Gets the number of uploaded elements. - /// - public int elementCount { get; } - - /// - /// Gets permitted GPU uses for this slice. - /// - public RenderBufferUsage usage { get; } - - /// - /// Gets whether this slice was produced by a frame upload service. - /// - public bool isValid => buffer.isValid && elementCount > 0; -} - -/// -/// Provides protected slice construction for replaceable frame-upload service implementations. -/// -public abstract class RenderFrameUploadProvider -{ - /// - /// Creates a frame-scoped slice over a provider-owned persistent upload buffer. - /// - /// - /// The persistent upload page backing the slice. - /// - /// - /// The zero-based first uploaded element. - /// - /// - /// The positive number of uploaded elements. - /// - /// - /// The GPU uses supported by the uploaded range. - /// - /// - /// The render frame during which the slice remains valid. - /// - /// - /// An opaque frame-scoped buffer slice. - /// - protected static RenderBufferSlice CreateBufferSlice( - PersistentBufferHandle buffer, - int firstElement, - int elementCount, - RenderBufferUsage usage, - ulong frameIndex - ) => new(buffer, firstElement, elementCount, usage, frameIndex); -} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderBufferUsage.cs b/src/services/rendering/Inno.Rendering/Device/RenderBufferUsage.cs new file mode 100644 index 000000000..ced61e6e3 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderBufferUsage.cs @@ -0,0 +1,43 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Declares intended buffer operations for capability and hazard validation. +/// +[Flags] +public enum RenderBufferUsage +{ + /// + /// Vertex input data. + /// + Vertex = 1 << 0, + /// + /// Index input data. + /// + Index = 1 << 1, + /// + /// Read-only shader data. + /// + Uniform = 1 << 2, + /// + /// Shader-readable and writable storage data. + /// + Storage = 1 << 3, + /// + /// Indirect command data. + /// + Indirect = 1 << 4, + /// + /// Copy operation source. + /// + CopySource = 1 << 5, + /// + /// Copy operation destination. + /// + CopyDestination = 1 << 6, + /// + /// Contents may be replaced at frame safety points. + /// + Dynamic = 1 << 7 +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderCommands.cs b/src/services/rendering/Inno.Rendering/Device/RenderCommandEncoder.cs similarity index 78% rename from src/services/rendering/Inno.Rendering/Device/RenderCommands.cs rename to src/services/rendering/Inno.Rendering/Device/RenderCommandEncoder.cs index 1b9f642c5..89b9c1585 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderCommands.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderCommandEncoder.cs @@ -2,168 +2,6 @@ namespace Inno.Rendering; -/// -/// Identifies a shader binding by stable manifest name. -/// -public readonly record struct RenderBindingID -{ - /// - /// Creates a stable shader binding identifier. - /// - /// - /// Stable manifest binding name. - /// - public RenderBindingID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the stable manifest binding name. - /// - public string value { get; } - - /// - /// Gets whether the identifier contains a stable manifest name. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); -} - -/// -/// Identifies a backend-neutral graphics pipeline object. -/// -public readonly record struct GraphicsPipelineHandle -{ - internal GraphicsPipelineHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a graphics pipeline. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Identifies a backend-neutral compute pipeline object. -/// -public readonly record struct ComputePipelineHandle -{ - internal ComputePipelineHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a compute pipeline. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Describes one texture subresource box for copy and blit commands. -/// -public readonly record struct RenderTextureRegion -{ - /// - /// Creates a texture subresource box. - /// - /// - /// Zero-based mip level. - /// - /// - /// Horizontal texel origin. - /// - /// - /// Vertical texel origin. - /// - /// - /// Array layer or depth-slice origin. - /// - /// - /// Positive texel width. - /// - /// - /// Positive texel height. - /// - /// - /// Positive layer or depth-slice count. - /// - public RenderTextureRegion( - int mip, - int x, - int y, - int layer, - int width, - int height, - int depth = 1 - ) { - ArgumentOutOfRangeException.ThrowIfNegative(mip); - ArgumentOutOfRangeException.ThrowIfNegative(x); - ArgumentOutOfRangeException.ThrowIfNegative(y); - ArgumentOutOfRangeException.ThrowIfNegative(layer); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(depth); - this.mip = mip; - this.x = x; - this.y = y; - this.layer = layer; - this.width = width; - this.height = height; - this.depth = depth; - } - - /// - /// Gets the zero-based mip level. - /// - public int mip { get; } - - /// - /// Gets the horizontal texel origin. - /// - public int x { get; } - - /// - /// Gets the vertical texel origin. - /// - public int y { get; } - - /// - /// Gets the array layer or depth-slice origin. - /// - public int layer { get; } - - /// - /// Gets the texel width. - /// - public int width { get; } - - /// - /// Gets the texel height. - /// - public int height { get; } - - /// - /// Gets the layer or depth-slice count. - /// - public int depth { get; } -} - /// /// Provides backend-neutral draw, dispatch and copy commands for one compiled pass. /// @@ -762,44 +600,3 @@ RenderBufferUsage requiredUsage } } } - -/// -/// Supplies the command encoder and immutable frame identity to a pass callback. -/// -public sealed class RenderPassContext -{ - internal RenderPassContext( - RenderCommandEncoder commands, - ulong frameIndex - ) { - this.commands = commands; - this.frameIndex = frameIndex; - } - - /// - /// Gets the command encoder scoped to the current pass. - /// - public RenderCommandEncoder commands { get; } - - /// - /// Gets the monotonic frame index. - /// - public ulong frameIndex { get; } -} - -/// -/// Executes one frame-scoped pass payload. -/// -/// -/// Neutral pass payload type. -/// -/// -/// Pass payload captured for this frame only. -/// -/// -/// Current pass execution context. -/// -public delegate void RenderPassExecute( - TPassData passData, - RenderPassContext context -); diff --git a/src/services/rendering/Inno.Rendering/Device/RenderProtocolIDs.cs b/src/services/rendering/Inno.Rendering/Device/RenderDataChannelID.cs similarity index 51% rename from src/services/rendering/Inno.Rendering/Device/RenderProtocolIDs.cs rename to src/services/rendering/Inno.Rendering/Device/RenderDataChannelID.cs index fff8859ba..c05f86ec9 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderProtocolIDs.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderDataChannelID.cs @@ -2,42 +2,6 @@ namespace Inno.Rendering; -/// -/// Identifies a pipeline-defined semantic resource without imposing a central resource catalog. -/// -public readonly record struct RenderResourceID -{ - /// - /// Creates an open semantic resource identifier. - /// - /// - /// Globally stable resource protocol value. - /// - public RenderResourceID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the globally stable protocol value. - /// - public string value { get; } - - /// - /// Gets whether the identifier contains a protocol value. - /// - public bool isValid => !string.IsNullOrWhiteSpace(value); - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} - /// /// Identifies one pipeline-owned frame-data channel without constraining its payload model. /// diff --git a/src/services/rendering/Inno.Rendering/Device/RenderDeviceFrameCounters.cs b/src/services/rendering/Inno.Rendering/Device/RenderDeviceFrameCounters.cs new file mode 100644 index 000000000..0ccc561a2 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderDeviceFrameCounters.cs @@ -0,0 +1,38 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Contains backend-recorded GPU command submissions for the current frame. +/// +public readonly record struct RenderDeviceFrameCounters +{ + /// + /// Creates immutable device frame counters. + /// + /// + /// Direct and indirect draw commands submitted so far. + /// + /// + /// Direct and indirect compute dispatches submitted so far. + /// + public RenderDeviceFrameCounters( + int drawCount, + int dispatchCount + ) { + ArgumentOutOfRangeException.ThrowIfNegative(drawCount); + ArgumentOutOfRangeException.ThrowIfNegative(dispatchCount); + this.drawCount = drawCount; + this.dispatchCount = dispatchCount; + } + + /// + /// Gets direct and indirect draw commands submitted during the current frame. + /// + public int drawCount { get; } + + /// + /// Gets direct and indirect compute dispatches submitted during the current frame. + /// + public int dispatchCount { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderFrameUploadProvider.cs b/src/services/rendering/Inno.Rendering/Device/RenderFrameUploadProvider.cs new file mode 100644 index 000000000..35cefb0d4 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderFrameUploadProvider.cs @@ -0,0 +1,36 @@ +namespace Inno.Rendering; + +/// +/// Provides protected slice construction for replaceable frame-upload service implementations. +/// +public abstract class RenderFrameUploadProvider +{ + /// + /// Creates a frame-scoped slice over a provider-owned persistent upload buffer. + /// + /// + /// The persistent upload page backing the slice. + /// + /// + /// The zero-based first uploaded element. + /// + /// + /// The positive number of uploaded elements. + /// + /// + /// The GPU uses supported by the uploaded range. + /// + /// + /// The render frame during which the slice remains valid. + /// + /// + /// An opaque frame-scoped buffer slice. + /// + protected static RenderBufferSlice CreateBufferSlice( + PersistentBufferHandle buffer, + int firstElement, + int elementCount, + RenderBufferUsage usage, + ulong frameIndex + ) => new(buffer, firstElement, elementCount, usage, frameIndex); +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderPassContext.cs b/src/services/rendering/Inno.Rendering/Device/RenderPassContext.cs new file mode 100644 index 000000000..d607b7617 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderPassContext.cs @@ -0,0 +1,25 @@ +namespace Inno.Rendering; + +/// +/// Supplies the command encoder and immutable frame identity to a pass callback. +/// +public sealed class RenderPassContext +{ + internal RenderPassContext( + RenderCommandEncoder commands, + ulong frameIndex + ) { + this.commands = commands; + this.frameIndex = frameIndex; + } + + /// + /// Gets the command encoder scoped to the current pass. + /// + public RenderCommandEncoder commands { get; } + + /// + /// Gets the monotonic frame index. + /// + public ulong frameIndex { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderPassExecute.cs b/src/services/rendering/Inno.Rendering/Device/RenderPassExecute.cs new file mode 100644 index 000000000..39c809f54 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderPassExecute.cs @@ -0,0 +1,18 @@ +namespace Inno.Rendering; + +/// +/// Executes one frame-scoped pass payload. +/// +/// +/// Neutral pass payload type. +/// +/// +/// Pass payload captured for this frame only. +/// +/// +/// Current pass execution context. +/// +public delegate void RenderPassExecute( + TPassData passData, + RenderPassContext context +); diff --git a/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs b/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs index b837f0b90..4a6d0a6b6 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderRasterState.cs @@ -1,82 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace Inno.Rendering; -/// -/// Selects triangle culling for a backend-neutral raster pipeline. -/// -public enum RenderCullMode -{ - /// - /// Disables face culling. - /// - None, - /// - /// Culls front-facing triangles. - /// - Front, - /// - /// Culls back-facing triangles. - /// - Back -} - -/// -/// Selects the winding order interpreted as the front face. -/// -public enum RenderFrontFace -{ - /// - /// Clockwise vertices form a front-facing triangle. - /// - Clockwise, - /// - /// Counter-clockwise vertices form a front-facing triangle. - /// - CounterClockwise -} - -/// -/// Selects depth comparison for a backend-neutral raster pipeline. -/// -public enum RenderDepthCompare -{ - /// - /// Always rejects. - /// - Never, - /// - /// Accepts smaller depth. - /// - Less, - /// - /// Accepts equal depth. - /// - Equal, - /// - /// Accepts smaller or equal depth. - /// - LessEqual, - /// - /// Accepts greater depth. - /// - Greater, - /// - /// Accepts unequal depth. - /// - NotEqual, - /// - /// Accepts greater or equal depth. - /// - GreaterEqual, - /// - /// Always accepts. - /// - Always -} - /// /// Stores backend-neutral fixed-function raster state. /// @@ -179,3 +102,76 @@ RenderPrimitiveTopology topology /// public RenderPrimitiveTopology topology { get; init; } = RenderPrimitiveTopology.TriangleList; } + +/// +/// Selects triangle culling for a backend-neutral raster pipeline. +/// +public enum RenderCullMode +{ + /// + /// Disables face culling. + /// + None, + /// + /// Culls front-facing triangles. + /// + Front, + /// + /// Culls back-facing triangles. + /// + Back +} + +/// +/// Selects the winding order interpreted as the front face. +/// +public enum RenderFrontFace +{ + /// + /// Clockwise vertices form a front-facing triangle. + /// + Clockwise, + /// + /// Counter-clockwise vertices form a front-facing triangle. + /// + CounterClockwise +} + +/// +/// Selects depth comparison for a backend-neutral raster pipeline. +/// +public enum RenderDepthCompare +{ + /// + /// Always rejects. + /// + Never, + /// + /// Accepts smaller depth. + /// + Less, + /// + /// Accepts equal depth. + /// + Equal, + /// + /// Accepts smaller or equal depth. + /// + LessEqual, + /// + /// Accepts greater depth. + /// + Greater, + /// + /// Accepts unequal depth. + /// + NotEqual, + /// + /// Accepts greater or equal depth. + /// + GreaterEqual, + /// + /// Always accepts. + /// + Always +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderResourceID.cs b/src/services/rendering/Inno.Rendering/Device/RenderResourceID.cs new file mode 100644 index 000000000..16d21287e --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderResourceID.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Identifies a pipeline-defined semantic resource without imposing a central resource catalog. +/// +public readonly record struct RenderResourceID +{ + /// + /// Creates an open semantic resource identifier. + /// + /// + /// Globally stable resource protocol value. + /// + public RenderResourceID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the globally stable protocol value. + /// + public string value { get; } + + /// + /// Gets whether the identifier contains a protocol value. + /// + public bool isValid => !string.IsNullOrWhiteSpace(value); + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderResources.cs b/src/services/rendering/Inno.Rendering/Device/RenderResources.cs deleted file mode 100644 index d63390879..000000000 --- a/src/services/rendering/Inno.Rendering/Device/RenderResources.cs +++ /dev/null @@ -1,555 +0,0 @@ -using System; - -namespace Inno.Rendering; - -/// -/// Declares backend-neutral texture storage formats. -/// -public enum RenderTextureFormat -{ - /// - /// Eight-bit single-channel normalized format. - /// - R8, - /// - /// Eight-bit two-channel normalized format. - /// - RG8, - /// - /// Eight-bit four-channel linear normalized format. - /// - RGBA8, - /// - /// Eight-bit four-channel sRGB format. - /// - RGBA8Srgb, - /// - /// Ten-bit RGB and two-bit alpha normalized format. - /// - RGB10A2, - /// - /// Eleven-bit RGB floating-point format. - /// - RG11B10Float, - /// - /// Half-precision four-channel floating-point format. - /// - RGBA16Float, - /// - /// Single-channel 32-bit floating-point format. - /// - R32Float, - /// - /// Twenty-four-bit depth and eight-bit stencil format. - /// - Depth24Stencil8, - /// - /// Thirty-two-bit floating-point depth format. - /// - Depth32Float -} - -/// -/// Identifies the dimensional shape of a backend-neutral texture resource. -/// -public enum RenderTextureDimension -{ - /// - /// Two-dimensional texture with optional array layers. - /// - Texture2D, - /// - /// Three-dimensional volume texture. - /// - Texture3D, - /// - /// Cubemap texture with optional cubemap array layers. - /// - Cube -} - -/// -/// Declares intended texture operations for capability and hazard validation. -/// -[Flags] -public enum RenderTextureUsage -{ - /// - /// Shader-readable texture. - /// - Sampled = 1 << 0, - /// - /// Raster color attachment. - /// - ColorAttachment = 1 << 1, - /// - /// Raster depth or stencil attachment. - /// - DepthStencilAttachment = 1 << 2, - /// - /// Shader-readable and writable unordered texture. - /// - Storage = 1 << 3, - /// - /// Copy operation source. - /// - CopySource = 1 << 4, - /// - /// Copy operation destination. - /// - CopyDestination = 1 << 5, - /// - /// Asynchronous transfer from GPU texture memory to CPU-visible bytes. - /// - Readback = 1 << 6 -} - -/// -/// Declares intended buffer operations for capability and hazard validation. -/// -[Flags] -public enum RenderBufferUsage -{ - /// - /// Vertex input data. - /// - Vertex = 1 << 0, - /// - /// Index input data. - /// - Index = 1 << 1, - /// - /// Read-only shader data. - /// - Uniform = 1 << 2, - /// - /// Shader-readable and writable storage data. - /// - Storage = 1 << 3, - /// - /// Indirect command data. - /// - Indirect = 1 << 4, - /// - /// Copy operation source. - /// - CopySource = 1 << 5, - /// - /// Copy operation destination. - /// - CopyDestination = 1 << 6, - /// - /// Contents may be replaced at frame safety points. - /// - Dynamic = 1 << 7 -} - -/// -/// Describes a render-graph texture independently from a graphics backend. -/// -public sealed class RenderTextureDescriptor : IEquatable -{ - /// - /// Creates a texture descriptor. - /// - /// - /// Texture width in pixels. - /// - /// - /// Texture height in pixels. - /// - /// - /// Storage format. - /// - /// - /// Permitted operations. - /// - /// - /// Number of mip levels. - /// - /// - /// Number of array layers. - /// - /// - /// Raster sample count. - /// - /// - /// Texture dimensional shape. - /// - /// - /// Base mip depth for a three-dimensional texture. - /// - public RenderTextureDescriptor( - int width, - int height, - RenderTextureFormat format, - RenderTextureUsage usage, - int mipCount = 1, - int arrayLayers = 1, - int sampleCount = 1, - RenderTextureDimension dimension = RenderTextureDimension.Texture2D, - int depth = 1 - ) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(mipCount); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(arrayLayers); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(depth); - if (sampleCount is not (1 or 2 or 4 or 8 or 16)) - { - throw new ArgumentOutOfRangeException(nameof(sampleCount), "Sample count must be 1, 2, 4, 8, or 16."); - } - - switch (dimension) - { - case RenderTextureDimension.Texture2D when depth != 1: - throw new ArgumentException("A two-dimensional texture must have depth one.", nameof(depth)); - case RenderTextureDimension.Texture3D when arrayLayers != 1: - throw new ArgumentException( - "A three-dimensional texture cannot also declare array layers.", - nameof(arrayLayers) - ); - case RenderTextureDimension.Texture3D when sampleCount != 1: - throw new ArgumentException("A three-dimensional texture cannot be multisampled.", nameof(sampleCount)); - case RenderTextureDimension.Cube when width != height: - throw new ArgumentException("Cubemap width and height must be equal.", nameof(height)); - case RenderTextureDimension.Cube when depth != 1: - throw new ArgumentException("A cubemap must have depth one.", nameof(depth)); - case RenderTextureDimension.Cube when sampleCount != 1: - throw new ArgumentException("A cubemap cannot be multisampled.", nameof(sampleCount)); - case RenderTextureDimension.Texture2D: - case RenderTextureDimension.Texture3D: - case RenderTextureDimension.Cube: - break; - default: - throw new ArgumentOutOfRangeException(nameof(dimension)); - } - - this.width = width; - this.height = height; - this.format = format; - this.usage = usage; - this.mipCount = mipCount; - this.arrayLayers = arrayLayers; - this.sampleCount = sampleCount; - this.dimension = dimension; - this.depth = depth; - } - - /// - /// Gets the texture width in pixels. - /// - public int width { get; } - - /// - /// Gets the texture height in pixels. - /// - public int height { get; } - - /// - /// Gets the storage format. - /// - public RenderTextureFormat format { get; } - - /// - /// Gets permitted operations. - /// - public RenderTextureUsage usage { get; } - - /// - /// Gets the number of mip levels. - /// - public int mipCount { get; } - - /// - /// Gets the number of array layers. - /// - public int arrayLayers { get; } - - /// - /// Gets the raster sample count. - /// - public int sampleCount { get; } - - /// - /// Gets the dimensional texture shape. - /// - public RenderTextureDimension dimension { get; } - - /// - /// Gets the base mip depth for a three-dimensional texture. - /// - public int depth { get; } - - /// - /// Gets the number of independently addressable layers or slices at one mip level. - /// - /// - /// Zero-based mip level. - /// - /// - /// The array-layer count for 2D textures, six faces per cubemap layer, or the mip depth for 3D textures. - /// - public int GetSubresourceLayerCount(int mipLevel) - { - if ((uint)mipLevel >= (uint)mipCount) - { - throw new ArgumentOutOfRangeException(nameof(mipLevel)); - } - return dimension switch - { - RenderTextureDimension.Texture2D => arrayLayers, - RenderTextureDimension.Texture3D => Math.Max(1, depth >> mipLevel), - RenderTextureDimension.Cube => checked(arrayLayers * 6), - _ => throw new ArgumentOutOfRangeException(nameof(dimension)) - }; - } - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// The value to compare with this instance. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - public bool Equals(RenderTextureDescriptor? other) - => other is not null - && width == other.width - && height == other.height - && format == other.format - && usage == other.usage - && mipCount == other.mipCount - && arrayLayers == other.arrayLayers - && sampleCount == other.sampleCount - && dimension == other.dimension - && depth == other.depth; - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// The object to compare with this instance. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - public override bool Equals(object? obj) => Equals(obj as RenderTextureDescriptor); - - /// - /// Computes a hash code from the fields that participate in logical equality. - /// - /// - /// A hash code consistent with the implemented equality contract. - /// - public override int GetHashCode() - { - var hash = new HashCode(); - hash.Add(width); - hash.Add(height); - hash.Add(format); - hash.Add(usage); - hash.Add(mipCount); - hash.Add(arrayLayers); - hash.Add(sampleCount); - hash.Add(dimension); - hash.Add(depth); - return hash.ToHashCode(); - } -} - -/// -/// Describes a render-graph buffer independently from a graphics backend. -/// -public sealed class RenderBufferDescriptor : IEquatable -{ - /// - /// Creates a buffer descriptor. - /// - /// - /// Number of addressable elements. - /// - /// - /// Element size in bytes. - /// - /// - /// Permitted operations. - /// - public RenderBufferDescriptor( - int elementCount, - int elementStride, - RenderBufferUsage usage - ) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(elementCount); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(elementStride); - this.elementCount = elementCount; - this.elementStride = elementStride; - this.usage = usage; - } - - /// - /// Gets the number of addressable elements. - /// - public int elementCount { get; } - - /// - /// Gets the element size in bytes. - /// - public int elementStride { get; } - - /// - /// Gets permitted operations. - /// - public RenderBufferUsage usage { get; } - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// The value to compare with this instance. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - public bool Equals(RenderBufferDescriptor? other) - => other is not null - && elementCount == other.elementCount - && elementStride == other.elementStride - && usage == other.usage; - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// The object to compare with this instance. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - public override bool Equals(object? obj) => Equals(obj as RenderBufferDescriptor); - - /// - /// Computes a hash code from the fields that participate in logical equality. - /// - /// - /// A hash code consistent with the implemented equality contract. - /// - public override int GetHashCode() => HashCode.Combine(elementCount, elementStride, usage); -} - -/// -/// Identifies a frame-scoped render-graph texture. -/// -public readonly record struct RenderTextureHandle -{ - internal RenderTextureHandle( - int index, - uint generation, - ulong allocationID - ) { - this.index = index; - this.generation = generation; - this.allocationID = allocationID; - } - - internal int index { get; } - internal uint generation { get; } - internal ulong allocationID { get; } - - /// - /// Gets whether the handle was created by a render graph. - /// - public bool isValid => index >= 0 && generation != 0 && allocationID != 0; -} - -/// -/// Identifies a frame-scoped render-graph buffer. -/// -public readonly record struct RenderBufferHandle -{ - internal RenderBufferHandle( - int index, - uint generation, - ulong allocationID - ) { - this.index = index; - this.generation = generation; - this.allocationID = allocationID; - } - - internal int index { get; } - internal uint generation { get; } - internal ulong allocationID { get; } - - /// - /// Gets whether the handle was created by a render graph. - /// - public bool isValid => index >= 0 && generation != 0 && allocationID != 0; -} - -/// -/// Identifies a persistent device texture without exposing a backend-native handle. -/// -public readonly record struct PersistentTextureHandle -{ - internal PersistentTextureHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a device texture. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Identifies a persistent device buffer without exposing a backend-native handle. -/// -public readonly record struct PersistentBufferHandle -{ - internal PersistentBufferHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a device buffer. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - -/// -/// Identifies a persistent presentation surface without exposing a backend framebuffer or swapchain handle. -/// -public readonly record struct RenderSurfaceHandle -{ - internal RenderSurfaceHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a presentation surface. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs b/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs index ffd3017b4..4af29f4f2 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderSamplerState.cs @@ -1,51 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; -/// -/// Selects texture filtering independently from a graphics backend. -/// -public enum RenderSamplerFilter -{ - /// - /// Uses nearest-neighbor filtering. - /// - Point, - /// - /// Uses linear filtering. - /// - Linear, - /// - /// Uses anisotropic filtering when supported. - /// - Anisotropic -} - -/// -/// Selects texture addressing independently for each coordinate axis. -/// -public enum RenderSamplerAddressMode -{ - /// - /// Repeats texture coordinates. - /// - Repeat, - /// - /// Mirrors repeated texture coordinates. - /// - Mirror, - /// - /// Clamps coordinates to the texture edge. - /// - Clamp, - /// - /// Samples the backend border color outside the texture. - /// - Border -} - /// /// Describes one native-serializable backend-neutral sampler binding. /// @@ -177,3 +133,45 @@ RenderSamplerState right RenderSamplerState right ) => !left.Equals(right); } + +/// +/// Selects texture filtering independently from a graphics backend. +/// +public enum RenderSamplerFilter +{ + /// + /// Uses nearest-neighbor filtering. + /// + Point, + /// + /// Uses linear filtering. + /// + Linear, + /// + /// Uses anisotropic filtering when supported. + /// + Anisotropic +} + +/// +/// Selects texture addressing independently for each coordinate axis. +/// +public enum RenderSamplerAddressMode +{ + /// + /// Repeats texture coordinates. + /// + Repeat, + /// + /// Mirrors repeated texture coordinates. + /// + Mirror, + /// + /// Clamps coordinates to the texture edge. + /// + Clamp, + /// + /// Samples the backend border color outside the texture. + /// + Border +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs index 23d32b0ac..828097d9d 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderShaderBindingDescriptor.cs @@ -1,70 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; namespace Inno.Rendering; -/// -/// Identifies a shader interface binding domain. -/// -public enum RenderShaderBindingKind -{ - /// - /// Vector or matrix uniform data. - /// - Uniform, - /// - /// Sampled texture and sampler state. - /// - Texture, - /// - /// Shader-readable or writable storage texture. - /// - StorageTexture, - /// - /// Compute-readable or writable buffer. - /// - StorageBuffer -} - -/// -/// Identifies the native-independent shape of one uniform binding. -/// -public enum RenderUniformType -{ - /// - /// Four-component 32-bit floating-point vector. - /// - Vector4, - /// - /// Three-by-three 32-bit floating-point matrix. - /// - Matrix3x3, - /// - /// Four-by-four 32-bit floating-point matrix. - /// - Matrix4x4 -} - -/// -/// Selects unordered storage-resource access for one shader binding. -/// -public enum RenderStorageAccess -{ - /// - /// Shader read-only access. - /// - Read, - /// - /// Shader write-only access. - /// - Write, - /// - /// Shader read and write access. - /// - ReadWrite -} - /// /// Declares one manifest-derived shader binding used for reflection validation. /// @@ -167,3 +104,64 @@ public RenderShaderBindingDescriptor( /// public string nativeName { get; } } + +/// +/// Identifies a shader interface binding domain. +/// +public enum RenderShaderBindingKind +{ + /// + /// Vector or matrix uniform data. + /// + Uniform, + /// + /// Sampled texture and sampler state. + /// + Texture, + /// + /// Shader-readable or writable storage texture. + /// + StorageTexture, + /// + /// Compute-readable or writable buffer. + /// + StorageBuffer +} + +/// +/// Identifies the native-independent shape of one uniform binding. +/// +public enum RenderUniformType +{ + /// + /// Four-component 32-bit floating-point vector. + /// + Vector4, + /// + /// Three-by-three 32-bit floating-point matrix. + /// + Matrix3x3, + /// + /// Four-by-four 32-bit floating-point matrix. + /// + Matrix4x4 +} + +/// +/// Selects unordered storage-resource access for one shader binding. +/// +public enum RenderStorageAccess +{ + /// + /// Shader read-only access. + /// + Read, + /// + /// Shader write-only access. + /// + Write, + /// + /// Shader read and write access. + /// + ReadWrite +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderStencilFaceState.cs b/src/services/rendering/Inno.Rendering/Device/RenderStencilFaceState.cs new file mode 100644 index 000000000..e26710174 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderStencilFaceState.cs @@ -0,0 +1,54 @@ +namespace Inno.Rendering; + +/// +/// Describes stencil behavior for one triangle face orientation. +/// +public readonly record struct RenderStencilFaceState +{ + /// + /// Creates one face stencil state. + /// + /// + /// Stencil comparison. + /// + /// + /// Operation after stencil comparison failure. + /// + /// + /// Operation after stencil success and depth failure. + /// + /// + /// Operation after stencil and depth success. + /// + public RenderStencilFaceState( + RenderStencilCompare compare, + RenderStencilOperation fail, + RenderStencilOperation depthFail, + RenderStencilOperation pass + ) { + this.compare = compare; + this.fail = fail; + this.depthFail = depthFail; + this.pass = pass; + } + + /// + /// Gets stencil comparison. + /// + public RenderStencilCompare compare { get; } + + /// + /// Gets the stencil-failure operation. + /// + public RenderStencilOperation fail { get; } + + /// + /// Gets the depth-failure operation. + /// + public RenderStencilOperation depthFail { get; } + + /// + /// Gets the complete-pass operation. + /// + public RenderStencilOperation pass { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs b/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs index d2b8a59e8..805c44fd9 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderStencilState.cs @@ -1,140 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace Inno.Rendering; -/// -/// Selects the comparison applied to stencil reference and stored values. -/// -public enum RenderStencilCompare -{ - /// - /// Never passes. - /// - Never, - /// - /// Passes when reference is smaller. - /// - Less, - /// - /// Passes when values are equal. - /// - Equal, - /// - /// Passes when reference is smaller or equal. - /// - LessEqual, - /// - /// Passes when reference is greater. - /// - Greater, - /// - /// Passes when values differ. - /// - NotEqual, - /// - /// Passes when reference is greater or equal. - /// - GreaterEqual, - /// - /// Always passes. - /// - Always -} - -/// -/// Selects the update applied to a stencil value. -/// -public enum RenderStencilOperation -{ - /// - /// Keeps the stored value. - /// - Keep, - /// - /// Clears the stored value to zero. - /// - Zero, - /// - /// Replaces the stored value with the reference. - /// - Replace, - /// - /// Increments and clamps the stored value. - /// - IncrementClamp, - /// - /// Increments and wraps the stored value. - /// - IncrementWrap, - /// - /// Decrements and clamps the stored value. - /// - DecrementClamp, - /// - /// Decrements and wraps the stored value. - /// - DecrementWrap, - /// - /// Bitwise-inverts the stored value. - /// - Invert -} - -/// -/// Describes stencil behavior for one triangle face orientation. -/// -public readonly record struct RenderStencilFaceState -{ - /// - /// Creates one face stencil state. - /// - /// - /// Stencil comparison. - /// - /// - /// Operation after stencil comparison failure. - /// - /// - /// Operation after stencil success and depth failure. - /// - /// - /// Operation after stencil and depth success. - /// - public RenderStencilFaceState( - RenderStencilCompare compare, - RenderStencilOperation fail, - RenderStencilOperation depthFail, - RenderStencilOperation pass - ) { - this.compare = compare; - this.fail = fail; - this.depthFail = depthFail; - this.pass = pass; - } - - /// - /// Gets stencil comparison. - /// - public RenderStencilCompare compare { get; } - - /// - /// Gets the stencil-failure operation. - /// - public RenderStencilOperation fail { get; } - - /// - /// Gets the depth-failure operation. - /// - public RenderStencilOperation depthFail { get; } - - /// - /// Gets the complete-pass operation. - /// - public RenderStencilOperation pass { get; } -} - /// /// Describes complete two-sided stencil state for one draw. /// @@ -227,3 +92,81 @@ RenderStencilFaceState back RenderStencilOperation.Keep ); } + +/// +/// Selects the comparison applied to stencil reference and stored values. +/// +public enum RenderStencilCompare +{ + /// + /// Never passes. + /// + Never, + /// + /// Passes when reference is smaller. + /// + Less, + /// + /// Passes when values are equal. + /// + Equal, + /// + /// Passes when reference is smaller or equal. + /// + LessEqual, + /// + /// Passes when reference is greater. + /// + Greater, + /// + /// Passes when values differ. + /// + NotEqual, + /// + /// Passes when reference is greater or equal. + /// + GreaterEqual, + /// + /// Always passes. + /// + Always +} + +/// +/// Selects the update applied to a stencil value. +/// +public enum RenderStencilOperation +{ + /// + /// Keeps the stored value. + /// + Keep, + /// + /// Clears the stored value to zero. + /// + Zero, + /// + /// Replaces the stored value with the reference. + /// + Replace, + /// + /// Increments and clamps the stored value. + /// + IncrementClamp, + /// + /// Increments and wraps the stored value. + /// + IncrementWrap, + /// + /// Decrements and clamps the stored value. + /// + DecrementClamp, + /// + /// Decrements and wraps the stored value. + /// + DecrementWrap, + /// + /// Bitwise-inverts the stored value. + /// + Invert +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderSurfaceHandle.cs b/src/services/rendering/Inno.Rendering/Device/RenderSurfaceHandle.cs new file mode 100644 index 000000000..f6ad3417c --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderSurfaceHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies a persistent presentation surface without exposing a backend framebuffer or swapchain handle. +/// +public readonly record struct RenderSurfaceHandle +{ + internal RenderSurfaceHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a presentation surface. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureDescriptor.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureDescriptor.cs new file mode 100644 index 000000000..a9edf563d --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureDescriptor.cs @@ -0,0 +1,218 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Describes a render-graph texture independently from a graphics backend. +/// +public sealed class RenderTextureDescriptor : IEquatable +{ + /// + /// Creates a texture descriptor. + /// + /// + /// Texture width in pixels. + /// + /// + /// Texture height in pixels. + /// + /// + /// Storage format. + /// + /// + /// Permitted operations. + /// + /// + /// Number of mip levels. + /// + /// + /// Number of array layers. + /// + /// + /// Raster sample count. + /// + /// + /// Texture dimensional shape. + /// + /// + /// Base mip depth for a three-dimensional texture. + /// + public RenderTextureDescriptor( + int width, + int height, + RenderTextureFormat format, + RenderTextureUsage usage, + int mipCount = 1, + int arrayLayers = 1, + int sampleCount = 1, + RenderTextureDimension dimension = RenderTextureDimension.Texture2D, + int depth = 1 + ) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(mipCount); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(arrayLayers); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(depth); + if (sampleCount is not (1 or 2 or 4 or 8 or 16)) + { + throw new ArgumentOutOfRangeException(nameof(sampleCount), "Sample count must be 1, 2, 4, 8, or 16."); + } + + switch (dimension) + { + case RenderTextureDimension.Texture2D when depth != 1: + throw new ArgumentException("A two-dimensional texture must have depth one.", nameof(depth)); + case RenderTextureDimension.Texture3D when arrayLayers != 1: + throw new ArgumentException( + "A three-dimensional texture cannot also declare array layers.", + nameof(arrayLayers) + ); + case RenderTextureDimension.Texture3D when sampleCount != 1: + throw new ArgumentException("A three-dimensional texture cannot be multisampled.", nameof(sampleCount)); + case RenderTextureDimension.Cube when width != height: + throw new ArgumentException("Cubemap width and height must be equal.", nameof(height)); + case RenderTextureDimension.Cube when depth != 1: + throw new ArgumentException("A cubemap must have depth one.", nameof(depth)); + case RenderTextureDimension.Cube when sampleCount != 1: + throw new ArgumentException("A cubemap cannot be multisampled.", nameof(sampleCount)); + case RenderTextureDimension.Texture2D: + case RenderTextureDimension.Texture3D: + case RenderTextureDimension.Cube: + break; + default: + throw new ArgumentOutOfRangeException(nameof(dimension)); + } + + this.width = width; + this.height = height; + this.format = format; + this.usage = usage; + this.mipCount = mipCount; + this.arrayLayers = arrayLayers; + this.sampleCount = sampleCount; + this.dimension = dimension; + this.depth = depth; + } + + /// + /// Gets the texture width in pixels. + /// + public int width { get; } + + /// + /// Gets the texture height in pixels. + /// + public int height { get; } + + /// + /// Gets the storage format. + /// + public RenderTextureFormat format { get; } + + /// + /// Gets permitted operations. + /// + public RenderTextureUsage usage { get; } + + /// + /// Gets the number of mip levels. + /// + public int mipCount { get; } + + /// + /// Gets the number of array layers. + /// + public int arrayLayers { get; } + + /// + /// Gets the raster sample count. + /// + public int sampleCount { get; } + + /// + /// Gets the dimensional texture shape. + /// + public RenderTextureDimension dimension { get; } + + /// + /// Gets the base mip depth for a three-dimensional texture. + /// + public int depth { get; } + + /// + /// Gets the number of independently addressable layers or slices at one mip level. + /// + /// + /// Zero-based mip level. + /// + /// + /// The array-layer count for 2D textures, six faces per cubemap layer, or the mip depth for 3D textures. + /// + public int GetSubresourceLayerCount(int mipLevel) + { + if ((uint)mipLevel >= (uint)mipCount) + { + throw new ArgumentOutOfRangeException(nameof(mipLevel)); + } + return dimension switch + { + RenderTextureDimension.Texture2D => arrayLayers, + RenderTextureDimension.Texture3D => Math.Max(1, depth >> mipLevel), + RenderTextureDimension.Cube => checked(arrayLayers * 6), + _ => throw new ArgumentOutOfRangeException(nameof(dimension)) + }; + } + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The value to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public bool Equals(RenderTextureDescriptor? other) + => other is not null + && width == other.width + && height == other.height + && format == other.format + && usage == other.usage + && mipCount == other.mipCount + && arrayLayers == other.arrayLayers + && sampleCount == other.sampleCount + && dimension == other.dimension + && depth == other.depth; + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The object to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public override bool Equals(object? obj) => Equals(obj as RenderTextureDescriptor); + + /// + /// Computes a hash code from the fields that participate in logical equality. + /// + /// + /// A hash code consistent with the implemented equality contract. + /// + public override int GetHashCode() + { + var hash = new HashCode(); + hash.Add(width); + hash.Add(height); + hash.Add(format); + hash.Add(usage); + hash.Add(mipCount); + hash.Add(arrayLayers); + hash.Add(sampleCount); + hash.Add(dimension); + hash.Add(depth); + return hash.ToHashCode(); + } +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureDimension.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureDimension.cs new file mode 100644 index 000000000..4eca7bbc4 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureDimension.cs @@ -0,0 +1,20 @@ +namespace Inno.Rendering; + +/// +/// Identifies the dimensional shape of a backend-neutral texture resource. +/// +public enum RenderTextureDimension +{ + /// + /// Two-dimensional texture with optional array layers. + /// + Texture2D, + /// + /// Three-dimensional volume texture. + /// + Texture3D, + /// + /// Cubemap texture with optional cubemap array layers. + /// + Cube +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureFormat.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureFormat.cs new file mode 100644 index 000000000..43bcf28a0 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureFormat.cs @@ -0,0 +1,48 @@ +namespace Inno.Rendering; + +/// +/// Declares backend-neutral texture storage formats. +/// +public enum RenderTextureFormat +{ + /// + /// Eight-bit single-channel normalized format. + /// + R8, + /// + /// Eight-bit two-channel normalized format. + /// + RG8, + /// + /// Eight-bit four-channel linear normalized format. + /// + RGBA8, + /// + /// Eight-bit four-channel sRGB format. + /// + RGBA8Srgb, + /// + /// Ten-bit RGB and two-bit alpha normalized format. + /// + RGB10A2, + /// + /// Eleven-bit RGB floating-point format. + /// + RG11B10Float, + /// + /// Half-precision four-channel floating-point format. + /// + RGBA16Float, + /// + /// Single-channel 32-bit floating-point format. + /// + R32Float, + /// + /// Twenty-four-bit depth and eight-bit stencil format. + /// + Depth24Stencil8, + /// + /// Thirty-two-bit floating-point depth format. + /// + Depth32Float +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureHandle.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureHandle.cs new file mode 100644 index 000000000..677dc3a19 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureHandle.cs @@ -0,0 +1,26 @@ +namespace Inno.Rendering; + +/// +/// Identifies a frame-scoped render-graph texture. +/// +public readonly record struct RenderTextureHandle +{ + internal RenderTextureHandle( + int index, + uint generation, + ulong allocationID + ) { + this.index = index; + this.generation = generation; + this.allocationID = allocationID; + } + + internal int index { get; } + internal uint generation { get; } + internal ulong allocationID { get; } + + /// + /// Gets whether the handle was created by a render graph. + /// + public bool isValid => index >= 0 && generation != 0 && allocationID != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackHandle.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackHandle.cs new file mode 100644 index 000000000..272669acb --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackHandle.cs @@ -0,0 +1,23 @@ +namespace Inno.Rendering; + +/// +/// Identifies one backend-neutral asynchronous texture readback operation. +/// +public readonly record struct RenderTextureReadbackHandle +{ + internal RenderTextureReadbackHandle( + ulong value, + uint deviceGeneration + ) { + this.value = value; + this.deviceGeneration = deviceGeneration; + } + + internal ulong value { get; } + internal uint deviceGeneration { get; } + + /// + /// Gets whether the handle identifies a device readback operation. + /// + public bool isValid => value != 0 && deviceGeneration != 0; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureReadback.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackResult.cs similarity index 76% rename from src/services/rendering/Inno.Rendering/Device/RenderTextureReadback.cs rename to src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackResult.cs index ce71bd931..27931258d 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderTextureReadback.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureReadbackResult.cs @@ -2,28 +2,6 @@ namespace Inno.Rendering; -/// -/// Identifies one backend-neutral asynchronous texture readback operation. -/// -public readonly record struct RenderTextureReadbackHandle -{ - internal RenderTextureReadbackHandle( - ulong value, - uint deviceGeneration - ) { - this.value = value; - this.deviceGeneration = deviceGeneration; - } - - internal ulong value { get; } - internal uint deviceGeneration { get; } - - /// - /// Gets whether the handle identifies a device readback operation. - /// - public bool isValid => value != 0 && deviceGeneration != 0; -} - /// /// Contains immutable bytes copied from one complete texture mip. /// diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureRegion.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureRegion.cs new file mode 100644 index 000000000..5390db5d2 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureRegion.cs @@ -0,0 +1,93 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Describes one texture subresource box for copy and blit commands. +/// +public readonly record struct RenderTextureRegion +{ + /// + /// Creates a texture subresource box. + /// + /// + /// Zero-based mip level. + /// + /// + /// Horizontal texel origin. + /// + /// + /// Vertical texel origin. + /// + /// + /// Array layer or depth-slice origin. + /// + /// + /// Positive texel width. + /// + /// + /// Positive texel height. + /// + /// + /// Positive layer or depth-slice count. + /// + public RenderTextureRegion( + int mip, + int x, + int y, + int layer, + int width, + int height, + int depth = 1 + ) { + ArgumentOutOfRangeException.ThrowIfNegative(mip); + ArgumentOutOfRangeException.ThrowIfNegative(x); + ArgumentOutOfRangeException.ThrowIfNegative(y); + ArgumentOutOfRangeException.ThrowIfNegative(layer); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(depth); + this.mip = mip; + this.x = x; + this.y = y; + this.layer = layer; + this.width = width; + this.height = height; + this.depth = depth; + } + + /// + /// Gets the zero-based mip level. + /// + public int mip { get; } + + /// + /// Gets the horizontal texel origin. + /// + public int x { get; } + + /// + /// Gets the vertical texel origin. + /// + public int y { get; } + + /// + /// Gets the array layer or depth-slice origin. + /// + public int layer { get; } + + /// + /// Gets the texel width. + /// + public int width { get; } + + /// + /// Gets the texel height. + /// + public int height { get; } + + /// + /// Gets the layer or depth-slice count. + /// + public int depth { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderTextureUsage.cs b/src/services/rendering/Inno.Rendering/Device/RenderTextureUsage.cs new file mode 100644 index 000000000..bda591e32 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderTextureUsage.cs @@ -0,0 +1,39 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Declares intended texture operations for capability and hazard validation. +/// +[Flags] +public enum RenderTextureUsage +{ + /// + /// Shader-readable texture. + /// + Sampled = 1 << 0, + /// + /// Raster color attachment. + /// + ColorAttachment = 1 << 1, + /// + /// Raster depth or stencil attachment. + /// + DepthStencilAttachment = 1 << 2, + /// + /// Shader-readable and writable unordered texture. + /// + Storage = 1 << 3, + /// + /// Copy operation source. + /// + CopySource = 1 << 4, + /// + /// Copy operation destination. + /// + CopyDestination = 1 << 5, + /// + /// Asynchronous transfer from GPU texture memory to CPU-visible bytes. + /// + Readback = 1 << 6 +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderVertexAttribute.cs b/src/services/rendering/Inno.Rendering/Device/RenderVertexAttribute.cs new file mode 100644 index 000000000..c57f9f15f --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Device/RenderVertexAttribute.cs @@ -0,0 +1,71 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Describes one vertex attribute in stream order. +/// +public readonly record struct RenderVertexAttribute +{ + /// + /// Creates a vertex attribute declaration. + /// + /// + /// Shader input semantic. + /// + /// + /// Packed component representation. + /// + /// + /// Explicit byte offset in the stream, or -1 to place the attribute directly after the preceding attribute. + /// + public RenderVertexAttribute( + RenderVertexSemantic semantic, + RenderVertexFormat format, + int byteOffset = -1 + ) { + ArgumentOutOfRangeException.ThrowIfLessThan(byteOffset, -1); + this.semantic = semantic; + this.format = format; + this.byteOffset = byteOffset; + } + + /// + /// Gets the shader input semantic. + /// + public RenderVertexSemantic semantic { get; } + + /// + /// Gets the packed component representation. + /// + public RenderVertexFormat format { get; } + + /// + /// Gets the explicit byte offset in the resolved stream layout, or -1 before a layout resolves automatic placement. + /// + public int byteOffset { get; } + + /// + /// Gets the packed byte size. + /// + public int byteSize + => format switch + { + RenderVertexFormat.Float1 => 4, + RenderVertexFormat.Float2 => 8, + RenderVertexFormat.Float3 => 12, + RenderVertexFormat.Float4 => 16, + RenderVertexFormat.Half2 => 4, + RenderVertexFormat.Half4 => 8, + RenderVertexFormat.UInt8Normalized2 => 2, + RenderVertexFormat.UInt8Normalized4 => 4, + RenderVertexFormat.UInt8Integer2 => 2, + RenderVertexFormat.UInt8Integer4 => 4, + RenderVertexFormat.UInt10Normalized4 => 4, + RenderVertexFormat.Int16Normalized2 => 4, + RenderVertexFormat.Int16Normalized4 => 8, + RenderVertexFormat.Int16Integer2 => 4, + RenderVertexFormat.Int16Integer4 => 8, + _ => throw new ArgumentOutOfRangeException(nameof(format)) + }; +} diff --git a/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs b/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs index bcf212a87..8967a1418 100644 --- a/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs +++ b/src/services/rendering/Inno.Rendering/Device/RenderVertexLayout.cs @@ -4,6 +4,121 @@ namespace Inno.Rendering; +/// +/// Defines one interleaved vertex stream independently from a graphics backend. +/// +public sealed class RenderVertexLayout : IEquatable +{ + private readonly IReadOnlyList m_attributes; + + /// + /// Creates an interleaved vertex layout. + /// + /// + /// Unique attributes in ascending byte order. Attributes with offset -1 are packed after the preceding attribute. + /// + /// + /// Explicit positive stream stride, or zero to use the end of the final attribute. A larger stride preserves + /// trailing application-defined padding. + /// + public RenderVertexLayout( + IReadOnlyList attributes, + int stride = 0 + ) { + ArgumentNullException.ThrowIfNull(attributes); + ArgumentOutOfRangeException.ThrowIfNegative(stride); + if (attributes.Count == 0) + { + throw new ArgumentException("A vertex layout requires at least one attribute.", nameof(attributes)); + } + + if (attributes.Select(static value => value.semantic).Distinct().Count() != attributes.Count) + { + throw new ArgumentException("A vertex layout cannot repeat a semantic.", nameof(attributes)); + } + + var resolved = new RenderVertexAttribute[attributes.Count]; + int occupiedEnd = 0; + for (int index = 0; index < attributes.Count; index++) + { + RenderVertexAttribute attribute = attributes[index]; + int offset = attribute.byteOffset < 0 ? occupiedEnd : attribute.byteOffset; + if (offset < occupiedEnd) + { + throw new ArgumentException( + $"Vertex attribute '{attribute.semantic}' overlaps a preceding attribute.", + nameof(attributes) + ); + } + + resolved[index] = new RenderVertexAttribute(attribute.semantic, attribute.format, offset); + occupiedEnd = checked(offset + attribute.byteSize); + } + + if (stride != 0 && stride < occupiedEnd) + { + throw new ArgumentException("Vertex stride cannot end before the final attribute.", nameof(stride)); + } + + m_attributes = Array.AsReadOnly(resolved); + this.stride = stride == 0 ? occupiedEnd : stride; + } + + /// + /// Gets attributes in byte-stream order. + /// + public IReadOnlyList attributes => m_attributes; + + /// + /// Gets the interleaved vertex stride in bytes. + /// + public int stride { get; } + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The value to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public bool Equals(RenderVertexLayout? other) + => other is not null + && stride == other.stride + && m_attributes.SequenceEqual(other.m_attributes); + + /// + /// Determines whether this instance and the supplied value represent the same logical state. + /// + /// + /// The object to compare with this instance. + /// + /// + /// when both values represent the same logical state; otherwise, . + /// + public override bool Equals(object? obj) => Equals(obj as RenderVertexLayout); + + /// + /// Computes a hash code from the fields that participate in logical equality. + /// + /// + /// A hash code consistent with the implemented equality contract. + /// + public override int GetHashCode() + { + var hash = new HashCode(); + foreach (RenderVertexAttribute attribute in m_attributes) + { + hash.Add(attribute); + } + + hash.Add(stride); + + return hash.ToHashCode(); + } +} + /// /// Identifies one backend-neutral vertex attribute semantic. /// @@ -150,189 +265,6 @@ public enum RenderVertexFormat Int16Integer4 } -/// -/// Describes one vertex attribute in stream order. -/// -public readonly record struct RenderVertexAttribute -{ - /// - /// Creates a vertex attribute declaration. - /// - /// - /// Shader input semantic. - /// - /// - /// Packed component representation. - /// - /// - /// Explicit byte offset in the stream, or -1 to place the attribute directly after the preceding attribute. - /// - public RenderVertexAttribute( - RenderVertexSemantic semantic, - RenderVertexFormat format, - int byteOffset = -1 - ) { - ArgumentOutOfRangeException.ThrowIfLessThan(byteOffset, -1); - this.semantic = semantic; - this.format = format; - this.byteOffset = byteOffset; - } - - /// - /// Gets the shader input semantic. - /// - public RenderVertexSemantic semantic { get; } - - /// - /// Gets the packed component representation. - /// - public RenderVertexFormat format { get; } - - /// - /// Gets the explicit byte offset in the resolved stream layout, or -1 before a layout resolves automatic placement. - /// - public int byteOffset { get; } - - /// - /// Gets the packed byte size. - /// - public int byteSize - => format switch - { - RenderVertexFormat.Float1 => 4, - RenderVertexFormat.Float2 => 8, - RenderVertexFormat.Float3 => 12, - RenderVertexFormat.Float4 => 16, - RenderVertexFormat.Half2 => 4, - RenderVertexFormat.Half4 => 8, - RenderVertexFormat.UInt8Normalized2 => 2, - RenderVertexFormat.UInt8Normalized4 => 4, - RenderVertexFormat.UInt8Integer2 => 2, - RenderVertexFormat.UInt8Integer4 => 4, - RenderVertexFormat.UInt10Normalized4 => 4, - RenderVertexFormat.Int16Normalized2 => 4, - RenderVertexFormat.Int16Normalized4 => 8, - RenderVertexFormat.Int16Integer2 => 4, - RenderVertexFormat.Int16Integer4 => 8, - _ => throw new ArgumentOutOfRangeException(nameof(format)) - }; -} - -/// -/// Defines one interleaved vertex stream independently from a graphics backend. -/// -public sealed class RenderVertexLayout : IEquatable -{ - private readonly IReadOnlyList m_attributes; - - /// - /// Creates an interleaved vertex layout. - /// - /// - /// Unique attributes in ascending byte order. Attributes with offset -1 are packed after the preceding attribute. - /// - /// - /// Explicit positive stream stride, or zero to use the end of the final attribute. A larger stride preserves - /// trailing application-defined padding. - /// - public RenderVertexLayout( - IReadOnlyList attributes, - int stride = 0 - ) { - ArgumentNullException.ThrowIfNull(attributes); - ArgumentOutOfRangeException.ThrowIfNegative(stride); - if (attributes.Count == 0) - { - throw new ArgumentException("A vertex layout requires at least one attribute.", nameof(attributes)); - } - - if (attributes.Select(static value => value.semantic).Distinct().Count() != attributes.Count) - { - throw new ArgumentException("A vertex layout cannot repeat a semantic.", nameof(attributes)); - } - - var resolved = new RenderVertexAttribute[attributes.Count]; - int occupiedEnd = 0; - for (int index = 0; index < attributes.Count; index++) - { - RenderVertexAttribute attribute = attributes[index]; - int offset = attribute.byteOffset < 0 ? occupiedEnd : attribute.byteOffset; - if (offset < occupiedEnd) - { - throw new ArgumentException( - $"Vertex attribute '{attribute.semantic}' overlaps a preceding attribute.", - nameof(attributes) - ); - } - - resolved[index] = new RenderVertexAttribute(attribute.semantic, attribute.format, offset); - occupiedEnd = checked(offset + attribute.byteSize); - } - - if (stride != 0 && stride < occupiedEnd) - { - throw new ArgumentException("Vertex stride cannot end before the final attribute.", nameof(stride)); - } - - m_attributes = Array.AsReadOnly(resolved); - this.stride = stride == 0 ? occupiedEnd : stride; - } - - /// - /// Gets attributes in byte-stream order. - /// - public IReadOnlyList attributes => m_attributes; - - /// - /// Gets the interleaved vertex stride in bytes. - /// - public int stride { get; } - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// The value to compare with this instance. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - public bool Equals(RenderVertexLayout? other) - => other is not null - && stride == other.stride - && m_attributes.SequenceEqual(other.m_attributes); - - /// - /// Determines whether this instance and the supplied value represent the same logical state. - /// - /// - /// The object to compare with this instance. - /// - /// - /// when both values represent the same logical state; otherwise, . - /// - public override bool Equals(object? obj) => Equals(obj as RenderVertexLayout); - - /// - /// Computes a hash code from the fields that participate in logical equality. - /// - /// - /// A hash code consistent with the implemented equality contract. - /// - public override int GetHashCode() - { - var hash = new HashCode(); - foreach (RenderVertexAttribute attribute in m_attributes) - { - hash.Add(attribute); - } - - hash.Add(stride); - - return hash.ToHashCode(); - } -} - /// /// Selects the integer representation of an index buffer. /// diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderAttachment.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderAttachment.cs new file mode 100644 index 000000000..fb33b101c --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderAttachment.cs @@ -0,0 +1,71 @@ +namespace Inno.Rendering; + +/// +/// Describes one compiled raster attachment. +/// +public sealed class CompiledRenderAttachment +{ + internal CompiledRenderAttachment(RenderAttachment attachment) + { + this.texture = attachment.texture; + this.slot = attachment.slot; + this.isDepth = attachment.isDepth; + this.mipLevel = attachment.mipLevel; + this.arrayLayer = attachment.arrayLayer; + this.loadAction = attachment.loadAction; + this.storeAction = attachment.storeAction; + this.clearColor = attachment.clearColor; + this.clearDepth = attachment.clearDepth; + this.clearStencil = attachment.clearStencil; + } + + /// + /// Gets the attached graph texture. + /// + public RenderTextureHandle texture { get; } + + /// + /// Gets the zero-based color slot, or zero for a depth attachment. + /// + public int slot { get; } + + /// + /// Gets whether this is a depth or depth-stencil attachment. + /// + public bool isDepth { get; } + + /// + /// Gets the attached mip level. + /// + public int mipLevel { get; } + + /// + /// Gets the attached texture-array layer. + /// + public int arrayLayer { get; } + + /// + /// Gets initial content behavior. + /// + public RenderLoadAction loadAction { get; } + + /// + /// Gets final content behavior. + /// + public RenderStoreAction storeAction { get; } + + /// + /// Gets the linear color clear value. + /// + public RenderClearColor clearColor { get; } + + /// + /// Gets the depth clear value. + /// + public float clearDepth { get; } + + /// + /// Gets the stencil clear value. + /// + public byte clearStencil { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderBuffer.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderBuffer.cs new file mode 100644 index 000000000..6988e9b8f --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderBuffer.cs @@ -0,0 +1,53 @@ +namespace Inno.Rendering; + +/// +/// Describes one buffer allocation selected by render-graph compilation. +/// +public sealed class CompiledRenderBuffer +{ + internal CompiledRenderBuffer( + RenderBufferHandle handle, + string name, + RenderBufferDescriptor descriptor, + bool imported, + PersistentBufferHandle persistentHandle, + int physicalSlot + ) { + this.handle = handle; + this.name = name; + this.descriptor = descriptor; + this.imported = imported; + this.persistentHandle = persistentHandle; + this.physicalSlot = physicalSlot; + } + + /// + /// Gets the frame-scoped logical handle. + /// + public RenderBufferHandle handle { get; } + + /// + /// Gets the debug and diagnostic name. + /// + public string name { get; } + + /// + /// Gets buffer requirements. + /// + public RenderBufferDescriptor descriptor { get; } + + /// + /// Gets whether the resource was imported from persistent device state. + /// + public bool imported { get; } + + /// + /// Gets the persistent device buffer for imported resources. + /// + public PersistentBufferHandle persistentHandle { get; } + + /// + /// Gets the aliasing allocation slot, or negative one for imported resources. + /// + public int physicalSlot { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs index b1ec91c3d..0f9888c19 100644 --- a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderGraph.cs @@ -7,357 +7,6 @@ namespace Inno.Rendering; -/// -/// Stores backend-ready column-major transform matrices for one programmable view. -/// -public sealed class RenderViewTransform -{ - private readonly float[] m_viewMatrix; - private readonly float[] m_projectionMatrix; - - /// - /// Creates a raster view transform. - /// - /// - /// Exactly sixteen column-major world-to-view values. - /// - /// - /// Exactly sixteen column-major projection values. - /// - public RenderViewTransform( - ReadOnlySpan viewMatrix, - ReadOnlySpan projectionMatrix - ) { - if (viewMatrix.Length != 16) - { - throw new ArgumentException("A view matrix requires exactly sixteen values.", nameof(viewMatrix)); - } - - if (projectionMatrix.Length != 16) - { - throw new ArgumentException( - "A projection matrix requires exactly sixteen values.", - nameof(projectionMatrix) - ); - } - - m_viewMatrix = viewMatrix.ToArray(); - m_projectionMatrix = projectionMatrix.ToArray(); - } - - /// - /// Gets the immutable column-major view matrix. - /// - public ReadOnlyMemory viewMatrix => m_viewMatrix; - - /// - /// Gets the immutable column-major projection matrix. - /// - public ReadOnlyMemory projectionMatrix => m_projectionMatrix; -} - -/// -/// Describes one texture allocation selected by render-graph compilation. -/// -public sealed class CompiledRenderTexture -{ - internal CompiledRenderTexture( - RenderTextureHandle handle, - string name, - RenderTextureDescriptor descriptor, - bool imported, - PersistentTextureHandle persistentHandle, - int physicalSlot - ) { - this.handle = handle; - this.name = name; - this.descriptor = descriptor; - this.imported = imported; - this.persistentHandle = persistentHandle; - this.physicalSlot = physicalSlot; - } - - /// - /// Gets the frame-scoped logical handle. - /// - public RenderTextureHandle handle { get; } - - /// - /// Gets the debug and diagnostic name. - /// - public string name { get; } - - /// - /// Gets texture requirements. - /// - public RenderTextureDescriptor descriptor { get; } - - /// - /// Gets whether the resource was imported from persistent device state. - /// - public bool imported { get; } - - /// - /// Gets the persistent device texture for imported resources. - /// - public PersistentTextureHandle persistentHandle { get; } - - /// - /// Gets the aliasing allocation slot, or negative one for imported resources. - /// - public int physicalSlot { get; } -} - -/// -/// Describes one buffer allocation selected by render-graph compilation. -/// -public sealed class CompiledRenderBuffer -{ - internal CompiledRenderBuffer( - RenderBufferHandle handle, - string name, - RenderBufferDescriptor descriptor, - bool imported, - PersistentBufferHandle persistentHandle, - int physicalSlot - ) { - this.handle = handle; - this.name = name; - this.descriptor = descriptor; - this.imported = imported; - this.persistentHandle = persistentHandle; - this.physicalSlot = physicalSlot; - } - - /// - /// Gets the frame-scoped logical handle. - /// - public RenderBufferHandle handle { get; } - - /// - /// Gets the debug and diagnostic name. - /// - public string name { get; } - - /// - /// Gets buffer requirements. - /// - public RenderBufferDescriptor descriptor { get; } - - /// - /// Gets whether the resource was imported from persistent device state. - /// - public bool imported { get; } - - /// - /// Gets the persistent device buffer for imported resources. - /// - public PersistentBufferHandle persistentHandle { get; } - - /// - /// Gets the aliasing allocation slot, or negative one for imported resources. - /// - public int physicalSlot { get; } -} - -/// -/// Describes one compiled raster attachment. -/// -public sealed class CompiledRenderAttachment -{ - internal CompiledRenderAttachment(RenderAttachment attachment) - { - this.texture = attachment.texture; - this.slot = attachment.slot; - this.isDepth = attachment.isDepth; - this.mipLevel = attachment.mipLevel; - this.arrayLayer = attachment.arrayLayer; - this.loadAction = attachment.loadAction; - this.storeAction = attachment.storeAction; - this.clearColor = attachment.clearColor; - this.clearDepth = attachment.clearDepth; - this.clearStencil = attachment.clearStencil; - } - - /// - /// Gets the attached graph texture. - /// - public RenderTextureHandle texture { get; } - - /// - /// Gets the zero-based color slot, or zero for a depth attachment. - /// - public int slot { get; } - - /// - /// Gets whether this is a depth or depth-stencil attachment. - /// - public bool isDepth { get; } - - /// - /// Gets the attached mip level. - /// - public int mipLevel { get; } - - /// - /// Gets the attached texture-array layer. - /// - public int arrayLayer { get; } - - /// - /// Gets initial content behavior. - /// - public RenderLoadAction loadAction { get; } - - /// - /// Gets final content behavior. - /// - public RenderStoreAction storeAction { get; } - - /// - /// Gets the linear color clear value. - /// - public RenderClearColor clearColor { get; } - - /// - /// Gets the depth clear value. - /// - public float clearDepth { get; } - - /// - /// Gets the stencil clear value. - /// - public byte clearStencil { get; } -} - -/// -/// Provides immutable backend-facing metadata for one scheduled pass. -/// -public sealed class CompiledRenderPass -{ - private readonly IReadOnlyList m_attachments; - private readonly Action m_execute; - - internal CompiledRenderPass( - string name, - RenderPhaseID phase, - RenderPassKind kind, - int viewIndex, - IReadOnlyList attachments, - RenderSurfaceHandle surface, - bool clearsPresentationTarget, - RenderClearColor presentationClearColor, - RenderViewTransform? viewTransform, - RenderPassRecordingMode recordingMode, - Action execute - ) { - this.name = name; - this.phase = phase; - this.kind = kind; - this.viewIndex = viewIndex; - m_attachments = Array.AsReadOnly(attachments.ToArray()); - this.surface = surface; - this.clearsPresentationTarget = clearsPresentationTarget; - this.presentationClearColor = presentationClearColor; - this.viewTransform = viewTransform; - this.recordingMode = recordingMode; - m_execute = execute; - } - - /// - /// Gets the unique diagnostic name. - /// - public string name { get; } - - /// - /// Gets the open render phase identifier. - /// - public RenderPhaseID phase { get; } - - /// - /// Gets the pass command domain. - /// - public RenderPassKind kind { get; } - - /// - /// Gets the backend-neutral logical view order. - /// - public int viewIndex { get; } - - /// - /// Gets raster attachments in declaration order. - /// - public IReadOnlyList attachments => m_attachments; - - /// - /// Gets the detached presentation surface, or an invalid handle for the primary backbuffer. - /// - public RenderSurfaceHandle surface { get; } - - /// - /// Gets whether this pass clears its presentation target before drawing. - /// - public bool clearsPresentationTarget { get; } - - /// - /// Gets the linear clear color for a presentation target. - /// - public RenderClearColor presentationClearColor { get; } - - /// - /// Gets backend-ready view transforms, or for a matrix-free pass. - /// - public RenderViewTransform? viewTransform { get; } - - /// - /// Gets whether callback recording is serial or worker-thread eligible. - /// - public RenderPassRecordingMode recordingMode { get; } - - internal void Execute(RenderPassContext context) => m_execute(context); -} - -/// -/// Bridges compiled graph execution to a concrete graphics backend. -/// -public interface IRenderGraphBackend -{ - /// - /// Begins execution and prepares transient allocations. - /// - /// - /// Compiled graph to execute. - /// - void BeginGraph(CompiledRenderGraph graph); - - /// - /// Begins one scheduled pass and acquires its command encoder. - /// - /// - /// Scheduled pass metadata. - /// - /// - /// A command encoder scoped to this pass. - /// - RenderCommandEncoder BeginPass(CompiledRenderPass pass); - - /// - /// Ends one scheduled pass and releases its encoder. - /// - /// - /// Scheduled pass metadata. - /// - void EndPass(CompiledRenderPass pass); - - /// - /// Ends graph execution without presenting an additional frame. - /// - /// - /// Compiled graph that finished or failed. - /// - void EndGraph(CompiledRenderGraph graph); -} - /// /// Contains validated, culled and topologically scheduled frame work. /// @@ -558,42 +207,3 @@ private Dictionary RecordParal } } } - -/// -/// Contains render-graph compilation diagnostics and an optional executable graph. -/// -public sealed class RenderGraphCompileResult -{ - private readonly IReadOnlyList m_diagnostics; - - internal RenderGraphCompileResult( - CompiledRenderGraph? graph, - IReadOnlyList diagnostics, - int culledPassCount = 0 - ) { - ArgumentOutOfRangeException.ThrowIfNegative(culledPassCount); - this.graph = graph; - m_diagnostics = Array.AsReadOnly(diagnostics.ToArray()); - this.culledPassCount = culledPassCount; - } - - /// - /// Gets the executable graph, or when compilation failed. - /// - public CompiledRenderGraph? graph { get; } - - /// - /// Gets deterministic compilation diagnostics. - /// - public IReadOnlyList diagnostics => m_diagnostics; - - /// - /// Gets passes removed because they did not contribute to an output or side effect. - /// - public int culledPassCount { get; } - - /// - /// Gets whether an executable graph was produced. - /// - public bool succeeded => graph is not null; -} diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderPass.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderPass.cs new file mode 100644 index 000000000..dbcdf2c07 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderPass.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Rendering; + +/// +/// Provides immutable backend-facing metadata for one scheduled pass. +/// +public sealed class CompiledRenderPass +{ + private readonly IReadOnlyList m_attachments; + private readonly Action m_execute; + + internal CompiledRenderPass( + string name, + RenderPhaseID phase, + RenderPassKind kind, + int viewIndex, + IReadOnlyList attachments, + RenderSurfaceHandle surface, + bool clearsPresentationTarget, + RenderClearColor presentationClearColor, + RenderViewTransform? viewTransform, + RenderPassRecordingMode recordingMode, + Action execute + ) { + this.name = name; + this.phase = phase; + this.kind = kind; + this.viewIndex = viewIndex; + m_attachments = Array.AsReadOnly(attachments.ToArray()); + this.surface = surface; + this.clearsPresentationTarget = clearsPresentationTarget; + this.presentationClearColor = presentationClearColor; + this.viewTransform = viewTransform; + this.recordingMode = recordingMode; + m_execute = execute; + } + + /// + /// Gets the unique diagnostic name. + /// + public string name { get; } + + /// + /// Gets the open render phase identifier. + /// + public RenderPhaseID phase { get; } + + /// + /// Gets the pass command domain. + /// + public RenderPassKind kind { get; } + + /// + /// Gets the backend-neutral logical view order. + /// + public int viewIndex { get; } + + /// + /// Gets raster attachments in declaration order. + /// + public IReadOnlyList attachments => m_attachments; + + /// + /// Gets the detached presentation surface, or an invalid handle for the primary backbuffer. + /// + public RenderSurfaceHandle surface { get; } + + /// + /// Gets whether this pass clears its presentation target before drawing. + /// + public bool clearsPresentationTarget { get; } + + /// + /// Gets the linear clear color for a presentation target. + /// + public RenderClearColor presentationClearColor { get; } + + /// + /// Gets backend-ready view transforms, or for a matrix-free pass. + /// + public RenderViewTransform? viewTransform { get; } + + /// + /// Gets whether callback recording is serial or worker-thread eligible. + /// + public RenderPassRecordingMode recordingMode { get; } + + internal void Execute(RenderPassContext context) => m_execute(context); +} diff --git a/src/services/rendering/Inno.Rendering/Graph/CompiledRenderTexture.cs b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderTexture.cs new file mode 100644 index 000000000..3aaf50bce --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/CompiledRenderTexture.cs @@ -0,0 +1,53 @@ +namespace Inno.Rendering; + +/// +/// Describes one texture allocation selected by render-graph compilation. +/// +public sealed class CompiledRenderTexture +{ + internal CompiledRenderTexture( + RenderTextureHandle handle, + string name, + RenderTextureDescriptor descriptor, + bool imported, + PersistentTextureHandle persistentHandle, + int physicalSlot + ) { + this.handle = handle; + this.name = name; + this.descriptor = descriptor; + this.imported = imported; + this.persistentHandle = persistentHandle; + this.physicalSlot = physicalSlot; + } + + /// + /// Gets the frame-scoped logical handle. + /// + public RenderTextureHandle handle { get; } + + /// + /// Gets the debug and diagnostic name. + /// + public string name { get; } + + /// + /// Gets texture requirements. + /// + public RenderTextureDescriptor descriptor { get; } + + /// + /// Gets whether the resource was imported from persistent device state. + /// + public bool imported { get; } + + /// + /// Gets the persistent device texture for imported resources. + /// + public PersistentTextureHandle persistentHandle { get; } + + /// + /// Gets the aliasing allocation slot, or negative one for imported resources. + /// + public int physicalSlot { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Graph/IRenderGraphBackend.cs b/src/services/rendering/Inno.Rendering/Graph/IRenderGraphBackend.cs new file mode 100644 index 000000000..58caf0297 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/IRenderGraphBackend.cs @@ -0,0 +1,42 @@ +namespace Inno.Rendering; + +/// +/// Bridges compiled graph execution to a concrete graphics backend. +/// +public interface IRenderGraphBackend +{ + /// + /// Begins execution and prepares transient allocations. + /// + /// + /// Compiled graph to execute. + /// + void BeginGraph(CompiledRenderGraph graph); + + /// + /// Begins one scheduled pass and acquires its command encoder. + /// + /// + /// Scheduled pass metadata. + /// + /// + /// A command encoder scoped to this pass. + /// + RenderCommandEncoder BeginPass(CompiledRenderPass pass); + + /// + /// Ends one scheduled pass and releases its encoder. + /// + /// + /// Scheduled pass metadata. + /// + void EndPass(CompiledRenderPass pass); + + /// + /// Ends graph execution without presenting an additional frame. + /// + /// + /// Compiled graph that finished or failed. + /// + void EndGraph(CompiledRenderGraph graph); +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderAttachment.cs b/src/services/rendering/Inno.Rendering/Graph/RenderAttachment.cs new file mode 100644 index 000000000..77fb53aba --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderAttachment.cs @@ -0,0 +1,14 @@ +namespace Inno.Rendering; + +internal sealed record RenderAttachment( + RenderTextureHandle texture, + int slot, + bool isDepth, + int mipLevel, + int arrayLayer, + RenderLoadAction loadAction, + RenderStoreAction storeAction, + RenderClearColor clearColor, + float clearDepth, + byte clearStencil +); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderBufferRecord.cs b/src/services/rendering/Inno.Rendering/Graph/RenderBufferRecord.cs new file mode 100644 index 000000000..db4abc2a6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderBufferRecord.cs @@ -0,0 +1,9 @@ +namespace Inno.Rendering; + +internal sealed record RenderBufferRecord( + string name, + RenderBufferDescriptor descriptor, + bool imported, + PersistentBufferHandle persistentHandle, + ulong allocationID +); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderClearColor.cs b/src/services/rendering/Inno.Rendering/Graph/RenderClearColor.cs new file mode 100644 index 000000000..fa3696a44 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderClearColor.cs @@ -0,0 +1,54 @@ +namespace Inno.Rendering; + +/// +/// Stores a linear clear color without depending on an engine math assembly. +/// +public readonly record struct RenderClearColor +{ + /// + /// Creates a linear clear color. + /// + /// + /// Red channel. + /// + /// + /// Green channel. + /// + /// + /// Blue channel. + /// + /// + /// Alpha channel. + /// + public RenderClearColor( + float r, + float g, + float b, + float a = 1f + ) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + } + + /// + /// Gets the red channel. + /// + public float r { get; } + + /// + /// Gets the green channel. + /// + public float g { get; } + + /// + /// Gets the blue channel. + /// + public float b { get; } + + /// + /// Gets the alpha channel. + /// + public float a { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompileResult.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompileResult.cs new file mode 100644 index 000000000..d82c8a889 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompileResult.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Inno.Rendering; + +/// +/// Contains render-graph compilation diagnostics and an optional executable graph. +/// +public sealed class RenderGraphCompileResult +{ + private readonly IReadOnlyList m_diagnostics; + + internal RenderGraphCompileResult( + CompiledRenderGraph? graph, + IReadOnlyList diagnostics, + int culledPassCount = 0 + ) { + ArgumentOutOfRangeException.ThrowIfNegative(culledPassCount); + this.graph = graph; + m_diagnostics = Array.AsReadOnly(diagnostics.ToArray()); + this.culledPassCount = culledPassCount; + } + + /// + /// Gets the executable graph, or when compilation failed. + /// + public CompiledRenderGraph? graph { get; } + + /// + /// Gets deterministic compilation diagnostics. + /// + public IReadOnlyList diagnostics => m_diagnostics; + + /// + /// Gets passes removed because they did not contribute to an output or side effect. + /// + public int culledPassCount { get; } + + /// + /// Gets whether an executable graph was produced. + /// + public bool succeeded => graph is not null; +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.ResourceAllocation.cs similarity index 99% rename from src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs rename to src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.ResourceAllocation.cs index 6dbfad6a5..6dacc9226 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphResourceAllocation.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphCompiler.ResourceAllocation.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Inno.Core.Diagnostics; namespace Inno.Rendering; diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphDiagnostic.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphDiagnostic.cs new file mode 100644 index 000000000..b675e63c6 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphDiagnostic.cs @@ -0,0 +1,69 @@ +using System; +using Inno.Core.Diagnostics; + +namespace Inno.Rendering; + +/// +/// Reports one structured render-graph compilation problem. +/// +public sealed class RenderGraphDiagnostic +{ + /// + /// Creates a render-graph diagnostic. + /// + /// + /// Stable machine-readable code. + /// + /// + /// Actionable diagnostic text. + /// + /// + /// Diagnostic impact. + /// + /// + /// Optional related pass name. + /// + /// + /// Optional related resource name. + /// + public RenderGraphDiagnostic( + string code, + string message, + DiagnosticSeverity severity, + string? passName = null, + string? resourceName = null + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(code); + ArgumentException.ThrowIfNullOrWhiteSpace(message); + this.code = code; + this.message = message; + this.severity = severity; + this.passName = passName; + this.resourceName = resourceName; + } + + /// + /// Gets the stable machine-readable code. + /// + public string code { get; } + + /// + /// Gets actionable diagnostic text. + /// + public string message { get; } + + /// + /// Gets diagnostic impact. + /// + public DiagnosticSeverity severity { get; } + + /// + /// Gets the related pass name, if any. + /// + public string? passName { get; } + + /// + /// Gets the related resource name, if any. + /// + public string? resourceName { get; } +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs deleted file mode 100644 index 2d97e6e17..000000000 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphTypes.cs +++ /dev/null @@ -1,356 +0,0 @@ -using System; -using System.Collections.Generic; -using Inno.Core.Diagnostics; - -namespace Inno.Rendering; - -/// -/// Identifies an open render phase protocol value. -/// -public readonly record struct RenderPhaseID -{ - /// - /// Creates an open render phase identifier. - /// - /// - /// Globally stable phase value. - /// - public RenderPhaseID(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - this.value = value; - } - - /// - /// Gets the globally stable phase value. - /// - public string value { get; } - - /// - /// Formats this value as a human-readable representation. - /// - /// - /// The human-readable representation of this value. - /// - public override string ToString() => value; -} - -/// -/// Distinguishes pass command domains for validation and backend execution. -/// -public enum RenderPassKind -{ - /// - /// Raster draw commands with optional attachments. - /// - Raster, - /// - /// Compute dispatch commands. - /// - Compute, - /// - /// Resource copy commands. - /// - Copy -} - -/// -/// Controls where a frame-local pass callback records backend-neutral commands. -/// -public enum RenderPassRecordingMode -{ - /// - /// Records directly on the graph execution thread. - /// - Serial, - /// - /// Records into an isolated command list on a worker thread, then replays in graph order. - /// - Parallel -} - -/// -/// Controls how existing attachment contents enter a raster pass. -/// -public enum RenderLoadAction -{ - /// - /// Preserves prior attachment contents. - /// - Load, - /// - /// Clears the attachment before rendering. - /// - Clear, - /// - /// Does not require prior attachment contents. - /// - Discard -} - -/// -/// Controls whether attachment contents remain valid after a raster pass. -/// -public enum RenderStoreAction -{ - /// - /// Preserves rendered contents. - /// - Store, - /// - /// Allows the backend to discard rendered contents. - /// - Discard -} - -/// -/// Stores a linear clear color without depending on an engine math assembly. -/// -public readonly record struct RenderClearColor -{ - /// - /// Creates a linear clear color. - /// - /// - /// Red channel. - /// - /// - /// Green channel. - /// - /// - /// Blue channel. - /// - /// - /// Alpha channel. - /// - public RenderClearColor( - float r, - float g, - float b, - float a = 1f - ) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - } - - /// - /// Gets the red channel. - /// - public float r { get; } - - /// - /// Gets the green channel. - /// - public float g { get; } - - /// - /// Gets the blue channel. - /// - public float b { get; } - - /// - /// Gets the alpha channel. - /// - public float a { get; } -} - -/// -/// Reports one structured render-graph compilation problem. -/// -public sealed class RenderGraphDiagnostic -{ - /// - /// Creates a render-graph diagnostic. - /// - /// - /// Stable machine-readable code. - /// - /// - /// Actionable diagnostic text. - /// - /// - /// Diagnostic impact. - /// - /// - /// Optional related pass name. - /// - /// - /// Optional related resource name. - /// - public RenderGraphDiagnostic( - string code, - string message, - DiagnosticSeverity severity, - string? passName = null, - string? resourceName = null - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(code); - ArgumentException.ThrowIfNullOrWhiteSpace(message); - this.code = code; - this.message = message; - this.severity = severity; - this.passName = passName; - this.resourceName = resourceName; - } - - /// - /// Gets the stable machine-readable code. - /// - public string code { get; } - - /// - /// Gets actionable diagnostic text. - /// - public string message { get; } - - /// - /// Gets diagnostic impact. - /// - public DiagnosticSeverity severity { get; } - - /// - /// Gets the related pass name, if any. - /// - public string? passName { get; } - - /// - /// Gets the related resource name, if any. - /// - public string? resourceName { get; } -} - -internal enum RenderResourceAccess -{ - Read, - Write, - ReadWrite -} - -internal enum RenderResourceUseKind -{ - GenericRead, - StorageRead, - StorageWrite, - StorageReadWrite, - CopySource, - CopyDestination, - ColorAttachment, - DepthStencilAttachment -} - -internal readonly record struct RenderResourceKey( - bool isTexture, - int index -); - -internal sealed record RenderResourceUse( - RenderResourceKey key, - RenderResourceAccess access, - RenderResourceUseKind kind -); - -internal sealed record RenderAttachment( - RenderTextureHandle texture, - int slot, - bool isDepth, - int mipLevel, - int arrayLayer, - RenderLoadAction loadAction, - RenderStoreAction storeAction, - RenderClearColor clearColor, - float clearDepth, - byte clearStencil -); - -internal sealed class RenderPassRecord -{ - /// - /// Gets the human-readable name used for presentation and diagnostics. - /// - public required string name { get; init; } - - /// - /// Gets the render phase that owns this pass declaration. - /// - public required RenderPhaseID phase { get; init; } - - /// - /// Gets the operation kind that determines how this value is interpreted. - /// - public required RenderPassKind kind { get; init; } - - /// - /// Gets the callback that records commands for this render pass. - /// - public required Action execute { get; init; } - - /// - /// Gets the render phases that must execute after this pass. - /// - public List before { get; } = []; - - /// - /// Gets the render phases that must execute before this pass. - /// - public List after { get; } = []; - - /// - /// Gets the complete resource access declarations used for graph dependency analysis. - /// - public List resources { get; } = []; - - /// - /// Gets the color and depth attachments written by this render pass. - /// - public List attachments { get; } = []; - - /// - /// Gets the presentation surface targeted by this render pass. - /// - public RenderSurfaceHandle surface { get; set; } - - /// - /// Gets the color used when the presentation surface is cleared. - /// - public RenderClearColor presentationClearColor { get; set; } - - /// - /// Gets the optional view and projection transform applied by this pass. - /// - public RenderViewTransform? viewTransform { get; set; } - - /// - /// Gets whether the caller-visible condition represented by this property is satisfied. - /// - public bool clearsPresentationTarget { get; set; } - - /// - /// Gets whether this value has side effect. - /// - public bool hasSideEffect { get; set; } - - /// - /// Gets whether the pass records graphics, compute, or transfer commands. - /// - public RenderPassRecordingMode recordingMode { get; set; } - - internal required int index { get; init; } -} - -internal sealed record RenderTextureRecord( - string name, - RenderTextureDescriptor descriptor, - bool imported, - PersistentTextureHandle persistentHandle, - ulong allocationID -); - -internal sealed record RenderBufferRecord( - string name, - RenderBufferDescriptor descriptor, - bool imported, - PersistentBufferHandle persistentHandle, - ulong allocationID -); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphDependencyAnalysis.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.DependencyAnalysis.cs similarity index 99% rename from src/services/rendering/Inno.Rendering/Graph/RenderGraphDependencyAnalysis.cs rename to src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.DependencyAnalysis.cs index 66894a8a7..4019c6e02 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphDependencyAnalysis.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.DependencyAnalysis.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Inno.Core.Diagnostics; diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderGraphScheduling.cs b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.Scheduling.cs similarity index 98% rename from src/services/rendering/Inno.Rendering/Graph/RenderGraphScheduling.cs rename to src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.Scheduling.cs index 378170028..9d64bea70 100644 --- a/src/services/rendering/Inno.Rendering/Graph/RenderGraphScheduling.cs +++ b/src/services/rendering/Inno.Rendering/Graph/RenderGraphValidator.Scheduling.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using Inno.Core.Diagnostics; namespace Inno.Rendering; diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderLoadAction.cs b/src/services/rendering/Inno.Rendering/Graph/RenderLoadAction.cs new file mode 100644 index 000000000..e3275d185 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderLoadAction.cs @@ -0,0 +1,20 @@ +namespace Inno.Rendering; + +/// +/// Controls how existing attachment contents enter a raster pass. +/// +public enum RenderLoadAction +{ + /// + /// Preserves prior attachment contents. + /// + Load, + /// + /// Clears the attachment before rendering. + /// + Clear, + /// + /// Does not require prior attachment contents. + /// + Discard +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderPassKind.cs b/src/services/rendering/Inno.Rendering/Graph/RenderPassKind.cs new file mode 100644 index 000000000..7d842312b --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderPassKind.cs @@ -0,0 +1,20 @@ +namespace Inno.Rendering; + +/// +/// Distinguishes pass command domains for validation and backend execution. +/// +public enum RenderPassKind +{ + /// + /// Raster draw commands with optional attachments. + /// + Raster, + /// + /// Compute dispatch commands. + /// + Compute, + /// + /// Resource copy commands. + /// + Copy +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderPassRecord.cs b/src/services/rendering/Inno.Rendering/Graph/RenderPassRecord.cs new file mode 100644 index 000000000..5b20057c4 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderPassRecord.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Rendering; + +internal sealed class RenderPassRecord +{ + /// + /// Gets the human-readable name used for presentation and diagnostics. + /// + public required string name { get; init; } + + /// + /// Gets the render phase that owns this pass declaration. + /// + public required RenderPhaseID phase { get; init; } + + /// + /// Gets the operation kind that determines how this value is interpreted. + /// + public required RenderPassKind kind { get; init; } + + /// + /// Gets the callback that records commands for this render pass. + /// + public required Action execute { get; init; } + + /// + /// Gets the render phases that must execute after this pass. + /// + public List before { get; } = []; + + /// + /// Gets the render phases that must execute before this pass. + /// + public List after { get; } = []; + + /// + /// Gets the complete resource access declarations used for graph dependency analysis. + /// + public List resources { get; } = []; + + /// + /// Gets the color and depth attachments written by this render pass. + /// + public List attachments { get; } = []; + + /// + /// Gets the presentation surface targeted by this render pass. + /// + public RenderSurfaceHandle surface { get; set; } + + /// + /// Gets the color used when the presentation surface is cleared. + /// + public RenderClearColor presentationClearColor { get; set; } + + /// + /// Gets the optional view and projection transform applied by this pass. + /// + public RenderViewTransform? viewTransform { get; set; } + + /// + /// Gets whether the caller-visible condition represented by this property is satisfied. + /// + public bool clearsPresentationTarget { get; set; } + + /// + /// Gets whether this value has side effect. + /// + public bool hasSideEffect { get; set; } + + /// + /// Gets whether the pass records graphics, compute, or transfer commands. + /// + public RenderPassRecordingMode recordingMode { get; set; } + + internal required int index { get; init; } +} + +/// +/// Controls where a frame-local pass callback records backend-neutral commands. +/// +public enum RenderPassRecordingMode +{ + /// + /// Records directly on the graph execution thread. + /// + Serial, + /// + /// Records into an isolated command list on a worker thread, then replays in graph order. + /// + Parallel +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderPhaseID.cs b/src/services/rendering/Inno.Rendering/Graph/RenderPhaseID.cs new file mode 100644 index 000000000..333376290 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderPhaseID.cs @@ -0,0 +1,34 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Identifies an open render phase protocol value. +/// +public readonly record struct RenderPhaseID +{ + /// + /// Creates an open render phase identifier. + /// + /// + /// Globally stable phase value. + /// + public RenderPhaseID(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + this.value = value; + } + + /// + /// Gets the globally stable phase value. + /// + public string value { get; } + + /// + /// Formats this value as a human-readable representation. + /// + /// + /// The human-readable representation of this value. + /// + public override string ToString() => value; +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderResourceAccess.cs b/src/services/rendering/Inno.Rendering/Graph/RenderResourceAccess.cs new file mode 100644 index 000000000..d5c2dc5ff --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderResourceAccess.cs @@ -0,0 +1,8 @@ +namespace Inno.Rendering; + +internal enum RenderResourceAccess +{ + Read, + Write, + ReadWrite +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderResourceKey.cs b/src/services/rendering/Inno.Rendering/Graph/RenderResourceKey.cs new file mode 100644 index 000000000..f8233ff51 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderResourceKey.cs @@ -0,0 +1,6 @@ +namespace Inno.Rendering; + +internal readonly record struct RenderResourceKey( + bool isTexture, + int index +); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderResourceUse.cs b/src/services/rendering/Inno.Rendering/Graph/RenderResourceUse.cs new file mode 100644 index 000000000..61e59607f --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderResourceUse.cs @@ -0,0 +1,7 @@ +namespace Inno.Rendering; + +internal sealed record RenderResourceUse( + RenderResourceKey key, + RenderResourceAccess access, + RenderResourceUseKind kind +); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderResourceUseKind.cs b/src/services/rendering/Inno.Rendering/Graph/RenderResourceUseKind.cs new file mode 100644 index 000000000..4e0b99eb3 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderResourceUseKind.cs @@ -0,0 +1,13 @@ +namespace Inno.Rendering; + +internal enum RenderResourceUseKind +{ + GenericRead, + StorageRead, + StorageWrite, + StorageReadWrite, + CopySource, + CopyDestination, + ColorAttachment, + DepthStencilAttachment +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderStoreAction.cs b/src/services/rendering/Inno.Rendering/Graph/RenderStoreAction.cs new file mode 100644 index 000000000..74ed44de2 --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderStoreAction.cs @@ -0,0 +1,16 @@ +namespace Inno.Rendering; + +/// +/// Controls whether attachment contents remain valid after a raster pass. +/// +public enum RenderStoreAction +{ + /// + /// Preserves rendered contents. + /// + Store, + /// + /// Allows the backend to discard rendered contents. + /// + Discard +} diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderTextureRecord.cs b/src/services/rendering/Inno.Rendering/Graph/RenderTextureRecord.cs new file mode 100644 index 000000000..c4dbe479d --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderTextureRecord.cs @@ -0,0 +1,9 @@ +namespace Inno.Rendering; + +internal sealed record RenderTextureRecord( + string name, + RenderTextureDescriptor descriptor, + bool imported, + PersistentTextureHandle persistentHandle, + ulong allocationID +); diff --git a/src/services/rendering/Inno.Rendering/Graph/RenderViewTransform.cs b/src/services/rendering/Inno.Rendering/Graph/RenderViewTransform.cs new file mode 100644 index 000000000..0cadf0e2c --- /dev/null +++ b/src/services/rendering/Inno.Rendering/Graph/RenderViewTransform.cs @@ -0,0 +1,52 @@ +using System; + +namespace Inno.Rendering; + +/// +/// Stores backend-ready column-major transform matrices for one programmable view. +/// +public sealed class RenderViewTransform +{ + private readonly float[] m_viewMatrix; + private readonly float[] m_projectionMatrix; + + /// + /// Creates a raster view transform. + /// + /// + /// Exactly sixteen column-major world-to-view values. + /// + /// + /// Exactly sixteen column-major projection values. + /// + public RenderViewTransform( + ReadOnlySpan viewMatrix, + ReadOnlySpan projectionMatrix + ) { + if (viewMatrix.Length != 16) + { + throw new ArgumentException("A view matrix requires exactly sixteen values.", nameof(viewMatrix)); + } + + if (projectionMatrix.Length != 16) + { + throw new ArgumentException( + "A projection matrix requires exactly sixteen values.", + nameof(projectionMatrix) + ); + } + + m_viewMatrix = viewMatrix.ToArray(); + m_projectionMatrix = projectionMatrix.ToArray(); + } + + /// + /// Gets the immutable column-major view matrix. + /// + public ReadOnlyMemory viewMatrix => m_viewMatrix; + + /// + /// Gets the immutable column-major projection matrix. + /// + public ReadOnlyMemory projectionMatrix => m_projectionMatrix; +} diff --git a/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs b/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs index b922ec6e1..44cddbf07 100644 --- a/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs +++ b/src/services/rendering/Inno.Rendering/Targets/RenderTarget.cs @@ -2,21 +2,6 @@ namespace Inno.Rendering; -/// -/// Identifies whether a request renders to the main swapchain or an offscreen target. -/// -public enum RenderTargetKind -{ - /// - /// Main application window swapchain. - /// - Backbuffer, - /// - /// Persistent offscreen render texture. - /// - Texture -} - /// /// Selects one render destination without exposing a swapchain or framebuffer handle. /// @@ -60,3 +45,18 @@ public static RenderTarget FromTexture(RenderTexture texture) return new RenderTarget(RenderTargetKind.Texture, texture); } } + +/// +/// Identifies whether a request renders to the main swapchain or an offscreen target. +/// +public enum RenderTargetKind +{ + /// + /// Main application window swapchain. + /// + Backbuffer, + /// + /// Persistent offscreen render texture. + /// + Texture +} diff --git a/src/services/storage/Inno.Storage/Storage.cs b/src/services/storage/Inno.Storage/Storage.cs index 42d9bc056..af231e0a1 100644 --- a/src/services/storage/Inno.Storage/Storage.cs +++ b/src/services/storage/Inno.Storage/Storage.cs @@ -2,41 +2,9 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Inno.Core.Execution; namespace Inno.Storage; -/// -/// Binds application storage to the current asynchronous execution context. -/// -public static class StorageExecutionContext -{ - private static readonly ExecutionSlot CURRENT_SCOPE = new("storage"); - - /// - /// Gets the storage service bound to the current execution context. - /// - /// - /// Thrown when no storage scope is active. - /// - public static IApplicationStorage current => CURRENT_SCOPE.current; - - /// - /// Binds a storage service until the returned strict last-in-first-out scope is disposed. - /// - /// - /// The host-owned application storage service. - /// - /// - /// A strict last-in-first-out execution scope. - /// - public static IDisposable EnterScope(IApplicationStorage storage) - { - ArgumentNullException.ThrowIfNull(storage); - return CURRENT_SCOPE.Enter(storage); - } -} - /// /// Provides script-friendly access to the current application storage sandbox. /// diff --git a/src/services/storage/Inno.Storage/StorageExecutionContext.cs b/src/services/storage/Inno.Storage/StorageExecutionContext.cs new file mode 100644 index 000000000..e68c584b6 --- /dev/null +++ b/src/services/storage/Inno.Storage/StorageExecutionContext.cs @@ -0,0 +1,35 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Storage; + +/// +/// Binds application storage to the current asynchronous execution context. +/// +public static class StorageExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("storage"); + + /// + /// Gets the storage service bound to the current execution context. + /// + /// + /// Thrown when no storage scope is active. + /// + public static IApplicationStorage current => CURRENT_SCOPE.current; + + /// + /// Binds a storage service until the returned strict last-in-first-out scope is disposed. + /// + /// + /// The host-owned application storage service. + /// + /// + /// A strict last-in-first-out execution scope. + /// + public static IDisposable EnterScope(IApplicationStorage storage) + { + ArgumentNullException.ThrowIfNull(storage); + return CURRENT_SCOPE.Enter(storage); + } +} diff --git a/src/services/text/Inno.Text/FontAsset.cs b/src/services/text/Inno.Text/FontAsset.cs index 6f685bde8..c6c2d9875 100644 --- a/src/services/text/Inno.Text/FontAsset.cs +++ b/src/services/text/Inno.Text/FontAsset.cs @@ -1,100 +1,9 @@ using System; -using System.Buffers.Binary; using Inno.Assets; using Inno.Extensibility.Types; namespace Inno.Text; -/// -/// Describes immutable metadata for an imported OpenType font source. -/// -public readonly record struct FontMetadata -{ - /// - /// Creates validated imported font metadata. - /// - /// - /// The number of faces in the source collection. - /// - /// - /// The encoded source length in bytes. - /// - public FontMetadata( - int faceCount, - long encodedByteLength - ) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(faceCount); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(encodedByteLength); - this.faceCount = faceCount; - this.encodedByteLength = encodedByteLength; - } - - /// - /// Gets the number of independently addressable faces in the source. - /// - public int faceCount { get; } - - /// - /// Gets the encoded source length in bytes. - /// - public long encodedByteLength { get; } -} - -/// -/// Encodes the compact runtime payload shared by the font importer and text runtime. -/// -public static class FontMetadataCodec -{ - private const uint C_MAGIC = 0x544E_4649; - private const int C_SIZE = 16; - - /// - /// Encodes validated metadata into a deterministic runtime payload. - /// - /// - /// The metadata to encode. - /// - /// - /// The compact runtime payload. - /// - public static byte[] Encode(FontMetadata metadata) - { - var output = new byte[C_SIZE]; - BinaryPrimitives.WriteUInt32LittleEndian(output, C_MAGIC); - BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(4), metadata.faceCount); - BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(8), metadata.encodedByteLength); - return output; - } - - /// - /// Decodes and validates a compact font runtime payload. - /// - /// - /// The complete runtime payload. - /// - /// - /// The decoded metadata. - /// - public static FontMetadata Decode(ReadOnlySpan payload) - { - if (payload.Length != C_SIZE || BinaryPrimitives.ReadUInt32LittleEndian(payload) != C_MAGIC) - { - throw new InvalidOperationException("The font runtime payload is invalid."); - } - try - { - return new FontMetadata( - BinaryPrimitives.ReadInt32LittleEndian(payload[4..]), - BinaryPrimitives.ReadInt64LittleEndian(payload[8..]) - ); - } - catch (ArgumentOutOfRangeException exception) - { - throw new InvalidOperationException("The font runtime payload contains invalid metadata.", exception); - } - } -} - /// /// Represents one imported OpenType font file or collection. /// diff --git a/src/services/text/Inno.Text/FontMetadata.cs b/src/services/text/Inno.Text/FontMetadata.cs new file mode 100644 index 000000000..a8937388f --- /dev/null +++ b/src/services/text/Inno.Text/FontMetadata.cs @@ -0,0 +1,38 @@ +using System; + +namespace Inno.Text; + +/// +/// Describes immutable metadata for an imported OpenType font source. +/// +public readonly record struct FontMetadata +{ + /// + /// Creates validated imported font metadata. + /// + /// + /// The number of faces in the source collection. + /// + /// + /// The encoded source length in bytes. + /// + public FontMetadata( + int faceCount, + long encodedByteLength + ) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(faceCount); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(encodedByteLength); + this.faceCount = faceCount; + this.encodedByteLength = encodedByteLength; + } + + /// + /// Gets the number of independently addressable faces in the source. + /// + public int faceCount { get; } + + /// + /// Gets the encoded source length in bytes. + /// + public long encodedByteLength { get; } +} diff --git a/src/services/text/Inno.Text/FontMetadataCodec.cs b/src/services/text/Inno.Text/FontMetadataCodec.cs new file mode 100644 index 000000000..d5c9c6519 --- /dev/null +++ b/src/services/text/Inno.Text/FontMetadataCodec.cs @@ -0,0 +1,59 @@ +using System; +using System.Buffers.Binary; + +namespace Inno.Text; + +/// +/// Encodes the compact runtime payload shared by the font importer and text runtime. +/// +public static class FontMetadataCodec +{ + private const uint C_MAGIC = 0x544E_4649; + private const int C_SIZE = 16; + + /// + /// Encodes validated metadata into a deterministic runtime payload. + /// + /// + /// The metadata to encode. + /// + /// + /// The compact runtime payload. + /// + public static byte[] Encode(FontMetadata metadata) + { + var output = new byte[C_SIZE]; + BinaryPrimitives.WriteUInt32LittleEndian(output, C_MAGIC); + BinaryPrimitives.WriteInt32LittleEndian(output.AsSpan(4), metadata.faceCount); + BinaryPrimitives.WriteInt64LittleEndian(output.AsSpan(8), metadata.encodedByteLength); + return output; + } + + /// + /// Decodes and validates a compact font runtime payload. + /// + /// + /// The complete runtime payload. + /// + /// + /// The decoded metadata. + /// + public static FontMetadata Decode(ReadOnlySpan payload) + { + if (payload.Length != C_SIZE || BinaryPrimitives.ReadUInt32LittleEndian(payload) != C_MAGIC) + { + throw new InvalidOperationException("The font runtime payload is invalid."); + } + try + { + return new FontMetadata( + BinaryPrimitives.ReadInt32LittleEndian(payload[4..]), + BinaryPrimitives.ReadInt64LittleEndian(payload[8..]) + ); + } + catch (ArgumentOutOfRangeException exception) + { + throw new InvalidOperationException("The font runtime payload contains invalid metadata.", exception); + } + } +} diff --git a/src/services/text/Inno.Text/GlyphBitmap.cs b/src/services/text/Inno.Text/GlyphBitmap.cs new file mode 100644 index 000000000..023edf7a4 --- /dev/null +++ b/src/services/text/Inno.Text/GlyphBitmap.cs @@ -0,0 +1,88 @@ +using System; + +namespace Inno.Text; + +/// +/// Contains one rasterized glyph as tightly packed 8-bit coverage. +/// +public sealed class GlyphBitmap +{ + private readonly byte[] m_pixels; + + /// + /// Creates a validated immutable glyph bitmap. + /// + /// + /// The bitmap width in pixels. + /// + /// + /// The bitmap height in pixels. + /// + /// + /// The horizontal bearing in pixels. + /// + /// + /// The vertical bearing in pixels. + /// + /// + /// The horizontal glyph advance. + /// + /// + /// Tightly packed row-major 8-bit coverage. + /// + public GlyphBitmap( + int width, + int height, + int bearingX, + int bearingY, + float advanceX, + ReadOnlySpan pixels + ) { + ArgumentOutOfRangeException.ThrowIfNegative(width); + ArgumentOutOfRangeException.ThrowIfNegative(height); + if (pixels.Length != checked(width * height)) + { + throw new ArgumentException("Glyph coverage length must match its dimensions.", nameof(pixels)); + } + if (!float.IsFinite(advanceX)) + { + throw new ArgumentOutOfRangeException(nameof(advanceX)); + } + this.width = width; + this.height = height; + this.bearingX = bearingX; + this.bearingY = bearingY; + this.advanceX = advanceX; + m_pixels = pixels.ToArray(); + } + + /// + /// Gets the bitmap width in pixels. + /// + public int width { get; } + + /// + /// Gets the bitmap height in pixels. + /// + public int height { get; } + + /// + /// Gets the horizontal bearing in pixels. + /// + public int bearingX { get; } + + /// + /// Gets the vertical bearing in pixels. + /// + public int bearingY { get; } + + /// + /// Gets the horizontal glyph advance. + /// + public float advanceX { get; } + + /// + /// Gets tightly packed row-major 8-bit coverage. + /// + public ReadOnlyMemory pixels => m_pixels; +} diff --git a/src/services/text/Inno.Text/Text.cs b/src/services/text/Inno.Text/Text.cs index 4f63c1558..9ab9de203 100644 --- a/src/services/text/Inno.Text/Text.cs +++ b/src/services/text/Inno.Text/Text.cs @@ -1,36 +1,5 @@ -using System; -using Inno.Core.Execution; - namespace Inno.Text; -/// -/// Binds one text service to the current asynchronous execution context. -/// -public static class TextExecutionContext -{ - private static readonly ExecutionSlot CURRENT_SCOPE = new("text"); - - /// - /// Gets the text service bound to the current execution context. - /// - public static ITextService current => CURRENT_SCOPE.current; - - /// - /// Binds a text service until the returned strict last-in-first-out scope is disposed. - /// - /// - /// The host-owned text service. - /// - /// - /// The caller-owned binding scope. - /// - public static IDisposable EnterScope(ITextService text) - { - ArgumentNullException.ThrowIfNull(text); - return CURRENT_SCOPE.Enter(text); - } -} - /// /// Provides script-friendly access to Unicode shaping and glyph rasterization. /// diff --git a/src/services/text/Inno.Text/TextDirection.cs b/src/services/text/Inno.Text/TextDirection.cs new file mode 100644 index 000000000..01556f3f9 --- /dev/null +++ b/src/services/text/Inno.Text/TextDirection.cs @@ -0,0 +1,28 @@ +namespace Inno.Text; + +/// +/// Selects the logical direction used by the shaping engine. +/// +public enum TextDirection +{ + /// + /// Lets the shaping engine infer direction from the text. + /// + Automatic, + /// + /// Shapes text from left to right. + /// + LeftToRight, + /// + /// Shapes text from right to left. + /// + RightToLeft, + /// + /// Shapes text from top to bottom. + /// + TopToBottom, + /// + /// Shapes text from bottom to top. + /// + BottomToTop +} diff --git a/src/services/text/Inno.Text/TextExecutionContext.cs b/src/services/text/Inno.Text/TextExecutionContext.cs new file mode 100644 index 000000000..0135c3de7 --- /dev/null +++ b/src/services/text/Inno.Text/TextExecutionContext.cs @@ -0,0 +1,32 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.Text; + +/// +/// Binds one text service to the current asynchronous execution context. +/// +public static class TextExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("text"); + + /// + /// Gets the text service bound to the current execution context. + /// + public static ITextService current => CURRENT_SCOPE.current; + + /// + /// Binds a text service until the returned strict last-in-first-out scope is disposed. + /// + /// + /// The host-owned text service. + /// + /// + /// The caller-owned binding scope. + /// + public static IDisposable EnterScope(ITextService text) + { + ArgumentNullException.ThrowIfNull(text); + return CURRENT_SCOPE.Enter(text); + } +} diff --git a/src/services/text/Inno.Text/TextFontHandle.cs b/src/services/text/Inno.Text/TextFontHandle.cs new file mode 100644 index 000000000..6c7a57382 --- /dev/null +++ b/src/services/text/Inno.Text/TextFontHandle.cs @@ -0,0 +1,15 @@ +namespace Inno.Text; + +/// +/// Identifies one font face loaded into a text backend generation. +/// +/// +/// The concrete value read or transformed by this operation. +/// +public readonly record struct TextFontHandle(ulong value) +{ + /// + /// Gets whether this handle identifies a loaded face. + /// + public bool isValid => value != 0; +} diff --git a/src/services/text/Inno.Text/TextFontStyle.cs b/src/services/text/Inno.Text/TextFontStyle.cs new file mode 100644 index 000000000..6ce404519 --- /dev/null +++ b/src/services/text/Inno.Text/TextFontStyle.cs @@ -0,0 +1,20 @@ +namespace Inno.Text; + +/// +/// Selects the typographic slant requested from a font face. +/// +public enum TextFontStyle +{ + /// + /// Uses an upright face. + /// + Normal, + /// + /// Uses an italic face. + /// + Italic, + /// + /// Uses an oblique face. + /// + Oblique +} diff --git a/src/services/text/Inno.Text/TextGlyph.cs b/src/services/text/Inno.Text/TextGlyph.cs new file mode 100644 index 000000000..8e45d7c7c --- /dev/null +++ b/src/services/text/Inno.Text/TextGlyph.cs @@ -0,0 +1,32 @@ +namespace Inno.Text; + +/// +/// Describes one positioned glyph emitted by Unicode shaping. +/// +/// +/// The glyph identifier in the font face that produced this layout. +/// +/// +/// The source cluster index reported by the backend. The FreeType/HarfBuzz backend +/// reports a UTF-8 byte offset, not a UTF-16 character index. +/// +/// +/// The horizontal pen advance in logical pixels, including backend-applied letter spacing. +/// +/// +/// The vertical pen advance in logical pixels, including backend-applied letter spacing. +/// +/// +/// The horizontal placement offset from the pen position in logical pixels. +/// +/// +/// The vertical placement offset from the pen position in logical pixels. +/// +public readonly record struct TextGlyph( + uint glyphID, + uint cluster, + float advanceX, + float advanceY, + float offsetX, + float offsetY +); diff --git a/src/services/text/Inno.Text/TextLayout.cs b/src/services/text/Inno.Text/TextLayout.cs new file mode 100644 index 000000000..329925cbf --- /dev/null +++ b/src/services/text/Inno.Text/TextLayout.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Text; + +/// +/// Contains immutable positioned glyphs and aggregate bounds for one shaped string. +/// +public sealed class TextLayout +{ + private readonly TextGlyph[] m_glyphs; + + /// + /// Creates an immutable text layout. + /// + /// + /// The positioned glyph sequence. + /// + /// + /// The face metrics used by the layout. + /// + /// + /// The logical horizontal advance. + /// + /// + /// The logical line height. + /// + public TextLayout( + IEnumerable glyphs, + TextMetrics metrics, + float width, + float height + ) { + ArgumentNullException.ThrowIfNull(glyphs); + if (!float.IsFinite(width) || width < 0f) + { + throw new ArgumentOutOfRangeException(nameof(width)); + } + if (!float.IsFinite(height) || height < 0f) + { + throw new ArgumentOutOfRangeException(nameof(height)); + } + m_glyphs = [..glyphs]; + this.metrics = metrics; + this.width = width; + this.height = height; + } + + /// + /// Gets the immutable positioned glyph sequence. + /// + public IReadOnlyList glyphs => m_glyphs; + + /// + /// Gets the font metrics used to build this layout. + /// + public TextMetrics metrics { get; } + + /// + /// Gets the aggregate horizontal advance. + /// + public float width { get; } + + /// + /// Gets the aggregate line height. + /// + public float height { get; } +} diff --git a/src/services/text/Inno.Text/TextMetrics.cs b/src/services/text/Inno.Text/TextMetrics.cs new file mode 100644 index 000000000..d59ac4d63 --- /dev/null +++ b/src/services/text/Inno.Text/TextMetrics.cs @@ -0,0 +1,27 @@ +namespace Inno.Text; + +/// +/// Describes scalable metrics for one font face and logical size. +/// +/// +/// The scaled face ascender in logical pixels, using the backend's coordinate convention. +/// +/// +/// The scaled face descender in logical pixels, using the backend's coordinate convention. +/// +/// +/// The recommended line spacing in logical pixels for the selected face and size. +/// +/// +/// The scaled underline position relative to the baseline in logical pixels. +/// +/// +/// The scaled underline thickness in logical pixels. +/// +public readonly record struct TextMetrics( + float ascender, + float descender, + float lineHeight, + float underlinePosition, + float underlineThickness +); diff --git a/src/services/text/Inno.Text/TextShapingOptions.cs b/src/services/text/Inno.Text/TextShapingOptions.cs new file mode 100644 index 000000000..3e37b5c2b --- /dev/null +++ b/src/services/text/Inno.Text/TextShapingOptions.cs @@ -0,0 +1,55 @@ +using System; + +namespace Inno.Text; + +/// +/// Defines language and script hints for one shaping operation. +/// +public readonly record struct TextShapingOptions +{ + /// + /// Creates shaping hints. + /// + /// + /// The logical text direction. + /// + /// + /// An optional BCP 47 language code. + /// + /// + /// An optional ISO 15924 script code. + /// + public TextShapingOptions( + TextDirection direction = TextDirection.Automatic, + string? language = null, + string? script = null + ) { + if (!Enum.IsDefined(direction)) + { + throw new ArgumentOutOfRangeException(nameof(direction)); + } + this.direction = direction; + this.language = string.IsNullOrWhiteSpace(language) ? null : language.Trim(); + this.script = string.IsNullOrWhiteSpace(script) ? null : script.Trim(); + } + + /// + /// Gets automatic shaping hints. + /// + public static TextShapingOptions automatic { get; } = new(); + + /// + /// Gets the requested logical direction. + /// + public TextDirection direction { get; } + + /// + /// Gets the optional BCP 47 language code. + /// + public string? language { get; } + + /// + /// Gets the optional ISO 15924 script code. + /// + public string? script { get; } +} diff --git a/src/services/text/Inno.Text/TextStyle.cs b/src/services/text/Inno.Text/TextStyle.cs new file mode 100644 index 000000000..74a4d14a6 --- /dev/null +++ b/src/services/text/Inno.Text/TextStyle.cs @@ -0,0 +1,88 @@ +using System; + +namespace Inno.Text; + +/// +/// Defines immutable font selection and sizing for one shaping operation. +/// +public readonly record struct TextStyle +{ + /// + /// Creates validated text styling. + /// + /// + /// The positive font size in logical pixels. + /// + /// + /// The zero-based face index within the font collection. + /// + /// + /// The requested CSS-compatible weight from 1 through 1000. + /// + /// + /// The requested face slant. + /// + /// + /// Additional logical pixels inserted after each glyph. + /// + public TextStyle( + float fontSize, + int faceIndex = 0, + int weight = 400, + TextFontStyle style = TextFontStyle.Normal, + float letterSpacing = 0f + ) { + if (!float.IsFinite(fontSize) || fontSize <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(fontSize)); + } + ArgumentOutOfRangeException.ThrowIfNegative(faceIndex); + if (weight is < 1 or > 1000) + { + throw new ArgumentOutOfRangeException(nameof(weight)); + } + if (!Enum.IsDefined(style)) + { + throw new ArgumentOutOfRangeException(nameof(style)); + } + if (!float.IsFinite(letterSpacing)) + { + throw new ArgumentOutOfRangeException(nameof(letterSpacing)); + } + this.fontSize = fontSize; + this.faceIndex = faceIndex; + this.weight = weight; + this.style = style; + this.letterSpacing = letterSpacing; + } + + /// + /// Gets a 16-pixel regular default style. + /// + public static TextStyle defaultValue { get; } = new(16f); + + /// + /// Gets the logical font size. + /// + public float fontSize { get; } + + /// + /// Gets the collection face index. + /// + public int faceIndex { get; } + + /// + /// Gets the CSS-compatible font weight. + /// + public int weight { get; } + + /// + /// Gets the requested face slant. + /// + public TextFontStyle style { get; } + + /// + /// Gets additional spacing appended to each glyph advance. + /// + public float letterSpacing { get; } +} diff --git a/src/services/text/Inno.Text/TextTypes.cs b/src/services/text/Inno.Text/TextTypes.cs deleted file mode 100644 index faa03c2ce..000000000 --- a/src/services/text/Inno.Text/TextTypes.cs +++ /dev/null @@ -1,407 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Inno.Text; - -/// -/// Selects the logical direction used by the shaping engine. -/// -public enum TextDirection -{ - /// - /// Lets the shaping engine infer direction from the text. - /// - Automatic, - /// - /// Shapes text from left to right. - /// - LeftToRight, - /// - /// Shapes text from right to left. - /// - RightToLeft, - /// - /// Shapes text from top to bottom. - /// - TopToBottom, - /// - /// Shapes text from bottom to top. - /// - BottomToTop -} - -/// -/// Selects the typographic slant requested from a font face. -/// -public enum TextFontStyle -{ - /// - /// Uses an upright face. - /// - Normal, - /// - /// Uses an italic face. - /// - Italic, - /// - /// Uses an oblique face. - /// - Oblique -} - -/// -/// Identifies one font face loaded into a text backend generation. -/// -/// -/// The concrete value read or transformed by this operation. -/// -public readonly record struct TextFontHandle(ulong value) -{ - /// - /// Gets whether this handle identifies a loaded face. - /// - public bool isValid => value != 0; -} - -/// -/// Defines immutable font selection and sizing for one shaping operation. -/// -public readonly record struct TextStyle -{ - /// - /// Creates validated text styling. - /// - /// - /// The positive font size in logical pixels. - /// - /// - /// The zero-based face index within the font collection. - /// - /// - /// The requested CSS-compatible weight from 1 through 1000. - /// - /// - /// The requested face slant. - /// - /// - /// Additional logical pixels inserted after each glyph. - /// - public TextStyle( - float fontSize, - int faceIndex = 0, - int weight = 400, - TextFontStyle style = TextFontStyle.Normal, - float letterSpacing = 0f - ) { - if (!float.IsFinite(fontSize) || fontSize <= 0f) - { - throw new ArgumentOutOfRangeException(nameof(fontSize)); - } - ArgumentOutOfRangeException.ThrowIfNegative(faceIndex); - if (weight is < 1 or > 1000) - { - throw new ArgumentOutOfRangeException(nameof(weight)); - } - if (!Enum.IsDefined(style)) - { - throw new ArgumentOutOfRangeException(nameof(style)); - } - if (!float.IsFinite(letterSpacing)) - { - throw new ArgumentOutOfRangeException(nameof(letterSpacing)); - } - this.fontSize = fontSize; - this.faceIndex = faceIndex; - this.weight = weight; - this.style = style; - this.letterSpacing = letterSpacing; - } - - /// - /// Gets a 16-pixel regular default style. - /// - public static TextStyle defaultValue { get; } = new(16f); - - /// - /// Gets the logical font size. - /// - public float fontSize { get; } - - /// - /// Gets the collection face index. - /// - public int faceIndex { get; } - - /// - /// Gets the CSS-compatible font weight. - /// - public int weight { get; } - - /// - /// Gets the requested face slant. - /// - public TextFontStyle style { get; } - - /// - /// Gets additional spacing appended to each glyph advance. - /// - public float letterSpacing { get; } -} - -/// -/// Defines language and script hints for one shaping operation. -/// -public readonly record struct TextShapingOptions -{ - /// - /// Creates shaping hints. - /// - /// - /// The logical text direction. - /// - /// - /// An optional BCP 47 language code. - /// - /// - /// An optional ISO 15924 script code. - /// - public TextShapingOptions( - TextDirection direction = TextDirection.Automatic, - string? language = null, - string? script = null - ) { - if (!Enum.IsDefined(direction)) - { - throw new ArgumentOutOfRangeException(nameof(direction)); - } - this.direction = direction; - this.language = string.IsNullOrWhiteSpace(language) ? null : language.Trim(); - this.script = string.IsNullOrWhiteSpace(script) ? null : script.Trim(); - } - - /// - /// Gets automatic shaping hints. - /// - public static TextShapingOptions automatic { get; } = new(); - - /// - /// Gets the requested logical direction. - /// - public TextDirection direction { get; } - - /// - /// Gets the optional BCP 47 language code. - /// - public string? language { get; } - - /// - /// Gets the optional ISO 15924 script code. - /// - public string? script { get; } -} - -/// -/// Describes one positioned glyph emitted by Unicode shaping. -/// -/// -/// The glyph identifier in the font face that produced this layout. -/// -/// -/// The source cluster index reported by the backend. The FreeType/HarfBuzz backend -/// reports a UTF-8 byte offset, not a UTF-16 character index. -/// -/// -/// The horizontal pen advance in logical pixels, including backend-applied letter spacing. -/// -/// -/// The vertical pen advance in logical pixels, including backend-applied letter spacing. -/// -/// -/// The horizontal placement offset from the pen position in logical pixels. -/// -/// -/// The vertical placement offset from the pen position in logical pixels. -/// -public readonly record struct TextGlyph( - uint glyphID, - uint cluster, - float advanceX, - float advanceY, - float offsetX, - float offsetY -); - -/// -/// Describes scalable metrics for one font face and logical size. -/// -/// -/// The scaled face ascender in logical pixels, using the backend's coordinate convention. -/// -/// -/// The scaled face descender in logical pixels, using the backend's coordinate convention. -/// -/// -/// The recommended line spacing in logical pixels for the selected face and size. -/// -/// -/// The scaled underline position relative to the baseline in logical pixels. -/// -/// -/// The scaled underline thickness in logical pixels. -/// -public readonly record struct TextMetrics( - float ascender, - float descender, - float lineHeight, - float underlinePosition, - float underlineThickness -); - -/// -/// Contains immutable positioned glyphs and aggregate bounds for one shaped string. -/// -public sealed class TextLayout -{ - private readonly TextGlyph[] m_glyphs; - - /// - /// Creates an immutable text layout. - /// - /// - /// The positioned glyph sequence. - /// - /// - /// The face metrics used by the layout. - /// - /// - /// The logical horizontal advance. - /// - /// - /// The logical line height. - /// - public TextLayout( - IEnumerable glyphs, - TextMetrics metrics, - float width, - float height - ) { - ArgumentNullException.ThrowIfNull(glyphs); - if (!float.IsFinite(width) || width < 0f) - { - throw new ArgumentOutOfRangeException(nameof(width)); - } - if (!float.IsFinite(height) || height < 0f) - { - throw new ArgumentOutOfRangeException(nameof(height)); - } - m_glyphs = [..glyphs]; - this.metrics = metrics; - this.width = width; - this.height = height; - } - - /// - /// Gets the immutable positioned glyph sequence. - /// - public IReadOnlyList glyphs => m_glyphs; - - /// - /// Gets the font metrics used to build this layout. - /// - public TextMetrics metrics { get; } - - /// - /// Gets the aggregate horizontal advance. - /// - public float width { get; } - - /// - /// Gets the aggregate line height. - /// - public float height { get; } -} - -/// -/// Contains one rasterized glyph as tightly packed 8-bit coverage. -/// -public sealed class GlyphBitmap -{ - private readonly byte[] m_pixels; - - /// - /// Creates a validated immutable glyph bitmap. - /// - /// - /// The bitmap width in pixels. - /// - /// - /// The bitmap height in pixels. - /// - /// - /// The horizontal bearing in pixels. - /// - /// - /// The vertical bearing in pixels. - /// - /// - /// The horizontal glyph advance. - /// - /// - /// Tightly packed row-major 8-bit coverage. - /// - public GlyphBitmap( - int width, - int height, - int bearingX, - int bearingY, - float advanceX, - ReadOnlySpan pixels - ) { - ArgumentOutOfRangeException.ThrowIfNegative(width); - ArgumentOutOfRangeException.ThrowIfNegative(height); - if (pixels.Length != checked(width * height)) - { - throw new ArgumentException("Glyph coverage length must match its dimensions.", nameof(pixels)); - } - if (!float.IsFinite(advanceX)) - { - throw new ArgumentOutOfRangeException(nameof(advanceX)); - } - this.width = width; - this.height = height; - this.bearingX = bearingX; - this.bearingY = bearingY; - this.advanceX = advanceX; - m_pixels = pixels.ToArray(); - } - - /// - /// Gets the bitmap width in pixels. - /// - public int width { get; } - - /// - /// Gets the bitmap height in pixels. - /// - public int height { get; } - - /// - /// Gets the horizontal bearing in pixels. - /// - public int bearingX { get; } - - /// - /// Gets the vertical bearing in pixels. - /// - public int bearingY { get; } - - /// - /// Gets the horizontal glyph advance. - /// - public float advanceX { get; } - - /// - /// Gets tightly packed row-major 8-bit coverage. - /// - public ReadOnlyMemory pixels => m_pixels; -} diff --git a/src/services/ui/Inno.UI.Assets/IUIDocumentFrontend.cs b/src/services/ui/Inno.UI.Assets/IUIDocumentFrontend.cs new file mode 100644 index 000000000..9e4f0fb4d --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/IUIDocumentFrontend.cs @@ -0,0 +1,23 @@ +namespace Inno.UI.Assets; + +/// +/// Validates one UI document language without creating runtime UI objects. +/// +public interface IUIDocumentFrontend +{ + /// + /// Gets the open source-language identity. + /// + UIDocumentLanguageID languageID { get; } + + /// + /// Analyzes one immutable source snapshot. + /// + /// + /// Original source snapshot. + /// + /// + /// Canonical text or neutral diagnostics. + /// + UIDocumentAnalysis Analyze(UIDocumentSourceFile source); +} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentAnalysis.cs b/src/services/ui/Inno.UI.Assets/UIDocumentAnalysis.cs new file mode 100644 index 000000000..ad307cc17 --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentAnalysis.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +namespace Inno.UI.Assets; + +/// +/// Returns validated text without retaining parser or implementation objects. +/// +public sealed class UIDocumentAnalysis +{ + /// + /// Creates a frozen analysis result. + /// + /// + /// Validated canonical text, or null on failure. + /// + /// + /// Complete frontend diagnostics. + /// + /// + /// Font assets declared by the document. + /// + public UIDocumentAnalysis( + string? text, + IEnumerable diagnostics, + IEnumerable? fonts = null + ) { + this.text = text; + this.diagnostics = new ReadOnlyCollection( + diagnostics?.ToArray() + ?? throw new ArgumentNullException(nameof(diagnostics)) + ); + this.fonts = new ReadOnlyCollection(fonts?.ToArray() ?? []); + } + + /// + /// Gets canonical source text, or null after failure. + /// + public string? text { get; } + + /// + /// Gets frozen diagnostics. + /// + public IReadOnlyList diagnostics { get; } + + /// + /// Gets font assets declared by the canonical document. + /// + public IReadOnlyList fonts { get; } + + /// + /// Gets whether the frontend accepted the source. + /// + public bool succeeded => text is not null && diagnostics.Count == 0; +} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentDiagnostic.cs b/src/services/ui/Inno.UI.Assets/UIDocumentDiagnostic.cs new file mode 100644 index 000000000..0cd7520fe --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentDiagnostic.cs @@ -0,0 +1,23 @@ +namespace Inno.UI.Assets; + +/// +/// Reports a language-neutral source problem. +/// +/// +/// Stable diagnostic code. +/// +/// +/// Actionable description. +/// +/// +/// One-based source line. +/// +/// +/// One-based source column. +/// +public sealed record UIDocumentDiagnostic( + string code, + string message, + int line, + int column +); diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentFontDeclaration.cs b/src/services/ui/Inno.UI.Assets/UIDocumentFontDeclaration.cs new file mode 100644 index 000000000..a3e36c3a8 --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentFontDeclaration.cs @@ -0,0 +1,25 @@ +using Inno.Text; + +namespace Inno.UI.Assets; + +/// +/// One font asset declared by a UI document language frontend. +/// +/// +/// Isolated font asset path. +/// +/// +/// Document-private physical family used in canonical text. +/// +/// +/// CSS-compatible face style. +/// +/// +/// CSS-compatible face weight. +/// +public sealed record UIDocumentFontDeclaration( + string assetPath, + string family, + TextFontStyle style, + int weight +); diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentFrontend.cs b/src/services/ui/Inno.UI.Assets/UIDocumentFrontend.cs deleted file mode 100644 index ca9a2271c..000000000 --- a/src/services/ui/Inno.UI.Assets/UIDocumentFrontend.cs +++ /dev/null @@ -1,266 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using Inno.Assets; -using Inno.Extensibility.Types; -using Inno.Text; - -namespace Inno.UI.Assets; - -/// -/// Contains immutable source text supplied to a UI language frontend. -/// -/// -/// Original asset mount path. -/// -/// -/// Strictly decoded UTF-8 text. -/// -/// -/// Reads and records an optional isolated source dependency. -/// -public sealed record UIDocumentSourceFile( - string assetPath, - string text, - Func? readSource = null -); - -/// -/// Reports a language-neutral source problem. -/// -/// -/// Stable diagnostic code. -/// -/// -/// Actionable description. -/// -/// -/// One-based source line. -/// -/// -/// One-based source column. -/// -public sealed record UIDocumentDiagnostic( - string code, - string message, - int line, - int column -); - -/// -/// One font asset declared by a UI document language frontend. -/// -/// -/// Isolated font asset path. -/// -/// -/// Document-private physical family used in canonical text. -/// -/// -/// CSS-compatible face style. -/// -/// -/// CSS-compatible face weight. -/// -public sealed record UIDocumentFontDeclaration( - string assetPath, - string family, - TextFontStyle style, - int weight -); - -/// -/// Returns validated text without retaining parser or implementation objects. -/// -public sealed class UIDocumentAnalysis -{ - /// - /// Creates a frozen analysis result. - /// - /// - /// Validated canonical text, or null on failure. - /// - /// - /// Complete frontend diagnostics. - /// - /// - /// Font assets declared by the document. - /// - public UIDocumentAnalysis( - string? text, - IEnumerable diagnostics, - IEnumerable? fonts = null - ) { - this.text = text; - this.diagnostics = new ReadOnlyCollection( - diagnostics?.ToArray() - ?? throw new ArgumentNullException(nameof(diagnostics)) - ); - this.fonts = new ReadOnlyCollection(fonts?.ToArray() ?? []); - } - - /// - /// Gets canonical source text, or null after failure. - /// - public string? text { get; } - - /// - /// Gets frozen diagnostics. - /// - public IReadOnlyList diagnostics { get; } - - /// - /// Gets font assets declared by the canonical document. - /// - public IReadOnlyList fonts { get; } - - /// - /// Gets whether the frontend accepted the source. - /// - public bool succeeded => text is not null && diagnostics.Count == 0; -} - -/// -/// Validates one UI document language without creating runtime UI objects. -/// -public interface IUIDocumentFrontend -{ - /// - /// Gets the open source-language identity. - /// - UIDocumentLanguageID languageID { get; } - - /// - /// Analyzes one immutable source snapshot. - /// - /// - /// Original source snapshot. - /// - /// - /// Canonical text or neutral diagnostics. - /// - UIDocumentAnalysis Analyze(UIDocumentSourceFile source); -} - -/// -/// Owns one immutable UI language registration snapshot. -/// -public sealed class UIDocumentFrontendCatalog -{ - private readonly Dictionary m_frontends = []; - - /// - /// Captures a validated provider set. - /// - /// - /// Providers owned by the authoring generation. - /// - public UIDocumentFrontendCatalog(IEnumerable frontends) - { - ArgumentNullException.ThrowIfNull(frontends); - foreach (IUIDocumentFrontend frontend in frontends) - { - if (frontend is null || !frontend.languageID.isValid || !m_frontends.TryAdd(frontend.languageID, frontend)) - { - throw new ArgumentException("UI document frontends require unique, assigned language IDs.", nameof(frontends)); - } - } - this.languageIDs = new ReadOnlyCollection([.. m_frontends.Keys]); - } - - /// - /// Gets registered language identities. - /// - public IReadOnlyList languageIDs { get; } - - /// - /// Analyzes source using an explicit language. - /// - /// - /// Registered language identity. - /// - /// - /// Immutable source snapshot. - /// - /// - /// Neutral analysis result. - /// - public UIDocumentAnalysis Analyze( - UIDocumentLanguageID language, - UIDocumentSourceFile source - ) => m_frontends.TryGetValue(language, out IUIDocumentFrontend? frontend) - ? frontend.Analyze(source) ?? throw new InvalidOperationException($"UI language '{language}' returned no analysis.") - : throw new NotSupportedException($"UI document language '{language}' is unavailable."); - - internal IEnumerable providers => m_frontends.Values; -} - -/// -/// Discovers UI language frontends through the shared type-generation transaction. -/// -public sealed class UIDocumentFrontendRegistry : TypeRegistry -{ - private readonly TypeCatalog m_types; - - /// - /// Registers with the owner type catalog. - /// - /// - /// Catalog that outlives this registry. - /// - public UIDocumentFrontendRegistry(TypeCatalog types) - : base(types) - { - m_types = types; - } - - /// - /// Analyzes source while preventing provider retirement. - /// - /// - /// Exact language identity. - /// - /// - /// Immutable source snapshot. - /// - /// - /// Detached neutral analysis. - /// - public UIDocumentAnalysis Analyze( - UIDocumentLanguageID language, - UIDocumentSourceFile source - ) { - using IDisposable operation = m_types.AcquireOperation("Analyze UI document source"); - return current.Analyze(language, source); - } - - /// - /// Builds a validated result from the current immutable input snapshot. - /// - /// - /// The active type catalog generation used for extension resolution. - /// - /// - /// The validated ui document frontend catalog that represents the completed operation. - /// - protected override UIDocumentFrontendCatalog Build(TypeCacheSnapshot types) - { - List providers = []; - foreach (Type type in types.GetTypesImplementing() - .Select(reference => reference.Resolve(types)) - .OrderBy(static type => type.FullName, StringComparer.Ordinal) - ) { - providers.Add(CreateExtension(type)); - } - return new UIDocumentFrontendCatalog(providers); - } - - /// - /// Releases the generation lease retained by an immutable registry snapshot. - /// - /// - /// The immutable state snapshot consumed by this operation. - /// - protected override void DisposeSnapshot(UIDocumentFrontendCatalog snapshot) => DisposeExtensions(snapshot.providers); -} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentFrontendCatalog.cs b/src/services/ui/Inno.UI.Assets/UIDocumentFrontendCatalog.cs new file mode 100644 index 000000000..8a02df8bc --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentFrontendCatalog.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.UI.Assets; + +/// +/// Owns one immutable UI language registration snapshot. +/// +public sealed class UIDocumentFrontendCatalog +{ + private readonly Dictionary m_frontends = []; + + /// + /// Captures a validated provider set. + /// + /// + /// Providers owned by the authoring generation. + /// + public UIDocumentFrontendCatalog(IEnumerable frontends) + { + ArgumentNullException.ThrowIfNull(frontends); + foreach (IUIDocumentFrontend frontend in frontends) + { + if (frontend is null || !frontend.languageID.isValid || !m_frontends.TryAdd(frontend.languageID, frontend)) + { + throw new ArgumentException("UI document frontends require unique, assigned language IDs.", nameof(frontends)); + } + } + this.languageIDs = new ReadOnlyCollection([.. m_frontends.Keys]); + } + + /// + /// Gets registered language identities. + /// + public IReadOnlyList languageIDs { get; } + + /// + /// Analyzes source using an explicit language. + /// + /// + /// Registered language identity. + /// + /// + /// Immutable source snapshot. + /// + /// + /// Neutral analysis result. + /// + public UIDocumentAnalysis Analyze( + UIDocumentLanguageID language, + UIDocumentSourceFile source + ) => m_frontends.TryGetValue(language, out IUIDocumentFrontend? frontend) + ? frontend.Analyze(source) ?? throw new InvalidOperationException($"UI language '{language}' returned no analysis.") + : throw new NotSupportedException($"UI document language '{language}' is unavailable."); + + internal IEnumerable providers => m_frontends.Values; +} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentFrontendRegistry.cs b/src/services/ui/Inno.UI.Assets/UIDocumentFrontendRegistry.cs new file mode 100644 index 000000000..9b3c85c9c --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentFrontendRegistry.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Inno.Extensibility.Types; + +namespace Inno.UI.Assets; + +/// +/// Discovers UI language frontends through the shared type-generation transaction. +/// +public sealed class UIDocumentFrontendRegistry : TypeRegistry +{ + private readonly TypeCatalog m_types; + + /// + /// Registers with the owner type catalog. + /// + /// + /// Catalog that outlives this registry. + /// + public UIDocumentFrontendRegistry(TypeCatalog types) + : base(types) + { + m_types = types; + } + + /// + /// Analyzes source while preventing provider retirement. + /// + /// + /// Exact language identity. + /// + /// + /// Immutable source snapshot. + /// + /// + /// Detached neutral analysis. + /// + public UIDocumentAnalysis Analyze( + UIDocumentLanguageID language, + UIDocumentSourceFile source + ) { + using IDisposable operation = m_types.AcquireOperation("Analyze UI document source"); + return current.Analyze(language, source); + } + + /// + /// Builds a validated result from the current immutable input snapshot. + /// + /// + /// The active type catalog generation used for extension resolution. + /// + /// + /// The validated ui document frontend catalog that represents the completed operation. + /// + protected override UIDocumentFrontendCatalog Build(TypeCacheSnapshot types) + { + List providers = []; + foreach (Type type in types.GetTypesImplementing() + .Select(reference => reference.Resolve(types)) + .OrderBy(static type => type.FullName, StringComparer.Ordinal) + ) { + providers.Add(CreateExtension(type)); + } + return new UIDocumentFrontendCatalog(providers); + } + + /// + /// Releases the generation lease retained by an immutable registry snapshot. + /// + /// + /// The immutable state snapshot consumed by this operation. + /// + protected override void DisposeSnapshot(UIDocumentFrontendCatalog snapshot) => DisposeExtensions(snapshot.providers); +} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs b/src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs new file mode 100644 index 000000000..066a7c26b --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Text; + +namespace Inno.UI.Assets; + +/// +/// Coordinates source analysis, font dependencies, and runtime UI asset emission. +/// +public static class UIDocumentImportPipeline +{ + /// + /// Validates and emits a deterministic runtime payload. + /// + /// + /// Source import context. + /// + /// + /// Candidate writer. + /// + /// + /// Explicit source language. + /// + /// + /// Explicit runtime implementation. + /// + /// + /// Cancellation observed by artifact writes. + /// + /// + /// An operation completing after the payload is staged. + /// + public static async ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + UIDocumentLanguageID language, + string implementationID, + CancellationToken cancellationToken + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(implementationID); + string text = context.ReadUtf8Text(); + using var frontends = new UIDocumentFrontendRegistry(context.types); + UIDocumentAnalysis analysis = frontends.Analyze( + language, + new UIDocumentSourceFile(context.assetPath.ToString(), text, context.ReadSourceUtf8Text) + ); + if (!analysis.succeeded) + { + throw new InvalidDataException( + string.Join( + "\n", + analysis.diagnostics.Select(static diagnostic => + $"{diagnostic.line}:{diagnostic.column}: {diagnostic.code}: {diagnostic.message}") + ) + ); + } + var fonts = new List(analysis.fonts.Count); + foreach (UIDocumentFontDeclaration declaration in analysis.fonts) + { + FontAsset font = context.ResolveDependency(AssetPath.Parse(declaration.assetPath)); + if (font.isMissing || font.metadata is not { faceCount: > 0 }) + { + throw new InvalidDataException($"UI font asset '{declaration.assetPath}' has no usable face."); + } + context.DependsOnArtifact(font.identity.persistentID); + fonts.Add( + new UIDocumentFontFace( + font.identity.persistentID, + declaration.family, + declaration.style, + declaration.weight + ) + ); + } + string sourceUri = $"innoasset://{context.assetPath.source.value}/{context.assetPath.localPath}"; + var source = new UIDocumentSource(language, analysis.text!, sourceUri); + output.SetAsset(new UIDocumentAsset()); + await output.WriteArtifactAsync( + "runtime", + UIDocumentAsset.CreateRuntimePayload(implementationID, source, fonts), + cancellationToken + ).ConfigureAwait(false); + } +} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentImporter.cs b/src/services/ui/Inno.UI.Assets/UIDocumentImporter.cs index ce3ca8080..c274d57b2 100644 --- a/src/services/ui/Inno.UI.Assets/UIDocumentImporter.cs +++ b/src/services/ui/Inno.UI.Assets/UIDocumentImporter.cs @@ -1,13 +1,9 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Threading; using System.Threading.Tasks; -using Inno.Assets; using Inno.Assets.Pipeline; using Inno.Core.Serialization; -using Inno.Text; namespace Inno.UI.Assets; @@ -63,82 +59,3 @@ await UIDocumentImportPipeline.ImportAsync( ).ConfigureAwait(false); } } - -/// -/// Coordinates source analysis, font dependencies, and runtime UI asset emission. -/// -public static class UIDocumentImportPipeline -{ - /// - /// Validates and emits a deterministic runtime payload. - /// - /// - /// Source import context. - /// - /// - /// Candidate writer. - /// - /// - /// Explicit source language. - /// - /// - /// Explicit runtime implementation. - /// - /// - /// Cancellation observed by artifact writes. - /// - /// - /// An operation completing after the payload is staged. - /// - public static async ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - UIDocumentLanguageID language, - string implementationID, - CancellationToken cancellationToken - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(implementationID); - string text = context.ReadUtf8Text(); - using var frontends = new UIDocumentFrontendRegistry(context.types); - UIDocumentAnalysis analysis = frontends.Analyze( - language, - new UIDocumentSourceFile(context.assetPath.ToString(), text, context.ReadSourceUtf8Text) - ); - if (!analysis.succeeded) - { - throw new InvalidDataException( - string.Join( - "\n", - analysis.diagnostics.Select(static diagnostic => - $"{diagnostic.line}:{diagnostic.column}: {diagnostic.code}: {diagnostic.message}") - ) - ); - } - var fonts = new List(analysis.fonts.Count); - foreach (UIDocumentFontDeclaration declaration in analysis.fonts) - { - FontAsset font = context.ResolveDependency(AssetPath.Parse(declaration.assetPath)); - if (font.isMissing || font.metadata is not { faceCount: > 0 }) - { - throw new InvalidDataException($"UI font asset '{declaration.assetPath}' has no usable face."); - } - context.DependsOnArtifact(font.identity.persistentID); - fonts.Add( - new UIDocumentFontFace( - font.identity.persistentID, - declaration.family, - declaration.style, - declaration.weight - ) - ); - } - string sourceUri = $"innoasset://{context.assetPath.source.value}/{context.assetPath.localPath}"; - var source = new UIDocumentSource(language, analysis.text!, sourceUri); - output.SetAsset(new UIDocumentAsset()); - await output.WriteArtifactAsync( - "runtime", - UIDocumentAsset.CreateRuntimePayload(implementationID, source, fonts), - cancellationToken - ).ConfigureAwait(false); - } -} diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentSourceFile.cs b/src/services/ui/Inno.UI.Assets/UIDocumentSourceFile.cs new file mode 100644 index 000000000..df1149031 --- /dev/null +++ b/src/services/ui/Inno.UI.Assets/UIDocumentSourceFile.cs @@ -0,0 +1,22 @@ +using System; +using Inno.Assets; + +namespace Inno.UI.Assets; + +/// +/// Contains immutable source text supplied to a UI language frontend. +/// +/// +/// Original asset mount path. +/// +/// +/// Strictly decoded UTF-8 text. +/// +/// +/// Reads and records an optional isolated source dependency. +/// +public sealed record UIDocumentSourceFile( + string assetPath, + string text, + Func? readSource = null +); diff --git a/src/services/ui/Inno.UI/UI.cs b/src/services/ui/Inno.UI/UI.cs index d3e5ed194..774e01162 100644 --- a/src/services/ui/Inno.UI/UI.cs +++ b/src/services/ui/Inno.UI/UI.cs @@ -1,37 +1,7 @@ -using System; using System.Collections.Generic; -using Inno.Core.Execution; namespace Inno.UI; -/// -/// Binds one UI service to the current asynchronous execution context. -/// -public static class UIExecutionContext -{ - private static readonly ExecutionSlot CURRENT_SCOPE = new("ui"); - - /// - /// Gets the UI service bound to the current execution context. - /// - public static IUIService current => CURRENT_SCOPE.current; - - /// - /// Binds a UI service until the returned strict last-in-first-out scope is disposed. - /// - /// - /// The host-owned UI service. - /// - /// - /// The caller-owned binding scope. - /// - public static IDisposable EnterScope(IUIService ui) - { - ArgumentNullException.ThrowIfNull(ui); - return CURRENT_SCOPE.Enter(ui); - } -} - /// /// Provides script-friendly retained-mode UI operations. /// diff --git a/src/services/ui/Inno.UI/UIBackendCapabilities.cs b/src/services/ui/Inno.UI/UIBackendCapabilities.cs index 6d0c4bb7b..afc67e1d3 100644 --- a/src/services/ui/Inno.UI/UIBackendCapabilities.cs +++ b/src/services/ui/Inno.UI/UIBackendCapabilities.cs @@ -67,26 +67,3 @@ public enum UIBackendCapability /// FontCollectionFaceSelection } - -/// -/// Reports that the selected backend cannot perform an explicitly requested optional operation. -/// -public sealed class UICapabilityUnavailableException : NotSupportedException -{ - /// - /// Creates a capability failure without naming a concrete implementation. - /// - /// - /// Unavailable neutral capability. - /// - public UICapabilityUnavailableException(UIBackendCapability capability) - : base($"The selected UI backend does not support capability '{capability}'.") - { - this.capability = capability; - } - - /// - /// Gets the unavailable capability. - /// - public UIBackendCapability capability { get; } -} diff --git a/src/services/ui/Inno.UI/UICapabilityUnavailableException.cs b/src/services/ui/Inno.UI/UICapabilityUnavailableException.cs new file mode 100644 index 000000000..effc75fef --- /dev/null +++ b/src/services/ui/Inno.UI/UICapabilityUnavailableException.cs @@ -0,0 +1,26 @@ +using System; + +namespace Inno.UI; + +/// +/// Reports that the selected backend cannot perform an explicitly requested optional operation. +/// +public sealed class UICapabilityUnavailableException : NotSupportedException +{ + /// + /// Creates a capability failure without naming a concrete implementation. + /// + /// + /// Unavailable neutral capability. + /// + public UICapabilityUnavailableException(UIBackendCapability capability) + : base($"The selected UI backend does not support capability '{capability}'.") + { + this.capability = capability; + } + + /// + /// Gets the unavailable capability. + /// + public UIBackendCapability capability { get; } +} diff --git a/src/services/ui/Inno.UI/UIClipRectangle.cs b/src/services/ui/Inno.UI/UIClipRectangle.cs new file mode 100644 index 000000000..66f37404e --- /dev/null +++ b/src/services/ui/Inno.UI/UIClipRectangle.cs @@ -0,0 +1,23 @@ +namespace Inno.UI; + +/// +/// Defines an integer clipping rectangle in UI surface coordinates. +/// +/// +/// The horizontal or first component. +/// +/// +/// The vertical or second component. +/// +/// +/// The width in logical units or pixels required by this operation. +/// +/// +/// The height in logical units or pixels required by this operation. +/// +public readonly record struct UIClipRectangle( + int x, + int y, + int width, + int height +); diff --git a/src/services/ui/Inno.UI/UIHandles.cs b/src/services/ui/Inno.UI/UIContextHandle.cs similarity index 52% rename from src/services/ui/Inno.UI/UIHandles.cs rename to src/services/ui/Inno.UI/UIContextHandle.cs index 4ddc5e5a5..00fbb8783 100644 --- a/src/services/ui/Inno.UI/UIHandles.cs +++ b/src/services/ui/Inno.UI/UIContextHandle.cs @@ -13,17 +13,3 @@ public readonly record struct UIContextHandle(ulong value) /// public bool isValid => value != 0; } - -/// -/// Identifies one document owned by a UI context. -/// -/// -/// The concrete value read or transformed by this operation. -/// -public readonly record struct UIDocumentHandle(ulong value) -{ - /// - /// Gets whether this handle identifies a live document candidate. - /// - public bool isValid => value != 0; -} diff --git a/src/services/ui/Inno.UI/UIContextOptions.cs b/src/services/ui/Inno.UI/UIContextOptions.cs new file mode 100644 index 000000000..d9e81517d --- /dev/null +++ b/src/services/ui/Inno.UI/UIContextOptions.cs @@ -0,0 +1,63 @@ +using System; + +namespace Inno.UI; + +/// +/// Defines one independent UI layout and interaction surface. +/// +public readonly record struct UIContextOptions +{ + /// + /// Creates validated context options. + /// + /// + /// A non-empty diagnostic context name. + /// + /// + /// The positive initial width in pixels. + /// + /// + /// The positive initial height in pixels. + /// + /// + /// The positive density-independent pixel ratio. + /// + public UIContextOptions( + string name, + int width, + int height, + float density = 1f + ) { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (!float.IsFinite(density) || density <= 0f) + { + throw new ArgumentOutOfRangeException(nameof(density)); + } + this.name = name.Trim(); + this.width = width; + this.height = height; + this.density = density; + } + + /// + /// Gets the diagnostic context name. + /// + public string name { get; } + + /// + /// Gets the initial width in pixels. + /// + public int width { get; } + + /// + /// Gets the initial height in pixels. + /// + public int height { get; } + + /// + /// Gets the density-independent pixel ratio. + /// + public float density { get; } +} diff --git a/src/services/ui/Inno.UI/UIDocumentFragment.cs b/src/services/ui/Inno.UI/UIDocumentFragment.cs new file mode 100644 index 000000000..a66595a36 --- /dev/null +++ b/src/services/ui/Inno.UI/UIDocumentFragment.cs @@ -0,0 +1,41 @@ +using System; + +namespace Inno.UI; + +/// +/// Contains a language-tagged fragment for a backend-specific document mutation. +/// +public readonly record struct UIDocumentFragment +{ + /// + /// Creates a validated source fragment. + /// + /// + /// Explicit fragment language. + /// + /// + /// Complete fragment text. + /// + public UIDocumentFragment( + UIDocumentLanguageID language, + string text + ) { + if (!language.isValid) + { + throw new ArgumentException("A document fragment requires an assigned language.", nameof(language)); + } + ArgumentNullException.ThrowIfNull(text); + this.language = language; + this.text = text; + } + + /// + /// Gets the explicitly selected fragment language. + /// + public UIDocumentLanguageID language { get; } + + /// + /// Gets the complete fragment text. + /// + public string text { get; } +} diff --git a/src/services/ui/Inno.UI/UIDocumentHandle.cs b/src/services/ui/Inno.UI/UIDocumentHandle.cs new file mode 100644 index 000000000..23e780673 --- /dev/null +++ b/src/services/ui/Inno.UI/UIDocumentHandle.cs @@ -0,0 +1,15 @@ +namespace Inno.UI; + +/// +/// Identifies one document owned by a UI context. +/// +/// +/// The concrete value read or transformed by this operation. +/// +public readonly record struct UIDocumentHandle(ulong value) +{ + /// + /// Gets whether this handle identifies a live document candidate. + /// + public bool isValid => value != 0; +} diff --git a/src/services/ui/Inno.UI/UIIdentifiers.cs b/src/services/ui/Inno.UI/UIDocumentLanguageID.cs similarity index 100% rename from src/services/ui/Inno.UI/UIIdentifiers.cs rename to src/services/ui/Inno.UI/UIDocumentLanguageID.cs diff --git a/src/services/ui/Inno.UI/UIDocumentSource.cs b/src/services/ui/Inno.UI/UIDocumentSource.cs new file mode 100644 index 000000000..f3b370565 --- /dev/null +++ b/src/services/ui/Inno.UI/UIDocumentSource.cs @@ -0,0 +1,52 @@ +using System; + +namespace Inno.UI; + +/// +/// Contains immutable text in one explicitly selected UI document language. +/// +public sealed class UIDocumentSource +{ + /// + /// Creates a validated in-memory document source. + /// + /// + /// Explicit source language understood by a registered backend. + /// + /// + /// Complete immutable document text. + /// + /// + /// Virtual source address used only for diagnostics and relative dependency identity. + /// + public UIDocumentSource( + UIDocumentLanguageID language, + string text, + string sourceUri = "memory://ui-document" + ) { + if (!language.isValid) + { + throw new ArgumentException("A document source requires an assigned language.", nameof(language)); + } + ArgumentException.ThrowIfNullOrWhiteSpace(text); + ArgumentException.ThrowIfNullOrWhiteSpace(sourceUri); + this.language = language; + this.text = text; + this.sourceUri = sourceUri; + } + + /// + /// Gets the explicitly selected source language. + /// + public UIDocumentLanguageID language { get; } + + /// + /// Gets the complete immutable source text. + /// + public string text { get; } + + /// + /// Gets the virtual source address. + /// + public string sourceUri { get; } +} diff --git a/src/services/ui/Inno.UI/UIDrawCommand.cs b/src/services/ui/Inno.UI/UIDrawCommand.cs new file mode 100644 index 000000000..a7530cf41 --- /dev/null +++ b/src/services/ui/Inno.UI/UIDrawCommand.cs @@ -0,0 +1,23 @@ +namespace Inno.UI; + +/// +/// Describes one draw of a previously published mesh. +/// +/// +/// The ui mesh handle value used to initialize this instance. +/// +/// +/// The ui texture handle value used to initialize this instance. +/// +/// +/// The bool value used to initialize this instance. +/// +/// +/// The ui clip rectangle value used to initialize this instance. +/// +public readonly record struct UIDrawCommand( + UIMeshHandle mesh, + UITextureHandle texture, + bool scissorEnabled, + UIClipRectangle scissor +); diff --git a/src/services/ui/Inno.UI/UIEvent.cs b/src/services/ui/Inno.UI/UIEvent.cs new file mode 100644 index 000000000..1a3bd6e2b --- /dev/null +++ b/src/services/ui/Inno.UI/UIEvent.cs @@ -0,0 +1,83 @@ +using System; +using Inno.Core.Events; + +namespace Inno.UI; + +/// +/// Describes one queued document event after a context update. +/// +public sealed class UIEvent : Event +{ + /// + /// Creates a document event with its source document and target element. + /// + /// + /// The kind of document interaction. + /// + /// + /// The document that produced the event. + /// + /// + /// The target element identifier, which can be empty. + /// + public UIEvent( + UIEventType type, + UIDocumentHandle document, + string targetID + ) { + ArgumentNullException.ThrowIfNull(targetID); + this.type = type; + this.document = document; + this.targetID = targetID; + } + + /// + /// Gets the kind of document interaction. + /// + public UIEventType type { get; } + + /// + /// Gets the source document. + /// + public UIDocumentHandle document { get; } + + /// + /// Gets the target element identifier. + /// + public string targetID { get; } +} + +/// +/// Identifies one document event made visible to game code. +/// +public enum UIEventType +{ + /// + /// The target was clicked. + /// + Click, + /// + /// The target value changed. + /// + Change, + /// + /// A form was submitted. + /// + Submit, + /// + /// The target gained focus. + /// + Focus, + /// + /// The target lost focus. + /// + Blur, + /// + /// A pointer entered the target. + /// + MouseEnter, + /// + /// A pointer left the target. + /// + MouseLeave +} diff --git a/src/services/ui/Inno.UI/UIExecutionContext.cs b/src/services/ui/Inno.UI/UIExecutionContext.cs new file mode 100644 index 000000000..a135c5f97 --- /dev/null +++ b/src/services/ui/Inno.UI/UIExecutionContext.cs @@ -0,0 +1,32 @@ +using System; +using Inno.Core.Execution; + +namespace Inno.UI; + +/// +/// Binds one UI service to the current asynchronous execution context. +/// +public static class UIExecutionContext +{ + private static readonly ExecutionSlot CURRENT_SCOPE = new("ui"); + + /// + /// Gets the UI service bound to the current execution context. + /// + public static IUIService current => CURRENT_SCOPE.current; + + /// + /// Binds a UI service until the returned strict last-in-first-out scope is disposed. + /// + /// + /// The host-owned UI service. + /// + /// + /// The caller-owned binding scope. + /// + public static IDisposable EnterScope(IUIService ui) + { + ArgumentNullException.ThrowIfNull(ui); + return CURRENT_SCOPE.Enter(ui); + } +} diff --git a/src/services/ui/Inno.UI/UIInputSnapshot.cs b/src/services/ui/Inno.UI/UIInputSnapshot.cs new file mode 100644 index 000000000..99c4fe4de --- /dev/null +++ b/src/services/ui/Inno.UI/UIInputSnapshot.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Input; +using Inno.Core.Mathematics; + +namespace Inno.UI; + +/// +/// Carries one immutable input snapshot across the UI backend boundary. +/// +public sealed class UIInputSnapshot +{ + /// + /// Creates one backend-neutral UI input snapshot. + /// + /// + /// Pointer position in surface coordinates. + /// + /// + /// Pointer wheel movement. + /// + /// + /// Active keyboard modifiers. + /// + /// + /// Physical keys pressed this frame. + /// + /// + /// Physical keys released this frame. + /// + /// + /// Pointer buttons pressed this frame. + /// + /// + /// Pointer buttons released this frame. + /// + /// + /// Ordered Unicode text commits. + /// + public UIInputSnapshot( + Vector2 mousePosition, + Vector2 scrollDelta, + KeyModifier modifiers, + IReadOnlyCollection keysPressed, + IReadOnlyCollection keysReleased, + IReadOnlyCollection buttonsPressed, + IReadOnlyCollection buttonsReleased, + IReadOnlyList textInput + ) { + ArgumentNullException.ThrowIfNull(keysPressed); + ArgumentNullException.ThrowIfNull(keysReleased); + ArgumentNullException.ThrowIfNull(buttonsPressed); + ArgumentNullException.ThrowIfNull(buttonsReleased); + ArgumentNullException.ThrowIfNull(textInput); + this.mousePosition = mousePosition; + this.scrollDelta = scrollDelta; + this.modifiers = modifiers; + this.keysPressed = keysPressed; + this.keysReleased = keysReleased; + this.buttonsPressed = buttonsPressed; + this.buttonsReleased = buttonsReleased; + this.textInput = textInput; + } + + /// + /// Gets the pointer position. + /// + public Vector2 mousePosition { get; } + + /// + /// Gets pointer wheel movement. + /// + public Vector2 scrollDelta { get; } + + /// + /// Gets active keyboard modifiers. + /// + public KeyModifier modifiers { get; } + + /// + /// Gets physical keys pressed this frame. + /// + public IReadOnlyCollection keysPressed { get; } + + /// + /// Gets physical keys released this frame. + /// + public IReadOnlyCollection keysReleased { get; } + + /// + /// Gets pointer buttons pressed this frame. + /// + public IReadOnlyCollection buttonsPressed { get; } + + /// + /// Gets pointer buttons released this frame. + /// + public IReadOnlyCollection buttonsReleased { get; } + + /// + /// Gets ordered Unicode text commits. + /// + public IReadOnlyList textInput { get; } +} diff --git a/src/services/ui/Inno.UI/UIMeshUpdate.cs b/src/services/ui/Inno.UI/UIMeshUpdate.cs new file mode 100644 index 000000000..92c45b53f --- /dev/null +++ b/src/services/ui/Inno.UI/UIMeshUpdate.cs @@ -0,0 +1,45 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.UI; + +/// +/// Publishes one immutable mesh generation to a rendering plugin. +/// +public sealed class UIMeshUpdate +{ + private readonly IReadOnlyList m_vertices; + private readonly IReadOnlyList m_indices; + + internal UIMeshUpdate( + UIMeshHandle mesh, + ulong revision, + UIVertex[] vertices, + uint[] indices + ) { + this.mesh = mesh; + this.revision = revision; + m_vertices = new ReadOnlyCollection(vertices); + m_indices = new ReadOnlyCollection(indices); + } + + /// + /// Gets the generation-scoped mesh handle. + /// + public UIMeshHandle mesh { get; } + + /// + /// Gets the monotonically increasing mesh content revision. + /// + public ulong revision { get; } + + /// + /// Gets immutable local-space vertices. + /// + public IReadOnlyList vertices => m_vertices; + + /// + /// Gets immutable triangle indices. + /// + public IReadOnlyList indices => m_indices; +} diff --git a/src/services/ui/Inno.UI/UIRenderFrame.cs b/src/services/ui/Inno.UI/UIRenderFrame.cs new file mode 100644 index 000000000..fde7fc63a --- /dev/null +++ b/src/services/ui/Inno.UI/UIRenderFrame.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Inno.UI; + +/// +/// Contains incremental resource changes and ordered draw commands for one UI context. +/// +public sealed class UIRenderFrame +{ + private readonly IReadOnlyList m_meshUpdates; + private readonly IReadOnlyList m_releasedMeshes; + private readonly IReadOnlyList m_textureUpdates; + private readonly IReadOnlyList m_releasedTextures; + private readonly IReadOnlyList m_commands; + + internal UIRenderFrame( + UIMeshUpdate[] meshUpdates, + UIMeshHandle[] releasedMeshes, + UITextureUpdate[] textureUpdates, + UITextureHandle[] releasedTextures, + UIDrawCommand[] commands + ) { + m_meshUpdates = new ReadOnlyCollection(meshUpdates); + m_releasedMeshes = new ReadOnlyCollection(releasedMeshes); + m_textureUpdates = new ReadOnlyCollection(textureUpdates); + m_releasedTextures = new ReadOnlyCollection(releasedTextures); + m_commands = new ReadOnlyCollection(commands); + } + + /// + /// Gets an empty resource-delta frame. + /// + public static UIRenderFrame empty { get; } = new([], [], [], [], []); + + /// + /// Gets created or replaced mesh generations. + /// + public IReadOnlyList meshUpdates => m_meshUpdates; + + /// + /// Gets mesh generations that must be retired. + /// + public IReadOnlyList releasedMeshes => m_releasedMeshes; + + /// + /// Gets created or replaced texture generations. + /// + public IReadOnlyList textureUpdates => m_textureUpdates; + + /// + /// Gets texture generations that must be retired. + /// + public IReadOnlyList releasedTextures => m_releasedTextures; + + /// + /// Gets ordered draws referencing published resources. + /// + public IReadOnlyList commands => m_commands; + + /// + /// Creates a command-free frame that deterministically retires plugin-owned resources. + /// + /// + /// Assigned mesh handles to retire. + /// + /// + /// Assigned texture handles to retire. + /// + /// + /// An immutable retirement frame. + /// + public static UIRenderFrame CreateRetirement( + UIMeshHandle[] meshes, + UITextureHandle[] textures + ) { + ArgumentNullException.ThrowIfNull(meshes); + ArgumentNullException.ThrowIfNull(textures); + if (Array.Exists(meshes, static value => !value.isValid)) + { + throw new ArgumentException("Retirement meshes must be assigned.", nameof(meshes)); + } + if (Array.Exists(textures, static value => !value.isValid)) + { + throw new ArgumentException("Retirement textures must be assigned.", nameof(textures)); + } + return new([], (UIMeshHandle[])meshes.Clone(), [], (UITextureHandle[])textures.Clone(), []); + } +} diff --git a/src/services/ui/Inno.UI/UIRenderFrameBuilder.cs b/src/services/ui/Inno.UI/UIRenderFrameBuilder.cs new file mode 100644 index 000000000..fcceec845 --- /dev/null +++ b/src/services/ui/Inno.UI/UIRenderFrameBuilder.cs @@ -0,0 +1,179 @@ +using System; +using System.Collections.Generic; + +namespace Inno.UI; + +/// +/// Builds one immutable backend-neutral frame while transferring ownership of update arrays. +/// +/// +/// This backend SPI is intentionally not exported to ordinary game scripts. +/// +public sealed class UIRenderFrameBuilder +{ + private readonly List m_meshUpdates = []; + private readonly List m_releasedMeshes = []; + private readonly List m_textureUpdates = []; + private readonly List m_releasedTextures = []; + private readonly List m_commands = []; + private bool m_built; + + /// + /// Adds one mesh update and takes exclusive ownership of both arrays. + /// + /// + /// Assigned mesh handle. + /// + /// + /// Positive content revision. + /// + /// + /// Owned vertex array; the caller must not mutate it afterward. + /// + /// + /// Owned index array; the caller must not mutate it afterward. + /// + public void AddMeshUpdate( + UIMeshHandle mesh, + ulong revision, + UIVertex[] vertices, + uint[] indices + ) { + EnsureMutable(); + if (!mesh.isValid) + { + throw new ArgumentException("A mesh update requires an assigned handle.", nameof(mesh)); + } + ArgumentOutOfRangeException.ThrowIfZero(revision); + ArgumentNullException.ThrowIfNull(vertices); + ArgumentNullException.ThrowIfNull(indices); + if (vertices.Length == 0 || indices.Length == 0) + { + throw new ArgumentException("A mesh update requires nonempty geometry."); + } + foreach (uint index in indices) + { + if (index >= vertices.Length) + { + throw new ArgumentException("A mesh index references a vertex outside the update.", nameof(indices)); + } + } + m_meshUpdates.Add(new UIMeshUpdate(mesh, revision, vertices, indices)); + } + + /// + /// Adds one mesh retirement. + /// + /// + /// Assigned mesh handle. + /// + public void AddReleasedMesh(UIMeshHandle mesh) + { + EnsureMutable(); + if (!mesh.isValid) + { + throw new ArgumentException("A released mesh requires an assigned handle.", nameof(mesh)); + } + m_releasedMeshes.Add(mesh); + } + + /// + /// Adds one texture update and takes exclusive ownership of its pixel array. + /// + /// + /// Assigned texture handle. + /// + /// + /// Positive content revision. + /// + /// + /// Positive pixel width. + /// + /// + /// Positive pixel height. + /// + /// + /// Owned tightly packed premultiplied RGBA8 pixels. + /// + public void AddTextureUpdate( + UITextureHandle texture, + ulong revision, + int width, + int height, + byte[] pixels + ) { + EnsureMutable(); + if (!texture.isValid) + { + throw new ArgumentException("A texture update requires an assigned handle.", nameof(texture)); + } + ArgumentOutOfRangeException.ThrowIfZero(revision); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + ArgumentNullException.ThrowIfNull(pixels); + if (pixels.Length != checked(width * height * 4)) + { + throw new ArgumentException("Texture pixels must be tightly packed RGBA8.", nameof(pixels)); + } + m_textureUpdates.Add(new UITextureUpdate(texture, revision, width, height, pixels)); + } + + /// + /// Adds one texture retirement. + /// + /// + /// Assigned texture handle. + /// + public void AddReleasedTexture(UITextureHandle texture) + { + EnsureMutable(); + if (!texture.isValid) + { + throw new ArgumentException("A released texture requires an assigned handle.", nameof(texture)); + } + m_releasedTextures.Add(texture); + } + + /// + /// Adds one ordered mesh draw. + /// + /// + /// Draw command referencing an assigned mesh. + /// + public void AddCommand(UIDrawCommand command) + { + EnsureMutable(); + if (!command.mesh.isValid) + { + throw new ArgumentException("A draw command requires an assigned mesh.", nameof(command)); + } + m_commands.Add(command); + } + + /// + /// Freezes the accumulated frame. The builder cannot be reused. + /// + /// + /// An immutable frame owning every supplied array. + /// + public UIRenderFrame Build() + { + EnsureMutable(); + m_built = true; + return new( + m_meshUpdates.ToArray(), + m_releasedMeshes.ToArray(), + m_textureUpdates.ToArray(), + m_releasedTextures.ToArray(), + m_commands.ToArray() + ); + } + + private void EnsureMutable() + { + if (m_built) + { + throw new InvalidOperationException("A UI render-frame builder can only build one frame."); + } + } +} diff --git a/src/services/ui/Inno.UI/UIRendering.cs b/src/services/ui/Inno.UI/UIRendering.cs deleted file mode 100644 index 732ddc14f..000000000 --- a/src/services/ui/Inno.UI/UIRendering.cs +++ /dev/null @@ -1,423 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; - -namespace Inno.UI; - -/// -/// Describes one vertex in backend-neutral UI draw geometry. -/// -/// -/// The horizontal or first component. -/// -/// -/// The vertical or second component. -/// -/// -/// The float value used to initialize this instance. -/// -/// -/// The concrete value read or transformed by this operation. -/// -/// -/// The uint value used to initialize this instance. -/// -public readonly record struct UIVertex( - float x, - float y, - float u, - float v, - uint color -); - -/// -/// Defines an integer clipping rectangle in UI surface coordinates. -/// -/// -/// The horizontal or first component. -/// -/// -/// The vertical or second component. -/// -/// -/// The width in logical units or pixels required by this operation. -/// -/// -/// The height in logical units or pixels required by this operation. -/// -public readonly record struct UIClipRectangle( - int x, - int y, - int width, - int height -); - -/// -/// Publishes one immutable mesh generation to a rendering plugin. -/// -public sealed class UIMeshUpdate -{ - private readonly IReadOnlyList m_vertices; - private readonly IReadOnlyList m_indices; - - internal UIMeshUpdate( - UIMeshHandle mesh, - ulong revision, - UIVertex[] vertices, - uint[] indices - ) { - this.mesh = mesh; - this.revision = revision; - m_vertices = new ReadOnlyCollection(vertices); - m_indices = new ReadOnlyCollection(indices); - } - - /// - /// Gets the generation-scoped mesh handle. - /// - public UIMeshHandle mesh { get; } - - /// - /// Gets the monotonically increasing mesh content revision. - /// - public ulong revision { get; } - - /// - /// Gets immutable local-space vertices. - /// - public IReadOnlyList vertices => m_vertices; - - /// - /// Gets immutable triangle indices. - /// - public IReadOnlyList indices => m_indices; -} - -/// -/// Publishes one immutable premultiplied RGBA8 texture generation. -/// -public sealed class UITextureUpdate -{ - private readonly byte[] m_pixels; - - internal UITextureUpdate( - UITextureHandle texture, - ulong revision, - int width, - int height, - byte[] pixels - ) { - this.texture = texture; - this.revision = revision; - this.width = width; - this.height = height; - m_pixels = pixels; - } - - /// - /// Gets the generation-scoped texture handle. - /// - public UITextureHandle texture { get; } - - /// - /// Gets the monotonically increasing content revision. - /// - public ulong revision { get; } - - /// - /// Gets the texture width. - /// - public int width { get; } - - /// - /// Gets the texture height. - /// - public int height { get; } - - /// - /// Gets immutable tightly packed premultiplied RGBA8 pixels. - /// - public ReadOnlyMemory pixels => m_pixels; -} - -/// -/// Describes one draw of a previously published mesh. -/// -/// -/// The ui mesh handle value used to initialize this instance. -/// -/// -/// The ui texture handle value used to initialize this instance. -/// -/// -/// The bool value used to initialize this instance. -/// -/// -/// The ui clip rectangle value used to initialize this instance. -/// -public readonly record struct UIDrawCommand( - UIMeshHandle mesh, - UITextureHandle texture, - bool scissorEnabled, - UIClipRectangle scissor -); - -/// -/// Contains incremental resource changes and ordered draw commands for one UI context. -/// -public sealed class UIRenderFrame -{ - private readonly IReadOnlyList m_meshUpdates; - private readonly IReadOnlyList m_releasedMeshes; - private readonly IReadOnlyList m_textureUpdates; - private readonly IReadOnlyList m_releasedTextures; - private readonly IReadOnlyList m_commands; - - internal UIRenderFrame( - UIMeshUpdate[] meshUpdates, - UIMeshHandle[] releasedMeshes, - UITextureUpdate[] textureUpdates, - UITextureHandle[] releasedTextures, - UIDrawCommand[] commands - ) { - m_meshUpdates = new ReadOnlyCollection(meshUpdates); - m_releasedMeshes = new ReadOnlyCollection(releasedMeshes); - m_textureUpdates = new ReadOnlyCollection(textureUpdates); - m_releasedTextures = new ReadOnlyCollection(releasedTextures); - m_commands = new ReadOnlyCollection(commands); - } - - /// - /// Gets an empty resource-delta frame. - /// - public static UIRenderFrame empty { get; } = new([], [], [], [], []); - - /// - /// Gets created or replaced mesh generations. - /// - public IReadOnlyList meshUpdates => m_meshUpdates; - - /// - /// Gets mesh generations that must be retired. - /// - public IReadOnlyList releasedMeshes => m_releasedMeshes; - - /// - /// Gets created or replaced texture generations. - /// - public IReadOnlyList textureUpdates => m_textureUpdates; - - /// - /// Gets texture generations that must be retired. - /// - public IReadOnlyList releasedTextures => m_releasedTextures; - - /// - /// Gets ordered draws referencing published resources. - /// - public IReadOnlyList commands => m_commands; - - /// - /// Creates a command-free frame that deterministically retires plugin-owned resources. - /// - /// - /// Assigned mesh handles to retire. - /// - /// - /// Assigned texture handles to retire. - /// - /// - /// An immutable retirement frame. - /// - public static UIRenderFrame CreateRetirement( - UIMeshHandle[] meshes, - UITextureHandle[] textures - ) { - ArgumentNullException.ThrowIfNull(meshes); - ArgumentNullException.ThrowIfNull(textures); - if (Array.Exists(meshes, static value => !value.isValid)) - { - throw new ArgumentException("Retirement meshes must be assigned.", nameof(meshes)); - } - if (Array.Exists(textures, static value => !value.isValid)) - { - throw new ArgumentException("Retirement textures must be assigned.", nameof(textures)); - } - return new([], (UIMeshHandle[])meshes.Clone(), [], (UITextureHandle[])textures.Clone(), []); - } -} - -/// -/// Builds one immutable backend-neutral frame while transferring ownership of update arrays. -/// -/// -/// This backend SPI is intentionally not exported to ordinary game scripts. -/// -public sealed class UIRenderFrameBuilder -{ - private readonly List m_meshUpdates = []; - private readonly List m_releasedMeshes = []; - private readonly List m_textureUpdates = []; - private readonly List m_releasedTextures = []; - private readonly List m_commands = []; - private bool m_built; - - /// - /// Adds one mesh update and takes exclusive ownership of both arrays. - /// - /// - /// Assigned mesh handle. - /// - /// - /// Positive content revision. - /// - /// - /// Owned vertex array; the caller must not mutate it afterward. - /// - /// - /// Owned index array; the caller must not mutate it afterward. - /// - public void AddMeshUpdate( - UIMeshHandle mesh, - ulong revision, - UIVertex[] vertices, - uint[] indices - ) { - EnsureMutable(); - if (!mesh.isValid) - { - throw new ArgumentException("A mesh update requires an assigned handle.", nameof(mesh)); - } - ArgumentOutOfRangeException.ThrowIfZero(revision); - ArgumentNullException.ThrowIfNull(vertices); - ArgumentNullException.ThrowIfNull(indices); - if (vertices.Length == 0 || indices.Length == 0) - { - throw new ArgumentException("A mesh update requires nonempty geometry."); - } - foreach (uint index in indices) - { - if (index >= vertices.Length) - { - throw new ArgumentException("A mesh index references a vertex outside the update.", nameof(indices)); - } - } - m_meshUpdates.Add(new UIMeshUpdate(mesh, revision, vertices, indices)); - } - - /// - /// Adds one mesh retirement. - /// - /// - /// Assigned mesh handle. - /// - public void AddReleasedMesh(UIMeshHandle mesh) - { - EnsureMutable(); - if (!mesh.isValid) - { - throw new ArgumentException("A released mesh requires an assigned handle.", nameof(mesh)); - } - m_releasedMeshes.Add(mesh); - } - - /// - /// Adds one texture update and takes exclusive ownership of its pixel array. - /// - /// - /// Assigned texture handle. - /// - /// - /// Positive content revision. - /// - /// - /// Positive pixel width. - /// - /// - /// Positive pixel height. - /// - /// - /// Owned tightly packed premultiplied RGBA8 pixels. - /// - public void AddTextureUpdate( - UITextureHandle texture, - ulong revision, - int width, - int height, - byte[] pixels - ) { - EnsureMutable(); - if (!texture.isValid) - { - throw new ArgumentException("A texture update requires an assigned handle.", nameof(texture)); - } - ArgumentOutOfRangeException.ThrowIfZero(revision); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - ArgumentNullException.ThrowIfNull(pixels); - if (pixels.Length != checked(width * height * 4)) - { - throw new ArgumentException("Texture pixels must be tightly packed RGBA8.", nameof(pixels)); - } - m_textureUpdates.Add(new UITextureUpdate(texture, revision, width, height, pixels)); - } - - /// - /// Adds one texture retirement. - /// - /// - /// Assigned texture handle. - /// - public void AddReleasedTexture(UITextureHandle texture) - { - EnsureMutable(); - if (!texture.isValid) - { - throw new ArgumentException("A released texture requires an assigned handle.", nameof(texture)); - } - m_releasedTextures.Add(texture); - } - - /// - /// Adds one ordered mesh draw. - /// - /// - /// Draw command referencing an assigned mesh. - /// - public void AddCommand(UIDrawCommand command) - { - EnsureMutable(); - if (!command.mesh.isValid) - { - throw new ArgumentException("A draw command requires an assigned mesh.", nameof(command)); - } - m_commands.Add(command); - } - - /// - /// Freezes the accumulated frame. The builder cannot be reused. - /// - /// - /// An immutable frame owning every supplied array. - /// - public UIRenderFrame Build() - { - EnsureMutable(); - m_built = true; - return new( - m_meshUpdates.ToArray(), - m_releasedMeshes.ToArray(), - m_textureUpdates.ToArray(), - m_releasedTextures.ToArray(), - m_commands.ToArray() - ); - } - - private void EnsureMutable() - { - if (m_built) - { - throw new InvalidOperationException("A UI render-frame builder can only build one frame."); - } - } -} diff --git a/src/services/ui/Inno.UI/UITextureData.cs b/src/services/ui/Inno.UI/UITextureData.cs new file mode 100644 index 000000000..14795d8f2 --- /dev/null +++ b/src/services/ui/Inno.UI/UITextureData.cs @@ -0,0 +1,54 @@ +using System; + +namespace Inno.UI; + +/// +/// Contains immutable RGBA8 texture pixels addressable by a document source name. +/// +public sealed class UITextureData +{ + private readonly byte[] m_pixels; + + /// + /// Creates a validated immutable texture. + /// + /// + /// The positive texture width. + /// + /// + /// The positive texture height. + /// + /// + /// Tightly packed RGBA8 pixels. + /// + public UITextureData( + int width, + int height, + ReadOnlySpan pixels + ) { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + if (pixels.Length != checked(width * height * 4)) + { + throw new ArgumentException("UI texture pixels must be tightly packed RGBA8.", nameof(pixels)); + } + this.width = width; + this.height = height; + m_pixels = pixels.ToArray(); + } + + /// + /// Gets the texture width. + /// + public int width { get; } + + /// + /// Gets the texture height. + /// + public int height { get; } + + /// + /// Gets the immutable RGBA8 pixels. + /// + public ReadOnlyMemory pixels => m_pixels; +} diff --git a/src/services/ui/Inno.UI/UITextureUpdate.cs b/src/services/ui/Inno.UI/UITextureUpdate.cs new file mode 100644 index 000000000..ccbb3a821 --- /dev/null +++ b/src/services/ui/Inno.UI/UITextureUpdate.cs @@ -0,0 +1,50 @@ +using System; + +namespace Inno.UI; + +/// +/// Publishes one immutable premultiplied RGBA8 texture generation. +/// +public sealed class UITextureUpdate +{ + private readonly byte[] m_pixels; + + internal UITextureUpdate( + UITextureHandle texture, + ulong revision, + int width, + int height, + byte[] pixels + ) { + this.texture = texture; + this.revision = revision; + this.width = width; + this.height = height; + m_pixels = pixels; + } + + /// + /// Gets the generation-scoped texture handle. + /// + public UITextureHandle texture { get; } + + /// + /// Gets the monotonically increasing content revision. + /// + public ulong revision { get; } + + /// + /// Gets the texture width. + /// + public int width { get; } + + /// + /// Gets the texture height. + /// + public int height { get; } + + /// + /// Gets immutable tightly packed premultiplied RGBA8 pixels. + /// + public ReadOnlyMemory pixels => m_pixels; +} diff --git a/src/services/ui/Inno.UI/UITypes.cs b/src/services/ui/Inno.UI/UITypes.cs deleted file mode 100644 index 20439371a..000000000 --- a/src/services/ui/Inno.UI/UITypes.cs +++ /dev/null @@ -1,382 +0,0 @@ -using System; -using System.Collections.Generic; -using Inno.Core.Events; -using Inno.Core.Input; -using Inno.Core.Mathematics; - -namespace Inno.UI; - -/// -/// Defines one independent UI layout and interaction surface. -/// -public readonly record struct UIContextOptions -{ - /// - /// Creates validated context options. - /// - /// - /// A non-empty diagnostic context name. - /// - /// - /// The positive initial width in pixels. - /// - /// - /// The positive initial height in pixels. - /// - /// - /// The positive density-independent pixel ratio. - /// - public UIContextOptions( - string name, - int width, - int height, - float density = 1f - ) { - ArgumentException.ThrowIfNullOrWhiteSpace(name); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - if (!float.IsFinite(density) || density <= 0f) - { - throw new ArgumentOutOfRangeException(nameof(density)); - } - this.name = name.Trim(); - this.width = width; - this.height = height; - this.density = density; - } - - /// - /// Gets the diagnostic context name. - /// - public string name { get; } - - /// - /// Gets the initial width in pixels. - /// - public int width { get; } - - /// - /// Gets the initial height in pixels. - /// - public int height { get; } - - /// - /// Gets the density-independent pixel ratio. - /// - public float density { get; } -} - -/// -/// Contains immutable text in one explicitly selected UI document language. -/// -public sealed class UIDocumentSource -{ - /// - /// Creates a validated in-memory document source. - /// - /// - /// Explicit source language understood by a registered backend. - /// - /// - /// Complete immutable document text. - /// - /// - /// Virtual source address used only for diagnostics and relative dependency identity. - /// - public UIDocumentSource( - UIDocumentLanguageID language, - string text, - string sourceUri = "memory://ui-document" - ) { - if (!language.isValid) - { - throw new ArgumentException("A document source requires an assigned language.", nameof(language)); - } - ArgumentException.ThrowIfNullOrWhiteSpace(text); - ArgumentException.ThrowIfNullOrWhiteSpace(sourceUri); - this.language = language; - this.text = text; - this.sourceUri = sourceUri; - } - - /// - /// Gets the explicitly selected source language. - /// - public UIDocumentLanguageID language { get; } - - /// - /// Gets the complete immutable source text. - /// - public string text { get; } - - /// - /// Gets the virtual source address. - /// - public string sourceUri { get; } -} - -/// -/// Contains a language-tagged fragment for a backend-specific document mutation. -/// -public readonly record struct UIDocumentFragment -{ - /// - /// Creates a validated source fragment. - /// - /// - /// Explicit fragment language. - /// - /// - /// Complete fragment text. - /// - public UIDocumentFragment( - UIDocumentLanguageID language, - string text - ) { - if (!language.isValid) - { - throw new ArgumentException("A document fragment requires an assigned language.", nameof(language)); - } - ArgumentNullException.ThrowIfNull(text); - this.language = language; - this.text = text; - } - - /// - /// Gets the explicitly selected fragment language. - /// - public UIDocumentLanguageID language { get; } - - /// - /// Gets the complete fragment text. - /// - public string text { get; } -} - -/// -/// Contains immutable RGBA8 texture pixels addressable by a document source name. -/// -public sealed class UITextureData -{ - private readonly byte[] m_pixels; - - /// - /// Creates a validated immutable texture. - /// - /// - /// The positive texture width. - /// - /// - /// The positive texture height. - /// - /// - /// Tightly packed RGBA8 pixels. - /// - public UITextureData( - int width, - int height, - ReadOnlySpan pixels - ) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - if (pixels.Length != checked(width * height * 4)) - { - throw new ArgumentException("UI texture pixels must be tightly packed RGBA8.", nameof(pixels)); - } - this.width = width; - this.height = height; - m_pixels = pixels.ToArray(); - } - - /// - /// Gets the texture width. - /// - public int width { get; } - - /// - /// Gets the texture height. - /// - public int height { get; } - - /// - /// Gets the immutable RGBA8 pixels. - /// - public ReadOnlyMemory pixels => m_pixels; -} - -/// -/// Identifies one document event made visible to game code. -/// -public enum UIEventType -{ - /// - /// The target was clicked. - /// - Click, - /// - /// The target value changed. - /// - Change, - /// - /// A form was submitted. - /// - Submit, - /// - /// The target gained focus. - /// - Focus, - /// - /// The target lost focus. - /// - Blur, - /// - /// A pointer entered the target. - /// - MouseEnter, - /// - /// A pointer left the target. - /// - MouseLeave -} - -/// -/// Describes one queued document event after a context update. -/// -public sealed class UIEvent : Event -{ - /// - /// Creates a document event with its source document and target element. - /// - /// - /// The kind of document interaction. - /// - /// - /// The document that produced the event. - /// - /// - /// The target element identifier, which can be empty. - /// - public UIEvent( - UIEventType type, - UIDocumentHandle document, - string targetID - ) { - ArgumentNullException.ThrowIfNull(targetID); - this.type = type; - this.document = document; - this.targetID = targetID; - } - - /// - /// Gets the kind of document interaction. - /// - public UIEventType type { get; } - - /// - /// Gets the source document. - /// - public UIDocumentHandle document { get; } - - /// - /// Gets the target element identifier. - /// - public string targetID { get; } -} - -/// -/// Carries one immutable input snapshot across the UI backend boundary. -/// -public sealed class UIInputSnapshot -{ - /// - /// Creates one backend-neutral UI input snapshot. - /// - /// - /// Pointer position in surface coordinates. - /// - /// - /// Pointer wheel movement. - /// - /// - /// Active keyboard modifiers. - /// - /// - /// Physical keys pressed this frame. - /// - /// - /// Physical keys released this frame. - /// - /// - /// Pointer buttons pressed this frame. - /// - /// - /// Pointer buttons released this frame. - /// - /// - /// Ordered Unicode text commits. - /// - public UIInputSnapshot( - Vector2 mousePosition, - Vector2 scrollDelta, - KeyModifier modifiers, - IReadOnlyCollection keysPressed, - IReadOnlyCollection keysReleased, - IReadOnlyCollection buttonsPressed, - IReadOnlyCollection buttonsReleased, - IReadOnlyList textInput - ) { - ArgumentNullException.ThrowIfNull(keysPressed); - ArgumentNullException.ThrowIfNull(keysReleased); - ArgumentNullException.ThrowIfNull(buttonsPressed); - ArgumentNullException.ThrowIfNull(buttonsReleased); - ArgumentNullException.ThrowIfNull(textInput); - this.mousePosition = mousePosition; - this.scrollDelta = scrollDelta; - this.modifiers = modifiers; - this.keysPressed = keysPressed; - this.keysReleased = keysReleased; - this.buttonsPressed = buttonsPressed; - this.buttonsReleased = buttonsReleased; - this.textInput = textInput; - } - - /// - /// Gets the pointer position. - /// - public Vector2 mousePosition { get; } - - /// - /// Gets pointer wheel movement. - /// - public Vector2 scrollDelta { get; } - - /// - /// Gets active keyboard modifiers. - /// - public KeyModifier modifiers { get; } - - /// - /// Gets physical keys pressed this frame. - /// - public IReadOnlyCollection keysPressed { get; } - - /// - /// Gets physical keys released this frame. - /// - public IReadOnlyCollection keysReleased { get; } - - /// - /// Gets pointer buttons pressed this frame. - /// - public IReadOnlyCollection buttonsPressed { get; } - - /// - /// Gets pointer buttons released this frame. - /// - public IReadOnlyCollection buttonsReleased { get; } - - /// - /// Gets ordered Unicode text commits. - /// - public IReadOnlyList textInput { get; } -} diff --git a/src/services/ui/Inno.UI/UIVertex.cs b/src/services/ui/Inno.UI/UIVertex.cs new file mode 100644 index 000000000..eaed4ff97 --- /dev/null +++ b/src/services/ui/Inno.UI/UIVertex.cs @@ -0,0 +1,27 @@ +namespace Inno.UI; + +/// +/// Describes one vertex in backend-neutral UI draw geometry. +/// +/// +/// The horizontal or first component. +/// +/// +/// The vertical or second component. +/// +/// +/// The float value used to initialize this instance. +/// +/// +/// The concrete value read or transformed by this operation. +/// +/// +/// The uint value used to initialize this instance. +/// +public readonly record struct UIVertex( + float x, + float y, + float u, + float v, + uint color +); diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs new file mode 100644 index 000000000..acf1d606b --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.runtime-dependency-alternate")] +internal sealed class AlternateDependencyAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".depgraph2"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new DependencyAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs index 96b4d162d..b94f12f9e 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AssetLoaderTests.cs @@ -10,8 +10,6 @@ using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Assets; -using Inno.Assets.Pipeline; using Inno.Content; using Inno.Content.Testing; using Inno.Core.Diagnostics; @@ -2540,419 +2538,3 @@ private sealed class TestDiagnosticSink : IDiagnosticSink internal Dictionary reports { get; } = new(StringComparer.Ordinal); } } - -[StableTypeID("501988d0-c069-4dcf-97f6-e899b24e5801")] -internal sealed class PrivateConstructorAsset : AssetObject -{ - [SerializableProperty] - internal string value { get; set; } = string.Empty; -} - -[AssetImporter("inno.tests.private-constructor")] -internal sealed class PrivateConstructorAssetImporter : AssetImporter -{ - private static readonly IReadOnlyList EXTENSIONS = [".privateasset"]; - - private PrivateConstructorAssetImporter() {} - - public override IReadOnlyList supportedExtensions => EXTENSIONS; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new PrivateConstructorAsset { value = context.ReadUtf8Text() }); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeID("8d0d31ab-f9ea-4297-b865-e9014ae82a94")] -internal sealed class DeferredAsset : AssetObject; - -[StableTypeID("79cef88a-3d5a-4c36-8095-a59cae3c641c")] -internal sealed class ExtensionDependentAsset : AssetObject; - -[AssetImporter("tests.extension-dependent")] -internal sealed class ExtensionDependentImporter : AssetImporter -{ - internal static bool available; - internal static int attempts; - public override IReadOnlyList supportedExtensions { get; } = [".extensionasset"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - attempts++; - if (!available) - { - throw new AssetImportExtensionUnavailableException("tests.target", "tests.surface"); - } - output.SetAsset(new ExtensionDependentAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("tests.extension-consumer")] -internal sealed class ExtensionConsumerImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".extensiondependent"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - string source = context.ReadUtf8Text(); - if (Guid.TryParse(source, out Guid id)) - { - _ = context.references.Resolve( - id, - context.services.GetStableTypeID(), - "surface.extensionasset", - typeof(ExtensionDependentAsset), - "$.shader" - ); - } - else - { - _ = context.ResolveDependency(AssetPath.Project(source)); - } - output.SetAsset(new ExtensionDependentAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("inno.tests.deferred")] -internal sealed class DeferredAssetImporter : AssetImporter -{ - private static readonly IReadOnlyList EXTENSIONS = [".deferredasset"]; - - public override IReadOnlyList supportedExtensions => isAvailable ? EXTENSIONS : []; - - internal static bool isAvailable { get; set; } = true; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new DeferredAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeID("a49b603c-0f5f-4861-903a-3819513da002")] -internal sealed class DependencyAsset : AssetObject; - -[AssetImporter("inno.tests.runtime-dependency")] -internal sealed class DependencyAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".depgraph"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - string dependency = context.ReadUtf8Text().Trim(); - if (!string.IsNullOrWhiteSpace(dependency)) - { - output.DependsOnAsset(AssetPath.Parse(dependency)); - } - output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("inno.tests.runtime-dependency-alternate")] -internal sealed class AlternateDependencyAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".depgraph2"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("inno.tests.build-input")] -internal sealed class BuildInputAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".buildinput"]; - public override AssetDeploymentScope deploymentScope => AssetDeploymentScope.AuthoringOnly; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - string text = context.ReadUtf8Text(); - if (text == "failed") - { - throw new InvalidDataException("Required authoring input failed."); - } - if (Guid.TryParse(text, out Guid dependency)) - { - context.DependsOnArtifact(dependency); - } - output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("authoring", context.sourceBytes, cancellationToken, AssetDeploymentScope.AuthoringOnly); - } -} - -[AssetImporter("inno.tests.mixed-scope")] -internal sealed class MixedScopeAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".mixedscope"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new DependencyAsset()); - if (context.ReadUtf8Text() == "authoring") - { - output.SetDeploymentScope(AssetDeploymentScope.AuthoringOnly); - return output.WriteArtifactAsync( - "graph", - context.sourceBytes, - cancellationToken, - AssetDeploymentScope.AuthoringOnly - ); - } - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("inno.tests.build-consumer")] -internal sealed class BuildConsumerAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".buildconsumer"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - context.DependsOnArtifact(Guid.Parse(context.ReadUtf8Text())); - output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeID("a80d363f-8e49-4615-89ee-589613b91c03")] -internal sealed class ImportGraphAsset : AssetObject; - -[AssetImporter("inno.tests.import-dependency")] -internal sealed class ImportGraphAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".importgraph"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - string dependency = context.ReadUtf8Text().Trim(); - if (!string.IsNullOrWhiteSpace(dependency)) - { - output.DependsOnSource(AssetPath.Parse(dependency)); - } - output.SetAsset(new ImportGraphAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeID("490def27-4cdd-48a0-b324-9b7438600404")] -internal sealed class SlowAsset : AssetObject -{ - [SerializableProperty] - internal string value { get; set; } = string.Empty; -} - -[AssetImporter("inno.tests.slow")] -internal sealed class SlowAssetImporter : AssetImporter -{ - internal static readonly ManualResetEventSlim IMPORT_STARTED = new(false); - internal static readonly ManualResetEventSlim ALLOW_IMPORT = new(false); - internal static int importCount; - - public override IReadOnlyList supportedExtensions { get; } = [".slowasset"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - Interlocked.Increment(ref importCount); - IMPORT_STARTED.Set(); - if (!ALLOW_IMPORT.Wait(TimeSpan.FromSeconds(5))) - { - throw new TimeoutException("The slow importer test gate was not released."); - } - output.SetAsset(new SlowAsset { value = context.ReadUtf8Text() }); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } - - internal static void Reset() - { - importCount = 0; - IMPORT_STARTED.Reset(); - ALLOW_IMPORT.Reset(); - } -} - -[StableTypeID("fa17dc36-b9cc-4187-b5da-72906ad00505")] -internal sealed class MutableAsset : AssetObject -{ - [SerializableProperty] - internal string value { get; set; } = string.Empty; -} - -[AssetImporter("inno.tests.mutable")] -internal sealed class MutableAssetImporter : AssetImporter -{ - internal static int attempts; - public override IReadOnlyList supportedExtensions { get; } = [".mutableasset"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - attempts++; - string value = context.ReadUtf8Text(); - if (value == "!invalid!") - { - throw new InvalidDataException("The mutable asset source is invalid."); - } - output.SetAsset(new MutableAsset { value = value }); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } - - protected override ValueTask?> ExportAsync( - AssetExportContext context, - MutableAsset asset, - CancellationToken cancellationToken - ) => ValueTask.FromResult?>(Encoding.UTF8.GetBytes(asset.value)); -} - -[StableTypeID("9f9f5f9f-4d86-414f-9ff9-78ad8ec60606")] -internal sealed class HookAsset : AssetObject -{ - internal int payloadChangeCount; - internal int unloadingCount; - internal int pendingUnloads; - internal bool failUnloading; - internal bool retirementExpired; - - protected override void OnRuntimePayloadChanged( - ReadOnlyMemory previousPayload, - ReadOnlyMemory currentPayload - ) => Interlocked.Increment(ref payloadChangeCount); - - protected override void OnUnloading() - { - Interlocked.Increment(ref unloadingCount); - if (retirementExpired) - { - throw new RetirementTimeoutException("The test asset work exceeded its retirement deadline."); - } - if (pendingUnloads > 0) - { - pendingUnloads--; - throw new RetirementPendingException("The test asset still owns unfinished work."); - } - if (failUnloading) - { - throw new InvalidOperationException("The test asset release failed."); - } - } -} - -[AssetImporter("inno.tests.hook")] -internal sealed class HookAssetImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".hookasset"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new HookAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -internal static class ImporterConflictProbe -{ - internal static bool duplicateExtension; -} - -[StableTypeID("da675da1-9276-40c4-9964-0eb4b8ff9a07")] -internal sealed class ImporterConflictAsset : AssetObject; - -[AssetImporter("inno.tests.conflict-a")] -internal sealed class ImporterConflictAssetImporterA : AssetImporter -{ - public override IReadOnlyList supportedExtensions - => ImporterConflictProbe.duplicateExtension - ? [".conflict"] - : [".probea"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new ImporterConflictAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[AssetImporter("inno.tests.conflict-b")] -internal sealed class ImporterConflictAssetImporterB : AssetImporter -{ - public override IReadOnlyList supportedExtensions - => ImporterConflictProbe.duplicateExtension - ? [".conflict"] - : [".probeb"]; - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new ImporterConflictAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -[StableTypeID("8f87f452-203e-4cd4-9c91-c93af4802141")] -internal sealed class TestBuildDefinitionAsset : AssetObject -{ - [SerializableProperty] - internal string label { get; set; } = string.Empty; -} - -[AssetBuildProcessor("inno.tests.aggregate-build")] -internal sealed class TestBuildProcessor : AssetBuildProcessor -{ - protected override ValueTask BuildAsync( - AssetBuildContext context, - AssetArtifactWriter output, - CancellationToken cancellationToken - ) { - string value = context.definition.label + ":" + context.inputs.Count; - return output.WriteAsync("result", Encoding.UTF8.GetBytes(value), cancellationToken); - } -} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs new file mode 100644 index 000000000..6e86aa37c --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.build-consumer")] +internal sealed class BuildConsumerAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".buildconsumer"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + context.DependsOnArtifact(Guid.Parse(context.ReadUtf8Text())); + output.SetAsset(new DependencyAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs new file mode 100644 index 000000000..d6621f625 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.build-input")] +internal sealed class BuildInputAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".buildinput"]; + public override AssetDeploymentScope deploymentScope => AssetDeploymentScope.AuthoringOnly; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + string text = context.ReadUtf8Text(); + if (text == "failed") + { + throw new InvalidDataException("Required authoring input failed."); + } + if (Guid.TryParse(text, out Guid dependency)) + { + context.DependsOnArtifact(dependency); + } + output.SetAsset(new DependencyAsset()); + return output.WriteArtifactAsync("authoring", context.sourceBytes, cancellationToken, AssetDeploymentScope.AuthoringOnly); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ClipContribution.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ClipContribution.cs new file mode 100644 index 000000000..e4ab0b97a --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ClipContribution.cs @@ -0,0 +1,9 @@ +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline.Tests; + +internal sealed class ClipContribution : ISerializable +{ + [SerializableProperty] + public TextAsset? clip { get; set; } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettings.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettings.cs new file mode 100644 index 000000000..6a266e1f4 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettings.cs @@ -0,0 +1,13 @@ +using System; +using Inno.Core.Settings; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("2c7288db-eb9e-43a5-9894-bf9d10b22a2d")] +[ProjectSettingDefinition("tests.settings.clip")] +internal sealed class ClipSettings : ClipSettingsBase +{ + internal static readonly Guid TYPE_ID = new("2c7288db-eb9e-43a5-9894-bf9d10b22a2d"); + internal static ProjectSettingID id => new("tests.settings.clip"); +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsBase.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsBase.cs new file mode 100644 index 000000000..ae837f583 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsBase.cs @@ -0,0 +1,12 @@ +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline.Tests; + +internal abstract class ClipSettingsBase : ISerializable +{ + [SerializableProperty] + public TextAsset? clip { get; set; } + + [SerializableProperty] + public string[] labels { get; set; } = []; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsComposer.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsComposer.cs new file mode 100644 index 000000000..c43f842b9 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ClipSettingsComposer.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using Inno.Core.Settings; + +namespace Inno.Assets.Pipeline.Tests; + +[ProjectSettingComposer("tests.settings.composed-clip")] +internal sealed class ClipSettingsComposer : ProjectSettingComposer +{ + protected override ClipContribution CaptureContribution( + ComposedClipSettings baseline, + ComposedClipSettings value + ) => new() { clip = value.clip }; + + protected override bool IsEmpty(ClipContribution contribution) => contribution.clip is null; + + protected override void Compose( + ComposedClipSettings target, + IReadOnlyList> contributions + ) { + foreach (ProjectSettingContribution contribution in contributions) + { + target.clip = contribution.value.clip; + } + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ComposedClipSettings.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ComposedClipSettings.cs new file mode 100644 index 000000000..025f6e067 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ComposedClipSettings.cs @@ -0,0 +1,11 @@ +using Inno.Core.Settings; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("cbeec86a-29da-4894-915f-b6239086ee05")] +[ProjectSettingDefinition("tests.settings.composed-clip")] +internal sealed class ComposedClipSettings : ClipSettingsBase +{ + internal static ProjectSettingID id => new("tests.settings.composed-clip"); +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredAsset.cs new file mode 100644 index 000000000..a5f6b2e34 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredAsset.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("bdb3db71-e9cb-4d46-839b-3cbe302c5555")] +internal sealed class ConfiguredAsset : AssetObject +{ + [SerializableProperty] + internal string value { get; set; } = string.Empty; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs new file mode 100644 index 000000000..4385d67af --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Inno.Core.Serialization; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("tests.configured")] +internal sealed class ConfiguredImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".configured"]; + + public override ISerializable CreateImportSettings() => new ConfiguredSettings(); + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + ConfiguredSettings settings = (ConfiguredSettings)context.importSettings!; + if (settings.multiplier < 0) throw new InvalidOperationException("A negative multiplier is invalid."); + string value = $"{settings.multiplier}:{context.ReadUtf8Text()}"; + if (settings.lookup is not null) value += ":" + settings.lookup.content; + output.SetAsset(new ConfiguredAsset { value = value }); + return output.WriteArtifactAsync("runtime", Encoding.UTF8.GetBytes(value), cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredSettings.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredSettings.cs new file mode 100644 index 000000000..7e5a02f82 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredSettings.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("f58eaeea-4bd5-4f3a-a7c0-c5a5414a6bb4")] +internal sealed class ConfiguredSettings : ISerializable +{ + [SerializableProperty] + internal int multiplier { get; set; } = 1; + + [SerializableProperty] + internal TextAsset? lookup { get; set; } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAsset.cs new file mode 100644 index 000000000..4f721ab56 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAsset.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("8d0d31ab-f9ea-4297-b865-e9014ae82a94")] +internal sealed class DeferredAsset : AssetObject; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs new file mode 100644 index 000000000..475168ac8 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.deferred")] +internal sealed class DeferredAssetImporter : AssetImporter +{ + private static readonly IReadOnlyList EXTENSIONS = [".deferredasset"]; + + public override IReadOnlyList supportedExtensions => isAvailable ? EXTENSIONS : []; + + internal static bool isAvailable { get; set; } = true; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new DeferredAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAsset.cs new file mode 100644 index 000000000..16e7c8d3b --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAsset.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("a49b603c-0f5f-4861-903a-3819513da002")] +internal sealed class DependencyAsset : AssetObject; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs new file mode 100644 index 000000000..6132b83c8 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.runtime-dependency")] +internal sealed class DependencyAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".depgraph"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + string dependency = context.ReadUtf8Text().Trim(); + if (!string.IsNullOrWhiteSpace(dependency)) + { + output.DependsOnAsset(AssetPath.Parse(dependency)); + } + output.SetAsset(new DependencyAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs new file mode 100644 index 000000000..248365108 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("tests.extension-consumer")] +internal sealed class ExtensionConsumerImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".extensiondependent"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + string source = context.ReadUtf8Text(); + if (Guid.TryParse(source, out Guid id)) + { + _ = context.references.Resolve( + id, + context.services.GetStableTypeID(), + "surface.extensionasset", + typeof(ExtensionDependentAsset), + "$.shader" + ); + } + else + { + _ = context.ResolveDependency(AssetPath.Project(source)); + } + output.SetAsset(new ExtensionDependentAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentAsset.cs new file mode 100644 index 000000000..214c3c0b8 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentAsset.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("79cef88a-3d5a-4c36-8095-a59cae3c641c")] +internal sealed class ExtensionDependentAsset : AssetObject; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs new file mode 100644 index 000000000..7fc15af59 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("tests.extension-dependent")] +internal sealed class ExtensionDependentImporter : AssetImporter +{ + internal static bool available; + internal static int attempts; + public override IReadOnlyList supportedExtensions { get; } = [".extensionasset"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + attempts++; + if (!available) + { + throw new AssetImportExtensionUnavailableException("tests.target", "tests.surface"); + } + output.SetAsset(new ExtensionDependentAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/HookAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/HookAsset.cs new file mode 100644 index 000000000..a69e57461 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/HookAsset.cs @@ -0,0 +1,39 @@ +using System; +using System.Threading; +using Inno.Core.Execution; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("9f9f5f9f-4d86-414f-9ff9-78ad8ec60606")] +internal sealed class HookAsset : AssetObject +{ + internal int payloadChangeCount; + internal int unloadingCount; + internal int pendingUnloads; + internal bool failUnloading; + internal bool retirementExpired; + + protected override void OnRuntimePayloadChanged( + ReadOnlyMemory previousPayload, + ReadOnlyMemory currentPayload + ) => Interlocked.Increment(ref payloadChangeCount); + + protected override void OnUnloading() + { + Interlocked.Increment(ref unloadingCount); + if (retirementExpired) + { + throw new RetirementTimeoutException("The test asset work exceeded its retirement deadline."); + } + if (pendingUnloads > 0) + { + pendingUnloads--; + throw new RetirementPendingException("The test asset still owns unfinished work."); + } + if (failUnloading) + { + throw new InvalidOperationException("The test asset release failed."); + } + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs new file mode 100644 index 000000000..db44fc682 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.hook")] +internal sealed class HookAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".hookasset"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new HookAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAsset.cs new file mode 100644 index 000000000..45cf43c4c --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAsset.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("a80d363f-8e49-4615-89ee-589613b91c03")] +internal sealed class ImportGraphAsset : AssetObject; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs new file mode 100644 index 000000000..e537b8f3b --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.import-dependency")] +internal sealed class ImportGraphAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".importgraph"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + string dependency = context.ReadUtf8Text().Trim(); + if (!string.IsNullOrWhiteSpace(dependency)) + { + output.DependsOnSource(AssetPath.Parse(dependency)); + } + output.SetAsset(new ImportGraphAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs index d55a9cd6a..ab88cf065 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImportSettingsTests.cs @@ -1,13 +1,8 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Text; -using System.Threading; -using System.Threading.Tasks; using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Assets; using Inno.Core.Diagnostics; using Inno.Core.Identity; using Inno.Core.Logging; @@ -217,41 +212,3 @@ internal AssetLoader CreateReadOnlyLoader(AssetSourceID id) ); } } - -[StableTypeID("f58eaeea-4bd5-4f3a-a7c0-c5a5414a6bb4")] -internal sealed class ConfiguredSettings : ISerializable -{ - [SerializableProperty] - internal int multiplier { get; set; } = 1; - - [SerializableProperty] - internal TextAsset? lookup { get; set; } -} - -[StableTypeID("bdb3db71-e9cb-4d46-839b-3cbe302c5555")] -internal sealed class ConfiguredAsset : AssetObject -{ - [SerializableProperty] - internal string value { get; set; } = string.Empty; -} - -[AssetImporter("tests.configured")] -internal sealed class ConfiguredImporter : AssetImporter -{ - public override IReadOnlyList supportedExtensions { get; } = [".configured"]; - - public override ISerializable CreateImportSettings() => new ConfiguredSettings(); - - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - ConfiguredSettings settings = (ConfiguredSettings)context.importSettings!; - if (settings.multiplier < 0) throw new InvalidOperationException("A negative multiplier is invalid."); - string value = $"{settings.multiplier}:{context.ReadUtf8Text()}"; - if (settings.lookup is not null) value += ":" + settings.lookup.content; - output.SetAsset(new ConfiguredAsset { value = value }); - return output.WriteArtifactAsync("runtime", Encoding.UTF8.GetBytes(value), cancellationToken); - } -} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAsset.cs new file mode 100644 index 000000000..faa294416 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAsset.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("da675da1-9276-40c4-9964-0eb4b8ff9a07")] +internal sealed class ImporterConflictAsset : AssetObject; diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs new file mode 100644 index 000000000..61bde289b --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.conflict-a")] +internal sealed class ImporterConflictAssetImporterA : AssetImporter +{ + public override IReadOnlyList supportedExtensions + => ImporterConflictProbe.duplicateExtension + ? [".conflict"] + : [".probea"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new ImporterConflictAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs new file mode 100644 index 000000000..f7ee339cf --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.conflict-b")] +internal sealed class ImporterConflictAssetImporterB : AssetImporter +{ + public override IReadOnlyList supportedExtensions + => ImporterConflictProbe.duplicateExtension + ? [".conflict"] + : [".probeb"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new ImporterConflictAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictProbe.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictProbe.cs new file mode 100644 index 000000000..9efe43087 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictProbe.cs @@ -0,0 +1,6 @@ +namespace Inno.Assets.Pipeline.Tests; + +internal static class ImporterConflictProbe +{ + internal static bool duplicateExtension; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs new file mode 100644 index 000000000..225867daa --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.mixed-scope")] +internal sealed class MixedScopeAssetImporter : AssetImporter +{ + public override IReadOnlyList supportedExtensions { get; } = [".mixedscope"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new DependencyAsset()); + if (context.ReadUtf8Text() == "authoring") + { + output.SetDeploymentScope(AssetDeploymentScope.AuthoringOnly); + return output.WriteArtifactAsync( + "graph", + context.sourceBytes, + cancellationToken, + AssetDeploymentScope.AuthoringOnly + ); + } + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/MutableAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/MutableAsset.cs new file mode 100644 index 000000000..8d7e28148 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/MutableAsset.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("fa17dc36-b9cc-4187-b5da-72906ad00505")] +internal sealed class MutableAsset : AssetObject +{ + [SerializableProperty] + internal string value { get; set; } = string.Empty; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs new file mode 100644 index 000000000..2774ffe43 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.mutable")] +internal sealed class MutableAssetImporter : AssetImporter +{ + internal static int attempts; + public override IReadOnlyList supportedExtensions { get; } = [".mutableasset"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + attempts++; + string value = context.ReadUtf8Text(); + if (value == "!invalid!") + { + throw new InvalidDataException("The mutable asset source is invalid."); + } + output.SetAsset(new MutableAsset { value = value }); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } + + protected override ValueTask?> ExportAsync( + AssetExportContext context, + MutableAsset asset, + CancellationToken cancellationToken + ) => ValueTask.FromResult?>(Encoding.UTF8.GetBytes(asset.value)); +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAsset.cs new file mode 100644 index 000000000..483dcf434 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAsset.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("501988d0-c069-4dcf-97f6-e899b24e5801")] +internal sealed class PrivateConstructorAsset : AssetObject +{ + [SerializableProperty] + internal string value { get; set; } = string.Empty; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs new file mode 100644 index 000000000..c0b1542b4 --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.private-constructor")] +internal sealed class PrivateConstructorAssetImporter : AssetImporter +{ + private static readonly IReadOnlyList EXTENSIONS = [".privateasset"]; + + private PrivateConstructorAssetImporter() {} + + public override IReadOnlyList supportedExtensions => EXTENSIONS; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new PrivateConstructorAsset { value = context.ReadUtf8Text() }); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs b/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs index bde2a8f32..96d9b9529 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/SettingsReferenceTests.cs @@ -1,12 +1,9 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Assets; -using Inno.Assets.Pipeline; using Inno.Content; using Inno.Content.Testing; using Inno.Core.Diagnostics; @@ -247,54 +244,3 @@ public void Dispose() internal ProjectSettingsStore settings { get; } } } - -internal abstract class ClipSettingsBase : ISerializable -{ - [SerializableProperty] - public TextAsset? clip { get; set; } - - [SerializableProperty] - public string[] labels { get; set; } = []; -} - -[StableTypeID("2c7288db-eb9e-43a5-9894-bf9d10b22a2d")] -[ProjectSettingDefinition("tests.settings.clip")] -internal sealed class ClipSettings : ClipSettingsBase -{ - internal static readonly Guid TYPE_ID = new("2c7288db-eb9e-43a5-9894-bf9d10b22a2d"); - internal static ProjectSettingID id => new("tests.settings.clip"); -} - -[StableTypeID("cbeec86a-29da-4894-915f-b6239086ee05")] -[ProjectSettingDefinition("tests.settings.composed-clip")] -internal sealed class ComposedClipSettings : ClipSettingsBase -{ - internal static ProjectSettingID id => new("tests.settings.composed-clip"); -} - -internal sealed class ClipContribution : ISerializable -{ - [SerializableProperty] - public TextAsset? clip { get; set; } -} - -[ProjectSettingComposer("tests.settings.composed-clip")] -internal sealed class ClipSettingsComposer : ProjectSettingComposer -{ - protected override ClipContribution CaptureContribution( - ComposedClipSettings baseline, - ComposedClipSettings value - ) => new() { clip = value.clip }; - - protected override bool IsEmpty(ClipContribution contribution) => contribution.clip is null; - - protected override void Compose( - ComposedClipSettings target, - IReadOnlyList> contributions - ) { - foreach (ProjectSettingContribution contribution in contributions) - { - target.clip = contribution.value.clip; - } - } -} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/SlowAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/SlowAsset.cs new file mode 100644 index 000000000..36144d3cf --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/SlowAsset.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("490def27-4cdd-48a0-b324-9b7438600404")] +internal sealed class SlowAsset : AssetObject +{ + [SerializableProperty] + internal string value { get; set; } = string.Empty; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs new file mode 100644 index 000000000..6bbd4f73b --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetImporter("inno.tests.slow")] +internal sealed class SlowAssetImporter : AssetImporter +{ + internal static readonly ManualResetEventSlim IMPORT_STARTED = new(false); + internal static readonly ManualResetEventSlim ALLOW_IMPORT = new(false); + internal static int importCount; + + public override IReadOnlyList supportedExtensions { get; } = [".slowasset"]; + + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + Interlocked.Increment(ref importCount); + IMPORT_STARTED.Set(); + if (!ALLOW_IMPORT.Wait(TimeSpan.FromSeconds(5))) + { + throw new TimeoutException("The slow importer test gate was not released."); + } + output.SetAsset(new SlowAsset { value = context.ReadUtf8Text() }); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } + + internal static void Reset() + { + importCount = 0; + IMPORT_STARTED.Reset(); + ALLOW_IMPORT.Reset(); + } +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildDefinitionAsset.cs b/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildDefinitionAsset.cs new file mode 100644 index 000000000..7fc23c3dc --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildDefinitionAsset.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.Tests; + +[StableTypeID("8f87f452-203e-4cd4-9c91-c93af4802141")] +internal sealed class TestBuildDefinitionAsset : AssetObject +{ + [SerializableProperty] + internal string label { get; set; } = string.Empty; +} diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs b/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs new file mode 100644 index 000000000..b46d3baea --- /dev/null +++ b/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs @@ -0,0 +1,18 @@ +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.Tests; + +[AssetBuildProcessor("inno.tests.aggregate-build")] +internal sealed class TestBuildProcessor : AssetBuildProcessor +{ + protected override ValueTask BuildAsync( + AssetBuildContext context, + AssetArtifactWriter output, + CancellationToken cancellationToken + ) { + string value = context.definition.label + ":" + context.inputs.Count; + return output.WriteAsync("result", Encoding.UTF8.GetBytes(value), cancellationToken); + } +} diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs new file mode 100644 index 000000000..6ccdf98a8 --- /dev/null +++ b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.DuplicateImporterFixture; + +/// +/// Deliberately shares its importer identity with to test candidate rejection. +/// +[AssetImporter("inno.tests.duplicate-importer")] +public sealed class DuplicateImporterA : AssetImporter +{ + /// + /// Gets this fixture's extension; distinct extensions do not make duplicate importer identities valid. + /// + public override IReadOnlyList supportedExtensions { get; } = [".duplicateid"]; + + /// + /// Supplies a fixture asset and writes the source bytes as its runtime artifact through the borrowed writer. + /// + /// + /// The current source snapshot owned by the import operation. + /// + /// + /// The borrowed writer receiving the candidate asset and artifact. + /// + /// + /// Cancels the artifact write without publishing a complete candidate. + /// + /// + /// The artifact write operation, preserving its failure or cancellation. + /// + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new DuplicateImporterAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterAsset.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterAsset.cs new file mode 100644 index 000000000..d53e42c4c --- /dev/null +++ b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterAsset.cs @@ -0,0 +1,9 @@ +using Inno.Extensibility.Types; + +namespace Inno.Assets.Pipeline.DuplicateImporterFixture; + +/// +/// Supplies a stable, field-free asset for conflicting importer registration fixtures. +/// +[StableTypeID("27a0c796-5e7b-4e65-b9e5-2a0ced76675c")] +public sealed class DuplicateImporterAsset : AssetObject; diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs new file mode 100644 index 000000000..f9b9bc40f --- /dev/null +++ b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Inno.Assets.Pipeline.DuplicateImporterFixture; + +/// +/// Deliberately conflicts with despite using a different file extension. +/// +[AssetImporter("inno.tests.duplicate-importer")] +public sealed class DuplicateImporterB : AssetImporter +{ + /// + /// Gets the alternate extension used to prove identity conflicts are independent of extension selection. + /// + public override IReadOnlyList supportedExtensions { get; } = [".duplicateid-b"]; + + /// + /// Supplies a fixture asset and writes the source bytes as its runtime artifact through the borrowed writer. + /// + /// + /// The current source snapshot owned by the import operation. + /// + /// + /// The borrowed writer receiving the candidate asset and artifact. + /// + /// + /// Cancels the artifact write without publishing a complete candidate. + /// + /// + /// The artifact write operation, preserving its failure or cancellation. + /// + protected override ValueTask ImportAsync( + AssetImportContext context, + AssetImportWriter output, + CancellationToken cancellationToken + ) { + output.SetAsset(new DuplicateImporterAsset()); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + } +} diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs deleted file mode 100644 index 78a2fdb93..000000000 --- a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporters.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Inno.Assets; -using Inno.Assets.Pipeline; -using Inno.Extensibility.Types; - -namespace Inno.Assets.Pipeline.DuplicateImporterFixture; - -/// -/// Supplies a stable, field-free asset for conflicting importer registration fixtures. -/// -[StableTypeID("27a0c796-5e7b-4e65-b9e5-2a0ced76675c")] -public sealed class DuplicateImporterAsset : AssetObject; - -/// -/// Deliberately shares its importer identity with to test candidate rejection. -/// -[AssetImporter("inno.tests.duplicate-importer")] -public sealed class DuplicateImporterA : AssetImporter -{ - /// - /// Gets this fixture's extension; distinct extensions do not make duplicate importer identities valid. - /// - public override IReadOnlyList supportedExtensions { get; } = [".duplicateid"]; - - /// - /// Supplies a fixture asset and writes the source bytes as its runtime artifact through the borrowed writer. - /// - /// - /// The current source snapshot owned by the import operation. - /// - /// - /// The borrowed writer receiving the candidate asset and artifact. - /// - /// - /// Cancels the artifact write without publishing a complete candidate. - /// - /// - /// The artifact write operation, preserving its failure or cancellation. - /// - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new DuplicateImporterAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} - -/// -/// Deliberately conflicts with despite using a different file extension. -/// -[AssetImporter("inno.tests.duplicate-importer")] -public sealed class DuplicateImporterB : AssetImporter -{ - /// - /// Gets the alternate extension used to prove identity conflicts are independent of extension selection. - /// - public override IReadOnlyList supportedExtensions { get; } = [".duplicateid-b"]; - - /// - /// Supplies a fixture asset and writes the source bytes as its runtime artifact through the borrowed writer. - /// - /// - /// The current source snapshot owned by the import operation. - /// - /// - /// The borrowed writer receiving the candidate asset and artifact. - /// - /// - /// Cancels the artifact write without publishing a complete candidate. - /// - /// - /// The artifact write operation, preserving its failure or cancellation. - /// - protected override ValueTask ImportAsync( - AssetImportContext context, - AssetImportWriter output, - CancellationToken cancellationToken - ) { - output.SetAsset(new DuplicateImporterAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); - } -} diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceCollection.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceCollection.cs new file mode 100644 index 000000000..8d085e9ec --- /dev/null +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceCollection.cs @@ -0,0 +1,9 @@ +using Xunit; + +namespace Inno.Adapter.Rendering.Bgfx.Tests; + +[CollectionDefinition(C_NAME, DisableParallelization = true)] +public sealed class BgfxDeviceCollection : ICollectionFixture +{ + public const string C_NAME = "BGFX device"; +} diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceFixture.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceFixture.cs new file mode 100644 index 000000000..7172e57ae --- /dev/null +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceFixture.cs @@ -0,0 +1,28 @@ +using System; +using Inno.Rendering; + +namespace Inno.Adapter.Rendering.Bgfx.Tests; + +public sealed class BgfxDeviceFixture : IDisposable +{ + public BgfxDeviceFixture() + { + this.device = CreateDevice(); + } + + public BgfxDevice device { get; } + + public void Dispose() => device.Dispose(); + + private static BgfxDevice CreateDevice() + => new(new BgfxDeviceOptions + { + preferredBackend = GraphicsApi.noop, + backbufferWidth = 1, + backbufferHeight = 1, + verticalSync = false, + sRgbBackbuffer = false, + forceSingleThreaded = true, + deferredDestroyFrames = 2 + }); +} diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs index 284048404..7515a2382 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxDeviceTests.cs @@ -1,7 +1,6 @@ using System; using Xunit; using Inno.Adapter.Platform; -using Inno.Platform; using Inno.Rendering; namespace Inno.Adapter.Rendering.Bgfx.Tests; @@ -436,33 +435,3 @@ private CompiledRenderGraph BuildColorTargetGraph( return builder.Compile().graph!; } } - -[CollectionDefinition(C_NAME, DisableParallelization = true)] -public sealed class BgfxDeviceCollection : ICollectionFixture -{ - public const string C_NAME = "BGFX device"; -} - -public sealed class BgfxDeviceFixture : IDisposable -{ - public BgfxDeviceFixture() - { - this.device = CreateDevice(); - } - - public BgfxDevice device { get; } - - public void Dispose() => device.Dispose(); - - private static BgfxDevice CreateDevice() - => new(new BgfxDeviceOptions - { - preferredBackend = GraphicsApi.noop, - backbufferWidth = 1, - backbufferHeight = 1, - verticalSync = false, - sRgbBackbuffer = false, - forceSingleThreaded = true, - deferredDestroyFrames = 2 - }); -} diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs index 4311da835..18596ce1d 100644 --- a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/BgfxSurfaceRetirementTests.cs @@ -155,6 +155,3 @@ BgfxSurfaceRole role ) => default; } } - -[CollectionDefinition("Windowed BGFX", DisableParallelization = true)] -public sealed class WindowedBgfxCollection; diff --git a/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/WindowedBgfxCollection.cs b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/WindowedBgfxCollection.cs new file mode 100644 index 000000000..9741bddf4 --- /dev/null +++ b/tests/backends/Bgfx/Inno.Adapter.Rendering.Bgfx.Tests/WindowedBgfxCollection.cs @@ -0,0 +1,6 @@ +using Xunit; + +namespace Inno.Adapter.Rendering.Bgfx.Tests; + +[CollectionDefinition("Windowed BGFX", DisableParallelization = true)] +public sealed class WindowedBgfxCollection; diff --git a/tests/core/Inno.Core.Diagnostics.Tests/DiagnoseCollection.cs b/tests/core/Inno.Core.Diagnostics.Tests/DiagnoseCollection.cs new file mode 100644 index 000000000..e13aeb1de --- /dev/null +++ b/tests/core/Inno.Core.Diagnostics.Tests/DiagnoseCollection.cs @@ -0,0 +1,6 @@ +using Xunit; + +namespace Inno.Core.Diagnostics.Tests; + +[CollectionDefinition("Diagnose", DisableParallelization = true)] +public sealed class DiagnoseCollection; diff --git a/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs b/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs index ea705a95f..ec7cbeb27 100644 --- a/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs +++ b/tests/core/Inno.Core.Diagnostics.Tests/DiagnosticHubTests.cs @@ -2,13 +2,9 @@ using System.Collections.Generic; using System.Linq; using Xunit; -using Inno.Core.Diagnostics; namespace Inno.Core.Diagnostics.Tests; -[CollectionDefinition("Diagnose", DisableParallelization = true)] -public sealed class DiagnoseCollection; - [Collection("Diagnose")] public sealed class DiagnosticHubTests : IDisposable { diff --git a/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs b/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs index 1081fcd8a..682c4f978 100644 --- a/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs +++ b/tests/core/Inno.Core.Logging.Tests/LoggingBehaviorTests.cs @@ -6,14 +6,10 @@ using System.Threading; using System.Threading.Tasks; using Xunit; -using Inno.Core.Logging; using Inno.Extensibility.Modules; namespace Inno.Core.Logging.Tests; -[CollectionDefinition("Logging", DisableParallelization = true)] -public sealed class LoggingCollection; - [Collection("Logging")] public sealed class LoggingBehaviorTests : IDisposable { diff --git a/tests/core/Inno.Core.Logging.Tests/LoggingCollection.cs b/tests/core/Inno.Core.Logging.Tests/LoggingCollection.cs new file mode 100644 index 000000000..a2b50da37 --- /dev/null +++ b/tests/core/Inno.Core.Logging.Tests/LoggingCollection.cs @@ -0,0 +1,6 @@ +using Xunit; + +namespace Inno.Core.Logging.Tests; + +[CollectionDefinition("Logging", DisableParallelization = true)] +public sealed class LoggingCollection; diff --git a/tests/core/Inno.Core.Serialization.Tests/AmbiguousHost.cs b/tests/core/Inno.Core.Serialization.Tests/AmbiguousHost.cs new file mode 100644 index 000000000..9a13ea1b4 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/AmbiguousHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class AmbiguousHost : ISerializable +{ + [SerializableProperty] + public AmbiguousValue? item { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/AmbiguousLeftConverter.cs b/tests/core/Inno.Core.Serialization.Tests/AmbiguousLeftConverter.cs new file mode 100644 index 000000000..235d9d45a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/AmbiguousLeftConverter.cs @@ -0,0 +1,13 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class AmbiguousLeftConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + IAmbiguousLeft value + ) {} + + public override IAmbiguousLeft Read(SerializationReader reader) => new AmbiguousValue(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/AmbiguousRightConverter.cs b/tests/core/Inno.Core.Serialization.Tests/AmbiguousRightConverter.cs new file mode 100644 index 000000000..647501ee1 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/AmbiguousRightConverter.cs @@ -0,0 +1,13 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class AmbiguousRightConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + IAmbiguousRight value + ) {} + + public override IAmbiguousRight Read(SerializationReader reader) => new AmbiguousValue(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/AmbiguousValue.cs b/tests/core/Inno.Core.Serialization.Tests/AmbiguousValue.cs new file mode 100644 index 000000000..a53579454 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/AmbiguousValue.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class AmbiguousValue : IAmbiguousLeft, IAmbiguousRight; diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRoot.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRoot.cs new file mode 100644 index 000000000..552f87b66 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRoot.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureArrayRoot : ISerializable +{ + internal List rows = []; + internal Guid scope = Guid.NewGuid(); + internal int mode; + internal int keys; + internal bool allowKeys = true; + internal bool stateful; + internal bool failKey; + internal Action? onWrite; + internal SerializationCaptureKeyBuilder? savedBuilder; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRootConverter.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRootConverter.cs new file mode 100644 index 000000000..5c85f74c8 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRootConverter.cs @@ -0,0 +1,54 @@ +using System; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureArrayRootConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + CaptureArrayRoot value + ) { + writer.Write("scope", value.scope); + writer.WriteObjectArray( + "rows", + value.rows, + ( + child, + row + ) => + { + row.writes++; + value.onWrite?.Invoke(); + child.Write("number", row.number); + child.Write("mode", value.mode); + if (value.stateful) + { + child.WritePropertiesData("state", row.state); + } + }, + captureKey: ( + row, + key + ) => + { + value.keys++; + value.savedBuilder = key; + if (value.failKey) + { + throw new InvalidOperationException("Array key failure."); + } + if (!value.allowKeys || !key.TryAddOwner(row, row.revision)) + { + return false; + } + key.AddValue(value.scope); + key.AddValue(unchecked((ulong)value.mode)); + key.AddValue(value.stateful ? 1UL : 0UL); + return true; + } + ); + } + + public override CaptureArrayRoot Read(SerializationReader reader) => throw new NotSupportedException(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRow.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRow.cs new file mode 100644 index 000000000..3f26c0ec5 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureArrayRow.cs @@ -0,0 +1,11 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureArrayRow : IdentityObject, ISerializable +{ + internal int number; + internal int writes; + internal ulong? revision = 0; + internal ConvertedCaptureProperties state = new(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRoot.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRoot.cs new file mode 100644 index 000000000..88b87fa58 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRoot.cs @@ -0,0 +1,8 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureBlobRoot : IdentityObject, ISerializable +{ + internal byte[] data = []; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRootConverter.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRootConverter.cs new file mode 100644 index 000000000..541dbe9db --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureBlobRootConverter.cs @@ -0,0 +1,19 @@ +using System; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureBlobRootConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + CaptureBlobRoot value + ) => writer.Write("data", value.data); + + public override CaptureBlobRoot Read(SerializationReader reader) => throw new NotSupportedException(); + + protected override bool TryCaptureKey( + CaptureBlobRoot value, + SerializationCaptureKeyBuilder key + ) => key.TryAddOwner(value, 0); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValue.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValue.cs new file mode 100644 index 000000000..39632e4c2 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValue.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal struct CaptureConvertedValue +{ + public int number; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValueConverter.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValueConverter.cs new file mode 100644 index 000000000..310a6c7c8 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureConvertedValueConverter.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureConvertedValueConverter : SerializationConverter +{ + internal static readonly List EVENTS = []; + internal static int calls; + + public CaptureConvertedValueConverter() + { + EVENTS.Add("construct"); + } + + public override void Write( + SerializationWriter writer, + CaptureConvertedValue value + ) { + EVENTS.Add("convert-write"); + writer.Write("number", value.number); + writer.Write("call", ++calls); + } + + public override CaptureConvertedValue Read(SerializationReader reader) => new() { number = reader.Read("number") }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureGetterStruct.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureGetterStruct.cs new file mode 100644 index 000000000..c2f128d37 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureGetterStruct.cs @@ -0,0 +1,16 @@ +namespace Inno.Core.Serialization.Tests; + +internal struct CaptureGetterStruct +{ + internal static int calls; + + public int value + { + get + { + calls++; + return 1; + } + set {} + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureKeyContext.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyContext.cs new file mode 100644 index 000000000..74a6cf4dc --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyContext.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureKeyContext +{ + internal ulong value; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRoot.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRoot.cs new file mode 100644 index 000000000..3583cf951 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRoot.cs @@ -0,0 +1,24 @@ +using System; +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureKeyRoot : IdentityObject, ISerializable +{ + internal ulong? revision = 0; + internal int number; + internal string? text; + internal bool allowKey = true; + internal bool ignoreDecline; + internal bool failKey; + internal bool failWrite; + internal int writeCalls; + internal int keyCalls; + internal ISerializable? properties; + internal CaptureConvertedValue? converted; + internal Action? onWrite; + internal Action? onKey; + internal SerializationCaptureKeyBuilder? savedBuilder; + + internal void Touch() => revision++; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRootConverter.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRootConverter.cs new file mode 100644 index 000000000..5331f7a2d --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureKeyRootConverter.cs @@ -0,0 +1,57 @@ +using System; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CaptureKeyRootConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + CaptureKeyRoot value + ) { + value.writeCalls++; + value.onWrite?.Invoke(); + if (value.failWrite) + { + throw new InvalidOperationException("Capture writer failure."); + } + writer.Write("number", value.number); + writer.Write("text", value.text); + writer.Write("context", writer.context.TryGet(out CaptureKeyContext? context) ? context!.value : 0UL); + if (value.properties is not null) + { + writer.WritePropertiesData("properties", value.properties); + } + if (value.converted.HasValue) + { + writer.Write("converted", value.converted.Value); + } + } + + public override CaptureKeyRoot Read(SerializationReader reader) => throw new NotSupportedException(); + + protected override bool TryCaptureKey( + CaptureKeyRoot value, + SerializationCaptureKeyBuilder key + ) { + value.keyCalls++; + value.savedBuilder = key; + if (value.failKey) + { + throw new InvalidOperationException("Capture key failure."); + } + if (!value.allowKey) + { + return false; + } + key.EnsureCapacity(5); + bool complete = key.TryAddOwner(value, value.revision); + key.AddValue(key.context.TryGet(out CaptureKeyContext? context) ? context!.value : 0UL); + if (value.properties is not null) + { + complete &= key.TryAddProperties(value.properties); + } + value.onKey?.Invoke(key); + return complete || value.ignoreDecline; + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CapturePropertyLoadContext.cs b/tests/core/Inno.Core.Serialization.Tests/CapturePropertyLoadContext.cs new file mode 100644 index 000000000..f290780b6 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CapturePropertyLoadContext.cs @@ -0,0 +1,11 @@ +using System.Linq; +using System.Reflection; +using System.Runtime.Loader; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CapturePropertyLoadContext() : AssemblyLoadContext(isCollectible: true) +{ + protected override Assembly? Load(AssemblyName name) + => Default.Assemblies.FirstOrDefault(assembly => assembly.GetName().Name == name.Name); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CaptureRevisionProperties.cs b/tests/core/Inno.Core.Serialization.Tests/CaptureRevisionProperties.cs new file mode 100644 index 000000000..c994ab8fd --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CaptureRevisionProperties.cs @@ -0,0 +1,35 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +/// +/// Provides a real public extension type for collectible metadata and capture-key acceptance. +/// +[SerializationRevision("m_revision")] +public sealed class CaptureRevisionProperties : IdentityObject, ISerializable +{ + private ulong? m_revision = 0; + private int m_number; + + /// + /// Creates an initially empty tracked property source. + /// + public CaptureRevisionProperties() {} + + /// + /// Gets or sets the serialized number, advancing its complete source-owned revision before mutation. + /// + [SerializableProperty] + public int number + { + get => m_number; + set + { + if (m_revision is { } revision) + { + m_revision = revision == ulong.MaxValue ? null : revision + 1; + } + m_number = value; + } + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureConverter.cs new file mode 100644 index 000000000..23c85fa8f --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureConverter.cs @@ -0,0 +1,31 @@ +using System; +using System.Threading; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConcurrentCaptureConverter : SerializationConverter, IDisposable +{ + internal static int constructions; + internal static int disposals; + + /// + /// Records construction of the converter owned by the captured generation. + /// + public ConcurrentCaptureConverter() + { + Interlocked.Increment(ref constructions); + } + + /// + public override void Write( + SerializationWriter writer, + ConcurrentCaptureValue value + ) => writer.Write("count", value.count); + + /// + public override ConcurrentCaptureValue Read(SerializationReader reader) => new(reader.Read("count")); + + /// + public void Dispose() => Interlocked.Increment(ref disposals); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureValue.cs b/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureValue.cs new file mode 100644 index 000000000..eb253d7c9 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConcurrentCaptureValue.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConcurrentCaptureValue(int count) : ISerializable +{ + internal int count { get; } = count; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedCaptureProperties.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedCaptureProperties.cs new file mode 100644 index 000000000..cfbb185e9 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedCaptureProperties.cs @@ -0,0 +1,12 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +[SerializationRevision("revision")] +internal sealed class ConvertedCaptureProperties : IdentityObject, ISerializable +{ + [SerializableProperty] + public CaptureConvertedValue value = new() { number = 1 }; + + private ulong? revision => 0; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedChild.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedChild.cs new file mode 100644 index 000000000..9aa7414a3 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedChild.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedChild +{ + public int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedChildConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedChildConverter.cs new file mode 100644 index 000000000..c7d072d9b --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedChildConverter.cs @@ -0,0 +1,13 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedChildConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + ConvertedChild value + ) => writer.Write("value", value.value); + + public override ConvertedChild Read(SerializationReader reader) => new() { value = reader.Read("value") }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedChildHost.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedChildHost.cs new file mode 100644 index 000000000..61aaae947 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedChildHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedChildHost : ISerializable +{ + [SerializableProperty] + public ConvertedChild? child { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSample.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSample.cs new file mode 100644 index 000000000..0efe296ff --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSample.cs @@ -0,0 +1,11 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedConstructorSample : ISerializable +{ + public ConvertedConstructorSample(int value) + { + this.value = value; + } + + public int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSampleConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSampleConverter.cs new file mode 100644 index 000000000..cbdc1ad40 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedConstructorSampleConverter.cs @@ -0,0 +1,18 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedConstructorSampleConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + ConvertedConstructorSample value + ) => writer.Write("value", value.value); + + public override ConvertedConstructorSample Read(SerializationReader reader) => new(reader.Read("value")); + + public override void Restore( + SerializationReader reader, + ConvertedConstructorSample target + ) => target.value = reader.Read("value"); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSample.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSample.cs new file mode 100644 index 000000000..8ee0188b0 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSample.cs @@ -0,0 +1,10 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedHookSample : ISerializable +{ + public int value { get; set; } + public int hookCount { get; private set; } + + [OnSerializableRestored] + private void AfterRestore() => hookCount++; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSampleConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSampleConverter.cs new file mode 100644 index 000000000..782878178 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ConvertedHookSampleConverter.cs @@ -0,0 +1,18 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ConvertedHookSampleConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + ConvertedHookSample value + ) => writer.Write("value", value.value); + + public override ConvertedHookSample Read(SerializationReader reader) => new() { value = reader.Read("value") }; + + public override void Restore( + SerializationReader reader, + ConvertedHookSample target + ) => target.value = reader.Read("value"); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CurrentSchemaSample.cs b/tests/core/Inno.Core.Serialization.Tests/CurrentSchemaSample.cs new file mode 100644 index 000000000..0b2e9b980 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CurrentSchemaSample.cs @@ -0,0 +1,18 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class CurrentSchemaSample : ISerializable +{ + [SerializableProperty] + public string changed { get; set; } = "default"; + + [SerializableProperty(PropertyVisibility.Hide)] + public string compatible { get; set; } = "new"; + + [SerializableProperty] + public int added { get; set; } = 17; + + public int restoreCount { get; private set; } + + [OnSerializableRestored] + private void AfterRestore() => restoreCount++; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CycleHost.cs b/tests/core/Inno.Core.Serialization.Tests/CycleHost.cs new file mode 100644 index 000000000..c63087173 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CycleHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class CycleHost : ISerializable +{ + [SerializableProperty] + public CycleValue? value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CycleValue.cs b/tests/core/Inno.Core.Serialization.Tests/CycleValue.cs new file mode 100644 index 000000000..0fd0d250a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CycleValue.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class CycleValue +{ + public CycleValue? next { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/CycleValueConverter.cs b/tests/core/Inno.Core.Serialization.Tests/CycleValueConverter.cs new file mode 100644 index 000000000..13068a4c5 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/CycleValueConverter.cs @@ -0,0 +1,13 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class CycleValueConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + CycleValue value + ) => writer.Write("next", value.next); + + public override CycleValue Read(SerializationReader reader) => new() { next = reader.Read("next") }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/DefaultSample.cs b/tests/core/Inno.Core.Serialization.Tests/DefaultSample.cs new file mode 100644 index 000000000..895302612 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/DefaultSample.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class DefaultSample : ISerializable +{ + [SerializableProperty] + public bool enabled { get; set; } + + [SerializableProperty] + public int count { get; set; } + + [SerializableProperty] + public float ratio { get; set; } + + [SerializableProperty] + public decimal price { get; set; } + + [SerializableProperty] + public string name { get; set; } = string.Empty; + + [SerializableProperty] + public Guid identity { get; set; } + + [SerializableProperty] + public SampleMode mode { get; set; } + + [SerializableProperty] + public int? optional { get; set; } + + [SerializableProperty] + public byte[] bytes { get; set; } = []; + + [SerializableProperty] + public int[] numbers { get; set; } = []; + + [SerializableProperty] + public List values { get; set; } = []; + + [SerializableProperty] + public Dictionary map { get; set; } = []; + + [SerializableProperty] + public StructSample data { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyBaseSample.cs b/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyBaseSample.cs new file mode 100644 index 000000000..a153c7f34 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyBaseSample.cs @@ -0,0 +1,8 @@ +namespace Inno.Core.Serialization.Tests; + +// Open: DuplicateKeyDerivedSample derives from it. +internal class DuplicateKeyBaseSample : ISerializable +{ + [SerializableProperty] + public int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyDerivedSample.cs b/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyDerivedSample.cs new file mode 100644 index 000000000..58a2e4637 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/DuplicateKeyDerivedSample.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class DuplicateKeyDerivedSample : DuplicateKeyBaseSample +{ + [SerializableProperty] + public new int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ExactBase.cs b/tests/core/Inno.Core.Serialization.Tests/ExactBase.cs new file mode 100644 index 000000000..1cff88419 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ExactBase.cs @@ -0,0 +1,8 @@ +namespace Inno.Core.Serialization.Tests; + +// Open: ExactLeaf derives from it for the converter-selection tests. +internal class ExactBase +{ + public int value { get; set; } + public string selectedBy { get; set; } = string.Empty; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ExactBaseConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ExactBaseConverter.cs new file mode 100644 index 000000000..b301a253c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ExactBaseConverter.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ExactBaseConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + ExactBase value + ) => writer.Write("value", value.value); + + public override ExactBase Read(SerializationReader reader) + => new ExactLeaf { value = reader.Read("value"), selectedBy = "base" }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ExactHost.cs b/tests/core/Inno.Core.Serialization.Tests/ExactHost.cs new file mode 100644 index 000000000..71fdf585d --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ExactHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ExactHost : ISerializable +{ + [SerializableProperty] + public ExactLeaf? item { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ExactLeaf.cs b/tests/core/Inno.Core.Serialization.Tests/ExactLeaf.cs new file mode 100644 index 000000000..b9dc3bfcf --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ExactLeaf.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class ExactLeaf : ExactBase; diff --git a/tests/core/Inno.Core.Serialization.Tests/ExactLeafConverter.cs b/tests/core/Inno.Core.Serialization.Tests/ExactLeafConverter.cs new file mode 100644 index 000000000..72f92f623 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ExactLeafConverter.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ExactLeafConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + ExactLeaf value + ) => writer.Write("value", value.value); + + public override ExactLeaf Read(SerializationReader reader) + => new() { value = reader.Read("value"), selectedBy = "exact" }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/FreshCaptureMetadataSource.cs b/tests/core/Inno.Core.Serialization.Tests/FreshCaptureMetadataSource.cs new file mode 100644 index 000000000..ebfa5304c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/FreshCaptureMetadataSource.cs @@ -0,0 +1,15 @@ +using System; +using Inno.Adapter.Serialization.DotNet; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class FreshCaptureMetadataSource : ISerializationMetadataSource +{ + private readonly ReflectionSerializationMetadataSource m_source = new(); + + public SerializationTypeMetadata GetMetadata(Type type) + { + SerializationTypeMetadata original = m_source.GetMetadata(type); + return new(type, original.members, original.CreateInstance, original.restored, original.collection, original.requiresConverter); + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/GenericBox.cs b/tests/core/Inno.Core.Serialization.Tests/GenericBox.cs new file mode 100644 index 000000000..ebb7bdded --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/GenericBox.cs @@ -0,0 +1,11 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class GenericBox +{ + public GenericBox(T value) + { + this.value = value; + } + + public T value { get; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/GenericBoxConverter.cs b/tests/core/Inno.Core.Serialization.Tests/GenericBoxConverter.cs new file mode 100644 index 000000000..de443dd7a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/GenericBoxConverter.cs @@ -0,0 +1,13 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class GenericBoxConverter : SerializationConverter> +{ + public override void Write( + SerializationWriter writer, + GenericBox value + ) => writer.Write("value", value.value); + + public override GenericBox Read(SerializationReader reader) => new(reader.Read("value")); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/GenericBoxHost.cs b/tests/core/Inno.Core.Serialization.Tests/GenericBoxHost.cs new file mode 100644 index 000000000..ed527643c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/GenericBoxHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class GenericBoxHost : ISerializable +{ + [SerializableProperty] + public GenericBox? box { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/GetterCaptureProperties.cs b/tests/core/Inno.Core.Serialization.Tests/GetterCaptureProperties.cs new file mode 100644 index 000000000..c869a407e --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/GetterCaptureProperties.cs @@ -0,0 +1,12 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +[SerializationRevision("revision")] +internal sealed class GetterCaptureProperties : IdentityObject, ISerializable +{ + [SerializableProperty] + public CaptureGetterStruct value = new(); + + private ulong? revision => 0; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/HookBaseSample.cs b/tests/core/Inno.Core.Serialization.Tests/HookBaseSample.cs new file mode 100644 index 000000000..3faf409fb --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/HookBaseSample.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +// Open: HookDerivedSample derives from it to inherit its serialization hooks. +internal class HookBaseSample : ISerializable +{ + [SerializableProperty] + public int value { get; set; } + + public List calls { get; } = []; + + [OnSerializableRestored] + private void AfterBaseRestore() => calls.Add("base"); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/HookDerivedSample.cs b/tests/core/Inno.Core.Serialization.Tests/HookDerivedSample.cs new file mode 100644 index 000000000..08de20ed4 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/HookDerivedSample.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class HookDerivedSample : HookBaseSample +{ + [OnSerializableRestored] + private void AfterDerivedRestore() => calls.Add("derived"); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/IAmbiguousLeft.cs b/tests/core/Inno.Core.Serialization.Tests/IAmbiguousLeft.cs new file mode 100644 index 000000000..04e9e1e69 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/IAmbiguousLeft.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal interface IAmbiguousLeft; diff --git a/tests/core/Inno.Core.Serialization.Tests/IAmbiguousRight.cs b/tests/core/Inno.Core.Serialization.Tests/IAmbiguousRight.cs new file mode 100644 index 000000000..89c140436 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/IAmbiguousRight.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal interface IAmbiguousRight; diff --git a/tests/core/Inno.Core.Serialization.Tests/ISampleContext.cs b/tests/core/Inno.Core.Serialization.Tests/ISampleContext.cs new file mode 100644 index 000000000..130c4465e --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ISampleContext.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal interface ISampleContext; diff --git a/tests/core/Inno.Core.Serialization.Tests/IVariantValue.cs b/tests/core/Inno.Core.Serialization.Tests/IVariantValue.cs new file mode 100644 index 000000000..6cbc6032c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/IVariantValue.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal interface IVariantValue +{ + T value { get; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MapHost.cs b/tests/core/Inno.Core.Serialization.Tests/MapHost.cs new file mode 100644 index 000000000..3ad6e2e0a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MapHost.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class MapHost : ISerializable +{ + [SerializableProperty] + public Dictionary values { get; set; } = []; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingChild.cs b/tests/core/Inno.Core.Serialization.Tests/MissingChild.cs new file mode 100644 index 000000000..5e815d7dc --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingChild.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MissingChild +{ + public int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingClassCollectionHost.cs b/tests/core/Inno.Core.Serialization.Tests/MissingClassCollectionHost.cs new file mode 100644 index 000000000..52859ad74 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingClassCollectionHost.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class MissingClassCollectionHost : ISerializable +{ + [SerializableProperty] + public List children { get; set; } = []; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingClassHost.cs b/tests/core/Inno.Core.Serialization.Tests/MissingClassHost.cs new file mode 100644 index 000000000..d84e5d65a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingClassHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MissingClassHost : ISerializable +{ + [SerializableProperty] + public MissingChild? child { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingConstructorSample.cs b/tests/core/Inno.Core.Serialization.Tests/MissingConstructorSample.cs new file mode 100644 index 000000000..dc066061c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingConstructorSample.cs @@ -0,0 +1,12 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MissingConstructorSample : ISerializable +{ + public MissingConstructorSample(int value) + { + this.value = value; + } + + [SerializableProperty] + public int value { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingRequiredConverterSample.cs b/tests/core/Inno.Core.Serialization.Tests/MissingRequiredConverterSample.cs new file mode 100644 index 000000000..53a8831d7 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingRequiredConverterSample.cs @@ -0,0 +1,4 @@ +namespace Inno.Core.Serialization.Tests; + +[RequiresSerializationConverter] +internal sealed class MissingRequiredConverterSample : ISerializable; diff --git a/tests/core/Inno.Core.Serialization.Tests/MissingSetterSample.cs b/tests/core/Inno.Core.Serialization.Tests/MissingSetterSample.cs new file mode 100644 index 000000000..148d0cbdc --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MissingSetterSample.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MissingSetterSample : ISerializable +{ + [SerializableProperty] + public int value { get; } = 1; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCapture.cs b/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCapture.cs new file mode 100644 index 000000000..422a5a113 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCapture.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MutatingBinaryCapture : ISerializable +{ + internal byte[] bytes = [1]; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCaptureConverter.cs b/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCaptureConverter.cs new file mode 100644 index 000000000..ee7dea70f --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MutatingBinaryCaptureConverter.cs @@ -0,0 +1,16 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class MutatingBinaryCaptureConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + MutatingBinaryCapture value + ) { + writer.Write("bytes", value.bytes); + value.bytes[0] = 2; + } + + public override MutatingBinaryCapture Read(SerializationReader reader) => new() { bytes = reader.Read("bytes") }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/MutatingPropertyCapture.cs b/tests/core/Inno.Core.Serialization.Tests/MutatingPropertyCapture.cs new file mode 100644 index 000000000..e850eda2b --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/MutatingPropertyCapture.cs @@ -0,0 +1,14 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class MutatingPropertyCapture : ISerializable +{ + private readonly byte[] m_bytes = [1]; + + [SerializableProperty(PropertyVisibility.Serialize)] + public byte[] bytes => m_bytes; + + [SerializableProperty(PropertyVisibility.Serialize)] + public int mutate => m_bytes[0] = 2; + + internal void Reset() => m_bytes[0] = 1; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestBase.cs b/tests/core/Inno.Core.Serialization.Tests/NearestBase.cs new file mode 100644 index 000000000..109df762b --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestBase.cs @@ -0,0 +1,8 @@ +namespace Inno.Core.Serialization.Tests; + +// Open: NearestMid derives from it for the converter-selection tests. +internal class NearestBase +{ + public int value { get; set; } + public string selectedBy { get; set; } = string.Empty; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestBaseConverter.cs b/tests/core/Inno.Core.Serialization.Tests/NearestBaseConverter.cs new file mode 100644 index 000000000..7a10a979a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestBaseConverter.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class NearestBaseConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + NearestBase value + ) => writer.Write("value", value.value); + + public override NearestBase Read(SerializationReader reader) + => new NearestLeaf { value = reader.Read("value"), selectedBy = "base" }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestHost.cs b/tests/core/Inno.Core.Serialization.Tests/NearestHost.cs new file mode 100644 index 000000000..9e1fa96d8 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestHost.cs @@ -0,0 +1,7 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class NearestHost : ISerializable +{ + [SerializableProperty] + public NearestLeaf? item { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestLeaf.cs b/tests/core/Inno.Core.Serialization.Tests/NearestLeaf.cs new file mode 100644 index 000000000..abf9640cf --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestLeaf.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class NearestLeaf : NearestMid; diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestMid.cs b/tests/core/Inno.Core.Serialization.Tests/NearestMid.cs new file mode 100644 index 000000000..0923f3360 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestMid.cs @@ -0,0 +1,4 @@ +namespace Inno.Core.Serialization.Tests; + +// Open: NearestLeaf derives from it for the converter-selection tests. +internal class NearestMid : NearestBase; diff --git a/tests/core/Inno.Core.Serialization.Tests/NearestMidConverter.cs b/tests/core/Inno.Core.Serialization.Tests/NearestMidConverter.cs new file mode 100644 index 000000000..bcd1454fd --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/NearestMidConverter.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class NearestMidConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + NearestMid value + ) => writer.Write("value", value.value); + + public override NearestMid Read(SerializationReader reader) + => new NearestLeaf { value = reader.Read("value"), selectedBy = "mid" }; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/OrdinalCapture.cs b/tests/core/Inno.Core.Serialization.Tests/OrdinalCapture.cs new file mode 100644 index 000000000..312a675e6 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/OrdinalCapture.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class OrdinalCapture : ISerializable +{ + internal string[] names = ["first", "second", "third"]; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/OrdinalCaptureConverter.cs b/tests/core/Inno.Core.Serialization.Tests/OrdinalCaptureConverter.cs new file mode 100644 index 000000000..e1aab966a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/OrdinalCaptureConverter.cs @@ -0,0 +1,19 @@ +using System; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class OrdinalCaptureConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + OrdinalCapture value + ) { + foreach (string name in value.names) + { + writer.Write(name, 7); + } + } + + public override OrdinalCapture Read(SerializationReader reader) => throw new NotSupportedException(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/PreviousSchemaSample.cs b/tests/core/Inno.Core.Serialization.Tests/PreviousSchemaSample.cs new file mode 100644 index 000000000..c928158c9 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/PreviousSchemaSample.cs @@ -0,0 +1,13 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class PreviousSchemaSample : ISerializable +{ + [SerializableProperty] + public int changed { get; set; } + + [SerializableProperty(PropertyVisibility.Hide)] + public string compatible { get; set; } = string.Empty; + + [SerializableProperty] + public int removed { get; set; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/PrivateConstructorSample.cs b/tests/core/Inno.Core.Serialization.Tests/PrivateConstructorSample.cs new file mode 100644 index 000000000..8dd7e5bcf --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/PrivateConstructorSample.cs @@ -0,0 +1,14 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class PrivateConstructorSample : ISerializable +{ + private PrivateConstructorSample() + { + this.wasConstructed = true; + } + + [SerializableProperty] + public int value { get; set; } + + public bool wasConstructed { get; } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/PureCaptureFields.cs b/tests/core/Inno.Core.Serialization.Tests/PureCaptureFields.cs new file mode 100644 index 000000000..db712830a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/PureCaptureFields.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal struct PureCaptureFields +{ + public float number; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/PureFieldCaptureProperties.cs b/tests/core/Inno.Core.Serialization.Tests/PureFieldCaptureProperties.cs new file mode 100644 index 000000000..0b4a1de16 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/PureFieldCaptureProperties.cs @@ -0,0 +1,21 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +[SerializationRevision("m_revision")] +internal sealed class PureFieldCaptureProperties : IdentityObject, ISerializable +{ + private ulong? m_revision = 0; + private PureCaptureFields m_value; + + [SerializableProperty] + public PureCaptureFields value + { + get => m_value; + set + { + m_revision++; + m_value = value; + } + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/RejectCaptureStream.cs b/tests/core/Inno.Core.Serialization.Tests/RejectCaptureStream.cs new file mode 100644 index 000000000..a33376beb --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/RejectCaptureStream.cs @@ -0,0 +1,9 @@ +using System; +using System.IO; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class RejectCaptureStream : MemoryStream +{ + public override void Write(ReadOnlySpan buffer) => throw new IOException("The test destination rejects writes."); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/SampleContext.cs b/tests/core/Inno.Core.Serialization.Tests/SampleContext.cs new file mode 100644 index 000000000..69aaf781f --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/SampleContext.cs @@ -0,0 +1,3 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class SampleContext : ISampleContext; diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs index e6c51ca8e..a4b79e326 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.ArrayKeys.cs @@ -1,10 +1,8 @@ using System; -using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Xunit; using Inno.Core.Identity; -using Inno.Core.Serialization.Converters; namespace Inno.Core.Serialization.Tests; @@ -150,99 +148,3 @@ public void DeclinedArrayKeysCannotReuseAnEarlierCertifiedElement() Assert.Equal(m_serialization.Serialize(source), changed.ToArray()); } } - -internal sealed class CaptureArrayRoot : ISerializable -{ - internal List rows = []; - internal Guid scope = Guid.NewGuid(); - internal int mode; - internal int keys; - internal bool allowKeys = true; - internal bool stateful; - internal bool failKey; - internal Action? onWrite; - internal SerializationCaptureKeyBuilder? savedBuilder; -} - -internal sealed class CaptureArrayRow : IdentityObject, ISerializable -{ - internal int number; - internal int writes; - internal ulong? revision = 0; - internal ConvertedCaptureProperties state = new(); -} - -internal sealed class CaptureArrayRootConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - CaptureArrayRoot value - ) { - writer.Write("scope", value.scope); - writer.WriteObjectArray( - "rows", - value.rows, - ( - child, - row - ) => - { - row.writes++; - value.onWrite?.Invoke(); - child.Write("number", row.number); - child.Write("mode", value.mode); - if (value.stateful) - { - child.WritePropertiesData("state", row.state); - } - }, - captureKey: ( - row, - key - ) => - { - value.keys++; - value.savedBuilder = key; - if (value.failKey) - { - throw new InvalidOperationException("Array key failure."); - } - if (!value.allowKeys || !key.TryAddOwner(row, row.revision)) - { - return false; - } - key.AddValue(value.scope); - key.AddValue(unchecked((ulong)value.mode)); - key.AddValue(value.stateful ? 1UL : 0UL); - return true; - } - ); - } - - public override CaptureArrayRoot Read(SerializationReader reader) => throw new NotSupportedException(); -} - -internal sealed class CaptureBlobRoot : IdentityObject, ISerializable -{ - internal byte[] data = []; -} - -internal sealed class CaptureBlobRootConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - CaptureBlobRoot value - ) => writer.Write("data", value.data); - - public override CaptureBlobRoot Read(SerializationReader reader) => throw new NotSupportedException(); - - protected override bool TryCaptureKey( - CaptureBlobRoot value, - SerializationCaptureKeyBuilder key - ) => key.TryAddOwner(value, 0); -} - -internal sealed class RejectCaptureStream : MemoryStream -{ - public override void Write(ReadOnlySpan buffer) => throw new IOException("The test destination rejects writes."); -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs index 2d90371db..8a8cdf4b0 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.CaptureKeys.cs @@ -1,15 +1,10 @@ using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.Loader; using System.Threading.Tasks; using Xunit; using Inno.Adapter.Serialization.DotNet; using Inno.Core.Identity; -using Inno.Core.Serialization.Converters; namespace Inno.Core.Serialization.Tests; @@ -353,226 +348,3 @@ WeakReference context return (snapshot, builder, assemblyReference, contextReference); } } - -internal sealed class CaptureKeyRoot : IdentityObject, ISerializable -{ - internal ulong? revision = 0; - internal int number; - internal string? text; - internal bool allowKey = true; - internal bool ignoreDecline; - internal bool failKey; - internal bool failWrite; - internal int writeCalls; - internal int keyCalls; - internal ISerializable? properties; - internal CaptureConvertedValue? converted; - internal Action? onWrite; - internal Action? onKey; - internal SerializationCaptureKeyBuilder? savedBuilder; - - internal void Touch() => revision++; -} - -internal sealed class CaptureKeyContext -{ - internal ulong value; -} - -internal sealed class CaptureKeyRootConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - CaptureKeyRoot value - ) { - value.writeCalls++; - value.onWrite?.Invoke(); - if (value.failWrite) - { - throw new InvalidOperationException("Capture writer failure."); - } - writer.Write("number", value.number); - writer.Write("text", value.text); - writer.Write("context", writer.context.TryGet(out CaptureKeyContext? context) ? context!.value : 0UL); - if (value.properties is not null) - { - writer.WritePropertiesData("properties", value.properties); - } - if (value.converted.HasValue) - { - writer.Write("converted", value.converted.Value); - } - } - - public override CaptureKeyRoot Read(SerializationReader reader) => throw new NotSupportedException(); - - protected override bool TryCaptureKey( - CaptureKeyRoot value, - SerializationCaptureKeyBuilder key - ) { - value.keyCalls++; - value.savedBuilder = key; - if (value.failKey) - { - throw new InvalidOperationException("Capture key failure."); - } - if (!value.allowKey) - { - return false; - } - key.EnsureCapacity(5); - bool complete = key.TryAddOwner(value, value.revision); - key.AddValue(key.context.TryGet(out CaptureKeyContext? context) ? context!.value : 0UL); - if (value.properties is not null) - { - complete &= key.TryAddProperties(value.properties); - } - value.onKey?.Invoke(key); - return complete || value.ignoreDecline; - } -} - -/// -/// Provides a real public extension type for collectible metadata and capture-key acceptance. -/// -[SerializationRevision("m_revision")] -public sealed class CaptureRevisionProperties : IdentityObject, ISerializable -{ - private ulong? m_revision = 0; - private int m_number; - - /// - /// Creates an initially empty tracked property source. - /// - public CaptureRevisionProperties() {} - - /// - /// Gets or sets the serialized number, advancing its complete source-owned revision before mutation. - /// - [SerializableProperty] - public int number - { - get => m_number; - set - { - if (m_revision is { } revision) - { - m_revision = revision == ulong.MaxValue ? null : revision + 1; - } - m_number = value; - } - } -} - -internal sealed class UntrackedCaptureProperties : IdentityObject, ISerializable -{ - [SerializableProperty] - public int number; -} - -[SerializationRevision("revision")] -internal sealed class ConvertedCaptureProperties : IdentityObject, ISerializable -{ - [SerializableProperty] - public CaptureConvertedValue value = new() { number = 1 }; - - private ulong? revision => 0; -} - -[SerializationRevision("m_revision")] -internal sealed class PureFieldCaptureProperties : IdentityObject, ISerializable -{ - private ulong? m_revision = 0; - private PureCaptureFields m_value; - - [SerializableProperty] - public PureCaptureFields value - { - get => m_value; - set - { - m_revision++; - m_value = value; - } - } -} - -internal struct PureCaptureFields -{ - public float number; -} - -[SerializationRevision("revision")] -internal sealed class GetterCaptureProperties : IdentityObject, ISerializable -{ - [SerializableProperty] - public CaptureGetterStruct value = new(); - - private ulong? revision => 0; -} - -internal struct CaptureGetterStruct -{ - internal static int calls; - - public int value - { - get - { - calls++; - return 1; - } - set {} - } -} - -internal struct CaptureConvertedValue -{ - public int number; -} - -internal sealed class CaptureConvertedValueConverter : SerializationConverter -{ - internal static readonly List EVENTS = []; - internal static int calls; - - public CaptureConvertedValueConverter() - { - EVENTS.Add("construct"); - } - - public override void Write( - SerializationWriter writer, - CaptureConvertedValue value - ) { - EVENTS.Add("convert-write"); - writer.Write("number", value.number); - writer.Write("call", ++calls); - } - - public override CaptureConvertedValue Read(SerializationReader reader) => new() { number = reader.Read("number") }; -} - -[SerializationRevision("revision")] -internal sealed class SerializedCaptureCounter : IdentityObject, ISerializable -{ - [SerializableProperty(PropertyVisibility.Serialize)] - public ulong revision => 0; -} - -internal sealed class FreshCaptureMetadataSource : ISerializationMetadataSource -{ - private readonly ReflectionSerializationMetadataSource m_source = new(); - - public SerializationTypeMetadata GetMetadata(Type type) - { - SerializationTypeMetadata original = m_source.GetMetadata(type); - return new(type, original.members, original.CreateInstance, original.restored, original.collection, original.requiresConverter); - } -} - -internal sealed class CapturePropertyLoadContext() : AssemblyLoadContext(isCollectible: true) -{ - protected override Assembly? Load(AssemblyName name) - => Default.Assemblies.FirstOrDefault(assembly => assembly.GetName().Name == name.Name); -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs index 396ec562b..fc48e9aa6 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Concurrency.cs @@ -1,8 +1,6 @@ using System; -using System.Threading; using System.Threading.Tasks; using Xunit; -using Inno.Core.Serialization.Converters; namespace Inno.Core.Serialization.Tests; @@ -34,34 +32,3 @@ public void ConcurrentCapturedOperationsPublishOneConverterAndRetireItAfterTheLa Assert.Throws(() => generation.Serialize(scalar)); } } - -internal sealed class ConcurrentCaptureValue(int count) : ISerializable -{ - internal int count { get; } = count; -} - -internal sealed class ConcurrentCaptureConverter : SerializationConverter, IDisposable -{ - internal static int constructions; - internal static int disposals; - - /// - /// Records construction of the converter owned by the captured generation. - /// - public ConcurrentCaptureConverter() - { - Interlocked.Increment(ref constructions); - } - - /// - public override void Write( - SerializationWriter writer, - ConcurrentCaptureValue value - ) => writer.Write("count", value.count); - - /// - public override ConcurrentCaptureValue Read(SerializationReader reader) => new(reader.Read("count")); - - /// - public void Dispose() => Interlocked.Increment(ref disposals); -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs index e7b9d84cb..9ae889ed5 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.OrdinalReuse.cs @@ -1,6 +1,5 @@ using System; using Xunit; -using Inno.Core.Serialization.Converters; namespace Inno.Core.Serialization.Tests; @@ -23,23 +22,3 @@ public void ReusedScalarKeysPreserveCanonicalBytesAndRejectOutOfOrderDuplicates( Assert.Same(before, m_serialization.CaptureSnapshot(value, previous: before)); } } - -internal sealed class OrdinalCapture : ISerializable -{ - internal string[] names = ["first", "second", "third"]; -} - -internal sealed class OrdinalCaptureConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - OrdinalCapture value - ) { - foreach (string name in value.names) - { - writer.Write(name, 7); - } - } - - public override OrdinalCapture Read(SerializationReader reader) => throw new NotSupportedException(); -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs index b44806fd9..79f2c7b5e 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.Snapshots.cs @@ -1,10 +1,8 @@ using System; -using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Xunit; -using Inno.Core.Serialization.Converters; namespace Inno.Core.Serialization.Tests; @@ -235,81 +233,3 @@ public void UnchangedLargeBinaryCaptureDoesNotCopyItsPayload() return (m_serialization.CaptureSnapshot(value), new WeakReference(value)); } } - -internal sealed class MutatingBinaryCapture : ISerializable -{ - internal byte[] bytes = [1]; -} - -internal sealed class MutatingBinaryCaptureConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - MutatingBinaryCapture value - ) { - writer.Write("bytes", value.bytes); - value.bytes[0] = 2; - } - - public override MutatingBinaryCapture Read(SerializationReader reader) => new() { bytes = reader.Read("bytes") }; -} - -internal sealed class MutatingPropertyCapture : ISerializable -{ - private readonly byte[] m_bytes = [1]; - - [SerializableProperty(PropertyVisibility.Serialize)] - public byte[] bytes => m_bytes; - - [SerializableProperty(PropertyVisibility.Serialize)] - public int mutate => m_bytes[0] = 2; - - internal void Reset() => m_bytes[0] = 1; -} - -internal sealed class SnapshotEnvelope : ISerializable -{ - internal bool omitState; - internal bool fail; - internal bool duplicate; - internal int writeCalls; - internal long observedTypeGeneration; - - internal Dictionary fields { get; } = []; - internal List items { get; } = []; - internal DefaultSample state { get; } = new(); -} - -internal sealed class SnapshotEnvelopeConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - SnapshotEnvelope value - ) { - value.writeCalls++; - value.observedTypeGeneration = writer.typeSnapshot.version; - foreach (KeyValuePair pair in value.fields) - { - writer.Write(pair.Key, pair.Value); - } - if (value.duplicate) - { - writer.Write("duplicate", 1); - writer.Write("duplicate", 2); - } - if (!value.omitState) - { - writer.WritePropertiesData("state", value.state); - writer.WriteObjectArray("items", value.items, static ( - child, - number - ) => child.Write("value", number)); - } - if (value.fail) - { - throw new InvalidOperationException("Capture rejected by its source converter."); - } - } - - public override SnapshotEnvelope Read(SerializationReader reader) => throw new NotSupportedException(); -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs index a4e67913a..d12f8496e 100644 --- a/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs +++ b/tests/core/Inno.Core.Serialization.Tests/SerializationBehaviorTests.cs @@ -7,7 +7,6 @@ using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Core.Serialization.Converters; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; @@ -713,471 +712,3 @@ internal enum SampleMode Easy, Hard } - -internal sealed class PreviousSchemaSample : ISerializable -{ - [SerializableProperty] - public int changed { get; set; } - - [SerializableProperty(PropertyVisibility.Hide)] - public string compatible { get; set; } = string.Empty; - - [SerializableProperty] - public int removed { get; set; } -} - -internal sealed class CurrentSchemaSample : ISerializable -{ - [SerializableProperty] - public string changed { get; set; } = "default"; - - [SerializableProperty(PropertyVisibility.Hide)] - public string compatible { get; set; } = "new"; - - [SerializableProperty] - public int added { get; set; } = 17; - - public int restoreCount { get; private set; } - - [OnSerializableRestored] - private void AfterRestore() => restoreCount++; -} - -internal sealed class DefaultSample : ISerializable -{ - [SerializableProperty] - public bool enabled { get; set; } - - [SerializableProperty] - public int count { get; set; } - - [SerializableProperty] - public float ratio { get; set; } - - [SerializableProperty] - public decimal price { get; set; } - - [SerializableProperty] - public string name { get; set; } = string.Empty; - - [SerializableProperty] - public Guid identity { get; set; } - - [SerializableProperty] - public SampleMode mode { get; set; } - - [SerializableProperty] - public int? optional { get; set; } - - [SerializableProperty] - public byte[] bytes { get; set; } = []; - - [SerializableProperty] - public int[] numbers { get; set; } = []; - - [SerializableProperty] - public List values { get; set; } = []; - - [SerializableProperty] - public Dictionary map { get; set; } = []; - - [SerializableProperty] - public StructSample data { get; set; } -} - -internal struct StructSample -{ - public int x; - public int y { get; set; } - public readonly int readOnly; - - [SerializableProperty] - private int m_hidden; - - public readonly int computed => x + m_hidden; - public readonly int hidden => m_hidden; - - private StructSample( - int x, - int y, - int hidden - ) { - this.x = x; - this.y = y; - this.readOnly = 99; - m_hidden = hidden; - } - - internal static StructSample Create( - int x, - int y, - int hidden - ) => new(x, y, hidden); -} - -internal sealed class PrivateConstructorSample : ISerializable -{ - private PrivateConstructorSample() - { - this.wasConstructed = true; - } - - [SerializableProperty] - public int value { get; set; } - - public bool wasConstructed { get; } -} - -internal sealed class MissingConstructorSample : ISerializable -{ - public MissingConstructorSample(int value) - { - this.value = value; - } - - [SerializableProperty] - public int value { get; set; } -} - -internal sealed class ConvertedConstructorSample : ISerializable -{ - public ConvertedConstructorSample(int value) - { - this.value = value; - } - - public int value { get; set; } -} - -internal sealed class ConvertedConstructorSampleConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - ConvertedConstructorSample value - ) => writer.Write("value", value.value); - - public override ConvertedConstructorSample Read(SerializationReader reader) => new(reader.Read("value")); - - public override void Restore( - SerializationReader reader, - ConvertedConstructorSample target - ) => target.value = reader.Read("value"); -} - -internal sealed class ThrowingConstructorSample : ISerializable -{ - private ThrowingConstructorSample() - { - throw new ApplicationException("constructor failure"); - } -} - -[RequiresSerializationConverter] -internal sealed class MissingRequiredConverterSample : ISerializable; - -internal sealed class VisibilitySample : ISerializable -{ - [SerializableProperty] - public int shown { get; set; } - - [SerializableProperty(PropertyVisibility.Hide)] - public int hidden { get; set; } - - [SerializableProperty(PropertyVisibility.Readonly)] - public int readOnly { get; set; } - - [SerializableProperty(PropertyVisibility.Transient)] - public int transient { get; set; } - - [SerializableProperty(PropertyVisibility.SerializeOnly)] - public int serializeOnly { get; set; } - - [SerializableProperty(PropertyVisibility.DeserializeOnly)] - public int deserializeOnly { get; set; } -} - -internal sealed class MissingSetterSample : ISerializable -{ - [SerializableProperty] - public int value { get; } = 1; -} - -// Open: DuplicateKeyDerivedSample derives from it. -internal class DuplicateKeyBaseSample : ISerializable -{ - [SerializableProperty] - public int value { get; set; } -} - -internal sealed class DuplicateKeyDerivedSample : DuplicateKeyBaseSample -{ - [SerializableProperty] - public new int value { get; set; } -} - -internal sealed class MissingChild -{ - public int value { get; set; } -} - -internal sealed class MissingClassHost : ISerializable -{ - [SerializableProperty] - public MissingChild? child { get; set; } -} - -internal sealed class MissingClassCollectionHost : ISerializable -{ - [SerializableProperty] - public List children { get; set; } = []; -} - -internal sealed class ConvertedChild -{ - public int value { get; set; } -} - -internal sealed class ConvertedChildHost : ISerializable -{ - [SerializableProperty] - public ConvertedChild? child { get; set; } -} - -internal sealed class CycleValue -{ - public CycleValue? next { get; set; } -} - -internal sealed class CycleHost : ISerializable -{ - [SerializableProperty] - public CycleValue? value { get; set; } -} - -internal sealed class CycleValueConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - CycleValue value - ) => writer.Write("next", value.next); - - public override CycleValue Read(SerializationReader reader) => new() { next = reader.Read("next") }; -} - -internal sealed class ConvertedChildConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - ConvertedChild value - ) => writer.Write("value", value.value); - - public override ConvertedChild Read(SerializationReader reader) => new() { value = reader.Read("value") }; -} - -// Open: NearestMid derives from it for the converter-selection tests. -internal class NearestBase -{ - public int value { get; set; } - public string selectedBy { get; set; } = string.Empty; -} - -// Open: NearestLeaf derives from it for the converter-selection tests. -internal class NearestMid : NearestBase; - -internal sealed class NearestLeaf : NearestMid; - -internal sealed class NearestHost : ISerializable -{ - [SerializableProperty] - public NearestLeaf? item { get; set; } -} - -internal sealed class NearestBaseConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - NearestBase value - ) => writer.Write("value", value.value); - - public override NearestBase Read(SerializationReader reader) - => new NearestLeaf { value = reader.Read("value"), selectedBy = "base" }; -} - -internal sealed class NearestMidConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - NearestMid value - ) => writer.Write("value", value.value); - - public override NearestMid Read(SerializationReader reader) - => new NearestLeaf { value = reader.Read("value"), selectedBy = "mid" }; -} - -// Open: ExactLeaf derives from it for the converter-selection tests. -internal class ExactBase -{ - public int value { get; set; } - public string selectedBy { get; set; } = string.Empty; -} - -internal sealed class ExactLeaf : ExactBase; - -internal sealed class ExactHost : ISerializable -{ - [SerializableProperty] - public ExactLeaf? item { get; set; } -} - -internal sealed class ExactBaseConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - ExactBase value - ) => writer.Write("value", value.value); - - public override ExactBase Read(SerializationReader reader) - => new ExactLeaf { value = reader.Read("value"), selectedBy = "base" }; -} - -internal sealed class ExactLeafConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - ExactLeaf value - ) => writer.Write("value", value.value); - - public override ExactLeaf Read(SerializationReader reader) - => new() { value = reader.Read("value"), selectedBy = "exact" }; -} - -internal interface IAmbiguousLeft; - -internal interface IAmbiguousRight; - -internal sealed class AmbiguousValue : IAmbiguousLeft, IAmbiguousRight; - -internal sealed class AmbiguousHost : ISerializable -{ - [SerializableProperty] - public AmbiguousValue? item { get; set; } -} - -internal sealed class AmbiguousLeftConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - IAmbiguousLeft value - ) {} - - public override IAmbiguousLeft Read(SerializationReader reader) => new AmbiguousValue(); -} - -internal sealed class AmbiguousRightConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - IAmbiguousRight value - ) {} - - public override IAmbiguousRight Read(SerializationReader reader) => new AmbiguousValue(); -} - -internal sealed class GenericBox -{ - public GenericBox(T value) - { - this.value = value; - } - - public T value { get; } -} - -internal sealed class GenericBoxHost : ISerializable -{ - [SerializableProperty] - public GenericBox? box { get; set; } -} - -internal sealed class GenericBoxConverter : SerializationConverter> -{ - public override void Write( - SerializationWriter writer, - GenericBox value - ) => writer.Write("value", value.value); - - public override GenericBox Read(SerializationReader reader) => new(reader.Read("value")); -} - -internal interface IVariantValue -{ - T value { get; } -} - -internal sealed class VariantValue(string value) : IVariantValue -{ - public string value { get; } = value; -} - -internal sealed class VariantValueConverter : SerializationConverter> -{ - public override void Write( - SerializationWriter writer, - IVariantValue value - ) => writer.Write("value", (string)value.value); - - public override IVariantValue Read(SerializationReader reader) - => new VariantValue(reader.Read("value")); -} - -internal interface ISampleContext; - -internal sealed class SampleContext : ISampleContext; - -// Open: HookDerivedSample derives from it to inherit its serialization hooks. -internal class HookBaseSample : ISerializable -{ - [SerializableProperty] - public int value { get; set; } - - public List calls { get; } = []; - - [OnSerializableRestored] - private void AfterBaseRestore() => calls.Add("base"); -} - -internal sealed class HookDerivedSample : HookBaseSample -{ - [OnSerializableRestored] - private void AfterDerivedRestore() => calls.Add("derived"); -} - -internal sealed class ConvertedHookSample : ISerializable -{ - public int value { get; set; } - public int hookCount { get; private set; } - - [OnSerializableRestored] - private void AfterRestore() => hookCount++; -} - -internal sealed class ConvertedHookSampleConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - ConvertedHookSample value - ) => writer.Write("value", value.value); - - public override ConvertedHookSample Read(SerializationReader reader) => new() { value = reader.Read("value") }; - - public override void Restore( - SerializationReader reader, - ConvertedHookSample target - ) => target.value = reader.Read("value"); -} - -internal sealed class MapHost : ISerializable -{ - [SerializableProperty] - public Dictionary values { get; set; } = []; -} diff --git a/tests/core/Inno.Core.Serialization.Tests/SerializedCaptureCounter.cs b/tests/core/Inno.Core.Serialization.Tests/SerializedCaptureCounter.cs new file mode 100644 index 000000000..478efbbe0 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/SerializedCaptureCounter.cs @@ -0,0 +1,10 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +[SerializationRevision("revision")] +internal sealed class SerializedCaptureCounter : IdentityObject, ISerializable +{ + [SerializableProperty(PropertyVisibility.Serialize)] + public ulong revision => 0; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelope.cs b/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelope.cs new file mode 100644 index 000000000..c6a6d1953 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelope.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class SnapshotEnvelope : ISerializable +{ + internal bool omitState; + internal bool fail; + internal bool duplicate; + internal int writeCalls; + internal long observedTypeGeneration; + + internal Dictionary fields { get; } = []; + internal List items { get; } = []; + internal DefaultSample state { get; } = new(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelopeConverter.cs b/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelopeConverter.cs new file mode 100644 index 000000000..216eee285 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/SnapshotEnvelopeConverter.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class SnapshotEnvelopeConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + SnapshotEnvelope value + ) { + value.writeCalls++; + value.observedTypeGeneration = writer.typeSnapshot.version; + foreach (KeyValuePair pair in value.fields) + { + writer.Write(pair.Key, pair.Value); + } + if (value.duplicate) + { + writer.Write("duplicate", 1); + writer.Write("duplicate", 2); + } + if (!value.omitState) + { + writer.WritePropertiesData("state", value.state); + writer.WriteObjectArray("items", value.items, static ( + child, + number + ) => child.Write("value", number)); + } + if (value.fail) + { + throw new InvalidOperationException("Capture rejected by its source converter."); + } + } + + public override SnapshotEnvelope Read(SerializationReader reader) => throw new NotSupportedException(); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/StructSample.cs b/tests/core/Inno.Core.Serialization.Tests/StructSample.cs new file mode 100644 index 000000000..1f1286e91 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/StructSample.cs @@ -0,0 +1,31 @@ +namespace Inno.Core.Serialization.Tests; + +internal struct StructSample +{ + public int x; + public int y { get; set; } + public readonly int readOnly; + + [SerializableProperty] + private int m_hidden; + + public readonly int computed => x + m_hidden; + public readonly int hidden => m_hidden; + + private StructSample( + int x, + int y, + int hidden + ) { + this.x = x; + this.y = y; + this.readOnly = 99; + m_hidden = hidden; + } + + internal static StructSample Create( + int x, + int y, + int hidden + ) => new(x, y, hidden); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/ThrowingConstructorSample.cs b/tests/core/Inno.Core.Serialization.Tests/ThrowingConstructorSample.cs new file mode 100644 index 000000000..bc2d4d33a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/ThrowingConstructorSample.cs @@ -0,0 +1,11 @@ +using System; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class ThrowingConstructorSample : ISerializable +{ + private ThrowingConstructorSample() + { + throw new ApplicationException("constructor failure"); + } +} diff --git a/tests/core/Inno.Core.Serialization.Tests/UntrackedCaptureProperties.cs b/tests/core/Inno.Core.Serialization.Tests/UntrackedCaptureProperties.cs new file mode 100644 index 000000000..51174051c --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/UntrackedCaptureProperties.cs @@ -0,0 +1,9 @@ +using Inno.Core.Identity; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class UntrackedCaptureProperties : IdentityObject, ISerializable +{ + [SerializableProperty] + public int number; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/VariantValue.cs b/tests/core/Inno.Core.Serialization.Tests/VariantValue.cs new file mode 100644 index 000000000..2d7252b44 --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/VariantValue.cs @@ -0,0 +1,6 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class VariantValue(string value) : IVariantValue +{ + public string value { get; } = value; +} diff --git a/tests/core/Inno.Core.Serialization.Tests/VariantValueConverter.cs b/tests/core/Inno.Core.Serialization.Tests/VariantValueConverter.cs new file mode 100644 index 000000000..e6b87741d --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/VariantValueConverter.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization.Converters; + +namespace Inno.Core.Serialization.Tests; + +internal sealed class VariantValueConverter : SerializationConverter> +{ + public override void Write( + SerializationWriter writer, + IVariantValue value + ) => writer.Write("value", (string)value.value); + + public override IVariantValue Read(SerializationReader reader) + => new VariantValue(reader.Read("value")); +} diff --git a/tests/core/Inno.Core.Serialization.Tests/VisibilitySample.cs b/tests/core/Inno.Core.Serialization.Tests/VisibilitySample.cs new file mode 100644 index 000000000..b0b728f4a --- /dev/null +++ b/tests/core/Inno.Core.Serialization.Tests/VisibilitySample.cs @@ -0,0 +1,22 @@ +namespace Inno.Core.Serialization.Tests; + +internal sealed class VisibilitySample : ISerializable +{ + [SerializableProperty] + public int shown { get; set; } + + [SerializableProperty(PropertyVisibility.Hide)] + public int hidden { get; set; } + + [SerializableProperty(PropertyVisibility.Readonly)] + public int readOnly { get; set; } + + [SerializableProperty(PropertyVisibility.Transient)] + public int transient { get; set; } + + [SerializableProperty(PropertyVisibility.SerializeOnly)] + public int serializeOnly { get; set; } + + [SerializableProperty(PropertyVisibility.DeserializeOnly)] + public int deserializeOnly { get; set; } +} diff --git a/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalState.cs b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalState.cs new file mode 100644 index 000000000..a14d85f5a --- /dev/null +++ b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalState.cs @@ -0,0 +1,34 @@ +using System.Numerics; +using Inno.Editor.ImGui.ImGuiWidget; + +namespace Inno.Editor.ImGui.Tests; + +public sealed class DynamicModalState +{ + public string message = "Short"; + public float zoom = 1f; + public bool showAction = true; + public bool showProgress = true; + public bool indeterminate; + public string? details; + public Vector2 initialSize; + public bool resizable; + public bool visible = true; + public bool rejectPreparation; + public bool rejectDraw; + public bool canceled; + public int actions; + public bool popupOpen; + public Vector2 actionMin; + public float scrollMaxX; + public float wrapWidth; + public float bodyHeight; + public float bodyContentHeight; + public int preparations; + public int draws; + public DialogPresentation content; + public DialogLayout layout; + public Vector2 windowSize; + public Vector2 windowMax; + public Vector2 actionMax; +} diff --git a/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs index 8cfdbeaee..28277d249 100644 --- a/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs +++ b/tests/editor/Inno.Editor.ImGui.Tests/DynamicModalTests.cs @@ -9,7 +9,6 @@ using Inno.Core.Input; using Inno.Core.Logging; using Inno.Editor.Core; -using Inno.Editor.ImGui.ImGuiWidget; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Native.ImGui; @@ -381,89 +380,3 @@ internal void Frame() } } } - -public sealed class DynamicModalState -{ - public string message = "Short"; - public float zoom = 1f; - public bool showAction = true; - public bool showProgress = true; - public bool indeterminate; - public string? details; - public Vector2 initialSize; - public bool resizable; - public bool visible = true; - public bool rejectPreparation; - public bool rejectDraw; - public bool canceled; - public int actions; - public bool popupOpen; - public Vector2 actionMin; - public float scrollMaxX; - public float wrapWidth; - public float bodyHeight; - public float bodyContentHeight; - public int preparations; - public int draws; - public DialogPresentation content; - public DialogLayout layout; - public Vector2 windowSize; - public Vector2 windowMax; - public Vector2 actionMax; -} - -[EditorModal("tests.dynamic-modal", "Dynamic Modal")] -public sealed unsafe class DynamicTestModal(DynamicModalState state) : EditorModal -{ - public override bool isVisible => state.visible; - public override bool allowScrolling => false; - public override Vector2 initialSize => state.initialSize; - public override bool canResize => state.resizable; - - protected override Vector2? OnPrepare( - EditorContext context, - Vector2 availableContentSize - ) { - state.preparations++; - if (state.rejectPreparation) throw new InvalidOperationException("Rejected modal measurement."); - EditorUISession.current.widgets.style.SetZoom(state.zoom); - state.content = new( - state.message, - state.showProgress ? 0.5f : null, - state.indeterminate, - actionLabel: state.showAction ? "Cancel" : null, - actionEnabled: !state.canceled, - details: state.details, - cancelOnEscape: true - ); - state.layout = EditorUISession.current.widgets.MeasureDialog(state.content, availableContentSize); - return state.layout.size; - } - - protected override void OnDraw(EditorContext context) - { - state.draws++; - state.windowSize = NativeGui.GetWindowSize(); - state.windowMax = NativeGui.GetWindowPos() + state.windowSize; - if (EditorUISession.current.widgets.DrawDialog(state.content, state.layout)) - { - state.actions++; - state.canceled = true; - } - state.actionMin = NativeGui.GetItemRectMin(); - state.scrollMaxX = NativeGui.GetScrollMaxX(); - ImGuiWindow* window = NativeGui.Raw.GetCurrentWindow(); - state.wrapWidth = NativeGui.GetContentRegionAvail().X; - state.bodyHeight = state.message.Length == 0 ? 0f : NativeGui.CalcTextSize(state.message, false, state.wrapWidth).Y; - state.bodyContentHeight = state.bodyHeight; - if (window->DC.ChildWindows.Size > 0) - { - ImGuiWindow* child = window->DC.ChildWindows.Data[0]; - state.wrapWidth = child->WorkRect.Max.X - child->WorkRect.Min.X; - state.bodyHeight = child->Size.Y; - state.bodyContentHeight = child->ContentSize.Y; - } - if (state.rejectDraw) throw new InvalidOperationException("Rejected modal drawing."); - state.actionMax = NativeGui.GetItemRectMax(); - } -} diff --git a/tests/editor/Inno.Editor.ImGui.Tests/DynamicTestModal.cs b/tests/editor/Inno.Editor.ImGui.Tests/DynamicTestModal.cs new file mode 100644 index 000000000..69d6bfa93 --- /dev/null +++ b/tests/editor/Inno.Editor.ImGui.Tests/DynamicTestModal.cs @@ -0,0 +1,64 @@ +using System; +using System.Numerics; +using Inno.Editor.Core; +using Inno.Native.ImGui; + +using NativeGui = Inno.Native.ImGui.ImGui; + +namespace Inno.Editor.ImGui.Tests; + +[EditorModal("tests.dynamic-modal", "Dynamic Modal")] +public sealed unsafe class DynamicTestModal(DynamicModalState state) : EditorModal +{ + public override bool isVisible => state.visible; + public override bool allowScrolling => false; + public override Vector2 initialSize => state.initialSize; + public override bool canResize => state.resizable; + + protected override Vector2? OnPrepare( + EditorContext context, + Vector2 availableContentSize + ) { + state.preparations++; + if (state.rejectPreparation) throw new InvalidOperationException("Rejected modal measurement."); + EditorUISession.current.widgets.style.SetZoom(state.zoom); + state.content = new( + state.message, + state.showProgress ? 0.5f : null, + state.indeterminate, + actionLabel: state.showAction ? "Cancel" : null, + actionEnabled: !state.canceled, + details: state.details, + cancelOnEscape: true + ); + state.layout = EditorUISession.current.widgets.MeasureDialog(state.content, availableContentSize); + return state.layout.size; + } + + protected override void OnDraw(EditorContext context) + { + state.draws++; + state.windowSize = NativeGui.GetWindowSize(); + state.windowMax = NativeGui.GetWindowPos() + state.windowSize; + if (EditorUISession.current.widgets.DrawDialog(state.content, state.layout)) + { + state.actions++; + state.canceled = true; + } + state.actionMin = NativeGui.GetItemRectMin(); + state.scrollMaxX = NativeGui.GetScrollMaxX(); + ImGuiWindow* window = NativeGui.Raw.GetCurrentWindow(); + state.wrapWidth = NativeGui.GetContentRegionAvail().X; + state.bodyHeight = state.message.Length == 0 ? 0f : NativeGui.CalcTextSize(state.message, false, state.wrapWidth).Y; + state.bodyContentHeight = state.bodyHeight; + if (window->DC.ChildWindows.Size > 0) + { + ImGuiWindow* child = window->DC.ChildWindows.Data[0]; + state.wrapWidth = child->WorkRect.Max.X - child->WorkRect.Min.X; + state.bodyHeight = child->Size.Y; + state.bodyContentHeight = child->ContentSize.Y; + } + if (state.rejectDraw) throw new InvalidOperationException("Rejected modal drawing."); + state.actionMax = NativeGui.GetItemRectMax(); + } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/BatchValidationComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/BatchValidationComponent.cs new file mode 100644 index 000000000..21fe80399 --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/BatchValidationComponent.cs @@ -0,0 +1,25 @@ +using System; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("9ea6d04d-4ed3-48f3-ac3a-b09372a575ab")] +internal sealed class BatchValidationComponent : GameComponent +{ + [SerializableProperty] + public int value { get; set; } + + [SerializableProperty] + public bool rejectAnswer { get; set; } + + [OnSerializableRestored] + private void Validate() + { + if (rejectAnswer && value == 42) + { + throw new InvalidOperationException("The current owner rejected this batch value."); + } + } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/CoupledHistoryComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/CoupledHistoryComponent.cs new file mode 100644 index 000000000..cd89937cd --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/CoupledHistoryComponent.cs @@ -0,0 +1,33 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("f25d91a5-df87-4ed6-a383-12a9071af66e")] +internal sealed class CoupledHistoryComponent : GameBehavior +{ + private bool m_primary = true; + private CoupledHistoryMode m_mode; + + [SerializableProperty] + public bool primary + { + get => m_primary; + set => m_primary = value && mode == CoupledHistoryMode.Base; + } + + [SerializableProperty] + public CoupledHistoryMode mode + { + get => m_mode; + set + { + m_mode = value; + if (value == CoupledHistoryMode.Overlay) + { + m_primary = false; + } + } + } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs b/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs index a454c9c15..bd9050c5c 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/EditorHistoryTests.cs @@ -1,12 +1,10 @@ using System; -using System.Collections.Generic; using System.IO; using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Core.Input; using Inno.Core.Logging; using Inno.Editor.Core; -using Inno.Editor.Interactions; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; @@ -322,94 +320,3 @@ public void Dispose() internal IEditorHistory history => runtime.interactions.history; } } - -[EditorHistoryHandler(NeutralValueHistoryHandler.C_KIND)] -public sealed class NeutralValueHistoryHandler : EditorHistoryHandler -{ - public const string C_KIND = "tests/neutral-values"; - private static readonly HashSet<(int slot, EditorHistoryDirection direction)> BLOCKED = []; - private static readonly Dictionary VALUES = []; - - public static EditorHistoryChange CreateChange( - int slot, - int before, - int after, - string? mergeKey = null - ) { - var bytes = new byte[sizeof(int) * 3]; - BitConverter.GetBytes(slot).CopyTo(bytes, 0); - BitConverter.GetBytes(before).CopyTo(bytes, sizeof(int)); - BitConverter.GetBytes(after).CopyTo(bytes, sizeof(int) * 2); - return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(bytes), mergeKey); - } - - public static int GetValue(int slot) => VALUES.TryGetValue(slot, out int value) ? value : 0; - - public static void SetValue( - int slot, - int value - ) => VALUES[slot] = value; - - public static void Block( - int slot, - EditorHistoryDirection direction - ) => BLOCKED.Add((slot, direction)); - - public static void Unblock( - int slot, - EditorHistoryDirection direction - ) => BLOCKED.Remove((slot, direction)); - - public static void Reset() - { - BLOCKED.Clear(); - VALUES.Clear(); - } - - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) => change.payload.length >= sizeof(int) * 3 - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); - - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - byte[] bytes = change.payload.ReadBytes(); - int slot = BitConverter.ToInt32(bytes, 0); - if (BLOCKED.Contains((slot, direction))) - { - return EditorHistoryResult.Failure($"Slot {slot} is blocked for {direction}."); - } - int offset = direction == EditorHistoryDirection.Undo ? sizeof(int) : sizeof(int) * 2; - VALUES[slot] = BitConverter.ToInt32(bytes, offset); - return EditorHistoryResult.Success(); - } - - protected override bool TryMerge( - EditorHistoryChange older, - EditorHistoryChange newer, - out EditorHistoryChange? merged - ) { - byte[] olderBytes = older.payload.ReadBytes(); - byte[] newerBytes = newer.payload.ReadBytes(); - int slot = BitConverter.ToInt32(olderBytes, 0); - if (slot != BitConverter.ToInt32(newerBytes, 0)) - { - merged = null; - return false; - } - - merged = CreateChange( - slot, - BitConverter.ToInt32(olderBytes, sizeof(int)), - BitConverter.ToInt32(newerBytes, sizeof(int) * 2), - older.mergeKey - ); - return true; - } -} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/HistoryAssetReferenceComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/HistoryAssetReferenceComponent.cs new file mode 100644 index 000000000..90ef3b0f1 --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/HistoryAssetReferenceComponent.cs @@ -0,0 +1,14 @@ +using Inno.Assets; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("edbd3940-a94c-499e-8f03-b0e232a39b21")] +[AllowMultipleComponent] +internal sealed class HistoryAssetReferenceComponent : GameComponent +{ + [SerializableProperty] + public TextAsset? asset { get; set; } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/HistoryComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/HistoryComponent.cs new file mode 100644 index 000000000..3bfb8f5d3 --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/HistoryComponent.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("267e77d8-1112-4cf9-a9f1-01d9a1e59bbc")] +[AllowMultipleComponent] +internal sealed class HistoryComponent : GameBehavior +{ + [SerializableProperty] + public int value { get; set; } + + protected override void Reset() => value = 7; +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/HistoryReferenceComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/HistoryReferenceComponent.cs new file mode 100644 index 000000000..09f86fcde --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/HistoryReferenceComponent.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("b269c970-8afe-46a0-a4a0-f44f737d059a")] +internal sealed class HistoryReferenceComponent : GameComponent +{ + [SerializableProperty] + public GameObject? targetObject { get; set; } + + [SerializableProperty] + public GameComponent? targetComponent { get; set; } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/HistorySystem.cs b/tests/editor/Inno.Editor.Interactions.Tests/HistorySystem.cs new file mode 100644 index 000000000..a0863ccd4 --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/HistorySystem.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("f00d5950-1136-4393-b246-644b69948f90")] +[AllowMultipleSystem] +internal sealed class HistorySystem : GameSystem +{ + [SerializableProperty] + public int value { get; set; } + + protected override void Reset() => value = 11; +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/NeutralValueHistoryHandler.cs b/tests/editor/Inno.Editor.Interactions.Tests/NeutralValueHistoryHandler.cs new file mode 100644 index 000000000..08046849a --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/NeutralValueHistoryHandler.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Editor.Interactions.Tests; + +[EditorHistoryHandler(NeutralValueHistoryHandler.C_KIND)] +public sealed class NeutralValueHistoryHandler : EditorHistoryHandler +{ + public const string C_KIND = "tests/neutral-values"; + private static readonly HashSet<(int slot, EditorHistoryDirection direction)> BLOCKED = []; + private static readonly Dictionary VALUES = []; + + public static EditorHistoryChange CreateChange( + int slot, + int before, + int after, + string? mergeKey = null + ) { + var bytes = new byte[sizeof(int) * 3]; + BitConverter.GetBytes(slot).CopyTo(bytes, 0); + BitConverter.GetBytes(before).CopyTo(bytes, sizeof(int)); + BitConverter.GetBytes(after).CopyTo(bytes, sizeof(int) * 2); + return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(bytes), mergeKey); + } + + public static int GetValue(int slot) => VALUES.TryGetValue(slot, out int value) ? value : 0; + + public static void SetValue( + int slot, + int value + ) => VALUES[slot] = value; + + public static void Block( + int slot, + EditorHistoryDirection direction + ) => BLOCKED.Add((slot, direction)); + + public static void Unblock( + int slot, + EditorHistoryDirection direction + ) => BLOCKED.Remove((slot, direction)); + + public static void Reset() + { + BLOCKED.Clear(); + VALUES.Clear(); + } + + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) => change.payload.length >= sizeof(int) * 3 + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); + + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + byte[] bytes = change.payload.ReadBytes(); + int slot = BitConverter.ToInt32(bytes, 0); + if (BLOCKED.Contains((slot, direction))) + { + return EditorHistoryResult.Failure($"Slot {slot} is blocked for {direction}."); + } + int offset = direction == EditorHistoryDirection.Undo ? sizeof(int) : sizeof(int) * 2; + VALUES[slot] = BitConverter.ToInt32(bytes, offset); + return EditorHistoryResult.Success(); + } + + protected override bool TryMerge( + EditorHistoryChange older, + EditorHistoryChange newer, + out EditorHistoryChange? merged + ) { + byte[] olderBytes = older.payload.ReadBytes(); + byte[] newerBytes = newer.payload.ReadBytes(); + int slot = BitConverter.ToInt32(olderBytes, 0); + if (slot != BitConverter.ToInt32(newerBytes, 0)) + { + merged = null; + return false; + } + + merged = CreateChange( + slot, + BitConverter.ToInt32(olderBytes, sizeof(int)), + BitConverter.ToInt32(newerBytes, sizeof(int) * 2), + older.mergeKey + ); + return true; + } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/RestoreCleanupFailureComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/RestoreCleanupFailureComponent.cs new file mode 100644 index 000000000..257102391 --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/RestoreCleanupFailureComponent.cs @@ -0,0 +1,17 @@ +using System; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("71cc27da-2c47-47f2-a037-c9bc29615358")] +[AllowMultipleComponent] +internal sealed class RestoreCleanupFailureComponent : GameBehavior +{ + [SerializableProperty] + public int value { get; set; } = 5; + + [OnSerializableRestored] + private void OnRestored() => throw new InvalidOperationException("Injected restore callback failure."); +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryProbe.cs b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryProbe.cs new file mode 100644 index 000000000..07bc9c94c --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryProbe.cs @@ -0,0 +1,25 @@ +using Inno.Editor.Core; +using Inno.Editor.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[EditorModule("tests.scene-history-probe", order: 220)] +public sealed class SceneHistoryProbe : EditorModule +{ + public SceneHistoryProbe( + SceneEdits sceneEdits, + IEditorSceneWorkspace workspace + ) { + edits = sceneEdits; + documents = workspace; + } + + public static SceneEdits? edits { get; private set; } + public static IEditorSceneWorkspace? documents { get; private set; } + + public static void Reset() + { + edits = null; + documents = null; + } +} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs index b82c011ee..e7f57070c 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.Selection.cs @@ -2,8 +2,6 @@ using Xunit; using Inno.Core.Identity; using Inno.Core.Mathematics; -using Inno.Core.Serialization; -using Inno.Extensibility.Types; using Inno.Scene; using Inno.Scene.Components; @@ -130,22 +128,3 @@ public void BatchMovePreservesRootOrderAndRestoresIndependentPlacements() Assert.Same(destination.transform, first.transform.parent); } } - -[StableTypeID("9ea6d04d-4ed3-48f3-ac3a-b09372a575ab")] -internal sealed class BatchValidationComponent : GameComponent -{ - [SerializableProperty] - public int value { get; set; } - - [SerializableProperty] - public bool rejectAnswer { get; set; } - - [OnSerializableRestored] - private void Validate() - { - if (rejectAnswer && value == 42) - { - throw new InvalidOperationException("The current owner rejected this batch value."); - } - } -} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs index f501ad38b..fabd9c2cf 100644 --- a/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs +++ b/tests/editor/Inno.Editor.Interactions.Tests/SceneHistoryTests.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using System.Linq; using System.Runtime.CompilerServices; using Xunit; using Inno.Adapter.Modules.DotNet; @@ -11,7 +10,6 @@ using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Mathematics; -using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Scene; using Inno.Extensibility.Modules; @@ -813,127 +811,8 @@ public void RestorePreviousState() } } -[EditorModule("tests.scene-history-probe", order: 220)] -public sealed class SceneHistoryProbe : EditorModule -{ - public SceneHistoryProbe( - SceneEdits sceneEdits, - IEditorSceneWorkspace workspace - ) { - edits = sceneEdits; - documents = workspace; - } - - public static SceneEdits? edits { get; private set; } - public static IEditorSceneWorkspace? documents { get; private set; } - - public static void Reset() - { - edits = null; - documents = null; - } -} - -[StableTypeID("267e77d8-1112-4cf9-a9f1-01d9a1e59bbc")] -[AllowMultipleComponent] -internal sealed class HistoryComponent : GameBehavior -{ - [SerializableProperty] - public int value { get; set; } - - protected override void Reset() => value = 7; -} - internal enum CoupledHistoryMode { Base, Overlay } - -[StableTypeID("f25d91a5-df87-4ed6-a383-12a9071af66e")] -internal sealed class CoupledHistoryComponent : GameBehavior -{ - private bool m_primary = true; - private CoupledHistoryMode m_mode; - - [SerializableProperty] - public bool primary - { - get => m_primary; - set => m_primary = value && mode == CoupledHistoryMode.Base; - } - - [SerializableProperty] - public CoupledHistoryMode mode - { - get => m_mode; - set - { - m_mode = value; - if (value == CoupledHistoryMode.Overlay) - { - m_primary = false; - } - } - } -} - -[StableTypeID("b269c970-8afe-46a0-a4a0-f44f737d059a")] -internal sealed class HistoryReferenceComponent : GameComponent -{ - [SerializableProperty] - public GameObject? targetObject { get; set; } - - [SerializableProperty] - public GameComponent? targetComponent { get; set; } -} - -[StableTypeID("edbd3940-a94c-499e-8f03-b0e232a39b21")] -[AllowMultipleComponent] -internal sealed class HistoryAssetReferenceComponent : GameComponent -{ - [SerializableProperty] - public TextAsset? asset { get; set; } -} - -[StableTypeID("f00d5950-1136-4393-b246-644b69948f90")] -[AllowMultipleSystem] -internal sealed class HistorySystem : GameSystem -{ - [SerializableProperty] - public int value { get; set; } - - protected override void Reset() => value = 11; -} - -[StableTypeID("71cc27da-2c47-47f2-a037-c9bc29615358")] -[AllowMultipleComponent] -internal sealed class RestoreCleanupFailureComponent : GameBehavior -{ - [SerializableProperty] - public int value { get; set; } = 5; - - [OnSerializableRestored] - private void OnRestored() => throw new InvalidOperationException("Injected restore callback failure."); -} - -[StableTypeID("8503e97b-1845-4ab2-a116-1ece04934a4b")] -[AllowMultipleComponent] -internal sealed class SubtreeRestoreFailureComponent : GameBehavior -{ - internal static bool throwOnDestroy; - - [SerializableProperty] - public int value { get; set; } = 5; - - protected override void OnDestroy() - { - if (throwOnDestroy) - { - throw new InvalidOperationException("Injected subtree destruction callback failure."); - } - } - - [OnSerializableRestored] - private void OnRestored() => throw new InvalidOperationException("Injected subtree restore callback failure."); -} diff --git a/tests/editor/Inno.Editor.Interactions.Tests/SubtreeRestoreFailureComponent.cs b/tests/editor/Inno.Editor.Interactions.Tests/SubtreeRestoreFailureComponent.cs new file mode 100644 index 000000000..8497ca25e --- /dev/null +++ b/tests/editor/Inno.Editor.Interactions.Tests/SubtreeRestoreFailureComponent.cs @@ -0,0 +1,27 @@ +using System; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.Interactions.Tests; + +[StableTypeID("8503e97b-1845-4ab2-a116-1ece04934a4b")] +[AllowMultipleComponent] +internal sealed class SubtreeRestoreFailureComponent : GameBehavior +{ + internal static bool throwOnDestroy; + + [SerializableProperty] + public int value { get; set; } = 5; + + protected override void OnDestroy() + { + if (throwOnDestroy) + { + throw new InvalidOperationException("Injected subtree destruction callback failure."); + } + } + + [OnSerializableRestored] + private void OnRestored() => throw new InvalidOperationException("Injected subtree restore callback failure."); +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/AtomicEditorSetting.cs b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicEditorSetting.cs new file mode 100644 index 000000000..45c7d9ab8 --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicEditorSetting.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using Inno.Editor.Settings; + +namespace Inno.Editor.PlayMode.Tests; + +[EditorSettingPath("Editor/Atomic Editor/Value")] +public sealed class AtomicEditorSetting : EditorSetting +{ + public static readonly List> SNAPSHOTS = []; + public static bool stage; + public static bool throwOnDraw; + public static bool observe; + + public override EditorSettingObject defaultValue + { + get + { + var value = new EditorSettingObject(); + value.SetAsInt32("value", 0); + return value; + } + } + + protected override void OnDraw(EditorSettingObject setting) + { + if (throwOnDraw) + { + throw new InvalidOperationException("Controlled Settings drawer failure."); + } + if (observe + && (SNAPSHOTS.Count == 0 || !SNAPSHOTS[^1].TryGetTarget(out EditorSettingObject? last) || !ReferenceEquals(last, setting)) + ) { + SNAPSHOTS.Add(new WeakReference(setting)); + } + if (!stage) + { + return; + } + setting.SetAsInt32("value", 42); + stage = false; + } +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectEditor.cs b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectEditor.cs new file mode 100644 index 000000000..df804951a --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectEditor.cs @@ -0,0 +1,19 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.PlayMode.Tests; + +[ProjectSettingPath("Project/Atomic Project/Value")] +public sealed class AtomicProjectEditor : ProjectSettingEditor +{ + public static bool stage; + + protected override void OnDraw(AtomicProjectSetting setting) + { + if (!stage) + { + return; + } + setting.value = 84; + stage = false; + } +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectSetting.cs b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectSetting.cs new file mode 100644 index 000000000..f17faca76 --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/AtomicProjectSetting.cs @@ -0,0 +1,12 @@ +using Inno.Core.Serialization; +using Inno.Core.Settings; + +namespace Inno.Editor.PlayMode.Tests; + +[GenerateSerializationConverter] +[ProjectSettingDefinition("tests.ui.atomic-settings")] +public sealed class AtomicProjectSetting : ISerializable +{ + [SerializableProperty] + public int value { get; set; } +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureComponent.cs b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureComponent.cs new file mode 100644 index 000000000..2d4d70d2c --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureComponent.cs @@ -0,0 +1,19 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.PlayMode.Tests; + +[StableTypeID("942e794b-1c53-45a6-80e6-a641d76fdd09")] +[AllowMultipleComponent] +internal sealed class DirtyCaptureComponent : GameComponent +{ + [SerializableProperty] + public int number; + + [SerializableProperty] + public GameObject? target; + + [SerializableProperty] + public DirtyCaptureValue state { get; set; } = new(); +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValue.cs b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValue.cs new file mode 100644 index 000000000..3215726b2 --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValue.cs @@ -0,0 +1,8 @@ +namespace Inno.Editor.PlayMode.Tests; + +internal sealed class DirtyCaptureValue +{ + internal int value; + internal bool reject; + internal int reads; +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValueConverter.cs b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValueConverter.cs new file mode 100644 index 000000000..b706e1493 --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/DirtyCaptureValueConverter.cs @@ -0,0 +1,22 @@ +using System; +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Editor.PlayMode.Tests; + +internal sealed class DirtyCaptureValueConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + DirtyCaptureValue value + ) { + value.reads++; + writer.Write("value", value.value); + if (value.reject) + { + throw new InvalidOperationException("The test-owned converter rejected capture."); + } + } + + public override DirtyCaptureValue Read(SerializationReader reader) => new() { value = reader.Read("value") }; +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs index 616842bae..7d564c47e 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/EditorPlayModeTests.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Xunit; @@ -13,7 +12,6 @@ using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Mathematics; -using Inno.Core.Serialization; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Editor.Scene; @@ -741,13 +739,3 @@ public void Dispose() } } } - -[StableTypeID("9afec1fd-c1ef-45fa-9bcc-0b3e2877d613")] -internal sealed class PlayModeAssetReferenceBehavior : GameBehavior -{ - /// - /// Gets or sets the asset reference copied into the isolated Play Mode scene. - /// - [SerializableProperty] - public TextAsset? asset { get; set; } -} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeAssetReferenceBehavior.cs b/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeAssetReferenceBehavior.cs new file mode 100644 index 000000000..959d9582a --- /dev/null +++ b/tests/editor/Inno.Editor.PlayMode.Tests/PlayModeAssetReferenceBehavior.cs @@ -0,0 +1,16 @@ +using Inno.Assets; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene; + +namespace Inno.Editor.PlayMode.Tests; + +[StableTypeID("9afec1fd-c1ef-45fa-9bcc-0b3e2877d613")] +internal sealed class PlayModeAssetReferenceBehavior : GameBehavior +{ + /// + /// Gets or sets the asset reference copied into the isolated Play Mode scene. + /// + [SerializableProperty] + public TextAsset? asset { get; set; } +} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs index 77a4e6bb9..14cc2ba5a 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/SceneDirtyCaptureTests.cs @@ -5,8 +5,6 @@ using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; -using Inno.Core.Serialization.Converters; -using Inno.Extensibility.Types; using Inno.Scene; using Inno.Testing.Editor.Native; @@ -184,41 +182,3 @@ GameScene scene ) ); } - -[StableTypeID("942e794b-1c53-45a6-80e6-a641d76fdd09")] -[AllowMultipleComponent] -internal sealed class DirtyCaptureComponent : GameComponent -{ - [SerializableProperty] - public int number; - - [SerializableProperty] - public GameObject? target; - - [SerializableProperty] - public DirtyCaptureValue state { get; set; } = new(); -} - -internal sealed class DirtyCaptureValue -{ - internal int value; - internal bool reject; - internal int reads; -} - -internal sealed class DirtyCaptureValueConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - DirtyCaptureValue value - ) { - value.reads++; - writer.Write("value", value.value); - if (value.reject) - { - throw new InvalidOperationException("The test-owned converter rejected capture."); - } - } - - public override DirtyCaptureValue Read(SerializationReader reader) => new() { value = reader.Read("value") }; -} diff --git a/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs b/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs index 33a375405..7e9aa6b85 100644 --- a/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs +++ b/tests/editor/Inno.Editor.PlayMode.Tests/SettingsApplyNativeTests.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; @@ -7,7 +6,6 @@ using Xunit; using Xunit.Sdk; using Inno.Core.IO; -using Inno.Core.Serialization; using Inno.Core.Settings; using Inno.Editor.Interactions; using Inno.Editor.Settings; @@ -327,65 +325,3 @@ private void Click(Vector2 point) } } } - -[EditorSettingPath("Editor/Atomic Editor/Value")] -public sealed class AtomicEditorSetting : EditorSetting -{ - public static readonly List> SNAPSHOTS = []; - public static bool stage; - public static bool throwOnDraw; - public static bool observe; - - public override EditorSettingObject defaultValue - { - get - { - var value = new EditorSettingObject(); - value.SetAsInt32("value", 0); - return value; - } - } - - protected override void OnDraw(EditorSettingObject setting) - { - if (throwOnDraw) - { - throw new InvalidOperationException("Controlled Settings drawer failure."); - } - if (observe - && (SNAPSHOTS.Count == 0 || !SNAPSHOTS[^1].TryGetTarget(out EditorSettingObject? last) || !ReferenceEquals(last, setting)) - ) { - SNAPSHOTS.Add(new WeakReference(setting)); - } - if (!stage) - { - return; - } - setting.SetAsInt32("value", 42); - stage = false; - } -} - -[GenerateSerializationConverter] -[ProjectSettingDefinition("tests.ui.atomic-settings")] -public sealed class AtomicProjectSetting : ISerializable -{ - [SerializableProperty] - public int value { get; set; } -} - -[ProjectSettingPath("Project/Atomic Project/Value")] -public sealed class AtomicProjectEditor : ProjectSettingEditor -{ - public static bool stage; - - protected override void OnDraw(AtomicProjectSetting setting) - { - if (!stage) - { - return; - } - setting.value = 84; - stage = false; - } -} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ADisposeObserverModule.cs b/tests/editor/Inno.Editor.Presentation.Tests/ADisposeObserverModule.cs new file mode 100644 index 000000000..f06fbfff5 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ADisposeObserverModule.cs @@ -0,0 +1,36 @@ +using System; +using Inno.Editor.Core; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorModule("tests.dispose-observer", order: 900)] +public sealed class ADisposeObserverModule(EditorInteractions interactions) : EditorModule +{ + public static bool historyAvailableDuringStop; + public static bool historyDisposedDuringDispose; + public static int disposeCount; + + protected override void OnStop(EditorContext context) + { + if (interactions.history.isFaulted) + { + return; + } + using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Shutdown probe"); + historyAvailableDuringStop = transaction.Rollback().succeeded; + } + + protected override void OnDispose() + { + disposeCount++; + try + { + using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Disposed probe"); + } + catch (ObjectDisposedException) + { + historyDisposedDuringDispose = true; + } + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/AreaResolveAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/AreaResolveAction.cs new file mode 100644 index 000000000..6fff125a4 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/AreaResolveAction.cs @@ -0,0 +1,11 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.resolve", "tests/special", priority: 100)] +public sealed class AreaResolveAction : EditorAction +{ + protected override EditorActionState Query(EditorActionContext context) => new(true, true, displayName: "area"); + + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/BaseResolveAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/BaseResolveAction.cs new file mode 100644 index 000000000..f8b0ece96 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/BaseResolveAction.cs @@ -0,0 +1,11 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.resolve")] +public sealed class BaseResolveAction : EditorAction +{ + protected override EditorActionState Query(EditorActionContext context) => new(true, true, displayName: "base"); + + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/BaseTarget.cs b/tests/editor/Inno.Editor.Presentation.Tests/BaseTarget.cs new file mode 100644 index 000000000..b771631d5 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/BaseTarget.cs @@ -0,0 +1,4 @@ +namespace Inno.Editor.Presentation.Tests; + +// Open: DerivedTarget derives from it for the action-resolution tests. +public class BaseTarget; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/CommitOnPresentationLostAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/CommitOnPresentationLostAction.cs new file mode 100644 index 000000000..dd7384bc0 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/CommitOnPresentationLostAction.cs @@ -0,0 +1,27 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.commit-on-presentation-lost")] +public sealed class CommitOnPresentationLostAction : EditorAction +{ + private InteractionTarget? m_target; + + protected override void Execute(EditorActionContext context) + { + m_target = context.target; + Activate(context); + } + + protected override void OnPresentationLost() + { + if (m_target is not null) + { + m_target.committedValue = "Committed on focus loss"; + } + m_target = null; + Complete(); + } + + protected override void OnCancelled() => m_target = null; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/DeferredAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/DeferredAction.cs new file mode 100644 index 000000000..35514c600 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/DeferredAction.cs @@ -0,0 +1,11 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.deferred")] +public sealed class DeferredAction : EditorAction +{ + public static int executeCount; + + protected override void Execute(EditorActionContext context) => executeCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/DerivedTarget.cs b/tests/editor/Inno.Editor.Presentation.Tests/DerivedTarget.cs new file mode 100644 index 000000000..fa4f16b89 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/DerivedTarget.cs @@ -0,0 +1,3 @@ +namespace Inno.Editor.Presentation.Tests; + +public sealed class DerivedTarget : BaseTarget; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/DragSource.cs b/tests/editor/Inno.Editor.Presentation.Tests/DragSource.cs new file mode 100644 index 000000000..32cdb2986 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/DragSource.cs @@ -0,0 +1,5 @@ +using Inno.Core.Identity; + +namespace Inno.Editor.Presentation.Tests; + +public sealed class DragSource : IdentityObject; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/DropTarget.cs b/tests/editor/Inno.Editor.Presentation.Tests/DropTarget.cs new file mode 100644 index 000000000..204c3fd8b --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/DropTarget.cs @@ -0,0 +1,6 @@ +namespace Inno.Editor.Presentation.Tests; + +public sealed class DropTarget +{ + public bool wasDropped { get; set; } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/DynamicMenuSource.cs b/tests/editor/Inno.Editor.Presentation.Tests/DynamicMenuSource.cs new file mode 100644 index 000000000..473d26a60 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/DynamicMenuSource.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorMenuSource("tests/menu")] +public sealed class DynamicMenuSource : EditorMenuSource +{ + public override void Build( + EditorMenuContext context, + EditorMenuBuilder builder + ) { + builder.AddGroup("Tools/Create/Libraries", order: 150, separatorBefore: true); + builder.Add("Tools/Create/Libraries/Function", "tests.menu", order: 150); + builder.Add("Tools/Create/Generated", "tests.menu", order: 200); + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs index ff9e12cdf..67c7621ac 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.Commands.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using Xunit; using Inno.Core.Events; using Inno.Core.Input; @@ -67,52 +66,3 @@ public void ShortcutIndexRefreshPreservesDispatchAndRejectsRepeats() Assert.Equal(2, MultiShortcutAction.executeCount); } } - -public sealed class MenuStateTarget -{ - public bool visible = true; - public bool enabled = true; - public bool isChecked; - public string label = "Current"; -} - -[EditorAction("tests.menu-state", "tests/static-menu")] -[EditorMenu("tests/static-menu", "Tools/State")] -public sealed class MenuStateAction : EditorAction -{ - protected override EditorActionState Query(EditorActionContext context) - => context.target is MenuStateTarget target - ? new EditorActionState(target.visible, target.enabled, target.isChecked, target.label, "Current owner is read-only.") - : EditorActionState.hidden; - - protected override void Execute(EditorActionContext context) {} -} - -[EditorAction("tests.menu-fallback", "tests/shared-menu")] -[EditorMenu("tests/shared-menu", "Shared", order: 100)] -public sealed class MenuFallbackAction : EditorAction -{ - protected override void Execute(EditorActionContext context) {} -} - -[EditorAction("tests.menu-conditional", "tests/shared-menu")] -[EditorMenu("tests/shared-menu", "Shared", order: 200)] -public sealed class MenuConditionalAction : EditorAction -{ - protected override EditorActionState Query(EditorActionContext context) - => context.target is MenuStateTarget { visible: true } ? EditorActionState.enabled : EditorActionState.hidden; - - protected override void Execute(EditorActionContext context) {} -} - -[EditorMenuSource("tests/failed-menu")] -public sealed class RejectedMenuSource : EditorMenuSource -{ - public override void Build( - EditorMenuContext context, - EditorMenuBuilder builder - ) { - builder.Add("Partial", "tests.menu"); - throw new InvalidOperationException("Candidate menu source failed."); - } -} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs index 176bebd30..af88150f0 100644 --- a/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs +++ b/tests/editor/Inno.Editor.Presentation.Tests/EditorRuntimeTests.cs @@ -7,17 +7,13 @@ using Inno.Adapter.Modules.DotNet; using Inno.Core.Diagnostics; using Inno.Core.Events; -using Inno.Core.Execution; using Inno.Core.Identity; using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Mathematics; -using Inno.Core.Serialization; -using Inno.Core.Settings; using Inno.Editor.Core; using Inno.Editor.ImGui; using Inno.Editor.Interactions; -using Inno.Editor.Settings; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; @@ -894,523 +890,8 @@ private sealed class TestDiagnosticSink : IDiagnosticSink } } -// Open: DerivedTarget derives from it for the action-resolution tests. -public class BaseTarget; - -public sealed class DerivedTarget : BaseTarget; - -public sealed class DragSource : IdentityObject; - -public sealed class DropTarget -{ - public bool wasDropped { get; set; } -} - -public sealed class InteractionTarget -{ - public string? committedValue { get; set; } - public string? validationMessage { get; set; } -} - public sealed record InteractionPresentation( string value, bool submit, bool cancel = false ); - -[EditorHistoryHandler(NeutralHistoryHandler.C_KIND)] -public sealed class NeutralHistoryHandler : EditorHistoryHandler -{ - public const string C_KIND = "tests/neutral-value"; - public static int value; - - public static EditorHistoryChange CreateChange( - int before, - int after - ) { - var bytes = new byte[sizeof(int) * 2]; - BitConverter.GetBytes(before).CopyTo(bytes, 0); - BitConverter.GetBytes(after).CopyTo(bytes, sizeof(int)); - return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(bytes)); - } - - protected override EditorHistoryAvailability Query( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) => change.payload.length >= sizeof(int) * 2 - ? EditorHistoryAvailability.Available() - : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); - - protected override EditorHistoryResult Apply( - EditorHistoryContext context, - EditorHistoryChange change, - EditorHistoryDirection direction - ) { - byte[] bytes = change.payload.ReadBytes(); - value = BitConverter.ToInt32(bytes, direction == EditorHistoryDirection.Undo ? 0 : sizeof(int)); - return EditorHistoryResult.Success(); - } -} - -public interface ITestHostService; - -public sealed class TestHostService : ITestHostService; - -[EditorPanel("tests.host-service", "Host Service")] -public sealed class HostServicePanel : EditorPanel -{ - public static ITestHostService? current; - - public HostServicePanel(ITestHostService service) - { - current = service; - } - - protected override void OnDraw(EditorContext context) => _ = context; -} - -[EditorModule("tests.state")] -public sealed class TestModule : EditorModule -{ - public static int startCount; - public static int stopCount; - public static int stateValue; - public static int restoredStateValue; - public static bool rebuildDuringRestore; - public static bool captureFailure; - public static bool throwOnStart; - public static bool throwOnStop; - public static int pendingStops; - - private readonly TypeCatalog m_types; - - public TestModule(TypeCatalog types) - { - m_types = types; - } - - protected override void Capture(EditorState state) - { - if (captureFailure) - { - throw new InvalidOperationException("The test module state cannot be captured."); - } - state.Set("value", stateValue); - } - - protected override void Restore(EditorState state) - { - restoredStateValue = state.Get("value", 0); - if (!rebuildDuringRestore) - { - return; - } - rebuildDuringRestore = false; - m_types.Rebuild(); - } - - protected override void OnStart(EditorContext context) - { - startCount++; - if (throwOnStart) - { - throw new InvalidOperationException("Injected module startup failure."); - } - if (startCount == 1) - { - m_types.Rebuild(); - } - } - - protected override void OnStop(EditorContext context) - { - stopCount++; - ShutdownOrder.events.Add("module.stop"); - if (pendingStops-- > 0) - { - throw new RetirementPendingException("Module-owned work has not drained."); - } - if (throwOnStop) - { - throw new InvalidOperationException("Injected module stop failure."); - } - } -} - -[EditorModule("tests.update-barrier", order: -200)] -public sealed class UpdateBarrierModule : EditorModule -{ - public static bool block; - public static bool throwWhenRead; - public static int barrierReadCount; - - public override bool blocksFollowingUpdates - { - get - { - barrierReadCount++; - return throwWhenRead ? throw new InvalidOperationException("Injected module barrier failure.") : block; - } - } -} - -[EditorModule("tests.following-update", order: -199)] -public sealed class FollowingUpdateModule : EditorModule -{ - public static int updateCount; - - protected override void OnUpdate(EditorContext context) => updateCount++; -} - -[EditorPanel("tests.panel", "Test", defaultOpen: false, menuPath: "Testing")] -public sealed class TestPanel(TestModule module) : EditorPanel -{ - public static int attachCount; - public static int detachCount; - public static bool firstAttachPrecededModuleStart; - public static bool throwFromWindowPadding; - public static bool throwOnAttach; - public static bool throwOnDetach; - public static int pendingDetaches; - - public override bool useWindowPadding - => throwFromWindowPadding ? throw new InvalidOperationException("Injected panel presentation failure.") : true; - - protected override void OnAttach(EditorContext context) - { - _ = module; - if (attachCount == 0) - { - firstAttachPrecededModuleStart = TestModule.startCount == 0; - } - attachCount++; - if (throwOnAttach) - { - throw new InvalidOperationException("Injected panel attachment failure."); - } - } - - protected override void OnDetach(EditorContext context) - { - detachCount++; - ShutdownOrder.events.Add("panel.detach"); - if (pendingDetaches-- > 0) - { - throw new RetirementPendingException("Panel-owned work has not drained."); - } - if (throwOnDetach) - { - throw new InvalidOperationException("Injected panel detach failure."); - } - } - - protected override void OnDraw(EditorContext context) {} -} - -[StableTypeID("0fbd66e2-303e-4b35-83a1-fc2b90d58360")] -[ProjectSettingDefinition("tests.editor.multi-presentation")] -public sealed class MultiPresentationSetting : ISerializable -{ - public static ProjectSettingID settingID => new("tests.editor.multi-presentation"); - - [SerializableProperty] - public int value { get; set; } = 7; -} - -[ProjectSettingPath("Project/Tests/Multi/Primary")] -public sealed class PrimaryMultiPresentationEditor : ProjectSettingEditor -{ - protected override void OnDraw(MultiPresentationSetting setting) => _ = setting; -} - -[ProjectSettingPath("Project/Tests/Multi/Secondary")] -public sealed class SecondaryMultiPresentationEditor : ProjectSettingEditor -{ - protected override void OnDraw(MultiPresentationSetting setting) => _ = setting; -} - -[EditorAction("tests.resolve")] -public sealed class BaseResolveAction : EditorAction -{ - protected override EditorActionState Query(EditorActionContext context) => new(true, true, displayName: "base"); - - protected override void Execute(EditorActionContext context) {} -} - -[EditorAction("tests.resolve", "tests/special", priority: 100)] -public sealed class AreaResolveAction : EditorAction -{ - protected override EditorActionState Query(EditorActionContext context) => new(true, true, displayName: "area"); - - protected override void Execute(EditorActionContext context) {} -} - -[EditorAction("tests.deferred")] -public sealed class DeferredAction : EditorAction -{ - public static int executeCount; - - protected override void Execute(EditorActionContext context) => executeCount++; -} - -[EditorAction("tests.action-metadata", "tests/action-metadata")] -public sealed class MetadataAction : EditorAction -{ - public static int targetTypeReadCount; - public static bool throwWhenRead; - - public override Type? targetType - { - get - { - targetTypeReadCount++; - return throwWhenRead ? throw new InvalidOperationException("Action metadata was read at runtime.") : typeof(BaseTarget); - } - } - - protected override void Execute(EditorActionContext context) {} -} - -[EditorAction("tests.multiple-shortcuts", "tests/multiple-shortcuts")] -[EditorShortcut("tests/multiple-shortcuts", KeyCode.F3)] -[EditorShortcut("tests/multiple-shortcuts", KeyCode.F4)] -public sealed class MultiShortcutAction : EditorAction -{ - public static int executeCount; - - protected override void Execute(EditorActionContext context) => executeCount++; -} - -[EditorAction("tests.toolbar", "tests/toolbar")] -[EditorToolbarItem("tests/toolbar", EditorToolbarIcon.Play, "Start Runtime", activeIcon: EditorToolbarIcon.Stop)] -public sealed class ToolbarAction : EditorAction -{ - public static bool isChecked; - public static int executeCount; - - protected override EditorActionState Query(EditorActionContext context) - => new(true, true, isChecked, isChecked ? "Stop Runtime" : "Start Runtime"); - - protected override void Execute(EditorActionContext context) => executeCount++; -} - -[EditorAction("tests.throw-after-activate", "tests/throw-after-activate")] -public sealed class ThrowAfterActivateAction : EditorAction -{ - public static int cancelCount; - - protected override void Execute(EditorActionContext context) - { - Activate(context); - throw new InvalidOperationException("Injected action execution failure."); - } - - protected override void OnCancelled() => cancelCount++; -} - -[EditorModule("tests.dispose-observer", order: 900)] -public sealed class ADisposeObserverModule(EditorInteractions interactions) : EditorModule -{ - public static bool historyAvailableDuringStop; - public static bool historyDisposedDuringDispose; - public static int disposeCount; - - protected override void OnStop(EditorContext context) - { - if (interactions.history.isFaulted) - { - return; - } - using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Shutdown probe"); - historyAvailableDuringStop = transaction.Rollback().succeeded; - } - - protected override void OnDispose() - { - disposeCount++; - try - { - using EditorHistoryTransaction transaction = interactions.history.BeginTransaction("Disposed probe"); - } - catch (ObjectDisposedException) - { - historyDisposedDuringDispose = true; - } - } -} - -[EditorModule("tests.throwing-dispose", order: 901)] -public sealed class ZThrowingDisposeModule : EditorModule -{ - public static bool throwOnDispose; - public static int disposeCount; - - protected override void OnDispose() - { - disposeCount++; - if (throwOnDispose) - { - throw new InvalidOperationException("Injected extension disposal failure."); - } - } -} - -internal static class ShutdownOrder -{ - internal static List events { get; } = []; -} - -[EditorAction("tests.interaction")] -public sealed class InteractionAction : EditorPresentationAction -{ - private string m_value = string.Empty; - - protected override void Execute(EditorActionContext context) - { - m_value = "Initial"; - context.target.validationMessage = null; - Activate(context); - } - - protected override bool Present(EditorActionContext context) - { - InteractionPresentation presentation = context.argument; - if (presentation.cancel) - { - Cancel(); - return true; - } - - m_value = presentation.value; - if (!presentation.submit) - { - return true; - } - if (string.IsNullOrWhiteSpace(m_value)) - { - context.target.validationMessage = "A name is required."; - return true; - } - - context.target.committedValue = m_value; - context.target.validationMessage = null; - Complete(); - return true; - } - - protected override void OnCancelled() => m_value = string.Empty; -} - -[EditorAction("tests.commit-on-presentation-lost")] -public sealed class CommitOnPresentationLostAction : EditorAction -{ - private InteractionTarget? m_target; - - protected override void Execute(EditorActionContext context) - { - m_target = context.target; - Activate(context); - } - - protected override void OnPresentationLost() - { - if (m_target is not null) - { - m_target.committedValue = "Committed on focus loss"; - } - m_target = null; - Complete(); - } - - protected override void OnCancelled() => m_target = null; -} - -[EditorAction("tests.menu")] -[EditorMenu("tests/menu", "Tools/Create/Asset", order: 100)] -public sealed class MenuAction : EditorAction -{ - protected override void Execute(EditorActionContext context) {} -} - -[EditorMenuSource("tests/menu")] -public sealed class DynamicMenuSource : EditorMenuSource -{ - public override void Build( - EditorMenuContext context, - EditorMenuBuilder builder - ) { - builder.AddGroup("Tools/Create/Libraries", order: 150, separatorBefore: true); - builder.Add("Tools/Create/Libraries/Function", "tests.menu", order: 150); - builder.Add("Tools/Create/Generated", "tests.menu", order: 200); - } -} - -[EditorDrop("tests/drop")] -public sealed class TestDrop : EditorDrop -{ - protected override EditorDropStatus Query(EditorDropContext context) => EditorDropStatus.Accept(); - - protected override EditorDropResult Drop(EditorDropContext context) - { - context.target.wasDropped = true; - return EditorDropResult.Accepted(); - } -} - -public sealed class TestDocumentProvider : EditorDocumentProvider -{ - public int openCount { get; private set; } - public int saveCount { get; private set; } - public int closeCount { get; private set; } - public override string id => "tests.documents"; - - public override bool CanOpen(string assetPath) - => assetPath.EndsWith(".ispriteatlas2d", StringComparison.Ordinal) - || assetPath.EndsWith(".itilemap2d", StringComparison.Ordinal); - - public override void Open(EditorDocumentContext context) => openCount++; - - public override bool Save(EditorDocumentContext context) - { - saveCount++; - return true; - } - - public override void Close(EditorDocumentContext context) => closeCount++; -} - -public sealed class TestViewportCoordinates : IEditorViewportCoordinateConverter -{ - public Vector2 ScreenToWorld(Vector2 screenPosition) => screenPosition * 2f; - - public Vector2 WorldToScreen(Vector2 worldPosition) => worldPosition / 2f; -} - -public sealed class TestViewportTool(IEditorHistory history) : EditorViewportTool -{ - public int downCount { get; private set; } - public int upCount { get; private set; } - public override string id => "tests.viewport.paint"; - public override EditorViewportCursor cursor => EditorViewportCursor.Crosshair; - - public override void OnPointerDown( - EditorViewportToolContext context, - EditorViewportPointerEvent pointer - ) { - downCount++; - context.CapturePointer(pointer.pointerID); - context.BeginHistoryGesture("Paint Tile"); - NeutralHistoryHandler.value = 1; - history.RecordApplied("Paint Tile Cell", NeutralHistoryHandler.CreateChange(before: 0, after: 1)); - } - - public override void OnPointerUp( - EditorViewportToolContext context, - EditorViewportPointerEvent pointer - ) { - upCount++; - context.CompleteHistoryGesture(commit: true); - context.ReleasePointer(); - } -} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/FollowingUpdateModule.cs b/tests/editor/Inno.Editor.Presentation.Tests/FollowingUpdateModule.cs new file mode 100644 index 000000000..af22ed09d --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/FollowingUpdateModule.cs @@ -0,0 +1,11 @@ +using Inno.Editor.Core; + +namespace Inno.Editor.Presentation.Tests; + +[EditorModule("tests.following-update", order: -199)] +public sealed class FollowingUpdateModule : EditorModule +{ + public static int updateCount; + + protected override void OnUpdate(EditorContext context) => updateCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/HostServicePanel.cs b/tests/editor/Inno.Editor.Presentation.Tests/HostServicePanel.cs new file mode 100644 index 000000000..d96f7acf5 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/HostServicePanel.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Core; + +namespace Inno.Editor.Presentation.Tests; + +[EditorPanel("tests.host-service", "Host Service")] +public sealed class HostServicePanel : EditorPanel +{ + public static ITestHostService? current; + + public HostServicePanel(ITestHostService service) + { + current = service; + } + + protected override void OnDraw(EditorContext context) => _ = context; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ITestHostService.cs b/tests/editor/Inno.Editor.Presentation.Tests/ITestHostService.cs new file mode 100644 index 000000000..c38437405 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ITestHostService.cs @@ -0,0 +1,3 @@ +namespace Inno.Editor.Presentation.Tests; + +public interface ITestHostService; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/InteractionAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/InteractionAction.cs new file mode 100644 index 000000000..9c68bac5b --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/InteractionAction.cs @@ -0,0 +1,44 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.interaction")] +public sealed class InteractionAction : EditorPresentationAction +{ + private string m_value = string.Empty; + + protected override void Execute(EditorActionContext context) + { + m_value = "Initial"; + context.target.validationMessage = null; + Activate(context); + } + + protected override bool Present(EditorActionContext context) + { + InteractionPresentation presentation = context.argument; + if (presentation.cancel) + { + Cancel(); + return true; + } + + m_value = presentation.value; + if (!presentation.submit) + { + return true; + } + if (string.IsNullOrWhiteSpace(m_value)) + { + context.target.validationMessage = "A name is required."; + return true; + } + + context.target.committedValue = m_value; + context.target.validationMessage = null; + Complete(); + return true; + } + + protected override void OnCancelled() => m_value = string.Empty; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/InteractionTarget.cs b/tests/editor/Inno.Editor.Presentation.Tests/InteractionTarget.cs new file mode 100644 index 000000000..e96736fda --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/InteractionTarget.cs @@ -0,0 +1,7 @@ +namespace Inno.Editor.Presentation.Tests; + +public sealed class InteractionTarget +{ + public string? committedValue { get; set; } + public string? validationMessage { get; set; } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MenuAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MenuAction.cs new file mode 100644 index 000000000..7bcfb8bf1 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MenuAction.cs @@ -0,0 +1,10 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.menu")] +[EditorMenu("tests/menu", "Tools/Create/Asset", order: 100)] +public sealed class MenuAction : EditorAction +{ + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MenuConditionalAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MenuConditionalAction.cs new file mode 100644 index 000000000..57338410c --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MenuConditionalAction.cs @@ -0,0 +1,13 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.menu-conditional", "tests/shared-menu")] +[EditorMenu("tests/shared-menu", "Shared", order: 200)] +public sealed class MenuConditionalAction : EditorAction +{ + protected override EditorActionState Query(EditorActionContext context) + => context.target is MenuStateTarget { visible: true } ? EditorActionState.enabled : EditorActionState.hidden; + + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MenuFallbackAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MenuFallbackAction.cs new file mode 100644 index 000000000..d346096b8 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MenuFallbackAction.cs @@ -0,0 +1,10 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.menu-fallback", "tests/shared-menu")] +[EditorMenu("tests/shared-menu", "Shared", order: 100)] +public sealed class MenuFallbackAction : EditorAction +{ + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MenuStateAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MenuStateAction.cs new file mode 100644 index 000000000..86b02ccb5 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MenuStateAction.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.menu-state", "tests/static-menu")] +[EditorMenu("tests/static-menu", "Tools/State")] +public sealed class MenuStateAction : EditorAction +{ + protected override EditorActionState Query(EditorActionContext context) + => context.target is MenuStateTarget target + ? new EditorActionState(target.visible, target.enabled, target.isChecked, target.label, "Current owner is read-only.") + : EditorActionState.hidden; + + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MenuStateTarget.cs b/tests/editor/Inno.Editor.Presentation.Tests/MenuStateTarget.cs new file mode 100644 index 000000000..e5b67ba00 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MenuStateTarget.cs @@ -0,0 +1,9 @@ +namespace Inno.Editor.Presentation.Tests; + +public sealed class MenuStateTarget +{ + public bool visible = true; + public bool enabled = true; + public bool isChecked; + public string label = "Current"; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MetadataAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MetadataAction.cs new file mode 100644 index 000000000..0d404cb07 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MetadataAction.cs @@ -0,0 +1,22 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.action-metadata", "tests/action-metadata")] +public sealed class MetadataAction : EditorAction +{ + public static int targetTypeReadCount; + public static bool throwWhenRead; + + public override Type? targetType + { + get + { + targetTypeReadCount++; + return throwWhenRead ? throw new InvalidOperationException("Action metadata was read at runtime.") : typeof(BaseTarget); + } + } + + protected override void Execute(EditorActionContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MultiPresentationSetting.cs b/tests/editor/Inno.Editor.Presentation.Tests/MultiPresentationSetting.cs new file mode 100644 index 000000000..5181f28d4 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MultiPresentationSetting.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Core.Settings; +using Inno.Extensibility.Types; + +namespace Inno.Editor.Presentation.Tests; + +[StableTypeID("0fbd66e2-303e-4b35-83a1-fc2b90d58360")] +[ProjectSettingDefinition("tests.editor.multi-presentation")] +public sealed class MultiPresentationSetting : ISerializable +{ + public static ProjectSettingID settingID => new("tests.editor.multi-presentation"); + + [SerializableProperty] + public int value { get; set; } = 7; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/MultiShortcutAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/MultiShortcutAction.cs new file mode 100644 index 000000000..b634b40dd --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/MultiShortcutAction.cs @@ -0,0 +1,14 @@ +using Inno.Core.Input; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.multiple-shortcuts", "tests/multiple-shortcuts")] +[EditorShortcut("tests/multiple-shortcuts", KeyCode.F3)] +[EditorShortcut("tests/multiple-shortcuts", KeyCode.F4)] +public sealed class MultiShortcutAction : EditorAction +{ + public static int executeCount; + + protected override void Execute(EditorActionContext context) => executeCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/NeutralHistoryHandler.cs b/tests/editor/Inno.Editor.Presentation.Tests/NeutralHistoryHandler.cs new file mode 100644 index 000000000..4ca626cab --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/NeutralHistoryHandler.cs @@ -0,0 +1,39 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorHistoryHandler(NeutralHistoryHandler.C_KIND)] +public sealed class NeutralHistoryHandler : EditorHistoryHandler +{ + public const string C_KIND = "tests/neutral-value"; + public static int value; + + public static EditorHistoryChange CreateChange( + int before, + int after + ) { + var bytes = new byte[sizeof(int) * 2]; + BitConverter.GetBytes(before).CopyTo(bytes, 0); + BitConverter.GetBytes(after).CopyTo(bytes, sizeof(int)); + return new EditorHistoryChange(C_KIND, EditorHistoryPayload.FromBytes(bytes)); + } + + protected override EditorHistoryAvailability Query( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) => change.payload.length >= sizeof(int) * 2 + ? EditorHistoryAvailability.Available() + : EditorHistoryAvailability.Unavailable("The neutral value payload is truncated."); + + protected override EditorHistoryResult Apply( + EditorHistoryContext context, + EditorHistoryChange change, + EditorHistoryDirection direction + ) { + byte[] bytes = change.payload.ReadBytes(); + value = BitConverter.ToInt32(bytes, direction == EditorHistoryDirection.Undo ? 0 : sizeof(int)); + return EditorHistoryResult.Success(); + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/PrimaryMultiPresentationEditor.cs b/tests/editor/Inno.Editor.Presentation.Tests/PrimaryMultiPresentationEditor.cs new file mode 100644 index 000000000..8c57dfc6b --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/PrimaryMultiPresentationEditor.cs @@ -0,0 +1,9 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Presentation.Tests; + +[ProjectSettingPath("Project/Tests/Multi/Primary")] +public sealed class PrimaryMultiPresentationEditor : ProjectSettingEditor +{ + protected override void OnDraw(MultiPresentationSetting setting) => _ = setting; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/RejectedMenuSource.cs b/tests/editor/Inno.Editor.Presentation.Tests/RejectedMenuSource.cs new file mode 100644 index 000000000..21b1f02f6 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/RejectedMenuSource.cs @@ -0,0 +1,16 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorMenuSource("tests/failed-menu")] +public sealed class RejectedMenuSource : EditorMenuSource +{ + public override void Build( + EditorMenuContext context, + EditorMenuBuilder builder + ) { + builder.Add("Partial", "tests.menu"); + throw new InvalidOperationException("Candidate menu source failed."); + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/SecondaryMultiPresentationEditor.cs b/tests/editor/Inno.Editor.Presentation.Tests/SecondaryMultiPresentationEditor.cs new file mode 100644 index 000000000..407a688eb --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/SecondaryMultiPresentationEditor.cs @@ -0,0 +1,9 @@ +using Inno.Editor.Settings; + +namespace Inno.Editor.Presentation.Tests; + +[ProjectSettingPath("Project/Tests/Multi/Secondary")] +public sealed class SecondaryMultiPresentationEditor : ProjectSettingEditor +{ + protected override void OnDraw(MultiPresentationSetting setting) => _ = setting; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ShutdownOrder.cs b/tests/editor/Inno.Editor.Presentation.Tests/ShutdownOrder.cs new file mode 100644 index 000000000..73ba0ca74 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ShutdownOrder.cs @@ -0,0 +1,8 @@ +using System.Collections.Generic; + +namespace Inno.Editor.Presentation.Tests; + +internal static class ShutdownOrder +{ + internal static List events { get; } = []; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestDocumentProvider.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestDocumentProvider.cs new file mode 100644 index 000000000..001520a85 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestDocumentProvider.cs @@ -0,0 +1,26 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +public sealed class TestDocumentProvider : EditorDocumentProvider +{ + public int openCount { get; private set; } + public int saveCount { get; private set; } + public int closeCount { get; private set; } + public override string id => "tests.documents"; + + public override bool CanOpen(string assetPath) + => assetPath.EndsWith(".ispriteatlas2d", StringComparison.Ordinal) + || assetPath.EndsWith(".itilemap2d", StringComparison.Ordinal); + + public override void Open(EditorDocumentContext context) => openCount++; + + public override bool Save(EditorDocumentContext context) + { + saveCount++; + return true; + } + + public override void Close(EditorDocumentContext context) => closeCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestDrop.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestDrop.cs new file mode 100644 index 000000000..ea00f846c --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestDrop.cs @@ -0,0 +1,15 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorDrop("tests/drop")] +public sealed class TestDrop : EditorDrop +{ + protected override EditorDropStatus Query(EditorDropContext context) => EditorDropStatus.Accept(); + + protected override EditorDropResult Drop(EditorDropContext context) + { + context.target.wasDropped = true; + return EditorDropResult.Accepted(); + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestHostService.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestHostService.cs new file mode 100644 index 000000000..c184dbbc6 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestHostService.cs @@ -0,0 +1,3 @@ +namespace Inno.Editor.Presentation.Tests; + +public sealed class TestHostService : ITestHostService; diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestModule.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestModule.cs new file mode 100644 index 000000000..998615d4c --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestModule.cs @@ -0,0 +1,74 @@ +using System; +using Inno.Core.Execution; +using Inno.Editor.Core; +using Inno.Extensibility.Types; + +namespace Inno.Editor.Presentation.Tests; + +[EditorModule("tests.state")] +public sealed class TestModule : EditorModule +{ + public static int startCount; + public static int stopCount; + public static int stateValue; + public static int restoredStateValue; + public static bool rebuildDuringRestore; + public static bool captureFailure; + public static bool throwOnStart; + public static bool throwOnStop; + public static int pendingStops; + + private readonly TypeCatalog m_types; + + public TestModule(TypeCatalog types) + { + m_types = types; + } + + protected override void Capture(EditorState state) + { + if (captureFailure) + { + throw new InvalidOperationException("The test module state cannot be captured."); + } + state.Set("value", stateValue); + } + + protected override void Restore(EditorState state) + { + restoredStateValue = state.Get("value", 0); + if (!rebuildDuringRestore) + { + return; + } + rebuildDuringRestore = false; + m_types.Rebuild(); + } + + protected override void OnStart(EditorContext context) + { + startCount++; + if (throwOnStart) + { + throw new InvalidOperationException("Injected module startup failure."); + } + if (startCount == 1) + { + m_types.Rebuild(); + } + } + + protected override void OnStop(EditorContext context) + { + stopCount++; + ShutdownOrder.events.Add("module.stop"); + if (pendingStops-- > 0) + { + throw new RetirementPendingException("Module-owned work has not drained."); + } + if (throwOnStop) + { + throw new InvalidOperationException("Injected module stop failure."); + } + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestPanel.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestPanel.cs new file mode 100644 index 000000000..a7311eb23 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestPanel.cs @@ -0,0 +1,50 @@ +using System; +using Inno.Core.Execution; +using Inno.Editor.Core; + +namespace Inno.Editor.Presentation.Tests; + +[EditorPanel("tests.panel", "Test", defaultOpen: false, menuPath: "Testing")] +public sealed class TestPanel(TestModule module) : EditorPanel +{ + public static int attachCount; + public static int detachCount; + public static bool firstAttachPrecededModuleStart; + public static bool throwFromWindowPadding; + public static bool throwOnAttach; + public static bool throwOnDetach; + public static int pendingDetaches; + + public override bool useWindowPadding + => throwFromWindowPadding ? throw new InvalidOperationException("Injected panel presentation failure.") : true; + + protected override void OnAttach(EditorContext context) + { + _ = module; + if (attachCount == 0) + { + firstAttachPrecededModuleStart = TestModule.startCount == 0; + } + attachCount++; + if (throwOnAttach) + { + throw new InvalidOperationException("Injected panel attachment failure."); + } + } + + protected override void OnDetach(EditorContext context) + { + detachCount++; + ShutdownOrder.events.Add("panel.detach"); + if (pendingDetaches-- > 0) + { + throw new RetirementPendingException("Panel-owned work has not drained."); + } + if (throwOnDetach) + { + throw new InvalidOperationException("Injected panel detach failure."); + } + } + + protected override void OnDraw(EditorContext context) {} +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestViewportCoordinates.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestViewportCoordinates.cs new file mode 100644 index 000000000..d063a0e99 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestViewportCoordinates.cs @@ -0,0 +1,11 @@ +using Inno.Core.Mathematics; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +public sealed class TestViewportCoordinates : IEditorViewportCoordinateConverter +{ + public Vector2 ScreenToWorld(Vector2 screenPosition) => screenPosition * 2f; + + public Vector2 WorldToScreen(Vector2 worldPosition) => worldPosition / 2f; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/TestViewportTool.cs b/tests/editor/Inno.Editor.Presentation.Tests/TestViewportTool.cs new file mode 100644 index 000000000..3392fddf5 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/TestViewportTool.cs @@ -0,0 +1,31 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +public sealed class TestViewportTool(IEditorHistory history) : EditorViewportTool +{ + public int downCount { get; private set; } + public int upCount { get; private set; } + public override string id => "tests.viewport.paint"; + public override EditorViewportCursor cursor => EditorViewportCursor.Crosshair; + + public override void OnPointerDown( + EditorViewportToolContext context, + EditorViewportPointerEvent pointer + ) { + downCount++; + context.CapturePointer(pointer.pointerID); + context.BeginHistoryGesture("Paint Tile"); + NeutralHistoryHandler.value = 1; + history.RecordApplied("Paint Tile Cell", NeutralHistoryHandler.CreateChange(before: 0, after: 1)); + } + + public override void OnPointerUp( + EditorViewportToolContext context, + EditorViewportPointerEvent pointer + ) { + upCount++; + context.CompleteHistoryGesture(commit: true); + context.ReleasePointer(); + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ThrowAfterActivateAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/ThrowAfterActivateAction.cs new file mode 100644 index 000000000..13f58da85 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ThrowAfterActivateAction.cs @@ -0,0 +1,18 @@ +using System; +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.throw-after-activate", "tests/throw-after-activate")] +public sealed class ThrowAfterActivateAction : EditorAction +{ + public static int cancelCount; + + protected override void Execute(EditorActionContext context) + { + Activate(context); + throw new InvalidOperationException("Injected action execution failure."); + } + + protected override void OnCancelled() => cancelCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ToolbarAction.cs b/tests/editor/Inno.Editor.Presentation.Tests/ToolbarAction.cs new file mode 100644 index 000000000..4ee053215 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ToolbarAction.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Interactions; + +namespace Inno.Editor.Presentation.Tests; + +[EditorAction("tests.toolbar", "tests/toolbar")] +[EditorToolbarItem("tests/toolbar", EditorToolbarIcon.Play, "Start Runtime", activeIcon: EditorToolbarIcon.Stop)] +public sealed class ToolbarAction : EditorAction +{ + public static bool isChecked; + public static int executeCount; + + protected override EditorActionState Query(EditorActionContext context) + => new(true, true, isChecked, isChecked ? "Stop Runtime" : "Start Runtime"); + + protected override void Execute(EditorActionContext context) => executeCount++; +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/UpdateBarrierModule.cs b/tests/editor/Inno.Editor.Presentation.Tests/UpdateBarrierModule.cs new file mode 100644 index 000000000..d0d42caa4 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/UpdateBarrierModule.cs @@ -0,0 +1,21 @@ +using System; +using Inno.Editor.Core; + +namespace Inno.Editor.Presentation.Tests; + +[EditorModule("tests.update-barrier", order: -200)] +public sealed class UpdateBarrierModule : EditorModule +{ + public static bool block; + public static bool throwWhenRead; + public static int barrierReadCount; + + public override bool blocksFollowingUpdates + { + get + { + barrierReadCount++; + return throwWhenRead ? throw new InvalidOperationException("Injected module barrier failure.") : block; + } + } +} diff --git a/tests/editor/Inno.Editor.Presentation.Tests/ZThrowingDisposeModule.cs b/tests/editor/Inno.Editor.Presentation.Tests/ZThrowingDisposeModule.cs new file mode 100644 index 000000000..6285d81d0 --- /dev/null +++ b/tests/editor/Inno.Editor.Presentation.Tests/ZThrowingDisposeModule.cs @@ -0,0 +1,20 @@ +using System; +using Inno.Editor.Core; + +namespace Inno.Editor.Presentation.Tests; + +[EditorModule("tests.throwing-dispose", order: 901)] +public sealed class ZThrowingDisposeModule : EditorModule +{ + public static bool throwOnDispose; + public static int disposeCount; + + protected override void OnDispose() + { + disposeCount++; + if (throwOnDispose) + { + throw new InvalidOperationException("Injected extension disposal failure."); + } + } +} diff --git a/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs b/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleHostTests.cs similarity index 99% rename from tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs rename to tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleHostTests.cs index 1d2b778cd..7ec6b8bc8 100644 --- a/tests/extensibility/Inno.Extensibility.Modules.Tests/AssemblyManagerTests.cs +++ b/tests/extensibility/Inno.Extensibility.Modules.Tests/ModuleHostTests.cs @@ -11,7 +11,6 @@ using System.Threading.Tasks; using Xunit; using Inno.Adapter.Modules.DotNet; -using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/AbstractAttributedType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/AbstractAttributedType.cs new file mode 100644 index 000000000..bac6ace83 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/AbstractAttributedType.cs @@ -0,0 +1,4 @@ +namespace Inno.Extensibility.Types.Tests; + +[TestMarker] +public abstract class AbstractAttributedType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/AttributedType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/AttributedType.cs new file mode 100644 index 000000000..58a139e82 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/AttributedType.cs @@ -0,0 +1,4 @@ +namespace Inno.Extensibility.Types.Tests; + +[TestMarker] +public sealed class AttributedType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/DeterministicStableType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/DeterministicStableType.cs new file mode 100644 index 000000000..d568044b6 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/DeterministicStableType.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public sealed class DeterministicStableType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/GeneratedMappedType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/GeneratedMappedType.cs new file mode 100644 index 000000000..a22e04d59 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/GeneratedMappedType.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public sealed class GeneratedMappedType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/ITestContract.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/ITestContract.cs new file mode 100644 index 000000000..0ab726418 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/ITestContract.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public interface ITestContract; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideNamespaceType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideNamespaceType.cs index 49b7bdaf5..9c0ec6716 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideNamespaceType.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideNamespaceType.cs @@ -1,8 +1,3 @@ -using Inno.Extensibility.Types; - namespace ExternalNamespace; public sealed class OutsideNamespaceType; - -[StableTypeID("33333333-3333-3333-3333-333333333333")] -public sealed class OutsideStableAnnotatedType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideStableAnnotatedType.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideStableAnnotatedType.cs new file mode 100644 index 000000000..0b6f8d19d --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/OutsideStableAnnotatedType.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace ExternalNamespace; + +[StableTypeID("33333333-3333-3333-3333-333333333333")] +public sealed class OutsideStableAnnotatedType; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeA.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeA.cs new file mode 100644 index 000000000..454f181d8 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeA.cs @@ -0,0 +1,4 @@ +namespace Inno.Extensibility.Types.Tests; + +[StableTypeID("11111111-1111-1111-1111-111111111111")] +public sealed class StableAnnotatedTypeA; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs new file mode 100644 index 000000000..c14706abd --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs @@ -0,0 +1,4 @@ +namespace Inno.Extensibility.Types.Tests; + +[StableTypeID("22222222-2222-2222-2222-222222222222")] +public struct StableAnnotatedTypeB; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractContractImpl.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractContractImpl.cs new file mode 100644 index 000000000..c042d0c37 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractContractImpl.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public abstract class TestAbstractContractImpl : ITestContract; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractDerived.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractDerived.cs new file mode 100644 index 000000000..65d598990 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestAbstractDerived.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public abstract class TestAbstractDerived : TestBase; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestBase.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestBase.cs new file mode 100644 index 000000000..c4a2acc85 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestBase.cs @@ -0,0 +1,4 @@ +namespace Inno.Extensibility.Types.Tests; + +// Open: TestDerived and TestAbstractDerived derive from it for the subtype queries. +public class TestBase; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestContractImpl.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestContractImpl.cs new file mode 100644 index 000000000..dce36e796 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestContractImpl.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public sealed class TestContractImpl : ITestContract; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestDerived.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestDerived.cs new file mode 100644 index 000000000..6304a17b6 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestDerived.cs @@ -0,0 +1,3 @@ +namespace Inno.Extensibility.Types.Tests; + +public sealed class TestDerived : TestBase; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TestMarkerAttribute.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TestMarkerAttribute.cs new file mode 100644 index 000000000..20e2c5b04 --- /dev/null +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TestMarkerAttribute.cs @@ -0,0 +1,6 @@ +using System; + +namespace Inno.Extensibility.Types.Tests; + +[AttributeUsage(AttributeTargets.Class)] +public sealed class TestMarkerAttribute : Attribute; diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs index 446a2cf7a..d3120acef 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/TypeCacheTests.cs @@ -7,7 +7,6 @@ using Inno.Adapter.Modules.DotNet; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; -using Inno.Extensibility.Types; namespace Inno.Extensibility.Types.Tests; @@ -315,35 +314,3 @@ Exception exception internal sealed record Snapshot(int id); } } - -// Open: TestDerived and TestAbstractDerived derive from it for the subtype queries. -public class TestBase; - -public sealed class TestDerived : TestBase; - -public abstract class TestAbstractDerived : TestBase; - -public interface ITestContract; - -public sealed class TestContractImpl : ITestContract; - -public abstract class TestAbstractContractImpl : ITestContract; - -[AttributeUsage(AttributeTargets.Class)] -public sealed class TestMarkerAttribute : Attribute; - -[TestMarker] -public sealed class AttributedType; - -[TestMarker] -public abstract class AbstractAttributedType; - -[StableTypeID("11111111-1111-1111-1111-111111111111")] -public sealed class StableAnnotatedTypeA; - -[StableTypeID("22222222-2222-2222-2222-222222222222")] -public struct StableAnnotatedTypeB; - -public sealed class DeterministicStableType; - -public sealed class GeneratedMappedType; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/FirstConflictingExtension.cs b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/FirstConflictingExtension.cs new file mode 100644 index 000000000..03ea205ca --- /dev/null +++ b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/FirstConflictingExtension.cs @@ -0,0 +1,9 @@ +using Inno.Extensibility.Types; + +namespace Inno.Extensibility.Modules.TestModule; + +/// +/// Declares the first half of an intentional stable-type-identity collision in a rejected candidate module. +/// +[StableTypeID("44a4cda2-a03e-4918-8db2-f37048a9e4f1")] +public sealed class FirstConflictingExtension; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/ConflictingExtensions.cs b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/SecondConflictingExtension.cs similarity index 57% rename from tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/ConflictingExtensions.cs rename to tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/SecondConflictingExtension.cs index bcf901775..ba8fc0fed 100644 --- a/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/ConflictingExtensions.cs +++ b/tests/extensibility/fixtures/Inno.Extensibility.Modules.TestModule.Invalid/SecondConflictingExtension.cs @@ -2,12 +2,6 @@ namespace Inno.Extensibility.Modules.TestModule; -/// -/// Declares the first half of an intentional stable-type-identity collision in a rejected candidate module. -/// -[StableTypeID("44a4cda2-a03e-4918-8db2-f37048a9e4f1")] -public sealed class FirstConflictingExtension; - /// /// Repeats the first declaration's identity so candidate admission must preserve the previous valid generation. /// diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkedType.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkedType.cs new file mode 100644 index 000000000..0704324b5 --- /dev/null +++ b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkedType.cs @@ -0,0 +1,7 @@ +namespace Inno.Extensibility.Types.TestAssets.A; + +/// +/// Provides a marked declaration whose visibility follows fixture assembly A's active source registration. +/// +[AssemblyAMarker] +public sealed class AssemblyAMarkedType; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyATypes.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkerAttribute.cs similarity index 58% rename from tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyATypes.cs rename to tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkerAttribute.cs index cc3f08153..abb010d51 100644 --- a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyATypes.cs +++ b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyA/AssemblyAMarkerAttribute.cs @@ -7,9 +7,3 @@ namespace Inno.Extensibility.Types.TestAssets.A; /// [AttributeUsage(AttributeTargets.Class)] public sealed class AssemblyAMarkerAttribute : Attribute; - -/// -/// Provides a marked declaration whose visibility follows fixture assembly A's active source registration. -/// -[AssemblyAMarker] -public sealed class AssemblyAMarkedType; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkedType.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkedType.cs new file mode 100644 index 000000000..a65d3fd49 --- /dev/null +++ b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkedType.cs @@ -0,0 +1,7 @@ +namespace Inno.Extensibility.Types.TestAssets.B; + +/// +/// Provides a distinct marked declaration for combined-source discovery and source-removal tests. +/// +[AssemblyBMarker] +public sealed class AssemblyBMarkedType; diff --git a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBTypes.cs b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkerAttribute.cs similarity index 59% rename from tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBTypes.cs rename to tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkerAttribute.cs index 155f40eab..c0cb4f16b 100644 --- a/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBTypes.cs +++ b/tests/extensibility/fixtures/Inno.Extensibility.Types.TestAssemblyB/AssemblyBMarkerAttribute.cs @@ -7,9 +7,3 @@ namespace Inno.Extensibility.Types.TestAssets.B; /// [AttributeUsage(AttributeTargets.Class)] public sealed class AssemblyBMarkerAttribute : Attribute; - -/// -/// Provides a distinct marked declaration for combined-source discovery and source-removal tests. -/// -[AssemblyBMarker] -public sealed class AssemblyBMarkedType; diff --git a/tests/plugins/Inno.Plugins.Tests/PluginDefaultTestSetting.cs b/tests/plugins/Inno.Plugins.Tests/PluginDefaultTestSetting.cs new file mode 100644 index 000000000..9b3c079e7 --- /dev/null +++ b/tests/plugins/Inno.Plugins.Tests/PluginDefaultTestSetting.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Core.Settings; +using Inno.Extensibility.Types; + +namespace Inno.Plugins.Authoring.Tests; + +[StableTypeID("706c1248-478b-43f1-a44d-98a1a8f7b919")] +[ProjectSettingDefinition("tests.plugins.default")] +internal sealed class PluginDefaultTestSetting : ISerializable +{ + [SerializableProperty] + public int value { get; set; } = 1; + + internal static ProjectSettingID id => new("tests.plugins.default"); +} diff --git a/tests/plugins/Inno.Plugins.Tests/PluginSourceSerializationCollection.cs b/tests/plugins/Inno.Plugins.Tests/PluginSourceSerializationCollection.cs new file mode 100644 index 000000000..a8de2d9fe --- /dev/null +++ b/tests/plugins/Inno.Plugins.Tests/PluginSourceSerializationCollection.cs @@ -0,0 +1,6 @@ +using Xunit; + +namespace Inno.Plugins.Authoring.Tests; + +[CollectionDefinition("Plugin source serialization", DisableParallelization = true)] +public sealed class PluginSourceSerializationCollection; diff --git a/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs b/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs index 966b0ca19..efcd0b6ab 100644 --- a/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs +++ b/tests/plugins/Inno.Plugins.Tests/PluginSourceServiceTests.cs @@ -20,8 +20,6 @@ using Inno.Core.Settings; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Inno.Plugins; -using Inno.Plugins.Authoring; namespace Inno.Plugins.Authoring.Tests; @@ -982,31 +980,3 @@ byte[] bytes output.Write(bytes); } } - -[CollectionDefinition("Plugin source serialization", DisableParallelization = true)] -public sealed class PluginSourceSerializationCollection; - -[StableTypeID("706c1248-478b-43f1-a44d-98a1a8f7b919")] -[ProjectSettingDefinition("tests.plugins.default")] -internal sealed class PluginDefaultTestSetting : ISerializable -{ - [SerializableProperty] - public int value { get; set; } = 1; - - internal static ProjectSettingID id => new("tests.plugins.default"); -} - -internal sealed class TestAssetSourceMeta : ISerializable -{ - [SerializableProperty] - public Guid persistentId { get; set; } - - [SerializableProperty] - public int sourceKind { get; set; } - - [SerializableProperty] - public string importerId { get; set; } = string.Empty; - - [SerializableProperty] - public byte[] importerSettingsBytes { get; set; } = []; -} diff --git a/tests/plugins/Inno.Plugins.Tests/TestAssetSourceMeta.cs b/tests/plugins/Inno.Plugins.Tests/TestAssetSourceMeta.cs new file mode 100644 index 000000000..ec2c97e6a --- /dev/null +++ b/tests/plugins/Inno.Plugins.Tests/TestAssetSourceMeta.cs @@ -0,0 +1,19 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Plugins.Authoring.Tests; + +internal sealed class TestAssetSourceMeta : ISerializable +{ + [SerializableProperty] + public Guid persistentId { get; set; } + + [SerializableProperty] + public int sourceKind { get; set; } + + [SerializableProperty] + public string importerId { get; set; } = string.Empty; + + [SerializableProperty] + public byte[] importerSettingsBytes { get; set; } = []; +} diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs index b061f6b0f..59b3d83b9 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/MeshAndStateTests.cs @@ -1,18 +1,11 @@ using System; -using System.Buffers.Binary; -using System.Collections.Generic; -using System.IO; -using System.Text; using Xunit; using Inno.Adapter.Modules.DotNet; using Inno.Adapter.Serialization.DotNet; -using Inno.Assets; using Inno.Core.Mathematics; using Inno.Core.Serialization; using Inno.Extensibility.Modules; using Inno.Extensibility.Types; -using Inno.Rendering; -using Inno.Rendering.Assets; namespace Inno.Rendering.Assets.Authoring.Tests; @@ -244,6 +237,3 @@ private static GraphicsCapabilities CreateCapabilities(GraphicsCapability featur homogeneousDepth: false ); } - -[CollectionDefinition("Rendering assets serialization", DisableParallelization = true)] -public sealed class RenderingAssetsSerializationCollection; diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetSourceMeta.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetSourceMeta.cs new file mode 100644 index 000000000..9159069a4 --- /dev/null +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetSourceMeta.cs @@ -0,0 +1,19 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Assets.Authoring.Tests; + +internal sealed class RenderingAssetSourceMeta : ISerializable +{ + [SerializableProperty] + public Guid persistentId { get; set; } + + [SerializableProperty] + public int sourceKind { get; set; } + + [SerializableProperty] + public string importerId { get; set; } = string.Empty; + + [SerializableProperty] + public byte[] importerSettingsBytes { get; set; } = []; +} diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetsSerializationCollection.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetsSerializationCollection.cs new file mode 100644 index 000000000..cd12d037a --- /dev/null +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingAssetsSerializationCollection.cs @@ -0,0 +1,6 @@ +using Xunit; + +namespace Inno.Rendering.Assets.Authoring.Tests; + +[CollectionDefinition("Rendering assets serialization", DisableParallelization = true)] +public sealed class RenderingAssetsSerializationCollection; diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImportSettingsEnvelope.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImportSettingsEnvelope.cs new file mode 100644 index 000000000..cdf7c65e3 --- /dev/null +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImportSettingsEnvelope.cs @@ -0,0 +1,16 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Rendering.Assets.Authoring.Tests; + +internal sealed class RenderingImportSettingsEnvelope : ISerializable +{ + [SerializableProperty] + public Guid stableTypeId { get; set; } + + [SerializableProperty] + public byte[] properties { get; set; } = []; + + [SerializableProperty] + public Guid[] dependencies { get; set; } = []; +} diff --git a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs index 3e8519629..fbe53ca61 100644 --- a/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs +++ b/tests/rendering/Inno.Rendering.Assets.Authoring.Tests/RenderingImporterIntegrationTests.cs @@ -19,8 +19,6 @@ using Inno.Extensibility.Modules; using Inno.Extensibility.Types; using Inno.Integration.MacOSArm64.Bgfx; -using Inno.Rendering.Assets; -using Inno.Rendering.Assets.Authoring; using Inno.Rendering.Runtime; using Inno.Rendering.Shaders; @@ -505,30 +503,3 @@ private struct NestedPipelineReferences [StableTypeID("830a7851-bc19-44d4-a6e6-a6c38f6bb972")] private sealed class OtherPipelineSettings : ISerializable; } - -internal sealed class RenderingAssetSourceMeta : ISerializable -{ - [SerializableProperty] - public Guid persistentId { get; set; } - - [SerializableProperty] - public int sourceKind { get; set; } - - [SerializableProperty] - public string importerId { get; set; } = string.Empty; - - [SerializableProperty] - public byte[] importerSettingsBytes { get; set; } = []; -} - -internal sealed class RenderingImportSettingsEnvelope : ISerializable -{ - [SerializableProperty] - public Guid stableTypeId { get; set; } - - [SerializableProperty] - public byte[] properties { get; set; } = []; - - [SerializableProperty] - public Guid[] dependencies { get; set; } = []; -} diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs index 0ee7b1fc3..163035f54 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/EmptyRenderingKernelTests.cs @@ -1,29 +1,6 @@ using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; using Xunit; -using Inno.Adapter.Modules.DotNet; -using Inno.Adapter.Serialization.DotNet; -using Inno.Assets; -using Inno.Core.Diagnostics; -using Inno.Core.Execution; -using Inno.Core.Identity; -using Inno.Core.Input; -using Inno.Core.Mathematics; -using Inno.Core.Serialization; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Reload; -using Inno.Extensibility.Types; -using Inno.Input; -using Inno.References; -using Inno.Rendering; using Inno.Rendering.Assets; -using Inno.Rendering.Runtime; -using Inno.Runtime.Contracts; namespace Inno.Rendering.Runtime.Tests; @@ -71,2480 +48,3 @@ public void OpenShaderProtocolsRemainBackendNeutral() Assert.Contains(publicTypes, static type => type == typeof(ShaderPassRoleID)); } } - -public sealed partial class RenderRuntimeGenerationTests : IDisposable -{ - private readonly string m_cacheDirectory = Path.Combine( - Path.GetTempPath(), - "InnoRenderRuntimeTests", - Guid.NewGuid().ToString("N") - ); - - private readonly IdentityAllocator m_identities; - private readonly IDisposable m_identityScope; - private readonly ModuleHost m_modules; - private readonly TypeCatalog m_types; - private readonly SerializationRegistry m_serialization; - - public RenderRuntimeGenerationTests() - { - _ = typeof(TextureAsset); - m_identities = new IdentityAllocator(); - m_identityScope = m_identities.EnterScope(); - m_modules = new ModuleHost( - new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly)} - ); - m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); - m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); - ResourceProbePipeline.action = null; - DisposablePipeline.Reset(); - PendingFeature.Reset(); - TestRequestProvider.Reset(); - FirstTestRenderModel.Reset(); - SecondTestRenderModel.Reset(); - CompositionLayerPipeline.viewports.Clear(); - UploadPipeline.Reset(); - TexturePrewarmPipeline.texture = null; - PendingShaderPipeline.Reset(); - ReadbackPipeline.Reset(); - PresentationPipeline.Reset(); - } - - public void Dispose() - { - ResourceProbePipeline.action = null; - m_serialization.Dispose(); - m_types.Dispose(); - m_modules.Dispose(); - m_identityScope.Dispose(); - if (Directory.Exists(m_cacheDirectory)) - { - Directory.Delete(m_cacheDirectory, recursive: true); - } - } - - [Fact] - public void GeometryCandidatePublishesACompletePairAndPreservesOldPairAfterPartialAllocationFailure() - { - IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); - using var runtime = new RenderRuntime(m_types, backend, new TestDiagnosticSink()); - var owner = new AssetRuntimeOwner(); - var geometry = new GeometryAsset(3, 3, 1, default, default); - m_identities.Register(geometry); - byte[] bytes = GeometryArtifact.Encode( - new GeometryData( - [ - new GeometryVertex(default, default, default, default), - new GeometryVertex(default, default, default, default), - new GeometryVertex(default, default, default, default) - ], - [0, 1, 2], - [new GeometrySection(0, 3)] - ) - ); - owner.Initialize(geometry, AssetPath.Project("triangle.obj"), "first", bytes, false, 1); - RenderGeometry? first = null; - ResourceProbePipeline.action = resources => resources.TryResolveGeometry(geometry, out first); - RunResourceFrame(runtime); - Assert.NotNull(first); - Assert.Equal(2, device.createdBuffers.Count); - device.failBufferCreationAt = 4; - owner.Initialize(geometry, AssetPath.Project("triangle.obj"), "second", bytes, false, 2); - RenderGeometry? failed = null; - ResourceProbePipeline.action = resources => resources.TryResolveGeometry(geometry, out failed); - RunResourceFrame(runtime); - Assert.NotNull(failed); - Assert.Equal(first!.vertexBuffer, failed!.vertexBuffer); - Assert.Equal(first.indexBuffer, failed.indexBuffer); - Assert.Equal(device.createdBuffers[2], Assert.Single(device.destroyedBuffers)); - device.failBufferCreationAt = 0; - RunResourceFrame(runtime); - Assert.NotEqual(first.vertexBuffer, failed.vertexBuffer); - Assert.NotEqual(first.indexBuffer, failed.indexBuffer); - Assert.Equal(3, device.destroyedBuffers.Count); - runtime.Dispose(); - Assert.Equal(device.createdBuffers.Count, device.destroyedBuffers.Count); - owner.Release(geometry); - m_identities.Unregister(geometry); - ResourceProbePipeline.action = null; - } - - [Fact] - public void PersistentResourceAdmissionAndReplacementStayBoundedAcrossFrames() - { - IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); - using var runtime = new RenderRuntime( - m_types, - backend, - new TestDiagnosticSink(), - resourceLimits: new RenderResourceLimits { resourcesPerKind = 1 } - ); - var descriptor = new PersistentBufferDescriptor(new RenderBufferDescriptor(4, 4, RenderBufferUsage.Storage)); - int rejected = 0; - for (int frame = 0; frame < 256; frame++) - { - long revision = frame; - ResourceProbePipeline.action = resources => - { - _ = resources.AcquireBuffer(new RenderPersistentResourceID("owned"), revision, descriptor, new byte[16], "owned"); - try - { - resources.AcquireBuffer(new RenderPersistentResourceID("overflow"), revision, descriptor, new byte[16], "overflow"); - } - catch (InvalidOperationException) - { - rejected++; - } - }; - RunResourceFrame(runtime); - Assert.Equal(1, runtime.resourceStatistics.activeResources); - } - Assert.Equal(256, rejected); - Assert.Equal(256, runtime.resourceStatistics.rejectedResources); - runtime.Dispose(); - Assert.Equal(256, device.createdBuffers.Count); - Assert.Equal(256, device.destroyedBuffers.Count); - ResourceProbePipeline.action = null; - } - - [Fact] - public async Task ReadbackAdmissionIsRejectedBeforeAllocatingASecondNativeOperation() - { - var device = new RecordingRenderDevice(supportsReadback: true); - using var runtime = new RenderRuntime( - m_types, - device, - new TestDiagnosticSink(), - resourceLimits: new RenderResourceLimits { pendingReadbacks = 1 } - ); - Task? readback = null; - bool rejected = false; - ResourceProbePipeline.action = resources => - { - readback = resources.ReadTextureAsync(device.textureHandle).AsTask(); - try - { - _ = resources.ReadTextureAsync(device.textureHandle); - } - catch (InvalidOperationException) - { - rejected = true; - } - }; - RunResourceFrame(runtime); - ResourceProbePipeline.action = null; - Assert.True(rejected); - Assert.Equal(1, runtime.resourceStatistics.pendingReadbacks); - Assert.Equal(1, runtime.resourceStatistics.rejectedReadbacks); - runtime.Dispose(); - await Assert.ThrowsAsync(() => readback!); - Assert.Equal(1, device.cancelReadbackCount); - } - - [Fact] - public void SuccessfulTypeCacheChangeRetiresUnrequestedPipelineAtFrameBoundary() - { - IRenderDevice device = TestDeviceProxy.Create(out _); - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID }; - - Assert.True(runtime.TryActivateDefaultPipeline(asset)); - Assert.Equal(1, DisposablePipeline.createdCount); - Assert.Equal(0, DisposablePipeline.disposedCount); - - m_types.Rebuild(); - BeginRenderFrame(runtime, 0f); - - Assert.Equal(1, DisposablePipeline.disposedCount); - - runtime.AfterRender(default); - runtime.EndFrame(default); - runtime.Detach(); - } - - [Fact] - public void PendingProviderRetirementIsRetriedBeforeTheSnapshotIsReleased() - { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); - Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID })); - TestRequestProvider.pendingRetirements = 2; - - m_types.Rebuild(); - - Assert.Equal(3, TestRequestProvider.retirementAttempts); - Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID })); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void InvalidInitialContributorsFailBeforeRegisteringAnExtensionOwner(bool duplicate) - { - var contributor = new SideEffectContributor(); - IRenderFrameGraphContributor[] contributors = duplicate ? [contributor, contributor] : [null!]; - Assert.Throws(() => new RenderRuntime( - m_types, - TestDeviceProxy.Create(out _), - new TestDiagnosticSink(), - contributors - )); - m_types.Rebuild(); - Assert.Equal(0, TestRequestProvider.retirementAttempts); - } - - [Fact] - public void PendingFeatureRetirementKeepsItsPipelineAliveUntilQuiescent() - { - var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy device), new TestDiagnosticSink()); - Assert.True( - runtime.TryActivateDefaultPipeline(new RenderPipelineAsset - { - pipelineTypeId = DisposablePipeline.C_EXTENSION_ID, - features = [new RenderFeatureConfiguration(PendingFeature.C_EXTENSION_ID)] - }) - ); - PendingFeature.pendingRetirements = 2; - DisposablePipeline.pendingRetirements = 1; - - runtime.Dispose(); - runtime.Dispose(); - - Assert.Equal(3, PendingFeature.retirementAttempts); - Assert.Equal(2, DisposablePipeline.retirementAttempts); - Assert.Equal(1, DisposablePipeline.disposedCount); - Assert.Equal(1, device.endFrameCount); - Assert.Throws(() => runtime.Submit(CreateRequest("Late", new RenderPipelineAsset()))); - } - - [Fact] - public void RejectedPipelineWaitsForItsCandidateToRetireBeforeKeepingLastGood() - { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); - var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID }; - Assert.True(runtime.TryActivateDefaultPipeline(asset)); - DisposablePipeline.rejectConfiguration = true; - DisposablePipeline.pendingRetirements = 2; - asset.pipelineState = new SerializedRenderExtensionState(Guid.NewGuid(), [1]); - - Assert.True(runtime.TryActivateDefaultPipeline(asset)); - - Assert.Equal(3, DisposablePipeline.retirementAttempts); - Assert.Equal(1, DisposablePipeline.disposedCount); - DisposablePipeline.rejectConfiguration = false; - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void ReloadRetirementDrainsPendingBeforeFinishingTheTransaction(bool commit) - { - using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); - Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID })); - IRenderRuntimeReloadTransaction transaction = runtime.BeginExtensionReload(); - transaction.Prepare(); - transaction.Activate(); - DisposablePipeline.pendingRetirements = 2; - - if (commit) - { - transaction.Complete(); - } - else - { - transaction.Rollback(); - } - - Assert.Equal(3, DisposablePipeline.retirementAttempts); - Assert.Equal(1, DisposablePipeline.disposedCount); - runtime.BeginExtensionReload().Rollback(); - } - - [Fact] - public void TargetCapacityRejectsBeforeNativeAllocationAndReopensAfterRelease() - { - IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); - using var targets = new RenderTargetStore(backend, capacity: 1); - backend.BeginFrame(); - var descriptor = new RenderTextureDescriptor( - 16, - 16, - RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment - ); - var first = new RenderTexture("First", descriptor); - var second = new RenderTexture("Second", descriptor); - var graph = new RenderGraphBuilder(1, backend.capabilities); - targets.Import(graph, first); - Assert.Throws(() => targets.Import(graph, second)); - Assert.Single(device.createdTextures); - Assert.Equal(1, targets.rejectedCount); - targets.Release(first); - targets.PrepareFrame(); - targets.Import(new RenderGraphBuilder(2, backend.capabilities), second); - Assert.Equal(1, targets.count); - targets.Dispose(); - Assert.Equal(device.createdTextures.Count, device.destroyedTextures.Count); - backend.EndFrame(); - } - - [Fact] - public void UploadAdmissionResetsEachFrameWithoutGrowingResidentPages() - { - IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); - using var runtime = new RenderRuntime(m_types, backend, new TestDiagnosticSink(), resourceLimits: - new RenderResourceLimits { uploadPages = 1, uploadResidentBytes = 4096, uploadBytesPerFrame = 36 }); - for (int frame = 0; frame < 256; frame++) - { - runtime.Submit(CreateRequest("Upload budget", new RenderPipelineAsset { pipelineTypeId = UploadPipeline.C_EXTENSION_ID })); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(1, runtime.resourceStatistics.uploadPages); - Assert.Equal(36, runtime.resourceStatistics.uploadedFrameBytes); - } - Assert.Equal(256, runtime.resourceStatistics.rejectedUploads); - Assert.Single(device.createdBuffers); - runtime.Dispose(); - Assert.Single(device.destroyedBuffers); - } - - [Fact] - public void TargetRetirementRetainsProgressAndOrdinaryErrorsAcrossPendingRetries() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var targets = new RenderTargetStore(device); - device.BeginFrame(); - var descriptor = new RenderTextureDescriptor( - 16, - 16, - RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment - ); - var graph = new RenderGraphBuilder(1, device.capabilities); - targets.Import(graph, new RenderTexture("First", descriptor)); - targets.Import(graph, new RenderTexture("Second", descriptor)); - targets.Import(graph, new RenderTexture("Third", descriptor)); - proxy.failFirstTextureRetirement = true; - proxy.pendingTextureRetirement = proxy.createdTextures[1]; - - Assert.Throws(targets.Dispose); - Assert.Equal(2, proxy.textureRetirementAttempts); - Assert.True(proxy.frameOpen); - Assert.Throws(() => targets.Import(graph, new RenderTexture("Late", descriptor))); - Assert.Throws(targets.Dispose); - Assert.Equal(4, proxy.textureRetirementAttempts); - Assert.Equal(proxy.createdTextures.Skip(1), proxy.destroyedTextures); - targets.Dispose(); - Assert.Equal(4, proxy.textureRetirementAttempts); - device.EndFrame(); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void TerminalPipelineRetirementBlocksAdmissionAndPreservesLowerOwners(bool duringFrame) - { - var modules = new ModuleHost(new ModuleHostOptions - { - catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly) - }); - var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); - var runtime = new RenderRuntime(types, TestDeviceProxy.Create(out TestDeviceProxy device), new TestDiagnosticSink()); - var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID }; - Assert.True(runtime.TryActivateDefaultPipeline(asset)); - DisposablePipeline.retirementExpired = true; - try - { - if (duringFrame) - { - asset.pipelineState = new SerializedRenderExtensionState(Guid.NewGuid(), [1]); - DisposablePipeline.rejectConfiguration = true; - runtime.Submit(CreateRequest("Faulting candidate", asset)); - BeginRenderFrame(runtime, 0f); - Assert.Throws(() => runtime.AfterRender(default)); - Assert.True(device.frameOpen); - } - else - { - Assert.Throws(runtime.Dispose); - } - Assert.Throws(() => runtime.Submit(CreateRequest("Late", new RenderPipelineAsset()))); - Assert.Throws(() => runtime.RegisterContributor(new SideEffectContributor())); - Assert.Throws(() => runtime.BeginExtensionReload()); - Assert.ThrowsAny(() => types.Rebuild()); - Assert.Equal(1, DisposablePipeline.retirementAttempts); - Assert.Equal(0, TestRequestProvider.retirementAttempts); - Assert.Equal(0, device.endFrameCount); - - DisposablePipeline.retirementExpired = false; - Assert.ThrowsAny(runtime.Dispose); - Assert.ThrowsAny(types.Dispose); - Assert.ThrowsAny(modules.Dispose); - Assert.Equal(1, DisposablePipeline.retirementAttempts); - Assert.Equal(0, device.endFrameCount); - } - finally - { - DisposablePipeline.retirementExpired = false; - DisposablePipeline.rejectConfiguration = false; - } - } - - [Fact] - public void RuntimeKeepsItsMaintenanceFrameOpenUntilTargetsFinishRetiring() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - var target = new RenderTexture( - "Pending Target", - new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment) - ); - runtime.Submit( - new RenderRequest( - "Target", - RenderTarget.FromTexture(target), - new RenderViewport(0, 0, 16, 16), - new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID } - ) - ); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - proxy.pendingTextureRetirement = Assert.Single(proxy.createdTextures); - - runtime.Dispose(); - - Assert.Equal(2, proxy.textureRetirementAttempts); - Assert.Single(proxy.destroyedTextures); - Assert.False(proxy.frameOpen); - Assert.Equal(2, proxy.endFrameCount); - } - - [Fact] - public void RemovingAndRestoringPluginRenderingCommitsTheSameUnavailableStateAsColdStart() - { - const string C_EXTENSION_ID = "tests.runtime.reloadable-plugin"; - DotNetModuleSource plugin = CreateRenderingPluginRequest(); - AssemblyModuleHandle activeModule = m_modules.Load(plugin); - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var diagnostics = new TestDiagnosticSink(); - using var runtime = new RenderRuntime(m_types, device, diagnostics); - var asset = new RenderPipelineAsset { pipelineTypeId = C_EXTENSION_ID }; - var featureAsset = new RenderPipelineAsset - { - pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID, - features = [new RenderFeatureConfiguration("tests.runtime.reloadable-plugin-feature")] - }; - - runtime.Submit(CreateRequest("Before Removal", asset)); - runtime.Submit(CreateRequest("Feature Before Removal", featureAsset)); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(1, proxy.executeCount); - proxy.ReleaseRecordedGraph(); - - QueueCollectiblePayload(runtime, m_types, asset); - (IAssemblyUnloadProbe removalMonitor, IRenderRuntimeReloadTransaction renderingRemoval) = RemoveRenderingPlugin( - runtime, - m_modules, - plugin - ); - - ForceCollection(); - Assert.True(removalMonitor.isCompleted); - GC.KeepAlive(renderingRemoval); - - runtime.Submit(CreateRequest("While Unavailable", asset)); - runtime.Submit(CreateRequest("Feature While Unavailable", featureAsset)); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(1, proxy.executeCount); - Assert.DoesNotContain( - diagnostics.items, - static diagnostic => diagnostic.code == "RENDER_EXTENSION_RELOAD_REJECTED" - ); - - IRenderRuntimeReloadTransaction renderingRecovery = runtime.BeginExtensionReload(); - using (AssemblyReloadSession recovery = m_modules.BeginReload([plugin])) - { - activeModule = recovery.context.module; - recovery.Activate(); - renderingRecovery.Prepare(); - renderingRecovery.Activate(); - _ = recovery.Complete(); - renderingRecovery.Complete(); - } - - runtime.Submit(CreateRequest("After Recovery", asset)); - runtime.Submit(CreateRequest("Feature After Recovery", featureAsset)); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(2, proxy.executeCount); - - proxy.ReleaseRecordedGraph(); - runtime.Detach(); - IAssemblyUnloadProbe recoveryMonitor = m_modules.Unload(activeModule); - ForceCollection(); - Assert.True(recoveryMonitor.isCompleted); - } - - [Fact] - public void RemovingUnusedRenderingPluginReleasesItsAssemblyContext() - { - DotNetModuleSource plugin = CreateRenderingPluginRequest(); - _ = m_modules.Load(plugin); - IAssemblyUnloadProbe monitor = RemoveUnusedPlugin(m_modules, plugin); - - ForceCollection(); - - Assert.True(monitor.isCompleted); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void FrameStatisticsReportBackendCommandsAndGraphCulling(bool reportsAllocations) - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - proxy.frameCounters = new RenderDeviceFrameCounters(3, 2); - proxy.allocationCounters = reportsAllocations - ? new RenderDeviceAllocationCounters(device.generation, 17, 23, 11) - : null; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - using IDisposable executionScope = runtime.EnterExecutionScope(); - var asset = new RenderPipelineAsset { pipelineTypeId = StatisticsPipeline.C_EXTENSION_ID }; - runtime.Attach(); - Assert.True(runtime.TryActivateDefaultPipeline(asset)); - runtime.Submit( - new RenderRequest("Statistics", RenderTarget.backbuffer, new RenderViewport(0, 0, 64, 64), asset) - ); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - RenderFrameStatistics statistics = Assert.IsType(GraphicsSettings.frameStatistics); - Assert.Equal(1, statistics.viewCount); - Assert.Equal(3, statistics.drawCount); - Assert.Equal(2, statistics.dispatchCount); - Assert.Equal(1, statistics.culledPassCount); - Assert.Equal(proxy.allocationCounters, statistics.allocationCounters); - proxy.allocationCounters = new RenderDeviceAllocationCounters(device.generation, 19, 25, 13); - Assert.NotEqual(proxy.allocationCounters, statistics.allocationCounters); - runtime.Detach(); - } - - [Fact] - public void DeviceSynchronizationIsRequiredAndUnsupportedDiagnosticsAreExplicitlyUnavailable() - { - Assert.True(typeof(IRenderDevice).GetMethod(nameof(IRenderDevice.SetVerticalSync))!.IsAbstract); - using var backend = new RecordingRenderDevice(); - IRenderDevice device = backend; - device.SetVerticalSync(true); - Assert.True(backend.verticalSync); - device.SetVerticalSync(false); - Assert.False(backend.verticalSync); - Assert.Null(device.allocationCounters); - Assert.Throws(() => new RenderDeviceAllocationCounters(0, 0, 0, 0)); - } - - [Fact] - public void GraphicsFacadeResolvesTheCurrentlyBoundRenderingRuntime() - { - IRenderDevice firstDevice = TestDeviceProxy.Create(out TestDeviceProxy firstProxy); - IRenderDevice secondDevice = TestDeviceProxy.Create(out TestDeviceProxy secondProxy); - firstProxy.frameCounters = new RenderDeviceFrameCounters(2, 0); - secondProxy.frameCounters = new RenderDeviceFrameCounters(7, 1); - using var first = new RenderRuntime(m_types, firstDevice, new TestDiagnosticSink()); - using var second = new RenderRuntime(m_types, secondDevice, new TestDiagnosticSink()); - var asset = new RenderPipelineAsset { pipelineTypeId = StatisticsPipeline.C_EXTENSION_ID }; - - using (first.EnterExecutionScope()) - { - first.Attach(); - Assert.True(first.TryActivateDefaultPipeline(asset)); - first.Submit(CreateRequest("First Runtime", asset)); - BeginRenderFrame(first, 0f); - first.AfterRender(default); - first.EndFrame(default); - Assert.Equal(2, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); - - using (second.EnterExecutionScope()) - { - second.Attach(); - Assert.True(second.TryActivateDefaultPipeline(asset)); - second.Submit(CreateRequest("Second Runtime", asset)); - BeginRenderFrame(second, 0f); - second.AfterRender(default); - second.EndFrame(default); - Assert.Equal(7, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); - } - - Assert.Equal(2, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); - } - - Assert.Null(GraphicsSettings.frameStatistics); - Assert.Throws(() => GraphicsSettings.defaultPipeline = asset); - second.Detach(); - first.Detach(); - } - - [Fact] - public void RequestProviderProducesCurrentFrameWorkThroughPublicPluginApi() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; - TestRequestProvider.pipeline = asset; - TestRequestProvider.enabled = true; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Attach(); - - BeginRenderFrame(runtime, 1f / 60f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, TestRequestProvider.submitCount); - Assert.Equal(1, proxy.executeCount); - CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); - Assert.Equal("Request[0] Provider Request/Visible", pass.name); - runtime.Detach(); - } - - [Fact] - public void RequestProviderReceivesExplicitHostContentScope() - { - IRenderDevice device = TestDeviceProxy.Create(out _); - Guid contentID = Guid.Parse("3aee0ced-b598-4366-ab45-a6ef8e0feb30"); - var content = new TestContent(); - var identities = new IdentityAllocator(); - identities.Register(content, contentID); - var scope = new ContentReadScope([content.identity], contentID); - Assert.True(scope.TryGetValue(contentID, out TestContent? resolved)); - Assert.Same(content, resolved); - TestRequestProvider.enabled = true; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), contentScopeProvider: () => scope); - runtime.Attach(); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Same(scope, TestRequestProvider.lastContent); - Assert.Throws(() => scope.TryGetValue(contentID, out TestContent? _)); - runtime.Detach(); - } - - [Fact] - public void PrimaryPresentationViewportIsSharedAndLetterboxSurfaceIsCleared() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - proxy.presentationSize = new RenderPresentationSize(1000, 1000); - TestRequestProvider.enabled = true; - var runtime = new RenderRuntime( - m_types, - device, - new TestDiagnosticSink(), - primaryPresentationViewportProvider: static size => new RenderViewport( - 0, - (size.height - 562) / 2, - size.width, - 562 - ) - ); - runtime.Attach(); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(new RenderViewport(0, 219, 1000, 562), TestRequestProvider.lastPresentationViewport); - CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); - Assert.Equal("Primary Presentation Background", pass.name); - Assert.True(pass.clearsPresentationTarget); - Assert.Equal(new RenderClearColor(0f, 0f, 0f, 1f), pass.presentationClearColor); - runtime.Detach(); - } - - [Fact] - public void PrimaryOutputScalesLogicalWindowPointerToPhysicalPixels() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - proxy.presentationSize = new RenderPresentationSize(2560, 1440); - TestRequestProvider.enabled = true; - var snapshot = new InputSnapshot( - 1, - mousePosition: new Vector2(400f, 274f), - mouseButtonsPressed: [MouseButton.Left] - ); - using var runtime = new RenderRuntime( - m_types, - device, - new TestDiagnosticSink(), - inputSnapshotProvider: () => snapshot, - primaryInputSurfaceSizeProvider: static () => new RenderPresentationSize(1280, 720) - ); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(new Vector2(800f, 548f), TestRequestProvider.lastInput.pointerPosition); - Assert.Single(TestRequestProvider.lastInput.buttonsPressed); - } - - [Fact] - public void CompetingModelsDoNotShareATargetWhenAnExactRouteExists() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var diagnostics = new TestDiagnosticSink(); - proxy.capabilities = new GraphicsCapabilities( - GraphicsApi.metal, - GraphicsCapability.None, - new GraphicsLimits(64, 4, 4096, 8), - Enum.GetValues(), - Enum.GetValues(), - [], - [], - originBottomLeft: false, - homogeneousDepth: false - ); - proxy.presentationSize = new RenderPresentationSize(1000, 1000); - FirstTestRenderModel.enabled = true; - SecondTestRenderModel.enabled = true; - using var runtime = new RenderRuntime( - m_types, - device, - diagnostics, - primaryPresentationViewportProvider: static _ => new RenderViewport(100, 200, 800, 600), - compositionProgramProvider: new TestCompositionProgramProvider() - ); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(0, FirstTestRenderModel.buildCount); - Assert.Equal(0, SecondTestRenderModel.buildCount); - Assert.Contains(diagnostics.items, item => ( - item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" - && item.message.Contains("Multiple rendering models", StringComparison.Ordinal) - )); - - runtime.SetPrimaryRoute( - new RenderOutputRoute( - [ - new RenderOutputLayer(SecondTestRenderModel.C_EXTENSION_ID, []), - new RenderOutputLayer(FirstTestRenderModel.C_EXTENSION_ID, []) - ] - ) - ); - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Equal(1, FirstTestRenderModel.buildCount); - Assert.Equal(1, SecondTestRenderModel.buildCount); - Assert.Equal( - [new RenderViewport(0, 0, 800, 600), new RenderViewport(0, 0, 800, 600)], - CompositionLayerPipeline.viewports - ); - Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE"); - Assert.DoesNotContain(diagnostics.items, item => ( - item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" - && item.message.Contains("independent model targets", StringComparison.Ordinal) - )); - Assert.True( - diagnostics.items.All(item => item.code != "RENDER_OUTPUT_COMPOSITION_FAILED"), - string.Join("\n", diagnostics.items.Select(item => item.message)) - ); - Assert.True(proxy.lastGraph is not null, string.Join("\n", diagnostics.items.Select(item => item.message))); - Assert.Contains(proxy.lastGraph.passes, pass => pass.name.Contains("Layer 2", StringComparison.Ordinal)); - runtime.Detach(); - } - - [Fact] - public void OutputWithoutAnApplicableModelReportsItsMissingRenderer() - { - var diagnostics = new TestDiagnosticSink(); - using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), diagnostics); - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.Contains(diagnostics.items, item => ( - item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" - && item.message.Contains("No rendering model", StringComparison.Ordinal) - )); - runtime.Detach(); - } - - [Fact] - public void LinearPresentationReceivesOneTransferAfterAllModelLayers() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - proxy.primaryPresentationEncodesSrgb = false; - proxy.presentationSize = new RenderPresentationSize(800, 600); - FirstTestRenderModel.enabled = true; - SecondTestRenderModel.enabled = true; - var diagnostics = new TestDiagnosticSink(); - using var runtime = new RenderRuntime( - m_types, - device, - diagnostics, - compositionProgramProvider: new TestCompositionProgramProvider() - ); - runtime.SetPrimaryRoute( - new RenderOutputRoute( - [ - new RenderOutputLayer(FirstTestRenderModel.C_EXTENSION_ID, []), - new RenderOutputLayer(SecondTestRenderModel.C_EXTENSION_ID, []) - ] - ) - ); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_COMPOSITION_FAILED"); - Assert.NotNull(proxy.lastGraph); - Assert.Single(proxy.lastGraph.passes.Where(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal))); - Assert.Contains("Output Transfer", proxy.lastGraph.passes[^1].name, StringComparison.Ordinal); - Assert.Contains(proxy.lastGraph.textures, texture => ( - texture.name.EndsWith("/Composition", StringComparison.Ordinal) - && texture.descriptor.width == 800 - && texture.descriptor.height == 600 - && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb - )); - runtime.Detach(); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public void SingleModelPresentationEncodesColorExactlyOnce(bool presentationEncodesSrgb) - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - proxy.primaryPresentationEncodesSrgb = presentationEncodesSrgb; - proxy.presentationSize = new RenderPresentationSize(800, 600); - FirstTestRenderModel.enabled = true; - var diagnostics = new TestDiagnosticSink(); - using var runtime = new RenderRuntime( - m_types, - device, - diagnostics, - compositionProgramProvider: new TestCompositionProgramProvider() - ); - - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, FirstTestRenderModel.buildCount); - Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_COMPOSITION_FAILED"); - Assert.NotNull(proxy.lastGraph); - Assert.Equal( - presentationEncodesSrgb ? 0 : 1, - proxy.lastGraph.passes.Count(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal)) - ); - Assert.DoesNotContain( - proxy.lastGraph.textures, - texture => texture.name.EndsWith("/Composition", StringComparison.Ordinal) - ); - if (!presentationEncodesSrgb) - { - Assert.Contains("Output Transfer", proxy.lastGraph.passes[^1].name, StringComparison.Ordinal); - Assert.Contains(proxy.lastGraph.textures, texture => ( - texture.name.Contains("Model Layer 1", StringComparison.Ordinal) - && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb - )); - } - runtime.Detach(); - } - - [Fact] - public void EditorOwnedOffscreenOutputsDoNotReportAnUnusedPrimaryModel() - { - var diagnostics = new TestDiagnosticSink(); - using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), diagnostics); - runtime.SetPrimaryModelOutputEnabled(false); - BeginRenderFrame(runtime, 0f); - runtime.Render(default); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE"); - runtime.Detach(); - } - - [Fact] - public void MultipleRequestsAndContributorsCompileAndExecuteAsOneFrameGraph() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; - var contributor = new SideEffectContributor(); - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), [contributor]); - runtime.Submit(CreateRequest("Second", asset, priority: 10)); - runtime.Submit(CreateRequest("First", asset, priority: -10)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, proxy.executeCount); - string[] names = Assert.IsType(proxy.lastGraph).passes - .Select(static pass => pass.name) - .ToArray(); - string[] expectedNames = - [ - "Request[0] First/Visible", - "Request[1] Second/Visible", - "Contributor[0] SideEffectContributor/Overlay" - ]; - Assert.Equal(expectedNames, names); - runtime.Detach(); - } - - [Fact] - public void OverlappingRequestsPreserveEarlierPresentationLayersInSchedulingOrder() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var asset = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.C_EXTENSION_ID }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(CreateRequest("Overlay", asset, priority: 100)); - runtime.Submit(CreateRequest("Base", asset, priority: 0)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal( - new[] - { - new PresentationObservation("Base", false), - new PresentationObservation("Overlay", true) - }, - PresentationPipeline.observations - ); - Assert.Equal(1, proxy.executeCount); - runtime.Detach(); - } - - [Fact] - public void DisjointViewportsCanInitializeTheSamePresentationTargetIndependently() - { - IRenderDevice device = TestDeviceProxy.Create(out _); - var asset = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.C_EXTENSION_ID }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(new RenderRequest("Left", RenderTarget.backbuffer, new RenderViewport(0, 0, 32, 64), asset)); - runtime.Submit(new RenderRequest("Right", RenderTarget.backbuffer, new RenderViewport(32, 0, 32, 64), asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal( - new[] - { - new PresentationObservation("Left", false), - new PresentationObservation("Right", false) - }, - PresentationPipeline.observations - ); - runtime.Detach(); - } - - [Fact] - public void FailedRequestDoesNotClaimThePresentationTarget() - { - IRenderDevice device = TestDeviceProxy.Create(out _); - var failed = new RenderPipelineAsset { pipelineTypeId = ThrowingPipeline.C_EXTENSION_ID }; - var valid = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.C_EXTENSION_ID }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(CreateRequest("Failed", failed, priority: 0)); - runtime.Submit(CreateRequest("Recovery", valid, priority: 100)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(new[] { new PresentationObservation("Recovery", false) }, PresentationPipeline.observations); - runtime.Detach(); - } - - [Fact] - public void ReplacedAndReleasedTargetsRemainValidAcrossPreparedPresentationFrames() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var registry = new RenderTargetStore(device); - var target = new RenderTexture( - "Deferred Target", - new RenderTextureDescriptor( - 32, - 32, - RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled - ) - ); - - device.BeginFrame(); - registry.PrepareFrame(); - _ = registry.Import(new RenderGraphBuilder(1, device.capabilities), target); - _ = device.EndFrame(); - PersistentTextureHandle first = Assert.Single(proxy.createdTextures); - - target.Resize( - new RenderTextureDescriptor( - 64, - 64, - RenderTextureFormat.RGBA8, - RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled - ) - ); - device.BeginFrame(); - registry.PrepareFrame(); - _ = registry.Import(new RenderGraphBuilder(2, device.capabilities), target); - _ = device.EndFrame(); - PersistentTextureHandle second = proxy.createdTextures[1]; - Assert.Empty(proxy.destroyedTextures); - - device.BeginFrame(); - registry.PrepareFrame(); - _ = device.EndFrame(); - Assert.Empty(proxy.destroyedTextures); - - device.BeginFrame(); - registry.PrepareFrame(); - _ = device.EndFrame(); - Assert.Equal(new[] { first }, proxy.destroyedTextures); - - registry.Release(target); - for (int frame = 0; frame < 2; frame++) - { - device.BeginFrame(); - registry.PrepareFrame(); - _ = device.EndFrame(); - } - Assert.Equal(new[] { first }, proxy.destroyedTextures); - - device.BeginFrame(); - registry.PrepareFrame(); - registry.Dispose(); - _ = device.EndFrame(); - Assert.Equal(new[] { first, second }, proxy.destroyedTextures); - } - - [Fact] - public void DetachUsesADeviceSafetyFrameToReleaseResidentTargets() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; - var target = new RenderTexture( - "Detach Target", - new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment) - ); - runtime.Submit( - new RenderRequest("Detach", RenderTarget.FromTexture(target), new RenderViewport(0, 0, 16, 16), asset) - ); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - PersistentTextureHandle resident = Assert.Single(proxy.createdTextures); - - runtime.Detach(); - - Assert.Equal(new[] { resident }, proxy.destroyedTextures); - Assert.False(proxy.frameOpen); - Assert.Equal(2, proxy.endFrameCount); - } - - [Fact] - public void FailedRequestRollsBackWithoutDiscardingOtherRequests() - { - IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); - var diagnostics = new TestDiagnosticSink(); - var failed = new RenderPipelineAsset { pipelineTypeId = ThrowingPipeline.C_EXTENSION_ID }; - var valid = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; - var runtime = new RenderRuntime(m_types, device, diagnostics); - runtime.Submit(CreateRequest("A Failed", failed)); - runtime.Submit(CreateRequest("B Valid", valid)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, proxy.executeCount); - CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); - Assert.Equal("Request[1] B Valid/Visible", pass.name); - Assert.Contains(diagnostics.items, diagnostic => diagnostic.code == "RENDER_REQUEST_FAILED"); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Assert.DoesNotContain(diagnostics.items, diagnostic => diagnostic.code == "RENDER_REQUEST_FAILED"); - runtime.Detach(); - } - - [Fact] - public void FrameUploadsReusePagesAndResetSliceOffsetsBetweenFrames() - { - var device = new RecordingRenderDevice(); - var asset = new RenderPipelineAsset { pipelineTypeId = UploadPipeline.C_EXTENSION_ID }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - - runtime.Submit(CreateRequest("Upload A", asset)); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, device.createBufferCount); - Assert.Equal(new[] { 0, 3 }, device.bufferUpdateOffsets.ToArray()); - Assert.Equal(0, UploadPipeline.firstSlice.firstElement); - Assert.Equal(3, UploadPipeline.secondSlice.firstElement); - Assert.Equal(3, UploadPipeline.secondSlice.elementCount); - - UploadPipeline.singleUpload = true; - runtime.Submit(CreateRequest("Upload B", asset)); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, device.createBufferCount); - Assert.Equal(new[] { 0, 3, 0 }, device.bufferUpdateOffsets.ToArray()); - Assert.Equal(0, UploadPipeline.firstSlice.firstElement); - runtime.Detach(); - } - - [Fact] - public void TexturePrewarmRunsOutsideTheRenderFrameAndDoesNotDelaySubmission() - { - var texture = new TextureAsset(1, 1, TextureColorSpace.Srgb, "png"); - Assert.True(m_identities.Register(texture)); - TexturePrewarmPipeline.texture = texture; - - var compiler = new DelayedTextureArtifactSource(); - var device = new RecordingRenderDevice(); - var asset = new RenderPipelineAsset { pipelineTypeId = TexturePrewarmPipeline.C_EXTENSION_ID }; - var artifacts = new DelayedArtifactProvider(compiler); - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), targetArtifacts: artifacts); - runtime.Submit(CreateRequest("Prewarm", asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, device.endFrameCount); - Assert.True(compiler.started.Wait(TimeSpan.FromSeconds(2))); - Assert.False(compiler.isCompleted); - compiler.Complete([1, 2, 3, 4]); - runtime.Detach(); - } - - [Fact] - public void PendingShaderCompilationDoesNotPublishAnUnavailableArtifactError() - { - var contract = new ShaderContractID("tests.pending.contract"); - var role = new ShaderPassRoleID("draw"); - var pass = new ShaderPassDefinition("draw", ShaderProgramKind.Raster); - var shader = new ShaderAsset(); - Assert.True(m_identities.Register(shader)); - shader.SetDefinition( - new ShaderDefinition( - "Pending Shader", - [], - [], - [pass], - [new ShaderTechniqueDefinition( - new ShaderTechniqueID("default"), - contract, - [new ShaderTechniquePass(role, pass.name)] - )] - ), - m_serialization, - SerializationContext.empty - ); - PendingShaderPipeline.material = new MaterialAsset { shader = shader }; - PendingShaderPipeline.contract = contract; - PendingShaderPipeline.role = role; - - var diagnostics = new TestDiagnosticSink(); - var compiler = new DelayedTextureArtifactSource(); - var runtime = new RenderRuntime( - m_types, - new RecordingRenderDevice(), - diagnostics, - targetArtifacts: new DelayedArtifactProvider(compiler) - ); - var asset = new RenderPipelineAsset { pipelineTypeId = PendingShaderPipeline.C_EXTENSION_ID }; - runtime.Submit(CreateRequest("Pending Shader", asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.False(PendingShaderPipeline.resolved); - Assert.DoesNotContain( - diagnostics.items, - static diagnostic => diagnostic.code == "RENDER_SHADER_TARGET_UNAVAILABLE" - ); - runtime.Detach(); - } - - [Fact] - public async Task PersistentTextureRegionUpdateAndReadbackCompleteAcrossFrameBoundaries() - { - var device = new RecordingRenderDevice(supportsReadback: true); - ReadbackPipeline.texture = device.textureHandle; - var asset = new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.C_EXTENSION_ID }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(CreateRequest("Readback", asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(new RenderTextureRegion(0, 1, 1, 0, 2, 2), device.updatedRegion); - Assert.Equal(Enumerable.Range(0, 16).Select(static value => (byte)value), device.updatedBytes); - Task readback = Assert.IsType>( - ReadbackPipeline.readback - ); - Assert.False(readback.IsCompleted); - - device.readbackReady = true; - BeginRenderFrame(runtime, 0f); - RenderTextureReadbackResult result = await readback; - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(16, result.rowPitch); - Assert.Equal(64, result.data.Length); - Assert.All(result.data.ToArray(), static value => Assert.Equal((byte)37, value)); - runtime.Detach(); - } - - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task PendingUploadOrReadbackRetirementPreservesDependentWork(bool pendingReadback) - { - var device = new RecordingRenderDevice(supportsReadback: true); - ReadbackPipeline.texture = device.textureHandle; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(CreateRequest("Upload", new RenderPipelineAsset { pipelineTypeId = UploadPipeline.C_EXTENSION_ID })); - runtime.Submit(CreateRequest("Readback", new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.C_EXTENSION_ID })); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - Task readback = Assert.IsType>(ReadbackPipeline.readback); - device.pendingBufferRetirements = pendingReadback ? 0 : 1; - device.pendingReadbackRetirements = pendingReadback ? 1 : 0; - - runtime.Dispose(); - - Assert.Equal(pendingReadback ? 1 : 2, device.bufferRetirementAttempts); - Assert.Equal(pendingReadback ? 2 : 1, device.cancelReadbackCount); - Assert.Equal(2, device.endFrameCount); - await Assert.ThrowsAsync(async () => await readback); - runtime.Dispose(); - Assert.Equal(2, device.endFrameCount); - } - - [Fact] - public async Task CancelingReadbackReleasesTheDeviceOperationAtTheNextFrameBoundary() - { - var device = new RecordingRenderDevice(supportsReadback: true); - using var cancellation = new CancellationTokenSource(); - ReadbackPipeline.texture = device.textureHandle; - ReadbackPipeline.cancellationToken = cancellation.Token; - var asset = new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.C_EXTENSION_ID }; - var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); - runtime.Submit(CreateRequest("Canceled Readback", asset)); - - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - cancellation.Cancel(); - Task readback = Assert.IsType>( - ReadbackPipeline.readback - ); - Assert.False(readback.IsCompleted); - BeginRenderFrame(runtime, 0f); - await Assert.ThrowsAnyAsync(async () => await readback); - runtime.AfterRender(default); - runtime.EndFrame(default); - - Assert.Equal(1, device.cancelReadbackCount); - runtime.Detach(); - } - - private DotNetModuleSource CreateRenderingPluginRequest() - => new() - { - moduleName = "RenderingRuntimeReloadTests", - artifactRootDirectory = Path.Combine(m_cacheDirectory, "Modules"), - mainAssemblyPath = Path.Combine( - AppContext.BaseDirectory, - "Modules", - "RenderingReload", - "Inno.Rendering.Runtime.Reload.TestModule.dll" - ), - domain = AssemblyDomain.InnoPlugin, - scope = AssemblyScope.Runtime - }; - - private static void RunResourceFrame(RenderRuntime runtime) - { - runtime.Submit( - CreateRequest("Resource ownership", new RenderPipelineAsset { pipelineTypeId = ResourceProbePipeline.C_EXTENSION_ID }) - ); - BeginRenderFrame(runtime, 0f); - runtime.AfterRender(default); - runtime.EndFrame(default); - } - - private static RenderRequest CreateRequest( - string name, - RenderPipelineAsset pipeline, - int priority = 0 - ) => new(name, RenderTarget.backbuffer, new RenderViewport(0, 0, 64, 64), pipeline, priority: priority); - - [MethodImpl(MethodImplOptions.NoInlining)] - private static ( - IAssemblyUnloadProbe monitor, - IRenderRuntimeReloadTransaction transaction) RemoveRenderingPlugin( - RenderRuntime runtime, - ModuleHost modules, - DotNetModuleSource plugin - ) { - IRenderRuntimeReloadTransaction rendering = runtime.BeginExtensionReload(); - using AssemblyReloadSession removal = modules.BeginReload([], [plugin.moduleName]); - removal.Activate(); - rendering.Prepare(); - rendering.Activate(); - IAssemblyUnloadProbe monitor = removal.Complete(); - rendering.Complete(); - return (monitor, rendering); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static IAssemblyUnloadProbe RemoveUnusedPlugin( - ModuleHost modules, - DotNetModuleSource plugin - ) { - using AssemblyReloadSession removal = modules.BeginReload([], [plugin.moduleName]); - removal.Activate(); - return removal.Complete(); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static void QueueCollectiblePayload( - RenderRuntime runtime, - TypeCatalog types, - RenderPipelineAsset pipeline - ) { - Type payloadType = types.current.types - .Select(type => type.Resolve(types)) - .Single(type => string.Equals( - type.FullName, - "Inno.Rendering.Runtime.Reload.TestModule.ReloadableFramePayload", - StringComparison.Ordinal - )); - object payload = Activator.CreateInstance(payloadType) - ?? throw new InvalidOperationException("The collectible frame payload could not be created."); - var data = new RenderFrameData(); - data.Set(new RenderDataChannelID("tests.runtime.collectible-payload"), payload); - runtime.Submit( - new RenderRequest( - "Collectible Pending Request", - RenderTarget.backbuffer, - new RenderViewport(0, 0, 64, 64), - pipeline, - data - ) - ); - } - - [MethodImpl(MethodImplOptions.NoInlining)] - private static void ForceCollection() - { - for (int attempt = 0; attempt < 8; attempt++) - { - GC.Collect(2, GCCollectionMode.Forced, blocking: true, compacting: true); - GC.WaitForPendingFinalizers(); - } - } - - private static void BeginRenderFrame( - RenderRuntime runtime, - float deltaTime - ) { - if (!runtime.isStarted) - { - runtime.Attach(); - } - var frame = new RuntimeFrame(0, deltaTime, deltaTime, 0, 0, 1, false); - runtime.BeginFrame(frame); - runtime.BeforeRender(frame); - } - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class ResourceProbePipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.resource-owner"; - internal static Action? action; - - public override void Build(RenderPipelineContext context) - { - action?.Invoke(context.resourceService); - context.graph.AddRasterPass("Resources", new RenderPhaseID("tests.resources"), 0, static ( - _, - _ - ) => {}).HasSideEffect(); - } - } - - private sealed class TestContent : IdentityObject; - - [RenderModelExtension(C_EXTENSION_ID)] - private sealed class FirstTestRenderModel : IRenderModel - { - internal const string C_EXTENSION_ID = "tests.runtime.model.first"; - internal static bool enabled; - internal static int buildCount; - - public bool CanRender(RenderOutputSession session) => enabled; - - public RenderModelOutput Build(RenderOutputSession session) - { - buildCount++; - return new RenderModelOutput( - "First Model", - new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.C_EXTENSION_ID }, - new RenderFrameData() - ); - } - - public void Dispose() {} - - internal static void Reset() - { - enabled = false; - buildCount = 0; - } - } - - [RenderModelExtension(C_EXTENSION_ID)] - private sealed class SecondTestRenderModel : IRenderModel - { - internal const string C_EXTENSION_ID = "tests.runtime.model.second"; - internal static bool enabled; - internal static int buildCount; - - public bool CanRender(RenderOutputSession session) => enabled; - - public RenderModelOutput Build(RenderOutputSession session) - { - buildCount++; - return new RenderModelOutput( - "Second Model", - new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.C_EXTENSION_ID }, - new RenderFrameData() - ); - } - - public void Dispose() {} - - internal static void Reset() - { - enabled = false; - buildCount = 0; - } - } - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class DisposablePipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.disposable"; - - public DisposablePipeline() - { - createdCount++; - } - - public override void Build(RenderPipelineContext context) => _ = context; - - internal static int createdCount { get; private set; } - internal static int disposedCount { get; private set; } - internal static bool rejectConfiguration { get; set; } - internal static int pendingRetirements { get; set; } - internal static int retirementAttempts { get; private set; } - internal static bool retirementExpired { get; set; } - - protected override void OnConfigure( - SerializedRenderExtensionState state, - RenderExtensionStateContext settings - ) { - _ = state; - if (rejectConfiguration) - { - throw new InvalidOperationException("Rejected pipeline configuration candidate."); - } - } - - protected override void Dispose(bool disposing) - { - _ = disposing; - retirementAttempts++; - if (retirementExpired) - { - throw new RetirementTimeoutException("The pipeline-owned device work exceeded its deadline."); - } - if (pendingRetirements > 0) - { - pendingRetirements--; - throw new RetirementPendingException("Pipeline work remains active."); - } - disposedCount++; - } - - internal static void Reset() - { - createdCount = 0; - disposedCount = 0; - rejectConfiguration = false; - pendingRetirements = 0; - retirementAttempts = 0; - retirementExpired = false; - } - } - - [RenderFeatureExtension(C_EXTENSION_ID)] - private sealed class PendingFeature : RenderPipelineFeature, IDisposable - { - internal const string C_EXTENSION_ID = "tests.runtime.pending-feature"; - - public override void AddRenderPasses(RenderFeatureContext context) {} - - public void Dispose() - { - retirementAttempts++; - Assert.Equal(0, DisposablePipeline.disposedCount); - if (pendingRetirements > 0) - { - pendingRetirements--; - throw new RetirementPendingException("Feature work remains active."); - } - } - - internal static int pendingRetirements { get; set; } - internal static int retirementAttempts { get; private set; } - - internal static void Reset() - { - retirementAttempts = 0; - pendingRetirements = 0; - } - } - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class StatisticsPipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.statistics"; - - public override void Build(RenderPipelineContext context) - { - context.graph - .AddRasterPass( - "Visible", - new RenderPhaseID("tests.statistics.visible"), - 0, - static ( - _, - _ - ) => {} - ) - .HasSideEffect(); - context.graph.AddRasterPass( - "Culled", - new RenderPhaseID("tests.statistics.culled"), - 0, - static ( - _, - _ - ) => {} - ); - } - } - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class CompositionLayerPipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.composition-layer"; - - public override void Build(RenderPipelineContext context) - { - viewports.Add(context.request.viewport); - RasterPassBuilder pass = context.graph.AddRasterPass( - "Scene Color", - new RenderPhaseID("tests.runtime.composition-layer"), - 0, - static ( - _, - _ - ) => {} - ); - if (context.outputTexture.isValid) - { - pass.UseColorAttachment( - context.outputTexture, - 0, - RenderLoadAction.Clear, - RenderStoreAction.Store, - new RenderClearColor(0f, 0f, 0f, 0f) - ); - } - else - { - pass.ClearPresentationTarget(default).HasSideEffect(); - } - } - - internal static List viewports { get; } = []; - } - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class SideEffectPipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.side-effect"; - - public override void Build(RenderPipelineContext context) - => context.graph - .AddRasterPass( - "Visible", - new RenderPhaseID("tests.runtime.visible"), - 0, - static ( - _, - _ - ) => {} - ) - .HasSideEffect(); - } - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class PresentationPipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.presentation"; - - public override void Build(RenderPipelineContext context) - { - observations.Add(new PresentationObservation(context.request.name, context.preservePresentationTarget)); - context.graph - .AddRasterPass( - "Presentation", - new RenderPhaseID("tests.runtime.presentation"), - 0, - static ( - _, - _ - ) => {} - ) - .HasSideEffect(); - } - - internal static List observations { get; } = []; - - internal static void Reset() => observations.Clear(); - } - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class ThrowingPipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.throwing"; - - public override void Build(RenderPipelineContext context) - { - context.graph - .AddRasterPass( - "Rolled Back", - new RenderPhaseID("tests.runtime.rolled-back"), - 0, - static ( - _, - _ - ) => {} - ) - .HasSideEffect(); - throw new InvalidOperationException("Expected request failure."); - } - } - - private readonly record struct PresentationObservation( - string requestName, - bool preserveTarget - ); - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class UploadPipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.upload"; - - public override void Build(RenderPipelineContext context) - { - var layout = new RenderVertexLayout( - [ - new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) - ] - ); - var descriptor = new RenderBufferUploadDescriptor(layout.stride, RenderBufferUsage.Vertex, layout); - firstSlice = context.uploads.UploadBuffer(descriptor, new byte[layout.stride * 3], "Vertices"); - if (!singleUpload) - { - secondSlice = context.uploads.UploadBuffer(descriptor, new byte[layout.stride * 3], "Vertices"); - } - } - - internal static RenderBufferSlice firstSlice { get; private set; } - internal static RenderBufferSlice secondSlice { get; private set; } - internal static bool singleUpload { get; set; } - - internal static void Reset() - { - firstSlice = default; - secondSlice = default; - singleUpload = false; - } - } - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class TexturePrewarmPipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.texture-prewarm"; - - public override void Build(RenderPipelineContext context) - { - context.resourceService.PrewarmTexture( - texture ?? throw new InvalidOperationException("A test texture is required.") - ); - context.graph - .AddRasterPass( - "Submit While Prewarming", - new RenderPhaseID("tests.runtime.prewarm"), - 0, - static ( - _, - _ - ) => {} - ) - .HasSideEffect(); - } - - internal static TextureAsset? texture { get; set; } - } - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class PendingShaderPipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.pending-shader"; - - public override void Build(RenderPipelineContext context) - { - resolved = context.resourceService.TryResolveGraphicsMaterial( - material ?? throw new InvalidOperationException("A test material is required."), - contract, - role, - null, - null, - out _ - ); - context.graph - .AddRasterPass( - "Submit While Compiling", - new RenderPhaseID("tests.runtime.pending-shader"), - 0, - static ( - _, - _ - ) => {} - ) - .HasSideEffect(); - } - - internal static MaterialAsset? material { get; set; } - internal static ShaderContractID contract { get; set; } - internal static ShaderPassRoleID role { get; set; } - internal static bool resolved { get; private set; } - - internal static void Reset() - { - material = null; - contract = default; - role = default; - resolved = false; - } - } - - [RenderPipelineExtension(C_EXTENSION_ID)] - private sealed class ReadbackPipeline : RenderPipeline - { - internal const string C_EXTENSION_ID = "tests.runtime.readback"; - - public override void Build(RenderPipelineContext context) - { - byte[] update = Enumerable.Range(0, 16).Select(static value => (byte)value).ToArray(); - context.resourceService.UpdateTexture(texture, new RenderTextureRegion(0, 1, 1, 0, 2, 2), update); - readback ??= context.resourceService - .ReadTextureAsync(texture, cancellationToken: cancellationToken) - .AsTask(); - context.graph - .AddRasterPass( - "Readback Submission", - new RenderPhaseID("tests.runtime.readback"), - 0, - static ( - _, - _ - ) => {} - ) - .HasSideEffect(); - } - - internal static PersistentTextureHandle texture { get; set; } - internal static CancellationToken cancellationToken { get; set; } - internal static Task? readback { get; private set; } - - internal static void Reset() - { - texture = default; - cancellationToken = default; - readback = null; - } - } - - [RenderRequestProviderExtension(C_EXTENSION_ID)] - private sealed class TestRequestProvider : RenderRequestProvider - { - internal const string C_EXTENSION_ID = "tests.runtime.request-provider"; - - public override void Submit(RenderRequestProviderContext context) - { - if (!enabled) - { - return; - } - submitCount++; - lastContent = context.content; - lastPresentationViewport = context.primaryPresentationViewport; - lastInput = context.input; - if (pipeline is null) - { - return; - } - context.requests.Submit(CreateRequest("Provider Request", pipeline)); - } - - internal static bool enabled { get; set; } - internal static RenderPipelineAsset? pipeline { get; set; } - internal static int submitCount { get; private set; } - internal static int pendingRetirements { get; set; } - internal static int retirementAttempts { get; private set; } - internal static ContentReadScope? lastContent { get; private set; } - internal static RenderViewport? lastPresentationViewport { get; private set; } - internal static RenderOutputInput lastInput { get; private set; } = RenderOutputInput.empty; - - protected override void Dispose(bool disposing) - { - retirementAttempts++; - if (pendingRetirements > 0) - { - pendingRetirements--; - throw new RetirementPendingException("Provider work remains active."); - } - } - - internal static void Reset() - { - enabled = false; - pipeline = null; - submitCount = 0; - pendingRetirements = 0; - retirementAttempts = 0; - lastContent = null; - lastPresentationViewport = default; - lastInput = RenderOutputInput.empty; - } - } - - private sealed class SideEffectContributor : IRenderFrameGraphContributor - { - public void PrepareFrame(ulong frameIndex) => _ = frameIndex; - - public void AddRenderPasses( - RenderGraphBuilder graph, - ulong frameIndex - ) { - _ = frameIndex; - graph - .AddRasterPass( - "Overlay", - new RenderPhaseID("tests.runtime.overlay"), - 0, - static ( - _, - _ - ) => {} - ) - .HasSideEffect(); - } - } - - private sealed class TestDiagnosticSink : IDiagnosticReporter - { - public void Publish(Diagnostic diagnostic) => items.Add(diagnostic); - - public void Resolve( - string code, - string? semanticID = null, - Guid? objectID = null - ) => items.RemoveAll(diagnostic => ( - string.Equals(diagnostic.code, code, StringComparison.Ordinal) - && string.Equals(diagnostic.semanticID, semanticID, StringComparison.Ordinal) && diagnostic.objectID == objectID - )); - - public void Replace(IEnumerable diagnostics) - { - items.Clear(); - items.AddRange(diagnostics); - } - - internal List items { get; } = []; - } - - private sealed class TestDeviceProxy : RenderDevice, IRenderDevice - { - private static readonly GraphicsCapabilities CAPABILITIES = new( - GraphicsApi.noop, - GraphicsCapability.None, - new GraphicsLimits(64, 4, 4096, 8), - Enum.GetValues(), - Enum.GetValues(), - [], - [], - originBottomLeft: false, - homogeneousDepth: false - ); - - private int m_bufferCreationCount; - - public RenderDeviceFrameCounters frameCounters { get; internal set; } - public RenderDeviceAllocationCounters? allocationCounters { get; internal set; } - - public GraphicsCapabilities capabilities { get; internal set; } = CAPABILITIES; - public uint generation => 1; - public RenderPresentationSize? presentationSize { get; set; } = new(1, 1); - - public RenderPresentationSize? primaryPresentationSize - { - get => presentationSize; - private set => presentationSize = value; - } - - public bool primaryPresentationEncodesSrgb { get; set; } = true; - - public void SetVerticalSync(bool enabled) => verticalSync = enabled; - - public void BeginFrame() - { - Assert.False(frameOpen); - frameOpen = true; - } - - public void Execute( - CompiledRenderGraph graph, - ulong frameIndex - ) { - Assert.True(frameOpen); - _ = frameIndex; - executeCount++; - lastGraph = graph; - } - - public uint EndFrame() - { - Assert.True(frameOpen); - frameOpen = false; - endFrameCount++; - return checked((uint)endFrameCount); - } - - public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; - - public PersistentTextureHandle CreateTexture( - RenderTextureDescriptor descriptor, - string name - ) { - Assert.True(frameOpen); - _ = descriptor; - _ = name; - PersistentTextureHandle texture = CreatePersistentTextureHandle( - checked((ulong)createdTextures.Count + 1), - generation - ); - createdTextures.Add(texture); - return texture; - } - - public void UpdateTexture( - PersistentTextureHandle texture, - ReadOnlySpan data, - int mipLevel = 0, - int arrayLayer = 0 - ) { - _ = texture; - _ = data; - _ = mipLevel; - _ = arrayLayer; - } - - public void UpdateTextureRegion( - PersistentTextureHandle texture, - RenderTextureRegion region, - ReadOnlySpan data - ) { - _ = texture; - _ = region; - _ = data; - } - - public RenderTextureReadbackHandle BeginTextureReadback( - PersistentTextureHandle texture, - int mipLevel = 0 - ) { - _ = texture; - _ = mipLevel; - return default; - } - - public bool TryGetTextureReadback( - RenderTextureReadbackHandle readback, - out RenderTextureReadbackResult? result - ) { - _ = readback; - result = null; - return false; - } - - public void CancelTextureReadback(RenderTextureReadbackHandle readback) => _ = readback; - - public void DestroyTexture(PersistentTextureHandle texture) - { - Assert.True(frameOpen); - textureRetirementAttempts++; - if (failFirstTextureRetirement) - { - failFirstTextureRetirement = false; - throw new InvalidOperationException("Texture retirement failed."); - } - if (texture == pendingTextureRetirement) - { - pendingTextureRetirement = default; - throw new RetirementPendingException("Texture still has pending work."); - } - destroyedTextures.Add(texture); - } - - public PersistentBufferHandle CreateBuffer( - PersistentBufferDescriptor descriptor, - ReadOnlySpan initialData, - string name - ) { - m_bufferCreationCount++; - if (m_bufferCreationCount == failBufferCreationAt) - { - throw new InvalidOperationException("Native allocation rejected."); - } - PersistentBufferHandle handle = CreatePersistentBufferHandle((ulong)m_bufferCreationCount, generation); - createdBuffers.Add(handle); - return handle; - } - - public void UpdateBuffer( - PersistentBufferHandle buffer, - ReadOnlySpan data, - int startElement = 0 - ) { - _ = buffer; - _ = data; - _ = startElement; - } - - public void DestroyBuffer(PersistentBufferHandle buffer) - { - Assert.DoesNotContain(buffer, destroyedBuffers); - destroyedBuffers.Add(buffer); - } - - public GraphicsPipelineHandle CreateGraphicsPipeline( - GraphicsPipelineDescriptor descriptor, - string name - ) { - _ = descriptor; - _ = name; - return default; - } - - public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) => _ = pipeline; - - public ComputePipelineHandle CreateComputePipeline( - ComputePipelineDescriptor descriptor, - string name - ) { - _ = descriptor; - _ = name; - return default; - } - - public void DestroyComputePipeline(ComputePipelineHandle pipeline) => _ = pipeline; - - public void Dispose() {} - - internal bool verticalSync { get; private set; } - - internal List createdBuffers { get; } = []; - internal List destroyedBuffers { get; } = []; - internal int failBufferCreationAt { get; set; } - - internal List createdTextures { get; } = []; - internal List destroyedTextures { get; } = []; - internal bool frameOpen { get; private set; } - internal int endFrameCount { get; private set; } - internal int executeCount { get; private set; } - internal int textureRetirementAttempts { get; private set; } - internal bool failFirstTextureRetirement { get; set; } - internal PersistentTextureHandle pendingTextureRetirement { get; set; } - internal CompiledRenderGraph? lastGraph { get; private set; } - - internal void ReleaseRecordedGraph() => lastGraph = null; - - internal static IRenderDevice Create(out TestDeviceProxy proxy) - { - proxy = new TestDeviceProxy(); - return proxy; - } - } - - private sealed class RecordingRenderDevice : RenderDevice, IRenderDevice - { - private readonly RenderTextureDescriptor m_readbackDescriptor = new( - 4, - 4, - RenderTextureFormat.RGBA8, - RenderTextureUsage.Readback - ); - - private readonly RenderTextureReadbackHandle m_readbackHandle; - - internal RecordingRenderDevice(bool supportsReadback = false) - { - this.capabilities = new GraphicsCapabilities( - GraphicsApi.noop, - supportsReadback ? GraphicsCapability.TextureReadback : GraphicsCapability.None, - new GraphicsLimits(64, 4, 4096, 8), - Enum.GetValues(), - Enum.GetValues(), - [], - [], - originBottomLeft: false, - homogeneousDepth: false - ); - this.textureHandle = CreatePersistentTextureHandle(1UL, generation); - m_readbackHandle = CreateRenderTextureReadbackHandle(1UL, generation); - } - - public GraphicsCapabilities capabilities { get; } - - public uint generation => 1; - public RenderPresentationSize? primaryPresentationSize { get; private set; } = new(1, 1); - public bool primaryPresentationEncodesSrgb => true; - - public void SetVerticalSync(bool enabled) => verticalSync = enabled; - - public void BeginFrame() {} - - public void Execute( - CompiledRenderGraph graph, - ulong frameIndex - ) { - _ = graph; - _ = frameIndex; - executeCount++; - } - - public uint EndFrame() - { - endFrameCount++; - return checked((uint)endFrameCount); - } - - public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; - - public PersistentTextureHandle CreateTexture( - RenderTextureDescriptor descriptor, - string name - ) { - _ = descriptor; - _ = name; - return default; - } - - public void UpdateTexture( - PersistentTextureHandle texture, - ReadOnlySpan data, - int mipLevel = 0, - int arrayLayer = 0 - ) { - _ = texture; - _ = data; - _ = mipLevel; - _ = arrayLayer; - } - - public void UpdateTextureRegion( - PersistentTextureHandle texture, - RenderTextureRegion region, - ReadOnlySpan data - ) { - Assert.Equal(textureHandle, texture); - updatedRegion = region; - updatedBytes = data.ToArray(); - } - - public RenderTextureReadbackHandle BeginTextureReadback( - PersistentTextureHandle texture, - int mipLevel = 0 - ) { - Assert.Equal(textureHandle, texture); - _ = mipLevel; - return m_readbackHandle; - } - - public bool TryGetTextureReadback( - RenderTextureReadbackHandle readback, - out RenderTextureReadbackResult? result - ) { - Assert.Equal(m_readbackHandle, readback); - result = readbackReady - ? new RenderTextureReadbackResult( - m_readbackDescriptor, - 0, - 16, - Enumerable.Repeat((byte)37, 64).ToArray() - ) - : null; - return result is not null; - } - - public void CancelTextureReadback(RenderTextureReadbackHandle readback) - { - Assert.Equal(m_readbackHandle, readback); - cancelReadbackCount++; - if (pendingReadbackRetirements > 0) - { - pendingReadbackRetirements--; - Assert.False(ReadbackPipeline.readback!.IsCompleted); - Assert.Equal(1, endFrameCount); - throw new RetirementPendingException("Readback cancellation remains active."); - } - } - - public void DestroyTexture(PersistentTextureHandle texture) => _ = texture; - - public PersistentBufferHandle CreateBuffer( - PersistentBufferDescriptor descriptor, - ReadOnlySpan initialData, - string name - ) { - _ = descriptor; - _ = initialData; - _ = name; - createBufferCount++; - return default; - } - - public void UpdateBuffer( - PersistentBufferHandle buffer, - ReadOnlySpan data, - int startElement = 0 - ) { - _ = buffer; - _ = data; - bufferUpdateOffsets.Add(startElement); - } - - public void DestroyBuffer(PersistentBufferHandle buffer) - { - bufferRetirementAttempts++; - if (pendingBufferRetirements > 0) - { - pendingBufferRetirements--; - Assert.Equal(0, cancelReadbackCount); - Assert.False(ReadbackPipeline.readback!.IsCompleted); - Assert.Equal(1, endFrameCount); - throw new RetirementPendingException("Upload work remains active."); - } - } - - public GraphicsPipelineHandle CreateGraphicsPipeline( - GraphicsPipelineDescriptor descriptor, - string name - ) { - if (name == failProgramName) throw new InvalidOperationException("Injected program allocation failure."); - GraphicsPipelineHandle handle = CreateGraphicsPipelineHandle(checked((ulong)createdPrograms.Count + 1), generation); - createdPrograms.Add(handle); - programDescriptors.Add(descriptor); - return handle; - } - - public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) - { - programRetirementAttempts++; - if (pendingProgramRetirements > 0) - { - pendingProgramRetirements--; - throw new RetirementPendingException("Injected unfinished program retirement."); - } - Assert.DoesNotContain(pipeline, destroyedPrograms); - destroyedPrograms.Add(pipeline); - if (failedProgramRetirements > 0) - { - failedProgramRetirements--; - throw new InvalidOperationException("Injected completed program retirement failure."); - } - } - - public ComputePipelineHandle CreateComputePipeline( - ComputePipelineDescriptor descriptor, - string name - ) { - _ = descriptor; - _ = name; - return default; - } - - public void DestroyComputePipeline(ComputePipelineHandle pipeline) => _ = pipeline; - - public void Dispose() {} - - internal List createdPrograms { get; } = []; - internal List destroyedPrograms { get; } = []; - internal List programDescriptors { get; } = []; - internal string? failProgramName { get; set; } - internal int pendingProgramRetirements { get; set; } - internal int failedProgramRetirements { get; set; } - internal int programRetirementAttempts { get; private set; } - internal bool verticalSync { get; private set; } - - internal List bufferUpdateOffsets { get; } = []; - internal PersistentTextureHandle textureHandle { get; } - internal RenderTextureRegion? updatedRegion { get; private set; } - internal byte[] updatedBytes { get; private set; } = []; - internal bool readbackReady { get; set; } - internal int cancelReadbackCount { get; private set; } - internal int pendingReadbackRetirements { get; set; } - internal int pendingBufferRetirements { get; set; } - internal int bufferRetirementAttempts { get; private set; } - internal int createBufferCount { get; private set; } - internal int endFrameCount { get; private set; } - internal int executeCount { get; private set; } - } - - private sealed class DelayedTextureArtifactSource - { - private readonly TaskCompletionSource m_completion = new( - TaskCreationOptions.RunContinuationsAsynchronously - ); - - internal ManualResetEventSlim started { get; } = new(initialState: false); - internal bool isCompleted => m_completion.Task.IsCompleted; - - internal Task LoadAsync(CancellationToken cancellationToken = default) - { - started.Set(); - return m_completion.Task.WaitAsync(cancellationToken); - } - - internal void Complete(byte[] data) => m_completion.TrySetResult(data); - } - - private sealed class DelayedArtifactProvider(DelayedTextureArtifactSource compiler) : IRenderTargetArtifactProvider - { - private Task? m_texture; - - public ShaderDefinition ReadShaderDefinition(RenderShaderArtifact artifact) - => throw new InvalidOperationException("This pending provider never publishes a shader artifact."); - - public RenderTargetArtifactStatus GetShaderArtifact( - ShaderAsset shader, - RenderShaderVariant variant, - GraphicsCapabilities capabilities, - out RenderShaderArtifact? artifact - ) { - _ = shader; - _ = variant; - _ = capabilities; - artifact = null; - return RenderTargetArtifactStatus.Pending; - } - - public RenderTargetArtifactStatus GetTextureArtifact( - RenderTextureArtifactReference texture, - out ReadOnlyMemory artifact - ) { - _ = texture; - m_texture ??= compiler.LoadAsync(); - if (m_texture.IsCompletedSuccessfully) - { - artifact = m_texture.Result; - return RenderTargetArtifactStatus.Ready; - } - artifact = ReadOnlyMemory.Empty; - return RenderTargetArtifactStatus.Pending; - } - } - - private sealed class TestCompositionProgramProvider : IRenderLayerCompositionProgramProvider - { - public GraphicsPipelineDescriptor CreateDescriptor( - GraphicsCapabilities capabilities, - RenderVertexLayout vertexLayout - ) { - _ = capabilities; - return new GraphicsPipelineDescriptor( - [1], - [1], - [new RenderShaderBindingDescriptor( - new RenderBindingID("s_tex"), - RenderShaderBindingKind.Texture, - 0, - nativeName: "s_tex" - )], - vertexLayout - ); - } - - public GraphicsPipelineDescriptor CreateOutputTransferDescriptor( - GraphicsCapabilities capabilities, - RenderVertexLayout vertexLayout - ) => CreateDescriptor(capabilities, vertexLayout); - } -} diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.ShaderProgramPublication.cs similarity index 99% rename from tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs rename to tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.ShaderProgramPublication.cs index 4ff6dc64c..24d263dd0 100644 --- a/tests/rendering/Inno.Rendering.Runtime.Tests/ShaderProgramPublicationTests.cs +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.ShaderProgramPublication.cs @@ -3,9 +3,7 @@ using System.Linq; using Xunit; using Inno.Core.Serialization; -using Inno.Rendering; using Inno.Rendering.Assets; -using Inno.Rendering.Runtime; namespace Inno.Rendering.Runtime.Tests; diff --git a/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.cs b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.cs new file mode 100644 index 000000000..cd92fcc53 --- /dev/null +++ b/tests/rendering/Inno.Rendering.Runtime.Tests/RenderRuntimeGenerationTests.cs @@ -0,0 +1,2503 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Assets; +using Inno.Core.Diagnostics; +using Inno.Core.Execution; +using Inno.Core.Identity; +using Inno.Core.Input; +using Inno.Core.Mathematics; +using Inno.Core.Serialization; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Reload; +using Inno.Extensibility.Types; +using Inno.Input; +using Inno.References; +using Inno.Rendering.Assets; +using Inno.Runtime.Contracts; + +namespace Inno.Rendering.Runtime.Tests; + +public sealed partial class RenderRuntimeGenerationTests : IDisposable +{ + private readonly string m_cacheDirectory = Path.Combine( + Path.GetTempPath(), + "InnoRenderRuntimeTests", + Guid.NewGuid().ToString("N") + ); + + private readonly IdentityAllocator m_identities; + private readonly IDisposable m_identityScope; + private readonly ModuleHost m_modules; + private readonly TypeCatalog m_types; + private readonly SerializationRegistry m_serialization; + + public RenderRuntimeGenerationTests() + { + _ = typeof(TextureAsset); + m_identities = new IdentityAllocator(); + m_identityScope = m_identities.EnterScope(); + m_modules = new ModuleHost( + new ModuleHostOptions { catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly)} + ); + m_types = new TypeCatalog(m_modules, new ReflectionTypeCatalogSource()); + m_serialization = new SerializationRegistry(m_types, new ReflectionSerializationMetadataSource()); + ResourceProbePipeline.action = null; + DisposablePipeline.Reset(); + PendingFeature.Reset(); + TestRequestProvider.Reset(); + FirstTestRenderModel.Reset(); + SecondTestRenderModel.Reset(); + CompositionLayerPipeline.viewports.Clear(); + UploadPipeline.Reset(); + TexturePrewarmPipeline.texture = null; + PendingShaderPipeline.Reset(); + ReadbackPipeline.Reset(); + PresentationPipeline.Reset(); + } + + public void Dispose() + { + ResourceProbePipeline.action = null; + m_serialization.Dispose(); + m_types.Dispose(); + m_modules.Dispose(); + m_identityScope.Dispose(); + if (Directory.Exists(m_cacheDirectory)) + { + Directory.Delete(m_cacheDirectory, recursive: true); + } + } + + [Fact] + public void GeometryCandidatePublishesACompletePairAndPreservesOldPairAfterPartialAllocationFailure() + { + IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); + using var runtime = new RenderRuntime(m_types, backend, new TestDiagnosticSink()); + var owner = new AssetRuntimeOwner(); + var geometry = new GeometryAsset(3, 3, 1, default, default); + m_identities.Register(geometry); + byte[] bytes = GeometryArtifact.Encode( + new GeometryData( + [ + new GeometryVertex(default, default, default, default), + new GeometryVertex(default, default, default, default), + new GeometryVertex(default, default, default, default) + ], + [0, 1, 2], + [new GeometrySection(0, 3)] + ) + ); + owner.Initialize(geometry, AssetPath.Project("triangle.obj"), "first", bytes, false, 1); + RenderGeometry? first = null; + ResourceProbePipeline.action = resources => resources.TryResolveGeometry(geometry, out first); + RunResourceFrame(runtime); + Assert.NotNull(first); + Assert.Equal(2, device.createdBuffers.Count); + device.failBufferCreationAt = 4; + owner.Initialize(geometry, AssetPath.Project("triangle.obj"), "second", bytes, false, 2); + RenderGeometry? failed = null; + ResourceProbePipeline.action = resources => resources.TryResolveGeometry(geometry, out failed); + RunResourceFrame(runtime); + Assert.NotNull(failed); + Assert.Equal(first!.vertexBuffer, failed!.vertexBuffer); + Assert.Equal(first.indexBuffer, failed.indexBuffer); + Assert.Equal(device.createdBuffers[2], Assert.Single(device.destroyedBuffers)); + device.failBufferCreationAt = 0; + RunResourceFrame(runtime); + Assert.NotEqual(first.vertexBuffer, failed.vertexBuffer); + Assert.NotEqual(first.indexBuffer, failed.indexBuffer); + Assert.Equal(3, device.destroyedBuffers.Count); + runtime.Dispose(); + Assert.Equal(device.createdBuffers.Count, device.destroyedBuffers.Count); + owner.Release(geometry); + m_identities.Unregister(geometry); + ResourceProbePipeline.action = null; + } + + [Fact] + public void PersistentResourceAdmissionAndReplacementStayBoundedAcrossFrames() + { + IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); + using var runtime = new RenderRuntime( + m_types, + backend, + new TestDiagnosticSink(), + resourceLimits: new RenderResourceLimits { resourcesPerKind = 1 } + ); + var descriptor = new PersistentBufferDescriptor(new RenderBufferDescriptor(4, 4, RenderBufferUsage.Storage)); + int rejected = 0; + for (int frame = 0; frame < 256; frame++) + { + long revision = frame; + ResourceProbePipeline.action = resources => + { + _ = resources.AcquireBuffer(new RenderPersistentResourceID("owned"), revision, descriptor, new byte[16], "owned"); + try + { + resources.AcquireBuffer(new RenderPersistentResourceID("overflow"), revision, descriptor, new byte[16], "overflow"); + } + catch (InvalidOperationException) + { + rejected++; + } + }; + RunResourceFrame(runtime); + Assert.Equal(1, runtime.resourceStatistics.activeResources); + } + Assert.Equal(256, rejected); + Assert.Equal(256, runtime.resourceStatistics.rejectedResources); + runtime.Dispose(); + Assert.Equal(256, device.createdBuffers.Count); + Assert.Equal(256, device.destroyedBuffers.Count); + ResourceProbePipeline.action = null; + } + + [Fact] + public async Task ReadbackAdmissionIsRejectedBeforeAllocatingASecondNativeOperation() + { + var device = new RecordingRenderDevice(supportsReadback: true); + using var runtime = new RenderRuntime( + m_types, + device, + new TestDiagnosticSink(), + resourceLimits: new RenderResourceLimits { pendingReadbacks = 1 } + ); + Task? readback = null; + bool rejected = false; + ResourceProbePipeline.action = resources => + { + readback = resources.ReadTextureAsync(device.textureHandle).AsTask(); + try + { + _ = resources.ReadTextureAsync(device.textureHandle); + } + catch (InvalidOperationException) + { + rejected = true; + } + }; + RunResourceFrame(runtime); + ResourceProbePipeline.action = null; + Assert.True(rejected); + Assert.Equal(1, runtime.resourceStatistics.pendingReadbacks); + Assert.Equal(1, runtime.resourceStatistics.rejectedReadbacks); + runtime.Dispose(); + await Assert.ThrowsAsync(() => readback!); + Assert.Equal(1, device.cancelReadbackCount); + } + + [Fact] + public void SuccessfulTypeCacheChangeRetiresUnrequestedPipelineAtFrameBoundary() + { + IRenderDevice device = TestDeviceProxy.Create(out _); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID }; + + Assert.True(runtime.TryActivateDefaultPipeline(asset)); + Assert.Equal(1, DisposablePipeline.createdCount); + Assert.Equal(0, DisposablePipeline.disposedCount); + + m_types.Rebuild(); + BeginRenderFrame(runtime, 0f); + + Assert.Equal(1, DisposablePipeline.disposedCount); + + runtime.AfterRender(default); + runtime.EndFrame(default); + runtime.Detach(); + } + + [Fact] + public void PendingProviderRetirementIsRetriedBeforeTheSnapshotIsReleased() + { + using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); + Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID })); + TestRequestProvider.pendingRetirements = 2; + + m_types.Rebuild(); + + Assert.Equal(3, TestRequestProvider.retirementAttempts); + Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID })); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void InvalidInitialContributorsFailBeforeRegisteringAnExtensionOwner(bool duplicate) + { + var contributor = new SideEffectContributor(); + IRenderFrameGraphContributor[] contributors = duplicate ? [contributor, contributor] : [null!]; + Assert.Throws(() => new RenderRuntime( + m_types, + TestDeviceProxy.Create(out _), + new TestDiagnosticSink(), + contributors + )); + m_types.Rebuild(); + Assert.Equal(0, TestRequestProvider.retirementAttempts); + } + + [Fact] + public void PendingFeatureRetirementKeepsItsPipelineAliveUntilQuiescent() + { + var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out TestDeviceProxy device), new TestDiagnosticSink()); + Assert.True( + runtime.TryActivateDefaultPipeline(new RenderPipelineAsset + { + pipelineTypeId = DisposablePipeline.C_EXTENSION_ID, + features = [new RenderFeatureConfiguration(PendingFeature.C_EXTENSION_ID)] + }) + ); + PendingFeature.pendingRetirements = 2; + DisposablePipeline.pendingRetirements = 1; + + runtime.Dispose(); + runtime.Dispose(); + + Assert.Equal(3, PendingFeature.retirementAttempts); + Assert.Equal(2, DisposablePipeline.retirementAttempts); + Assert.Equal(1, DisposablePipeline.disposedCount); + Assert.Equal(1, device.endFrameCount); + Assert.Throws(() => runtime.Submit(CreateRequest("Late", new RenderPipelineAsset()))); + } + + [Fact] + public void RejectedPipelineWaitsForItsCandidateToRetireBeforeKeepingLastGood() + { + using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); + var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID }; + Assert.True(runtime.TryActivateDefaultPipeline(asset)); + DisposablePipeline.rejectConfiguration = true; + DisposablePipeline.pendingRetirements = 2; + asset.pipelineState = new SerializedRenderExtensionState(Guid.NewGuid(), [1]); + + Assert.True(runtime.TryActivateDefaultPipeline(asset)); + + Assert.Equal(3, DisposablePipeline.retirementAttempts); + Assert.Equal(1, DisposablePipeline.disposedCount); + DisposablePipeline.rejectConfiguration = false; + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReloadRetirementDrainsPendingBeforeFinishingTheTransaction(bool commit) + { + using var runtime = new RenderRuntime(m_types, TestDeviceProxy.Create(out _), new TestDiagnosticSink()); + Assert.True(runtime.TryActivateDefaultPipeline(new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID })); + IRenderRuntimeReloadTransaction transaction = runtime.BeginExtensionReload(); + transaction.Prepare(); + transaction.Activate(); + DisposablePipeline.pendingRetirements = 2; + + if (commit) + { + transaction.Complete(); + } + else + { + transaction.Rollback(); + } + + Assert.Equal(3, DisposablePipeline.retirementAttempts); + Assert.Equal(1, DisposablePipeline.disposedCount); + runtime.BeginExtensionReload().Rollback(); + } + + [Fact] + public void TargetCapacityRejectsBeforeNativeAllocationAndReopensAfterRelease() + { + IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); + using var targets = new RenderTargetStore(backend, capacity: 1); + backend.BeginFrame(); + var descriptor = new RenderTextureDescriptor( + 16, + 16, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment + ); + var first = new RenderTexture("First", descriptor); + var second = new RenderTexture("Second", descriptor); + var graph = new RenderGraphBuilder(1, backend.capabilities); + targets.Import(graph, first); + Assert.Throws(() => targets.Import(graph, second)); + Assert.Single(device.createdTextures); + Assert.Equal(1, targets.rejectedCount); + targets.Release(first); + targets.PrepareFrame(); + targets.Import(new RenderGraphBuilder(2, backend.capabilities), second); + Assert.Equal(1, targets.count); + targets.Dispose(); + Assert.Equal(device.createdTextures.Count, device.destroyedTextures.Count); + backend.EndFrame(); + } + + [Fact] + public void UploadAdmissionResetsEachFrameWithoutGrowingResidentPages() + { + IRenderDevice backend = TestDeviceProxy.Create(out TestDeviceProxy device); + using var runtime = new RenderRuntime(m_types, backend, new TestDiagnosticSink(), resourceLimits: + new RenderResourceLimits { uploadPages = 1, uploadResidentBytes = 4096, uploadBytesPerFrame = 36 }); + for (int frame = 0; frame < 256; frame++) + { + runtime.Submit(CreateRequest("Upload budget", new RenderPipelineAsset { pipelineTypeId = UploadPipeline.C_EXTENSION_ID })); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(1, runtime.resourceStatistics.uploadPages); + Assert.Equal(36, runtime.resourceStatistics.uploadedFrameBytes); + } + Assert.Equal(256, runtime.resourceStatistics.rejectedUploads); + Assert.Single(device.createdBuffers); + runtime.Dispose(); + Assert.Single(device.destroyedBuffers); + } + + [Fact] + public void TargetRetirementRetainsProgressAndOrdinaryErrorsAcrossPendingRetries() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var targets = new RenderTargetStore(device); + device.BeginFrame(); + var descriptor = new RenderTextureDescriptor( + 16, + 16, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment + ); + var graph = new RenderGraphBuilder(1, device.capabilities); + targets.Import(graph, new RenderTexture("First", descriptor)); + targets.Import(graph, new RenderTexture("Second", descriptor)); + targets.Import(graph, new RenderTexture("Third", descriptor)); + proxy.failFirstTextureRetirement = true; + proxy.pendingTextureRetirement = proxy.createdTextures[1]; + + Assert.Throws(targets.Dispose); + Assert.Equal(2, proxy.textureRetirementAttempts); + Assert.True(proxy.frameOpen); + Assert.Throws(() => targets.Import(graph, new RenderTexture("Late", descriptor))); + Assert.Throws(targets.Dispose); + Assert.Equal(4, proxy.textureRetirementAttempts); + Assert.Equal(proxy.createdTextures.Skip(1), proxy.destroyedTextures); + targets.Dispose(); + Assert.Equal(4, proxy.textureRetirementAttempts); + device.EndFrame(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TerminalPipelineRetirementBlocksAdmissionAndPreservesLowerOwners(bool duringFrame) + { + var modules = new ModuleHost(new ModuleHostOptions + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(EmptyRenderingKernelTests).Assembly) + }); + var types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); + var runtime = new RenderRuntime(types, TestDeviceProxy.Create(out TestDeviceProxy device), new TestDiagnosticSink()); + var asset = new RenderPipelineAsset { pipelineTypeId = DisposablePipeline.C_EXTENSION_ID }; + Assert.True(runtime.TryActivateDefaultPipeline(asset)); + DisposablePipeline.retirementExpired = true; + try + { + if (duringFrame) + { + asset.pipelineState = new SerializedRenderExtensionState(Guid.NewGuid(), [1]); + DisposablePipeline.rejectConfiguration = true; + runtime.Submit(CreateRequest("Faulting candidate", asset)); + BeginRenderFrame(runtime, 0f); + Assert.Throws(() => runtime.AfterRender(default)); + Assert.True(device.frameOpen); + } + else + { + Assert.Throws(runtime.Dispose); + } + Assert.Throws(() => runtime.Submit(CreateRequest("Late", new RenderPipelineAsset()))); + Assert.Throws(() => runtime.RegisterContributor(new SideEffectContributor())); + Assert.Throws(() => runtime.BeginExtensionReload()); + Assert.ThrowsAny(() => types.Rebuild()); + Assert.Equal(1, DisposablePipeline.retirementAttempts); + Assert.Equal(0, TestRequestProvider.retirementAttempts); + Assert.Equal(0, device.endFrameCount); + + DisposablePipeline.retirementExpired = false; + Assert.ThrowsAny(runtime.Dispose); + Assert.ThrowsAny(types.Dispose); + Assert.ThrowsAny(modules.Dispose); + Assert.Equal(1, DisposablePipeline.retirementAttempts); + Assert.Equal(0, device.endFrameCount); + } + finally + { + DisposablePipeline.retirementExpired = false; + DisposablePipeline.rejectConfiguration = false; + } + } + + [Fact] + public void RuntimeKeepsItsMaintenanceFrameOpenUntilTargetsFinishRetiring() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + var target = new RenderTexture( + "Pending Target", + new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment) + ); + runtime.Submit( + new RenderRequest( + "Target", + RenderTarget.FromTexture(target), + new RenderViewport(0, 0, 16, 16), + new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID } + ) + ); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + proxy.pendingTextureRetirement = Assert.Single(proxy.createdTextures); + + runtime.Dispose(); + + Assert.Equal(2, proxy.textureRetirementAttempts); + Assert.Single(proxy.destroyedTextures); + Assert.False(proxy.frameOpen); + Assert.Equal(2, proxy.endFrameCount); + } + + [Fact] + public void RemovingAndRestoringPluginRenderingCommitsTheSameUnavailableStateAsColdStart() + { + const string C_EXTENSION_ID = "tests.runtime.reloadable-plugin"; + DotNetModuleSource plugin = CreateRenderingPluginRequest(); + AssemblyModuleHandle activeModule = m_modules.Load(plugin); + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var diagnostics = new TestDiagnosticSink(); + using var runtime = new RenderRuntime(m_types, device, diagnostics); + var asset = new RenderPipelineAsset { pipelineTypeId = C_EXTENSION_ID }; + var featureAsset = new RenderPipelineAsset + { + pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID, + features = [new RenderFeatureConfiguration("tests.runtime.reloadable-plugin-feature")] + }; + + runtime.Submit(CreateRequest("Before Removal", asset)); + runtime.Submit(CreateRequest("Feature Before Removal", featureAsset)); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(1, proxy.executeCount); + proxy.ReleaseRecordedGraph(); + + QueueCollectiblePayload(runtime, m_types, asset); + (IAssemblyUnloadProbe removalMonitor, IRenderRuntimeReloadTransaction renderingRemoval) = RemoveRenderingPlugin( + runtime, + m_modules, + plugin + ); + + ForceCollection(); + Assert.True(removalMonitor.isCompleted); + GC.KeepAlive(renderingRemoval); + + runtime.Submit(CreateRequest("While Unavailable", asset)); + runtime.Submit(CreateRequest("Feature While Unavailable", featureAsset)); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(1, proxy.executeCount); + Assert.DoesNotContain( + diagnostics.items, + static diagnostic => diagnostic.code == "RENDER_EXTENSION_RELOAD_REJECTED" + ); + + IRenderRuntimeReloadTransaction renderingRecovery = runtime.BeginExtensionReload(); + using (AssemblyReloadSession recovery = m_modules.BeginReload([plugin])) + { + activeModule = recovery.context.module; + recovery.Activate(); + renderingRecovery.Prepare(); + renderingRecovery.Activate(); + _ = recovery.Complete(); + renderingRecovery.Complete(); + } + + runtime.Submit(CreateRequest("After Recovery", asset)); + runtime.Submit(CreateRequest("Feature After Recovery", featureAsset)); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(2, proxy.executeCount); + + proxy.ReleaseRecordedGraph(); + runtime.Detach(); + IAssemblyUnloadProbe recoveryMonitor = m_modules.Unload(activeModule); + ForceCollection(); + Assert.True(recoveryMonitor.isCompleted); + } + + [Fact] + public void RemovingUnusedRenderingPluginReleasesItsAssemblyContext() + { + DotNetModuleSource plugin = CreateRenderingPluginRequest(); + _ = m_modules.Load(plugin); + IAssemblyUnloadProbe monitor = RemoveUnusedPlugin(m_modules, plugin); + + ForceCollection(); + + Assert.True(monitor.isCompleted); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FrameStatisticsReportBackendCommandsAndGraphCulling(bool reportsAllocations) + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + proxy.frameCounters = new RenderDeviceFrameCounters(3, 2); + proxy.allocationCounters = reportsAllocations + ? new RenderDeviceAllocationCounters(device.generation, 17, 23, 11) + : null; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + using IDisposable executionScope = runtime.EnterExecutionScope(); + var asset = new RenderPipelineAsset { pipelineTypeId = StatisticsPipeline.C_EXTENSION_ID }; + runtime.Attach(); + Assert.True(runtime.TryActivateDefaultPipeline(asset)); + runtime.Submit( + new RenderRequest("Statistics", RenderTarget.backbuffer, new RenderViewport(0, 0, 64, 64), asset) + ); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + RenderFrameStatistics statistics = Assert.IsType(GraphicsSettings.frameStatistics); + Assert.Equal(1, statistics.viewCount); + Assert.Equal(3, statistics.drawCount); + Assert.Equal(2, statistics.dispatchCount); + Assert.Equal(1, statistics.culledPassCount); + Assert.Equal(proxy.allocationCounters, statistics.allocationCounters); + proxy.allocationCounters = new RenderDeviceAllocationCounters(device.generation, 19, 25, 13); + Assert.NotEqual(proxy.allocationCounters, statistics.allocationCounters); + runtime.Detach(); + } + + [Fact] + public void DeviceSynchronizationIsRequiredAndUnsupportedDiagnosticsAreExplicitlyUnavailable() + { + Assert.True(typeof(IRenderDevice).GetMethod(nameof(IRenderDevice.SetVerticalSync))!.IsAbstract); + using var backend = new RecordingRenderDevice(); + IRenderDevice device = backend; + device.SetVerticalSync(true); + Assert.True(backend.verticalSync); + device.SetVerticalSync(false); + Assert.False(backend.verticalSync); + Assert.Null(device.allocationCounters); + Assert.Throws(() => new RenderDeviceAllocationCounters(0, 0, 0, 0)); + } + + [Fact] + public void GraphicsFacadeResolvesTheCurrentlyBoundRenderingRuntime() + { + IRenderDevice firstDevice = TestDeviceProxy.Create(out TestDeviceProxy firstProxy); + IRenderDevice secondDevice = TestDeviceProxy.Create(out TestDeviceProxy secondProxy); + firstProxy.frameCounters = new RenderDeviceFrameCounters(2, 0); + secondProxy.frameCounters = new RenderDeviceFrameCounters(7, 1); + using var first = new RenderRuntime(m_types, firstDevice, new TestDiagnosticSink()); + using var second = new RenderRuntime(m_types, secondDevice, new TestDiagnosticSink()); + var asset = new RenderPipelineAsset { pipelineTypeId = StatisticsPipeline.C_EXTENSION_ID }; + + using (first.EnterExecutionScope()) + { + first.Attach(); + Assert.True(first.TryActivateDefaultPipeline(asset)); + first.Submit(CreateRequest("First Runtime", asset)); + BeginRenderFrame(first, 0f); + first.AfterRender(default); + first.EndFrame(default); + Assert.Equal(2, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); + + using (second.EnterExecutionScope()) + { + second.Attach(); + Assert.True(second.TryActivateDefaultPipeline(asset)); + second.Submit(CreateRequest("Second Runtime", asset)); + BeginRenderFrame(second, 0f); + second.AfterRender(default); + second.EndFrame(default); + Assert.Equal(7, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); + } + + Assert.Equal(2, Assert.IsType(GraphicsSettings.frameStatistics).drawCount); + } + + Assert.Null(GraphicsSettings.frameStatistics); + Assert.Throws(() => GraphicsSettings.defaultPipeline = asset); + second.Detach(); + first.Detach(); + } + + [Fact] + public void RequestProviderProducesCurrentFrameWorkThroughPublicPluginApi() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; + TestRequestProvider.pipeline = asset; + TestRequestProvider.enabled = true; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Attach(); + + BeginRenderFrame(runtime, 1f / 60f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, TestRequestProvider.submitCount); + Assert.Equal(1, proxy.executeCount); + CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); + Assert.Equal("Request[0] Provider Request/Visible", pass.name); + runtime.Detach(); + } + + [Fact] + public void RequestProviderReceivesExplicitHostContentScope() + { + IRenderDevice device = TestDeviceProxy.Create(out _); + Guid contentID = Guid.Parse("3aee0ced-b598-4366-ab45-a6ef8e0feb30"); + var content = new TestContent(); + var identities = new IdentityAllocator(); + identities.Register(content, contentID); + var scope = new ContentReadScope([content.identity], contentID); + Assert.True(scope.TryGetValue(contentID, out TestContent? resolved)); + Assert.Same(content, resolved); + TestRequestProvider.enabled = true; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), contentScopeProvider: () => scope); + runtime.Attach(); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Same(scope, TestRequestProvider.lastContent); + Assert.Throws(() => scope.TryGetValue(contentID, out TestContent? _)); + runtime.Detach(); + } + + [Fact] + public void PrimaryPresentationViewportIsSharedAndLetterboxSurfaceIsCleared() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + proxy.presentationSize = new RenderPresentationSize(1000, 1000); + TestRequestProvider.enabled = true; + var runtime = new RenderRuntime( + m_types, + device, + new TestDiagnosticSink(), + primaryPresentationViewportProvider: static size => new RenderViewport( + 0, + (size.height - 562) / 2, + size.width, + 562 + ) + ); + runtime.Attach(); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(new RenderViewport(0, 219, 1000, 562), TestRequestProvider.lastPresentationViewport); + CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); + Assert.Equal("Primary Presentation Background", pass.name); + Assert.True(pass.clearsPresentationTarget); + Assert.Equal(new RenderClearColor(0f, 0f, 0f, 1f), pass.presentationClearColor); + runtime.Detach(); + } + + [Fact] + public void PrimaryOutputScalesLogicalWindowPointerToPhysicalPixels() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + proxy.presentationSize = new RenderPresentationSize(2560, 1440); + TestRequestProvider.enabled = true; + var snapshot = new InputSnapshot( + 1, + mousePosition: new Vector2(400f, 274f), + mouseButtonsPressed: [MouseButton.Left] + ); + using var runtime = new RenderRuntime( + m_types, + device, + new TestDiagnosticSink(), + inputSnapshotProvider: () => snapshot, + primaryInputSurfaceSizeProvider: static () => new RenderPresentationSize(1280, 720) + ); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(new Vector2(800f, 548f), TestRequestProvider.lastInput.pointerPosition); + Assert.Single(TestRequestProvider.lastInput.buttonsPressed); + } + + [Fact] + public void CompetingModelsDoNotShareATargetWhenAnExactRouteExists() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var diagnostics = new TestDiagnosticSink(); + proxy.capabilities = new GraphicsCapabilities( + GraphicsApi.metal, + GraphicsCapability.None, + new GraphicsLimits(64, 4, 4096, 8), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); + proxy.presentationSize = new RenderPresentationSize(1000, 1000); + FirstTestRenderModel.enabled = true; + SecondTestRenderModel.enabled = true; + using var runtime = new RenderRuntime( + m_types, + device, + diagnostics, + primaryPresentationViewportProvider: static _ => new RenderViewport(100, 200, 800, 600), + compositionProgramProvider: new TestCompositionProgramProvider() + ); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(0, FirstTestRenderModel.buildCount); + Assert.Equal(0, SecondTestRenderModel.buildCount); + Assert.Contains(diagnostics.items, item => ( + item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" + && item.message.Contains("Multiple rendering models", StringComparison.Ordinal) + )); + + runtime.SetPrimaryRoute( + new RenderOutputRoute( + [ + new RenderOutputLayer(SecondTestRenderModel.C_EXTENSION_ID, []), + new RenderOutputLayer(FirstTestRenderModel.C_EXTENSION_ID, []) + ] + ) + ); + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Equal(1, FirstTestRenderModel.buildCount); + Assert.Equal(1, SecondTestRenderModel.buildCount); + Assert.Equal( + [new RenderViewport(0, 0, 800, 600), new RenderViewport(0, 0, 800, 600)], + CompositionLayerPipeline.viewports + ); + Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE"); + Assert.DoesNotContain(diagnostics.items, item => ( + item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" + && item.message.Contains("independent model targets", StringComparison.Ordinal) + )); + Assert.True( + diagnostics.items.All(item => item.code != "RENDER_OUTPUT_COMPOSITION_FAILED"), + string.Join("\n", diagnostics.items.Select(item => item.message)) + ); + Assert.True(proxy.lastGraph is not null, string.Join("\n", diagnostics.items.Select(item => item.message))); + Assert.Contains(proxy.lastGraph.passes, pass => pass.name.Contains("Layer 2", StringComparison.Ordinal)); + runtime.Detach(); + } + + [Fact] + public void OutputWithoutAnApplicableModelReportsItsMissingRenderer() + { + var diagnostics = new TestDiagnosticSink(); + using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), diagnostics); + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.Contains(diagnostics.items, item => ( + item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE" + && item.message.Contains("No rendering model", StringComparison.Ordinal) + )); + runtime.Detach(); + } + + [Fact] + public void LinearPresentationReceivesOneTransferAfterAllModelLayers() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + proxy.primaryPresentationEncodesSrgb = false; + proxy.presentationSize = new RenderPresentationSize(800, 600); + FirstTestRenderModel.enabled = true; + SecondTestRenderModel.enabled = true; + var diagnostics = new TestDiagnosticSink(); + using var runtime = new RenderRuntime( + m_types, + device, + diagnostics, + compositionProgramProvider: new TestCompositionProgramProvider() + ); + runtime.SetPrimaryRoute( + new RenderOutputRoute( + [ + new RenderOutputLayer(FirstTestRenderModel.C_EXTENSION_ID, []), + new RenderOutputLayer(SecondTestRenderModel.C_EXTENSION_ID, []) + ] + ) + ); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_COMPOSITION_FAILED"); + Assert.NotNull(proxy.lastGraph); + Assert.Single(proxy.lastGraph.passes.Where(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal))); + Assert.Contains("Output Transfer", proxy.lastGraph.passes[^1].name, StringComparison.Ordinal); + Assert.Contains(proxy.lastGraph.textures, texture => ( + texture.name.EndsWith("/Composition", StringComparison.Ordinal) + && texture.descriptor.width == 800 + && texture.descriptor.height == 600 + && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb + )); + runtime.Detach(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void SingleModelPresentationEncodesColorExactlyOnce(bool presentationEncodesSrgb) + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + proxy.primaryPresentationEncodesSrgb = presentationEncodesSrgb; + proxy.presentationSize = new RenderPresentationSize(800, 600); + FirstTestRenderModel.enabled = true; + var diagnostics = new TestDiagnosticSink(); + using var runtime = new RenderRuntime( + m_types, + device, + diagnostics, + compositionProgramProvider: new TestCompositionProgramProvider() + ); + + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, FirstTestRenderModel.buildCount); + Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_COMPOSITION_FAILED"); + Assert.NotNull(proxy.lastGraph); + Assert.Equal( + presentationEncodesSrgb ? 0 : 1, + proxy.lastGraph.passes.Count(pass => pass.name.Contains("Output Transfer", StringComparison.Ordinal)) + ); + Assert.DoesNotContain( + proxy.lastGraph.textures, + texture => texture.name.EndsWith("/Composition", StringComparison.Ordinal) + ); + if (!presentationEncodesSrgb) + { + Assert.Contains("Output Transfer", proxy.lastGraph.passes[^1].name, StringComparison.Ordinal); + Assert.Contains(proxy.lastGraph.textures, texture => ( + texture.name.Contains("Model Layer 1", StringComparison.Ordinal) + && texture.descriptor.format == RenderTextureFormat.RGBA8Srgb + )); + } + runtime.Detach(); + } + + [Fact] + public void EditorOwnedOffscreenOutputsDoNotReportAnUnusedPrimaryModel() + { + var diagnostics = new TestDiagnosticSink(); + using var runtime = new RenderRuntime(m_types, new RecordingRenderDevice(), diagnostics); + runtime.SetPrimaryModelOutputEnabled(false); + BeginRenderFrame(runtime, 0f); + runtime.Render(default); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.DoesNotContain(diagnostics.items, item => item.code == "RENDER_OUTPUT_MODEL_UNAVAILABLE"); + runtime.Detach(); + } + + [Fact] + public void MultipleRequestsAndContributorsCompileAndExecuteAsOneFrameGraph() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; + var contributor = new SideEffectContributor(); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), [contributor]); + runtime.Submit(CreateRequest("Second", asset, priority: 10)); + runtime.Submit(CreateRequest("First", asset, priority: -10)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, proxy.executeCount); + string[] names = Assert.IsType(proxy.lastGraph).passes + .Select(static pass => pass.name) + .ToArray(); + string[] expectedNames = + [ + "Request[0] First/Visible", + "Request[1] Second/Visible", + "Contributor[0] SideEffectContributor/Overlay" + ]; + Assert.Equal(expectedNames, names); + runtime.Detach(); + } + + [Fact] + public void OverlappingRequestsPreserveEarlierPresentationLayersInSchedulingOrder() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var asset = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(CreateRequest("Overlay", asset, priority: 100)); + runtime.Submit(CreateRequest("Base", asset, priority: 0)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal( + new[] + { + new PresentationObservation("Base", false), + new PresentationObservation("Overlay", true) + }, + PresentationPipeline.observations + ); + Assert.Equal(1, proxy.executeCount); + runtime.Detach(); + } + + [Fact] + public void DisjointViewportsCanInitializeTheSamePresentationTargetIndependently() + { + IRenderDevice device = TestDeviceProxy.Create(out _); + var asset = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(new RenderRequest("Left", RenderTarget.backbuffer, new RenderViewport(0, 0, 32, 64), asset)); + runtime.Submit(new RenderRequest("Right", RenderTarget.backbuffer, new RenderViewport(32, 0, 32, 64), asset)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal( + new[] + { + new PresentationObservation("Left", false), + new PresentationObservation("Right", false) + }, + PresentationPipeline.observations + ); + runtime.Detach(); + } + + [Fact] + public void FailedRequestDoesNotClaimThePresentationTarget() + { + IRenderDevice device = TestDeviceProxy.Create(out _); + var failed = new RenderPipelineAsset { pipelineTypeId = ThrowingPipeline.C_EXTENSION_ID }; + var valid = new RenderPipelineAsset { pipelineTypeId = PresentationPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(CreateRequest("Failed", failed, priority: 0)); + runtime.Submit(CreateRequest("Recovery", valid, priority: 100)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(new[] { new PresentationObservation("Recovery", false) }, PresentationPipeline.observations); + runtime.Detach(); + } + + [Fact] + public void ReplacedAndReleasedTargetsRemainValidAcrossPreparedPresentationFrames() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var registry = new RenderTargetStore(device); + var target = new RenderTexture( + "Deferred Target", + new RenderTextureDescriptor( + 32, + 32, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); + + device.BeginFrame(); + registry.PrepareFrame(); + _ = registry.Import(new RenderGraphBuilder(1, device.capabilities), target); + _ = device.EndFrame(); + PersistentTextureHandle first = Assert.Single(proxy.createdTextures); + + target.Resize( + new RenderTextureDescriptor( + 64, + 64, + RenderTextureFormat.RGBA8, + RenderTextureUsage.ColorAttachment | RenderTextureUsage.Sampled + ) + ); + device.BeginFrame(); + registry.PrepareFrame(); + _ = registry.Import(new RenderGraphBuilder(2, device.capabilities), target); + _ = device.EndFrame(); + PersistentTextureHandle second = proxy.createdTextures[1]; + Assert.Empty(proxy.destroyedTextures); + + device.BeginFrame(); + registry.PrepareFrame(); + _ = device.EndFrame(); + Assert.Empty(proxy.destroyedTextures); + + device.BeginFrame(); + registry.PrepareFrame(); + _ = device.EndFrame(); + Assert.Equal(new[] { first }, proxy.destroyedTextures); + + registry.Release(target); + for (int frame = 0; frame < 2; frame++) + { + device.BeginFrame(); + registry.PrepareFrame(); + _ = device.EndFrame(); + } + Assert.Equal(new[] { first }, proxy.destroyedTextures); + + device.BeginFrame(); + registry.PrepareFrame(); + registry.Dispose(); + _ = device.EndFrame(); + Assert.Equal(new[] { first, second }, proxy.destroyedTextures); + } + + [Fact] + public void DetachUsesADeviceSafetyFrameToReleaseResidentTargets() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + var asset = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; + var target = new RenderTexture( + "Detach Target", + new RenderTextureDescriptor(16, 16, RenderTextureFormat.RGBA8, RenderTextureUsage.ColorAttachment) + ); + runtime.Submit( + new RenderRequest("Detach", RenderTarget.FromTexture(target), new RenderViewport(0, 0, 16, 16), asset) + ); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + PersistentTextureHandle resident = Assert.Single(proxy.createdTextures); + + runtime.Detach(); + + Assert.Equal(new[] { resident }, proxy.destroyedTextures); + Assert.False(proxy.frameOpen); + Assert.Equal(2, proxy.endFrameCount); + } + + [Fact] + public void FailedRequestRollsBackWithoutDiscardingOtherRequests() + { + IRenderDevice device = TestDeviceProxy.Create(out TestDeviceProxy proxy); + var diagnostics = new TestDiagnosticSink(); + var failed = new RenderPipelineAsset { pipelineTypeId = ThrowingPipeline.C_EXTENSION_ID }; + var valid = new RenderPipelineAsset { pipelineTypeId = SideEffectPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, diagnostics); + runtime.Submit(CreateRequest("A Failed", failed)); + runtime.Submit(CreateRequest("B Valid", valid)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, proxy.executeCount); + CompiledRenderPass pass = Assert.Single(Assert.IsType(proxy.lastGraph).passes); + Assert.Equal("Request[1] B Valid/Visible", pass.name); + Assert.Contains(diagnostics.items, diagnostic => diagnostic.code == "RENDER_REQUEST_FAILED"); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Assert.DoesNotContain(diagnostics.items, diagnostic => diagnostic.code == "RENDER_REQUEST_FAILED"); + runtime.Detach(); + } + + [Fact] + public void FrameUploadsReusePagesAndResetSliceOffsetsBetweenFrames() + { + var device = new RecordingRenderDevice(); + var asset = new RenderPipelineAsset { pipelineTypeId = UploadPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + + runtime.Submit(CreateRequest("Upload A", asset)); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, device.createBufferCount); + Assert.Equal(new[] { 0, 3 }, device.bufferUpdateOffsets.ToArray()); + Assert.Equal(0, UploadPipeline.firstSlice.firstElement); + Assert.Equal(3, UploadPipeline.secondSlice.firstElement); + Assert.Equal(3, UploadPipeline.secondSlice.elementCount); + + UploadPipeline.singleUpload = true; + runtime.Submit(CreateRequest("Upload B", asset)); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, device.createBufferCount); + Assert.Equal(new[] { 0, 3, 0 }, device.bufferUpdateOffsets.ToArray()); + Assert.Equal(0, UploadPipeline.firstSlice.firstElement); + runtime.Detach(); + } + + [Fact] + public void TexturePrewarmRunsOutsideTheRenderFrameAndDoesNotDelaySubmission() + { + var texture = new TextureAsset(1, 1, TextureColorSpace.Srgb, "png"); + Assert.True(m_identities.Register(texture)); + TexturePrewarmPipeline.texture = texture; + + var compiler = new DelayedTextureArtifactSource(); + var device = new RecordingRenderDevice(); + var asset = new RenderPipelineAsset { pipelineTypeId = TexturePrewarmPipeline.C_EXTENSION_ID }; + var artifacts = new DelayedArtifactProvider(compiler); + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink(), targetArtifacts: artifacts); + runtime.Submit(CreateRequest("Prewarm", asset)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, device.endFrameCount); + Assert.True(compiler.started.Wait(TimeSpan.FromSeconds(2))); + Assert.False(compiler.isCompleted); + compiler.Complete([1, 2, 3, 4]); + runtime.Detach(); + } + + [Fact] + public void PendingShaderCompilationDoesNotPublishAnUnavailableArtifactError() + { + var contract = new ShaderContractID("tests.pending.contract"); + var role = new ShaderPassRoleID("draw"); + var pass = new ShaderPassDefinition("draw", ShaderProgramKind.Raster); + var shader = new ShaderAsset(); + Assert.True(m_identities.Register(shader)); + shader.SetDefinition( + new ShaderDefinition( + "Pending Shader", + [], + [], + [pass], + [new ShaderTechniqueDefinition( + new ShaderTechniqueID("default"), + contract, + [new ShaderTechniquePass(role, pass.name)] + )] + ), + m_serialization, + SerializationContext.empty + ); + PendingShaderPipeline.material = new MaterialAsset { shader = shader }; + PendingShaderPipeline.contract = contract; + PendingShaderPipeline.role = role; + + var diagnostics = new TestDiagnosticSink(); + var compiler = new DelayedTextureArtifactSource(); + var runtime = new RenderRuntime( + m_types, + new RecordingRenderDevice(), + diagnostics, + targetArtifacts: new DelayedArtifactProvider(compiler) + ); + var asset = new RenderPipelineAsset { pipelineTypeId = PendingShaderPipeline.C_EXTENSION_ID }; + runtime.Submit(CreateRequest("Pending Shader", asset)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.False(PendingShaderPipeline.resolved); + Assert.DoesNotContain( + diagnostics.items, + static diagnostic => diagnostic.code == "RENDER_SHADER_TARGET_UNAVAILABLE" + ); + runtime.Detach(); + } + + [Fact] + public async Task PersistentTextureRegionUpdateAndReadbackCompleteAcrossFrameBoundaries() + { + var device = new RecordingRenderDevice(supportsReadback: true); + ReadbackPipeline.texture = device.textureHandle; + var asset = new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(CreateRequest("Readback", asset)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(new RenderTextureRegion(0, 1, 1, 0, 2, 2), device.updatedRegion); + Assert.Equal(Enumerable.Range(0, 16).Select(static value => (byte)value), device.updatedBytes); + Task readback = Assert.IsType>( + ReadbackPipeline.readback + ); + Assert.False(readback.IsCompleted); + + device.readbackReady = true; + BeginRenderFrame(runtime, 0f); + RenderTextureReadbackResult result = await readback; + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(16, result.rowPitch); + Assert.Equal(64, result.data.Length); + Assert.All(result.data.ToArray(), static value => Assert.Equal((byte)37, value)); + runtime.Detach(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task PendingUploadOrReadbackRetirementPreservesDependentWork(bool pendingReadback) + { + var device = new RecordingRenderDevice(supportsReadback: true); + ReadbackPipeline.texture = device.textureHandle; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(CreateRequest("Upload", new RenderPipelineAsset { pipelineTypeId = UploadPipeline.C_EXTENSION_ID })); + runtime.Submit(CreateRequest("Readback", new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.C_EXTENSION_ID })); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + Task readback = Assert.IsType>(ReadbackPipeline.readback); + device.pendingBufferRetirements = pendingReadback ? 0 : 1; + device.pendingReadbackRetirements = pendingReadback ? 1 : 0; + + runtime.Dispose(); + + Assert.Equal(pendingReadback ? 1 : 2, device.bufferRetirementAttempts); + Assert.Equal(pendingReadback ? 2 : 1, device.cancelReadbackCount); + Assert.Equal(2, device.endFrameCount); + await Assert.ThrowsAsync(async () => await readback); + runtime.Dispose(); + Assert.Equal(2, device.endFrameCount); + } + + [Fact] + public async Task CancelingReadbackReleasesTheDeviceOperationAtTheNextFrameBoundary() + { + var device = new RecordingRenderDevice(supportsReadback: true); + using var cancellation = new CancellationTokenSource(); + ReadbackPipeline.texture = device.textureHandle; + ReadbackPipeline.cancellationToken = cancellation.Token; + var asset = new RenderPipelineAsset { pipelineTypeId = ReadbackPipeline.C_EXTENSION_ID }; + var runtime = new RenderRuntime(m_types, device, new TestDiagnosticSink()); + runtime.Submit(CreateRequest("Canceled Readback", asset)); + + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + cancellation.Cancel(); + Task readback = Assert.IsType>( + ReadbackPipeline.readback + ); + Assert.False(readback.IsCompleted); + BeginRenderFrame(runtime, 0f); + await Assert.ThrowsAnyAsync(async () => await readback); + runtime.AfterRender(default); + runtime.EndFrame(default); + + Assert.Equal(1, device.cancelReadbackCount); + runtime.Detach(); + } + + private DotNetModuleSource CreateRenderingPluginRequest() + => new() + { + moduleName = "RenderingRuntimeReloadTests", + artifactRootDirectory = Path.Combine(m_cacheDirectory, "Modules"), + mainAssemblyPath = Path.Combine( + AppContext.BaseDirectory, + "Modules", + "RenderingReload", + "Inno.Rendering.Runtime.Reload.TestModule.dll" + ), + domain = AssemblyDomain.InnoPlugin, + scope = AssemblyScope.Runtime + }; + + private static void RunResourceFrame(RenderRuntime runtime) + { + runtime.Submit( + CreateRequest("Resource ownership", new RenderPipelineAsset { pipelineTypeId = ResourceProbePipeline.C_EXTENSION_ID }) + ); + BeginRenderFrame(runtime, 0f); + runtime.AfterRender(default); + runtime.EndFrame(default); + } + + private static RenderRequest CreateRequest( + string name, + RenderPipelineAsset pipeline, + int priority = 0 + ) => new(name, RenderTarget.backbuffer, new RenderViewport(0, 0, 64, 64), pipeline, priority: priority); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static ( + IAssemblyUnloadProbe monitor, + IRenderRuntimeReloadTransaction transaction) RemoveRenderingPlugin( + RenderRuntime runtime, + ModuleHost modules, + DotNetModuleSource plugin + ) { + IRenderRuntimeReloadTransaction rendering = runtime.BeginExtensionReload(); + using AssemblyReloadSession removal = modules.BeginReload([], [plugin.moduleName]); + removal.Activate(); + rendering.Prepare(); + rendering.Activate(); + IAssemblyUnloadProbe monitor = removal.Complete(); + rendering.Complete(); + return (monitor, rendering); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static IAssemblyUnloadProbe RemoveUnusedPlugin( + ModuleHost modules, + DotNetModuleSource plugin + ) { + using AssemblyReloadSession removal = modules.BeginReload([], [plugin.moduleName]); + removal.Activate(); + return removal.Complete(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void QueueCollectiblePayload( + RenderRuntime runtime, + TypeCatalog types, + RenderPipelineAsset pipeline + ) { + Type payloadType = types.current.types + .Select(type => type.Resolve(types)) + .Single(type => string.Equals( + type.FullName, + "Inno.Rendering.Runtime.Reload.TestModule.ReloadableFramePayload", + StringComparison.Ordinal + )); + object payload = Activator.CreateInstance(payloadType) + ?? throw new InvalidOperationException("The collectible frame payload could not be created."); + var data = new RenderFrameData(); + data.Set(new RenderDataChannelID("tests.runtime.collectible-payload"), payload); + runtime.Submit( + new RenderRequest( + "Collectible Pending Request", + RenderTarget.backbuffer, + new RenderViewport(0, 0, 64, 64), + pipeline, + data + ) + ); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ForceCollection() + { + for (int attempt = 0; attempt < 8; attempt++) + { + GC.Collect(2, GCCollectionMode.Forced, blocking: true, compacting: true); + GC.WaitForPendingFinalizers(); + } + } + + private static void BeginRenderFrame( + RenderRuntime runtime, + float deltaTime + ) { + if (!runtime.isStarted) + { + runtime.Attach(); + } + var frame = new RuntimeFrame(0, deltaTime, deltaTime, 0, 0, 1, false); + runtime.BeginFrame(frame); + runtime.BeforeRender(frame); + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class ResourceProbePipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.resource-owner"; + internal static Action? action; + + public override void Build(RenderPipelineContext context) + { + action?.Invoke(context.resourceService); + context.graph.AddRasterPass("Resources", new RenderPhaseID("tests.resources"), 0, static ( + _, + _ + ) => {}).HasSideEffect(); + } + } + + private sealed class TestContent : IdentityObject; + + [RenderModelExtension(C_EXTENSION_ID)] + private sealed class FirstTestRenderModel : IRenderModel + { + internal const string C_EXTENSION_ID = "tests.runtime.model.first"; + internal static bool enabled; + internal static int buildCount; + + public bool CanRender(RenderOutputSession session) => enabled; + + public RenderModelOutput Build(RenderOutputSession session) + { + buildCount++; + return new RenderModelOutput( + "First Model", + new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.C_EXTENSION_ID }, + new RenderFrameData() + ); + } + + public void Dispose() {} + + internal static void Reset() + { + enabled = false; + buildCount = 0; + } + } + + [RenderModelExtension(C_EXTENSION_ID)] + private sealed class SecondTestRenderModel : IRenderModel + { + internal const string C_EXTENSION_ID = "tests.runtime.model.second"; + internal static bool enabled; + internal static int buildCount; + + public bool CanRender(RenderOutputSession session) => enabled; + + public RenderModelOutput Build(RenderOutputSession session) + { + buildCount++; + return new RenderModelOutput( + "Second Model", + new RenderPipelineAsset { pipelineTypeId = CompositionLayerPipeline.C_EXTENSION_ID }, + new RenderFrameData() + ); + } + + public void Dispose() {} + + internal static void Reset() + { + enabled = false; + buildCount = 0; + } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class DisposablePipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.disposable"; + + public DisposablePipeline() + { + createdCount++; + } + + public override void Build(RenderPipelineContext context) => _ = context; + + internal static int createdCount { get; private set; } + internal static int disposedCount { get; private set; } + internal static bool rejectConfiguration { get; set; } + internal static int pendingRetirements { get; set; } + internal static int retirementAttempts { get; private set; } + internal static bool retirementExpired { get; set; } + + protected override void OnConfigure( + SerializedRenderExtensionState state, + RenderExtensionStateContext settings + ) { + _ = state; + if (rejectConfiguration) + { + throw new InvalidOperationException("Rejected pipeline configuration candidate."); + } + } + + protected override void Dispose(bool disposing) + { + _ = disposing; + retirementAttempts++; + if (retirementExpired) + { + throw new RetirementTimeoutException("The pipeline-owned device work exceeded its deadline."); + } + if (pendingRetirements > 0) + { + pendingRetirements--; + throw new RetirementPendingException("Pipeline work remains active."); + } + disposedCount++; + } + + internal static void Reset() + { + createdCount = 0; + disposedCount = 0; + rejectConfiguration = false; + pendingRetirements = 0; + retirementAttempts = 0; + retirementExpired = false; + } + } + + [RenderFeatureExtension(C_EXTENSION_ID)] + private sealed class PendingFeature : RenderPipelineFeature, IDisposable + { + internal const string C_EXTENSION_ID = "tests.runtime.pending-feature"; + + public override void AddRenderPasses(RenderFeatureContext context) {} + + public void Dispose() + { + retirementAttempts++; + Assert.Equal(0, DisposablePipeline.disposedCount); + if (pendingRetirements > 0) + { + pendingRetirements--; + throw new RetirementPendingException("Feature work remains active."); + } + } + + internal static int pendingRetirements { get; set; } + internal static int retirementAttempts { get; private set; } + + internal static void Reset() + { + retirementAttempts = 0; + pendingRetirements = 0; + } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class StatisticsPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.statistics"; + + public override void Build(RenderPipelineContext context) + { + context.graph + .AddRasterPass( + "Visible", + new RenderPhaseID("tests.statistics.visible"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + context.graph.AddRasterPass( + "Culled", + new RenderPhaseID("tests.statistics.culled"), + 0, + static ( + _, + _ + ) => {} + ); + } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class CompositionLayerPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.composition-layer"; + + public override void Build(RenderPipelineContext context) + { + viewports.Add(context.request.viewport); + RasterPassBuilder pass = context.graph.AddRasterPass( + "Scene Color", + new RenderPhaseID("tests.runtime.composition-layer"), + 0, + static ( + _, + _ + ) => {} + ); + if (context.outputTexture.isValid) + { + pass.UseColorAttachment( + context.outputTexture, + 0, + RenderLoadAction.Clear, + RenderStoreAction.Store, + new RenderClearColor(0f, 0f, 0f, 0f) + ); + } + else + { + pass.ClearPresentationTarget(default).HasSideEffect(); + } + } + + internal static List viewports { get; } = []; + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class SideEffectPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.side-effect"; + + public override void Build(RenderPipelineContext context) + => context.graph + .AddRasterPass( + "Visible", + new RenderPhaseID("tests.runtime.visible"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class PresentationPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.presentation"; + + public override void Build(RenderPipelineContext context) + { + observations.Add(new PresentationObservation(context.request.name, context.preservePresentationTarget)); + context.graph + .AddRasterPass( + "Presentation", + new RenderPhaseID("tests.runtime.presentation"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + + internal static List observations { get; } = []; + + internal static void Reset() => observations.Clear(); + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class ThrowingPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.throwing"; + + public override void Build(RenderPipelineContext context) + { + context.graph + .AddRasterPass( + "Rolled Back", + new RenderPhaseID("tests.runtime.rolled-back"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + throw new InvalidOperationException("Expected request failure."); + } + } + + private readonly record struct PresentationObservation( + string requestName, + bool preserveTarget + ); + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class UploadPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.upload"; + + public override void Build(RenderPipelineContext context) + { + var layout = new RenderVertexLayout( + [ + new RenderVertexAttribute(RenderVertexSemantic.Position, RenderVertexFormat.Float3) + ] + ); + var descriptor = new RenderBufferUploadDescriptor(layout.stride, RenderBufferUsage.Vertex, layout); + firstSlice = context.uploads.UploadBuffer(descriptor, new byte[layout.stride * 3], "Vertices"); + if (!singleUpload) + { + secondSlice = context.uploads.UploadBuffer(descriptor, new byte[layout.stride * 3], "Vertices"); + } + } + + internal static RenderBufferSlice firstSlice { get; private set; } + internal static RenderBufferSlice secondSlice { get; private set; } + internal static bool singleUpload { get; set; } + + internal static void Reset() + { + firstSlice = default; + secondSlice = default; + singleUpload = false; + } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class TexturePrewarmPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.texture-prewarm"; + + public override void Build(RenderPipelineContext context) + { + context.resourceService.PrewarmTexture( + texture ?? throw new InvalidOperationException("A test texture is required.") + ); + context.graph + .AddRasterPass( + "Submit While Prewarming", + new RenderPhaseID("tests.runtime.prewarm"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + + internal static TextureAsset? texture { get; set; } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class PendingShaderPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.pending-shader"; + + public override void Build(RenderPipelineContext context) + { + resolved = context.resourceService.TryResolveGraphicsMaterial( + material ?? throw new InvalidOperationException("A test material is required."), + contract, + role, + null, + null, + out _ + ); + context.graph + .AddRasterPass( + "Submit While Compiling", + new RenderPhaseID("tests.runtime.pending-shader"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + + internal static MaterialAsset? material { get; set; } + internal static ShaderContractID contract { get; set; } + internal static ShaderPassRoleID role { get; set; } + internal static bool resolved { get; private set; } + + internal static void Reset() + { + material = null; + contract = default; + role = default; + resolved = false; + } + } + + [RenderPipelineExtension(C_EXTENSION_ID)] + private sealed class ReadbackPipeline : RenderPipeline + { + internal const string C_EXTENSION_ID = "tests.runtime.readback"; + + public override void Build(RenderPipelineContext context) + { + byte[] update = Enumerable.Range(0, 16).Select(static value => (byte)value).ToArray(); + context.resourceService.UpdateTexture(texture, new RenderTextureRegion(0, 1, 1, 0, 2, 2), update); + readback ??= context.resourceService + .ReadTextureAsync(texture, cancellationToken: cancellationToken) + .AsTask(); + context.graph + .AddRasterPass( + "Readback Submission", + new RenderPhaseID("tests.runtime.readback"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + + internal static PersistentTextureHandle texture { get; set; } + internal static CancellationToken cancellationToken { get; set; } + internal static Task? readback { get; private set; } + + internal static void Reset() + { + texture = default; + cancellationToken = default; + readback = null; + } + } + + [RenderRequestProviderExtension(C_EXTENSION_ID)] + private sealed class TestRequestProvider : RenderRequestProvider + { + internal const string C_EXTENSION_ID = "tests.runtime.request-provider"; + + public override void Submit(RenderRequestProviderContext context) + { + if (!enabled) + { + return; + } + submitCount++; + lastContent = context.content; + lastPresentationViewport = context.primaryPresentationViewport; + lastInput = context.input; + if (pipeline is null) + { + return; + } + context.requests.Submit(CreateRequest("Provider Request", pipeline)); + } + + internal static bool enabled { get; set; } + internal static RenderPipelineAsset? pipeline { get; set; } + internal static int submitCount { get; private set; } + internal static int pendingRetirements { get; set; } + internal static int retirementAttempts { get; private set; } + internal static ContentReadScope? lastContent { get; private set; } + internal static RenderViewport? lastPresentationViewport { get; private set; } + internal static RenderOutputInput lastInput { get; private set; } = RenderOutputInput.empty; + + protected override void Dispose(bool disposing) + { + retirementAttempts++; + if (pendingRetirements > 0) + { + pendingRetirements--; + throw new RetirementPendingException("Provider work remains active."); + } + } + + internal static void Reset() + { + enabled = false; + pipeline = null; + submitCount = 0; + pendingRetirements = 0; + retirementAttempts = 0; + lastContent = null; + lastPresentationViewport = default; + lastInput = RenderOutputInput.empty; + } + } + + private sealed class SideEffectContributor : IRenderFrameGraphContributor + { + public void PrepareFrame(ulong frameIndex) => _ = frameIndex; + + public void AddRenderPasses( + RenderGraphBuilder graph, + ulong frameIndex + ) { + _ = frameIndex; + graph + .AddRasterPass( + "Overlay", + new RenderPhaseID("tests.runtime.overlay"), + 0, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); + } + } + + private sealed class TestDiagnosticSink : IDiagnosticReporter + { + public void Publish(Diagnostic diagnostic) => items.Add(diagnostic); + + public void Resolve( + string code, + string? semanticID = null, + Guid? objectID = null + ) => items.RemoveAll(diagnostic => ( + string.Equals(diagnostic.code, code, StringComparison.Ordinal) + && string.Equals(diagnostic.semanticID, semanticID, StringComparison.Ordinal) && diagnostic.objectID == objectID + )); + + public void Replace(IEnumerable diagnostics) + { + items.Clear(); + items.AddRange(diagnostics); + } + + internal List items { get; } = []; + } + + private sealed class TestDeviceProxy : RenderDevice, IRenderDevice + { + private static readonly GraphicsCapabilities CAPABILITIES = new( + GraphicsApi.noop, + GraphicsCapability.None, + new GraphicsLimits(64, 4, 4096, 8), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); + + private int m_bufferCreationCount; + + public RenderDeviceFrameCounters frameCounters { get; internal set; } + public RenderDeviceAllocationCounters? allocationCounters { get; internal set; } + + public GraphicsCapabilities capabilities { get; internal set; } = CAPABILITIES; + public uint generation => 1; + public RenderPresentationSize? presentationSize { get; set; } = new(1, 1); + + public RenderPresentationSize? primaryPresentationSize + { + get => presentationSize; + private set => presentationSize = value; + } + + public bool primaryPresentationEncodesSrgb { get; set; } = true; + + public void SetVerticalSync(bool enabled) => verticalSync = enabled; + + public void BeginFrame() + { + Assert.False(frameOpen); + frameOpen = true; + } + + public void Execute( + CompiledRenderGraph graph, + ulong frameIndex + ) { + Assert.True(frameOpen); + _ = frameIndex; + executeCount++; + lastGraph = graph; + } + + public uint EndFrame() + { + Assert.True(frameOpen); + frameOpen = false; + endFrameCount++; + return checked((uint)endFrameCount); + } + + public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; + + public PersistentTextureHandle CreateTexture( + RenderTextureDescriptor descriptor, + string name + ) { + Assert.True(frameOpen); + _ = descriptor; + _ = name; + PersistentTextureHandle texture = CreatePersistentTextureHandle( + checked((ulong)createdTextures.Count + 1), + generation + ); + createdTextures.Add(texture); + return texture; + } + + public void UpdateTexture( + PersistentTextureHandle texture, + ReadOnlySpan data, + int mipLevel = 0, + int arrayLayer = 0 + ) { + _ = texture; + _ = data; + _ = mipLevel; + _ = arrayLayer; + } + + public void UpdateTextureRegion( + PersistentTextureHandle texture, + RenderTextureRegion region, + ReadOnlySpan data + ) { + _ = texture; + _ = region; + _ = data; + } + + public RenderTextureReadbackHandle BeginTextureReadback( + PersistentTextureHandle texture, + int mipLevel = 0 + ) { + _ = texture; + _ = mipLevel; + return default; + } + + public bool TryGetTextureReadback( + RenderTextureReadbackHandle readback, + out RenderTextureReadbackResult? result + ) { + _ = readback; + result = null; + return false; + } + + public void CancelTextureReadback(RenderTextureReadbackHandle readback) => _ = readback; + + public void DestroyTexture(PersistentTextureHandle texture) + { + Assert.True(frameOpen); + textureRetirementAttempts++; + if (failFirstTextureRetirement) + { + failFirstTextureRetirement = false; + throw new InvalidOperationException("Texture retirement failed."); + } + if (texture == pendingTextureRetirement) + { + pendingTextureRetirement = default; + throw new RetirementPendingException("Texture still has pending work."); + } + destroyedTextures.Add(texture); + } + + public PersistentBufferHandle CreateBuffer( + PersistentBufferDescriptor descriptor, + ReadOnlySpan initialData, + string name + ) { + m_bufferCreationCount++; + if (m_bufferCreationCount == failBufferCreationAt) + { + throw new InvalidOperationException("Native allocation rejected."); + } + PersistentBufferHandle handle = CreatePersistentBufferHandle((ulong)m_bufferCreationCount, generation); + createdBuffers.Add(handle); + return handle; + } + + public void UpdateBuffer( + PersistentBufferHandle buffer, + ReadOnlySpan data, + int startElement = 0 + ) { + _ = buffer; + _ = data; + _ = startElement; + } + + public void DestroyBuffer(PersistentBufferHandle buffer) + { + Assert.DoesNotContain(buffer, destroyedBuffers); + destroyedBuffers.Add(buffer); + } + + public GraphicsPipelineHandle CreateGraphicsPipeline( + GraphicsPipelineDescriptor descriptor, + string name + ) { + _ = descriptor; + _ = name; + return default; + } + + public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) => _ = pipeline; + + public ComputePipelineHandle CreateComputePipeline( + ComputePipelineDescriptor descriptor, + string name + ) { + _ = descriptor; + _ = name; + return default; + } + + public void DestroyComputePipeline(ComputePipelineHandle pipeline) => _ = pipeline; + + public void Dispose() {} + + internal bool verticalSync { get; private set; } + + internal List createdBuffers { get; } = []; + internal List destroyedBuffers { get; } = []; + internal int failBufferCreationAt { get; set; } + + internal List createdTextures { get; } = []; + internal List destroyedTextures { get; } = []; + internal bool frameOpen { get; private set; } + internal int endFrameCount { get; private set; } + internal int executeCount { get; private set; } + internal int textureRetirementAttempts { get; private set; } + internal bool failFirstTextureRetirement { get; set; } + internal PersistentTextureHandle pendingTextureRetirement { get; set; } + internal CompiledRenderGraph? lastGraph { get; private set; } + + internal void ReleaseRecordedGraph() => lastGraph = null; + + internal static IRenderDevice Create(out TestDeviceProxy proxy) + { + proxy = new TestDeviceProxy(); + return proxy; + } + } + + private sealed class RecordingRenderDevice : RenderDevice, IRenderDevice + { + private readonly RenderTextureDescriptor m_readbackDescriptor = new( + 4, + 4, + RenderTextureFormat.RGBA8, + RenderTextureUsage.Readback + ); + + private readonly RenderTextureReadbackHandle m_readbackHandle; + + internal RecordingRenderDevice(bool supportsReadback = false) + { + this.capabilities = new GraphicsCapabilities( + GraphicsApi.noop, + supportsReadback ? GraphicsCapability.TextureReadback : GraphicsCapability.None, + new GraphicsLimits(64, 4, 4096, 8), + Enum.GetValues(), + Enum.GetValues(), + [], + [], + originBottomLeft: false, + homogeneousDepth: false + ); + this.textureHandle = CreatePersistentTextureHandle(1UL, generation); + m_readbackHandle = CreateRenderTextureReadbackHandle(1UL, generation); + } + + public GraphicsCapabilities capabilities { get; } + + public uint generation => 1; + public RenderPresentationSize? primaryPresentationSize { get; private set; } = new(1, 1); + public bool primaryPresentationEncodesSrgb => true; + + public void SetVerticalSync(bool enabled) => verticalSync = enabled; + + public void BeginFrame() {} + + public void Execute( + CompiledRenderGraph graph, + ulong frameIndex + ) { + _ = graph; + _ = frameIndex; + executeCount++; + } + + public uint EndFrame() + { + endFrameCount++; + return checked((uint)endFrameCount); + } + + public void SetPrimaryPresentationSize(RenderPresentationSize? size) => primaryPresentationSize = size; + + public PersistentTextureHandle CreateTexture( + RenderTextureDescriptor descriptor, + string name + ) { + _ = descriptor; + _ = name; + return default; + } + + public void UpdateTexture( + PersistentTextureHandle texture, + ReadOnlySpan data, + int mipLevel = 0, + int arrayLayer = 0 + ) { + _ = texture; + _ = data; + _ = mipLevel; + _ = arrayLayer; + } + + public void UpdateTextureRegion( + PersistentTextureHandle texture, + RenderTextureRegion region, + ReadOnlySpan data + ) { + Assert.Equal(textureHandle, texture); + updatedRegion = region; + updatedBytes = data.ToArray(); + } + + public RenderTextureReadbackHandle BeginTextureReadback( + PersistentTextureHandle texture, + int mipLevel = 0 + ) { + Assert.Equal(textureHandle, texture); + _ = mipLevel; + return m_readbackHandle; + } + + public bool TryGetTextureReadback( + RenderTextureReadbackHandle readback, + out RenderTextureReadbackResult? result + ) { + Assert.Equal(m_readbackHandle, readback); + result = readbackReady + ? new RenderTextureReadbackResult( + m_readbackDescriptor, + 0, + 16, + Enumerable.Repeat((byte)37, 64).ToArray() + ) + : null; + return result is not null; + } + + public void CancelTextureReadback(RenderTextureReadbackHandle readback) + { + Assert.Equal(m_readbackHandle, readback); + cancelReadbackCount++; + if (pendingReadbackRetirements > 0) + { + pendingReadbackRetirements--; + Assert.False(ReadbackPipeline.readback!.IsCompleted); + Assert.Equal(1, endFrameCount); + throw new RetirementPendingException("Readback cancellation remains active."); + } + } + + public void DestroyTexture(PersistentTextureHandle texture) => _ = texture; + + public PersistentBufferHandle CreateBuffer( + PersistentBufferDescriptor descriptor, + ReadOnlySpan initialData, + string name + ) { + _ = descriptor; + _ = initialData; + _ = name; + createBufferCount++; + return default; + } + + public void UpdateBuffer( + PersistentBufferHandle buffer, + ReadOnlySpan data, + int startElement = 0 + ) { + _ = buffer; + _ = data; + bufferUpdateOffsets.Add(startElement); + } + + public void DestroyBuffer(PersistentBufferHandle buffer) + { + bufferRetirementAttempts++; + if (pendingBufferRetirements > 0) + { + pendingBufferRetirements--; + Assert.Equal(0, cancelReadbackCount); + Assert.False(ReadbackPipeline.readback!.IsCompleted); + Assert.Equal(1, endFrameCount); + throw new RetirementPendingException("Upload work remains active."); + } + } + + public GraphicsPipelineHandle CreateGraphicsPipeline( + GraphicsPipelineDescriptor descriptor, + string name + ) { + if (name == failProgramName) throw new InvalidOperationException("Injected program allocation failure."); + GraphicsPipelineHandle handle = CreateGraphicsPipelineHandle(checked((ulong)createdPrograms.Count + 1), generation); + createdPrograms.Add(handle); + programDescriptors.Add(descriptor); + return handle; + } + + public void DestroyGraphicsPipeline(GraphicsPipelineHandle pipeline) + { + programRetirementAttempts++; + if (pendingProgramRetirements > 0) + { + pendingProgramRetirements--; + throw new RetirementPendingException("Injected unfinished program retirement."); + } + Assert.DoesNotContain(pipeline, destroyedPrograms); + destroyedPrograms.Add(pipeline); + if (failedProgramRetirements > 0) + { + failedProgramRetirements--; + throw new InvalidOperationException("Injected completed program retirement failure."); + } + } + + public ComputePipelineHandle CreateComputePipeline( + ComputePipelineDescriptor descriptor, + string name + ) { + _ = descriptor; + _ = name; + return default; + } + + public void DestroyComputePipeline(ComputePipelineHandle pipeline) => _ = pipeline; + + public void Dispose() {} + + internal List createdPrograms { get; } = []; + internal List destroyedPrograms { get; } = []; + internal List programDescriptors { get; } = []; + internal string? failProgramName { get; set; } + internal int pendingProgramRetirements { get; set; } + internal int failedProgramRetirements { get; set; } + internal int programRetirementAttempts { get; private set; } + internal bool verticalSync { get; private set; } + + internal List bufferUpdateOffsets { get; } = []; + internal PersistentTextureHandle textureHandle { get; } + internal RenderTextureRegion? updatedRegion { get; private set; } + internal byte[] updatedBytes { get; private set; } = []; + internal bool readbackReady { get; set; } + internal int cancelReadbackCount { get; private set; } + internal int pendingReadbackRetirements { get; set; } + internal int pendingBufferRetirements { get; set; } + internal int bufferRetirementAttempts { get; private set; } + internal int createBufferCount { get; private set; } + internal int endFrameCount { get; private set; } + internal int executeCount { get; private set; } + } + + private sealed class DelayedTextureArtifactSource + { + private readonly TaskCompletionSource m_completion = new( + TaskCreationOptions.RunContinuationsAsynchronously + ); + + internal ManualResetEventSlim started { get; } = new(initialState: false); + internal bool isCompleted => m_completion.Task.IsCompleted; + + internal Task LoadAsync(CancellationToken cancellationToken = default) + { + started.Set(); + return m_completion.Task.WaitAsync(cancellationToken); + } + + internal void Complete(byte[] data) => m_completion.TrySetResult(data); + } + + private sealed class DelayedArtifactProvider(DelayedTextureArtifactSource compiler) : IRenderTargetArtifactProvider + { + private Task? m_texture; + + public ShaderDefinition ReadShaderDefinition(RenderShaderArtifact artifact) + => throw new InvalidOperationException("This pending provider never publishes a shader artifact."); + + public RenderTargetArtifactStatus GetShaderArtifact( + ShaderAsset shader, + RenderShaderVariant variant, + GraphicsCapabilities capabilities, + out RenderShaderArtifact? artifact + ) { + _ = shader; + _ = variant; + _ = capabilities; + artifact = null; + return RenderTargetArtifactStatus.Pending; + } + + public RenderTargetArtifactStatus GetTextureArtifact( + RenderTextureArtifactReference texture, + out ReadOnlyMemory artifact + ) { + _ = texture; + m_texture ??= compiler.LoadAsync(); + if (m_texture.IsCompletedSuccessfully) + { + artifact = m_texture.Result; + return RenderTargetArtifactStatus.Ready; + } + artifact = ReadOnlyMemory.Empty; + return RenderTargetArtifactStatus.Pending; + } + } + + private sealed class TestCompositionProgramProvider : IRenderLayerCompositionProgramProvider + { + public GraphicsPipelineDescriptor CreateDescriptor( + GraphicsCapabilities capabilities, + RenderVertexLayout vertexLayout + ) { + _ = capabilities; + return new GraphicsPipelineDescriptor( + [1], + [1], + [new RenderShaderBindingDescriptor( + new RenderBindingID("s_tex"), + RenderShaderBindingKind.Texture, + 0, + nativeName: "s_tex" + )], + vertexLayout + ); + } + + public GraphicsPipelineDescriptor CreateOutputTransferDescriptor( + GraphicsCapabilities capabilities, + RenderVertexLayout vertexLayout + ) => CreateDescriptor(capabilities, vertexLayout); + } +} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/MetalShaderFactAttribute.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/MetalShaderFactAttribute.cs new file mode 100644 index 000000000..9487f1a3a --- /dev/null +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/MetalShaderFactAttribute.cs @@ -0,0 +1,15 @@ +using System; +using Xunit; + +namespace Inno.Rendering.Shaders.Tests; + +public sealed class MetalShaderFactAttribute : FactAttribute +{ + public MetalShaderFactAttribute() + { + if (!OperatingSystem.IsMacOS()) + { + this.Skip = "Requires the macOS BGFX Metal compiler; Windows validation is explicitly deferred."; + } + } +} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/NodeRegistryProbe.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/NodeRegistryProbe.cs new file mode 100644 index 000000000..c9c36b92b --- /dev/null +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/NodeRegistryProbe.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; + +namespace Inno.Rendering.Shaders.Tests; + +internal sealed class NodeRegistryProbe : IShaderNodeCompiler, IDisposable +{ + internal static int created; + internal static int disposed; + internal static bool conflict; + private readonly string m_id; + + public NodeRegistryProbe() + { + created++; + m_id = conflict ? "inno.shader.constant" : "tests.registry.node"; + } + + public string definitionID => m_id; + + public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => []; + + public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) => new Dictionary(); + + public void Dispose() => disposed++; +} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryFrontendProbe.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryFrontendProbe.cs new file mode 100644 index 000000000..04c66036e --- /dev/null +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/RegistryFrontendProbe.cs @@ -0,0 +1,33 @@ +using System; + +namespace Inno.Rendering.Shaders.Tests; + +internal sealed class RegistryFrontendProbe : IShaderSourceFrontend, IDisposable +{ + internal static int created; + internal static int disposed; + internal static bool conflict; + private readonly string m_languageID; + + public RegistryFrontendProbe() + { + created++; + m_languageID = conflict ? "inno.shader-language.bgfx-sc" : "tests.registry.language"; + } + + public string languageID => m_languageID; + + public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) + => new( + new ShaderSourceFunction( + request.entryPoint, + ShaderSourceType.Atomic("float"), + [], + new ShaderSourcePosition(request.source.assetPath, 1, 1) + ), + [], + [] + ); + + public void Dispose() => disposed++; +} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs index 749f993b0..2f75bf6a1 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphLoweringTests.Validation.cs @@ -120,25 +120,3 @@ public void RegistryDiscoversExtensionsAndRollsBackDuplicateCandidatesWithoutLea Assert.Equal(NodeRegistryProbe.created, NodeRegistryProbe.disposed); } } - -internal sealed class NodeRegistryProbe : IShaderNodeCompiler, IDisposable -{ - internal static int created; - internal static int disposed; - internal static bool conflict; - private readonly string m_id; - - public NodeRegistryProbe() - { - created++; - m_id = conflict ? "inno.shader.constant" : "tests.registry.node"; - } - - public string definitionID => m_id; - - public IReadOnlyList GetPorts(ShaderNodeDescriptionContext context) => []; - - public IReadOnlyDictionary Lower(ShaderNodeLoweringContext context) => new Dictionary(); - - public void Dispose() => disposed++; -} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphSharedProgramTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.SharedProgram.cs similarity index 99% rename from tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphSharedProgramTests.cs rename to tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.SharedProgram.cs index ee11721a6..579d1893d 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphSharedProgramTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.SharedProgram.cs @@ -3,7 +3,6 @@ using Xunit; using Inno.Core.Graphs; using Inno.Core.Serialization; -using Inno.Rendering; using Inno.Rendering.Assets; namespace Inno.Rendering.Shaders.Tests; diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.Storage.cs similarity index 99% rename from tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs rename to tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.Storage.cs index ff85d1177..887ffd352 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphStorageTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderGraphProgramTests.Storage.cs @@ -8,7 +8,6 @@ using Inno.Core.Graphs; using Inno.Core.Serialization; using Inno.Integration.MacOSArm64.Bgfx; -using Inno.Rendering; using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs index 90eeb63b1..efd1d4567 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderSourceFrontendRegistryTests.cs @@ -84,33 +84,3 @@ public void Dispose() internal TypeCatalog types { get; } } } - -internal sealed class RegistryFrontendProbe : IShaderSourceFrontend, IDisposable -{ - internal static int created; - internal static int disposed; - internal static bool conflict; - private readonly string m_languageID; - - public RegistryFrontendProbe() - { - created++; - m_languageID = conflict ? "inno.shader-language.bgfx-sc" : "tests.registry.language"; - } - - public string languageID => m_languageID; - - public ShaderSourceAnalysis Analyze(ShaderSourceRequest request) - => new( - new ShaderSourceFunction( - request.entryPoint, - ShaderSourceType.Atomic("float"), - [], - new ShaderSourcePosition(request.source.assetPath, 1, 1) - ), - [], - [] - ); - - public void Dispose() => disposed++; -} diff --git a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs index 3abb7bd69..582bb1dff 100644 --- a/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs +++ b/tests/rendering/Inno.Rendering.Shaders.Tests/ShaderTypedNativeCompilationTests.cs @@ -9,23 +9,10 @@ using Inno.Build.Toolchains.Bgfx.Tools; using Inno.Core.Diagnostics; using Inno.Integration.MacOSArm64.Bgfx; -using Inno.Rendering; -using Inno.Rendering.Assets; using Inno.Rendering.Assets.Authoring; namespace Inno.Rendering.Shaders.Tests; -public sealed class MetalShaderFactAttribute : FactAttribute -{ - public MetalShaderFactAttribute() - { - if (!OperatingSystem.IsMacOS()) - { - this.Skip = "Requires the macOS BGFX Metal compiler; Windows validation is explicitly deferred."; - } - } -} - [SupportedOSPlatform("macos")] public sealed class ShaderTypedNativeCompilationTests { diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableFramePayload.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableFramePayload.cs new file mode 100644 index 000000000..361ba93f0 --- /dev/null +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableFramePayload.cs @@ -0,0 +1,6 @@ +namespace Inno.Rendering.Runtime.Reload.TestModule; + +/// +/// Provides a collectible value used to verify that frame-data queues release retired plugins. +/// +public sealed class ReloadableFramePayload; diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderFeature.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderFeature.cs new file mode 100644 index 000000000..bb76565c9 --- /dev/null +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderFeature.cs @@ -0,0 +1,26 @@ +namespace Inno.Rendering.Runtime.Reload.TestModule; + +[RenderFeatureExtension(C_EXTENSION_ID)] +internal sealed class ReloadableRenderFeature : RenderPipelineFeature +{ + internal const string C_EXTENSION_ID = "tests.runtime.reloadable-plugin-feature"; + + /// + /// Adds observable feature work to the active pipeline graph. + /// + /// + /// The active feature context that owns the frame graph mutation. + /// + public override void AddRenderPasses(RenderFeatureContext context) + => context.graph + .AddRasterPass( + "Reloadable Plugin Feature Pass", + new RenderPhaseID("tests.runtime.reloadable-plugin-feature.visible"), + 1, + static ( + _, + _ + ) => {} + ) + .HasSideEffect(); +} diff --git a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs index 407ac4e26..4fbd5a199 100644 --- a/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs +++ b/tests/rendering/fixtures/Inno.Rendering.Runtime.Reload.TestModule/ReloadableRenderPipeline.cs @@ -1,13 +1,5 @@ -using Inno.Rendering; -using Inno.Rendering.Runtime; - namespace Inno.Rendering.Runtime.Reload.TestModule; -/// -/// Provides a collectible value used to verify that frame-data queues release retired plugins. -/// -public sealed class ReloadableFramePayload; - /// /// Supplies a collectible Plugin-owned pipeline for rendering generation removal tests. /// @@ -38,28 +30,3 @@ public override void Build(RenderPipelineContext context) ) .HasSideEffect(); } - -[RenderFeatureExtension(C_EXTENSION_ID)] -internal sealed class ReloadableRenderFeature : RenderPipelineFeature -{ - internal const string C_EXTENSION_ID = "tests.runtime.reloadable-plugin-feature"; - - /// - /// Adds observable feature work to the active pipeline graph. - /// - /// - /// The active feature context that owns the frame graph mutation. - /// - public override void AddRenderPasses(RenderFeatureContext context) - => context.graph - .AddRasterPass( - "Reloadable Plugin Feature Pass", - new RenderPhaseID("tests.runtime.reloadable-plugin-feature.visible"), - 1, - static ( - _, - _ - ) => {} - ) - .HasSideEffect(); -} diff --git a/tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs b/tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs deleted file mode 100644 index 7ab855b4e..000000000 --- a/tests/scene/Inno.Scene.Tests/EngineAssetComponents.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Collections.Generic; -using Inno.Assets; -using Inno.Core.Serialization; -using Inno.Extensibility.Types; -using Inno.Scene; - -namespace Inno.Scene.Tests; - -[StableTypeID("cc867fe9-866c-4a19-ac69-5e561b20a874")] -internal sealed class EngineAssetReferenceComponent : GameComponent -{ - [SerializableProperty] - public TextAsset? asset { get; set; } -} - -[StableTypeID("b4ada657-2b58-4929-b1c0-616b54bb0939")] -internal sealed class EngineObjectReferenceComponent : GameComponent -{ - [SerializableProperty] - public GameObject? targetObject { get; set; } - - [SerializableProperty] - public int value { get; set; } -} - -internal sealed class PrefabInstantiationBehavior : GameBehavior -{ - public PrefabAsset? prefab { get; set; } - - public List instances { get; } = []; - - protected override void Update() - { - if (prefab is not null && instances.Count < 2) - { - instances.Add(gameObject.scene.InstantiatePrefab(prefab, gameObject.transform)); - } - } -} diff --git a/tests/scene/Inno.Scene.Tests/EngineAssetReferenceComponent.cs b/tests/scene/Inno.Scene.Tests/EngineAssetReferenceComponent.cs new file mode 100644 index 000000000..3f701db2b --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/EngineAssetReferenceComponent.cs @@ -0,0 +1,12 @@ +using Inno.Assets; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("cc867fe9-866c-4a19-ac69-5e561b20a874")] +internal sealed class EngineAssetReferenceComponent : GameComponent +{ + [SerializableProperty] + public TextAsset? asset { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/EngineObjectReferenceComponent.cs b/tests/scene/Inno.Scene.Tests/EngineObjectReferenceComponent.cs new file mode 100644 index 000000000..79a6a8495 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/EngineObjectReferenceComponent.cs @@ -0,0 +1,14 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("b4ada657-2b58-4929-b1c0-616b54bb0939")] +internal sealed class EngineObjectReferenceComponent : GameComponent +{ + [SerializableProperty] + public GameObject? targetObject { get; set; } + + [SerializableProperty] + public int value { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/GameSystemTests.cs b/tests/scene/Inno.Scene.Tests/GameSystemTests.cs index ec0a38c04..57144d553 100644 --- a/tests/scene/Inno.Scene.Tests/GameSystemTests.cs +++ b/tests/scene/Inno.Scene.Tests/GameSystemTests.cs @@ -1,10 +1,7 @@ using System; using System.Collections.Generic; -using System.Linq; using Xunit; using Inno.Core.Serialization; -using Inno.Extensibility.Types; -using Inno.Scene; namespace Inno.Scene.Tests; @@ -174,24 +171,3 @@ ICollection execution protected override void OnUpdate() => execution.Add(label); } } - -[StableTypeID("b469170b-a1f2-4176-b3ad-252d1cb53b90")] -internal sealed class StateSystem : GameSystem -{ - [SerializableProperty] - public int value { get; set; } - - [SerializableProperty] - public SystemReferenceComponent? component { get; set; } - - public int resetCount { get; private set; } - - protected override void Reset() => resetCount++; -} - -[StableTypeID("75344398-ed18-46ae-808b-e0cb45d93850")] -internal sealed class SystemReferenceComponent : GameComponent -{ - [SerializableProperty] - public StateSystem? system { get; set; } -} diff --git a/tests/scene/Inno.Scene.Tests/LayerValueComponent.cs b/tests/scene/Inno.Scene.Tests/LayerValueComponent.cs new file mode 100644 index 000000000..2f6546761 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/LayerValueComponent.cs @@ -0,0 +1,15 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; +using Inno.Scene.Layers; + +namespace Inno.Scene.Tests; + +[StableTypeID("821c7b92-9aeb-40cb-924e-169004199ef0")] +internal sealed class LayerValueComponent : GameComponent +{ + [SerializableProperty] + public GameLayer layer { get; set; } + + [SerializableProperty] + public GameLayerMask mask { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/OrderComponentA.cs b/tests/scene/Inno.Scene.Tests/OrderComponentA.cs new file mode 100644 index 000000000..8103b4f68 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/OrderComponentA.cs @@ -0,0 +1,3 @@ +namespace Inno.Scene.Tests; + +internal sealed class OrderComponentA : GameComponent; diff --git a/tests/scene/Inno.Scene.Tests/OrderComponentB.cs b/tests/scene/Inno.Scene.Tests/OrderComponentB.cs new file mode 100644 index 000000000..ed90e7f9e --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/OrderComponentB.cs @@ -0,0 +1,3 @@ +namespace Inno.Scene.Tests; + +internal sealed class OrderComponentB : GameComponent; diff --git a/tests/scene/Inno.Scene.Tests/OrderSerializationSystemA.cs b/tests/scene/Inno.Scene.Tests/OrderSerializationSystemA.cs new file mode 100644 index 000000000..a657710ec --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/OrderSerializationSystemA.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("f7bc9bf3-288a-45b3-9caa-26289d66c181")] +internal sealed class OrderSerializationSystemA : GameSystem; diff --git a/tests/scene/Inno.Scene.Tests/OrderSerializationSystemB.cs b/tests/scene/Inno.Scene.Tests/OrderSerializationSystemB.cs new file mode 100644 index 000000000..3aa4e6d83 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/OrderSerializationSystemB.cs @@ -0,0 +1,6 @@ +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("6924359d-798d-4384-bdb2-1b0e34ab3fbb")] +internal sealed class OrderSerializationSystemB : GameSystem; diff --git a/tests/scene/Inno.Scene.Tests/PrefabInstantiationBehavior.cs b/tests/scene/Inno.Scene.Tests/PrefabInstantiationBehavior.cs new file mode 100644 index 000000000..a3b378375 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/PrefabInstantiationBehavior.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace Inno.Scene.Tests; + +internal sealed class PrefabInstantiationBehavior : GameBehavior +{ + public PrefabAsset? prefab { get; set; } + + public List instances { get; } = []; + + protected override void Update() + { + if (prefab is not null && instances.Count < 2) + { + instances.Add(gameObject.scene.InstantiatePrefab(prefab, gameObject.transform)); + } + } +} diff --git a/tests/scene/Inno.Scene.Tests/PropertyElementEnvelope.cs b/tests/scene/Inno.Scene.Tests/PropertyElementEnvelope.cs new file mode 100644 index 000000000..880951010 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/PropertyElementEnvelope.cs @@ -0,0 +1,34 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Scene.Tests; + +/// +/// Creates valid and deliberately invalid current element envelopes through the public serializer. +/// +internal sealed class PropertyElementEnvelope : ISerializable +{ + [SerializableProperty] + public Guid typeId { get; set; } + + [SerializableProperty] + public string typeName { get; set; } = string.Empty; + + [SerializableProperty] + public byte[] properties { get; set; } = []; + + [SerializableProperty] + public Guid[] dependencyIds { get; set; } = []; + + [SerializableProperty] + public Guid[] dependencyTypes { get; set; } = []; + + [SerializableProperty] + public string[] dependencyPaths { get; set; } = []; + + [SerializableProperty] + public Guid[] aliasIds { get; set; } = []; + + [SerializableProperty] + public Guid[] aliasTargets { get; set; } = []; +} diff --git a/tests/scene/Inno.Scene.Tests/PropertyReferenceProbe.cs b/tests/scene/Inno.Scene.Tests/PropertyReferenceProbe.cs new file mode 100644 index 000000000..d89d5f4bc --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/PropertyReferenceProbe.cs @@ -0,0 +1,31 @@ +using System; +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("486290eb-6cc4-4a96-918a-c8022f51ad85")] +internal sealed class PropertyReferenceProbe : GameComponent +{ + [SerializableProperty(order = -1)] + public int trigger + { + get + { + beforeRead?.Invoke(); + return 0; + } + set {} + } + + [SerializableProperty] + public GameObject? targetObject { get; set; } + + [SerializableProperty] + public GameComponent? targetComponent { get; set; } + + [SerializableProperty] + public GameSystem? targetSystem { get; set; } + + internal Action? beforeRead { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/PropertyReferenceTokenFixture.cs b/tests/scene/Inno.Scene.Tests/PropertyReferenceTokenFixture.cs new file mode 100644 index 000000000..0fe05cbf1 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/PropertyReferenceTokenFixture.cs @@ -0,0 +1,13 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Scene.Tests; + +internal sealed class PropertyReferenceTokenFixture : ISerializable +{ + [SerializableProperty] + public int kind { get; set; } + + [SerializableProperty] + public Guid sourceId { get; set; } +} diff --git a/tests/scene/Inno.Scene.Tests/ReferenceComponent.cs b/tests/scene/Inno.Scene.Tests/ReferenceComponent.cs new file mode 100644 index 000000000..52c49fdbb --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/ReferenceComponent.cs @@ -0,0 +1,21 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("09d35197-7161-4fdf-8d60-95ecf3555c0c")] +internal sealed class ReferenceComponent : GameComponent +{ + [SerializableProperty] + public int value { get; set; } + + [SerializableProperty] + public GameObject? targetObject { get; set; } + + [SerializableProperty] + public ReferenceComponent? targetComponent { get; set; } + + public int resetCount { get; private set; } + + protected override void Reset() => resetCount++; +} diff --git a/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs b/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs index 5fad50261..6c212ae5a 100644 --- a/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs +++ b/tests/scene/Inno.Scene.Tests/SceneFacadeTests.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Linq; using Xunit; -using Inno.Runtime; -using Inno.Scene; using Inno.Scene.Components; namespace Inno.Scene.Tests; @@ -425,7 +423,3 @@ protected override void Reset() } } } - -internal sealed class OrderComponentA : GameComponent; - -internal sealed class OrderComponentB : GameComponent; diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs index 9bbc824c3..26a41c5cd 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyAliases.cs @@ -134,42 +134,3 @@ public void PropertyRestoreRejectsAnInvalidReferenceKindBeforeAssigningTheTarget Assert.Null(probe.targetComponent); } } - -internal sealed class PropertyReferenceTokenFixture : ISerializable -{ - [SerializableProperty] - public int kind { get; set; } - - [SerializableProperty] - public Guid sourceId { get; set; } -} - -/// -/// Creates valid and deliberately invalid current element envelopes through the public serializer. -/// -internal sealed class PropertyElementEnvelope : ISerializable -{ - [SerializableProperty] - public Guid typeId { get; set; } - - [SerializableProperty] - public string typeName { get; set; } = string.Empty; - - [SerializableProperty] - public byte[] properties { get; set; } = []; - - [SerializableProperty] - public Guid[] dependencyIds { get; set; } = []; - - [SerializableProperty] - public Guid[] dependencyTypes { get; set; } = []; - - [SerializableProperty] - public string[] dependencyPaths { get; set; } = []; - - [SerializableProperty] - public Guid[] aliasIds { get; set; } = []; - - [SerializableProperty] - public Guid[] aliasTargets { get; set; } = []; -} diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs index 91127e2e3..3826b5e40 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.PropertyReferences.cs @@ -3,8 +3,6 @@ using Xunit; using Inno.Assets; using Inno.Core.Identity; -using Inno.Core.Serialization; -using Inno.Extensibility.Types; namespace Inno.Scene.Tests; @@ -157,29 +155,3 @@ public void NestedPropertyReadsAndGetterFailuresRestoreTheOuterReferenceScope() Assert.NotEmpty(m_serialization.Serialize(nestedScene.CreateObject("Independent prefab"), m_serializationContext)); } } - -[StableTypeID("486290eb-6cc4-4a96-918a-c8022f51ad85")] -internal sealed class PropertyReferenceProbe : GameComponent -{ - [SerializableProperty(order = -1)] - public int trigger - { - get - { - beforeRead?.Invoke(); - return 0; - } - set {} - } - - [SerializableProperty] - public GameObject? targetObject { get; set; } - - [SerializableProperty] - public GameComponent? targetComponent { get; set; } - - [SerializableProperty] - public GameSystem? targetSystem { get; set; } - - internal Action? beforeRead { get; set; } -} diff --git a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs index 0aa955267..9bf0b6087 100644 --- a/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs +++ b/tests/scene/Inno.Scene.Tests/SceneSerializationTests.cs @@ -6,7 +6,6 @@ using Inno.Core.Serialization; using Inno.Core.Serialization.Converters; using Inno.Extensibility.Types; -using Inno.Scene; using Inno.Scene.Components; using Inno.Scene.Layers; @@ -300,36 +299,3 @@ private static ( return (sceneReference, objectReference, componentReference); } } - -[StableTypeID("09d35197-7161-4fdf-8d60-95ecf3555c0c")] -internal sealed class ReferenceComponent : GameComponent -{ - [SerializableProperty] - public int value { get; set; } - - [SerializableProperty] - public GameObject? targetObject { get; set; } - - [SerializableProperty] - public ReferenceComponent? targetComponent { get; set; } - - public int resetCount { get; private set; } - - protected override void Reset() => resetCount++; -} - -[StableTypeID("f7bc9bf3-288a-45b3-9caa-26289d66c181")] -internal sealed class OrderSerializationSystemA : GameSystem; - -[StableTypeID("6924359d-798d-4384-bdb2-1b0e34ab3fbb")] -internal sealed class OrderSerializationSystemB : GameSystem; - -[StableTypeID("821c7b92-9aeb-40cb-924e-169004199ef0")] -internal sealed class LayerValueComponent : GameComponent -{ - [SerializableProperty] - public GameLayer layer { get; set; } - - [SerializableProperty] - public GameLayerMask mask { get; set; } -} diff --git a/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs b/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs index 14bca30f5..3b78f2508 100644 --- a/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs +++ b/tests/scene/Inno.Scene.Tests/SceneTestsCollection.cs @@ -1,15 +1,4 @@ -using System; -using System.IO; using Xunit; -using Inno.Adapter.Modules.DotNet; -using Inno.Adapter.Serialization.DotNet; -using Inno.Assets; -using Inno.Core.Diagnostics; -using Inno.Core.Identity; -using Inno.Core.Logging; -using Inno.Core.Serialization; -using Inno.Extensibility.Modules; -using Inno.Extensibility.Types; namespace Inno.Scene.Tests; @@ -18,60 +7,3 @@ public sealed class SceneTestsCollection : ICollectionFixture { public const string C_NAME = nameof(SceneTestsCollection); } - -public sealed class SceneTestsFixture : IDisposable -{ - private readonly string m_cacheDirectory = Path.Combine( - Path.GetTempPath(), - "InnoSceneTests", - Guid.NewGuid().ToString("N") - ); - - public SceneTestsFixture() - { - _ = typeof(SceneAsset); - this.modules = new ModuleHost(new ModuleHostOptions - { - catalogSource = new DotNetAssemblyCatalogSource(typeof(SceneTestsCollection).Assembly) - }); - this.types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); - this.serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); - this.world = new SceneWorld(identities, types); - this.assets = new RejectingAssetReferenceResolver(); - this.serializationContext = AssetSerializationContext.Create(assets); - } - - public ModuleHost modules { get; } - public TypeCatalog types { get; } - public SerializationRegistry serialization { get; } - public IAssetReferenceResolver assets { get; } - public IdentityAllocator identities { get; } = new(); - public DiagnosticHub diagnostics { get; } = new(); - public LogRouter logs { get; } = new(); - public SceneWorld world { get; } - public SerializationContext serializationContext { get; } - - public void Dispose() - { - world.Dispose(); - serialization.Dispose(); - types.Dispose(); - modules.Dispose(); - logs.Dispose(); - if (Directory.Exists(m_cacheDirectory)) - { - Directory.Delete(m_cacheDirectory, recursive: true); - } - } - - private sealed class RejectingAssetReferenceResolver : IAssetReferenceResolver - { - public AssetObject Resolve( - Guid persistentID, - Guid stableTypeID, - string lastKnownPath, - Type expectedType, - string propertyPath - ) => throw new InvalidOperationException($"Unexpected asset reference '{persistentID:D}' at '{propertyPath}'."); - } -} diff --git a/tests/scene/Inno.Scene.Tests/SceneTestsFixture.cs b/tests/scene/Inno.Scene.Tests/SceneTestsFixture.cs new file mode 100644 index 000000000..ddb84d5b9 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/SceneTestsFixture.cs @@ -0,0 +1,70 @@ +using System; +using System.IO; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Assets; +using Inno.Core.Diagnostics; +using Inno.Core.Identity; +using Inno.Core.Logging; +using Inno.Core.Serialization; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +public sealed class SceneTestsFixture : IDisposable +{ + private readonly string m_cacheDirectory = Path.Combine( + Path.GetTempPath(), + "InnoSceneTests", + Guid.NewGuid().ToString("N") + ); + + public SceneTestsFixture() + { + _ = typeof(SceneAsset); + this.modules = new ModuleHost(new ModuleHostOptions + { + catalogSource = new DotNetAssemblyCatalogSource(typeof(SceneTestsCollection).Assembly) + }); + this.types = new TypeCatalog(modules, new ReflectionTypeCatalogSource()); + this.serialization = new SerializationRegistry(types, new ReflectionSerializationMetadataSource()); + this.world = new SceneWorld(identities, types); + this.assets = new RejectingAssetReferenceResolver(); + this.serializationContext = AssetSerializationContext.Create(assets); + } + + public ModuleHost modules { get; } + public TypeCatalog types { get; } + public SerializationRegistry serialization { get; } + public IAssetReferenceResolver assets { get; } + public IdentityAllocator identities { get; } = new(); + public DiagnosticHub diagnostics { get; } = new(); + public LogRouter logs { get; } = new(); + public SceneWorld world { get; } + public SerializationContext serializationContext { get; } + + public void Dispose() + { + world.Dispose(); + serialization.Dispose(); + types.Dispose(); + modules.Dispose(); + logs.Dispose(); + if (Directory.Exists(m_cacheDirectory)) + { + Directory.Delete(m_cacheDirectory, recursive: true); + } + } + + private sealed class RejectingAssetReferenceResolver : IAssetReferenceResolver + { + public AssetObject Resolve( + Guid persistentID, + Guid stableTypeID, + string lastKnownPath, + Type expectedType, + string propertyPath + ) => throw new InvalidOperationException($"Unexpected asset reference '{persistentID:D}' at '{propertyPath}'."); + } +} diff --git a/tests/scene/Inno.Scene.Tests/StateSystem.cs b/tests/scene/Inno.Scene.Tests/StateSystem.cs new file mode 100644 index 000000000..bda23b938 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/StateSystem.cs @@ -0,0 +1,18 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("b469170b-a1f2-4176-b3ad-252d1cb53b90")] +internal sealed class StateSystem : GameSystem +{ + [SerializableProperty] + public int value { get; set; } + + [SerializableProperty] + public SystemReferenceComponent? component { get; set; } + + public int resetCount { get; private set; } + + protected override void Reset() => resetCount++; +} diff --git a/tests/scene/Inno.Scene.Tests/SystemReferenceComponent.cs b/tests/scene/Inno.Scene.Tests/SystemReferenceComponent.cs new file mode 100644 index 000000000..4ac6a0212 --- /dev/null +++ b/tests/scene/Inno.Scene.Tests/SystemReferenceComponent.cs @@ -0,0 +1,11 @@ +using Inno.Core.Serialization; +using Inno.Extensibility.Types; + +namespace Inno.Scene.Tests; + +[StableTypeID("75344398-ed18-46ae-808b-e0cb45d93850")] +internal sealed class SystemReferenceComponent : GameComponent +{ + [SerializableProperty] + public StateSystem? system { get; set; } +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/AttributeOwner.cs b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeOwner.cs new file mode 100644 index 000000000..480904553 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeOwner.cs @@ -0,0 +1,20 @@ +using System; +using Inno.Core.Serialization; +using Inno.Editor.Annotations; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class AttributeOwner : ISerializable +{ + [SerializableProperty] + [Header("Presentation", "Decorators are composed before the property row.")] + [Text("Persistent decorator text remains visible.")] + [Tooltip("Reusable hover guidance.")] + [InspectorName("Friendly Value")] + [Range(2, 8)] + [ShowIf(nameof(showValue))] + [ProbeInspector] + public AttributeValue value { get; set; } = new(); + + internal bool showValue { get; set; } +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValue.cs b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValue.cs new file mode 100644 index 000000000..7f5505c5b --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValue.cs @@ -0,0 +1,3 @@ +namespace Inno.Editor.Scripting.Tests; + +internal sealed class AttributeValue; diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValueDrawer.cs b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValueDrawer.cs new file mode 100644 index 000000000..c3f3c69b5 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/AttributeValueDrawer.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using Inno.Editor.Inspection; + +namespace Inno.Editor.Scripting.Tests; + +[PropertyDrawer(typeof(AttributeValue), priority: 10_000)] +internal sealed class AttributeValueDrawer : IPropertyDrawer +{ + public void Draw(PropertyDrawContext context) + => observations.Add($"{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); + + internal static List observations { get; } = []; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayload.cs b/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayload.cs new file mode 100644 index 000000000..ca7321253 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayload.cs @@ -0,0 +1,8 @@ +using Inno.Core.Serialization; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class CapturedScriptPayload(ISerializable payload) : ISerializable +{ + internal ISerializable payload { get; } = payload; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayloadConverter.cs b/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayloadConverter.cs new file mode 100644 index 000000000..a263b2c35 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/CapturedScriptPayloadConverter.cs @@ -0,0 +1,16 @@ +using System; +using Inno.Core.Serialization; +using Inno.Core.Serialization.Converters; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class CapturedScriptPayloadConverter : SerializationConverter +{ + public override void Write( + SerializationWriter writer, + CapturedScriptPayload value + ) => writer.WritePropertiesData("state", value.payload); + + public override CapturedScriptPayload Read(SerializationReader reader) + => throw new NotSupportedException("This fixture only captures an existing generation."); +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailure.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailure.cs new file mode 100644 index 000000000..649b208fe --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailure.cs @@ -0,0 +1,3 @@ +namespace Inno.Editor.Scripting.Tests; + +internal sealed class InlineFailure; diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailureDrawer.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailureDrawer.cs new file mode 100644 index 000000000..6365f97d9 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InlineFailureDrawer.cs @@ -0,0 +1,10 @@ +using System; +using Inno.Editor.Inspection; + +namespace Inno.Editor.Scripting.Tests; + +[PropertyDrawer(typeof(InlineFailure), priority: 10_000)] +internal sealed class InlineFailureDrawer : IPropertyDrawer +{ + public void Draw(PropertyDrawContext context) => throw new InvalidOperationException("Inline drawer failure."); +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InlineOwner.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InlineOwner.cs new file mode 100644 index 000000000..e270b5aba --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InlineOwner.cs @@ -0,0 +1,9 @@ +using Inno.Core.Serialization; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class InlineOwner : ISerializable +{ + [SerializableProperty] + public InlineParent value { get; set; } = new(); +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InlineParent.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InlineParent.cs new file mode 100644 index 000000000..f5891cd60 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InlineParent.cs @@ -0,0 +1,6 @@ +namespace Inno.Editor.Scripting.Tests; + +internal sealed class InlineParent +{ + internal InlineFailure child { get; } = new(); +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InlineParentDrawer.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InlineParentDrawer.cs new file mode 100644 index 000000000..23a29fa7a --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InlineParentDrawer.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Inspection; + +namespace Inno.Editor.Scripting.Tests; + +[PropertyDrawer(typeof(InlineParent), priority: 10_000)] +internal sealed class InlineParentDrawer : IPropertyDrawer +{ + internal static bool drewAfterFailure; + + public void Draw(PropertyDrawContext context) + { + InlineParent parent = (InlineParent)context.GetValue()!; + context.DrawInlineChild("child", typeof(InlineFailure), () => parent.child, static _ => {}, readOnly: true); + drewAfterFailure = true; + } +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs index 86ff30c87..7a0d2a30a 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/InspectionPipelineTests.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; using BGCS.Runtime; @@ -11,9 +9,7 @@ using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Serialization; -using Inno.Editor.Annotations; using Inno.Editor.Core; -using Inno.Editor.ImGui; using Inno.Editor.Inspection; using Inno.Editor.Interactions; using Inno.Extensibility.Modules; @@ -21,7 +17,6 @@ using Inno.Native.ImGui; using EditorUI = Inno.Editor.ImGui.EditorUISession; -using EditorWidget = Inno.Editor.ImGui.ImGuiWidget.ImGuiWidget; using NativeImGui = Inno.Native.ImGui.ImGui; using NativeVector2 = Inno.Native.ImGui.ImVec2C; @@ -304,106 +299,4 @@ public bool ChangeProperty( } } -internal sealed class InlineOwner : ISerializable -{ - [SerializableProperty] - public InlineParent value { get; set; } = new(); -} - -internal sealed class InlineParent -{ - internal InlineFailure child { get; } = new(); -} - -internal sealed class InlineFailure; - -internal sealed class TextStateOwner : ISerializable -{ - [SerializableProperty] - public TextStateValue value { get; set; } = new("Unset"); -} - internal sealed record TextStateValue(string id); - -internal sealed class AttributeOwner : ISerializable -{ - [SerializableProperty] - [Header("Presentation", "Decorators are composed before the property row.")] - [Text("Persistent decorator text remains visible.")] - [Tooltip("Reusable hover guidance.")] - [InspectorName("Friendly Value")] - [Range(2, 8)] - [ShowIf(nameof(showValue))] - [ProbeInspector] - public AttributeValue value { get; set; } = new(); - - internal bool showValue { get; set; } -} - -internal sealed class AttributeValue; - -[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] -internal sealed class ProbeInspectorAttribute : InspectorPresentationAttribute; - -[InspectorAttributeDrawer(typeof(ProbeInspectorAttribute), priority: 10_000)] -internal sealed class ProbeInspectorAttributeDrawer : IInspectorAttributeDrawer -{ - public void Update(InspectorAttributeDrawContext context) - => observations.Add($"update:{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); - - public void DrawBefore(InspectorAttributeDrawContext context) - { - _ = context; - observations.Add("before"); - } - - public void DrawAfter(InspectorAttributeDrawContext context) - { - _ = context; - observations.Add("after"); - } - - internal static List observations { get; } = []; -} - -[PropertyDrawer(typeof(AttributeValue), priority: 10_000)] -internal sealed class AttributeValueDrawer : IPropertyDrawer -{ - public void Draw(PropertyDrawContext context) - => observations.Add($"{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); - - internal static List observations { get; } = []; -} - -[PropertyDrawer(typeof(TextStateValue), priority: 10_000)] -internal sealed class TextStateDrawer : IPropertyDrawer -{ - public void Draw(PropertyDrawContext context) - { - TextStateValue value = (TextStateValue)context.GetValue()!; - bool hasState = context.TryGetTextState("editing", out string? state); - observations.Add($"{value.id}:{(hasState ? state : "")}"); - context.SetTextState("editing", value.id); - } - - internal static List observations { get; } = []; -} - -[PropertyDrawer(typeof(InlineParent), priority: 10_000)] -internal sealed class InlineParentDrawer : IPropertyDrawer -{ - internal static bool drewAfterFailure; - - public void Draw(PropertyDrawContext context) - { - InlineParent parent = (InlineParent)context.GetValue()!; - context.DrawInlineChild("child", typeof(InlineFailure), () => parent.child, static _ => {}, readOnly: true); - drewAfterFailure = true; - } -} - -[PropertyDrawer(typeof(InlineFailure), priority: 10_000)] -internal sealed class InlineFailureDrawer : IPropertyDrawer -{ - public void Draw(PropertyDrawContext context) => throw new InvalidOperationException("Inline drawer failure."); -} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttribute.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttribute.cs new file mode 100644 index 000000000..3e5469f50 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttribute.cs @@ -0,0 +1,7 @@ +using System; +using Inno.Editor.Annotations; + +namespace Inno.Editor.Scripting.Tests; + +[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] +internal sealed class ProbeInspectorAttribute : InspectorPresentationAttribute; diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttributeDrawer.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttributeDrawer.cs new file mode 100644 index 000000000..375ae54ea --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ProbeInspectorAttributeDrawer.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using Inno.Editor.Inspection; + +namespace Inno.Editor.Scripting.Tests; + +[InspectorAttributeDrawer(typeof(ProbeInspectorAttribute), priority: 10_000)] +internal sealed class ProbeInspectorAttributeDrawer : IInspectorAttributeDrawer +{ + public void Update(InspectorAttributeDrawContext context) + => observations.Add($"update:{context.label}:{context.isReadOnly}:{context.minimum}:{context.maximum}"); + + public void DrawBefore(InspectorAttributeDrawContext context) + { + _ = context; + observations.Add("before"); + } + + public void DrawAfter(InspectorAttributeDrawContext context) + { + _ = context; + observations.Add("after"); + } + + internal static List observations { get; } = []; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/SampleIdentitySettings.cs b/tests/scripting/Inno.Editor.Scripting.Tests/SampleIdentitySettings.cs new file mode 100644 index 000000000..240a13074 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/SampleIdentitySettings.cs @@ -0,0 +1,13 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class SampleIdentitySettings : ISerializable +{ + /// + /// Gets or sets one neutral identity stored inside an import settings payload. + /// + [SerializableProperty] + public Guid referenceId { get; set; } +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/SceneReloadProbe.cs b/tests/scripting/Inno.Editor.Scripting.Tests/SceneReloadProbe.cs new file mode 100644 index 000000000..bcd33e85a --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/SceneReloadProbe.cs @@ -0,0 +1,17 @@ +using Inno.Editor.Core; +using Inno.Editor.Scene; + +namespace Inno.Editor.Scripting.Tests; + +[EditorModule("tests.scene-reload-probe", order: 102)] +public sealed class SceneReloadProbe : EditorModule +{ + public SceneReloadProbe(IEditorSceneWorkspace sceneWorkspace) + { + workspace = sceneWorkspace; + } + + public static IEditorSceneWorkspace? workspace { get; private set; } + + public static void Reset() => workspace = null; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingAssetSourceMeta.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingAssetSourceMeta.cs new file mode 100644 index 000000000..8954ae2f2 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingAssetSourceMeta.cs @@ -0,0 +1,19 @@ +using System; +using Inno.Core.Serialization; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class ScriptingAssetSourceMeta : ISerializable +{ + [SerializableProperty] + public Guid persistentId { get; set; } + + [SerializableProperty] + public int sourceKind { get; set; } + + [SerializableProperty] + public string importerId { get; set; } = string.Empty; + + [SerializableProperty] + public byte[] importerSettingsBytes { get; set; } = []; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingCompilationProbe.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingCompilationProbe.cs new file mode 100644 index 000000000..253d48fac --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingCompilationProbe.cs @@ -0,0 +1,16 @@ +using Inno.Editor.Core; + +namespace Inno.Editor.Scripting.Tests; + +[EditorModule("tests.scripting-compilation-probe", order: 101)] +public sealed class ScriptingCompilationProbe : EditorModule +{ + public ScriptingCompilationProbe(IEditorScriptCompilation scripting) + { + compilation = scripting; + } + + public static IEditorScriptCompilation? compilation { get; private set; } + + public static void Reset() => compilation = null; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs new file mode 100644 index 000000000..f9fde197c --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs @@ -0,0 +1,296 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Xunit; +using Inno.Adapter.Modules.DotNet; +using Inno.Adapter.Serialization.DotNet; +using Inno.Assets; +using Inno.Assets.Pipeline; +using Inno.Build; +using Inno.Core.IO; +using Inno.Core.Identity; +using Inno.Core.Input; +using Inno.Core.Logging; +using Inno.Core.Serialization; +using Inno.Core.Settings; +using Inno.Editor.Core; +using Inno.Editor.Interactions; +using Inno.Extensibility.Modules; +using Inno.Extensibility.Types; +using Inno.Plugins.Authoring; +using Inno.Runtime; +using Inno.Scripting.Compiler; +using Inno.Scripting.Reload; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class ScriptingFixture : IDisposable +{ + private readonly IdentityAllocator m_identities = new(); + private readonly IDisposable m_diagnosticScope; + private readonly IDisposable m_identityScope; + private readonly ProjectSettingsStore m_settings; + private readonly PluginEnvironment m_plugins; + private RuntimeSession? m_editorSession; + private bool m_disposed; + + internal ScriptingFixture( + Action? configureProject = null, + bool enableFileSystemWatcher = false, + int fileWatcherFlushDelayMs = 100 + ) { + this.projectRoot = Path.Combine(Path.GetTempPath(), "InnoScriptingPipelineTests", Guid.NewGuid().ToString("N")); + string assetRoot = Path.Combine(projectRoot, "Assets"); + string pluginRoot = Path.Combine(projectRoot, "Plugins"); + string libraryRoot = Path.Combine(projectRoot, "Library"); + Directory.CreateDirectory(assetRoot); + Directory.CreateDirectory(pluginRoot); + Directory.CreateDirectory(libraryRoot); + m_identityScope = m_identities.EnterScope(); + this.host = new EngineHostBuilder().UseMetadataSources( + new DotNetAssemblyCatalogSource(typeof(ScriptingPipelineTests).Assembly), + new ReflectionTypeCatalogSource(), + new ReflectionSerializationMetadataSource() + ).Build(); + m_diagnosticScope = host.diagnostics.EnterScope(); + configureProject?.Invoke(projectRoot, host.serialization); + var pluginSources = new PluginSourceService(host.serialization, pluginRoot, libraryRoot); + PluginScanResult scan = pluginSources.Scan(); + AssetPipelineOptions options = AssetPipelineOptions.Create(assetRoot, libraryRoot); + this.assets = new AssetPipeline( + host.modules, + host.types, + host.serialization, + m_identities, + host.diagnostics, + host.logs, + options with + { + enableFileSystemWatcher = enableFileSystemWatcher, + fileWatcherFlushDelayMs = fileWatcherFlushDelayMs, + sourceMounts = [..options.sourceMounts!, ..PluginSourceService.GetActivatableMounts(scan)] + } + ); + m_settings = new ProjectSettingsStore( + new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, "Settings.Project.inno"))), + host.types, + host.serialization, + new ProjectID("tests.scripting"), + AssetSerializationContext.Create(assets) + ); + m_plugins = new PluginEnvironment(assets, m_settings, host.serialization, pluginRoot, libraryRoot, scan, host.modules.generations); + string dotnetHost = Path.Combine( + Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), + OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" + ); + this.compiler = new ScriptCompiler( + new ScriptCompilerOptions + { + projectRootDirectory = projectRoot, + compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) + }, + assets, + m_plugins + ); + } + + public void Dispose() + { + if (m_disposed) + { + return; + } + m_disposed = true; + m_editorSession?.Dispose(); + m_plugins.Dispose(); + assets.Dispose(); + m_settings.Dispose(); + m_diagnosticScope.Dispose(); + host.Dispose(); + m_identityScope.Dispose(); + if (Directory.Exists(projectRoot)) + { + Directory.Delete(projectRoot, recursive: true); + } + } + + internal string projectRoot { get; } + internal EngineHost host { get; } + internal AssetPipeline assets { get; } + internal ScriptCompiler compiler { get; } + internal IReadOnlyList activePlugins => m_plugins.activePlugins; + + internal RuntimeSession editorSession + => m_editorSession ?? throw new InvalidOperationException("The Editor runtime session has not been created."); + + internal void Write( + string relativePath, + string source + ) { + string path = Path.Combine(projectRoot, "Assets", relativePath); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, source); + } + + internal void Move( + string sourceRelativePath, + string destinationRelativePath + ) { + string source = Path.Combine(projectRoot, "Assets", sourceRelativePath); + string destination = Path.Combine(projectRoot, "Assets", destinationRelativePath); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + File.Move(source, destination); + string sourceMetadata = source + ".imeta"; + if (File.Exists(sourceMetadata)) + { + File.Move(sourceMetadata, destination + ".imeta"); + } + } + + internal void WriteVersionedBehavior(int version) + => Write("VersionedBehavior.cs", $$""" + using InnoEngine.Scene; + + public sealed class VersionedBehavior : GameBehavior + { + public int version => {{version}}; + } + """); + + internal void Rescan() => assets.Rescan(); + + internal ScriptCompilationResult Compile( + IProgress? progress = null, + CancellationToken cancellationToken = default + ) { + Rescan(); + return compiler.CompileAuthoringGenerationAsync(progress, cancellationToken).GetAwaiter().GetResult(); + } + + internal ScriptCompilationResult CompileRuntimeDeployment( + string? targetRuntimeDirectory = null, + IProgress? progress = null, + CancellationToken cancellationToken = default + ) { + Rescan(); + return compiler + .CompileRuntimeDeploymentAsync(targetRuntimeDirectory ?? AppContext.BaseDirectory, progress, cancellationToken) + .GetAwaiter() + .GetResult(); + } + + internal string CreateDeploymentRuntime() + { + string directory = Path.Combine(projectRoot, "TargetRuntime"); + Directory.CreateDirectory(directory); + foreach (string source in Directory.EnumerateFiles(AppContext.BaseDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly)) + { + File.Copy(source, Path.Combine(directory, Path.GetFileName(source)), overwrite: true); + } + + return directory; + } + + internal ScriptReloadHost CreateReloadHost( + EditorReloadCoordinator? reloads = null, + bool autoCompile = false + ) => new( + new ScriptReloadOptions + { + autoCompile = autoCompile, + debounceMilliseconds = 0, + compilationWarningTimeout = Timeout.InfiniteTimeSpan + }, + compiler, + assets, + m_plugins, + host.modules, + m_settings, + reloads ?? new EditorReloadCoordinator(), + CreateScriptModuleSource + ); + + internal ScriptCompilationResult CompilePending(ScriptReloadHost reload) + { + Rescan(); + reload.RecompileScripting(); + Assert.True(reload.TryCompilePending(out Task? compilation)); + return Assert.IsAssignableFrom>(compilation).GetAwaiter().GetResult(); + } + + internal ScriptCompilationResult CompilePendingPluginReload(ScriptReloadHost reload) + { + reload.ReloadPlugins(); + Assert.True(reload.TryCompilePending(out Task? compilation)); + return Assert.IsAssignableFrom>(compilation).GetAwaiter().GetResult(); + } + + internal bool RefreshPlugins() => m_plugins.Refresh(); + + internal Type ResolveActiveType(string name) + { + TypeCacheSnapshot snapshot = host.types.current; + return snapshot.types + .Select(typeRef => typeRef.Resolve(snapshot)) + .Single(type => string.Equals(type.Name, name, StringComparison.Ordinal)); + } + + internal EditorInteractionRuntime CreateEditorRuntime(EditorReloadCoordinator? reloads = null) + { + ScriptingCompilationProbe.Reset(); + SceneReloadProbe.Reset(); + reloads ??= new EditorReloadCoordinator(); + RuntimeSession editorSession = CreateEditorSession(); + return new EditorInteractionRuntime( + new EditorContext(projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), + host.types, + host.logs, + [ + host.types, + host.serialization, + m_identities, + editorSession.identities, + host.modules, + assets, + m_plugins, + m_settings, + compiler, + new Func(CreateScriptModuleSource), + editorSession, + reloads + ] + ); + } + + internal RuntimeSession CreateEditorSession() + { + m_editorSession ??= host.CreateSession( + new RuntimeSessionOptions + { + kind = RuntimeSessionKind.Edit, + applicationID = "tests.editor", + createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(projectRoot, "Persistent", "tests.editor"), "Logs")), + referenceResolvers = [assets] + } + ); + return m_editorSession; + } + + private IModuleSource CreateScriptModuleSource(ScriptModuleDeployment deployment) + => new DotNetModuleSource + { + artifactRootDirectory = Path.Combine(projectRoot, "Library", "Assemblies"), + moduleName = deployment.moduleName, + mainAssemblyPath = deployment.mainAssemblyPath, + domain = deployment.domain, + scope = deployment.scope, + preloadAssemblyPaths = deployment.preloadAssemblyPaths, + upstreamModuleNames = deployment.upstreamModuleNames, + assemblyScopes = deployment.assemblyScopes, + collectible = true + }; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UILifecycle.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UILifecycle.cs index 597301599..4f5467803 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UILifecycle.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.UILifecycle.cs @@ -2,7 +2,6 @@ using System.Runtime.CompilerServices; using Xunit; using Inno.Core.Serialization; -using Inno.Core.Serialization.Converters; using Inno.Editor.Core; using Inno.Editor.Interactions; using Inno.Scripting.Compiler; @@ -117,19 +116,3 @@ int version Assert.True(item.status.isEnabled); } } - -internal sealed class CapturedScriptPayload(ISerializable payload) : ISerializable -{ - internal ISerializable payload { get; } = payload; -} - -internal sealed class CapturedScriptPayloadConverter : SerializationConverter -{ - public override void Write( - SerializationWriter writer, - CapturedScriptPayload value - ) => writer.WritePropertiesData("state", value.payload); - - public override CapturedScriptPayload Read(SerializationReader reader) - => throw new NotSupportedException("This fixture only captures an existing generation."); -} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs index 2fe14f081..be435b7ec 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs @@ -8,23 +8,17 @@ using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Runtime.Loader; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Xunit; -using Inno.Adapter.Modules.DotNet; -using Inno.Adapter.Serialization.DotNet; using Inno.Assets; using Inno.Assets.Pipeline; -using Inno.Build; using Inno.Core.Diagnostics; using Inno.Core.Execution; using Inno.Core.IO; -using Inno.Core.Identity; -using Inno.Core.Input; using Inno.Core.Logging; using Inno.Core.Serialization; using Inno.Core.Settings; @@ -33,12 +27,10 @@ using Inno.Editor.Interactions; using Inno.Editor.PlayMode; using Inno.Editor.Scene; -using Inno.Editor.Scripting; using Inno.Extensibility.Modules; using Inno.Extensibility.Reload; using Inno.Extensibility.Types; using Inno.Plugins; -using Inno.Plugins.Authoring; using Inno.Runtime; using Inno.Scene; using Inno.Scene.Components; @@ -2582,320 +2574,3 @@ private sealed class TestSceneReloadTransaction(ISceneReloadStateTransfer transf public void RestorePreviousState() => transfer.RestorePreviousState(); } } - -internal sealed class ScriptingFixture : IDisposable -{ - private readonly IdentityAllocator m_identities = new(); - private readonly IDisposable m_diagnosticScope; - private readonly IDisposable m_identityScope; - private readonly ProjectSettingsStore m_settings; - private readonly PluginEnvironment m_plugins; - private RuntimeSession? m_editorSession; - private bool m_disposed; - - internal ScriptingFixture( - Action? configureProject = null, - bool enableFileSystemWatcher = false, - int fileWatcherFlushDelayMs = 100 - ) { - this.projectRoot = Path.Combine(Path.GetTempPath(), "InnoScriptingPipelineTests", Guid.NewGuid().ToString("N")); - string assetRoot = Path.Combine(projectRoot, "Assets"); - string pluginRoot = Path.Combine(projectRoot, "Plugins"); - string libraryRoot = Path.Combine(projectRoot, "Library"); - Directory.CreateDirectory(assetRoot); - Directory.CreateDirectory(pluginRoot); - Directory.CreateDirectory(libraryRoot); - m_identityScope = m_identities.EnterScope(); - this.host = new EngineHostBuilder().UseMetadataSources( - new DotNetAssemblyCatalogSource(typeof(ScriptingPipelineTests).Assembly), - new ReflectionTypeCatalogSource(), - new ReflectionSerializationMetadataSource() - ).Build(); - m_diagnosticScope = host.diagnostics.EnterScope(); - configureProject?.Invoke(projectRoot, host.serialization); - var pluginSources = new PluginSourceService(host.serialization, pluginRoot, libraryRoot); - PluginScanResult scan = pluginSources.Scan(); - AssetPipelineOptions options = AssetPipelineOptions.Create(assetRoot, libraryRoot); - this.assets = new AssetPipeline( - host.modules, - host.types, - host.serialization, - m_identities, - host.diagnostics, - host.logs, - options with - { - enableFileSystemWatcher = enableFileSystemWatcher, - fileWatcherFlushDelayMs = fileWatcherFlushDelayMs, - sourceMounts = [..options.sourceMounts!, ..PluginSourceService.GetActivatableMounts(scan)] - } - ); - m_settings = new ProjectSettingsStore( - new FileByteDocumentStore(Path.GetFullPath(Path.Combine(projectRoot, "Settings.Project.inno"))), - host.types, - host.serialization, - new ProjectID("tests.scripting"), - AssetSerializationContext.Create(assets) - ); - m_plugins = new PluginEnvironment(assets, m_settings, host.serialization, pluginRoot, libraryRoot, scan, host.modules.generations); - string dotnetHost = Path.Combine( - Path.GetFullPath("../../..", RuntimeEnvironment.GetRuntimeDirectory()), - OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet" - ); - this.compiler = new ScriptCompiler( - new ScriptCompilerOptions - { - projectRootDirectory = projectRoot, - compilationEnvironment = new SdkScriptCompilationEnvironment(dotnetHost, projectRoot) - }, - assets, - m_plugins - ); - } - - public void Dispose() - { - if (m_disposed) - { - return; - } - m_disposed = true; - m_editorSession?.Dispose(); - m_plugins.Dispose(); - assets.Dispose(); - m_settings.Dispose(); - m_diagnosticScope.Dispose(); - host.Dispose(); - m_identityScope.Dispose(); - if (Directory.Exists(projectRoot)) - { - Directory.Delete(projectRoot, recursive: true); - } - } - - internal string projectRoot { get; } - internal EngineHost host { get; } - internal AssetPipeline assets { get; } - internal ScriptCompiler compiler { get; } - internal IReadOnlyList activePlugins => m_plugins.activePlugins; - - internal RuntimeSession editorSession - => m_editorSession ?? throw new InvalidOperationException("The Editor runtime session has not been created."); - - internal void Write( - string relativePath, - string source - ) { - string path = Path.Combine(projectRoot, "Assets", relativePath); - Directory.CreateDirectory(Path.GetDirectoryName(path)!); - File.WriteAllText(path, source); - } - - internal void Move( - string sourceRelativePath, - string destinationRelativePath - ) { - string source = Path.Combine(projectRoot, "Assets", sourceRelativePath); - string destination = Path.Combine(projectRoot, "Assets", destinationRelativePath); - Directory.CreateDirectory(Path.GetDirectoryName(destination)!); - File.Move(source, destination); - string sourceMetadata = source + ".imeta"; - if (File.Exists(sourceMetadata)) - { - File.Move(sourceMetadata, destination + ".imeta"); - } - } - - internal void WriteVersionedBehavior(int version) - => Write("VersionedBehavior.cs", $$""" - using InnoEngine.Scene; - - public sealed class VersionedBehavior : GameBehavior - { - public int version => {{version}}; - } - """); - - internal void Rescan() => assets.Rescan(); - - internal ScriptCompilationResult Compile( - IProgress? progress = null, - CancellationToken cancellationToken = default - ) { - Rescan(); - return compiler.CompileAuthoringGenerationAsync(progress, cancellationToken).GetAwaiter().GetResult(); - } - - internal ScriptCompilationResult CompileRuntimeDeployment( - string? targetRuntimeDirectory = null, - IProgress? progress = null, - CancellationToken cancellationToken = default - ) { - Rescan(); - return compiler - .CompileRuntimeDeploymentAsync(targetRuntimeDirectory ?? AppContext.BaseDirectory, progress, cancellationToken) - .GetAwaiter() - .GetResult(); - } - - internal string CreateDeploymentRuntime() - { - string directory = Path.Combine(projectRoot, "TargetRuntime"); - Directory.CreateDirectory(directory); - foreach (string source in Directory.EnumerateFiles(AppContext.BaseDirectory, "Inno.*.dll", SearchOption.TopDirectoryOnly)) - { - File.Copy(source, Path.Combine(directory, Path.GetFileName(source)), overwrite: true); - } - - return directory; - } - - internal ScriptReloadHost CreateReloadHost( - EditorReloadCoordinator? reloads = null, - bool autoCompile = false - ) => new( - new ScriptReloadOptions - { - autoCompile = autoCompile, - debounceMilliseconds = 0, - compilationWarningTimeout = Timeout.InfiniteTimeSpan - }, - compiler, - assets, - m_plugins, - host.modules, - m_settings, - reloads ?? new EditorReloadCoordinator(), - CreateScriptModuleSource - ); - - internal ScriptCompilationResult CompilePending(ScriptReloadHost reload) - { - Rescan(); - reload.RecompileScripting(); - Assert.True(reload.TryCompilePending(out Task? compilation)); - return Assert.IsAssignableFrom>(compilation).GetAwaiter().GetResult(); - } - - internal ScriptCompilationResult CompilePendingPluginReload(ScriptReloadHost reload) - { - reload.ReloadPlugins(); - Assert.True(reload.TryCompilePending(out Task? compilation)); - return Assert.IsAssignableFrom>(compilation).GetAwaiter().GetResult(); - } - - internal bool RefreshPlugins() => m_plugins.Refresh(); - - internal Type ResolveActiveType(string name) - { - TypeCacheSnapshot snapshot = host.types.current; - return snapshot.types - .Select(typeRef => typeRef.Resolve(snapshot)) - .Single(type => string.Equals(type.Name, name, StringComparison.Ordinal)); - } - - internal EditorInteractionRuntime CreateEditorRuntime(EditorReloadCoordinator? reloads = null) - { - ScriptingCompilationProbe.Reset(); - SceneReloadProbe.Reset(); - reloads ??= new EditorReloadCoordinator(); - RuntimeSession editorSession = CreateEditorSession(); - return new EditorInteractionRuntime( - new EditorContext(projectRoot, new EditorKeyboardPolicy(KeyModifier.Control, "Super")), - host.types, - host.logs, - [ - host.types, - host.serialization, - m_identities, - editorSession.identities, - host.modules, - assets, - m_plugins, - m_settings, - compiler, - new Func(CreateScriptModuleSource), - editorSession, - reloads - ] - ); - } - - internal RuntimeSession CreateEditorSession() - { - m_editorSession ??= host.CreateSession( - new RuntimeSessionOptions - { - kind = RuntimeSessionKind.Edit, - applicationID = "tests.editor", - createLogSink = _ => new FileLogSink(Path.Combine(Path.Combine(projectRoot, "Persistent", "tests.editor"), "Logs")), - referenceResolvers = [assets] - } - ); - return m_editorSession; - } - - private IModuleSource CreateScriptModuleSource(ScriptModuleDeployment deployment) - => new DotNetModuleSource - { - artifactRootDirectory = Path.Combine(projectRoot, "Library", "Assemblies"), - moduleName = deployment.moduleName, - mainAssemblyPath = deployment.mainAssemblyPath, - domain = deployment.domain, - scope = deployment.scope, - preloadAssemblyPaths = deployment.preloadAssemblyPaths, - upstreamModuleNames = deployment.upstreamModuleNames, - assemblyScopes = deployment.assemblyScopes, - collectible = true - }; -} - -internal sealed class SampleIdentitySettings : ISerializable -{ - /// - /// Gets or sets one neutral identity stored inside an import settings payload. - /// - [SerializableProperty] - public Guid referenceId { get; set; } -} - -internal sealed class ScriptingAssetSourceMeta : ISerializable -{ - [SerializableProperty] - public Guid persistentId { get; set; } - - [SerializableProperty] - public int sourceKind { get; set; } - - [SerializableProperty] - public string importerId { get; set; } = string.Empty; - - [SerializableProperty] - public byte[] importerSettingsBytes { get; set; } = []; -} - -[EditorModule("tests.scripting-compilation-probe", order: 101)] -public sealed class ScriptingCompilationProbe : EditorModule -{ - public ScriptingCompilationProbe(IEditorScriptCompilation scripting) - { - compilation = scripting; - } - - public static IEditorScriptCompilation? compilation { get; private set; } - - public static void Reset() => compilation = null; -} - -[EditorModule("tests.scene-reload-probe", order: 102)] -public sealed class SceneReloadProbe : EditorModule -{ - public SceneReloadProbe(IEditorSceneWorkspace sceneWorkspace) - { - workspace = sceneWorkspace; - } - - public static IEditorSceneWorkspace? workspace { get; private set; } - - public static void Reset() => workspace = null; -} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/TextStateDrawer.cs b/tests/scripting/Inno.Editor.Scripting.Tests/TextStateDrawer.cs new file mode 100644 index 000000000..b27338c95 --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/TextStateDrawer.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using Inno.Editor.Inspection; + +namespace Inno.Editor.Scripting.Tests; + +[PropertyDrawer(typeof(TextStateValue), priority: 10_000)] +internal sealed class TextStateDrawer : IPropertyDrawer +{ + public void Draw(PropertyDrawContext context) + { + TextStateValue value = (TextStateValue)context.GetValue()!; + bool hasState = context.TryGetTextState("editing", out string? state); + observations.Add($"{value.id}:{(hasState ? state : "")}"); + context.SetTextState("editing", value.id); + } + + internal static List observations { get; } = []; +} diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/TextStateOwner.cs b/tests/scripting/Inno.Editor.Scripting.Tests/TextStateOwner.cs new file mode 100644 index 000000000..8048a3fef --- /dev/null +++ b/tests/scripting/Inno.Editor.Scripting.Tests/TextStateOwner.cs @@ -0,0 +1,9 @@ +using Inno.Core.Serialization; + +namespace Inno.Editor.Scripting.Tests; + +internal sealed class TextStateOwner : ISerializable +{ + [SerializableProperty] + public TextStateValue value { get; set; } = new("Unset"); +} diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressCollection.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressCollection.cs new file mode 100644 index 000000000..47ba10b69 --- /dev/null +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressCollection.cs @@ -0,0 +1,9 @@ +using Xunit; + +namespace Inno.Tooling.Validation.Integration.Tests; + +/// +/// Isolates the process console while observing the public validation entry's live progress. +/// +[CollectionDefinition(nameof(ValidationProgressCollection), DisableParallelization = true)] +public sealed class ValidationProgressCollection; diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs index 8029b9710..d21749292 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs @@ -10,12 +10,6 @@ namespace Inno.Tooling.Validation.Integration.Tests; -/// -/// Isolates the process console while observing the public validation entry's live progress. -/// -[CollectionDefinition(nameof(ValidationProgressCollection), DisableParallelization = true)] -public sealed class ValidationProgressCollection; - [Collection(nameof(ValidationProgressCollection))] public sealed class ValidationProgressTests { diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/EmptyBodyStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/EmptyBodyStyleRule.cs index 6da3918f2..883e00877 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/EmptyBodyStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/EmptyBodyStyleRule.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -57,47 +56,3 @@ or LocalFunctionStatementSyntax return edits; } } - -// B-07: an empty type ends with a semicolon and has no braces. -internal sealed class EmptyTypeStyleRule : StyleRule -{ - private const string C_ID = "B-07"; - - internal override string id => C_ID; - - internal override StyleRuleKind kind => StyleRuleKind.Rewrite; - - internal override void Check( - StyleSource source, - ICollection findings - ) { - foreach (StyleEdit edit in Fix(source)) - { - findings.Add(source.Finding(C_ID, edit.end - 1, "End an empty type with a semicolon instead of braces.")); - } - } - - internal override IReadOnlyList Fix(StyleSource source) - { - List edits = []; - foreach (SyntaxNode node in source.root.DescendantNodes()) - { - if (node is not TypeDeclarationSyntax { Members.Count: 0 } type - || type.OpenBraceToken.Span.Length == 0 - || type.CloseBraceToken.IsMissing - ) { - continue; - } - SyntaxToken previous = type.OpenBraceToken.GetPreviousToken(); - if (!StyleLayout.IsBlank(source.content, previous.Span.End, type.OpenBraceToken.SpanStart)) continue; - if (!StyleLayout.IsBlank(source.content, type.OpenBraceToken.Span.End, type.CloseBraceToken.SpanStart)) - { - continue; - } - if (type.DescendantTrivia().Any(static trivia => trivia.IsDirective)) continue; - edits.Add(new StyleEdit(previous.Span.End, type.CloseBraceToken.Span.End, ";")); - } - - return edits; - } -} diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/EmptyTypeStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/EmptyTypeStyleRule.cs new file mode 100644 index 000000000..015416910 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/EmptyTypeStyleRule.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// B-07: an empty type ends with a semicolon and has no braces. +internal sealed class EmptyTypeStyleRule : StyleRule +{ + private const string C_ID = "B-07"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + foreach (StyleEdit edit in Fix(source)) + { + findings.Add(source.Finding(C_ID, edit.end - 1, "End an empty type with a semicolon instead of braces.")); + } + } + + internal override IReadOnlyList Fix(StyleSource source) + { + List edits = []; + foreach (SyntaxNode node in source.root.DescendantNodes()) + { + if (node is not TypeDeclarationSyntax { Members.Count: 0 } type + || type.OpenBraceToken.Span.Length == 0 + || type.CloseBraceToken.IsMissing + ) { + continue; + } + SyntaxToken previous = type.OpenBraceToken.GetPreviousToken(); + if (!StyleLayout.IsBlank(source.content, previous.Span.End, type.OpenBraceToken.SpanStart)) continue; + if (!StyleLayout.IsBlank(source.content, type.OpenBraceToken.Span.End, type.CloseBraceToken.SpanStart)) + { + continue; + } + if (type.DescendantTrivia().Any(static trivia => trivia.IsDirective)) continue; + edits.Add(new StyleEdit(previous.Span.End, type.CloseBraceToken.Span.End, ";")); + } + + return edits; + } +} diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiCapture.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiCapture.cs new file mode 100644 index 000000000..fa445b019 --- /dev/null +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiCapture.cs @@ -0,0 +1,11 @@ +namespace Inno.Tooling.Documentation.Indexing; + +internal sealed record DocumentationApiCapture( + string path, + string sha256, + string model, + string configuration, + string? target, + string sourceRevision, + string sourceTree +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs index 91d781a9d..0e4907415 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiComposition.cs @@ -12,23 +12,6 @@ namespace Inno.Tooling.Documentation.Indexing; -internal sealed record DocumentationApiOrigin( - string page, - string id, - string path, - string source, - string editorialStatus, - string? scope, - string revision, - string[] surfaces -); - -internal sealed record DocumentationComposedContent( - IReadOnlyDictionary pages, - IReadOnlyDictionary inputs, - IReadOnlyList origins -); - internal static class DocumentationApiComposition { internal static DocumentationComposedContent Prepare( @@ -425,3 +408,20 @@ int level return body; } } + +internal sealed record DocumentationApiOrigin( + string page, + string id, + string path, + string source, + string editorialStatus, + string? scope, + string revision, + string[] surfaces +); + +internal sealed record DocumentationComposedContent( + IReadOnlyDictionary pages, + IReadOnlyDictionary inputs, + IReadOnlyList origins +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiContent.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiContent.cs index ef7fa7a80..e6711456f 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiContent.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiContent.cs @@ -2,48 +2,13 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using YamlDotNet.Core; using YamlDotNet.RepresentationModel; -using Inno.Core.IO; namespace Inno.Tooling.Documentation.Indexing; -internal sealed record DocumentationApiContentEntry( - string symbol, - string path, - string type, - string title, - string contract -); - -internal sealed record DocumentationApiContentRegistry( - string schema, - IReadOnlyList entries, - IReadOnlyList? navigation = null -); - -internal sealed record DocumentationApiEdit( - string path, - string? before, - string? text -); - -internal sealed record DocumentationApiWarning( - string symbol, - string path, - string code, - string message -); - -internal sealed record DocumentationApiPlan( - IReadOnlyList edits, - IReadOnlyList warnings, - int symbols -); - internal static class DocumentationApiContent { internal const string C_REGISTRY = "reference/api/content.json"; @@ -443,3 +408,36 @@ private static string PathName(DocumentationApiFact fact) private static string Normalize(string text) => Regex.Replace(text, "\\s+", " ").Trim(); } + +internal sealed record DocumentationApiContentEntry( + string symbol, + string path, + string type, + string title, + string contract +); + +internal sealed record DocumentationApiContentRegistry( + string schema, + IReadOnlyList entries, + IReadOnlyList? navigation = null +); + +internal sealed record DocumentationApiEdit( + string path, + string? before, + string? text +); + +internal sealed record DocumentationApiWarning( + string symbol, + string path, + string code, + string message +); + +internal sealed record DocumentationApiPlan( + IReadOnlyList edits, + IReadOnlyList warnings, + int symbols +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFacts.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFacts.cs index 3aea1072a..7d089968c 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFacts.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiFacts.cs @@ -7,27 +7,6 @@ namespace Inno.Tooling.Documentation.Indexing; -internal sealed record DocumentationApiFact( - string key, - string project, - string family, - string? scope, - string id, - string? containingType, - string kind, - string signature, - string signatureHash, - string documentation, - string source, - int line, - string revision, - string configuration, - string? target, - string surface, - string? baseType, - IReadOnlyList interfaces -); - internal static class DocumentationApiFacts { internal static IReadOnlyDictionary Read( @@ -223,3 +202,24 @@ string relative string name ) => value.TryGetProperty(name, out JsonElement result) && result.ValueKind != JsonValueKind.Null ? result.GetString() : null; } + +internal sealed record DocumentationApiFact( + string key, + string project, + string family, + string? scope, + string id, + string? containingType, + string kind, + string signature, + string signatureHash, + string documentation, + string source, + int line, + string revision, + string configuration, + string? target, + string surface, + string? baseType, + IReadOnlyList interfaces +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPackage.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPackage.cs index 742adc88e..8638a2a06 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPackage.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationApiPackage.cs @@ -10,22 +10,6 @@ namespace Inno.Tooling.Documentation.Indexing; -internal sealed record DocumentationApiPackageFile( - string path, - string sha256, - string text -); - -internal sealed record DocumentationApiPackageData( - string schema, - string repository, - string revision, - string sourceTree, - string toolingRevision, - string contentIdentity, - IReadOnlyList files -); - internal static class DocumentationApiPackage { private const string C_BINDING = "reference/engine.lock.json"; @@ -267,3 +251,19 @@ private static string Identity(IEnumerable files) ) ); } + +internal sealed record DocumentationApiPackageFile( + string path, + string sha256, + string text +); + +internal sealed record DocumentationApiPackageData( + string schema, + string repository, + string revision, + string sourceTree, + string toolingRevision, + string contentIdentity, + IReadOnlyList files +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationBinding.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationBinding.cs new file mode 100644 index 000000000..f2d29f0a1 --- /dev/null +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationBinding.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace Inno.Tooling.Documentation.Indexing; + +internal sealed record DocumentationBinding( + string repository, + string revision, + string sourceTree, + string projectManifest, + string projectManifestIdentity, + string toolingRevision, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyList? apiManifests = null +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationManifest.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationManifest.cs new file mode 100644 index 000000000..4fa099087 --- /dev/null +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationManifest.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace Inno.Tooling.Documentation.Indexing; + +internal sealed record DocumentationManifest( + string identity, + string schema, + string parserSchema, + DocumentationBinding binding, + IReadOnlyDictionary pages, + IReadOnlyList projects, + IReadOnlyList search, + IReadOnlyList symbols, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyList? references = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyDictionary? sourceFiles = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyList? apiOrigins = null +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationModels.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationModels.cs deleted file mode 100644 index 8d0b71d57..000000000 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationModels.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System.Collections.Generic; -using System.Text.Json.Serialization; - -namespace Inno.Tooling.Documentation.Indexing; - -internal sealed record DocumentationProject( - string name, - string path, - string? entry, - string[] surfaces -); - -internal sealed record DocumentationBinding( - string repository, - string revision, - string sourceTree, - string projectManifest, - string projectManifestIdentity, - string toolingRevision, - [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyList? apiManifests = null -); - -internal sealed record DocumentationApiCapture( - string path, - string sha256, - string model, - string configuration, - string? target, - string sourceRevision, - string sourceTree -); - -internal sealed record DocumentationManifest( - string identity, - string schema, - string parserSchema, - DocumentationBinding binding, - IReadOnlyDictionary pages, - IReadOnlyList projects, - IReadOnlyList search, - IReadOnlyList symbols, - [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyList? references = null, - [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyDictionary? sourceFiles = null, - [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyList? apiOrigins = null -); - -internal sealed record DocumentationSymbolReference( - string project, - string surface, - string id, - string pageId, - string anchor, - string[]? surfaces = null -); - -internal sealed record DocumentationPageReference( - string pageId, - string key, - string payloadIdentity, - DocumentationMetadata metadata -); - -internal sealed record DocumentationSearchEntry( - string pageId, - string section, - string title, - string body, - string[] tokens -); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationPage.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationPage.cs index 98c8067ba..686f400cf 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationPage.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationPage.cs @@ -2,18 +2,6 @@ namespace Inno.Tooling.Documentation.Indexing; -internal sealed record DocumentationMetadata( - string uid, - string kind, - string[] owners, - string[] aliases, - string[] contracts, - string? apiSurface, - DocumentationExampleContext? examples, - string? apiScope = null, - string[]? apiSurfaces = null -); - internal sealed record DocumentationPage( string path, string identity, @@ -27,6 +15,18 @@ internal sealed record DocumentationPage( IReadOnlyList codeBlocks ); +internal sealed record DocumentationMetadata( + string uid, + string kind, + string[] owners, + string[] aliases, + string[] contracts, + string? apiSurface, + DocumentationExampleContext? examples, + string? apiScope = null, + string[]? apiSurfaces = null +); + internal sealed record DocumentationSection( string anchor, string title, diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationPageReference.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationPageReference.cs new file mode 100644 index 000000000..cace63e21 --- /dev/null +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationPageReference.cs @@ -0,0 +1,8 @@ +namespace Inno.Tooling.Documentation.Indexing; + +internal sealed record DocumentationPageReference( + string pageId, + string key, + string payloadIdentity, + DocumentationMetadata metadata +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationProject.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationProject.cs new file mode 100644 index 000000000..8ddba26b9 --- /dev/null +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationProject.cs @@ -0,0 +1,8 @@ +namespace Inno.Tooling.Documentation.Indexing; + +internal sealed record DocumentationProject( + string name, + string path, + string? entry, + string[] surfaces +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs index 6f94fa846..5711b75de 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationProjectGuides.cs @@ -11,17 +11,6 @@ namespace Inno.Tooling.Documentation.Indexing; -internal sealed record DocumentationProjectGuide( - string path, - string uid, - string project -); - -internal sealed record DocumentationProjectGuideRegistry( - string schema, - DocumentationProjectGuide[] entries -); - internal static class DocumentationProjectGuides { internal const string C_REGISTRY = "reference/projects/content.json"; @@ -390,3 +379,14 @@ private static string Serialize(YamlMappingNode metadata) return text.EndsWith("\n...", StringComparison.Ordinal) ? text[..^4] : text; } } + +internal sealed record DocumentationProjectGuide( + string path, + string uid, + string project +); + +internal sealed record DocumentationProjectGuideRegistry( + string schema, + DocumentationProjectGuide[] entries +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationSearchEntry.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationSearchEntry.cs new file mode 100644 index 000000000..aa7957dcf --- /dev/null +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationSearchEntry.cs @@ -0,0 +1,9 @@ +namespace Inno.Tooling.Documentation.Indexing; + +internal sealed record DocumentationSearchEntry( + string pageId, + string section, + string title, + string body, + string[] tokens +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationSymbolReference.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationSymbolReference.cs new file mode 100644 index 000000000..c6ea551d5 --- /dev/null +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationSymbolReference.cs @@ -0,0 +1,10 @@ +namespace Inno.Tooling.Documentation.Indexing; + +internal sealed record DocumentationSymbolReference( + string project, + string surface, + string id, + string pageId, + string anchor, + string[]? surfaces = null +); diff --git a/tools/Inno.Tooling.Documentation/Indexing/DocumentationXml.cs b/tools/Inno.Tooling.Documentation/Indexing/DocumentationXml.cs index 80e7ef4a8..300cf4fb6 100644 --- a/tools/Inno.Tooling.Documentation/Indexing/DocumentationXml.cs +++ b/tools/Inno.Tooling.Documentation/Indexing/DocumentationXml.cs @@ -7,13 +7,6 @@ namespace Inno.Tooling.Documentation.Indexing; -internal sealed record DocumentationXmlContent( - string[] summaries, - string body -) { - internal string summary => string.Join("\n\n", summaries); -} - internal static class DocumentationXml { internal static DocumentationXmlContent Read(string xml) @@ -184,3 +177,10 @@ string Cell(XElement? value) ) + "\n\n"; } } + +internal sealed record DocumentationXmlContent( + string[] summaries, + string body +) { + internal string summary => string.Join("\n\n", summaries); +} diff --git a/tools/Inno.Tooling.Validation/ValidationPlan.cs b/tools/Inno.Tooling.Validation/ValidationPlan.cs index 13e42ff82..283a18f8f 100644 --- a/tools/Inno.Tooling.Validation/ValidationPlan.cs +++ b/tools/Inno.Tooling.Validation/ValidationPlan.cs @@ -4,23 +4,6 @@ namespace Inno.Tooling.Validation; -internal sealed record ValidationPlanningResult( - ValidationPlan? plan, - ValidationPreparation? preparation -); - -internal sealed record ValidationPreparation( - string status, - string kind, - string root, - string commit, - string baseline, - string inputIdentity, - string reason, - string[] owners, - Dictionary sources -); - internal sealed record ValidationPlan( string root, string baseline, @@ -65,6 +48,23 @@ public bool backendRequired )); } +internal sealed record ValidationPlanningResult( + ValidationPlan? plan, + ValidationPreparation? preparation +); + +internal sealed record ValidationPreparation( + string status, + string kind, + string root, + string commit, + string baseline, + string inputIdentity, + string reason, + string[] owners, + Dictionary sources +); + internal sealed record BackendPackageReceipt( string target, string sha256, diff --git a/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs b/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs index def5c60ef..9d2986bed 100644 --- a/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs +++ b/tools/Inno.Tooling.Validation/ValidationPlanner.Backends.cs @@ -12,23 +12,6 @@ namespace Inno.Tooling.Validation; -internal sealed record BackendInputPlan( - string commit, - string target, - string configuration, - Dictionary projects, - string[] required, - string[] tests, - string[] missingNativeProducts, - string? developmentProperties, - Dictionary? consumers = null -); - -internal sealed record BackendConsumerInputs( - string identity, - string[] backendOwners -); - internal static partial class ValidationPlanner { internal static async Task BindBackendsAsync( @@ -554,3 +537,20 @@ private sealed record BackendNativeProduct( string configuration ); } + +internal sealed record BackendInputPlan( + string commit, + string target, + string configuration, + Dictionary projects, + string[] required, + string[] tests, + string[] missingNativeProducts, + string? developmentProperties, + Dictionary? consumers = null +); + +internal sealed record BackendConsumerInputs( + string identity, + string[] backendOwners +); diff --git a/tools/Inno.Tooling.Validation/ValidationProfile.cs b/tools/Inno.Tooling.Validation/ValidationProfile.cs index 586d37f3c..43a0e7786 100644 --- a/tools/Inno.Tooling.Validation/ValidationProfile.cs +++ b/tools/Inno.Tooling.Validation/ValidationProfile.cs @@ -1,5 +1,3 @@ -using System; - namespace Inno.Tooling.Validation; internal enum ValidationProfile @@ -11,18 +9,3 @@ internal enum ValidationProfile Performance, NativeProducer } - -internal static class ValidationProfiles -{ - internal static ValidationProfile Parse(string value) - => value switch - { - "fast" => ValidationProfile.Fast, - "pull-request" => ValidationProfile.PullRequest, - "master" => ValidationProfile.Master, - "full" => ValidationProfile.Full, - "performance" => ValidationProfile.Performance, - "native-producer" => ValidationProfile.NativeProducer, - _ => throw new ArgumentException("Unknown validation profile: " + value) - }; -} diff --git a/tools/Inno.Tooling.Validation/ValidationProfiles.cs b/tools/Inno.Tooling.Validation/ValidationProfiles.cs new file mode 100644 index 000000000..8c43fa6fe --- /dev/null +++ b/tools/Inno.Tooling.Validation/ValidationProfiles.cs @@ -0,0 +1,18 @@ +using System; + +namespace Inno.Tooling.Validation; + +internal static class ValidationProfiles +{ + internal static ValidationProfile Parse(string value) + => value switch + { + "fast" => ValidationProfile.Fast, + "pull-request" => ValidationProfile.PullRequest, + "master" => ValidationProfile.Master, + "full" => ValidationProfile.Full, + "performance" => ValidationProfile.Performance, + "native-producer" => ValidationProfile.NativeProducer, + _ => throw new ArgumentException("Unknown validation profile: " + value) + }; +} diff --git a/tools/Inno.Tooling.Validation/ValidationShard.cs b/tools/Inno.Tooling.Validation/ValidationShard.cs index f65f8e505..d5ae979e4 100644 --- a/tools/Inno.Tooling.Validation/ValidationShard.cs +++ b/tools/Inno.Tooling.Validation/ValidationShard.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - namespace Inno.Tooling.Validation; internal sealed record ValidationShard( @@ -10,248 +5,3 @@ internal sealed record ValidationShard( string[] checks, string[] prerequisites ); - -internal static class ValidationShards -{ - internal const int C_EVIDENCE_VERSION = 2; - - internal static ValidationShard[] Create(ValidationCheck[] checks) - { - Dictionary owners = checks.ToDictionary( - static check => check.id, - static check => ( - check.exclusion is not null || check.context is null - ? "architecture" - : check.context == "managed" ? "managed" : "native" - ), - StringComparer.Ordinal - ); - List shards = []; - foreach (IGrouping group in checks.GroupBy(check => owners[check.id], StringComparer.Ordinal)) - { - var prerequisites = new HashSet(StringComparer.Ordinal); - foreach (string required in group.Where(static check => check.exclusion is null) - .SelectMany(static check => check.prerequisites) - ) { - if (!owners.TryGetValue(required, out string? owner)) - { - throw new InvalidDataException("A shard requires an unplanned check: " + required); - } - if (owner != group.Key) - { - prerequisites.Add(owner); - } - } - shards.Add( - new ValidationShard( - group.Key, - group.Select(static check => check.id).ToArray(), - prerequisites.Order(StringComparer.Ordinal).ToArray() - ) - ); - } - return shards.ToArray(); - } - - internal static ValidationShard Require( - ValidationPlan plan, - string id - ) { - ValidationShard[] expected = Create(plan.checks); - if (plan.shards is null - || plan.shards.Length != expected.Length - || expected.Any( - shard => ( - plan.shards.Count( - actual => ( - actual.id == shard.id - && actual.checks.SequenceEqual(shard.checks, StringComparer.Ordinal) - && actual.prerequisites.SequenceEqual(shard.prerequisites, StringComparer.Ordinal) - ) - ) != 1 - ) - ) - ) { - throw new InvalidDataException("The frozen shard partition does not cover the exact plan."); - } - return expected.SingleOrDefault(shard => shard.id == id) ?? throw new InvalidDataException("Unknown validation shard: " + id); - } - - internal static HashSet? InvalidatedChecks( - ValidationPlan plan, - ValidationEvidence? previous - ) { - if (previous is not { completed: true, version: C_EVIDENCE_VERSION, failures: not null } - || previous.environment != plan.environment - || previous.results.DistinctBy(result => result.id).Count() != previous.results.Length - ) { - return null; - } - - var invalid = new HashSet(StringComparer.Ordinal); - foreach (ValidationRunFailure fault in previous.failures) - { - if (fault.stage == "output-stability") - { - ValidationCheck? producer = plan.checks.SingleOrDefault(check => check.id == fault.owner); - if (producer is null) - { - return null; - } - invalid.Add(producer.id); - foreach (ValidationCheck consumer in plan.checks.Where(check => ( - check.context == producer.context - && check.inputs.Contains("@" + producer.owner, StringComparer.Ordinal) - ))) { - invalid.Add(consumer.id); - } - } - else if (fault.stage == "test-execution") - { - ValidationCheck[] owners = plan.checks.Where(check => check.kind == "test" && check.context == fault.owner).ToArray(); - if (!owners.Any(owner => previous.results.Any(result => result.id == owner.id && result.status == "Failed"))) - { - invalid.UnionWith(owners.Select(owner => owner.id)); - } - } - else - { - return null; - } - } - if (invalid.Count != 0) - { - int before; - do - { - before = invalid.Count; - foreach (ValidationCheck check in plan.checks.Where(check => check.prerequisites.Any(invalid.Contains))) - { - invalid.Add(check.id); - } - } - while (before != invalid.Count); - } - return invalid; - } - - internal static ValidationResult[] ValidateEvidence( - ValidationPlan plan, - ValidationEvidence evidence, - string? shard = null - ) { - if (evidence.version != C_EVIDENCE_VERSION || evidence.failures is null) - { - throw new InvalidDataException("Validation evidence has an unsupported format."); - } - if (evidence.commit != plan.commit - || evidence.tree != plan.tree - || evidence.environment != plan.environment - || evidence.planIdentity != ValidationInputs.PlanIdentity(plan) - || evidence.shard != shard - ) { - throw new InvalidDataException("Validation evidence has a different candidate, plan, environment or execution scope."); - } - HashSet? selected = shard is null ? null : Require(plan, shard).checks.ToHashSet(StringComparer.Ordinal); - ValidationCheck[] checks = plan.checks.Where(check => selected is null || selected.Contains(check.id)).ToArray(); - if (checks.Length == 0) - { - throw new InvalidDataException("No planned checks were discovered."); - } - HashSet expected = checks.Select(static check => check.id).ToHashSet(StringComparer.Ordinal); - ILookup observed = evidence.results.ToLookup(static result => result.id, StringComparer.Ordinal); - List errors = []; - foreach (IGrouping group in observed) - { - if (!expected.Contains(group.Key)) - { - errors.Add("Unplanned check: " + group.Key); - } - if (group.Count() != 1) - { - errors.Add("Duplicate check: " + group.Key); - } - } - foreach (ValidationCheck check in checks) - { - ValidationResult? result = observed[check.id].FirstOrDefault(); - if (result is null) - { - errors.Add("Missing check: " + check.id); - } - else if (result.inputIdentity != ValidationInputs.CheckIdentity(plan, check, plan.inputs)) - { - errors.Add("Stale check: " + check.id); - } - else if (check.exclusion is null ? result.status is not ("Passed" or "Reused") : result.status != "NotApplicable") - { - errors.Add(check.id + ": " + result.detail); - } - } - errors.AddRange(evidence.failures.Select(static fault => fault.stage + ": " + fault.detail)); - if (!evidence.completed) - { - errors.Add("Validation did not complete closing verification."); - } - if (errors.Count != 0) - { - throw new InvalidDataException(string.Join(Environment.NewLine, errors)); - } - return evidence.results; - } - - internal static ValidationResult[] Prerequisites( - ValidationPlan plan, - ValidationShard shard, - IReadOnlyList evidence - ) { - if (evidence.Count != shard.prerequisites.Length) - { - throw new InvalidDataException("The shard is missing prerequisites or received unrelated receipts."); - } - return shard.prerequisites.SelectMany(id => - { - ValidationEvidence[] matches = evidence.Where(receipt => receipt.shard == id).ToArray(); - if (matches.Length != 1) - { - throw new InvalidDataException("Missing or duplicate prerequisite shard: " + id); - } - return ValidateEvidence(plan, matches[0], id); - }).ToArray(); - } - - internal static ValidationEvidence Join( - ValidationPlan plan, - IReadOnlyList evidence - ) { - if (plan.shards is null || evidence.Count != plan.shards.Length) - { - throw new InvalidDataException("The required shard matrix is incomplete or duplicated."); - } - List results = []; - foreach (ValidationShard shard in plan.shards) - { - _ = Require(plan, shard.id); - ValidationEvidence[] matches = evidence.Where(receipt => receipt.shard == shard.id).ToArray(); - if (matches.Length != 1) - { - throw new InvalidDataException("Missing or duplicate execution shard: " + shard.id); - } - results.AddRange(ValidateEvidence(plan, matches[0], shard.id)); - } - - var joined = new ValidationEvidence( - plan.commit, - plan.tree, - plan.environment, - evidence.Min(static receipt => receipt.started), - results.ToArray(), - C_EVIDENCE_VERSION, - [], - ValidationInputs.PlanIdentity(plan), - completed: true - ); - _ = ValidateEvidence(plan, joined); - return joined; - } -} diff --git a/tools/Inno.Tooling.Validation/ValidationShards.cs b/tools/Inno.Tooling.Validation/ValidationShards.cs new file mode 100644 index 000000000..259b07c7e --- /dev/null +++ b/tools/Inno.Tooling.Validation/ValidationShards.cs @@ -0,0 +1,251 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Inno.Tooling.Validation; + +internal static class ValidationShards +{ + internal const int C_EVIDENCE_VERSION = 2; + + internal static ValidationShard[] Create(ValidationCheck[] checks) + { + Dictionary owners = checks.ToDictionary( + static check => check.id, + static check => ( + check.exclusion is not null || check.context is null + ? "architecture" + : check.context == "managed" ? "managed" : "native" + ), + StringComparer.Ordinal + ); + List shards = []; + foreach (IGrouping group in checks.GroupBy(check => owners[check.id], StringComparer.Ordinal)) + { + var prerequisites = new HashSet(StringComparer.Ordinal); + foreach (string required in group.Where(static check => check.exclusion is null) + .SelectMany(static check => check.prerequisites) + ) { + if (!owners.TryGetValue(required, out string? owner)) + { + throw new InvalidDataException("A shard requires an unplanned check: " + required); + } + if (owner != group.Key) + { + prerequisites.Add(owner); + } + } + shards.Add( + new ValidationShard( + group.Key, + group.Select(static check => check.id).ToArray(), + prerequisites.Order(StringComparer.Ordinal).ToArray() + ) + ); + } + return shards.ToArray(); + } + + internal static ValidationShard Require( + ValidationPlan plan, + string id + ) { + ValidationShard[] expected = Create(plan.checks); + if (plan.shards is null + || plan.shards.Length != expected.Length + || expected.Any( + shard => ( + plan.shards.Count( + actual => ( + actual.id == shard.id + && actual.checks.SequenceEqual(shard.checks, StringComparer.Ordinal) + && actual.prerequisites.SequenceEqual(shard.prerequisites, StringComparer.Ordinal) + ) + ) != 1 + ) + ) + ) { + throw new InvalidDataException("The frozen shard partition does not cover the exact plan."); + } + return expected.SingleOrDefault(shard => shard.id == id) ?? throw new InvalidDataException("Unknown validation shard: " + id); + } + + internal static HashSet? InvalidatedChecks( + ValidationPlan plan, + ValidationEvidence? previous + ) { + if (previous is not { completed: true, version: C_EVIDENCE_VERSION, failures: not null } + || previous.environment != plan.environment + || previous.results.DistinctBy(result => result.id).Count() != previous.results.Length + ) { + return null; + } + + var invalid = new HashSet(StringComparer.Ordinal); + foreach (ValidationRunFailure fault in previous.failures) + { + if (fault.stage == "output-stability") + { + ValidationCheck? producer = plan.checks.SingleOrDefault(check => check.id == fault.owner); + if (producer is null) + { + return null; + } + invalid.Add(producer.id); + foreach (ValidationCheck consumer in plan.checks.Where(check => ( + check.context == producer.context + && check.inputs.Contains("@" + producer.owner, StringComparer.Ordinal) + ))) { + invalid.Add(consumer.id); + } + } + else if (fault.stage == "test-execution") + { + ValidationCheck[] owners = plan.checks.Where(check => check.kind == "test" && check.context == fault.owner).ToArray(); + if (!owners.Any(owner => previous.results.Any(result => result.id == owner.id && result.status == "Failed"))) + { + invalid.UnionWith(owners.Select(owner => owner.id)); + } + } + else + { + return null; + } + } + if (invalid.Count != 0) + { + int before; + do + { + before = invalid.Count; + foreach (ValidationCheck check in plan.checks.Where(check => check.prerequisites.Any(invalid.Contains))) + { + invalid.Add(check.id); + } + } + while (before != invalid.Count); + } + return invalid; + } + + internal static ValidationResult[] ValidateEvidence( + ValidationPlan plan, + ValidationEvidence evidence, + string? shard = null + ) { + if (evidence.version != C_EVIDENCE_VERSION || evidence.failures is null) + { + throw new InvalidDataException("Validation evidence has an unsupported format."); + } + if (evidence.commit != plan.commit + || evidence.tree != plan.tree + || evidence.environment != plan.environment + || evidence.planIdentity != ValidationInputs.PlanIdentity(plan) + || evidence.shard != shard + ) { + throw new InvalidDataException("Validation evidence has a different candidate, plan, environment or execution scope."); + } + HashSet? selected = shard is null ? null : Require(plan, shard).checks.ToHashSet(StringComparer.Ordinal); + ValidationCheck[] checks = plan.checks.Where(check => selected is null || selected.Contains(check.id)).ToArray(); + if (checks.Length == 0) + { + throw new InvalidDataException("No planned checks were discovered."); + } + HashSet expected = checks.Select(static check => check.id).ToHashSet(StringComparer.Ordinal); + ILookup observed = evidence.results.ToLookup(static result => result.id, StringComparer.Ordinal); + List errors = []; + foreach (IGrouping group in observed) + { + if (!expected.Contains(group.Key)) + { + errors.Add("Unplanned check: " + group.Key); + } + if (group.Count() != 1) + { + errors.Add("Duplicate check: " + group.Key); + } + } + foreach (ValidationCheck check in checks) + { + ValidationResult? result = observed[check.id].FirstOrDefault(); + if (result is null) + { + errors.Add("Missing check: " + check.id); + } + else if (result.inputIdentity != ValidationInputs.CheckIdentity(plan, check, plan.inputs)) + { + errors.Add("Stale check: " + check.id); + } + else if (check.exclusion is null ? result.status is not ("Passed" or "Reused") : result.status != "NotApplicable") + { + errors.Add(check.id + ": " + result.detail); + } + } + errors.AddRange(evidence.failures.Select(static fault => fault.stage + ": " + fault.detail)); + if (!evidence.completed) + { + errors.Add("Validation did not complete closing verification."); + } + if (errors.Count != 0) + { + throw new InvalidDataException(string.Join(Environment.NewLine, errors)); + } + return evidence.results; + } + + internal static ValidationResult[] Prerequisites( + ValidationPlan plan, + ValidationShard shard, + IReadOnlyList evidence + ) { + if (evidence.Count != shard.prerequisites.Length) + { + throw new InvalidDataException("The shard is missing prerequisites or received unrelated receipts."); + } + return shard.prerequisites.SelectMany(id => + { + ValidationEvidence[] matches = evidence.Where(receipt => receipt.shard == id).ToArray(); + if (matches.Length != 1) + { + throw new InvalidDataException("Missing or duplicate prerequisite shard: " + id); + } + return ValidateEvidence(plan, matches[0], id); + }).ToArray(); + } + + internal static ValidationEvidence Join( + ValidationPlan plan, + IReadOnlyList evidence + ) { + if (plan.shards is null || evidence.Count != plan.shards.Length) + { + throw new InvalidDataException("The required shard matrix is incomplete or duplicated."); + } + List results = []; + foreach (ValidationShard shard in plan.shards) + { + _ = Require(plan, shard.id); + ValidationEvidence[] matches = evidence.Where(receipt => receipt.shard == shard.id).ToArray(); + if (matches.Length != 1) + { + throw new InvalidDataException("Missing or duplicate execution shard: " + shard.id); + } + results.AddRange(ValidateEvidence(plan, matches[0], shard.id)); + } + + var joined = new ValidationEvidence( + plan.commit, + plan.tree, + plan.environment, + evidence.Min(static receipt => receipt.started), + results.ToArray(), + C_EVIDENCE_VERSION, + [], + ValidationInputs.PlanIdentity(plan), + completed: true + ); + _ = ValidateEvidence(plan, joined); + return joined; + } +} From 71992d96d08e1e79bbdd49cc3016a00328633daa Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sun, 22 Nov 2026 03:23:27 +0000 Subject: [PATCH 28/33] feat(tooling): check the file and type name rule F-02 The style engine reports a file that declares no type named like it, a primary type that is not first, and a second top-level type other than an enum, a delegate or a positional record. Whether a companion is used only by the primary type stays in review. --- .../decisions/CSHARP_STYLE_RULEBOOK.md | 5 +- .../StyleCommandTests.cs | 61 +++++++++++- .../Style/Rules/FileTypeNameStyleRule.cs | 92 +++++++++++++++++++ .../Style/StyleEngine.cs | 3 +- 4 files changed, 156 insertions(+), 5 deletions(-) create mode 100644 tools/Inno.Tooling.Architecture/Style/Rules/FileTypeNameStyleRule.cs diff --git a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md index 29188a42e..8c9754c98 100644 --- a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md +++ b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md @@ -50,7 +50,7 @@ The engine currently enforces these rules. A finding is reported under the first | Reported ID | Also covers | | --- | --- | -| F-01, F-03, F-04, F-05 | | +| F-01, F-02, F-03, F-04, F-05 | | | N-01, N-03, N-04, N-05 | N-06 | | NM-01 to NM-13 | | | T-01, T-02, T-03, T-04 | | @@ -67,12 +67,13 @@ The engine currently enforces these rules. A finding is reported under the first | E-01, E-03, E-04, E-05, E-06, E-07, E-08, E-09, E-10, E-11, E-12 | | | D-02, D-05, D-06 | D-04 | -Every other rule is not yet checked by the tool and is enforced in review: F-02, N-02, T-05, T-07, T-08, B-02, A-04, S-01, S-02, E-02, all X rules, D-03 and all TS rules. The compiler enforces D-01 through `CS1591`. The checks for N-05, E-04 and E-08 read syntax only: N-05 recognizes a qualified name by its root namespace, E-04 reports a negated `is null` and leaves `==` comparisons to review because an overloaded operator is not visible in syntax, and E-08 knows the members that the same type declaration declares. The naming check reads syntax only: it trusts the names of overrides, interface implementations, native interop declarations and serialized members, and it exempts test methods from the `Async` suffix. `.editorconfig` states the same naming table for editors. +Every other rule is not yet checked by the tool and is enforced in review: N-02, T-05, T-07, T-08, B-02, A-04, S-01, S-02, E-02, all X rules, D-03 and all TS rules. The compiler enforces D-01 through `CS1591`. The checks for N-05, E-04 and E-08 read syntax only: N-05 recognizes a qualified name by its root namespace, E-04 reports a negated `is null` and leaves `==` comparisons to review because an overloaded operator is not visible in syntax, and E-08 knows the members that the same type declaration declares. The naming check reads syntax only: it trusts the names of overrides, interface implementations, native interop declarations and serialized members, and it exempts test methods from the `Async` suffix. `.editorconfig` states the same naming table for editors. These checks read syntax only and report the part of a rule that syntax decides: | ID | Reported | Left to review | | --- | --- | --- | +| F-02 | A file that declares no type named like it, a primary type that is not first, and a second top-level type other than an enum, a delegate or a positional record. `Type.Part.cs` is named after `Type`. | Whether the companion is used only by the primary type. | | M-02 | A block body that is one `return`, call, assignment or `throw`; a constructor with an expression body. | A body that holds a comment or a directive. | | P-03 | A `CancellationToken` parameter of a declaration that is not named `cancellationToken`. | Its position in the list, and lambda parameters. | | W-04 | A line break directly before or after `=`; the fix joins the lines. | | diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs index 4e0d6c445..83d4c3713 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Text.RegularExpressions; using Xunit; namespace Inno.Tooling.Architecture.Tests; @@ -43,12 +44,16 @@ string text string root = CreateRoot(); try { - string path = Path.Combine(root, "src", "Probe.cs"); + string path = Path.Combine(root, "src", FirstTypeName(text) + ".cs"); + string report = Path.Combine(root, "report.tsv"); File.WriteAllText(path, text); Assert.Equal(0, StyleCommand.Execute(["check", root, "--rule", rule])); - Assert.Equal(0, StyleCommand.Execute(["fix", root])); + StyleCommand.Execute(["fix", root, "--report", report]); Assert.Equal(text, File.ReadAllText(path)); + + // A probe may declare several types to cover one rule; no other rule reports it. + Assert.All(File.ReadAllLines(report), static line => Assert.StartsWith("F-02\t", line, StringComparison.Ordinal)); } finally { @@ -128,6 +133,10 @@ string text )] [InlineData("M-02", "internal sealed class Probe\n{\n internal int Read()\n {\n return 1;\n }\n}")] [InlineData("M-02", "internal sealed class Probe\n{\n private int m_count;\n\n internal Probe() => m_count = 1;\n}")] + [InlineData("F-02", "internal sealed class Sample;")] + [InlineData("F-02", "internal enum ProbeKind\n{\n First\n}\n\ninternal sealed class Probe;")] + [InlineData("F-02", "internal sealed class Probe;\n\ninternal sealed class Sample;")] + [InlineData("F-02", "internal sealed class Probe;\n\ninternal sealed record ProbeOptions\n{\n internal int value { get; init; }\n}")] public void FindingsThatNeedTheAuthorAreReportedAndLeftUnchanged( string rule, string text @@ -221,6 +230,28 @@ public void ARuleFilterReportsOnlyTheRequestedRuleOfARuleFamily() } } + [Theory] + [InlineData("Probe.Observation.cs", "internal sealed partial class Probe;\n", 0)] + [InlineData("Probe.Observation.cs", "internal sealed partial class Observation;\n", 1)] + [InlineData("Usings.cs", "using System;\n", 0)] + public void APartFileIsNamedAfterTheTypeItExtends( + string name, + string text, + int expected + ) { + string root = CreateRoot(); + try + { + File.WriteAllText(Path.Combine(root, "src", name), text); + + Assert.Equal(expected, StyleCommand.Execute(["check", root, "--rule", "F-02"])); + } + finally + { + Directory.Delete(root, recursive: true); + } + } + [Fact] public void FixKeepsTextInsideMultiLineStrings() { @@ -1564,6 +1595,25 @@ internal int Read(string path) public static TheoryData Kept() => new() { + { + "F-02", + Source( + """ + internal sealed class Probe; + + internal sealed class Probe; + + internal enum ProbeKind + { + First + } + + internal delegate void ProbeChanged(ProbeKind kind); + + internal sealed record ProbeOptions(ProbeKind kind); + """ + ) + }, { "B-09", Source( @@ -2196,5 +2246,12 @@ private static string CreateRoot() return root; } + // Names the probe file after its first type, as F-02 requires. + private static string FirstTypeName(string text) + { + Match match = Regex.Match(text, @"\b(?:class|struct|interface|enum|record)\s+(?!struct\b|class\b)(\w+)"); + return match.Success ? match.Groups[1].Value : "Probe"; + } + private static string Source(string text) => text + "\n"; } diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/FileTypeNameStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/FileTypeNameStyleRule.cs new file mode 100644 index 000000000..cebd88a81 --- /dev/null +++ b/tools/Inno.Tooling.Architecture/Style/Rules/FileTypeNameStyleRule.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Inno.Tooling.Architecture; + +// F-02: a file is named after its primary type, which comes first. `Type.Part.cs` holds a part of `Type`. +// Another top-level type shares the file only when it is an enum, a delegate or a positional record. +// Whether that companion is used only by the primary type is left to review. +internal sealed class FileTypeNameStyleRule : StyleRule +{ + private const string C_ID = "F-02"; + + internal override string id => C_ID; + + internal override StyleRuleKind kind => StyleRuleKind.Rewrite; + + internal override void Check( + StyleSource source, + ICollection findings + ) { + List types = []; + Collect(((CompilationUnitSyntax)source.root).Members, types); + if (types.Count == 0) return; + + string stem = Path.GetFileNameWithoutExtension(source.path); + int separator = stem.IndexOf('.', StringComparison.Ordinal); + string primary = separator < 0 ? stem : stem[..separator]; + if (!types.Any(type => Name(type) == primary)) + { + findings.Add( + source.Finding( + C_ID, + types[0].SpanStart, + $"Name the file after its primary type. `{Path.GetFileName(source.path)}` declares no `{primary}`." + ) + ); + return; + } + + if (Name(types[0]) != primary) + { + findings.Add( + source.Finding( + C_ID, + types[0].SpanStart, + $"Put the primary type `{primary}` first. Found `{Name(types[0])}`." + ) + ); + } + + foreach (MemberDeclarationSyntax type in types) + { + if (Name(type) == primary || IsCompanion(type)) continue; + findings.Add( + source.Finding( + C_ID, + type.SpanStart, + $"Move `{Name(type)}` to its own file. Only an enum, a delegate or a positional record shares a file." + ) + ); + } + } + + private static void Collect( + SyntaxList members, + List types + ) { + foreach (MemberDeclarationSyntax member in members) + { + if (member is BaseNamespaceDeclarationSyntax scope) + { + Collect(scope.Members, types); + } + else if (member is BaseTypeDeclarationSyntax or DelegateDeclarationSyntax) + { + types.Add(member); + } + } + } + + private static string Name(MemberDeclarationSyntax type) + => type is DelegateDeclarationSyntax callback + ? callback.Identifier.ValueText + : ((BaseTypeDeclarationSyntax)type).Identifier.ValueText; + + private static bool IsCompanion(MemberDeclarationSyntax type) + => type is EnumDeclarationSyntax or DelegateDeclarationSyntax or RecordDeclarationSyntax { ParameterList: not null }; +} diff --git a/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs b/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs index 056d3b741..f14c6dc21 100644 --- a/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs +++ b/tools/Inno.Tooling.Architecture/Style/StyleEngine.cs @@ -80,7 +80,8 @@ internal static class StyleEngine new CancellationParameterStyleRule(), new ProhibitedTriviaStyleRule(), new StringBuildStyleRule(), - new ExpressionBodyStyleRule() + new ExpressionBodyStyleRule(), + new FileTypeNameStyleRule() ]; internal static IEnumerable EnumerateSources(string root) From 7ee69644991d3cab017eec1bdf64f8e9af9afaec Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sun, 22 Nov 2026 03:23:27 +0000 Subject: [PATCH 29/33] docs(rules): state the catch, blocking wait and record constructor boundaries X-04 allows a failure boundary to catch Exception when it records the failure. X-05 allows a blocking wait where a contract fixes a synchronous signature and requires tests to await. T-07 lets a record use an ordinary constructor when it validates or normalizes its arguments. --- .agents/rulebook/csharp-style/04-types.md | 2 +- .agents/rulebook/csharp-style/13-control-flow.md | 3 ++- .agents/rulebook/csharp-style/16-exceptions.md | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.agents/rulebook/csharp-style/04-types.md b/.agents/rulebook/csharp-style/04-types.md index c5cea11a2..3e4e32c8f 100644 --- a/.agents/rulebook/csharp-style/04-types.md +++ b/.agents/rulebook/csharp-style/04-types.md @@ -156,7 +156,7 @@ public abstract class EditorDrop ## T-07 Primary constructors -- A record always uses a primary constructor. +- A record uses a primary constructor. A record whose constructor validates or normalizes its arguments uses an ordinary constructor, and a record populated through `init` or `required` properties declares none. - A class or struct may use a primary constructor to receive its dependencies. When it does, it uses the parameters directly and does not copy them into `m_` fields. - Use an ordinary constructor with `m_` fields when arguments need validation or the fields must be `readonly`. - Primary constructor parameters follow P-01. A base list follows the closing parenthesis as `) : Base`, with the opening brace on its own line. Without a base list the type body starts with `) {`. diff --git a/.agents/rulebook/csharp-style/13-control-flow.md b/.agents/rulebook/csharp-style/13-control-flow.md index c7b2bde99..8e4fe0d4c 100644 --- a/.agents/rulebook/csharp-style/13-control-flow.md +++ b/.agents/rulebook/csharp-style/13-control-flow.md @@ -100,6 +100,7 @@ throw new Exception("bad version"); ## X-04 `catch` - Catch the specific type that can be handled. When catching `Exception`, filter with `when` or rethrow with `throw;` after handling. +- A handler at a failure boundary may catch `Exception` without a filter or a rethrow when it records the failure: it logs it, reports it as a diagnostic, stores it in a result or aggregates it for a later throw. - The variable is named `exception` by default. A name that states the role, such as `cleanupFailure`, is allowed when the exception is stored or aggregated. Omit the variable when it is not used. - A bare `catch` without a type is only for "clean up, then rethrow". - A `catch` block that deliberately ignores an exception contains a comment that says why. @@ -149,7 +150,7 @@ catch (Exception ex) - Return `Task` or `ValueTask`. Never write `async void`. - The method name ends with `Async` (NM-04). `CancellationToken cancellationToken` is the last parameter and is passed down to every asynchronous call. - In product code (`src`, `build`, `backends`, `platforms`, `tools`, `entry`) every `await` ends with `.ConfigureAwait(false)`. Test code does not use `ConfigureAwait`. -- Do not block on asynchronous results with `.Wait()`, `.Result` or `.GetAwaiter().GetResult()`. An entry point that must wait synchronously carries a comment that explains why. +- Do not block on asynchronous results with `.Wait()`, `.Result` or `.GetAwaiter().GetResult()`. A member whose synchronous signature is fixed by a contract may wait at that boundary (see Exceptions). Test code awaits instead: the test method returns `async Task`. - On a broken `await` call, `.ConfigureAwait(false)` follows the closing parenthesis on its line. ```csharp diff --git a/.agents/rulebook/csharp-style/16-exceptions.md b/.agents/rulebook/csharp-style/16-exceptions.md index 858bde8a1..d2696943f 100644 --- a/.agents/rulebook/csharp-style/16-exceptions.md +++ b/.agents/rulebook/csharp-style/16-exceptions.md @@ -21,6 +21,7 @@ The following cases follow an external contract. Do not rename or reformat them | Generator templates and their tests | `global::` and fully qualified names required by the generation protocol | | | Source text used as test data | Its own formatting (TS-03) | | | Serialized value types | Property setters that the serializer writes, so the record struct is not `readonly` (T-04) | `AssetPath`, `ShaderPropertyID` | +| Synchronous contract boundaries | A blocking wait on an asynchronous result inside a member whose synchronous signature is fixed (X-05) | MSBuild `Execute`, `Dispose`, `Main`, a synchronous interface member or public API over an asynchronous implementation | | Overloaded equality operators | `== null` and `!= null` where the type defines the result of the comparison (E-04) | `EngineObject`, whose destroyed instances compare equal to `null` | Keep each exception as small as possible: it covers the name or the layout bound by the contract, and the rest of the file follows the rulebook. From 3afa333f1b44548c1edb0e28e6e703854916d85e Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sun, 22 Nov 2026 03:23:27 +0000 Subject: [PATCH 30/33] chore(git): skip the file split commit in blame --- .git-blame-ignore-revs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 173b92727..a35fdd1eb 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -12,3 +12,5 @@ c46af2ba7e19ca3a69f2ab46bdb4aa8d17d70bec 49f33b29104df851a5ed5ad7cea453c68d527dc4 # Apply the remaining mechanical rulebook rules dce88f2ec6c70c91cdd7c9a9dcabd30e8d431a4d +# Keep one top-level type per file +840d139fa9e9be55c8d9c370caca105b22b96e2b From f296c4ab561f99eae8a92f4cc8e9132761c4c9d7 Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sun, 22 Nov 2026 04:10:11 +0000 Subject: [PATCH 31/33] style(csharp): put the cancellation token last Rule P-03. Move the `CancellationToken` parameter to the end of 28 declarations and reorder the arguments of their 147 call sites and the XML `` entries. A required token that precedes optional or `params` parameters stays where it is: it cannot move without gaining a default value. --- .../BgfxBuildSession.cs | 4 +-- .../Publishing/DotNetPublishExecutor.cs | 4 +-- .../ImGuiToolchain.cs | 4 +-- .../ImGuizmoToolchain.cs | 4 +-- .../MiniAudioToolchain.cs | 4 +-- .../Inno.Build.Toolchains.UI/UIToolchain.cs | 4 +-- .../Sdl3Toolchain.cs | 4 +-- .../TextToolchain.cs | 4 +-- .../Generation/BindingGenerationOperation.cs | 8 +++--- .../Identity/BindingInputPlanning.cs | 4 +-- .../NativeBindingGenerator.Inputs.cs | 2 +- build/cli/Inno.Build.Cli/BuildWorkspace.cs | 4 +-- .../Commands/NativeDependenciesCommand.cs | 6 +++- .../Commands/SupportPackCommand.cs | 4 +-- .../Player/PlayerSupportPackCatalog.cs | 10 +++---- .../SdkScriptCompilationEnvironment.cs | 4 +-- .../PlayerSupportPackPublisher.cs | 14 +++++----- .../SourcePlayerSupportPackProvisioner.cs | 4 +-- .../MaterializeBindingsTask.cs | 2 +- .../Inno.Build.Tasks/CompileShaderTask.cs | 8 +++--- .../PublishSupportPackTask.cs | 2 +- .../Cache/BuildArtifactReadLease.cs | 10 +++---- .../Cache/BuildCacheCleanupPlan.cs | 6 ++-- .../Cache/NativeArtifactTransfer.cs | 12 ++++---- .../NativeDependencyManifest.Aggregates.cs | 4 +-- .../Cache/NativeDependencyManifest.cs | 2 +- .../ManagedInputEvaluatorPreparation.cs | 4 +-- .../Managed/ManagedProjectGraphCapture.cs | 28 +++++++++---------- .../Native/NativeArtifactPublisher.cs | 10 +++---- .../Native/NativeCMakeExecutor.cs | 8 +++--- .../ToolchainEnvironment.cs | 28 +++++++++---------- .../BrowserWasm32NativeProductExecutor.cs | 8 +++--- .../Targets/MacOSArm64GameBuildTarget.cs | 12 ++++---- .../Targets/WindowsX64GameBuildTarget.cs | 12 ++++---- .../Samples/AssetSampleImportModule.cs | 4 +-- ...itorRenderTargetArtifactProvider.Drafts.cs | 4 +-- .../AnimationClipImporter.cs | 2 +- .../Artifacts/AssetArtifactWriter.cs | 10 +++---- .../Importers/BinaryAssetImporter.cs | 2 +- .../Importing/Importers/TextAssetImporter.cs | 2 +- .../Importing/Importing/AssetImportWriter.cs | 10 +++---- .../Runtime/AssetDatabase.Residency.cs | 22 +++++++-------- .../Importers/PrefabAssetImporter.cs | 2 +- .../Importers/SceneAssetImporter.cs | 2 +- .../core/Inno.Core.Execution/LifetimeScope.cs | 6 ++-- .../Importers/CSharpScriptImporter.cs | 6 ++-- .../ScriptAssemblyDefinitionImporter.cs | 2 +- .../Inno.Scripting.Compiler/ScriptCompiler.cs | 10 +++---- .../Inno.Scripting.Reload/ScriptReloadHost.cs | 2 +- .../Inno.Audio.Assets/AudioClipImporter.cs | 4 +-- .../Compilation/ShaderGraphArtifact.cs | 10 +++---- .../Importing/GeometryAssetImporter.cs | 4 +-- .../Importing/MaterialAssetImporter.cs | 2 +- .../Importing/RenderPipelineAssetImporter.cs | 2 +- .../Importing/ShaderAssetImporter.cs | 14 ++++++---- .../Importing/ShaderFunctionImporter.cs | 4 +-- .../Importing/TextureAssetImporter.cs | 4 +-- .../text/Inno.Text.Assets/FontImporter.cs | 4 +-- .../UIDocumentImportPipeline.cs | 2 +- .../AlternateDependencyAssetImporter.cs | 2 +- .../BuildConsumerAssetImporter.cs | 2 +- .../BuildInputAssetImporter.cs | 2 +- .../ConfiguredImporter.cs | 2 +- .../DeferredAssetImporter.cs | 2 +- .../DependencyAssetImporter.cs | 2 +- .../ExtensionConsumerImporter.cs | 2 +- .../ExtensionDependentImporter.cs | 2 +- .../HookAssetImporter.cs | 2 +- .../ImportGraphAssetImporter.cs | 2 +- .../ImporterConflictAssetImporterA.cs | 2 +- .../ImporterConflictAssetImporterB.cs | 2 +- .../MixedScopeAssetImporter.cs | 6 ++-- .../MutableAssetImporter.cs | 2 +- .../PrivateConstructorAssetImporter.cs | 2 +- .../SlowAssetImporter.cs | 2 +- .../TestBuildProcessor.cs | 2 +- .../DuplicateImporterA.cs | 2 +- .../DuplicateImporterB.cs | 2 +- .../BindingSelectionLifetimeTests.cs | 8 +++--- .../NativeBindingGenerationTests.cs | 4 +-- .../DevelopmentAppHostSdkTests.cs | 4 +-- .../ManagedOutputOwnershipTests.cs | 4 +-- .../SolutionBootstrapOwnershipTests.cs | 12 ++++---- .../TaskPublisherBootstrapTests.cs | 4 +-- .../StaticGraphRestoreTests.cs | 4 +-- .../SupportPackPublisherTests.cs | 12 ++++---- .../NativeArtifactImportTests.cs | 2 +- .../NativeArtifactPublicationTests.cs | 9 ++++-- .../NativeDependencyManifestTests.cs | 4 +-- .../NativeProductExecutorTests.cs | 4 +-- .../ProductNativeCacheLookupTests.cs | 2 +- .../ProductNativePreparationTests.cs | 2 +- .../BrowserDependencyConsumptionTests.cs | 4 +-- .../ControlledSampleAssetImporter.cs | 2 +- .../ScriptingFixture.cs | 2 +- .../ScriptingPipelineTests.cs | 12 ++++---- .../CSharp14ScriptingTests.cs | 8 +++--- .../ScriptCachePublicationTests.cs | 4 +-- .../ArchitectureOutputOwnerTests.cs | 2 +- .../ValidationCompletionTests.cs | 18 ++++++------ .../ValidationProgressTests.cs | 2 +- .../ValidationPlanningTests.cs | 2 +- .../ValidationRepository.cs | 8 +++--- .../ArchitectureValidator.cs | 4 +-- .../DocumentationExportPlan.cs | 2 +- .../DocumentationProjectReferences.cs | 4 +-- .../DocumentationReferences.cs | 2 +- .../DocumentationSourceModels.cs | 4 +-- .../MSBuildProjectGraphValidator.cs | 2 +- .../DocumentationCommand.cs | 4 +-- .../DocumentationStore.cs | 10 +++---- .../ValidationCommand.cs | 4 +-- .../ValidationPlanner.cs | 8 +++--- .../ValidationRunner.cs | 4 +-- 114 files changed, 315 insertions(+), 298 deletions(-) diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs index c0d2b632f..dec72545a 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx/BgfxBuildSession.cs @@ -65,7 +65,6 @@ await ToolchainEnvironment.RunAsync( ); } }, - cancellationToken, describeOutputs: ( @scoped, output @@ -75,7 +74,8 @@ await ToolchainEnvironment.RunAsync( file, includeTools ? NativeArtifactRole.SupportFile : NativeArtifactRole.SharedLibrary )) - .ToArray() + .ToArray(), + cancellationToken: cancellationToken ).ConfigureAwait(false); } diff --git a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs index 41bec1487..089ad6b91 100644 --- a/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs +++ b/backends/DotNet/build/Inno.Build.Managed.DotNet/Publishing/DotNetPublishExecutor.cs @@ -77,10 +77,10 @@ await ToolchainEnvironment.RunAsync( request.sdk.hostPath, arguments, workspace.toolPath, - cancellationToken, DotNetSdkEnvironment.Create(request.sdk.hostPath), output, - error + error, + cancellationToken ).ConfigureAwait(false); } catch (InvalidOperationException exception) diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs index 05dc88f2c..e6cf5b642 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGui/ImGuiToolchain.cs @@ -87,7 +87,6 @@ public static async Task BuildAsync( File.Copy(import, Path.Combine(link, Path.GetFileName(import))); } }, - cancellationToken, describeOutputs: static ( @scoped, output @@ -99,7 +98,8 @@ public static async Task BuildAsync( Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary - )).ToArray() + )).ToArray(), + cancellationToken: cancellationToken ).ConfigureAwait(false); } diff --git a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs index b17bfe478..c369b9dec 100644 --- a/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs +++ b/backends/ImGui/build/Inno.Build.Toolchains.ImGuizmo/ImGuizmoToolchain.cs @@ -94,7 +94,6 @@ public static async Task BuildAsync( File.Copy(library, Path.Combine(output, name)); token.ThrowIfCancellationRequested(); }, - cancellationToken, describeOutputs: static ( @scoped, output @@ -106,7 +105,8 @@ public static async Task BuildAsync( Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary - )).ToArray() + )).ToArray(), + cancellationToken: cancellationToken ).ConfigureAwait(false); } diff --git a/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs b/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs index fcd0c54fe..d3dead361 100644 --- a/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs +++ b/backends/MiniAudio/build/Inno.Build.Toolchains.MiniAudio/MiniAudioToolchain.cs @@ -77,7 +77,6 @@ public static async Task BuildAsync( string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); }, - cancellationToken, describeOutputs: static ( @scoped, output @@ -89,7 +88,8 @@ public static async Task BuildAsync( Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary - )).ToArray() + )).ToArray(), + cancellationToken: cancellationToken ).ConfigureAwait(false); } diff --git a/backends/RmlUi/build/Inno.Build.Toolchains.UI/UIToolchain.cs b/backends/RmlUi/build/Inno.Build.Toolchains.UI/UIToolchain.cs index 369ad7ecb..f85a7da48 100644 --- a/backends/RmlUi/build/Inno.Build.Toolchains.UI/UIToolchain.cs +++ b/backends/RmlUi/build/Inno.Build.Toolchains.UI/UIToolchain.cs @@ -82,7 +82,6 @@ public static async Task BuildAsync( string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); }, - cancellationToken, describeOutputs: static ( @scoped, output @@ -94,7 +93,8 @@ public static async Task BuildAsync( Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary - )).ToArray() + )).ToArray(), + cancellationToken: cancellationToken ).ConfigureAwait(false); } diff --git a/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs b/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs index 301f87a71..78075c0cb 100644 --- a/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs +++ b/backends/Sdl3/build/Inno.Build.Toolchains.Sdl3/Sdl3Toolchain.cs @@ -76,7 +76,6 @@ public static async Task BuildAsync( string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); }, - cancellationToken, describeOutputs: static ( @scoped, output @@ -88,7 +87,8 @@ public static async Task BuildAsync( Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary - )).ToArray() + )).ToArray(), + cancellationToken: cancellationToken ).ConfigureAwait(false); } diff --git a/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs b/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs index 7bac07adf..9bbf1b52b 100644 --- a/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs +++ b/backends/Text/build/Inno.Build.Toolchains.Text/TextToolchain.cs @@ -81,7 +81,6 @@ public static async Task BuildAsync( string name = ToolchainEnvironment.NormalizeOutputName(Path.GetFileName(library), scoped.configuration); File.Copy(library, Path.Combine(output, name)); }, - cancellationToken, describeOutputs: static ( @scoped, output @@ -93,7 +92,8 @@ public static async Task BuildAsync( Path.GetRelativePath(output, file).StartsWith("Link" + Path.DirectorySeparatorChar, StringComparison.Ordinal) ? NativeArtifactRole.ImportLibrary : NativeArtifactRole.SharedLibrary - )).ToArray() + )).ToArray(), + cancellationToken: cancellationToken ).ConfigureAwait(false); } diff --git a/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs b/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs index 4b03dfcfb..7ad569279 100644 --- a/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs +++ b/build/bindings/Inno.Build.Bindings/Generation/BindingGenerationOperation.cs @@ -138,8 +138,8 @@ await BuildArtifactReadLease.AcquireAsync( Path.Combine(m_context.engineRoot, "artifacts", "bindings"), fingerprint, ["Native", "Generated"], - cancellationToken, - m_context + m_context, + cancellationToken ).ConfigureAwait(false) ); protectedTargets.Add(destination); @@ -233,8 +233,8 @@ await BuildArtifactReadLease.AcquireAsync( Path.Combine(m_context.engineRoot, "artifacts", "bindings"), descriptor.fingerprint, ["Native", "Generated"], - cancellationToken, - m_context + m_context, + cancellationToken ).ConfigureAwait(false) ); } diff --git a/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs b/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs index 097de2b87..7f24ca081 100644 --- a/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs +++ b/build/bindings/Inno.Build.Bindings/Identity/BindingInputPlanning.cs @@ -11,8 +11,8 @@ internal static class BindingInputPlanning internal static ValueTask ComputeAsync( NativeBuildContext context, NativeBindingGenerationRequest request, - CancellationToken cancellationToken, - NativeBindingProfile profile + NativeBindingProfile profile, + CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(request); diff --git a/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs b/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs index ac73066e2..7e7537dea 100644 --- a/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs +++ b/build/bindings/Inno.Build.Bindings/NativeBindingGenerator.Inputs.cs @@ -17,5 +17,5 @@ public ValueTask ComputeInputFingerprintAsync( NativeBuildContext context, NativeBindingGenerationRequest request, CancellationToken cancellationToken - ) => BindingInputPlanning.ComputeAsync(context, request, cancellationToken, m_profile); + ) => BindingInputPlanning.ComputeAsync(context, request, m_profile, cancellationToken); } diff --git a/build/cli/Inno.Build.Cli/BuildWorkspace.cs b/build/cli/Inno.Build.Cli/BuildWorkspace.cs index 03e7f2ced..8c9059d73 100644 --- a/build/cli/Inno.Build.Cli/BuildWorkspace.cs +++ b/build/cli/Inno.Build.Cli/BuildWorkspace.cs @@ -86,8 +86,8 @@ CancellationToken cancellationToken ) => { ScriptCompilationResult result = await m_compiler.CompileAuthoringGenerationAsync( - cancellationToken: cancellationToken, - sourceSnapshot: sources + sourceSnapshot: sources, + cancellationToken: cancellationToken ).ConfigureAwait(false); if (!result.success) { diff --git a/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs b/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs index 02e2be1a8..4aa99ae29 100644 --- a/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/NativeDependenciesCommand.cs @@ -29,7 +29,11 @@ CancellationToken cancellationToken if (operation == "export-cache") { - await NativeArtifactTransfer.ExportAsync(request.root, options.Require("output"), cancellationToken).ConfigureAwait(false); + await NativeArtifactTransfer.ExportAsync( + request.root, + options.Require("output"), + cancellationToken: cancellationToken + ).ConfigureAwait(false); return; } diff --git a/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs b/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs index 8865985b6..a6d62c740 100644 --- a/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs +++ b/build/cli/Inno.Build.Cli/Commands/SupportPackCommand.cs @@ -21,8 +21,8 @@ CancellationToken cancellationToken output, context.target, context.composition.dotnetHost, - cancellationToken, - context.nativeDependencies.Length == 0 ? null : context.nativeDependencies + context.nativeDependencies.Length == 0 ? null : context.nativeDependencies, + cancellationToken ).ConfigureAwait(false); string archive = options.Read("archive", string.Empty); if (archive.Length != 0) diff --git a/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs b/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs index 261ab539e..413a0816c 100644 --- a/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs +++ b/build/pipeline/Inno.Build/Player/PlayerSupportPackCatalog.cs @@ -190,13 +190,13 @@ public PlayerSupportPackLease Acquire( /// /// The target validator for runtime and linker inputs. /// - /// - /// Cancels validation or lease acquisition before selecting the completed pack. - /// /// /// Optional final source-input gate after output validation and any publication wait. /// Omit only when the caller exclusively owns a fully prepared tree with no external preparation inputs. /// + /// + /// Cancels validation or lease acquisition before selecting the completed pack. + /// /// /// Reading ownership of the selected immutable pack; earlier readers retain their own protection. /// @@ -213,8 +213,8 @@ public async ValueTask PublishAsync( BuildTargetID target, string stagingDirectory, IPlayerSupportPackValidator validator, - CancellationToken cancellationToken = default, - Func? verifyInputs = null + Func? verifyInputs = null, + CancellationToken cancellationToken = default ) { ArgumentException.ThrowIfNullOrWhiteSpace(stagingDirectory); ArgumentNullException.ThrowIfNull(validator); diff --git a/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs b/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs index 023d91783..876d1eaab 100644 --- a/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs +++ b/build/pipeline/Inno.Build/Scripting/SdkScriptCompilationEnvironment.cs @@ -129,10 +129,10 @@ await ToolchainEnvironment.RunAsync( sdk.hostPath, arguments, directory, - cancellationToken, DotNetSdkEnvironment.Create(sdk.hostPath), output, - errors + errors, + cancellationToken ).ConfigureAwait(false); return output.ToString(); } diff --git a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs index 1efe96f9c..898159103 100644 --- a/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs +++ b/build/support/Inno.Build.SupportPacks.Core/PlayerSupportPackPublisher.cs @@ -55,12 +55,12 @@ public PlayerSupportPackPublisher(IEnumerable sources) /// /// The SDK executable selected by the host. /// - /// - /// Cancels preparation before directory installation begins. - /// /// /// An explicit native selection disabling third-party production, or null for local source preparation. /// + /// + /// Cancels preparation before directory installation begins. + /// /// /// Reading ownership of the selected Pack and any post-commit diagnostics. Dispose after consuming its files. /// @@ -88,8 +88,8 @@ public async ValueTask PublishAsync( string outputRoot, BuildTargetID target, string dotnetHost, - CancellationToken cancellationToken = default, - string? nativeDependencies = null + string? nativeDependencies = null, + CancellationToken cancellationToken = default ) { ArgumentException.ThrowIfNullOrWhiteSpace(engineRoot); ArgumentException.ThrowIfNullOrWhiteSpace(outputRoot); @@ -159,8 +159,8 @@ await plan.PrepareAsync(staging, cancellationToken) target, staging, source, - cancellationToken, - plan.VerifyInputsAsync + plan.VerifyInputsAsync, + cancellationToken ).ConfigureAwait(false); try { diff --git a/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs b/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs index 266c7f49c..1dab53dc2 100644 --- a/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs +++ b/build/support/Inno.Build.SupportPacks.Core/SourcePlayerSupportPackProvisioner.cs @@ -89,8 +89,8 @@ public async ValueTask ProvisionAsync( supportPackRoot, target, m_dotnetHost, - cancellationToken, - m_nativeDependencies + m_nativeDependencies, + cancellationToken ).ConfigureAwait(false); foreach (string diagnostic in installed.diagnostics) { diff --git a/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs b/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs index 17b0e4021..e829cbf31 100644 --- a/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs +++ b/build/tasks/Inno.Build.TaskHosting/MaterializeBindingsTask.cs @@ -161,7 +161,7 @@ CancellationToken cancellationToken throw new ArgumentException("The selected source is outside its declared binding artifact."); } return BuildArtifactReadLease - .AcquireAsync(directory, ArtifactOwnerDirectory, Fingerprint, ["Native", "Generated"], cancellationToken) + .AcquireAsync(directory, ArtifactOwnerDirectory, Fingerprint, ["Native", "Generated"], cancellationToken: cancellationToken) .AsTask() .GetAwaiter() .GetResult(); diff --git a/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs b/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs index a05ef8c57..d43d5702f 100644 --- a/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs +++ b/build/tasks/Inno.Build.Tasks/CompileShaderTask.cs @@ -105,7 +105,7 @@ public override bool Execute() { throw new ArgumentException("The shader platform or rendering API is invalid."); } - ToolRunner tools = PrepareTools(cancellation.Token, out string compilerFingerprint, out BuildArtifactReadLease toolLease); + ToolRunner tools = PrepareTools(out string compilerFingerprint, out BuildArtifactReadLease toolLease, cancellation.Token); using BuildArtifactReadLease toolOwnership = toolLease; CompileProduct(tools, compilerFingerprint, platform, renderer, cancellation.Token); return true; @@ -137,9 +137,9 @@ public void Cancel() } private ToolRunner PrepareTools( - CancellationToken cancellationToken, out string compilerFingerprint, - out BuildArtifactReadLease reading + out BuildArtifactReadLease reading, + CancellationToken cancellationToken ) { var context = new NativeBuildContext(EngineRoot, "release"); BuildCompositionContext execution = StandardBuildEnvironment.Capture(AppContext.BaseDirectory, new BuildTargetID(ToolTarget)); @@ -235,7 +235,7 @@ record = [product.directory, product.fingerprint, .. product.files]; Path.Combine(EngineRoot, "artifacts", "native"), record[1], ["Outputs", "Metadata"], - cancellationToken + cancellationToken: cancellationToken ) .AsTask() .GetAwaiter() diff --git a/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs b/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs index 029ee3c88..dbac74d23 100644 --- a/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs +++ b/build/tasks/Inno.Build.Tasks/PublishSupportPackTask.cs @@ -77,7 +77,7 @@ public override bool Execute() execution.toolsTarget ); using PlayerSupportPackPublication installed = StandardBuildDistribution.Create(context).build.supportPacks - .PublishAsync(EngineRoot, OutputRoot, new BuildTargetID(Target), DotnetHost, cancellation.Token) + .PublishAsync(EngineRoot, OutputRoot, new BuildTargetID(Target), DotnetHost, cancellationToken: cancellation.Token) .AsTask() .GetAwaiter() .GetResult(); diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs index 26522b867..0241936b6 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildArtifactReadLease.cs @@ -39,12 +39,12 @@ private BuildArtifactReadLease(CoordinatedFileLease lease) /// /// The complete relative output roots declared by the publisher. /// - /// - /// Cancels ownership acquisition without releasing another reader's protection. - /// /// /// Optional borrowed operation receiving output-integrity read statistics; its input cache is not used. /// + /// + /// Cancels ownership acquisition without releasing another reader's protection. + /// /// /// Reading ownership which the caller must retain until all artifact access completes. /// @@ -65,8 +65,8 @@ public static async ValueTask AcquireAsync( string ownerDirectory, string fingerprint, IReadOnlyList outputDirectories, - CancellationToken cancellationToken = default, - NativeBuildContext? statistics = null + NativeBuildContext? statistics = null, + CancellationToken cancellationToken = default ) => await TryAcquireAsync( directory, ownerDirectory, diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs index 606ef61f9..266a44193 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/BuildCacheCleanupPlan.cs @@ -161,7 +161,7 @@ public static BuildCacheCleanupPlan Create( Stopwatch elapsed = Stopwatch.StartNew(); try { - BuildCacheCleanupPlan plan = CreateCore(workspace, owners, policy, retireAll, targetID, bounded.Token, elapsed); + BuildCacheCleanupPlan plan = CreateCore(workspace, owners, policy, retireAll, targetID, elapsed, bounded.Token); if (elapsed.Elapsed >= policy.timeBudget) { throw new TimeoutException("Cache inventory exceeded its operation time budget; no artifact was retired."); @@ -204,8 +204,8 @@ private static BuildCacheCleanupPlan CreateCore( BuildCachePolicy policy, bool retireAll, string? targetID, - CancellationToken cancellationToken, - Stopwatch elapsed + Stopwatch elapsed, + CancellationToken cancellationToken ) { ArgumentException.ThrowIfNullOrWhiteSpace(workspace); ArgumentNullException.ThrowIfNull(owners); diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs index 2b2cdce75..06d59df50 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeArtifactTransfer.cs @@ -23,12 +23,12 @@ public static class NativeArtifactTransfer /// /// The explicit transport file, atomically replaced after complete export. /// - /// - /// Cancels copying before the completed archive replaces its previous version. - /// /// /// Optional exact artifact paths relative to the artifacts root. Every selected generation must be exported. /// + /// + /// Cancels copying before the completed archive replaces its previous version. + /// /// /// The number of verified generations exported. /// @@ -41,8 +41,8 @@ public static class NativeArtifactTransfer public static async Task ExportAsync( string engineRoot, string archivePath, - CancellationToken cancellationToken = default, - IReadOnlySet? selectedArtifacts = null + IReadOnlySet? selectedArtifacts = null, + CancellationToken cancellationToken = default ) { string root = Path.GetFullPath(engineRoot); string destination = PathBoundary.RequireUnlinkedPath(root, Path.GetFullPath(archivePath)); @@ -85,7 +85,7 @@ public static async Task ExportAsync( owner.directory, parts[3], OutputRoots(parts[0]), - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); foreach (string file in PathBoundary.EnumerateFiles(artifact.directory).Order(StringComparer.Ordinal)) { diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs index ba7167ea1..16c67fd42 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.Aggregates.cs @@ -85,7 +85,7 @@ CancellationToken cancellationToken Directory.CreateDirectory(output); string assetName = product.component + "-" + product.targetID + "-" + product.fingerprint + ".zip"; string archive = Path.Combine(output, assetName); - await NativeArtifactTransfer.ExportAsync(context.engineRoot, archive, cancellationToken, directories).ConfigureAwait(false); + await NativeArtifactTransfer.ExportAsync(context.engineRoot, archive, directories, cancellationToken).ConfigureAwait(false); using FileStream payload = File.OpenRead(archive); string hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellationToken).ConfigureAwait(false)); string revision = (await ToolchainEnvironment.CaptureOutputAsync( @@ -255,7 +255,7 @@ string[] dependencies owner, fingerprint, outputs, - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); try { diff --git a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs index 5d7908f98..be98fd01d 100644 --- a/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs +++ b/build/toolchains/Inno.Build.Toolchains/Cache/NativeDependencyManifest.cs @@ -278,7 +278,7 @@ await bindingContext string asset = step.id + "-" + product.targetID + "-" + product.fingerprint + ".zip"; string archive = Path.Combine(output, asset); - await NativeArtifactTransfer.ExportAsync(root, archive, cancellationToken, selected).ConfigureAwait(false); + await NativeArtifactTransfer.ExportAsync(root, archive, selected, cancellationToken).ConfigureAwait(false); using FileStream payload = File.OpenRead(archive); string digest = Convert.ToHexStringLower(await SHA256.HashDataAsync(payload, cancellationToken).ConfigureAwait(false)); assets.Add( diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs index 51ea1c4db..4f77a3f0f 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedInputEvaluatorPreparation.cs @@ -186,8 +186,8 @@ await ToolchainEnvironment.RunAsync( Path.GetDirectoryName(directory)!, fingerprint, ["Outputs"], - cancellationToken, - context + context, + cancellationToken ).ConfigureAwait(false); try { diff --git a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs index 3d9abe9cf..3296f50d7 100644 --- a/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs +++ b/build/toolchains/Inno.Build.Toolchains/Managed/ManagedProjectGraphCapture.cs @@ -29,12 +29,12 @@ public static class ManagedProjectGraphCapture /// /// The complete evaluation properties, including configuration and any explicit output owner. /// - /// - /// Cancels preparation or evaluation and drains child processes before releasing owners. - /// /// /// Resolves compile references and implicit symbols after restore without building project references or native products. /// + /// + /// Cancels preparation or evaluation and drains child processes before releasing owners. + /// /// /// A JSON array of SDK snapshots. An empty request or failed evaluation throws instead of returning partial evidence. /// @@ -55,8 +55,8 @@ public static async Task CaptureAsync( string dotnetHost, IReadOnlyList projects, IReadOnlyDictionary properties, - CancellationToken cancellationToken = default, - bool resolveReferences = false + bool resolveReferences = false, + CancellationToken cancellationToken = default ) { ValidateProjects(projects, properties); DotNetSdkDescriptor sdk = await DotNetSdkResolver.ResolveDirectoryAsync( @@ -64,7 +64,7 @@ public static async Task CaptureAsync( engineRoot, cancellationToken ).ConfigureAwait(false); - return await EvaluateAsync(engineRoot, sdk, projects, properties, cancellationToken, resolveReferences).ConfigureAwait(false); + return await EvaluateAsync(engineRoot, sdk, projects, properties, resolveReferences, cancellationToken).ConfigureAwait(false); } /// @@ -82,12 +82,12 @@ public static async Task CaptureAsync( /// /// The complete evaluation properties, including configuration and any explicit output owner. /// - /// - /// Cancels preparation or evaluation and drains child processes before releasing owners. - /// /// /// Resolves compile references and implicit symbols after restore without building project references or native products. /// + /// + /// Cancels preparation or evaluation and drains child processes before releasing owners. + /// /// /// A JSON array of SDK snapshots. An empty request or failed evaluation throws instead of returning partial evidence. /// @@ -108,12 +108,12 @@ public static async Task CaptureSelectedAsync( DotNetSdkDescriptor sdk, IReadOnlyList projects, IReadOnlyDictionary properties, - CancellationToken cancellationToken = default, - bool resolveReferences = false + bool resolveReferences = false, + CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(sdk); ValidateProjects(projects, properties); - return await EvaluateAsync(engineRoot, sdk, projects, properties, cancellationToken, resolveReferences).ConfigureAwait(false); + return await EvaluateAsync(engineRoot, sdk, projects, properties, resolveReferences, cancellationToken).ConfigureAwait(false); } private static void ValidateProjects( @@ -140,8 +140,8 @@ private static async Task EvaluateAsync( DotNetSdkDescriptor sdk, IReadOnlyList projects, IReadOnlyDictionary properties, - CancellationToken cancellationToken, - bool resolveReferences + bool resolveReferences, + CancellationToken cancellationToken ) { var context = new NativeBuildContext(engineRoot, "debug"); using ManagedInputEvaluatorPreparation.Result evaluator = await ManagedInputEvaluatorPreparation.PrepareAsync( diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs index c1058f8dd..8b3ced933 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeArtifactPublisher.cs @@ -27,12 +27,12 @@ public static class NativeArtifactPublisher /// Producer receiving an identity-scoped context, private output directory and cancellation token. /// It must await all work and validate required outputs before returning. /// - /// - /// Cancels ownership acquisition or candidate preparation before publication. - /// /// /// The producer's exact role inventory, or null for generic support payloads. /// + /// + /// Cancels ownership acquisition or candidate preparation before publication. + /// /// /// A complete native product with an exact, read-only output closure. /// @@ -52,8 +52,8 @@ public static async Task PublishAsync( NativeBuildContext context, NativeBuildRecipe recipe, Func build, - CancellationToken cancellationToken = default, - Func>? describeOutputs = null + Func>? describeOutputs = null, + CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(recipe); diff --git a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs index 3ff5d212d..63938afcd 100644 --- a/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs +++ b/build/toolchains/Inno.Build.Toolchains/Native/NativeCMakeExecutor.cs @@ -156,8 +156,8 @@ await ToolchainEnvironment.RunAsync( selection.ResolveExecutable("cmake"), configure, sources.root, - cancellationToken, - environment + environment, + cancellationToken ).ConfigureAwait(false); List build = ["--build", buildDirectory, "--config", buildType]; if (target is not null) @@ -169,8 +169,8 @@ await ToolchainEnvironment.RunAsync( selection.ResolveExecutable("cmake"), build, sources.root, - cancellationToken, - environment + environment, + cancellationToken ).ConfigureAwait(false); return buildDirectory; } diff --git a/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs b/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs index 22fd1417d..4baf5b4e9 100644 --- a/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs +++ b/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs @@ -175,7 +175,7 @@ public static Task RunAsync( string workingDirectory, CancellationToken cancellationToken, IReadOnlyDictionary? environment = null - ) => RunCoreAsync(fileName, arguments, workingDirectory, cancellationToken, environment, Console.Out); + ) => RunCoreAsync(fileName, arguments, workingDirectory, environment, Console.Out, cancellationToken); /// /// Executes a declared absolute tool with an explicitly resolved SDK environment and records the operation cost. @@ -192,12 +192,12 @@ public static Task RunAsync( /// /// The owned source or intermediate directory. /// - /// - /// Cancels execution and drains the complete process tree. - /// /// /// The frozen environment supplied by the selected SDK resolver. /// + /// + /// Cancels execution and drains the complete process tree. + /// /// /// Completion after successful exit and output delivery. /// @@ -215,8 +215,8 @@ public static Task RunAsync( string fileName, IReadOnlyList arguments, string workingDirectory, - CancellationToken cancellationToken, - IReadOnlyDictionary environment + IReadOnlyDictionary environment, + CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(environment); @@ -240,9 +240,6 @@ IReadOnlyDictionary environment /// /// The project directory controlling SDK and workload resolution. /// - /// - /// Cancels the complete process tree and drains both output streams. - /// /// /// Optional child-only toolchain variables. Null values remove inherited variables; /// empty values remain explicitly empty. @@ -253,6 +250,9 @@ IReadOnlyDictionary environment /// /// The caller-owned standard error destination; the runner does not dispose it. /// + /// + /// Cancels the complete process tree and drains both output streams. + /// /// /// Completion after successful exit and complete output delivery; failures propagate. /// @@ -269,10 +269,10 @@ public static Task RunAsync( string fileName, IReadOnlyList arguments, string workingDirectory, - CancellationToken cancellationToken, IReadOnlyDictionary? environment, TextWriter standardOutput, - TextWriter standardError + TextWriter standardError, + CancellationToken cancellationToken ) { ArgumentNullException.ThrowIfNull(standardOutput); ArgumentNullException.ThrowIfNull(standardError); @@ -391,7 +391,7 @@ public static async Task CaptureOutputAsync( using var output = new StringWriter(); try { - await RunCoreAsync(fileName, arguments, workingDirectory, cancellationToken, environment, output).ConfigureAwait(false); + await RunCoreAsync(fileName, arguments, workingDirectory, environment, output, cancellationToken).ConfigureAwait(false); } catch (InvalidOperationException failure) { @@ -546,9 +546,9 @@ private static async Task RunCoreAsync( string fileName, IReadOnlyList arguments, string workingDirectory, - CancellationToken cancellationToken, IReadOnlyDictionary? environment, - TextWriter standardOutput + TextWriter standardOutput, + CancellationToken cancellationToken ) { var start = new ProcessStartInfo(fileName) { WorkingDirectory = workingDirectory }; foreach (string argument in arguments) diff --git a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs index 256521123..9ad52abcb 100644 --- a/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs +++ b/platforms/BrowserWasm32/build/Inno.Build.BrowserWasm32/Native/BrowserWasm32NativeProductExecutor.cs @@ -163,8 +163,8 @@ await ToolchainEnvironment.RunAsync( tools.ResolveExecutable("cmake"), ["--install", build, "--component", "Inno"], scoped.engineRoot, - token, - tools.environment + tools.environment, + token ).ConfigureAwait(false); ValidateNativeOutputs(output, tools.targetID, plan); NativeBindingGenerationDescriptor.WriteSelection( @@ -178,7 +178,6 @@ await ToolchainEnvironment.RunAsync( ) ); }, - cancellationToken, describeOutputs: static ( @scoped, output @@ -188,7 +187,8 @@ await ToolchainEnvironment.RunAsync( file, Path.GetExtension(file) == ".a" ? NativeArtifactRole.StaticArchive : NativeArtifactRole.SupportFile )) - .ToArray() + .ToArray(), + cancellationToken: cancellationToken ).ConfigureAwait(false); return new ProductNativeBuildResult([product], generations, Path.Combine(product.directory, "Outputs"), recipe); } diff --git a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs index 194555902..9d1352ea6 100644 --- a/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs +++ b/platforms/MacOSArm64/build/Inno.Build.MacOSArm64/Targets/MacOSArm64GameBuildTarget.cs @@ -80,8 +80,8 @@ public async ValueTask PackageAsync( await CopyDirectoryAsync( context.managedDeployment.outputDirectory, executableRoot, - cancellationToken, - excludeCompilerReferences: true + excludeCompilerReferences: true, + cancellationToken: cancellationToken ) .ConfigureAwait(false); string player = Path.Combine(executableRoot, "Inno.Player.MacOSArm64"); @@ -93,8 +93,8 @@ await CopyDirectoryAsync( await CopyDirectoryAsync( context.contentDirectory, Path.Combine(resources, "Content"), - cancellationToken, - excludeCompilerReferences: false + excludeCompilerReferences: false, + cancellationToken: cancellationToken ) .ConfigureAwait(false); Directory.CreateDirectory(contents); @@ -123,8 +123,8 @@ await File private static async ValueTask CopyDirectoryAsync( string source, string destination, - CancellationToken cancellationToken, - bool excludeCompilerReferences + bool excludeCompilerReferences, + CancellationToken cancellationToken ) { Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) diff --git a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs index ee55cbabc..8b2ddde16 100644 --- a/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs +++ b/platforms/WindowsX64/build/Inno.Build.WindowsX64/Targets/WindowsX64GameBuildTarget.cs @@ -76,8 +76,8 @@ public async ValueTask PackageAsync( await CopyDirectoryAsync( context.managedDeployment.outputDirectory, application, - cancellationToken, - excludeCompilerReferences: true + excludeCompilerReferences: true, + cancellationToken: cancellationToken ).ConfigureAwait(false); string player = Path.Combine(application, "Inno.Player.WindowsX64.exe"); if (!File.Exists(player)) @@ -88,8 +88,8 @@ await CopyDirectoryAsync( await CopyDirectoryAsync( context.contentDirectory, Path.Combine(application, "Content"), - cancellationToken, - excludeCompilerReferences: false + excludeCompilerReferences: false, + cancellationToken: cancellationToken ) .ConfigureAwait(false); return application; @@ -98,8 +98,8 @@ await CopyDirectoryAsync( private static async ValueTask CopyDirectoryAsync( string source, string destination, - CancellationToken cancellationToken, - bool excludeCompilerReferences + bool excludeCompilerReferences, + CancellationToken cancellationToken ) { Directory.CreateDirectory(destination); foreach (string directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) diff --git a/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs b/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs index eca6a6680..176ab915f 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/Samples/AssetSampleImportModule.cs @@ -154,8 +154,8 @@ protected override void OnUpdate(EditorContext context) { ScriptCompilationResult result = await m_compiler.CompileAuthoringGenerationAsync( new ImportProgress(this, operation), - cancellationToken, - sources + sources, + cancellationToken ).ConfigureAwait(false); if (!result.success) { diff --git a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs index e4695ceec..5cc542ac9 100644 --- a/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs +++ b/src/composition/editor/features/Inno.Editor.Rendering/Compilation/EditorRenderTargetArtifactProvider.Drafts.cs @@ -74,7 +74,6 @@ GraphicsCapabilities capabilities using ArtifactLease lease = m_assets.AcquireArtifact(id, ShaderSourceBundle.C_OUTPUT_NAME); return lease.ReadAllBytes(); }, - m_lifetime.Token, ( id, _ @@ -85,7 +84,8 @@ GraphicsCapabilities capabilities throw new InvalidDataException($"Shader graph node '{id}' has no current successful import."); } return ShaderGraphArtifact.ReadDocument(ShaderGraphArtifact.Read(node, m_assets), m_serialization); - } + }, + m_lifetime.Token ); string hash = ShaderGraphArtifact.GetSemanticHash(captured, m_serialization); if (environmentChanged || entry.semanticHash != hash) diff --git a/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs b/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs index 574408bf5..551b23f2f 100644 --- a/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs +++ b/src/content/animation/Inno.Animation.Assets/AnimationClipImporter.cs @@ -52,7 +52,7 @@ CancellationToken cancellationToken }; clip.Validate(); output.SetAsset(clip); - await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); } /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs index e3a58dcf5..bae2444be 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Artifacts/AssetArtifactWriter.cs @@ -24,20 +24,20 @@ public sealed class AssetArtifactWriter /// /// The output content. /// - /// - /// Cancellation for the write operation. - /// /// /// Whether runtime packages retain this output. /// + /// + /// Cancellation for the write operation. + /// /// /// A completed operation after the output has been staged. /// public ValueTask WriteAsync( string outputName, ReadOnlyMemory bytes, - CancellationToken cancellationToken = default, - AssetDeploymentScope deploymentScope = AssetDeploymentScope.Runtime + AssetDeploymentScope deploymentScope = AssetDeploymentScope.Runtime, + CancellationToken cancellationToken = default ) { cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(outputName)) diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs index a96eebf89..aa1280d61 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/BinaryAssetImporter.cs @@ -38,7 +38,7 @@ CancellationToken cancellationToken byte[] payload = context.sourceBytes.ToArray(); var asset = new BinaryAsset(payload.Length); output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", payload, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", payload, cancellationToken: cancellationToken).ConfigureAwait(false); } /// diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs index e1241a73a..ad7568f62 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Importers/TextAssetImporter.cs @@ -53,7 +53,7 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", Encoding.UTF8.GetBytes(content), - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs index 78100419b..2c611ec39 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Importing/AssetImportWriter.cs @@ -80,20 +80,20 @@ public void SetAsset(TAsset asset) /// /// The output content. /// - /// - /// Cancellation for the write operation. - /// /// /// Whether this output is retained in runtime packages. Runtime payload and asset state cannot be authoring-only. /// + /// + /// Cancellation for the write operation. + /// /// /// A completed operation after the output has been staged. /// public ValueTask WriteArtifactAsync( string outputName, ReadOnlyMemory bytes, - CancellationToken cancellationToken = default, - AssetDeploymentScope deploymentScope = AssetDeploymentScope.Runtime + AssetDeploymentScope deploymentScope = AssetDeploymentScope.Runtime, + CancellationToken cancellationToken = default ) { cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(outputName)) diff --git a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs index cacfa67e1..3d42989d0 100644 --- a/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs +++ b/src/content/assets/Inno.Assets/Runtime/AssetDatabase.Residency.cs @@ -176,7 +176,6 @@ CancellationToken cancellationToken m_pendingLoads.Add( new PendingAcquisition( shared.preparation, - cancellationToken, payloads => { TAsset asset = LoadRecord(record, pin: false, payloads); @@ -187,7 +186,8 @@ CancellationToken cancellationToken () => completion.TrySetCanceled( cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true) ), - () => ReleasePreparation(record.persistentID, shared) + () => ReleasePreparation(record.persistentID, shared), + cancellationToken ) ); m_peakPendingLoads = Math.Max(m_peakPendingLoads, m_pendingLoads.Count); @@ -290,8 +290,8 @@ private void EnsureResidencyOwner() private static async Task ReadPayloadAsync( PayloadRead read, ContentReadLease lease, - CancellationToken cancellationToken, - SemaphoreSlim slots + SemaphoreSlim slots, + CancellationToken cancellationToken ) { await slots.WaitAsync(cancellationToken).ConfigureAwait(false); try @@ -368,13 +368,13 @@ SemaphoreSlim slots { if (ExecutionContext.IsFlowSuppressed()) { - this.preparation = Task.Run(() => PrepareAsync(read, lease, cancellation.Token, slots)); + this.preparation = Task.Run(() => PrepareAsync(read, lease, slots, cancellation.Token)); } else { using (ExecutionContext.SuppressFlow()) { - this.preparation = Task.Run(() => PrepareAsync(read, lease, cancellation.Token, slots)); + this.preparation = Task.Run(() => PrepareAsync(read, lease, slots, cancellation.Token)); } } } @@ -394,23 +394,23 @@ SemaphoreSlim slots private static async Task PrepareAsync( PayloadRead read, ContentReadLease lease, - CancellationToken cancellationToken, - SemaphoreSlim slots + SemaphoreSlim slots, + CancellationToken cancellationToken ) { using (lease) { - return await ReadPayloadAsync(read, lease, cancellationToken, slots).ConfigureAwait(false); + return await ReadPayloadAsync(read, lease, slots, cancellationToken).ConfigureAwait(false); } } } private sealed class PendingAcquisition( Task> preparation, - CancellationToken cancellationToken, Action> publish, Action fail, Action cancel, - Action release + Action release, + CancellationToken cancellationToken ) { internal Task> preparation { get; } = preparation; diff --git a/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs b/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs index 5a74666c5..45984b8b3 100644 --- a/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs +++ b/src/content/scene/Inno.Scene.Assets/Importers/PrefabAssetImporter.cs @@ -53,7 +53,7 @@ CancellationToken cancellationToken output.DependsOnAsset(dependencies[i]); } output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", envelope.payload, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", envelope.payload, cancellationToken: cancellationToken).ConfigureAwait(false); } /// diff --git a/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs b/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs index 004f428ab..e9832d483 100644 --- a/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs +++ b/src/content/scene/Inno.Scene.Assets/Importers/SceneAssetImporter.cs @@ -53,7 +53,7 @@ CancellationToken cancellationToken output.DependsOnAsset(dependencies[i]); } output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", envelope.payload, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", envelope.payload, cancellationToken: cancellationToken).ConfigureAwait(false); } /// diff --git a/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs b/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs index c089fbeb4..53d452a44 100644 --- a/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs +++ b/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs @@ -172,7 +172,7 @@ public Task RunAsync( ArgumentNullException.ThrowIfNull(operation); var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); TrackCore(completion.Task, observeCompletion: false); - _ = CompleteOperationAsync(operation, cancellationToken, completion); + _ = CompleteOperationAsync(operation, completion, cancellationToken); return completion.Task; } @@ -465,8 +465,8 @@ private void EnsureAccepting() private async Task CompleteOperationAsync( Func> operation, - CancellationToken cancellationToken, - TaskCompletionSource completion + TaskCompletionSource completion, + CancellationToken cancellationToken ) { try { diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs index 8d05d964c..90fd1e906 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/CSharpScriptImporter.cs @@ -76,12 +76,12 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "source", Encoding.UTF8.GetBytes(source), - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); await output.WriteArtifactAsync( "diagnostics", Encoding.UTF8.GetBytes(string.Join(Environment.NewLine, diagnostics)), - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); var typeManifest = new ScriptSourceTypeManifest( context.persistentID, @@ -91,7 +91,7 @@ await output.WriteArtifactAsync( await output.WriteArtifactAsync( "type-manifest", context.serialization.Serialize(typeManifest), - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs index baf602b60..a7a4250a1 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/Importers/ScriptAssemblyDefinitionImporter.cs @@ -58,7 +58,7 @@ out IReadOnlyList dependencies throw new InvalidOperationException("Assembly definition scope must be Runtime or Editor."); } output.SetAsset(asset); - await output.WriteArtifactAsync("source", context.sourceBytes, cancellationToken) + await output.WriteArtifactAsync("source", context.sourceBytes, cancellationToken: cancellationToken) .ConfigureAwait(false); } diff --git a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs index 7178ad991..912c7fd90 100644 --- a/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs +++ b/src/runtime/scripting/Inno.Scripting.Compiler/ScriptCompiler.cs @@ -71,13 +71,13 @@ PluginEnvironment plugins /// /// Optional observer for monotonic compiler progress. /// - /// - /// The token that cancels compilation before an artifact generation is committed. - /// /// /// Optional isolated authoring sources. Capture on its owner thread and keep its transaction /// alive until compilation drains; null selects the current Plugin candidate or active sources. /// + /// + /// The token that cancels compilation before an artifact generation is committed. + /// /// /// The immutable diagnostics and artifacts produced by the compilation attempt. /// @@ -102,8 +102,8 @@ PluginEnvironment plugins /// public ValueTask CompileAuthoringGenerationAsync( IProgress? progress = null, - CancellationToken cancellationToken = default, - IAssetSourceSnapshot? sourceSnapshot = null + IAssetSourceSnapshot? sourceSnapshot = null, + CancellationToken cancellationToken = default ) => ScriptCompilerEngine.CompileAsync( m_options, m_assets, diff --git a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs index 038128ef4..84ae18cb0 100644 --- a/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs +++ b/src/runtime/scripting/Inno.Scripting.Reload/ScriptReloadHost.cs @@ -680,7 +680,7 @@ private async ValueTask CompileAsync( operation, isCompilerUpdate: true )), - effectiveCancellation + cancellationToken: effectiveCancellation ) .ConfigureAwait(false); } diff --git a/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs b/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs index 00740e02f..dddf87640 100644 --- a/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs +++ b/src/services/audio/Inno.Audio.Assets/AudioClipImporter.cs @@ -50,9 +50,9 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", AudioClipMetadataCodec.Encode(metadata), - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); - await output.WriteArtifactAsync("audio-data", context.sourceBytes, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("audio-data", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); } private static AudioClipMetadata ReadWav(ReadOnlySpan bytes) diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs index f0edfe18d..58d945b78 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Compilation/ShaderGraphArtifact.cs @@ -42,12 +42,12 @@ public static partial class ShaderGraphArtifact /// /// Reads an immutable function bundle by stable identity and diagnostic last-known path. /// - /// - /// Cancellation before node expansion, target expansion and dependency reads. - /// /// /// Reads an authored Shader graph used as a reusable node, when the graph contains one. /// + /// + /// Cancellation before node expansion, target expansion and dependency reads. + /// /// /// Native immutable authoring artifact bytes usable by import or isolated preview compilation. /// @@ -57,8 +57,8 @@ public static byte[] Capture( SerializationRegistry serialization, SerializationContext context, Func readSource, - CancellationToken cancellationToken = default, - Func? readGraph = null + Func? readGraph = null, + CancellationToken cancellationToken = default ) { ArgumentNullException.ThrowIfNull(readSource); using IDisposable operation = types.AcquireOperation("Capture shader authoring candidate"); diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs index 5fdb64c51..1d4a2d113 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/GeometryAssetImporter.cs @@ -76,8 +76,8 @@ byte[] ReadDependency(string relativePath) ); output.SetAsset(asset); byte[] artifact = GeometryArtifact.Encode(data); - await output.WriteArtifactAsync("runtime", artifact, cancellationToken).ConfigureAwait(false); - await output.WriteArtifactAsync("geometry", artifact, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", artifact, cancellationToken: cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("geometry", artifact, cancellationToken: cancellationToken).ConfigureAwait(false); } private static (Vector3 center, Vector3 extents) CalculateBounds(GeometryData data) diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs index 521282ac7..24fe897ac 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/MaterialAssetImporter.cs @@ -51,7 +51,7 @@ out IReadOnlyList dependencies } Validate(asset); output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken) + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken) .ConfigureAwait(false); } diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs index 666ed24d3..4f8a78c26 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/RenderPipelineAssetImporter.cs @@ -51,7 +51,7 @@ out IReadOnlyList dependencies } Validate(asset); output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken) + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken) .ConfigureAwait(false); } diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs index 053382cc7..5f605759d 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderAssetImporter.cs @@ -77,7 +77,6 @@ CancellationToken cancellationToken ); return sourceLease.ReadAllBytes(); }, - cancellationToken, ( id, path @@ -97,7 +96,8 @@ CancellationToken cancellationToken } using ArtifactLease graphLease = context.AcquireArtifact(node.identity.persistentID, ShaderGraphArtifact.C_OUTPUT_NAME); return ShaderGraphArtifact.ReadDocument(graphLease.ReadAllBytes(), context.serialization); - } + }, + cancellationToken ); } catch (ShaderTargetUnavailableException exception) @@ -120,13 +120,17 @@ CancellationToken cancellationToken } else { - await output.WriteArtifactAsync("runtime", ReadOnlyMemory.Empty, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync( + "runtime", + ReadOnlyMemory.Empty, + cancellationToken: cancellationToken + ).ConfigureAwait(false); } await output.WriteArtifactAsync( ShaderGraphArtifact.C_OUTPUT_NAME, captured, - cancellationToken, - AssetDeploymentScope.AuthoringOnly + AssetDeploymentScope.AuthoringOnly, + cancellationToken ).ConfigureAwait(false); } diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs index 61d04493a..a6a6485eb 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/ShaderFunctionImporter.cs @@ -113,8 +113,8 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( ShaderSourceBundle.C_OUTPUT_NAME, ShaderSourceBundle.Encode(modules, context.serialization), - cancellationToken, - AssetDeploymentScope.AuthoringOnly + AssetDeploymentScope.AuthoringOnly, + cancellationToken ).ConfigureAwait(false); } diff --git a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs index 8ffdaa67a..c5c7632f4 100644 --- a/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs +++ b/src/services/rendering/Inno.Rendering.Assets.Authoring/Importing/TextureAssetImporter.cs @@ -57,8 +57,8 @@ CancellationToken cancellationToken context.extension.TrimStart('.').ToLowerInvariant() ); output.SetAsset(asset); - await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken).ConfigureAwait(false); - await output.WriteArtifactAsync("source", context.sourceBytes, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("source", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); } internal static (int width, int height) ReadPngSize(ReadOnlySpan bytes) diff --git a/src/services/text/Inno.Text.Assets/FontImporter.cs b/src/services/text/Inno.Text.Assets/FontImporter.cs index 518980162..13d04e7ef 100644 --- a/src/services/text/Inno.Text.Assets/FontImporter.cs +++ b/src/services/text/Inno.Text.Assets/FontImporter.cs @@ -44,9 +44,9 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", FontMetadataCodec.Encode(metadata), - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); - await output.WriteArtifactAsync("font-data", context.sourceBytes, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("font-data", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); } private static FontMetadata ReadMetadata(ReadOnlySpan source) diff --git a/src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs b/src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs index 066a7c26b..dd6be1e8a 100644 --- a/src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs +++ b/src/services/ui/Inno.UI.Assets/UIDocumentImportPipeline.cs @@ -84,7 +84,7 @@ CancellationToken cancellationToken await output.WriteArtifactAsync( "runtime", UIDocumentAsset.CreateRuntimePayload(implementationID, source, fonts), - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs index acf1d606b..89a653dc8 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/AlternateDependencyAssetImporter.cs @@ -15,6 +15,6 @@ protected override ValueTask ImportAsync( CancellationToken cancellationToken ) { output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs index 6e86aa37c..154e90b89 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/BuildConsumerAssetImporter.cs @@ -17,6 +17,6 @@ CancellationToken cancellationToken ) { context.DependsOnArtifact(Guid.Parse(context.ReadUtf8Text())); output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs index d6621f625..c9d28fde2 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/BuildInputAssetImporter.cs @@ -27,6 +27,6 @@ CancellationToken cancellationToken context.DependsOnArtifact(dependency); } output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("authoring", context.sourceBytes, cancellationToken, AssetDeploymentScope.AuthoringOnly); + return output.WriteArtifactAsync("authoring", context.sourceBytes, AssetDeploymentScope.AuthoringOnly, cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs index 4385d67af..f86a106ea 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ConfiguredImporter.cs @@ -24,6 +24,6 @@ CancellationToken cancellationToken string value = $"{settings.multiplier}:{context.ReadUtf8Text()}"; if (settings.lookup is not null) value += ":" + settings.lookup.content; output.SetAsset(new ConfiguredAsset { value = value }); - return output.WriteArtifactAsync("runtime", Encoding.UTF8.GetBytes(value), cancellationToken); + return output.WriteArtifactAsync("runtime", Encoding.UTF8.GetBytes(value), cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs index 475168ac8..be7792d5d 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/DeferredAssetImporter.cs @@ -19,6 +19,6 @@ protected override ValueTask ImportAsync( CancellationToken cancellationToken ) { output.SetAsset(new DeferredAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs index 6132b83c8..0e64742c4 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/DependencyAssetImporter.cs @@ -20,6 +20,6 @@ CancellationToken cancellationToken output.DependsOnAsset(AssetPath.Parse(dependency)); } output.SetAsset(new DependencyAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs index 248365108..cef26d308 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionConsumerImporter.cs @@ -31,6 +31,6 @@ CancellationToken cancellationToken _ = context.ResolveDependency(AssetPath.Project(source)); } output.SetAsset(new ExtensionDependentAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs index 7fc15af59..65800417f 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ExtensionDependentImporter.cs @@ -22,6 +22,6 @@ CancellationToken cancellationToken throw new AssetImportExtensionUnavailableException("tests.target", "tests.surface"); } output.SetAsset(new ExtensionDependentAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs index db44fc682..294f60729 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/HookAssetImporter.cs @@ -15,6 +15,6 @@ protected override ValueTask ImportAsync( CancellationToken cancellationToken ) { output.SetAsset(new HookAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs index e537b8f3b..707609198 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImportGraphAssetImporter.cs @@ -20,6 +20,6 @@ CancellationToken cancellationToken output.DependsOnSource(AssetPath.Parse(dependency)); } output.SetAsset(new ImportGraphAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs index 61bde289b..313246a87 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterA.cs @@ -18,6 +18,6 @@ protected override ValueTask ImportAsync( CancellationToken cancellationToken ) { output.SetAsset(new ImporterConflictAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs index f7ee339cf..350acd927 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/ImporterConflictAssetImporterB.cs @@ -18,6 +18,6 @@ protected override ValueTask ImportAsync( CancellationToken cancellationToken ) { output.SetAsset(new ImporterConflictAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs index 225867daa..6e6c03213 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/MixedScopeAssetImporter.cs @@ -21,10 +21,10 @@ CancellationToken cancellationToken return output.WriteArtifactAsync( "graph", context.sourceBytes, - cancellationToken, - AssetDeploymentScope.AuthoringOnly + AssetDeploymentScope.AuthoringOnly, + cancellationToken ); } - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs index 2774ffe43..add48bd87 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/MutableAssetImporter.cs @@ -25,7 +25,7 @@ CancellationToken cancellationToken throw new InvalidDataException("The mutable asset source is invalid."); } output.SetAsset(new MutableAsset { value = value }); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } protected override ValueTask?> ExportAsync( diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs index c0b1542b4..9839139c7 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/PrivateConstructorAssetImporter.cs @@ -19,6 +19,6 @@ protected override ValueTask ImportAsync( CancellationToken cancellationToken ) { output.SetAsset(new PrivateConstructorAsset { value = context.ReadUtf8Text() }); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs b/tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs index 6bbd4f73b..7f8db1c64 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/SlowAssetImporter.cs @@ -26,7 +26,7 @@ CancellationToken cancellationToken throw new TimeoutException("The slow importer test gate was not released."); } output.SetAsset(new SlowAsset { value = context.ReadUtf8Text() }); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } internal static void Reset() diff --git a/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs b/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs index b46d3baea..ec2496d3e 100644 --- a/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs +++ b/tests/assets/Inno.Assets.Pipeline.Tests/TestBuildProcessor.cs @@ -13,6 +13,6 @@ protected override ValueTask BuildAsync( CancellationToken cancellationToken ) { string value = context.definition.label + ":" + context.inputs.Count; - return output.WriteAsync("result", Encoding.UTF8.GetBytes(value), cancellationToken); + return output.WriteAsync("result", Encoding.UTF8.GetBytes(value), cancellationToken: cancellationToken); } } diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs index 6ccdf98a8..50be9acea 100644 --- a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs +++ b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterA.cs @@ -36,6 +36,6 @@ protected override ValueTask ImportAsync( CancellationToken cancellationToken ) { output.SetAsset(new DuplicateImporterAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs index f9b9bc40f..420d8bcb6 100644 --- a/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs +++ b/tests/assets/fixtures/Inno.Assets.Pipeline.DuplicateImporterFixture/DuplicateImporterB.cs @@ -36,6 +36,6 @@ protected override ValueTask ImportAsync( CancellationToken cancellationToken ) { output.SetAsset(new DuplicateImporterAsset()); - return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken); + return output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken); } } diff --git a/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs b/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs index 1d917838b..3991b5f31 100644 --- a/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/BindingSelectionLifetimeTests.cs @@ -46,10 +46,10 @@ public async Task PublicationWithoutItsCompiledSelectionFailsBeforePreparingTheT sdk, ["msbuild", project, "-t:PublishProductNativeDeployment", "-nodeReuse:false", "-v:minimal"], root, - timeout.Token, null, output, - error + error, + timeout.Token )); Assert.NotNull(failure); string messages = output.ToString() + error; @@ -140,10 +140,10 @@ async Task ExecuteAsync(string command) sdk, [command, project, "--disable-build-servers", "-m:1", "-nodeReuse:false", "-v:minimal"], root, - timeout.Token, null, output, - error + error, + timeout.Token )); Assert.True(failure is null, output.ToString() + error + failure); } diff --git a/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs b/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs index da3a5b77c..0275f5bb0 100644 --- a/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs +++ b/tests/build/Inno.Build.Bindings.Tests/NativeBindingGenerationTests.cs @@ -83,12 +83,12 @@ NativeBuildRecipe Recipe(NativeBuildContext current) productions++; return File.WriteAllTextAsync(Path.Combine(output, "fixture.data"), "native payload", token); }, - cancellation, describeOutputs: static ( _, output ) => - [new NativeArtifact("fixture", Path.Combine(output, "fixture.data"), NativeArtifactRole.SharedLibrary)] + [new NativeArtifact("fixture", Path.Combine(output, "fixture.data"), NativeArtifactRole.SharedLibrary)], + cancellationToken: cancellation ), Recipe, static ( diff --git a/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs b/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs index 314173e23..4450cfb0d 100644 --- a/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/DevelopmentAppHostSdkTests.cs @@ -66,10 +66,10 @@ await ToolchainEnvironment.RunAsync( host, ["build", project, "-nologo", "-nodeReuse:false"], owner.directory, - CancellationToken.None, DotNetSdkEnvironment.Create(host), buildOutput, - buildErrors + buildErrors, + CancellationToken.None ); } catch (InvalidOperationException failure) diff --git a/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs b/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs index c963fcb6f..addd6305b 100644 --- a/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/ManagedOutputOwnershipTests.cs @@ -221,10 +221,10 @@ private static async Task RunAsync( host, arguments, directory, - cancellation.Token, DotNetSdkEnvironment.Create(host), output ?? captured, - error + error, + cancellation.Token )); Assert.True(failure is null, $"{failure}{Environment.NewLine}{output ?? captured}{Environment.NewLine}{error}"); } diff --git a/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs b/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs index a5f5275cb..76e66bb66 100644 --- a/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/SolutionBootstrapOwnershipTests.cs @@ -49,10 +49,10 @@ bool explicitlyDisablePreparation "-nr:false" ], repository, - cancellation.Token, DotNetSdkEnvironment.Create(host), output, - error + error, + cancellation.Token )); Assert.True(failure is null, $"{failure}\n{output}\n{error}"); Assert.False(Directory.Exists(tasks), output.ToString()); @@ -110,10 +110,10 @@ async Task InvokeAsync(string owner) host, ["msbuild", project, "-t:Build", "-nr:false", "-p:InnoTaskBootstrapOwner=" + owner], root, - cancellation.Token, DotNetSdkEnvironment.Create(host), output, - error + error, + cancellation.Token )); if (failure is not null) { @@ -178,10 +178,10 @@ await File.WriteAllTextAsync(solution, """ host, ["msbuild", solution, "-m:2", "-nodeReuse:false", "-v:quiet"], fixture, - cancellation.Token, DotNetSdkEnvironment.Create(host), output, - error + error, + cancellation.Token )); Assert.True(failure is null, $"{failure}{Environment.NewLine}{output}{Environment.NewLine}{error}"); string first = File.ReadAllText(Path.Combine(fixture, "First.owner")).Trim(); diff --git a/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs b/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs index befd59daa..ffe80bb59 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskPublisherBootstrapTests.cs @@ -123,10 +123,10 @@ string runtimeIdentifier "-p:WasmBuildNative=true" ], repository, - timeout.Token, DotNetSdkEnvironment.Create(dotnet), output, - errors + errors, + timeout.Token )); Assert.True(failure is null, $"{failure}\n{output}\n{errors}"); int requests = 0; diff --git a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs index fd2fd9ba8..9dfd66a7e 100644 --- a/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs +++ b/tests/build/Inno.Build.ProductProfiles.Integration.Tests/StaticGraphRestoreTests.cs @@ -196,10 +196,10 @@ await ToolchainEnvironment.RunAsync( "-getItem:ProjectReference" ], Path.GetDirectoryName(project)!, - cancellation.Token, DotNetSdkEnvironment.Create(host), output, - error + error, + cancellation.Token ); return JsonDocument.Parse(output.ToString()); } diff --git a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs index c1b6102ca..f32683d21 100644 --- a/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs +++ b/tests/build/Inno.Build.SupportPacks.Tests/SupportPackPublisherTests.cs @@ -110,7 +110,7 @@ public async Task CancellationDuringPlanningLeavesNoOutputAndExecutesNoPlan() }); await Assert.ThrowsAnyAsync(() => new PlayerSupportPackPublisher([source]) - .PublishAsync(m_root, output, TARGET, "unused", cancellation.Token) + .PublishAsync(m_root, output, TARGET, "unused", cancellationToken: cancellation.Token) .AsTask()); Assert.False(Directory.Exists(output)); @@ -183,7 +183,7 @@ public async Task CancellationRejectsCandidateBeforeInstallation() var publisher = new PlayerSupportPackPublisher([new TestSource(null)]); string output = Path.Combine(m_root, "Packs"); await Assert.ThrowsAnyAsync( - () => publisher.PublishAsync(m_root, output, TARGET, "unused", cancellation.Token).AsTask() + () => publisher.PublishAsync(m_root, output, TARGET, "unused", cancellationToken: cancellation.Token).AsTask() ); Assert.False(Directory.Exists(output)); } @@ -207,7 +207,7 @@ public async Task CancellationDuringValidationPreservesTheInstalledPack() var publisher = new PlayerSupportPackPublisher([new TestSource(null, cancellation.Cancel)]); await Assert.ThrowsAnyAsync( - () => publisher.PublishAsync(m_root, output, TARGET, "unused", cancellation.Token).AsTask() + () => publisher.PublishAsync(m_root, output, TARGET, "unused", cancellationToken: cancellation.Token).AsTask() ); Assert.Equal("candidate", File.ReadAllText(Path.Combine(installed, "References", "Inno.Test.dll"))); @@ -273,7 +273,7 @@ await Assert.ThrowsAnyAsync(() => publisher.PublishA output, TARGET, "unused", - cancellation.Token + cancellationToken: cancellation.Token ).AsTask()); Assert.Equal("changed externally", File.ReadAllText(file)); @@ -299,7 +299,9 @@ public async Task WaitingWriterCanCancelWithoutEnteringPreparationOrDisturbingTh var second = new PlayerSupportPackPublisher( [new TestSource(new InvalidOperationException("Preparation must not run."))] ); - Task waiting = second.PublishAsync(m_root, output, TARGET, "unused", cancellation.Token).AsTask(); + Task waiting = second + .PublishAsync(m_root, output, TARGET, "unused", cancellationToken: cancellation.Token) + .AsTask(); try { cancellation.Cancel(); diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs index 65f44e1d4..e357cc37c 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactImportTests.cs @@ -220,7 +220,7 @@ public async Task CanceledExportPreservesThePreviousTransport() using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); await Assert.ThrowsAnyAsync( - () => NativeArtifactTransfer.ExportAsync(producer, archive, cancellation.Token) + () => NativeArtifactTransfer.ExportAsync(producer, archive, cancellationToken: cancellation.Token) ); Assert.Equal(before, File.ReadAllBytes(archive)); Assert.Empty(Directory.GetFiles(Path.GetDirectoryName(archive)!, "*.staging-*")); diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs index 153d26d8f..043c3679f 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeArtifactPublicationTests.cs @@ -44,7 +44,12 @@ CancellationToken cancellationToken using NativeBuildProduct first = await NativeArtifactPublisher.PublishAsync(context, recipe, ProduceAsync); File.WriteAllText(first.files[0], "damaged"); using var cancellation = new CancellationTokenSource(); - Task waiting = NativeArtifactPublisher.PublishAsync(CreateContext(), recipe, ProduceAsync, cancellation.Token); + Task waiting = NativeArtifactPublisher.PublishAsync( + CreateContext(), + recipe, + ProduceAsync, + cancellationToken: cancellation.Token + ); await prepared.Task.WaitAsync(TimeSpan.FromSeconds(5)); await Task.Delay(80); Assert.False(waiting.IsCompleted); @@ -570,7 +575,7 @@ await Assert.ThrowsAnyAsync(() => NativeArtifactPubl await File.WriteAllTextAsync(Path.Combine(output, "api.native"), "candidate", token); cancellation.Cancel(); }, - cancellation.Token + cancellationToken: cancellation.Token )); Assert.Empty(Directory.EnumerateFiles(Path.Combine(m_root, "artifacts"), "api.native", SearchOption.AllDirectories)); Assert.Empty(Directory.GetDirectories(m_root, "*.staging-*", SearchOption.AllDirectories)); diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs index 826663b4d..ec406a9d4 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeDependencyManifestTests.cs @@ -381,11 +381,11 @@ CancellationToken cancellationToken m_productions++; return File.WriteAllTextAsync(Path.Combine(output, "output.data"), "payload", token); }, - cancellationToken, describeOutputs: static ( _, output - ) => [new NativeArtifact("fixture", Path.Combine(output, "output.data"), NativeArtifactRole.StaticArchive)] + ) => [new NativeArtifact("fixture", Path.Combine(output, "output.data"), NativeArtifactRole.StaticArchive)], + cancellationToken: cancellationToken ); private static Task GitAsync( diff --git a/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs b/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs index 8399e296e..8dae4fc07 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/NativeProductExecutorTests.cs @@ -154,11 +154,11 @@ CancellationToken cancellationToken m_productions++; return File.WriteAllTextAsync(Path.Combine(output, "probe-output.data"), "archive", token); }, - cancellationToken, describeOutputs: static ( operation, output - ) => [new NativeArtifact("probe-archive", Path.Combine(output, "probe-output.data"), NativeArtifactRole.StaticArchive)] + ) => [new NativeArtifact("probe-archive", Path.Combine(output, "probe-output.data"), NativeArtifactRole.StaticArchive)], + cancellationToken: cancellationToken ); private sealed class SelectedExecutor : INativeProductExecutor diff --git a/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs index ae1626578..1f2e676b9 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ProductNativeCacheLookupTests.cs @@ -117,7 +117,7 @@ private ProductNativeBuildPlan Plan() { Interlocked.Increment(ref m_builds); await File.WriteAllTextAsync(Path.Combine(output, "result.native"), "complete", token); - }, cancellation), + }, cancellationToken: cancellation), context => Recipe(context, id), static ( relative, diff --git a/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs index bd162b5f7..ea7496933 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ProductNativePreparationTests.cs @@ -274,7 +274,7 @@ private ProductNativeBuildPlan Plan(NativeLibraryKind kind = NativeLibraryKind.S { Interlocked.Increment(ref m_productions); await File.WriteAllTextAsync(Path.Combine(output, "result.fixture"), "result", token); - }, cancellation), + }, cancellationToken: cancellation), Recipe, ( path, diff --git a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs index 70b8ec2f8..879d6ded6 100644 --- a/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs +++ b/tests/platforms/BrowserWasm32/Inno.Build.BrowserWasm32.Integration.Tests/BrowserDependencyConsumptionTests.cs @@ -38,8 +38,8 @@ public async Task MatchingStaticDependenciesProduceARealManagedPlayerSupportPack output, target, dotnet, - cancellation.Token, - manifest + manifest, + cancellation.Token ); distribution.platforms.Single(platform => platform.descriptor.id == target).supportPackSource.Validate(pack.directory); Assert.True(File.Exists(Path.Combine(pack.directory, "References", "Inno.Player.Runtime.dll"))); diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs index b3cceb331..626dd1f92 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ControlledSampleAssetImporter.cs @@ -57,7 +57,7 @@ CancellationToken cancellationToken await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); } output.SetAsset(new TextAsset(context.ReadUtf8Text())); - await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken).ConfigureAwait(false); + await output.WriteArtifactAsync("runtime", context.sourceBytes, cancellationToken: cancellationToken).ConfigureAwait(false); } internal sealed class Control : IDisposable diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs index f9fde197c..977fd7ff0 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingFixture.cs @@ -168,7 +168,7 @@ internal ScriptCompilationResult Compile( CancellationToken cancellationToken = default ) { Rescan(); - return compiler.CompileAuthoringGenerationAsync(progress, cancellationToken).GetAwaiter().GetResult(); + return compiler.CompileAuthoringGenerationAsync(progress, cancellationToken: cancellationToken).GetAwaiter().GetResult(); } internal ScriptCompilationResult CompileRuntimeDeployment( diff --git a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs index be435b7ec..933f3950b 100644 --- a/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs +++ b/tests/scripting/Inno.Editor.Scripting.Tests/ScriptingPipelineTests.cs @@ -780,8 +780,8 @@ public void InstalledPluginSampleImportsAsAnImmediatelyCompilableWritableCopy() ) => { ScriptCompilationResult candidate = await fixture.compiler.CompileAuthoringGenerationAsync( - cancellationToken: cancellationToken, - sourceSnapshot: sources + sourceSnapshot: sources, + cancellationToken: cancellationToken ); Assert.True(candidate.success, FormatDiagnostics(candidate)); }); @@ -823,8 +823,8 @@ public void InvalidSampleScriptPreflightLeavesNoProjectCopy() ) => { ScriptCompilationResult candidate = await fixture.compiler.CompileAuthoringGenerationAsync( - cancellationToken: cancellationToken, - sourceSnapshot: sources + sourceSnapshot: sources, + cancellationToken: cancellationToken ); if (!candidate.success) { @@ -1218,8 +1218,8 @@ public void SampleCompilerReferencePreparationRunsOnWorker() { ScriptCompilationResult result = await fixture.compiler.CompileAuthoringGenerationAsync( progress, - cancellationToken, - sources + sources, + cancellationToken ).ConfigureAwait(false); Assert.True(result.success, FormatDiagnostics(result)); }); diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs index 53eeaef5f..5a3e70065 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/CSharp14ScriptingTests.cs @@ -56,10 +56,10 @@ await Assert.ThrowsAsync(() => ToolchainEnvironment.R sdk.hostPath, [sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nr:false", "-p:" + property + "=" + value], fixture.projectRoot, - CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath), output, - errors + errors, + CancellationToken.None )); Assert.Contains("IDE compiler input '" + property + "' differs", output.ToString() + errors, StringComparison.Ordinal); } @@ -368,10 +368,10 @@ await ToolchainEnvironment.RunAsync( sdk.hostPath, [sdk.cliPath, "build", project, "--disable-build-servers", "-m:1", "-nr:false", "-v:quiet"], directory, - CancellationToken.None, DotNetSdkEnvironment.Create(sdk.hostPath), output, - errors + errors, + CancellationToken.None ); return output.ToString(); } diff --git a/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs b/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs index 2cc9ac68d..192f253b0 100644 --- a/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs +++ b/tests/scripting/Inno.Scripting.Compiler.Tests/ScriptCachePublicationTests.cs @@ -48,7 +48,7 @@ public async Task ReusedAssembliesPublishAfterATemporaryStagingReaderReleasesThe ); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); Task compilation = fixture.compiler - .CompileAuthoringGenerationAsync(observer, cancellation.Token) + .CompileAuthoringGenerationAsync(observer, cancellationToken: cancellation.Token) .AsTask(); Exception? compilationFailure = null; bool captured = false; @@ -197,7 +197,7 @@ private static void VerifyRejectedPublication(bool cancel) ); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); Task compilation = fixture.compiler - .CompileAuthoringGenerationAsync(observer, cancellation.Token) + .CompileAuthoringGenerationAsync(observer, cancellationToken: cancellation.Token) .AsTask(); try { diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs index 068243a88..bd3e0f68a 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/ArchitectureOutputOwnerTests.cs @@ -103,7 +103,7 @@ await ManagedProjectGraphCapture.CaptureAsync( ["BuildProjectReferences"] = "false", ["InnoProductRestore"] = "false" }, - cancellation.Token + cancellationToken: cancellation.Token ) ); string captured = ArchitectureCommandFixture.Run( diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs index d5e03ed5b..31e1fa00a 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationCompletionTests.cs @@ -77,12 +77,12 @@ public sealed class CompilationInputProbe } """); - Assert.Equal(0, await repository.RunCurrentAsync(cancellation.Token, "artifacts/warmup")); + Assert.Equal(0, await repository.RunCurrentAsync("artifacts/warmup", cancellation.Token)); repository.Write(C_PROBE, File.ReadAllText(source) + "\n// Change this owner's compilation input.\n"); byte[] original = File.ReadAllBytes(source); DateTime timestamp = File.GetLastWriteTimeUtc(source); File.WriteAllText(gate, "mutate after planning"); - await Assert.ThrowsAsync(() => repository.RunCurrentAsync(cancellation.Token, "artifacts/run")); + await Assert.ThrowsAsync(() => repository.RunCurrentAsync("artifacts/run", cancellation.Token)); using (JsonDocument failed = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/run/results.json")))) { JsonElement[] results = failed.RootElement.GetProperty("results").EnumerateArray().ToArray(); @@ -100,7 +100,7 @@ public sealed class CompilationInputProbe } File.WriteAllBytes(source, original); File.SetLastWriteTimeUtc(source, timestamp); - Assert.Equal(0, await repository.RunCurrentAsync(cancellation.Token, "artifacts/repaired")); + Assert.Equal(0, await repository.RunCurrentAsync("artifacts/repaired", cancellation.Token)); Assert.Equal( 0, await repository.EvidenceAsync(repository.PathOf("artifacts/repaired/results.json"), "artifacts/repaired/plan.json") @@ -122,7 +122,7 @@ await repository.EvidenceAsync(repository.PathOf("artifacts/repaired/results.jso dependencyOutput = repository.BindWorkspace(dependencyOutput); DateTime outputTimestamp = File.GetLastWriteTimeUtc(dependencyOutput); byte[] dependencyBytes = File.ReadAllBytes(dependencyOutput); - Assert.Equal(0, await repository.RunAsync(cancellation.Token, "artifacts/owner-only")); + Assert.Equal(0, await repository.RunAsync("artifacts/owner-only", cancellationToken: cancellation.Token)); Assert.Equal(dependencyBytes, File.ReadAllBytes(dependencyOutput)); Assert.Equal(outputTimestamp, File.GetLastWriteTimeUtc(dependencyOutput)); @@ -137,7 +137,9 @@ await repository.EvidenceAsync(repository.PathOf("artifacts/repaired/results.jso { Assert.Single(plan.RootElement.GetProperty("owners").EnumerateArray()); } - await Assert.ThrowsAsync(() => repository.RunAsync(cancellation.Token, "artifacts/dependency-changed")); + await Assert.ThrowsAsync( + () => repository.RunAsync("artifacts/dependency-changed", cancellationToken: cancellation.Token) + ); using JsonDocument changed = JsonDocument.Parse(File.ReadAllText(repository.PathOf("artifacts/dependency-changed/results.json"))); Assert.Contains(changed.RootElement.GetProperty("results").EnumerateArray(), result => ( result.GetProperty("id").GetString() == "test:tests/input/Inno.Input.Tests/Inno.Input.Tests.csproj" @@ -180,7 +182,7 @@ public async Task FailedClosingReadCannotCertifyOtherwisePassingIntermediateResu using JsonDocument plan = await repository.PlanAsync(); Assert.Empty(plan.RootElement.GetProperty("owners").EnumerateArray()); using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(5)); - Task execution = repository.RunAsync(cancellation.Token); + Task execution = repository.RunAsync(cancellationToken: cancellation.Token); try { while (!File.Exists(signal)) @@ -211,7 +213,7 @@ public async Task FailedClosingReadCannotCertifyOtherwisePassingIntermediateResu await Assert.ThrowsAsync(() => repository.EvidenceAsync(evidence)); // Recovery starts after the failed run and its evidence have been inspected. It owns its full execution budget. using var recovery = new CancellationTokenSource(TimeSpan.FromMinutes(5)); - Assert.Equal(0, await repository.RunAsync(recovery.Token, "artifacts/completed")); + Assert.Equal(0, await repository.RunAsync("artifacts/completed", cancellationToken: recovery.Token)); Assert.Equal(0, await repository.EvidenceAsync(repository.PathOf("artifacts/completed/results.json"))); } finally @@ -472,7 +474,7 @@ await repository.SdkAsync( string output = "artifacts/union-" + value; try { - Assert.Equal(0, await repository.RunAsync(cancellation.Token, output)); + Assert.Equal(0, await repository.RunAsync(output, cancellationToken: cancellation.Token)); } catch (Exception failure) { diff --git a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs index d21749292..df27253ee 100644 --- a/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Integration.Tests/ValidationProgressTests.cs @@ -39,7 +39,7 @@ public async Task QuietChildReportsActivityBeforeExitAndCancellationRetainsItsFa Task? running = null; try { - running = repository.RunAsync(cancellation.Token); + running = repository.RunAsync(cancellationToken: cancellation.Token); string activity = await capture.activity.Task.WaitAsync(TimeSpan.FromMinutes(2)); Assert.False(running.IsCompleted); Assert.StartsWith("Process active: instructions.log;", activity); diff --git a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs index d05716c39..a8651e978 100644 --- a/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs +++ b/tests/tooling/Inno.Tooling.Validation.Tests/ValidationPlanningTests.cs @@ -1520,7 +1520,7 @@ public async Task ACompetingOutputWriterCanCancelWithoutAdoptingOrReleasingAnoth string parent = Path.GetDirectoryName(artifacts)!; using FileLease writer = await FileLease.AcquireAsync(artifacts + ".lock", TimeSpan.FromSeconds(5)); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(60)); - Task competing = repository.RunAsync(cancellation.Token); + Task competing = repository.RunAsync(cancellationToken: cancellation.Token); while (!BuildCacheOwnerCatalog.ReadOwners(repository.PathOf(".")).Any(owner => owner.directory == parent)) { cancellation.Token.ThrowIfCancellationRequested(); diff --git a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs index 7fef991a6..39512383a 100644 --- a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs +++ b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs @@ -191,8 +191,8 @@ public Task EvidenceAsync( ]); public Task RunCurrentAsync( - CancellationToken cancellationToken, - string output + string output, + CancellationToken cancellationToken ) => ValidationCommand.ExecuteAsync([ "run", "--engine-root", @@ -206,9 +206,9 @@ string output ], cancellationToken); public Task RunAsync( - CancellationToken cancellationToken = default, string output = "artifacts/run", - string? evidence = null + string? evidence = null, + CancellationToken cancellationToken = default ) => ValidationCommand.ExecuteAsync([ "run", "--engine-root", diff --git a/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs b/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs index 02aebaa3e..b7b695a7d 100644 --- a/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs +++ b/tools/Inno.Tooling.Architecture/ArchitectureValidator.cs @@ -193,8 +193,8 @@ public static int Execute( repositoryRoot, configuration, evaluatedReferences, - cancellationToken, - failures + failures, + cancellationToken ); var sourceTrees = new Dictionary(StringComparer.Ordinal); if (!metadataOnly) diff --git a/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs b/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs index 9014e5223..9d5643f8b 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationExportPlan.cs @@ -74,7 +74,7 @@ string Required(string key) dotnet, graphProjects, properties, - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); using JsonDocument graph = JsonDocument.Parse(graphText); foreach (JsonElement node in graph.RootElement.EnumerateArray()) diff --git a/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs b/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs index e6531ecee..d69ce2e17 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationProjectReferences.cs @@ -332,8 +332,8 @@ private CSharpCompilation Evaluate( m_dotnetHost, projects, batchProperties, - cancellationToken, - resolveReferences: true + resolveReferences: true, + cancellationToken: cancellationToken ).GetAwaiter().GetResult(); using JsonDocument batch = JsonDocument.Parse(captured); foreach (JsonElement snapshot in batch.RootElement.EnumerateArray()) diff --git a/tools/Inno.Tooling.Architecture/DocumentationReferences.cs b/tools/Inno.Tooling.Architecture/DocumentationReferences.cs index db847db93..0e89efdf1 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationReferences.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationReferences.cs @@ -576,7 +576,7 @@ private static IReadOnlyList CaptureApi( selectedProjects: selected, sdkSnapshot: sdkSnapshot ); - var models = new DocumentationSourceModels(root, configuration, references, cancellationToken, failures); + var models = new DocumentationSourceModels(root, configuration, references, failures, cancellationToken); List inventory = []; using var cache = new DocumentationExportCache(root, cancellationToken); foreach (string project in selected.Order(StringComparer.Ordinal)) diff --git a/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs b/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs index 52c8bc034..ff93c35b0 100644 --- a/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs +++ b/tools/Inno.Tooling.Architecture/DocumentationSourceModels.cs @@ -28,8 +28,8 @@ internal DocumentationSourceModels( string repositoryRoot, string configuration, DocumentationProjectReferences? projectReferences = null, - CancellationToken cancellationToken = default, - ICollection? failures = null + ICollection? failures = null, + CancellationToken cancellationToken = default ) { m_projectReferences = projectReferences; m_cancellation = cancellationToken; diff --git a/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs b/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs index a34ae930b..ec004f752 100644 --- a/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs +++ b/tools/Inno.Tooling.Architecture/MSBuildProjectGraphValidator.cs @@ -53,7 +53,7 @@ internal static async Task> ValidateAsync( dotnetHost, projects, properties, - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); using JsonDocument snapshots = JsonDocument.Parse(graph); foreach (JsonElement snapshot in snapshots.RootElement.EnumerateArray()) diff --git a/tools/Inno.Tooling.Documentation/DocumentationCommand.cs b/tools/Inno.Tooling.Documentation/DocumentationCommand.cs index fc12f1811..588a718b2 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationCommand.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationCommand.cs @@ -130,8 +130,8 @@ public static async Task ExecuteAsync( cache, options.GetValueOrDefault("--snapshot"), options.GetValueOrDefault("--source-tree"), - cancellationToken, - sourceEvidence + sourceEvidence, + cancellationToken ).ConfigureAwait(false); if (operation == "catalog") { diff --git a/tools/Inno.Tooling.Documentation/DocumentationStore.cs b/tools/Inno.Tooling.Documentation/DocumentationStore.cs index f935a085c..a9b7a55cf 100644 --- a/tools/Inno.Tooling.Documentation/DocumentationStore.cs +++ b/tools/Inno.Tooling.Documentation/DocumentationStore.cs @@ -340,13 +340,13 @@ DocumentationResult Finish(string message) /// /// Expected engine input tree, or null when the caller only needs the explicitly bound documentation snapshot. /// - /// - /// Cancels reading lease acquisition and manifest loading. - /// /// /// Explicit certificate authenticated during preparation, or null for an unverified session. /// A certificate must cover the exact source tree and every protected API reference. /// + /// + /// Cancels reading lease acquisition and manifest loading. + /// /// /// A caller-owned query session. Dispose it after the final query to release its generation reading lease. /// @@ -360,8 +360,8 @@ public static async Task OpenAsync( string cacheRoot, string? snapshot = null, string? expectedSourceTree = null, - CancellationToken cancellationToken = default, - DocumentationEvidence? sourceEvidence = null + DocumentationEvidence? sourceEvidence = null, + CancellationToken cancellationToken = default ) { string output = Path.GetFullPath(cacheRoot); PathBoundary.RequireUnlinkedPath(output, output); diff --git a/tools/Inno.Tooling.Validation/ValidationCommand.cs b/tools/Inno.Tooling.Validation/ValidationCommand.cs index 9b261e295..a6d6d7ac1 100644 --- a/tools/Inno.Tooling.Validation/ValidationCommand.cs +++ b/tools/Inno.Tooling.Validation/ValidationCommand.cs @@ -329,7 +329,7 @@ await File.WriteAllTextAsync( && plan.contexts.ContainsKey("native") ) { Console.WriteLine( - $"Retained {await NativeArtifactTransfer.ExportAsync(root, retentionArchive, cancellationToken).ConfigureAwait(false)} complete immutable generations; reconciliation must still succeed independently." + $"Retained {await NativeArtifactTransfer.ExportAsync(root, retentionArchive, cancellationToken: cancellationToken).ConfigureAwait(false)} complete immutable generations; reconciliation must still succeed independently." ); } if (planPath is not null @@ -454,7 +454,7 @@ await File.WriteAllBytesAsync( if (options.TryGetValue("--cache-output", out string? cacheOutput) && plan.contexts.ContainsKey("native")) { Console.WriteLine( - $"Exported {await NativeArtifactTransfer.ExportAsync(root, cacheOutput, cancellationToken).ConfigureAwait(false)} verified immutable generations." + $"Exported {await NativeArtifactTransfer.ExportAsync(root, cacheOutput, cancellationToken: cancellationToken).ConfigureAwait(false)} verified immutable generations." ); } return 0; diff --git a/tools/Inno.Tooling.Validation/ValidationPlanner.cs b/tools/Inno.Tooling.Validation/ValidationPlanner.cs index 3bf372b9e..50d95da47 100644 --- a/tools/Inno.Tooling.Validation/ValidationPlanner.cs +++ b/tools/Inno.Tooling.Validation/ValidationPlanner.cs @@ -133,7 +133,7 @@ internal static async Task CreateAsync( sdk, paths.Select(path => Path.Combine(root, path)).ToArray(), properties, - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); RecordStage("sdk-capture"); using JsonDocument graph = JsonDocument.Parse(captured); @@ -527,7 +527,7 @@ internal static async Task CreateAsync( sdk, paths.Select(path => Path.Combine(root, path)).ToArray(), evaluationProperties, - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); using JsonDocument nativeGraph = JsonDocument.Parse(nativeCapture); RequireCompilerInputs(nativeGraph.RootElement); @@ -942,7 +942,7 @@ void Visit(ValidationProject node) sdk, paths.Select(path => Path.Combine(root, path)).ToArray(), releaseInputsProperties, - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); using JsonDocument backendGraph = JsonDocument.Parse(backendCapture); RequireCompilerInputs(backendGraph.RootElement); @@ -963,7 +963,7 @@ void Visit(ValidationProject node) sdk, paths.Select(path => Path.Combine(root, path)).ToArray(), evaluationProperties, - cancellationToken + cancellationToken: cancellationToken ).ConfigureAwait(false); using JsonDocument releaseGraph = JsonDocument.Parse(releaseCapture); RequireCompilerInputs(releaseGraph.RootElement); diff --git a/tools/Inno.Tooling.Validation/ValidationRunner.cs b/tools/Inno.Tooling.Validation/ValidationRunner.cs index 8b448b9aa..377d281e5 100644 --- a/tools/Inno.Tooling.Validation/ValidationRunner.cs +++ b/tools/Inno.Tooling.Validation/ValidationRunner.cs @@ -1021,8 +1021,8 @@ async Task ResolveCompilationGraphAsync(string context) plan.dotnet, projects, plan.contexts[context].properties, - cancellationToken, - resolveReferences: true + resolveReferences: true, + cancellationToken: cancellationToken ).ConfigureAwait(false); string destination = Path.Combine(directory, context + "-resolved-sdk-graph.json"); await File.WriteAllTextAsync(destination, graph, cancellationToken).ConfigureAwait(false); From 4492ff0e3f5ca688b2918fd224aca5b52d2bc864 Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sun, 22 Nov 2026 04:10:11 +0000 Subject: [PATCH 32/33] style(csharp): name ignored failures and make plain structs readonly Rule X-04. A bare `catch` that does not rethrow becomes `catch (Exception)`, and each handler that ignores the failure says why in a comment. Rule T-05. The tree widget value structs and one test struct become `readonly`. Rule X-05. `ValidationRepository.Git` reads the process output without blocking on a task result. --- .../Execution/ToolRunner.cs | 2 +- .../Context/PlatformImGuiContext.Clipboard.cs | 5 +++-- .../pipeline/Inno.Build/Game/GameBuildPipeline.cs | 2 +- .../Inno.Build.Toolchains/ToolchainEnvironment.cs | 2 +- .../History/AssetSourceArchive.cs | 3 ++- .../Documents/EditorSceneWorkspace.Persistence.cs | 3 ++- .../History/ScenePropertyHistoryHandler.cs | 3 ++- .../History/SceneScalarHistoryHandler.cs | 3 ++- .../References/SceneReferenceIndex.cs | 3 ++- .../Inno.Editor.Graph/GraphHistoryHandler.cs | 3 ++- .../History/EditorHistoryBlobStore.cs | 4 ++-- .../Hosting/EditorHostResourceStack.cs | 2 +- .../Widgets/TreeWidgetHighlightRect.cs | 6 +++--- .../Widgets/TreeWidgetLineSegment.cs | 6 +++--- .../Widgets/TreeWidgetNodeState.cs | 10 +++++----- .../Inno.Assets.Pipeline/AssetPipeline.Changes.cs | 4 ++-- .../AssetPipeline.Mutations.cs | 4 ++-- .../Importing/AssetLoader.SourceIO.cs | 3 ++- .../Inno.Assets.Pipeline/Importing/AssetLoader.cs | 2 +- .../Importing/Catalog/AssetCatalogStore.cs | 3 ++- .../core/Inno.Core.Execution/LifetimeScope.cs | 2 +- .../Inno.Extensibility.Types/TypeRegistry.cs | 3 ++- .../TaskHostPublicationProcess.cs | 5 ++++- .../ToolchainProcessTests.cs | 2 +- .../StableAnnotatedTypeB.cs | 2 +- .../ValidationRepository.cs | 14 ++++++++++---- 26 files changed, 60 insertions(+), 41 deletions(-) diff --git a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs index 2f1bf4643..19bce6caf 100644 --- a/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs +++ b/backends/Bgfx/build/Inno.Build.Toolchains.Bgfx.Tools/Execution/ToolRunner.cs @@ -188,7 +188,7 @@ await standardError.ConfigureAwait(false) { await Task.WhenAll(standardOutput, standardError).ConfigureAwait(false); } - catch + catch (Exception) { // Observe both readers before preserving the original operation failure. } diff --git a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs index b235d538a..fee99168e 100644 --- a/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs +++ b/backends/ImGui/runtime/Inno.Adapter.Presentation.ImGui.Sdl3/Context/PlatformImGuiContext.Clipboard.cs @@ -76,8 +76,9 @@ private void ReleaseClipboardText() PlatformImGuiContext? owner = FindClipboardContext(context); return owner is null ? null : owner.GetClipboardText(); } - catch + catch (Exception) { + // An exception must not unwind into native code. Null reports that no text is available. return null; } } @@ -94,7 +95,7 @@ private static void PlatformSetClipboardTextCallback( _ = SDL.Raw.SetClipboardText(text); } } - catch + catch (Exception) { // Exceptions must not cross Dear ImGui's unmanaged callback boundary. } diff --git a/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs b/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs index a21a59ca6..c3cf81af9 100644 --- a/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs +++ b/build/pipeline/Inno.Build/Game/GameBuildPipeline.cs @@ -366,7 +366,7 @@ private static async ValueTask ObserveCompletionAsync(Task? task) { await task.ConfigureAwait(false); } - catch + catch (Exception) { // The primary build path reports the stage failure; cleanup only observes task completion. } diff --git a/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs b/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs index 4baf5b4e9..6780053bf 100644 --- a/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs +++ b/build/toolchains/Inno.Build.Toolchains/ToolchainEnvironment.cs @@ -621,7 +621,7 @@ private static async Task RunProcessAsync( { await Task.WhenAll(exited, output, error).ConfigureAwait(false); } - catch + catch (Exception) { // Observe all pumps while preserving the failure that initiated process cleanup. } diff --git a/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs b/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs index 00f504cc1..243ed164b 100644 --- a/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs +++ b/src/composition/editor/features/Inno.Editor.Assets/History/AssetSourceArchive.cs @@ -155,8 +155,9 @@ ReadOnlySpan data assets.Rescan(); assets.WaitForIdle(); } - catch + catch (Exception) { + // The original failure is rethrown below. A failed rescan must not replace it. } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs index 3f541e9c4..9628c0d25 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/Documents/EditorSceneWorkspace.Persistence.cs @@ -260,8 +260,9 @@ out SceneDocumentSnapshot snapshot { SynchronizeSource(scene, document); } - catch + catch (Exception) { + // The source could not be synchronized. The document stays dirty. document.isDirty = true; } relativePath = document.sourcePath; diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs index d8ebaa645..fed8b1ce0 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/ScenePropertyHistoryHandler.cs @@ -226,8 +226,9 @@ out EditorHistoryChange? merged ); return true; } - catch + catch (Exception) { + // A payload that cannot be decoded is not merged. The two changes stay separate. return false; } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs index acb98057b..eec509cda 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/History/SceneScalarHistoryHandler.cs @@ -156,8 +156,9 @@ out EditorHistoryChange? merged ); return true; } - catch + catch (Exception) { + // A payload that cannot be decoded is not merged. The two changes stay separate. return false; } } diff --git a/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs b/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs index 79f879f39..1f66b5c65 100644 --- a/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs +++ b/src/composition/editor/features/Inno.Editor.Scene/References/SceneReferenceIndex.cs @@ -278,8 +278,9 @@ ISet visited { fieldValue = fields[i].GetValue(value); } - catch + catch (Exception) { + // A field that cannot be read is skipped. continue; } if (ContainsReference(fieldValue, targetIDs, visited)) diff --git a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs index 9a789dc61..6b5df0f5c 100644 --- a/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs +++ b/src/composition/editor/framework/Inno.Editor.Graph/GraphHistoryHandler.cs @@ -113,8 +113,9 @@ out EditorHistoryChange? merged ); return true; } - catch + catch (Exception) { + // A payload that cannot be decoded is not merged. The two changes stay separate. return false; } } diff --git a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs index 4801718f8..7af065d6c 100644 --- a/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs +++ b/src/composition/editor/framework/Inno.Editor.Interactions/History/EditorHistoryBlobStore.cs @@ -40,7 +40,7 @@ public void Dispose() Directory.Delete(m_sessionDirectory, recursive: true); } } - catch + catch (Exception) { // A stale session directory is safe to remove with the project's Library cache. } @@ -94,7 +94,7 @@ internal void Release(string path) File.Delete(path); } } - catch + catch (Exception) { // Session cleanup retries deletion when the history is disposed. } diff --git a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs index 99ba86e57..c0efc74b8 100644 --- a/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs +++ b/src/composition/editor/hosting/Inno.Editor.Hosting/Hosting/EditorHostResourceStack.cs @@ -43,7 +43,7 @@ public void Dispose() { reportCleanupFailure(exception); } - catch + catch (Exception) { // Cleanup diagnostics must never replace the original startup failure. } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs index 1a59e8945..41ce4a06e 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetHighlightRect.cs @@ -2,8 +2,8 @@ namespace Inno.Editor.ImGui.ImGuiWidget; -internal struct TreeWidgetHighlightRect +internal readonly struct TreeWidgetHighlightRect { - internal Vector2 min; - internal Vector2 max; + internal Vector2 min { get; init; } + internal Vector2 max { get; init; } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs index 5f4b1283a..00dc2e7d0 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetLineSegment.cs @@ -2,8 +2,8 @@ namespace Inno.Editor.ImGui.ImGuiWidget; -internal struct TreeWidgetLineSegment +internal readonly struct TreeWidgetLineSegment { - internal Vector2 from; - internal Vector2 to; + internal Vector2 from { get; init; } + internal Vector2 to { get; init; } } diff --git a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs index 53a36b009..b279ba3fc 100644 --- a/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs +++ b/src/composition/editor/presentation/Inno.Editor.ImGui/Widgets/TreeWidgetNodeState.cs @@ -2,10 +2,10 @@ namespace Inno.Editor.ImGui.ImGuiWidget; -internal struct TreeWidgetNodeState +internal readonly struct TreeWidgetNodeState { - internal string id; - internal Vector2 cursor; - internal float rowMaxY; - internal bool hasNextSibling; + internal string id { get; init; } + internal Vector2 cursor { get; init; } + internal float rowMaxY { get; init; } + internal bool hasNextSibling { get; init; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs index dcf21b6be..2b959e79e 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Changes.cs @@ -194,7 +194,7 @@ private void InvokeObservers(Action? handlers) { ((Action)handler)(); } - catch + catch (Exception) { // Observer failures cannot roll back committed manager state. } @@ -215,7 +215,7 @@ T value { ((Action)handler)(value); } - catch + catch (Exception) { // Observer failures cannot roll back committed manager state. } diff --git a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs index 11327750c..c8857d185 100644 --- a/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs +++ b/src/content/assets/Inno.Assets.Pipeline/AssetPipeline.Mutations.cs @@ -421,7 +421,7 @@ bool isDirectory MovePhysicalSource(targetPath, sourcePath, isDirectory); } } - catch + catch (Exception) { // The following catalog rescan reports any remaining physical conflict. } @@ -438,7 +438,7 @@ string targetPath File.Move(targetPath, sourcePath); } } - catch + catch (Exception) { // The following catalog rescan reports any remaining metadata conflict. } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs index eb822e849..8cc57cee6 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.SourceIO.cs @@ -250,8 +250,9 @@ out AssetSourceMeta sourceMeta sourceMeta = m_serialization.Deserialize(bytes); return sourceMeta.persistentId != Guid.Empty; } - catch + catch (Exception) { + // Metadata that cannot be deserialized is reported as unreadable. return false; } } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs index 5fd7e3d9c..1bf825c15 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/AssetLoader.cs @@ -381,7 +381,7 @@ private void PublishReloaded(AssetObject asset) { ((Action)handler)(asset); } - catch + catch (Exception) { // Observer failures cannot roll back an already committed asset transaction. } diff --git a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs index 0d6b8a65a..8769e0023 100644 --- a/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs +++ b/src/content/assets/Inno.Assets.Pipeline/Importing/Catalog/AssetCatalogStore.cs @@ -58,8 +58,9 @@ internal AssetMeta[] Load() } return DeserializeEntries(snapshot.entries); } - catch + catch (Exception) { + // An unreadable catalog is treated as empty. return []; } } diff --git a/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs b/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs index 53d452a44..bb9496710 100644 --- a/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs +++ b/src/foundation/core/Inno.Core.Execution/LifetimeScope.cs @@ -322,7 +322,7 @@ public async ValueTask DisposeAsync() { await Task.WhenAll(pending).ConfigureAwait(false); } - catch + catch (Exception) { // Dispose observes every fault after all work has completed. } diff --git a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs index e33f8e22d..8c1d7d2ef 100644 --- a/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs +++ b/src/foundation/extensibility/Inno.Extensibility.Types/TypeRegistry.cs @@ -578,8 +578,9 @@ Exception exception { OnCleanupFailed(phase, exception); } - catch + catch (Exception) { + // The cleanup failure is already reported to the type catalog. A failing observer must not hide it. } } diff --git a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs index cd3a38c6d..c963d963a 100644 --- a/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs +++ b/tests/build/Inno.Build.Integration.Tests/TaskHostPublicationProcess.cs @@ -164,7 +164,10 @@ internal static async Task StartAsync(string root) { await running; } - catch (Exception) { } + catch (Exception) + { + // The original failure is rethrown below. The failure of the canceled run is not needed. + } budget.Dispose(); throw; } diff --git a/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs b/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs index 870313cdc..68ec9bbcf 100644 --- a/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs +++ b/tests/build/Inno.Build.Toolchains.Tests/ToolchainProcessTests.cs @@ -215,7 +215,7 @@ sleep 120 & { await running.WaitAsync(TimeSpan.FromSeconds(10)); } - catch + catch (Exception) { // Observe the failure after requesting cleanup, including a timed-out assertion. } diff --git a/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs b/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs index c14706abd..747a3435d 100644 --- a/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs +++ b/tests/extensibility/Inno.Extensibility.Types.Tests/StableAnnotatedTypeB.cs @@ -1,4 +1,4 @@ namespace Inno.Extensibility.Types.Tests; [StableTypeID("22222222-2222-2222-2222-222222222222")] -public struct StableAnnotatedTypeB; +public readonly struct StableAnnotatedTypeB; diff --git a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs index 39512383a..b1c6b7ad7 100644 --- a/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs +++ b/tests/tooling/fixtures/Inno.Testing.Validation/ValidationRepository.cs @@ -2,6 +2,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -127,14 +128,19 @@ public string Git(params string[] arguments) start.ArgumentList.Add(argument); } using Process process = Process.Start(start)!; - Task output = process.StandardOutput.ReadToEndAsync(); - Task error = process.StandardError.ReadToEndAsync(); + var error = new StringBuilder(); + process.ErrorDataReceived += ( + _, + data + ) => error.AppendLine(data.Data); + process.BeginErrorReadLine(); + string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) { - throw new InvalidOperationException(output.Result + error.Result); + throw new InvalidOperationException(output + error); } - return output.Result.Trim(); + return output.Trim(); } public async Task PlanAsync( From d7e238d4e3d5312123d2826c9c4df1080947415e Mon Sep 17 00:00:00 2001 From: Hsuan-Kai Liao Date: Sun, 22 Nov 2026 04:10:11 +0000 Subject: [PATCH 33/33] feat(tooling): check the cancellation token position Rule P-03 now reports a `CancellationToken` parameter that is not last. A required token that precedes optional or `params` parameters is not reported. --- .../decisions/CSHARP_STYLE_RULEBOOK.md | 2 +- .../StyleCommandTests.cs | 16 ++++++ .../Rules/CancellationParameterStyleRule.cs | 57 +++++++++++++++---- 3 files changed, 63 insertions(+), 12 deletions(-) diff --git a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md index 8c9754c98..cf6b679c2 100644 --- a/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md +++ b/.agents/records/decisions/CSHARP_STYLE_RULEBOOK.md @@ -75,7 +75,7 @@ These checks read syntax only and report the part of a rule that syntax decides: | --- | --- | --- | | F-02 | A file that declares no type named like it, a primary type that is not first, and a second top-level type other than an enum, a delegate or a positional record. `Type.Part.cs` is named after `Type`. | Whether the companion is used only by the primary type. | | M-02 | A block body that is one `return`, call, assignment or `throw`; a constructor with an expression body. | A body that holds a comment or a directive. | -| P-03 | A `CancellationToken` parameter of a declaration that is not named `cancellationToken`. | Its position in the list, and lambda parameters. | +| P-03 | A `CancellationToken` parameter of a declaration that is not named `cancellationToken` or is not the last parameter. | A required token that precedes optional or `params` parameters, and lambda parameters. | | W-04 | A line break directly before or after `=`; the fix joins the lines. | | | I-02 | A declaration typed as an array or `List` (or a `var` local) whose value is `new[] {}`, `new T[] {}`, `Array.Empty()` or a `List` creation without constructor arguments. | A creation without a target type: a call receiver, an inferred generic argument, an anonymous-type member. | | E-05 | A hand-written `if` that throws `ArgumentNullException` for the tested name, and `?? throw new ArgumentNullException(nameof(x))` on a parameter in a statement of a block body. | Expression bodies and initializers, range checks, custom messages. | diff --git a/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs index 83d4c3713..ac7293ba8 100644 --- a/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs +++ b/tests/tooling/Inno.Tooling.Architecture.Tests/StyleCommandTests.cs @@ -123,6 +123,11 @@ string text "internal sealed class Probe\n{\n internal object Run(object value)\n {\n return value ?? throw new ArgumentNullException(nameof(value));\n }\n}" )] [InlineData("P-03", "internal sealed class Probe\n{\n internal void Run(CancellationToken token) {}\n}")] + [InlineData("P-03", "internal sealed class Probe\n{\n internal void Run(CancellationToken cancellationToken, int count) {}\n}")] + [InlineData( + "P-03", + "internal sealed class Probe\n{\n internal void Run(CancellationToken cancellationToken = default, int count = 0) {}\n}" + )] [InlineData("D-06", "internal sealed class Probe\n{\n #region State\n internal int count => 0;\n #endregion\n}")] [InlineData("D-06", "#nullable disable\ninternal sealed class Probe;")] [InlineData("D-06", "internal sealed class Probe\n{\n /* The count. */\n internal int count => 0;\n}")] @@ -2160,6 +2165,17 @@ internal Task RunAsync(CancellationToken cancellationToken) Func step = token => Task.Delay(1, token); return step(cancellationToken); } + + internal Task WaitAsync( + int count, + CancellationToken cancellationToken, + string? label = null + ) => Task.Delay(count, cancellationToken); + + internal Task WaitAllAsync( + CancellationToken cancellationToken, + params int[] counts + ) => Task.Delay(counts.Length, cancellationToken); } """ ) diff --git a/tools/Inno.Tooling.Architecture/Style/Rules/CancellationParameterStyleRule.cs b/tools/Inno.Tooling.Architecture/Style/Rules/CancellationParameterStyleRule.cs index a784cbc9a..ed9246315 100644 --- a/tools/Inno.Tooling.Architecture/Style/Rules/CancellationParameterStyleRule.cs +++ b/tools/Inno.Tooling.Architecture/Style/Rules/CancellationParameterStyleRule.cs @@ -1,12 +1,14 @@ using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Inno.Tooling.Architecture; -// P-03: a `CancellationToken` parameter of a declaration is named `cancellationToken`. +// P-03: a `CancellationToken` parameter of a declaration is named `cancellationToken` and is the last parameter. // A lambda parameter is not reported: it may have to differ from a token of the enclosing member. +// A required token that precedes optional or `params` parameters is not reported: it cannot move without a default. internal sealed class CancellationParameterStyleRule : StyleRule { private const string C_ID = "P-03"; @@ -22,16 +24,49 @@ ICollection findings ) { foreach (ParameterSyntax parameter in source.root.DescendantNodes().OfType()) { - if (parameter.Type is not IdentifierNameSyntax { Identifier.ValueText: "CancellationToken" }) continue; - if (parameter.Parent is not ParameterListSyntax { Parent: not AnonymousFunctionExpressionSyntax }) continue; - if (parameter.Identifier.ValueText == C_NAME) continue; - findings.Add( - source.Finding( - C_ID, - parameter.Identifier.SpanStart, - $"Name the parameter `{C_NAME}`. Found `{parameter.Identifier.ValueText}`." - ) - ); + if (!IsCancellationToken(parameter)) continue; + if (parameter.Parent is not ParameterListSyntax { Parent: not AnonymousFunctionExpressionSyntax } list) + { + continue; + } + if (parameter.Identifier.ValueText != C_NAME) + { + findings.Add( + source.Finding( + C_ID, + parameter.Identifier.SpanStart, + $"Name the parameter `{C_NAME}`. Found `{parameter.Identifier.ValueText}`." + ) + ); + } + + if (MustMoveLast(parameter, list)) + { + findings.Add( + source.Finding( + C_ID, + parameter.SpanStart, + $"Make `{parameter.Identifier.ValueText}` the last parameter." + ) + ); + } } } + + private static bool MustMoveLast( + ParameterSyntax parameter, + ParameterListSyntax list + ) { + int index = list.Parameters.IndexOf(parameter); + if (index == list.Parameters.Count - 1) return false; + + List later = list.Parameters.Skip(index + 1).ToList(); + if (later.Any(IsCancellationToken)) return false; + + return parameter.Default is not null + || !later.Any(other => other.Default is not null || other.Modifiers.Any(SyntaxKind.ParamsKeyword)); + } + + private static bool IsCancellationToken(ParameterSyntax parameter) + => parameter.Type is IdentifierNameSyntax { Identifier.ValueText: "CancellationToken" }; }